text
stringlengths
54
60.6k
<commit_before>#include "config.h" #include <iostream> #include <string> #include <pybind11/pybind11.h> #include <autocxxpy/autocxxpy.hpp> #include "module.hpp" #include "wrappers.hpp" #include "generated_functions.h" #include "xtp_trader_api.h" #include "xtp_quote_api.h" void generate_caster_(pybind11::object & parent) { struct caster: autocxxpy::caster{}; auto c = autocxxpy::caster::bind<caster>(parent, "caster"); autocxxpy::caster::try_generate<XTPRspInfoStruct>(c, "toXTPRspInfoStruct)"); autocxxpy::caster::try_generate<XTPSpecificTickerStruct>(c, "toXTPSpecificTickerStruct)"); autocxxpy::caster::try_generate<XTPMarketDataStockExData>(c, "toXTPMarketDataStockExData)"); autocxxpy::caster::try_generate<XTPMarketDataOptionExData>(c, "toXTPMarketDataOptionExData)"); autocxxpy::caster::try_generate<XTPMarketDataStruct>(c, "toXTPMarketDataStruct)"); autocxxpy::caster::try_generate<XTPQuoteStaticInfo>(c, "toXTPQuoteStaticInfo)"); autocxxpy::caster::try_generate<OrderBookStruct>(c, "toOrderBookStruct)"); autocxxpy::caster::try_generate<XTPTickByTickEntrust>(c, "toXTPTickByTickEntrust)"); autocxxpy::caster::try_generate<XTPTickByTickTrade>(c, "toXTPTickByTickTrade)"); autocxxpy::caster::try_generate<XTPTickByTickStruct>(c, "toXTPTickByTickStruct)"); autocxxpy::caster::try_generate<XTPTickerPriceInfo>(c, "toXTPTickerPriceInfo)"); autocxxpy::caster::try_generate<XTPOrderInsertInfo>(c, "toXTPOrderInsertInfo)"); autocxxpy::caster::try_generate<XTPOrderCancelInfo>(c, "toXTPOrderCancelInfo)"); autocxxpy::caster::try_generate<XTPOrderInfo>(c, "toXTPOrderInfo)"); autocxxpy::caster::try_generate<XTPTradeReport>(c, "toXTPTradeReport)"); autocxxpy::caster::try_generate<XTPQueryOrderReq>(c, "toXTPQueryOrderReq)"); autocxxpy::caster::try_generate<XTPQueryReportByExecIdReq>(c, "toXTPQueryReportByExecIdReq)"); autocxxpy::caster::try_generate<XTPQueryTraderReq>(c, "toXTPQueryTraderReq)"); autocxxpy::caster::try_generate<XTPQueryAssetRsp>(c, "toXTPQueryAssetRsp)"); autocxxpy::caster::try_generate<XTPQueryStkPositionRsp>(c, "toXTPQueryStkPositionRsp)"); autocxxpy::caster::try_generate<XTPFundTransferNotice>(c, "toXTPFundTransferNotice)"); autocxxpy::caster::try_generate<XTPQueryFundTransferLogReq>(c, "toXTPQueryFundTransferLogReq)"); autocxxpy::caster::try_generate<XTPQueryStructuredFundInfoReq>(c, "toXTPQueryStructuredFundInfoReq)"); autocxxpy::caster::try_generate<XTPStructuredFundInfo>(c, "toXTPStructuredFundInfo)"); autocxxpy::caster::try_generate<XTPQueryETFBaseReq>(c, "toXTPQueryETFBaseReq)"); autocxxpy::caster::try_generate<XTPQueryETFBaseRsp>(c, "toXTPQueryETFBaseRsp)"); autocxxpy::caster::try_generate<XTPQueryETFComponentReq>(c, "toXTPQueryETFComponentReq)"); autocxxpy::caster::try_generate<XTPQueryETFComponentRsp>(c, "toXTPQueryETFComponentRsp)"); autocxxpy::caster::try_generate<XTPQueryIPOTickerRsp>(c, "toXTPQueryIPOTickerRsp)"); autocxxpy::caster::try_generate<XTPQueryIPOQuotaRsp>(c, "toXTPQueryIPOQuotaRsp)"); autocxxpy::caster::try_generate<XTPQueryOptionAuctionInfoReq>(c, "toXTPQueryOptionAuctionInfoReq)"); autocxxpy::caster::try_generate<XTPQueryOptionAuctionInfoRsp>(c, "toXTPQueryOptionAuctionInfoRsp)"); autocxxpy::caster::try_generate<XTPCrdCashRepayRsp>(c, "toXTPCrdCashRepayRsp)"); autocxxpy::caster::try_generate<XTPCrdCashRepayDebtInterestFeeRsp>(c, "toXTPCrdCashRepayDebtInterestFeeRsp)"); autocxxpy::caster::try_generate<XTPCrdCashRepayInfo>(c, "toXTPCrdCashRepayInfo)"); autocxxpy::caster::try_generate<XTPCrdDebtInfo>(c, "toXTPCrdDebtInfo)"); autocxxpy::caster::try_generate<XTPCrdFundInfo>(c, "toXTPCrdFundInfo)"); autocxxpy::caster::try_generate<XTPClientQueryCrdDebtStockReq>(c, "toXTPClientQueryCrdDebtStockReq)"); autocxxpy::caster::try_generate<XTPCrdDebtStockInfo>(c, "toXTPCrdDebtStockInfo)"); autocxxpy::caster::try_generate<XTPClientQueryCrdPositionStockReq>(c, "toXTPClientQueryCrdPositionStockReq)"); autocxxpy::caster::try_generate<XTPClientQueryCrdPositionStkInfo>(c, "toXTPClientQueryCrdPositionStkInfo)"); autocxxpy::caster::try_generate<XTPClientQueryCrdSurplusStkReqInfo>(c, "toXTPClientQueryCrdSurplusStkReqInfo)"); autocxxpy::caster::try_generate<XTPClientQueryCrdSurplusStkRspInfo>(c, "toXTPClientQueryCrdSurplusStkRspInfo)"); autocxxpy::caster::try_generate<XTPClientCrdExtendDebtInfo>(c, "toXTPClientCrdExtendDebtInfo)"); autocxxpy::caster::try_generate<XTPFundTransferReq>(c, "toXTPFundTransferReq)"); autocxxpy::caster::try_generate<XTPVersionType>(c, "toXTPVersionType)"); autocxxpy::caster::try_generate<XTP_LOG_LEVEL>(c, "toXTP_LOG_LEVEL)"); autocxxpy::caster::try_generate<XTP_PROTOCOL_TYPE>(c, "toXTP_PROTOCOL_TYPE)"); autocxxpy::caster::try_generate<XTP_EXCHANGE_TYPE>(c, "toXTP_EXCHANGE_TYPE)"); autocxxpy::caster::try_generate<XTP_MARKET_TYPE>(c, "toXTP_MARKET_TYPE)"); autocxxpy::caster::try_generate<XTP_PRICE_TYPE>(c, "toXTP_PRICE_TYPE)"); autocxxpy::caster::try_generate<XTP_SIDE_TYPE>(c, "toXTP_SIDE_TYPE)"); autocxxpy::caster::try_generate<XTP_POSITION_EFFECT_TYPE>(c, "toXTP_POSITION_EFFECT_TYPE)"); autocxxpy::caster::try_generate<XTP_ORDER_ACTION_STATUS_TYPE>(c, "toXTP_ORDER_ACTION_STATUS_TYPE)"); autocxxpy::caster::try_generate<XTP_ORDER_STATUS_TYPE>(c, "toXTP_ORDER_STATUS_TYPE)"); autocxxpy::caster::try_generate<XTP_ORDER_SUBMIT_STATUS_TYPE>(c, "toXTP_ORDER_SUBMIT_STATUS_TYPE)"); autocxxpy::caster::try_generate<XTP_TE_RESUME_TYPE>(c, "toXTP_TE_RESUME_TYPE)"); autocxxpy::caster::try_generate<ETF_REPLACE_TYPE>(c, "toETF_REPLACE_TYPE)"); autocxxpy::caster::try_generate<XTP_TICKER_TYPE>(c, "toXTP_TICKER_TYPE)"); autocxxpy::caster::try_generate<XTP_BUSINESS_TYPE>(c, "toXTP_BUSINESS_TYPE)"); autocxxpy::caster::try_generate<XTP_ACCOUNT_TYPE>(c, "toXTP_ACCOUNT_TYPE)"); autocxxpy::caster::try_generate<XTP_FUND_TRANSFER_TYPE>(c, "toXTP_FUND_TRANSFER_TYPE)"); autocxxpy::caster::try_generate<XTP_FUND_OPER_STATUS>(c, "toXTP_FUND_OPER_STATUS)"); autocxxpy::caster::try_generate<XTP_SPLIT_MERGE_STATUS>(c, "toXTP_SPLIT_MERGE_STATUS)"); autocxxpy::caster::try_generate<XTP_TBT_TYPE>(c, "toXTP_TBT_TYPE)"); autocxxpy::caster::try_generate<XTP_OPT_CALL_OR_PUT_TYPE>(c, "toXTP_OPT_CALL_OR_PUT_TYPE)"); autocxxpy::caster::try_generate<XTP_OPT_EXERCISE_TYPE_TYPE>(c, "toXTP_OPT_EXERCISE_TYPE_TYPE)"); autocxxpy::caster::try_generate<XTP_POSITION_DIRECTION_TYPE>(c, "toXTP_POSITION_DIRECTION_TYPE)"); autocxxpy::caster::try_generate<XTP_CRD_CR_STATUS>(c, "toXTP_CRD_CR_STATUS)"); autocxxpy::caster::try_generate<TXTPTradeTypeType>(c, "toTXTPTradeTypeType)"); autocxxpy::caster::try_generate<TXTPOrderTypeType>(c, "toTXTPOrderTypeType)"); autocxxpy::caster::try_generate<XTPRI>(c, "toXTPRI)"); autocxxpy::caster::try_generate<XTPST>(c, "toXTPST)"); autocxxpy::caster::try_generate<XTPMD>(c, "toXTPMD)"); autocxxpy::caster::try_generate<XTPQSI>(c, "toXTPQSI)"); autocxxpy::caster::try_generate<XTPOB>(c, "toXTPOB)"); autocxxpy::caster::try_generate<XTPTBT>(c, "toXTPTBT)"); autocxxpy::caster::try_generate<XTPTPI>(c, "toXTPTPI)"); autocxxpy::caster::try_generate<XTPQueryOrderRsp>(c, "toXTPQueryOrderRsp)"); autocxxpy::caster::try_generate<XTPQueryTradeRsp>(c, "toXTPQueryTradeRsp)"); autocxxpy::caster::try_generate<XTPFundTransferLog>(c, "toXTPFundTransferLog)"); autocxxpy::caster::try_generate<XTPQueryETFBaseRsp>(c, "toXTPQueryETFBaseRsp)"); autocxxpy::caster::try_generate<XTPQueryETFComponentReq>(c, "toXTPQueryETFComponentReq)"); autocxxpy::caster::try_generate<XTPCrdDebtInfo>(c, "toXTPCrdDebtInfo)"); autocxxpy::caster::try_generate<XTPCrdFundInfo>(c, "toXTPCrdFundInfo)"); autocxxpy::caster::try_generate<XTPClientQueryCrdDebtStockReq>(c, "toXTPClientQueryCrdDebtStockReq)"); autocxxpy::caster::try_generate<XTPCrdDebtStockInfo>(c, "toXTPCrdDebtStockInfo)"); autocxxpy::caster::try_generate<XTPClientQueryCrdPositionStockReq>(c, "toXTPClientQueryCrdPositionStockReq)"); autocxxpy::caster::try_generate<XTPClientQueryCrdPositionStkInfo>(c, "toXTPClientQueryCrdPositionStkInfo)"); autocxxpy::caster::try_generate<XTPClientQueryCrdSurplusStkReqInfo>(c, "toXTPClientQueryCrdSurplusStkReqInfo)"); autocxxpy::caster::try_generate<XTPClientQueryCrdSurplusStkRspInfo>(c, "toXTPClientQueryCrdSurplusStkRspInfo)"); autocxxpy::caster::try_generate<XTPClientCrdExtendDebtInfo>(c, "toXTPClientCrdExtendDebtInfo)"); autocxxpy::caster::try_generate<XTPFundTransferAck>(c, "toXTPFundTransferAck)"); } <commit_msg>Delete generated_functions_3.cpp<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "../config/config.hpp" #ifdef MFEM_USE_MPI #ifdef MFEM_USE_PETSC #ifdef MFEM_USE_SLEPC #include "linalg.hpp" #include "slepc.h" #include "petscinternals.hpp" static PetscErrorCode ierr; namespace mfem { void MFEMInitializeSlepc() { MFEMInitializeSlepc(NULL,NULL,NULL,NULL); } void MFEMInitializeSlepc(int *argc,char*** argv) { MFEMInitializeSlepc(argc,argv,NULL,NULL); } void MFEMInitializeSlepc(int *argc,char ***argv,const char rc_file[], const char help[]) { ierr = SlepcInitialize(argc,argv,rc_file,help); MFEM_VERIFY(!ierr,"Unable to initialize SLEPc"); } void MFEMFinalizeSlepc() { ierr = SlepcFinalize(); MFEM_VERIFY(!ierr,"Unable to finalize SLEPc"); } SlepcEigenSolver::SlepcEigenSolver(MPI_Comm comm, const std::string &prefix) { clcustom = false; VR = NULL; VC = NULL; ierr = EPSCreate(comm,&eps); CCHKERRQ(comm,ierr); ierr = EPSSetOptionsPrefix(eps, prefix.c_str()); PCHKERRQ(eps, ierr); } SlepcEigenSolver::~SlepcEigenSolver() { delete VR; delete VC; MPI_Comm comm; ierr = PetscObjectGetComm((PetscObject)eps,&comm); PCHKERRQ(eps,ierr); ierr = EPSDestroy(&eps); CCHKERRQ(comm,ierr); } void SlepcEigenSolver::SetOperator(const PetscParMatrix &op) { delete VR; delete VC; VR = VC = NULL; ierr = EPSSetOperators(eps,op,NULL); PCHKERRQ(eps, ierr); VR = new PetscParVector(op, true, false); VC = new PetscParVector(op, true, false); } void SlepcEigenSolver::SetOperators(const PetscParMatrix &op, const PetscParMatrix&opB) { delete VR; delete VC; VR = VC = NULL; ierr = EPSSetOperators(eps,op,opB); PCHKERRQ(eps,ierr); VR = new PetscParVector(op, true, false); VC = new PetscParVector(op, true, false); } void SlepcEigenSolver::SetTol(double tol) { PetscInt max_its; ierr = EPSGetTolerances(eps,NULL,&max_its); PCHKERRQ(eps,ierr); // Work around uninitialized maximum iterations if (max_its==0) { max_its = PETSC_DECIDE; } ierr = EPSSetTolerances(eps,tol,max_its); PCHKERRQ(eps,ierr); } void SlepcEigenSolver::SetMaxIter(int max_its) { double tol; ierr = EPSGetTolerances(eps,&tol,NULL); PCHKERRQ(eps,ierr); ierr = EPSSetTolerances(eps,tol,max_its); PCHKERRQ(eps,ierr); } void SlepcEigenSolver::SetNumModes(int num_eigs) { ierr = EPSSetDimensions(eps,num_eigs,PETSC_DECIDE,PETSC_DECIDE); PCHKERRQ(eps,ierr); } void SlepcEigenSolver::Solve() { Customize(); ierr = EPSSolve(eps); PCHKERRQ(eps,ierr); } void SlepcEigenSolver::Customize(bool customize) const { if (!customize) {clcustom = true; } if (!clcustom) { ierr = EPSSetFromOptions(eps); PCHKERRQ(eps,ierr); } clcustom = true; } void SlepcEigenSolver::GetEigenvalue(unsigned int i, double & lr) const { ierr = EPSGetEigenvalue(eps,i,&lr,NULL); PCHKERRQ(eps,ierr); } void SlepcEigenSolver::GetEigenvalue(unsigned int i, double & lr, double & lc) const { ierr = EPSGetEigenvalue(eps,i,&lr,&lc); PCHKERRQ(eps,ierr); } void SlepcEigenSolver::GetEigenvector(unsigned int i, Vector & vr) const { MFEM_VERIFY(VR,"Missing real vector"); MFEM_ASSERT(vr.Size() == VR->Size(), "invalid vr.Size() = " << vr.Size() << ", expected size = " << VR->Size()); VR->PlaceArray(vr.GetData()); ierr = EPSGetEigenvector(eps,i,*VR,NULL); PCHKERRQ(eps,ierr); VR->ResetArray(); } void SlepcEigenSolver::GetEigenvector(unsigned int i, Vector & vr, Vector & vc) const { MFEM_VERIFY(VR,"Missing real vector"); MFEM_VERIFY(VC,"Missing imaginary vector"); MFEM_ASSERT(vr.Size() == VR->Size(), "invalid vr.Size() = " << vr.Size() << ", expected size = " << VR->Size()); MFEM_ASSERT(vc.Size() == VC->Size(), "invalid vc.Size() = " << vc.Size() << ", expected size = " << VC->Size()); VR->PlaceArray(vr.GetData()); VC->PlaceArray(vc.GetData()); ierr = EPSGetEigenvector(eps,i,*VR,*VC); PCHKERRQ(eps,ierr); VR->ResetArray(); VC->ResetArray(); } int SlepcEigenSolver::GetNumConverged() { PetscInt num_conv; ierr = EPSGetConverged(eps,&num_conv); PCHKERRQ(eps,ierr); return num_conv; } void SlepcEigenSolver::SetWhichEigenpairs(SlepcEigenSolver::Which which) { switch (which) { case SlepcEigenSolver::LARGEST_MAGNITUDE: ierr = EPSSetWhichEigenpairs(eps,EPS_LARGEST_MAGNITUDE); PCHKERRQ(eps,ierr); break; case SlepcEigenSolver::SMALLEST_MAGNITUDE: ierr = EPSSetWhichEigenpairs(eps,EPS_SMALLEST_MAGNITUDE); PCHKERRQ(eps,ierr); break; case SlepcEigenSolver::LARGEST_REAL: ierr = EPSSetWhichEigenpairs(eps,EPS_LARGEST_REAL); PCHKERRQ(eps,ierr); break; case SlepcEigenSolver::SMALLEST_REAL: ierr = EPSSetWhichEigenpairs(eps,EPS_SMALLEST_REAL); PCHKERRQ(eps,ierr); break; case SlepcEigenSolver::LARGEST_IMAGINARY: ierr = EPSSetWhichEigenpairs(eps,EPS_LARGEST_IMAGINARY); PCHKERRQ(eps,ierr); break; case SlepcEigenSolver::SMALLEST_IMAGINARY: ierr = EPSSetWhichEigenpairs(eps,EPS_SMALLEST_IMAGINARY); PCHKERRQ(eps,ierr); break; case SlepcEigenSolver::TARGET_MAGNITUDE: ierr = EPSSetWhichEigenpairs(eps,EPS_TARGET_MAGNITUDE); PCHKERRQ(eps,ierr); break; case SlepcEigenSolver::TARGET_REAL: ierr = EPSSetWhichEigenpairs(eps,EPS_TARGET_REAL); PCHKERRQ(eps,ierr); break; default: MFEM_ABORT("Which eigenpair not implemented!"); break; } } void SlepcEigenSolver::SetTarget(double target) { ierr = EPSSetTarget(eps,target); PCHKERRQ(eps,ierr); } void SlepcEigenSolver::SetSpectralTransformation( SlepcEigenSolver::SpectralTransformation transformation) { ST st; ierr = EPSGetST(eps,&st); PCHKERRQ(eps,ierr); switch (transformation) { case SlepcEigenSolver::SHIFT: ierr = STSetType(st,STSHIFT); PCHKERRQ(eps,ierr); break; case SlepcEigenSolver::SHIFT_INVERT: ierr = STSetType(st,STSINVERT); PCHKERRQ(eps,ierr); break; default: MFEM_ABORT("Spectral transformation not implemented!"); break; } } } #endif // MFEM_USE_SLEPC #endif // MFEM_USE_PETSC #endif // MFEM_USE_MPI <commit_msg>make casting clear with PetscInt<commit_after>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "../config/config.hpp" #ifdef MFEM_USE_MPI #ifdef MFEM_USE_PETSC #ifdef MFEM_USE_SLEPC #include "linalg.hpp" #include "slepc.h" #include "petscinternals.hpp" static PetscErrorCode ierr; namespace mfem { void MFEMInitializeSlepc() { MFEMInitializeSlepc(NULL,NULL,NULL,NULL); } void MFEMInitializeSlepc(int *argc,char*** argv) { MFEMInitializeSlepc(argc,argv,NULL,NULL); } void MFEMInitializeSlepc(int *argc,char ***argv,const char rc_file[], const char help[]) { ierr = SlepcInitialize(argc,argv,rc_file,help); MFEM_VERIFY(!ierr,"Unable to initialize SLEPc"); } void MFEMFinalizeSlepc() { ierr = SlepcFinalize(); MFEM_VERIFY(!ierr,"Unable to finalize SLEPc"); } SlepcEigenSolver::SlepcEigenSolver(MPI_Comm comm, const std::string &prefix) { clcustom = false; VR = NULL; VC = NULL; ierr = EPSCreate(comm,&eps); CCHKERRQ(comm,ierr); ierr = EPSSetOptionsPrefix(eps, prefix.c_str()); PCHKERRQ(eps, ierr); } SlepcEigenSolver::~SlepcEigenSolver() { delete VR; delete VC; MPI_Comm comm; ierr = PetscObjectGetComm((PetscObject)eps,&comm); PCHKERRQ(eps,ierr); ierr = EPSDestroy(&eps); CCHKERRQ(comm,ierr); } void SlepcEigenSolver::SetOperator(const PetscParMatrix &op) { delete VR; delete VC; VR = VC = NULL; ierr = EPSSetOperators(eps,op,NULL); PCHKERRQ(eps, ierr); VR = new PetscParVector(op, true, false); VC = new PetscParVector(op, true, false); } void SlepcEigenSolver::SetOperators(const PetscParMatrix &op, const PetscParMatrix&opB) { delete VR; delete VC; VR = VC = NULL; ierr = EPSSetOperators(eps,op,opB); PCHKERRQ(eps,ierr); VR = new PetscParVector(op, true, false); VC = new PetscParVector(op, true, false); } void SlepcEigenSolver::SetTol(double tol) { PetscInt max_its; ierr = EPSGetTolerances(eps,NULL,&max_its); PCHKERRQ(eps,ierr); // Work around uninitialized maximum iterations if (max_its==0) { max_its = PETSC_DECIDE; } ierr = EPSSetTolerances(eps,tol,max_its); PCHKERRQ(eps,ierr); } void SlepcEigenSolver::SetMaxIter(int max_its) { double tol; ierr = EPSGetTolerances(eps,&tol,NULL); PCHKERRQ(eps,ierr); ierr = EPSSetTolerances(eps,tol,max_its); PCHKERRQ(eps,ierr); } void SlepcEigenSolver::SetNumModes(int num_eigs) { ierr = EPSSetDimensions(eps,num_eigs,PETSC_DECIDE,PETSC_DECIDE); PCHKERRQ(eps,ierr); } void SlepcEigenSolver::Solve() { Customize(); ierr = EPSSolve(eps); PCHKERRQ(eps,ierr); } void SlepcEigenSolver::Customize(bool customize) const { if (!customize) {clcustom = true; } if (!clcustom) { ierr = EPSSetFromOptions(eps); PCHKERRQ(eps,ierr); } clcustom = true; } void SlepcEigenSolver::GetEigenvalue(unsigned int i, double & lr) const { ierr = EPSGetEigenvalue(eps,i,&lr,NULL); PCHKERRQ(eps,ierr); } void SlepcEigenSolver::GetEigenvalue(unsigned int i, double & lr, double & lc) const { ierr = EPSGetEigenvalue(eps,i,&lr,&lc); PCHKERRQ(eps,ierr); } void SlepcEigenSolver::GetEigenvector(unsigned int i, Vector & vr) const { MFEM_VERIFY(VR,"Missing real vector"); MFEM_ASSERT(vr.Size() == VR->Size(), "invalid vr.Size() = " << vr.Size() << ", expected size = " << VR->Size()); VR->PlaceArray(vr.GetData()); ierr = EPSGetEigenvector(eps,i,*VR,NULL); PCHKERRQ(eps,ierr); VR->ResetArray(); } void SlepcEigenSolver::GetEigenvector(unsigned int i, Vector & vr, Vector & vc) const { MFEM_VERIFY(VR,"Missing real vector"); MFEM_VERIFY(VC,"Missing imaginary vector"); MFEM_ASSERT(vr.Size() == VR->Size(), "invalid vr.Size() = " << vr.Size() << ", expected size = " << VR->Size()); MFEM_ASSERT(vc.Size() == VC->Size(), "invalid vc.Size() = " << vc.Size() << ", expected size = " << VC->Size()); VR->PlaceArray(vr.GetData()); VC->PlaceArray(vc.GetData()); ierr = EPSGetEigenvector(eps,i,*VR,*VC); PCHKERRQ(eps,ierr); VR->ResetArray(); VC->ResetArray(); } int SlepcEigenSolver::GetNumConverged() { PetscInt num_conv; ierr = EPSGetConverged(eps,&num_conv); PCHKERRQ(eps,ierr); return static_cast<int>(num_conv); } void SlepcEigenSolver::SetWhichEigenpairs(SlepcEigenSolver::Which which) { switch (which) { case SlepcEigenSolver::LARGEST_MAGNITUDE: ierr = EPSSetWhichEigenpairs(eps,EPS_LARGEST_MAGNITUDE); PCHKERRQ(eps,ierr); break; case SlepcEigenSolver::SMALLEST_MAGNITUDE: ierr = EPSSetWhichEigenpairs(eps,EPS_SMALLEST_MAGNITUDE); PCHKERRQ(eps,ierr); break; case SlepcEigenSolver::LARGEST_REAL: ierr = EPSSetWhichEigenpairs(eps,EPS_LARGEST_REAL); PCHKERRQ(eps,ierr); break; case SlepcEigenSolver::SMALLEST_REAL: ierr = EPSSetWhichEigenpairs(eps,EPS_SMALLEST_REAL); PCHKERRQ(eps,ierr); break; case SlepcEigenSolver::LARGEST_IMAGINARY: ierr = EPSSetWhichEigenpairs(eps,EPS_LARGEST_IMAGINARY); PCHKERRQ(eps,ierr); break; case SlepcEigenSolver::SMALLEST_IMAGINARY: ierr = EPSSetWhichEigenpairs(eps,EPS_SMALLEST_IMAGINARY); PCHKERRQ(eps,ierr); break; case SlepcEigenSolver::TARGET_MAGNITUDE: ierr = EPSSetWhichEigenpairs(eps,EPS_TARGET_MAGNITUDE); PCHKERRQ(eps,ierr); break; case SlepcEigenSolver::TARGET_REAL: ierr = EPSSetWhichEigenpairs(eps,EPS_TARGET_REAL); PCHKERRQ(eps,ierr); break; default: MFEM_ABORT("Which eigenpair not implemented!"); break; } } void SlepcEigenSolver::SetTarget(double target) { ierr = EPSSetTarget(eps,target); PCHKERRQ(eps,ierr); } void SlepcEigenSolver::SetSpectralTransformation( SlepcEigenSolver::SpectralTransformation transformation) { ST st; ierr = EPSGetST(eps,&st); PCHKERRQ(eps,ierr); switch (transformation) { case SlepcEigenSolver::SHIFT: ierr = STSetType(st,STSHIFT); PCHKERRQ(eps,ierr); break; case SlepcEigenSolver::SHIFT_INVERT: ierr = STSetType(st,STSINVERT); PCHKERRQ(eps,ierr); break; default: MFEM_ABORT("Spectral transformation not implemented!"); break; } } } #endif // MFEM_USE_SLEPC #endif // MFEM_USE_PETSC #endif // MFEM_USE_MPI <|endoftext|>
<commit_before><commit_msg>Workaround for msvc-6.5: *_EQUAL macros give Internal Compiler Errors, when inlining is turned on.<commit_after><|endoftext|>
<commit_before><commit_msg>Eigenize calc_table_posterior<commit_after><|endoftext|>
<commit_before><commit_msg>Avoid deprecated `stream_from` ctor.<commit_after><|endoftext|>
<commit_before> #include <iostream> #include <fstream> #include <string> #include <vector> #include <boost/algorithm/string.hpp> #include <libdevcore/Common.h> #include <libdevcore/CommonIO.h> #include <libevmface/Instruction.h> #include "Compiler.h" #include "ExecutionEngine.h" using namespace dev; void show_usage() { // FIXME: Use arg[0] as program name? std::cerr << "usage: evmcc (-b|-c|-d)+ <inputfile.bc>\n"; } int main(int argc, char** argv) { std::string input_file; bool opt_dissassemble = false; bool opt_show_bytes = false; bool opt_compile = false; bool opt_interpret = false; bool opt_unknown = false; for (int i = 1; i < argc; i++) { std::string option = argv[i]; if (option == "-b") opt_show_bytes = true; else if (option == "-c") opt_compile = true; else if (option == "-d") opt_dissassemble = true; else if (option == "-i") opt_interpret = true; else if (option[0] != '-' && input_file.empty()) input_file = option; else { opt_unknown = true; break; } } if (opt_unknown || input_file.empty() || (!opt_show_bytes && !opt_compile && !opt_dissassemble && !opt_interpret)) { show_usage(); exit(1); } std::ifstream ifs(input_file); if (!ifs.is_open()) { std::cerr << "cannot open file " << input_file << std::endl; exit(1); } std::string src((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>())); boost::algorithm::trim(src); bytes bytecode = fromHex(src); if (opt_show_bytes) { std::cout << dev::memDump(bytecode) << std::endl; } if (opt_dissassemble) { std::string assembly = eth::disassemble(bytecode); std::cout << assembly << std::endl; } if (opt_compile) { evmcc::Compiler().compile(bytecode)->dump(); } if (opt_interpret) { auto engine = evmcc::ExecutionEngine(); auto module = evmcc::Compiler().compile(bytecode); module->dump(); auto result = engine.run(std::move(module)); return result; } return 0; } <commit_msg>Output compilation (option -c) result to standard output by default<commit_after> #include <iostream> #include <fstream> #include <string> #include <vector> #include <boost/algorithm/string.hpp> #include <llvm/Support/raw_os_ostream.h> #include <libdevcore/Common.h> #include <libdevcore/CommonIO.h> #include <libevmface/Instruction.h> #include "Compiler.h" #include "ExecutionEngine.h" using namespace dev; void show_usage() { // FIXME: Use arg[0] as program name? std::cerr << "usage: evmcc (-b|-c|-d)+ <inputfile.bc>\n"; } int main(int argc, char** argv) { std::string input_file; bool opt_dissassemble = false; bool opt_show_bytes = false; bool opt_compile = false; bool opt_interpret = false; bool opt_unknown = false; for (int i = 1; i < argc; i++) { std::string option = argv[i]; if (option == "-b") opt_show_bytes = true; else if (option == "-c") opt_compile = true; else if (option == "-d") opt_dissassemble = true; else if (option == "-i") opt_interpret = true; else if (option[0] != '-' && input_file.empty()) input_file = option; else { opt_unknown = true; break; } } if (opt_unknown || input_file.empty() || (!opt_show_bytes && !opt_compile && !opt_dissassemble && !opt_interpret)) { show_usage(); exit(1); } std::ifstream ifs(input_file); if (!ifs.is_open()) { std::cerr << "cannot open file " << input_file << std::endl; exit(1); } std::string src((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>())); boost::algorithm::trim(src); bytes bytecode = fromHex(src); if (opt_show_bytes) { std::cout << dev::memDump(bytecode) << std::endl; } if (opt_dissassemble) { std::string assembly = eth::disassemble(bytecode); std::cout << assembly << std::endl; } if (opt_compile) { auto module = evmcc::Compiler().compile(bytecode); llvm::raw_os_ostream out(std::cout); module->print(out, nullptr); } if (opt_interpret) { auto engine = evmcc::ExecutionEngine(); auto module = evmcc::Compiler().compile(bytecode); module->dump(); auto result = engine.run(std::move(module)); return result; } return 0; } <|endoftext|>
<commit_before>/* * Copyright Andrey Semashev 2007 - 2013. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ /*! * \file empty_deleter.hpp * \author Andrey Semashev * \date 22.04.2007 * * This header is deprecated, use boost/utility/empty_deleter.hpp instead. The header is left for * backward compatibility and will be removed in future versions. */ #ifndef BOOST_LOG_UTILITY_EMPTY_DELETER_HPP_INCLUDED_ #define BOOST_LOG_UTILITY_EMPTY_DELETER_HPP_INCLUDED_ #include <boost/utility/empty_deleter.hpp> #include <boost/log/detail/config.hpp> #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif #if defined(__GNUC__) #pragma message "Boost.Log: This header is deprecated, use boost/utility/empty_deleter.hpp instead." #elif defined(_MSC_VER) #pragma message("Boost.Log: This header is deprecated, use boost/utility/empty_deleter.hpp instead.") #endif namespace boost { BOOST_LOG_OPEN_NAMESPACE using boost::empty_deleter BOOST_LOG_CLOSE_NAMESPACE // namespace log } // namespace boost #endif // BOOST_LOG_UTILITY_EMPTY_DELETER_HPP_INCLUDED_ <commit_msg>Fixed compilation.<commit_after>/* * Copyright Andrey Semashev 2007 - 2013. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ /*! * \file empty_deleter.hpp * \author Andrey Semashev * \date 22.04.2007 * * This header is deprecated, use boost/utility/empty_deleter.hpp instead. The header is left for * backward compatibility and will be removed in future versions. */ #ifndef BOOST_LOG_UTILITY_EMPTY_DELETER_HPP_INCLUDED_ #define BOOST_LOG_UTILITY_EMPTY_DELETER_HPP_INCLUDED_ #include <boost/utility/empty_deleter.hpp> #include <boost/log/detail/config.hpp> #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif #if defined(__GNUC__) #pragma message "Boost.Log: This header is deprecated, use boost/utility/empty_deleter.hpp instead." #elif defined(_MSC_VER) #pragma message("Boost.Log: This header is deprecated, use boost/utility/empty_deleter.hpp instead.") #endif namespace boost { BOOST_LOG_OPEN_NAMESPACE using boost::empty_deleter; BOOST_LOG_CLOSE_NAMESPACE // namespace log } // namespace boost #endif // BOOST_LOG_UTILITY_EMPTY_DELETER_HPP_INCLUDED_ <|endoftext|>
<commit_before>// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __STOUT_DURATION_HPP__ #define __STOUT_DURATION_HPP__ #include <ctype.h> // For 'isdigit'. // For 'timeval'. #ifndef __WINDOWS__ #include <time.h> #endif // __WINDOWS__ #include <iomanip> #include <iostream> #include <limits> #include <string> #include "error.hpp" #include "numify.hpp" #include "try.hpp" class Duration { public: static Try<Duration> parse(const std::string& s) { // TODO(benh): Support negative durations (i.e., starts with '-'). size_t index = 0; while (index < s.size()) { if (isdigit(s[index]) || s[index] == '.') { index++; continue; } Try<double> value = numify<double>(s.substr(0, index)); if (value.isError()) { return Error(value.error()); } const std::string unit = s.substr(index); if (unit == "ns") { return Duration(value.get(), NANOSECONDS); } else if (unit == "us") { return Duration(value.get(), MICROSECONDS); } else if (unit == "ms") { return Duration(value.get(), MILLISECONDS); } else if (unit == "secs") { return Duration(value.get(), SECONDS); } else if (unit == "mins") { return Duration(value.get(), MINUTES); } else if (unit == "hrs") { return Duration(value.get(), HOURS); } else if (unit == "days") { return Duration(value.get(), DAYS); } else if (unit == "weeks") { return Duration(value.get(), WEEKS); } else { return Error("Unknown duration unit '" + unit + "'"); } } return Error("Invalid duration '" + s + "'"); } static Try<Duration> create(double seconds); constexpr Duration() : nanos(0) {} explicit Duration(const timeval& t) { nanos = t.tv_sec * SECONDS + t.tv_usec * MICROSECONDS; } int64_t ns() const { return nanos; } double us() const { return static_cast<double>(nanos) / MICROSECONDS; } double ms() const { return static_cast<double>(nanos) / MILLISECONDS; } double secs() const { return static_cast<double>(nanos) / SECONDS; } double mins() const { return static_cast<double>(nanos) / MINUTES; } double hrs() const { return static_cast<double>(nanos) / HOURS; } double days() const { return static_cast<double>(nanos) / DAYS; } double weeks() const { return static_cast<double>(nanos) / WEEKS; } struct timeval timeval() const { struct timeval t; t.tv_sec = secs(); t.tv_usec = us() - (t.tv_sec * MILLISECONDS); return t; } bool operator<(const Duration& d) const { return nanos < d.nanos; } bool operator<=(const Duration& d) const { return nanos <= d.nanos; } bool operator>(const Duration& d) const { return nanos > d.nanos; } bool operator>=(const Duration& d) const { return nanos >= d.nanos; } bool operator==(const Duration& d) const { return nanos == d.nanos; } bool operator!=(const Duration& d) const { return nanos != d.nanos; } Duration& operator+=(const Duration& that) { nanos += that.nanos; return *this; } Duration& operator-=(const Duration& that) { nanos -= that.nanos; return *this; } Duration& operator*=(double multiplier) { nanos = static_cast<int64_t>(nanos * multiplier); return *this; } Duration& operator/=(double divisor) { nanos = static_cast<int64_t>(nanos / divisor); return *this; } Duration operator+(const Duration& that) const { Duration sum = *this; sum += that; return sum; } Duration operator-(const Duration& that) const { Duration diff = *this; diff -= that; return diff; } Duration operator*(double multiplier) const { Duration product = *this; product *= multiplier; return product; } Duration operator/(double divisor) const { Duration quotient = *this; quotient /= divisor; return quotient; } // A constant holding the maximum value a Duration can have. static constexpr Duration max(); // A constant holding the minimum (negative) value a Duration can // have. static constexpr Duration min(); // A constant holding a Duration of a "zero" value. static constexpr Duration zero() { return Duration(); } protected: static const int64_t NANOSECONDS = 1; static const int64_t MICROSECONDS = 1000 * NANOSECONDS; static const int64_t MILLISECONDS = 1000 * MICROSECONDS; static const int64_t SECONDS = 1000 * MILLISECONDS; static const int64_t MINUTES = 60 * SECONDS; static const int64_t HOURS = 60 * MINUTES; static const int64_t DAYS = 24 * HOURS; static const int64_t WEEKS = 7 * DAYS; // For the Seconds, Minutes, Hours, Days & Weeks constructor. constexpr Duration(int32_t value, int64_t unit) : nanos(value * unit) {} // For the Nanoseconds, Microseconds, Milliseconds constructor. constexpr Duration(int64_t value, int64_t unit) : nanos(value * unit) {} private: // Used only by "parse". constexpr Duration(double value, int64_t unit) : nanos(static_cast<int64_t>(value * unit)) {} int64_t nanos; friend std::ostream& operator<<( std::ostream& stream, const Duration& duration); }; class Nanoseconds : public Duration { public: explicit constexpr Nanoseconds(int64_t nanoseconds) : Duration(nanoseconds, NANOSECONDS) {} constexpr Nanoseconds(const Duration& d) : Duration(d) {} double value() const { return static_cast<double>(this->ns()); } static std::string units() { return "ns"; } }; class Microseconds : public Duration { public: explicit constexpr Microseconds(int64_t microseconds) : Duration(microseconds, MICROSECONDS) {} constexpr Microseconds(const Duration& d) : Duration(d) {} double value() const { return this->us(); } static std::string units() { return "us"; } }; class Milliseconds : public Duration { public: explicit constexpr Milliseconds(int64_t milliseconds) : Duration(milliseconds, MILLISECONDS) {} constexpr Milliseconds(const Duration& d) : Duration(d) {} double value() const { return this->ms(); } static std::string units() { return "ms"; } }; class Seconds : public Duration { public: explicit constexpr Seconds(int64_t seconds) : Duration(seconds, SECONDS) {} constexpr Seconds(const Duration& d) : Duration(d) {} double value() const { return this->secs(); } static std::string units() { return "secs"; } }; class Minutes : public Duration { public: explicit constexpr Minutes(int32_t minutes) : Duration(minutes, MINUTES) {} constexpr Minutes(const Duration& d) : Duration(d) {} double value() const { return this->mins(); } static std::string units() { return "mins"; } }; class Hours : public Duration { public: explicit constexpr Hours(int32_t hours) : Duration(hours, HOURS) {} constexpr Hours(const Duration& d) : Duration(d) {} double value() const { return this->hrs(); } static std::string units() { return "hrs"; } }; class Days : public Duration { public: explicit Days(int32_t days) : Duration(days, DAYS) {} Days(const Duration& d) : Duration(d) {} double value() const { return this->days(); } static std::string units() { return "days"; } }; class Weeks : public Duration { public: explicit constexpr Weeks(int32_t value) : Duration(value, WEEKS) {} constexpr Weeks(const Duration& d) : Duration(d) {} double value() const { return this->weeks(); } static std::string units() { return "weeks"; } }; inline std::ostream& operator<<(std::ostream& stream, const Duration& duration_) { long precision = stream.precision(); // Output the duration in full double precision. stream.precision(std::numeric_limits<double>::digits10); // Parse the duration as the sign and the absolute value. Duration duration = duration_; if (duration_ < Duration::zero()) { stream << "-"; // Duration::min() may not be representable as a positive Duration. if (duration_ == Duration::min()) { duration = Duration::max(); } else { duration = duration_ * -1; } } // First determine which bucket of time unit the duration falls into // then check whether the duration can be represented as a whole // number with this time unit or a smaller one. // e.g. 1.42857142857143weeks falls into the 'Weeks' bucket but // reads better with a smaller unit: '10days'. So we use 'days' // instead of 'weeks' to output the duration. int64_t nanoseconds = duration.ns(); if (duration < Microseconds(1)) { stream << duration.ns() << Nanoseconds::units(); } else if (duration < Milliseconds(1)) { if (nanoseconds % Duration::MICROSECONDS != 0) { // We can't get a whole number using this unit but we can at // one level down. stream << duration.ns() << Nanoseconds::units(); } else { stream << duration.us() << Microseconds::units(); } } else if (duration < Seconds(1)) { if (nanoseconds % Duration::MILLISECONDS != 0 && nanoseconds % Duration::MICROSECONDS == 0) { stream << duration.us() << Microseconds::units(); } else { stream << duration.ms() << Milliseconds::units(); } } else if (duration < Minutes(1)) { if (nanoseconds % Duration::SECONDS != 0 && nanoseconds % Duration::MILLISECONDS == 0) { stream << duration.ms() << Milliseconds::units(); } else { stream << duration.secs() << Seconds::units(); } } else if (duration < Hours(1)) { if (nanoseconds % Duration::MINUTES != 0 && nanoseconds % Duration::SECONDS == 0) { stream << duration.secs() << Seconds::units(); } else { stream << duration.mins() << Minutes::units(); } } else if (duration < Days(1)) { if (nanoseconds % Duration::HOURS != 0 && nanoseconds % Duration::MINUTES == 0) { stream << duration.mins() << Minutes::units(); } else { stream << duration.hrs() << Hours::units(); } } else if (duration < Weeks(1)) { if (nanoseconds % Duration::DAYS != 0 && nanoseconds % Duration::HOURS == 0) { stream << duration.hrs() << Hours::units(); } else { stream << duration.days() << Days::units(); } } else { if (nanoseconds % Duration::WEEKS != 0 && nanoseconds % Duration::DAYS == 0) { stream << duration.days() << Days::units(); } else { stream << duration.weeks() << Weeks::units(); } } // Return the stream to original formatting state. stream.precision(precision); return stream; } inline Try<Duration> Duration::create(double seconds) { if (seconds * SECONDS > std::numeric_limits<int64_t>::max() || seconds * SECONDS < std::numeric_limits<int64_t>::min()) { return Error("Argument out of the range that a Duration can represent due " "to int64_t's size limit"); } return Nanoseconds(static_cast<int64_t>(seconds * SECONDS)); } inline constexpr Duration Duration::max() { return Nanoseconds(std::numeric_limits<int64_t>::max()); } inline constexpr Duration Duration::min() { return Nanoseconds(std::numeric_limits<int64_t>::min()); } #endif // __STOUT_DURATION_HPP__ <commit_msg>Removed constructors which use restricted integral width.<commit_after>// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __STOUT_DURATION_HPP__ #define __STOUT_DURATION_HPP__ #include <ctype.h> // For 'isdigit'. // For 'timeval'. #ifndef __WINDOWS__ #include <time.h> #endif // __WINDOWS__ #include <iomanip> #include <iostream> #include <limits> #include <string> #include "error.hpp" #include "numify.hpp" #include "try.hpp" class Duration { public: static Try<Duration> parse(const std::string& s) { // TODO(benh): Support negative durations (i.e., starts with '-'). size_t index = 0; while (index < s.size()) { if (isdigit(s[index]) || s[index] == '.') { index++; continue; } Try<double> value = numify<double>(s.substr(0, index)); if (value.isError()) { return Error(value.error()); } const std::string unit = s.substr(index); if (unit == "ns") { return Duration(value.get(), NANOSECONDS); } else if (unit == "us") { return Duration(value.get(), MICROSECONDS); } else if (unit == "ms") { return Duration(value.get(), MILLISECONDS); } else if (unit == "secs") { return Duration(value.get(), SECONDS); } else if (unit == "mins") { return Duration(value.get(), MINUTES); } else if (unit == "hrs") { return Duration(value.get(), HOURS); } else if (unit == "days") { return Duration(value.get(), DAYS); } else if (unit == "weeks") { return Duration(value.get(), WEEKS); } else { return Error("Unknown duration unit '" + unit + "'"); } } return Error("Invalid duration '" + s + "'"); } static Try<Duration> create(double seconds); constexpr Duration() : nanos(0) {} explicit Duration(const timeval& t) { nanos = t.tv_sec * SECONDS + t.tv_usec * MICROSECONDS; } int64_t ns() const { return nanos; } double us() const { return static_cast<double>(nanos) / MICROSECONDS; } double ms() const { return static_cast<double>(nanos) / MILLISECONDS; } double secs() const { return static_cast<double>(nanos) / SECONDS; } double mins() const { return static_cast<double>(nanos) / MINUTES; } double hrs() const { return static_cast<double>(nanos) / HOURS; } double days() const { return static_cast<double>(nanos) / DAYS; } double weeks() const { return static_cast<double>(nanos) / WEEKS; } struct timeval timeval() const { struct timeval t; t.tv_sec = secs(); t.tv_usec = us() - (t.tv_sec * MILLISECONDS); return t; } bool operator<(const Duration& d) const { return nanos < d.nanos; } bool operator<=(const Duration& d) const { return nanos <= d.nanos; } bool operator>(const Duration& d) const { return nanos > d.nanos; } bool operator>=(const Duration& d) const { return nanos >= d.nanos; } bool operator==(const Duration& d) const { return nanos == d.nanos; } bool operator!=(const Duration& d) const { return nanos != d.nanos; } Duration& operator+=(const Duration& that) { nanos += that.nanos; return *this; } Duration& operator-=(const Duration& that) { nanos -= that.nanos; return *this; } Duration& operator*=(double multiplier) { nanos = static_cast<int64_t>(nanos * multiplier); return *this; } Duration& operator/=(double divisor) { nanos = static_cast<int64_t>(nanos / divisor); return *this; } Duration operator+(const Duration& that) const { Duration sum = *this; sum += that; return sum; } Duration operator-(const Duration& that) const { Duration diff = *this; diff -= that; return diff; } Duration operator*(double multiplier) const { Duration product = *this; product *= multiplier; return product; } Duration operator/(double divisor) const { Duration quotient = *this; quotient /= divisor; return quotient; } // A constant holding the maximum value a Duration can have. static constexpr Duration max(); // A constant holding the minimum (negative) value a Duration can // have. static constexpr Duration min(); // A constant holding a Duration of a "zero" value. static constexpr Duration zero() { return Duration(); } protected: static const int64_t NANOSECONDS = 1; static const int64_t MICROSECONDS = 1000 * NANOSECONDS; static const int64_t MILLISECONDS = 1000 * MICROSECONDS; static const int64_t SECONDS = 1000 * MILLISECONDS; static const int64_t MINUTES = 60 * SECONDS; static const int64_t HOURS = 60 * MINUTES; static const int64_t DAYS = 24 * HOURS; static const int64_t WEEKS = 7 * DAYS; // Construct from a (value, unit) pair. constexpr Duration(int64_t value, int64_t unit) : nanos(value * unit) {} private: // Used only by "parse". constexpr Duration(double value, int64_t unit) : nanos(static_cast<int64_t>(value * unit)) {} int64_t nanos; friend std::ostream& operator<<( std::ostream& stream, const Duration& duration); }; class Nanoseconds : public Duration { public: explicit constexpr Nanoseconds(int64_t nanoseconds) : Duration(nanoseconds, NANOSECONDS) {} constexpr Nanoseconds(const Duration& d) : Duration(d) {} double value() const { return static_cast<double>(this->ns()); } static std::string units() { return "ns"; } }; class Microseconds : public Duration { public: explicit constexpr Microseconds(int64_t microseconds) : Duration(microseconds, MICROSECONDS) {} constexpr Microseconds(const Duration& d) : Duration(d) {} double value() const { return this->us(); } static std::string units() { return "us"; } }; class Milliseconds : public Duration { public: explicit constexpr Milliseconds(int64_t milliseconds) : Duration(milliseconds, MILLISECONDS) {} constexpr Milliseconds(const Duration& d) : Duration(d) {} double value() const { return this->ms(); } static std::string units() { return "ms"; } }; class Seconds : public Duration { public: explicit constexpr Seconds(int64_t seconds) : Duration(seconds, SECONDS) {} constexpr Seconds(const Duration& d) : Duration(d) {} double value() const { return this->secs(); } static std::string units() { return "secs"; } }; class Minutes : public Duration { public: explicit constexpr Minutes(int64_t minutes) : Duration(minutes, MINUTES) {} constexpr Minutes(const Duration& d) : Duration(d) {} double value() const { return this->mins(); } static std::string units() { return "mins"; } }; class Hours : public Duration { public: explicit constexpr Hours(int64_t hours) : Duration(hours, HOURS) {} constexpr Hours(const Duration& d) : Duration(d) {} double value() const { return this->hrs(); } static std::string units() { return "hrs"; } }; class Days : public Duration { public: explicit Days(int64_t days) : Duration(days, DAYS) {} Days(const Duration& d) : Duration(d) {} double value() const { return this->days(); } static std::string units() { return "days"; } }; class Weeks : public Duration { public: explicit constexpr Weeks(int64_t value) : Duration(value, WEEKS) {} constexpr Weeks(const Duration& d) : Duration(d) {} double value() const { return this->weeks(); } static std::string units() { return "weeks"; } }; inline std::ostream& operator<<(std::ostream& stream, const Duration& duration_) { long precision = stream.precision(); // Output the duration in full double precision. stream.precision(std::numeric_limits<double>::digits10); // Parse the duration as the sign and the absolute value. Duration duration = duration_; if (duration_ < Duration::zero()) { stream << "-"; // Duration::min() may not be representable as a positive Duration. if (duration_ == Duration::min()) { duration = Duration::max(); } else { duration = duration_ * -1; } } // First determine which bucket of time unit the duration falls into // then check whether the duration can be represented as a whole // number with this time unit or a smaller one. // e.g. 1.42857142857143weeks falls into the 'Weeks' bucket but // reads better with a smaller unit: '10days'. So we use 'days' // instead of 'weeks' to output the duration. int64_t nanoseconds = duration.ns(); if (duration < Microseconds(1)) { stream << duration.ns() << Nanoseconds::units(); } else if (duration < Milliseconds(1)) { if (nanoseconds % Duration::MICROSECONDS != 0) { // We can't get a whole number using this unit but we can at // one level down. stream << duration.ns() << Nanoseconds::units(); } else { stream << duration.us() << Microseconds::units(); } } else if (duration < Seconds(1)) { if (nanoseconds % Duration::MILLISECONDS != 0 && nanoseconds % Duration::MICROSECONDS == 0) { stream << duration.us() << Microseconds::units(); } else { stream << duration.ms() << Milliseconds::units(); } } else if (duration < Minutes(1)) { if (nanoseconds % Duration::SECONDS != 0 && nanoseconds % Duration::MILLISECONDS == 0) { stream << duration.ms() << Milliseconds::units(); } else { stream << duration.secs() << Seconds::units(); } } else if (duration < Hours(1)) { if (nanoseconds % Duration::MINUTES != 0 && nanoseconds % Duration::SECONDS == 0) { stream << duration.secs() << Seconds::units(); } else { stream << duration.mins() << Minutes::units(); } } else if (duration < Days(1)) { if (nanoseconds % Duration::HOURS != 0 && nanoseconds % Duration::MINUTES == 0) { stream << duration.mins() << Minutes::units(); } else { stream << duration.hrs() << Hours::units(); } } else if (duration < Weeks(1)) { if (nanoseconds % Duration::DAYS != 0 && nanoseconds % Duration::HOURS == 0) { stream << duration.hrs() << Hours::units(); } else { stream << duration.days() << Days::units(); } } else { if (nanoseconds % Duration::WEEKS != 0 && nanoseconds % Duration::DAYS == 0) { stream << duration.days() << Days::units(); } else { stream << duration.weeks() << Weeks::units(); } } // Return the stream to original formatting state. stream.precision(precision); return stream; } inline Try<Duration> Duration::create(double seconds) { if (seconds * SECONDS > std::numeric_limits<int64_t>::max() || seconds * SECONDS < std::numeric_limits<int64_t>::min()) { return Error("Argument out of the range that a Duration can represent due " "to int64_t's size limit"); } return Nanoseconds(static_cast<int64_t>(seconds * SECONDS)); } inline constexpr Duration Duration::max() { return Nanoseconds(std::numeric_limits<int64_t>::max()); } inline constexpr Duration Duration::min() { return Nanoseconds(std::numeric_limits<int64_t>::min()); } #endif // __STOUT_DURATION_HPP__ <|endoftext|>
<commit_before>/** * File : D.cpp * Author : Kazune Takahashi * Created : 2/9/2019, 9:16:48 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int L; ll A[200010]; ll B[200010]; // even ll C[200010]; // odd ll sum[200010][3]; ll calc(int a, int b, int c, int d) { ll ans = 0; ans += sum[a][0] - sum[0][0]; ans += sum[b][1] - sum[a][1]; ans += sum[c][2] - sum[b][2]; ans += sum[d][1] - sum[c][1]; ans += sum[L][0] - sum[d][0]; return ans; } int main() { cin >> L; ll mini = 0; for (auto i = 0; i < L; i++) { cin >> A[i]; mini += A[i]; } bool zero = true; for (auto i = 0; i < L; i++) { if (A[i] > 0) { zero = false; break; } } if (zero) { cout << 0 << endl; return 0; } for (auto i = 0; i < L; i++) { if (A[i] == 0) { B[i] = 2; } else if (A[i] % 2 == 0) { B[i] = 0; } else { B[i] = 1; } } for (auto i = 0; i < L; i++) { if (A[i] % 2 == 1) { C[i] = 0; } else { C[i] = 1; } } sum[0][0] = sum[0][1] = sum[0][2] = 0; for (auto i = 0; i < L; i++) { sum[0][i + 1] = sum[0][i] + A[i]; sum[1][i + 1] = sum[1][i] + B[i]; sum[2][i + 1] = sum[2][i] + C[i]; } for (auto a = 0; a <= L; a++) { for (auto b = a; b <= L; b++) { for (auto c = b; c <= L; c++) { for (auto d = c; d <= L; d++) { ll t = calc(a, b, c, d); if (t <= mini) { mini = min(mini, t); cerr << "calc(" << a << ", " << b << ", " << c << ", " << d << ") = " << t << endl; } } } } } cerr << mini << endl; }<commit_msg>tried D.cpp to 'D'<commit_after>/** * File : D.cpp * Author : Kazune Takahashi * Created : 2/9/2019, 9:16:48 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int L; ll A[200010]; ll B[200010]; // even ll C[200010]; // odd ll sum[3][200010]; ll calc(int a, int b, int c, int d) { ll ans = 0; ans += sum[0][a] - sum[0][0]; ans += sum[1][b] - sum[1][a]; ans += sum[2][c] - sum[2][b]; ans += sum[1][d] - sum[1][c]; ans += sum[0][L] - sum[0][d]; return ans; } int main() { cin >> L; ll mini = 0; for (auto i = 0; i < L; i++) { cin >> A[i]; mini += A[i]; } bool zero = true; for (auto i = 0; i < L; i++) { if (A[i] > 0) { zero = false; break; } } if (zero) { cout << 0 << endl; return 0; } for (auto i = 0; i < L; i++) { if (A[i] == 0) { B[i] = 2; } else if (A[i] % 2 == 0) { B[i] = 0; } else { B[i] = 1; } } for (auto i = 0; i < L; i++) { if (A[i] % 2 == 1) { C[i] = 0; } else { C[i] = 1; } } sum[0][0] = sum[0][1] = sum[0][2] = 0; for (auto i = 0; i < L; i++) { sum[0][i + 1] = sum[0][i] + A[i]; sum[1][i + 1] = sum[1][i] + B[i]; sum[2][i + 1] = sum[2][i] + C[i]; } for (auto a = 0; a <= L; a++) { for (auto b = a; b <= L; b++) { for (auto c = b; c <= L; c++) { for (auto d = c; d <= L; d++) { ll t = calc(a, b, c, d); if (t <= mini) { mini = min(mini, t); cerr << "calc(" << a << ", " << b << ", " << c << ", " << d << ") = " << t << endl; } } } } } cerr << mini << endl; }<|endoftext|>
<commit_before> /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #ifndef _Stroika_Foundation_Database_SQL_ORM_TableConnection_inl_ #define _Stroika_Foundation_Database_SQL_ORM_TableConnection_inl_ 1 #include "../../../Debug/Trace.h" namespace Stroika::Foundation::Database::SQL::ORM { /* ******************************************************************************** ******************************** TableConnection ******************************* ******************************************************************************** */ template <typename T, typename TRAITS> TableConnection<T, TRAITS>::TableConnection (const Connection::Ptr& conn, const Schema::Table& tableSchema, const ObjectVariantMapper& objectVariantMapper) : pConnection{[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) { const TableConnection* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &TableConnection::pConnection); return thisObj->fConnection_; }} , pTableSchema{[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) { const TableConnection* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &TableConnection::pTableSchema); return thisObj->fTableSchema_; }} , pObjectVariantMapper{[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) { const TableConnection* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &TableConnection::pObjectVariantMapper); return thisObj->fObjectVariantMapper_; }} , fConnection_{conn} , fTableSchema_{tableSchema} , fObjectVariantMapper_{objectVariantMapper} , fGetByID_Statement_{conn->mkStatement (Schema::StandardSQLStatements{tableSchema}.GetByID ())} , fGetAll_Statement_{conn->mkStatement (Schema::StandardSQLStatements{tableSchema}.GetAllElements ())} , fAddNew_Statement_{conn->mkStatement (Schema::StandardSQLStatements{tableSchema}.Insert ())} , fUpdate_Statement_{conn->mkStatement (Schema::StandardSQLStatements{tableSchema}.UpdateByID ())} { Require (conn != nullptr); // too late, but good docs } template <typename T, typename TRAITS> inline TableConnection<T, TRAITS>::TableConnection (const TableConnection& src) : TableConnection{src.fConnection_, src.fTableSchema_, src.fObjectVariantMapper_} { } template <typename T, typename TRAITS> optional<T> TableConnection<T, TRAITS>::GetByID (const typename TRAITS::IDType& id) { lock_guard<const AssertExternallySynchronizedMutex> critSec{*this}; using DataExchange::VariantValue; using Stroika::Foundation::Common::KeyValuePair; fGetByID_Statement_.Reset (); fGetByID_Statement_.Bind (initializer_list<KeyValuePair<String, VariantValue>>{{fTableSchema_.GetIDField ()->fName, TRAITS::ID2VariantValue (id)}}); if constexpr (TRAITS::kTraceLogEachRequest) { DbgTrace (L"SQL: %s", fGetByID_Statement_.GetSQL (Statement::WhichSQLFlag::eExpanded).c_str ()); } auto rows = fGetByID_Statement_.GetAllRows () .template Select<T> ([this] (const Statement::Row& r) { return fObjectVariantMapper_.ToObject<T> (VariantValue{fTableSchema_.MapFromDB (r)}); }); if (rows.empty ()) { return nullopt; } Ensure (rows.size () == 1); // cuz arg sb a key return *rows.First (); } template <typename T, typename TRAITS> Sequence<T> TableConnection<T, TRAITS>::GetAll () { lock_guard<const AssertExternallySynchronizedMutex> critSec{*this}; using DataExchange::VariantValue; using Stroika::Foundation::Common::KeyValuePair; if constexpr (TRAITS::kTraceLogEachRequest) { DbgTrace (L"SQL: %s", fGetAll_Statement_.GetSQL ().c_str ()); } auto rows = fGetAll_Statement_.GetAllRows () .template Select<T> ([this] (const Statement::Row& r) { return fObjectVariantMapper_.ToObject<T> (VariantValue{fTableSchema_.MapFromDB (r)}); }); return Sequence<T>{rows}; } template <typename T, typename TRAITS> void TableConnection<T, TRAITS>::AddNew (const T& v) { lock_guard<const AssertExternallySynchronizedMutex> critSec{*this}; using DataExchange::VariantValue; using Stroika::Foundation::Common::KeyValuePair; fAddNew_Statement_.Reset (); fAddNew_Statement_.Bind (fTableSchema_.MapToDB (fObjectVariantMapper_.FromObject (v).template As<Mapping<String, VariantValue>> ())); if constexpr (TRAITS::kTraceLogEachRequest) { DbgTrace (L"SQL: %s", fAddNew_Statement_.GetSQL (Statement::WhichSQLFlag::eExpanded).c_str ()); } fAddNew_Statement_.Execute (); } template <typename T, typename TRAITS> void TableConnection<T, TRAITS>::AddOrUpdate (const T& v) { // this can and should be done more efficiently if (auto i = GetByID (v)) { Update (v); } else { AddNew (v); } } template <typename T, typename TRAITS> void TableConnection<T, TRAITS>::Update (const T& v) { lock_guard<const AssertExternallySynchronizedMutex> critSec{*this}; using DataExchange::VariantValue; using Stroika::Foundation::Common::KeyValuePair; fUpdate_Statement_.Reset (); fUpdate_Statement_.Bind (fTableSchema_.MapToDB (fObjectVariantMapper_.FromObject (v).template As<Mapping<String, VariantValue>> ())); if constexpr (TRAITS::kTraceLogEachRequest) { DbgTrace (L"SQL: %s", fUpdate_Statement_.GetSQL (Statement::WhichSQLFlag::eExpanded).c_str ()); } fUpdate_Statement_.Execute (); } } #endif /*_Stroika_Foundation_Database_SQL_ORM_TableConnection_inl_*/ <commit_msg>mostly cosmetic cleanups to SQL/ORM/TableConnection<commit_after> /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #ifndef _Stroika_Foundation_Database_SQL_ORM_TableConnection_inl_ #define _Stroika_Foundation_Database_SQL_ORM_TableConnection_inl_ 1 #include "../../../Debug/Trace.h" namespace Stroika::Foundation::Database::SQL::ORM { /* ******************************************************************************** ******************************** TableConnection ******************************* ******************************************************************************** */ template <typename T, typename TRAITS> TableConnection<T, TRAITS>::TableConnection (const Connection::Ptr& conn, const Schema::Table& tableSchema, const ObjectVariantMapper& objectVariantMapper) : pConnection{[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) { const TableConnection* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &TableConnection::pConnection); return thisObj->fConnection_; }} , pTableSchema{[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) { const TableConnection* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &TableConnection::pTableSchema); return thisObj->fTableSchema_; }} , pObjectVariantMapper{[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) { const TableConnection* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &TableConnection::pObjectVariantMapper); return thisObj->fObjectVariantMapper_; }} , fConnection_{conn} , fTableSchema_{tableSchema} , fObjectVariantMapper_{objectVariantMapper} , fGetByID_Statement_{conn->mkStatement (Schema::StandardSQLStatements{tableSchema}.GetByID ())} , fGetAll_Statement_{conn->mkStatement (Schema::StandardSQLStatements{tableSchema}.GetAllElements ())} , fAddNew_Statement_{conn->mkStatement (Schema::StandardSQLStatements{tableSchema}.Insert ())} , fUpdate_Statement_{conn->mkStatement (Schema::StandardSQLStatements{tableSchema}.UpdateByID ())} { Require (conn != nullptr); // too late, but good docs } template <typename T, typename TRAITS> inline TableConnection<T, TRAITS>::TableConnection (const TableConnection& src) : TableConnection{src.fConnection_, src.fTableSchema_, src.fObjectVariantMapper_} { } template <typename T, typename TRAITS> optional<T> TableConnection<T, TRAITS>::GetByID (const typename TRAITS::IDType& id) { lock_guard<const AssertExternallySynchronizedMutex> critSec{*this}; using DataExchange::VariantValue; using Stroika::Foundation::Common::KeyValuePair; fGetByID_Statement_.Reset (); fGetByID_Statement_.Bind (initializer_list<KeyValuePair<String, VariantValue>>{{fTableSchema_.GetIDField ()->fName, TRAITS::ID2VariantValue (id)}}); if constexpr (TRAITS::kTraceLogEachRequest) { DbgTrace (L"SQL: %s", fGetByID_Statement_.GetSQL (Statement::WhichSQLFlag::eExpanded).c_str ()); } auto rows = fGetByID_Statement_.GetAllRows () .template Select<T> ([this] (const Statement::Row& r) { return fObjectVariantMapper_.ToObject<T> (VariantValue{fTableSchema_.MapFromDB (r)}); }); if (rows.empty ()) { return nullopt; } Ensure (rows.size () == 1); // cuz arg sb a key return *rows.First (); } template <typename T, typename TRAITS> Sequence<T> TableConnection<T, TRAITS>::GetAll () { lock_guard<const AssertExternallySynchronizedMutex> critSec{*this}; using DataExchange::VariantValue; using Stroika::Foundation::Common::KeyValuePair; if constexpr (TRAITS::kTraceLogEachRequest) { DbgTrace (L"SQL: %s", fGetAll_Statement_.GetSQL ().c_str ()); } auto rows = fGetAll_Statement_.GetAllRows () .template Select<T> ([this] (const Statement::Row& r) { return fObjectVariantMapper_.ToObject<T> (VariantValue{fTableSchema_.MapFromDB (r)}); }); return Sequence<T>{rows}; } template <typename T, typename TRAITS> void TableConnection<T, TRAITS>::AddNew (const T& v) { lock_guard<const AssertExternallySynchronizedMutex> critSec{*this}; using DataExchange::VariantValue; fAddNew_Statement_.Reset (); fAddNew_Statement_.Bind (fTableSchema_.MapToDB (fObjectVariantMapper_.FromObject (v).template As<Mapping<String, VariantValue>> ())); if constexpr (TRAITS::kTraceLogEachRequest) { DbgTrace (L"SQL: %s", fAddNew_Statement_.GetSQL (Statement::WhichSQLFlag::eExpanded).c_str ()); } fAddNew_Statement_.Execute (); } template <typename T, typename TRAITS> void TableConnection<T, TRAITS>::AddOrUpdate (const T& v) { // this can and should be done more efficiently if (GetByID (v)) { Update (v); } else { AddNew (v); } } template <typename T, typename TRAITS> void TableConnection<T, TRAITS>::Update (const T& v) { lock_guard<const AssertExternallySynchronizedMutex> critSec{*this}; using DataExchange::VariantValue; using Stroika::Foundation::Common::KeyValuePair; fUpdate_Statement_.Reset (); fUpdate_Statement_.Bind (fTableSchema_.MapToDB (fObjectVariantMapper_.FromObject (v).template As<Mapping<String, VariantValue>> ())); if constexpr (TRAITS::kTraceLogEachRequest) { DbgTrace (L"SQL: %s", fUpdate_Statement_.GetSQL (Statement::WhichSQLFlag::eExpanded).c_str ()); } fUpdate_Statement_.Execute (); } } #endif /*_Stroika_Foundation_Database_SQL_ORM_TableConnection_inl_*/ <|endoftext|>
<commit_before>#include "otbTrainImagesBase.h" namespace otb { namespace Wrapper { class TrainImagesClassifier : public TrainImagesBase { public: typedef TrainImagesClassifier Self; typedef TrainImagesBase Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; itkNewMacro( Self ) itkTypeMacro( Self, Superclass ) void DoInit() ITK_OVERRIDE { SetName( "TrainImagesClassifier" ); SetDescription( "Train a classifier from multiple pairs of images and training vector data." ); // Documentation SetDocName( "Train a classifier from multiple images" ); SetDocLongDescription( "This application performs a classifier training from multiple pairs of input images and training vector data. " "Samples are composed of pixel values in each band optionally centered and reduced using an XML statistics file produced by " "the ComputeImagesStatistics application.\n The training vector data must contain polygons with a positive integer field " "representing the class label. The name of this field can be set using the \"Class label field\" parameter. Training and validation " "sample lists are built such that each class is equally represented in both lists. One parameter allows controlling the ratio " "between the number of samples in training and validation sets. Two parameters allow managing the size of the training and " "validation sets per class and per image.\n Several classifier parameters can be set depending on the chosen classifier. In the " "validation process, the confusion matrix is organized the following way: rows = reference labels, columns = produced labels. " "In the header of the optional confusion matrix output file, the validation (reference) and predicted (produced) class labels" " are ordered according to the rows/columns of the confusion matrix.\n This application is based on LibSVM and OpenCV Machine Learning " "(2.3.1 and later)." ); SetDocLimitations( "None" ); SetDocAuthors( "OTB-Team" ); SetDocSeeAlso( "OpenCV documentation for machine learning http://docs.opencv.org/modules/ml/doc/ml.html " ); AddDocTag( Tags::Learning ); // Perform initialization ClearApplications(); InitIO(); InitSampling(); InitClassification(); AddDocTag( Tags::Learning ); // Doc example parameter settings SetDocExampleParameterValue( "io.il", "QB_1_ortho.tif" ); SetDocExampleParameterValue( "io.vd", "VectorData_QB1.shp" ); SetDocExampleParameterValue( "io.imstat", "EstimateImageStatisticsQB1.xml" ); SetDocExampleParameterValue( "sample.mv", "100" ); SetDocExampleParameterValue( "sample.mt", "100" ); SetDocExampleParameterValue( "sample.vtr", "0.5" ); SetDocExampleParameterValue( "sample.vfn", "Class" ); SetDocExampleParameterValue( "classifier", "libsvm" ); SetDocExampleParameterValue( "classifier.libsvm.k", "linear" ); SetDocExampleParameterValue( "classifier.libsvm.c", "1" ); SetDocExampleParameterValue( "classifier.libsvm.opt", "false" ); SetDocExampleParameterValue( "io.out", "svmModelQB1.txt" ); SetDocExampleParameterValue( "io.confmatout", "svmConfusionMatrixQB1.csv" ); } void DoUpdateParameters() ITK_OVERRIDE { if( HasValue( "io.vd" ) && IsParameterEnabled( "io.vd" )) { UpdatePolygonClassStatisticsParameters(); } // Change mandatory of input vector depending on supervised and unsupervised mode. // if( HasValue( "classifier" ) ) // { // UpdateInternalParameters( "training" ); // switch( trainVectorBase->GetClassifierCategory() ) // { // case TrainVectorBase::Unsupervised: // MandatoryOff( "io.vd" ); // break; // default: // case TrainVectorBase::Supervised: // MandatoryOn( "io.vd" ); // break; // } // } } /** * Select and Extract samples for validation with computed statistics and rates. * Validation samples could be empty if sample.vrt == 0 and if no dedicated validation are provided. * If no dedicated validation is provided the training is split corresponding to the sample.vtr parameter, * in this case if no vector data have been provided, the training rates and statistics are computed * on the selection and extraction training result. * fileNames.sampleOutputs contains training data and after an ExtractValidationData training data will * be split to fileNames.sampleTrainOutputs. * \param imageList * \param fileNames * \param validationVectorFileList * \param rates * \param HasInputVector */ void ExtractValidationData(FloatVectorImageListType *imageList, TrainFileNamesHandler& fileNames, std::vector<std::string> validationVectorFileList, const SamplingRates& rates, bool HasInputVector ) { if( !validationVectorFileList.empty() ) // Compute class statistics and sampling rate of validation data if provided. { ComputePolygonStatistics( imageList, validationVectorFileList, fileNames.polyStatValidOutputs ); ComputeSamplingRate( fileNames.polyStatValidOutputs, fileNames.rateValidOut, rates.fmv ); SelectAndExtractValidationSamples( fileNames, imageList, validationVectorFileList ); // if( HasInputVector ) // if input vector is provided the sampleTrainOutputs is the previously extracted sampleOutputs fileNames.sampleTrainOutputs = fileNames.sampleOutputs; } else if(GetParameterFloat("sample.vtr") != 0.0)// Split training data to validation { // if( !HasInputVector ) // Compute one class statistics and sampling rate for the generated vector. // ComputePolygonStatistics( imageList, fileNames.sampleOutputs, fileNames.polyStatTrainOutputs ); // ComputeSamplingRate( fileNames.polyStatTrainOutputs, fileNames.rateTrainOut, rates.fmt ); SplitTrainingToValidationSamples( fileNames, imageList ); } else // nothing to do, except update fileNames { fileNames.sampleTrainOutputs = fileNames.sampleOutputs; } } /** * Extract Training data depending if input vector is provided * \param imageList list of the image * \param fileNames handler that contain filenames * \param vectorFileList input vector file list (if provided * \param rates */ void ExtractTrainData(FloatVectorImageListType *imageList, const TrainFileNamesHandler& fileNames, std::vector<std::string> vectorFileList, const SamplingRates& rates) { // if( !vectorFileList.empty() ) // Select and Extract samples for training with computed statistics and rates // { ComputePolygonStatistics( imageList, vectorFileList, fileNames.polyStatTrainOutputs ); ComputeSamplingRate( fileNames.polyStatTrainOutputs, fileNames.rateTrainOut, rates.fmt ); SelectAndExtractTrainSamples( fileNames, imageList, vectorFileList, SamplingStrategy::CLASS ); // } // else // Select training samples base on geometric sampling if no input vector is provided // { // SelectAndExtractTrainSamples( fileNames, imageList, vectorFileList, SamplingStrategy::GEOMETRIC, "fid" ); // } } void DoExecute() { TrainFileNamesHandler fileNames; std::vector<std::string> vectorFileList; FloatVectorImageListType *imageList = GetParameterImageList( "io.il" ); bool HasInputVector = IsParameterEnabled( "io.vd" ) && HasValue( "io.vd" ); if(HasInputVector) vectorFileList = GetParameterStringList( "io.vd" ); unsigned long nbInputs = imageList->Size(); if( !HasInputVector ) // && trainVectorBase->GetClassifierCategory() == TrainVectorBase::Supervised ) { otbAppLogFATAL( "Missing input vector data files" ); } if( !vectorFileList.empty() && nbInputs > vectorFileList.size() ) { otbAppLogFATAL( "Missing input vector data files to match number of images (" << nbInputs << ")." ); } // check if validation vectors are given std::vector<std::string> validationVectorFileList; bool dedicatedValidation = false; if( IsParameterEnabled( "io.valid" ) && HasValue( "io.valid" ) ) { validationVectorFileList = GetParameterStringList( "io.valid" ); if( nbInputs > validationVectorFileList.size() ) { otbAppLogFATAL( "Missing validation vector data files to match number of images (" << nbInputs << ")." ); } dedicatedValidation = true; } fileNames.CreateTemporaryFileNames( GetParameterString( "io.out" ), nbInputs, dedicatedValidation ); // Compute final maximum sampling rates for both training and validation samples SamplingRates rates = ComputeFinalMaximumSamplingRates( dedicatedValidation ); ExtractTrainData(imageList, fileNames, vectorFileList, rates); ExtractValidationData(imageList, fileNames, validationVectorFileList, rates, HasInputVector); // Then train the model with extracted samples TrainModel( imageList, fileNames.sampleTrainOutputs, fileNames.sampleValidOutputs ); // cleanup if( IsParameterEnabled( "cleanup" ) ) { otbAppLogINFO( <<"Final clean-up ..." ); fileNames.clear(); } } private : void UpdatePolygonClassStatisticsParameters() { std::vector<std::string> vectorFileList = GetParameterStringList( "io.vd" ); GetInternalApplication( "polystat" )->SetParameterString( "vec", vectorFileList[0], false ); UpdateInternalParameters( "polystat" ); } }; } } OTB_APPLICATION_EXPORT( otb::Wrapper::TrainImagesClassifier )<commit_msg>WRG: Remove not used warning.<commit_after>#include "otbTrainImagesBase.h" namespace otb { namespace Wrapper { class TrainImagesClassifier : public TrainImagesBase { public: typedef TrainImagesClassifier Self; typedef TrainImagesBase Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; itkNewMacro( Self ) itkTypeMacro( Self, Superclass ) void DoInit() ITK_OVERRIDE { SetName( "TrainImagesClassifier" ); SetDescription( "Train a classifier from multiple pairs of images and training vector data." ); // Documentation SetDocName( "Train a classifier from multiple images" ); SetDocLongDescription( "This application performs a classifier training from multiple pairs of input images and training vector data. " "Samples are composed of pixel values in each band optionally centered and reduced using an XML statistics file produced by " "the ComputeImagesStatistics application.\n The training vector data must contain polygons with a positive integer field " "representing the class label. The name of this field can be set using the \"Class label field\" parameter. Training and validation " "sample lists are built such that each class is equally represented in both lists. One parameter allows controlling the ratio " "between the number of samples in training and validation sets. Two parameters allow managing the size of the training and " "validation sets per class and per image.\n Several classifier parameters can be set depending on the chosen classifier. In the " "validation process, the confusion matrix is organized the following way: rows = reference labels, columns = produced labels. " "In the header of the optional confusion matrix output file, the validation (reference) and predicted (produced) class labels" " are ordered according to the rows/columns of the confusion matrix.\n This application is based on LibSVM and OpenCV Machine Learning " "(2.3.1 and later)." ); SetDocLimitations( "None" ); SetDocAuthors( "OTB-Team" ); SetDocSeeAlso( "OpenCV documentation for machine learning http://docs.opencv.org/modules/ml/doc/ml.html " ); AddDocTag( Tags::Learning ); // Perform initialization ClearApplications(); InitIO(); InitSampling(); InitClassification(); AddDocTag( Tags::Learning ); // Doc example parameter settings SetDocExampleParameterValue( "io.il", "QB_1_ortho.tif" ); SetDocExampleParameterValue( "io.vd", "VectorData_QB1.shp" ); SetDocExampleParameterValue( "io.imstat", "EstimateImageStatisticsQB1.xml" ); SetDocExampleParameterValue( "sample.mv", "100" ); SetDocExampleParameterValue( "sample.mt", "100" ); SetDocExampleParameterValue( "sample.vtr", "0.5" ); SetDocExampleParameterValue( "sample.vfn", "Class" ); SetDocExampleParameterValue( "classifier", "libsvm" ); SetDocExampleParameterValue( "classifier.libsvm.k", "linear" ); SetDocExampleParameterValue( "classifier.libsvm.c", "1" ); SetDocExampleParameterValue( "classifier.libsvm.opt", "false" ); SetDocExampleParameterValue( "io.out", "svmModelQB1.txt" ); SetDocExampleParameterValue( "io.confmatout", "svmConfusionMatrixQB1.csv" ); } void DoUpdateParameters() ITK_OVERRIDE { if( HasValue( "io.vd" ) && IsParameterEnabled( "io.vd" )) { UpdatePolygonClassStatisticsParameters(); } // Change mandatory of input vector depending on supervised and unsupervised mode. // if( HasValue( "classifier" ) ) // { // UpdateInternalParameters( "training" ); // switch( trainVectorBase->GetClassifierCategory() ) // { // case TrainVectorBase::Unsupervised: // MandatoryOff( "io.vd" ); // break; // default: // case TrainVectorBase::Supervised: // MandatoryOn( "io.vd" ); // break; // } // } } /** * Select and Extract samples for validation with computed statistics and rates. * Validation samples could be empty if sample.vrt == 0 and if no dedicated validation are provided. * If no dedicated validation is provided the training is split corresponding to the sample.vtr parameter, * in this case if no vector data have been provided, the training rates and statistics are computed * on the selection and extraction training result. * fileNames.sampleOutputs contains training data and after an ExtractValidationData training data will * be split to fileNames.sampleTrainOutputs. * \param imageList * \param fileNames * \param validationVectorFileList * \param rates * \param HasInputVector */ void ExtractValidationData(FloatVectorImageListType *imageList, TrainFileNamesHandler& fileNames, std::vector<std::string> validationVectorFileList, const SamplingRates& rates, bool itkNotUsed(HasInputVector) ) { if( !validationVectorFileList.empty() ) // Compute class statistics and sampling rate of validation data if provided. { ComputePolygonStatistics( imageList, validationVectorFileList, fileNames.polyStatValidOutputs ); ComputeSamplingRate( fileNames.polyStatValidOutputs, fileNames.rateValidOut, rates.fmv ); SelectAndExtractValidationSamples( fileNames, imageList, validationVectorFileList ); // if( HasInputVector ) // if input vector is provided the sampleTrainOutputs is the previously extracted sampleOutputs fileNames.sampleTrainOutputs = fileNames.sampleOutputs; } else if(GetParameterFloat("sample.vtr") != 0.0)// Split training data to validation { // if( !HasInputVector ) // Compute one class statistics and sampling rate for the generated vector. // ComputePolygonStatistics( imageList, fileNames.sampleOutputs, fileNames.polyStatTrainOutputs ); // ComputeSamplingRate( fileNames.polyStatTrainOutputs, fileNames.rateTrainOut, rates.fmt ); SplitTrainingToValidationSamples( fileNames, imageList ); } else // nothing to do, except update fileNames { fileNames.sampleTrainOutputs = fileNames.sampleOutputs; } } /** * Extract Training data depending if input vector is provided * \param imageList list of the image * \param fileNames handler that contain filenames * \param vectorFileList input vector file list (if provided * \param rates */ void ExtractTrainData(FloatVectorImageListType *imageList, const TrainFileNamesHandler& fileNames, std::vector<std::string> vectorFileList, const SamplingRates& rates) { // if( !vectorFileList.empty() ) // Select and Extract samples for training with computed statistics and rates // { ComputePolygonStatistics( imageList, vectorFileList, fileNames.polyStatTrainOutputs ); ComputeSamplingRate( fileNames.polyStatTrainOutputs, fileNames.rateTrainOut, rates.fmt ); SelectAndExtractTrainSamples( fileNames, imageList, vectorFileList, SamplingStrategy::CLASS ); // } // else // Select training samples base on geometric sampling if no input vector is provided // { // SelectAndExtractTrainSamples( fileNames, imageList, vectorFileList, SamplingStrategy::GEOMETRIC, "fid" ); // } } void DoExecute() { TrainFileNamesHandler fileNames; std::vector<std::string> vectorFileList; FloatVectorImageListType *imageList = GetParameterImageList( "io.il" ); bool HasInputVector = IsParameterEnabled( "io.vd" ) && HasValue( "io.vd" ); if(HasInputVector) vectorFileList = GetParameterStringList( "io.vd" ); unsigned long nbInputs = imageList->Size(); if( !HasInputVector ) // && trainVectorBase->GetClassifierCategory() == TrainVectorBase::Supervised ) { otbAppLogFATAL( "Missing input vector data files" ); } if( !vectorFileList.empty() && nbInputs > vectorFileList.size() ) { otbAppLogFATAL( "Missing input vector data files to match number of images (" << nbInputs << ")." ); } // check if validation vectors are given std::vector<std::string> validationVectorFileList; bool dedicatedValidation = false; if( IsParameterEnabled( "io.valid" ) && HasValue( "io.valid" ) ) { validationVectorFileList = GetParameterStringList( "io.valid" ); if( nbInputs > validationVectorFileList.size() ) { otbAppLogFATAL( "Missing validation vector data files to match number of images (" << nbInputs << ")." ); } dedicatedValidation = true; } fileNames.CreateTemporaryFileNames( GetParameterString( "io.out" ), nbInputs, dedicatedValidation ); // Compute final maximum sampling rates for both training and validation samples SamplingRates rates = ComputeFinalMaximumSamplingRates( dedicatedValidation ); ExtractTrainData(imageList, fileNames, vectorFileList, rates); ExtractValidationData(imageList, fileNames, validationVectorFileList, rates, HasInputVector); // Then train the model with extracted samples TrainModel( imageList, fileNames.sampleTrainOutputs, fileNames.sampleValidOutputs ); // cleanup if( IsParameterEnabled( "cleanup" ) ) { otbAppLogINFO( <<"Final clean-up ..." ); fileNames.clear(); } } private : void UpdatePolygonClassStatisticsParameters() { std::vector<std::string> vectorFileList = GetParameterStringList( "io.vd" ); GetInternalApplication( "polystat" )->SetParameterString( "vec", vectorFileList[0], false ); UpdateInternalParameters( "polystat" ); } }; } } OTB_APPLICATION_EXPORT( otb::Wrapper::TrainImagesClassifier )<|endoftext|>
<commit_before>/** * @file Simulation.cpp * @author <a href="mailto:[email protected]">Benjamin Schlotter</a> * Implementation of class Simulation */ #include "Simulation.h" using namespace naoth; using namespace std; Simulation::Simulation() { DEBUG_REQUEST_REGISTER("Simulation:draw_one_action_point:global","draw_one_action_point:global", true); DEBUG_REQUEST_REGISTER("Simulation:draw_ball","draw_ball", true); DEBUG_REQUEST_REGISTER("Simulation:ActionTarget","ActionTarget", true); //actionRingBuffer.resize(ActionModel::numOfActions); //calculate the actions action_local.reserve(ActionNew::numOfActions); action_local.push_back(Action(ActionNew::none, Vector2d())); action_local.push_back(Action(ActionNew::kick_long, Vector2d(theParameters.action_long_kick_distance, 0))); // long action_local.push_back(Action(ActionNew::kick_short, Vector2d(theParameters.action_short_kick_distance, 0))); // short action_local.push_back(Action(ActionNew::sidekick_right, Vector2d(0, -theParameters.action_sidekick_distance))); // right action_local.push_back(Action(ActionNew::sidekick_left, Vector2d(0, theParameters.action_sidekick_distance))); // left actionRingBuffer.resize(ActionNew::numOfActions); } Simulation::~Simulation(){} void Simulation::execute() { if(!getBallModel().valid || getFrameInfo().getTimeInSeconds() >= getBallModel().frameInfoWhenBallWasSeen.getTimeInSeconds()+1) { return; } else { int best_action = 0; for(size_t i=0; i<actionRingBuffer.size(); i++) { simulate(action_local[i], actionRingBuffer[i]); if(action_local[i].potential < action_local[best_action].potential) { best_action = i; } } getActionNew().myAction = action_local[best_action].id(); } }//end execute void Simulation::simulate(Simulation::Action& action, RingBufferWithSum<double, 30>& actionRingBuffer)const { Vector2d ballPositionResult = calculateOneAction(action); DEBUG_REQUEST("Simulation:draw_one_action_point:global", FIELD_DRAWING_CONTEXT; PEN("000000", 1); CIRCLE( ballPositionResult.x, ballPositionResult.y, 50); ); double v = evaluateAction(ballPositionResult); actionRingBuffer.add(v); action.potential = actionRingBuffer.getAverage(); //if there is big gap between our values(average and median), we know it is not good //action.goodness = actionRingBuffer.getAverage()/actionRingBuffer.getMedian(); } Vector2d Simulation::calculateOneAction(const Action& action) const { // STEP 1: predict the action outcome const Vector2d& ballRelativePreview = getBallModel().positionPreview; DEBUG_REQUEST("Simulation:draw_ball", FIELD_DRAWING_CONTEXT; PEN("FF0000", 1); Vector2d ball = getRobotPose() * getBallModel().positionPreview; CIRCLE( ball.x, ball.y, 50); ); Vector2d result = action.predict(ballRelativePreview, 0.1, Math::fromDegrees(5)); DEBUG_REQUEST("Simulation:ActionTarget", FIELD_DRAWING_CONTEXT; PEN("0000FF", 1); Vector2d ball = getRobotPose() * result; CIRCLE( ball.x, ball.y, 50); ); // STEP 2: calculate the goal line GoalModel::Goal oppGoalModel = getSelfLocGoalModel().getOppGoal(getCompassDirection(), getFieldInfo()); Vector2d oppGoalPostLeftPreview = getMotionStatus().plannedMotion.hip / oppGoalModel.leftPost; Vector2d oppGoalPostRightPreview = getMotionStatus().plannedMotion.hip / oppGoalModel.rightPost; //the endpoints of our line are a shortened version of the goal line Vector2d leftEndpoint = oppGoalPostLeftPreview + Vector2d(getFieldInfo().goalpostRadius + getFieldInfo().ballRadius,0); Vector2d rightEndpoint = oppGoalPostRightPreview - Vector2d(getFieldInfo().goalpostRadius + getFieldInfo().ballRadius,0); // this is the goalline we are shooting for Math::LineSegment goalLinePreview(leftEndpoint, rightEndpoint); // STEP 3: estimate external factors (shooting a goal, ball moved by referee) //Math::LineSegment shootLine(ballRelativePreview, outsideField(lonely_action.target));//hmm Math::LineSegment shootLine(ballRelativePreview, result); Vector2d resultingBallPosition; if(shootLine.intersect(goalLinePreview) && goalLinePreview.intersect(shootLine)) { resultingBallPosition = Vector2d(getFieldInfo().xPosOpponentGoal+200, 0.0); } else { resultingBallPosition = outsideField(getRobotPose() * result); } return resultingBallPosition; } //correction of distance in percentage, angle in degrees Vector2d Simulation::Action::predict(const Vector2d& ball, double distance_variance, double angle_variance) const { double random_length = 2.0*Math::random()-1.0; double random_angle = 2.0*Math::random()-1.0; Vector2d noisyAction = actionVector + actionVector*(distance_variance*random_length); noisyAction.rotate(angle_variance*random_angle); return ball + noisyAction; } //calcualte according to the rules, without the roboter position, the ball position //if it goes outside the field Vector2d Simulation::outsideField(const Vector2d& globalPoint) const { Vector2d point = globalPoint; //Schusslinie Math::LineSegment shootLine(getBallModel().positionPreview, globalPoint); if(getFieldInfo().fieldRect.inside(point)){ return point; } else //Nach Prioritten geordnet - zuerst die Regeln mit dem mglichst schlimmsten Resultat { //Opponent Groundline Out - Ball einen Meter hinter Roboter mind ansto hhe. jeweils seite wo ins ausgeht if(point.x > getFieldInfo().xPosOpponentGroundline) { Vector2d OppOutPoint = getFieldInfo().oppLineSegment.point(getFieldInfo().oppLineSegment.intersection(shootLine)); if(OppOutPoint.y < 0) { return Vector2d(0, getFieldInfo().yThrowInLineRight);//range check } else { return Vector2d(0, getFieldInfo().yThrowInLineLeft); } } //Own Groundline out - an der seite wo raus geht else if(point.x < getFieldInfo().xPosOwnGroundline) { Vector2d OwnOutPoint = getFieldInfo().ownLineSegment.point(getFieldInfo().ownLineSegment.intersection(shootLine)); if(OwnOutPoint.y < 0) { return Vector2d(getFieldInfo().xThrowInLineOwn, getFieldInfo().yThrowInLineRight);//range check } else { return Vector2d(getFieldInfo().xThrowInLineOwn, getFieldInfo().yThrowInLineLeft); } } //an der linken Seite raus -> ein meter hinter roboter oder wo ins ausgeht ein meter hinter else if(point.y > getFieldInfo().yPosLeftSideline ) { Vector2d leftOutPoint = getFieldInfo().leftLineSegment.point(getFieldInfo().leftLineSegment.intersection(shootLine)); point.x = min(leftOutPoint.x,getRobotPose().translation.x); if(point.x-1000 < getFieldInfo().xThrowInLineOwn) { point.x = getFieldInfo().xThrowInLineOwn; } else { point.x -= 1000; } return Vector2d(point.x, getFieldInfo().yThrowInLineLeft); //range check } //an der rechten Seite raus -> ein meter hinter roboter oder wo ins ausgeht ein meter hinter else //(point.y < getFieldInfo().yPosRightSideline) { Vector2d rightOutPoint = getFieldInfo().rightLineSegment.point(getFieldInfo().rightLineSegment.intersection(shootLine)); point.x = min(rightOutPoint.x,getRobotPose().translation.x); if(point.x-1000 < getFieldInfo().xThrowInLineOwn) { point.x = getFieldInfo().xThrowInLineOwn; } else { point.x -= 1000; } return Vector2d(point.x, getFieldInfo().yThrowInLineRight);//range check } } } double Simulation::evaluateAction(const Vector2d& a) const{ return (Vector2d(getFieldInfo().xPosOpponentGoal+200, 0.0)-a).abs(); } <commit_msg>Draw best action<commit_after>/** * @file Simulation.cpp * @author <a href="mailto:[email protected]">Benjamin Schlotter</a> * Implementation of class Simulation */ #include "Simulation.h" using namespace naoth; using namespace std; Simulation::Simulation() { DEBUG_REQUEST_REGISTER("Simulation:draw_one_action_point:global","draw_one_action_point:global", true); DEBUG_REQUEST_REGISTER("Simulation:draw_ball","draw_ball", true); DEBUG_REQUEST_REGISTER("Simulation:ActionTarget","ActionTarget", true); DEBUG_REQUEST_REGISTER("Simulation:draw_best_action","best action",false); //actionRingBuffer.resize(ActionModel::numOfActions); //calculate the actions action_local.reserve(ActionNew::numOfActions); action_local.push_back(Action(ActionNew::none, Vector2d())); action_local.push_back(Action(ActionNew::kick_long, Vector2d(theParameters.action_long_kick_distance, 0))); // long action_local.push_back(Action(ActionNew::kick_short, Vector2d(theParameters.action_short_kick_distance, 0))); // short action_local.push_back(Action(ActionNew::sidekick_right, Vector2d(0, -theParameters.action_sidekick_distance))); // right action_local.push_back(Action(ActionNew::sidekick_left, Vector2d(0, theParameters.action_sidekick_distance))); // left actionRingBuffer.resize(ActionNew::numOfActions); } Simulation::~Simulation(){} void Simulation::execute() { if(!getBallModel().valid || getFrameInfo().getTimeInSeconds() >= getBallModel().frameInfoWhenBallWasSeen.getTimeInSeconds()+1) { return; } else { int best_action = 0; for(size_t i=0; i<actionRingBuffer.size(); i++) { simulate(action_local[i], actionRingBuffer[i]); if(action_local[i].potential < action_local[best_action].potential) { best_action = i; } } getActionNew().myAction = action_local[best_action].id(); DEBUG_REQUEST("Simulation:draw_best_action", FIELD_DRAWING_CONTEXT; PEN("FFAA00", 4); Vector2d actionGlobal = action_local[best_action].target; CIRCLE(actionGlobal.x, actionGlobal.y, 50); ); } }//end execute void Simulation::simulate(Simulation::Action& action, RingBufferWithSum<double, 30>& actionRingBuffer)const { Vector2d ballPositionResult = calculateOneAction(action); DEBUG_REQUEST("Simulation:draw_one_action_point:global", FIELD_DRAWING_CONTEXT; PEN("000000", 1); CIRCLE( ballPositionResult.x, ballPositionResult.y, 50); ); double v = evaluateAction(ballPositionResult); actionRingBuffer.add(v); // HACK action.potential = actionRingBuffer.getAverage(); action.target = ballPositionResult; //if there is big gap between our values(average and median), we know it is not good //action.goodness = actionRingBuffer.getAverage()/actionRingBuffer.getMedian(); } Vector2d Simulation::calculateOneAction(const Action& action) const { // STEP 1: predict the action outcome const Vector2d& ballRelativePreview = getBallModel().positionPreview; DEBUG_REQUEST("Simulation:draw_ball", FIELD_DRAWING_CONTEXT; PEN("FF0000", 1); Vector2d ball = getRobotPose() * getBallModel().positionPreview; CIRCLE( ball.x, ball.y, 50); ); Vector2d result = action.predict(ballRelativePreview, 0.1, Math::fromDegrees(5)); DEBUG_REQUEST("Simulation:ActionTarget", FIELD_DRAWING_CONTEXT; PEN("0000FF", 1); Vector2d ball = getRobotPose() * result; CIRCLE( ball.x, ball.y, 50); ); // STEP 2: calculate the goal line GoalModel::Goal oppGoalModel = getSelfLocGoalModel().getOppGoal(getCompassDirection(), getFieldInfo()); Vector2d oppGoalPostLeftPreview = getMotionStatus().plannedMotion.hip / oppGoalModel.leftPost; Vector2d oppGoalPostRightPreview = getMotionStatus().plannedMotion.hip / oppGoalModel.rightPost; //the endpoints of our line are a shortened version of the goal line Vector2d leftEndpoint = oppGoalPostLeftPreview + Vector2d(getFieldInfo().goalpostRadius + getFieldInfo().ballRadius,0); Vector2d rightEndpoint = oppGoalPostRightPreview - Vector2d(getFieldInfo().goalpostRadius + getFieldInfo().ballRadius,0); // this is the goalline we are shooting for Math::LineSegment goalLinePreview(leftEndpoint, rightEndpoint); // STEP 3: estimate external factors (shooting a goal, ball moved by referee) //Math::LineSegment shootLine(ballRelativePreview, outsideField(lonely_action.target));//hmm Math::LineSegment shootLine(ballRelativePreview, result); Vector2d resultingBallPosition; if(shootLine.intersect(goalLinePreview) && goalLinePreview.intersect(shootLine)) { resultingBallPosition = Vector2d(getFieldInfo().xPosOpponentGoal+200, 0.0); } else { resultingBallPosition = outsideField(getRobotPose() * result); } return resultingBallPosition; } //correction of distance in percentage, angle in degrees Vector2d Simulation::Action::predict(const Vector2d& ball, double distance_variance, double angle_variance) const { double random_length = 2.0*Math::random()-1.0; double random_angle = 2.0*Math::random()-1.0; Vector2d noisyAction = actionVector + actionVector*(distance_variance*random_length); noisyAction.rotate(angle_variance*random_angle); return ball + noisyAction; } //calcualte according to the rules, without the roboter position, the ball position //if it goes outside the field Vector2d Simulation::outsideField(const Vector2d& globalPoint) const { Vector2d point = globalPoint; //Schusslinie Math::LineSegment shootLine(getBallModel().positionPreview, globalPoint); if(getFieldInfo().fieldRect.inside(point)){ return point; } else //Nach Prioritten geordnet - zuerst die Regeln mit dem mglichst schlimmsten Resultat { //Opponent Groundline Out - Ball einen Meter hinter Roboter mind ansto hhe. jeweils seite wo ins ausgeht if(point.x > getFieldInfo().xPosOpponentGroundline) { Vector2d OppOutPoint = getFieldInfo().oppLineSegment.point(getFieldInfo().oppLineSegment.intersection(shootLine)); if(OppOutPoint.y < 0) { return Vector2d(0, getFieldInfo().yThrowInLineRight);//range check } else { return Vector2d(0, getFieldInfo().yThrowInLineLeft); } } //Own Groundline out - an der seite wo raus geht else if(point.x < getFieldInfo().xPosOwnGroundline) { Vector2d OwnOutPoint = getFieldInfo().ownLineSegment.point(getFieldInfo().ownLineSegment.intersection(shootLine)); if(OwnOutPoint.y < 0) { return Vector2d(getFieldInfo().xThrowInLineOwn, getFieldInfo().yThrowInLineRight);//range check } else { return Vector2d(getFieldInfo().xThrowInLineOwn, getFieldInfo().yThrowInLineLeft); } } //an der linken Seite raus -> ein meter hinter roboter oder wo ins ausgeht ein meter hinter else if(point.y > getFieldInfo().yPosLeftSideline ) { Vector2d leftOutPoint = getFieldInfo().leftLineSegment.point(getFieldInfo().leftLineSegment.intersection(shootLine)); point.x = min(leftOutPoint.x,getRobotPose().translation.x); if(point.x-1000 < getFieldInfo().xThrowInLineOwn) { point.x = getFieldInfo().xThrowInLineOwn; } else { point.x -= 1000; } return Vector2d(point.x, getFieldInfo().yThrowInLineLeft); //range check } //an der rechten Seite raus -> ein meter hinter roboter oder wo ins ausgeht ein meter hinter else //(point.y < getFieldInfo().yPosRightSideline) { Vector2d rightOutPoint = getFieldInfo().rightLineSegment.point(getFieldInfo().rightLineSegment.intersection(shootLine)); point.x = min(rightOutPoint.x,getRobotPose().translation.x); if(point.x-1000 < getFieldInfo().xThrowInLineOwn) { point.x = getFieldInfo().xThrowInLineOwn; } else { point.x -= 1000; } return Vector2d(point.x, getFieldInfo().yThrowInLineRight);//range check } } } double Simulation::evaluateAction(const Vector2d& a) const{ return (Vector2d(getFieldInfo().xPosOpponentGoal+200, 0.0)-a).abs(); } <|endoftext|>
<commit_before> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Test.h" #include "SkPath.h" #include "SkLineClipper.h" #include "SkEdgeClipper.h" static void test_edgeclipper(skiatest::Reporter* reporter) { SkEdgeClipper clipper; const SkPoint pts[] = { { 3.0995476e+010, 42.929779 }, { -3.0995163e+010, 51.050385 }, { -3.0995157e+010, 51.050392 }, { -3.0995134e+010, 51.050400 }, }; const SkRect clip = { 0, 0, 300, 200 }; // this should not assert, even though our choppers do a poor numerical // job when computing their t values. // http://code.google.com/p/skia/issues/detail?id=444 clipper.clipCubic(pts, clip); } static void test_intersectline(skiatest::Reporter* reporter) { static const SkScalar L = 0; static const SkScalar T = 0; static const SkScalar R = SkIntToScalar(100); static const SkScalar B = SkIntToScalar(100); static const SkScalar CX = SkScalarHalf(L + R); static const SkScalar CY = SkScalarHalf(T + B); static const SkRect gR = { L, T, R, B }; size_t i; SkPoint dst[2]; static const SkPoint gEmpty[] = { // sides { L, CY }, { L - 10, CY }, { R, CY }, { R + 10, CY }, { CX, T }, { CX, T - 10 }, { CX, B }, { CX, B + 10 }, // corners { L, T }, { L - 10, T - 10 }, { L, B }, { L - 10, B + 10 }, { R, T }, { R + 10, T - 10 }, { R, B }, { R + 10, B + 10 }, }; for (i = 0; i < SK_ARRAY_COUNT(gEmpty); i += 2) { bool valid = SkLineClipper::IntersectLine(&gEmpty[i], gR, dst); if (valid) { SkDebugf("----- [%d] %g %g -> %g %g\n", i/2, dst[0].fX, dst[0].fY, dst[1].fX, dst[1].fY); } REPORTER_ASSERT(reporter, !valid); } static const SkPoint gFull[] = { // diagonals, chords { L, T }, { R, B }, { L, B }, { R, T }, { CX, T }, { CX, B }, { L, CY }, { R, CY }, { CX, T }, { R, CY }, { CX, T }, { L, CY }, { L, CY }, { CX, B }, { R, CY }, { CX, B }, // edges { L, T }, { L, B }, { R, T }, { R, B }, { L, T }, { R, T }, { L, B }, { R, B }, }; for (i = 0; i < SK_ARRAY_COUNT(gFull); i += 2) { bool valid = SkLineClipper::IntersectLine(&gFull[i], gR, dst); if (!valid || memcmp(&gFull[i], dst, sizeof(dst))) { SkDebugf("++++ [%d] %g %g -> %g %g\n", i/2, dst[0].fX, dst[0].fY, dst[1].fX, dst[1].fY); } REPORTER_ASSERT(reporter, valid && !memcmp(&gFull[i], dst, sizeof(dst))); } static const SkPoint gPartial[] = { { L - 10, CY }, { CX, CY }, { L, CY }, { CX, CY }, { CX, T - 10 }, { CX, CY }, { CX, T }, { CX, CY }, { R + 10, CY }, { CX, CY }, { R, CY }, { CX, CY }, { CX, B + 10 }, { CX, CY }, { CX, B }, { CX, CY }, // extended edges { L, T - 10 }, { L, B + 10 }, { L, T }, { L, B }, { R, T - 10 }, { R, B + 10 }, { R, T }, { R, B }, { L - 10, T }, { R + 10, T }, { L, T }, { R, T }, { L - 10, B }, { R + 10, B }, { L, B }, { R, B }, }; for (i = 0; i < SK_ARRAY_COUNT(gPartial); i += 4) { bool valid = SkLineClipper::IntersectLine(&gPartial[i], gR, dst); if (!valid || memcmp(&gPartial[i+2], dst, sizeof(dst))) { SkDebugf("++++ [%d] %g %g -> %g %g\n", i/2, dst[0].fX, dst[0].fY, dst[1].fX, dst[1].fY); } REPORTER_ASSERT(reporter, valid && !memcmp(&gPartial[i+2], dst, sizeof(dst))); } } void TestClipper(skiatest::Reporter* reporter) { test_intersectline(reporter); test_edgeclipper(reporter); } #include "TestClassDef.h" DEFINE_TESTCLASS("Clipper", TestClipperClass, TestClipper) <commit_msg>Fix SkScalar values in ClipperTest.cpp; these were breaking one Windows buildbot<commit_after> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Test.h" #include "SkPath.h" #include "SkLineClipper.h" #include "SkEdgeClipper.h" static void test_edgeclipper(skiatest::Reporter* reporter) { SkEdgeClipper clipper; const SkPoint pts[] = { { SkFloatToScalar(3.0995476e+010), SkFloatToScalar(42.929779) }, { SkFloatToScalar(-3.0995163e+010), SkFloatToScalar(51.050385) }, { SkFloatToScalar(-3.0995157e+010), SkFloatToScalar(51.050392) }, { SkFloatToScalar(-3.0995134e+010), SkFloatToScalar(51.050400) }, }; const SkRect clip = { 0, 0, SkIntToScalar(300), SkIntToScalar(200) }; // this should not assert, even though our choppers do a poor numerical // job when computing their t values. // http://code.google.com/p/skia/issues/detail?id=444 clipper.clipCubic(pts, clip); } static void test_intersectline(skiatest::Reporter* reporter) { static const SkScalar L = 0; static const SkScalar T = 0; static const SkScalar R = SkIntToScalar(100); static const SkScalar B = SkIntToScalar(100); static const SkScalar CX = SkScalarHalf(L + R); static const SkScalar CY = SkScalarHalf(T + B); static const SkRect gR = { L, T, R, B }; size_t i; SkPoint dst[2]; static const SkPoint gEmpty[] = { // sides { L, CY }, { L - 10, CY }, { R, CY }, { R + 10, CY }, { CX, T }, { CX, T - 10 }, { CX, B }, { CX, B + 10 }, // corners { L, T }, { L - 10, T - 10 }, { L, B }, { L - 10, B + 10 }, { R, T }, { R + 10, T - 10 }, { R, B }, { R + 10, B + 10 }, }; for (i = 0; i < SK_ARRAY_COUNT(gEmpty); i += 2) { bool valid = SkLineClipper::IntersectLine(&gEmpty[i], gR, dst); if (valid) { SkDebugf("----- [%d] %g %g -> %g %g\n", i/2, dst[0].fX, dst[0].fY, dst[1].fX, dst[1].fY); } REPORTER_ASSERT(reporter, !valid); } static const SkPoint gFull[] = { // diagonals, chords { L, T }, { R, B }, { L, B }, { R, T }, { CX, T }, { CX, B }, { L, CY }, { R, CY }, { CX, T }, { R, CY }, { CX, T }, { L, CY }, { L, CY }, { CX, B }, { R, CY }, { CX, B }, // edges { L, T }, { L, B }, { R, T }, { R, B }, { L, T }, { R, T }, { L, B }, { R, B }, }; for (i = 0; i < SK_ARRAY_COUNT(gFull); i += 2) { bool valid = SkLineClipper::IntersectLine(&gFull[i], gR, dst); if (!valid || memcmp(&gFull[i], dst, sizeof(dst))) { SkDebugf("++++ [%d] %g %g -> %g %g\n", i/2, dst[0].fX, dst[0].fY, dst[1].fX, dst[1].fY); } REPORTER_ASSERT(reporter, valid && !memcmp(&gFull[i], dst, sizeof(dst))); } static const SkPoint gPartial[] = { { L - 10, CY }, { CX, CY }, { L, CY }, { CX, CY }, { CX, T - 10 }, { CX, CY }, { CX, T }, { CX, CY }, { R + 10, CY }, { CX, CY }, { R, CY }, { CX, CY }, { CX, B + 10 }, { CX, CY }, { CX, B }, { CX, CY }, // extended edges { L, T - 10 }, { L, B + 10 }, { L, T }, { L, B }, { R, T - 10 }, { R, B + 10 }, { R, T }, { R, B }, { L - 10, T }, { R + 10, T }, { L, T }, { R, T }, { L - 10, B }, { R + 10, B }, { L, B }, { R, B }, }; for (i = 0; i < SK_ARRAY_COUNT(gPartial); i += 4) { bool valid = SkLineClipper::IntersectLine(&gPartial[i], gR, dst); if (!valid || memcmp(&gPartial[i+2], dst, sizeof(dst))) { SkDebugf("++++ [%d] %g %g -> %g %g\n", i/2, dst[0].fX, dst[0].fY, dst[1].fX, dst[1].fY); } REPORTER_ASSERT(reporter, valid && !memcmp(&gPartial[i+2], dst, sizeof(dst))); } } void TestClipper(skiatest::Reporter* reporter) { test_intersectline(reporter); test_edgeclipper(reporter); } #include "TestClassDef.h" DEFINE_TESTCLASS("Clipper", TestClipperClass, TestClipper) <|endoftext|>
<commit_before>/*~ * Copyright (C) 2013 - 2016 George Makrydakis <[email protected]> * * This file is part of 'clause', a highly generic C++ meta-programming library, * subject to the terms and conditions of the Mozilla Public License v 2.0. If * a copy of the MPLv2 license text was not distributed with this file, you can * obtain it at: http://mozilla.org/MPL/2.0/. * * The 'clause' library is an experimental library in active development with * a source code repository at: https://github.com/irrequietus/clause.git and * issue tracker at https://github.com/irrequietus/clause/issues. * */ #include <clause/ample/test.hh> #include <clause/ample/charseq.hh> #include <clause/ample/ensure.hh> #include <clause/ppmpf/algorithms/map.hh> namespace clause { namespace ample { namespace test { // The #define CLAUSE_OPRTS_() \ add, sub, mul ,div, mod, size_of, base_of, factor_of, push_back \ , push_front, pop_back, pop_front, clear, is_empty, leq, geq, neq \ , equal, less, greater, head_of, tail_of, null_of, join, atpos \ , assign_atpos, insert_at, split_at, circular_shiftl, circular_shiftr \ , shiftl, shiftr, prev, next, apply #define CLAUSE_ENSURE_PAIRS(x) \ PPMPF_CAT(ensure1_,x),PPMPF_CAT(ensure2_,x) #define PPMPF_VXPP_SET0(a) \ ()(template<typename...> struct PPMPF_CAT(oprt_,a) {};)\ (CLAUSE_OPRTS_()) #define PPMPF_VXPP_SET1(a) \ ()(struct PPMPF_CAT(ensure1_,a) : vldt_types< \ typename clause::ample::ensure<test1>::template PPMPF_CAT(oprt_,a)<>\ , typename test1::template PPMPF_CAT(oprt_,a)<> > { \ ample_vldt_(PPMPF_QUOTE(ensure for ::template PPMPF_CAT(oprt_,a) 1)) \ };)(CLAUSE_OPRTS_()) #define PPMPF_VXPP_SET2(a) \ ()(struct PPMPF_CAT(ensure2_,a) : vldt_types< \ typename clause::ample::ensure<test2>::template PPMPF_CAT(oprt_,a)<>\ , typename clause::ample::failure<test2> > { \ ample_vldt_(PPMPF_QUOTE(ensure for ::template PPMPF_CAT(oprt_,a) 2)) \ };)(CLAUSE_OPRTS_()) struct test1 { /* Generate the necessary code for all tokens in CLAUSE_OPRTS_() */ #include PPMPF_VXPP_FMAPOF(0) }; struct test2 { /* This must be empty in order to check the sfinae behavior of 'ensure' */ }; /* Generate all the code necessary for the tests! */ #define PPMPF_VXPP_SETS() (1,2) #include PPMPF_VXPP_FMAPSETS() struct check_ensure : check< true /* Code generation through PPMPF_MAP below: */ , check_all<PPMPF_EXCISE(PPMPF_MAP( (CLAUSE_ENSURE_PAIRS,(__0)(_1)) , PPMPF_UTUP(CLAUSE_OPRTS_())))>> {}; } /* test */ } /* ample */ } /* clause */ int main() { return AMPLE_TEST_RUN( check_ensure , "testing clause::ample::ensure template" ); } <commit_msg>More explanatory comments in the ensure test/example using VXPP.<commit_after>/*~ * Copyright (C) 2013 - 2016 George Makrydakis <[email protected]> * * This file is part of 'clause', a highly generic C++ meta-programming library, * subject to the terms and conditions of the Mozilla Public License v 2.0. If * a copy of the MPLv2 license text was not distributed with this file, you can * obtain it at: http://mozilla.org/MPL/2.0/. * * The 'clause' library is an experimental library in active development with * a source code repository at: https://github.com/irrequietus/clause.git and * issue tracker at https://github.com/irrequietus/clause/issues. * */ #include <clause/ample/test.hh> #include <clause/ample/charseq.hh> #include <clause/ample/ensure.hh> #include <clause/ppmpf/algorithms/map.hh> namespace clause { namespace ample { namespace test { // Let's add all the necessary functions for checking related oprt handlers in // an ensure template candidate check. #define CLAUSE_OPRTS_() \ add, sub, mul ,div, mod, size_of, base_of, factor_of, push_back \ , push_front, pop_back, pop_front, clear, is_empty, leq, geq, neq \ , equal, less, greater, head_of, tail_of, null_of, join, atpos \ , assign_atpos, insert_at, split_at, circular_shiftl, circular_shiftr \ , shiftl, shiftr, prev, next, apply // Pairs created between two different versions of oprt handler checks created. #define CLAUSE_ENSURE_PAIRS(x) \ PPMPF_CAT(ensure1_,x),PPMPF_CAT(ensure2_,x) // NOTE: The first set expands vertically handler generation, #define PPMPF_VXPP_SET0(a) \ ()(template<typename...> struct PPMPF_CAT(oprt_,a) {};)\ (CLAUSE_OPRTS_()) // NOTE: The second set expands vertically creating various validation tests for // the first ensure (the ensure1 check) for the success of the tests in // the generated code; note that we embed "test1" directly here, we will // use that identifier later on, see below. This is done for convenience. #define PPMPF_VXPP_SET1(a) \ ()(struct PPMPF_CAT(ensure1_,a) : vldt_types< \ typename clause::ample::ensure<test1>::template PPMPF_CAT(oprt_,a)<>\ , typename test1::template PPMPF_CAT(oprt_,a)<> > { \ ample_vldt_(PPMPF_QUOTE(ensure for ::template PPMPF_CAT(oprt_,a) 1)) \ };)(CLAUSE_OPRTS_()) // NOTE: The third set expands vertical failure tests, see what happened with // set defined previously (SET1). Same reason for test2 identifier use // as test1: convenience, wouldn't want to add extra magic to an example. #define PPMPF_VXPP_SET2(a) \ ()(struct PPMPF_CAT(ensure2_,a) : vldt_types< \ typename clause::ample::ensure<test2>::template PPMPF_CAT(oprt_,a)<>\ , typename clause::ample::failure<test2> > { \ ample_vldt_(PPMPF_QUOTE(ensure for ::template PPMPF_CAT(oprt_,a) 2)) \ };)(CLAUSE_OPRTS_()) // This struct will contain all the successful oprt handlers inside, so the // expansion has to occur internally; this is why PPMPF_VXPP_FMAPOF(0) is // invoked to expand. struct test1 { /* Generate the necessary code for all tokens in CLAUSE_OPRTS_() */ #include PPMPF_VXPP_FMAPOF(0) }; // This struct will NOT contain all the successful oprt handlers inside, so the // expansion has to occur internally; this is why there is no expansion of any // SETs through PPMPF_VXPP_FMAPOF or PPMPF_VXPP_FMAPSETS struct test2 { /* This must be empty in order to check the sfinae behavior of 'ensure' */ }; /* Generate all the code necessary for the tests! */ #define PPMPF_VXPP_SETS() (1,2) #include PPMPF_VXPP_FMAPSETS() struct check_ensure : check< true /* Code generation through PPMPF_MAP below: */ , check_all<PPMPF_EXCISE(PPMPF_MAP( (CLAUSE_ENSURE_PAIRS,(__0)(_1)) , PPMPF_UTUP(CLAUSE_OPRTS_())))>> {}; } /* test */ } /* ample */ } /* clause */ int main() { return AMPLE_TEST_RUN( check_ensure , "testing clause::ample::ensure template" ); } <|endoftext|>
<commit_before>/* * This content is released under the MIT License as specified in https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE */ #include "includes.h" using namespace spdlog::details; static const std::string target_filename = "logs/file_helper_test.txt"; static void write_with_helper(file_helper &helper, size_t howmany) { log_msg msg; msg.formatted << std::string(howmany, '1'); helper.write(msg); helper.flush(); } TEST_CASE("file_helper_filename", "[file_helper::filename()]]") { prepare_logdir(); file_helper helper; helper.open(target_filename); REQUIRE(helper.filename() == target_filename); } TEST_CASE("file_helper_size", "[file_helper::size()]]") { prepare_logdir(); size_t expected_size = 123; { file_helper helper; helper.open(target_filename); write_with_helper(helper, expected_size); REQUIRE(static_cast<size_t>(helper.size()) == expected_size); } REQUIRE(get_filesize(target_filename) == expected_size); } TEST_CASE("file_helper_exists", "[file_helper::file_exists()]]") { prepare_logdir(); REQUIRE(!file_helper::file_exists(target_filename)); file_helper helper; helper.open(target_filename); REQUIRE(file_helper::file_exists(target_filename)); } TEST_CASE("file_helper_reopen", "[file_helper::reopen()]]") { prepare_logdir(); file_helper helper; helper.open(target_filename); write_with_helper(helper, 12); REQUIRE(helper.size() == 12); helper.reopen(true); REQUIRE(helper.size() == 0); } TEST_CASE("file_helper_reopen2", "[file_helper::reopen(false)]]") { prepare_logdir(); size_t expected_size = 14; file_helper helper; helper.open(target_filename); write_with_helper(helper, expected_size); REQUIRE(helper.size() == expected_size); helper.reopen(false); REQUIRE(helper.size() == expected_size); } static void test_split_ext(spdlog::filename_t& filename, spdlog::filename_t & expected_base, spdlog::filename_t & expected_ext) { #ifdef _WIN32 // replace folder sep std::replace(filename.begin(), filename.end(), '/', '\\'); std::replace(expected_base.begin(), expected_base.end(), '/', '\\'); #endif spdlog::filename_t basename, ext; std::tie(basename, ext) = file_helper::split_by_extenstion(filename); REQUIRE(basename == expected_base); REQUIRE(ext == expected_ext); } TEST_CASE("file_helper_split_by_extenstion", "[file_helper::split_by_extenstion()]]") { using file_t = spdlog::filename_t; test_split_ext(file_t("mylog.txt"), file_t("mylog"), file_t(".txt")); test_split_ext(file_t(".mylog.txt"), file_t(".mylog"), file_t(".txt")); test_split_ext(file_t(".mylog"), file_t(".mylog"), file_t("")); test_split_ext(file_t("/aaa/bb.d/mylog"), file_t("/aaa/bb.d/mylog"), file_t("")); test_split_ext(file_t("/aaa/bb.d/mylog.txt"), file_t("/aaa/bb.d/mylog"), file_t(".txt")); test_split_ext(file_t("aaa/bbb/ccc/mylog.txt"), file_t("aaa/bbb/ccc/mylog"), file_t(".txt")); test_split_ext(file_t("aaa/bbb/ccc/mylog."), file_t("aaa/bbb/ccc/mylog."), file_t("")); test_split_ext(file_t("aaa/bbb/ccc/.mylog.txt"), file_t("aaa/bbb/ccc/.mylog"), file_t(".txt")); test_split_ext(file_t("/aaa/bbb/ccc/mylog.txt"), file_t("/aaa/bbb/ccc/mylog"), file_t(".txt")); test_split_ext(file_t("/aaa/bbb/ccc/.mylog"), file_t("/aaa/bbb/ccc/.mylog"), file_t("")); test_split_ext(file_t("../mylog.txt"), file_t("../mylog"), file_t(".txt")); test_split_ext(file_t(".././mylog.txt"), file_t(".././mylog"), file_t(".txt")); test_split_ext(file_t(".././mylog.txt/xxx"), file_t(".././mylog.txt/xxx"), file_t("")); test_split_ext(file_t("/mylog.txt"), file_t("/mylog"), file_t(".txt")); test_split_ext(file_t("//mylog.txt"), file_t("//mylog"), file_t(".txt")); } <commit_msg>Fixed file_helper::split_by_extenstion and added more tests for it<commit_after>/* * This content is released under the MIT License as specified in https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE */ #include "includes.h" using namespace spdlog::details; static const std::string target_filename = "logs/file_helper_test.txt"; static void write_with_helper(file_helper &helper, size_t howmany) { log_msg msg; msg.formatted << std::string(howmany, '1'); helper.write(msg); helper.flush(); } TEST_CASE("file_helper_filename", "[file_helper::filename()]]") { prepare_logdir(); file_helper helper; helper.open(target_filename); REQUIRE(helper.filename() == target_filename); } TEST_CASE("file_helper_size", "[file_helper::size()]]") { prepare_logdir(); size_t expected_size = 123; { file_helper helper; helper.open(target_filename); write_with_helper(helper, expected_size); REQUIRE(static_cast<size_t>(helper.size()) == expected_size); } REQUIRE(get_filesize(target_filename) == expected_size); } TEST_CASE("file_helper_exists", "[file_helper::file_exists()]]") { prepare_logdir(); REQUIRE(!file_helper::file_exists(target_filename)); file_helper helper; helper.open(target_filename); REQUIRE(file_helper::file_exists(target_filename)); } TEST_CASE("file_helper_reopen", "[file_helper::reopen()]]") { prepare_logdir(); file_helper helper; helper.open(target_filename); write_with_helper(helper, 12); REQUIRE(helper.size() == 12); helper.reopen(true); REQUIRE(helper.size() == 0); } TEST_CASE("file_helper_reopen2", "[file_helper::reopen(false)]]") { prepare_logdir(); size_t expected_size = 14; file_helper helper; helper.open(target_filename); write_with_helper(helper, expected_size); REQUIRE(helper.size() == expected_size); helper.reopen(false); REQUIRE(helper.size() == expected_size); } static void test_split_ext(spdlog::filename_t& filename, spdlog::filename_t & expected_base, spdlog::filename_t & expected_ext) { #ifdef _WIN32 // replace folder sep std::replace(filename.begin(), filename.end(), '/', '\\'); std::replace(expected_base.begin(), expected_base.end(), '/', '\\'); #endif spdlog::filename_t basename, ext; std::tie(basename, ext) = file_helper::split_by_extenstion(filename); REQUIRE(basename == expected_base); REQUIRE(ext == expected_ext); } TEST_CASE("file_helper_split_by_extenstion", "[file_helper::split_by_extenstion()]]") { using file_t = spdlog::filename_t; test_split_ext(file_t("mylog.txt"), file_t("mylog"), file_t(".txt")); test_split_ext(file_t(".mylog.txt"), file_t(".mylog"), file_t(".txt")); test_split_ext(file_t(".mylog"), file_t(".mylog"), file_t("")); test_split_ext(file_t("/aaa/bb.d/mylog"), file_t("/aaa/bb.d/mylog"), file_t("")); test_split_ext(file_t("/aaa/bb.d/mylog.txt"), file_t("/aaa/bb.d/mylog"), file_t(".txt")); test_split_ext(file_t("aaa/bbb/ccc/mylog.txt"), file_t("aaa/bbb/ccc/mylog"), file_t(".txt")); test_split_ext(file_t("aaa/bbb/ccc/mylog."), file_t("aaa/bbb/ccc/mylog."), file_t("")); test_split_ext(file_t("aaa/bbb/ccc/.mylog.txt"), file_t("aaa/bbb/ccc/.mylog"), file_t(".txt")); test_split_ext(file_t("/aaa/bbb/ccc/mylog.txt"), file_t("/aaa/bbb/ccc/mylog"), file_t(".txt")); test_split_ext(file_t("/aaa/bbb/ccc/.mylog"), file_t("/aaa/bbb/ccc/.mylog"), file_t("")); test_split_ext(file_t("../mylog.txt"), file_t("../mylog"), file_t(".txt")); test_split_ext(file_t(".././mylog.txt"), file_t(".././mylog"), file_t(".txt")); test_split_ext(file_t(".././mylog.txt/xxx"), file_t(".././mylog.txt/xxx"), file_t("")); test_split_ext(file_t("/mylog.txt"), file_t("/mylog"), file_t(".txt")); test_split_ext(file_t("//mylog.txt"), file_t("//mylog"), file_t(".txt")); test_split_ext(file_t(""), file_t(""), file_t("")); test_split_ext(file_t("."), file_t("."), file_t("")); test_split_ext(file_t("..txt"), file_t("."), file_t(".txt")); } <|endoftext|>
<commit_before>#include "signal.hpp" #include "signal-forward.hpp" #include <iostream> #include <algorithm> #include <cassert> using namespace pac; struct Server { int even = 0; pac::signal<int(int)> sigadd; pac::signal<int(int)> sigsub; typename pac::signal<int(int)>::results_type Add( int in ) { return sigadd.emit( in ); } typename pac::signal<int(int)>::results_type Sub( int in ) { return sigsub.emit( in ); } }; struct Client { Server& server; connection con_add; connection con_sub; Client(Server& s) : server(s) { con_add = server.sigadd.connect( this, &Client::OnAdd); BARK; con_sub = server.sigsub.connect( this, &Client::OnSub); } int OnAdd( int in ) { return in * 2; } int OnSub( int in ) { return in - 2; } }; int another_add( int in ) { return in + 7; } int another_dec( int in ) { return in -7; } bool sigfwd_cb( double x, double y ) { std::cout << "Point @ " << x << "," << y << "\n"; return x > y; } int sigfwd2_cb( int x ) { std::cout << "Join me - join the Dark Side!\n"; return x + 111; } int main(int, char *[]) { Server s; Client *c = new Client{s}; auto r1 = s.Add( 5 ); // should be 5 * 2 == { 10 } assert( std::accumulate( r1.begin(), r1.end(), 0 ) == 10 ); { auto con = s.sigadd.connect( another_add ); auto r2 = s.Add( 5 ); // should be { 10, 12 } assert( std::accumulate( r2.begin(), r2.end(), 0 ) == 22 ); con.disconnect(); auto r3 = s.Add( 5 ); // should have lost above connection - return to { 10 } assert( std::accumulate( r3.begin(), r3.end(), 0 ) == 10 ); con = s.sigadd.connect( another_add ); auto r4 = s.Add( 5 ); // should be { 10, 12 } assert( std::accumulate( r4.begin(), r4.end(), 0 ) == 22 ); } { auto r1 = s.Add( 5 ); // should have lost above connection - return to { 10 } assert( std::accumulate( r1.begin(), r1.end(), 0 ) == 10 ); } auto r2 = s.Sub( 3 ); for ( auto r : r2 ) std::cout << r << "\n"; // std::function<void()> transformer = // [](){ }; // signal forwarding tests // signal_forward< pac::signal<int(int)>, void(bool) > fwd( s.sigadd, // transformer // ); // just for fun, made the transform functions 'hard' auto infunc = std::bind( []( int in ) { return in != 0; }, std::placeholders::_1 ); // std::function<int(bool)> outfunc = []( bool in ) { return in ? 6969 : -1069; }; auto outfunc = []( bool in ) { return in ? 6969 : -1069; }; signal_catcher< decltype( s.sigadd ), decltype(infunc), decltype(outfunc) > catcher( s.sigadd, infunc, outfunc ); for ( auto r : s.Add( 5 ) ) std::cout << "r = " << r << "\n"; // forwarded slot test std::function< std::tuple<double,double>(int) > inf = []( int in ) { BARK; return std::make_tuple( in * 3.14, in * 2 * 3.14 ); }; pac::callback<bool(double,double)> mycb = []( double in1, double in2 ) { return in1 > in2; }; // std::function< int( bool ) > outf = // []( bool out ) { BARK; int r = out ? 1001 : 2002; return r; }; pac::callback< int( bool ) > outf = []( bool out ) { BARK; int r = out ? 1001 : 2002; return r; }; pac::forwarded_slot< decltype( mycb ), decltype( inf ), decltype( outf ) > fslot( mycb, inf, outf ); std::cout << pac::apply( mycb, std::make_tuple( 3.141, 3.14 ) ) << "\n"; auto *castslot = dynamic_cast<pac::slot< callback<int( int )> > *>( &fslot ); assert( castslot ); std::cout << castslot->callback( 99 ) << "\n"; pac::signal< int( int ) > origsig; auto savemecon = origsig.connect_slot( *castslot ); for ( auto r : origsig.emit( 5 ) ) std::cout << "s = " << r << "\n"; pac::signal_forward< decltype( origsig ), bool( double,double ) > sigf( origsig, inf, outf ); // This works auto sigfcon2 = sigf.connect_slot( *castslot ); //But this is broken currently auto sigfcon = sigf.connect( sigfwd_cb ); origsig.emit( 5 ); { pac::connection_block block { sigfcon }; origsig.emit( 5 ); } sigfcon.disconnect(); sigfcon.disconnect(); sigfcon.disconnect(); sigfcon.disconnect(); sigfcon.disconnect(); sigfcon.disconnect(); sigfcon.disconnect(); origsig.emit( 5 ); pac::signal_forward< decltype(origsig ), int( int ) > sigf2( origsig ); auto sigf2con = sigf2.connect( sigfwd2_cb ); origsig.emit( 5 ); return 0; } <commit_msg>Fix mem leak in signals-test - use smart ptr<commit_after>#include "signal.hpp" #include "signal-forward.hpp" #include <iostream> #include <algorithm> #include <memory> #include <cassert> using namespace pac; struct Server { int even = 0; pac::signal<int(int)> sigadd; pac::signal<int(int)> sigsub; typename pac::signal<int(int)>::results_type Add( int in ) { return sigadd.emit( in ); } typename pac::signal<int(int)>::results_type Sub( int in ) { return sigsub.emit( in ); } }; struct Client { Server& server; connection con_add; connection con_sub; Client(Server& s) : server(s) { con_add = server.sigadd.connect( this, &Client::OnAdd); BARK; con_sub = server.sigsub.connect( this, &Client::OnSub); } int OnAdd( int in ) { return in * 2; } int OnSub( int in ) { return in - 2; } }; int another_add( int in ) { return in + 7; } int another_dec( int in ) { return in -7; } bool sigfwd_cb( double x, double y ) { std::cout << "Point @ " << x << "," << y << "\n"; return x > y; } int sigfwd2_cb( int x ) { std::cout << "Join me - join the Dark Side!\n"; return x + 111; } int main(int, char *[]) { Server s; auto c = std::make_shared<Client>( s ); auto r1 = s.Add( 5 ); // should be 5 * 2 == { 10 } assert( std::accumulate( r1.begin(), r1.end(), 0 ) == 10 ); { auto con = s.sigadd.connect( another_add ); auto r2 = s.Add( 5 ); // should be { 10, 12 } assert( std::accumulate( r2.begin(), r2.end(), 0 ) == 22 ); con.disconnect(); auto r3 = s.Add( 5 ); // should have lost above connection - return to { 10 } assert( std::accumulate( r3.begin(), r3.end(), 0 ) == 10 ); con = s.sigadd.connect( another_add ); auto r4 = s.Add( 5 ); // should be { 10, 12 } assert( std::accumulate( r4.begin(), r4.end(), 0 ) == 22 ); } { auto r1 = s.Add( 5 ); // should have lost above connection - return to { 10 } assert( std::accumulate( r1.begin(), r1.end(), 0 ) == 10 ); } auto r2 = s.Sub( 3 ); for ( auto r : r2 ) std::cout << r << "\n"; // std::function<void()> transformer = // [](){ }; // signal forwarding tests // signal_forward< pac::signal<int(int)>, void(bool) > fwd( s.sigadd, // transformer // ); // just for fun, made the transform functions 'hard' auto infunc = std::bind( []( int in ) { return in != 0; }, std::placeholders::_1 ); // std::function<int(bool)> outfunc = []( bool in ) { return in ? 6969 : -1069; }; auto outfunc = []( bool in ) { return in ? 6969 : -1069; }; signal_catcher< decltype( s.sigadd ), decltype(infunc), decltype(outfunc) > catcher( s.sigadd, infunc, outfunc ); for ( auto r : s.Add( 5 ) ) std::cout << "r = " << r << "\n"; // forwarded slot test std::function< std::tuple<double,double>(int) > inf = []( int in ) { BARK; return std::make_tuple( in * 3.14, in * 2 * 3.14 ); }; pac::callback<bool(double,double)> mycb = []( double in1, double in2 ) { return in1 > in2; }; // std::function< int( bool ) > outf = // []( bool out ) { BARK; int r = out ? 1001 : 2002; return r; }; pac::callback< int( bool ) > outf = []( bool out ) { BARK; int r = out ? 1001 : 2002; return r; }; pac::forwarded_slot< decltype( mycb ), decltype( inf ), decltype( outf ) > fslot( mycb, inf, outf ); std::cout << pac::apply( mycb, std::make_tuple( 3.141, 3.14 ) ) << "\n"; auto *castslot = dynamic_cast<pac::slot< callback<int( int )> > *>( &fslot ); assert( castslot ); std::cout << castslot->callback( 99 ) << "\n"; pac::signal< int( int ) > origsig; auto savemecon = origsig.connect_slot( *castslot ); for ( auto r : origsig.emit( 5 ) ) std::cout << "s = " << r << "\n"; pac::signal_forward< decltype( origsig ), bool( double,double ) > sigf( origsig, inf, outf ); // This works auto sigfcon2 = sigf.connect_slot( *castslot ); //But this is broken currently auto sigfcon = sigf.connect( sigfwd_cb ); origsig.emit( 5 ); { pac::connection_block block { sigfcon }; origsig.emit( 5 ); } sigfcon.disconnect(); sigfcon.disconnect(); sigfcon.disconnect(); sigfcon.disconnect(); sigfcon.disconnect(); sigfcon.disconnect(); sigfcon.disconnect(); origsig.emit( 5 ); pac::signal_forward< decltype(origsig ), int( int ) > sigf2( origsig ); auto sigf2con = sigf2.connect( sigfwd2_cb ); origsig.emit( 5 ); return 0; } <|endoftext|>
<commit_before>/* * DShow Native wrapper * Copyright (c) 2010 Gianluigi Tiesi <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "stdafx.h" class DSCodec { public: DSCodec::DSCodec(const char *filename, const GUID guid, BITMAPINFOHEADER *bih) : m_guid(guid), m_bih(bih), m_hDll(NULL), m_filter(NULL), m_iPin(NULL), m_oPin(NULL), m_iMem(NULL) { strncpy(m_fname, filename, MAX_PATH); } BOOL LoadLibrary(void) { return ((m_hDll = ::LoadLibrary(m_fname)) != NULL); } BOOL CreateFilter(void) { LPFNGETCLASSOBJECT pDllGetClassObject = (LPFNGETCLASSOBJECT) GetProcAddress(m_hDll, "DllGetClassObject"); if (!pDllGetClassObject) return FALSE; HRESULT res; IClassFactory *factory; res = pDllGetClassObject(m_guid, IID_IClassFactory, (LPVOID *) &factory); if (FAILED(res))return FALSE; IUnknown* object; res = factory->CreateInstance(NULL, IID_IUnknown, (LPVOID *) &object); factory->Release(); if (FAILED(res)) return FALSE; res = object->QueryInterface(IID_IBaseFilter, (LPVOID *) &m_filter); object->Release(); return (!FAILED(res)); } BOOL ReleaseFilter(void) { return m_filter->Release(); } BOOL SetInputType(void) { m_sOurType.majortype = MEDIATYPE_Video; m_sOurType.subtype = MEDIATYPE_Video; m_sOurType.subtype.Data1 = m_bih->biCompression; //m_sOurType.subtype.Data1 = m_bih->biCompression = 0x31637661; //avc1 m_sOurType.formattype = FORMAT_VideoInfo; m_sOurType.bFixedSizeSamples = FALSE; m_sOurType.bTemporalCompression = TRUE; m_sOurType.lSampleSize = 1; m_sOurType.pUnk = NULL; memset(&m_mp2vi, 0, sizeof(m_mp2vi)); m_mp2vi.hdr.rcSource.left = m_mp2vi.hdr.rcSource.top = 0; m_mp2vi.hdr.rcSource.right = m_bih->biWidth; m_mp2vi.hdr.rcSource.bottom = m_bih->biHeight; m_mp2vi.hdr.rcTarget = m_mp2vi.hdr.rcSource; m_mp2vi.hdr.dwBitRate = 0; m_mp2vi.hdr.AvgTimePerFrame = 0; m_mp2vi.hdr.dwPictAspectRatioX = m_bih->biWidth; m_mp2vi.hdr.dwPictAspectRatioY = m_bih->biHeight; memcpy(&m_mp2vi.hdr.bmiHeader, m_bih, sizeof(BITMAPINFOHEADER)); m_mp2vi.hdr.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); m_sOurType.formattype = FORMAT_MPEG2Video; m_sOurType.pbFormat = (BYTE *) &m_mp2vi; m_sOurType.cbFormat = sizeof(MPEG2VIDEOINFO); return TRUE; } BOOL EnumPins(void) { HRESULT res; IEnumPins *enumpins; res = m_filter->EnumPins(&enumpins); enumpins->Reset(); IPin *pin; PIN_INFO pInfo; while ((res = enumpins->Next(1, &pin, NULL)) == S_OK) { pin->QueryPinInfo(&pInfo); wprintf(L"Pin: %s - %s\n", pInfo.achName, (pInfo.dir == PINDIR_INPUT) ? L"Input" : L"Output"); if (pInfo.dir == PINDIR_INPUT) { m_iPin = pin; m_iPin->AddRef(); } else if (pInfo.dir == PINDIR_OUTPUT) { m_oPin = pin; m_oPin->AddRef(); } pin->Release(); } enumpins->Release(); res = m_iPin->QueryInterface(IID_IMemInputPin, (LPVOID *) &m_iMem); return TRUE; } BOOL CreateGraph(void) { this->EnumPins(); this->SetInputType(); HRESULT res; DebugBreak(); res = m_iPin->QueryAccept(&m_sOurType); //CBaseFilter s_filter = CBaseFilter(); return TRUE; } BOOL ShowPropertyPage(void) { if (!m_filter) return FALSE; HRESULT res; ISpecifyPropertyPages *pProp; if ((res = m_filter->QueryInterface(IID_ISpecifyPropertyPages, (LPVOID *) &pProp)) == S_OK) { // Get the filter's name and IUnknown pointer. FILTER_INFO FilterInfo; res = m_filter->QueryFilterInfo(&FilterInfo); IUnknown *pFilterUnk; res = m_filter->QueryInterface(IID_IUnknown, (LPVOID *) &pFilterUnk); CAUUID caGUID; pProp->GetPages(&caGUID); pProp->Release(); __try { res = OleCreatePropertyFrame( NULL, // Parent window 0, 0, // Reserved FilterInfo.achName, // Caption for the dialog box 1, // Number of objects (just the filter) &pFilterUnk, // Array of object pointers. caGUID.cElems, // Number of property pages caGUID.pElems, // Array of property page CLSIDs 0, // Locale identifier 0, NULL // Reserved ); } __except(EXCEPTION_EXECUTE_HANDLER) { } // Clean up. pFilterUnk->Release(); /* FIXME: it crashes (broken example on msdn?) */ //FilterInfo.pGraph->Release(); CoTaskMemFree(caGUID.pElems); } return (!FAILED(res)); } private: HMODULE m_hDll; GUID m_guid; char m_fname[MAX_PATH + 1]; BITMAPINFOHEADER *m_bih; IBaseFilter *m_filter; IPin *m_iPin; IPin *m_oPin; IMemInputPin *m_iMem; AM_MEDIA_TYPE m_sOurType, m_sDestType; MPEG2VIDEOINFO m_mp2vi; }; extern "C" DSCodec * WINAPI DSOpenCodec(const char *dll, const GUID guid, BITMAPINFOHEADER* bih) { DSCodec *codec = new DSCodec(dll, guid, bih); if (!codec->LoadLibrary()) return NULL; if (!codec->CreateFilter()) return NULL; if (!codec->CreateGraph()) return NULL; return codec; } extern "C" void WINAPI DSCloseCodec(DSCodec *codec) { codec->ReleaseFilter(); delete codec; } extern "C" BOOL WINAPI DSShowPropertyPage(DSCodec *codec) { return codec->ShowPropertyPage(); } BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID lpReserved) { switch (reason) { case DLL_PROCESS_ATTACH: { DisableThreadLibraryCalls(hModule); return (OleInitialize(NULL) == S_OK); } case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: return TRUE; case DLL_PROCESS_DETACH: break; } return TRUE; } <commit_msg>added a switch to set input type depending on compression type<commit_after>/* * DShow Native wrapper * Copyright (c) 2010 Gianluigi Tiesi <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "stdafx.h" class DSCodec { public: DSCodec::DSCodec(const char *filename, const GUID guid, BITMAPINFOHEADER *bih) : m_guid(guid), m_bih(bih), m_hDll(NULL), m_filter(NULL), m_iPin(NULL), m_oPin(NULL), m_iMem(NULL) { strncpy(m_fname, filename, MAX_PATH); } BOOL LoadLibrary(void) { return ((m_hDll = ::LoadLibrary(m_fname)) != NULL); } BOOL CreateFilter(void) { LPFNGETCLASSOBJECT pDllGetClassObject = (LPFNGETCLASSOBJECT) GetProcAddress(m_hDll, "DllGetClassObject"); if (!pDllGetClassObject) return FALSE; HRESULT res; IClassFactory *factory; res = pDllGetClassObject(m_guid, IID_IClassFactory, (LPVOID *) &factory); if (FAILED(res))return FALSE; IUnknown* object; res = factory->CreateInstance(NULL, IID_IUnknown, (LPVOID *) &object); factory->Release(); if (FAILED(res)) return FALSE; res = object->QueryInterface(IID_IBaseFilter, (LPVOID *) &m_filter); object->Release(); return (!FAILED(res)); } BOOL ReleaseFilter(void) { return m_filter->Release(); } BOOL SetInputType(void) { m_sOurType.majortype = MEDIATYPE_Video; m_sOurType.subtype = MEDIATYPE_Video; m_sOurType.subtype.Data1 = m_bih->biCompression; m_sOurType.formattype = FORMAT_VideoInfo; m_sOurType.bFixedSizeSamples = FALSE; m_sOurType.bTemporalCompression = TRUE; m_sOurType.lSampleSize = 1; m_sOurType.pUnk = NULL; switch (m_bih->biCompression) { case mmioFOURCC('H', '2', '6', '4'): case mmioFOURCC('h', '2', '6', '4'): case mmioFOURCC('X', '2', '6', '4'): case mmioFOURCC('x', '2', '6', '4'): case mmioFOURCC('A', 'V', 'C', '1'): case mmioFOURCC('a', 'v', 'c', '1'): case mmioFOURCC('d', 'a', 'v', 'c'): case mmioFOURCC('D', 'A', 'V', 'C'): case mmioFOURCC('V', 'S', 'S', 'H'): return SetInputMPEG2(); } return SetInputVideoInfo(); } BOOL SetInputVideoInfo(void) { memset(&m_vi, 0, sizeof(m_vi)); memcpy(&m_vi.bmiHeader, m_bih, m_bih->biSize); m_vi.rcSource.left = m_vi.rcSource.top = 0; m_vi.rcSource.right = m_bih->biWidth; m_vi.rcSource.bottom = m_bih->biHeight; m_vi.rcTarget = m_vi.rcSource; m_sOurType.formattype = FORMAT_VideoInfo; m_sOurType.pbFormat = (BYTE *) &m_vi; m_sOurType.cbFormat = sizeof(VIDEOINFOHEADER); return TRUE; } BOOL SetInputMPEG2(void) { memset(&m_mp2vi, 0, sizeof(m_mp2vi)); m_mp2vi.hdr.rcSource.left = m_mp2vi.hdr.rcSource.top = 0; m_mp2vi.hdr.rcSource.right = m_bih->biWidth; m_mp2vi.hdr.rcSource.bottom = m_bih->biHeight; m_mp2vi.hdr.rcTarget = m_mp2vi.hdr.rcSource; m_mp2vi.hdr.dwBitRate = 0; m_mp2vi.hdr.AvgTimePerFrame = 0; m_mp2vi.hdr.dwPictAspectRatioX = m_bih->biWidth; m_mp2vi.hdr.dwPictAspectRatioY = m_bih->biHeight; memcpy(&m_mp2vi.hdr.bmiHeader, m_bih, sizeof(BITMAPINFOHEADER)); m_mp2vi.hdr.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); m_sOurType.formattype = FORMAT_MPEG2Video; m_sOurType.pbFormat = (BYTE *) &m_mp2vi; m_sOurType.cbFormat = sizeof(MPEG2VIDEOINFO); return TRUE; } BOOL EnumPins(void) { HRESULT res; IEnumPins *enumpins; res = m_filter->EnumPins(&enumpins); enumpins->Reset(); IPin *pin; PIN_INFO pInfo; while ((res = enumpins->Next(1, &pin, NULL)) == S_OK) { pin->QueryPinInfo(&pInfo); wprintf(L"Pin: %s - %s\n", pInfo.achName, (pInfo.dir == PINDIR_INPUT) ? L"Input" : L"Output"); if (pInfo.dir == PINDIR_INPUT) { m_iPin = pin; m_iPin->AddRef(); } else if (pInfo.dir == PINDIR_OUTPUT) { m_oPin = pin; m_oPin->AddRef(); } pin->Release(); } enumpins->Release(); res = m_iPin->QueryInterface(IID_IMemInputPin, (LPVOID *) &m_iMem); return TRUE; } BOOL CreateGraph(void) { this->EnumPins(); this->SetInputType(); HRESULT res; DebugBreak(); res = m_iPin->QueryAccept(&m_sOurType); //CBaseFilter s_filter = CBaseFilter(); return TRUE; } BOOL ShowPropertyPage(void) { if (!m_filter) return FALSE; HRESULT res; ISpecifyPropertyPages *pProp; if ((res = m_filter->QueryInterface(IID_ISpecifyPropertyPages, (LPVOID *) &pProp)) == S_OK) { // Get the filter's name and IUnknown pointer. FILTER_INFO FilterInfo; res = m_filter->QueryFilterInfo(&FilterInfo); IUnknown *pFilterUnk; res = m_filter->QueryInterface(IID_IUnknown, (LPVOID *) &pFilterUnk); CAUUID caGUID; pProp->GetPages(&caGUID); pProp->Release(); __try { res = OleCreatePropertyFrame( NULL, // Parent window 0, 0, // Reserved FilterInfo.achName, // Caption for the dialog box 1, // Number of objects (just the filter) &pFilterUnk, // Array of object pointers. caGUID.cElems, // Number of property pages caGUID.pElems, // Array of property page CLSIDs 0, // Locale identifier 0, NULL // Reserved ); } __except(EXCEPTION_EXECUTE_HANDLER) { } // Clean up. pFilterUnk->Release(); /* FIXME: it crashes (broken example on msdn?) */ //FilterInfo.pGraph->Release(); CoTaskMemFree(caGUID.pElems); } return (!FAILED(res)); } private: HMODULE m_hDll; GUID m_guid; char m_fname[MAX_PATH + 1]; BITMAPINFOHEADER *m_bih; IBaseFilter *m_filter; IPin *m_iPin; IPin *m_oPin; IMemInputPin *m_iMem; AM_MEDIA_TYPE m_sOurType, m_sDestType; MPEG2VIDEOINFO m_mp2vi; VIDEOINFOHEADER m_vi; }; extern "C" DSCodec * WINAPI DSOpenCodec(const char *dll, const GUID guid, BITMAPINFOHEADER* bih) { DSCodec *codec = new DSCodec(dll, guid, bih); if (!codec->LoadLibrary()) return NULL; if (!codec->CreateFilter()) return NULL; if (!codec->CreateGraph()) return NULL; return codec; } extern "C" void WINAPI DSCloseCodec(DSCodec *codec) { codec->ReleaseFilter(); delete codec; } extern "C" BOOL WINAPI DSShowPropertyPage(DSCodec *codec) { return codec->ShowPropertyPage(); } BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID lpReserved) { switch (reason) { case DLL_PROCESS_ATTACH: { DisableThreadLibraryCalls(hModule); return (OleInitialize(NULL) == S_OK); } case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: return TRUE; case DLL_PROCESS_DETACH: break; } return TRUE; } <|endoftext|>
<commit_before>/* ** Copyright 2013 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. ** ** For more information : [email protected] */ #include "com/centreon/broker/extcmd/command_request.hh" #include "com/centreon/broker/extcmd/internal.hh" #include "com/centreon/broker/extcmd/factory.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" #include "com/centreon/broker/logging/logging.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::extcmd; /************************************** * * * Global Objects * * * **************************************/ /** * @brief Command file initialization routine. * * Initialize the command file endpoint. */ void extcmd::load() { io::events& e(io::events::instance()); // Register extcmd protocol. io::protocols::instance().reg( "extcmd", extcmd::factory(), 1, 7); // Register extcmd category. e.register_category("extcmd", io::events::extcmd); // Register event. e.register_event( io::events::extcmd, io::events::de_command_request, io::event_info( "command_request", &command_request::operations, command_request::entries)); e.register_event( io::events::extcmd, io::events::de_command_result, io::event_info( "command_result", &command_request::operations, command_request::entries)); return ; } /** * @brief Command file cleanup routine. * * Delete the command file endpoint. */ void extcmd::unload() { // Unregister protocol. io::protocols::instance().unreg("extcmd"); // Unregister category. io::events::instance().unregister_category(io::events::extcmd); return ; } <commit_msg>Extcmd: fix command result registration.<commit_after>/* ** Copyright 2013 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. ** ** For more information : [email protected] */ #include "com/centreon/broker/extcmd/command_request.hh" #include "com/centreon/broker/extcmd/command_result.hh" #include "com/centreon/broker/extcmd/internal.hh" #include "com/centreon/broker/extcmd/factory.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" #include "com/centreon/broker/logging/logging.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::extcmd; /************************************** * * * Global Objects * * * **************************************/ /** * @brief Command file initialization routine. * * Initialize the command file endpoint. */ void extcmd::load() { io::events& e(io::events::instance()); // Register extcmd protocol. io::protocols::instance().reg( "extcmd", extcmd::factory(), 1, 7); // Register extcmd category. e.register_category("extcmd", io::events::extcmd); // Register event. e.register_event( io::events::extcmd, io::events::de_command_request, io::event_info( "command_request", &command_request::operations, command_request::entries)); e.register_event( io::events::extcmd, io::events::de_command_result, io::event_info( "command_result", &command_result::operations, command_result::entries)); return ; } /** * @brief Command file cleanup routine. * * Delete the command file endpoint. */ void extcmd::unload() { // Unregister protocol. io::protocols::instance().unreg("extcmd"); // Unregister category. io::events::instance().unregister_category(io::events::extcmd); return ; } <|endoftext|>
<commit_before>#include "renderState.h" namespace Tangram { namespace RenderState { Blending blending; DepthTest depthTest; StencilTest stencilTest; Culling culling; DepthWrite depthWrite; BlendingFunc blendingFunc; StencilWrite stencilWrite; StencilFunc stencilFunc; StencilOp stencilOp; ColorWrite colorWrite; FrontFace frontFace; CullFace cullFace; VertexBuffer vertexBuffer; IndexBuffer indexBuffer; void bindVertexBuffer(GLuint _id) { glBindBuffer(GL_ARRAY_BUFFER, _id); } void bindIndexBuffer(GLuint _id) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _id); } void configure() { blending.init(GL_FALSE); blendingFunc.init(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); culling.init(GL_TRUE); cullFace.init(GL_BACK); frontFace.init(GL_CCW); depthTest.init(GL_TRUE); depthWrite.init(GL_TRUE); glDisable(GL_STENCIL_TEST); glDepthFunc(GL_LEQUAL); glClearDepthf(1.0); glDepthRangef(0.0, 1.0); glClearColor(0.3, 0.3, 0.3, 1.0); vertexBuffer.init(-1); indexBuffer.init(-1); } } } <commit_msg>use max unsigned int value as bad value for buffers<commit_after>#include "renderState.h" namespace Tangram { namespace RenderState { Blending blending; DepthTest depthTest; StencilTest stencilTest; Culling culling; DepthWrite depthWrite; BlendingFunc blendingFunc; StencilWrite stencilWrite; StencilFunc stencilFunc; StencilOp stencilOp; ColorWrite colorWrite; FrontFace frontFace; CullFace cullFace; VertexBuffer vertexBuffer; IndexBuffer indexBuffer; void bindVertexBuffer(GLuint _id) { glBindBuffer(GL_ARRAY_BUFFER, _id); } void bindIndexBuffer(GLuint _id) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _id); } void configure() { blending.init(GL_FALSE); blendingFunc.init(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); culling.init(GL_TRUE); cullFace.init(GL_BACK); frontFace.init(GL_CCW); depthTest.init(GL_TRUE); depthWrite.init(GL_TRUE); glDisable(GL_STENCIL_TEST); glDepthFunc(GL_LEQUAL); glClearDepthf(1.0); glDepthRangef(0.0, 1.0); glClearColor(0.3, 0.3, 0.3, 1.0); vertexBuffer.init(std::numeric_limits<unsigned int>::max()); indexBuffer.init(std::numeric_limits<unsigned int>::max()); } } } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef COSV_STR_TYPES_HXX #define COSV_STR_TYPES_HXX namespace csv { /** Provides some generally used constants. */ struct str { public: typedef ::size_t position; typedef ::size_t size; enum constants { npos = position(-1), maxsize = size(-1) }; enum insert_mode { overwrite = 0, insert = 1 }; }; /** Is used for string comparisons. @collab String @collab various csv::compare(...) functions */ class CharOrder_Table { public: /** @precond Parameter i_pCharWeightsArray must have size of 256. */ CharOrder_Table( const int * i_pCharWeightsArray ); /** @return the weight of the char i_c. @precond Even with unusual implementations, where char has more than 8 bit, there must be true: 0 <= i_c < 256. */ int operator()( char i_c ) const; private: int cWeights[256]; }; // IMPLEMENTATION inline int CharOrder_Table::operator()( char i_c ) const { return cWeights[ UINT8(i_c) ]; } } // namespace csv #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>WaE: enumeral and non-enumeral type in conditional expression<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef COSV_STR_TYPES_HXX #define COSV_STR_TYPES_HXX namespace csv { /** Provides some generally used constants. */ struct str { public: typedef ::size_t position; typedef ::size_t size; static const position npos = -1; static const size maxsize = -1; enum insert_mode { overwrite = 0, insert = 1 }; }; /** Is used for string comparisons. @collab String @collab various csv::compare(...) functions */ class CharOrder_Table { public: /** @precond Parameter i_pCharWeightsArray must have size of 256. */ CharOrder_Table( const int * i_pCharWeightsArray ); /** @return the weight of the char i_c. @precond Even with unusual implementations, where char has more than 8 bit, there must be true: 0 <= i_c < 256. */ int operator()( char i_c ) const; private: int cWeights[256]; }; // IMPLEMENTATION inline int CharOrder_Table::operator()( char i_c ) const { return cWeights[ UINT8(i_c) ]; } } // namespace csv #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/* -*- indent-tabs-mode: nil -*- */ #include <gtest/gtest.h> #include <memory> #include <stdint.h> #include <string> #include "log/etcd_consistent_store-inl.h" #include "log/file_db.h" #include "log/log_signer.h" #include "log/log_verifier.h" #include "log/sqlite_db.h" #include "log/test_db.h" #include "log/test_signer.h" #include "log/tree_signer-inl.h" #include "log/tree_signer.h" #include "merkletree/merkle_verifier.h" #include "proto/ct.pb.h" #include "util/fake_etcd.h" #include "util/mock_masterelection.h" #include "util/status_test_util.h" #include "util/sync_task.h" #include "util/testing.h" #include "util/thread_pool.h" #include "util/util.h" namespace cert_trans { using cert_trans::EntryHandle; using cert_trans::LoggedCertificate; using cert_trans::MockMasterElection; using ct::ClusterNodeState; using ct::SequenceMapping; using ct::SignedTreeHead; using std::make_shared; using std::move; using std::shared_ptr; using std::string; using std::unique_ptr; using std::unordered_map; using std::vector; using testing::NiceMock; using util::Status; typedef Database<LoggedCertificate> DB; typedef TreeSigner<LoggedCertificate> TS; // TODO(alcutter): figure out if/how we can keep abstract rather than // hardcoding LoggedCertificate in here. template <class T> class TreeSignerTest : public ::testing::Test { protected: TreeSignerTest() : test_db_(), base_(make_shared<libevent::Base>()), event_pump_(base_), etcd_client_(base_.get()), pool_(2), test_signer_(), verifier_(), tree_signer_() { } void SetUp() { test_db_.reset(new TestDB<T>); verifier_.reset(new LogVerifier(TestSigner::DefaultLogSigVerifier(), new MerkleVerifier(new Sha256Hasher()))); store_.reset(new EtcdConsistentStore<LoggedCertificate>( base_.get(), &pool_, &etcd_client_, &election_, "/root", "id")); tree_signer_.reset(new TS(std::chrono::duration<double>(0), db(), unique_ptr<CompactMerkleTree>( new CompactMerkleTree(new Sha256Hasher)), store_.get(), TestSigner::DefaultLogSigner())); // Set a default empty STH so that we can call UpdateTree() on the signer. store_->SetServingSTH(SignedTreeHead()); // Force an empty sequence mapping file: { util::SyncTask task(&pool_); EtcdClient::Response r; etcd_client_.ForceSet("/root/sequence_mapping", "", &r, task.task()); task.Wait(); } } void AddPendingEntry(LoggedCertificate* logged_cert) const { logged_cert->clear_sequence_number(); CHECK(this->store_->AddPendingEntry(logged_cert).ok()); } void DeletePendingEntry(const LoggedCertificate& logged_cert) const { EntryHandle<LoggedCertificate> e; CHECK_EQ(Status::OK, this->store_->GetPendingEntryForHash(logged_cert.Hash(), &e)); CHECK_EQ(Status::OK, this->store_->DeleteEntry(&e)); } void AddSequencedEntry(LoggedCertificate* logged_cert, int64_t seq) const { logged_cert->clear_sequence_number(); CHECK(this->store_->AddPendingEntry(logged_cert).ok()); // This below would normally be done by TreeSigner::SequenceNewEntries() EntryHandle<LoggedCertificate> entry; EntryHandle<SequenceMapping> mapping; CHECK(this->store_->GetSequenceMapping(&mapping).ok()); SequenceMapping::Mapping* m(mapping.MutableEntry()->add_mapping()); m->set_sequence_number(seq); m->set_entry_hash(logged_cert->Hash()); CHECK(this->store_->UpdateSequenceMapping(&mapping).ok()); logged_cert->set_sequence_number(seq); CHECK_EQ(Database<LoggedCertificate>::OK, this->db()->CreateSequencedEntry(*logged_cert)); } TS* GetSimilar() { return new TS(std::chrono::duration<double>(0), db(), unique_ptr<CompactMerkleTree>(new CompactMerkleTree( *tree_signer_->cert_tree_, new Sha256Hasher)), store_.get(), TestSigner::DefaultLogSigner()); } T* db() const { return test_db_->db(); } std::unique_ptr<TestDB<T>> test_db_; shared_ptr<libevent::Base> base_; libevent::EventPumpThread event_pump_; FakeEtcdClient etcd_client_; ThreadPool pool_; NiceMock<MockMasterElection> election_; std::unique_ptr<EtcdConsistentStore<LoggedCertificate>> store_; TestSigner test_signer_; std::unique_ptr<LogVerifier> verifier_; std::unique_ptr<TS> tree_signer_; }; typedef testing::Types<FileDB<LoggedCertificate>, SQLiteDB<LoggedCertificate>> Databases; EntryHandle<LoggedCertificate> H(const LoggedCertificate& l) { EntryHandle<LoggedCertificate> handle; handle.MutableEntry()->CopyFrom(l); return handle; } TYPED_TEST_CASE(TreeSignerTest, Databases); TYPED_TEST(TreeSignerTest, PendingEntriesOrder) { PendingEntriesOrder<LoggedCertificate> ordering; LoggedCertificate lowest; this->test_signer_.CreateUnique(&lowest); // Can't be lower than itself! EXPECT_FALSE(ordering(H(lowest), H(lowest))); // check timestamp: LoggedCertificate higher_timestamp(lowest); higher_timestamp.mutable_sct()->set_timestamp(lowest.timestamp() + 1); EXPECT_TRUE(ordering(H(lowest), H(higher_timestamp))); EXPECT_FALSE(ordering(H(higher_timestamp), H(lowest))); // check hash fallback: LoggedCertificate higher_hash(lowest); while (higher_hash.Hash() <= lowest.Hash()) { this->test_signer_.CreateUnique(&higher_hash); higher_hash.mutable_sct()->set_timestamp(lowest.timestamp()); } EXPECT_TRUE(ordering(H(lowest), H(higher_hash))); EXPECT_FALSE(ordering(H(higher_hash), H(lowest))); } // TODO(ekasper): KAT tests. TYPED_TEST(TreeSignerTest, Sign) { LoggedCertificate logged_cert; this->test_signer_.CreateUnique(&logged_cert); this->AddPendingEntry(&logged_cert); // this->AddSequencedEntry(&logged_cert, 0); EXPECT_OK(this->tree_signer_->SequenceNewEntries()); EXPECT_EQ(TS::OK, this->tree_signer_->UpdateTree()); const SignedTreeHead sth(this->tree_signer_->LatestSTH()); EXPECT_EQ(1U, sth.tree_size()); EXPECT_EQ(sth.timestamp(), this->tree_signer_->LastUpdateTime()); } TYPED_TEST(TreeSignerTest, Timestamp) { LoggedCertificate logged_cert; this->test_signer_.CreateUnique(&logged_cert); this->AddSequencedEntry(&logged_cert, 0); EXPECT_EQ(TS::OK, this->tree_signer_->UpdateTree()); uint64_t last_update = this->tree_signer_->LastUpdateTime(); EXPECT_GE(last_update, logged_cert.sct().timestamp()); // Now create a second entry with a timestamp some time in the future // and verify that the signer's timestamp is greater than that. uint64_t future = last_update + 10000; LoggedCertificate logged_cert2; this->test_signer_.CreateUnique(&logged_cert2); logged_cert2.mutable_sct()->set_timestamp(future); this->AddSequencedEntry(&logged_cert2, 1); EXPECT_EQ(TS::OK, this->tree_signer_->UpdateTree()); EXPECT_GE(this->tree_signer_->LastUpdateTime(), future); } TYPED_TEST(TreeSignerTest, Verify) { LoggedCertificate logged_cert; this->test_signer_.CreateUnique(&logged_cert); this->AddSequencedEntry(&logged_cert, 0); EXPECT_EQ(TS::OK, this->tree_signer_->UpdateTree()); const SignedTreeHead sth(this->tree_signer_->LatestSTH()); EXPECT_EQ(LogVerifier::VERIFY_OK, this->verifier_->VerifySignedTreeHead(sth)); } TYPED_TEST(TreeSignerTest, ResumeClean) { LoggedCertificate logged_cert; this->test_signer_.CreateUnique(&logged_cert); this->AddSequencedEntry(&logged_cert, 0); EXPECT_EQ(TS::OK, this->tree_signer_->UpdateTree()); const SignedTreeHead sth(this->tree_signer_->LatestSTH()); { // Simulate the caller of UpdateTree() pushing this new tree out to the // cluster. ClusterNodeState node_state; *node_state.mutable_newest_sth() = sth; CHECK_EQ(util::Status::OK, this->store_->SetClusterNodeState(node_state)); } TS* signer2 = this->GetSimilar(); // Update EXPECT_EQ(TS::OK, signer2->UpdateTree()); const SignedTreeHead sth2(signer2->LatestSTH()); EXPECT_LT(sth.timestamp(), sth2.timestamp()); EXPECT_EQ(sth.sha256_root_hash(), sth2.sha256_root_hash()); EXPECT_EQ(sth.tree_size(), sth2.tree_size()); delete signer2; } // Test resuming when the tree head signature is lagging behind the // sequence number commits. TYPED_TEST(TreeSignerTest, ResumePartialSign) { EXPECT_EQ(TS::OK, this->tree_signer_->UpdateTree()); const SignedTreeHead sth(this->tree_signer_->LatestSTH()); { // Simulate the caller of UpdateTree() pushing this new tree out to the // cluster. ClusterNodeState node_state; *node_state.mutable_newest_sth() = sth; CHECK_EQ(util::Status::OK, this->store_->SetClusterNodeState(node_state)); } LoggedCertificate logged_cert; this->test_signer_.CreateUnique(&logged_cert); this->AddSequencedEntry(&logged_cert, 0); TS* signer2 = this->GetSimilar(); EXPECT_EQ(TS::OK, signer2->UpdateTree()); const SignedTreeHead sth2(signer2->LatestSTH()); // The signer should have picked up the sequence number commit. EXPECT_EQ(1U, sth2.tree_size()); EXPECT_LT(sth.timestamp(), sth2.timestamp()); EXPECT_NE(sth.sha256_root_hash(), sth2.sha256_root_hash()); delete signer2; } TYPED_TEST(TreeSignerTest, SignEmpty) { EXPECT_EQ(TS::OK, this->tree_signer_->UpdateTree()); const SignedTreeHead sth(this->tree_signer_->LatestSTH()); EXPECT_GT(sth.timestamp(), 0U); EXPECT_EQ(sth.tree_size(), 0U); } TYPED_TEST(TreeSignerTest, SequenceNewEntriesCleansUpOldSequenceMappings) { LoggedCertificate logged_cert; this->test_signer_.CreateUnique(&logged_cert); this->AddPendingEntry(&logged_cert); EXPECT_OK(this->tree_signer_->SequenceNewEntries()); EXPECT_EQ(TS::OK, this->tree_signer_->UpdateTree()); EXPECT_EQ(Status::OK, this->store_->SetServingSTH(this->tree_signer_->LatestSTH())); sleep(1); { EntryHandle<SequenceMapping> mapping; CHECK_EQ(Status::OK, this->store_->GetSequenceMapping(&mapping)); EXPECT_EQ(1, mapping.Entry().mapping_size()); EXPECT_EQ(logged_cert.Hash(), mapping.Entry().mapping(0).entry_hash()); } unordered_map<string, LoggedCertificate> new_logged_certs; for (int i(0); i < 2; ++i) { LoggedCertificate c; this->test_signer_.CreateUnique(&c); this->AddPendingEntry(&c); new_logged_certs.insert(make_pair(c.Hash(), c)); } this->DeletePendingEntry(logged_cert); LOG(INFO) << "2"; EXPECT_OK(this->tree_signer_->SequenceNewEntries()); { EntryHandle<SequenceMapping> mapping; CHECK_EQ(Status::OK, this->store_->GetSequenceMapping(&mapping)); CHECK_LE(mapping.Entry().mapping_size(), INT_MAX); EXPECT_EQ(new_logged_certs.size(), static_cast<size_t>(mapping.Entry().mapping_size())); for (int i(0); i < mapping.Entry().mapping_size(); ++i) { const auto& m(mapping.Entry().mapping(i)); EXPECT_NE(new_logged_certs.end(), new_logged_certs.find(m.entry_hash())); } } } } // namespace cert_trans int main(int argc, char** argv) { cert_trans::test::InitTesting(argv[0], &argc, &argv, true); return RUN_ALL_TESTS(); } <commit_msg>Review fix.<commit_after>/* -*- indent-tabs-mode: nil -*- */ #include <gtest/gtest.h> #include <memory> #include <stdint.h> #include <string> #include "log/etcd_consistent_store-inl.h" #include "log/file_db.h" #include "log/log_signer.h" #include "log/log_verifier.h" #include "log/sqlite_db.h" #include "log/test_db.h" #include "log/test_signer.h" #include "log/tree_signer-inl.h" #include "log/tree_signer.h" #include "merkletree/merkle_verifier.h" #include "proto/ct.pb.h" #include "util/fake_etcd.h" #include "util/mock_masterelection.h" #include "util/status_test_util.h" #include "util/sync_task.h" #include "util/testing.h" #include "util/thread_pool.h" #include "util/util.h" namespace cert_trans { using cert_trans::EntryHandle; using cert_trans::LoggedCertificate; using cert_trans::MockMasterElection; using ct::ClusterNodeState; using ct::SequenceMapping; using ct::SignedTreeHead; using std::make_shared; using std::move; using std::shared_ptr; using std::string; using std::unique_ptr; using std::unordered_map; using std::vector; using testing::NiceMock; using util::Status; typedef Database<LoggedCertificate> DB; typedef TreeSigner<LoggedCertificate> TS; // TODO(alcutter): figure out if/how we can keep abstract rather than // hardcoding LoggedCertificate in here. template <class T> class TreeSignerTest : public ::testing::Test { protected: TreeSignerTest() : test_db_(), base_(make_shared<libevent::Base>()), event_pump_(base_), etcd_client_(base_.get()), pool_(2), test_signer_(), verifier_(), tree_signer_() { } void SetUp() { test_db_.reset(new TestDB<T>); verifier_.reset(new LogVerifier(TestSigner::DefaultLogSigVerifier(), new MerkleVerifier(new Sha256Hasher()))); store_.reset(new EtcdConsistentStore<LoggedCertificate>( base_.get(), &pool_, &etcd_client_, &election_, "/root", "id")); tree_signer_.reset(new TS(std::chrono::duration<double>(0), db(), unique_ptr<CompactMerkleTree>( new CompactMerkleTree(new Sha256Hasher)), store_.get(), TestSigner::DefaultLogSigner())); // Set a default empty STH so that we can call UpdateTree() on the signer. store_->SetServingSTH(SignedTreeHead()); // Force an empty sequence mapping file: { util::SyncTask task(&pool_); EtcdClient::Response r; etcd_client_.ForceSet("/root/sequence_mapping", "", &r, task.task()); task.Wait(); } } void AddPendingEntry(LoggedCertificate* logged_cert) const { logged_cert->clear_sequence_number(); CHECK(this->store_->AddPendingEntry(logged_cert).ok()); } void DeletePendingEntry(const LoggedCertificate& logged_cert) const { EntryHandle<LoggedCertificate> e; CHECK_EQ(Status::OK, this->store_->GetPendingEntryForHash(logged_cert.Hash(), &e)); CHECK_EQ(Status::OK, this->store_->DeleteEntry(&e)); } void AddSequencedEntry(LoggedCertificate* logged_cert, int64_t seq) const { logged_cert->clear_sequence_number(); CHECK(this->store_->AddPendingEntry(logged_cert).ok()); // This below would normally be done by TreeSigner::SequenceNewEntries() EntryHandle<LoggedCertificate> entry; EntryHandle<SequenceMapping> mapping; CHECK(this->store_->GetSequenceMapping(&mapping).ok()); SequenceMapping::Mapping* m(mapping.MutableEntry()->add_mapping()); m->set_sequence_number(seq); m->set_entry_hash(logged_cert->Hash()); CHECK(this->store_->UpdateSequenceMapping(&mapping).ok()); logged_cert->set_sequence_number(seq); CHECK_EQ(Database<LoggedCertificate>::OK, this->db()->CreateSequencedEntry(*logged_cert)); } TS* GetSimilar() { return new TS(std::chrono::duration<double>(0), db(), unique_ptr<CompactMerkleTree>(new CompactMerkleTree( *tree_signer_->cert_tree_, new Sha256Hasher)), store_.get(), TestSigner::DefaultLogSigner()); } T* db() const { return test_db_->db(); } std::unique_ptr<TestDB<T>> test_db_; shared_ptr<libevent::Base> base_; libevent::EventPumpThread event_pump_; FakeEtcdClient etcd_client_; ThreadPool pool_; NiceMock<MockMasterElection> election_; std::unique_ptr<EtcdConsistentStore<LoggedCertificate>> store_; TestSigner test_signer_; std::unique_ptr<LogVerifier> verifier_; std::unique_ptr<TS> tree_signer_; }; typedef testing::Types<FileDB<LoggedCertificate>, SQLiteDB<LoggedCertificate>> Databases; EntryHandle<LoggedCertificate> H(const LoggedCertificate& l) { EntryHandle<LoggedCertificate> handle; handle.MutableEntry()->CopyFrom(l); return handle; } TYPED_TEST_CASE(TreeSignerTest, Databases); TYPED_TEST(TreeSignerTest, PendingEntriesOrder) { PendingEntriesOrder<LoggedCertificate> ordering; LoggedCertificate lowest; this->test_signer_.CreateUnique(&lowest); // Can't be lower than itself! EXPECT_FALSE(ordering(H(lowest), H(lowest))); // check timestamp: LoggedCertificate higher_timestamp(lowest); higher_timestamp.mutable_sct()->set_timestamp(lowest.timestamp() + 1); EXPECT_TRUE(ordering(H(lowest), H(higher_timestamp))); EXPECT_FALSE(ordering(H(higher_timestamp), H(lowest))); // check hash fallback: LoggedCertificate higher_hash(lowest); while (higher_hash.Hash() <= lowest.Hash()) { this->test_signer_.CreateUnique(&higher_hash); higher_hash.mutable_sct()->set_timestamp(lowest.timestamp()); } EXPECT_TRUE(ordering(H(lowest), H(higher_hash))); EXPECT_FALSE(ordering(H(higher_hash), H(lowest))); } // TODO(ekasper): KAT tests. TYPED_TEST(TreeSignerTest, Sign) { LoggedCertificate logged_cert; this->test_signer_.CreateUnique(&logged_cert); this->AddPendingEntry(&logged_cert); // this->AddSequencedEntry(&logged_cert, 0); EXPECT_OK(this->tree_signer_->SequenceNewEntries()); EXPECT_EQ(TS::OK, this->tree_signer_->UpdateTree()); const SignedTreeHead sth(this->tree_signer_->LatestSTH()); EXPECT_EQ(1U, sth.tree_size()); EXPECT_EQ(sth.timestamp(), this->tree_signer_->LastUpdateTime()); } TYPED_TEST(TreeSignerTest, Timestamp) { LoggedCertificate logged_cert; this->test_signer_.CreateUnique(&logged_cert); this->AddSequencedEntry(&logged_cert, 0); EXPECT_EQ(TS::OK, this->tree_signer_->UpdateTree()); uint64_t last_update = this->tree_signer_->LastUpdateTime(); EXPECT_GE(last_update, logged_cert.sct().timestamp()); // Now create a second entry with a timestamp some time in the future // and verify that the signer's timestamp is greater than that. uint64_t future = last_update + 10000; LoggedCertificate logged_cert2; this->test_signer_.CreateUnique(&logged_cert2); logged_cert2.mutable_sct()->set_timestamp(future); this->AddSequencedEntry(&logged_cert2, 1); EXPECT_EQ(TS::OK, this->tree_signer_->UpdateTree()); EXPECT_GE(this->tree_signer_->LastUpdateTime(), future); } TYPED_TEST(TreeSignerTest, Verify) { LoggedCertificate logged_cert; this->test_signer_.CreateUnique(&logged_cert); this->AddSequencedEntry(&logged_cert, 0); EXPECT_EQ(TS::OK, this->tree_signer_->UpdateTree()); const SignedTreeHead sth(this->tree_signer_->LatestSTH()); EXPECT_EQ(LogVerifier::VERIFY_OK, this->verifier_->VerifySignedTreeHead(sth)); } TYPED_TEST(TreeSignerTest, ResumeClean) { LoggedCertificate logged_cert; this->test_signer_.CreateUnique(&logged_cert); this->AddSequencedEntry(&logged_cert, 0); EXPECT_EQ(TS::OK, this->tree_signer_->UpdateTree()); const SignedTreeHead sth(this->tree_signer_->LatestSTH()); { // Simulate the caller of UpdateTree() pushing this new tree out to the // cluster. ClusterNodeState node_state; *node_state.mutable_newest_sth() = sth; CHECK_EQ(util::Status::OK, this->store_->SetClusterNodeState(node_state)); } TS* signer2 = this->GetSimilar(); // Update EXPECT_EQ(TS::OK, signer2->UpdateTree()); const SignedTreeHead sth2(signer2->LatestSTH()); EXPECT_LT(sth.timestamp(), sth2.timestamp()); EXPECT_EQ(sth.sha256_root_hash(), sth2.sha256_root_hash()); EXPECT_EQ(sth.tree_size(), sth2.tree_size()); delete signer2; } // Test resuming when the tree head signature is lagging behind the // sequence number commits. TYPED_TEST(TreeSignerTest, ResumePartialSign) { EXPECT_EQ(TS::OK, this->tree_signer_->UpdateTree()); const SignedTreeHead sth(this->tree_signer_->LatestSTH()); { // Simulate the caller of UpdateTree() pushing this new tree out to the // cluster. ClusterNodeState node_state; *node_state.mutable_newest_sth() = sth; CHECK_EQ(util::Status::OK, this->store_->SetClusterNodeState(node_state)); } LoggedCertificate logged_cert; this->test_signer_.CreateUnique(&logged_cert); this->AddSequencedEntry(&logged_cert, 0); TS* signer2 = this->GetSimilar(); EXPECT_EQ(TS::OK, signer2->UpdateTree()); const SignedTreeHead sth2(signer2->LatestSTH()); // The signer should have picked up the sequence number commit. EXPECT_EQ(1U, sth2.tree_size()); EXPECT_LT(sth.timestamp(), sth2.timestamp()); EXPECT_NE(sth.sha256_root_hash(), sth2.sha256_root_hash()); delete signer2; } TYPED_TEST(TreeSignerTest, SignEmpty) { EXPECT_EQ(TS::OK, this->tree_signer_->UpdateTree()); const SignedTreeHead sth(this->tree_signer_->LatestSTH()); EXPECT_GT(sth.timestamp(), 0U); EXPECT_EQ(sth.tree_size(), 0U); } TYPED_TEST(TreeSignerTest, SequenceNewEntriesCleansUpOldSequenceMappings) { LoggedCertificate logged_cert; this->test_signer_.CreateUnique(&logged_cert); this->AddPendingEntry(&logged_cert); EXPECT_OK(this->tree_signer_->SequenceNewEntries()); EXPECT_EQ(TS::OK, this->tree_signer_->UpdateTree()); EXPECT_EQ(Status::OK, this->store_->SetServingSTH(this->tree_signer_->LatestSTH())); sleep(1); { EntryHandle<SequenceMapping> mapping; CHECK_EQ(Status::OK, this->store_->GetSequenceMapping(&mapping)); EXPECT_EQ(1, mapping.Entry().mapping_size()); EXPECT_EQ(logged_cert.Hash(), mapping.Entry().mapping(0).entry_hash()); } unordered_map<string, LoggedCertificate> new_logged_certs; for (int i(0); i < 2; ++i) { LoggedCertificate c; this->test_signer_.CreateUnique(&c); this->AddPendingEntry(&c); new_logged_certs.insert(make_pair(c.Hash(), c)); } this->DeletePendingEntry(logged_cert); LOG(INFO) << "2"; EXPECT_OK(this->tree_signer_->SequenceNewEntries()); { EntryHandle<SequenceMapping> mapping; CHECK_EQ(Status::OK, this->store_->GetSequenceMapping(&mapping)); CHECK_GE(mapping.Entry().mapping_size(), 0); EXPECT_EQ(new_logged_certs.size(), static_cast<size_t>(mapping.Entry().mapping_size())); for (int i(0); i < mapping.Entry().mapping_size(); ++i) { const auto& m(mapping.Entry().mapping(i)); EXPECT_NE(new_logged_certs.end(), new_logged_certs.find(m.entry_hash())); } } } } // namespace cert_trans int main(int argc, char** argv) { cert_trans::test::InitTesting(argv[0], &argc, &argv, true); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include <csignal> #include <fcntl.h> #include <gflags/gflags.h> #include <glog/logging.h> #include <gtest/gtest.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/wait.h> #include <unistd.h> #include "net/connection_pool.h" #include "net/url_fetcher.h" #include "util/libevent_wrapper.h" #include "util/status_test_util.h" #include "util/sync_task.h" #include "util/testing.h" #include "util/thread_pool.h" DECLARE_int32(connection_read_timeout_seconds); DECLARE_int32(connection_write_timeout_seconds); DECLARE_string(trusted_root_certs); namespace cert_trans { using std::make_shared; using std::shared_ptr; using std::string; using std::to_string; using std::unique_ptr; using util::SyncTask; using util::testing::StatusIs; DEFINE_string(cert_dir, "test/testdata/urlfetcher_test_certs", "Directory containing the test certs."); const uint16_t kLocalHostPort = 4433; const uint16_t kNonLocalHostPort = 4434; const uint16_t kStarExampleComPort = 4435; const uint16_t kBinkyExampleComPort = 4436; const uint16_t kExampleComPort = 4437; const uint16_t k127_0_0_1Port = 4438; const uint16_t kHangPort = 4439; namespace { class LocalhostResolver : public libevent::Base::Resolver { public: string Resolve(const std::string& name) override { return "127.0.0.1"; } }; pid_t RunOpenSSLServer(uint16_t port, const std::string& cert_file, const std::string& key_file, const std::string& mode = "-www") { pid_t pid(fork()); if (pid == -1) { LOG(INFO) << "fork() failed: " << pid; } else if (pid == 0) { const string port_str(to_string(port)); const string cert_str(FLAGS_cert_dir + "/" + cert_file); const string key_str(FLAGS_cert_dir + "/" + key_file); const char* argv[]{"openssl", "s_server", "-accept", port_str.c_str(), "-cert", cert_str.c_str(), "-key", key_str.c_str(), mode.c_str(), 0L}; execvp(argv[0], const_cast<char**>(argv)); } return pid; } } // namespace class UrlFetcherTest : public ::testing::Test { public: UrlFetcherTest() : base_(make_shared<libevent::Base>( unique_ptr<libevent::Base::Resolver>(new LocalhostResolver))), event_pump_(base_), pool_() { FLAGS_trusted_root_certs = FLAGS_cert_dir + "/ca-cert.pem"; fetcher_.reset(new UrlFetcher(base_.get(), &pool_)); } protected: shared_ptr<libevent::Base> base_; shared_ptr<UrlFetcher> fetcher_; libevent::EventPumpThread event_pump_; ThreadPool pool_; }; TEST_F(UrlFetcherTest, TestCertMatchesHost) { UrlFetcher::Request req( URL("https://localhost:" + to_string(kLocalHostPort))); UrlFetcher::Response resp; SyncTask task(&pool_); fetcher_->Fetch(req, &resp, task.task()); task.Wait(); EXPECT_EQ(util::Status::OK, task.status()); EXPECT_EQ(200, resp.status_code); } TEST_F(UrlFetcherTest, TestCertDoesNotMatchHost) { UrlFetcher::Request req( URL("https://localhost:" + to_string(kNonLocalHostPort))); UrlFetcher::Response resp; SyncTask task(&pool_); fetcher_->Fetch(req, &resp, task.task()); task.Wait(); EXPECT_THAT(task.status(), StatusIs(util::error::UNAVAILABLE)); EXPECT_EQ(kSSLErrorStatus, resp.status_code); } TEST_F(UrlFetcherTest, TestNotListening) { UrlFetcher::Request req(URL("https://localhost:63544")); UrlFetcher::Response resp; SyncTask task(&pool_); fetcher_->Fetch(req, &resp, task.task()); task.Wait(); EXPECT_THAT(task.status(), StatusIs(util::error::UNAVAILABLE)); EXPECT_EQ(kUnknownErrorStatus, resp.status_code); } TEST_F(UrlFetcherTest, TestStarMatchesSubdomain) { UrlFetcher::Request req( URL("https://donkey.example.com:" + to_string(kStarExampleComPort))); UrlFetcher::Response resp; SyncTask task(&pool_); fetcher_->Fetch(req, &resp, task.task()); task.Wait(); EXPECT_EQ(util::Status::OK, task.status()); EXPECT_EQ(200, resp.status_code); } TEST_F(UrlFetcherTest, TestStarDoesNotMatcheIncorrectParentDomain) { UrlFetcher::Request req( URL("https://donkey.9600.org:" + to_string(kStarExampleComPort))); UrlFetcher::Response resp; SyncTask task(&pool_); fetcher_->Fetch(req, &resp, task.task()); task.Wait(); EXPECT_THAT(task.status(), StatusIs(util::error::UNAVAILABLE)); EXPECT_EQ(kSSLErrorStatus, resp.status_code); } TEST_F(UrlFetcherTest, TestSubdomainMatches) { UrlFetcher::Request req( URL("https://binky.example.com:" + to_string(kBinkyExampleComPort))); UrlFetcher::Response resp; SyncTask task(&pool_); fetcher_->Fetch(req, &resp, task.task()); task.Wait(); EXPECT_EQ(util::Status::OK, task.status()); EXPECT_EQ(200, resp.status_code); } TEST_F(UrlFetcherTest, TestSubdomainDoesNotMatchIncorrectParentDomain) { UrlFetcher::Request req( URL("https://binky.9600.org:" + to_string(kBinkyExampleComPort))); UrlFetcher::Response resp; SyncTask task(&pool_); fetcher_->Fetch(req, &resp, task.task()); task.Wait(); EXPECT_THAT(task.status(), StatusIs(util::error::UNAVAILABLE)); EXPECT_EQ(kSSLErrorStatus, resp.status_code); } TEST_F(UrlFetcherTest, TestSubstringSubjectDoesNotMatch) { UrlFetcher::Request req( URL("https://superexample.com:" + to_string(kExampleComPort))); UrlFetcher::Response resp; SyncTask task(&pool_); fetcher_->Fetch(req, &resp, task.task()); task.Wait(); EXPECT_THAT(task.status(), StatusIs(util::error::UNAVAILABLE)); EXPECT_EQ(kSSLErrorStatus, resp.status_code); } TEST_F(UrlFetcherTest, TestSuperstringSubjectDoesNotMatch) { UrlFetcher::Request req( URL("https://xample.com:" + to_string(kExampleComPort))); UrlFetcher::Response resp; SyncTask task(&pool_); fetcher_->Fetch(req, &resp, task.task()); task.Wait(); EXPECT_THAT(task.status(), StatusIs(util::error::UNAVAILABLE)); EXPECT_EQ(kSSLErrorStatus, resp.status_code); } TEST_F(UrlFetcherTest, TestSubstringHostDoesNotMatch) { UrlFetcher::Request req(URL("https://exampl:" + to_string(kExampleComPort))); UrlFetcher::Response resp; SyncTask task(&pool_); fetcher_->Fetch(req, &resp, task.task()); task.Wait(); EXPECT_THAT(task.status(), StatusIs(util::error::UNAVAILABLE)); EXPECT_EQ(kSSLErrorStatus, resp.status_code); } TEST_F(UrlFetcherTest, TestIpMatches) { UrlFetcher::Request req( URL("https://127.0.0.1:" + to_string(k127_0_0_1Port))); UrlFetcher::Response resp; SyncTask task(&pool_); fetcher_->Fetch(req, &resp, task.task()); task.Wait(); EXPECT_EQ(util::Status::OK, task.status()); EXPECT_EQ(200, resp.status_code); } TEST_F(UrlFetcherTest, TestWrongIpDoesNotMatch) { UrlFetcher::Request req(URL("https://1.2.3.4:" + to_string(k127_0_0_1Port))); UrlFetcher::Response resp; SyncTask task(&pool_); fetcher_->Fetch(req, &resp, task.task()); task.Wait(); EXPECT_THAT(task.status(), StatusIs(util::error::UNAVAILABLE)); EXPECT_EQ(kSSLErrorStatus, resp.status_code); } TEST_F(UrlFetcherTest, TestTimeout) { UrlFetcher::Request req(URL("http://localhost:" + to_string(kHangPort))); UrlFetcher::Response resp; FLAGS_connection_read_timeout_seconds = 1; FLAGS_connection_write_timeout_seconds = 1; SyncTask task(&pool_); fetcher_->Fetch(req, &resp, task.task()); task.Wait(); EXPECT_THAT(task.status(), StatusIs(util::error::DEADLINE_EXCEEDED)); EXPECT_EQ(kTimeout, resp.status_code); } } // namespace cert_trans namespace { pid_t localhost_pid(0); pid_t nonlocalhost_pid(0); pid_t star_example_com_pid(0); pid_t binky_example_com_pid(0); pid_t example_com_pid(0); pid_t ip_address_pid(0); void KillAllOpenSSLServers() { kill(localhost_pid, SIGTERM); kill(nonlocalhost_pid, SIGTERM); kill(star_example_com_pid, SIGTERM); kill(binky_example_com_pid, SIGTERM); kill(example_com_pid, SIGTERM); kill(ip_address_pid, SIGTERM); waitpid(localhost_pid, nullptr, 0); waitpid(nonlocalhost_pid, nullptr, 0); waitpid(star_example_com_pid, nullptr, 0); waitpid(binky_example_com_pid, nullptr, 0); waitpid(example_com_pid, nullptr, 0); waitpid(ip_address_pid, nullptr, 0); } } // namespace int main(int argc, char** argv) { cert_trans::test::InitTesting(argv[0], &argc, &argv, true); OpenSSL_add_all_algorithms(); ERR_load_BIO_strings(); ERR_load_crypto_strings(); SSL_load_error_strings(); SSL_library_init(); signal(SIGPIPE, SIG_IGN); int hang_fd(socket(AF_INET, SOCK_STREAM, 0)); CHECK_NE(-1, hang_fd); CHECK_NE(-1, fcntl(hang_fd, F_SETFL, O_NONBLOCK)); struct sockaddr_in hang_addr; bzero((char*)&hang_addr, sizeof(hang_addr)); hang_addr.sin_family = AF_INET; hang_addr.sin_addr.s_addr = INADDR_ANY; hang_addr.sin_port = htons(cert_trans::kHangPort); CHECK_EQ(0, bind(hang_fd, reinterpret_cast<struct sockaddr*>(&hang_addr), sizeof(hang_addr))); CHECK_EQ(0, listen(hang_fd, 10)); struct sockaddr_in other_addr; socklen_t other_size; accept(hang_fd, reinterpret_cast<struct sockaddr*>(&other_addr), &other_size); localhost_pid = cert_trans::RunOpenSSLServer(cert_trans::kLocalHostPort, "localhost-cert.pem", "localhost-key.pem"); nonlocalhost_pid = cert_trans::RunOpenSSLServer(cert_trans::kNonLocalHostPort, "not-localhost-cert.pem", "not-localhost-key.pem"); star_example_com_pid = cert_trans::RunOpenSSLServer(cert_trans::kStarExampleComPort, "star_example_com-cert.pem", "star_example_com-key.pem"); binky_example_com_pid = cert_trans::RunOpenSSLServer(cert_trans::kBinkyExampleComPort, "binky_example_com-cert.pem", "binky_example_com-key.pem"); example_com_pid = cert_trans::RunOpenSSLServer(cert_trans::kExampleComPort, "example_com-cert.pem", "example_com-key.pem"); ip_address_pid = cert_trans::RunOpenSSLServer(cert_trans::k127_0_0_1Port, "127_0_0_1-cert.pem", "127_0_0_1-key.pem"); sleep(1); const int ret(RUN_ALL_TESTS()); KillAllOpenSSLServers(); close(hang_fd); return ret; } <commit_msg>Output the error message when there is a problem.<commit_after>#include <csignal> #include <fcntl.h> #include <gflags/gflags.h> #include <glog/logging.h> #include <gtest/gtest.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/wait.h> #include <unistd.h> #include "net/connection_pool.h" #include "net/url_fetcher.h" #include "util/libevent_wrapper.h" #include "util/status_test_util.h" #include "util/sync_task.h" #include "util/testing.h" #include "util/thread_pool.h" DECLARE_int32(connection_read_timeout_seconds); DECLARE_int32(connection_write_timeout_seconds); DECLARE_string(trusted_root_certs); namespace cert_trans { using std::make_shared; using std::shared_ptr; using std::string; using std::to_string; using std::unique_ptr; using util::SyncTask; using util::testing::StatusIs; DEFINE_string(cert_dir, "test/testdata/urlfetcher_test_certs", "Directory containing the test certs."); const uint16_t kLocalHostPort = 4433; const uint16_t kNonLocalHostPort = 4434; const uint16_t kStarExampleComPort = 4435; const uint16_t kBinkyExampleComPort = 4436; const uint16_t kExampleComPort = 4437; const uint16_t k127_0_0_1Port = 4438; const uint16_t kHangPort = 4439; namespace { class LocalhostResolver : public libevent::Base::Resolver { public: string Resolve(const std::string& name) override { return "127.0.0.1"; } }; pid_t RunOpenSSLServer(uint16_t port, const std::string& cert_file, const std::string& key_file, const std::string& mode = "-www") { pid_t pid(fork()); if (pid == -1) { LOG(INFO) << "fork() failed: " << pid; } else if (pid == 0) { const string port_str(to_string(port)); const string cert_str(FLAGS_cert_dir + "/" + cert_file); const string key_str(FLAGS_cert_dir + "/" + key_file); const char* argv[]{"openssl", "s_server", "-accept", port_str.c_str(), "-cert", cert_str.c_str(), "-key", key_str.c_str(), mode.c_str(), 0L}; execvp(argv[0], const_cast<char**>(argv)); } return pid; } } // namespace class UrlFetcherTest : public ::testing::Test { public: UrlFetcherTest() : base_(make_shared<libevent::Base>( unique_ptr<libevent::Base::Resolver>(new LocalhostResolver))), event_pump_(base_), pool_() { FLAGS_trusted_root_certs = FLAGS_cert_dir + "/ca-cert.pem"; fetcher_.reset(new UrlFetcher(base_.get(), &pool_)); } protected: shared_ptr<libevent::Base> base_; shared_ptr<UrlFetcher> fetcher_; libevent::EventPumpThread event_pump_; ThreadPool pool_; }; TEST_F(UrlFetcherTest, TestCertMatchesHost) { UrlFetcher::Request req( URL("https://localhost:" + to_string(kLocalHostPort))); UrlFetcher::Response resp; SyncTask task(&pool_); fetcher_->Fetch(req, &resp, task.task()); task.Wait(); EXPECT_EQ(util::Status::OK, task.status()); EXPECT_EQ(200, resp.status_code); } TEST_F(UrlFetcherTest, TestCertDoesNotMatchHost) { UrlFetcher::Request req( URL("https://localhost:" + to_string(kNonLocalHostPort))); UrlFetcher::Response resp; SyncTask task(&pool_); fetcher_->Fetch(req, &resp, task.task()); task.Wait(); EXPECT_THAT(task.status(), StatusIs(util::error::UNAVAILABLE)); EXPECT_EQ(kSSLErrorStatus, resp.status_code); } TEST_F(UrlFetcherTest, TestNotListening) { UrlFetcher::Request req(URL("https://localhost:63544")); UrlFetcher::Response resp; SyncTask task(&pool_); fetcher_->Fetch(req, &resp, task.task()); task.Wait(); EXPECT_THAT(task.status(), StatusIs(util::error::UNAVAILABLE)); EXPECT_EQ(kUnknownErrorStatus, resp.status_code); } TEST_F(UrlFetcherTest, TestStarMatchesSubdomain) { UrlFetcher::Request req( URL("https://donkey.example.com:" + to_string(kStarExampleComPort))); UrlFetcher::Response resp; SyncTask task(&pool_); fetcher_->Fetch(req, &resp, task.task()); task.Wait(); EXPECT_EQ(util::Status::OK, task.status()); EXPECT_EQ(200, resp.status_code); } TEST_F(UrlFetcherTest, TestStarDoesNotMatcheIncorrectParentDomain) { UrlFetcher::Request req( URL("https://donkey.9600.org:" + to_string(kStarExampleComPort))); UrlFetcher::Response resp; SyncTask task(&pool_); fetcher_->Fetch(req, &resp, task.task()); task.Wait(); EXPECT_THAT(task.status(), StatusIs(util::error::UNAVAILABLE)); EXPECT_EQ(kSSLErrorStatus, resp.status_code); } TEST_F(UrlFetcherTest, TestSubdomainMatches) { UrlFetcher::Request req( URL("https://binky.example.com:" + to_string(kBinkyExampleComPort))); UrlFetcher::Response resp; SyncTask task(&pool_); fetcher_->Fetch(req, &resp, task.task()); task.Wait(); EXPECT_EQ(util::Status::OK, task.status()); EXPECT_EQ(200, resp.status_code); } TEST_F(UrlFetcherTest, TestSubdomainDoesNotMatchIncorrectParentDomain) { UrlFetcher::Request req( URL("https://binky.9600.org:" + to_string(kBinkyExampleComPort))); UrlFetcher::Response resp; SyncTask task(&pool_); fetcher_->Fetch(req, &resp, task.task()); task.Wait(); EXPECT_THAT(task.status(), StatusIs(util::error::UNAVAILABLE)); EXPECT_EQ(kSSLErrorStatus, resp.status_code); } TEST_F(UrlFetcherTest, TestSubstringSubjectDoesNotMatch) { UrlFetcher::Request req( URL("https://superexample.com:" + to_string(kExampleComPort))); UrlFetcher::Response resp; SyncTask task(&pool_); fetcher_->Fetch(req, &resp, task.task()); task.Wait(); EXPECT_THAT(task.status(), StatusIs(util::error::UNAVAILABLE)); EXPECT_EQ(kSSLErrorStatus, resp.status_code); } TEST_F(UrlFetcherTest, TestSuperstringSubjectDoesNotMatch) { UrlFetcher::Request req( URL("https://xample.com:" + to_string(kExampleComPort))); UrlFetcher::Response resp; SyncTask task(&pool_); fetcher_->Fetch(req, &resp, task.task()); task.Wait(); EXPECT_THAT(task.status(), StatusIs(util::error::UNAVAILABLE)); EXPECT_EQ(kSSLErrorStatus, resp.status_code); } TEST_F(UrlFetcherTest, TestSubstringHostDoesNotMatch) { UrlFetcher::Request req(URL("https://exampl:" + to_string(kExampleComPort))); UrlFetcher::Response resp; SyncTask task(&pool_); fetcher_->Fetch(req, &resp, task.task()); task.Wait(); EXPECT_THAT(task.status(), StatusIs(util::error::UNAVAILABLE)); EXPECT_EQ(kSSLErrorStatus, resp.status_code); } TEST_F(UrlFetcherTest, TestIpMatches) { UrlFetcher::Request req( URL("https://127.0.0.1:" + to_string(k127_0_0_1Port))); UrlFetcher::Response resp; SyncTask task(&pool_); fetcher_->Fetch(req, &resp, task.task()); task.Wait(); EXPECT_EQ(util::Status::OK, task.status()); EXPECT_EQ(200, resp.status_code); } TEST_F(UrlFetcherTest, TestWrongIpDoesNotMatch) { UrlFetcher::Request req(URL("https://1.2.3.4:" + to_string(k127_0_0_1Port))); UrlFetcher::Response resp; SyncTask task(&pool_); fetcher_->Fetch(req, &resp, task.task()); task.Wait(); EXPECT_THAT(task.status(), StatusIs(util::error::UNAVAILABLE)); EXPECT_EQ(kSSLErrorStatus, resp.status_code); } TEST_F(UrlFetcherTest, TestTimeout) { UrlFetcher::Request req(URL("http://localhost:" + to_string(kHangPort))); UrlFetcher::Response resp; FLAGS_connection_read_timeout_seconds = 1; FLAGS_connection_write_timeout_seconds = 1; SyncTask task(&pool_); fetcher_->Fetch(req, &resp, task.task()); task.Wait(); EXPECT_THAT(task.status(), StatusIs(util::error::DEADLINE_EXCEEDED)); EXPECT_EQ(kTimeout, resp.status_code); } } // namespace cert_trans namespace { pid_t localhost_pid(0); pid_t nonlocalhost_pid(0); pid_t star_example_com_pid(0); pid_t binky_example_com_pid(0); pid_t example_com_pid(0); pid_t ip_address_pid(0); void KillAllOpenSSLServers() { kill(localhost_pid, SIGTERM); kill(nonlocalhost_pid, SIGTERM); kill(star_example_com_pid, SIGTERM); kill(binky_example_com_pid, SIGTERM); kill(example_com_pid, SIGTERM); kill(ip_address_pid, SIGTERM); waitpid(localhost_pid, nullptr, 0); waitpid(nonlocalhost_pid, nullptr, 0); waitpid(star_example_com_pid, nullptr, 0); waitpid(binky_example_com_pid, nullptr, 0); waitpid(example_com_pid, nullptr, 0); waitpid(ip_address_pid, nullptr, 0); } } // namespace int main(int argc, char** argv) { cert_trans::test::InitTesting(argv[0], &argc, &argv, true); OpenSSL_add_all_algorithms(); ERR_load_BIO_strings(); ERR_load_crypto_strings(); SSL_load_error_strings(); SSL_library_init(); signal(SIGPIPE, SIG_IGN); int hang_fd(socket(AF_INET, SOCK_STREAM, 0)); CHECK_NE(-1, hang_fd); CHECK_NE(-1, fcntl(hang_fd, F_SETFL, O_NONBLOCK)); struct sockaddr_in hang_addr; bzero((char*)&hang_addr, sizeof(hang_addr)); hang_addr.sin_family = AF_INET; hang_addr.sin_addr.s_addr = INADDR_ANY; hang_addr.sin_port = htons(cert_trans::kHangPort); CHECK_EQ(0, bind(hang_fd, reinterpret_cast<struct sockaddr*>(&hang_addr), sizeof(hang_addr))) << strerror(errno); CHECK_EQ(0, listen(hang_fd, 10)); struct sockaddr_in other_addr; socklen_t other_size; accept(hang_fd, reinterpret_cast<struct sockaddr*>(&other_addr), &other_size); localhost_pid = cert_trans::RunOpenSSLServer(cert_trans::kLocalHostPort, "localhost-cert.pem", "localhost-key.pem"); nonlocalhost_pid = cert_trans::RunOpenSSLServer(cert_trans::kNonLocalHostPort, "not-localhost-cert.pem", "not-localhost-key.pem"); star_example_com_pid = cert_trans::RunOpenSSLServer(cert_trans::kStarExampleComPort, "star_example_com-cert.pem", "star_example_com-key.pem"); binky_example_com_pid = cert_trans::RunOpenSSLServer(cert_trans::kBinkyExampleComPort, "binky_example_com-cert.pem", "binky_example_com-key.pem"); example_com_pid = cert_trans::RunOpenSSLServer(cert_trans::kExampleComPort, "example_com-cert.pem", "example_com-key.pem"); ip_address_pid = cert_trans::RunOpenSSLServer(cert_trans::k127_0_0_1Port, "127_0_0_1-cert.pem", "127_0_0_1-key.pem"); sleep(1); const int ret(RUN_ALL_TESTS()); KillAllOpenSSLServers(); close(hang_fd); return ret; } <|endoftext|>
<commit_before><commit_msg>getLibEnv always returned an empty string anyway so make it void instead<commit_after><|endoftext|>
<commit_before>#if OSL_DEBUG_LEVEL == 0 #define NDEBUG #endif #include <assert.h> #include <interface.hxx> #include <cstdio> #include <hash_map> #include <string> using namespace std; static hash_map< string, string >* pStringResources = NULL; static string getResFileName( const char* progname ) { string aRet = progname; size_t pos = aRet.rfind( '/' ); // FIXME: search PATH if necessary assert( pos != string::npos ); aRet.erase( pos ); aRet.append( "/resource/crash_dump.res" ); return aRet; } static void filterString( string& rString ) { static const char* pProductName = getenv( "PRODUCTNAME" ); static int nProductLen = pProductName ? strlen( pProductName ) : 0; static const char* pProductVersion = getenv( "PRODUCTVERSION" ); static int nVersionLen = pProductVersion ? strlen( pProductVersion ) : 0; // fill in eventually escaped characters string::size_type pos = 0; while( (pos = rString.find( '\\' ) ) != string::npos ) { char cRep = 0; switch( rString[pos+1] ) { case 't': cRep = '\t';break; case 'n': cRep = '\n';break; case 'r': cRep = '\r';break; case 'f': cRep = '\f';break; default: cRep = rString[pos+1]; } if( cRep ) rString.replace( pos, 2, &cRep, 1 ); } while( (pos = rString.find( '~' ) ) != string::npos ) { // replace mnemonic marker rString.replace( pos, 1, "_", 1 ); } while( (pos = rString.find( "%PRODUCTNAME%" ) ) != string::npos ) { rString.replace( pos, 13, pProductName ? pProductName : "OpenOffice" ); } while( (pos = rString.find( "%PRODUCTVERSION%" ) ) != string::npos ) { rString.replace( pos, 16, pProductVersion ? pProductVersion : "" ); } // remove whitespace at end pos = rString.find_last_not_of( "\r\n\t\f " ); if( pos != string::npos ) rString.erase( pos+1 ); } void StringResource::init( int argc, char** argv ) { pStringResources = new hash_map< string, string >(); string aResFile = getResFileName( argv[0] ); FILE* fp = fopen( aResFile.c_str(), "r" ); if( fp ) { char buf[4096]; string aKey; string aValue; while( ! feof( fp ) ) { if( ! fgets( buf, sizeof(buf), fp ) ) break; char* pEq = strchr( buf, '=' ); if( ! pEq || *(pEq+1) == 0 ) // invalid line continue; aKey = string(buf, pEq-buf); aValue = pEq+1; while( (aValue.empty() || aValue[ aValue.size()-1 ] != '\n') && ! feof( fp ) ) { if( fgets( buf, sizeof( buf ), fp ) ) aValue.append( buf ); } filterString( aValue ); (*pStringResources)[aKey] = aValue; } fclose( fp ); } } const char* StringResource::get( const char* pKey ) { hash_map< string, string >::const_iterator it = pStringResources->find( pKey ); return (it == pStringResources->end()) ? "" : it->second.c_str(); } <commit_msg>INTEGRATION: CWS geordi2q11 (1.1.64); FILE MERGED 2003/12/15 17:59:59 hr 1.1.64.1: #111934#: join CWS ooo111fix1<commit_after>/************************************************************************* * * $RCSfile: res.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2003-12-17 19:28:27 $ * * 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 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 * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #if OSL_DEBUG_LEVEL == 0 #define NDEBUG #endif #include <assert.h> #include <interface.hxx> #include <cstdio> #include <hash_map> #include <string> using namespace std; static hash_map< string, string >* pStringResources = NULL; static string getResFileName( const char* progname ) { string aRet = progname; size_t pos = aRet.rfind( '/' ); // FIXME: search PATH if necessary assert( pos != string::npos ); aRet.erase( pos ); aRet.append( "/resource/crash_dump.res" ); return aRet; } static void filterString( string& rString ) { static const char* pProductName = getenv( "PRODUCTNAME" ); static int nProductLen = pProductName ? strlen( pProductName ) : 0; static const char* pProductVersion = getenv( "PRODUCTVERSION" ); static int nVersionLen = pProductVersion ? strlen( pProductVersion ) : 0; // fill in eventually escaped characters string::size_type pos = 0; while( (pos = rString.find( '\\' ) ) != string::npos ) { char cRep = 0; switch( rString[pos+1] ) { case 't': cRep = '\t';break; case 'n': cRep = '\n';break; case 'r': cRep = '\r';break; case 'f': cRep = '\f';break; default: cRep = rString[pos+1]; } if( cRep ) rString.replace( pos, 2, &cRep, 1 ); } while( (pos = rString.find( '~' ) ) != string::npos ) { // replace mnemonic marker rString.replace( pos, 1, "_", 1 ); } while( (pos = rString.find( "%PRODUCTNAME%" ) ) != string::npos ) { rString.replace( pos, 13, pProductName ? pProductName : "OpenOffice" ); } while( (pos = rString.find( "%PRODUCTVERSION%" ) ) != string::npos ) { rString.replace( pos, 16, pProductVersion ? pProductVersion : "" ); } // remove whitespace at end pos = rString.find_last_not_of( "\r\n\t\f " ); if( pos != string::npos ) rString.erase( pos+1 ); } void StringResource::init( int argc, char** argv ) { pStringResources = new hash_map< string, string >(); string aResFile = getResFileName( argv[0] ); FILE* fp = fopen( aResFile.c_str(), "r" ); if( fp ) { char buf[4096]; string aKey; string aValue; while( ! feof( fp ) ) { if( ! fgets( buf, sizeof(buf), fp ) ) break; char* pEq = strchr( buf, '=' ); if( ! pEq || *(pEq+1) == 0 ) // invalid line continue; aKey = string(buf, pEq-buf); aValue = pEq+1; while( (aValue.empty() || aValue[ aValue.size()-1 ] != '\n') && ! feof( fp ) ) { if( fgets( buf, sizeof( buf ), fp ) ) aValue.append( buf ); } filterString( aValue ); (*pStringResources)[aKey] = aValue; } fclose( fp ); } } const char* StringResource::get( const char* pKey ) { hash_map< string, string >::const_iterator it = pStringResources->find( pKey ); return (it == pStringResources->end()) ? "" : it->second.c_str(); } <|endoftext|>
<commit_before>//@author A0097630B #include "stdafx.h" #include "parse_tree/show_query.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; namespace You { namespace NLP { namespace UnitTests { TEST_CLASS(ShowQueryTests) { TEST_METHOD(convertsToStream) { { std::wostringstream stream; stream << DUMMY; Assert::AreEqual( std::wstring(L"Show tasks (criteria none, sort by " L"Description ascending)"), stream.str()); } } TEST_METHOD(convertsToString) { Assert::AreEqual( std::wstring(L"Show tasks (criteria none, sort by " L"Description ascending)"), boost::lexical_cast<std::wstring>(DUMMY)); } TEST_METHOD(comparesEquality) { SHOW_QUERY local = DUMMY; Assert::AreEqual(DUMMY, local); } TEST_METHOD(comparesInequality) { SHOW_QUERY local { { SHOW_QUERY::FIELD_ORDER { TaskField::DESCRIPTION, SHOW_QUERY::Order::ASCENDING } } }; Assert::AreEqual(DUMMY, local); SHOW_QUERY local2 = local; local2.order.push_back(SHOW_QUERY::FIELD_ORDER { TaskField::DESCRIPTION }); Assert::AreNotEqual(DUMMY, local2); } private: /// A dummy object. static const SHOW_QUERY DUMMY; }; const SHOW_QUERY ShowQueryTests::DUMMY { { { TaskField::DESCRIPTION, SHOW_QUERY::Order::ASCENDING } } }; } // namespace UnitTests } // namespace NLP } // namespace You <commit_msg>Increase code coverage.<commit_after>//@author A0097630B #include "stdafx.h" #include "parse_tree/show_query.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; namespace You { namespace NLP { namespace UnitTests { TEST_CLASS(ShowQueryTests) { TEST_METHOD(convertsToStream) { { std::wostringstream stream; stream << DUMMY; Assert::AreEqual( std::wstring(L"Show tasks (criteria none, sort by " L"Description ascending)"), stream.str()); } } TEST_METHOD(convertsToString) { Assert::AreEqual( std::wstring(L"Show tasks (criteria none, sort by " L"Description ascending)"), boost::lexical_cast<std::wstring>(DUMMY)); } TEST_METHOD(comparesEquality) { SHOW_QUERY local = DUMMY; Assert::AreEqual(DUMMY, local); } TEST_METHOD(comparesInequality) { SHOW_QUERY local { { SHOW_QUERY::FIELD_ORDER { TaskField::DESCRIPTION, SHOW_QUERY::Order::ASCENDING } } }; Assert::AreEqual(DUMMY, local); local.order[0].field = TaskField::DEADLINE; Assert::AreNotEqual(DUMMY, local); SHOW_QUERY local2 = local; local2.order.push_back(SHOW_QUERY::FIELD_ORDER { TaskField::DESCRIPTION }); Assert::AreNotEqual(DUMMY, local2); } private: /// A dummy object. static const SHOW_QUERY DUMMY; }; const SHOW_QUERY ShowQueryTests::DUMMY { { { TaskField::DESCRIPTION, SHOW_QUERY::Order::ASCENDING } } }; } // namespace UnitTests } // namespace NLP } // namespace You <|endoftext|>
<commit_before>#include "Bootstrapper.hpp" #include "Connection.hpp" using Dissent::Utils::Timer; using Dissent::Utils::TimerCallback; using Dissent::Utils::TimerMethod; namespace Dissent { namespace Connections { Bootstrapper::Bootstrapper(ConnectionManager &cm, const QList<Address> &remote_endpoints) : ConnectionAcquirer(cm), _remote_endpoints(remote_endpoints), _bootstrap_event(0) { } Bootstrapper::~Bootstrapper() { if(_bootstrap_event) { _bootstrap_event->Stop(); delete _bootstrap_event; } } bool Bootstrapper::Start() { if(!ConnectionAcquirer::Start()) { return false; } Bootstrap(0); return true; } bool Bootstrapper::Stop() { if(!ConnectionAcquirer::Stop()) { return false; } if(_bootstrap_event) { _bootstrap_event->Stop(); delete _bootstrap_event; _bootstrap_event = 0; } return true; } void Bootstrapper::HandleConnection(Connection *con) { const Address &addr = con->GetEdge()->GetRemotePersistentAddress(); if(!_remote_endpoints.contains(addr)) { _remote_endpoints.append(addr); } QObject::connect(con, SIGNAL(Disconnected(const QString &)), this, SLOT(HandleDisconnect(const QString &))); } void Bootstrapper::HandleConnectionAttemptFailure(const Address &, const QString &) { Bootstrap(0); } void Bootstrapper::Bootstrap(const int &) { if(!NeedConnection()) { if(_bootstrap_event) { _bootstrap_event->Stop(); delete _bootstrap_event; _bootstrap_event = 0; } return; } else if(_bootstrap_event == 0) { TimerCallback *cb = new TimerMethod<Bootstrapper, int>(this, &Bootstrapper::Bootstrap, 0); _bootstrap_event = new TimerEvent(Timer::GetInstance().QueueCallback(cb, 5000, 5000)); } foreach(const Address &addr, _remote_endpoints) { GetConnectionManager().ConnectTo(addr); } } void Bootstrapper::HandleDisconnect(const QString &) { Bootstrap(0); } bool Bootstrapper::NeedConnection() { return GetConnectionManager().GetConnectionTable().GetConnections().count() == 1; } } } <commit_msg>[Connections] Bootstrapper::Bootstrap was running too frequently<commit_after>#include "Bootstrapper.hpp" #include "Connection.hpp" using Dissent::Utils::Timer; using Dissent::Utils::TimerCallback; using Dissent::Utils::TimerMethod; namespace Dissent { namespace Connections { Bootstrapper::Bootstrapper(ConnectionManager &cm, const QList<Address> &remote_endpoints) : ConnectionAcquirer(cm), _remote_endpoints(remote_endpoints), _bootstrap_event(0) { } Bootstrapper::~Bootstrapper() { if(_bootstrap_event) { _bootstrap_event->Stop(); delete _bootstrap_event; } } bool Bootstrapper::Start() { if(!ConnectionAcquirer::Start()) { return false; } Bootstrap(0); return true; } bool Bootstrapper::Stop() { if(!ConnectionAcquirer::Stop()) { return false; } if(_bootstrap_event) { _bootstrap_event->Stop(); delete _bootstrap_event; _bootstrap_event = 0; } return true; } void Bootstrapper::HandleConnection(Connection *con) { const Address &addr = con->GetEdge()->GetRemotePersistentAddress(); if(!_remote_endpoints.contains(addr)) { _remote_endpoints.append(addr); } QObject::connect(con, SIGNAL(Disconnected(const QString &)), this, SLOT(HandleDisconnect(const QString &))); } void Bootstrapper::HandleConnectionAttemptFailure(const Address &, const QString &) { Bootstrap(0); } void Bootstrapper::Bootstrap(const int &val) { if(!NeedConnection()) { if(_bootstrap_event) { _bootstrap_event->Stop(); delete _bootstrap_event; _bootstrap_event = 0; } return; } else if(_bootstrap_event == 0) { TimerCallback *cb = new TimerMethod<Bootstrapper, int>(this, &Bootstrapper::Bootstrap, -1); _bootstrap_event = new TimerEvent(Timer::GetInstance().QueueCallback(cb, 5000, 5000)); } else if(val != -1) { return; } foreach(const Address &addr, _remote_endpoints) { GetConnectionManager().ConnectTo(addr); } } void Bootstrapper::HandleDisconnect(const QString &) { Bootstrap(0); } bool Bootstrapper::NeedConnection() { return GetConnectionManager().GetConnectionTable().GetConnections().count() == 1; } } } <|endoftext|>
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "Framework.h" #include "Profiler.h" #include "IRenderer.h" #include "CoreException.h" #include "Application.h" #include "VersionInfo.h" #include "ConfigAPI.h" #include "PluginAPI.h" #include "LoggingFunctions.h" #include "IModule.h" #include "FrameAPI.h" #include "InputAPI.h" #include "AssetAPI.h" #include "AudioAPI.h" #include "ConsoleAPI.h" #include "SceneAPI.h" #include "UiAPI.h" #include "UiMainWindow.h" #ifndef _WINDOWS #include <sys/ioctl.h> #endif #include <iostream> #include <QDir> #include "MemoryLeakCheck.h" /// Temporary utility structure for storing supported command line parameters and their descriptions. struct CommandLineParameterMap { /// Prints the structure to std::cout. void Print() const { QMap<QString, QString>::const_iterator it = commands.begin(); while(it != commands.end()) { int charIdx = 0; const int treshold = 15; // Max line width is fixed 80 chars on Windows, but can vary on *nix. #ifdef _WINDOWS const int maxLineWidth = 80; #else struct winsize w; ioctl(0, TIOCGWINSZ, &w); const int maxLineWidth = (int)w.ws_row; #endif int cmdLength = it.key().length(); std::cout << it.key().toStdString(); if (cmdLength >= treshold) { std::cout << std::endl; for(charIdx = 0; charIdx < treshold ; ++charIdx) std::cout << " "; } else for(charIdx = cmdLength; charIdx < treshold ; ++charIdx) std::cout << " "; for(int i = 0; i < it.value().length(); ++i) { std::cout << it.value()[i].toAscii(); ++charIdx; if (charIdx >= maxLineWidth) { charIdx = 0; for(charIdx; charIdx < treshold ; ++charIdx) std::cout << " "; } } std::cout << std::endl; ++it; } } QMap<QString, QString> commands; }; Framework *Framework::instance = 0; Framework::Framework(int argc, char** argv) : exit_signal_(false), argc_(argc), argv_(argv), headless_(false), application(0), frame(0), console(0), scene(0), input(0), asset(0), audio(0), plugin(0), config(0), ui(0), #ifdef PROFILING profiler(0), #endif renderer(0), apiVersionInfo(0), applicationVersionInfo(0) { // Remember this Framework instance in a static pointer. Note that this does not help visibility for external DLL code linking to Framework. instance = this; // Api/Application name and version. Can be accessed via ApiVersionInfo() and ApplicationVersionInfo(). /// @note Modify these values when you are making a custom Tundra. Also the version needs to be changed here on releases. apiVersionInfo = new ApiVersionInfo(2, 0, 0, 0); applicationVersionInfo = new ApplicationVersionInfo(2, 0, 0, 0, "realXtend", "Tundra"); CommandLineParameterMap cmdLineDescs; ///\todo Make it possible for modules to know when "--help" command was issued and list the command line parameters they support. ///\todo Remove non-Framework parameters from the list below. cmdLineDescs.commands["--help"] = "Produce help message"; // Framework cmdLineDescs.commands["--headless"] = "Run in headless mode without any windows or rendering"; // Framework & OgreRenderingModule cmdLineDescs.commands["--disablerunonload"] = "Do not start script applications (EC_Script's with applicationName defined) automatically"; //JavascriptModule cmdLineDescs.commands["--server"] = "Start Tundra server"; // TundraLogicModule cmdLineDescs.commands["--port"] = "Start server in the specified port"; // TundraLogicModule cmdLineDescs.commands["--protocol"] = "Start server with the specified protocol. Options: '--protocol tcp' and '--protocol udp'. Defaults to tcp if no protocol is spesified."; // KristalliProtocolModule cmdLineDescs.commands["--fpslimit"] = "Specifies the fps cap to use in rendering. Default: 60. Pass in 0 to disable"; // OgreRenderingModule cmdLineDescs.commands["--run"] = "Run script on startup"; // JavaScriptModule cmdLineDescs.commands["--file"] = "Load scene on startup. Accepts absolute and relative paths, local:// and http:// are accepted and fetched via the AssetAPI."; // TundraLogicModule & AssetModule cmdLineDescs.commands["--storage"] = "Adds the given directory as a local storage directory on startup"; // AssetModule cmdLineDescs.commands["--config"] = "Specifies the startup configration file to use"; // Framework cmdLineDescs.commands["--login"] = "Automatically login to server using provided data. Url syntax: {tundra|http|https}://host[:port]/?username=x[&password=y&avatarurl=z&protocol={udp|tcp}]. Minimum information needed to try a connection in the url are host and username"; cmdLineDescs.commands["--netrate"] = "Specifies the number of network updates per second. Default: 30."; // TundraLogicModule cmdLineDescs.commands["--clear-asset-cache"] = "At the start of Tundra, remove all data and metadata files from asset cache."; if (HasCommandLineParameter("--help")) { std::cout << "Supported command line arguments: " << std::endl; cmdLineDescs.Print(); Exit(); } else { if (HasCommandLineParameter("--headless")) headless_ = true; #ifdef PROFILING profiler = new Profiler(); PROFILE(FW_Startup); #endif profilerQObj = new ProfilerQObj; // Create ConfigAPI, pass application data and prepare data folder. config = new ConfigAPI(this); config->PrepareDataFolder("configuration"); // Create QApplication application = new Application(this, argc_, argv_); // Create core APIs frame = new FrameAPI(this); scene = new SceneAPI(this); asset = new AssetAPI(this, headless_); if (!HasCommandLineParameter("--noassetcache")) asset->OpenAssetCache(Application::UserDataDirectory() + QDir::separator() + "assetcache"); ui = new UiAPI(this); audio = new AudioAPI(this, asset); // AudioAPI depends on the AssetAPI, so must be loaded after it. input = new InputAPI(this); plugin = new PluginAPI(this); console = new ConsoleAPI(this); console->RegisterCommand("exit", "Shuts down gracefully.", this, SLOT(Exit())); // Initialize SceneAPI. scene->Initialise(); RegisterDynamicObject("ui", ui); RegisterDynamicObject("frame", frame); RegisterDynamicObject("input", input); RegisterDynamicObject("console", console); RegisterDynamicObject("asset", asset); RegisterDynamicObject("audio", audio); RegisterDynamicObject("application", application); RegisterDynamicObject("config", config); RegisterDynamicObject("apiversion", apiVersionInfo); RegisterDynamicObject("applicationversion", applicationVersionInfo); RegisterDynamicObject("profiler", profilerQObj); } } Framework::~Framework() { SAFE_DELETE(input); SAFE_DELETE(asset); SAFE_DELETE(audio); SAFE_DELETE(plugin); #ifdef PROFILING SAFE_DELETE(profiler); #endif SAFE_DELETE(profilerQObj); SAFE_DELETE(console); SAFE_DELETE(scene); SAFE_DELETE(frame); SAFE_DELETE(ui); SAFE_DELETE(apiVersionInfo); SAFE_DELETE(applicationVersionInfo); // This delete must be the last one in Framework since application derives QApplication. // When we delete QApplication, we must have ensured that all QObjects have been deleted. /// \bug Framework is itself a QObject and we should delete application only after Framework has been deleted. A refactor is required. delete application; } void Framework::ProcessOneFrame() { if (exit_signal_ == true) return; // We've accidentally ended up to update a frame, but we're actually quitting. PROFILE(Framework_ProcessOneFrame); static tick_t clock_freq; static tick_t last_clocktime; if (!last_clocktime) last_clocktime = GetCurrentClockTime(); if (!clock_freq) clock_freq = GetCurrentClockFreq(); tick_t curr_clocktime = GetCurrentClockTime(); double frametime = ((double)curr_clocktime - (double)last_clocktime) / (double) clock_freq; last_clocktime = curr_clocktime; for(size_t i = 0; i < modules.size(); ++i) { try { #ifdef PROFILING ProfilerSection ps(("Module_" + modules[i]->Name() + "_Update").c_str()); #endif modules[i]->Update(frametime); } catch(const std::exception &e) { std::cout << "ProcessOneFrame caught an exception while updating module " << modules[i]->Name() << ": " << (e.what() ? e.what() : "(null)") << std::endl; LogError(std::string("ProcessOneFrame caught an exception while updating module " + modules[i]->Name() + ": " + (e.what() ? e.what() : "(null)"))); } catch(...) { std::cout << "ProcessOneFrame caught an unknown exception while updating module " << modules[i]->Name() << std::endl; LogError(std::string("ProcessOneFrame caught an unknown exception while updating module " + modules[i]->Name())); } } asset->Update(frametime); input->Update(frametime); audio->Update(frametime); console->Update(frametime); frame->Update(frametime); if (renderer) renderer->Render(frametime); } void Framework::Go() { // Check if we were never supposed to run if (exit_signal_) return; srand(time(0)); plugin->LoadPluginsFromXML(plugin->ConfigurationFile()); for(size_t i = 0; i < modules.size(); ++i) { LogDebug("Initializing module " + modules[i]->Name()); modules[i]->Initialize(); } // Run our QApplication subclass. application->Go(); // Qt main loop execution has ended, we are exiting. exit_signal_ = true; for(size_t i = 0; i < modules.size(); ++i) { LogDebug("Uninitializing module " + modules[i]->Name()); modules[i]->Uninitialize(); } // Deinitialize all core APIs. scene->Reset(); asset->Reset(); console->Reset(); frame->Reset(); input->SaveKeyBindingsToFile(); input->Reset(); audio->Reset(); for(size_t i = 0; i < modules.size(); ++i) { LogDebug("Unloading module " + modules[i]->Name()); modules[i]->Unload(); } // Delete all modules. modules.clear(); // Now that each module has been deleted, they've closed all their windows as well. Tear down the main UI. ui->Reset(); // Actually unload all DLL plugins from memory. plugin->UnloadPlugins(); } void Framework::Exit() { exit_signal_ = true; if (application) application->AboutToExit(); } void Framework::ForceExit() { exit_signal_ = true; if (application) application->quit(); } void Framework::CancelExit() { exit_signal_ = false; // Our main loop is stopped when we are exiting, // we need to start it back up again if something canceled the exit. if (application) application->UpdateFrame(); } Application *Framework::App() const { return application; } #ifdef PROFILING Profiler *Framework::GetProfiler() const { return profiler; } #endif FrameAPI *Framework::Frame() const { return frame; } InputAPI *Framework::Input() const { return input; } UiAPI *Framework::Ui() const { return ui; } ConsoleAPI *Framework::Console() const { return console; } AudioAPI *Framework::Audio() const { return audio; } AssetAPI *Framework::Asset() const { return asset; } SceneAPI *Framework::Scene() const { return scene; } ConfigAPI *Framework::Config() const { return config; } /* ConnectionAPI *Framework::Connection() const { return connection; } ServerAPI *Framework::Server() const { return server; } */ PluginAPI *Framework::Plugins() const { return plugin; } IRenderer *Framework::Renderer() const { return renderer; } ApiVersionInfo *Framework::ApiVersion() const { return apiVersionInfo; } ApplicationVersionInfo *Framework::ApplicationVersion() const { return applicationVersionInfo; } void Framework::RegisterRenderer(IRenderer *renderer_) { renderer = renderer_; } void Framework::RegisterModule(IModule *module) { module->SetFramework(this); modules.push_back(boost::shared_ptr<IModule>(module)); module->Load(); } IModule *Framework::GetModuleByName(const QString &name) const { for(size_t i = 0; i < modules.size(); ++i) if (modules[i]->Name() == name.toStdString()) return modules[i].get(); return 0; } bool Framework::RegisterDynamicObject(QString name, QObject *object) { if (name.length() == 0 || !object) return false; // We never override a property if it already exists. if (property(name.toStdString().c_str()).isValid()) return false; setProperty(name.toStdString().c_str(), QVariant::fromValue<QObject*>(object)); return true; } bool Framework::HasCommandLineParameter(const QString &value) const { for(int i = 0; i < argc_; ++i) if (QString(argv_[i]) == value) return true; return false; } QStringList Framework::CommandLineParameters(const QString &key) const { QStringList ret; for(int i = 0; i < argc_; ++i) if (QString(argv_[i]) == key && i+1 < argc_ && !QString(argv_[i+1]).startsWith("--")) ret.append(argv_[++i]); return ret; } <commit_msg>Init profilerQObj to null in Framework ctor. Otherwise application crashes on exit when running tundra --help.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "Framework.h" #include "Profiler.h" #include "IRenderer.h" #include "CoreException.h" #include "Application.h" #include "VersionInfo.h" #include "ConfigAPI.h" #include "PluginAPI.h" #include "LoggingFunctions.h" #include "IModule.h" #include "FrameAPI.h" #include "InputAPI.h" #include "AssetAPI.h" #include "AudioAPI.h" #include "ConsoleAPI.h" #include "SceneAPI.h" #include "UiAPI.h" #include "UiMainWindow.h" #ifndef _WINDOWS #include <sys/ioctl.h> #endif #include <iostream> #include <QDir> #include "MemoryLeakCheck.h" /// Temporary utility structure for storing supported command line parameters and their descriptions. struct CommandLineParameterMap { /// Prints the structure to std::cout. void Print() const { QMap<QString, QString>::const_iterator it = commands.begin(); while(it != commands.end()) { int charIdx = 0; const int treshold = 15; // Max line width is fixed 80 chars on Windows, but can vary on *nix. #ifdef _WINDOWS const int maxLineWidth = 80; #else struct winsize w; ioctl(0, TIOCGWINSZ, &w); const int maxLineWidth = (int)w.ws_row; #endif int cmdLength = it.key().length(); std::cout << it.key().toStdString(); if (cmdLength >= treshold) { std::cout << std::endl; for(charIdx = 0; charIdx < treshold ; ++charIdx) std::cout << " "; } else for(charIdx = cmdLength; charIdx < treshold ; ++charIdx) std::cout << " "; for(int i = 0; i < it.value().length(); ++i) { std::cout << it.value()[i].toAscii(); ++charIdx; if (charIdx >= maxLineWidth) { charIdx = 0; for(charIdx; charIdx < treshold ; ++charIdx) std::cout << " "; } } std::cout << std::endl; ++it; } } QMap<QString, QString> commands; }; Framework *Framework::instance = 0; Framework::Framework(int argc, char** argv) : exit_signal_(false), argc_(argc), argv_(argv), headless_(false), application(0), frame(0), console(0), scene(0), input(0), asset(0), audio(0), plugin(0), config(0), ui(0), #ifdef PROFILING profiler(0), #endif profilerQObj(0), renderer(0), apiVersionInfo(0), applicationVersionInfo(0) { // Remember this Framework instance in a static pointer. Note that this does not help visibility for external DLL code linking to Framework. instance = this; // Api/Application name and version. Can be accessed via ApiVersionInfo() and ApplicationVersionInfo(). /// @note Modify these values when you are making a custom Tundra. Also the version needs to be changed here on releases. apiVersionInfo = new ApiVersionInfo(2, 0, 0, 0); applicationVersionInfo = new ApplicationVersionInfo(2, 0, 0, 0, "realXtend", "Tundra"); CommandLineParameterMap cmdLineDescs; ///\todo Make it possible for modules to know when "--help" command was issued and list the command line parameters they support. ///\todo Remove non-Framework parameters from the list below. cmdLineDescs.commands["--help"] = "Produce help message"; // Framework cmdLineDescs.commands["--headless"] = "Run in headless mode without any windows or rendering"; // Framework & OgreRenderingModule cmdLineDescs.commands["--disablerunonload"] = "Do not start script applications (EC_Script's with applicationName defined) automatically"; //JavascriptModule cmdLineDescs.commands["--server"] = "Start Tundra server"; // TundraLogicModule cmdLineDescs.commands["--port"] = "Start server in the specified port"; // TundraLogicModule cmdLineDescs.commands["--protocol"] = "Start server with the specified protocol. Options: '--protocol tcp' and '--protocol udp'. Defaults to tcp if no protocol is spesified."; // KristalliProtocolModule cmdLineDescs.commands["--fpslimit"] = "Specifies the fps cap to use in rendering. Default: 60. Pass in 0 to disable"; // OgreRenderingModule cmdLineDescs.commands["--run"] = "Run script on startup"; // JavaScriptModule cmdLineDescs.commands["--file"] = "Load scene on startup. Accepts absolute and relative paths, local:// and http:// are accepted and fetched via the AssetAPI."; // TundraLogicModule & AssetModule cmdLineDescs.commands["--storage"] = "Adds the given directory as a local storage directory on startup"; // AssetModule cmdLineDescs.commands["--config"] = "Specifies the startup configration file to use"; // Framework cmdLineDescs.commands["--login"] = "Automatically login to server using provided data. Url syntax: {tundra|http|https}://host[:port]/?username=x[&password=y&avatarurl=z&protocol={udp|tcp}]. Minimum information needed to try a connection in the url are host and username"; cmdLineDescs.commands["--netrate"] = "Specifies the number of network updates per second. Default: 30."; // TundraLogicModule cmdLineDescs.commands["--clear-asset-cache"] = "At the start of Tundra, remove all data and metadata files from asset cache."; if (HasCommandLineParameter("--help")) { std::cout << "Supported command line arguments: " << std::endl; cmdLineDescs.Print(); Exit(); } else { if (HasCommandLineParameter("--headless")) headless_ = true; #ifdef PROFILING profiler = new Profiler(); PROFILE(FW_Startup); #endif profilerQObj = new ProfilerQObj; // Create ConfigAPI, pass application data and prepare data folder. config = new ConfigAPI(this); config->PrepareDataFolder("configuration"); // Create QApplication application = new Application(this, argc_, argv_); // Create core APIs frame = new FrameAPI(this); scene = new SceneAPI(this); asset = new AssetAPI(this, headless_); if (!HasCommandLineParameter("--noassetcache")) asset->OpenAssetCache(Application::UserDataDirectory() + QDir::separator() + "assetcache"); ui = new UiAPI(this); audio = new AudioAPI(this, asset); // AudioAPI depends on the AssetAPI, so must be loaded after it. input = new InputAPI(this); plugin = new PluginAPI(this); console = new ConsoleAPI(this); console->RegisterCommand("exit", "Shuts down gracefully.", this, SLOT(Exit())); // Initialize SceneAPI. scene->Initialise(); RegisterDynamicObject("ui", ui); RegisterDynamicObject("frame", frame); RegisterDynamicObject("input", input); RegisterDynamicObject("console", console); RegisterDynamicObject("asset", asset); RegisterDynamicObject("audio", audio); RegisterDynamicObject("application", application); RegisterDynamicObject("config", config); RegisterDynamicObject("apiversion", apiVersionInfo); RegisterDynamicObject("applicationversion", applicationVersionInfo); RegisterDynamicObject("profiler", profilerQObj); } } Framework::~Framework() { SAFE_DELETE(input); SAFE_DELETE(asset); SAFE_DELETE(audio); SAFE_DELETE(plugin); #ifdef PROFILING SAFE_DELETE(profiler); #endif SAFE_DELETE(profilerQObj); SAFE_DELETE(console); SAFE_DELETE(scene); SAFE_DELETE(frame); SAFE_DELETE(ui); SAFE_DELETE(apiVersionInfo); SAFE_DELETE(applicationVersionInfo); // This delete must be the last one in Framework since application derives QApplication. // When we delete QApplication, we must have ensured that all QObjects have been deleted. /// \bug Framework is itself a QObject and we should delete application only after Framework has been deleted. A refactor is required. delete application; } void Framework::ProcessOneFrame() { if (exit_signal_ == true) return; // We've accidentally ended up to update a frame, but we're actually quitting. PROFILE(Framework_ProcessOneFrame); static tick_t clock_freq; static tick_t last_clocktime; if (!last_clocktime) last_clocktime = GetCurrentClockTime(); if (!clock_freq) clock_freq = GetCurrentClockFreq(); tick_t curr_clocktime = GetCurrentClockTime(); double frametime = ((double)curr_clocktime - (double)last_clocktime) / (double) clock_freq; last_clocktime = curr_clocktime; for(size_t i = 0; i < modules.size(); ++i) { try { #ifdef PROFILING ProfilerSection ps(("Module_" + modules[i]->Name() + "_Update").c_str()); #endif modules[i]->Update(frametime); } catch(const std::exception &e) { std::cout << "ProcessOneFrame caught an exception while updating module " << modules[i]->Name() << ": " << (e.what() ? e.what() : "(null)") << std::endl; LogError(std::string("ProcessOneFrame caught an exception while updating module " + modules[i]->Name() + ": " + (e.what() ? e.what() : "(null)"))); } catch(...) { std::cout << "ProcessOneFrame caught an unknown exception while updating module " << modules[i]->Name() << std::endl; LogError(std::string("ProcessOneFrame caught an unknown exception while updating module " + modules[i]->Name())); } } asset->Update(frametime); input->Update(frametime); audio->Update(frametime); console->Update(frametime); frame->Update(frametime); if (renderer) renderer->Render(frametime); } void Framework::Go() { // Check if we were never supposed to run if (exit_signal_) return; srand(time(0)); plugin->LoadPluginsFromXML(plugin->ConfigurationFile()); for(size_t i = 0; i < modules.size(); ++i) { LogDebug("Initializing module " + modules[i]->Name()); modules[i]->Initialize(); } // Run our QApplication subclass. application->Go(); // Qt main loop execution has ended, we are exiting. exit_signal_ = true; for(size_t i = 0; i < modules.size(); ++i) { LogDebug("Uninitializing module " + modules[i]->Name()); modules[i]->Uninitialize(); } // Deinitialize all core APIs. scene->Reset(); asset->Reset(); console->Reset(); frame->Reset(); input->SaveKeyBindingsToFile(); input->Reset(); audio->Reset(); for(size_t i = 0; i < modules.size(); ++i) { LogDebug("Unloading module " + modules[i]->Name()); modules[i]->Unload(); } // Delete all modules. modules.clear(); // Now that each module has been deleted, they've closed all their windows as well. Tear down the main UI. ui->Reset(); // Actually unload all DLL plugins from memory. plugin->UnloadPlugins(); } void Framework::Exit() { exit_signal_ = true; if (application) application->AboutToExit(); } void Framework::ForceExit() { exit_signal_ = true; if (application) application->quit(); } void Framework::CancelExit() { exit_signal_ = false; // Our main loop is stopped when we are exiting, // we need to start it back up again if something canceled the exit. if (application) application->UpdateFrame(); } Application *Framework::App() const { return application; } #ifdef PROFILING Profiler *Framework::GetProfiler() const { return profiler; } #endif FrameAPI *Framework::Frame() const { return frame; } InputAPI *Framework::Input() const { return input; } UiAPI *Framework::Ui() const { return ui; } ConsoleAPI *Framework::Console() const { return console; } AudioAPI *Framework::Audio() const { return audio; } AssetAPI *Framework::Asset() const { return asset; } SceneAPI *Framework::Scene() const { return scene; } ConfigAPI *Framework::Config() const { return config; } /* ConnectionAPI *Framework::Connection() const { return connection; } ServerAPI *Framework::Server() const { return server; } */ PluginAPI *Framework::Plugins() const { return plugin; } IRenderer *Framework::Renderer() const { return renderer; } ApiVersionInfo *Framework::ApiVersion() const { return apiVersionInfo; } ApplicationVersionInfo *Framework::ApplicationVersion() const { return applicationVersionInfo; } void Framework::RegisterRenderer(IRenderer *renderer_) { renderer = renderer_; } void Framework::RegisterModule(IModule *module) { module->SetFramework(this); modules.push_back(boost::shared_ptr<IModule>(module)); module->Load(); } IModule *Framework::GetModuleByName(const QString &name) const { for(size_t i = 0; i < modules.size(); ++i) if (modules[i]->Name() == name.toStdString()) return modules[i].get(); return 0; } bool Framework::RegisterDynamicObject(QString name, QObject *object) { if (name.length() == 0 || !object) return false; // We never override a property if it already exists. if (property(name.toStdString().c_str()).isValid()) return false; setProperty(name.toStdString().c_str(), QVariant::fromValue<QObject*>(object)); return true; } bool Framework::HasCommandLineParameter(const QString &value) const { for(int i = 0; i < argc_; ++i) if (QString(argv_[i]) == value) return true; return false; } QStringList Framework::CommandLineParameters(const QString &key) const { QStringList ret; for(int i = 0; i < argc_; ++i) if (QString(argv_[i]) == key && i+1 < argc_ && !QString(argv_[i+1]).startsWith("--")) ret.append(argv_[++i]); return ret; } <|endoftext|>
<commit_before>// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. #pragma once /*! \file rx-skip.cpp \brief Make new observable with skipped first count items from this observable. \tparam Count the type of the items counter \param t the number of items to skip \return An observable that is identical to the source observable except that it does not emit the first t items that the source observable emits. \sample \snippet skip.cpp skip sample \snippet output.txt skip sample */ #if !defined(RXCPP_OPERATORS_RX_SKIP_HPP) #define RXCPP_OPERATORS_RX_SKIP_HPP #include "../rx-includes.hpp" namespace rxcpp { namespace operators { namespace detail { template<class... AN> struct skip_invalid_arguments {}; template<class... AN> struct skip_invalid : public rxo::operator_base<skip_invalid_arguments<AN...>> { using type = observable<skip_invalid_arguments<AN...>, skip_invalid<AN...>>; }; template<class... AN> using skip_invalid_t = typename skip_invalid<AN...>::type; template<class T, class Observable, class Count> struct skip : public operator_base<T> { typedef rxu::decay_t<Observable> source_type; typedef rxu::decay_t<Count> count_type; struct values { values(source_type s, count_type t) : source(std::move(s)) , count(std::move(t)) { } source_type source; count_type count; }; values initial; skip(source_type s, count_type t) : initial(std::move(s), std::move(t)) { } struct mode { enum type { skipping, // ignore messages triggered, // capture messages errored, // error occured stopped // observable completed }; }; template<class Subscriber> void on_subscribe(const Subscriber& s) const { typedef Subscriber output_type; struct state_type : public std::enable_shared_from_this<state_type> , public values { state_type(const values& i, const output_type& oarg) : values(i) , mode_value(i.count > 0 ? mode::skipping : mode::triggered) , out(oarg) { } typename mode::type mode_value; output_type out; }; // take a copy of the values for each subscription auto state = std::make_shared<state_type>(initial, s); composite_subscription source_lifetime; s.add(source_lifetime); state->source.subscribe( // split subscription lifetime source_lifetime, // on_next [state](T t) { if (state->mode_value == mode::skipping) { if (--state->count == 0) { state->mode_value = mode::triggered; } } else { state->out.on_next(t); } }, // on_error [state](std::exception_ptr e) { state->mode_value = mode::errored; state->out.on_error(e); }, // on_completed [state]() { state->mode_value = mode::stopped; state->out.on_completed(); } ); } }; } /*! @copydoc rx-skip.hpp */ template<class... AN> auto skip(AN&&... an) -> operator_factory<skip_tag, AN...> { return operator_factory<skip_tag, AN...>(std::make_tuple(std::forward<AN>(an)...)); } } template<> struct member_overload<skip_tag> { template<class Observable, class Count, class Enabled = rxu::enable_if_all_true_type_t< is_observable<Observable>>, class SourceValue = rxu::value_type_t<Observable>, class Skip = rxo::detail::skip<SourceValue, rxu::decay_t<Observable>, rxu::decay_t<Count>>, class Value = rxu::value_type_t<Skip>, class Result = observable<Value, Skip>> static Result member(Observable&& o, Count&& c) { return Result(Skip(std::forward<Observable>(o), std::forward<Count>(c))); } template<class... AN> static operators::detail::skip_invalid_t<AN...> member(AN...) { std::terminate(); return {}; static_assert(sizeof...(AN) == 10000, "skip takes (optional Count)"); } }; } #endif <commit_msg>fix documentation typo in skip<commit_after>// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. #pragma once /*! \file rx-skip.hpp \brief Make new observable with skipped first count items from this observable. \tparam Count the type of the items counter \param t the number of items to skip \return An observable that is identical to the source observable except that it does not emit the first t items that the source observable emits. \sample \snippet skip.cpp skip sample \snippet output.txt skip sample */ #if !defined(RXCPP_OPERATORS_RX_SKIP_HPP) #define RXCPP_OPERATORS_RX_SKIP_HPP #include "../rx-includes.hpp" namespace rxcpp { namespace operators { namespace detail { template<class... AN> struct skip_invalid_arguments {}; template<class... AN> struct skip_invalid : public rxo::operator_base<skip_invalid_arguments<AN...>> { using type = observable<skip_invalid_arguments<AN...>, skip_invalid<AN...>>; }; template<class... AN> using skip_invalid_t = typename skip_invalid<AN...>::type; template<class T, class Observable, class Count> struct skip : public operator_base<T> { typedef rxu::decay_t<Observable> source_type; typedef rxu::decay_t<Count> count_type; struct values { values(source_type s, count_type t) : source(std::move(s)) , count(std::move(t)) { } source_type source; count_type count; }; values initial; skip(source_type s, count_type t) : initial(std::move(s), std::move(t)) { } struct mode { enum type { skipping, // ignore messages triggered, // capture messages errored, // error occured stopped // observable completed }; }; template<class Subscriber> void on_subscribe(const Subscriber& s) const { typedef Subscriber output_type; struct state_type : public std::enable_shared_from_this<state_type> , public values { state_type(const values& i, const output_type& oarg) : values(i) , mode_value(i.count > 0 ? mode::skipping : mode::triggered) , out(oarg) { } typename mode::type mode_value; output_type out; }; // take a copy of the values for each subscription auto state = std::make_shared<state_type>(initial, s); composite_subscription source_lifetime; s.add(source_lifetime); state->source.subscribe( // split subscription lifetime source_lifetime, // on_next [state](T t) { if (state->mode_value == mode::skipping) { if (--state->count == 0) { state->mode_value = mode::triggered; } } else { state->out.on_next(t); } }, // on_error [state](std::exception_ptr e) { state->mode_value = mode::errored; state->out.on_error(e); }, // on_completed [state]() { state->mode_value = mode::stopped; state->out.on_completed(); } ); } }; } /*! @copydoc rx-skip.hpp */ template<class... AN> auto skip(AN&&... an) -> operator_factory<skip_tag, AN...> { return operator_factory<skip_tag, AN...>(std::make_tuple(std::forward<AN>(an)...)); } } template<> struct member_overload<skip_tag> { template<class Observable, class Count, class Enabled = rxu::enable_if_all_true_type_t< is_observable<Observable>>, class SourceValue = rxu::value_type_t<Observable>, class Skip = rxo::detail::skip<SourceValue, rxu::decay_t<Observable>, rxu::decay_t<Count>>, class Value = rxu::value_type_t<Skip>, class Result = observable<Value, Skip>> static Result member(Observable&& o, Count&& c) { return Result(Skip(std::forward<Observable>(o), std::forward<Count>(c))); } template<class... AN> static operators::detail::skip_invalid_t<AN...> member(AN...) { std::terminate(); return {}; static_assert(sizeof...(AN) == 10000, "skip takes (optional Count)"); } }; } #endif <|endoftext|>
<commit_before> // NetherFortGen.cpp // Implements the cNetherFortGen class representing the nether fortress generator #include "Globals.h" #include "NetherFortGen.h" #include "Prefabs/NetherFortPrefabs.h" static const int NEIGHBORHOOD_SIZE = 3; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // cNetherFortGen::cNetherFort: class cNetherFortGen::cNetherFort { public: cNetherFortGen & m_ParentGen; int m_BlockX, m_BlockZ; int m_GridSize; int m_Seed; cPlacedPieces m_Pieces; cNetherFort(cNetherFortGen & a_ParentGen, int a_BlockX, int a_BlockZ, int a_GridSize, int a_MaxDepth, int a_Seed) : m_ParentGen(a_ParentGen), m_BlockX(a_BlockX), m_BlockZ(a_BlockZ), m_GridSize(a_GridSize), m_Seed(a_Seed) { // TODO: Proper Y-coord placement int BlockY = 64; // Generate pieces: cBFSPieceGenerator pg(m_ParentGen, a_Seed); pg.PlacePieces(a_BlockX, BlockY, a_BlockZ, a_MaxDepth, m_Pieces); } /** Carves the system into the chunk data */ void ProcessChunk(cChunkDesc & a_Chunk) { for (cPlacedPieces::const_iterator itr = m_Pieces.begin(), end = m_Pieces.end(); itr != end; ++itr) { const cPrefab & Prefab = (const cPrefab &)((*itr)->GetPiece()); Prefab.Draw(a_Chunk, *itr); } // for itr - m_PlacedPieces[] } }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // cNetherFortGen: cNetherFortGen::cNetherFortGen(int a_Seed, int a_GridSize, int a_MaxDepth) : m_Seed(a_Seed), m_Noise(a_Seed), m_GridSize(a_GridSize), m_MaxDepth(a_MaxDepth) { // Initialize the prefabs: for (size_t i = 0; i < g_NetherFortPrefabs1Count; i++) { cPrefab * Prefab = new cPrefab(g_NetherFortPrefabs1[i]); m_AllPieces.push_back(Prefab); if (Prefab->HasConnectorType(0)) { m_OuterPieces.push_back(Prefab); } if (Prefab->HasConnectorType(1)) { m_InnerPieces.push_back(Prefab); } } // Initialize the starting piece prefabs: for (size_t i = 0; i < g_NetherFortStartingPrefabs1Count; i++) { m_StartingPieces.push_back(new cPrefab(g_NetherFortStartingPrefabs1[i])); } // DEBUG: Try one round of placement: cPlacedPieces Pieces; cBFSPieceGenerator pg(*this, a_Seed); pg.PlacePieces(0, 64, 0, a_MaxDepth, Pieces); } cNetherFortGen::~cNetherFortGen() { ClearCache(); for (cPieces::iterator itr = m_AllPieces.begin(), end = m_AllPieces.end(); itr != end; ++itr) { delete *itr; } // for itr - m_AllPieces[] m_AllPieces.clear(); } void cNetherFortGen::ClearCache(void) { // TODO } void cNetherFortGen::GetFortsForChunk(int a_ChunkX, int a_ChunkZ, cNetherForts & a_Forts) { int BaseX = a_ChunkX * cChunkDef::Width / m_GridSize; int BaseZ = a_ChunkZ * cChunkDef::Width / m_GridSize; if (BaseX < 0) { --BaseX; } if (BaseZ < 0) { --BaseZ; } BaseX -= NEIGHBORHOOD_SIZE / 2; BaseZ -= NEIGHBORHOOD_SIZE / 2; // Walk the cache, move each cave system that we want into a_Forts: int StartX = BaseX * m_GridSize; int EndX = (BaseX + NEIGHBORHOOD_SIZE + 1) * m_GridSize; int StartZ = BaseZ * m_GridSize; int EndZ = (BaseZ + NEIGHBORHOOD_SIZE + 1) * m_GridSize; for (cNetherForts::iterator itr = m_Cache.begin(), end = m_Cache.end(); itr != end;) { if ( ((*itr)->m_BlockX >= StartX) && ((*itr)->m_BlockX < EndX) && ((*itr)->m_BlockZ >= StartZ) && ((*itr)->m_BlockZ < EndZ) ) { // want a_Forts.push_back(*itr); itr = m_Cache.erase(itr); } else { // don't want ++itr; } } // for itr - m_Cache[] // Create those forts that haven't been in the cache: for (int x = 0; x < NEIGHBORHOOD_SIZE; x++) { int RealX = (BaseX + x) * m_GridSize; for (int z = 0; z < NEIGHBORHOOD_SIZE; z++) { int RealZ = (BaseZ + z) * m_GridSize; bool Found = false; for (cNetherForts::const_iterator itr = a_Forts.begin(), end = a_Forts.end(); itr != end; ++itr) { if (((*itr)->m_BlockX == RealX) && ((*itr)->m_BlockZ == RealZ)) { Found = true; break; } } // for itr - a_Mineshafts if (!Found) { a_Forts.push_back(new cNetherFort(*this, RealX, RealZ, m_GridSize, m_MaxDepth, m_Seed)); } } // for z } // for x // Copy a_Forts into m_Cache to the beginning: cNetherForts FortsCopy (a_Forts); m_Cache.splice(m_Cache.begin(), FortsCopy, FortsCopy.begin(), FortsCopy.end()); // Trim the cache if it's too long: if (m_Cache.size() > 100) { cNetherForts::iterator itr = m_Cache.begin(); std::advance(itr, 100); for (cNetherForts::iterator end = m_Cache.end(); itr != end; ++itr) { delete *itr; } itr = m_Cache.begin(); std::advance(itr, 100); m_Cache.erase(itr, m_Cache.end()); } } void cNetherFortGen::GenFinish(cChunkDesc & a_ChunkDesc) { int ChunkX = a_ChunkDesc.GetChunkX(); int ChunkZ = a_ChunkDesc.GetChunkZ(); cNetherForts Forts; GetFortsForChunk(ChunkX, ChunkZ, Forts); for (cNetherForts::const_iterator itr = Forts.begin(); itr != Forts.end(); ++itr) { (*itr)->ProcessChunk(a_ChunkDesc); } // for itr - Forts[] } cPieces cNetherFortGen::GetPiecesWithConnector(int a_ConnectorType) { switch (a_ConnectorType) { case 0: return m_OuterPieces; case 1: return m_InnerPieces; default: return cPieces(); } } cPieces cNetherFortGen::GetStartingPieces(void) { return m_StartingPieces; } void cNetherFortGen::PiecePlaced(const cPiece & a_Piece) { UNUSED(a_Piece); } void cNetherFortGen::Reset(void) { // Nothing needed } <commit_msg>Fixed a memory leak in NetherFortGen.<commit_after> // NetherFortGen.cpp // Implements the cNetherFortGen class representing the nether fortress generator #include "Globals.h" #include "NetherFortGen.h" #include "Prefabs/NetherFortPrefabs.h" static const int NEIGHBORHOOD_SIZE = 3; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // cNetherFortGen::cNetherFort: class cNetherFortGen::cNetherFort { public: cNetherFortGen & m_ParentGen; int m_BlockX, m_BlockZ; int m_GridSize; int m_Seed; cPlacedPieces m_Pieces; cNetherFort(cNetherFortGen & a_ParentGen, int a_BlockX, int a_BlockZ, int a_GridSize, int a_MaxDepth, int a_Seed) : m_ParentGen(a_ParentGen), m_BlockX(a_BlockX), m_BlockZ(a_BlockZ), m_GridSize(a_GridSize), m_Seed(a_Seed) { // TODO: Proper Y-coord placement int BlockY = 64; // Generate pieces: cBFSPieceGenerator pg(m_ParentGen, a_Seed); pg.PlacePieces(a_BlockX, BlockY, a_BlockZ, a_MaxDepth, m_Pieces); } ~cNetherFort() { cPieceGenerator::FreePieces(m_Pieces); } /** Carves the system into the chunk data */ void ProcessChunk(cChunkDesc & a_Chunk) { for (cPlacedPieces::const_iterator itr = m_Pieces.begin(), end = m_Pieces.end(); itr != end; ++itr) { const cPrefab & Prefab = (const cPrefab &)((*itr)->GetPiece()); Prefab.Draw(a_Chunk, *itr); } // for itr - m_PlacedPieces[] } }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // cNetherFortGen: cNetherFortGen::cNetherFortGen(int a_Seed, int a_GridSize, int a_MaxDepth) : m_Seed(a_Seed), m_Noise(a_Seed), m_GridSize(a_GridSize), m_MaxDepth(a_MaxDepth) { // Initialize the prefabs: for (size_t i = 0; i < g_NetherFortPrefabs1Count; i++) { cPrefab * Prefab = new cPrefab(g_NetherFortPrefabs1[i]); m_AllPieces.push_back(Prefab); if (Prefab->HasConnectorType(0)) { m_OuterPieces.push_back(Prefab); } if (Prefab->HasConnectorType(1)) { m_InnerPieces.push_back(Prefab); } } // Initialize the starting piece prefabs: for (size_t i = 0; i < g_NetherFortStartingPrefabs1Count; i++) { m_StartingPieces.push_back(new cPrefab(g_NetherFortStartingPrefabs1[i])); } // DEBUG: Try one round of placement: cPlacedPieces Pieces; cBFSPieceGenerator pg(*this, a_Seed); pg.PlacePieces(0, 64, 0, a_MaxDepth, Pieces); } cNetherFortGen::~cNetherFortGen() { ClearCache(); for (cPieces::iterator itr = m_AllPieces.begin(), end = m_AllPieces.end(); itr != end; ++itr) { delete *itr; } // for itr - m_AllPieces[] m_AllPieces.clear(); } void cNetherFortGen::ClearCache(void) { // TODO } void cNetherFortGen::GetFortsForChunk(int a_ChunkX, int a_ChunkZ, cNetherForts & a_Forts) { int BaseX = a_ChunkX * cChunkDef::Width / m_GridSize; int BaseZ = a_ChunkZ * cChunkDef::Width / m_GridSize; if (BaseX < 0) { --BaseX; } if (BaseZ < 0) { --BaseZ; } BaseX -= NEIGHBORHOOD_SIZE / 2; BaseZ -= NEIGHBORHOOD_SIZE / 2; // Walk the cache, move each cave system that we want into a_Forts: int StartX = BaseX * m_GridSize; int EndX = (BaseX + NEIGHBORHOOD_SIZE + 1) * m_GridSize; int StartZ = BaseZ * m_GridSize; int EndZ = (BaseZ + NEIGHBORHOOD_SIZE + 1) * m_GridSize; for (cNetherForts::iterator itr = m_Cache.begin(), end = m_Cache.end(); itr != end;) { if ( ((*itr)->m_BlockX >= StartX) && ((*itr)->m_BlockX < EndX) && ((*itr)->m_BlockZ >= StartZ) && ((*itr)->m_BlockZ < EndZ) ) { // want a_Forts.push_back(*itr); itr = m_Cache.erase(itr); } else { // don't want ++itr; } } // for itr - m_Cache[] // Create those forts that haven't been in the cache: for (int x = 0; x < NEIGHBORHOOD_SIZE; x++) { int RealX = (BaseX + x) * m_GridSize; for (int z = 0; z < NEIGHBORHOOD_SIZE; z++) { int RealZ = (BaseZ + z) * m_GridSize; bool Found = false; for (cNetherForts::const_iterator itr = a_Forts.begin(), end = a_Forts.end(); itr != end; ++itr) { if (((*itr)->m_BlockX == RealX) && ((*itr)->m_BlockZ == RealZ)) { Found = true; break; } } // for itr - a_Mineshafts if (!Found) { a_Forts.push_back(new cNetherFort(*this, RealX, RealZ, m_GridSize, m_MaxDepth, m_Seed)); } } // for z } // for x // Copy a_Forts into m_Cache to the beginning: cNetherForts FortsCopy (a_Forts); m_Cache.splice(m_Cache.begin(), FortsCopy, FortsCopy.begin(), FortsCopy.end()); // Trim the cache if it's too long: if (m_Cache.size() > 100) { cNetherForts::iterator itr = m_Cache.begin(); std::advance(itr, 100); for (cNetherForts::iterator end = m_Cache.end(); itr != end; ++itr) { delete *itr; } itr = m_Cache.begin(); std::advance(itr, 100); m_Cache.erase(itr, m_Cache.end()); } } void cNetherFortGen::GenFinish(cChunkDesc & a_ChunkDesc) { int ChunkX = a_ChunkDesc.GetChunkX(); int ChunkZ = a_ChunkDesc.GetChunkZ(); cNetherForts Forts; GetFortsForChunk(ChunkX, ChunkZ, Forts); for (cNetherForts::const_iterator itr = Forts.begin(); itr != Forts.end(); ++itr) { (*itr)->ProcessChunk(a_ChunkDesc); } // for itr - Forts[] } cPieces cNetherFortGen::GetPiecesWithConnector(int a_ConnectorType) { switch (a_ConnectorType) { case 0: return m_OuterPieces; case 1: return m_InnerPieces; default: return cPieces(); } } cPieces cNetherFortGen::GetStartingPieces(void) { return m_StartingPieces; } void cNetherFortGen::PiecePlaced(const cPiece & a_Piece) { UNUSED(a_Piece); } void cNetherFortGen::Reset(void) { // Nothing needed } <|endoftext|>
<commit_before>// Setup for tests that use result of stl namespace test. #if defined(KWSYS_STL_HAVE_STD) # if KWSYS_STL_HAVE_STD # define kwsys_stl std # else # define kwsys_stl # endif #endif #ifdef TEST_KWSYS_STL_HAVE_STD #include <list> void f(std::list<int>*) {} int main() { return 0; } #endif #ifdef TEST_KWSYS_IOS_USE_ANSI #include <iosfwd> int main() { return 0; } #endif #ifdef TEST_KWSYS_IOS_HAVE_STD #include <iosfwd> void f(std::ostream*) {} int main() { return 0; } #endif #ifdef TEST_KWSYS_IOS_USE_SSTREAM #include <sstream> int main() { return 0; } #endif #ifdef TEST_KWSYS_IOS_USE_STRSTREAM_H #include <strstream.h> int main() { return 0; } #endif #ifdef TEST_KWSYS_IOS_USE_STRSTREA_H #include <strstrea.h> int main() { return 0; } #endif #ifdef TEST_KWSYS_STL_STRING_HAVE_OSTREAM # include <iostream.h> # include <string> void f(ostream& os, const kwsys_stl::string& s) { os << s; } int main() { return 0; } #endif #ifdef TEST_KWSYS_STL_STRING_HAVE_ISTREAM # include <iostream.h> # include <string> void f(istream& is, kwsys_stl::string& s) { is >> s; } int main() { return 0; } #endif #ifdef TEST_KWSYS_STL_STRING_HAVE_NEQ_CHAR # include <string> bool f(const kwsys_stl::string& s) { return s != ""; } int main() { return 0; } #endif #ifdef TEST_KWSYS_CXX_HAS_CSTDDEF #include <cstddef> void f(size_t) {} int main() { return 0; } #endif #ifdef TEST_KWSYS_CXX_HAS_NULL_TEMPLATE_ARGS template <class T> class A; template <class T> int f(A<T>&); template <class T> class A { public: // "friend int f<>(A<T>&)" would conform friend int f(A<T>&); private: int x; }; template <class T> int f(A<T>& a) { return a.x = 0; } template int f(A<int>&); int main() { A<int> a; return f(a); } #endif #ifdef TEST_KWSYS_CXX_HAS_MEMBER_TEMPLATES template <class U> class A { public: U u; A(): u(0) {} template <class V> V m(V* p) { return *p = u; } }; int main() { A<short> a; int s = 1; return a.m(&s); } #endif #ifdef TEST_KWSYS_CXX_HAS_FULL_SPECIALIZATION template <class T> struct A {}; template <> struct A<int*> { static int f() { return 0; } }; int main() { return A<int*>::f(); } #endif #ifdef TEST_KWSYS_CXX_HAS_ARGUMENT_DEPENDENT_LOOKUP namespace N { class A {}; int f(A*) { return 0; } } void f(void*); int main() { N::A* a = 0; return f(a); } #endif #ifdef TEST_KWSYS_STL_HAS_ITERATOR_TRAITS #include <iterator> void f(kwsys_stl::iterator_traits<int*>::iterator_category const&) {} int main() { return 0; } #endif #ifdef TEST_KWSYS_STL_HAS_ITERATOR_CATEGORY #include <iterator> void f(int* x) { kwsys_stl::iterator_category(x); } int main() { return 0; } #endif #ifdef TEST_KWSYS_STL_HAS___ITERATOR_CATEGORY #include <iterator> void f(int* x) { kwsys_stl::__iterator_category(x); } int main() { return 0; } #endif #ifdef TEST_KWSYS_STL_HAS_ALLOCATOR_NONTEMPLATE #include <memory> void f(kwsys_stl::allocator const&) {} int main() { return 0; } #endif #ifdef TEST_KWSYS_STL_HAS_ALLOCATOR_REBIND #include <memory> template <class T, class Alloc> void f(const T&, const Alloc&) { typedef typename Alloc::template rebind<T>::other alloc_type; }; int main() { f(0, kwsys_stl::allocator<char>()); return 0; } #endif #ifdef TEST_KWSYS_STL_HAS_ALLOCATOR_MAX_SIZE_ARGUMENT #include <memory> void f(kwsys_stl::allocator<char> const& a) { a.max_size(sizeof(int)); }; int main() { f(kwsys_stl::allocator<char>()); return 0; } #endif #ifdef TEST_KWSYS_STAT_HAS_ST_MTIM #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> int main() { struct stat stat1; (void)stat1.st_mtim.tv_sec; (void)stat1.st_mtim.tv_nsec; return 0; } #endif <commit_msg>BUG: Fix iterator traits test to use a real iterator instead of int*.<commit_after>// Setup for tests that use result of stl namespace test. #if defined(KWSYS_STL_HAVE_STD) # if KWSYS_STL_HAVE_STD # define kwsys_stl std # else # define kwsys_stl # endif #endif #ifdef TEST_KWSYS_STL_HAVE_STD #include <list> void f(std::list<int>*) {} int main() { return 0; } #endif #ifdef TEST_KWSYS_IOS_USE_ANSI #include <iosfwd> int main() { return 0; } #endif #ifdef TEST_KWSYS_IOS_HAVE_STD #include <iosfwd> void f(std::ostream*) {} int main() { return 0; } #endif #ifdef TEST_KWSYS_IOS_USE_SSTREAM #include <sstream> int main() { return 0; } #endif #ifdef TEST_KWSYS_IOS_USE_STRSTREAM_H #include <strstream.h> int main() { return 0; } #endif #ifdef TEST_KWSYS_IOS_USE_STRSTREA_H #include <strstrea.h> int main() { return 0; } #endif #ifdef TEST_KWSYS_STL_STRING_HAVE_OSTREAM # include <iostream.h> # include <string> void f(ostream& os, const kwsys_stl::string& s) { os << s; } int main() { return 0; } #endif #ifdef TEST_KWSYS_STL_STRING_HAVE_ISTREAM # include <iostream.h> # include <string> void f(istream& is, kwsys_stl::string& s) { is >> s; } int main() { return 0; } #endif #ifdef TEST_KWSYS_STL_STRING_HAVE_NEQ_CHAR # include <string> bool f(const kwsys_stl::string& s) { return s != ""; } int main() { return 0; } #endif #ifdef TEST_KWSYS_CXX_HAS_CSTDDEF #include <cstddef> void f(size_t) {} int main() { return 0; } #endif #ifdef TEST_KWSYS_CXX_HAS_NULL_TEMPLATE_ARGS template <class T> class A; template <class T> int f(A<T>&); template <class T> class A { public: // "friend int f<>(A<T>&)" would conform friend int f(A<T>&); private: int x; }; template <class T> int f(A<T>& a) { return a.x = 0; } template int f(A<int>&); int main() { A<int> a; return f(a); } #endif #ifdef TEST_KWSYS_CXX_HAS_MEMBER_TEMPLATES template <class U> class A { public: U u; A(): u(0) {} template <class V> V m(V* p) { return *p = u; } }; int main() { A<short> a; int s = 1; return a.m(&s); } #endif #ifdef TEST_KWSYS_CXX_HAS_FULL_SPECIALIZATION template <class T> struct A {}; template <> struct A<int*> { static int f() { return 0; } }; int main() { return A<int*>::f(); } #endif #ifdef TEST_KWSYS_CXX_HAS_ARGUMENT_DEPENDENT_LOOKUP namespace N { class A {}; int f(A*) { return 0; } } void f(void*); int main() { N::A* a = 0; return f(a); } #endif #ifdef TEST_KWSYS_STL_HAS_ITERATOR_TRAITS #include <iterator> #include <list> void f(kwsys_stl::iterator_traits<kwsys_stl::list<int>::iterator>::iterator_category const&) {} int main() { return 0; } #endif #ifdef TEST_KWSYS_STL_HAS_ITERATOR_CATEGORY #include <iterator> #include <list> void f(kwsys_stl::list<int>::iterator x) { kwsys_stl::iterator_category(x); } int main() { return 0; } #endif #ifdef TEST_KWSYS_STL_HAS___ITERATOR_CATEGORY #include <iterator> #include <list> void f(kwsys_stl::list<int>::iterator x) { kwsys_stl::__iterator_category(x); } int main() { return 0; } #endif #ifdef TEST_KWSYS_STL_HAS_ALLOCATOR_NONTEMPLATE #include <memory> void f(kwsys_stl::allocator const&) {} int main() { return 0; } #endif #ifdef TEST_KWSYS_STL_HAS_ALLOCATOR_REBIND #include <memory> template <class T, class Alloc> void f(const T&, const Alloc&) { typedef typename Alloc::template rebind<T>::other alloc_type; }; int main() { f(0, kwsys_stl::allocator<char>()); return 0; } #endif #ifdef TEST_KWSYS_STL_HAS_ALLOCATOR_MAX_SIZE_ARGUMENT #include <memory> void f(kwsys_stl::allocator<char> const& a) { a.max_size(sizeof(int)); }; int main() { f(kwsys_stl::allocator<char>()); return 0; } #endif #ifdef TEST_KWSYS_STAT_HAS_ST_MTIM #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> int main() { struct stat stat1; (void)stat1.st_mtim.tv_sec; (void)stat1.st_mtim.tv_nsec; return 0; } #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2011, Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "bindings/v8/ScriptProfiler.h" #include "V8ArrayBufferView.h" #include "V8DOMWindow.h" #include "V8Node.h" #include "bindings/v8/RetainedDOMInfo.h" #include "bindings/v8/ScriptObject.h" #include "bindings/v8/V8Binding.h" #include "bindings/v8/V8DOMWrapper.h" #include "bindings/v8/WrapperTypeInfo.h" #include "core/dom/Document.h" #include "core/dom/WebCoreMemoryInstrumentation.h" #include "core/inspector/BindingVisitors.h" #include <v8-profiler.h> #include <v8.h> #include "wtf/ThreadSpecific.h" namespace WebCore { typedef HashMap<String, double> ProfileNameIdleTimeMap; void ScriptProfiler::start(const String& title) { ProfileNameIdleTimeMap* profileNameIdleTimeMap = ScriptProfiler::currentProfileNameIdleTimeMap(); if (profileNameIdleTimeMap->contains(title)) return; profileNameIdleTimeMap->add(title, 0); v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::CpuProfiler* profiler = isolate->GetCpuProfiler(); if (!profiler) return; v8::HandleScope handleScope(isolate); profiler->StartCpuProfiling(v8String(title, isolate), true); } PassRefPtr<ScriptProfile> ScriptProfiler::stop(const String& title) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::CpuProfiler* profiler = isolate->GetCpuProfiler(); if (!profiler) return 0; v8::HandleScope handleScope(isolate); const v8::CpuProfile* profile = profiler->StopCpuProfiling(v8String(title, isolate)); if (!profile) return 0; String profileTitle = toWebCoreString(profile->GetTitle()); double idleTime = 0.0; ProfileNameIdleTimeMap* profileNameIdleTimeMap = ScriptProfiler::currentProfileNameIdleTimeMap(); ProfileNameIdleTimeMap::iterator profileIdleTime = profileNameIdleTimeMap->find(profileTitle); if (profileIdleTime != profileNameIdleTimeMap->end()) { idleTime = profileIdleTime->value * 1000.0; profileNameIdleTimeMap->remove(profileIdleTime); } return ScriptProfile::create(profile, idleTime); } void ScriptProfiler::collectGarbage() { v8::V8::LowMemoryNotification(); } ScriptObject ScriptProfiler::objectByHeapObjectId(unsigned id) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HeapProfiler* profiler = isolate->GetHeapProfiler(); if (!profiler) return ScriptObject(); // As ids are unique, it doesn't matter which HeapSnapshot owns HeapGraphNode. // We need to find first HeapSnapshot containing a node with the specified id. const v8::HeapGraphNode* node = 0; for (int i = 0, l = profiler->GetSnapshotCount(); i < l; ++i) { const v8::HeapSnapshot* snapshot = profiler->GetHeapSnapshot(i); node = snapshot->GetNodeById(id); if (node) break; } if (!node) return ScriptObject(); v8::HandleScope handleScope(isolate); v8::Handle<v8::Value> value = node->GetHeapValue(); if (!value->IsObject()) return ScriptObject(); v8::Handle<v8::Object> object = value.As<v8::Object>(); if (object->InternalFieldCount() >= v8DefaultWrapperInternalFieldCount) { v8::Handle<v8::Value> wrapper = object->GetInternalField(v8DOMWrapperObjectIndex); // Skip wrapper boilerplates which are like regular wrappers but don't have // native object. if (!wrapper.IsEmpty() && wrapper->IsUndefined()) return ScriptObject(); } ScriptState* scriptState = ScriptState::forContext(object->CreationContext()); return ScriptObject(scriptState, object); } unsigned ScriptProfiler::getHeapObjectId(const ScriptValue& value) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HeapProfiler* profiler = isolate->GetHeapProfiler(); v8::SnapshotObjectId id = profiler->GetObjectId(value.v8Value()); return id; } namespace { class ActivityControlAdapter : public v8::ActivityControl { public: ActivityControlAdapter(ScriptProfiler::HeapSnapshotProgress* progress) : m_progress(progress), m_firstReport(true) { } ControlOption ReportProgressValue(int done, int total) { ControlOption result = m_progress->isCanceled() ? kAbort : kContinue; if (m_firstReport) { m_firstReport = false; m_progress->Start(total); } else m_progress->Worked(done); if (done >= total) m_progress->Done(); return result; } private: ScriptProfiler::HeapSnapshotProgress* m_progress; bool m_firstReport; }; class GlobalObjectNameResolver : public v8::HeapProfiler::ObjectNameResolver { public: virtual const char* GetName(v8::Handle<v8::Object> object) { if (V8DOMWrapper::isWrapperOfType(object, &V8DOMWindow::info)) { DOMWindow* window = V8DOMWindow::toNative(object); if (window) { CString url = window->document()->url().string().utf8(); m_strings.append(url); return url.data(); } } return 0; } private: Vector<CString> m_strings; }; } // namespace void ScriptProfiler::startTrackingHeapObjects() { v8::Isolate::GetCurrent()->GetHeapProfiler()->StartTrackingHeapObjects(); } namespace { class HeapStatsStream : public v8::OutputStream { public: HeapStatsStream(ScriptProfiler::OutputStream* stream) : m_stream(stream) { } virtual void EndOfStream() OVERRIDE { } virtual WriteResult WriteAsciiChunk(char* data, int size) OVERRIDE { ASSERT(false); return kAbort; } virtual WriteResult WriteHeapStatsChunk(v8::HeapStatsUpdate* updateData, int count) OVERRIDE { Vector<uint32_t> rawData(count * 3); for (int i = 0; i < count; ++i) { int offset = i * 3; rawData[offset] = updateData[i].index; rawData[offset + 1] = updateData[i].count; rawData[offset + 2] = updateData[i].size; } m_stream->write(rawData.data(), rawData.size()); return kContinue; } private: ScriptProfiler::OutputStream* m_stream; }; } unsigned ScriptProfiler::requestHeapStatsUpdate(ScriptProfiler::OutputStream* stream) { HeapStatsStream heapStatsStream(stream); return v8::Isolate::GetCurrent()->GetHeapProfiler()->GetHeapStats(&heapStatsStream); } void ScriptProfiler::stopTrackingHeapObjects() { v8::Isolate::GetCurrent()->GetHeapProfiler()->StopTrackingHeapObjects(); } // FIXME: This method should receive a ScriptState, from which we should retrieve an Isolate. PassRefPtr<ScriptHeapSnapshot> ScriptProfiler::takeHeapSnapshot(const String& title, HeapSnapshotProgress* control) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HeapProfiler* profiler = isolate->GetHeapProfiler(); if (!profiler) return 0; v8::HandleScope handleScope(isolate); ASSERT(control); ActivityControlAdapter adapter(control); GlobalObjectNameResolver resolver; const v8::HeapSnapshot* snapshot = profiler->TakeHeapSnapshot(v8String(title, isolate), &adapter, &resolver); return snapshot ? ScriptHeapSnapshot::create(snapshot) : 0; } static v8::RetainedObjectInfo* retainedDOMInfo(uint16_t classId, v8::Handle<v8::Value> wrapper) { ASSERT(classId == v8DOMNodeClassId); if (!wrapper->IsObject()) return 0; Node* node = V8Node::toNative(wrapper.As<v8::Object>()); return node ? new RetainedDOMInfo(node) : 0; } void ScriptProfiler::initialize() { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HeapProfiler* profiler = isolate->GetHeapProfiler(); if (profiler) profiler->SetWrapperClassInfoProvider(v8DOMNodeClassId, &retainedDOMInfo); } void ScriptProfiler::visitNodeWrappers(WrappedNodeVisitor* visitor) { // visitNodeWrappers() should receive a ScriptState and retrieve an Isolate // from the ScriptState. v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handleScope(isolate); class DOMNodeWrapperVisitor : public v8::PersistentHandleVisitor { public: DOMNodeWrapperVisitor(WrappedNodeVisitor* visitor, v8::Isolate* isolate) : m_visitor(visitor) , m_isolate(isolate) { } virtual void VisitPersistentHandle(v8::Persistent<v8::Value> value, uint16_t classId) OVERRIDE { if (classId != v8DOMNodeClassId) return; UNUSED_PARAM(m_isolate); ASSERT(V8Node::HasInstance(value, m_isolate, worldType(m_isolate))); ASSERT(value->IsObject()); #ifdef V8_USE_UNSAFE_HANDLES v8::Persistent<v8::Object> wrapper = v8::Persistent<v8::Object>::Cast(value); #else v8::Persistent<v8::Object>& wrapper = v8::Persistent<v8::Object>::Cast(value); #endif m_visitor->visitNode(V8Node::toNative(wrapper)); } private: WrappedNodeVisitor* m_visitor; v8::Isolate* m_isolate; } wrapperVisitor(visitor, isolate); v8::V8::VisitHandlesWithClassIds(&wrapperVisitor); } void ScriptProfiler::visitExternalStrings(ExternalStringVisitor* visitor) { V8PerIsolateData::current()->visitExternalStrings(visitor); } void ScriptProfiler::visitExternalArrays(ExternalArrayVisitor* visitor) { class DOMObjectWrapperVisitor : public v8::PersistentHandleVisitor { public: explicit DOMObjectWrapperVisitor(ExternalArrayVisitor* visitor) : m_visitor(visitor) { } virtual void VisitPersistentHandle(v8::Persistent<v8::Value> value, uint16_t classId) OVERRIDE { if (classId != v8DOMObjectClassId) return; ASSERT(value->IsObject()); #ifdef V8_USE_UNSAFE_HANDLES v8::Persistent<v8::Object> wrapper = v8::Persistent<v8::Object>::Cast(value); #else v8::Persistent<v8::Object>& wrapper = v8::Persistent<v8::Object>::Cast(value); #endif if (!toWrapperTypeInfo(wrapper)->isSubclass(&V8ArrayBufferView::info)) return; m_visitor->visitJSExternalArray(V8ArrayBufferView::toNative(wrapper)); } private: ExternalArrayVisitor* m_visitor; } wrapperVisitor(visitor); v8::V8::VisitHandlesWithClassIds(&wrapperVisitor); } void ScriptProfiler::collectBindingMemoryInfo(MemoryInstrumentation* instrumentation) { V8PerIsolateData* data = V8PerIsolateData::current(); instrumentation->addRootObject(data); } size_t ScriptProfiler::profilerSnapshotsSize() { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HeapProfiler* profiler = isolate->GetHeapProfiler(); if (!profiler) return 0; return profiler->GetProfilerMemorySize(); } ProfileNameIdleTimeMap* ScriptProfiler::currentProfileNameIdleTimeMap() { AtomicallyInitializedStatic(WTF::ThreadSpecific<ProfileNameIdleTimeMap>*, map = new WTF::ThreadSpecific<ProfileNameIdleTimeMap>); return *map; } } // namespace WebCore <commit_msg>Fix r151732.<commit_after>/* * Copyright (c) 2011, Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "bindings/v8/ScriptProfiler.h" #include "V8ArrayBufferView.h" #include "V8DOMWindow.h" #include "V8Node.h" #include "bindings/v8/RetainedDOMInfo.h" #include "bindings/v8/ScriptObject.h" #include "bindings/v8/V8Binding.h" #include "bindings/v8/V8DOMWrapper.h" #include "bindings/v8/WrapperTypeInfo.h" #include "core/dom/Document.h" #include "core/dom/WebCoreMemoryInstrumentation.h" #include "core/inspector/BindingVisitors.h" #include <v8-profiler.h> #include <v8.h> #include "wtf/ThreadSpecific.h" namespace WebCore { typedef HashMap<String, double> ProfileNameIdleTimeMap; void ScriptProfiler::start(const String& title) { ProfileNameIdleTimeMap* profileNameIdleTimeMap = ScriptProfiler::currentProfileNameIdleTimeMap(); if (profileNameIdleTimeMap->contains(title)) return; profileNameIdleTimeMap->add(title, 0); v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::CpuProfiler* profiler = isolate->GetCpuProfiler(); if (!profiler) return; v8::HandleScope handleScope(isolate); profiler->StartCpuProfiling(v8String(title, isolate), true); } PassRefPtr<ScriptProfile> ScriptProfiler::stop(const String& title) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::CpuProfiler* profiler = isolate->GetCpuProfiler(); if (!profiler) return 0; v8::HandleScope handleScope(isolate); const v8::CpuProfile* profile = profiler->StopCpuProfiling(v8String(title, isolate)); if (!profile) return 0; String profileTitle = toWebCoreString(profile->GetTitle()); double idleTime = 0.0; ProfileNameIdleTimeMap* profileNameIdleTimeMap = ScriptProfiler::currentProfileNameIdleTimeMap(); ProfileNameIdleTimeMap::iterator profileIdleTime = profileNameIdleTimeMap->find(profileTitle); if (profileIdleTime != profileNameIdleTimeMap->end()) { idleTime = profileIdleTime->value * 1000.0; profileNameIdleTimeMap->remove(profileIdleTime); } return ScriptProfile::create(profile, idleTime); } void ScriptProfiler::collectGarbage() { v8::V8::LowMemoryNotification(); } ScriptObject ScriptProfiler::objectByHeapObjectId(unsigned id) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HeapProfiler* profiler = isolate->GetHeapProfiler(); if (!profiler) return ScriptObject(); // As ids are unique, it doesn't matter which HeapSnapshot owns HeapGraphNode. // We need to find first HeapSnapshot containing a node with the specified id. const v8::HeapGraphNode* node = 0; for (int i = 0, l = profiler->GetSnapshotCount(); i < l; ++i) { const v8::HeapSnapshot* snapshot = profiler->GetHeapSnapshot(i); node = snapshot->GetNodeById(id); if (node) break; } if (!node) return ScriptObject(); v8::HandleScope handleScope(isolate); v8::Handle<v8::Value> value = node->GetHeapValue(); if (!value->IsObject()) return ScriptObject(); v8::Handle<v8::Object> object = value.As<v8::Object>(); if (object->InternalFieldCount() >= v8DefaultWrapperInternalFieldCount) { v8::Handle<v8::Value> wrapper = object->GetInternalField(v8DOMWrapperObjectIndex); // Skip wrapper boilerplates which are like regular wrappers but don't have // native object. if (!wrapper.IsEmpty() && wrapper->IsUndefined()) return ScriptObject(); } ScriptState* scriptState = ScriptState::forContext(object->CreationContext()); return ScriptObject(scriptState, object); } unsigned ScriptProfiler::getHeapObjectId(const ScriptValue& value) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HeapProfiler* profiler = isolate->GetHeapProfiler(); v8::SnapshotObjectId id = profiler->GetObjectId(value.v8Value()); return id; } namespace { class ActivityControlAdapter : public v8::ActivityControl { public: ActivityControlAdapter(ScriptProfiler::HeapSnapshotProgress* progress) : m_progress(progress), m_firstReport(true) { } ControlOption ReportProgressValue(int done, int total) { ControlOption result = m_progress->isCanceled() ? kAbort : kContinue; if (m_firstReport) { m_firstReport = false; m_progress->Start(total); } else m_progress->Worked(done); if (done >= total) m_progress->Done(); return result; } private: ScriptProfiler::HeapSnapshotProgress* m_progress; bool m_firstReport; }; class GlobalObjectNameResolver : public v8::HeapProfiler::ObjectNameResolver { public: virtual const char* GetName(v8::Handle<v8::Object> object) { if (V8DOMWrapper::isWrapperOfType(object, &V8DOMWindow::info)) { DOMWindow* window = V8DOMWindow::toNative(object); if (window) { CString url = window->document()->url().string().utf8(); m_strings.append(url); return url.data(); } } return 0; } private: Vector<CString> m_strings; }; } // namespace void ScriptProfiler::startTrackingHeapObjects() { v8::Isolate::GetCurrent()->GetHeapProfiler()->StartTrackingHeapObjects(); } namespace { class HeapStatsStream : public v8::OutputStream { public: HeapStatsStream(ScriptProfiler::OutputStream* stream) : m_stream(stream) { } virtual void EndOfStream() OVERRIDE { } virtual WriteResult WriteAsciiChunk(char* data, int size) OVERRIDE { ASSERT(false); return kAbort; } virtual WriteResult WriteHeapStatsChunk(v8::HeapStatsUpdate* updateData, int count) OVERRIDE { Vector<uint32_t> rawData(count * 3); for (int i = 0; i < count; ++i) { int offset = i * 3; rawData[offset] = updateData[i].index; rawData[offset + 1] = updateData[i].count; rawData[offset + 2] = updateData[i].size; } m_stream->write(rawData.data(), rawData.size()); return kContinue; } private: ScriptProfiler::OutputStream* m_stream; }; } unsigned ScriptProfiler::requestHeapStatsUpdate(ScriptProfiler::OutputStream* stream) { HeapStatsStream heapStatsStream(stream); return v8::Isolate::GetCurrent()->GetHeapProfiler()->GetHeapStats(&heapStatsStream); } void ScriptProfiler::stopTrackingHeapObjects() { v8::Isolate::GetCurrent()->GetHeapProfiler()->StopTrackingHeapObjects(); } // FIXME: This method should receive a ScriptState, from which we should retrieve an Isolate. PassRefPtr<ScriptHeapSnapshot> ScriptProfiler::takeHeapSnapshot(const String& title, HeapSnapshotProgress* control) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HeapProfiler* profiler = isolate->GetHeapProfiler(); if (!profiler) return 0; v8::HandleScope handleScope(isolate); ASSERT(control); ActivityControlAdapter adapter(control); GlobalObjectNameResolver resolver; const v8::HeapSnapshot* snapshot = profiler->TakeHeapSnapshot(v8String(title, isolate), &adapter, &resolver); return snapshot ? ScriptHeapSnapshot::create(snapshot) : 0; } static v8::RetainedObjectInfo* retainedDOMInfo(uint16_t classId, v8::Handle<v8::Value> wrapper) { ASSERT(classId == v8DOMNodeClassId); if (!wrapper->IsObject()) return 0; Node* node = V8Node::toNative(wrapper.As<v8::Object>()); return node ? new RetainedDOMInfo(node) : 0; } void ScriptProfiler::initialize() { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HeapProfiler* profiler = isolate->GetHeapProfiler(); if (profiler) profiler->SetWrapperClassInfoProvider(v8DOMNodeClassId, &retainedDOMInfo); } void ScriptProfiler::visitNodeWrappers(WrappedNodeVisitor* visitor) { // visitNodeWrappers() should receive a ScriptState and retrieve an Isolate // from the ScriptState. v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handleScope(isolate); class DOMNodeWrapperVisitor : public v8::PersistentHandleVisitor { public: DOMNodeWrapperVisitor(WrappedNodeVisitor* visitor, v8::Isolate* isolate) : m_visitor(visitor) , m_isolate(isolate) { } #ifdef V8_USE_OLD_STYLE_PERSISTENT_HANDLE_VISITORS virtual void VisitPersistentHandle(v8::Persistent<v8::Value> value, uint16_t classId) OVERRIDE { VisitPersistentHandle(&value, classId); } virtual void VisitPersistentHandle(v8::Persistent<v8::Value>* value, uint16_t classId) #else virtual void VisitPersistentHandle(v8::Persistent<v8::Value>* value, uint16_t classId) OVERRIDE #endif { if (classId != v8DOMNodeClassId) return; UNUSED_PARAM(m_isolate); ASSERT(V8Node::HasInstance(*value, m_isolate, worldType(m_isolate))); ASSERT((*value)->IsObject()); #ifdef V8_USE_UNSAFE_HANDLES v8::Persistent<v8::Object> wrapper = v8::Persistent<v8::Object>::Cast(*value); #else v8::Persistent<v8::Object>& wrapper = v8::Persistent<v8::Object>::Cast(*value); #endif m_visitor->visitNode(V8Node::toNative(wrapper)); } private: WrappedNodeVisitor* m_visitor; v8::Isolate* m_isolate; } wrapperVisitor(visitor, isolate); v8::V8::VisitHandlesWithClassIds(&wrapperVisitor); } void ScriptProfiler::visitExternalStrings(ExternalStringVisitor* visitor) { V8PerIsolateData::current()->visitExternalStrings(visitor); } void ScriptProfiler::visitExternalArrays(ExternalArrayVisitor* visitor) { class DOMObjectWrapperVisitor : public v8::PersistentHandleVisitor { public: explicit DOMObjectWrapperVisitor(ExternalArrayVisitor* visitor) : m_visitor(visitor) { } #ifdef V8_USE_OLD_STYLE_PERSISTENT_HANDLE_VISITORS virtual void VisitPersistentHandle(v8::Persistent<v8::Value> value, uint16_t classId) OVERRIDE { VisitPersistentHandle(&value, classId); } virtual void VisitPersistentHandle(v8::Persistent<v8::Value>* value, uint16_t classId) #else virtual void VisitPersistentHandle(v8::Persistent<v8::Value>* value, uint16_t classId) OVERRIDE #endif { if (classId != v8DOMObjectClassId) return; ASSERT((*value)->IsObject()); #ifdef V8_USE_UNSAFE_HANDLES v8::Persistent<v8::Object> wrapper = v8::Persistent<v8::Object>::Cast(*value); #else v8::Persistent<v8::Object>& wrapper = v8::Persistent<v8::Object>::Cast(*value); #endif if (!toWrapperTypeInfo(wrapper)->isSubclass(&V8ArrayBufferView::info)) return; m_visitor->visitJSExternalArray(V8ArrayBufferView::toNative(wrapper)); } private: ExternalArrayVisitor* m_visitor; } wrapperVisitor(visitor); v8::V8::VisitHandlesWithClassIds(&wrapperVisitor); } void ScriptProfiler::collectBindingMemoryInfo(MemoryInstrumentation* instrumentation) { V8PerIsolateData* data = V8PerIsolateData::current(); instrumentation->addRootObject(data); } size_t ScriptProfiler::profilerSnapshotsSize() { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HeapProfiler* profiler = isolate->GetHeapProfiler(); if (!profiler) return 0; return profiler->GetProfilerMemorySize(); } ProfileNameIdleTimeMap* ScriptProfiler::currentProfileNameIdleTimeMap() { AtomicallyInitializedStatic(WTF::ThreadSpecific<ProfileNameIdleTimeMap>*, map = new WTF::ThreadSpecific<ProfileNameIdleTimeMap>); return *map; } } // namespace WebCore <|endoftext|>
<commit_before>// This file is a part of the OpenSurgSim project. // Copyright 2013-2015, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "SurgSim/Devices/Leap/LeapScaffold.h" #include <boost/thread/mutex.hpp> #include <Leap.h> #include <list> #include "SurgSim/DataStructures/DataGroup.h" #include "SurgSim/DataStructures/DataGroupBuilder.h" #include "SurgSim/Framework/Log.h" #include "SurgSim/Framework/SharedInstance.h" #include "SurgSim/Math/Matrix.h" #include "SurgSim/Math/RigidTransform.h" #include "SurgSim/Math/Vector.h" using SurgSim::Math::RigidTransform3d; using SurgSim::Math::Vector3d; namespace { RigidTransform3d makeRigidTransform(const Leap::Matrix& rotation, const Leap::Vector& translation, bool isRightHanded = true) { Leap::Matrix matrix = rotation; if (!isRightHanded) { matrix.zBasis *= -1.0; } // Convert milimeters to meters matrix.origin = translation * 0.001f; SurgSim::Math::Matrix44d transform; matrix.toArray4x4(transform.data()); return RigidTransform3d(transform.transpose()); } void updateDataGroup(const Leap::Hand& hand, SurgSim::DataStructures::DataGroup* inputData) { static const std::array<std::string, 5> fingerNames = {"Thumb", "IndexFinger", "MiddleFinger", "RingFinger", "SmallFinger"}; static const std::array<std::string, 4> boneNames = {"Metacarpal", "Proximal", "Intermediate", "Distal"}; inputData->poses().set("pose", makeRigidTransform(hand.basis(), hand.palmPosition(), hand.isRight())); std::string name; const Leap::FingerList fingers = hand.fingers(); for (const Leap::Finger& finger : fingers) { for (int boneType = Leap::Bone::TYPE_PROXIMAL; boneType <= Leap::Bone::TYPE_DISTAL; ++boneType) { Leap::Bone bone = finger.bone(static_cast<Leap::Bone::Type>(boneType)); name = fingerNames[finger.type()] + boneNames[boneType]; inputData->poses().set(name, makeRigidTransform(bone.basis(), bone.prevJoint(), hand.isRight())); inputData->scalars().set(name + "Length", bone.length() / 1000.0); inputData->scalars().set(name + "Width", bone.width() / 1000.0); } } } }; namespace SurgSim { namespace Devices { class LeapScaffold::Listener : public Leap::Listener { public: Listener() : m_scaffold(LeapScaffold::getOrCreateSharedInstance()), m_logger(Framework::Logger::getLogger("Leap")) { } void onConnect(const Leap::Controller&) override { SURGSIM_LOG_INFO(m_logger) << "Connected to Leap Motion camera"; } void onDisconnect(const Leap::Controller&) override { SURGSIM_LOG_INFO(m_logger) << "Diconnected from Leap Motion camera"; } void onFrame(const Leap::Controller&) override { auto scaffold = m_scaffold.lock(); if (scaffold != nullptr) { scaffold->handleFrame(); } } private: std::weak_ptr<Devices::LeapScaffold> m_scaffold; std::shared_ptr<Framework::Logger> m_logger; }; struct LeapScaffold::DeviceData { explicit DeviceData(LeapDevice* device) : deviceObject(device), handId(std::numeric_limits<int32_t>::quiet_NaN()) { } /// The corresponding device object. LeapDevice* const deviceObject; /// A unique id for the hand, assigned by the Leap SDK int32_t handId; }; struct LeapScaffold::StateData { // The SDK's interface to a single Leap Motion Camera Leap::Controller controller; /// A listener that receives updates from the Leap SDK std::unique_ptr<Listener> listener; /// The list of known devices. std::list<std::unique_ptr<DeviceData>> activeDevices; /// The mutex that protects the list of known devices. boost::mutex mutex; }; LeapScaffold::LeapScaffold() : m_state(new StateData), m_logger(Framework::Logger::getLogger("Leap")) { } LeapScaffold::~LeapScaffold() { if (m_state->listener != nullptr) { m_state->controller.removeListener(*m_state->listener); } } bool LeapScaffold::registerDevice(LeapDevice* device) { bool success = true; boost::lock_guard<boost::mutex> lock(m_state->mutex); const std::string deviceName = device->getName(); auto sameName = [&deviceName](const std::unique_ptr<DeviceData>& info) { return info->deviceObject->getName() == deviceName; }; auto found = std::find_if(m_state->activeDevices.cbegin(), m_state->activeDevices.cend(), sameName); if (found == m_state->activeDevices.end()) { std::unique_ptr<DeviceData> info(new DeviceData(device)); success = doRegisterDevice(info.get()); if (success) { SURGSIM_LOG_INFO(m_logger) << "Device " << device->getName() << ": Registered"; m_state->activeDevices.emplace_back(std::move(info)); } else { SURGSIM_LOG_SEVERE(m_logger) << "Device " << device->getName() << ": Not registered"; } } else { SURGSIM_LOG_SEVERE(m_logger) << "Tried to register a device when the same name, '" << device->getName() << "', is already present!"; success = false; } return success; } bool LeapScaffold::doRegisterDevice(DeviceData* info) { if (m_state->listener == nullptr) { m_state->listener = std::unique_ptr<Listener>(new Listener); m_state->controller.addListener(*m_state->listener); } if (info->deviceObject->isProvidingImages()) { m_state->controller.setPolicy(Leap::Controller::PolicyFlag::POLICY_IMAGES); } return true; } bool LeapScaffold::unregisterDevice(const LeapDevice* device) { bool success = true; boost::lock_guard<boost::mutex> lock(m_state->mutex); auto& devices = m_state->activeDevices; if (device->isProvidingImages()) { auto providingImages = [](const std::unique_ptr<DeviceData>& info) { return info->deviceObject->isProvidingImages(); }; if (std::find_if(devices.begin(), devices.end(), providingImages) == devices.end()) { m_state->controller.clearPolicy(Leap::Controller::PolicyFlag::POLICY_IMAGES); } } auto sameDevice = [device](const std::unique_ptr<DeviceData>& info) { return info->deviceObject == device; }; auto info = std::find_if(devices.begin(), devices.end(), sameDevice); if (info != devices.end()) { devices.erase(info); SURGSIM_LOG_INFO(m_logger) << "Device " << device->getName() << ": Unregistered"; } else { SURGSIM_LOG_SEVERE(m_logger) << "Attempted to release a non-registered device named '" << device->getName() << "."; success = false; } return success; } void LeapScaffold::handleFrame() { updateHandData(); updateImageData(); for (auto& device : m_state->activeDevices) { device->deviceObject->pushInput(); } } void LeapScaffold::updateHandData() { std::list<DeviceData*> unassignedDevices; for (auto& device : m_state->activeDevices) { unassignedDevices.push_back(device.get()); } std::list<Leap::HandList::const_iterator> newHands; Leap::HandList hands = m_state->controller.frame().hands(); for (auto hand = hands.begin(); hand != hands.end(); ++hand) { auto sameHandId = [hand](const std::unique_ptr<DeviceData>& info) { return info->handId == (*hand).id(); }; auto assignedDevice = std::find_if(m_state->activeDevices.begin(), m_state->activeDevices.end(), sameHandId); if (assignedDevice != m_state->activeDevices.end()) { updateDataGroup(*hand, &(*assignedDevice)->deviceObject->getInputData()); unassignedDevices.remove(assignedDevice->get()); } else { newHands.push_back(hand); } } static auto higherConfidence = [](const Leap::HandList::const_iterator &a, const Leap::HandList::const_iterator &b) { return (*a).confidence() > (*b).confidence(); }; newHands.sort(higherConfidence); for (auto& newHand : newHands) { auto sameHandType = [newHand](DeviceData* info) { return (info->deviceObject->getHandType() == HANDTYPE_LEFT) == (*newHand).isLeft(); }; auto unassignedDevice = std::find_if(unassignedDevices.begin(), unassignedDevices.end(), sameHandType); if (unassignedDevice != unassignedDevices.end()) { (*unassignedDevice)->handId = (*newHand).id(); updateDataGroup(*newHand, &(*unassignedDevice)->deviceObject->getInputData()); unassignedDevices.remove(*unassignedDevice); } } for(auto& unassignedDevice : unassignedDevices) { unassignedDevice->deviceObject->getInputData().poses().resetAll(); } } void LeapScaffold::updateImageData() { Leap::ImageList images = m_state->controller.frame().images(); if (!images.isEmpty()) { typedef DataStructures::DataGroup::ImageType ImageType; ImageType leftImage(images[0].width(), images[0].height(), 1, images[0].data()); ImageType rightImage(images[1].width(), images[1].height(), 1, images[1].data()); // scale values to 0..1 leftImage.getAsVector() *= (1.0f / 255.0f); rightImage.getAsVector() *= (1.0f / 255.0f); for (auto& device : m_state->activeDevices) { if (device->deviceObject->isProvidingImages()) { device->deviceObject->getInputData().images().set("left", leftImage); device->deviceObject->getInputData().images().set("right", rightImage); } else { device->deviceObject->getInputData().images().resetAll(); } } } else { for (auto& device : m_state->activeDevices) { device->deviceObject->getInputData().images().resetAll(); } } } std::shared_ptr<LeapScaffold> LeapScaffold::getOrCreateSharedInstance() { static auto creator = []() { return std::shared_ptr<LeapScaffold>(new LeapScaffold); }; static Framework::SharedInstance<LeapScaffold> sharedInstance(creator); return sharedInstance.get(); } DataStructures::DataGroup LeapScaffold::buildDeviceInputData() { DataStructures::DataGroupBuilder builder; builder.addImage("left"); builder.addImage("right"); builder.addPose("pose"); builder.addPose("ThumbProximal"); builder.addPose("ThumbIntermediate"); builder.addPose("ThumbDistal"); builder.addPose("IndexFingerProximal"); builder.addPose("IndexFingerIntermediate"); builder.addPose("IndexFingerDistal"); builder.addPose("MiddleFingerProximal"); builder.addPose("MiddleFingerIntermediate"); builder.addPose("MiddleFingerDistal"); builder.addPose("RingFingerProximal"); builder.addPose("RingFingerIntermediate"); builder.addPose("RingFingerDistal"); builder.addPose("SmallFingerProximal"); builder.addPose("SmallFingerIntermediate"); builder.addPose("SmallFingerDistal"); builder.addScalar("ThumbProximalWidth"); builder.addScalar("ThumbIntermediateWidth"); builder.addScalar("ThumbDistalWidth"); builder.addScalar("IndexFingerProximalWidth"); builder.addScalar("IndexFingerIntermediateWidth"); builder.addScalar("IndexFingerDistalWidth"); builder.addScalar("MiddleFingerProximalWidth"); builder.addScalar("MiddleFingerIntermediateWidth"); builder.addScalar("MiddleFingerDistalWidth"); builder.addScalar("RingFingerProximalWidth"); builder.addScalar("RingFingerIntermediateWidth"); builder.addScalar("RingFingerDistalWidth"); builder.addScalar("SmallFingerProximalWidth"); builder.addScalar("SmallFingerIntermediateWidth"); builder.addScalar("SmallFingerDistalWidth"); builder.addScalar("ThumbProximalLength"); builder.addScalar("ThumbIntermediateLength"); builder.addScalar("ThumbDistalLength"); builder.addScalar("IndexFingerProximalLength"); builder.addScalar("IndexFingerIntermediateLength"); builder.addScalar("IndexFingerDistalLength"); builder.addScalar("MiddleFingerProximalLength"); builder.addScalar("MiddleFingerIntermediateLength"); builder.addScalar("MiddleFingerDistalLength"); builder.addScalar("RingFingerProximalLength"); builder.addScalar("RingFingerIntermediateLength"); builder.addScalar("RingFingerDistalLength"); builder.addScalar("SmallFingerProximalLength"); builder.addScalar("SmallFingerIntermediateLength"); builder.addScalar("SmallFingerDistalLength"); return builder.createData(); } void LeapScaffold::setUseHmdTrackingMode(bool useHmdTrackingMode) { if (useHmdTrackingMode) { m_state->controller.setPolicy(Leap::Controller::PolicyFlag::POLICY_OPTIMIZE_HMD); } else { m_state->controller.clearPolicy(Leap::Controller::PolicyFlag::POLICY_OPTIMIZE_HMD); } } bool LeapScaffold::isUsingHmdTrackingMode() const { return m_state->controller.isPolicySet(Leap::Controller::PolicyFlag::POLICY_OPTIMIZE_HMD); } }; // namespace Devices }; // namespace SurgSim <commit_msg>LeapScaffold uses "Devices/Leap" for logger name.<commit_after>// This file is a part of the OpenSurgSim project. // Copyright 2013-2015, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "SurgSim/Devices/Leap/LeapScaffold.h" #include <boost/thread/mutex.hpp> #include <Leap.h> #include <list> #include "SurgSim/DataStructures/DataGroup.h" #include "SurgSim/DataStructures/DataGroupBuilder.h" #include "SurgSim/Framework/Log.h" #include "SurgSim/Framework/SharedInstance.h" #include "SurgSim/Math/Matrix.h" #include "SurgSim/Math/RigidTransform.h" #include "SurgSim/Math/Vector.h" using SurgSim::Math::RigidTransform3d; namespace { RigidTransform3d makeRigidTransform(const Leap::Matrix& rotation, const Leap::Vector& translation, bool isRightHanded = true) { Leap::Matrix matrix = rotation; if (!isRightHanded) { matrix.zBasis *= -1.0; } // Convert milimeters to meters matrix.origin = translation * 0.001f; SurgSim::Math::Matrix44d transform; matrix.toArray4x4(transform.data()); return RigidTransform3d(transform.transpose()); } void updateDataGroup(const Leap::Hand& hand, SurgSim::DataStructures::DataGroup* inputData) { static const std::array<std::string, 5> fingerNames = {"Thumb", "IndexFinger", "MiddleFinger", "RingFinger", "SmallFinger"}; static const std::array<std::string, 4> boneNames = {"Metacarpal", "Proximal", "Intermediate", "Distal"}; inputData->poses().set("pose", makeRigidTransform(hand.basis(), hand.palmPosition(), hand.isRight())); std::string name; const Leap::FingerList fingers = hand.fingers(); for (const Leap::Finger& finger : fingers) { for (int boneType = Leap::Bone::TYPE_PROXIMAL; boneType <= Leap::Bone::TYPE_DISTAL; ++boneType) { Leap::Bone bone = finger.bone(static_cast<Leap::Bone::Type>(boneType)); name = fingerNames[finger.type()] + boneNames[boneType]; inputData->poses().set(name, makeRigidTransform(bone.basis(), bone.prevJoint(), hand.isRight())); inputData->scalars().set(name + "Length", bone.length() / 1000.0); inputData->scalars().set(name + "Width", bone.width() / 1000.0); } } } }; namespace SurgSim { namespace Devices { class LeapScaffold::Listener : public Leap::Listener { public: Listener() : m_scaffold(LeapScaffold::getOrCreateSharedInstance()), m_logger(Framework::Logger::getLogger("Devices/Leap")) { } void onConnect(const Leap::Controller&) override { SURGSIM_LOG_INFO(m_logger) << "Connected to Leap Motion camera"; } void onDisconnect(const Leap::Controller&) override { SURGSIM_LOG_INFO(m_logger) << "Diconnected from Leap Motion camera"; } void onFrame(const Leap::Controller&) override { auto scaffold = m_scaffold.lock(); if (scaffold != nullptr) { scaffold->handleFrame(); } } private: std::weak_ptr<Devices::LeapScaffold> m_scaffold; std::shared_ptr<Framework::Logger> m_logger; }; struct LeapScaffold::DeviceData { explicit DeviceData(LeapDevice* device) : deviceObject(device), handId(std::numeric_limits<int32_t>::quiet_NaN()) { } /// The corresponding device object. LeapDevice* const deviceObject; /// A unique id for the hand, assigned by the Leap SDK int32_t handId; }; struct LeapScaffold::StateData { // The SDK's interface to a single Leap Motion Camera Leap::Controller controller; /// A listener that receives updates from the Leap SDK std::unique_ptr<Listener> listener; /// The list of known devices. std::list<std::unique_ptr<DeviceData>> activeDevices; /// The mutex that protects the list of known devices. boost::mutex mutex; }; LeapScaffold::LeapScaffold() : m_state(new StateData), m_logger(Framework::Logger::getLogger("Devices/Leap")) { } LeapScaffold::~LeapScaffold() { if (m_state->listener != nullptr) { m_state->controller.removeListener(*m_state->listener); } } bool LeapScaffold::registerDevice(LeapDevice* device) { bool success = true; boost::lock_guard<boost::mutex> lock(m_state->mutex); const std::string deviceName = device->getName(); auto sameName = [&deviceName](const std::unique_ptr<DeviceData>& info) { return info->deviceObject->getName() == deviceName; }; auto found = std::find_if(m_state->activeDevices.cbegin(), m_state->activeDevices.cend(), sameName); if (found == m_state->activeDevices.end()) { std::unique_ptr<DeviceData> info(new DeviceData(device)); success = doRegisterDevice(info.get()); if (success) { SURGSIM_LOG_INFO(m_logger) << "Device " << device->getName() << ": Registered"; m_state->activeDevices.emplace_back(std::move(info)); } else { SURGSIM_LOG_SEVERE(m_logger) << "Device " << device->getName() << ": Not registered"; } } else { SURGSIM_LOG_SEVERE(m_logger) << "Tried to register a device when the same name, '" << device->getName() << "', is already present!"; success = false; } return success; } bool LeapScaffold::doRegisterDevice(DeviceData* info) { if (m_state->listener == nullptr) { m_state->listener = std::unique_ptr<Listener>(new Listener); m_state->controller.addListener(*m_state->listener); } if (info->deviceObject->isProvidingImages()) { m_state->controller.setPolicy(Leap::Controller::PolicyFlag::POLICY_IMAGES); } return true; } bool LeapScaffold::unregisterDevice(const LeapDevice* device) { bool success = true; boost::lock_guard<boost::mutex> lock(m_state->mutex); auto& devices = m_state->activeDevices; if (device->isProvidingImages()) { auto providingImages = [](const std::unique_ptr<DeviceData>& info) { return info->deviceObject->isProvidingImages(); }; if (std::find_if(devices.begin(), devices.end(), providingImages) == devices.end()) { m_state->controller.clearPolicy(Leap::Controller::PolicyFlag::POLICY_IMAGES); } } auto sameDevice = [device](const std::unique_ptr<DeviceData>& info) { return info->deviceObject == device; }; auto info = std::find_if(devices.begin(), devices.end(), sameDevice); if (info != devices.end()) { devices.erase(info); SURGSIM_LOG_INFO(m_logger) << "Device " << device->getName() << ": Unregistered"; } else { SURGSIM_LOG_SEVERE(m_logger) << "Attempted to release a non-registered device named '" << device->getName() << "."; success = false; } return success; } void LeapScaffold::handleFrame() { updateHandData(); updateImageData(); for (auto& device : m_state->activeDevices) { device->deviceObject->pushInput(); } } void LeapScaffold::updateHandData() { std::list<DeviceData*> unassignedDevices; for (auto& device : m_state->activeDevices) { unassignedDevices.push_back(device.get()); } std::list<Leap::HandList::const_iterator> newHands; Leap::HandList hands = m_state->controller.frame().hands(); for (auto hand = hands.begin(); hand != hands.end(); ++hand) { auto sameHandId = [hand](const std::unique_ptr<DeviceData>& info) { return info->handId == (*hand).id(); }; auto assignedDevice = std::find_if(m_state->activeDevices.begin(), m_state->activeDevices.end(), sameHandId); if (assignedDevice != m_state->activeDevices.end()) { updateDataGroup(*hand, &(*assignedDevice)->deviceObject->getInputData()); unassignedDevices.remove(assignedDevice->get()); } else { newHands.push_back(hand); } } static auto higherConfidence = [](const Leap::HandList::const_iterator &a, const Leap::HandList::const_iterator &b) { return (*a).confidence() > (*b).confidence(); }; newHands.sort(higherConfidence); for (auto& newHand : newHands) { auto sameHandType = [newHand](DeviceData* info) { return (info->deviceObject->getHandType() == HANDTYPE_LEFT) == (*newHand).isLeft(); }; auto unassignedDevice = std::find_if(unassignedDevices.begin(), unassignedDevices.end(), sameHandType); if (unassignedDevice != unassignedDevices.end()) { (*unassignedDevice)->handId = (*newHand).id(); updateDataGroup(*newHand, &(*unassignedDevice)->deviceObject->getInputData()); unassignedDevices.remove(*unassignedDevice); } } for(auto& unassignedDevice : unassignedDevices) { unassignedDevice->deviceObject->getInputData().poses().resetAll(); } } void LeapScaffold::updateImageData() { Leap::ImageList images = m_state->controller.frame().images(); if (!images.isEmpty()) { typedef DataStructures::DataGroup::ImageType ImageType; ImageType leftImage(images[0].width(), images[0].height(), 1, images[0].data()); ImageType rightImage(images[1].width(), images[1].height(), 1, images[1].data()); // scale values to 0..1 leftImage.getAsVector() *= (1.0f / 255.0f); rightImage.getAsVector() *= (1.0f / 255.0f); for (auto& device : m_state->activeDevices) { if (device->deviceObject->isProvidingImages()) { device->deviceObject->getInputData().images().set("left", leftImage); device->deviceObject->getInputData().images().set("right", rightImage); } else { device->deviceObject->getInputData().images().resetAll(); } } } else { for (auto& device : m_state->activeDevices) { device->deviceObject->getInputData().images().resetAll(); } } } std::shared_ptr<LeapScaffold> LeapScaffold::getOrCreateSharedInstance() { static auto creator = []() { return std::shared_ptr<LeapScaffold>(new LeapScaffold); }; static Framework::SharedInstance<LeapScaffold> sharedInstance(creator); return sharedInstance.get(); } DataStructures::DataGroup LeapScaffold::buildDeviceInputData() { DataStructures::DataGroupBuilder builder; builder.addImage("left"); builder.addImage("right"); builder.addPose("pose"); builder.addPose("ThumbProximal"); builder.addPose("ThumbIntermediate"); builder.addPose("ThumbDistal"); builder.addPose("IndexFingerProximal"); builder.addPose("IndexFingerIntermediate"); builder.addPose("IndexFingerDistal"); builder.addPose("MiddleFingerProximal"); builder.addPose("MiddleFingerIntermediate"); builder.addPose("MiddleFingerDistal"); builder.addPose("RingFingerProximal"); builder.addPose("RingFingerIntermediate"); builder.addPose("RingFingerDistal"); builder.addPose("SmallFingerProximal"); builder.addPose("SmallFingerIntermediate"); builder.addPose("SmallFingerDistal"); builder.addScalar("ThumbProximalWidth"); builder.addScalar("ThumbIntermediateWidth"); builder.addScalar("ThumbDistalWidth"); builder.addScalar("IndexFingerProximalWidth"); builder.addScalar("IndexFingerIntermediateWidth"); builder.addScalar("IndexFingerDistalWidth"); builder.addScalar("MiddleFingerProximalWidth"); builder.addScalar("MiddleFingerIntermediateWidth"); builder.addScalar("MiddleFingerDistalWidth"); builder.addScalar("RingFingerProximalWidth"); builder.addScalar("RingFingerIntermediateWidth"); builder.addScalar("RingFingerDistalWidth"); builder.addScalar("SmallFingerProximalWidth"); builder.addScalar("SmallFingerIntermediateWidth"); builder.addScalar("SmallFingerDistalWidth"); builder.addScalar("ThumbProximalLength"); builder.addScalar("ThumbIntermediateLength"); builder.addScalar("ThumbDistalLength"); builder.addScalar("IndexFingerProximalLength"); builder.addScalar("IndexFingerIntermediateLength"); builder.addScalar("IndexFingerDistalLength"); builder.addScalar("MiddleFingerProximalLength"); builder.addScalar("MiddleFingerIntermediateLength"); builder.addScalar("MiddleFingerDistalLength"); builder.addScalar("RingFingerProximalLength"); builder.addScalar("RingFingerIntermediateLength"); builder.addScalar("RingFingerDistalLength"); builder.addScalar("SmallFingerProximalLength"); builder.addScalar("SmallFingerIntermediateLength"); builder.addScalar("SmallFingerDistalLength"); return builder.createData(); } void LeapScaffold::setUseHmdTrackingMode(bool useHmdTrackingMode) { if (useHmdTrackingMode) { m_state->controller.setPolicy(Leap::Controller::PolicyFlag::POLICY_OPTIMIZE_HMD); } else { m_state->controller.clearPolicy(Leap::Controller::PolicyFlag::POLICY_OPTIMIZE_HMD); } } bool LeapScaffold::isUsingHmdTrackingMode() const { return m_state->controller.isPolicySet(Leap::Controller::PolicyFlag::POLICY_OPTIMIZE_HMD); } }; // namespace Devices }; // namespace SurgSim <|endoftext|>
<commit_before>#include "../Include/CEntityNode.h" #include "../Include/CSceneNode.h" #include "../Include/CMenuNode.h" #include "cocos2d.h" using namespace cocos2d; namespace LM { CEntityNode::CEntityNode(EAnchor a_eAnchor, int a_iWidth, int a_iHeight, int a_iXPosition, int a_iYPosition, const std::string& a_sID) : m_eAnchor(a_eAnchor), m_iXPosition(a_iXPosition), m_iYPosition(a_iYPosition), m_iWidth(a_iWidth), m_iHeight(a_iHeight), m_bVisible(true), m_bLocked(false), m_sID(a_sID), m_fEntityStartScale(0), m_pCocosEntity(nullptr) { } void CEntityNode::UnInit(bool removeChild) { //m_pCocosEntity->autorelease(); //m_pCocosEntity->release(); if (m_pCocosEntity != nullptr) { if(removeChild) GetParentScene()->removeChild(m_pCocosEntity); m_pCocosEntity = nullptr; CNode::UnInit(removeChild); } else { return; } } void CEntityNode::Revert(bool a_bVisible) { Show(a_bVisible); if (m_sID != "") CCLOG("reverting : %s", m_sID.c_str()); m_pCocosEntity->setPosition(m_oEntityStartLocation); m_pCocosEntity->setScale(m_fEntityStartScale); for (CNode* itNode : m_vChildren) { CEntityNode* pEntity = dynamic_cast<CEntityNode*>(itNode); if (pEntity) { pEntity->Revert(a_bVisible); } } } cocos2d::Node* CEntityNode::GetCocosEntity() { return m_pCocosEntity; } void CEntityNode::AddListener(const std::string& a_rEvent, const CEventCallback& a_rCallback) { std::map<std::string, std::vector<CEventCallback>>::iterator it = m_mListeners.find(a_rEvent); if (it != m_mListeners.end()) { it->second.push_back(a_rCallback); } else { std::vector<CEventCallback> oCallbacks; oCallbacks.push_back(a_rCallback); m_mListeners.insert(std::pair<std::string, std::vector<CEventCallback>>(a_rEvent, oCallbacks)); } } void CEntityNode::DisableEvent(const std::string& a_rEvent) { m_oDisabledEvents.insert(a_rEvent); } void CEntityNode::EnableEvent(const std::string& a_rEvent) { m_oDisabledEvents.erase(a_rEvent); } bool CEntityNode::EventIsDisabled(const std::string& a_rEvent) { return (m_oDisabledEvents.find(a_rEvent) != m_oDisabledEvents.end()); } bool CEntityNode::IsListeningTo(const std::string& a_rEvent) { if (m_oDisabledEvents.find(a_rEvent) == m_oDisabledEvents.end()) { std::map<std::string, std::vector<CEventCallback>>::iterator it = m_mListeners.find(a_rEvent); return (it != m_mListeners.end()); } } void CEntityNode::Dispatch(const std::string& a_rEvent, CEntityNode* a_pSender) { if (m_oDisabledEvents.find(a_rEvent) == m_oDisabledEvents.end()) { std::map<std::string, std::vector<CEventCallback>>::iterator it = m_mListeners.find(a_rEvent); if (it != m_mListeners.end()) { for (CEventCallback oCallback : it->second) { CCLOG("CEntity::Dispatch : Calling callback %s on entity %s", a_rEvent.c_str(), m_sID.c_str()); oCallback(a_pSender); } } } } void CEntityNode::PopulateParent(bool a_bDoScaling, bool a_bAddToParent) { // Size oVisibleSize = Director::getInstance()->getVisibleSize(); // Vec2 oOrigin = Director::getInstance()->getVisibleOrigin(); Size oVisibleSize = GetParentVisibleSize(); Vec2 oOrigin = GetParentOrigin(); switch (m_eAnchor) { case LM::CENTER: m_pCocosEntity->setAnchorPoint(Vec2(0.5, 0.5)); m_pCocosEntity->setPosition(Vec2(oOrigin.x + oVisibleSize.width/2, oOrigin.y + oVisibleSize.height/2)); break; case LM::BOTTOM_LEFT: m_pCocosEntity->setAnchorPoint(Vec2(0, 0)); m_pCocosEntity->setPosition(Vec2(oOrigin.x, oOrigin.y)); break; case LM::LEFT: m_pCocosEntity->setAnchorPoint(Vec2(0, 0.5)); m_pCocosEntity->setPosition(Vec2(oOrigin.x, oOrigin.y + oVisibleSize.height / 2)); break; case LM::TOP_LEFT: m_pCocosEntity->setAnchorPoint(Vec2(0, 1)); m_pCocosEntity->setPosition(Vec2(oOrigin.x, oOrigin.y + oVisibleSize.height)); break; case LM::TOP: m_pCocosEntity->setAnchorPoint(Vec2(0.5, 1)); m_pCocosEntity->setPosition(Vec2(oOrigin.x + oVisibleSize.width / 2, oOrigin.y + oVisibleSize.height)); break; case LM::TOP_RIGHT: m_pCocosEntity->setAnchorPoint(Vec2(1, 1)); m_pCocosEntity->setPosition(Vec2(oOrigin.x + oVisibleSize.width, oOrigin.y + oVisibleSize.height)); break; case LM::RIGHT: m_pCocosEntity->setAnchorPoint(Vec2(1, 0.5)); m_pCocosEntity->setPosition(Vec2(oOrigin.x + oVisibleSize.width, oOrigin.y + oVisibleSize.height / 2)); break; case LM::BOTTOM_RIGHT: m_pCocosEntity->setAnchorPoint(Vec2(1, 0)); m_pCocosEntity->setPosition(Vec2(oOrigin.x + oVisibleSize.width, oOrigin.y)); break; case LM::BOTTOM: m_pCocosEntity->setAnchorPoint(Vec2(0.5, 0)); m_pCocosEntity->setPosition(Vec2(oOrigin.x + oVisibleSize.width / 2, oOrigin.y)); break; case LM::FLOAT: m_pCocosEntity->setAnchorPoint(Vec2(0.5, 0.5)); m_pCocosEntity->setPosition(Vec2(m_iXPosition, m_iYPosition)); break; default: break; } if (a_bDoScaling) { float fNewScale; if (m_iWidth != 0) { float fOldWidth = m_pCocosEntity->getBoundingBox().getMaxX() - m_pCocosEntity->getBoundingBox().getMinX(); float fNewWidth = oVisibleSize.width * ((float)m_iWidth / 100.0f); fNewScale = fNewWidth / fOldWidth; } else { float fOldHeight = m_pCocosEntity->getBoundingBox().getMaxY() - m_pCocosEntity->getBoundingBox().getMinY(); float fNewHeight = oVisibleSize.height * ((float)m_iHeight / 100.0f); fNewScale = fNewHeight / fOldHeight; } m_pCocosEntity->setScale(fNewScale); } if (a_bAddToParent) { cocos2d::Scene* pScene = GetParentScene(); if (pScene) { pScene->addChild(m_pCocosEntity, 0); } } m_pCocosEntity->setVisible(m_bVisible); m_oEntityStartLocation = m_pCocosEntity->getPosition(); m_fEntityStartScale = m_pCocosEntity->getScale(); Dispatch("Init"); } Scene* CEntityNode::GetParentScene() { CSceneNode* pParentScene = dynamic_cast<CSceneNode*>(m_pParent); if (pParentScene) { return pParentScene->GetScene(); } else { CEntityNode* pParentNode = dynamic_cast<CEntityNode*>(m_pParent); if (pParentNode) { return pParentNode->GetParentScene(); } } } Size CEntityNode::GetParentVisibleSize() { CEntityNode* pParentEntity = dynamic_cast<CEntityNode*>(m_pParent); if (pParentEntity) { return pParentEntity->GetVisibleSize(); } return Director::getInstance()->getVisibleSize(); } Vec2 CEntityNode::GetParentOrigin() { CEntityNode* pParentEntity = dynamic_cast<CEntityNode*>(m_pParent); if (pParentEntity) { return pParentEntity->GetOrigin(); } return Director::getInstance()->getVisibleOrigin(); } Size CEntityNode::GetVisibleSize() { //return m_pCocosEntity->getContentSize(); Rect oBoundingBox = m_pCocosEntity->getBoundingBox(); return Size(oBoundingBox.getMaxX() - oBoundingBox.getMinX(), oBoundingBox.getMaxY() - oBoundingBox.getMinY()); } Vec2 CEntityNode::GetOrigin() { Rect oBoundingBox = m_pCocosEntity->getBoundingBox(); return Vec2(oBoundingBox.getMinX(), oBoundingBox.getMinY()); } void CEntityNode::SetVisible(bool a_bVisible) { m_bVisible = a_bVisible; } bool CEntityNode::IsVisible() { return m_bVisible; } std::string CEntityNode::GetID() { return m_sID; } void CEntityNode::SetID(const std::string& a_rID) { m_sID = a_rID; } void CEntityNode::Show(bool a_bVisible) { if (GetID() != "" && a_bVisible) CCLOG("Showing entity : %s", GetID().c_str()); m_bVisible = a_bVisible; if (m_pCocosEntity) { m_pCocosEntity->setVisible(a_bVisible); FadeIn(); } for (CNode* itNode : *this) { CEntityNode* pEntity = dynamic_cast<CEntityNode*>(itNode); if (pEntity && (!pEntity->IsListeningTo("Show") || !a_bVisible)) { pEntity->Show(a_bVisible); } } } void CEntityNode::Colorize(bool a_bColored) { if (GetID() != "" && a_bColored) CCLOG("Colorize entity : %s", GetID().c_str()); m_bColored = a_bColored; if (a_bColored && dynamic_cast<Sprite*>(m_pCocosEntity)) { BlendFunc oColoredBlend; oColoredBlend.src = GL_SRC_ALPHA; oColoredBlend.dst = GL_ONE_MINUS_SRC_ALPHA; dynamic_cast<Sprite*>(m_pCocosEntity)->setBlendFunc(oColoredBlend); } for (CNode* itNode : *this) { CEntityNode* pEntity = dynamic_cast<CEntityNode*>(itNode); if (pEntity && (!pEntity->IsListeningTo("Colorize") || !a_bColored)) { pEntity->Colorize(a_bColored); } } } bool CEntityNode::IsLocked() { return m_bLocked; } Vec2 CEntityNode::GetEntityStartLocation() { return m_oEntityStartLocation; } float CEntityNode::GetEntityStartScale() { return m_fEntityStartScale; } void CEntityNode::Fade() { auto fpReleaseEntity = CallFunc::create([this]() { CEntityNode::Release(this); this->Revert(); }); auto oFadeOut = FadeOut::create(0.5f); auto oSequence = Sequence::create(oFadeOut, fpReleaseEntity, nullptr); m_pCocosEntity->runAction(oSequence); for (CNode* itNode : m_vChildren) { CEntityNode* pChildEntity = dynamic_cast<CEntityNode*>(itNode); if (pChildEntity) { pChildEntity->Fade(); } } } void CEntityNode::FadeIn() { CCLOG("CEntityNode::FadeIn %s", m_sID.c_str()); auto oFadeIn = FadeIn::create(0.5f); m_pCocosEntity->runAction(oFadeIn); /*for (CNode* itNode : m_vChildren) { CEntityNode* pChildEntity = dynamic_cast<CEntityNode*>(itNode); if (pChildEntity) { pChildEntity->FadeIn(); } }*/ } bool CEntityNode::Lock(CEntityNode* a_pEntity) { if (!a_pEntity->IsLocked()) { a_pEntity->m_bLocked = true; for (CNode* itNode : *a_pEntity) { CEntityNode* pEntity = dynamic_cast<CEntityNode*>(itNode); if (pEntity) { CEntityNode::Lock(pEntity); } } return true; } return false; } void CEntityNode::Release(CEntityNode* a_pEntity) { a_pEntity->m_bLocked = false; for (CNode* itNode : *a_pEntity) { CEntityNode* pEntity = dynamic_cast<CEntityNode*>(itNode); if (pEntity) { CEntityNode::Release(pEntity); } } } } // namespace LM <commit_msg>fixed black entities in LudoMuse<commit_after>#include "../Include/CEntityNode.h" #include "../Include/CSceneNode.h" #include "../Include/CMenuNode.h" #include "cocos2d.h" using namespace cocos2d; namespace LM { CEntityNode::CEntityNode(EAnchor a_eAnchor, int a_iWidth, int a_iHeight, int a_iXPosition, int a_iYPosition, const std::string& a_sID) : m_eAnchor(a_eAnchor), m_iXPosition(a_iXPosition), m_iYPosition(a_iYPosition), m_iWidth(a_iWidth), m_iHeight(a_iHeight), m_bVisible(true), m_bLocked(false), m_sID(a_sID), m_fEntityStartScale(0), m_pCocosEntity(nullptr), m_bColored(true) { } void CEntityNode::UnInit(bool removeChild) { //m_pCocosEntity->autorelease(); //m_pCocosEntity->release(); if (m_pCocosEntity != nullptr) { if(removeChild) GetParentScene()->removeChild(m_pCocosEntity); m_pCocosEntity = nullptr; CNode::UnInit(removeChild); } else { return; } } void CEntityNode::Revert(bool a_bVisible) { Show(a_bVisible); if (m_sID != "") CCLOG("reverting : %s", m_sID.c_str()); m_pCocosEntity->setPosition(m_oEntityStartLocation); m_pCocosEntity->setScale(m_fEntityStartScale); for (CNode* itNode : m_vChildren) { CEntityNode* pEntity = dynamic_cast<CEntityNode*>(itNode); if (pEntity) { pEntity->Revert(a_bVisible); } } } cocos2d::Node* CEntityNode::GetCocosEntity() { return m_pCocosEntity; } void CEntityNode::AddListener(const std::string& a_rEvent, const CEventCallback& a_rCallback) { std::map<std::string, std::vector<CEventCallback>>::iterator it = m_mListeners.find(a_rEvent); if (it != m_mListeners.end()) { it->second.push_back(a_rCallback); } else { std::vector<CEventCallback> oCallbacks; oCallbacks.push_back(a_rCallback); m_mListeners.insert(std::pair<std::string, std::vector<CEventCallback>>(a_rEvent, oCallbacks)); } } void CEntityNode::DisableEvent(const std::string& a_rEvent) { m_oDisabledEvents.insert(a_rEvent); } void CEntityNode::EnableEvent(const std::string& a_rEvent) { m_oDisabledEvents.erase(a_rEvent); } bool CEntityNode::EventIsDisabled(const std::string& a_rEvent) { return (m_oDisabledEvents.find(a_rEvent) != m_oDisabledEvents.end()); } bool CEntityNode::IsListeningTo(const std::string& a_rEvent) { if (m_oDisabledEvents.find(a_rEvent) == m_oDisabledEvents.end()) { std::map<std::string, std::vector<CEventCallback>>::iterator it = m_mListeners.find(a_rEvent); return (it != m_mListeners.end()); } } void CEntityNode::Dispatch(const std::string& a_rEvent, CEntityNode* a_pSender) { if (m_oDisabledEvents.find(a_rEvent) == m_oDisabledEvents.end()) { std::map<std::string, std::vector<CEventCallback>>::iterator it = m_mListeners.find(a_rEvent); if (it != m_mListeners.end()) { for (CEventCallback oCallback : it->second) { CCLOG("CEntity::Dispatch : Calling callback %s on entity %s", a_rEvent.c_str(), m_sID.c_str()); oCallback(a_pSender); } } } } void CEntityNode::PopulateParent(bool a_bDoScaling, bool a_bAddToParent) { // Size oVisibleSize = Director::getInstance()->getVisibleSize(); // Vec2 oOrigin = Director::getInstance()->getVisibleOrigin(); Size oVisibleSize = GetParentVisibleSize(); Vec2 oOrigin = GetParentOrigin(); switch (m_eAnchor) { case LM::CENTER: m_pCocosEntity->setAnchorPoint(Vec2(0.5, 0.5)); m_pCocosEntity->setPosition(Vec2(oOrigin.x + oVisibleSize.width/2, oOrigin.y + oVisibleSize.height/2)); break; case LM::BOTTOM_LEFT: m_pCocosEntity->setAnchorPoint(Vec2(0, 0)); m_pCocosEntity->setPosition(Vec2(oOrigin.x, oOrigin.y)); break; case LM::LEFT: m_pCocosEntity->setAnchorPoint(Vec2(0, 0.5)); m_pCocosEntity->setPosition(Vec2(oOrigin.x, oOrigin.y + oVisibleSize.height / 2)); break; case LM::TOP_LEFT: m_pCocosEntity->setAnchorPoint(Vec2(0, 1)); m_pCocosEntity->setPosition(Vec2(oOrigin.x, oOrigin.y + oVisibleSize.height)); break; case LM::TOP: m_pCocosEntity->setAnchorPoint(Vec2(0.5, 1)); m_pCocosEntity->setPosition(Vec2(oOrigin.x + oVisibleSize.width / 2, oOrigin.y + oVisibleSize.height)); break; case LM::TOP_RIGHT: m_pCocosEntity->setAnchorPoint(Vec2(1, 1)); m_pCocosEntity->setPosition(Vec2(oOrigin.x + oVisibleSize.width, oOrigin.y + oVisibleSize.height)); break; case LM::RIGHT: m_pCocosEntity->setAnchorPoint(Vec2(1, 0.5)); m_pCocosEntity->setPosition(Vec2(oOrigin.x + oVisibleSize.width, oOrigin.y + oVisibleSize.height / 2)); break; case LM::BOTTOM_RIGHT: m_pCocosEntity->setAnchorPoint(Vec2(1, 0)); m_pCocosEntity->setPosition(Vec2(oOrigin.x + oVisibleSize.width, oOrigin.y)); break; case LM::BOTTOM: m_pCocosEntity->setAnchorPoint(Vec2(0.5, 0)); m_pCocosEntity->setPosition(Vec2(oOrigin.x + oVisibleSize.width / 2, oOrigin.y)); break; case LM::FLOAT: m_pCocosEntity->setAnchorPoint(Vec2(0.5, 0.5)); m_pCocosEntity->setPosition(Vec2(m_iXPosition, m_iYPosition)); break; default: break; } if (a_bDoScaling) { float fNewScale; if (m_iWidth != 0) { float fOldWidth = m_pCocosEntity->getBoundingBox().getMaxX() - m_pCocosEntity->getBoundingBox().getMinX(); float fNewWidth = oVisibleSize.width * ((float)m_iWidth / 100.0f); fNewScale = fNewWidth / fOldWidth; } else { float fOldHeight = m_pCocosEntity->getBoundingBox().getMaxY() - m_pCocosEntity->getBoundingBox().getMinY(); float fNewHeight = oVisibleSize.height * ((float)m_iHeight / 100.0f); fNewScale = fNewHeight / fOldHeight; } m_pCocosEntity->setScale(fNewScale); } if (a_bAddToParent) { cocos2d::Scene* pScene = GetParentScene(); if (pScene) { pScene->addChild(m_pCocosEntity, 0); } } m_pCocosEntity->setVisible(m_bVisible); m_oEntityStartLocation = m_pCocosEntity->getPosition(); m_fEntityStartScale = m_pCocosEntity->getScale(); Dispatch("Init"); } Scene* CEntityNode::GetParentScene() { CSceneNode* pParentScene = dynamic_cast<CSceneNode*>(m_pParent); if (pParentScene) { return pParentScene->GetScene(); } else { CEntityNode* pParentNode = dynamic_cast<CEntityNode*>(m_pParent); if (pParentNode) { return pParentNode->GetParentScene(); } } } Size CEntityNode::GetParentVisibleSize() { CEntityNode* pParentEntity = dynamic_cast<CEntityNode*>(m_pParent); if (pParentEntity) { return pParentEntity->GetVisibleSize(); } return Director::getInstance()->getVisibleSize(); } Vec2 CEntityNode::GetParentOrigin() { CEntityNode* pParentEntity = dynamic_cast<CEntityNode*>(m_pParent); if (pParentEntity) { return pParentEntity->GetOrigin(); } return Director::getInstance()->getVisibleOrigin(); } Size CEntityNode::GetVisibleSize() { //return m_pCocosEntity->getContentSize(); Rect oBoundingBox = m_pCocosEntity->getBoundingBox(); return Size(oBoundingBox.getMaxX() - oBoundingBox.getMinX(), oBoundingBox.getMaxY() - oBoundingBox.getMinY()); } Vec2 CEntityNode::GetOrigin() { Rect oBoundingBox = m_pCocosEntity->getBoundingBox(); return Vec2(oBoundingBox.getMinX(), oBoundingBox.getMinY()); } void CEntityNode::SetVisible(bool a_bVisible) { m_bVisible = a_bVisible; } bool CEntityNode::IsVisible() { return m_bVisible; } std::string CEntityNode::GetID() { return m_sID; } void CEntityNode::SetID(const std::string& a_rID) { m_sID = a_rID; } void CEntityNode::Show(bool a_bVisible) { if (GetID() != "" && a_bVisible) CCLOG("Showing entity : %s", GetID().c_str()); m_bVisible = a_bVisible; if (m_pCocosEntity) { m_pCocosEntity->setVisible(a_bVisible); FadeIn(); } for (CNode* itNode : *this) { CEntityNode* pEntity = dynamic_cast<CEntityNode*>(itNode); if (pEntity && (!pEntity->IsListeningTo("Show") || !a_bVisible)) { pEntity->Show(a_bVisible); } } } void CEntityNode::Colorize(bool a_bColored) { if (GetID() != "" && a_bColored) CCLOG("Colorize entity : %s", GetID().c_str()); m_bColored = a_bColored; if (a_bColored && dynamic_cast<Sprite*>(m_pCocosEntity)) { BlendFunc oColoredBlend; oColoredBlend.src = GL_SRC_ALPHA; oColoredBlend.dst = GL_ONE_MINUS_SRC_ALPHA; dynamic_cast<Sprite*>(m_pCocosEntity)->setBlendFunc(oColoredBlend); } for (CNode* itNode : *this) { CEntityNode* pEntity = dynamic_cast<CEntityNode*>(itNode); if (pEntity && (!pEntity->IsListeningTo("Colorize") || !a_bColored)) { pEntity->Colorize(a_bColored); } } } bool CEntityNode::IsLocked() { return m_bLocked; } Vec2 CEntityNode::GetEntityStartLocation() { return m_oEntityStartLocation; } float CEntityNode::GetEntityStartScale() { return m_fEntityStartScale; } void CEntityNode::Fade() { auto fpReleaseEntity = CallFunc::create([this]() { CEntityNode::Release(this); this->Revert(); }); auto oFadeOut = FadeOut::create(0.5f); auto oSequence = Sequence::create(oFadeOut, fpReleaseEntity, nullptr); m_pCocosEntity->runAction(oSequence); for (CNode* itNode : m_vChildren) { CEntityNode* pChildEntity = dynamic_cast<CEntityNode*>(itNode); if (pChildEntity) { pChildEntity->Fade(); } } } void CEntityNode::FadeIn() { CCLOG("CEntityNode::FadeIn %s", m_sID.c_str()); auto oFadeIn = FadeIn::create(0.5f); m_pCocosEntity->runAction(oFadeIn); /*for (CNode* itNode : m_vChildren) { CEntityNode* pChildEntity = dynamic_cast<CEntityNode*>(itNode); if (pChildEntity) { pChildEntity->FadeIn(); } }*/ } bool CEntityNode::Lock(CEntityNode* a_pEntity) { if (!a_pEntity->IsLocked()) { a_pEntity->m_bLocked = true; for (CNode* itNode : *a_pEntity) { CEntityNode* pEntity = dynamic_cast<CEntityNode*>(itNode); if (pEntity) { CEntityNode::Lock(pEntity); } } return true; } return false; } void CEntityNode::Release(CEntityNode* a_pEntity) { a_pEntity->m_bLocked = false; for (CNode* itNode : *a_pEntity) { CEntityNode* pEntity = dynamic_cast<CEntityNode*>(itNode); if (pEntity) { CEntityNode::Release(pEntity); } } } } // namespace LM <|endoftext|>
<commit_before>#include <LoggerProcess.hpp> #include <iostream> // cin #include <exception> // std::set_unexpected int main(int argc, char** argv) { int uniqueIdentifier = 0; if(argc == 1) { // Assume default name using namespace std; cout << "Assumes default name on filemap." << endl; } else if(argc == 2) { using namespace std; // Assume started from game with unique identifier uniqueIdentifier = atoi(argv[1]); // Check so that i's not zero if(uniqueIdentifier == 0) { cout << "Invalid unique identifier for filemap." << endl; cout << "Assumes default name on filemap." << endl; } } else { // Something is probably wrong wrong using namespace std; cout << "A confusing amount of arguments: " << argc << "." << endl; cout << "Assumes default name on filemap." << endl; } LoggerProcess application; try { application.Initialize(uniqueIdentifier); application.Run(); } catch(std::exception& e) { using namespace std; cout << "Unknown error: " << e.what() << endl; #ifdef _DEBUG std::cin.get(); #endif } catch(...) { using namespace std; cout << "Unknown error." << endl; // TODORT debug info } return 0; }<commit_msg>Removed legacy comment<commit_after>#include <LoggerProcess.hpp> #include <iostream> // cin #include <exception> // std::set_unexpected int main(int argc, char** argv) { int uniqueIdentifier = 0; if(argc == 1) { // Assume default name using namespace std; cout << "Assumes default name on filemap." << endl; } else if(argc == 2) { using namespace std; // Assume started from game with unique identifier uniqueIdentifier = atoi(argv[1]); // Check so that i's not zero if(uniqueIdentifier == 0) { cout << "Invalid unique identifier for filemap." << endl; cout << "Assumes default name on filemap." << endl; } } else { // Something is probably wrong wrong using namespace std; cout << "A confusing amount of arguments: " << argc << "." << endl; cout << "Assumes default name on filemap." << endl; } LoggerProcess application; try { application.Initialize(uniqueIdentifier); application.Run(); } catch(std::exception& e) { using namespace std; cout << "Unknown error: " << e.what() << endl; #ifdef _DEBUG std::cin.get(); #endif } catch(...) { using namespace std; cout << "Unknown error." << endl; } return 0; }<|endoftext|>
<commit_before>#include "TriDualGraph.h" #include <iostream> #include <tbb/parallel_for.h> #include <tbb/parallel_for_each.h> #include <algorithm> #include <ModelLoader.h> #include <LNormUtil.h> using namespace Zephyr::Common; using namespace Zephyr::Graphics; Zephyr::Algorithm::TriDualGraph::TriDualGraph() { ModelLoader loader; auto filePath = "..\\model\\Lightning\\lightning_obj.obj"; std::shared_ptr<RenderableModel> mpModel(new RenderableModel(L"Lightning")); mpModel->loadFromFile(filePath); auto mesh = mpModel->getMesh(0); build(mesh); auto result = getNeighbourNodeId(1); /* Triangle tri(Point(1.0f,1.0f,1.0f), Point(2.0f,2.0f,2.0f), Point(0.0f,0.0f,0.0f)); auto area = tri.computeArea(); std::cout << area; TriNode triNode1, triNode2; auto nodeId1 = addNode(triNode1); auto nodeId2 = addNode(triNode2); auto node = getNode(nodeId1); getNeighbourNodeId(nodeId1); linkNodes(nodeId1, nodeId2); */ } Zephyr::Algorithm::TriDualGraph::~TriDualGraph() { } void Zephyr::Algorithm::TriDualGraph::build(const Graphics::Mesh & mesh) { const auto& indices = mesh.getIndices(); const auto& vertices = mesh.getVertices(); std::multimap<EdgeIdPair, int> edgesToNodeMap; // need to track Max ||Ni - Nj|| // Edge Inf float MaxE = 0; // create all the Node/Face for (int faceId = 0; faceId < mesh.getFaceCount(); ++faceId) { int currentId = faceId * 3; std::vector<int> index(3); index[0] = indices[currentId]; index[1] = indices[currentId+1]; index[2] = indices[currentId+2]; auto vertex = vertices[index[0]].pos; auto point0 = Point(vertex.x, vertex.y, vertex.z); vertex = vertices[index[1]].pos; auto point1 = Point(vertex.x, vertex.y, vertex.z); vertex = vertices[index[2]].pos; auto point2 = Point(vertex.x, vertex.y, vertex.z); // add the node to the dual graph TriNode triNode(point0, point1, point2); int currentNodeId = addNode(triNode); // sort the indices in order, so edge id pair will match std::sort(index.begin(), index.end()); // create the edges and link with other node for (int i = 0; i < 3; ++i) { EdgeIdPair edgePair; edgePair = ((i != 2) ? EdgeIdPair(index[i], index[i + 1]) : EdgeIdPair(index[0], index[2])); // find all the node that share this edge and link them auto relatedNodeIds = edgesToNodeMap.equal_range(edgePair); for (auto relatedNodeItr = relatedNodeIds.first; relatedNodeItr != relatedNodeIds.second; ++relatedNodeItr) { int relatedNodeId = relatedNodeItr->second; // link the two node int edgeId = linkNodes(relatedNodeId, currentNodeId); if (-1 == edgeId) continue; auto& edge = getEdge(edgeId); auto& node1 = getNode(currentNodeId); auto normal1 = node1.data.computeNormalNorm(); auto& node2 = getNode(relatedNodeId); auto normal2 = node2.data.computeNormalNorm(); // 2 // -B || Ni - Nj || // Inf const float B = 1.0f; // Ni - Nj auto normalDiff = normal1 - normal2; // float infNorm = Common::LNormUtil::LInfinityNorm(normalDiff); float infNormSq = infNorm * infNorm; float upperTerm = (-1.0f * B * infNormSq); // need to track Max Edge LInfinityNorm if (MaxE < infNorm) MaxE = infNorm; // store the upper term first, later after all the edges is done, we get the lower term (depend on MaxE) edge.data.weight = upperTerm; } edgesToNodeMap.insert(std::make_pair(edgePair, currentNodeId)); } } // for each edge, compute the actual weight // Actual weight = Exp ( UpperTerm / LowerTerm ) // we already have UpperTerm computed above for each edge.data.weight float lowerTerm = MaxE; tbb::parallel_for_each(mEdges.begin(), mEdges.end(), [&](Edge& edge) { edge.data.weight = std::exp(edge.data.weight / lowerTerm); }); } std::vector<std::vector<int>> Zephyr::Algorithm::TriDualGraph::segment(const std::vector<std::vector<int>>& inStrokes) { // Build X // Formulate to solver return std::vector<std::vector<int>>(); } <commit_msg>Use ternary operator instead of if statement for MaxE tracking.<commit_after>#include "TriDualGraph.h" #include <iostream> #include <tbb/parallel_for.h> #include <tbb/parallel_for_each.h> #include <algorithm> #include <ModelLoader.h> #include <LNormUtil.h> using namespace Zephyr::Common; using namespace Zephyr::Graphics; Zephyr::Algorithm::TriDualGraph::TriDualGraph() { ModelLoader loader; auto filePath = "..\\model\\Lightning\\lightning_obj.obj"; std::shared_ptr<RenderableModel> mpModel(new RenderableModel(L"Lightning")); mpModel->loadFromFile(filePath); auto mesh = mpModel->getMesh(0); build(mesh); auto result = getNeighbourNodeId(1); /* Triangle tri(Point(1.0f,1.0f,1.0f), Point(2.0f,2.0f,2.0f), Point(0.0f,0.0f,0.0f)); auto area = tri.computeArea(); std::cout << area; TriNode triNode1, triNode2; auto nodeId1 = addNode(triNode1); auto nodeId2 = addNode(triNode2); auto node = getNode(nodeId1); getNeighbourNodeId(nodeId1); linkNodes(nodeId1, nodeId2); */ } Zephyr::Algorithm::TriDualGraph::~TriDualGraph() { } void Zephyr::Algorithm::TriDualGraph::build(const Graphics::Mesh & mesh) { const auto& indices = mesh.getIndices(); const auto& vertices = mesh.getVertices(); std::multimap<EdgeIdPair, int> edgesToNodeMap; // need to track Max ||Ni - Nj|| // Edge Inf float MaxE = 0; // create all the Node/Face for (int faceId = 0; faceId < mesh.getFaceCount(); ++faceId) { int currentId = faceId * 3; std::vector<int> index(3); index[0] = indices[currentId]; index[1] = indices[currentId+1]; index[2] = indices[currentId+2]; auto vertex = vertices[index[0]].pos; auto point0 = Point(vertex.x, vertex.y, vertex.z); vertex = vertices[index[1]].pos; auto point1 = Point(vertex.x, vertex.y, vertex.z); vertex = vertices[index[2]].pos; auto point2 = Point(vertex.x, vertex.y, vertex.z); // add the node to the dual graph TriNode triNode(point0, point1, point2); int currentNodeId = addNode(triNode); // sort the indices in order, so edge id pair will match std::sort(index.begin(), index.end()); // create the edges and link with other node for (int i = 0; i < 3; ++i) { EdgeIdPair edgePair; edgePair = ((i != 2) ? EdgeIdPair(index[i], index[i + 1]) : EdgeIdPair(index[0], index[2])); // find all the node that share this edge and link them auto relatedNodeIds = edgesToNodeMap.equal_range(edgePair); for (auto relatedNodeItr = relatedNodeIds.first; relatedNodeItr != relatedNodeIds.second; ++relatedNodeItr) { int relatedNodeId = relatedNodeItr->second; // link the two node int edgeId = linkNodes(relatedNodeId, currentNodeId); if (-1 == edgeId) continue; auto& edge = getEdge(edgeId); auto& node1 = getNode(currentNodeId); auto normal1 = node1.data.computeNormalNorm(); auto& node2 = getNode(relatedNodeId); auto normal2 = node2.data.computeNormalNorm(); // 2 // -B || Ni - Nj || // Inf const float B = 1.0f; // Ni - Nj auto normalDiff = normal1 - normal2; // float infNorm = Common::LNormUtil::LInfinityNorm(normalDiff); float infNormSq = infNorm * infNorm; float upperTerm = (-1.0f * B * infNormSq); // need to track Max Edge LInfinityNorm MaxE = MaxE < infNorm ? infNorm : MaxE; // store the upper term first, later after all the edges is done, we get the lower term (depend on MaxE) edge.data.weight = upperTerm; } edgesToNodeMap.insert(std::make_pair(edgePair, currentNodeId)); } } // for each edge, compute the actual weight // Actual weight = Exp ( UpperTerm / LowerTerm ) // we already have UpperTerm computed above for each edge.data.weight float lowerTerm = MaxE; tbb::parallel_for_each(mEdges.begin(), mEdges.end(), [&](Edge& edge) { edge.data.weight = std::exp(edge.data.weight / lowerTerm); }); } std::vector<std::vector<int>> Zephyr::Algorithm::TriDualGraph::segment(const std::vector<std::vector<int>>& inStrokes) { // Build X // Formulate to solver return std::vector<std::vector<int>>(); } <|endoftext|>
<commit_before>// some global var/constants const Int_t kNSM = 4; // for first LHC run const Int_t kNRCU = 2; AliCaloAltroMapping *fMapping[4]; // 1 for each side (A/C) and each RCU (0/1), i.e. 2*2 total const Int_t kNBranch = 2; const Int_t kNFEC = 10; // 0..9, when including LED Ref const Int_t kNChip = 5; // really 0,2..4, i.e. skip #1 const Int_t kNChan = 16; Float_t fMeanPed[kNSM][kNRCU][kNBranch][kNFEC][kNChip][kNChan]; Float_t fRmsPed[kNSM][kNRCU][kNBranch][kNFEC][kNChip][kNChan]; // const int kNStrips = 24; // per SM Int_t fHWAddrLEDRef[kNStrips][2]; // [2] is for Low/High gain // help methods void GetPedVal(const Int_t iSM, const Int_t igain, const TProfile2D *h2); void GetPedValLEDRef(const Int_t iSM, const Int_t igain, const TProfile *h); void PrintScript(); void Clear(); Int_t GetHWAddress(Int_t iside, Int_t icol, Int_t irow, Int_t igain); Int_t GetHWAddressLEDRef(Int_t istrip, Int_t igain); void DecodeHWAddress(Int_t hwAddr, Int_t & branch, Int_t & FEC, Int_t & chip, Int_t & chan); void GetMapping(); void CreateMappingLEDRef(); // main method void GeneratePedestalScript(const char * filename = "alien/Run113790_113790_v1_s0.root") { // get the DA info/object TFile *file = TFile::Open(filename); AliCaloCalibPedestal *emcCalibPedestal = AliCDBEntry->GetObject(); // Get mapping file info, and clear arrays Clear(); GetMapping(); CreateMappingLEDRef(); // Store the pedestal info for (Int_t iSM=0; iSM<kNSM; iSM++) { GetPedVal( iSM, 0, emcCalibPedestal->GetPedProfileLowGain(iSM) ); GetPedVal( iSM, 1, emcCalibPedestal->GetPedProfileHighGain(iSM) ); GetPedValLEDRef( iSM, 0, emcCalibPedestal->GetPedLEDRefProfileLowGain(iSM) ); GetPedValLEDRef( iSM, 1, emcCalibPedestal->GetPedLEDRefProfileHighGain(iSM) ); } // Generate the needed scripts PrintScript(); } void GetPedVal(const Int_t iSM, const Int_t igain, const TProfile2D *h2) { Int_t isect = iSM / 2; // Int_t iside = iSM % 2; // A or C side Int_t nCols = h2->GetNbinsX(); Int_t nRows = h2->GetNbinsY(); // debug print printf("GetPedVal: iSM %d isect %d iside %d igain %d nRows %d nCols %d\n", iSM, isect, iside, igain, nRows, nCols); Int_t hwAddress = 0; Int_t iRCU = 0; Int_t branch = 0; Int_t FEC = 0; Int_t chip = 0; Int_t chan = 0; Int_t icol = 0; Int_t irow = 0; Int_t bin = 0; for (icol=0; icol<nCols; icol++) { for (irow=0; irow<nRows; irow++) { hwAddress = GetHWAddress(iside, icol, irow, igain, iRCU); DecodeHWAddress(hwAddress, branch, FEC, chip, chan); bin = h2->FindBin(icol, irow); // store the values fMeanPed[iSM][iRCU][branch][FEC][chip][chan] = h2->GetBinContent(bin); fRmsPed[iSM][iRCU][branch][FEC][chip][chan] = h2->GetBinError(bin); } } return; } void GetPedValLEDRef(const Int_t iSM, const Int_t igain, const TProfile *h) { Int_t isect = iSM / 2; // Int_t iside = iSM % 2; // A or C side Int_t nStrips = h->GetNbinsX(); // debug print printf("GetPedValLEDRef: iSM %d isect %d iside %d igain %d nStrips %d\n", iSM, isect, iside, igain, nStrips); Int_t hwAddress = 0; Int_t iRCU = 0; // always true for LED Ref FEE Int_t branch = 0; Int_t FEC = 0; Int_t chip = 0; Int_t chan = 0; Int_t icol = 0; Int_t irow = 0; Int_t bin = 0; for (int istrip=0; istrip<nStrips; istrip++) { hwAddress = GetHWAddressLEDRef(istrip, igain); DecodeHWAddress(hwAddress, branch, FEC, chip, chan); bin = h->FindBin(istrip); // store the values fMeanPed[iSM][iRCU][branch][FEC][chip][chan] = h->GetBinContent(bin); fRmsPed[iSM][iRCU][branch][FEC][chip][chan] = h->GetBinError(bin); } return; } void PrintScript() { const char * sideStr[] = {"A","C"}; const char * branchStr[] = {"A","B"}; int VFPED = 0x06; int RCUWrite = 0x200000; char filename[100]; char scriptLine[200]; Int_t iSM = 0; Int_t iRCU = 0; Int_t ibranch = 0; Int_t iFEC = 0; Int_t ichip = 0; Int_t ichan = 0; Int_t Ped = 0; for (iSM=0; iSM<kNSM; iSM++) { int iside = iSM % 2; int isect = iSM / 2; for (iRCU=0; iRCU<kNRCU; iRCU++) { sprintf(filename, "setSM%1s%dRCU%d.scr", sideStr[iside], isect, iRCU); ofstream fout(filename); int nscriptLines = 0; for (ibranch=0; ibranch<kNBranch; ibranch++) { int firstFEC = 1; if (ibranch==0 && iRCU==0) { // extra LED Ref FEE in this location firstFEC = 0; } for (iFEC=firstFEC; iFEC<kNFEC; iFEC++) { // FEC 1..9 (or 0..9) for (ichip=0; ichip<kNChip; ichip++) { // ALTRO 0,2,3,4 if (ichip!=1) { for (ichan=0; ichan<kNChan; ichan++) { if (iFEC!=0 || (ichan<8 || ichan>11)) { Ped = TMath::Nint(fMeanPed[iSM][iRCU][ibranch][iFEC][ichip][ichan]); // int writeAddr = (ibranch << 16) | (iFEC << 12) | (ichip << 9) | (ichan << 5) | VFPED | RCUWrite; sprintf(scriptLine, "w 0x%04x 0x%06x # Branch %s, Card %d, Altro %d, Chan %d", nscriptLines, writeAddr, branchStr[ibranch], iFEC, ichip, ichan); fout << scriptLine << endl; nscriptLines++; int writeVal = (Ped | RCUWrite); sprintf(scriptLine, "w 0x%04x 0x%06x # Pedestal 0x%x = %d", nscriptLines, writeVal, Ped, Ped); fout << scriptLine << endl; nscriptLines++; } } } } } } // ending, with execute and update step.. sprintf(scriptLine, "w 0x%04x 0x380000 # End of the sequence", nscriptLines); fout << scriptLine << endl; nscriptLines++; sprintf(scriptLine, "w 0x%04x 0x3F0000 # End of the instruction memory", nscriptLines); fout << scriptLine << endl; nscriptLines++; fout << "wait 100 us" << endl; fout << "w 0x5304 0x0 \# execute and update registers" << endl; fout.close(); } // iRCU }// iSM return; } void Clear() { for (Int_t iSM=0; iSM<kNSM; iSM++) { for (Int_t iRCU=0; iRCU<kNRCU; iRCU++) { for (Int_t ibranch=0; ibranch<kNBranch; ibranch++) { for (Int_t iFEC=0; iFEC<kNFEC; iFEC++) { for (Int_t ichip=0; ichip<kNChip; ichip++) { for (Int_t ichan=0; ichan<kNChan; ichan++) { fMeanPed[iSM][iRCU][ibranch][iFEC][ichip][ichan] = 0; fRmsPed[iSM][iRCU][ibranch][iFEC][ichip][ichan] = 0; } } } } } } for (int istrip=0; istrip<kNStrips; istrip++) { fHWAddrLEDRef[istrip][0] = 0; fHWAddrLEDRef[istrip][1] = 0; } return; } void DecodeHWAddress(Int_t hwAddr, Int_t & branch, Int_t & FEC, Int_t & chip, Int_t & chan) { chan = hwAddr & 0xf; chip = (hwAddr >> 4) & 0x7; FEC = (hwAddr >> 7) & 0xf; branch = (hwAddr >> 11) & 0x1; return; } Int_t GetHWAddress(Int_t iside, Int_t icol, Int_t irow, Int_t igain, Int_t & iRCU) { iRCU = -111; //RCU0 if (0<=irow&&irow<8) iRCU=0; // first cable row else if (8<=irow&&irow<16 && 0<=icol&&icol<24) iRCU=0; // first half; //second cable row //RCU1 else if(8<=irow&&irow<16 && 24<=icol&&icol<48) iRCU=1; // second half; //second cable row else if(16<=irow&&irow<24) iRCU=1; // third cable row // swap for odd=C side, to allow us to cable both sides the same Int_t iRCUSide = iRCU; if (iside == 1) { iRCU = 1 - iRCU; iRCUSide = iRCU + 2; // to make it map file index } Int_t hwAddress = fMapping[iRCUSide]->GetHWAddress(irow, icol, igain); return hwAddress; } Int_t GetHWAddressLEDRef(Int_t istrip, Int_t igain) { Int_t iRCU = 0; // for both sides; LED ref info is the same for both sides Int_t caloflag = 3; // AliCaloRawStreamV3::kLEDMonData; Int_t hwAddress = fHWAddrLEDRef[istrip][igain]; return hwAddress; } void GetMapping() { TString sides[]={"A","C"}; // Read mapping files from $ALICE_ROOT/CALO/mapping/*.data TString path = gSystem->Getenv("ALICE_ROOT"); path += "/EMCAL/mapping/RCU"; TString path2; for(Int_t j = 0; j < 2; j++){ // sides for(Int_t i = 0; i < 2; i++) { // RCU path2 = path; path2 += i; path2 += sides[j]; path2 += ".data"; printf("Mapping file: %s\n",path2.Data()); fMapping[j*2 + i] = new AliCaloAltroMapping(path2.Data()); } } return; } void CreateMappingLEDRef() { Int_t iRCU = 0; // for both sides; LED ref info is the same for both sides Int_t caloflag = 3; // AliCaloRawStreamV3::kLEDMonData; Int_t maxAddr = 1 << 7; // LED Ref FEE is in FEC pos 0, i.e. addr space 0..127 int nLEDRefFEEChan = 0; Int_t branch = 0; Int_t FEC = 0; Int_t chip = 0; Int_t chan = 0; for (int hwaddr = 0; hwaddr<maxAddr; hwaddr++) { DecodeHWAddress(hwaddr, branch, FEC, chip, chan); if ( (chip!=1 && chip<kNChip) && // ALTROs 0,2,3,4 (chan<8 || chan>11) ) { // actual installed LED Ref FEE channels int istrip = fMapping[iRCU]->GetPad(hwaddr); int igain = fMapping[iRCU]->GetPadRow(hwaddr); int iflag = fMapping[iRCU]->GetSector(hwaddr); if (iflag == caloflag) { fHWAddrLEDRef[istrip][igain] = hwaddr; nLEDRefFEEChan++; } } } cout << " nLEDRefFEEChan " << nLEDRefFEEChan << endl; } <commit_msg>check for channels with bad pedestal RMS values (noisy)<commit_after>// some global var/constants const Int_t kNSM = 4; // for first LHC run const Int_t kNRCU = 2; AliCaloAltroMapping *fMapping[4]; // 1 for each side (A/C) and each RCU (0/1), i.e. 2*2 total const Int_t kNBranch = 2; const Int_t kNFEC = 10; // 0..9, when including LED Ref const Int_t kNChip = 5; // really 0,2..4, i.e. skip #1 const Int_t kNChan = 16; Float_t fMeanPed[kNSM][kNRCU][kNBranch][kNFEC][kNChip][kNChan]; Float_t fRmsPed[kNSM][kNRCU][kNBranch][kNFEC][kNChip][kNChan]; // const int kNStrips = 24; // per SM Int_t fHWAddrLEDRef[kNStrips][2]; // [2] is for Low/High gain const Bool_t kDebug = kFALSE; const Float_t kBadRMS = 20; // help methods void GetPedVal(const Int_t iSM, const Int_t igain, const TProfile2D *h2); void GetPedValLEDRef(const Int_t iSM, const Int_t igain, const TProfile *h); void PrintScript(); void Clear(); Int_t GetHWAddress(Int_t iside, Int_t icol, Int_t irow, Int_t igain); Int_t GetHWAddressLEDRef(Int_t istrip, Int_t igain); void DecodeHWAddress(Int_t hwAddr, Int_t & branch, Int_t & FEC, Int_t & chip, Int_t & chan); void GetMapping(); void CreateMappingLEDRef(); // main method void //GeneratePedestalScript(const char * filename = "alien/Run113790_113790_v1_s0.root") // 1st set GeneratePedestalScript(const char * filename = "Run117756_117756_v1_s0.root") // 2nd set { // get the DA info/object TFile *file = TFile::Open(filename); //TMP AliCaloCalibPedestal *emcCalibPedestal = AliCDBEntry->GetObject(); if (kDebug) { file->ls(); } // Get mapping file info, and clear arrays Clear(); GetMapping(); CreateMappingLEDRef(); // Store the pedestal info for (Int_t iSM=0; iSM<kNSM; iSM++) { GetPedVal( iSM, 0, emcCalibPedestal->GetPedProfileLowGain(iSM) ); GetPedVal( iSM, 1, emcCalibPedestal->GetPedProfileHighGain(iSM) ); GetPedValLEDRef( iSM, 0, emcCalibPedestal->GetPedLEDRefProfileLowGain(iSM) ); GetPedValLEDRef( iSM, 1, emcCalibPedestal->GetPedLEDRefProfileHighGain(iSM) ); } // Generate the needed scripts PrintScript(); } void GetPedVal(const Int_t iSM, const Int_t igain, const TProfile2D *h2) { Int_t isect = iSM / 2; // Int_t iside = iSM % 2; // A or C side Int_t nCols = h2->GetNbinsX(); Int_t nRows = h2->GetNbinsY(); if (kDebug) { printf("GetPedVal: iSM %d isect %d iside %d igain %d nRows %d nCols %d\n", iSM, isect, iside, igain, nRows, nCols); } Int_t hwAddress = 0; Int_t iRCU = 0; Int_t branch = 0; Int_t FEC = 0; Int_t chip = 0; Int_t chan = 0; Int_t icol = 0; Int_t irow = 0; Int_t bin = 0; for (icol=0; icol<nCols; icol++) { for (irow=0; irow<nRows; irow++) { hwAddress = GetHWAddress(iside, icol, irow, igain, iRCU); DecodeHWAddress(hwAddress, branch, FEC, chip, chan); bin = h2->FindBin(icol, irow); // store the values fMeanPed[iSM][iRCU][branch][FEC][chip][chan] = h2->GetBinContent(bin); fRmsPed[iSM][iRCU][branch][FEC][chip][chan] = h2->GetBinError(bin); // report bad RMS channels: if (h2->GetBinError(bin) > kBadRMS) { printf(" bad pedestal RMS: iSM %d icol %d irow %d igain %d iRCU %d branch %d FEC %d chip %d chan %d - mean %4.1f rms %4.1f\n", iSM, icol, irow, igain, iRCU, branch, FEC, chip, chan, h2->GetBinContent(bin), h2->GetBinError(bin)); } } } return; } void GetPedValLEDRef(const Int_t iSM, const Int_t igain, const TProfile *h) { Int_t isect = iSM / 2; // Int_t iside = iSM % 2; // A or C side Int_t nStrips = h->GetNbinsX(); if (kDebug) { printf("GetPedValLEDRef: iSM %d isect %d iside %d igain %d nStrips %d\n", iSM, isect, iside, igain, nStrips); } Int_t hwAddress = 0; Int_t iRCU = 0; // always true for LED Ref FEE Int_t branch = 0; Int_t FEC = 0; Int_t chip = 0; Int_t chan = 0; Int_t icol = 0; Int_t irow = 0; Int_t bin = 0; for (int istrip=0; istrip<nStrips; istrip++) { hwAddress = GetHWAddressLEDRef(istrip, igain); DecodeHWAddress(hwAddress, branch, FEC, chip, chan); bin = h->FindBin(istrip); // store the values fMeanPed[iSM][iRCU][branch][FEC][chip][chan] = h->GetBinContent(bin); fRmsPed[iSM][iRCU][branch][FEC][chip][chan] = h->GetBinError(bin); } return; } void PrintScript() { const char * sideStr[] = {"A","C"}; const char * branchStr[] = {"A","B"}; int VFPED = 0x06; int RCUWrite = 0x200000; char filename[100]; char scriptLine[200]; Int_t iSM = 0; Int_t iRCU = 0; Int_t ibranch = 0; Int_t iFEC = 0; Int_t ichip = 0; Int_t ichan = 0; Int_t Ped = 0; for (iSM=0; iSM<kNSM; iSM++) { int iside = iSM % 2; int isect = iSM / 2; for (iRCU=0; iRCU<kNRCU; iRCU++) { sprintf(filename, "setSM%1s%dRCU%d.scr", sideStr[iside], isect, iRCU); ofstream fout(filename); int nscriptLines = 0; for (ibranch=0; ibranch<kNBranch; ibranch++) { int firstFEC = 1; if (ibranch==0 && iRCU==0) { // extra LED Ref FEE in this location firstFEC = 0; } for (iFEC=firstFEC; iFEC<kNFEC; iFEC++) { // FEC 1..9 (or 0..9) for (ichip=0; ichip<kNChip; ichip++) { // ALTRO 0,2,3,4 if (ichip!=1) { for (ichan=0; ichan<kNChan; ichan++) { if (iFEC!=0 || (ichan<8 || ichan>11)) { Ped = TMath::Nint(fMeanPed[iSM][iRCU][ibranch][iFEC][ichip][ichan]); // raise Ped value to max for channels with exceptionally large RMS if (fRmsPed[iSM][iRCU][ibranch][iFEC][ichip][ichan] > kBadRMS) { printf(" bad pedestal RMS: iSM %d iRCU %d ibranch %d iFEC %d ichip %d ichan %d - raising from %d to 0x3ff\n", iSM, iRCU, ibranch, iFEC, ichip, ichan, Ped); Ped = 0x3ff; } // int writeAddr = (ibranch << 16) | (iFEC << 12) | (ichip << 9) | (ichan << 5) | VFPED | RCUWrite; sprintf(scriptLine, "w 0x%04x 0x%06x # Branch %s, Card %d, Altro %d, Chan %d", nscriptLines, writeAddr, branchStr[ibranch], iFEC, ichip, ichan); fout << scriptLine << endl; nscriptLines++; int writeVal = (Ped | RCUWrite); sprintf(scriptLine, "w 0x%04x 0x%06x # Pedestal 0x%x = %d", nscriptLines, writeVal, Ped, Ped); fout << scriptLine << endl; nscriptLines++; } } } } } } // ending, with execute and update step.. sprintf(scriptLine, "w 0x%04x 0x380000 # End of the sequence", nscriptLines); fout << scriptLine << endl; nscriptLines++; sprintf(scriptLine, "w 0x%04x 0x3F0000 # End of the instruction memory", nscriptLines); fout << scriptLine << endl; nscriptLines++; fout << "wait 100 us" << endl; fout << "w 0x5304 0x0 \# execute and update registers" << endl; fout.close(); } // iRCU }// iSM return; } void Clear() { for (Int_t iSM=0; iSM<kNSM; iSM++) { for (Int_t iRCU=0; iRCU<kNRCU; iRCU++) { for (Int_t ibranch=0; ibranch<kNBranch; ibranch++) { for (Int_t iFEC=0; iFEC<kNFEC; iFEC++) { for (Int_t ichip=0; ichip<kNChip; ichip++) { for (Int_t ichan=0; ichan<kNChan; ichan++) { fMeanPed[iSM][iRCU][ibranch][iFEC][ichip][ichan] = 0; fRmsPed[iSM][iRCU][ibranch][iFEC][ichip][ichan] = 0; } } } } } } for (int istrip=0; istrip<kNStrips; istrip++) { fHWAddrLEDRef[istrip][0] = 0; fHWAddrLEDRef[istrip][1] = 0; } return; } void DecodeHWAddress(Int_t hwAddr, Int_t & branch, Int_t & FEC, Int_t & chip, Int_t & chan) { chan = hwAddr & 0xf; chip = (hwAddr >> 4) & 0x7; FEC = (hwAddr >> 7) & 0xf; branch = (hwAddr >> 11) & 0x1; return; } Int_t GetHWAddress(Int_t iside, Int_t icol, Int_t irow, Int_t igain, Int_t & iRCU) { iRCU = -111; //RCU0 if (0<=irow&&irow<8) iRCU=0; // first cable row else if (8<=irow&&irow<16 && 0<=icol&&icol<24) iRCU=0; // first half; //second cable row //RCU1 else if(8<=irow&&irow<16 && 24<=icol&&icol<48) iRCU=1; // second half; //second cable row else if(16<=irow&&irow<24) iRCU=1; // third cable row // swap for odd=C side, to allow us to cable both sides the same Int_t iRCUSide = iRCU; if (iside == 1) { iRCU = 1 - iRCU; iRCUSide = iRCU + 2; // to make it map file index } Int_t hwAddress = fMapping[iRCUSide]->GetHWAddress(irow, icol, igain); return hwAddress; } Int_t GetHWAddressLEDRef(Int_t istrip, Int_t igain) { Int_t iRCU = 0; // for both sides; LED ref info is the same for both sides Int_t caloflag = 3; // AliCaloRawStreamV3::kLEDMonData; Int_t hwAddress = fHWAddrLEDRef[istrip][igain]; return hwAddress; } void GetMapping() { TString sides[]={"A","C"}; // Read mapping files from $ALICE_ROOT/CALO/mapping/*.data TString path = gSystem->Getenv("ALICE_ROOT"); path += "/EMCAL/mapping/RCU"; TString path2; for(Int_t j = 0; j < 2; j++){ // sides for(Int_t i = 0; i < 2; i++) { // RCU path2 = path; path2 += i; path2 += sides[j]; path2 += ".data"; if (kDebug) { printf("Mapping file: %s\n",path2.Data()); } fMapping[j*2 + i] = new AliCaloAltroMapping(path2.Data()); } } return; } void CreateMappingLEDRef() { Int_t iRCU = 0; // for both sides; LED ref info is the same for both sides Int_t caloflag = 3; // AliCaloRawStreamV3::kLEDMonData; Int_t maxAddr = 1 << 7; // LED Ref FEE is in FEC pos 0, i.e. addr space 0..127 int nLEDRefFEEChan = 0; Int_t branch = 0; Int_t FEC = 0; Int_t chip = 0; Int_t chan = 0; for (int hwaddr = 0; hwaddr<maxAddr; hwaddr++) { DecodeHWAddress(hwaddr, branch, FEC, chip, chan); if ( (chip!=1 && chip<kNChip) && // ALTROs 0,2,3,4 (chan<8 || chan>11) ) { // actual installed LED Ref FEE channels int istrip = fMapping[iRCU]->GetPad(hwaddr); int igain = fMapping[iRCU]->GetPadRow(hwaddr); int iflag = fMapping[iRCU]->GetSector(hwaddr); if (iflag == caloflag) { fHWAddrLEDRef[istrip][igain] = hwaddr; nLEDRefFEEChan++; } } } if (kDebug) { cout << " nLEDRefFEEChan " << nLEDRefFEEChan << endl; } } <|endoftext|>
<commit_before>#include <ros/ros.h> #include <aidu_core/node.h> #include <aidu_elevator/elevator.h> #include <aidu_elevator/actions/locatebutton.h> #include <aidu_elevator/actions/pushbutton.h> #include <aidu_elevator/OutsideButton.h> #include <aidu_elevator/ElevatorNavigation.h> #include <aidu_elevator/actions/go_to_door.h> #include <aidu_elevator/actions/movetobutton.h> #include <aidu_elevator/actions/move_in_elevator.h> #include <aidu_elevator/Button.h> using namespace aidu; Elevator::Elevator(): core::Node::Node() { subscriber = nh->subscribe<aidu_elevator::ElevatorNavigation>("/elevator/navigation", 1, &Elevator::activate, this); this->currentAction = 0; } void Elevator::activate(const aidu_elevator::ElevatorNavigation::ConstPtr& message) { targetFloor = message->target_floor; currentFloor = message->current_floor; //removeActions(); setupActions(); } void Elevator::removeActions() { while (this->currentAction != 0) { aidu::elevator::Action* next = this->currentAction->getNextAction(); delete this->currentAction; this->currentAction = next; } } void Elevator::setupActions() { // Construct actions int outsideButton; if (currentFloor > targetFloor) { outsideButton = aidu_elevator::Button::BUTTON_DOWN; } else { outsideButton = aidu_elevator::Button::BUTTON_UP; } int insideButton; switch(targetFloor) { case -1: insideButton = aidu_elevator::Button::BUTTON_K; break; case 0: insideButton = aidu_elevator::Button::BUTTON_B; break; case 1: insideButton = aidu_elevator::Button::BUTTON_1; break; case 2: insideButton = aidu_elevator::Button::BUTTON_2; break; case 3: insideButton = aidu_elevator::Button::BUTTON_3; break; case 4: insideButton = aidu_elevator::Button::BUTTON_4; break; default: ROS_ERROR("Unknown target floor: %d", targetFloor); return; } elevator::LocateButton* locateButtonOutside = new elevator::LocateButton(this->nh, outsideButton, 0.0); elevator::MoveToButton* moveToButtonOutside = new elevator::MoveToButton(this->nh, outsideButton); elevator::PushButton* pushButtonOutside = new elevator::PushButton(this->nh, outsideButton); elevator::GoToDoor* goToDoor = new elevator::GoToDoor(this->nh); elevator::MoveInElevator* moveInElevator = new elevator::MoveInElevator(this->nh); elevator::LocateButton* locateButtonInside = new elevator::LocateButton(this->nh, insideButton, -1.56); elevator::PushButton* pushButtonInside = new elevator::PushButton(this->nh, insideButton); // Chain actions together locateButtonOutside->setNextAction(moveToButtonOutside); moveToButtonOutside->setNextAction(pushButtonOutside); pushButtonOutside->setNextAction(goToDoor); goToDoor->setNextAction(moveInElevator); moveInElevator->setNextAction(locateButtonInside); locateButtonInside->setNextAction(pushButtonInside); // Set the first action as current action this->currentAction = moveInElevator; } void Elevator::spin() { ros::Rate loopRate(20); while(ros::ok()) { if(this->currentAction != 0) { this->currentAction->execute(); if(this->currentAction->finished()) { aidu::elevator::Action* next = this->currentAction->getNextAction(); delete this->currentAction; this->currentAction = next; } } ros::spinOnce(); loopRate.sleep(); } } int main(int argc, char **argv) { ros::init(argc, argv, "elevator"); aidu::Elevator elevator; elevator.spin(); return 0; }<commit_msg>Added reposition to the chain of events<commit_after>#include <ros/ros.h> #include <aidu_core/node.h> #include <aidu_elevator/elevator.h> #include <aidu_elevator/actions/locatebutton.h> #include <aidu_elevator/actions/pushbutton.h> #include <aidu_elevator/OutsideButton.h> #include <aidu_elevator/ElevatorNavigation.h> #include <aidu_elevator/actions/go_to_door.h> #include <aidu_elevator/actions/movetobutton.h> #include <aidu_elevator/actions/move_in_elevator.h> #include <aidu_elevator/actions/reposition.h> #include <aidu_elevator/Button.h> using namespace aidu; Elevator::Elevator(): core::Node::Node() { subscriber = nh->subscribe<aidu_elevator::ElevatorNavigation>("/elevator/navigation", 1, &Elevator::activate, this); this->currentAction = 0; } void Elevator::activate(const aidu_elevator::ElevatorNavigation::ConstPtr& message) { targetFloor = message->target_floor; currentFloor = message->current_floor; //removeActions(); setupActions(); } void Elevator::removeActions() { while (this->currentAction != 0) { aidu::elevator::Action* next = this->currentAction->getNextAction(); delete this->currentAction; this->currentAction = next; } } void Elevator::setupActions() { // Construct actions int outsideButton; if (currentFloor > targetFloor) { outsideButton = aidu_elevator::Button::BUTTON_DOWN; } else { outsideButton = aidu_elevator::Button::BUTTON_UP; } int insideButton; switch(targetFloor) { case -1: insideButton = aidu_elevator::Button::BUTTON_K; break; case 0: insideButton = aidu_elevator::Button::BUTTON_B; break; case 1: insideButton = aidu_elevator::Button::BUTTON_1; break; case 2: insideButton = aidu_elevator::Button::BUTTON_2; break; case 3: insideButton = aidu_elevator::Button::BUTTON_3; break; case 4: insideButton = aidu_elevator::Button::BUTTON_4; break; default: ROS_ERROR("Unknown target floor: %d", targetFloor); return; } elevator::LocateButton* locateButtonOutside = new elevator::LocateButton(this->nh, outsideButton, 0.0); elevator::MoveToButton* moveToButtonOutside = new elevator::MoveToButton(this->nh, outsideButton); elevator::PushButton* pushButtonOutside = new elevator::PushButton(this->nh, outsideButton); elevator::GoToDoor* goToDoor = new elevator::GoToDoor(this->nh); elevator::MoveInElevator* moveInElevator = new elevator::MoveInElevator(this->nh); elevator::LocateButton* locateButtonInside = new elevator::LocateButton(this->nh, insideButton, -1.56); elevator::PushButton* pushButtonInside = new elevator::PushButton(this->nh, insideButton); elevator::Reposition* reposition = new elevator::Reposition(this->nh); // Chain actions together locateButtonOutside->setNextAction(moveToButtonOutside); moveToButtonOutside->setNextAction(pushButtonOutside); pushButtonOutside->setNextAction(goToDoor); goToDoor->setNextAction(moveInElevator); moveInElevator->setNextAction(locateButtonInside); locateButtonInside->setNextAction(pushButtonInside); pushButtonInside->setNextAction(reposition); // Set the first action as current action this->currentAction = moveInElevator; } void Elevator::spin() { ros::Rate loopRate(20); while(ros::ok()) { if(this->currentAction != 0) { this->currentAction->execute(); if(this->currentAction->finished()) { aidu::elevator::Action* next = this->currentAction->getNextAction(); delete this->currentAction; this->currentAction = next; } } ros::spinOnce(); loopRate.sleep(); } } int main(int argc, char **argv) { ros::init(argc, argv, "elevator"); aidu::Elevator elevator; elevator.spin(); return 0; }<|endoftext|>
<commit_before>/* This file is part of Akregator. Copyright (C) 2007 Frank Osterfeld <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "selectioncontroller.h" #include "actionmanager.h" #include "article.h" #include "articlemodel.h" #include "feedlist.h" #include "subscriptionlistmodel.h" #include "treenode.h" #include <KRandom> #include <KDebug> #include <QAbstractItemView> #include <QMenu> #include <QTimer> using namespace Akregator; namespace { static Akregator::Article articleForIndex( const QModelIndex& index, Akregator::FeedList* feedList ) { if ( !index.isValid() ) return Akregator::Article(); const QString guid = index.data( Akregator::ArticleModel::GuidRole ).toString(); const QString feedId = index.data( Akregator::ArticleModel::FeedIdRole ).toString(); return feedList->findArticle( feedId, guid ); } static QList<Akregator::Article> articlesForIndexes( const QModelIndexList& indexes, Akregator::FeedList* feedList ) { QList<Akregator::Article> articles; Q_FOREACH ( const QModelIndex i, indexes ) { articles.append( articleForIndex( i, feedList ) ); } return articles; } static Akregator::TreeNode* subscriptionForIndex( const QModelIndex& index, Akregator::FeedList* feedList ) { if ( !index.isValid() ) return 0L; return feedList->findByID( index.data( Akregator::SubscriptionListModel::SubscriptionIdRole ).toInt() ); } } // anon namespace Akregator::SelectionController::SelectionController( QObject* parent ) : AbstractSelectionController( parent ), m_feedList( 0 ), m_feedSelector( 0 ), m_articleLister( 0 ), m_singleDisplay( 0 ), m_subscriptionModel ( 0 ), m_folderExpansionHandler( 0 ), m_selectedSubscription( 0 ), m_articleModel( 0 ) { m_articleFetchTimer = new QTimer( this ); connect( m_articleFetchTimer, SIGNAL( timeout() ), this, SLOT( articleHeadersAvailable() ) ); } void Akregator::SelectionController::setFeedSelector( QAbstractItemView* feedSelector ) { if ( m_feedSelector ) { m_feedSelector->disconnect( this ); if ( m_feedSelector->selectionModel() ) m_feedSelector->selectionModel()->disconnect( this ); } m_feedSelector = feedSelector; setUp(); } void Akregator::SelectionController::setArticleLister( Akregator::ArticleLister* lister ) { if ( m_articleLister ) m_articleLister->articleSelectionModel()->disconnect( this ); m_articleLister = lister; setUp(); } void Akregator::SelectionController::setSingleArticleDisplay( Akregator::SingleArticleDisplay* display ) { m_singleDisplay = display; } Akregator::Article Akregator::SelectionController::currentArticle() const { return ::articleForIndex( m_articleLister->articleSelectionModel()->currentIndex(), m_feedList ); } QList<Akregator::Article> Akregator::SelectionController::selectedArticles() const { return ::articlesForIndexes( m_articleLister->articleSelectionModel()->selectedRows(), m_feedList ); } Akregator::TreeNode* Akregator::SelectionController::selectedSubscription() const { return ::subscriptionForIndex( m_feedSelector->selectionModel()->currentIndex(), m_feedList ); } void Akregator::SelectionController::setFeedList( Akregator::FeedList* list ) { m_feedList = list; setUp(); } void Akregator::SelectionController::setFolderExpansionHandler( Akregator::FolderExpansionHandler* handler ) { m_folderExpansionHandler = handler; if ( !handler ) return; handler->setFeedList( m_feedList ); handler->setModel( m_subscriptionModel ); } void Akregator::SelectionController::setUp() { kDebug(); if ( !m_feedList || !m_feedSelector || !m_articleLister ) return; m_subscriptionModel = new SubscriptionListModel( m_feedList, this ); if ( m_folderExpansionHandler ) { m_folderExpansionHandler->setFeedList( m_feedList ); m_folderExpansionHandler->setModel( m_subscriptionModel ); } m_feedSelector->setModel( m_subscriptionModel ); // setUp might be called more than once, so disconnect first //connect exactly once: disconnect( m_feedSelector->selectionModel(), SIGNAL( currentChanged( QModelIndex, QModelIndex ) ), this, SLOT( selectedSubscriptionChanged( QModelIndex ) ) ); connect( m_feedSelector->selectionModel(), SIGNAL( currentChanged( QModelIndex, QModelIndex ) ), this, SLOT( selectedSubscriptionChanged( QModelIndex ) ) ); //connect exactly once: disconnect( m_feedSelector, SIGNAL( customContextMenuRequested( QPoint ) ), this, SLOT( subscriptionContextMenuRequested( QPoint ) ) ); connect( m_feedSelector, SIGNAL( customContextMenuRequested( QPoint ) ), this, SLOT( subscriptionContextMenuRequested( QPoint ) ) ); if ( m_articleLister->itemView() ) { //connect exactly once: disconnect( m_articleLister->itemView(), SIGNAL( doubleClicked( QModelIndex ) ), this, SLOT( articleIndexDoubleClicked( QModelIndex ) ) ); connect( m_articleLister->itemView(), SIGNAL( doubleClicked( QModelIndex ) ), this, SLOT( articleIndexDoubleClicked( QModelIndex ) ) ); } } void Akregator::SelectionController::articleHeadersAvailable() { if(m_articleModel) delete m_articleModel; m_articleModel = new Akregator::ArticleModel( m_selectedSubscription ); m_articleLister->setArticleModel( m_articleModel ); m_articleLister->setIsAggregation( m_selectedSubscription->isAggregation() ); connect( m_articleLister->articleSelectionModel(), SIGNAL( selectionChanged( QItemSelection, QItemSelection ) ), this, SLOT( articleSelectionChanged() ) ); } void Akregator::SelectionController::selectedSubscriptionChanged( const QModelIndex& index ) { if ( !index.isValid() ) return; m_selectedSubscription = selectedSubscription(); emit currentSubscriptionChanged( m_selectedSubscription ); // using a timer here internally to simulate async data fetching (which is still synchronous), // to ensure the UI copes with async behavior later on if ( m_articleFetchTimer->isActive() ) m_articleFetchTimer->stop(); // to come: kill running list job m_articleFetchTimer->setInterval( KRandom::random() % 400 ); m_articleFetchTimer->setSingleShot( true ); m_articleFetchTimer->start(); } void Akregator::SelectionController::subscriptionContextMenuRequested( const QPoint& point ) { Q_ASSERT( m_feedSelector ); const TreeNode* const node = ::subscriptionForIndex( m_feedSelector->indexAt( point ), m_feedList ); if ( !node ) return; QWidget* w = ActionManager::getInstance()->container( node->isGroup() ? "feedgroup_popup" : "feeds_popup" ); QMenu* popup = qobject_cast<QMenu*>( w ); if ( popup ) { const QPoint globalPos = m_feedSelector->viewport()->mapToGlobal( point ); popup->exec( globalPos ); } } void Akregator::SelectionController::articleSelectionChanged() { const Akregator::Article article = currentArticle(); if ( m_singleDisplay ) m_singleDisplay->showArticle( article ); emit currentArticleChanged( article ); } void Akregator::SelectionController::articleIndexDoubleClicked( const QModelIndex& index ) { const Akregator::Article article = ::articleForIndex( index, m_feedList ); emit articleDoubleClicked( article ); } void SelectionController::setFilters( const std::vector<boost::shared_ptr<const Filters::AbstractMatcher> >& matchers ) { Q_ASSERT( m_articleLister ); m_articleLister->setFilters( matchers ); } #include "selectioncontroller.moc" <commit_msg>SVN_SILENT --warning<commit_after>/* This file is part of Akregator. Copyright (C) 2007 Frank Osterfeld <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "selectioncontroller.h" #include "actionmanager.h" #include "article.h" #include "articlemodel.h" #include "feedlist.h" #include "subscriptionlistmodel.h" #include "treenode.h" #include <KRandom> #include <KDebug> #include <QAbstractItemView> #include <QMenu> #include <QTimer> using namespace Akregator; namespace { static Akregator::Article articleForIndex( const QModelIndex& index, Akregator::FeedList* feedList ) { if ( !index.isValid() ) return Akregator::Article(); const QString guid = index.data( Akregator::ArticleModel::GuidRole ).toString(); const QString feedId = index.data( Akregator::ArticleModel::FeedIdRole ).toString(); return feedList->findArticle( feedId, guid ); } static QList<Akregator::Article> articlesForIndexes( const QModelIndexList& indexes, Akregator::FeedList* feedList ) { QList<Akregator::Article> articles; Q_FOREACH ( const QModelIndex i, indexes ) { articles.append( articleForIndex( i, feedList ) ); } return articles; } static Akregator::TreeNode* subscriptionForIndex( const QModelIndex& index, Akregator::FeedList* feedList ) { if ( !index.isValid() ) return 0L; return feedList->findByID( index.data( Akregator::SubscriptionListModel::SubscriptionIdRole ).toInt() ); } } // anon namespace Akregator::SelectionController::SelectionController( QObject* parent ) : AbstractSelectionController( parent ), m_feedList( 0 ), m_feedSelector( 0 ), m_articleLister( 0 ), m_singleDisplay( 0 ), m_subscriptionModel ( 0 ), m_folderExpansionHandler( 0 ), m_articleModel( 0 ), m_selectedSubscription( 0 ) { m_articleFetchTimer = new QTimer( this ); connect( m_articleFetchTimer, SIGNAL( timeout() ), this, SLOT( articleHeadersAvailable() ) ); } void Akregator::SelectionController::setFeedSelector( QAbstractItemView* feedSelector ) { if ( m_feedSelector ) { m_feedSelector->disconnect( this ); if ( m_feedSelector->selectionModel() ) m_feedSelector->selectionModel()->disconnect( this ); } m_feedSelector = feedSelector; setUp(); } void Akregator::SelectionController::setArticleLister( Akregator::ArticleLister* lister ) { if ( m_articleLister ) m_articleLister->articleSelectionModel()->disconnect( this ); m_articleLister = lister; setUp(); } void Akregator::SelectionController::setSingleArticleDisplay( Akregator::SingleArticleDisplay* display ) { m_singleDisplay = display; } Akregator::Article Akregator::SelectionController::currentArticle() const { return ::articleForIndex( m_articleLister->articleSelectionModel()->currentIndex(), m_feedList ); } QList<Akregator::Article> Akregator::SelectionController::selectedArticles() const { return ::articlesForIndexes( m_articleLister->articleSelectionModel()->selectedRows(), m_feedList ); } Akregator::TreeNode* Akregator::SelectionController::selectedSubscription() const { return ::subscriptionForIndex( m_feedSelector->selectionModel()->currentIndex(), m_feedList ); } void Akregator::SelectionController::setFeedList( Akregator::FeedList* list ) { m_feedList = list; setUp(); } void Akregator::SelectionController::setFolderExpansionHandler( Akregator::FolderExpansionHandler* handler ) { m_folderExpansionHandler = handler; if ( !handler ) return; handler->setFeedList( m_feedList ); handler->setModel( m_subscriptionModel ); } void Akregator::SelectionController::setUp() { kDebug(); if ( !m_feedList || !m_feedSelector || !m_articleLister ) return; m_subscriptionModel = new SubscriptionListModel( m_feedList, this ); if ( m_folderExpansionHandler ) { m_folderExpansionHandler->setFeedList( m_feedList ); m_folderExpansionHandler->setModel( m_subscriptionModel ); } m_feedSelector->setModel( m_subscriptionModel ); // setUp might be called more than once, so disconnect first //connect exactly once: disconnect( m_feedSelector->selectionModel(), SIGNAL( currentChanged( QModelIndex, QModelIndex ) ), this, SLOT( selectedSubscriptionChanged( QModelIndex ) ) ); connect( m_feedSelector->selectionModel(), SIGNAL( currentChanged( QModelIndex, QModelIndex ) ), this, SLOT( selectedSubscriptionChanged( QModelIndex ) ) ); //connect exactly once: disconnect( m_feedSelector, SIGNAL( customContextMenuRequested( QPoint ) ), this, SLOT( subscriptionContextMenuRequested( QPoint ) ) ); connect( m_feedSelector, SIGNAL( customContextMenuRequested( QPoint ) ), this, SLOT( subscriptionContextMenuRequested( QPoint ) ) ); if ( m_articleLister->itemView() ) { //connect exactly once: disconnect( m_articleLister->itemView(), SIGNAL( doubleClicked( QModelIndex ) ), this, SLOT( articleIndexDoubleClicked( QModelIndex ) ) ); connect( m_articleLister->itemView(), SIGNAL( doubleClicked( QModelIndex ) ), this, SLOT( articleIndexDoubleClicked( QModelIndex ) ) ); } } void Akregator::SelectionController::articleHeadersAvailable() { if(m_articleModel) delete m_articleModel; m_articleModel = new Akregator::ArticleModel( m_selectedSubscription ); m_articleLister->setArticleModel( m_articleModel ); m_articleLister->setIsAggregation( m_selectedSubscription->isAggregation() ); connect( m_articleLister->articleSelectionModel(), SIGNAL( selectionChanged( QItemSelection, QItemSelection ) ), this, SLOT( articleSelectionChanged() ) ); } void Akregator::SelectionController::selectedSubscriptionChanged( const QModelIndex& index ) { if ( !index.isValid() ) return; m_selectedSubscription = selectedSubscription(); emit currentSubscriptionChanged( m_selectedSubscription ); // using a timer here internally to simulate async data fetching (which is still synchronous), // to ensure the UI copes with async behavior later on if ( m_articleFetchTimer->isActive() ) m_articleFetchTimer->stop(); // to come: kill running list job m_articleFetchTimer->setInterval( KRandom::random() % 400 ); m_articleFetchTimer->setSingleShot( true ); m_articleFetchTimer->start(); } void Akregator::SelectionController::subscriptionContextMenuRequested( const QPoint& point ) { Q_ASSERT( m_feedSelector ); const TreeNode* const node = ::subscriptionForIndex( m_feedSelector->indexAt( point ), m_feedList ); if ( !node ) return; QWidget* w = ActionManager::getInstance()->container( node->isGroup() ? "feedgroup_popup" : "feeds_popup" ); QMenu* popup = qobject_cast<QMenu*>( w ); if ( popup ) { const QPoint globalPos = m_feedSelector->viewport()->mapToGlobal( point ); popup->exec( globalPos ); } } void Akregator::SelectionController::articleSelectionChanged() { const Akregator::Article article = currentArticle(); if ( m_singleDisplay ) m_singleDisplay->showArticle( article ); emit currentArticleChanged( article ); } void Akregator::SelectionController::articleIndexDoubleClicked( const QModelIndex& index ) { const Akregator::Article article = ::articleForIndex( index, m_feedList ); emit articleDoubleClicked( article ); } void SelectionController::setFilters( const std::vector<boost::shared_ptr<const Filters::AbstractMatcher> >& matchers ) { Q_ASSERT( m_articleLister ); m_articleLister->setFilters( matchers ); } #include "selectioncontroller.moc" <|endoftext|>
<commit_before>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <gtest/gtest.h> #include <fstream> #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/inference/tensorrt/convert/ut_helper.h" namespace paddle { namespace inference { namespace tensorrt { TEST(Pool2dOpConverter, main) { framework::Scope scope; std::unordered_set<std::string> parameters; TRTConvertValidation validator(5, parameters, scope, 1 << 15); // The ITensor's Dims should not contain the batch size. // So, the ITensor's Dims of input and output should be C * H * W. validator.DeclInputVar("pool2d-X", nvinfer1::Dims3(3, 4, 4)); validator.DeclOutputVar("pool2d-Out", nvinfer1::Dims3(3, 2, 2)); // Prepare Op description framework::OpDesc desc; desc.SetType("pool2d"); desc.SetInput("X", {"pool2d-X"}); desc.SetOutput("Out", {"pool2d-Out"}); std::vector<int> ksize({2, 2}); std::vector<int> strides({2, 2}); std::vector<int> paddings({0, 0}); std::string pooling_t = "max"; bool global_pooling = false; desc.SetAttr("pooling_type", pooling_t); desc.SetAttr("ksize", ksize); desc.SetAttr("strides", strides); desc.SetAttr("paddings", paddings); desc.SetAttr("global_pooling", global_pooling); LOG(INFO) << "set OP"; validator.SetOp(*desc.Proto()); LOG(INFO) << "execute"; validator.Execute(3); } } // namespace tensorrt } // namespace inference } // namespace paddle USE_OP(pool2d); <commit_msg>add pool2d test for global_pooling true<commit_after>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <gtest/gtest.h> #include <fstream> #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/inference/tensorrt/convert/ut_helper.h" namespace paddle { namespace inference { namespace tensorrt { TEST(Pool2dOpConverter, main) { framework::Scope scope; std::unordered_set<std::string> parameters; TRTConvertValidation validator(5, parameters, scope, 1 << 15); // The ITensor's Dims should not contain the batch size. // So, the ITensor's Dims of input and output should be C * H * W. validator.DeclInputVar("pool2d-X", nvinfer1::Dims3(3, 4, 4)); validator.DeclOutputVar("pool2d-Out", nvinfer1::Dims3(3, 2, 2)); // Prepare Op description framework::OpDesc desc; desc.SetType("pool2d"); desc.SetInput("X", {"pool2d-X"}); desc.SetOutput("Out", {"pool2d-Out"}); std::vector<int> ksize({2, 2}); std::vector<int> strides({2, 2}); std::vector<int> paddings({0, 0}); std::string pooling_t = "max"; bool global_pooling = false; desc.SetAttr("pooling_type", pooling_t); desc.SetAttr("ksize", ksize); desc.SetAttr("strides", strides); desc.SetAttr("paddings", paddings); desc.SetAttr("global_pooling", global_pooling); LOG(INFO) << "set OP"; validator.SetOp(*desc.Proto()); LOG(INFO) << "execute"; validator.Execute(3); } TEST(Pool2dOpConverter, test_global_pooling) { framework::Scope scope; std::unordered_set<std::string> parameters; TRTConvertValidation validator(5, parameters, scope, 1 << 15); // The ITensor's Dims should not contain the batch size. // So, the ITensor's Dims of input and output should be C * H * W. validator.DeclInputVar("pool2d-X", nvinfer1::Dims3(3, 4, 4)); validator.DeclOutputVar("pool2d-Out", nvinfer1::Dims3(3, 1, 1)); // Prepare Op description framework::OpDesc desc; desc.SetType("pool2d"); desc.SetInput("X", {"pool2d-X"}); desc.SetOutput("Out", {"pool2d-Out"}); std::vector<int> ksize({2, 2}); std::vector<int> strides({2, 2}); std::vector<int> paddings({0, 0}); std::string pooling_t = "max"; bool global_pooling = true; desc.SetAttr("pooling_type", pooling_t); desc.SetAttr("ksize", ksize); desc.SetAttr("strides", strides); desc.SetAttr("paddings", paddings); desc.SetAttr("global_pooling", global_pooling); LOG(INFO) << "set OP"; validator.SetOp(*desc.Proto()); LOG(INFO) << "execute"; validator.Execute(3); } } // namespace tensorrt } // namespace inference } // namespace paddle USE_OP(pool2d); <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: except.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2001-11-06 16:58:18 $ * * 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 <stdio.h> #include <dlfcn.h> #include <cxxabi.h> #include <hash_map> #include <rtl/strbuf.hxx> #include <rtl/ustrbuf.hxx> #include <osl/diagnose.h> #include <osl/mutex.hxx> #include <bridges/cpp_uno/bridge.hxx> #include <typelib/typedescription.hxx> #include <uno/any2.h> #include "share.hxx" using namespace ::std; using namespace ::osl; using namespace ::rtl; using namespace ::com::sun::star::uno; using namespace ::__cxxabiv1; namespace CPPU_CURRENT_NAMESPACE { void dummy_can_throw_anything( char const * ) { } //================================================================================================== static OUString toUNOname( char const * p ) SAL_THROW( () ) { #ifdef DEBUG char const * start = p; #endif // example: N3com3sun4star4lang24IllegalArgumentExceptionE OUStringBuffer buf( 64 ); OSL_ASSERT( 'N' == *p ); ++p; // skip N while ('E' != *p) { // read chars count long n = (*p++ - '0'); while ('0' <= *p && '9' >= *p) { n *= 10; n += (*p++ - '0'); } buf.appendAscii( p, n ); p += n; if ('E' != *p) buf.append( (sal_Unicode)'.' ); } #ifdef DEBUG OUString ret( buf.makeStringAndClear() ); OString c_ret( OUStringToOString( ret, RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> toUNOname(): %s => %s\n", start, c_ret.getStr() ); return ret; #else return buf.makeStringAndClear(); #endif } //================================================================================================== class RTTI { typedef hash_map< OUString, type_info *, OUStringHash > t_rtti_map; Mutex m_mutex; t_rtti_map m_rttis; t_rtti_map m_generatedRttis; void * m_hApp; public: RTTI() SAL_THROW( () ); ~RTTI() SAL_THROW( () ); type_info * getRTTI( typelib_CompoundTypeDescription * ) SAL_THROW( () ); private: type_info * generateRTTI( typelib_CompoundTypeDescription *, const char *pRttiName) SAL_THROW( () ); }; //__________________________________________________________________________________________________ RTTI::RTTI() SAL_THROW( () ) : m_hApp( dlopen( 0, RTLD_LAZY ) ) { } //__________________________________________________________________________________________________ RTTI::~RTTI() SAL_THROW( () ) { dlclose( m_hApp ); } //__________________________________________________________________________________________________ type_info * RTTI::generateRTTI( typelib_CompoundTypeDescription * pTypeDescr, const char *pRttiName ) { type_info *rtti = 0; if( ! pTypeDescr->pBaseTypeDescription ) { // this class has no base class rtti = new __class_type_info( strdup(pRttiName) ); } else { // ensure availability of base type_info *baseRtti = getRTTI( (typelib_CompoundTypeDescription*) pTypeDescr->pBaseTypeDescription ); rtti = new __si_class_type_info( strdup( pRttiName ), (__class_type_info *) baseRtti ); } return rtti; } //__________________________________________________________________________________________________ type_info * RTTI::getRTTI( typelib_CompoundTypeDescription *pTypeDescr ) SAL_THROW( () ) { type_info * rtti; OUString const & unoName = *(OUString const *)&pTypeDescr->aBase.pTypeName; MutexGuard guard( m_mutex ); t_rtti_map::const_iterator iFind( m_rttis.find( unoName ) ); if (iFind == m_rttis.end()) { // RTTI symbol OStringBuffer buf( 64 ); buf.append( RTL_CONSTASCII_STRINGPARAM("_ZTIN") ); sal_Int32 index = 0; do { OUString token( unoName.getToken( 0, '.', index ) ); buf.append( token.getLength() ); OString c_token( OUStringToOString( token, RTL_TEXTENCODING_ASCII_US ) ); buf.append( c_token ); } while (index >= 0); buf.append( 'E' ); OString rttiName( buf.makeStringAndClear() ); rtti = (type_info *)dlsym( m_hApp, rttiName.getStr() ); if( rtti ) { pair< t_rtti_map::iterator, bool > insertion( m_rttis.insert( t_rtti_map::value_type( unoName, rtti ) ) ); OSL_ENSURE( insertion.second, "### inserting new rtti failed?!" ); } else { // try to lookup the symbol in the generated rtti map t_rtti_map::const_iterator iFind( m_generatedRttis.find( unoName ) ); if (iFind == m_generatedRttis.end()) { // we must generate it ! // symbol and rtti-name is nearly identical, // the symbol is prefixed with _ZTI fprintf( stderr,"generated rtti for %s\n" , rttiName.getStr()+4 ); rtti = generateRTTI( pTypeDescr , rttiName+4 ); pair< t_rtti_map::iterator, bool > insertion( m_generatedRttis.insert( t_rtti_map::value_type( unoName, rtti ) ) ); OSL_ENSURE( insertion.second, "### inserting new rtti failed?!" ); } else { rtti = iFind->second; } } } else { rtti = iFind->second; } return rtti; } //-------------------------------------------------------------------------------------------------- static void deleteException( void * pExc ) { __cxa_exception const * header = ((__cxa_exception const *)pExc - 1); typelib_TypeDescription * pTD = 0; OUString unoName( toUNOname( header->exceptionType->name() ) ); ::typelib_typedescription_getByName( &pTD, unoName.pData ); OSL_ENSURE( pTD, "### unknown exception type! leaving out destruction => leaking!!!" ); if (pTD) { ::uno_destructData( pExc, pTD, cpp_release ); ::typelib_typedescription_release( pTD ); } } //================================================================================================== void raiseException( uno_Any * pUnoExc, uno_Mapping * pUno2Cpp ) { void * pCppExc; type_info * rtti; { // construct cpp exception object typelib_TypeDescription * pTypeDescr = 0; TYPELIB_DANGER_GET( &pTypeDescr, pUnoExc->pType ); OSL_ASSERT( pTypeDescr ); if (! pTypeDescr) terminate(); pCppExc = __cxa_allocate_exception( pTypeDescr->nSize ); ::uno_copyAndConvertData( pCppExc, pUnoExc->pData, pTypeDescr, pUno2Cpp ); // destruct uno exception ::uno_any_destruct( pUnoExc, 0 ); // avoiding locked counts static RTTI * s_rtti = 0; if (! s_rtti) { MutexGuard guard( Mutex::getGlobalMutex() ); if (! s_rtti) { #ifdef LEAK_STATIC_DATA s_rtti = new RTTI(); #else static RTTI rtti_data; s_rtti = &rtti_data; #endif } } rtti = (type_info *)s_rtti->getRTTI( (typelib_CompoundTypeDescription *) pTypeDescr ); TYPELIB_DANGER_RELEASE( pTypeDescr ); OSL_ENSURE( rtti, "### no rtti for throwing exception!" ); if (! rtti) terminate(); } __cxa_throw( pCppExc, rtti, deleteException ); } //================================================================================================== void fillUnoException( __cxa_exception * header, uno_Any * pExc, uno_Mapping * pCpp2Uno ) { OSL_ENSURE( header, "### no exception header!!!" ); if (! header) terminate(); typelib_TypeDescription * pExcTypeDescr = 0; OUString unoName( toUNOname( header->exceptionType->name() ) ); ::typelib_typedescription_getByName( &pExcTypeDescr, unoName.pData ); OSL_ENSURE( pExcTypeDescr, "### can not get type description for exception!!!" ); if (! pExcTypeDescr) terminate(); // construct uno exception any ::uno_any_constructAndConvert( pExc, header->adjustedPtr, pExcTypeDescr, pCpp2Uno ); ::typelib_typedescription_release( pExcTypeDescr ); } } <commit_msg>#92951#<commit_after>/************************************************************************* * * $RCSfile: except.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: dbo $ $Date: 2001-11-08 12:35:28 $ * * 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 <stdio.h> #include <dlfcn.h> #include <cxxabi.h> #include <hash_map> #include <rtl/strbuf.hxx> #include <rtl/ustrbuf.hxx> #include <osl/diagnose.h> #include <osl/mutex.hxx> #include <bridges/cpp_uno/bridge.hxx> #include <typelib/typedescription.hxx> #include <uno/any2.h> #include "share.hxx" using namespace ::std; using namespace ::osl; using namespace ::rtl; using namespace ::com::sun::star::uno; using namespace ::__cxxabiv1; namespace CPPU_CURRENT_NAMESPACE { void dummy_can_throw_anything( char const * ) { } //================================================================================================== static OUString toUNOname( char const * p ) SAL_THROW( () ) { #ifdef DEBUG char const * start = p; #endif // example: N3com3sun4star4lang24IllegalArgumentExceptionE OUStringBuffer buf( 64 ); OSL_ASSERT( 'N' == *p ); ++p; // skip N while ('E' != *p) { // read chars count long n = (*p++ - '0'); while ('0' <= *p && '9' >= *p) { n *= 10; n += (*p++ - '0'); } buf.appendAscii( p, n ); p += n; if ('E' != *p) buf.append( (sal_Unicode)'.' ); } #ifdef DEBUG OUString ret( buf.makeStringAndClear() ); OString c_ret( OUStringToOString( ret, RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> toUNOname(): %s => %s\n", start, c_ret.getStr() ); return ret; #else return buf.makeStringAndClear(); #endif } //================================================================================================== class RTTI { typedef hash_map< OUString, type_info *, OUStringHash > t_rtti_map; Mutex m_mutex; t_rtti_map m_rttis; t_rtti_map m_generatedRttis; void * m_hApp; public: RTTI() SAL_THROW( () ); ~RTTI() SAL_THROW( () ); type_info * getRTTI( typelib_CompoundTypeDescription * ) SAL_THROW( () ); }; //__________________________________________________________________________________________________ RTTI::RTTI() SAL_THROW( () ) : m_hApp( dlopen( 0, RTLD_LAZY ) ) { } //__________________________________________________________________________________________________ RTTI::~RTTI() SAL_THROW( () ) { dlclose( m_hApp ); } //__________________________________________________________________________________________________ type_info * RTTI::getRTTI( typelib_CompoundTypeDescription *pTypeDescr ) SAL_THROW( () ) { type_info * rtti; OUString const & unoName = *(OUString const *)&pTypeDescr->aBase.pTypeName; MutexGuard guard( m_mutex ); t_rtti_map::const_iterator iFind( m_rttis.find( unoName ) ); if (iFind == m_rttis.end()) { // RTTI symbol OStringBuffer buf( 64 ); buf.append( RTL_CONSTASCII_STRINGPARAM("_ZTIN") ); sal_Int32 index = 0; do { OUString token( unoName.getToken( 0, '.', index ) ); buf.append( token.getLength() ); OString c_token( OUStringToOString( token, RTL_TEXTENCODING_ASCII_US ) ); buf.append( c_token ); } while (index >= 0); buf.append( 'E' ); OString symName( buf.makeStringAndClear() ); rtti = (type_info *)dlsym( m_hApp, symName.getStr() ); if (rtti) { pair< t_rtti_map::iterator, bool > insertion( m_rttis.insert( t_rtti_map::value_type( unoName, rtti ) ) ); OSL_ENSURE( insertion.second, "### inserting new rtti failed?!" ); } else { // try to lookup the symbol in the generated rtti map t_rtti_map::const_iterator iFind( m_generatedRttis.find( unoName ) ); if (iFind == m_generatedRttis.end()) { // we must generate it ! // symbol and rtti-name is nearly identical, // the symbol is prefixed with _ZTI char const * rttiName = symName.getStr() +4; #ifdef DEBUG fprintf( stderr,"generated rtti for %s\n", rttiName ); #endif if (pTypeDescr->pBaseTypeDescription) { // ensure availability of base type_info * base_rtti = getRTTI( (typelib_CompoundTypeDescription *)pTypeDescr->pBaseTypeDescription ); rtti = new __si_class_type_info( strdup( rttiName ), (__class_type_info *)base_rtti ); } else { // this class has no base class rtti = new __class_type_info( strdup( rttiName ) ); } pair< t_rtti_map::iterator, bool > insertion( m_generatedRttis.insert( t_rtti_map::value_type( unoName, rtti ) ) ); OSL_ENSURE( insertion.second, "### inserting new generated rtti failed?!" ); } else // taking already generated rtti { rtti = iFind->second; } } } else { rtti = iFind->second; } return rtti; } //-------------------------------------------------------------------------------------------------- static void deleteException( void * pExc ) { __cxa_exception const * header = ((__cxa_exception const *)pExc - 1); typelib_TypeDescription * pTD = 0; OUString unoName( toUNOname( header->exceptionType->name() ) ); ::typelib_typedescription_getByName( &pTD, unoName.pData ); OSL_ENSURE( pTD, "### unknown exception type! leaving out destruction => leaking!!!" ); if (pTD) { ::uno_destructData( pExc, pTD, cpp_release ); ::typelib_typedescription_release( pTD ); } } //================================================================================================== void raiseException( uno_Any * pUnoExc, uno_Mapping * pUno2Cpp ) { void * pCppExc; type_info * rtti; { // construct cpp exception object typelib_TypeDescription * pTypeDescr = 0; TYPELIB_DANGER_GET( &pTypeDescr, pUnoExc->pType ); OSL_ASSERT( pTypeDescr ); if (! pTypeDescr) terminate(); pCppExc = __cxa_allocate_exception( pTypeDescr->nSize ); ::uno_copyAndConvertData( pCppExc, pUnoExc->pData, pTypeDescr, pUno2Cpp ); // destruct uno exception ::uno_any_destruct( pUnoExc, 0 ); // avoiding locked counts static RTTI * s_rtti = 0; if (! s_rtti) { MutexGuard guard( Mutex::getGlobalMutex() ); if (! s_rtti) { #ifdef LEAK_STATIC_DATA s_rtti = new RTTI(); #else static RTTI rtti_data; s_rtti = &rtti_data; #endif } } rtti = (type_info *)s_rtti->getRTTI( (typelib_CompoundTypeDescription *) pTypeDescr ); TYPELIB_DANGER_RELEASE( pTypeDescr ); OSL_ENSURE( rtti, "### no rtti for throwing exception!" ); if (! rtti) terminate(); } __cxa_throw( pCppExc, rtti, deleteException ); } //================================================================================================== void fillUnoException( __cxa_exception * header, uno_Any * pExc, uno_Mapping * pCpp2Uno ) { OSL_ENSURE( header, "### no exception header!!!" ); if (! header) terminate(); typelib_TypeDescription * pExcTypeDescr = 0; OUString unoName( toUNOname( header->exceptionType->name() ) ); ::typelib_typedescription_getByName( &pExcTypeDescr, unoName.pData ); OSL_ENSURE( pExcTypeDescr, "### can not get type description for exception!!!" ); if (! pExcTypeDescr) terminate(); // construct uno exception any ::uno_any_constructAndConvert( pExc, header->adjustedPtr, pExcTypeDescr, pCpp2Uno ); ::typelib_typedescription_release( pExcTypeDescr ); } } <|endoftext|>
<commit_before>/************************************************************************** * * Copyright 2011 Jose Fonseca * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **************************************************************************/ #include <string.h> #include "retrace.hpp" #include "glproc.hpp" #include "glstate.hpp" #include "glretrace.hpp" #include "os_time.hpp" namespace glretrace { bool insideList = false; bool insideGlBeginEnd = false; struct CallQuery { GLuint ids[3]; unsigned call; GLuint program; const trace::FunctionSig *sig; uint64_t start; uint64_t duration; }; static bool firstFrame = true; static std::list<CallQuery> callQueries; static const int maxActiveCallQueries = 128; static std::map<glws::Context*, GLuint> activePrograms; void checkGlError(trace::Call &call) { GLenum error = glGetError(); if (error == GL_NO_ERROR) { return; } std::ostream & os = retrace::warning(call); os << "glGetError("; os << call.name(); os << ") = "; switch (error) { case GL_INVALID_ENUM: os << "GL_INVALID_ENUM"; break; case GL_INVALID_VALUE: os << "GL_INVALID_VALUE"; break; case GL_INVALID_OPERATION: os << "GL_INVALID_OPERATION"; break; case GL_STACK_OVERFLOW: os << "GL_STACK_OVERFLOW"; break; case GL_STACK_UNDERFLOW: os << "GL_STACK_UNDERFLOW"; break; case GL_OUT_OF_MEMORY: os << "GL_OUT_OF_MEMORY"; break; case GL_INVALID_FRAMEBUFFER_OPERATION: os << "GL_INVALID_FRAMEBUFFER_OPERATION"; break; case GL_TABLE_TOO_LARGE: os << "GL_TABLE_TOO_LARGE"; break; default: os << error; break; } os << "\n"; } static GLuint64 getGpuTimestamp() { GLuint query = 0; GLuint64 timestamp = 0; if (retrace::profilingGpuTimes) { glGenQueries(1, &query); glQueryCounter(query, GL_TIMESTAMP); glGetQueryObjectui64vEXT(query, GL_QUERY_RESULT, &timestamp); glDeleteQueries(1, &query); } return timestamp; } static GLuint64 getCpuTimestamp() { if (retrace::profilingCpuTimes) { return os::getTime() * (1.0E9 / os::timeFrequency); } else { return 0; } } static void completeCallQuery(CallQuery& query) { /* Get call start and duration */ GLuint64 timestamp = 0, duration = 0, samples = 0; if (retrace::profilingGpuTimes) { glGetQueryObjectui64vEXT(query.ids[0], GL_QUERY_RESULT, &timestamp); glGetQueryObjectui64vEXT(query.ids[1], GL_QUERY_RESULT, &duration); } if (retrace::profilingPixelsDrawn) { glGetQueryObjectui64vEXT(query.ids[2], GL_QUERY_RESULT, &samples); } glDeleteQueries(3, query.ids); /* Add call to profile */ retrace::profiler.addCall(query.call, query.sig->name, query.program, samples, timestamp, duration, query.start, query.duration); } void flushQueries() { for (std::list<CallQuery>::iterator itr = callQueries.begin(); itr != callQueries.end(); ++itr) { completeCallQuery(*itr); } callQueries.clear(); } void setActiveProgram(GLuint program) { activePrograms[glretrace::currentContext] = program; } static GLuint getActiveProgram() { std::map<glws::Context*, GLuint>::iterator it; it = activePrograms.find(glretrace::currentContext); if (it == activePrograms.end()) return 0; return it->second; } void beginProfile(trace::Call &call) { if (firstFrame) { const char* extensions = (const char*)glGetString(GL_EXTENSIONS); if (!glws::checkExtension("GL_ARB_timer_query", extensions)) { std::cout << "Error: Cannot run profile, GL_ARB_timer_query extension is not supported." << std::endl; exit(-1); } frame_start(); } /* Ensure we don't have TOO many queries waiting for results */ if (callQueries.size() >= maxActiveCallQueries) { completeCallQuery(callQueries.front()); callQueries.pop_front(); } /* Create call query */ CallQuery query; query.call = call.no; query.sig = call.sig; query.program = getActiveProgram(); glGenQueries(3, query.ids); if (retrace::profilingGpuTimes) { glQueryCounter(query.ids[0], GL_TIMESTAMP); glBeginQuery(GL_TIME_ELAPSED, query.ids[1]); } if (retrace::profilingPixelsDrawn) { glBeginQuery(GL_SAMPLES_PASSED, query.ids[2]); } if (retrace::profilingCpuTimes) { query.start = os::getTime(); } callQueries.push_back(query); } void endProfile(trace::Call &call) { if (retrace::profilingCpuTimes) { CallQuery& query = callQueries.back(); query.duration = (os::getTime() - query.start) * (1.0E9 / os::timeFrequency); } if (retrace::profilingGpuTimes) { glEndQuery(GL_TIME_ELAPSED); } if (retrace::profilingPixelsDrawn) { glEndQuery(GL_SAMPLES_PASSED); } } void frame_start() { firstFrame = false; if (retrace::profiling) { retrace::profiler.addFrameStart(retrace::frameNo, getGpuTimestamp(), getCpuTimestamp()); } } void frame_complete(trace::Call &call) { if (retrace::profiling) { /* Complete any remaining queries */ flushQueries(); /* Indicate end of current frame */ retrace::profiler.addFrameEnd(getGpuTimestamp(), getCpuTimestamp()); } retrace::frameComplete(call); /* Indicate start of next frame */ frame_start(); if (!currentDrawable) { return; } if (retrace::debug && !currentDrawable->visible) { retrace::warning(call) << "could not infer drawable size (glViewport never called)\n"; } } } /* namespace glretrace */ void retrace::setUp(void) { glws::init(); } void retrace::addCallbacks(retrace::Retracer &retracer) { retracer.addCallbacks(glretrace::gl_callbacks); retracer.addCallbacks(glretrace::glx_callbacks); retracer.addCallbacks(glretrace::wgl_callbacks); retracer.addCallbacks(glretrace::cgl_callbacks); retracer.addCallbacks(glretrace::egl_callbacks); } image::Image * retrace::getSnapshot(void) { if (!glretrace::currentDrawable) { return NULL; } return glstate::getDrawBufferImage(); } bool retrace::dumpState(std::ostream &os) { if (glretrace::insideGlBeginEnd || !glretrace::currentDrawable || !glretrace::currentContext) { return false; } glstate::dumpCurrentContext(os); return true; } void retrace::flushRendering(void) { glretrace::flushQueries(); glFlush(); } void retrace::waitForInput(void) { while (glws::processEvents()) { } } void retrace::cleanUp(void) { glws::cleanup(); } <commit_msg>Removed arbitary limit on active queries.<commit_after>/************************************************************************** * * Copyright 2011 Jose Fonseca * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **************************************************************************/ #include <string.h> #include "retrace.hpp" #include "glproc.hpp" #include "glstate.hpp" #include "glretrace.hpp" #include "os_time.hpp" namespace glretrace { bool insideList = false; bool insideGlBeginEnd = false; struct CallQuery { GLuint ids[3]; unsigned call; GLuint program; const trace::FunctionSig *sig; uint64_t start; uint64_t duration; }; static bool firstFrame = true; static std::list<CallQuery> callQueries; static std::map<glws::Context*, GLuint> activePrograms; void checkGlError(trace::Call &call) { GLenum error = glGetError(); if (error == GL_NO_ERROR) { return; } std::ostream & os = retrace::warning(call); os << "glGetError("; os << call.name(); os << ") = "; switch (error) { case GL_INVALID_ENUM: os << "GL_INVALID_ENUM"; break; case GL_INVALID_VALUE: os << "GL_INVALID_VALUE"; break; case GL_INVALID_OPERATION: os << "GL_INVALID_OPERATION"; break; case GL_STACK_OVERFLOW: os << "GL_STACK_OVERFLOW"; break; case GL_STACK_UNDERFLOW: os << "GL_STACK_UNDERFLOW"; break; case GL_OUT_OF_MEMORY: os << "GL_OUT_OF_MEMORY"; break; case GL_INVALID_FRAMEBUFFER_OPERATION: os << "GL_INVALID_FRAMEBUFFER_OPERATION"; break; case GL_TABLE_TOO_LARGE: os << "GL_TABLE_TOO_LARGE"; break; default: os << error; break; } os << "\n"; } static GLuint64 getGpuTimestamp() { GLuint query = 0; GLuint64 timestamp = 0; if (retrace::profilingGpuTimes) { glGenQueries(1, &query); glQueryCounter(query, GL_TIMESTAMP); glGetQueryObjectui64vEXT(query, GL_QUERY_RESULT, &timestamp); glDeleteQueries(1, &query); } return timestamp; } static GLuint64 getCpuTimestamp() { if (retrace::profilingCpuTimes) { return os::getTime() * (1.0E9 / os::timeFrequency); } else { return 0; } } static void completeCallQuery(CallQuery& query) { /* Get call start and duration */ GLuint64 timestamp = 0, duration = 0, samples = 0; if (retrace::profilingGpuTimes) { glGetQueryObjectui64vEXT(query.ids[0], GL_QUERY_RESULT, &timestamp); glGetQueryObjectui64vEXT(query.ids[1], GL_QUERY_RESULT, &duration); } if (retrace::profilingPixelsDrawn) { glGetQueryObjectui64vEXT(query.ids[2], GL_QUERY_RESULT, &samples); } glDeleteQueries(3, query.ids); /* Add call to profile */ retrace::profiler.addCall(query.call, query.sig->name, query.program, samples, timestamp, duration, query.start, query.duration); } void flushQueries() { for (std::list<CallQuery>::iterator itr = callQueries.begin(); itr != callQueries.end(); ++itr) { completeCallQuery(*itr); } callQueries.clear(); } void setActiveProgram(GLuint program) { activePrograms[glretrace::currentContext] = program; } static GLuint getActiveProgram() { std::map<glws::Context*, GLuint>::iterator it; it = activePrograms.find(glretrace::currentContext); if (it == activePrograms.end()) return 0; return it->second; } void beginProfile(trace::Call &call) { if (firstFrame) { const char* extensions = (const char*)glGetString(GL_EXTENSIONS); if (!glws::checkExtension("GL_ARB_timer_query", extensions)) { std::cout << "Error: Cannot run profile, GL_ARB_timer_query extension is not supported." << std::endl; exit(-1); } frame_start(); } /* Create call query */ CallQuery query; query.call = call.no; query.sig = call.sig; query.program = getActiveProgram(); glGenQueries(3, query.ids); if (retrace::profilingGpuTimes) { glQueryCounter(query.ids[0], GL_TIMESTAMP); glBeginQuery(GL_TIME_ELAPSED, query.ids[1]); } if (retrace::profilingPixelsDrawn) { glBeginQuery(GL_SAMPLES_PASSED, query.ids[2]); } if (retrace::profilingCpuTimes) { query.start = os::getTime(); } callQueries.push_back(query); } void endProfile(trace::Call &call) { if (retrace::profilingCpuTimes) { CallQuery& query = callQueries.back(); query.duration = (os::getTime() - query.start) * (1.0E9 / os::timeFrequency); } if (retrace::profilingGpuTimes) { glEndQuery(GL_TIME_ELAPSED); } if (retrace::profilingPixelsDrawn) { glEndQuery(GL_SAMPLES_PASSED); } } void frame_start() { firstFrame = false; if (retrace::profiling) { retrace::profiler.addFrameStart(retrace::frameNo, getGpuTimestamp(), getCpuTimestamp()); } } void frame_complete(trace::Call &call) { if (retrace::profiling) { /* Complete any remaining queries */ flushQueries(); /* Indicate end of current frame */ retrace::profiler.addFrameEnd(getGpuTimestamp(), getCpuTimestamp()); } retrace::frameComplete(call); /* Indicate start of next frame */ frame_start(); if (!currentDrawable) { return; } if (retrace::debug && !currentDrawable->visible) { retrace::warning(call) << "could not infer drawable size (glViewport never called)\n"; } } } /* namespace glretrace */ void retrace::setUp(void) { glws::init(); } void retrace::addCallbacks(retrace::Retracer &retracer) { retracer.addCallbacks(glretrace::gl_callbacks); retracer.addCallbacks(glretrace::glx_callbacks); retracer.addCallbacks(glretrace::wgl_callbacks); retracer.addCallbacks(glretrace::cgl_callbacks); retracer.addCallbacks(glretrace::egl_callbacks); } image::Image * retrace::getSnapshot(void) { if (!glretrace::currentDrawable) { return NULL; } return glstate::getDrawBufferImage(); } bool retrace::dumpState(std::ostream &os) { if (glretrace::insideGlBeginEnd || !glretrace::currentDrawable || !glretrace::currentContext) { return false; } glstate::dumpCurrentContext(os); return true; } void retrace::flushRendering(void) { glretrace::flushQueries(); glFlush(); } void retrace::waitForInput(void) { while (glws::processEvents()) { } } void retrace::cleanUp(void) { glws::cleanup(); } <|endoftext|>
<commit_before>#include "ROOT/TDataFrame.hxx" #include "gtest/gtest.h" using namespace ROOT::Experimental; class TDFRanges : public ::testing::Test { protected: TDFRanges() : fTDF(100) {} TDataFrame &GetTDF() { return fTDF; } private: TDataFrame fTDF; }; TEST_F(TDFRanges, API) { auto &tdf = GetTDF(); // all Range signatures. Event-loop is run once auto c1 = tdf.Range(0).Count(); auto c2 = tdf.Range(10).Count(); auto m = tdf.Range(5, 50).Max<ULong64_t>("tdfentry_"); auto t = tdf.Range(5, 10, 3).Take<ULong64_t>("tdfentry_"); EXPECT_EQ(*c1, 100u); EXPECT_EQ(*c2, 10u); EXPECT_EQ(*m, 49u); EXPECT_EQ(*t, std::vector<ULong64_t>({5, 8})); } TEST_F(TDFRanges, FromRange) { auto &d = GetTDF(); auto min = d.Range(10, 50).Range(10, 20).Min<ULong64_t>("tdfentry_"); EXPECT_EQ(*min, 20u); } TEST_F(TDFRanges, FromFilter) { auto &d = GetTDF(); auto count = d.Filter([](ULong64_t b) { return b > 95; }, {"tdfentry_"}).Range(10).Count(); EXPECT_EQ(*count, 4u); } TEST_F(TDFRanges, FromDefine) { auto &d = GetTDF(); auto count = d.Define("dummy", []() { return 42; }).Range(10).Count(); EXPECT_EQ(*count, 10u); } TEST_F(TDFRanges, EarlyStop) { auto &d = GetTDF(); // TODO how do I check that the event-loop is actually interrupted after 20 iterations? unsigned int count = 0; auto b1 = d.Range(10).Count(); auto b2 = d.Define("counter", [&count]() { ++count; return 42; }) .Range(20) .Take<int>("counter"); EXPECT_EQ(*b1, 10u); EXPECT_EQ(*b2, std::vector<int>(20, 42)); EXPECT_EQ(count, 20u); } TEST_F(TDFRanges, NoEarlyStopping) { auto &d = GetTDF(); auto f = d.Filter([](int b) { return b % 2 == 0; }, {"tdfentry_"}); auto b3 = f.Range(2).Count(); auto b4 = f.Count(); } #ifdef R__USE_IMT TEST(TDFRangesMT, ThrowIfIMT) { bool hasThrown = false; ROOT::EnableImplicitMT(); TDataFrame d(0); try { d.Range(0); } catch (const std::exception &e) { hasThrown = true; EXPECT_STREQ(e.what(), "Range was called with ImplicitMT enabled. Multi-thread ranges are not supported."); } EXPECT_TRUE(hasThrown); } #endif /**** REGRESSION TESTS ****/ TEST_F(TDFRanges, CorrectEarlyStop) { // one child ending before the father -- only one stop signal must be propagated upstream auto &d = GetTDF(); auto twenty = d.Range(10, 50).Range(10, 20).Min<ULong64_t>("tdfentry_"); auto four = d.Filter([](ULong64_t b) { return b > 95; }, {"tdfentry_"}).Range(10).Count(); EXPECT_EQ(*twenty, 20u); EXPECT_EQ(*four, 4u); // child and parent ending on the same entry -- only one stop signal must be propagated upstream auto two = d.Range(2).Range(2).Count(); auto ten = d.Range(10).Count(); EXPECT_EQ(*two, 2u); EXPECT_EQ(*ten, 10u); } TEST_F(TDFRanges, FinishAllActions) { // regression test for ROOT-9232 // reaching stop with multiple actions to be processed, remaining actions must be processed for this last entry auto &d = GetTDF(); auto ranged = d.Range(0, 3); auto c1 = ranged.Count(); auto c2 = ranged.Count(); EXPECT_EQ(*c1, 3ull); EXPECT_EQ(*c2, *c1); } <commit_msg>[TDF] Add regression test for ROOT-9272<commit_after>#include "ROOT/TDataFrame.hxx" #include "gtest/gtest.h" using namespace ROOT::Experimental; class TDFRanges : public ::testing::Test { protected: TDFRanges() : fTDF(100) {} TDataFrame &GetTDF() { return fTDF; } private: TDataFrame fTDF; }; TEST_F(TDFRanges, API) { auto &tdf = GetTDF(); // all Range signatures. Event-loop is run once auto c1 = tdf.Range(0).Count(); auto c2 = tdf.Range(10).Count(); auto m = tdf.Range(5, 50).Max<ULong64_t>("tdfentry_"); auto t = tdf.Range(5, 10, 3).Take<ULong64_t>("tdfentry_"); EXPECT_EQ(*c1, 100u); EXPECT_EQ(*c2, 10u); EXPECT_EQ(*m, 49u); EXPECT_EQ(*t, std::vector<ULong64_t>({5, 8})); } TEST_F(TDFRanges, FromRange) { auto &d = GetTDF(); auto min = d.Range(10, 50).Range(10, 20).Min<ULong64_t>("tdfentry_"); EXPECT_EQ(*min, 20u); } TEST_F(TDFRanges, FromFilter) { auto &d = GetTDF(); auto count = d.Filter([](ULong64_t b) { return b > 95; }, {"tdfentry_"}).Range(10).Count(); EXPECT_EQ(*count, 4u); } TEST_F(TDFRanges, FromDefine) { auto &d = GetTDF(); auto count = d.Define("dummy", []() { return 42; }).Range(10).Count(); EXPECT_EQ(*count, 10u); } TEST_F(TDFRanges, EarlyStop) { auto &d = GetTDF(); // TODO how do I check that the event-loop is actually interrupted after 20 iterations? unsigned int count = 0; auto b1 = d.Range(10).Count(); auto b2 = d.Define("counter", [&count]() { ++count; return 42; }) .Range(20) .Take<int>("counter"); EXPECT_EQ(*b1, 10u); EXPECT_EQ(*b2, std::vector<int>(20, 42)); EXPECT_EQ(count, 20u); } TEST_F(TDFRanges, NoEarlyStopping) { auto &d = GetTDF(); auto f = d.Filter([](int b) { return b % 2 == 0; }, {"tdfentry_"}); auto b3 = f.Range(2).Count(); auto b4 = f.Count(); } #ifdef R__USE_IMT TEST(TDFRangesMT, ThrowIfIMT) { bool hasThrown = false; ROOT::EnableImplicitMT(); TDataFrame d(0); try { d.Range(0); } catch (const std::exception &e) { hasThrown = true; EXPECT_STREQ(e.what(), "Range was called with ImplicitMT enabled. Multi-thread ranges are not supported."); } EXPECT_TRUE(hasThrown); } #endif /**** REGRESSION TESTS ****/ TEST_F(TDFRanges, CorrectEarlyStop) { // one child ending before the father -- only one stop signal must be propagated upstream auto &d = GetTDF(); auto twenty = d.Range(10, 50).Range(10, 20).Min<ULong64_t>("tdfentry_"); auto four = d.Filter([](ULong64_t b) { return b > 95; }, {"tdfentry_"}).Range(10).Count(); EXPECT_EQ(*twenty, 20u); EXPECT_EQ(*four, 4u); // child and parent ending on the same entry -- only one stop signal must be propagated upstream auto two = d.Range(2).Range(2).Count(); auto ten = d.Range(10).Count(); EXPECT_EQ(*two, 2u); EXPECT_EQ(*ten, 10u); } TEST_F(TDFRanges, FinishAllActions) { // regression test for ROOT-9232 // reaching stop with multiple actions to be processed, remaining actions must be processed for this last entry auto &d = GetTDF(); auto ranged = d.Range(0, 3); auto c1 = ranged.Count(); auto c2 = ranged.Count(); EXPECT_EQ(*c1, 3ull); EXPECT_EQ(*c2, *c1); } TEST_F(TDFRanges, EntryLoss) { // regression test for ROOT-9272 auto d = GetTDF(); auto d_0_30 = d.Range(0, 30); EXPECT_EQ(*d_0_30.Count(), 30u); EXPECT_EQ(*d_0_30.Count(), 30u); } /****** END REGRESSION TESTS ******/ <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved */ #ifndef _Stroika_Foundation_Memory_SharedByValue_inl_ #define _Stroika_Foundation_Memory_SharedByValue_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Debug/Trace.h" namespace Stroika { namespace Foundation { namespace Memory { /* ******************************************************************************** ************** SharedByValue_CopyByFunction<T,SHARED_IMLP> ********************* ******************************************************************************** */ template <typename T, typename SHARED_IMLP> inline SharedByValue_CopyByFunction<T, SHARED_IMLP>::SharedByValue_CopyByFunction (SHARED_IMLP (*copier) (const T&)) noexcept : fCopier (copier) { RequireNotNull (copier); } template <typename T, typename SHARED_IMLP> inline SHARED_IMLP SharedByValue_CopyByFunction<T, SHARED_IMLP>::Copy (const T& t) const { AssertNotNull (fCopier); return (*fCopier) (t); } /* ******************************************************************************** *************** SharedByValue_CopyByDefault<T,SHARED_IMLP> ********************* ******************************************************************************** */ template <typename T, typename SHARED_IMLP> inline SHARED_IMLP SharedByValue_CopyByDefault<T, SHARED_IMLP>::Copy (const T& t) { return SHARED_IMLP (new T (t)); } /* ******************************************************************************** ****** SharedByValue_CopySharedPtrExternallySynchronized<T,SHARED_IMLP> ******** ******************************************************************************** */ template <typename T, typename SHARED_IMLP> inline SHARED_IMLP SharedByValue_CopySharedPtrExternallySynchronized<T, SHARED_IMLP>::Load (const SHARED_IMLP& copyFrom) { return copyFrom; } template <typename T, typename SHARED_IMLP> inline void SharedByValue_CopySharedPtrExternallySynchronized<T, SHARED_IMLP>::Store (SHARED_IMLP* storeTo, const SHARED_IMLP& o) { RequireNotNull (storeTo); *storeTo = o; } /* ******************************************************************************** ********* SharedByValue_CopySharedPtrAtomicSynchronized<T,SHARED_IMLP> ********* ******************************************************************************** */ template <typename T, typename SHARED_IMLP> inline SHARED_IMLP SharedByValue_CopySharedPtrAtomicSynchronized<T, SHARED_IMLP>::Load (const SHARED_IMLP& copyFrom) { return atomic_load (&copyFrom); } template <typename T, typename SHARED_IMLP> inline void SharedByValue_CopySharedPtrAtomicSynchronized<T, SHARED_IMLP>::Store (SHARED_IMLP* storeTo, const SHARED_IMLP& o) { RequireNotNull (storeTo); atomic_store (storeTo, o); } /* ******************************************************************************** ****************************** SharedByValue<TRAITS> *************************** ******************************************************************************** */ template <typename TRAITS> inline SharedByValue<TRAITS>::SharedByValue () noexcept : fCopier_ (element_copier_type ()) , fSharedImpl_ () { } template <typename TRAITS> inline SharedByValue<TRAITS>::SharedByValue (nullptr_t n) noexcept : fCopier_ (element_copier_type ()) , fSharedImpl_ () { } template <typename TRAITS> inline SharedByValue<TRAITS>::SharedByValue (const SharedByValue<TRAITS>& from) noexcept : fCopier_ (from.fCopier_) , fSharedImpl_ (shared_impl_copier_type::Load (from.fSharedImpl_)) { } template <typename TRAITS> inline SharedByValue<TRAITS>::SharedByValue (SharedByValue<TRAITS>&& from) noexcept : fCopier_ (from.fCopier_) , fSharedImpl_ (std::move (from.fSharedImpl_)) { } template <typename TRAITS> inline SharedByValue<TRAITS>::SharedByValue (const shared_ptr_type& from, const element_copier_type& copier) noexcept : fCopier_ (copier) , fSharedImpl_ (shared_impl_copier_type::Load (from)) { } template <typename TRAITS> inline SharedByValue<TRAITS>::SharedByValue (shared_ptr_type&& from, const element_copier_type&& copier) noexcept : fCopier_ (move (copier)) , fSharedImpl_ (move (from)) { } template <typename TRAITS> inline SharedByValue<TRAITS>::SharedByValue (element_type* from, const element_copier_type& copier) : fCopier_ (copier) , fSharedImpl_ (from) { } template <typename TRAITS> inline SharedByValue<TRAITS>& SharedByValue<TRAITS>::operator= (const SharedByValue<TRAITS>& rhs) { // If the pointers are the same, there is no need to copy, as the reference counts must also be the same, // and we can avoid the (common) and costly memory barrier if (fSharedImpl_.get () != rhs.fSharedImpl_.get ()) { fCopier_ = rhs.fCopier_; shared_impl_copier_type::Store (&fSharedImpl_, shared_impl_copier_type::Load (rhs.fSharedImpl_)); } return *this; } template <typename TRAITS> inline SharedByValue<TRAITS>& SharedByValue<TRAITS>::operator= (SharedByValue<TRAITS>&& rhs) { // If the pointers are the same, there is no need to copy, as the reference counts must also be the same, // and we can avoid the (common) and costly memory barrier if (fSharedImpl_.get () != rhs.fSharedImpl_.get ()) { fCopier_ = rhs.fCopier_; // ASSUME if doing a move() then this doesn't need to be a multithread safe copy (from the source), since // if its a temporary, you cannot have mulitple peopel referring to me shared_impl_copier_type::Store (&fSharedImpl_, rhs.fSharedImpl_); } return *this; } template <typename TRAITS> inline SharedByValue<TRAITS>& SharedByValue<TRAITS>::operator= (const shared_ptr_type& from) { // If the pointers are the same, there is no need to copy, as the reference counts must also be the same, // and we can avoid the (common) and costly memory barrier if (fSharedImpl_.get () != from.get ()) { shared_impl_copier_type::Store (&fSharedImpl_, shared_impl_copier_type::Load (from)); } return *this; } template <typename TRAITS> inline SharedByValue<TRAITS>& SharedByValue<TRAITS>::operator= (shared_ptr_type&& from) { // If the pointers are the same, there is no need to copy, as the reference counts must also be the same, // and we can avoid the (common) and costly memory barrier if (fSharedImpl_.get () != from.get ()) { // ASSUME if doing a move() then this doesn't need to be a multithread safe copy (from the source), since // if its a temporary, you cannot have mulitple peopel referring to me shared_impl_copier_type::Store (&fSharedImpl_, from); } return *this; } template <typename TRAITS> inline const typename SharedByValue<TRAITS>::element_type* SharedByValue<TRAITS>::get () const noexcept { return fSharedImpl_.get (); } template <typename TRAITS> template <typename... COPY_ARGS> inline typename SharedByValue<TRAITS>::element_type* SharedByValue<TRAITS>::get (COPY_ARGS&&... copyArgs) { element_type* ptr = fSharedImpl_.get (); /* * For non-const pointing, we must clone ourselves (if there are * extra referneces). If we are a nullptr pointer, nobody could actually * rereference it anyhow, so don't bother with the Assure1Reference() * in that case. */ if (ptr != nullptr) { Assure1Reference (forward<COPY_ARGS> (copyArgs)...); ptr = fSharedImpl_.get (); EnsureNotNull (ptr); } return ptr; } template <typename TRAITS> inline const typename SharedByValue<TRAITS>::element_type* SharedByValue<TRAITS>::cget () const noexcept { return get (); } template <typename TRAITS> inline const typename SharedByValue<TRAITS>::element_type* SharedByValue<TRAITS>::operator-> () const { return fSharedImpl_.get (); } template <typename TRAITS> inline typename SharedByValue<TRAITS>::element_type* SharedByValue<TRAITS>::operator-> () { return get (); } template <typename TRAITS> inline const typename SharedByValue<TRAITS>::element_type& SharedByValue<TRAITS>::operator* () const { const element_type* ptr = get (); EnsureNotNull (ptr); return *ptr; } template <typename TRAITS> inline typename SharedByValue<TRAITS>::element_type& SharedByValue<TRAITS>::operator* () { /* * For non-const dereferencing, we must clone ourselves (if there are * extra referneces). */ Assure1Reference (); element_type* ptr = get (); EnsureNotNull (ptr); return *ptr; } template <typename TRAITS> inline bool SharedByValue<TRAITS>::operator== (const SharedByValue<TRAITS>& rhs) const { return fSharedImpl_ == rhs.fSharedImpl_; } template <typename TRAITS> inline bool SharedByValue<TRAITS>::operator!= (const SharedByValue<TRAITS>& rhs) const { return fSharedImpl_ != rhs.fSharedImpl_; } template <typename TRAITS> inline typename SharedByValue<TRAITS>::element_copier_type SharedByValue<TRAITS>::GetCopier () const { return fCopier_; } template <typename TRAITS> inline SharedByValue_State SharedByValue<TRAITS>::GetSharingState () const { switch (fSharedImpl_.use_count ()) { case 0: Assert (fSharedImpl_.get () == nullptr); return SharedByValue_State::eNull; case 1: Assert (fSharedImpl_.get () != nullptr); return SharedByValue_State::eSolo; default: Assert (fSharedImpl_.get () != nullptr); //NOT NECESSARILY - cuz there is no lock // between the use_count and this unique call, so another object could decrement its count // and this could be that it was shared, but is no solo. // Assert (not fSharedImpl_.unique ()); // -- LGP 2015-01-10 return SharedByValue_State::eShared; } } template <typename TRAITS> inline bool SharedByValue<TRAITS>::unique () const { return fSharedImpl_.use_count () == 1; } template <typename TRAITS> inline unsigned int SharedByValue<TRAITS>::use_count () const { return fSharedImpl_.use_count (); } template <typename TRAITS> template <typename... COPY_ARGS> inline void SharedByValue<TRAITS>::Assure1Reference (COPY_ARGS&&... copyArgs) { if (not fSharedImpl_.use_count () == 1) { BreakReferences_ (forward<COPY_ARGS> (copyArgs)...); } } template <typename TRAITS> template <typename... COPY_ARGS> void SharedByValue<TRAITS>::BreakReferences_ (COPY_ARGS&&... copyArgs) { shared_ptr_type ptr2Clone{shared_impl_copier_type::Load (fSharedImpl_)}; // other thread could change this (if other thread accesses same envelope) // but this copy prevents the bare ptr from possibly becoming invalidated element_type* ptr = ptr2Clone.get (); RequireNotNull (ptr); /* * For a valid pointer that is reference counted and multiply shared, * make a copy of that pointer via our fCloner function, and assign * that cloned reference to this. * * Note that by doing so, we remove any references to the current * item, and end up with our having the sole reference to the new copy of fPtr. * * Since we will be cloning the given pointer, we assume(assert) that * it is non-nullptr. */ //Require (!SHARED_IMLP::unique ()); This is not NECESSARILY so. Another thread could have just released this pointer, in which case // the creation of a new object was pointless, but harmless, as the assignemnt should decrement to zero the old // value and it should go away. *this = SharedByValue<TRAITS> (fCopier_.Copy (*ptr, forward<COPY_ARGS> (copyArgs)...), fCopier_); #if qDebug //Ensure (fSharedImpl_.unique ()); // technically not 100% guarantied if two threads did this at the same time, but so rare interesting if ever triggered. // may need to lose this assert - maybe replace with #if qDebug DbgTrace if (not unique ()) { DbgTrace ("probably a bug, but not necessarily..."); } #endif } } } } #endif /*_Stroika_Foundation_Memory_SharedByValue_inl_*/ <commit_msg>fixed typo<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved */ #ifndef _Stroika_Foundation_Memory_SharedByValue_inl_ #define _Stroika_Foundation_Memory_SharedByValue_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Debug/Trace.h" namespace Stroika { namespace Foundation { namespace Memory { /* ******************************************************************************** ************** SharedByValue_CopyByFunction<T,SHARED_IMLP> ********************* ******************************************************************************** */ template <typename T, typename SHARED_IMLP> inline SharedByValue_CopyByFunction<T, SHARED_IMLP>::SharedByValue_CopyByFunction (SHARED_IMLP (*copier) (const T&)) noexcept : fCopier (copier) { RequireNotNull (copier); } template <typename T, typename SHARED_IMLP> inline SHARED_IMLP SharedByValue_CopyByFunction<T, SHARED_IMLP>::Copy (const T& t) const { AssertNotNull (fCopier); return (*fCopier) (t); } /* ******************************************************************************** *************** SharedByValue_CopyByDefault<T,SHARED_IMLP> ********************* ******************************************************************************** */ template <typename T, typename SHARED_IMLP> inline SHARED_IMLP SharedByValue_CopyByDefault<T, SHARED_IMLP>::Copy (const T& t) { return SHARED_IMLP (new T (t)); } /* ******************************************************************************** ****** SharedByValue_CopySharedPtrExternallySynchronized<T,SHARED_IMLP> ******** ******************************************************************************** */ template <typename T, typename SHARED_IMLP> inline SHARED_IMLP SharedByValue_CopySharedPtrExternallySynchronized<T, SHARED_IMLP>::Load (const SHARED_IMLP& copyFrom) { return copyFrom; } template <typename T, typename SHARED_IMLP> inline void SharedByValue_CopySharedPtrExternallySynchronized<T, SHARED_IMLP>::Store (SHARED_IMLP* storeTo, const SHARED_IMLP& o) { RequireNotNull (storeTo); *storeTo = o; } /* ******************************************************************************** ********* SharedByValue_CopySharedPtrAtomicSynchronized<T,SHARED_IMLP> ********* ******************************************************************************** */ template <typename T, typename SHARED_IMLP> inline SHARED_IMLP SharedByValue_CopySharedPtrAtomicSynchronized<T, SHARED_IMLP>::Load (const SHARED_IMLP& copyFrom) { return atomic_load (&copyFrom); } template <typename T, typename SHARED_IMLP> inline void SharedByValue_CopySharedPtrAtomicSynchronized<T, SHARED_IMLP>::Store (SHARED_IMLP* storeTo, const SHARED_IMLP& o) { RequireNotNull (storeTo); atomic_store (storeTo, o); } /* ******************************************************************************** ****************************** SharedByValue<TRAITS> *************************** ******************************************************************************** */ template <typename TRAITS> inline SharedByValue<TRAITS>::SharedByValue () noexcept : fCopier_ (element_copier_type ()) , fSharedImpl_ () { } template <typename TRAITS> inline SharedByValue<TRAITS>::SharedByValue (nullptr_t n) noexcept : fCopier_ (element_copier_type ()) , fSharedImpl_ () { } template <typename TRAITS> inline SharedByValue<TRAITS>::SharedByValue (const SharedByValue<TRAITS>& from) noexcept : fCopier_ (from.fCopier_) , fSharedImpl_ (shared_impl_copier_type::Load (from.fSharedImpl_)) { } template <typename TRAITS> inline SharedByValue<TRAITS>::SharedByValue (SharedByValue<TRAITS>&& from) noexcept : fCopier_ (from.fCopier_) , fSharedImpl_ (std::move (from.fSharedImpl_)) { } template <typename TRAITS> inline SharedByValue<TRAITS>::SharedByValue (const shared_ptr_type& from, const element_copier_type& copier) noexcept : fCopier_ (copier) , fSharedImpl_ (shared_impl_copier_type::Load (from)) { } template <typename TRAITS> inline SharedByValue<TRAITS>::SharedByValue (shared_ptr_type&& from, const element_copier_type&& copier) noexcept : fCopier_ (move (copier)) , fSharedImpl_ (move (from)) { } template <typename TRAITS> inline SharedByValue<TRAITS>::SharedByValue (element_type* from, const element_copier_type& copier) : fCopier_ (copier) , fSharedImpl_ (from) { } template <typename TRAITS> inline SharedByValue<TRAITS>& SharedByValue<TRAITS>::operator= (const SharedByValue<TRAITS>& rhs) { // If the pointers are the same, there is no need to copy, as the reference counts must also be the same, // and we can avoid the (common) and costly memory barrier if (fSharedImpl_.get () != rhs.fSharedImpl_.get ()) { fCopier_ = rhs.fCopier_; shared_impl_copier_type::Store (&fSharedImpl_, shared_impl_copier_type::Load (rhs.fSharedImpl_)); } return *this; } template <typename TRAITS> inline SharedByValue<TRAITS>& SharedByValue<TRAITS>::operator= (SharedByValue<TRAITS>&& rhs) { // If the pointers are the same, there is no need to copy, as the reference counts must also be the same, // and we can avoid the (common) and costly memory barrier if (fSharedImpl_.get () != rhs.fSharedImpl_.get ()) { fCopier_ = rhs.fCopier_; // ASSUME if doing a move() then this doesn't need to be a multithread safe copy (from the source), since // if its a temporary, you cannot have mulitple peopel referring to me shared_impl_copier_type::Store (&fSharedImpl_, rhs.fSharedImpl_); } return *this; } template <typename TRAITS> inline SharedByValue<TRAITS>& SharedByValue<TRAITS>::operator= (const shared_ptr_type& from) { // If the pointers are the same, there is no need to copy, as the reference counts must also be the same, // and we can avoid the (common) and costly memory barrier if (fSharedImpl_.get () != from.get ()) { shared_impl_copier_type::Store (&fSharedImpl_, shared_impl_copier_type::Load (from)); } return *this; } template <typename TRAITS> inline SharedByValue<TRAITS>& SharedByValue<TRAITS>::operator= (shared_ptr_type&& from) { // If the pointers are the same, there is no need to copy, as the reference counts must also be the same, // and we can avoid the (common) and costly memory barrier if (fSharedImpl_.get () != from.get ()) { // ASSUME if doing a move() then this doesn't need to be a multithread safe copy (from the source), since // if its a temporary, you cannot have mulitple peopel referring to me shared_impl_copier_type::Store (&fSharedImpl_, from); } return *this; } template <typename TRAITS> inline const typename SharedByValue<TRAITS>::element_type* SharedByValue<TRAITS>::get () const noexcept { return fSharedImpl_.get (); } template <typename TRAITS> template <typename... COPY_ARGS> inline typename SharedByValue<TRAITS>::element_type* SharedByValue<TRAITS>::get (COPY_ARGS&&... copyArgs) { element_type* ptr = fSharedImpl_.get (); /* * For non-const pointing, we must clone ourselves (if there are * extra referneces). If we are a nullptr pointer, nobody could actually * rereference it anyhow, so don't bother with the Assure1Reference() * in that case. */ if (ptr != nullptr) { Assure1Reference (forward<COPY_ARGS> (copyArgs)...); ptr = fSharedImpl_.get (); EnsureNotNull (ptr); } return ptr; } template <typename TRAITS> inline const typename SharedByValue<TRAITS>::element_type* SharedByValue<TRAITS>::cget () const noexcept { return get (); } template <typename TRAITS> inline const typename SharedByValue<TRAITS>::element_type* SharedByValue<TRAITS>::operator-> () const { return fSharedImpl_.get (); } template <typename TRAITS> inline typename SharedByValue<TRAITS>::element_type* SharedByValue<TRAITS>::operator-> () { return get (); } template <typename TRAITS> inline const typename SharedByValue<TRAITS>::element_type& SharedByValue<TRAITS>::operator* () const { const element_type* ptr = get (); EnsureNotNull (ptr); return *ptr; } template <typename TRAITS> inline typename SharedByValue<TRAITS>::element_type& SharedByValue<TRAITS>::operator* () { /* * For non-const dereferencing, we must clone ourselves (if there are * extra referneces). */ Assure1Reference (); element_type* ptr = get (); EnsureNotNull (ptr); return *ptr; } template <typename TRAITS> inline bool SharedByValue<TRAITS>::operator== (const SharedByValue<TRAITS>& rhs) const { return fSharedImpl_ == rhs.fSharedImpl_; } template <typename TRAITS> inline bool SharedByValue<TRAITS>::operator!= (const SharedByValue<TRAITS>& rhs) const { return fSharedImpl_ != rhs.fSharedImpl_; } template <typename TRAITS> inline typename SharedByValue<TRAITS>::element_copier_type SharedByValue<TRAITS>::GetCopier () const { return fCopier_; } template <typename TRAITS> inline SharedByValue_State SharedByValue<TRAITS>::GetSharingState () const { switch (fSharedImpl_.use_count ()) { case 0: Assert (fSharedImpl_.get () == nullptr); return SharedByValue_State::eNull; case 1: Assert (fSharedImpl_.get () != nullptr); return SharedByValue_State::eSolo; default: Assert (fSharedImpl_.get () != nullptr); //NOT NECESSARILY - cuz there is no lock // between the use_count and this unique call, so another object could decrement its count // and this could be that it was shared, but is no solo. // Assert (not fSharedImpl_.unique ()); // -- LGP 2015-01-10 return SharedByValue_State::eShared; } } template <typename TRAITS> inline bool SharedByValue<TRAITS>::unique () const { return fSharedImpl_.use_count () == 1; } template <typename TRAITS> inline unsigned int SharedByValue<TRAITS>::use_count () const { return fSharedImpl_.use_count (); } template <typename TRAITS> template <typename... COPY_ARGS> inline void SharedByValue<TRAITS>::Assure1Reference (COPY_ARGS&&... copyArgs) { if (fSharedImpl_.use_count () > 1) { BreakReferences_ (forward<COPY_ARGS> (copyArgs)...); } } template <typename TRAITS> template <typename... COPY_ARGS> void SharedByValue<TRAITS>::BreakReferences_ (COPY_ARGS&&... copyArgs) { shared_ptr_type ptr2Clone{shared_impl_copier_type::Load (fSharedImpl_)}; // other thread could change this (if other thread accesses same envelope) // but this copy prevents the bare ptr from possibly becoming invalidated element_type* ptr = ptr2Clone.get (); RequireNotNull (ptr); /* * For a valid pointer that is reference counted and multiply shared, * make a copy of that pointer via our fCloner function, and assign * that cloned reference to this. * * Note that by doing so, we remove any references to the current * item, and end up with our having the sole reference to the new copy of fPtr. * * Since we will be cloning the given pointer, we assume(assert) that * it is non-nullptr. */ //Require (!SHARED_IMLP::unique ()); This is not NECESSARILY so. Another thread could have just released this pointer, in which case // the creation of a new object was pointless, but harmless, as the assignemnt should decrement to zero the old // value and it should go away. *this = SharedByValue<TRAITS> (fCopier_.Copy (*ptr, forward<COPY_ARGS> (copyArgs)...), fCopier_); #if qDebug //Ensure (fSharedImpl_.unique ()); // technically not 100% guarantied if two threads did this at the same time, but so rare interesting if ever triggered. // may need to lose this assert - maybe replace with #if qDebug DbgTrace if (not unique ()) { DbgTrace ("probably a bug, but not necessarily..."); } #endif } } } } #endif /*_Stroika_Foundation_Memory_SharedByValue_inl_*/ <|endoftext|>
<commit_before>#include <chrono> #include <string> #include "depthai/depthai.hpp" int main(int argc, char** argv) { using namespace std::chrono; dai::DeviceBootloader::Type blType = dai::DeviceBootloader::Type::AUTO; if(argc > 1) { std::string blTypeStr(argv[1]); if(blTypeStr == "usb") { blType = dai::DeviceBootloader::Type::USB; } else if(blTypeStr == "network") { blType = dai::DeviceBootloader::Type::NETWORK; } else { std::cout << "Specify either 'usb' or 'network' bootloader type\n"; return 0; } } std::cout << "Warning! Flashing bootloader can potentially soft brick your device and should be done with caution." << std::endl; std::cout << "Do not unplug your device while the bootloader is flashing." << std::endl; std::cout << "Type 'y' and press enter to proceed, otherwise exits: "; if(std::cin.get() != 'y') { std::cout << "Prompt declined, exiting..." << std::endl; return -1; } bool found = false; dai::DeviceInfo info; std::tie(found, info) = dai::DeviceBootloader::getFirstAvailableDevice(); if(!found) { std::cout << "No device found to flash. Exiting." << std::endl; return -1; } // Open DeviceBootloader and allow flashing bootloader std::cout << "Booting latest bootloader first, will take a tad longer..." << std::endl; dai::DeviceBootloader bl(info, true); auto currentBlType = bl.getType(); // Check if bootloader type is the same if(blType != dai::DeviceBootloader::Type::AUTO && currentBlType != blType) { std::cout << "Are you sure you want to flash '" << blType << "' bootloader over current '" << currentBlType << "' bootloader?" << std::endl; std::cout << "Type 'y' and press enter to proceed, otherwise exits: "; std::cin.ignore(); if(std::cin.get() != 'y') { std::cout << "Prompt declined, exiting..." << std::endl; return -1; } } // Create a progress callback lambda auto progress = [](float p) { std::cout << "Flashing Progress..." << p * 100 << "%" << std::endl; }; std::cout << "Flashing " << currentBlType << " bootloader..." << std::endl; auto t1 = steady_clock::now(); bool success = false; std::string message; std::tie(success, message) = bl.flashBootloader(dai::DeviceBootloader::Memory::FLASH, currentBlType, progress); if(success) { std::cout << "Flashing successful. Took " << duration_cast<milliseconds>(steady_clock::now() - t1).count() << "ms" << std::endl; } else { std::cout << "Flashing failed: " << message << std::endl; } return 0; }<commit_msg>flash_bootloader: fix flashing NETWORK bootloader (when booted over USB), or flashing a different bootloader type<commit_after>#include <chrono> #include <string> #include "depthai/depthai.hpp" int main(int argc, char** argv) { using namespace std::chrono; dai::DeviceBootloader::Type blType = dai::DeviceBootloader::Type::AUTO; if(argc > 1) { std::string blTypeStr(argv[1]); if(blTypeStr == "usb") { blType = dai::DeviceBootloader::Type::USB; } else if(blTypeStr == "network") { blType = dai::DeviceBootloader::Type::NETWORK; } else { std::cout << "Specify either 'usb' or 'network' bootloader type\n"; return 0; } } std::cout << "Warning! Flashing bootloader can potentially soft brick your device and should be done with caution." << std::endl; std::cout << "Do not unplug your device while the bootloader is flashing." << std::endl; std::cout << "Type 'y' and press enter to proceed, otherwise exits: "; if(std::cin.get() != 'y') { std::cout << "Prompt declined, exiting..." << std::endl; return -1; } bool found = false; dai::DeviceInfo info; std::tie(found, info) = dai::DeviceBootloader::getFirstAvailableDevice(); if(!found) { std::cout << "No device found to flash. Exiting." << std::endl; return -1; } // Open DeviceBootloader and allow flashing bootloader std::cout << "Booting latest bootloader first, will take a tad longer..." << std::endl; dai::DeviceBootloader bl(info, true); auto currentBlType = bl.getType(); if(blType == dai::DeviceBootloader::Type::AUTO) { blType = currentBlType; } // Check if bootloader type is the same if(currentBlType != blType) { std::cout << "Are you sure you want to flash '" << blType << "' bootloader over current '" << currentBlType << "' bootloader?" << std::endl; std::cout << "Type 'y' and press enter to proceed, otherwise exits: "; std::cin.ignore(); if(std::cin.get() != 'y') { std::cout << "Prompt declined, exiting..." << std::endl; return -1; } } // Create a progress callback lambda auto progress = [](float p) { std::cout << "Flashing Progress..." << p * 100 << "%" << std::endl; }; std::cout << "Flashing " << blType << " bootloader..." << std::endl; auto t1 = steady_clock::now(); bool success = false; std::string message; std::tie(success, message) = bl.flashBootloader(dai::DeviceBootloader::Memory::FLASH, blType, progress); if(success) { std::cout << "Flashing successful. Took " << duration_cast<milliseconds>(steady_clock::now() - t1).count() << "ms" << std::endl; } else { std::cout << "Flashing failed: " << message << std::endl; } return 0; }<|endoftext|>
<commit_before>/* Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <string> #include "kernel/error_msgs.h" namespace lean { format pp_indent_expr(formatter const & fmt, expr const & e) { return nest(get_pp_indent(fmt.get_options()), compose(line(), fmt(e))); } format pp_type_expected(formatter const & fmt, expr const & e) { return compose(format("type expected at"), pp_indent_expr(fmt, e)); } format pp_function_expected(formatter const & fmt, expr const & e) { return compose(format("function expected at"), pp_indent_expr(fmt, e)); } MK_THREAD_LOCAL_GET_DEF(list<options>, get_distinguishing_pp_options) list<options> set_distinguishing_pp_options(list<options> const & opts) { list<options> r = get_distinguishing_pp_options(); get_distinguishing_pp_options() = opts; return r; } static std::tuple<format, format> pp_until_different(formatter const & fmt, expr const & e1, expr const & e2, list<options> extra) { formatter fmt1 = fmt; while (true) { format r1 = pp_indent_expr(fmt1, e1); format r2 = pp_indent_expr(fmt1, e2); if (!format_pp_eq(r1, r2, fmt1.get_options())) return mk_pair(r1, r2); if (!extra) return mk_pair(pp_indent_expr(fmt, e1), pp_indent_expr(fmt, e2)); options o = join(head(extra), fmt.get_options()); fmt1 = fmt.update_options(o); extra = tail(extra); } } std::tuple<format, format> pp_until_different(formatter const & fmt, expr const & e1, expr const & e2) { return pp_until_different(fmt, e1, e2, get_distinguishing_pp_options()); } format pp_app_type_mismatch(formatter const & fmt, expr const & app, expr const & arg, expr const & expected_type, expr const & given_type) { format r; format expected_fmt, given_fmt; std::tie(expected_fmt, given_fmt) = pp_until_different(fmt, expected_type, given_type); r += format("type mismatch at application"); r += pp_indent_expr(fmt, app); r += compose(line(), format("term")); r += pp_indent_expr(fmt, arg); r += compose(line(), format("has type")); r += given_fmt; r += compose(line(), format("but is expected to have type")); r += expected_fmt; return r; } format pp_def_type_mismatch(formatter const & fmt, name const & n, expr const & expected_type, expr const & given_type) { format expected_fmt, given_fmt; std::tie(expected_fmt, given_fmt) = pp_until_different(fmt, expected_type, given_type); format r("type mismatch at definition '"); r += format(n); r += format("', has type"); r += given_fmt; r += compose(line(), format("but is expected to have type")); r += expected_fmt; return r; } static format pp_until_meta_visible(formatter const & fmt, expr const & e, list<options> extra) { formatter fmt1 = fmt; while (true) { format r = pp_indent_expr(fmt1, e); std::ostringstream out; out << mk_pair(r, fmt1.get_options()); if (out.str().find("?M") != std::string::npos) return r; if (!extra) return pp_indent_expr(fmt, e); options o = join(head(extra), fmt.get_options()); fmt1 = fmt.update_options(o); extra = tail(extra); } } format pp_until_meta_visible(formatter const & fmt, expr const & e) { return pp_until_meta_visible(fmt, e, get_distinguishing_pp_options()); } format pp_decl_has_metavars(formatter const & fmt, name const & n, expr const & e, bool is_type) { format r("failed to add declaration '"); r += format(n); r += format("' to environment, "); if (is_type) r += format("type"); else r += format("value"); r += format(" has metavariables"); r += pp_until_meta_visible(fmt, e); return r; } } <commit_msg>fix(kernel/error_msgs): ignore binder information when comparing type mismatches, fixes #304<commit_after>/* Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <string> #include "kernel/replace_fn.h" #include "kernel/error_msgs.h" namespace lean { format pp_indent_expr(formatter const & fmt, expr const & e) { return nest(get_pp_indent(fmt.get_options()), compose(line(), fmt(e))); } format pp_type_expected(formatter const & fmt, expr const & e) { return compose(format("type expected at"), pp_indent_expr(fmt, e)); } format pp_function_expected(formatter const & fmt, expr const & e) { return compose(format("function expected at"), pp_indent_expr(fmt, e)); } MK_THREAD_LOCAL_GET_DEF(list<options>, get_distinguishing_pp_options) list<options> set_distinguishing_pp_options(list<options> const & opts) { list<options> r = get_distinguishing_pp_options(); get_distinguishing_pp_options() = opts; return r; } static expr erase_binder_info(expr const & e) { return replace(e, [](expr const & e) { if (is_binding(e) && binding_info(e) != binder_info()) { return some_expr(update_binding(e, erase_binder_info(binding_domain(e)), erase_binder_info(binding_body(e)), binder_info())); } else { return none_expr(); } }); } static std::tuple<format, format> pp_until_different(formatter const & fmt, expr const & e1, expr const & e2, list<options> extra) { formatter fmt1 = fmt; expr n_e1 = erase_binder_info(e1); expr n_e2 = erase_binder_info(e2); while (true) { format r1 = pp_indent_expr(fmt1, n_e1); format r2 = pp_indent_expr(fmt1, n_e2); if (!format_pp_eq(r1, r2, fmt1.get_options())) return mk_pair(pp_indent_expr(fmt1, e1), pp_indent_expr(fmt1, e2)); if (!extra) return mk_pair(pp_indent_expr(fmt, e1), pp_indent_expr(fmt, e2)); options o = join(head(extra), fmt.get_options()); fmt1 = fmt.update_options(o); extra = tail(extra); } } std::tuple<format, format> pp_until_different(formatter const & fmt, expr const & e1, expr const & e2) { return pp_until_different(fmt, e1, e2, get_distinguishing_pp_options()); } format pp_app_type_mismatch(formatter const & fmt, expr const & app, expr const & arg, expr const & expected_type, expr const & given_type) { format r; format expected_fmt, given_fmt; std::tie(expected_fmt, given_fmt) = pp_until_different(fmt, expected_type, given_type); r += format("type mismatch at application"); r += pp_indent_expr(fmt, app); r += compose(line(), format("term")); r += pp_indent_expr(fmt, arg); r += compose(line(), format("has type")); r += given_fmt; r += compose(line(), format("but is expected to have type")); r += expected_fmt; return r; } format pp_def_type_mismatch(formatter const & fmt, name const & n, expr const & expected_type, expr const & given_type) { format expected_fmt, given_fmt; std::tie(expected_fmt, given_fmt) = pp_until_different(fmt, expected_type, given_type); format r("type mismatch at definition '"); r += format(n); r += format("', has type"); r += given_fmt; r += compose(line(), format("but is expected to have type")); r += expected_fmt; return r; } static format pp_until_meta_visible(formatter const & fmt, expr const & e, list<options> extra) { formatter fmt1 = fmt; while (true) { format r = pp_indent_expr(fmt1, e); std::ostringstream out; out << mk_pair(r, fmt1.get_options()); if (out.str().find("?M") != std::string::npos) return r; if (!extra) return pp_indent_expr(fmt, e); options o = join(head(extra), fmt.get_options()); fmt1 = fmt.update_options(o); extra = tail(extra); } } format pp_until_meta_visible(formatter const & fmt, expr const & e) { return pp_until_meta_visible(fmt, e, get_distinguishing_pp_options()); } format pp_decl_has_metavars(formatter const & fmt, name const & n, expr const & e, bool is_type) { format r("failed to add declaration '"); r += format(n); r += format("' to environment, "); if (is_type) r += format("type"); else r += format("value"); r += format(" has metavariables"); r += pp_until_meta_visible(fmt, e); return r; } } <|endoftext|>
<commit_before>// KalmanFilter.cpp : Uses all available information to make optimal estimation. // C++ implementation of Python code. // From Udacity CS 373 Artificial Intelliegence for Robots. // Taught by Sebastian Thrun. // C++ version by Tyler Folsom; March 6, 2012. // //#include "stdafx.h" // required for MSVC. Remove for Arduino. #include "Matrix.h" /* Kalman filter Matrix x state: longs for position_mm_east, position_mm_north, velocity_mm_s_east, velocity_mm_s_north */ void Filter(REAL* State, // e.g x, y position, x, y velocity REAL* uncertainty, // P uncertainty covariance REAL* measurements, // Z: measured x and y position in mm REAL deltaT_s, // time from previous state to measurement in seconds REAL* variance) // variance of the measurements { REAL state_transition[] = {1., 0, deltaT_s, 0, 0, 1., 0, deltaT_s, 0, 0, 1, 0, 0, 0, 0, 1}; // position' = 1*position + 1*velocity // velocity' = 1*velocity REAL observable[] = {1., 0, 0, 0, 0, 1., 0, 0}; // only position is measurable; not velocity matrix x = matrix(4,1,State); // initial state (location and velocity) matrix P = matrix(4,4, uncertainty); // 4x4 initial uncertainty matrix meas = matrix(2,1,measurements); matrix u = matrix( 4, 1); // 4x1 external motion; set to 0. // u comes from what the vehicle is trying to do, e.g. accelerate. matrix F = matrix(4,4, state_transition); // next state function matrix H = matrix(2,4, observable); // measurement function matrix R = matrix(2,2, variance); // measurement variance matrix I = matrix(4); // 4x4 identity matrix // prediction matrix Fx = F * x; matrix xNew = Fx + u; x = xNew; // x = F*x + u matrix Ftrans = F.transpose(); matrix PFt = P * Ftrans; matrix P2 = F * PFt; P = P2; // P = F * P * F.transpose(); Show("x= "); x.show(); Show("dt = "); Show(deltaT_s); Show("P= "); P.show(); // measurement update // Arduino compiler gets confused on combining multiple matrix operations. matrix Hx = H * x; matrix y = meas - Hx; // y = Z- H * x matrix transp = H.transpose(); matrix PHt = P * transp; matrix HPH = H * PHt; matrix S = HPH + R; // S = H * P * H.transpose() + R; matrix Sinv = S.inverse(); matrix K = PHt * Sinv;// K = P * H.transpose()*S.inverse(); matrix Ky = K * y; matrix x_Ky = x + Ky; x = x_Ky; matrix KH = K*H; matrix IKH = I-(KH); matrix Pnew = IKH * P; // (I-(K*H)) * P; P = Pnew; Show("R= "); R.show(); Show("K= "); K.show(); Show("x= "); x.show(); Show("P= "); P.show(); // Put x into State and P into Uncertainty. x.values(State); P.values(uncertainty); return; } <commit_msg>More flexible dimensions on matrices.<commit_after>// KalmanFilter.cpp : Uses all available information to make optimal estimation. // C++ implementation of Python code. // From Udacity CS 373 Artificial Intelliegence for Robots. // Taught by Sebastian Thrun. // C++ version by Tyler Folsom; March 6, 2012. // //#include "stdafx.h" // required for MSVC. Remove for Arduino. #include "Matrix.h" /* Kalman filter Matrix x state: longs for position_mm_east, position_mm_north, velocity_mm_s_east, velocity_mm_s_north */ #define NSTATES 4 #define NSEEN 2 void Filter(REAL* State, // e.g x, y position, x, y velocity REAL* uncertainty, // P uncertainty covariance REAL* measurements, // Z: measured x and y position in mm REAL deltaT_s, // time from previous state to measurement in seconds REAL* variance) // variance of the measurements { REAL state_transition[NSTATES*NSTATES] = {1., 0, deltaT_s, 0, 0, 1., 0, deltaT_s, 0, 0, 1, 0, 0, 0, 0, 1}; REAL state_transition[] = {1., 0, deltaT_s, 0, 0, 1., 0, deltaT_s, 0, 0, 1, 0, 0, 0, 0, 1}; // position' = 1*position + 1*velocity // velocity' = 1*velocity REAL observable[NSEEN*NSTATES]; // = {1., 0, 0, 0, // 0, 1., 0, 0}; // only position is measurable; not velocity matrix x = matrix(NSTATES,1,State); // initial state (location and velocity) matrix P = matrix(NSTATES,NSTATES, uncertainty); // 4x4 initial uncertainty matrix meas = matrix(NSEEN,1,measurements); matrix u = matrix( NSTATES, 1); // 4x1 external motion; set to 0. // u comes from what the vehicle is trying to do, e.g. accelerate. matrix F = matrix(NSTATES,NSTATES, state_transition); // next state function for (int i = 0; i < NSEEN*NSTATES; i++) { observable[i] = i%(NSTATES+1) ? 0 : 1; } matrix H = matrix(NSEEN,NSTATES, observable); // measurement function H.show(); matrix R = matrix(NSEEN,NSEEN, variance); // measurement variance matrix I = matrix(NSTATES); // 4x4 identity matrix // prediction matrix Fx = F * x; matrix xNew = Fx + u; x = xNew; // x = F*x + u matrix Ftrans = F.transpose(); matrix PFt = P * Ftrans; matrix P2 = F * PFt; P = P2; // P = F * P * F.transpose(); Show("x= "); x.show(); Show("dt = "); Show(deltaT_s); Show("P= "); P.show(); // measurement update // Arduino compiler gets confused on combining multiple matrix operations. matrix Hx = H * x; matrix y = meas - Hx; // y = Z- H * x matrix transp = H.transpose(); matrix PHt = P * transp; matrix HPH = H * PHt; matrix S = HPH + R; // S = H * P * H.transpose() + R; matrix Sinv = S.inverse(); matrix K = PHt * Sinv;// K = P * H.transpose()*S.inverse(); matrix Ky = K * y; matrix x_Ky = x + Ky; x = x_Ky; matrix KH = K*H; matrix IKH = I-(KH); matrix Pnew = IKH * P; // (I-(K*H)) * P; P = Pnew; Show("R= "); R.show(); Show("K= "); K.show(); Show("x= "); x.show(); Show("P= "); P.show(); // Put x into State and P into Uncertainty. x.values(State); P.values(uncertainty); return; } <|endoftext|>
<commit_before>/*========================================================================= Program: Bender Copyright (c) Kitware Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt 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. =========================================================================*/ // Bender includes #include "CreateTetrahedralMeshCLP.h" #include "benderIOUtils.h" // ITK includes #include "itkBinaryThresholdImageFilter.h" #include "itkCastImageFilter.h" #include "itkImageFileWriter.h" #include "itkImageRegionConstIterator.h" #include "itkImageRegionIterator.h" #include "itkRelabelComponentImageFilter.h" #include "itkConstantPadImageFilter.h" // Slicer includes #include "itkPluginUtilities.h" // VTK includes #include <vtkCleanPolyData.h> #include <vtkCellArray.h> #include <vtkCellData.h> #include <vtkTetra.h> #include <vtkTransform.h> #include <vtkTransformPolyDataFilter.h> #include <vtkPolyData.h> #include <vtkPolyDataWriter.h> #include <vtkMath.h> #include <vtkNew.h> #include <vtkSmartPointer.h> // Cleaver includes #include <Cleaver/Cleaver.h> #include <Cleaver/InverseField.h> #include <Cleaver/PaddedVolume.h> #include <Cleaver/ScalarField.h> #include <Cleaver/Volume.h> #include <LabelMapField.h> // Use an anonymous namespace to keep class types and function names // from colliding when module is used as shared object module. Every // thing should be in an anonymous namespace except for the module // entry point, e.g. main() // namespace { template <class T> int DoIt( int argc, char * argv[] ); std::vector<Cleaver::LabelMapField::ImageType::Pointer> SplitLabelMaps( int argc, char * argv[]); } // end of anonymous namespace int main( int argc, char * argv[] ) { PARSE_ARGS; itk::ImageIOBase::IOPixelType pixelType; itk::ImageIOBase::IOComponentType componentType; try { itk::GetImageType(InputVolume, pixelType, componentType); switch( componentType ) { case itk::ImageIOBase::UCHAR: return DoIt<unsigned char>( argc, argv ); break; case itk::ImageIOBase::CHAR: return DoIt<char>( argc, argv ); break; case itk::ImageIOBase::USHORT: return DoIt<unsigned short>( argc, argv ); break; case itk::ImageIOBase::SHORT: return DoIt<short>( argc, argv ); break; case itk::ImageIOBase::UINT: return DoIt<unsigned int>( argc, argv ); break; case itk::ImageIOBase::INT: return DoIt<int>( argc, argv ); break; case itk::ImageIOBase::ULONG: return DoIt<unsigned long>( argc, argv ); break; case itk::ImageIOBase::LONG: return DoIt<long>( argc, argv ); break; case itk::ImageIOBase::FLOAT: return DoIt<float>( argc, argv ); break; case itk::ImageIOBase::DOUBLE: return DoIt<double>( argc, argv ); break; case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE: default: std::cerr << "Unknown component type: " << componentType << std::endl; break; } } catch( itk::ExceptionObject & excep ) { std::cerr << argv[0] << ": exception caught !" << std::endl; std::cerr << excep << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } // Use an anonymous namespace to keep class types and function names // from colliding when module is used as shared object module. Every // thing should be in an anonymous namespace except for the module // entry point, e.g. main() // namespace { std::vector<Cleaver::LabelMapField::ImageType::Pointer > SplitLabelMaps(Cleaver::LabelMapField::ImageType *image, bool verbose) { typedef Cleaver::LabelMapField::ImageType LabelImageType; typedef itk::RelabelComponentImageFilter<LabelImageType, LabelImageType> RelabelFilterType; typedef itk::BinaryThresholdImageFilter<LabelImageType, LabelImageType> ThresholdFilterType; typedef itk::ImageFileWriter<LabelImageType> ImageWriterType; // Assign continuous labels to the connected components, background is // considered to be 0 and will be ignored in the relabeling process. RelabelFilterType::Pointer relabelFilter = RelabelFilterType::New(); relabelFilter->SetInput( image ); relabelFilter->Update(); if (verbose) { std::cout << "Total Number of Labels: " << relabelFilter->GetNumberOfObjects() << std::endl; } // Extract the labels typedef RelabelFilterType::LabelType LabelType; ThresholdFilterType::Pointer skinThresholdFilter = ThresholdFilterType::New(); // Create a list of images corresponding to labels std::vector<LabelImageType::Pointer> labels; // The skin label will become background for internal (smaller) organs skinThresholdFilter->SetInput(relabelFilter->GetOutput()); skinThresholdFilter->SetLowerThreshold(1); skinThresholdFilter->SetUpperThreshold(relabelFilter->GetNumberOfObjects()+1); skinThresholdFilter->SetInsideValue(-1); skinThresholdFilter->SetOutsideValue(0); skinThresholdFilter->Update(); labels.push_back(skinThresholdFilter->GetOutput()); for (LabelType i = 1, end = relabelFilter->GetNumberOfObjects()+1; i < end; ++i) { ThresholdFilterType::Pointer organThresholdFilter = ThresholdFilterType::New(); organThresholdFilter->SetInput(relabelFilter->GetOutput()); organThresholdFilter->SetLowerThreshold(i); organThresholdFilter->SetUpperThreshold(i); organThresholdFilter->SetInsideValue(i); organThresholdFilter->SetOutsideValue(-1); organThresholdFilter->Update(); labels.push_back(organThresholdFilter->GetOutput()); } return labels; } template <class T> int DoIt( int argc, char * argv[] ) { PARSE_ARGS; typedef Cleaver::LabelMapField::ImageType LabelImageType; typedef T InputPixelType; typedef itk::Image<InputPixelType,3> InputImageType; typedef itk::CastImageFilter<InputImageType, LabelImageType> CastFilterType; typedef itk::ImageFileReader<InputImageType> ReaderType; typedef itk::ConstantPadImageFilter<InputImageType, InputImageType> ConstantPadType; typename CastFilterType::Pointer castingFilter = CastFilterType::New(); typename ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( InputVolume ); reader->Update(); castingFilter->SetInput(reader->GetOutput()); std::vector<Cleaver::ScalarField*> labelMaps; std::vector<LabelImageType::Pointer> labels = SplitLabelMaps(castingFilter->GetOutput(), verbose); // Get a map from the original labels to the new labels std::map<InputPixelType, InputPixelType> originalLabels; for(size_t i = 0; i < labels.size(); ++i) { itk::ImageRegionConstIterator<InputImageType> imageIterator( reader->GetOutput(), reader->GetOutput()->GetLargestPossibleRegion()); itk::ImageRegionConstIterator<LabelImageType> labelsIterator( labels[i], labels[i]->GetLargestPossibleRegion()); bool foundCorrespondence = false; while(!imageIterator.IsAtEnd() && !labelsIterator.IsAtEnd() && !foundCorrespondence) { if (labelsIterator.Value() > 0) { originalLabels[labelsIterator.Value()] = imageIterator.Value(); } ++imageIterator; ++labelsIterator; } } if (verbose) { std::cout << "Total labels found: " << labels.size() << std::endl; } for(size_t i = 0; i < labels.size(); ++i) { labelMaps.push_back(new Cleaver::LabelMapField(labels[i])); static_cast<Cleaver::LabelMapField*>(labelMaps.back())-> SetGenerateDataFromLabels(true); } if(labelMaps.empty()) { std::cerr << "Failed to load image data. Terminating." << std::endl; return 0; } if(labelMaps.size() < 2) { labelMaps.push_back(new Cleaver::InverseField(labelMaps[0])); } Cleaver::AbstractVolume *volume = new Cleaver::Volume(labelMaps); volume = new Cleaver::PaddedVolume(volume); if (verbose) { std::cout << "Creating Mesh with Volume Size " << volume->size().toString() << std::endl; } //-------------------------------- // Create Mesher & TetMesh //-------------------------------- Cleaver::TetMesh *cleaverMesh = Cleaver::createMeshFromVolume(volume, verbose); if (!cleaverMesh) { // Clean up delete volume; delete cleaverMesh; std::cerr << "Mesh computation failed !" << std::endl; return EXIT_FAILURE; } //------------------ // Compute Angles //------------------ if(verbose) { cleaverMesh->computeAngles(); std::cout.precision(12); std::cout << "Worst Angles:" << std::endl; std::cout << "min: " << cleaverMesh->min_angle << std::endl; std::cout << "max: " << cleaverMesh->max_angle << std::endl; } const int airLabel = 0; int paddedVolumeLabel = labels.size(); vtkNew<vtkCellArray> meshTetras; vtkNew<vtkIntArray> cellData; for(size_t i = 0, end = cleaverMesh->tets.size(); i < end; ++i) { int label = cleaverMesh->tets[i]->mat_label; if(label == airLabel || label == paddedVolumeLabel) { continue; } vtkNew<vtkTetra> meshTetra; meshTetra->GetPointIds()->SetId(0, cleaverMesh->tets[i]->verts[0]->tm_v_index); meshTetra->GetPointIds()->SetId(1, cleaverMesh->tets[i]->verts[1]->tm_v_index); meshTetra->GetPointIds()->SetId(2, cleaverMesh->tets[i]->verts[2]->tm_v_index); meshTetra->GetPointIds()->SetId(3, cleaverMesh->tets[i]->verts[3]->tm_v_index); meshTetras->InsertNextCell(meshTetra.GetPointer()); cellData->InsertNextValue(originalLabels[label]); } vtkNew<vtkPoints> points; points->SetNumberOfPoints(cleaverMesh->verts.size()); for (size_t i = 0, end = cleaverMesh->verts.size(); i < end; ++i) { Cleaver::vec3 &pos = cleaverMesh->verts[i]->pos(); points->SetPoint(i, pos.x, pos.y, pos.z); } vtkSmartPointer<vtkPolyData> vtkMesh = vtkSmartPointer<vtkPolyData>::New(); vtkMesh->SetPoints(points.GetPointer()); vtkMesh->SetPolys(meshTetras.GetPointer()); vtkMesh->GetCellData()->SetScalars(cellData.GetPointer()); vtkNew<vtkCleanPolyData> cleanFilter; cleanFilter->SetInput(vtkMesh); // Since cleaver does not take into account the image properties such as // sapcing or origin, we need to transform the output points so the mesh can // match the original image. vtkNew<vtkTransform> transform; LabelImageType::SpacingType spacing = reader->GetOutput()->GetSpacing(); LabelImageType::PointType origin = reader->GetOutput()->GetOrigin(); LabelImageType::DirectionType imageDirection = reader->GetOutput()->GetDirection(); // Transform points to RAS (what is concatenated first is done last !) vtkNew<vtkMatrix4x4> rasMatrix; rasMatrix->Identity(); rasMatrix->SetElement(0, 0, -1.0); rasMatrix->SetElement(1, 1, -1.0); transform->Concatenate(rasMatrix.GetPointer()); // Translation double voxelSize[3]; voxelSize[0] = spacing[0]; voxelSize[1] = spacing[1]; voxelSize[2] = spacing[2]; double voxelDiagonale = vtkMath::Norm(voxelSize) / 2; vtkNew<vtkMatrix4x4> directionMatrix; directionMatrix->Identity(); for (int i = 0; i < imageDirection.RowDimensions; ++i) { for (int j = 0; j < imageDirection.ColumnDimensions; ++j) { directionMatrix->SetElement(i, j, imageDirection[i][j]); } } vtkNew<vtkTransform> offsetTransform; offsetTransform->Concatenate(directionMatrix.GetPointer()); double offset = (Cleaver::PaddedVolume::DefaultThickness + 1) * voxelDiagonale; double* offsets = offsetTransform->TransformDoubleVector(offset, offset, offset); transform->Translate( origin[0] - offsets[0], origin[1] - offsets[1], origin[2] - offsets[2]); // Scaling and rotation vtkNew<vtkMatrix4x4> scaleMatrix; scaleMatrix->DeepCopy(directionMatrix.GetPointer()); for (int i = 0; i < spacing.GetNumberOfComponents(); ++i) { scaleMatrix->SetElement(i, i, scaleMatrix->GetElement(i, i) * spacing[i]); } transform->Concatenate(scaleMatrix.GetPointer()); // Actual transformation vtkNew<vtkTransformPolyDataFilter> transformFilter; transformFilter->SetInput(cleanFilter->GetOutput()); transformFilter->SetTransform(transform.GetPointer()); bender::IOUtils::WritePolyData(transformFilter->GetOutput(), OutputMesh); // Clean up delete volume; delete cleaverMesh; return EXIT_SUCCESS; } } // end of anonymous namespace <commit_msg>Prevent point merging in clean filter<commit_after>/*========================================================================= Program: Bender Copyright (c) Kitware Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt 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. =========================================================================*/ // Bender includes #include "CreateTetrahedralMeshCLP.h" #include "benderIOUtils.h" // ITK includes #include "itkBinaryThresholdImageFilter.h" #include "itkCastImageFilter.h" #include "itkImageFileWriter.h" #include "itkImageRegionConstIterator.h" #include "itkImageRegionIterator.h" #include "itkRelabelComponentImageFilter.h" #include "itkConstantPadImageFilter.h" // Slicer includes #include "itkPluginUtilities.h" // VTK includes #include <vtkCleanPolyData.h> #include <vtkCellArray.h> #include <vtkCellData.h> #include <vtkTetra.h> #include <vtkTransform.h> #include <vtkTransformPolyDataFilter.h> #include <vtkPolyData.h> #include <vtkPolyDataWriter.h> #include <vtkMath.h> #include <vtkNew.h> #include <vtkSmartPointer.h> // Cleaver includes #include <Cleaver/Cleaver.h> #include <Cleaver/InverseField.h> #include <Cleaver/PaddedVolume.h> #include <Cleaver/ScalarField.h> #include <Cleaver/Volume.h> #include <LabelMapField.h> // Use an anonymous namespace to keep class types and function names // from colliding when module is used as shared object module. Every // thing should be in an anonymous namespace except for the module // entry point, e.g. main() // namespace { template <class T> int DoIt( int argc, char * argv[] ); std::vector<Cleaver::LabelMapField::ImageType::Pointer> SplitLabelMaps( int argc, char * argv[]); } // end of anonymous namespace int main( int argc, char * argv[] ) { PARSE_ARGS; itk::ImageIOBase::IOPixelType pixelType; itk::ImageIOBase::IOComponentType componentType; try { itk::GetImageType(InputVolume, pixelType, componentType); switch( componentType ) { case itk::ImageIOBase::UCHAR: return DoIt<unsigned char>( argc, argv ); break; case itk::ImageIOBase::CHAR: return DoIt<char>( argc, argv ); break; case itk::ImageIOBase::USHORT: return DoIt<unsigned short>( argc, argv ); break; case itk::ImageIOBase::SHORT: return DoIt<short>( argc, argv ); break; case itk::ImageIOBase::UINT: return DoIt<unsigned int>( argc, argv ); break; case itk::ImageIOBase::INT: return DoIt<int>( argc, argv ); break; case itk::ImageIOBase::ULONG: return DoIt<unsigned long>( argc, argv ); break; case itk::ImageIOBase::LONG: return DoIt<long>( argc, argv ); break; case itk::ImageIOBase::FLOAT: return DoIt<float>( argc, argv ); break; case itk::ImageIOBase::DOUBLE: return DoIt<double>( argc, argv ); break; case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE: default: std::cerr << "Unknown component type: " << componentType << std::endl; break; } } catch( itk::ExceptionObject & excep ) { std::cerr << argv[0] << ": exception caught !" << std::endl; std::cerr << excep << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } // Use an anonymous namespace to keep class types and function names // from colliding when module is used as shared object module. Every // thing should be in an anonymous namespace except for the module // entry point, e.g. main() // namespace { std::vector<Cleaver::LabelMapField::ImageType::Pointer > SplitLabelMaps(Cleaver::LabelMapField::ImageType *image, bool verbose) { typedef Cleaver::LabelMapField::ImageType LabelImageType; typedef itk::RelabelComponentImageFilter<LabelImageType, LabelImageType> RelabelFilterType; typedef itk::BinaryThresholdImageFilter<LabelImageType, LabelImageType> ThresholdFilterType; typedef itk::ImageFileWriter<LabelImageType> ImageWriterType; // Assign continuous labels to the connected components, background is // considered to be 0 and will be ignored in the relabeling process. RelabelFilterType::Pointer relabelFilter = RelabelFilterType::New(); relabelFilter->SetInput( image ); relabelFilter->Update(); if (verbose) { std::cout << "Total Number of Labels: " << relabelFilter->GetNumberOfObjects() << std::endl; } // Extract the labels typedef RelabelFilterType::LabelType LabelType; ThresholdFilterType::Pointer skinThresholdFilter = ThresholdFilterType::New(); // Create a list of images corresponding to labels std::vector<LabelImageType::Pointer> labels; // The skin label will become background for internal (smaller) organs skinThresholdFilter->SetInput(relabelFilter->GetOutput()); skinThresholdFilter->SetLowerThreshold(1); skinThresholdFilter->SetUpperThreshold(relabelFilter->GetNumberOfObjects()+1); skinThresholdFilter->SetInsideValue(-1); skinThresholdFilter->SetOutsideValue(0); skinThresholdFilter->Update(); labels.push_back(skinThresholdFilter->GetOutput()); for (LabelType i = 1, end = relabelFilter->GetNumberOfObjects()+1; i < end; ++i) { ThresholdFilterType::Pointer organThresholdFilter = ThresholdFilterType::New(); organThresholdFilter->SetInput(relabelFilter->GetOutput()); organThresholdFilter->SetLowerThreshold(i); organThresholdFilter->SetUpperThreshold(i); organThresholdFilter->SetInsideValue(i); organThresholdFilter->SetOutsideValue(-1); organThresholdFilter->Update(); labels.push_back(organThresholdFilter->GetOutput()); } return labels; } template <class T> int DoIt( int argc, char * argv[] ) { PARSE_ARGS; typedef Cleaver::LabelMapField::ImageType LabelImageType; typedef T InputPixelType; typedef itk::Image<InputPixelType,3> InputImageType; typedef itk::CastImageFilter<InputImageType, LabelImageType> CastFilterType; typedef itk::ImageFileReader<InputImageType> ReaderType; typedef itk::ConstantPadImageFilter<InputImageType, InputImageType> ConstantPadType; typename CastFilterType::Pointer castingFilter = CastFilterType::New(); typename ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( InputVolume ); reader->Update(); castingFilter->SetInput(reader->GetOutput()); std::vector<Cleaver::ScalarField*> labelMaps; std::vector<LabelImageType::Pointer> labels = SplitLabelMaps(castingFilter->GetOutput(), verbose); // Get a map from the original labels to the new labels std::map<InputPixelType, InputPixelType> originalLabels; for(size_t i = 0; i < labels.size(); ++i) { itk::ImageRegionConstIterator<InputImageType> imageIterator( reader->GetOutput(), reader->GetOutput()->GetLargestPossibleRegion()); itk::ImageRegionConstIterator<LabelImageType> labelsIterator( labels[i], labels[i]->GetLargestPossibleRegion()); bool foundCorrespondence = false; while(!imageIterator.IsAtEnd() && !labelsIterator.IsAtEnd() && !foundCorrespondence) { if (labelsIterator.Value() > 0) { originalLabels[labelsIterator.Value()] = imageIterator.Value(); } ++imageIterator; ++labelsIterator; } } if (verbose) { std::cout << "Total labels found: " << labels.size() << std::endl; } for(size_t i = 0; i < labels.size(); ++i) { labelMaps.push_back(new Cleaver::LabelMapField(labels[i])); static_cast<Cleaver::LabelMapField*>(labelMaps.back())-> SetGenerateDataFromLabels(true); } if(labelMaps.empty()) { std::cerr << "Failed to load image data. Terminating." << std::endl; return 0; } if(labelMaps.size() < 2) { labelMaps.push_back(new Cleaver::InverseField(labelMaps[0])); } Cleaver::AbstractVolume *volume = new Cleaver::Volume(labelMaps); volume = new Cleaver::PaddedVolume(volume); if (verbose) { std::cout << "Creating Mesh with Volume Size " << volume->size().toString() << std::endl; } //-------------------------------- // Create Mesher & TetMesh //-------------------------------- Cleaver::TetMesh *cleaverMesh = Cleaver::createMeshFromVolume(volume, verbose); if (!cleaverMesh) { // Clean up delete volume; delete cleaverMesh; std::cerr << "Mesh computation failed !" << std::endl; return EXIT_FAILURE; } //------------------ // Compute Angles //------------------ if(verbose) { cleaverMesh->computeAngles(); std::cout.precision(12); std::cout << "Worst Angles:" << std::endl; std::cout << "min: " << cleaverMesh->min_angle << std::endl; std::cout << "max: " << cleaverMesh->max_angle << std::endl; } const int airLabel = 0; int paddedVolumeLabel = labels.size(); vtkNew<vtkCellArray> meshTetras; vtkNew<vtkIntArray> cellData; for(size_t i = 0, end = cleaverMesh->tets.size(); i < end; ++i) { int label = cleaverMesh->tets[i]->mat_label; if(label == airLabel || label == paddedVolumeLabel) { continue; } vtkNew<vtkTetra> meshTetra; meshTetra->GetPointIds()->SetId(0, cleaverMesh->tets[i]->verts[0]->tm_v_index); meshTetra->GetPointIds()->SetId(1, cleaverMesh->tets[i]->verts[1]->tm_v_index); meshTetra->GetPointIds()->SetId(2, cleaverMesh->tets[i]->verts[2]->tm_v_index); meshTetra->GetPointIds()->SetId(3, cleaverMesh->tets[i]->verts[3]->tm_v_index); meshTetras->InsertNextCell(meshTetra.GetPointer()); cellData->InsertNextValue(originalLabels[label]); } vtkNew<vtkPoints> points; points->SetNumberOfPoints(cleaverMesh->verts.size()); for (size_t i = 0, end = cleaverMesh->verts.size(); i < end; ++i) { Cleaver::vec3 &pos = cleaverMesh->verts[i]->pos(); points->SetPoint(i, pos.x, pos.y, pos.z); } vtkSmartPointer<vtkPolyData> vtkMesh = vtkSmartPointer<vtkPolyData>::New(); vtkMesh->SetPoints(points.GetPointer()); vtkMesh->SetPolys(meshTetras.GetPointer()); vtkMesh->GetCellData()->SetScalars(cellData.GetPointer()); vtkNew<vtkCleanPolyData> cleanFilter; cleanFilter->PointMergingOff(); // Prevent from creating triangles or lines cleanFilter->SetInput(vtkMesh); // Since cleaver does not take into account the image properties such as // sapcing or origin, we need to transform the output points so the mesh can // match the original image. vtkNew<vtkTransform> transform; LabelImageType::SpacingType spacing = reader->GetOutput()->GetSpacing(); LabelImageType::PointType origin = reader->GetOutput()->GetOrigin(); LabelImageType::DirectionType imageDirection = reader->GetOutput()->GetDirection(); // Transform points to RAS (what is concatenated first is done last !) vtkNew<vtkMatrix4x4> rasMatrix; rasMatrix->Identity(); rasMatrix->SetElement(0, 0, -1.0); rasMatrix->SetElement(1, 1, -1.0); transform->Concatenate(rasMatrix.GetPointer()); // Translation double voxelSize[3]; voxelSize[0] = spacing[0]; voxelSize[1] = spacing[1]; voxelSize[2] = spacing[2]; double voxelDiagonale = vtkMath::Norm(voxelSize) / 2; vtkNew<vtkMatrix4x4> directionMatrix; directionMatrix->Identity(); for (int i = 0; i < imageDirection.RowDimensions; ++i) { for (int j = 0; j < imageDirection.ColumnDimensions; ++j) { directionMatrix->SetElement(i, j, imageDirection[i][j]); } } vtkNew<vtkTransform> offsetTransform; offsetTransform->Concatenate(directionMatrix.GetPointer()); double offset = (Cleaver::PaddedVolume::DefaultThickness + 1) * voxelDiagonale; double* offsets = offsetTransform->TransformDoubleVector(offset, offset, offset); transform->Translate( origin[0] - offsets[0], origin[1] - offsets[1], origin[2] - offsets[2]); // Scaling and rotation vtkNew<vtkMatrix4x4> scaleMatrix; scaleMatrix->DeepCopy(directionMatrix.GetPointer()); for (int i = 0; i < spacing.GetNumberOfComponents(); ++i) { scaleMatrix->SetElement(i, i, scaleMatrix->GetElement(i, i) * spacing[i]); } transform->Concatenate(scaleMatrix.GetPointer()); // Actual transformation vtkNew<vtkTransformPolyDataFilter> transformFilter; transformFilter->SetInput(cleanFilter->GetOutput()); transformFilter->SetTransform(transform.GetPointer()); bender::IOUtils::WritePolyData(transformFilter->GetOutput(), OutputMesh); // Clean up delete volume; delete cleaverMesh; return EXIT_SUCCESS; } } // end of anonymous namespace <|endoftext|>
<commit_before>AliAnalysisTask *AddTask_rbailhac_lowmass_PbPb(Bool_t getFromAlien=kFALSE, TString cFileName = "Config_rbailhac_lowmass_PbPb.C", TString calibFileName = "", UInt_t trigger = AliVEvent::kINT7|AliVEvent::kCentral|AliVEvent::kSemiCentral, const Int_t CenMin = 0, const Int_t CenMax = 10, const Bool_t isMC = kFALSE, const Bool_t isMix = kTRUE, const Int_t Nmix = 10, const TString outputFileName="LMEE.root", Bool_t rejpileup = kTRUE ) { //get the current analysis manager AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTask_rbailhac_test", "No analysis manager found."); return 0; } //Base Directory for GRID / LEGO Train TString configBasePath= "$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/"; if(getFromAlien && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/r/rbailhac/PWGDQ/dielectron/macrosLMEE/%s .",cFileName.Data()))) ){ configBasePath=Form("%s/",gSystem->pwd()); } TString configFilePath(configBasePath+cFileName); std::cout << "Configpath: " << configFilePath << std::endl; if (!gROOT->GetListOfGlobalFunctions()->FindObject("Config_rbailhac_lowmass_PbPb")) { printf("Load macro now\n"); gROOT->LoadMacro(configFilePath.Data()); } // trigger TString triggername = "NULL"; if(trigger == (UInt_t)AliVEvent::kINT7) triggername = "kINT7"; else if(trigger == (UInt_t)AliVEvent::kCentral) triggername = "kCentral"; else if(trigger == (UInt_t)AliVEvent::kSemiCentral) triggername = "kSemiCentral"; else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kCentral | AliVEvent::kSemiCentral)) triggername = "kCombinedCentralityTriggers"; else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kCentral)) triggername = "kCombinedCentral"; else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kSemiCentral)) triggername = "kCombinedSemiCentral"; //create task and add it to the manager (MB) TString appendix; appendix += TString::Format("Cen%d_%d_%s_rejpileup%d",CenMin,CenMax,triggername.Data(),rejpileup); printf("appendix %s\n", appendix.Data()); AliAnalysisTaskMultiDielectron *task = new AliAnalysisTaskMultiDielectron(Form("MultiDielectron_%s",appendix.Data())); task->UsePhysicsSelection(); task->SetTriggerMask(trigger); // PID postcalibration THnF *hs_mean_TPC_El = 0x0; THnF *hs_width_TPC_El = 0x0; THnF *hs_mean_ITS_El = 0x0; THnF *hs_width_ITS_El = 0x0; THnF *hs_mean_TOF_El = 0x0; THnF *hs_width_TOF_El = 0x0; THnF *hs_mean_TPC_Pi = 0x0; THnF *hs_width_TPC_Pi = 0x0; THnF *hs_mean_TPC_Ka = 0x0; THnF *hs_width_TPC_Ka = 0x0; THnF *hs_mean_TPC_Pr = 0x0; THnF *hs_width_TPC_Pr = 0x0; // PID post-calibration TFile *rootfile = 0x0; if(calibFileName.Contains("pass3")){ printf("reading : %s for PID calibration\n",calibFileName.Data()); rootfile = TFile::Open(calibFileName,"READ"); hs_mean_TPC_El = (THnF*)rootfile->Get("hs_mean_TPC_El"); hs_width_TPC_El = (THnF*)rootfile->Get("hs_width_TPC_El"); hs_mean_ITS_El = (THnF*)rootfile->Get("hs_mean_ITS_El"); hs_width_ITS_El = (THnF*)rootfile->Get("hs_width_ITS_El"); hs_mean_TOF_El = (THnF*)rootfile->Get("hs_mean_TOF_El"); hs_width_TOF_El = (THnF*)rootfile->Get("hs_width_TOF_El"); hs_mean_TPC_Pi = (THnF*)rootfile->Get("hs_mean_TPC_Pi"); hs_width_TPC_Pi = (THnF*)rootfile->Get("hs_width_TPC_Pi"); hs_mean_TPC_Ka = (THnF*)rootfile->Get("hs_mean_TPC_Ka"); hs_width_TPC_Ka = (THnF*)rootfile->Get("hs_width_TPC_Ka"); hs_mean_TPC_Pr = (THnF*)rootfile->Get("hs_mean_TPC_Pr"); hs_width_TPC_Pr = (THnF*)rootfile->Get("hs_width_TPC_Pr"); } // Number of cuts const Int_t nDie = (Int_t)gROOT->ProcessLine("GetN()"); //add dielectron analysis with different cuts to the task for (Int_t i=0; i<nDie; ++i){ //nDie defined in config file AliDielectron *diel = reinterpret_cast<AliDielectron*>(gROOT->ProcessLine(Form("Config_rbailhac_lowmass_PbPb(%d,%d)",i,isMC,isMix))); if(!diel) continue; if(rootfile && rootfile->IsOpen()){ diel->SetPIDCaibinPU(kTRUE); //for electron diel->SetCentroidCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kElectron,hs_mean_TPC_El ,AliDielectronVarManager::kNSDDSSDclsEvent,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta); diel-> SetWidthCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kElectron,hs_width_TPC_El,AliDielectronVarManager::kNSDDSSDclsEvent,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta); diel->SetCentroidCorrFunctionPU(AliDielectronPID::kITS,AliPID::kElectron,hs_mean_ITS_El ,AliDielectronVarManager::kNSDDSSDclsEvent,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta); diel-> SetWidthCorrFunctionPU(AliDielectronPID::kITS,AliPID::kElectron,hs_width_ITS_El,AliDielectronVarManager::kNSDDSSDclsEvent,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta); diel->SetCentroidCorrFunctionPU(AliDielectronPID::kTOF,AliPID::kElectron,hs_mean_TOF_El ,AliDielectronVarManager::kNSDDSSDclsEvent,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta); diel-> SetWidthCorrFunctionPU(AliDielectronPID::kTOF,AliPID::kElectron,hs_width_TOF_El,AliDielectronVarManager::kNSDDSSDclsEvent,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta); //for pion diel->SetCentroidCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kPion,hs_mean_TPC_Pi ,AliDielectronVarManager::kNSDDSSDclsEvent,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta); diel-> SetWidthCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kPion,hs_width_TPC_Pi ,AliDielectronVarManager::kNSDDSSDclsEvent,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta); //for kaon diel->SetCentroidCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kKaon,hs_mean_TPC_Ka ,AliDielectronVarManager::kNSDDSSDclsEvent,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta); diel-> SetWidthCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kKaon,hs_width_TPC_Ka ,AliDielectronVarManager::kNSDDSSDclsEvent,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta); //for proton diel->SetCentroidCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kProton,hs_mean_TPC_Pr ,AliDielectronVarManager::kNSDDSSDclsEvent,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta); diel-> SetWidthCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kProton,hs_width_TPC_Pr ,AliDielectronVarManager::kNSDDSSDclsEvent,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta); } if(isMix) { printf("Add event mixing handler\n"); AliDielectronMixingHandler *mix = new AliDielectronMixingHandler; mix->SetMixType(AliDielectronMixingHandler::kAll); mix->AddVariable(AliDielectronVarManager::kZvPrim,"-10., -8., -6., -4., -2. , 0., 2., 4., 6., 8. , 10."); mix->AddVariable(AliDielectronVarManager::kCentralityNew,"0,5,10,30,50,70,90,101"); mix->AddVariable(AliDielectronVarManager::kNacc,"0,10000"); mix->SetDepth(Nmix); if(!isMC) diel->SetMixingHandler(mix); } task->AddDielectron(diel); }//loop //Add event filter task->SetEventFilter((reinterpret_cast<AliDielectronEventCuts*>(gROOT->ProcessLine(Form("GetEventCuts(%f,%f,%d,\"%s\")",(Float_t)CenMin,(Float_t)CenMax,rejpileup,"V0M"))))); mgr->AddTask(task); //create output container AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(Form("tree_lowmass_%s", appendix.Data()), TTree::Class(), AliAnalysisManager::kExchangeContainer, Form("%s",outputFileName.Data())); AliAnalysisDataContainer *cOutputHist1 = mgr->CreateContainer(Form("Histos_diel_lowmass_%s", appendix.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s",outputFileName.Data())); AliAnalysisDataContainer *cOutputHist2 = mgr->CreateContainer(Form("CF_diel_lowmass_%s", appendix.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s",outputFileName.Data())); AliAnalysisDataContainer *cOutputHist3 = mgr->CreateContainer(Form("rbailhac_lowmass_EventStat_%s", appendix.Data()), TH1D::Class(), AliAnalysisManager::kOutputContainer, Form("%s",outputFileName.Data())); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 0, coutput1 ); mgr->ConnectOutput(task, 1, cOutputHist1); mgr->ConnectOutput(task, 2, cOutputHist2); mgr->ConnectOutput(task, 3, cOutputHist3); return task; } <commit_msg>Fix for input of Config<commit_after>AliAnalysisTask *AddTask_rbailhac_lowmass_PbPb(Bool_t getFromAlien=kFALSE, TString cFileName = "Config_rbailhac_lowmass_PbPb.C", TString calibFileName = "", UInt_t trigger = AliVEvent::kINT7|AliVEvent::kCentral|AliVEvent::kSemiCentral, const Int_t CenMin = 0, const Int_t CenMax = 10, const Bool_t isMC = kFALSE, const Bool_t isMix = kTRUE, const Int_t Nmix = 10, const TString outputFileName="LMEE.root", Bool_t rejpileup = kTRUE ) { //get the current analysis manager AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTask_rbailhac_test", "No analysis manager found."); return 0; } //Base Directory for GRID / LEGO Train TString configBasePath= "$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/"; if(getFromAlien && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/r/rbailhac/PWGDQ/dielectron/macrosLMEE/%s .",cFileName.Data()))) ){ configBasePath=Form("%s/",gSystem->pwd()); } TString configFilePath(configBasePath+cFileName); std::cout << "Configpath: " << configFilePath << std::endl; if (!gROOT->GetListOfGlobalFunctions()->FindObject("Config_rbailhac_lowmass_PbPb")) { printf("Load macro now\n"); gROOT->LoadMacro(configFilePath.Data()); } // trigger TString triggername = "NULL"; if(trigger == (UInt_t)AliVEvent::kINT7) triggername = "kINT7"; else if(trigger == (UInt_t)AliVEvent::kCentral) triggername = "kCentral"; else if(trigger == (UInt_t)AliVEvent::kSemiCentral) triggername = "kSemiCentral"; else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kCentral | AliVEvent::kSemiCentral)) triggername = "kCombinedCentralityTriggers"; else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kCentral)) triggername = "kCombinedCentral"; else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kSemiCentral)) triggername = "kCombinedSemiCentral"; //create task and add it to the manager (MB) TString appendix; appendix += TString::Format("Cen%d_%d_%s_rejpileup%d",CenMin,CenMax,triggername.Data(),rejpileup); printf("appendix %s\n", appendix.Data()); AliAnalysisTaskMultiDielectron *task = new AliAnalysisTaskMultiDielectron(Form("MultiDielectron_%s",appendix.Data())); task->UsePhysicsSelection(); task->SetTriggerMask(trigger); // PID postcalibration THnF *hs_mean_TPC_El = 0x0; THnF *hs_width_TPC_El = 0x0; THnF *hs_mean_ITS_El = 0x0; THnF *hs_width_ITS_El = 0x0; THnF *hs_mean_TOF_El = 0x0; THnF *hs_width_TOF_El = 0x0; THnF *hs_mean_TPC_Pi = 0x0; THnF *hs_width_TPC_Pi = 0x0; THnF *hs_mean_TPC_Ka = 0x0; THnF *hs_width_TPC_Ka = 0x0; THnF *hs_mean_TPC_Pr = 0x0; THnF *hs_width_TPC_Pr = 0x0; // PID post-calibration TFile *rootfile = 0x0; if(calibFileName.Contains("pass3")){ printf("reading : %s for PID calibration\n",calibFileName.Data()); rootfile = TFile::Open(calibFileName,"READ"); hs_mean_TPC_El = (THnF*)rootfile->Get("hs_mean_TPC_El"); hs_width_TPC_El = (THnF*)rootfile->Get("hs_width_TPC_El"); hs_mean_ITS_El = (THnF*)rootfile->Get("hs_mean_ITS_El"); hs_width_ITS_El = (THnF*)rootfile->Get("hs_width_ITS_El"); hs_mean_TOF_El = (THnF*)rootfile->Get("hs_mean_TOF_El"); hs_width_TOF_El = (THnF*)rootfile->Get("hs_width_TOF_El"); hs_mean_TPC_Pi = (THnF*)rootfile->Get("hs_mean_TPC_Pi"); hs_width_TPC_Pi = (THnF*)rootfile->Get("hs_width_TPC_Pi"); hs_mean_TPC_Ka = (THnF*)rootfile->Get("hs_mean_TPC_Ka"); hs_width_TPC_Ka = (THnF*)rootfile->Get("hs_width_TPC_Ka"); hs_mean_TPC_Pr = (THnF*)rootfile->Get("hs_mean_TPC_Pr"); hs_width_TPC_Pr = (THnF*)rootfile->Get("hs_width_TPC_Pr"); } // Number of cuts const Int_t nDie = (Int_t)gROOT->ProcessLine("GetN()"); //add dielectron analysis with different cuts to the task for (Int_t i=0; i<nDie; ++i){ //nDie defined in config file AliDielectron *diel = reinterpret_cast<AliDielectron*>(gROOT->ProcessLine(Form("Config_rbailhac_lowmass_PbPb(%d,%d,%d)",i,isMC,isMix))); if(!diel) continue; if(rootfile && rootfile->IsOpen()){ diel->SetPIDCaibinPU(kTRUE); //for electron diel->SetCentroidCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kElectron,hs_mean_TPC_El ,AliDielectronVarManager::kNSDDSSDclsEvent,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta); diel-> SetWidthCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kElectron,hs_width_TPC_El,AliDielectronVarManager::kNSDDSSDclsEvent,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta); diel->SetCentroidCorrFunctionPU(AliDielectronPID::kITS,AliPID::kElectron,hs_mean_ITS_El ,AliDielectronVarManager::kNSDDSSDclsEvent,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta); diel-> SetWidthCorrFunctionPU(AliDielectronPID::kITS,AliPID::kElectron,hs_width_ITS_El,AliDielectronVarManager::kNSDDSSDclsEvent,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta); diel->SetCentroidCorrFunctionPU(AliDielectronPID::kTOF,AliPID::kElectron,hs_mean_TOF_El ,AliDielectronVarManager::kNSDDSSDclsEvent,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta); diel-> SetWidthCorrFunctionPU(AliDielectronPID::kTOF,AliPID::kElectron,hs_width_TOF_El,AliDielectronVarManager::kNSDDSSDclsEvent,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta); //for pion diel->SetCentroidCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kPion,hs_mean_TPC_Pi ,AliDielectronVarManager::kNSDDSSDclsEvent,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta); diel-> SetWidthCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kPion,hs_width_TPC_Pi ,AliDielectronVarManager::kNSDDSSDclsEvent,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta); //for kaon diel->SetCentroidCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kKaon,hs_mean_TPC_Ka ,AliDielectronVarManager::kNSDDSSDclsEvent,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta); diel-> SetWidthCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kKaon,hs_width_TPC_Ka ,AliDielectronVarManager::kNSDDSSDclsEvent,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta); //for proton diel->SetCentroidCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kProton,hs_mean_TPC_Pr ,AliDielectronVarManager::kNSDDSSDclsEvent,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta); diel-> SetWidthCorrFunctionPU(AliDielectronPID::kTPC,AliPID::kProton,hs_width_TPC_Pr ,AliDielectronVarManager::kNSDDSSDclsEvent,AliDielectronVarManager::kTPCpileupZ,AliDielectronVarManager::kTPCpileupM,AliDielectronVarManager::kPIn,AliDielectronVarManager::kEta); } if(isMix) { printf("Add event mixing handler\n"); AliDielectronMixingHandler *mix = new AliDielectronMixingHandler; mix->SetMixType(AliDielectronMixingHandler::kAll); mix->AddVariable(AliDielectronVarManager::kZvPrim,"-10., -8., -6., -4., -2. , 0., 2., 4., 6., 8. , 10."); mix->AddVariable(AliDielectronVarManager::kCentralityNew,"0,5,10,30,50,70,90,101"); mix->AddVariable(AliDielectronVarManager::kNacc,"0,10000"); mix->SetDepth(Nmix); if(!isMC) diel->SetMixingHandler(mix); } task->AddDielectron(diel); }//loop //Add event filter task->SetEventFilter((reinterpret_cast<AliDielectronEventCuts*>(gROOT->ProcessLine(Form("GetEventCuts(%f,%f,%d,\"%s\")",(Float_t)CenMin,(Float_t)CenMax,rejpileup,"V0M"))))); mgr->AddTask(task); //create output container AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(Form("tree_lowmass_%s", appendix.Data()), TTree::Class(), AliAnalysisManager::kExchangeContainer, Form("%s",outputFileName.Data())); AliAnalysisDataContainer *cOutputHist1 = mgr->CreateContainer(Form("Histos_diel_lowmass_%s", appendix.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s",outputFileName.Data())); AliAnalysisDataContainer *cOutputHist2 = mgr->CreateContainer(Form("CF_diel_lowmass_%s", appendix.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s",outputFileName.Data())); AliAnalysisDataContainer *cOutputHist3 = mgr->CreateContainer(Form("rbailhac_lowmass_EventStat_%s", appendix.Data()), TH1D::Class(), AliAnalysisManager::kOutputContainer, Form("%s",outputFileName.Data())); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 0, coutput1 ); mgr->ConnectOutput(task, 1, cOutputHist1); mgr->ConnectOutput(task, 2, cOutputHist2); mgr->ConnectOutput(task, 3, cOutputHist3); return task; } <|endoftext|>
<commit_before>#pragma once /* plugins.hpp ( , - flplugin.cpp) */ /* Copyright 1996 Eugene Roshal Copyright 2000 Far Group All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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 "bitflags.hpp" #include "plclass.hpp" #include "PluginA.hpp" #include "configdb.hpp" #include "mix.hpp" class SaveScreen; class FileEditor; class Viewer; class Frame; class Panel; struct FileListItem; enum { PLUGIN_FARGETFILE, PLUGIN_FARGETFILES, PLUGIN_FARPUTFILES, PLUGIN_FARDELETEFILES, PLUGIN_FARMAKEDIRECTORY, PLUGIN_FAROTHER }; // Plugin.WorkFlags enum PLUGINITEMWORKFLAGS { PIWF_CACHED = 0x00000001, // PIWF_PRELOADED = 0x00000002, // PIWF_DONTLOADAGAIN = 0x00000004, // , // PIWF_DATALOADED = 0x00000008, // LoadData }; // Plugin.FuncFlags - enum PLUGINITEMCALLFUNCFLAGS { PICFF_LOADED = 0x00000001, // DLL ;-) PICFF_OPENPANEL = 0x00000004, // PICFF_ANALYSE = 0x00000008, // PICFF_CLOSEPANEL = 0x00000010, // PICFF_GETGLOBALINFO = 0x00000002, // PICFF_SETSTARTUPINFO = 0x00000004, // PICFF_OPENPLUGIN = 0x00000008, // PICFF_OPENFILEPLUGIN = 0x00000010, // PICFF_CLOSEPLUGIN = 0x00000020, // PICFF_GETPLUGININFO = 0x00000040, // PICFF_GETOPENPANELINFO = 0x00000080, // PICFF_GETFINDDATA = 0x00000100, // PICFF_FREEFINDDATA = 0x00000200, // PICFF_GETVIRTUALFINDDATA = 0x00000400, // PICFF_FREEVIRTUALFINDDATA = 0x00000800, // PICFF_SETDIRECTORY = 0x00001000, // PICFF_GETFILES = 0x00002000, // PICFF_PUTFILES = 0x00004000, // PICFF_DELETEFILES = 0x00008000, // PICFF_MAKEDIRECTORY = 0x00010000, // PICFF_PROCESSHOSTFILE = 0x00020000, // PICFF_SETFINDLIST = 0x00040000, // PICFF_CONFIGURE = 0x00080000, // PICFF_EXITFAR = 0x00100000, // PICFF_PROCESSPANELINPUT = 0x00200000, // PICFF_PROCESSPANELEVENT = 0x00400000, // PICFF_PROCESSEDITOREVENT = 0x00800000, // PICFF_COMPARE = 0x01000000, // PICFF_PROCESSEDITORINPUT = 0x02000000, // PICFF_MINFARVERSION = 0x04000000, // PICFF_PROCESSVIEWEREVENT = 0x08000000, // PICFF_PROCESSDIALOGEVENT = 0x10000000, // PICFF_PROCESSSYNCHROEVENT = 0x20000000, // PICFF_PROCESSCONSOLEINPUT = 0x40000000, // }; // PluginManager.Flags enum PLUGINSETFLAGS { PSIF_ENTERTOOPENPLUGIN = 0x00000001, // OpenPlugin PSIF_PLUGINSLOADDED = 0x80000000, // }; enum OPENFILEPLUGINTYPE { OFP_NORMAL, OFP_ALTERNATIVE, OFP_SEARCH, OFP_CREATE, OFP_EXTRACT, OFP_COMMANDS, }; // plugin.call .. typedef unsigned int CALLPLUGINFLAGS; static const CALLPLUGINFLAGS CPT_MENU = 0x00000001L, CPT_CONFIGURE = 0x00000002L, CPT_CMDLINE = 0x00000004L, CPT_INTERNAL = 0x00000008L, CPT_MASK = 0x0000000FL, CPT_CHECKONLY = 0x10000000L; struct CallPluginInfo { CALLPLUGINFLAGS CallFlags; int OpenFrom; union { GUID *ItemGuid; const wchar_t *Command; }; // CallPluginItem Plugin *pPlugin; GUID FoundGuid; }; struct PluginHandle { HANDLE hPlugin; class Plugin *pPlugin; }; class Dialog; class PluginManager { public: PluginManager(); ~PluginManager(); // API functions HANDLE Open(Plugin *pPlugin,int OpenFrom,const GUID& Guid,intptr_t Item); HANDLE OpenFilePlugin(const string* Name, int OpMode, OPENFILEPLUGINTYPE Type); HANDLE OpenFindListPlugin(const PluginPanelItem *PanelItem,size_t ItemsNumber); void ClosePanel(HANDLE hPlugin); void GetOpenPanelInfo(HANDLE hPlugin, OpenPanelInfo *Info); int GetFindData(HANDLE hPlugin,PluginPanelItem **pPanelItem,size_t *pItemsNumber,int OpMode); void FreeFindData(HANDLE hPlugin,PluginPanelItem *PanelItem,size_t ItemsNumber,bool FreeUserData); int GetVirtualFindData(HANDLE hPlugin,PluginPanelItem **pPanelItem,size_t *pItemsNumber,const string& Path); void FreeVirtualFindData(HANDLE hPlugin,PluginPanelItem *PanelItem,size_t ItemsNumber); int SetDirectory(HANDLE hPlugin,const string& Dir,int OpMode,struct UserDataItem *UserData=nullptr); int GetFile(HANDLE hPlugin,PluginPanelItem *PanelItem,const string& DestPath,string &strResultName,int OpMode); int GetFiles(HANDLE hPlugin,PluginPanelItem *PanelItem,size_t ItemsNumber,bool Move,const wchar_t **DestPath,int OpMode); int PutFiles(HANDLE hPlugin,PluginPanelItem *PanelItem,size_t ItemsNumber,bool Move,int OpMode); int DeleteFiles(HANDLE hPlugin,PluginPanelItem *PanelItem,size_t ItemsNumber,int OpMode); int MakeDirectory(HANDLE hPlugin,const wchar_t **Name,int OpMode); int ProcessHostFile(HANDLE hPlugin,PluginPanelItem *PanelItem,size_t ItemsNumber,int OpMode); int ProcessKey(HANDLE hPlugin,const INPUT_RECORD *Rec,bool Pred); int ProcessEvent(HANDLE hPlugin,int Event,void *Param); int Compare(HANDLE hPlugin,const PluginPanelItem *Item1,const PluginPanelItem *Item2,unsigned int Mode); int ProcessEditorInput(INPUT_RECORD *Rec); int ProcessEditorEvent(int Event,void *Param,int EditorID); int ProcessSubscribedEditorEvent(int Event,void *Param,int EditorID, const std::list<GUID> &PluginIds); int ProcessViewerEvent(int Event,void *Param,int ViewerID); int ProcessDialogEvent(int Event,FarDialogEvent *Param); int ProcessConsoleInput(ProcessConsoleInputInfo *Info); void GetCustomData(FileListItem *ListItem); int UnloadPlugin(Plugin *pPlugin, DWORD dwException); HANDLE LoadPluginExternal(const string& lpwszModuleName, bool LoadToMem); int UnloadPluginExternal(HANDLE hPlugin); bool IsPluginUnloaded(Plugin* pPlugin); void LoadPlugins(); std::list<Plugin*>::const_iterator begin() const { return SortedPlugins.cbegin(); } std::list<Plugin*>::const_iterator end() const { return SortedPlugins.cend(); } std::list<Plugin*>::const_iterator cbegin() const { return begin(); } std::list<Plugin*>::const_iterator cend() const { return end(); } // buggy implementation of begin()/end() in VC10, name "iterator" is hardcoded. #if defined(_MSC_VER) && _MSC_VER < 1700 typedef std::list<Plugin*>::const_iterator iterator; #endif typedef Plugin* value_type; Plugin *GetPlugin(const string& ModuleName); size_t GetPluginsCount() const { return SortedPlugins.size(); } #ifndef NO_WRAPPER size_t OemPluginsPresent() const { return OemPluginsCount > 0; } #endif // NO_WRAPPER bool IsPluginsLoaded() const { return Flags.Check(PSIF_PLUGINSLOADDED); } bool CheckFlags(DWORD NewFlags) const { return Flags.Check(NewFlags); } void Configure(int StartPos=0); void ConfigureCurrent(Plugin *pPlugin,const GUID& Guid); int CommandsMenu(int ModalType,int StartPos,const wchar_t *HistoryName=nullptr); bool GetDiskMenuItem(Plugin *pPlugin,size_t PluginItem,bool &ItemPresent, wchar_t& PluginHotkey, string &strPluginText, GUID &Guid); int UseFarCommand(HANDLE hPlugin,int CommandType); void ReloadLanguage(); void DiscardCache(); int ProcessCommandLine(const string& Command,Panel *Target=nullptr); bool SetHotKeyDialog(Plugin *pPlugin, const GUID& Guid, PluginsHotkeysConfig::HotKeyTypeEnum HotKeyType, const string& DlgPluginTitle); void ShowPluginInfo(Plugin *pPlugin, const GUID& Guid); size_t GetPluginInformation(Plugin *pPlugin, FarGetPluginInformation *pInfo, size_t BufferSize); // $ .09.2000 SVS - CallPlugin - ID OpenFrom = OPEN_* int CallPlugin(const GUID& SysID,int OpenFrom, void *Data, void **Ret=nullptr); int CallPluginItem(const GUID& Guid, CallPluginInfo *Data); Plugin *FindPlugin(const GUID& SysID) const; static const GUID& GetGUID(HANDLE hPlugin); void RefreshPluginsList(); void UndoRemove(Plugin* plugin); FileEditor* GetCurEditor() const { return m_CurEditor; } void SetCurEditor(FileEditor* Editor) { m_CurEditor = Editor; } Viewer* GetCurViewer() const { return m_CurViewer; } void SetCurViewer(Viewer* Viewer) { m_CurViewer = Viewer; } private: void LoadIfCacheAbsent(); void ReadUserBackgound(SaveScreen *SaveScr); void GetHotKeyPluginKey(Plugin *pPlugin, string &strPluginKey); void GetPluginHotKey(Plugin *pPlugin,const GUID& Guid, PluginsHotkeysConfig::HotKeyTypeEnum HotKeyType,string &strHotKey); Plugin* LoadPlugin(const string& lpwszModuleName, const FAR_FIND_DATA &FindData, bool LoadToMem); bool AddPlugin(Plugin *pPlugin); bool RemovePlugin(Plugin *pPlugin); bool UpdateId(Plugin *pPlugin, const GUID& Id); void LoadPluginsFromCache(); std::unordered_map<GUID, std::unique_ptr<Plugin>, uuid_hash, uuid_equal> Plugins; std::list<Plugin*> SortedPlugins; std::list<Plugin*> UnloadedPlugins; BitFlags Flags; #ifndef NO_WRAPPER size_t OemPluginsCount; #endif // NO_WRAPPER FileEditor* m_CurEditor; Viewer* m_CurViewer; friend class Plugin; }; <commit_msg>minor<commit_after>#pragma once /* plugins.hpp ( , - flplugin.cpp) */ /* Copyright 1996 Eugene Roshal Copyright 2000 Far Group All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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 "bitflags.hpp" #include "plclass.hpp" #include "PluginA.hpp" #include "configdb.hpp" #include "mix.hpp" class SaveScreen; class FileEditor; class Viewer; class Frame; class Panel; struct FileListItem; enum { PLUGIN_FARGETFILE, PLUGIN_FARGETFILES, PLUGIN_FARPUTFILES, PLUGIN_FARDELETEFILES, PLUGIN_FARMAKEDIRECTORY, PLUGIN_FAROTHER }; // Plugin.WorkFlags enum PLUGINITEMWORKFLAGS { PIWF_CACHED = 0x00000001, // PIWF_PRELOADED = 0x00000002, // PIWF_DONTLOADAGAIN = 0x00000004, // , // PIWF_DATALOADED = 0x00000008, // LoadData }; // Plugin.FuncFlags - enum PLUGINITEMCALLFUNCFLAGS { PICFF_LOADED = 0x00000001, // DLL ;-) PICFF_OPENPANEL = 0x00000004, // PICFF_ANALYSE = 0x00000008, // PICFF_CLOSEPANEL = 0x00000010, // PICFF_GETGLOBALINFO = 0x00000002, // PICFF_SETSTARTUPINFO = 0x00000004, // PICFF_OPENPLUGIN = 0x00000008, // PICFF_OPENFILEPLUGIN = 0x00000010, // PICFF_CLOSEPLUGIN = 0x00000020, // PICFF_GETPLUGININFO = 0x00000040, // PICFF_GETOPENPANELINFO = 0x00000080, // PICFF_GETFINDDATA = 0x00000100, // PICFF_FREEFINDDATA = 0x00000200, // PICFF_GETVIRTUALFINDDATA = 0x00000400, // PICFF_FREEVIRTUALFINDDATA = 0x00000800, // PICFF_SETDIRECTORY = 0x00001000, // PICFF_GETFILES = 0x00002000, // PICFF_PUTFILES = 0x00004000, // PICFF_DELETEFILES = 0x00008000, // PICFF_MAKEDIRECTORY = 0x00010000, // PICFF_PROCESSHOSTFILE = 0x00020000, // PICFF_SETFINDLIST = 0x00040000, // PICFF_CONFIGURE = 0x00080000, // PICFF_EXITFAR = 0x00100000, // PICFF_PROCESSPANELINPUT = 0x00200000, // PICFF_PROCESSPANELEVENT = 0x00400000, // PICFF_PROCESSEDITOREVENT = 0x00800000, // PICFF_COMPARE = 0x01000000, // PICFF_PROCESSEDITORINPUT = 0x02000000, // PICFF_MINFARVERSION = 0x04000000, // PICFF_PROCESSVIEWEREVENT = 0x08000000, // PICFF_PROCESSDIALOGEVENT = 0x10000000, // PICFF_PROCESSSYNCHROEVENT = 0x20000000, // PICFF_PROCESSCONSOLEINPUT = 0x40000000, // }; // PluginManager.Flags enum PLUGINSETFLAGS { PSIF_ENTERTOOPENPLUGIN = 0x00000001, // OpenPlugin PSIF_PLUGINSLOADDED = 0x80000000, // }; enum OPENFILEPLUGINTYPE { OFP_NORMAL, OFP_ALTERNATIVE, OFP_SEARCH, OFP_CREATE, OFP_EXTRACT, OFP_COMMANDS, }; // plugin.call .. typedef unsigned int CALLPLUGINFLAGS; static const CALLPLUGINFLAGS CPT_MENU = 0x00000001L, CPT_CONFIGURE = 0x00000002L, CPT_CMDLINE = 0x00000004L, CPT_INTERNAL = 0x00000008L, CPT_MASK = 0x0000000FL, CPT_CHECKONLY = 0x10000000L; struct CallPluginInfo { CALLPLUGINFLAGS CallFlags; int OpenFrom; union { GUID *ItemGuid; const wchar_t *Command; }; // CallPluginItem Plugin *pPlugin; GUID FoundGuid; }; struct PluginHandle { HANDLE hPlugin; class Plugin *pPlugin; }; class Dialog; class PluginManager { public: PluginManager(); ~PluginManager(); // API functions HANDLE Open(Plugin *pPlugin,int OpenFrom,const GUID& Guid,intptr_t Item); HANDLE OpenFilePlugin(const string* Name, int OpMode, OPENFILEPLUGINTYPE Type); HANDLE OpenFindListPlugin(const PluginPanelItem *PanelItem,size_t ItemsNumber); void ClosePanel(HANDLE hPlugin); void GetOpenPanelInfo(HANDLE hPlugin, OpenPanelInfo *Info); int GetFindData(HANDLE hPlugin,PluginPanelItem **pPanelItem,size_t *pItemsNumber,int OpMode); void FreeFindData(HANDLE hPlugin,PluginPanelItem *PanelItem,size_t ItemsNumber,bool FreeUserData); int GetVirtualFindData(HANDLE hPlugin,PluginPanelItem **pPanelItem,size_t *pItemsNumber,const string& Path); void FreeVirtualFindData(HANDLE hPlugin,PluginPanelItem *PanelItem,size_t ItemsNumber); int SetDirectory(HANDLE hPlugin,const string& Dir,int OpMode,struct UserDataItem *UserData=nullptr); int GetFile(HANDLE hPlugin,PluginPanelItem *PanelItem,const string& DestPath,string &strResultName,int OpMode); int GetFiles(HANDLE hPlugin,PluginPanelItem *PanelItem,size_t ItemsNumber,bool Move,const wchar_t **DestPath,int OpMode); int PutFiles(HANDLE hPlugin,PluginPanelItem *PanelItem,size_t ItemsNumber,bool Move,int OpMode); int DeleteFiles(HANDLE hPlugin,PluginPanelItem *PanelItem,size_t ItemsNumber,int OpMode); int MakeDirectory(HANDLE hPlugin,const wchar_t **Name,int OpMode); int ProcessHostFile(HANDLE hPlugin,PluginPanelItem *PanelItem,size_t ItemsNumber,int OpMode); int ProcessKey(HANDLE hPlugin,const INPUT_RECORD *Rec,bool Pred); int ProcessEvent(HANDLE hPlugin,int Event,void *Param); int Compare(HANDLE hPlugin,const PluginPanelItem *Item1,const PluginPanelItem *Item2,unsigned int Mode); int ProcessEditorInput(INPUT_RECORD *Rec); int ProcessEditorEvent(int Event,void *Param,int EditorID); int ProcessSubscribedEditorEvent(int Event,void *Param,int EditorID, const std::list<GUID> &PluginIds); int ProcessViewerEvent(int Event,void *Param,int ViewerID); int ProcessDialogEvent(int Event,FarDialogEvent *Param); int ProcessConsoleInput(ProcessConsoleInputInfo *Info); void GetCustomData(FileListItem *ListItem); int UnloadPlugin(Plugin *pPlugin, DWORD dwException); HANDLE LoadPluginExternal(const string& lpwszModuleName, bool LoadToMem); int UnloadPluginExternal(HANDLE hPlugin); bool IsPluginUnloaded(Plugin* pPlugin); void LoadPlugins(); std::list<Plugin*>::const_iterator begin() const { return SortedPlugins.cbegin(); } std::list<Plugin*>::const_iterator end() const { return SortedPlugins.cend(); } std::list<Plugin*>::const_iterator cbegin() const { return begin(); } std::list<Plugin*>::const_iterator cend() const { return end(); } #if defined(_MSC_VER) && _MSC_VER < 1700 // buggy implementation of begin()/end() in VC10, name "iterator" is hardcoded. typedef std::list<Plugin*>::const_iterator iterator; #endif typedef Plugin* value_type; Plugin *GetPlugin(const string& ModuleName); size_t GetPluginsCount() const { return SortedPlugins.size(); } #ifndef NO_WRAPPER size_t OemPluginsPresent() const { return OemPluginsCount > 0; } #endif // NO_WRAPPER bool IsPluginsLoaded() const { return Flags.Check(PSIF_PLUGINSLOADDED); } bool CheckFlags(DWORD NewFlags) const { return Flags.Check(NewFlags); } void Configure(int StartPos=0); void ConfigureCurrent(Plugin *pPlugin,const GUID& Guid); int CommandsMenu(int ModalType,int StartPos,const wchar_t *HistoryName=nullptr); bool GetDiskMenuItem(Plugin *pPlugin,size_t PluginItem,bool &ItemPresent, wchar_t& PluginHotkey, string &strPluginText, GUID &Guid); int UseFarCommand(HANDLE hPlugin,int CommandType); void ReloadLanguage(); void DiscardCache(); int ProcessCommandLine(const string& Command,Panel *Target=nullptr); bool SetHotKeyDialog(Plugin *pPlugin, const GUID& Guid, PluginsHotkeysConfig::HotKeyTypeEnum HotKeyType, const string& DlgPluginTitle); void ShowPluginInfo(Plugin *pPlugin, const GUID& Guid); size_t GetPluginInformation(Plugin *pPlugin, FarGetPluginInformation *pInfo, size_t BufferSize); // $ .09.2000 SVS - CallPlugin - ID OpenFrom = OPEN_* int CallPlugin(const GUID& SysID,int OpenFrom, void *Data, void **Ret=nullptr); int CallPluginItem(const GUID& Guid, CallPluginInfo *Data); Plugin *FindPlugin(const GUID& SysID) const; static const GUID& GetGUID(HANDLE hPlugin); void RefreshPluginsList(); void UndoRemove(Plugin* plugin); FileEditor* GetCurEditor() const { return m_CurEditor; } void SetCurEditor(FileEditor* Editor) { m_CurEditor = Editor; } Viewer* GetCurViewer() const { return m_CurViewer; } void SetCurViewer(Viewer* Viewer) { m_CurViewer = Viewer; } private: void LoadIfCacheAbsent(); void ReadUserBackgound(SaveScreen *SaveScr); void GetHotKeyPluginKey(Plugin *pPlugin, string &strPluginKey); void GetPluginHotKey(Plugin *pPlugin,const GUID& Guid, PluginsHotkeysConfig::HotKeyTypeEnum HotKeyType,string &strHotKey); Plugin* LoadPlugin(const string& lpwszModuleName, const FAR_FIND_DATA &FindData, bool LoadToMem); bool AddPlugin(Plugin *pPlugin); bool RemovePlugin(Plugin *pPlugin); bool UpdateId(Plugin *pPlugin, const GUID& Id); void LoadPluginsFromCache(); std::unordered_map<GUID, std::unique_ptr<Plugin>, uuid_hash, uuid_equal> Plugins; std::list<Plugin*> SortedPlugins; std::list<Plugin*> UnloadedPlugins; BitFlags Flags; #ifndef NO_WRAPPER size_t OemPluginsCount; #endif // NO_WRAPPER FileEditor* m_CurEditor; Viewer* m_CurViewer; friend class Plugin; }; <|endoftext|>
<commit_before>/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "util/optional.h" #include "util/buffer.h" #include "kernel/free_vars.h" #include "kernel/instantiate.h" #include "kernel/kernel.h" #include "library/equality.h" #include "library/kernel_bindings.h" #include "library/hop_match.h" namespace lean { class hop_match_fn { buffer<optional<expr>> & m_subst; buffer<expr> m_vars; optional<ro_environment> m_env; bool is_free_var(expr const & x, unsigned ctx_size) const { return is_var(x) && var_idx(x) >= ctx_size; } bool is_locally_bound(expr const & x, unsigned ctx_size) const { return is_var(x) && var_idx(x) < ctx_size; } optional<expr> get_subst(expr const & x, unsigned ctx_size) const { lean_assert(is_free_var(x, ctx_size)); unsigned vidx = var_idx(x) - ctx_size; unsigned sz = m_subst.size(); if (vidx >= sz) throw exception("ill-formed higher-order matching problem"); return m_subst[sz - vidx - 1]; } bool has_locally_bound_var(expr const & t, unsigned ctx_size) const { return has_free_var(t, 0, ctx_size); } void assign(expr const & p, expr const & t, unsigned ctx_size) { lean_assert(is_free_var(p, ctx_size)); lean_assert(!get_subst(p, ctx_size)); unsigned vidx = var_idx(p) - ctx_size; unsigned sz = m_subst.size(); m_subst[sz - vidx - 1] = t; } bool args_are_distinct_locally_bound_vars(expr const & p, unsigned ctx_size, buffer<expr> & vars) { lean_assert(is_app(p)); vars.clear(); unsigned num = num_args(p); for (unsigned i = 1; i < num; i++) { expr const & v = arg(p, i); if (!is_locally_bound(v, ctx_size)) return false; if (std::find(vars.begin(), vars.end(), v) != vars.end()) return false; vars.push_back(v); } return true; } /** \brief Return t' when all locally bound variables in \c t occur in vars at positions [0, vars_size). The locally bound variables occurring in \c t are replaced using the following mapping: vars[vars_size - 1] ==> #0 ... vars[0] ==> #vars_size - 1 None is returned if \c t contains a locally bound variable that does not occur in \c vars. Remark: vars_size <= vars.size() */ optional<expr> proj_core(expr const & t, unsigned ctx_size, buffer<expr> const & vars, unsigned vars_size) { bool failed = false; expr r = replace(t, [&](expr const & e, unsigned offset) -> expr { if (is_var(e)) { unsigned vidx = var_idx(e); if (vidx < offset) return e; vidx -= offset; if (vidx < ctx_size) { // e is locally bound for (unsigned i = 0; i < vars_size; i++) { if (var_idx(vars[i]) == vidx) return mk_var(offset + vars_size - i - 1); } failed = true; return e; } else if (ctx_size != vars_size) { return mk_var(offset + vidx - ctx_size + vars_size); } else { return e; } } else { return e; } }); if (failed) return none_expr(); else return some_expr(r); } // We say \c t has a simple projection when it is of the form (f v1 ... vn) // where f does no contain locally bound variables, and v1 ... vn are exactly the variables in vars. // In this case, the proj procedure can return f instead of (fun xn .... x1, f x1 ... xn) bool is_simple_proj(expr const & t, unsigned ctx_size, buffer<expr> const & vars) { if (is_app(t) && !has_locally_bound_var(arg(t, 0), ctx_size) && num_args(t) == vars.size() + 1) { for (unsigned i = 0; i < vars.size(); i++) if (arg(t, i+1) != vars[i]) return false; return true; } else { return false; } } /** \brief Return <tt>(fun (x1 ... xn) t')</tt> if all locally bound variables in \c t occur in vars. \c n is the size of \c vars. None is returned if \c t contains a locally bound variable that does not occur in \c vars. */ optional<expr> proj(expr const & t, context const & ctx, unsigned ctx_size, buffer<expr> const & vars) { if (is_simple_proj(t, ctx_size, vars)) { return some_expr(lower_free_vars(arg(t, 0), ctx_size, ctx_size)); } optional<expr> t_prime = proj_core(t, ctx_size, vars, vars.size()); if (!t_prime) return none_expr(); expr r = *t_prime; unsigned i = vars.size(); while (i > 0) { --i; unsigned vidx = var_idx(vars[i]); auto p = lookup_ext(ctx, vidx); context_entry const & entry = p.first; context entry_ctx = p.second; if (!entry.get_domain()) return none_expr(); expr d = *entry.get_domain(); optional<expr> new_d = proj_core(d, entry_ctx.size(), vars, i); if (!new_d) return none_expr(); r = mk_lambda(entry.get_name(), *new_d, r); } return some_expr(r); } optional<expr> unfold_constant(expr const & c) { if (is_constant(c)) { auto obj = (*m_env)->find_object(const_name(c)); if (obj && (obj->is_definition() || obj->is_builtin())) return some_expr(obj->get_value()); } return none_expr(); } bool match_constant(expr const & p, expr const & t) { if (p == t) return true; auto new_p = unfold_constant(p); if (new_p) return match_constant(*new_p, t); return false; } bool match(expr const & p, expr const & t, context const & ctx, unsigned ctx_size) { lean_assert(ctx.size() == ctx_size); if (is_free_var(p, ctx_size)) { auto s = get_subst(p, ctx_size); if (s) { return lift_free_vars(*s, ctx_size) == t; } else if (has_locally_bound_var(t, ctx_size)) { return false; } else { assign(p, lower_free_vars(t, ctx_size, ctx_size), ctx_size); return true; } } else if (is_app(p) && is_free_var(arg(p, 0), ctx_size) && args_are_distinct_locally_bound_vars(p, ctx_size, m_vars)) { // higher-order pattern case auto s = get_subst(arg(p, 0), ctx_size); unsigned num = num_args(p); if (s) { expr f = lift_free_vars(*s, ctx_size); expr new_p = apply_beta(f, num - 1, &(arg(p, 1))); return new_p == t; } else { optional<expr> new_t = proj(t, ctx, ctx_size, m_vars); if (new_t) { assign(arg(p, 0), *new_t, ctx_size); return true; } // fallback to the first-order case } } if (p == t && !has_free_var_ge(p, ctx_size)) { return true; } if (m_env && is_constant(p)) { return match_constant(p, t); } if (is_equality(p) && is_equality(t) && (!is_eq(p) || !is_eq(t))) { // Remark: if p and t are homogeneous equality, then we handle as an application (in the else branch) // We do that because we can get more information. For example, the pattern // may be (eq #1 a b). // This branch ignores the type. expr_pair p1 = get_equality_args(p); expr_pair p2 = get_equality_args(t); return match(p1.first, p2.first, ctx, ctx_size) && match(p1.second, p2.second, ctx, ctx_size); } else { if (p.kind() != t.kind()) return false; switch (p.kind()) { case expr_kind::Var: case expr_kind::Constant: case expr_kind::Type: case expr_kind::Value: case expr_kind::MetaVar: return false; case expr_kind::App: { unsigned i1 = num_args(p); unsigned i2 = num_args(t); while (i1 > 0 && i2 > 0) { --i1; --i2; if (i1 == 0 && i2 > 0) { return match(arg(p, i1), mk_app(i2+1, begin_args(t)), ctx, ctx_size); } else if (i2 == 0 && i1 > 0) { return match(mk_app(i1+1, begin_args(p)), arg(t, i2), ctx, ctx_size); } else { if (!match(arg(p, i1), arg(t, i2), ctx, ctx_size)) return false; } } return true; } case expr_kind::Lambda: case expr_kind::Pi: return match(abst_domain(p), abst_domain(t), ctx, ctx_size) && match(abst_body(p), abst_body(t), extend(ctx, abst_name(t), abst_domain(t)), ctx_size+1); case expr_kind::Let: // TODO(Leo) return false; } } lean_unreachable(); } public: hop_match_fn(buffer<optional<expr>> & subst, optional<ro_environment> const & env):m_subst(subst), m_env(env) {} bool operator()(expr const & p, expr const & t) { return match(p, t, context(), 0); } }; bool hop_match(expr const & p, expr const & t, buffer<optional<expr>> & subst, optional<ro_environment> const & env) { return hop_match_fn(subst, env)(p, t); } static int hop_match_core(lua_State * L, optional<ro_environment> const & env) { int nargs = lua_gettop(L); expr p = to_expr(L, 1); expr t = to_expr(L, 2); int k = 0; if (nargs >= 4) { k = luaL_checkinteger(L, 4); if (k < 0) throw exception("hop_match, arg #4 must be non-negative"); } else { k = free_var_range(p); } buffer<optional<expr>> subst; subst.resize(k); if (hop_match(p, t, subst, env)) { lua_newtable(L); int i = 1; for (auto s : subst) { if (s) { push_expr(L, *s); } else { lua_pushboolean(L, false); } lua_rawseti(L, -2, i); i = i + 1; } } else { lua_pushnil(L); } return 1; } static int hop_match(lua_State * L) { int nargs = lua_gettop(L); if (nargs >= 3) { if (!lua_isnil(L, 3)) { ro_shared_environment env(L, 3); return hop_match_core(L, optional<ro_environment>(env)); } else { return hop_match_core(L, optional<ro_environment>()); } } else { ro_shared_environment env(L); return hop_match_core(L, optional<ro_environment>(env)); } } void open_hop_match(lua_State * L) { SET_GLOBAL_FUN(hop_match, "hop_match"); } } <commit_msg>feat(library/hop_match): make the higher order pattern matcher slightly stronger<commit_after>/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "util/optional.h" #include "util/buffer.h" #include "kernel/free_vars.h" #include "kernel/instantiate.h" #include "kernel/kernel.h" #include "kernel/for_each_fn.h" #include "kernel/replace_visitor.h" #include "library/equality.h" #include "library/kernel_bindings.h" #include "library/hop_match.h" namespace lean { class hop_match_fn { buffer<optional<expr>> & m_subst; buffer<expr> m_vars; optional<ro_environment> m_env; bool is_free_var(expr const & x, unsigned ctx_size) const { return is_var(x) && var_idx(x) >= ctx_size; } bool is_locally_bound(expr const & x, unsigned ctx_size) const { return is_var(x) && var_idx(x) < ctx_size; } optional<expr> get_subst(expr const & x, unsigned ctx_size) const { lean_assert(is_free_var(x, ctx_size)); unsigned vidx = var_idx(x) - ctx_size; unsigned sz = m_subst.size(); if (vidx >= sz) throw exception("ill-formed higher-order matching problem"); return m_subst[sz - vidx - 1]; } bool has_locally_bound_var(expr const & t, unsigned ctx_size) const { return has_free_var(t, 0, ctx_size); } void assign(expr const & p, expr const & t, unsigned ctx_size) { lean_assert(is_free_var(p, ctx_size)); lean_assert(!get_subst(p, ctx_size)); unsigned vidx = var_idx(p) - ctx_size; unsigned sz = m_subst.size(); m_subst[sz - vidx - 1] = t; } bool args_are_distinct_locally_bound_vars(expr const & p, unsigned ctx_size, buffer<expr> & vars) { lean_assert(is_app(p)); vars.clear(); unsigned num = num_args(p); for (unsigned i = 1; i < num; i++) { expr const & v = arg(p, i); if (!is_locally_bound(v, ctx_size)) return false; if (std::find(vars.begin(), vars.end(), v) != vars.end()) return false; vars.push_back(v); } return true; } /** \brief Return t' when all locally bound variables in \c t occur in vars at positions [0, vars_size). The locally bound variables occurring in \c t are replaced using the following mapping: vars[vars_size - 1] ==> #0 ... vars[0] ==> #vars_size - 1 None is returned if \c t contains a locally bound variable that does not occur in \c vars. Remark: vars_size <= vars.size() */ optional<expr> proj_core(expr const & t, unsigned ctx_size, buffer<expr> const & vars, unsigned vars_size) { bool failed = false; expr r = replace(t, [&](expr const & e, unsigned offset) -> expr { if (is_var(e)) { unsigned vidx = var_idx(e); if (vidx < offset) return e; vidx -= offset; if (vidx < ctx_size) { // e is locally bound for (unsigned i = 0; i < vars_size; i++) { if (var_idx(vars[i]) == vidx) return mk_var(offset + vars_size - i - 1); } failed = true; return e; } else if (ctx_size != vars_size) { return mk_var(offset + vidx - ctx_size + vars_size); } else { return e; } } else { return e; } }); if (failed) return none_expr(); else return some_expr(r); } // We say \c t has a simple projection when it is of the form (f v1 ... vn) // where f does no contain locally bound variables, and v1 ... vn are exactly the variables in vars. // In this case, the proj procedure can return f instead of (fun xn .... x1, f x1 ... xn) bool is_simple_proj(expr const & t, unsigned ctx_size, buffer<expr> const & vars) { if (is_app(t) && !has_locally_bound_var(arg(t, 0), ctx_size) && num_args(t) == vars.size() + 1) { for (unsigned i = 0; i < vars.size(); i++) if (arg(t, i+1) != vars[i]) return false; return true; } else { return false; } } /** \brief Return <tt>(fun (x1 ... xn) t')</tt> if all locally bound variables in \c t occur in vars. \c n is the size of \c vars. None is returned if \c t contains a locally bound variable that does not occur in \c vars. */ optional<expr> proj(expr const & t, context const & ctx, unsigned ctx_size, buffer<expr> const & vars) { if (is_simple_proj(t, ctx_size, vars)) { return some_expr(lower_free_vars(arg(t, 0), ctx_size, ctx_size)); } optional<expr> t_prime = proj_core(t, ctx_size, vars, vars.size()); if (!t_prime) return none_expr(); expr r = *t_prime; unsigned i = vars.size(); while (i > 0) { --i; unsigned vidx = var_idx(vars[i]); auto p = lookup_ext(ctx, vidx); context_entry const & entry = p.first; context entry_ctx = p.second; if (!entry.get_domain()) return none_expr(); expr d = *entry.get_domain(); optional<expr> new_d = proj_core(d, entry_ctx.size(), vars, i); if (!new_d) return none_expr(); r = mk_lambda(entry.get_name(), *new_d, r); } return some_expr(r); } optional<expr> unfold_constant(expr const & c) { if (is_constant(c)) { auto obj = (*m_env)->find_object(const_name(c)); if (obj && (obj->is_definition() || obj->is_builtin())) return some_expr(obj->get_value()); } return none_expr(); } bool match_constant(expr const & p, expr const & t) { if (p == t) return true; auto new_p = unfold_constant(p); if (new_p) return match_constant(*new_p, t); return false; } /** \brief Return true iff all free variables in the pattern \c p are assigned. */ bool all_free_vars_are_assigned(expr const & p, unsigned ctx_size) const { bool result = true; for_each(p, [&](expr const & v, unsigned offset) { if (!result) return false; if (is_var(v) && is_free_var(v, ctx_size + offset) && !get_subst(v, ctx_size + offset)) { result = false; } return true; }); return result; } /** \brief Auxiliary functional object for instantiating the free variables in a pattern. */ class instantiate_free_vars_proc : public replace_visitor { protected: hop_match_fn & m_ref; unsigned m_ctx_size; virtual expr visit_var(expr const & x, context const & ctx) { unsigned real_ctx_sz = ctx.size() + m_ctx_size; if (m_ref.is_free_var(x, real_ctx_sz)) { optional<expr> r = m_ref.get_subst(x, real_ctx_sz); lean_assert(r); return lift_free_vars(*r, real_ctx_sz); } else { return x; } } virtual expr visit_app(expr const & e, context const & ctx) { unsigned real_ctx_sz = ctx.size() + m_ctx_size; expr const & f = arg(e, 0); if (is_var(f) && m_ref.is_free_var(f, real_ctx_sz)) { buffer<expr> new_args; for (unsigned i = 0; i < num_args(e); i++) new_args.push_back(visit(arg(e, i), ctx)); if (is_lambda(new_args[0])) return apply_beta(new_args[0], new_args.size() - 1, new_args.data() + 1); else return mk_app(new_args); } else { return replace_visitor::visit_app(e, ctx); } } public: instantiate_free_vars_proc(hop_match_fn & fn, unsigned ctx_size): m_ref(fn), m_ctx_size(ctx_size) { } }; bool match(expr const & p, expr const & t, context const & ctx, unsigned ctx_size) { lean_assert(ctx.size() == ctx_size); if (is_free_var(p, ctx_size)) { auto s = get_subst(p, ctx_size); if (s) { return lift_free_vars(*s, ctx_size) == t; } else if (has_locally_bound_var(t, ctx_size)) { return false; } else { assign(p, lower_free_vars(t, ctx_size, ctx_size), ctx_size); return true; } } else if (is_app(p) && is_free_var(arg(p, 0), ctx_size)) { if (args_are_distinct_locally_bound_vars(p, ctx_size, m_vars)) { // higher-order pattern case auto s = get_subst(arg(p, 0), ctx_size); unsigned num = num_args(p); if (s) { expr f = lift_free_vars(*s, ctx_size); expr new_p = apply_beta(f, num - 1, &(arg(p, 1))); return new_p == t; } else { optional<expr> new_t = proj(t, ctx, ctx_size, m_vars); if (new_t) { assign(arg(p, 0), *new_t, ctx_size); return true; } } } if (all_free_vars_are_assigned(p, ctx_size)) { instantiate_free_vars_proc proc(*this, ctx_size); expr new_p = proc(p); return new_p == t; } // fallback to the first-order case } if (p == t && !has_free_var_ge(p, ctx_size)) { return true; } if (m_env && is_constant(p)) { return match_constant(p, t); } if (is_equality(p) && is_equality(t) && (!is_eq(p) || !is_eq(t))) { // Remark: if p and t are homogeneous equality, then we handle as an application (in the else branch) // We do that because we can get more information. For example, the pattern // may be (eq #1 a b). // This branch ignores the type. expr_pair p1 = get_equality_args(p); expr_pair p2 = get_equality_args(t); return match(p1.first, p2.first, ctx, ctx_size) && match(p1.second, p2.second, ctx, ctx_size); } else { if (p.kind() != t.kind()) return false; switch (p.kind()) { case expr_kind::Var: case expr_kind::Constant: case expr_kind::Type: case expr_kind::Value: case expr_kind::MetaVar: return false; case expr_kind::App: { unsigned i1 = num_args(p); unsigned i2 = num_args(t); while (i1 > 0 && i2 > 0) { --i1; --i2; if (i1 == 0 && i2 > 0) { return match(arg(p, i1), mk_app(i2+1, begin_args(t)), ctx, ctx_size); } else if (i2 == 0 && i1 > 0) { return match(mk_app(i1+1, begin_args(p)), arg(t, i2), ctx, ctx_size); } else { if (!match(arg(p, i1), arg(t, i2), ctx, ctx_size)) return false; } } return true; } case expr_kind::Lambda: case expr_kind::Pi: return match(abst_domain(p), abst_domain(t), ctx, ctx_size) && match(abst_body(p), abst_body(t), extend(ctx, abst_name(t), abst_domain(t)), ctx_size+1); case expr_kind::Let: // TODO(Leo) return false; } } lean_unreachable(); } public: hop_match_fn(buffer<optional<expr>> & subst, optional<ro_environment> const & env):m_subst(subst), m_env(env) {} bool operator()(expr const & p, expr const & t) { return match(p, t, context(), 0); } }; bool hop_match(expr const & p, expr const & t, buffer<optional<expr>> & subst, optional<ro_environment> const & env) { return hop_match_fn(subst, env)(p, t); } static int hop_match_core(lua_State * L, optional<ro_environment> const & env) { int nargs = lua_gettop(L); expr p = to_expr(L, 1); expr t = to_expr(L, 2); int k = 0; if (nargs >= 4) { k = luaL_checkinteger(L, 4); if (k < 0) throw exception("hop_match, arg #4 must be non-negative"); } else { k = free_var_range(p); } buffer<optional<expr>> subst; subst.resize(k); if (hop_match(p, t, subst, env)) { lua_newtable(L); int i = 1; for (auto s : subst) { if (s) { push_expr(L, *s); } else { lua_pushboolean(L, false); } lua_rawseti(L, -2, i); i = i + 1; } } else { lua_pushnil(L); } return 1; } static int hop_match(lua_State * L) { int nargs = lua_gettop(L); if (nargs >= 3) { if (!lua_isnil(L, 3)) { ro_shared_environment env(L, 3); return hop_match_core(L, optional<ro_environment>(env)); } else { return hop_match_core(L, optional<ro_environment>()); } } else { ro_shared_environment env(L); return hop_match_core(L, optional<ro_environment>(env)); } } void open_hop_match(lua_State * L) { SET_GLOBAL_FUN(hop_match, "hop_match"); } } <|endoftext|>
<commit_before>#ifndef TURBO_MEMORY_TAGGED_PTR_HPP #define TURBO_MEMORY_TAGGED_PTR_HPP #include <cstdint> #include <atomic> #include <limits> #include <stdexcept> #include <string> #include <turbo/toolset/extension.hpp> namespace turbo { namespace memory { class unaligned_ptr_error : public std::invalid_argument { public: explicit unaligned_ptr_error(const std::string& what) : invalid_argument(what) { } explicit unaligned_ptr_error(const char* what) : invalid_argument(what) { } }; template <class value_t, class tag_t> class tagged_ptr { public: typedef value_t value_type; typedef tag_t tag_type; typedef value_t* value_ptr_type; inline tagged_ptr() noexcept : ptr_(nullptr) { } inline explicit tagged_ptr(value_t* ptr) : ptr_(ptr) { if ((reinterpret_cast<std::uintptr_t>(ptr) & tag_mask()) != 0U) { throw unaligned_ptr_error("Given pointer is not a multiple of 4"); } } tagged_ptr(const tagged_ptr<value_t, tag_t>& other) = default; tagged_ptr(tagged_ptr<value_t, tag_t>&& other) = default; tagged_ptr<value_t, tag_t>& operator=(const tagged_ptr<value_t, tag_t>& other) = default; tagged_ptr<value_t, tag_t>& operator=(tagged_ptr<value_t, tag_t>&& other) = default; ~tagged_ptr() noexcept = default; inline value_t* get_ptr() const { return reinterpret_cast<value_t*>(reinterpret_cast<std::uintptr_t>(ptr_) & ptr_mask()); } inline tag_t get_tag() const { return static_cast<tag_t>(reinterpret_cast<std::uintptr_t>(ptr_) & tag_mask()); } inline bool is_empty() const { return get_ptr() == nullptr; } inline void set_tag(tag_t tag) { ptr_ = reinterpret_cast<value_t*>(reinterpret_cast<std::uintptr_t>(get_ptr()) | (static_cast<std::uintptr_t>(tag) & tag_mask())); } inline bool operator==(const tagged_ptr<value_t, tag_t>& other) const { return ptr_ == other.ptr_; } inline bool operator!=(const tagged_ptr<value_t, tag_t>& other) const { return !(*this == other); } inline tagged_ptr<value_t, tag_t> operator|(const tag_t tag) const { tagged_ptr<value_t, tag_t> tmp; tmp.set_tag(tag); return tmp; } inline void reset(value_t* ptr) { ptr_ = ptr; } inline value_t& operator*() { return *get_ptr(); } inline value_t* operator->() { return get_ptr(); } private: friend class std::atomic<tagged_ptr<value_t, tag_t>>; constexpr std::uintptr_t ptr_mask() { return std::numeric_limits<std::uintptr_t>::max() - 3U; } constexpr std::uintptr_t tag_mask() { return static_cast<std::uintptr_t>(3U); } value_t* ptr_; }; } // namespace memory } // namespace turbo namespace std { /// /// Partial specialisation of std::atomic for tagged_ptr /// template <class value_t, class tag_t> struct atomic<turbo::memory::tagged_ptr<value_t, tag_t>> : public std::atomic<typename turbo::memory::tagged_ptr<value_t, tag_t>::value_ptr_type> { typedef turbo::memory::tagged_ptr<value_t, tag_t> tagged_ptr_type; typedef std::atomic<typename tagged_ptr_type::value_ptr_type> base_type; atomic() noexcept = default; constexpr atomic(tagged_ptr_type value) noexcept : base_type(value.ptr_) { } atomic(const atomic&) = delete; ~atomic() noexcept = default; using base_type::is_lock_free; inline void store(tagged_ptr_type value, memory_order sync = memory_order_seq_cst) volatile noexcept { base_type::store(value.ptr_, sync); } inline void store(tagged_ptr_type value, memory_order sync = memory_order_seq_cst) noexcept { base_type::store(value.ptr_, sync); } inline tagged_ptr_type load(memory_order sync = memory_order_seq_cst) const volatile noexcept { tagged_ptr_type tmp; tmp.reset(base_type::load(sync)); return tmp; } inline tagged_ptr_type load(memory_order sync = memory_order_seq_cst) const noexcept { tagged_ptr_type tmp; tmp.reset(base_type::load(sync)); return tmp; } operator tagged_ptr_type() const volatile noexcept { return load(); } operator tagged_ptr_type() const noexcept { return load(); } inline tagged_ptr_type exchange(tagged_ptr_type value, memory_order sync = memory_order_seq_cst) volatile noexcept { return tagged_ptr_type(base_type::exchange(value.ptr_, sync)); } inline tagged_ptr_type exchange(tagged_ptr_type value, memory_order sync = memory_order_seq_cst) noexcept { return tagged_ptr_type(base_type::exchange(value.ptr_, sync)); } inline bool compare_exchange_weak(tagged_ptr_type& expected, tagged_ptr_type value, memory_order sync = memory_order_seq_cst) volatile noexcept { return base_type::compare_exchange_weak(expected.ptr_, value.ptr_, sync); } inline bool compare_exchange_weak(tagged_ptr_type& expected, tagged_ptr_type value, memory_order sync = memory_order_seq_cst) noexcept { return base_type::compare_exchange_weak(expected.ptr_, value.ptr_, sync); } inline bool compare_exchange_weak(tagged_ptr_type& expected, tagged_ptr_type value, memory_order success, memory_order failure) volatile noexcept { return base_type::compare_exchange_weak(expected.ptr_, value.ptr_, success, failure); } inline bool compare_exchange_weak(tagged_ptr_type& expected, tagged_ptr_type value, memory_order success, memory_order failure) noexcept { return base_type::compare_exchange_weak(expected.ptr_, value.ptr_, success, failure); } inline bool compare_exchange_strong(tagged_ptr_type& expected, tagged_ptr_type value, memory_order sync = memory_order_seq_cst) volatile noexcept { return base_type::compare_exchange_strong(expected.ptr_, value.ptr_, sync); } inline bool compare_exchange_strong(tagged_ptr_type& expected, tagged_ptr_type value, memory_order sync = memory_order_seq_cst) noexcept { return base_type::compare_exchange_strong(expected.ptr_, value.ptr_, sync); } inline bool compare_exchange_strong(tagged_ptr_type& expected, tagged_ptr_type value, memory_order success, memory_order failure) volatile noexcept { return base_type::compare_exchange_strong(expected.ptr_, value.ptr_, success, failure); } inline bool compare_exchange_strong(tagged_ptr_type& expected, tagged_ptr_type value, memory_order success, memory_order failure) noexcept { return base_type::compare_exchange_strong(expected.ptr_, value.ptr_, success, failure); } }; } // namespace std #endif <commit_msg>the atomic tagged_ptr specialisation should privately inherit its base class since we don't want to expose a sub-type relationship<commit_after>#ifndef TURBO_MEMORY_TAGGED_PTR_HPP #define TURBO_MEMORY_TAGGED_PTR_HPP #include <cstdint> #include <atomic> #include <limits> #include <stdexcept> #include <string> #include <turbo/toolset/extension.hpp> namespace turbo { namespace memory { class unaligned_ptr_error : public std::invalid_argument { public: explicit unaligned_ptr_error(const std::string& what) : invalid_argument(what) { } explicit unaligned_ptr_error(const char* what) : invalid_argument(what) { } }; template <class value_t, class tag_t> class tagged_ptr { public: typedef value_t value_type; typedef tag_t tag_type; typedef value_t* value_ptr_type; inline tagged_ptr() noexcept : ptr_(nullptr) { } inline explicit tagged_ptr(value_t* ptr) : ptr_(ptr) { if ((reinterpret_cast<std::uintptr_t>(ptr) & tag_mask()) != 0U) { throw unaligned_ptr_error("Given pointer is not a multiple of 4"); } } tagged_ptr(const tagged_ptr<value_t, tag_t>& other) = default; tagged_ptr(tagged_ptr<value_t, tag_t>&& other) = default; tagged_ptr<value_t, tag_t>& operator=(const tagged_ptr<value_t, tag_t>& other) = default; tagged_ptr<value_t, tag_t>& operator=(tagged_ptr<value_t, tag_t>&& other) = default; ~tagged_ptr() noexcept = default; inline value_t* get_ptr() const { return reinterpret_cast<value_t*>(reinterpret_cast<std::uintptr_t>(ptr_) & ptr_mask()); } inline tag_t get_tag() const { return static_cast<tag_t>(reinterpret_cast<std::uintptr_t>(ptr_) & tag_mask()); } inline bool is_empty() const { return get_ptr() == nullptr; } inline void set_tag(tag_t tag) { ptr_ = reinterpret_cast<value_t*>(reinterpret_cast<std::uintptr_t>(get_ptr()) | (static_cast<std::uintptr_t>(tag) & tag_mask())); } inline bool operator==(const tagged_ptr<value_t, tag_t>& other) const { return ptr_ == other.ptr_; } inline bool operator!=(const tagged_ptr<value_t, tag_t>& other) const { return !(*this == other); } inline tagged_ptr<value_t, tag_t> operator|(const tag_t tag) const { tagged_ptr<value_t, tag_t> tmp; tmp.set_tag(tag); return tmp; } inline void reset(value_t* ptr) { ptr_ = ptr; } inline value_t& operator*() { return *get_ptr(); } inline value_t* operator->() { return get_ptr(); } private: friend class std::atomic<tagged_ptr<value_t, tag_t>>; constexpr std::uintptr_t ptr_mask() { return std::numeric_limits<std::uintptr_t>::max() - 3U; } constexpr std::uintptr_t tag_mask() { return static_cast<std::uintptr_t>(3U); } value_t* ptr_; }; } // namespace memory } // namespace turbo namespace std { /// /// Partial specialisation of std::atomic for tagged_ptr /// template <class value_t, class tag_t> struct atomic<turbo::memory::tagged_ptr<value_t, tag_t>> : private std::atomic<typename turbo::memory::tagged_ptr<value_t, tag_t>::value_ptr_type> { typedef turbo::memory::tagged_ptr<value_t, tag_t> tagged_ptr_type; typedef std::atomic<typename tagged_ptr_type::value_ptr_type> base_type; atomic() noexcept = default; constexpr atomic(tagged_ptr_type value) noexcept : base_type(value.ptr_) { } atomic(const atomic&) = delete; ~atomic() noexcept = default; using base_type::is_lock_free; inline void store(tagged_ptr_type value, memory_order sync = memory_order_seq_cst) volatile noexcept { base_type::store(value.ptr_, sync); } inline void store(tagged_ptr_type value, memory_order sync = memory_order_seq_cst) noexcept { base_type::store(value.ptr_, sync); } inline tagged_ptr_type load(memory_order sync = memory_order_seq_cst) const volatile noexcept { tagged_ptr_type tmp; tmp.reset(base_type::load(sync)); return tmp; } inline tagged_ptr_type load(memory_order sync = memory_order_seq_cst) const noexcept { tagged_ptr_type tmp; tmp.reset(base_type::load(sync)); return tmp; } operator tagged_ptr_type() const volatile noexcept { return load(); } operator tagged_ptr_type() const noexcept { return load(); } inline tagged_ptr_type exchange(tagged_ptr_type value, memory_order sync = memory_order_seq_cst) volatile noexcept { return tagged_ptr_type(base_type::exchange(value.ptr_, sync)); } inline tagged_ptr_type exchange(tagged_ptr_type value, memory_order sync = memory_order_seq_cst) noexcept { return tagged_ptr_type(base_type::exchange(value.ptr_, sync)); } inline bool compare_exchange_weak(tagged_ptr_type& expected, tagged_ptr_type value, memory_order sync = memory_order_seq_cst) volatile noexcept { return base_type::compare_exchange_weak(expected.ptr_, value.ptr_, sync); } inline bool compare_exchange_weak(tagged_ptr_type& expected, tagged_ptr_type value, memory_order sync = memory_order_seq_cst) noexcept { return base_type::compare_exchange_weak(expected.ptr_, value.ptr_, sync); } inline bool compare_exchange_weak(tagged_ptr_type& expected, tagged_ptr_type value, memory_order success, memory_order failure) volatile noexcept { return base_type::compare_exchange_weak(expected.ptr_, value.ptr_, success, failure); } inline bool compare_exchange_weak(tagged_ptr_type& expected, tagged_ptr_type value, memory_order success, memory_order failure) noexcept { return base_type::compare_exchange_weak(expected.ptr_, value.ptr_, success, failure); } inline bool compare_exchange_strong(tagged_ptr_type& expected, tagged_ptr_type value, memory_order sync = memory_order_seq_cst) volatile noexcept { return base_type::compare_exchange_strong(expected.ptr_, value.ptr_, sync); } inline bool compare_exchange_strong(tagged_ptr_type& expected, tagged_ptr_type value, memory_order sync = memory_order_seq_cst) noexcept { return base_type::compare_exchange_strong(expected.ptr_, value.ptr_, sync); } inline bool compare_exchange_strong(tagged_ptr_type& expected, tagged_ptr_type value, memory_order success, memory_order failure) volatile noexcept { return base_type::compare_exchange_strong(expected.ptr_, value.ptr_, success, failure); } inline bool compare_exchange_strong(tagged_ptr_type& expected, tagged_ptr_type value, memory_order success, memory_order failure) noexcept { return base_type::compare_exchange_strong(expected.ptr_, value.ptr_, success, failure); } }; } // namespace std #endif <|endoftext|>
<commit_before>#pragma once #include "client_base.hpp" #include "sub_router.hpp" namespace czrpc { namespace client { class sub_client : public client_base { public: sub_client(const sub_client&) = delete; sub_client& operator=(const sub_client&) = delete; sub_client() : heartbeats_work_(heartbeats_ios_), heartbeats_timer_(heartbeats_ios_) { client_type_ = client_type::sub_client; } virtual ~sub_client() { stop(); } virtual void run() override final { client_base::run(); sync_connect(); start_heartbeats_thread(); } virtual void stop() override final { stop_heartbeats_thread(); client_base::stop(); } template<typename Function> void subscribe(const std::string& topic_name, const Function& func) { sync_connect(); client_flag flag{ serialize_mode::serialize, client_type_ }; request_content content; content.protocol = topic_name; content.body = subscribe_topic_flag; call_one_way(flag, content); sub_router::singleton::get()->bind(topic_name, func); } template<typename Function, typename Self> void subscribe(const std::string& topic_name, const Function& func, Self* self) { sync_connect(); client_flag flag{ serialize_mode::serialize, client_type_ }; request_content content; content.protocol = topic_name; content.body = subscribe_topic_flag; call_one_way(flag, content); sub_router::singleton::get()->bind(topic_name, func, self); } template<typename Function> void async_subscribe(const std::string& topic_name, const Function& func) { sync_connect(); client_flag flag{ serialize_mode::serialize, client_type_ }; request_content content; content.protocol = topic_name; content.body = subscribe_topic_flag; async_call_one_way(flag, content); sub_router::singleton::get()->bind(topic_name, func); } template<typename Function, typename Self> void async_subscribe(const std::string& topic_name, const Function& func, Self* self) { sync_connect(); client_flag flag{ serialize_mode::serialize, client_type_ }; request_content content; content.protocol = topic_name; content.body = subscribe_topic_flag; async_call_one_way(flag, content); sub_router::singleton::get()->bind(topic_name, func, self); } template<typename Function> void subscribe_raw(const std::string& topic_name, const Function& func) { sync_connect(); client_flag flag{ serialize_mode::non_serialize, client_type_ }; request_content content; content.protocol = topic_name; content.body = subscribe_topic_flag; call_one_way(flag, content); sub_router::singleton::get()->bind_raw(topic_name, func); } template<typename Function, typename Self> void subscribe_raw(const std::string& topic_name, const Function& func, Self* self) { sync_connect(); client_flag flag{ serialize_mode::non_serialize, client_type_ }; request_content content; content.protocol = topic_name; content.body = subscribe_topic_flag; call_one_way(flag, content); sub_router::singleton::get()->bind_raw(topic_name, func, self); } template<typename Function> void async_subscribe_raw(const std::string& topic_name, const Function& func) { sync_connect(); client_flag flag{ serialize_mode::non_serialize, client_type_ }; request_content content; content.protocol = topic_name; content.body = subscribe_topic_flag; async_call_one_way(flag, content); sub_router::singleton::get()->bind_raw(topic_name, func); } template<typename Function, typename Self> void async_subscribe_raw(const std::string& topic_name, const Function& func, Self* self) { sync_connect(); client_flag flag{ serialize_mode::non_serialize, client_type_ }; request_content content; content.protocol = topic_name; content.body = subscribe_topic_flag; async_call_one_way(flag, content); sub_router::singleton::get()->bind_raw(topic_name, func, self); } void cancel_subscribe(const std::string& topic_name) { sync_connect(); client_flag flag{ serialize_mode::serialize, client_type_ }; request_content content; content.protocol = topic_name; content.body = cancel_subscribe_topic_flag; call_one_way(flag, content); sub_router::singleton::get()->unbind(topic_name); } void cancel_subscribe_raw(const std::string& topic_name) { sync_connect(); client_flag flag{ serialize_mode::serialize, client_type_ }; request_content content; content.protocol = topic_name; content.body = cancel_subscribe_topic_flag; call_one_way(flag, content); sub_router::singleton::get()->unbind_raw(topic_name); } void async_cancel_subscribe(const std::string& topic_name) { sync_connect(); client_flag flag{ serialize_mode::serialize, client_type_ }; request_content content; content.protocol = topic_name; content.body = cancel_subscribe_topic_flag; async_call_one_way(flag, content); sub_router::singleton::get()->unbind(topic_name); } void async_cancel_subscribe_raw(const std::string& topic_name) { sync_connect(); client_flag flag{ serialize_mode::serialize, client_type_ }; request_content content; content.protocol = topic_name; content.body = cancel_subscribe_topic_flag; async_call_one_way(flag, content); sub_router::singleton::get()->unbind_raw(topic_name); } bool is_subscribe(const std::string& topic_name) { return sub_router::singleton::get()->is_bind(topic_name); } bool is_subscribe_raw(const std::string& topic_name) { return sub_router::singleton::get()->is_bind_raw(topic_name); } private: void async_read_head() { boost::asio::async_read(get_socket(), boost::asio::buffer(push_head_buf_), [this](boost::system::error_code ec, std::size_t) { if (!get_socket().is_open()) { log_warn("Socket is not open"); return; } if (ec) { log_warn(ec.message()); return; } if (async_check_head()) { async_read_content(); } else { async_read_head(); } }); } bool async_check_head() { memcpy(&push_head_, push_head_buf_, sizeof(push_head_buf_)); unsigned int len = push_head_.protocol_len + push_head_.message_name_len + push_head_.body_len; return (len > 0 && len < max_buffer_len) ? true : false; } void async_read_content() { content_.clear(); content_.resize(push_head_.protocol_len + push_head_.message_name_len + push_head_.body_len); boost::asio::async_read(get_socket(), boost::asio::buffer(content_), [this](boost::system::error_code ec, std::size_t) { async_read_head(); if (!get_socket().is_open()) { log_warn("Socket is not open"); return; } if (ec) { log_warn(ec.message()); return; } push_content content; content.protocol.assign(&content_[0], push_head_.protocol_len); content.message_name.assign(&content_[push_head_.protocol_len], push_head_.message_name_len); content.body.assign(&content_[push_head_.protocol_len + push_head_.message_name_len], push_head_.body_len); bool ok = sub_router::singleton::get()->route(push_head_.mode, content); if (!ok) { log_warn("Router failed"); return; } }); } void heartbeats_timer() { std::cout << "###################################### heartbeats_timer" << std::endl; try { sync_connect(); client_flag flag{ serialize_mode::serialize, client_type_ }; request_content content; content.protocol = heartbeats_flag; content.body = heartbeats_flag; async_call_one_way(flag, content); } catch (std::exception& e) { log_warn(e.what()); } } void retry_subscribe() { try { for (auto& topic_name : sub_router::singleton::get()->get_all_topic()) { client_flag flag{ serialize_mode::serialize, client_type_ }; request_content content; content.protocol = topic_name; content.body = subscribe_topic_flag; async_call_one_way(flag, content); } } catch (std::exception& e) { log_warn(e.what()); } } void start_heartbeats_thread() { heatbeats_thread_ = std::make_unique<std::thread>([this]{ heartbeats_ios_.run(); }); heartbeats_timer_.bind([this]{ heartbeats_timer(); }); heartbeats_timer_.start(heartbeats_milli); } void stop_heartbeats_thread() { heartbeats_ios_.stop(); if (heatbeats_thread_ != nullptr) { if (heatbeats_thread_->joinable()) { heatbeats_thread_->join(); } } } void sync_connect() { if (try_connect()) { async_read_head(); retry_subscribe(); } } private: char push_head_buf_[push_header_len]; push_header push_head_; std::vector<char> content_; boost::asio::io_service heartbeats_ios_; boost::asio::io_service::work heartbeats_work_; std::unique_ptr<std::thread> heatbeats_thread_; atimer<> heartbeats_timer_; }; } } <commit_msg>update<commit_after>#pragma once #include "client_base.hpp" #include "sub_router.hpp" namespace czrpc { namespace client { class sub_client : public client_base { public: sub_client(const sub_client&) = delete; sub_client& operator=(const sub_client&) = delete; sub_client() : heartbeats_work_(heartbeats_ios_), heartbeats_timer_(heartbeats_ios_) { client_type_ = client_type::sub_client; } virtual ~sub_client() { stop(); } virtual void run() override final { client_base::run(); sync_connect(); start_heartbeats_thread(); } virtual void stop() override final { stop_heartbeats_thread(); client_base::stop(); } template<typename Function> void subscribe(const std::string& topic_name, const Function& func) { sync_connect(); client_flag flag{ serialize_mode::serialize, client_type_ }; request_content content; content.protocol = topic_name; content.body = subscribe_topic_flag; call_one_way(flag, content); sub_router::singleton::get()->bind(topic_name, func); } template<typename Function, typename Self> void subscribe(const std::string& topic_name, const Function& func, Self* self) { sync_connect(); client_flag flag{ serialize_mode::serialize, client_type_ }; request_content content; content.protocol = topic_name; content.body = subscribe_topic_flag; call_one_way(flag, content); sub_router::singleton::get()->bind(topic_name, func, self); } template<typename Function> void async_subscribe(const std::string& topic_name, const Function& func) { sync_connect(); client_flag flag{ serialize_mode::serialize, client_type_ }; request_content content; content.protocol = topic_name; content.body = subscribe_topic_flag; async_call_one_way(flag, content); sub_router::singleton::get()->bind(topic_name, func); } template<typename Function, typename Self> void async_subscribe(const std::string& topic_name, const Function& func, Self* self) { sync_connect(); client_flag flag{ serialize_mode::serialize, client_type_ }; request_content content; content.protocol = topic_name; content.body = subscribe_topic_flag; async_call_one_way(flag, content); sub_router::singleton::get()->bind(topic_name, func, self); } template<typename Function> void subscribe_raw(const std::string& topic_name, const Function& func) { sync_connect(); client_flag flag{ serialize_mode::non_serialize, client_type_ }; request_content content; content.protocol = topic_name; content.body = subscribe_topic_flag; call_one_way(flag, content); sub_router::singleton::get()->bind_raw(topic_name, func); } template<typename Function, typename Self> void subscribe_raw(const std::string& topic_name, const Function& func, Self* self) { sync_connect(); client_flag flag{ serialize_mode::non_serialize, client_type_ }; request_content content; content.protocol = topic_name; content.body = subscribe_topic_flag; call_one_way(flag, content); sub_router::singleton::get()->bind_raw(topic_name, func, self); } template<typename Function> void async_subscribe_raw(const std::string& topic_name, const Function& func) { sync_connect(); client_flag flag{ serialize_mode::non_serialize, client_type_ }; request_content content; content.protocol = topic_name; content.body = subscribe_topic_flag; async_call_one_way(flag, content); sub_router::singleton::get()->bind_raw(topic_name, func); } template<typename Function, typename Self> void async_subscribe_raw(const std::string& topic_name, const Function& func, Self* self) { sync_connect(); client_flag flag{ serialize_mode::non_serialize, client_type_ }; request_content content; content.protocol = topic_name; content.body = subscribe_topic_flag; async_call_one_way(flag, content); sub_router::singleton::get()->bind_raw(topic_name, func, self); } void cancel_subscribe(const std::string& topic_name) { sync_connect(); client_flag flag{ serialize_mode::serialize, client_type_ }; request_content content; content.protocol = topic_name; content.body = cancel_subscribe_topic_flag; call_one_way(flag, content); sub_router::singleton::get()->unbind(topic_name); } void cancel_subscribe_raw(const std::string& topic_name) { sync_connect(); client_flag flag{ serialize_mode::serialize, client_type_ }; request_content content; content.protocol = topic_name; content.body = cancel_subscribe_topic_flag; call_one_way(flag, content); sub_router::singleton::get()->unbind_raw(topic_name); } void async_cancel_subscribe(const std::string& topic_name) { sync_connect(); client_flag flag{ serialize_mode::serialize, client_type_ }; request_content content; content.protocol = topic_name; content.body = cancel_subscribe_topic_flag; async_call_one_way(flag, content); sub_router::singleton::get()->unbind(topic_name); } void async_cancel_subscribe_raw(const std::string& topic_name) { sync_connect(); client_flag flag{ serialize_mode::serialize, client_type_ }; request_content content; content.protocol = topic_name; content.body = cancel_subscribe_topic_flag; async_call_one_way(flag, content); sub_router::singleton::get()->unbind_raw(topic_name); } bool is_subscribe(const std::string& topic_name) { return sub_router::singleton::get()->is_bind(topic_name); } bool is_subscribe_raw(const std::string& topic_name) { return sub_router::singleton::get()->is_bind_raw(topic_name); } private: void async_read_head() { boost::asio::async_read(get_socket(), boost::asio::buffer(push_head_buf_), [this](boost::system::error_code ec, std::size_t) { if (!get_socket().is_open()) { log_warn("Socket is not open"); return; } if (ec) { log_warn(ec.message()); return; } if (async_check_head()) { async_read_content(); } else { async_read_head(); } }); } bool async_check_head() { memcpy(&push_head_, push_head_buf_, sizeof(push_head_buf_)); if (push_head_.protocol_len + push_head_.message_name_len + push_head_.body_len > max_buffer_len) { log_warn("Content len is too big"); return false; } return true; } void async_read_content() { content_.clear(); content_.resize(push_head_.protocol_len + push_head_.message_name_len + push_head_.body_len); boost::asio::async_read(get_socket(), boost::asio::buffer(content_), [this](boost::system::error_code ec, std::size_t) { async_read_head(); if (!get_socket().is_open()) { log_warn("Socket is not open"); return; } if (ec) { log_warn(ec.message()); return; } push_content content; content.protocol.assign(&content_[0], push_head_.protocol_len); content.message_name.assign(&content_[push_head_.protocol_len], push_head_.message_name_len); content.body.assign(&content_[push_head_.protocol_len + push_head_.message_name_len], push_head_.body_len); bool ok = sub_router::singleton::get()->route(push_head_.mode, content); if (!ok) { log_warn("Router failed"); return; } }); } void heartbeats_timer() { std::cout << "###################################### heartbeats_timer" << std::endl; try { sync_connect(); client_flag flag{ serialize_mode::serialize, client_type_ }; request_content content; content.protocol = heartbeats_flag; content.body = heartbeats_flag; async_call_one_way(flag, content); } catch (std::exception& e) { log_warn(e.what()); } } void retry_subscribe() { try { for (auto& topic_name : sub_router::singleton::get()->get_all_topic()) { client_flag flag{ serialize_mode::serialize, client_type_ }; request_content content; content.protocol = topic_name; content.body = subscribe_topic_flag; async_call_one_way(flag, content); } } catch (std::exception& e) { log_warn(e.what()); } } void start_heartbeats_thread() { heatbeats_thread_ = std::make_unique<std::thread>([this]{ heartbeats_ios_.run(); }); heartbeats_timer_.bind([this]{ heartbeats_timer(); }); heartbeats_timer_.start(heartbeats_milli); } void stop_heartbeats_thread() { heartbeats_ios_.stop(); if (heatbeats_thread_ != nullptr) { if (heatbeats_thread_->joinable()) { heatbeats_thread_->join(); } } } void sync_connect() { if (try_connect()) { async_read_head(); retry_subscribe(); } } private: char push_head_buf_[push_header_len]; push_header push_head_; std::vector<char> content_; boost::asio::io_service heartbeats_ios_; boost::asio::io_service::work heartbeats_work_; std::unique_ptr<std::thread> heatbeats_thread_; atimer<> heartbeats_timer_; }; } } <|endoftext|>
<commit_before>// See LICENSE.SiFive for license details. // See LICENSE.Berkeley for license details. #if VM_TRACE #include <memory> #if CY_FST_TRACE #include "verilated_fst_c.h" #else #include "verilated.h" #include "verilated_vcd_c.h" #endif // CY_FST_TRACE #endif // VM_TRACE #include <fesvr/dtm.h> #include <fesvr/tsi.h> #include "remote_bitbang.h" #include <iostream> #include <fcntl.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <getopt.h> // For option parsing, which is split across this file, Verilog, and // FESVR's HTIF, a few external files must be pulled in. The list of // files and what they provide is enumerated: // // $RISCV/include/fesvr/htif.h: // defines: // - HTIF_USAGE_OPTIONS // - HTIF_LONG_OPTIONS_OPTIND // - HTIF_LONG_OPTIONS // $(ROCKETCHIP_DIR)/generated-src(-debug)?/$(CONFIG).plusArgs: // defines: // - PLUSARG_USAGE_OPTIONS // variables: // - static const char * verilog_plusargs extern tsi_t* tsi; extern dtm_t* dtm; extern remote_bitbang_t * jtag; static uint64_t trace_count = 0; bool verbose = false; bool done_reset = false; void handle_sigterm(int sig) { dtm->stop(); } double sc_time_stamp() { return trace_count; } static void usage(const char * program_name) { printf("Usage: %s [EMULATOR OPTION]... [VERILOG PLUSARG]... [HOST OPTION]... BINARY [TARGET OPTION]...\n", program_name); fputs("\ Run a BINARY on the Rocket Chip emulator.\n\ \n\ Mandatory arguments to long options are mandatory for short options too.\n\ \n\ EMULATOR OPTIONS\n\ -c, --cycle-count Print the cycle count before exiting\n\ +cycle-count\n\ -h, --help Display this help and exit\n\ -m, --max-cycles=CYCLES Kill the emulation after CYCLES\n\ +max-cycles=CYCLES\n\ -s, --seed=SEED Use random number seed SEED\n\ -r, --rbb-port=PORT Use PORT for remote bit bang (with OpenOCD and GDB) \n\ If not specified, a random port will be chosen\n\ automatically.\n\ -V, --verbose Enable all Chisel printfs (cycle-by-cycle info)\n\ +verbose\n\ ", stdout); #if VM_TRACE == 0 fputs("\ \n\ EMULATOR DEBUG OPTIONS (only supported in debug build -- try `make debug`)\n", stdout); #endif fputs("\ -v, --vcd=FILE, Write vcd trace to FILE (or '-' for stdout)\n\ -x, --dump-start=CYCLE Start VCD tracing at CYCLE\n\ +dump-start\n\ ", stdout); fputs("\n" PLUSARG_USAGE_OPTIONS, stdout); fputs("\n" HTIF_USAGE_OPTIONS, stdout); printf("\n" "EXAMPLES\n" " - run a bare metal test:\n" " %s $RISCV/riscv64-unknown-elf/share/riscv-tests/isa/rv64ui-p-add\n" " - run a bare metal test showing cycle-by-cycle information:\n" " %s +verbose $RISCV/riscv64-unknown-elf/share/riscv-tests/isa/rv64ui-p-add 2>&1 | spike-dasm\n" #if VM_TRACE " - run a bare metal test to generate a VCD waveform:\n" " %s -v rv64ui-p-add.vcd $RISCV/riscv64-unknown-elf/share/riscv-tests/isa/rv64ui-p-add\n" #endif " - run an ELF (you wrote, called 'hello') using the proxy kernel:\n" " %s pk hello\n", program_name, program_name, program_name #if VM_TRACE , program_name #endif ); } int main(int argc, char** argv) { unsigned random_seed = (unsigned)time(NULL) ^ (unsigned)getpid(); uint64_t max_cycles = -1; int ret = 0; bool print_cycles = false; // Port numbers are 16 bit unsigned integers. uint16_t rbb_port = 0; #if VM_TRACE const char* vcdfile_name = NULL; FILE * vcdfile = NULL; uint64_t start = 0; #endif int verilog_plusargs_legal = 1; opterr = 1; while (1) { static struct option long_options[] = { {"cycle-count", no_argument, 0, 'c' }, {"help", no_argument, 0, 'h' }, {"max-cycles", required_argument, 0, 'm' }, {"seed", required_argument, 0, 's' }, {"rbb-port", required_argument, 0, 'r' }, {"verbose", no_argument, 0, 'V' }, {"permissive", no_argument, 0, 'p' }, {"permissive-off", no_argument, 0, 'o' }, #if VM_TRACE {"vcd", required_argument, 0, 'v' }, {"dump-start", required_argument, 0, 'x' }, #endif HTIF_LONG_OPTIONS }; int option_index = 0; #if VM_TRACE int c = getopt_long(argc, argv, "-chm:s:r:v:Vx:po", long_options, &option_index); #else int c = getopt_long(argc, argv, "-chm:s:r:Vpo", long_options, &option_index); #endif if (c == -1) break; retry: switch (c) { // Process long and short EMULATOR options case '?': usage(argv[0]); return 1; case 'c': print_cycles = true; break; case 'h': usage(argv[0]); return 0; case 'm': max_cycles = atoll(optarg); break; case 's': random_seed = atoi(optarg); break; case 'r': rbb_port = atoi(optarg); break; case 'V': verbose = true; break; case 'p': opterr = 0; break; case 'o': opterr = 1; break; #if VM_TRACE case 'v': { vcdfile_name = optarg; // printf("%s\n", vcdfile_name); vcdfile = strcmp(optarg, "-") == 0 ? stdout : fopen(optarg, "w"); if (!vcdfile) { std::cerr << "Unable to open " << optarg << " for VCD write\n"; return 1; } break; } case 'x': start = atoll(optarg); break; #endif // Process legacy '+' EMULATOR arguments by replacing them with // their getopt equivalents case 1: { std::string arg = optarg; if (arg.substr(0, 1) != "+") { optind--; goto done_processing; } if (arg == "+verbose") c = 'V'; else if (arg.substr(0, 12) == "+max-cycles=") { c = 'm'; optarg = optarg+12; } #if VM_TRACE else if (arg.substr(0, 12) == "+dump-start=") { c = 'x'; optarg = optarg+12; } #endif else if (arg.substr(0, 12) == "+cycle-count") c = 'c'; else if (arg == "+permissive") c = 'p'; else if (arg == "+permissive-off") c = 'o'; // If we don't find a legacy '+' EMULATOR argument, it still could be // a VERILOG_PLUSARG and not an error. else if (verilog_plusargs_legal) { const char ** plusarg = &verilog_plusargs[0]; int legal_verilog_plusarg = 0; while (*plusarg && (legal_verilog_plusarg == 0)){ if (arg.substr(1, strlen(*plusarg)) == *plusarg) { legal_verilog_plusarg = 1; } plusarg ++; } if (!legal_verilog_plusarg) { verilog_plusargs_legal = 0; } else { c = 'P'; } goto retry; } // If we STILL don't find a legacy '+' argument, it still could be // an HTIF (HOST) argument and not an error. If this is the case, then // we're done processing EMULATOR and VERILOG arguments. else { static struct option htif_long_options [] = { HTIF_LONG_OPTIONS }; struct option * htif_option = &htif_long_options[0]; while (htif_option->name) { if (arg.substr(1, strlen(htif_option->name)) == htif_option->name) { optind--; goto done_processing; } htif_option++; } if(opterr) { std::cerr << argv[0] << ": invalid plus-arg (Verilog or HTIF) \"" << arg << "\"\n"; c = '?'; } else { c = 'p'; } } goto retry; } case 'P': break; // Nothing to do here, Verilog PlusArg // Realize that we've hit HTIF (HOST) arguments or error out default: if (c >= HTIF_LONG_OPTIONS_OPTIND) { optind--; goto done_processing; } c = '?'; goto retry; } } done_processing: if (optind == argc) { std::cerr << "No binary specified for emulator\n"; usage(argv[0]); return 1; } int htif_argc = 1 + argc - optind; htif_argv = (char **) malloc((htif_argc) * sizeof (char *)); htif_argv[0] = argv[0]; for (int i = 1; optind < argc;) htif_argv[i++] = argv[optind++]; if (verbose) fprintf(stderr, "using random seed %u\n", random_seed); srand(random_seed); srand48(random_seed); Verilated::randReset(2); Verilated::commandArgs(htif_argc, htif_argv); TEST_HARNESS *tile = new TEST_HARNESS; #if VM_TRACE Verilated::traceEverOn(true); // Verilator must compute traced signals #if CY_FST_TRACE std::unique_ptr<VerilatedFstC> tfp(new VerilatedFstC); #else std::unique_ptr<VerilatedVcdFILE> vcdfd(new VerilatedVcdFILE(vcdfile)); std::unique_ptr<VerilatedVcdC> tfp(new VerilatedVcdC(vcdfd.get())); #endif // CY_FST_TRACE if (vcdfile_name) { tile->trace(tfp.get(), 99); // Trace 99 levels of hierarchy tfp->open(vcdfile_name); } #endif // VM_TRACE // RocketChip currently only supports RBB port 0, so this needs to stay here jtag = new remote_bitbang_t(rbb_port); signal(SIGTERM, handle_sigterm); bool dump; // start reset off low so a rising edge triggers async reset tile->reset = 0; tile->clock = 0; tile->eval(); // reset for several cycles to handle pipelined reset for (int i = 0; i < 100; i++) { tile->reset = 1; tile->clock = 0; tile->eval(); #if VM_TRACE dump = tfp && trace_count >= start; if (dump) tfp->dump(static_cast<vluint64_t>(trace_count * 2)); #endif tile->clock = 1; tile->eval(); #if VM_TRACE if (dump) tfp->dump(static_cast<vluint64_t>(trace_count * 2 + 1)); #endif trace_count ++; } tile->reset = 0; done_reset = true; do { tile->clock = 0; tile->eval(); #if VM_TRACE dump = tfp && trace_count >= start; if (dump) tfp->dump(static_cast<vluint64_t>(trace_count * 2)); #endif tile->clock = 1; tile->eval(); #if VM_TRACE if (dump) tfp->dump(static_cast<vluint64_t>(trace_count * 2 + 1)); #endif trace_count++; } // for verilator multithreading. need to do 1 loop before checking if // tsi exists, since tsi is created by verilated thread on the first // serial_tick. while ((!dtm || !dtm->done()) && (!jtag || !jtag->done()) && (!tsi || !tsi->done()) && !tile->io_success && trace_count < max_cycles); #if VM_TRACE if (tfp) tfp->close(); if (vcdfile) fclose(vcdfile); #endif if (dtm && dtm->exit_code()) { fprintf(stderr, "*** FAILED *** via dtm (code = %d, seed %d) after %ld cycles\n", dtm->exit_code(), random_seed, trace_count); ret = dtm->exit_code(); } else if (tsi && tsi->exit_code()) { fprintf(stderr, "*** FAILED *** (code = %d, seed %d) after %ld cycles\n", tsi->exit_code(), random_seed, trace_count); ret = tsi->exit_code(); } else if (jtag && jtag->exit_code()) { fprintf(stderr, "*** FAILED *** via jtag (code = %d, seed %d) after %ld cycles\n", jtag->exit_code(), random_seed, trace_count); ret = jtag->exit_code(); } else if (trace_count == max_cycles) { fprintf(stderr, "*** FAILED *** via trace_count (timeout, seed %d) after %ld cycles\n", random_seed, trace_count); ret = 2; } else if (verbose || print_cycles) { fprintf(stderr, "*** PASSED *** Completed after %ld cycles\n", trace_count); } if (dtm) delete dtm; if (tsi) delete tsi; if (jtag) delete jtag; if (tile) delete tile; if (htif_argv) free(htif_argv); return ret; } <commit_msg>Remove comments<commit_after>// See LICENSE.SiFive for license details. // See LICENSE.Berkeley for license details. #if VM_TRACE #include <memory> #if CY_FST_TRACE #include "verilated_fst_c.h" #else #include "verilated.h" #include "verilated_vcd_c.h" #endif // CY_FST_TRACE #endif // VM_TRACE #include <fesvr/dtm.h> #include <fesvr/tsi.h> #include "remote_bitbang.h" #include <iostream> #include <fcntl.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <getopt.h> // For option parsing, which is split across this file, Verilog, and // FESVR's HTIF, a few external files must be pulled in. The list of // files and what they provide is enumerated: // // $RISCV/include/fesvr/htif.h: // defines: // - HTIF_USAGE_OPTIONS // - HTIF_LONG_OPTIONS_OPTIND // - HTIF_LONG_OPTIONS // $(ROCKETCHIP_DIR)/generated-src(-debug)?/$(CONFIG).plusArgs: // defines: // - PLUSARG_USAGE_OPTIONS // variables: // - static const char * verilog_plusargs extern tsi_t* tsi; extern dtm_t* dtm; extern remote_bitbang_t * jtag; static uint64_t trace_count = 0; bool verbose = false; bool done_reset = false; void handle_sigterm(int sig) { dtm->stop(); } double sc_time_stamp() { return trace_count; } static void usage(const char * program_name) { printf("Usage: %s [EMULATOR OPTION]... [VERILOG PLUSARG]... [HOST OPTION]... BINARY [TARGET OPTION]...\n", program_name); fputs("\ Run a BINARY on the Rocket Chip emulator.\n\ \n\ Mandatory arguments to long options are mandatory for short options too.\n\ \n\ EMULATOR OPTIONS\n\ -c, --cycle-count Print the cycle count before exiting\n\ +cycle-count\n\ -h, --help Display this help and exit\n\ -m, --max-cycles=CYCLES Kill the emulation after CYCLES\n\ +max-cycles=CYCLES\n\ -s, --seed=SEED Use random number seed SEED\n\ -r, --rbb-port=PORT Use PORT for remote bit bang (with OpenOCD and GDB) \n\ If not specified, a random port will be chosen\n\ automatically.\n\ -V, --verbose Enable all Chisel printfs (cycle-by-cycle info)\n\ +verbose\n\ ", stdout); #if VM_TRACE == 0 fputs("\ \n\ EMULATOR DEBUG OPTIONS (only supported in debug build -- try `make debug`)\n", stdout); #endif fputs("\ -v, --vcd=FILE, Write vcd trace to FILE (or '-' for stdout)\n\ -x, --dump-start=CYCLE Start VCD tracing at CYCLE\n\ +dump-start\n\ ", stdout); fputs("\n" PLUSARG_USAGE_OPTIONS, stdout); fputs("\n" HTIF_USAGE_OPTIONS, stdout); printf("\n" "EXAMPLES\n" " - run a bare metal test:\n" " %s $RISCV/riscv64-unknown-elf/share/riscv-tests/isa/rv64ui-p-add\n" " - run a bare metal test showing cycle-by-cycle information:\n" " %s +verbose $RISCV/riscv64-unknown-elf/share/riscv-tests/isa/rv64ui-p-add 2>&1 | spike-dasm\n" #if VM_TRACE " - run a bare metal test to generate a VCD waveform:\n" " %s -v rv64ui-p-add.vcd $RISCV/riscv64-unknown-elf/share/riscv-tests/isa/rv64ui-p-add\n" #endif " - run an ELF (you wrote, called 'hello') using the proxy kernel:\n" " %s pk hello\n", program_name, program_name, program_name #if VM_TRACE , program_name #endif ); } int main(int argc, char** argv) { unsigned random_seed = (unsigned)time(NULL) ^ (unsigned)getpid(); uint64_t max_cycles = -1; int ret = 0; bool print_cycles = false; // Port numbers are 16 bit unsigned integers. uint16_t rbb_port = 0; #if VM_TRACE const char* vcdfile_name = NULL; FILE * vcdfile = NULL; uint64_t start = 0; #endif int verilog_plusargs_legal = 1; opterr = 1; while (1) { static struct option long_options[] = { {"cycle-count", no_argument, 0, 'c' }, {"help", no_argument, 0, 'h' }, {"max-cycles", required_argument, 0, 'm' }, {"seed", required_argument, 0, 's' }, {"rbb-port", required_argument, 0, 'r' }, {"verbose", no_argument, 0, 'V' }, {"permissive", no_argument, 0, 'p' }, {"permissive-off", no_argument, 0, 'o' }, #if VM_TRACE {"vcd", required_argument, 0, 'v' }, {"dump-start", required_argument, 0, 'x' }, #endif HTIF_LONG_OPTIONS }; int option_index = 0; #if VM_TRACE int c = getopt_long(argc, argv, "-chm:s:r:v:Vx:po", long_options, &option_index); #else int c = getopt_long(argc, argv, "-chm:s:r:Vpo", long_options, &option_index); #endif if (c == -1) break; retry: switch (c) { // Process long and short EMULATOR options case '?': usage(argv[0]); return 1; case 'c': print_cycles = true; break; case 'h': usage(argv[0]); return 0; case 'm': max_cycles = atoll(optarg); break; case 's': random_seed = atoi(optarg); break; case 'r': rbb_port = atoi(optarg); break; case 'V': verbose = true; break; case 'p': opterr = 0; break; case 'o': opterr = 1; break; #if VM_TRACE case 'v': { vcdfile_name = optarg; vcdfile = strcmp(optarg, "-") == 0 ? stdout : fopen(optarg, "w"); if (!vcdfile) { std::cerr << "Unable to open " << optarg << " for VCD write\n"; return 1; } break; } case 'x': start = atoll(optarg); break; #endif // Process legacy '+' EMULATOR arguments by replacing them with // their getopt equivalents case 1: { std::string arg = optarg; if (arg.substr(0, 1) != "+") { optind--; goto done_processing; } if (arg == "+verbose") c = 'V'; else if (arg.substr(0, 12) == "+max-cycles=") { c = 'm'; optarg = optarg+12; } #if VM_TRACE else if (arg.substr(0, 12) == "+dump-start=") { c = 'x'; optarg = optarg+12; } #endif else if (arg.substr(0, 12) == "+cycle-count") c = 'c'; else if (arg == "+permissive") c = 'p'; else if (arg == "+permissive-off") c = 'o'; // If we don't find a legacy '+' EMULATOR argument, it still could be // a VERILOG_PLUSARG and not an error. else if (verilog_plusargs_legal) { const char ** plusarg = &verilog_plusargs[0]; int legal_verilog_plusarg = 0; while (*plusarg && (legal_verilog_plusarg == 0)){ if (arg.substr(1, strlen(*plusarg)) == *plusarg) { legal_verilog_plusarg = 1; } plusarg ++; } if (!legal_verilog_plusarg) { verilog_plusargs_legal = 0; } else { c = 'P'; } goto retry; } // If we STILL don't find a legacy '+' argument, it still could be // an HTIF (HOST) argument and not an error. If this is the case, then // we're done processing EMULATOR and VERILOG arguments. else { static struct option htif_long_options [] = { HTIF_LONG_OPTIONS }; struct option * htif_option = &htif_long_options[0]; while (htif_option->name) { if (arg.substr(1, strlen(htif_option->name)) == htif_option->name) { optind--; goto done_processing; } htif_option++; } if(opterr) { std::cerr << argv[0] << ": invalid plus-arg (Verilog or HTIF) \"" << arg << "\"\n"; c = '?'; } else { c = 'p'; } } goto retry; } case 'P': break; // Nothing to do here, Verilog PlusArg // Realize that we've hit HTIF (HOST) arguments or error out default: if (c >= HTIF_LONG_OPTIONS_OPTIND) { optind--; goto done_processing; } c = '?'; goto retry; } } done_processing: if (optind == argc) { std::cerr << "No binary specified for emulator\n"; usage(argv[0]); return 1; } int htif_argc = 1 + argc - optind; htif_argv = (char **) malloc((htif_argc) * sizeof (char *)); htif_argv[0] = argv[0]; for (int i = 1; optind < argc;) htif_argv[i++] = argv[optind++]; if (verbose) fprintf(stderr, "using random seed %u\n", random_seed); srand(random_seed); srand48(random_seed); Verilated::randReset(2); Verilated::commandArgs(htif_argc, htif_argv); TEST_HARNESS *tile = new TEST_HARNESS; #if VM_TRACE Verilated::traceEverOn(true); // Verilator must compute traced signals #if CY_FST_TRACE std::unique_ptr<VerilatedFstC> tfp(new VerilatedFstC); #else std::unique_ptr<VerilatedVcdFILE> vcdfd(new VerilatedVcdFILE(vcdfile)); std::unique_ptr<VerilatedVcdC> tfp(new VerilatedVcdC(vcdfd.get())); #endif // CY_FST_TRACE if (vcdfile_name) { tile->trace(tfp.get(), 99); // Trace 99 levels of hierarchy tfp->open(vcdfile_name); } #endif // VM_TRACE // RocketChip currently only supports RBB port 0, so this needs to stay here jtag = new remote_bitbang_t(rbb_port); signal(SIGTERM, handle_sigterm); bool dump; // start reset off low so a rising edge triggers async reset tile->reset = 0; tile->clock = 0; tile->eval(); // reset for several cycles to handle pipelined reset for (int i = 0; i < 100; i++) { tile->reset = 1; tile->clock = 0; tile->eval(); #if VM_TRACE dump = tfp && trace_count >= start; if (dump) tfp->dump(static_cast<vluint64_t>(trace_count * 2)); #endif tile->clock = 1; tile->eval(); #if VM_TRACE if (dump) tfp->dump(static_cast<vluint64_t>(trace_count * 2 + 1)); #endif trace_count ++; } tile->reset = 0; done_reset = true; do { tile->clock = 0; tile->eval(); #if VM_TRACE dump = tfp && trace_count >= start; if (dump) tfp->dump(static_cast<vluint64_t>(trace_count * 2)); #endif tile->clock = 1; tile->eval(); #if VM_TRACE if (dump) tfp->dump(static_cast<vluint64_t>(trace_count * 2 + 1)); #endif trace_count++; } // for verilator multithreading. need to do 1 loop before checking if // tsi exists, since tsi is created by verilated thread on the first // serial_tick. while ((!dtm || !dtm->done()) && (!jtag || !jtag->done()) && (!tsi || !tsi->done()) && !tile->io_success && trace_count < max_cycles); #if VM_TRACE if (tfp) tfp->close(); if (vcdfile) fclose(vcdfile); #endif if (dtm && dtm->exit_code()) { fprintf(stderr, "*** FAILED *** via dtm (code = %d, seed %d) after %ld cycles\n", dtm->exit_code(), random_seed, trace_count); ret = dtm->exit_code(); } else if (tsi && tsi->exit_code()) { fprintf(stderr, "*** FAILED *** (code = %d, seed %d) after %ld cycles\n", tsi->exit_code(), random_seed, trace_count); ret = tsi->exit_code(); } else if (jtag && jtag->exit_code()) { fprintf(stderr, "*** FAILED *** via jtag (code = %d, seed %d) after %ld cycles\n", jtag->exit_code(), random_seed, trace_count); ret = jtag->exit_code(); } else if (trace_count == max_cycles) { fprintf(stderr, "*** FAILED *** via trace_count (timeout, seed %d) after %ld cycles\n", random_seed, trace_count); ret = 2; } else if (verbose || print_cycles) { fprintf(stderr, "*** PASSED *** Completed after %ld cycles\n", trace_count); } if (dtm) delete dtm; if (tsi) delete tsi; if (jtag) delete jtag; if (tile) delete tile; if (htif_argv) free(htif_argv); return ret; } <|endoftext|>
<commit_before>#include "inventory.h" #include <facter/facts/collection.hpp> #include <cthun-client/src/log/log.h> #include <valijson/constraints/concrete_constraints.hpp> #include <sstream> LOG_DECLARE_NAMESPACE("agent.inventory"); namespace CthunAgent { namespace Modules { Inventory::Inventory() { // Set the module name name = "inventory"; valijson::constraints::TypeConstraint json_type_string { valijson::constraints::TypeConstraint::kString }; valijson::constraints::TypeConstraint json_type_any { valijson::constraints::TypeConstraint::kAny }; valijson::Schema input_schema; input_schema.addConstraint(json_type_string); valijson::Schema output_schema; output_schema.addConstraint(json_type_any); actions["inventory"] = Action { input_schema, output_schema }; } void Inventory::call_action(std::string action, const Json::Value& input, Json::Value& output) { std::ostringstream fact_stream; try { facter::facts::collection facts; facts.add_default_facts(); facts.write(fact_stream, facter::facts::format::json); } catch (...) { LOG_ERROR("failed to retrieve facts"); Json::Value err_result; err_result["error"] = "Failed to retrieve facts"; output = err_result; return; } LOG_TRACE("facts: %1%", fact_stream.str()); // Parse the facts string (json) and copy into output Json::Reader reader; if (!reader.parse(fact_stream.str(), output)) { // Unexpected LOG_ERROR("json decode of facts failed"); Json::Value err_result; err_result["error"] = "Failed to parse facts"; output = err_result; } } } // namespace Modules } // namespace CthunAgent <commit_msg>(maint) - fix inventory action input/output validation<commit_after>#include "inventory.h" #include <facter/facts/collection.hpp> #include <cthun-client/src/log/log.h> #include <valijson/constraints/concrete_constraints.hpp> #include <sstream> LOG_DECLARE_NAMESPACE("agent.inventory"); namespace CthunAgent { namespace Modules { Inventory::Inventory() { // Set the module name name = "inventory"; valijson::constraints::TypeConstraint json_type_object { valijson::constraints::TypeConstraint::kObject }; valijson::Schema input_schema; input_schema.addConstraint(json_type_object); valijson::Schema output_schema; output_schema.addConstraint(json_type_object); actions["inventory"] = Action { input_schema, output_schema }; } void Inventory::call_action(std::string action, const Json::Value& input, Json::Value& output) { std::ostringstream fact_stream; try { facter::facts::collection facts; facts.add_default_facts(); facts.write(fact_stream, facter::facts::format::json); } catch (...) { LOG_ERROR("failed to retrieve facts"); Json::Value err_result; err_result["error"] = "Failed to retrieve facts"; output = err_result; return; } LOG_TRACE("facts: %1%", fact_stream.str()); // Parse the facts string (json) and copy into output Json::Reader reader; if (!reader.parse(fact_stream.str(), output)) { // Unexpected LOG_ERROR("json decode of facts failed"); Json::Value err_result; err_result["error"] = "Failed to parse facts"; output = err_result; } } } // namespace Modules } // namespace CthunAgent <|endoftext|>
<commit_before>#include "cuda_runtime.h" #include "device_launch_parameters.h" #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #include <imgui.h> #include "aten.h" #include "atenscene.h" #include "idaten.h" #include "scenedefs.h" #define MULTI_GPU_SVGF static int WIDTH = 1280; static int HEIGHT = 720; static const char* TITLE = "multigpu"; #ifdef ENABLE_OMP static uint32_t g_threadnum = 8; #else static uint32_t g_threadnum = 1; #endif static aten::PinholeCamera g_camera; static bool g_isCameraDirty = false; static aten::AcceleratedScene<aten::GPUBvh> g_scene; #ifdef MULTI_GPU_SVGF static idaten::GpuProxy<idaten::SVGFPathTracingMultiGPU> g_tracer[2]; static aten::TAA g_taa; static aten::FBO g_fbo; static aten::RasterizeRenderer g_rasterizer; #else static idaten::GpuProxy<idaten::PathTracingMultiGPU> g_tracer[2]; #endif static const idaten::TileDomain g_tileDomain[2] = { { 0, 0, WIDTH, HEIGHT / 2 }, { 0, HEIGHT / 2, WIDTH, HEIGHT / 2 }, }; static aten::visualizer* g_visualizer = nullptr; static bool g_willShowGUI = true; static bool g_willTakeScreenShot = false; static int g_cntScreenShot = 0; static int g_maxSamples = 1; static int g_maxBounce = 5; void onRun(aten::window* window) { if (g_isCameraDirty) { g_camera.update(); auto camparam = g_camera.param(); camparam.znear = real(0.1); camparam.zfar = real(10000.0); for (int i = 0; i < AT_COUNTOF(g_tracer); i++) { g_tracer[i].getRenderer().updateCamera(camparam); } g_isCameraDirty = false; g_visualizer->clear(); } aten::timer timer; timer.begin(); #ifdef MULTI_GPU_SVGF g_rasterizer.draw( g_tracer[0].getRenderer().frame(), &g_scene, &g_camera, &g_fbo); #endif for (int i = 0; i < AT_COUNTOF(g_tracer); i++) { g_tracer[i].render( g_tileDomain[i], g_maxSamples, g_maxBounce); } for (int i = 1; i < AT_COUNTOF(g_tracer); i++) { g_tracer[0].gather(g_tracer[i]); } g_tracer[0].postRender(WIDTH, HEIGHT); auto cudaelapsed = timer.end(); g_visualizer->render(false); if (g_willTakeScreenShot) { static char buffer[1024]; ::sprintf(buffer, "sc_%d.png\0", g_cntScreenShot); g_visualizer->takeScreenshot(buffer); g_willTakeScreenShot = false; g_cntScreenShot++; AT_PRINTF("Take Screenshot[%s]\n", buffer); } if (g_willShowGUI) { ImGui::Text("%.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); ImGui::Text("cuda : %.3f ms", cudaelapsed); ImGui::Text("%.3f Mrays/sec", (WIDTH * HEIGHT * g_maxSamples) / real(1000 * 1000) * (real(1000) / cudaelapsed)); window->drawImGui(); } } void onClose() { } bool g_isMouseLBtnDown = false; bool g_isMouseRBtnDown = false; int g_prevX = 0; int g_prevY = 0; void onMouseBtn(bool left, bool press, int x, int y) { g_isMouseLBtnDown = false; g_isMouseRBtnDown = false; if (press) { g_prevX = x; g_prevY = y; g_isMouseLBtnDown = left; g_isMouseRBtnDown = !left; } } void onMouseMove(int x, int y) { if (g_isMouseLBtnDown) { aten::CameraOperator::rotate( g_camera, WIDTH, HEIGHT, g_prevX, g_prevY, x, y); g_isCameraDirty = true; } else if (g_isMouseRBtnDown) { aten::CameraOperator::move( g_camera, g_prevX, g_prevY, x, y, real(0.001)); g_isCameraDirty = true; } g_prevX = x; g_prevY = y; } void onMouseWheel(int delta) { aten::CameraOperator::dolly(g_camera, delta * real(0.1)); g_isCameraDirty = true; } void onKey(bool press, aten::Key key) { static const real offset = real(0.1); if (press) { if (key == aten::Key::Key_F1) { g_willShowGUI = !g_willShowGUI; return; } else if (key == aten::Key::Key_F2) { g_willTakeScreenShot = true; return; } } if (press) { switch (key) { case aten::Key::Key_W: case aten::Key::Key_UP: aten::CameraOperator::moveForward(g_camera, offset); break; case aten::Key::Key_S: case aten::Key::Key_DOWN: aten::CameraOperator::moveForward(g_camera, -offset); break; case aten::Key::Key_D: case aten::Key::Key_RIGHT: aten::CameraOperator::moveRight(g_camera, offset); break; case aten::Key::Key_A: case aten::Key::Key_LEFT: aten::CameraOperator::moveRight(g_camera, -offset); break; case aten::Key::Key_Z: aten::CameraOperator::moveUp(g_camera, offset); break; case aten::Key::Key_X: aten::CameraOperator::moveUp(g_camera, -offset); break; case aten::Key::Key_R: { aten::vec3 pos, at; real vfov; Scene::getCameraPosAndAt(pos, at, vfov); g_camera.init( pos, at, aten::vec3(0, 1, 0), vfov, WIDTH, HEIGHT); } break; default: break; } g_isCameraDirty = true; } } int main() { idaten::initCuda(); aten::timer::init(); aten::OMPUtil::setThreadNum(g_threadnum); aten::initSampler(WIDTH, HEIGHT); aten::window::init( WIDTH, HEIGHT, TITLE, onRun, onClose, onMouseBtn, onMouseMove, onMouseWheel, onKey); g_visualizer = aten::visualizer::init(WIDTH, HEIGHT); #ifdef MULTI_GPU_SVGF g_taa.init( WIDTH, HEIGHT, "../shader/fullscreen_vs.glsl", "../shader/taa_fs.glsl", "../shader/fullscreen_vs.glsl", "../shader/taa_final_fs.glsl"); g_visualizer->addPostProc(&g_taa); g_rasterizer.init( WIDTH, HEIGHT, "../shader/ssrt_vs.glsl", "../shader/ssrt_gs.glsl", "../shader/ssrt_fs.glsl"); g_fbo.asMulti(2); g_fbo.init( WIDTH, HEIGHT, aten::PixelFormat::rgba32f, true); g_taa.setMotionDepthBufferHandle(g_fbo.getTexHandle(1)); #endif aten::GammaCorrection gamma; gamma.init( WIDTH, HEIGHT, "../shader/fullscreen_vs.glsl", "../shader/gamma_fs.glsl"); g_visualizer->addPostProc(&gamma); aten::vec3 pos, at; real vfov; Scene::getCameraPosAndAt(pos, at, vfov); g_camera.init( pos, at, aten::vec3(0, 1, 0), vfov, WIDTH, HEIGHT); Scene::makeScene(&g_scene); g_scene.build(); auto envmap = aten::ImageLoader::load("../../asset/envmap/studio015.hdr"); aten::envmap bg; bg.init(envmap); aten::ImageBasedLight ibl(&bg); g_scene.addImageBasedLight(&ibl); std::vector<aten::GeomParameter> shapeparams; std::vector<aten::PrimitiveParamter> primparams; std::vector<aten::LightParameter> lightparams; std::vector<aten::MaterialParameter> mtrlparms; std::vector<aten::vertex> vtxparams; aten::DataCollector::collect( shapeparams, primparams, lightparams, mtrlparms, vtxparams); const auto& nodes = g_scene.getAccel()->getNodes(); const auto& mtxs = g_scene.getAccel()->getMatrices(); std::vector<idaten::TextureResource> tex; { auto texs = aten::texture::getTextures(); for (const auto t : texs) { tex.push_back( idaten::TextureResource(t->colors(), t->width(), t->height())); } } for (auto& l : lightparams) { if (l.type == aten::LightType::IBL) { l.envmap.idx = envmap->id(); } } auto camparam = g_camera.param(); camparam.znear = real(0.1); camparam.zfar = real(10000.0); g_tracer[0].init(0); #if 1 g_tracer[1].init(1); // Set P2P access between GPUs. g_tracer[0].setPeerAccess(1); g_tracer[1].setPeerAccess(0); #endif for (int i = 0; i < AT_COUNTOF(g_tracer); i++) { const auto& tileDomain = g_tileDomain[i]; g_tracer[i].setCurrent(); g_tracer[i].getRenderer().getCompaction().init( tileDomain.w * tileDomain.h, 1024); int w = i == 0 ? WIDTH : tileDomain.w; int h = i == 0 ? HEIGHT : tileDomain.h; g_tracer[i].getRenderer().update( aten::visualizer::getTexHandle(), w, h, camparam, shapeparams, mtrlparms, lightparams, nodes, primparams, vtxparams, mtxs, tex, idaten::EnvmapResource(envmap->id(), ibl.getAvgIlluminace(), real(4))); #ifdef MULTI_GPU_SVGF g_tracer[i].getRenderer().setGBuffer( g_fbo.getTexHandle(0), g_fbo.getTexHandle(1)); #endif } aten::window::run(); aten::window::terminate(); } <commit_msg>Implement for multi gpu.<commit_after>#include "cuda_runtime.h" #include "device_launch_parameters.h" #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #include <imgui.h> #include "aten.h" #include "atenscene.h" #include "idaten.h" #include "scenedefs.h" #define MULTI_GPU_SVGF #define GPU_NUM (2) static int WIDTH = 1280; static int HEIGHT = 720; static const char* TITLE = "multigpu"; #ifdef ENABLE_OMP static uint32_t g_threadnum = 8; #else static uint32_t g_threadnum = 1; #endif static aten::PinholeCamera g_camera; static bool g_isCameraDirty = false; static aten::AcceleratedScene<aten::GPUBvh> g_scene; #ifdef MULTI_GPU_SVGF static idaten::GpuProxy<idaten::SVGFPathTracingMultiGPU> g_tracer[GPU_NUM]; static aten::TAA g_taa; static aten::FBO g_fbo; static aten::RasterizeRenderer g_rasterizer; using GpuProxy = idaten::GpuProxy<idaten::SVGFPathTracingMultiGPU>; #else static idaten::GpuProxy<idaten::PathTracingMultiGPU> g_tracer[GPU_NUM]; using GpuProxy = idaten::GpuProxy<idaten::PathTracingMultiGPU>; #endif #if (GPU_NUM == 4) static const idaten::TileDomain g_tileDomain[4] = { { 0, 0 * HEIGHT / 4, WIDTH, HEIGHT / 4 }, { 0, 1 * HEIGHT / 4, WIDTH, HEIGHT / 4 }, { 0, 2 * HEIGHT / 4, WIDTH, HEIGHT / 4 }, { 0, 3 * HEIGHT / 4, WIDTH, HEIGHT / 4 }, }; #else static const idaten::TileDomain g_tileDomain[2] = { { 0, 0 * HEIGHT / 2, WIDTH, HEIGHT / 2 }, { 0, 1 * HEIGHT / 2, WIDTH, HEIGHT / 2 }, }; #endif static aten::visualizer* g_visualizer = nullptr; static bool g_willShowGUI = true; static bool g_willTakeScreenShot = false; static int g_cntScreenShot = 0; static int g_maxSamples = 1; static int g_maxBounce = 5; void onRun(aten::window* window) { if (g_isCameraDirty) { g_camera.update(); auto camparam = g_camera.param(); camparam.znear = real(0.1); camparam.zfar = real(10000.0); for (int i = 0; i < AT_COUNTOF(g_tracer); i++) { g_tracer[i].getRenderer().updateCamera(camparam); } g_isCameraDirty = false; g_visualizer->clear(); } aten::timer timer; timer.begin(); #ifdef MULTI_GPU_SVGF g_rasterizer.draw( g_tracer[0].getRenderer().frame(), &g_scene, &g_camera, &g_fbo); #endif for (int i = 0; i < AT_COUNTOF(g_tracer); i++) { g_tracer[i].render( g_tileDomain[i], g_maxSamples, g_maxBounce); } #if (GPU_NUM == 4) GpuProxy::swapCopy(g_tracer, AT_COUNTOF(g_tracer)); #else g_tracer[0].copyP2P(g_tracer[1]); #endif g_tracer[0].postRender(WIDTH, HEIGHT); auto cudaelapsed = timer.end(); g_visualizer->render(false); if (g_willTakeScreenShot) { static char buffer[1024]; ::sprintf(buffer, "sc_%d.png\0", g_cntScreenShot); g_visualizer->takeScreenshot(buffer); g_willTakeScreenShot = false; g_cntScreenShot++; AT_PRINTF("Take Screenshot[%s]\n", buffer); } if (g_willShowGUI) { ImGui::Text("%.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); ImGui::Text("cuda : %.3f ms", cudaelapsed); ImGui::Text("%.3f Mrays/sec", (WIDTH * HEIGHT * g_maxSamples) / real(1000 * 1000) * (real(1000) / cudaelapsed)); window->drawImGui(); } } void onClose() { } bool g_isMouseLBtnDown = false; bool g_isMouseRBtnDown = false; int g_prevX = 0; int g_prevY = 0; void onMouseBtn(bool left, bool press, int x, int y) { g_isMouseLBtnDown = false; g_isMouseRBtnDown = false; if (press) { g_prevX = x; g_prevY = y; g_isMouseLBtnDown = left; g_isMouseRBtnDown = !left; } } void onMouseMove(int x, int y) { if (g_isMouseLBtnDown) { aten::CameraOperator::rotate( g_camera, WIDTH, HEIGHT, g_prevX, g_prevY, x, y); g_isCameraDirty = true; } else if (g_isMouseRBtnDown) { aten::CameraOperator::move( g_camera, g_prevX, g_prevY, x, y, real(0.001)); g_isCameraDirty = true; } g_prevX = x; g_prevY = y; } void onMouseWheel(int delta) { aten::CameraOperator::dolly(g_camera, delta * real(0.1)); g_isCameraDirty = true; } void onKey(bool press, aten::Key key) { static const real offset = real(0.1); if (press) { if (key == aten::Key::Key_F1) { g_willShowGUI = !g_willShowGUI; return; } else if (key == aten::Key::Key_F2) { g_willTakeScreenShot = true; return; } } if (press) { switch (key) { case aten::Key::Key_W: case aten::Key::Key_UP: aten::CameraOperator::moveForward(g_camera, offset); break; case aten::Key::Key_S: case aten::Key::Key_DOWN: aten::CameraOperator::moveForward(g_camera, -offset); break; case aten::Key::Key_D: case aten::Key::Key_RIGHT: aten::CameraOperator::moveRight(g_camera, offset); break; case aten::Key::Key_A: case aten::Key::Key_LEFT: aten::CameraOperator::moveRight(g_camera, -offset); break; case aten::Key::Key_Z: aten::CameraOperator::moveUp(g_camera, offset); break; case aten::Key::Key_X: aten::CameraOperator::moveUp(g_camera, -offset); break; case aten::Key::Key_R: { aten::vec3 pos, at; real vfov; Scene::getCameraPosAndAt(pos, at, vfov); g_camera.init( pos, at, aten::vec3(0, 1, 0), vfov, WIDTH, HEIGHT); } break; default: break; } g_isCameraDirty = true; } } int main() { idaten::initCuda(); aten::timer::init(); aten::OMPUtil::setThreadNum(g_threadnum); aten::initSampler(WIDTH, HEIGHT); auto window = aten::window::init( WIDTH, HEIGHT, TITLE, onRun, onClose, onMouseBtn, onMouseMove, onMouseWheel, onKey); window->enableVSync(false); g_visualizer = aten::visualizer::init(WIDTH, HEIGHT); #ifdef MULTI_GPU_SVGF g_taa.init( WIDTH, HEIGHT, "../shader/fullscreen_vs.glsl", "../shader/taa_fs.glsl", "../shader/fullscreen_vs.glsl", "../shader/taa_final_fs.glsl"); g_visualizer->addPostProc(&g_taa); g_rasterizer.init( WIDTH, HEIGHT, "../shader/ssrt_vs.glsl", "../shader/ssrt_gs.glsl", "../shader/ssrt_fs.glsl"); g_fbo.asMulti(2); g_fbo.init( WIDTH, HEIGHT, aten::PixelFormat::rgba32f, true); g_taa.setMotionDepthBufferHandle(g_fbo.getTexHandle(1)); #endif aten::GammaCorrection gamma; gamma.init( WIDTH, HEIGHT, "../shader/fullscreen_vs.glsl", "../shader/gamma_fs.glsl"); g_visualizer->addPostProc(&gamma); aten::vec3 pos, at; real vfov; Scene::getCameraPosAndAt(pos, at, vfov); g_camera.init( pos, at, aten::vec3(0, 1, 0), vfov, WIDTH, HEIGHT); Scene::makeScene(&g_scene); g_scene.build(); auto envmap = aten::ImageLoader::load("../../asset/envmap/studio015.hdr"); aten::envmap bg; bg.init(envmap); aten::ImageBasedLight ibl(&bg); g_scene.addImageBasedLight(&ibl); std::vector<aten::GeomParameter> shapeparams; std::vector<aten::PrimitiveParamter> primparams; std::vector<aten::LightParameter> lightparams; std::vector<aten::MaterialParameter> mtrlparms; std::vector<aten::vertex> vtxparams; aten::DataCollector::collect( shapeparams, primparams, lightparams, mtrlparms, vtxparams); const auto& nodes = g_scene.getAccel()->getNodes(); const auto& mtxs = g_scene.getAccel()->getMatrices(); std::vector<idaten::TextureResource> tex; { auto texs = aten::texture::getTextures(); for (const auto t : texs) { tex.push_back( idaten::TextureResource(t->colors(), t->width(), t->height())); } } for (auto& l : lightparams) { if (l.type == aten::LightType::IBL) { l.envmap.idx = envmap->id(); } } auto camparam = g_camera.param(); camparam.znear = real(0.1); camparam.zfar = real(10000.0); g_tracer[0].init(0); g_tracer[1].init(1); // Set P2P access between GPUs. g_tracer[0].setPeerAccess(1); g_tracer[1].setPeerAccess(0); #if (GPU_NUM == 4) g_tracer[2].init(2); g_tracer[3].init(3); g_tracer[2].setPeerAccess(3); g_tracer[3].setPeerAccess(2); #endif for (int i = 0; i < AT_COUNTOF(g_tracer); i++) { const auto& tileDomain = g_tileDomain[i]; g_tracer[i].setCurrent(); g_tracer[i].getRenderer().getCompaction().init( tileDomain.w * tileDomain.h, 1024); int w = i == 0 ? WIDTH : tileDomain.w; int h = i == 0 ? HEIGHT : tileDomain.h; h = i == 2 ? HEIGHT / 2 : h; g_tracer[i].getRenderer().update( aten::visualizer::getTexHandle(), w, h, camparam, shapeparams, mtrlparms, lightparams, nodes, primparams, vtxparams, mtxs, tex, idaten::EnvmapResource(envmap->id(), ibl.getAvgIlluminace(), real(4))); #ifdef MULTI_GPU_SVGF g_tracer[i].getRenderer().setGBuffer( g_fbo.getTexHandle(0), g_fbo.getTexHandle(1)); #endif } aten::window::run(); aten::window::terminate(); } <|endoftext|>
<commit_before>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/framework/ir/embedding_fc_lstm_fuse_pass.h" #include <algorithm> #include <string> #include "paddle/fluid/framework/lod_tensor.h" #include "paddle/fluid/operators/math/blas.h" #include "paddle/fluid/operators/math/cpu_vec.h" #include "paddle/fluid/operators/math/fc_compute.h" #include "paddle/fluid/platform/cpu_info.h" namespace paddle { namespace framework { namespace ir { static int BuildFusion(Graph* graph, const std::string& name_scope, Scope* scope, bool with_fc_bias) { GraphPatternDetector gpd; auto* pattern = gpd.mutable_pattern(); // Build pattern PDNode* x = pattern->NewNode(patterns::PDNodeName(name_scope, "x")) ->assert_is_op_input("lookup_table") ->assert_var_not_persistable(); patterns::Embedding embedding_pattern(pattern, name_scope); // TODO(jczaja): Intermediate can only be for val that are not used anywhere // but lookup table output may go into other LSTM (for reverse // direction) auto* embedding_out = embedding_pattern(x); patterns::FC fc_pattern(pattern, name_scope); // fc_out is a tmp var, will be removed after fuse, so marked as intermediate. auto* fc_out = fc_pattern(embedding_out, with_fc_bias)->AsIntermediate(); patterns::LSTM lstm_pattern(pattern, name_scope); lstm_pattern(fc_out); // Create New OpDesc auto embedding_lstm_creator = [&](Node* embedding, Node* W, Node* lstm, Node* input, Node* weight_x, Node* weight_h, Node* bias, Node* hidden, Node* cell, Node* xx, Node* fc_bias) { OpDesc op_desc; op_desc.SetType("fused_embedding_fc_lstm"); #define SET_IN(Key, node__) op_desc.SetInput(#Key, {node__->Name()}); SET_IN(Ids, input); SET_IN(WeightH, weight_h); // Neet to have this passed as We need Wc data for peephole connections SET_IN(Bias, bias); #undef SET_IN // Multiply embeddings with Weights PADDLE_ENFORCE(scope); const std::string& embeddings = patterns::UniqueKey("Embeddings"); auto* embeddings_var = scope->Var(embeddings); PADDLE_ENFORCE(embeddings_var); auto* embeddings_tensor = embeddings_var->GetMutable<framework::LoDTensor>(); // Get WeightX size: [single_embedding, fc_size] // and embedding size: [dict_size, single_embedding] // and create new size of embeddings eg. [dict_size , hidden_size] auto* embedding_var = scope->FindVar(W->Name()); PADDLE_ENFORCE(embedding_var); const auto& embedding_tensor = embedding_var->Get<framework::LoDTensor>(); const auto& weightx_tensor = scope->FindVar(weight_x->Name())->Get<framework::LoDTensor>(); embeddings_tensor->Resize( {embedding_tensor.dims()[0], weightx_tensor.dims()[1]}); // Multiplie embeddings via WeightsX and add bias auto embedding_data = embedding_tensor.data<float>(); auto weightx_data = weightx_tensor.data<float>(); auto embeddings_data = embeddings_tensor->mutable_data<float>(platform::CPUPlace()); // Adding biases to GEMM result to be auto* lstm_bias_var = scope->FindVar(bias->Name()); PADDLE_ENFORCE(lstm_bias_var); const auto& lstm_bias_tensor = lstm_bias_var->Get<framework::LoDTensor>(); auto alpha = 1.0f; auto beta = 1.0f; int m = embedding_tensor.dims()[0]; int n = weightx_tensor.dims()[1]; int k = embedding_tensor.dims()[1]; // Copy only gate biases values (only actual bias data, not peephole // weights) std::vector<float> combined_biases; combined_biases.reserve(n); std::copy_n(lstm_bias_tensor.data<float>(), n, std::back_inserter(combined_biases)); if (with_fc_bias) { // Add FC-bias with LSTM-bias (into GEMM result to be) auto* fc_bias_var = scope->FindVar(fc_bias->Name()); const auto& fc_bias_tensor = fc_bias_var->Get<framework::LoDTensor>(); for (int i = 0; i < fc_bias_tensor.numel(); i++) { combined_biases[i] += fc_bias_tensor.data<float>()[i]; } } // broadcast biases std::vector<float> ones(m, 1.0f); paddle::operators::math::CBlas<float>::GEMM( CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, 1, alpha, &ones[0], 1, &combined_biases[0], n, 0.0f, embeddings_data, n); // Wx*embeddings paddle::operators::math::CBlas<float>::GEMM( CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, alpha, embedding_data, k, weightx_data, n, beta, embeddings_data, n); op_desc.SetInput("Embeddings", {embeddings}); // Create temp variables. const std::string BatchedInput = patterns::UniqueKey("BatchedInput"); const std::string BatchedCellPreAct = patterns::UniqueKey("BatchedCellPreAct"); const std::string BatchedGate = patterns::UniqueKey("BatchedGate"); scope->Var(BatchedInput)->GetMutable<framework::LoDTensor>(); scope->Var(BatchedCellPreAct)->GetMutable<framework::LoDTensor>(); scope->Var(BatchedGate)->GetMutable<framework::LoDTensor>(); op_desc.SetInput("H0", {}); op_desc.SetInput("C0", {}); op_desc.SetOutput("Hidden", {hidden->Name()}); op_desc.SetOutput("Cell", {cell->Name()}); op_desc.SetOutput("XX", {xx->Name()}); op_desc.SetOutput("BatchedGate", {BatchedGate}); op_desc.SetOutput("BatchCellPreAct", {BatchedCellPreAct}); op_desc.SetOutput("BatchedInput", {BatchedInput}); op_desc.SetAttr("is_reverse", lstm->Op()->GetAttr("is_reverse")); op_desc.SetAttr("use_peepholes", lstm->Op()->GetAttr("use_peepholes")); // TODO(TJ): get from attr op_desc.SetAttr("use_seq", true); PADDLE_ENFORCE(graph->Has(kParamScopeAttr)); auto* scope = graph->Get<Scope*>(kParamScopeAttr); #define OP_SET_OUT(x) \ const std::string x = patterns::UniqueKey(#x); \ op_desc.SetOutput(#x, {x}); \ scope->Var(x)->GetMutable<LoDTensor>() OP_SET_OUT(BatchedCell); OP_SET_OUT(BatchedHidden); OP_SET_OUT(ReorderedH0); OP_SET_OUT(ReorderedC0); #undef OP_SET_OUT auto* op = graph->CreateOpNode(&op_desc); IR_NODE_LINK_TO(input, op); IR_NODE_LINK_TO(weight_x, op); IR_NODE_LINK_TO(weight_h, op); IR_NODE_LINK_TO(bias, op); IR_NODE_LINK_TO(op, hidden); return op; }; int fusion_count{0}; auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph, Graph* g) { GET_IR_NODE_FROM_SUBGRAPH(lstm, lstm, lstm_pattern); GET_IR_NODE_FROM_SUBGRAPH(Weight, Weight, lstm_pattern); GET_IR_NODE_FROM_SUBGRAPH(Bias, Bias, lstm_pattern); GET_IR_NODE_FROM_SUBGRAPH(Cell, Cell, lstm_pattern); GET_IR_NODE_FROM_SUBGRAPH(Hidden, Hidden, lstm_pattern); GET_IR_NODE_FROM_SUBGRAPH(lookup_table, lookup_table, embedding_pattern); GET_IR_NODE_FROM_SUBGRAPH(W, W, embedding_pattern); GET_IR_NODE_FROM_SUBGRAPH(w, w, fc_pattern); GET_IR_NODE_FROM_SUBGRAPH(mul, mul, fc_pattern); // TODO(jczaja): Add support for is_sparse / is_distributed auto is_sparse = boost::get<bool>(lookup_table->Op()->GetAttr("is_sparse")); auto is_distributed = boost::get<bool>(lookup_table->Op()->GetAttr("is_distributed")); if (is_sparse == true || is_distributed == true) { return; } if (with_fc_bias) { GET_IR_NODE_FROM_SUBGRAPH(fc_out, Out, fc_pattern); GET_IR_NODE_FROM_SUBGRAPH(fc_bias, bias, fc_pattern); GET_IR_NODE_FROM_SUBGRAPH(elementwise_add, elementwise_add, fc_pattern); embedding_lstm_creator(lookup_table, W, lstm, subgraph.at(x), w, Weight, Bias, Hidden, Cell, fc_out, fc_bias); // Remove unneeded nodes. // TODO(jczaja): Proper removing of loopup table std::unordered_set<const Node*> marked_nodes( //{lookup_table, mul, lstm, elementwise_add, fc_bias, W}); {mul, lstm, elementwise_add, fc_bias}); GraphSafeRemoveNodes(graph, marked_nodes); } else { GET_IR_NODE_FROM_SUBGRAPH(fc_out, mul_out, fc_pattern); embedding_lstm_creator(lookup_table, W, lstm, subgraph.at(x), w, Weight, Bias, Hidden, Cell, fc_out, nullptr); // Remove unneeded nodes. // TODO(jczaja): Proper removing of loopup table // std::unordered_set<const Node*> marked_nodes({lookup_table, W, mul, // lstm}); std::unordered_set<const Node*> marked_nodes({mul, lstm}); GraphSafeRemoveNodes(graph, marked_nodes); } ++fusion_count; }; gpd(graph, handler); return fusion_count; } std::unique_ptr<ir::Graph> EmbeddingFCLSTMFusePass::ApplyImpl( std::unique_ptr<ir::Graph> graph) const { FusePassBase::Init(name_scope_, graph.get()); int fusion_count = BuildFusion(graph.get(), name_scope_, param_scope(), true /*with_fc_bias*/); AddStatis(fusion_count); return graph; } } // namespace ir } // namespace framework } // namespace paddle REGISTER_PASS(embedding_fc_lstm_fuse_pass, paddle::framework::ir::EmbeddingFCLSTMFusePass); <commit_msg>- Fix to comment<commit_after>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/framework/ir/embedding_fc_lstm_fuse_pass.h" #include <algorithm> #include <string> #include "paddle/fluid/framework/lod_tensor.h" #include "paddle/fluid/operators/math/blas.h" #include "paddle/fluid/operators/math/cpu_vec.h" #include "paddle/fluid/operators/math/fc_compute.h" #include "paddle/fluid/platform/cpu_info.h" namespace paddle { namespace framework { namespace ir { static int BuildFusion(Graph* graph, const std::string& name_scope, Scope* scope, bool with_fc_bias) { GraphPatternDetector gpd; auto* pattern = gpd.mutable_pattern(); // Build pattern PDNode* x = pattern->NewNode(patterns::PDNodeName(name_scope, "x")) ->assert_is_op_input("lookup_table") ->assert_var_not_persistable(); patterns::Embedding embedding_pattern(pattern, name_scope); // TODO(jczaja): Intermediate can only be for val that are not used anywhere // but lookup table output may go into other LSTM (for reverse // direction) auto* embedding_out = embedding_pattern(x); patterns::FC fc_pattern(pattern, name_scope); // fc_out is a tmp var, will be removed after fuse, so marked as intermediate. auto* fc_out = fc_pattern(embedding_out, with_fc_bias)->AsIntermediate(); patterns::LSTM lstm_pattern(pattern, name_scope); lstm_pattern(fc_out); // Create New OpDesc auto embedding_lstm_creator = [&](Node* embedding, Node* W, Node* lstm, Node* input, Node* weight_x, Node* weight_h, Node* bias, Node* hidden, Node* cell, Node* xx, Node* fc_bias) { OpDesc op_desc; op_desc.SetType("fused_embedding_fc_lstm"); #define SET_IN(Key, node__) op_desc.SetInput(#Key, {node__->Name()}); SET_IN(Ids, input); SET_IN(WeightH, weight_h); // Neet to have this passed as We need Wc data for peephole connections SET_IN(Bias, bias); #undef SET_IN // Multiply embeddings with Weights PADDLE_ENFORCE(scope); const std::string& embeddings = patterns::UniqueKey("Embeddings"); auto* embeddings_var = scope->Var(embeddings); PADDLE_ENFORCE(embeddings_var); auto* embeddings_tensor = embeddings_var->GetMutable<framework::LoDTensor>(); // Get WeightX size: [single_embedding, fc_size] // and embedding size: [dict_size, single_embedding] // and create new size of embeddings eg. [dict_size , hidden_size] auto* embedding_var = scope->FindVar(W->Name()); PADDLE_ENFORCE(embedding_var); const auto& embedding_tensor = embedding_var->Get<framework::LoDTensor>(); const auto& weightx_tensor = scope->FindVar(weight_x->Name())->Get<framework::LoDTensor>(); embeddings_tensor->Resize( {embedding_tensor.dims()[0], weightx_tensor.dims()[1]}); // Multiplie embeddings via WeightsX and add bias auto embedding_data = embedding_tensor.data<float>(); auto weightx_data = weightx_tensor.data<float>(); auto embeddings_data = embeddings_tensor->mutable_data<float>(platform::CPUPlace()); // Adding biases to GEMM result to be auto* lstm_bias_var = scope->FindVar(bias->Name()); PADDLE_ENFORCE(lstm_bias_var); const auto& lstm_bias_tensor = lstm_bias_var->Get<framework::LoDTensor>(); auto alpha = 1.0f; auto beta = 1.0f; int m = embedding_tensor.dims()[0]; int n = weightx_tensor.dims()[1]; int k = embedding_tensor.dims()[1]; // Copy only gate biases values (only actual bias data, not peephole // weights) std::vector<float> combined_biases; combined_biases.reserve(n); std::copy_n(lstm_bias_tensor.data<float>(), n, std::back_inserter(combined_biases)); if (with_fc_bias) { // Add FC-bias with LSTM-bias (into GEMM result to be) auto* fc_bias_var = scope->FindVar(fc_bias->Name()); const auto& fc_bias_tensor = fc_bias_var->Get<framework::LoDTensor>(); for (int i = 0; i < fc_bias_tensor.numel(); i++) { combined_biases[i] += fc_bias_tensor.data<float>()[i]; } } // broadcast biases std::vector<float> ones(m, 1.0f); paddle::operators::math::CBlas<float>::GEMM( CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, 1, alpha, &ones[0], 1, &combined_biases[0], n, 0.0f, embeddings_data, n); // Wx*embeddings paddle::operators::math::CBlas<float>::GEMM( CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, alpha, embedding_data, k, weightx_data, n, beta, embeddings_data, n); op_desc.SetInput("Embeddings", {embeddings}); // Create temp variables. const std::string BatchedInput = patterns::UniqueKey("BatchedInput"); const std::string BatchedCellPreAct = patterns::UniqueKey("BatchedCellPreAct"); const std::string BatchedGate = patterns::UniqueKey("BatchedGate"); scope->Var(BatchedInput)->GetMutable<framework::LoDTensor>(); scope->Var(BatchedCellPreAct)->GetMutable<framework::LoDTensor>(); scope->Var(BatchedGate)->GetMutable<framework::LoDTensor>(); op_desc.SetInput("H0", {}); op_desc.SetInput("C0", {}); op_desc.SetOutput("Hidden", {hidden->Name()}); op_desc.SetOutput("Cell", {cell->Name()}); op_desc.SetOutput("XX", {xx->Name()}); op_desc.SetOutput("BatchedGate", {BatchedGate}); op_desc.SetOutput("BatchCellPreAct", {BatchedCellPreAct}); op_desc.SetOutput("BatchedInput", {BatchedInput}); op_desc.SetAttr("is_reverse", lstm->Op()->GetAttr("is_reverse")); op_desc.SetAttr("use_peepholes", lstm->Op()->GetAttr("use_peepholes")); // TODO(TJ): get from attr op_desc.SetAttr("use_seq", true); PADDLE_ENFORCE(graph->Has(kParamScopeAttr)); auto* scope = graph->Get<Scope*>(kParamScopeAttr); #define OP_SET_OUT(x) \ const std::string x = patterns::UniqueKey(#x); \ op_desc.SetOutput(#x, {x}); \ scope->Var(x)->GetMutable<LoDTensor>() OP_SET_OUT(BatchedCell); OP_SET_OUT(BatchedHidden); OP_SET_OUT(ReorderedH0); OP_SET_OUT(ReorderedC0); #undef OP_SET_OUT auto* op = graph->CreateOpNode(&op_desc); IR_NODE_LINK_TO(input, op); IR_NODE_LINK_TO(weight_x, op); IR_NODE_LINK_TO(weight_h, op); IR_NODE_LINK_TO(bias, op); IR_NODE_LINK_TO(op, hidden); return op; }; int fusion_count{0}; auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph, Graph* g) { GET_IR_NODE_FROM_SUBGRAPH(lstm, lstm, lstm_pattern); GET_IR_NODE_FROM_SUBGRAPH(Weight, Weight, lstm_pattern); GET_IR_NODE_FROM_SUBGRAPH(Bias, Bias, lstm_pattern); GET_IR_NODE_FROM_SUBGRAPH(Cell, Cell, lstm_pattern); GET_IR_NODE_FROM_SUBGRAPH(Hidden, Hidden, lstm_pattern); GET_IR_NODE_FROM_SUBGRAPH(lookup_table, lookup_table, embedding_pattern); GET_IR_NODE_FROM_SUBGRAPH(W, W, embedding_pattern); GET_IR_NODE_FROM_SUBGRAPH(w, w, fc_pattern); GET_IR_NODE_FROM_SUBGRAPH(mul, mul, fc_pattern); // TODO(jczaja): Add support for is_sparse / is_distributed auto is_sparse = boost::get<bool>(lookup_table->Op()->GetAttr("is_sparse")); auto is_distributed = boost::get<bool>(lookup_table->Op()->GetAttr("is_distributed")); if (is_sparse == true || is_distributed == true) { return; } if (with_fc_bias) { GET_IR_NODE_FROM_SUBGRAPH(fc_out, Out, fc_pattern); GET_IR_NODE_FROM_SUBGRAPH(fc_bias, bias, fc_pattern); GET_IR_NODE_FROM_SUBGRAPH(elementwise_add, elementwise_add, fc_pattern); embedding_lstm_creator(lookup_table, W, lstm, subgraph.at(x), w, Weight, Bias, Hidden, Cell, fc_out, fc_bias); // Remove unneeded nodes. // TODO(jczaja): Proper removing of lookup table std::unordered_set<const Node*> marked_nodes( //{lookup_table, mul, lstm, elementwise_add, fc_bias, W}); {mul, lstm, elementwise_add, fc_bias}); GraphSafeRemoveNodes(graph, marked_nodes); } else { GET_IR_NODE_FROM_SUBGRAPH(fc_out, mul_out, fc_pattern); embedding_lstm_creator(lookup_table, W, lstm, subgraph.at(x), w, Weight, Bias, Hidden, Cell, fc_out, nullptr); // Remove unneeded nodes. // TODO(jczaja): Proper removing of lookup table // std::unordered_set<const Node*> marked_nodes({lookup_table, W, mul, // lstm}); std::unordered_set<const Node*> marked_nodes({mul, lstm}); GraphSafeRemoveNodes(graph, marked_nodes); } ++fusion_count; }; gpd(graph, handler); return fusion_count; } std::unique_ptr<ir::Graph> EmbeddingFCLSTMFusePass::ApplyImpl( std::unique_ptr<ir::Graph> graph) const { FusePassBase::Init(name_scope_, graph.get()); int fusion_count = BuildFusion(graph.get(), name_scope_, param_scope(), true /*with_fc_bias*/); AddStatis(fusion_count); return graph; } } // namespace ir } // namespace framework } // namespace paddle REGISTER_PASS(embedding_fc_lstm_fuse_pass, paddle::framework::ir::EmbeddingFCLSTMFusePass); <|endoftext|>
<commit_before>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "DistributedData.h" #include "MooseUtils.h" #include "MooseError.h" #include "libmesh/dense_vector.h" namespace StochasticTools { template <typename T> DistributedData<T>::DistributedData(const libMesh::Parallel::Communicator & comm_in) : libMesh::ParallelObject(comm_in), _closed(false), _n_local_entries(0) { } template <typename T> void DistributedData<T>::initializeContainer(unsigned int n_global_entries) { // This function can be used when a linear partitioning is required and the // number of global samples is known in advance. unsigned int local_entry_begin; unsigned int local_entry_end; MooseUtils::linearPartitionItems(n_global_entries, n_processors(), processor_id(), _n_local_entries, local_entry_begin, local_entry_end); _local_entries.resize(_n_local_entries); _local_entry_ids.resize(_n_local_entries); // Filling the sample ID vector, leaving the elements of the sample vector // with the default constructor. for (unsigned int entry_i = local_entry_begin; entry_i < local_entry_end; ++entry_i) { _local_entry_ids[entry_i] = entry_i; } } template <typename T> void DistributedData<T>::addNewEntry(unsigned int glob_i, const T & entry) { auto it = std::find(_local_entry_ids.begin(), _local_entry_ids.end(), glob_i); if (it != _local_entry_ids.end()) ::mooseError("Local object ID (", glob_i, ") already exists!"); if (_closed) ::mooseError("DistributeData has already been closed, cannot add new elements!"); _local_entries.push_back(entry); _local_entry_ids.push_back(glob_i); _n_local_entries += 1; } template <typename T> void DistributedData<T>::changeEntry(unsigned int glob_i, const T & entry) { auto it = std::find(_local_entry_ids.begin(), _local_entry_ids.end(), glob_i); if (it == _local_entry_ids.end()) ::mooseError("Local object ID (", glob_i, ") does not exists!"); if (_closed) ::mooseError("DistributeData has already been closed, cannot change elements!"); _local_entries[std::distance(_local_entry_ids.begin(), it)] = entry; } template <typename T> const T & DistributedData<T>::getGlobalEntry(unsigned int glob_i) const { auto it = std::find(_local_entry_ids.begin(), _local_entry_ids.end(), glob_i); if (it == _local_entry_ids.end()) ::mooseError("Local object ID (", glob_i, ") does not exists!"); return _local_entries[std::distance(_local_entry_ids.begin(), it)]; } template <typename T> const T & DistributedData<T>::getLocalEntry(unsigned int loc_i) const { if (loc_i > _n_local_entries - 1) ::mooseError("The requested local index (", loc_i, ") is greater than the size (", _n_local_entries, ") of the locally stored vector!"); return _local_entries[loc_i]; } template <typename T> unsigned int DistributedData<T>::getNumberOfGlobalEntries() const { unsigned int val = _n_local_entries; _communicator.sum(val); return val; } template <typename T> bool DistributedData<T>::hasGlobalEntry(unsigned int glob_i) const { const auto it = std::find(_local_entry_ids.begin(), _local_entry_ids.end(), glob_i); if (it != _local_entry_ids.end()) return true; return false; } template <typename T> unsigned int DistributedData<T>::getLocalIndex(unsigned int glob_i) const { const auto it = std::find(_local_entry_ids.begin(), _local_entry_ids.end(), glob_i); if (it == _local_entry_ids.end()) ::mooseError("Local object ID (", glob_i, ") does not exists!"); return std::distance(_local_entry_ids.begin(), it); } template <typename T> unsigned int DistributedData<T>::getGlobalIndex(unsigned int loc_i) const { if (loc_i > _n_local_entries - 1) ::mooseError("The requested local index (", loc_i, ") is greater than the size (", _n_local_entries, ") of the locally stored vector!"); return _local_entry_ids[loc_i]; } // Explicit instantiation of types that are necessary. template class DistributedData<DenseVector<Real>>; template class DistributedData<std::shared_ptr<DenseVector<Real>>>; template class DistributedData<std::vector<Real>>; } // StochasticTools namespace <commit_msg>Small modification in DistributedData. (#15731)<commit_after>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "DistributedData.h" #include "MooseUtils.h" #include "MooseError.h" #include "libmesh/dense_vector.h" namespace StochasticTools { template <typename T> DistributedData<T>::DistributedData(const libMesh::Parallel::Communicator & comm_in) : libMesh::ParallelObject(comm_in), _closed(false), _n_local_entries(0) { } template <typename T> void DistributedData<T>::initializeContainer(unsigned int n_global_entries) { // This function can be used when a linear partitioning is required and the // number of global samples is known in advance. Need to do conversion because of // because of 64 bit dof indices. dof_id_type local_entry_begin; dof_id_type local_entry_end; dof_id_type n_local_entries; MooseUtils::linearPartitionItems(n_global_entries, n_processors(), processor_id(), n_local_entries, local_entry_begin, local_entry_end); _n_local_entries = n_local_entries; _local_entries.resize(_n_local_entries); _local_entry_ids.resize(_n_local_entries); // Filling the sample ID vector, leaving the elements of the sample vector // with the default constructor. for (dof_id_type entry_i = local_entry_begin; entry_i < local_entry_end; ++entry_i) { _local_entry_ids[entry_i] = entry_i; } } template <typename T> void DistributedData<T>::addNewEntry(unsigned int glob_i, const T & entry) { auto it = std::find(_local_entry_ids.begin(), _local_entry_ids.end(), glob_i); if (it != _local_entry_ids.end()) ::mooseError("Local object ID (", glob_i, ") already exists!"); if (_closed) ::mooseError("DistributeData has already been closed, cannot add new elements!"); _local_entries.push_back(entry); _local_entry_ids.push_back(glob_i); _n_local_entries += 1; } template <typename T> void DistributedData<T>::changeEntry(unsigned int glob_i, const T & entry) { auto it = std::find(_local_entry_ids.begin(), _local_entry_ids.end(), glob_i); if (it == _local_entry_ids.end()) ::mooseError("Local object ID (", glob_i, ") does not exists!"); if (_closed) ::mooseError("DistributeData has already been closed, cannot change elements!"); _local_entries[std::distance(_local_entry_ids.begin(), it)] = entry; } template <typename T> const T & DistributedData<T>::getGlobalEntry(unsigned int glob_i) const { auto it = std::find(_local_entry_ids.begin(), _local_entry_ids.end(), glob_i); if (it == _local_entry_ids.end()) ::mooseError("Local object ID (", glob_i, ") does not exists!"); return _local_entries[std::distance(_local_entry_ids.begin(), it)]; } template <typename T> const T & DistributedData<T>::getLocalEntry(unsigned int loc_i) const { if (loc_i > _n_local_entries - 1) ::mooseError("The requested local index (", loc_i, ") is greater than the size (", _n_local_entries, ") of the locally stored vector!"); return _local_entries[loc_i]; } template <typename T> unsigned int DistributedData<T>::getNumberOfGlobalEntries() const { unsigned int val = _n_local_entries; _communicator.sum(val); return val; } template <typename T> bool DistributedData<T>::hasGlobalEntry(unsigned int glob_i) const { const auto it = std::find(_local_entry_ids.begin(), _local_entry_ids.end(), glob_i); if (it != _local_entry_ids.end()) return true; return false; } template <typename T> unsigned int DistributedData<T>::getLocalIndex(unsigned int glob_i) const { const auto it = std::find(_local_entry_ids.begin(), _local_entry_ids.end(), glob_i); if (it == _local_entry_ids.end()) ::mooseError("Local object ID (", glob_i, ") does not exists!"); return std::distance(_local_entry_ids.begin(), it); } template <typename T> unsigned int DistributedData<T>::getGlobalIndex(unsigned int loc_i) const { if (loc_i > _n_local_entries - 1) ::mooseError("The requested local index (", loc_i, ") is greater than the size (", _n_local_entries, ") of the locally stored vector!"); return _local_entry_ids[loc_i]; } // Explicit instantiation of types that are necessary. template class DistributedData<DenseVector<Real>>; template class DistributedData<std::shared_ptr<DenseVector<Real>>>; template class DistributedData<std::vector<Real>>; } // StochasticTools namespace <|endoftext|>
<commit_before>#include "vtkActor.h" #include "vtkCamera.h" #include "vtkCommand.h" #include "vtkImageData.h" #include "vtkImagePlaneWidget.h" #include "vtkInteractorEventRecorder.h" #include "vtkKochanekSpline.h" #include "vtkParametricSpline.h" #include "vtkPlaneSource.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkProperty2D.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" #include "vtkSplineWidget.h" #include "vtkTextProperty.h" // Callback for the spline widget interaction class vtkSplineWidgetCallback : public vtkCommand { public: static vtkSplineWidgetCallback *New() { return new vtkSplineWidgetCallback; } virtual void Execute(vtkObject *caller, unsigned long, void*) { vtkSplineWidget *spline = reinterpret_cast<vtkSplineWidget*>(caller); spline->GetPolyData(Poly); } vtkSplineWidgetCallback():Poly(0){}; vtkPolyData* Poly; }; int main( int, char *[] ) { vtkRenderer* ren1 = vtkRenderer::New(); vtkRenderWindow* renWin = vtkRenderWindow::New(); renWin->AddRenderer( ren1); vtkRenderWindowInteractor* iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow( renWin); planeSource->Update(); vtkPlaneSource* planeSource; planeSource->Update(); vtkPolyDataMapper* planeSourceMapper = vtkPolyDataMapper::New(); planeSourceMapper->SetInput(planeSource->GetOutput()); vtkActor* planeSourceActor = vtkActor::New(); planeSourceActor->SetMapper(planeSourceMapper); vtkSplineWidget* spline = vtkSplineWidget::New(); spline->SetInteractor( iren); spline->SetInput(planeSource->GetOutput()); spline->SetPriority(1.0); spline->KeyPressActivationOff(); spline->PlaceWidget(); spline->ProjectToPlaneOn(); spline->SetProjectionNormal(0); spline->SetProjectionPosition(102.4); //initial plane oriented position spline->SetProjectionNormal(3); //allow arbitrary oblique orientations spline->SetPlaneSource(planeSource); // Specify the type of spline (change from default vtkCardinalSpline) vtkKochanekSpline* xspline = vtkKochanekSpline::New(); vtkKochanekSpline* yspline = vtkKochanekSpline::New(); vtkKochanekSpline* zspline = vtkKochanekSpline::New(); vtkParametricSpline* para = spline->GetParametricSpline(); para->SetXSpline(xspline); para->SetYSpline(yspline); para->SetZSpline(zspline); vtkPolyData* poly = vtkPolyData::New(); spline->GetPolyData(poly); vtkSplineWidgetCallback* swcb = vtkSplineWidgetCallback::New(); swcb->Poly = poly; spline->AddObserver(vtkCommand::InteractionEvent,swcb); ren1->SetBackground( 0.1, 0.2, 0.4); ren1->AddActor(planeSourceActor); renWin->SetSize( 600, 300); renWin->Render(); spline->On(); spline->SetNumberOfHandles(4); spline->SetNumberOfHandles(5); spline->SetResolution(399); // Set up an interesting viewpoint vtkCamera* camera = ren1->GetActiveCamera(); // Render the image iren->Initialize(); renWin->Render(); return EXIT_SUCCESS; } <commit_msg>Widgets example: fix up logic around planeSource<commit_after>#include "vtkActor.h" #include "vtkCamera.h" #include "vtkCommand.h" #include "vtkImageData.h" #include "vtkImagePlaneWidget.h" #include "vtkInteractorEventRecorder.h" #include "vtkKochanekSpline.h" #include "vtkParametricSpline.h" #include "vtkPlaneSource.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkProperty2D.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" #include "vtkSplineWidget.h" #include "vtkTextProperty.h" // Callback for the spline widget interaction class vtkSplineWidgetCallback : public vtkCommand { public: static vtkSplineWidgetCallback *New() { return new vtkSplineWidgetCallback; } virtual void Execute(vtkObject *caller, unsigned long, void*) { vtkSplineWidget *spline = reinterpret_cast<vtkSplineWidget*>(caller); spline->GetPolyData(Poly); } vtkSplineWidgetCallback():Poly(0){}; vtkPolyData* Poly; }; int main( int, char *[] ) { vtkRenderer* ren1 = vtkRenderer::New(); vtkRenderWindow* renWin = vtkRenderWindow::New(); renWin->AddRenderer( ren1); vtkRenderWindowInteractor* iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow( renWin); vtkPlaneSource* planeSource = vtkPlaneSource::New(); planeSource->Update(); vtkPolyDataMapper* planeSourceMapper = vtkPolyDataMapper::New(); planeSourceMapper->SetInput(planeSource->GetOutput()); vtkActor* planeSourceActor = vtkActor::New(); planeSourceActor->SetMapper(planeSourceMapper); vtkSplineWidget* spline = vtkSplineWidget::New(); spline->SetInteractor( iren); spline->SetInput(planeSource->GetOutput()); spline->SetPriority(1.0); spline->KeyPressActivationOff(); spline->PlaceWidget(); spline->ProjectToPlaneOn(); spline->SetProjectionNormal(0); spline->SetProjectionPosition(102.4); //initial plane oriented position spline->SetProjectionNormal(3); //allow arbitrary oblique orientations spline->SetPlaneSource(planeSource); // Specify the type of spline (change from default vtkCardinalSpline) vtkKochanekSpline* xspline = vtkKochanekSpline::New(); vtkKochanekSpline* yspline = vtkKochanekSpline::New(); vtkKochanekSpline* zspline = vtkKochanekSpline::New(); vtkParametricSpline* para = spline->GetParametricSpline(); para->SetXSpline(xspline); para->SetYSpline(yspline); para->SetZSpline(zspline); vtkPolyData* poly = vtkPolyData::New(); spline->GetPolyData(poly); vtkSplineWidgetCallback* swcb = vtkSplineWidgetCallback::New(); swcb->Poly = poly; spline->AddObserver(vtkCommand::InteractionEvent,swcb); ren1->SetBackground( 0.1, 0.2, 0.4); ren1->AddActor(planeSourceActor); renWin->SetSize( 600, 300); renWin->Render(); spline->On(); spline->SetNumberOfHandles(4); spline->SetNumberOfHandles(5); spline->SetResolution(399); // Set up an interesting viewpoint vtkCamera* camera = ren1->GetActiveCamera(); // Render the image iren->Initialize(); renWin->Render(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#define STRICT #define ORBITER_MODULE #include "Orbitersdk.h" #include "PersistData.h" #include "MasterMFD.h" int mfdIdentifierMode; DLLCLBK void InitModule(HINSTANCE hDLL) { static char *name = "Master"; MFDMODESPECEX spec; spec.name = name; spec.key = OAPI_KEY_M; spec.context = NULL; spec.msgproc = MasterMFD::MsgProc; mfdIdentifierMode = oapiRegisterMFDMode(spec); //load lines PersistantData::fillLineData("testTree.txt"); } DLLCLBK void opcOpenRenderViewport(HWND hRenderWnd, DWORD width, DWORD height, BOOL fullscreen) { //ready container PersistantData::readyContainer(); } DLLCLBK void ExitModule(HINSTANCE hDLL) { oapiUnregisterMFDMode(mfdIdentifierMode); } DLLCLBK void opcPreStep(double simt, double simdt, double mjd) { if (PersistantData::switchMFD) { //switch it! oapiOpenMFD(PersistantData::mfdMode, PersistantData::mfdNum); //rest switchMFD PersistantData::switchMFD = false; } } MasterMFD::MasterMFD(int _mfdNumber, DWORD w, DWORD h, VESSEL *vessel) : MFD2(w, h, vessel), width(w), height(h), mfdNumber(_mfdNumber) { //start with default container currentContainer = &(PersistantData::topContainer); } bool MasterMFD::areAtTop() { return !(currentContainer->parent); } bool MasterMFD::ConsumeButton(int bt, int event) { if (!(event & PANEL_MOUSE_LBDOWN)) return false; switch (buttons[bt].buttonType) { case ButtonType::CAT: { //go into a subcategory currentContainer = currentContainer->children[buttons[bt].id]; //update location generateTreeLocation(); return true; break; } case ButtonType::MFD: { //schedule a MFD switch at next frame PersistantData::mfdMode = currentContainer->MFDS[buttons[bt].id].mfdID; PersistantData::mfdNum = mfdNumber; PersistantData::switchMFD = true; return true; break; } default: return false; } } bool MasterMFD::Update(oapi::Sketchpad* skp) { resetNextButton(); generateTreeLocation(); drawNavigation(skp); drawCategories(skp); drawMFDS(skp); return true; } //regenerate tree location void MasterMFD::generateTreeLocation() { //start with current subcategory name if (currentContainer->parent != NULL) treeLocation = currentContainer->name; //go up through parents, appending name MFDContainer* navigationContainer = currentContainer; while (navigationContainer->parent != NULL ) { navigationContainer = navigationContainer->parent; //write out this one's name, with an arrow if ((navigationContainer->name.compare(""))) treeLocation.insert(0, navigationContainer->name + "->"); } } void MasterMFD::drawNavigation(oapi::Sketchpad* skp) { Title(skp, "MasterMFD"); //draw current location in the tree skp->SetFont(GetDefaultFont(0)); skp->SetTextColor(GetDefaultColour(2)); //justify text in the center int xCoord = (width - skp->GetTextWidth(treeLocation.c_str())) / 2; drawAtLinePercentage(xCoord, .05, treeLocation.c_str(), skp); } void MasterMFD::drawCategories(oapi::Sketchpad* skp) { skp->SetFont(GetDefaultFont(0)); skp->SetTextColor(GetDefaultColour(0)); //draw the current categories in green for (int i = 0; i < currentContainer->children.size(); i++) { drawTextAtNextButton(currentContainer->children[i]->name, ButtonData(ButtonType::CAT, i), skp); } } void MasterMFD::drawMFDS(oapi::Sketchpad* skp) { skp->SetFont(GetDefaultFont(0)); skp->SetTextColor(GetDefaultColour(1)); //draw the current categories in green for (int i = 0; i < currentContainer->MFDS.size(); i++) { drawTextAtNextButton(currentContainer->MFDS[i].name, ButtonData(ButtonType::MFD,i), skp); } } void MasterMFD::drawTextAtNextButton(std::string text, ButtonData info, oapi::Sketchpad* skp) { buttons.push_back(info); if (nextButton < 12) drawTextNextToButton(nextButton, text, skp); nextButton++; } void MasterMFD::resetNextButton() { buttons.clear(); nextButton = 0; } void MasterMFD::drawTextNextToButton(int buttonNum, std::string text, oapi::Sketchpad* skp) { double percentY = .143 * (buttonNum % 6) + .14; //if buttonNum is less than 6 (on the left side), just draw normally //otherwise, draw out from the right if (buttonNum < 6) drawAtLinePercentage(3, percentY, text, skp); //3 pixels out for spacing else drawAtLinePercentage(width - skp->GetTextWidth(text.c_str()) - 3, percentY, text, skp); } void MasterMFD::drawAtLinePercentage(int xLoc, double percentY, std::string text, oapi::Sketchpad* skp) { skp->Text(xLoc, percentY * height, text.c_str(), text.size()); } // message parser int MasterMFD::MsgProc(UINT msg, UINT mfd, WPARAM wparam, LPARAM lparam) { switch (msg) { case OAPI_MSG_MFD_OPENEDEX: { MFDMODEOPENSPEC *ospec = (MFDMODEOPENSPEC*)wparam; return (int)(new MasterMFD(mfd,ospec->w, ospec->h, (VESSEL*)lparam)); } } return 0; }<commit_msg>Added navigation control-a back button<commit_after>#define STRICT #define ORBITER_MODULE #include "Orbitersdk.h" #include "PersistData.h" #include "MasterMFD.h" int mfdIdentifierMode; DLLCLBK void InitModule(HINSTANCE hDLL) { static char *name = "Master"; MFDMODESPECEX spec; spec.name = name; spec.key = OAPI_KEY_M; spec.context = NULL; spec.msgproc = MasterMFD::MsgProc; mfdIdentifierMode = oapiRegisterMFDMode(spec); //load lines PersistantData::fillLineData("testTree.txt"); } DLLCLBK void opcOpenRenderViewport(HWND hRenderWnd, DWORD width, DWORD height, BOOL fullscreen) { //ready container PersistantData::readyContainer(); } DLLCLBK void ExitModule(HINSTANCE hDLL) { oapiUnregisterMFDMode(mfdIdentifierMode); } DLLCLBK void opcPreStep(double simt, double simdt, double mjd) { if (PersistantData::switchMFD) { //switch it! oapiOpenMFD(PersistantData::mfdMode, PersistantData::mfdNum); //rest switchMFD PersistantData::switchMFD = false; } } MasterMFD::MasterMFD(int _mfdNumber, DWORD w, DWORD h, VESSEL *vessel) : MFD2(w, h, vessel), width(w), height(h), mfdNumber(_mfdNumber) { //start with default container currentContainer = &(PersistantData::topContainer); } bool MasterMFD::areAtTop() { return !(currentContainer->parent); } bool MasterMFD::ConsumeButton(int bt, int event) { if (!(event & PANEL_MOUSE_LBDOWN)) return false; switch (buttons[bt].buttonType) { case ButtonType::NAV: { //switch the ID switch (buttons[bt].id) { case 0: //it's the back button, advance up the tree currentContainer = currentContainer->parent; generateTreeLocation(); return true; break; } break; } case ButtonType::CAT: { //go into a subcategory currentContainer = currentContainer->children[buttons[bt].id]; //update location generateTreeLocation(); return true; break; } case ButtonType::MFD: { //schedule a MFD switch at next frame PersistantData::mfdMode = currentContainer->MFDS[buttons[bt].id].mfdID; PersistantData::mfdNum = mfdNumber; PersistantData::switchMFD = true; return true; break; } default: return false; } } bool MasterMFD::Update(oapi::Sketchpad* skp) { resetNextButton(); generateTreeLocation(); drawNavigation(skp); drawCategories(skp); drawMFDS(skp); return true; } //regenerate tree location void MasterMFD::generateTreeLocation() { treeLocation = ""; //start with current subcategory name if (currentContainer->parent != NULL) treeLocation = currentContainer->name; //go up through parents, appending name MFDContainer* navigationContainer = currentContainer; while (navigationContainer->parent != NULL ) { navigationContainer = navigationContainer->parent; //write out this one's name, with an arrow if ((navigationContainer->name.compare(""))) treeLocation.insert(0, navigationContainer->name + "->"); } } void MasterMFD::drawNavigation(oapi::Sketchpad* skp) { Title(skp, "MasterMFD"); //draw current location in the tree skp->SetFont(GetDefaultFont(0)); skp->SetTextColor(GetDefaultColour(2)); //justify text in the center int xCoord = (width - skp->GetTextWidth(treeLocation.c_str())) / 2; drawAtLinePercentage(xCoord, .05, treeLocation.c_str(), skp); //if we aren't at the top, draw a "back" button to advance up a category if (!areAtTop()) drawTextAtNextButton("Back", ButtonData(ButtonType::NAV, 0), skp); } void MasterMFD::drawCategories(oapi::Sketchpad* skp) { skp->SetFont(GetDefaultFont(0)); skp->SetTextColor(GetDefaultColour(0)); //draw the current categories in green for (int i = 0; i < currentContainer->children.size(); i++) { drawTextAtNextButton(currentContainer->children[i]->name, ButtonData(ButtonType::CAT, i), skp); } } void MasterMFD::drawMFDS(oapi::Sketchpad* skp) { skp->SetFont(GetDefaultFont(0)); skp->SetTextColor(GetDefaultColour(1)); //draw the current categories in green for (int i = 0; i < currentContainer->MFDS.size(); i++) { drawTextAtNextButton(currentContainer->MFDS[i].name, ButtonData(ButtonType::MFD,i), skp); } } void MasterMFD::drawTextAtNextButton(std::string text, ButtonData info, oapi::Sketchpad* skp) { buttons.push_back(info); if (nextButton < 12) drawTextNextToButton(nextButton, text, skp); nextButton++; } void MasterMFD::resetNextButton() { buttons.clear(); nextButton = 0; } void MasterMFD::drawTextNextToButton(int buttonNum, std::string text, oapi::Sketchpad* skp) { double percentY = .143 * (buttonNum % 6) + .14; //if buttonNum is less than 6 (on the left side), just draw normally //otherwise, draw out from the right if (buttonNum < 6) drawAtLinePercentage(3, percentY, text, skp); //3 pixels out for spacing else drawAtLinePercentage(width - skp->GetTextWidth(text.c_str()) - 3, percentY, text, skp); } void MasterMFD::drawAtLinePercentage(int xLoc, double percentY, std::string text, oapi::Sketchpad* skp) { skp->Text(xLoc, percentY * height, text.c_str(), text.size()); } // message parser int MasterMFD::MsgProc(UINT msg, UINT mfd, WPARAM wparam, LPARAM lparam) { switch (msg) { case OAPI_MSG_MFD_OPENEDEX: { MFDMODEOPENSPEC *ospec = (MFDMODEOPENSPEC*)wparam; return (int)(new MasterMFD(mfd,ospec->w, ospec->h, (VESSEL*)lparam)); } } return 0; }<|endoftext|>
<commit_before>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 Clifford Wolf <[email protected]> * Copyright (C) 2018 David Shah <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "pcf.h" #include <sstream> #include "log.h" #include "util.h" NEXTPNR_NAMESPACE_BEGIN // Read a w // Apply PCF constraints to a pre-packing design bool apply_pcf(Context *ctx, std::string filename, std::istream &in) { try { if (!in) log_error("failed to open PCF file\n"); std::string line; int lineno = 0; while (std::getline(in, line)) { lineno++; size_t cstart = line.find("#"); if (cstart != std::string::npos) line = line.substr(0, cstart); std::stringstream ss(line); std::vector<std::string> words; std::string tmp; while (ss >> tmp) words.push_back(tmp); if (words.size() == 0) continue; std::string cmd = words.at(0); bool nowarn = false; if (cmd == "set_io") { size_t args_end = 1; std::vector<std::pair<IdString, std::string>> extra_attrs; while (args_end < words.size() && words.at(args_end).at(0) == '-') { const auto &setting = words.at(args_end); if (setting == "-pullup") { const auto &value = words.at(++args_end); if (value == "yes" || value == "1") extra_attrs.emplace_back(std::make_pair(ctx->id("PULLUP"), "1")); else if (value == "no" || value == "0") extra_attrs.emplace_back(std::make_pair(ctx->id("PULLUP"), "0")); else log_error("Invalid value '%s' for -pullup (on line %d)\n", value.c_str(), lineno); } else if (setting == "-pullup_resistor") { const auto &value = words.at(++args_end); if (ctx->args.type != ArchArgs::UP5K) log_error("Pullup resistance can only be set on UP5K (on line %d)\n", lineno); if (value != "3P3K" && value != "6P8K" && value != "10K" && value != "100K") log_error("Invalid value '%s' for -pullup_resistor (on line %d)\n", value.c_str(), lineno); extra_attrs.emplace_back(std::make_pair(ctx->id("PULLUP_RESISTOR"), value)); } else if (setting == "-nowarn") { nowarn = true; } else if (setting == "--warn-no-port") { } else { log_warning("Ignoring PCF setting '%s' (on line %d)\n", setting.c_str(), lineno); } args_end++; } if (args_end >= words.size() - 1) log_error("expected PCF syntax 'set_io cell pin' (on line %d)\n", lineno); std::string cell = words.at(args_end); std::string pin = words.at(args_end + 1); auto fnd_cell = ctx->cells.find(ctx->id(cell)); if (fnd_cell == ctx->cells.end()) { if (!nowarn) log_warning("unmatched constraint '%s' (on line %d)\n", cell.c_str(), lineno); } else { BelId pin_bel = ctx->getPackagePinBel(pin); if (pin_bel == BelId()) log_error("package does not have a pin named '%s' (on line %d)\n", pin.c_str(), lineno); if (fnd_cell->second->attrs.count(ctx->id("BEL"))) log_error("duplicate pin constraint on '%s' (on line %d)\n", cell.c_str(), lineno); fnd_cell->second->attrs[ctx->id("BEL")] = ctx->getBelName(pin_bel).str(ctx); log_info("constrained '%s' to bel '%s'\n", cell.c_str(), fnd_cell->second->attrs[ctx->id("BEL")].c_str()); for (const auto &attr : extra_attrs) fnd_cell->second->attrs[attr.first] = attr.second; } } else { log_error("unsupported PCF command '%s' (on line %d)\n", cmd.c_str(), lineno); } } for (auto cell : sorted(ctx->cells)) { CellInfo *ci = cell.second; if (ci->type == ctx->id("$nextpnr_ibuf") || ci->type == ctx->id("$nextpnr_obuf") || ci->type == ctx->id("$nextpnr_iobuf")) { if (!ci->attrs.count(ctx->id("BEL"))) { if (bool_or_default(ctx->settings, ctx->id("pcf_allow_unconstrained"))) log_warning("IO '%s' is unconstrained in PCF and will be automatically placed\n", cell.first.c_str(ctx)); else log_error("IO '%s' is unconstrained in PCF (override this error with " "--pcf-allow-unconstrained)\n", cell.first.c_str(ctx)); } } } ctx->settings.emplace(ctx->id("input/pcf"), filename); return true; } catch (log_execution_error_exception) { return false; } } NEXTPNR_NAMESPACE_END <commit_msg>ice40: Warn that trailing PCF settings are ignored<commit_after>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 Clifford Wolf <[email protected]> * Copyright (C) 2018 David Shah <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "pcf.h" #include <sstream> #include "log.h" #include "util.h" NEXTPNR_NAMESPACE_BEGIN // Read a w // Apply PCF constraints to a pre-packing design bool apply_pcf(Context *ctx, std::string filename, std::istream &in) { try { if (!in) log_error("failed to open PCF file\n"); std::string line; int lineno = 0; while (std::getline(in, line)) { lineno++; size_t cstart = line.find("#"); if (cstart != std::string::npos) line = line.substr(0, cstart); std::stringstream ss(line); std::vector<std::string> words; std::string tmp; while (ss >> tmp) words.push_back(tmp); if (words.size() == 0) continue; std::string cmd = words.at(0); bool nowarn = false; if (cmd == "set_io") { size_t args_end = 1; std::vector<std::pair<IdString, std::string>> extra_attrs; while (args_end < words.size() && words.at(args_end).at(0) == '-') { const auto &setting = words.at(args_end); if (setting == "-pullup") { const auto &value = words.at(++args_end); if (value == "yes" || value == "1") extra_attrs.emplace_back(std::make_pair(ctx->id("PULLUP"), "1")); else if (value == "no" || value == "0") extra_attrs.emplace_back(std::make_pair(ctx->id("PULLUP"), "0")); else log_error("Invalid value '%s' for -pullup (on line %d)\n", value.c_str(), lineno); } else if (setting == "-pullup_resistor") { const auto &value = words.at(++args_end); if (ctx->args.type != ArchArgs::UP5K) log_error("Pullup resistance can only be set on UP5K (on line %d)\n", lineno); if (value != "3P3K" && value != "6P8K" && value != "10K" && value != "100K") log_error("Invalid value '%s' for -pullup_resistor (on line %d)\n", value.c_str(), lineno); extra_attrs.emplace_back(std::make_pair(ctx->id("PULLUP_RESISTOR"), value)); } else if (setting == "-nowarn") { nowarn = true; } else if (setting == "--warn-no-port") { } else { log_warning("Ignoring PCF setting '%s' (on line %d)\n", setting.c_str(), lineno); } args_end++; } if (args_end > words.size() - 2) log_error("expected PCF syntax 'set_io cell pin' (on line %d)\n", lineno); else if (args_end < words.size() - 2 && !nowarn) log_warning("Ignoring trailing PCF settings (on line %d)\n", lineno); std::string cell = words.at(args_end); std::string pin = words.at(args_end + 1); auto fnd_cell = ctx->cells.find(ctx->id(cell)); if (fnd_cell == ctx->cells.end()) { if (!nowarn) log_warning("unmatched constraint '%s' (on line %d)\n", cell.c_str(), lineno); } else { BelId pin_bel = ctx->getPackagePinBel(pin); if (pin_bel == BelId()) log_error("package does not have a pin named '%s' (on line %d)\n", pin.c_str(), lineno); if (fnd_cell->second->attrs.count(ctx->id("BEL"))) log_error("duplicate pin constraint on '%s' (on line %d)\n", cell.c_str(), lineno); fnd_cell->second->attrs[ctx->id("BEL")] = ctx->getBelName(pin_bel).str(ctx); log_info("constrained '%s' to bel '%s'\n", cell.c_str(), fnd_cell->second->attrs[ctx->id("BEL")].c_str()); for (const auto &attr : extra_attrs) fnd_cell->second->attrs[attr.first] = attr.second; } } else { log_error("unsupported PCF command '%s' (on line %d)\n", cmd.c_str(), lineno); } } for (auto cell : sorted(ctx->cells)) { CellInfo *ci = cell.second; if (ci->type == ctx->id("$nextpnr_ibuf") || ci->type == ctx->id("$nextpnr_obuf") || ci->type == ctx->id("$nextpnr_iobuf")) { if (!ci->attrs.count(ctx->id("BEL"))) { if (bool_or_default(ctx->settings, ctx->id("pcf_allow_unconstrained"))) log_warning("IO '%s' is unconstrained in PCF and will be automatically placed\n", cell.first.c_str(ctx)); else log_error("IO '%s' is unconstrained in PCF (override this error with " "--pcf-allow-unconstrained)\n", cell.first.c_str(ctx)); } } } ctx->settings.emplace(ctx->id("input/pcf"), filename); return true; } catch (log_execution_error_exception) { return false; } } NEXTPNR_NAMESPACE_END <|endoftext|>
<commit_before>#ifndef MJOLNIR_CORE_MULTIPLE_BASIN_FORCE_FIELD_HPP #define MJOLNIR_CORE_MULTIPLE_BASIN_FORCE_FIELD_HPP #include <mjolnir/forcefield/MultipleBasin/MultipleBasinUnitBase.hpp> #include <mjolnir/core/SimulatorTraits.hpp> #include <mjolnir/core/Topology.hpp> #include <mjolnir/core/ForceFieldBase.hpp> #include <mjolnir/core/LocalForceField.hpp> #include <mjolnir/core/GlobalForceField.hpp> #include <mjolnir/core/ExternalForceField.hpp> #include <mjolnir/util/string.hpp> #include <algorithm> #include <numeric> #include <memory> namespace mjolnir { // MultipleBasinForceField // // In some cases, protein has several domains that undergoes conformational // changes independently. // // .-. .-. __ .-. // ( A )( B ) -> (A'|( B ) // `-' `-' `- `-' // | | // v v // .-. __ __ __ // ( A )|B') -> (A'|B') // `-' -' `- -' // // To handle such cases, MultipleBasinForceField has several N-basin forcefields // inside and manage them in a proper way. // template<typename traitsT> class MultipleBasinForceField : public ForceFieldBase<traitsT> { public: using traits_type = traitsT; using base_type = ForceFieldBase<traits_type>; using real_type = typename base_type::real_type; using coordinate_type = typename base_type::coordinate_type; using system_type = typename base_type::system_type; using topology_type = Topology; using local_forcefield_type = LocalForceField<traits_type>; using global_forcefield_type = GlobalForceField<traits_type>; using external_forcefield_type = ExternalForceField<traits_type>; using constraint_forcefield_type = ConstraintForceField<traits_type>; using forcefield_type = std::tuple< local_forcefield_type, global_forcefield_type, external_forcefield_type>; // a set of potentials that are correlated in the way of MultipleBasin. using multiple_basin_unit_type = std::unique_ptr<MultipleBasinUnitBase<traits_type>>; public: MultipleBasinForceField(forcefield_type&& common, constraint_forcefield_type&& constraint, std::vector<multiple_basin_unit_type>&& units) : loc_common_(std::move(std::get<0>(common))), glo_common_(std::move(std::get<1>(common))), ext_common_(std::move(std::get<2>(common))), constraint_(std::move(constraint)), units_(std::move(units)) {} MultipleBasinForceField(forcefield_type&& common, // no constraint std::vector<multiple_basin_unit_type>&& units) : loc_common_(std::move(std::get<0>(common))), glo_common_(std::move(std::get<1>(common))), ext_common_(std::move(std::get<2>(common))), units_(std::move(units)) {} ~MultipleBasinForceField() override = default; MultipleBasinForceField(const MultipleBasinForceField&) = delete; MultipleBasinForceField(MultipleBasinForceField&&) = default; MultipleBasinForceField& operator=(const MultipleBasinForceField&) = delete; MultipleBasinForceField& operator=(MultipleBasinForceField&&) = default; void initialize(const system_type& sys) override { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_FUNCTION(); // ------------------------------------------------------------------- // write topologies. Here we assume topologies are the same MJOLNIR_LOG_INFO("writing topology"); topol_.resize(sys.size()); for(auto& unit : this->units_) { // each unit does not know the size of the system. // we need to tell them the size. unit->write_topology(sys, topol_); } loc_common_.write_topology(topol_); topol_.construct_molecules(); MJOLNIR_LOG_INFO("initializing forcefields"); for(auto& unit : this->units_) { unit->initialize(sys, this->topol_); } loc_common_.initialize(sys); glo_common_.initialize(sys, this->topol_); ext_common_.initialize(sys); // ------------------------------------------------------------------- // initialize buffers this->force_buffer_.resize(sys.size()); for(auto& fb : force_buffer_) { fb = math::make_coordinate<coordinate_type>(0, 0, 0); } this->virial_buffer_ = matrix33_type(0,0,0, 0,0,0, 0,0,0); return; } void calc_force(system_type& sys) const noexcept override { using std::swap; for(const auto& unit : this->units_) { unit->calc_force(sys); } swap(this->force_buffer_, sys.forces()); swap(this->virial_buffer_, sys.virial()); sys.preprocess_forces(); loc_common_.calc_force(sys); glo_common_.calc_force(sys); ext_common_.calc_force(sys); sys.postprocess_forces(); for(std::size_t i=0; i<sys.size(); ++i) { sys.force(i) += force_buffer_[i]; // restore other force force_buffer_[i] = math::make_coordinate<coordinate_type>(0, 0, 0); } sys.virial() += virial_buffer_; this->virial_buffer_ = matrix33_type(0,0,0, 0,0,0, 0,0,0); return ; } void calc_force_and_virial(system_type& sys) const noexcept override { using std::swap; for(const auto& unit : this->units_) { unit->calc_force_and_virial(sys); } swap(this->force_buffer_, sys.forces()); swap(this->virial_buffer_, sys.virial()); sys.preprocess_forces(); loc_common_.calc_force_and_virial(sys); glo_common_.calc_force_and_virial(sys); ext_common_.calc_force_and_virial(sys); sys.postprocess_forces(); for(std::size_t i=0; i<sys.size(); ++i) { sys.force(i) += force_buffer_[i]; // restore other force force_buffer_[i] = math::make_coordinate<coordinate_type>(0, 0, 0); } sys.virial() += virial_buffer_; this->virial_buffer_ = matrix33_type(0,0,0, 0,0,0, 0,0,0); return ; } real_type calc_energy(const system_type& sys) const noexcept override { real_type E = real_type(0.0); for(const auto& unit : this->units_) { E += unit->calc_energy(sys); } E += loc_common_.calc_energy(sys); E += glo_common_.calc_energy(sys); E += ext_common_.calc_energy(sys); return E; } void update(const system_type& sys) override { // update parameters (e.g. temperature). TODO: topologies? for(auto& unit : this->units_) { unit->update(sys, this->topol_); } loc_common_.update(sys); glo_common_.update(sys, this->topol_); ext_common_.update(sys); return; } // update margin of neighbor list void reduce_margin(const real_type dmargin, const system_type& sys) override { for(auto& unit : this->units_) { unit->reduce_margin(dmargin, sys); } loc_common_.reduce_margin(dmargin, sys); glo_common_.reduce_margin(dmargin, sys); ext_common_.reduce_margin(dmargin, sys); return; } void scale_margin(const real_type scale, const system_type& sys) override { for(auto& unit : this->units_) { unit->scale_margin(scale, sys); } loc_common_.scale_margin(scale, sys); glo_common_.scale_margin(scale, sys); ext_common_.scale_margin(scale, sys); return; } // ----------------------------------------------------------------------- // energy output format void format_energy_name(std::string& fmt) const override { using namespace mjolnir::literals::string_literals; for(const auto& unit : this->units_) { unit->format_energy_name(fmt); } fmt += "Common{"_s; loc_common_.format_energy_name(fmt); glo_common_.format_energy_name(fmt); ext_common_.format_energy_name(fmt); if(!fmt.empty() && fmt.back() == ' ') {fmt.pop_back();} fmt += "} "_s; return; } real_type format_energy(const system_type& sys, std::string& fmt) const override { real_type total = 0.0; for(const auto& unit : this->units_) { total += unit->format_energy(sys, fmt); } fmt += " "_s; // Common{ total += loc_common_.format_energy(sys, fmt); total += glo_common_.format_energy(sys, fmt); total += ext_common_.format_energy(sys, fmt); if(!fmt.empty() && fmt.back() == ' ') {fmt.pop_back();} fmt += " "_s; // } return total; } // ----------------------------------------------------------------------- topology_type const& topology() const noexcept override {return topol_;} constraint_forcefield_type const& constraint() const noexcept override {return constraint_;} local_forcefield_type const& common_local() const noexcept {return loc_common_;} global_forcefield_type const& common_global() const noexcept {return glo_common_;} external_forcefield_type const& common_external() const noexcept {return ext_common_;} std::vector<multiple_basin_unit_type> const& units() const noexcept {return units_;} private: topology_type topol_; local_forcefield_type loc_common_; global_forcefield_type glo_common_; external_forcefield_type ext_common_; constraint_forcefield_type constraint_; mutable coordinate_container_type force_buffer_; mutable matrix33_type virial_buffer_; std::vector<multiple_basin_unit_type> units_; }; #ifdef MJOLNIR_SEPARATE_BUILD extern template class MultipleBasinForceField<SimulatorTraits<double, UnlimitedBoundary >>; extern template class MultipleBasinForceField<SimulatorTraits<float, UnlimitedBoundary >>; extern template class MultipleBasinForceField<SimulatorTraits<double, CuboidalPeriodicBoundary>>; extern template class MultipleBasinForceField<SimulatorTraits<float, CuboidalPeriodicBoundary>>; #endif } // mjolnir #endif// MJOLNIR_CORE_MULTIPLE_BASIN_FORCE_FIELD_HPP <commit_msg>fix: add missing type aliases<commit_after>#ifndef MJOLNIR_CORE_MULTIPLE_BASIN_FORCE_FIELD_HPP #define MJOLNIR_CORE_MULTIPLE_BASIN_FORCE_FIELD_HPP #include <mjolnir/forcefield/MultipleBasin/MultipleBasinUnitBase.hpp> #include <mjolnir/core/SimulatorTraits.hpp> #include <mjolnir/core/Topology.hpp> #include <mjolnir/core/ForceFieldBase.hpp> #include <mjolnir/core/LocalForceField.hpp> #include <mjolnir/core/GlobalForceField.hpp> #include <mjolnir/core/ExternalForceField.hpp> #include <mjolnir/util/string.hpp> #include <algorithm> #include <numeric> #include <memory> namespace mjolnir { // MultipleBasinForceField // // In some cases, protein has several domains that undergoes conformational // changes independently. // // .-. .-. __ .-. // ( A )( B ) -> (A'|( B ) // `-' `-' `- `-' // | | // v v // .-. __ __ __ // ( A )|B') -> (A'|B') // `-' -' `- -' // // To handle such cases, MultipleBasinForceField has several N-basin forcefields // inside and manage them in a proper way. // template<typename traitsT> class MultipleBasinForceField : public ForceFieldBase<traitsT> { public: using traits_type = traitsT; using base_type = ForceFieldBase<traits_type>; using real_type = typename base_type::real_type; using coordinate_type = typename base_type::coordinate_type; using system_type = typename base_type::system_type; using matrix33_type = typename traits_type::matrix33_type; using topology_type = Topology; using coordinate_container_type = typename system_type::coordinate_container_type; using local_forcefield_type = LocalForceField<traits_type>; using global_forcefield_type = GlobalForceField<traits_type>; using external_forcefield_type = ExternalForceField<traits_type>; using constraint_forcefield_type = ConstraintForceField<traits_type>; using forcefield_type = std::tuple< local_forcefield_type, global_forcefield_type, external_forcefield_type>; // a set of potentials that are correlated in the way of MultipleBasin. using multiple_basin_unit_type = std::unique_ptr<MultipleBasinUnitBase<traits_type>>; public: MultipleBasinForceField(forcefield_type&& common, constraint_forcefield_type&& constraint, std::vector<multiple_basin_unit_type>&& units) : loc_common_(std::move(std::get<0>(common))), glo_common_(std::move(std::get<1>(common))), ext_common_(std::move(std::get<2>(common))), constraint_(std::move(constraint)), units_(std::move(units)) {} MultipleBasinForceField(forcefield_type&& common, // no constraint std::vector<multiple_basin_unit_type>&& units) : loc_common_(std::move(std::get<0>(common))), glo_common_(std::move(std::get<1>(common))), ext_common_(std::move(std::get<2>(common))), units_(std::move(units)) {} ~MultipleBasinForceField() override = default; MultipleBasinForceField(const MultipleBasinForceField&) = delete; MultipleBasinForceField(MultipleBasinForceField&&) = default; MultipleBasinForceField& operator=(const MultipleBasinForceField&) = delete; MultipleBasinForceField& operator=(MultipleBasinForceField&&) = default; void initialize(const system_type& sys) override { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_FUNCTION(); // ------------------------------------------------------------------- // write topologies. Here we assume topologies are the same MJOLNIR_LOG_INFO("writing topology"); topol_.resize(sys.size()); for(auto& unit : this->units_) { // each unit does not know the size of the system. // we need to tell them the size. unit->write_topology(sys, topol_); } loc_common_.write_topology(topol_); topol_.construct_molecules(); MJOLNIR_LOG_INFO("initializing forcefields"); for(auto& unit : this->units_) { unit->initialize(sys, this->topol_); } loc_common_.initialize(sys); glo_common_.initialize(sys, this->topol_); ext_common_.initialize(sys); // ------------------------------------------------------------------- // initialize buffers this->force_buffer_.resize(sys.size()); for(auto& fb : force_buffer_) { fb = math::make_coordinate<coordinate_type>(0, 0, 0); } this->virial_buffer_ = matrix33_type(0,0,0, 0,0,0, 0,0,0); return; } void calc_force(system_type& sys) const noexcept override { using std::swap; for(const auto& unit : this->units_) { unit->calc_force(sys); } swap(this->force_buffer_, sys.forces()); swap(this->virial_buffer_, sys.virial()); sys.preprocess_forces(); loc_common_.calc_force(sys); glo_common_.calc_force(sys); ext_common_.calc_force(sys); sys.postprocess_forces(); for(std::size_t i=0; i<sys.size(); ++i) { sys.force(i) += force_buffer_[i]; // restore other force force_buffer_[i] = math::make_coordinate<coordinate_type>(0, 0, 0); } sys.virial() += virial_buffer_; this->virial_buffer_ = matrix33_type(0,0,0, 0,0,0, 0,0,0); return ; } void calc_force_and_virial(system_type& sys) const noexcept override { using std::swap; for(const auto& unit : this->units_) { unit->calc_force_and_virial(sys); } swap(this->force_buffer_, sys.forces()); swap(this->virial_buffer_, sys.virial()); sys.preprocess_forces(); loc_common_.calc_force_and_virial(sys); glo_common_.calc_force_and_virial(sys); ext_common_.calc_force_and_virial(sys); sys.postprocess_forces(); for(std::size_t i=0; i<sys.size(); ++i) { sys.force(i) += force_buffer_[i]; // restore other force force_buffer_[i] = math::make_coordinate<coordinate_type>(0, 0, 0); } sys.virial() += virial_buffer_; this->virial_buffer_ = matrix33_type(0,0,0, 0,0,0, 0,0,0); return ; } real_type calc_energy(const system_type& sys) const noexcept override { real_type E = real_type(0.0); for(const auto& unit : this->units_) { E += unit->calc_energy(sys); } E += loc_common_.calc_energy(sys); E += glo_common_.calc_energy(sys); E += ext_common_.calc_energy(sys); return E; } void update(const system_type& sys) override { // update parameters (e.g. temperature). TODO: topologies? for(auto& unit : this->units_) { unit->update(sys, this->topol_); } loc_common_.update(sys); glo_common_.update(sys, this->topol_); ext_common_.update(sys); return; } // update margin of neighbor list void reduce_margin(const real_type dmargin, const system_type& sys) override { for(auto& unit : this->units_) { unit->reduce_margin(dmargin, sys); } loc_common_.reduce_margin(dmargin, sys); glo_common_.reduce_margin(dmargin, sys); ext_common_.reduce_margin(dmargin, sys); return; } void scale_margin(const real_type scale, const system_type& sys) override { for(auto& unit : this->units_) { unit->scale_margin(scale, sys); } loc_common_.scale_margin(scale, sys); glo_common_.scale_margin(scale, sys); ext_common_.scale_margin(scale, sys); return; } // ----------------------------------------------------------------------- // energy output format void format_energy_name(std::string& fmt) const override { using namespace mjolnir::literals::string_literals; for(const auto& unit : this->units_) { unit->format_energy_name(fmt); } fmt += "Common{"_s; loc_common_.format_energy_name(fmt); glo_common_.format_energy_name(fmt); ext_common_.format_energy_name(fmt); if(!fmt.empty() && fmt.back() == ' ') {fmt.pop_back();} fmt += "} "_s; return; } real_type format_energy(const system_type& sys, std::string& fmt) const override { real_type total = 0.0; for(const auto& unit : this->units_) { total += unit->format_energy(sys, fmt); } fmt += " "_s; // Common{ total += loc_common_.format_energy(sys, fmt); total += glo_common_.format_energy(sys, fmt); total += ext_common_.format_energy(sys, fmt); if(!fmt.empty() && fmt.back() == ' ') {fmt.pop_back();} fmt += " "_s; // } return total; } // ----------------------------------------------------------------------- topology_type const& topology() const noexcept override {return topol_;} constraint_forcefield_type const& constraint() const noexcept override {return constraint_;} local_forcefield_type const& common_local() const noexcept {return loc_common_;} global_forcefield_type const& common_global() const noexcept {return glo_common_;} external_forcefield_type const& common_external() const noexcept {return ext_common_;} std::vector<multiple_basin_unit_type> const& units() const noexcept {return units_;} private: topology_type topol_; local_forcefield_type loc_common_; global_forcefield_type glo_common_; external_forcefield_type ext_common_; constraint_forcefield_type constraint_; mutable coordinate_container_type force_buffer_; mutable matrix33_type virial_buffer_; std::vector<multiple_basin_unit_type> units_; }; #ifdef MJOLNIR_SEPARATE_BUILD extern template class MultipleBasinForceField<SimulatorTraits<double, UnlimitedBoundary >>; extern template class MultipleBasinForceField<SimulatorTraits<float, UnlimitedBoundary >>; extern template class MultipleBasinForceField<SimulatorTraits<double, CuboidalPeriodicBoundary>>; extern template class MultipleBasinForceField<SimulatorTraits<float, CuboidalPeriodicBoundary>>; #endif } // mjolnir #endif// MJOLNIR_CORE_MULTIPLE_BASIN_FORCE_FIELD_HPP <|endoftext|>
<commit_before>void SETUP() { CheckLoadLibrary("libPWG2spectra"); // Set the include paths gROOT->ProcessLine(".include PWG2spectra/SPECTRA"); // Set our location, so that other packages can find us gSystem->Setenv("PWG2spectra_INCLUDE", "PWG2spectra"); } Int_t CheckLoadLibrary(const char* library) { // checks if a library is already loaded, if not loads the library if (strlen(gSystem->GetLibraries(Form("%s.so", library), "", kFALSE)) > 0) return 1; return gSystem->Load(library); } <commit_msg>attempting to add support for par arhcives in forward<commit_after>void SETUP() { CheckLoadLibrary("libPWG2forward"); // Set the include paths gROOT->ProcessLine(".include PWG2forward/FORWARD"); // Set our location, so that other packages can find us gSystem->Setenv("PWG2forward_INCLUDE", "PWG2forward"); } Int_t CheckLoadLibrary(const char* library) { // checks if a library is already loaded, if not loads the library if (strlen(gSystem->GetLibraries(Form("%s.so", library), "", kFALSE)) > 0) return 1; return gSystem->Load(library); } <|endoftext|>
<commit_before>#include "KCClient.h" typedef KCClient C; const std::map<QString, C::processFunc> C::processFuncs = { // Global info ------------------------------------------------------------- // Ships { "/kcsapi/api_get_master/ship", &C::_processMasterShipsData }, // Sortie maps { "/kcsapi/api_get_master/mapinfo", 0 }, // Expeditions { "/kcsapi/api_get_master/mission", 0 }, // Member info ------------------------------------------------------------- { "/kcsapi/api_get_member/basic", 0 }, { "/kcsapi/api_get_member/record", 0 }, // Items { "/kcsapi/api_get_member/slotitem", 0 }, // Current items { "/kcsapi/api_get_member/useitem", 0 }, // Ships { "/kcsapi/api_get_memeber/ship", &C::_processPlayerShipsData }, { "/kcsapi/api_get_member/ship2", 0 }, // TODO { "/kcsapi/api_get_member/ship3", 0 }, // TODO { "/kcsapi/api_get_member/material", 0 }, // Resources // Various statuses { "/kcsapi/api_get_member/deck", &C::_processPlayerFleetsData }, // Fleets { "/kcsapi/api_get_member/ndock", &C::_processPlayerRepairsData }, // Dock (repair) { "/kcsapi/api_get_member/kdock", &C::_processPlayerConstructionsData }, // Construction // Quests { "/kcsapi/api_get_member/questlist", 0 }, { "/kcsapi/api_req_quest/start", 0 }, // Start tracking { "/kcsapi/api_req_quest/stop", 0 }, // Stop tracking { "/kcsapi/api_req_quest/clearitemget", 0 }, // Finish quest // Actions { "/kcsapi/api_req_kaisou/powerup", 0 }, // Modernization { "/kcsapi/api_req_kaisou/remodeling", 0 }, { "/kcsapi/api_req_hokyu/charge", 0 }, // TODO (Resupplying) { "/kcsapi/api_get_member/actionlog", 0 }, { "/kcsapi/api_req_hensei/change", 0 }, // Swap out ships // ??? { "/kcsapi/api_get_member/deck_port", 0 }, // Battle info ------------------------------------------------------------- // Expeditions { "/kcsapi/api_req_mission/start", 0 }, { "/kcsapi/api_req_mission/result", 0 }, // Sorties { "/kcsapi/api_req_map/start", 0 }, // Start a sortie { "/kcsapi/api_req_sortie/battle", 0 }, { "/kcsapi/api_req_battle_midnight/battle", 0 }, { "/kcsapi/api_req_sortie/battleresult", 0 }, // Practice { "/kcsapi/api_get_member/practice", 0 }, { "/kcsapi/api_req_member/getothersdeck", 0 }, { "/kcsapi/api_req_practice/battle", 0 }, { "/kcsapi/api_req_practice/midnight_battle", 0 }, { "/kcsapi/api_req_practice/battle_result", 0 }, // Miscellaneous ------------------------------------------------------------ { "/kcsapi/api_auth_member/logincheck", 0 }, }; <commit_msg>add a bunch more API endpoints<commit_after>#include "KCClient.h" typedef KCClient C; const std::map<QString, C::processFunc> C::processFuncs = { // Global info ------------------------------------------------------------- // Ships { "/kcsapi/api_get_master/ship", &C::_processMasterShipsData }, // Sortie maps { "/kcsapi/api_get_master/mapinfo", 0 }, { "/kcsapi/api_get_master/mapcell", 0 }, // Expeditions { "/kcsapi/api_get_master/mission", 0 }, // Member info ------------------------------------------------------------- { "/kcsapi/api_get_member/basic", 0 }, { "/kcsapi/api_get_member/record", 0 }, // Items { "/kcsapi/api_get_member/slotitem", 0 }, // Current items { "/kcsapi/api_get_member/unsetslot", 0 }, // Remove item { "/kcsapi/api_get_member/useitem", 0 }, // Ships { "/kcsapi/api_get_memeber/ship", &C::_processPlayerShipsData }, { "/kcsapi/api_get_member/ship2", 0 }, // TODO { "/kcsapi/api_get_member/ship3", 0 }, // TODO { "/kcsapi/api_get_member/material", 0 }, // Resources // Various statuses { "/kcsapi/api_get_member/deck", &C::_processPlayerFleetsData }, // Fleets { "/kcsapi/api_get_member/ndock", &C::_processPlayerRepairsData }, // Dock (repair) { "/kcsapi/api_get_member/kdock", &C::_processPlayerConstructionsData }, // Construction // Quests { "/kcsapi/api_get_member/questlist", 0 }, { "/kcsapi/api_req_quest/start", 0 }, // Start tracking { "/kcsapi/api_req_quest/stop", 0 }, // Stop tracking { "/kcsapi/api_req_quest/clearitemget", 0 }, // Finish quest // Actions { "/kcsapi/api_req_kaisou/powerup", 0 }, // Modernization { "/kcsapi/api_req_kaisou/remodeling", 0 }, { "/kcsapi/api_req_hokyu/charge", 0 }, // TODO (Resupplying) { "/kcsapi/api_req_hensei/change", 0 }, // Swap out ships { "/kcsapi/api_req_nyukyo/start", 0 }, // Start a bath { "/kcsapi/api_req_nyukyo/speedchange", 0 }, // Buckets are cool { "/kcsapi/api_req_kousyou/createship", 0 }, { "/kcsapi/api_req_kousyou/createship_speedchange", 0 }, // FLAME { "/kcsapi/api_req_kousyou/getship", 0 }, // Finish construction { "/kcsapi/api_req_kousyou/destroyship", 0 }, { "/kcsapi/api_req_kousyou/createitem", 0 }, { "/kcsapi/api_req_kousyou/destroyitem2", 0 }, { "/kcsapi/api_get_member/actionlog", 0 }, // Furniture { "/kcsapi/api_req_furniture/change", 0 }, // Store { "/kcsapi/api_get_master/payitem", 0 }, // Load the pay shop { "/kcsapi/api_req_furniture/buy", 0 }, // ??? { "/kcsapi/api_get_member/deck_port", 0 }, // Battle info ------------------------------------------------------------- // Expeditions { "/kcsapi/api_req_mission/start", 0 }, { "/kcsapi/api_req_mission/result", 0 }, // Sorties { "/kcsapi/api_req_map/start", 0 }, // Start a sortie { "/kcsapi/api_req_map/next", 0 }, // Next cell to go to { "/kcsapi/api_req_sortie/battle", 0 }, { "/kcsapi/api_req_battle_midnight/battle", 0 }, { "/kcsapi/api_req_sortie/battleresult", 0 }, // Practice { "/kcsapi/api_get_member/practice", 0 }, { "/kcsapi/api_req_member/getothersdeck", 0 }, { "/kcsapi/api_req_practice/battle", 0 }, { "/kcsapi/api_req_practice/midnight_battle", 0 }, { "/kcsapi/api_req_practice/battle_result", 0 }, // Miscellaneous ------------------------------------------------------------ { "/kcsapi/api_auth_member/logincheck", 0 }, }; <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkSocketCommunicator.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 AUTHORS 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 "vtkSocketCommunicator.h" #include "vtkSocketController.h" #include "vtkObjectFactory.h" #ifdef _WIN32 #define WSA_VERSION MAKEWORD(1,1) #define vtkCloseSocketMacro(sock) (closesocket(sock)) #else #define vtkCloseSocketMacro(sock) (close(sock)) #endif //------------------------------------------------------------------------------ vtkSocketCommunicator* vtkSocketCommunicator::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkSocketCommunicator"); if(ret) { return (vtkSocketCommunicator*)ret; } // If the factory was unable to create the object, then create it here. return new vtkSocketCommunicator; } //---------------------------------------------------------------------------- vtkSocketCommunicator::vtkSocketCommunicator() { this->Socket = -1; this->IsConnected = 0; this->NumberOfProcesses = 2; this->SwapBytesInReceivedData = 0; } //---------------------------------------------------------------------------- vtkSocketCommunicator::~vtkSocketCommunicator() { if (this->IsConnected) { vtkCloseSocketMacro(this->Socket); } } //---------------------------------------------------------------------------- void vtkSocketCommunicator::PrintSelf(ostream& os, vtkIndent indent) { vtkCommunicator::PrintSelf(os,indent); os << indent << "SwapBytesInReceivedData: " << this->SwapBytesInReceivedData << endl; } static inline int checkForError(int id, int maxId) { if ( id == 0 ) { vtkGenericWarningMacro("Can not connect to myself!"); return 1; } else if ( id >= maxId ) { vtkGenericWarningMacro("No port for process " << id << " exists."); return 1; } return 0; } template <class T> static int SendMessage(T* data, int length, int tag, int sock) { // Need to check the return value of these send(sock, (char *)&tag, sizeof(int), 0); int totalLength = length*sizeof(T); int sent; sent = send(sock, (char*)data, totalLength, 0); if (sent == -1) { vtkGenericWarningMacro("Could not send message."); return 0; } while ( sent < totalLength ) { sent += send ( sock, (char*)data+sent, totalLength-sent, 0 ); if (sent == -1) { vtkGenericWarningMacro("Could not send message."); return 0; } } return 1; } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Send(int *data, int length, int remoteProcessId, int tag) { if ( checkForError(remoteProcessId, this->NumberOfProcesses) ) { return 0; } return SendMessage(data, length, tag, this->Socket); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Send(unsigned long *data, int length, int remoteProcessId, int tag) { if ( checkForError(remoteProcessId, this->NumberOfProcesses) ) { return 0; } return SendMessage(data, length, tag, this->Socket); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Send(char *data, int length, int remoteProcessId, int tag) { if ( checkForError(remoteProcessId, this->NumberOfProcesses) ) { return 0; } return SendMessage(data, length, tag, this->Socket); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Send(float *data, int length, int remoteProcessId, int tag) { if ( checkForError(remoteProcessId, this->NumberOfProcesses) ) { return 0; } return SendMessage(data, length, tag, this->Socket); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Send(double *data, int length, int remoteProcessId, int tag) { if ( checkForError(remoteProcessId, this->NumberOfProcesses) ) { return 0; } return SendMessage(data, length, tag, this->Socket); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::ReceiveMessage( char *data, int size, int length, int tag ) { int recvTag=-1; // Need to check the return value of these recv( this->Socket, (char *)&recvTag, sizeof(int), MSG_PEEK ); if ( this->SwapBytesInReceivedData ) { vtkSwap4( &recvTag ); } if ( recvTag != tag ) { return 0; } if (recv( this->Socket, (char *)&recvTag, sizeof(int), 0 ) == -1) { vtkErrorMacro("Could not receive message."); return 0; } int totalLength = length * size; int received; received = recv( this->Socket, data, totalLength, 0 ); if (received == -1) { vtkErrorMacro("Could not receive message."); return 0; } while ( received < totalLength ) { received += recv( this->Socket, &(data[received]), totalLength-received, 0 ); if (received == -1) { vtkErrorMacro("Could not receive message."); return 0; } } // Unless we're dealing with chars, then check byte ordering // This is really bad and should probably use some enum for types if (this->SwapBytesInReceivedData) { if (size == 4) { vtkSwap4Range(data, length); } else { vtkSwap8Range(data, length); } } return 1; } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Receive(int *data, int length, int remoteProcessId, int tag) { if ( checkForError(remoteProcessId, this->NumberOfProcesses) ) { return 0; } int retval = ReceiveMessage( (char *)data, sizeof(int), length, tag ); if ( tag == vtkMultiProcessController::RMI_TAG ) { data[2] = 1; } return retval; } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Receive(unsigned long *data, int length, int remoteProcessId, int tag) { if ( checkForError(remoteProcessId, this->NumberOfProcesses) ) { return 0; } return ReceiveMessage( (char *)data, sizeof(unsigned long), length, tag ); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Receive(char *data, int length, int remoteProcessId, int tag) { if ( checkForError(remoteProcessId, this->NumberOfProcesses) ) { return 0; } return ReceiveMessage( (char *)data, sizeof(char), length, tag); } int vtkSocketCommunicator::Receive(float *data, int length, int remoteProcessId, int tag) { if ( checkForError(remoteProcessId, this->NumberOfProcesses) ) { return 0; } return ReceiveMessage( (char *)data, sizeof(float), length, tag); } int vtkSocketCommunicator::Receive(double *data, int length, int remoteProcessId, int tag) { if ( checkForError(remoteProcessId, this->NumberOfProcesses) ) { return 0; } return ReceiveMessage( (char *)data, sizeof(double), length, tag); } int vtkSocketCommunicator::WaitForConnection(int port, int timeout) { if ( this->IsConnected ) { vtkErrorMacro("Port " << 1 << " is occupied."); return 0; } int sock = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in server; server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons(port); if ( bind(sock, (sockaddr *)&server, sizeof(server)) ) { vtkErrorMacro("Can not bind socket to port " << port); return 0; } listen(sock,1); this->Socket = accept(sock, 0, 0); if ( this->Socket == -1 ) { vtkErrorMacro("Error in accept."); return 0; } vtkCloseSocketMacro(sock); this->IsConnected = 1; // Handshake to determine if the client machine has the same endianness char clientIsBE; if ( !ReceiveMessage( &clientIsBE, sizeof(char), 1, vtkSocketController::ENDIAN_TAG) ) { vtkErrorMacro("Endian handshake failed."); return 0; } vtkDebugMacro(<< "Client is " << ( clientIsBE ? "big" : "little" ) << "-endian"); #ifdef VTK_WORDS_BIGENDIAN char IAmBE = 1; #else char IAmBE = 0; #endif vtkDebugMacro(<< "I am " << ( IAmBE ? "big" : "little" ) << "-endian"); SendMessage( &IAmBE, 1, vtkSocketController::ENDIAN_TAG, this->Socket ); if ( clientIsBE != IAmBE ) { this->SwapBytesInReceivedData = 1; } return 1; } void vtkSocketCommunicator::CloseConnection() { if ( this->IsConnected ) { vtkCloseSocketMacro(this->Socket); this->IsConnected = 0; } } int vtkSocketCommunicator::ConnectTo ( char* hostName, int port ) { if ( this->IsConnected ) { vtkErrorMacro("Communicator port " << 1 << " is occupied."); return 0; } struct hostent* hp; hp = gethostbyname(hostName); if (!hp) { unsigned long addr = inet_addr(hostName); hp = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET); } if (!hp) { vtkErrorMacro("Unknown host: " << hostName); return 0; } this->Socket = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in name; name.sin_family = AF_INET; memcpy(&name.sin_addr, hp->h_addr, hp->h_length); name.sin_port = htons(port); if( connect(this->Socket, (sockaddr *)&name, sizeof(name)) < 0) { vtkErrorMacro("Can not connect to " << hostName << " on port " << port); return 0; } vtkDebugMacro("Connected to " << hostName << " on port " << port); this->IsConnected = 1; // Handshake to determine if the server machine has the same endianness #ifdef VTK_WORDS_BIGENDIAN char IAmBE = 1; #else char IAmBE = 0; #endif vtkDebugMacro(<< "I am " << ( IAmBE ? "big" : "little" ) << "-endian"); SendMessage( &IAmBE, 1, vtkSocketController::ENDIAN_TAG, this->Socket ); char serverIsBE; if ( !ReceiveMessage( &serverIsBE, sizeof(char), 1, vtkSocketController::ENDIAN_TAG ) ) { vtkErrorMacro("Endian handshake failed."); return 0; } vtkDebugMacro(<< "Server is " << ( serverIsBE ? "big" : "little" ) << "-endian"); if ( serverIsBE != IAmBE ) { this->SwapBytesInReceivedData = 1; } return 1; } <commit_msg>ENH added support for vtkDataArray<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkSocketCommunicator.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 AUTHORS 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 "vtkSocketCommunicator.h" #include "vtkSocketController.h" #include "vtkObjectFactory.h" #ifdef _WIN32 #define WSA_VERSION MAKEWORD(1,1) #define vtkCloseSocketMacro(sock) (closesocket(sock)) #else #define vtkCloseSocketMacro(sock) (close(sock)) #endif //------------------------------------------------------------------------------ vtkSocketCommunicator* vtkSocketCommunicator::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkSocketCommunicator"); if(ret) { return (vtkSocketCommunicator*)ret; } // If the factory was unable to create the object, then create it here. return new vtkSocketCommunicator; } //---------------------------------------------------------------------------- vtkSocketCommunicator::vtkSocketCommunicator() { this->Socket = -1; this->IsConnected = 0; this->NumberOfProcesses = 2; this->SwapBytesInReceivedData = 0; } //---------------------------------------------------------------------------- vtkSocketCommunicator::~vtkSocketCommunicator() { if (this->IsConnected) { vtkCloseSocketMacro(this->Socket); } } //---------------------------------------------------------------------------- void vtkSocketCommunicator::PrintSelf(ostream& os, vtkIndent indent) { vtkCommunicator::PrintSelf(os,indent); os << indent << "SwapBytesInReceivedData: " << this->SwapBytesInReceivedData << endl; } static inline int checkForError(int id, int maxId) { if ( id == 0 ) { vtkGenericWarningMacro("Can not connect to myself!"); return 1; } else if ( id >= maxId ) { vtkGenericWarningMacro("No port for process " << id << " exists."); return 1; } return 0; } template <class T> static int SendMessage(T* data, int length, int tag, int sock) { // Need to check the return value of these send(sock, (char *)&tag, sizeof(int), 0); int totalLength = length*sizeof(T); int sent; sent = send(sock, (char*)data, totalLength, 0); if (sent == -1) { vtkGenericWarningMacro("Could not send message."); return 0; } while ( sent < totalLength ) { sent += send ( sock, (char*)data+sent, totalLength-sent, 0 ); if (sent == -1) { vtkGenericWarningMacro("Could not send message."); return 0; } } return 1; } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Send(int *data, int length, int remoteProcessId, int tag) { if ( checkForError(remoteProcessId, this->NumberOfProcesses) ) { return 0; } return SendMessage(data, length, tag, this->Socket); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Send(unsigned long *data, int length, int remoteProcessId, int tag) { if ( checkForError(remoteProcessId, this->NumberOfProcesses) ) { return 0; } return SendMessage(data, length, tag, this->Socket); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Send(char *data, int length, int remoteProcessId, int tag) { if ( checkForError(remoteProcessId, this->NumberOfProcesses) ) { return 0; } return SendMessage(data, length, tag, this->Socket); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Send(unsigned char *data, int length, int remoteProcessId, int tag) { if ( checkForError(remoteProcessId, this->NumberOfProcesses) ) { return 0; } return SendMessage(data, length, tag, this->Socket); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Send(float *data, int length, int remoteProcessId, int tag) { if ( checkForError(remoteProcessId, this->NumberOfProcesses) ) { return 0; } return SendMessage(data, length, tag, this->Socket); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Send(double *data, int length, int remoteProcessId, int tag) { if ( checkForError(remoteProcessId, this->NumberOfProcesses) ) { return 0; } return SendMessage(data, length, tag, this->Socket); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Send(vtkIdType *data, int length, int remoteProcessId, int tag) { if ( checkForError(remoteProcessId, this->NumberOfProcesses) ) { return 0; } return SendMessage(data, length, tag, this->Socket); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::ReceiveMessage( char *data, int size, int length, int tag ) { int recvTag=-1; // Need to check the return value of these recv( this->Socket, (char *)&recvTag, sizeof(int), MSG_PEEK ); if ( this->SwapBytesInReceivedData ) { vtkSwap4( &recvTag ); } if ( recvTag != tag ) { return 0; } if (recv( this->Socket, (char *)&recvTag, sizeof(int), 0 ) == -1) { vtkErrorMacro("Could not receive message."); return 0; } int totalLength = length * size; int received; received = recv( this->Socket, data, totalLength, 0 ); if (received == -1) { vtkErrorMacro("Could not receive message."); return 0; } while ( received < totalLength ) { received += recv( this->Socket, &(data[received]), totalLength-received, 0 ); if (received == -1) { vtkErrorMacro("Could not receive message."); return 0; } } // Unless we're dealing with chars, then check byte ordering // This is really bad and should probably use some enum for types if (this->SwapBytesInReceivedData) { if (size == 4) { vtkSwap4Range(data, length); } else { vtkSwap8Range(data, length); } } return 1; } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Receive(int *data, int length, int remoteProcessId, int tag) { if ( checkForError(remoteProcessId, this->NumberOfProcesses) ) { return 0; } int retval = ReceiveMessage( (char *)data, sizeof(int), length, tag ); if ( tag == vtkMultiProcessController::RMI_TAG ) { data[2] = 1; } return retval; } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Receive(unsigned long *data, int length, int remoteProcessId, int tag) { if ( checkForError(remoteProcessId, this->NumberOfProcesses) ) { return 0; } return ReceiveMessage( (char *)data, sizeof(unsigned long), length, tag ); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Receive(char *data, int length, int remoteProcessId, int tag) { if ( checkForError(remoteProcessId, this->NumberOfProcesses) ) { return 0; } return ReceiveMessage( (char *)data, sizeof(char), length, tag); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Receive(unsigned char *data, int length, int remoteProcessId, int tag) { if ( checkForError(remoteProcessId, this->NumberOfProcesses) ) { return 0; } return ReceiveMessage( (char *)data, sizeof(char), length, tag); } int vtkSocketCommunicator::Receive(float *data, int length, int remoteProcessId, int tag) { if ( checkForError(remoteProcessId, this->NumberOfProcesses) ) { return 0; } return ReceiveMessage( (char *)data, sizeof(float), length, tag); } int vtkSocketCommunicator::Receive(double *data, int length, int remoteProcessId, int tag) { if ( checkForError(remoteProcessId, this->NumberOfProcesses) ) { return 0; } return ReceiveMessage( (char *)data, sizeof(double), length, tag); } int vtkSocketCommunicator::Receive(vtkIdType *data, int length, int remoteProcessId, int tag) { if ( checkForError(remoteProcessId, this->NumberOfProcesses) ) { return 0; } return ReceiveMessage( (char *)data, sizeof(vtkIdType), length, tag); } int vtkSocketCommunicator::WaitForConnection(int port, int timeout) { if ( this->IsConnected ) { vtkErrorMacro("Port " << 1 << " is occupied."); return 0; } int sock = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in server; server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons(port); if ( bind(sock, (sockaddr *)&server, sizeof(server)) ) { vtkErrorMacro("Can not bind socket to port " << port); return 0; } listen(sock,1); this->Socket = accept(sock, 0, 0); if ( this->Socket == -1 ) { vtkErrorMacro("Error in accept."); return 0; } vtkCloseSocketMacro(sock); this->IsConnected = 1; // Handshake to determine if the client machine has the same endianness char clientIsBE; if ( !ReceiveMessage( &clientIsBE, sizeof(char), 1, vtkSocketController::ENDIAN_TAG) ) { vtkErrorMacro("Endian handshake failed."); return 0; } vtkDebugMacro(<< "Client is " << ( clientIsBE ? "big" : "little" ) << "-endian"); #ifdef VTK_WORDS_BIGENDIAN char IAmBE = 1; #else char IAmBE = 0; #endif vtkDebugMacro(<< "I am " << ( IAmBE ? "big" : "little" ) << "-endian"); SendMessage( &IAmBE, 1, vtkSocketController::ENDIAN_TAG, this->Socket ); if ( clientIsBE != IAmBE ) { this->SwapBytesInReceivedData = 1; } return 1; } void vtkSocketCommunicator::CloseConnection() { if ( this->IsConnected ) { vtkCloseSocketMacro(this->Socket); this->IsConnected = 0; } } int vtkSocketCommunicator::ConnectTo ( char* hostName, int port ) { if ( this->IsConnected ) { vtkErrorMacro("Communicator port " << 1 << " is occupied."); return 0; } struct hostent* hp; hp = gethostbyname(hostName); if (!hp) { unsigned long addr = inet_addr(hostName); hp = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET); } if (!hp) { vtkErrorMacro("Unknown host: " << hostName); return 0; } this->Socket = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in name; name.sin_family = AF_INET; memcpy(&name.sin_addr, hp->h_addr, hp->h_length); name.sin_port = htons(port); if( connect(this->Socket, (sockaddr *)&name, sizeof(name)) < 0) { vtkErrorMacro("Can not connect to " << hostName << " on port " << port); return 0; } vtkDebugMacro("Connected to " << hostName << " on port " << port); this->IsConnected = 1; // Handshake to determine if the server machine has the same endianness #ifdef VTK_WORDS_BIGENDIAN char IAmBE = 1; #else char IAmBE = 0; #endif vtkDebugMacro(<< "I am " << ( IAmBE ? "big" : "little" ) << "-endian"); SendMessage( &IAmBE, 1, vtkSocketController::ENDIAN_TAG, this->Socket ); char serverIsBE; if ( !ReceiveMessage( &serverIsBE, sizeof(char), 1, vtkSocketController::ENDIAN_TAG ) ) { vtkErrorMacro("Endian handshake failed."); return 0; } vtkDebugMacro(<< "Server is " << ( serverIsBE ? "big" : "little" ) << "-endian"); if ( serverIsBE != IAmBE ) { this->SwapBytesInReceivedData = 1; } return 1; } <|endoftext|>
<commit_before>#include "routing/edge_estimator.hpp" #include "routing/routing_helpers.hpp" #include "traffic/traffic_info.hpp" #include "base/assert.hpp" #include <algorithm> #include <unordered_map> using namespace routing; using namespace std; using namespace traffic; namespace { enum class Purpose { Weight, ETA }; double TimeBetweenSec(m2::PointD const & from, m2::PointD const & to, double speedMpS) { CHECK_GREATER(speedMpS, 0.0, ("from:", MercatorBounds::ToLatLon(from), "to:", MercatorBounds::ToLatLon(to))); double const distanceM = MercatorBounds::DistanceOnEarth(from, to); return distanceM / speedMpS; } double CalcTrafficFactor(SpeedGroup speedGroup) { double constexpr kImpossibleDrivingFactor = 1e4; if (speedGroup == SpeedGroup::TempBlock) return kImpossibleDrivingFactor; double const percentage = 0.01 * static_cast<double>(kSpeedGroupThresholdPercentage[static_cast<size_t>(speedGroup)]); CHECK_GREATER(percentage, 0.0, ("Speed group:", speedGroup)); return 1.0 / percentage; } double GetPedestrianClimbPenalty(double tangent) { if (tangent < 0) return 1.0 + 2.0 * (-tangent); return 1.0 + 5.0 * tangent; } double GetBicycleClimbPenalty(double tangent) { if (tangent <= 0) return 1.0; return 1.0 + 10.0 * tangent; } double GetCarClimbPenalty(double /* tangent */) { return 1.0; } template <typename GetClimbPenalty> double CalcClimbSegment(Purpose purpose, Segment const & segment, RoadGeometry const & road, GetClimbPenalty && getClimbPenalty) { Junction const & from = road.GetJunction(segment.GetPointId(false /* front */)); Junction const & to = road.GetJunction(segment.GetPointId(true /* front */)); VehicleModelInterface::SpeedKMpH const & speed = road.GetSpeed(segment.IsForward()); double const distance = MercatorBounds::DistanceOnEarth(from.GetPoint(), to.GetPoint()); double const speedMpS = KMPH2MPS(purpose == Purpose::Weight ? speed.m_weight : speed.m_eta); CHECK_GREATER(speedMpS, 0.0, ()); double const timeSec = distance / speedMpS; if (base::AlmostEqualAbs(distance, 0.0, 0.1)) return timeSec; double const altitudeDiff = static_cast<double>(to.GetAltitude()) - static_cast<double>(from.GetAltitude()); return timeSec * getClimbPenalty(altitudeDiff / distance); } } // namespace namespace routing { // EdgeEstimator ----------------------------------------------------------------------------------- EdgeEstimator::EdgeEstimator(double maxWeightSpeedKMpH, double offroadSpeedKMpH) : m_maxWeightSpeedMpS(KMPH2MPS(maxWeightSpeedKMpH)), m_offroadSpeedMpS(KMPH2MPS(offroadSpeedKMpH)) { CHECK_GREATER(m_offroadSpeedMpS, 0.0, ()); CHECK_GREATER_OR_EQUAL(m_maxWeightSpeedMpS, m_offroadSpeedMpS, ()); } double EdgeEstimator::CalcHeuristic(m2::PointD const & from, m2::PointD const & to) const { return TimeBetweenSec(from, to, m_maxWeightSpeedMpS); } double EdgeEstimator::CalcLeapWeight(m2::PointD const & from, m2::PointD const & to) const { // Let us assume for the time being that // leap edges will be added with a half of max speed. // @TODO(bykoianko) It's necessary to gather statistics to calculate better factor(s) instead of // one below. return TimeBetweenSec(from, to, m_maxWeightSpeedMpS / 2.0); } double EdgeEstimator::CalcOffroadWeight(m2::PointD const & from, m2::PointD const & to) const { return TimeBetweenSec(from, to, m_offroadSpeedMpS); } // PedestrianEstimator ----------------------------------------------------------------------------- class PedestrianEstimator final : public EdgeEstimator { public: PedestrianEstimator(double maxWeightSpeedKMpH, double offroadSpeedKMpH) : EdgeEstimator(maxWeightSpeedKMpH, offroadSpeedKMpH) { } // EdgeEstimator overrides: double GetUTurnPenalty() const override { return 0.0 /* seconds */; } bool LeapIsAllowed(NumMwmId /* mwmId */) const override { return false; } double CalcSegmentWeight(Segment const & segment, RoadGeometry const & road) const override { return CalcClimbSegment(Purpose::Weight, segment, road, GetPedestrianClimbPenalty); } double CalcSegmentETA(Segment const & segment, RoadGeometry const & road) const override { return CalcClimbSegment(Purpose::ETA, segment, road, GetPedestrianClimbPenalty); } }; // BicycleEstimator -------------------------------------------------------------------------------- class BicycleEstimator final : public EdgeEstimator { public: BicycleEstimator(double maxWeightSpeedKMpH, double offroadSpeedKMpH) : EdgeEstimator(maxWeightSpeedKMpH, offroadSpeedKMpH) { } // EdgeEstimator overrides: double GetUTurnPenalty() const override { return 20.0 /* seconds */; } bool LeapIsAllowed(NumMwmId /* mwmId */) const override { return false; } double CalcSegmentWeight(Segment const & segment, RoadGeometry const & road) const override { return CalcClimbSegment(Purpose::Weight, segment, road, GetBicycleClimbPenalty); } double CalcSegmentETA(Segment const & segment, RoadGeometry const & road) const override { return CalcClimbSegment(Purpose::ETA, segment, road, GetBicycleClimbPenalty); } }; // CarEstimator ------------------------------------------------------------------------------------ class CarEstimator final : public EdgeEstimator { public: CarEstimator(shared_ptr<TrafficStash> trafficStash, double maxWeightSpeedKMpH, double offroadSpeedKMpH); // EdgeEstimator overrides: double CalcSegmentWeight(Segment const & segment, RoadGeometry const & road) const override; double CalcSegmentETA(Segment const & segment, RoadGeometry const & road) const override; double GetUTurnPenalty() const override; bool LeapIsAllowed(NumMwmId mwmId) const override; private: double CalcSegment(Purpose purpose, Segment const & segment, RoadGeometry const & road) const; shared_ptr<TrafficStash> m_trafficStash; }; CarEstimator::CarEstimator(shared_ptr<TrafficStash> trafficStash, double maxWeightSpeedKMpH, double offroadSpeedKMpH) : EdgeEstimator(maxWeightSpeedKMpH, offroadSpeedKMpH), m_trafficStash(move(trafficStash)) { } double CarEstimator::CalcSegmentWeight(Segment const & segment, RoadGeometry const & road) const { return CalcSegment(Purpose::Weight, segment, road); } double CarEstimator::CalcSegmentETA(Segment const & segment, RoadGeometry const & road) const { return CalcSegment(Purpose::ETA, segment, road); } double CarEstimator::GetUTurnPenalty() const { // Adds 2 minutes penalty for U-turn. The value is quite arbitrary // and needs to be properly selected after a number of real-world // experiments. return 2 * 60; // seconds } bool CarEstimator::LeapIsAllowed(NumMwmId mwmId) const { return !m_trafficStash->Has(mwmId); } double CarEstimator::CalcSegment(Purpose purpose, Segment const & segment, RoadGeometry const & road) const { // Current time estimation are too optimistic. // Need more accurate tuning: traffic lights, traffic jams, road models and so on. // Add some penalty to make estimation of a more realistic. // TODO: make accurate tuning, remove penalty. double constexpr kTimePenalty = 1.8; double result = CalcClimbSegment(purpose, segment, road, GetCarClimbPenalty); if (m_trafficStash) { SpeedGroup const speedGroup = m_trafficStash->GetSpeedGroup(segment); ASSERT_LESS(speedGroup, SpeedGroup::Count, ()); double const trafficFactor = CalcTrafficFactor(speedGroup); result *= trafficFactor; if (speedGroup != SpeedGroup::Unknown && speedGroup != SpeedGroup::G5) result *= kTimePenalty; } return result; } // EdgeEstimator ----------------------------------------------------------------------------------- // static shared_ptr<EdgeEstimator> EdgeEstimator::Create(VehicleType vehicleType, double maxWeighSpeedKMpH, double offroadSpeedKMpH, shared_ptr<TrafficStash> trafficStash) { switch (vehicleType) { case VehicleType::Pedestrian: case VehicleType::Transit: return make_shared<PedestrianEstimator>(maxWeighSpeedKMpH, offroadSpeedKMpH); case VehicleType::Bicycle: return make_shared<BicycleEstimator>(maxWeighSpeedKMpH, offroadSpeedKMpH); case VehicleType::Car: return make_shared<CarEstimator>(trafficStash, maxWeighSpeedKMpH, offroadSpeedKMpH); case VehicleType::Count: CHECK(false, ("Can't create EdgeEstimator for", vehicleType)); return nullptr; } UNREACHABLE(); } // static shared_ptr<EdgeEstimator> EdgeEstimator::Create(VehicleType vehicleType, VehicleModelInterface const & vehicleModel, shared_ptr<TrafficStash> trafficStash) { return Create(vehicleType, vehicleModel.GetMaxWeightSpeed(), vehicleModel.GetOffroadSpeed(), trafficStash); } } // namespace routing <commit_msg>[routing] Adding weight for graph and eta in case of going up for pedestrian and bicycle routing.<commit_after>#include "routing/edge_estimator.hpp" #include "routing/routing_helpers.hpp" #include "traffic/traffic_info.hpp" #include "indexer/feature_altitude.hpp" #include "base/assert.hpp" #include <algorithm> #include <unordered_map> using namespace routing; using namespace std; using namespace traffic; namespace { feature::TAltitude constexpr mountainSicknessAltitudeM = 3000; enum class Purpose { Weight, ETA }; double TimeBetweenSec(m2::PointD const & from, m2::PointD const & to, double speedMpS) { CHECK_GREATER(speedMpS, 0.0, ("from:", MercatorBounds::ToLatLon(from), "to:", MercatorBounds::ToLatLon(to))); double const distanceM = MercatorBounds::DistanceOnEarth(from, to); return distanceM / speedMpS; } double CalcTrafficFactor(SpeedGroup speedGroup) { double constexpr kImpossibleDrivingFactor = 1e4; if (speedGroup == SpeedGroup::TempBlock) return kImpossibleDrivingFactor; double const percentage = 0.01 * static_cast<double>(kSpeedGroupThresholdPercentage[static_cast<size_t>(speedGroup)]); CHECK_GREATER(percentage, 0.0, ("Speed group:", speedGroup)); return 1.0 / percentage; } double GetPedestrianClimbPenalty(double tangent, feature::TAltitude altitudeM) { if (tangent <= 0) // Descent return 1.0 + 2.0 * (-tangent); // Climb. if (altitudeM < mountainSicknessAltitudeM) return 1.0 + 10.0 * tangent; else return 1.0 + 30.0 * tangent; } double GetBicycleClimbPenalty(double tangent, feature::TAltitude altitudeM) { if (tangent <= 0) // Descent return 1.0; // Climb. if (altitudeM < mountainSicknessAltitudeM) return 1.0 + 30.0 * tangent; else return 1.0 + 50.0 * tangent; } double GetCarClimbPenalty(double /* tangent */, feature::TAltitude /* altitude */) { return 1.0; } template <typename GetClimbPenalty> double CalcClimbSegment(Purpose purpose, Segment const & segment, RoadGeometry const & road, GetClimbPenalty && getClimbPenalty) { Junction const & from = road.GetJunction(segment.GetPointId(false /* front */)); Junction const & to = road.GetJunction(segment.GetPointId(true /* front */)); VehicleModelInterface::SpeedKMpH const & speed = road.GetSpeed(segment.IsForward()); double const distance = MercatorBounds::DistanceOnEarth(from.GetPoint(), to.GetPoint()); double const speedMpS = KMPH2MPS(purpose == Purpose::Weight ? speed.m_weight : speed.m_eta); CHECK_GREATER(speedMpS, 0.0, ()); double const timeSec = distance / speedMpS; if (base::AlmostEqualAbs(distance, 0.0, 0.1)) return timeSec; double const altitudeDiff = static_cast<double>(to.GetAltitude()) - static_cast<double>(from.GetAltitude()); return timeSec * getClimbPenalty(altitudeDiff / distance, to.GetAltitude()); } } // namespace namespace routing { // EdgeEstimator ----------------------------------------------------------------------------------- EdgeEstimator::EdgeEstimator(double maxWeightSpeedKMpH, double offroadSpeedKMpH) : m_maxWeightSpeedMpS(KMPH2MPS(maxWeightSpeedKMpH)), m_offroadSpeedMpS(KMPH2MPS(offroadSpeedKMpH)) { CHECK_GREATER(m_offroadSpeedMpS, 0.0, ()); CHECK_GREATER_OR_EQUAL(m_maxWeightSpeedMpS, m_offroadSpeedMpS, ()); } double EdgeEstimator::CalcHeuristic(m2::PointD const & from, m2::PointD const & to) const { return TimeBetweenSec(from, to, m_maxWeightSpeedMpS); } double EdgeEstimator::CalcLeapWeight(m2::PointD const & from, m2::PointD const & to) const { // Let us assume for the time being that // leap edges will be added with a half of max speed. // @TODO(bykoianko) It's necessary to gather statistics to calculate better factor(s) instead of // one below. return TimeBetweenSec(from, to, m_maxWeightSpeedMpS / 2.0); } double EdgeEstimator::CalcOffroadWeight(m2::PointD const & from, m2::PointD const & to) const { return TimeBetweenSec(from, to, m_offroadSpeedMpS); } // PedestrianEstimator ----------------------------------------------------------------------------- class PedestrianEstimator final : public EdgeEstimator { public: PedestrianEstimator(double maxWeightSpeedKMpH, double offroadSpeedKMpH) : EdgeEstimator(maxWeightSpeedKMpH, offroadSpeedKMpH) { } // EdgeEstimator overrides: double GetUTurnPenalty() const override { return 0.0 /* seconds */; } bool LeapIsAllowed(NumMwmId /* mwmId */) const override { return false; } double CalcSegmentWeight(Segment const & segment, RoadGeometry const & road) const override { return CalcClimbSegment(Purpose::Weight, segment, road, GetPedestrianClimbPenalty); } double CalcSegmentETA(Segment const & segment, RoadGeometry const & road) const override { return CalcClimbSegment(Purpose::ETA, segment, road, GetPedestrianClimbPenalty); } }; // BicycleEstimator -------------------------------------------------------------------------------- class BicycleEstimator final : public EdgeEstimator { public: BicycleEstimator(double maxWeightSpeedKMpH, double offroadSpeedKMpH) : EdgeEstimator(maxWeightSpeedKMpH, offroadSpeedKMpH) { } // EdgeEstimator overrides: double GetUTurnPenalty() const override { return 20.0 /* seconds */; } bool LeapIsAllowed(NumMwmId /* mwmId */) const override { return false; } double CalcSegmentWeight(Segment const & segment, RoadGeometry const & road) const override { return CalcClimbSegment(Purpose::Weight, segment, road, GetBicycleClimbPenalty); } double CalcSegmentETA(Segment const & segment, RoadGeometry const & road) const override { return CalcClimbSegment(Purpose::ETA, segment, road, GetBicycleClimbPenalty); } }; // CarEstimator ------------------------------------------------------------------------------------ class CarEstimator final : public EdgeEstimator { public: CarEstimator(shared_ptr<TrafficStash> trafficStash, double maxWeightSpeedKMpH, double offroadSpeedKMpH); // EdgeEstimator overrides: double CalcSegmentWeight(Segment const & segment, RoadGeometry const & road) const override; double CalcSegmentETA(Segment const & segment, RoadGeometry const & road) const override; double GetUTurnPenalty() const override; bool LeapIsAllowed(NumMwmId mwmId) const override; private: double CalcSegment(Purpose purpose, Segment const & segment, RoadGeometry const & road) const; shared_ptr<TrafficStash> m_trafficStash; }; CarEstimator::CarEstimator(shared_ptr<TrafficStash> trafficStash, double maxWeightSpeedKMpH, double offroadSpeedKMpH) : EdgeEstimator(maxWeightSpeedKMpH, offroadSpeedKMpH), m_trafficStash(move(trafficStash)) { } double CarEstimator::CalcSegmentWeight(Segment const & segment, RoadGeometry const & road) const { return CalcSegment(Purpose::Weight, segment, road); } double CarEstimator::CalcSegmentETA(Segment const & segment, RoadGeometry const & road) const { return CalcSegment(Purpose::ETA, segment, road); } double CarEstimator::GetUTurnPenalty() const { // Adds 2 minutes penalty for U-turn. The value is quite arbitrary // and needs to be properly selected after a number of real-world // experiments. return 2 * 60; // seconds } bool CarEstimator::LeapIsAllowed(NumMwmId mwmId) const { return !m_trafficStash->Has(mwmId); } double CarEstimator::CalcSegment(Purpose purpose, Segment const & segment, RoadGeometry const & road) const { // Current time estimation are too optimistic. // Need more accurate tuning: traffic lights, traffic jams, road models and so on. // Add some penalty to make estimation of a more realistic. // TODO: make accurate tuning, remove penalty. double constexpr kTimePenalty = 1.8; double result = CalcClimbSegment(purpose, segment, road, GetCarClimbPenalty); if (m_trafficStash) { SpeedGroup const speedGroup = m_trafficStash->GetSpeedGroup(segment); ASSERT_LESS(speedGroup, SpeedGroup::Count, ()); double const trafficFactor = CalcTrafficFactor(speedGroup); result *= trafficFactor; if (speedGroup != SpeedGroup::Unknown && speedGroup != SpeedGroup::G5) result *= kTimePenalty; } return result; } // EdgeEstimator ----------------------------------------------------------------------------------- // static shared_ptr<EdgeEstimator> EdgeEstimator::Create(VehicleType vehicleType, double maxWeighSpeedKMpH, double offroadSpeedKMpH, shared_ptr<TrafficStash> trafficStash) { switch (vehicleType) { case VehicleType::Pedestrian: case VehicleType::Transit: return make_shared<PedestrianEstimator>(maxWeighSpeedKMpH, offroadSpeedKMpH); case VehicleType::Bicycle: return make_shared<BicycleEstimator>(maxWeighSpeedKMpH, offroadSpeedKMpH); case VehicleType::Car: return make_shared<CarEstimator>(trafficStash, maxWeighSpeedKMpH, offroadSpeedKMpH); case VehicleType::Count: CHECK(false, ("Can't create EdgeEstimator for", vehicleType)); return nullptr; } UNREACHABLE(); } // static shared_ptr<EdgeEstimator> EdgeEstimator::Create(VehicleType vehicleType, VehicleModelInterface const & vehicleModel, shared_ptr<TrafficStash> trafficStash) { return Create(vehicleType, vehicleModel.GetMaxWeightSpeed(), vehicleModel.GetOffroadSpeed(), trafficStash); } } // namespace routing <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "gtest/gtest.h" extern "C" { #include "modules/audio_processing/utility/delay_estimator.h" #include "modules/audio_processing/utility/delay_estimator_internal.h" #include "modules/audio_processing/utility/delay_estimator_wrapper.h" } #include "typedefs.h" namespace { enum { kSpectrumSize = 65 }; // Delay history sizes. enum { kMaxDelay = 100 }; enum { kLookahead = 10 }; // Length of binary spectrum sequence. enum { kSequenceLength = 400 }; class DelayEstimatorTest : public ::testing::Test { protected: DelayEstimatorTest(); virtual void SetUp(); virtual void TearDown(); void Init(); void InitBinary(); void* handle_; DelayEstimator* self_; BinaryDelayEstimator* binary_handle_; BinaryDelayEstimatorFarend* binary_farend_handle_; int spectrum_size_; // Dummy input spectra. float far_f_[kSpectrumSize]; float near_f_[kSpectrumSize]; uint16_t far_u16_[kSpectrumSize]; uint16_t near_u16_[kSpectrumSize]; }; DelayEstimatorTest::DelayEstimatorTest() : handle_(NULL), self_(NULL), binary_handle_(NULL), binary_farend_handle_(NULL), spectrum_size_(kSpectrumSize) { // Dummy input data are set with more or less arbitrary non-zero values. memset(far_f_, 1, sizeof(far_f_)); memset(near_f_, 2, sizeof(near_f_)); memset(far_u16_, 1, sizeof(far_u16_)); memset(near_u16_, 2, sizeof(near_u16_)); } void DelayEstimatorTest::SetUp() { handle_ = WebRtc_CreateDelayEstimator(kSpectrumSize, kMaxDelay, kLookahead); ASSERT_TRUE(handle_ != NULL); self_ = reinterpret_cast<DelayEstimator*>(handle_); binary_farend_handle_ = WebRtc_CreateBinaryDelayEstimatorFarend(kMaxDelay + kLookahead); ASSERT_TRUE(binary_farend_handle_ != NULL); binary_handle_ = WebRtc_CreateBinaryDelayEstimator(binary_farend_handle_, kLookahead); ASSERT_TRUE(binary_handle_ != NULL); } void DelayEstimatorTest::TearDown() { WebRtc_FreeDelayEstimator(handle_); handle_ = NULL; self_ = NULL; WebRtc_FreeBinaryDelayEstimator(binary_handle_); binary_handle_ = NULL; WebRtc_FreeBinaryDelayEstimatorFarend(binary_farend_handle_); binary_farend_handle_ = NULL; } void DelayEstimatorTest::Init() { // Initialize Delay Estimator EXPECT_EQ(0, WebRtc_InitDelayEstimator(handle_)); // Verify initialization. EXPECT_EQ(0, self_->far_spectrum_initialized); EXPECT_EQ(0, self_->near_spectrum_initialized); EXPECT_EQ(-2, WebRtc_last_delay(handle_)); // Delay in initial state. EXPECT_EQ(0, WebRtc_last_delay_quality(handle_)); // Zero quality. } void DelayEstimatorTest::InitBinary() { // Initialize Binary Delay Estimator (far-end part). WebRtc_InitBinaryDelayEstimatorFarend(binary_farend_handle_); // Initialize Binary Delay Estimator WebRtc_InitBinaryDelayEstimator(binary_handle_); // Verify initialization. This does not guarantee a complete check, since // |last_delay| may be equal to -2 before initialization if done on the fly. EXPECT_EQ(-2, binary_handle_->last_delay); } TEST_F(DelayEstimatorTest, CorrectErrorReturnsOfWrapper) { // In this test we verify correct error returns on invalid API calls. // WebRtc_CreateDelayEstimator() should return a NULL pointer on invalid input // values. // Make sure we have a non-NULL value at start, so we can detect NULL after // create failure. void* handle = handle_; handle = WebRtc_CreateDelayEstimator(33, kMaxDelay, kLookahead); EXPECT_TRUE(handle == NULL); handle = handle_; handle = WebRtc_CreateDelayEstimator(kSpectrumSize, kMaxDelay, -1); EXPECT_TRUE(handle == NULL); handle = handle_; handle = WebRtc_CreateDelayEstimator(kSpectrumSize, 0, 0); EXPECT_TRUE(handle == NULL); // WebRtc_InitDelayEstimator() should return -1 if we have a NULL pointer as // |handle|. EXPECT_EQ(-1, WebRtc_InitDelayEstimator(NULL)); // WebRtc_DelayEstimatorProcessFloat() should return -1 if we have: // 1) NULL pointer as |handle|. // 2) NULL pointer as far-end spectrum. // 3) NULL pointer as near-end spectrum. // 4) Incorrect spectrum size. EXPECT_EQ(-1, WebRtc_DelayEstimatorProcessFloat(NULL, far_f_, near_f_, spectrum_size_)); // Use |handle_| which is properly created at SetUp(). EXPECT_EQ(-1, WebRtc_DelayEstimatorProcessFloat(handle_, NULL, near_f_, spectrum_size_)); EXPECT_EQ(-1, WebRtc_DelayEstimatorProcessFloat(handle_, far_f_, NULL, spectrum_size_)); EXPECT_EQ(-1, WebRtc_DelayEstimatorProcessFloat(handle_, far_f_, near_f_, spectrum_size_ + 1)); // WebRtc_DelayEstimatorProcessFix() should return -1 if we have: // 1) NULL pointer as |handle|. // 2) NULL pointer as far-end spectrum. // 3) NULL pointer as near-end spectrum. // 4) Incorrect spectrum size. // 5) Too high precision in far-end spectrum (Q-domain > 15). // 6) Too high precision in near-end spectrum (Q-domain > 15). EXPECT_EQ(-1, WebRtc_DelayEstimatorProcessFix(NULL, far_u16_, near_u16_, spectrum_size_, 0, 0)); // Use |handle_| which is properly created at SetUp(). EXPECT_EQ(-1, WebRtc_DelayEstimatorProcessFix(handle_, NULL, near_u16_, spectrum_size_, 0, 0)); EXPECT_EQ(-1, WebRtc_DelayEstimatorProcessFix(handle_, far_u16_, NULL, spectrum_size_, 0, 0)); EXPECT_EQ(-1, WebRtc_DelayEstimatorProcessFix(handle_, far_u16_, near_u16_, spectrum_size_ + 1, 0, 0)); EXPECT_EQ(-1, WebRtc_DelayEstimatorProcessFix(handle_, far_u16_, near_u16_, spectrum_size_, 16, 0)); EXPECT_EQ(-1, WebRtc_DelayEstimatorProcessFix(handle_, far_u16_, near_u16_, spectrum_size_, 0, 16)); // WebRtc_last_delay() should return -1 if we have a NULL pointer as |handle|. EXPECT_EQ(-1, WebRtc_last_delay(NULL)); // WebRtc_last_delay_quality() should return -1 if we have a NULL pointer as // |handle|. EXPECT_EQ(-1, WebRtc_last_delay_quality(NULL)); // Free any local memory if needed. WebRtc_FreeDelayEstimator(handle); } TEST_F(DelayEstimatorTest, InitializedSpectrumAfterProcess) { // In this test we verify that the mean spectra are initialized after first // time we call Process(). // For floating point operations, process one frame and verify initialization // flag. Init(); EXPECT_EQ(-2, WebRtc_DelayEstimatorProcessFloat(handle_, far_f_, near_f_, spectrum_size_)); EXPECT_EQ(1, self_->far_spectrum_initialized); EXPECT_EQ(1, self_->near_spectrum_initialized); // For fixed point operations, process one frame and verify initialization // flag. Init(); EXPECT_EQ(-2, WebRtc_DelayEstimatorProcessFix(handle_, far_u16_, near_u16_, spectrum_size_, 0, 0)); EXPECT_EQ(1, self_->far_spectrum_initialized); EXPECT_EQ(1, self_->near_spectrum_initialized); } TEST_F(DelayEstimatorTest, CorrectLastDelay) { // In this test we verify that we get the correct last delay upon valid call. // We simply process the same data until we leave the initialized state // (|last_delay| = -2). Then we compare the Process() output with the // last_delay() call. int last_delay = 0; // Floating point operations. Init(); for (int i = 0; i < 200; i++) { last_delay = WebRtc_DelayEstimatorProcessFloat(handle_, far_f_, near_f_, spectrum_size_); if (last_delay != -2) { EXPECT_EQ(last_delay, WebRtc_last_delay(handle_)); EXPECT_EQ(7203, WebRtc_last_delay_quality(handle_)); break; } } // Verify that we have left the initialized state. EXPECT_NE(-2, WebRtc_last_delay(handle_)); EXPECT_NE(0, WebRtc_last_delay_quality(handle_)); // Fixed point operations. Init(); for (int i = 0; i < 200; i++) { last_delay = WebRtc_DelayEstimatorProcessFix(handle_, far_u16_, near_u16_, spectrum_size_, 0, 0); if (last_delay != -2) { EXPECT_EQ(last_delay, WebRtc_last_delay(handle_)); EXPECT_EQ(7203, WebRtc_last_delay_quality(handle_)); break; } } // Verify that we have left the initialized state. EXPECT_NE(-2, WebRtc_last_delay(handle_)); EXPECT_NE(0, WebRtc_last_delay_quality(handle_)); } TEST_F(DelayEstimatorTest, CorrectErrorReturnsOfBinaryEstimator) { // In this test we verify correct output on invalid API calls to the Binary // Delay Estimator. BinaryDelayEstimator* binary_handle = binary_handle_; // WebRtc_CreateBinaryDelayEstimator() should return -1 if we have a NULL // pointer as |binary_handle| or invalid input values. Upon failure, the // |binary_handle| should be NULL. // Make sure we have a non-NULL value at start, so we can detect NULL after // create failure. binary_handle = WebRtc_CreateBinaryDelayEstimator(NULL, kLookahead); EXPECT_TRUE(binary_handle == NULL); binary_handle = binary_handle_; binary_handle = WebRtc_CreateBinaryDelayEstimator(binary_farend_handle_, -1); EXPECT_TRUE(binary_handle == NULL); binary_handle = binary_handle_; binary_handle = WebRtc_CreateBinaryDelayEstimator(0, 0); EXPECT_TRUE(binary_handle == NULL); } TEST_F(DelayEstimatorTest, MeanEstimatorFix) { // In this test we verify that we update the mean value in correct direction // only. With "direction" we mean increase or decrease. int32_t mean_value = 4000; int32_t mean_value_before = mean_value; int32_t new_mean_value = mean_value * 2; // Increasing |mean_value|. WebRtc_MeanEstimatorFix(new_mean_value, 10, &mean_value); EXPECT_LT(mean_value_before, mean_value); EXPECT_GT(new_mean_value, mean_value); // Decreasing |mean_value|. new_mean_value = mean_value / 2; mean_value_before = mean_value; WebRtc_MeanEstimatorFix(new_mean_value, 10, &mean_value); EXPECT_GT(mean_value_before, mean_value); EXPECT_LT(new_mean_value, mean_value); } TEST_F(DelayEstimatorTest, ExactDelayEstimate) { // In this test we verify that we get the correct delay estimate if we shift // the signal accordingly. We verify both causal and non-causal delays. // Construct a sequence of binary spectra used to verify delay estimate. The // |kSequenceLength| has to be long enough for the delay estimation to leave // the initialized state. uint32_t binary_spectrum[kSequenceLength + kMaxDelay + kLookahead]; binary_spectrum[0] = 1; for (int i = 1; i < (kSequenceLength + kMaxDelay + kLookahead); i++) { binary_spectrum[i] = 3 * binary_spectrum[i - 1]; } // Verify the delay for both causal and non-causal systems. For causal systems // the delay is equivalent with a positive |offset| of the far-end sequence. // For non-causal systems the delay is equivalent with a negative |offset| of // the far-end sequence. for (int offset = -kLookahead; offset < kMaxDelay; offset++) { InitBinary(); for (int i = kLookahead; i < (kSequenceLength + kLookahead); i++) { WebRtc_AddBinaryFarSpectrum(binary_farend_handle_, binary_spectrum[i + offset]); int delay = WebRtc_ProcessBinarySpectrum(binary_handle_, binary_spectrum[i]); // Verify that we WebRtc_binary_last_delay() returns correct delay. EXPECT_EQ(delay, WebRtc_binary_last_delay(binary_handle_)); if (delay != -2) { // Verify correct delay estimate. In the non-causal case the true delay // is equivalent with the |offset|. EXPECT_EQ(offset, delay - kLookahead); } } // Verify that we have left the initialized state. EXPECT_NE(-2, WebRtc_binary_last_delay(binary_handle_)); EXPECT_NE(0, WebRtc_binary_last_delay_quality(binary_handle_)); } } } // namespace <commit_msg>Added tests for multiple near-end support.<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "gtest/gtest.h" extern "C" { #include "modules/audio_processing/utility/delay_estimator.h" #include "modules/audio_processing/utility/delay_estimator_internal.h" #include "modules/audio_processing/utility/delay_estimator_wrapper.h" } #include "typedefs.h" namespace { enum { kSpectrumSize = 65 }; // Delay history sizes. enum { kMaxDelay = 100 }; enum { kLookahead = 10 }; // Length of binary spectrum sequence. enum { kSequenceLength = 400 }; class DelayEstimatorTest : public ::testing::Test { protected: DelayEstimatorTest(); virtual void SetUp(); virtual void TearDown(); void Init(); void InitBinary(); void VerifyDelay(BinaryDelayEstimator* binary_handle, int offset, int delay); void RunBinarySpectra(BinaryDelayEstimator* binary1, BinaryDelayEstimator* binary2, int near_offset, int lookahead_offset, int far_offset); void RunBinarySpectraTest(int near_offset, int lookahead_offset); void* handle_; DelayEstimator* self_; BinaryDelayEstimator* binary_; BinaryDelayEstimatorFarend* binary_farend_; int spectrum_size_; // Dummy input spectra. float far_f_[kSpectrumSize]; float near_f_[kSpectrumSize]; uint16_t far_u16_[kSpectrumSize]; uint16_t near_u16_[kSpectrumSize]; uint32_t binary_spectrum_[kSequenceLength + kMaxDelay + kLookahead]; }; DelayEstimatorTest::DelayEstimatorTest() : handle_(NULL), self_(NULL), binary_(NULL), binary_farend_(NULL), spectrum_size_(kSpectrumSize) { // Dummy input data are set with more or less arbitrary non-zero values. memset(far_f_, 1, sizeof(far_f_)); memset(near_f_, 2, sizeof(near_f_)); memset(far_u16_, 1, sizeof(far_u16_)); memset(near_u16_, 2, sizeof(near_u16_)); // Construct a sequence of binary spectra used to verify delay estimate. The // |kSequenceLength| has to be long enough for the delay estimation to leave // the initialized state. binary_spectrum_[0] = 1; for (int i = 1; i < (kSequenceLength + kMaxDelay + kLookahead); i++) { binary_spectrum_[i] = 3 * binary_spectrum_[i - 1]; } } void DelayEstimatorTest::SetUp() { handle_ = WebRtc_CreateDelayEstimator(kSpectrumSize, kMaxDelay, kLookahead); ASSERT_TRUE(handle_ != NULL); self_ = reinterpret_cast<DelayEstimator*>(handle_); binary_farend_ = WebRtc_CreateBinaryDelayEstimatorFarend(kMaxDelay + kLookahead); ASSERT_TRUE(binary_farend_ != NULL); binary_ = WebRtc_CreateBinaryDelayEstimator(binary_farend_, kLookahead); ASSERT_TRUE(binary_ != NULL); } void DelayEstimatorTest::TearDown() { WebRtc_FreeDelayEstimator(handle_); handle_ = NULL; self_ = NULL; WebRtc_FreeBinaryDelayEstimator(binary_); binary_ = NULL; WebRtc_FreeBinaryDelayEstimatorFarend(binary_farend_); binary_farend_ = NULL; } void DelayEstimatorTest::Init() { // Initialize Delay Estimator EXPECT_EQ(0, WebRtc_InitDelayEstimator(handle_)); // Verify initialization. EXPECT_EQ(0, self_->far_spectrum_initialized); EXPECT_EQ(0, self_->near_spectrum_initialized); EXPECT_EQ(-2, WebRtc_last_delay(handle_)); // Delay in initial state. EXPECT_EQ(0, WebRtc_last_delay_quality(handle_)); // Zero quality. } void DelayEstimatorTest::InitBinary() { // Initialize Binary Delay Estimator (far-end part). WebRtc_InitBinaryDelayEstimatorFarend(binary_farend_); // Initialize Binary Delay Estimator WebRtc_InitBinaryDelayEstimator(binary_); // Verify initialization. This does not guarantee a complete check, since // |last_delay| may be equal to -2 before initialization if done on the fly. EXPECT_EQ(-2, binary_->last_delay); } void DelayEstimatorTest::VerifyDelay(BinaryDelayEstimator* binary_handle, int offset, int delay) { // Verify that we WebRtc_binary_last_delay() returns correct delay. EXPECT_EQ(delay, WebRtc_binary_last_delay(binary_handle)); if (delay != -2) { // Verify correct delay estimate. In the non-causal case the true delay // is equivalent with the |offset|. EXPECT_EQ(offset, delay); } } void DelayEstimatorTest::RunBinarySpectra(BinaryDelayEstimator* binary1, BinaryDelayEstimator* binary2, int near_offset, int lookahead_offset, int far_offset) { WebRtc_InitBinaryDelayEstimatorFarend(binary_farend_); WebRtc_InitBinaryDelayEstimator(binary1); WebRtc_InitBinaryDelayEstimator(binary2); // Verify initialization. This does not guarantee a complete check, since // |last_delay| may be equal to -2 before initialization if done on the fly. EXPECT_EQ(-2, binary1->last_delay); EXPECT_EQ(-2, binary2->last_delay); for (int i = kLookahead; i < (kSequenceLength + kLookahead); i++) { WebRtc_AddBinaryFarSpectrum(binary_farend_, binary_spectrum_[i + far_offset]); int delay_1 = WebRtc_ProcessBinarySpectrum(binary1, binary_spectrum_[i]); int delay_2 = WebRtc_ProcessBinarySpectrum(binary2, binary_spectrum_[i - near_offset]); VerifyDelay(binary1, far_offset + kLookahead, delay_1); VerifyDelay(binary2, far_offset + kLookahead + lookahead_offset + near_offset, delay_2); // Expect the two delay estimates to be offset by |lookahead_offset| + // |near_offset| when we have left the initial state. if ((delay_1 != -2) && (delay_2 != -2)) { EXPECT_EQ(delay_1, delay_2 - lookahead_offset - near_offset); } if ((near_offset == 0) && (lookahead_offset == 0)) { EXPECT_EQ(delay_1, delay_2); } } // Verify that we have left the initialized state. EXPECT_NE(-2, WebRtc_binary_last_delay(binary1)); EXPECT_NE(0, WebRtc_binary_last_delay_quality(binary1)); EXPECT_NE(-2, WebRtc_binary_last_delay(binary2)); EXPECT_NE(0, WebRtc_binary_last_delay_quality(binary2)); } void DelayEstimatorTest::RunBinarySpectraTest(int near_offset, int lookahead_offset) { BinaryDelayEstimator* binary2 = WebRtc_CreateBinaryDelayEstimator(binary_farend_, kLookahead + lookahead_offset); // Verify the delay for both causal and non-causal systems. For causal systems // the delay is equivalent with a positive |offset| of the far-end sequence. // For non-causal systems the delay is equivalent with a negative |offset| of // the far-end sequence. for (int offset = -kLookahead; offset < kMaxDelay - lookahead_offset - near_offset; offset++) { RunBinarySpectra(binary_, binary2, near_offset, lookahead_offset, offset); } WebRtc_FreeBinaryDelayEstimator(binary2); binary2 = NULL; } TEST_F(DelayEstimatorTest, CorrectErrorReturnsOfWrapper) { // In this test we verify correct error returns on invalid API calls. // WebRtc_CreateDelayEstimator() should return a NULL pointer on invalid input // values. // Make sure we have a non-NULL value at start, so we can detect NULL after // create failure. void* handle = handle_; handle = WebRtc_CreateDelayEstimator(33, kMaxDelay, kLookahead); EXPECT_TRUE(handle == NULL); handle = handle_; handle = WebRtc_CreateDelayEstimator(kSpectrumSize, kMaxDelay, -1); EXPECT_TRUE(handle == NULL); handle = handle_; handle = WebRtc_CreateDelayEstimator(kSpectrumSize, 0, 0); EXPECT_TRUE(handle == NULL); // WebRtc_InitDelayEstimator() should return -1 if we have a NULL pointer as // |handle|. EXPECT_EQ(-1, WebRtc_InitDelayEstimator(NULL)); // WebRtc_DelayEstimatorProcessFloat() should return -1 if we have: // 1) NULL pointer as |handle|. // 2) NULL pointer as far-end spectrum. // 3) NULL pointer as near-end spectrum. // 4) Incorrect spectrum size. EXPECT_EQ(-1, WebRtc_DelayEstimatorProcessFloat(NULL, far_f_, near_f_, spectrum_size_)); // Use |handle_| which is properly created at SetUp(). EXPECT_EQ(-1, WebRtc_DelayEstimatorProcessFloat(handle_, NULL, near_f_, spectrum_size_)); EXPECT_EQ(-1, WebRtc_DelayEstimatorProcessFloat(handle_, far_f_, NULL, spectrum_size_)); EXPECT_EQ(-1, WebRtc_DelayEstimatorProcessFloat(handle_, far_f_, near_f_, spectrum_size_ + 1)); // WebRtc_DelayEstimatorProcessFix() should return -1 if we have: // 1) NULL pointer as |handle|. // 2) NULL pointer as far-end spectrum. // 3) NULL pointer as near-end spectrum. // 4) Incorrect spectrum size. // 5) Too high precision in far-end spectrum (Q-domain > 15). // 6) Too high precision in near-end spectrum (Q-domain > 15). EXPECT_EQ(-1, WebRtc_DelayEstimatorProcessFix(NULL, far_u16_, near_u16_, spectrum_size_, 0, 0)); // Use |handle_| which is properly created at SetUp(). EXPECT_EQ(-1, WebRtc_DelayEstimatorProcessFix(handle_, NULL, near_u16_, spectrum_size_, 0, 0)); EXPECT_EQ(-1, WebRtc_DelayEstimatorProcessFix(handle_, far_u16_, NULL, spectrum_size_, 0, 0)); EXPECT_EQ(-1, WebRtc_DelayEstimatorProcessFix(handle_, far_u16_, near_u16_, spectrum_size_ + 1, 0, 0)); EXPECT_EQ(-1, WebRtc_DelayEstimatorProcessFix(handle_, far_u16_, near_u16_, spectrum_size_, 16, 0)); EXPECT_EQ(-1, WebRtc_DelayEstimatorProcessFix(handle_, far_u16_, near_u16_, spectrum_size_, 0, 16)); // WebRtc_last_delay() should return -1 if we have a NULL pointer as |handle|. EXPECT_EQ(-1, WebRtc_last_delay(NULL)); // WebRtc_last_delay_quality() should return -1 if we have a NULL pointer as // |handle|. EXPECT_EQ(-1, WebRtc_last_delay_quality(NULL)); // Free any local memory if needed. WebRtc_FreeDelayEstimator(handle); } TEST_F(DelayEstimatorTest, InitializedSpectrumAfterProcess) { // In this test we verify that the mean spectra are initialized after first // time we call Process(). // For floating point operations, process one frame and verify initialization // flag. Init(); EXPECT_EQ(-2, WebRtc_DelayEstimatorProcessFloat(handle_, far_f_, near_f_, spectrum_size_)); EXPECT_EQ(1, self_->far_spectrum_initialized); EXPECT_EQ(1, self_->near_spectrum_initialized); // For fixed point operations, process one frame and verify initialization // flag. Init(); EXPECT_EQ(-2, WebRtc_DelayEstimatorProcessFix(handle_, far_u16_, near_u16_, spectrum_size_, 0, 0)); EXPECT_EQ(1, self_->far_spectrum_initialized); EXPECT_EQ(1, self_->near_spectrum_initialized); } TEST_F(DelayEstimatorTest, CorrectLastDelay) { // In this test we verify that we get the correct last delay upon valid call. // We simply process the same data until we leave the initialized state // (|last_delay| = -2). Then we compare the Process() output with the // last_delay() call. int last_delay = 0; // Floating point operations. Init(); for (int i = 0; i < 200; i++) { last_delay = WebRtc_DelayEstimatorProcessFloat(handle_, far_f_, near_f_, spectrum_size_); if (last_delay != -2) { EXPECT_EQ(last_delay, WebRtc_last_delay(handle_)); EXPECT_EQ(7203, WebRtc_last_delay_quality(handle_)); break; } } // Verify that we have left the initialized state. EXPECT_NE(-2, WebRtc_last_delay(handle_)); EXPECT_NE(0, WebRtc_last_delay_quality(handle_)); // Fixed point operations. Init(); for (int i = 0; i < 200; i++) { last_delay = WebRtc_DelayEstimatorProcessFix(handle_, far_u16_, near_u16_, spectrum_size_, 0, 0); if (last_delay != -2) { EXPECT_EQ(last_delay, WebRtc_last_delay(handle_)); EXPECT_EQ(7203, WebRtc_last_delay_quality(handle_)); break; } } // Verify that we have left the initialized state. EXPECT_NE(-2, WebRtc_last_delay(handle_)); EXPECT_NE(0, WebRtc_last_delay_quality(handle_)); } TEST_F(DelayEstimatorTest, CorrectErrorReturnsOfBinaryEstimator) { // In this test we verify correct output on invalid API calls to the Binary // Delay Estimator. BinaryDelayEstimator* binary_handle = binary_; // WebRtc_CreateBinaryDelayEstimator() should return -1 if we have a NULL // pointer as |binary_handle| or invalid input values. Upon failure, the // |binary_handle| should be NULL. // Make sure we have a non-NULL value at start, so we can detect NULL after // create failure. binary_handle = WebRtc_CreateBinaryDelayEstimator(NULL, kLookahead); EXPECT_TRUE(binary_handle == NULL); binary_handle = binary_; binary_handle = WebRtc_CreateBinaryDelayEstimator(binary_farend_, -1); EXPECT_TRUE(binary_handle == NULL); binary_handle = binary_; binary_handle = WebRtc_CreateBinaryDelayEstimator(0, 0); EXPECT_TRUE(binary_handle == NULL); } TEST_F(DelayEstimatorTest, MeanEstimatorFix) { // In this test we verify that we update the mean value in correct direction // only. With "direction" we mean increase or decrease. int32_t mean_value = 4000; int32_t mean_value_before = mean_value; int32_t new_mean_value = mean_value * 2; // Increasing |mean_value|. WebRtc_MeanEstimatorFix(new_mean_value, 10, &mean_value); EXPECT_LT(mean_value_before, mean_value); EXPECT_GT(new_mean_value, mean_value); // Decreasing |mean_value|. new_mean_value = mean_value / 2; mean_value_before = mean_value; WebRtc_MeanEstimatorFix(new_mean_value, 10, &mean_value); EXPECT_GT(mean_value_before, mean_value); EXPECT_LT(new_mean_value, mean_value); } TEST_F(DelayEstimatorTest, ExactDelayEstimateMultipleNearSameSpectrum) { // In this test we verify that we get the correct delay estimates if we shift // the signal accordingly. We create two Binary Delay Estimators and feed them // with the same signals, so they should output the same results. // We verify both causal and non-causal delays. RunBinarySpectraTest(0, 0); } TEST_F(DelayEstimatorTest, ExactDelayEstimateMultipleNearDifferentSpectrum) { // In this test we use the same setup as above, but we now feed the two Binary // Delay Estimators with different signals, so they should output different // results. const int kNearOffset = 1; RunBinarySpectraTest(kNearOffset, 0); } TEST_F(DelayEstimatorTest, ExactDelayEstimateMultipleNearDifferentLookahead) { // In this test we use the same setup as above, feeding the two Binary // Delay Estimators with the same signals. The difference is that we create // them with different lookahead. const int kLookaheadOffset = 1; RunBinarySpectraTest(0, kLookaheadOffset); } } // namespace <|endoftext|>
<commit_before>/* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2009 Bernhard Beschow <[email protected]> * Copyright (C) 2007 Sebastian Pipping <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "kateregexp.h" KateRegExp::KateRegExp(const QString &pattern, Qt::CaseSensitivity cs, QRegExp::PatternSyntax syntax) : m_regExp(pattern, cs, syntax) { } // these things can besides '.' and '\s' make apptern multi-line: // \n, \x000A, \x????-\x????, \0012, \0???-\0??? // a multi-line pattern must not pass as single-line, the other // way around will just result in slower searches and is therefore // not as critical int KateRegExp::repairPattern(bool & stillMultiLine) { const QString & text = pattern(); // read-only input for parsing // get input const int inputLen = text.length(); int input = 0; // walker index // prepare output QString output; output.reserve(2 * inputLen + 1); // twice should be enough for the average case // parser state stillMultiLine = false; int replaceCount = 0; bool insideClass = false; while (input < inputLen) { if (insideClass) { // wait for closing, unescaped ']' switch (text[input].unicode()) { case L'\\': switch (text[input + 1].unicode()) { case L'x': if (input + 5 < inputLen) { // copy "\x????" unmodified output.append(text.mid(input, 6)); input += 6; } else { // copy "\x" unmodified output.append(text.mid(input, 2)); input += 2; } stillMultiLine = true; break; case L'0': if (input + 4 < inputLen) { // copy "\0???" unmodified output.append(text.mid(input, 5)); input += 5; } else { // copy "\0" unmodified output.append(text.mid(input, 2)); input += 2; } stillMultiLine = true; break; case L's': // replace "\s" with "[ \t]" output.append("[ \\t]"); input += 2; replaceCount++; break; case L'n': stillMultiLine = true; // FALLTROUGH default: // copy "\?" unmodified output.append(text.mid(input, 2)); input += 2; } break; case L']': // copy "]" unmodified insideClass = false; output.append(text[input]); input++; break; default: // copy "?" unmodified output.append(text[input]); input++; } } else { // search for real dots and \S switch (text[input].unicode()) { case L'\\': switch (text[input + 1].unicode()) { case L'x': if (input + 5 < inputLen) { // copy "\x????" unmodified output.append(text.mid(input, 6)); input += 6; } else { // copy "\x" unmodified output.append(text.mid(input, 2)); input += 2; } stillMultiLine = true; break; case L'0': if (input + 4 < inputLen) { // copy "\0???" unmodified output.append(text.mid(input, 5)); input += 5; } else { // copy "\0" unmodified output.append(text.mid(input, 2)); input += 2; } stillMultiLine = true; break; case L's': // replace "\s" with "[ \t]" output.append("[ \\t]"); input += 2; replaceCount++; break; case L'n': stillMultiLine = true; // FALLTROUGH default: // copy "\?" unmodified output.append(text.mid(input, 2)); input += 2; } break; case L'.': // replace " with "[^\n]" output.append("[^\\n]"); input++; replaceCount++; break; case L'[': // copy "]" unmodified insideClass = true; output.append(text[input]); input++; break; default: // copy "?" unmodified output.append(text[input]); input++; } } } // Overwrite with repaired pattern m_regExp.setPattern(output); return replaceCount; } bool KateRegExp::isMultiLine() const { const QString &text = pattern(); // parser state bool insideClass = false; for (int input = 0; input < text.length(); /*empty*/ ) { if (insideClass) { // wait for closing, unescaped ']' switch (text[input].unicode()) { case L'\\': switch (text[input + 1].unicode()) { case L'x': return true; case L'0': return true; case L's': // replace "\s" with "[ \t]" input += 2; break; case L'n': return true; // FALLTROUGH default: // copy "\?" unmodified input += 2; } break; case L']': // copy "]" unmodified insideClass = false; input++; break; default: // copy "?" unmodified input++; } } else { // search for real dots and \S switch (text[input].unicode()) { case L'\\': switch (text[input + 1].unicode()) { case L'x': return true; case L'0': return true; case L's': // replace "\s" with "[ \t]" input += 2; break; case L'n': return true; default: // copy "\?" unmodified input += 2; } break; case L'.': // replace " with "[^\n]" input++; break; case L'[': // copy "]" unmodified insideClass = true; input++; break; default: // copy "?" unmodified input++; } } } return false; } int KateRegExp::indexIn(const QString &str, int start, int end) const { return m_regExp.indexIn(str.left(end), start, QRegExp::CaretAtZero); } int KateRegExp::lastIndexIn(const QString &str, int start, int end) const { const int index = m_regExp.lastIndexIn(str.mid(start, end-start), -1, QRegExp::CaretAtZero); if (index == -1) return -1; const int index2 = m_regExp.indexIn(str.left(end), start+index, QRegExp::CaretAtZero); return index2; } // kate: space-indent on; indent-width 2; replace-tabs on; <commit_msg>Match '$' only with end of lines when searching backward<commit_after>/* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2009 Bernhard Beschow <[email protected]> * Copyright (C) 2007 Sebastian Pipping <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "kateregexp.h" KateRegExp::KateRegExp(const QString &pattern, Qt::CaseSensitivity cs, QRegExp::PatternSyntax syntax) : m_regExp(pattern, cs, syntax) { } // these things can besides '.' and '\s' make apptern multi-line: // \n, \x000A, \x????-\x????, \0012, \0???-\0??? // a multi-line pattern must not pass as single-line, the other // way around will just result in slower searches and is therefore // not as critical int KateRegExp::repairPattern(bool & stillMultiLine) { const QString & text = pattern(); // read-only input for parsing // get input const int inputLen = text.length(); int input = 0; // walker index // prepare output QString output; output.reserve(2 * inputLen + 1); // twice should be enough for the average case // parser state stillMultiLine = false; int replaceCount = 0; bool insideClass = false; while (input < inputLen) { if (insideClass) { // wait for closing, unescaped ']' switch (text[input].unicode()) { case L'\\': switch (text[input + 1].unicode()) { case L'x': if (input + 5 < inputLen) { // copy "\x????" unmodified output.append(text.mid(input, 6)); input += 6; } else { // copy "\x" unmodified output.append(text.mid(input, 2)); input += 2; } stillMultiLine = true; break; case L'0': if (input + 4 < inputLen) { // copy "\0???" unmodified output.append(text.mid(input, 5)); input += 5; } else { // copy "\0" unmodified output.append(text.mid(input, 2)); input += 2; } stillMultiLine = true; break; case L's': // replace "\s" with "[ \t]" output.append("[ \\t]"); input += 2; replaceCount++; break; case L'n': stillMultiLine = true; // FALLTROUGH default: // copy "\?" unmodified output.append(text.mid(input, 2)); input += 2; } break; case L']': // copy "]" unmodified insideClass = false; output.append(text[input]); input++; break; default: // copy "?" unmodified output.append(text[input]); input++; } } else { // search for real dots and \S switch (text[input].unicode()) { case L'\\': switch (text[input + 1].unicode()) { case L'x': if (input + 5 < inputLen) { // copy "\x????" unmodified output.append(text.mid(input, 6)); input += 6; } else { // copy "\x" unmodified output.append(text.mid(input, 2)); input += 2; } stillMultiLine = true; break; case L'0': if (input + 4 < inputLen) { // copy "\0???" unmodified output.append(text.mid(input, 5)); input += 5; } else { // copy "\0" unmodified output.append(text.mid(input, 2)); input += 2; } stillMultiLine = true; break; case L's': // replace "\s" with "[ \t]" output.append("[ \\t]"); input += 2; replaceCount++; break; case L'n': stillMultiLine = true; // FALLTROUGH default: // copy "\?" unmodified output.append(text.mid(input, 2)); input += 2; } break; case L'.': // replace " with "[^\n]" output.append("[^\\n]"); input++; replaceCount++; break; case L'[': // copy "]" unmodified insideClass = true; output.append(text[input]); input++; break; default: // copy "?" unmodified output.append(text[input]); input++; } } } // Overwrite with repaired pattern m_regExp.setPattern(output); return replaceCount; } bool KateRegExp::isMultiLine() const { const QString &text = pattern(); // parser state bool insideClass = false; for (int input = 0; input < text.length(); /*empty*/ ) { if (insideClass) { // wait for closing, unescaped ']' switch (text[input].unicode()) { case L'\\': switch (text[input + 1].unicode()) { case L'x': return true; case L'0': return true; case L's': // replace "\s" with "[ \t]" input += 2; break; case L'n': return true; // FALLTROUGH default: // copy "\?" unmodified input += 2; } break; case L']': // copy "]" unmodified insideClass = false; input++; break; default: // copy "?" unmodified input++; } } else { // search for real dots and \S switch (text[input].unicode()) { case L'\\': switch (text[input + 1].unicode()) { case L'x': return true; case L'0': return true; case L's': // replace "\s" with "[ \t]" input += 2; break; case L'n': return true; default: // copy "\?" unmodified input += 2; } break; case L'.': // replace " with "[^\n]" input++; break; case L'[': // copy "]" unmodified insideClass = true; input++; break; default: // copy "?" unmodified input++; } } } return false; } int KateRegExp::indexIn(const QString &str, int start, int end) const { return m_regExp.indexIn(str.left(end), start, QRegExp::CaretAtZero); } int KateRegExp::lastIndexIn(const QString &str, int start, int end) const { if (end <= 0) return -1; const int index = m_regExp.lastIndexIn(str.mid(start), end-1, QRegExp::CaretAtZero); if (index == -1) return -1; const int index2 = m_regExp.indexIn(str.left(end), start+index, QRegExp::CaretAtZero); return index2; } // kate: space-indent on; indent-width 2; replace-tabs on; <|endoftext|>
<commit_before>#include <array> #include <iostream> #include "GL/glew.h" #include "RaZ/Math/Matrix.hpp" #include "RaZ/Math/Vector.hpp" #include "RaZ/Render/ShaderProgram.hpp" namespace Raz { ShaderProgram::ShaderProgram() : m_index{ glCreateProgram() } {} ShaderProgram::ShaderProgram(ShaderProgram&& program) noexcept : m_index{ std::exchange(program.m_index, GL_INVALID_INDEX) }, m_vertShader{ std::move(program.m_vertShader) }, m_fragShader{ std::move(program.m_fragShader) }, m_geomShader{ std::move(program.m_geomShader) }, m_uniforms{ std::move(program.m_uniforms) } {} void ShaderProgram::setVertexShader(VertexShader&& vertShader) { m_vertShader = std::move(vertShader); glAttachShader(m_index, m_vertShader.getIndex()); } void ShaderProgram::setFragmentShader(FragmentShader&& fragShader) { m_fragShader = std::move(fragShader); glAttachShader(m_index, m_fragShader.getIndex()); } void ShaderProgram::setGeometryShader(GeometryShader&& geomShader) { m_geomShader = std::make_unique<GeometryShader>(std::move(geomShader)); glAttachShader(m_index, m_geomShader->getIndex()); } void ShaderProgram::setShaders(VertexShader&& vertShader, FragmentShader&& fragShader) { setVertexShader(std::move(vertShader)); setFragmentShader(std::move(fragShader)); updateShaders(); } void ShaderProgram::setShaders(VertexShader&& vertShader, FragmentShader&& fragShader, GeometryShader&& geomShader) { setVertexShader(std::move(vertShader)); setFragmentShader(std::move(fragShader)); setGeometryShader(std::move(geomShader)); updateShaders(); } void ShaderProgram::loadShaders() const { m_vertShader.load(); m_fragShader.load(); if (m_geomShader) m_geomShader->load(); } void ShaderProgram::compileShaders() const { m_vertShader.compile(); m_fragShader.compile(); if (m_geomShader) m_geomShader->compile(); } void ShaderProgram::link() const { glLinkProgram(m_index); if (!isLinked()) { std::array<char, 512> infoLog {}; glGetProgramInfoLog(m_index, static_cast<int>(infoLog.size()), nullptr, infoLog.data()); std::cerr << "Error: Shader program link failed (ID " << m_index << ").\n" << infoLog.data() << std::endl; } } bool ShaderProgram::isLinked() const { int success; glGetProgramiv(m_index, GL_LINK_STATUS, &success); return static_cast<bool>(success); } void ShaderProgram::use() const { glUseProgram(m_index); } void ShaderProgram::updateShaders() const { loadShaders(); compileShaders(); link(); use(); } void ShaderProgram::createUniform(const std::string& uniformName) { m_uniforms.emplace(uniformName, recoverUniformLocation(uniformName)); } int ShaderProgram::recoverUniformLocation(const std::string& uniformName) const { const auto uniform = m_uniforms.find(uniformName); if (uniform != m_uniforms.cend()) return uniform->second; return glGetUniformLocation(m_index, uniformName.c_str()); } template <> void ShaderProgram::sendUniform(int uniformIndex, int value) const { glUniform1i(uniformIndex, value); } template <> void ShaderProgram::sendUniform(int uniformIndex, uint8_t value) const { glUniform1ui(uniformIndex, static_cast<unsigned int>(value)); } template <> void ShaderProgram::sendUniform(int uniformIndex, uint16_t value) const { glUniform1ui(uniformIndex, static_cast<unsigned int>(value)); } template <> void ShaderProgram::sendUniform(int uniformIndex, uint32_t value) const { glUniform1ui(uniformIndex, static_cast<unsigned int>(value)); } template <> void ShaderProgram::sendUniform(int uniformIndex, uint64_t value) const { glUniform1ui(uniformIndex, static_cast<unsigned int>(value)); } template <> void ShaderProgram::sendUniform(int uniformIndex, float value) const { glUniform1f(uniformIndex, value); } template <> void ShaderProgram::sendUniform(int uniformIndex, const Vec3f& vec) const { glUniform3fv(uniformIndex, 1, vec.getDataPtr()); } template <> void ShaderProgram::sendUniform(int uniformIndex, const Vec4f& vec) const { glUniform4fv(uniformIndex, 1, vec.getDataPtr()); } template <> void ShaderProgram::sendUniform(int uniformIndex, const Mat3f& mat) const { glUniformMatrix3fv(uniformIndex, 1, GL_FALSE, mat.getDataPtr()); } template <> void ShaderProgram::sendUniform(int uniformIndex, const Mat4f& mat) const { glUniformMatrix4fv(uniformIndex, 1, GL_FALSE, mat.getDataPtr()); } void ShaderProgram::destroyVertexShader() { glDetachShader(m_index, m_vertShader.getIndex()); m_vertShader.destroy(); } void ShaderProgram::destroyFragmentShader() { glDetachShader(m_index, m_fragShader.getIndex()); m_fragShader.destroy(); } void ShaderProgram::destroyGeometryShader() { if (!m_geomShader) return; glDetachShader(m_index, m_geomShader->getIndex()); m_geomShader->destroy(); m_geomShader.reset(); } ShaderProgram& ShaderProgram::operator=(ShaderProgram&& program) noexcept { std::swap(m_index, program.m_index); m_vertShader = std::move(program.m_vertShader); m_fragShader = std::move(program.m_fragShader); m_geomShader = std::move(program.m_geomShader); m_uniforms = std::move(program.m_uniforms); return *this; } ShaderProgram::~ShaderProgram() { if (m_index == GL_INVALID_INDEX) return; glDeleteProgram(m_index); } } // namespace Raz <commit_msg>[Render/ShaderProgram] Added overloads to sendUniform()<commit_after>#include <array> #include <iostream> #include "GL/glew.h" #include "RaZ/Math/Matrix.hpp" #include "RaZ/Math/Vector.hpp" #include "RaZ/Render/ShaderProgram.hpp" namespace Raz { ShaderProgram::ShaderProgram() : m_index{ glCreateProgram() } {} ShaderProgram::ShaderProgram(ShaderProgram&& program) noexcept : m_index{ std::exchange(program.m_index, GL_INVALID_INDEX) }, m_vertShader{ std::move(program.m_vertShader) }, m_fragShader{ std::move(program.m_fragShader) }, m_geomShader{ std::move(program.m_geomShader) }, m_uniforms{ std::move(program.m_uniforms) } {} void ShaderProgram::setVertexShader(VertexShader&& vertShader) { m_vertShader = std::move(vertShader); glAttachShader(m_index, m_vertShader.getIndex()); } void ShaderProgram::setFragmentShader(FragmentShader&& fragShader) { m_fragShader = std::move(fragShader); glAttachShader(m_index, m_fragShader.getIndex()); } void ShaderProgram::setGeometryShader(GeometryShader&& geomShader) { m_geomShader = std::make_unique<GeometryShader>(std::move(geomShader)); glAttachShader(m_index, m_geomShader->getIndex()); } void ShaderProgram::setShaders(VertexShader&& vertShader, FragmentShader&& fragShader) { setVertexShader(std::move(vertShader)); setFragmentShader(std::move(fragShader)); updateShaders(); } void ShaderProgram::setShaders(VertexShader&& vertShader, FragmentShader&& fragShader, GeometryShader&& geomShader) { setVertexShader(std::move(vertShader)); setFragmentShader(std::move(fragShader)); setGeometryShader(std::move(geomShader)); updateShaders(); } void ShaderProgram::loadShaders() const { m_vertShader.load(); m_fragShader.load(); if (m_geomShader) m_geomShader->load(); } void ShaderProgram::compileShaders() const { m_vertShader.compile(); m_fragShader.compile(); if (m_geomShader) m_geomShader->compile(); } void ShaderProgram::link() const { glLinkProgram(m_index); if (!isLinked()) { std::array<char, 512> infoLog {}; glGetProgramInfoLog(m_index, static_cast<int>(infoLog.size()), nullptr, infoLog.data()); std::cerr << "Error: Shader program link failed (ID " << m_index << ").\n" << infoLog.data() << std::endl; } } bool ShaderProgram::isLinked() const { int success; glGetProgramiv(m_index, GL_LINK_STATUS, &success); return static_cast<bool>(success); } void ShaderProgram::use() const { glUseProgram(m_index); } void ShaderProgram::updateShaders() const { loadShaders(); compileShaders(); link(); use(); } void ShaderProgram::createUniform(const std::string& uniformName) { m_uniforms.emplace(uniformName, recoverUniformLocation(uniformName)); } int ShaderProgram::recoverUniformLocation(const std::string& uniformName) const { const auto uniform = m_uniforms.find(uniformName); if (uniform != m_uniforms.cend()) return uniform->second; return glGetUniformLocation(m_index, uniformName.c_str()); } template <> void ShaderProgram::sendUniform(int uniformIndex, int8_t value) const { glUniform1i(uniformIndex, static_cast<int>(value)); } template <> void ShaderProgram::sendUniform(int uniformIndex, int16_t value) const { glUniform1i(uniformIndex, static_cast<int>(value)); } template <> void ShaderProgram::sendUniform(int uniformIndex, int32_t value) const { glUniform1i(uniformIndex, static_cast<int>(value)); } template <> void ShaderProgram::sendUniform(int uniformIndex, int64_t value) const { glUniform1i(uniformIndex, static_cast<int>(value)); } template <> void ShaderProgram::sendUniform(int uniformIndex, uint8_t value) const { glUniform1ui(uniformIndex, static_cast<unsigned int>(value)); } template <> void ShaderProgram::sendUniform(int uniformIndex, uint16_t value) const { glUniform1ui(uniformIndex, static_cast<unsigned int>(value)); } template <> void ShaderProgram::sendUniform(int uniformIndex, uint32_t value) const { glUniform1ui(uniformIndex, static_cast<unsigned int>(value)); } template <> void ShaderProgram::sendUniform(int uniformIndex, uint64_t value) const { glUniform1ui(uniformIndex, static_cast<unsigned int>(value)); } template <> void ShaderProgram::sendUniform(int uniformIndex, float value) const { glUniform1f(uniformIndex, value); } template <> void ShaderProgram::sendUniform(int uniformIndex, const Vec2f& vec) const { glUniform2fv(uniformIndex, 1, vec.getDataPtr()); } template <> void ShaderProgram::sendUniform(int uniformIndex, const Vec3f& vec) const { glUniform3fv(uniformIndex, 1, vec.getDataPtr()); } template <> void ShaderProgram::sendUniform(int uniformIndex, const Vec4f& vec) const { glUniform4fv(uniformIndex, 1, vec.getDataPtr()); } template <> void ShaderProgram::sendUniform(int uniformIndex, const Mat2f& mat) const { glUniformMatrix2fv(uniformIndex, 1, GL_FALSE, mat.getDataPtr()); } template <> void ShaderProgram::sendUniform(int uniformIndex, const Mat3f& mat) const { glUniformMatrix3fv(uniformIndex, 1, GL_FALSE, mat.getDataPtr()); } template <> void ShaderProgram::sendUniform(int uniformIndex, const Mat4f& mat) const { glUniformMatrix4fv(uniformIndex, 1, GL_FALSE, mat.getDataPtr()); } void ShaderProgram::destroyVertexShader() { glDetachShader(m_index, m_vertShader.getIndex()); m_vertShader.destroy(); } void ShaderProgram::destroyFragmentShader() { glDetachShader(m_index, m_fragShader.getIndex()); m_fragShader.destroy(); } void ShaderProgram::destroyGeometryShader() { if (!m_geomShader) return; glDetachShader(m_index, m_geomShader->getIndex()); m_geomShader->destroy(); m_geomShader.reset(); } ShaderProgram& ShaderProgram::operator=(ShaderProgram&& program) noexcept { std::swap(m_index, program.m_index); m_vertShader = std::move(program.m_vertShader); m_fragShader = std::move(program.m_fragShader); m_geomShader = std::move(program.m_geomShader); m_uniforms = std::move(program.m_uniforms); return *this; } ShaderProgram::~ShaderProgram() { if (m_index == GL_INVALID_INDEX) return; glDeleteProgram(m_index); } } // namespace Raz <|endoftext|>
<commit_before>#include "generator.h" #include <cassert> #include <cstring> #include <deque> #include <iostream> #include <map> #include "dictionary.h" #include "label.h" static void compileCall(FILE* f, const char* wordName, bool tailCall, Dictionary* dictionary) { fprintf(f, tailCall ? "\tjmp %s\n" : "\tjsr %s\n", label(wordName).c_str()); dictionary->markAsUsed(wordName); } void generateAsm(FILE* f, const Tokens& tokens, Dictionary* dictionary) { std::deque<int> stack; int localLabel = 0; bool state = false; std::set<int> undefinedVariables; int variableLabel = 0; std::map<std::string, int> variableLabels; for (auto it = tokens.begin(); it != tokens.end(); ++it) { switch (it->type) { case Allot: assert(!stack.empty()); fprintf(f, "* = * + %i\n", stack.back()); stack.pop_back(); break; case Create: ++it; if (it == tokens.end() || it->type != WordName) { fprintf(stderr, "create must be followed by a word name!"); exit(1); } fprintf(f, "\n%s:\n", label(it->stringData).c_str()); dictionary->addWord(it->stringData); free(it->stringData); break; case String: fprintf(f, "\tjsr litstring\n!byte %i\n!text \"%s\"\n", (int)strlen(it->stringData), it->stringData); dictionary->markAsUsed("litstring"); free(it->stringData); break; case Variable: ++it; if (it == tokens.end() || it->type != WordName) { fprintf(stderr, "variable must be followed by a word name!"); exit(1); } fprintf(f, "\n%s:\n", label(it->stringData).c_str()); dictionary->addWord(it->stringData); fprintf(f, "\tlda #<+\n\tldy #>+\n\tjmp pushya\n+\n!word vl_%i\n", variableLabel); undefinedVariables.insert(variableLabel); variableLabels[it->stringData] = variableLabel; ++variableLabel; dictionary->markAsUsed("pushya"); free(it->stringData); break; case Store: if (!state) { int variableLabel = stack.back(); stack.pop_back(); int value = stack.back(); stack.pop_back(); fprintf(f, "vl_%i = %i\n", variableLabel, value); undefinedVariables.erase(variableLabel); break; } else { ++it; bool tailCall = (it != tokens.end() && it->type == SemiColon); --it; compileCall(f, "!", tailCall, dictionary); } break; case WordName: // printf("WordName %s\n", it->stringData); assert(it->stringData); if (state) { ++it; bool tailCall = (it != tokens.end() && it->type == SemiColon); --it; compileCall(f, it->stringData, tailCall, dictionary); if (tailCall) { ++it; // Skips ; } free(it->stringData); } else { char* wordName = it->stringData; if (variableLabels.find(wordName) != variableLabels.end()) { stack.push_back(variableLabels[wordName]); free(it->stringData); } else { fprintf(stderr, "Variable '%s' not defined\n", wordName); exit(1); } } break; case Number: if (state) { dictionary->markAsUsed("lit"); fprintf(f, "\tjsr lit\n\t!word %i\n", it->intData); } else { stack.push_back(it->intData); } break; case Code: { char* p = it->stringData; std::string wordName; while (!isspace(*p)) { wordName.push_back(*p); ++p; } dictionary->addWord(wordName.c_str()); if (*p == '\n') { ++p; } if (label(wordName.c_str()) != wordName) { fprintf(f, "%s:\t; %s\n%s\n", label(wordName.c_str()).c_str(), wordName.c_str(), p); } else { fprintf(f, "%s:\n%s\n", wordName.c_str(), p); } } free(it->stringData); break; case Colon: ++it; if (it == tokens.end() || it->type != WordName) { fprintf(stderr, ": must be followed by a word name! (is type %i)\n", it->type); exit(1); } fprintf(f, "\n%s:", label(it->stringData).c_str()); // printf("Colon %s\n", it->stringData); dictionary->addWord(it->stringData); if (it->stringData != label(it->stringData)) { fprintf(f, "\t; %s", it->stringData); } fprintf(f, "\n"); free(it->stringData); state = true; break; case Drop: fputs("\tinx\t; drop\n", f); break; case SemiColon: fputs("\trts\n", f); state = false; break; case If: fprintf(f, "\tjsr ifcmp\n\tbeq .l%i\n", localLabel); dictionary->markAsUsed("ifcmp"); stack.push_back(localLabel++); break; case Else: fprintf(f, "\tjmp .l%i\n.l%i:\n", localLabel, stack.back()); stack.pop_back(); stack.push_back(localLabel++); break; case Then: fprintf(f, ".l%i:\n", stack.back()); stack.pop_back(); break; case Begin: stack.push_back(localLabel); fprintf(f, ".l%i:\n", localLabel++); break; case Again: fprintf(f, "\tjmp .l%i\n", stack.back()); stack.pop_back(); break; case Value: ++it; if (it == tokens.end() || it->type != WordName) { fprintf(stderr, "value must be followed by a word name!"); exit(1); } fprintf(f, "\n%s:\n", label(it->stringData).c_str()); dictionary->addWord(it->stringData); fprintf(f, "\tlda #%i\n", stack.back() & 0xff); fprintf(f, "\tldy #%i\n", stack.back() >> 8); fprintf(f, "\tjmp pushya\n"); stack.pop_back(); dictionary->markAsUsed("pushya"); free(it->stringData); break; } } } <commit_msg>set state to false on tail calls<commit_after>#include "generator.h" #include <cassert> #include <cstring> #include <deque> #include <iostream> #include <map> #include "dictionary.h" #include "label.h" static void compileCall(FILE* f, const char* wordName, bool tailCall, Dictionary* dictionary) { fprintf(f, tailCall ? "\tjmp %s\n" : "\tjsr %s\n", label(wordName).c_str()); dictionary->markAsUsed(wordName); } void generateAsm(FILE* f, const Tokens& tokens, Dictionary* dictionary) { std::deque<int> stack; int localLabel = 0; bool state = false; std::set<int> undefinedVariables; int variableLabel = 0; std::map<std::string, int> variableLabels; for (auto it = tokens.begin(); it != tokens.end(); ++it) { switch (it->type) { case Allot: assert(!stack.empty()); fprintf(f, "* = * + %i\n", stack.back()); stack.pop_back(); break; case Create: ++it; if (it == tokens.end() || it->type != WordName) { fprintf(stderr, "create must be followed by a word name!"); exit(1); } // printf("Create '%s'\n", it->stringData); fprintf(f, "\n%s:\n", label(it->stringData).c_str()); dictionary->addWord(it->stringData); free(it->stringData); break; case String: fprintf(f, "\tjsr litstring\n!byte %i\n!text \"%s\"\n", (int)strlen(it->stringData), it->stringData); dictionary->markAsUsed("litstring"); free(it->stringData); break; case Variable: // puts("Variable"); ++it; if (it == tokens.end() || it->type != WordName) { fprintf(stderr, "variable must be followed by a word name!"); exit(1); } fprintf(f, "\n%s:\n", label(it->stringData).c_str()); dictionary->addWord(it->stringData); fprintf(f, "\tlda #<+\n\tldy #>+\n\tjmp pushya\n+\n!word vl_%i\n", variableLabel); undefinedVariables.insert(variableLabel); variableLabels[it->stringData] = variableLabel; ++variableLabel; dictionary->markAsUsed("pushya"); free(it->stringData); break; case Store: if (!state) { int variableLabel = stack.back(); stack.pop_back(); int value = stack.back(); stack.pop_back(); fprintf(f, "vl_%i = %i\n", variableLabel, value); undefinedVariables.erase(variableLabel); break; } else { ++it; bool tailCall = (it != tokens.end() && it->type == SemiColon); --it; compileCall(f, "!", tailCall, dictionary); if (tailCall) { ++it; // Skips ; state = false; } } break; case WordName: // printf("WordName %s\n", it->stringData); assert(it->stringData); if (state) { ++it; bool tailCall = (it != tokens.end() && it->type == SemiColon); --it; compileCall(f, it->stringData, tailCall, dictionary); if (tailCall) { ++it; // Skips ; state = false; } free(it->stringData); } else { char* wordName = it->stringData; if (variableLabels.find(wordName) != variableLabels.end()) { stack.push_back(variableLabels[wordName]); free(it->stringData); } else { fprintf(stderr, "Variable '%s' not defined\n", wordName); exit(1); } } break; case Number: // puts("Number"); if (state) { dictionary->markAsUsed("lit"); fprintf(f, "\tjsr lit\n\t!word %i\n", it->intData); } else { stack.push_back(it->intData); } break; case Code: // puts("Code"); { char* p = it->stringData; std::string wordName; while (!isspace(*p)) { wordName.push_back(*p); ++p; } dictionary->addWord(wordName.c_str()); if (*p == '\n') { ++p; } if (label(wordName.c_str()) != wordName) { fprintf(f, "%s:\t; %s\n%s\n", label(wordName.c_str()).c_str(), wordName.c_str(), p); } else { fprintf(f, "%s:\n%s\n", wordName.c_str(), p); } } free(it->stringData); break; case Colon: ++it; if (it == tokens.end() || it->type != WordName) { fprintf(stderr, ": must be followed by a word name! (is type %i)\n", it->type); exit(1); } fprintf(f, "\n%s:", label(it->stringData).c_str()); // printf("Colon %s\n", it->stringData); dictionary->addWord(it->stringData); if (it->stringData != label(it->stringData)) { fprintf(f, "\t; %s", it->stringData); } fprintf(f, "\n"); free(it->stringData); state = true; break; case Drop: fputs("\tinx\t; drop\n", f); break; case SemiColon: fputs("\trts\n", f); state = false; break; case If: fprintf(f, "\tjsr ifcmp\n\tbeq .l%i\n", localLabel); dictionary->markAsUsed("ifcmp"); stack.push_back(localLabel++); break; case Else: fprintf(f, "\tjmp .l%i\n.l%i:\n", localLabel, stack.back()); stack.pop_back(); stack.push_back(localLabel++); break; case Then: fprintf(f, ".l%i:\n", stack.back()); stack.pop_back(); break; case Begin: stack.push_back(localLabel); fprintf(f, ".l%i:\n", localLabel++); break; case Again: fprintf(f, "\tjmp .l%i\n", stack.back()); stack.pop_back(); break; case Value: ++it; if (it == tokens.end() || it->type != WordName) { fprintf(stderr, "value must be followed by a word name!"); exit(1); } fprintf(f, "\n%s:\n", label(it->stringData).c_str()); dictionary->addWord(it->stringData); fprintf(f, "\tlda #%i\n", stack.back() & 0xff); fprintf(f, "\tldy #%i\n", stack.back() >> 8); fprintf(f, "\tjmp pushya\n"); stack.pop_back(); dictionary->markAsUsed("pushya"); free(it->stringData); break; } } } <|endoftext|>
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/memory/scoped_ptr.h" #include "chrome/test/base/testing_profile.h" #include "components/autofill/browser/wallet/encryption_escrow_client.h" #include "components/autofill/browser/wallet/encryption_escrow_client_observer.h" #include "components/autofill/browser/wallet/instrument.h" #include "components/autofill/browser/wallet/wallet_test_util.h" #include "content/public/test/test_browser_thread.h" #include "googleurl/src/gurl.h" #include "net/base/net_errors.h" #include "net/http/http_status_code.h" #include "net/url_request/test_url_fetcher_factory.h" #include "net/url_request/url_fetcher_delegate.h" #include "net/url_request/url_request_status.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace autofill { namespace wallet { namespace { const char kEncryptOtpRequest[] = "cvv=30:000102030405"; const char kEncryptOtpResponse[] = "session_material|encrypted_one_time_pad"; const char kEscrowInstrumentInformationRequest[] = "gid=obfuscated_gaia_id&cardNumber=4444444444444448&cvv=123"; const char kEscrowCardVerificationNumberRequest[] = "gid=obfuscated_gaia_id&cvv=123"; class MockEncryptionEscrowClientObserver : public EncryptionEscrowClientObserver, public base::SupportsWeakPtr<MockEncryptionEscrowClientObserver> { public: MockEncryptionEscrowClientObserver() {} ~MockEncryptionEscrowClientObserver() {} MOCK_METHOD2(OnDidEncryptOneTimePad, void(const std::string& encrypted_one_time_pad, const std::string& session_material)); MOCK_METHOD1(OnDidEscrowCardVerificationNumber, void(const std::string& escrow_handle)); MOCK_METHOD1(OnDidEscrowInstrumentInformation, void(const std::string& escrow_handle)); // TODO(isherman): Add test expectations for calls to this method. MOCK_METHOD0(OnDidMakeRequest, void()); MOCK_METHOD0(OnMalformedResponse, void()); MOCK_METHOD1(OnNetworkError, void(int response_code)); }; } // namespace class TestEncryptionEscrowClient : public EncryptionEscrowClient { public: TestEncryptionEscrowClient( net::URLRequestContextGetter* context_getter, EncryptionEscrowClientObserver* observer) : EncryptionEscrowClient(context_getter, observer) {} bool HasRequestInProgress() const { return request() != NULL; } }; class EncryptionEscrowClientTest : public testing::Test { public: EncryptionEscrowClientTest() : instrument_(GetTestInstrument()), io_thread_(content::BrowserThread::IO) {} virtual void SetUp() OVERRIDE { io_thread_.StartIOThread(); profile_.CreateRequestContext(); encryption_escrow_client_.reset(new TestEncryptionEscrowClient( profile_.GetRequestContext(), &observer_)); } virtual void TearDown() OVERRIDE { encryption_escrow_client_.reset(); profile_.ResetRequestContext(); io_thread_.Stop(); } std::vector<uint8> MakeOneTimePad() { std::vector<uint8> one_time_pad; one_time_pad.push_back(0); one_time_pad.push_back(1); one_time_pad.push_back(2); one_time_pad.push_back(3); one_time_pad.push_back(4); one_time_pad.push_back(5); return one_time_pad; } void VerifyAndFinishRequest(net::HttpStatusCode response_code, const std::string& request_body, const std::string& response_body) { net::TestURLFetcher* fetcher = factory_.GetFetcherByID(1); ASSERT_TRUE(fetcher); EXPECT_EQ(request_body, fetcher->upload_data()); fetcher->set_response_code(response_code); fetcher->SetResponseString(response_body); fetcher->delegate()->OnURLFetchComplete(fetcher); } protected: scoped_ptr<TestEncryptionEscrowClient> encryption_escrow_client_; testing::StrictMock<MockEncryptionEscrowClientObserver> observer_; scoped_ptr<Instrument> instrument_; private: // The profile's request context must be released on the IO thread. content::TestBrowserThread io_thread_; TestingProfile profile_; net::TestURLFetcherFactory factory_; }; TEST_F(EncryptionEscrowClientTest, NetworkError) { EXPECT_CALL(observer_, OnDidMakeRequest()).Times(1); EXPECT_CALL(observer_, OnNetworkError(net::HTTP_UNAUTHORIZED)).Times(1); encryption_escrow_client_->EscrowInstrumentInformation(*instrument_, "obfuscated_gaia_id"); VerifyAndFinishRequest(net::HTTP_UNAUTHORIZED, kEscrowInstrumentInformationRequest, std::string()); } TEST_F(EncryptionEscrowClientTest, EscrowInstrumentInformationSuccess) { EXPECT_CALL(observer_, OnDidMakeRequest()).Times(1); EXPECT_CALL(observer_, OnDidEscrowInstrumentInformation("abc")).Times(1); encryption_escrow_client_->EscrowInstrumentInformation(*instrument_, "obfuscated_gaia_id"); VerifyAndFinishRequest(net::HTTP_OK, kEscrowInstrumentInformationRequest, "abc"); } TEST_F(EncryptionEscrowClientTest, EscrowInstrumentInformationFailure) { EXPECT_CALL(observer_, OnDidMakeRequest()).Times(1); EXPECT_CALL(observer_, OnMalformedResponse()).Times(1); encryption_escrow_client_->EscrowInstrumentInformation(*instrument_, "obfuscated_gaia_id"); VerifyAndFinishRequest(net::HTTP_OK, kEscrowInstrumentInformationRequest, std::string()); } TEST_F(EncryptionEscrowClientTest, EscrowCardVerificationNumberSuccess) { EXPECT_CALL(observer_, OnDidMakeRequest()).Times(1); EXPECT_CALL(observer_, OnDidEscrowCardVerificationNumber("abc")).Times(1); encryption_escrow_client_->EscrowCardVerificationNumber("123", "obfuscated_gaia_id"); VerifyAndFinishRequest(net::HTTP_OK, kEscrowCardVerificationNumberRequest, "abc"); } TEST_F(EncryptionEscrowClientTest, EscrowCardVerificationNumberFailure) { EXPECT_CALL(observer_, OnDidMakeRequest()).Times(1); EXPECT_CALL(observer_, OnMalformedResponse()).Times(1); encryption_escrow_client_->EscrowCardVerificationNumber("123", "obfuscated_gaia_id"); VerifyAndFinishRequest(net::HTTP_OK, kEscrowCardVerificationNumberRequest, std::string()); } TEST_F(EncryptionEscrowClientTest, EncryptOneTimePadSuccess) { EXPECT_CALL(observer_, OnDidMakeRequest()).Times(1); EXPECT_CALL(observer_, OnDidEncryptOneTimePad("encrypted_one_time_pad", "session_material")).Times(1); encryption_escrow_client_->EncryptOneTimePad(MakeOneTimePad()); VerifyAndFinishRequest(net::HTTP_OK, kEncryptOtpRequest, kEncryptOtpResponse); } TEST_F(EncryptionEscrowClientTest, EncryptOneTimePadFailure) { EXPECT_CALL(observer_, OnDidMakeRequest()).Times(1); EXPECT_CALL(observer_, OnMalformedResponse()).Times(1); encryption_escrow_client_->EncryptOneTimePad(MakeOneTimePad()); VerifyAndFinishRequest(net::HTTP_OK, kEncryptOtpRequest, std::string()); } TEST_F(EncryptionEscrowClientTest, CancelRequest) { EXPECT_CALL(observer_, OnDidMakeRequest()).Times(1); encryption_escrow_client_->EncryptOneTimePad(MakeOneTimePad()); EXPECT_TRUE(encryption_escrow_client_->HasRequestInProgress()); encryption_escrow_client_->CancelRequest(); EXPECT_FALSE(encryption_escrow_client_->HasRequestInProgress()); } } // namespace wallet } // namespace autofill <commit_msg>Remove a stale TODO<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/memory/scoped_ptr.h" #include "chrome/test/base/testing_profile.h" #include "components/autofill/browser/wallet/encryption_escrow_client.h" #include "components/autofill/browser/wallet/encryption_escrow_client_observer.h" #include "components/autofill/browser/wallet/instrument.h" #include "components/autofill/browser/wallet/wallet_test_util.h" #include "content/public/test/test_browser_thread.h" #include "googleurl/src/gurl.h" #include "net/base/net_errors.h" #include "net/http/http_status_code.h" #include "net/url_request/test_url_fetcher_factory.h" #include "net/url_request/url_fetcher_delegate.h" #include "net/url_request/url_request_status.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace autofill { namespace wallet { namespace { const char kEncryptOtpRequest[] = "cvv=30:000102030405"; const char kEncryptOtpResponse[] = "session_material|encrypted_one_time_pad"; const char kEscrowInstrumentInformationRequest[] = "gid=obfuscated_gaia_id&cardNumber=4444444444444448&cvv=123"; const char kEscrowCardVerificationNumberRequest[] = "gid=obfuscated_gaia_id&cvv=123"; class MockEncryptionEscrowClientObserver : public EncryptionEscrowClientObserver, public base::SupportsWeakPtr<MockEncryptionEscrowClientObserver> { public: MockEncryptionEscrowClientObserver() {} ~MockEncryptionEscrowClientObserver() {} MOCK_METHOD2(OnDidEncryptOneTimePad, void(const std::string& encrypted_one_time_pad, const std::string& session_material)); MOCK_METHOD1(OnDidEscrowCardVerificationNumber, void(const std::string& escrow_handle)); MOCK_METHOD1(OnDidEscrowInstrumentInformation, void(const std::string& escrow_handle)); MOCK_METHOD0(OnDidMakeRequest, void()); MOCK_METHOD0(OnMalformedResponse, void()); MOCK_METHOD1(OnNetworkError, void(int response_code)); }; } // namespace class TestEncryptionEscrowClient : public EncryptionEscrowClient { public: TestEncryptionEscrowClient( net::URLRequestContextGetter* context_getter, EncryptionEscrowClientObserver* observer) : EncryptionEscrowClient(context_getter, observer) {} bool HasRequestInProgress() const { return request() != NULL; } }; class EncryptionEscrowClientTest : public testing::Test { public: EncryptionEscrowClientTest() : instrument_(GetTestInstrument()), io_thread_(content::BrowserThread::IO) {} virtual void SetUp() OVERRIDE { io_thread_.StartIOThread(); profile_.CreateRequestContext(); encryption_escrow_client_.reset(new TestEncryptionEscrowClient( profile_.GetRequestContext(), &observer_)); } virtual void TearDown() OVERRIDE { encryption_escrow_client_.reset(); profile_.ResetRequestContext(); io_thread_.Stop(); } std::vector<uint8> MakeOneTimePad() { std::vector<uint8> one_time_pad; one_time_pad.push_back(0); one_time_pad.push_back(1); one_time_pad.push_back(2); one_time_pad.push_back(3); one_time_pad.push_back(4); one_time_pad.push_back(5); return one_time_pad; } void VerifyAndFinishRequest(net::HttpStatusCode response_code, const std::string& request_body, const std::string& response_body) { net::TestURLFetcher* fetcher = factory_.GetFetcherByID(1); ASSERT_TRUE(fetcher); EXPECT_EQ(request_body, fetcher->upload_data()); fetcher->set_response_code(response_code); fetcher->SetResponseString(response_body); fetcher->delegate()->OnURLFetchComplete(fetcher); } protected: scoped_ptr<TestEncryptionEscrowClient> encryption_escrow_client_; testing::StrictMock<MockEncryptionEscrowClientObserver> observer_; scoped_ptr<Instrument> instrument_; private: // The profile's request context must be released on the IO thread. content::TestBrowserThread io_thread_; TestingProfile profile_; net::TestURLFetcherFactory factory_; }; TEST_F(EncryptionEscrowClientTest, NetworkError) { EXPECT_CALL(observer_, OnDidMakeRequest()).Times(1); EXPECT_CALL(observer_, OnNetworkError(net::HTTP_UNAUTHORIZED)).Times(1); encryption_escrow_client_->EscrowInstrumentInformation(*instrument_, "obfuscated_gaia_id"); VerifyAndFinishRequest(net::HTTP_UNAUTHORIZED, kEscrowInstrumentInformationRequest, std::string()); } TEST_F(EncryptionEscrowClientTest, EscrowInstrumentInformationSuccess) { EXPECT_CALL(observer_, OnDidMakeRequest()).Times(1); EXPECT_CALL(observer_, OnDidEscrowInstrumentInformation("abc")).Times(1); encryption_escrow_client_->EscrowInstrumentInformation(*instrument_, "obfuscated_gaia_id"); VerifyAndFinishRequest(net::HTTP_OK, kEscrowInstrumentInformationRequest, "abc"); } TEST_F(EncryptionEscrowClientTest, EscrowInstrumentInformationFailure) { EXPECT_CALL(observer_, OnDidMakeRequest()).Times(1); EXPECT_CALL(observer_, OnMalformedResponse()).Times(1); encryption_escrow_client_->EscrowInstrumentInformation(*instrument_, "obfuscated_gaia_id"); VerifyAndFinishRequest(net::HTTP_OK, kEscrowInstrumentInformationRequest, std::string()); } TEST_F(EncryptionEscrowClientTest, EscrowCardVerificationNumberSuccess) { EXPECT_CALL(observer_, OnDidMakeRequest()).Times(1); EXPECT_CALL(observer_, OnDidEscrowCardVerificationNumber("abc")).Times(1); encryption_escrow_client_->EscrowCardVerificationNumber("123", "obfuscated_gaia_id"); VerifyAndFinishRequest(net::HTTP_OK, kEscrowCardVerificationNumberRequest, "abc"); } TEST_F(EncryptionEscrowClientTest, EscrowCardVerificationNumberFailure) { EXPECT_CALL(observer_, OnDidMakeRequest()).Times(1); EXPECT_CALL(observer_, OnMalformedResponse()).Times(1); encryption_escrow_client_->EscrowCardVerificationNumber("123", "obfuscated_gaia_id"); VerifyAndFinishRequest(net::HTTP_OK, kEscrowCardVerificationNumberRequest, std::string()); } TEST_F(EncryptionEscrowClientTest, EncryptOneTimePadSuccess) { EXPECT_CALL(observer_, OnDidMakeRequest()).Times(1); EXPECT_CALL(observer_, OnDidEncryptOneTimePad("encrypted_one_time_pad", "session_material")).Times(1); encryption_escrow_client_->EncryptOneTimePad(MakeOneTimePad()); VerifyAndFinishRequest(net::HTTP_OK, kEncryptOtpRequest, kEncryptOtpResponse); } TEST_F(EncryptionEscrowClientTest, EncryptOneTimePadFailure) { EXPECT_CALL(observer_, OnDidMakeRequest()).Times(1); EXPECT_CALL(observer_, OnMalformedResponse()).Times(1); encryption_escrow_client_->EncryptOneTimePad(MakeOneTimePad()); VerifyAndFinishRequest(net::HTTP_OK, kEncryptOtpRequest, std::string()); } TEST_F(EncryptionEscrowClientTest, CancelRequest) { EXPECT_CALL(observer_, OnDidMakeRequest()).Times(1); encryption_escrow_client_->EncryptOneTimePad(MakeOneTimePad()); EXPECT_TRUE(encryption_escrow_client_->HasRequestInProgress()); encryption_escrow_client_->CancelRequest(); EXPECT_FALSE(encryption_escrow_client_->HasRequestInProgress()); } } // namespace wallet } // namespace autofill <|endoftext|>
<commit_before>// // Copyright (c) 2013-2014 Christoph Malek // See LICENSE for more information. // #ifndef RJ_GAME_BACKGROUND_BACKGROUND_MANAGER_HPP #define RJ_GAME_BACKGROUND_BACKGROUND_MANAGER_HPP #include "background_component.hpp" #include "basic_background_component.hpp" #include <rectojump/game/components/gradient_rect.hpp> #include <mlk/containers/container_utl.h> #include <mlk/types/types.h> namespace rj { class game; class background_manager { using bbc_ptr = mlk::sptr<basic_background_component>; game& m_game; gradient_rect m_bgshape; sf::RectangleShape m_textureshape; std::vector<bbc_ptr> m_components; public: background_manager(game& g) : m_game{g} { } void update(dur duration) { for(auto& a : m_components) a->update(duration); this->erase_destroyed(); } void render() { rndr::ro(m_game, m_bgshape); for(auto& a : m_components) a->render(); rndr::ro(m_game, m_textureshape); } void set_bg_shape(const gradient_rect& shape) noexcept {m_bgshape = shape;} void set_tx_shape(const sf::RectangleShape& shape) noexcept {m_textureshape = shape;} template<typename Obj_Type, typename... Args> mlk::sptr<background_component<Obj_Type>> create_object(Args&&... args) { auto ptr(std::make_shared<background_component<Obj_Type>>(m_game, std::forward<Args>(args)...)); m_components.emplace_back(ptr); return ptr; } private: void erase_destroyed() noexcept { mlk::cnt::remove_all_if( [](const bbc_ptr& p){return p->is_destroyed();}, m_components); } }; } #endif // RJ_GAME_BACKGROUND_BACKGROUND_MANAGER_HPP <commit_msg>added num_components()<commit_after>// // Copyright (c) 2013-2014 Christoph Malek // See LICENSE for more information. // #ifndef RJ_GAME_BACKGROUND_BACKGROUND_MANAGER_HPP #define RJ_GAME_BACKGROUND_BACKGROUND_MANAGER_HPP #include "background_component.hpp" #include "basic_background_component.hpp" #include <rectojump/game/components/gradient_rect.hpp> #include <mlk/containers/container_utl.h> #include <mlk/types/types.h> namespace rj { class game; class background_manager { using bbc_ptr = mlk::sptr<basic_background_component>; game& m_game; gradient_rect m_bgshape; sf::RectangleShape m_textureshape; std::vector<bbc_ptr> m_components; public: background_manager(game& g) : m_game{g} { } void update(dur duration) { for(auto& a : m_components) a->update(duration); this->erase_destroyed(); } void render() { rndr::ro(m_game, m_bgshape); for(auto& a : m_components) a->render(); rndr::ro(m_game, m_textureshape); } template<typename Obj_Type, typename... Args> mlk::sptr<background_component<Obj_Type>> create_object(Args&&... args) { auto ptr(std::make_shared<background_component<Obj_Type>>(m_game, std::forward<Args>(args)...)); m_components.emplace_back(ptr); return ptr; } void set_bg_shape(const gradient_rect& shape) noexcept {m_bgshape = shape;} void set_tx_shape(const sf::RectangleShape& shape) noexcept {m_textureshape = shape;} std::size_t num_components() const noexcept {return m_components.size();} private: void erase_destroyed() noexcept { mlk::cnt::remove_all_if( [](const bbc_ptr& p){return p->is_destroyed();}, m_components); } }; } #endif // RJ_GAME_BACKGROUND_BACKGROUND_MANAGER_HPP <|endoftext|>
<commit_before>// @(#)root/pgsql:$Name: $:$Id: TPgSQLServer.cxx,v 1.5 2002/04/02 15:44:15 rdm Exp $ // Author: g.p.ciceri <[email protected]> 01/06/2001 /************************************************************************* * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TPgSQLServer.h" #include "TPgSQLResult.h" #include "TUrl.h" ClassImp(TPgSQLServer) //______________________________________________________________________________ TPgSQLServer::TPgSQLServer(const char *db, const char *uid, const char *pw) { // Open a connection to a PgSQL DB server. The db arguments should be // of the form "pgsql://<host>[:<port>][/<database>]", e.g.: // "pgsql://pcroot.cern.ch:3456/test". The uid is the username and pw // the password that should be used for the connection. fPgSQL = 0; TUrl url(db); if (!url.IsValid()) { Error("TPgSQLServer", "malformed db argument %s", db); MakeZombie(); return; } if (strncmp(url.GetProtocol(), "pgsql", 5)) { Error("TPgSQLServer", "protocol in db argument should be pgsql it is %s", url.GetProtocol()); MakeZombie(); return; } const char *dbase = url.GetFile(); if (url.GetPort()) { TString port; port += url.GetPort(); fPgSQL = PQsetdbLogin(url.GetHost(), port, 0, 0, dbase, uid, pw); } else fPgSQL = PQsetdbLogin(url.GetHost(), 0, 0, 0, dbase, uid, pw); if (PQstatus(fPgSQL) != CONNECTION_BAD) { fType = "PgSQL"; fHost = url.GetHost(); fDB = dbase; fPort = url.GetPort(); } else { Error("TPgSQLServer", "connection to %s failed", url.GetHost()); MakeZombie(); } } //______________________________________________________________________________ TPgSQLServer::~TPgSQLServer() { // Close connection to PgSQL DB server. if (IsConnected()) Close(); } //______________________________________________________________________________ void TPgSQLServer::Close(Option_t *) { // Close connection to PgSQL DB server. if (!fPgSQL) return; PQfinish(fPgSQL); fPort = -1; } //______________________________________________________________________________ TSQLResult *TPgSQLServer::Query(const char *sql) { // Execute SQL command. Result object must be deleted by the user. // Returns a pointer to a TSQLResult object if successful, 0 otherwise. // The result object must be deleted by the user. if (!IsConnected()) { Error("Query", "not connected"); return 0; } PGresult *res = PQexec(fPgSQL, sql); if ((PQresultStatus(res) != PGRES_COMMAND_OK) && (PQresultStatus(res) != PGRES_TUPLES_OK)) { Error("Query", PQresultErrorMessage(res)); PQclear(res); return 0; } return new TPgSQLResult(res); } //______________________________________________________________________________ Int_t TPgSQLServer::SelectDataBase(const char *dbname) { // Select a database. Returns 0 if successful, non-zero otherwise. // For PgSQL: only to be used to check the dbname. if (!IsConnected()) { Error("SelectDataBase", "not connected"); return -1; } if (fDB != dbname) { Error("SelectDataBase", "no such database"); return -1; } return 0; } //______________________________________________________________________________ TSQLResult *TPgSQLServer::GetDataBases(const char *wild) { // List all available databases. Wild is for wildcarding "t%" list all // databases starting with "t". // Returns a pointer to a TSQLResult object if successful, 0 otherwise. // The result object must be deleted by the user. if (!IsConnected()) { Error("GetDataBases", "not connected"); return 0; } TString sql = "SELECT pg_database.datname FROM pg_database"; if (wild) sql += Form(" WHERE pg_database.datname LIKE '%s'", wild); return Query(sql); } //______________________________________________________________________________ TSQLResult *TPgSQLServer::GetTables(const char *dbname, const char *wild) { // List all tables in the specified database. Wild is for wildcarding // "t%" list all tables starting with "t". // Returns a pointer to a TSQLResult object if successful, 0 otherwise. // The result object must be deleted by the user. if (!IsConnected()) { Error("GetTables", "not connected"); return 0; } if (SelectDataBase(dbname) != 0) { Error("GetTables", "no such database %s", dbname); return 0; } TString sql = "SELECT relname FROM pg_class"; if (wild) sql += Form(" WHERE relname LIKE '%s'", wild); return Query(sql); } //______________________________________________________________________________ TSQLResult *TPgSQLServer::GetColumns(const char *dbname, const char *table, const char *wild) { // List all columns in specified table in the specified database. // Wild is for wildcarding "t%" list all columns starting with "t". // Returns a pointer to a TSQLResult object if successful, 0 otherwise. // The result object must be deleted by the user. if (!IsConnected()) { Error("GetColumns", "not connected"); return 0; } if (SelectDataBase(dbname) != 0) { Error("GetColumns", "no such database %s", dbname); return 0; } char *sql; if (wild) sql = Form("SELECT RELNAME FROM %s LIKE %s", table, wild); else sql = Form("SELECT RELNAME FROM %s", table); //return Query(sql); Error("GetColumns", "not implemented"); return 0; } //______________________________________________________________________________ Int_t TPgSQLServer::CreateDataBase(const char *dbname) { // Create a database. Returns 0 if successful, non-zero otherwise. if (!IsConnected()) { Error("CreateDataBase", "not connected"); return -1; } char *sql; sql = Form("CREATE DATABASE %s", dbname); PGresult *res = PQexec(fPgSQL, sql); PQclear(res); return 0; } //______________________________________________________________________________ Int_t TPgSQLServer::DropDataBase(const char *dbname) { // Drop (i.e. delete) a database. Returns 0 if successful, non-zero // otherwise. if (!IsConnected()) { Error("DropDataBase", "not connected"); return -1; } char *sql; sql = Form("DROP DATABASE %s", dbname); PGresult *res = PQexec(fPgSQL, sql); PQclear(res); return 0; } //______________________________________________________________________________ Int_t TPgSQLServer::Reload() { // Reload permission tables. Returns 0 if successful, non-zero // otherwise. User must have reload permissions. if (!IsConnected()) { Error("Reload", "not connected"); return -1; } Error("Reload", "not implemented"); return 0; } //______________________________________________________________________________ Int_t TPgSQLServer::Shutdown() { // Shutdown the database server. Returns 0 if successful, non-zero // otherwise. User must have shutdown permissions. if (!IsConnected()) { Error("Shutdown", "not connected"); return -1; } Error("Shutdown", "not implemented"); return 0; } //______________________________________________________________________________ const char *TPgSQLServer::ServerInfo() { // Return server info. if (!IsConnected()) { Error("ServerInfo", "not connected"); return 0; } Error("ServerInfo", "not implemented"); return 0; } <commit_msg>From Dennis Box: I was looking at TPgSQLServer.cxx and I noticed some unimplemented functionality which I knew how to fix: 1) SelectDataBase(const char* dbname) actually changes connection to specified database 'dbname' 2) GetColumns(db,table,wc) is implemented 3) ServerInfo() is implemented<commit_after>// @(#)root/pgsql:$Name:$:$Id: TPgSQLServer.cxx,v 1.6 2006/05/31 14:45:41 rdm Exp $ // Author: g.p.ciceri <[email protected]> 01/06/2001 /************************************************************************* * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TPgSQLServer.h" #include "TPgSQLResult.h" #include "TUrl.h" ClassImp(TPgSQLServer) //______________________________________________________________________________ TPgSQLServer::TPgSQLServer(const char *db, const char *uid, const char *pw) { // Open a connection to a PgSQL DB server. The db arguments should be // of the form "pgsql://<host>[:<port>][/<database>]", e.g.: // "pgsql://pcroot.cern.ch:3456/test". The uid is the username and pw // the password that should be used for the connection. fPgSQL = 0; TUrl url(db); if (!url.IsValid()) { Error("TPgSQLServer", "malformed db argument %s", db); MakeZombie(); return; } if (strncmp(url.GetProtocol(), "pgsql", 5)) { Error("TPgSQLServer", "protocol in db argument should be pgsql it is %s", url.GetProtocol()); MakeZombie(); return; } const char *dbase = url.GetFile(); if (url.GetPort()) { TString port; port += url.GetPort(); fPgSQL = PQsetdbLogin(url.GetHost(), port, 0, 0, dbase, uid, pw); } else fPgSQL = PQsetdbLogin(url.GetHost(), 0, 0, 0, dbase, uid, pw); if (PQstatus(fPgSQL) != CONNECTION_BAD) { fType = "PgSQL"; fHost = url.GetHost(); fDB = dbase; fPort = url.GetPort(); } else { Error("TPgSQLServer", "connection to %s failed", url.GetHost()); MakeZombie(); } } //______________________________________________________________________________ TPgSQLServer::~TPgSQLServer() { // Close connection to PgSQL DB server. if (IsConnected()) Close(); } //______________________________________________________________________________ void TPgSQLServer::Close(Option_t *) { // Close connection to PgSQL DB server. if (!fPgSQL) return; PQfinish(fPgSQL); fPort = -1; } //______________________________________________________________________________ TSQLResult *TPgSQLServer::Query(const char *sql) { // Execute SQL command. Result object must be deleted by the user. // Returns a pointer to a TSQLResult object if successful, 0 otherwise. // The result object must be deleted by the user. if (!IsConnected()) { Error("Query", "not connected"); return 0; } PGresult *res = PQexec(fPgSQL, sql); if ((PQresultStatus(res) != PGRES_COMMAND_OK) && (PQresultStatus(res) != PGRES_TUPLES_OK)) { Error("Query", PQresultErrorMessage(res)); PQclear(res); return 0; } return new TPgSQLResult(res); } //______________________________________________________________________________ Int_t TPgSQLServer::SelectDataBase(const char *dbname) { // Select a database. Returns 0 if successful, non-zero otherwise. TString usr; TString pwd; TString port; TString opts; if (!IsConnected()) { Error("SelectDataBase", "not connected"); return -1; } if (dbname == fDB) { return 0; } else { usr = PQuser(fPgSQL); pwd = PQpass(fPgSQL); port = PQport(fPgSQL); opts = PQoptions(fPgSQL); Close(); fPgSQL = PQsetdbLogin(fHost.Data(), port.Data(), opts.Data(), 0, dbname, usr.Data(), pwd.Data()); if (PQstatus(fPgSQL) == CONNECTION_OK) { fDB=dbname; fPort=port.Atoi(); } else { Error("SelectDataBase", PQerrorMessage(fPgSQL)); return -1; } } return 0; } //______________________________________________________________________________ TSQLResult *TPgSQLServer::GetDataBases(const char *wild) { // List all available databases. Wild is for wildcarding "t%" list all // databases starting with "t". // Returns a pointer to a TSQLResult object if successful, 0 otherwise. // The result object must be deleted by the user. if (!IsConnected()) { Error("GetDataBases", "not connected"); return 0; } TString sql = "SELECT pg_database.datname FROM pg_database"; if (wild) sql += Form(" WHERE pg_database.datname LIKE '%s'", wild); return Query(sql); } //______________________________________________________________________________ TSQLResult *TPgSQLServer::GetTables(const char *dbname, const char *wild) { // List all tables in the specified database. Wild is for wildcarding // "t%" list all tables starting with "t". // Returns a pointer to a TSQLResult object if successful, 0 otherwise. // The result object must be deleted by the user. if (!IsConnected()) { Error("GetTables", "not connected"); return 0; } if (SelectDataBase(dbname) != 0) { Error("GetTables", "no such database %s", dbname); return 0; } TString sql = "SELECT relname FROM pg_class"; if (wild) sql += Form(" WHERE relname LIKE '%s'", wild); return Query(sql); } //______________________________________________________________________________ TSQLResult *TPgSQLServer::GetColumns(const char *dbname, const char *table, const char *wild) { // List all columns in specified table in the specified database. // Wild is for wildcarding "t%" list all columns starting with "t". // Returns a pointer to a TSQLResult object if successful, 0 otherwise. // The result object must be deleted by the user. if (!IsConnected()) { Error("GetColumns", "not connected"); return 0; } if (SelectDataBase(dbname) != 0) { Error("GetColumns", "no such database %s", dbname); return 0; } char *sql; if (wild) sql = Form("select a.attname,t.typname,a.attnotnull \ from pg_attribute a, pg_class c, pg_type t \ where c.oid=a.attrelid and c.relname='%s' and \ a.atttypid=t.oid and a.attnum>0 \ and a.attname like '%s' order by a.attnum ", table,wild); else sql = Form("select a.attname,t.typname,a.attnotnull \ from pg_attribute a, pg_class c, pg_type t \ where c.oid=a.attrelid and c.relname='%s' and \ a.atttypid=t.oid and a.attnum>0 order by a.attnum",table); return Query(sql); } //______________________________________________________________________________ Int_t TPgSQLServer::CreateDataBase(const char *dbname) { // Create a database. Returns 0 if successful, non-zero otherwise. if (!IsConnected()) { Error("CreateDataBase", "not connected"); return -1; } char *sql; sql = Form("CREATE DATABASE %s", dbname); PGresult *res = PQexec(fPgSQL, sql); PQclear(res); return 0; } //______________________________________________________________________________ Int_t TPgSQLServer::DropDataBase(const char *dbname) { // Drop (i.e. delete) a database. Returns 0 if successful, non-zero // otherwise. if (!IsConnected()) { Error("DropDataBase", "not connected"); return -1; } char *sql; sql = Form("DROP DATABASE %s", dbname); PGresult *res = PQexec(fPgSQL, sql); PQclear(res); return 0; } //______________________________________________________________________________ Int_t TPgSQLServer::Reload() { // Reload permission tables. Returns 0 if successful, non-zero // otherwise. User must have reload permissions. if (!IsConnected()) { Error("Reload", "not connected"); return -1; } Error("Reload", "not implemented"); return 0; } //______________________________________________________________________________ Int_t TPgSQLServer::Shutdown() { // Shutdown the database server. Returns 0 if successful, non-zero // otherwise. User must have shutdown permissions. if (!IsConnected()) { Error("Shutdown", "not connected"); return -1; } Error("Shutdown", "not implemented"); return 0; } //______________________________________________________________________________ const char *TPgSQLServer::ServerInfo() { // Return server info. TString svrinfo = "postgres "; if (!IsConnected()) { Error("ServerInfo", "not connected"); return 0; } char *sql = "select setting from pg_settings where name='server_version'"; PGresult *res = PQexec(fPgSQL, sql); int stat = PQresultStatus(res); if (stat == PGRES_TUPLES_OK && PQntuples(res)) { char *vers = PQgetvalue(res,0,0); svrinfo += vers; } else svrinfo += "unknown version number"; return svrinfo; } <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osg/AnimationPath> #include <osg/MatrixTransform> #include <osg/PositionAttitudeTransform> using namespace osg; void AnimationPath::insert(double time,const ControlPoint& controlPoint) { _timeControlPointMap[time] = controlPoint; } bool AnimationPath::getInterpolatedControlPoint(double time,ControlPoint& controlPoint) const { if (_timeControlPointMap.empty()) return false; switch(_loopMode) { case(SWING): { double modulated_time = (time - getFirstTime())/(getPeriod()*2.0); double fraction_part = modulated_time - floor(modulated_time); if (fraction_part>0.5) fraction_part = 1.0-fraction_part; time = getFirstTime()+(fraction_part*2.0) * getPeriod(); break; } case(LOOP): { double modulated_time = (time - getFirstTime())/getPeriod(); double fraction_part = modulated_time - floor(modulated_time); time = getFirstTime()+fraction_part * getPeriod(); break; } case(NO_LOOPING): // no need to modulate the time. break; } TimeControlPointMap::const_iterator second = _timeControlPointMap.lower_bound(time); if (second==_timeControlPointMap.begin()) { controlPoint = second->second; } else if (second!=_timeControlPointMap.end()) { TimeControlPointMap::const_iterator first = second; --first; // we have both a lower bound and the next item. // deta_time = second.time - first.time double delta_time = second->first - first->first; if (delta_time==0.0) controlPoint = first->second; else { controlPoint.interpolate((time - first->first)/delta_time, first->second, second->second); } } else // (second==_timeControlPointMap.end()) { controlPoint = _timeControlPointMap.rbegin()->second; } return true; } void AnimationPath::read(std::istream& in) { while (!in.eof()) { double time; osg::Vec3d position; osg::Quat rotation; in >> time >> position.x() >> position.y() >> position.z() >> rotation.x() >> rotation.y() >> rotation.z() >> rotation.w(); if(!in.eof()) insert(time,osg::AnimationPath::ControlPoint(position,rotation)); } } void AnimationPath::write(std::ostream& fout) const { int prec = fout.precision(); fout.precision(15); const TimeControlPointMap& tcpm = getTimeControlPointMap(); for(TimeControlPointMap::const_iterator tcpmitr=tcpm.begin(); tcpmitr!=tcpm.end(); ++tcpmitr) { const ControlPoint& cp = tcpmitr->second; fout<<tcpmitr->first<<" "<<cp._position<<" "<<cp._rotation<<std::endl; } fout.precision(prec); } class AnimationPathCallbackVisitor : public NodeVisitor { public: AnimationPathCallbackVisitor(const AnimationPath::ControlPoint& cp, const osg::Vec3d& pivotPoint, bool useInverseMatrix): _cp(cp), _pivotPoint(pivotPoint), _useInverseMatrix(useInverseMatrix) {} virtual void apply(MatrixTransform& mt) { Matrix matrix; if (_useInverseMatrix) _cp.getInverse(matrix); else _cp.getMatrix(matrix); mt.setMatrix(osg::Matrix::translate(-_pivotPoint)*matrix); } virtual void apply(PositionAttitudeTransform& pat) { if (_useInverseMatrix) { Matrix matrix; _cp.getInverse(matrix); pat.setPosition(matrix.getTrans()); pat.setAttitude(_cp._rotation.inverse()); pat.setScale(osg::Vec3(1.0f/_cp._scale.x(),1.0f/_cp._scale.y(),1.0f/_cp._scale.z())); pat.setPivotPoint(_pivotPoint); } else { pat.setPosition(_cp._position); pat.setAttitude(_cp._rotation); pat.setScale(_cp._scale); pat.setPivotPoint(_pivotPoint); } } AnimationPath::ControlPoint _cp; osg::Vec3d _pivotPoint; bool _useInverseMatrix; }; void AnimationPathCallback::operator()(Node* node, NodeVisitor* nv) { if (_animationPath.valid() && nv->getVisitorType()==NodeVisitor::UPDATE_VISITOR && nv->getFrameStamp()) { double time = nv->getFrameStamp()->getReferenceTime(); _latestTime = time; if (!_pause) { // Only update _firstTime the first time, when its value is still DBL_MAX if (_firstTime==DBL_MAX) _firstTime = time; update(*node); } } // must call any nested node callbacks and continue subgraph traversal. NodeCallback::traverse(node,nv); } double AnimationPathCallback::getAnimationTime() const { return ((_latestTime-_firstTime)-_timeOffset)*_timeMultiplier; } void AnimationPathCallback::update(osg::Node& node) { AnimationPath::ControlPoint cp; if (_animationPath->getInterpolatedControlPoint(getAnimationTime(),cp)) { AnimationPathCallbackVisitor apcv(cp,_pivotPoint,_useInverseMatrix); node.accept(apcv); } } void AnimationPathCallback::reset() { _firstTime = _latestTime; _pauseTime = _latestTime; } void AnimationPathCallback::setPause(bool pause) { if (_pause==pause) { return; } _pause = pause; if (_pause) { _pauseTime = _latestTime; } else { _firstTime += (_latestTime-_pauseTime); } } <commit_msg>Changed the AnimationPathCallback::reset() to reset the _firstTime to DBL_MAX so that it resets on the next update traversal.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osg/AnimationPath> #include <osg/MatrixTransform> #include <osg/PositionAttitudeTransform> using namespace osg; void AnimationPath::insert(double time,const ControlPoint& controlPoint) { _timeControlPointMap[time] = controlPoint; } bool AnimationPath::getInterpolatedControlPoint(double time,ControlPoint& controlPoint) const { if (_timeControlPointMap.empty()) return false; switch(_loopMode) { case(SWING): { double modulated_time = (time - getFirstTime())/(getPeriod()*2.0); double fraction_part = modulated_time - floor(modulated_time); if (fraction_part>0.5) fraction_part = 1.0-fraction_part; time = getFirstTime()+(fraction_part*2.0) * getPeriod(); break; } case(LOOP): { double modulated_time = (time - getFirstTime())/getPeriod(); double fraction_part = modulated_time - floor(modulated_time); time = getFirstTime()+fraction_part * getPeriod(); break; } case(NO_LOOPING): // no need to modulate the time. break; } TimeControlPointMap::const_iterator second = _timeControlPointMap.lower_bound(time); if (second==_timeControlPointMap.begin()) { controlPoint = second->second; } else if (second!=_timeControlPointMap.end()) { TimeControlPointMap::const_iterator first = second; --first; // we have both a lower bound and the next item. // deta_time = second.time - first.time double delta_time = second->first - first->first; if (delta_time==0.0) controlPoint = first->second; else { controlPoint.interpolate((time - first->first)/delta_time, first->second, second->second); } } else // (second==_timeControlPointMap.end()) { controlPoint = _timeControlPointMap.rbegin()->second; } return true; } void AnimationPath::read(std::istream& in) { while (!in.eof()) { double time; osg::Vec3d position; osg::Quat rotation; in >> time >> position.x() >> position.y() >> position.z() >> rotation.x() >> rotation.y() >> rotation.z() >> rotation.w(); if(!in.eof()) insert(time,osg::AnimationPath::ControlPoint(position,rotation)); } } void AnimationPath::write(std::ostream& fout) const { int prec = fout.precision(); fout.precision(15); const TimeControlPointMap& tcpm = getTimeControlPointMap(); for(TimeControlPointMap::const_iterator tcpmitr=tcpm.begin(); tcpmitr!=tcpm.end(); ++tcpmitr) { const ControlPoint& cp = tcpmitr->second; fout<<tcpmitr->first<<" "<<cp._position<<" "<<cp._rotation<<std::endl; } fout.precision(prec); } class AnimationPathCallbackVisitor : public NodeVisitor { public: AnimationPathCallbackVisitor(const AnimationPath::ControlPoint& cp, const osg::Vec3d& pivotPoint, bool useInverseMatrix): _cp(cp), _pivotPoint(pivotPoint), _useInverseMatrix(useInverseMatrix) {} virtual void apply(MatrixTransform& mt) { Matrix matrix; if (_useInverseMatrix) _cp.getInverse(matrix); else _cp.getMatrix(matrix); mt.setMatrix(osg::Matrix::translate(-_pivotPoint)*matrix); } virtual void apply(PositionAttitudeTransform& pat) { if (_useInverseMatrix) { Matrix matrix; _cp.getInverse(matrix); pat.setPosition(matrix.getTrans()); pat.setAttitude(_cp._rotation.inverse()); pat.setScale(osg::Vec3(1.0f/_cp._scale.x(),1.0f/_cp._scale.y(),1.0f/_cp._scale.z())); pat.setPivotPoint(_pivotPoint); } else { pat.setPosition(_cp._position); pat.setAttitude(_cp._rotation); pat.setScale(_cp._scale); pat.setPivotPoint(_pivotPoint); } } AnimationPath::ControlPoint _cp; osg::Vec3d _pivotPoint; bool _useInverseMatrix; }; void AnimationPathCallback::operator()(Node* node, NodeVisitor* nv) { if (_animationPath.valid() && nv->getVisitorType()==NodeVisitor::UPDATE_VISITOR && nv->getFrameStamp()) { double time = nv->getFrameStamp()->getReferenceTime(); _latestTime = time; if (!_pause) { // Only update _firstTime the first time, when its value is still DBL_MAX if (_firstTime==DBL_MAX) _firstTime = time; update(*node); } } // must call any nested node callbacks and continue subgraph traversal. NodeCallback::traverse(node,nv); } double AnimationPathCallback::getAnimationTime() const { return ((_latestTime-_firstTime)-_timeOffset)*_timeMultiplier; } void AnimationPathCallback::update(osg::Node& node) { AnimationPath::ControlPoint cp; if (_animationPath->getInterpolatedControlPoint(getAnimationTime(),cp)) { AnimationPathCallbackVisitor apcv(cp,_pivotPoint,_useInverseMatrix); node.accept(apcv); } } void AnimationPathCallback::reset() { #if 1 _firstTime = DBL_MAX; _pauseTime = DBL_MAX; #else _firstTime = _latestTime; _pauseTime = _latestTime; #endif } void AnimationPathCallback::setPause(bool pause) { if (_pause==pause) { return; } _pause = pause; if (_firstTime==DBL_MAX) return; if (_pause) { _pauseTime = _latestTime; } else { _firstTime += (_latestTime-_pauseTime); } } <|endoftext|>
<commit_before>#include <errno.h> #include <cassert> #include <vector> #include <string> #include <openssl/bio.h> #include <openssl/evp.h> #include <curl/curl.h> #include "opkele/util.h" #include "opkele/exception.h" namespace opkele { using namespace std; namespace util { /* * base64 */ string encode_base64(const void *data,size_t length) { BIO *b64 = 0, *bmem = 0; try { b64 = BIO_new(BIO_f_base64()); if(!b64) throw exception_openssl(OPKELE_CP_ "failed to BIO_new() base64 encoder"); BIO_set_flags(b64,BIO_FLAGS_BASE64_NO_NL); bmem = BIO_new(BIO_s_mem()); BIO_set_flags(b64,BIO_CLOSE); if(!bmem) throw exception_openssl(OPKELE_CP_ "failed to BIO_new() memory buffer"); BIO_push(b64,bmem); if(BIO_write(b64,data,length)!=length) throw exception_openssl(OPKELE_CP_ "failed to BIO_write()"); BIO_flush(b64); char *rvd; long rvl = BIO_get_mem_data(bmem,&rvd); string rv(rvd,rvl); BIO_free_all(b64); return rv; }catch(...) { if(b64) BIO_free_all(b64); throw; } } void decode_base64(const string& data,vector<unsigned char>& rv) { BIO *b64 = 0, *bmem = 0; rv.clear(); try { bmem = BIO_new_mem_buf((void*)data.data(),data.size()); if(!bmem) throw exception_openssl(OPKELE_CP_ "failed to BIO_new_mem_buf()"); b64 = BIO_new(BIO_f_base64()); if(!b64) throw exception_openssl(OPKELE_CP_ "failed to BIO_new() base64 decoder"); BIO_set_flags(b64,BIO_FLAGS_BASE64_NO_NL); BIO_push(b64,bmem); unsigned char tmp[512]; size_t rb = 0; while((rb=BIO_read(b64,tmp,sizeof(tmp)))>0) rv.insert(rv.end(),tmp,&tmp[rb]); BIO_free_all(b64); }catch(...) { if(b64) BIO_free_all(b64); throw; } } /* * big numerics */ BIGNUM *base64_to_bignum(const string& b64) { vector<unsigned char> bin; decode_base64(b64,bin); BIGNUM *rv = BN_bin2bn(&(bin.front()),bin.size(),0); if(!rv) throw failed_conversion(OPKELE_CP_ "failed to BN_bin2bn()"); return rv; } BIGNUM *dec_to_bignum(const string& dec) { BIGNUM *rv = 0; if(!BN_dec2bn(&rv,dec.c_str())) throw failed_conversion(OPKELE_CP_ "failed to BN_dec2bn()"); return rv; } string bignum_to_base64(const BIGNUM *bn) { vector<unsigned char> bin(BN_num_bytes(bn)+1); unsigned char *binptr = &(bin.front())+1; int l = BN_bn2bin(bn,binptr); if(l && (*binptr)&0x80){ (*(--binptr)) = 0; ++l; } return encode_base64(binptr,l); } /* * w3c times */ string time_to_w3c(time_t t) { struct tm tm_t; if(!gmtime_r(&t,&tm_t)) throw failed_conversion(OPKELE_CP_ "failed to BN_dec2bn()"); char rv[25]; if(!strftime(rv,sizeof(rv)-1,"%Y-%m-%dT%H:%M:%SZ",&tm_t)) throw failed_conversion(OPKELE_CP_ "failed to strftime()"); return rv; } time_t w3c_to_time(const string& w) { struct tm tm_t; memset(&tm_t,0,sizeof(tm_t)); if( sscanf( w.c_str(), "%04d-%02d-%02dT%02d:%02d:%02dZ", &tm_t.tm_year,&tm_t.tm_mon,&tm_t.tm_mday, &tm_t.tm_hour,&tm_t.tm_min,&tm_t.tm_sec ) != 6 ) throw failed_conversion(OPKELE_CP_ "failed to sscanf()"); tm_t.tm_mon--; tm_t.tm_year-=1900; time_t rv = mktime(&tm_t); if(rv==(time_t)-1) throw failed_conversion(OPKELE_CP_ "failed to mktime()"); return rv; } /* * */ string url_encode(const string& str) { char * t = curl_escape(str.c_str(),str.length()); if(!t) throw failed_conversion(OPKELE_CP_ "failed to curl_escape()"); string rv(t); curl_free(t); return rv; } string long_to_string(long l) { char rv[32]; int r=snprintf(rv,sizeof(rv),"%ld",l); if(r<0 || r>=sizeof(rv)) throw failed_conversion(OPKELE_CP_ "failed to snprintf()"); return rv; } long string_to_long(const string& s) { char *endptr = 0; long rv = strtol(s.c_str(),&endptr,10); if((!endptr) || endptr==s.c_str()) throw failed_conversion(OPKELE_CP_ "failed to strtol()"); return rv; } } } <commit_msg>keep compiler happy and check more error conditions<commit_after>#include <errno.h> #include <cassert> #include <vector> #include <string> #include <openssl/bio.h> #include <openssl/evp.h> #include <curl/curl.h> #include "opkele/util.h" #include "opkele/exception.h" namespace opkele { using namespace std; namespace util { /* * base64 */ string encode_base64(const void *data,size_t length) { BIO *b64 = 0, *bmem = 0; try { b64 = BIO_new(BIO_f_base64()); if(!b64) throw exception_openssl(OPKELE_CP_ "failed to BIO_new() base64 encoder"); BIO_set_flags(b64,BIO_FLAGS_BASE64_NO_NL); bmem = BIO_new(BIO_s_mem()); BIO_set_flags(b64,BIO_CLOSE); if(!bmem) throw exception_openssl(OPKELE_CP_ "failed to BIO_new() memory buffer"); BIO_push(b64,bmem); if(((size_t)BIO_write(b64,data,length))!=length) throw exception_openssl(OPKELE_CP_ "failed to BIO_write()"); if(BIO_flush(b64)!=1) throw exception_openssl(OPKELE_CP_ "failed to BIO_flush()"); char *rvd; long rvl = BIO_get_mem_data(bmem,&rvd); string rv(rvd,rvl); BIO_free_all(b64); return rv; }catch(...) { if(b64) BIO_free_all(b64); throw; } } void decode_base64(const string& data,vector<unsigned char>& rv) { BIO *b64 = 0, *bmem = 0; rv.clear(); try { bmem = BIO_new_mem_buf((void*)data.data(),data.size()); if(!bmem) throw exception_openssl(OPKELE_CP_ "failed to BIO_new_mem_buf()"); b64 = BIO_new(BIO_f_base64()); if(!b64) throw exception_openssl(OPKELE_CP_ "failed to BIO_new() base64 decoder"); BIO_set_flags(b64,BIO_FLAGS_BASE64_NO_NL); BIO_push(b64,bmem); unsigned char tmp[512]; size_t rb = 0; while((rb=BIO_read(b64,tmp,sizeof(tmp)))>0) rv.insert(rv.end(),tmp,&tmp[rb]); BIO_free_all(b64); }catch(...) { if(b64) BIO_free_all(b64); throw; } } /* * big numerics */ BIGNUM *base64_to_bignum(const string& b64) { vector<unsigned char> bin; decode_base64(b64,bin); BIGNUM *rv = BN_bin2bn(&(bin.front()),bin.size(),0); if(!rv) throw failed_conversion(OPKELE_CP_ "failed to BN_bin2bn()"); return rv; } BIGNUM *dec_to_bignum(const string& dec) { BIGNUM *rv = 0; if(!BN_dec2bn(&rv,dec.c_str())) throw failed_conversion(OPKELE_CP_ "failed to BN_dec2bn()"); return rv; } string bignum_to_base64(const BIGNUM *bn) { vector<unsigned char> bin(BN_num_bytes(bn)+1); unsigned char *binptr = &(bin.front())+1; int l = BN_bn2bin(bn,binptr); if(l && (*binptr)&0x80){ (*(--binptr)) = 0; ++l; } return encode_base64(binptr,l); } /* * w3c times */ string time_to_w3c(time_t t) { struct tm tm_t; if(!gmtime_r(&t,&tm_t)) throw failed_conversion(OPKELE_CP_ "failed to BN_dec2bn()"); char rv[25]; if(!strftime(rv,sizeof(rv)-1,"%Y-%m-%dT%H:%M:%SZ",&tm_t)) throw failed_conversion(OPKELE_CP_ "failed to strftime()"); return rv; } time_t w3c_to_time(const string& w) { struct tm tm_t; memset(&tm_t,0,sizeof(tm_t)); if( sscanf( w.c_str(), "%04d-%02d-%02dT%02d:%02d:%02dZ", &tm_t.tm_year,&tm_t.tm_mon,&tm_t.tm_mday, &tm_t.tm_hour,&tm_t.tm_min,&tm_t.tm_sec ) != 6 ) throw failed_conversion(OPKELE_CP_ "failed to sscanf()"); tm_t.tm_mon--; tm_t.tm_year-=1900; time_t rv = mktime(&tm_t); if(rv==(time_t)-1) throw failed_conversion(OPKELE_CP_ "failed to mktime()"); return rv; } /* * */ string url_encode(const string& str) { char * t = curl_escape(str.c_str(),str.length()); if(!t) throw failed_conversion(OPKELE_CP_ "failed to curl_escape()"); string rv(t); curl_free(t); return rv; } string long_to_string(long l) { char rv[32]; int r=snprintf(rv,sizeof(rv),"%ld",l); if(r<0 || r>=(int)sizeof(rv)) throw failed_conversion(OPKELE_CP_ "failed to snprintf()"); return rv; } long string_to_long(const string& s) { char *endptr = 0; long rv = strtol(s.c_str(),&endptr,10); if((!endptr) || endptr==s.c_str()) throw failed_conversion(OPKELE_CP_ "failed to strtol()"); return rv; } } } <|endoftext|>
<commit_before>/* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "loader-gif.h" #include <gif_lib.h> #include <cstdlib> #include <dali/integration-api/debug.h> #include <dali/integration-api/bitmap.h> namespace Dali { using Integration::Bitmap; using Dali::Integration::PixelBuffer; namespace TizenPlatform { namespace { // simple class to enforce clean-up of GIF structures struct AutoCleanupGif { AutoCleanupGif(GifFileType*& _gifInfo) : gifInfo(_gifInfo) { } ~AutoCleanupGif() { if(NULL != gifInfo) { // clean up GIF resources int errorCode = 0; //D_GIF_SUCCEEDED is 0 DGifCloseFile(gifInfo, &errorCode); if( errorCode ) { DALI_LOG_ERROR( "GIF Loader: DGifCloseFile Error. Code: %d\n", errorCode); } } } GifFileType*& gifInfo; }; // Simple class to enforce clean-up of PixelBuffer struct AutoDeleteBuffer { AutoDeleteBuffer( PixelBuffer* _buffer ) : buffer( _buffer ) { } ~AutoDeleteBuffer() { delete []buffer; } PixelBuffer* buffer; }; // Used in the GIF interlace algorithm to determine the starting byte and the increment required // for each pass. struct InterlacePair { unsigned int startingByte; unsigned int incrementalByte; }; // Used in the GIF interlace algorithm to determine the order and which location to read data from // the file. const InterlacePair INTERLACE_PAIR_TABLE [] = { { 0, 8 }, // Starting at 0, read every 8 bytes. { 4, 8 }, // Starting at 4, read every 8 bytes. { 2, 4 }, // Starting at 2, read every 4 bytes. { 1, 2 }, // Starting at 1, read every 2 bytes. }; const unsigned int INTERLACE_PAIR_TABLE_SIZE( sizeof( INTERLACE_PAIR_TABLE ) / sizeof( InterlacePair ) ); /// Function used by Gif_Lib to read from the image file. int ReadDataFromGif(GifFileType *gifInfo, GifByteType *data, int length) { FILE *fp = reinterpret_cast<FILE*>(gifInfo->UserData); return fread( data, sizeof( GifByteType ), length, fp); } /// Loads the GIF Header. bool LoadGifHeader(FILE *fp, unsigned int &width, unsigned int &height, GifFileType** gifInfo) { int errorCode = 0; //D_GIF_SUCCEEDED is 0 *gifInfo = DGifOpen(reinterpret_cast<void*>(fp), ReadDataFromGif, &errorCode); if ( !(*gifInfo) || errorCode ) { DALI_LOG_ERROR( "GIF Loader: DGifOpen Error. Code: %d\n", errorCode); return false; } width = (*gifInfo)->SWidth; height = (*gifInfo)->SHeight; // No proper size in GIF. if ( width <= 0 || height <= 0 ) { return false; } return true; } /// Decode the GIF image. bool DecodeImage( GifFileType* gifInfo, PixelBuffer* decodedData, const unsigned int width, const unsigned int height, const unsigned int bytesPerRow ) { if ( gifInfo->Image.Interlace ) { // If the image is interlaced, then use the GIF interlace algorithm to read the file appropriately. const InterlacePair* interlacePairPtr( INTERLACE_PAIR_TABLE ); for ( unsigned int interlacePair = 0; interlacePair < INTERLACE_PAIR_TABLE_SIZE; ++interlacePair, ++interlacePairPtr ) { for( unsigned int currentByte = interlacePairPtr->startingByte; currentByte < height; currentByte += interlacePairPtr->incrementalByte ) { PixelBuffer* row = decodedData + currentByte * bytesPerRow; if ( DGifGetLine( gifInfo, row, width ) == GIF_ERROR ) { DALI_LOG_ERROR( "GIF Loader: Error reading Interlaced GIF\n" ); return false; } } } } else { // Non-interlace does not require any erratic reading / jumping. PixelBuffer* decodedDataPtr( decodedData ); for ( unsigned int row = 0; row < height; ++row ) { if ( DGifGetLine( gifInfo, decodedDataPtr, width ) == GIF_ERROR) { DALI_LOG_ERROR( "GIF Loader: Error reading non-interlaced GIF\n" ); return false; } decodedDataPtr += bytesPerRow; } } return true; } // Retrieves the colors used in the GIF image. GifColorType* GetImageColors( SavedImage* image, GifFileType* gifInfo ) { GifColorType* color( NULL ); if ( image->ImageDesc.ColorMap ) { color = image->ImageDesc.ColorMap->Colors; } else { // if there is no color map for this image use the default one color = gifInfo->SColorMap->Colors; } return color; } /// Called when we want to handle IMAGE_DESC_RECORD_TYPE bool HandleImageDescriptionRecordType( Bitmap& bitmap, GifFileType* gifInfo, unsigned int width, unsigned int height, bool& finished ) { if ( DGifGetImageDesc( gifInfo ) == GIF_ERROR ) { DALI_LOG_ERROR( "GIF Loader: Error getting Image Description\n" ); return false; } // Ensure there is at least 1 image in the GIF. if ( gifInfo->ImageCount < 1 ) { DALI_LOG_ERROR( "GIF Loader: No Images\n" ); return false; } SavedImage* image( &gifInfo->SavedImages[ gifInfo->ImageCount - 1 ] ); const GifImageDesc& desc( image->ImageDesc ); // Create a buffer to store the decoded data. PixelBuffer* decodedData( new PixelBuffer[ width * height * sizeof( GifPixelType ) ] ); AutoDeleteBuffer autoDeleteBuffer( decodedData ); const unsigned int bytesPerRow( width * sizeof( GifPixelType ) ); const unsigned int actualWidth( desc.Width ); const unsigned int actualHeight( desc.Height ); // Decode the GIF Image if ( !DecodeImage( gifInfo, decodedData, actualWidth, actualHeight, bytesPerRow ) ) { return false; } // Get the colormap for the GIF GifColorType* color( GetImageColors( image, gifInfo ) ); // If it's an animated GIF, we still only read the first image // Create and populate pixel buffer. Pixel::Format pixelFormat( Pixel::RGB888 ); PixelBuffer *pixels = bitmap.GetPackedPixelsProfile()->ReserveBuffer( pixelFormat, actualWidth, actualHeight ); for (unsigned int row = 0; row < actualHeight; ++row) { for (unsigned int column = 0; column < actualWidth; ++column) { unsigned char index = decodedData[row * width + column]; pixels[0] = color[index].Red; pixels[1] = color[index].Green; pixels[2] = color[index].Blue; pixels += 3; } } finished = true; return true; } /// Called when we want to handle EXTENSION_RECORD_TYPE bool HandleExtensionRecordType( GifFileType* gifInfo ) { SavedImage image; image.ExtensionBlocks = NULL; image.ExtensionBlockCount = 0; GifByteType *extensionByte( NULL ); // Not really interested in the extensions so just skip them unless there is an error. for ( int extRetCode = DGifGetExtension( gifInfo, &image.ExtensionBlocks->Function, &extensionByte ); extensionByte != NULL; extRetCode = DGifGetExtensionNext( gifInfo, &extensionByte ) ) { if ( extRetCode == GIF_ERROR ) { DALI_LOG_ERROR( "GIF Loader: Error reading GIF Extension record.\n" ); return false; } } return true; } } // unnamed namespace bool LoadGifHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height ) { GifFileType* gifInfo = NULL; AutoCleanupGif autoCleanupGif(gifInfo); FILE* const fp = input.file; return LoadGifHeader(fp, width, height, &gifInfo); } bool LoadBitmapFromGif( const ResourceLoadingClient& client, const ImageLoader::Input& input, Integration::Bitmap& bitmap ) { FILE* const fp = input.file; // Load the GIF Header file. GifFileType* gifInfo( NULL ); unsigned int width( 0 ); unsigned int height( 0 ); if ( !LoadGifHeader( fp, width, height, &gifInfo ) ) { return false; } AutoCleanupGif autoGif( gifInfo ); // Check each record in the GIF file. bool finished( false ); GifRecordType recordType( UNDEFINED_RECORD_TYPE ); for ( int returnCode = DGifGetRecordType( gifInfo, &recordType ); !finished && recordType != TERMINATE_RECORD_TYPE; returnCode = DGifGetRecordType( gifInfo, &recordType ) ) { if ( returnCode == GIF_ERROR ) { DALI_LOG_ERROR( "GIF Loader: Error getting Record Type\n" ); return false; } if( IMAGE_DESC_RECORD_TYPE == recordType ) { if ( !HandleImageDescriptionRecordType( bitmap, gifInfo, width, height, finished ) ) { return false; } } else if ( EXTENSION_RECORD_TYPE == recordType ) { if ( !HandleExtensionRecordType( gifInfo )) { return false; } } } return true; } } // namespace TizenPlatform } // namespace Dali <commit_msg>Revert "[3.0] giflib upgrade"<commit_after>/* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "loader-gif.h" #include <gif_lib.h> #include <cstdlib> #include <dali/integration-api/debug.h> #include <dali/integration-api/bitmap.h> namespace Dali { using Integration::Bitmap; using Dali::Integration::PixelBuffer; namespace TizenPlatform { namespace { // simple class to enforce clean-up of GIF structures struct AutoCleanupGif { AutoCleanupGif(GifFileType*& _gifInfo) : gifInfo(_gifInfo) { } ~AutoCleanupGif() { if(NULL != gifInfo) { // clean up GIF resources DGifCloseFile(gifInfo); } } GifFileType*& gifInfo; }; // Simple class to enforce clean-up of PixelBuffer struct AutoDeleteBuffer { AutoDeleteBuffer( PixelBuffer* _buffer ) : buffer( _buffer ) { } ~AutoDeleteBuffer() { delete []buffer; } PixelBuffer* buffer; }; // Used in the GIF interlace algorithm to determine the starting byte and the increment required // for each pass. struct InterlacePair { unsigned int startingByte; unsigned int incrementalByte; }; // Used in the GIF interlace algorithm to determine the order and which location to read data from // the file. const InterlacePair INTERLACE_PAIR_TABLE [] = { { 0, 8 }, // Starting at 0, read every 8 bytes. { 4, 8 }, // Starting at 4, read every 8 bytes. { 2, 4 }, // Starting at 2, read every 4 bytes. { 1, 2 }, // Starting at 1, read every 2 bytes. }; const unsigned int INTERLACE_PAIR_TABLE_SIZE( sizeof( INTERLACE_PAIR_TABLE ) / sizeof( InterlacePair ) ); /// Function used by Gif_Lib to read from the image file. int ReadDataFromGif(GifFileType *gifInfo, GifByteType *data, int length) { FILE *fp = reinterpret_cast<FILE*>(gifInfo->UserData); return fread( data, sizeof( GifByteType ), length, fp); } /// Loads the GIF Header. bool LoadGifHeader(FILE *fp, unsigned int &width, unsigned int &height, GifFileType** gifInfo) { *gifInfo = DGifOpen(reinterpret_cast<void*>(fp), ReadDataFromGif); if ( !(*gifInfo) ) { return false; } width = (*gifInfo)->SWidth; height = (*gifInfo)->SHeight; // No proper size in GIF. if ( width <= 0 || height <= 0 ) { return false; } return true; } /// Decode the GIF image. bool DecodeImage( GifFileType* gifInfo, PixelBuffer* decodedData, const unsigned int width, const unsigned int height, const unsigned int bytesPerRow ) { if ( gifInfo->Image.Interlace ) { // If the image is interlaced, then use the GIF interlace algorithm to read the file appropriately. const InterlacePair* interlacePairPtr( INTERLACE_PAIR_TABLE ); for ( unsigned int interlacePair = 0; interlacePair < INTERLACE_PAIR_TABLE_SIZE; ++interlacePair, ++interlacePairPtr ) { for( unsigned int currentByte = interlacePairPtr->startingByte; currentByte < height; currentByte += interlacePairPtr->incrementalByte ) { PixelBuffer* row = decodedData + currentByte * bytesPerRow; if ( DGifGetLine( gifInfo, row, width ) == GIF_ERROR ) { DALI_LOG_ERROR( "GIF Loader: Error reading Interlaced GIF\n" ); return false; } } } } else { // Non-interlace does not require any erratic reading / jumping. PixelBuffer* decodedDataPtr( decodedData ); for ( unsigned int row = 0; row < height; ++row ) { if ( DGifGetLine( gifInfo, decodedDataPtr, width ) == GIF_ERROR) { DALI_LOG_ERROR( "GIF Loader: Error reading non-interlaced GIF\n" ); return false; } decodedDataPtr += bytesPerRow; } } return true; } // Retrieves the colors used in the GIF image. GifColorType* GetImageColors( SavedImage* image, GifFileType* gifInfo ) { GifColorType* color( NULL ); if ( image->ImageDesc.ColorMap ) { color = image->ImageDesc.ColorMap->Colors; } else { // if there is no color map for this image use the default one color = gifInfo->SColorMap->Colors; } return color; } /// Called when we want to handle IMAGE_DESC_RECORD_TYPE bool HandleImageDescriptionRecordType( Bitmap& bitmap, GifFileType* gifInfo, unsigned int width, unsigned int height, bool& finished ) { if ( DGifGetImageDesc( gifInfo ) == GIF_ERROR ) { DALI_LOG_ERROR( "GIF Loader: Error getting Image Description\n" ); return false; } // Ensure there is at least 1 image in the GIF. if ( gifInfo->ImageCount < 1 ) { DALI_LOG_ERROR( "GIF Loader: No Images\n" ); return false; } SavedImage* image( &gifInfo->SavedImages[ gifInfo->ImageCount - 1 ] ); const GifImageDesc& desc( image->ImageDesc ); // Create a buffer to store the decoded data. PixelBuffer* decodedData( new PixelBuffer[ width * height * sizeof( GifPixelType ) ] ); AutoDeleteBuffer autoDeleteBuffer( decodedData ); const unsigned int bytesPerRow( width * sizeof( GifPixelType ) ); const unsigned int actualWidth( desc.Width ); const unsigned int actualHeight( desc.Height ); // Decode the GIF Image if ( !DecodeImage( gifInfo, decodedData, actualWidth, actualHeight, bytesPerRow ) ) { return false; } // Get the colormap for the GIF GifColorType* color( GetImageColors( image, gifInfo ) ); // If it's an animated GIF, we still only read the first image // Create and populate pixel buffer. Pixel::Format pixelFormat( Pixel::RGB888 ); PixelBuffer *pixels = bitmap.GetPackedPixelsProfile()->ReserveBuffer( pixelFormat, actualWidth, actualHeight ); for (unsigned int row = 0; row < actualHeight; ++row) { for (unsigned int column = 0; column < actualWidth; ++column) { unsigned char index = decodedData[row * width + column]; pixels[0] = color[index].Red; pixels[1] = color[index].Green; pixels[2] = color[index].Blue; pixels += 3; } } finished = true; return true; } /// Called when we want to handle EXTENSION_RECORD_TYPE bool HandleExtensionRecordType( GifFileType* gifInfo ) { SavedImage image; image.ExtensionBlocks = NULL; image.ExtensionBlockCount = 0; GifByteType *extensionByte( NULL ); // Not really interested in the extensions so just skip them unless there is an error. for ( int extRetCode = DGifGetExtension( gifInfo, &image.Function, &extensionByte ); extensionByte != NULL; extRetCode = DGifGetExtensionNext( gifInfo, &extensionByte ) ) { if ( extRetCode == GIF_ERROR ) { DALI_LOG_ERROR( "GIF Loader: Error reading GIF Extension record.\n" ); return false; } } return true; } } // unnamed namespace bool LoadGifHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height ) { GifFileType* gifInfo = NULL; AutoCleanupGif autoCleanupGif(gifInfo); FILE* const fp = input.file; return LoadGifHeader(fp, width, height, &gifInfo); } bool LoadBitmapFromGif( const ResourceLoadingClient& client, const ImageLoader::Input& input, Integration::Bitmap& bitmap ) { FILE* const fp = input.file; // Load the GIF Header file. GifFileType* gifInfo( NULL ); unsigned int width( 0 ); unsigned int height( 0 ); if ( !LoadGifHeader( fp, width, height, &gifInfo ) ) { return false; } AutoCleanupGif autoGif( gifInfo ); // Check each record in the GIF file. bool finished( false ); GifRecordType recordType( UNDEFINED_RECORD_TYPE ); for ( int returnCode = DGifGetRecordType( gifInfo, &recordType ); !finished && recordType != TERMINATE_RECORD_TYPE; returnCode = DGifGetRecordType( gifInfo, &recordType ) ) { if ( returnCode == GIF_ERROR ) { DALI_LOG_ERROR( "GIF Loader: Error getting Record Type\n" ); return false; } if( IMAGE_DESC_RECORD_TYPE == recordType ) { if ( !HandleImageDescriptionRecordType( bitmap, gifInfo, width, height, finished ) ) { return false; } } else if ( EXTENSION_RECORD_TYPE == recordType ) { if ( !HandleExtensionRecordType( gifInfo )) { return false; } } } return true; } } // namespace TizenPlatform } // namespace Dali <|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. 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 "paddle/memory/memory.h" #include "paddle/platform/place.h" #include "gtest/gtest.h" TEST(BuddyAllocator, CPUAllocation) { void *p = nullptr; EXPECT_EQ(p, nullptr); paddle::platform::CPUPlace cpu; p = paddle::memory::Alloc(cpu, 4096); EXPECT_NE(p, nullptr); paddle::memory::Free(cpu, p); } TEST(BuddyAllocator, CPUMultAlloc) { paddle::platform::CPUPlace cpu; std::vector<void *> ps; ps.reserve(8); for (auto size : {256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304}) { ps.emplace_back(paddle::memory::Alloc(cpu, size)); } for (auto p : ps) { paddle::memory::Free(cpu, p); } } #ifndef PADDLE_ONLY_CPU TEST(BuddyAllocator, GPUAllocation) { void *p = nullptr; EXPECT_EQ(p, nullptr); paddle::platform::GPUPlace gpu(0); p = paddle::memory::Alloc(gpu, 4096); EXPECT_NE(p, nullptr); paddle::memory::Free(gpu, p); } #endif // PADDLE_ONLY_CPU <commit_msg>Add memory alignment test<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. 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 "paddle/memory/memory.h" #include "gtest/gtest.h" #include "paddle/platform/place.h" template <typename T> inline bool is_aligned(T *p, size_t n = alignof(T)) { return 0 == (reinterpret_cast<uintptr_t>(p) % n); } TEST(BuddyAllocator, CPUAllocation) { void *p = nullptr; EXPECT_EQ(p, nullptr); paddle::platform::CPUPlace cpu; p = paddle::memory::Alloc(cpu, 4096); EXPECT_NE(p, nullptr); paddle::memory::Free(cpu, p); } TEST(BuddyAllocator, CPUMultAlloc) { paddle::platform::CPUPlace cpu; std::vector<void *> ps; ps.reserve(8); for (auto size : {128, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304}) { ps.emplace_back(paddle::memory::Alloc(cpu, size)); } for (auto p : ps) { EXPECT_EQ(is_aligned(p, 32), true); paddle::memory::Free(cpu, p); } } #ifndef PADDLE_ONLY_CPU TEST(BuddyAllocator, GPUAllocation) { void *p = nullptr; EXPECT_EQ(p, nullptr); paddle::platform::GPUPlace gpu(0); p = paddle::memory::Alloc(gpu, 4096); EXPECT_NE(p, nullptr); paddle::memory::Free(gpu, p); } TEST(BuddyAllocator, GPUMultAlloc) { paddle::platform::GPUPlace gpu; std::vector<void *> ps; ps.reserve(8); for (auto size : {128, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304}) { ps.emplace_back(paddle::memory::Alloc(gpu, size)); } for (auto p : ps) { EXPECT_EQ(is_aligned(p, 32), true); paddle::memory::Free(gpu, p); } } #endif // PADDLE_ONLY_CPU <|endoftext|>
<commit_before>#include "shape/compound.h" #define rb_array_p(x) RB_TYPE_P(x, T_ARRAY) VALUE sr_cCompound; SR_SHAPE_GET(Compound, compound) SR_SHAPE_CHECK(Compound, compound) bool siren_compound_install() { SR_SHAPE_INIT(Compound) rb_define_method(sr_cCompound, "initialize", RUBY_METHOD_FUNC(siren_compound_init), -1); rb_define_method(sr_cCompound, "push", RUBY_METHOD_FUNC(siren_compound_push), -1); rb_define_method(sr_cCompound, "<<", RUBY_METHOD_FUNC(siren_compound_push), -1); rb_define_method(sr_cCompound, "delete", RUBY_METHOD_FUNC(siren_compound_delete), -1); return true; } VALUE siren_compound_init(int argc, VALUE* argv, VALUE self) { VALUE* a; VALUE len; rb_scan_args(argc, argv, "*", &a, &len); TopoDS_Compound comp; BRep_Builder B; B.MakeCompound(comp); for (int i = 0; i < len; i++) { VALUE arg = *(a + i); if (rb_array_p(arg)) { VALUE subary = rb_funcall(arg, rb_intern("flatten"), 0); for (int j = 0; j < RARRAY_LEN(subary); j++) { TopoDS_Shape* shape = siren_shape_get(RARRAY_AREF(subary, j)); B.Add(comp, *shape); } } else { TopoDS_Shape* shape = siren_shape_get(arg); B.Add(comp, *shape); } } auto p = siren_shape_get(self); *p = comp; return self; } VALUE siren_compound_push(int argc, VALUE* argv, VALUE self) { VALUE* a; VALUE len; rb_scan_args(argc, argv, "*", &a, &len); TopoDS_Compound comp = siren_compound_get(self); BRep_Builder B; for (int i = 0; i < len; i++) { VALUE arg = *(a + i); if (rb_array_p(arg)) { VALUE subary = rb_funcall(arg, rb_intern("flatten"), 0); for (int j = 0; j < RARRAY_LEN(subary); j++) { TopoDS_Shape* shape = siren_shape_get(RARRAY_AREF(subary, j)); B.Add(comp, *shape); } } else { TopoDS_Shape* shape = siren_shape_get(arg); B.Add(comp, *shape); } } return self; } VALUE siren_compound_delete(int argc, VALUE* argv, VALUE self) { VALUE* a; VALUE len; rb_scan_args(argc, argv, "*", &a, &len); TopoDS_Compound comp = siren_compound_get(self); BRep_Builder B; for (int i = 0; i < len; i++) { VALUE arg = *(a + i); if (rb_array_p(arg)) { VALUE subary = rb_funcall(arg, rb_intern("flatten"), 0); for (int j = 0; j < RARRAY_LEN(subary); j++) { TopoDS_Shape* shape = siren_shape_get(RARRAY_AREF(subary, j)); B.Remove(comp, *shape); } } else { TopoDS_Shape* shape = siren_shape_get(arg); B.Remove(comp, *shape); } } return self; } <commit_msg>Update Siren::Compound#initialize method.<commit_after>#include "shape/compound.h" #define rb_array_p(x) RB_TYPE_P(x, T_ARRAY) VALUE sr_cCompound; SR_SHAPE_GET(Compound, compound) SR_SHAPE_CHECK(Compound, compound) bool siren_compound_install() { SR_SHAPE_INIT(Compound) rb_define_method(sr_cCompound, "initialize", RUBY_METHOD_FUNC(siren_compound_init), -1); rb_define_method(sr_cCompound, "push", RUBY_METHOD_FUNC(siren_compound_push), -1); rb_define_method(sr_cCompound, "<<", RUBY_METHOD_FUNC(siren_compound_push), -1); rb_define_method(sr_cCompound, "delete", RUBY_METHOD_FUNC(siren_compound_delete), -1); return true; } VALUE siren_compound_init(int argc, VALUE* argv, VALUE self) { VALUE a; rb_scan_args(argc, argv, "*", &a); TopoDS_Compound comp; BRep_Builder B; B.MakeCompound(comp); rb_funcall(a, rb_intern("flatten!"), 0); for (int i = 0; i < RARRAY_LEN(a); i++) { VALUE item = RARRAY_AREF(a, i); TopoDS_Shape* shape = siren_shape_get(item); B.Add(comp, *shape); } auto p = siren_shape_get(self); *p = comp; return self; } VALUE siren_compound_push(int argc, VALUE* argv, VALUE self) { VALUE* a; VALUE len; rb_scan_args(argc, argv, "*", &a, &len); TopoDS_Compound comp = siren_compound_get(self); BRep_Builder B; for (int i = 0; i < len; i++) { VALUE arg = *(a + i); if (rb_array_p(arg)) { VALUE subary = rb_funcall(arg, rb_intern("flatten"), 0); for (int j = 0; j < RARRAY_LEN(subary); j++) { TopoDS_Shape* shape = siren_shape_get(RARRAY_AREF(subary, j)); B.Add(comp, *shape); } } else { TopoDS_Shape* shape = siren_shape_get(arg); B.Add(comp, *shape); } } return self; } VALUE siren_compound_delete(int argc, VALUE* argv, VALUE self) { VALUE* a; VALUE len; rb_scan_args(argc, argv, "*", &a, &len); TopoDS_Compound comp = siren_compound_get(self); BRep_Builder B; for (int i = 0; i < len; i++) { VALUE arg = *(a + i); if (rb_array_p(arg)) { VALUE subary = rb_funcall(arg, rb_intern("flatten"), 0); for (int j = 0; j < RARRAY_LEN(subary); j++) { TopoDS_Shape* shape = siren_shape_get(RARRAY_AREF(subary, j)); B.Remove(comp, *shape); } } else { TopoDS_Shape* shape = siren_shape_get(arg); B.Remove(comp, *shape); } } return self; } <|endoftext|>
<commit_before>//#define CONSOLE_DEBUG #include <iostream> #include <thread> #include <Windows.h> #include "Core/Halite.h" GLFWwindow * window; void handleMouse(GLFWwindow * w, int button, int action, int mods); void handleCursor(GLFWwindow * w, double x, double y); void handleKeys(GLFWwindow * w, int button, int scancode, int action, int mods); void handleChars(GLFWwindow * w, unsigned int code); void handleDrop(GLFWwindow * w, int count, const char ** paths); void handleErrors(int error, const char * description); void handleResize(GLFWwindow * w, int width, int height); void renderLaunch(); Halite * my_game; //Is a pointer to avoid problems with assignment, dynamic memory, and default constructors. bool isPaused = false, leftPressed = false, rightPressed = false, upPressed = false, downPressed = false, shiftPressed = false, newGame = false, isLaunch = true, mousePressed = false; float maxFps = 8, turnNumber = 0, graphZoom = 1.0, maxZoom, mouseX, mouseY; short numTurns; std::string filename; std::fstream debug; FTPixmapFont * t; #ifdef CONSOLE_DEBUG int main() #else INT WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR lpCmdLine, INT nCmdShow) #endif { //Open debug: std::string debugfilename = "logs/"; time_t rawtime; tm timeinfo; time(&rawtime); localtime_s(&timeinfo, &rawtime); const int STRING_LEN = 30; char timeC[STRING_LEN]; asctime_s(timeC, STRING_LEN, &timeinfo); std::string timeString(timeC); timeString.pop_back(); std::replace_if(timeString.begin(), timeString.end(), [](char c) -> bool { return c == ' '; }, '_'); std::replace_if(timeString.begin(), timeString.end(), [](char c) -> bool { return c == ':'; }, '-'); debugfilename += timeString.substr(4); debugfilename += ".log"; debug.open(debugfilename, std::ios_base::out); if(!debug.is_open()) //If file couldn't be opened. { debug.open("DEBUG.log", std::ios_base::out); debug << "I couldn't find the folder \"logs\" and consequently can't create multiple logs. Please create that folder for me in the future."; debug.flush(); } // start GL context and O/S window using the GLFW helper library if(!glfwInit()) { debug << "Could not start GLFW3\n"; return EXIT_FAILURE; } GLFWmonitor* primary = glfwGetPrimaryMonitor(); const GLFWvidmode * mode = glfwGetVideoMode(primary); glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate); window = glfwCreateWindow(mode->width * 2 / 3, mode->height * 2 / 3, "Halite", NULL, NULL); if(!window) { debug << "Could not open window with GLFW3\n"; glfwTerminate(); return EXIT_FAILURE; } glfwMakeContextCurrent(window); glewExperimental = GL_TRUE; if(glewInit() != GLEW_OK) return EXIT_FAILURE; debug << (const char *)glGetString(GL_VERSION); util::initShaderHandler(&debug); t = new FTPixmapFont("fonts/FreeSans.ttf"); t->FaceSize(48); //Set handlers: //Set leopard handler. glfwSetKeyCallback(window, handleKeys); //Set character handler. glfwSetCharCallback(window, handleChars); //Set mouse handler glfwSetMouseButtonCallback(window, handleMouse); //Set cursor handler. glfwSetCursorPosCallback(window, handleCursor); //Set error callback handler glfwSetErrorCallback(handleErrors); //Set file drop function glfwSetDropCallback(window, handleDrop); //Set window resize handler glfwSetWindowSizeCallback(window, handleResize); my_game = new Halite(); while(isLaunch && !glfwWindowShouldClose(window)) renderLaunch(); clock_t c = clock(); while(!glfwWindowShouldClose(window)) { //Limit render rate: float delta = float(clock() - c) / CLOCKS_PER_SEC; c = clock(); short turnNumberS = turnNumber; my_game->render(window, turnNumberS, graphZoom, mouseX, mouseY, mousePressed); if(abs(turnNumber - float(turnNumberS) > 1)) turnNumber = turnNumberS; //Means it's gone past the right edge //Poll events glfwPollEvents(); if(upPressed && maxFps <= 120) maxFps += maxFps * delta; else if(downPressed && maxFps != 4) maxFps -= maxFps * delta; if(leftPressed) { if(shiftPressed) turnNumber -= 5 * maxFps * delta; else turnNumber -= maxFps * delta; } else if(rightPressed) { if(shiftPressed) turnNumber += 5 * maxFps * delta; else turnNumber += maxFps * delta; } else if(!isPaused) turnNumber += maxFps * delta; if(turnNumber < 0) turnNumber = 0; } return EXIT_SUCCESS; } void handleMouse(GLFWwindow * w, int button, int action, int mods) { if(button == GLFW_MOUSE_BUTTON_1) { mousePressed = action == GLFW_PRESS; } } void handleCursor(GLFWwindow * w, double x, double y) { int sx, sy; glfwGetWindowSize(window, &sx, &sy); mouseX = (float(2 * x) / sx) - 1.0; mouseY = (float(-2 * y) / sy) + 1.0; } void handleKeys(GLFWwindow * w, int key, int scancode, int action, int mods) { if(key == GLFW_KEY_LEFT && action == GLFW_PRESS) { leftPressed = true; isPaused = true; } else if(key == GLFW_KEY_RIGHT && action == GLFW_PRESS) { rightPressed = true; isPaused = true; } else if(key == GLFW_KEY_LEFT && action == GLFW_RELEASE) { leftPressed = false; } else if(key == GLFW_KEY_RIGHT && action == GLFW_RELEASE) { rightPressed = false; } else if(key == GLFW_KEY_UP && action == GLFW_PRESS) { upPressed = true; } else if(key == GLFW_KEY_DOWN && action == GLFW_PRESS) { downPressed = true; } else if(key == GLFW_KEY_UP && action == GLFW_RELEASE) { upPressed = false; } else if(key == GLFW_KEY_DOWN && action == GLFW_RELEASE) { downPressed = false; } else if((key == GLFW_KEY_LEFT_SHIFT || key == GLFW_KEY_RIGHT_SHIFT) && action == GLFW_PRESS) { shiftPressed = true; } else if((key == GLFW_KEY_LEFT_SHIFT || key == GLFW_KEY_RIGHT_SHIFT) && action == GLFW_RELEASE) { shiftPressed = false; } else if(key == GLFW_KEY_ESCAPE) { exit(0); } } void handleChars(GLFWwindow * w, unsigned int code) { if(code == ' ') isPaused = !isPaused; else if(code == '+') { graphZoom *= 1.5; if(graphZoom > maxZoom) graphZoom = maxZoom; } else if(code == '-') { graphZoom /= 1.5; if(graphZoom < 1) graphZoom = 1; } else if(code == '>' || code == '.') { turnNumber++; isPaused = true; } else if(code == '<' || code == ',') { turnNumber--; isPaused = true; } else if(code == 'Z' || code == 'z') { turnNumber = 0; } else if(code == 'X' || code == 'x') { turnNumber = numTurns - 1; } } void handleDrop(GLFWwindow * w, int count, const char ** paths) { unsigned short wi, he; try { numTurns = my_game->input(w, paths[0], wi, he); } catch(std::runtime_error e) { debug << e.what(); #ifdef CONSOLE_DEBUG std::cout << e.what(); #endif return; } maxFps = 8; const int MIN_POINTS_VISIBLE = 3; //Set new max_zoom. We allow zooming until only MIN_POINTS_VISIBLE points are visible. maxZoom = numTurns / float(MIN_POINTS_VISIBLE); isLaunch = false; isPaused = false; turnNumber = 0; } void handleErrors(int error, const char * description) { debug << description; } void handleResize(GLFWwindow * w, int width, int height) { glViewport(0, 0, width, height); } void renderLaunch() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); util::renderText(t, window, -.85, 0.0, 36, "Drop a replay on-screen to watch it!"); glfwSwapBuffers(window); glfwPollEvents(); }<commit_msg>See prev<commit_after><|endoftext|>
<commit_before>//#include "vive_sensors_pipeline.h" //#include "settings.h" #include "application.h" #include "pheatherstation.h" #include "cactus_io_BME280_I2C.h" #include <Wire.h> #include <iostream> #include <string> #include <stdio.h> class println; const int LED_FLASH = D7; // Instead of writing D7 over and over again, we'll write led2. This one is the little blue LED on your board. On the Photon it is next to D7, and on the Core it is next to the USB jack. int THERMISTOR = A3; // 10k thermistor int ANEMOMETER = D3; int WINDVANE = A0; int RAINGAUGE = WKP; double VCC = 3.33; // VCC voltage source int ADC_MAX = 4096; SYSTEM_MODE(MANUAL); PheatherStation gStation(VCC); BME280_I2C gBMESensor; bool bFoundSensor; uint8_t chipID; void anemometer_interrupt(); void raingauge_interrupt(); void debug_message(const string& msg) { Serial.println(msg.c_str()); Serial1.println(msg.c_str()); } void setup() { chipID = 0; //WiFi.connect(); //waitUntil(WiFi.ready); pinMode(LED_FLASH, OUTPUT); pinMode(THERMISTOR, INPUT); pinMode(WINDVANE, INPUT); pinMode(ANEMOMETER, INPUT); attachInterrupt(ANEMOMETER, anemometer_interrupt, RISING); pinMode(RAINGAUGE, INPUT); attachInterrupt(RAINGAUGE, raingauge_interrupt, RISING); Serial.begin(9600); Serial1.begin(9600); gStation.set_logger([=](const string& msg) { debug_message(msg); }); bFoundSensor = gBMESensor.begin(chipID); } void loop() { digitalWrite(LED_FLASH, HIGH); // Turn ON the LED delay(1000); // Wait for 1000mS = 1 second digitalWrite(LED_FLASH, LOW); // Turn OFF the LED delay(1000); // Wait for 1 second if (bFoundSensor) { debug_message("found BME280"); } else { debug_message("Could not find BME280"); char buffer[8]; sprintf(buffer, "%u", chipID); debug_message(buffer); } int digValue = analogRead(THERMISTOR); gStation.set_thermistor_voltage( digValue/(double)ADC_MAX * VCC ) ; char buffer[16]; //sprintf(buffer, "%f", gStation.get_temperature()); //string msg = "ambient temperature: "; //msg += buffer; //debug_message(msg); gBMESensor.readSensor(); float c_i2c = gBMESensor.getTemperature_C(); float pres_mb = gBMESensor.getPressure_MB(); float humidity = gBMESensor.getHumidity(); memset(buffer, '\0', 16); sprintf(buffer, "%f", c_i2c); string msg = "i2c temp: "; msg += buffer; debug_message(msg); /* memset(buffer, '\0', 16); sprintf(buffer, "%f", pres_mb); msg = " pressure mb: "; msg += buffer; debug_message(msg); memset(buffer, '\0', 16); sprintf(buffer, "%f", humidity); msg = " humidity: "; msg += buffer; debug_message(msg); */ digValue = analogRead(WINDVANE); } void anemometer_interrupt() { debug_message("anemometer revolution\n"); } void raingauge_interrupt() { debug_message("rain gauage trigger\n"); }<commit_msg>BME280 sensor working<commit_after>//#include "vive_sensors_pipeline.h" //#include "settings.h" #include "application.h" #include "pheatherstation.h" #include "cactus_io_BME280_I2C.h" #include <Wire.h> #include <iostream> #include <string> #include <sstream> #include <stdio.h> class println; const int LED_FLASH = D7; // Instead of writing D7 over and over again, we'll write led2. This one is the little blue LED on your board. On the Photon it is next to D7, and on the Core it is next to the USB jack. int THERMISTOR = A3; // 10k thermistor int ANEMOMETER = D3; int WINDVANE = A0; int RAINGAUGE = WKP; double VCC = 3.33; // VCC voltage source int ADC_MAX = 4096; SYSTEM_MODE(MANUAL); PheatherStation gStation(VCC); BME280_I2C gBMESensor(0x76); bool bFoundSensor; uint8_t chipID; void anemometer_interrupt(); void raingauge_interrupt(); void debug_message(const string& msg) { Serial.println(msg.c_str()); Serial1.println(msg.c_str()); } void setup() { chipID = 0; //WiFi.connect(); //waitUntil(WiFi.ready); pinMode(LED_FLASH, OUTPUT); pinMode(THERMISTOR, INPUT); pinMode(WINDVANE, INPUT); pinMode(ANEMOMETER, INPUT); attachInterrupt(ANEMOMETER, anemometer_interrupt, RISING); pinMode(RAINGAUGE, INPUT); attachInterrupt(RAINGAUGE, raingauge_interrupt, RISING); Serial.begin(9600); Serial1.begin(9600); gStation.set_logger([=](const string& msg) { debug_message(msg); }); bFoundSensor = gBMESensor.begin(chipID); } void loop() { digitalWrite(LED_FLASH, HIGH); // Turn ON the LED delay(1000); // Wait for 1000mS = 1 second digitalWrite(LED_FLASH, LOW); // Turn OFF the LED delay(1000); // Wait for 1 second int digValue = analogRead(THERMISTOR); gStation.set_thermistor_voltage( digValue/(double)ADC_MAX * VCC ) ; stringstream msg; msg << "ambient temperature: "; msg << gStation.get_temperature() << endl; gBMESensor.readSensor(); float c_i2c = gBMESensor.getTemperature_C(); float pres_mb = gBMESensor.getPressure_MB(); float humidity = gBMESensor.getHumidity(); msg << "i2c temp: "; msg << c_i2c << endl; msg << " pressure mb: "; msg << pres_mb << endl; msg << " humidity: "; msg << humidity << endl; debug_message(msg.str()); digValue = analogRead(WINDVANE); /* byte error, address; int nDevices; nDevices = 0; for(address = 1; address < 127; address++ ) { if (address == 1) { debug_message("Scanning..."); delay(5000); } // The i2c_scanner uses the return value of // the Write.endTransmisstion to see if // a device did acknowledge to the address. Wire.beginTransmission(address); error = Wire.endTransmission(); stringstream msg; if (error == 0) { msg << "I2C device found at address "; msg << (int)address << " !"; nDevices++; } else if (error==4) { msg << "Unknow error at address"; msg << (int)address; } string msg_str = msg.str(); if (!msg_str.empty()) { debug_message(msg_str); } delay(100); debug_message("."); } if (nDevices == 0) debug_message("No I2C devices found\n"); else debug_message("done\n"); */ } void anemometer_interrupt() { debug_message("anemometer revolution\n"); } void raingauge_interrupt() { debug_message("rain gauage trigger\n"); }<|endoftext|>
<commit_before>// -*- mode:c++;coding:utf-8; -*- vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:enc=utf-8: /* The MIT License Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or http://flusspferd.org/contributors.txt) 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 "flusspferd/create.hpp" #include "flusspferd/binary.hpp" #include "flusspferd/tracer.hpp" #include "flusspferd/modules.hpp" #include "flusspferd/security.hpp" #include "flusspferd/arguments.hpp" #include "flusspferd/class_description.hpp" #include "flusspferd/property_iterator.hpp" #include <sstream> #include <curl/curl.h> #include <boost/ptr_container/ptr_unordered_map.hpp> #include <boost/exception/get_error_info.hpp> #include <boost/assign/ptr_map_inserter.hpp> #include <boost/version.hpp> #include <iostream> using namespace flusspferd; namespace { typedef boost::error_info<struct tag_curlcode, CURLcode> curlcode_info; struct exception : flusspferd::exception { exception(std::string const &what) : std::runtime_error(what), flusspferd::exception(what) { } char const *what() const throw() { #if BOOST_VERSION < 103900 boost::shared_ptr<CURLcode const*> code; #else CURLcode const *code; #endif if( (code = ::boost::get_error_info<curlcode_info>(*this)) ) { std::string what_ = flusspferd::exception::what(); what_ += ": "; what_ += curl_easy_strerror(*code); return what_.c_str(); } else { return flusspferd::exception::what(); } } }; void global_init(long flags) { CURLcode ret = curl_global_init(flags); if(ret != 0) { throw flusspferd::exception(std::string("curl_global_init: ") + curl_easy_strerror(ret)); } } class Easy; namespace { struct handle_option { virtual ~handle_option() =0; virtual value default_value() const { return value(); } virtual property_attributes default_attributes() const { return property_attributes(); } virtual void handle(Easy &e, value const &v) const =0; }; handle_option::~handle_option() { } typedef boost::ptr_unordered_map<std::string, handle_option> options_map_t; options_map_t const &get_options(); } FLUSSPFERD_CLASS_DESCRIPTION ( EasyOpt, (constructor_name, "EasyOpt") (full_name, "cURL.Easy.EasyOpt") (constructible, false) ) { Easy &parent; public: EasyOpt(flusspferd::object const &self, Easy &parent) : base_type(self), parent(parent) { } static EasyOpt &create(Easy &p) { return flusspferd::create_native_object<EasyOpt>(object(), boost::ref(p)); } protected: bool property_resolve(value const &id, unsigned access); }; FLUSSPFERD_CLASS_DESCRIPTION ( Easy, (constructor_name, "Easy") (full_name, "cURL.Easy") (methods, ("cleanup", bind, cleanup) ("perform", bind, perform) ("reset", bind, reset) ("escape", bind, escape) ("unescape", bind, unescape) ("valid", bind, valid)) (properties, ("options", getter, get_opt)) ) { CURL *handle; EasyOpt &opt; static size_t writefunction(void *ptr, size_t size, size_t nmemb, void *stream) { assert(stream); Easy &self = *reinterpret_cast<Easy*>(stream); byte_array data(object(), reinterpret_cast<byte_array::element_type*>(ptr), size*nmemb); arguments arg; arg.push_back(value(data)); arg.push_back(value(size)); object callback = self.opt.get_property("writefunction").to_object(); value v = callback.call(arg); return v.to_number(); } protected: void trace(flusspferd::tracer &trc) { trc("options", opt); } public: CURL *data() { return handle; } bool valid() { return handle; } CURL *get() { if(!handle) { throw flusspferd::exception("CURL handle not valid!"); } return handle; } EasyOpt &get_opt() { return opt; } Easy(flusspferd::object const &self, flusspferd::call_context&) : base_type(self), handle(curl_easy_init()), opt(EasyOpt::create(*this)) { if(!handle) { throw flusspferd::exception("curl_easy_init"); } } Easy(flusspferd::object const &self, CURL *hnd) : base_type(self), handle(hnd), opt(EasyOpt::create(*this)) { assert(handle); } void cleanup() { if(handle) { curl_easy_cleanup(handle); handle = 0x0; } } ~Easy() { cleanup(); } /** * Applies all options set in EasyOpt. * This is called automatically. * Shouldn't be necessary to call it manually! * * Not exported. * * Maybe this should be called by unwrap and be private ... */ void apply_options() { std::cout << "apply_options()\n"; options_map_t const &options = get_options(); for(property_iterator i = opt.begin(); i != opt.end(); ++i) { std::cout << "\t" << i->to_std_string() << "\n"; options_map_t::const_iterator option = options.find(i->to_std_string()); if(option != options.end()) { option->second->handle(*this, opt.get_property(*i)); } } } void perform() { apply_options(); CURLcode res = curl_easy_perform(get()); if(res != 0) { throw flusspferd::exception(std::string("curl_easy_perform: ") + curl_easy_strerror(res)); } } void reset() { curl_easy_reset(get()); } std::string unescape(char const *input) { int len; char *const uesc = curl_easy_unescape(get(), input, 0, &len); if(!uesc) { throw flusspferd::exception("curl_easy_unescape"); } std::string ret(uesc, len); curl_free(uesc); return ret; } std::string escape(char const *input) { char *const esc = curl_easy_escape(get(), input, 0); if(!esc) { throw flusspferd::exception("curl_easy_escape"); } std::string ret(esc); curl_free(esc); return ret; } static Easy &create(CURL *hnd) { return flusspferd::create_native_object<Easy>(object(), hnd); } //private: template<typename T> void do_setopt(CURLoption what, T data) { std::cout << "setopt (" << (unsigned)what << ' ' << data << '\n'; // DEBUG CURLcode res = curl_easy_setopt(get(), what, data); if(res != 0) { throw flusspferd::exception(std::string("curl_easy_setopt: ") + curl_easy_strerror(res)); } } void do_setopt_function(CURLoption what, bool default_) { if(default_) { do_setopt(what, 0x0); } else { switch(what) { case CURLOPT_WRITEFUNCTION: do_setopt(CURLOPT_WRITEFUNCTION, &writefunction); do_setopt(CURLOPT_WRITEDATA, this); break; default: throw flusspferd::exception("unkown function option"); }; } } }; Easy &wrap(CURL *hnd) { return Easy::create(hnd); } CURL *unwrap(Easy &c) { return c.data(); } namespace { struct integer_option : handle_option { integer_option(CURLoption what) : what(what) { } value default_value() const { return value(0); } void handle(Easy &e, value const &v) const { e.do_setopt(what, v.to_number()); } private: CURLoption what; }; struct string_option : handle_option { string_option(CURLoption what) : what(what) { } value default_value() const { return value(""); } void handle(Easy &e, value const &v) const { e.do_setopt(what, v.to_std_string().c_str()); // TODO this won't work! string needs to be stored. } private: CURLoption what; }; struct function_option : handle_option { function_option(CURLoption what) : what(what) { } void handle(Easy &e, value const &v) const { e.do_setopt_function(what, v.is_undefined_or_null()); } private: CURLoption what; }; options_map_t const &get_options() { static options_map_t map; if(map.empty()) { boost::assign::ptr_map_insert<integer_option>(map) ("verbose", CURLOPT_VERBOSE) ("header", CURLOPT_HEADER) ("noprogress", CURLOPT_NOPROGRESS) ("nosignal", CURLOPT_NOSIGNAL); boost::assign::ptr_map_insert<function_option>(map) ("writeFunction", CURLOPT_WRITEFUNCTION); boost::assign::ptr_map_insert<string_option>(map) ("url", CURLOPT_URL); } return map; } } bool EasyOpt::property_resolve(value const &id, unsigned) { std::string const name = id.to_std_string(); options_map_t::const_iterator const i = get_options().find(name); if(i != get_options().end()) { define_property(id.get_string(), i->second->default_value()); return true; } else { return false; } } FLUSSPFERD_LOADER_SIMPLE(cURL) { local_root_scope scope; cURL.define_property("GLOBAL_ALL", value(CURL_GLOBAL_ALL), read_only_property | permanent_property); cURL.define_property("GLOBAL_SSL", value(CURL_GLOBAL_SSL), read_only_property | permanent_property); cURL.define_property("GLOBAL_WIN32", value(CURL_GLOBAL_WIN32), read_only_property | permanent_property); cURL.define_property("GLOBAL_NOTHING", value(CURL_GLOBAL_NOTHING), read_only_property | permanent_property); create_native_function(cURL, "globalInit", &global_init); cURL.define_property("version", value(curl_version()), read_only_property | permanent_property); load_class<EasyOpt>(cURL); load_class<Easy>(cURL); } } <commit_msg>curl: minor fixes<commit_after>// -*- mode:c++;coding:utf-8; -*- vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:enc=utf-8: /* The MIT License Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or http://flusspferd.org/contributors.txt) 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 "flusspferd/create.hpp" #include "flusspferd/binary.hpp" #include "flusspferd/tracer.hpp" #include "flusspferd/modules.hpp" #include "flusspferd/security.hpp" #include "flusspferd/arguments.hpp" #include "flusspferd/class_description.hpp" #include "flusspferd/property_iterator.hpp" #include <sstream> #include <curl/curl.h> #include <boost/ptr_container/ptr_unordered_map.hpp> #include <boost/exception/get_error_info.hpp> #include <boost/assign/ptr_map_inserter.hpp> #include <boost/version.hpp> #include <iostream> using namespace flusspferd; namespace { typedef boost::error_info<struct tag_curlcode, CURLcode> curlcode_info; struct exception : flusspferd::exception { exception(std::string const &what) : std::runtime_error(what), flusspferd::exception(what) { } char const *what() const throw() { #if BOOST_VERSION < 103900 boost::shared_ptr<CURLcode const*> code; #else CURLcode const *code; #endif if( (code = ::boost::get_error_info<curlcode_info>(*this)) ) { std::string what_ = flusspferd::exception::what(); what_ += ": "; what_ += curl_easy_strerror(*code); return what_.c_str(); } else { return flusspferd::exception::what(); } } }; void global_init(long flags) { CURLcode ret = curl_global_init(flags); if(ret != 0) { throw flusspferd::exception(std::string("curl_global_init: ") + curl_easy_strerror(ret)); } } class Easy; namespace { struct handle_option { virtual ~handle_option() =0; virtual value default_value() const { return value(); } virtual property_attributes default_attributes() const { return property_attributes(); } virtual void handle(Easy &e, value const &v) const =0; }; handle_option::~handle_option() { } typedef boost::ptr_unordered_map<std::string, handle_option> options_map_t; options_map_t const &get_options(); } FLUSSPFERD_CLASS_DESCRIPTION ( EasyOpt, (constructor_name, "EasyOpt") (full_name, "cURL.Easy.EasyOpt") (constructible, false) ) { Easy &parent; public: EasyOpt(flusspferd::object const &self, Easy &parent) : base_type(self), parent(parent) { } static EasyOpt &create(Easy &p) { return flusspferd::create_native_object<EasyOpt>(object(), boost::ref(p)); } protected: bool property_resolve(value const &id, unsigned access); }; FLUSSPFERD_CLASS_DESCRIPTION ( Easy, (constructor_name, "Easy") (full_name, "cURL.Easy") (methods, ("cleanup", bind, cleanup) ("perform", bind, perform) ("reset", bind, reset) ("escape", bind, escape) ("unescape", bind, unescape) ("valid", bind, valid)) (properties, ("options", getter, get_opt)) ) { CURL *handle; EasyOpt &opt; static size_t writefunction(void *ptr, size_t size, size_t nmemb, void *stream) { assert(stream); Easy &self = *reinterpret_cast<Easy*>(stream); byte_array data(object(), reinterpret_cast<byte_array::element_type*>(ptr), size*nmemb); arguments arg; arg.push_back(value(data)); arg.push_back(value(size)); object callback = self.opt.get_property("writeFunction").to_object(); value v = callback.call(arg); return v.to_number(); } protected: void trace(flusspferd::tracer &trc) { trc("options", opt); } public: CURL *data() { return handle; } bool valid() { return handle; } CURL *get() { if(!handle) { throw flusspferd::exception("CURL handle not valid!"); } return handle; } EasyOpt &get_opt() { return opt; } Easy(flusspferd::object const &self, flusspferd::call_context&) : base_type(self), handle(curl_easy_init()), opt(EasyOpt::create(*this)) { if(!handle) { throw flusspferd::exception("curl_easy_init"); } } Easy(flusspferd::object const &self, CURL *hnd) : base_type(self), handle(hnd), opt(EasyOpt::create(*this)) { assert(handle); } void cleanup() { if(handle) { curl_easy_cleanup(handle); handle = 0x0; } } ~Easy() { cleanup(); } /** * Applies all options set in EasyOpt. * This is called automatically. * Shouldn't be necessary to call it manually! * * Not exported. * * Maybe this should be called by unwrap and be private ... */ void apply_options() { std::cout << "apply_options()\n"; options_map_t const &options = get_options(); for(property_iterator i = opt.begin(); i != opt.end(); ++i) { std::cout << "\t" << i->to_std_string() << "\n"; options_map_t::const_iterator option = options.find(i->to_std_string()); if(option != options.end()) { option->second->handle(*this, opt.get_property(*i)); } } } void perform() { apply_options(); CURLcode res = curl_easy_perform(get()); if(res != 0) { throw flusspferd::exception(std::string("curl_easy_perform: ") + curl_easy_strerror(res)); } } void reset() { curl_easy_reset(get()); } std::string unescape(char const *input) { int len; char *const uesc = curl_easy_unescape(get(), input, 0, &len); if(!uesc) { throw flusspferd::exception("curl_easy_unescape"); } std::string ret(uesc, len); curl_free(uesc); return ret; } std::string escape(char const *input) { char *const esc = curl_easy_escape(get(), input, 0); if(!esc) { throw flusspferd::exception("curl_easy_escape"); } std::string ret(esc); curl_free(esc); return ret; } static Easy &create(CURL *hnd) { return flusspferd::create_native_object<Easy>(object(), hnd); } //private: template<typename T> void do_setopt(CURLoption what, T data) { std::cout << "setopt (" << (unsigned)what << ' ' << data << '\n'; // DEBUG CURLcode res = curl_easy_setopt(get(), what, data); if(res != 0) { throw flusspferd::exception(std::string("curl_easy_setopt: ") + curl_easy_strerror(res)); } } void do_setopt_function(CURLoption what, bool default_) { if(default_) { do_setopt(what, 0x0); } else { switch(what) { case CURLOPT_WRITEFUNCTION: do_setopt(CURLOPT_WRITEFUNCTION, &writefunction); do_setopt(CURLOPT_WRITEDATA, this); break; default: throw flusspferd::exception("unkown function option"); }; } } }; Easy &wrap(CURL *hnd) { return Easy::create(hnd); } CURL *unwrap(Easy &c) { return c.data(); } namespace { struct integer_option : handle_option { integer_option(CURLoption what) : what(what) { } value default_value() const { return value(0); } void handle(Easy &e, value const &v) const { e.do_setopt(what, v.to_number()); } private: CURLoption what; }; struct string_option : handle_option { string_option(CURLoption what) : what(what) { } value default_value() const { return value(""); } void handle(Easy &e, value const &v) const { e.do_setopt(what, v.to_std_string().c_str()); // TODO this won't work! string needs to be stored. } private: CURLoption what; }; struct function_option : handle_option { function_option(CURLoption what) : what(what) { } void handle(Easy &e, value const &v) const { e.do_setopt_function(what, v.is_undefined_or_null()); } private: CURLoption what; }; options_map_t const &get_options() { static options_map_t map; if(map.empty()) { boost::assign::ptr_map_insert<integer_option>(map) ("verbose", CURLOPT_VERBOSE) ("header", CURLOPT_HEADER) ("noProgress", CURLOPT_NOPROGRESS) ("noSignal", CURLOPT_NOSIGNAL); boost::assign::ptr_map_insert<function_option>(map) ("writeFunction", CURLOPT_WRITEFUNCTION); boost::assign::ptr_map_insert<string_option>(map) ("url", CURLOPT_URL); } return map; } } bool EasyOpt::property_resolve(value const &id, unsigned) { std::string const name = id.to_std_string(); options_map_t::const_iterator const i = get_options().find(name); if(i != get_options().end()) { define_property(id.get_string(), i->second->default_value(), i->second->default_attributes()); return true; } else { return false; } } FLUSSPFERD_LOADER_SIMPLE(cURL) { local_root_scope scope; cURL.define_property("GLOBAL_ALL", value(CURL_GLOBAL_ALL), read_only_property | permanent_property); cURL.define_property("GLOBAL_SSL", value(CURL_GLOBAL_SSL), read_only_property | permanent_property); cURL.define_property("GLOBAL_WIN32", value(CURL_GLOBAL_WIN32), read_only_property | permanent_property); cURL.define_property("GLOBAL_NOTHING", value(CURL_GLOBAL_NOTHING), read_only_property | permanent_property); create_native_function(cURL, "globalInit", &global_init); cURL.define_property("version", value(curl_version()), read_only_property | permanent_property); load_class<EasyOpt>(cURL); load_class<Easy>(cURL); } } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2012. All rights reserved */ #include "../StroikaPreComp.h" #include <algorithm> #include <cstdlib> #include <sstream> #include "../../Foundation/Characters/Format.h" #include "../../Foundation/Containers/Common.h" #include "../../Foundation/Containers/SetUtils.h" #include "../../Foundation/DataExchangeFormat/BadFormatException.h" #include "../../Foundation/DataExchangeFormat/InternetMediaType.h" #include "../../Foundation/Debug/Assertions.h" #include "../../Foundation/Execution/Exceptions.h" #include "../../Foundation/IO/Network/HTTP/Exception.h" #include "../../Foundation/IO/Network/HTTP/Headers.h" #include "../../Foundation/Memory/SmallStackBuffer.h" #include "HTTPResponse.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Memory; using namespace Stroika::Frameworks; using namespace Stroika::Frameworks::WebServer; namespace { const set<String> kDisallowedOtherHeaders_ = Containers::mkS<String> ( IO::Network::HTTP::HeaderName::kContentLength, IO::Network::HTTP::HeaderName::kContentType ); } /* ******************************************************************************** ************************ WebServer::HTTPResponse ******************************* ******************************************************************************** */ namespace { // Based on looking at a handlful of typical file sizes...5k to 80k, but ave around // 25 and median abit above 32k. Small, not very representative sampling. And the more we use // subscripts (script src=x) this number could shrink. // // MAY want to switch to using SmallStackBuffer<Byte> - but before doing so, do some cleanups of its bugs and make sure // its optimized about how much it copies etc. Its really only tuned for POD-types (OK here but not necessarily good about reallocs). // // -- LGP 2011-07-06 const size_t kMinResponseBufferReserve_ = 32 * 1024; const size_t kResponseBufferReallocChunkSizeReserve_ = 16 * 1024; } HTTPResponse::HTTPResponse (const IO::Network::Socket& s, Streams::BinaryOutputStream& outStream, const InternetMediaType& ct) : fSocket_ (s) , fUnderlyingOutStream_ (outStream) , fUseOutStream_ (outStream) , fState_ (eInProgress) , fStatus_ (StatusCodes::kOK) , fStatusOverrideReason_ () , fHeaders_ () , fContentType_ (ct) , fCodePage_ (Characters::kCodePage_UTF8) , fBytes_ () , fContentSizePolicy_ (eAutoCompute_CSP) , fContentSize_ (0) { AddHeader (IO::Network::HTTP::HeaderName::kServer, L"Stroka-Based-Web-Server"); } HTTPResponse::~HTTPResponse () { Require (fState_ == eCompleted); } void HTTPResponse::SetContentSizePolicy (ContentSizePolicy csp) { Require (csp == eAutoCompute_CSP or csp == eNone_CSP); fContentSizePolicy_ = csp; } void HTTPResponse::SetContentSizePolicy (ContentSizePolicy csp, uint64_t size) { Require (csp == eExact_CSP); Require (fState_ == eInProgress); fContentSizePolicy_ = csp; fContentSize_ = size; } void HTTPResponse::SetContentType (const InternetMediaType& contentType) { Require (fState_ == eInProgress); fContentType_ = contentType; } void HTTPResponse::SetCodePage (Characters::CodePage codePage) { Require (fState_ == eInProgress); Require (fBytes_.empty ()); fCodePage_ = codePage; } void HTTPResponse::SetStatus (Status newStatus, const String& overrideReason) { Require (fState_ == eInProgress); fStatus_ = newStatus; fStatusOverrideReason_ = overrideReason; } void HTTPResponse::AddHeader (String headerName, String value) { Require (fState_ == eInProgress); Require (kDisallowedOtherHeaders_.find (headerName) == kDisallowedOtherHeaders_.end ()); ClearHeader (headerName); fHeaders_.insert (map<String, String>::value_type (headerName, value)); } void HTTPResponse::ClearHeader () { Require (fState_ == eInProgress); fHeaders_.clear (); } void HTTPResponse::ClearHeader (String headerName) { Require (fState_ == eInProgress); Require (kDisallowedOtherHeaders_.find (headerName) == kDisallowedOtherHeaders_.end ()); map<String, String>::iterator i = fHeaders_.find (headerName); if (i != fHeaders_.end ()) { fHeaders_.erase (i); } } map<String, String> HTTPResponse::GetSpecialHeaders () const { return fHeaders_; } map<String, String> HTTPResponse::GetEffectiveHeaders () const { map<String, String> tmp = GetSpecialHeaders (); switch (GetContentSizePolicy ()) { case eAutoCompute_CSP: case eExact_CSP: { wostringstream buf; buf << fContentSize_; tmp.insert (map<String, String>::value_type (IO::Network::HTTP::HeaderName::kContentLength, buf.str ())); } break; } if (not fContentType_.empty ()) { wstring contentTypeString = fContentType_.As<wstring> (); // Don't override already specifed characterset if (fContentType_.IsTextFormat () and contentTypeString.find (';') == wstring::npos) { contentTypeString += L"; charset=" + Characters::GetCharsetString (fCodePage_); } tmp.insert (map<String, String>::value_type (IO::Network::HTTP::HeaderName::kContentType, contentTypeString)); } return tmp; } void HTTPResponse::Flush () { if (fState_ == eInProgress) { { String statusMsg = fStatusOverrideReason_.empty () ? IO::Network::HTTP::Exception::GetStandardTextForStatus (fStatus_, true) : fStatusOverrideReason_; wstring version = L"1.1"; wstring tmp = Characters::Format (L"HTTP/%s %d %s\r\n", version.c_str (), fStatus_, statusMsg.c_str ()); string utf8 = String (tmp).AsUTF8 (); fUseOutStream_.Write (reinterpret_cast<const Byte*> (Containers::Start (utf8)), reinterpret_cast<const Byte*> (Containers::End (utf8))); } { map<String, String> headers2Write = GetEffectiveHeaders (); for (map<String, String>::const_iterator i = headers2Write.begin (); i != headers2Write.end (); ++i) { wstring tmp = Characters::Format (L"%s: %s\r\n", i->first.c_str (), i->second.c_str ()); string utf8 = String (tmp).AsUTF8 (); fUseOutStream_.Write (reinterpret_cast<const Byte*> (Containers::Start (utf8)), reinterpret_cast<const Byte*> (Containers::End (utf8))); } } const char kCRLF[] = "\r\n"; fUseOutStream_.Write (reinterpret_cast<const Byte*> (kCRLF), reinterpret_cast<const Byte*> (kCRLF + 2)); fState_ = eInProgressHeaderSentState; } // write BYTES to fOutStream if (not fBytes_.empty ()) { Assert (fState_ != eCompleted); // We PREVENT any writes when completed fUseOutStream_.Write (Containers::Start (fBytes_), Containers::End (fBytes_)); fBytes_.clear (); } if (fState_ != eCompleted) { fUseOutStream_.Flush (); } Ensure (fBytes_.empty ()); } void HTTPResponse::End () { Require ((fState_ == eInProgress) or (fState_ == eInProgressHeaderSentState)); Flush (); fState_ = eCompleted; Ensure (fState_ == eCompleted); Ensure (fBytes_.empty ()); } void HTTPResponse::Abort () { if (fState_ != eCompleted) { fState_ = eCompleted; fUseOutStream_.Abort (); fSocket_.Close (); fBytes_.clear (); } Ensure (fState_ == eCompleted); Ensure (fBytes_.empty ()); } void HTTPResponse::Redirect (const String& url) { Require (fState_ == eInProgress); fBytes_.clear (); // PERHAPS should clear some header values??? AddHeader (L"Connection", L"close"); // needed for redirect AddHeader (L"Location", url); // needed for redirect SetStatus (StatusCodes::kMovedPermanently); Flush (); fState_ = eCompleted; } void HTTPResponse::write (const Byte* s, const Byte* e) { Require ((fState_ == eInProgress) or (fState_ == eInProgressHeaderSentState)); Require ((fState_ == eInProgress) or (GetContentSizePolicy () != eAutoCompute_CSP)); Require (s <= e); if (s < e) { Containers::ReserveSpeedTweekAddN (fBytes_, (e - s), kResponseBufferReallocChunkSizeReserve_); fBytes_.insert (fBytes_.end (), s, e); if (GetContentSizePolicy () == eAutoCompute_CSP) { // Because for autocompute - illegal to call flush and then write fContentSize_ = fBytes_.size (); } } } void HTTPResponse::write (const wchar_t* s, const wchar_t* e) { Require ((fState_ == eInProgress) or (fState_ == eInProgressHeaderSentState)); Require ((fState_ == eInProgress) or (GetContentSizePolicy () != eAutoCompute_CSP)); Require (s <= e); if (s < e) { wstring tmp = wstring (s, e); string cpStr = Characters::WideStringToNarrow (tmp, fCodePage_); if (not cpStr.empty ()) { fBytes_.insert (fBytes_.end (), reinterpret_cast<const Byte*> (cpStr.c_str ()), reinterpret_cast<const Byte*> (cpStr.c_str () + cpStr.length ())); if (GetContentSizePolicy () == eAutoCompute_CSP) { // Because for autocompute - illegal to call flush and then write fContentSize_ = fBytes_.size (); } } } } <commit_msg>fixed minor bug with change of placement of STL containers into Containers::STL<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2012. All rights reserved */ #include "../StroikaPreComp.h" #include <algorithm> #include <cstdlib> #include <sstream> #include "../../Foundation/Characters/Format.h" #include "../../Foundation/Containers/Common.h" #include "../../Foundation/Containers/STL/SetUtils.h" #include "../../Foundation/DataExchangeFormat/BadFormatException.h" #include "../../Foundation/DataExchangeFormat/InternetMediaType.h" #include "../../Foundation/Debug/Assertions.h" #include "../../Foundation/Execution/Exceptions.h" #include "../../Foundation/IO/Network/HTTP/Exception.h" #include "../../Foundation/IO/Network/HTTP/Headers.h" #include "../../Foundation/Memory/SmallStackBuffer.h" #include "HTTPResponse.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Memory; using namespace Stroika::Frameworks; using namespace Stroika::Frameworks::WebServer; namespace { const set<String> kDisallowedOtherHeaders_ = Containers::STL::mkS<String> ( IO::Network::HTTP::HeaderName::kContentLength, IO::Network::HTTP::HeaderName::kContentType ); } /* ******************************************************************************** ************************ WebServer::HTTPResponse ******************************* ******************************************************************************** */ namespace { // Based on looking at a handlful of typical file sizes...5k to 80k, but ave around // 25 and median abit above 32k. Small, not very representative sampling. And the more we use // subscripts (script src=x) this number could shrink. // // MAY want to switch to using SmallStackBuffer<Byte> - but before doing so, do some cleanups of its bugs and make sure // its optimized about how much it copies etc. Its really only tuned for POD-types (OK here but not necessarily good about reallocs). // // -- LGP 2011-07-06 const size_t kMinResponseBufferReserve_ = 32 * 1024; const size_t kResponseBufferReallocChunkSizeReserve_ = 16 * 1024; } HTTPResponse::HTTPResponse (const IO::Network::Socket& s, Streams::BinaryOutputStream& outStream, const InternetMediaType& ct) : fSocket_ (s) , fUnderlyingOutStream_ (outStream) , fUseOutStream_ (outStream) , fState_ (eInProgress) , fStatus_ (StatusCodes::kOK) , fStatusOverrideReason_ () , fHeaders_ () , fContentType_ (ct) , fCodePage_ (Characters::kCodePage_UTF8) , fBytes_ () , fContentSizePolicy_ (eAutoCompute_CSP) , fContentSize_ (0) { AddHeader (IO::Network::HTTP::HeaderName::kServer, L"Stroka-Based-Web-Server"); } HTTPResponse::~HTTPResponse () { Require (fState_ == eCompleted); } void HTTPResponse::SetContentSizePolicy (ContentSizePolicy csp) { Require (csp == eAutoCompute_CSP or csp == eNone_CSP); fContentSizePolicy_ = csp; } void HTTPResponse::SetContentSizePolicy (ContentSizePolicy csp, uint64_t size) { Require (csp == eExact_CSP); Require (fState_ == eInProgress); fContentSizePolicy_ = csp; fContentSize_ = size; } void HTTPResponse::SetContentType (const InternetMediaType& contentType) { Require (fState_ == eInProgress); fContentType_ = contentType; } void HTTPResponse::SetCodePage (Characters::CodePage codePage) { Require (fState_ == eInProgress); Require (fBytes_.empty ()); fCodePage_ = codePage; } void HTTPResponse::SetStatus (Status newStatus, const String& overrideReason) { Require (fState_ == eInProgress); fStatus_ = newStatus; fStatusOverrideReason_ = overrideReason; } void HTTPResponse::AddHeader (String headerName, String value) { Require (fState_ == eInProgress); Require (kDisallowedOtherHeaders_.find (headerName) == kDisallowedOtherHeaders_.end ()); ClearHeader (headerName); fHeaders_.insert (map<String, String>::value_type (headerName, value)); } void HTTPResponse::ClearHeader () { Require (fState_ == eInProgress); fHeaders_.clear (); } void HTTPResponse::ClearHeader (String headerName) { Require (fState_ == eInProgress); Require (kDisallowedOtherHeaders_.find (headerName) == kDisallowedOtherHeaders_.end ()); map<String, String>::iterator i = fHeaders_.find (headerName); if (i != fHeaders_.end ()) { fHeaders_.erase (i); } } map<String, String> HTTPResponse::GetSpecialHeaders () const { return fHeaders_; } map<String, String> HTTPResponse::GetEffectiveHeaders () const { map<String, String> tmp = GetSpecialHeaders (); switch (GetContentSizePolicy ()) { case eAutoCompute_CSP: case eExact_CSP: { wostringstream buf; buf << fContentSize_; tmp.insert (map<String, String>::value_type (IO::Network::HTTP::HeaderName::kContentLength, buf.str ())); } break; } if (not fContentType_.empty ()) { wstring contentTypeString = fContentType_.As<wstring> (); // Don't override already specifed characterset if (fContentType_.IsTextFormat () and contentTypeString.find (';') == wstring::npos) { contentTypeString += L"; charset=" + Characters::GetCharsetString (fCodePage_); } tmp.insert (map<String, String>::value_type (IO::Network::HTTP::HeaderName::kContentType, contentTypeString)); } return tmp; } void HTTPResponse::Flush () { if (fState_ == eInProgress) { { String statusMsg = fStatusOverrideReason_.empty () ? IO::Network::HTTP::Exception::GetStandardTextForStatus (fStatus_, true) : fStatusOverrideReason_; wstring version = L"1.1"; wstring tmp = Characters::Format (L"HTTP/%s %d %s\r\n", version.c_str (), fStatus_, statusMsg.c_str ()); string utf8 = String (tmp).AsUTF8 (); fUseOutStream_.Write (reinterpret_cast<const Byte*> (Containers::Start (utf8)), reinterpret_cast<const Byte*> (Containers::End (utf8))); } { map<String, String> headers2Write = GetEffectiveHeaders (); for (map<String, String>::const_iterator i = headers2Write.begin (); i != headers2Write.end (); ++i) { wstring tmp = Characters::Format (L"%s: %s\r\n", i->first.c_str (), i->second.c_str ()); string utf8 = String (tmp).AsUTF8 (); fUseOutStream_.Write (reinterpret_cast<const Byte*> (Containers::Start (utf8)), reinterpret_cast<const Byte*> (Containers::End (utf8))); } } const char kCRLF[] = "\r\n"; fUseOutStream_.Write (reinterpret_cast<const Byte*> (kCRLF), reinterpret_cast<const Byte*> (kCRLF + 2)); fState_ = eInProgressHeaderSentState; } // write BYTES to fOutStream if (not fBytes_.empty ()) { Assert (fState_ != eCompleted); // We PREVENT any writes when completed fUseOutStream_.Write (Containers::Start (fBytes_), Containers::End (fBytes_)); fBytes_.clear (); } if (fState_ != eCompleted) { fUseOutStream_.Flush (); } Ensure (fBytes_.empty ()); } void HTTPResponse::End () { Require ((fState_ == eInProgress) or (fState_ == eInProgressHeaderSentState)); Flush (); fState_ = eCompleted; Ensure (fState_ == eCompleted); Ensure (fBytes_.empty ()); } void HTTPResponse::Abort () { if (fState_ != eCompleted) { fState_ = eCompleted; fUseOutStream_.Abort (); fSocket_.Close (); fBytes_.clear (); } Ensure (fState_ == eCompleted); Ensure (fBytes_.empty ()); } void HTTPResponse::Redirect (const String& url) { Require (fState_ == eInProgress); fBytes_.clear (); // PERHAPS should clear some header values??? AddHeader (L"Connection", L"close"); // needed for redirect AddHeader (L"Location", url); // needed for redirect SetStatus (StatusCodes::kMovedPermanently); Flush (); fState_ = eCompleted; } void HTTPResponse::write (const Byte* s, const Byte* e) { Require ((fState_ == eInProgress) or (fState_ == eInProgressHeaderSentState)); Require ((fState_ == eInProgress) or (GetContentSizePolicy () != eAutoCompute_CSP)); Require (s <= e); if (s < e) { Containers::ReserveSpeedTweekAddN (fBytes_, (e - s), kResponseBufferReallocChunkSizeReserve_); fBytes_.insert (fBytes_.end (), s, e); if (GetContentSizePolicy () == eAutoCompute_CSP) { // Because for autocompute - illegal to call flush and then write fContentSize_ = fBytes_.size (); } } } void HTTPResponse::write (const wchar_t* s, const wchar_t* e) { Require ((fState_ == eInProgress) or (fState_ == eInProgressHeaderSentState)); Require ((fState_ == eInProgress) or (GetContentSizePolicy () != eAutoCompute_CSP)); Require (s <= e); if (s < e) { wstring tmp = wstring (s, e); string cpStr = Characters::WideStringToNarrow (tmp, fCodePage_); if (not cpStr.empty ()) { fBytes_.insert (fBytes_.end (), reinterpret_cast<const Byte*> (cpStr.c_str ()), reinterpret_cast<const Byte*> (cpStr.c_str () + cpStr.length ())); if (GetContentSizePolicy () == eAutoCompute_CSP) { // Because for autocompute - illegal to call flush and then write fContentSize_ = fBytes_.size (); } } } } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __itkTestingHashImageFilter_hxx #define __itkTestingHashImageFilter_hxx #include "itkTestingHashImageFilter.h" #include "itkByteSwapper.h" #include "itksys/MD5.h" namespace itk { namespace Testing { // // Constructor // template<class TImageType> HashImageFilter<TImageType>::HashImageFilter() { // create data object this->ProcessObject::SetNthOutput( 1, this->MakeOutput(1).GetPointer() ); this->InPlaceOn(); } // // MakeOutput // template<class TImageType> typename HashImageFilter<TImageType>::DataObjectPointer HashImageFilter<TImageType>::MakeOutput(unsigned int idx) { if ( idx == 1 ) { return static_cast< DataObject * >( HashObjectType::New().GetPointer() ); } return Superclass::MakeOutput(idx); } // // AfterThreadedGenerateData // template<class TImageType> void HashImageFilter<TImageType>::AfterThreadedGenerateData() { // NOTE: We have choose our super class to be the // CastImageFilter. The filter is derived from the // InPlaceFilter. The CastImageFilter will copy its input, in the // best fashion based on the InPlace setting. We want the // behavior. This methods is called after the caster has done it's // work. Superclass::AfterThreadedGenerateData(); typedef TImageType ImageType; typedef typename ImageType::PixelType PixelType; typedef typename NumericTraits<PixelType>::ValueType ValueType; typedef itk::ByteSwapper<ValueType> Swapper; itksysMD5 *md5 = itksysMD5_New(); itksysMD5_Initialize( md5 ); typename ImageType::ConstPointer input = this->GetInput(); // make a good guess about the number of components in each pixel size_t numberOfComponent = sizeof(PixelType) / sizeof(ValueType ); if ( strcmp(input->GetNameOfClass(), "VectorImage") == 0 ) { // spacial case for VectorImages numberOfComponent = ImageType::AccessorFunctorType::GetVectorLength(input); } else if ( sizeof(PixelType) % sizeof(ValueType) != 0 ) { itkExceptionMacro("Unsupported data type for hashing!"); } // we feel bad about accessing the data this way ValueType *buffer = static_cast<ValueType*>( (void *)input->GetBufferPointer() ); typename ImageType::RegionType largestRegion = input->GetBufferedRegion(); const size_t numberOfValues = largestRegion.GetNumberOfPixels()*numberOfComponent; // Possible byte swap so we always calculate on little endian data if ( Swapper::SystemIsBigEndian() ) { Swapper::SwapRangeFromSystemToLittleEndian ( buffer, numberOfValues ); } itksysMD5_Append( md5, (unsigned char*)buffer, numberOfValues*sizeof(ValueType) ); if ( Swapper::SystemIsBigEndian() ) { Swapper::SwapRangeFromSystemToLittleEndian ( buffer, numberOfValues ); } //////// // NOTE: THIS IS NOT A NULL TERMINATED STRING!!! //////// const size_t DigestSize = 32u; char Digest[DigestSize]; itksysMD5_FinalizeHex( md5, Digest ); this->GetHashOutput()->Set( std::string(Digest, DigestSize) ); } // // EnlargeOutputRequestedRegion // template<class TImageType> void HashImageFilter<TImageType>::EnlargeOutputRequestedRegion(DataObject *data) { Superclass::EnlargeOutputRequestedRegion(data); // set the output region to the largest and let the pipeline // propagate the requested region to the input data->SetRequestedRegionToLargestPossibleRegion(); } // // PrintSelf // template<class TImageType> void HashImageFilter<TImageType>::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "HashFunction: " << m_HashFunction << std::endl; } } // end namespace Testing } // end namespace itk #endif // __itkTestingHashImageFilter_txx <commit_msg>BUG: Fix memory leak in TestingHashImageFilter<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __itkTestingHashImageFilter_hxx #define __itkTestingHashImageFilter_hxx #include "itkTestingHashImageFilter.h" #include "itkByteSwapper.h" #include "itksys/MD5.h" namespace itk { namespace Testing { // // Constructor // template<class TImageType> HashImageFilter<TImageType>::HashImageFilter() { // create data object this->ProcessObject::SetNthOutput( 1, this->MakeOutput(1).GetPointer() ); this->InPlaceOn(); } // // MakeOutput // template<class TImageType> typename HashImageFilter<TImageType>::DataObjectPointer HashImageFilter<TImageType>::MakeOutput(unsigned int idx) { if ( idx == 1 ) { return static_cast< DataObject * >( HashObjectType::New().GetPointer() ); } return Superclass::MakeOutput(idx); } // // AfterThreadedGenerateData // template<class TImageType> void HashImageFilter<TImageType>::AfterThreadedGenerateData() { // NOTE: We have choose our super class to be the // CastImageFilter. The filter is derived from the // InPlaceFilter. The CastImageFilter will copy its input, in the // best fashion based on the InPlace setting. We want the // behavior. This methods is called after the caster has done it's // work. Superclass::AfterThreadedGenerateData(); typedef TImageType ImageType; typedef typename ImageType::PixelType PixelType; typedef typename NumericTraits<PixelType>::ValueType ValueType; typedef itk::ByteSwapper<ValueType> Swapper; itksysMD5 *md5 = itksysMD5_New(); itksysMD5_Initialize( md5 ); try { typename ImageType::ConstPointer input = this->GetInput(); // make a good guess about the number of components in each pixel size_t numberOfComponent = sizeof(PixelType) / sizeof(ValueType ); if ( strcmp(input->GetNameOfClass(), "VectorImage") == 0 ) { // spacial case for VectorImages numberOfComponent = ImageType::AccessorFunctorType::GetVectorLength(input); } else if ( sizeof(PixelType) % sizeof(ValueType) != 0 ) { itkExceptionMacro("Unsupported data type for hashing!"); } // we feel bad about accessing the data this way ValueType *buffer = static_cast<ValueType*>( (void *)input->GetBufferPointer() ); typename ImageType::RegionType largestRegion = input->GetBufferedRegion(); const size_t numberOfValues = largestRegion.GetNumberOfPixels()*numberOfComponent; // Possible byte swap so we always calculate on little endian data if ( Swapper::SystemIsBigEndian() ) { Swapper::SwapRangeFromSystemToLittleEndian ( buffer, numberOfValues ); } itksysMD5_Append( md5, (unsigned char*)buffer, numberOfValues*sizeof(ValueType) ); if ( Swapper::SystemIsBigEndian() ) { Swapper::SwapRangeFromSystemToLittleEndian ( buffer, numberOfValues ); } //////// // NOTE: THIS IS NOT A NULL TERMINATED STRING!!! //////// const size_t DigestSize = 32u; char Digest[DigestSize]; itksysMD5_FinalizeHex( md5, Digest ); this->GetHashOutput()->Set( std::string(Digest, DigestSize) ); } catch (... ) { // free all resources when an exception occours itksysMD5_Delete( md5 ); throw; } // free resources itksysMD5_Delete( md5 ); } // // EnlargeOutputRequestedRegion // template<class TImageType> void HashImageFilter<TImageType>::EnlargeOutputRequestedRegion(DataObject *data) { Superclass::EnlargeOutputRequestedRegion(data); // set the output region to the largest and let the pipeline // propagate the requested region to the input data->SetRequestedRegionToLargestPossibleRegion(); } // // PrintSelf // template<class TImageType> void HashImageFilter<TImageType>::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "HashFunction: " << m_HashFunction << std::endl; } } // end namespace Testing } // end namespace itk #endif // __itkTestingHashImageFilter_txx <|endoftext|>
<commit_before>#line 2 "quanta/core/object/io_text.cpp" /** @copyright MIT license; see @ref index or the accompanying LICENSE file. */ #include <quanta/core/config.hpp> #include <togo/core/error/assert.hpp> #include <togo/core/log/log.hpp> #include <togo/core/memory/memory.hpp> #include <togo/core/memory/temp_allocator.hpp> #include <togo/core/collection/array.hpp> #include <togo/core/string/string.hpp> #include <togo/core/io/types.hpp> #include <togo/core/io/io.hpp> #include <togo/core/io/file_stream.hpp> #include <quanta/core/object/object.hpp> #include <quanta/core/object/io/parser.ipp> #include <cstdio> namespace quanta { /// Read text-format object from stream. /// /// Returns false if a parser error occurred. pinfo will have the /// position and error message of the parser. bool object::read_text(Object& root, IReader& stream, ObjectParserInfo& pinfo) { TempAllocator<4096> allocator{}; ObjectParser p{stream, pinfo, allocator}; array::reserve(p.stack, 32); array::reserve(p.buffer, 4096 - (1 * sizeof(void*)) - (32 * sizeof(ObjectParser::Branch))); object::clear(root); parser_init(p, root); return parser_read(p); } /// Read text-format object from stream (sans parser info). bool object::read_text(Object& root, IReader& stream) { ObjectParserInfo pinfo{}; if (!object::read_text(root, stream, pinfo)) { TOGO_LOG_ERRORF( "failed to read object: [%2u,%2u]: %s\n", pinfo.line, pinfo.column, pinfo.message ); return false; } return true; } /// Read text-format object from file. bool object::read_text_file(Object& root, StringRef const& path) { FileReader stream{}; if (!stream.open(path)) { TOGO_LOG_ERRORF( "failed to read object from '%.*s': failed to open file\n", path.size, path.data ); return false; } ObjectParserInfo pinfo{}; bool const success = object::read_text(root, stream, pinfo); if (!success) { TOGO_LOG_ERRORF( "failed to read object from '%.*s': [%2u,%2u]: %s\n", path.size, path.data, pinfo.line, pinfo.column, pinfo.message ); } stream.close(); return success; } // write namespace { static constexpr char const TABS[]{ "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" }; #define RETURN_ERROR(x) if (!(x)) { return false; } static bool write_tabs(IWriter& stream, unsigned tabs) { while (tabs > 0) { unsigned const amount = min(tabs, array_extent(TABS)); if (!io::write(stream, TABS, amount)) { return false; } tabs -= amount; } return true; } #if defined(TOGO_COMPILER_CLANG) || \ defined(TOGO_COMPILER_GCC) __attribute__((__format__ (__printf__, 2, 3))) #endif static bool writef(IWriter& stream, char const* const format, ...) { char buffer[256]; va_list va; va_start(va, format); signed const size = std::vsnprintf(buffer, array_extent(buffer), format, va); va_end(va); if (size < 0) { return false; } return io::write(stream, buffer, static_cast<unsigned>(size)); } inline static unsigned quote_level(StringRef const& str) { unsigned level = str.empty() ? 1 : 0; if (str.size >= 1) { char const c = str.data[0]; if ((c >= '0' && c <= '9') || c == '-' || c == '+') { level = 1; } } auto const it_end = end(str); for (auto it = begin(str); it != it_end && level < 2; ++it) { switch (*it) { case '\t': case ' ': case ',': case ';': case ':': case '=': case '{': case '}': case '[': case ']': case '(': case ')': case '/': case '`': level = 1; break; case '\"': // fall-through case '\n': level = 2; break; } } return level; } inline static bool write_quote(IWriter& stream, unsigned level) { switch (level) { case 0: break; case 1: RETURN_ERROR(io::write_value(stream, '\"')); break; case 2: RETURN_ERROR(io::write(stream, "```", 3)); break; } return true; } inline static bool write_identifier(IWriter& stream, StringRef const& str) { RETURN_ERROR(io::write(stream, str.data, str.size)); return true; } inline static bool write_string(IWriter& stream, StringRef const& str) { unsigned const level = quote_level(str); RETURN_ERROR( write_quote(stream, level) && io::write(stream, str.data, str.size) && write_quote(stream, level) ); return true; } inline static bool write_source(IWriter& stream, unsigned source, bool uncertain) { RETURN_ERROR( io::write(stream, "$?", 1 + uncertain) && (source == 0 || writef(stream, "%u", source)) ); return true; } inline static bool write_markers(IWriter& stream, Object const& obj) { if (object::marker_value_uncertain(obj)) { RETURN_ERROR(io::write_value(stream, '?')); } else if (object::marker_value_guess(obj)) { RETURN_ERROR(io::write(stream, "G~", 2)); } auto approximation = object::value_approximation(obj); if (approximation < 0) { RETURN_ERROR(io::write(stream, "~~~", unsigned_cast(-approximation))); } else if (approximation > 0) { RETURN_ERROR(io::write(stream, "^^^", unsigned_cast(approximation))); } return true; } static bool write_object( IWriter& stream, Object const& obj, unsigned tabs ); static bool write_tag( IWriter& stream, Object const& obj, unsigned tabs ) { RETURN_ERROR( io::write_value(stream, ':') && write_markers(stream, obj) && write_identifier(stream, object::name(obj)) ); if (object::has_children(obj)) { RETURN_ERROR(io::write_value(stream, '(')); auto& last_child = array::back(object::children(obj)); for (auto& child : object::children(obj)) { RETURN_ERROR( write_object(stream, child, tabs) && (&child == &last_child || io::write(stream, ", ", 2)) ); } RETURN_ERROR(io::write_value(stream, ')')); } return true; } static bool write_object( IWriter& stream, Object const& obj, unsigned tabs ) { if (object::is_named(obj)) { RETURN_ERROR( write_identifier(stream, object::name(obj)) && io::write(stream, " = ", 3) ); } RETURN_ERROR(write_markers(stream, obj)); switch (object::type(obj)) { case ObjectValueType::null: if ( !(obj.properties & Object::M_VALUE_MARKERS) && !object::has_children(obj) && !object::has_tags(obj) ) { RETURN_ERROR(io::write(stream, "null", 4)); } break; case ObjectValueType::boolean: if (obj.value.boolean) { RETURN_ERROR(io::write(stream, "true", 4)); } else { RETURN_ERROR(io::write(stream, "false", 5)); } break; case ObjectValueType::integer: RETURN_ERROR(writef(stream, "%ld", obj.value.numeric.integer)); break; case ObjectValueType::decimal: RETURN_ERROR(writef(stream, "%.6lg", obj.value.numeric.decimal)); break; case ObjectValueType::string: RETURN_ERROR(write_string(stream, object::string(obj))); break; } if (object::has_unit(obj)) { RETURN_ERROR(write_identifier(stream, object::unit(obj))); } if (object::has_source(obj) || object::marker_source_uncertain(obj)) { RETURN_ERROR(write_source(stream, object::source(obj), object::marker_source_uncertain(obj))); if (object::has_sub_source(obj) || object::marker_sub_source_uncertain(obj)) { RETURN_ERROR(write_source(stream, object::sub_source(obj), object::marker_sub_source_uncertain(obj))); } } // TODO: split pre- and post-tags for (auto& tag : object::tags(obj)) { RETURN_ERROR(write_tag(stream, tag, tabs)); } if (object::has_children(obj)) { RETURN_ERROR(io::write(stream, "{\n", 2)); ++tabs; for (auto& child : object::children(obj)) { RETURN_ERROR( write_tabs(stream, tabs) && write_object(stream, child, tabs) && io::write_value(stream, '\n') ); } --tabs; RETURN_ERROR( write_tabs(stream, tabs) && io::write_value(stream, '}') ); } if (object::has_quantity(obj)) { auto& quantity = *object::quantity(obj); RETURN_ERROR(io::write_value(stream, '[')); if (object::has_children(quantity)) { auto& last_child = array::back(object::children(quantity)); for (auto& child : object::children(quantity)) { RETURN_ERROR( write_object(stream, child, 0) && (&child == &last_child || io::write(stream, ", ", 2)) ); } } else { RETURN_ERROR(write_object(stream, quantity, 0)); } RETURN_ERROR(io::write_value(stream, ']')); } return true; } #undef RETURN_ERROR } // anonymous namespace // unsigned object::prewrite_fix() // TODO // bool object::prewrite_validate() // TODO // tag: /* if (unmanaged_string::empty(name)) { TOGO_LOG_ERROR("unnamed tag\n"); return false; } else if (!object::is_null(obj)) { TOGO_LOG_ERRORF("tag '%.*s' is non-null\n", name.size, name.data); return false; } else if (object::has_tags(obj)) { TOGO_LOG_ERRORF("tag '%.*s' has tags itself\n", name.size, name.data); return false; } else if (object::has_quantity(obj)) { TOGO_LOG_ERRORF("tag '%.*s' has quantity\n", name.size, name.data); return false; } */ /// Write text-format object to stream. /// /// Returns true if the write succeeded. bool object::write_text(Object const& obj, IWriter& stream) { for (auto& child : object::children(obj)) { if (!( write_object(stream, child, 0) && io::write_value(stream, '\n') )) { return false; } } return io::status(stream).ok(); } /// Write text-format object to file. bool object::write_text_file(Object const& obj, StringRef const& path) { FileWriter stream{}; if (!stream.open(path, false)) { TOGO_LOG_ERRORF( "failed to write object to '%.*s': failed to open file\n", path.size, path.data ); return false; } bool const success = object::write_text(obj, stream); stream.close(); return success; } } // namespace quanta <commit_msg>lib/core/object/io_text: implemented expression writing.<commit_after>#line 2 "quanta/core/object/io_text.cpp" /** @copyright MIT license; see @ref index or the accompanying LICENSE file. */ #include <quanta/core/config.hpp> #include <togo/core/error/assert.hpp> #include <togo/core/log/log.hpp> #include <togo/core/memory/memory.hpp> #include <togo/core/memory/temp_allocator.hpp> #include <togo/core/collection/array.hpp> #include <togo/core/string/string.hpp> #include <togo/core/io/types.hpp> #include <togo/core/io/io.hpp> #include <togo/core/io/file_stream.hpp> #include <quanta/core/object/object.hpp> #include <quanta/core/object/io/parser.ipp> #include <cstdio> namespace quanta { /// Read text-format object from stream. /// /// Returns false if a parser error occurred. pinfo will have the /// position and error message of the parser. bool object::read_text(Object& root, IReader& stream, ObjectParserInfo& pinfo) { TempAllocator<4096> allocator{}; ObjectParser p{stream, pinfo, allocator}; array::reserve(p.stack, 32); array::reserve(p.buffer, 4096 - (1 * sizeof(void*)) - (32 * sizeof(ObjectParser::Branch))); object::clear(root); parser_init(p, root); return parser_read(p); } /// Read text-format object from stream (sans parser info). bool object::read_text(Object& root, IReader& stream) { ObjectParserInfo pinfo{}; if (!object::read_text(root, stream, pinfo)) { TOGO_LOG_ERRORF( "failed to read object: [%2u,%2u]: %s\n", pinfo.line, pinfo.column, pinfo.message ); return false; } return true; } /// Read text-format object from file. bool object::read_text_file(Object& root, StringRef const& path) { FileReader stream{}; if (!stream.open(path)) { TOGO_LOG_ERRORF( "failed to read object from '%.*s': failed to open file\n", path.size, path.data ); return false; } ObjectParserInfo pinfo{}; bool const success = object::read_text(root, stream, pinfo); if (!success) { TOGO_LOG_ERRORF( "failed to read object from '%.*s': [%2u,%2u]: %s\n", path.size, path.data, pinfo.line, pinfo.column, pinfo.message ); } stream.close(); return success; } // write namespace { static constexpr char const TABS[]{ "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" }; #define RETURN_ERROR(x) if (!(x)) { return false; } static bool write_tabs(IWriter& stream, unsigned tabs) { while (tabs > 0) { unsigned const amount = min(tabs, array_extent(TABS)); if (!io::write(stream, TABS, amount)) { return false; } tabs -= amount; } return true; } #if defined(TOGO_COMPILER_CLANG) || \ defined(TOGO_COMPILER_GCC) __attribute__((__format__ (__printf__, 2, 3))) #endif static bool writef(IWriter& stream, char const* const format, ...) { char buffer[256]; va_list va; va_start(va, format); signed const size = std::vsnprintf(buffer, array_extent(buffer), format, va); va_end(va); if (size < 0) { return false; } return io::write(stream, buffer, static_cast<unsigned>(size)); } inline static unsigned quote_level(StringRef const& str) { unsigned level = str.empty() ? 1 : 0; if (str.size >= 1) { char const c = str.data[0]; if ((c >= '0' && c <= '9') || c == '-' || c == '+') { level = 1; } } auto const it_end = end(str); for (auto it = begin(str); it != it_end && level < 2; ++it) { switch (*it) { case '\t': case ' ': case ',': case ';': case ':': case '=': case '{': case '}': case '[': case ']': case '(': case ')': case '/': case '`': level = 1; break; case '\"': // fall-through case '\n': level = 2; break; } } return level; } inline static bool write_quote(IWriter& stream, unsigned level) { switch (level) { case 0: break; case 1: RETURN_ERROR(io::write_value(stream, '\"')); break; case 2: RETURN_ERROR(io::write(stream, "```", 3)); break; } return true; } inline static bool write_identifier(IWriter& stream, StringRef const& str) { RETURN_ERROR(io::write(stream, str.data, str.size)); return true; } inline static bool write_string(IWriter& stream, StringRef const& str) { unsigned const level = quote_level(str); RETURN_ERROR( write_quote(stream, level) && io::write(stream, str.data, str.size) && write_quote(stream, level) ); return true; } inline static bool write_source(IWriter& stream, unsigned source, bool uncertain) { RETURN_ERROR( io::write(stream, "$?", 1 + uncertain) && (source == 0 || writef(stream, "%u", source)) ); return true; } inline static bool write_markers(IWriter& stream, Object const& obj) { if (object::marker_value_uncertain(obj)) { RETURN_ERROR(io::write_value(stream, '?')); } else if (object::marker_value_guess(obj)) { RETURN_ERROR(io::write(stream, "G~", 2)); } auto approximation = object::value_approximation(obj); if (approximation < 0) { RETURN_ERROR(io::write(stream, "~~~", unsigned_cast(-approximation))); } else if (approximation > 0) { RETURN_ERROR(io::write(stream, "^^^", unsigned_cast(approximation))); } return true; } static bool write_object( IWriter& stream, Object const& obj, unsigned tabs ); static bool write_tag( IWriter& stream, Object const& obj, unsigned tabs ) { RETURN_ERROR( io::write_value(stream, ':') && write_markers(stream, obj) && write_identifier(stream, object::name(obj)) ); if (object::has_children(obj)) { RETURN_ERROR(io::write_value(stream, '(')); auto& last_child = array::back(object::children(obj)); for (auto& child : object::children(obj)) { RETURN_ERROR( write_object(stream, child, tabs) && (&child == &last_child || io::write(stream, ", ", 2)) ); } RETURN_ERROR(io::write_value(stream, ')')); } return true; } inline char const* op_string(ObjectOperator const op) { switch (op) { case ObjectOperator::add: return " + "; case ObjectOperator::sub: return " - "; case ObjectOperator::mul: return " * "; case ObjectOperator::div: return " / "; } } static bool write_expression( IWriter& stream, Object const& obj, unsigned tabs ) { if (object::has_children(obj)) { auto& children = object::children(obj); auto it = begin(children); auto end = array::end(children); RETURN_ERROR(write_object(stream, *it, tabs)); for (++it; it != end; ++it) { RETURN_ERROR( io::write(stream, op_string(object::op(*it)), 3) && write_object(stream, *it, tabs) ); } } return true; } static bool write_object( IWriter& stream, Object const& obj, unsigned tabs ) { if (object::is_expression(obj)) { return write_expression(stream, obj, tabs); } else if (object::is_named(obj)) { RETURN_ERROR( write_identifier(stream, object::name(obj)) && io::write(stream, " = ", 3) ); } RETURN_ERROR(write_markers(stream, obj)); switch (object::type(obj)) { case ObjectValueType::null: if ( !(obj.properties & Object::M_VALUE_MARKERS) && !object::has_children(obj) && !object::has_tags(obj) ) { RETURN_ERROR(io::write(stream, "null", 4)); } break; case ObjectValueType::boolean: if (obj.value.boolean) { RETURN_ERROR(io::write(stream, "true", 4)); } else { RETURN_ERROR(io::write(stream, "false", 5)); } break; case ObjectValueType::integer: RETURN_ERROR(writef(stream, "%ld", obj.value.numeric.integer)); break; case ObjectValueType::decimal: RETURN_ERROR(writef(stream, "%.6lg", obj.value.numeric.decimal)); break; case ObjectValueType::string: RETURN_ERROR(write_string(stream, object::string(obj))); break; case ObjectValueType::expression: break; } if (object::has_unit(obj)) { RETURN_ERROR(write_identifier(stream, object::unit(obj))); } if (object::has_source(obj) || object::marker_source_uncertain(obj)) { RETURN_ERROR(write_source(stream, object::source(obj), object::marker_source_uncertain(obj))); if (object::has_sub_source(obj) || object::marker_sub_source_uncertain(obj)) { RETURN_ERROR(write_source(stream, object::sub_source(obj), object::marker_sub_source_uncertain(obj))); } } // TODO: split pre- and post-tags for (auto& tag : object::tags(obj)) { RETURN_ERROR(write_tag(stream, tag, tabs)); } if (object::has_children(obj)) { RETURN_ERROR(io::write(stream, "{\n", 2)); ++tabs; for (auto& child : object::children(obj)) { RETURN_ERROR( write_tabs(stream, tabs) && write_object(stream, child, tabs) && io::write_value(stream, '\n') ); } --tabs; RETURN_ERROR( write_tabs(stream, tabs) && io::write_value(stream, '}') ); } if (object::has_quantity(obj)) { auto& quantity = *object::quantity(obj); RETURN_ERROR(io::write_value(stream, '[')); if (object::has_children(quantity)) { auto& last_child = array::back(object::children(quantity)); for (auto& child : object::children(quantity)) { RETURN_ERROR( write_object(stream, child, 0) && (&child == &last_child || io::write(stream, ", ", 2)) ); } } else { RETURN_ERROR(write_object(stream, quantity, 0)); } RETURN_ERROR(io::write_value(stream, ']')); } return true; } #undef RETURN_ERROR } // anonymous namespace // unsigned object::prewrite_fix() // TODO // bool object::prewrite_validate() // TODO // tag: /* if (unmanaged_string::empty(name)) { TOGO_LOG_ERROR("unnamed tag\n"); return false; } else if (!object::is_null(obj)) { TOGO_LOG_ERRORF("tag '%.*s' is non-null\n", name.size, name.data); return false; } else if (object::has_tags(obj)) { TOGO_LOG_ERRORF("tag '%.*s' has tags itself\n", name.size, name.data); return false; } else if (object::has_quantity(obj)) { TOGO_LOG_ERRORF("tag '%.*s' has quantity\n", name.size, name.data); return false; } */ /// Write text-format object to stream. /// /// Returns true if the write succeeded. bool object::write_text(Object const& obj, IWriter& stream) { for (auto& child : object::children(obj)) { if (!( write_object(stream, child, 0) && io::write_value(stream, '\n') )) { return false; } } return io::status(stream).ok(); } /// Write text-format object to file. bool object::write_text_file(Object const& obj, StringRef const& path) { FileWriter stream{}; if (!stream.open(path, false)) { TOGO_LOG_ERRORF( "failed to write object to '%.*s': failed to open file\n", path.size, path.data ); return false; } bool const success = object::write_text(obj, stream); stream.close(); return success; } } // namespace quanta <|endoftext|>
<commit_before>AliAnalysisTaskSEXicPlus2XiPiPifromAODtracks *AddTaskXicPlus2XiPiPifromAODtracksJ(TString finname="", TString outputFileName="", Bool_t theMCon=kFALSE, Bool_t writeVariableTree=kTRUE, Bool_t reconstructPrimVert=kFALSE, Bool_t fillOnlySig = kFALSE, Bool_t fillOnlyBkg = kFALSE, Bool_t fillSparse = kFALSE, Bool_t HMTrigOn = kTRUE, //jcho, for HM analysis Bool_t EvtInfo = kFALSE //jcho, to write the event tree ) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskLc2V0YW", "No analysis manager to connect to."); return NULL; } Bool_t stdcuts=kFALSE; TFile* filecuts; if( finname.EqualTo("") ) { stdcuts=kTRUE; } else { filecuts=TFile::Open(finname.Data()); if(!filecuts ||(filecuts&& !filecuts->IsOpen())){ cout << "Input file not found : check your cut object" << endl; return 0x0; // AliFatal("Input file not found : check your cut object"); } } AliRDHFCutsXicPlustoXiPiPifromAODtracks* RDHFCutsXic2PiPianal = new AliRDHFCutsXicPlustoXiPiPifromAODtracks(); if (stdcuts) RDHFCutsXic2PiPianal->SetStandardCutsPP2010(); else RDHFCutsXic2PiPianal = (AliRDHFCutsXicPlustoXiPiPifromAODtracks*)filecuts->Get("XicPlusAnalysisCuts"); RDHFCutsXic2PiPianal->SetName("XicPlusAnalysisCuts"); RDHFCutsXic2PiPianal->SetMinPtCandidate(2.); RDHFCutsXic2PiPianal->SetMaxPtCandidate(10000.); // mm let's see if everything is ok if (!RDHFCutsXic2PiPianal) { cout << "Specific AliRDHFCutsXic2PiPianal not found\n"; return 0x0; } //CREATE THE TASK if(writeVariableTree && fillSparse) { cout << "You are enabling the filling of both Tree and THnSparse\n"; cout << "Please choose only one of the two options.\n"; return 0x0; } AliAnalysisTaskSEXicPlus2XiPiPifromAODtracks *task = new AliAnalysisTaskSEXicPlus2XiPiPifromAODtracks("AliAnalysisTaskSEXicPlus2XiPiPifromAODtracks",RDHFCutsXic2PiPianal,writeVariableTree,fillSparse,HMTrigOn,EvtInfo); task->SetMC(theMCon); task->SetFillSignalOnly(fillOnlySig); task->SetFillBkgOnly(fillOnlyBkg); if ((!theMCon && fillOnlySig) || (!theMCon && fillOnlyBkg) || (fillOnlySig && fillOnlyBkg)) {cout<< "Wrong settings for MC" << endl; return 0x0;} task->SetDebugLevel(1); task->SetReconstructPrimVert(reconstructPrimVert); //mgr->AddTask(task); task->UseTrig_kINT7(); //jcho if (HMTrigOn){ task->UseTrig_kHMV0(); //jcho, HM Trigger task->UseTrig_kHMSPD(); //jcho, HM Trigger } // Create and connect containers for input/output TString outputfile = AliAnalysisManager::GetCommonFileName(); outputfile += ":PWG3_D2H_XicPlus2XiPiPi_"; outputfile += outputFileName.Data(); if(HMTrigOn) outputfile += "_HM"; mgr->AddTask(task); //jcho mgr->ConnectInput(task,0,mgr->GetCommonInputContainer()); // ----- output data ----- AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(Form("chist%s",outputFileName.Data()),TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); // general histos mgr->ConnectOutput(task,1,coutput1); AliAnalysisDataContainer *coutputXic2 = mgr->CreateContainer(Form("XicPlus2XiPiPiCuts%s",outputFileName.Data()),TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); // cuts mgr->ConnectOutput(task,2,coutputXic2); if (writeVariableTree) { AliAnalysisDataContainer *coutputXic3 = mgr->CreateContainer(Form("XicPlusvariables%s",outputFileName.Data()),TTree::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); mgr->ConnectOutput(task,3,coutputXic3); }else{ AliAnalysisDataContainer *coutputXic3 = mgr->CreateContainer(Form("XicPlusAll%s",outputFileName.Data()),TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); // general histos mgr->ConnectOutput(task,3,coutputXic3); } AliAnalysisDataContainer *coutputXic4 = mgr->CreateContainer(Form("XicPlus2XiPiPiNorm%s",outputFileName.Data()),AliNormalizationCounter::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); // normalization counter mgr->ConnectOutput(task,4,coutputXic4); // For HM analysis -------jcho AliAnalysisDataContainer *coutputXic5 = mgr->CreateContainer(Form("MB_0to100%s",outputFileName.Data()),AliNormalizationCounter::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); mgr->ConnectOutput(task,5,coutputXic5); AliAnalysisDataContainer *coutputXic6 = mgr->CreateContainer(Form("MB_0point1to30%s",outputFileName.Data()),AliNormalizationCounter::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); mgr->ConnectOutput(task,6,coutputXic6); AliAnalysisDataContainer *coutputXic7 = mgr->CreateContainer(Form("MB_30to100%s",outputFileName.Data()),AliNormalizationCounter::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); mgr->ConnectOutput(task,7,coutputXic7); AliAnalysisDataContainer *coutputXic8 = mgr->CreateContainer(Form("HMV0_0to0point1%s",outputFileName.Data()),AliNormalizationCounter::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); mgr->ConnectOutput(task,8,coutputXic8); AliAnalysisDataContainer *coutputXic9 = mgr->CreateContainer(Form("HMV0_0to100%s",outputFileName.Data()),AliNormalizationCounter::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); mgr->ConnectOutput(task,9,coutputXic9); if(EvtInfo) { AliAnalysisDataContainer *coutputXic10 = mgr->CreateContainer(Form("XicPlusEventvariables%s",outputFileName.Data()),TTree::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); //jcho, Event variables tree mgr->ConnectOutput(task,10,coutputXic10); } return task; } <commit_msg>Minor debug on addtask<commit_after>AliAnalysisTaskSEXicPlus2XiPiPifromAODtracks *AddTaskXicPlus2XiPiPifromAODtracks(TString finname="", TString outputFileName="", Bool_t theMCon=kFALSE, Bool_t writeVariableTree=kTRUE, Bool_t reconstructPrimVert=kFALSE, Bool_t fillOnlySig = kFALSE, Bool_t fillOnlyBkg = kFALSE, Bool_t fillSparse = kFALSE, Bool_t HMTrigOn = kTRUE, //jcho, for HM analysis Bool_t EvtInfo = kFALSE //jcho, to write the event tree ) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskLc2V0YW", "No analysis manager to connect to."); return NULL; } Bool_t stdcuts=kFALSE; TFile* filecuts; if( finname.EqualTo("") ) { stdcuts=kTRUE; } else { filecuts=TFile::Open(finname.Data()); if(!filecuts ||(filecuts&& !filecuts->IsOpen())){ cout << "Input file not found : check your cut object" << endl; return 0x0; // AliFatal("Input file not found : check your cut object"); } } AliRDHFCutsXicPlustoXiPiPifromAODtracks* RDHFCutsXic2PiPianal = new AliRDHFCutsXicPlustoXiPiPifromAODtracks(); if (stdcuts) RDHFCutsXic2PiPianal->SetStandardCutsPP2010(); else RDHFCutsXic2PiPianal = (AliRDHFCutsXicPlustoXiPiPifromAODtracks*)filecuts->Get("XicPlusAnalysisCuts"); RDHFCutsXic2PiPianal->SetName("XicPlusAnalysisCuts"); RDHFCutsXic2PiPianal->SetMinPtCandidate(2.); RDHFCutsXic2PiPianal->SetMaxPtCandidate(10000.); // mm let's see if everything is ok if (!RDHFCutsXic2PiPianal) { cout << "Specific AliRDHFCutsXic2PiPianal not found\n"; return 0x0; } //CREATE THE TASK if(writeVariableTree && fillSparse) { cout << "You are enabling the filling of both Tree and THnSparse\n"; cout << "Please choose only one of the two options.\n"; return 0x0; } AliAnalysisTaskSEXicPlus2XiPiPifromAODtracks *task = new AliAnalysisTaskSEXicPlus2XiPiPifromAODtracks("AliAnalysisTaskSEXicPlus2XiPiPifromAODtracks",RDHFCutsXic2PiPianal,writeVariableTree,fillSparse,HMTrigOn,EvtInfo); task->SetMC(theMCon); task->SetFillSignalOnly(fillOnlySig); task->SetFillBkgOnly(fillOnlyBkg); if ((!theMCon && fillOnlySig) || (!theMCon && fillOnlyBkg) || (fillOnlySig && fillOnlyBkg)) {cout<< "Wrong settings for MC" << endl; return 0x0;} task->SetDebugLevel(1); task->SetReconstructPrimVert(reconstructPrimVert); //mgr->AddTask(task); task->UseTrig_kINT7(); //jcho if (HMTrigOn){ task->UseTrig_kHMV0(); //jcho, HM Trigger task->UseTrig_kHMSPD(); //jcho, HM Trigger } // Create and connect containers for input/output TString outputfile = AliAnalysisManager::GetCommonFileName(); outputfile += ":PWG3_D2H_XicPlus2XiPiPi_"; outputfile += outputFileName.Data(); if(HMTrigOn) outputfile += "_HM"; mgr->AddTask(task); //jcho mgr->ConnectInput(task,0,mgr->GetCommonInputContainer()); // ----- output data ----- AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(Form("chist%s",outputFileName.Data()),TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); // general histos mgr->ConnectOutput(task,1,coutput1); AliAnalysisDataContainer *coutputXic2 = mgr->CreateContainer(Form("XicPlus2XiPiPiCuts%s",outputFileName.Data()),TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); // cuts mgr->ConnectOutput(task,2,coutputXic2); if (writeVariableTree) { AliAnalysisDataContainer *coutputXic3 = mgr->CreateContainer(Form("XicPlusvariables%s",outputFileName.Data()),TTree::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); mgr->ConnectOutput(task,3,coutputXic3); }else{ AliAnalysisDataContainer *coutputXic3 = mgr->CreateContainer(Form("XicPlusAll%s",outputFileName.Data()),TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); // general histos mgr->ConnectOutput(task,3,coutputXic3); } AliAnalysisDataContainer *coutputXic4 = mgr->CreateContainer(Form("XicPlus2XiPiPiNorm%s",outputFileName.Data()),AliNormalizationCounter::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); // normalization counter mgr->ConnectOutput(task,4,coutputXic4); // For HM analysis -------jcho AliAnalysisDataContainer *coutputXic5 = mgr->CreateContainer(Form("MB_0to100%s",outputFileName.Data()),AliNormalizationCounter::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); mgr->ConnectOutput(task,5,coutputXic5); AliAnalysisDataContainer *coutputXic6 = mgr->CreateContainer(Form("MB_0point1to30%s",outputFileName.Data()),AliNormalizationCounter::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); mgr->ConnectOutput(task,6,coutputXic6); AliAnalysisDataContainer *coutputXic7 = mgr->CreateContainer(Form("MB_30to100%s",outputFileName.Data()),AliNormalizationCounter::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); mgr->ConnectOutput(task,7,coutputXic7); AliAnalysisDataContainer *coutputXic8 = mgr->CreateContainer(Form("HMV0_0to0point1%s",outputFileName.Data()),AliNormalizationCounter::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); mgr->ConnectOutput(task,8,coutputXic8); AliAnalysisDataContainer *coutputXic9 = mgr->CreateContainer(Form("HMV0_0to100%s",outputFileName.Data()),AliNormalizationCounter::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); mgr->ConnectOutput(task,9,coutputXic9); if(EvtInfo) { AliAnalysisDataContainer *coutputXic10 = mgr->CreateContainer(Form("XicPlusEventvariables%s",outputFileName.Data()),TTree::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); //jcho, Event variables tree mgr->ConnectOutput(task,10,coutputXic10); } return task; } <|endoftext|>
<commit_before>/* * qca_securemessage.cpp - Qt Cryptographic Architecture * Copyright (C) 2003-2005 Justin Karneges <[email protected]> * Copyright (C) 2004,2005 Brad Hards <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include "qca_securemessage.h" #include <qdatetime.h> #include "qca_publickey.h" #include "qca_cert.h" namespace QCA { //---------------------------------------------------------------------------- // SecureMessageKey //---------------------------------------------------------------------------- SecureMessageKey::SecureMessageKey() { } SecureMessageKey::SecureMessageKey(const SecureMessageKey &from) { Q_UNUSED(from); } SecureMessageKey::~SecureMessageKey() { } SecureMessageKey & SecureMessageKey::operator=(const SecureMessageKey &from) { Q_UNUSED(from); return *this; } SecureMessageKey::Type SecureMessageKey::type() const { return None; } QString SecureMessageKey::pgpPublicKey() const { return QString(); } QString SecureMessageKey::pgpSecretKey() const { return QString(); } void SecureMessageKey::setPGPPublicKey(const QString &id, const QString &name) { Q_UNUSED(id); Q_UNUSED(name); } void SecureMessageKey::setPGPSecretKey(const QString &id) { Q_UNUSED(id); } CertificateChain SecureMessageKey::x509CertificateChain() const { return CertificateChain(); } PrivateKey SecureMessageKey::x509PrivateKey() const { return PrivateKey(); } void SecureMessageKey::setX509CertificateChain(const CertificateChain &c) { Q_UNUSED(c); } void SecureMessageKey::setX509PrivateKey(const PrivateKey &k) { Q_UNUSED(k); } bool SecureMessageKey::havePrivate() const { return false; } QString SecureMessageKey::id() const { return QString(); } QString SecureMessageKey::name() const { return QString(); } //---------------------------------------------------------------------------- // SecureMessage //---------------------------------------------------------------------------- SecureMessage::SecureMessage(SecureMessageSystem *system) { Q_UNUSED(system); } SecureMessage::~SecureMessage() { } /*void SecureMessage::encrypt(const QSecureArray &in, const SecureMessageKey &key) { Q_UNUSED(in); Q_UNUSED(key); } void SecureMessage::encrypt(const QSecureArray &in, const SecureMessageKeyList &keys) { Q_UNUSED(in); Q_UNUSED(keys); } void SecureMessage::encryptAndSign(const QSecureArray &in, const SecureMessageKey &key, const SecureMessageKey &signer, Mode m) { Q_UNUSED(in); Q_UNUSED(key); Q_UNUSED(signer); Q_UNUSED(m); } void SecureMessage::encryptAndSign(const QSecureArray &in, const SecureMessageKeyList &keys, const SecureMessageKey &signer, Mode m) { Q_UNUSED(in); Q_UNUSED(keys); Q_UNUSED(signer); Q_UNUSED(m); } void SecureMessage::decrypt(const QString &in) { Q_UNUSED(in); } void SecureMessage::sign(const QSecureArray &in, const SecureMessageKey &signer) { Q_UNUSED(in); Q_UNUSED(signer); } void SecureMessage::verify(const QSecureArray &in, const QString &sig) { Q_UNUSED(in); Q_UNUSED(sig); }*/ bool SecureMessage::canSignMultiple() const { return false; } void SecureMessage::setEnableBundleSigner(bool b) { Q_UNUSED(b); } void SecureMessage::setFormat(Format f) { Q_UNUSED(f); } void SecureMessage::setRecipient(const SecureMessageKey &key) { Q_UNUSED(key); } void SecureMessage::setRecipients(const SecureMessageKeyList &keys) { Q_UNUSED(keys); } void SecureMessage::setSigner(const SecureMessageKey &key) { Q_UNUSED(key); } void SecureMessage::setSigners(const SecureMessageKeyList &keys) { Q_UNUSED(keys); } void SecureMessage::startEncrypt() { } void SecureMessage::startDecrypt() { } void SecureMessage::startSign(SignMode m = Message); { Q_UNUSED(m); } void SecureMessage::startVerify(const QSecureArray &sig) { Q_UNUSED(sig); } void SecureMessage::startEncryptAndSign(Order o) { Q_UNUSED(o); } void SecureMessage::startDecryptAndVerify(Order o) { Q_UNUSED(o); } void SecureMessage::update(const QSecureArray &in) { Q_UNUSED(in); } QSecureArray SecureMessage::read(int size) { Q_UNUSED(size); return QSecureArray(); } int SecureMessage::bytesAvailable() const { return 0; } void SecureMessage::end() { } bool SecureMessage::waitForFinished() { return false; } bool SecureMessage::success() const { return false; } SecureMessage::Error SecureMessage::errorCode() const { return ErrUnknown; } QSecureArray SecureMessage::signature() const { return QSecureArray(); } SecureMessage::VerifyResult SecureMessage::verifyResult() const { return Invalid; } CertValidity SecureMessage::keyValidity() const { return QCA::Valid; } SecureMessageKey SecureMessage::key() const { return SecureMessageKey(); } QDateTime SecureMessage::timestamp() const { return QDateTime(); } //---------------------------------------------------------------------------- // SecureMessageSystem //---------------------------------------------------------------------------- SecureMessageSystem::SecureMessageSystem(QObject *parent, const char *name) :QObject(parent, name) { } SecureMessageSystem::~SecureMessageSystem() { } //---------------------------------------------------------------------------- // OpenPGP //---------------------------------------------------------------------------- OpenPGP::OpenPGP(QObject *parent, const char *name, const QString &provider) :SecureMessageSystem(parent, name), Algorithm("openpgp", provider) { } OpenPGP::~OpenPGP() { } void OpenPGP::setAllowAgent(bool) { } void OpenPGP::submitPassphrase(const QSecureArray &passphrase) { Q_UNUSED(passphrase); } SecureMessageKeyList OpenPGP::secretKeys() const { return SecureMessageKeyList(); } SecureMessageKeyList OpenPGP::publicKeys() const { return SecureMessageKeyList(); } //---------------------------------------------------------------------------- // SMIME //---------------------------------------------------------------------------- SMIME::SMIME(QObject *parent, const char *name, const QString &provider) :SecureMessageSystem(parent, name), Algorithm("smime", provider) { } SMIME::~SMIME() { } void SMIME::setStore(const Store &store) { Q_UNUSED(store); } void SMIME::setPrivateKeys(const QValueList<PrivateKey> &keys) { Q_UNUSED(keys); } } <commit_msg>Yeah, I should compile this stuff before committing it.<commit_after>/* * qca_securemessage.cpp - Qt Cryptographic Architecture * Copyright (C) 2003-2005 Justin Karneges <[email protected]> * Copyright (C) 2004,2005 Brad Hards <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include "qca_securemessage.h" #include <qdatetime.h> #include "qca_publickey.h" #include "qca_cert.h" namespace QCA { //---------------------------------------------------------------------------- // SecureMessageKey //---------------------------------------------------------------------------- SecureMessageKey::SecureMessageKey() { } SecureMessageKey::SecureMessageKey(const SecureMessageKey &from) { Q_UNUSED(from); } SecureMessageKey::~SecureMessageKey() { } SecureMessageKey & SecureMessageKey::operator=(const SecureMessageKey &from) { Q_UNUSED(from); return *this; } SecureMessageKey::Type SecureMessageKey::type() const { return None; } QString SecureMessageKey::pgpPublicKey() const { return QString(); } QString SecureMessageKey::pgpSecretKey() const { return QString(); } void SecureMessageKey::setPGPPublicKey(const QString &id, const QString &name) { Q_UNUSED(id); Q_UNUSED(name); } void SecureMessageKey::setPGPSecretKey(const QString &id) { Q_UNUSED(id); } CertificateChain SecureMessageKey::x509CertificateChain() const { return CertificateChain(); } PrivateKey SecureMessageKey::x509PrivateKey() const { return PrivateKey(); } void SecureMessageKey::setX509CertificateChain(const CertificateChain &c) { Q_UNUSED(c); } void SecureMessageKey::setX509PrivateKey(const PrivateKey &k) { Q_UNUSED(k); } bool SecureMessageKey::havePrivate() const { return false; } QString SecureMessageKey::id() const { return QString(); } QString SecureMessageKey::name() const { return QString(); } //---------------------------------------------------------------------------- // SecureMessage //---------------------------------------------------------------------------- SecureMessage::SecureMessage(SecureMessageSystem *system) { Q_UNUSED(system); } SecureMessage::~SecureMessage() { } /*void SecureMessage::encrypt(const QSecureArray &in, const SecureMessageKey &key) { Q_UNUSED(in); Q_UNUSED(key); } void SecureMessage::encrypt(const QSecureArray &in, const SecureMessageKeyList &keys) { Q_UNUSED(in); Q_UNUSED(keys); } void SecureMessage::encryptAndSign(const QSecureArray &in, const SecureMessageKey &key, const SecureMessageKey &signer, Mode m) { Q_UNUSED(in); Q_UNUSED(key); Q_UNUSED(signer); Q_UNUSED(m); } void SecureMessage::encryptAndSign(const QSecureArray &in, const SecureMessageKeyList &keys, const SecureMessageKey &signer, Mode m) { Q_UNUSED(in); Q_UNUSED(keys); Q_UNUSED(signer); Q_UNUSED(m); } void SecureMessage::decrypt(const QString &in) { Q_UNUSED(in); } void SecureMessage::sign(const QSecureArray &in, const SecureMessageKey &signer) { Q_UNUSED(in); Q_UNUSED(signer); } void SecureMessage::verify(const QSecureArray &in, const QString &sig) { Q_UNUSED(in); Q_UNUSED(sig); }*/ bool SecureMessage::canSignMultiple() const { return false; } void SecureMessage::setEnableBundleSigner(bool b) { Q_UNUSED(b); } void SecureMessage::setFormat(Format f) { Q_UNUSED(f); } void SecureMessage::setRecipient(const SecureMessageKey &key) { Q_UNUSED(key); } void SecureMessage::setRecipients(const SecureMessageKeyList &keys) { Q_UNUSED(keys); } void SecureMessage::setSigner(const SecureMessageKey &key) { Q_UNUSED(key); } void SecureMessage::setSigners(const SecureMessageKeyList &keys) { Q_UNUSED(keys); } void SecureMessage::startEncrypt() { } void SecureMessage::startDecrypt() { } void SecureMessage::startSign(SignMode m) { Q_UNUSED(m); } void SecureMessage::startVerify(const QSecureArray &sig) { Q_UNUSED(sig); } void SecureMessage::startEncryptAndSign(Order o) { Q_UNUSED(o); } void SecureMessage::startDecryptAndVerify(Order o) { Q_UNUSED(o); } void SecureMessage::update(const QSecureArray &in) { Q_UNUSED(in); } QSecureArray SecureMessage::read(int size) { Q_UNUSED(size); return QSecureArray(); } int SecureMessage::bytesAvailable() const { return 0; } void SecureMessage::end() { } bool SecureMessage::waitForFinished() { return false; } bool SecureMessage::success() const { return false; } SecureMessage::Error SecureMessage::errorCode() const { return ErrUnknown; } QSecureArray SecureMessage::signature() const { return QSecureArray(); } SecureMessage::VerifyResult SecureMessage::verifyResult() const { return Invalid; } CertValidity SecureMessage::keyValidity() const { return QCA::Valid; } SecureMessageKey SecureMessage::key() const { return SecureMessageKey(); } QDateTime SecureMessage::timestamp() const { return QDateTime(); } //---------------------------------------------------------------------------- // SecureMessageSystem //---------------------------------------------------------------------------- SecureMessageSystem::SecureMessageSystem(QObject *parent, const char *name) :QObject(parent, name) { } SecureMessageSystem::~SecureMessageSystem() { } //---------------------------------------------------------------------------- // OpenPGP //---------------------------------------------------------------------------- OpenPGP::OpenPGP(QObject *parent, const char *name, const QString &provider) :SecureMessageSystem(parent, name), Algorithm("openpgp", provider) { } OpenPGP::~OpenPGP() { } void OpenPGP::setAllowAgent(bool) { } void OpenPGP::submitPassphrase(const QSecureArray &passphrase) { Q_UNUSED(passphrase); } SecureMessageKeyList OpenPGP::secretKeys() const { return SecureMessageKeyList(); } SecureMessageKeyList OpenPGP::publicKeys() const { return SecureMessageKeyList(); } //---------------------------------------------------------------------------- // SMIME //---------------------------------------------------------------------------- SMIME::SMIME(QObject *parent, const char *name, const QString &provider) :SecureMessageSystem(parent, name), Algorithm("smime", provider) { } SMIME::~SMIME() { } void SMIME::setStore(const Store &store) { Q_UNUSED(store); } void SMIME::setPrivateKeys(const QValueList<PrivateKey> &keys) { Q_UNUSED(keys); } } <|endoftext|>
<commit_before>#include "nametablemodel.h" #include "guiutil.h" #include "walletmodel.h" #include "guiconstants.h" #include "../headers.h" #include "../namecoin.h" #include "ui_interface.h" #include <QTimer> extern std::map<std::vector<unsigned char>, PreparedNameFirstUpdate> mapMyNameFirstUpdate; // ExpiresIn column is right-aligned as it contains numbers static int column_alignments[] = { Qt::AlignLeft|Qt::AlignVCenter, // Name Qt::AlignLeft|Qt::AlignVCenter, // Value Qt::AlignLeft|Qt::AlignVCenter, // Address Qt::AlignRight|Qt::AlignVCenter // Expires in }; struct NameTableEntryLessThan { bool operator()(const NameTableEntry &a, const NameTableEntry &b) const { return a.name < b.name; } bool operator()(const NameTableEntry &a, const QString &b) const { return a.name < b; } bool operator()(const QString &a, const NameTableEntry &b) const { return a < b.name; } }; // Returns true if new height is better /*static*/ bool NameTableEntry::CompareHeight(int nOldHeight, int nNewHeight) { if (nOldHeight == NAME_NON_EXISTING) return true; // We use optimistic way, assuming that unconfirmed transaction will eventually become confirmed, // so we update the name in the table immediately. Ideally we need a separate way of displaying // unconfirmed names (e.g. grayed out) if (nNewHeight == NAME_UNCONFIRMED) return true; // Here we rely on the fact that dummy height values are always negative return nNewHeight > nOldHeight; } // Private implementation class NameTablePriv { public: CWallet *wallet; QList<NameTableEntry> cachedNameTable; NameTableModel *parent; NameTablePriv(CWallet *wallet, NameTableModel *parent): wallet(wallet), parent(parent) {} void refreshNameTable() { cachedNameTable.clear(); std::map< std::vector<unsigned char>, NameTableEntry > vNamesO; CRITICAL_BLOCK(cs_main) CRITICAL_BLOCK(wallet->cs_mapWallet) { CTxIndex txindex; uint256 hash; CTxDB txdb("r"); CTransaction tx; std::vector<unsigned char> vchName; std::vector<unsigned char> vchValue; int nHeight; BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, wallet->mapWallet) { hash = item.second.GetHash(); bool fConfirmed; bool fTransferred = false; // TODO: Maybe CMerkleTx::GetDepthInMainChain() would be faster? if (!txdb.ReadDiskTx(hash, tx, txindex)) { tx = item.second; fConfirmed = false; } else fConfirmed = true; if (tx.nVersion != NAMECOIN_TX_VERSION) continue; // name if (!GetNameOfTx(tx, vchName)) continue; // value if (!GetValueOfNameTx(tx, vchValue)) continue; if (!hooks->IsMine(wallet->mapWallet[tx.GetHash()])) fTransferred = true; // height if (fConfirmed) { nHeight = GetTxPosHeight(txindex.pos); if (nHeight + GetDisplayExpirationDepth(nHeight) - pindexBest->nHeight <= 0) continue; // Expired } else nHeight = NameTableEntry::NAME_UNCONFIRMED; // get last active name only std::map< std::vector<unsigned char>, NameTableEntry >::iterator mi = vNamesO.find(vchName); if (mi != vNamesO.end() && !NameTableEntry::CompareHeight(mi->second.nHeight, nHeight)) continue; std::string strAddress = ""; GetNameAddress(tx, strAddress); vNamesO[vchName] = NameTableEntry(stringFromVch(vchName), stringFromVch(vchValue), strAddress, nHeight, fTransferred); } } // Add existing names BOOST_FOREACH(const PAIRTYPE(std::vector<unsigned char>, NameTableEntry)& item, vNamesO) if (!item.second.transferred) cachedNameTable.append(item.second); // Add pending names (name_new) BOOST_FOREACH(const PAIRTYPE(std::vector<unsigned char>, PreparedNameFirstUpdate)& item, mapMyNameFirstUpdate) { std::string strAddress = ""; GetNameAddress(item.second.wtx, strAddress); cachedNameTable.append(NameTableEntry(stringFromVch(item.first), stringFromVch(item.second.vchData), strAddress, NameTableEntry::NAME_NEW)); } // qLowerBound() and qUpperBound() require our cachedNameTable list to be sorted in asc order qSort(cachedNameTable.begin(), cachedNameTable.end(), NameTableEntryLessThan()); } void refreshName(const std::vector<unsigned char> &inName) { NameTableEntry nameObj(stringFromVch(inName), std::string(), std::string(), NameTableEntry::NAME_NON_EXISTING); CRITICAL_BLOCK(cs_main) CRITICAL_BLOCK(wallet->cs_mapWallet) { CTxIndex txindex; uint256 hash; CTxDB txdb("r"); CTransaction tx; std::vector<unsigned char> vchName; std::vector<unsigned char> vchValue; int nHeight; BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, wallet->mapWallet) { hash = item.second.GetHash(); bool fConfirmed; bool fTransferred = false; if (!txdb.ReadDiskTx(hash, tx, txindex)) { tx = item.second; fConfirmed = false; } else fConfirmed = true; if (tx.nVersion != NAMECOIN_TX_VERSION) continue; // name if (!GetNameOfTx(tx, vchName) || vchName != inName) continue; // value if (!GetValueOfNameTx(tx, vchValue)) continue; if (!hooks->IsMine(wallet->mapWallet[tx.GetHash()])) fTransferred = true; // height if (fConfirmed) { nHeight = GetTxPosHeight(txindex.pos); if (nHeight + GetDisplayExpirationDepth(nHeight) - pindexBest->nHeight <= 0) continue; // Expired } else nHeight = NameTableEntry::NAME_UNCONFIRMED; // get last active name only if (!NameTableEntry::CompareHeight(nameObj.nHeight, nHeight)) continue; std::string strAddress = ""; GetNameAddress(tx, strAddress); nameObj.value = QString::fromStdString(stringFromVch(vchValue)); nameObj.address = QString::fromStdString(strAddress); nameObj.nHeight = nHeight; nameObj.transferred = fTransferred; } } // Transferred name is not ours anymore - remove it from the table if (nameObj.transferred) nameObj.nHeight = NameTableEntry::NAME_NON_EXISTING; // Find name in model QList<NameTableEntry>::iterator lower = qLowerBound( cachedNameTable.begin(), cachedNameTable.end(), nameObj.name, NameTableEntryLessThan()); QList<NameTableEntry>::iterator upper = qUpperBound( cachedNameTable.begin(), cachedNameTable.end(), nameObj.name, NameTableEntryLessThan()); bool inModel = (lower != upper); if (inModel) { // In model - update or delete if (nameObj.nHeight != NameTableEntry::NAME_NON_EXISTING) updateEntry(nameObj, CT_UPDATED); else updateEntry(nameObj, CT_DELETED); } else { // Not in model - add or do nothing if (nameObj.nHeight != NameTableEntry::NAME_NON_EXISTING) updateEntry(nameObj, CT_NEW); } } void updateEntry(const NameTableEntry &nameObj, int status, int *outNewRowIndex = NULL) { updateEntry(nameObj.name, nameObj.value, nameObj.address, nameObj.nHeight, status, outNewRowIndex); } void updateEntry(const QString &name, const QString &value, const QString &address, int nHeight, int status, int *outNewRowIndex = NULL) { // Find name in model QList<NameTableEntry>::iterator lower = qLowerBound( cachedNameTable.begin(), cachedNameTable.end(), name, NameTableEntryLessThan()); QList<NameTableEntry>::iterator upper = qUpperBound( cachedNameTable.begin(), cachedNameTable.end(), name, NameTableEntryLessThan()); int lowerIndex = (lower - cachedNameTable.begin()); int upperIndex = (upper - cachedNameTable.begin()); bool inModel = (lower != upper); switch(status) { case CT_NEW: if (inModel) { if (outNewRowIndex) { *outNewRowIndex = parent->index(lowerIndex, 0).row(); // HACK: ManageNamesPage uses this to ensure updating and get selected row, // so we do not write warning into the log in this case } else OutputDebugStringF("Warning: NameTablePriv::updateEntry: Got CT_NOW, but entry is already in model\n"); break; } parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex); cachedNameTable.insert(lowerIndex, NameTableEntry(name, value, address, nHeight)); parent->endInsertRows(); if (outNewRowIndex) *outNewRowIndex = parent->index(lowerIndex, 0).row(); break; case CT_UPDATED: if (!inModel) { OutputDebugStringF("Warning: NameTablePriv::updateEntry: Got CT_UPDATED, but entry is not in model\n"); break; } lower->name = name; lower->value = value; lower->address = address; lower->nHeight = nHeight; parent->emitDataChanged(lowerIndex); break; case CT_DELETED: if (!inModel) { OutputDebugStringF("Warning: NameTablePriv::updateEntry: Got CT_DELETED, but entry is not in model\n"); break; } parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1); cachedNameTable.erase(lower, upper); parent->endRemoveRows(); break; } } int size() { return cachedNameTable.size(); } NameTableEntry *index(int idx) { if (idx >= 0 && idx < cachedNameTable.size()) { return &cachedNameTable[idx]; } else { return NULL; } } }; NameTableModel::NameTableModel(CWallet *wallet, WalletModel *parent) : QAbstractTableModel(parent), walletModel(parent), wallet(wallet), priv(0), cachedNumBlocks(0) { columns << tr("Name") << tr("Value") << tr("Address") << tr("Expires in"); priv = new NameTablePriv(wallet, this); priv->refreshNameTable(); QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(updateExpiration())); timer->start(MODEL_UPDATE_DELAY); } NameTableModel::~NameTableModel() { delete priv; } void NameTableModel::updateExpiration() { if (nBestHeight != cachedNumBlocks) { LOCK(cs_main); cachedNumBlocks = nBestHeight; // Blocks came in since last poll. // Delete expired names for (int i = 0, n = priv->size(); i < n; i++) { NameTableEntry *item = priv->index(i); if (!item->HeightValid()) continue; // Currently, unconfirmed names do not expire in the table int nHeight = item->nHeight; if (nHeight + GetDisplayExpirationDepth(nHeight) - pindexBest->nHeight <= 0) { priv->updateEntry(item->name, item->value, item->address, item->nHeight, CT_DELETED); // Data array changed - restart scan n = priv->size(); i = -1; } } // Invalidate expiration counter for all rows. // Qt is smart enough to only actually request the data for the // visible rows. emit dataChanged(index(0, ExpiresIn), index(priv->size()-1, ExpiresIn)); } } void NameTableModel::updateTransaction(const QString &hash, int status) { uint256 hash256; hash256.SetHex(hash.toStdString()); CTransaction tx; { LOCK(wallet->cs_wallet); // Find transaction in wallet std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash256); if (mi == wallet->mapWallet.end()) return; // Not our transaction tx = mi->second; } std::vector<unsigned char> vchName; if (!GetNameOfTx(tx, vchName)) return; // Non-name transaction priv->refreshName(vchName); } int NameTableModel::rowCount(const QModelIndex &parent /* = QModelIndex()*/) const { Q_UNUSED(parent); return priv->size(); } int NameTableModel::columnCount(const QModelIndex &parent /* = QModelIndex()*/) const { Q_UNUSED(parent); return columns.length(); } QVariant NameTableModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); NameTableEntry *rec = static_cast<NameTableEntry*>(index.internalPointer()); if (role == Qt::DisplayRole || role == Qt::EditRole) { switch (index.column()) { case Name: return rec->name; case Value: return rec->value; case Address: return rec->address; case ExpiresIn: if (!rec->HeightValid()) { if (rec->nHeight == NameTableEntry::NAME_NEW) return QString("pending (new)"); return QString("pending (update)"); } else return rec->nHeight + GetDisplayExpirationDepth(rec->nHeight) - pindexBest->nHeight; } } else if (role == Qt::TextAlignmentRole) return column_alignments[index.column()]; else if (role == Qt::FontRole) { QFont font; if (index.column() == Address) font = GUIUtil::bitcoinAddressFont(); return font; } return QVariant(); } QVariant NameTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal) { if (role == Qt::DisplayRole) { return columns[section]; } else if (role == Qt::TextAlignmentRole) { return column_alignments[section]; } else if (role == Qt::ToolTipRole) { switch (section) { case Name: return tr("Name registered using Namecoin."); case Value: return tr("Data associated with the name."); case Address: return tr("Namecoin address to which the name is registered."); case ExpiresIn: return tr("Number of blocks, after which the name will expire. Update name to renew it."); } } } return QVariant(); } Qt::ItemFlags NameTableModel::flags(const QModelIndex &index) const { if (!index.isValid()) return 0; //NameTableEntry *rec = static_cast<NameTableEntry*>(index.internalPointer()); return Qt::ItemIsSelectable | Qt::ItemIsEnabled; } QModelIndex NameTableModel::index(int row, int column, const QModelIndex &parent /* = QModelIndex()*/) const { Q_UNUSED(parent); NameTableEntry *data = priv->index(row); if (data) { return createIndex(row, column, priv->index(row)); } else { return QModelIndex(); } } void NameTableModel::updateEntry(const QString &name, const QString &value, const QString &address, int nHeight, int status, int *outNewRowIndex /* = NULL*/) { priv->updateEntry(name, value, address, nHeight, status, outNewRowIndex); } void NameTableModel::emitDataChanged(int idx) { emit dataChanged(index(idx, 0), index(idx, columns.length()-1)); } <commit_msg>Make the GUI a little less sluggish. (Port from Huntercoin, thanks Domob).<commit_after>#include "nametablemodel.h" #include "guiutil.h" #include "walletmodel.h" #include "guiconstants.h" #include "../headers.h" #include "../namecoin.h" #include "ui_interface.h" #include <QTimer> extern std::map<std::vector<unsigned char>, PreparedNameFirstUpdate> mapMyNameFirstUpdate; // ExpiresIn column is right-aligned as it contains numbers static int column_alignments[] = { Qt::AlignLeft|Qt::AlignVCenter, // Name Qt::AlignLeft|Qt::AlignVCenter, // Value Qt::AlignLeft|Qt::AlignVCenter, // Address Qt::AlignRight|Qt::AlignVCenter // Expires in }; struct NameTableEntryLessThan { bool operator()(const NameTableEntry &a, const NameTableEntry &b) const { return a.name < b.name; } bool operator()(const NameTableEntry &a, const QString &b) const { return a.name < b; } bool operator()(const QString &a, const NameTableEntry &b) const { return a < b.name; } }; // Returns true if new height is better /*static*/ bool NameTableEntry::CompareHeight(int nOldHeight, int nNewHeight) { if (nOldHeight == NAME_NON_EXISTING) return true; // We use optimistic way, assuming that unconfirmed transaction will eventually become confirmed, // so we update the name in the table immediately. Ideally we need a separate way of displaying // unconfirmed names (e.g. grayed out) if (nNewHeight == NAME_UNCONFIRMED) return true; // Here we rely on the fact that dummy height values are always negative return nNewHeight > nOldHeight; } // Private implementation class NameTablePriv { public: CWallet *wallet; QList<NameTableEntry> cachedNameTable; NameTableModel *parent; NameTablePriv(CWallet *wallet, NameTableModel *parent): wallet(wallet), parent(parent) {} void refreshNameTable() { cachedNameTable.clear(); std::map< std::vector<unsigned char>, NameTableEntry > vNamesO; CRITICAL_BLOCK(cs_main) CRITICAL_BLOCK(wallet->cs_mapWallet) { CTxIndex txindex; uint256 hash; CTxDB txdb("r"); CTransaction tx; std::vector<unsigned char> vchName; std::vector<unsigned char> vchValue; int nHeight; BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, wallet->mapWallet) { hash = item.second.GetHash(); bool fConfirmed; bool fTransferred = false; // TODO: Maybe CMerkleTx::GetDepthInMainChain() would be faster? if (!txdb.ReadDiskTx(hash, tx, txindex)) { tx = item.second; fConfirmed = false; } else fConfirmed = true; if (tx.nVersion != NAMECOIN_TX_VERSION) continue; // name if (!GetNameOfTx(tx, vchName)) continue; // value if (!GetValueOfNameTx(tx, vchValue)) continue; if (!hooks->IsMine(wallet->mapWallet[tx.GetHash()])) fTransferred = true; // height if (fConfirmed) { nHeight = GetTxPosHeight(txindex.pos); if (nHeight + GetDisplayExpirationDepth(nHeight) - pindexBest->nHeight <= 0) continue; // Expired } else nHeight = NameTableEntry::NAME_UNCONFIRMED; // get last active name only std::map< std::vector<unsigned char>, NameTableEntry >::iterator mi = vNamesO.find(vchName); if (mi != vNamesO.end() && !NameTableEntry::CompareHeight(mi->second.nHeight, nHeight)) continue; std::string strAddress = ""; GetNameAddress(tx, strAddress); vNamesO[vchName] = NameTableEntry(stringFromVch(vchName), stringFromVch(vchValue), strAddress, nHeight, fTransferred); } } // Add existing names BOOST_FOREACH(const PAIRTYPE(std::vector<unsigned char>, NameTableEntry)& item, vNamesO) if (!item.second.transferred) cachedNameTable.append(item.second); // Add pending names (name_new) BOOST_FOREACH(const PAIRTYPE(std::vector<unsigned char>, PreparedNameFirstUpdate)& item, mapMyNameFirstUpdate) { std::string strAddress = ""; GetNameAddress(item.second.wtx, strAddress); cachedNameTable.append(NameTableEntry(stringFromVch(item.first), stringFromVch(item.second.vchData), strAddress, NameTableEntry::NAME_NEW)); } // qLowerBound() and qUpperBound() require our cachedNameTable list to be sorted in asc order qSort(cachedNameTable.begin(), cachedNameTable.end(), NameTableEntryLessThan()); } void refreshName(const std::vector<unsigned char> &inName) { NameTableEntry nameObj(stringFromVch(inName), std::string(), std::string(), NameTableEntry::NAME_NON_EXISTING); CRITICAL_BLOCK(cs_main) CRITICAL_BLOCK(wallet->cs_mapWallet) { CTxIndex txindex; uint256 hash; CTxDB txdb("r"); CTransaction tx; std::vector<unsigned char> vchName; std::vector<unsigned char> vchValue; int nHeight; BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, wallet->mapWallet) { hash = item.second.GetHash(); bool fConfirmed; bool fTransferred = false; if (!txdb.ReadDiskTx(hash, tx, txindex)) { tx = item.second; fConfirmed = false; } else fConfirmed = true; if (tx.nVersion != NAMECOIN_TX_VERSION) continue; // name if (!GetNameOfTx(tx, vchName) || vchName != inName) continue; // value if (!GetValueOfNameTx(tx, vchValue)) continue; if (!hooks->IsMine(wallet->mapWallet[tx.GetHash()])) fTransferred = true; // height if (fConfirmed) { nHeight = GetTxPosHeight(txindex.pos); if (nHeight + GetDisplayExpirationDepth(nHeight) - pindexBest->nHeight <= 0) continue; // Expired } else nHeight = NameTableEntry::NAME_UNCONFIRMED; // get last active name only if (!NameTableEntry::CompareHeight(nameObj.nHeight, nHeight)) continue; std::string strAddress = ""; GetNameAddress(tx, strAddress); nameObj.value = QString::fromStdString(stringFromVch(vchValue)); nameObj.address = QString::fromStdString(strAddress); nameObj.nHeight = nHeight; nameObj.transferred = fTransferred; } } // Transferred name is not ours anymore - remove it from the table if (nameObj.transferred) nameObj.nHeight = NameTableEntry::NAME_NON_EXISTING; // Find name in model QList<NameTableEntry>::iterator lower = qLowerBound( cachedNameTable.begin(), cachedNameTable.end(), nameObj.name, NameTableEntryLessThan()); QList<NameTableEntry>::iterator upper = qUpperBound( cachedNameTable.begin(), cachedNameTable.end(), nameObj.name, NameTableEntryLessThan()); bool inModel = (lower != upper); if (inModel) { // In model - update or delete if (nameObj.nHeight != NameTableEntry::NAME_NON_EXISTING) updateEntry(nameObj, CT_UPDATED); else updateEntry(nameObj, CT_DELETED); } else { // Not in model - add or do nothing if (nameObj.nHeight != NameTableEntry::NAME_NON_EXISTING) updateEntry(nameObj, CT_NEW); } } void updateEntry(const NameTableEntry &nameObj, int status, int *outNewRowIndex = NULL) { updateEntry(nameObj.name, nameObj.value, nameObj.address, nameObj.nHeight, status, outNewRowIndex); } void updateEntry(const QString &name, const QString &value, const QString &address, int nHeight, int status, int *outNewRowIndex = NULL) { // Find name in model QList<NameTableEntry>::iterator lower = qLowerBound( cachedNameTable.begin(), cachedNameTable.end(), name, NameTableEntryLessThan()); QList<NameTableEntry>::iterator upper = qUpperBound( cachedNameTable.begin(), cachedNameTable.end(), name, NameTableEntryLessThan()); int lowerIndex = (lower - cachedNameTable.begin()); int upperIndex = (upper - cachedNameTable.begin()); bool inModel = (lower != upper); switch(status) { case CT_NEW: if (inModel) { if (outNewRowIndex) { *outNewRowIndex = parent->index(lowerIndex, 0).row(); // HACK: ManageNamesPage uses this to ensure updating and get selected row, // so we do not write warning into the log in this case } else OutputDebugStringF("Warning: NameTablePriv::updateEntry: Got CT_NOW, but entry is already in model\n"); break; } parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex); cachedNameTable.insert(lowerIndex, NameTableEntry(name, value, address, nHeight)); parent->endInsertRows(); if (outNewRowIndex) *outNewRowIndex = parent->index(lowerIndex, 0).row(); break; case CT_UPDATED: if (!inModel) { OutputDebugStringF("Warning: NameTablePriv::updateEntry: Got CT_UPDATED, but entry is not in model\n"); break; } lower->name = name; lower->value = value; lower->address = address; lower->nHeight = nHeight; parent->emitDataChanged(lowerIndex); break; case CT_DELETED: if (!inModel) { OutputDebugStringF("Warning: NameTablePriv::updateEntry: Got CT_DELETED, but entry is not in model\n"); break; } parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1); cachedNameTable.erase(lower, upper); parent->endRemoveRows(); break; } } int size() { return cachedNameTable.size(); } NameTableEntry *index(int idx) { if (idx >= 0 && idx < cachedNameTable.size()) { return &cachedNameTable[idx]; } else { return NULL; } } }; NameTableModel::NameTableModel(CWallet *wallet, WalletModel *parent) : QAbstractTableModel(parent), walletModel(parent), wallet(wallet), priv(0), cachedNumBlocks(0) { columns << tr("Name") << tr("Value") << tr("Address") << tr("Expires in"); priv = new NameTablePriv(wallet, this); priv->refreshNameTable(); QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(updateExpiration())); timer->start(MODEL_UPDATE_DELAY); } NameTableModel::~NameTableModel() { delete priv; } void NameTableModel::updateExpiration() { if (nBestHeight != cachedNumBlocks) { CTryCriticalBlock criticalBlock(cs_main); if (!criticalBlock.Entered()) return; cachedNumBlocks = nBestHeight; // Blocks came in since last poll. // Delete expired names for (int i = 0, n = priv->size(); i < n; i++) { NameTableEntry *item = priv->index(i); if (!item->HeightValid()) continue; // Currently, unconfirmed names do not expire in the table int nHeight = item->nHeight; if (nHeight + GetDisplayExpirationDepth(nHeight) - pindexBest->nHeight <= 0) { priv->updateEntry(item->name, item->value, item->address, item->nHeight, CT_DELETED); // Data array changed - restart scan n = priv->size(); i = -1; } } // Invalidate expiration counter for all rows. // Qt is smart enough to only actually request the data for the // visible rows. emit dataChanged(index(0, ExpiresIn), index(priv->size()-1, ExpiresIn)); } } void NameTableModel::updateTransaction(const QString &hash, int status) { uint256 hash256; hash256.SetHex(hash.toStdString()); CTransaction tx; { LOCK(wallet->cs_wallet); // Find transaction in wallet std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash256); if (mi == wallet->mapWallet.end()) return; // Not our transaction tx = mi->second; } std::vector<unsigned char> vchName; if (!GetNameOfTx(tx, vchName)) return; // Non-name transaction priv->refreshName(vchName); } int NameTableModel::rowCount(const QModelIndex &parent /* = QModelIndex()*/) const { Q_UNUSED(parent); return priv->size(); } int NameTableModel::columnCount(const QModelIndex &parent /* = QModelIndex()*/) const { Q_UNUSED(parent); return columns.length(); } QVariant NameTableModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); NameTableEntry *rec = static_cast<NameTableEntry*>(index.internalPointer()); if (role == Qt::DisplayRole || role == Qt::EditRole) { switch (index.column()) { case Name: return rec->name; case Value: return rec->value; case Address: return rec->address; case ExpiresIn: if (!rec->HeightValid()) { if (rec->nHeight == NameTableEntry::NAME_NEW) return QString("pending (new)"); return QString("pending (update)"); } else return rec->nHeight + GetDisplayExpirationDepth(rec->nHeight) - pindexBest->nHeight; } } else if (role == Qt::TextAlignmentRole) return column_alignments[index.column()]; else if (role == Qt::FontRole) { QFont font; if (index.column() == Address) font = GUIUtil::bitcoinAddressFont(); return font; } return QVariant(); } QVariant NameTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal) { if (role == Qt::DisplayRole) { return columns[section]; } else if (role == Qt::TextAlignmentRole) { return column_alignments[section]; } else if (role == Qt::ToolTipRole) { switch (section) { case Name: return tr("Name registered using Namecoin."); case Value: return tr("Data associated with the name."); case Address: return tr("Namecoin address to which the name is registered."); case ExpiresIn: return tr("Number of blocks, after which the name will expire. Update name to renew it."); } } } return QVariant(); } Qt::ItemFlags NameTableModel::flags(const QModelIndex &index) const { if (!index.isValid()) return 0; //NameTableEntry *rec = static_cast<NameTableEntry*>(index.internalPointer()); return Qt::ItemIsSelectable | Qt::ItemIsEnabled; } QModelIndex NameTableModel::index(int row, int column, const QModelIndex &parent /* = QModelIndex()*/) const { Q_UNUSED(parent); NameTableEntry *data = priv->index(row); if (data) { return createIndex(row, column, priv->index(row)); } else { return QModelIndex(); } } void NameTableModel::updateEntry(const QString &name, const QString &value, const QString &address, int nHeight, int status, int *outNewRowIndex /* = NULL*/) { priv->updateEntry(name, value, address, nHeight, status, outNewRowIndex); } void NameTableModel::emitDataChanged(int idx) { emit dataChanged(index(idx, 0), index(idx, columns.length()-1)); } <|endoftext|>
<commit_before>#include "sendcoinsentry.h" #include "ui_sendcoinsentry.h" #include "guiutil.h" #include "bitcoinunits.h" #include "addressbookpage.h" #include "walletmodel.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include <QApplication> #include <QClipboard> SendCoinsEntry::SendCoinsEntry(QWidget *parent) : QFrame(parent), ui(new Ui::SendCoinsEntry), model(0) { ui->setupUi(this); #ifdef Q_WS_MAC ui->payToLayout->setSpacing(4); #endif #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book")); ui->payTo->setPlaceholderText(tr("Enter a KittehCoin address (starts with D)")); #endif setFocusPolicy(Qt::TabFocus); setFocusProxy(ui->payTo); GUIUtil::setupAddressWidget(ui->payTo, this); } SendCoinsEntry::~SendCoinsEntry() { delete ui; } void SendCoinsEntry::on_pasteButton_clicked() { // Paste text from clipboard into recipient field ui->payTo->setText(QApplication::clipboard()->text()); } void SendCoinsEntry::on_addressBookButton_clicked() { if(!model) return; AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if(dlg.exec()) { ui->payTo->setText(dlg.getReturnValue()); ui->payAmount->setFocus(); } } void SendCoinsEntry::on_payTo_textChanged(const QString &address) { if(!model) return; // Fill in label from address book, if address has an associated label QString associatedLabel = model->getAddressTableModel()->labelForAddress(address); if(!associatedLabel.isEmpty()) ui->addAsLabel->setText(associatedLabel); } void SendCoinsEntry::setModel(WalletModel *model) { this->model = model; if(model && model->getOptionsModel()) connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); clear(); } void SendCoinsEntry::setRemoveEnabled(bool enabled) { ui->deleteButton->setEnabled(enabled); } void SendCoinsEntry::clear() { ui->payTo->clear(); ui->addAsLabel->clear(); ui->payAmount->clear(); ui->payTo->setFocus(); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void SendCoinsEntry::on_deleteButton_clicked() { emit removeEntry(this); } bool SendCoinsEntry::validate() { // Check input validity bool retval = true; if(!ui->payAmount->validate()) { retval = false; } else { if(ui->payAmount->value() <= 0) { // Cannot send 0 coins or less ui->payAmount->setValid(false); retval = false; } } if(!ui->payTo->hasAcceptableInput() || (model && !model->validateAddress(ui->payTo->text()))) { ui->payTo->setValid(false); retval = false; } return retval; } SendCoinsRecipient SendCoinsEntry::getValue() { SendCoinsRecipient rv; rv.address = ui->payTo->text(); rv.label = ui->addAsLabel->text(); rv.amount = ui->payAmount->value(); return rv; } QWidget *SendCoinsEntry::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, ui->payTo); QWidget::setTabOrder(ui->payTo, ui->addressBookButton); QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton); QWidget::setTabOrder(ui->pasteButton, ui->deleteButton); QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel); return ui->payAmount->setupTabChain(ui->addAsLabel); } void SendCoinsEntry::setValue(const SendCoinsRecipient &value) { ui->payTo->setText(value.address); ui->addAsLabel->setText(value.label); ui->payAmount->setValue(value.amount); } bool SendCoinsEntry::isClear() { return ui->payTo->text().isEmpty(); } void SendCoinsEntry::setFocus() { ui->payTo->setFocus(); } void SendCoinsEntry::updateDisplayUnit() { if(model && model->getOptionsModel()) { // Update payAmount with the current unit ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); } } <commit_msg>UI : Remove ref to D in send coin<commit_after>#include "sendcoinsentry.h" #include "ui_sendcoinsentry.h" #include "guiutil.h" #include "bitcoinunits.h" #include "addressbookpage.h" #include "walletmodel.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include <QApplication> #include <QClipboard> SendCoinsEntry::SendCoinsEntry(QWidget *parent) : QFrame(parent), ui(new Ui::SendCoinsEntry), model(0) { ui->setupUi(this); #ifdef Q_WS_MAC ui->payToLayout->setSpacing(4); #endif #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book")); ui->payTo->setPlaceholderText(tr("Enter a KittehCoin address (starts with K)")); #endif setFocusPolicy(Qt::TabFocus); setFocusProxy(ui->payTo); GUIUtil::setupAddressWidget(ui->payTo, this); } SendCoinsEntry::~SendCoinsEntry() { delete ui; } void SendCoinsEntry::on_pasteButton_clicked() { // Paste text from clipboard into recipient field ui->payTo->setText(QApplication::clipboard()->text()); } void SendCoinsEntry::on_addressBookButton_clicked() { if(!model) return; AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if(dlg.exec()) { ui->payTo->setText(dlg.getReturnValue()); ui->payAmount->setFocus(); } } void SendCoinsEntry::on_payTo_textChanged(const QString &address) { if(!model) return; // Fill in label from address book, if address has an associated label QString associatedLabel = model->getAddressTableModel()->labelForAddress(address); if(!associatedLabel.isEmpty()) ui->addAsLabel->setText(associatedLabel); } void SendCoinsEntry::setModel(WalletModel *model) { this->model = model; if(model && model->getOptionsModel()) connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); clear(); } void SendCoinsEntry::setRemoveEnabled(bool enabled) { ui->deleteButton->setEnabled(enabled); } void SendCoinsEntry::clear() { ui->payTo->clear(); ui->addAsLabel->clear(); ui->payAmount->clear(); ui->payTo->setFocus(); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void SendCoinsEntry::on_deleteButton_clicked() { emit removeEntry(this); } bool SendCoinsEntry::validate() { // Check input validity bool retval = true; if(!ui->payAmount->validate()) { retval = false; } else { if(ui->payAmount->value() <= 0) { // Cannot send 0 coins or less ui->payAmount->setValid(false); retval = false; } } if(!ui->payTo->hasAcceptableInput() || (model && !model->validateAddress(ui->payTo->text()))) { ui->payTo->setValid(false); retval = false; } return retval; } SendCoinsRecipient SendCoinsEntry::getValue() { SendCoinsRecipient rv; rv.address = ui->payTo->text(); rv.label = ui->addAsLabel->text(); rv.amount = ui->payAmount->value(); return rv; } QWidget *SendCoinsEntry::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, ui->payTo); QWidget::setTabOrder(ui->payTo, ui->addressBookButton); QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton); QWidget::setTabOrder(ui->pasteButton, ui->deleteButton); QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel); return ui->payAmount->setupTabChain(ui->addAsLabel); } void SendCoinsEntry::setValue(const SendCoinsRecipient &value) { ui->payTo->setText(value.address); ui->addAsLabel->setText(value.label); ui->payAmount->setValue(value.amount); } bool SendCoinsEntry::isClear() { return ui->payTo->text().isEmpty(); } void SendCoinsEntry::setFocus() { ui->payTo->setFocus(); } void SendCoinsEntry::updateDisplayUnit() { if(model && model->getOptionsModel()) { // Update payAmount with the current unit ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); } } <|endoftext|>
<commit_before>/* * (C) Copyright 2013 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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. * */ #include <config.h> #include "media_config.hpp" #include <glibmm.h> #include <fstream> #include <iostream> #include <boost/filesystem.hpp> #include <version.hpp> #include <ModuleLoader.hpp> #include <glib/gstdio.h> #include <ftw.h> #include "services/Service.hpp" #include "services/ServiceFactory.hpp" #include <SignalHandler.hpp> #define GST_CAT_DEFAULT kurento_media_server GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "KurentoMediaServer" #define ENV_VAR "GST_PLUGIN_PATH" #define FILE_PERMISIONS (S_IRWXU | S_IRWXG | S_IRWXO) #define ROOT_TMP_DIR "/tmp/kms" #define TMP_DIR_TEMPLATE ROOT_TMP_DIR "/XXXXXX" #define CERTTOOL_TEMPLATE "autoCerttool.tmpl" #define CERT_KEY_PEM_FILE "autoCertkey.pem" using namespace ::kurento; using boost::shared_ptr; using namespace boost::filesystem; using ::Glib::KeyFile; using ::Glib::KeyFileFlags; static Service *service; GstSDPMessage *sdpPattern; std::string stunServerAddress, pemCertificate; __pid_t pid; gint stunServerPort; Glib::RefPtr<Glib::MainLoop> loop = Glib::MainLoop::create (); static gchar *conf_file; static gchar *tmp_dir; static GOptionEntry entries[] = { { "conf-file", 'f', 0, G_OPTION_ARG_FILENAME, &conf_file, "Configuration file", NULL }, {NULL} }; Glib::RefPtr<Glib::IOChannel> channel; static void check_port (int port) { if (port <= 0 || port > G_MAXUSHORT) { throw Glib::KeyFileError (Glib::KeyFileError::PARSE, "Invalid value"); } } static gchar * read_entire_file (const gchar *file_name) { gchar *data; long f_size; FILE *fp; fp = fopen (file_name, "r"); if (fp == NULL) { return NULL; } fseek (fp, 0, SEEK_END); f_size = ftell (fp); fseek (fp, 0, SEEK_SET); data = (gchar *) g_malloc0 (f_size + 1); if (fread (data, 1, f_size, fp) != (size_t) f_size) { GST_ERROR ("Error reading file"); } fclose (fp); data[f_size] = '\0'; return data; } static GstSDPMessage * load_sdp_pattern (Glib::KeyFile &configFile, const std::string &confFileName) { GstSDPResult result; GstSDPMessage *sdp_pattern = NULL; gchar *sdp_pattern_text; std::string sdp_pattern_file_name; GST_DEBUG ("Load SDP Pattern"); result = gst_sdp_message_new (&sdp_pattern); if (result != GST_SDP_OK) { GST_ERROR ("Error creating sdp message"); return NULL; } sdp_pattern_file_name = configFile.get_string (SERVER_GROUP, SDP_PATTERN_KEY); boost::filesystem::path p (confFileName.c_str () ); sdp_pattern_file_name.insert (0, "/"); sdp_pattern_file_name.insert (0, p.parent_path ().c_str() ); sdp_pattern_text = read_entire_file (sdp_pattern_file_name.c_str () ); if (sdp_pattern_text == NULL) { GST_ERROR ("Error reading SDP pattern file"); gst_sdp_message_free (sdp_pattern); return NULL; } result = gst_sdp_message_parse_buffer ( (const guint8 *) sdp_pattern_text, -1, sdp_pattern); g_free (sdp_pattern_text); if (result != GST_SDP_OK) { GST_ERROR ("Error parsing SDP config pattern"); gst_sdp_message_free (sdp_pattern); return NULL; } return sdp_pattern; } static void configure_kurento_media_server (KeyFile &configFile, const std::string &file_name) { gchar *sdpMessageText = NULL; try { sdpPattern = load_sdp_pattern (configFile, file_name); GST_DEBUG ("SDP: \n%s", sdpMessageText = gst_sdp_message_as_text (sdpPattern) ); g_free (sdpMessageText); } catch (const Glib::KeyFileError &err) { GST_ERROR ("%s", err.what ().c_str () ); GST_WARNING ("Wrong codec configuration, communication won't be possible"); } try { service = ServiceFactory::create_service (configFile); } catch (std::exception &e) { GST_ERROR ("Error creating service: %s", e.what() ); exit (1); } catch (Glib::Exception &e) { GST_ERROR ("Error creating service: %s", e.what().c_str() ); exit (1); } } static gchar * generate_certkey_pem_file (const gchar *dir) { gchar *cmd, *template_path, *pem_path; int ret; if (dir == NULL) { return NULL; } pem_path = g_strdup_printf ("%s/%s", dir, CERT_KEY_PEM_FILE); cmd = g_strconcat ("/bin/sh -c \"certtool --generate-privkey --outfile ", pem_path, "\"", NULL); ret = system (cmd); g_free (cmd); if (ret == -1) { goto err; } template_path = g_strdup_printf ("%s/%s", dir, CERTTOOL_TEMPLATE); cmd = g_strconcat ("/bin/sh -c \"echo 'organization = kurento' > ", template_path, " && certtool --generate-self-signed --load-privkey ", pem_path, " --template ", template_path, " >> ", pem_path, " 2>/dev/null\"", NULL); g_free (template_path); ret = system (cmd); g_free (cmd); if (ret == -1) { goto err; } return pem_path; err: GST_ERROR ("Error while generating certificate file"); g_free (pem_path); return NULL; } static void configure_web_rtc_end_point (KeyFile &configFile, const std::string &file_name) { gint port; std::string pem_certificate_file_name; try { stunServerAddress = configFile.get_string (WEB_RTC_END_POINT_GROUP, WEB_RTC_END_POINT_STUN_SERVER_ADDRESS_KEY); } catch (const Glib::KeyFileError &err) { GST_WARNING ("Setting default address %s to stun server", STUN_SERVER_ADDRESS); stunServerAddress = STUN_SERVER_ADDRESS; } try { port = configFile.get_integer (WEB_RTC_END_POINT_GROUP, WEB_RTC_END_POINT_STUN_SERVER_PORT_KEY); check_port (port); stunServerPort = port; } catch (const Glib::KeyFileError &err) { GST_WARNING ("Setting default port %d to stun server", STUN_SERVER_PORT); stunServerPort = STUN_SERVER_PORT; } try { pem_certificate_file_name = configFile.get_string (WEB_RTC_END_POINT_GROUP, WEB_RTC_END_POINT_PEM_CERTIFICATE_KEY); boost::filesystem::path p (file_name.c_str () ); pem_certificate_file_name.insert (0, "/"); pem_certificate_file_name.insert (0, p.parent_path ().c_str() ); pemCertificate = pem_certificate_file_name.c_str(); } catch (const Glib::KeyFileError &err) { //generate a valid pem certificate gchar t[] = TMP_DIR_TEMPLATE; gchar *autogenerated_pem_file; g_mkdir_with_parents (ROOT_TMP_DIR, FILE_PERMISIONS); tmp_dir = g_strdup (g_mkdtemp_full (t, FILE_PERMISIONS) ); autogenerated_pem_file = generate_certkey_pem_file (tmp_dir); if (autogenerated_pem_file == NULL ) { pemCertificate = ""; GST_ERROR ("%s", err.what ().c_str () ); GST_WARNING ("Could not create Pem Certificate or Pem Certificate not found"); } else { pemCertificate = autogenerated_pem_file; } } } static void load_config (const std::string &file_name) { KeyFile configFile; pid = getpid(); GST_INFO ("Reading configuration from: %s", file_name.c_str () ); try { configFile.load_from_file (file_name, KeyFileFlags::KEY_FILE_KEEP_COMMENTS | KeyFileFlags::KEY_FILE_KEEP_TRANSLATIONS); } catch (const Glib::Error &ex) { GST_ERROR ("Error loading configuration: %s", ex.what ().c_str () ); throw ex; } /* parse options so as to configure services */ configure_kurento_media_server (configFile, file_name); configure_web_rtc_end_point (configFile, file_name); GST_INFO ("Configuration loaded successfully"); } static void signal_handler (uint32_t signo) { static unsigned int __terminated = 0; switch (signo) { case SIGINT: case SIGTERM: if (__terminated == 0) { GST_DEBUG ("Terminating."); loop->quit (); } __terminated = 1; break; case SIGPIPE: GST_DEBUG ("Ignore sigpipe signal"); break; case SIGSEGV: GST_DEBUG ("Segmentation fault. Aborting process execution"); abort (); default: break; } } static int delete_file (const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) { int rv = g_remove (fpath); if (rv) { GST_WARNING ("Error deleting file: %s. %s", fpath, strerror (errno) ); } return rv; } static void remove_recursive (const gchar *path) { nftw (path, delete_file, 64, FTW_DEPTH | FTW_PHYS); } static void deleteCertificate () { // Only parent process can delete certificate if (pid != getpid() ) { return; } if (tmp_dir != NULL) { remove_recursive (tmp_dir); g_free (tmp_dir); } } static void check_if_plugins_are_available () { GstPlugin *plugin = gst_plugin_load_by_name ("kurento"); if (plugin == NULL) { g_printerr ("Kurento plugin not found, try adding the plugins route with " "--gst-plugin-path parameter. See help (--help-gst) " "for more info\n"); exit (1); } g_clear_object (&plugin); } int main (int argc, char **argv) { sigset_t mask; std::shared_ptr <SignalHandler> signalHandler; GError *error = NULL; GOptionContext *context; gchar *oldEnv, *newEnv; Glib::init(); oldEnv = getenv (ENV_VAR); if (oldEnv == NULL) { newEnv = g_strdup_printf ("%s", PLUGIN_PATH); } else { newEnv = g_strdup_printf ("%s:%s", oldEnv, PLUGIN_PATH); } setenv (ENV_VAR, newEnv, 1); g_free (newEnv); gst_init (&argc, &argv); GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); context = g_option_context_new (""); g_option_context_add_main_entries (context, entries, NULL); g_option_context_add_group (context, gst_init_get_option_group () ); if (!g_option_context_parse (context, &argc, &argv, &error) ) { g_printerr ("option parsing failed: %s\n", error->message); g_option_context_free (context); g_error_free (error); exit (1); } g_option_context_free (context); check_if_plugins_are_available (); /* Install our signal handler */ sigemptyset (&mask); sigaddset (&mask, SIGINT); sigaddset (&mask, SIGTERM); sigaddset (&mask, SIGSEGV); sigaddset (&mask, SIGPIPE); signalHandler = std::shared_ptr <SignalHandler> (new SignalHandler (mask, signal_handler) ); GST_INFO ("Kmsc version: %s", get_version () ); if (!conf_file) { load_config (DEFAULT_CONFIG_FILE); } else { load_config ( (std::string) conf_file); } /* Start service */ service->start (); loop->run (); signalHandler.reset(); deleteCertificate (); service->stop(); delete service; return 0; } <commit_msg>Use a different temporal directory for each instance<commit_after>/* * (C) Copyright 2013 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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. * */ #include <config.h> #include "media_config.hpp" #include <glibmm.h> #include <fstream> #include <iostream> #include <boost/filesystem.hpp> #include <version.hpp> #include <ModuleLoader.hpp> #include <glib/gstdio.h> #include <ftw.h> #include "services/Service.hpp" #include "services/ServiceFactory.hpp" #include <SignalHandler.hpp> #define GST_CAT_DEFAULT kurento_media_server GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "KurentoMediaServer" #define ENV_VAR "GST_PLUGIN_PATH" #define FILE_PERMISIONS (S_IRWXU | S_IRWXG | S_IRWXO) #define TMP_DIR_TEMPLATE "/tmp/kms_XXXXXX" #define CERTTOOL_TEMPLATE "autoCerttool.tmpl" #define CERT_KEY_PEM_FILE "autoCertkey.pem" using namespace ::kurento; using boost::shared_ptr; using namespace boost::filesystem; using ::Glib::KeyFile; using ::Glib::KeyFileFlags; static Service *service; GstSDPMessage *sdpPattern; std::string stunServerAddress, pemCertificate; __pid_t pid; gint stunServerPort; Glib::RefPtr<Glib::MainLoop> loop = Glib::MainLoop::create (); static gchar *conf_file; static gchar *tmp_dir; static GOptionEntry entries[] = { { "conf-file", 'f', 0, G_OPTION_ARG_FILENAME, &conf_file, "Configuration file", NULL }, {NULL} }; Glib::RefPtr<Glib::IOChannel> channel; static void check_port (int port) { if (port <= 0 || port > G_MAXUSHORT) { throw Glib::KeyFileError (Glib::KeyFileError::PARSE, "Invalid value"); } } static gchar * read_entire_file (const gchar *file_name) { gchar *data; long f_size; FILE *fp; fp = fopen (file_name, "r"); if (fp == NULL) { return NULL; } fseek (fp, 0, SEEK_END); f_size = ftell (fp); fseek (fp, 0, SEEK_SET); data = (gchar *) g_malloc0 (f_size + 1); if (fread (data, 1, f_size, fp) != (size_t) f_size) { GST_ERROR ("Error reading file"); } fclose (fp); data[f_size] = '\0'; return data; } static GstSDPMessage * load_sdp_pattern (Glib::KeyFile &configFile, const std::string &confFileName) { GstSDPResult result; GstSDPMessage *sdp_pattern = NULL; gchar *sdp_pattern_text; std::string sdp_pattern_file_name; GST_DEBUG ("Load SDP Pattern"); result = gst_sdp_message_new (&sdp_pattern); if (result != GST_SDP_OK) { GST_ERROR ("Error creating sdp message"); return NULL; } sdp_pattern_file_name = configFile.get_string (SERVER_GROUP, SDP_PATTERN_KEY); boost::filesystem::path p (confFileName.c_str () ); sdp_pattern_file_name.insert (0, "/"); sdp_pattern_file_name.insert (0, p.parent_path ().c_str() ); sdp_pattern_text = read_entire_file (sdp_pattern_file_name.c_str () ); if (sdp_pattern_text == NULL) { GST_ERROR ("Error reading SDP pattern file"); gst_sdp_message_free (sdp_pattern); return NULL; } result = gst_sdp_message_parse_buffer ( (const guint8 *) sdp_pattern_text, -1, sdp_pattern); g_free (sdp_pattern_text); if (result != GST_SDP_OK) { GST_ERROR ("Error parsing SDP config pattern"); gst_sdp_message_free (sdp_pattern); return NULL; } return sdp_pattern; } static void configure_kurento_media_server (KeyFile &configFile, const std::string &file_name) { gchar *sdpMessageText = NULL; try { sdpPattern = load_sdp_pattern (configFile, file_name); GST_DEBUG ("SDP: \n%s", sdpMessageText = gst_sdp_message_as_text (sdpPattern) ); g_free (sdpMessageText); } catch (const Glib::KeyFileError &err) { GST_ERROR ("%s", err.what ().c_str () ); GST_WARNING ("Wrong codec configuration, communication won't be possible"); } try { service = ServiceFactory::create_service (configFile); } catch (std::exception &e) { GST_ERROR ("Error creating service: %s", e.what() ); exit (1); } catch (Glib::Exception &e) { GST_ERROR ("Error creating service: %s", e.what().c_str() ); exit (1); } } static gchar * generate_certkey_pem_file (const gchar *dir) { gchar *cmd, *template_path, *pem_path; int ret; if (dir == NULL) { return NULL; } pem_path = g_strdup_printf ("%s/%s", dir, CERT_KEY_PEM_FILE); cmd = g_strconcat ("/bin/sh -c \"certtool --generate-privkey --outfile ", pem_path, "\"", NULL); ret = system (cmd); g_free (cmd); if (ret == -1) { goto err; } template_path = g_strdup_printf ("%s/%s", dir, CERTTOOL_TEMPLATE); cmd = g_strconcat ("/bin/sh -c \"echo 'organization = kurento' > ", template_path, " && certtool --generate-self-signed --load-privkey ", pem_path, " --template ", template_path, " >> ", pem_path, " 2>/dev/null\"", NULL); g_free (template_path); ret = system (cmd); g_free (cmd); if (ret == -1) { goto err; } return pem_path; err: GST_ERROR ("Error while generating certificate file"); g_free (pem_path); return NULL; } static void configure_web_rtc_end_point (KeyFile &configFile, const std::string &file_name) { gint port; std::string pem_certificate_file_name; try { stunServerAddress = configFile.get_string (WEB_RTC_END_POINT_GROUP, WEB_RTC_END_POINT_STUN_SERVER_ADDRESS_KEY); } catch (const Glib::KeyFileError &err) { GST_WARNING ("Setting default address %s to stun server", STUN_SERVER_ADDRESS); stunServerAddress = STUN_SERVER_ADDRESS; } try { port = configFile.get_integer (WEB_RTC_END_POINT_GROUP, WEB_RTC_END_POINT_STUN_SERVER_PORT_KEY); check_port (port); stunServerPort = port; } catch (const Glib::KeyFileError &err) { GST_WARNING ("Setting default port %d to stun server", STUN_SERVER_PORT); stunServerPort = STUN_SERVER_PORT; } try { pem_certificate_file_name = configFile.get_string (WEB_RTC_END_POINT_GROUP, WEB_RTC_END_POINT_PEM_CERTIFICATE_KEY); boost::filesystem::path p (file_name.c_str () ); pem_certificate_file_name.insert (0, "/"); pem_certificate_file_name.insert (0, p.parent_path ().c_str() ); pemCertificate = pem_certificate_file_name.c_str(); } catch (const Glib::KeyFileError &err) { //generate a valid pem certificate gchar t[] = TMP_DIR_TEMPLATE; gchar *autogenerated_pem_file; tmp_dir = g_strdup (g_mkdtemp_full (t, FILE_PERMISIONS) ); autogenerated_pem_file = generate_certkey_pem_file (tmp_dir); if (autogenerated_pem_file == NULL ) { pemCertificate = ""; GST_ERROR ("%s", err.what ().c_str () ); GST_WARNING ("Could not create Pem Certificate or Pem Certificate not found"); } else { pemCertificate = autogenerated_pem_file; } } } static void load_config (const std::string &file_name) { KeyFile configFile; pid = getpid(); GST_INFO ("Reading configuration from: %s", file_name.c_str () ); try { configFile.load_from_file (file_name, KeyFileFlags::KEY_FILE_KEEP_COMMENTS | KeyFileFlags::KEY_FILE_KEEP_TRANSLATIONS); } catch (const Glib::Error &ex) { GST_ERROR ("Error loading configuration: %s", ex.what ().c_str () ); throw ex; } /* parse options so as to configure services */ configure_kurento_media_server (configFile, file_name); configure_web_rtc_end_point (configFile, file_name); GST_INFO ("Configuration loaded successfully"); } static void signal_handler (uint32_t signo) { static unsigned int __terminated = 0; switch (signo) { case SIGINT: case SIGTERM: if (__terminated == 0) { GST_DEBUG ("Terminating."); loop->quit (); } __terminated = 1; break; case SIGPIPE: GST_DEBUG ("Ignore sigpipe signal"); break; case SIGSEGV: GST_DEBUG ("Segmentation fault. Aborting process execution"); abort (); default: break; } } static int delete_file (const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) { int rv = g_remove (fpath); if (rv) { GST_WARNING ("Error deleting file: %s. %s", fpath, strerror (errno) ); } return rv; } static void remove_recursive (const gchar *path) { nftw (path, delete_file, 64, FTW_DEPTH | FTW_PHYS); } static void deleteCertificate () { // Only parent process can delete certificate if (pid != getpid() ) { return; } if (tmp_dir != NULL) { remove_recursive (tmp_dir); g_free (tmp_dir); } } static void check_if_plugins_are_available () { GstPlugin *plugin = gst_plugin_load_by_name ("kurento"); if (plugin == NULL) { g_printerr ("Kurento plugin not found, try adding the plugins route with " "--gst-plugin-path parameter. See help (--help-gst) " "for more info\n"); exit (1); } g_clear_object (&plugin); } int main (int argc, char **argv) { sigset_t mask; std::shared_ptr <SignalHandler> signalHandler; GError *error = NULL; GOptionContext *context; gchar *oldEnv, *newEnv; Glib::init(); oldEnv = getenv (ENV_VAR); if (oldEnv == NULL) { newEnv = g_strdup_printf ("%s", PLUGIN_PATH); } else { newEnv = g_strdup_printf ("%s:%s", oldEnv, PLUGIN_PATH); } setenv (ENV_VAR, newEnv, 1); g_free (newEnv); gst_init (&argc, &argv); GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); context = g_option_context_new (""); g_option_context_add_main_entries (context, entries, NULL); g_option_context_add_group (context, gst_init_get_option_group () ); if (!g_option_context_parse (context, &argc, &argv, &error) ) { g_printerr ("option parsing failed: %s\n", error->message); g_option_context_free (context); g_error_free (error); exit (1); } g_option_context_free (context); check_if_plugins_are_available (); /* Install our signal handler */ sigemptyset (&mask); sigaddset (&mask, SIGINT); sigaddset (&mask, SIGTERM); sigaddset (&mask, SIGSEGV); sigaddset (&mask, SIGPIPE); signalHandler = std::shared_ptr <SignalHandler> (new SignalHandler (mask, signal_handler) ); GST_INFO ("Kmsc version: %s", get_version () ); if (!conf_file) { load_config (DEFAULT_CONFIG_FILE); } else { load_config ( (std::string) conf_file); } /* Start service */ service->start (); loop->run (); signalHandler.reset(); deleteCertificate (); service->stop(); delete service; return 0; } <|endoftext|>
<commit_before>#include <pybind11/pybind11.h> #include <pybind11/stl.h> #include "choices.hpp" #include "feature.hpp" #include "polymer.hpp" #include "simulation.hpp" #include "tracker.hpp" namespace py = pybind11; using namespace pybind11::literals; PYBIND11_MODULE(pinetree, m) { m.doc() = (R"doc( Python module ----------------------- .. currentmodule:: pysinthe.core )doc"); m.def("seed", &Random::seed, "Set a global seed for the simulation."); py::class_<SpeciesTracker>(m, "SpeciesTracker") .def("get_instance", SpeciesTracker::Instance, py::return_value_policy::reference) .def("increment", &SpeciesTracker::Increment); py::class_<Simulation, std::shared_ptr<Simulation>>( m, "Simulation", "Set up and run a gene expression simulation.") .def(py::init<int, int, double>(), "run_time"_a, "time_step"_a, "cell_volume"_a) .def_property("stop_time", (double (Simulation::*)()) & Simulation::stop_time, (void (Simulation::*)(double)) & Simulation::stop_time, "stop time of simulation") .def_property("time_step", (double (Simulation::*)()) & Simulation::time_step, (void (Simulation::*)(double)) & Simulation::time_step, "time step at which to output data") .def("add_reaction", &Simulation::AddReaction, "add a species-level reaction") .def("register_genome", &Simulation::RegisterGenome, "register a genome") .def("add_species", &Simulation::AddSpecies, "add species") .def("add_polymerase", &Simulation::AddPolymerase, "name"_a, "footprint"_a, "speed"_a, "copy_number"_a, "add a polymerase") .def("run", &Simulation::Run, "run the simulation"); // Binding for abtract Reaction so pybind11 doesn't complain when doing // conversions between Reaction and its child classes py::class_<Reaction, Reaction::Ptr>( m, "Reaction", "A generic Reaction designed to be extended."); py::class_<SpeciesReaction, Reaction, SpeciesReaction::Ptr>( m, "SpeciesReaction", "Define a species-level reaction.") .def(py::init<double, double, const std::vector<std::string> &, const std::vector<std::string> &>()); py::class_<Bind, Reaction, std::shared_ptr<Bind>>(m, "Bind").def( py::init<double, double, const std::string &, const Polymerase &>()); py::class_<Bridge, Reaction, std::shared_ptr<Bridge>>(m, "Bridge") .def(py::init<Polymer::Ptr>()); // Features and elements py::class_<Feature, std::shared_ptr<Feature>>(m, "Feature") .def_property("start", (int (Feature::*)()) & Feature::start, (void (Feature::*)(int)) & Feature::start) .def_property("stop", (int (Feature::*)()) & Feature::stop, (void (Feature::*)(int)) & Feature::stop) .def_property_readonly( "type", (const std::string &(Feature::*)() const) & Feature::type) .def_property_readonly( "name", (const std::string &(Feature::*)() const) & Feature::name); py::class_<Element, Feature, Element::Ptr>(m, "Element") .def_property("gene", (const std::string &(Element::*)() const) & Element::gene, (void (Element::*)(const std::string &)) & Element::gene); py::class_<Promoter, Element, Promoter::Ptr>(m, "Promoter") .def(py::init<const std::string &, int, int, const std::map<std::string, double> &>()); py::class_<Terminator, Element, Terminator::Ptr>(m, "Terminator") .def(py::init<const std::string &, int, int, const std::map<std::string, double> &>()) .def_property( "reading_frame", (int (Terminator::*)()) & Terminator::reading_frame, (void (Terminator::*)(int)) & Terminator::set_reading_frame); py::class_<Polymerase, Feature, Polymerase::Ptr>(m, "Polymerase") .def(py::init<const std::string &, int, int>()); // Polymers, genomes, and transcripts py::class_<Polymer, Polymer::Ptr>(m, "Polymer"); py::class_<Genome, Polymer, Genome::Ptr>(m, "Genome") .def(py::init<const std::string &, int>(), "name"_a, "length"_a) .def("add_mask", &Genome::AddMask, "start"_a, "interactions"_a) .def("add_weights", &Genome::AddWeights, "weights"_a) .def("add_promoter", &Genome::AddPromoter, "name"_a, "start"_a, "stop"_a, "interactions"_a) .def("add_terminator", &Genome::AddTerminator, "name"_a, "start"_a, "stop"_a, "efficiency"_a) .def("add_gene", &Genome::AddGene, "name"_a, "start"_a, "stop"_a, "rbs_start"_a, "rbs_stop"_a, "rbs_strength"_a); }<commit_msg>removed deprecated python bindings<commit_after>#include <pybind11/pybind11.h> #include <pybind11/stl.h> #include "choices.hpp" #include "feature.hpp" #include "polymer.hpp" #include "simulation.hpp" #include "tracker.hpp" namespace py = pybind11; using namespace pybind11::literals; PYBIND11_MODULE(pinetree, m) { m.doc() = (R"doc( Python module ----------------------- .. currentmodule:: pysinthe.core )doc"); m.def("seed", &Random::seed, "Set a global seed for the simulation."); py::class_<SpeciesTracker>(m, "SpeciesTracker") .def("get_instance", SpeciesTracker::Instance, py::return_value_policy::reference) .def("increment", &SpeciesTracker::Increment); py::class_<Simulation, std::shared_ptr<Simulation>>( m, "Simulation", "Set up and run a gene expression simulation.") .def(py::init<int, int, double>(), "run_time"_a, "time_step"_a, "cell_volume"_a) .def("add_reaction", &Simulation::AddReaction, "add a species-level reaction") .def("register_genome", &Simulation::RegisterGenome, "register a genome") .def("add_species", &Simulation::AddSpecies, "add species") .def("add_polymerase", &Simulation::AddPolymerase, "name"_a, "footprint"_a, "speed"_a, "copy_number"_a, "add a polymerase") .def("run", &Simulation::Run, "run the simulation"); // Polymers, genomes, and transcripts py::class_<Polymer, Polymer::Ptr>(m, "Polymer"); py::class_<Genome, Polymer, Genome::Ptr>(m, "Genome") .def(py::init<const std::string &, int>(), "name"_a, "length"_a) .def("add_mask", &Genome::AddMask, "start"_a, "interactions"_a) .def("add_weights", &Genome::AddWeights, "weights"_a) .def("add_promoter", &Genome::AddPromoter, "name"_a, "start"_a, "stop"_a, "interactions"_a) .def("add_terminator", &Genome::AddTerminator, "name"_a, "start"_a, "stop"_a, "efficiency"_a) .def("add_gene", &Genome::AddGene, "name"_a, "start"_a, "stop"_a, "rbs_start"_a, "rbs_stop"_a, "rbs_strength"_a); }<|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) 2016 Jan Kelling * * 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. */ ///\file ///\brief Base classes for making types observable or observe the lifetime of objects. #pragma once #include <vector> #include <algorithm> #include <atomic> #include <mutex> namespace nytl { class Observable; ///\ingroup utility ///Base class for classes that observe the lifetime of other Observeable objects. class Observer { friend class Observable; virtual void observeableDestruction(Observable&) = 0; }; ///\ingroup utility ///\brief Utility class to make the objects lifetime observable. ///\details Base class that can be derived from if the lifetime of objects of this class should be ///observeable by others. Also see nytl::Observer and nytl::ObservingPtr. class Observable { protected: std::vector<Observer*> observer_; std::mutex mutex_; public: ~Observable() { //no lock guard needed. Undefined behavior if destructor and accesing run at the same time for(auto& obs : observer_) obs->observeableDestruction(*this); } void addObserver(Observer& obs) { std::lock_guard<std::mutex> lock(mutex_); observer_.push_back(&obs); } bool removeObserver(Observer& obs) { std::lock_guard<std::mutex> lock(mutex_); return (observer_.cend() == std::remove(observer_.begin(), observer_.end(), &obs)); } bool moveObserver(Observer& oldone, Observer& newone) { std::lock_guard<std::mutex> lock(mutex_); auto it = std::find(observer_.begin(), observer_.end(), &oldone); if(it == observer_.cend()) return 0; *it = &newone; return 1; } }; ///\ingroup utility ///\brief Smart pointer class that observes the lifetime of its object. ///\details Basically a smart pointer that does always know, whether the object it points to is //alive or not. Does only work with objects of classes that are derived from nytl::Observeable. ///Semantics are related to std::unique_ptr. template <typename T> class ObservingPtr : public Observer { private: std::atomic<T*> object_ {nullptr}; virtual void observableDestruction(Observable&) override { object_ = nullptr; } public: ObservingPtr() = default; ObservingPtr(T* obj) : object_(obj) { if(object_) object_->addObserver(*this); } ObservingPtr(T& obj) : object_(&obj) { object_->addObserver(*this); } ~ObservingPtr(){ if(object_) object_->removeObserver(*this); } ObservingPtr(const ObservingPtr& other) : object_(other.object_) { object_->addObserver(*this); } ObservingPtr& operator=(const ObservingPtr& other) { reset(other.object_); return *this; } ObservingPtr(ObservingPtr&& other) noexcept : object_(other.object_) { if(object_) object_->moveObserver(other, *this); other.object_ = nullptr; } ObservingPtr& operator=(ObservingPtr&& other) noexcept { reset(); object_ = other.object_; if(object_) object_->moveObserver(other, *this); other.object_ = nullptr; return *this; } void reset(T* obj = nullptr) { if(obj) obj->addObserver(*this); if(object_) object_->removeObserver(*this); object_ = obj; } void reset(T& obj) { obj.addObserver(*this); if(object_) object_->removeObserver(*this); object_ = &obj; } T* get() { return object_; } T& operator*(){ return *object_; } const T& operator*() const { return *object_; } T* operator->(){ return object_; } const T* operator->() const { return object_; } operator bool() const { return (object_ != nullptr); } void swap(ObservingPtr& other) noexcept { if(object_) object_->moveObserver(*this, other); if(other.object_) other.object_->moveObserver(other, *this); std::swap(object_, other.object_); } }; } <commit_msg>fixed observe.hpp bug, removed thread safety (for now, wip)<commit_after>/* * The MIT License (MIT) * * Copyright (c) 2016 Jan Kelling * * 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. */ ///\file ///\brief Base classes for making types observable or observe the lifetime of objects. #pragma once #include <vector> #include <algorithm> #include <atomic> #include <mutex> namespace nytl { ///XXX: at the moment not threadsafe. Discussion needed whether this would make sense. class Observable; ///\ingroup utility ///Base class for classes that observe the lifetime of other Observeable objects. class Observer { friend class Observable; virtual void obsDestruction(Observable&) = 0; }; ///\ingroup utility ///\brief Utility class to make the objects lifetime observable. ///\details Base class that can be derived from if the lifetime of objects of this class should be ///observeable by others. Also see nytl::Observer and nytl::ObservingPtr. class Observable { protected: std::vector<Observer*> observer_; //std::mutex mutex_; public: ~Observable() { //no lock guard needed. Undefined behavior if destructor and accesing run at the same time for(auto& obs : observer_) obs->obsDestruction(*this); } void addObserver(Observer& obs) { //std::lock_guard<std::mutex> lock(mutex_); observer_.push_back(&obs); } bool removeObserver(Observer& obs) { //std::lock_guard<std::mutex> lock(mutex_); return (observer_.cend() == std::remove(observer_.begin(), observer_.end(), &obs)); } bool moveObserver(Observer& oldone, Observer& newone) { //std::lock_guard<std::mutex> lock(mutex_); auto it = std::find(observer_.begin(), observer_.end(), &oldone); if(it == observer_.cend()) return 0; *it = &newone; return 1; } }; ///\ingroup utility ///\brief Smart pointer class that observes the lifetime of its object. ///\details Basically a smart pointer that does always know, whether the object it points to is //alive or not. Does only work with objects of classes that are derived from nytl::Observeable. ///Semantics are related to std::unique_ptr. template <typename T> class ObservingPtr : public Observer { private: T* object_ {nullptr}; virtual void obsDestruction(Observable&) override { object_ = nullptr; } public: ObservingPtr() = default; ObservingPtr(T* obj) : object_(obj) { if(object_) object_->addObserver(*this); } ObservingPtr(T& obj) : object_(&obj) { object_->addObserver(*this); } ~ObservingPtr(){ if(object_) object_->removeObserver(*this); } ObservingPtr(const ObservingPtr& other) : object_(other.object_) { if(object_) object_->addObserver(*this); } ObservingPtr& operator=(const ObservingPtr& other) { reset(other.object_); return *this; } ObservingPtr(ObservingPtr&& other) noexcept : object_(other.object_) { if(object_) object_->moveObserver(other, *this); other.object_ = nullptr; } ObservingPtr& operator=(ObservingPtr&& other) noexcept { reset(); object_ = other.object_; if(object_) object_->moveObserver(other, *this); other.object_ = nullptr; return *this; } void reset(T* obj = nullptr) { if(obj) obj->addObserver(*this); if(object_) object_->removeObserver(*this); object_ = obj; } void reset(T& obj) { obj.addObserver(*this); if(object_) object_->removeObserver(*this); object_ = &obj; } T* get() const { return object_; } T& operator*(){ return *object_; } const T& operator*() const { return *object_; } T* operator->(){ return object_; } const T* operator->() const { return object_; } operator bool() const { return (object_ != nullptr); } void swap(ObservingPtr& other) noexcept { if(object_) object_->moveObserver(*this, other); if(other.object_) other.object_->moveObserver(other, *this); std::swap(object_, other.object_); } }; } <|endoftext|>
<commit_before>class RegisterClassDetails { public: private: BitSet _members; }; class RegisterClass { public: private: int _index; }; class ConstantClassDetails { public: bool matches(int c) { if (c < _minimum || c > _maximum) return false; return (c - _minimum) % _step == 0; } private: int _minimum; int _maximum; int _step; }; class ConstantClass { public: private: int _index; }; class Register { public: private: int _index; }; class BinaryMatcher { public: private: }; class InstructionPattern { public: bool matches(Byte* data) { } private: Array<BinaryMatcher> _matchers; Array<RegisterClass> _registerHoles; Array<ConstantClass> _constantHoles; }; class Instruction { public: private: InstructionPattern* _patter; Array<Register> _registers; Array<int> _constants; }; class MachineDescription { public: Array<InstructionPattern> _patterns; Array<RegisterClassDetails> _registerClassDetails; Array<ConstantClassDetails> _constantClassDetails; }; <commit_msg>More machine description<commit_after>class RegisterClassDetails { public: private: BitSet _members; }; class RegisterClass { public: private: int _index; }; class ConstantClassDetails { public: bool matches(int c) { if (c < _minimum || c > _maximum) return false; return (c - _minimum) % _step == 0; } private: int _minimum; int _maximum; int _step; }; class ConstantClass { public: private: int _index; }; class Register { public: private: int _index; }; class BinaryMatcher { public: private: }; class ConstantByteMatcher : public BinaryMatcher { public: private: Byte _match; }; class InstructionPattern { public: bool matches(Byte* data) { } private: Array<BinaryMatcher> _matchers; Array<RegisterClass> _registerHoles; Array<ConstantClass> _constantHoles; }; class Instruction { public: private: InstructionPattern* _patter; Array<Register> _registers; Array<int> _constants; }; class MachineDescription { public: Array<InstructionPattern> _patterns; Array<RegisterClassDetails> _registerClassDetails; Array<ConstantClassDetails> _constantClassDetails; }; <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: callbacks.hxx,v $ * * $Revision: 1.11 $ * * last change: $Author: rt $ $Date: 2003-12-01 12:03: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 EXPRESS 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 _XMLOFF_FORMS_CALLBACKS_HXX_ #define _XMLOFF_FORMS_CALLBACKS_HXX_ #ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_ #include <com/sun/star/container/XIndexAccess.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_SCRIPT_SCRIPTEVENTDESCRIPTOR_HPP_ #include <com/sun/star/script/ScriptEventDescriptor.hpp> #endif #ifndef _VOS_REF_HXX_ #include <vos/ref.hxx> #endif class SvXMLImport; class SvXMLExport; class SvXMLExportPropertyMapper; class SvXMLStyleContext; //......................................................................... namespace xmloff { //......................................................................... class OAttribute2Property; //===================================================================== //= IFormsExportContext //===================================================================== class IFormsExportContext { public: virtual SvXMLExport& getGlobalContext() = 0; virtual ::vos::ORef< SvXMLExportPropertyMapper > getStylePropertyMapper() = 0; /** steps through a collection and exports all children of this collection */ virtual void exportCollectionElements( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& _rxCollection) = 0; virtual ::rtl::OUString getObjectStyleName( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxObject ) = 0; }; //===================================================================== //= IControlIdMap //===================================================================== class IControlIdMap { public: /** register a control id */ virtual void registerControlId( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControl, const ::rtl::OUString& _rId) = 0; /** register references to a control. <p>In the XML representation, the control which is refered by others stores the ids of these other controls, but in "real life" :) the referring controls store the referred one as property.</p> <p>This method allows a referred control to announce to ids of the referring ones.</p> @param _rxControl the referred control @param _rReferringControls a (comma separated) list of control ids of referring controls */ virtual void registerControlReferences( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControl, const ::rtl::OUString& _rReferringControls) = 0; }; //===================================================================== //= IFormsImportContext //===================================================================== class IFormsImportContext { public: virtual IControlIdMap& getControlIdMap() = 0; virtual OAttribute2Property& getAttributeMap() = 0; virtual ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getServiceFactory() = 0; virtual SvXMLImport& getGlobalContext() = 0; virtual const SvXMLStyleContext* getStyleElement(const ::rtl::OUString& _rStyleName) const = 0; virtual void enterEventContext() = 0; virtual void leaveEventContext() = 0; /** applies the given number style to the given object */ virtual void applyControlNumberStyle( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControlModel, const ::rtl::OUString& _rControlNumerStyleName ) = 0; /** registers a control model for later binding to a spreadsheet cell value */ virtual void registerCellValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControlModel, const ::rtl::OUString& _rCellAddress ) = 0; /** registers a list-like control model for later binding to a spreadsheet cell range as list source */ virtual void registerCellRangeListSource( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControlModel, const ::rtl::OUString& _rCellRangeAddress ) = 0; }; //===================================================================== //= IEventAttacherManager //===================================================================== class IEventAttacherManager { public: virtual void registerEvents( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxElement, const ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >& _rEvents ) = 0; }; //===================================================================== //= IEventAttacher //===================================================================== class IEventAttacher { public: virtual void registerEvents( const ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >& _rEvents ) = 0; }; //......................................................................... } // namespace xmloff //......................................................................... #endif // _XMLOFF_FORMS_CALLBACKS_HXX_ /************************************************************************* * history: * $Log: not supported by cvs2svn $ * Revision 1.10.24.2 2003/11/24 15:00:21 obo * undo last change * * Revision 1.10 2003/10/21 08:38:06 obo * INTEGRATION: CWS formcelllinkage (1.9.160); FILE MERGED * 2003/10/01 09:55:17 fs 1.9.160.1: #i18994# merging the changes from the CWS fs002 * * Revision 1.9.160.1 2003/10/01 09:55:17 fs * #i18994# merging the changes from the CWS fs002 * * Revision 1.9.156.1 2003/09/25 14:28:35 fs * #18994# merging the changes from cws_srx645_fs002 branch * * Revision 1.9.152.1 2003/09/17 12:26:44 fs * #18999# #19367# persistence for cell value and cell range bindings * * Revision 1.9 2002/10/25 13:11:31 fs * #104402# new methods on the import context callback for importing column styles * * Revision 1.8 2002/10/25 07:35:35 fs * #104402# +IFormsExportContext::getObjectStyleName * * Revision 1.7 2001/02/01 09:46:47 fs * no own style handling anymore - the shape exporter is responsible for our styles now * * Revision 1.6 2001/01/24 09:34:10 fs * +IFormsImportContext::enter-/leaveEventContext * * Revision 1.5 2001/01/02 15:58:21 fs * event ex- & import * * Revision 1.4 2000/12/18 15:14:35 fs * some changes ... now exporting/importing styles * * Revision 1.3 2000/12/13 10:35:50 fs * included XPropertySet.hpp * * Revision 1.2 2000/12/12 12:00:37 fs * +IControlIdMap / +IFormsImportContext * * Revision 1.1 2000/11/17 19:01:13 fs * initial checkin - export and/or import the applications form layer * * * Revision 1.0 17.11.00 18:42:07 fs ************************************************************************/ <commit_msg>INTEGRATION: CWS eforms2 (1.11.28); FILE MERGED 2004/10/01 18:04:45 dvo 1.11.28.4: #i34802# load/save binding fir lists as form:xforms-list-source 2004/08/25 17:48:12 dvo 1.11.28.3: #i31958# load/save xforms:submission attribute on buttons 2004/03/18 17:38:14 dvo 1.11.28.2: #114856# continue XForms implementation (also remove define DVO_XFORMS) 2004/01/28 14:51:27 dvo 1.11.28.1: #114856# load xforms:bind attribute for form controls (use DVO_XFORMS define)<commit_after>/************************************************************************* * * $RCSfile: callbacks.hxx,v $ * * $Revision: 1.12 $ * * last change: $Author: obo $ $Date: 2004-11-16 10:08:41 $ * * 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 EXPRESS 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 _XMLOFF_FORMS_CALLBACKS_HXX_ #define _XMLOFF_FORMS_CALLBACKS_HXX_ #ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_ #include <com/sun/star/container/XIndexAccess.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_SCRIPT_SCRIPTEVENTDESCRIPTOR_HPP_ #include <com/sun/star/script/ScriptEventDescriptor.hpp> #endif #ifndef _VOS_REF_HXX_ #include <vos/ref.hxx> #endif class SvXMLImport; class SvXMLExport; class SvXMLExportPropertyMapper; class SvXMLStyleContext; //......................................................................... namespace xmloff { //......................................................................... class OAttribute2Property; //===================================================================== //= IFormsExportContext //===================================================================== class IFormsExportContext { public: virtual SvXMLExport& getGlobalContext() = 0; virtual ::vos::ORef< SvXMLExportPropertyMapper > getStylePropertyMapper() = 0; /** steps through a collection and exports all children of this collection */ virtual void exportCollectionElements( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& _rxCollection) = 0; virtual ::rtl::OUString getObjectStyleName( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxObject ) = 0; }; //===================================================================== //= IControlIdMap //===================================================================== class IControlIdMap { public: /** register a control id */ virtual void registerControlId( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControl, const ::rtl::OUString& _rId) = 0; /** register references to a control. <p>In the XML representation, the control which is refered by others stores the ids of these other controls, but in "real life" :) the referring controls store the referred one as property.</p> <p>This method allows a referred control to announce to ids of the referring ones.</p> @param _rxControl the referred control @param _rReferringControls a (comma separated) list of control ids of referring controls */ virtual void registerControlReferences( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControl, const ::rtl::OUString& _rReferringControls) = 0; }; //===================================================================== //= IFormsImportContext //===================================================================== class IFormsImportContext { public: virtual IControlIdMap& getControlIdMap() = 0; virtual OAttribute2Property& getAttributeMap() = 0; virtual ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getServiceFactory() = 0; virtual SvXMLImport& getGlobalContext() = 0; virtual const SvXMLStyleContext* getStyleElement(const ::rtl::OUString& _rStyleName) const = 0; virtual void enterEventContext() = 0; virtual void leaveEventContext() = 0; /** applies the given number style to the given object */ virtual void applyControlNumberStyle( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControlModel, const ::rtl::OUString& _rControlNumerStyleName ) = 0; /** registers a control model for later binding to a spreadsheet cell value */ virtual void registerCellValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControlModel, const ::rtl::OUString& _rCellAddress ) = 0; /** registers a list-like control model for later binding to a spreadsheet cell range as list source */ virtual void registerCellRangeListSource( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControlModel, const ::rtl::OUString& _rCellRangeAddress ) = 0; /** registers a control model for later binding to an XForms binding */ virtual void registerXFormsValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControlModel, const ::rtl::OUString& _rBindingID ) = 0; /** registers a control model for later binding an XForms list binding */ virtual void registerXFormsListBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControlModel, const ::rtl::OUString& _rBindingID ) = 0; /** registers a control model for later binding to an XForms submission */ virtual void registerXFormsSubmission( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControlModel, const ::rtl::OUString& _rBindingID ) = 0; }; //===================================================================== //= IEventAttacherManager //===================================================================== class IEventAttacherManager { public: virtual void registerEvents( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxElement, const ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >& _rEvents ) = 0; }; //===================================================================== //= IEventAttacher //===================================================================== class IEventAttacher { public: virtual void registerEvents( const ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >& _rEvents ) = 0; }; //......................................................................... } // namespace xmloff //......................................................................... #endif // _XMLOFF_FORMS_CALLBACKS_HXX_ /************************************************************************* * history: * $Log: not supported by cvs2svn $ * Revision 1.11.28.4 2004/10/01 18:04:45 dvo * #i34802# load/save binding fir lists as form:xforms-list-source * * Revision 1.11.28.3 2004/08/25 17:48:12 dvo * #i31958# load/save xforms:submission attribute on buttons * * Revision 1.11.28.2 2004/03/18 17:38:14 dvo * #114856# continue XForms implementation * (also remove define DVO_XFORMS) * * Revision 1.11.28.1 2004/01/28 14:51:27 dvo * #114856# load xforms:bind attribute for form controls * (use DVO_XFORMS define) * * Revision 1.11 2003/12/01 12:03:25 rt * INTEGRATION: CWS geordi2q09 (1.10.24); FILE MERGED * 2003/11/24 15:00:21 obo 1.10.24.2: undo last change * 2003/11/21 16:48:36 obo 1.10.24.1: #111934#: join CWS comboboxlink * * Revision 1.10.24.2 2003/11/24 15:00:21 obo * undo last change * * Revision 1.10 2003/10/21 08:38:06 obo * INTEGRATION: CWS formcelllinkage (1.9.160); FILE MERGED * 2003/10/01 09:55:17 fs 1.9.160.1: #i18994# merging the changes from the CWS fs002 * * Revision 1.9.160.1 2003/10/01 09:55:17 fs * #i18994# merging the changes from the CWS fs002 * * Revision 1.9.156.1 2003/09/25 14:28:35 fs * #18994# merging the changes from cws_srx645_fs002 branch * * Revision 1.9.152.1 2003/09/17 12:26:44 fs * #18999# #19367# persistence for cell value and cell range bindings * * Revision 1.9 2002/10/25 13:11:31 fs * #104402# new methods on the import context callback for importing column styles * * Revision 1.8 2002/10/25 07:35:35 fs * #104402# +IFormsExportContext::getObjectStyleName * * Revision 1.7 2001/02/01 09:46:47 fs * no own style handling anymore - the shape exporter is responsible for our styles now * * Revision 1.6 2001/01/24 09:34:10 fs * +IFormsImportContext::enter-/leaveEventContext * * Revision 1.5 2001/01/02 15:58:21 fs * event ex- & import * * Revision 1.4 2000/12/18 15:14:35 fs * some changes ... now exporting/importing styles * * Revision 1.3 2000/12/13 10:35:50 fs * included XPropertySet.hpp * * Revision 1.2 2000/12/12 12:00:37 fs * +IControlIdMap / +IFormsImportContext * * Revision 1.1 2000/11/17 19:01:13 fs * initial checkin - export and/or import the applications form layer * * * Revision 1.0 17.11.00 18:42:07 fs ************************************************************************/ <|endoftext|>
<commit_before>/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** rtspvideocapturer.cpp ** ** -------------------------------------------------------------------------*/ #ifdef HAVE_LIVE555 #include "webrtc/base/timeutils.h" #include "webrtc/base/logging.h" #include "webrtc/base/optional.h" #include "webrtc/modules/video_coding/h264_sprop_parameter_sets.h" #include "webrtc/api/video/i420_buffer.h" #include "webrtc/common_video/libyuv/include/webrtc_libyuv.h" #include "libyuv/convert.h" #include "rtspvideocapturer.h" uint8_t marker[] = { 0, 0, 0, 1}; RTSPVideoCapturer::RTSPVideoCapturer(const std::string & uri, int timeout, bool rtpovertcp) : m_connection(m_env, this, uri.c_str(), timeout, rtpovertcp, 1) { LOG(INFO) << "RTSPVideoCapturer" << uri ; m_h264 = h264_new(); } RTSPVideoCapturer::~RTSPVideoCapturer() { h264_free(m_h264); } bool RTSPVideoCapturer::onNewSession(const char* id,const char* media, const char* codec, const char* sdp) { LOG(INFO) << "RTSPVideoCapturer::onNewSession" << media << "/" << codec << " " << sdp; bool success = false; if ( (strcmp(media, "video") == 0) && (strcmp(codec, "H264") == 0) ) { m_codec = codec; const char* pattern="sprop-parameter-sets="; const char* sprop=strstr(sdp, pattern); if (sprop) { std::string sdpstr(sprop+strlen(pattern)); size_t pos = sdpstr.find_first_of(" \r\n"); if (pos != std::string::npos) { sdpstr.erase(pos); } webrtc::H264SpropParameterSets sprops; if (sprops.DecodeSprop(sdpstr)) { struct timeval presentationTime; timerclear(&presentationTime); std::vector<uint8_t> sps; sps.insert(sps.end(), marker, marker+sizeof(marker)); sps.insert(sps.end(), sprops.sps_nalu().begin(), sprops.sps_nalu().end()); onData(id, sps.data(), sps.size(), presentationTime); std::vector<uint8_t> pps; pps.insert(pps.end(), marker, marker+sizeof(marker)); pps.insert(pps.end(), sprops.pps_nalu().begin(), sprops.pps_nalu().end()); onData(id, pps.data(), pps.size(), presentationTime); } else { LOG(WARNING) << "Cannot decode SPS:" << sprop; } } success = true; } else if ( (strcmp(media, "video") == 0) && (strcmp(codec, "JPEG") == 0) ) { m_codec = codec; success = true; } return success; } bool RTSPVideoCapturer::onData(const char* id, unsigned char* buffer, ssize_t size, struct timeval presentationTime) { int64_t ts = presentationTime.tv_sec; ts = ts*1000 + presentationTime.tv_usec/1000; LOG(INFO) << "RTSPVideoCapturer:onData size:" << size << " ts:" << ts; int res = 0; if (m_codec == "H264") { int nal_start = 0; int nal_end = 0; find_nal_unit(buffer, size, &nal_start, &nal_end); read_nal_unit(m_h264, &buffer[nal_start], nal_end - nal_start); LOG(LS_VERBOSE) << "NAL:" << m_h264->nal->nal_unit_type; if (m_h264->nal->nal_unit_type == NAL_UNIT_TYPE_SPS) { LOG(LS_VERBOSE) << "===========================SPS"; m_cfg.clear(); m_cfg.insert(m_cfg.end(), buffer, buffer+size); unsigned int width = ((m_h264->sps->pic_width_in_mbs_minus1 +1)*16) - m_h264->sps->frame_crop_left_offset*2 - m_h264->sps->frame_crop_right_offset*2; unsigned int height= ((2 - m_h264->sps->frame_mbs_only_flag)* (m_h264->sps->pic_height_in_map_units_minus1 +1) * 16) - (m_h264->sps->frame_crop_top_offset * 2) - (m_h264->sps->frame_crop_bottom_offset * 2); unsigned int fps=25; LOG(LS_VERBOSE) << "=========set timing_info_present_flag:" << m_h264->sps->vui.timing_info_present_flag << " " << m_h264->sps->vui.time_scale << " " << m_h264->sps->vui.num_units_in_tick; if (m_decoder.get()) { if ( (GetCaptureFormat()->width != width) || (GetCaptureFormat()->height != height) ) { LOG(INFO) << "format changed => set format from " << GetCaptureFormat()->width << "x" << GetCaptureFormat()->height << " to " << width << "x" << height; m_decoder.reset(NULL); } } if (!m_decoder.get()) { LOG(INFO) << "=========set format " << width << "x" << height << " fps:" << fps; cricket::VideoFormat videoFormat(width, height, cricket::VideoFormat::FpsToInterval(fps), cricket::FOURCC_I420); SetCaptureFormat(&videoFormat); m_decoder.reset(m_factory.CreateVideoDecoder(webrtc::VideoCodecType::kVideoCodecH264)); webrtc::VideoCodec codec_settings; codec_settings.codecType = webrtc::VideoCodecType::kVideoCodecH264; m_decoder->InitDecode(&codec_settings,2); m_decoder->RegisterDecodeCompleteCallback(this); } } else if (m_h264->nal->nal_unit_type == NAL_UNIT_TYPE_PPS) { LOG(LS_VERBOSE) << "===========================PPS"; m_cfg.insert(m_cfg.end(), buffer, buffer+size); } else if (m_decoder.get()) { if (m_h264->nal->nal_unit_type == NAL_UNIT_TYPE_CODED_SLICE_IDR) { LOG(LS_VERBOSE) << "===========================IDR"; uint8_t buf[m_cfg.size() + size]; memcpy(buf, m_cfg.data(), m_cfg.size()); memcpy(buf+m_cfg.size(), buffer, size); webrtc::EncodedImage input_image(buf, sizeof(buf), sizeof(buf) + webrtc::EncodedImage::GetBufferPaddingBytes(webrtc::VideoCodecType::kVideoCodecH264)); input_image._completeFrame = true; input_image._frameType = webrtc::kVideoFrameKey; input_image._timeStamp = ts; input_image.capture_time_ms_ = ts; res = m_decoder->Decode(input_image, false, NULL); } else { LOG(LS_VERBOSE) << "===========================" << m_h264->nal->nal_unit_type; webrtc::EncodedImage input_image(buffer, size, size + webrtc::EncodedImage::GetBufferPaddingBytes(webrtc::VideoCodecType::kVideoCodecH264)); input_image._completeFrame = false; input_image._frameType = webrtc::kVideoFrameDelta; input_image._timeStamp = ts; input_image.capture_time_ms_ = ts; res = m_decoder->Decode(input_image, false, NULL); } } else { LOG(LS_ERROR) << "===========================onData no decoder"; res = -1; } } else if (m_codec == "JPEG") { int32_t width = 0; int32_t height = 0; if (libyuv::MJPGSize(buffer, size, &width, &height) == 0) { int stride_y = width; int stride_uv = (width + 1) / 2; rtc::scoped_refptr<webrtc::I420Buffer> I420buffer = webrtc::I420Buffer::Create(width, height, stride_y, stride_uv, stride_uv); const int conversionResult = ConvertToI420(webrtc::VideoType::kMJPEG, buffer, 0, 0, width, height, size, webrtc::kVideoRotation_0, I420buffer.get()); if (conversionResult >= 0) { webrtc::VideoFrame frame(I420buffer, 0, ts, webrtc::kVideoRotation_0); this->Decoded(frame); } else { LOG(LS_ERROR) << "===========================onData decoder error:" << conversionResult; } } else { LOG(LS_ERROR) << "===========================onData cannot JPEG dimension"; } } return (res == 0); } ssize_t RTSPVideoCapturer::onNewBuffer(unsigned char* buffer, ssize_t size) { ssize_t markerSize = 0; if (m_codec == "H264") { if (size > sizeof(marker)) { memcpy( buffer, marker, sizeof(marker) ); markerSize = sizeof(marker); } } return markerSize; } int32_t RTSPVideoCapturer::Decoded(webrtc::VideoFrame& decodedImage) { LOG(INFO) << "RTSPVideoCapturer::Decoded " << decodedImage.size() << " " << decodedImage.timestamp_us() << " " << decodedImage.timestamp() << " " << decodedImage.ntp_time_ms(); this->OnFrame(decodedImage, decodedImage.height(), decodedImage.width()); return true; } cricket::CaptureState RTSPVideoCapturer::Start(const cricket::VideoFormat& format) { SetCaptureFormat(&format); SetCaptureState(cricket::CS_RUNNING); rtc::Thread::Start(); return cricket::CS_RUNNING; } void RTSPVideoCapturer::Stop() { m_env.stop(); rtc::Thread::Stop(); SetCaptureFormat(NULL); SetCaptureState(cricket::CS_STOPPED); } void RTSPVideoCapturer::Run() { m_env.mainloop(); } bool RTSPVideoCapturer::GetPreferredFourccs(std::vector<unsigned int>* fourccs) { return true; } #endif <commit_msg>improve sdp parsing<commit_after>/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** rtspvideocapturer.cpp ** ** -------------------------------------------------------------------------*/ #ifdef HAVE_LIVE555 #include "webrtc/base/timeutils.h" #include "webrtc/base/logging.h" #include "webrtc/base/optional.h" #include "webrtc/modules/video_coding/h264_sprop_parameter_sets.h" #include "webrtc/api/video/i420_buffer.h" #include "webrtc/common_video/libyuv/include/webrtc_libyuv.h" #include "libyuv/convert.h" #include "rtspvideocapturer.h" uint8_t marker[] = { 0, 0, 0, 1}; RTSPVideoCapturer::RTSPVideoCapturer(const std::string & uri, int timeout, bool rtpovertcp) : m_connection(m_env, this, uri.c_str(), timeout, rtpovertcp, 1) { LOG(INFO) << "RTSPVideoCapturer" << uri ; m_h264 = h264_new(); } RTSPVideoCapturer::~RTSPVideoCapturer() { h264_free(m_h264); } bool RTSPVideoCapturer::onNewSession(const char* id,const char* media, const char* codec, const char* sdp) { LOG(INFO) << "RTSPVideoCapturer::onNewSession " << media << "/" << codec << " " << sdp; bool success = false; if ( (strcmp(media, "video") == 0) && (strcmp(codec, "H264") == 0) ) { m_codec = codec; const char* pattern="sprop-parameter-sets="; const char* sprop=strstr(sdp, pattern); if (sprop) { std::string sdpstr(sprop+strlen(pattern)); size_t pos = sdpstr.find_first_of(" ;\r\n"); if (pos != std::string::npos) { sdpstr.erase(pos); } webrtc::H264SpropParameterSets sprops; if (sprops.DecodeSprop(sdpstr)) { struct timeval presentationTime; timerclear(&presentationTime); std::vector<uint8_t> sps; sps.insert(sps.end(), marker, marker+sizeof(marker)); sps.insert(sps.end(), sprops.sps_nalu().begin(), sprops.sps_nalu().end()); onData(id, sps.data(), sps.size(), presentationTime); std::vector<uint8_t> pps; pps.insert(pps.end(), marker, marker+sizeof(marker)); pps.insert(pps.end(), sprops.pps_nalu().begin(), sprops.pps_nalu().end()); onData(id, pps.data(), pps.size(), presentationTime); } else { LOG(WARNING) << "Cannot decode SPS:" << sprop; } } success = true; } else if ( (strcmp(media, "video") == 0) && (strcmp(codec, "JPEG") == 0) ) { m_codec = codec; success = true; } return success; } bool RTSPVideoCapturer::onData(const char* id, unsigned char* buffer, ssize_t size, struct timeval presentationTime) { int64_t ts = presentationTime.tv_sec; ts = ts*1000 + presentationTime.tv_usec/1000; LOG(LS_VERBOSE) << "RTSPVideoCapturer:onData size:" << size << " ts:" << ts; int res = 0; if (m_codec == "H264") { int nal_start = 0; int nal_end = 0; find_nal_unit(buffer, size, &nal_start, &nal_end); read_nal_unit(m_h264, &buffer[nal_start], nal_end - nal_start); LOG(LS_VERBOSE) << "NAL:" << m_h264->nal->nal_unit_type; if (m_h264->nal->nal_unit_type == NAL_UNIT_TYPE_SPS) { LOG(LS_VERBOSE) << "===========================SPS"; m_cfg.clear(); m_cfg.insert(m_cfg.end(), buffer, buffer+size); unsigned int width = ((m_h264->sps->pic_width_in_mbs_minus1 +1)*16) - m_h264->sps->frame_crop_left_offset*2 - m_h264->sps->frame_crop_right_offset*2; unsigned int height= ((2 - m_h264->sps->frame_mbs_only_flag)* (m_h264->sps->pic_height_in_map_units_minus1 +1) * 16) - (m_h264->sps->frame_crop_top_offset * 2) - (m_h264->sps->frame_crop_bottom_offset * 2); unsigned int fps=25; LOG(LS_VERBOSE) << "=========set timing_info_present_flag:" << m_h264->sps->vui.timing_info_present_flag << " " << m_h264->sps->vui.time_scale << " " << m_h264->sps->vui.num_units_in_tick; if (m_decoder.get()) { if ( (GetCaptureFormat()->width != width) || (GetCaptureFormat()->height != height) ) { LOG(INFO) << "format changed => set format from " << GetCaptureFormat()->width << "x" << GetCaptureFormat()->height << " to " << width << "x" << height; m_decoder.reset(NULL); } } if (!m_decoder.get()) { LOG(INFO) << "=========set format " << width << "x" << height << " fps:" << fps; cricket::VideoFormat videoFormat(width, height, cricket::VideoFormat::FpsToInterval(fps), cricket::FOURCC_I420); SetCaptureFormat(&videoFormat); m_decoder.reset(m_factory.CreateVideoDecoder(webrtc::VideoCodecType::kVideoCodecH264)); webrtc::VideoCodec codec_settings; codec_settings.codecType = webrtc::VideoCodecType::kVideoCodecH264; m_decoder->InitDecode(&codec_settings,2); m_decoder->RegisterDecodeCompleteCallback(this); } } else if (m_h264->nal->nal_unit_type == NAL_UNIT_TYPE_PPS) { LOG(LS_VERBOSE) << "===========================PPS"; m_cfg.insert(m_cfg.end(), buffer, buffer+size); } else if (m_decoder.get()) { if (m_h264->nal->nal_unit_type == NAL_UNIT_TYPE_CODED_SLICE_IDR) { LOG(LS_VERBOSE) << "===========================IDR"; uint8_t buf[m_cfg.size() + size]; memcpy(buf, m_cfg.data(), m_cfg.size()); memcpy(buf+m_cfg.size(), buffer, size); webrtc::EncodedImage input_image(buf, sizeof(buf), sizeof(buf) + webrtc::EncodedImage::GetBufferPaddingBytes(webrtc::VideoCodecType::kVideoCodecH264)); input_image._completeFrame = true; input_image._frameType = webrtc::kVideoFrameKey; input_image._timeStamp = ts; input_image.capture_time_ms_ = ts; res = m_decoder->Decode(input_image, false, NULL); } else { LOG(LS_VERBOSE) << "===========================" << m_h264->nal->nal_unit_type; webrtc::EncodedImage input_image(buffer, size, size + webrtc::EncodedImage::GetBufferPaddingBytes(webrtc::VideoCodecType::kVideoCodecH264)); input_image._completeFrame = false; input_image._frameType = webrtc::kVideoFrameDelta; input_image._timeStamp = ts; input_image.capture_time_ms_ = ts; res = m_decoder->Decode(input_image, false, NULL); } } else { LOG(LS_ERROR) << "===========================onData no decoder"; res = -1; } } else if (m_codec == "JPEG") { int32_t width = 0; int32_t height = 0; if (libyuv::MJPGSize(buffer, size, &width, &height) == 0) { int stride_y = width; int stride_uv = (width + 1) / 2; rtc::scoped_refptr<webrtc::I420Buffer> I420buffer = webrtc::I420Buffer::Create(width, height, stride_y, stride_uv, stride_uv); const int conversionResult = ConvertToI420(webrtc::VideoType::kMJPEG, buffer, 0, 0, width, height, size, webrtc::kVideoRotation_0, I420buffer.get()); if (conversionResult >= 0) { webrtc::VideoFrame frame(I420buffer, ts, ts, webrtc::kVideoRotation_0); this->Decoded(frame); } else { LOG(LS_ERROR) << "===========================onData decoder error:" << conversionResult; } } else { LOG(LS_ERROR) << "===========================onData cannot JPEG dimension"; } } return (res == 0); } ssize_t RTSPVideoCapturer::onNewBuffer(unsigned char* buffer, ssize_t size) { ssize_t markerSize = 0; if (m_codec == "H264") { if (size > sizeof(marker)) { memcpy( buffer, marker, sizeof(marker) ); markerSize = sizeof(marker); } } return markerSize; } int32_t RTSPVideoCapturer::Decoded(webrtc::VideoFrame& decodedImage) { LOG(LS_VERBOSE) << "RTSPVideoCapturer::Decoded " << decodedImage.size() << " " << decodedImage.timestamp_us() << " " << decodedImage.timestamp() << " " << decodedImage.ntp_time_ms(); this->OnFrame(decodedImage, decodedImage.height(), decodedImage.width()); return true; } cricket::CaptureState RTSPVideoCapturer::Start(const cricket::VideoFormat& format) { SetCaptureFormat(&format); SetCaptureState(cricket::CS_RUNNING); rtc::Thread::Start(); return cricket::CS_RUNNING; } void RTSPVideoCapturer::Stop() { m_env.stop(); rtc::Thread::Stop(); SetCaptureFormat(NULL); SetCaptureState(cricket::CS_STOPPED); } void RTSPVideoCapturer::Run() { m_env.mainloop(); } bool RTSPVideoCapturer::GetPreferredFourccs(std::vector<unsigned int>* fourccs) { return true; } #endif <|endoftext|>
<commit_before>// Copyright (c) 2011-2013 Steinwurf ApS // 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 Steinwurf ApS 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 Steinwurf ApS 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. #pragma once #include <stdint.h> #include <cassert> #include <algorithm> #include "storage.hpp" #include "convert_endian.hpp" namespace sak { /// The idea behind the endian_stream is to provide a stream-like interface /// for accessing a fixed-size buffer. /// All complexity regarding endianness is encapsulated. class endian_stream { public: /// Creates an endian stream on top of a pre-allocated buffer of the /// specified size /// @param buffer a pointer to the buffer /// @param size the size of the buffer in bytes endian_stream(uint8_t* buffer, uint32_t size); /// Writes a value of the size of ValueType to the buffer /// @param value the value to write template<class ValueType> void write(ValueType value) { // Make sure there is enough space in the underlying buffer assert(m_size >= m_position + sizeof(ValueType)); // Write the value at the current position big_endian::put<ValueType>(value, &m_buffer[m_position]); // Advance the current position m_position += sizeof(ValueType); } /// Writes the contents of a sak::storage container to the buffer /// @param storage the storage to write void write(const mutable_storage& storage) { // Make sure there is enough space in the underlying buffer assert(m_size >= m_position + storage.m_size); // Copy the data to the buffer std::copy_n(storage.m_data, storage.m_size, &m_buffer[m_position]); // Advance the current position m_position += storage.m_size; } /// Reads from the buffer and moves the read position. /// @param value reference to the value to be read template<class ValueType> void read(ValueType& value) { // Make sure there is enough data to read in the underlying buffer assert(m_size >= m_position + sizeof(ValueType)); // Read the value at the current position value = big_endian::get<ValueType>(&m_buffer[m_position]); // Advance the current position m_position += sizeof(ValueType); } /// Reads data from the buffer to fill a mutable storage /// @param storage the storage to be filled void read(mutable_storage& storage) { // Make sure there is enough data to read in the underlying buffer assert(m_size >= m_position + storage.m_size); // Copy the data from the buffer to the storage std::copy_n(&m_buffer[m_position], storage.m_size, storage.m_data); // Advance the current position m_position += storage.m_size; } /// Gets the size of the buffer /// @return the size of the buffer uint32_t size() const; /// Gets the current read/write position of the buffer /// @return the current position uint32_t position() const; /// Changes the current read/write position of the buffer /// @param new_position the new position void seek(uint32_t new_position); private: /// Pointer to the buffer uint8_t* m_buffer; /// The size of the buffer uint32_t m_size; /// The current position uint32_t m_position; }; } <commit_msg>fix to the const storage problem<commit_after>// Copyright (c) 2011-2013 Steinwurf ApS // 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 Steinwurf ApS 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 Steinwurf ApS 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. #pragma once #include <stdint.h> #include <cassert> #include <algorithm> #include "storage.hpp" #include "convert_endian.hpp" namespace sak { /// The idea behind the endian_stream is to provide a stream-like interface /// for accessing a fixed-size buffer. /// All complexity regarding endianness is encapsulated. class endian_stream { public: /// Creates an endian stream on top of a pre-allocated buffer of the /// specified size /// @param buffer a pointer to the buffer /// @param size the size of the buffer in bytes endian_stream(uint8_t* buffer, uint32_t size); /// Writes a value of the size of ValueType to the buffer /// @param value the value to write template<class ValueType> void write(ValueType value) { // Make sure there is enough space in the underlying buffer assert(m_size >= m_position + sizeof(ValueType)); // Write the value at the current position big_endian::put<ValueType>(value, &m_buffer[m_position]); // Advance the current position m_position += sizeof(ValueType); } /// Writes the contents of a sak::storage container to the buffer /// @param storage the storage to write void write(const mutable_storage& storage) { write(const_storage(storage)); } /// Writes the contents of a sak::storage container to the buffer /// @param storage the storage to write void write(const const_storage& storage) { // Make sure there is enough space in the underlying buffer assert(m_size >= m_position + storage.m_size); // Copy the data to the buffer std::copy_n(storage.m_data, storage.m_size, &m_buffer[m_position]); // Advance the current position m_position += storage.m_size; } /// Reads from the buffer and moves the read position. /// @param value reference to the value to be read template<class ValueType> void read(ValueType& value) { // Make sure there is enough data to read in the underlying buffer assert(m_size >= m_position + sizeof(ValueType)); // Read the value at the current position value = big_endian::get<ValueType>(&m_buffer[m_position]); // Advance the current position m_position += sizeof(ValueType); } /// Reads data from the buffer to fill a mutable storage /// @param storage the storage to be filled void read(const mutable_storage& storage) { // Make sure there is enough data to read in the underlying buffer assert(m_size >= m_position + storage.m_size); // Copy the data from the buffer to the storage std::copy_n(&m_buffer[m_position], storage.m_size, storage.m_data); // Advance the current position m_position += storage.m_size; } /// Gets the size of the buffer /// @return the size of the buffer uint32_t size() const; /// Gets the current read/write position of the buffer /// @return the current position uint32_t position() const; /// Changes the current read/write position of the buffer /// @param new_position the new position void seek(uint32_t new_position); private: /// Pointer to the buffer uint8_t* m_buffer; /// The size of the buffer uint32_t m_size; /// The current position uint32_t m_position; }; } <|endoftext|>
<commit_before>// This file is part of Poseidon. // Copyleft 2022, LH_Mouse. All wrongs reserved. #include "../precompiled.ipp" #include "tcp_socket.hpp" #include "../static/async_logger.hpp" #include "../utils.hpp" #include <sys/socket.h> #include <netinet/tcp.h> namespace poseidon { TCP_Socket:: TCP_Socket(unique_posix_fd&& fd) : Abstract_Socket(::std::move(fd)) { // Use `TCP_NODELAY`. Errors are ignored. int ival = 1; ::setsockopt(this->fd(), IPPROTO_TCP, TCP_NODELAY, &ival, sizeof(ival)); } TCP_Socket:: TCP_Socket(const Socket_Address& addr) : Abstract_Socket(addr.family(), SOCK_STREAM, IPPROTO_TCP) { // Use `TCP_NODELAY`. Errors are ignored. int ival = 1; ::setsockopt(this->fd(), IPPROTO_TCP, TCP_NODELAY, &ival, sizeof(ival)); if((::connect(this->fd(), addr.addr(), addr.ssize()) != 0) && (errno != EINPROGRESS)) POSEIDON_THROW(( "Failed to initiate TCP connection to `$4`", "[`connect()` failed: $3]", "[TCP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno(), addr); } TCP_Socket:: ~TCP_Socket() { } void TCP_Socket:: do_abstract_socket_on_closed(int err) { POSEIDON_LOG_INFO(( "TCP connection to `$3` closed: $4", "[TCP socket `$1` (class `$2`)]"), this, typeid(*this), this->get_remote_address(), format_errno(err)); } void TCP_Socket:: do_abstract_socket_on_readable() { recursive_mutex::unique_lock io_lock; auto& queue = this->do_abstract_socket_lock_read_queue(io_lock); // Try getting some bytes from this socket. size_t datalen; try_io: queue.reserve(0xFFFFU); datalen = queue.capacity(); ::ssize_t r = ::recv(this->fd(), queue.mut_end(), datalen, 0); datalen = (size_t) r; if(r == 0) { // Shut the connection down. Semi-open connections are not supported. POSEIDON_LOG_INFO(("Closing TCP connection: remote = $1"), this->get_remote_address()); ::shutdown(this->fd(), SHUT_RDWR); return; } if(r < 0) { switch(errno) { case EINTR: goto try_io; #if EWOULDBLOCK != EAGAIN case EAGAIN: #endif case EWOULDBLOCK: return; } POSEIDON_THROW(( "Error reading TCP socket", "[`recv()` failed: $3]", "[TCP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno()); } // Accept these data. queue.accept(datalen); this->do_on_tcp_stream(queue); } void TCP_Socket:: do_abstract_socket_on_writable() { recursive_mutex::unique_lock io_lock; auto& queue = this->do_abstract_socket_lock_write_queue(io_lock); // Send some bytes from the write queue. size_t datalen; try_io: datalen = queue.size(); ::ssize_t r = 0; if(datalen != 0) { r = ::send(this->fd(), queue.begin(), datalen, 0); } datalen = (size_t) r; if(r < 0) { switch(errno) { case EINTR: goto try_io; #if EWOULDBLOCK != EAGAIN case EAGAIN: #endif case EWOULDBLOCK: return; } POSEIDON_THROW(( "Error writing TCP socket", "[`send()` failed: $3]", "[TCP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno()); } // Remove sent bytes from the write queue. queue.discard(datalen); // Deliver the establishment notification. if(ROCKET_UNEXPECT(this->do_set_established())) this->do_on_tcp_connected(); } void TCP_Socket:: do_abstract_socket_on_exception(exception& stdex) { this->quick_shut_down(); POSEIDON_LOG_WARN(( "TCP connection terminated due to exception: $3", "[TCP socket `$1` (class `$2`)]"), this, typeid(*this), stdex); } void TCP_Socket:: do_on_tcp_connected() { POSEIDON_LOG_INFO(( "TCP connection to `$3` established", "[TCP socket `$1` (class `$2`)]"), this, typeid(*this), this->get_remote_address()); } const cow_string& TCP_Socket:: get_remote_address() const { if(!this->m_peername_ready.load()) { plain_mutex::unique_lock lock(this->m_peername_mutex); // Try getting the address. Socket_Address addr; ::socklen_t addrlen = (::socklen_t) addr.capacity(); if(::getpeername(this->fd(), addr.mut_addr(), &addrlen) != 0) return this->m_peername = format_string("(error: $1)", format_errno()); // Cache the result. addr.set_size(addrlen); this->m_peername = addr.format(); this->m_peername_ready.store(true); } return this->m_peername; } bool TCP_Socket:: tcp_send(const char* data, size_t size) { if(size && !data) POSEIDON_THROW(( "Null data pointer", "[TCP socket `$1` (class `$2`)]"), this, typeid(*this)); // If this socket has been marked closed, fail immediately. if(this->socket_state() == socket_state_closed) return false; recursive_mutex::unique_lock io_lock; auto& queue = this->do_abstract_socket_lock_write_queue(io_lock); // Append data for sending. queue.putn(data, size); // Try writing once. This is essential for the edge-triggered epoll to work // reliably, because the level-triggered epoll does not check for `EPOLLOUT` by // default. If the packet has been sent anyway, discard it from the write queue. this->do_abstract_socket_on_writable(); return true; } bool TCP_Socket:: tcp_send(const linear_buffer& data) { return this->tcp_send(data.data(), data.size()); } bool TCP_Socket:: tcp_send(const cow_string& data) { return this->tcp_send(data.data(), data.size()); } bool TCP_Socket:: tcp_send(const string& data) { return this->tcp_send(data.data(), data.size()); } bool TCP_Socket:: tcp_shut_down() noexcept { return ::shutdown(this->fd(), SHUT_RDWR) == 0; } } // namespace poseidon <commit_msg>tcp_socket: Cleanup<commit_after>// This file is part of Poseidon. // Copyleft 2022, LH_Mouse. All wrongs reserved. #include "../precompiled.ipp" #include "tcp_socket.hpp" #include "../static/async_logger.hpp" #include "../utils.hpp" #include <sys/socket.h> #include <netinet/tcp.h> namespace poseidon { TCP_Socket:: TCP_Socket(unique_posix_fd&& fd) : Abstract_Socket(::std::move(fd)) { // Use `TCP_NODELAY`. Errors are ignored. int ival = 1; ::setsockopt(this->fd(), IPPROTO_TCP, TCP_NODELAY, &ival, sizeof(ival)); } TCP_Socket:: TCP_Socket(const Socket_Address& addr) : Abstract_Socket(addr.family(), SOCK_STREAM, IPPROTO_TCP) { // Use `TCP_NODELAY`. Errors are ignored. int ival = 1; ::setsockopt(this->fd(), IPPROTO_TCP, TCP_NODELAY, &ival, sizeof(ival)); if((::connect(this->fd(), addr.addr(), addr.ssize()) != 0) && (errno != EINPROGRESS)) POSEIDON_THROW(( "Failed to initiate TCP connection to `$4`", "[`connect()` failed: $3]", "[TCP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno(), addr); } TCP_Socket:: ~TCP_Socket() { } void TCP_Socket:: do_abstract_socket_on_closed(int err) { POSEIDON_LOG_INFO(( "TCP connection to `$3` closed: $4", "[TCP socket `$1` (class `$2`)]"), this, typeid(*this), this->get_remote_address(), format_errno(err)); } void TCP_Socket:: do_abstract_socket_on_readable() { recursive_mutex::unique_lock io_lock; auto& queue = this->do_abstract_socket_lock_read_queue(io_lock); ::ssize_t r; // Try getting some bytes from this socket. try_io: queue.reserve(0xFFFFU); r = ::recv(this->fd(), queue.mut_end(), queue.capacity(), 0); if(r == 0) { // Shut the connection down. Semi-open connections are not supported. POSEIDON_LOG_INFO(("Closing TCP connection: remote = $1"), this->get_remote_address()); ::shutdown(this->fd(), SHUT_RDWR); return; } if(r < 0) { switch(errno) { case EINTR: goto try_io; #if EWOULDBLOCK != EAGAIN case EAGAIN: #endif case EWOULDBLOCK: return; } POSEIDON_THROW(( "Error reading TCP socket", "[`recv()` failed: $3]", "[TCP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno()); } // Accept these data. queue.accept((size_t) r); this->do_on_tcp_stream(queue); } void TCP_Socket:: do_abstract_socket_on_writable() { recursive_mutex::unique_lock io_lock; auto& queue = this->do_abstract_socket_lock_write_queue(io_lock); ::ssize_t r; // Send some bytes from the write queue. try_io: r = 0; if(!queue.empty()) { r = ::send(this->fd(), queue.begin(), queue.size(), 0); if(r > 0) queue.discard((size_t) r); } if(r < 0) { switch(errno) { case EINTR: goto try_io; #if EWOULDBLOCK != EAGAIN case EAGAIN: #endif case EWOULDBLOCK: return; } POSEIDON_THROW(( "Error writing TCP socket", "[`send()` failed: $3]", "[TCP socket `$1` (class `$2`)]"), this, typeid(*this), format_errno()); } if(ROCKET_UNEXPECT(this->do_set_established())) { // Deliver the establishment notification. this->do_on_tcp_connected(); } } void TCP_Socket:: do_abstract_socket_on_exception(exception& stdex) { this->quick_shut_down(); POSEIDON_LOG_WARN(( "TCP connection terminated due to exception: $3", "[TCP socket `$1` (class `$2`)]"), this, typeid(*this), stdex); } void TCP_Socket:: do_on_tcp_connected() { POSEIDON_LOG_INFO(( "TCP connection to `$3` established", "[TCP socket `$1` (class `$2`)]"), this, typeid(*this), this->get_remote_address()); } const cow_string& TCP_Socket:: get_remote_address() const { if(!this->m_peername_ready.load()) { plain_mutex::unique_lock lock(this->m_peername_mutex); // Try getting the address. Socket_Address addr; ::socklen_t addrlen = (::socklen_t) addr.capacity(); if(::getpeername(this->fd(), addr.mut_addr(), &addrlen) != 0) return this->m_peername = format_string("(error: $1)", format_errno()); // Cache the result. addr.set_size(addrlen); this->m_peername = addr.format(); this->m_peername_ready.store(true); } return this->m_peername; } bool TCP_Socket:: tcp_send(const char* data, size_t size) { if(size && !data) POSEIDON_THROW(( "Null data pointer", "[TCP socket `$1` (class `$2`)]"), this, typeid(*this)); // If this socket has been marked closed, fail immediately. if(this->socket_state() == socket_state_closed) return false; recursive_mutex::unique_lock io_lock; auto& queue = this->do_abstract_socket_lock_write_queue(io_lock); // Append data for sending. queue.putn(data, size); // Try writing once. This is essential for the edge-triggered epoll to work // reliably, because the level-triggered epoll does not check for `EPOLLOUT` by // default. If the packet has been sent anyway, discard it from the write queue. this->do_abstract_socket_on_writable(); return true; } bool TCP_Socket:: tcp_send(const linear_buffer& data) { return this->tcp_send(data.data(), data.size()); } bool TCP_Socket:: tcp_send(const cow_string& data) { return this->tcp_send(data.data(), data.size()); } bool TCP_Socket:: tcp_send(const string& data) { return this->tcp_send(data.data(), data.size()); } bool TCP_Socket:: tcp_shut_down() noexcept { return ::shutdown(this->fd(), SHUT_RDWR) == 0; } } // namespace poseidon <|endoftext|>
<commit_before>/** @file sortable-serialise.cc * @brief Serialise floating point values to string which sort the same way. */ /* Copyright (C) 2007,2009,2015,2016 Olly Betts * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "sortable_serialise.h" #include <cfloat> #include <cmath> #include <cstring> #include <string> #include "cassert.h" // for ASSERT size_t sortable_serialise_(long double value, char * buf) { long double mantissa; int exponent; // Negative infinity. if (value < -LDBL_MAX) { return 0; } mantissa = frexpl(value, &exponent); /* Deal with zero specially. * * IEEE representation of long doubles uses 15 bits for the exponent, with a * bias of 16383. We bias this by subtracting 8, and non-IEEE * representations may allow higher exponents, so allow exponents down to * -32759 - if smaller exponents are possible anywhere, we underflow such * numbers to 0. */ if (mantissa == 0.0 || exponent < -(LDBL_MAX_EXP + LDBL_MAX_EXP - 1 - 8)) { *buf = '\x80'; return 1; } bool negative = (mantissa < 0); if (negative) { mantissa = -mantissa; } // Infinity, or extremely large non-IEEE representation. if (value > LDBL_MAX || exponent > LDBL_MAX_EXP + LDBL_MAX_EXP - 1 + 8) { if (negative) { // This can only happen with a non-IEEE representation, because // we've already tested for value < -LDBL_MAX return 0; } memset(buf, '\xff', 18); return 18; } // Encoding: // // [ 7 | 6 | 5 | 4 3 2 1 0] // Sm Se Le // // Sm stores the sign of the mantissa: 1 = positive or zero, 0 = negative. // Se stores the sign of the exponent: Sm for positive/zero, !Sm for neg. // Le stores the length of the exponent: !Se for 7 bits, Se for 15 bits. unsigned char next = (negative ? 0 : 0xe0); // Bias the exponent by 8 so that more small integers get short encodings. exponent -= 8; bool exponent_negative = (exponent < 0); if (exponent_negative) { exponent = -exponent; next ^= 0x60; } size_t len = 0; /* We store the exponent in 7 or 15 bits. If the number is negative, we * flip all the bits of the exponent, since larger negative numbers should * sort first. * * If the exponent is negative, we flip the bits of the exponent, since * larger negative exponents should sort first (unless the number is * negative, in which case they should sort later). */ ASSERT(exponent >= 0); if (exponent < 128) { next ^= 0x20; // Put the top 5 bits of the exponent into the lower 5 bits of the // first byte: next |= static_cast<unsigned char>(exponent >> 2); if (negative ^ exponent_negative) { next ^= 0x1f; } buf[len++] = next; // And the lower 2 bits of the exponent go into the upper 2 bits // of the second byte: next = static_cast<unsigned char>(exponent) << 6; if (negative ^ exponent_negative) { next ^= 0xc0; } } else { ASSERT((exponent >> 15) == 0); // Put the top 5 bits of the exponent into the lower 5 bits of the // first byte: next |= static_cast<unsigned char>(exponent >> 10); if (negative ^ exponent_negative) { next ^= 0x1f; } buf[len++] = next; // Put the bits 3-10 of the exponent into the second byte: next = static_cast<unsigned char>(exponent >> 2); if (negative ^ exponent_negative) { next ^= 0xff; } buf[len++] = next; // And the lower 2 bits of the exponent go into the upper 2 bits // of the third byte: next = static_cast<unsigned char>(exponent) << 6; if (negative ^ exponent_negative) { next ^= 0xc0; } } // Convert the 112 (or 113) bits of the mantissa into two 32-bit words. mantissa *= (negative ? 1073741824.0 : 2147483648.0); // 1<<30 : 1<<31 auto word1 = static_cast<unsigned>(mantissa); mantissa -= word1; mantissa *= 4294967296.0L; // 1<<32 auto word2 = static_cast<unsigned>(mantissa); mantissa -= word2; mantissa *= 4294967296.0L; // 1<<32 auto word3 = static_cast<unsigned>(mantissa); mantissa -= word3; mantissa *= 4294967296.0L; // 1<<32 auto word4 = static_cast<unsigned>(mantissa); // If the number is positive, the first bit will always be set because 0.5 // <= mantissa < 1, unless mantissa is zero, which we handle specially // above). If the number is negative, we negate the mantissa instead of // flipping all the bits, so in the case of 0.5, the first bit isn't set // so we need to store it explicitly. But for the cost of one extra // leading bit, we can save several trailing 0xff bytes in lots of common // cases. ASSERT(negative || (word1 & (1<<30))); if (negative) { // We negate the mantissa for negative numbers, so that the sort order // is reversed (since larger negative numbers should come first). word1 = -word1; if (word2 != 0 || word3 != 0 || word4 != 0) { ++word1; } word2 = -word2; if (word3 != 0 || word4 != 0) { ++word2; } word3 = -word3; if (word4 != 0) { ++word3; } word4 = -word4; } word1 &= 0x3fffffff; next |= static_cast<unsigned char>(word1 >> 24); buf[len++] = next; if (word1 != 0) { buf[len++] = char(word1 >> 16); buf[len++] = char(word1 >> 8); buf[len++] = char(word1); } if (word2 != 0 || word3 != 0 || word4 != 0) { buf[len++] = char(word2 >> 24); buf[len++] = char(word2 >> 16); buf[len++] = char(word2 >> 8); buf[len++] = char(word2); } if (word3 != 0 || word4 != 0) { buf[len++] = char(word3 >> 24); buf[len++] = char(word3 >> 16); buf[len++] = char(word3 >> 8); buf[len++] = char(word3); } if (word4 != 0) { buf[len++] = char(word4 >> 24); buf[len++] = char(word4 >> 16); buf[len++] = char(word4 >> 8); buf[len++] = char(word4); } // Finally, we can chop off any trailing zero bytes. while (len > 0 && buf[len - 1] == '\0') { --len; } return len; } std::string sortable_serialise(long double value) { char buf[18]; return std::string(buf, sortable_serialise_(value, buf)); } /// Get a number from the character at a given position in a string, returning /// 0 if the string isn't long enough. static inline unsigned char numfromstr(std::string_view str, std::size_t pos) { return (pos < str.size()) ? static_cast<unsigned char>(str[pos]) : '\0'; } long double sortable_unserialise(std::string_view value) { // Zero. if (value.size() == 1 && value[0] == '\x80') { return 0.0; } // Positive infinity. if (value.size() == 18 && memcmp(value.data(), "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff", 18) == 0 // NOLINT ) { #ifdef INFINITY // INFINITY is C99. Oddly, it's of type "float" so sanity check in // case it doesn't cast to double as infinity (apparently some // implementations have this problem). if ((long double)(INFINITY) > HUGE_VALL) { return INFINITY; } #endif return HUGE_VALL; } // Negative infinity. if (value.empty()) { #ifdef INFINITY if ((long double)(INFINITY) > HUGE_VALL) { return -INFINITY; } #endif return -HUGE_VALL; } unsigned char first = numfromstr(value, 0); size_t i = 0; first ^= static_cast<unsigned char>(first & 0xc0) >> 1; bool negative = (first & 0x80) == 0; bool exponent_negative = (first & 0x40) != 0; bool explen = (first & 0x20) == 0; int exponent = first & 0x1f; if (!explen) { first = numfromstr(value, ++i); exponent <<= 2; exponent |= (first >> 6); if (negative ^ exponent_negative) { exponent ^= 0x07f; } } else { first = numfromstr(value, ++i); exponent <<= 8; exponent |= first; first = numfromstr(value, ++i); exponent <<= 2; exponent |= (first >> 6); if (negative ^ exponent_negative) { exponent ^= 0x7fff; } } unsigned word1; word1 = (unsigned(first & 0x3f) << 24); word1 |= numfromstr(value, ++i) << 16; word1 |= numfromstr(value, ++i) << 8; word1 |= numfromstr(value, ++i); unsigned word2 = 0; if (i < value.size()) { word2 = numfromstr(value, ++i) << 24; word2 |= numfromstr(value, ++i) << 16; word2 |= numfromstr(value, ++i) << 8; word2 |= numfromstr(value, ++i); } unsigned word3 = 0; if (i < value.size()) { word3 = numfromstr(value, ++i) << 24; word3 |= numfromstr(value, ++i) << 16; word3 |= numfromstr(value, ++i) << 8; word3 |= numfromstr(value, ++i); } unsigned word4 = 0; if (i < value.size()) { word4 = numfromstr(value, ++i) << 24; word4 |= numfromstr(value, ++i) << 16; word4 |= numfromstr(value, ++i) << 8; word4 |= numfromstr(value, ++i); } if (negative) { word1 = -word1; if (word2 != 0 || word3 != 0 || word4 != 0) { ++word1; } word2 = -word2; if (word3 != 0 || word4 != 0) { ++word2; } word3 = -word3; if (word4 != 0) { ++word3; } word4 = -word4; ASSERT((word1 & 0xf0000000) != 0); word1 &= 0x3fffffff; } if (!negative) { word1 |= 1<<30; } long double mantissa = 0; if (word4 != 0u) { mantissa += word4 / 79228162514264337593543950336.0L; } // 1<<96 if (word3 != 0u) { mantissa += word3 / 18446744073709551616.0L; } // 1<<64 if (word2 != 0u) { mantissa += word2 / 4294967296.0L; } // 1<<32 if (word1 != 0u) { mantissa += word1; } mantissa /= (negative ? 1073741824.0 : 2147483648.0); // 1<<30 : 1<<31 if (exponent_negative) { exponent = -exponent; } exponent += 8; if (negative) { mantissa = -mantissa; } // We use scalbnl() since it's equivalent to ldexp() when FLT_RADIX == 2 // (which we currently assume), except that ldexp() will set errno if the // result overflows or underflows, which isn't really desirable here. return scalbnl(mantissa, exponent); } <commit_msg>Serialise: Fix copyright for sortable_serialise<commit_after>/* * Copyright (c) 2015-2019 Dubalu LLC * Copyright (C) 2007,2009,2015,2016 Olly Betts * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** @file sortable-serialise.cc * @brief Serialise floating point values to string which sort the same way. */ #include "sortable_serialise.h" #include <cfloat> #include <cmath> #include <cstring> #include <string> #include "cassert.h" // for ASSERT size_t sortable_serialise_(long double value, char * buf) { long double mantissa; int exponent; // Negative infinity. if (value < -LDBL_MAX) { return 0; } mantissa = frexpl(value, &exponent); /* Deal with zero specially. * * IEEE representation of long doubles uses 15 bits for the exponent, with a * bias of 16383. We bias this by subtracting 8, and non-IEEE * representations may allow higher exponents, so allow exponents down to * -32759 - if smaller exponents are possible anywhere, we underflow such * numbers to 0. */ if (mantissa == 0.0 || exponent < -(LDBL_MAX_EXP + LDBL_MAX_EXP - 1 - 8)) { *buf = '\x80'; return 1; } bool negative = (mantissa < 0); if (negative) { mantissa = -mantissa; } // Infinity, or extremely large non-IEEE representation. if (value > LDBL_MAX || exponent > LDBL_MAX_EXP + LDBL_MAX_EXP - 1 + 8) { if (negative) { // This can only happen with a non-IEEE representation, because // we've already tested for value < -LDBL_MAX return 0; } memset(buf, '\xff', 18); return 18; } // Encoding: // // [ 7 | 6 | 5 | 4 3 2 1 0] // Sm Se Le // // Sm stores the sign of the mantissa: 1 = positive or zero, 0 = negative. // Se stores the sign of the exponent: Sm for positive/zero, !Sm for neg. // Le stores the length of the exponent: !Se for 7 bits, Se for 15 bits. unsigned char next = (negative ? 0 : 0xe0); // Bias the exponent by 8 so that more small integers get short encodings. exponent -= 8; bool exponent_negative = (exponent < 0); if (exponent_negative) { exponent = -exponent; next ^= 0x60; } size_t len = 0; /* We store the exponent in 7 or 15 bits. If the number is negative, we * flip all the bits of the exponent, since larger negative numbers should * sort first. * * If the exponent is negative, we flip the bits of the exponent, since * larger negative exponents should sort first (unless the number is * negative, in which case they should sort later). */ ASSERT(exponent >= 0); if (exponent < 128) { next ^= 0x20; // Put the top 5 bits of the exponent into the lower 5 bits of the // first byte: next |= static_cast<unsigned char>(exponent >> 2); if (negative ^ exponent_negative) { next ^= 0x1f; } buf[len++] = next; // And the lower 2 bits of the exponent go into the upper 2 bits // of the second byte: next = static_cast<unsigned char>(exponent) << 6; if (negative ^ exponent_negative) { next ^= 0xc0; } } else { ASSERT((exponent >> 15) == 0); // Put the top 5 bits of the exponent into the lower 5 bits of the // first byte: next |= static_cast<unsigned char>(exponent >> 10); if (negative ^ exponent_negative) { next ^= 0x1f; } buf[len++] = next; // Put the bits 3-10 of the exponent into the second byte: next = static_cast<unsigned char>(exponent >> 2); if (negative ^ exponent_negative) { next ^= 0xff; } buf[len++] = next; // And the lower 2 bits of the exponent go into the upper 2 bits // of the third byte: next = static_cast<unsigned char>(exponent) << 6; if (negative ^ exponent_negative) { next ^= 0xc0; } } // Convert the 112 (or 113) bits of the mantissa into two 32-bit words. mantissa *= (negative ? 1073741824.0 : 2147483648.0); // 1<<30 : 1<<31 auto word1 = static_cast<unsigned>(mantissa); mantissa -= word1; mantissa *= 4294967296.0L; // 1<<32 auto word2 = static_cast<unsigned>(mantissa); mantissa -= word2; mantissa *= 4294967296.0L; // 1<<32 auto word3 = static_cast<unsigned>(mantissa); mantissa -= word3; mantissa *= 4294967296.0L; // 1<<32 auto word4 = static_cast<unsigned>(mantissa); // If the number is positive, the first bit will always be set because 0.5 // <= mantissa < 1, unless mantissa is zero, which we handle specially // above). If the number is negative, we negate the mantissa instead of // flipping all the bits, so in the case of 0.5, the first bit isn't set // so we need to store it explicitly. But for the cost of one extra // leading bit, we can save several trailing 0xff bytes in lots of common // cases. ASSERT(negative || (word1 & (1<<30))); if (negative) { // We negate the mantissa for negative numbers, so that the sort order // is reversed (since larger negative numbers should come first). word1 = -word1; if (word2 != 0 || word3 != 0 || word4 != 0) { ++word1; } word2 = -word2; if (word3 != 0 || word4 != 0) { ++word2; } word3 = -word3; if (word4 != 0) { ++word3; } word4 = -word4; } word1 &= 0x3fffffff; next |= static_cast<unsigned char>(word1 >> 24); buf[len++] = next; if (word1 != 0) { buf[len++] = char(word1 >> 16); buf[len++] = char(word1 >> 8); buf[len++] = char(word1); } if (word2 != 0 || word3 != 0 || word4 != 0) { buf[len++] = char(word2 >> 24); buf[len++] = char(word2 >> 16); buf[len++] = char(word2 >> 8); buf[len++] = char(word2); } if (word3 != 0 || word4 != 0) { buf[len++] = char(word3 >> 24); buf[len++] = char(word3 >> 16); buf[len++] = char(word3 >> 8); buf[len++] = char(word3); } if (word4 != 0) { buf[len++] = char(word4 >> 24); buf[len++] = char(word4 >> 16); buf[len++] = char(word4 >> 8); buf[len++] = char(word4); } // Finally, we can chop off any trailing zero bytes. while (len > 0 && buf[len - 1] == '\0') { --len; } return len; } std::string sortable_serialise(long double value) { char buf[18]; return std::string(buf, sortable_serialise_(value, buf)); } /// Get a number from the character at a given position in a string, returning /// 0 if the string isn't long enough. static inline unsigned char numfromstr(std::string_view str, std::size_t pos) { return (pos < str.size()) ? static_cast<unsigned char>(str[pos]) : '\0'; } long double sortable_unserialise(std::string_view value) { // Zero. if (value.size() == 1 && value[0] == '\x80') { return 0.0; } // Positive infinity. if (value.size() == 18 && memcmp(value.data(), "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff", 18) == 0 // NOLINT ) { #ifdef INFINITY // INFINITY is C99. Oddly, it's of type "float" so sanity check in // case it doesn't cast to double as infinity (apparently some // implementations have this problem). if ((long double)(INFINITY) > HUGE_VALL) { return INFINITY; } #endif return HUGE_VALL; } // Negative infinity. if (value.empty()) { #ifdef INFINITY if ((long double)(INFINITY) > HUGE_VALL) { return -INFINITY; } #endif return -HUGE_VALL; } unsigned char first = numfromstr(value, 0); size_t i = 0; first ^= static_cast<unsigned char>(first & 0xc0) >> 1; bool negative = (first & 0x80) == 0; bool exponent_negative = (first & 0x40) != 0; bool explen = (first & 0x20) == 0; int exponent = first & 0x1f; if (!explen) { first = numfromstr(value, ++i); exponent <<= 2; exponent |= (first >> 6); if (negative ^ exponent_negative) { exponent ^= 0x07f; } } else { first = numfromstr(value, ++i); exponent <<= 8; exponent |= first; first = numfromstr(value, ++i); exponent <<= 2; exponent |= (first >> 6); if (negative ^ exponent_negative) { exponent ^= 0x7fff; } } unsigned word1; word1 = (unsigned(first & 0x3f) << 24); word1 |= numfromstr(value, ++i) << 16; word1 |= numfromstr(value, ++i) << 8; word1 |= numfromstr(value, ++i); unsigned word2 = 0; if (i < value.size()) { word2 = numfromstr(value, ++i) << 24; word2 |= numfromstr(value, ++i) << 16; word2 |= numfromstr(value, ++i) << 8; word2 |= numfromstr(value, ++i); } unsigned word3 = 0; if (i < value.size()) { word3 = numfromstr(value, ++i) << 24; word3 |= numfromstr(value, ++i) << 16; word3 |= numfromstr(value, ++i) << 8; word3 |= numfromstr(value, ++i); } unsigned word4 = 0; if (i < value.size()) { word4 = numfromstr(value, ++i) << 24; word4 |= numfromstr(value, ++i) << 16; word4 |= numfromstr(value, ++i) << 8; word4 |= numfromstr(value, ++i); } if (negative) { word1 = -word1; if (word2 != 0 || word3 != 0 || word4 != 0) { ++word1; } word2 = -word2; if (word3 != 0 || word4 != 0) { ++word2; } word3 = -word3; if (word4 != 0) { ++word3; } word4 = -word4; ASSERT((word1 & 0xf0000000) != 0); word1 &= 0x3fffffff; } if (!negative) { word1 |= 1<<30; } long double mantissa = 0; if (word4 != 0u) { mantissa += word4 / 79228162514264337593543950336.0L; } // 1<<96 if (word3 != 0u) { mantissa += word3 / 18446744073709551616.0L; } // 1<<64 if (word2 != 0u) { mantissa += word2 / 4294967296.0L; } // 1<<32 if (word1 != 0u) { mantissa += word1; } mantissa /= (negative ? 1073741824.0 : 2147483648.0); // 1<<30 : 1<<31 if (exponent_negative) { exponent = -exponent; } exponent += 8; if (negative) { mantissa = -mantissa; } // We use scalbnl() since it's equivalent to ldexp() when FLT_RADIX == 2 // (which we currently assume), except that ldexp() will set errno if the // result overflows or underflows, which isn't really desirable here. return scalbnl(mantissa, exponent); } <|endoftext|>
<commit_before>// Copyright (c) 2021 The Orbit 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 "SessionSetup/TargetLabel.h" #include <QAction> #include <QDesktopServices> #include <QImage> #include <QMenu> #include <QPalette> #include <QPixmap> #include <QUrl> #include <memory> #include <optional> #include "SessionSetup/DoubleClickableLabel.h" #include "ui_TargetLabel.h" namespace { const QColor kDefaultTextColor{"white"}; const QColor kGreenColor{"#66BB6A"}; const QColor kOrangeColor{"orange"}; const QColor kRedColor{"#E64646"}; const QString kLocalhostName{"localhost"}; QPixmap ColorizeIcon(const QPixmap& pixmap, const QColor& color) { QImage colored_image = pixmap.toImage(); for (int y = 0; y < colored_image.height(); y++) { for (int x = 0; x < colored_image.width(); x++) { QColor color_with_alpha = color; color_with_alpha.setAlpha(colored_image.pixelColor(x, y).alpha()); colored_image.setPixelColor(x, y, color_with_alpha); } } return QPixmap::fromImage(std::move(colored_image)); } QPixmap GetGreenConnectedIcon() { const static QPixmap kGreenConnectedIcon = ColorizeIcon(QPixmap{":/actions/connected"}, kGreenColor); return kGreenConnectedIcon; } QPixmap GetOrangeDisconnectedIcon() { const static QPixmap kOrangeDisconnectedIcon = ColorizeIcon(QPixmap{":/actions/alert"}, kOrangeColor); return kOrangeDisconnectedIcon; } QPixmap GetRedDisconnectedIcon() { const static QPixmap kRedDisconnectedIcon = ColorizeIcon(QPixmap{":/actions/disconnected"}, kRedColor); return kRedDisconnectedIcon; } } // namespace namespace orbit_session_setup { namespace fs = std::filesystem; TargetLabel::TargetLabel(QWidget* parent) : QWidget(parent), ui_(std::make_unique<Ui::TargetLabel>()) { ui_->setupUi(this); QObject::connect(ui_->fileLabel, &DoubleClickableLabel::DoubleClicked, this, &TargetLabel::OpenContainingFolder); QObject::connect(ui_->fileLabel, &DoubleClickableLabel::customContextMenuRequested, this, [this](const QPoint& pos) { QAction action{QIcon(":/actions/folder"), "Open Containing Folder", this}; QObject::connect(&action, &QAction::triggered, this, &TargetLabel::OpenContainingFolder); QMenu menu; menu.addAction(&action); menu.exec(mapToGlobal(pos)); }); } TargetLabel::~TargetLabel() = default; void TargetLabel::ChangeToFileTarget(const FileTarget& file_target) { ChangeToFileTarget(file_target.GetCaptureFilePath()); } void TargetLabel::SetFile(const std::filesystem::path& file_path) { file_path_ = file_path; ui_->fileLabel->setText(QString::fromStdString(file_path.filename().string())); ui_->fileLabel->setToolTip(QString::fromStdString(file_path.string())); ui_->fileLabel->setVisible(true); emit SizeChanged(); } void TargetLabel::ChangeToFileTarget(const fs::path& path) { Clear(); SetFile(path); ui_->targetLabel->setVisible(false); emit SizeChanged(); } void TargetLabel::ChangeToStadiaTarget(const StadiaTarget& stadia_target) { ChangeToStadiaTarget(*stadia_target.GetProcess(), stadia_target.GetConnection()->GetInstance()); } void TargetLabel::ChangeToStadiaTarget(const orbit_client_data::ProcessData& process, const orbit_ggp::Instance& instance) { ChangeToStadiaTarget(QString::fromStdString(process.name()), process.cpu_usage(), instance.display_name); } void TargetLabel::ChangeToStadiaTarget(const QString& process_name, double cpu_usage, const QString& instance_name) { Clear(); process_ = process_name; machine_ = instance_name; SetProcessCpuUsageInPercent(cpu_usage); ui_->targetLabel->setVisible(true); ui_->fileLabel->setVisible(false); } void TargetLabel::ChangeToLocalTarget(const LocalTarget& local_target) { ChangeToLocalTarget(*local_target.GetProcess()); } void TargetLabel::ChangeToLocalTarget(const orbit_client_data::ProcessData& process) { ChangeToLocalTarget(QString::fromStdString(process.name()), process.cpu_usage()); } void TargetLabel::ChangeToLocalTarget(const QString& process_name, double cpu_usage) { Clear(); process_ = process_name; machine_ = kLocalhostName; SetProcessCpuUsageInPercent(cpu_usage); ui_->targetLabel->setVisible(true); ui_->fileLabel->setVisible(false); } bool TargetLabel::SetProcessCpuUsageInPercent(double cpu_usage) { if (process_.isEmpty() || machine_.isEmpty()) return false; ui_->targetLabel->setText( QString{"%1 (%2%) @ %3"}.arg(process_).arg(cpu_usage, 0, 'f', 0).arg(machine_)); SetColor(kGreenColor); setToolTip({}); SetIcon(IconType::kGreenConnectedIcon); emit SizeChanged(); return true; } bool TargetLabel::SetProcessEnded() { if (process_.isEmpty() || machine_.isEmpty()) return false; ui_->targetLabel->setText(QString{"%1 @ %2"}.arg(process_, machine_)); SetColor(kOrangeColor); setToolTip("The process ended."); SetIcon(IconType::kOrangeDisconnectedIcon); emit SizeChanged(); return true; } bool TargetLabel::SetConnectionDead(const QString& error_message) { if (process_.isEmpty() || machine_.isEmpty()) return false; ui_->targetLabel->setText(QString{"%1 @ %2"}.arg(process_, machine_)); SetColor(kRedColor); setToolTip(error_message); SetIcon(IconType::kRedDisconnectedIcon); emit SizeChanged(); return true; } void TargetLabel::Clear() { process_ = ""; machine_ = ""; file_path_.reset(); ui_->fileLabel->setText({}); ui_->targetLabel->setText({}); ui_->fileLabel->setVisible(false); ui_->targetLabel->setVisible(false); SetColor(kDefaultTextColor); setToolTip({}); ClearIcon(); emit SizeChanged(); } QColor TargetLabel::GetTargetColor() const { return ui_->targetLabel->palette().color(QPalette::WindowText); } QString TargetLabel::GetTargetText() const { return ui_->targetLabel->text(); } QString TargetLabel::GetFileText() const { return ui_->fileLabel->text(); } void TargetLabel::SetColor(const QColor& color) { // This class is used in a QFrame and in QMenuBar. To make the coloring work in a QFrame the // QColorRole QPalette::WindowText needs to be set. For QMenuBar QPalette::ButtonText needs to be // set. QPalette palette{}; palette.setColor(QPalette::WindowText, color); palette.setColor(QPalette::ButtonText, color); ui_->targetLabel->setPalette(palette); } void TargetLabel::SetIcon(IconType icon_type) { icon_type_ = icon_type; switch (icon_type) { case IconType::kGreenConnectedIcon: ui_->iconLabel->setPixmap(GetGreenConnectedIcon()); break; case IconType::kOrangeDisconnectedIcon: ui_->iconLabel->setPixmap(GetOrangeDisconnectedIcon()); break; case IconType::kRedDisconnectedIcon: ui_->iconLabel->setPixmap(GetRedDisconnectedIcon()); break; } ui_->iconLabel->setVisible(true); } void TargetLabel::ClearIcon() { icon_type_ = std::nullopt; ui_->iconLabel->setPixmap(QPixmap{}); ui_->iconLabel->setVisible(false); } void TargetLabel::OpenContainingFolder() { if (!file_path_.has_value()) return; QUrl url = QUrl::fromLocalFile(QString::fromStdString(file_path_->parent_path().string())); if (!QDesktopServices::openUrl(url)) { ERROR("Opening containing folder of \"%s\"", file_path_->string()); } } } // namespace orbit_session_setup <commit_msg>TargetLabel is no longer updated unless needed (#2813)<commit_after>// Copyright (c) 2021 The Orbit 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 "SessionSetup/TargetLabel.h" #include <QAction> #include <QDesktopServices> #include <QImage> #include <QMenu> #include <QPalette> #include <QPixmap> #include <QUrl> #include <memory> #include <optional> #include "SessionSetup/DoubleClickableLabel.h" #include "ui_TargetLabel.h" namespace { const QColor kDefaultTextColor{"white"}; const QColor kGreenColor{"#66BB6A"}; const QColor kOrangeColor{"orange"}; const QColor kRedColor{"#E64646"}; const QString kLocalhostName{"localhost"}; QPixmap ColorizeIcon(const QPixmap& pixmap, const QColor& color) { QImage colored_image = pixmap.toImage(); for (int y = 0; y < colored_image.height(); y++) { for (int x = 0; x < colored_image.width(); x++) { QColor color_with_alpha = color; color_with_alpha.setAlpha(colored_image.pixelColor(x, y).alpha()); colored_image.setPixelColor(x, y, color_with_alpha); } } return QPixmap::fromImage(std::move(colored_image)); } QPixmap GetGreenConnectedIcon() { const static QPixmap kGreenConnectedIcon = ColorizeIcon(QPixmap{":/actions/connected"}, kGreenColor); return kGreenConnectedIcon; } QPixmap GetOrangeDisconnectedIcon() { const static QPixmap kOrangeDisconnectedIcon = ColorizeIcon(QPixmap{":/actions/alert"}, kOrangeColor); return kOrangeDisconnectedIcon; } QPixmap GetRedDisconnectedIcon() { const static QPixmap kRedDisconnectedIcon = ColorizeIcon(QPixmap{":/actions/disconnected"}, kRedColor); return kRedDisconnectedIcon; } } // namespace namespace orbit_session_setup { namespace fs = std::filesystem; TargetLabel::TargetLabel(QWidget* parent) : QWidget(parent), ui_(std::make_unique<Ui::TargetLabel>()) { ui_->setupUi(this); QObject::connect(ui_->fileLabel, &DoubleClickableLabel::DoubleClicked, this, &TargetLabel::OpenContainingFolder); QObject::connect(ui_->fileLabel, &DoubleClickableLabel::customContextMenuRequested, this, [this](const QPoint& pos) { QAction action{QIcon(":/actions/folder"), "Open Containing Folder", this}; QObject::connect(&action, &QAction::triggered, this, &TargetLabel::OpenContainingFolder); QMenu menu; menu.addAction(&action); menu.exec(mapToGlobal(pos)); }); } TargetLabel::~TargetLabel() = default; void TargetLabel::ChangeToFileTarget(const FileTarget& file_target) { ChangeToFileTarget(file_target.GetCaptureFilePath()); } void TargetLabel::SetFile(const std::filesystem::path& file_path) { // Without this, the size of the target label is not correctly updated when a capture is opened // directly from the connection window. It's unclear why this happens, might be related to // multiple `SizeChanged` signals being emitted while the main window is still being shown. if (file_path_ == file_path) return; file_path_ = file_path; ui_->fileLabel->setText(QString::fromStdString(file_path.filename().string())); ui_->fileLabel->setToolTip(QString::fromStdString(file_path.string())); ui_->fileLabel->setVisible(true); emit SizeChanged(); } void TargetLabel::ChangeToFileTarget(const fs::path& path) { Clear(); SetFile(path); ui_->targetLabel->setVisible(false); emit SizeChanged(); } void TargetLabel::ChangeToStadiaTarget(const StadiaTarget& stadia_target) { ChangeToStadiaTarget(*stadia_target.GetProcess(), stadia_target.GetConnection()->GetInstance()); } void TargetLabel::ChangeToStadiaTarget(const orbit_client_data::ProcessData& process, const orbit_ggp::Instance& instance) { ChangeToStadiaTarget(QString::fromStdString(process.name()), process.cpu_usage(), instance.display_name); } void TargetLabel::ChangeToStadiaTarget(const QString& process_name, double cpu_usage, const QString& instance_name) { Clear(); process_ = process_name; machine_ = instance_name; SetProcessCpuUsageInPercent(cpu_usage); ui_->targetLabel->setVisible(true); ui_->fileLabel->setVisible(false); } void TargetLabel::ChangeToLocalTarget(const LocalTarget& local_target) { ChangeToLocalTarget(*local_target.GetProcess()); } void TargetLabel::ChangeToLocalTarget(const orbit_client_data::ProcessData& process) { ChangeToLocalTarget(QString::fromStdString(process.name()), process.cpu_usage()); } void TargetLabel::ChangeToLocalTarget(const QString& process_name, double cpu_usage) { Clear(); process_ = process_name; machine_ = kLocalhostName; SetProcessCpuUsageInPercent(cpu_usage); ui_->targetLabel->setVisible(true); ui_->fileLabel->setVisible(false); } bool TargetLabel::SetProcessCpuUsageInPercent(double cpu_usage) { if (process_.isEmpty() || machine_.isEmpty()) return false; ui_->targetLabel->setText( QString{"%1 (%2%) @ %3"}.arg(process_).arg(cpu_usage, 0, 'f', 0).arg(machine_)); SetColor(kGreenColor); setToolTip({}); SetIcon(IconType::kGreenConnectedIcon); emit SizeChanged(); return true; } bool TargetLabel::SetProcessEnded() { if (process_.isEmpty() || machine_.isEmpty()) return false; ui_->targetLabel->setText(QString{"%1 @ %2"}.arg(process_, machine_)); SetColor(kOrangeColor); setToolTip("The process ended."); SetIcon(IconType::kOrangeDisconnectedIcon); emit SizeChanged(); return true; } bool TargetLabel::SetConnectionDead(const QString& error_message) { if (process_.isEmpty() || machine_.isEmpty()) return false; ui_->targetLabel->setText(QString{"%1 @ %2"}.arg(process_, machine_)); SetColor(kRedColor); setToolTip(error_message); SetIcon(IconType::kRedDisconnectedIcon); emit SizeChanged(); return true; } void TargetLabel::Clear() { process_ = ""; machine_ = ""; file_path_.reset(); ui_->fileLabel->setText({}); ui_->targetLabel->setText({}); ui_->fileLabel->setVisible(false); ui_->targetLabel->setVisible(false); SetColor(kDefaultTextColor); setToolTip({}); ClearIcon(); emit SizeChanged(); } QColor TargetLabel::GetTargetColor() const { return ui_->targetLabel->palette().color(QPalette::WindowText); } QString TargetLabel::GetTargetText() const { return ui_->targetLabel->text(); } QString TargetLabel::GetFileText() const { return ui_->fileLabel->text(); } void TargetLabel::SetColor(const QColor& color) { // This class is used in a QFrame and in QMenuBar. To make the coloring work in a QFrame the // QColorRole QPalette::WindowText needs to be set. For QMenuBar QPalette::ButtonText needs to be // set. QPalette palette{}; palette.setColor(QPalette::WindowText, color); palette.setColor(QPalette::ButtonText, color); ui_->targetLabel->setPalette(palette); } void TargetLabel::SetIcon(IconType icon_type) { icon_type_ = icon_type; switch (icon_type) { case IconType::kGreenConnectedIcon: ui_->iconLabel->setPixmap(GetGreenConnectedIcon()); break; case IconType::kOrangeDisconnectedIcon: ui_->iconLabel->setPixmap(GetOrangeDisconnectedIcon()); break; case IconType::kRedDisconnectedIcon: ui_->iconLabel->setPixmap(GetRedDisconnectedIcon()); break; } ui_->iconLabel->setVisible(true); } void TargetLabel::ClearIcon() { icon_type_ = std::nullopt; ui_->iconLabel->setPixmap(QPixmap{}); ui_->iconLabel->setVisible(false); } void TargetLabel::OpenContainingFolder() { if (!file_path_.has_value()) return; QUrl url = QUrl::fromLocalFile(QString::fromStdString(file_path_->parent_path().string())); if (!QDesktopServices::openUrl(url)) { ERROR("Opening containing folder of \"%s\"", file_path_->string()); } } } // namespace orbit_session_setup <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2062 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1246912 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/03/14 03:00:09<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2063 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3072 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 2052260 by chui@ocl-promo-incrementor on 2020/01/04 03:00:14<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3073 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2578 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1507743 by johtaylo@johtaylo-jtincrementor2-increment on 2018/01/25 03:01:01<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2579 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>