text
stringlengths
54
60.6k
<commit_before>/* * Copyright (c) 2015,2018 Immo Software * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o 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. * * o Neither the name of the copyright holder nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "asr_envelope.h" #include "arm_math.h" using namespace slab; //------------------------------------------------------------------------------ // Code //------------------------------------------------------------------------------ ASREnvelope::ASREnvelope() : AudioFilter(), m_attack(), m_release(), m_peak(1.0f), m_mode(kOneShotAR), m_enableSustain(false), m_releaseOffset(0), m_elapsedSamples(0) { } void ASREnvelope::set_sample_rate(float rate) { AudioFilter::set_sample_rate(rate); m_attack.set_sample_rate(rate); m_release.set_sample_rate(rate); } void ASREnvelope::set_mode(EnvelopeMode mode) { m_mode = mode; m_enableSustain = (mode == kOneShotASR); } void ASREnvelope::set_peak(float peak) { m_peak = peak; m_attack.set_begin_value(0.0f); m_attack.set_end_value(peak); m_release.set_begin_value(peak); m_release.set_end_value(0.0f); } void ASREnvelope::set_length_in_seconds(EnvelopeStage stage, float seconds) { switch (stage) { case kAttack: m_attack.set_length_in_seconds(seconds); break; case kRelease: m_release.set_length_in_seconds(seconds); break; default: break; } } void ASREnvelope::set_length_in_samples(EnvelopeStage stage, uint32_t samples) { switch (stage) { case kAttack: m_attack.set_length_in_samples(samples); break; case kRelease: m_release.set_length_in_samples(samples); break; default: break; } } float ASREnvelope::get_length_in_seconds(EnvelopeStage stage) { switch (stage) { case kAttack: return m_attack.get_length_in_seconds(); case kRelease: return m_release.get_length_in_seconds(); default: break; } return 0.0f; } uint32_t ASREnvelope::get_length_in_samples(EnvelopeStage stage) { switch (stage) { case kAttack: return m_attack.get_length_in_samples(); case kRelease: return m_release.get_length_in_samples(); default: break; } return 0; } void ASREnvelope::set_curve_type(EnvelopeStage stage, AudioRamp::CurveType theType) { switch (stage) { case kAttack: m_attack.set_curve_type(theType); break; case kRelease: m_release.set_curve_type(theType); break; default: break; } } void ASREnvelope::recompute() { // Recompute the slope of both ramps. m_attack.recompute(); m_release.recompute(); } void ASREnvelope::set_release_offset(uint32_t offset) { m_releaseOffset = m_elapsedSamples + offset; } void ASREnvelope::reset() { m_attack.reset(); m_release.reset(); m_elapsedSamples = 0; m_releaseOffset = 0; } float ASREnvelope::next() { float sample; process(&sample, 1); return sample; } bool ASREnvelope::is_finished() { return m_attack.is_finished() && (!m_enableSustain || (m_releaseOffset != 0 && m_elapsedSamples >= m_releaseOffset)) && m_release.is_finished(); } void ASREnvelope::process(float * samples, uint32_t count) { uint32_t totalRemaining = count; while (totalRemaining) { // Special case to prevent infinite loop if the stages are both 0 length and // we're in the looping envelope mode. if (m_mode == kLoopingAR && m_attack.get_length_in_samples() == 0 && m_release.get_length_in_samples() == 0) { arm_fill_f32(0.0f, samples, totalRemaining); return; } // Attack. uint32_t attackCount = m_attack.get_remaining_samples(); if (attackCount > count) { attackCount = count; } if (attackCount) { m_attack.process(samples, attackCount); } // Sustain. if (attackCount < count) { int32_t sustainCount = 0; if (m_enableSustain) { sustainCount = count - attackCount; if (m_releaseOffset > 0) { if (attackCount + sustainCount + m_elapsedSamples > m_releaseOffset) { sustainCount = m_releaseOffset - m_elapsedSamples - attackCount; if (sustainCount < 0) { sustainCount = 0; } } } if (sustainCount > 0) { arm_fill_f32(m_peak, samples + attackCount, sustainCount); } } // Release. uint32_t attackSustainCount = attackCount + sustainCount; if (attackSustainCount < count) { uint32_t releaseCount = count - attackSustainCount; if (m_mode == kLoopingAR) { uint32_t releaseRemaining = m_release.get_remaining_samples(); if (releaseRemaining > releaseCount) { m_release.process(samples + attackSustainCount, releaseCount); } else { // Fill last part of release stage, then retrigger and loop. m_release.process(samples + attackSustainCount, releaseRemaining); reset(); uint32_t thisLoopCount = attackSustainCount + releaseRemaining; totalRemaining -= thisLoopCount; samples += thisLoopCount; m_elapsedSamples += thisLoopCount; count = releaseCount - releaseRemaining; continue; } } else { // For non-looping modes, we can just let the release stage fill to the end. if (releaseCount) { m_release.process(samples + attackSustainCount, releaseCount); } } } } totalRemaining -= count; m_elapsedSamples += count; } } //------------------------------------------------------------------------------ // EOF //------------------------------------------------------------------------------ <commit_msg>Fixed ASREnvelope::is_finished() for looping env mode.<commit_after>/* * Copyright (c) 2015,2018 Immo Software * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o 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. * * o Neither the name of the copyright holder nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "asr_envelope.h" #include "arm_math.h" using namespace slab; //------------------------------------------------------------------------------ // Code //------------------------------------------------------------------------------ ASREnvelope::ASREnvelope() : AudioFilter(), m_attack(), m_release(), m_peak(1.0f), m_mode(kOneShotAR), m_enableSustain(false), m_releaseOffset(0), m_elapsedSamples(0) { } void ASREnvelope::set_sample_rate(float rate) { AudioFilter::set_sample_rate(rate); m_attack.set_sample_rate(rate); m_release.set_sample_rate(rate); } void ASREnvelope::set_mode(EnvelopeMode mode) { m_mode = mode; m_enableSustain = (mode == kOneShotASR); } void ASREnvelope::set_peak(float peak) { m_peak = peak; m_attack.set_begin_value(0.0f); m_attack.set_end_value(peak); m_release.set_begin_value(peak); m_release.set_end_value(0.0f); } void ASREnvelope::set_length_in_seconds(EnvelopeStage stage, float seconds) { switch (stage) { case kAttack: m_attack.set_length_in_seconds(seconds); break; case kRelease: m_release.set_length_in_seconds(seconds); break; default: break; } } void ASREnvelope::set_length_in_samples(EnvelopeStage stage, uint32_t samples) { switch (stage) { case kAttack: m_attack.set_length_in_samples(samples); break; case kRelease: m_release.set_length_in_samples(samples); break; default: break; } } float ASREnvelope::get_length_in_seconds(EnvelopeStage stage) { switch (stage) { case kAttack: return m_attack.get_length_in_seconds(); case kRelease: return m_release.get_length_in_seconds(); default: break; } return 0.0f; } uint32_t ASREnvelope::get_length_in_samples(EnvelopeStage stage) { switch (stage) { case kAttack: return m_attack.get_length_in_samples(); case kRelease: return m_release.get_length_in_samples(); default: break; } return 0; } void ASREnvelope::set_curve_type(EnvelopeStage stage, AudioRamp::CurveType theType) { switch (stage) { case kAttack: m_attack.set_curve_type(theType); break; case kRelease: m_release.set_curve_type(theType); break; default: break; } } void ASREnvelope::recompute() { // Recompute the slope of both ramps. m_attack.recompute(); m_release.recompute(); } void ASREnvelope::set_release_offset(uint32_t offset) { m_releaseOffset = m_elapsedSamples + offset; } void ASREnvelope::reset() { m_attack.reset(); m_release.reset(); m_elapsedSamples = 0; m_releaseOffset = 0; } float ASREnvelope::next() { float sample; process(&sample, 1); return sample; } bool ASREnvelope::is_finished() { return (m_mode != kLoopingAR) && (m_attack.is_finished() && (!m_enableSustain || (m_releaseOffset != 0 && m_elapsedSamples >= m_releaseOffset)) && m_release.is_finished()); } void ASREnvelope::process(float * samples, uint32_t count) { uint32_t totalRemaining = count; while (totalRemaining) { // Special case to prevent infinite loop if the stages are both 0 length and // we're in the looping envelope mode. if (m_mode == kLoopingAR && m_attack.get_length_in_samples() == 0 && m_release.get_length_in_samples() == 0) { arm_fill_f32(0.0f, samples, totalRemaining); return; } // Attack. uint32_t attackCount = m_attack.get_remaining_samples(); if (attackCount > count) { attackCount = count; } if (attackCount) { m_attack.process(samples, attackCount); } // Sustain. if (attackCount < count) { int32_t sustainCount = 0; if (m_enableSustain) { sustainCount = count - attackCount; if (m_releaseOffset > 0) { if (attackCount + sustainCount + m_elapsedSamples > m_releaseOffset) { sustainCount = m_releaseOffset - m_elapsedSamples - attackCount; if (sustainCount < 0) { sustainCount = 0; } } } if (sustainCount > 0) { arm_fill_f32(m_peak, samples + attackCount, sustainCount); } } // Release. uint32_t attackSustainCount = attackCount + sustainCount; if (attackSustainCount < count) { uint32_t releaseCount = count - attackSustainCount; if (m_mode == kLoopingAR) { uint32_t releaseRemaining = m_release.get_remaining_samples(); if (releaseRemaining > releaseCount) { m_release.process(samples + attackSustainCount, releaseCount); } else { // Fill last part of release stage, then retrigger and loop. m_release.process(samples + attackSustainCount, releaseRemaining); reset(); uint32_t thisLoopCount = attackSustainCount + releaseRemaining; totalRemaining -= thisLoopCount; samples += thisLoopCount; m_elapsedSamples += thisLoopCount; count = releaseCount - releaseRemaining; continue; } } else { // For non-looping modes, we can just let the release stage fill to the end. if (releaseCount) { m_release.process(samples + attackSustainCount, releaseCount); } } } } totalRemaining -= count; m_elapsedSamples += count; } } //------------------------------------------------------------------------------ // EOF //------------------------------------------------------------------------------ <|endoftext|>
<commit_before>//===-- SIOptimizeExecMaskingPreRA.cpp ------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // /// \file /// This pass removes redundant S_OR_B64 instructions enabling lanes in /// the exec. If two SI_END_CF (lowered as S_OR_B64) come together without any /// vector instructions between them we can only keep outer SI_END_CF, given /// that CFG is structured and exec bits of the outer end statement are always /// not less than exec bit of the inner one. /// /// This needs to be done before the RA to eliminate saved exec bits registers /// but after register coalescer to have no vector registers copies in between /// of different end cf statements. /// //===----------------------------------------------------------------------===// #include "AMDGPU.h" #include "AMDGPUSubtarget.h" #include "SIInstrInfo.h" #include "MCTargetDesc/AMDGPUMCTargetDesc.h" #include "llvm/CodeGen/LiveIntervals.h" #include "llvm/CodeGen/MachineFunctionPass.h" using namespace llvm; #define DEBUG_TYPE "si-optimize-exec-masking-pre-ra" namespace { class SIOptimizeExecMaskingPreRA : public MachineFunctionPass { public: static char ID; public: SIOptimizeExecMaskingPreRA() : MachineFunctionPass(ID) { initializeSIOptimizeExecMaskingPreRAPass(*PassRegistry::getPassRegistry()); } bool runOnMachineFunction(MachineFunction &MF) override; StringRef getPassName() const override { return "SI optimize exec mask operations pre-RA"; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<LiveIntervals>(); AU.setPreservesAll(); MachineFunctionPass::getAnalysisUsage(AU); } }; } // End anonymous namespace. INITIALIZE_PASS_BEGIN(SIOptimizeExecMaskingPreRA, DEBUG_TYPE, "SI optimize exec mask operations pre-RA", false, false) INITIALIZE_PASS_DEPENDENCY(LiveIntervals) INITIALIZE_PASS_END(SIOptimizeExecMaskingPreRA, DEBUG_TYPE, "SI optimize exec mask operations pre-RA", false, false) char SIOptimizeExecMaskingPreRA::ID = 0; char &llvm::SIOptimizeExecMaskingPreRAID = SIOptimizeExecMaskingPreRA::ID; FunctionPass *llvm::createSIOptimizeExecMaskingPreRAPass() { return new SIOptimizeExecMaskingPreRA(); } static bool isEndCF(const MachineInstr& MI, const SIRegisterInfo* TRI) { return MI.getOpcode() == AMDGPU::S_OR_B64 && MI.modifiesRegister(AMDGPU::EXEC, TRI); } static bool isFullExecCopy(const MachineInstr& MI) { return MI.isFullCopy() && MI.getOperand(1).getReg() == AMDGPU::EXEC; } static unsigned getOrNonExecReg(const MachineInstr &MI, const SIInstrInfo &TII) { auto Op = TII.getNamedOperand(MI, AMDGPU::OpName::src1); if (Op->isReg() && Op->getReg() != AMDGPU::EXEC) return Op->getReg(); Op = TII.getNamedOperand(MI, AMDGPU::OpName::src0); if (Op->isReg() && Op->getReg() != AMDGPU::EXEC) return Op->getReg(); return AMDGPU::NoRegister; } static MachineInstr* getOrExecSource(const MachineInstr &MI, const SIInstrInfo &TII, const MachineRegisterInfo &MRI) { auto SavedExec = getOrNonExecReg(MI, TII); if (SavedExec == AMDGPU::NoRegister) return nullptr; auto SaveExecInst = MRI.getUniqueVRegDef(SavedExec); if (!SaveExecInst || !isFullExecCopy(*SaveExecInst)) return nullptr; return SaveExecInst; } // Optimize sequence // %sel = V_CNDMASK_B32_e64 0, 1, %cc // %cmp = V_CMP_NE_U32 1, %1 // $vcc = S_AND_B64 $exec, %cmp // S_CBRANCH_VCC[N]Z // => // $vcc = S_ANDN2_B64 $exec, %cc // S_CBRANCH_VCC[N]Z // // It is the negation pattern inserted by DAGCombiner::visitBRCOND() in the // rebuildSetCC(). We start with S_CBRANCH to avoid exhaustive search, but // only 3 first instructions are really needed. S_AND_B64 with exec is a // required part of the pattern since V_CNDMASK_B32 writes zeroes for inactive // lanes. // // Returns %cc register on success. static unsigned optimizeVcndVcmpPair(MachineBasicBlock &MBB, const GCNSubtarget &ST, MachineRegisterInfo &MRI, LiveIntervals *LIS) { const SIRegisterInfo *TRI = ST.getRegisterInfo(); const SIInstrInfo *TII = ST.getInstrInfo(); const unsigned AndOpc = AMDGPU::S_AND_B64; const unsigned Andn2Opc = AMDGPU::S_ANDN2_B64; const unsigned CondReg = AMDGPU::VCC; const unsigned ExecReg = AMDGPU::EXEC; auto I = llvm::find_if(MBB.terminators(), [](const MachineInstr &MI) { unsigned Opc = MI.getOpcode(); return Opc == AMDGPU::S_CBRANCH_VCCZ || Opc == AMDGPU::S_CBRANCH_VCCNZ; }); if (I == MBB.terminators().end()) return AMDGPU::NoRegister; auto *And = TRI->findReachingDef(CondReg, AMDGPU::NoSubRegister, *I, MRI, LIS); if (!And || And->getOpcode() != AndOpc || !And->getOperand(1).isReg() || !And->getOperand(2).isReg()) return AMDGPU::NoRegister; MachineOperand *AndCC = &And->getOperand(1); unsigned CmpReg = AndCC->getReg(); unsigned CmpSubReg = AndCC->getSubReg(); if (CmpReg == ExecReg) { AndCC = &And->getOperand(2); CmpReg = AndCC->getReg(); CmpSubReg = AndCC->getSubReg(); } else if (And->getOperand(2).getReg() != ExecReg) { return AMDGPU::NoRegister; } auto *Cmp = TRI->findReachingDef(CmpReg, CmpSubReg, *And, MRI, LIS); if (!Cmp || !(Cmp->getOpcode() == AMDGPU::V_CMP_NE_U32_e32 || Cmp->getOpcode() == AMDGPU::V_CMP_NE_U32_e64) || Cmp->getParent() != And->getParent()) return AMDGPU::NoRegister; MachineOperand *Op1 = TII->getNamedOperand(*Cmp, AMDGPU::OpName::src0); MachineOperand *Op2 = TII->getNamedOperand(*Cmp, AMDGPU::OpName::src1); if (Op1->isImm() && Op2->isReg()) std::swap(Op1, Op2); if (!Op1->isReg() || !Op2->isImm() || Op2->getImm() != 1) return AMDGPU::NoRegister; unsigned SelReg = Op1->getReg(); auto *Sel = TRI->findReachingDef(SelReg, Op1->getSubReg(), *Cmp, MRI, LIS); if (!Sel || Sel->getOpcode() != AMDGPU::V_CNDMASK_B32_e64) return AMDGPU::NoRegister; if (TII->hasModifiersSet(*Sel, AMDGPU::OpName::src0_modifiers) || TII->hasModifiersSet(*Sel, AMDGPU::OpName::src0_modifiers)) return AMDGPU::NoRegister; Op1 = TII->getNamedOperand(*Sel, AMDGPU::OpName::src0); Op2 = TII->getNamedOperand(*Sel, AMDGPU::OpName::src1); MachineOperand *CC = TII->getNamedOperand(*Sel, AMDGPU::OpName::src2); if (!Op1->isImm() || !Op2->isImm() || !CC->isReg() || Op1->getImm() != 0 || Op2->getImm() != 1) return AMDGPU::NoRegister; LLVM_DEBUG(dbgs() << "Folding sequence:\n\t" << *Sel << '\t' << *Cmp << '\t' << *And); unsigned CCReg = CC->getReg(); LIS->RemoveMachineInstrFromMaps(*And); MachineInstr *Andn2 = BuildMI(MBB, *And, And->getDebugLoc(), TII->get(Andn2Opc), And->getOperand(0).getReg()) .addReg(ExecReg) .addReg(CCReg, CC->getSubReg()); And->eraseFromParent(); LIS->InsertMachineInstrInMaps(*Andn2); LLVM_DEBUG(dbgs() << "=>\n\t" << *Andn2 << '\n'); // Try to remove compare. Cmp value should not used in between of cmp // and s_and_b64 if VCC or just unused if any other register. if ((TargetRegisterInfo::isVirtualRegister(CmpReg) && MRI.use_nodbg_empty(CmpReg)) || (CmpReg == CondReg && std::none_of(std::next(Cmp->getIterator()), Andn2->getIterator(), [&](const MachineInstr &MI) { return MI.readsRegister(CondReg, TRI); }))) { LLVM_DEBUG(dbgs() << "Erasing: " << *Cmp << '\n'); LIS->RemoveMachineInstrFromMaps(*Cmp); Cmp->eraseFromParent(); // Try to remove v_cndmask_b32. if (TargetRegisterInfo::isVirtualRegister(SelReg) && MRI.use_nodbg_empty(SelReg)) { LLVM_DEBUG(dbgs() << "Erasing: " << *Sel << '\n'); LIS->RemoveMachineInstrFromMaps(*Sel); Sel->eraseFromParent(); } } return CCReg; } bool SIOptimizeExecMaskingPreRA::runOnMachineFunction(MachineFunction &MF) { if (skipFunction(MF.getFunction())) return false; const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); const SIRegisterInfo *TRI = ST.getRegisterInfo(); const SIInstrInfo *TII = ST.getInstrInfo(); MachineRegisterInfo &MRI = MF.getRegInfo(); LiveIntervals *LIS = &getAnalysis<LiveIntervals>(); DenseSet<unsigned> RecalcRegs({AMDGPU::EXEC_LO, AMDGPU::EXEC_HI}); bool Changed = false; for (MachineBasicBlock &MBB : MF) { if (unsigned Reg = optimizeVcndVcmpPair(MBB, ST, MRI, LIS)) { RecalcRegs.insert(Reg); RecalcRegs.insert(AMDGPU::VCC_LO); RecalcRegs.insert(AMDGPU::VCC_HI); RecalcRegs.insert(AMDGPU::SCC); Changed = true; } // Try to remove unneeded instructions before s_endpgm. if (MBB.succ_empty()) { if (MBB.empty()) continue; // Skip this if the endpgm has any implicit uses, otherwise we would need // to be careful to update / remove them. // S_ENDPGM always has a single imm operand that is not used other than to // end up in the encoding MachineInstr &Term = MBB.back(); if (Term.getOpcode() != AMDGPU::S_ENDPGM || Term.getNumOperands() != 1) continue; SmallVector<MachineBasicBlock*, 4> Blocks({&MBB}); while (!Blocks.empty()) { auto CurBB = Blocks.pop_back_val(); auto I = CurBB->rbegin(), E = CurBB->rend(); if (I != E) { if (I->isUnconditionalBranch() || I->getOpcode() == AMDGPU::S_ENDPGM) ++I; else if (I->isBranch()) continue; } while (I != E) { if (I->isDebugInstr()) { I = std::next(I); continue; } if (I->mayStore() || I->isBarrier() || I->isCall() || I->hasUnmodeledSideEffects() || I->hasOrderedMemoryRef()) break; LLVM_DEBUG(dbgs() << "Removing no effect instruction: " << *I << '\n'); for (auto &Op : I->operands()) { if (Op.isReg()) RecalcRegs.insert(Op.getReg()); } auto Next = std::next(I); LIS->RemoveMachineInstrFromMaps(*I); I->eraseFromParent(); I = Next; Changed = true; } if (I != E) continue; // Try to ascend predecessors. for (auto *Pred : CurBB->predecessors()) { if (Pred->succ_size() == 1) Blocks.push_back(Pred); } } continue; } // Try to collapse adjacent endifs. auto Lead = MBB.begin(), E = MBB.end(); if (MBB.succ_size() != 1 || Lead == E || !isEndCF(*Lead, TRI)) continue; const MachineBasicBlock* Succ = *MBB.succ_begin(); if (!MBB.isLayoutSuccessor(Succ)) continue; auto I = std::next(Lead); for ( ; I != E; ++I) if (!TII->isSALU(*I) || I->readsRegister(AMDGPU::EXEC, TRI)) break; if (I != E) continue; const auto NextLead = Succ->begin(); if (NextLead == Succ->end() || !isEndCF(*NextLead, TRI) || !getOrExecSource(*NextLead, *TII, MRI)) continue; LLVM_DEBUG(dbgs() << "Redundant EXEC = S_OR_B64 found: " << *Lead << '\n'); auto SaveExec = getOrExecSource(*Lead, *TII, MRI); unsigned SaveExecReg = getOrNonExecReg(*Lead, *TII); for (auto &Op : Lead->operands()) { if (Op.isReg()) RecalcRegs.insert(Op.getReg()); } LIS->RemoveMachineInstrFromMaps(*Lead); Lead->eraseFromParent(); if (SaveExecReg) { LIS->removeInterval(SaveExecReg); LIS->createAndComputeVirtRegInterval(SaveExecReg); } Changed = true; // If the only use of saved exec in the removed instruction is S_AND_B64 // fold the copy now. if (!SaveExec || !SaveExec->isFullCopy()) continue; unsigned SavedExec = SaveExec->getOperand(0).getReg(); bool SafeToReplace = true; for (auto& U : MRI.use_nodbg_instructions(SavedExec)) { if (U.getParent() != SaveExec->getParent()) { SafeToReplace = false; break; } LLVM_DEBUG(dbgs() << "Redundant EXEC COPY: " << *SaveExec << '\n'); } if (SafeToReplace) { LIS->RemoveMachineInstrFromMaps(*SaveExec); SaveExec->eraseFromParent(); MRI.replaceRegWith(SavedExec, AMDGPU::EXEC); LIS->removeInterval(SavedExec); } } if (Changed) { for (auto Reg : RecalcRegs) { if (TargetRegisterInfo::isVirtualRegister(Reg)) { LIS->removeInterval(Reg); if (!MRI.reg_empty(Reg)) LIS->createAndComputeVirtRegInterval(Reg); } else { LIS->removeAllRegUnitsForPhysReg(Reg); } } } return Changed; } <commit_msg>AMDGPU: Remove unnecessary check for isFullCopy<commit_after>//===-- SIOptimizeExecMaskingPreRA.cpp ------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // /// \file /// This pass removes redundant S_OR_B64 instructions enabling lanes in /// the exec. If two SI_END_CF (lowered as S_OR_B64) come together without any /// vector instructions between them we can only keep outer SI_END_CF, given /// that CFG is structured and exec bits of the outer end statement are always /// not less than exec bit of the inner one. /// /// This needs to be done before the RA to eliminate saved exec bits registers /// but after register coalescer to have no vector registers copies in between /// of different end cf statements. /// //===----------------------------------------------------------------------===// #include "AMDGPU.h" #include "AMDGPUSubtarget.h" #include "SIInstrInfo.h" #include "MCTargetDesc/AMDGPUMCTargetDesc.h" #include "llvm/CodeGen/LiveIntervals.h" #include "llvm/CodeGen/MachineFunctionPass.h" using namespace llvm; #define DEBUG_TYPE "si-optimize-exec-masking-pre-ra" namespace { class SIOptimizeExecMaskingPreRA : public MachineFunctionPass { public: static char ID; public: SIOptimizeExecMaskingPreRA() : MachineFunctionPass(ID) { initializeSIOptimizeExecMaskingPreRAPass(*PassRegistry::getPassRegistry()); } bool runOnMachineFunction(MachineFunction &MF) override; StringRef getPassName() const override { return "SI optimize exec mask operations pre-RA"; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<LiveIntervals>(); AU.setPreservesAll(); MachineFunctionPass::getAnalysisUsage(AU); } }; } // End anonymous namespace. INITIALIZE_PASS_BEGIN(SIOptimizeExecMaskingPreRA, DEBUG_TYPE, "SI optimize exec mask operations pre-RA", false, false) INITIALIZE_PASS_DEPENDENCY(LiveIntervals) INITIALIZE_PASS_END(SIOptimizeExecMaskingPreRA, DEBUG_TYPE, "SI optimize exec mask operations pre-RA", false, false) char SIOptimizeExecMaskingPreRA::ID = 0; char &llvm::SIOptimizeExecMaskingPreRAID = SIOptimizeExecMaskingPreRA::ID; FunctionPass *llvm::createSIOptimizeExecMaskingPreRAPass() { return new SIOptimizeExecMaskingPreRA(); } static bool isEndCF(const MachineInstr& MI, const SIRegisterInfo* TRI) { return MI.getOpcode() == AMDGPU::S_OR_B64 && MI.modifiesRegister(AMDGPU::EXEC, TRI); } static bool isFullExecCopy(const MachineInstr& MI) { return MI.getOperand(1).getReg() == AMDGPU::EXEC; } static unsigned getOrNonExecReg(const MachineInstr &MI, const SIInstrInfo &TII) { auto Op = TII.getNamedOperand(MI, AMDGPU::OpName::src1); if (Op->isReg() && Op->getReg() != AMDGPU::EXEC) return Op->getReg(); Op = TII.getNamedOperand(MI, AMDGPU::OpName::src0); if (Op->isReg() && Op->getReg() != AMDGPU::EXEC) return Op->getReg(); return AMDGPU::NoRegister; } static MachineInstr* getOrExecSource(const MachineInstr &MI, const SIInstrInfo &TII, const MachineRegisterInfo &MRI) { auto SavedExec = getOrNonExecReg(MI, TII); if (SavedExec == AMDGPU::NoRegister) return nullptr; auto SaveExecInst = MRI.getUniqueVRegDef(SavedExec); if (!SaveExecInst || !isFullExecCopy(*SaveExecInst)) return nullptr; return SaveExecInst; } // Optimize sequence // %sel = V_CNDMASK_B32_e64 0, 1, %cc // %cmp = V_CMP_NE_U32 1, %1 // $vcc = S_AND_B64 $exec, %cmp // S_CBRANCH_VCC[N]Z // => // $vcc = S_ANDN2_B64 $exec, %cc // S_CBRANCH_VCC[N]Z // // It is the negation pattern inserted by DAGCombiner::visitBRCOND() in the // rebuildSetCC(). We start with S_CBRANCH to avoid exhaustive search, but // only 3 first instructions are really needed. S_AND_B64 with exec is a // required part of the pattern since V_CNDMASK_B32 writes zeroes for inactive // lanes. // // Returns %cc register on success. static unsigned optimizeVcndVcmpPair(MachineBasicBlock &MBB, const GCNSubtarget &ST, MachineRegisterInfo &MRI, LiveIntervals *LIS) { const SIRegisterInfo *TRI = ST.getRegisterInfo(); const SIInstrInfo *TII = ST.getInstrInfo(); const unsigned AndOpc = AMDGPU::S_AND_B64; const unsigned Andn2Opc = AMDGPU::S_ANDN2_B64; const unsigned CondReg = AMDGPU::VCC; const unsigned ExecReg = AMDGPU::EXEC; auto I = llvm::find_if(MBB.terminators(), [](const MachineInstr &MI) { unsigned Opc = MI.getOpcode(); return Opc == AMDGPU::S_CBRANCH_VCCZ || Opc == AMDGPU::S_CBRANCH_VCCNZ; }); if (I == MBB.terminators().end()) return AMDGPU::NoRegister; auto *And = TRI->findReachingDef(CondReg, AMDGPU::NoSubRegister, *I, MRI, LIS); if (!And || And->getOpcode() != AndOpc || !And->getOperand(1).isReg() || !And->getOperand(2).isReg()) return AMDGPU::NoRegister; MachineOperand *AndCC = &And->getOperand(1); unsigned CmpReg = AndCC->getReg(); unsigned CmpSubReg = AndCC->getSubReg(); if (CmpReg == ExecReg) { AndCC = &And->getOperand(2); CmpReg = AndCC->getReg(); CmpSubReg = AndCC->getSubReg(); } else if (And->getOperand(2).getReg() != ExecReg) { return AMDGPU::NoRegister; } auto *Cmp = TRI->findReachingDef(CmpReg, CmpSubReg, *And, MRI, LIS); if (!Cmp || !(Cmp->getOpcode() == AMDGPU::V_CMP_NE_U32_e32 || Cmp->getOpcode() == AMDGPU::V_CMP_NE_U32_e64) || Cmp->getParent() != And->getParent()) return AMDGPU::NoRegister; MachineOperand *Op1 = TII->getNamedOperand(*Cmp, AMDGPU::OpName::src0); MachineOperand *Op2 = TII->getNamedOperand(*Cmp, AMDGPU::OpName::src1); if (Op1->isImm() && Op2->isReg()) std::swap(Op1, Op2); if (!Op1->isReg() || !Op2->isImm() || Op2->getImm() != 1) return AMDGPU::NoRegister; unsigned SelReg = Op1->getReg(); auto *Sel = TRI->findReachingDef(SelReg, Op1->getSubReg(), *Cmp, MRI, LIS); if (!Sel || Sel->getOpcode() != AMDGPU::V_CNDMASK_B32_e64) return AMDGPU::NoRegister; if (TII->hasModifiersSet(*Sel, AMDGPU::OpName::src0_modifiers) || TII->hasModifiersSet(*Sel, AMDGPU::OpName::src0_modifiers)) return AMDGPU::NoRegister; Op1 = TII->getNamedOperand(*Sel, AMDGPU::OpName::src0); Op2 = TII->getNamedOperand(*Sel, AMDGPU::OpName::src1); MachineOperand *CC = TII->getNamedOperand(*Sel, AMDGPU::OpName::src2); if (!Op1->isImm() || !Op2->isImm() || !CC->isReg() || Op1->getImm() != 0 || Op2->getImm() != 1) return AMDGPU::NoRegister; LLVM_DEBUG(dbgs() << "Folding sequence:\n\t" << *Sel << '\t' << *Cmp << '\t' << *And); unsigned CCReg = CC->getReg(); LIS->RemoveMachineInstrFromMaps(*And); MachineInstr *Andn2 = BuildMI(MBB, *And, And->getDebugLoc(), TII->get(Andn2Opc), And->getOperand(0).getReg()) .addReg(ExecReg) .addReg(CCReg, CC->getSubReg()); And->eraseFromParent(); LIS->InsertMachineInstrInMaps(*Andn2); LLVM_DEBUG(dbgs() << "=>\n\t" << *Andn2 << '\n'); // Try to remove compare. Cmp value should not used in between of cmp // and s_and_b64 if VCC or just unused if any other register. if ((TargetRegisterInfo::isVirtualRegister(CmpReg) && MRI.use_nodbg_empty(CmpReg)) || (CmpReg == CondReg && std::none_of(std::next(Cmp->getIterator()), Andn2->getIterator(), [&](const MachineInstr &MI) { return MI.readsRegister(CondReg, TRI); }))) { LLVM_DEBUG(dbgs() << "Erasing: " << *Cmp << '\n'); LIS->RemoveMachineInstrFromMaps(*Cmp); Cmp->eraseFromParent(); // Try to remove v_cndmask_b32. if (TargetRegisterInfo::isVirtualRegister(SelReg) && MRI.use_nodbg_empty(SelReg)) { LLVM_DEBUG(dbgs() << "Erasing: " << *Sel << '\n'); LIS->RemoveMachineInstrFromMaps(*Sel); Sel->eraseFromParent(); } } return CCReg; } bool SIOptimizeExecMaskingPreRA::runOnMachineFunction(MachineFunction &MF) { if (skipFunction(MF.getFunction())) return false; const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); const SIRegisterInfo *TRI = ST.getRegisterInfo(); const SIInstrInfo *TII = ST.getInstrInfo(); MachineRegisterInfo &MRI = MF.getRegInfo(); LiveIntervals *LIS = &getAnalysis<LiveIntervals>(); DenseSet<unsigned> RecalcRegs({AMDGPU::EXEC_LO, AMDGPU::EXEC_HI}); bool Changed = false; for (MachineBasicBlock &MBB : MF) { if (unsigned Reg = optimizeVcndVcmpPair(MBB, ST, MRI, LIS)) { RecalcRegs.insert(Reg); RecalcRegs.insert(AMDGPU::VCC_LO); RecalcRegs.insert(AMDGPU::VCC_HI); RecalcRegs.insert(AMDGPU::SCC); Changed = true; } // Try to remove unneeded instructions before s_endpgm. if (MBB.succ_empty()) { if (MBB.empty()) continue; // Skip this if the endpgm has any implicit uses, otherwise we would need // to be careful to update / remove them. // S_ENDPGM always has a single imm operand that is not used other than to // end up in the encoding MachineInstr &Term = MBB.back(); if (Term.getOpcode() != AMDGPU::S_ENDPGM || Term.getNumOperands() != 1) continue; SmallVector<MachineBasicBlock*, 4> Blocks({&MBB}); while (!Blocks.empty()) { auto CurBB = Blocks.pop_back_val(); auto I = CurBB->rbegin(), E = CurBB->rend(); if (I != E) { if (I->isUnconditionalBranch() || I->getOpcode() == AMDGPU::S_ENDPGM) ++I; else if (I->isBranch()) continue; } while (I != E) { if (I->isDebugInstr()) { I = std::next(I); continue; } if (I->mayStore() || I->isBarrier() || I->isCall() || I->hasUnmodeledSideEffects() || I->hasOrderedMemoryRef()) break; LLVM_DEBUG(dbgs() << "Removing no effect instruction: " << *I << '\n'); for (auto &Op : I->operands()) { if (Op.isReg()) RecalcRegs.insert(Op.getReg()); } auto Next = std::next(I); LIS->RemoveMachineInstrFromMaps(*I); I->eraseFromParent(); I = Next; Changed = true; } if (I != E) continue; // Try to ascend predecessors. for (auto *Pred : CurBB->predecessors()) { if (Pred->succ_size() == 1) Blocks.push_back(Pred); } } continue; } // Try to collapse adjacent endifs. auto Lead = MBB.begin(), E = MBB.end(); if (MBB.succ_size() != 1 || Lead == E || !isEndCF(*Lead, TRI)) continue; const MachineBasicBlock* Succ = *MBB.succ_begin(); if (!MBB.isLayoutSuccessor(Succ)) continue; auto I = std::next(Lead); for ( ; I != E; ++I) if (!TII->isSALU(*I) || I->readsRegister(AMDGPU::EXEC, TRI)) break; if (I != E) continue; const auto NextLead = Succ->begin(); if (NextLead == Succ->end() || !isEndCF(*NextLead, TRI) || !getOrExecSource(*NextLead, *TII, MRI)) continue; LLVM_DEBUG(dbgs() << "Redundant EXEC = S_OR_B64 found: " << *Lead << '\n'); auto SaveExec = getOrExecSource(*Lead, *TII, MRI); unsigned SaveExecReg = getOrNonExecReg(*Lead, *TII); for (auto &Op : Lead->operands()) { if (Op.isReg()) RecalcRegs.insert(Op.getReg()); } LIS->RemoveMachineInstrFromMaps(*Lead); Lead->eraseFromParent(); if (SaveExecReg) { LIS->removeInterval(SaveExecReg); LIS->createAndComputeVirtRegInterval(SaveExecReg); } Changed = true; // If the only use of saved exec in the removed instruction is S_AND_B64 // fold the copy now. if (!SaveExec || !SaveExec->isFullCopy()) continue; unsigned SavedExec = SaveExec->getOperand(0).getReg(); bool SafeToReplace = true; for (auto& U : MRI.use_nodbg_instructions(SavedExec)) { if (U.getParent() != SaveExec->getParent()) { SafeToReplace = false; break; } LLVM_DEBUG(dbgs() << "Redundant EXEC COPY: " << *SaveExec << '\n'); } if (SafeToReplace) { LIS->RemoveMachineInstrFromMaps(*SaveExec); SaveExec->eraseFromParent(); MRI.replaceRegWith(SavedExec, AMDGPU::EXEC); LIS->removeInterval(SavedExec); } } if (Changed) { for (auto Reg : RecalcRegs) { if (TargetRegisterInfo::isVirtualRegister(Reg)) { LIS->removeInterval(Reg); if (!MRI.reg_empty(Reg)) LIS->createAndComputeVirtRegInterval(Reg); } else { LIS->removeAllRegUnitsForPhysReg(Reg); } } } return Changed; } <|endoftext|>
<commit_before>// // interpreter.cpp // SimpleInformationRetrievalTools // // Created by ryecao on 6/9/15. // Copyright (c) 2015 Zhendong Cao. All rights reserved. // #include "Interpreter.h" #include <iostream> #include <sstream> #include <string> #include <cctype> using namespace std; vector<pair<string,string> > Interpreter::ProcessQuery(InvertedIndex* II, const string query){ istringstream query_stream(query); string word; vector<int> bool_op_pos; vector<string> query_vector; vector<string> parameters; vector<pair<string,string> > result; bool search_type_set = false; bool synonym_set = false; bool top_k_set = false; int pos = 0; while(query_stream >> word){ if (word == "AND" || word == "OR" || word == "NOT" ){ _search_type = BOOL; search_type_set = true; bool_op_pos.push_back(pos); } if (word[0] == '-') { parameters.push_back(word); } else{ query_vector.push_back(II->trim(word)); } pos++; } for (auto &para:parameters){ if(search_type_set == false){ if (para == "-PHRASE_SEARCH"){ _search_type = PHRASE_SEARCH; search_type_set = true; } } if (synonym_set == false){ if (para == "-SYNONYM_ON"){ _synonym_mode = SYNONYM_ON; synonym_set = true; } else if (para == "-SYNONYM_OFF"){ _synonym_mode = SYNONYM_OFF; synonym_set = true; } } if (top_k_set == false){ if ( para == "-TOP_K_OFF"){ _top_k_mode = TOP_K_OFF; top_k_set = true; } if ( para == "-TOP_K_HEAP"){ _top_k_mode = TOP_K_HEAP; top_k_set = true; } if ( para == "-TOP_K_CHAMPION_LIST"){ _top_k_mode = TOP_K_CHAMPION_LIST; top_k_set = true; } if ( para == "-TOP_K_STATIC_QUALITY_SCORE"){ _top_k_mode = TOP_K_STATIC_QUALITY_SCORE; top_k_set = true; } if ( para == "-TOP_K_CLUSTER_PRUNING"){ _top_k_mode = TOP_K_CLUSTER_PRUNING; top_k_set = true; } } } if (_search_type == BOOL){ string segment = ""; int bool_pos = 0; for (int i = 0; i < query_vector.size(); ++i){ if(i == bool_op_pos[bool_pos]){ if (segment != ""){ if (bool_pos == 0){ result.push_back(make_pair("AND",segment.substr(0, segment.size()-1))); } else{ string str = query_vector[bool_op_pos[bool_pos-1]]; transform(str.begin(), str.end(), str.begin(), ::toupper); result.push_back(make_pair(str, segment.substr(0, segment.size()-1))); } } bool_pos++; segment = ""; continue; } segment += query_vector[i] + " "; } string str = query_vector[bool_op_pos[bool_pos-1]]; transform(str.begin(), str.end(), str.begin(), ::toupper); result.push_back(make_pair(str, segment.substr(0, segment.size()-1))); } else{ for (auto &q:query_vector){ result.push_back(make_pair("AND", q)); } } std::vector<pair<string, string> > filtered_result; for(auto &t: result){ if (!II->CheckStopWord(t.second)){ filtered_result.push_back(t); } } // for(auto &t: result){ // cout<<"1op: "<<t.first<<"term: "<<t.second<<endl; // } // for(auto &t: filtered_result){ // cout<<"2op: "<<t.first<<"term: "<<t.second<<endl; // } return filtered_result; } <commit_msg>mode modified<commit_after>// // interpreter.cpp // SimpleInformationRetrievalTools // // Created by ryecao on 6/9/15. // Copyright (c) 2015 Zhendong Cao. All rights reserved. // #include "Interpreter.h" #include <iostream> #include <sstream> #include <string> #include <cctype> using namespace std; vector<pair<string,string> > Interpreter::ProcessQuery(InvertedIndex* II, const string query){ istringstream query_stream(query); string word; vector<int> bool_op_pos; vector<string> query_vector; vector<string> parameters; vector<pair<string,string> > result; _search_type = NORMAL; _top_k_mode = TOP_K_OFF; _synonym_mode = SYNONYM_OFF; bool search_type_set = false; bool synonym_set = false; bool top_k_set = false; int pos = 0; while(query_stream >> word){ if (word == "AND" || word == "OR" || word == "NOT" ){ _search_type = BOOL; search_type_set = true; bool_op_pos.push_back(pos); } if (word[0] == '-') { parameters.push_back(word); } else{ query_vector.push_back(II->trim(word)); } pos++; } for (auto &para:parameters){ if(search_type_set == false){ if (para == "-PHRASE_SEARCH"){ _search_type = PHRASE_SEARCH; search_type_set = true; } } if (synonym_set == false){ if (para == "-SYNONYM_ON"){ _synonym_mode = SYNONYM_ON; synonym_set = true; } else if (para == "-SYNONYM_OFF"){ _synonym_mode = SYNONYM_OFF; synonym_set = true; } } if (top_k_set == false){ if ( para == "-TOP_K_OFF"){ _top_k_mode = TOP_K_OFF; top_k_set = true; } if ( para == "-TOP_K_HEAP"){ _top_k_mode = TOP_K_HEAP; top_k_set = true; } if ( para == "-TOP_K_CHAMPION_LIST"){ _top_k_mode = TOP_K_CHAMPION_LIST; top_k_set = true; } if ( para == "-TOP_K_STATIC_QUALITY_SCORE"){ _top_k_mode = TOP_K_STATIC_QUALITY_SCORE; top_k_set = true; } if ( para == "-TOP_K_CLUSTER_PRUNING"){ _top_k_mode = TOP_K_CLUSTER_PRUNING; top_k_set = true; } } } if (_search_type == BOOL){ string segment = ""; int bool_pos = 0; for (int i = 0; i < query_vector.size(); ++i){ if(i == bool_op_pos[bool_pos]){ if (segment != ""){ if (bool_pos == 0){ result.push_back(make_pair("AND",segment.substr(0, segment.size()-1))); } else{ string str = query_vector[bool_op_pos[bool_pos-1]]; transform(str.begin(), str.end(), str.begin(), ::toupper); result.push_back(make_pair(str, segment.substr(0, segment.size()-1))); } } bool_pos++; segment = ""; continue; } segment += query_vector[i] + " "; } string str = query_vector[bool_op_pos[bool_pos-1]]; transform(str.begin(), str.end(), str.begin(), ::toupper); result.push_back(make_pair(str, segment.substr(0, segment.size()-1))); } else{ for (auto &q:query_vector){ result.push_back(make_pair("AND", q)); } } std::vector<pair<string, string> > filtered_result; for(auto &t: result){ if (!II->CheckStopWord(t.second)){ filtered_result.push_back(t); } } // for(auto &t: result){ // cout<<"1op: "<<t.first<<"term: "<<t.second<<endl; // } // for(auto &t: filtered_result){ // cout<<"2op: "<<t.first<<"term: "<<t.second<<endl; // } return filtered_result; } <|endoftext|>
<commit_before>#include "ConstantMaterial.h" template <> InputParameters validParams<ConstantMaterial>() { InputParameters params = validParams<Material>(); params.addParam<Real>("value", 0., "Constant value being assigned into the property"); params.addRequiredParam<std::string>("property_name", "The property name to declare"); params.addCoupledVar( "derivative_vars", "Names of variables for which to create (zero) material derivative properties"); return params; } ConstantMaterial::ConstantMaterial(const InputParameters & parameters) : DerivativeMaterialInterface<Material>(parameters), _value(getParam<Real>("value")), _property_name(getParam<std::string>("property_name")), _property(declareProperty<Real>(_property_name)), _n_derivative_vars(coupledComponents("derivative_vars")) { // get references to new material property derivatives _derivative_properties.resize(_n_derivative_vars); for (unsigned int i = 0; i < _n_derivative_vars; ++i) _derivative_properties[i] = &declarePropertyDerivative<Real>(_property_name, getVar("derivative_vars", i)->name()); } void ConstantMaterial::computeQpProperties() { _property[_qp] = _value; for (unsigned int i = 0; i < _n_derivative_vars; ++i) (*_derivative_properties[i])[_qp] = 0; } <commit_msg>Register objects in individual source files instead of RELAP7App.C<commit_after>#include "ConstantMaterial.h" registerMooseObject("RELAP7App", ConstantMaterial); template <> InputParameters validParams<ConstantMaterial>() { InputParameters params = validParams<Material>(); params.addParam<Real>("value", 0., "Constant value being assigned into the property"); params.addRequiredParam<std::string>("property_name", "The property name to declare"); params.addCoupledVar( "derivative_vars", "Names of variables for which to create (zero) material derivative properties"); return params; } ConstantMaterial::ConstantMaterial(const InputParameters & parameters) : DerivativeMaterialInterface<Material>(parameters), _value(getParam<Real>("value")), _property_name(getParam<std::string>("property_name")), _property(declareProperty<Real>(_property_name)), _n_derivative_vars(coupledComponents("derivative_vars")) { // get references to new material property derivatives _derivative_properties.resize(_n_derivative_vars); for (unsigned int i = 0; i < _n_derivative_vars; ++i) _derivative_properties[i] = &declarePropertyDerivative<Real>(_property_name, getVar("derivative_vars", i)->name()); } void ConstantMaterial::computeQpProperties() { _property[_qp] = _value; for (unsigned int i = 0; i < _n_derivative_vars; ++i) (*_derivative_properties[i])[_qp] = 0; } <|endoftext|>
<commit_before>/* Calendar access for KDE Alarm Daemon. This file is part of the KDE alarm daemon. Copyright (c) 2001 David Jarvie <software@astrojar.org.uk> 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., 675 Mass Ave, Cambridge, MA 02139, 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 <kstandarddirs.h> #include <ksimpleconfig.h> #include <kio/netaccess.h> #include <kdebug.h> #include "adcalendarbase.h" ADCalendarBase::EventsMap ADCalendarBase::eventsHandled_; ADCalendarBase::ADCalendarBase(const QString& url, const QCString& appname, Type type) : urlString_(url), appName_(appname), actionType_(type), loaded_(false), mUnregistered(false) { if (appName_ == "korganizer") { KConfig cfg( locate( "config", "korganizerrc" ) ); cfg.setGroup( "Time & Date" ); QString tz = cfg.readEntry( "TimeZoneId" ); kdDebug(5900) << "ADCalendarBase(): tz: " << tz << endl; setTimeZoneId( cfg.readEntry( "TimeZoneId" ) ); } } /* * Load the calendar file. */ bool ADCalendarBase::loadFile_(const QCString& appName) { loaded_ = false; KURL url(urlString_); QString tmpFile; if (KIO::NetAccess::download(url, tmpFile)) { kdDebug(5900) << "--- Downloaded to " << tmpFile << endl; loaded_ = load(tmpFile); KIO::NetAccess::removeTempFile(tmpFile); if (!loaded_) kdDebug(5900) << "ADCalendarBase::loadFile_(): Error loading calendar file '" << tmpFile << "'\n"; else { // Remove all now non-existent events from the handled list for (EventsMap::Iterator it = eventsHandled_.begin(); it != eventsHandled_.end(); ) { if (it.data().calendarURL == urlString_ && !event(it.key())) { // Event belonged to this calendar, but can't find it any more EventsMap::Iterator i = it; ++it; // prevent iterator becoming invalid with remove() eventsHandled_.remove(i); } else ++it; } } } else if (!appName.isEmpty()) { #if TODO_handle_download_error KMessageBox::error(0L, i18n("Cannot download calendar from\n%1.") .arg(url.prettyURL()), appName); #endif } return loaded_; } void ADCalendarBase::dump() const { kdDebug(5900) << " <calendar>" << endl; kdDebug(5900) << " <url>" << urlString() << "</url>" << endl; kdDebug(5900) << " <appname>" << appName() << "</appname>" << endl; if ( loaded() ) kdDebug(5900) << " <loaded/>" << endl; kdDebug(5900) << " <actiontype>" << int(actionType()) << "</actiontype>" << endl; if (enabled() ) kdDebug(5900) << " <enabled/>" << endl; else kdDebug(5900) << " <disabled/>" << endl; if (available()) kdDebug(5900) << " <available/>" << endl; kdDebug(5900) << " </calendar>" << endl; } <commit_msg>Patch from Randy Pearson which fixed kalarmd not using korganizer's time zone<commit_after>/* Calendar access for KDE Alarm Daemon. This file is part of the KDE alarm daemon. Copyright (c) 2001 David Jarvie <software@astrojar.org.uk> 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., 675 Mass Ave, Cambridge, MA 02139, 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 <kstandarddirs.h> #include <ksimpleconfig.h> #include <kio/netaccess.h> #include <kdebug.h> #include "adcalendarbase.h" ADCalendarBase::EventsMap ADCalendarBase::eventsHandled_; ADCalendarBase::ADCalendarBase(const QString& url, const QCString& appname, Type type) : urlString_(url), appName_(appname), actionType_(type), loaded_(false), mUnregistered(false) { if (appName_ == "korgac") { KConfig cfg( locate( "config", "korganizerrc" ) ); cfg.setGroup( "Time & Date" ); QString tz = cfg.readEntry( "TimeZoneId" ); kdDebug(5900) << "ADCalendarBase(): tz: " << tz << endl; setTimeZoneId( cfg.readEntry( "TimeZoneId" ) ); } } /* * Load the calendar file. */ bool ADCalendarBase::loadFile_(const QCString& appName) { loaded_ = false; KURL url(urlString_); QString tmpFile; if (KIO::NetAccess::download(url, tmpFile)) { kdDebug(5900) << "--- Downloaded to " << tmpFile << endl; loaded_ = load(tmpFile); KIO::NetAccess::removeTempFile(tmpFile); if (!loaded_) kdDebug(5900) << "ADCalendarBase::loadFile_(): Error loading calendar file '" << tmpFile << "'\n"; else { // Remove all now non-existent events from the handled list for (EventsMap::Iterator it = eventsHandled_.begin(); it != eventsHandled_.end(); ) { if (it.data().calendarURL == urlString_ && !event(it.key())) { // Event belonged to this calendar, but can't find it any more EventsMap::Iterator i = it; ++it; // prevent iterator becoming invalid with remove() eventsHandled_.remove(i); } else ++it; } } } else if (!appName.isEmpty()) { #if TODO_handle_download_error KMessageBox::error(0L, i18n("Cannot download calendar from\n%1.") .arg(url.prettyURL()), appName); #endif } return loaded_; } void ADCalendarBase::dump() const { kdDebug(5900) << " <calendar>" << endl; kdDebug(5900) << " <url>" << urlString() << "</url>" << endl; kdDebug(5900) << " <appname>" << appName() << "</appname>" << endl; if ( loaded() ) kdDebug(5900) << " <loaded/>" << endl; kdDebug(5900) << " <actiontype>" << int(actionType()) << "</actiontype>" << endl; if (enabled() ) kdDebug(5900) << " <enabled/>" << endl; else kdDebug(5900) << " <disabled/>" << endl; if (available()) kdDebug(5900) << " <available/>" << endl; kdDebug(5900) << " </calendar>" << endl; } <|endoftext|>
<commit_before>// Include Radium base application and its simple Gui #include <Gui/BaseApplication.hpp> #include <Gui/RadiumWindow/SimpleWindowFactory.hpp> // include the core geometry/appearance interface #include <Core/Geometry/MeshPrimitives.hpp> // include the Engine/entity/component/system/animation interface #include <Engine/FrameInfo.hpp> #include <Engine/Scene/EntityManager.hpp> #include <Engine/Scene/GeometryComponent.hpp> #include <Engine/Scene/System.hpp> // include the task animation interface #include <Core/Tasks/Task.hpp> // include the Camera and default camera manager interface #include <Engine/Scene/CameraComponent.hpp> #include <Engine/Scene/DefaultCameraManager.hpp> // include the viewer to activate the camera #include <Gui/Viewer/CameraManipulator.hpp> #include <Gui/Viewer/Viewer.hpp> // To terminate the demo after 4 seconds #include <QTimer> using namespace Ra; using namespace Ra::Core; using namespace Ra::Engine; /* ---------------------------------------------------------------------------------------------- */ /* Simple animation system to move an entity */ /* ---------------------------------------------------------------------------------------------- */ //! [Define a simple animation system] /// This system will be added to the engine. /// Every frame it will add a task to update the transformation of the attached entities. class EntityAnimationSystem : public Scene::System { public: void addEntity( Scene::Entity* e ) { m_animatedEntities.push_back( e ); } virtual void generateTasks( TaskQueue* q, const FrameInfo& info ) override { // get the entity of the first component auto t = info.m_animationTime; for ( auto e : m_animatedEntities ) { // Transform the entity q->registerTask( new Ra::Core::FunctionTask( [e, t]() { Transform T = e->getTransform(); T.translate( Vector3 {std::cos( t ) * 0.025, -std::sin( t ) * 0.025, 0_ra} ); e->setTransform( T ); }, "move" ) ); } } private: std::vector<Scene::Entity*> m_animatedEntities; }; //! [Define a simple animation system] /* ---------------------------------------------------------------------------------------------- */ /* main function that build the demo scene */ /* ---------------------------------------------------------------------------------------------- */ int main( int argc, char* argv[] ) { //! [Creating the application] Gui::BaseApplication app( argc, argv ); app.initialize( Ra::Gui::SimpleWindowFactory {} ); //! [Creating the application] //![Parameterize the Engine time loop] app.m_engine->setEndTime( std::numeric_limits<Scalar>::max() ); app.m_engine->setRealTime( true ); app.m_engine->play( true ); //![Parameterize the Engine time loop] //! [Cache the camera manager] auto cameraManager = static_cast<Scene::DefaultCameraManager*>( app.m_engine->getSystem( "DefaultCameraManager" ) ); //! [Cache the camera manager] //! [Add usefull custom key events] auto callback = [cameraManager]( QKeyEvent* event ) { cameraManager->activate( event->key() - '0' ); }; app.m_mainWindow->getViewer()->addKeyPressEventAction( "switchCam0", "Key_0", "ShiftModifier", "", "false", callback ); app.m_mainWindow->getViewer()->addKeyPressEventAction( "switchCam1", "Key_1", "ShiftModifier", "", "false", callback ); //! [Add usefull custom key events] //! [Create the camera animation system demonstrator] auto animationSystem = new EntityAnimationSystem; app.m_engine->registerSystem( "Simple animation system", animationSystem ); //! [Create the demo animation system] //! [Create the demo fixed component] { //! [Create the engine entity for the fixed component] auto e = app.m_engine->getEntityManager()->createEntity( "Fixed cube" ); //! [Create the engine entity for the fixed component] //! [Creating the cube] auto cube = Geometry::makeSharpBox( {0.5f, 0.5f, 0.5f}, Utils::Color::Green() ); //! [Creating the Cube] //! [Create a geometry component with the cube] auto c = new Scene::TriangleMeshComponent( "Fixed cube geometry", e, std::move( cube ), nullptr ); //! [Create a geometry component with the cube] } //! [Create the demo fixed component] //! [Create the demo animated entity/components] { //! [Create the animated entity ] auto e = app.m_engine->getEntityManager()->createEntity( "Animated entity" ); Transform transform( Translation {1, 1, 0} ); e->setTransform( transform ); e->swapTransformBuffers(); //! [Create the animated entity ] //! [Register the entity to the animation system ] animationSystem->addEntity( e ); //! [Register the entity to the animation system ] //! [attach components to the animated entity ] // an animated yellow cube auto cube = Geometry::makeSharpBox( {0.1f, 0.1f, 0.1f}, Ra::Core::Utils::Color::Yellow() ); new Scene::TriangleMeshComponent( "Fixed cube geometry", e, std::move( cube ), nullptr ); // an animated camera, thay is not the one active at startup. Use key '0' to activate auto camera = new Scene::CameraComponent( e, "Animated Camera" ); camera->initialize(); camera->getCamera()->setPosition( Vector3 {0.5, 0, 0} ); camera->getCamera()->setDirection( Vector3 {-1, 0, 0} ); camera->show( true ); cameraManager->addCamera( camera ); //! [attach components to the animated entity ] } //! [Create the demo animated entity/components] //! [Create the fixed reference camera] { auto e = app.m_engine->getEntityManager()->createEntity( "Fixed Camera" ); auto camera = new Scene::CameraComponent( e, "Camera" ); camera->initialize(); camera->getCamera()->setPosition( Vector3 {0, 0, 5} ); camera->getCamera()->setDirection( Vector3 {0, 0, -1} ); camera->show( true ); cameraManager->addCamera( camera ); // Activating a camera require 2 things : // ask the camera manager to activate the camera cameraManager->activate( cameraManager->getCameraIndex( camera ) ); // ask the CameraManipulator to update its camera info app.m_mainWindow->getViewer()->getCameraManipulator()->updateCamera(); } //! [Create the fixed reference camera] //! [Tell the window that something is to be displayed] // Do not call app.m_mainWindow->prepareDisplay(); as it replace the active camera by the // default one app.m_mainWindow->getViewer()->makeCurrent(); app.m_mainWindow->getViewer()->getRenderer()->buildAllRenderTechniques(); app.m_mainWindow->getViewer()->doneCurrent(); //! [Tell the window that something is to be displayed] #if 0 // terminate the app after 30 second (approximatively). // All interactions on the viewer can be done when the application executes. auto close_timer = new QTimer( &app ); close_timer->setInterval( 30000 ); QObject::connect( close_timer, &QTimer::timeout, [&app]() { app.appNeedsToQuit(); } ); close_timer->start(); #endif return app.exec(); } <commit_msg>add comments<commit_after>// Include Radium base application and its simple Gui #include <Gui/BaseApplication.hpp> #include <Gui/RadiumWindow/SimpleWindowFactory.hpp> // include the core geometry/appearance interface #include <Core/Geometry/MeshPrimitives.hpp> // include the Engine/entity/component/system/animation interface #include <Engine/FrameInfo.hpp> #include <Engine/Scene/EntityManager.hpp> #include <Engine/Scene/GeometryComponent.hpp> #include <Engine/Scene/System.hpp> // include the task animation interface #include <Core/Tasks/Task.hpp> // include the Camera and default camera manager interface #include <Engine/Scene/CameraComponent.hpp> #include <Engine/Scene/DefaultCameraManager.hpp> // include the viewer to activate the camera #include <Gui/Viewer/CameraManipulator.hpp> #include <Gui/Viewer/Viewer.hpp> // To terminate the demo after a given time #include <QTimer> using namespace Ra; using namespace Ra::Core; using namespace Ra::Engine; /* ---------------------------------------------------------------------------------------------- */ /* Simple animation system to move an entity */ /* ---------------------------------------------------------------------------------------------- */ //! [Define a simple animation system] /// This system will be added to the engine. /// Every frame it will add a task to update the transformation of the attached entities. class EntityAnimationSystem : public Scene::System { public: void addEntity( Scene::Entity* e ) { m_animatedEntities.push_back( e ); } virtual void generateTasks( TaskQueue* q, const FrameInfo& info ) override { // get the entity of the first component auto t = info.m_animationTime; for ( auto e : m_animatedEntities ) { // Transform the entity q->registerTask( new Ra::Core::FunctionTask( [e, t]() { Transform T = e->getTransform(); T.translate( Vector3 {std::cos( t ) * 0.025, -std::sin( t ) * 0.025, 0_ra} ); e->setTransform( T ); }, "move" ) ); } } private: std::vector<Scene::Entity*> m_animatedEntities; }; //! [Define a simple animation system] /* ---------------------------------------------------------------------------------------------- */ /* main function that build the demo scene */ /* ---------------------------------------------------------------------------------------------- */ int main( int argc, char* argv[] ) { //! [Creating the application] Gui::BaseApplication app( argc, argv ); app.initialize( Ra::Gui::SimpleWindowFactory {} ); //! [Creating the application] //![Parameterize the Engine time loop] app.m_engine->setEndTime( std::numeric_limits<Scalar>::max() ); app.m_engine->setRealTime( true ); app.m_engine->play( true ); //![Parameterize the Engine time loop] //! [Cache the camera manager] auto cameraManager = static_cast<Scene::DefaultCameraManager*>( app.m_engine->getSystem( "DefaultCameraManager" ) ); //! [Cache the camera manager] //! [Add usefull custom key events] auto callback = [cameraManager]( QKeyEvent* event ) { // Convert ascii code to camera index cameraManager->activate( event->key() - '0' ); }; app.m_mainWindow->getViewer()->addKeyPressEventAction( "switchCam0", "Key_0", "ShiftModifier", "", "false", callback ); app.m_mainWindow->getViewer()->addKeyPressEventAction( "switchCam1", "Key_1", "ShiftModifier", "", "false", callback ); //! [Add usefull custom key events] //! [Create the camera animation system demonstrator] auto animationSystem = new EntityAnimationSystem; app.m_engine->registerSystem( "Simple animation system", animationSystem ); //! [Create the demo animation system] //! [Create the demo fixed entity/component] { //! [Create the engine entity for the fixed component] auto e = app.m_engine->getEntityManager()->createEntity( "Fixed cube" ); //! [Create the engine entity for the fixed component] //! [Creating the cube] auto cube = Geometry::makeSharpBox( {0.5f, 0.5f, 0.5f}, Utils::Color::Green() ); //! [Creating the Cube] //! [Create a geometry component with the cube] auto c = new Scene::TriangleMeshComponent( "Fixed cube geometry", e, std::move( cube ), nullptr ); //! [Create a geometry component with the cube] } //! [Create the demo fixed entity/component] //! [Create the demo animated entity/components] { //! [Create the animated entity ] auto e = app.m_engine->getEntityManager()->createEntity( "Animated entity" ); Transform transform( Translation {1, 1, 0} ); e->setTransform( transform ); e->swapTransformBuffers(); //! [Create the animated entity ] //! [Register the entity to the animation system ] animationSystem->addEntity( e ); //! [Register the entity to the animation system ] //! [attach components to the animated entity ] // an animated yellow cube auto cube = Geometry::makeSharpBox( {0.1f, 0.1f, 0.1f}, Ra::Core::Utils::Color::Yellow() ); new Scene::TriangleMeshComponent( "Fixed cube geometry", e, std::move( cube ), nullptr ); // an animated camera, thay is not the one active at startup. Use key '0' to activate auto camera = new Scene::CameraComponent( e, "Animated Camera" ); camera->initialize(); camera->getCamera()->setPosition( Vector3 {0.5, 0, 0} ); camera->getCamera()->setDirection( Vector3 {-1, 0, 0} ); camera->show( true ); cameraManager->addCamera( camera ); //! [attach components to the animated entity ] } //! [Create the demo animated entity/components] //! [Create the fixed reference camera] { auto e = app.m_engine->getEntityManager()->createEntity( "Fixed Camera" ); auto camera = new Scene::CameraComponent( e, "Camera" ); camera->initialize(); camera->getCamera()->setPosition( Vector3 {0, 0, 5} ); camera->getCamera()->setDirection( Vector3 {0, 0, -1} ); camera->show( true ); cameraManager->addCamera( camera ); // Activating a camera require 2 things : // ask the camera manager to activate the camera cameraManager->activate( cameraManager->getCameraIndex( camera ) ); // ask the CameraManipulator to update its camera info app.m_mainWindow->getViewer()->getCameraManipulator()->updateCamera(); } //! [Create the fixed reference camera] //! [Tell the window that something is to be displayed] // Do not call app.m_mainWindow->prepareDisplay(); as it replace the active camera by the // default one app.m_mainWindow->getViewer()->makeCurrent(); app.m_mainWindow->getViewer()->getRenderer()->buildAllRenderTechniques(); app.m_mainWindow->getViewer()->doneCurrent(); //! [Tell the window that something is to be displayed] #if 0 // terminate the app after 30 second (approximatively). // All interactions on the viewer can be done when the application executes. auto close_timer = new QTimer( &app ); close_timer->setInterval( 30000 ); QObject::connect( close_timer, &QTimer::timeout, [&app]() { app.appNeedsToQuit(); } ); close_timer->start(); #endif return app.exec(); } <|endoftext|>
<commit_before>/* This file is part of the KDE project Copyright (C) 2006 Matthias Kretz <kretz@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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. */ #include "outputdevicechoice.h" #include <phonon/backendcapabilities.h> #include <phonon/objectdescription.h> OutputDeviceChoice::OutputDeviceChoice( QWidget* parent ) : QWidget( parent ) { setupUi( this ); notificationDeviceList->setModel( &m_notificationModel ); musicDeviceList->setModel( &m_musicModel ); videoDeviceList->setModel( &m_videoModel ); communicationDeviceList->setModel( &m_communicationModel ); connect( notificationDeviceList->selectionModel(), SIGNAL( currentRowChanged( const QModelIndex& , const QModelIndex& ) ), SLOT( updateButtonsEnabled() ) ); connect( musicDeviceList->selectionModel(), SIGNAL( currentRowChanged( const QModelIndex& , const QModelIndex& ) ), SLOT( updateButtonsEnabled() ) ); connect( videoDeviceList->selectionModel(), SIGNAL( currentRowChanged( const QModelIndex& , const QModelIndex& ) ), SLOT( updateButtonsEnabled() ) ); connect( communicationDeviceList->selectionModel(), SIGNAL( currentRowChanged( const QModelIndex& , const QModelIndex& ) ), SLOT( updateButtonsEnabled() ) ); } void OutputDeviceChoice::load() { QList<Phonon::AudioOutputDevice> list = Phonon::BackendCapabilities::availableAudioOutputDevices(); m_notificationModel.setModelData( list ); m_musicModel.setModelData( list ); m_videoModel.setModelData( list ); m_communicationModel.setModelData( list ); } void OutputDeviceChoice::save() { } void OutputDeviceChoice::defaults() { QList<Phonon::AudioOutputDevice> list = Phonon::BackendCapabilities::availableAudioOutputDevices(); m_notificationModel.setModelData( list ); m_musicModel.setModelData( list ); m_videoModel.setModelData( list ); m_communicationModel.setModelData( list ); } void OutputDeviceChoice::on_notificationPreferButton_clicked() { m_notificationModel.moveUp( notificationDeviceList->currentIndex() ); updateButtonsEnabled(); } void OutputDeviceChoice::on_notificationNoPreferButton_clicked() { m_notificationModel.moveDown( notificationDeviceList->currentIndex() ); updateButtonsEnabled(); } void OutputDeviceChoice::on_musicPreferButton_clicked() { m_musicModel.moveUp( musicDeviceList->currentIndex() ); updateButtonsEnabled(); } void OutputDeviceChoice::on_musicNoPreferButton_clicked() { m_musicModel.moveDown( musicDeviceList->currentIndex() ); updateButtonsEnabled(); } void OutputDeviceChoice::on_videoPreferButton_clicked() { m_videoModel.moveUp( videoDeviceList->currentIndex() ); updateButtonsEnabled(); } void OutputDeviceChoice::on_videoNoPreferButton_clicked() { m_videoModel.moveDown( videoDeviceList->currentIndex() ); updateButtonsEnabled(); } void OutputDeviceChoice::on_communicationPreferButton_clicked() { m_communicationModel.moveUp( communicationDeviceList->currentIndex() ); updateButtonsEnabled(); } void OutputDeviceChoice::on_communicationNoPreferButton_clicked() { m_communicationModel.moveDown( communicationDeviceList->currentIndex() ); updateButtonsEnabled(); } void OutputDeviceChoice::updateButtonsEnabled() { notificationPreferButton->setEnabled( notificationDeviceList->currentIndex().row() > 0 ); notificationNoPreferButton->setEnabled( notificationDeviceList->currentIndex().row() < m_notificationModel.rowCount() - 1 ); musicPreferButton->setEnabled( musicDeviceList->currentIndex().row() > 0 ); musicNoPreferButton->setEnabled( musicDeviceList->currentIndex().row() < m_musicModel.rowCount() - 1 ); videoPreferButton->setEnabled( videoDeviceList->currentIndex().row() > 0 ); videoNoPreferButton->setEnabled( videoDeviceList->currentIndex().row() < m_videoModel.rowCount() - 1 ); communicationPreferButton->setEnabled( communicationDeviceList->currentIndex().row() > 0 ); communicationNoPreferButton->setEnabled( communicationDeviceList->currentIndex().row() < m_communicationModel.rowCount() - 1 ); } #include "outputdevicechoice.moc" // vim: sw=4 ts=4 noet <commit_msg>enable only buttons where an item is selected<commit_after>/* This file is part of the KDE project Copyright (C) 2006 Matthias Kretz <kretz@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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. */ #include "outputdevicechoice.h" #include <phonon/backendcapabilities.h> #include <phonon/objectdescription.h> OutputDeviceChoice::OutputDeviceChoice( QWidget* parent ) : QWidget( parent ) { setupUi( this ); notificationDeviceList->setModel( &m_notificationModel ); musicDeviceList->setModel( &m_musicModel ); videoDeviceList->setModel( &m_videoModel ); communicationDeviceList->setModel( &m_communicationModel ); connect( notificationDeviceList->selectionModel(), SIGNAL( currentRowChanged( const QModelIndex& , const QModelIndex& ) ), SLOT( updateButtonsEnabled() ) ); connect( musicDeviceList->selectionModel(), SIGNAL( currentRowChanged( const QModelIndex& , const QModelIndex& ) ), SLOT( updateButtonsEnabled() ) ); connect( videoDeviceList->selectionModel(), SIGNAL( currentRowChanged( const QModelIndex& , const QModelIndex& ) ), SLOT( updateButtonsEnabled() ) ); connect( communicationDeviceList->selectionModel(), SIGNAL( currentRowChanged( const QModelIndex& , const QModelIndex& ) ), SLOT( updateButtonsEnabled() ) ); } void OutputDeviceChoice::load() { QList<Phonon::AudioOutputDevice> list = Phonon::BackendCapabilities::availableAudioOutputDevices(); m_notificationModel.setModelData( list ); m_musicModel.setModelData( list ); m_videoModel.setModelData( list ); m_communicationModel.setModelData( list ); } void OutputDeviceChoice::save() { } void OutputDeviceChoice::defaults() { QList<Phonon::AudioOutputDevice> list = Phonon::BackendCapabilities::availableAudioOutputDevices(); m_notificationModel.setModelData( list ); m_musicModel.setModelData( list ); m_videoModel.setModelData( list ); m_communicationModel.setModelData( list ); } void OutputDeviceChoice::on_notificationPreferButton_clicked() { m_notificationModel.moveUp( notificationDeviceList->currentIndex() ); updateButtonsEnabled(); } void OutputDeviceChoice::on_notificationNoPreferButton_clicked() { m_notificationModel.moveDown( notificationDeviceList->currentIndex() ); updateButtonsEnabled(); } void OutputDeviceChoice::on_musicPreferButton_clicked() { m_musicModel.moveUp( musicDeviceList->currentIndex() ); updateButtonsEnabled(); } void OutputDeviceChoice::on_musicNoPreferButton_clicked() { m_musicModel.moveDown( musicDeviceList->currentIndex() ); updateButtonsEnabled(); } void OutputDeviceChoice::on_videoPreferButton_clicked() { m_videoModel.moveUp( videoDeviceList->currentIndex() ); updateButtonsEnabled(); } void OutputDeviceChoice::on_videoNoPreferButton_clicked() { m_videoModel.moveDown( videoDeviceList->currentIndex() ); updateButtonsEnabled(); } void OutputDeviceChoice::on_communicationPreferButton_clicked() { m_communicationModel.moveUp( communicationDeviceList->currentIndex() ); updateButtonsEnabled(); } void OutputDeviceChoice::on_communicationNoPreferButton_clicked() { m_communicationModel.moveDown( communicationDeviceList->currentIndex() ); updateButtonsEnabled(); } void OutputDeviceChoice::updateButtonsEnabled() { QModelIndex idx = notificationDeviceList->currentIndex(); notificationPreferButton->setEnabled( idx.isValid() && idx.row() > 0 ); notificationNoPreferButton->setEnabled( idx.isValid() && idx.row() < m_notificationModel.rowCount() - 1 ); idx = musicDeviceList->currentIndex(); musicPreferButton->setEnabled( idx.isValid() && idx.row() > 0 ); musicNoPreferButton->setEnabled( idx.isValid() && idx.row() < m_musicModel.rowCount() - 1 ); idx = videoDeviceList->currentIndex(); videoPreferButton->setEnabled( idx.isValid() && idx.row() > 0 ); videoNoPreferButton->setEnabled( idx.isValid() && idx.row() < m_videoModel.rowCount() - 1 ); idx = communicationDeviceList->currentIndex(); communicationPreferButton->setEnabled( idx.isValid() && idx.row() > 0 ); communicationNoPreferButton->setEnabled( idx.isValid() && idx.row() < m_communicationModel.rowCount() - 1 ); } #include "outputdevicechoice.moc" // vim: sw=4 ts=4 noet <|endoftext|>
<commit_before>// PWM output a 4Mhz Square Wave // by dotnfc@163.com // // Assembled by dotnfc as Arducleo Sample // 2016/08/23 #include "mbed.h" #include "PwmOutEx.h" PwmOutEx mypwm(PWM_OUT, 4000000); DigitalOut myled(LED1); int main() { printf ("4Mhz frequency on PA1/A1 pin.\n"); while(1) { myled = !myled; wait(1); } } <commit_msg>Update pwm4_4mhz_main.cpp<commit_after>// PWM output a 4Mhz Square Wave // by dotnfc@163.com // // Assembled by dotnfc as Arducleo Sample // 2016/08/23 #include "mbed.h" #include "PwmOutEx.h" PwmOutEx mypwm(PWM_OUT, 4000000); DigitalOut myled(LED1); int main() { printf ("4Mhz frequency on PWM_OUT/D3 pin.\n"); while(1) { myled = !myled; wait(1); } } <|endoftext|>
<commit_before>//****************************************************************** // // Copyright 2014 Intel Mobile Communications GmbH 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. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // OCClient.cpp : Defines the entry point for the console application. // #include <string> #include <map> #include <cstdlib> #include <pthread.h> #include <mutex> #include <condition_variable> #include "OCPlatform.h" #include "OCApi.h" using namespace OC; typedef std::map<OCResourceIdentifier, std::shared_ptr<OCResource>> DiscoveredResourceMap; DiscoveredResourceMap discoveredResources; std::shared_ptr<OCResource> curResource; static ObserveType OBSERVE_TYPE_TO_USE = ObserveType::Observe; class Light { public: bool m_state; int m_power; std::string m_name; Light() : m_state(false), m_power(0), m_name("") { } }; Light mylight; int observe_count() { static int oc = 0; return ++oc; } void onObserve(const HeaderOptions headerOptions, const OCRepresentation& rep, const int& eCode, const int& sequenceNumber) { if(eCode == OC_STACK_OK) { std::cout << "OBSERVE RESULT:"<<std::endl; std::cout << "\tSequenceNumber: "<< sequenceNumber << endl; rep.getValue("state", mylight.m_state); rep.getValue("power", mylight.m_power); rep.getValue("name", mylight.m_name); std::cout << "\tstate: " << mylight.m_state << std::endl; std::cout << "\tpower: " << mylight.m_power << std::endl; std::cout << "\tname: " << mylight.m_name << std::endl; if(observe_count() > 30) { std::cout<<"Cancelling Observe..."<<std::endl; OCStackResult result = curResource->cancelObserve(); std::cout << "Cancel result: "<< result <<std::endl; sleep(10); std::cout << "DONE"<<std::endl; std::exit(0); } } else { std::cout << "onObserve Response error: " << eCode << std::endl; std::exit(-1); } } void onPost2(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode) { if(eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CREATED) { std::cout << "POST request was successful" << std::endl; if(rep.hasAttribute("createduri")) { std::cout << "\tUri of the created resource: " << rep.getValue<std::string>("createduri") << std::endl; } else { rep.getValue("state", mylight.m_state); rep.getValue("power", mylight.m_power); rep.getValue("name", mylight.m_name); std::cout << "\tstate: " << mylight.m_state << std::endl; std::cout << "\tpower: " << mylight.m_power << std::endl; std::cout << "\tname: " << mylight.m_name << std::endl; } if (OBSERVE_TYPE_TO_USE == ObserveType::Observe) std::cout << endl << "Observe is used." << endl << endl; else if (OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll) std::cout << endl << "ObserveAll is used." << endl << endl; curResource->observe(OBSERVE_TYPE_TO_USE, QueryParamsMap(), &onObserve); } else { std::cout << "onPost2 Response error: " << eCode << std::endl; std::exit(-1); } } void onPost(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode) { if(eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CREATED) { std::cout << "POST request was successful" << std::endl; if(rep.hasAttribute("createduri")) { std::cout << "\tUri of the created resource: " << rep.getValue<std::string>("createduri") << std::endl; } else { rep.getValue("state", mylight.m_state); rep.getValue("power", mylight.m_power); rep.getValue("name", mylight.m_name); std::cout << "\tstate: " << mylight.m_state << std::endl; std::cout << "\tpower: " << mylight.m_power << std::endl; std::cout << "\tname: " << mylight.m_name << std::endl; } OCRepresentation rep2; std::cout << "Posting light representation..."<<std::endl; mylight.m_state = true; mylight.m_power = 55; rep2.setValue("state", mylight.m_state); rep2.setValue("power", mylight.m_power); curResource->post(rep2, QueryParamsMap(), &onPost2); } else { std::cout << "onPost Response error: " << eCode << std::endl; std::exit(-1); } } // Local function to put a different state for this resource void postLightRepresentation(std::shared_ptr<OCResource> resource) { if(resource) { OCRepresentation rep; std::cout << "Posting light representation..."<<std::endl; mylight.m_state = false; mylight.m_power = 105; rep.setValue("state", mylight.m_state); rep.setValue("power", mylight.m_power); // Invoke resource's post API with rep, query map and the callback parameter resource->post(rep, QueryParamsMap(), &onPost); } } // callback handler on PUT request void onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode) { if(eCode == OC_STACK_OK) { std::cout << "PUT request was successful" << std::endl; rep.getValue("state", mylight.m_state); rep.getValue("power", mylight.m_power); rep.getValue("name", mylight.m_name); std::cout << "\tstate: " << mylight.m_state << std::endl; std::cout << "\tpower: " << mylight.m_power << std::endl; std::cout << "\tname: " << mylight.m_name << std::endl; postLightRepresentation(curResource); } else { std::cout << "onPut Response error: " << eCode << std::endl; std::exit(-1); } } // Local function to put a different state for this resource void putLightRepresentation(std::shared_ptr<OCResource> resource) { if(resource) { OCRepresentation rep; std::cout << "Putting light representation..."<<std::endl; mylight.m_state = true; mylight.m_power = 15; rep.setValue("state", mylight.m_state); rep.setValue("power", mylight.m_power); // Invoke resource's put API with rep, query map and the callback parameter resource->put(rep, QueryParamsMap(), &onPut); } } // Callback handler on GET request void onGet(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode) { if(eCode == OC_STACK_OK) { std::cout << "GET request was successful" << std::endl; std::cout << "Resource URI: " << rep.getUri() << std::endl; rep.getValue("state", mylight.m_state); rep.getValue("power", mylight.m_power); rep.getValue("name", mylight.m_name); std::cout << "\tstate: " << mylight.m_state << std::endl; std::cout << "\tpower: " << mylight.m_power << std::endl; std::cout << "\tname: " << mylight.m_name << std::endl; putLightRepresentation(curResource); } else { std::cout << "onGET Response error: " << eCode << std::endl; std::exit(-1); } } // Local function to get representation of light resource void getLightRepresentation(std::shared_ptr<OCResource> resource) { if(resource) { std::cout << "Getting Light Representation..."<<std::endl; // Invoke resource's get API with the callback parameter QueryParamsMap test; resource->get(test, &onGet); } } // Callback to found resources void foundResource(std::shared_ptr<OCResource> resource) { std::string resourceURI; std::string hostAddress; try { if(discoveredResources.find(resource->uniqueIdentifier()) == discoveredResources.end()) { std::cout << "Found resource " << resource->uniqueIdentifier() << " for the first time on server with ID: "<< resource->sid()<<std::endl; discoveredResources[resource->uniqueIdentifier()] = resource; } else { std::cout<<"Found resource "<< resource->uniqueIdentifier() << " again!"<<std::endl; } if(curResource) { std::cout << "Found another resource, ignoring"<<std::endl; return; } // Do some operations with resource object. if(resource) { std::cout<<"DISCOVERED Resource:"<<std::endl; // Get the resource URI resourceURI = resource->uri(); std::cout << "\tURI of the resource: " << resourceURI << std::endl; // Get the resource host address hostAddress = resource->host(); std::cout << "\tHost address of the resource: " << hostAddress << std::endl; // Get the resource types std::cout << "\tList of resource types: " << std::endl; for(auto &resourceTypes : resource->getResourceTypes()) { std::cout << "\t\t" << resourceTypes << std::endl; } // Get the resource interfaces std::cout << "\tList of resource interfaces: " << std::endl; for(auto &resourceInterfaces : resource->getResourceInterfaces()) { std::cout << "\t\t" << resourceInterfaces << std::endl; } if(resourceURI == "/a/light") { curResource = resource; // Call a local function which will internally invoke get API on the resource pointer getLightRepresentation(resource); } } else { // Resource is invalid std::cout << "Resource is invalid" << std::endl; } } catch(std::exception& e) { //log(e.what()); } } void PrintUsage() { std::cout << std::endl; #ifdef CA_INT std::cout << "Usage : simpleclient <ObserveType> <ConnectivityType>" << std::endl; #else std::cout << "Usage : simpleclient <ObserveType>" << std::endl; #endif std::cout << " ObserveType : 1 - Observe" << std::endl; std::cout << " ObserveType : 2 - ObserveAll" << std::endl; #ifdef CA_INT std::cout<<" connectivityType: Default WIFI" << std::endl; std::cout << " ConnectivityType : 0 - ETHERNET"<< std::endl; std::cout << " ConnectivityType : 1 - WIFI"<< std::endl; #endif } int main(int argc, char* argv[]) { ostringstream requestURI; #ifdef CA_INT OCConnectivityType connectivityType = OC_WIFI; #endif try { if (argc == 1) { OBSERVE_TYPE_TO_USE = ObserveType::Observe; } #ifdef CA_INT else if (argc >= 2) #else else if (argc == 2) #endif { int value = stoi(argv[1]); if (value == 1) OBSERVE_TYPE_TO_USE = ObserveType::Observe; else if (value == 2) OBSERVE_TYPE_TO_USE = ObserveType::ObserveAll; else OBSERVE_TYPE_TO_USE = ObserveType::Observe; #ifdef CA_INT if(argc == 3) { std::size_t inputValLen; int optionSelected = stoi(argv[2], &inputValLen); if(inputValLen == strlen(argv[2])) { if(optionSelected == 0) { connectivityType = OC_ETHERNET; } else if(optionSelected == 1) { connectivityType = OC_WIFI; } else { std::cout << "Invalid connectivity type selected. Using default WIFI" << std::endl; } } else { std::cout << "Invalid connectivity type selected. Using default WIFI" << std::endl; } } } #endif else { PrintUsage(); return -1; } } catch(exception& e) { std::cout << "Invalid input argument. Using WIFI as connectivity type" << std::endl; } // Create PlatformConfig object PlatformConfig cfg { OC::ServiceType::InProc, OC::ModeType::Client, "0.0.0.0", 0, OC::QualityOfService::LowQos }; OCPlatform::Configure(cfg); try { // makes it so that all boolean values are printed as 'true/false' in this stream std::cout.setf(std::ios::boolalpha); // Find all resources requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.light"; #ifdef CA_INT OCPlatform::findResource("", requestURI.str(), connectivityType, &foundResource); #else OCPlatform::findResource("", requestURI.str(), &foundResource); #endif std::cout<< "Finding Resource... " <<std::endl; // Find resource is done twice so that we discover the original resources a second time. // These resources will have the same uniqueidentifier (yet be different objects), so that // we can verify/show the duplicate-checking code in foundResource(above); #ifdef CA_INT OCPlatform::findResource("", requestURI.str(), connectivityType, &foundResource); #else OCPlatform::findResource("", requestURI.str(), &foundResource); #endif std::cout<< "Finding Resource for second time... " <<std::endl; while(true) { // some operations } // A condition variable will free the mutex it is given, then do a non- // intensive block until 'notify' is called on it. In this case, since we // don't ever call cv.notify, this should be a non-processor intensive version // of while(true); std::mutex blocker; std::condition_variable cv; std::unique_lock<std::mutex> lock(blocker); cv.wait(lock); }catch(OCException& e) { //log(e.what()); } return 0; } <commit_msg>Fixed seg fault in simpleclient sample app (Bug IOT-130)<commit_after>//****************************************************************** // // Copyright 2014 Intel Mobile Communications GmbH 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. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // OCClient.cpp : Defines the entry point for the console application. // #include <string> #include <map> #include <cstdlib> #include <pthread.h> #include <mutex> #include <condition_variable> #include "OCPlatform.h" #include "OCApi.h" using namespace OC; typedef std::map<OCResourceIdentifier, std::shared_ptr<OCResource>> DiscoveredResourceMap; DiscoveredResourceMap discoveredResources; std::shared_ptr<OCResource> curResource; static ObserveType OBSERVE_TYPE_TO_USE = ObserveType::Observe; class Light { public: bool m_state; int m_power; std::string m_name; Light() : m_state(false), m_power(0), m_name("") { } }; Light mylight; int observe_count() { static int oc = 0; return ++oc; } void onObserve(const HeaderOptions headerOptions, const OCRepresentation& rep, const int& eCode, const int& sequenceNumber) { try { if(eCode == OC_STACK_OK) { std::cout << "OBSERVE RESULT:"<<std::endl; std::cout << "\tSequenceNumber: "<< sequenceNumber << endl; rep.getValue("state", mylight.m_state); rep.getValue("power", mylight.m_power); rep.getValue("name", mylight.m_name); std::cout << "\tstate: " << mylight.m_state << std::endl; std::cout << "\tpower: " << mylight.m_power << std::endl; std::cout << "\tname: " << mylight.m_name << std::endl; if(observe_count() > 30) { std::cout<<"Cancelling Observe..."<<std::endl; OCStackResult result = curResource->cancelObserve(); std::cout << "Cancel result: "<< result <<std::endl; sleep(10); std::cout << "DONE"<<std::endl; std::exit(0); } } else { std::cout << "onObserve Response error: " << eCode << std::endl; std::exit(-1); } } catch(std::exception& e) { std::cout << "Exception: " << e.what() << " in onObserve" << std::endl; } } void onPost2(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode) { try { if(eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CREATED) { std::cout << "POST request was successful" << std::endl; if(rep.hasAttribute("createduri")) { std::cout << "\tUri of the created resource: " << rep.getValue<std::string>("createduri") << std::endl; } else { rep.getValue("state", mylight.m_state); rep.getValue("power", mylight.m_power); rep.getValue("name", mylight.m_name); std::cout << "\tstate: " << mylight.m_state << std::endl; std::cout << "\tpower: " << mylight.m_power << std::endl; std::cout << "\tname: " << mylight.m_name << std::endl; } if (OBSERVE_TYPE_TO_USE == ObserveType::Observe) std::cout << endl << "Observe is used." << endl << endl; else if (OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll) std::cout << endl << "ObserveAll is used." << endl << endl; curResource->observe(OBSERVE_TYPE_TO_USE, QueryParamsMap(), &onObserve); } else { std::cout << "onPost2 Response error: " << eCode << std::endl; std::exit(-1); } } catch(std::exception& e) { std::cout << "Exception: " << e.what() << " in onPost2" << std::endl; } } void onPost(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode) { try { if(eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CREATED) { std::cout << "POST request was successful" << std::endl; if(rep.hasAttribute("createduri")) { std::cout << "\tUri of the created resource: " << rep.getValue<std::string>("createduri") << std::endl; } else { rep.getValue("state", mylight.m_state); rep.getValue("power", mylight.m_power); rep.getValue("name", mylight.m_name); std::cout << "\tstate: " << mylight.m_state << std::endl; std::cout << "\tpower: " << mylight.m_power << std::endl; std::cout << "\tname: " << mylight.m_name << std::endl; } OCRepresentation rep2; std::cout << "Posting light representation..."<<std::endl; mylight.m_state = true; mylight.m_power = 55; rep2.setValue("state", mylight.m_state); rep2.setValue("power", mylight.m_power); curResource->post(rep2, QueryParamsMap(), &onPost2); } else { std::cout << "onPost Response error: " << eCode << std::endl; std::exit(-1); } } catch(std::exception& e) { std::cout << "Exception: " << e.what() << " in onPost" << std::endl; } } // Local function to put a different state for this resource void postLightRepresentation(std::shared_ptr<OCResource> resource) { if(resource) { OCRepresentation rep; std::cout << "Posting light representation..."<<std::endl; mylight.m_state = false; mylight.m_power = 105; rep.setValue("state", mylight.m_state); rep.setValue("power", mylight.m_power); // Invoke resource's post API with rep, query map and the callback parameter resource->post(rep, QueryParamsMap(), &onPost); } } // callback handler on PUT request void onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode) { try { if(eCode == OC_STACK_OK) { std::cout << "PUT request was successful" << std::endl; rep.getValue("state", mylight.m_state); rep.getValue("power", mylight.m_power); rep.getValue("name", mylight.m_name); std::cout << "\tstate: " << mylight.m_state << std::endl; std::cout << "\tpower: " << mylight.m_power << std::endl; std::cout << "\tname: " << mylight.m_name << std::endl; postLightRepresentation(curResource); } else { std::cout << "onPut Response error: " << eCode << std::endl; std::exit(-1); } } catch(std::exception& e) { std::cout << "Exception: " << e.what() << " in onPut" << std::endl; } } // Local function to put a different state for this resource void putLightRepresentation(std::shared_ptr<OCResource> resource) { if(resource) { OCRepresentation rep; std::cout << "Putting light representation..."<<std::endl; mylight.m_state = true; mylight.m_power = 15; rep.setValue("state", mylight.m_state); rep.setValue("power", mylight.m_power); // Invoke resource's put API with rep, query map and the callback parameter resource->put(rep, QueryParamsMap(), &onPut); } } // Callback handler on GET request void onGet(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode) { try { if(eCode == OC_STACK_OK) { std::cout << "GET request was successful" << std::endl; std::cout << "Resource URI: " << rep.getUri() << std::endl; rep.getValue("state", mylight.m_state); rep.getValue("power", mylight.m_power); rep.getValue("name", mylight.m_name); std::cout << "\tstate: " << mylight.m_state << std::endl; std::cout << "\tpower: " << mylight.m_power << std::endl; std::cout << "\tname: " << mylight.m_name << std::endl; putLightRepresentation(curResource); } else { std::cout << "onGET Response error: " << eCode << std::endl; std::exit(-1); } } catch(std::exception& e) { std::cout << "Exception: " << e.what() << " in onGet" << std::endl; } } // Local function to get representation of light resource void getLightRepresentation(std::shared_ptr<OCResource> resource) { if(resource) { std::cout << "Getting Light Representation..."<<std::endl; // Invoke resource's get API with the callback parameter QueryParamsMap test; resource->get(test, &onGet); } } // Callback to found resources void foundResource(std::shared_ptr<OCResource> resource) { std::string resourceURI; std::string hostAddress; try { if(discoveredResources.find(resource->uniqueIdentifier()) == discoveredResources.end()) { std::cout << "Found resource " << resource->uniqueIdentifier() << " for the first time on server with ID: "<< resource->sid()<<std::endl; discoveredResources[resource->uniqueIdentifier()] = resource; } else { std::cout<<"Found resource "<< resource->uniqueIdentifier() << " again!"<<std::endl; } if(curResource) { std::cout << "Found another resource, ignoring"<<std::endl; return; } // Do some operations with resource object. if(resource) { std::cout<<"DISCOVERED Resource:"<<std::endl; // Get the resource URI resourceURI = resource->uri(); std::cout << "\tURI of the resource: " << resourceURI << std::endl; // Get the resource host address hostAddress = resource->host(); std::cout << "\tHost address of the resource: " << hostAddress << std::endl; // Get the resource types std::cout << "\tList of resource types: " << std::endl; for(auto &resourceTypes : resource->getResourceTypes()) { std::cout << "\t\t" << resourceTypes << std::endl; } // Get the resource interfaces std::cout << "\tList of resource interfaces: " << std::endl; for(auto &resourceInterfaces : resource->getResourceInterfaces()) { std::cout << "\t\t" << resourceInterfaces << std::endl; } if(resourceURI == "/a/light") { curResource = resource; // Call a local function which will internally invoke get API on the resource pointer getLightRepresentation(resource); } } else { // Resource is invalid std::cout << "Resource is invalid" << std::endl; } } catch(std::exception& e) { //log(e.what()); } } void PrintUsage() { std::cout << std::endl; #ifdef CA_INT std::cout << "Usage : simpleclient <ObserveType> <ConnectivityType>" << std::endl; #else std::cout << "Usage : simpleclient <ObserveType>" << std::endl; #endif std::cout << " ObserveType : 1 - Observe" << std::endl; std::cout << " ObserveType : 2 - ObserveAll" << std::endl; #ifdef CA_INT std::cout<<" connectivityType: Default WIFI" << std::endl; std::cout << " ConnectivityType : 0 - ETHERNET"<< std::endl; std::cout << " ConnectivityType : 1 - WIFI"<< std::endl; #endif } int main(int argc, char* argv[]) { ostringstream requestURI; #ifdef CA_INT OCConnectivityType connectivityType = OC_WIFI; #endif try { if (argc == 1) { OBSERVE_TYPE_TO_USE = ObserveType::Observe; } #ifdef CA_INT else if (argc >= 2) #else else if (argc == 2) #endif { int value = stoi(argv[1]); if (value == 1) OBSERVE_TYPE_TO_USE = ObserveType::Observe; else if (value == 2) OBSERVE_TYPE_TO_USE = ObserveType::ObserveAll; else OBSERVE_TYPE_TO_USE = ObserveType::Observe; #ifdef CA_INT if(argc == 3) { std::size_t inputValLen; int optionSelected = stoi(argv[2], &inputValLen); if(inputValLen == strlen(argv[2])) { if(optionSelected == 0) { connectivityType = OC_ETHERNET; } else if(optionSelected == 1) { connectivityType = OC_WIFI; } else { std::cout << "Invalid connectivity type selected. Using default WIFI" << std::endl; } } else { std::cout << "Invalid connectivity type selected. Using default WIFI" << std::endl; } } } #endif else { PrintUsage(); return -1; } } catch(exception& e) { std::cout << "Invalid input argument. Using WIFI as connectivity type" << std::endl; } // Create PlatformConfig object PlatformConfig cfg { OC::ServiceType::InProc, OC::ModeType::Client, "0.0.0.0", 0, OC::QualityOfService::LowQos }; OCPlatform::Configure(cfg); try { // makes it so that all boolean values are printed as 'true/false' in this stream std::cout.setf(std::ios::boolalpha); // Find all resources requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.light"; #ifdef CA_INT OCPlatform::findResource("", requestURI.str(), connectivityType, &foundResource); #else OCPlatform::findResource("", requestURI.str(), &foundResource); #endif std::cout<< "Finding Resource... " <<std::endl; // Find resource is done twice so that we discover the original resources a second time. // These resources will have the same uniqueidentifier (yet be different objects), so that // we can verify/show the duplicate-checking code in foundResource(above); #ifdef CA_INT OCPlatform::findResource("", requestURI.str(), connectivityType, &foundResource); #else OCPlatform::findResource("", requestURI.str(), &foundResource); #endif std::cout<< "Finding Resource for second time... " <<std::endl; while(true) { // some operations } // A condition variable will free the mutex it is given, then do a non- // intensive block until 'notify' is called on it. In this case, since we // don't ever call cv.notify, this should be a non-processor intensive version // of while(true); std::mutex blocker; std::condition_variable cv; std::unique_lock<std::mutex> lock(blocker); cv.wait(lock); }catch(OCException& e) { //log(e.what()); } return 0; } <|endoftext|>
<commit_before>/* * Copyright 2016, Simula Research Laboratory * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <iostream> #include <fstream> #include <sstream> #include <string> #include <cmath> #include <iomanip> #include <stdlib.h> #include <boost/program_options.hpp> #include <popsift/popsift.h> #include <popsift/sift_conf.h> #include <popsift/common/device_prop.h> #include "pgmread.h" using namespace std; static void validate( const char* appName, popsift::Config& config ); static bool print_dev_info = false; static bool print_time_info = false; static bool write_as_uchar = false; static void parseargs(int argc, char** argv, popsift::Config& config, string& inputFile) { using namespace boost::program_options; options_description options("Options"); options.add_options() ("help,h", "Print usage") ("verbose,v", bool_switch()->notifier([&](bool) {config.setVerbose(); }), "") ("log,l", bool_switch()->notifier([&](bool) {config.setLogMode(popsift::Config::All); }), "Write debugging files") ("input-file,i", value<std::string>(&inputFile)->required(), "Input file"); options_description parameters("Parameters"); parameters.add_options() ("octaves", value<int>(&config.octaves), "Number of octaves") ("levels", value<int>(&config.levels), "Number of levels per octave") ("sigma", value<float>()->notifier([&](float f) { config.setSigma(f); }), "Initial sigma value") ("threshold", value<float>()->notifier([&](float f) { config.setThreshold(f); }), "Contrast threshold") ("edge-threshold", value<float>()->notifier([&](float f) { config.setEdgeLimit(f); }), "On-edge threshold") ("edge-limit", value<float>()->notifier([&](float f) { config.setEdgeLimit(f); }), "On-edge threshold") ("downsampling", value<float>()->notifier([&](float f) { config.setDownsampling(f); }), "Downscale width and height of input by 2^N") ("initial-blur", value<float>()->notifier([&](float f) {config.setInitialBlur(f); }), "Assume initial blur, subtract when blurring first time"); options_description modes("Modes"); modes.add_options() ("popsift-mode", bool_switch()->notifier([&](bool) {config.setMode(popsift::Config::PopSift); }), "During the initial upscale, shift pixels by 1. In extrema refinement, steps up to 0.6, do not reject points when reaching max iterations, " "first contrast threshold is .8 * peak thresh. Shift feature coords octave 0 back to original pos.") ("vlfeat-mode", bool_switch()->notifier([&](bool) { config.setMode(popsift::Config::VLFeat); }), "During the initial upscale, shift pixels by 1. That creates a sharper upscaled image. " "In extrema refinement, steps up to 0.6, levels remain unchanged, " "do not reject points when reaching max iterations, " "first contrast threshold is .8 * peak thresh.") ("opencv-mode", bool_switch()->notifier([&](bool) { config.setMode(popsift::Config::OpenCV); }), "During the initial upscale, shift pixels by 0.5. " "In extrema refinement, steps up to 0.5, " "reject points when reaching max iterations, " "first contrast threshold is floor(.5 * peak thresh). " "Computed filter width are lower than VLFeat/PopSift") ("root-sift", bool_switch()->notifier([&](bool) { config.setUseRootSift(true); }), "Use the L1-based norm for OpenMVG rather than L2-based as in OpenCV") ("norm-multi", value<int>()->notifier([&](int i) {config.setNormalizationMultiplier(i); }), "Multiply the descriptor by pow(2,<int>).") ("dp-off", bool_switch()->notifier([&](bool) { config.setDPOrientation(false); config.setDPDescriptors(false); }), "Switch all CUDA Dynamic Parallelism off.") ("dp-ori-off", bool_switch()->notifier([&](bool) { config.setDPOrientation(false); }), "Switch DP off for orientation computation") ("dp-desc-off", bool_switch()->notifier([&](bool) { config.setDPDescriptors(false); }), "Switch DP off for descriptor computation"); options_description informational("Informational"); informational.add_options() ("print-gauss-tables", bool_switch()->notifier([&](bool) { config.setPrintGaussTables(); }), "A debug output printing Gauss filter size and tables") ("print-dev-info", bool_switch(&print_dev_info)->default_value(false), "A debug output printing CUDA device information") ("print-time-info", bool_switch(&print_time_info)->default_value(false), "A debug output printing image processing time after load()") ("write-as-uchar", bool_switch(&write_as_uchar)->default_value(false), "Output descriptors rounded to int Scaling to sensible ranges is not automatic, should be combined with --norm-multi=9 or similar"); //("test-direct-scaling") options_description all("Allowed options"); all.add(options).add(parameters).add(modes).add(informational); variables_map vm; store(parse_command_line(argc, argv, all), vm); if (vm.count("help")) { std::cout << all << '\n'; exit(1); } notify(vm); // Notify does processing (e.g., raise exceptions if required args are missing) } int main(int argc, char **argv) { cudaDeviceReset(); popsift::Config config; string inputFile = ""; const char* appName = argv[0]; try { parseargs(argc, argv, config, inputFile); // Parse command line std::cout << inputFile << std::endl; } catch (std::exception& e) { std::cout << e.what() << std::endl; exit(1); } int w; int h; unsigned char* image_data = readPGMfile( inputFile, w, h ); if( image_data == 0 ) { exit( -1 ); } // cerr << "Input image size: " // << w << "X" << h // << " filename: " << boost::filesystem::path(inputFile).filename() << endl; popsift::cuda::device_prop_t deviceInfo; deviceInfo.set( 0, print_dev_info ); if( print_dev_info ) deviceInfo.print( ); PopSift PopSift( config ); PopSift.init( 0, w, h, print_time_info ); popsift::Features* feature_list = PopSift.execute( 0, image_data, print_time_info ); PopSift.uninit( 0 ); std::ofstream of( "output-features.txt" ); of << *feature_list; delete feature_list; delete [] image_data; return 0; } static void validate( const char* appName, popsift::Config& config ) { switch( config.getGaussGroup() ) { case 1 : case 2 : case 3 : case 8 : break; default : cerr << "Only 2, 3 or 8 Gauss levels can be combined at this time" << endl; exit( -1 ); } } <commit_msg>Bugfix in handling of bool_switch arguments.<commit_after>/* * Copyright 2016, Simula Research Laboratory * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <iostream> #include <fstream> #include <sstream> #include <string> #include <cmath> #include <iomanip> #include <stdlib.h> #include <boost/program_options.hpp> #include <popsift/popsift.h> #include <popsift/sift_conf.h> #include <popsift/common/device_prop.h> #include "pgmread.h" using namespace std; static void validate( const char* appName, popsift::Config& config ); static bool print_dev_info = false; static bool print_time_info = false; static bool write_as_uchar = false; static void parseargs(int argc, char** argv, popsift::Config& config, string& inputFile) { using namespace boost::program_options; options_description options("Options"); options.add_options() ("help,h", "Print usage") ("verbose,v", bool_switch()->notifier([&](bool v) { if (v) config.setVerbose(); }), "") ("log,l", bool_switch()->notifier([&](bool v) { if(v) config.setLogMode(popsift::Config::All); }), "Write debugging files") ("input-file,i", value<std::string>(&inputFile)->required(), "Input file"); options_description parameters("Parameters"); parameters.add_options() ("octaves", value<int>(&config.octaves), "Number of octaves") ("levels", value<int>(&config.levels), "Number of levels per octave") ("sigma", value<float>()->notifier([&](float f) { config.setSigma(f); }), "Initial sigma value") ("threshold", value<float>()->notifier([&](float f) { config.setThreshold(f); }), "Contrast threshold") ("edge-threshold", value<float>()->notifier([&](float f) { config.setEdgeLimit(f); }), "On-edge threshold") ("edge-limit", value<float>()->notifier([&](float f) { config.setEdgeLimit(f); }), "On-edge threshold") ("downsampling", value<float>()->notifier([&](float f) { config.setDownsampling(f); }), "Downscale width and height of input by 2^N") ("initial-blur", value<float>()->notifier([&](float f) {config.setInitialBlur(f); }), "Assume initial blur, subtract when blurring first time"); options_description modes("Modes"); modes.add_options() ("popsift-mode", bool_switch()->notifier([&](bool v) { if(v) config.setMode(popsift::Config::PopSift); }), "During the initial upscale, shift pixels by 1. In extrema refinement, steps up to 0.6, do not reject points when reaching max iterations, " "first contrast threshold is .8 * peak thresh. Shift feature coords octave 0 back to original pos.") ("vlfeat-mode", bool_switch()->notifier([&](bool v) { if (v) config.setMode(popsift::Config::VLFeat); }), "During the initial upscale, shift pixels by 1. That creates a sharper upscaled image. " "In extrema refinement, steps up to 0.6, levels remain unchanged, " "do not reject points when reaching max iterations, " "first contrast threshold is .8 * peak thresh.") ("opencv-mode", bool_switch()->notifier([&](bool v) { if (v) config.setMode(popsift::Config::OpenCV); }), "During the initial upscale, shift pixels by 0.5. " "In extrema refinement, steps up to 0.5, " "reject points when reaching max iterations, " "first contrast threshold is floor(.5 * peak thresh). " "Computed filter width are lower than VLFeat/PopSift") ("root-sift", bool_switch()->notifier([&](bool v) { if (v) config.setUseRootSift(true); }), "Use the L1-based norm for OpenMVG rather than L2-based as in OpenCV") ("norm-multi", value<int>()->notifier([&](int i) {config.setNormalizationMultiplier(i); }), "Multiply the descriptor by pow(2,<int>).") ("dp-off", bool_switch()->notifier([&](bool v) { if (v) config.setDPOrientation(false); config.setDPDescriptors(false); }), "Switch all CUDA Dynamic Parallelism off.") ("dp-ori-off", bool_switch()->notifier([&](bool v) { if (v) config.setDPOrientation(false); }), "Switch DP off for orientation computation") ("dp-desc-off", bool_switch()->notifier([&](bool v) { if (v) config.setDPDescriptors(false); }), "Switch DP off for descriptor computation"); options_description informational("Informational"); informational.add_options() ("print-gauss-tables", bool_switch()->notifier([&](bool v) { if (v) config.setPrintGaussTables(); }), "A debug output printing Gauss filter size and tables") ("print-dev-info", bool_switch(&print_dev_info)->default_value(false), "A debug output printing CUDA device information") ("print-time-info", bool_switch(&print_time_info)->default_value(false), "A debug output printing image processing time after load()") ("write-as-uchar", bool_switch(&write_as_uchar)->default_value(false), "Output descriptors rounded to int Scaling to sensible ranges is not automatic, should be combined with --norm-multi=9 or similar"); //("test-direct-scaling") options_description all("Allowed options"); all.add(options).add(parameters).add(modes).add(informational); variables_map vm; store(parse_command_line(argc, argv, all), vm); if (vm.count("help")) { std::cout << all << '\n'; exit(1); } notify(vm); // Notify does processing (e.g., raise exceptions if required args are missing) } int main(int argc, char **argv) { cudaDeviceReset(); popsift::Config config; string inputFile = ""; const char* appName = argv[0]; try { parseargs(argc, argv, config, inputFile); // Parse command line std::cout << inputFile << std::endl; } catch (std::exception& e) { std::cout << e.what() << std::endl; exit(1); } int w; int h; unsigned char* image_data = readPGMfile( inputFile, w, h ); if( image_data == 0 ) { exit( -1 ); } // cerr << "Input image size: " // << w << "X" << h // << " filename: " << boost::filesystem::path(inputFile).filename() << endl; popsift::cuda::device_prop_t deviceInfo; deviceInfo.set( 0, print_dev_info ); if( print_dev_info ) deviceInfo.print( ); PopSift PopSift( config ); PopSift.init( 0, w, h, print_time_info ); popsift::Features* feature_list = PopSift.execute( 0, image_data, print_time_info ); PopSift.uninit( 0 ); std::ofstream of( "output-features.txt" ); of << *feature_list; delete feature_list; delete [] image_data; return 0; } static void validate( const char* appName, popsift::Config& config ) { switch( config.getGaussGroup() ) { case 1 : case 2 : case 3 : case 8 : break; default : cerr << "Only 2, 3 or 8 Gauss levels can be combined at this time" << endl; exit( -1 ); } } <|endoftext|>
<commit_before>// MIT License // // Copyright (c) 2017-2018 Artur Wyszyński, aljen at hitomi dot pl // // 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 "spaghetti/registry.h" #include <vector> #include "filesystem.h" #include "shared_library.h" #include "elements/all.h" #include "nodes/all.h" #include "spaghetti/logger.h" #include "spaghetti/version.h" inline void init_resources() { Q_INIT_RESOURCE(icons); } namespace spaghetti { struct Registry::PIMPL { using Plugins = std::vector<std::shared_ptr<SharedLibrary>>; using MetaInfos = std::vector<MetaInfo>; MetaInfos metaInfos{}; Plugins plugins{}; }; Registry &Registry::get() { static Registry s_registry{}; return s_registry; } Registry::~Registry() = default; Registry::Registry() : m_pimpl{ std::make_unique<PIMPL>() } { log::init(); log::info("Spaghetti version: {}, git: {}@{}, build date: {}, {}", version::STRING, version::BRANCH, version::COMMIT_SHORT_HASH, __DATE__, __TIME__); } void Registry::registerInternalElements() { init_resources(); using namespace elements; registerElement<Package>("Package", ":/logic/package.png"); registerElement<gates::And>("AND (Bool)", ":/gates/and.png"); registerElement<gates::Nand>("NAND (Bool)", ":/gates/nand.png"); registerElement<gates::Nor>("NOR (Bool)", ":/gates/nor.png"); registerElement<gates::Not>("NOT (Bool)", ":/gates/not.png"); registerElement<gates::Or>("OR (Bool)", ":/gates/or.png"); registerElement<logic::IfGreaterEqual>("If A >= B (Float)", ":/unknown.png"); registerElement<logic::IfGreater>("If A > B (Float)", ":/unknown.png"); registerElement<logic::IfEqual>("If A == B (Float)", ":/unknown.png"); registerElement<logic::IfLower>("If A < B (Float)", ":/unknown.png"); registerElement<logic::IfLowerEqual>("If A <= B (Float)", ":/unknown.png"); registerElement<logic::MultiplexerInt>("Multiplexer (Int)", ":/unknown.png"); registerElement<logic::DemultiplexerInt>("Demultiplexer (Int)", ":/unknown.png"); registerElement<logic::Blinker, nodes::logic::Blinker>("Blinker (Bool)", ":/unknown.png"); registerElement<logic::Clock, nodes::logic::Clock>("Clock (ms)", ":/logic/clock.png"); registerElement<logic::Switch>("Switch (Int)", ":/logic/switch.png"); registerElement<math::Abs>("Abs (Float)", ":/unknown.png"); registerElement<math::Add>("Add (Float)", ":/unknown.png"); registerElement<math::AddIf>("Add If (Float)", ":/unknown.png"); registerElement<math::Subtract>("Subtract (Float)", ":/unknown.png"); registerElement<math::SubtractIf>("Subtract If (Float)", ":/unknown.png"); registerElement<math::Divide>("Divide (Float)", ":/unknown.png"); registerElement<math::DivideIf>("Divide If (Float)", ":/unknown.png"); registerElement<math::Multiply>("Multiply (Float)", ":/unknown.png"); registerElement<math::MultiplyIf>("Multiply If (Float)", ":/unknown.png"); registerElement<math::Cos>("Cos (Rad)", ":/unknown.png"); registerElement<math::Sin>("Sin (Rad)", ":/unknown.png"); registerElement<ui::FloatInfo, nodes::ui::FloatInfo>("Info (Float)", ":/values/const_float.png"); registerElement<ui::IntInfo, nodes::ui::IntInfo>("Info (Int)", ":/values/const_int.png"); registerElement<ui::PushButton, nodes::ui::PushButton>("Push Button (Bool)", ":/ui/push_button.png"); registerElement<ui::ToggleButton, nodes::ui::ToggleButton>("Toggle Button (Bool)", ":/ui/toggle_button.png"); registerElement<values::ConstBool, nodes::values::ConstBool>("Const value (Bool)", ":/values/const_bool.png"); registerElement<values::ConstFloat, nodes::values::ConstFloat>("Const value (Float)", ":/values/const_float.png"); registerElement<values::ConstInt, nodes::values::ConstInt>("Const value (Int)", ":/values/const_int.png"); registerElement<values::RandomBool>("Random value (Bool)", ":/values/random_value.png"); registerElement<values::Degree2Radian>("Convert angle (Deg2Rad)", ":/unknown.png"); registerElement<values::Radian2Degree>("Convert angle (Rad2Deg)", ":/unknown.png"); registerElement<values::Int2Float>("Convert value (Int2Float)", ":/unknown.png"); registerElement<values::Float2Int>("Convert value (Float2Int)", ":/unknown.png"); registerElement<values::MinInt>("Minimum value (Int)", ":/unknown.png"); registerElement<values::MaxInt>("Maximum value (Int)", ":/unknown.png"); registerElement<values::MinFloat>("Minimum value (Float)", ":/unknown.png"); registerElement<values::MaxFloat>("Maximum value (Float)", ":/unknown.png"); registerElement<values::ClampFloat>("Clamp value (Float)", ":/unknown.png"); registerElement<values::ClampInt>("Clamp value (Int)", ":/unknown.png"); } void Registry::loadPlugins() { fs::path const PLUGINS_DIR{ "../plugins" }; if (!fs::is_directory(PLUGINS_DIR)) return; for (auto const &ENTRY : fs::directory_iterator(PLUGINS_DIR)) { if (!fs::is_regular_file(ENTRY)) continue; std::error_code error{}; auto plugin = std::make_shared<SharedLibrary>(ENTRY, error); if (error.value() != 0 || !plugin->has("register_plugin")) continue; auto registerPlugin = plugin->get<void(Registry &)>("register_plugin"); registerPlugin(*this); m_pimpl->plugins.emplace_back(std::move(plugin)); } } Element *Registry::createElement(string::hash_t const a_hash) { auto const &META_INFO = metaInfoFor(a_hash); assert(META_INFO.cloneElement); return META_INFO.cloneElement(); } Node *Registry::createNode(string::hash_t const a_hash) { auto const &META_INFO = metaInfoFor(a_hash); assert(META_INFO.cloneNode); return META_INFO.cloneNode(); } std::string Registry::elementName(string::hash_t const a_hash) { auto const &META_INFO = metaInfoFor(a_hash); return META_INFO.name; } std::string Registry::elementIcon(string::hash_t const a_hash) { auto const &META_INFO = metaInfoFor(a_hash); return META_INFO.icon; } void Registry::addElement(MetaInfo &a_metaInfo) { auto &metaInfos = m_pimpl->metaInfos; metaInfos.push_back(std::move(a_metaInfo)); } bool Registry::hasElement(string::hash_t const a_hash) const { auto const &META_INFOS = m_pimpl->metaInfos; auto const IT = std::find_if(std::begin(META_INFOS), std::end(META_INFOS), [a_hash](auto const &a_metaInfo) { return a_metaInfo.hash == a_hash; }); return IT != std::end(META_INFOS); } size_t Registry::size() const { auto const &META_INFOS = m_pimpl->metaInfos; return META_INFOS.size(); } Registry::MetaInfo const &Registry::metaInfoFor(string::hash_t const a_hash) const { auto &metaInfos = m_pimpl->metaInfos; assert(hasElement(a_hash)); auto const IT = std::find_if(std::begin(metaInfos), std::end(metaInfos), [a_hash](auto const &a_metaInfo) { return a_metaInfo.hash == a_hash; }); return *IT; } Registry::MetaInfo const &Registry::metaInfoAt(size_t const a_index) const { auto const &META_INFOS = m_pimpl->metaInfos; return META_INFOS[a_index]; } } // namespace spaghetti <commit_msg>Load symlinks too<commit_after>// MIT License // // Copyright (c) 2017-2018 Artur Wyszyński, aljen at hitomi dot pl // // 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 "spaghetti/registry.h" #include <vector> #include "filesystem.h" #include "shared_library.h" #include "elements/all.h" #include "nodes/all.h" #include "spaghetti/logger.h" #include "spaghetti/version.h" inline void init_resources() { Q_INIT_RESOURCE(icons); } namespace spaghetti { struct Registry::PIMPL { using Plugins = std::vector<std::shared_ptr<SharedLibrary>>; using MetaInfos = std::vector<MetaInfo>; MetaInfos metaInfos{}; Plugins plugins{}; }; Registry &Registry::get() { static Registry s_registry{}; return s_registry; } Registry::~Registry() = default; Registry::Registry() : m_pimpl{ std::make_unique<PIMPL>() } { log::init(); log::info("Spaghetti version: {}, git: {}@{}, build date: {}, {}", version::STRING, version::BRANCH, version::COMMIT_SHORT_HASH, __DATE__, __TIME__); } void Registry::registerInternalElements() { init_resources(); using namespace elements; registerElement<Package>("Package", ":/logic/package.png"); registerElement<gates::And>("AND (Bool)", ":/gates/and.png"); registerElement<gates::Nand>("NAND (Bool)", ":/gates/nand.png"); registerElement<gates::Nor>("NOR (Bool)", ":/gates/nor.png"); registerElement<gates::Not>("NOT (Bool)", ":/gates/not.png"); registerElement<gates::Or>("OR (Bool)", ":/gates/or.png"); registerElement<logic::IfGreaterEqual>("If A >= B (Float)", ":/unknown.png"); registerElement<logic::IfGreater>("If A > B (Float)", ":/unknown.png"); registerElement<logic::IfEqual>("If A == B (Float)", ":/unknown.png"); registerElement<logic::IfLower>("If A < B (Float)", ":/unknown.png"); registerElement<logic::IfLowerEqual>("If A <= B (Float)", ":/unknown.png"); registerElement<logic::MultiplexerInt>("Multiplexer (Int)", ":/unknown.png"); registerElement<logic::DemultiplexerInt>("Demultiplexer (Int)", ":/unknown.png"); registerElement<logic::Blinker, nodes::logic::Blinker>("Blinker (Bool)", ":/unknown.png"); registerElement<logic::Clock, nodes::logic::Clock>("Clock (ms)", ":/logic/clock.png"); registerElement<logic::Switch>("Switch (Int)", ":/logic/switch.png"); registerElement<math::Abs>("Abs (Float)", ":/unknown.png"); registerElement<math::Add>("Add (Float)", ":/unknown.png"); registerElement<math::AddIf>("Add If (Float)", ":/unknown.png"); registerElement<math::Subtract>("Subtract (Float)", ":/unknown.png"); registerElement<math::SubtractIf>("Subtract If (Float)", ":/unknown.png"); registerElement<math::Divide>("Divide (Float)", ":/unknown.png"); registerElement<math::DivideIf>("Divide If (Float)", ":/unknown.png"); registerElement<math::Multiply>("Multiply (Float)", ":/unknown.png"); registerElement<math::MultiplyIf>("Multiply If (Float)", ":/unknown.png"); registerElement<math::Cos>("Cos (Rad)", ":/unknown.png"); registerElement<math::Sin>("Sin (Rad)", ":/unknown.png"); registerElement<ui::FloatInfo, nodes::ui::FloatInfo>("Info (Float)", ":/values/const_float.png"); registerElement<ui::IntInfo, nodes::ui::IntInfo>("Info (Int)", ":/values/const_int.png"); registerElement<ui::PushButton, nodes::ui::PushButton>("Push Button (Bool)", ":/ui/push_button.png"); registerElement<ui::ToggleButton, nodes::ui::ToggleButton>("Toggle Button (Bool)", ":/ui/toggle_button.png"); registerElement<values::ConstBool, nodes::values::ConstBool>("Const value (Bool)", ":/values/const_bool.png"); registerElement<values::ConstFloat, nodes::values::ConstFloat>("Const value (Float)", ":/values/const_float.png"); registerElement<values::ConstInt, nodes::values::ConstInt>("Const value (Int)", ":/values/const_int.png"); registerElement<values::RandomBool>("Random value (Bool)", ":/values/random_value.png"); registerElement<values::Degree2Radian>("Convert angle (Deg2Rad)", ":/unknown.png"); registerElement<values::Radian2Degree>("Convert angle (Rad2Deg)", ":/unknown.png"); registerElement<values::Int2Float>("Convert value (Int2Float)", ":/unknown.png"); registerElement<values::Float2Int>("Convert value (Float2Int)", ":/unknown.png"); registerElement<values::MinInt>("Minimum value (Int)", ":/unknown.png"); registerElement<values::MaxInt>("Maximum value (Int)", ":/unknown.png"); registerElement<values::MinFloat>("Minimum value (Float)", ":/unknown.png"); registerElement<values::MaxFloat>("Maximum value (Float)", ":/unknown.png"); registerElement<values::ClampFloat>("Clamp value (Float)", ":/unknown.png"); registerElement<values::ClampInt>("Clamp value (Int)", ":/unknown.png"); } void Registry::loadPlugins() { fs::path const PLUGINS_DIR{ "../plugins" }; if (!fs::is_directory(PLUGINS_DIR)) return; for (auto const &ENTRY : fs::directory_iterator(PLUGINS_DIR)) { spaghetti::log::info("Loading {}..", ENTRY.path().string()); if (!(fs::is_regular_file(ENTRY) || fs::is_symlink(ENTRY))) continue; std::error_code error{}; auto plugin = std::make_shared<SharedLibrary>(ENTRY, error); if (error.value() != 0 || !plugin->has("register_plugin")) continue; auto registerPlugin = plugin->get<void(Registry &)>("register_plugin"); registerPlugin(*this); m_pimpl->plugins.emplace_back(std::move(plugin)); } } Element *Registry::createElement(string::hash_t const a_hash) { auto const &META_INFO = metaInfoFor(a_hash); assert(META_INFO.cloneElement); return META_INFO.cloneElement(); } Node *Registry::createNode(string::hash_t const a_hash) { auto const &META_INFO = metaInfoFor(a_hash); assert(META_INFO.cloneNode); return META_INFO.cloneNode(); } std::string Registry::elementName(string::hash_t const a_hash) { auto const &META_INFO = metaInfoFor(a_hash); return META_INFO.name; } std::string Registry::elementIcon(string::hash_t const a_hash) { auto const &META_INFO = metaInfoFor(a_hash); return META_INFO.icon; } void Registry::addElement(MetaInfo &a_metaInfo) { auto &metaInfos = m_pimpl->metaInfos; metaInfos.push_back(std::move(a_metaInfo)); } bool Registry::hasElement(string::hash_t const a_hash) const { auto const &META_INFOS = m_pimpl->metaInfos; auto const IT = std::find_if(std::begin(META_INFOS), std::end(META_INFOS), [a_hash](auto const &a_metaInfo) { return a_metaInfo.hash == a_hash; }); return IT != std::end(META_INFOS); } size_t Registry::size() const { auto const &META_INFOS = m_pimpl->metaInfos; return META_INFOS.size(); } Registry::MetaInfo const &Registry::metaInfoFor(string::hash_t const a_hash) const { auto &metaInfos = m_pimpl->metaInfos; assert(hasElement(a_hash)); auto const IT = std::find_if(std::begin(metaInfos), std::end(metaInfos), [a_hash](auto const &a_metaInfo) { return a_metaInfo.hash == a_hash; }); return *IT; } Registry::MetaInfo const &Registry::metaInfoAt(size_t const a_index) const { auto const &META_INFOS = m_pimpl->metaInfos; return META_INFOS[a_index]; } } // namespace spaghetti <|endoftext|>
<commit_before>/** * @file PipeProcess.hpp * @brief PipeProcess class prototype. * @author zer0 * @date 2016-05-19 */ #ifndef __INCLUDE_LIBTBAG__LIBTBAG_PROCESS_PIPEPROCESS_HPP__ #define __INCLUDE_LIBTBAG__LIBTBAG_PROCESS_PIPEPROCESS_HPP__ // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif #include <libtbag/config.h> #include <libtbag/process/Process.hpp> #include <array> #include <vector> #include <sstream> #include <iostream> // ------------------- NAMESPACE_LIBTBAG_OPEN // ------------------- namespace process { /** * PipeProcess class prototype. * * @author zer0 * @date 2016-05-19 */ class PipeProcess : public Process { public: static constexpr int const STANDARD_INPUT_FD = 0; ///< @c stdin static constexpr int const STANDARD_OUTPUT_FD = 1; ///< @c stdout static constexpr int const STANDARD_ERROR_FD = 2; ///< @c stderr static constexpr int const STDIO_SIZE = 3; private: uv_pipe_t _pipe_stdin; uv_pipe_t _pipe_stdout; uv_pipe_t _pipe_stderr; std::array<uv_stdio_container_t, STDIO_SIZE> _stdios; private: std::vector<char> _buffer_stdout; std::vector<char> _buffer_stderr; std::stringstream _stream_stdout; std::stringstream _stream_stderr; public: PipeProcess() { this->initPipe(); this->addHandle((uv_handle_t*)&this->_pipe_stdin); this->addHandle((uv_handle_t*)&this->_pipe_stdout); this->addHandle((uv_handle_t*)&this->_pipe_stderr); } virtual ~PipeProcess() { this->removeHandle((uv_handle_t*)&this->_pipe_stdin); this->removeHandle((uv_handle_t*)&this->_pipe_stdout); this->removeHandle((uv_handle_t*)&this->_pipe_stderr); } private: void initPipe() { // The ipc argument is a boolean to indicate // if this pipe will be used for handle passing between processes. int const ENABLE_IPC = 1; int const DISABLE_IPC = 0; REMOVE_UNUSED_VARIABLE(ENABLE_IPC); REMOVE_UNUSED_VARIABLE(DISABLE_IPC); uv_pipe_init(this->getLoopPointer(), &_pipe_stdin , DISABLE_IPC); uv_pipe_init(this->getLoopPointer(), &_pipe_stdout, DISABLE_IPC); uv_pipe_init(this->getLoopPointer(), &_pipe_stderr, DISABLE_IPC); uv_stdio_flags const READ_PIPE_FLAGS = static_cast<uv_stdio_flags>(UV_CREATE_PIPE | UV_READABLE_PIPE); uv_stdio_flags const WRITE_PIPE_FLAGS = static_cast<uv_stdio_flags>(UV_CREATE_PIPE | UV_WRITABLE_PIPE); this->_stdios[STANDARD_INPUT_FD].flags = READ_PIPE_FLAGS; this->_stdios[STANDARD_INPUT_FD].data.stream = (uv_stream_t*)&this->_pipe_stdin; this->_stdios[STANDARD_OUTPUT_FD].flags = WRITE_PIPE_FLAGS; this->_stdios[STANDARD_OUTPUT_FD].data.stream = (uv_stream_t*)&this->_pipe_stdout; this->_stdios[STANDARD_ERROR_FD ].flags = WRITE_PIPE_FLAGS; this->_stdios[STANDARD_ERROR_FD ].data.stream = (uv_stream_t*)&this->_pipe_stderr; uv_process_options_t & options = this->atOptions(); options.stdio = &this->_stdios[0]; options.stdio_count = STDIO_SIZE; } private: void reallocWithStreamBuffer(std::vector<char> & buffer, std::size_t size) { if (buffer.size() < size) { buffer.resize(size); } } public: virtual void onAlloc(uv_handle_t * handle, size_t suggested_size, uv_buf_t * buf) override { if (handle == (uv_handle_t*)&this->_pipe_stdout) { reallocWithStreamBuffer(this->_buffer_stdout, suggested_size); buf->base = &this->_buffer_stdout[0]; buf->len = this->_buffer_stdout.size(); } else if (handle == (uv_handle_t*)&this->_pipe_stderr) { reallocWithStreamBuffer(this->_buffer_stderr, suggested_size); buf->base = &this->_buffer_stderr[0]; buf->len = this->_buffer_stderr.size(); } else { // ERROR. } } public: virtual void onRead(uv_stream_t * stream, ssize_t nread, uv_buf_t const * buf) override { if (nread == UV_EOF) { // END OF FILE. } else if (nread < 0){ // ERROR. } else { if (stream == (uv_stream_t*)&this->_pipe_stdout) { this->_stream_stdout.write(&this->_buffer_stdout[0], nread); } else if (stream == (uv_stream_t*)&this->_pipe_stderr) { this->_stream_stderr.write(&this->_buffer_stderr[0], nread); } else { // ERROR. } } } public: virtual void onWrite(uv_write_t * req, int status) override { if (status == 0) { // SUCCESS. } else { // ERROR. } } public: bool read() { int error_code = 0; REMOVE_UNUSED_VARIABLE(error_code); error_code |= uv_read_start((uv_stream_t*) &this->_pipe_stdout, &loop::uv_event::onAlloc, &loop::uv_event::onRead); assert(error_code == 0); error_code |= uv_read_start((uv_stream_t*) &this->_pipe_stderr, &loop::uv_event::onAlloc, &loop::uv_event::onRead); assert(error_code == 0); return (error_code == 0 ? true : false); } private: std::string _standard_input_cache; public: void setStandardInput(std::string const & input) { this->_standard_input_cache = input; } private: std::vector<char> _buffer_stdin; uv_buf_t _buffer_info_stdin; uv_write_t _write_stdin; private: bool write(std::string const & write) { this->_buffer_stdin.clear(); this->_buffer_stdin.insert(this->_buffer_stdin.begin(), write.begin(), write.end()); this->_buffer_info_stdin.base = &this->_buffer_stdin[0]; this->_buffer_info_stdin.len = this->_buffer_stdin.size(); int error_code = 0; REMOVE_UNUSED_VARIABLE(error_code); error_code = uv_write(&this->_write_stdin , (uv_stream_t*) &this->_pipe_stdin , &this->_buffer_info_stdin , 1 , &loop::uv_event::onWrite); // std::cout << uv_err_name(error_code) << ": " // << uv_strerror(error_code) << std::endl; return (error_code == 0 ? true : false); } bool write() { return this->write(this->_standard_input_cache); } public: virtual bool exe() override { if (this->spawn() && this->write() && this->read()) { return this->runDefault(); } return false; } public: std::string getStandardOutput() const { return this->_stream_stdout.str(); } std::string getStandardError() const { return this->_stream_stderr.str(); } }; } // namespace process // -------------------- NAMESPACE_LIBTBAG_CLOSE // -------------------- #endif // __INCLUDE_LIBTBAG__LIBTBAG_PROCESS_PIPEPROCESS_HPP__ <commit_msg>Trivial commit.<commit_after>/** * @file PipeProcess.hpp * @brief PipeProcess class prototype. * @author zer0 * @date 2016-05-19 */ #ifndef __INCLUDE_LIBTBAG__LIBTBAG_PROCESS_PIPEPROCESS_HPP__ #define __INCLUDE_LIBTBAG__LIBTBAG_PROCESS_PIPEPROCESS_HPP__ // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif #include <libtbag/config.h> #include <libtbag/process/Process.hpp> #include <array> #include <vector> #include <sstream> // ------------------- NAMESPACE_LIBTBAG_OPEN // ------------------- namespace process { /** * PipeProcess class prototype. * * @author zer0 * @date 2016-05-19 */ class PipeProcess : public Process { public: static constexpr int const STANDARD_INPUT_FD = 0; ///< @c stdin static constexpr int const STANDARD_OUTPUT_FD = 1; ///< @c stdout static constexpr int const STANDARD_ERROR_FD = 2; ///< @c stderr static constexpr int const STDIO_SIZE = 3; private: uv_pipe_t _pipe_stdin; uv_pipe_t _pipe_stdout; uv_pipe_t _pipe_stderr; std::array<uv_stdio_container_t, STDIO_SIZE> _stdios; private: std::vector<char> _buffer_stdout; std::vector<char> _buffer_stderr; std::stringstream _stream_stdout; std::stringstream _stream_stderr; public: PipeProcess() { this->initPipe(); this->addHandle((uv_handle_t*)&this->_pipe_stdin); this->addHandle((uv_handle_t*)&this->_pipe_stdout); this->addHandle((uv_handle_t*)&this->_pipe_stderr); } virtual ~PipeProcess() { this->removeHandle((uv_handle_t*)&this->_pipe_stdin); this->removeHandle((uv_handle_t*)&this->_pipe_stdout); this->removeHandle((uv_handle_t*)&this->_pipe_stderr); } private: void initPipe() { // The ipc argument is a boolean to indicate // if this pipe will be used for handle passing between processes. int const ENABLE_IPC = 1; int const DISABLE_IPC = 0; REMOVE_UNUSED_VARIABLE(ENABLE_IPC); REMOVE_UNUSED_VARIABLE(DISABLE_IPC); uv_pipe_init(this->getLoopPointer(), &_pipe_stdin , DISABLE_IPC); uv_pipe_init(this->getLoopPointer(), &_pipe_stdout, DISABLE_IPC); uv_pipe_init(this->getLoopPointer(), &_pipe_stderr, DISABLE_IPC); uv_stdio_flags const READ_PIPE_FLAGS = static_cast<uv_stdio_flags>(UV_CREATE_PIPE | UV_READABLE_PIPE); uv_stdio_flags const WRITE_PIPE_FLAGS = static_cast<uv_stdio_flags>(UV_CREATE_PIPE | UV_WRITABLE_PIPE); this->_stdios[STANDARD_INPUT_FD].flags = READ_PIPE_FLAGS; this->_stdios[STANDARD_INPUT_FD].data.stream = (uv_stream_t*)&this->_pipe_stdin; this->_stdios[STANDARD_OUTPUT_FD].flags = WRITE_PIPE_FLAGS; this->_stdios[STANDARD_OUTPUT_FD].data.stream = (uv_stream_t*)&this->_pipe_stdout; this->_stdios[STANDARD_ERROR_FD ].flags = WRITE_PIPE_FLAGS; this->_stdios[STANDARD_ERROR_FD ].data.stream = (uv_stream_t*)&this->_pipe_stderr; uv_process_options_t & options = this->atOptions(); options.stdio = &this->_stdios[0]; options.stdio_count = STDIO_SIZE; } private: void reallocWithStreamBuffer(std::vector<char> & buffer, std::size_t size) { if (buffer.size() < size) { buffer.resize(size); } } public: virtual void onAlloc(uv_handle_t * handle, size_t suggested_size, uv_buf_t * buf) override { if (handle == (uv_handle_t*)&this->_pipe_stdout) { reallocWithStreamBuffer(this->_buffer_stdout, suggested_size); buf->base = &this->_buffer_stdout[0]; buf->len = this->_buffer_stdout.size(); } else if (handle == (uv_handle_t*)&this->_pipe_stderr) { reallocWithStreamBuffer(this->_buffer_stderr, suggested_size); buf->base = &this->_buffer_stderr[0]; buf->len = this->_buffer_stderr.size(); } else { // ERROR. } } public: virtual void onRead(uv_stream_t * stream, ssize_t nread, uv_buf_t const * buf) override { if (nread == UV_EOF) { // END OF FILE. } else if (nread < 0){ // ERROR. } else { if (stream == (uv_stream_t*)&this->_pipe_stdout) { this->_stream_stdout.write(&this->_buffer_stdout[0], nread); } else if (stream == (uv_stream_t*)&this->_pipe_stderr) { this->_stream_stderr.write(&this->_buffer_stderr[0], nread); } else { // ERROR. } } } public: virtual void onWrite(uv_write_t * req, int status) override { if (status == 0) { // SUCCESS. } else { // ERROR. } } public: bool read() { int error_code = 0; REMOVE_UNUSED_VARIABLE(error_code); error_code |= uv_read_start((uv_stream_t*) &this->_pipe_stdout, &loop::uv_event::onAlloc, &loop::uv_event::onRead); assert(error_code == 0); error_code |= uv_read_start((uv_stream_t*) &this->_pipe_stderr, &loop::uv_event::onAlloc, &loop::uv_event::onRead); assert(error_code == 0); return (error_code == 0 ? true : false); } private: std::string _standard_input_cache; public: void setStandardInput(std::string const & input) { this->_standard_input_cache = input; } private: std::vector<char> _buffer_stdin; uv_buf_t _buffer_info_stdin; uv_write_t _write_stdin; private: bool write(std::string const & write) { this->_buffer_stdin.clear(); this->_buffer_stdin.insert(this->_buffer_stdin.begin(), write.begin(), write.end()); this->_buffer_info_stdin.base = &this->_buffer_stdin[0]; this->_buffer_info_stdin.len = this->_buffer_stdin.size(); int error_code = 0; REMOVE_UNUSED_VARIABLE(error_code); error_code = uv_write(&this->_write_stdin , (uv_stream_t*) &this->_pipe_stdin , &this->_buffer_info_stdin , 1 , &loop::uv_event::onWrite); // std::cout << uv_err_name(error_code) << ": " // << uv_strerror(error_code) << std::endl; return (error_code == 0 ? true : false); } bool write() { return this->write(this->_standard_input_cache); } public: virtual bool exe() override { if (this->spawn() && this->write() && this->read()) { return this->runDefault(); } return false; } public: std::string getStandardOutput() const { return this->_stream_stdout.str(); } std::string getStandardError() const { return this->_stream_stderr.str(); } }; } // namespace process // -------------------- NAMESPACE_LIBTBAG_CLOSE // -------------------- #endif // __INCLUDE_LIBTBAG__LIBTBAG_PROCESS_PIPEPROCESS_HPP__ <|endoftext|>
<commit_before> #include "ksp_plugin/planetarium.hpp" #include <vector> #include "geometry/point.hpp" namespace principia { namespace ksp_plugin { namespace internal_planetarium { using geometry::Position; using geometry::RP2Line; using quantities::Time; Planetarium::Parameters::Parameters(double const sphere_radius_multiplier) : sphere_radius_multiplier_(sphere_radius_multiplier) {} Planetarium::Planetarium( Parameters const& parameters, Perspective<Navigation, Camera, Length, OrthogonalMap> const& perspective, not_null<Ephemeris<Barycentric> const*> const ephemeris, not_null<NavigationFrame const*> const plotting_frame) : parameters_(parameters), perspective_(perspective), ephemeris_(ephemeris), plotting_frame_(plotting_frame) {} RP2Lines<Length, Camera> Planetarium::PlotMethod0( DiscreteTrajectory<Barycentric>::Iterator const& begin, DiscreteTrajectory<Barycentric>::Iterator const& end, Instant const& now) const { auto const plottable_spheres = ComputePlottableSpheres(now); auto const plottable_segments = ComputePlottableSegments(plottable_spheres, begin, end); RP2Lines<Length, Camera> rp2_lines; for (auto const& plottable_segment : plottable_segments) { // Apply the projection to the current plottable segment. auto const rp2_first = perspective_(plottable_segment.first); auto const rp2_second = perspective_(plottable_segment.second); // Ignore any segment that goes behind the camera. // TODO(phl): These segments should probably be clipped to the focal plane. if (!rp2_first || !rp2_second) { continue; } // Create a new ℝP² line when two segments are not consecutive. if (rp2_lines.empty() || rp2_lines.back().back() != *rp2_first) { RP2Line<Length, Camera> const rp2_line = {*rp2_first, *rp2_second}; rp2_lines.push_back(rp2_line); } else { rp2_lines.back().push_back(*rp2_second); } } return rp2_lines; } std::vector<Sphere<Length, Navigation>> Planetarium::ComputePlottableSpheres( Instant const& now) const { RigidMotion<Barycentric, Navigation> const rigid_motion_at_now = plotting_frame_->ToThisFrameAtTime(now); std::vector<Sphere<Length, Navigation>> plottable_spheres; auto const& bodies = ephemeris_->bodies(); for (auto const body : bodies) { auto const trajectory = ephemeris_->trajectory(body); Length const mean_radius = body->mean_radius(); Position<Barycentric> const centre_in_barycentric = trajectory->EvaluatePosition(now); // TODO(phl): Don't create a plottable sphere if the body is very far from // the camera. What should the criterion be? plottable_spheres.emplace_back( rigid_motion_at_now.rigid_transformation()(centre_in_barycentric), parameters_.sphere_radius_multiplier_ * mean_radius); } return plottable_spheres; } std::vector<Segment<Displacement<Navigation>>> Planetarium::ComputePlottableSegments( const std::vector<Sphere<Length, Navigation>>& plottable_spheres, DiscreteTrajectory<Barycentric>::Iterator const& begin, DiscreteTrajectory<Barycentric>::Iterator const& end) const { std::vector<Segment<Displacement<Navigation>>> all_segments; if (begin == end) { return all_segments; } auto it1 = begin; Instant t1 = it1.time(); RigidMotion<Barycentric, Navigation> rigid_motion_at_t1 = plotting_frame_->ToThisFrameAtTime(t1); Position<Navigation> p1 = rigid_motion_at_t1(it1.degrees_of_freedom()).position(); auto it2 = it1; while (++it2 != end) { // Processing one segment of the trajectory. Instant const t2 = it2.time(); // Transform the degrees of freedom to the plotting frame. RigidMotion<Barycentric, Navigation> const rigid_motion_at_t2 = plotting_frame_->ToThisFrameAtTime(t2); Position<Navigation> const p2 = rigid_motion_at_t2(it2.degrees_of_freedom()).position(); // Use the perspective to compute the visible segments in the Navigation // frame. const Segment<Displacement<Navigation>> segment = {p1, p2}; auto segments = perspective_.VisibleSegments(segment, plottable_spheres); std::move(segments.begin(), segments.end(), std::back_inserter(all_segments)); it1 = it2; t1 = t2; rigid_motion_at_t1 = rigid_motion_at_t2; p1 = p2; } return all_segments; } } // namespace internal_planetarium } // namespace ksp_plugin } // namespace principia <commit_msg>Truncate at the focal plane for plotting.<commit_after> #include "ksp_plugin/planetarium.hpp" #include <vector> #include "geometry/point.hpp" namespace principia { namespace ksp_plugin { namespace internal_planetarium { using geometry::Position; using geometry::RP2Line; using quantities::Time; Planetarium::Parameters::Parameters(double const sphere_radius_multiplier) : sphere_radius_multiplier_(sphere_radius_multiplier) {} Planetarium::Planetarium( Parameters const& parameters, Perspective<Navigation, Camera, Length, OrthogonalMap> const& perspective, not_null<Ephemeris<Barycentric> const*> const ephemeris, not_null<NavigationFrame const*> const plotting_frame) : parameters_(parameters), perspective_(perspective), ephemeris_(ephemeris), plotting_frame_(plotting_frame) {} RP2Lines<Length, Camera> Planetarium::PlotMethod0( DiscreteTrajectory<Barycentric>::Iterator const& begin, DiscreteTrajectory<Barycentric>::Iterator const& end, Instant const& now) const { auto const plottable_spheres = ComputePlottableSpheres(now); auto const plottable_segments = ComputePlottableSegments(plottable_spheres, begin, end); RP2Lines<Length, Camera> rp2_lines; for (auto const& plottable_segment : plottable_segments) { // Apply the projection to the current plottable segment. auto const rp2_first = perspective_(plottable_segment.first); auto const rp2_second = perspective_(plottable_segment.second); // Create a new ℝP² line when two segments are not consecutive. if (rp2_lines.empty() || rp2_lines.back().back() != rp2_first) { RP2Line<Length, Camera> const rp2_line = {rp2_first, rp2_second}; rp2_lines.push_back(rp2_line); } else { rp2_lines.back().push_back(rp2_second); } } return rp2_lines; } std::vector<Sphere<Length, Navigation>> Planetarium::ComputePlottableSpheres( Instant const& now) const { RigidMotion<Barycentric, Navigation> const rigid_motion_at_now = plotting_frame_->ToThisFrameAtTime(now); std::vector<Sphere<Length, Navigation>> plottable_spheres; auto const& bodies = ephemeris_->bodies(); for (auto const body : bodies) { auto const trajectory = ephemeris_->trajectory(body); Length const mean_radius = body->mean_radius(); Position<Barycentric> const centre_in_barycentric = trajectory->EvaluatePosition(now); // TODO(phl): Don't create a plottable sphere if the body is very far from // the camera. What should the criterion be? plottable_spheres.emplace_back( rigid_motion_at_now.rigid_transformation()(centre_in_barycentric), parameters_.sphere_radius_multiplier_ * mean_radius); } return plottable_spheres; } std::vector<Segment<Displacement<Navigation>>> Planetarium::ComputePlottableSegments( const std::vector<Sphere<Length, Navigation>>& plottable_spheres, DiscreteTrajectory<Barycentric>::Iterator const& begin, DiscreteTrajectory<Barycentric>::Iterator const& end) const { std::vector<Segment<Displacement<Navigation>>> all_segments; if (begin == end) { return all_segments; } auto it1 = begin; Instant t1 = it1.time(); RigidMotion<Barycentric, Navigation> rigid_motion_at_t1 = plotting_frame_->ToThisFrameAtTime(t1); Position<Navigation> p1 = rigid_motion_at_t1(it1.degrees_of_freedom()).position(); auto it2 = it1; while (++it2 != end) { // Processing one segment of the trajectory. Instant const t2 = it2.time(); // Transform the degrees of freedom to the plotting frame. RigidMotion<Barycentric, Navigation> const rigid_motion_at_t2 = plotting_frame_->ToThisFrameAtTime(t2); Position<Navigation> const p2 = rigid_motion_at_t2(it2.degrees_of_freedom()).position(); // Find the part of the segment that is behind the focal plane. We don't // care about things that are in front of the focal plane. const Segment<Displacement<Navigation>> segment = {p1, p2}; auto const segment_behind_focal_plane = perspective_.SegmentBehindFocalPlane(segment); if (segment_behind_focal_plane) { // Find the part(s) of the segment that are not hidden by spheres. These // are the ones we want to plot. auto segments = perspective_.VisibleSegments(*segment_behind_focal_plane, plottable_spheres); std::move(segments.begin(), segments.end(), std::back_inserter(all_segments)); } it1 = it2; t1 = t2; rigid_motion_at_t1 = rigid_motion_at_t2; p1 = p2; } return all_segments; } } // namespace internal_planetarium } // namespace ksp_plugin } // namespace principia <|endoftext|>
<commit_before>/* Copyright (c) 2008-2020 Jan W. Krieger (<jan@jkrieger.de>) last modification: $LastChangedDate$ (revision $Rev$) This software is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation, either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License (LGPL) for more details. You should have received a copy of the GNU Lesser General Public License (LGPL) along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "jkqttools.h" #include <QList> #include <QApplication> #include <QLocale> #include <QtCore> #if (QT_VERSION>QT_VERSION_CHECK(5, 3, 0)) # include <QScreen> # include <QGuiApplication> #else # include <QDesktopWidget> #endif #if QT_VERSION>=QT_VERSION_CHECK(6,0,0) # include <QByteArrayView> #endif void jksaveWidgetGeometry(QSettings& settings, QWidget* widget, const QString& prefix) { settings.setValue(prefix+"pos", widget->pos()); settings.setValue(prefix+"size", widget->size()); } void jkloadWidgetGeometry(QSettings& settings, QWidget* widget, QPoint defaultPosition, QSize defaultSize, const QString& prefix) { QPoint pos = settings.value(prefix+"pos", defaultPosition).toPoint(); const QSize size = settings.value(prefix+"size", defaultSize).toSize(); #if (QT_VERSION>=QT_VERSION_CHECK(5, 3, 0)) const auto widgeo = widget->screen()->geometry(); #else const auto widgeo = QApplication::desktop()->screenGeometry(widget); #endif widget->resize(size.boundedTo(widgeo.size())); if (pos.x()<0 || pos.x()>widgeo.width()) pos.setX(0); if (pos.y()<0 || pos.y()>widgeo.height()) pos.setY(0); widget->move(pos); } void jkloadWidgetGeometry(QSettings& settings, QWidget* widget, const QString& prefix) { jkloadWidgetGeometry(settings, widget, QPoint(10, 10), QSize(100, 100), prefix); } void jksaveSplitter(QSettings& settings, QSplitter* splitter, const QString& prefix) { /*QList<int> sizes=splitter->sizes(); QString data=""; for (int i=0; i<sizes.size(); i++) { if (!data.isEmpty()) data=data+","; data=data+QLocale::system().toString(sizes[i]); } settings.setValue(prefix+"splitter_sizes", data);*/ settings.setValue(prefix+"splitter_sizes", splitter->saveState()); } void jkloadSplitter(QSettings& settings, QSplitter* splitter, const QString& prefix) { /*QString data=settings.value(prefix+"splitter_sizes", "").toString(); QList<int> sizes, s1; QStringList sl=data.split(","); for (int i=0; i<sl.size(); i++) { sizes.append(sl[i].toInt()); } s1=splitter->sizes(); for (int i=0; i<s1.count(); i++) { if (i<sizes.size()) s1[i]=sizes[i]; }*/ splitter->restoreState(settings.value(prefix+"splitter_sizes").toByteArray()); } QString jkVariantListToString(const QList<QVariant>& data, const QString& separator) { QString r=""; QLocale loc=QLocale::c(); loc.setNumberOptions(QLocale::OmitGroupSeparator); for (int i=0; i<data.size(); i++) { if (i>0) r=r+separator; QVariant v=data[i]; #if (QT_VERSION>=QT_VERSION_CHECK(6, 0, 0)) if (v.typeId()==QMetaType::Bool) r=r+loc.toString(v.toBool()); else if (v.typeId()==QMetaType::Char) r=r+loc.toString(v.toInt()); else if (v.typeId()==QMetaType::QDate) r=r+loc.toString(v.toDate()); else if (v.typeId()==QMetaType::QDateTime) r=r+loc.toString(v.toDateTime()); else if (v.typeId()==QMetaType::Double) r=r+loc.toString(v.toDouble()); else if (v.typeId()==QMetaType::Int) r=r+loc.toString(v.toInt()); else if (v.typeId()==QMetaType::LongLong) r=r+loc.toString(v.toLongLong()); else if (v.typeId()==QMetaType::QString) r=r+QString("\"%1\"").arg(v.toString().replace("\"", "_").replace("\t", " ").replace("\r", "").replace("\n", " ").replace(",", " ").replace(";", " ")); else if (v.typeId()==QMetaType::QTime) r=r+loc.toString(v.toTime()); else if (v.typeId()==QMetaType::UInt) r=r+loc.toString(v.toUInt()); else if (v.typeId()==QMetaType::ULongLong) r=r+loc.toString(v.toULongLong()); else r=r+v.toString(); #else switch (v.type()) { case QVariant::Bool: r=r+loc.toString(v.toBool()); break; case QVariant::Char: r=r+loc.toString(v.toInt()); break; case QVariant::Date: r=r+loc.toString(v.toDate()); break; case QVariant::DateTime: r=r+loc.toString(v.toDateTime()); break; case QVariant::Double: r=r+loc.toString(v.toDouble()); break; case QVariant::Int: r=r+loc.toString(v.toInt()); break; case QVariant::LongLong: r=r+loc.toString(v.toLongLong()); break; case QVariant::String: r=r+QString("\"%1\"").arg(v.toString().replace("\"", "_").replace("\t", " ").replace("\r", "").replace("\n", " ").replace(",", " ").replace(";", " ")); break; case QVariant::Time: r=r+loc.toString(v.toTime()); break; case QVariant::UInt: r=r+loc.toString(v.toUInt()); break; case QVariant::ULongLong: r=r+loc.toString(v.toULongLong()); break; //case : r=r+loc.toString(v.); break; default: r=r+v.toString(); break; } #endif } return r; } JKQTCOMMON_LIB_EXPORT QString jkqtp_filenameize(const QString& data) { QString r; QString data1=data.simplified(); for (int i=0; i<data1.size(); i++) { #if (QT_VERSION>=QT_VERSION_CHECK(6, 0, 0)) const auto c=data1[i]; #else QCharRef c=data1[i]; #endif if (c.isLetterOrNumber() || (c=='-') || (c=='_') || (c=='.')) { r+=c; } else { r+='_'; } } return r; } QString jkqtp_toValidVariableName(const QString& input) { QString out=""; for (int i=0; i<input.size(); i++) { if (input[i].isLetter()) out=out+input[i]; if (input[i].isDigit()&&(out.size()>0)) out=out+input[i]; if ((input[i]=='_')&&(out.size()>0)) out=out+input[i]; } return out; } QString jkqtp_KeyboardModifiers2String(Qt::KeyboardModifiers modifiers, bool useNONE) { if (modifiers==Qt::NoModifier) { if (useNONE) return "NONE"; else return ""; } QString ret=""; auto append=[](QString& ret, const QString & appending, const QString& separator="+") { if (appending.size()<=0) return; if (ret.size()>0) ret+=separator; ret+=appending; }; if ((modifiers&Qt::ShiftModifier)==Qt::ShiftModifier) append(ret, "SHIFT", "+"); if ((modifiers&Qt::ControlModifier)==Qt::ControlModifier) append(ret, "CTRL", "+"); if ((modifiers&Qt::AltModifier)==Qt::AltModifier) append(ret, "ALT", "+"); if ((modifiers&Qt::MetaModifier)==Qt::MetaModifier) append(ret, "META", "+"); if ((modifiers&Qt::KeypadModifier)==Qt::KeypadModifier) append(ret, "KEYPAD", "+"); if ((modifiers&Qt::GroupSwitchModifier)==Qt::GroupSwitchModifier) append(ret, "GROUP", "+"); return ret; } Qt::KeyboardModifiers jkqtp_String2KeyboardModifiers(const QString &modifiers) { auto mods=modifiers.toUpper().split("+"); Qt::KeyboardModifiers ret=Qt::NoModifier; for (const auto& m: mods) { if (m.trimmed()=="SHIFT") ret |= Qt::ShiftModifier; else if (m.trimmed()=="CTRL") ret |= Qt::ControlModifier; else if (m.trimmed()=="ALT") ret |= Qt::AltModifier; else if (m.trimmed()=="META") ret |= Qt::MetaModifier; else if (m.trimmed()=="KEYPAD") ret |= Qt::KeypadModifier; else if (m.trimmed()=="GROUP") ret |= Qt::GroupSwitchModifier; } return ret; } QString jkqtp_MouseButton2String(Qt::MouseButton button, bool useNONE) { if (button==Qt::NoButton) { if (useNONE) return "NONE"; else return ""; } if (button==Qt::LeftButton) return "LEFT"; if (button==Qt::RightButton) return "RIGHT"; #if (QT_VERSION>=QT_VERSION_CHECK(6, 0, 0)) if (button==Qt::MiddleButton) return "MIDDLE"; #else if (button==Qt::MidButton) return "MIDDLE"; #endif if (button==Qt::BackButton) return "BACK"; if (button==Qt::ForwardButton) return "FORWARD"; if (button==Qt::TaskButton) return "TASK"; if (button==Qt::ExtraButton4) return "EXTRA4"; if (button==Qt::ExtraButton5) return "EXTRA5"; if (button==Qt::ExtraButton6) return "EXTRA6"; if (button==Qt::ExtraButton7) return "EXTRA7"; if (button==Qt::ExtraButton8) return "EXTRA8"; if (button==Qt::ExtraButton9) return "EXTRA9"; if (button==Qt::ExtraButton10) return "EXTRA10"; if (button==Qt::ExtraButton11) return "EXTRA11"; if (button==Qt::ExtraButton12) return "EXTRA12"; if (button==Qt::ExtraButton13) return "EXTRA13"; if (button==Qt::ExtraButton14) return "EXTRA14"; if (button==Qt::ExtraButton15) return "EXTRA15"; if (button==Qt::ExtraButton16) return "EXTRA16"; if (button==Qt::ExtraButton17) return "EXTRA17"; if (button==Qt::ExtraButton18) return "EXTRA18"; if (button==Qt::ExtraButton19) return "EXTRA19"; if (button==Qt::ExtraButton20) return "EXTRA20"; if (button==Qt::ExtraButton21) return "EXTRA21"; if (button==Qt::ExtraButton22) return "EXTRA22"; if (button==Qt::ExtraButton23) return "EXTRA23"; if (button==Qt::ExtraButton24) return "EXTRA24"; return "UNKNOWN"; } Qt::MouseButton jkqtp_String2MouseButton(const QString &button) { auto but=button.toUpper().trimmed(); if (but=="LEFT") return Qt::LeftButton; if (but=="RIGHT") return Qt::RightButton; #if (QT_VERSION>=QT_VERSION_CHECK(6, 0, 0)) if (but=="MIDDLE") return Qt::MiddleButton; #else if (but=="MIDDLE") return Qt::MidButton; #endif if (but=="BACK") return Qt::BackButton; if (but=="FORWARD") return Qt::ForwardButton; if (but=="TASK") return Qt::TaskButton; if (but=="EXTRA4") return Qt::ExtraButton4; if (but=="EXTRA5") return Qt::ExtraButton5; if (but=="EXTRA6") return Qt::ExtraButton6; if (but=="EXTRA7") return Qt::ExtraButton7; if (but=="EXTRA8") return Qt::ExtraButton8; if (but=="EXTRA9") return Qt::ExtraButton9; if (but=="EXTRA10") return Qt::ExtraButton10; if (but=="EXTRA11") return Qt::ExtraButton11; if (but=="EXTRA12") return Qt::ExtraButton12; if (but=="EXTRA13") return Qt::ExtraButton13; if (but=="EXTRA14") return Qt::ExtraButton14; if (but=="EXTRA15") return Qt::ExtraButton15; if (but=="EXTRA16") return Qt::ExtraButton16; if (but=="EXTRA17") return Qt::ExtraButton17; if (but=="EXTRA18") return Qt::ExtraButton18; if (but=="EXTRA19") return Qt::ExtraButton19; if (but=="EXTRA20") return Qt::ExtraButton20; if (but=="EXTRA21") return Qt::ExtraButton21; if (but=="EXTRA22") return Qt::ExtraButton22; if (but=="EXTRA23") return Qt::ExtraButton23; if (but=="EXTRA24") return Qt::ExtraButton24; return Qt::NoButton; } quint16 jkqtp_checksum(const void *data, size_t len) { #if QT_VERSION>=QT_VERSION_CHECK(6,0,0) return qChecksum(QByteArrayView(static_cast<const uint8_t*>(data), len)); #else return qChecksum(static_cast<const char*>(data), len); #endif } <commit_msg>fix for Qt < 5.14<commit_after>/* Copyright (c) 2008-2020 Jan W. Krieger (<jan@jkrieger.de>) last modification: $LastChangedDate$ (revision $Rev$) This software is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation, either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License (LGPL) for more details. You should have received a copy of the GNU Lesser General Public License (LGPL) along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "jkqttools.h" #include <QList> #include <QApplication> #include <QLocale> #include <QtCore> #if (QT_VERSION>QT_VERSION_CHECK(5, 14, 0)) # include <QScreen> # include <QGuiApplication> #else # include <QDesktopWidget> #endif #if QT_VERSION>=QT_VERSION_CHECK(6,0,0) # include <QByteArrayView> #endif void jksaveWidgetGeometry(QSettings& settings, QWidget* widget, const QString& prefix) { settings.setValue(prefix+"pos", widget->pos()); settings.setValue(prefix+"size", widget->size()); } void jkloadWidgetGeometry(QSettings& settings, QWidget* widget, QPoint defaultPosition, QSize defaultSize, const QString& prefix) { QPoint pos = settings.value(prefix+"pos", defaultPosition).toPoint(); const QSize size = settings.value(prefix+"size", defaultSize).toSize(); #if (QT_VERSION>=QT_VERSION_CHECK(5, 14, 0)) const auto widgeo = widget->screen()->geometry(); #else const auto widgeo = QApplication::desktop()->screenGeometry(widget); #endif widget->resize(size.boundedTo(widgeo.size())); if (pos.x()<0 || pos.x()>widgeo.width()) pos.setX(0); if (pos.y()<0 || pos.y()>widgeo.height()) pos.setY(0); widget->move(pos); } void jkloadWidgetGeometry(QSettings& settings, QWidget* widget, const QString& prefix) { jkloadWidgetGeometry(settings, widget, QPoint(10, 10), QSize(100, 100), prefix); } void jksaveSplitter(QSettings& settings, QSplitter* splitter, const QString& prefix) { /*QList<int> sizes=splitter->sizes(); QString data=""; for (int i=0; i<sizes.size(); i++) { if (!data.isEmpty()) data=data+","; data=data+QLocale::system().toString(sizes[i]); } settings.setValue(prefix+"splitter_sizes", data);*/ settings.setValue(prefix+"splitter_sizes", splitter->saveState()); } void jkloadSplitter(QSettings& settings, QSplitter* splitter, const QString& prefix) { /*QString data=settings.value(prefix+"splitter_sizes", "").toString(); QList<int> sizes, s1; QStringList sl=data.split(","); for (int i=0; i<sl.size(); i++) { sizes.append(sl[i].toInt()); } s1=splitter->sizes(); for (int i=0; i<s1.count(); i++) { if (i<sizes.size()) s1[i]=sizes[i]; }*/ splitter->restoreState(settings.value(prefix+"splitter_sizes").toByteArray()); } QString jkVariantListToString(const QList<QVariant>& data, const QString& separator) { QString r=""; QLocale loc=QLocale::c(); loc.setNumberOptions(QLocale::OmitGroupSeparator); for (int i=0; i<data.size(); i++) { if (i>0) r=r+separator; QVariant v=data[i]; #if (QT_VERSION>=QT_VERSION_CHECK(6, 0, 0)) if (v.typeId()==QMetaType::Bool) r=r+loc.toString(v.toBool()); else if (v.typeId()==QMetaType::Char) r=r+loc.toString(v.toInt()); else if (v.typeId()==QMetaType::QDate) r=r+loc.toString(v.toDate()); else if (v.typeId()==QMetaType::QDateTime) r=r+loc.toString(v.toDateTime()); else if (v.typeId()==QMetaType::Double) r=r+loc.toString(v.toDouble()); else if (v.typeId()==QMetaType::Int) r=r+loc.toString(v.toInt()); else if (v.typeId()==QMetaType::LongLong) r=r+loc.toString(v.toLongLong()); else if (v.typeId()==QMetaType::QString) r=r+QString("\"%1\"").arg(v.toString().replace("\"", "_").replace("\t", " ").replace("\r", "").replace("\n", " ").replace(",", " ").replace(";", " ")); else if (v.typeId()==QMetaType::QTime) r=r+loc.toString(v.toTime()); else if (v.typeId()==QMetaType::UInt) r=r+loc.toString(v.toUInt()); else if (v.typeId()==QMetaType::ULongLong) r=r+loc.toString(v.toULongLong()); else r=r+v.toString(); #else switch (v.type()) { case QVariant::Bool: r=r+loc.toString(v.toBool()); break; case QVariant::Char: r=r+loc.toString(v.toInt()); break; case QVariant::Date: r=r+loc.toString(v.toDate()); break; case QVariant::DateTime: r=r+loc.toString(v.toDateTime()); break; case QVariant::Double: r=r+loc.toString(v.toDouble()); break; case QVariant::Int: r=r+loc.toString(v.toInt()); break; case QVariant::LongLong: r=r+loc.toString(v.toLongLong()); break; case QVariant::String: r=r+QString("\"%1\"").arg(v.toString().replace("\"", "_").replace("\t", " ").replace("\r", "").replace("\n", " ").replace(",", " ").replace(";", " ")); break; case QVariant::Time: r=r+loc.toString(v.toTime()); break; case QVariant::UInt: r=r+loc.toString(v.toUInt()); break; case QVariant::ULongLong: r=r+loc.toString(v.toULongLong()); break; //case : r=r+loc.toString(v.); break; default: r=r+v.toString(); break; } #endif } return r; } JKQTCOMMON_LIB_EXPORT QString jkqtp_filenameize(const QString& data) { QString r; QString data1=data.simplified(); for (int i=0; i<data1.size(); i++) { #if (QT_VERSION>=QT_VERSION_CHECK(6, 0, 0)) const auto c=data1[i]; #else QCharRef c=data1[i]; #endif if (c.isLetterOrNumber() || (c=='-') || (c=='_') || (c=='.')) { r+=c; } else { r+='_'; } } return r; } QString jkqtp_toValidVariableName(const QString& input) { QString out=""; for (int i=0; i<input.size(); i++) { if (input[i].isLetter()) out=out+input[i]; if (input[i].isDigit()&&(out.size()>0)) out=out+input[i]; if ((input[i]=='_')&&(out.size()>0)) out=out+input[i]; } return out; } QString jkqtp_KeyboardModifiers2String(Qt::KeyboardModifiers modifiers, bool useNONE) { if (modifiers==Qt::NoModifier) { if (useNONE) return "NONE"; else return ""; } QString ret=""; auto append=[](QString& ret, const QString & appending, const QString& separator="+") { if (appending.size()<=0) return; if (ret.size()>0) ret+=separator; ret+=appending; }; if ((modifiers&Qt::ShiftModifier)==Qt::ShiftModifier) append(ret, "SHIFT", "+"); if ((modifiers&Qt::ControlModifier)==Qt::ControlModifier) append(ret, "CTRL", "+"); if ((modifiers&Qt::AltModifier)==Qt::AltModifier) append(ret, "ALT", "+"); if ((modifiers&Qt::MetaModifier)==Qt::MetaModifier) append(ret, "META", "+"); if ((modifiers&Qt::KeypadModifier)==Qt::KeypadModifier) append(ret, "KEYPAD", "+"); if ((modifiers&Qt::GroupSwitchModifier)==Qt::GroupSwitchModifier) append(ret, "GROUP", "+"); return ret; } Qt::KeyboardModifiers jkqtp_String2KeyboardModifiers(const QString &modifiers) { auto mods=modifiers.toUpper().split("+"); Qt::KeyboardModifiers ret=Qt::NoModifier; for (const auto& m: mods) { if (m.trimmed()=="SHIFT") ret |= Qt::ShiftModifier; else if (m.trimmed()=="CTRL") ret |= Qt::ControlModifier; else if (m.trimmed()=="ALT") ret |= Qt::AltModifier; else if (m.trimmed()=="META") ret |= Qt::MetaModifier; else if (m.trimmed()=="KEYPAD") ret |= Qt::KeypadModifier; else if (m.trimmed()=="GROUP") ret |= Qt::GroupSwitchModifier; } return ret; } QString jkqtp_MouseButton2String(Qt::MouseButton button, bool useNONE) { if (button==Qt::NoButton) { if (useNONE) return "NONE"; else return ""; } if (button==Qt::LeftButton) return "LEFT"; if (button==Qt::RightButton) return "RIGHT"; #if (QT_VERSION>=QT_VERSION_CHECK(6, 0, 0)) if (button==Qt::MiddleButton) return "MIDDLE"; #else if (button==Qt::MidButton) return "MIDDLE"; #endif if (button==Qt::BackButton) return "BACK"; if (button==Qt::ForwardButton) return "FORWARD"; if (button==Qt::TaskButton) return "TASK"; if (button==Qt::ExtraButton4) return "EXTRA4"; if (button==Qt::ExtraButton5) return "EXTRA5"; if (button==Qt::ExtraButton6) return "EXTRA6"; if (button==Qt::ExtraButton7) return "EXTRA7"; if (button==Qt::ExtraButton8) return "EXTRA8"; if (button==Qt::ExtraButton9) return "EXTRA9"; if (button==Qt::ExtraButton10) return "EXTRA10"; if (button==Qt::ExtraButton11) return "EXTRA11"; if (button==Qt::ExtraButton12) return "EXTRA12"; if (button==Qt::ExtraButton13) return "EXTRA13"; if (button==Qt::ExtraButton14) return "EXTRA14"; if (button==Qt::ExtraButton15) return "EXTRA15"; if (button==Qt::ExtraButton16) return "EXTRA16"; if (button==Qt::ExtraButton17) return "EXTRA17"; if (button==Qt::ExtraButton18) return "EXTRA18"; if (button==Qt::ExtraButton19) return "EXTRA19"; if (button==Qt::ExtraButton20) return "EXTRA20"; if (button==Qt::ExtraButton21) return "EXTRA21"; if (button==Qt::ExtraButton22) return "EXTRA22"; if (button==Qt::ExtraButton23) return "EXTRA23"; if (button==Qt::ExtraButton24) return "EXTRA24"; return "UNKNOWN"; } Qt::MouseButton jkqtp_String2MouseButton(const QString &button) { auto but=button.toUpper().trimmed(); if (but=="LEFT") return Qt::LeftButton; if (but=="RIGHT") return Qt::RightButton; #if (QT_VERSION>=QT_VERSION_CHECK(6, 0, 0)) if (but=="MIDDLE") return Qt::MiddleButton; #else if (but=="MIDDLE") return Qt::MidButton; #endif if (but=="BACK") return Qt::BackButton; if (but=="FORWARD") return Qt::ForwardButton; if (but=="TASK") return Qt::TaskButton; if (but=="EXTRA4") return Qt::ExtraButton4; if (but=="EXTRA5") return Qt::ExtraButton5; if (but=="EXTRA6") return Qt::ExtraButton6; if (but=="EXTRA7") return Qt::ExtraButton7; if (but=="EXTRA8") return Qt::ExtraButton8; if (but=="EXTRA9") return Qt::ExtraButton9; if (but=="EXTRA10") return Qt::ExtraButton10; if (but=="EXTRA11") return Qt::ExtraButton11; if (but=="EXTRA12") return Qt::ExtraButton12; if (but=="EXTRA13") return Qt::ExtraButton13; if (but=="EXTRA14") return Qt::ExtraButton14; if (but=="EXTRA15") return Qt::ExtraButton15; if (but=="EXTRA16") return Qt::ExtraButton16; if (but=="EXTRA17") return Qt::ExtraButton17; if (but=="EXTRA18") return Qt::ExtraButton18; if (but=="EXTRA19") return Qt::ExtraButton19; if (but=="EXTRA20") return Qt::ExtraButton20; if (but=="EXTRA21") return Qt::ExtraButton21; if (but=="EXTRA22") return Qt::ExtraButton22; if (but=="EXTRA23") return Qt::ExtraButton23; if (but=="EXTRA24") return Qt::ExtraButton24; return Qt::NoButton; } quint16 jkqtp_checksum(const void *data, size_t len) { #if QT_VERSION>=QT_VERSION_CHECK(6,0,0) return qChecksum(QByteArrayView(static_cast<const uint8_t*>(data), len)); #else return qChecksum(static_cast<const char*>(data), len); #endif } <|endoftext|>
<commit_before>/*------------------------------------------------------------------------ * Copyright (c) 2015 The Khronos Group Inc. * Copyright (c) 2015 Samsung Electronics Co., Ltd. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and/or associated documentation files (the * "Materials"), to deal in the Materials without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Materials, and to * permit persons to whom the Materials are furnished to do so, subject to * the following conditions: * * The above copyright notice(s) and this permission notice shall be included * in all copies or substantial portions of the Materials. * * The Materials are Confidential Information as defined by the * Khronos Membership Agreement until designated non-confidential by Khronos, * at which point this condition clause shall be removed. * * THE MATERIALS ARE 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 * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. * *//*! * \file * \brief Vulkan shader render test cases *//*--------------------------------------------------------------------*/ #include "vktShaderRenderCaseTests.hpp" #include "vktShaderRenderCase.hpp" #include "vktTexture.hpp" #include "deUniquePtr.hpp" namespace vkt { namespace shaderrendercase { inline void eval_DEBUG (ShaderEvalContext& c) { c.color = tcu::Vec4(1, 0, 1, 1); } inline void eval_DEBUG_TEX (ShaderEvalContext& c) { c.color.xyz() = c.texture2D(0, c.coords.swizzle(0, 1)).swizzle(0,1,2); } void empty_uniform (ShaderRenderCaseInstance& /* instance */) {} struct test_struct { tcu::Vec4 a; tcu::Vec4 b; tcu::Vec4 c; tcu::Vec4 d; }; void dummy_uniforms (ShaderRenderCaseInstance& instance, const tcu::Vec4& constCoords) { DE_UNREF(constCoords); instance.useUniform(0u, UI_ZERO); instance.useUniform(1u, UI_ONE); //instance.addUniform(1u, vk::VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1.0f); //instance.addUniform(0u, vk::VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0.5f); instance.addUniform(2u, vk::VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, tcu::Vec4(1, 0.5f, 1.0f, 0.5f)); test_struct data = { tcu::Vec4(0.1f), tcu::Vec4(0.2f), tcu::Vec4(0.3f), tcu::Vec4(0.4f), }; instance.addUniform<test_struct>(3u, vk::VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, data); instance.useSampler2D(4u, 0u); } void dummy_attributes (ShaderRenderCaseInstance& instance, deUint32 numVertices) { std::vector<float> data; data.resize(numVertices); for(deUint32 i = 0; i < numVertices; i++) data[i] = 1.0; instance.addAttribute(4u, vk::VK_FORMAT_R32_SFLOAT, sizeof(float), numVertices, &data[0]); } class DummyShaderRenderCaseInstance : public ShaderRenderCaseInstance { public: DummyShaderRenderCaseInstance (Context& context, bool isVertexCase, ShaderEvaluator& evaluator, UniformSetup& uniformSetup, AttributeSetupFunc attribFunc) : ShaderRenderCaseInstance(context, isVertexCase, evaluator, uniformSetup, attribFunc) , m_brickTexture(DE_NULL) {} virtual ~DummyShaderRenderCaseInstance (void) { if (m_brickTexture) { delete m_brickTexture; m_brickTexture = DE_NULL; } } protected: virtual void setup (void) { m_brickTexture = Texture2D::create(m_context, m_context.getTestContext().getArchive(), "data/brick.png"); m_textures.push_back(TextureBinding(m_brickTexture, tcu::Sampler(tcu::Sampler::CLAMP_TO_EDGE, tcu::Sampler::CLAMP_TO_EDGE, tcu::Sampler::CLAMP_TO_EDGE, tcu::Sampler::LINEAR, tcu::Sampler::LINEAR))); } Texture2D* m_brickTexture; }; class DummyTestRenderCase : public ShaderRenderCase<DummyShaderRenderCaseInstance> { public: DummyTestRenderCase (tcu::TestContext& testCtx, const std::string& name, const std::string& description, bool isVertexCase, ShaderEvalFunc evalFunc, std::string vertexShader, std::string fragmentShader) : ShaderRenderCase(testCtx, name, description, isVertexCase, evalFunc, new UniformSetup(dummy_uniforms), dummy_attributes) { m_vertShaderSource = vertexShader; m_fragShaderSource = fragmentShader; } }; static tcu::TestCaseGroup* dummyTests (tcu::TestContext& testCtx) { de::MovePtr<tcu::TestCaseGroup> dummyTests (new tcu::TestCaseGroup(testCtx, "dummy", "Dummy ShaderRenderCase based Tests")); std::string base_vertex = "#version 140\n" "#extension GL_ARB_separate_shader_objects : enable\n" "#extension GL_ARB_shading_language_420pack : enable\n" "layout(location = 0) in highp vec4 a_position;\n" "layout(location = 1) in highp vec4 a_coords;\n" "layout(location = 2) in highp vec4 a_unitCoords;\n" "layout(location = 3) in mediump float a_one;\n" "layout(location = 4) in mediump float a_in1;\n" "layout (set=0, binding=0) uniform buf {\n" " bool item;\n" "};\n" "layout (set=0, binding=1) uniform buf2 {\n" " int item2;\n" "};\n" "layout (set=0, binding=2) uniform buf3 {\n" " vec4 item3;\n" "};\n" "struct FF { highp float a, b; };\n" "layout (set=0, binding=3) uniform buf4 {\n" " FF f_1;\n" " FF f_2;\n" " highp vec2 f_3[2];\n" "};\n" "layout(location=0) out mediump vec4 v_color;\n" "layout(location=1) out mediump vec4 v_coords;\n" "void main (void) { \n" " gl_Position = a_position;\n" " v_coords = a_coords;\n" " v_color = vec4(a_coords.xyz, f_1.a + f_2.a + f_3[0].x + f_3[1].x - (item ? item2 : 0));\n" "}\n"; std::string base_fragment = "#version 140\n" "#extension GL_ARB_separate_shader_objects : enable\n" "#extension GL_ARB_shading_language_420pack : enable\n" "layout(location = 0) out mediump vec4 o_color;\n" "layout(location=0) in mediump vec4 v_color;\n" "layout(location=1) in mediump vec4 v_coords;\n" "void main (void) { o_color = v_coords; }\n"; std::string debug_fragment = "#version 140 \n" "#extension GL_ARB_separate_shader_objects : enable\n" "#extension GL_ARB_shading_language_420pack : enable\n" "layout(location=0) in vec4 v_color;\n" "layout(location=1) in vec4 v_coords;\n" "layout(location = 0) out lowp vec4 o_color;\n" "layout (set=0, binding=3) uniform buf {\n" " float item[4];\n" "};\n" "layout (set=0, binding=4) uniform sampler2D tex;\n" "void main (void) { o_color = texture(tex, v_coords.xy); }\n"; dummyTests->addChild(new DummyTestRenderCase(testCtx, "testVertex", "testVertex", true, evalCoordsPassthrough, base_vertex, base_fragment)); dummyTests->addChild(new DummyTestRenderCase(testCtx, "testFragment", "testFragment", false, eval_DEBUG_TEX, base_vertex, debug_fragment)); return dummyTests.release(); } tcu::TestCaseGroup* createTests (tcu::TestContext& testCtx) { de::MovePtr<tcu::TestCaseGroup> shaderRenderCaseTests (new tcu::TestCaseGroup(testCtx, "shaderRenderCase", "ShaderRenderCase Tests")); shaderRenderCaseTests->addChild(dummyTests(testCtx)); return shaderRenderCaseTests.release(); } } // shaderrendercase } // vkt <commit_msg>ShaderRenderCase: remove dummy test-cases<commit_after>/*------------------------------------------------------------------------ * Copyright (c) 2015 The Khronos Group Inc. * Copyright (c) 2015 Samsung Electronics Co., Ltd. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and/or associated documentation files (the * "Materials"), to deal in the Materials without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Materials, and to * permit persons to whom the Materials are furnished to do so, subject to * the following conditions: * * The above copyright notice(s) and this permission notice shall be included * in all copies or substantial portions of the Materials. * * The Materials are Confidential Information as defined by the * Khronos Membership Agreement until designated non-confidential by Khronos, * at which point this condition clause shall be removed. * * THE MATERIALS ARE 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 * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. * *//*! * \file * \brief Vulkan shader render test cases *//*--------------------------------------------------------------------*/ #include "vktShaderRenderCaseTests.hpp" #include "vktShaderRenderCase.hpp" #include "vktTexture.hpp" #include "deUniquePtr.hpp" namespace vkt { namespace shaderrendercase { tcu::TestCaseGroup* createTests (tcu::TestContext& testCtx) { de::MovePtr<tcu::TestCaseGroup> shaderRenderCaseTests (new tcu::TestCaseGroup(testCtx, "shaderRenderCase", "ShaderRenderCase Tests")); return shaderRenderCaseTests.release(); } } // shaderrendercase } // vkt <|endoftext|>
<commit_before>/* * Copyright (c) 2013 Nicholas Corgan (n.corgan@gmail.com) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #include <math.h> #include <time.h> #include <boost/assign.hpp> #include "spec_pkmn_gen345impl.hpp" using namespace std; namespace pkmnsim { spec_pkmn_gen345impl::spec_pkmn_gen345impl(base_pkmn::sptr b, int lvl, int gen, string m1, string m2, string m3, string m4): spec_pkmn(b,m1,m2,m3,m4,gen,lvl) { srand ( time(NULL) ); pid = rand(); unsigned int otid = rand(); sid = ((unsigned short*)(&otid))[0]; tid = ((unsigned short*)(&otid))[1]; //Random individual values ivHP = rand() % 32; ivATK = rand() % 32; ivDEF = rand() % 32; ivSPD = rand() % 32; ivSATK = rand() % 32; ivSDEF = rand() % 32; /* * Random effort values within following rules: * - Sum <= 510 * - EV <= 255 */ evHP = 256; evATK = 256; evDEF = 256; evSPD = 256; evSATK = 256; evSDEF = 256; while((evHP+evATK+evDEF+evSPD+evSATK+evSDEF)>510 || evHP>255 || evATK>255 || evDEF>255 || evSPD>255 || evSATK>255 || evSDEF>255) { evHP = rand() % 256; evATK = rand() % 256; evDEF = rand() % 256; evSPD = rand() % 256; evSATK = rand() % 256; evSDEF = rand() % 256; } gender = determine_gender(); nature = determine_nature(); ability = determine_ability(); held_item = "None"; if(base->get_species_id () == 292) HP = 1; else HP = get_hp_from_iv_ev(); ATK = get_stat_from_iv_ev("ATK",ivATK,evATK); DEF = get_stat_from_iv_ev("DEF",ivDEF,evDEF); SPD = get_stat_from_iv_ev("SPD",ivSPD,evSPD); SATK = get_stat_from_iv_ev("SATK",ivSATK,evSATK); SDEF = get_stat_from_iv_ev("SDEF",ivSDEF,evSATK); sprite_path = b->get_sprite_path((gender != Genders::FEMALE), is_shiny()); nonvolatile_status = Statuses::OK; reset_volatile_status_map(); } dict<string, int> spec_pkmn_gen345impl::get_stats() { dict<string, int> stats; stats["HP"] = HP; stats["ATK"] = ATK; stats["DEF"] = DEF; stats["SATK"] = SATK; stats["SDEF"] = SDEF; stats["SPD"] = SPD; return stats; } dict<string, int> spec_pkmn_gen345impl::get_IVs() { dict<string, int> stats; stats["HP"] = ivHP; stats["ATK"] = ivATK; stats["DEF"] = ivDEF; stats["SATK"] = ivSATK; stats["SDEF"] = ivSDEF; stats["SPD"] = ivSPD; return stats; } dict<string, int> spec_pkmn_gen345impl::get_EVs() { dict<string, int> stats; stats["HP"] = evHP; stats["ATK"] = evATK; stats["DEF"] = evDEF; stats["SATK"] = evSATK; stats["SDEF"] = evSDEF; stats["SPD"] = evSPD; return stats; } int spec_pkmn_gen345impl::get_gender() {return gender;} bool spec_pkmn_gen345impl::is_shiny() { int p1, p2, E, F; p1 = (pid & 0xFFFF0000) >> 16; p2 = pid & 0xFFFF; E = tid ^ sid; F = p1 ^ p2; return (E ^ F) < 8; } pkmn_nature::sptr spec_pkmn_gen345impl::get_nature() {return nature;} string spec_pkmn_gen345impl::get_ability() {return ability;} string spec_pkmn_gen345impl::get_held_item() {return held_item;} string spec_pkmn_gen345impl::get_info() { string types_str; dict<int, string> types = base->get_types(); if(types[1] == "None") types_str = types[0]; else types_str = types[0] + "/" + types[1]; string stats_str = to_string(HP) + ", " + to_string(ATK) + ", " + to_string(DEF) + ", " + to_string(SATK) + ", " + to_string(SDEF) + ", " + to_string(SPD); //Get gender character char gender_char; switch(gender) { case Genders::MALE: gender_char = 'M'; break; case Genders::FEMALE: gender_char = 'F'; break; default: gender_char = 'N'; break; } string output_string; output_string = nickname + " (" + base->get_species_name() + " " + gender_char + ")\n" + "Level " + to_string(level) + "\n" + "Type: " + types_str + "\n" + "Ability: " + ability + "\n" + "Held Item: " + held_item + "\n" + "Stats: " + stats_str; return output_string; } string spec_pkmn_gen345impl::get_info_verbose() { string types_str; dict<int, string> types = base->get_types(); if(types[1] == "None") types_str = types[0]; else types_str = types[0] + "/" + types[1]; string output_string; output_string = nickname + " (" + base->get_species_name() + ")\n" + "Level " + to_string(level) + "\n" + "Type: " + types_str + "\n" + "Ability: " + ability + "\n" + "Held Item: " + held_item + "\n" + "Stats:\n" + " - HP: " + to_string(HP) + "\n" + " - Attack: " + to_string(ATK) + "\n" + " - Defense: " + to_string(DEF) + "\n" + " - Special Attack: " + to_string(SATK) + "\n" + " - Special Defense: " + to_string(SDEF) + "\n" + " - Speed: " + to_string(SPD) + "\n" + "Individual Values:\n" + " - HP: " + to_string(ivHP) + "\n" + " - Attack: " + to_string(ivATK) + "\n" + " - Defense: " + to_string(ivDEF) + "\n" + " - Special Attack: " + to_string(ivSATK) + "\n" + " - Special Defense: " + to_string(ivSDEF) + "\n" + " - Speed: " + to_string(ivSPD) + "\n" + "Effort Values:\n" + " - HP: " + to_string(evHP) + "\n" + " - Attack: " + to_string(evATK) + "\n" + " - Defense: " + to_string(evDEF) + "\n" + " - Special Attack: " + to_string(evSATK) + "\n" + " - Special Defense: " + to_string(evSDEF) + "\n" + " - Speed: " + to_string(evSPD) + "\n"; return output_string; } void spec_pkmn_gen345impl::set_form(int form) { base->set_form(form); HP = get_hp_from_iv_ev(); ATK = get_stat_from_iv_ev("ATK", ivATK, evATK); DEF = get_stat_from_iv_ev("DEF", ivDEF, evDEF); SATK = get_stat_from_iv_ev("SATK", ivSATK, evSATK); SDEF = get_stat_from_iv_ev("SDEF", ivSDEF, evSDEF); SPD = get_stat_from_iv_ev("SPD", ivSPD, evSPD); icon_path = base->get_icon_path(); sprite_path = base->get_sprite_path((gender != Genders::FEMALE), is_shiny()); } void spec_pkmn_gen345impl::set_form(std::string form) { base->set_form(form); HP = get_hp_from_iv_ev(); ATK = get_stat_from_iv_ev("ATK", ivATK, evATK); DEF = get_stat_from_iv_ev("DEF", ivDEF, evDEF); SATK = get_stat_from_iv_ev("SATK", ivSATK, evSATK); SDEF = get_stat_from_iv_ev("SDEF", ivSDEF, evSDEF); SPD = get_stat_from_iv_ev("SPD", ivSPD, evSPD); icon_path = base->get_icon_path(); sprite_path = base->get_sprite_path((gender != Genders::FEMALE), is_shiny()); } int spec_pkmn_gen345impl::get_hp_from_iv_ev() { dict<string, int> stats = base->get_base_stats(); int hp_val = int(floor(((double(ivHP) + (2.0*double(stats["HP"])) + (0.25*double(evHP)) + 100.0) * double(level))/100.0 + 10.0)); return hp_val; } int spec_pkmn_gen345impl::get_stat_from_iv_ev(string stat, int ivSTAT, int evSTAT) { dict<string, int> stats = base->get_base_stats(); double nature_mod = nature->get_mods()[stat]; int stat_val = int(ceil(((((double(ivSTAT) + 2.0*double(stats[stat]) + 0.25*double(evSTAT)) * double(level))/100.0) + 5.0) * nature_mod)); return stat_val; } void spec_pkmn_gen345impl::reset_volatile_status_map() { volatile_status_map = boost::assign::map_list_of ("confusion",0) ("curse",0) ("embargo",0) ("encore",0) ("flinch",0) ("heal block",0) ("identification",0) ("infatuation",0) ("nightmare",0) ("partially trapped",0) ("perish song",0) ("seeded",0) ("taunt",0) ("telekinetic levitation",0) ("torment",0) ("trapped",0) ("aqua ring",0) ("bracing",0) ("center of attention",0) ("defense curl",0) ("focus energy",0) ("glowing",0) ("rooting",0) ("magic coat",0) ("magnetic levitation",0) ("minimize",0) ("protection",0) ("reintging",0) ("semi-invulnerable",0) ("substitute",0) ("taking aim",0) ("taking in sunlight",0) ("withdrawing",0) ("whipping up a whirlwind",0) ; } int spec_pkmn_gen345impl::determine_gender() { if(base->get_chance_male() + base->get_chance_female() == 0) return Genders::GENDERLESS; else if(base->get_chance_male() == 1.0) return Genders::MALE; else if(base->get_chance_female() == 1.0) return Genders::FEMALE; else { if((pid % 256) > int(floor(255*(1-base->get_chance_male())))) gender = Genders::MALE; else gender = Genders::FEMALE; } } pkmn_nature::sptr spec_pkmn_gen345impl::determine_nature() { string nature_names[] = {"Hardy","Lonely","Brave","Adamant","Naughty","Bold", "Docile","Relaxed","Impish","Lax","Timid","Hasty", "Serious","Jolly","Naive","Modest","Mild","Quiet", "Bashful","Rash","Calm","Gentle","Sassy","Careful", "Quirky"}; return pkmn_nature::make(nature_names[pid % 25]); } string spec_pkmn_gen345impl::determine_ability() { srand( time(NULL) ); dict<int, string> abilities = base->get_abilities(); if(abilities[1] == "None" and abilities[2] == "None") ability = abilities[0]; //Single ability else if(abilities[2] == "None") ability = abilities[rand() % 2]; //Two abilities, no hidden ability else if(abilities[1] == "None" and abilities[2] != "None") //One normal ability, one hidden ability { int num; do { num = rand() % 3; } while(num == 1); ability = abilities[num]; } else ability = abilities[rand() % 3]; //Three abilities return ability; } } <commit_msg>lib: fixed Clang non-return warning in spec_pkmn_gen345impl<commit_after>/* * Copyright (c) 2013 Nicholas Corgan (n.corgan@gmail.com) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #include <math.h> #include <time.h> #include <boost/assign.hpp> #include "spec_pkmn_gen345impl.hpp" using namespace std; namespace pkmnsim { spec_pkmn_gen345impl::spec_pkmn_gen345impl(base_pkmn::sptr b, int lvl, int gen, string m1, string m2, string m3, string m4): spec_pkmn(b,m1,m2,m3,m4,gen,lvl) { srand ( time(NULL) ); pid = rand(); unsigned int otid = rand(); sid = ((unsigned short*)(&otid))[0]; tid = ((unsigned short*)(&otid))[1]; //Random individual values ivHP = rand() % 32; ivATK = rand() % 32; ivDEF = rand() % 32; ivSPD = rand() % 32; ivSATK = rand() % 32; ivSDEF = rand() % 32; /* * Random effort values within following rules: * - Sum <= 510 * - EV <= 255 */ evHP = 256; evATK = 256; evDEF = 256; evSPD = 256; evSATK = 256; evSDEF = 256; while((evHP+evATK+evDEF+evSPD+evSATK+evSDEF)>510 || evHP>255 || evATK>255 || evDEF>255 || evSPD>255 || evSATK>255 || evSDEF>255) { evHP = rand() % 256; evATK = rand() % 256; evDEF = rand() % 256; evSPD = rand() % 256; evSATK = rand() % 256; evSDEF = rand() % 256; } gender = determine_gender(); nature = determine_nature(); ability = determine_ability(); held_item = "None"; if(base->get_species_id () == 292) HP = 1; else HP = get_hp_from_iv_ev(); ATK = get_stat_from_iv_ev("ATK",ivATK,evATK); DEF = get_stat_from_iv_ev("DEF",ivDEF,evDEF); SPD = get_stat_from_iv_ev("SPD",ivSPD,evSPD); SATK = get_stat_from_iv_ev("SATK",ivSATK,evSATK); SDEF = get_stat_from_iv_ev("SDEF",ivSDEF,evSATK); sprite_path = b->get_sprite_path((gender != Genders::FEMALE), is_shiny()); nonvolatile_status = Statuses::OK; reset_volatile_status_map(); } dict<string, int> spec_pkmn_gen345impl::get_stats() { dict<string, int> stats; stats["HP"] = HP; stats["ATK"] = ATK; stats["DEF"] = DEF; stats["SATK"] = SATK; stats["SDEF"] = SDEF; stats["SPD"] = SPD; return stats; } dict<string, int> spec_pkmn_gen345impl::get_IVs() { dict<string, int> stats; stats["HP"] = ivHP; stats["ATK"] = ivATK; stats["DEF"] = ivDEF; stats["SATK"] = ivSATK; stats["SDEF"] = ivSDEF; stats["SPD"] = ivSPD; return stats; } dict<string, int> spec_pkmn_gen345impl::get_EVs() { dict<string, int> stats; stats["HP"] = evHP; stats["ATK"] = evATK; stats["DEF"] = evDEF; stats["SATK"] = evSATK; stats["SDEF"] = evSDEF; stats["SPD"] = evSPD; return stats; } int spec_pkmn_gen345impl::get_gender() {return gender;} bool spec_pkmn_gen345impl::is_shiny() { int p1, p2, E, F; p1 = (pid & 0xFFFF0000) >> 16; p2 = pid & 0xFFFF; E = tid ^ sid; F = p1 ^ p2; return (E ^ F) < 8; } pkmn_nature::sptr spec_pkmn_gen345impl::get_nature() {return nature;} string spec_pkmn_gen345impl::get_ability() {return ability;} string spec_pkmn_gen345impl::get_held_item() {return held_item;} string spec_pkmn_gen345impl::get_info() { string types_str; dict<int, string> types = base->get_types(); if(types[1] == "None") types_str = types[0]; else types_str = types[0] + "/" + types[1]; string stats_str = to_string(HP) + ", " + to_string(ATK) + ", " + to_string(DEF) + ", " + to_string(SATK) + ", " + to_string(SDEF) + ", " + to_string(SPD); //Get gender character char gender_char; switch(gender) { case Genders::MALE: gender_char = 'M'; break; case Genders::FEMALE: gender_char = 'F'; break; default: gender_char = 'N'; break; } string output_string; output_string = nickname + " (" + base->get_species_name() + " " + gender_char + ")\n" + "Level " + to_string(level) + "\n" + "Type: " + types_str + "\n" + "Ability: " + ability + "\n" + "Held Item: " + held_item + "\n" + "Stats: " + stats_str; return output_string; } string spec_pkmn_gen345impl::get_info_verbose() { string types_str; dict<int, string> types = base->get_types(); if(types[1] == "None") types_str = types[0]; else types_str = types[0] + "/" + types[1]; string output_string; output_string = nickname + " (" + base->get_species_name() + ")\n" + "Level " + to_string(level) + "\n" + "Type: " + types_str + "\n" + "Ability: " + ability + "\n" + "Held Item: " + held_item + "\n" + "Stats:\n" + " - HP: " + to_string(HP) + "\n" + " - Attack: " + to_string(ATK) + "\n" + " - Defense: " + to_string(DEF) + "\n" + " - Special Attack: " + to_string(SATK) + "\n" + " - Special Defense: " + to_string(SDEF) + "\n" + " - Speed: " + to_string(SPD) + "\n" + "Individual Values:\n" + " - HP: " + to_string(ivHP) + "\n" + " - Attack: " + to_string(ivATK) + "\n" + " - Defense: " + to_string(ivDEF) + "\n" + " - Special Attack: " + to_string(ivSATK) + "\n" + " - Special Defense: " + to_string(ivSDEF) + "\n" + " - Speed: " + to_string(ivSPD) + "\n" + "Effort Values:\n" + " - HP: " + to_string(evHP) + "\n" + " - Attack: " + to_string(evATK) + "\n" + " - Defense: " + to_string(evDEF) + "\n" + " - Special Attack: " + to_string(evSATK) + "\n" + " - Special Defense: " + to_string(evSDEF) + "\n" + " - Speed: " + to_string(evSPD) + "\n"; return output_string; } void spec_pkmn_gen345impl::set_form(int form) { base->set_form(form); HP = get_hp_from_iv_ev(); ATK = get_stat_from_iv_ev("ATK", ivATK, evATK); DEF = get_stat_from_iv_ev("DEF", ivDEF, evDEF); SATK = get_stat_from_iv_ev("SATK", ivSATK, evSATK); SDEF = get_stat_from_iv_ev("SDEF", ivSDEF, evSDEF); SPD = get_stat_from_iv_ev("SPD", ivSPD, evSPD); icon_path = base->get_icon_path(); sprite_path = base->get_sprite_path((gender != Genders::FEMALE), is_shiny()); } void spec_pkmn_gen345impl::set_form(std::string form) { base->set_form(form); HP = get_hp_from_iv_ev(); ATK = get_stat_from_iv_ev("ATK", ivATK, evATK); DEF = get_stat_from_iv_ev("DEF", ivDEF, evDEF); SATK = get_stat_from_iv_ev("SATK", ivSATK, evSATK); SDEF = get_stat_from_iv_ev("SDEF", ivSDEF, evSDEF); SPD = get_stat_from_iv_ev("SPD", ivSPD, evSPD); icon_path = base->get_icon_path(); sprite_path = base->get_sprite_path((gender != Genders::FEMALE), is_shiny()); } int spec_pkmn_gen345impl::get_hp_from_iv_ev() { dict<string, int> stats = base->get_base_stats(); int hp_val = int(floor(((double(ivHP) + (2.0*double(stats["HP"])) + (0.25*double(evHP)) + 100.0) * double(level))/100.0 + 10.0)); return hp_val; } int spec_pkmn_gen345impl::get_stat_from_iv_ev(string stat, int ivSTAT, int evSTAT) { dict<string, int> stats = base->get_base_stats(); double nature_mod = nature->get_mods()[stat]; int stat_val = int(ceil(((((double(ivSTAT) + 2.0*double(stats[stat]) + 0.25*double(evSTAT)) * double(level))/100.0) + 5.0) * nature_mod)); return stat_val; } void spec_pkmn_gen345impl::reset_volatile_status_map() { volatile_status_map = boost::assign::map_list_of ("confusion",0) ("curse",0) ("embargo",0) ("encore",0) ("flinch",0) ("heal block",0) ("identification",0) ("infatuation",0) ("nightmare",0) ("partially trapped",0) ("perish song",0) ("seeded",0) ("taunt",0) ("telekinetic levitation",0) ("torment",0) ("trapped",0) ("aqua ring",0) ("bracing",0) ("center of attention",0) ("defense curl",0) ("focus energy",0) ("glowing",0) ("rooting",0) ("magic coat",0) ("magnetic levitation",0) ("minimize",0) ("protection",0) ("reintging",0) ("semi-invulnerable",0) ("substitute",0) ("taking aim",0) ("taking in sunlight",0) ("withdrawing",0) ("whipping up a whirlwind",0) ; } int spec_pkmn_gen345impl::determine_gender() { if(base->get_chance_male() + base->get_chance_female() == 0) return Genders::GENDERLESS; else if(base->get_chance_male() == 1.0) return Genders::MALE; else if(base->get_chance_female() == 1.0) return Genders::FEMALE; else { if((pid % 256) > int(floor(255*(1-base->get_chance_male())))) return Genders::MALE; else return Genders::FEMALE; } //Should never get here, this stops Clang from complaining return Genders::MALE; } pkmn_nature::sptr spec_pkmn_gen345impl::determine_nature() { string nature_names[] = {"Hardy","Lonely","Brave","Adamant","Naughty","Bold", "Docile","Relaxed","Impish","Lax","Timid","Hasty", "Serious","Jolly","Naive","Modest","Mild","Quiet", "Bashful","Rash","Calm","Gentle","Sassy","Careful", "Quirky"}; return pkmn_nature::make(nature_names[pid % 25]); } string spec_pkmn_gen345impl::determine_ability() { srand( time(NULL) ); dict<int, string> abilities = base->get_abilities(); if(abilities[1] == "None" and abilities[2] == "None") ability = abilities[0]; //Single ability else if(abilities[2] == "None") ability = abilities[rand() % 2]; //Two abilities, no hidden ability else if(abilities[1] == "None" and abilities[2] != "None") //One normal ability, one hidden ability { int num; do { num = rand() % 3; } while(num == 1); ability = abilities[num]; } else ability = abilities[rand() % 3]; //Three abilities return ability; } } <|endoftext|>
<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Gearmand client and server library. * * Copyright (C) 2013 Data Differential, http://datadifferential.com/ * Copyright (C) 2013 Keyur Govande * 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. * * * The names of its contributors may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /** * @file * @brief Server options */ #include "gear_config.h" #include "libgearman/common.h" #include <memory> bool gearman_request_option(gearman_universal_st &universal, gearman_string_t &option) { char* option_str_cpy = (char*) malloc(gearman_size(option)); if (option_str_cpy == NULL) { gearman_error(universal, GEARMAN_MEMORY_ALLOCATION_FAILURE, "malloc()"); return false; } strncpy(option_str_cpy, gearman_c_str(option), gearman_size(option)); gearman_server_options_st *server_options = new (std::nothrow) gearman_server_options_st(universal, option_str_cpy, gearman_size(option)); if (server_options == NULL) { free(option_str_cpy); gearman_error(universal, GEARMAN_MEMORY_ALLOCATION_FAILURE, "new gearman_server_options_st()"); return false; } return true; } gearman_server_options_st::gearman_server_options_st(gearman_universal_st &universal_arg, const char* option_arg, const size_t option_arg_size) : _option(option_arg_size), next(NULL), prev(NULL), universal(universal_arg) { _option.append(option_arg, option_arg_size); if (universal.server_options_list) { universal.server_options_list->prev= this; } next= universal.server_options_list; universal.server_options_list= this; } gearman_server_options_st::gearman_server_options_st(const gearman_server_options_st& copy) : _option(copy.option()), next(NULL), prev(NULL), universal(copy.universal) { if (universal.server_options_list) { universal.server_options_list->prev= this; } next= universal.server_options_list; universal.server_options_list= this; } gearman_server_options_st::~gearman_server_options_st() { { // Remove from universal list if (universal.server_options_list == this) { universal.server_options_list= next; } if (prev) { prev->next= next; } if (next) { next->prev= prev; } } } <commit_msg>Fix one malloc call.<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Gearmand client and server library. * * Copyright (C) 2013 Data Differential, http://datadifferential.com/ * Copyright (C) 2013 Keyur Govande * 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. * * * The names of its contributors may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /** * @file * @brief Server options */ #include "gear_config.h" #include "libgearman/common.h" #include <memory> bool gearman_request_option(gearman_universal_st &universal, gearman_string_t &option) { gearman_server_options_st *server_options = new (std::nothrow) gearman_server_options_st(universal, gearman_c_str(option), gearman_size(option)); if (server_options == NULL) { gearman_error(universal, GEARMAN_MEMORY_ALLOCATION_FAILURE, "new gearman_server_options_st()"); return false; } return true; } gearman_server_options_st::gearman_server_options_st(gearman_universal_st &universal_arg, const char* option_arg, const size_t option_arg_size) : _option(option_arg_size), next(NULL), prev(NULL), universal(universal_arg) { _option.append(option_arg, option_arg_size); if (universal.server_options_list) { universal.server_options_list->prev= this; } next= universal.server_options_list; universal.server_options_list= this; } gearman_server_options_st::gearman_server_options_st(const gearman_server_options_st& copy) : _option(copy.option()), next(NULL), prev(NULL), universal(copy.universal) { if (universal.server_options_list) { universal.server_options_list->prev= this; } next= universal.server_options_list; universal.server_options_list= this; } gearman_server_options_st::~gearman_server_options_st() { { // Remove from universal list if (universal.server_options_list == this) { universal.server_options_list= next; } if (prev) { prev->next= next; } if (next) { next->prev= prev; } } } <|endoftext|>
<commit_before>/***************************************************************************** * Project: RooFit * * Package: RooFitModels * * @(#)root/roofit:$Id$ * Authors: * * Kyle Cranmer * * *****************************************************************************/ ////////////////////////////////////////////////////////////////////////////// // // BEGIN_HTML // Bernstein basis polynomials are positive-definite in the range [0,1]. // In this implementation, we extend [0,1] to be the range of the parameter. // There are n+1 Bernstein basis polynomials of degree n. // Thus, by providing N coefficients that are positive-definite, there // is a natural way to have well bahaved polynomail PDFs. // For any n, the n+1 basis polynomials 'form a partition of unity', eg. // they sum to one for all values of x. See // http://www.idav.ucdavis.edu/education/CAGDNotes/Bernstein-Polynomials.pdf // END_HTML // #include "RooFit.h" #include "Riostream.h" #include "Riostream.h" #include <math.h> #include "TMath.h" #include "RooBernstein.h" #include "RooAbsReal.h" #include "RooRealVar.h" #include "RooArgList.h" using namespace std; ClassImp(RooBernstein) ; //_____________________________________________________________________________ RooBernstein::RooBernstein() { } //_____________________________________________________________________________ RooBernstein::RooBernstein(const char* name, const char* title, RooAbsReal& x, const RooArgList& coefList): RooAbsPdf(name, title), _x("x", "Dependent", this, x), _coefList("coefficients","List of coefficients",this) { // Constructor TIterator* coefIter = coefList.createIterator() ; RooAbsArg* coef ; while((coef = (RooAbsArg*)coefIter->Next())) { if (!dynamic_cast<RooAbsReal*>(coef)) { cout << "RooBernstein::ctor(" << GetName() << ") ERROR: coefficient " << coef->GetName() << " is not of type RooAbsReal" << endl ; assert(0) ; } _coefList.add(*coef) ; } delete coefIter ; } //_____________________________________________________________________________ RooBernstein::RooBernstein(const RooBernstein& other, const char* name) : RooAbsPdf(other, name), _x("x", this, other._x), _coefList("coefList",this,other._coefList) { } //_____________________________________________________________________________ Double_t RooBernstein::evaluate() const { Double_t xmin = _x.min(); Double_t x = (_x - xmin) / (_x.max() - xmin); // rescale to [0,1] Int_t degree = _coefList.getSize() - 1; // n+1 polys of degree n RooFIter iter = _coefList.fwdIterator(); if(degree == 0) { return ((RooAbsReal *)iter.next())->getVal(); } else if(degree == 1) { Double_t a0 = ((RooAbsReal *)iter.next())->getVal(); // c0 Double_t a1 = ((RooAbsReal *)iter.next())->getVal(); // c1 - c0 return a1 * x + a0; } else if(degree == 2) { Double_t a0 = ((RooAbsReal *)iter.next())->getVal(); // c0 Double_t a1 = 2 * (((RooAbsReal *)iter.next())->getVal() - a0); // 2 * (c1 - c0) Double_t a2 = ((RooAbsReal *)iter.next())->getVal() - a1 - a0; // c0 - 2 * c1 + c2 return (a2 * x + a1) * x + a0; } else if(degree > 2) { Double_t t = x; Double_t s = 1 - x; Double_t result = ((RooAbsReal *)iter.next())->getVal() * s; for(Int_t i = 1; i < degree; i++) { result = (result + t * TMath::Binomial(degree, i) * ((RooAbsReal *)iter.next())->getVal()) * s; t *= x; } result += t * ((RooAbsReal *)iter.next())->getVal(); return result; } // in case list of arguments passed is empty return TMath::SignalingNaN(); } //_____________________________________________________________________________ Int_t RooBernstein::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* rangeName) const { // No analytical calculation available (yet) of integrals over subranges if (rangeName && strlen(rangeName)) { return 0 ; } if (matchArgs(allVars, analVars, _x)) return 1; return 0; } //_____________________________________________________________________________ Double_t RooBernstein::analyticalIntegral(Int_t code, const char* rangeName) const { assert(code==1) ; Double_t xmin = _x.min(rangeName); Double_t xmax = _x.max(rangeName); Int_t degree= _coefList.getSize()-1; // n+1 polys of degree n Double_t norm(0) ; RooFIter iter = _coefList.fwdIterator() ; Double_t temp=0; for (int i=0; i<=degree; ++i){ // for each of the i Bernstein basis polynomials // represent it in the 'power basis' (the naive polynomial basis) // where the integral is straight forward. temp = 0; for (int j=i; j<=degree; ++j){ // power basisŧ temp += pow(-1.,j-i) * TMath::Binomial(degree, j) * TMath::Binomial(j,i) / (j+1); } temp *= ((RooAbsReal*)iter.next())->getVal(); // include coeff norm += temp; // add this basis's contribution to total } norm *= xmax-xmin; return norm; } <commit_msg>fix evaluation of Bernstein for degree=1 ( see https://savannah.cern.ch/bugs/?97190 )<commit_after>/***************************************************************************** * Project: RooFit * * Package: RooFitModels * * @(#)root/roofit:$Id$ * Authors: * * Kyle Cranmer * * *****************************************************************************/ ////////////////////////////////////////////////////////////////////////////// // // BEGIN_HTML // Bernstein basis polynomials are positive-definite in the range [0,1]. // In this implementation, we extend [0,1] to be the range of the parameter. // There are n+1 Bernstein basis polynomials of degree n. // Thus, by providing N coefficients that are positive-definite, there // is a natural way to have well bahaved polynomail PDFs. // For any n, the n+1 basis polynomials 'form a partition of unity', eg. // they sum to one for all values of x. See // http://www.idav.ucdavis.edu/education/CAGDNotes/Bernstein-Polynomials.pdf // END_HTML // #include "RooFit.h" #include "Riostream.h" #include "Riostream.h" #include <math.h> #include "TMath.h" #include "RooBernstein.h" #include "RooAbsReal.h" #include "RooRealVar.h" #include "RooArgList.h" using namespace std; ClassImp(RooBernstein) ; //_____________________________________________________________________________ RooBernstein::RooBernstein() { } //_____________________________________________________________________________ RooBernstein::RooBernstein(const char* name, const char* title, RooAbsReal& x, const RooArgList& coefList): RooAbsPdf(name, title), _x("x", "Dependent", this, x), _coefList("coefficients","List of coefficients",this) { // Constructor TIterator* coefIter = coefList.createIterator() ; RooAbsArg* coef ; while((coef = (RooAbsArg*)coefIter->Next())) { if (!dynamic_cast<RooAbsReal*>(coef)) { cout << "RooBernstein::ctor(" << GetName() << ") ERROR: coefficient " << coef->GetName() << " is not of type RooAbsReal" << endl ; assert(0) ; } _coefList.add(*coef) ; } delete coefIter ; } //_____________________________________________________________________________ RooBernstein::RooBernstein(const RooBernstein& other, const char* name) : RooAbsPdf(other, name), _x("x", this, other._x), _coefList("coefList",this,other._coefList) { } //_____________________________________________________________________________ Double_t RooBernstein::evaluate() const { Double_t xmin = _x.min(); Double_t x = (_x - xmin) / (_x.max() - xmin); // rescale to [0,1] Int_t degree = _coefList.getSize() - 1; // n+1 polys of degree n RooFIter iter = _coefList.fwdIterator(); if(degree == 0) { return ((RooAbsReal *)iter.next())->getVal(); } else if(degree == 1) { Double_t a0 = ((RooAbsReal *)iter.next())->getVal(); // c0 Double_t a1 = ((RooAbsReal *)iter.next())->getVal() - a0; // c1 - c0 return a1 * x + a0; } else if(degree == 2) { Double_t a0 = ((RooAbsReal *)iter.next())->getVal(); // c0 Double_t a1 = 2 * (((RooAbsReal *)iter.next())->getVal() - a0); // 2 * (c1 - c0) Double_t a2 = ((RooAbsReal *)iter.next())->getVal() - a1 - a0; // c0 - 2 * c1 + c2 return (a2 * x + a1) * x + a0; } else if(degree > 2) { Double_t t = x; Double_t s = 1 - x; Double_t result = ((RooAbsReal *)iter.next())->getVal() * s; for(Int_t i = 1; i < degree; i++) { result = (result + t * TMath::Binomial(degree, i) * ((RooAbsReal *)iter.next())->getVal()) * s; t *= x; } result += t * ((RooAbsReal *)iter.next())->getVal(); return result; } // in case list of arguments passed is empty return TMath::SignalingNaN(); } //_____________________________________________________________________________ Int_t RooBernstein::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* rangeName) const { // No analytical calculation available (yet) of integrals over subranges if (rangeName && strlen(rangeName)) { return 0 ; } if (matchArgs(allVars, analVars, _x)) return 1; return 0; } //_____________________________________________________________________________ Double_t RooBernstein::analyticalIntegral(Int_t code, const char* rangeName) const { assert(code==1) ; Double_t xmin = _x.min(rangeName); Double_t xmax = _x.max(rangeName); Int_t degree= _coefList.getSize()-1; // n+1 polys of degree n Double_t norm(0) ; RooFIter iter = _coefList.fwdIterator() ; Double_t temp=0; for (int i=0; i<=degree; ++i){ // for each of the i Bernstein basis polynomials // represent it in the 'power basis' (the naive polynomial basis) // where the integral is straight forward. temp = 0; for (int j=i; j<=degree; ++j){ // power basisŧ temp += pow(-1.,j-i) * TMath::Binomial(degree, j) * TMath::Binomial(j,i) / (j+1); } temp *= ((RooAbsReal*)iter.next())->getVal(); // include coeff norm += temp; // add this basis's contribution to total } norm *= xmax-xmin; return norm; } <|endoftext|>
<commit_before>#include "@HEADER@" // TODO Insert code here. void @CLASS@::foo() { } <commit_msg>Tweaked scaf.cpp<commit_after>#include "@HEADER@" void @CLASS@::foo() { // TODO Insert code here. } <|endoftext|>
<commit_before>/** events.cc -*- C++ -*- Rémi Attab, 18 Apr 2014 Copyright (c) 2014 Datacratic. All rights reserved. Publishable event implementation. */ #include "events.h" #include "soa/service/zmq_endpoint.h" #include "soa/service/zmq_named_pub_sub.h" using namespace std; using namespace ML; namespace RTBKIT { /******************************************************************************/ /* UTILS */ /******************************************************************************/ namespace { std::string publishTimestamp() { return Date::now().print(5); } } // namespace anonymous /******************************************************************************/ /* MATCHED WIN LOSS */ /******************************************************************************/ void MatchedWinLoss:: initFinishedInfo(const FinishedInfo& info) { auctionId = info.auctionId; impId = info.adSpotId; impIndex = info.spotIndex; winPrice = info.winPrice; rawWinPrice = info.rawWinPrice; response = info.bid; requestStr = info.bidRequestStr; requestStrFormat = info.bidRequestStrFormat; meta = info.winMeta; augmentations = info.augmentations; } void MatchedWinLoss:: initMisc(const PostAuctionEvent& event) { uids = event.uids; timestamp = event.timestamp; } void MatchedWinLoss:: initMisc(Date timestamp, UserIds uids) { this->timestamp = timestamp; this->uids = std::move(uids); } MatchedWinLoss:: MatchedWinLoss( Type type, Confidence confidence, const PostAuctionEvent& event, const FinishedInfo& info) : type(type), confidence(confidence) { initFinishedInfo(info); initMisc(event); } MatchedWinLoss:: MatchedWinLoss( Type type, Confidence confidence, const FinishedInfo& info, Date timestamp, UserIds uids) : type(type), confidence(confidence) { initFinishedInfo(info); initMisc(timestamp, std::move(uids)); } std::string MatchedWinLoss:: typeString() const { switch (type) { case LateWin: case Win: return "WIN"; case Loss: return "LOSS"; } ExcAssert(false); } std::string MatchedWinLoss:: confidenceString() const { switch (confidence) { case Inferred: return "inferred"; case Guaranteed: return "guaranteed"; } ExcAssert(false); } void MatchedWinLoss:: publish(ZmqNamedPublisher& logger) const { logger.publish( "MATCHED" + typeString(), // 0 publishTimestamp(), // 1 auctionId.toString(), // 2 std::to_string(impIndex), // 3 response.agent, // 4 response.account.at(1, ""), // 5 winPrice.toString(), // 6 response.price.maxPrice.toString(), // 7 std::to_string(response.price.priority), // 8 requestStr, // 9 response.bidData.toJsonStr(), // 10 response.meta, // 11 // This is where things start to get weird. std::to_string(response.creativeId), // 12 response.creativeName, // 13 response.account.at(0, ""), // 14 uids.toJsonStr(), // 15 meta, // 16 // And this is where we lose all pretenses of sanity. response.account.at(0, ""), // 17 impId.toString(), // 18 response.account.toString(), // 19 // Ok back to sanity now. requestStrFormat, // 20 rawWinPrice.toString(), // 21 augmentations.toString() // 22 ); } void MatchedWinLoss:: publish(AnalyticsPublisher & logger) const { logger.publish( "MATCHED" + typeString(), publishTimestamp(), auctionId.toString(), response.account.toString(), winPrice.toString(), rawWinPrice.toString(), uids.toJsonStr() ); } /******************************************************************************/ /* MATCHED CAMPAIGN EVENT */ /******************************************************************************/ MatchedCampaignEvent:: MatchedCampaignEvent(std::string label, const FinishedInfo& info) : label(std::move(label)), auctionId(info.auctionId), impId(info.adSpotId), impIndex(info.spotIndex), account(info.bid.account), requestStr(info.bidRequestStr), requestStrFormat(info.bidRequestStrFormat), response(info.bid), bid(info.bidToJson()), win(info.winToJson()), campaignEvents(info.campaignEvents.toJson()), visits(info.visitsToJson()), augmentations(info.augmentations) { auto it = std::find_if(info.campaignEvents.begin(), info.campaignEvents.end(), [&](const CampaignEvent& event) { return event.label_ == label; } ); if(it != info.campaignEvents.end()) timestamp = it->time_; } void MatchedCampaignEvent:: publish(ZmqNamedPublisher& logger) const { logger.publish( "MATCHED" + label, // 0 publishTimestamp(), // 1 auctionId.toString(), // 2 impId.toString(), // 3 requestStr, // 4 bid, // 5 win, // 6 campaignEvents, // 7 visits, // 8 account.at(0, ""), // 9 account.at(1, ""), // 10 account.toString(), // 11 requestStrFormat // 12 ); } void MatchedCampaignEvent:: publish(AnalyticsPublisher & logger) const { logger.publish( "MATCHED" + label, publishTimestamp(), auctionId.toString(), account.toString() ); } /******************************************************************************/ /* UNMATCHED EVENT */ /******************************************************************************/ UnmatchedEvent:: UnmatchedEvent(std::string reason, PostAuctionEvent event) : reason(std::move(reason)), event(std::move(event)) {} void UnmatchedEvent:: publish(ZmqNamedPublisher& logger) const { logger.publish( // Use event type not label since label is only defined for campaign events. "UNMATCHED" + string(print(event.type)), // 0 publishTimestamp(), // 1 reason, // 2 event.auctionId.toString(), // 3 event.adSpotId.toString(), // 4 std::to_string(event.timestamp.secondsSinceEpoch()), // 5 event.metadata.toJson() // 6 ); } void UnmatchedEvent:: publish(AnalyticsPublisher & logger) const { logger.publish( "UNMATCHED" + string(print(event.type)), publishTimestamp(), reason, event.auctionId.toString(), std::to_string(event.timestamp.secondsSinceEpoch()) ); } /******************************************************************************/ /* POST AUCTION ERROR EVENT */ /******************************************************************************/ PostAuctionErrorEvent:: PostAuctionErrorEvent(std::string key, std::string message) : key(std::move(key)), message(std::move(message)) {} void PostAuctionErrorEvent:: publish(ZmqNamedPublisher& logger) const { logger.publish("PAERROR", publishTimestamp(), key, message); } void PostAuctionErrorEvent:: publish(AnalyticsPublisher & logger) const { logger.publish("PAERROR", publishTimestamp(), key, message); } } // namepsace RTBKIT <commit_msg>MatchedCampaignEvent: fixed bad search for the timestamp<commit_after>/** events.cc -*- C++ -*- Rémi Attab, 18 Apr 2014 Copyright (c) 2014 Datacratic. All rights reserved. Publishable event implementation. */ #include "events.h" #include "soa/service/zmq_endpoint.h" #include "soa/service/zmq_named_pub_sub.h" using namespace std; using namespace ML; namespace RTBKIT { /******************************************************************************/ /* UTILS */ /******************************************************************************/ namespace { std::string publishTimestamp() { return Date::now().print(5); } } // namespace anonymous /******************************************************************************/ /* MATCHED WIN LOSS */ /******************************************************************************/ void MatchedWinLoss:: initFinishedInfo(const FinishedInfo& info) { auctionId = info.auctionId; impId = info.adSpotId; impIndex = info.spotIndex; winPrice = info.winPrice; rawWinPrice = info.rawWinPrice; response = info.bid; requestStr = info.bidRequestStr; requestStrFormat = info.bidRequestStrFormat; meta = info.winMeta; augmentations = info.augmentations; } void MatchedWinLoss:: initMisc(const PostAuctionEvent& event) { uids = event.uids; timestamp = event.timestamp; } void MatchedWinLoss:: initMisc(Date timestamp, UserIds uids) { this->timestamp = timestamp; this->uids = std::move(uids); } MatchedWinLoss:: MatchedWinLoss( Type type, Confidence confidence, const PostAuctionEvent& event, const FinishedInfo& info) : type(type), confidence(confidence) { initFinishedInfo(info); initMisc(event); } MatchedWinLoss:: MatchedWinLoss( Type type, Confidence confidence, const FinishedInfo& info, Date timestamp, UserIds uids) : type(type), confidence(confidence) { initFinishedInfo(info); initMisc(timestamp, std::move(uids)); } std::string MatchedWinLoss:: typeString() const { switch (type) { case LateWin: case Win: return "WIN"; case Loss: return "LOSS"; } ExcAssert(false); } std::string MatchedWinLoss:: confidenceString() const { switch (confidence) { case Inferred: return "inferred"; case Guaranteed: return "guaranteed"; } ExcAssert(false); } void MatchedWinLoss:: publish(ZmqNamedPublisher& logger) const { logger.publish( "MATCHED" + typeString(), // 0 publishTimestamp(), // 1 auctionId.toString(), // 2 std::to_string(impIndex), // 3 response.agent, // 4 response.account.at(1, ""), // 5 winPrice.toString(), // 6 response.price.maxPrice.toString(), // 7 std::to_string(response.price.priority), // 8 requestStr, // 9 response.bidData.toJsonStr(), // 10 response.meta, // 11 // This is where things start to get weird. std::to_string(response.creativeId), // 12 response.creativeName, // 13 response.account.at(0, ""), // 14 uids.toJsonStr(), // 15 meta, // 16 // And this is where we lose all pretenses of sanity. response.account.at(0, ""), // 17 impId.toString(), // 18 response.account.toString(), // 19 // Ok back to sanity now. requestStrFormat, // 20 rawWinPrice.toString(), // 21 augmentations.toString() // 22 ); } void MatchedWinLoss:: publish(AnalyticsPublisher & logger) const { logger.publish( "MATCHED" + typeString(), publishTimestamp(), auctionId.toString(), response.account.toString(), winPrice.toString(), rawWinPrice.toString(), uids.toJsonStr() ); } /******************************************************************************/ /* MATCHED CAMPAIGN EVENT */ /******************************************************************************/ MatchedCampaignEvent:: MatchedCampaignEvent(std::string label, const FinishedInfo& info) : label(std::move(label)), auctionId(info.auctionId), impId(info.adSpotId), impIndex(info.spotIndex), account(info.bid.account), requestStr(info.bidRequestStr), requestStrFormat(info.bidRequestStrFormat), response(info.bid), bid(info.bidToJson()), win(info.winToJson()), campaignEvents(info.campaignEvents.toJson()), visits(info.visitsToJson()), augmentations(info.augmentations) { auto it = std::find_if(info.campaignEvents.begin(), info.campaignEvents.end(), [&](const CampaignEvent& event) { return event.label_ == this->label; } ); if(it != info.campaignEvents.end()) timestamp = it->time_; } void MatchedCampaignEvent:: publish(ZmqNamedPublisher& logger) const { logger.publish( "MATCHED" + label, // 0 publishTimestamp(), // 1 auctionId.toString(), // 2 impId.toString(), // 3 requestStr, // 4 bid, // 5 win, // 6 campaignEvents, // 7 visits, // 8 account.at(0, ""), // 9 account.at(1, ""), // 10 account.toString(), // 11 requestStrFormat // 12 ); } void MatchedCampaignEvent:: publish(AnalyticsPublisher & logger) const { logger.publish( "MATCHED" + label, publishTimestamp(), auctionId.toString(), account.toString() ); } /******************************************************************************/ /* UNMATCHED EVENT */ /******************************************************************************/ UnmatchedEvent:: UnmatchedEvent(std::string reason, PostAuctionEvent event) : reason(std::move(reason)), event(std::move(event)) {} void UnmatchedEvent:: publish(ZmqNamedPublisher& logger) const { logger.publish( // Use event type not label since label is only defined for campaign events. "UNMATCHED" + string(print(event.type)), // 0 publishTimestamp(), // 1 reason, // 2 event.auctionId.toString(), // 3 event.adSpotId.toString(), // 4 std::to_string(event.timestamp.secondsSinceEpoch()), // 5 event.metadata.toJson() // 6 ); } void UnmatchedEvent:: publish(AnalyticsPublisher & logger) const { logger.publish( "UNMATCHED" + string(print(event.type)), publishTimestamp(), reason, event.auctionId.toString(), std::to_string(event.timestamp.secondsSinceEpoch()) ); } /******************************************************************************/ /* POST AUCTION ERROR EVENT */ /******************************************************************************/ PostAuctionErrorEvent:: PostAuctionErrorEvent(std::string key, std::string message) : key(std::move(key)), message(std::move(message)) {} void PostAuctionErrorEvent:: publish(ZmqNamedPublisher& logger) const { logger.publish("PAERROR", publishTimestamp(), key, message); } void PostAuctionErrorEvent:: publish(AnalyticsPublisher & logger) const { logger.publish("PAERROR", publishTimestamp(), key, message); } } // namepsace RTBKIT <|endoftext|>
<commit_before>#pragma once #include <memory> #include <vector> #include <boost/thread/tss.hpp> #include "blackhole/attribute.hpp" #include "blackhole/detail/config/atomic.hpp" #include "blackhole/detail/config/noncopyable.hpp" #include "blackhole/detail/config/nullptr.hpp" #include "blackhole/detail/util/unique.hpp" #include "error/handler.hpp" #include "filter.hpp" #include "frontend.hpp" #include "keyword.hpp" #include "keyword/message.hpp" #include "keyword/severity.hpp" #include "keyword/thread.hpp" #include "keyword/timestamp.hpp" #include "keyword/tracebit.hpp" #include "blackhole/config.hpp" namespace blackhole { class scoped_attributes_concept_t; template<typename Level> struct logger_verbosity_traits { typedef Level level_type; static inline bool passed(level_type logger_verbosity, level_type record_verbosity) { typedef typename aux::underlying_type<Level>::type underlying_type; return static_cast<underlying_type>(record_verbosity) >= static_cast<underlying_type>(logger_verbosity); } }; class logger_base_t { friend class scoped_attributes_concept_t; friend void swap(logger_base_t& lhs, logger_base_t& rhs) BLACKHOLE_NOEXCEPT; protected: typedef boost::shared_mutex rw_mutex_type; typedef boost::shared_lock<rw_mutex_type> reader_lock_type; typedef boost::unique_lock<rw_mutex_type> writer_lock_type; struct state_t { std::atomic<bool> enabled; std::atomic<bool> tracked; filter_t filter; struct attrbutes_t { attribute::set_t global; boost::thread_specific_ptr<scoped_attributes_concept_t> scoped; attrbutes_t(void(*deleter)(scoped_attributes_concept_t*)) : scoped(deleter) {} } attributes; std::vector<std::unique_ptr<base_frontend_t>> frontends; log::exception_handler_t exception; struct { mutable rw_mutex_type open; mutable rw_mutex_type push; } lock; state_t(); }; state_t state; public: logger_base_t(); //! @compat GCC4.4 //! Blaming GCC4.4 - it needs explicit move constructor definition, //! because it cannot define default move constructor for derived class. logger_base_t(logger_base_t&& other) BLACKHOLE_NOEXCEPT; logger_base_t& operator=(logger_base_t&& other) BLACKHOLE_NOEXCEPT; bool enabled() const; void enabled(bool enable); bool tracked() const; void tracked(bool enable); void set_filter(filter_t&& filter); void add_attribute(const attribute::pair_t& attribute); //!@todo: May be drop it, because there are wrappers? void add_frontend(std::unique_ptr<base_frontend_t> frontend); void set_exception_handler(log::exception_handler_t&& handler); record_t open_record() const; record_t open_record(attribute::pair_t attribute) const; record_t open_record(attribute::set_t attributes) const; void push(record_t&& record) const; protected: record_t open_record(attribute::set_t internal, attribute::set_t external) const; }; /// Concept form scoped attributes holder. /*! * @note: It's not movable to avoid moving to another thread. */ class scoped_attributes_concept_t { BLACKHOLE_DECLARE_NONCOPYABLE(scoped_attributes_concept_t); logger_base_t *m_logger; scoped_attributes_concept_t *m_previous; friend void swap(logger_base_t&, logger_base_t&) BLACKHOLE_NOEXCEPT; public: scoped_attributes_concept_t(logger_base_t& log); virtual ~scoped_attributes_concept_t(); virtual const attribute::set_t& attributes() const = 0; protected: bool has_parent() const; const scoped_attributes_concept_t& parent() const; }; template<typename Level> class verbose_logger_t : public logger_base_t { public: typedef Level level_type; private: level_type level; public: //!@todo: Replace with initialization ctor, repository.create<>("name", ...). verbose_logger_t() : logger_base_t(), level(static_cast<level_type>(0)) {} //! @compat: GCC4.4 //! GCC 4.4 doesn't create default copy/move constructor for derived //! classes. It's a bug. verbose_logger_t(verbose_logger_t&& other) BLACKHOLE_NOEXCEPT : logger_base_t(std::move(other)), level(static_cast<level_type>(other.level)) {} verbose_logger_t& operator=(verbose_logger_t&& other) BLACKHOLE_NOEXCEPT { logger_base_t::operator=(std::move(other)); level = other.level; return *this; } // Explicit import other overloaded methods. using logger_base_t::open_record; /*! * Gets the current upper verbosity bound. */ level_type verbosity() const { return level; } /*! * Sets the upper verbosity bound. * Every log event with a verbosity less than `level` will be dropped. * @param[in] level - Upper verbosity value. */ void verbosity(level_type level) { this->level = level; } /*! * Tries to open log record with specific verbosity level. * * Internally this method compares desired verbosity level with the upper * one and checks for tracebit attribute (temporary until filter redesign). * Can return invalid log record if some conditions are not met. * @param[in] level - Desired verbosity level. * @return valid or invalid `record_t` object. * @todo: Replace with custom filter once a time. */ record_t open_record(level_type level, attribute::set_t local = attribute::set_t()) const { typedef logger_verbosity_traits<level_type> verbosity_traits; const bool passed = verbosity_traits::passed(this->level, level); bool trace = false; if (!passed) { auto it = local.find(keyword::tracebit().name()); if (it != local.end()) { trace = boost::get<keyword::tag::tracebit_t::type>(it->second.value); } else { reader_lock_type lock(state.lock.open); if (state.attributes.scoped.get()) { const auto& scoped = state.attributes.scoped->attributes(); auto it = scoped.find(keyword::tracebit().name()); if (it != scoped.end()) { trace = boost::get<keyword::tag::tracebit_t::type>( it->second.value ); } } } } if (passed || trace) { attribute::set_t internal; internal.insert(keyword::severity<Level>() = level); return logger_base_t::open_record(std::move(internal), std::move(local)); } return record_t(); } }; } // namespace blackhole #if defined(BLACKHOLE_HEADER_ONLY) #include "blackhole/logger.ipp" #endif <commit_msg>[Planning] Seems like I've found filter solution.<commit_after>#pragma once #include <memory> #include <vector> #include <boost/thread/tss.hpp> #include "blackhole/attribute.hpp" #include "blackhole/detail/config/atomic.hpp" #include "blackhole/detail/config/noncopyable.hpp" #include "blackhole/detail/config/nullptr.hpp" #include "blackhole/detail/util/unique.hpp" #include "error/handler.hpp" #include "filter.hpp" #include "frontend.hpp" #include "keyword.hpp" #include "keyword/message.hpp" #include "keyword/severity.hpp" #include "keyword/thread.hpp" #include "keyword/timestamp.hpp" #include "keyword/tracebit.hpp" #include "blackhole/config.hpp" namespace blackhole { class scoped_attributes_concept_t; template<typename Level> struct logger_verbosity_traits { typedef Level level_type; static inline bool passed(level_type logger_verbosity, level_type record_verbosity) { typedef typename aux::underlying_type<Level>::type underlying_type; return static_cast<underlying_type>(record_verbosity) >= static_cast<underlying_type>(logger_verbosity); } }; class logger_base_t { friend class scoped_attributes_concept_t; friend void swap(logger_base_t& lhs, logger_base_t& rhs) BLACKHOLE_NOEXCEPT; protected: typedef boost::shared_mutex rw_mutex_type; typedef boost::shared_lock<rw_mutex_type> reader_lock_type; typedef boost::unique_lock<rw_mutex_type> writer_lock_type; struct state_t { std::atomic<bool> enabled; std::atomic<bool> tracked; filter_t filter; struct attrbutes_t { attribute::set_t global; boost::thread_specific_ptr<scoped_attributes_concept_t> scoped; attrbutes_t(void(*deleter)(scoped_attributes_concept_t*)) : scoped(deleter) {} } attributes; std::vector<std::unique_ptr<base_frontend_t>> frontends; log::exception_handler_t exception; struct { mutable rw_mutex_type open; mutable rw_mutex_type push; } lock; state_t(); }; state_t state; public: logger_base_t(); //! @compat GCC4.4 //! Blaming GCC4.4 - it needs explicit move constructor definition, //! because it cannot define default move constructor for derived class. logger_base_t(logger_base_t&& other) BLACKHOLE_NOEXCEPT; logger_base_t& operator=(logger_base_t&& other) BLACKHOLE_NOEXCEPT; bool enabled() const; void enabled(bool enable); bool tracked() const; void tracked(bool enable); void set_filter(filter_t&& filter); void add_attribute(const attribute::pair_t& attribute); //!@todo: May be drop it, because there are wrappers? void add_frontend(std::unique_ptr<base_frontend_t> frontend); void set_exception_handler(log::exception_handler_t&& handler); record_t open_record() const; record_t open_record(attribute::pair_t attribute) const; record_t open_record(attribute::set_t attributes) const; void push(record_t&& record) const; protected: record_t open_record(attribute::set_t internal, attribute::set_t external) const; }; /// Concept form scoped attributes holder. /*! * @note: It's not movable to avoid moving to another thread. */ class scoped_attributes_concept_t { BLACKHOLE_DECLARE_NONCOPYABLE(scoped_attributes_concept_t); logger_base_t *m_logger; scoped_attributes_concept_t *m_previous; friend void swap(logger_base_t&, logger_base_t&) BLACKHOLE_NOEXCEPT; public: scoped_attributes_concept_t(logger_base_t& log); virtual ~scoped_attributes_concept_t(); virtual const attribute::set_t& attributes() const = 0; protected: bool has_parent() const; const scoped_attributes_concept_t& parent() const; }; template<typename Level> class verbose_logger_t : public logger_base_t { public: typedef Level level_type; private: level_type level; //!@todo: Filter function (level_type level, const lightweight_view&) -> bool. //! - By default checks verbosity level. //! - Removes that creepy `logger_verbosity_traits`. //! - Filter hierarchy: verbose_logger_t -> logger_t -> sink_t. public: //!@todo: Replace with initialization ctor, repository.create<>("name", ...). verbose_logger_t() : logger_base_t(), level(static_cast<level_type>(0)) {} //! @compat: GCC4.4 //! GCC 4.4 doesn't create default copy/move constructor for derived //! classes. It's a bug. verbose_logger_t(verbose_logger_t&& other) BLACKHOLE_NOEXCEPT : logger_base_t(std::move(other)), level(static_cast<level_type>(other.level)) {} verbose_logger_t& operator=(verbose_logger_t&& other) BLACKHOLE_NOEXCEPT { logger_base_t::operator=(std::move(other)); level = other.level; return *this; } // Explicit import other overloaded methods. using logger_base_t::open_record; /*! * Gets the current upper verbosity bound. */ level_type verbosity() const { return level; } /*! * Sets the upper verbosity bound. * Every log event with a verbosity less than `level` will be dropped. * @param[in] level - Upper verbosity value. */ void verbosity(level_type level) { this->level = level; } /*! * Tries to open log record with specific verbosity level. * * Internally this method compares desired verbosity level with the upper * one and checks for tracebit attribute (temporary until filter redesign). * Can return invalid log record if some conditions are not met. * @param[in] level - Desired verbosity level. * @return valid or invalid `record_t` object. * @todo: Replace with custom filter once a time. */ record_t open_record(level_type level, attribute::set_t local = attribute::set_t()) const { typedef logger_verbosity_traits<level_type> verbosity_traits; const bool passed = verbosity_traits::passed(this->level, level); bool trace = false; if (!passed) { auto it = local.find(keyword::tracebit().name()); if (it != local.end()) { trace = boost::get<keyword::tag::tracebit_t::type>(it->second.value); } else { reader_lock_type lock(state.lock.open); if (state.attributes.scoped.get()) { const auto& scoped = state.attributes.scoped->attributes(); auto it = scoped.find(keyword::tracebit().name()); if (it != scoped.end()) { trace = boost::get<keyword::tag::tracebit_t::type>( it->second.value ); } } } } if (passed || trace) { attribute::set_t internal; internal.insert(keyword::severity<Level>() = level); return logger_base_t::open_record(std::move(internal), std::move(local)); } return record_t(); } }; } // namespace blackhole #if defined(BLACKHOLE_HEADER_ONLY) #include "blackhole/logger.ipp" #endif <|endoftext|>
<commit_before>/* * mkContext.cpp * MonkVG-XCode * * Created by Micah Pearlman on 2/22/09. * Copyright 2009 Monk Games. All rights reserved. * */ #include "mkContext.h" #include "glPath.h" using namespace MonkVG; //static VGContext *g_context = NULL; VG_API_CALL VGboolean vgCreateContextSH(VGint width, VGint height) { IContext::instance().Initialize(); IContext::instance().setWidth( width ); IContext::instance().setHeight( height ); IContext::instance().resize(); return VG_TRUE; } VG_API_CALL void vgResizeSurfaceSH(VGint width, VGint height) { IContext::instance().setWidth( width ); IContext::instance().setHeight( height ); IContext::instance().resize(); } VG_API_CALL void vgDestroyContextSH() { } VG_API_CALL void VG_API_ENTRY vgSetf (VGuint type, VGfloat value) VG_API_EXIT { IContext::instance().set( type, value ); } VG_API_CALL void VG_API_ENTRY vgSeti (VGuint type, VGint value) VG_API_EXIT { IContext::instance().set( type, value ); } VG_API_CALL void VG_API_ENTRY vgSetfv(VGuint type, VGint count, const VGfloat * values) VG_API_EXIT { IContext::instance().set( type, values ); } VG_API_CALL void VG_API_ENTRY vgSetiv(VGuint type, VGint count, const VGint * values) VG_API_EXIT { } VG_API_CALL VGfloat VG_API_ENTRY vgGetf(VGuint type) VG_API_EXIT { return -1.0f; } VG_API_CALL VGint VG_API_ENTRY vgGeti(VGuint type) VG_API_EXIT { return -1; } VG_API_CALL VGint VG_API_ENTRY vgGetVectorSize(VGuint type) VG_API_EXIT { return -1; } VG_API_CALL void VG_API_ENTRY vgGetfv(VGuint type, VGint count, VGfloat * values) VG_API_EXIT { } VG_API_CALL void VG_API_ENTRY vgGetiv(VGuint type, VGint count, VGint * values) VG_API_EXIT { } /* Masking and Clearing */ VG_API_CALL void VG_API_ENTRY vgClear(VGint x, VGint y, VGint width, VGint height) VG_API_EXIT { IContext::instance().clear( x, y, width, height ); } /*-------------------------------------------------- * Returns the oldest error pending on the current * context and clears its error code *--------------------------------------------------*/ VG_API_CALL VGErrorCode vgGetError(void) { return IContext::instance().getError(); } namespace MonkVG { IContext::IContext() : _error( VG_NO_ERROR ) , _width( 0 ) , _height( 0 ) , _stroke_line_width( 1.0f ) , _stroke_paint( 0 ) , _fill_paint( 0 ) , _active_matrix( &_path_user_to_surface ) , _fill_rule( VG_EVEN_ODD ) , _renderingQuality( VG_RENDERING_QUALITY_BETTER ) , _tessellationIterations( 16 ) , _matrixMode( VG_MATRIX_PATH_USER_TO_SURFACE ) , _currentBatch( 0 ) , _imageMode( VG_DRAW_IMAGE_NORMAL ) { _path_user_to_surface.setIdentity(); _glyph_user_to_surface.setIdentity(); _image_user_to_surface.setIdentity(); _active_matrix->setIdentity(); _glyph_origin[0] = _glyph_origin[1] = 0; setImageMode( _imageMode ); } //// parameters //// void IContext::set( VGuint type, VGfloat f ) { switch ( type ) { case VG_STROKE_LINE_WIDTH: setStrokeLineWidth( f ); break; default: setError( VG_ILLEGAL_ARGUMENT_ERROR ); break; } } void IContext::set( VGuint type, const VGfloat * fv ) { switch ( type ) { case VG_CLEAR_COLOR: setClearColor( fv ); break; case VG_GLYPH_ORIGIN: setGlyphOrigin( fv ); break; default: setError( VG_ILLEGAL_ARGUMENT_ERROR ); break; } } void IContext::set( VGuint type, VGint i ) { switch ( type ) { case VG_MATRIX_MODE: setMatrixMode( (VGMatrixMode)i ); break; case VG_FILL_RULE: setFillRule( (VGFillRule)i ); break; case VG_TESSELLATION_ITERATIONS_MNK: setTessellationIterations( i ); break; case VG_IMAGE_MODE: setImageMode( (VGImageMode)i ); break; default: break; } } void IContext::get( VGuint type, VGfloat &f ) const { switch ( type ) { case VG_STROKE_LINE_WIDTH: f = getStrokeLineWidth(); break; default: IContext::instance().setError( VG_ILLEGAL_ARGUMENT_ERROR ); break; } } void IContext::get( VGuint type, VGfloat *fv ) const { switch ( type ) { case VG_CLEAR_COLOR: getClearColor( fv ); break; case VG_GLYPH_ORIGIN: getGlyphOrigin( fv ); break; default: IContext::instance().setError( VG_ILLEGAL_ARGUMENT_ERROR ); break; } } void IContext::get( VGuint type, VGint& i ) const { i = -1; switch ( type ) { case VG_MATRIX_MODE: i = getMatrixMode( ); break; case VG_FILL_RULE: i = getFillRule( ); break; case VG_TESSELLATION_ITERATIONS_MNK: i = getTessellationIterations( ); break; case VG_IMAGE_MODE: i = getImageMode( ); break; default: break; } } }<commit_msg>add stub for vgFlush and vgFinish<commit_after>/* * mkContext.cpp * MonkVG-XCode * * Created by Micah Pearlman on 2/22/09. * Copyright 2009 Monk Games. All rights reserved. * */ #include "mkContext.h" #include "glPath.h" using namespace MonkVG; //static VGContext *g_context = NULL; VG_API_CALL VGboolean vgCreateContextSH(VGint width, VGint height) { IContext::instance().Initialize(); IContext::instance().setWidth( width ); IContext::instance().setHeight( height ); IContext::instance().resize(); return VG_TRUE; } VG_API_CALL void vgResizeSurfaceSH(VGint width, VGint height) { IContext::instance().setWidth( width ); IContext::instance().setHeight( height ); IContext::instance().resize(); } VG_API_CALL void vgDestroyContextSH() { } VG_API_CALL void VG_API_ENTRY vgSetf (VGuint type, VGfloat value) VG_API_EXIT { IContext::instance().set( type, value ); } VG_API_CALL void VG_API_ENTRY vgSeti (VGuint type, VGint value) VG_API_EXIT { IContext::instance().set( type, value ); } VG_API_CALL void VG_API_ENTRY vgSetfv(VGuint type, VGint count, const VGfloat * values) VG_API_EXIT { IContext::instance().set( type, values ); } VG_API_CALL void VG_API_ENTRY vgSetiv(VGuint type, VGint count, const VGint * values) VG_API_EXIT { } VG_API_CALL VGfloat VG_API_ENTRY vgGetf(VGuint type) VG_API_EXIT { return -1.0f; } VG_API_CALL VGint VG_API_ENTRY vgGeti(VGuint type) VG_API_EXIT { return -1; } VG_API_CALL VGint VG_API_ENTRY vgGetVectorSize(VGuint type) VG_API_EXIT { return -1; } VG_API_CALL void VG_API_ENTRY vgGetfv(VGuint type, VGint count, VGfloat * values) VG_API_EXIT { } VG_API_CALL void VG_API_ENTRY vgGetiv(VGuint type, VGint count, VGint * values) VG_API_EXIT { } /* Masking and Clearing */ VG_API_CALL void VG_API_ENTRY vgClear(VGint x, VGint y, VGint width, VGint height) VG_API_EXIT { IContext::instance().clear( x, y, width, height ); } /* Finish and Flush */ VG_API_CALL void VG_API_ENTRY vgFinish(void) VG_API_EXIT { glFinish(); } VG_API_CALL void VG_API_ENTRY vgFlush(void) VG_API_EXIT { glFlush(); } /*-------------------------------------------------- * Returns the oldest error pending on the current * context and clears its error code *--------------------------------------------------*/ VG_API_CALL VGErrorCode vgGetError(void) { return IContext::instance().getError(); } namespace MonkVG { IContext::IContext() : _error( VG_NO_ERROR ) , _width( 0 ) , _height( 0 ) , _stroke_line_width( 1.0f ) , _stroke_paint( 0 ) , _fill_paint( 0 ) , _active_matrix( &_path_user_to_surface ) , _fill_rule( VG_EVEN_ODD ) , _renderingQuality( VG_RENDERING_QUALITY_BETTER ) , _tessellationIterations( 16 ) , _matrixMode( VG_MATRIX_PATH_USER_TO_SURFACE ) , _currentBatch( 0 ) , _imageMode( VG_DRAW_IMAGE_NORMAL ) { _path_user_to_surface.setIdentity(); _glyph_user_to_surface.setIdentity(); _image_user_to_surface.setIdentity(); _active_matrix->setIdentity(); _glyph_origin[0] = _glyph_origin[1] = 0; setImageMode( _imageMode ); } //// parameters //// void IContext::set( VGuint type, VGfloat f ) { switch ( type ) { case VG_STROKE_LINE_WIDTH: setStrokeLineWidth( f ); break; default: setError( VG_ILLEGAL_ARGUMENT_ERROR ); break; } } void IContext::set( VGuint type, const VGfloat * fv ) { switch ( type ) { case VG_CLEAR_COLOR: setClearColor( fv ); break; case VG_GLYPH_ORIGIN: setGlyphOrigin( fv ); break; default: setError( VG_ILLEGAL_ARGUMENT_ERROR ); break; } } void IContext::set( VGuint type, VGint i ) { switch ( type ) { case VG_MATRIX_MODE: setMatrixMode( (VGMatrixMode)i ); break; case VG_FILL_RULE: setFillRule( (VGFillRule)i ); break; case VG_TESSELLATION_ITERATIONS_MNK: setTessellationIterations( i ); break; case VG_IMAGE_MODE: setImageMode( (VGImageMode)i ); break; default: break; } } void IContext::get( VGuint type, VGfloat &f ) const { switch ( type ) { case VG_STROKE_LINE_WIDTH: f = getStrokeLineWidth(); break; default: IContext::instance().setError( VG_ILLEGAL_ARGUMENT_ERROR ); break; } } void IContext::get( VGuint type, VGfloat *fv ) const { switch ( type ) { case VG_CLEAR_COLOR: getClearColor( fv ); break; case VG_GLYPH_ORIGIN: getGlyphOrigin( fv ); break; default: IContext::instance().setError( VG_ILLEGAL_ARGUMENT_ERROR ); break; } } void IContext::get( VGuint type, VGint& i ) const { i = -1; switch ( type ) { case VG_MATRIX_MODE: i = getMatrixMode( ); break; case VG_FILL_RULE: i = getFillRule( ); break; case VG_TESSELLATION_ITERATIONS_MNK: i = getTessellationIterations( ); break; case VG_IMAGE_MODE: i = getImageMode( ); break; default: break; } } } <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author 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 <asio/ip/host_name.hpp> #include <asio/ip/multicast.hpp> #include <boost/bind.hpp> #include "libtorrent/socket.hpp" #include "libtorrent/enum_net.hpp" #include "libtorrent/broadcast_socket.hpp" #include "libtorrent/assert.hpp" namespace libtorrent { bool is_local(address const& a) { if (a.is_v6()) return a.to_v6().is_link_local(); address_v4 a4 = a.to_v4(); unsigned long ip = a4.to_ulong(); return ((ip & 0xff000000) == 0x0a000000 || (ip & 0xfff00000) == 0xac100000 || (ip & 0xffff0000) == 0xc0a80000); } bool is_loopback(address const& addr) { if (addr.is_v4()) return addr.to_v4() == address_v4::loopback(); else return addr.to_v6() == address_v6::loopback(); } bool is_multicast(address const& addr) { if (addr.is_v4()) return addr.to_v4().is_multicast(); else return addr.to_v6().is_multicast(); } bool is_any(address const& addr) { if (addr.is_v4()) return addr.to_v4() == address_v4::any(); else return addr.to_v6() == address_v6::any(); } address guess_local_address(asio::io_service& ios) { // make a best guess of the interface we're using and its IP asio::error_code ec; std::vector<address> const& interfaces = enum_net_interfaces(ios, ec); address ret = address_v4::any(); for (std::vector<address>::const_iterator i = interfaces.begin() , end(interfaces.end()); i != end; ++i) { address const& a = *i; if (is_loopback(a) || is_multicast(a) || is_any(a)) continue; // prefer a v4 address, but return a v6 if // there are no v4 if (a.is_v4()) return a; if (ret != address_v4::any()) ret = a; } return ret; } broadcast_socket::broadcast_socket(asio::io_service& ios , udp::endpoint const& multicast_endpoint , receive_handler_t const& handler , bool loopback) : m_multicast_endpoint(multicast_endpoint) , m_on_receive(handler) { TORRENT_ASSERT(is_multicast(m_multicast_endpoint.address())); using namespace asio::ip::multicast; asio::error_code ec; std::vector<address> interfaces = enum_net_interfaces(ios, ec); for (std::vector<address>::const_iterator i = interfaces.begin() , end(interfaces.end()); i != end; ++i) { // only broadcast to IPv4 addresses that are not local if (!is_local(*i)) continue; // only multicast on compatible networks if (i->is_v4() != multicast_endpoint.address().is_v4()) continue; // ignore any loopback interface if (is_loopback(*i)) continue; boost::shared_ptr<datagram_socket> s(new datagram_socket(ios)); if (i->is_v4()) { s->open(udp::v4(), ec); if (ec) continue; s->set_option(datagram_socket::reuse_address(true), ec); if (ec) continue; s->bind(udp::endpoint(address_v4::any(), multicast_endpoint.port()), ec); if (ec) continue; s->set_option(join_group(multicast_endpoint.address()), ec); if (ec) continue; s->set_option(outbound_interface(i->to_v4()), ec); if (ec) continue; } else { s->open(udp::v6(), ec); if (ec) continue; s->set_option(datagram_socket::reuse_address(true), ec); if (ec) continue; s->bind(udp::endpoint(address_v6::any(), multicast_endpoint.port()), ec); if (ec) continue; s->set_option(join_group(multicast_endpoint.address()), ec); if (ec) continue; // s->set_option(outbound_interface(i->to_v6()), ec); // if (ec) continue; } s->set_option(hops(255), ec); if (ec) continue; s->set_option(enable_loopback(loopback), ec); if (ec) continue; m_sockets.push_back(socket_entry(s)); socket_entry& se = m_sockets.back(); s->async_receive_from(asio::buffer(se.buffer, sizeof(se.buffer)) , se.remote, bind(&broadcast_socket::on_receive, this, &se, _1, _2)); #ifndef NDEBUG // std::cerr << "broadcast socket [ if: " << i->to_v4().to_string() // << " group: " << multicast_endpoint.address() << " ]" << std::endl; #endif } } void broadcast_socket::send(char const* buffer, int size, asio::error_code& ec) { for (std::list<socket_entry>::iterator i = m_sockets.begin() , end(m_sockets.end()); i != end; ++i) { asio::error_code e; i->socket->send_to(asio::buffer(buffer, size), m_multicast_endpoint, 0, e); #ifndef NDEBUG // std::cerr << " sending on " << i->socket->local_endpoint().address().to_string() << std::endl; #endif if (e) ec = e; } } void broadcast_socket::on_receive(socket_entry* s, asio::error_code const& ec , std::size_t bytes_transferred) { if (ec || bytes_transferred == 0) return; m_on_receive(s->remote, s->buffer, bytes_transferred); s->socket->async_receive_from(asio::buffer(s->buffer, sizeof(s->buffer)) , s->remote, bind(&broadcast_socket::on_receive, this, s, _1, _2)); } void broadcast_socket::close() { m_on_receive.clear(); for (std::list<socket_entry>::iterator i = m_sockets.begin() , end(m_sockets.end()); i != end; ++i) { i->socket->close(); } } } <commit_msg>fixed potential call to empty boost.function<commit_after>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author 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 <asio/ip/host_name.hpp> #include <asio/ip/multicast.hpp> #include <boost/bind.hpp> #include "libtorrent/socket.hpp" #include "libtorrent/enum_net.hpp" #include "libtorrent/broadcast_socket.hpp" #include "libtorrent/assert.hpp" namespace libtorrent { bool is_local(address const& a) { if (a.is_v6()) return a.to_v6().is_link_local(); address_v4 a4 = a.to_v4(); unsigned long ip = a4.to_ulong(); return ((ip & 0xff000000) == 0x0a000000 || (ip & 0xfff00000) == 0xac100000 || (ip & 0xffff0000) == 0xc0a80000); } bool is_loopback(address const& addr) { if (addr.is_v4()) return addr.to_v4() == address_v4::loopback(); else return addr.to_v6() == address_v6::loopback(); } bool is_multicast(address const& addr) { if (addr.is_v4()) return addr.to_v4().is_multicast(); else return addr.to_v6().is_multicast(); } bool is_any(address const& addr) { if (addr.is_v4()) return addr.to_v4() == address_v4::any(); else return addr.to_v6() == address_v6::any(); } address guess_local_address(asio::io_service& ios) { // make a best guess of the interface we're using and its IP asio::error_code ec; std::vector<address> const& interfaces = enum_net_interfaces(ios, ec); address ret = address_v4::any(); for (std::vector<address>::const_iterator i = interfaces.begin() , end(interfaces.end()); i != end; ++i) { address const& a = *i; if (is_loopback(a) || is_multicast(a) || is_any(a)) continue; // prefer a v4 address, but return a v6 if // there are no v4 if (a.is_v4()) return a; if (ret != address_v4::any()) ret = a; } return ret; } broadcast_socket::broadcast_socket(asio::io_service& ios , udp::endpoint const& multicast_endpoint , receive_handler_t const& handler , bool loopback) : m_multicast_endpoint(multicast_endpoint) , m_on_receive(handler) { TORRENT_ASSERT(is_multicast(m_multicast_endpoint.address())); using namespace asio::ip::multicast; asio::error_code ec; std::vector<address> interfaces = enum_net_interfaces(ios, ec); for (std::vector<address>::const_iterator i = interfaces.begin() , end(interfaces.end()); i != end; ++i) { // only broadcast to IPv4 addresses that are not local if (!is_local(*i)) continue; // only multicast on compatible networks if (i->is_v4() != multicast_endpoint.address().is_v4()) continue; // ignore any loopback interface if (is_loopback(*i)) continue; boost::shared_ptr<datagram_socket> s(new datagram_socket(ios)); if (i->is_v4()) { s->open(udp::v4(), ec); if (ec) continue; s->set_option(datagram_socket::reuse_address(true), ec); if (ec) continue; s->bind(udp::endpoint(address_v4::any(), multicast_endpoint.port()), ec); if (ec) continue; s->set_option(join_group(multicast_endpoint.address()), ec); if (ec) continue; s->set_option(outbound_interface(i->to_v4()), ec); if (ec) continue; } else { s->open(udp::v6(), ec); if (ec) continue; s->set_option(datagram_socket::reuse_address(true), ec); if (ec) continue; s->bind(udp::endpoint(address_v6::any(), multicast_endpoint.port()), ec); if (ec) continue; s->set_option(join_group(multicast_endpoint.address()), ec); if (ec) continue; // s->set_option(outbound_interface(i->to_v6()), ec); // if (ec) continue; } s->set_option(hops(255), ec); if (ec) continue; s->set_option(enable_loopback(loopback), ec); if (ec) continue; m_sockets.push_back(socket_entry(s)); socket_entry& se = m_sockets.back(); s->async_receive_from(asio::buffer(se.buffer, sizeof(se.buffer)) , se.remote, bind(&broadcast_socket::on_receive, this, &se, _1, _2)); #ifndef NDEBUG // std::cerr << "broadcast socket [ if: " << i->to_v4().to_string() // << " group: " << multicast_endpoint.address() << " ]" << std::endl; #endif } } void broadcast_socket::send(char const* buffer, int size, asio::error_code& ec) { for (std::list<socket_entry>::iterator i = m_sockets.begin() , end(m_sockets.end()); i != end; ++i) { asio::error_code e; i->socket->send_to(asio::buffer(buffer, size), m_multicast_endpoint, 0, e); #ifndef NDEBUG // std::cerr << " sending on " << i->socket->local_endpoint().address().to_string() << std::endl; #endif if (e) ec = e; } } void broadcast_socket::on_receive(socket_entry* s, asio::error_code const& ec , std::size_t bytes_transferred) { if (ec || bytes_transferred == 0 || !m_on_receive) return; m_on_receive(s->remote, s->buffer, bytes_transferred); s->socket->async_receive_from(asio::buffer(s->buffer, sizeof(s->buffer)) , s->remote, bind(&broadcast_socket::on_receive, this, s, _1, _2)); } void broadcast_socket::close() { m_on_receive.clear(); for (std::list<socket_entry>::iterator i = m_sockets.begin() , end(m_sockets.end()); i != end; ++i) { i->socket->close(); } } } <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author 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 <asio/ip/host_name.hpp> #include <asio/ip/multicast.hpp> #include <boost/bind.hpp> #include "libtorrent/socket.hpp" #include "libtorrent/enum_net.hpp" #include "libtorrent/broadcast_socket.hpp" #include "libtorrent/assert.hpp" namespace libtorrent { bool is_local(address const& a) { if (a.is_v6()) return false; address_v4 a4 = a.to_v4(); unsigned long ip = a4.to_ulong(); return ((ip & 0xff000000) == 0x0a000000 || (ip & 0xfff00000) == 0xac100000 || (ip & 0xffff0000) == 0xc0a80000); } address_v4 guess_local_address(asio::io_service& ios) { // make a best guess of the interface we're using and its IP udp::resolver r(ios); udp::resolver::iterator i = r.resolve(udp::resolver::query(asio::ip::host_name(), "0")); for (;i != udp::resolver_iterator(); ++i) { // ignore the loopback if (i->endpoint().address() == address_v4((127 << 24) + 1)) continue; // ignore non-IPv4 addresses if (i->endpoint().address().is_v4()) break; } if (i == udp::resolver_iterator()) return address_v4::any(); return i->endpoint().address().to_v4(); } broadcast_socket::broadcast_socket(asio::io_service& ios , udp::endpoint const& multicast_endpoint , receive_handler_t const& handler) : m_multicast_endpoint(multicast_endpoint) , m_on_receive(handler) { assert(m_multicast_endpoint.address().is_v4()); assert(m_multicast_endpoint.address().to_v4().is_multicast()); using namespace asio::ip::multicast; asio::error_code ec; std::vector<address> interfaces = enum_net_interfaces(ios, ec); for (std::vector<address>::const_iterator i = interfaces.begin() , end(interfaces.end()); i != end; ++i) { // only broadcast to IPv4 addresses that are not local if (!i->is_v4() || !is_local(*i)) continue; // ignore the loopback interface if (i->to_v4() == address_v4((127 << 24) + 1)) continue; boost::shared_ptr<datagram_socket> s(new datagram_socket(ios)); s->open(udp::v4(), ec); if (ec) continue; s->set_option(datagram_socket::reuse_address(true), ec); if (ec) continue; s->bind(udp::endpoint(*i, multicast_endpoint.port()), ec); if (ec) continue; s->set_option(join_group(multicast_endpoint.address()), ec); if (ec) continue; s->set_option(outbound_interface(i->to_v4()), ec); if (ec) continue; s->set_option(hops(255), ec); if (ec) continue; s->set_option(enable_loopback(true), ec); if (ec) continue; m_sockets.push_back(socket_entry(s)); socket_entry& se = m_sockets.back(); s->async_receive_from(asio::buffer(se.buffer, sizeof(se.buffer)) , se.remote, bind(&broadcast_socket::on_receive, this, &se, _1, _2)); #ifndef NDEBUG // std::cerr << "broadcast socket [ if: " << i->to_v4().to_string() // << " group: " << multicast_endpoint.address() << " ]" << std::endl; #endif } } void broadcast_socket::send(char const* buffer, int size, asio::error_code& ec) { for (std::list<socket_entry>::iterator i = m_sockets.begin() , end(m_sockets.end()); i != end; ++i) { asio::error_code e; i->socket->send_to(asio::buffer(buffer, size), m_multicast_endpoint, 0, e); #ifndef NDEBUG // std::cerr << " sending on " << i->socket->local_endpoint().address().to_string() << std::endl; #endif if (e) ec = e; } } void broadcast_socket::on_receive(socket_entry* s, asio::error_code const& ec , std::size_t bytes_transferred) { if (ec || bytes_transferred == 0) return; m_on_receive(s->remote, s->buffer, bytes_transferred); s->socket->async_receive_from(asio::buffer(s->buffer, sizeof(s->buffer)) , s->remote, bind(&broadcast_socket::on_receive, this, s, _1, _2)); } void broadcast_socket::close() { for (std::list<socket_entry>::iterator i = m_sockets.begin() , end(m_sockets.end()); i != end; ++i) { i->socket->close(); } } } <commit_msg>broadcast socket fix<commit_after>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author 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 <asio/ip/host_name.hpp> #include <asio/ip/multicast.hpp> #include <boost/bind.hpp> #include "libtorrent/socket.hpp" #include "libtorrent/enum_net.hpp" #include "libtorrent/broadcast_socket.hpp" #include "libtorrent/assert.hpp" namespace libtorrent { bool is_local(address const& a) { if (a.is_v6()) return false; address_v4 a4 = a.to_v4(); unsigned long ip = a4.to_ulong(); return ((ip & 0xff000000) == 0x0a000000 || (ip & 0xfff00000) == 0xac100000 || (ip & 0xffff0000) == 0xc0a80000); } address_v4 guess_local_address(asio::io_service& ios) { // make a best guess of the interface we're using and its IP udp::resolver r(ios); udp::resolver::iterator i = r.resolve(udp::resolver::query(asio::ip::host_name(), "0")); for (;i != udp::resolver_iterator(); ++i) { // ignore the loopback if (i->endpoint().address() == address_v4((127 << 24) + 1)) continue; // ignore non-IPv4 addresses if (i->endpoint().address().is_v4()) break; } if (i == udp::resolver_iterator()) return address_v4::any(); return i->endpoint().address().to_v4(); } broadcast_socket::broadcast_socket(asio::io_service& ios , udp::endpoint const& multicast_endpoint , receive_handler_t const& handler) : m_multicast_endpoint(multicast_endpoint) , m_on_receive(handler) { assert(m_multicast_endpoint.address().is_v4()); assert(m_multicast_endpoint.address().to_v4().is_multicast()); using namespace asio::ip::multicast; asio::error_code ec; std::vector<address> interfaces = enum_net_interfaces(ios, ec); for (std::vector<address>::const_iterator i = interfaces.begin() , end(interfaces.end()); i != end; ++i) { // only broadcast to IPv4 addresses that are not local if (!i->is_v4() || !is_local(*i)) continue; // ignore the loopback interface if (i->to_v4() == address_v4((127 << 24) + 1)) continue; boost::shared_ptr<datagram_socket> s(new datagram_socket(ios)); s->open(udp::v4(), ec); if (ec) continue; s->set_option(datagram_socket::reuse_address(true), ec); if (ec) continue; s->bind(udp::endpoint(address_v4::any(), multicast_endpoint.port()), ec); if (ec) continue; s->set_option(join_group(multicast_endpoint.address()), ec); if (ec) continue; s->set_option(outbound_interface(i->to_v4()), ec); if (ec) continue; s->set_option(hops(255), ec); if (ec) continue; s->set_option(enable_loopback(true), ec); if (ec) continue; m_sockets.push_back(socket_entry(s)); socket_entry& se = m_sockets.back(); s->async_receive_from(asio::buffer(se.buffer, sizeof(se.buffer)) , se.remote, bind(&broadcast_socket::on_receive, this, &se, _1, _2)); #ifndef NDEBUG // std::cerr << "broadcast socket [ if: " << i->to_v4().to_string() // << " group: " << multicast_endpoint.address() << " ]" << std::endl; #endif } } void broadcast_socket::send(char const* buffer, int size, asio::error_code& ec) { for (std::list<socket_entry>::iterator i = m_sockets.begin() , end(m_sockets.end()); i != end; ++i) { asio::error_code e; i->socket->send_to(asio::buffer(buffer, size), m_multicast_endpoint, 0, e); #ifndef NDEBUG // std::cerr << " sending on " << i->socket->local_endpoint().address().to_string() << std::endl; #endif if (e) ec = e; } } void broadcast_socket::on_receive(socket_entry* s, asio::error_code const& ec , std::size_t bytes_transferred) { if (ec || bytes_transferred == 0) return; m_on_receive(s->remote, s->buffer, bytes_transferred); s->socket->async_receive_from(asio::buffer(s->buffer, sizeof(s->buffer)) , s->remote, bind(&broadcast_socket::on_receive, this, s, _1, _2)); } void broadcast_socket::close() { for (std::list<socket_entry>::iterator i = m_sockets.begin() , end(m_sockets.end()); i != end; ++i) { i->socket->close(); } } } <|endoftext|>
<commit_before>#include <sirius.h> #include <thread> using namespace sirius; void test_fft_omp(vector3d<int>& dims__) { printf("test of threaded FFTs (OMP version)\n"); int max_num_threads = Platform::max_num_threads(); std::vector< std::pair<int, int> > threads_conf; for (int i = 1; i <= max_num_threads; i++) { for (int j = 1; j <= max_num_threads; j++) { if (i * j < 2 * max_num_threads) threads_conf.push_back(std::pair<int, int>(i, j)); } } matrix3d<double> reciprocal_lattice_vectors; for (int i = 0; i < 3; i++) reciprocal_lattice_vectors(i, i) = 1.0; for (int k = 0; k < (int)threads_conf.size(); k++) { printf("\n"); printf("number of fft threads: %i, number of fft workers: %i\n", threads_conf[k].first, threads_conf[k].second); FFT3D<CPU> fft(dims__, threads_conf[k].first, threads_conf[k].second); fft.init_gvec(20.0, reciprocal_lattice_vectors); int num_phi = 160; mdarray<double_complex, 2> phi(fft.num_gvec(), num_phi); for (int i = 0; i < num_phi; i++) { for (int ig = 0; ig < fft.num_gvec(); ig++) phi(ig, i) = type_wrapper<double_complex>::random(); } Timer t("fft_loop"); #pragma omp parallel num_threads(fft.num_fft_threads()) { int thread_id = Platform::thread_id(); #pragma omp for for (int i = 0; i < num_phi; i++) { fft.input(fft.num_gvec(), fft.index_map(), &phi(0, i), thread_id); fft.transform(1, thread_id); for (int ir = 0; ir < fft.size(); ir++) fft.buffer(ir, thread_id) += 1.0; fft.transform(-1, thread_id); fft.output(fft.num_gvec(), fft.index_map(), &phi(0, i), thread_id); } } double tval = t.stop(); printf("performance: %f, (FFT/sec.)\n", 2 * num_phi / tval); } } void test_fft_pthread(vector3d<int>& dims__) { printf("test of threaded FFTs (pthread version)\n"); int max_num_threads = Platform::max_num_threads(); std::vector< std::pair<int, int> > threads_conf; for (int i = 1; i <= max_num_threads; i++) { for (int j = 1; j <= max_num_threads; j++) { if (i * j < 2 * max_num_threads) threads_conf.push_back(std::pair<int, int>(i, j)); } } matrix3d<double> reciprocal_lattice_vectors; for (int i = 0; i < 3; i++) reciprocal_lattice_vectors(i, i) = 1.0; for (int k = 0; k < (int)threads_conf.size(); k++) { printf("\n"); printf("number of fft threads: %i, number of fft workers: %i\n", threads_conf[k].first, threads_conf[k].second); FFT3D<CPU> fft(dims__, threads_conf[k].first, threads_conf[k].second); fft.init_gvec(20.0, reciprocal_lattice_vectors); int num_phi = 160; mdarray<double_complex, 2> phi(fft.num_gvec(), num_phi); for (int i = 0; i < num_phi; i++) { for (int ig = 0; ig < fft.num_gvec(); ig++) phi(ig, i) = type_wrapper<double_complex>::random(); } std::atomic_int ibnd; ibnd.store(0); Timer t("fft_loop"); std::vector<std::thread> fft_threads; for (int thread_id = 0; thread_id < fft.num_fft_threads(); thread_id++) { fft_threads.push_back(std::thread([thread_id, num_phi, &ibnd, &fft, &phi]() { while (true) { int i = ibnd++; if (i >= num_phi) return; fft.input(fft.num_gvec(), fft.index_map(), &phi(0, i), thread_id); fft.transform(1, thread_id); for (int ir = 0; ir < fft.size(); ir++) fft.buffer(ir, thread_id) += 1.0; fft.transform(-1, thread_id); fft.output(fft.num_gvec(), fft.index_map(), &phi(0, i), thread_id); } })); } for (auto& thread: fft_threads) thread.join(); double tval = t.stop(); printf("performance: %f, (FFT/sec.)\n", 2 * num_phi / tval); } } int main(int argn, char **argv) { cmd_args args; args.register_key("--dims=", "{vector3d<int>} FFT dimensions"); args.parse_args(argn, argv); if (argn == 1) { printf("Usage: %s [options]\n", argv[0]); args.print_help(); exit(0); } vector3d<int> dims = args.value< vector3d<int> >("dims"); Platform::initialize(1); test_fft_omp(dims); test_fft_pthread(dims); Platform::finalize(); } <commit_msg>new test<commit_after>#include <sirius.h> #include <thread> #include <mutex> using namespace sirius; void test_fft_omp(vector3d<int>& dims__) { printf("test of threaded FFTs (OMP version)\n"); int max_num_threads = Platform::max_num_threads(); std::vector< std::pair<int, int> > threads_conf; for (int i = 1; i <= max_num_threads; i++) { for (int j = 1; j <= max_num_threads; j++) { if (i * j < 2 * max_num_threads) threads_conf.push_back(std::pair<int, int>(i, j)); } } matrix3d<double> reciprocal_lattice_vectors; for (int i = 0; i < 3; i++) reciprocal_lattice_vectors(i, i) = 1.0; for (int k = 0; k < (int)threads_conf.size(); k++) { printf("\n"); printf("number of fft threads: %i, number of fft workers: %i\n", threads_conf[k].first, threads_conf[k].second); FFT3D<CPU> fft(dims__, threads_conf[k].first, threads_conf[k].second); fft.init_gvec(20.0, reciprocal_lattice_vectors); int num_phi = 160; mdarray<double_complex, 2> phi(fft.num_gvec(), num_phi); for (int i = 0; i < num_phi; i++) { for (int ig = 0; ig < fft.num_gvec(); ig++) phi(ig, i) = type_wrapper<double_complex>::random(); } Timer t("fft_loop"); #pragma omp parallel num_threads(fft.num_fft_threads()) { int thread_id = Platform::thread_id(); #pragma omp for for (int i = 0; i < num_phi; i++) { fft.input(fft.num_gvec(), fft.index_map(), &phi(0, i), thread_id); fft.transform(1, thread_id); for (int ir = 0; ir < fft.size(); ir++) fft.buffer(ir, thread_id) += 1.0; fft.transform(-1, thread_id); fft.output(fft.num_gvec(), fft.index_map(), &phi(0, i), thread_id); } } double tval = t.stop(); printf("performance: %f, (FFT/sec.)\n", 2 * num_phi / tval); } } void test_fft_pthread(vector3d<int>& dims__) { printf("test of threaded FFTs (pthread version)\n"); int max_num_threads = Platform::max_num_threads(); std::vector< std::pair<int, int> > threads_conf; for (int i = 1; i <= max_num_threads; i++) { for (int j = 1; j <= max_num_threads; j++) { if (i * j < 2 * max_num_threads) threads_conf.push_back(std::pair<int, int>(i, j)); } } matrix3d<double> reciprocal_lattice_vectors; for (int i = 0; i < 3; i++) reciprocal_lattice_vectors(i, i) = 1.0; for (int k = 0; k < (int)threads_conf.size(); k++) { printf("\n"); printf("number of fft threads: %i, number of fft workers: %i\n", threads_conf[k].first, threads_conf[k].second); FFT3D<CPU> fft(dims__, threads_conf[k].first, threads_conf[k].second); fft.init_gvec(20.0, reciprocal_lattice_vectors); int num_phi = 160; mdarray<double_complex, 2> phi(fft.num_gvec(), num_phi); for (int i = 0; i < num_phi; i++) { for (int ig = 0; ig < fft.num_gvec(); ig++) phi(ig, i) = type_wrapper<double_complex>::random(); } std::atomic_int ibnd; ibnd.store(0); Timer t("fft_loop"); std::vector<std::thread> fft_threads; for (int thread_id = 0; thread_id < fft.num_fft_threads(); thread_id++) { fft_threads.push_back(std::thread([thread_id, num_phi, &ibnd, &fft, &phi]() { while (true) { int i = ibnd++; if (i >= num_phi) return; fft.input(fft.num_gvec(), fft.index_map(), &phi(0, i), thread_id); fft.transform(1, thread_id); for (int ir = 0; ir < fft.size(); ir++) fft.buffer(ir, thread_id) += 1.0; fft.transform(-1, thread_id); fft.output(fft.num_gvec(), fft.index_map(), &phi(0, i), thread_id); } })); } for (auto& thread: fft_threads) thread.join(); double tval = t.stop(); printf("performance: %f, (FFT/sec.)\n", 2 * num_phi / tval); } } void test_fft_pthread_mutex(vector3d<int>& dims__) { printf("\n"); printf("test of threaded FFTs (pthread version, mutex lock)\n"); int max_num_threads = Platform::max_num_threads(); std::vector< std::pair<int, int> > threads_conf; for (int i = 1; i <= max_num_threads; i++) { for (int j = 1; j <= max_num_threads; j++) { if (i * j < 2 * max_num_threads) threads_conf.push_back(std::pair<int, int>(i, j)); } } matrix3d<double> reciprocal_lattice_vectors; for (int i = 0; i < 3; i++) reciprocal_lattice_vectors(i, i) = 1.0; for (int k = 0; k < (int)threads_conf.size(); k++) { printf("\n"); printf("number of fft threads: %i, number of fft workers: %i\n", threads_conf[k].first, threads_conf[k].second); FFT3D<CPU> fft(dims__, threads_conf[k].first, threads_conf[k].second); fft.init_gvec(20.0, reciprocal_lattice_vectors); int num_phi = 160; mdarray<double_complex, 2> phi(fft.num_gvec(), num_phi); for (int i = 0; i < num_phi; i++) { for (int ig = 0; ig < fft.num_gvec(); ig++) phi(ig, i) = type_wrapper<double_complex>::random(); } int ibnd = 0; std::mutex ibnd_mutex; Timer t("fft_loop"); std::vector<std::thread> fft_threads; for (int thread_id = 0; thread_id < fft.num_fft_threads(); thread_id++) { fft_threads.push_back(std::thread([thread_id, num_phi, &ibnd, &ibnd_mutex, &fft, &phi]() { while (true) { ibnd_mutex.lock(); int i = ibnd; if (ibnd + 1 > num_phi) { ibnd_mutex.unlock(); return; } else { ibnd++; } ibnd_mutex.unlock(); fft.input(fft.num_gvec(), fft.index_map(), &phi(0, i), thread_id); fft.transform(1, thread_id); for (int ir = 0; ir < fft.size(); ir++) fft.buffer(ir, thread_id) += 1.0; fft.transform(-1, thread_id); fft.output(fft.num_gvec(), fft.index_map(), &phi(0, i), thread_id); } })); } for (auto& thread: fft_threads) thread.join(); double tval = t.stop(); printf("performance: %f, (FFT/sec.)\n", 2 * num_phi / tval); } } int main(int argn, char **argv) { cmd_args args; args.register_key("--dims=", "{vector3d<int>} FFT dimensions"); args.parse_args(argn, argv); if (argn == 1) { printf("Usage: %s [options]\n", argv[0]); args.print_help(); exit(0); } vector3d<int> dims = args.value< vector3d<int> >("dims"); Platform::initialize(1); //test_fft_omp(dims); test_fft_pthread(dims); test_fft_pthread_mutex(dims); Platform::finalize(); } <|endoftext|>
<commit_before>#include "cinder/app/AppNative.h" #include "cinder/gl/gl.h" #include "cinder/Rand.h" #include "entityx/Event.h" #include "entityx/Entity.h" #include "entityx/System.h" #include "pockets/Types.h" #include "puptent/Rendering.h" using namespace ci; using namespace ci::app; using namespace std; using namespace puptent; using namespace entityx; using pockets::Vertex2d; struct SpriteData { ci::Vec2f registration_point = ci::Vec2f::zero(); ci::Vec2i size = ci::Vec2i( 48, 48 ); const ci::Rectf texture_bounds = ci::Rectf(0,0,1,1); }; struct Sprite : Component<Sprite> { struct Drawing{ SpriteData sprite; float hold; // frames to hold }; Sprite() { applyDataToMesh(); } void applyDataToMesh() { // set mesh data from current frame const auto drawing = currentFrame().sprite; Rectf tex_coord_rect = drawing.texture_bounds; Rectf position_rect( Vec2f::zero(), drawing.size ); position_rect -= drawing.registration_point; mesh->vertices[0].position = { position_rect.getX2(), position_rect.getY1() }; mesh->vertices[1].position = { position_rect.getX1(), position_rect.getY1() }; mesh->vertices[2].position = { position_rect.getX2(), position_rect.getY2() }; mesh->vertices[3].position = { position_rect.getX1(), position_rect.getY2() }; mesh->vertices[0].tex_coord = { tex_coord_rect.getX2(), tex_coord_rect.getY1() }; mesh->vertices[1].tex_coord = { tex_coord_rect.getX1(), tex_coord_rect.getY1() }; mesh->vertices[2].tex_coord = { tex_coord_rect.getX2(), tex_coord_rect.getY2() }; mesh->vertices[3].tex_coord = { tex_coord_rect.getX1(), tex_coord_rect.getY2() }; } const Drawing &currentFrame() const { return frames.at( current_index ); } std::vector<Drawing> frames; int current_index = 0; // this limits us to 32k frames per animation... float hold = 0.0f; // time spent on this frame float frame_duration = 1.0f / 24.0f; bool looping = true; // feels like we should create the mesh here and then add that mesh component to stuff shared_ptr<RenderMesh2d> mesh = shared_ptr<RenderMesh2d>{ new RenderMesh2d{ 4, 0 } }; // the mesh we will be updating }; struct SpriteSystem : public System<SpriteSystem> { void update( shared_ptr<EntityManager> es, shared_ptr<EventManager> events, double dt ) override { for( auto entity : es->entities_with_components<Sprite>() ) { auto sprite = entity.component<Sprite>(); sprite->hold += dt; int next_index = sprite->current_index; if( sprite->hold > sprite->frame_duration * sprite->currentFrame().hold ) { // move to next frame next_index += 1; sprite->hold = 0.0f; } else if ( sprite->hold < 0.0f ) { // step back a frame next_index -= 1; sprite->hold = sprite->frame_duration * sprite->currentFrame().hold; } if( next_index >= static_cast<int>( sprite->frames.size() ) ) { // handle wraparound at end next_index = sprite->looping ? 0 : sprite->frames.size() - 1; } else if( next_index < 0 ) { // handle wraparound at beginning next_index = sprite->looping ? sprite->frames.size() - 1 : 0; } if( next_index != sprite->current_index ) { // the frame index has changed, update display sprite->current_index = next_index; sprite->applyDataToMesh(); } } } }; struct Velocity : Component<Velocity> { Velocity( float x = 0.0f, float y = 0.0f ): velocity( x, y ) {} ci::Vec2f velocity; }; struct MovementSystem : public System<MovementSystem> { void update( shared_ptr<EntityManager> es, shared_ptr<EventManager> events, double dt ) override { if( mElements.empty() ) { for( auto entity : es->entities_with_components<Locus>() ) { mElements.push_back( entity.component<Locus>() ); } } for( auto& loc : mElements ) { loc->rotation = fmodf( loc->rotation + M_PI * 0.01f, M_PI * 2 ); } } vector<shared_ptr<Locus>> mElements; }; class PupTentApp : public AppNative { public: void prepareSettings( Settings *settings ); void setup(); void update(); void draw(); private: shared_ptr<EventManager> mEvents; shared_ptr<EntityManager> mEntities; shared_ptr<SystemManager> mSystemManager; shared_ptr<MovementSystem> mMovement; double mLastUpdate = 0.0; double mAverageRenderTime = 0; }; void PupTentApp::prepareSettings( Settings *settings ) { settings->disableFrameRate(); } void PupTentApp::setup() { gl::enableVerticalSync(); mEvents = EventManager::make(); mEntities = EntityManager::make(mEvents); mSystemManager = SystemManager::make( mEntities, mEvents ); mSystemManager->add<MovementSystem>(); mSystemManager->add<RenderSystem>(); mSystemManager->configure(); Rand r; Vec2f center = getWindowCenter(); for( int i = 0; i < 1000; ++i ) { Entity entity = mEntities->create(); auto loc = shared_ptr<Locus>{ new Locus }; auto mesh = shared_ptr<RenderMesh2d>{ new RenderMesh2d }; ColorA color{ CM_HSV, r.nextFloat( 1.0f ), 0.9f, 0.9f, 1.0f }; for( auto &v : mesh->vertices ) { v.color = color; } loc->position = { r.nextFloat( getWindowWidth() ), r.nextFloat( getWindowHeight() ) }; loc->rotation = r.nextFloat( M_PI * 2 ); mesh->render_layer = loc->position.distance( center ); entity.assign<Locus>( loc ); entity.assign<RenderMesh2d>( mesh ); } } void PupTentApp::update() { double now = getElapsedSeconds(); double dt = now - mLastUpdate; mLastUpdate = now; double start = getElapsedSeconds(); mSystemManager->update<MovementSystem>( dt ); double end = getElapsedSeconds(); if( getElapsedFrames() % 120 == 0 ) { cout << "Update: " << (end - start) * 1000 << endl; } } void PupTentApp::draw() { // clear out the window with black gl::clear( Color( 0, 0, 0 ) ); double start = getElapsedSeconds(); mSystemManager->update<RenderSystem>( 0.0 ); mSystemManager->system<RenderSystem>()->draw(); double end = getElapsedSeconds(); double ms = (end - start) * 1000; mAverageRenderTime = (mAverageRenderTime * 59.0 + ms) / 60.0; if( getElapsedFrames() % 120 == 0 ) { cout << "Render ms: " << mAverageRenderTime << endl; } } CINDER_APP_NATIVE( PupTentApp, RendererGl( RendererGl::AA_MSAA_4 ) ) <commit_msg>Use events to update cached lists in SpriteSystem.<commit_after>#include "cinder/app/AppNative.h" #include "cinder/gl/gl.h" #include "cinder/Rand.h" #include "entityx/Event.h" #include "entityx/Entity.h" #include "entityx/System.h" #include "pockets/Types.h" #include "pockets/CollectionUtilities.hpp" #include "puptent/Rendering.h" using namespace ci; using namespace ci::app; using namespace std; using namespace puptent; using namespace entityx; using pockets::Vertex2d; struct SpriteData { ci::Vec2f registration_point = ci::Vec2f::zero(); ci::Vec2i size = ci::Vec2i( 48, 48 ); const ci::Rectf texture_bounds = ci::Rectf(0,0,1,1); }; struct Sprite : Component<Sprite> { struct Drawing{ SpriteData sprite; float hold; // frames to hold }; Sprite() { applyDataToMesh(); } void applyDataToMesh() { // set mesh data from current frame const auto drawing = currentFrame().sprite; Rectf tex_coord_rect = drawing.texture_bounds; Rectf position_rect( Vec2f::zero(), drawing.size ); position_rect -= drawing.registration_point; mesh->vertices[0].position = { position_rect.getX2(), position_rect.getY1() }; mesh->vertices[1].position = { position_rect.getX1(), position_rect.getY1() }; mesh->vertices[2].position = { position_rect.getX2(), position_rect.getY2() }; mesh->vertices[3].position = { position_rect.getX1(), position_rect.getY2() }; mesh->vertices[0].tex_coord = { tex_coord_rect.getX2(), tex_coord_rect.getY1() }; mesh->vertices[1].tex_coord = { tex_coord_rect.getX1(), tex_coord_rect.getY1() }; mesh->vertices[2].tex_coord = { tex_coord_rect.getX2(), tex_coord_rect.getY2() }; mesh->vertices[3].tex_coord = { tex_coord_rect.getX1(), tex_coord_rect.getY2() }; } const Drawing &currentFrame() const { return frames.at( current_index ); } std::vector<Drawing> frames; int current_index = 0; // this limits us to 32k frames per animation... float hold = 0.0f; // time spent on this frame float frame_duration = 1.0f / 24.0f; bool looping = true; // we create the mesh here and then add that mesh to entities // that way, we know we are using the expected mesh in the entity shared_ptr<RenderMesh2d> mesh = shared_ptr<RenderMesh2d>{ new RenderMesh2d{ 4, 0 } }; // the mesh we will be updating }; struct SpriteSystem : public System<SpriteSystem>, Receiver<SpriteSystem> { void configure( shared_ptr<EventManager> events ) override { events->subscribe<EntityDestroyedEvent>( *this ); events->subscribe<ComponentAddedEvent<Sprite>>( *this ); } void receive( const EntityDestroyedEvent &event ) { // stop tracking the entity auto entity = event.entity; if( entity.component<Sprite>() ) { vector_remove( &mEntities, entity ); } } void receive( const ComponentAddedEvent<Sprite> &event ) { // track the sprite mEntities.push_back( event.entity ); } void update( shared_ptr<EntityManager> es, shared_ptr<EventManager> events, double dt ) override { for( auto entity : mEntities ) { auto sprite = entity.component<Sprite>(); sprite->hold += dt; int next_index = sprite->current_index; if( sprite->hold > sprite->frame_duration * sprite->currentFrame().hold ) { // move to next frame next_index += 1; sprite->hold = 0.0f; } else if ( sprite->hold < 0.0f ) { // step back a frame next_index -= 1; sprite->hold = sprite->frame_duration * sprite->currentFrame().hold; } if( next_index >= static_cast<int>( sprite->frames.size() ) ) { // handle wraparound at end next_index = sprite->looping ? 0 : sprite->frames.size() - 1; } else if( next_index < 0 ) { // handle wraparound at beginning next_index = sprite->looping ? sprite->frames.size() - 1 : 0; } if( next_index != sprite->current_index ) { // the frame index has changed, update display sprite->current_index = next_index; sprite->applyDataToMesh(); } } } private: std::vector<Entity> mEntities; }; struct Velocity : Component<Velocity> { Velocity( float x = 0.0f, float y = 0.0f ): velocity( x, y ) {} ci::Vec2f velocity; }; struct MovementSystem : public System<MovementSystem> { void update( shared_ptr<EntityManager> es, shared_ptr<EventManager> events, double dt ) override { if( mElements.empty() ) { for( auto entity : es->entities_with_components<Locus>() ) { mElements.push_back( entity.component<Locus>() ); } } for( auto& loc : mElements ) { loc->rotation = fmodf( loc->rotation + M_PI * 0.01f, M_PI * 2 ); } } vector<shared_ptr<Locus>> mElements; }; class PupTentApp : public AppNative { public: void prepareSettings( Settings *settings ); void setup(); void update(); void draw(); private: shared_ptr<EventManager> mEvents; shared_ptr<EntityManager> mEntities; shared_ptr<SystemManager> mSystemManager; shared_ptr<MovementSystem> mMovement; double mLastUpdate = 0.0; double mAverageRenderTime = 0; }; void PupTentApp::prepareSettings( Settings *settings ) { settings->disableFrameRate(); } void PupTentApp::setup() { gl::enableVerticalSync(); mEvents = EventManager::make(); mEntities = EntityManager::make(mEvents); mSystemManager = SystemManager::make( mEntities, mEvents ); mSystemManager->add<MovementSystem>(); mSystemManager->add<RenderSystem>(); mSystemManager->configure(); Rand r; Vec2f center = getWindowCenter(); for( int i = 0; i < 1000; ++i ) { Entity entity = mEntities->create(); auto loc = shared_ptr<Locus>{ new Locus }; auto mesh = shared_ptr<RenderMesh2d>{ new RenderMesh2d }; ColorA color{ CM_HSV, r.nextFloat( 1.0f ), 0.9f, 0.9f, 1.0f }; for( auto &v : mesh->vertices ) { v.color = color; } loc->position = { r.nextFloat( getWindowWidth() ), r.nextFloat( getWindowHeight() ) }; loc->rotation = r.nextFloat( M_PI * 2 ); mesh->render_layer = loc->position.distance( center ); entity.assign<Locus>( loc ); entity.assign<RenderMesh2d>( mesh ); } } void PupTentApp::update() { double now = getElapsedSeconds(); double dt = now - mLastUpdate; mLastUpdate = now; double start = getElapsedSeconds(); mSystemManager->update<MovementSystem>( dt ); double end = getElapsedSeconds(); if( getElapsedFrames() % 120 == 0 ) { cout << "Update: " << (end - start) * 1000 << endl; } } void PupTentApp::draw() { // clear out the window with black gl::clear( Color( 0, 0, 0 ) ); double start = getElapsedSeconds(); mSystemManager->update<RenderSystem>( 0.0 ); mSystemManager->system<RenderSystem>()->draw(); double end = getElapsedSeconds(); double ms = (end - start) * 1000; mAverageRenderTime = (mAverageRenderTime * 59.0 + ms) / 60.0; if( getElapsedFrames() % 120 == 0 ) { cout << "Render ms: " << mAverageRenderTime << endl; } } CINDER_APP_NATIVE( PupTentApp, RendererGl( RendererGl::AA_MSAA_4 ) ) <|endoftext|>
<commit_before>#include <iostream> #include <ros/ros.h> #include "../libraries/nodes/ConverterNode.h" int main (int argc,char* argv[]) { ros::init(argc, argv, "CONVERTER"); ConverterNode converterNode; ros::spin(); return 0; } <commit_msg>moving all to branch 2D<commit_after>#include <iostream> #include <ros/ros.h> #include "../libraries/nodes/ConverterNode.h" int main (int argc,char* argv[]) { ros::init(argc, argv, "CONVERTER"); ConverterNode converterNode; ros::spin(); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: vbaworksheets.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2007-04-25 16:14:08 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "vbaworksheets.hxx" #include <sfx2/dispatch.hxx> #include <sfx2/app.hxx> #include <sfx2/bindings.hxx> #include <sfx2/request.hxx> #include <sfx2/viewfrm.hxx> #include <sfx2/itemwrapper.hxx> #include <svtools/itemset.hxx> #include <svtools/eitem.hxx> #include <comphelper/processfactory.hxx> #include <cppuhelper/implbase3.hxx> #include <com/sun/star/sheet/XSpreadsheetDocument.hpp> #include <com/sun/star/container/XEnumerationAccess.hpp> #include <com/sun/star/sheet/XSpreadsheetView.hpp> #include <com/sun/star/container/XNamed.hpp> #include <com/sun/star/lang/IndexOutOfBoundsException.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <org/openoffice/excel/XApplication.hpp> #include <tools/string.hxx> #include "vbaglobals.hxx" #include "vbaworksheet.hxx" #include "vbaworkbook.hxx" using namespace ::org::openoffice; using namespace ::com::sun::star; class SheetsEnumeration : public EnumerationHelperImpl { uno::Reference< frame::XModel > m_xModel; public: SheetsEnumeration( const uno::Reference< uno::XComponentContext >& xContext, const uno::Reference< container::XEnumeration >& xEnumeration, const uno::Reference< frame::XModel >& xModel ) throw ( uno::RuntimeException ) : EnumerationHelperImpl( xContext, xEnumeration ), m_xModel( xModel ) {} virtual uno::Any SAL_CALL nextElement( ) throw (container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException) { uno::Reference< sheet::XSpreadsheet > xSheet( m_xEnumeration->nextElement(), uno::UNO_QUERY_THROW ); return uno::makeAny( uno::Reference< excel::XWorksheet > ( new ScVbaWorksheet( m_xContext, xSheet, m_xModel ) ) ); } }; ScVbaWorksheets::ScVbaWorksheets( const uno::Reference< ::com::sun::star::uno::XComponentContext > & xContext, const uno::Reference< sheet::XSpreadsheets >& xSheets, const uno::Reference< frame::XModel >& xModel ): ScVbaWorksheets_BASE( xContext, uno::Reference< container::XIndexAccess >( xSheets, uno::UNO_QUERY ) ), mxModel( xModel ), m_xSheets( xSheets ) { } ScVbaWorksheets::ScVbaWorksheets( const uno::Reference< ::com::sun::star::uno::XComponentContext > & xContext, const uno::Reference< container::XEnumerationAccess >& xEnumAccess, const uno::Reference< frame::XModel >& xModel ): ScVbaWorksheets_BASE( xContext, uno::Reference< container::XIndexAccess >( xEnumAccess, uno::UNO_QUERY ) ), mxModel(xModel) { } // XEnumerationAccess uno::Type ScVbaWorksheets::getElementType() throw (uno::RuntimeException) { return excel::XWorksheet::static_type(0); } uno::Reference< container::XEnumeration > ScVbaWorksheets::createEnumeration() throw (uno::RuntimeException) { if ( !m_xSheets.is() ) { uno::Reference< container::XEnumerationAccess > xAccess( m_xIndexAccess, uno::UNO_QUERY_THROW ); return xAccess->createEnumeration(); } uno::Reference< container::XEnumerationAccess > xEnumAccess( m_xSheets, uno::UNO_QUERY_THROW ); return new SheetsEnumeration( m_xContext, xEnumAccess->createEnumeration(), mxModel ); } uno::Any ScVbaWorksheets::createCollectionObject( const uno::Any& aSource ) { uno::Reference< sheet::XSpreadsheet > xSheet( aSource, uno::UNO_QUERY ); return uno::makeAny( uno::Reference< excel::XWorksheet > ( new ScVbaWorksheet( m_xContext, xSheet, mxModel ) ) ); } // XWorksheets uno::Any ScVbaWorksheets::Add( const uno::Any& Before, const uno::Any& After, const uno::Any& Count, const uno::Any& Type ) throw (uno::RuntimeException) { if ( isSelectedSheets() ) return uno::Any(); // or should we throw? rtl::OUString aStringSheet; sal_Bool bBefore(sal_True); SCTAB nSheetIndex = 0; SCTAB nNewSheets = 1, nType = 0; Count >>= nNewSheets; Type >>= nType; SCTAB nCount = 0; Before >>= aStringSheet; if (!aStringSheet.getLength()) { After >>= aStringSheet; bBefore = sal_False; } if (!aStringSheet.getLength()) { aStringSheet = ScVbaGlobals::getGlobalsImpl( m_xContext )->getApplication()->getActiveWorkbook()->getActiveSheet()->getName(); bBefore = sal_True; } nCount = static_cast< SCTAB >( m_xIndexAccess->getCount() ); for (SCTAB i=0; i < nCount; i++) { uno::Reference< sheet::XSpreadsheet > xSheet(m_xIndexAccess->getByIndex(i), uno::UNO_QUERY); uno::Reference< container::XNamed > xNamed( xSheet, uno::UNO_QUERY_THROW ); if (xNamed->getName() == aStringSheet) { nSheetIndex = i; break; } } if(!bBefore) nSheetIndex++; SCTAB nSheetName = nCount + 1L; String aStringBase( RTL_CONSTASCII_USTRINGPARAM("Sheet") ); uno::Any result; for (SCTAB i=0; i < nNewSheets; i++, nSheetName++) { String aStringName = aStringBase; aStringName += String::CreateFromInt32(nSheetName); while (m_xNameAccess->hasByName(aStringName)) { nSheetName++; aStringName = aStringBase; aStringName += String::CreateFromInt32(nSheetName); } m_xSheets->insertNewByName(aStringName, nSheetIndex + i); result = getItemByStringIndex( aStringName ); } return result; } void ScVbaWorksheets::Delete() throw (uno::RuntimeException) { //SC_VBA_STUB(); } bool ScVbaWorksheets::isSelectedSheets() { return !m_xSheets.is(); } void SAL_CALL ScVbaWorksheets::PrintOut( const uno::Any& From, const uno::Any& To, const uno::Any& Copies, const uno::Any& Preview, const uno::Any& ActivePrinter, const uno::Any& PrintToFile, const uno::Any& Collate, const uno::Any& PrToFileName ) throw (uno::RuntimeException) { sal_Int32 nTo = 0; sal_Int32 nFrom = 0; sal_Int16 nCopies = 1; sal_Bool bCollate = sal_False; sal_Bool bSelection = sal_False; From >>= nFrom; To >>= nTo; Copies >>= nCopies; if ( nCopies > 1 ) // Collate only useful when more that 1 copy Collate >>= bCollate; if ( !( nFrom || nTo ) ) if ( isSelectedSheets() ) bSelection = sal_True; PrintOutHelper( From, To, Copies, Preview, ActivePrinter, PrintToFile, Collate, PrToFileName, mxModel, bSelection ); } uno::Any SAL_CALL ScVbaWorksheets::getVisible() throw (uno::RuntimeException) { sal_Bool bVisible = sal_True; uno::Reference< container::XEnumeration > xEnum( createEnumeration(), uno::UNO_QUERY_THROW ); while ( xEnum->hasMoreElements() ) { uno::Reference< excel::XWorksheet > xSheet( xEnum->nextElement(), uno::UNO_QUERY_THROW ); if ( xSheet->getVisible() == sal_False ) { bVisible = sal_False; break; } } return uno::makeAny( bVisible ); } void SAL_CALL ScVbaWorksheets::setVisible( const uno::Any& _visible ) throw (uno::RuntimeException) { sal_Bool bState; if ( _visible >>= bState ) { uno::Reference< container::XEnumeration > xEnum( createEnumeration(), uno::UNO_QUERY_THROW ); while ( xEnum->hasMoreElements() ) { uno::Reference< excel::XWorksheet > xSheet( xEnum->nextElement(), uno::UNO_QUERY_THROW ); xSheet->setVisible( bState ); } } else throw uno::RuntimeException( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Visible property doesn't support non boolean #FIXME" ) ), uno::Reference< uno::XInterface >() ); } //ScVbaCollectionBaseImpl uno::Any ScVbaWorksheets::getItemByStringIndex( const rtl::OUString& sIndex ) throw (uno::RuntimeException) { String sScIndex = sIndex; ScDocument::ConvertToValidTabName( sScIndex, '_' ); return ScVbaCollectionBaseImpl::getItemByStringIndex( sScIndex ); } <commit_msg>INTEGRATION: CWS npower7 (1.2.2); FILE MERGED 2007/05/17 16:12:07 npower 1.2.2.1: fix warning = error on mac build ( from tinderbox )<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: vbaworksheets.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2007-08-30 10:05:17 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "vbaworksheets.hxx" #include <sfx2/dispatch.hxx> #include <sfx2/app.hxx> #include <sfx2/bindings.hxx> #include <sfx2/request.hxx> #include <sfx2/viewfrm.hxx> #include <sfx2/itemwrapper.hxx> #include <svtools/itemset.hxx> #include <svtools/eitem.hxx> #include <comphelper/processfactory.hxx> #include <cppuhelper/implbase3.hxx> #include <com/sun/star/sheet/XSpreadsheetDocument.hpp> #include <com/sun/star/container/XEnumerationAccess.hpp> #include <com/sun/star/sheet/XSpreadsheetView.hpp> #include <com/sun/star/container/XNamed.hpp> #include <com/sun/star/lang/IndexOutOfBoundsException.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <org/openoffice/excel/XApplication.hpp> #include <tools/string.hxx> #include "vbaglobals.hxx" #include "vbaworksheet.hxx" #include "vbaworkbook.hxx" using namespace ::org::openoffice; using namespace ::com::sun::star; class SheetsEnumeration : public EnumerationHelperImpl { uno::Reference< frame::XModel > m_xModel; public: SheetsEnumeration( const uno::Reference< uno::XComponentContext >& xContext, const uno::Reference< container::XEnumeration >& xEnumeration, const uno::Reference< frame::XModel >& xModel ) throw ( uno::RuntimeException ) : EnumerationHelperImpl( xContext, xEnumeration ), m_xModel( xModel ) {} virtual uno::Any SAL_CALL nextElement( ) throw (container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException) { uno::Reference< sheet::XSpreadsheet > xSheet( m_xEnumeration->nextElement(), uno::UNO_QUERY_THROW ); return uno::makeAny( uno::Reference< excel::XWorksheet > ( new ScVbaWorksheet( m_xContext, xSheet, m_xModel ) ) ); } }; ScVbaWorksheets::ScVbaWorksheets( const uno::Reference< ::com::sun::star::uno::XComponentContext > & xContext, const uno::Reference< sheet::XSpreadsheets >& xSheets, const uno::Reference< frame::XModel >& xModel ): ScVbaWorksheets_BASE( xContext, uno::Reference< container::XIndexAccess >( xSheets, uno::UNO_QUERY ) ), mxModel( xModel ), m_xSheets( xSheets ) { } ScVbaWorksheets::ScVbaWorksheets( const uno::Reference< ::com::sun::star::uno::XComponentContext > & xContext, const uno::Reference< container::XEnumerationAccess >& xEnumAccess, const uno::Reference< frame::XModel >& xModel ): ScVbaWorksheets_BASE( xContext, uno::Reference< container::XIndexAccess >( xEnumAccess, uno::UNO_QUERY ) ), mxModel(xModel) { } // XEnumerationAccess uno::Type ScVbaWorksheets::getElementType() throw (uno::RuntimeException) { return excel::XWorksheet::static_type(0); } uno::Reference< container::XEnumeration > ScVbaWorksheets::createEnumeration() throw (uno::RuntimeException) { if ( !m_xSheets.is() ) { uno::Reference< container::XEnumerationAccess > xAccess( m_xIndexAccess, uno::UNO_QUERY_THROW ); return xAccess->createEnumeration(); } uno::Reference< container::XEnumerationAccess > xEnumAccess( m_xSheets, uno::UNO_QUERY_THROW ); return new SheetsEnumeration( m_xContext, xEnumAccess->createEnumeration(), mxModel ); } uno::Any ScVbaWorksheets::createCollectionObject( const uno::Any& aSource ) { uno::Reference< sheet::XSpreadsheet > xSheet( aSource, uno::UNO_QUERY ); return uno::makeAny( uno::Reference< excel::XWorksheet > ( new ScVbaWorksheet( m_xContext, xSheet, mxModel ) ) ); } // XWorksheets uno::Any ScVbaWorksheets::Add( const uno::Any& Before, const uno::Any& After, const uno::Any& Count, const uno::Any& Type ) throw (uno::RuntimeException) { if ( isSelectedSheets() ) return uno::Any(); // or should we throw? rtl::OUString aStringSheet; sal_Bool bBefore(sal_True); SCTAB nSheetIndex = 0; SCTAB nNewSheets = 1, nType = 0; Count >>= nNewSheets; Type >>= nType; SCTAB nCount = 0; Before >>= aStringSheet; if (!aStringSheet.getLength()) { After >>= aStringSheet; bBefore = sal_False; } if (!aStringSheet.getLength()) { aStringSheet = ScVbaGlobals::getGlobalsImpl( m_xContext )->getApplication()->getActiveWorkbook()->getActiveSheet()->getName(); bBefore = sal_True; } nCount = static_cast< SCTAB >( m_xIndexAccess->getCount() ); for (SCTAB i=0; i < nCount; i++) { uno::Reference< sheet::XSpreadsheet > xSheet(m_xIndexAccess->getByIndex(i), uno::UNO_QUERY); uno::Reference< container::XNamed > xNamed( xSheet, uno::UNO_QUERY_THROW ); if (xNamed->getName() == aStringSheet) { nSheetIndex = i; break; } } if(!bBefore) nSheetIndex++; SCTAB nSheetName = nCount + 1L; String aStringBase( RTL_CONSTASCII_USTRINGPARAM("Sheet") ); uno::Any result; for (SCTAB i=0; i < nNewSheets; i++, nSheetName++) { String aStringName = aStringBase; aStringName += String::CreateFromInt32(nSheetName); while (m_xNameAccess->hasByName(aStringName)) { nSheetName++; aStringName = aStringBase; aStringName += String::CreateFromInt32(nSheetName); } m_xSheets->insertNewByName(aStringName, nSheetIndex + i); result = getItemByStringIndex( aStringName ); } return result; } void ScVbaWorksheets::Delete() throw (uno::RuntimeException) { //SC_VBA_STUB(); } bool ScVbaWorksheets::isSelectedSheets() { return !m_xSheets.is(); } void SAL_CALL ScVbaWorksheets::PrintOut( const uno::Any& From, const uno::Any& To, const uno::Any& Copies, const uno::Any& Preview, const uno::Any& ActivePrinter, const uno::Any& PrintToFile, const uno::Any& Collate, const uno::Any& PrToFileName ) throw (uno::RuntimeException) { sal_Int32 nTo = 0; sal_Int32 nFrom = 0; sal_Int16 nCopies = 1; sal_Bool bCollate = sal_False; sal_Bool bSelection = sal_False; From >>= nFrom; To >>= nTo; Copies >>= nCopies; if ( nCopies > 1 ) // Collate only useful when more that 1 copy Collate >>= bCollate; if ( !( nFrom || nTo ) ) if ( isSelectedSheets() ) bSelection = sal_True; PrintOutHelper( From, To, Copies, Preview, ActivePrinter, PrintToFile, Collate, PrToFileName, mxModel, bSelection ); } uno::Any SAL_CALL ScVbaWorksheets::getVisible() throw (uno::RuntimeException) { sal_Bool bVisible = sal_True; uno::Reference< container::XEnumeration > xEnum( createEnumeration(), uno::UNO_QUERY_THROW ); while ( xEnum->hasMoreElements() ) { uno::Reference< excel::XWorksheet > xSheet( xEnum->nextElement(), uno::UNO_QUERY_THROW ); if ( xSheet->getVisible() == sal_False ) { bVisible = sal_False; break; } } return uno::makeAny( bVisible ); } void SAL_CALL ScVbaWorksheets::setVisible( const uno::Any& _visible ) throw (uno::RuntimeException) { sal_Bool bState = sal_False; if ( _visible >>= bState ) { uno::Reference< container::XEnumeration > xEnum( createEnumeration(), uno::UNO_QUERY_THROW ); while ( xEnum->hasMoreElements() ) { uno::Reference< excel::XWorksheet > xSheet( xEnum->nextElement(), uno::UNO_QUERY_THROW ); xSheet->setVisible( bState ); } } else throw uno::RuntimeException( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Visible property doesn't support non boolean #FIXME" ) ), uno::Reference< uno::XInterface >() ); } //ScVbaCollectionBaseImpl uno::Any ScVbaWorksheets::getItemByStringIndex( const rtl::OUString& sIndex ) throw (uno::RuntimeException) { String sScIndex = sIndex; ScDocument::ConvertToValidTabName( sScIndex, '_' ); return ScVbaCollectionBaseImpl::getItemByStringIndex( sScIndex ); } <|endoftext|>
<commit_before>/* * PosixFileScanner.cpp * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include <core/system/FileScanner.hpp> #include <dirent.h> #include <sys/stat.h> #include <core/Error.hpp> #include <core/Log.hpp> #include <core/FilePath.hpp> #include <core/BoostThread.hpp> namespace core { namespace system { namespace { #ifdef __APPLE__ int entryFilter(struct dirent *entry) #else int entryFilter(const struct dirent *entry) #endif { if (::strcmp(entry->d_name, ".") == 0 || ::strcmp(entry->d_name, "..") == 0) return 0; else return 1; } } // anonymous namespace Error scanFiles(const tree<FileInfo>::iterator_base& fromNode, const FileScannerOptions& options, tree<FileInfo>* pTree) { // clear all existing pTree->erase_children(fromNode); // create FilePath for root FilePath rootPath(fromNode->absolutePath()); // yield if requested (only applies to recursive scans) if (options.recursive && options.yield) boost::this_thread::yield(); // call onBeforeScanDir hook if (options.onBeforeScanDir) { Error error = options.onBeforeScanDir(*fromNode); if (error) return error; } // read directory contents struct dirent **namelist; int entries = ::scandir(fromNode->absolutePath().c_str(), &namelist, entryFilter, ::alphasort); if (entries == -1) { Error error = systemError(boost::system::errc::no_such_file_or_directory, ERROR_LOCATION); error.addProperty("path", fromNode->absolutePath()); return error; } // iterate over entries for(int i=0; i<entries; i++) { // yield every 10 entries if requested if (options.yield) { if (i % 10 == 0) boost::this_thread::yield(); } // get the entry (then free it) and compute the path dirent entry = *namelist[i]; ::free(namelist[i]); std::string name(entry.d_name, #ifdef __APPLE__ entry.d_namlen); #else entry.d_reclen); #endif std::string path = rootPath.childPath(name).absolutePath(); // get the attributes struct stat st; int res = ::lstat(path.c_str(), &st); if (res == -1) { Error error = systemError(errno, ERROR_LOCATION); error.addProperty("path", path); LOG_ERROR(error); continue; } // create the FileInfo FileInfo fileInfo; bool isSymlink = S_ISLNK(st.st_mode); if (S_ISDIR(st.st_mode)) { fileInfo = FileInfo(path, true, isSymlink); } else { fileInfo = FileInfo(path, false, st.st_size, #ifdef __APPLE__ st.st_mtimespec.tv_sec, #else st.st_mtime, #endif isSymlink); } // apply the filter (if any) if (!options.filter || options.filter(fileInfo)) { // add the correct type of FileEntry if (fileInfo.isDirectory()) { tree<FileInfo>::iterator_base child = pTree->append_child(fromNode, fileInfo); // recurse if requested and this isn't a link if (options.recursive && !fileInfo.isSymlink()) { // try to scan the files in the subdirectory -- if we fail // we continue because we don't want one "bad" directory // to cause us to abort the entire scan. yes the tree // will be incomplete however it will be even more incompete // if we fail entirely Error error = scanFiles(child, options, pTree); if (error) LOG_ERROR(error); } } else { pTree->append_child(fromNode, fileInfo); } } } // free the namelist ::free(namelist); // return success return Success(); } } // namespace system } // namespace core <commit_msg>free namelist immediately after copying file names (don't allow alloc to survive recursive calls)<commit_after>/* * PosixFileScanner.cpp * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include <core/system/FileScanner.hpp> #include <dirent.h> #include <sys/stat.h> #include <boost/foreach.hpp> #include <core/Error.hpp> #include <core/Log.hpp> #include <core/FilePath.hpp> #include <core/BoostThread.hpp> namespace core { namespace system { namespace { #ifdef __APPLE__ int entryFilter(struct dirent *entry) #else int entryFilter(const struct dirent *entry) #endif { if (::strcmp(entry->d_name, ".") == 0 || ::strcmp(entry->d_name, "..") == 0) return 0; else return 1; } // wrapper for scandir api Error scanDir(const std::string& dirPath, std::vector<std::string>* pNames) { // read directory contents into namelist struct dirent **namelist; int entries = ::scandir(dirPath.c_str(), &namelist, entryFilter, ::alphasort); if (entries == -1) { Error error = systemError(errno, ERROR_LOCATION); error.addProperty("path", dirPath); return error; } // extract the namelist then free it for(int i=0; i<entries; i++) { // get the name (then free it) std::string name(namelist[i]->d_name, #ifdef __APPLE__ namelist[i]->d_namlen); #else namelist[i]->d_reclen); #endif ::free(namelist[i]); // add to the vector pNames->push_back(name); } ::free(namelist); return Success(); } } // anonymous namespace Error scanFiles(const tree<FileInfo>::iterator_base& fromNode, const FileScannerOptions& options, tree<FileInfo>* pTree) { // clear all existing pTree->erase_children(fromNode); // create FilePath for root FilePath rootPath(fromNode->absolutePath()); // yield if requested (only applies to recursive scans) if (options.recursive && options.yield) boost::this_thread::yield(); // call onBeforeScanDir hook if (options.onBeforeScanDir) { Error error = options.onBeforeScanDir(*fromNode); if (error) return error; } // read directory contents std::vector<std::string> names; Error error = scanDir(fromNode->absolutePath(), &names); if (error) return error; // iterate over the names BOOST_FOREACH(const std::string& name, names) { // compute the path std::string path = rootPath.childPath(name).absolutePath(); // get the attributes struct stat st; int res = ::lstat(path.c_str(), &st); if (res == -1) { Error error = systemError(errno, ERROR_LOCATION); error.addProperty("path", path); LOG_ERROR(error); continue; } // create the FileInfo FileInfo fileInfo; bool isSymlink = S_ISLNK(st.st_mode); if (S_ISDIR(st.st_mode)) { fileInfo = FileInfo(path, true, isSymlink); } else { fileInfo = FileInfo(path, false, st.st_size, #ifdef __APPLE__ st.st_mtimespec.tv_sec, #else st.st_mtime, #endif isSymlink); } // apply the filter (if any) if (!options.filter || options.filter(fileInfo)) { // add the correct type of FileEntry if (fileInfo.isDirectory()) { tree<FileInfo>::iterator_base child = pTree->append_child(fromNode, fileInfo); // recurse if requested and this isn't a link if (options.recursive && !fileInfo.isSymlink()) { // try to scan the files in the subdirectory -- if we fail // we continue because we don't want one "bad" directory // to cause us to abort the entire scan. yes the tree // will be incomplete however it will be even more incompete // if we fail entirely Error error = scanFiles(child, options, pTree); if (error) LOG_ERROR(error); } } else { pTree->append_child(fromNode, fileInfo); } } } // return success return Success(); } } // namespace system } // namespace core <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "System.h" #include <decaf/lang/exceptions/NullPointerException.h> #include <decaf/lang/exceptions/IllegalArgumentException.h> #include <decaf/lang/exceptions/RuntimeException.h> #include <decaf/util/Date.h> #include <decaf/util/StringTokenizer.h> #include <apr.h> #include <apr_errno.h> #include <apr_env.h> #ifdef APR_HAVE_UNISTD_H #include <unistd.h> #endif #include <cstdlib> using namespace std; using namespace decaf; using namespace decaf::lang; using namespace decaf::util; using namespace decaf::internal; using namespace decaf::lang::exceptions; //////////////////////////////////////////////////////////////////////////////// AprPool System::aprPool; //////////////////////////////////////////////////////////////////////////////// System::System() { } //////////////////////////////////////////////////////////////////////////////// void System::unsetenv( const std::string& name ) throw ( lang::Exception ) { apr_status_t result = APR_SUCCESS; // Clear the value, errors are thrown out as an exception result = apr_env_delete( name.c_str(), aprPool.getAprPool() ); aprPool.cleanup(); if( result != APR_SUCCESS ) { char buffer[256] = {0}; throw NullPointerException( __FILE__, __LINE__, "System::getenv - ", apr_strerror( result, buffer, 255 ) ); } } //////////////////////////////////////////////////////////////////////////////// std::string System::getenv( const std::string& name ) throw ( Exception ) { char* value = NULL; apr_status_t result = APR_SUCCESS; // Read the value, errors are thrown out as an exception result = apr_env_get( &value, name.c_str(), aprPool.getAprPool() ); if( result != APR_SUCCESS ) { char buffer[256] = {0}; throw NullPointerException( __FILE__, __LINE__, "System::getenv - ", apr_strerror( result, buffer, 255 ) ); } // Copy and cleanup if( value == NULL ) { return ""; } std::string envVal( value ); aprPool.cleanup(); return value; } //////////////////////////////////////////////////////////////////////////////// void System::setenv( const std::string& name, const std::string& value ) throw ( lang::Exception ) { apr_status_t result = APR_SUCCESS; // Write the value, errors are thrown out as an exception result = apr_env_set( name.c_str(), value.c_str(), aprPool.getAprPool() ); aprPool.cleanup(); if( result != APR_SUCCESS ) { char buffer[256] = {0}; throw NullPointerException( __FILE__, __LINE__, "System::getenv - ", apr_strerror( result, buffer, 255 ) ); } } //////////////////////////////////////////////////////////////////////////////// long long System::currentTimeMillis() { return Date::getCurrentTimeMilliseconds(); } //////////////////////////////////////////////////////////////////////////////// Map<string, string> System::getenv() throw ( Exception ) { Map<string, string> values; StringTokenizer tokenizer( "" ); string key = ""; string value = ""; int tokens = 0; char** env = getEnvArray(); if( env == NULL ) { throw RuntimeException( __FILE__, __LINE__, "System::getenv - Failed to enumerate the environment." ); } for( int i = 0; *(env + i); i++ ){ tokenizer.reset( env[i], "=" ); delete env[i]; // Clean them as we go tokens = tokenizer.countTokens(); if( tokens == 1 ) { // special case, no value set, store empty string as value key = tokenizer.nextToken(); value = string(""); } else if( tokens > 2 ) { // special case: first equals delimits the key value, the rest are // part of the variable std::string envVal( environ[i] ); int pos = envVal.find( "=" ); key = envVal.substr( 0, pos ); value = envVal.substr( pos + 1, string::npos ); } else if( tokens == 0 ) { // Odd case, got a string with no equals sign. throw IllegalArgumentException( __FILE__, __LINE__, "System::getenv - Invalid env string. %s", environ[i] ); } else { // Normal case. key = tokenizer.nextToken(); value = tokenizer.nextToken(); } // Store the env var values.setValue( key, value ); } // cleanup delete [] env; return values; } #if defined(_WIN32) #include <windows.h> //////////////////////////////////////////////////////////////////////////////// char** System::getEnvArray() { char** buffer = NULL; int count = 0; LPTSTR lpszVars; LPVOID lpvEnv; lpvEnv = GetEnvironmentStrings(); if( NULL == lpvEnv ){ return NULL; } lpszVars = (LPTSTR)lpvEnv; while( *lpszVars != NULL ) { count++; lpszVars += strlen(lpszVars)+1; } // allocate buffer first dimension buffer = new char*[count+1]; buffer[count] = NULL; lpszVars = (LPTSTR)lpvEnv; int index = 0; while( *lpszVars != NULL ) { buffer[++index] = strdup( lpszVars ); lpszVars += strlen(lpszVars)+1; } FreeEnvironmentStrings( (LPTCH)lpvEnv ); return buffer; } #else //////////////////////////////////////////////////////////////////////////////// char** System::getEnvArray() { char** buffer = NULL; int count = 0; for( int i = 0; *(environ + i); i++ ){ count++; } // allocate buffer first dimension buffer = new char*[count+1]; buffer[count] = NULL; for( int i = 0; *(environ + i); i++ ){ buffer[i] = strdup( environ[i] ); } return buffer; } #endif <commit_msg>https://issues.apache.org/activemq/browse/AMQCPP-144<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "System.h" #include <decaf/lang/exceptions/NullPointerException.h> #include <decaf/lang/exceptions/IllegalArgumentException.h> #include <decaf/lang/exceptions/RuntimeException.h> #include <decaf/util/Date.h> #include <decaf/util/StringTokenizer.h> #include <apr.h> #include <apr_errno.h> #include <apr_env.h> #ifdef APR_HAVE_UNISTD_H #include <unistd.h> #endif #include <cstdlib> using namespace std; using namespace decaf; using namespace decaf::lang; using namespace decaf::util; using namespace decaf::internal; using namespace decaf::lang::exceptions; //////////////////////////////////////////////////////////////////////////////// AprPool System::aprPool; //////////////////////////////////////////////////////////////////////////////// System::System() { } //////////////////////////////////////////////////////////////////////////////// void System::unsetenv( const std::string& name ) throw ( lang::Exception ) { apr_status_t result = APR_SUCCESS; // Clear the value, errors are thrown out as an exception result = apr_env_delete( name.c_str(), aprPool.getAprPool() ); aprPool.cleanup(); if( result != APR_SUCCESS ) { char buffer[256] = {0}; throw NullPointerException( __FILE__, __LINE__, "System::getenv - ", apr_strerror( result, buffer, 255 ) ); } } //////////////////////////////////////////////////////////////////////////////// std::string System::getenv( const std::string& name ) throw ( Exception ) { char* value = NULL; apr_status_t result = APR_SUCCESS; // Read the value, errors are thrown out as an exception result = apr_env_get( &value, name.c_str(), aprPool.getAprPool() ); if( result != APR_SUCCESS ) { char buffer[256] = {0}; throw NullPointerException( __FILE__, __LINE__, "System::getenv - ", apr_strerror( result, buffer, 255 ) ); } // Copy and cleanup if( value == NULL ) { return ""; } std::string envVal( value ); aprPool.cleanup(); return value; } //////////////////////////////////////////////////////////////////////////////// void System::setenv( const std::string& name, const std::string& value ) throw ( lang::Exception ) { apr_status_t result = APR_SUCCESS; // Write the value, errors are thrown out as an exception result = apr_env_set( name.c_str(), value.c_str(), aprPool.getAprPool() ); aprPool.cleanup(); if( result != APR_SUCCESS ) { char buffer[256] = {0}; throw NullPointerException( __FILE__, __LINE__, "System::getenv - ", apr_strerror( result, buffer, 255 ) ); } } //////////////////////////////////////////////////////////////////////////////// long long System::currentTimeMillis() { return Date::getCurrentTimeMilliseconds(); } //////////////////////////////////////////////////////////////////////////////// Map<string, string> System::getenv() throw ( Exception ) { Map<string, string> values; StringTokenizer tokenizer( "" ); string key = ""; string value = ""; int tokens = 0; char** env = getEnvArray(); if( env == NULL ) { throw RuntimeException( __FILE__, __LINE__, "System::getenv - Failed to enumerate the environment." ); } for( int i = 0; *(env + i); i++ ){ tokenizer.reset( env[i], "=" ); delete env[i]; // Clean them as we go tokens = tokenizer.countTokens(); if( tokens == 1 ) { // special case, no value set, store empty string as value key = tokenizer.nextToken(); value = string(""); } else if( tokens > 2 ) { // special case: first equals delimits the key value, the rest are // part of the variable std::string envVal( environ[i] ); int pos = envVal.find( "=" ); key = envVal.substr( 0, pos ); value = envVal.substr( pos + 1, string::npos ); } else if( tokens == 0 ) { // Odd case, got a string with no equals sign. throw IllegalArgumentException( __FILE__, __LINE__, "System::getenv - Invalid env string. %s", environ[i] ); } else { // Normal case. key = tokenizer.nextToken(); value = tokenizer.nextToken(); } // Store the env var values.setValue( key, value ); } // cleanup delete [] env; return values; } #if defined(_WIN32) #include <windows.h> //////////////////////////////////////////////////////////////////////////////// char** System::getEnvArray() { char** buffer = NULL; int count = 0; LPTSTR lpszVars; LPVOID lpvEnv; lpvEnv = GetEnvironmentStrings(); if( NULL == lpvEnv ){ return NULL; } lpszVars = (LPTSTR)lpvEnv; while( *lpszVars != NULL ) { count++; lpszVars += strlen(lpszVars)+1; } // allocate buffer first dimension buffer = new char*[count+1]; buffer[count] = NULL; lpszVars = (LPTSTR)lpvEnv; int index = 0; while( *lpszVars != NULL ) { buffer[++index] = strdup( lpszVars ); lpszVars += strlen(lpszVars)+1; } FreeEnvironmentStrings( (LPTCH)lpvEnv ); return buffer; } #else //////////////////////////////////////////////////////////////////////////////// // Defined here for OSX extern char** environ; //////////////////////////////////////////////////////////////////////////////// char** System::getEnvArray() { char** buffer = NULL; int count = 0; for( int i = 0; *(environ + i); i++ ){ count++; } // allocate buffer first dimension buffer = new char*[count+1]; buffer[count] = NULL; for( int i = 0; *(environ + i); i++ ){ buffer[i] = strdup( environ[i] ); } return buffer; } #endif <|endoftext|>
<commit_before> #include <memory.h> #include <netinet/in.h> #include <util/util.h> extern "C" { #include <libbinpac/libbinpac++.h> } #undef DBG_LOG #include "Pac2Analyzer.h" #include "Plugin.h" #include "Manager.h" #include "LocalReporter.h" #include "profile.h" using namespace bro::hilti; using namespace binpac; using std::shared_ptr; Pac2_Analyzer::Pac2_Analyzer(analyzer::Analyzer* analyzer) { orig.cookie.type = Pac2Cookie::PROTOCOL; orig.cookie.protocol_cookie.analyzer = analyzer; orig.cookie.protocol_cookie.is_orig = true; resp.cookie.type = Pac2Cookie::PROTOCOL; resp.cookie.protocol_cookie.analyzer = analyzer; resp.cookie.protocol_cookie.is_orig = false; } Pac2_Analyzer::~Pac2_Analyzer() { } void Pac2_Analyzer::Init() { orig.parser = 0; orig.data = 0; orig.resume = 0; resp.parser = 0; resp.data = 0; resp.resume = 0; orig.cookie.protocol_cookie.tag = HiltiPlugin.Mgr()->TagForAnalyzer(orig.cookie.protocol_cookie.analyzer->GetAnalyzerTag()); resp.cookie.protocol_cookie.tag = orig.cookie.protocol_cookie.tag; } void Pac2_Analyzer::Done() { GC_DTOR(orig.parser, hlt_BinPACHilti_Parser); GC_DTOR(orig.data, hlt_bytes); GC_DTOR(orig.resume, hlt_exception); GC_DTOR(resp.parser, hlt_BinPACHilti_Parser); GC_DTOR(resp.data, hlt_bytes); GC_DTOR(resp.resume, hlt_exception); Init(); } static inline void debug_msg(analyzer::Analyzer* analyzer, const char* msg, int len, const u_char* data, bool is_orig) { #ifdef DEBUG if ( data ) { PLUGIN_DBG_LOG(HiltiPlugin, "[%s/%lu/%s] %s: |%s|", analyzer->GetAnalyzerName(), analyzer->GetID(), (is_orig ? "orig" : "resp"), msg, fmt_bytes((const char*) data, min(40, len)), len > 40 ? "..." : ""); } else { PLUGIN_DBG_LOG(HiltiPlugin, "[%s/%lu/%s] %s", analyzer->GetAnalyzerName(), analyzer->GetID(), (is_orig ? "orig" : "resp"), msg); } #endif } int Pac2_Analyzer::FeedChunk(int len, const u_char* data, bool is_orig, bool eod) { hlt_execution_context* ctx = hlt_global_execution_context(); hlt_exception* excpt = 0; Endpoint* endp = is_orig ? &orig : &resp; // If parser is set but not data, a previous parsing process has // finished. If so, we ignore all further input. if ( endp->parser && ! endp->data ) { if ( len ) debug_msg(endp->cookie.protocol_cookie.analyzer, "further data ignored", len, data, is_orig); return 0; } if ( ! endp->parser ) { endp->parser = HiltiPlugin.Mgr()->ParserForAnalyzer(endp->cookie.protocol_cookie.analyzer->GetAnalyzerTag(), is_orig); if ( ! endp->parser ) { debug_msg(endp->cookie.protocol_cookie.analyzer, "no unit specificed for parsing", 0, 0, is_orig); return 1; } GC_CCTOR(endp->parser, hlt_BinPACHilti_Parser); } int result = 0; bool done = false; bool error = false; if ( ! endp->data ) { // First chunk. debug_msg(endp->cookie.protocol_cookie.analyzer, "initial chunk", len, data, is_orig); endp->data = hlt_bytes_new_from_data_copy((const int8_t*)data, len, &excpt, ctx); if ( eod ) hlt_bytes_freeze(endp->data, 1, &excpt, ctx); #ifdef BRO_PLUGIN_HAVE_PROFILING profile_update(PROFILE_HILTI_LAND, PROFILE_START); #endif void* pobj = (*endp->parser->parse_func)(endp->data, &endp->cookie, &excpt, ctx); #ifdef BRO_PLUGIN_HAVE_PROFILING profile_update(PROFILE_HILTI_LAND, PROFILE_STOP); #endif GC_DTOR_GENERIC(&pobj, endp->parser->type_info); } else { // Resume parsing. debug_msg(endp->cookie.protocol_cookie.analyzer, "resuming with chunk", len, data, is_orig); assert(endp->data && endp->resume); if ( len ) hlt_bytes_append_raw_copy(endp->data, (int8_t*)data, len, &excpt, ctx); if ( eod ) hlt_bytes_freeze(endp->data, 1, &excpt, ctx); #ifdef BRO_PLUGIN_HAVE_PROFILING profile_update(PROFILE_HILTI_LAND, PROFILE_START); #endif void* pobj = (*endp->parser->resume_func)(endp->resume, &excpt, ctx); #ifdef BRO_PLUGIN_HAVE_PROFILING profile_update(PROFILE_HILTI_LAND, PROFILE_STOP); #endif GC_DTOR_GENERIC(&pobj, endp->parser->type_info); endp->resume = 0; } if ( excpt ) { if ( hlt_exception_is_yield(excpt) ) { debug_msg(endp->cookie.protocol_cookie.analyzer, "parsing yielded", 0, 0, is_orig); endp->resume = excpt; excpt = 0; result = -1; } else { // A parse error. hlt_exception* excpt2 = 0; hlt_string s = hlt_exception_to_string(&hlt_type_info_hlt_exception, &excpt, 0, &excpt2, ctx); char* e = hlt_string_to_native(s, &excpt2, ctx); assert(! excpt2); ParseError(e, is_orig); hlt_free(e); GC_DTOR(s, hlt_string); GC_DTOR(excpt, hlt_exception); excpt = 0; error = true; result = 0; } } else // No exception. { done = true; result = 1; } // TODO: For now we just stop on error, later we might attempt to // restart parsing. if ( eod || done || error ) { GC_DTOR(endp->data, hlt_bytes); endp->data = 0; // Marker that we're done parsing. } return result; } void Pac2_Analyzer::FlipRoles() { Endpoint tmp = orig; orig = resp; resp = tmp; } void Pac2_Analyzer::ParseError(const string& msg, bool is_orig) { Endpoint* endp = is_orig ? &orig : &resp; string s = "parse error: " + msg; debug_msg(endp->cookie.protocol_cookie.analyzer, s.c_str(), 0, 0, is_orig); reporter::weird(endp->cookie.protocol_cookie.analyzer->Conn(), s); } analyzer::Analyzer* Pac2_TCP_Analyzer::InstantiateAnalyzer(Connection* conn) { return new Pac2_TCP_Analyzer(conn); } Pac2_TCP_Analyzer::Pac2_TCP_Analyzer(Connection* conn) : Pac2_Analyzer(this), TCP_ApplicationAnalyzer(conn) { skip_orig = skip_resp = false; } Pac2_TCP_Analyzer::~Pac2_TCP_Analyzer() { } void Pac2_TCP_Analyzer::Init() { TCP_ApplicationAnalyzer::Init(); Pac2_Analyzer::Init(); } void Pac2_TCP_Analyzer::Done() { TCP_ApplicationAnalyzer::Done(); Pac2_Analyzer::Done(); EndOfData(true); EndOfData(false); } void Pac2_TCP_Analyzer::DeliverStream(int len, const u_char* data, bool is_orig) { TCP_ApplicationAnalyzer::DeliverStream(len, data, is_orig); if ( is_orig && skip_orig ) return; if ( (! is_orig) && skip_resp ) return; if ( TCP() && TCP()->IsPartial() ) return; int rc = FeedChunk(len, data, is_orig, false); if ( rc >= 0 ) { if ( is_orig ) { debug_msg(this, ::util::fmt("parsing %s, skipping further originator payload", (rc > 0 ? "finished" : "failed")).c_str(), 0, 0, is_orig); skip_orig = 1; } else { debug_msg(this, ::util::fmt("parsing %s, skipping further responder payload", (rc > 0 ? "finished" : "failed")).c_str(), 0, 0, is_orig); skip_resp = 1; } if ( skip_orig && skip_resp ) { debug_msg(this, "both endpoints finished, skipping all further TCP processing", 0, 0, is_orig); SetSkip(1); } } } void Pac2_TCP_Analyzer::Undelivered(uint64 seq, int len, bool is_orig) { TCP_ApplicationAnalyzer::Undelivered(seq, len, is_orig); // This mimics the (modified) Bro HTTP analyzer. // Otherwise stop parsing the connection if ( is_orig ) { debug_msg(this, "undelivered data, skipping further originator payload", 0, 0, is_orig); skip_orig = 1; } else { debug_msg(this, "undelivered data, skipping further originator payload", 0, 0, is_orig); skip_resp = 1; } } void Pac2_TCP_Analyzer::EndOfData(bool is_orig) { TCP_ApplicationAnalyzer::EndOfData(is_orig); if ( is_orig && skip_orig ) return; if ( (! is_orig) && skip_resp ) return; if ( TCP() && TCP()->IsPartial() ) return; FeedChunk(0, (const u_char*)"", is_orig, true); } void Pac2_TCP_Analyzer::FlipRoles() { TCP_ApplicationAnalyzer::FlipRoles(); Pac2_Analyzer::FlipRoles(); } void Pac2_TCP_Analyzer::EndpointEOF(bool is_orig) { TCP_ApplicationAnalyzer::EndpointEOF(is_orig); //FeedChunk(0, (const u_char*)"", is_orig, true); } void Pac2_TCP_Analyzer::ConnectionClosed(analyzer::tcp::TCP_Endpoint* endpoint, analyzer::tcp::TCP_Endpoint* peer, int gen_event) { TCP_ApplicationAnalyzer::ConnectionClosed(endpoint, peer, gen_event); } void Pac2_TCP_Analyzer::ConnectionFinished(int half_finished) { TCP_ApplicationAnalyzer::ConnectionFinished(half_finished); } void Pac2_TCP_Analyzer::ConnectionReset() { TCP_ApplicationAnalyzer::ConnectionReset(); } void Pac2_TCP_Analyzer::PacketWithRST() { TCP_ApplicationAnalyzer::PacketWithRST(); } analyzer::Analyzer* Pac2_UDP_Analyzer::InstantiateAnalyzer(Connection* conn) { return new Pac2_UDP_Analyzer(conn); } Pac2_UDP_Analyzer::Pac2_UDP_Analyzer(Connection* conn) : Pac2_Analyzer(this), Analyzer(conn) { } Pac2_UDP_Analyzer::~Pac2_UDP_Analyzer() { } void Pac2_UDP_Analyzer::Init() { Analyzer::Init(); Pac2_Analyzer::Init(); } void Pac2_UDP_Analyzer::Done() { Analyzer::Done(); Pac2_Analyzer::Done(); } void Pac2_UDP_Analyzer::DeliverPacket(int len, const u_char* data, bool is_orig, uint64 seq, const IP_Hdr* ip, int caplen) { Analyzer::DeliverPacket(len, data, is_orig, seq, ip, caplen); FeedChunk(len, data, is_orig, true); Pac2_Analyzer::Done(); } void Pac2_UDP_Analyzer::Undelivered(uint64 seq, int len, bool is_orig) { Analyzer::Undelivered(seq, len, is_orig); } void Pac2_UDP_Analyzer::EndOfData(bool is_orig) { Analyzer::EndOfData(is_orig); } void Pac2_UDP_Analyzer::FlipRoles() { Analyzer::FlipRoles(); } <commit_msg>Compile fix.<commit_after> #include <memory.h> #include <netinet/in.h> #include <util/util.h> extern "C" { #include <libbinpac/libbinpac++.h> } #undef DBG_LOG #include "Pac2Analyzer.h" #include "Plugin.h" #include "Manager.h" #include "LocalReporter.h" using namespace bro::hilti; using namespace binpac; using std::shared_ptr; Pac2_Analyzer::Pac2_Analyzer(analyzer::Analyzer* analyzer) { orig.cookie.type = Pac2Cookie::PROTOCOL; orig.cookie.protocol_cookie.analyzer = analyzer; orig.cookie.protocol_cookie.is_orig = true; resp.cookie.type = Pac2Cookie::PROTOCOL; resp.cookie.protocol_cookie.analyzer = analyzer; resp.cookie.protocol_cookie.is_orig = false; } Pac2_Analyzer::~Pac2_Analyzer() { } void Pac2_Analyzer::Init() { orig.parser = 0; orig.data = 0; orig.resume = 0; resp.parser = 0; resp.data = 0; resp.resume = 0; orig.cookie.protocol_cookie.tag = HiltiPlugin.Mgr()->TagForAnalyzer(orig.cookie.protocol_cookie.analyzer->GetAnalyzerTag()); resp.cookie.protocol_cookie.tag = orig.cookie.protocol_cookie.tag; } void Pac2_Analyzer::Done() { GC_DTOR(orig.parser, hlt_BinPACHilti_Parser); GC_DTOR(orig.data, hlt_bytes); GC_DTOR(orig.resume, hlt_exception); GC_DTOR(resp.parser, hlt_BinPACHilti_Parser); GC_DTOR(resp.data, hlt_bytes); GC_DTOR(resp.resume, hlt_exception); Init(); } static inline void debug_msg(analyzer::Analyzer* analyzer, const char* msg, int len, const u_char* data, bool is_orig) { #ifdef DEBUG if ( data ) { PLUGIN_DBG_LOG(HiltiPlugin, "[%s/%lu/%s] %s: |%s|", analyzer->GetAnalyzerName(), analyzer->GetID(), (is_orig ? "orig" : "resp"), msg, fmt_bytes((const char*) data, min(40, len)), len > 40 ? "..." : ""); } else { PLUGIN_DBG_LOG(HiltiPlugin, "[%s/%lu/%s] %s", analyzer->GetAnalyzerName(), analyzer->GetID(), (is_orig ? "orig" : "resp"), msg); } #endif } int Pac2_Analyzer::FeedChunk(int len, const u_char* data, bool is_orig, bool eod) { hlt_execution_context* ctx = hlt_global_execution_context(); hlt_exception* excpt = 0; Endpoint* endp = is_orig ? &orig : &resp; // If parser is set but not data, a previous parsing process has // finished. If so, we ignore all further input. if ( endp->parser && ! endp->data ) { if ( len ) debug_msg(endp->cookie.protocol_cookie.analyzer, "further data ignored", len, data, is_orig); return 0; } if ( ! endp->parser ) { endp->parser = HiltiPlugin.Mgr()->ParserForAnalyzer(endp->cookie.protocol_cookie.analyzer->GetAnalyzerTag(), is_orig); if ( ! endp->parser ) { debug_msg(endp->cookie.protocol_cookie.analyzer, "no unit specificed for parsing", 0, 0, is_orig); return 1; } GC_CCTOR(endp->parser, hlt_BinPACHilti_Parser); } int result = 0; bool done = false; bool error = false; if ( ! endp->data ) { // First chunk. debug_msg(endp->cookie.protocol_cookie.analyzer, "initial chunk", len, data, is_orig); endp->data = hlt_bytes_new_from_data_copy((const int8_t*)data, len, &excpt, ctx); if ( eod ) hlt_bytes_freeze(endp->data, 1, &excpt, ctx); #ifdef BRO_PLUGIN_HAVE_PROFILING profile_update(PROFILE_HILTI_LAND, PROFILE_START); #endif void* pobj = (*endp->parser->parse_func)(endp->data, &endp->cookie, &excpt, ctx); #ifdef BRO_PLUGIN_HAVE_PROFILING profile_update(PROFILE_HILTI_LAND, PROFILE_STOP); #endif GC_DTOR_GENERIC(&pobj, endp->parser->type_info); } else { // Resume parsing. debug_msg(endp->cookie.protocol_cookie.analyzer, "resuming with chunk", len, data, is_orig); assert(endp->data && endp->resume); if ( len ) hlt_bytes_append_raw_copy(endp->data, (int8_t*)data, len, &excpt, ctx); if ( eod ) hlt_bytes_freeze(endp->data, 1, &excpt, ctx); #ifdef BRO_PLUGIN_HAVE_PROFILING profile_update(PROFILE_HILTI_LAND, PROFILE_START); #endif void* pobj = (*endp->parser->resume_func)(endp->resume, &excpt, ctx); #ifdef BRO_PLUGIN_HAVE_PROFILING profile_update(PROFILE_HILTI_LAND, PROFILE_STOP); #endif GC_DTOR_GENERIC(&pobj, endp->parser->type_info); endp->resume = 0; } if ( excpt ) { if ( hlt_exception_is_yield(excpt) ) { debug_msg(endp->cookie.protocol_cookie.analyzer, "parsing yielded", 0, 0, is_orig); endp->resume = excpt; excpt = 0; result = -1; } else { // A parse error. hlt_exception* excpt2 = 0; hlt_string s = hlt_exception_to_string(&hlt_type_info_hlt_exception, &excpt, 0, &excpt2, ctx); char* e = hlt_string_to_native(s, &excpt2, ctx); assert(! excpt2); ParseError(e, is_orig); hlt_free(e); GC_DTOR(s, hlt_string); GC_DTOR(excpt, hlt_exception); excpt = 0; error = true; result = 0; } } else // No exception. { done = true; result = 1; } // TODO: For now we just stop on error, later we might attempt to // restart parsing. if ( eod || done || error ) { GC_DTOR(endp->data, hlt_bytes); endp->data = 0; // Marker that we're done parsing. } return result; } void Pac2_Analyzer::FlipRoles() { Endpoint tmp = orig; orig = resp; resp = tmp; } void Pac2_Analyzer::ParseError(const string& msg, bool is_orig) { Endpoint* endp = is_orig ? &orig : &resp; string s = "parse error: " + msg; debug_msg(endp->cookie.protocol_cookie.analyzer, s.c_str(), 0, 0, is_orig); reporter::weird(endp->cookie.protocol_cookie.analyzer->Conn(), s); } analyzer::Analyzer* Pac2_TCP_Analyzer::InstantiateAnalyzer(Connection* conn) { return new Pac2_TCP_Analyzer(conn); } Pac2_TCP_Analyzer::Pac2_TCP_Analyzer(Connection* conn) : Pac2_Analyzer(this), TCP_ApplicationAnalyzer(conn) { skip_orig = skip_resp = false; } Pac2_TCP_Analyzer::~Pac2_TCP_Analyzer() { } void Pac2_TCP_Analyzer::Init() { TCP_ApplicationAnalyzer::Init(); Pac2_Analyzer::Init(); } void Pac2_TCP_Analyzer::Done() { TCP_ApplicationAnalyzer::Done(); Pac2_Analyzer::Done(); EndOfData(true); EndOfData(false); } void Pac2_TCP_Analyzer::DeliverStream(int len, const u_char* data, bool is_orig) { TCP_ApplicationAnalyzer::DeliverStream(len, data, is_orig); if ( is_orig && skip_orig ) return; if ( (! is_orig) && skip_resp ) return; if ( TCP() && TCP()->IsPartial() ) return; int rc = FeedChunk(len, data, is_orig, false); if ( rc >= 0 ) { if ( is_orig ) { debug_msg(this, ::util::fmt("parsing %s, skipping further originator payload", (rc > 0 ? "finished" : "failed")).c_str(), 0, 0, is_orig); skip_orig = 1; } else { debug_msg(this, ::util::fmt("parsing %s, skipping further responder payload", (rc > 0 ? "finished" : "failed")).c_str(), 0, 0, is_orig); skip_resp = 1; } if ( skip_orig && skip_resp ) { debug_msg(this, "both endpoints finished, skipping all further TCP processing", 0, 0, is_orig); SetSkip(1); } } } void Pac2_TCP_Analyzer::Undelivered(uint64 seq, int len, bool is_orig) { TCP_ApplicationAnalyzer::Undelivered(seq, len, is_orig); // This mimics the (modified) Bro HTTP analyzer. // Otherwise stop parsing the connection if ( is_orig ) { debug_msg(this, "undelivered data, skipping further originator payload", 0, 0, is_orig); skip_orig = 1; } else { debug_msg(this, "undelivered data, skipping further originator payload", 0, 0, is_orig); skip_resp = 1; } } void Pac2_TCP_Analyzer::EndOfData(bool is_orig) { TCP_ApplicationAnalyzer::EndOfData(is_orig); if ( is_orig && skip_orig ) return; if ( (! is_orig) && skip_resp ) return; if ( TCP() && TCP()->IsPartial() ) return; FeedChunk(0, (const u_char*)"", is_orig, true); } void Pac2_TCP_Analyzer::FlipRoles() { TCP_ApplicationAnalyzer::FlipRoles(); Pac2_Analyzer::FlipRoles(); } void Pac2_TCP_Analyzer::EndpointEOF(bool is_orig) { TCP_ApplicationAnalyzer::EndpointEOF(is_orig); //FeedChunk(0, (const u_char*)"", is_orig, true); } void Pac2_TCP_Analyzer::ConnectionClosed(analyzer::tcp::TCP_Endpoint* endpoint, analyzer::tcp::TCP_Endpoint* peer, int gen_event) { TCP_ApplicationAnalyzer::ConnectionClosed(endpoint, peer, gen_event); } void Pac2_TCP_Analyzer::ConnectionFinished(int half_finished) { TCP_ApplicationAnalyzer::ConnectionFinished(half_finished); } void Pac2_TCP_Analyzer::ConnectionReset() { TCP_ApplicationAnalyzer::ConnectionReset(); } void Pac2_TCP_Analyzer::PacketWithRST() { TCP_ApplicationAnalyzer::PacketWithRST(); } analyzer::Analyzer* Pac2_UDP_Analyzer::InstantiateAnalyzer(Connection* conn) { return new Pac2_UDP_Analyzer(conn); } Pac2_UDP_Analyzer::Pac2_UDP_Analyzer(Connection* conn) : Pac2_Analyzer(this), Analyzer(conn) { } Pac2_UDP_Analyzer::~Pac2_UDP_Analyzer() { } void Pac2_UDP_Analyzer::Init() { Analyzer::Init(); Pac2_Analyzer::Init(); } void Pac2_UDP_Analyzer::Done() { Analyzer::Done(); Pac2_Analyzer::Done(); } void Pac2_UDP_Analyzer::DeliverPacket(int len, const u_char* data, bool is_orig, uint64 seq, const IP_Hdr* ip, int caplen) { Analyzer::DeliverPacket(len, data, is_orig, seq, ip, caplen); FeedChunk(len, data, is_orig, true); Pac2_Analyzer::Done(); } void Pac2_UDP_Analyzer::Undelivered(uint64 seq, int len, bool is_orig) { Analyzer::Undelivered(seq, len, is_orig); } void Pac2_UDP_Analyzer::EndOfData(bool is_orig) { Analyzer::EndOfData(is_orig); } void Pac2_UDP_Analyzer::FlipRoles() { Analyzer::FlipRoles(); } <|endoftext|>
<commit_before>#pragma once #include <vector> #include <memory> #include <utility> #include <functional> #include "Indexer.hpp" namespace Core { template <typename Key, typename Object, class IndexerClass> class VectorIndexer { public: using IndexerType = IndexerClass; using VectorType = std::vector<Object>; VectorIndexer() : _vector(), _indexer() {} Object& Add(const Key& key, Object&& object) { return Add(key, object); } Object& Add(const Key& key, Object& object) { uint idx = _vector.size(); _indexer.Add(key, idx); _vector.push_back(object); return _vector[idx]; } const Object& Add(const Key& key, const Object& object) { return Add(key, const_cast<Object&>(object)); } const Object& Get(unsigned int index) const { return _vector[index]; } Object& Get(unsigned int index) { return const_cast<Object&>(static_cast<const VectorIndexer<Key, Object, IndexerType>*>(this)->Get(index)); } const Object* Find(const Key& key) const { uint findIndex = _indexer.Find(key); bool isFound = findIndex != decltype(_indexer)::FailIndex(); return isFound ? &Get(findIndex) : nullptr; } Object* Find(const Key& key) { return const_cast<Object*>(static_cast<const VectorIndexer<Key, Object, IndexerType>*>(this)->Find(key)); } bool Has(const Key& key) const { return _indexer.Has(key); } void Delete(const Key& key) { uint findIdx = _indexer.Find(key); if (findIdx == IndexerType::FailIndex()) return; uint ereaseIdx = findIdx; _vector.erase(_vector.begin() + ereaseIdx); _indexer.Delete(key); } void DeleteAll() { _vector.clear(); _indexer.DeleteAll(); } GET_CONST_ACCESSOR(Vector, const auto&, _vector); GET_CONST_ACCESSOR(Indexer, const auto&, _indexer); GET_CONST_ACCESSOR(Size, unsigned int, _vector.size()); private: std::vector<Object> _vector; IndexerType _indexer; }; template<typename Key, typename Object> using VectorMap = VectorIndexer<Key, Object, IndexMap<Key>>; template<typename Key, typename Object> using VectorHashMap = VectorIndexer<Key, Object, IndexHashMap<Key>>; } <commit_msg>VectorIndexer - Iterate 구현<commit_after>#pragma once #include <vector> #include <memory> #include <utility> #include <functional> #include "Indexer.hpp" namespace Core { template <typename Key, typename Object, class IndexerClass> class VectorIndexer { public: using IndexerType = IndexerClass; using VectorType = std::vector<Object>; VectorIndexer() : _vector(), _indexer() {} Object& Add(const Key& key, Object&& object) { return Add(key, object); } Object& Add(const Key& key, Object& object) { uint idx = _vector.size(); _indexer.Add(key, idx); _vector.push_back(object); return _vector[idx]; } const Object& Add(const Key& key, const Object& object) { return Add(key, const_cast<Object&>(object)); } const Object& Get(unsigned int index) const { return _vector[index]; } Object& Get(unsigned int index) { return const_cast<Object&>(static_cast<const VectorIndexer<Key, Object, IndexerType>*>(this)->Get(index)); } const Object* Find(const Key& key) const { uint findIndex = _indexer.Find(key); bool isFound = findIndex != decltype(_indexer)::FailIndex(); return isFound ? &Get(findIndex) : nullptr; } Object* Find(const Key& key) { return const_cast<Object*>(static_cast<const VectorIndexer<Key, Object, IndexerType>*>(this)->Find(key)); } bool Has(const Key& key) const { return _indexer.Has(key); } void Delete(const Key& key) { uint findIdx = _indexer.Find(key); if (findIdx == IndexerType::FailIndex()) return; uint ereaseIdx = findIdx; _vector.erase(_vector.begin() + ereaseIdx); _indexer.Delete(key); } void DeleteAll() { _vector.clear(); _indexer.DeleteAll(); } GET_CONST_ACCESSOR(Vector, const auto&, _vector); GET_CONST_ACCESSOR(Indexer, const auto&, _indexer); GET_CONST_ACCESSOR(Size, unsigned int, _vector.size()); template <class Iterator> void Iterate(Iterator iterator) { for (auto& iter : _vector) iterator(iter); } private: std::vector<Object> _vector; IndexerType _indexer; }; template<typename Key, typename Object> using VectorMap = VectorIndexer<Key, Object, IndexMap<Key>>; template<typename Key, typename Object> using VectorHashMap = VectorIndexer<Key, Object, IndexHashMap<Key>>; } <|endoftext|>
<commit_before>#include "estimator/dcm_attitude_estimator.hpp" #include "protocol/messages.hpp" #include "unit_config.hpp" DCMAttitudeEstimator::DCMAttitudeEstimator(Communicator& communicator) : dcm(Eigen::Matrix3f::Identity()), attitudeMessageStream(communicator, 20) { } attitude_estimate_t DCMAttitudeEstimator::update(const sensor_reading_group_t& readings) { Eigen::Vector3f corr = Eigen::Vector3f::Zero(); float accelWeight = 0.0f; float magWeight = 0.0f; // If an accelerometer is available, use the provided gravity vector to // correct for drift in the DCM. if(readings.accel) { Eigen::Vector3f accel((*readings.accel).axes.data()); // Calculate accelerometer weight before normalization accelWeight = getAccelWeight(accel); accel.normalize(); corr += dcm.col(2).cross(-accel) * accelWeight; } // If a magnetometer is available, use the provided north vector to correct // the yaw. if(readings.mag) { Eigen::Vector3f mag((*readings.mag).axes.data()); // TODO: Calculate mag weight? magWeight = 0.001f; // "Project" the magnetometer into the global xy plane. Eigen::Vector3f magGlobal = dcm.transpose() * mag; magGlobal(2) = 0.0f; // Convert back to body coordinates. Eigen::Vector3f magBody = dcm * magGlobal; // Normalize because we only care about the prevailing direction. magBody.normalize(); corr += dcm.col(0).cross(magBody - dcm.col(0)) * magWeight; } // If a gyroscope is available, integrate the provided rotational velocity and // add it to the correction vector. if(readings.gyro) { Eigen::Vector3f gyro((*readings.gyro).axes.data()); corr += gyro * unit_config::DT * (1.0f - accelWeight - magWeight); } // Use small angle approximations to build a rotation matrix modelling the // attitude change over the time step. Eigen::Matrix3f dcmStep; dcmStep << 1.0f, corr.z(), -corr.y(), -corr.z(), 1.0f, corr.x(), corr.y(), -corr.x(), 1.0f; // Rotate the DCM. dcm = dcmStep * dcm; orthonormalize(); updateStream(); return makeEstimate(readings); } void DCMAttitudeEstimator::orthonormalize() { // Make the i and j vectors orthogonal float error = dcm.row(0).dot(dcm.row(1)); Eigen::Matrix3f corr = Eigen::Matrix3f::Zero(); corr.row(0) = dcm.row(1) * (-error) / 2; corr.row(1) = dcm.row(0) * (-error) / 2; dcm.row(0) += corr.row(0); dcm.row(1) += corr.row(1); // Estimate k vector from corrected i and j vectors dcm.row(2) = dcm.row(0).cross(dcm.row(1)); // Normalize all vectors dcm.rowwise().normalize(); } float DCMAttitudeEstimator::getAccelWeight(Eigen::Vector3f accel) const { // TODO(kyle): Pull these out as parameters float maxAccelWeight = 0.005f; // Accelerometer weight at exactly 1g float validAccelRange = 0.5f; // Maximum additional acceleration until accelWeight goes to 0 // Deweight accelerometer as a linear function of the reading's difference // from 1g. float accelOffset = std::abs(1.0f - accel.norm()); float accelWeight = -maxAccelWeight / validAccelRange * accelOffset + maxAccelWeight; // Limit weight to a minimum of 0 accelWeight = std::max(0.0f, accelWeight); return accelWeight; } void DCMAttitudeEstimator::updateStream() { if(attitudeMessageStream.ready()) { protocol::message::attitude_message_t m { .dcm = { // estimate.roll, estimate.pitch, estimate.yaw, // accel(0), accel(1), accel(2), // NOTE: normalized // gyro(0), gyro(1), gyro(2), dcm(0, 0), dcm(0, 1), dcm(0, 2), dcm(1, 0), dcm(1, 1), dcm(1, 2), dcm(2, 0), dcm(2, 1), dcm(2, 2) } }; attitudeMessageStream.publish(m); } } <commit_msg>Clean up attitude estimator.<commit_after>#include "estimator/dcm_attitude_estimator.hpp" #include "protocol/messages.hpp" #include "unit_config.hpp" DCMAttitudeEstimator::DCMAttitudeEstimator(Communicator& communicator) : dcm(Eigen::Matrix3f::Identity()), attitudeMessageStream(communicator, 20) { } attitude_estimate_t DCMAttitudeEstimator::update(const sensor_reading_group_t& readings) { Eigen::Vector3f corr = Eigen::Vector3f::Zero(); float accelWeight = 0.0f; float magWeight = 0.0f; // If an accelerometer is available, use the provided gravity vector to // correct for drift in the DCM. if(readings.accel) { Eigen::Vector3f accel((*readings.accel).axes.data()); // Calculate accelerometer weight before normalization accelWeight = getAccelWeight(accel); accel.normalize(); corr += dcm.col(2).cross(-accel) * accelWeight; } // If a magnetometer is available, use the provided north vector to correct // the yaw. if(readings.mag) { Eigen::Vector3f mag((*readings.mag).axes.data()); // TODO: Calculate mag weight? magWeight = 0.001f; // "Project" the magnetometer into the global xy plane. Eigen::Vector3f magGlobal = dcm.transpose() * mag; magGlobal(2) = 0.0f; // Convert back to body coordinates. Eigen::Vector3f magBody = dcm * magGlobal; // Normalize because we only care about the prevailing direction. magBody.normalize(); corr += dcm.col(0).cross(magBody - dcm.col(0)) * magWeight; } // If a gyroscope is available, integrate the provided rotational velocity and // add it to the correction vector. if(readings.gyro) { Eigen::Vector3f gyro((*readings.gyro).axes.data()); corr += gyro * unit_config::DT * (1.0f - accelWeight - magWeight); } // Use small angle approximations to build a rotation matrix modelling the // attitude change over the time step. Eigen::Matrix3f dcmStep; dcmStep << 1.0f, corr.z(), -corr.y(), -corr.z(), 1.0f, corr.x(), corr.y(), -corr.x(), 1.0f; // Rotate the DCM. dcm = dcmStep * dcm; orthonormalize(); updateStream(); return makeEstimate(readings); } void DCMAttitudeEstimator::orthonormalize() { // Make the i and j vectors orthogonal float error = dcm.row(0).dot(dcm.row(1)); Eigen::Matrix3f corr = Eigen::Matrix3f::Zero(); corr.row(0) = dcm.row(1) * (-error) / 2; corr.row(1) = dcm.row(0) * (-error) / 2; dcm.row(0) += corr.row(0); dcm.row(1) += corr.row(1); // Estimate k vector from corrected i and j vectors dcm.row(2) = dcm.row(0).cross(dcm.row(1)); // Normalize all vectors dcm.rowwise().normalize(); } float DCMAttitudeEstimator::getAccelWeight(Eigen::Vector3f accel) const { // TODO(kyle): Pull these out as parameters float maxAccelWeight = 0.005f; // Accelerometer weight at exactly 1g float validAccelRange = 0.5f; // Maximum additional acceleration until accelWeight goes to 0 // Deweight accelerometer as a linear function of the reading's difference // from 1g. float accelOffset = std::abs(1.0f - accel.norm()); float accelWeight = -maxAccelWeight / validAccelRange * accelOffset + maxAccelWeight; // Limit weight to a minimum of 0 accelWeight = std::max(0.0f, accelWeight); return accelWeight; } attitude_estimate_t DCMAttitudeEstimator::makeEstimate(const sensor_reading_group_t& readings) { attitude_estimate_t estimate = { // TODO: Are these trig functions safe at extreme angles? .roll = -atan2f(dcm(2, 1), dcm(2, 2)) * dcm(0, 0) + atan2f(dcm(2, 0), dcm(2, 2)) * dcm(0, 1), .pitch = atan2f(dcm(2, 0), dcm(2, 2)) * dcm(1, 1) - atan2f(dcm(2, 1), dcm(2, 2)) * dcm(1, 0), .yaw = 0.0f, // atan2f(dcm(1, 1), dcm(0, 1)), .roll_vel = 0.0f, .pitch_vel = 0.0f, .yaw_vel = 0.0f }; // If a gyro is available then use the direct readings for velocity // calculation. if(readings.gyro) { estimate.roll_vel = (*readings.gyro).axes[0]; estimate.pitch_vel = (*readings.gyro).axes[1]; estimate.yaw_vel = (*readings.gyro).axes[2]; } else { // TODO: Differentiate estimates or just ignore? } return estimate; } void DCMAttitudeEstimator::updateStream() { if(attitudeMessageStream.ready()) { protocol::message::attitude_message_t m { .dcm = { dcm(0, 0), dcm(0, 1), dcm(0, 2), dcm(1, 0), dcm(1, 1), dcm(1, 2), dcm(2, 0), dcm(2, 1), dcm(2, 2) } }; attitudeMessageStream.publish(m); } } <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2007 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include "common.h" /* system headers */ #include <iostream> #include <string> #include <vector> #include <map> /* common headers */ #include "bzfio.h" #include "version.h" #include "TextUtils.h" #include "commands.h" #include "bzfsAPI.h" #include "DirectoryNames.h" #include "OSFile.h" #ifdef _WIN32 std::string extension = ".dll"; std::string globalPluginDir = ".\\plugins\\"; #else std::string extension = ".so"; std::string globalPluginDir = "$(prefix)/lib/bzflag/"; #endif typedef std::map<std::string, bz_APIPluginHandler*> tmCustomPluginMap; tmCustomPluginMap customPluginMap; typedef struct { std::string foundPath; std::string plugin; #ifdef _WIN32 HINSTANCE handle; #else void* handle; #endif }trPluginRecord; std::vector<trPluginRecord> vPluginList; typedef enum { eLoadFailedDupe = -1, eLoadFailedError = 0, eLoadComplete }PluginLoadReturn; bool pluginExists ( std::string plugin ) { for ( int i = 0; i < (int)vPluginList.size(); i++ ) { if ( vPluginList[i].foundPath == plugin ) return true; } return false; } std::string findPlugin ( std::string pluginName ) { // see if we can just open the bloody thing FILE *fp = fopen(pluginName.c_str(),"rb"); if (fp) { fclose(fp); return pluginName; } // now try it with the standard extension std::string name = pluginName + extension; fp = fopen(name.c_str(),"rb"); if (fp) { fclose(fp); return name; } // check the local users plugins dir name = getConfigDirName(BZ_CONFIG_DIR_VERSION) + pluginName + extension; fp = fopen(name.c_str(),"rb"); if (fp) { fclose(fp); return name; } // check the global plugins dir name = globalPluginDir + pluginName + extension; fp = fopen(name.c_str(),"rb"); if (fp) { fclose(fp); return name; } return std::string(""); } void unload1Plugin ( int iPluginID ); #ifdef _WIN32 # include <windows.h> int getPluginVersion ( HINSTANCE hLib ) { int (*lpProc)(void); lpProc = (int (__cdecl *)(void))GetProcAddress(hLib, "bz_GetVersion"); if (lpProc) return lpProc(); return 0; } PluginLoadReturn load1Plugin ( std::string plugin, std::string config ) { int (*lpProc)(const char*); std::string realPluginName = findPlugin(plugin); if (pluginExists(realPluginName)) { logDebugMessage(1,"LoadPlugin fialed:%s is already loaded\n",realPluginName.c_str()); return eLoadFailedDupe; } HINSTANCE hLib = LoadLibrary(realPluginName.c_str()); if (hLib) { if (getPluginVersion(hLib) > BZ_API_VERSION) { logDebugMessage(1,"Plugin:%s found but expects an newer API version (%d), upgrade your bzfs\n",plugin.c_str(),getPluginVersion(hLib)); FreeLibrary(hLib); return eLoadFailedError; } else { lpProc = (int (__cdecl *)(const char*))GetProcAddress(hLib, "bz_Load"); if (lpProc) { lpProc(config.c_str()); logDebugMessage(1,"Plugin:%s loaded\n",plugin.c_str()); trPluginRecord pluginRecord; pluginRecord.foundPath = realPluginName; pluginRecord.handle = hLib; pluginRecord.plugin = plugin; vPluginList.push_back(pluginRecord); } else { logDebugMessage(1,"Plugin:%s found but does not contain bz_Load method\n",plugin.c_str()); FreeLibrary(hLib); return eLoadFailedError; } } } else { logDebugMessage(1,"Plugin:%s not found\n",plugin.c_str()); return eLoadFailedError; } return eLoadComplete; } void unload1Plugin ( int iPluginID ) { int (*lpProc)(void); trPluginRecord &plugin = vPluginList[iPluginID]; if (!plugin.handle) return; lpProc = (int (__cdecl *)(void))GetProcAddress(plugin.handle, "bz_Unload"); if (lpProc) lpProc(); else logDebugMessage(1,"Plugin does not contain bz_UnLoad method\n"); FreeLibrary(plugin.handle); plugin.handle = NULL; plugin.foundPath = ""; plugin.plugin = ""; } #else # include <dlfcn.h> std::vector<void*> vLibHandles; int getPluginVersion ( void* hLib ) { int (*lpProc)(void); lpProc = force_cast<int (*)(void)>(dlsym(hLib,"bz_GetVersion")); if (lpProc) return (*lpProc)(); return 0; } PluginLoadReturn load1Plugin ( std::string plugin, std::string config ) { int (*lpProc)(const char*); std::string realPluginName = findPlugin(plugin); if (pluginExists(realPluginName)) { logDebugMessage(1,"LoadPlugin fialed:%s is already loaded\n",realPluginName.c_str()); return eLoadFailedDupe; } void *hLib = dlopen(realPluginName.c_str(), RTLD_LAZY | RTLD_GLOBAL); if (hLib) { if (dlsym(hLib, "bz_Load") == NULL) { logDebugMessage(1,"Plugin:%s found but does not contain bz_Load method, error %s\n",plugin.c_str(),dlerror()); dlclose(hLib); return eLoadFailedError; } int version = getPluginVersion(hLib); if (version < BZ_API_VERSION) { logDebugMessage(1,"Plugin:%s found but expects an older API version (%d), upgrade it\n", plugin.c_str(), version); dlclose(hLib); return eLoadFailedError; } else { lpProc = force_cast<int (*)(const char*)>(dlsym(hLib,"bz_Load")); if (lpProc) { (*lpProc)(config.c_str()); logDebugMessage(1,"Plugin:%s loaded\n",plugin.c_str()); trPluginRecord pluginRecord; pluginRecord.handle = hLib; pluginRecord.plugin = plugin; vPluginList.push_back(pluginRecord); return eLoadComplete; } } } else { logDebugMessage(1,"Plugin:%s not found, error %s\n",plugin.c_str(), dlerror()); return eLoadFailedError; } logDebugMessage(1,"If you see this, there is something terribly wrong.\n"); return eLoadFailedError; } void unload1Plugin ( int iPluginID ) { int (*lpProc)(void); trPluginRecord &plugin = vPluginList[iPluginID]; if(!plugin.handle) return; lpProc = force_cast<int (*)(void)>(dlsym(plugin.handle, "bz_Unload")); if (lpProc) (*lpProc)(); else logDebugMessage(1,"Plugin does not contain bz_UnLoad method, error %s\n",dlerror()); dlclose(plugin.handle); plugin.handle = NULL; plugin.foundPath = ""; plugin.plugin = ""; } #endif bool loadPlugin ( std::string plugin, std::string config ) { // check and see if it's an extension we have a handler for std::string ext; std::vector<std::string> parts = TextUtils::tokenize(plugin,std::string(".")); ext = parts[parts.size()-1]; tmCustomPluginMap::iterator itr = customPluginMap.find(TextUtils::tolower(ext)); if (itr != customPluginMap.end() && itr->second) { bz_APIPluginHandler *handler = itr->second; return handler->handle(plugin,config); } else return load1Plugin(plugin,config) == eLoadComplete; } bool unloadPlugin ( std::string plugin ) { // unload the first one of the name we find for (unsigned int i = 0; i < vPluginList.size();i++) { if ( vPluginList[i].plugin == plugin ) { unload1Plugin(i); vPluginList.erase(vPluginList.begin()+i); return true; } } return false; } void unloadPlugins ( void ) { for (unsigned int i = 0; i < vPluginList.size();i++) unload1Plugin(i); vPluginList.clear(); removeCustomSlashCommand("loadplugin"); removeCustomSlashCommand("unloadplugin"); removeCustomSlashCommand("listplugins"); } std::vector<std::string> getPluginList ( void ) { std::vector<std::string> plugins; for (unsigned int i = 0; i < vPluginList.size();i++) plugins.push_back(vPluginList[i].plugin); return plugins; } void parseServerCommand(const char *message, int dstPlayerId); class DynamicPluginCommands : public bz_CustomSlashCommandHandler { public: virtual ~DynamicPluginCommands(){}; virtual bool handle ( int playerID, bz_ApiString _command, bz_ApiString _message, bz_APIStringList *params ) { bz_BasePlayerRecord record; std::string command = _command.c_str(); std::string message = _message.c_str(); bz_BasePlayerRecord *p = bz_getPlayerByIndex(playerID); if (!p) return false; record = *p; bz_freePlayerRecord(p); // list needs listPlugins permission if ( TextUtils::tolower(command) == "listplugins" ) { if (!bz_hasPerm(playerID, "listPlugins")) { bz_sendTextMessage(BZ_SERVER,playerID,"You do not have permission to run the /listplugins command"); return true; } else { std::vector<std::string> plugins = getPluginList(); if (!plugins.size()) bz_sendTextMessage(BZ_SERVER,playerID,"No Plug-ins loaded."); else { bz_sendTextMessage(BZ_SERVER,playerID,"Plug-ins loaded:"); for ( unsigned int i = 0; i < plugins.size(); i++) bz_sendTextMessage(BZ_SERVER,playerID,plugins[i].c_str()); } } return true; } if ( !record.admin ) { bz_sendTextMessage(BZ_SERVER,playerID,"You do not have permission to (un)load plug-ins."); return true; } if ( TextUtils::tolower(command) == "loadplugin" ) { if ( !params->size() ) { bz_sendTextMessage(BZ_SERVER,playerID,"Usage: /loadplugin plug-in"); return true; } std::vector<std::string> subparams = TextUtils::tokenize(message,std::string(",")); std::string config; if ( subparams.size() >1) config = subparams[1]; if (loadPlugin(subparams[0],config)) bz_sendTextMessage(BZ_SERVER,playerID,"Plug-in loaded."); else bz_sendTextMessage(BZ_SERVER,playerID,"Plug-in load failed."); return true; } if ( TextUtils::tolower(command) == "unloadplugin" ) { if ( !params->size() ) { bz_sendTextMessage(BZ_SERVER,playerID,"Usage: /unloadplugin plug-in"); return true; } if ( unloadPlugin(std::string(params->get(0).c_str())) ) bz_sendTextMessage(BZ_SERVER,playerID,"Plug-in unloaded."); return true; } return true; } }; DynamicPluginCommands command; // auto load plugin dir std::string getAutoLoadDir ( void ) { if (BZDB.isSet("PlugInAutoLoadDir")) return BZDB.get("PlugInAutoLoadDir"); #if (defined(_WIN32) || defined(WIN32)) char exePath[MAX_PATH]; GetModuleFileName(NULL,exePath,MAX_PATH); char* last = strrchr(exePath,'\\'); if (last) *last = '\0'; strcat(exePath,"\\plugins"); return std::string(exePath); #else return std::string(""); #endif } void initPlugins ( void ) { customPluginMap.clear(); registerCustomSlashCommand("loadplugin",&command); registerCustomSlashCommand("unloadplugin",&command); registerCustomSlashCommand("listplugins",&command); #ifdef _WIN32 #ifdef _DEBUG OSDir dir; std::string path = getAutoLoadDir(); if (getAutoLoadDir().size()) { dir.setOSDir(getAutoLoadDir()); OSFile file; while(dir.getNextFile(file,"*.dll",false) ) loadPlugin(file.getOSName(),std::string("")); } #endif //_DEBUG #endif } bool registerCustomPluginHandler ( std::string exte, bz_APIPluginHandler *handler ) { std::string ext = TextUtils::tolower(exte); customPluginMap[ext] = handler; return true; } bool removeCustomPluginHandler ( std::string ext, bz_APIPluginHandler *handler ) { tmCustomPluginMap::iterator itr = customPluginMap.find(TextUtils::tolower(ext)); if (itr == customPluginMap.end() || itr->second != handler) return false; customPluginMap.erase(itr); return true; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>let bz_Load return non zero and be unloaded, in the case of a fatal error.<commit_after>/* bzflag * Copyright (c) 1993 - 2007 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include "common.h" /* system headers */ #include <iostream> #include <string> #include <vector> #include <map> /* common headers */ #include "bzfio.h" #include "version.h" #include "TextUtils.h" #include "commands.h" #include "bzfsAPI.h" #include "DirectoryNames.h" #include "OSFile.h" #ifdef _WIN32 std::string extension = ".dll"; std::string globalPluginDir = ".\\plugins\\"; #else std::string extension = ".so"; std::string globalPluginDir = "$(prefix)/lib/bzflag/"; #endif typedef std::map<std::string, bz_APIPluginHandler*> tmCustomPluginMap; tmCustomPluginMap customPluginMap; typedef struct { std::string foundPath; std::string plugin; #ifdef _WIN32 HINSTANCE handle; #else void* handle; #endif }trPluginRecord; std::vector<trPluginRecord> vPluginList; typedef enum { eLoadFailedDupe = -1, eLoadFailedError = 0, eLoadFailedRuntime, eLoadComplete }PluginLoadReturn; bool pluginExists ( std::string plugin ) { for ( int i = 0; i < (int)vPluginList.size(); i++ ) { if ( vPluginList[i].foundPath == plugin ) return true; } return false; } std::string findPlugin ( std::string pluginName ) { // see if we can just open the bloody thing FILE *fp = fopen(pluginName.c_str(),"rb"); if (fp) { fclose(fp); return pluginName; } // now try it with the standard extension std::string name = pluginName + extension; fp = fopen(name.c_str(),"rb"); if (fp) { fclose(fp); return name; } // check the local users plugins dir name = getConfigDirName(BZ_CONFIG_DIR_VERSION) + pluginName + extension; fp = fopen(name.c_str(),"rb"); if (fp) { fclose(fp); return name; } // check the global plugins dir name = globalPluginDir + pluginName + extension; fp = fopen(name.c_str(),"rb"); if (fp) { fclose(fp); return name; } return std::string(""); } void unload1Plugin ( int iPluginID ); #ifdef _WIN32 # include <windows.h> int getPluginVersion ( HINSTANCE hLib ) { int (*lpProc)(void); lpProc = (int (__cdecl *)(void))GetProcAddress(hLib, "bz_GetVersion"); if (lpProc) return lpProc(); return 0; } PluginLoadReturn load1Plugin ( std::string plugin, std::string config ) { int (*lpProc)(const char*); std::string realPluginName = findPlugin(plugin); if (pluginExists(realPluginName)) { logDebugMessage(1,"LoadPlugin fialed:%s is already loaded\n",realPluginName.c_str()); return eLoadFailedDupe; } HINSTANCE hLib = LoadLibrary(realPluginName.c_str()); if (hLib) { if (getPluginVersion(hLib) > BZ_API_VERSION) { logDebugMessage(1,"Plugin:%s found but expects an newer API version (%d), upgrade your bzfs\n",plugin.c_str(),getPluginVersion(hLib)); FreeLibrary(hLib); return eLoadFailedError; } else { lpProc = (int (__cdecl *)(const char*))GetProcAddress(hLib, "bz_Load"); if (lpProc) { if (lpProc(config.c_str())!= 0) { logDebugMessage(1,"Plugin:%s found but bz_Load returned an error\n",plugin.c_str()); FreeLibrary(hLib); return eLoadFailedRuntime; } logDebugMessage(1,"Plugin:%s loaded\n",plugin.c_str()); trPluginRecord pluginRecord; pluginRecord.foundPath = realPluginName; pluginRecord.handle = hLib; pluginRecord.plugin = plugin; vPluginList.push_back(pluginRecord); } else { logDebugMessage(1,"Plugin:%s found but does not contain bz_Load method\n",plugin.c_str()); FreeLibrary(hLib); return eLoadFailedError; } } } else { logDebugMessage(1,"Plugin:%s not found\n",plugin.c_str()); return eLoadFailedError; } return eLoadComplete; } void unload1Plugin ( int iPluginID ) { int (*lpProc)(void); trPluginRecord &plugin = vPluginList[iPluginID]; if (!plugin.handle) return; lpProc = (int (__cdecl *)(void))GetProcAddress(plugin.handle, "bz_Unload"); if (lpProc) lpProc(); else logDebugMessage(1,"Plugin does not contain bz_UnLoad method\n"); FreeLibrary(plugin.handle); plugin.handle = NULL; plugin.foundPath = ""; plugin.plugin = ""; } #else # include <dlfcn.h> std::vector<void*> vLibHandles; int getPluginVersion ( void* hLib ) { int (*lpProc)(void); lpProc = force_cast<int (*)(void)>(dlsym(hLib,"bz_GetVersion")); if (lpProc) return (*lpProc)(); return 0; } PluginLoadReturn load1Plugin ( std::string plugin, std::string config ) { int (*lpProc)(const char*); std::string realPluginName = findPlugin(plugin); if (pluginExists(realPluginName)) { logDebugMessage(1,"LoadPlugin fialed:%s is already loaded\n",realPluginName.c_str()); return eLoadFailedDupe; } void *hLib = dlopen(realPluginName.c_str(), RTLD_LAZY | RTLD_GLOBAL); if (hLib) { if (dlsym(hLib, "bz_Load") == NULL) { logDebugMessage(1,"Plugin:%s found but does not contain bz_Load method, error %s\n",plugin.c_str(),dlerror()); dlclose(hLib); return eLoadFailedError; } int version = getPluginVersion(hLib); if (version < BZ_API_VERSION) { logDebugMessage(1,"Plugin:%s found but expects an older API version (%d), upgrade it\n", plugin.c_str(), version); dlclose(hLib); return eLoadFailedError; } else { lpProc = force_cast<int (*)(const char*)>(dlsym(hLib,"bz_Load")); if (lpProc) { if((*lpProc)(config.c_str())) { logDebugMessage(1,"Plugin:%s found but bz_Load returned an error\n",plugin.c_str()); return eLoadFailedRuntime; } logDebugMessage(1,"Plugin:%s loaded\n",plugin.c_str()); trPluginRecord pluginRecord; pluginRecord.handle = hLib; pluginRecord.plugin = plugin; vPluginList.push_back(pluginRecord); return eLoadComplete; } } } else { logDebugMessage(1,"Plugin:%s not found, error %s\n",plugin.c_str(), dlerror()); return eLoadFailedError; } logDebugMessage(1,"If you see this, there is something terribly wrong.\n"); return eLoadFailedError; } void unload1Plugin ( int iPluginID ) { int (*lpProc)(void); trPluginRecord &plugin = vPluginList[iPluginID]; if(!plugin.handle) return; lpProc = force_cast<int (*)(void)>(dlsym(plugin.handle, "bz_Unload")); if (lpProc) (*lpProc)(); else logDebugMessage(1,"Plugin does not contain bz_UnLoad method, error %s\n",dlerror()); dlclose(plugin.handle); plugin.handle = NULL; plugin.foundPath = ""; plugin.plugin = ""; } #endif bool loadPlugin ( std::string plugin, std::string config ) { // check and see if it's an extension we have a handler for std::string ext; std::vector<std::string> parts = TextUtils::tokenize(plugin,std::string(".")); ext = parts[parts.size()-1]; tmCustomPluginMap::iterator itr = customPluginMap.find(TextUtils::tolower(ext)); if (itr != customPluginMap.end() && itr->second) { bz_APIPluginHandler *handler = itr->second; return handler->handle(plugin,config); } else return load1Plugin(plugin,config) == eLoadComplete; } bool unloadPlugin ( std::string plugin ) { // unload the first one of the name we find for (unsigned int i = 0; i < vPluginList.size();i++) { if ( vPluginList[i].plugin == plugin ) { unload1Plugin(i); vPluginList.erase(vPluginList.begin()+i); return true; } } return false; } void unloadPlugins ( void ) { for (unsigned int i = 0; i < vPluginList.size();i++) unload1Plugin(i); vPluginList.clear(); removeCustomSlashCommand("loadplugin"); removeCustomSlashCommand("unloadplugin"); removeCustomSlashCommand("listplugins"); } std::vector<std::string> getPluginList ( void ) { std::vector<std::string> plugins; for (unsigned int i = 0; i < vPluginList.size();i++) plugins.push_back(vPluginList[i].plugin); return plugins; } void parseServerCommand(const char *message, int dstPlayerId); class DynamicPluginCommands : public bz_CustomSlashCommandHandler { public: virtual ~DynamicPluginCommands(){}; virtual bool handle ( int playerID, bz_ApiString _command, bz_ApiString _message, bz_APIStringList *params ) { bz_BasePlayerRecord record; std::string command = _command.c_str(); std::string message = _message.c_str(); bz_BasePlayerRecord *p = bz_getPlayerByIndex(playerID); if (!p) return false; record = *p; bz_freePlayerRecord(p); // list needs listPlugins permission if ( TextUtils::tolower(command) == "listplugins" ) { if (!bz_hasPerm(playerID, "listPlugins")) { bz_sendTextMessage(BZ_SERVER,playerID,"You do not have permission to run the /listplugins command"); return true; } else { std::vector<std::string> plugins = getPluginList(); if (!plugins.size()) bz_sendTextMessage(BZ_SERVER,playerID,"No Plug-ins loaded."); else { bz_sendTextMessage(BZ_SERVER,playerID,"Plug-ins loaded:"); for ( unsigned int i = 0; i < plugins.size(); i++) bz_sendTextMessage(BZ_SERVER,playerID,plugins[i].c_str()); } } return true; } if ( !record.admin ) { bz_sendTextMessage(BZ_SERVER,playerID,"You do not have permission to (un)load plug-ins."); return true; } if ( TextUtils::tolower(command) == "loadplugin" ) { if ( !params->size() ) { bz_sendTextMessage(BZ_SERVER,playerID,"Usage: /loadplugin plug-in"); return true; } std::vector<std::string> subparams = TextUtils::tokenize(message,std::string(",")); std::string config; if ( subparams.size() >1) config = subparams[1]; if (loadPlugin(subparams[0],config)) bz_sendTextMessage(BZ_SERVER,playerID,"Plug-in loaded."); else bz_sendTextMessage(BZ_SERVER,playerID,"Plug-in load failed."); return true; } if ( TextUtils::tolower(command) == "unloadplugin" ) { if ( !params->size() ) { bz_sendTextMessage(BZ_SERVER,playerID,"Usage: /unloadplugin plug-in"); return true; } if ( unloadPlugin(std::string(params->get(0).c_str())) ) bz_sendTextMessage(BZ_SERVER,playerID,"Plug-in unloaded."); return true; } return true; } }; DynamicPluginCommands command; // auto load plugin dir std::string getAutoLoadDir ( void ) { if (BZDB.isSet("PlugInAutoLoadDir")) return BZDB.get("PlugInAutoLoadDir"); #if (defined(_WIN32) || defined(WIN32)) char exePath[MAX_PATH]; GetModuleFileName(NULL,exePath,MAX_PATH); char* last = strrchr(exePath,'\\'); if (last) *last = '\0'; strcat(exePath,"\\plugins"); return std::string(exePath); #else return std::string(""); #endif } void initPlugins ( void ) { customPluginMap.clear(); registerCustomSlashCommand("loadplugin",&command); registerCustomSlashCommand("unloadplugin",&command); registerCustomSlashCommand("listplugins",&command); #ifdef _WIN32 #ifdef _DEBUG OSDir dir; std::string path = getAutoLoadDir(); if (getAutoLoadDir().size()) { dir.setOSDir(getAutoLoadDir()); OSFile file; while(dir.getNextFile(file,"*.dll",false) ) loadPlugin(file.getOSName(),std::string("")); } #endif //_DEBUG #endif } bool registerCustomPluginHandler ( std::string exte, bz_APIPluginHandler *handler ) { std::string ext = TextUtils::tolower(exte); customPluginMap[ext] = handler; return true; } bool removeCustomPluginHandler ( std::string ext, bz_APIPluginHandler *handler ) { tmCustomPluginMap::iterator itr = customPluginMap.find(TextUtils::tolower(ext)); if (itr == customPluginMap.end() || itr->second != handler) return false; customPluginMap.erase(itr); return true; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2009 Torus Knot Software Ltd Also see acknowledgements in Readme.html You may use this sample code for anything you like, it is not covered by the same license as the rest of the engine. ----------------------------------------------------------------------------- */ #include "MaterialControls.h" #include "OgreLogManager.h" #include "OgreStringVector.h" #include "OgreStringConverter.h" #include "OgreConfigFile.h" #include "OgreResourceGroupManager.h" #include "OgreException.h" /******************************************************************************** MaterialControls Methods *********************************************************************************/ void MaterialControls::addControl(const Ogre::String& params) { // params is a string containing using the following format: // "<Control Name>, <Shader parameter name>, <Parameter Type>, <Min Val>, <Max Val>, <Parameter Sub Index>" // break up long string into components Ogre::StringVector vecparams = Ogre::StringUtil::split(params, ","); // if there are not five elements then log error and move on if (vecparams.size() != 6) { Ogre::LogManager::getSingleton().logMessage( "Incorrect number of parameters passed in params string for MaterialControls::addControl()" ); return; } ShaderControl newControl; Ogre::StringUtil::trim(vecparams[0]); newControl.Name = vecparams[0]; Ogre::StringUtil::trim(vecparams[1]); newControl.ParamName = vecparams[1]; Ogre::StringUtil::trim(vecparams[2]); if (vecparams[2] == "GPU_VERTEX") newControl.ValType = GPU_VERTEX; else if (vecparams[2] == "GPU_FRAGMENT") newControl.ValType = GPU_FRAGMENT; newControl.MinVal = Ogre::StringConverter::parseReal(vecparams[3]); newControl.MaxVal = Ogre::StringConverter::parseReal(vecparams[4]); newControl.ElementIndex = Ogre::StringConverter::parseInt(vecparams[5]); mShaderControlsContainer.push_back(newControl); } void loadMaterialControlsFile(MaterialControlsContainer& controlsContainer, const Ogre::String& filename) { // Load material controls from config file Ogre::ConfigFile cf; try { cf.load(filename, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, "\t;=", true); // Go through all sections & controls in the file Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator(); Ogre::String secName, typeName, materialName, dataString; while (seci.hasMoreElements()) { secName = seci.peekNextKey(); Ogre::ConfigFile::SettingsMultiMap* settings = seci.getNext(); if (!secName.empty() && settings) { materialName = cf.getSetting("material", secName); MaterialControls newMaaterialControls(secName, materialName); controlsContainer.push_back(newMaaterialControls); size_t idx = controlsContainer.size() - 1; Ogre::ConfigFile::SettingsMultiMap::iterator i; for (i = settings->begin(); i != settings->end(); ++i) { typeName = i->first; dataString = i->second; if (typeName == "control") controlsContainer[idx].addControl(dataString); } } } Ogre::LogManager::getSingleton().logMessage( "Material Controls setup" ); } catch (Ogre::Exception e) { // Guess the file didn't exist } } void loadAllMaterialControlFiles(MaterialControlsContainer& controlsContainer) { Ogre::StringVectorPtr fileStringVector = Ogre::ResourceGroupManager::getSingleton().findResourceNames( "Popular", "*.controls"); Ogre::StringVector::iterator controlsFileNameIterator = fileStringVector->begin(); while ( controlsFileNameIterator != fileStringVector->end() ) { loadMaterialControlsFile(controlsContainer, *controlsFileNameIterator); ++controlsFileNameIterator; } } <commit_msg>Ocean demo: added code to show only supported materials.<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2009 Torus Knot Software Ltd Also see acknowledgements in Readme.html You may use this sample code for anything you like, it is not covered by the same license as the rest of the engine. ----------------------------------------------------------------------------- */ #include "MaterialControls.h" #include "OgreLogManager.h" #include "OgreStringVector.h" #include "OgreStringConverter.h" #include "OgreConfigFile.h" #include "OgreResourceGroupManager.h" #include "OgreException.h" #include "OgreMaterial.h" #include "OgreTechnique.h" #include "OgreMaterialManager.h" /******************************************************************************** MaterialControls Methods *********************************************************************************/ void MaterialControls::addControl(const Ogre::String& params) { // params is a string containing using the following format: // "<Control Name>, <Shader parameter name>, <Parameter Type>, <Min Val>, <Max Val>, <Parameter Sub Index>" // break up long string into components Ogre::StringVector vecparams = Ogre::StringUtil::split(params, ","); // if there are not five elements then log error and move on if (vecparams.size() != 6) { Ogre::LogManager::getSingleton().logMessage( "Incorrect number of parameters passed in params string for MaterialControls::addControl()" ); return; } ShaderControl newControl; Ogre::StringUtil::trim(vecparams[0]); newControl.Name = vecparams[0]; Ogre::StringUtil::trim(vecparams[1]); newControl.ParamName = vecparams[1]; Ogre::StringUtil::trim(vecparams[2]); if (vecparams[2] == "GPU_VERTEX") newControl.ValType = GPU_VERTEX; else if (vecparams[2] == "GPU_FRAGMENT") newControl.ValType = GPU_FRAGMENT; newControl.MinVal = Ogre::StringConverter::parseReal(vecparams[3]); newControl.MaxVal = Ogre::StringConverter::parseReal(vecparams[4]); newControl.ElementIndex = Ogre::StringConverter::parseInt(vecparams[5]); mShaderControlsContainer.push_back(newControl); } void loadMaterialControlsFile(MaterialControlsContainer& controlsContainer, const Ogre::String& filename) { // Load material controls from config file Ogre::ConfigFile cf; try { cf.load(filename, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, "\t;=", true); // Go through all sections & controls in the file Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator(); Ogre::String secName, typeName, materialName, dataString; while (seci.hasMoreElements()) { secName = seci.peekNextKey(); Ogre::ConfigFile::SettingsMultiMap* settings = seci.getNext(); if (!secName.empty() && settings) { materialName = cf.getSetting("material", secName); Ogre::MaterialPtr curMat = Ogre::MaterialManager::getSingleton().getByName(materialName); curMat->load(); Ogre::Technique * curTec = curMat->getBestTechnique(); if (!curTec || !curTec->isSupported()) { continue; } MaterialControls newMaaterialControls(secName, materialName); controlsContainer.push_back(newMaaterialControls); size_t idx = controlsContainer.size() - 1; Ogre::ConfigFile::SettingsMultiMap::iterator i; for (i = settings->begin(); i != settings->end(); ++i) { typeName = i->first; dataString = i->second; if (typeName == "control") controlsContainer[idx].addControl(dataString); } } } Ogre::LogManager::getSingleton().logMessage( "Material Controls setup" ); } catch (Ogre::Exception e) { // Guess the file didn't exist } } void loadAllMaterialControlFiles(MaterialControlsContainer& controlsContainer) { Ogre::StringVectorPtr fileStringVector = Ogre::ResourceGroupManager::getSingleton().findResourceNames( "Popular", "*.controls"); Ogre::StringVector::iterator controlsFileNameIterator = fileStringVector->begin(); while ( controlsFileNameIterator != fileStringVector->end() ) { loadMaterialControlsFile(controlsContainer, *controlsFileNameIterator); ++controlsFileNameIterator; } } <|endoftext|>
<commit_before>#include "StateSpace.h" // NOTE: cannot initialise angle_bins or velocity_bins here as they are static. Also space is not a field of StateSpace and // _angle_max and _velocity_max are not declared. StateSpace::StateSpace(PriorityQueue<int,double> queue ): space1(_angle_max, std::vector< PriorityQueue<int,double> > (_velocity_max, PriorityQueue<int,double> (queue))) space2(_angle_max, std::vector< PriorityQueue<int,double> > (_velocity_max, PriorityQueue<int,double> (queue))) {} StateSpace::SubscriptProxy1 StateSpace::operator[](const unsigned int robot_state) { //throw if the the index is out of bounds if(robot_state>1)throw std::domain_error("action index exceeded"); //return proxy object to accept second [] operator return SubscriptProxy1( robot_state ? space1 : space2 ); } //searches state space by state object PriorityQueue<int, double>& StateSpace::operator[](const State & state) { //call the subscript operators with the members of the state object return (*this)[state.robot_state][state.theta][state.theta_dot]; } void setAngleBins(const double val) { angle_bins=val; } void setVelocityBins(const double val) { velocity_bins=val; } <commit_msg>Update StateSpace.cpp<commit_after>#include "StateSpace.h" // NOTE: cannot initialise angle_bins or velocity_bins here as they are static. Also space is not a field of StateSpace and // _angle_max and _velocity_max are not declared. StateSpace::StateSpace(int _angle_bins, int _velocity_bins, PriorityQueue<int,double> queue ): space1(_angle_bins, std::vector< PriorityQueue<int,double> > (_velocity_bins, PriorityQueue<int,double> (queue))) space2(_angle_bins, std::vector< PriorityQueue<int,double> > (_velocity_bins, PriorityQueue<int,double> (queue))) {} StateSpace::SubscriptProxy1 StateSpace::operator[](const unsigned int robot_state) { //throw if the the index is out of bounds if(robot_state>1)throw std::domain_error("action index exceeded"); //return proxy object to accept second [] operator return SubscriptProxy1( robot_state ? space1 : space2 ); } //searches state space by state object PriorityQueue<int, double>& StateSpace::operator[](const State & state) { //call the subscript operators with the members of the state object return (*this)[state.robot_state][state.theta][state.theta_dot]; } void setAngleBins(const double val) { angle_bins=val; } void setVelocityBins(const double val) { velocity_bins=val; } <|endoftext|>
<commit_before>/** * @file StateSpace.cpp * * @brief Implementation file for StateSpace class. * * @author Machine Learning Team 2015-2016 * @date March, 2016 */ #include "StateSpace.h" int StateSpace::angle_bins; int StateSpace::velocity_bins; /** * Creates a state space object initialised with a given number of bins for discretising angles and * velocities of the system. A (const referenced) PriorityQueue instance is passed to the constructor * in order to initialise state space actions and experiences - not that this queue then should be * the queue of default initial action(s) and prioritised experience(s). */ StateSpace::StateSpace(int _angle_bins, int _velocity_bins, double _angle_max, double _velocity_max const PriorityQueue<int, double>& queue) : space1(_angle_bins, std::vector< PriorityQueue<int, double> >(_velocity_bins, PriorityQueue<int, double>(queue))), space2(_angle_bins, std::vector< PriorityQueue<int, double> >(_velocity_bins, PriorityQueue<int, double>(queue))) { angle_bins = _angle_bins-1; velocity_bins = _velocity_bins-1; angle_max = _angle_max; velocity_ = _velocity_max; } /** * Operator to be used for triple subscript indexing, returns a SubscriptProxy1 object. * * Correct indexing of this method is as follows: * * \code{.cpp} * state_space_object[robot_state][angle][velocity] * \endcode */ StateSpace::SubscriptProxy1 StateSpace::operator[](const unsigned int robot_state) { //throw if the the index is out of bounds if (robot_state>1)throw std::domain_error("action index exceeded"); //return proxy object to accept second [] operator return SubscriptProxy1(robot_state ? space1 : space2); } /** * Operator to be used for single subscript indexing, returns a PriorityQueue object. * * Correct indexing of this method is as follows: * * \code{.cpp} * state_space_object[state_object] * \endcode */ PriorityQueue<int, double>& StateSpace::operator[](const State & state) { //call the subscript operators with the members of the state object return (*this)[state.robot_state][state.theta][state.theta_dot]; } <commit_msg>cleared up bens shit again<commit_after>/** * @file StateSpace.cpp * * @brief Implementation file for StateSpace class. * * @author Machine Learning Team 2015-2016 * @date March, 2016 */ #include "StateSpace.h" int StateSpace::angle_bins; int StateSpace::velocity_bins; /** * Creates a state space object initialised with a given number of bins for discretising angles and * velocities of the system. A (const referenced) PriorityQueue instance is passed to the constructor * in order to initialise state space actions and experiences - not that this queue then should be * the queue of default initial action(s) and prioritised experience(s). */ StateSpace::StateSpace(int _angle_bins, int _velocity_bins, double _angle_max, double _velocity_max, const PriorityQueue<int, double>& queue) : space1(_angle_bins, std::vector< PriorityQueue<int, double> >(_velocity_bins, PriorityQueue<int, double>(queue))), space2(_angle_bins, std::vector< PriorityQueue<int, double> >(_velocity_bins, PriorityQueue<int, double>(queue))) { angle_bins = _angle_bins-1; velocity_bins = _velocity_bins-1; angle_max = _angle_max; velocity_ = _velocity_max; } /** * Operator to be used for triple subscript indexing, returns a SubscriptProxy1 object. * * Correct indexing of this method is as follows: * * \code{.cpp} * state_space_object[robot_state][angle][velocity] * \endcode */ StateSpace::SubscriptProxy1 StateSpace::operator[](const unsigned int robot_state) { //throw if the the index is out of bounds if (robot_state>1)throw std::domain_error("action index exceeded"); //return proxy object to accept second [] operator return SubscriptProxy1(robot_state ? space1 : space2); } /** * Operator to be used for single subscript indexing, returns a PriorityQueue object. * * Correct indexing of this method is as follows: * * \code{.cpp} * state_space_object[state_object] * \endcode */ PriorityQueue<int, double>& StateSpace::operator[](const State & state) { //call the subscript operators with the members of the state object return (*this)[state.robot_state][state.theta][state.theta_dot]; } <|endoftext|>
<commit_before>/*! * \file painter_brush.cpp * \brief file painter_brush.cpp * * Copyright 2016 by Intel. * * Contact: kevin.rogovin@intel.com * * This Source Code Form is subject to the * terms of the Mozilla Public License, v. 2.0. * If a copy of the MPL was not distributed with * this file, You can obtain one at * http://mozilla.org/MPL/2.0/. * * \author Kevin Rogovin <kevin.rogovin@intel.com> * */ #include <algorithm> #include <fastuidraw/painter/painter_brush.hpp> //////////////////////////////////// // fastuidraw::PainterBrush methods unsigned int fastuidraw::PainterBrush:: data_size(void) const { unsigned int return_value(0); uint32_t pshader = shader(); return_value += FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(color_data_size); if (pshader & image_mask) { return_value += FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(image_data_size); } switch(gradient_type()) { case no_gradient_type: break; case linear_gradient_type: return_value += FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(linear_gradient_data_size); break; case sweep_gradient_type: return_value += FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(sweep_gradient_data_size); break; case radial_gradient_type: return_value += FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(radial_gradient_data_size); break; default: FASTUIDRAWassert(!"Invalid gradient_type()"); break; } if (pshader & repeat_window_mask) { return_value += FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(repeat_window_data_size); } if (pshader & transformation_translation_mask) { return_value += FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(transformation_translation_data_size); } if (pshader & transformation_matrix_mask) { return_value += FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(transformation_matrix_data_size); } return return_value; } void fastuidraw::PainterBrush:: pack_data(c_array<generic_data> dst) const { unsigned int current(0); unsigned int sz; c_array<generic_data> sub_dest; uint32_t pshader = shader(); { sz = FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(color_data_size); sub_dest = dst.sub_array(current, sz); current += sz; sub_dest[color_red_offset].f = m_data.m_color.x(); sub_dest[color_green_offset].f = m_data.m_color.y(); sub_dest[color_blue_offset].f = m_data.m_color.z(); sub_dest[color_alpha_offset].f = m_data.m_color.w(); } if (pshader & image_mask) { sz = FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(image_data_size); sub_dest = dst.sub_array(current, sz); current += sz; FASTUIDRAWassert(m_data.m_image); uvec3 loc(m_data.m_image->master_index_tile()); uint32_t lookups(m_data.m_image->number_index_lookups()); sub_dest[image_size_xy_offset].u = pack_bits(image_size_x_bit0, image_size_x_num_bits, m_data.m_image_size.x()) | pack_bits(image_size_y_bit0, image_size_y_num_bits, m_data.m_image_size.y()); sub_dest[image_start_xy_offset].u = pack_bits(image_size_x_bit0, image_size_x_num_bits, m_data.m_image_start.x()) | pack_bits(image_size_y_bit0, image_size_y_num_bits, m_data.m_image_start.y()); if (m_data.m_image->type() == Image::on_atlas) { sub_dest[image_atlas_location_xyz_offset].u = pack_bits(image_atlas_location_x_bit0, image_atlas_location_x_num_bits, loc.x()) | pack_bits(image_atlas_location_y_bit0, image_atlas_location_y_num_bits, loc.y()) | pack_bits(image_atlas_location_z_bit0, image_atlas_location_z_num_bits, loc.z()); sub_dest[image_number_lookups_offset].u = lookups; } else { uint64_t v, hi, low; v = m_data.m_image->bindless_handle(); hi = uint64_unpack_bits(32, 32, v); low = uint64_unpack_bits(0, 32, v); sub_dest[image_bindless_handle_hi_offset].u = hi; sub_dest[image_bindless_handle_low_offset].u = low; } } enum gradient_type_t tp(gradient_type()); if (tp != no_gradient_type) { if (tp == radial_gradient_type) { sz = FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(radial_gradient_data_size); } else { FASTUIDRAWassert(sweep_gradient_data_size == linear_gradient_data_size); sz = FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(linear_gradient_data_size); } sub_dest = dst.sub_array(current, sz); current += sz; FASTUIDRAWassert(m_data.m_cs); FASTUIDRAWassert(m_data.m_cs->texel_location().x() >= 0); FASTUIDRAWassert(m_data.m_cs->texel_location().y() >= 0); uint32_t x, y; x = static_cast<uint32_t>(m_data.m_cs->texel_location().x()); y = static_cast<uint32_t>(m_data.m_cs->texel_location().y()); sub_dest[gradient_color_stop_xy_offset].u = pack_bits(gradient_color_stop_x_bit0, gradient_color_stop_x_num_bits, x) | pack_bits(gradient_color_stop_y_bit0, gradient_color_stop_y_num_bits, y); sub_dest[gradient_color_stop_length_offset].u = m_data.m_cs->width(); sub_dest[gradient_p0_x_offset].f = m_data.m_grad_start.x(); sub_dest[gradient_p0_y_offset].f = m_data.m_grad_start.y(); sub_dest[gradient_p1_x_offset].f = m_data.m_grad_end.x(); sub_dest[gradient_p1_y_offset].f = m_data.m_grad_end.y(); if (tp == radial_gradient_type) { sub_dest[gradient_start_radius_offset].f = m_data.m_grad_start_r; sub_dest[gradient_end_radius_offset].f = m_data.m_grad_end_r; } } if (pshader & repeat_window_mask) { sz = FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(repeat_window_data_size); sub_dest = dst.sub_array(current, sz); current += sz; sub_dest[repeat_window_x_offset].f = m_data.m_window_position.x(); sub_dest[repeat_window_y_offset].f = m_data.m_window_position.y(); sub_dest[repeat_window_width_offset].f = m_data.m_window_size.x(); sub_dest[repeat_window_height_offset].f = m_data.m_window_size.y(); } if (pshader & transformation_matrix_mask) { sz = FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(transformation_matrix_data_size); sub_dest = dst.sub_array(current, sz); current += sz; sub_dest[transformation_matrix_row0_col0_offset].f = m_data.m_transformation_matrix(0, 0); sub_dest[transformation_matrix_row0_col1_offset].f = m_data.m_transformation_matrix(0, 1); sub_dest[transformation_matrix_row1_col0_offset].f = m_data.m_transformation_matrix(1, 0); sub_dest[transformation_matrix_row1_col1_offset].f = m_data.m_transformation_matrix(1, 1); } if (pshader & transformation_translation_mask) { sz = FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(transformation_translation_data_size); sub_dest = dst.sub_array(current, sz); current += sz; sub_dest[transformation_translation_x_offset].f = m_data.m_transformation_p.x(); sub_dest[transformation_translation_y_offset].f = m_data.m_transformation_p.y(); } FASTUIDRAWassert(current == dst.size()); } fastuidraw::PainterBrush& fastuidraw::PainterBrush:: sub_image(const reference_counted_ptr<const Image> &im, uvec2 xy, uvec2 wh, enum image_filter f, enum mipmap_t mipmap_filtering) { uint32_t filter_bits, type_bits, mip_bits, fmt_bits; filter_bits = (im) ? uint32_t(f) : uint32_t(0); type_bits = (im) ? uint32_t(im->type()) : uint32_t(0); fmt_bits = (im) ? uint32_t(im->format()) : uint32_t(0); mip_bits = (im && mipmap_filtering == apply_mipmapping) ? uint32_t(im->number_mipmap_levels()): uint32_t(0); mip_bits = (mip_bits != 0u && f != image_filter_nearest) ? mip_bits - 1u : mip_bits; mip_bits = t_min(mip_bits, FASTUIDRAW_MAX_VALUE_FROM_NUM_BITS(image_mipmap_num_bits)); m_data.m_image = im; m_data.m_image_start = xy; m_data.m_image_size = wh; m_data.m_shader_raw &= ~image_mask; m_data.m_shader_raw |= pack_bits(image_filter_bit0, image_filter_num_bits, filter_bits); m_data.m_shader_raw &= ~image_type_mask; m_data.m_shader_raw |= pack_bits(image_type_bit0, image_type_num_bits, type_bits); m_data.m_shader_raw &= ~image_mipmap_mask; m_data.m_shader_raw |= pack_bits(image_mipmap_bit0, image_mipmap_num_bits, mip_bits); m_data.m_shader_raw &= ~image_format_mask; m_data.m_shader_raw |= pack_bits(image_format_bit0, image_format_num_bits, fmt_bits); return *this; } fastuidraw::PainterBrush& fastuidraw::PainterBrush:: image(const reference_counted_ptr<const Image> &im, enum image_filter f, enum mipmap_t mipmap_filtering) { uvec2 sz(0, 0); if (im) { sz = uvec2(im->dimensions()); } return sub_image(im, uvec2(0,0), sz, f, mipmap_filtering); } uint32_t fastuidraw::PainterBrush:: shader(void) const { uint32_t return_value; FASTUIDRAWstatic_assert(number_shader_bits <= 32u); return_value = m_data.m_shader_raw; if (!m_data.m_image && !m_data.m_cs) { /* lacking an image or gradient means the brush does * nothing and so all bits should be down. */ return_value = 0; } return return_value; } fastuidraw::PainterBrush& fastuidraw::PainterBrush:: reset(void) { color(1.0, 1.0, 1.0, 1.0); m_data.m_shader_raw = 0u; m_data.m_image = nullptr; m_data.m_cs = nullptr; m_data.m_transformation_p = vec2(0.0f, 0.0f); m_data.m_transformation_matrix = float2x2(); return *this; } <commit_msg>fastuidraw/painter/painter_brush: bug fix for computing max-mipmap-level.<commit_after>/*! * \file painter_brush.cpp * \brief file painter_brush.cpp * * Copyright 2016 by Intel. * * Contact: kevin.rogovin@intel.com * * This Source Code Form is subject to the * terms of the Mozilla Public License, v. 2.0. * If a copy of the MPL was not distributed with * this file, You can obtain one at * http://mozilla.org/MPL/2.0/. * * \author Kevin Rogovin <kevin.rogovin@intel.com> * */ #include <algorithm> #include <fastuidraw/painter/painter_brush.hpp> //////////////////////////////////// // fastuidraw::PainterBrush methods unsigned int fastuidraw::PainterBrush:: data_size(void) const { unsigned int return_value(0); uint32_t pshader = shader(); return_value += FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(color_data_size); if (pshader & image_mask) { return_value += FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(image_data_size); } switch(gradient_type()) { case no_gradient_type: break; case linear_gradient_type: return_value += FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(linear_gradient_data_size); break; case sweep_gradient_type: return_value += FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(sweep_gradient_data_size); break; case radial_gradient_type: return_value += FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(radial_gradient_data_size); break; default: FASTUIDRAWassert(!"Invalid gradient_type()"); break; } if (pshader & repeat_window_mask) { return_value += FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(repeat_window_data_size); } if (pshader & transformation_translation_mask) { return_value += FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(transformation_translation_data_size); } if (pshader & transformation_matrix_mask) { return_value += FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(transformation_matrix_data_size); } return return_value; } void fastuidraw::PainterBrush:: pack_data(c_array<generic_data> dst) const { unsigned int current(0); unsigned int sz; c_array<generic_data> sub_dest; uint32_t pshader = shader(); { sz = FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(color_data_size); sub_dest = dst.sub_array(current, sz); current += sz; sub_dest[color_red_offset].f = m_data.m_color.x(); sub_dest[color_green_offset].f = m_data.m_color.y(); sub_dest[color_blue_offset].f = m_data.m_color.z(); sub_dest[color_alpha_offset].f = m_data.m_color.w(); } if (pshader & image_mask) { sz = FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(image_data_size); sub_dest = dst.sub_array(current, sz); current += sz; FASTUIDRAWassert(m_data.m_image); uvec3 loc(m_data.m_image->master_index_tile()); uint32_t lookups(m_data.m_image->number_index_lookups()); sub_dest[image_size_xy_offset].u = pack_bits(image_size_x_bit0, image_size_x_num_bits, m_data.m_image_size.x()) | pack_bits(image_size_y_bit0, image_size_y_num_bits, m_data.m_image_size.y()); sub_dest[image_start_xy_offset].u = pack_bits(image_size_x_bit0, image_size_x_num_bits, m_data.m_image_start.x()) | pack_bits(image_size_y_bit0, image_size_y_num_bits, m_data.m_image_start.y()); if (m_data.m_image->type() == Image::on_atlas) { sub_dest[image_atlas_location_xyz_offset].u = pack_bits(image_atlas_location_x_bit0, image_atlas_location_x_num_bits, loc.x()) | pack_bits(image_atlas_location_y_bit0, image_atlas_location_y_num_bits, loc.y()) | pack_bits(image_atlas_location_z_bit0, image_atlas_location_z_num_bits, loc.z()); sub_dest[image_number_lookups_offset].u = lookups; } else { uint64_t v, hi, low; v = m_data.m_image->bindless_handle(); hi = uint64_unpack_bits(32, 32, v); low = uint64_unpack_bits(0, 32, v); sub_dest[image_bindless_handle_hi_offset].u = hi; sub_dest[image_bindless_handle_low_offset].u = low; } } enum gradient_type_t tp(gradient_type()); if (tp != no_gradient_type) { if (tp == radial_gradient_type) { sz = FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(radial_gradient_data_size); } else { FASTUIDRAWassert(sweep_gradient_data_size == linear_gradient_data_size); sz = FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(linear_gradient_data_size); } sub_dest = dst.sub_array(current, sz); current += sz; FASTUIDRAWassert(m_data.m_cs); FASTUIDRAWassert(m_data.m_cs->texel_location().x() >= 0); FASTUIDRAWassert(m_data.m_cs->texel_location().y() >= 0); uint32_t x, y; x = static_cast<uint32_t>(m_data.m_cs->texel_location().x()); y = static_cast<uint32_t>(m_data.m_cs->texel_location().y()); sub_dest[gradient_color_stop_xy_offset].u = pack_bits(gradient_color_stop_x_bit0, gradient_color_stop_x_num_bits, x) | pack_bits(gradient_color_stop_y_bit0, gradient_color_stop_y_num_bits, y); sub_dest[gradient_color_stop_length_offset].u = m_data.m_cs->width(); sub_dest[gradient_p0_x_offset].f = m_data.m_grad_start.x(); sub_dest[gradient_p0_y_offset].f = m_data.m_grad_start.y(); sub_dest[gradient_p1_x_offset].f = m_data.m_grad_end.x(); sub_dest[gradient_p1_y_offset].f = m_data.m_grad_end.y(); if (tp == radial_gradient_type) { sub_dest[gradient_start_radius_offset].f = m_data.m_grad_start_r; sub_dest[gradient_end_radius_offset].f = m_data.m_grad_end_r; } } if (pshader & repeat_window_mask) { sz = FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(repeat_window_data_size); sub_dest = dst.sub_array(current, sz); current += sz; sub_dest[repeat_window_x_offset].f = m_data.m_window_position.x(); sub_dest[repeat_window_y_offset].f = m_data.m_window_position.y(); sub_dest[repeat_window_width_offset].f = m_data.m_window_size.x(); sub_dest[repeat_window_height_offset].f = m_data.m_window_size.y(); } if (pshader & transformation_matrix_mask) { sz = FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(transformation_matrix_data_size); sub_dest = dst.sub_array(current, sz); current += sz; sub_dest[transformation_matrix_row0_col0_offset].f = m_data.m_transformation_matrix(0, 0); sub_dest[transformation_matrix_row0_col1_offset].f = m_data.m_transformation_matrix(0, 1); sub_dest[transformation_matrix_row1_col0_offset].f = m_data.m_transformation_matrix(1, 0); sub_dest[transformation_matrix_row1_col1_offset].f = m_data.m_transformation_matrix(1, 1); } if (pshader & transformation_translation_mask) { sz = FASTUIDRAW_ROUND_UP_MULTIPLE_OF4(transformation_translation_data_size); sub_dest = dst.sub_array(current, sz); current += sz; sub_dest[transformation_translation_x_offset].f = m_data.m_transformation_p.x(); sub_dest[transformation_translation_y_offset].f = m_data.m_transformation_p.y(); } FASTUIDRAWassert(current == dst.size()); } fastuidraw::PainterBrush& fastuidraw::PainterBrush:: sub_image(const reference_counted_ptr<const Image> &im, uvec2 xy, uvec2 wh, enum image_filter f, enum mipmap_t mipmap_filtering) { uint32_t filter_bits, type_bits, mip_bits, fmt_bits; filter_bits = (im) ? uint32_t(f) : uint32_t(0); type_bits = (im) ? uint32_t(im->type()) : uint32_t(0); fmt_bits = (im) ? uint32_t(im->format()) : uint32_t(0); mip_bits = (im && mipmap_filtering == apply_mipmapping) ? uint32_t(t_max(im->number_mipmap_levels(), 1u) - 1u): uint32_t(0); mip_bits = (mip_bits != 0u && f != image_filter_nearest) ? mip_bits - 1u : mip_bits; mip_bits = t_min(mip_bits, FASTUIDRAW_MAX_VALUE_FROM_NUM_BITS(image_mipmap_num_bits)); m_data.m_image = im; m_data.m_image_start = xy; m_data.m_image_size = wh; m_data.m_shader_raw &= ~image_mask; m_data.m_shader_raw |= pack_bits(image_filter_bit0, image_filter_num_bits, filter_bits); m_data.m_shader_raw &= ~image_type_mask; m_data.m_shader_raw |= pack_bits(image_type_bit0, image_type_num_bits, type_bits); m_data.m_shader_raw &= ~image_mipmap_mask; m_data.m_shader_raw |= pack_bits(image_mipmap_bit0, image_mipmap_num_bits, mip_bits); m_data.m_shader_raw &= ~image_format_mask; m_data.m_shader_raw |= pack_bits(image_format_bit0, image_format_num_bits, fmt_bits); return *this; } fastuidraw::PainterBrush& fastuidraw::PainterBrush:: image(const reference_counted_ptr<const Image> &im, enum image_filter f, enum mipmap_t mipmap_filtering) { uvec2 sz(0, 0); if (im) { sz = uvec2(im->dimensions()); } return sub_image(im, uvec2(0,0), sz, f, mipmap_filtering); } uint32_t fastuidraw::PainterBrush:: shader(void) const { uint32_t return_value; FASTUIDRAWstatic_assert(number_shader_bits <= 32u); return_value = m_data.m_shader_raw; if (!m_data.m_image && !m_data.m_cs) { /* lacking an image or gradient means the brush does * nothing and so all bits should be down. */ return_value = 0; } return return_value; } fastuidraw::PainterBrush& fastuidraw::PainterBrush:: reset(void) { color(1.0, 1.0, 1.0, 1.0); m_data.m_shader_raw = 0u; m_data.m_image = nullptr; m_data.m_cs = nullptr; m_data.m_transformation_p = vec2(0.0f, 0.0f); m_data.m_transformation_matrix = float2x2(); return *this; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** This file is part of the CAMP library. ** ** The MIT License (MIT) ** ** Copyright (C) 2009-2014 TEGESO/TEGESOFT and/or its subsidiary(-ies) and mother company. ** Contact: Tegesoft Information (contact@tegesoft.com) ** ** 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 <camp/classbuilderbase.hpp> #include <camp/property.hpp> #include <camp/function.hpp> #include <camp/class.hpp> namespace camp { //------------------------------------------------------------------------------------------------- ClassBuilderBase::ClassBuilderBase(Class& target) : m_target(&target) , m_currentTagHolder(m_target) , m_currentProperty(nullptr) , m_currentFunction(nullptr) { } //------------------------------------------------------------------------------------------------- Class& ClassBuilderBase::getClass() { return *m_target; } //------------------------------------------------------------------------------------------------- void ClassBuilderBase::addBase(const Class& baseClass, int offset) { #ifdef _DEBUG { // First make sure that the base class is not already a base of the current class const uint32_t baseId = baseClass.id(); const Class::BaseVector& bases = m_target->m_bases; const size_t numberOfBases = bases.size(); for (size_t i = 0; i < numberOfBases; ++i) { assert(bases[i].base->id() != baseId); } } #endif // Add the base metaclass to the bases of the current class Class::BaseInfo baseInfos; baseInfos.base = &baseClass; baseInfos.offset = offset; m_target->m_bases.push_back(baseInfos); { // Copy all properties of the base class into the current class Class::SortedPropertyVector& targetProperties = m_target->m_properties; const Class::SortedPropertyVector& baseProperties = baseClass.m_properties; const size_t numberOfProperties = baseProperties.size(); for (size_t i = 0; i < numberOfProperties; ++i) { const Class::PropertyEntry& propertyEntry = baseProperties[i]; Class::SortedPropertyVector::const_iterator iterator = std::lower_bound(targetProperties.cbegin(), targetProperties.cend(), propertyEntry.id, Class::OrderByPropertyId()); targetProperties.emplace(iterator, Class::PropertyEntry(propertyEntry.id, propertyEntry.propertyPtr)); } } { // Copy all functions of the base class into the current class Class::SortedFunctionVector& targetFunctions = m_target->m_functions; const Class::SortedFunctionVector& baseFunctions = baseClass.m_functions; const size_t numberOfFunctions = baseFunctions.size(); for (size_t i = 0; i < numberOfFunctions; ++i) { const Class::FunctionEntry& functionEntry = baseFunctions[i]; Class::SortedFunctionVector::const_iterator iterator = std::lower_bound(targetFunctions.cbegin(), targetFunctions.cend(), functionEntry.id, Class::OrderByFunctionId()); targetFunctions.emplace(iterator, Class::FunctionEntry(functionEntry.id, functionEntry.functionPtr)); } } } //------------------------------------------------------------------------------------------------- void ClassBuilderBase::addConstructor(Constructor* constructor) { m_target->m_constructors.push_back(constructor); } //------------------------------------------------------------------------------------------------- void ClassBuilderBase::addProperty(Property* property) { // Retrieve the class' properties sorted by ID Class::SortedPropertyVector& properties = m_target->m_properties; // Replace any property that already exists with the same ID const uint32_t id = property->id(); Class::SortedPropertyVector::const_iterator iterator = std::lower_bound(properties.cbegin(), properties.cend(), id, Class::OrderByPropertyId()); if (iterator != properties.end() && iterator._Ptr->id == id) { // Found, so just replace property iterator._Ptr->propertyPtr = Class::PropertyPtr(property); } else { // Not found, insert new property properties.emplace(iterator, Class::PropertyEntry(id, Class::PropertyPtr(property))); } m_currentTagHolder = m_currentProperty = property; m_currentFunction = nullptr; } //------------------------------------------------------------------------------------------------- void ClassBuilderBase::addFunction(Function* function) { // Retrieve the class' functions sorted by ID Class::SortedFunctionVector& functions = m_target->m_functions; // Replace any function that already exists with the same ID const uint32_t id = function->id(); Class::SortedFunctionVector::const_iterator iterator = std::lower_bound(functions.cbegin(), functions.cend(), id, Class::OrderByFunctionId()); if (iterator != functions.end() && iterator._Ptr->id == id) { // Found, so just replace function iterator._Ptr->functionPtr = Class::FunctionPtr(function); } else { // Not found, insert new function functions.emplace(iterator, Class::FunctionEntry(id, Class::FunctionPtr(function))); } m_currentTagHolder = m_currentFunction = function; m_currentProperty = nullptr; } //------------------------------------------------------------------------------------------------- void ClassBuilderBase::addTag(const char* name, const detail::Getter<Value>& value) { assert(m_currentTagHolder); // Retrieve the tag holders tags sorted by ID const StringId id(name); TagHolder::SortedTagVector& tags = m_currentTagHolder->m_tags; // Replace any tag that already exists with the same ID TagHolder::SortedTagVector::const_iterator iterator = std::lower_bound(tags.cbegin(), tags.cend(), id, TagHolder::OrderByTagId()); if (iterator != tags.end() && iterator._Ptr->id == id) { // Found, so just replace tag value // -> Should not happen for efficiency reasons assert(false); iterator._Ptr->value = value; } else { // Not found, insert new tag tags.emplace(iterator, TagHolder::TagEntry(id, name, value)); } } } // namespace camp <commit_msg>"camp::ClassBuilderBase::addBase()" properly handle property and function name duplicates<commit_after>/**************************************************************************** ** ** This file is part of the CAMP library. ** ** The MIT License (MIT) ** ** Copyright (C) 2009-2014 TEGESO/TEGESOFT and/or its subsidiary(-ies) and mother company. ** Contact: Tegesoft Information (contact@tegesoft.com) ** ** 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 <camp/classbuilderbase.hpp> #include <camp/property.hpp> #include <camp/function.hpp> #include <camp/class.hpp> namespace camp { //------------------------------------------------------------------------------------------------- ClassBuilderBase::ClassBuilderBase(Class& target) : m_target(&target) , m_currentTagHolder(m_target) , m_currentProperty(nullptr) , m_currentFunction(nullptr) { } //------------------------------------------------------------------------------------------------- Class& ClassBuilderBase::getClass() { return *m_target; } //------------------------------------------------------------------------------------------------- void ClassBuilderBase::addBase(const Class& baseClass, int offset) { #ifdef _DEBUG { // First make sure that the base class is not already a base of the current class const uint32_t baseId = baseClass.id(); const Class::BaseVector& bases = m_target->m_bases; const size_t numberOfBases = bases.size(); for (size_t i = 0; i < numberOfBases; ++i) { assert(bases[i].base->id() != baseId); } } #endif // Add the base metaclass to the bases of the current class Class::BaseInfo baseInfos; baseInfos.base = &baseClass; baseInfos.offset = offset; m_target->m_bases.push_back(baseInfos); { // Copy all properties of the base class into the current class Class::SortedPropertyVector& targetProperties = m_target->m_properties; const Class::SortedPropertyVector& baseProperties = baseClass.m_properties; const size_t numberOfProperties = baseProperties.size(); for (size_t i = 0; i < numberOfProperties; ++i) { const Class::PropertyEntry& basePropertyEntry = baseProperties[i]; // Replace any property that already exists with the same ID const uint32_t id = basePropertyEntry.id; Class::SortedPropertyVector::const_iterator iterator = std::lower_bound(targetProperties.cbegin(), targetProperties.cend(), id, Class::OrderByPropertyId()); if (iterator != targetProperties.end() && iterator._Ptr->id == id) { // Found, so just replace property iterator._Ptr->propertyPtr = basePropertyEntry.propertyPtr; } else { // Not found, insert new property targetProperties.emplace(iterator, Class::PropertyEntry(id, basePropertyEntry.propertyPtr)); } } } { // Copy all functions of the base class into the current class Class::SortedFunctionVector& targetFunctions = m_target->m_functions; const Class::SortedFunctionVector& baseFunctions = baseClass.m_functions; const size_t numberOfFunctions = baseFunctions.size(); for (size_t i = 0; i < numberOfFunctions; ++i) { const Class::FunctionEntry& baseFunctionEntry = baseFunctions[i]; // Replace any function that already exists with the same ID const uint32_t id = baseFunctionEntry.id; Class::SortedFunctionVector::const_iterator iterator = std::lower_bound(targetFunctions.cbegin(), targetFunctions.cend(), id, Class::OrderByFunctionId()); if (iterator != targetFunctions.end() && iterator._Ptr->id == id) { // Found, so just replace function iterator._Ptr->functionPtr = baseFunctionEntry.functionPtr; } else { // Not found, insert new function targetFunctions.emplace(iterator, Class::FunctionEntry(id, baseFunctionEntry.functionPtr)); } } } } //------------------------------------------------------------------------------------------------- void ClassBuilderBase::addConstructor(Constructor* constructor) { m_target->m_constructors.push_back(constructor); } //------------------------------------------------------------------------------------------------- void ClassBuilderBase::addProperty(Property* property) { // Retrieve the class' properties sorted by ID Class::SortedPropertyVector& properties = m_target->m_properties; // Replace any property that already exists with the same ID const uint32_t id = property->id(); Class::SortedPropertyVector::const_iterator iterator = std::lower_bound(properties.cbegin(), properties.cend(), id, Class::OrderByPropertyId()); if (iterator != properties.end() && iterator._Ptr->id == id) { // Found, so just replace property iterator._Ptr->propertyPtr = Class::PropertyPtr(property); } else { // Not found, insert new property properties.emplace(iterator, Class::PropertyEntry(id, Class::PropertyPtr(property))); } m_currentTagHolder = m_currentProperty = property; m_currentFunction = nullptr; } //------------------------------------------------------------------------------------------------- void ClassBuilderBase::addFunction(Function* function) { // Retrieve the class' functions sorted by ID Class::SortedFunctionVector& functions = m_target->m_functions; // Replace any function that already exists with the same ID const uint32_t id = function->id(); Class::SortedFunctionVector::const_iterator iterator = std::lower_bound(functions.cbegin(), functions.cend(), id, Class::OrderByFunctionId()); if (iterator != functions.end() && iterator._Ptr->id == id) { // Found, so just replace function iterator._Ptr->functionPtr = Class::FunctionPtr(function); } else { // Not found, insert new function functions.emplace(iterator, Class::FunctionEntry(id, Class::FunctionPtr(function))); } m_currentTagHolder = m_currentFunction = function; m_currentProperty = nullptr; } //------------------------------------------------------------------------------------------------- void ClassBuilderBase::addTag(const char* name, const detail::Getter<Value>& value) { assert(m_currentTagHolder); // Retrieve the tag holders tags sorted by ID const StringId id(name); TagHolder::SortedTagVector& tags = m_currentTagHolder->m_tags; // Replace any tag that already exists with the same ID TagHolder::SortedTagVector::const_iterator iterator = std::lower_bound(tags.cbegin(), tags.cend(), id, TagHolder::OrderByTagId()); if (iterator != tags.end() && iterator._Ptr->id == id) { // Found, so just replace tag value // -> Should not happen for efficiency reasons assert(false); iterator._Ptr->value = value; } else { // Not found, insert new tag tags.emplace(iterator, TagHolder::TagEntry(id, name, value)); } } } // namespace camp <|endoftext|>
<commit_before>/****************************************************************************** ** Filename: cutoffs.c ** Purpose: Routines to manipulate an array of class cutoffs. ** Author: Dan Johnson ** ** (c) Copyright Hewlett-Packard Company, 1988. ** 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 Files and Type Defines ----------------------------------------------------------------------------*/ #include <cstdio> #include <sstream> // for std::istringstream #include <string> // for std::string #include "classify.h" #include "helpers.h" #include "serialis.h" #include <tesseract/unichar.h> #define MAX_CUTOFF 1000 namespace tesseract { /** * Open file, read in all of the class-id/cutoff pairs * and insert them into the Cutoffs array. Cutoffs are * indexed in the array by class id. Unused entries in the * array are set to an arbitrarily high cutoff value. * @param fp file containing cutoff definitions * @param Cutoffs array to put cutoffs into */ void Classify::ReadNewCutoffs(TFile* fp, uint16_t* Cutoffs) { int Cutoff; if (shape_table_ != nullptr) { if (!shapetable_cutoffs_.DeSerialize(fp)) { tprintf("Error during read of shapetable pffmtable!\n"); } } for (int i = 0; i < MAX_NUM_CLASSES; i++) Cutoffs[i] = MAX_CUTOFF; const int kMaxLineSize = 100; char line[kMaxLineSize]; while (fp->FGets(line, kMaxLineSize) != nullptr) { std::string Class; CLASS_ID ClassId; std::istringstream stream(line); stream >> Class >> Cutoff; if (stream.fail()) { break; } if (Class.compare("NULL") == 0) { ClassId = unicharset.unichar_to_id(" "); } else { ClassId = unicharset.unichar_to_id(Class.c_str()); } ASSERT_HOST(ClassId >= 0 && ClassId < MAX_NUM_CLASSES); Cutoffs[ClassId] = Cutoff; } } } // namespace tesseract <commit_msg>Correctly read cutoff classes.<commit_after>/****************************************************************************** ** Filename: cutoffs.c ** Purpose: Routines to manipulate an array of class cutoffs. ** Author: Dan Johnson ** ** (c) Copyright Hewlett-Packard Company, 1988. ** 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 Files and Type Defines ----------------------------------------------------------------------------*/ #include <cstdio> #include <sstream> // for std::istringstream #include <string> // for std::string #include "classify.h" #include "helpers.h" #include "serialis.h" #include <tesseract/unichar.h> #define MAX_CUTOFF 1000 namespace tesseract { /** * Open file, read in all of the class-id/cutoff pairs * and insert them into the Cutoffs array. Cutoffs are * indexed in the array by class id. Unused entries in the * array are set to an arbitrarily high cutoff value. * @param fp file containing cutoff definitions * @param Cutoffs array to put cutoffs into */ void Classify::ReadNewCutoffs(TFile* fp, uint16_t* Cutoffs) { int Cutoff; if (shape_table_ != nullptr) { if (!shapetable_cutoffs_.DeSerialize(fp)) { tprintf("Error during read of shapetable pffmtable!\n"); } } for (int i = 0; i < MAX_NUM_CLASSES; i++) Cutoffs[i] = MAX_CUTOFF; const int kMaxLineSize = 100; char line[kMaxLineSize]; while (fp->FGets(line, kMaxLineSize) != nullptr) { std::string Class; auto p = line; while (*p != ' ' && p - line < kMaxLineSize) Class.push_back(*p++); CLASS_ID ClassId; // do not use stream to extract Class as it may contain unicode spaces (0xA0) // they are eaten by stream, but they are a part of Class std::istringstream stream(p); stream >> Cutoff; if (stream.fail()) { break; } if (Class.compare("NULL") == 0) { ClassId = unicharset.unichar_to_id(" "); } else { ClassId = unicharset.unichar_to_id(Class.c_str()); } ASSERT_HOST(ClassId >= 0 && ClassId < MAX_NUM_CLASSES); Cutoffs[ClassId] = Cutoff; } } } // namespace tesseract <|endoftext|>
<commit_before>/*********************************************************************************************************************** * Copyright (C) 2016 Andrew Zonenberg and contributors * * * * This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General * * Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) * * any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * * more details. * * * * You should have received a copy of the GNU Lesser General Public License along with this program; if not, you may * * find one here: * * https://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt * * or you may search the http://www.gnu.org website for the version 2.1 license, or you may write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * **********************************************************************************************************************/ #include <log.h> #include <Greenpak4.h> using namespace std; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Construction / destruction Greenpak4ShiftRegister::Greenpak4ShiftRegister( Greenpak4Device* device, unsigned int matrix, unsigned int ibase, unsigned int oword, unsigned int cbase) : Greenpak4BitstreamEntity(device, matrix, ibase, oword, cbase) , m_clock(device->GetGround()) , m_input(device->GetGround()) , m_reset(device->GetPower()) //If we hold the shreg in reset forever, GreenPAK Designer gives a DRC error. //This is harmless if the shreg is unused, but warnings are bad so don't do that , m_delayA(1) //default must be 0xf so that unused ones show as unused , m_delayB(1) , m_invertA(false) { } Greenpak4ShiftRegister::~Greenpak4ShiftRegister() { } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Accessors string Greenpak4ShiftRegister::GetDescription() { char buf[128]; snprintf(buf, sizeof(buf), "SHREG_%u", m_matrix); return string(buf); } vector<string> Greenpak4ShiftRegister::GetInputPorts() const { vector<string> r; r.push_back("IN"); r.push_back("nRST"); r.push_back("CLK"); return r; } void Greenpak4ShiftRegister::SetInput(string port, Greenpak4EntityOutput src) { if(port == "IN") m_input = src; else if(port == "nRST") m_reset = src; else if(port == "CLK") m_clock = src; //ignore anything else silently (should not be possible since synthesis would error out) } vector<string> Greenpak4ShiftRegister::GetOutputPorts() const { vector<string> r; r.push_back("OUTA"); r.push_back("OUTB"); return r; } unsigned int Greenpak4ShiftRegister::GetOutputNetNumber(string port) { if(port == "OUTA") return m_outputBaseWord + 1; else if(port == "OUTB") return m_outputBaseWord; else return -1; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Serialization bool Greenpak4ShiftRegister::CommitChanges() { //Get our cell, or bail if we're unassigned auto ncell = dynamic_cast<Greenpak4NetlistCell*>(GetNetlistEntity()); if(ncell == NULL) return true; if(ncell->HasParameter("OUTA_TAP")) { m_delayA = atoi(ncell->m_parameters["OUTA_TAP"].c_str()); if( (m_delayA < 1) || (m_delayA > 16) ) { LogError("Shift register OUTA_TAP must be in [1, 16]\n"); return false; } } if(ncell->HasParameter("OUTB_TAP")) { m_delayB = atoi(ncell->m_parameters["OUTB_TAP"].c_str()); if( (m_delayB < 1) || (m_delayB > 16) ) { LogError("Shift register OUTB_TAP must be in [1, 16]\n"); return false; } } if(ncell->HasParameter("OUTA_INVERT")) m_invertA = atoi(ncell->m_parameters["OUTA_INVERT"].c_str()); return true; } bool Greenpak4ShiftRegister::Load(bool* /*bitstream*/) { //TODO: Do our inputs LogError("Unimplemented\n"); return false; } bool Greenpak4ShiftRegister::Save(bool* bitstream) { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // INPUT BUS if(!WriteMatrixSelector(bitstream, m_inputBaseWord + 0, m_clock)) return false; if(!WriteMatrixSelector(bitstream, m_inputBaseWord + 1, m_input)) return false; if(!WriteMatrixSelector(bitstream, m_inputBaseWord + 2, m_reset)) return false; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Configuration //Tap B comes first (considered output 0 in Silego docs but we flip so that A has the inverter) //Note that we use 0-based tap positions, while the parameter to the shreg is 1-based delay in clocks int delayB = m_delayB - 1; bitstream[m_configBase + 0] = (delayB & 1) ? true : false; bitstream[m_configBase + 1] = (delayB & 2) ? true : false; bitstream[m_configBase + 2] = (delayB & 4) ? true : false; bitstream[m_configBase + 3] = (delayB & 8) ? true : false; //then tap A int delayA = m_delayA - 1; bitstream[m_configBase + 4] = (delayA & 1) ? true : false; bitstream[m_configBase + 5] = (delayA & 2) ? true : false; bitstream[m_configBase + 6] = (delayA & 4) ? true : false; bitstream[m_configBase + 7] = (delayA & 8) ? true : false; //then invert flag bitstream[m_configBase + 8] = m_invertA; return true; } <commit_msg>greenpak4: Unused shift registers are now held in reset again (proper idle state for unused shregs)<commit_after>/*********************************************************************************************************************** * Copyright (C) 2016 Andrew Zonenberg and contributors * * * * This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General * * Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) * * any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * * more details. * * * * You should have received a copy of the GNU Lesser General Public License along with this program; if not, you may * * find one here: * * https://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt * * or you may search the http://www.gnu.org website for the version 2.1 license, or you may write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * **********************************************************************************************************************/ #include <log.h> #include <Greenpak4.h> using namespace std; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Construction / destruction Greenpak4ShiftRegister::Greenpak4ShiftRegister( Greenpak4Device* device, unsigned int matrix, unsigned int ibase, unsigned int oword, unsigned int cbase) : Greenpak4BitstreamEntity(device, matrix, ibase, oword, cbase) , m_clock(device->GetGround()) , m_input(device->GetGround()) , m_reset(device->GetGround()) //Hold shreg in reset if not used , m_delayA(1) //default must be 0xf so that unused ones show as unused , m_delayB(1) , m_invertA(false) { } Greenpak4ShiftRegister::~Greenpak4ShiftRegister() { } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Accessors string Greenpak4ShiftRegister::GetDescription() { char buf[128]; snprintf(buf, sizeof(buf), "SHREG_%u", m_matrix); return string(buf); } vector<string> Greenpak4ShiftRegister::GetInputPorts() const { vector<string> r; r.push_back("IN"); r.push_back("nRST"); r.push_back("CLK"); return r; } void Greenpak4ShiftRegister::SetInput(string port, Greenpak4EntityOutput src) { if(port == "IN") m_input = src; else if(port == "nRST") m_reset = src; else if(port == "CLK") m_clock = src; //ignore anything else silently (should not be possible since synthesis would error out) } vector<string> Greenpak4ShiftRegister::GetOutputPorts() const { vector<string> r; r.push_back("OUTA"); r.push_back("OUTB"); return r; } unsigned int Greenpak4ShiftRegister::GetOutputNetNumber(string port) { if(port == "OUTA") return m_outputBaseWord + 1; else if(port == "OUTB") return m_outputBaseWord; else return -1; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Serialization bool Greenpak4ShiftRegister::CommitChanges() { //Get our cell, or bail if we're unassigned auto ncell = dynamic_cast<Greenpak4NetlistCell*>(GetNetlistEntity()); if(ncell == NULL) return true; if(ncell->HasParameter("OUTA_TAP")) { m_delayA = atoi(ncell->m_parameters["OUTA_TAP"].c_str()); if( (m_delayA < 1) || (m_delayA > 16) ) { LogError("Shift register OUTA_TAP must be in [1, 16]\n"); return false; } } if(ncell->HasParameter("OUTB_TAP")) { m_delayB = atoi(ncell->m_parameters["OUTB_TAP"].c_str()); if( (m_delayB < 1) || (m_delayB > 16) ) { LogError("Shift register OUTB_TAP must be in [1, 16]\n"); return false; } } if(ncell->HasParameter("OUTA_INVERT")) m_invertA = atoi(ncell->m_parameters["OUTA_INVERT"].c_str()); return true; } bool Greenpak4ShiftRegister::Load(bool* /*bitstream*/) { //TODO: Do our inputs LogError("Unimplemented\n"); return false; } bool Greenpak4ShiftRegister::Save(bool* bitstream) { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // INPUT BUS if(!WriteMatrixSelector(bitstream, m_inputBaseWord + 0, m_clock)) return false; if(!WriteMatrixSelector(bitstream, m_inputBaseWord + 1, m_input)) return false; if(!WriteMatrixSelector(bitstream, m_inputBaseWord + 2, m_reset)) return false; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Configuration //Tap B comes first (considered output 0 in Silego docs but we flip so that A has the inverter) //Note that we use 0-based tap positions, while the parameter to the shreg is 1-based delay in clocks int delayB = m_delayB - 1; bitstream[m_configBase + 0] = (delayB & 1) ? true : false; bitstream[m_configBase + 1] = (delayB & 2) ? true : false; bitstream[m_configBase + 2] = (delayB & 4) ? true : false; bitstream[m_configBase + 3] = (delayB & 8) ? true : false; //then tap A int delayA = m_delayA - 1; bitstream[m_configBase + 4] = (delayA & 1) ? true : false; bitstream[m_configBase + 5] = (delayA & 2) ? true : false; bitstream[m_configBase + 6] = (delayA & 4) ? true : false; bitstream[m_configBase + 7] = (delayA & 8) ? true : false; //then invert flag bitstream[m_configBase + 8] = m_invertA; return true; } <|endoftext|>
<commit_before>// Copyright (c) 2012 Intel Corp // Copyright (c) 2012 The Chromium Authors // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co // pies 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 al // l copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM // PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES // S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS // OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH // ETHER 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 "content/nw/src/nw_package.h" #include <vector> #include "base/command_line.h" #include "base/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/json/json_file_value_serializer.h" #include "base/string_split.h" #include "base/string_util.h" #include "base/threading/thread_restrictions.h" #include "base/values.h" #include "chrome/common/zip.h" #include "content/nw/src/common/shell_switches.h" #include "googleurl/src/gurl.h" #include "grit/nw_resources.h" #include "net/base/escape.h" #include "third_party/node/deps/uv/include/uv.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/image/image.h" #include "ui/gfx/image/image_skia_rep.h" #include "webkit/glue/image_decoder.h" namespace nw { namespace { #ifndef PATH_MAX #define PATH_MAX MAX_PATH #endif bool MakePathAbsolute(FilePath* file_path) { DCHECK(file_path); FilePath current_directory; if (!file_util::GetCurrentDirectory(&current_directory)) return false; if (file_path->IsAbsolute()) return true; if (current_directory.empty()) return file_util::AbsolutePath(file_path); if (!current_directory.IsAbsolute()) return false; *file_path = current_directory.Append(*file_path); return true; } FilePath GetSelfPath() { CommandLine* command_line = CommandLine::ForCurrentProcess(); FilePath path; size_t size = 2*PATH_MAX; char* execPath = new char[size]; if (uv_exepath(execPath, &size) == 0) { path = FilePath::FromUTF8Unsafe(std::string(execPath, size)); } else { path = FilePath(command_line->GetProgram()); } #if defined(OS_MACOSX) // Find if we have node-webkit.app/Resources/app.nw. path = path.DirName().DirName().Append("Resources").Append("app.nw"); #endif return path; } void RelativePathToURI(FilePath root, base::DictionaryValue* manifest) { std::string old; if (!manifest->GetString(switches::kmMain, &old)) return; // Don't append path if there is already a prefix if (MatchPattern(old, "*://*")) return; FilePath main_path = root.Append(FilePath::FromUTF8Unsafe(old)); manifest->SetString(switches::kmMain, std::string("file://") + main_path.AsUTF8Unsafe()); } std::wstring ASCIIToWide(const std::string& ascii) { DCHECK(IsStringASCII(ascii)) << ascii; return std::wstring(ascii.begin(), ascii.end()); } } // namespace Package::Package() : path_(GetSelfPath()), self_extract_(true) { // First try to extract self. if (InitFromPath()) return; // Then see if we have arguments and extract it. CommandLine* command_line = CommandLine::ForCurrentProcess(); const CommandLine::StringVector& args = command_line->GetArgs(); if (args.size() > 0) { self_extract_ = false; path_ = FilePath(args[0]); } else { // Try to load from the folder where the exe resides. // Note: self_extract_ is true here, otherwise a 'Invalid Package' error // would be triggered. path_ = GetSelfPath().DirName(); #if defined(OS_MACOSX) path_ = path_.DirName().DirName().DirName(); #endif } if (InitFromPath()) return; // Finally we init with default settings. self_extract_ = false; InitWithDefault(); } Package::Package(FilePath path) : path_(path), self_extract_(false) { if (!InitFromPath()) InitWithDefault(); } Package::~Package() { } FilePath Package::ConvertToAbsoutePath(const FilePath& path) { if (path.IsAbsolute()) return path; return this->path().Append(path); } bool Package::GetImage(const FilePath& icon_path, gfx::Image* image) { FilePath path = ConvertToAbsoutePath(icon_path); // Read the file from disk. std::string file_contents; if (path.empty() || !file_util::ReadFileToString(path, &file_contents)) return false; // Decode the bitmap using WebKit's image decoder. const unsigned char* data = reinterpret_cast<const unsigned char*>(file_contents.data()); webkit_glue::ImageDecoder decoder; scoped_ptr<SkBitmap> decoded(new SkBitmap()); // Note: This class only decodes bitmaps from extension resources. Chrome // doesn't (for security reasons) directly load extension resources provided // by the extension author, but instead decodes them in a separate // locked-down utility process. Only if the decoding succeeds is the image // saved from memory to disk and subsequently used in the Chrome UI. // Chrome is therefore decoding bitmaps here that were generated by Chrome. *decoded = decoder.Decode(data, file_contents.length()); if (decoded->empty()) return false; // Unable to decode. *image = gfx::Image(*decoded.release()); return true; } GURL Package::GetStartupURL() { std::string url; // Specify URL in --url CommandLine* command_line = CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kUrl)) { url = command_line->GetSwitchValueASCII(switches::kUrl); GURL gurl(url); if (!gurl.has_scheme()) return GURL(std::string("http://") + url); return gurl; } // Report if encountered errors. if (!error_page_url_.empty()) return GURL(error_page_url_); // Read from manifest. if (root()->GetString(switches::kmMain, &url)) return GURL(url); else return GURL("nw:blank"); } std::string Package::GetName() { std::string name("node-webkit"); root()->GetString(switches::kmName, &name); return name; } bool Package::GetUseNode() { bool use_node = true; root()->GetBoolean(switches::kmNodejs, &use_node); return use_node; } base::DictionaryValue* Package::window() { base::DictionaryValue* window; root()->GetDictionaryWithoutPathExpansion(switches::kmWindow, &window); return window; } bool Package::InitFromPath() { base::ThreadRestrictions::SetIOAllowed(true); if (!ExtractPath()) return false; // path_/package.json FilePath manifest_path = path_.AppendASCII("package.json"); if (!file_util::PathExists(manifest_path)) { if (!self_extract()) ReportError("Invalid package", "There is no 'package.json' in the package, please make " "sure the 'package.json' is in the root of the package."); return false; } // Parse file. std::string error; JSONFileValueSerializer serializer(manifest_path); scoped_ptr<Value> root(serializer.Deserialize(NULL, &error)); if (!root.get()) { ReportError("Unable to parse package.json", error.empty() ? "Failed to read the manifest file: " + manifest_path.AsUTF8Unsafe() : error); return false; } else if (!root->IsType(Value::TYPE_DICTIONARY)) { ReportError("Invalid package.json", "package.json's content should be a object type."); return false; } // Save result in global root_.reset(static_cast<DictionaryValue*>(root.release())); // Check fields const char* required_fields[] = { switches::kmMain, switches::kmName }; for (unsigned i = 0; i < arraysize(required_fields); i++) if (!root_->HasKey(required_fields[i])) { ReportError("Invalid package.json", std::string("Field '") + required_fields[i] + "'" " is required."); return false; } // Force window field no empty. if (!root_->HasKey(switches::kmWindow)) { base::DictionaryValue* window = new base::DictionaryValue(); window->SetString(switches::kmPosition, "center"); root_->Set(switches::kmWindow, window); } // Read chromium command line args. ReadChromiumArgs(); RelativePathToURI(path_, this->root()); return true; } void Package::InitWithDefault() { root_.reset(new base::DictionaryValue()); root()->SetString(switches::kmName, "node-webkit"); root()->SetString(switches::kmMain, "nw:blank"); base::DictionaryValue* window = new base::DictionaryValue(); root()->Set(switches::kmWindow, window); // Hide toolbar if specifed in the command line. if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kNoToolbar)) window->SetBoolean(switches::kmToolbar, false); // Window should show in center by default. window->SetString(switches::kmPosition, "center"); } bool Package::ExtractPath() { // Convert to absoulute path. if (!MakePathAbsolute(&path_)) { ReportError("Cannot extract package", "Path is invalid: " + path_.AsUTF8Unsafe()); return false; } // Read symbolic link. #if defined(OS_POSIX) FilePath target; if (file_util::ReadSymbolicLink(path_, &target)) path_ = target; #endif // If it's a file then try to extract from it. if (!file_util::DirectoryExists(path_)) { FilePath extracted_path; if (ExtractPackage(path_, &extracted_path)) { path_ = extracted_path; } else if (!self_extract()) { ReportError("Cannot extract package", "Failed to unzip the package file: " + path_.AsUTF8Unsafe()); return false; } } return true; } bool Package::ExtractPackage(const FilePath& zip_file, FilePath* where) { // Auto clean our temporary directory static scoped_ptr<base::ScopedTempDir> scoped_temp_dir; #if defined(OS_WIN) if (!file_util::CreateNewTempDirectory(L"nw", where)) { #else if (!file_util::CreateNewTempDirectory("nw", where)) { #endif ReportError("Cannot extract package", "Unable to create temporary directory."); return false; } scoped_temp_dir.reset(new base::ScopedTempDir()); if (!scoped_temp_dir->Set(*where)) { ReportError("Cannot extract package", "Unable to set temporary directory."); return false; } return zip::Unzip(zip_file, *where); } void Package::ReadChromiumArgs() { if (!root()->HasKey(switches::kmChromiumArgs)) return; std::string args; if (!root()->GetStringASCII(switches::kmChromiumArgs, &args)) return; std::vector<std::string> chromium_args; base::SplitString(args, ' ', &chromium_args); CommandLine* command_line = CommandLine::ForCurrentProcess(); for (unsigned i = 0; i < chromium_args.size(); ++i) { CommandLine::StringType key, value; #if defined(OS_WIN) // Note:: On Windows, the |CommandLine::StringType| will be |std::wstring|, // so the chromium_args[i] is not compatible. We convert the wstring to // string here is safe beacuse we use ASCII only. if (!IsSwitch(ASCIIToWide(chromium_args[i]), &key, &value)) continue; command_line->AppendSwitchASCII(WideToASCII(key), WideToASCII(value)); #elif if (!IsSwitch(chromium_args[i], &key, &value)) continue; command_line->AppendSwitchASCII(key, value); #endif } } void Package::ReportError(const std::string& title, const std::string& content) { if (!error_page_url_.empty()) return; const base::StringPiece template_html( ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_NW_PACKAGE_ERROR)); if (template_html.empty()) { // Print hand written error info if nw.pak doesn't exist. NOTREACHED() << "Unable to load error template."; error_page_url_ = "data:text/html;base64,VW5hYmxlIHRvIGZpbmQgbncucGFrLgo="; return; } std::vector<std::string> subst; subst.push_back(title); subst.push_back(content); error_page_url_ = "data:text/html;charset=utf-8," + net::EscapeQueryParamValue( ReplaceStringPlaceholders(template_html, subst, NULL), false); } } // namespace nw <commit_msg>Fix compilation error on 'elif'<commit_after>// Copyright (c) 2012 Intel Corp // Copyright (c) 2012 The Chromium Authors // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co // pies 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 al // l copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM // PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES // S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS // OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH // ETHER 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 "content/nw/src/nw_package.h" #include <vector> #include "base/command_line.h" #include "base/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/json/json_file_value_serializer.h" #include "base/string_split.h" #include "base/string_util.h" #include "base/threading/thread_restrictions.h" #include "base/values.h" #include "chrome/common/zip.h" #include "content/nw/src/common/shell_switches.h" #include "googleurl/src/gurl.h" #include "grit/nw_resources.h" #include "net/base/escape.h" #include "third_party/node/deps/uv/include/uv.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/image/image.h" #include "ui/gfx/image/image_skia_rep.h" #include "webkit/glue/image_decoder.h" namespace nw { namespace { #ifndef PATH_MAX #define PATH_MAX MAX_PATH #endif bool MakePathAbsolute(FilePath* file_path) { DCHECK(file_path); FilePath current_directory; if (!file_util::GetCurrentDirectory(&current_directory)) return false; if (file_path->IsAbsolute()) return true; if (current_directory.empty()) return file_util::AbsolutePath(file_path); if (!current_directory.IsAbsolute()) return false; *file_path = current_directory.Append(*file_path); return true; } FilePath GetSelfPath() { CommandLine* command_line = CommandLine::ForCurrentProcess(); FilePath path; size_t size = 2*PATH_MAX; char* execPath = new char[size]; if (uv_exepath(execPath, &size) == 0) { path = FilePath::FromUTF8Unsafe(std::string(execPath, size)); } else { path = FilePath(command_line->GetProgram()); } #if defined(OS_MACOSX) // Find if we have node-webkit.app/Resources/app.nw. path = path.DirName().DirName().Append("Resources").Append("app.nw"); #endif return path; } void RelativePathToURI(FilePath root, base::DictionaryValue* manifest) { std::string old; if (!manifest->GetString(switches::kmMain, &old)) return; // Don't append path if there is already a prefix if (MatchPattern(old, "*://*")) return; FilePath main_path = root.Append(FilePath::FromUTF8Unsafe(old)); manifest->SetString(switches::kmMain, std::string("file://") + main_path.AsUTF8Unsafe()); } std::wstring ASCIIToWide(const std::string& ascii) { DCHECK(IsStringASCII(ascii)) << ascii; return std::wstring(ascii.begin(), ascii.end()); } } // namespace Package::Package() : path_(GetSelfPath()), self_extract_(true) { // First try to extract self. if (InitFromPath()) return; // Then see if we have arguments and extract it. CommandLine* command_line = CommandLine::ForCurrentProcess(); const CommandLine::StringVector& args = command_line->GetArgs(); if (args.size() > 0) { self_extract_ = false; path_ = FilePath(args[0]); } else { // Try to load from the folder where the exe resides. // Note: self_extract_ is true here, otherwise a 'Invalid Package' error // would be triggered. path_ = GetSelfPath().DirName(); #if defined(OS_MACOSX) path_ = path_.DirName().DirName().DirName(); #endif } if (InitFromPath()) return; // Finally we init with default settings. self_extract_ = false; InitWithDefault(); } Package::Package(FilePath path) : path_(path), self_extract_(false) { if (!InitFromPath()) InitWithDefault(); } Package::~Package() { } FilePath Package::ConvertToAbsoutePath(const FilePath& path) { if (path.IsAbsolute()) return path; return this->path().Append(path); } bool Package::GetImage(const FilePath& icon_path, gfx::Image* image) { FilePath path = ConvertToAbsoutePath(icon_path); // Read the file from disk. std::string file_contents; if (path.empty() || !file_util::ReadFileToString(path, &file_contents)) return false; // Decode the bitmap using WebKit's image decoder. const unsigned char* data = reinterpret_cast<const unsigned char*>(file_contents.data()); webkit_glue::ImageDecoder decoder; scoped_ptr<SkBitmap> decoded(new SkBitmap()); // Note: This class only decodes bitmaps from extension resources. Chrome // doesn't (for security reasons) directly load extension resources provided // by the extension author, but instead decodes them in a separate // locked-down utility process. Only if the decoding succeeds is the image // saved from memory to disk and subsequently used in the Chrome UI. // Chrome is therefore decoding bitmaps here that were generated by Chrome. *decoded = decoder.Decode(data, file_contents.length()); if (decoded->empty()) return false; // Unable to decode. *image = gfx::Image(*decoded.release()); return true; } GURL Package::GetStartupURL() { std::string url; // Specify URL in --url CommandLine* command_line = CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kUrl)) { url = command_line->GetSwitchValueASCII(switches::kUrl); GURL gurl(url); if (!gurl.has_scheme()) return GURL(std::string("http://") + url); return gurl; } // Report if encountered errors. if (!error_page_url_.empty()) return GURL(error_page_url_); // Read from manifest. if (root()->GetString(switches::kmMain, &url)) return GURL(url); else return GURL("nw:blank"); } std::string Package::GetName() { std::string name("node-webkit"); root()->GetString(switches::kmName, &name); return name; } bool Package::GetUseNode() { bool use_node = true; root()->GetBoolean(switches::kmNodejs, &use_node); return use_node; } base::DictionaryValue* Package::window() { base::DictionaryValue* window; root()->GetDictionaryWithoutPathExpansion(switches::kmWindow, &window); return window; } bool Package::InitFromPath() { base::ThreadRestrictions::SetIOAllowed(true); if (!ExtractPath()) return false; // path_/package.json FilePath manifest_path = path_.AppendASCII("package.json"); if (!file_util::PathExists(manifest_path)) { if (!self_extract()) ReportError("Invalid package", "There is no 'package.json' in the package, please make " "sure the 'package.json' is in the root of the package."); return false; } // Parse file. std::string error; JSONFileValueSerializer serializer(manifest_path); scoped_ptr<Value> root(serializer.Deserialize(NULL, &error)); if (!root.get()) { ReportError("Unable to parse package.json", error.empty() ? "Failed to read the manifest file: " + manifest_path.AsUTF8Unsafe() : error); return false; } else if (!root->IsType(Value::TYPE_DICTIONARY)) { ReportError("Invalid package.json", "package.json's content should be a object type."); return false; } // Save result in global root_.reset(static_cast<DictionaryValue*>(root.release())); // Check fields const char* required_fields[] = { switches::kmMain, switches::kmName }; for (unsigned i = 0; i < arraysize(required_fields); i++) if (!root_->HasKey(required_fields[i])) { ReportError("Invalid package.json", std::string("Field '") + required_fields[i] + "'" " is required."); return false; } // Force window field no empty. if (!root_->HasKey(switches::kmWindow)) { base::DictionaryValue* window = new base::DictionaryValue(); window->SetString(switches::kmPosition, "center"); root_->Set(switches::kmWindow, window); } // Read chromium command line args. ReadChromiumArgs(); RelativePathToURI(path_, this->root()); return true; } void Package::InitWithDefault() { root_.reset(new base::DictionaryValue()); root()->SetString(switches::kmName, "node-webkit"); root()->SetString(switches::kmMain, "nw:blank"); base::DictionaryValue* window = new base::DictionaryValue(); root()->Set(switches::kmWindow, window); // Hide toolbar if specifed in the command line. if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kNoToolbar)) window->SetBoolean(switches::kmToolbar, false); // Window should show in center by default. window->SetString(switches::kmPosition, "center"); } bool Package::ExtractPath() { // Convert to absoulute path. if (!MakePathAbsolute(&path_)) { ReportError("Cannot extract package", "Path is invalid: " + path_.AsUTF8Unsafe()); return false; } // Read symbolic link. #if defined(OS_POSIX) FilePath target; if (file_util::ReadSymbolicLink(path_, &target)) path_ = target; #endif // If it's a file then try to extract from it. if (!file_util::DirectoryExists(path_)) { FilePath extracted_path; if (ExtractPackage(path_, &extracted_path)) { path_ = extracted_path; } else if (!self_extract()) { ReportError("Cannot extract package", "Failed to unzip the package file: " + path_.AsUTF8Unsafe()); return false; } } return true; } bool Package::ExtractPackage(const FilePath& zip_file, FilePath* where) { // Auto clean our temporary directory static scoped_ptr<base::ScopedTempDir> scoped_temp_dir; #if defined(OS_WIN) if (!file_util::CreateNewTempDirectory(L"nw", where)) { #else if (!file_util::CreateNewTempDirectory("nw", where)) { #endif ReportError("Cannot extract package", "Unable to create temporary directory."); return false; } scoped_temp_dir.reset(new base::ScopedTempDir()); if (!scoped_temp_dir->Set(*where)) { ReportError("Cannot extract package", "Unable to set temporary directory."); return false; } return zip::Unzip(zip_file, *where); } void Package::ReadChromiumArgs() { if (!root()->HasKey(switches::kmChromiumArgs)) return; std::string args; if (!root()->GetStringASCII(switches::kmChromiumArgs, &args)) return; std::vector<std::string> chromium_args; base::SplitString(args, ' ', &chromium_args); CommandLine* command_line = CommandLine::ForCurrentProcess(); for (unsigned i = 0; i < chromium_args.size(); ++i) { CommandLine::StringType key, value; #if defined(OS_WIN) // Note:: On Windows, the |CommandLine::StringType| will be |std::wstring|, // so the chromium_args[i] is not compatible. We convert the wstring to // string here is safe beacuse we use ASCII only. if (!IsSwitch(ASCIIToWide(chromium_args[i]), &key, &value)) continue; command_line->AppendSwitchASCII(WideToASCII(key), WideToASCII(value)); #else if (!IsSwitch(chromium_args[i], &key, &value)) continue; command_line->AppendSwitchASCII(key, value); #endif } } void Package::ReportError(const std::string& title, const std::string& content) { if (!error_page_url_.empty()) return; const base::StringPiece template_html( ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_NW_PACKAGE_ERROR)); if (template_html.empty()) { // Print hand written error info if nw.pak doesn't exist. NOTREACHED() << "Unable to load error template."; error_page_url_ = "data:text/html;base64,VW5hYmxlIHRvIGZpbmQgbncucGFrLgo="; return; } std::vector<std::string> subst; subst.push_back(title); subst.push_back(content); error_page_url_ = "data:text/html;charset=utf-8," + net::EscapeQueryParamValue( ReplaceStringPlaceholders(template_html, subst, NULL), false); } } // namespace nw <|endoftext|>
<commit_before> #include "astronomy/date.hpp" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "testing_utilities/almost_equals.hpp" #include "testing_utilities/numerics.hpp" namespace principia { namespace astronomy { namespace internal_date { using quantities::si::Micro; using testing_utilities::AbsoluteError; using testing_utilities::AlmostEquals; using ::testing::AllOf; using ::testing::Eq; using ::testing::Ge; using ::testing::Lt; class DateTest : public testing::Test {}; using DateDeathTest = DateTest; // The checks are giant boolean expressions which are entirely repeated in the // error message; we try to match the relevant part. #if !((PRINCIPIA_COMPILER_CLANG || PRINCIPIA_COMPILER_CLANG_CL) && \ WE_LIKE_N3599) TEST_F(DateDeathTest, InvalidCalendarDate) { EXPECT_DEATH("2001-04-00T12:00:00"_TT, "day >= 1"); EXPECT_DEATH("2001-02-29T12:00:00"_TT, "day <= month_length"); EXPECT_DEATH("2001-03-32T12:00:00"_TT, "day <= month_length"); EXPECT_DEATH("2001-04-31T12:00:00"_TT, "day <= month_length"); EXPECT_DEATH("2001-00-01T12:00:00"_TT, "month >= 1"); EXPECT_DEATH("2001-13-01T12:00:00"_TT, "month <= 12"); EXPECT_DEATH("2001-00-01T12:00:00"_TT, "month >= 1"); EXPECT_DEATH("1582-01-01T12:00:00"_TT, "year >= 1583"); } TEST_F(DateDeathTest, InvalidTime) { EXPECT_DEATH("2001-01-01T25:00:00"_TT, "hour_ <= 23"); EXPECT_DEATH("2001-01-01T24:01:00"_TT, "minute_ == 0"); EXPECT_DEATH("2001-01-01T24:00:01"_TT, "second_ == 0"); EXPECT_DEATH("2001-01-01T00:60:00"_TT, "minute_ <= 59"); EXPECT_DEATH("2001-01-01T00:00:60"_TT, "second_ <= 59"); EXPECT_DEATH("2001-01-01T23:59:61"_TT, "second_ == 60"); } TEST_F(DateDeathTest, InvalidDateTime) { EXPECT_DEATH("2001-01-01T23:59:60"_TT, ""); } #endif namespace { constexpr Instant j2000_week = "1999-W52-6T12:00:00"_TT; constexpr Instant j2000_from_tt = "2000-01-01T12:00:00"_TT; constexpr Instant j2000_from_tai = "2000-01-01T11:59:27,816"_TAI; constexpr Instant j2000_from_utc = "2000-01-01T11:58:55,816"_UTC; constexpr Instant j2000_tai = "2000-01-01T12:00:00"_TAI; constexpr Instant j2000_tai_from_tt = "2000-01-01T12:00:32,184"_TT; static_assert(j2000_week == J2000, ""); static_assert(j2000_from_tt == J2000, ""); static_assert(j2000_from_tai == J2000, ""); static_assert(j2000_from_utc == J2000, ""); static_assert(j2000_tai == j2000_tai_from_tt, ""); static_assert(j2000_tai - J2000 == 32.184 * Second, ""); // Check that week dates that go to the previous year work. static_assert("1914-W01-1T00:00:00"_TT == "19131229T000000"_TT, ""); } // namespace TEST_F(DateTest, ReferenceDates) { EXPECT_THAT("1858-11-17T00:00:00"_TT, Eq(ModifiedJulianDate(0))); EXPECT_THAT(j2000_week, Eq(J2000)); EXPECT_THAT(j2000_from_tt, Eq(J2000)); EXPECT_THAT(j2000_from_tai, Eq(J2000)); EXPECT_THAT(j2000_from_utc, Eq(J2000)); EXPECT_THAT(j2000_tai, Eq(j2000_tai_from_tt)); EXPECT_THAT(j2000_tai - J2000, Eq(32.184 * Second)); // Besselian epochs. constexpr Instant B1900 = "1899-12-31T00:00:00"_TT + 0.8135 * Day; Instant const JD2415020_3135 = JulianDate(2415020.3135); EXPECT_THAT(B1900, AlmostEquals(JD2415020_3135, 51)); EXPECT_THAT(testing_utilities::AbsoluteError(JD2415020_3135, B1900), AllOf(Ge(10 * Micro(Second)), Lt(100 * Micro(Second)))); constexpr Instant B1950 = "1949-12-31T00:00:00"_TT + 0.9235 * Day; Instant const JD2433282_4235 = JulianDate(2433282.4235); EXPECT_THAT(B1950, AlmostEquals(JD2433282_4235, 26)); EXPECT_THAT(testing_utilities::AbsoluteError(JD2433282_4235, B1950), AllOf(Ge(1 * Micro(Second)), Lt(10 * Micro(Second)))); } TEST_F(DateTest, LeapSecond) { Instant const eleven_fifty_nine_and_fifty_eight_seconds = "2015-06-30T23:59:58"_UTC; EXPECT_THAT(eleven_fifty_nine_and_fifty_eight_seconds + 1 * Second, Eq("2015-06-30T23:59:59"_UTC)); EXPECT_THAT(eleven_fifty_nine_and_fifty_eight_seconds + 1.5 * Second, Eq("2015-06-30T23:59:59,5"_UTC)); EXPECT_THAT(eleven_fifty_nine_and_fifty_eight_seconds + 2 * Second, Eq("2015-06-30T23:59:60"_UTC)); EXPECT_THAT(eleven_fifty_nine_and_fifty_eight_seconds + 2.5 * Second, Eq("2015-06-30T23:59:60,5"_UTC)); EXPECT_THAT(eleven_fifty_nine_and_fifty_eight_seconds + 3 * Second, Eq("2015-06-30T24:00:00"_UTC)); EXPECT_THAT(eleven_fifty_nine_and_fifty_eight_seconds + 3 * Second, Eq("2015-07-01T00:00:00"_UTC)); } } // namespace internal_date } // namespace astronomy } // namespace principia <commit_msg>Test.<commit_after> #include "astronomy/date.hpp" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "testing_utilities/almost_equals.hpp" #include "testing_utilities/numerics.hpp" namespace principia { namespace astronomy { namespace internal_date { using quantities::si::Micro; using testing_utilities::AbsoluteError; using testing_utilities::AlmostEquals; using ::testing::AllOf; using ::testing::Eq; using ::testing::Ge; using ::testing::Lt; class DateTest : public testing::Test {}; using DateDeathTest = DateTest; // The checks are giant boolean expressions which are entirely repeated in the // error message; we try to match the relevant part. #if !((PRINCIPIA_COMPILER_CLANG || PRINCIPIA_COMPILER_CLANG_CL) && \ WE_LIKE_N3599) TEST_F(DateDeathTest, InvalidCalendarDate) { EXPECT_DEATH("2001-04-00T12:00:00"_TT, "day >= 1"); EXPECT_DEATH("2001-02-29T12:00:00"_TT, "day <= month_length"); EXPECT_DEATH("2001-03-32T12:00:00"_TT, "day <= month_length"); EXPECT_DEATH("2001-04-31T12:00:00"_TT, "day <= month_length"); EXPECT_DEATH("2001-00-01T12:00:00"_TT, "month >= 1"); EXPECT_DEATH("2001-13-01T12:00:00"_TT, "month <= 12"); EXPECT_DEATH("2001-00-01T12:00:00"_TT, "month >= 1"); EXPECT_DEATH("1582-01-01T12:00:00"_TT, "year >= 1583"); } TEST_F(DateDeathTest, InvalidTime) { EXPECT_DEATH("2001-01-01T25:00:00"_TT, "hour_ <= 23"); EXPECT_DEATH("2001-01-01T24:01:00"_TT, "minute_ == 0"); EXPECT_DEATH("2001-01-01T24:00:01"_TT, "second_ == 0"); EXPECT_DEATH("2001-01-01T00:60:00"_TT, "minute_ <= 59"); EXPECT_DEATH("2001-01-01T00:00:60"_TT, "second_ <= 59"); EXPECT_DEATH("2001-01-01T23:59:61"_TT, "second_ == 60"); } TEST_F(DateDeathTest, InvalidDateTime) { EXPECT_DEATH("2001-01-01T23:59:60"_TT, ""); } #endif namespace { constexpr Instant j2000_week = "1999-W52-6T12:00:00"_TT; constexpr Instant j2000_from_tt = "2000-01-01T12:00:00"_TT; constexpr Instant j2000_from_tai = "2000-01-01T11:59:27,816"_TAI; constexpr Instant j2000_from_utc = "2000-01-01T11:58:55,816"_UTC; constexpr Instant j2000_tai = "2000-01-01T12:00:00"_TAI; constexpr Instant j2000_tai_from_tt = "2000-01-01T12:00:32,184"_TT; static_assert(j2000_week == J2000, ""); static_assert(j2000_from_tt == J2000, ""); static_assert(j2000_from_tai == J2000, ""); static_assert(j2000_from_utc == J2000, ""); static_assert(j2000_tai == j2000_tai_from_tt, ""); static_assert(j2000_tai - J2000 == 32.184 * Second, ""); // Check that week dates that go to the previous year work. static_assert("1914-W01-1T00:00:00"_TT == "19131229T000000"_TT, ""); } // namespace TEST_F(DateTest, ReferenceDates) { EXPECT_THAT("1858-11-17T00:00:00"_TT, Eq(ModifiedJulianDate(0))); EXPECT_THAT(j2000_week, Eq(J2000)); EXPECT_THAT(j2000_from_tt, Eq(J2000)); EXPECT_THAT(j2000_from_tai, Eq(J2000)); EXPECT_THAT(j2000_from_utc, Eq(J2000)); EXPECT_THAT(j2000_tai, Eq(j2000_tai_from_tt)); EXPECT_THAT(j2000_tai - J2000, Eq(32.184 * Second)); // Besselian epochs. constexpr Instant B1900 = "1899-12-31T00:00:00"_TT + 0.8135 * Day; Instant const JD2415020_3135 = JulianDate(2415020.3135); EXPECT_THAT(B1900, AlmostEquals(JD2415020_3135, 51)); EXPECT_THAT(testing_utilities::AbsoluteError(JD2415020_3135, B1900), AllOf(Ge(10 * Micro(Second)), Lt(100 * Micro(Second)))); constexpr Instant B1950 = "1949-12-31T00:00:00"_TT + 0.9235 * Day; Instant const JD2433282_4235 = JulianDate(2433282.4235); EXPECT_THAT(B1950, AlmostEquals(JD2433282_4235, 26)); EXPECT_THAT(testing_utilities::AbsoluteError(JD2433282_4235, B1950), AllOf(Ge(1 * Micro(Second)), Lt(10 * Micro(Second)))); } TEST_F(DateTest, LeapSecond) { Instant const eleven_fifty_nine_and_fifty_eight_seconds = "2015-06-30T23:59:58"_UTC; EXPECT_THAT(eleven_fifty_nine_and_fifty_eight_seconds + 1 * Second, Eq("2015-06-30T23:59:59"_UTC)); EXPECT_THAT(eleven_fifty_nine_and_fifty_eight_seconds + 1.5 * Second, Eq("2015-06-30T23:59:59,5"_UTC)); EXPECT_THAT(eleven_fifty_nine_and_fifty_eight_seconds + 2 * Second, Eq("2015-06-30T23:59:60"_UTC)); EXPECT_THAT(eleven_fifty_nine_and_fifty_eight_seconds + 2.5 * Second, Eq("2015-06-30T23:59:60,5"_UTC)); EXPECT_THAT(eleven_fifty_nine_and_fifty_eight_seconds + 3 * Second, Eq("2015-06-30T24:00:00"_UTC)); EXPECT_THAT(eleven_fifty_nine_and_fifty_eight_seconds + 3 * Second, Eq("2015-07-01T00:00:00"_UTC)); constexpr Instant end_of_december_2016 = "2016-12-31T24:00:00"_UTC; EXPECT_THAT(end_of_december_2016 - 2 * Second, Eq("2016-12-31T23:59:59"_UTC)); EXPECT_THAT(end_of_december_2016 - 1 * Second, Eq("2016-12-31T23:59:60"_UTC)); EXPECT_THAT(end_of_december_2016 - 0 * Second, Eq("2017-01-01T00:00:00"_UTC)); EXPECT_THAT("2016-12-31T23:59:59"_UTC - "2016-12-31T23:59:59"_TAI, Eq(36 * Second)); EXPECT_THAT("2017-01-01T00:00:00"_UTC - "2017-01-01T00:00:00"_TAI, Eq(37 * Second)); } } // namespace internal_date } // namespace astronomy } // namespace principia <|endoftext|>
<commit_before>#include <iostream> #include <curl/curl.h> #include <string> #include <sstream> #include <fstream> #include "rapidjson/document.h" #include "geojson.h" #include "tileData.h" #include "earcut.hpp" #include "objexport.h" #include "aobaker.h" namespace mapbox { namespace util { template <> struct nth<0, Point> { inline static float get(const Point &t) { return t.x; }; }; template <> struct nth<1, Point> { inline static float get(const Point &t) { return t.y; }; }; }} struct PolygonVertex { glm::vec3 position; glm::vec3 normal; }; struct PolygonMesh { std::vector<unsigned int> indices; std::vector<PolygonVertex> vertices; }; static size_t write_data(void *_ptr, size_t _size, size_t _nmemb, void *_stream) { ((std::stringstream*) _stream)->write(reinterpret_cast<char *>(_ptr), _size * _nmemb); return _size * _nmemb; } std::unique_ptr<TileData> downloadTile(const std::string& _url, const Tile& _tile) { curl_global_init(CURL_GLOBAL_DEFAULT); bool success = true; CURL* curlHandle = curl_easy_init(); std::stringstream out; // set up curl to perform fetch curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, &out); curl_easy_setopt(curlHandle, CURLOPT_URL, _url.c_str()); curl_easy_setopt(curlHandle, CURLOPT_HEADER, 0L); curl_easy_setopt(curlHandle, CURLOPT_VERBOSE, 0L); curl_easy_setopt(curlHandle, CURLOPT_ACCEPT_ENCODING, "gzip"); curl_easy_setopt(curlHandle, CURLOPT_NOSIGNAL, 1L); printf("Fetching URL with curl: %s\n", _url.c_str()); CURLcode result = curl_easy_perform(curlHandle); if (result != CURLE_OK) { printf("curl_easy_perform failed: %s\n", curl_easy_strerror(result)); success = false; } else { printf("Fetched tile: %s\n", _url.c_str()); // parse written data into a JSON object rapidjson::Document doc; doc.Parse(out.str().c_str()); if (doc.HasParseError()) { printf("Error parsing tile\n"); return nullptr; } std::unique_ptr<TileData> data = std::unique_ptr<TileData>(new TileData()); for (auto layer = doc.MemberBegin(); layer != doc.MemberEnd(); ++layer) { data->layers.emplace_back(std::string(layer->name.GetString())); GeoJson::extractLayer(layer->value, data->layers.back(), _tile); } return std::move(data); } return nullptr; } void buildPolygonExtrusion(const Polygon& _polygon, double _minHeight, double _height, std::vector<PolygonVertex>& _vertices, std::vector<unsigned int>& _indices) { int vertexDataOffset = _vertices.size(); glm::vec3 upVector(0.0f, 0.0f, 1.0f); glm::vec3 normalVector; for (auto& line : _polygon) { size_t lineSize = line.size(); for (size_t i = 0; i < lineSize - 1; i++) { glm::vec3 a(line[i]); glm::vec3 b(line[i+1]); normalVector = glm::cross(upVector, b - a); normalVector = glm::normalize(normalVector); a.z = _height; _vertices.push_back({a, normalVector}); b.z = _height; _vertices.push_back({b, normalVector}); a.z = _minHeight; _vertices.push_back({a, normalVector}); b.z = _minHeight; _vertices.push_back({b, normalVector}); _indices.push_back(vertexDataOffset); _indices.push_back(vertexDataOffset + 1); _indices.push_back(vertexDataOffset + 2); _indices.push_back(vertexDataOffset + 1); _indices.push_back(vertexDataOffset + 3); _indices.push_back(vertexDataOffset + 2); vertexDataOffset += 4; } } } void buildPolygon(const Polygon& _polygon, double _height, std::vector<PolygonVertex>& _vertices, std::vector<unsigned int>& _indices) { mapbox::Earcut<float, unsigned int> earcut; earcut(_polygon); unsigned int vertexDataOffset = _vertices.size(); if (vertexDataOffset == 0) { _indices = std::move(earcut.indices); } else { _indices.reserve(_indices.size() + earcut.indices.size()); for (auto i : earcut.indices) { _indices.push_back(vertexDataOffset + i); } } static glm::vec3 normal(0.0, 0.0, 1.0); for (auto& p : earcut.vertices) { glm::vec3 coord(p[0], p[1], _height); _vertices.push_back({coord, normal}); } } bool saveOBJ(std::string _outputOBJ, bool _splitMeshes, const std::vector<PolygonMesh> _meshes) { std::ofstream file(_outputOBJ); if (file.is_open()) { int indexOffset = 0; if (_splitMeshes) { int meshCnt = 0; for (const PolygonMesh& mesh : _meshes) { if (mesh.vertices.size() == 0) { continue; } file << "o mesh" << meshCnt++ << "\n"; for (auto vertex : mesh.vertices) { file << "v " << vertex.position.x << " " << vertex.position.y << " " << vertex.position.z << "\n"; } for (auto vertex : mesh.vertices) { file << "vn " << vertex.normal.x << " " << vertex.normal.y << " " << vertex.normal.z << "\n"; } for (int i = 0; i < mesh.indices.size(); i += 3) { file << "f " << mesh.indices[i] + indexOffset + 1 << "//" << mesh.indices[i] + indexOffset + 1; file << " "; file << mesh.indices[i+1] + indexOffset + 1 << "//" << mesh.indices[i+1] + indexOffset + 1; file << " "; file << mesh.indices[i+2] + indexOffset + 1 << "//" << mesh.indices[i+2] + indexOffset + 1 << "\n"; } file << "\n"; indexOffset += mesh.vertices.size(); } } else { for (const PolygonMesh& mesh : _meshes) { if (mesh.vertices.size() == 0) { continue; } for (auto vertex : mesh.vertices) { file << "v " << vertex.position.x << " " << vertex.position.y << " " << vertex.position.z << "\n"; } } for (const PolygonMesh& mesh : _meshes) { for (auto vertex : mesh.vertices) { file << "vn " << vertex.normal.x << " " << vertex.normal.y << " " << vertex.normal.z << "\n"; } } for (const PolygonMesh& mesh : _meshes) { for (int i = 0; i < mesh.indices.size(); i += 3) { file << "f " << mesh.indices[i] + indexOffset + 1 << "//" << mesh.indices[i] + indexOffset + 1; file << " "; file << mesh.indices[i+1] + indexOffset + 1 << "//" << mesh.indices[i+1] + indexOffset + 1; file << " "; file << mesh.indices[i+2] + indexOffset + 1 << "//" << mesh.indices[i+2] + indexOffset + 1 << "\n"; } indexOffset += mesh.vertices.size(); } } file.close(); printf("Save %s\n", _outputOBJ.c_str()); return true; } return false; } int objexport(int _tileX, int _tileY, int _tileZ, bool _splitMeshes, int _sizehint, int _nsamples, bool _bakeAO) { std::string apiKey = "vector-tiles-qVaBcRA"; std::string url = "http://vector.mapzen.com/osm/all/" + std::to_string(_tileZ) + "/" + std::to_string(_tileX) + "/" + std::to_string(_tileY) + ".json?api_key=" + apiKey; Tile tile = {_tileX, _tileY, _tileZ}; auto data = downloadTile(url, tile); if (!data) { printf("Failed to download tile data\n"); return EXIT_FAILURE; } glm::dvec4 bounds = tileBounds(tile, 256.0); double scale = 0.5 * glm::abs(bounds.x - bounds.z); double invScale = 1.0 / scale; const static std::string key_height("height"); const static std::string key_min_height("min_height"); std::vector<PolygonMesh> meshes; for (auto layer : data->layers) { //if (layer.name == "buildings" || layer.name == "landuse") { for (auto feature : layer.features) { auto itHeight = feature.props.numericProps.find(key_height); auto itMinHeight = feature.props.numericProps.find(key_min_height); double height = 0.0; double minHeight = 0.0; if (itHeight != feature.props.numericProps.end()) { height = itHeight->second * invScale; } if (itMinHeight != feature.props.numericProps.end()) { minHeight = itMinHeight->second * invScale; } PolygonMesh mesh; for (auto polygon : feature.polygons) { if (minHeight != height) { buildPolygonExtrusion(polygon, minHeight, height, mesh.vertices, mesh.indices); } buildPolygon(polygon, height, mesh.vertices, mesh.indices); } meshes.push_back(mesh); } //} } std::string outFile = std::to_string(_tileX) + "." + std::to_string(_tileY) + "." + std::to_string(_tileZ); std::string outputOBJ = outFile + ".obj"; if (!saveOBJ(outputOBJ, _splitMeshes, meshes)) { return EXIT_FAILURE; } if (_bakeAO) { return aobaker_bake(outputOBJ.c_str(), (outFile + "-ao.obj").c_str(), (outFile + ".png").c_str(), _sizehint, _nsamples, false, false, 1.0); } return EXIT_SUCCESS; } <commit_msg>Fix on empty meshes<commit_after>#include <iostream> #include <curl/curl.h> #include <string> #include <sstream> #include <fstream> #include "rapidjson/document.h" #include "geojson.h" #include "tileData.h" #include "earcut.hpp" #include "objexport.h" #include "aobaker.h" namespace mapbox { namespace util { template <> struct nth<0, Point> { inline static float get(const Point &t) { return t.x; }; }; template <> struct nth<1, Point> { inline static float get(const Point &t) { return t.y; }; }; }} struct PolygonVertex { glm::vec3 position; glm::vec3 normal; }; struct PolygonMesh { std::vector<unsigned int> indices; std::vector<PolygonVertex> vertices; }; static size_t write_data(void *_ptr, size_t _size, size_t _nmemb, void *_stream) { ((std::stringstream*) _stream)->write(reinterpret_cast<char *>(_ptr), _size * _nmemb); return _size * _nmemb; } std::unique_ptr<TileData> downloadTile(const std::string& _url, const Tile& _tile) { curl_global_init(CURL_GLOBAL_DEFAULT); bool success = true; CURL* curlHandle = curl_easy_init(); std::stringstream out; // set up curl to perform fetch curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, &out); curl_easy_setopt(curlHandle, CURLOPT_URL, _url.c_str()); curl_easy_setopt(curlHandle, CURLOPT_HEADER, 0L); curl_easy_setopt(curlHandle, CURLOPT_VERBOSE, 0L); curl_easy_setopt(curlHandle, CURLOPT_ACCEPT_ENCODING, "gzip"); curl_easy_setopt(curlHandle, CURLOPT_NOSIGNAL, 1L); printf("Fetching URL with curl: %s\n", _url.c_str()); CURLcode result = curl_easy_perform(curlHandle); if (result != CURLE_OK) { printf("curl_easy_perform failed: %s\n", curl_easy_strerror(result)); success = false; } else { printf("Fetched tile: %s\n", _url.c_str()); // parse written data into a JSON object rapidjson::Document doc; doc.Parse(out.str().c_str()); if (doc.HasParseError()) { printf("Error parsing tile\n"); return nullptr; } std::unique_ptr<TileData> data = std::unique_ptr<TileData>(new TileData()); for (auto layer = doc.MemberBegin(); layer != doc.MemberEnd(); ++layer) { data->layers.emplace_back(std::string(layer->name.GetString())); GeoJson::extractLayer(layer->value, data->layers.back(), _tile); } return std::move(data); } return nullptr; } void buildPolygonExtrusion(const Polygon& _polygon, double _minHeight, double _height, std::vector<PolygonVertex>& _vertices, std::vector<unsigned int>& _indices) { int vertexDataOffset = _vertices.size(); glm::vec3 upVector(0.0f, 0.0f, 1.0f); glm::vec3 normalVector; for (auto& line : _polygon) { size_t lineSize = line.size(); for (size_t i = 0; i < lineSize - 1; i++) { glm::vec3 a(line[i]); glm::vec3 b(line[i+1]); normalVector = glm::cross(upVector, b - a); normalVector = glm::normalize(normalVector); a.z = _height; _vertices.push_back({a, normalVector}); b.z = _height; _vertices.push_back({b, normalVector}); a.z = _minHeight; _vertices.push_back({a, normalVector}); b.z = _minHeight; _vertices.push_back({b, normalVector}); _indices.push_back(vertexDataOffset); _indices.push_back(vertexDataOffset + 1); _indices.push_back(vertexDataOffset + 2); _indices.push_back(vertexDataOffset + 1); _indices.push_back(vertexDataOffset + 3); _indices.push_back(vertexDataOffset + 2); vertexDataOffset += 4; } } } void buildPolygon(const Polygon& _polygon, double _height, std::vector<PolygonVertex>& _vertices, std::vector<unsigned int>& _indices) { mapbox::Earcut<float, unsigned int> earcut; earcut(_polygon); unsigned int vertexDataOffset = _vertices.size(); if (vertexDataOffset == 0) { _indices = std::move(earcut.indices); } else { _indices.reserve(_indices.size() + earcut.indices.size()); for (auto i : earcut.indices) { _indices.push_back(vertexDataOffset + i); } } static glm::vec3 normal(0.0, 0.0, 1.0); for (auto& p : earcut.vertices) { glm::vec3 coord(p[0], p[1], _height); _vertices.push_back({coord, normal}); } } bool saveOBJ(std::string _outputOBJ, bool _splitMeshes, const std::vector<PolygonMesh> _meshes) { std::ofstream file(_outputOBJ); if (file.is_open()) { int indexOffset = 0; if (_splitMeshes) { int meshCnt = 0; for (const PolygonMesh& mesh : _meshes) { if (mesh.vertices.size() == 0) { continue; } file << "o mesh" << meshCnt++ << "\n"; for (auto vertex : mesh.vertices) { file << "v " << vertex.position.x << " " << vertex.position.y << " " << vertex.position.z << "\n"; } for (auto vertex : mesh.vertices) { file << "vn " << vertex.normal.x << " " << vertex.normal.y << " " << vertex.normal.z << "\n"; } for (int i = 0; i < mesh.indices.size(); i += 3) { file << "f " << mesh.indices[i] + indexOffset + 1 << "//" << mesh.indices[i] + indexOffset + 1; file << " "; file << mesh.indices[i+1] + indexOffset + 1 << "//" << mesh.indices[i+1] + indexOffset + 1; file << " "; file << mesh.indices[i+2] + indexOffset + 1 << "//" << mesh.indices[i+2] + indexOffset + 1 << "\n"; } file << "\n"; indexOffset += mesh.vertices.size(); } } else { for (const PolygonMesh& mesh : _meshes) { if (mesh.vertices.size() == 0) { continue; } for (auto vertex : mesh.vertices) { file << "v " << vertex.position.x << " " << vertex.position.y << " " << vertex.position.z << "\n"; } } for (const PolygonMesh& mesh : _meshes) { if (mesh.vertices.size() == 0) { continue; } for (auto vertex : mesh.vertices) { file << "vn " << vertex.normal.x << " " << vertex.normal.y << " " << vertex.normal.z << "\n"; } } for (const PolygonMesh& mesh : _meshes) { if (mesh.vertices.size() == 0) { continue; } for (int i = 0; i < mesh.indices.size(); i += 3) { file << "f " << mesh.indices[i] + indexOffset + 1 << "//" << mesh.indices[i] + indexOffset + 1; file << " "; file << mesh.indices[i+1] + indexOffset + 1 << "//" << mesh.indices[i+1] + indexOffset + 1; file << " "; file << mesh.indices[i+2] + indexOffset + 1 << "//" << mesh.indices[i+2] + indexOffset + 1 << "\n"; } indexOffset += mesh.vertices.size(); } } file.close(); printf("Save %s\n", _outputOBJ.c_str()); return true; } return false; } int objexport(int _tileX, int _tileY, int _tileZ, bool _splitMeshes, int _sizehint, int _nsamples, bool _bakeAO) { std::string apiKey = "vector-tiles-qVaBcRA"; std::string url = "http://vector.mapzen.com/osm/all/" + std::to_string(_tileZ) + "/" + std::to_string(_tileX) + "/" + std::to_string(_tileY) + ".json?api_key=" + apiKey; Tile tile = {_tileX, _tileY, _tileZ}; auto data = downloadTile(url, tile); if (!data) { printf("Failed to download tile data\n"); return EXIT_FAILURE; } glm::dvec4 bounds = tileBounds(tile, 256.0); double scale = 0.5 * glm::abs(bounds.x - bounds.z); double invScale = 1.0 / scale; const static std::string key_height("height"); const static std::string key_min_height("min_height"); std::vector<PolygonMesh> meshes; for (auto layer : data->layers) { //if (layer.name == "buildings" || layer.name == "landuse") { for (auto feature : layer.features) { auto itHeight = feature.props.numericProps.find(key_height); auto itMinHeight = feature.props.numericProps.find(key_min_height); double height = 0.0; double minHeight = 0.0; if (itHeight != feature.props.numericProps.end()) { height = itHeight->second * invScale; } if (itMinHeight != feature.props.numericProps.end()) { minHeight = itMinHeight->second * invScale; } PolygonMesh mesh; for (auto polygon : feature.polygons) { if (minHeight != height) { buildPolygonExtrusion(polygon, minHeight, height, mesh.vertices, mesh.indices); } buildPolygon(polygon, height, mesh.vertices, mesh.indices); } meshes.push_back(mesh); } //} } std::string outFile = std::to_string(_tileX) + "." + std::to_string(_tileY) + "." + std::to_string(_tileZ); std::string outputOBJ = outFile + ".obj"; if (!saveOBJ(outputOBJ, _splitMeshes, meshes)) { return EXIT_FAILURE; } if (_bakeAO) { return aobaker_bake(outputOBJ.c_str(), (outFile + "-ao.obj").c_str(), (outFile + ".png").c_str(), _sizehint, _nsamples, false, false, 1.0); } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <ros/ros.h> #include <tf/transform_broadcaster.h> #include <nav_msgs/Odometry.h> #include <ax2550/Encoders.h> int wheel1_new, wheel2_new, wheel3_new, wheel4_new; double dt_front, dt_rear; double x = 0.0; double y = 0.0; double th = 0.0; double vx = 0.0; double vy = 0.0; double vth = 0.0; const double wheel_radius = 0.125; const double wheel_circumference = 0.785; const double k = 0.44; //the sum of the distance between the wheel's x-coord and the origin, and the y-coord and the origin const double encoder_resolution = 1250*4*20; ros::Publisher odom_pub; ros::Subscriber fr_enc; ros::Subscriber rr_enc; void computeOdom(); void feCallBack(const ax2550::Encoders::ConstPtr& msg) { wheel1_new = msg->right_wheel; wheel4_new = msg->left_wheel; dt_front = msg->time_delta; } void reCallBack(const ax2550::Encoders::ConstPtr& msg) { wheel2_new = msg->right_wheel; wheel3_new = msg->left_wheel; dt_rear = msg->time_delta; computeOdom(); } void computeOdom() { double avg_dt = (dt_front + dt_rear)/2.0; if(avg_dt == 0) { avg_dt = dt_front; } ros::Time current_time = ros::Time::now(); double dist_per_tick = wheel_circumference / encoder_resolution; //compute the velocities double v_w1 = (wheel1_new * dist_per_tick)/dt_front; double v_w2 = (wheel2_new * dist_per_tick)/dt_rear; double v_w3 = (wheel3_new * dist_per_tick)/dt_rear; double v_w4 = (wheel4_new * dist_per_tick)/dt_front; vx = (wheel_radius/4)*(v_w1+v_w2+v_w3+v_w4); vy = (wheel_radius/4)*(-v_w1+v_w2-v_w3+v_w4); vth = (wheel_radius/(4*k))*(-v_w1-v_w2+v_w3+v_w4); //compute odometry in a typical way given the velocities of the robot double delta_x = vx * avg_dt; double delta_y = vy * avg_dt; double delta_th = vth * avg_dt; x = x + delta_x; y = y + delta_y; th = th + delta_th; //since all odometry is 6DOF we'll need a quaternion created from yaw geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(th); //first, we'll publish the transform over tf geometry_msgs::TransformStamped odom_trans; odom_trans.header.stamp = current_time; odom_trans.header.frame_id = "odom"; odom_trans.child_frame_id = "base_footprint"; odom_trans.transform.translation.x = x; odom_trans.transform.translation.y = y; odom_trans.transform.translation.z = 0.0; odom_trans.transform.rotation = odom_quat; tf::TransformBroadcaster odom_broadcaster; //send the transform odom_broadcaster.sendTransform(odom_trans); //next, we'll publish the odometry message over ROS nav_msgs::Odometry odom; odom.header.stamp = current_time; odom.header.frame_id = "odom"; //set the position odom.pose.pose.position.x = x; odom.pose.pose.position.y = y; odom.pose.pose.position.z = 0.0; odom.pose.pose.orientation = odom_quat; //set the covariance odom.pose.covariance[0] = 0.2; odom.pose.covariance[7] = 0.2; odom.pose.covariance[14] = 1e100; odom.pose.covariance[21] = 1e100; odom.pose.covariance[28] = 1e100; odom.pose.covariance[35] = 0.2; //set the velocity odom.child_frame_id = "base_footprint"; odom.twist.twist.linear.x = vx; odom.twist.twist.linear.y = vy; odom.twist.twist.angular.z = vth; //publish the message odom_pub.publish(odom); } int main(int argc, char** argv) { ros::init(argc, argv, "omni_odom"); ros::NodeHandle n; odom_pub = n.advertise<nav_msgs::Odometry>("omni_odom", 60); fr_enc = n.subscribe("front_encoders", 1, feCallBack); rr_enc = n.subscribe("rear_encoders", 1, reCallBack); ros::spin(); return 0; } <commit_msg>Fixed the odom transform broadcaster<commit_after>#include <ros/ros.h> #include <tf/transform_broadcaster.h> #include <nav_msgs/Odometry.h> #include <ax2550/Encoders.h> #include <tf/transform_datatypes.h> int wheel1_new, wheel2_new, wheel3_new, wheel4_new; double dt_front, dt_rear; double x = 0.0; double y = 0.0; double th = 0.0; double vx = 0.0; double vy = 0.0; double vth = 0.0; const double wheel_radius = 0.125; const double wheel_circumference = 0.785; const double k = 0.44; //the sum of the distance between the wheel's x-coord and the origin, and the y-coord and the origin const double encoder_resolution = 1250*4*20; ros::Publisher odom_pub; ros::Subscriber fr_enc; ros::Subscriber rr_enc; tf::TransformBroadcaster *odom_broadcaster; void computeOdom(); void feCallBack(const ax2550::Encoders::ConstPtr& msg) { wheel1_new = msg->right_wheel; wheel4_new = msg->left_wheel; dt_front = msg->time_delta; } void reCallBack(const ax2550::Encoders::ConstPtr& msg) { wheel2_new = msg->right_wheel; wheel3_new = msg->left_wheel; dt_rear = msg->time_delta; computeOdom(); } void computeOdom() { double avg_dt = (dt_front + dt_rear)/2.0; if(avg_dt == 0) { avg_dt = dt_front; } ros::Time current_time = ros::Time::now(); double dist_per_tick = wheel_circumference / encoder_resolution; //compute the velocities double v_w1 = (wheel1_new * dist_per_tick)/dt_front; double v_w2 = (wheel2_new * dist_per_tick)/dt_rear; double v_w3 = (wheel3_new * dist_per_tick)/dt_rear; double v_w4 = (wheel4_new * dist_per_tick)/dt_front; vx = (wheel_radius/4)*(v_w1+v_w2+v_w3+v_w4); vy = (wheel_radius/4)*(-v_w1+v_w2-v_w3+v_w4); vth = (wheel_radius/(4*k))*(-v_w1-v_w2+v_w3+v_w4); //compute odometry in a typical way given the velocities of the robot double delta_x = vx * avg_dt; double delta_y = vy * avg_dt; double delta_th = vth * avg_dt; x = x + delta_x; y = y + delta_y; th = th + delta_th; //since all odometry is 6DOF we'll need a quaternion created from yaw geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(th); //first, we'll publish the transform over tf geometry_msgs::TransformStamped odom_trans; odom_trans.header.stamp = current_time; odom_trans.header.frame_id = "odom"; odom_trans.child_frame_id = "base_footprint"; odom_trans.transform.translation.x = x; odom_trans.transform.translation.y = y; odom_trans.transform.translation.z = 0.0; odom_trans.transform.rotation = odom_quat; odom_broadcaster = new tf::TransformBroadcaster(); //send the transform odom_broadcaster->sendTransform(odom_trans); //next, we'll publish the odometry message over ROS nav_msgs::Odometry odom; odom.header.stamp = current_time; odom.header.frame_id = "odom"; //set the position odom.pose.pose.position.x = x; odom.pose.pose.position.y = y; odom.pose.pose.position.z = 0.0; odom.pose.pose.orientation = odom_quat; //set the covariance odom.pose.covariance[0] = 0.2; odom.pose.covariance[7] = 0.2; odom.pose.covariance[14] = 1e100; odom.pose.covariance[21] = 1e100; odom.pose.covariance[28] = 1e100; odom.pose.covariance[35] = 0.2; //set the velocity odom.child_frame_id = "base_footprint"; odom.twist.twist.linear.x = vx; odom.twist.twist.linear.y = vy; odom.twist.twist.angular.z = vth; //publish the message odom_pub.publish(odom); } int main(int argc, char** argv) { ros::init(argc, argv, "omni_odom"); ros::NodeHandle n; odom_pub = n.advertise<nav_msgs::Odometry>("omni_odom", 60); fr_enc = n.subscribe("front_encoders", 1, feCallBack); rr_enc = n.subscribe("rear_encoders", 1, reCallBack); ros::spin(); return 0; } <|endoftext|>
<commit_before> #include "../Flare.h" #include "FlareMenuPawn.h" #include "FlarePlayerController.h" /*---------------------------------------------------- Constructor ----------------------------------------------------*/ AFlareMenuPawn::AFlareMenuPawn(const class FObjectInitializer& PCIP) : Super(PCIP) , InitialYaw(150) , DisplayDistance(800) , DisplaySize(300) , ShipDisplaySize(500) , SlideInOutUpOffset(0, 0, -2000) , SlideInOutSideOffset(0, 2000, 0) , SlideInOutTime(0.4) , CurrentSpacecraft(NULL) , SlideFromAToB(true) , SlideDirection(1) { // Structure to hold one-time initialization struct FConstructorStatics { ConstructorHelpers::FObjectFinderOptional<UStaticMesh> CurrentPart; FConstructorStatics() : CurrentPart(TEXT("/Game/Ships/Airframes/SM_Airframe_Ghoul")) {} }; static FConstructorStatics ConstructorStatics; FAttachmentTransformRules AttachRules(EAttachmentRule::KeepRelative, false); // Dummy root to allow better configuration of the subparts USceneComponent* SceneComponent = PCIP.CreateDefaultSubobject<USceneComponent>(this, TEXT("SceneComponent")); CameraContainerYaw->AttachToComponent(SceneComponent, AttachRules); RootComponent = SceneComponent; // Part container turnplate PartContainer = PCIP.CreateDefaultSubobject<USceneComponent>(this, TEXT("PartContainer")); PartContainer->AttachToComponent(RootComponent, AttachRules); // Create static mesh component for the part CurrentPartA = PCIP.CreateDefaultSubobject<UFlareSpacecraftComponent>(this, TEXT("PartA")); CurrentPartA->SetStaticMesh(ConstructorStatics.CurrentPart.Get()); CurrentPartA->SetSimulatePhysics(false); CurrentPartA->AttachToComponent(PartContainer, AttachRules); // Create static mesh component for the part CurrentPartB = PCIP.CreateDefaultSubobject<UFlareSpacecraftComponent>(this, TEXT("PartB")); CurrentPartB->SetStaticMesh(ConstructorStatics.CurrentPart.Get()); CurrentPartB->SetSimulatePhysics(false); CurrentPartB->AttachToComponent(PartContainer, AttachRules); } /*---------------------------------------------------- Gameplay events ----------------------------------------------------*/ void AFlareMenuPawn::BeginPlay() { Super::BeginPlay(); ResetContent(true); } void AFlareMenuPawn::Tick(float DeltaSeconds) { Super::Tick(DeltaSeconds); SlideInOutCurrentTime += DeltaSeconds; // Compute new positions for the current and old part float PartPositionAlpha = FMath::Clamp(SlideInOutCurrentTime / SlideInOutTime, 0.0f, 1.0f); FVector SlideInDelta = SlideDirection * FMath::InterpEaseOut(SlideInOutOffset, FVector::ZeroVector, PartPositionAlpha, 2); FVector SlideOutDelta = -SlideDirection * FMath::InterpEaseIn(FVector::ZeroVector, SlideInOutOffset, PartPositionAlpha, 1); // Part sliding CurrentPartA->SetRelativeLocation(CurrentPartOffsetA + (SlideFromAToB ? SlideOutDelta : SlideInDelta)); CurrentPartB->SetRelativeLocation(CurrentPartOffsetB + (SlideFromAToB ? SlideInDelta : SlideOutDelta)); // Ship sliding if (CurrentSpacecraft) { CurrentSpacecraft->SetActorLocation(GetActorLocation() + CurrentShipOffset + SlideInDelta); } // Camera float Speed = FMath::Clamp(DeltaSeconds * 12, 0.f, 1.f); ExternalCameraPitchTarget = FMath::Clamp(ExternalCameraPitchTarget, -GetCameraMaxPitch(), GetCameraMaxPitch()); ExternalCameraPitch = ExternalCameraPitch * (1 - Speed) + ExternalCameraPitchTarget * Speed; SetCameraPitch(ExternalCameraPitch); float LastExternalCameraYaw = ExternalCameraYaw; ExternalCameraYaw = ExternalCameraYaw * (1 - Speed) + ExternalCameraYawTarget * Speed; FRotator DeltaRot = FRotator::MakeFromEuler(FVector(0, 0, ExternalCameraYaw - LastExternalCameraYaw)); if (CurrentSpacecraft) { CurrentSpacecraft->AddActorLocalRotation(DeltaRot); } else { PartContainer->AddLocalRotation(DeltaRot); } } /*---------------------------------------------------- Resource loading ----------------------------------------------------*/ void AFlareMenuPawn::ShowShip(UFlareSimulatedSpacecraft* Spacecraft) { // Clean up ResetContent(); // Spawn parameters FActorSpawnParameters Params; Params.bNoFail = true; Params.Instigator = this; Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn; // Spawn and setup the ship FAttachmentTransformRules AttachRules(EAttachmentRule::SnapToTarget, false); CurrentSpacecraft = GetWorld()->SpawnActor<AFlareSpacecraft>(Spacecraft->GetDescription()->SpacecraftTemplate, Params); CurrentSpacecraft->AttachToActor(this, AttachRules, NAME_None); // Setup rotation and scale CurrentSpacecraft->SetActorScale3D(FVector(1, 1, 1)); float Scale = ShipDisplaySize / CurrentSpacecraft->GetMeshScale(); FLOGV("AFlareMenuPawn::ShowShip : DS=%f, MS=%f, S=%f", ShipDisplaySize, CurrentSpacecraft->GetMeshScale(), Scale); CurrentSpacecraft->SetActorScale3D(Scale * FVector(1, 1, 1)); CurrentSpacecraft->SetActorRelativeRotation(FRotator(0, InitialYaw, 0)); // Slide SlideInOutCurrentTime = 0.0f; SlideInOutOffset = SlideInOutSideOffset; SetSlideDirection(true); CurrentSpacecraft->StartPresentation(); // UI CurrentSpacecraft->Load(Spacecraft); } void AFlareMenuPawn::ShowPart(const FFlareSpacecraftComponentDescription* PartDesc) { // Choose a part to work with SlideFromAToB = !SlideFromAToB; UFlareSpacecraftComponent* CurrentPart = SlideFromAToB ? CurrentPartB : CurrentPartA; UFlareCompany* TargetCompany = CurrentSpacecraft ? CurrentSpacecraft->GetParent()->GetCompany() : GetPC()->GetCompany(); FVector& CurrentPartOffset = SlideFromAToB ? CurrentPartOffsetB : CurrentPartOffsetA; // Clean up ResetContent(); // Load the parts and scale accordingly CurrentPart->SetVisibleInUpgrade(true); FFlareSpacecraftComponentSave Data; Data.Damage = 0; Data.ComponentIdentifier = PartDesc->Identifier; CurrentPart->Initialize(&Data, TargetCompany, this, true); CurrentPart->SetWorldScale3D(FVector(1, 1, 1)); float Scale = DisplaySize / CurrentPart->GetMeshScale(); CurrentPart->SetWorldScale3D(Scale * FVector(1, 1, 1)); // Reset position to compute the offsets CurrentPart->SetRelativeLocation(FVector::ZeroVector); FRotator OldRot = PartContainer->GetComponentRotation(); PartContainer->SetRelativeRotation(FRotator::ZeroRotator); CurrentPart->SetRelativeRotation(FRotator(0, -InitialYaw, 0)); // Except on RCSs, center the part if (PartDesc->Type != EFlarePartType::RCS) { CurrentPartOffset = GetActorLocation() - CurrentPart->Bounds.GetBox().GetCenter(); } else { CurrentPartOffset = FVector::ZeroVector; } // Setup offset and rotation PartContainer->SetRelativeRotation(OldRot); SlideInOutOffset = SlideInOutUpOffset; SlideInOutCurrentTime = 0.0f; } /*---------------------------------------------------- Gameplay ----------------------------------------------------*/ void AFlareMenuPawn::ResetContent(bool Unsafe) { // Delete ship if existing if (CurrentSpacecraft && !Unsafe) { CurrentSpacecraft->Destroy(); CurrentSpacecraft = NULL; } // Hide parts CurrentPartA->SetVisibleInUpgrade(false); CurrentPartB->SetVisibleInUpgrade(false); // Setup panning SetCameraPitch(-CameraMaxPitch / 2); ExternalCameraPitchTarget = -CameraMaxPitch / 2; ExternalCameraPitch = ExternalCameraPitchTarget; SetCameraDistance(DisplayDistance); } void AFlareMenuPawn::UpdateCustomization() { if (CurrentSpacecraft) { CurrentSpacecraft->UpdateCustomization(); } else { CurrentPartA->UpdateCustomization(); CurrentPartB->UpdateCustomization(); } } void AFlareMenuPawn::SetCameraOffset(FVector2D Offset) { SetCameraLocalPosition(FVector(0, -Offset.X, -Offset.Y)); } void AFlareMenuPawn::SetSlideDirection(bool GoUp) { SlideDirection = GoUp ? 1 : -1; } void AFlareMenuPawn::UseLightBackground() { UpdateBackgroundColor(0.9, 0.1); } void AFlareMenuPawn::UseDarkBackground() { UpdateBackgroundColor(0.05, 0.85); } /*---------------------------------------------------- Input ----------------------------------------------------*/ void AFlareMenuPawn::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) { FCHECK(PlayerInputComponent); } void AFlareMenuPawn::PitchInput(float Val) { if (Val) { ExternalCameraPitchTarget += CameraPanSpeed * Val; } } void AFlareMenuPawn::YawInput(float Val) { if (Val) { ExternalCameraYawTarget += - CameraPanSpeed * Val; } } <commit_msg>Tweak background color inside menus<commit_after> #include "../Flare.h" #include "FlareMenuPawn.h" #include "FlarePlayerController.h" /*---------------------------------------------------- Constructor ----------------------------------------------------*/ AFlareMenuPawn::AFlareMenuPawn(const class FObjectInitializer& PCIP) : Super(PCIP) , InitialYaw(150) , DisplayDistance(800) , DisplaySize(300) , ShipDisplaySize(500) , SlideInOutUpOffset(0, 0, -2000) , SlideInOutSideOffset(0, 2000, 0) , SlideInOutTime(0.4) , CurrentSpacecraft(NULL) , SlideFromAToB(true) , SlideDirection(1) { // Structure to hold one-time initialization struct FConstructorStatics { ConstructorHelpers::FObjectFinderOptional<UStaticMesh> CurrentPart; FConstructorStatics() : CurrentPart(TEXT("/Game/Ships/Airframes/SM_Airframe_Ghoul")) {} }; static FConstructorStatics ConstructorStatics; FAttachmentTransformRules AttachRules(EAttachmentRule::KeepRelative, false); // Dummy root to allow better configuration of the subparts USceneComponent* SceneComponent = PCIP.CreateDefaultSubobject<USceneComponent>(this, TEXT("SceneComponent")); CameraContainerYaw->AttachToComponent(SceneComponent, AttachRules); RootComponent = SceneComponent; // Part container turnplate PartContainer = PCIP.CreateDefaultSubobject<USceneComponent>(this, TEXT("PartContainer")); PartContainer->AttachToComponent(RootComponent, AttachRules); // Create static mesh component for the part CurrentPartA = PCIP.CreateDefaultSubobject<UFlareSpacecraftComponent>(this, TEXT("PartA")); CurrentPartA->SetStaticMesh(ConstructorStatics.CurrentPart.Get()); CurrentPartA->SetSimulatePhysics(false); CurrentPartA->AttachToComponent(PartContainer, AttachRules); // Create static mesh component for the part CurrentPartB = PCIP.CreateDefaultSubobject<UFlareSpacecraftComponent>(this, TEXT("PartB")); CurrentPartB->SetStaticMesh(ConstructorStatics.CurrentPart.Get()); CurrentPartB->SetSimulatePhysics(false); CurrentPartB->AttachToComponent(PartContainer, AttachRules); } /*---------------------------------------------------- Gameplay events ----------------------------------------------------*/ void AFlareMenuPawn::BeginPlay() { Super::BeginPlay(); ResetContent(true); } void AFlareMenuPawn::Tick(float DeltaSeconds) { Super::Tick(DeltaSeconds); SlideInOutCurrentTime += DeltaSeconds; // Compute new positions for the current and old part float PartPositionAlpha = FMath::Clamp(SlideInOutCurrentTime / SlideInOutTime, 0.0f, 1.0f); FVector SlideInDelta = SlideDirection * FMath::InterpEaseOut(SlideInOutOffset, FVector::ZeroVector, PartPositionAlpha, 2); FVector SlideOutDelta = -SlideDirection * FMath::InterpEaseIn(FVector::ZeroVector, SlideInOutOffset, PartPositionAlpha, 1); // Part sliding CurrentPartA->SetRelativeLocation(CurrentPartOffsetA + (SlideFromAToB ? SlideOutDelta : SlideInDelta)); CurrentPartB->SetRelativeLocation(CurrentPartOffsetB + (SlideFromAToB ? SlideInDelta : SlideOutDelta)); // Ship sliding if (CurrentSpacecraft) { CurrentSpacecraft->SetActorLocation(GetActorLocation() + CurrentShipOffset + SlideInDelta); } // Camera float Speed = FMath::Clamp(DeltaSeconds * 12, 0.f, 1.f); ExternalCameraPitchTarget = FMath::Clamp(ExternalCameraPitchTarget, -GetCameraMaxPitch(), GetCameraMaxPitch()); ExternalCameraPitch = ExternalCameraPitch * (1 - Speed) + ExternalCameraPitchTarget * Speed; SetCameraPitch(ExternalCameraPitch); float LastExternalCameraYaw = ExternalCameraYaw; ExternalCameraYaw = ExternalCameraYaw * (1 - Speed) + ExternalCameraYawTarget * Speed; FRotator DeltaRot = FRotator::MakeFromEuler(FVector(0, 0, ExternalCameraYaw - LastExternalCameraYaw)); if (CurrentSpacecraft) { CurrentSpacecraft->AddActorLocalRotation(DeltaRot); } else { PartContainer->AddLocalRotation(DeltaRot); } } /*---------------------------------------------------- Resource loading ----------------------------------------------------*/ void AFlareMenuPawn::ShowShip(UFlareSimulatedSpacecraft* Spacecraft) { // Clean up ResetContent(); // Spawn parameters FActorSpawnParameters Params; Params.bNoFail = true; Params.Instigator = this; Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn; // Spawn and setup the ship FAttachmentTransformRules AttachRules(EAttachmentRule::SnapToTarget, false); CurrentSpacecraft = GetWorld()->SpawnActor<AFlareSpacecraft>(Spacecraft->GetDescription()->SpacecraftTemplate, Params); CurrentSpacecraft->AttachToActor(this, AttachRules, NAME_None); // Setup rotation and scale CurrentSpacecraft->SetActorScale3D(FVector(1, 1, 1)); float Scale = ShipDisplaySize / CurrentSpacecraft->GetMeshScale(); FLOGV("AFlareMenuPawn::ShowShip : DS=%f, MS=%f, S=%f", ShipDisplaySize, CurrentSpacecraft->GetMeshScale(), Scale); CurrentSpacecraft->SetActorScale3D(Scale * FVector(1, 1, 1)); CurrentSpacecraft->SetActorRelativeRotation(FRotator(0, InitialYaw, 0)); // Slide SlideInOutCurrentTime = 0.0f; SlideInOutOffset = SlideInOutSideOffset; SetSlideDirection(true); CurrentSpacecraft->StartPresentation(); // UI CurrentSpacecraft->Load(Spacecraft); } void AFlareMenuPawn::ShowPart(const FFlareSpacecraftComponentDescription* PartDesc) { // Choose a part to work with SlideFromAToB = !SlideFromAToB; UFlareSpacecraftComponent* CurrentPart = SlideFromAToB ? CurrentPartB : CurrentPartA; UFlareCompany* TargetCompany = CurrentSpacecraft ? CurrentSpacecraft->GetParent()->GetCompany() : GetPC()->GetCompany(); FVector& CurrentPartOffset = SlideFromAToB ? CurrentPartOffsetB : CurrentPartOffsetA; // Clean up ResetContent(); // Load the parts and scale accordingly CurrentPart->SetVisibleInUpgrade(true); FFlareSpacecraftComponentSave Data; Data.Damage = 0; Data.ComponentIdentifier = PartDesc->Identifier; CurrentPart->Initialize(&Data, TargetCompany, this, true); CurrentPart->SetWorldScale3D(FVector(1, 1, 1)); float Scale = DisplaySize / CurrentPart->GetMeshScale(); CurrentPart->SetWorldScale3D(Scale * FVector(1, 1, 1)); // Reset position to compute the offsets CurrentPart->SetRelativeLocation(FVector::ZeroVector); FRotator OldRot = PartContainer->GetComponentRotation(); PartContainer->SetRelativeRotation(FRotator::ZeroRotator); CurrentPart->SetRelativeRotation(FRotator(0, -InitialYaw, 0)); // Except on RCSs, center the part if (PartDesc->Type != EFlarePartType::RCS) { CurrentPartOffset = GetActorLocation() - CurrentPart->Bounds.GetBox().GetCenter(); } else { CurrentPartOffset = FVector::ZeroVector; } // Setup offset and rotation PartContainer->SetRelativeRotation(OldRot); SlideInOutOffset = SlideInOutUpOffset; SlideInOutCurrentTime = 0.0f; } /*---------------------------------------------------- Gameplay ----------------------------------------------------*/ void AFlareMenuPawn::ResetContent(bool Unsafe) { // Delete ship if existing if (CurrentSpacecraft && !Unsafe) { CurrentSpacecraft->Destroy(); CurrentSpacecraft = NULL; } // Hide parts CurrentPartA->SetVisibleInUpgrade(false); CurrentPartB->SetVisibleInUpgrade(false); // Setup panning SetCameraPitch(-CameraMaxPitch / 2); ExternalCameraPitchTarget = -CameraMaxPitch / 2; ExternalCameraPitch = ExternalCameraPitchTarget; SetCameraDistance(DisplayDistance); } void AFlareMenuPawn::UpdateCustomization() { if (CurrentSpacecraft) { CurrentSpacecraft->UpdateCustomization(); } else { CurrentPartA->UpdateCustomization(); CurrentPartB->UpdateCustomization(); } } void AFlareMenuPawn::SetCameraOffset(FVector2D Offset) { SetCameraLocalPosition(FVector(0, -Offset.X, -Offset.Y)); } void AFlareMenuPawn::SetSlideDirection(bool GoUp) { SlideDirection = GoUp ? 1 : -1; } void AFlareMenuPawn::UseLightBackground() { UpdateBackgroundColor(1.0, 0.0); } void AFlareMenuPawn::UseDarkBackground() { UpdateBackgroundColor(0.04, 0.7); } /*---------------------------------------------------- Input ----------------------------------------------------*/ void AFlareMenuPawn::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) { FCHECK(PlayerInputComponent); } void AFlareMenuPawn::PitchInput(float Val) { if (Val) { ExternalCameraPitchTarget += CameraPanSpeed * Val; } } void AFlareMenuPawn::YawInput(float Val) { if (Val) { ExternalCameraYawTarget += - CameraPanSpeed * Val; } } <|endoftext|>
<commit_before>// // Copyright (c) 2008-2018 the Urho3D project. // // 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 "../Core/Context.h" #include "../Engine/PluginApplication.h" #include <cr/cr.h> namespace Urho3D { static const StringHash contextKey("PluginApplication"); int PluginMain(void* ctx_, size_t operation, PluginApplication*(*factory)(Context*), void(*destroyer)(PluginApplication*)) { assert(ctx_); auto* ctx = static_cast<cr_plugin*>(ctx_); auto context = static_cast<Context*>(ctx->userdata); auto application = dynamic_cast<PluginApplication*>(context->GetGlobalVar(contextKey).GetPtr()); switch (operation) { case CR_LOAD: { application = factory(context); context->SetGlobalVar(contextKey, application); application->OnLoad(); return 0; } case CR_UNLOAD: case CR_CLOSE: { context->SetGlobalVar(contextKey, Variant::EMPTY); application->OnUnload(); destroyer(application); return 0; } case CR_STEP: { return 0; } default: break; } assert(false); return -3; } } <commit_msg>Engine: Do not store native plugin application in context global vars. This enables use of multiple plugins if cr.h supports them.<commit_after>// // Copyright (c) 2008-2018 the Urho3D project. // // 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 "../Core/Context.h" #include "../Engine/PluginApplication.h" #include <cr/cr.h> namespace Urho3D { int PluginMain(void* ctx_, size_t operation, PluginApplication*(*factory)(Context*), void(*destroyer)(PluginApplication*)) { assert(ctx_); auto* ctx = static_cast<cr_plugin*>(ctx_); switch (operation) { case CR_LOAD: { auto* context = static_cast<Context*>(ctx->userdata); auto* application = factory(context); application->OnLoad(); ctx->userdata = application; return 0; } case CR_UNLOAD: case CR_CLOSE: { auto* application = static_cast<PluginApplication*>(ctx->userdata); application->OnUnload(); ctx->userdata = application->GetContext(); destroyer(application); return 0; } case CR_STEP: { return 0; } default: break; } assert(false); return -3; } } <|endoftext|>
<commit_before>#include "../checkpoint/checkpoint.h" #include "myrandom/myrand.h" #include <array> // for std::array #include <cstdint> // for std::uint32_t #include <functional> // for std::hash #include <iomanip> // for std::setiosflags, std::setprecision #include <iostream> // for std::cout #include <string> // for std::string #include <utility> // for std::move #ifdef _CHECK_PARALELL_PERFORM #include <vector> // for std::vector #endif #include <boost/container/flat_map.hpp> // for boost::container::flat_map #include <tbb/concurrent_hash_map.h> // for tbb::concurrent_hash_map #include <tbb/concurrent_vector.h> // for tbb::concurrent_vector #include <tbb/parallel_for.h> // for tbb::parallel_for namespace { //! A global variable (constant expression). /*! モンテカルロシミュレーションの試行回数 */ static auto constexpr MCMAX = 1000000U; //! A global variable (constant expression). /*! UかDの文字列の長さ */ static auto constexpr RANDNUMTABLELEN = 100U; //! A global variable (constant). /*! UとDの文字列の可能な集合の配列 */ static std::array<std::string, 8U> const udarray = { "DDD", "DDU", "DUD", "DUU", "UDD", "UDU", "UUD", "UUU" }; //! A typedef. /*! 文字列とその文字列に対応する出現回数のstd::map */ using mymap = boost::container::flat_map<std::string, std::uint32_t>; //! A typedef. /*! 文字列のペア */ using strpair = std::pair<std::string, std::string>; //! A struct. /*! strpairを扱うハッシュと比較操作を定義する構造体 */ struct MyHashCompare final { //! A public static member function. /*! strpairからハッシュを生成する \param sp 文字列のペア \return 与えられたstrpairのハッシュ */ static std::size_t hash(strpair const & sp) { auto const h1 = std::hash<std::string>()(sp.first); auto const h2 = std::hash<std::string>()(sp.second); return h1 ^ (h2 << 1); } //! A public static member function. /*! 二つのstrpairを比較する \param lhs 左辺のstrpair \param rhs 右辺のstrpair \return 文字列のペアが等しい場合にはtrue */ static bool equal(strpair const & lhs, strpair const & rhs) { return lhs == rhs; } }; //! A typedef. /*! 各文字列の順列に対応する勝利回数の結果を格納するtbb::concurrent_hash_map */ using myhashmap = tbb::concurrent_hash_map<strpair, std::uint32_t, MyHashCompare>; //! A typedef. /*! 文字列のペアと、どちらの文字列が勝ったかのstd::pair */ using mymap2 = boost::container::flat_map<strpair, bool>; //! A typedef. /*! 文字列のペアと、文字列の勝利数のstd::pair */ using mymap3 = boost::container::flat_map<strpair, std::uint32_t>; //! A function. /*! 文字列の可能な順列を列挙する \return 文字列の可能な順列を列挙したstd::array */ std::array<strpair, 56U> makecombination(); //! A global variable (constant). /*! udarrayから二つを抽出したときの可能な順列の配列 */ static std::array<strpair, 56U> const cbarray = makecombination(); #ifdef _CHECK_PARALELL_PERFORM //! A function. /*! 文字列のペアの、前者が勝利した回数を集計する \param mcresultwinningavg 文字列のペアと、どちらの文字列が勝ったかの結果が格納された連想配列の可変長配列 \return 文字列のペアの、前者が勝利した回数が格納された連想配列 */ mymap3 aggregateWinningAvg(std::vector<mymap2> const & mcresultwinningavg); #endif //! A function. /*! 文字列のペアの、前者が勝利した回数を集計する \param mcresultwinningavg 文字列のペアと、どちらの文字列が勝ったかの結果が格納された連想配列の可変長配列 \return 文字列のペアの、前者が勝利した回数が格納された連想配列 */ mymap3 aggregateWinningAvg(tbb::concurrent_vector<mymap2> const & mcresultwinningavg); //! A function. /*! UDのランダム文字列を生成する \param mr 自作乱数クラスのオブジェクト \return UDのランダム文字列を格納したstd::string */ inline auto makerandomudstr(myrandom::MyRand & mr); #ifdef _CHECK_PARALELL_PERFORM //! A function. /*! モンテカルロ・シミュレーションを行う \return 期待値と、どちらの文字列が先に出現したかどうかのモンテカルロ・シミュレーションの結果のstd::pair */ std::pair<std::vector<mymap>, std::vector<mymap2> > montecarlo(); #endif //! A function. /*! モンテカルロ・シミュレーションをTBBで並列化して行う \return 期待値と、どちらの文字列が先に出現したかどうかのモンテカルロ・シミュレーションの結果のstd::pair */ std::pair< tbb::concurrent_vector<mymap>, tbb::concurrent_vector<mymap2> > montecarloTBB(); //! A function. /*! 期待値に対するモンテカルロ・シミュレーションの実装 \param mr 自作乱数クラスのオブジェクト \return 期待値に対するモンテカルロ・シミュレーションの結果が格納された連想配列 */ mymap montecarloImplAvg(myrandom::MyRand & mr); //! A function. /*! 文字列のペアのうち、どちらの文字列が先に出現したかのモンテカルロ・シミュレーションの実装 \param mr 自作乱数クラスのオブジェクト \return 文字列のペアのうち、どちらの文字列が先に出現したかのモンテカルロ・シミュレーションの結果が格納された連想配列 */ mymap2 montecarloImplWinningAvg(myrandom::MyRand & mr); //! A function. /*! UとDのランダム文字列から与えられた文字列の位置を検索し、文字列の末尾の位置を与える \param str 検索する文字列 \param udstr UとDのランダム文字列 \return 検索された文字列の末尾の位置 */ inline std::uint32_t myfind(std::string const & str, std::string const & udstr); //! A template function. /*! 期待値に対するモンテカルロ・シミュレーションの和を計算する \return 期待値に対するモンテカルロ・シミュレーションの結果の和の連想配列 */ template <typename T> mymap sumMontecarloAvg(T const & mcresultavg); } int main() { checkpoint::CheckPoint cp; cp.checkpoint("処理開始", __LINE__); #ifdef _CHECK_PARALELL_PERFORM { // モンテカルロ・シミュレーションの結果を代入 auto const mcresult(montecarlo()); // 各文字列のペアに対する勝率を計算する auto const trialwinningavg(aggregateWinningAvg(mcresult.second)); } cp.checkpoint("並列化無効", __LINE__); #endif // モンテカルロ・シミュレーションの結果を代入 auto const mcresultTBB(montecarloTBB()); // 各文字列のペアに対する勝率を計算する auto const trialwinningavg(aggregateWinningAvg(mcresultTBB.second)); cp.checkpoint("並列化有効", __LINE__); // 期待値に対するモンテカルロ・シミュレーションの結果の和を計算する auto const trialavg(sumMontecarloAvg(mcresultTBB.first)); // 各文字列に対する期待値の表示 std::cout << std::setprecision(1) << std::setiosflags(std::ios::fixed); for (auto && itr = trialavg.begin(); itr != trialavg.end(); ++itr) { std::cout << itr->first << " が出るまでの期待値: " << static_cast<double>(itr->second) / static_cast<double>(MCMAX) << "回\n"; } // 各文字列のペアに対する勝率の表示 std::cout << "\n "; for (auto i = 0; i < 8; i++) { std::cout << udarray[i] << " "; } std::cout << '\n'; auto && itr = trialwinningavg.begin(); auto const len = udarray.size(); for (auto i = 0U; i < len; i++) { std::cout << itr->first.first << ' '; for (auto j = 0U; j < len; j++) { if (i == j) { std::cout << " "; } else { std::cout << static_cast<double>(itr->second) / static_cast<double>(MCMAX) * 100.0 << ' '; ++itr; } } std::cout << '\n'; } cp.checkpoint("それ以外の処理", __LINE__); cp.checkpoint_print(); return 0; } namespace { #ifdef _CHECK_PARALELL_PERFORM mymap3 aggregateWinningAvg(std::vector<mymap2> const & mcresultwinningavg) { // 各文字列の順列に対応する勝利回数の結果を格納するboost::container::flat_map mymap3 trialwinningavg; // tbb::concurrent_hash_mapの初期化 for (auto const & sp : cbarray) { trialwinningavg[sp] = 0U; } // 試行回数分繰り返す for (auto const & mcr : mcresultwinningavg) { for (auto && itr = mcr.begin(); itr != mcr.end(); ++itr) { if (itr->second) { trialwinningavg[itr->first]++; } } } return trialwinningavg; } #endif mymap3 aggregateWinningAvg(tbb::concurrent_vector<mymap2> const & mcresultwinningavg) { // 各文字列の順列に対応する勝利回数の結果を格納するtbb::concurrent_hash_map myhashmap trial; // tbb::concurrent_hash_mapの初期化 for (auto const & sp : cbarray) { myhashmap::accessor a; trial.insert(a, sp); a->second = 0U; } // 試行回数分繰り返す tbb::parallel_for( tbb::blocked_range<std::uint32_t>(0U, MCMAX), [&mcresultwinningavg, &trial](auto const & range) { for (auto && i = range.begin(); i != range.end(); ++i) { auto const mcr = mcresultwinningavg[i]; for (auto && itr = mcr.begin(); itr != mcr.end(); ++itr) { if (itr->second) { myhashmap::accessor a; trial.insert(a, itr->first); a->second++; } } } }); // boost::container::flat_mapに計算結果を複写 boost::container::flat_map<strpair, std::uint32_t> trialwinningavg; for (auto && res : trial) { trialwinningavg[res.first] = res.second; } return trialwinningavg; } std::array<strpair, 56U> makecombination() { // 全ての可能な順列を収納する配列 std::array<strpair, 56U> cb; // カウンタ auto cnt = 0; // 全ての可能な順列を列挙 auto const len = udarray.size(); for (auto i = 0U; i < len; i++) { for (auto j = 0U; j < len; j++) { if (i != j) { cb[cnt++] = std::make_pair(udarray[i], udarray[j]); } } } return cb; } auto makerandomudstr(myrandom::MyRand & mr) { // UDのランダム文字列を格納するstd::string std::string udstring(RANDNUMTABLELEN, '\0'); // UDのランダム文字列を格納 for (auto && c : udstring) { c = mr.myrand() > 3 ? 'U' : 'D'; } // UDのランダム文字列を返す return udstring; } #ifdef _CHECK_PARALELL_PERFORM std::pair<std::vector<mymap>, std::vector<mymap2> > montecarlo() { // 期待値に対するモンテカルロ・シミュレーションの結果を格納するための可変長配列 std::vector<mymap> mcresultavg; // どちらの文字列が先に出現したかどうかのモンテカルロ・シミュレーションの結果を格納するための可変長配列 std::vector<mymap2> mcresultwinningavg; // MCMAX個の容量を確保 mcresultavg.reserve(MCMAX); mcresultwinningavg.reserve(MCMAX); // 自作乱数クラスを初期化 myrandom::MyRand mr(1, 6); // 試行回数分繰り返す for (auto i = 0U; i < MCMAX; i++) { // 期待値に対するモンテカルロ・シミュレーションの結果を代入 mcresultavg.push_back(montecarloImplAvg(mr)); // どちらの文字列が先に出現したかどうかのモンテカルロ・シミュレーションの結果を代入 mcresultwinningavg.push_back(montecarloImplWinningAvg(mr)); } return std::make_pair(std::move(mcresultavg), std::move(mcresultwinningavg)); } #endif std::pair<tbb::concurrent_vector<mymap>, tbb::concurrent_vector<mymap2> > montecarloTBB() { // 期待値に対するモンテカルロ・シミュレーションの結果を格納するための可変長配列 tbb::concurrent_vector<mymap> mcresultavg; // どちらの文字列が先に出現したかどうかのモンテカルロ・シミュレーションの結果を格納するための可変長配列 tbb::concurrent_vector<mymap2> mcresultwinningavg; // MCMAX個の容量を確保 mcresultavg.reserve(MCMAX); mcresultwinningavg.reserve(MCMAX); // 試行回数分繰り返す tbb::parallel_for( 0U, MCMAX, 1U, [&mcresultavg, &mcresultwinningavg](auto) { // 自作乱数クラスを初期化 myrandom::MyRand mr(1, 6); // 期待値に対するモンテカルロ・シミュレーションの結果を代入 mcresultavg.push_back(montecarloImplAvg(mr)); // どちらの文字列が先に出現したかどうかのモンテカルロ・シミュレーションの結果を代入 mcresultwinningavg.push_back(montecarloImplWinningAvg(mr)); }); return std::make_pair(std::move(mcresultavg), std::move(mcresultwinningavg)); } mymap montecarloImplAvg(myrandom::MyRand & mr) { // UDのランダム文字列 auto const udstr(makerandomudstr(mr)); // 検索結果のstd::map mymap result; // 文字列が最初に出現するのは何文字目かを検索し結果を代入 for (auto const & str : udarray) { result.insert(std::make_pair(str, myfind(str, udstr))); } return result; } mymap2 montecarloImplWinningAvg(myrandom::MyRand & mr) { // UDのランダム文字列 auto const udstr(makerandomudstr(mr)); // 検索結果のstd::map mymap2 result; // どちらの文字列が先に出現したかの結果を代入 for (auto const & sp : cbarray) { result.insert(std::make_pair(sp, myfind(sp.first, udstr) < myfind(sp.second, udstr))); } // 検索結果を返す return result; } std::uint32_t myfind(std::string const & str, std::string const & udstr) { // 文字列の位置を検索 auto const pos = udstr.find(str); // posをその文字列の末尾の位置に変換 // もし文字列が見つかっていなかった場合はRANDNUMTABLELENに変換 return pos != std::string::npos ? static_cast<std::uint32_t>(pos + 3) : RANDNUMTABLELEN; } template <typename T> mymap sumMontecarloAvg(T const & mcresultavg) { // 各文字列に対して、期待値に対するモンテカルロ・シミュレーションの結果の和を格納するstd::map mymap trial; // std::mapの初期化 for (auto const & str : udarray) { trial[str] = 0; } // 試行回数分繰り返す for (auto const & mcr : mcresultavg) { for (auto && itr = mcr.begin(); itr != mcr.end(); ++itr) { trial[itr->first] += itr->second; } } return trial; } } <commit_msg>細かい修正<commit_after><|endoftext|>
<commit_before>// // OSGEventHandler.cpp // // Handle OSG events, turn them into VTP events. // // Copyright (c) 2011 Virtual Terrain Project // Free for all uses, see license.txt for details. // #include "vtlib/vtlib.h" #include "OSGEventHandler.h" #include "vtdata/vtLog.h" #define GEA osgGA::GUIEventAdapter // shorthand #define GEType osgGA::GUIEventAdapter::EventType // shorthand #define GEMask osgGA::GUIEventAdapter::ModKeyMask // shorthand #define GEKey osgGA::GUIEventAdapter::KeySymbol // shorthand bool vtOSGEventHandler::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { GEType etype = ea.getEventType(); //if (etype != osgGA::GUIEventAdapter::FRAME) // VTLOG("getEventType %d button %d\n", etype, ea.getButton()); switch (etype) { case GEType::KEYDOWN: //case GEType::KEYUP: handleKeyEvent(ea); break; case GEType::PUSH: case GEType::RELEASE: case GEType::DOUBLECLICK: case GEType::DRAG: case GEType::MOVE: handleMouseEvent(ea); break; case GEType::FRAME: break; case GEType::RESIZE: VTLOG("RESIZE %d %d\n", ea.getWindowWidth(), ea.getWindowHeight()); vtGetScene()->SetWindowSize(ea.getWindowWidth(), ea.getWindowHeight()); break; case GEType::SCROLL: VTLOG("SCROLL\n"); break; case GEType::CLOSE_WINDOW: VTLOG("CLOSE_WINDOW\n"); break; case GEType::QUIT_APPLICATION: VTLOG("QUIT_APPLICATION\n"); break; } return false; } void vtOSGEventHandler::handleKeyEvent(const osgGA::GUIEventAdapter& ea) { int vtkey = ea.getKey(); int flags = 0; int mkm = ea.getModKeyMask(); if (mkm & GEMask::MODKEY_SHIFT) flags |= VT_SHIFT; if (mkm & GEMask::MODKEY_CTRL) flags |= VT_CONTROL; if (mkm & GEMask::MODKEY_ALT) flags |= VT_ALT; switch (ea.getKey()) { case GEKey::KEY_Home: vtkey = VTK_HOME; break; case GEKey::KEY_Left: vtkey = VTK_LEFT; break; case GEKey::KEY_Up: vtkey = VTK_UP; break; case GEKey::KEY_Right: vtkey = VTK_RIGHT; break; case GEKey::KEY_Down: vtkey = VTK_DOWN; break; case GEKey::KEY_Page_Up: vtkey = VTK_PAGEUP; break; case GEKey::KEY_Page_Down: vtkey = VTK_PAGEDOWN; break; case GEKey::KEY_F1 : vtkey = VTK_F1; break; case GEKey::KEY_F2 : vtkey = VTK_F2; break; case GEKey::KEY_F3 : vtkey = VTK_F3; break; case GEKey::KEY_F4 : vtkey = VTK_F4; break; case GEKey::KEY_F5 : vtkey = VTK_F5; break; case GEKey::KEY_F6 : vtkey = VTK_F6; break; case GEKey::KEY_F7 : vtkey = VTK_F7; break; case GEKey::KEY_F8 : vtkey = VTK_F8; break; case GEKey::KEY_F9 : vtkey = VTK_F9; break; case GEKey::KEY_F10: vtkey = VTK_F10; break; case GEKey::KEY_F11: vtkey = VTK_F11; break; case GEKey::KEY_F12: vtkey = VTK_F12; break; case GEKey::KEY_Shift_L: vtkey = VTK_SHIFT; break; case GEKey::KEY_Shift_R: vtkey = VTK_SHIFT; break; case GEKey::KEY_Control_L: vtkey = VTK_CONTROL; break; case GEKey::KEY_Control_R: vtkey = VTK_CONTROL; break; case GEKey::KEY_Alt_L: vtkey = VTK_ALT; break; case GEKey::KEY_Alt_R: vtkey = VTK_ALT; break; } vtGetScene()->OnKey(vtkey, flags); } void vtOSGEventHandler::handleMouseEvent(const osgGA::GUIEventAdapter& ea) { // Turn OSG mouse event into a VT mouse event vtMouseEvent event; event.flags = 0; event.pos.Set(ea.getX(), ea.getWindowHeight()-1-ea.getY()); // Flip Y from OSG to everyone else int mkm = ea.getModKeyMask(); if (mkm & GEMask::MODKEY_SHIFT) event.flags |= VT_SHIFT; if (mkm & GEMask::MODKEY_CTRL) event.flags |= VT_CONTROL; if (mkm & GEMask::MODKEY_ALT) event.flags |= VT_ALT; GEType etype = ea.getEventType(); switch (etype) { case GEType::PUSH: event.type = VT_DOWN; if (ea.getButton() == GEA::LEFT_MOUSE_BUTTON) event.button = VT_LEFT; else if (ea.getButton() == GEA::MIDDLE_MOUSE_BUTTON) event.button = VT_MIDDLE; else if (ea.getButton() == GEA::RIGHT_MOUSE_BUTTON) event.button = VT_RIGHT; vtGetScene()->OnMouse(event); break; case GEType::RELEASE: event.type = VT_UP; if (ea.getButton() == GEA::LEFT_MOUSE_BUTTON) event.button = VT_LEFT; else if (ea.getButton() == GEA::MIDDLE_MOUSE_BUTTON) event.button = VT_MIDDLE; else if (ea.getButton() == GEA::RIGHT_MOUSE_BUTTON) event.button = VT_RIGHT; vtGetScene()->OnMouse(event); break; case GEType::DOUBLECLICK: break; case GEType::DRAG: case GEType::MOVE: event.type = VT_MOVE; if (ea.getButton() == 0) event.button = VT_LEFT; else if (ea.getButton() == 1) event.button = VT_MIDDLE; else if (ea.getButton() == 2) event.button = VT_RIGHT; vtGetScene()->OnMouse(event); break; } }<commit_msg>Fixed some compiler warnings<commit_after>// // OSGEventHandler.cpp // // Handle OSG events, turn them into VTP events. // // Copyright (c) 2011 Virtual Terrain Project // Free for all uses, see license.txt for details. // #include "vtlib/vtlib.h" #include "OSGEventHandler.h" #include "vtdata/vtLog.h" #define GEA osgGA::GUIEventAdapter // shorthand #define GEType osgGA::GUIEventAdapter::EventType // shorthand bool vtOSGEventHandler::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { GEType etype = ea.getEventType(); //if (etype != GEA::FRAME) // VTLOG("getEventType %d button %d\n", etype, ea.getButton()); switch (etype) { case GEA::KEYDOWN: //case GEA::KEYUP: handleKeyEvent(ea); break; case GEA::PUSH: case GEA::RELEASE: case GEA::DOUBLECLICK: case GEA::DRAG: case GEA::MOVE: handleMouseEvent(ea); break; case GEA::FRAME: break; case GEA::RESIZE: VTLOG("RESIZE %d %d\n", ea.getWindowWidth(), ea.getWindowHeight()); vtGetScene()->SetWindowSize(ea.getWindowWidth(), ea.getWindowHeight()); break; case GEA::SCROLL: VTLOG("SCROLL\n"); break; case GEA::CLOSE_WINDOW: VTLOG("CLOSE_WINDOW\n"); break; case GEA::QUIT_APPLICATION: VTLOG("QUIT_APPLICATION\n"); break; } return false; } void vtOSGEventHandler::handleKeyEvent(const osgGA::GUIEventAdapter& ea) { int vtkey = ea.getKey(); int flags = 0; int mkm = ea.getModKeyMask(); if (mkm & GEA::MODKEY_SHIFT) flags |= VT_SHIFT; if (mkm & GEA::MODKEY_CTRL) flags |= VT_CONTROL; if (mkm & GEA::MODKEY_ALT) flags |= VT_ALT; switch (ea.getKey()) { case GEA::KEY_Home: vtkey = VTK_HOME; break; case GEA::KEY_Left: vtkey = VTK_LEFT; break; case GEA::KEY_Up: vtkey = VTK_UP; break; case GEA::KEY_Right: vtkey = VTK_RIGHT; break; case GEA::KEY_Down: vtkey = VTK_DOWN; break; case GEA::KEY_Page_Up: vtkey = VTK_PAGEUP; break; case GEA::KEY_Page_Down: vtkey = VTK_PAGEDOWN; break; case GEA::KEY_F1 : vtkey = VTK_F1; break; case GEA::KEY_F2 : vtkey = VTK_F2; break; case GEA::KEY_F3 : vtkey = VTK_F3; break; case GEA::KEY_F4 : vtkey = VTK_F4; break; case GEA::KEY_F5 : vtkey = VTK_F5; break; case GEA::KEY_F6 : vtkey = VTK_F6; break; case GEA::KEY_F7 : vtkey = VTK_F7; break; case GEA::KEY_F8 : vtkey = VTK_F8; break; case GEA::KEY_F9 : vtkey = VTK_F9; break; case GEA::KEY_F10: vtkey = VTK_F10; break; case GEA::KEY_F11: vtkey = VTK_F11; break; case GEA::KEY_F12: vtkey = VTK_F12; break; case GEA::KEY_Shift_L: vtkey = VTK_SHIFT; break; case GEA::KEY_Shift_R: vtkey = VTK_SHIFT; break; case GEA::KEY_Control_L: vtkey = VTK_CONTROL; break; case GEA::KEY_Control_R: vtkey = VTK_CONTROL; break; case GEA::KEY_Alt_L: vtkey = VTK_ALT; break; case GEA::KEY_Alt_R: vtkey = VTK_ALT; break; } vtGetScene()->OnKey(vtkey, flags); } void vtOSGEventHandler::handleMouseEvent(const osgGA::GUIEventAdapter& ea) { // Turn OSG mouse event into a VT mouse event vtMouseEvent event; event.flags = 0; event.pos.Set(ea.getX(), ea.getWindowHeight()-1-ea.getY()); // Flip Y from OSG to everyone else int mkm = ea.getModKeyMask(); if (mkm & GEA::MODKEY_SHIFT) event.flags |= VT_SHIFT; if (mkm & GEA::MODKEY_CTRL) event.flags |= VT_CONTROL; if (mkm & GEA::MODKEY_ALT) event.flags |= VT_ALT; GEType etype = ea.getEventType(); switch (etype) { case GEA::PUSH: event.type = VT_DOWN; if (ea.getButton() == GEA::LEFT_MOUSE_BUTTON) event.button = VT_LEFT; else if (ea.getButton() == GEA::MIDDLE_MOUSE_BUTTON) event.button = VT_MIDDLE; else if (ea.getButton() == GEA::RIGHT_MOUSE_BUTTON) event.button = VT_RIGHT; vtGetScene()->OnMouse(event); break; case GEA::RELEASE: event.type = VT_UP; if (ea.getButton() == GEA::LEFT_MOUSE_BUTTON) event.button = VT_LEFT; else if (ea.getButton() == GEA::MIDDLE_MOUSE_BUTTON) event.button = VT_MIDDLE; else if (ea.getButton() == GEA::RIGHT_MOUSE_BUTTON) event.button = VT_RIGHT; vtGetScene()->OnMouse(event); break; case GEA::DOUBLECLICK: break; case GEA::DRAG: case GEA::MOVE: event.type = VT_MOVE; if (ea.getButton() == 0) event.button = VT_LEFT; else if (ea.getButton() == 1) event.button = VT_MIDDLE; else if (ea.getButton() == 2) event.button = VT_RIGHT; vtGetScene()->OnMouse(event); break; } }<|endoftext|>
<commit_before>#include <string> #include "protagonist.h" #include "drafter.h" #include "refractToV8.h" using std::string; using namespace v8; using namespace protagonist; NAN_METHOD(protagonist::ParseSync) { Nan::HandleScope scope; // Check arguments if (info.Length() != 1 && info.Length() != 2) { Nan::ThrowTypeError("wrong number of arguments, `parseSync(string, options)` expected"); return; } if (!info[0]->IsString()) { Nan::ThrowTypeError("wrong argument - string expected, `parseSync(string, options)`"); return; } if (info.Length() == 2 && !info[1]->IsObject()) { Nan::ThrowTypeError("wrong argument - object expected, `parseSync(string, options)`"); return; } // Get source data String::Utf8Value sourceData(info[0]->ToString()); // Prepare options drafter_parse_options parseOptions = {false}; drafter_serialize_options serializeOptions = {false, DRAFTER_SERIALIZE_JSON}; if (info.Length() == 2) { OptionsResult *optionsResult = ParseOptionsObject(Handle<Object>::Cast(info[1]), false); if (optionsResult->error != NULL) { Nan::ThrowTypeError(optionsResult->error); } parseOptions = optionsResult->parseOptions; serializeOptions = optionsResult->serializeOptions; FreeOptionsResult(&optionsResult); } // Parse the source data drafter_result *result; int err_code = drafter_parse_blueprint(*sourceData, &result, parseOptions); switch (err_code) { case DRAFTER_EUNKNOWN: Nan::ThrowError("Parser: Unknown Error"); break; case DRAFTER_EINVALID_INPUT: Nan::ThrowError("Parser: Invalid Input"); break; case DRAFTER_EINVALID_OUTPUT: Nan::ThrowError("Parser: Invalid Output"); break; default: break; } Local<Value> v8result = refract2v8(result, serializeOptions); info.GetReturnValue().Set(v8result); } <commit_msg>fix(parseSync): Free drafter parseResult<commit_after>#include <string> #include "protagonist.h" #include "drafter.h" #include "refractToV8.h" using std::string; using namespace v8; using namespace protagonist; NAN_METHOD(protagonist::ParseSync) { Nan::HandleScope scope; // Check arguments if (info.Length() != 1 && info.Length() != 2) { Nan::ThrowTypeError("wrong number of arguments, `parseSync(string, options)` expected"); return; } if (!info[0]->IsString()) { Nan::ThrowTypeError("wrong argument - string expected, `parseSync(string, options)`"); return; } if (info.Length() == 2 && !info[1]->IsObject()) { Nan::ThrowTypeError("wrong argument - object expected, `parseSync(string, options)`"); return; } // Get source data String::Utf8Value sourceData(info[0]->ToString()); // Prepare options drafter_parse_options parseOptions = {false}; drafter_serialize_options serializeOptions = {false, DRAFTER_SERIALIZE_JSON}; if (info.Length() == 2) { OptionsResult *optionsResult = ParseOptionsObject(Handle<Object>::Cast(info[1]), false); if (optionsResult->error != NULL) { Nan::ThrowTypeError(optionsResult->error); } parseOptions = optionsResult->parseOptions; serializeOptions = optionsResult->serializeOptions; FreeOptionsResult(&optionsResult); } // Parse the source data drafter_result *result; int err_code = drafter_parse_blueprint(*sourceData, &result, parseOptions); switch (err_code) { case DRAFTER_EUNKNOWN: Nan::ThrowError("Parser: Unknown Error"); break; case DRAFTER_EINVALID_INPUT: Nan::ThrowError("Parser: Invalid Input"); break; case DRAFTER_EINVALID_OUTPUT: Nan::ThrowError("Parser: Invalid Output"); break; default: break; } Local<Value> v8result = refract2v8(result, serializeOptions); drafter_free_result(result); info.GetReturnValue().Set(v8result); } <|endoftext|>
<commit_before>//===-- CommandObjectDisassemble.cpp ----------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "CommandObjectDisassemble.h" // C Includes // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/Core/AddressRange.h" #include "lldb/Interpreter/Args.h" #include "lldb/Interpreter/CommandCompletions.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" #include "lldb/Core/Disassembler.h" #include "lldb/Interpreter/Options.h" #include "lldb/Core/SourceManager.h" #include "lldb/Target/StackFrame.h" #include "lldb/Symbol/Symbol.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #define DEFAULT_DISASM_BYTE_SIZE 32 using namespace lldb; using namespace lldb_private; CommandObjectDisassemble::CommandOptions::CommandOptions () : Options(), m_func_name(), m_start_addr(), m_end_addr () { ResetOptionValues(); } CommandObjectDisassemble::CommandOptions::~CommandOptions () { } Error CommandObjectDisassemble::CommandOptions::SetOptionValue (int option_idx, const char *option_arg) { Error error; char short_option = (char) m_getopt_table[option_idx].val; switch (short_option) { case 'm': show_mixed = true; break; case 'c': num_lines_context = Args::StringToUInt32(option_arg, 0, 0); break; case 'b': show_bytes = true; break; case 's': m_start_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 0); if (m_start_addr == LLDB_INVALID_ADDRESS) m_start_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 16); if (m_start_addr == LLDB_INVALID_ADDRESS) error.SetErrorStringWithFormat ("Invalid start address string '%s'.\n", optarg); break; case 'e': m_end_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 0); if (m_end_addr == LLDB_INVALID_ADDRESS) m_end_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 16); if (m_end_addr == LLDB_INVALID_ADDRESS) error.SetErrorStringWithFormat ("Invalid end address string '%s'.\n", optarg); break; case 'n': m_func_name = option_arg; break; case 'r': raw = true; break; default: error.SetErrorStringWithFormat("Unrecognized short option '%c'.\n", short_option); break; } return error; } void CommandObjectDisassemble::CommandOptions::ResetOptionValues () { Options::ResetOptionValues(); show_mixed = false; show_bytes = false; num_lines_context = 0; m_func_name.clear(); m_start_addr = LLDB_INVALID_ADDRESS; m_end_addr = LLDB_INVALID_ADDRESS; } const lldb::OptionDefinition* CommandObjectDisassemble::CommandOptions::GetDefinitions () { return g_option_table; } lldb::OptionDefinition CommandObjectDisassemble::CommandOptions::g_option_table[] = { { LLDB_OPT_SET_ALL, false, "bytes", 'b', no_argument, NULL, 0, NULL, "Show opcode bytes when disassembling."}, { LLDB_OPT_SET_ALL, false, "context", 'c', required_argument, NULL, 0, "<num-lines>", "Number of context lines of source to show."}, { LLDB_OPT_SET_ALL, false, "mixed", 'm', no_argument, NULL, 0, NULL, "Enable mixed source and assembly display."}, { LLDB_OPT_SET_ALL, false, "raw", 'r', no_argument, NULL, 0, NULL, "Print raw disassembly with no symbol information."}, { LLDB_OPT_SET_1, true, "start-address", 's', required_argument, NULL, 0, "<start-address>", "Address to start disassembling."}, { LLDB_OPT_SET_1, false, "end-address", 'e', required_argument, NULL, 0, "<end-address>", "Address to start disassembling."}, { LLDB_OPT_SET_2, true, "name", 'n', required_argument, NULL, CommandCompletions::eSymbolCompletion, "<function-name>", "Disassemble entire contents of the given function name."}, { LLDB_OPT_SET_3, false, "current-frame", 'f', no_argument, NULL, 0, "<current-frame>", "Disassemble entire contents of the current frame's function."}, { 0, false, NULL, 0, 0, NULL, 0, NULL, NULL } }; //------------------------------------------------------------------------- // CommandObjectDisassemble //------------------------------------------------------------------------- CommandObjectDisassemble::CommandObjectDisassemble () : CommandObject ("disassemble", "Disassemble bytes in the current function or anywhere in the inferior program.", "disassemble [<cmd-options>]") { } CommandObjectDisassemble::~CommandObjectDisassemble() { } void CommandObjectDisassemble::Disassemble ( CommandContext *context, CommandInterpreter *interpreter, CommandReturnObject &result, Disassembler *disassembler, const SymbolContextList &sc_list ) { const size_t count = sc_list.GetSize(); SymbolContext sc; AddressRange range; for (size_t i=0; i<count; ++i) { if (sc_list.GetContextAtIndex(i, sc) == false) break; if (sc.GetAddressRange(eSymbolContextFunction | eSymbolContextSymbol, range)) { lldb::addr_t addr = range.GetBaseAddress().GetLoadAddress(context->GetExecutionContext().process); if (addr != LLDB_INVALID_ADDRESS) { lldb::addr_t end_addr = addr + range.GetByteSize(); Disassemble (context, interpreter, result, disassembler, addr, end_addr); } } } } void CommandObjectDisassemble::Disassemble ( CommandContext *context, CommandInterpreter *interpreter, CommandReturnObject &result, Disassembler *disassembler, lldb::addr_t addr, lldb::addr_t end_addr ) { if (addr == LLDB_INVALID_ADDRESS) return; if (end_addr == LLDB_INVALID_ADDRESS || addr >= end_addr) end_addr = addr + DEFAULT_DISASM_BYTE_SIZE; ExecutionContext exe_ctx (context->GetExecutionContext()); DataExtractor data; size_t bytes_disassembled = disassembler->ParseInstructions (&exe_ctx, eAddressTypeLoad, addr, end_addr - addr, data); if (bytes_disassembled == 0) { // Nothing got disassembled... } else { // We got some things disassembled... size_t num_instructions = disassembler->GetInstructionList().GetSize(); uint32_t offset = 0; Stream &output_stream = result.GetOutputStream(); SymbolContext sc; SymbolContext prev_sc; AddressRange sc_range; if (m_options.show_mixed) output_stream.IndentMore (); for (size_t i=0; i<num_instructions; ++i) { Disassembler::Instruction *inst = disassembler->GetInstructionList().GetInstructionAtIndex (i); if (inst) { lldb::addr_t curr_addr = addr + offset; if (m_options.show_mixed) { Process *process = context->GetExecutionContext().process; if (!sc_range.ContainsLoadAddress (curr_addr, process)) { prev_sc = sc; Address curr_so_addr; if (process && process->ResolveLoadAddress (curr_addr, curr_so_addr)) { if (curr_so_addr.GetSection()) { Module *module = curr_so_addr.GetSection()->GetModule(); uint32_t resolved_mask = module->ResolveSymbolContextForAddress(curr_so_addr, eSymbolContextEverything, sc); if (resolved_mask) { sc.GetAddressRange (eSymbolContextEverything, sc_range); if (sc != prev_sc) { if (offset != 0) output_stream.EOL(); sc.DumpStopContext(&output_stream, process, curr_so_addr); output_stream.EOL(); if (sc.comp_unit && sc.line_entry.IsValid()) { interpreter->GetSourceManager().DisplaySourceLinesWithLineNumbers ( sc.line_entry.file, sc.line_entry.line, m_options.num_lines_context, m_options.num_lines_context, m_options.num_lines_context ? "->" : "", &output_stream); } } } } } } } if (m_options.show_mixed) output_stream.IndentMore (); output_stream.Indent(); size_t inst_byte_size = inst->GetByteSize(); inst->Dump(&output_stream, curr_addr, m_options.show_bytes ? &data : NULL, offset, exe_ctx, m_options.raw); output_stream.EOL(); offset += inst_byte_size; if (m_options.show_mixed) output_stream.IndentLess (); } else { break; } } if (m_options.show_mixed) output_stream.IndentLess (); } } bool CommandObjectDisassemble::Execute ( Args& command, CommandContext *context, CommandInterpreter *interpreter, CommandReturnObject &result ) { Target *target = context->GetTarget(); if (target == NULL) { result.AppendError ("invalid target, set executable file using 'file' command"); result.SetStatus (eReturnStatusFailed); return false; } ArchSpec arch(target->GetArchitecture()); if (!arch.IsValid()) { result.AppendError ("target needs valid architecure in order to be able to disassemble"); result.SetStatus (eReturnStatusFailed); return false; } Disassembler *disassembler = Disassembler::FindPlugin(arch); if (disassembler == NULL) { result.AppendErrorWithFormat ("Unable to find Disassembler plug-in for %s architecture.\n", arch.AsCString()); result.SetStatus (eReturnStatusFailed); return false; } result.SetStatus (eReturnStatusSuccessFinishResult); lldb::addr_t addr = LLDB_INVALID_ADDRESS; lldb::addr_t end_addr = LLDB_INVALID_ADDRESS; ConstString name; const size_t argc = command.GetArgumentCount(); if (argc != 0) { result.AppendErrorWithFormat ("\"disassemble\" doesn't take any arguments.\n"); result.SetStatus (eReturnStatusFailed); return false; } if (m_options.m_start_addr != LLDB_INVALID_ADDRESS) { addr = m_options.m_start_addr; if (m_options.m_end_addr != LLDB_INVALID_ADDRESS) { end_addr = m_options.m_end_addr; if (end_addr < addr) { result.AppendErrorWithFormat ("End address before start address.\n"); result.SetStatus (eReturnStatusFailed); return false; } } else end_addr = addr + DEFAULT_DISASM_BYTE_SIZE; } else if (!m_options.m_func_name.empty()) { ConstString tmpname(m_options.m_func_name.c_str()); name = tmpname; } else { ExecutionContext exe_ctx(context->GetExecutionContext()); if (exe_ctx.frame) { SymbolContext sc(exe_ctx.frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextSymbol)); if (sc.function) { addr = sc.function->GetAddressRange().GetBaseAddress().GetLoadAddress(exe_ctx.process); if (addr != LLDB_INVALID_ADDRESS) end_addr = addr + sc.function->GetAddressRange().GetByteSize(); } else if (sc.symbol && sc.symbol->GetAddressRangePtr()) { addr = sc.symbol->GetAddressRangePtr()->GetBaseAddress().GetLoadAddress(exe_ctx.process); if (addr != LLDB_INVALID_ADDRESS) { end_addr = addr + sc.symbol->GetAddressRangePtr()->GetByteSize(); if (addr == end_addr) end_addr += DEFAULT_DISASM_BYTE_SIZE; } } else { addr = exe_ctx.frame->GetPC().GetLoadAddress(exe_ctx.process); if (addr != LLDB_INVALID_ADDRESS) end_addr = addr + DEFAULT_DISASM_BYTE_SIZE; } } else { result.AppendError ("invalid frame"); result.SetStatus (eReturnStatusFailed); return false; } } if (!name.IsEmpty()) { SymbolContextList sc_list; if (target->GetImages().FindFunctions(name, sc_list)) { Disassemble (context, interpreter, result, disassembler, sc_list); } else if (target->GetImages().FindSymbolsWithNameAndType(name, eSymbolTypeCode, sc_list)) { Disassemble (context, interpreter, result, disassembler, sc_list); } else { result.AppendErrorWithFormat ("Unable to find symbol with name '%s'.\n", name.GetCString()); result.SetStatus (eReturnStatusFailed); return false; } } else { Disassemble (context, interpreter, result, disassembler, addr, end_addr); } return result.Succeeded(); } <commit_msg>Unstick the -r option for the disassemble command.<commit_after>//===-- CommandObjectDisassemble.cpp ----------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "CommandObjectDisassemble.h" // C Includes // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/Core/AddressRange.h" #include "lldb/Interpreter/Args.h" #include "lldb/Interpreter/CommandCompletions.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" #include "lldb/Core/Disassembler.h" #include "lldb/Interpreter/Options.h" #include "lldb/Core/SourceManager.h" #include "lldb/Target/StackFrame.h" #include "lldb/Symbol/Symbol.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #define DEFAULT_DISASM_BYTE_SIZE 32 using namespace lldb; using namespace lldb_private; CommandObjectDisassemble::CommandOptions::CommandOptions () : Options(), m_func_name(), m_start_addr(), m_end_addr () { ResetOptionValues(); } CommandObjectDisassemble::CommandOptions::~CommandOptions () { } Error CommandObjectDisassemble::CommandOptions::SetOptionValue (int option_idx, const char *option_arg) { Error error; char short_option = (char) m_getopt_table[option_idx].val; switch (short_option) { case 'm': show_mixed = true; break; case 'c': num_lines_context = Args::StringToUInt32(option_arg, 0, 0); break; case 'b': show_bytes = true; break; case 's': m_start_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 0); if (m_start_addr == LLDB_INVALID_ADDRESS) m_start_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 16); if (m_start_addr == LLDB_INVALID_ADDRESS) error.SetErrorStringWithFormat ("Invalid start address string '%s'.\n", optarg); break; case 'e': m_end_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 0); if (m_end_addr == LLDB_INVALID_ADDRESS) m_end_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 16); if (m_end_addr == LLDB_INVALID_ADDRESS) error.SetErrorStringWithFormat ("Invalid end address string '%s'.\n", optarg); break; case 'n': m_func_name = option_arg; break; case 'r': raw = true; break; default: error.SetErrorStringWithFormat("Unrecognized short option '%c'.\n", short_option); break; } return error; } void CommandObjectDisassemble::CommandOptions::ResetOptionValues () { Options::ResetOptionValues(); show_mixed = false; show_bytes = false; num_lines_context = 0; m_func_name.clear(); m_start_addr = LLDB_INVALID_ADDRESS; m_end_addr = LLDB_INVALID_ADDRESS; raw = false; } const lldb::OptionDefinition* CommandObjectDisassemble::CommandOptions::GetDefinitions () { return g_option_table; } lldb::OptionDefinition CommandObjectDisassemble::CommandOptions::g_option_table[] = { { LLDB_OPT_SET_ALL, false, "bytes", 'b', no_argument, NULL, 0, NULL, "Show opcode bytes when disassembling."}, { LLDB_OPT_SET_ALL, false, "context", 'c', required_argument, NULL, 0, "<num-lines>", "Number of context lines of source to show."}, { LLDB_OPT_SET_ALL, false, "mixed", 'm', no_argument, NULL, 0, NULL, "Enable mixed source and assembly display."}, { LLDB_OPT_SET_ALL, false, "raw", 'r', no_argument, NULL, 0, NULL, "Print raw disassembly with no symbol information."}, { LLDB_OPT_SET_1, true, "start-address", 's', required_argument, NULL, 0, "<start-address>", "Address to start disassembling."}, { LLDB_OPT_SET_1, false, "end-address", 'e', required_argument, NULL, 0, "<end-address>", "Address to start disassembling."}, { LLDB_OPT_SET_2, true, "name", 'n', required_argument, NULL, CommandCompletions::eSymbolCompletion, "<function-name>", "Disassemble entire contents of the given function name."}, { LLDB_OPT_SET_3, false, "current-frame", 'f', no_argument, NULL, 0, "<current-frame>", "Disassemble entire contents of the current frame's function."}, { 0, false, NULL, 0, 0, NULL, 0, NULL, NULL } }; //------------------------------------------------------------------------- // CommandObjectDisassemble //------------------------------------------------------------------------- CommandObjectDisassemble::CommandObjectDisassemble () : CommandObject ("disassemble", "Disassemble bytes in the current function or anywhere in the inferior program.", "disassemble [<cmd-options>]") { } CommandObjectDisassemble::~CommandObjectDisassemble() { } void CommandObjectDisassemble::Disassemble ( CommandContext *context, CommandInterpreter *interpreter, CommandReturnObject &result, Disassembler *disassembler, const SymbolContextList &sc_list ) { const size_t count = sc_list.GetSize(); SymbolContext sc; AddressRange range; for (size_t i=0; i<count; ++i) { if (sc_list.GetContextAtIndex(i, sc) == false) break; if (sc.GetAddressRange(eSymbolContextFunction | eSymbolContextSymbol, range)) { lldb::addr_t addr = range.GetBaseAddress().GetLoadAddress(context->GetExecutionContext().process); if (addr != LLDB_INVALID_ADDRESS) { lldb::addr_t end_addr = addr + range.GetByteSize(); Disassemble (context, interpreter, result, disassembler, addr, end_addr); } } } } void CommandObjectDisassemble::Disassemble ( CommandContext *context, CommandInterpreter *interpreter, CommandReturnObject &result, Disassembler *disassembler, lldb::addr_t addr, lldb::addr_t end_addr ) { if (addr == LLDB_INVALID_ADDRESS) return; if (end_addr == LLDB_INVALID_ADDRESS || addr >= end_addr) end_addr = addr + DEFAULT_DISASM_BYTE_SIZE; ExecutionContext exe_ctx (context->GetExecutionContext()); DataExtractor data; size_t bytes_disassembled = disassembler->ParseInstructions (&exe_ctx, eAddressTypeLoad, addr, end_addr - addr, data); if (bytes_disassembled == 0) { // Nothing got disassembled... } else { // We got some things disassembled... size_t num_instructions = disassembler->GetInstructionList().GetSize(); uint32_t offset = 0; Stream &output_stream = result.GetOutputStream(); SymbolContext sc; SymbolContext prev_sc; AddressRange sc_range; if (m_options.show_mixed) output_stream.IndentMore (); for (size_t i=0; i<num_instructions; ++i) { Disassembler::Instruction *inst = disassembler->GetInstructionList().GetInstructionAtIndex (i); if (inst) { lldb::addr_t curr_addr = addr + offset; if (m_options.show_mixed) { Process *process = context->GetExecutionContext().process; if (!sc_range.ContainsLoadAddress (curr_addr, process)) { prev_sc = sc; Address curr_so_addr; if (process && process->ResolveLoadAddress (curr_addr, curr_so_addr)) { if (curr_so_addr.GetSection()) { Module *module = curr_so_addr.GetSection()->GetModule(); uint32_t resolved_mask = module->ResolveSymbolContextForAddress(curr_so_addr, eSymbolContextEverything, sc); if (resolved_mask) { sc.GetAddressRange (eSymbolContextEverything, sc_range); if (sc != prev_sc) { if (offset != 0) output_stream.EOL(); sc.DumpStopContext(&output_stream, process, curr_so_addr); output_stream.EOL(); if (sc.comp_unit && sc.line_entry.IsValid()) { interpreter->GetSourceManager().DisplaySourceLinesWithLineNumbers ( sc.line_entry.file, sc.line_entry.line, m_options.num_lines_context, m_options.num_lines_context, m_options.num_lines_context ? "->" : "", &output_stream); } } } } } } } if (m_options.show_mixed) output_stream.IndentMore (); output_stream.Indent(); size_t inst_byte_size = inst->GetByteSize(); inst->Dump(&output_stream, curr_addr, m_options.show_bytes ? &data : NULL, offset, exe_ctx, m_options.raw); output_stream.EOL(); offset += inst_byte_size; if (m_options.show_mixed) output_stream.IndentLess (); } else { break; } } if (m_options.show_mixed) output_stream.IndentLess (); } } bool CommandObjectDisassemble::Execute ( Args& command, CommandContext *context, CommandInterpreter *interpreter, CommandReturnObject &result ) { Target *target = context->GetTarget(); if (target == NULL) { result.AppendError ("invalid target, set executable file using 'file' command"); result.SetStatus (eReturnStatusFailed); return false; } ArchSpec arch(target->GetArchitecture()); if (!arch.IsValid()) { result.AppendError ("target needs valid architecure in order to be able to disassemble"); result.SetStatus (eReturnStatusFailed); return false; } Disassembler *disassembler = Disassembler::FindPlugin(arch); if (disassembler == NULL) { result.AppendErrorWithFormat ("Unable to find Disassembler plug-in for %s architecture.\n", arch.AsCString()); result.SetStatus (eReturnStatusFailed); return false; } result.SetStatus (eReturnStatusSuccessFinishResult); lldb::addr_t addr = LLDB_INVALID_ADDRESS; lldb::addr_t end_addr = LLDB_INVALID_ADDRESS; ConstString name; const size_t argc = command.GetArgumentCount(); if (argc != 0) { result.AppendErrorWithFormat ("\"disassemble\" doesn't take any arguments.\n"); result.SetStatus (eReturnStatusFailed); return false; } if (m_options.m_start_addr != LLDB_INVALID_ADDRESS) { addr = m_options.m_start_addr; if (m_options.m_end_addr != LLDB_INVALID_ADDRESS) { end_addr = m_options.m_end_addr; if (end_addr < addr) { result.AppendErrorWithFormat ("End address before start address.\n"); result.SetStatus (eReturnStatusFailed); return false; } } else end_addr = addr + DEFAULT_DISASM_BYTE_SIZE; } else if (!m_options.m_func_name.empty()) { ConstString tmpname(m_options.m_func_name.c_str()); name = tmpname; } else { ExecutionContext exe_ctx(context->GetExecutionContext()); if (exe_ctx.frame) { SymbolContext sc(exe_ctx.frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextSymbol)); if (sc.function) { addr = sc.function->GetAddressRange().GetBaseAddress().GetLoadAddress(exe_ctx.process); if (addr != LLDB_INVALID_ADDRESS) end_addr = addr + sc.function->GetAddressRange().GetByteSize(); } else if (sc.symbol && sc.symbol->GetAddressRangePtr()) { addr = sc.symbol->GetAddressRangePtr()->GetBaseAddress().GetLoadAddress(exe_ctx.process); if (addr != LLDB_INVALID_ADDRESS) { end_addr = addr + sc.symbol->GetAddressRangePtr()->GetByteSize(); if (addr == end_addr) end_addr += DEFAULT_DISASM_BYTE_SIZE; } } else { addr = exe_ctx.frame->GetPC().GetLoadAddress(exe_ctx.process); if (addr != LLDB_INVALID_ADDRESS) end_addr = addr + DEFAULT_DISASM_BYTE_SIZE; } } else { result.AppendError ("invalid frame"); result.SetStatus (eReturnStatusFailed); return false; } } if (!name.IsEmpty()) { SymbolContextList sc_list; if (target->GetImages().FindFunctions(name, sc_list)) { Disassemble (context, interpreter, result, disassembler, sc_list); } else if (target->GetImages().FindSymbolsWithNameAndType(name, eSymbolTypeCode, sc_list)) { Disassemble (context, interpreter, result, disassembler, sc_list); } else { result.AppendErrorWithFormat ("Unable to find symbol with name '%s'.\n", name.GetCString()); result.SetStatus (eReturnStatusFailed); return false; } } else { Disassemble (context, interpreter, result, disassembler, addr, end_addr); } return result.Succeeded(); } <|endoftext|>
<commit_before>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Stay tuned using twitter @navitia IRC #navitia on freenode https://groups.google.com/d/forum/navitia www.navitia.io */ #include "fill_disruption_from_chaos.h" #include "utils/logger.h" #include "type/datetime.h" #include <boost/make_shared.hpp> #include <boost/variant/static_visitor.hpp> #include <boost/variant/apply_visitor.hpp> #include <boost/range/algorithm/for_each.hpp> #include "boost/date_time/posix_time/posix_time.hpp" namespace navitia { namespace nt = navitia::type; namespace bt = boost::posix_time; static boost::shared_ptr<nt::new_disruption::Tag> make_tag(const chaos::Tag& chaos_tag, nt::new_disruption::DisruptionHolder& holder) { auto from_posix = navitia::from_posix_timestamp; auto& weak_tag = holder.tags[chaos_tag.id()]; if (auto tag = weak_tag.lock()) { return std::move(tag); } auto tag = boost::make_shared<nt::new_disruption::Tag>(); tag->uri = chaos_tag.id(); tag->name = chaos_tag.name(); tag->created_at = from_posix(chaos_tag.created_at()); tag->updated_at = from_posix(chaos_tag.updated_at()); weak_tag = tag; return std::move(tag); } static boost::shared_ptr<nt::new_disruption::Cause> make_cause(const chaos::Cause& chaos_cause, nt::new_disruption::DisruptionHolder& holder) { auto from_posix = navitia::from_posix_timestamp; auto& weak_cause = holder.causes[chaos_cause.id()]; if (auto cause = weak_cause.lock()) { return std::move(cause); } auto cause = boost::make_shared<nt::new_disruption::Cause>(); cause->uri = chaos_cause.id(); cause->wording = chaos_cause.wording(); cause->created_at = from_posix(chaos_cause.created_at()); cause->updated_at = from_posix(chaos_cause.updated_at()); weak_cause = cause; return std::move(cause); } static boost::shared_ptr<nt::new_disruption::Severity> make_severity(const chaos::Severity& chaos_severity, nt::new_disruption::DisruptionHolder& holder) { namespace tr = transit_realtime; namespace new_disr = nt::new_disruption; auto from_posix = navitia::from_posix_timestamp; auto& weak_severity = holder.severities[chaos_severity.id()]; if (auto severity = weak_severity.lock()) { return std::move(severity); } auto severity = boost::make_shared<new_disr::Severity>(); severity->uri = chaos_severity.id(); severity->wording = chaos_severity.wording(); severity->created_at = from_posix(chaos_severity.created_at()); severity->updated_at = from_posix(chaos_severity.updated_at()); severity->color = chaos_severity.color(); severity->priority = chaos_severity.priority(); switch (chaos_severity.effect()) { #define EFFECT_ENUM_CONVERSION(e) \ case tr::Alert_Effect_##e: severity->effect = new_disr::Effect::e; break EFFECT_ENUM_CONVERSION(NO_SERVICE); EFFECT_ENUM_CONVERSION(REDUCED_SERVICE); EFFECT_ENUM_CONVERSION(SIGNIFICANT_DELAYS); EFFECT_ENUM_CONVERSION(DETOUR); EFFECT_ENUM_CONVERSION(ADDITIONAL_SERVICE); EFFECT_ENUM_CONVERSION(MODIFIED_SERVICE); EFFECT_ENUM_CONVERSION(OTHER_EFFECT); EFFECT_ENUM_CONVERSION(UNKNOWN_EFFECT); EFFECT_ENUM_CONVERSION(STOP_MOVED); #undef EFFECT_ENUM_CONVERSION } return std::move(severity); } static boost::optional<nt::new_disruption::LineSection> make_line_section(const chaos::PtObject& chaos_section, nt::PT_Data& pt_data, const boost::shared_ptr<nt::new_disruption::Impact>& impact) { if (!chaos_section.has_pt_line_section()) { LOG4CPLUS_WARN(log4cplus::Logger::getInstance("log"), "fill_disruption_from_chaos: LineSection invalid!"); return boost::none; } const auto& pb_section = chaos_section.pt_line_section(); nt::new_disruption::LineSection line_section; auto* line = find_or_default(pb_section.line().uri(), pt_data.lines_map); if (line) { line_section.line = line; } else { LOG4CPLUS_WARN(log4cplus::Logger::getInstance("log"), "fill_disruption_from_chaos: line id " << pb_section.line().uri() << " in LineSection invalid!"); return boost::none; } if (const auto* start = find_or_default(pb_section.start_point().uri(), pt_data.stop_areas_map)) { line_section.start_point = start; } else { LOG4CPLUS_WARN(log4cplus::Logger::getInstance("log"), "fill_disruption_from_chaos: start_point id " << pb_section.start_point().uri() << " in LineSection invalid!"); return boost::none; } if (const auto* end = find_or_default(pb_section.end_point().uri(), pt_data.stop_areas_map)) { line_section.end_point = end; } else { LOG4CPLUS_WARN(log4cplus::Logger::getInstance("log"), "fill_disruption_from_chaos: end_point id " << pb_section.end_point().uri() << " in LineSection invalid!"); return boost::none; } if (impact) line->add_impact(impact); return line_section; } static std::vector<nt::new_disruption::PtObj> make_pt_objects(const google::protobuf::RepeatedPtrField<chaos::PtObject>& chaos_pt_objects, nt::PT_Data& pt_data, const boost::shared_ptr<nt::new_disruption::Impact>& impact = {}) { using namespace nt::new_disruption; std::vector<PtObj> res; for (const auto& chaos_pt_object: chaos_pt_objects) { switch (chaos_pt_object.pt_object_type()) { case chaos::PtObject_Type_network: res.push_back(make_pt_obj(nt::Type_e::Network, chaos_pt_object.uri(), pt_data, impact)); break; case chaos::PtObject_Type_stop_area: res.push_back(make_pt_obj(nt::Type_e::StopArea, chaos_pt_object.uri(), pt_data, impact)); break; case chaos::PtObject_Type_line_section: if (auto line_section = make_line_section(chaos_pt_object, pt_data, impact)) { res.push_back(*line_section); } break; case chaos::PtObject_Type_line: res.push_back(make_pt_obj(nt::Type_e::Line, chaos_pt_object.uri(), pt_data, impact)); break; case chaos::PtObject_Type_route: res.push_back(make_pt_obj(nt::Type_e::Route, chaos_pt_object.uri(), pt_data, impact)); break; case chaos::PtObject_Type_unkown_type: res.push_back(UnknownPtObj()); break; } // no created_at and updated_at? } return res; } static boost::shared_ptr<nt::new_disruption::Impact> make_impact(const chaos::Impact& chaos_impact, nt::PT_Data& pt_data) { auto from_posix = navitia::from_posix_timestamp; nt::new_disruption::DisruptionHolder& holder = pt_data.disruption_holder; auto impact = boost::make_shared<nt::new_disruption::Impact>(); impact->uri = chaos_impact.id(); impact->created_at = from_posix(chaos_impact.created_at()); impact->updated_at = from_posix(chaos_impact.updated_at()); for (const auto& chaos_ap: chaos_impact.application_periods()) { impact->application_periods.emplace_back(from_posix(chaos_ap.start()), from_posix(chaos_ap.end())); } impact->severity = make_severity(chaos_impact.severity(), holder); impact->informed_entities = make_pt_objects(chaos_impact.informed_entities(), pt_data, impact); for (const auto& chaos_message: chaos_impact.messages()) { const auto& channel = chaos_message.channel(); impact->messages.push_back({ chaos_message.text(), channel.id(), channel.name(), channel.content_type(), from_posix(chaos_message.created_at()), from_posix(chaos_message.updated_at()), }); } return std::move(impact); } struct apply_impact_visitor : public boost::static_visitor<> { boost::shared_ptr<nt::new_disruption::Impact> impact; nt::PT_Data& pt_data; apply_impact_visitor(boost::shared_ptr<nt::new_disruption::Impact> impact, nt::PT_Data& pt_data) : impact(impact), pt_data(pt_data) {} void operator()(nt::new_disruption::UnknownPtObj&) { } void operator()(const nt::Network * network) { for(auto line : network->line_list) { deactivate_vp_of(line); } } void operator()(const nt::StopArea * ) { } void operator()(nt::new_disruption::LineSection & ) { } void operator()(const nt::Line *line) { deactivate_vp_of(line); } void operator()(const nt::Route * route) { deactivate_vp_of(route); } void deactivate_vp_of(const nt::Route* route) const { auto f = [&](nt::VehicleJourney& vj) { nt::ValidityPattern vp(vj.adapted_validity_pattern); bool is_impacted = false; for (auto period : impact->application_periods) { bt::time_iterator titr(period.begin(), bt::hours(24)); for(;titr<period.end(); ++titr) { auto day = to_int_date(*titr); if (vp.check(day)) { vp.remove(day); is_impacted = true; } } } if (is_impacted) { for (auto vp_ : pt_data.validity_patterns) { if (vp_->days == vp.days) { vj.adapted_validity_pattern = vp_; return true; } } // We haven't found this vp, so we need to create it auto vp_ = new nt::ValidityPattern(vp); pt_data.validity_patterns.push_back(vp_); vj.adapted_validity_pattern = vp_; } return true; }; for (auto journey_pattern : route->journey_pattern_list) { journey_pattern->for_each_vehicle_journey(f); } } void deactivate_vp_of(const nt::Line* line) { for(auto route : line->route_list) { deactivate_vp_of(route); } } }; void apply_impact(boost::shared_ptr<nt::new_disruption::Impact>impact, nt::PT_Data& pt_data) { if (impact->severity->effect == nt::new_disruption::Effect::NO_SERVICE) { apply_impact_visitor v(impact, pt_data); boost::for_each(impact->informed_entities, boost::apply_visitor(v)); } } void delete_disruption(nt::PT_Data& pt_data, const std::string& disruption_id) { nt::new_disruption::DisruptionHolder &holder = pt_data.disruption_holder; auto it = find_if(holder.disruptions.begin(), holder.disruptions.end(), [&disruption_id](const std::unique_ptr<nt::new_disruption::Disruption>& disruption){ return disruption->uri == disruption_id; }); if(it != holder.disruptions.end()){ holder.disruptions.erase(it); //the disruption has ownership over the impacts so all items a deleted in cascade } } void add_disruption(nt::PT_Data& pt_data, const chaos::Disruption& chaos_disruption) { auto from_posix = navitia::from_posix_timestamp; nt::new_disruption::DisruptionHolder &holder = pt_data.disruption_holder; //we delete the disrupion before adding the new one delete_disruption(pt_data, chaos_disruption.id()); auto disruption = std::make_unique<nt::new_disruption::Disruption>(); disruption->uri = chaos_disruption.id(); disruption->reference = chaos_disruption.reference(); disruption->publication_period = { from_posix(chaos_disruption.publication_period().start()), from_posix(chaos_disruption.publication_period().end()) }; disruption->created_at = from_posix(chaos_disruption.created_at()); disruption->updated_at = from_posix(chaos_disruption.updated_at()); disruption->cause = make_cause(chaos_disruption.cause(), holder); for (const auto& chaos_impact: chaos_disruption.impacts()) { auto impact = make_impact(chaos_impact, pt_data); disruption->add_impact(impact); apply_impact(impact, pt_data); } disruption->localization = make_pt_objects(chaos_disruption.localization(), pt_data); for (const auto& chaos_tag: chaos_disruption.tags()) { disruption->tags.push_back(make_tag(chaos_tag, holder)); } disruption->note = chaos_disruption.note(); holder.disruptions.push_back(std::move(disruption)); } } // namespace navitia <commit_msg>chaos: add block line_section support<commit_after>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Stay tuned using twitter @navitia IRC #navitia on freenode https://groups.google.com/d/forum/navitia www.navitia.io */ #include "fill_disruption_from_chaos.h" #include "utils/logger.h" #include "type/datetime.h" #include <boost/make_shared.hpp> #include <boost/variant/static_visitor.hpp> #include <boost/variant/apply_visitor.hpp> #include <boost/range/algorithm/for_each.hpp> #include "boost/date_time/posix_time/posix_time.hpp" namespace navitia { namespace nt = navitia::type; namespace bt = boost::posix_time; static boost::shared_ptr<nt::new_disruption::Tag> make_tag(const chaos::Tag& chaos_tag, nt::new_disruption::DisruptionHolder& holder) { auto from_posix = navitia::from_posix_timestamp; auto& weak_tag = holder.tags[chaos_tag.id()]; if (auto tag = weak_tag.lock()) { return std::move(tag); } auto tag = boost::make_shared<nt::new_disruption::Tag>(); tag->uri = chaos_tag.id(); tag->name = chaos_tag.name(); tag->created_at = from_posix(chaos_tag.created_at()); tag->updated_at = from_posix(chaos_tag.updated_at()); weak_tag = tag; return std::move(tag); } static boost::shared_ptr<nt::new_disruption::Cause> make_cause(const chaos::Cause& chaos_cause, nt::new_disruption::DisruptionHolder& holder) { auto from_posix = navitia::from_posix_timestamp; auto& weak_cause = holder.causes[chaos_cause.id()]; if (auto cause = weak_cause.lock()) { return std::move(cause); } auto cause = boost::make_shared<nt::new_disruption::Cause>(); cause->uri = chaos_cause.id(); cause->wording = chaos_cause.wording(); cause->created_at = from_posix(chaos_cause.created_at()); cause->updated_at = from_posix(chaos_cause.updated_at()); weak_cause = cause; return std::move(cause); } static boost::shared_ptr<nt::new_disruption::Severity> make_severity(const chaos::Severity& chaos_severity, nt::new_disruption::DisruptionHolder& holder) { namespace tr = transit_realtime; namespace new_disr = nt::new_disruption; auto from_posix = navitia::from_posix_timestamp; auto& weak_severity = holder.severities[chaos_severity.id()]; if (auto severity = weak_severity.lock()) { return std::move(severity); } auto severity = boost::make_shared<new_disr::Severity>(); severity->uri = chaos_severity.id(); severity->wording = chaos_severity.wording(); severity->created_at = from_posix(chaos_severity.created_at()); severity->updated_at = from_posix(chaos_severity.updated_at()); severity->color = chaos_severity.color(); severity->priority = chaos_severity.priority(); switch (chaos_severity.effect()) { #define EFFECT_ENUM_CONVERSION(e) \ case tr::Alert_Effect_##e: severity->effect = new_disr::Effect::e; break EFFECT_ENUM_CONVERSION(NO_SERVICE); EFFECT_ENUM_CONVERSION(REDUCED_SERVICE); EFFECT_ENUM_CONVERSION(SIGNIFICANT_DELAYS); EFFECT_ENUM_CONVERSION(DETOUR); EFFECT_ENUM_CONVERSION(ADDITIONAL_SERVICE); EFFECT_ENUM_CONVERSION(MODIFIED_SERVICE); EFFECT_ENUM_CONVERSION(OTHER_EFFECT); EFFECT_ENUM_CONVERSION(UNKNOWN_EFFECT); EFFECT_ENUM_CONVERSION(STOP_MOVED); #undef EFFECT_ENUM_CONVERSION } return std::move(severity); } static boost::optional<nt::new_disruption::LineSection> make_line_section(const chaos::PtObject& chaos_section, nt::PT_Data& pt_data, const boost::shared_ptr<nt::new_disruption::Impact>& impact) { if (!chaos_section.has_pt_line_section()) { LOG4CPLUS_WARN(log4cplus::Logger::getInstance("log"), "fill_disruption_from_chaos: LineSection invalid!"); return boost::none; } const auto& pb_section = chaos_section.pt_line_section(); nt::new_disruption::LineSection line_section; auto* line = find_or_default(pb_section.line().uri(), pt_data.lines_map); if (line) { line_section.line = line; } else { LOG4CPLUS_WARN(log4cplus::Logger::getInstance("log"), "fill_disruption_from_chaos: line id " << pb_section.line().uri() << " in LineSection invalid!"); return boost::none; } if (const auto* start = find_or_default(pb_section.start_point().uri(), pt_data.stop_areas_map)) { line_section.start_point = start; } else { LOG4CPLUS_WARN(log4cplus::Logger::getInstance("log"), "fill_disruption_from_chaos: start_point id " << pb_section.start_point().uri() << " in LineSection invalid!"); return boost::none; } if (const auto* end = find_or_default(pb_section.end_point().uri(), pt_data.stop_areas_map)) { line_section.end_point = end; } else { LOG4CPLUS_WARN(log4cplus::Logger::getInstance("log"), "fill_disruption_from_chaos: end_point id " << pb_section.end_point().uri() << " in LineSection invalid!"); return boost::none; } if (impact) line->add_impact(impact); return line_section; } static std::vector<nt::new_disruption::PtObj> make_pt_objects(const google::protobuf::RepeatedPtrField<chaos::PtObject>& chaos_pt_objects, nt::PT_Data& pt_data, const boost::shared_ptr<nt::new_disruption::Impact>& impact = {}) { using namespace nt::new_disruption; std::vector<PtObj> res; for (const auto& chaos_pt_object: chaos_pt_objects) { switch (chaos_pt_object.pt_object_type()) { case chaos::PtObject_Type_network: res.push_back(make_pt_obj(nt::Type_e::Network, chaos_pt_object.uri(), pt_data, impact)); break; case chaos::PtObject_Type_stop_area: res.push_back(make_pt_obj(nt::Type_e::StopArea, chaos_pt_object.uri(), pt_data, impact)); break; case chaos::PtObject_Type_line_section: if (auto line_section = make_line_section(chaos_pt_object, pt_data, impact)) { res.push_back(*line_section); } break; case chaos::PtObject_Type_line: res.push_back(make_pt_obj(nt::Type_e::Line, chaos_pt_object.uri(), pt_data, impact)); break; case chaos::PtObject_Type_route: res.push_back(make_pt_obj(nt::Type_e::Route, chaos_pt_object.uri(), pt_data, impact)); break; case chaos::PtObject_Type_unkown_type: res.push_back(UnknownPtObj()); break; } // no created_at and updated_at? } return res; } static boost::shared_ptr<nt::new_disruption::Impact> make_impact(const chaos::Impact& chaos_impact, nt::PT_Data& pt_data) { auto from_posix = navitia::from_posix_timestamp; nt::new_disruption::DisruptionHolder& holder = pt_data.disruption_holder; auto impact = boost::make_shared<nt::new_disruption::Impact>(); impact->uri = chaos_impact.id(); impact->created_at = from_posix(chaos_impact.created_at()); impact->updated_at = from_posix(chaos_impact.updated_at()); for (const auto& chaos_ap: chaos_impact.application_periods()) { impact->application_periods.emplace_back(from_posix(chaos_ap.start()), from_posix(chaos_ap.end())); } impact->severity = make_severity(chaos_impact.severity(), holder); impact->informed_entities = make_pt_objects(chaos_impact.informed_entities(), pt_data, impact); for (const auto& chaos_message: chaos_impact.messages()) { const auto& channel = chaos_message.channel(); impact->messages.push_back({ chaos_message.text(), channel.id(), channel.name(), channel.content_type(), from_posix(chaos_message.created_at()), from_posix(chaos_message.updated_at()), }); } return std::move(impact); } struct apply_impact_visitor : public boost::static_visitor<> { boost::shared_ptr<nt::new_disruption::Impact> impact; nt::PT_Data& pt_data; apply_impact_visitor(boost::shared_ptr<nt::new_disruption::Impact> impact, nt::PT_Data& pt_data) : impact(impact), pt_data(pt_data) {} void operator()(nt::new_disruption::UnknownPtObj&) { } void operator()(const nt::Network * network) { for(auto line : network->line_list) { this->operator()(line); } } void operator()(const nt::StopArea * ) { } void operator()(nt::new_disruption::LineSection & ls) { this->operator()(ls.line); } void operator()(const nt::Line *line) { for(auto route : line->route_list) { this->operator()(route); } } void operator()(const nt::Route * route) { auto f = [&](nt::VehicleJourney& vj) { nt::ValidityPattern vp(vj.adapted_validity_pattern); bool is_impacted = false; for (auto period : impact->application_periods) { bt::time_iterator titr(period.begin(), bt::hours(24)); for(;titr<period.end(); ++titr) { auto day = to_int_date(*titr); if (vp.check(day)) { vp.remove(day); is_impacted = true; } } } if (is_impacted) { for (auto vp_ : pt_data.validity_patterns) { if (vp_->days == vp.days) { vj.adapted_validity_pattern = vp_; return true; } } // We haven't found this vp, so we need to create it auto vp_ = new nt::ValidityPattern(vp); pt_data.validity_patterns.push_back(vp_); vj.adapted_validity_pattern = vp_; } return true; }; for (auto journey_pattern : route->journey_pattern_list) { journey_pattern->for_each_vehicle_journey(f); } } }; void apply_impact(boost::shared_ptr<nt::new_disruption::Impact>impact, nt::PT_Data& pt_data) { if (impact->severity->effect == nt::new_disruption::Effect::NO_SERVICE) { apply_impact_visitor v(impact, pt_data); boost::for_each(impact->informed_entities, boost::apply_visitor(v)); } } void delete_disruption(nt::PT_Data& pt_data, const std::string& disruption_id) { nt::new_disruption::DisruptionHolder &holder = pt_data.disruption_holder; auto it = find_if(holder.disruptions.begin(), holder.disruptions.end(), [&disruption_id](const std::unique_ptr<nt::new_disruption::Disruption>& disruption){ return disruption->uri == disruption_id; }); if(it != holder.disruptions.end()){ holder.disruptions.erase(it); //the disruption has ownership over the impacts so all items a deleted in cascade } } void add_disruption(nt::PT_Data& pt_data, const chaos::Disruption& chaos_disruption) { auto from_posix = navitia::from_posix_timestamp; nt::new_disruption::DisruptionHolder &holder = pt_data.disruption_holder; //we delete the disrupion before adding the new one delete_disruption(pt_data, chaos_disruption.id()); auto disruption = std::make_unique<nt::new_disruption::Disruption>(); disruption->uri = chaos_disruption.id(); disruption->reference = chaos_disruption.reference(); disruption->publication_period = { from_posix(chaos_disruption.publication_period().start()), from_posix(chaos_disruption.publication_period().end()) }; disruption->created_at = from_posix(chaos_disruption.created_at()); disruption->updated_at = from_posix(chaos_disruption.updated_at()); disruption->cause = make_cause(chaos_disruption.cause(), holder); for (const auto& chaos_impact: chaos_disruption.impacts()) { auto impact = make_impact(chaos_impact, pt_data); disruption->add_impact(impact); apply_impact(impact, pt_data); } disruption->localization = make_pt_objects(chaos_disruption.localization(), pt_data); for (const auto& chaos_tag: chaos_disruption.tags()) { disruption->tags.push_back(make_tag(chaos_tag, holder)); } disruption->note = chaos_disruption.note(); holder.disruptions.push_back(std::move(disruption)); } } // namespace navitia <|endoftext|>
<commit_before>#include "pescanner.h" #include "fastqreader.h" #include <iostream> #include "htmlreporter.h" #include <unistd.h> #include <functional> #include <thread> #include <memory.h> #include "util.h" PairEndScanner::PairEndScanner(string fusionFile, string refFile, string read1File, string read2File, string html, int threadNum){ mRead1File = read1File; mRead2File = read2File; mFusionFile = fusionFile; mRefFile = refFile; mHtmlFile = html; mProduceFinished = false; mThreadNum = threadNum; mFusionMapper = NULL; } PairEndScanner::~PairEndScanner() { if(mFusionMapper != NULL) { delete mFusionMapper; mFusionMapper = NULL; } } bool PairEndScanner::scan(){ mFusionMapper = new FusionMapper(mRefFile, mFusionFile); initPackRepository(); std::thread producer(std::bind(&PairEndScanner::producerTask, this)); std::thread** threads = new thread*[mThreadNum]; for(int t=0; t<mThreadNum; t++){ threads[t] = new std::thread(std::bind(&PairEndScanner::consumerTask, this)); } producer.join(); for(int t=0; t<mThreadNum; t++){ threads[t]->join(); } for(int t=0; t<mThreadNum; t++){ delete threads[t]; threads[t] = NULL; } mFusionMapper->removeAlignables(); mFusionMapper->sortMatches(); mFusionMapper->clusterMatches(); textReport(mFusionMapper->fusionList, mFusionMapper->fusionMatches); htmlReport(mFusionMapper->fusionList, mFusionMapper->fusionMatches); mFusionMapper->freeMatches(); return true; } void PairEndScanner::pushMatch(Match* m){ std::unique_lock<std::mutex> lock(mFusionMtx); mFusionMapper->addMatch(m); lock.unlock(); } bool PairEndScanner::scanPairEnd(ReadPairPack* pack){ for(int p=0;p<pack->count;p++){ ReadPair* pair = pack->data[p]; Read* r1 = pair->mLeft; Read* r2 = pair->mRight; Read* rcr1 = NULL; Read* rcr2 = NULL; Read* merged = pair->fastMerge(); Read* mergedRC = NULL; if(merged != NULL) mergedRC = merged->reverseComplement(); else { rcr1 = r1->reverseComplement(); rcr2 = r2->reverseComplement(); } // if merged successfully, we only search the merged if(merged != NULL) { Match* matchMerged = mFusionMapper->mapRead(merged); if(matchMerged){ matchMerged->addOriginalPair(pair); pushMatch(matchMerged); } Match* matchMergedRC = mFusionMapper->mapRead(mergedRC); if(matchMergedRC){ matchMergedRC->addOriginalPair(pair); pushMatch(matchMergedRC); } continue; } // else still search R1 and R2 separatedly Match* matchR1 = mFusionMapper->mapRead(r1); if(matchR1){ matchR1->addOriginalPair(pair); pushMatch(matchR1); } Match* matchR2 = mFusionMapper->mapRead(r2); if(matchR2){ matchR2->addOriginalPair(pair); pushMatch(matchR2); } Match* matchRcr1 = mFusionMapper->mapRead(rcr1); if(matchRcr1){ matchRcr1->addOriginalPair(pair); matchRcr1->setReversed(true); pushMatch(matchRcr1); } Match* matchRcr2 = mFusionMapper->mapRead(rcr2); if(matchRcr2){ matchRcr2->addOriginalPair(pair); matchRcr2->setReversed(true); pushMatch(matchRcr2); } delete pair; if(merged!=NULL){ delete merged; delete mergedRC; } else { delete rcr1; delete rcr2; } } delete pack->data; delete pack; return true; } void PairEndScanner::initPackRepository() { mRepo.packBuffer = new ReadPairPack*[PACK_NUM_LIMIT]; memset(mRepo.packBuffer, 0, sizeof(ReadPairPack*)*PACK_NUM_LIMIT); mRepo.writePos = 0; mRepo.readPos = 0; mRepo.readCounter = 0; } void PairEndScanner::destroyPackRepository() { delete mRepo.packBuffer; mRepo.packBuffer = NULL; } void PairEndScanner::producePack(ReadPairPack* pack){ std::unique_lock<std::mutex> lock(mRepo.mtx); while(((mRepo.writePos + 1) % PACK_NUM_LIMIT) == mRepo.readPos) { mRepo.repoNotFull.wait(lock); } mRepo.packBuffer[mRepo.writePos] = pack; mRepo.writePos++; if (mRepo.writePos == PACK_NUM_LIMIT) mRepo.writePos = 0; mRepo.repoNotEmpty.notify_all(); lock.unlock(); } void PairEndScanner::consumePack(){ ReadPairPack* data; std::unique_lock<std::mutex> lock(mRepo.mtx); // read buffer is empty, just wait here. while(mRepo.writePos == mRepo.readPos) { if(mProduceFinished){ lock.unlock(); return; } mRepo.repoNotEmpty.wait(lock); } data = mRepo.packBuffer[mRepo.readPos]; (mRepo.readPos)++; lock.unlock(); scanPairEnd(data); if (mRepo.readPos >= PACK_NUM_LIMIT) mRepo.readPos = 0; mRepo.repoNotFull.notify_all(); } void PairEndScanner::producerTask() { int slept = 0; ReadPair** data = new ReadPair*[PACK_SIZE]; memset(data, 0, sizeof(ReadPair*)*PACK_SIZE); FastqReaderPair reader(mRead1File, mRead2File); int count=0; while(true){ ReadPair* read = reader.read(); if(!read){ // the last pack if(count>0){ ReadPairPack* pack = new ReadPairPack; pack->data = data; pack->count = count; producePack(pack); } data = NULL; break; } data[count] = read; count++; // a full pack if(count == PACK_SIZE){ ReadPairPack* pack = new ReadPairPack; pack->data = data; pack->count = count; producePack(pack); //re-initialize data for next pack data = new ReadPair*[PACK_SIZE]; memset(data, 0, sizeof(ReadPair*)*PACK_SIZE); // reset count to 0 count = 0; // if the consumer is far behind this producer, sleep and wait to limit memory usage while(mRepo.writePos - mRepo.readPos > PACK_IN_MEM_LIMIT){ //cout<<"sleep"<<endl; slept++; usleep(1000); } } } std::unique_lock<std::mutex> lock(mRepo.readCounterMtx); mProduceFinished = true; lock.unlock(); // if the last data initialized is not used, free it if(data != NULL) delete data; } void PairEndScanner::consumerTask() { while(true) { std::unique_lock<std::mutex> lock(mRepo.readCounterMtx); if(mProduceFinished && mRepo.writePos == mRepo.readPos){ lock.unlock(); break; } if(mProduceFinished){ consumePack(); lock.unlock(); } else { lock.unlock(); consumePack(); } } } void PairEndScanner::textReport(vector<Fusion>& fusionList, vector<Match*> *fusionMatches) { } void PairEndScanner::htmlReport(vector<Fusion>& fusionList, vector<Match*> *fusionMatches) { if(mHtmlFile == "") return; HtmlReporter reporter(mHtmlFile, fusionList, fusionMatches); reporter.run(); } <commit_msg>fixed a memory leak issue caused by inproper use of continue in pescanner<commit_after>#include "pescanner.h" #include "fastqreader.h" #include <iostream> #include "htmlreporter.h" #include <unistd.h> #include <functional> #include <thread> #include <memory.h> #include "util.h" PairEndScanner::PairEndScanner(string fusionFile, string refFile, string read1File, string read2File, string html, int threadNum){ mRead1File = read1File; mRead2File = read2File; mFusionFile = fusionFile; mRefFile = refFile; mHtmlFile = html; mProduceFinished = false; mThreadNum = threadNum; mFusionMapper = NULL; } PairEndScanner::~PairEndScanner() { if(mFusionMapper != NULL) { delete mFusionMapper; mFusionMapper = NULL; } } bool PairEndScanner::scan(){ mFusionMapper = new FusionMapper(mRefFile, mFusionFile); initPackRepository(); std::thread producer(std::bind(&PairEndScanner::producerTask, this)); std::thread** threads = new thread*[mThreadNum]; for(int t=0; t<mThreadNum; t++){ threads[t] = new std::thread(std::bind(&PairEndScanner::consumerTask, this)); } producer.join(); for(int t=0; t<mThreadNum; t++){ threads[t]->join(); } for(int t=0; t<mThreadNum; t++){ delete threads[t]; threads[t] = NULL; } mFusionMapper->removeAlignables(); mFusionMapper->sortMatches(); mFusionMapper->clusterMatches(); textReport(mFusionMapper->fusionList, mFusionMapper->fusionMatches); htmlReport(mFusionMapper->fusionList, mFusionMapper->fusionMatches); mFusionMapper->freeMatches(); return true; } void PairEndScanner::pushMatch(Match* m){ std::unique_lock<std::mutex> lock(mFusionMtx); mFusionMapper->addMatch(m); lock.unlock(); } bool PairEndScanner::scanPairEnd(ReadPairPack* pack){ for(int p=0;p<pack->count;p++){ ReadPair* pair = pack->data[p]; Read* r1 = pair->mLeft; Read* r2 = pair->mRight; Read* rcr1 = NULL; Read* rcr2 = NULL; Read* merged = pair->fastMerge(); Read* mergedRC = NULL; if(merged != NULL) mergedRC = merged->reverseComplement(); else { rcr1 = r1->reverseComplement(); rcr2 = r2->reverseComplement(); } // if merged successfully, we only search the merged if(merged != NULL) { Match* matchMerged = mFusionMapper->mapRead(merged); if(matchMerged){ matchMerged->addOriginalPair(pair); pushMatch(matchMerged); } Match* matchMergedRC = mFusionMapper->mapRead(mergedRC); if(matchMergedRC){ matchMergedRC->addOriginalPair(pair); pushMatch(matchMergedRC); } delete pair; delete merged; delete mergedRC; continue; } // else still search R1 and R2 separatedly Match* matchR1 = mFusionMapper->mapRead(r1); if(matchR1){ matchR1->addOriginalPair(pair); pushMatch(matchR1); } Match* matchR2 = mFusionMapper->mapRead(r2); if(matchR2){ matchR2->addOriginalPair(pair); pushMatch(matchR2); } Match* matchRcr1 = mFusionMapper->mapRead(rcr1); if(matchRcr1){ matchRcr1->addOriginalPair(pair); matchRcr1->setReversed(true); pushMatch(matchRcr1); } Match* matchRcr2 = mFusionMapper->mapRead(rcr2); if(matchRcr2){ matchRcr2->addOriginalPair(pair); matchRcr2->setReversed(true); pushMatch(matchRcr2); } delete pair; delete rcr1; delete rcr2; } delete pack->data; delete pack; return true; } void PairEndScanner::initPackRepository() { mRepo.packBuffer = new ReadPairPack*[PACK_NUM_LIMIT]; memset(mRepo.packBuffer, 0, sizeof(ReadPairPack*)*PACK_NUM_LIMIT); mRepo.writePos = 0; mRepo.readPos = 0; mRepo.readCounter = 0; } void PairEndScanner::destroyPackRepository() { delete mRepo.packBuffer; mRepo.packBuffer = NULL; } void PairEndScanner::producePack(ReadPairPack* pack){ std::unique_lock<std::mutex> lock(mRepo.mtx); while(((mRepo.writePos + 1) % PACK_NUM_LIMIT) == mRepo.readPos) { mRepo.repoNotFull.wait(lock); } mRepo.packBuffer[mRepo.writePos] = pack; mRepo.writePos++; if (mRepo.writePos == PACK_NUM_LIMIT) mRepo.writePos = 0; mRepo.repoNotEmpty.notify_all(); lock.unlock(); } void PairEndScanner::consumePack(){ ReadPairPack* data; std::unique_lock<std::mutex> lock(mRepo.mtx); // read buffer is empty, just wait here. while(mRepo.writePos == mRepo.readPos) { if(mProduceFinished){ lock.unlock(); return; } mRepo.repoNotEmpty.wait(lock); } data = mRepo.packBuffer[mRepo.readPos]; (mRepo.readPos)++; lock.unlock(); scanPairEnd(data); if (mRepo.readPos >= PACK_NUM_LIMIT) mRepo.readPos = 0; mRepo.repoNotFull.notify_all(); } void PairEndScanner::producerTask() { int slept = 0; ReadPair** data = new ReadPair*[PACK_SIZE]; memset(data, 0, sizeof(ReadPair*)*PACK_SIZE); FastqReaderPair reader(mRead1File, mRead2File); int count=0; while(true){ ReadPair* read = reader.read(); if(!read){ // the last pack if(count>0){ ReadPairPack* pack = new ReadPairPack; pack->data = data; pack->count = count; producePack(pack); } data = NULL; break; } data[count] = read; count++; // a full pack if(count == PACK_SIZE){ ReadPairPack* pack = new ReadPairPack; pack->data = data; pack->count = count; producePack(pack); //re-initialize data for next pack data = new ReadPair*[PACK_SIZE]; memset(data, 0, sizeof(ReadPair*)*PACK_SIZE); // reset count to 0 count = 0; // if the consumer is far behind this producer, sleep and wait to limit memory usage while(mRepo.writePos - mRepo.readPos > PACK_IN_MEM_LIMIT){ //cout<<"sleep"<<endl; slept++; usleep(1000); } } } std::unique_lock<std::mutex> lock(mRepo.readCounterMtx); mProduceFinished = true; lock.unlock(); // if the last data initialized is not used, free it if(data != NULL) delete data; } void PairEndScanner::consumerTask() { while(true) { std::unique_lock<std::mutex> lock(mRepo.readCounterMtx); if(mProduceFinished && mRepo.writePos == mRepo.readPos){ lock.unlock(); break; } if(mProduceFinished){ consumePack(); lock.unlock(); } else { lock.unlock(); consumePack(); } } } void PairEndScanner::textReport(vector<Fusion>& fusionList, vector<Match*> *fusionMatches) { } void PairEndScanner::htmlReport(vector<Fusion>& fusionList, vector<Match*> *fusionMatches) { if(mHtmlFile == "") return; HtmlReporter reporter(mHtmlFile, fusionList, fusionMatches); reporter.run(); } <|endoftext|>
<commit_before>// // PROJECT: Aspia Remote Desktop // FILE: base/file_enumerator.cc // LICENSE: See top-level directory // PROGRAMMERS: Dmitry Chapyshev (dmitry@aspia.ru) // #include "base/file_enumerator.h" #include "base/version_helpers.h" #include "base/logging.h" namespace aspia { FileEnumerator::FileEnumerator(const std::wstring& root_path, bool recursive, int file_type) : recursive_(recursive), file_type_(file_type) { // INCLUDE_DOT_DOT must not be specified if recursive. DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_))); memset(&find_data_, 0, sizeof(find_data_)); pending_paths_.push(root_path); } FileEnumerator::FileEnumerator(const std::wstring& root_path, bool recursive, int file_type, const std::wstring& pattern) : recursive_(recursive), file_type_(file_type), pattern_(pattern) { // INCLUDE_DOT_DOT must not be specified if recursive. DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_))); memset(&find_data_, 0, sizeof(find_data_)); pending_paths_.push(root_path); } FileEnumerator::~FileEnumerator() { if (find_handle_ != INVALID_HANDLE_VALUE) FindClose(find_handle_); } bool FileEnumerator::ShouldSkip(const std::wstring& path) { return path == L"." || (path == L".." && !(INCLUDE_DOT_DOT & file_type_)); } std::wstring FileEnumerator::Next() { while (has_find_data_ || !pending_paths_.empty()) { if (!has_find_data_) { // The last find FindFirstFile operation is done, prepare a new one. root_path_ = pending_paths_.top(); pending_paths_.pop(); // Start a new find operation. std::wstring src = root_path_; if (pattern_.empty()) src = src.append(L"*"); // No pattern = match everything. else src = src.append(pattern_); if (IsWindows7OrGreater()) { // Use a "large fetch" on newer Windows which should speed up large // enumerations (we seldom abort in the middle). find_handle_ = FindFirstFileExW(src.c_str(), FindExInfoBasic, // Omit short name. &find_data_, FindExSearchNameMatch, nullptr, FIND_FIRST_EX_LARGE_FETCH); } else { find_handle_ = FindFirstFileW(src.c_str(), &find_data_); } has_find_data_ = true; } else { // Search for the next file/directory. if (!FindNextFileW(find_handle_, &find_data_)) { FindClose(find_handle_); find_handle_ = INVALID_HANDLE_VALUE; } } if (INVALID_HANDLE_VALUE == find_handle_) { has_find_data_ = false; // This is reached when we have finished a directory and are advancing to // the next one in the queue. We applied the pattern (if any) to the files // in the root search directory, but for those directories which were // matched, we want to enumerate all files inside them. This will happen // when the handle is empty. pattern_.clear(); continue; } std::wstring cur_file(find_data_.cFileName); if (ShouldSkip(cur_file)) continue; // Construct the absolute filename. cur_file = root_path_.append(find_data_.cFileName); if (find_data_.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (recursive_) { // If |cur_file| is a directory, and we are doing recursive searching, // add it to pending_paths_ so we scan it after we finish scanning this // directory. However, don't do recursion through reparse points or we // may end up with an infinite cycle. DWORD attributes = GetFileAttributesW(cur_file.c_str()); if (!(attributes & FILE_ATTRIBUTE_REPARSE_POINT)) pending_paths_.push(cur_file); } if (file_type_ & FileEnumerator::DIRECTORIES) return cur_file; } else if (file_type_ & FileEnumerator::FILES) { return cur_file; } } return std::wstring(); } FileEnumerator::FileInfo FileEnumerator::GetInfo() const { if (!has_find_data_) return FileInfo(); FileInfo ret; memcpy(&ret.find_data_, &find_data_, sizeof(find_data_)); return ret; } FileEnumerator::FileInfo::FileInfo() { memset(&find_data_, 0, sizeof(find_data_)); } bool FileEnumerator::FileInfo::IsDirectory() const { return (find_data_.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0; } std::wstring FileEnumerator::FileInfo::GetName() const { return find_data_.cFileName; } int64_t FileEnumerator::FileInfo::GetSize() const { ULARGE_INTEGER size; size.HighPart = find_data_.nFileSizeHigh; size.LowPart = find_data_.nFileSizeLow; DCHECK_LE(size.QuadPart, static_cast<ULONGLONG>(std::numeric_limits<int64_t>::max())); return static_cast<int64_t>(size.QuadPart); } } // namespace aspia <commit_msg>- Fix bugs in FileEnumerator<commit_after>// // PROJECT: Aspia Remote Desktop // FILE: base/file_enumerator.cc // LICENSE: See top-level directory // PROGRAMMERS: Dmitry Chapyshev (dmitry@aspia.ru) // #include "base/file_enumerator.h" #include "base/version_helpers.h" #include "base/logging.h" namespace aspia { FileEnumerator::FileEnumerator(const std::wstring& root_path, bool recursive, int file_type) : recursive_(recursive), file_type_(file_type) { // INCLUDE_DOT_DOT must not be specified if recursive. DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_))); memset(&find_data_, 0, sizeof(find_data_)); pending_paths_.push(root_path); } FileEnumerator::FileEnumerator(const std::wstring& root_path, bool recursive, int file_type, const std::wstring& pattern) : recursive_(recursive), file_type_(file_type), pattern_(pattern) { // INCLUDE_DOT_DOT must not be specified if recursive. DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_))); memset(&find_data_, 0, sizeof(find_data_)); pending_paths_.push(root_path); } FileEnumerator::~FileEnumerator() { if (find_handle_ != INVALID_HANDLE_VALUE) FindClose(find_handle_); } bool FileEnumerator::ShouldSkip(const std::wstring& path) { return path == L"." || (path == L".." && !(INCLUDE_DOT_DOT & file_type_)); } std::wstring FileEnumerator::Next() { while (has_find_data_ || !pending_paths_.empty()) { if (!has_find_data_) { // The last find FindFirstFile operation is done, prepare a new one. root_path_ = pending_paths_.top(); pending_paths_.pop(); // Start a new find operation. std::wstring src = root_path_; if (pattern_.empty()) { src.append(L"\\*"); // No pattern = match everything. } else { src.append(L"\\"); src.append(pattern_); } if (IsWindows7OrGreater()) { // Use a "large fetch" on newer Windows which should speed up large // enumerations (we seldom abort in the middle). find_handle_ = FindFirstFileExW(src.c_str(), FindExInfoBasic, // Omit short name. &find_data_, FindExSearchNameMatch, nullptr, FIND_FIRST_EX_LARGE_FETCH); } else { find_handle_ = FindFirstFileW(src.c_str(), &find_data_); } has_find_data_ = true; } else { // Search for the next file/directory. if (!FindNextFileW(find_handle_, &find_data_)) { FindClose(find_handle_); find_handle_ = INVALID_HANDLE_VALUE; } } if (INVALID_HANDLE_VALUE == find_handle_) { has_find_data_ = false; // This is reached when we have finished a directory and are advancing to // the next one in the queue. We applied the pattern (if any) to the files // in the root search directory, but for those directories which were // matched, we want to enumerate all files inside them. This will happen // when the handle is empty. pattern_.clear(); continue; } std::wstring cur_file(find_data_.cFileName); if (ShouldSkip(cur_file)) continue; // Construct the absolute filename. cur_file = root_path_; cur_file.append(L"\\"); cur_file.append(find_data_.cFileName); if (find_data_.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (recursive_) { // If |cur_file| is a directory, and we are doing recursive searching, // add it to pending_paths_ so we scan it after we finish scanning this // directory. However, don't do recursion through reparse points or we // may end up with an infinite cycle. DWORD attributes = GetFileAttributesW(cur_file.c_str()); if (!(attributes & FILE_ATTRIBUTE_REPARSE_POINT)) pending_paths_.push(cur_file); } if (file_type_ & FileEnumerator::DIRECTORIES) return cur_file; } else if (file_type_ & FileEnumerator::FILES) { return cur_file; } } return std::wstring(); } FileEnumerator::FileInfo FileEnumerator::GetInfo() const { if (!has_find_data_) return FileInfo(); FileInfo ret; memcpy(&ret.find_data_, &find_data_, sizeof(find_data_)); return ret; } FileEnumerator::FileInfo::FileInfo() { memset(&find_data_, 0, sizeof(find_data_)); } bool FileEnumerator::FileInfo::IsDirectory() const { return (find_data_.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0; } std::wstring FileEnumerator::FileInfo::GetName() const { return find_data_.cFileName; } int64_t FileEnumerator::FileInfo::GetSize() const { ULARGE_INTEGER size; size.HighPart = find_data_.nFileSizeHigh; size.LowPart = find_data_.nFileSizeLow; DCHECK_LE(size.QuadPart, static_cast<ULONGLONG>(std::numeric_limits<int64_t>::max())); return static_cast<int64_t>(size.QuadPart); } } // namespace aspia <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of QMime ** ** Based on Qt Creator source code ** ** Qt Creator Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** **************************************************************************/ #include "qmimetype.h" #include "qmimetype_p.h" #include <QtCore/QLocale> #include "qmimedatabase.h" #include "magicmatcher_p.h" QT_BEGIN_NAMESPACE /*! \class QMimeGlobPattern \brief Glob pattern for file names for MIME type matching. \sa QMimeType, QMimeDatabase, QMimeMagicRuleMatcher, QMimeMagicRule \sa BinaryMatcher, HeuristicTextMagicMatcher \sa BaseMimeTypeParser, MimeTypeParser */ /*! \var QMimeTypeData::suffixPattern \brief Regular expression to match a suffix glob pattern: "*.ext" (and not sth like "Makefile" or "*.log[1-9]" */ QMimeTypeData::QMimeTypeData() : suffixPattern(QLatin1String("^\\*\\.[\\w+]+$")) { if (!suffixPattern.isValid()) qWarning("MimeTypeData(): invalid suffixPattern"); } void QMimeTypeData::clear() { type.clear(); comment.clear(); aliases.clear(); globPatterns.clear(); subClassOf.clear(); preferredSuffix.clear(); suffixes.clear(); magicMatchers.clear(); } void QMimeTypeData::assignSuffix(const QString &pattern) { if (suffixPattern.exactMatch(pattern)) { const QString suffix = pattern.right(pattern.size() - 2); suffixes.append(suffix); if (preferredSuffix.isEmpty()) preferredSuffix = suffix; } } void QMimeTypeData::assignSuffixes(const QStringList &patterns) { foreach (const QString &pattern, patterns) assignSuffix(pattern); } unsigned QMimeTypeData::matchesFileBySuffix(const QString &name) const { foreach (const QMimeGlobPattern &glob, globPatterns) { if (glob.regExp().exactMatch(name)) return glob.weight(); } return 0; } QList<QMimeGlobPattern> QMimeTypeData::toGlobPatterns(const QStringList &patterns, int weight) { QList<QMimeGlobPattern> globPatterns; foreach (const QString &pattern, patterns) { const QRegExp wildcard(pattern, Qt::CaseSensitive, QRegExp::WildcardUnix); globPatterns.append(QMimeGlobPattern(wildcard, weight)); } return globPatterns; } QStringList QMimeTypeData::fromGlobPatterns(const QList<QMimeGlobPattern> &globPatterns) { QStringList patterns; foreach (const QMimeGlobPattern &globPattern, globPatterns) patterns.append(globPattern.regExp().pattern()); return patterns; } static inline bool isTextFile(const QByteArray &data) { // UTF16 byte order marks static const char bigEndianBOM[] = "\xFE\xFF"; static const char littleEndianBOM[] = "\xFF\xFE"; const char *p = data.constData(); const char *e = p + data.size(); for ( ; p < e; ++p) { if (*p >= 0x01 && *p < 0x09) // Sure-fire binary return false; if (*p == 0) // Check for UTF16 return data.startsWith(bigEndianBOM) || data.startsWith(littleEndianBOM); } return true; } unsigned QMimeTypeData::matchesData(const QByteArray &data) const { unsigned priority = 0; if (!data.isEmpty()) { // TODO: discuss - this code is slow :( // Hack for text/plain and application/octet-stream if (magicMatchers.isEmpty()) { if (type == QLatin1String("text/plain") && isTextFile(data)) priority = 2; else if (type == QLatin1String("application/octet-stream")) priority = 1; } else { foreach (const QMimeMagicRuleMatcher &matcher, magicMatchers) { if (matcher.priority() > priority && matcher.matches(data)) priority = matcher.priority(); } } } return priority; } /*! \class QMimeType \brief MIME type data used in Qt Creator. Contains most information from standard MIME type XML database files. In addition, the class provides a list of suffixes and a concept of the 'preferred suffix' (derived from glob patterns). This is used for example to be able to configure the suffix used for C++-files in Qt Creator. MIME XML looks like: \code <?xml version="1.0" encoding="UTF-8"?> <mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info"> <!-- MIME types must match the desktop file associations --> <mime-type type="application/vnd.nokia.qt.qmakeprofile"> <comment xml:lang="en">Qt qmake Profile</comment> <glob pattern="*.pro" weight="50"/> </mime-type> </mime-info> \endcode \sa QMimeDatabase, QMimeMagicRuleMatcher, QMimeMagicRule, QMimeGlobPattern */ QMimeType::QMimeType() : d(new QMimeTypeData) { } QMimeType::QMimeType(const QMimeType &other) : d(other.d) { } QMimeType::QMimeType(const QMimeTypeData &dd) : d(new QMimeTypeData(dd)) { } QMimeType::~QMimeType() { } QMimeType &QMimeType::operator=(const QMimeType &other) { if (d != other.d) d = other.d; return *this; } bool QMimeType::operator==(const QMimeType &other) const { return d == other.d; } void QMimeType::clear() { d->clear(); } bool QMimeType::isValid() const { return !d->type.isEmpty(); } QString QMimeType::type() const { return d->type; } QString QMimeType::comment() const { return d->comment; } // Return "en", "de", etc. derived from "en_US", de_DE". static inline QString systemLanguage() { QString name = QLocale::system().name(); const int underScorePos = name.indexOf(QLatin1Char('_')); if (underScorePos != -1) name.truncate(underScorePos); return name; } /*! \param localeArg en, de... */ QString QMimeType::localeComment(const QString &localeArg) const { const QString locale = localeArg.isEmpty() ? systemLanguage() : localeArg; return d->localeComments.value(locale, d->comment); } QStringList QMimeType::aliases() const { return d->aliases; } QString QMimeType::genericIconName() const { return d->genericIconName; } QList<QMimeGlobPattern> QMimeType::weightedGlobPatterns() const { return d->globPatterns; } QStringList QMimeType::globPatterns() const { return QMimeTypeData::fromGlobPatterns(d->globPatterns); } QList<QMimeMagicRuleMatcher> QMimeType::magicMatchers() const { return d->magicMatchers; } QStringList QMimeType::subClassOf() const { return d->subClassOf; } /*! Returns the known suffixes for the MIME type. Extension over standard MIME data */ QStringList QMimeType::suffixes() const { return d->suffixes; } /*! Returns the preferred suffix for the MIME type. Extension over standard MIME data */ QString QMimeType::preferredSuffix() const { return d->preferredSuffix; } /*! Checks for \a type or one of the aliases. */ bool QMimeType::matchesType(const QString &type) const { return d->type == type || d->aliases.contains(type); } unsigned QMimeType::matchesData(const QByteArray &data) const { return d->matchesData(data); } /*! Checks the glob pattern weights and magic priorities so the highest value is returned. A 0 (zero) indicates no match. */ unsigned QMimeType::matchesFile(const QFileInfo &file) const { FileMatchContext context(file); const unsigned suffixPriority = d->matchesFileBySuffix(context.fileName()); if (suffixPriority >= QMimeGlobPattern::MaxWeight) return QMimeGlobPattern::MaxWeight; return qMax(suffixPriority, d->matchesData(context.data())); } /*! Performs search by glob patterns. */ unsigned QMimeType::matchesName(const QString &name) const { return d->matchesFileBySuffix(name); } /*! Returns a filter string usable for a file dialog. */ QString QMimeType::filterString() const { QString filter; if (!d->globPatterns.empty()) { // !Binary files // ### todo: Use localeComment() once creator is shipped with translations filter += d->comment + QLatin1String(" ("); for (int i = 0; i < d->globPatterns.size(); ++i) { if (i != 0) filter += QLatin1Char(' '); filter += d->globPatterns.at(i).regExp().pattern(); } filter += QLatin1Char(')'); } return filter; } void QMimeTypeData::setType(const QString &type) { QMimeTypeData *d = this; d->type = type; } void QMimeTypeData::setWeightedGlobPatterns(const QList<QMimeGlobPattern> &globPatterns) { QMimeTypeData *d = this; d->globPatterns = globPatterns; QString oldPrefferedSuffix = d->preferredSuffix; d->suffixes.clear(); d->preferredSuffix.clear(); d->assignSuffixes(QMimeTypeData::fromGlobPatterns(globPatterns)); if (d->preferredSuffix != oldPrefferedSuffix && d->suffixes.contains(oldPrefferedSuffix)) d->preferredSuffix = oldPrefferedSuffix; } void QMimeTypeData::setMagicMatchers(const QList<QMimeMagicRuleMatcher> &matchers) { QMimeTypeData *d = this; d->magicMatchers = matchers; } QT_END_NAMESPACE <commit_msg>Removed unnecessary dependecy.<commit_after>/************************************************************************** ** ** This file is part of QMime ** ** Based on Qt Creator source code ** ** Qt Creator Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** **************************************************************************/ #include "qmimetype.h" #include "qmimetype_p.h" #include <QtCore/QLocale> #include "magicmatcher_p.h" QT_BEGIN_NAMESPACE /*! \class QMimeGlobPattern \brief Glob pattern for file names for MIME type matching. \sa QMimeType, QMimeDatabase, QMimeMagicRuleMatcher, QMimeMagicRule \sa BinaryMatcher, HeuristicTextMagicMatcher \sa BaseMimeTypeParser, MimeTypeParser */ /*! \var QMimeTypeData::suffixPattern \brief Regular expression to match a suffix glob pattern: "*.ext" (and not sth like "Makefile" or "*.log[1-9]" */ QMimeTypeData::QMimeTypeData() : suffixPattern(QLatin1String("^\\*\\.[\\w+]+$")) { if (!suffixPattern.isValid()) qWarning("MimeTypeData(): invalid suffixPattern"); } void QMimeTypeData::clear() { type.clear(); comment.clear(); aliases.clear(); globPatterns.clear(); subClassOf.clear(); preferredSuffix.clear(); suffixes.clear(); magicMatchers.clear(); } void QMimeTypeData::assignSuffix(const QString &pattern) { if (suffixPattern.exactMatch(pattern)) { const QString suffix = pattern.right(pattern.size() - 2); suffixes.append(suffix); if (preferredSuffix.isEmpty()) preferredSuffix = suffix; } } void QMimeTypeData::assignSuffixes(const QStringList &patterns) { foreach (const QString &pattern, patterns) assignSuffix(pattern); } unsigned QMimeTypeData::matchesFileBySuffix(const QString &name) const { foreach (const QMimeGlobPattern &glob, globPatterns) { if (glob.regExp().exactMatch(name)) return glob.weight(); } return 0; } QList<QMimeGlobPattern> QMimeTypeData::toGlobPatterns(const QStringList &patterns, int weight) { QList<QMimeGlobPattern> globPatterns; foreach (const QString &pattern, patterns) { const QRegExp wildcard(pattern, Qt::CaseSensitive, QRegExp::WildcardUnix); globPatterns.append(QMimeGlobPattern(wildcard, weight)); } return globPatterns; } QStringList QMimeTypeData::fromGlobPatterns(const QList<QMimeGlobPattern> &globPatterns) { QStringList patterns; foreach (const QMimeGlobPattern &globPattern, globPatterns) patterns.append(globPattern.regExp().pattern()); return patterns; } static inline bool isTextFile(const QByteArray &data) { // UTF16 byte order marks static const char bigEndianBOM[] = "\xFE\xFF"; static const char littleEndianBOM[] = "\xFF\xFE"; const char *p = data.constData(); const char *e = p + data.size(); for ( ; p < e; ++p) { if (*p >= 0x01 && *p < 0x09) // Sure-fire binary return false; if (*p == 0) // Check for UTF16 return data.startsWith(bigEndianBOM) || data.startsWith(littleEndianBOM); } return true; } unsigned QMimeTypeData::matchesData(const QByteArray &data) const { unsigned priority = 0; if (!data.isEmpty()) { // TODO: discuss - this code is slow :( // Hack for text/plain and application/octet-stream if (magicMatchers.isEmpty()) { if (type == QLatin1String("text/plain") && isTextFile(data)) priority = 2; else if (type == QLatin1String("application/octet-stream")) priority = 1; } else { foreach (const QMimeMagicRuleMatcher &matcher, magicMatchers) { if (matcher.priority() > priority && matcher.matches(data)) priority = matcher.priority(); } } } return priority; } /*! \class QMimeType \brief MIME type data used in Qt Creator. Contains most information from standard MIME type XML database files. In addition, the class provides a list of suffixes and a concept of the 'preferred suffix' (derived from glob patterns). This is used for example to be able to configure the suffix used for C++-files in Qt Creator. MIME XML looks like: \code <?xml version="1.0" encoding="UTF-8"?> <mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info"> <!-- MIME types must match the desktop file associations --> <mime-type type="application/vnd.nokia.qt.qmakeprofile"> <comment xml:lang="en">Qt qmake Profile</comment> <glob pattern="*.pro" weight="50"/> </mime-type> </mime-info> \endcode \sa QMimeDatabase, QMimeMagicRuleMatcher, QMimeMagicRule, QMimeGlobPattern */ QMimeType::QMimeType() : d(new QMimeTypeData) { } QMimeType::QMimeType(const QMimeType &other) : d(other.d) { } QMimeType::QMimeType(const QMimeTypeData &dd) : d(new QMimeTypeData(dd)) { } QMimeType::~QMimeType() { } QMimeType &QMimeType::operator=(const QMimeType &other) { if (d != other.d) d = other.d; return *this; } bool QMimeType::operator==(const QMimeType &other) const { return d == other.d; } void QMimeType::clear() { d->clear(); } bool QMimeType::isValid() const { return !d->type.isEmpty(); } QString QMimeType::type() const { return d->type; } QString QMimeType::comment() const { return d->comment; } // Return "en", "de", etc. derived from "en_US", de_DE". static inline QString systemLanguage() { QString name = QLocale::system().name(); const int underScorePos = name.indexOf(QLatin1Char('_')); if (underScorePos != -1) name.truncate(underScorePos); return name; } /*! \param localeArg en, de... */ QString QMimeType::localeComment(const QString &localeArg) const { const QString locale = localeArg.isEmpty() ? systemLanguage() : localeArg; return d->localeComments.value(locale, d->comment); } QStringList QMimeType::aliases() const { return d->aliases; } QString QMimeType::genericIconName() const { return d->genericIconName; } QList<QMimeGlobPattern> QMimeType::weightedGlobPatterns() const { return d->globPatterns; } QStringList QMimeType::globPatterns() const { return QMimeTypeData::fromGlobPatterns(d->globPatterns); } QList<QMimeMagicRuleMatcher> QMimeType::magicMatchers() const { return d->magicMatchers; } QStringList QMimeType::subClassOf() const { return d->subClassOf; } /*! Returns the known suffixes for the MIME type. Extension over standard MIME data */ QStringList QMimeType::suffixes() const { return d->suffixes; } /*! Returns the preferred suffix for the MIME type. Extension over standard MIME data */ QString QMimeType::preferredSuffix() const { return d->preferredSuffix; } /*! Checks for \a type or one of the aliases. */ bool QMimeType::matchesType(const QString &type) const { return d->type == type || d->aliases.contains(type); } unsigned QMimeType::matchesData(const QByteArray &data) const { return d->matchesData(data); } /*! Checks the glob pattern weights and magic priorities so the highest value is returned. A 0 (zero) indicates no match. */ unsigned QMimeType::matchesFile(const QFileInfo &file) const { FileMatchContext context(file); const unsigned suffixPriority = d->matchesFileBySuffix(context.fileName()); if (suffixPriority >= QMimeGlobPattern::MaxWeight) return QMimeGlobPattern::MaxWeight; return qMax(suffixPriority, d->matchesData(context.data())); } /*! Performs search by glob patterns. */ unsigned QMimeType::matchesName(const QString &name) const { return d->matchesFileBySuffix(name); } /*! Returns a filter string usable for a file dialog. */ QString QMimeType::filterString() const { QString filter; if (!d->globPatterns.empty()) { // !Binary files // ### todo: Use localeComment() once creator is shipped with translations filter += d->comment + QLatin1String(" ("); for (int i = 0; i < d->globPatterns.size(); ++i) { if (i != 0) filter += QLatin1Char(' '); filter += d->globPatterns.at(i).regExp().pattern(); } filter += QLatin1Char(')'); } return filter; } void QMimeTypeData::setType(const QString &type) { QMimeTypeData *d = this; d->type = type; } void QMimeTypeData::setWeightedGlobPatterns(const QList<QMimeGlobPattern> &globPatterns) { QMimeTypeData *d = this; d->globPatterns = globPatterns; QString oldPrefferedSuffix = d->preferredSuffix; d->suffixes.clear(); d->preferredSuffix.clear(); d->assignSuffixes(QMimeTypeData::fromGlobPatterns(globPatterns)); if (d->preferredSuffix != oldPrefferedSuffix && d->suffixes.contains(oldPrefferedSuffix)) d->preferredSuffix = oldPrefferedSuffix; } void QMimeTypeData::setMagicMatchers(const QList<QMimeMagicRuleMatcher> &matchers) { QMimeTypeData *d = this; d->magicMatchers = matchers; } QT_END_NAMESPACE <|endoftext|>
<commit_before>// @(#)root/base:$Name: $:$Id: TVirtualPS.cxx,v 1.12 2005/09/02 07:51:51 brun Exp $ // Author: Rene Brun 05/09/99 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TVirtualPS is an abstract interface to a Postscript and SVG drivers // // // ////////////////////////////////////////////////////////////////////////// #include "Riostream.h" #include "TVirtualPS.h" TVirtualPS *gVirtualPS = 0; const Int_t kMaxBuffer = 250; ClassImp(TVirtualPS) //______________________________________________________________________________ // // TVirtualPS is an abstract interface to a Postscript driver // //______________________________________________________________________________ TVirtualPS::TVirtualPS() { // VirtualPS default constructor fStream = 0; fNByte = 0; fSizBuffer = kMaxBuffer; fBuffer = new char[fSizBuffer+1]; } //______________________________________________________________________________ TVirtualPS::TVirtualPS(const char *name, Int_t) : TNamed(name,"Postscript interface") { // VirtualPS constructor fStream = 0; fNByte = 0; fSizBuffer = kMaxBuffer; fBuffer = new char[fSizBuffer+1]; } //______________________________________________________________________________ TVirtualPS::~TVirtualPS() { // VirtualPS destructor if (fBuffer) delete [] fBuffer; } //______________________________________________________________________________ void TVirtualPS::PrintStr(const char *str) { // Output the string str in the output buffer Int_t len = strlen(str); if (len == 0) return; if( str[0] == '@') { if( fLenBuffer ) { fStream->write(fBuffer, fLenBuffer); fStream->write("\n",1); fNByte++; } if ( len < 2) { fBuffer[0] = ' '; } else { strcpy(fBuffer, str+1); } fLenBuffer = len-1; fPrinted = kTRUE; fNByte += len-1; return; } if( str[len-1] == '@') { if( fLenBuffer ) { fStream->write(fBuffer, fLenBuffer); fStream->write("\n",1); fNByte++; } fStream->write(str, len-1); fStream->write("\n",1); fLenBuffer = 0; fNByte += len; fPrinted = kTRUE; return; } if( (len + fLenBuffer ) > kMaxBuffer-1) { fStream->write(fBuffer, fLenBuffer); fStream->write("\n",1); fNByte++; strcpy(fBuffer, str); fLenBuffer = len; fNByte += len; } else { strcpy(fBuffer + fLenBuffer, str); fLenBuffer += len; fNByte += len; } fPrinted = kTRUE; } //______________________________________________________________________________ void TVirtualPS::PrintFast(Int_t len, const char *str) { // Fast version of Print fNByte += len; if( (len + fLenBuffer ) > kMaxBuffer-1) { fStream->write(fBuffer, fLenBuffer); fStream->write("\n",1); fNByte++; while (len > kMaxBuffer) { fStream->write(str,kMaxBuffer); len -= kMaxBuffer; str += kMaxBuffer; } strcpy(fBuffer, str); fLenBuffer = len; } else { strcpy(fBuffer + fLenBuffer, str); fLenBuffer += len; } fPrinted = kTRUE; } //______________________________________________________________________________ void TVirtualPS::WriteInteger(Int_t n, Bool_t space ) { // Write one Integer to the file // // n: Integer to be written in the file. // space: If TRUE, a space in written before the integer. char str[15]; if (space) { sprintf(str," %d", n); } else { sprintf(str,"%d", n); } PrintStr(str); } //______________________________________________________________________________ void TVirtualPS::WriteReal(Float_t z) { // Write a Real number to the file char str[15]; sprintf(str," %g", z); PrintStr(str); } <commit_msg>One more protection added to TVirtualPS::PrintFast (thanks Gordon Watts)<commit_after>// @(#)root/base:$Name: $:$Id: TVirtualPS.cxx,v 1.13 2005/09/04 08:28:39 brun Exp $ // Author: Rene Brun 05/09/99 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TVirtualPS is an abstract interface to a Postscript and SVG drivers // // // ////////////////////////////////////////////////////////////////////////// #include "Riostream.h" #include "TVirtualPS.h" TVirtualPS *gVirtualPS = 0; const Int_t kMaxBuffer = 250; ClassImp(TVirtualPS) //______________________________________________________________________________ // // TVirtualPS is an abstract interface to a Postscript driver // //______________________________________________________________________________ TVirtualPS::TVirtualPS() { // VirtualPS default constructor fStream = 0; fNByte = 0; fSizBuffer = kMaxBuffer; fBuffer = new char[fSizBuffer+1]; } //______________________________________________________________________________ TVirtualPS::TVirtualPS(const char *name, Int_t) : TNamed(name,"Postscript interface") { // VirtualPS constructor fStream = 0; fNByte = 0; fSizBuffer = kMaxBuffer; fBuffer = new char[fSizBuffer+1]; } //______________________________________________________________________________ TVirtualPS::~TVirtualPS() { // VirtualPS destructor if (fBuffer) delete [] fBuffer; } //______________________________________________________________________________ void TVirtualPS::PrintStr(const char *str) { // Output the string str in the output buffer Int_t len = strlen(str); if (len == 0) return; if( str[0] == '@') { if( fLenBuffer ) { fStream->write(fBuffer, fLenBuffer); fStream->write("\n",1); fNByte++; } if ( len < 2) { fBuffer[0] = ' '; } else { strcpy(fBuffer, str+1); } fLenBuffer = len-1; fPrinted = kTRUE; fNByte += len-1; return; } if( str[len-1] == '@') { if( fLenBuffer ) { fStream->write(fBuffer, fLenBuffer); fStream->write("\n",1); fNByte++; } fStream->write(str, len-1); fStream->write("\n",1); fLenBuffer = 0; fNByte += len; fPrinted = kTRUE; return; } if( (len + fLenBuffer ) > kMaxBuffer-1) { fStream->write(fBuffer, fLenBuffer); fStream->write("\n",1); fNByte++; strcpy(fBuffer, str); fLenBuffer = len; fNByte += len; } else { strcpy(fBuffer + fLenBuffer, str); fLenBuffer += len; fNByte += len; } fPrinted = kTRUE; } //______________________________________________________________________________ void TVirtualPS::PrintFast(Int_t len, const char *str) { // Fast version of Print fNByte += len; if( (len + fLenBuffer ) > kMaxBuffer-1) { fStream->write(fBuffer, fLenBuffer); fStream->write("\n",1); fNByte++; while (len > kMaxBuffer-1) { fStream->write(str,kMaxBuffer); len -= kMaxBuffer; str += kMaxBuffer; } strcpy(fBuffer, str); fLenBuffer = len; } else { strcpy(fBuffer + fLenBuffer, str); fLenBuffer += len; } fPrinted = kTRUE; } //______________________________________________________________________________ void TVirtualPS::WriteInteger(Int_t n, Bool_t space ) { // Write one Integer to the file // // n: Integer to be written in the file. // space: If TRUE, a space in written before the integer. char str[15]; if (space) { sprintf(str," %d", n); } else { sprintf(str,"%d", n); } PrintStr(str); } //______________________________________________________________________________ void TVirtualPS::WriteReal(Float_t z) { // Write a Real number to the file char str[15]; sprintf(str," %g", z); PrintStr(str); } <|endoftext|>
<commit_before>#include "SkBenchmark.h" #include "SkBitmap.h" #include "SkCanvas.h" #include "SkColorPriv.h" #include "SkGradientShader.h" #include "SkPaint.h" #include "SkShader.h" #include "SkString.h" #include "SkUnitMapper.h" struct GradData { int fCount; const SkColor* fColors; const SkScalar* fPos; }; static const SkColor gColors[] = { SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE, SK_ColorWHITE, SK_ColorBLACK }; static const SkScalar gPos0[] = { 0, SK_Scalar1 }; static const SkScalar gPos1[] = { SK_Scalar1/4, SK_Scalar1*3/4 }; static const SkScalar gPos2[] = { 0, SK_Scalar1/8, SK_Scalar1/2, SK_Scalar1*7/8, SK_Scalar1 }; static const GradData gGradData[] = { { 2, gColors, NULL }, { 2, gColors, gPos0 }, { 2, gColors, gPos1 }, { 5, gColors, NULL }, { 5, gColors, gPos2 } }; static SkShader* MakeLinear(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm, SkUnitMapper* mapper) { return SkGradientShader::CreateLinear(pts, data.fColors, data.fPos, data.fCount, tm, mapper); } static SkShader* MakeRadial(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm, SkUnitMapper* mapper) { SkPoint center; center.set(SkScalarAve(pts[0].fX, pts[1].fX), SkScalarAve(pts[0].fY, pts[1].fY)); return SkGradientShader::CreateRadial(center, center.fX, data.fColors, data.fPos, data.fCount, tm, mapper); } static SkShader* MakeSweep(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm, SkUnitMapper* mapper) { SkPoint center; center.set(SkScalarAve(pts[0].fX, pts[1].fX), SkScalarAve(pts[0].fY, pts[1].fY)); return SkGradientShader::CreateSweep(center.fX, center.fY, data.fColors, data.fPos, data.fCount, mapper); } static SkShader* Make2Radial(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm, SkUnitMapper* mapper) { SkPoint center0, center1; center0.set(SkScalarAve(pts[0].fX, pts[1].fX), SkScalarAve(pts[0].fY, pts[1].fY)); center1.set(SkScalarInterp(pts[0].fX, pts[1].fX, SkIntToScalar(3)/5), SkScalarInterp(pts[0].fY, pts[1].fY, SkIntToScalar(1)/4)); return SkGradientShader::CreateTwoPointRadial( center1, (pts[1].fX - pts[0].fX) / 7, center0, (pts[1].fX - pts[0].fX) / 2, data.fColors, data.fPos, data.fCount, tm, mapper); } typedef SkShader* (*GradMaker)(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm, SkUnitMapper* mapper); static const struct { GradMaker fMaker; const char* fName; int fRepeat; } gGrads[] = { { MakeLinear, "linear", 15 }, { MakeRadial, "radial1", 10 }, { MakeSweep, "sweep", 1 }, { Make2Radial, "radial2", 5 }, }; enum GradType { // these must match the order in gGrads kLinear_GradType, kRadial_GradType, kSweep_GradType, kRadial2_GradType }; /////////////////////////////////////////////////////////////////////////////// class GradientBench : public SkBenchmark { SkString fName; SkShader* fShader; int fCount; enum { W = 400, H = 400, N = 1 }; public: GradientBench(void* param, GradType gt) : INHERITED(param) { fName.printf("gradient_%s", gGrads[gt].fName); const SkPoint pts[2] = { { 0, 0 }, { SkIntToScalar(W), SkIntToScalar(H) } }; fCount = N * gGrads[gt].fRepeat; fShader = gGrads[gt].fMaker(pts, gGradData[0], SkShader::kClamp_TileMode, NULL); } virtual ~GradientBench() { fShader->unref(); } protected: virtual const char* onGetName() { return fName.c_str(); } virtual void onDraw(SkCanvas* canvas) { SkPaint paint; this->setupPaint(&paint); paint.setShader(fShader); SkRect r = { 0, 0, SkIntToScalar(W), SkIntToScalar(H) }; for (int i = 0; i < fCount; i++) { canvas->drawRect(r, paint); } } private: typedef SkBenchmark INHERITED; }; static SkBenchmark* Fact0(void* p) { return new GradientBench(p, kLinear_GradType); } static SkBenchmark* Fact1(void* p) { return new GradientBench(p, kRadial_GradType); } static SkBenchmark* Fact2(void* p) { return new GradientBench(p, kSweep_GradType); } static SkBenchmark* Fact3(void* p) { return new GradientBench(p, kRadial2_GradType); } static BenchRegistry gReg0(Fact0); static BenchRegistry gReg1(Fact1); static BenchRegistry gReg2(Fact2); static BenchRegistry gReg3(Fact3); <commit_msg>add tilemode options<commit_after>#include "SkBenchmark.h" #include "SkBitmap.h" #include "SkCanvas.h" #include "SkColorPriv.h" #include "SkGradientShader.h" #include "SkPaint.h" #include "SkShader.h" #include "SkString.h" #include "SkUnitMapper.h" struct GradData { int fCount; const SkColor* fColors; const SkScalar* fPos; }; static const SkColor gColors[] = { SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE, SK_ColorWHITE, SK_ColorBLACK }; static const SkScalar gPos0[] = { 0, SK_Scalar1 }; static const SkScalar gPos1[] = { SK_Scalar1/4, SK_Scalar1*3/4 }; static const SkScalar gPos2[] = { 0, SK_Scalar1/8, SK_Scalar1/2, SK_Scalar1*7/8, SK_Scalar1 }; static const GradData gGradData[] = { { 2, gColors, NULL }, { 2, gColors, gPos0 }, { 2, gColors, gPos1 }, { 5, gColors, NULL }, { 5, gColors, gPos2 } }; static SkShader* MakeLinear(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm, SkUnitMapper* mapper) { return SkGradientShader::CreateLinear(pts, data.fColors, data.fPos, data.fCount, tm, mapper); } static SkShader* MakeRadial(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm, SkUnitMapper* mapper) { SkPoint center; center.set(SkScalarAve(pts[0].fX, pts[1].fX), SkScalarAve(pts[0].fY, pts[1].fY)); return SkGradientShader::CreateRadial(center, center.fX, data.fColors, data.fPos, data.fCount, tm, mapper); } static SkShader* MakeSweep(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm, SkUnitMapper* mapper) { SkPoint center; center.set(SkScalarAve(pts[0].fX, pts[1].fX), SkScalarAve(pts[0].fY, pts[1].fY)); return SkGradientShader::CreateSweep(center.fX, center.fY, data.fColors, data.fPos, data.fCount, mapper); } static SkShader* Make2Radial(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm, SkUnitMapper* mapper) { SkPoint center0, center1; center0.set(SkScalarAve(pts[0].fX, pts[1].fX), SkScalarAve(pts[0].fY, pts[1].fY)); center1.set(SkScalarInterp(pts[0].fX, pts[1].fX, SkIntToScalar(3)/5), SkScalarInterp(pts[0].fY, pts[1].fY, SkIntToScalar(1)/4)); return SkGradientShader::CreateTwoPointRadial( center1, (pts[1].fX - pts[0].fX) / 7, center0, (pts[1].fX - pts[0].fX) / 2, data.fColors, data.fPos, data.fCount, tm, mapper); } typedef SkShader* (*GradMaker)(const SkPoint pts[2], const GradData& data, SkShader::TileMode tm, SkUnitMapper* mapper); static const struct { GradMaker fMaker; const char* fName; int fRepeat; } gGrads[] = { { MakeLinear, "linear", 15 }, { MakeRadial, "radial1", 10 }, { MakeSweep, "sweep", 1 }, { Make2Radial, "radial2", 5 }, }; enum GradType { // these must match the order in gGrads kLinear_GradType, kRadial_GradType, kSweep_GradType, kRadial2_GradType }; static const char* tilemodename(SkShader::TileMode tm) { switch (tm) { case SkShader::kClamp_TileMode: return "clamp"; case SkShader::kRepeat_TileMode: return "repeat"; case SkShader::kMirror_TileMode: return "mirror"; default: SkASSERT(!"unknown tilemode"); return "error"; } } /////////////////////////////////////////////////////////////////////////////// class GradientBench : public SkBenchmark { SkString fName; SkShader* fShader; int fCount; enum { W = 400, H = 400, N = 1 }; public: GradientBench(void* param, GradType gt, SkShader::TileMode tm = SkShader::kClamp_TileMode) : INHERITED(param) { fName.printf("gradient_%s_%s", gGrads[gt].fName, tilemodename(tm)); const SkPoint pts[2] = { { 0, 0 }, { SkIntToScalar(W), SkIntToScalar(H) } }; fCount = N * gGrads[gt].fRepeat; fShader = gGrads[gt].fMaker(pts, gGradData[0], tm, NULL); } virtual ~GradientBench() { fShader->unref(); } protected: virtual const char* onGetName() { return fName.c_str(); } virtual void onDraw(SkCanvas* canvas) { SkPaint paint; this->setupPaint(&paint); paint.setShader(fShader); SkRect r = { 0, 0, SkIntToScalar(W), SkIntToScalar(H) }; for (int i = 0; i < fCount; i++) { canvas->drawRect(r, paint); } } private: typedef SkBenchmark INHERITED; }; static SkBenchmark* Fact0(void* p) { return new GradientBench(p, kLinear_GradType); } static SkBenchmark* Fact1(void* p) { return new GradientBench(p, kRadial_GradType); } static SkBenchmark* Fact11(void* p) { return new GradientBench(p, kRadial_GradType, SkShader::kMirror_TileMode); } static SkBenchmark* Fact2(void* p) { return new GradientBench(p, kSweep_GradType); } static SkBenchmark* Fact3(void* p) { return new GradientBench(p, kRadial2_GradType); } static BenchRegistry gReg0(Fact0); static BenchRegistry gReg1(Fact1); static BenchRegistry gReg11(Fact11); static BenchRegistry gReg2(Fact2); static BenchRegistry gReg3(Fact3); <|endoftext|>
<commit_before> // g++-4.2 -O3 -DNDEBUG -I.. benchBlasGemm.cpp /usr/lib/libcblas.so.3 - o benchBlasGemm // possible options: // -DEIGEN_DONT_VECTORIZE // -msse2 // #define EIGEN_DEFAULT_TO_ROW_MAJOR #define _FLOAT #include <Eigen/Array> #include <Eigen/Core> #include "BenchTimer.h" // include the BLAS headers #include <cblas.h> #include <string> #ifdef _FLOAT typedef float Scalar; #define CBLAS_GEMM cblas_sgemm #else typedef double Scalar; #define CBLAS_GEMM cblas_dgemm #endif typedef Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic> MyMatrix; void bench_eigengemm(MyMatrix& mc, const MyMatrix& ma, const MyMatrix& mb, int nbloops); void bench_eigengemm_normal(MyMatrix& mc, const MyMatrix& ma, const MyMatrix& mb, int nbloops); void check_product(int M, int N, int K); void check_product(void); int main(int argc, char *argv[]) { // disable SSE exceptions #ifdef __GNUC__ { int aux; asm( "stmxcsr %[aux] \n\t" "orl $32832, %[aux] \n\t" "ldmxcsr %[aux] \n\t" : : [aux] "m" (aux)); } #endif int nbtries=1, nbloops=1, M, N, K; if (argc==2) { if (std::string(argv[1])=="check") check_product(); else M = N = K = atoi(argv[1]); } else if ((argc==3) && (std::string(argv[1])=="auto")) { M = N = K = atoi(argv[2]); nbloops = 1000000000/(M*M*M); if (nbloops<1) nbloops = 1; nbtries = 6; } else if (argc==4) { M = N = K = atoi(argv[1]); nbloops = atoi(argv[2]); nbtries = atoi(argv[3]); } else if (argc==6) { M = atoi(argv[1]); N = atoi(argv[2]); K = atoi(argv[3]); nbloops = atoi(argv[4]); nbtries = atoi(argv[5]); } else { std::cout << "Usage: " << argv[0] << " size \n"; std::cout << "Usage: " << argv[0] << " auto size\n"; std::cout << "Usage: " << argv[0] << " size nbloops nbtries\n"; std::cout << "Usage: " << argv[0] << " M N K nbloops nbtries\n"; std::cout << "Usage: " << argv[0] << " check\n"; std::cout << "Options:\n"; std::cout << " size unique size of the 2 matrices (integer)\n"; std::cout << " auto automatically set the number of repetitions and tries\n"; std::cout << " nbloops number of times the GEMM routines is executed\n"; std::cout << " nbtries number of times the loop is benched (return the best try)\n"; std::cout << " M N K sizes of the matrices: MxN = MxK * KxN (integers)\n"; std::cout << " check check eigen product using cblas as a reference\n"; exit(1); } double nbmad = double(M) * double(N) * double(K) * double(nbloops); if (!(std::string(argv[1])=="auto")) std::cout << M << " x " << N << " x " << K << "\n"; Scalar alpha, beta; MyMatrix ma(M,K), mb(K,N), mc(M,N); ma = MyMatrix::Random(M,K); mb = MyMatrix::Random(K,N); mc = MyMatrix::Random(M,N); Eigen::BenchTimer timer; // we simply compute c += a*b, so: alpha = 1; beta = 1; // bench cblas // ROWS_A, COLS_B, COLS_A, 1.0, A, COLS_A, B, COLS_B, 0.0, C, COLS_B); if (!(std::string(argv[1])=="auto")) { timer.reset(); for (uint k=0 ; k<nbtries ; ++k) { timer.start(); for (uint j=0 ; j<nbloops ; ++j) #ifdef EIGEN_DEFAULT_TO_ROW_MAJOR CBLAS_GEMM(CblasRowMajor, CblasNoTrans, CblasNoTrans, M, N, K, alpha, ma.data(), K, mb.data(), N, beta, mc.data(), N); #else CBLAS_GEMM(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, K, alpha, ma.data(), M, mb.data(), K, beta, mc.data(), M); #endif timer.stop(); } if (!(std::string(argv[1])=="auto")) std::cout << "cblas: " << timer.value() << " (" << 1e-3*floor(1e-6*nbmad/timer.value()) << " GFlops/s)\n"; else std::cout << M << " : " << timer.value() << " ; " << 1e-3*floor(1e-6*nbmad/timer.value()) << "\n"; } // clear ma = MyMatrix::Random(M,K); mb = MyMatrix::Random(K,N); mc = MyMatrix::Random(M,N); // eigen // if (!(std::string(argv[1])=="auto")) { timer.reset(); for (uint k=0 ; k<nbtries ; ++k) { timer.start(); bench_eigengemm(mc, ma, mb, nbloops); timer.stop(); } if (!(std::string(argv[1])=="auto")) std::cout << "eigen : " << timer.value() << " (" << 1e-3*floor(1e-6*nbmad/timer.value()) << " GFlops/s)\n"; else std::cout << M << " : " << timer.value() << " ; " << 1e-3*floor(1e-6*nbmad/timer.value()) << "\n"; } // clear ma = MyMatrix::Random(M,K); mb = MyMatrix::Random(K,N); mc = MyMatrix::Random(M,N); // eigen normal if (!(std::string(argv[1])=="auto")) { timer.reset(); for (uint k=0 ; k<nbtries ; ++k) { timer.start(); bench_eigengemm_normal(mc, ma, mb, nbloops); timer.stop(); } std::cout << "eigen : " << timer.value() << " (" << 1e-3*floor(1e-6*nbmad/timer.value()) << " GFlops/s)\n"; } return 0; } using namespace Eigen; void bench_eigengemm(MyMatrix& mc, const MyMatrix& ma, const MyMatrix& mb, int nbloops) { for (uint j=0 ; j<nbloops ; ++j) mc += (ma * mb).lazy(); } void bench_eigengemm_normal(MyMatrix& mc, const MyMatrix& ma, const MyMatrix& mb, int nbloops) { for (uint j=0 ; j<nbloops ; ++j) mc += Product<MyMatrix,MyMatrix,NormalProduct>(ma,mb).lazy(); } #define MYVERIFY(A,M) if (!(A)) { \ std::cout << "FAIL: " << M << "\n"; \ } void check_product(int M, int N, int K) { MyMatrix ma(M,K), mb(K,N), mc(M,N), maT(K,M), mbT(N,K), meigen(M,N), mref(M,N); ma = MyMatrix::Random(M,K); mb = MyMatrix::Random(K,N); maT = ma.transpose(); mbT = mb.transpose(); mc = MyMatrix::Random(M,N); MyMatrix::Scalar eps = 1e-4; meigen = mref = mc; CBLAS_GEMM(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, K, 1, ma.data(), M, mb.data(), K, 1, mref.data(), M); meigen += ma * mb; MYVERIFY(meigen.isApprox(mref, eps),". * ."); meigen = mref = mc; CBLAS_GEMM(CblasColMajor, CblasTrans, CblasNoTrans, M, N, K, 1, maT.data(), K, mb.data(), K, 1, mref.data(), M); meigen += maT.transpose() * mb; MYVERIFY(meigen.isApprox(mref, eps),"T * ."); meigen = mref = mc; CBLAS_GEMM(CblasColMajor, CblasTrans, CblasTrans, M, N, K, 1, maT.data(), K, mbT.data(), N, 1, mref.data(), M); meigen += (maT.transpose()) * (mbT.transpose()); MYVERIFY(meigen.isApprox(mref, eps),"T * T"); meigen = mref = mc; CBLAS_GEMM(CblasColMajor, CblasNoTrans, CblasTrans, M, N, K, 1, ma.data(), M, mbT.data(), N, 1, mref.data(), M); meigen += ma * mbT.transpose(); MYVERIFY(meigen.isApprox(mref, eps),". * T"); } void check_product(void) { int M, N, K; for (uint i=0; i<1000; ++i) { M = ei_random<int>(1,64); N = ei_random<int>(1,768); K = ei_random<int>(1,768); M = (0 + M) * 1; std::cout << M << " x " << N << " x " << K << "\n"; check_product(M, N, K); } } <commit_msg>update product bench<commit_after> // g++-4.2 -O3 -DNDEBUG -I.. benchBlasGemm.cpp /usr/lib/libcblas.so.3 - o benchBlasGemm // possible options: // -DEIGEN_DONT_VECTORIZE // -msse2 // #define EIGEN_DEFAULT_TO_ROW_MAJOR #define _FLOAT #include <Eigen/Array> #include <Eigen/Core> #include "BenchTimer.h" // include the BLAS headers #include <cblas.h> #include <string> #ifdef _FLOAT typedef float Scalar; #define CBLAS_GEMM cblas_sgemm #else typedef double Scalar; #define CBLAS_GEMM cblas_dgemm #endif typedef Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic> MyMatrix; void bench_eigengemm(MyMatrix& mc, const MyMatrix& ma, const MyMatrix& mb, int nbloops); void bench_eigengemm_normal(MyMatrix& mc, const MyMatrix& ma, const MyMatrix& mb, int nbloops); void check_product(int M, int N, int K); void check_product(void); int main(int argc, char *argv[]) { // disable SSE exceptions #ifdef __GNUC__ { int aux; asm( "stmxcsr %[aux] \n\t" "orl $32832, %[aux] \n\t" "ldmxcsr %[aux] \n\t" : : [aux] "m" (aux)); } #endif int nbtries=1, nbloops=1, M, N, K; if (argc==2) { if (std::string(argv[1])=="check") check_product(); else M = N = K = atoi(argv[1]); } else if ((argc==3) && (std::string(argv[1])=="auto")) { M = N = K = atoi(argv[2]); nbloops = 1000000000/(M*M*M); if (nbloops<1) nbloops = 1; nbtries = 6; } else if (argc==4) { M = N = K = atoi(argv[1]); nbloops = atoi(argv[2]); nbtries = atoi(argv[3]); } else if (argc==6) { M = atoi(argv[1]); N = atoi(argv[2]); K = atoi(argv[3]); nbloops = atoi(argv[4]); nbtries = atoi(argv[5]); } else { std::cout << "Usage: " << argv[0] << " size \n"; std::cout << "Usage: " << argv[0] << " auto size\n"; std::cout << "Usage: " << argv[0] << " size nbloops nbtries\n"; std::cout << "Usage: " << argv[0] << " M N K nbloops nbtries\n"; std::cout << "Usage: " << argv[0] << " check\n"; std::cout << "Options:\n"; std::cout << " size unique size of the 2 matrices (integer)\n"; std::cout << " auto automatically set the number of repetitions and tries\n"; std::cout << " nbloops number of times the GEMM routines is executed\n"; std::cout << " nbtries number of times the loop is benched (return the best try)\n"; std::cout << " M N K sizes of the matrices: MxN = MxK * KxN (integers)\n"; std::cout << " check check eigen product using cblas as a reference\n"; exit(1); } double nbmad = double(M) * double(N) * double(K) * double(nbloops); if (!(std::string(argv[1])=="auto")) std::cout << M << " x " << N << " x " << K << "\n"; Scalar alpha, beta; MyMatrix ma(M,K), mb(K,N), mc(M,N); ma = MyMatrix::Random(M,K); mb = MyMatrix::Random(K,N); mc = MyMatrix::Random(M,N); Eigen::BenchTimer timer; // we simply compute c += a*b, so: alpha = 1; beta = 1; // bench cblas // ROWS_A, COLS_B, COLS_A, 1.0, A, COLS_A, B, COLS_B, 0.0, C, COLS_B); if (!(std::string(argv[1])=="auto")) { timer.reset(); for (uint k=0 ; k<nbtries ; ++k) { timer.start(); for (uint j=0 ; j<nbloops ; ++j) #ifdef EIGEN_DEFAULT_TO_ROW_MAJOR CBLAS_GEMM(CblasRowMajor, CblasNoTrans, CblasNoTrans, M, N, K, alpha, ma.data(), K, mb.data(), N, beta, mc.data(), N); #else CBLAS_GEMM(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, K, alpha, ma.data(), M, mb.data(), K, beta, mc.data(), M); #endif timer.stop(); } if (!(std::string(argv[1])=="auto")) std::cout << "cblas: " << timer.value() << " (" << 1e-3*floor(1e-6*nbmad/timer.value()) << " GFlops/s)\n"; else std::cout << M << " : " << timer.value() << " ; " << 1e-3*floor(1e-6*nbmad/timer.value()) << "\n"; } // clear ma = MyMatrix::Random(M,K); mb = MyMatrix::Random(K,N); mc = MyMatrix::Random(M,N); // eigen // if (!(std::string(argv[1])=="auto")) { timer.reset(); for (uint k=0 ; k<nbtries ; ++k) { timer.start(); bench_eigengemm(mc, ma, mb, nbloops); timer.stop(); } if (!(std::string(argv[1])=="auto")) std::cout << "eigen : " << timer.value() << " (" << 1e-3*floor(1e-6*nbmad/timer.value()) << " GFlops/s)\n"; else std::cout << M << " : " << timer.value() << " ; " << 1e-3*floor(1e-6*nbmad/timer.value()) << "\n"; } // clear ma = MyMatrix::Random(M,K); mb = MyMatrix::Random(K,N); mc = MyMatrix::Random(M,N); // eigen normal if (!(std::string(argv[1])=="auto")) { timer.reset(); for (uint k=0 ; k<nbtries ; ++k) { timer.start(); bench_eigengemm_normal(mc, ma, mb, nbloops); timer.stop(); } std::cout << "eigen : " << timer.value() << " (" << 1e-3*floor(1e-6*nbmad/timer.value()) << " GFlops/s)\n"; } return 0; } using namespace Eigen; void bench_eigengemm(MyMatrix& mc, const MyMatrix& ma, const MyMatrix& mb, int nbloops) { for (uint j=0 ; j<nbloops ; ++j) mc.noalias() += ma * mb; } void bench_eigengemm_normal(MyMatrix& mc, const MyMatrix& ma, const MyMatrix& mb, int nbloops) { for (uint j=0 ; j<nbloops ; ++j) mc.noalias() += GeneralProduct<MyMatrix,MyMatrix,UnrolledProduct>(ma,mb); } #define MYVERIFY(A,M) if (!(A)) { \ std::cout << "FAIL: " << M << "\n"; \ } void check_product(int M, int N, int K) { MyMatrix ma(M,K), mb(K,N), mc(M,N), maT(K,M), mbT(N,K), meigen(M,N), mref(M,N); ma = MyMatrix::Random(M,K); mb = MyMatrix::Random(K,N); maT = ma.transpose(); mbT = mb.transpose(); mc = MyMatrix::Random(M,N); MyMatrix::Scalar eps = 1e-4; meigen = mref = mc; CBLAS_GEMM(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, K, 1, ma.data(), M, mb.data(), K, 1, mref.data(), M); meigen += ma * mb; MYVERIFY(meigen.isApprox(mref, eps),". * ."); meigen = mref = mc; CBLAS_GEMM(CblasColMajor, CblasTrans, CblasNoTrans, M, N, K, 1, maT.data(), K, mb.data(), K, 1, mref.data(), M); meigen += maT.transpose() * mb; MYVERIFY(meigen.isApprox(mref, eps),"T * ."); meigen = mref = mc; CBLAS_GEMM(CblasColMajor, CblasTrans, CblasTrans, M, N, K, 1, maT.data(), K, mbT.data(), N, 1, mref.data(), M); meigen += (maT.transpose()) * (mbT.transpose()); MYVERIFY(meigen.isApprox(mref, eps),"T * T"); meigen = mref = mc; CBLAS_GEMM(CblasColMajor, CblasNoTrans, CblasTrans, M, N, K, 1, ma.data(), M, mbT.data(), N, 1, mref.data(), M); meigen += ma * mbT.transpose(); MYVERIFY(meigen.isApprox(mref, eps),". * T"); } void check_product(void) { int M, N, K; for (uint i=0; i<1000; ++i) { M = ei_random<int>(1,64); N = ei_random<int>(1,768); K = ei_random<int>(1,768); M = (0 + M) * 1; std::cout << M << " x " << N << " x " << K << "\n"; check_product(M, N, K); } } <|endoftext|>
<commit_before>/* Copyright 2018 Stanford University * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "legion.h" #include "realm/python/python_module.h" #include "realm/python/python_source.h" #include <libgen.h> using namespace Legion; enum TaskIDs { MAIN_TASK_ID = 1, }; VariantID preregister_python_task_variant( const TaskVariantRegistrar &registrar, const char *module_name, const char *function_name, const void *userdata = NULL, size_t userlen = 0) { CodeDescriptor code_desc(Realm::Type::from_cpp_type<Processor::TaskFuncPtr>()); code_desc.add_implementation(new Realm::PythonSourceImplementation(module_name, function_name)); return Runtime::preregister_task_variant( registrar, code_desc, userdata, userlen, registrar.task_variant_name); } int main(int argc, char **argv) { // Add the binary directory to PYTHONPATH. This is needed for // in-place builds to find legion.py. // Do this before any threads are spawned. { char *bin_path = strdup(argv[0]); assert(bin_path != NULL); char *bin_dir = dirname(bin_path); char *previous_python_path = getenv("PYTHONPATH"); if (previous_python_path != 0) { size_t bufsize = strlen(previous_python_path) + strlen(bin_dir) + 2; char *buffer = (char *)calloc(bufsize, sizeof(char)); assert(buffer != 0); // assert(strlen(previous_python_path) + strlen(bin_dir) + 2 < bufsize); // Concatenate bin_dir to the end of PYTHONPATH. bufsize--; strncat(buffer, previous_python_path, bufsize); bufsize -= strlen(previous_python_path); strncat(buffer, ":", bufsize); bufsize -= strlen(":"); strncat(buffer, bin_dir, bufsize); bufsize -= strlen(bin_dir); setenv("PYTHONPATH", buffer, true /*overwrite*/); } else { setenv("PYTHONPATH", bin_dir, true /*overwrite*/); } free(bin_path); } if (argc < 2) { fprintf(stderr, "usage: %s <module_name>\n", argv[0]); exit(1); } const char *module_name = argv[1]; Realm::Python::PythonModule::import_python_module(module_name); { TaskVariantRegistrar registrar(MAIN_TASK_ID, "main"); registrar.add_constraint(ProcessorConstraint(Processor::PY_PROC)); preregister_python_task_variant(registrar, module_name, "main"); } Runtime::set_top_level_task_id(MAIN_TASK_ID); return Runtime::start(argc, argv); } <commit_msg>python: Update Python main.<commit_after>/* Copyright 2018 Stanford University * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "legion.h" #include "realm/python/python_module.h" #include "realm/python/python_source.h" #include <libgen.h> using namespace Legion; enum TaskIDs { MAIN_TASK_ID = 1, }; VariantID preregister_python_task_variant( const TaskVariantRegistrar &registrar, const char *module_name, const char *function_name, const void *userdata = NULL, size_t userlen = 0) { CodeDescriptor code_desc(Realm::Type::from_cpp_type<Processor::TaskFuncPtr>()); code_desc.add_implementation(new Realm::PythonSourceImplementation(module_name, function_name)); return Runtime::preregister_task_variant( registrar, code_desc, userdata, userlen, registrar.task_variant_name); } void preregister_python_initialization_function( const char *module_name, const char *function_name, const void *userdata = NULL, size_t userlen = 0) { CodeDescriptor code_desc(Realm::Type::from_cpp_type<Processor::TaskFuncPtr>()); code_desc.add_implementation(new Realm::PythonSourceImplementation(module_name, function_name)); return Runtime::preregister_initialization_function( Processor::PY_PROC, code_desc, userdata, userlen); } int main(int argc, char **argv) { // Add the binary directory to PYTHONPATH. This is needed for // in-place builds to find legion.py. // Do this before any threads are spawned. { char *bin_path = strdup(argv[0]); assert(bin_path != NULL); char *bin_dir = dirname(bin_path); char *previous_python_path = getenv("PYTHONPATH"); if (previous_python_path != 0) { size_t bufsize = strlen(previous_python_path) + strlen(bin_dir) + 2; char *buffer = (char *)calloc(bufsize, sizeof(char)); assert(buffer != 0); // assert(strlen(previous_python_path) + strlen(bin_dir) + 2 < bufsize); // Concatenate bin_dir to the end of PYTHONPATH. bufsize--; strncat(buffer, previous_python_path, bufsize); bufsize -= strlen(previous_python_path); strncat(buffer, ":", bufsize); bufsize -= strlen(":"); strncat(buffer, bin_dir, bufsize); bufsize -= strlen(bin_dir); setenv("PYTHONPATH", buffer, true /*overwrite*/); } else { setenv("PYTHONPATH", bin_dir, true /*overwrite*/); } free(bin_path); } if (argc < 2) { fprintf(stderr, "usage: %s <module_name>\n", argv[0]); exit(1); } const char *module_name = argv[1]; Realm::Python::PythonModule::import_python_module(module_name); { TaskVariantRegistrar registrar(MAIN_TASK_ID, "main"); registrar.add_constraint(ProcessorConstraint(Processor::PY_PROC)); preregister_python_task_variant(registrar, module_name, "main"); } Runtime::set_top_level_task_id(MAIN_TASK_ID); preregister_python_initialization_function("legion", "initialize"); return Runtime::start(argc, argv); } <|endoftext|>
<commit_before>/* Copyright (c) 2015-2020 Max Krasnyansky <max.krasnyansky@gmail.com> 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sched.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <cstdlib> #include <string> #include "hogl/detail/internal.hpp" #include "hogl/platform.hpp" #include "hogl/post.hpp" #if defined(__QNXNTO__) #include <sys/neutrino.h> #include <sys/syspage.h> #endif __HOGL_PRIV_NS_OPEN__ namespace hogl { // **** // CPU affinity support #if defined(__linux__) struct cpumask { cpu_set_t* cpuset; size_t ncpus; size_t nbytes; cpumask(unsigned int capacity = 256) : cpuset(nullptr), ncpus(capacity) { nbytes = CPU_ALLOC_SIZE(ncpus); cpuset = CPU_ALLOC(ncpus); if (cpuset) CPU_ZERO_S(nbytes, cpuset); } ~cpumask() { if (cpuset) CPU_FREE(cpuset); } bool valid() const { return cpuset != nullptr; } void set(unsigned int i) { CPU_SET_S(i, nbytes, cpuset); } int apply() { return pthread_setaffinity_np(pthread_self(), nbytes, cpuset); } }; #elif defined(__QNXNTO__) struct cpumask { unsigned *runmask; size_t ncpus; cpumask(unsigned int capacity = _syspage_ptr->num_cpu) : runmask(nullptr), ncpus(capacity) { int nbytes = RMSK_SIZE(ncpus) * sizeof(unsigned); runmask = (unsigned *) malloc(nbytes); if (!runmask) return; memset(runmask, 0, nbytes); } ~cpumask() { free(runmask); } bool valid() const { return false; } void set(unsigned int i) { RMSK_SET(i, runmask); } int apply() { return ThreadCtl_r(_NTO_TCTL_RUNMASK, runmask); } }; #else struct cpumask { bool valid() const { return false; } void set(unsigned int i) { ; } int apply() { platform::post_early(internal::WARN, "cpu-affinity not supported on this platform"); return EOPNOTSUPP; } }; #endif // FIXME: add support Linux kernel cpusets // Convert list format string into cpu mask. // @param str list string (comma-separated list of decimal numbers and ranges) // @param mask output mask // @param nbytes number of bytes in the mask // returns 0 on success, errno on invalid input strings. static int parse_cpulist(const std::string& str, cpumask& mask) { const char *p = str.c_str(); unsigned int a, b; do { if (!isdigit(*p)) return EINVAL; b = a = strtoul(p, (char **)&p, 10); if (*p == '-') { p++; if (!isdigit(*p)) return EINVAL; b = strtoul(p, (char **)&p, 10); } if (!(a <= b)) return EINVAL; if (b >= mask.ncpus) return ERANGE; while (a <= b) { mask.set(a); a++; } if (*p == ',') p++; } while (*p != '\0'); return 0; } static int parse_cpumask(const std::string& str, cpumask& mask) { // FIXME: limited to 64 cpus errno = 0; unsigned long long m = std::strtoull(str.c_str(), 0, 0); if (errno) return errno; for (unsigned int i=0; i < mask.ncpus; i++) if (m & (1<<i)) mask.set(i); return 0; } static int parse_cpu_affinity(const std::string& cpuset_str, cpumask& mask) { int err = 0; if (cpuset_str.compare(0, 5, "list:") == 0) err = parse_cpulist(cpuset_str.substr(5), mask); else if (cpuset_str.compare(0, 5, "mask:") == 0) err = parse_cpumask(cpuset_str.substr(5), mask); else err = parse_cpumask(cpuset_str, mask); return err; } static int set_cpu_affinity(const std::string& cpuset_str, bool dryrun = false) { int err = 0; cpumask mask; if (!mask.valid()) return EINVAL; err = parse_cpu_affinity(cpuset_str, mask); if (!err && !dryrun) err = mask.apply(); return err; } schedparam::schedparam(int _policy, int _priority, unsigned int _flags, const std::string _cpu_affinity) : policy(_policy), priority(_priority), flags(_flags), cpu_affinity(_cpu_affinity) { } schedparam::schedparam() : policy(SCHED_OTHER), priority(0), flags(0), cpu_affinity() { } bool schedparam::thread_enter(const char * /* title */) { bool failed = false; int err = 0; // Apply CPU affinity settings if (!this->cpu_affinity.empty()) { err = set_cpu_affinity(this->cpu_affinity); if (err) { platform::post_early(internal::WARN, "set-cpu-affinity failed: %s(%d)", strerror(err), err); failed = true; } } struct sched_param sp = {0}; sp.sched_priority = this->priority; err = pthread_setschedparam(pthread_self(), this->policy, &sp); if (err) { platform::post_early(internal::WARN, "pthread-setschedparam failed: %s(%d)", strerror(err), err); failed = true; } return !failed; } void schedparam::thread_exit() { if (flags & DELETE_ON_EXIT) delete this; } bool schedparam::validate() const { bool failed = false; int err = 0; // Check CPU affinity settings if (!this->cpu_affinity.empty()) { err = set_cpu_affinity(this->cpu_affinity, true /* dryrun */); if (err) { platform::post_early(internal::WARN, "invalid cpu-affinity: %s %s", this->cpu_affinity.c_str(), strerror(err)); failed = true; } } // FIXME: sanity check policy and priority return !failed; } std::ostream& operator<< (std::ostream& s, const schedparam& p) { std::ios_base::fmtflags fmt = s.flags(); s << "" << "{ " << "policy:" << p.policy << ", " << "priority:" << p.priority << ", " << "cpu-affinity:" << p.cpu_affinity << " }"; s.flags(fmt); return s; } } // namespace hogl __HOGL_PRIV_NS_CLOSE__ <commit_msg>Use latest QNX ThreadCtl command for setting both runtime and inherit masks<commit_after>/* Copyright (c) 2015-2020 Max Krasnyansky <max.krasnyansky@gmail.com> 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sched.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <cstdlib> #include <string> #include "hogl/detail/internal.hpp" #include "hogl/platform.hpp" #include "hogl/post.hpp" #if defined(__QNXNTO__) #include <sys/neutrino.h> #include <sys/syspage.h> #endif __HOGL_PRIV_NS_OPEN__ namespace hogl { // **** // CPU affinity support #if defined(__linux__) struct cpumask { cpu_set_t* cpuset; size_t ncpus; size_t nbytes; cpumask(unsigned int capacity = 256) : cpuset(nullptr), ncpus(capacity) { nbytes = CPU_ALLOC_SIZE(ncpus); cpuset = CPU_ALLOC(ncpus); if (cpuset) CPU_ZERO_S(nbytes, cpuset); } ~cpumask() { if (cpuset) CPU_FREE(cpuset); } bool valid() const { return cpuset != nullptr; } void set(unsigned int i) { CPU_SET_S(i, nbytes, cpuset); } int apply() { return pthread_setaffinity_np(pthread_self(), nbytes, cpuset); } }; #elif defined(__QNXNTO__) struct cpumask { int *data; unsigned *rmask; unsigned *imask; size_t ncpus; // Code below implements this layout // struct _thread_runmask { // int size; // unsigned runmask[size]; // unsigned inherit_mask[size]; // }; cpumask(unsigned int capacity = _syspage_ptr->num_cpu) : data(nullptr), ncpus(capacity) { int mask_bytes = RMSK_SIZE(ncpus) * sizeof(unsigned); data = (int*) calloc(1, sizeof(int) + mask_bytes * 2); if (!data) return; uint8_t *ptr = (uint8_t *) data; *data = RMSK_SIZE(ncpus); ptr += sizeof(int); rmask = (unsigned *) ptr; ptr += mask_bytes; imask = (unsigned *) ptr; ptr += mask_bytes; } ~cpumask() { free(data); } bool valid() const { return data != nullptr; } void set(unsigned int i) { RMSK_SET(i, rmask); RMSK_SET(i, imask); } int apply() { return ThreadCtl_r(_NTO_TCTL_RUNMASK_GET_AND_SET_INHERIT, data); } }; #else struct cpumask { bool valid() const { return false; } void set(unsigned int i) { ; } int apply() { platform::post_early(internal::WARN, "cpu-affinity not supported on this platform"); return EOPNOTSUPP; } }; #endif // FIXME: add support Linux kernel cpusets // Convert list format string into cpu mask. // @param str list string (comma-separated list of decimal numbers and ranges) // @param mask output mask // @param nbytes number of bytes in the mask // returns 0 on success, errno on invalid input strings. static int parse_cpulist(const std::string& str, cpumask& mask) { const char *p = str.c_str(); unsigned int a, b; do { if (!isdigit(*p)) return EINVAL; b = a = strtoul(p, (char **)&p, 10); if (*p == '-') { p++; if (!isdigit(*p)) return EINVAL; b = strtoul(p, (char **)&p, 10); } if (!(a <= b)) return EINVAL; if (b >= mask.ncpus) return ERANGE; while (a <= b) { mask.set(a); a++; } if (*p == ',') p++; } while (*p != '\0'); return 0; } static int parse_cpumask(const std::string& str, cpumask& mask) { // FIXME: limited to 64 cpus errno = 0; unsigned long long m = std::strtoull(str.c_str(), 0, 0); if (errno) return errno; for (unsigned int i=0; i < mask.ncpus; i++) if (m & (1<<i)) mask.set(i); return 0; } static int parse_cpu_affinity(const std::string& cpuset_str, cpumask& mask) { int err = 0; if (cpuset_str.compare(0, 5, "list:") == 0) err = parse_cpulist(cpuset_str.substr(5), mask); else if (cpuset_str.compare(0, 5, "mask:") == 0) err = parse_cpumask(cpuset_str.substr(5), mask); else err = parse_cpumask(cpuset_str, mask); return err; } static int set_cpu_affinity(const std::string& cpuset_str, bool dryrun = false) { int err = 0; cpumask mask; if (!mask.valid()) return EINVAL; err = parse_cpu_affinity(cpuset_str, mask); if (!err && !dryrun) err = mask.apply(); return err; } schedparam::schedparam(int _policy, int _priority, unsigned int _flags, const std::string _cpu_affinity) : policy(_policy), priority(_priority), flags(_flags), cpu_affinity(_cpu_affinity) { } schedparam::schedparam() : policy(SCHED_OTHER), priority(0), flags(0), cpu_affinity() { } bool schedparam::thread_enter(const char * /* title */) { bool failed = false; int err = 0; // Apply CPU affinity settings if (!this->cpu_affinity.empty()) { err = set_cpu_affinity(this->cpu_affinity); if (err) { platform::post_early(internal::WARN, "set-cpu-affinity failed: %s(%d)", strerror(err), err); failed = true; } } struct sched_param sp = {0}; sp.sched_priority = this->priority; err = pthread_setschedparam(pthread_self(), this->policy, &sp); if (err) { platform::post_early(internal::WARN, "pthread-setschedparam failed: %s(%d)", strerror(err), err); failed = true; } return !failed; } void schedparam::thread_exit() { if (flags & DELETE_ON_EXIT) delete this; } bool schedparam::validate() const { bool failed = false; int err = 0; // Check CPU affinity settings if (!this->cpu_affinity.empty()) { err = set_cpu_affinity(this->cpu_affinity, true /* dryrun */); if (err) { platform::post_early(internal::WARN, "invalid cpu-affinity: %s %s", this->cpu_affinity.c_str(), strerror(err)); failed = true; } } // FIXME: sanity check policy and priority return !failed; } std::ostream& operator<< (std::ostream& s, const schedparam& p) { std::ios_base::fmtflags fmt = s.flags(); s << "" << "{ " << "policy:" << p.policy << ", " << "priority:" << p.priority << ", " << "cpu-affinity:" << p.cpu_affinity << " }"; s.flags(fmt); return s; } } // namespace hogl __HOGL_PRIV_NS_CLOSE__ <|endoftext|>
<commit_before>/** * @file hrectbound_impl.hpp * * Implementation of hyper-rectangle bound policy class. * Template parameter Power is the metric to use; use 2 for Euclidean (L2). * * @experimental */ #ifndef __MLPACK_CORE_TREE_HRECTBOUND_IMPL_HPP #define __MLPACK_CORE_TREE_HRECTBOUND_IMPL_HPP #include <math.h> // In case it has not been included yet. #include "hrectbound.hpp" namespace mlpack { namespace bound { /** * Empty constructor. */ template<int Power, bool TakeRoot> HRectBound<Power, TakeRoot>::HRectBound() : dim(0), bounds(NULL) { /* Nothing to do. */ } /** * Initializes to specified dimensionality with each dimension the empty * set. */ template<int Power, bool TakeRoot> HRectBound<Power, TakeRoot>::HRectBound(const size_t dimension) : dim(dimension), bounds(new math::Range[dim]) { /* Nothing to do. */ } /*** * Copy constructor necessary to prevent memory leaks. */ template<int Power, bool TakeRoot> HRectBound<Power, TakeRoot>::HRectBound(const HRectBound& other) : dim(other.Dim()), bounds(new math::Range[dim]) { // Copy other bounds over. for (size_t i = 0; i < dim; i++) bounds[i] = other[i]; } /*** * Same as the copy constructor. */ template<int Power, bool TakeRoot> HRectBound<Power, TakeRoot>& HRectBound<Power, TakeRoot>::operator=( const HRectBound& other) { if (dim != other.Dim()) { // Reallocation is necessary. if (bounds) delete[] bounds; dim = other.Dim(); bounds = new math::Range[dim]; } // Now copy each of the bound values. for (size_t i = 0; i < dim; i++) bounds[i] = other[i]; return *this; } /** * Destructor: clean up memory. */ template<int Power, bool TakeRoot> HRectBound<Power, TakeRoot>::~HRectBound() { if (bounds) delete[] bounds; } /** * Resets all dimensions to the empty set. */ template<int Power, bool TakeRoot> void HRectBound<Power, TakeRoot>::Clear() { for (size_t i = 0; i < dim; i++) bounds[i] = math::Range(); } /** * Gets the range for a particular dimension. */ template<int Power, bool TakeRoot> inline const math::Range& HRectBound<Power, TakeRoot>::operator[]( const size_t i) const { return bounds[i]; } /** * Sets the range for the given dimension. */ template<int Power, bool TakeRoot> inline math::Range& HRectBound<Power, TakeRoot>::operator[](const size_t i) { return bounds[i]; } /*** * Calculates the centroid of the range, placing it into the given vector. * * @param centroid Vector which the centroid will be written to. */ template<int Power, bool TakeRoot> void HRectBound<Power, TakeRoot>::Centroid(arma::vec& centroid) const { // Set size correctly if necessary. if (!(centroid.n_elem == dim)) centroid.set_size(dim); for (size_t i = 0; i < dim; i++) centroid(i) = bounds[i].Mid(); } /** * Calculates minimum bound-to-point squared distance. */ template<int Power, bool TakeRoot> template<typename VecType> double HRectBound<Power, TakeRoot>::MinDistance(const VecType& point) const { Log::Assert(point.n_elem == dim); double sum = 0; double lower, higher; for (size_t d = 0; d < dim; d++) { lower = bounds[d].Lo() - point[d]; higher = point[d] - bounds[d].Hi(); // Since only one of 'lower' or 'higher' is negative, if we add each's // absolute value to itself and then sum those two, our result is the // nonnegative half of the equation times two; then we raise to power Power. sum += pow((lower + fabs(lower)) + (higher + fabs(higher)), (double) Power); } // Now take the Power'th root (but make sure our result is squared if it needs // to be); then cancel out the constant of 2 (which may have been squared now) // that was introduced earlier. The compiler should optimize out the if // statement entirely. if (TakeRoot) return pow(sum, 1.0 / (double) Power) / 2.0; else return sum / pow(2.0, Power); } /** * Calculates minimum bound-to-bound squared distance. */ template<int Power, bool TakeRoot> double HRectBound<Power, TakeRoot>::MinDistance(const HRectBound& other) const { Log::Assert(dim == other.dim); double sum = 0; const math::Range* mbound = bounds; const math::Range* obound = other.bounds; double lower, higher; for (size_t d = 0; d < dim; d++) { lower = obound->Lo() - mbound->Hi(); higher = mbound->Lo() - obound->Hi(); // We invoke the following: // x + fabs(x) = max(x * 2, 0) // (x * 2)^2 / 4 = x^2 sum += pow((lower + fabs(lower)) + (higher + fabs(higher)), (double) Power); // Move bound pointers. mbound++; obound++; } // The compiler should optimize out this if statement entirely. if (TakeRoot) return pow(sum, 1.0 / (double) Power) / 2.0; else return sum / pow(2.0, Power); } /** * Calculates maximum bound-to-point squared distance. */ template<int Power, bool TakeRoot> template<typename VecType> double HRectBound<Power, TakeRoot>::MaxDistance(const VecType& point) const { double sum = 0; Log::Assert(point.n_elem == dim); for (size_t d = 0; d < dim; d++) { double v = std::max(fabs(point[d] - bounds[d].Lo()), fabs(bounds[d].Hi() - point[d])); sum += pow(v, (double) Power); } // The compiler should optimize out this if statement entirely. if (TakeRoot) return pow(sum, 1.0 / (double) Power); else return sum; } /** * Computes maximum distance. */ template<int Power, bool TakeRoot> double HRectBound<Power, TakeRoot>::MaxDistance(const HRectBound& other) const { double sum = 0; Log::Assert(dim == other.dim); double v; for (size_t d = 0; d < dim; d++) { v = std::max(fabs(other.bounds[d].Hi() - bounds[d].Lo()), fabs(bounds[d].Hi() - other.bounds[d].Lo())); sum += pow(v, (double) Power); // v is non-negative. } // The compiler should optimize out this if statement entirely. if (TakeRoot) return pow(sum, 1.0 / (double) Power); else return sum; } /** * Calculates minimum and maximum bound-to-bound squared distance. */ template<int Power, bool TakeRoot> math::Range HRectBound<Power, TakeRoot>::RangeDistance(const HRectBound& other) const { double loSum = 0; double hiSum = 0; Log::Assert(dim == other.dim); double v1, v2, vLo, vHi; for (size_t d = 0; d < dim; d++) { v1 = other.bounds[d].Lo() - bounds[d].Hi(); v2 = bounds[d].Lo() - other.bounds[d].Hi(); // One of v1 or v2 is negative. if (v1 >= v2) { vHi = -v2; // Make it nonnegative. vLo = (v1 > 0) ? v1 : 0; // Force to be 0 if negative. } else { vHi = -v1; // Make it nonnegative. vLo = (v2 > 0) ? v2 : 0; // Force to be 0 if negative. } loSum += pow(vLo, (double) Power); hiSum += pow(vHi, (double) Power); } if (TakeRoot) return math::Range(pow(loSum, 1.0 / (double) Power), pow(hiSum, 1.0 / (double) Power)); else return math::Range(loSum, hiSum); } /** * Calculates minimum and maximum bound-to-point squared distance. */ template<int Power, bool TakeRoot> template<typename VecType> math::Range HRectBound<Power, TakeRoot>::RangeDistance(const VecType& point) const { double loSum = 0; double hiSum = 0; Log::Assert(point.n_elem == dim); double v1, v2, vLo, vHi; for (size_t d = 0; d < dim; d++) { v1 = bounds[d].Lo() - point[d]; // Negative if point[d] > lo. v2 = point[d] - bounds[d].Hi(); // Negative if point[d] < hi. // One of v1 or v2 (or both) is negative. if (v1 >= 0) // point[d] <= bounds_[d].Lo(). { vHi = -v2; // v2 will be larger but must be negated. vLo = v1; } else // point[d] is between lo and hi, or greater than hi. { if (v2 >= 0) { vHi = -v1; // v1 will be larger, but must be negated. vLo = v2; } else { vHi = -std::min(v1, v2); // Both are negative, but we need the larger. vLo = 0; } } loSum += pow(vLo, (double) Power); hiSum += pow(vHi, (double) Power); } if (TakeRoot) return math::Range(pow(loSum, 1.0 / (double) Power), pow(hiSum, 1.0 / (double) Power)); else return math::Range(loSum, hiSum); } /** * Expands this region to include a new point. */ template<int Power, bool TakeRoot> template<typename MatType> HRectBound<Power, TakeRoot>& HRectBound<Power, TakeRoot>::operator|=( const MatType& data) { Log::Assert(data.n_rows == dim); arma::vec mins = min(data, 1); arma::vec maxs = max(data, 1); for (size_t i = 0; i < dim; i++) bounds[i] |= math::Range(mins[i], maxs[i]); return *this; } /** * Expands this region to encompass another bound. */ template<int Power, bool TakeRoot> HRectBound<Power, TakeRoot>& HRectBound<Power, TakeRoot>::operator|=( const HRectBound& other) { assert(other.dim == dim); for (size_t i = 0; i < dim; i++) bounds[i] |= other.bounds[i]; return *this; } /** * Determines if a point is within this bound. */ template<int Power, bool TakeRoot> template<typename VecType> bool HRectBound<Power, TakeRoot>::Contains(const VecType& point) const { for (size_t i = 0; i < point.n_elem; i++) { if (!bounds[i].Contains(point(i))) return false; } return true; } }; // namespace bound }; // namespace mlpack #endif // __MLPACK_CORE_TREE_HRECTBOUND_IMPL_HPP <commit_msg>Workaround for the case of sparse matrices.<commit_after>/** * @file hrectbound_impl.hpp * * Implementation of hyper-rectangle bound policy class. * Template parameter Power is the metric to use; use 2 for Euclidean (L2). * * @experimental */ #ifndef __MLPACK_CORE_TREE_HRECTBOUND_IMPL_HPP #define __MLPACK_CORE_TREE_HRECTBOUND_IMPL_HPP #include <math.h> // In case it has not been included yet. #include "hrectbound.hpp" namespace mlpack { namespace bound { /** * Empty constructor. */ template<int Power, bool TakeRoot> HRectBound<Power, TakeRoot>::HRectBound() : dim(0), bounds(NULL) { /* Nothing to do. */ } /** * Initializes to specified dimensionality with each dimension the empty * set. */ template<int Power, bool TakeRoot> HRectBound<Power, TakeRoot>::HRectBound(const size_t dimension) : dim(dimension), bounds(new math::Range[dim]) { /* Nothing to do. */ } /*** * Copy constructor necessary to prevent memory leaks. */ template<int Power, bool TakeRoot> HRectBound<Power, TakeRoot>::HRectBound(const HRectBound& other) : dim(other.Dim()), bounds(new math::Range[dim]) { // Copy other bounds over. for (size_t i = 0; i < dim; i++) bounds[i] = other[i]; } /*** * Same as the copy constructor. */ template<int Power, bool TakeRoot> HRectBound<Power, TakeRoot>& HRectBound<Power, TakeRoot>::operator=( const HRectBound& other) { if (dim != other.Dim()) { // Reallocation is necessary. if (bounds) delete[] bounds; dim = other.Dim(); bounds = new math::Range[dim]; } // Now copy each of the bound values. for (size_t i = 0; i < dim; i++) bounds[i] = other[i]; return *this; } /** * Destructor: clean up memory. */ template<int Power, bool TakeRoot> HRectBound<Power, TakeRoot>::~HRectBound() { if (bounds) delete[] bounds; } /** * Resets all dimensions to the empty set. */ template<int Power, bool TakeRoot> void HRectBound<Power, TakeRoot>::Clear() { for (size_t i = 0; i < dim; i++) bounds[i] = math::Range(); } /** * Gets the range for a particular dimension. */ template<int Power, bool TakeRoot> inline const math::Range& HRectBound<Power, TakeRoot>::operator[]( const size_t i) const { return bounds[i]; } /** * Sets the range for the given dimension. */ template<int Power, bool TakeRoot> inline math::Range& HRectBound<Power, TakeRoot>::operator[](const size_t i) { return bounds[i]; } /*** * Calculates the centroid of the range, placing it into the given vector. * * @param centroid Vector which the centroid will be written to. */ template<int Power, bool TakeRoot> void HRectBound<Power, TakeRoot>::Centroid(arma::vec& centroid) const { // Set size correctly if necessary. if (!(centroid.n_elem == dim)) centroid.set_size(dim); for (size_t i = 0; i < dim; i++) centroid(i) = bounds[i].Mid(); } /** * Calculates minimum bound-to-point squared distance. */ template<int Power, bool TakeRoot> template<typename VecType> double HRectBound<Power, TakeRoot>::MinDistance(const VecType& point) const { Log::Assert(point.n_elem == dim); double sum = 0; double lower, higher; for (size_t d = 0; d < dim; d++) { lower = bounds[d].Lo() - point[d]; higher = point[d] - bounds[d].Hi(); // Since only one of 'lower' or 'higher' is negative, if we add each's // absolute value to itself and then sum those two, our result is the // nonnegative half of the equation times two; then we raise to power Power. sum += pow((lower + fabs(lower)) + (higher + fabs(higher)), (double) Power); } // Now take the Power'th root (but make sure our result is squared if it needs // to be); then cancel out the constant of 2 (which may have been squared now) // that was introduced earlier. The compiler should optimize out the if // statement entirely. if (TakeRoot) return pow(sum, 1.0 / (double) Power) / 2.0; else return sum / pow(2.0, Power); } /** * Calculates minimum bound-to-bound squared distance. */ template<int Power, bool TakeRoot> double HRectBound<Power, TakeRoot>::MinDistance(const HRectBound& other) const { Log::Assert(dim == other.dim); double sum = 0; const math::Range* mbound = bounds; const math::Range* obound = other.bounds; double lower, higher; for (size_t d = 0; d < dim; d++) { lower = obound->Lo() - mbound->Hi(); higher = mbound->Lo() - obound->Hi(); // We invoke the following: // x + fabs(x) = max(x * 2, 0) // (x * 2)^2 / 4 = x^2 sum += pow((lower + fabs(lower)) + (higher + fabs(higher)), (double) Power); // Move bound pointers. mbound++; obound++; } // The compiler should optimize out this if statement entirely. if (TakeRoot) return pow(sum, 1.0 / (double) Power) / 2.0; else return sum / pow(2.0, Power); } /** * Calculates maximum bound-to-point squared distance. */ template<int Power, bool TakeRoot> template<typename VecType> double HRectBound<Power, TakeRoot>::MaxDistance(const VecType& point) const { double sum = 0; Log::Assert(point.n_elem == dim); for (size_t d = 0; d < dim; d++) { double v = std::max(fabs(point[d] - bounds[d].Lo()), fabs(bounds[d].Hi() - point[d])); sum += pow(v, (double) Power); } // The compiler should optimize out this if statement entirely. if (TakeRoot) return pow(sum, 1.0 / (double) Power); else return sum; } /** * Computes maximum distance. */ template<int Power, bool TakeRoot> double HRectBound<Power, TakeRoot>::MaxDistance(const HRectBound& other) const { double sum = 0; Log::Assert(dim == other.dim); double v; for (size_t d = 0; d < dim; d++) { v = std::max(fabs(other.bounds[d].Hi() - bounds[d].Lo()), fabs(bounds[d].Hi() - other.bounds[d].Lo())); sum += pow(v, (double) Power); // v is non-negative. } // The compiler should optimize out this if statement entirely. if (TakeRoot) return pow(sum, 1.0 / (double) Power); else return sum; } /** * Calculates minimum and maximum bound-to-bound squared distance. */ template<int Power, bool TakeRoot> math::Range HRectBound<Power, TakeRoot>::RangeDistance(const HRectBound& other) const { double loSum = 0; double hiSum = 0; Log::Assert(dim == other.dim); double v1, v2, vLo, vHi; for (size_t d = 0; d < dim; d++) { v1 = other.bounds[d].Lo() - bounds[d].Hi(); v2 = bounds[d].Lo() - other.bounds[d].Hi(); // One of v1 or v2 is negative. if (v1 >= v2) { vHi = -v2; // Make it nonnegative. vLo = (v1 > 0) ? v1 : 0; // Force to be 0 if negative. } else { vHi = -v1; // Make it nonnegative. vLo = (v2 > 0) ? v2 : 0; // Force to be 0 if negative. } loSum += pow(vLo, (double) Power); hiSum += pow(vHi, (double) Power); } if (TakeRoot) return math::Range(pow(loSum, 1.0 / (double) Power), pow(hiSum, 1.0 / (double) Power)); else return math::Range(loSum, hiSum); } /** * Calculates minimum and maximum bound-to-point squared distance. */ template<int Power, bool TakeRoot> template<typename VecType> math::Range HRectBound<Power, TakeRoot>::RangeDistance(const VecType& point) const { double loSum = 0; double hiSum = 0; Log::Assert(point.n_elem == dim); double v1, v2, vLo, vHi; for (size_t d = 0; d < dim; d++) { v1 = bounds[d].Lo() - point[d]; // Negative if point[d] > lo. v2 = point[d] - bounds[d].Hi(); // Negative if point[d] < hi. // One of v1 or v2 (or both) is negative. if (v1 >= 0) // point[d] <= bounds_[d].Lo(). { vHi = -v2; // v2 will be larger but must be negated. vLo = v1; } else // point[d] is between lo and hi, or greater than hi. { if (v2 >= 0) { vHi = -v1; // v1 will be larger, but must be negated. vLo = v2; } else { vHi = -std::min(v1, v2); // Both are negative, but we need the larger. vLo = 0; } } loSum += pow(vLo, (double) Power); hiSum += pow(vHi, (double) Power); } if (TakeRoot) return math::Range(pow(loSum, 1.0 / (double) Power), pow(hiSum, 1.0 / (double) Power)); else return math::Range(loSum, hiSum); } /** * Expands this region to include a new point. */ template<int Power, bool TakeRoot> template<typename MatType> HRectBound<Power, TakeRoot>& HRectBound<Power, TakeRoot>::operator|=( const MatType& data) { Log::Assert(data.n_rows == dim); arma::vec mins(min(data, 1)); arma::vec maxs(max(data, 1)); for (size_t i = 0; i < dim; i++) bounds[i] |= math::Range(mins[i], maxs[i]); return *this; } /** * Expands this region to encompass another bound. */ template<int Power, bool TakeRoot> HRectBound<Power, TakeRoot>& HRectBound<Power, TakeRoot>::operator|=( const HRectBound& other) { assert(other.dim == dim); for (size_t i = 0; i < dim; i++) bounds[i] |= other.bounds[i]; return *this; } /** * Determines if a point is within this bound. */ template<int Power, bool TakeRoot> template<typename VecType> bool HRectBound<Power, TakeRoot>::Contains(const VecType& point) const { for (size_t i = 0; i < point.n_elem; i++) { if (!bounds[i].Contains(point(i))) return false; } return true; } }; // namespace bound }; // namespace mlpack #endif // __MLPACK_CORE_TREE_HRECTBOUND_IMPL_HPP <|endoftext|>
<commit_before>/** * @file MaximalInputs.cpp * @author Ngap Wei Tham * * Test the MaximalInputs and ColumnsToBlocks functions. */ #include <mlpack/core.hpp> #include <mlpack/core/math/columns_to_blocks.hpp> #include <mlpack/methods/sparse_autoencoder/maximal_inputs.hpp> #include <boost/test/unit_test.hpp> #include "old_boost_test_definitions.hpp" using namespace mlpack; arma::mat CreateMaximalInput() { arma::mat w1(2, 4); w1<<0<<1<<2<<3<<arma::endr <<4<<5<<6<<7; arma::mat input(5,5); input.submat(0, 0, 1, 3) = w1; arma::mat maximalInputs; mlpack::nn::MaximalInputs(input, maximalInputs); return maximalInputs; } void TestResults(arma::mat const &actualResult, arma::mat const &expectResult) { BOOST_REQUIRE(expectResult.n_rows == actualResult.n_rows && expectResult.n_cols == actualResult.n_cols); for(size_t i = 0; i != expectResult.n_elem; ++i) { BOOST_REQUIRE_CLOSE(expectResult[i], actualResult[i], 1e-2); } } BOOST_AUTO_TEST_SUITE(MaximalInputsTest); BOOST_AUTO_TEST_CASE(ColumnToBlocksEvaluate) { arma::mat output; mlpack::math::ColumnsToBlocks ctb(1,2); ctb.Transform(CreateMaximalInput(), output); arma::mat matlabResults; matlabResults<<-1<<-1<<-1<<-1<<-1<<-1<<-1<<arma::endr <<-1<<-1<<-0.42857<<-1<<0.14286<<0.71429<<-1<<arma::endr <<-1<<-0.71429<<-0.14286<<-1.00000<<0.42857<<1<<-1<<arma::endr <<-1<<-1<<-1<<-1<<-1<<-1<<-1; TestResults(output, matlabResults); } BOOST_AUTO_TEST_CASE(ColumnToBlocksChangeBlockSize) { arma::mat output; mlpack::math::ColumnsToBlocks ctb(1,2); ctb.BlockWidth(4); ctb.BlockHeight(1); ctb.BufValue(-3); ctb.Transform(CreateMaximalInput(), output); arma::mat matlabResults; matlabResults<<-3<<-3<<-3<<-3<<-3 <<-3<<-3<<-3<<-3<<-3<<-3<<arma::endr <<-3<<-1<<-0.71429<<-0.42857<<-0.14286 <<-3<<0.14286<<0.42857<<0.71429<<1<<-3<<arma::endr <<-3<<-3<<-3<<-3<<-3<<-3<<-3<<-3<<-3<<-3<<-3<<arma::endr; TestResults(output, matlabResults); } BOOST_AUTO_TEST_SUITE_END(); <commit_msg>Minor style fixes.<commit_after>/** * @file maximal_inputs_test.cpp * @author Ngap Wei Tham * * Test the MaximalInputs and ColumnsToBlocks functions. */ #include <mlpack/core.hpp> #include <mlpack/core/math/columns_to_blocks.hpp> #include <mlpack/methods/sparse_autoencoder/maximal_inputs.hpp> #include <boost/test/unit_test.hpp> #include "old_boost_test_definitions.hpp" using namespace mlpack; arma::mat CreateMaximalInput() { arma::mat w1(2, 4); w1 << 0 << 1 << 2 << 3 << arma::endr << 4 << 5 << 6 << 7; arma::mat input(5, 5); input.submat(0, 0, 1, 3) = w1; arma::mat maximalInputs; mlpack::nn::MaximalInputs(input, maximalInputs); return maximalInputs; } void TestResults(const arma::mat&actualResult, const arma::mat& expectResult) { BOOST_REQUIRE_EQUAL(expectResult.n_rows == actualResult.n_rows); BOOST_REQUIRE_EQUAL(expectResult.n_cols == actualResult.n_cols); for(size_t i = 0; i != expectResult.n_elem; ++i) { BOOST_REQUIRE_CLOSE(expectResult[i], actualResult[i], 1e-2); } } BOOST_AUTO_TEST_SUITE(MaximalInputsTest); BOOST_AUTO_TEST_CASE(ColumnToBlocksEvaluate) { arma::mat output; mlpack::math::ColumnsToBlocks ctb(1, 2); ctb.Transform(CreateMaximalInput(), output); arma::mat matlabResults; matlabResults << -1 << -1 << -1 << -1 << -1 << -1 << -1 << arma::endr << -1 << -1<< -0.42857 << -1 << 0.14286 << 0.71429 << -1 << arma::endr << -1 << -0.71429 << -0.14286 << -1 << 0.42857 << 1 << -1 << arma::endr << -1 << -1 << -1 << -1 << -1 << -1 << -1; TestResults(output, matlabResults); } BOOST_AUTO_TEST_CASE(ColumnToBlocksChangeBlockSize) { arma::mat output; mlpack::math::ColumnsToBlocks ctb(1, 2); ctb.BlockWidth(4); ctb.BlockHeight(1); ctb.BufValue(-3); ctb.Transform(CreateMaximalInput(), output); arma::mat matlabResults; matlabResults<< -3 << -3 << -3 << -3 << -3 << -3 << -3 << -3 << -3 << -3 << -3 << arma::endr << -3 << -1 << -0.71429 << -0.42857 << -0.14286 << -3 << 0.14286 << 0.42857 << 0.71429 << 1 << -3 << arma::endr << -3 << -3 << -3 << -3 << -3 << -3 << -3 << -3 << -3 << -3 << -3 << arma::endr; TestResults(output, matlabResults); } BOOST_AUTO_TEST_SUITE_END(); <|endoftext|>
<commit_before>/* * Copyright (c) 2003-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Nathan Binkert * Gabe Black */ #ifndef __FAULTS_HH__ #define __FAULTS_HH__ #include "base/refcnt.hh" #include "sim/stats.hh" #include "config/full_system.hh" class ThreadContext; class FaultBase; typedef RefCountingPtr<FaultBase> Fault; typedef const char * FaultName; typedef Stats::Scalar FaultStat; // Each class has it's name statically define in _name, // and has a virtual function to access it's name. // The function is necessary because otherwise, all objects // which are being accessed cast as a FaultBase * (namely // all faults returned using the Fault type) will use the // generic FaultBase name. class FaultBase : public RefCounted { public: virtual FaultName name() const = 0; virtual void invoke(ThreadContext * tc); // template<typename T> // bool isA() {return dynamic_cast<T *>(this);} virtual bool isMachineCheckFault() const {return false;} virtual bool isAlignmentFault() const {return false;} }; FaultBase * const NoFault = 0; class UnimpFault : public FaultBase { private: std::string panicStr; public: UnimpFault(std::string _str) : panicStr(_str) { } FaultName name() const {return "Unimplemented simulator feature";} void invoke(ThreadContext * tc); }; #if !FULL_SYSTEM class GenericPageTableFault : public FaultBase { private: Addr vaddr; public: FaultName name() const {return "Generic page table fault";} GenericPageTableFault(Addr va) : vaddr(va) {} void invoke(ThreadContext * tc); }; class GenericAlignmentFault : public FaultBase { private: Addr vaddr; public: FaultName name() const {return "Generic alignment fault";} GenericAlignmentFault(Addr va) : vaddr(va) {} void invoke(ThreadContext * tc); }; #endif #endif // __FAULTS_HH__ <commit_msg>Faults: Get rid of some commented out code in sim/faults.hh.<commit_after>/* * Copyright (c) 2003-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Nathan Binkert * Gabe Black */ #ifndef __FAULTS_HH__ #define __FAULTS_HH__ #include "base/refcnt.hh" #include "sim/stats.hh" #include "config/full_system.hh" class ThreadContext; class FaultBase; typedef RefCountingPtr<FaultBase> Fault; typedef const char * FaultName; typedef Stats::Scalar FaultStat; // Each class has it's name statically define in _name, // and has a virtual function to access it's name. // The function is necessary because otherwise, all objects // which are being accessed cast as a FaultBase * (namely // all faults returned using the Fault type) will use the // generic FaultBase name. class FaultBase : public RefCounted { public: virtual FaultName name() const = 0; virtual void invoke(ThreadContext * tc); virtual bool isMachineCheckFault() const {return false;} virtual bool isAlignmentFault() const {return false;} }; FaultBase * const NoFault = 0; class UnimpFault : public FaultBase { private: std::string panicStr; public: UnimpFault(std::string _str) : panicStr(_str) { } FaultName name() const {return "Unimplemented simulator feature";} void invoke(ThreadContext * tc); }; #if !FULL_SYSTEM class GenericPageTableFault : public FaultBase { private: Addr vaddr; public: FaultName name() const {return "Generic page table fault";} GenericPageTableFault(Addr va) : vaddr(va) {} void invoke(ThreadContext * tc); }; class GenericAlignmentFault : public FaultBase { private: Addr vaddr; public: FaultName name() const {return "Generic alignment fault";} GenericAlignmentFault(Addr va) : vaddr(va) {} void invoke(ThreadContext * tc); }; #endif #endif // __FAULTS_HH__ <|endoftext|>
<commit_before>// (C) Robert Osfield, Feb 2004. // GPL'd. #include <osg/ImageStream> #include <osg/Notify> #include <osg/Geode> #include <osg/GL> #include <osg/Timer> #include <osgDB/Registry> #include <osgDB/FileNameUtils> #include <osgDB/FileUtils> #include <xine.h> #include <xine/xineutils.h> #include <xine/video_out.h> #include "video_out_rgb.h" namespace osgXine { class XineImageStream : public osg::ImageStream { public: XineImageStream(): _xine(0), _vo(0), _ao(0), _visual(0), _stream(0), _event_queue(0), _ready(false) {} /** Copy constructor using CopyOp to manage deep vs shallow copy. */ XineImageStream(const XineImageStream& image,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY): ImageStream(image,copyop) {} META_Object(osgXine,XineImageStream); bool open(xine_t* xine, const std::string& filename) { if (filename==getFileName()) return true; _xine = xine; // create visual rgbout_visual_info_t* visual = new rgbout_visual_info_t; visual->levels = PXLEVEL_ALL; visual->format = PX_RGB32; visual->user_data = this; visual->callback = my_render_frame; // set up video driver _vo = xine_open_video_driver(_xine, "rgb", XINE_VISUAL_TYPE_RGBOUT, (void*)visual); // set up audio driver char* audio_driver = getenv("OSG_XINE_AUDIO_DRIVER"); _ao = audio_driver ? xine_open_audio_driver(_xine, audio_driver, NULL) : xine_open_audio_driver(_xine, "auto", NULL); if (!_vo) { osg::notify(osg::NOTICE)<<"Failed to create video driver"<<std::endl; return false; } // set up stream _stream = xine_stream_new(_xine, _ao, _vo); _event_queue = xine_event_new_queue(_stream); xine_event_create_listener_thread(_event_queue, event_listener, this); int result = xine_open(_stream, filename.c_str()); if (result==0) { osg::notify(osg::NOTICE)<<"Error: could not ready movie file."<<std::endl; close(); } _ready = false; // play(); return true; } virtual void play() { if (_status!=PLAYING && _stream) { if (_status==PAUSED) { xine_set_param (_stream, XINE_PARAM_SPEED, XINE_SPEED_NORMAL); } else { osg::notify(osg::INFO)<<"XineImageStream::play()"<<std::endl; if (xine_play(_stream, 0, 0)) { while (!_ready) { osg::notify(osg::INFO)<<" waiting..."<<std::endl; usleep(10000); } _status=PLAYING; } else { osg::notify(osg::NOTICE)<<"Error!!!"<<std::endl; } } } } virtual void pause() { if (_status==PAUSED || _status==INVALID) return; _status=PAUSED; if (_stream) { xine_set_param (_stream, XINE_PARAM_SPEED, XINE_SPEED_PAUSE); } } virtual void rewind() { if (_status==INVALID) return; _status=REWINDING; if (_stream) { osg::notify(osg::WARN)<<"Warning::XineImageStream::rewind() - rewind disabled at present."<<std::endl; // xine_trick_mode(_stream,XINE_TRICK_MODE_FAST_REWIND,0); } } virtual void quit(bool /*waitForThreadToExit*/ = true) { close(); } static void my_render_frame(uint32_t width, uint32_t height, void* data, void* userData) { XineImageStream* imageStream = (XineImageStream*) userData; GLenum pixelFormat = GL_BGRA; #if 0 if (!imageStream->_ready) { imageStream->allocateImage(width,height,1,pixelFormat,GL_UNSIGNED_BYTE,1); imageStream->setInternalTextureFormat(GL_RGBA); } osg::Timer_t start_tick = osg::Timer::instance()->tick(); memcpy(imageStream->data(),data,imageStream->getTotalSizeInBytes()); osg::notify(osg::NOTICE)<<"image memcpy size="<<imageStream->getTotalSizeInBytes()<<" time="<<osg::Timer::instance()->delta_m(start_tick,osg::Timer::instance()->tick())<<"ms"<<std::endl; imageStream->dirty(); #else imageStream->setImage(width,height,1, GL_RGB, pixelFormat,GL_UNSIGNED_BYTE, (unsigned char *)data, osg::Image::NO_DELETE, 1); #endif imageStream->_ready = true; } xine_t* _xine; xine_video_port_t* _vo; xine_audio_port_t* _ao; rgbout_visual_info_t* _visual; xine_stream_t* _stream; xine_event_queue_t* _event_queue; bool _ready; protected: virtual ~XineImageStream() { osg::notify(osg::INFO)<<"Killing XineImageStream"<<std::endl; close(); osg::notify(osg::INFO)<<"Closed XineImageStream"<<std::endl; } void close() { osg::notify(osg::INFO)<<"XineImageStream::close()"<<std::endl; if (_stream) { osg::notify(osg::INFO)<<" Closing stream"<<std::endl; xine_close(_stream); osg::notify(osg::INFO)<<" Disposing stream"<<std::endl; xine_dispose(_stream); _stream = 0; } if (_event_queue) { _event_queue = 0; } if (_ao) { osg::notify(osg::INFO)<<" Closing audio driver"<<std::endl; xine_close_audio_driver(_xine, _ao); _ao = 0; } if (_vo) { osg::notify(osg::INFO)<<" Closing video driver"<<std::endl; xine_close_video_driver(_xine, _vo); _vo = 0; } osg::notify(osg::INFO)<<"closed XineImageStream "<<std::endl; } static void event_listener(void *user_data, const xine_event_t *event) { XineImageStream* xis = reinterpret_cast<XineImageStream*>(user_data); switch(event->type) { case XINE_EVENT_UI_PLAYBACK_FINISHED: if (xis->getLoopingMode()==LOOPING) { //rewind(); xine_play(xis->_stream, 0, 0); } break; } } }; } class ReaderWriterXine : public osgDB::ReaderWriter { public: ReaderWriterXine() { _xine = xine_new(); const char* user_home = xine_get_homedir(); if(user_home) { char* cfgfile = NULL; asprintf(&(cfgfile), "%s/.xine/config", user_home); xine_config_load(_xine, cfgfile); } xine_init(_xine); register_rgbout_plugin(_xine); } virtual ~ReaderWriterXine() { osg::notify(osg::INFO)<<"~ReaderWriterXine()"<<std::endl; if (_xine) xine_exit(_xine); _xine = NULL; } virtual const char* className() const { return "Xine ImageStream Reader"; } virtual bool acceptsExtension(const std::string& extension) const { return osgDB::equalCaseInsensitive(extension,"mpg") || osgDB::equalCaseInsensitive(extension,"mpv") || osgDB::equalCaseInsensitive(extension,"db") || osgDB::equalCaseInsensitive(extension,"mov") || osgDB::equalCaseInsensitive(extension,"avi") || osgDB::equalCaseInsensitive(extension,"wmv") || osgDB::equalCaseInsensitive(extension,"xine"); } virtual ReadResult readImage(const std::string& file, const osgDB::ReaderWriter::Options* options) const { std::string ext = osgDB::getLowerCaseFileExtension(file); if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED; std::string fileName; if (ext=="xine") { fileName = osgDB::getNameLessExtension(file); osg::notify(osg::NOTICE)<<"Xine stipped filename = "<<fileName; } else { fileName = osgDB::findDataFile( file, options ); if (fileName.empty()) return ReadResult::FILE_NOT_FOUND; } osg::notify(osg::INFO)<<"ReaderWriterXine::readImage "<< file<< std::endl; osg::ref_ptr<osgXine::XineImageStream> imageStream = new osgXine::XineImageStream(); if (!imageStream->open(_xine, fileName)) return ReadResult::FILE_NOT_HANDLED; return imageStream.release(); } protected: xine_t* _xine; }; // now register with Registry to instantiate the above // reader/writer. osgDB::RegisterReaderWriterProxy<ReaderWriterXine> g_readerWriter_Xine_Proxy; <commit_msg>Improved handling of unsupported file formats.<commit_after>// (C) Robert Osfield, Feb 2004. // GPL'd. #include <osg/ImageStream> #include <osg/Notify> #include <osg/Geode> #include <osg/GL> #include <osg/Timer> #include <osgDB/Registry> #include <osgDB/FileNameUtils> #include <osgDB/FileUtils> #include <xine.h> #include <xine/xineutils.h> #include <xine/video_out.h> #include "video_out_rgb.h" namespace osgXine { class XineImageStream : public osg::ImageStream { public: XineImageStream(): _xine(0), _vo(0), _ao(0), _visual(0), _stream(0), _event_queue(0), _ready(false) {} /** Copy constructor using CopyOp to manage deep vs shallow copy. */ XineImageStream(const XineImageStream& image,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY): ImageStream(image,copyop) {} META_Object(osgXine,XineImageStream); bool open(xine_t* xine, const std::string& filename) { if (filename==getFileName()) return true; _xine = xine; // create visual rgbout_visual_info_t* visual = new rgbout_visual_info_t; visual->levels = PXLEVEL_ALL; visual->format = PX_RGB32; visual->user_data = this; visual->callback = my_render_frame; // set up video driver _vo = xine_open_video_driver(_xine, "rgb", XINE_VISUAL_TYPE_RGBOUT, (void*)visual); // set up audio driver char* audio_driver = getenv("OSG_XINE_AUDIO_DRIVER"); _ao = audio_driver ? xine_open_audio_driver(_xine, audio_driver, NULL) : xine_open_audio_driver(_xine, "auto", NULL); if (!_vo) { osg::notify(osg::NOTICE)<<"XineImageStream::open() : Failed to create video driver"<<std::endl; return false; } // set up stream _stream = xine_stream_new(_xine, _ao, _vo); _event_queue = xine_event_new_queue(_stream); xine_event_create_listener_thread(_event_queue, event_listener, this); int result = xine_open(_stream, filename.c_str()); if (result==0) { osg::notify(osg::INFO)<<"XineImageStream::open() : Could not ready movie file."<<std::endl; close(); return false; } _ready = false; // play(); return true; } virtual void play() { if (_status!=PLAYING && _stream) { if (_status==PAUSED) { xine_set_param (_stream, XINE_PARAM_SPEED, XINE_SPEED_NORMAL); } else { osg::notify(osg::INFO)<<"XineImageStream::play()"<<std::endl; if (xine_play(_stream, 0, 0)) { while (!_ready) { osg::notify(osg::INFO)<<" waiting..."<<std::endl; usleep(10000); } _status=PLAYING; } else { osg::notify(osg::NOTICE)<<"Error!!!"<<std::endl; } } } } virtual void pause() { if (_status==PAUSED || _status==INVALID) return; _status=PAUSED; if (_stream) { xine_set_param (_stream, XINE_PARAM_SPEED, XINE_SPEED_PAUSE); } } virtual void rewind() { if (_status==INVALID) return; _status=REWINDING; if (_stream) { osg::notify(osg::WARN)<<"Warning::XineImageStream::rewind() - rewind disabled at present."<<std::endl; // xine_trick_mode(_stream,XINE_TRICK_MODE_FAST_REWIND,0); } } virtual void quit(bool /*waitForThreadToExit*/ = true) { close(); } static void my_render_frame(uint32_t width, uint32_t height, void* data, void* userData) { XineImageStream* imageStream = (XineImageStream*) userData; GLenum pixelFormat = GL_BGRA; #if 0 if (!imageStream->_ready) { imageStream->allocateImage(width,height,1,pixelFormat,GL_UNSIGNED_BYTE,1); imageStream->setInternalTextureFormat(GL_RGBA); } osg::Timer_t start_tick = osg::Timer::instance()->tick(); memcpy(imageStream->data(),data,imageStream->getTotalSizeInBytes()); osg::notify(osg::NOTICE)<<"image memcpy size="<<imageStream->getTotalSizeInBytes()<<" time="<<osg::Timer::instance()->delta_m(start_tick,osg::Timer::instance()->tick())<<"ms"<<std::endl; imageStream->dirty(); #else imageStream->setImage(width,height,1, GL_RGB, pixelFormat,GL_UNSIGNED_BYTE, (unsigned char *)data, osg::Image::NO_DELETE, 1); #endif imageStream->_ready = true; } xine_t* _xine; xine_video_port_t* _vo; xine_audio_port_t* _ao; rgbout_visual_info_t* _visual; xine_stream_t* _stream; xine_event_queue_t* _event_queue; bool _ready; protected: virtual ~XineImageStream() { osg::notify(osg::INFO)<<"Killing XineImageStream"<<std::endl; close(); osg::notify(osg::INFO)<<"Closed XineImageStream"<<std::endl; } void close() { osg::notify(osg::INFO)<<"XineImageStream::close()"<<std::endl; if (_stream) { osg::notify(osg::INFO)<<" Closing stream"<<std::endl; xine_close(_stream); osg::notify(osg::INFO)<<" Disposing stream"<<std::endl; xine_dispose(_stream); _stream = 0; } if (_event_queue) { _event_queue = 0; } if (_ao) { osg::notify(osg::INFO)<<" Closing audio driver"<<std::endl; xine_close_audio_driver(_xine, _ao); _ao = 0; } if (_vo) { osg::notify(osg::INFO)<<" Closing video driver"<<std::endl; xine_close_video_driver(_xine, _vo); _vo = 0; } osg::notify(osg::INFO)<<"closed XineImageStream "<<std::endl; } static void event_listener(void *user_data, const xine_event_t *event) { XineImageStream* xis = reinterpret_cast<XineImageStream*>(user_data); switch(event->type) { case XINE_EVENT_UI_PLAYBACK_FINISHED: if (xis->getLoopingMode()==LOOPING) { //rewind(); xine_play(xis->_stream, 0, 0); } break; } } }; } class ReaderWriterXine : public osgDB::ReaderWriter { public: ReaderWriterXine() { _xine = xine_new(); const char* user_home = xine_get_homedir(); if(user_home) { char* cfgfile = NULL; asprintf(&(cfgfile), "%s/.xine/config", user_home); xine_config_load(_xine, cfgfile); } xine_init(_xine); register_rgbout_plugin(_xine); } virtual ~ReaderWriterXine() { osg::notify(osg::INFO)<<"~ReaderWriterXine()"<<std::endl; if (_xine) xine_exit(_xine); _xine = NULL; } virtual const char* className() const { return "Xine ImageStream Reader"; } virtual bool acceptsExtension(const std::string& extension) const { return osgDB::equalCaseInsensitive(extension,"mpg") || osgDB::equalCaseInsensitive(extension,"mpv") || osgDB::equalCaseInsensitive(extension,"db") || osgDB::equalCaseInsensitive(extension,"mov") || osgDB::equalCaseInsensitive(extension,"avi") || osgDB::equalCaseInsensitive(extension,"wmv") || osgDB::equalCaseInsensitive(extension,"xine"); } virtual ReadResult readImage(const std::string& file, const osgDB::ReaderWriter::Options* options) const { std::string ext = osgDB::getLowerCaseFileExtension(file); if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED; std::string fileName; if (ext=="xine") { fileName = osgDB::getNameLessExtension(file); osg::notify(osg::NOTICE)<<"Xine stipped filename = "<<fileName; } else { fileName = osgDB::findDataFile( file, options ); if (fileName.empty()) return ReadResult::FILE_NOT_FOUND; } osg::notify(osg::INFO)<<"ReaderWriterXine::readImage "<< file<< std::endl; osg::ref_ptr<osgXine::XineImageStream> imageStream = new osgXine::XineImageStream(); if (!imageStream->open(_xine, fileName)) return ReadResult::FILE_NOT_HANDLED; return imageStream.release(); } protected: xine_t* _xine; }; // now register with Registry to instantiate the above // reader/writer. osgDB::RegisterReaderWriterProxy<ReaderWriterXine> g_readerWriter_Xine_Proxy; <|endoftext|>
<commit_before>/** Copyright 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Roland Olbricht et al. * * This file is part of Overpass_API. * * Overpass_API is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Overpass_API is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Overpass_API. If not, see <http://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H #include <config.h> #undef VERSION #endif #include "../../expat/expat_justparse_interface.h" #include "../../template_db/dispatcher.h" #include "../frontend/console_output.h" #include "../frontend/user_interface.h" #include "../frontend/web_output.h" #include "../osm-backend/clone_database.h" #include "../statements/osm_script.h" #include "../statements/statement.h" #include "resource_manager.h" #include "scripting_core.h" #include <errno.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/resource.h> #include <sys/select.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <vector> int main(int argc, char *argv[]) { // read command line arguments std::string db_dir = ""; std::string clone_db_dir = ""; uint log_level = Error_Output::ASSISTING; Debug_Level debug_level = parser_execute; Clone_Settings clone_settings; int area_level = 0; bool respect_timeout = true; std::string xml_raw; int argpos = 1; while (argpos < argc) { if (!(strncmp(argv[argpos], "--db-dir=", 9))) { db_dir = ((std::string)argv[argpos]).substr(9); if ((!db_dir.empty()) && (db_dir[db_dir.size()-1] != '/')) db_dir += '/'; } else if (!(strcmp(argv[argpos], "--quiet"))) log_level = Error_Output::QUIET; else if (!(strcmp(argv[argpos], "--concise"))) log_level = Error_Output::CONCISE; else if (!(strcmp(argv[argpos], "--progress"))) log_level = Error_Output::PROGRESS; else if (!(strcmp(argv[argpos], "--verbose"))) log_level = Error_Output::VERBOSE; else if (!(strcmp(argv[argpos], "--rules"))) { area_level = 2; respect_timeout = false; } #ifdef HAVE_OVERPASS_XML else if (!(strcmp(argv[argpos], "--dump-xml"))) debug_level = parser_dump_xml; #endif else if (!(strcmp(argv[argpos], "--dump-pretty-ql"))) debug_level = parser_dump_pretty_map_ql; else if (!(strcmp(argv[argpos], "--dump-compact-ql"))) debug_level = parser_dump_compact_map_ql; else if (!(strcmp(argv[argpos], "--dump-bbox-ql"))) debug_level = parser_dump_bbox_map_ql; else if (!(strncmp(argv[argpos], "--clone=", 8))) { clone_db_dir = ((std::string)argv[argpos]).substr(8); if ((!clone_db_dir.empty()) && (clone_db_dir[clone_db_dir.size()-1] != '/')) clone_db_dir += '/'; } else if (!(strncmp(argv[argpos], "--request=", 10))) xml_raw = ((std::string)argv[argpos]).substr(10); else if (!(strncmp(argv[argpos], "--clone-compression=", 20))) { if (std::string(argv[argpos]).substr(20) == "no") clone_settings.compression_method = Block_Compression::NO_COMPRESSION; else if (std::string(argv[argpos]).substr(20) == "gz") clone_settings.compression_method = Block_Compression::ZLIB_COMPRESSION; #ifdef HAVE_LZ4 else if (std::string(argv[argpos]).substr(20) == "lz4") clone_settings.compression_method = Block_Compression::LZ4_COMPRESSION; #endif else { #ifdef HAVE_LZ4 std::cerr<<"For --clone-compression, please use \"no\", \"gz\", or \"lz4\" as value.\n"; #else std::cerr<<"For --clone-compression, please use \"no\" or \"gz\" as value.\n"; #endif return 0; } } else if (!(strncmp(argv[argpos], "--clone-map-compression=", 24))) { if (std::string(argv[argpos]).substr(24) == "no") clone_settings.map_compression_method = Block_Compression::NO_COMPRESSION; else if (std::string(argv[argpos]).substr(24) == "gz") clone_settings.map_compression_method = Block_Compression::ZLIB_COMPRESSION; #ifdef HAVE_LZ4 else if (std::string(argv[argpos]).substr(24) == "lz4") clone_settings.map_compression_method = Block_Compression::LZ4_COMPRESSION; #endif else { #ifdef HAVE_LZ4 std::cerr<<"For --clone-map-compression, please use \"no\", \"gz\", or \"lz4\" as value.\n"; #else std::cerr<<"For --clone-map-compression, please use \"no\" or \"gz\" as value.\n"; #endif return 0; } } else if (!(strncmp(argv[argpos], "--clone-parallel=", 17))) { clone_settings.parallel_processes = atoi(std::string(argv[argpos]).substr(17).c_str()); } else if (!(strcmp(argv[argpos], "--version"))) { std::cout<<"Overpass API version "<<basic_settings().version<<" "<<basic_settings().source_hash<<"\n"; return 0; } else { std::cout<<"Unknown argument: "<<argv[argpos]<<"\n\n" "Accepted arguments are:\n" " --db-dir=$DB_DIR: The directory where the database resides. If you set this parameter\n" " then osm3s_query will read from the database without using the dispatcher management.\n" #ifdef HAVE_OVERPASS_XML " --dump-xml: Don't execute the query but only dump the query in XML format.\n" #endif " --dump-pretty-ql: Don't execute the query but only dump the query in pretty QL format.\n" " --dump-compact-ql: Don't execute the query but only dump the query in compact QL format.\n" " --dump-bbox-ql: Don't execute the query but only dump the query in a suitable form\n" " for an OpenLayers slippy map.\n" " --clone=$TARGET_DIR: Write a consistent copy of the entire database to the given $TARGET_DIR.\n" " --clone-compression=$METHOD: Use a specific compression method $METHOD for clone bin files\n" " --clone-map-compression=$METHOD: Use a specific compression method $METHOD for clone map files\n" " --clone-parallel=n: Number of parallel threads used for clone generation\n" " --rules: Ignore all time limits and allow area creation by this query.\n" " --request=$QL: Use $QL instead of standard input as the request text.\n" " --quiet: Don't print anything on stderr.\n" " --concise: Print concise information on stderr.\n" " --progress: Print also progress information on stderr.\n" " --verbose: Print everything that happens on stderr.\n" " --version: Print version and exit.\n"; return 0; } ++argpos; } Console_Output error_output{log_level}; Statement::set_error_output(&error_output); // connect to dispatcher and get database dir try { Parsed_Query global_settings; if (!clone_db_dir.empty()) { // open read transaction and log this. area_level = determine_area_level(&error_output, area_level); Dispatcher_Stub dispatcher(db_dir, &error_output, "-- clone database --", get_uses_meta_data(), area_level, 24*60*60, 1024*1024*1024, global_settings); copy_file(dispatcher.resource_manager().get_transaction()->get_db_dir() + "/replicate_id", clone_db_dir + "/replicate_id"); clone_database(*dispatcher.resource_manager().get_transaction(), clone_db_dir, clone_settings); return 0; } if (xml_raw.empty()) xml_raw = get_xml_console(&error_output); if (error_output.display_encoding_errors()) return 0; Statement::Factory stmt_factory(global_settings); if (!parse_and_validate(stmt_factory, global_settings, xml_raw, &error_output, debug_level)) return 0; if (debug_level != parser_execute) return 0; Osm_Script_Statement* osm_script = 0; if (!get_statement_stack()->empty()) osm_script = dynamic_cast< Osm_Script_Statement* >(get_statement_stack()->front()); uint32 max_allowed_time = 0; uint64 max_allowed_space = 0; if (osm_script) { max_allowed_time = osm_script->get_max_allowed_time(); max_allowed_space = osm_script->get_max_allowed_space(); } else { Osm_Script_Statement temp(0, std::map< std::string, std::string >(), global_settings); max_allowed_time = temp.get_max_allowed_time(); max_allowed_space = temp.get_max_allowed_space(); } // Allow rules to run for unlimited time if (!respect_timeout) max_allowed_time = 0; if (error_output) error_output->runtime_remark( "Timeout is " + to_string(max_allowed_time) + " and maxsize is " + to_string(max_allowed_space) + "."); // open read transaction and log this. area_level = determine_area_level(&error_output, area_level); Dispatcher_Stub dispatcher(db_dir, &error_output, xml_raw, get_uses_meta_data(), area_level, max_allowed_time, max_allowed_space, global_settings); if (osm_script && osm_script->get_desired_timestamp()) dispatcher.resource_manager().set_desired_timestamp(osm_script->get_desired_timestamp()); Web_Output web_output(log_level); web_output.set_output_handler(global_settings.get_output_handler()); web_output.write_payload_header("", dispatcher.get_timestamp(), area_level > 0 ? dispatcher.get_area_timestamp() : "", false); dispatcher.resource_manager().start_cpu_timer(0); for (std::vector< Statement* >::const_iterator it(get_statement_stack()->begin()); it != get_statement_stack()->end(); ++it) (*it)->execute(dispatcher.resource_manager()); dispatcher.resource_manager().stop_cpu_timer(0); web_output.write_footer(); return 0; } catch (const Rate_limited_Error& e) { error_output.runtime_error(e.what()); return 1; } catch (const Timeout_Error& e) { error_output.runtime_error(e.what()); return 1; } catch (const File_Error &e) { if (e.origin != "Dispatcher_Stub::Dispatcher_Stub::1") { std::ostringstream temp; if (e.origin == "Dispatcher_Client::1") temp<<"The dispatcher (i.e. the database management system) is turned off."; else if (e.error_number == 0) temp<<"open64: "<<e.filename<<' '<<e.origin; else temp<<"open64: "<<e.error_number<<' '<<strerror(e.error_number)<<' '<<e.filename<<' '<<e.origin; error_output.runtime_error(temp.str()); } return 1; } catch (const Resource_Error &e) { std::ostringstream temp; if (e.timed_out) temp<<"Query timed out in \""<<e.stmt_name<<"\" at line "<<e.line_number <<" after "<<e.runtime<<" seconds."; else temp<<"Query run out of memory in \""<<e.stmt_name<<"\" at line " <<e.line_number<<" using about "<<e.size/(1024*1024)<<" MB of RAM."; error_output.runtime_error(temp.str()); return 2; } catch (const Context_Error &e) { error_output.runtime_error("Context error: " + e.message); return 3; } catch (const Exit_Error &e) { return 4; } catch(const std::bad_alloc& e) { rlimit limit; getrlimit(RLIMIT_AS, &limit); std::ostringstream temp; temp<<"Query run out of memory using about "<<limit.rlim_cur/(1024*1024)<<" MB of RAM."; error_output.runtime_error(temp.str()); return 5; } catch(const std::exception& e) { error_output.runtime_error(std::string("Query failed with the exception: ") + e.what()); return 6; } } <commit_msg>Fix syntax error<commit_after>/** Copyright 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Roland Olbricht et al. * * This file is part of Overpass_API. * * Overpass_API is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Overpass_API is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Overpass_API. If not, see <http://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H #include <config.h> #undef VERSION #endif #include "../../expat/expat_justparse_interface.h" #include "../../template_db/dispatcher.h" #include "../frontend/console_output.h" #include "../frontend/user_interface.h" #include "../frontend/web_output.h" #include "../osm-backend/clone_database.h" #include "../statements/osm_script.h" #include "../statements/statement.h" #include "resource_manager.h" #include "scripting_core.h" #include <errno.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/resource.h> #include <sys/select.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <vector> int main(int argc, char *argv[]) { // read command line arguments std::string db_dir = ""; std::string clone_db_dir = ""; uint log_level = Error_Output::ASSISTING; Debug_Level debug_level = parser_execute; Clone_Settings clone_settings; int area_level = 0; bool respect_timeout = true; std::string xml_raw; int argpos = 1; while (argpos < argc) { if (!(strncmp(argv[argpos], "--db-dir=", 9))) { db_dir = ((std::string)argv[argpos]).substr(9); if ((!db_dir.empty()) && (db_dir[db_dir.size()-1] != '/')) db_dir += '/'; } else if (!(strcmp(argv[argpos], "--quiet"))) log_level = Error_Output::QUIET; else if (!(strcmp(argv[argpos], "--concise"))) log_level = Error_Output::CONCISE; else if (!(strcmp(argv[argpos], "--progress"))) log_level = Error_Output::PROGRESS; else if (!(strcmp(argv[argpos], "--verbose"))) log_level = Error_Output::VERBOSE; else if (!(strcmp(argv[argpos], "--rules"))) { area_level = 2; respect_timeout = false; } #ifdef HAVE_OVERPASS_XML else if (!(strcmp(argv[argpos], "--dump-xml"))) debug_level = parser_dump_xml; #endif else if (!(strcmp(argv[argpos], "--dump-pretty-ql"))) debug_level = parser_dump_pretty_map_ql; else if (!(strcmp(argv[argpos], "--dump-compact-ql"))) debug_level = parser_dump_compact_map_ql; else if (!(strcmp(argv[argpos], "--dump-bbox-ql"))) debug_level = parser_dump_bbox_map_ql; else if (!(strncmp(argv[argpos], "--clone=", 8))) { clone_db_dir = ((std::string)argv[argpos]).substr(8); if ((!clone_db_dir.empty()) && (clone_db_dir[clone_db_dir.size()-1] != '/')) clone_db_dir += '/'; } else if (!(strncmp(argv[argpos], "--request=", 10))) xml_raw = ((std::string)argv[argpos]).substr(10); else if (!(strncmp(argv[argpos], "--clone-compression=", 20))) { if (std::string(argv[argpos]).substr(20) == "no") clone_settings.compression_method = Block_Compression::NO_COMPRESSION; else if (std::string(argv[argpos]).substr(20) == "gz") clone_settings.compression_method = Block_Compression::ZLIB_COMPRESSION; #ifdef HAVE_LZ4 else if (std::string(argv[argpos]).substr(20) == "lz4") clone_settings.compression_method = Block_Compression::LZ4_COMPRESSION; #endif else { #ifdef HAVE_LZ4 std::cerr<<"For --clone-compression, please use \"no\", \"gz\", or \"lz4\" as value.\n"; #else std::cerr<<"For --clone-compression, please use \"no\" or \"gz\" as value.\n"; #endif return 0; } } else if (!(strncmp(argv[argpos], "--clone-map-compression=", 24))) { if (std::string(argv[argpos]).substr(24) == "no") clone_settings.map_compression_method = Block_Compression::NO_COMPRESSION; else if (std::string(argv[argpos]).substr(24) == "gz") clone_settings.map_compression_method = Block_Compression::ZLIB_COMPRESSION; #ifdef HAVE_LZ4 else if (std::string(argv[argpos]).substr(24) == "lz4") clone_settings.map_compression_method = Block_Compression::LZ4_COMPRESSION; #endif else { #ifdef HAVE_LZ4 std::cerr<<"For --clone-map-compression, please use \"no\", \"gz\", or \"lz4\" as value.\n"; #else std::cerr<<"For --clone-map-compression, please use \"no\" or \"gz\" as value.\n"; #endif return 0; } } else if (!(strncmp(argv[argpos], "--clone-parallel=", 17))) { clone_settings.parallel_processes = atoi(std::string(argv[argpos]).substr(17).c_str()); } else if (!(strcmp(argv[argpos], "--version"))) { std::cout<<"Overpass API version "<<basic_settings().version<<" "<<basic_settings().source_hash<<"\n"; return 0; } else { std::cout<<"Unknown argument: "<<argv[argpos]<<"\n\n" "Accepted arguments are:\n" " --db-dir=$DB_DIR: The directory where the database resides. If you set this parameter\n" " then osm3s_query will read from the database without using the dispatcher management.\n" #ifdef HAVE_OVERPASS_XML " --dump-xml: Don't execute the query but only dump the query in XML format.\n" #endif " --dump-pretty-ql: Don't execute the query but only dump the query in pretty QL format.\n" " --dump-compact-ql: Don't execute the query but only dump the query in compact QL format.\n" " --dump-bbox-ql: Don't execute the query but only dump the query in a suitable form\n" " for an OpenLayers slippy map.\n" " --clone=$TARGET_DIR: Write a consistent copy of the entire database to the given $TARGET_DIR.\n" " --clone-compression=$METHOD: Use a specific compression method $METHOD for clone bin files\n" " --clone-map-compression=$METHOD: Use a specific compression method $METHOD for clone map files\n" " --clone-parallel=n: Number of parallel threads used for clone generation\n" " --rules: Ignore all time limits and allow area creation by this query.\n" " --request=$QL: Use $QL instead of standard input as the request text.\n" " --quiet: Don't print anything on stderr.\n" " --concise: Print concise information on stderr.\n" " --progress: Print also progress information on stderr.\n" " --verbose: Print everything that happens on stderr.\n" " --version: Print version and exit.\n"; return 0; } ++argpos; } Console_Output error_output{log_level}; Statement::set_error_output(&error_output); // connect to dispatcher and get database dir try { Parsed_Query global_settings; if (!clone_db_dir.empty()) { // open read transaction and log this. area_level = determine_area_level(&error_output, area_level); Dispatcher_Stub dispatcher(db_dir, &error_output, "-- clone database --", get_uses_meta_data(), area_level, 24*60*60, 1024*1024*1024, global_settings); copy_file(dispatcher.resource_manager().get_transaction()->get_db_dir() + "/replicate_id", clone_db_dir + "/replicate_id"); clone_database(*dispatcher.resource_manager().get_transaction(), clone_db_dir, clone_settings); return 0; } if (xml_raw.empty()) xml_raw = get_xml_console(&error_output); if (error_output.display_encoding_errors()) return 0; Statement::Factory stmt_factory(global_settings); if (!parse_and_validate(stmt_factory, global_settings, xml_raw, &error_output, debug_level)) return 0; if (debug_level != parser_execute) return 0; Osm_Script_Statement* osm_script = 0; if (!get_statement_stack()->empty()) osm_script = dynamic_cast< Osm_Script_Statement* >(get_statement_stack()->front()); uint32 max_allowed_time = 0; uint64 max_allowed_space = 0; if (osm_script) { max_allowed_time = osm_script->get_max_allowed_time(); max_allowed_space = osm_script->get_max_allowed_space(); } else { Osm_Script_Statement temp(0, std::map< std::string, std::string >(), global_settings); max_allowed_time = temp.get_max_allowed_time(); max_allowed_space = temp.get_max_allowed_space(); } // Allow rules to run for unlimited time if (!respect_timeout) max_allowed_time = 0; error_output.runtime_remark(fmt::format("Timeout is {} and maxsize is {}.", max_allowed_time, max_allowed_space)); // open read transaction and log this. area_level = determine_area_level(&error_output, area_level); Dispatcher_Stub dispatcher(db_dir, &error_output, xml_raw, get_uses_meta_data(), area_level, max_allowed_time, max_allowed_space, global_settings); if (osm_script && osm_script->get_desired_timestamp()) dispatcher.resource_manager().set_desired_timestamp(osm_script->get_desired_timestamp()); Web_Output web_output(log_level); web_output.set_output_handler(global_settings.get_output_handler()); web_output.write_payload_header("", dispatcher.get_timestamp(), area_level > 0 ? dispatcher.get_area_timestamp() : "", false); dispatcher.resource_manager().start_cpu_timer(0); for (std::vector< Statement* >::const_iterator it(get_statement_stack()->begin()); it != get_statement_stack()->end(); ++it) (*it)->execute(dispatcher.resource_manager()); dispatcher.resource_manager().stop_cpu_timer(0); web_output.write_footer(); return 0; } catch (const Rate_limited_Error& e) { error_output.runtime_error(e.what()); return 1; } catch (const Timeout_Error& e) { error_output.runtime_error(e.what()); return 1; } catch (const File_Error &e) { if (e.origin != "Dispatcher_Stub::Dispatcher_Stub::1") { std::ostringstream temp; if (e.origin == "Dispatcher_Client::1") temp<<"The dispatcher (i.e. the database management system) is turned off."; else if (e.error_number == 0) temp<<"open64: "<<e.filename<<' '<<e.origin; else temp<<"open64: "<<e.error_number<<' '<<strerror(e.error_number)<<' '<<e.filename<<' '<<e.origin; error_output.runtime_error(temp.str()); } return 1; } catch (const Resource_Error &e) { std::ostringstream temp; if (e.timed_out) temp<<"Query timed out in \""<<e.stmt_name<<"\" at line "<<e.line_number <<" after "<<e.runtime<<" seconds."; else temp<<"Query run out of memory in \""<<e.stmt_name<<"\" at line " <<e.line_number<<" using about "<<e.size/(1024*1024)<<" MB of RAM."; error_output.runtime_error(temp.str()); return 2; } catch (const Context_Error &e) { error_output.runtime_error("Context error: " + e.message); return 3; } catch (const Exit_Error &e) { return 4; } catch(const std::bad_alloc& e) { rlimit limit; getrlimit(RLIMIT_AS, &limit); std::ostringstream temp; temp<<"Query run out of memory using about "<<limit.rlim_cur/(1024*1024)<<" MB of RAM."; error_output.runtime_error(temp.str()); return 5; } catch(const std::exception& e) { error_output.runtime_error(std::string("Query failed with the exception: ") + e.what()); return 6; } } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // mapnik #include <mapnik/text/face.hpp> #include <mapnik/debug.hpp> extern "C" { #include FT_GLYPH_H } namespace mapnik { font_face::font_face(FT_Face face) : face_(face) {} bool font_face::set_character_sizes(double size) { return !FT_Set_Char_Size(face_,0,(FT_F26Dot6)(size * (1<<6)),0,0); } bool font_face::set_unscaled_character_sizes() { return !FT_Set_Char_Size(face_,0,face_->units_per_EM,0,0); } bool font_face::glyph_dimensions(glyph_info & glyph) const { FT_Vector pen; pen.x = 0; pen.y = 0; FT_Set_Transform(face_, 0, &pen); if (FT_Load_Glyph(face_, glyph.glyph_index, FT_LOAD_NO_HINTING)) { MAPNIK_LOG_ERROR(font_face) << "FT_Load_Glyph failed"; return false; } FT_Glyph image; if (FT_Get_Glyph(face_->glyph, &image)) { MAPNIK_LOG_ERROR(font_face) << "FT_Get_Glyph failed"; return false; } FT_BBox glyph_bbox; FT_Glyph_Get_CBox(image, FT_GLYPH_BBOX_TRUNCATE, &glyph_bbox); FT_Done_Glyph(image); glyph.unscaled_ymin = glyph_bbox.yMin; glyph.unscaled_ymax = glyph_bbox.yMax; glyph.unscaled_advance = face_->glyph->advance.x; glyph.unscaled_line_height = face_->size->metrics.height; return true; } font_face::~font_face() { MAPNIK_LOG_DEBUG(font_face) << "font_face: Clean up face \"" << family_name() << " " << style_name() << "\""; FT_Done_Face(face_); } /******************************************************************************/ void font_face_set::add(face_ptr face) { faces_.push_back(face); } void font_face_set::set_character_sizes(double size) { for (face_ptr const& face : faces_) { face->set_character_sizes(size); } } void font_face_set::set_unscaled_character_sizes() { for (face_ptr const& face : faces_) { face->set_unscaled_character_sizes(); } } /******************************************************************************/ void stroker::init(double radius) { FT_Stroker_Set(s_, (FT_Fixed) (radius * (1<<6)), FT_STROKER_LINECAP_ROUND, FT_STROKER_LINEJOIN_ROUND, 0); } stroker::~stroker() { MAPNIK_LOG_DEBUG(font_engine_freetype) << "stroker: Destroy stroker=" << s_; FT_Stroker_Done(s_); } }//ns mapnik <commit_msg>c++ - don't rely on implicit int to bool conversions<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // mapnik #include <mapnik/text/face.hpp> #include <mapnik/debug.hpp> extern "C" { #include FT_GLYPH_H } namespace mapnik { font_face::font_face(FT_Face face) : face_(face) {} bool font_face::set_character_sizes(double size) { return (FT_Set_Char_Size(face_,0,(FT_F26Dot6)(size * (1<<6)),0,0) == 0); } bool font_face::set_unscaled_character_sizes() { return (FT_Set_Char_Size(face_,0,face_->units_per_EM,0,0) == 0); } bool font_face::glyph_dimensions(glyph_info & glyph) const { FT_Vector pen; pen.x = 0; pen.y = 0; FT_Set_Transform(face_, 0, &pen); if (FT_Load_Glyph(face_, glyph.glyph_index, FT_LOAD_NO_HINTING)) { MAPNIK_LOG_ERROR(font_face) << "FT_Load_Glyph failed"; return false; } FT_Glyph image; if (FT_Get_Glyph(face_->glyph, &image)) { MAPNIK_LOG_ERROR(font_face) << "FT_Get_Glyph failed"; return false; } FT_BBox glyph_bbox; FT_Glyph_Get_CBox(image, FT_GLYPH_BBOX_TRUNCATE, &glyph_bbox); FT_Done_Glyph(image); glyph.unscaled_ymin = glyph_bbox.yMin; glyph.unscaled_ymax = glyph_bbox.yMax; glyph.unscaled_advance = face_->glyph->advance.x; glyph.unscaled_line_height = face_->size->metrics.height; return true; } font_face::~font_face() { MAPNIK_LOG_DEBUG(font_face) << "font_face: Clean up face \"" << family_name() << " " << style_name() << "\""; FT_Done_Face(face_); } /******************************************************************************/ void font_face_set::add(face_ptr face) { faces_.push_back(face); } void font_face_set::set_character_sizes(double size) { for (face_ptr const& face : faces_) { face->set_character_sizes(size); } } void font_face_set::set_unscaled_character_sizes() { for (face_ptr const& face : faces_) { face->set_unscaled_character_sizes(); } } /******************************************************************************/ void stroker::init(double radius) { FT_Stroker_Set(s_, (FT_Fixed) (radius * (1<<6)), FT_STROKER_LINECAP_ROUND, FT_STROKER_LINEJOIN_ROUND, 0); } stroker::~stroker() { MAPNIK_LOG_DEBUG(font_engine_freetype) << "stroker: Destroy stroker=" << s_; FT_Stroker_Done(s_); } }//ns mapnik <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Qt Software Information (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** **************************************************************************/ #include "debuggerdialogs.h" #include "ui_attachcoredialog.h" #include "ui_attachexternaldialog.h" #include "ui_attachremotedialog.h" #include "ui_startexternaldialog.h" #ifdef Q_OS_WIN # include "dbgwinutils.h" #endif #include <QtCore/QDebug> #include <QtCore/QDir> #include <QtCore/QFile> #include <QtGui/QStandardItemModel> #include <QtGui/QHeaderView> #include <QtGui/QFileDialog> #include <QtGui/QPushButton> #include <QtGui/QProxyModel> #include <QtGui/QSortFilterProxyModel> using namespace Debugger::Internal; /////////////////////////////////////////////////////////////////////// // // AttachCoreDialog // /////////////////////////////////////////////////////////////////////// AttachCoreDialog::AttachCoreDialog(QWidget *parent) : QDialog(parent), m_ui(new Ui::AttachCoreDialog) { m_ui->setupUi(this); m_ui->execFileName->setExpectedKind(Core::Utils::PathChooser::File); m_ui->execFileName->setPromptDialogTitle(tr("Select Executable")); m_ui->coreFileName->setExpectedKind(Core::Utils::PathChooser::File); m_ui->coreFileName->setPromptDialogTitle(tr("Select Executable")); m_ui->buttonBox->button(QDialogButtonBox::Ok)->setDefault(true); connect(m_ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(m_ui->buttonBox, SIGNAL(rejected()), this, SLOT(reject())); } AttachCoreDialog::~AttachCoreDialog() { delete m_ui; } QString AttachCoreDialog::executableFile() const { return m_ui->execFileName->path(); } void AttachCoreDialog::setExecutableFile(const QString &fileName) { m_ui->execFileName->setPath(fileName); } QString AttachCoreDialog::coreFile() const { return m_ui->coreFileName->path(); } void AttachCoreDialog::setCoreFile(const QString &fileName) { m_ui->coreFileName->setPath(fileName); } /////////////////////////////////////////////////////////////////////// // // process model helpers // /////////////////////////////////////////////////////////////////////// static QStandardItemModel *createProcessModel(QObject *parent) { QStandardItemModel *rc = new QStandardItemModel(parent); QStringList columns; columns << AttachExternalDialog::tr("Process ID") << AttachExternalDialog::tr("Name") << AttachExternalDialog::tr("State"); rc->setHorizontalHeaderLabels(columns); return rc; } static bool isProcessName(const QString &procname) { for (int i = 0; i != procname.size(); ++i) if (!procname.at(i).isDigit()) return false; return true; } bool operator<(const ProcData &p1, const ProcData &p2) { return p1.name < p2.name; } // Determine UNIX processes by reading "/proc" static QList<ProcData> unixProcessList() { QList<ProcData> rc; const QStringList procnames = QDir(QLatin1String("/proc/")).entryList(); if (procnames.isEmpty()) return rc; foreach (const QString &procname, procnames) { if (!isProcessName(procname)) continue; QString filename = QLatin1String("/proc/"); filename += procname; filename += QLatin1String("/stat"); QFile file(filename); file.open(QIODevice::ReadOnly); const QStringList data = QString::fromLocal8Bit(file.readAll()).split(' '); ProcData proc; proc.name = data.at(1); if (proc.name.startsWith(QLatin1Char('(')) && proc.name.endsWith(QLatin1Char(')'))) proc.name = proc.name.mid(1, proc.name.size() - 2); proc.state = data.at(2); proc.ppid = data.at(3); rc.push_back(proc); } return rc; } static void populateProcessModel(QStandardItemModel *model) { #ifdef Q_OS_WIN QList<ProcData> processes = winProcessList(); #else QList<ProcData> processes = unixProcessList(); #endif qStableSort(processes); if (const int rowCount = model->rowCount()) model->removeRows(0, rowCount); QStandardItem *root = model->invisibleRootItem(); foreach(const ProcData &proc, processes) { QList<QStandardItem *> row; row.append(new QStandardItem(proc.ppid)); row.append(new QStandardItem(proc.name)); if (!proc.image.isEmpty()) row.back()->setToolTip(proc.image); row.append(new QStandardItem(proc.state)); root->appendRow(row); } } /////////////////////////////////////////////////////////////////////// // // AttachExternalDialog // /////////////////////////////////////////////////////////////////////// AttachExternalDialog::AttachExternalDialog(QWidget *parent) : QDialog(parent), m_ui(new Ui::AttachExternalDialog), m_model(createProcessModel(this)), m_proxyModel(new QSortFilterProxyModel(this)) { m_ui->setupUi(this); m_ui->buttonBox->button(QDialogButtonBox::Ok)->setDefault(true); m_proxyModel->setSourceModel(m_model); m_proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); m_proxyModel->setFilterKeyColumn(1); m_ui->procView->setModel(m_proxyModel); m_ui->procView->setSortingEnabled(true); connect(m_ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(m_ui->buttonBox, SIGNAL(rejected()), this, SLOT(reject())); QPushButton *refreshButton = new QPushButton(tr("Refresh")); connect(refreshButton, SIGNAL(clicked()), this, SLOT(rebuildProcessList())); m_ui->buttonBox->addButton(refreshButton, QDialogButtonBox::ActionRole); connect(m_ui->procView, SIGNAL(activated(QModelIndex)), this, SLOT(procSelected(QModelIndex))); connect(m_ui->filterClearToolButton, SIGNAL(clicked()), m_ui->filterLineEdit, SLOT(clear())); connect(m_ui->filterLineEdit, SIGNAL(textChanged(QString)), m_proxyModel, SLOT(setFilterFixedString(QString))); rebuildProcessList(); } AttachExternalDialog::~AttachExternalDialog() { delete m_ui; } void AttachExternalDialog::rebuildProcessList() { populateProcessModel(m_model); m_ui->procView->expandAll(); m_ui->procView->resizeColumnToContents(0); m_ui->procView->resizeColumnToContents(1); m_ui->procView->sortByColumn(1, Qt::AscendingOrder); } void AttachExternalDialog::procSelected(const QModelIndex &proxyIndex) { const QModelIndex index0 = m_proxyModel->mapToSource(proxyIndex); QModelIndex index = index0.sibling(index0.row(), 0); if (const QStandardItem *item = m_model->itemFromIndex(index)) { m_ui->pidLineEdit->setText(item->text()); m_ui->buttonBox->button(QDialogButtonBox::Ok)->animateClick(); } } int AttachExternalDialog::attachPID() const { return m_ui->pidLineEdit->text().toInt(); } /////////////////////////////////////////////////////////////////////// // // AttachRemoteDialog // /////////////////////////////////////////////////////////////////////// AttachRemoteDialog::AttachRemoteDialog(QWidget *parent, const QString &pid) : QDialog(parent), m_ui(new Ui::AttachRemoteDialog), m_model(createProcessModel(this)) { m_ui->setupUi(this); m_ui->buttonBox->button(QDialogButtonBox::Ok)->setDefault(true); m_defaultPID = pid; m_ui->procView->setModel(m_model); m_ui->procView->setSortingEnabled(true); connect(m_ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(m_ui->buttonBox, SIGNAL(rejected()), this, SLOT(reject())); connect(m_ui->procView, SIGNAL(activated(QModelIndex)), this, SLOT(procSelected(QModelIndex))); m_ui->pidLineEdit->setText(m_defaultPID); rebuildProcessList(); } AttachRemoteDialog::~AttachRemoteDialog() { delete m_ui; } void AttachRemoteDialog::rebuildProcessList() { populateProcessModel(m_model); m_ui->procView->expandAll(); m_ui->procView->resizeColumnToContents(0); m_ui->procView->resizeColumnToContents(1); } void AttachRemoteDialog::procSelected(const QModelIndex &index0) { QModelIndex index = index0.sibling(index0.row(), 0); QStandardItem *item = m_model->itemFromIndex(index); if (!item) return; m_ui->pidLineEdit->setText(item->text()); accept(); } int AttachRemoteDialog::attachPID() const { return m_ui->pidLineEdit->text().toInt(); } /////////////////////////////////////////////////////////////////////// // // StartExternalDialog // /////////////////////////////////////////////////////////////////////// StartExternalDialog::StartExternalDialog(QWidget *parent) : QDialog(parent), m_ui(new Ui::StartExternalDialog) { m_ui->setupUi(this); m_ui->execFile->setExpectedKind(Core::Utils::PathChooser::File); m_ui->execFile->setPromptDialogTitle(tr("Select Executable")); m_ui->buttonBox->button(QDialogButtonBox::Ok)->setDefault(true); //execLabel->setHidden(false); //execEdit->setHidden(false); //browseButton->setHidden(false); m_ui->execLabel->setText(tr("Executable:")); m_ui->argLabel->setText(tr("Arguments:")); connect(m_ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(m_ui->buttonBox, SIGNAL(rejected()), this, SLOT(reject())); } StartExternalDialog::~StartExternalDialog() { delete m_ui; } void StartExternalDialog::setExecutableFile(const QString &str) { m_ui->execFile->setPath(str); } void StartExternalDialog::setExecutableArguments(const QString &str) { m_ui->argsEdit->setText(str); } QString StartExternalDialog::executableFile() const { return m_ui->execFile->path(); } QString StartExternalDialog::executableArguments() const { return m_ui->argsEdit->text(); } <commit_msg>Fixes: compile fix with namespaced Qt<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Qt Software Information (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** **************************************************************************/ #include "debuggerdialogs.h" #include "ui_attachcoredialog.h" #include "ui_attachexternaldialog.h" #include "ui_attachremotedialog.h" #include "ui_startexternaldialog.h" #ifdef Q_OS_WIN # include "dbgwinutils.h" #endif #include <QtCore/QDebug> #include <QtCore/QDir> #include <QtCore/QFile> #include <QtGui/QStandardItemModel> #include <QtGui/QHeaderView> #include <QtGui/QFileDialog> #include <QtGui/QPushButton> #include <QtGui/QProxyModel> #include <QtGui/QSortFilterProxyModel> using namespace Debugger::Internal; /////////////////////////////////////////////////////////////////////// // // AttachCoreDialog // /////////////////////////////////////////////////////////////////////// AttachCoreDialog::AttachCoreDialog(QWidget *parent) : QDialog(parent), m_ui(new Ui::AttachCoreDialog) { m_ui->setupUi(this); m_ui->execFileName->setExpectedKind(Core::Utils::PathChooser::File); m_ui->execFileName->setPromptDialogTitle(tr("Select Executable")); m_ui->coreFileName->setExpectedKind(Core::Utils::PathChooser::File); m_ui->coreFileName->setPromptDialogTitle(tr("Select Executable")); m_ui->buttonBox->button(QDialogButtonBox::Ok)->setDefault(true); connect(m_ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(m_ui->buttonBox, SIGNAL(rejected()), this, SLOT(reject())); } AttachCoreDialog::~AttachCoreDialog() { delete m_ui; } QString AttachCoreDialog::executableFile() const { return m_ui->execFileName->path(); } void AttachCoreDialog::setExecutableFile(const QString &fileName) { m_ui->execFileName->setPath(fileName); } QString AttachCoreDialog::coreFile() const { return m_ui->coreFileName->path(); } void AttachCoreDialog::setCoreFile(const QString &fileName) { m_ui->coreFileName->setPath(fileName); } /////////////////////////////////////////////////////////////////////// // // process model helpers // /////////////////////////////////////////////////////////////////////// static QStandardItemModel *createProcessModel(QObject *parent) { QStandardItemModel *rc = new QStandardItemModel(parent); QStringList columns; columns << AttachExternalDialog::tr("Process ID") << AttachExternalDialog::tr("Name") << AttachExternalDialog::tr("State"); rc->setHorizontalHeaderLabels(columns); return rc; } static bool isProcessName(const QString &procname) { for (int i = 0; i != procname.size(); ++i) if (!procname.at(i).isDigit()) return false; return true; } QT_BEGIN_NAMESPACE bool operator<(const ProcData &p1, const ProcData &p2) { return p1.name < p2.name; } QT_END_NAMESPACE // Determine UNIX processes by reading "/proc" static QList<ProcData> unixProcessList() { QList<ProcData> rc; const QStringList procnames = QDir(QLatin1String("/proc/")).entryList(); if (procnames.isEmpty()) return rc; foreach (const QString &procname, procnames) { if (!isProcessName(procname)) continue; QString filename = QLatin1String("/proc/"); filename += procname; filename += QLatin1String("/stat"); QFile file(filename); file.open(QIODevice::ReadOnly); const QStringList data = QString::fromLocal8Bit(file.readAll()).split(' '); ProcData proc; proc.name = data.at(1); if (proc.name.startsWith(QLatin1Char('(')) && proc.name.endsWith(QLatin1Char(')'))) proc.name = proc.name.mid(1, proc.name.size() - 2); proc.state = data.at(2); proc.ppid = data.at(3); rc.push_back(proc); } return rc; } static void populateProcessModel(QStandardItemModel *model) { #ifdef Q_OS_WIN QList<ProcData> processes = winProcessList(); #else QList<ProcData> processes = unixProcessList(); #endif qStableSort(processes); if (const int rowCount = model->rowCount()) model->removeRows(0, rowCount); QStandardItem *root = model->invisibleRootItem(); foreach(const ProcData &proc, processes) { QList<QStandardItem *> row; row.append(new QStandardItem(proc.ppid)); row.append(new QStandardItem(proc.name)); if (!proc.image.isEmpty()) row.back()->setToolTip(proc.image); row.append(new QStandardItem(proc.state)); root->appendRow(row); } } /////////////////////////////////////////////////////////////////////// // // AttachExternalDialog // /////////////////////////////////////////////////////////////////////// AttachExternalDialog::AttachExternalDialog(QWidget *parent) : QDialog(parent), m_ui(new Ui::AttachExternalDialog), m_proxyModel(new QSortFilterProxyModel(this)), m_model(createProcessModel(this)) { m_ui->setupUi(this); m_ui->buttonBox->button(QDialogButtonBox::Ok)->setDefault(true); m_proxyModel->setSourceModel(m_model); m_proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); m_proxyModel->setFilterKeyColumn(1); m_ui->procView->setModel(m_proxyModel); m_ui->procView->setSortingEnabled(true); connect(m_ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(m_ui->buttonBox, SIGNAL(rejected()), this, SLOT(reject())); QPushButton *refreshButton = new QPushButton(tr("Refresh")); connect(refreshButton, SIGNAL(clicked()), this, SLOT(rebuildProcessList())); m_ui->buttonBox->addButton(refreshButton, QDialogButtonBox::ActionRole); connect(m_ui->procView, SIGNAL(activated(QModelIndex)), this, SLOT(procSelected(QModelIndex))); connect(m_ui->filterClearToolButton, SIGNAL(clicked()), m_ui->filterLineEdit, SLOT(clear())); connect(m_ui->filterLineEdit, SIGNAL(textChanged(QString)), m_proxyModel, SLOT(setFilterFixedString(QString))); rebuildProcessList(); } AttachExternalDialog::~AttachExternalDialog() { delete m_ui; } void AttachExternalDialog::rebuildProcessList() { populateProcessModel(m_model); m_ui->procView->expandAll(); m_ui->procView->resizeColumnToContents(0); m_ui->procView->resizeColumnToContents(1); m_ui->procView->sortByColumn(1, Qt::AscendingOrder); } void AttachExternalDialog::procSelected(const QModelIndex &proxyIndex) { const QModelIndex index0 = m_proxyModel->mapToSource(proxyIndex); QModelIndex index = index0.sibling(index0.row(), 0); if (const QStandardItem *item = m_model->itemFromIndex(index)) { m_ui->pidLineEdit->setText(item->text()); m_ui->buttonBox->button(QDialogButtonBox::Ok)->animateClick(); } } int AttachExternalDialog::attachPID() const { return m_ui->pidLineEdit->text().toInt(); } /////////////////////////////////////////////////////////////////////// // // AttachRemoteDialog // /////////////////////////////////////////////////////////////////////// AttachRemoteDialog::AttachRemoteDialog(QWidget *parent, const QString &pid) : QDialog(parent), m_ui(new Ui::AttachRemoteDialog), m_model(createProcessModel(this)) { m_ui->setupUi(this); m_ui->buttonBox->button(QDialogButtonBox::Ok)->setDefault(true); m_defaultPID = pid; m_ui->procView->setModel(m_model); m_ui->procView->setSortingEnabled(true); connect(m_ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(m_ui->buttonBox, SIGNAL(rejected()), this, SLOT(reject())); connect(m_ui->procView, SIGNAL(activated(QModelIndex)), this, SLOT(procSelected(QModelIndex))); m_ui->pidLineEdit->setText(m_defaultPID); rebuildProcessList(); } AttachRemoteDialog::~AttachRemoteDialog() { delete m_ui; } void AttachRemoteDialog::rebuildProcessList() { populateProcessModel(m_model); m_ui->procView->expandAll(); m_ui->procView->resizeColumnToContents(0); m_ui->procView->resizeColumnToContents(1); } void AttachRemoteDialog::procSelected(const QModelIndex &index0) { QModelIndex index = index0.sibling(index0.row(), 0); QStandardItem *item = m_model->itemFromIndex(index); if (!item) return; m_ui->pidLineEdit->setText(item->text()); accept(); } int AttachRemoteDialog::attachPID() const { return m_ui->pidLineEdit->text().toInt(); } /////////////////////////////////////////////////////////////////////// // // StartExternalDialog // /////////////////////////////////////////////////////////////////////// StartExternalDialog::StartExternalDialog(QWidget *parent) : QDialog(parent), m_ui(new Ui::StartExternalDialog) { m_ui->setupUi(this); m_ui->execFile->setExpectedKind(Core::Utils::PathChooser::File); m_ui->execFile->setPromptDialogTitle(tr("Select Executable")); m_ui->buttonBox->button(QDialogButtonBox::Ok)->setDefault(true); //execLabel->setHidden(false); //execEdit->setHidden(false); //browseButton->setHidden(false); m_ui->execLabel->setText(tr("Executable:")); m_ui->argLabel->setText(tr("Arguments:")); connect(m_ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(m_ui->buttonBox, SIGNAL(rejected()), this, SLOT(reject())); } StartExternalDialog::~StartExternalDialog() { delete m_ui; } void StartExternalDialog::setExecutableFile(const QString &str) { m_ui->execFile->setPath(str); } void StartExternalDialog::setExecutableArguments(const QString &str) { m_ui->argsEdit->setText(str); } QString StartExternalDialog::executableFile() const { return m_ui->execFile->path(); } QString StartExternalDialog::executableArguments() const { return m_ui->argsEdit->text(); } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (info@qt.nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at info@qt.nokia.com. ** **************************************************************************/ #include "timelineview.h" #include <qdeclarativecontext.h> #include <qdeclarativeproperty.h> using namespace QmlProfiler::Internal; TimelineView::TimelineView(QDeclarativeItem *parent) : QDeclarativeItem(parent), m_delegate(0), m_startTime(0), m_endTime(0), m_startX(0), prevMin(0), prevMax(0), m_totalWidth(0) { } void TimelineView::componentComplete() { QDeclarativeItem::componentComplete(); } void TimelineView::clearData() { m_rangeList.clear(); m_items.clear(); m_startTime = 0; m_endTime = 0; m_startX = 0; prevMin = 0; prevMax = 0; m_prevLimits.clear(); m_totalWidth = 0; } void TimelineView::setRanges(const QScriptValue &value) { //TODO clear old values (always?) m_ranges = value; //### below code not yet used anywhere int length = m_ranges.property("length").toInt32(); for (int i = 0; i < length; ++i) { int type = m_ranges.property(i).property("type").toNumber(); Q_ASSERT(type >= 0); while (m_rangeList.count() <= type) m_rangeList.append(ValueList()); m_rangeList[type] << m_ranges.property(i); } for (int i = 0; i < m_rangeList.count(); ++i) m_prevLimits << PrevLimits(0, 0); qreal startValue = m_ranges.property(0).property("start").toNumber(); m_starts.clear(); m_starts.reserve(length); m_ends.clear(); m_ends.reserve(length); for (int i = 0; i < length; ++i) { m_starts.append(m_ranges.property(i).property("start").toNumber() - startValue); m_ends.append(m_ranges.property(i).property("start").toNumber() + m_ranges.property(i).property("duration").toNumber() - startValue); } } void TimelineView::setStartX(qreal arg) { if (arg == m_startX) return; if (!m_ranges.isArray()) return; qreal window = m_endTime - m_startTime; if (window == 0) //### return; qreal spacing = width() / window; qreal oldStart = m_startTime; m_startTime = arg / spacing; m_endTime += m_startTime - oldStart; updateTimeline(false); m_startX = arg; emit startXChanged(m_startX); } void TimelineView::updateTimeline(bool updateStartX) { if (!m_delegate) return; if (!m_ranges.isArray()) return; int length = m_ranges.property("length").toInt32(); qreal startValue = m_ranges.property(0).property("start").toNumber(); qreal endValue = m_ranges.property(length-1).property("start").toNumber() + m_ranges.property(length-1).property("duration").toNumber(); qreal totalRange = endValue - startValue; qreal window = m_endTime - m_startTime; if (window == 0) //### return; qreal spacing = width() / window; qreal oldtw = m_totalWidth; m_totalWidth = totalRange * spacing; // Find region samples int minsample = 0; int maxsample = 0; for (int i = 0; i < length; ++i) { if (m_ends.at(i) >= m_startTime) break; minsample = i; } for (int i = minsample + 1; i < length; ++i) { maxsample = i; if (m_starts.at(i) > m_endTime) break; } //### overkill (if we can expose whether or not data is nested) for (int i = maxsample + 1; i < length; ++i) { if (m_starts.at(i) < m_endTime) maxsample = i; } //qDebug() << maxsample - minsample; if (updateStartX) { qreal oldStartX = m_startX; m_startX = qRound(m_startTime * spacing); if (m_startX != oldStartX) { emit startXChanged(m_startX); } } //### emitting this before startXChanged was causing issues if (m_totalWidth != oldtw) emit totalWidthChanged(m_totalWidth); //clear items no longer in view while (prevMin < minsample) { delete m_items.take(prevMin); ++prevMin; } while (prevMax > maxsample) { delete m_items.take(prevMax); --prevMax; } // Show items int z = 0; for (int i = maxsample-1; i >= minsample; --i) { QDeclarativeItem *item = 0; item = m_items.value(i); bool creating = false; if (!item) { QDeclarativeContext *ctxt = new QDeclarativeContext(qmlContext(this)); item = qobject_cast<QDeclarativeItem*>(m_delegate->beginCreate(ctxt)); m_items.insert(i, item); creating = true; int type = m_ranges.property(i).property("type").toNumber(); ctxt->setParent(item); //### QDeclarative_setParent_noEvent(ctxt, item); instead? ctxt->setContextProperty("duration", qMax(qRound(m_ranges.property(i).property("duration").toNumber()/qreal(1000)),1)); ctxt->setContextProperty("fileName", m_ranges.property(i).property("fileName").toString()); ctxt->setContextProperty("line", m_ranges.property(i).property("line").toNumber()); ctxt->setContextProperty("index", i); ctxt->setContextProperty("nestingLevel", m_ranges.property(i).property("nestingLevel").toNumber()); ctxt->setContextProperty("nestingDepth", m_ranges.property(i).property("nestingDepth").toNumber()); QString label; QVariantList list = m_ranges.property(i).property("label").toVariant().value<QVariantList>(); for (int i = 0; i < list.size(); ++i) { if (i > 0) label += QLatin1Char('\n'); QString sub = list.at(i).toString(); //### only do rewrite for bindings... if (type == 3) { //### don't construct in loop QRegExp rewrite("\\(function \\$(\\w+)\\(\\) \\{ return (.+) \\}\\)"); bool match = rewrite.exactMatch(sub); if (match) sub = rewrite.cap(1) + ": " + rewrite.cap(2); } label += sub; } ctxt->setContextProperty("label", label); ctxt->setContextProperty("type", type); item->setParentItem(this); } if (item) { item->setX(m_starts.at(i)*spacing); qreal width = (m_ends.at(i)-m_starts.at(i)) * spacing; item->setWidth(width > 1 ? width : 1); item->setZValue(++z); } if (creating) m_delegate->completeCreate(); } prevMin = minsample; prevMax = maxsample; } <commit_msg>QmlProfiler: fixed skipping long events<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (info@qt.nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at info@qt.nokia.com. ** **************************************************************************/ #include "timelineview.h" #include <qdeclarativecontext.h> #include <qdeclarativeproperty.h> using namespace QmlProfiler::Internal; TimelineView::TimelineView(QDeclarativeItem *parent) : QDeclarativeItem(parent), m_delegate(0), m_startTime(0), m_endTime(0), m_startX(0), prevMin(0), prevMax(0), m_totalWidth(0) { } void TimelineView::componentComplete() { QDeclarativeItem::componentComplete(); } void TimelineView::clearData() { m_rangeList.clear(); m_items.clear(); m_startTime = 0; m_endTime = 0; m_startX = 0; prevMin = 0; prevMax = 0; m_prevLimits.clear(); m_totalWidth = 0; } void TimelineView::setRanges(const QScriptValue &value) { //TODO clear old values (always?) m_ranges = value; //### below code not yet used anywhere int length = m_ranges.property("length").toInt32(); for (int i = 0; i < length; ++i) { int type = m_ranges.property(i).property("type").toNumber(); Q_ASSERT(type >= 0); while (m_rangeList.count() <= type) m_rangeList.append(ValueList()); m_rangeList[type] << m_ranges.property(i); } for (int i = 0; i < m_rangeList.count(); ++i) m_prevLimits << PrevLimits(0, 0); qreal startValue = m_ranges.property(0).property("start").toNumber(); m_starts.clear(); m_starts.reserve(length); m_ends.clear(); m_ends.reserve(length); for (int i = 0; i < length; ++i) { m_starts.append(m_ranges.property(i).property("start").toNumber() - startValue); m_ends.append(m_ranges.property(i).property("start").toNumber() + m_ranges.property(i).property("duration").toNumber() - startValue); } } void TimelineView::setStartX(qreal arg) { if (arg == m_startX) return; if (!m_ranges.isArray()) return; qreal window = m_endTime - m_startTime; if (window == 0) //### return; qreal spacing = width() / window; qreal oldStart = m_startTime; m_startTime = arg / spacing; m_endTime += m_startTime - oldStart; updateTimeline(false); m_startX = arg; emit startXChanged(m_startX); } void TimelineView::updateTimeline(bool updateStartX) { if (!m_delegate) return; if (!m_ranges.isArray()) return; int length = m_ranges.property("length").toInt32(); qreal startValue = m_ranges.property(0).property("start").toNumber(); qreal endValue = m_ranges.property(length-1).property("start").toNumber() + m_ranges.property(length-1).property("duration").toNumber(); qreal totalRange = endValue - startValue; qreal window = m_endTime - m_startTime; if (window == 0) //### return; qreal spacing = width() / window; qreal oldtw = m_totalWidth; m_totalWidth = totalRange * spacing; // Find region samples int minsample = 0; int maxsample = 0; for (int i = 0; i < length; ++i) { if (m_ends.at(i) >= m_startTime) break; minsample = i; } for (int i = minsample + 1; i < length; ++i) { maxsample = i; if (m_starts.at(i) > m_endTime) break; } //### overkill (if we can expose whether or not data is nested) for (int i = maxsample + 1; i < length; ++i) { if (m_starts.at(i) < m_endTime) maxsample = i; } //qDebug() << maxsample - minsample; if (updateStartX) { qreal oldStartX = m_startX; m_startX = qRound(m_startTime * spacing); if (m_startX != oldStartX) { emit startXChanged(m_startX); } } //### emitting this before startXChanged was causing issues if (m_totalWidth != oldtw) emit totalWidthChanged(m_totalWidth); //clear items no longer in view while (prevMin < minsample) { delete m_items.take(prevMin); ++prevMin; } while (prevMax > maxsample) { delete m_items.take(prevMax); --prevMax; } // Show items int z = 0; for (int i = maxsample; i >= minsample; --i) { QDeclarativeItem *item = 0; item = m_items.value(i); bool creating = false; if (!item) { QDeclarativeContext *ctxt = new QDeclarativeContext(qmlContext(this)); item = qobject_cast<QDeclarativeItem*>(m_delegate->beginCreate(ctxt)); m_items.insert(i, item); creating = true; int type = m_ranges.property(i).property("type").toNumber(); ctxt->setParent(item); //### QDeclarative_setParent_noEvent(ctxt, item); instead? ctxt->setContextProperty("duration", qMax(qRound(m_ranges.property(i).property("duration").toNumber()/qreal(1000)),1)); ctxt->setContextProperty("fileName", m_ranges.property(i).property("fileName").toString()); ctxt->setContextProperty("line", m_ranges.property(i).property("line").toNumber()); ctxt->setContextProperty("index", i); ctxt->setContextProperty("nestingLevel", m_ranges.property(i).property("nestingLevel").toNumber()); ctxt->setContextProperty("nestingDepth", m_ranges.property(i).property("nestingDepth").toNumber()); QString label; QVariantList list = m_ranges.property(i).property("label").toVariant().value<QVariantList>(); for (int i = 0; i < list.size(); ++i) { if (i > 0) label += QLatin1Char('\n'); QString sub = list.at(i).toString(); //### only do rewrite for bindings... if (type == 3) { //### don't construct in loop QRegExp rewrite("\\(function \\$(\\w+)\\(\\) \\{ return (.+) \\}\\)"); bool match = rewrite.exactMatch(sub); if (match) sub = rewrite.cap(1) + ": " + rewrite.cap(2); } label += sub; } ctxt->setContextProperty("label", label); ctxt->setContextProperty("type", type); item->setParentItem(this); } if (item) { item->setX(m_starts.at(i)*spacing); qreal width = (m_ends.at(i)-m_starts.at(i)) * spacing; item->setWidth(width > 1 ? width : 1); item->setZValue(++z); } if (creating) m_delegate->completeCreate(); } prevMin = minsample; prevMax = maxsample; } <|endoftext|>
<commit_before>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2009 Emmanuel Benazera, juban@free.fr * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "se_parser_cuil.h" #include "miscutil.h" #include <strings.h> #include <iostream> using sp::miscutil; namespace seeks_plugins { se_parser_cuil::se_parser_cuil() :se_parser(),_start_results(false),_new_link(false),_sum_flag(false), _cite_flag(false),_screening(false),_pages(false) { } se_parser_cuil::~se_parser_cuil() { } void se_parser_cuil::start_element(parser_context *pc, const xmlChar *name, const xmlChar **attributes) { const char *tag = (const char*)name; if (strcasecmp(tag,"div") == 0) { const char *a_class = se_parser::get_attribute((const char**)attributes,"class"); const char *a_id = se_parser::get_attribute((const char**)attributes,"id"); if (!_start_results && a_class && strcasecmp(a_class,"result web_result") == 0) { _start_results = true; } if (a_id && _start_results && strncasecmp(a_id,"result_",7) == 0) { // check on previous snippet. if (pc->_current_snippet) { if (pc->_current_snippet->_title != "") { // no cache on cuil, so we give a link to an archived page. pc->_current_snippet->set_archive_link(); pc->_snippets->push_back(pc->_current_snippet); } else { delete pc->_current_snippet; pc->_current_snippet = NULL; } } // create new snippet. std::string count_str = std::string(a_id); try { count_str = count_str.substr(7); } catch(std::exception &e) { return; // stop here, do not create the snippet. } int count = atoi(count_str.c_str()); search_snippet *sp = new search_snippet(count-1); sp->_engine |= std::bitset<NSEs>(SE_CUIL); pc->_current_snippet = sp; _screening = true; } else if (a_class && _start_results && _screening && strcasecmp(a_class,"clear") == 0) _screening = false; // specify to stop parsing snippets until told otherwise (aka 'cut the crap'). else if (a_class && _start_results && _new_link && strcasecmp(a_class,"url-wrap") == 0) { // sets summary. _sum_flag = false; pc->_current_snippet->set_summary(_summary); _summary = ""; _new_link = false; _cite_flag = true; } else if (a_id && _start_results && !_screening && strcasecmp(a_id,"pages") == 0) { _pages = true; } } else if (_start_results && strcasecmp(tag,"a") == 0) { const char *a_class = se_parser::get_attribute((const char**)attributes,"class"); if (a_class && _screening && strcasecmp(a_class,"title_link") == 0) { // sets the link. const char *a_link = se_parser::get_attribute((const char**)attributes,"href"); const char *a_title = se_parser::get_attribute((const char**)attributes,"title"); if (a_link) { pc->_current_snippet->set_url(std::string(a_link)); _new_link = true; } if (a_title) { pc->_current_snippet->_title = std::string(a_title); } } else if (a_class && _pages) { if (a_class && strcasecmp(a_class,"pagelink ") == 0) { const char *a_link = se_parser::get_attribute((const char**)attributes,"href"); if (a_link) { std::string a_link_str = std::string(a_link); size_t ppos = a_link_str.find("&p="); size_t epos = a_link_str.find("_"); std::string pnum_str; try { pnum_str = a_link_str.substr(ppos+3,epos-ppos-3); } catch(std::exception &e) { return; // do not save this link. } int pnum = atoi(pnum_str.c_str()); try { _links_to_pages.insert(std::pair<int,std::string>(pnum,a_link_str.substr(ppos))); } catch(std::exception &e) { return; // do not save this link. } /* std::cout << "added page link: " << a_link_str.substr(ppos) << std::endl; std::cout << "pnum_str: " << pnum_str << std::endl; */ } } } } else if (_start_results && _screening && _new_link && strcasecmp(tag,"p") == 0) { _sum_flag = true; } } void se_parser_cuil::characters(parser_context *pc, const xmlChar *chars, int length) { handle_characters(pc, chars, length); } void se_parser_cuil::cdata(parser_context *pc, const xmlChar *chars, int length) { handle_characters(pc, chars, length); } void se_parser_cuil::handle_characters(parser_context *pc, const xmlChar *chars, int length) { if (_start_results && !_screening) return; else if (_sum_flag) { std::string a_chars = std::string((char*)chars); miscutil::replace_in_string(a_chars,"\n"," "); miscutil::replace_in_string(a_chars,"\r"," "); //miscutil::replace_in_string(a_chars,"-"," "); _summary += a_chars; } else if (_cite_flag) { std::string a_chars = std::string((char*)chars); miscutil::replace_in_string(a_chars,"\n"," "); miscutil::replace_in_string(a_chars,"\r"," "); _cite += a_chars; } } void se_parser_cuil::end_element(parser_context *pc, const xmlChar *name) { if (_start_results && !_screening) return; const char *tag = (const char*)name; if (_cite_flag && strcasecmp(tag,"a") == 0) { _cite_flag = false; pc->_current_snippet->_cite = _cite; _cite = ""; } else if (_pages && strcasecmp(tag,"div") == 0) _pages = false; } } /* end of namespace. */ <commit_msg>fixed ranking bug in cuil parser<commit_after>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2009 Emmanuel Benazera, juban@free.fr * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "se_parser_cuil.h" #include "miscutil.h" #include <strings.h> #include <iostream> using sp::miscutil; namespace seeks_plugins { se_parser_cuil::se_parser_cuil() :se_parser(),_start_results(false),_new_link(false),_sum_flag(false), _cite_flag(false),_screening(false),_pages(false) { } se_parser_cuil::~se_parser_cuil() { } void se_parser_cuil::start_element(parser_context *pc, const xmlChar *name, const xmlChar **attributes) { const char *tag = (const char*)name; if (strcasecmp(tag,"div") == 0) { const char *a_class = se_parser::get_attribute((const char**)attributes,"class"); const char *a_id = se_parser::get_attribute((const char**)attributes,"id"); if (!_start_results && a_class && strcasecmp(a_class,"result web_result") == 0) { _start_results = true; } if (a_id && _start_results && strncasecmp(a_id,"result_",7) == 0) { // check on previous snippet. if (pc->_current_snippet) { if (pc->_current_snippet->_title != "") { // no cache on cuil, so we give a link to an archived page. pc->_current_snippet->set_archive_link(); pc->_snippets->push_back(pc->_current_snippet); } else { delete pc->_current_snippet; pc->_current_snippet = NULL; } } // create new snippet. std::string count_str = std::string(a_id); try { count_str = count_str.substr(7); } catch(std::exception &e) { return; // stop here, do not create the snippet. } int count = atoi(count_str.c_str()); search_snippet *sp = new search_snippet(count); sp->_engine |= std::bitset<NSEs>(SE_CUIL); pc->_current_snippet = sp; _screening = true; } else if (a_class && _start_results && _screening && strcasecmp(a_class,"clear") == 0) _screening = false; // specify to stop parsing snippets until told otherwise (aka 'cut the crap'). else if (a_class && _start_results && _new_link && strcasecmp(a_class,"url-wrap") == 0) { // sets summary. _sum_flag = false; pc->_current_snippet->set_summary(_summary); _summary = ""; _new_link = false; _cite_flag = true; } else if (a_id && _start_results && !_screening && strcasecmp(a_id,"pages") == 0) { _pages = true; } } else if (_start_results && strcasecmp(tag,"a") == 0) { const char *a_class = se_parser::get_attribute((const char**)attributes,"class"); if (a_class && _screening && strcasecmp(a_class,"title_link") == 0) { // sets the link. const char *a_link = se_parser::get_attribute((const char**)attributes,"href"); const char *a_title = se_parser::get_attribute((const char**)attributes,"title"); if (a_link) { pc->_current_snippet->set_url(std::string(a_link)); _new_link = true; } if (a_title) { pc->_current_snippet->_title = std::string(a_title); } } else if (a_class && _pages) { if (a_class && strcasecmp(a_class,"pagelink ") == 0) { const char *a_link = se_parser::get_attribute((const char**)attributes,"href"); if (a_link) { std::string a_link_str = std::string(a_link); size_t ppos = a_link_str.find("&p="); size_t epos = a_link_str.find("_"); std::string pnum_str; try { pnum_str = a_link_str.substr(ppos+3,epos-ppos-3); } catch(std::exception &e) { return; // do not save this link. } int pnum = atoi(pnum_str.c_str()); try { _links_to_pages.insert(std::pair<int,std::string>(pnum,a_link_str.substr(ppos))); } catch(std::exception &e) { return; // do not save this link. } /* std::cout << "added page link: " << a_link_str.substr(ppos) << std::endl; std::cout << "pnum_str: " << pnum_str << std::endl; */ } } } } else if (_start_results && _screening && _new_link && strcasecmp(tag,"p") == 0) { _sum_flag = true; } } void se_parser_cuil::characters(parser_context *pc, const xmlChar *chars, int length) { handle_characters(pc, chars, length); } void se_parser_cuil::cdata(parser_context *pc, const xmlChar *chars, int length) { handle_characters(pc, chars, length); } void se_parser_cuil::handle_characters(parser_context *pc, const xmlChar *chars, int length) { if (_start_results && !_screening) return; else if (_sum_flag) { std::string a_chars = std::string((char*)chars); miscutil::replace_in_string(a_chars,"\n"," "); miscutil::replace_in_string(a_chars,"\r"," "); //miscutil::replace_in_string(a_chars,"-"," "); _summary += a_chars; } else if (_cite_flag) { std::string a_chars = std::string((char*)chars); miscutil::replace_in_string(a_chars,"\n"," "); miscutil::replace_in_string(a_chars,"\r"," "); _cite += a_chars; } } void se_parser_cuil::end_element(parser_context *pc, const xmlChar *name) { if (_start_results && !_screening) return; const char *tag = (const char*)name; if (_cite_flag && strcasecmp(tag,"a") == 0) { _cite_flag = false; pc->_current_snippet->_cite = _cite; _cite = ""; } else if (_pages && strcasecmp(tag,"div") == 0) _pages = false; } } /* end of namespace. */ <|endoftext|>
<commit_before>#ifdef R_OS_FREERTOS #include "RRealtimeTimer.h" #include "RScopedPointer.h" #include "RIsr.h" #include "RThread.h" #define RREALTIME_TIMER_WAIT_PASS(code) \ while(pdPASS != (code)) \ { \ RThread::yieldCurrentThread(); \ } static const int32_t sMaxDelayMS = static_cast<int32_t>(portMAX_DELAY) * portTICK_PERIOD_MS; RRealtimeTimer::RRealtimeTimer() : mHandle(NULL) , mIsSingleShot(false) , mExtended(0) #if (configUSE_16_BIT_TICKS == 1) , mExtendedCounter(0) #endif { // NOTE: Set timer run as idle task by default, but we can't set interval to // zero, otherwise the created timer will return to NULL, so we give value 1 . mHandle = xTimerCreate( "", 1, pdFALSE, // one-shot timer reinterpret_cast<void *>(0), _callback ); vTimerSetTimerID(mHandle, this); } RRealtimeTimer::~RRealtimeTimer() { RREALTIME_TIMER_WAIT_PASS(xTimerDelete(mHandle, portMAX_DELAY)); } int32_t RRealtimeTimer::interval() const { return static_cast<int32_t>(xTimerGetPeriod(mHandle)) * portTICK_PERIOD_MS #if (configUSE_16_BIT_TICKS == 1) * (mExtended + 1) #endif ; } bool RRealtimeTimer::isActive() const { return xTimerIsTimerActive(mHandle); } bool RRealtimeTimer::isSingleShot() const { return mIsSingleShot; } void RRealtimeTimer::setInterval(int32_t msec) { #if (configUSE_16_BIT_TICKS == 1) mExtended = static_cast<uint8_t>(msec / sMaxDelayMS); // A little trick to generate a fixed delay value, so that we needs not to // store the remainder msec /= (mExtended + 1); #endif msec /= portTICK_PERIOD_MS; if(msec <= 0) { msec = 1; } if(_rIsrExecuting()) { BaseType_t xHigherPriorityTaskWoken = pdFALSE; xTimerChangePeriodFromISR(mHandle, static_cast<rtime>(msec), &xHigherPriorityTaskWoken); // xTimerChangePeriod will cause timer start, so we need to stop it // immediately xHigherPriorityTaskWoken = pdFALSE; xTimerStopFromISR(mHandle, &xHigherPriorityTaskWoken); } else if(RThread::currentThreadId() == xTimerGetTimerDaemonTaskHandle()) { xTimerChangePeriod(mHandle, static_cast<rtime>(msec), 0); xTimerStop(mHandle, 0); } else { RREALTIME_TIMER_WAIT_PASS(xTimerChangePeriod( mHandle, static_cast<rtime>(msec), portMAX_DELAY)); RREALTIME_TIMER_WAIT_PASS(xTimerStop(mHandle, portMAX_DELAY)); } } void RRealtimeTimer::setSingleShot(bool singleShot) { mIsSingleShot = singleShot; } int RRealtimeTimer::timerId() const { // WARNING: We shorten handle to id value, but it may lead duplicate id values. return rShortenPtr(pvTimerGetTimerID(mHandle)); } void RRealtimeTimer::start() { #if (configUSE_16_BIT_TICKS == 1) mExtendedCounter.store(mExtended); #endif if(_rIsrExecuting()) { BaseType_t xHigherPriorityTaskWoken = pdFALSE; xTimerStartFromISR(mHandle, &xHigherPriorityTaskWoken); } else if(RThread::currentThreadId() == xTimerGetTimerDaemonTaskHandle()) { xTimerStart(mHandle, 0); } else { RREALTIME_TIMER_WAIT_PASS(xTimerStart(mHandle, portMAX_DELAY)); } } void RRealtimeTimer::start(int32_t msec) { setInterval(msec); start(); } void RRealtimeTimer::stop() { if(_rIsrExecuting()) { BaseType_t xHigherPriorityTaskWoken = pdFALSE; xTimerStopFromISR(mHandle, &xHigherPriorityTaskWoken); } else if(RThread::currentThreadId() == xTimerGetTimerDaemonTaskHandle()) { xTimerStop(mHandle, 0); } else { RREALTIME_TIMER_WAIT_PASS(xTimerStop(mHandle, portMAX_DELAY)); } } void RRealtimeTimer::run() { } bool RRealtimeTimer::_isRestartFromCallback() { return true; } void RRealtimeTimer::_redirectEvents() { } void RRealtimeTimer::_callback(TimerHandle_t handle) { auto self = static_cast<RRealtimeTimer *>(pvTimerGetTimerID(handle)); #if (configUSE_16_BIT_TICKS == 1) if(self->mExtendedCounter.addIfLargeThan(0, -1)) { // Do not use a block time if calling a timer API function from a // timer callback function, as doing so could cause a deadlock! xTimerStart(self->mHandle, 0); return; } #endif if(self->_isRestartFromCallback()) { self->run(); } else { // Do restart action inside event loop self->_redirectEvents(); return; } if(self->isSingleShot()) { return; } xTimerStart(self->mHandle, 0); } #endif // #ifdef R_OS_FREERTOS <commit_msg>Missing included RGlobal.h<commit_after>#include <RGlobal.h> #ifdef R_OS_FREERTOS #include "RRealtimeTimer.h" #include "RScopedPointer.h" #include "RIsr.h" #include "RThread.h" #define RREALTIME_TIMER_WAIT_PASS(code) \ while(pdPASS != (code)) \ { \ RThread::yieldCurrentThread(); \ } static const int32_t sMaxDelayMS = static_cast<int32_t>(portMAX_DELAY) * portTICK_PERIOD_MS; RRealtimeTimer::RRealtimeTimer() : mHandle(NULL) , mIsSingleShot(false) , mExtended(0) #if (configUSE_16_BIT_TICKS == 1) , mExtendedCounter(0) #endif { // NOTE: Set timer run as idle task by default, but we can't set interval to // zero, otherwise the created timer will return to NULL, so we give value 1 . mHandle = xTimerCreate( "", 1, pdFALSE, // one-shot timer reinterpret_cast<void *>(0), _callback ); vTimerSetTimerID(mHandle, this); } RRealtimeTimer::~RRealtimeTimer() { RREALTIME_TIMER_WAIT_PASS(xTimerDelete(mHandle, portMAX_DELAY)); } int32_t RRealtimeTimer::interval() const { return static_cast<int32_t>(xTimerGetPeriod(mHandle)) * portTICK_PERIOD_MS #if (configUSE_16_BIT_TICKS == 1) * (mExtended + 1) #endif ; } bool RRealtimeTimer::isActive() const { return xTimerIsTimerActive(mHandle); } bool RRealtimeTimer::isSingleShot() const { return mIsSingleShot; } void RRealtimeTimer::setInterval(int32_t msec) { #if (configUSE_16_BIT_TICKS == 1) mExtended = static_cast<uint8_t>(msec / sMaxDelayMS); // A little trick to generate a fixed delay value, so that we needs not to // store the remainder msec /= (mExtended + 1); #endif msec /= portTICK_PERIOD_MS; if(msec <= 0) { msec = 1; } if(_rIsrExecuting()) { BaseType_t xHigherPriorityTaskWoken = pdFALSE; xTimerChangePeriodFromISR(mHandle, static_cast<rtime>(msec), &xHigherPriorityTaskWoken); // xTimerChangePeriod will cause timer start, so we need to stop it // immediately xHigherPriorityTaskWoken = pdFALSE; xTimerStopFromISR(mHandle, &xHigherPriorityTaskWoken); } else if(RThread::currentThreadId() == xTimerGetTimerDaemonTaskHandle()) { xTimerChangePeriod(mHandle, static_cast<rtime>(msec), 0); xTimerStop(mHandle, 0); } else { RREALTIME_TIMER_WAIT_PASS(xTimerChangePeriod( mHandle, static_cast<rtime>(msec), portMAX_DELAY)); RREALTIME_TIMER_WAIT_PASS(xTimerStop(mHandle, portMAX_DELAY)); } } void RRealtimeTimer::setSingleShot(bool singleShot) { mIsSingleShot = singleShot; } int RRealtimeTimer::timerId() const { // WARNING: We shorten handle to id value, but it may lead duplicate id values. return rShortenPtr(pvTimerGetTimerID(mHandle)); } void RRealtimeTimer::start() { #if (configUSE_16_BIT_TICKS == 1) mExtendedCounter.store(mExtended); #endif if(_rIsrExecuting()) { BaseType_t xHigherPriorityTaskWoken = pdFALSE; xTimerStartFromISR(mHandle, &xHigherPriorityTaskWoken); } else if(RThread::currentThreadId() == xTimerGetTimerDaemonTaskHandle()) { xTimerStart(mHandle, 0); } else { RREALTIME_TIMER_WAIT_PASS(xTimerStart(mHandle, portMAX_DELAY)); } } void RRealtimeTimer::start(int32_t msec) { setInterval(msec); start(); } void RRealtimeTimer::stop() { if(_rIsrExecuting()) { BaseType_t xHigherPriorityTaskWoken = pdFALSE; xTimerStopFromISR(mHandle, &xHigherPriorityTaskWoken); } else if(RThread::currentThreadId() == xTimerGetTimerDaemonTaskHandle()) { xTimerStop(mHandle, 0); } else { RREALTIME_TIMER_WAIT_PASS(xTimerStop(mHandle, portMAX_DELAY)); } } void RRealtimeTimer::run() { } bool RRealtimeTimer::_isRestartFromCallback() { return true; } void RRealtimeTimer::_redirectEvents() { } void RRealtimeTimer::_callback(TimerHandle_t handle) { auto self = static_cast<RRealtimeTimer *>(pvTimerGetTimerID(handle)); #if (configUSE_16_BIT_TICKS == 1) if(self->mExtendedCounter.addIfLargeThan(0, -1)) { // Do not use a block time if calling a timer API function from a // timer callback function, as doing so could cause a deadlock! xTimerStart(self->mHandle, 0); return; } #endif if(self->_isRestartFromCallback()) { self->run(); } else { // Do restart action inside event loop self->_redirectEvents(); return; } if(self->isSingleShot()) { return; } xTimerStart(self->mHandle, 0); } #endif // #ifdef R_OS_FREERTOS <|endoftext|>
<commit_before> #include "voxel2stl.hpp" #include <omp.h> namespace voxel2stl { VoxelData::VoxelData(std::string filename, size_t anx, size_t any, size_t anz, double am, shared_ptr<spdlog::logger> alog) : nx(anx), ny(any), nz(anz), m(am), LoggedClass(alog) { log->debug("Voxeldata size is " + to_string(nx*ny*nz)); ifstream is(filename, ios::in | ios::binary); if (!is) { log->error("Voxel data file '" + filename + "' couldn't be loaded!"); log->flush(); throw exception(); } int num_threads; #pragma omp parallel { num_threads = omp_get_num_threads(); } char* buffer = (char*) malloc(nx*ny*nz); is.read(buffer,nx*ny*nz); // log->debug(std::string(buffer)); log->flush(); if(is) log->info("Voxel data read successfully."); else log->error("Error in reading of voxel data from file " + filename); log->flush(); is.close(); auto nx_old = nx; while (nx%num_threads) nx++; data.SetSize(nx*ny*nz); #pragma omp parallel for for(size_t i = 0; i < nx_old*ny*nz; i++) data[i] = (double) buffer[i]; // fill up for parallel computation #pragma omp parallel for for(size_t i = nx_old*ny*nz; i<nx*ny*nz; i++) data[i] = 0; free(buffer); } void VoxelData::WriteMaterials(const string & filename) const { log->debug("Start writing materials"); log->flush(); ofstream of; of.open(filename); for (auto i : Range(nx)) for (auto j : Range(ny)) for (auto k : Range(nz)) of << i*m << "," << j*m << "," << k*m << "," << (*this)(i,j,k) << endl; log->info("Coefficients written to file " + filename); of.close(); } void VoxelData::WriteMaterials(const string & filename, const Array<size_t>& region) const { log->debug("Start writing materials of regions:"); log->flush(); for(auto i : region) log->debug(i); ofstream of; of.open(filename); for (auto i : Range(std::max(size_t(0),region[0]),std::min(nx,region[1]))) for (auto j : Range(std::max(size_t(0),region[2]),std::min(ny,region[3]))) for (auto k : Range(std::max(size_t(0),region[4]),std::min(nz,region[5]))) of << i*m << "," << j*m << "," << k*m << "," << (*this)(i,j,k) << endl; log->info("Coefficients written to file " + filename); of.close(); } } <commit_msg>data to num thread alignment not necessary any more<commit_after> #include "voxel2stl.hpp" #include <omp.h> namespace voxel2stl { VoxelData::VoxelData(std::string filename, size_t anx, size_t any, size_t anz, double am, shared_ptr<spdlog::logger> alog) : nx(anx), ny(any), nz(anz), m(am), LoggedClass(alog) { log->debug("Voxeldata size is " + to_string(nx*ny*nz)); ifstream is(filename, ios::in | ios::binary); if (!is) { log->error("Voxel data file '" + filename + "' couldn't be loaded!"); log->flush(); throw exception(); } int num_threads; #pragma omp parallel { num_threads = omp_get_num_threads(); } char* buffer = (char*) malloc(nx*ny*nz); is.read(buffer,nx*ny*nz); // log->debug(std::string(buffer)); log->flush(); if(is) log->info("Voxel data read successfully."); else log->error("Error in reading of voxel data from file " + filename); log->flush(); is.close(); data.SetSize(nx*ny*nz); #pragma omp parallel for for(size_t i = 0; i < nx*ny*nz; i++) data[i] = (double) buffer[i]; free(buffer); } void VoxelData::WriteMaterials(const string & filename) const { log->debug("Start writing materials"); log->flush(); ofstream of; of.open(filename); for (auto i : Range(nx)) for (auto j : Range(ny)) for (auto k : Range(nz)) of << i*m << "," << j*m << "," << k*m << "," << (*this)(i,j,k) << endl; log->info("Coefficients written to file " + filename); of.close(); } void VoxelData::WriteMaterials(const string & filename, const Array<size_t>& region) const { log->debug("Start writing materials of regions:"); log->flush(); for(auto i : region) log->debug(i); ofstream of; of.open(filename); for (auto i : Range(std::max(size_t(0),region[0]),std::min(nx,region[1]))) for (auto j : Range(std::max(size_t(0),region[2]),std::min(ny,region[3]))) for (auto k : Range(std::max(size_t(0),region[4]),std::min(nz,region[5]))) of << i*m << "," << j*m << "," << k*m << "," << (*this)(i,j,k) << endl; log->info("Coefficients written to file " + filename); of.close(); } } <|endoftext|>
<commit_before>/* <x0/server.hpp> * * This file is part of the x0 web server, released under GPLv3. * (c) 2009 Chrisitan Parpart <trapni@gentoo.org> */ #ifndef sw_x0_server_h #define sw_x0_server_h #include <x0/config.hpp> #include <x0/logger.hpp> #include <x0/listener.hpp> #include <x0/handler.hpp> #include <x0/context.hpp> #include <x0/plugin.hpp> #include <x0/types.hpp> #include <boost/signals.hpp> #include <cstring> #include <string> #include <list> #include <map> namespace x0 { /** * \ingroup core * \brief implements the x0 web server. * * \see connection, request, response, plugin * \see server::start(), server::stop() */ class server : public boost::noncopyable { private: typedef std::pair<plugin_ptr, void *> plugin_value_t; typedef std::map<std::string, plugin_value_t> plugin_map_t; public: explicit server(boost::asio::io_service& io_service); ~server(); // {{{ service control /** configures this server as defined in the configuration section(s). */ void configure(); /** starts this server object by listening on new connections and processing them. */ void start(int argc, char *argv[]); /** pauses an already active server by not accepting further new connections until resumed. */ void pause(); /** resumes a currently paused server by continueing processing new connections. */ void resume(); /** reloads server configuration */ void reload(); /** gracefully stops a running server */ void stop(); // }}} // {{{ signals raised on request in order /** is invoked once a new client connection is established */ boost::signal<void(const connection_ptr&)> connection_open; /** is called at the very beginning of a request. */ boost::signal<void(request&)> pre_process; /** resolves document_root to use for this request. */ boost::signal<void(request&)> resolve_document_root; /** resolves request's physical filename (maps URI to physical path). */ boost::signal<void(request&)> resolve_entity; /** generates response content for this request being processed. */ handler generate_content; /** hook for generating accesslog logs and other things to be done after the request has been served. */ boost::signal<void(request&, response&)> request_done; /** is called at the very end of a request. */ boost::signal<void(request&, response&)> post_process; /** is called before a connection gets closed / or has been closed by remote point. */ boost::signal<void(const connection_ptr&)> connection_close; // }}} /** create server context data for given plugin. */ template<typename T> T& create_context(plugin *plug, T *d) { context_.set(plug, d); return context_.get<T>(plug); } /** retrieve server context data for given plugin. */ template<typename T> T& context(plugin *plug) { return context<T>(plug, "/"); } /** retrieve context data for given plugin at mapped file system path. * \param plug plugin data for which we want to retrieve the data for. * \param path mapped local file system path this context corresponds to. (e.g. "/var/www/") */ template<typename T> T& context(plugin *plug, const std::string& path) { return context_.get<T>(plug); } template<typename T> T *free_context(plugin *plug) { return context_.free<T>(plug); } x0::context& context() { return context_; } /** * retrieves reference to server currently loaded configuration. */ config& get_config(); /** * writes a log entry into the server's error log. */ void log(const char *filename, unsigned int line, severity s, const char *msg, ...); /** * sets up a TCP/IP listener on given bind_address and port. * * If there is already a listener on this bind_address:port pair * then no error will be raised. */ void setup_listener(int port, const std::string& bind_address = "0::0"); /** * loads a plugin into the server. * * \see plugin, unload_plugin(), loaded_plugins() */ void load_plugin(const std::string& name); /** safely unloads a plugin. */ void unload_plugin(const std::string& name); /** retrieves a list of currently loaded plugins */ std::vector<std::string> loaded_plugins() const; private: bool parse(int argc, char *argv[]); void drop_privileges(const std::string& user, const std::string& group); void daemonize(); static void reload_handler(int); static void terminate_handler(int); void handle_request(request& in, response& out); listener_ptr listener_by_port(int port); private: static server *instance_; x0::context context_; std::list<listener_ptr> listeners_; boost::asio::io_service& io_service_; bool paused_; config config_; std::string configfile_; int nofork_; logger_ptr logger_; plugin_map_t plugins_; }; #define LOG(srv, severity, message...) (srv).log(__FILENAME__, __LINE__, severity, message) } // namespace x0 #endif // vim:syntax=cpp <commit_msg>documenation-fu<commit_after>/* <x0/server.hpp> * * This file is part of the x0 web server, released under GPLv3. * (c) 2009 Chrisitan Parpart <trapni@gentoo.org> */ #ifndef sw_x0_server_h #define sw_x0_server_h #include <x0/config.hpp> #include <x0/logger.hpp> #include <x0/listener.hpp> #include <x0/handler.hpp> #include <x0/context.hpp> #include <x0/plugin.hpp> #include <x0/types.hpp> #include <boost/signals.hpp> #include <cstring> #include <string> #include <list> #include <map> namespace x0 { /** * \ingroup core * \brief implements the x0 web server. * * \see connection, request, response, plugin * \see server::start(), server::stop() */ class server : public boost::noncopyable { private: typedef std::pair<plugin_ptr, void *> plugin_value_t; typedef std::map<std::string, plugin_value_t> plugin_map_t; public: explicit server(boost::asio::io_service& io_service); ~server(); // {{{ service control /** configures this server as defined in the configuration section(s). */ void configure(); /** starts this server object by listening on new connections and processing them. */ void start(int argc, char *argv[]); /** pauses an already active server by not accepting further new connections until resumed. */ void pause(); /** resumes a currently paused server by continueing processing new connections. */ void resume(); /** reloads server configuration */ void reload(); /** gracefully stops a running server */ void stop(); // }}} // {{{ signals raised on request in order /** is invoked once a new client connection is established */ boost::signal<void(const connection_ptr&)> connection_open; /** is called at the very beginning of a request. */ boost::signal<void(request&)> pre_process; /** resolves document_root to use for this request. */ boost::signal<void(request&)> resolve_document_root; /** resolves request's physical filename (maps URI to physical path). */ boost::signal<void(request&)> resolve_entity; /** generates response content for this request being processed. */ handler generate_content; /** hook for generating accesslog logs and other things to be done after the request has been served. */ boost::signal<void(request&, response&)> request_done; /** is called at the very end of a request. */ boost::signal<void(request&, response&)> post_process; /** is called before a connection gets closed / or has been closed by remote point. */ boost::signal<void(const connection_ptr&)> connection_close; // }}} /** create server context data for given plugin. */ template<typename T> T& create_context(plugin *plug, T *d) { context_.set(plug, d); return context_.get<T>(plug); } /** retrieve server context data for given plugin. */ template<typename T> T& context(plugin *plug) { return context<T>(plug, "/"); } /** retrieve context data for given plugin at mapped file system path. * \param plug plugin data for which we want to retrieve the data for. * \param path mapped local file system path this context corresponds to. (e.g. "/var/www/") */ template<typename T> T& context(plugin *plug, const std::string& path) { return context_.get<T>(plug); } template<typename T> T *free_context(plugin *plug) { return context_.free<T>(plug); } /** retrieve the server configuration context. */ x0::context& context() { return context_; } /** * retrieves reference to server currently loaded configuration. */ config& get_config(); /** * writes a log entry into the server's error log. */ void log(const char *filename, unsigned int line, severity s, const char *msg, ...); /** * sets up a TCP/IP listener on given bind_address and port. * * If there is already a listener on this bind_address:port pair * then no error will be raised. */ void setup_listener(int port, const std::string& bind_address = "0::0"); /** * loads a plugin into the server. * * \see plugin, unload_plugin(), loaded_plugins() */ void load_plugin(const std::string& name); /** safely unloads a plugin. */ void unload_plugin(const std::string& name); /** retrieves a list of currently loaded plugins */ std::vector<std::string> loaded_plugins() const; private: bool parse(int argc, char *argv[]); void drop_privileges(const std::string& user, const std::string& group); void daemonize(); static void reload_handler(int); static void terminate_handler(int); void handle_request(request& in, response& out); listener_ptr listener_by_port(int port); private: static server *instance_; x0::context context_; std::list<listener_ptr> listeners_; boost::asio::io_service& io_service_; bool paused_; config config_; std::string configfile_; int nofork_; logger_ptr logger_; plugin_map_t plugins_; }; #define LOG(srv, severity, message...) (srv).log(__FILENAME__, __LINE__, severity, message) } // namespace x0 #endif // vim:syntax=cpp <|endoftext|>
<commit_before>// Copyright 2010 Gregory Szorc // // 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 <zippylog/zippylog.hpp> #include <zippylog/zippylogd/broker.hpp> #include <iostream> #include <string> using ::zippylog::zippylogd::Broker; using ::std::cout; using ::std::endl; using ::std::string; using ::std::vector; #ifdef LINUX static volatile sig_atomic_t active = 1; void signal_handler(int signo) { active = 0; signal(signo, SIG_DFL); } #endif int main(int argc, const char * const argv[]) { #ifdef LINUX signal(SIGINT, signal_handler); signal(SIGTERM, signal_handler); #endif try { ::zippylog::initialize_library(); //::zippylog::zippylogd::Zippylogd instance(params); //instance.Run(); // TODO remove broker code in favor of zippylogd class Broker broker(argv[1]); #ifdef LINUX broker.RunAsync(); while (active) pause(); #elif WINDOWS broker.Run(); #else #error "not implemented on this platform" #endif } catch (string s) { cout << "Exception:" << endl; cout << s; return 1; } catch (char * s) { cout << "Exception: " << s << endl; return 1; } catch (...) { cout << "received an exception" << endl; return 1; } ::zippylog::shutdown_library(); return 0; } <commit_msg>TODO on signal handling<commit_after>// Copyright 2010 Gregory Szorc // // 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 <zippylog/zippylog.hpp> #include <zippylog/zippylogd/broker.hpp> #include <iostream> #include <string> using ::zippylog::zippylogd::Broker; using ::std::cout; using ::std::endl; using ::std::string; using ::std::vector; #ifdef LINUX static volatile sig_atomic_t active = 1; void signal_handler(int signo) { active = 0; signal(signo, SIG_DFL); } #endif int main(int argc, const char * const argv[]) { #ifdef LINUX // TODO this signal handling is horribly naive signal(SIGINT, signal_handler); signal(SIGTERM, signal_handler); #endif try { ::zippylog::initialize_library(); //::zippylog::zippylogd::Zippylogd instance(params); //instance.Run(); // TODO remove broker code in favor of zippylogd class Broker broker(argv[1]); #ifdef LINUX broker.RunAsync(); while (active) pause(); #elif WINDOWS broker.Run(); #else #error "not implemented on this platform" #endif } catch (string s) { cout << "Exception:" << endl; cout << s; return 1; } catch (char * s) { cout << "Exception: " << s << endl; return 1; } catch (...) { cout << "received an exception" << endl; return 1; } ::zippylog::shutdown_library(); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ddefld.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2005-09-09 01:39:48 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _DDEFLD_HXX #define _DDEFLD_HXX #ifndef _LNKBASE_HXX //autogen #include <sfx2/lnkbase.hxx> #endif #ifndef INCLUDED_SWDLLAPI_H #include "swdllapi.h" #endif #ifndef _FLDBAS_HXX #include "fldbas.hxx" #endif class SwDoc; /*-------------------------------------------------------------------- Beschreibung: FieldType fuer DDE --------------------------------------------------------------------*/ class SW_DLLPUBLIC SwDDEFieldType : public SwFieldType { String aName; String aExpansion; ::sfx2::SvBaseLinkRef refLink; SwDoc* pDoc; USHORT nRefCnt; BOOL bCRLFFlag : 1; BOOL bDeleted : 1; SW_DLLPRIVATE void _RefCntChgd(); public: SwDDEFieldType( const String& rName, const String& rCmd, USHORT = sfx2::LINKUPDATE_ONCALL ); ~SwDDEFieldType(); const String& GetExpansion() const { return aExpansion; } void SetExpansion( const String& rStr ) { aExpansion = rStr, bCRLFFlag = FALSE; } virtual SwFieldType* Copy() const; virtual const String& GetName() const; virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMId ) const; virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMId ); String GetCmd() const; void SetCmd( const String& rStr ); USHORT GetType() const { return refLink->GetUpdateMode(); } void SetType( USHORT nType ) { refLink->SetUpdateMode( nType ); } BOOL IsDeleted() const { return bDeleted; } void SetDeleted( BOOL b ) { bDeleted = b; } BOOL IsConnected() const { return 0 != refLink->GetObj(); } void UpdateNow() { refLink->Update(); } void Disconnect() { refLink->Disconnect(); } const ::sfx2::SvBaseLink& GetBaseLink() const { return *refLink; } ::sfx2::SvBaseLink& GetBaseLink() { return *refLink; } const SwDoc* GetDoc() const { return pDoc; } SwDoc* GetDoc() { return pDoc; } void SetDoc( SwDoc* pDoc ); void IncRefCnt() { if( !nRefCnt++ && pDoc ) _RefCntChgd(); } void DecRefCnt() { if( !--nRefCnt && pDoc ) _RefCntChgd(); } void SetCRLFDelFlag( BOOL bFlag = TRUE ) { bCRLFFlag = bFlag; } BOOL IsCRLFDelFlag() const { return bCRLFFlag; } }; /*-------------------------------------------------------------------- Beschreibung: DDE-Feld --------------------------------------------------------------------*/ class SwDDEField : public SwField { public: SwDDEField(SwDDEFieldType*); ~SwDDEField(); virtual String Expand() const; virtual SwField* Copy() const; // ueber Typen Parameter ermitteln // Name kann nicht geaendert werden virtual const String& GetPar1() const; // Commando virtual String GetPar2() const; virtual void SetPar2(const String& rStr); }; #endif // _DDEFLD_HXX <commit_msg>INTEGRATION: CWS writercorehandoff (1.6.444); FILE MERGED 2005/09/13 11:20:10 tra 1.6.444.2: RESYNC: (1.6-1.7); FILE MERGED 2005/06/07 14:09:45 fme 1.6.444.1: #i50348# General cleanup - removed unused header files, functions, members, declarations etc.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ddefld.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2006-08-14 15:19:42 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _DDEFLD_HXX #define _DDEFLD_HXX #ifndef _LNKBASE_HXX //autogen #include <sfx2/lnkbase.hxx> #endif #ifndef INCLUDED_SWDLLAPI_H #include "swdllapi.h" #endif #ifndef _FLDBAS_HXX #include "fldbas.hxx" #endif class SwDoc; /*-------------------------------------------------------------------- Beschreibung: FieldType fuer DDE --------------------------------------------------------------------*/ class SW_DLLPUBLIC SwDDEFieldType : public SwFieldType { String aName; String aExpansion; ::sfx2::SvBaseLinkRef refLink; SwDoc* pDoc; USHORT nRefCnt; BOOL bCRLFFlag : 1; BOOL bDeleted : 1; SW_DLLPRIVATE void _RefCntChgd(); public: SwDDEFieldType( const String& rName, const String& rCmd, USHORT = sfx2::LINKUPDATE_ONCALL ); ~SwDDEFieldType(); const String& GetExpansion() const { return aExpansion; } void SetExpansion( const String& rStr ) { aExpansion = rStr, bCRLFFlag = FALSE; } virtual SwFieldType* Copy() const; virtual const String& GetName() const; virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMId ) const; virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMId ); String GetCmd() const; void SetCmd( const String& rStr ); USHORT GetType() const { return refLink->GetUpdateMode(); } void SetType( USHORT nType ) { refLink->SetUpdateMode( nType ); } BOOL IsDeleted() const { return bDeleted; } void SetDeleted( BOOL b ) { bDeleted = b; } void UpdateNow() { refLink->Update(); } void Disconnect() { refLink->Disconnect(); } const ::sfx2::SvBaseLink& GetBaseLink() const { return *refLink; } ::sfx2::SvBaseLink& GetBaseLink() { return *refLink; } const SwDoc* GetDoc() const { return pDoc; } SwDoc* GetDoc() { return pDoc; } void SetDoc( SwDoc* pDoc ); void IncRefCnt() { if( !nRefCnt++ && pDoc ) _RefCntChgd(); } void DecRefCnt() { if( !--nRefCnt && pDoc ) _RefCntChgd(); } void SetCRLFDelFlag( BOOL bFlag = TRUE ) { bCRLFFlag = bFlag; } }; /*-------------------------------------------------------------------- Beschreibung: DDE-Feld --------------------------------------------------------------------*/ class SwDDEField : public SwField { public: SwDDEField(SwDDEFieldType*); ~SwDDEField(); virtual String Expand() const; virtual SwField* Copy() const; // ueber Typen Parameter ermitteln // Name kann nicht geaendert werden virtual const String& GetPar1() const; // Commando virtual String GetPar2() const; virtual void SetPar2(const String& rStr); }; #endif // _DDEFLD_HXX <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: wdocsh.hxx,v $ * * $Revision: 1.11 $ * * last change: $Author: vg $ $Date: 2007-10-22 15:09:39 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SWWDOCSH_HXX #define _SWWDOCSH_HXX #ifndef INCLUDED_SWDLLAPI_H #include "swdllapi.h" #endif #ifndef _SWDOCSH_HXX #include "docsh.hxx" #endif #ifndef SW_SWDLL_HXX #include <swdll.hxx> #endif class SW_DLLPUBLIC SwWebDocShell: public SwDocShell { USHORT nSourcePara; // aktive Zeile in der SourceView public: using SotObject::GetInterface; // aber selbst implementieren SFX_DECL_INTERFACE(SW_WEBDOCSHELL) SFX_DECL_OBJECTFACTORY(); TYPEINFO(); SwWebDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED); ~SwWebDocShell(); virtual void FillClass( SvGlobalName * pClassName, sal_uInt32 * pClipFormat, String * pAppName, String * pLongUserName, String * pUserName, sal_Int32 nFileFormat ) const; USHORT GetSourcePara()const {return nSourcePara;} void SetSourcePara(USHORT nSet) {nSourcePara = nSet;} }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.11.216); FILE MERGED 2008/04/01 12:53:40 thb 1.11.216.2: #i85898# Stripping all external header guards 2008/03/31 16:52:46 rt 1.11.216.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: wdocsh.hxx,v $ * $Revision: 1.12 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SWWDOCSH_HXX #define _SWWDOCSH_HXX #include "swdllapi.h" #include "docsh.hxx" #include <swdll.hxx> class SW_DLLPUBLIC SwWebDocShell: public SwDocShell { USHORT nSourcePara; // aktive Zeile in der SourceView public: using SotObject::GetInterface; // aber selbst implementieren SFX_DECL_INTERFACE(SW_WEBDOCSHELL) SFX_DECL_OBJECTFACTORY(); TYPEINFO(); SwWebDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED); ~SwWebDocShell(); virtual void FillClass( SvGlobalName * pClassName, sal_uInt32 * pClipFormat, String * pAppName, String * pLongUserName, String * pUserName, sal_Int32 nFileFormat ) const; USHORT GetSourcePara()const {return nSourcePara;} void SetSourcePara(USHORT nSet) {nSourcePara = nSet;} }; #endif <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr> // // 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/. #ifndef EIGEN_NO_ASSERTION_CHECKING #define EIGEN_NO_ASSERTION_CHECKING #endif static int nb_temporaries; #define EIGEN_DENSE_STORAGE_CTOR_PLUGIN { if(size!=0) nb_temporaries++; } #include "main.h" #include <Eigen/Cholesky> #include <Eigen/QR> #define VERIFY_EVALUATION_COUNT(XPR,N) {\ nb_temporaries = 0; \ XPR; \ if(nb_temporaries!=N) std::cerr << "nb_temporaries == " << nb_temporaries << "\n"; \ VERIFY( (#XPR) && nb_temporaries==N ); \ } template<typename MatrixType,template <typename,int> class CholType> void test_chol_update(const MatrixType& symm) { typedef typename MatrixType::Scalar Scalar; typedef typename MatrixType::RealScalar RealScalar; typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType; MatrixType symmLo = symm.template triangularView<Lower>(); MatrixType symmUp = symm.template triangularView<Upper>(); MatrixType symmCpy = symm; CholType<MatrixType,Lower> chollo(symmLo); CholType<MatrixType,Upper> cholup(symmUp); for (int k=0; k<10; ++k) { VectorType vec = VectorType::Random(symm.rows()); RealScalar sigma = internal::random<RealScalar>(); symmCpy += sigma * vec * vec.adjoint(); // we are doing some downdates, so it might be the case that the matrix is not SPD anymore CholType<MatrixType,Lower> chol(symmCpy); if(chol.info()!=Success) break; chollo.rankUpdate(vec, sigma); VERIFY_IS_APPROX(symmCpy, chollo.reconstructedMatrix()); cholup.rankUpdate(vec, sigma); VERIFY_IS_APPROX(symmCpy, cholup.reconstructedMatrix()); } } template<typename MatrixType> void cholesky(const MatrixType& m) { typedef typename MatrixType::Index Index; /* this test covers the following files: LLT.h LDLT.h */ Index rows = m.rows(); Index cols = m.cols(); typedef typename MatrixType::Scalar Scalar; typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> SquareMatrixType; typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType; MatrixType a0 = MatrixType::Random(rows,cols); VectorType vecB = VectorType::Random(rows), vecX(rows); MatrixType matB = MatrixType::Random(rows,cols), matX(rows,cols); SquareMatrixType symm = a0 * a0.adjoint(); // let's make sure the matrix is not singular or near singular for (int k=0; k<3; ++k) { MatrixType a1 = MatrixType::Random(rows,cols); symm += a1 * a1.adjoint(); } SquareMatrixType symmUp = symm.template triangularView<Upper>(); SquareMatrixType symmLo = symm.template triangularView<Lower>(); // to test if really Cholesky only uses the upper triangular part, uncomment the following // FIXME: currently that fails !! //symm.template part<StrictlyLower>().setZero(); { LLT<SquareMatrixType,Lower> chollo(symmLo); VERIFY_IS_APPROX(symm, chollo.reconstructedMatrix()); vecX = chollo.solve(vecB); VERIFY_IS_APPROX(symm * vecX, vecB); matX = chollo.solve(matB); VERIFY_IS_APPROX(symm * matX, matB); // test the upper mode LLT<SquareMatrixType,Upper> cholup(symmUp); VERIFY_IS_APPROX(symm, cholup.reconstructedMatrix()); vecX = cholup.solve(vecB); VERIFY_IS_APPROX(symm * vecX, vecB); matX = cholup.solve(matB); VERIFY_IS_APPROX(symm * matX, matB); MatrixType neg = -symmLo; chollo.compute(neg); VERIFY(chollo.info()==NumericalIssue); VERIFY_IS_APPROX(MatrixType(chollo.matrixL().transpose().conjugate()), MatrixType(chollo.matrixU())); VERIFY_IS_APPROX(MatrixType(chollo.matrixU().transpose().conjugate()), MatrixType(chollo.matrixL())); VERIFY_IS_APPROX(MatrixType(cholup.matrixL().transpose().conjugate()), MatrixType(cholup.matrixU())); VERIFY_IS_APPROX(MatrixType(cholup.matrixU().transpose().conjugate()), MatrixType(cholup.matrixL())); } // LDLT { int sign = internal::random<int>()%2 ? 1 : -1; if(sign == -1) { symm = -symm; // test a negative matrix } SquareMatrixType symmUp = symm.template triangularView<Upper>(); SquareMatrixType symmLo = symm.template triangularView<Lower>(); LDLT<SquareMatrixType,Lower> ldltlo(symmLo); VERIFY_IS_APPROX(symm, ldltlo.reconstructedMatrix()); vecX = ldltlo.solve(vecB); VERIFY_IS_APPROX(symm * vecX, vecB); matX = ldltlo.solve(matB); VERIFY_IS_APPROX(symm * matX, matB); LDLT<SquareMatrixType,Upper> ldltup(symmUp); VERIFY_IS_APPROX(symm, ldltup.reconstructedMatrix()); vecX = ldltup.solve(vecB); VERIFY_IS_APPROX(symm * vecX, vecB); matX = ldltup.solve(matB); VERIFY_IS_APPROX(symm * matX, matB); VERIFY_IS_APPROX(MatrixType(ldltlo.matrixL().transpose().conjugate()), MatrixType(ldltlo.matrixU())); VERIFY_IS_APPROX(MatrixType(ldltlo.matrixU().transpose().conjugate()), MatrixType(ldltlo.matrixL())); VERIFY_IS_APPROX(MatrixType(ldltup.matrixL().transpose().conjugate()), MatrixType(ldltup.matrixU())); VERIFY_IS_APPROX(MatrixType(ldltup.matrixU().transpose().conjugate()), MatrixType(ldltup.matrixL())); if(MatrixType::RowsAtCompileTime==Dynamic) { // note : each inplace permutation requires a small temporary vector (mask) // check inplace solve matX = matB; VERIFY_EVALUATION_COUNT(matX = ldltlo.solve(matX), 0); VERIFY_IS_APPROX(matX, ldltlo.solve(matB).eval()); matX = matB; VERIFY_EVALUATION_COUNT(matX = ldltup.solve(matX), 0); VERIFY_IS_APPROX(matX, ldltup.solve(matB).eval()); } // restore if(sign == -1) symm = -symm; } // test some special use cases of SelfCwiseBinaryOp: MatrixType m1 = MatrixType::Random(rows,cols), m2(rows,cols); m2 = m1; m2 += symmLo.template selfadjointView<Lower>().llt().solve(matB); VERIFY_IS_APPROX(m2, m1 + symmLo.template selfadjointView<Lower>().llt().solve(matB)); m2 = m1; m2 -= symmLo.template selfadjointView<Lower>().llt().solve(matB); VERIFY_IS_APPROX(m2, m1 - symmLo.template selfadjointView<Lower>().llt().solve(matB)); m2 = m1; m2.noalias() += symmLo.template selfadjointView<Lower>().llt().solve(matB); VERIFY_IS_APPROX(m2, m1 + symmLo.template selfadjointView<Lower>().llt().solve(matB)); m2 = m1; m2.noalias() -= symmLo.template selfadjointView<Lower>().llt().solve(matB); VERIFY_IS_APPROX(m2, m1 - symmLo.template selfadjointView<Lower>().llt().solve(matB)); // update/downdate CALL_SUBTEST(( test_chol_update<SquareMatrixType,LLT>(symm) )); CALL_SUBTEST(( test_chol_update<SquareMatrixType,LDLT>(symm) )); } template<typename MatrixType> void cholesky_cplx(const MatrixType& m) { // classic test cholesky(m); // test mixing real/scalar types typedef typename MatrixType::Index Index; Index rows = m.rows(); Index cols = m.cols(); typedef typename MatrixType::Scalar Scalar; typedef typename NumTraits<Scalar>::Real RealScalar; typedef Matrix<RealScalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> RealMatrixType; typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType; RealMatrixType a0 = RealMatrixType::Random(rows,cols); VectorType vecB = VectorType::Random(rows), vecX(rows); MatrixType matB = MatrixType::Random(rows,cols), matX(rows,cols); RealMatrixType symm = a0 * a0.adjoint(); // let's make sure the matrix is not singular or near singular for (int k=0; k<3; ++k) { RealMatrixType a1 = RealMatrixType::Random(rows,cols); symm += a1 * a1.adjoint(); } { RealMatrixType symmLo = symm.template triangularView<Lower>(); LLT<RealMatrixType,Lower> chollo(symmLo); VERIFY_IS_APPROX(symm, chollo.reconstructedMatrix()); vecX = chollo.solve(vecB); VERIFY_IS_APPROX(symm * vecX, vecB); // matX = chollo.solve(matB); // VERIFY_IS_APPROX(symm * matX, matB); } // LDLT { int sign = internal::random<int>()%2 ? 1 : -1; if(sign == -1) { symm = -symm; // test a negative matrix } RealMatrixType symmLo = symm.template triangularView<Lower>(); LDLT<RealMatrixType,Lower> ldltlo(symmLo); VERIFY_IS_APPROX(symm, ldltlo.reconstructedMatrix()); vecX = ldltlo.solve(vecB); VERIFY_IS_APPROX(symm * vecX, vecB); // matX = ldltlo.solve(matB); // VERIFY_IS_APPROX(symm * matX, matB); } } // regression test for bug 241 template<typename MatrixType> void cholesky_bug241(const MatrixType& m) { eigen_assert(m.rows() == 2 && m.cols() == 2); typedef typename MatrixType::Scalar Scalar; typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType; MatrixType matA; matA << 1, 1, 1, 1; VectorType vecB; vecB << 1, 1; VectorType vecX = matA.ldlt().solve(vecB); VERIFY_IS_APPROX(matA * vecX, vecB); } // LDLT is not guaranteed to work for indefinite matrices, but happens to work fine if matrix is diagonal. // This test checks that LDLT reports correctly that matrix is indefinite. // See http://forum.kde.org/viewtopic.php?f=74&t=106942 template<typename MatrixType> void cholesky_indefinite(const MatrixType& m) { eigen_assert(m.rows() == 2 && m.cols() == 2); MatrixType mat; mat << 1, 0, 0, -1; LDLT<MatrixType> ldlt(mat); VERIFY(!ldlt.isNegative()); VERIFY(!ldlt.isPositive()); } template<typename MatrixType> void cholesky_verify_assert() { MatrixType tmp; LLT<MatrixType> llt; VERIFY_RAISES_ASSERT(llt.matrixL()) VERIFY_RAISES_ASSERT(llt.matrixU()) VERIFY_RAISES_ASSERT(llt.solve(tmp)) VERIFY_RAISES_ASSERT(llt.solveInPlace(&tmp)) LDLT<MatrixType> ldlt; VERIFY_RAISES_ASSERT(ldlt.matrixL()) VERIFY_RAISES_ASSERT(ldlt.permutationP()) VERIFY_RAISES_ASSERT(ldlt.vectorD()) VERIFY_RAISES_ASSERT(ldlt.isPositive()) VERIFY_RAISES_ASSERT(ldlt.isNegative()) VERIFY_RAISES_ASSERT(ldlt.solve(tmp)) VERIFY_RAISES_ASSERT(ldlt.solveInPlace(&tmp)) } void test_cholesky() { int s; for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_1( cholesky(Matrix<double,1,1>()) ); CALL_SUBTEST_3( cholesky(Matrix2d()) ); CALL_SUBTEST_3( cholesky_bug241(Matrix2d()) ); CALL_SUBTEST_3( cholesky_indefinite(Matrix2d()) ); CALL_SUBTEST_4( cholesky(Matrix3f()) ); CALL_SUBTEST_5( cholesky(Matrix4d()) ); s = internal::random<int>(1,EIGEN_TEST_MAX_SIZE); CALL_SUBTEST_2( cholesky(MatrixXd(s,s)) ); s = internal::random<int>(1,EIGEN_TEST_MAX_SIZE/2); CALL_SUBTEST_6( cholesky_cplx(MatrixXcd(s,s)) ); } CALL_SUBTEST_4( cholesky_verify_assert<Matrix3f>() ); CALL_SUBTEST_7( cholesky_verify_assert<Matrix3d>() ); CALL_SUBTEST_8( cholesky_verify_assert<MatrixXf>() ); CALL_SUBTEST_2( cholesky_verify_assert<MatrixXd>() ); // Test problem size constructors CALL_SUBTEST_9( LLT<MatrixXf>(10) ); CALL_SUBTEST_9( LDLT<MatrixXf>(10) ); EIGEN_UNUSED_VARIABLE(s) } <commit_msg>Add regression test for bug 608<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr> // // 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/. #ifndef EIGEN_NO_ASSERTION_CHECKING #define EIGEN_NO_ASSERTION_CHECKING #endif static int nb_temporaries; #define EIGEN_DENSE_STORAGE_CTOR_PLUGIN { if(size!=0) nb_temporaries++; } #include "main.h" #include <Eigen/Cholesky> #include <Eigen/QR> #define VERIFY_EVALUATION_COUNT(XPR,N) {\ nb_temporaries = 0; \ XPR; \ if(nb_temporaries!=N) std::cerr << "nb_temporaries == " << nb_temporaries << "\n"; \ VERIFY( (#XPR) && nb_temporaries==N ); \ } template<typename MatrixType,template <typename,int> class CholType> void test_chol_update(const MatrixType& symm) { typedef typename MatrixType::Scalar Scalar; typedef typename MatrixType::RealScalar RealScalar; typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType; MatrixType symmLo = symm.template triangularView<Lower>(); MatrixType symmUp = symm.template triangularView<Upper>(); MatrixType symmCpy = symm; CholType<MatrixType,Lower> chollo(symmLo); CholType<MatrixType,Upper> cholup(symmUp); for (int k=0; k<10; ++k) { VectorType vec = VectorType::Random(symm.rows()); RealScalar sigma = internal::random<RealScalar>(); symmCpy += sigma * vec * vec.adjoint(); // we are doing some downdates, so it might be the case that the matrix is not SPD anymore CholType<MatrixType,Lower> chol(symmCpy); if(chol.info()!=Success) break; chollo.rankUpdate(vec, sigma); VERIFY_IS_APPROX(symmCpy, chollo.reconstructedMatrix()); cholup.rankUpdate(vec, sigma); VERIFY_IS_APPROX(symmCpy, cholup.reconstructedMatrix()); } } template<typename MatrixType> void cholesky(const MatrixType& m) { typedef typename MatrixType::Index Index; /* this test covers the following files: LLT.h LDLT.h */ Index rows = m.rows(); Index cols = m.cols(); typedef typename MatrixType::Scalar Scalar; typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> SquareMatrixType; typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType; MatrixType a0 = MatrixType::Random(rows,cols); VectorType vecB = VectorType::Random(rows), vecX(rows); MatrixType matB = MatrixType::Random(rows,cols), matX(rows,cols); SquareMatrixType symm = a0 * a0.adjoint(); // let's make sure the matrix is not singular or near singular for (int k=0; k<3; ++k) { MatrixType a1 = MatrixType::Random(rows,cols); symm += a1 * a1.adjoint(); } SquareMatrixType symmUp = symm.template triangularView<Upper>(); SquareMatrixType symmLo = symm.template triangularView<Lower>(); // to test if really Cholesky only uses the upper triangular part, uncomment the following // FIXME: currently that fails !! //symm.template part<StrictlyLower>().setZero(); { LLT<SquareMatrixType,Lower> chollo(symmLo); VERIFY_IS_APPROX(symm, chollo.reconstructedMatrix()); vecX = chollo.solve(vecB); VERIFY_IS_APPROX(symm * vecX, vecB); matX = chollo.solve(matB); VERIFY_IS_APPROX(symm * matX, matB); // test the upper mode LLT<SquareMatrixType,Upper> cholup(symmUp); VERIFY_IS_APPROX(symm, cholup.reconstructedMatrix()); vecX = cholup.solve(vecB); VERIFY_IS_APPROX(symm * vecX, vecB); matX = cholup.solve(matB); VERIFY_IS_APPROX(symm * matX, matB); MatrixType neg = -symmLo; chollo.compute(neg); VERIFY(chollo.info()==NumericalIssue); VERIFY_IS_APPROX(MatrixType(chollo.matrixL().transpose().conjugate()), MatrixType(chollo.matrixU())); VERIFY_IS_APPROX(MatrixType(chollo.matrixU().transpose().conjugate()), MatrixType(chollo.matrixL())); VERIFY_IS_APPROX(MatrixType(cholup.matrixL().transpose().conjugate()), MatrixType(cholup.matrixU())); VERIFY_IS_APPROX(MatrixType(cholup.matrixU().transpose().conjugate()), MatrixType(cholup.matrixL())); } // LDLT { int sign = internal::random<int>()%2 ? 1 : -1; if(sign == -1) { symm = -symm; // test a negative matrix } SquareMatrixType symmUp = symm.template triangularView<Upper>(); SquareMatrixType symmLo = symm.template triangularView<Lower>(); LDLT<SquareMatrixType,Lower> ldltlo(symmLo); VERIFY_IS_APPROX(symm, ldltlo.reconstructedMatrix()); vecX = ldltlo.solve(vecB); VERIFY_IS_APPROX(symm * vecX, vecB); matX = ldltlo.solve(matB); VERIFY_IS_APPROX(symm * matX, matB); LDLT<SquareMatrixType,Upper> ldltup(symmUp); VERIFY_IS_APPROX(symm, ldltup.reconstructedMatrix()); vecX = ldltup.solve(vecB); VERIFY_IS_APPROX(symm * vecX, vecB); matX = ldltup.solve(matB); VERIFY_IS_APPROX(symm * matX, matB); VERIFY_IS_APPROX(MatrixType(ldltlo.matrixL().transpose().conjugate()), MatrixType(ldltlo.matrixU())); VERIFY_IS_APPROX(MatrixType(ldltlo.matrixU().transpose().conjugate()), MatrixType(ldltlo.matrixL())); VERIFY_IS_APPROX(MatrixType(ldltup.matrixL().transpose().conjugate()), MatrixType(ldltup.matrixU())); VERIFY_IS_APPROX(MatrixType(ldltup.matrixU().transpose().conjugate()), MatrixType(ldltup.matrixL())); if(MatrixType::RowsAtCompileTime==Dynamic) { // note : each inplace permutation requires a small temporary vector (mask) // check inplace solve matX = matB; VERIFY_EVALUATION_COUNT(matX = ldltlo.solve(matX), 0); VERIFY_IS_APPROX(matX, ldltlo.solve(matB).eval()); matX = matB; VERIFY_EVALUATION_COUNT(matX = ldltup.solve(matX), 0); VERIFY_IS_APPROX(matX, ldltup.solve(matB).eval()); } // restore if(sign == -1) symm = -symm; } // test some special use cases of SelfCwiseBinaryOp: MatrixType m1 = MatrixType::Random(rows,cols), m2(rows,cols); m2 = m1; m2 += symmLo.template selfadjointView<Lower>().llt().solve(matB); VERIFY_IS_APPROX(m2, m1 + symmLo.template selfadjointView<Lower>().llt().solve(matB)); m2 = m1; m2 -= symmLo.template selfadjointView<Lower>().llt().solve(matB); VERIFY_IS_APPROX(m2, m1 - symmLo.template selfadjointView<Lower>().llt().solve(matB)); m2 = m1; m2.noalias() += symmLo.template selfadjointView<Lower>().llt().solve(matB); VERIFY_IS_APPROX(m2, m1 + symmLo.template selfadjointView<Lower>().llt().solve(matB)); m2 = m1; m2.noalias() -= symmLo.template selfadjointView<Lower>().llt().solve(matB); VERIFY_IS_APPROX(m2, m1 - symmLo.template selfadjointView<Lower>().llt().solve(matB)); // update/downdate CALL_SUBTEST(( test_chol_update<SquareMatrixType,LLT>(symm) )); CALL_SUBTEST(( test_chol_update<SquareMatrixType,LDLT>(symm) )); } template<typename MatrixType> void cholesky_cplx(const MatrixType& m) { // classic test cholesky(m); // test mixing real/scalar types typedef typename MatrixType::Index Index; Index rows = m.rows(); Index cols = m.cols(); typedef typename MatrixType::Scalar Scalar; typedef typename NumTraits<Scalar>::Real RealScalar; typedef Matrix<RealScalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> RealMatrixType; typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType; RealMatrixType a0 = RealMatrixType::Random(rows,cols); VectorType vecB = VectorType::Random(rows), vecX(rows); MatrixType matB = MatrixType::Random(rows,cols), matX(rows,cols); RealMatrixType symm = a0 * a0.adjoint(); // let's make sure the matrix is not singular or near singular for (int k=0; k<3; ++k) { RealMatrixType a1 = RealMatrixType::Random(rows,cols); symm += a1 * a1.adjoint(); } { RealMatrixType symmLo = symm.template triangularView<Lower>(); LLT<RealMatrixType,Lower> chollo(symmLo); VERIFY_IS_APPROX(symm, chollo.reconstructedMatrix()); vecX = chollo.solve(vecB); VERIFY_IS_APPROX(symm * vecX, vecB); // matX = chollo.solve(matB); // VERIFY_IS_APPROX(symm * matX, matB); } // LDLT { int sign = internal::random<int>()%2 ? 1 : -1; if(sign == -1) { symm = -symm; // test a negative matrix } RealMatrixType symmLo = symm.template triangularView<Lower>(); LDLT<RealMatrixType,Lower> ldltlo(symmLo); VERIFY_IS_APPROX(symm, ldltlo.reconstructedMatrix()); vecX = ldltlo.solve(vecB); VERIFY_IS_APPROX(symm * vecX, vecB); // matX = ldltlo.solve(matB); // VERIFY_IS_APPROX(symm * matX, matB); } } // regression test for bug 241 template<typename MatrixType> void cholesky_bug241(const MatrixType& m) { eigen_assert(m.rows() == 2 && m.cols() == 2); typedef typename MatrixType::Scalar Scalar; typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType; MatrixType matA; matA << 1, 1, 1, 1; VectorType vecB; vecB << 1, 1; VectorType vecX = matA.ldlt().solve(vecB); VERIFY_IS_APPROX(matA * vecX, vecB); } // LDLT is not guaranteed to work for indefinite matrices, but happens to work fine if matrix is diagonal. // This test checks that LDLT reports correctly that matrix is indefinite. // See http://forum.kde.org/viewtopic.php?f=74&t=106942 template<typename MatrixType> void cholesky_indefinite(const MatrixType& m) { eigen_assert(m.rows() == 2 && m.cols() == 2); MatrixType mat; { mat << 1, 0, 0, -1; LDLT<MatrixType> ldlt(mat); VERIFY(!ldlt.isNegative()); VERIFY(!ldlt.isPositive()); } { mat << 1, 2, 2, 1; LDLT<MatrixType> ldlt(mat); VERIFY(!ldlt.isNegative()); VERIFY(!ldlt.isPositive()); } } template<typename MatrixType> void cholesky_verify_assert() { MatrixType tmp; LLT<MatrixType> llt; VERIFY_RAISES_ASSERT(llt.matrixL()) VERIFY_RAISES_ASSERT(llt.matrixU()) VERIFY_RAISES_ASSERT(llt.solve(tmp)) VERIFY_RAISES_ASSERT(llt.solveInPlace(&tmp)) LDLT<MatrixType> ldlt; VERIFY_RAISES_ASSERT(ldlt.matrixL()) VERIFY_RAISES_ASSERT(ldlt.permutationP()) VERIFY_RAISES_ASSERT(ldlt.vectorD()) VERIFY_RAISES_ASSERT(ldlt.isPositive()) VERIFY_RAISES_ASSERT(ldlt.isNegative()) VERIFY_RAISES_ASSERT(ldlt.solve(tmp)) VERIFY_RAISES_ASSERT(ldlt.solveInPlace(&tmp)) } void test_cholesky() { int s; for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_1( cholesky(Matrix<double,1,1>()) ); CALL_SUBTEST_3( cholesky(Matrix2d()) ); CALL_SUBTEST_3( cholesky_bug241(Matrix2d()) ); CALL_SUBTEST_3( cholesky_indefinite(Matrix2d()) ); CALL_SUBTEST_4( cholesky(Matrix3f()) ); CALL_SUBTEST_5( cholesky(Matrix4d()) ); s = internal::random<int>(1,EIGEN_TEST_MAX_SIZE); CALL_SUBTEST_2( cholesky(MatrixXd(s,s)) ); s = internal::random<int>(1,EIGEN_TEST_MAX_SIZE/2); CALL_SUBTEST_6( cholesky_cplx(MatrixXcd(s,s)) ); } CALL_SUBTEST_4( cholesky_verify_assert<Matrix3f>() ); CALL_SUBTEST_7( cholesky_verify_assert<Matrix3d>() ); CALL_SUBTEST_8( cholesky_verify_assert<MatrixXf>() ); CALL_SUBTEST_2( cholesky_verify_assert<MatrixXd>() ); // Test problem size constructors CALL_SUBTEST_9( LLT<MatrixXf>(10) ); CALL_SUBTEST_9( LDLT<MatrixXf>(10) ); EIGEN_UNUSED_VARIABLE(s) } <|endoftext|>
<commit_before>#include "application.h" #include <Tempest/SystemAPI> #include <Tempest/Event> #include <Tempest/Timer> #include <Tempest/Widget> #include <Tempest/Assert> #ifdef __WIN32 #include <windows.h> #endif #ifdef __ANDROID__ #include <unistd.h> #include <pthread.h> #endif #include <time.h> #include <iostream> using namespace Tempest; Application::App Application::app; Application::Application() { app.ret = -1; app.quit = false; SystemAPI::instance().startApplication(0); } Application::~Application() { SystemAPI::instance().endApplication(); T_ASSERT_X( Widget::count==0, "not all widgets was destroyed"); } int Application::exec() { execImpl(0); return app.ret; } bool Application::isQuit() { return app.quit; } void *Application::execImpl(void *) { while( !isQuit() ) { processEvents(); } return 0; } bool Application::processEvents( bool all ) { if( !app.quit ){ if( all ) app.ret = SystemAPI::instance().nextEvents(app.quit); else app.ret = SystemAPI::instance().nextEvent (app.quit); } processTimers(); return app.quit; } void Application::sleep(unsigned int msec) { #ifdef __WIN32 Sleep(msec); #else if( msec>=1000) sleep(msec/1000); if( msec%1000 ) usleep( 1000*(msec%1000) ); #endif } uint64_t Application::tickCount() { struct timespec now; clock_gettime(CLOCK_MONOTONIC, &now); return (uint8_t)now.tv_sec*1000LL + now.tv_nsec/1000000; } void Application::exit() { app.quit = true; } void Application::processTimers() { Application::App &a = app; for( size_t i=0; i<a.timer.size(); ++i ){ uint64_t t = tickCount(); uint64_t dt = (t-a.timer[i]->lastTimeout)/a.timer[i]->minterval; for( size_t r=0; r<dt && r<app.timer[i]->mrepeatCount; ++r ){ app.timer[i]->lastTimeout = t; app.timer[i]->timeout(); } } } <commit_msg>CLOCK_MONOTONIC_RAW<commit_after>#include "application.h" #include <Tempest/SystemAPI> #include <Tempest/Event> #include <Tempest/Timer> #include <Tempest/Widget> #include <Tempest/Assert> #ifdef __WIN32 #include <windows.h> #endif #ifdef __ANDROID__ #include <unistd.h> #include <pthread.h> #endif #include <time.h> #include <iostream> using namespace Tempest; Application::App Application::app; Application::Application() { app.ret = -1; app.quit = false; SystemAPI::instance().startApplication(0); } Application::~Application() { SystemAPI::instance().endApplication(); T_ASSERT_X( Widget::count==0, "not all widgets was destroyed"); } int Application::exec() { execImpl(0); return app.ret; } bool Application::isQuit() { return app.quit; } void *Application::execImpl(void *) { while( !isQuit() ) { processEvents(); } return 0; } bool Application::processEvents( bool all ) { if( !app.quit ){ if( all ) app.ret = SystemAPI::instance().nextEvents(app.quit); else app.ret = SystemAPI::instance().nextEvent (app.quit); } processTimers(); return app.quit; } void Application::sleep(unsigned int msec) { #ifdef __WIN32 Sleep(msec); #else if( msec>=1000) sleep(msec/1000); if( msec%1000 ) usleep( 1000*(msec%1000) ); #endif } uint64_t Application::tickCount() { timespec now; clock_gettime(CLOCK_MONOTONIC_RAW, &now); uint64_t t = (uint8_t)now.tv_sec; t *= 1000; t += now.tv_nsec/1000000; return t; } void Application::exit() { app.quit = true; } void Application::processTimers() { Application::App &a = app; for( size_t i=0; i<a.timer.size(); ++i ){ uint64_t t = tickCount(); uint64_t dt = (t-a.timer[i]->lastTimeout)/a.timer[i]->minterval; for( size_t r=0; r<dt && r<app.timer[i]->mrepeatCount; ++r ){ app.timer[i]->lastTimeout = t; app.timer[i]->timeout(); } } } <|endoftext|>
<commit_before>// This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_HDD_TEST_LINEARELLIPTIC_BLOCK_SWIPDG_EXPECTATIONS_HH #define DUNE_HDD_TEST_LINEARELLIPTIC_BLOCK_SWIPDG_EXPECTATIONS_HH #include <dune/stuff/common/disable_warnings.hh> # if HAVE_ALUGRID # include <dune/grid/alugrid.hh> # endif #include <dune/stuff/common/reenable_warnings.hh> #include <dune/stuff/test/gtest/gtest.h> #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/type_utils.hh> namespace Dune { namespace HDD { namespace LinearElliptic { namespace TestCases { // forwards template< class GridType > class ESV2007; namespace OS2014 { template< class GridType > class ParametricConvergence; } // namespace OS2014 #if HAVE_DUNE_GRID_MULTISCALE template< class GridType > class ESV2007Multiscale; namespace OS2014 { template< class GridType > class ParametricBlockConvergence; } // namespace OS2014 #endif // HAVE_DUNE_GRID_MULTISCALE } // namespace TestCases namespace Tests { namespace internal { template< class TestCaseType, int polOrder > class BlockSWIPDGStudyExpectationsBase { public: static size_t rate(const TestCaseType& /*test_case*/, const std::string type) { if (type == "L2") return polOrder + 1; else if (type == "H1_semi") return polOrder; else if (type.substr(0, 6) == "energy") return polOrder; else if (type == "eta_NC_OS2014") return polOrder; else if (type.substr(0, 12) == "eta_R_OS2014") return polOrder + 1; else if (type.substr(0, 13) == "eta_DF_OS2014") return polOrder; else if (type == "eta_OS2014") return polOrder; else if (type == "eta_OS2014_*") return polOrder; else if (type.substr(0, 10) == "eff_OS2014") return 0; else if (type.substr(0, 12) == "eff_OS2014_*") return 0; else EXPECT_TRUE(false) << "expected rate missing for type: " << type; return 0; } // ... rate(...) }; // class BlockSWIPDGStudyExpectationsBase } // namespace internal template< class TestCaseType, int polOrder = 1, bool anything = true > class BlockSWIPDGStudyExpectations : public internal::BlockSWIPDGStudyExpectationsBase< TestCaseType, polOrder > { public: static std::vector< double > results(const TestCaseType& /*test_case*/, const std::string type) { EXPECT_TRUE(false) << "Please record the expected results for\n" << "TestCaseType: " << Stuff::Common::Typename< TestCaseType >::value() << "\n" << "polOrder: " << polOrder << "\n" << "type: " << type << "\n" << "Please put an appropriate specialiaztion of BlockSWIPDGStudyExpectations for this TestCaseType " << "in a separate object file (see examples below) or add\n" << " 'template class BlockSWIPDGStudyExpectations< TestCaseType, " << polOrder << " >'\n" << "for this polOrder in the appropriate object file!\n\n" << "Oh: and do not forget to add\n" << " 'extern template class BlockSWIPDGStudyExpectations< ... >'\n" << "to each test source using these results!"; return {}; } // ... results(...) }; // BlockSWIPDGStudyExpectations } // namespace Tests } // namespace LinearElliptic } // namespace HDD } // namespace Dune #endif // DUNE_HDD_TEST_LINEARELLIPTIC_BLOCK_SWIPDG_EXPECTATIONS_HH <commit_msg>[test...block-swipdg-expectations] update rates<commit_after>// This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_HDD_TEST_LINEARELLIPTIC_BLOCK_SWIPDG_EXPECTATIONS_HH #define DUNE_HDD_TEST_LINEARELLIPTIC_BLOCK_SWIPDG_EXPECTATIONS_HH #include <dune/stuff/common/disable_warnings.hh> # if HAVE_ALUGRID # include <dune/grid/alugrid.hh> # endif #include <dune/stuff/common/reenable_warnings.hh> #include <dune/stuff/test/gtest/gtest.h> #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/type_utils.hh> namespace Dune { namespace HDD { namespace LinearElliptic { namespace TestCases { // forwards template< class GridType > class ESV2007; namespace OS2014 { template< class GridType > class ParametricConvergence; } // namespace OS2014 #if HAVE_DUNE_GRID_MULTISCALE template< class GridType > class ESV2007Multiscale; namespace OS2014 { template< class GridType > class ParametricBlockConvergence; } // namespace OS2014 #endif // HAVE_DUNE_GRID_MULTISCALE } // namespace TestCases namespace Tests { namespace internal { template< class TestCaseType, int polOrder > class BlockSWIPDGStudyExpectationsBase { public: static size_t rate(const TestCaseType& test_case, const std::string type) { const auto partitioning = test_case.partitioning(); if (type == "L2") return polOrder + 1; else if (type == "H1_semi" || type.substr(0, 6) == "energy") return polOrder; else if (type == "eta_NC_OS2014") return polOrder; else if (type.substr(0, 12) == "eta_R_OS2014") { if (partitioning.size() >= 8 && partitioning.substr(partitioning.size() - 8) == "H_with_h") return polOrder + 1; else return polOrder; } else if (type.substr(0, 13) == "eta_DF_OS2014") return polOrder; else if (type.substr(0, 10) == "eta_OS2014") return polOrder; else if (type.substr(0, 10) == "eff_OS2014") return 0; else EXPECT_TRUE(false) << "expected rate missing for type: " << type; return 0; } // ... rate(...) }; // class BlockSWIPDGStudyExpectationsBase } // namespace internal template< class TestCaseType, int polOrder = 1, bool anything = true > class BlockSWIPDGStudyExpectations : public internal::BlockSWIPDGStudyExpectationsBase< TestCaseType, polOrder > { public: static std::vector< double > results(const TestCaseType& /*test_case*/, const std::string type) { EXPECT_TRUE(false) << "Please record the expected results for\n" << "TestCaseType: " << Stuff::Common::Typename< TestCaseType >::value() << "\n" << "polOrder: " << polOrder << "\n" << "type: " << type << "\n" << "Please put an appropriate specialiaztion of BlockSWIPDGStudyExpectations for this TestCaseType " << "in a separate object file (see examples below) or add\n" << " 'template class BlockSWIPDGStudyExpectations< TestCaseType, " << polOrder << " >'\n" << "for this polOrder in the appropriate object file!\n\n" << "Oh: and do not forget to add\n" << " 'extern template class BlockSWIPDGStudyExpectations< ... >'\n" << "to each test source using these results!"; return {}; } // ... results(...) }; // BlockSWIPDGStudyExpectations } // namespace Tests } // namespace LinearElliptic } // namespace HDD } // namespace Dune #endif // DUNE_HDD_TEST_LINEARELLIPTIC_BLOCK_SWIPDG_EXPECTATIONS_HH <|endoftext|>
<commit_before>// // foundation.cpp // TraceRay // // Created by LazyLie on 15/6/16. // Copyright (c) 2015年 LeonardXu. All rights reserved. // #include "foundation.h" const double EPS = 1e-8; const double INFD = 1e10; const int THREAD_NUM = 20; const double PI = 3.1415926536; Vector::Vector() { x = y = z = 0; } Vector::Vector(double _x, double _y, double _z) { x = _x; y = _y; z = _z; } double& Vector::operator [] (const int id) { assert(0 <= id && id < 3); return (id == 0) ? x : (id == 1) ? y : z; } double Vector::operator [] (const int id) const { assert(0 <= id && id < 3); return (id == 0) ? x : (id == 1) ? y : z; } double norm(const Vector &v) { return sqrt(v.x * v.x + v.y * v.y + v.z * v.z); } Vector operator - (const Vector &a) { return Vector(-a.x, -a.y, -a.z); } Vector operator + (const Vector &a, const Vector &b) { return Vector(a.x + b.x, a.y + b.y, a.z + b.z); } Vector operator - (const Vector &a, const Vector &b) { return Vector(a.x - b.x, a.y - b.y, a.z - b.z); } Vector operator * (const double a, const Vector &b) { return Vector(a * b.x, a * b.y, a * b.z); } Vector operator * (const Vector &a, const double b) { return Vector(a.x * b, a.y * b, a.z * b); } Vector operator * (const Vector &a, const Vector &b) { return Vector(a.x * b.x, a.y * b.y, a.z * b.z); } Vector operator / (const Vector &a, const double b) { return Vector(a.x / b, a.y / b, a.z / b); } double innerProduct(const Vector &a, const Vector &b) { return a.x * b.x + a.y * b.y + a.z * b.z; } Vector crossProduct(const Vector &a, const Vector &b) { return Vector(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x); }<commit_msg>thread num<commit_after>// // foundation.cpp // TraceRay // // Created by LazyLie on 15/6/16. // Copyright (c) 2015年 LeonardXu. All rights reserved. // #include "foundation.h" const double EPS = 1e-8; const double INFD = 1e10; const int THREAD_NUM = 12; const double PI = 3.1415926536; Vector::Vector() { x = y = z = 0; } Vector::Vector(double _x, double _y, double _z) { x = _x; y = _y; z = _z; } double& Vector::operator [] (const int id) { assert(0 <= id && id < 3); return (id == 0) ? x : (id == 1) ? y : z; } double Vector::operator [] (const int id) const { assert(0 <= id && id < 3); return (id == 0) ? x : (id == 1) ? y : z; } double norm(const Vector &v) { return sqrt(v.x * v.x + v.y * v.y + v.z * v.z); } Vector operator - (const Vector &a) { return Vector(-a.x, -a.y, -a.z); } Vector operator + (const Vector &a, const Vector &b) { return Vector(a.x + b.x, a.y + b.y, a.z + b.z); } Vector operator - (const Vector &a, const Vector &b) { return Vector(a.x - b.x, a.y - b.y, a.z - b.z); } Vector operator * (const double a, const Vector &b) { return Vector(a * b.x, a * b.y, a * b.z); } Vector operator * (const Vector &a, const double b) { return Vector(a.x * b, a.y * b, a.z * b); } Vector operator * (const Vector &a, const Vector &b) { return Vector(a.x * b.x, a.y * b.y, a.z * b.z); } Vector operator / (const Vector &a, const double b) { return Vector(a.x / b, a.y / b, a.z / b); } double innerProduct(const Vector &a, const Vector &b) { return a.x * b.x + a.y * b.y + a.z * b.z; } Vector crossProduct(const Vector &a, const Vector &b) { return Vector(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x); }<|endoftext|>
<commit_before>/* ======================================================================= Copyright (c) 2011, Institute for Microelectronics, Institute for Analysis and Scientific Computing, TU Wien. ----------------- ViennaGrid - The Vienna Grid Library ----------------- Authors: Karl Rupp rupp@iue.tuwien.ac.at Josef Weinbub weinbub@iue.tuwien.ac.at (A list of additional contributors can be found in the PDF manual) License: MIT (X11), see file LICENSE in the base directory ======================================================================= */ //*********************************************** // Define the input-file format //*********************************************** #include "viennagrid/forwards.hpp" #include "viennagrid/config/default_configs.hpp" #include "viennagrid/algorithm/refine.hpp" #include "viennagrid/algorithm/spanned_volume.hpp" #include "viennagrid/algorithm/volume.hpp" // Helper: Remove all refinement tags on a cell // template <typename CellType> // void clear_refinement_tag(CellType & cell) // { // typedef typename CellType::config_type ConfigType; // typedef typename viennagrid::result_of::vertex<ConfigType>::type VertexType; // typedef typename viennagrid::result_of::line_range<CellType>::type EdgeOnCellContainer; // typedef typename viennagrid::result_of::iterator<EdgeOnCellContainer>::type EdgeOnCellIterator; // // EdgeOnCellContainer edges = viennagrid::elements(cell); // for(EdgeOnCellIterator eocit = edges.begin(); // eocit != edges.end(); // ++eocit) // { // viennadata::access<viennagrid::refinement_key, bool>(viennagrid::refinement_key())(*eocit) = false; // } // // viennadata::access<viennagrid::refinement_key, bool>(viennagrid::refinement_key())(cell) = false; // } // Helper: Remove all refinement tags on a cell template <typename CellType, typename EdgeRefinementTagAccessorT> void print_refinement_edges(CellType & cell, EdgeRefinementTagAccessorT const edge_refinement_tag_accessor) { // typedef typename CellType::config_type ConfigType; typedef typename viennagrid::result_of::vertex<CellType>::type VertexType; typedef typename viennagrid::result_of::line_range<CellType>::type EdgeOnCellContainer; typedef typename viennagrid::result_of::iterator<EdgeOnCellContainer>::type EdgeOnCellIterator; EdgeOnCellContainer edges = viennagrid::elements(cell); for(EdgeOnCellIterator eocit = edges.begin(); eocit != edges.end(); ++eocit) { // if (viennadata::access<viennagrid::refinement_key, bool>(viennagrid::refinement_key())(*eocit) == true) if (edge_refinement_tag_accessor(*eocit)) std::cout << *eocit << std::endl; //eocit->print_short(); } } template <typename MeshType> double mesh_surface(MeshType & mesh) { typedef typename viennagrid::result_of::cell_tag<MeshType>::type CellTag; typedef typename viennagrid::result_of::facet<MeshType>::type FacetType; typedef typename viennagrid::result_of::cell<MeshType>::type CellType; typedef typename viennagrid::result_of::cell_range<MeshType>::type CellContainer; typedef typename viennagrid::result_of::iterator<CellContainer>::type CellIterator; typedef typename viennagrid::result_of::facet_range<CellType>::type FacetOnCellContainer; typedef typename viennagrid::result_of::iterator<FacetOnCellContainer>::type FacetOnCellIterator; typedef std::map<FacetType *, std::size_t> CellFacetMap; CellFacetMap cell_on_facet_cnt; CellContainer cells = viennagrid::elements(mesh); for (CellIterator cit = cells.begin(); cit != cells.end(); ++cit) { FacetOnCellContainer facets = viennagrid::elements(*cit); for (FacetOnCellIterator focit = facets.begin(); focit != facets.end(); ++focit) { cell_on_facet_cnt[&(*focit)] += 1; } } double mesh_surface = 0; for (typename CellFacetMap::iterator cfmit = cell_on_facet_cnt.begin(); cfmit != cell_on_facet_cnt.end(); ++cfmit) { if (cfmit->second == 1) { mesh_surface += viennagrid::volume(*(cfmit->first)); } } return mesh_surface; } template <typename MeshType> int facet_check(MeshType & mesh) { typedef typename viennagrid::result_of::cell_tag<MeshType>::type CellTag; typedef typename viennagrid::result_of::facet<MeshType>::type FacetType; typedef typename viennagrid::result_of::cell<MeshType>::type CellType; typedef typename viennagrid::result_of::facet_range<MeshType>::type FacetContainer; typedef typename viennagrid::result_of::iterator<FacetContainer>::type FacetIterator; typedef typename viennagrid::result_of::cell_range<MeshType>::type CellContainer; typedef typename viennagrid::result_of::iterator<CellContainer>::type CellIterator; typedef typename viennagrid::result_of::facet_range<CellType>::type FacetOnCellContainer; typedef typename viennagrid::result_of::iterator<FacetOnCellContainer>::type FacetOnCellIterator; typedef std::map<FacetType *, std::size_t> CellFacetMap; CellFacetMap cell_on_facet_cnt; CellContainer cells = viennagrid::elements(mesh); for (CellIterator cit = cells.begin(); cit != cells.end(); ++cit) { FacetOnCellContainer facets = viennagrid::elements(*cit); for (FacetOnCellIterator focit = facets.begin(); focit != facets.end(); ++focit) { cell_on_facet_cnt[&(*focit)] += 1; } } for (typename CellFacetMap::iterator cfmit = cell_on_facet_cnt.begin(); cfmit != cell_on_facet_cnt.end(); ++cfmit) { if (cfmit->second > 2) { std::cerr << "Topology problem for facet: " << std::endl; std::cout << *(cfmit->first) << std::endl; CellContainer cells = viennagrid::elements(mesh); for (CellIterator cit = cells.begin(); cit != cells.end(); ++cit) { std::cout << "Cell: "; std::cout << *cit << std::endl; } FacetContainer facets = viennagrid::elements(mesh); for (FacetIterator fit = facets.begin(); fit != facets.end(); ++fit) { std::cout << "Facet: "; std::cout << *fit << std::endl; } return EXIT_FAILURE; } } return EXIT_SUCCESS; } template <typename MeshType> int surface_check(MeshType & mesh_old, MeshType & mesh_new) { typedef typename viennagrid::result_of::cell_tag<MeshType>::type CellTag; typedef typename viennagrid::result_of::facet<MeshType>::type FacetType; typedef typename viennagrid::result_of::cell<MeshType>::type CellType; typedef typename viennagrid::result_of::facet_range<MeshType>::type FacetContainer; typedef typename viennagrid::result_of::iterator<FacetContainer>::type FacetIterator; typedef typename viennagrid::result_of::cell_range<MeshType>::type CellContainer; typedef typename viennagrid::result_of::iterator<CellContainer>::type CellIterator; double old_surface = mesh_surface(mesh_old); double new_surface = mesh_surface(mesh_new); if ( (new_surface < 0.9999 * old_surface) || (new_surface > 1.0001 * old_surface) ) { CellContainer cells = viennagrid::elements(mesh_new); for (CellIterator cit = cells.begin(); cit != cells.end(); ++cit) { std::cout << "Cell: "; std::cout << *cit << std::endl; } FacetContainer facets = viennagrid::elements(mesh_new); for (FacetIterator fit = facets.begin(); fit != facets.end(); ++fit) { std::cout << "Facet: "; std::cout << *fit << std::endl; } std::cerr << "Surface check failed!" << std::endl; std::cerr << "Mesh surface before refinement: " << old_surface << std::endl; std::cerr << "Mesh surface after refinement: " << new_surface << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } template <typename MeshType> int volume_check(MeshType & mesh_old, MeshType & mesh_new) { double old_volume = viennagrid::volume(mesh_old); double new_volume = viennagrid::volume(mesh_new); if ( (new_volume < 0.9999 * old_volume) || (new_volume > 1.0001 * old_volume) ) { std::cerr << "Volume check failed!" << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } template <typename MeshType> int sanity_check(MeshType & mesh_old, MeshType & mesh_new) { if (facet_check(mesh_new) != EXIT_SUCCESS) return EXIT_FAILURE; //check for sane topology in new mesh if (surface_check(mesh_old, mesh_new) != EXIT_SUCCESS) return EXIT_FAILURE; //check for same surface if (volume_check(mesh_old, mesh_new) != EXIT_SUCCESS) return EXIT_FAILURE; return EXIT_SUCCESS; } <commit_msg>Added newline<commit_after>/* ======================================================================= Copyright (c) 2011, Institute for Microelectronics, Institute for Analysis and Scientific Computing, TU Wien. ----------------- ViennaGrid - The Vienna Grid Library ----------------- Authors: Karl Rupp rupp@iue.tuwien.ac.at Josef Weinbub weinbub@iue.tuwien.ac.at (A list of additional contributors can be found in the PDF manual) License: MIT (X11), see file LICENSE in the base directory ======================================================================= */ //*********************************************** // Define the input-file format //*********************************************** #include "viennagrid/forwards.hpp" #include "viennagrid/config/default_configs.hpp" #include "viennagrid/algorithm/refine.hpp" #include "viennagrid/algorithm/spanned_volume.hpp" #include "viennagrid/algorithm/volume.hpp" // Helper: Remove all refinement tags on a cell // template <typename CellType> // void clear_refinement_tag(CellType & cell) // { // typedef typename CellType::config_type ConfigType; // typedef typename viennagrid::result_of::vertex<ConfigType>::type VertexType; // typedef typename viennagrid::result_of::line_range<CellType>::type EdgeOnCellContainer; // typedef typename viennagrid::result_of::iterator<EdgeOnCellContainer>::type EdgeOnCellIterator; // // EdgeOnCellContainer edges = viennagrid::elements(cell); // for(EdgeOnCellIterator eocit = edges.begin(); // eocit != edges.end(); // ++eocit) // { // viennadata::access<viennagrid::refinement_key, bool>(viennagrid::refinement_key())(*eocit) = false; // } // // viennadata::access<viennagrid::refinement_key, bool>(viennagrid::refinement_key())(cell) = false; // } // Helper: Remove all refinement tags on a cell template <typename CellType, typename EdgeRefinementTagAccessorT> void print_refinement_edges(CellType & cell, EdgeRefinementTagAccessorT const edge_refinement_tag_accessor) { // typedef typename CellType::config_type ConfigType; typedef typename viennagrid::result_of::vertex<CellType>::type VertexType; typedef typename viennagrid::result_of::line_range<CellType>::type EdgeOnCellContainer; typedef typename viennagrid::result_of::iterator<EdgeOnCellContainer>::type EdgeOnCellIterator; EdgeOnCellContainer edges = viennagrid::elements(cell); for(EdgeOnCellIterator eocit = edges.begin(); eocit != edges.end(); ++eocit) { // if (viennadata::access<viennagrid::refinement_key, bool>(viennagrid::refinement_key())(*eocit) == true) if (edge_refinement_tag_accessor(*eocit)) std::cout << *eocit << std::endl; //eocit->print_short(); } } template <typename MeshType> double mesh_surface(MeshType & mesh) { typedef typename viennagrid::result_of::cell_tag<MeshType>::type CellTag; typedef typename viennagrid::result_of::facet<MeshType>::type FacetType; typedef typename viennagrid::result_of::cell<MeshType>::type CellType; typedef typename viennagrid::result_of::cell_range<MeshType>::type CellContainer; typedef typename viennagrid::result_of::iterator<CellContainer>::type CellIterator; typedef typename viennagrid::result_of::facet_range<CellType>::type FacetOnCellContainer; typedef typename viennagrid::result_of::iterator<FacetOnCellContainer>::type FacetOnCellIterator; typedef std::map<FacetType *, std::size_t> CellFacetMap; CellFacetMap cell_on_facet_cnt; CellContainer cells = viennagrid::elements(mesh); for (CellIterator cit = cells.begin(); cit != cells.end(); ++cit) { FacetOnCellContainer facets = viennagrid::elements(*cit); for (FacetOnCellIterator focit = facets.begin(); focit != facets.end(); ++focit) { cell_on_facet_cnt[&(*focit)] += 1; } } double mesh_surface = 0; for (typename CellFacetMap::iterator cfmit = cell_on_facet_cnt.begin(); cfmit != cell_on_facet_cnt.end(); ++cfmit) { if (cfmit->second == 1) { mesh_surface += viennagrid::volume(*(cfmit->first)); } } return mesh_surface; } template <typename MeshType> int facet_check(MeshType & mesh) { typedef typename viennagrid::result_of::cell_tag<MeshType>::type CellTag; typedef typename viennagrid::result_of::facet<MeshType>::type FacetType; typedef typename viennagrid::result_of::cell<MeshType>::type CellType; typedef typename viennagrid::result_of::facet_range<MeshType>::type FacetContainer; typedef typename viennagrid::result_of::iterator<FacetContainer>::type FacetIterator; typedef typename viennagrid::result_of::cell_range<MeshType>::type CellContainer; typedef typename viennagrid::result_of::iterator<CellContainer>::type CellIterator; typedef typename viennagrid::result_of::facet_range<CellType>::type FacetOnCellContainer; typedef typename viennagrid::result_of::iterator<FacetOnCellContainer>::type FacetOnCellIterator; typedef std::map<FacetType *, std::size_t> CellFacetMap; CellFacetMap cell_on_facet_cnt; CellContainer cells = viennagrid::elements(mesh); for (CellIterator cit = cells.begin(); cit != cells.end(); ++cit) { FacetOnCellContainer facets = viennagrid::elements(*cit); for (FacetOnCellIterator focit = facets.begin(); focit != facets.end(); ++focit) { cell_on_facet_cnt[&(*focit)] += 1; } } for (typename CellFacetMap::iterator cfmit = cell_on_facet_cnt.begin(); cfmit != cell_on_facet_cnt.end(); ++cfmit) { if (cfmit->second > 2) { std::cerr << "Topology problem for facet: " << std::endl; std::cout << *(cfmit->first) << std::endl; CellContainer cells = viennagrid::elements(mesh); for (CellIterator cit = cells.begin(); cit != cells.end(); ++cit) { std::cout << "Cell: "; std::cout << *cit << std::endl; } FacetContainer facets = viennagrid::elements(mesh); for (FacetIterator fit = facets.begin(); fit != facets.end(); ++fit) { std::cout << "Facet: "; std::cout << *fit << std::endl; } return EXIT_FAILURE; } } return EXIT_SUCCESS; } template <typename MeshType> int surface_check(MeshType & mesh_old, MeshType & mesh_new) { typedef typename viennagrid::result_of::cell_tag<MeshType>::type CellTag; typedef typename viennagrid::result_of::facet<MeshType>::type FacetType; typedef typename viennagrid::result_of::cell<MeshType>::type CellType; typedef typename viennagrid::result_of::facet_range<MeshType>::type FacetContainer; typedef typename viennagrid::result_of::iterator<FacetContainer>::type FacetIterator; typedef typename viennagrid::result_of::cell_range<MeshType>::type CellContainer; typedef typename viennagrid::result_of::iterator<CellContainer>::type CellIterator; double old_surface = mesh_surface(mesh_old); double new_surface = mesh_surface(mesh_new); if ( (new_surface < 0.9999 * old_surface) || (new_surface > 1.0001 * old_surface) ) { CellContainer cells = viennagrid::elements(mesh_new); for (CellIterator cit = cells.begin(); cit != cells.end(); ++cit) { std::cout << "Cell: "; std::cout << *cit << std::endl; } FacetContainer facets = viennagrid::elements(mesh_new); for (FacetIterator fit = facets.begin(); fit != facets.end(); ++fit) { std::cout << "Facet: "; std::cout << *fit << std::endl; } std::cerr << "Surface check failed!" << std::endl; std::cerr << "Mesh surface before refinement: " << old_surface << std::endl; std::cerr << "Mesh surface after refinement: " << new_surface << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } template <typename MeshType> int volume_check(MeshType & mesh_old, MeshType & mesh_new) { double old_volume = viennagrid::volume(mesh_old); double new_volume = viennagrid::volume(mesh_new); if ( (new_volume < 0.9999 * old_volume) || (new_volume > 1.0001 * old_volume) ) { std::cerr << "Volume check failed!" << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } template <typename MeshType> int sanity_check(MeshType & mesh_old, MeshType & mesh_new) { if (facet_check(mesh_new) != EXIT_SUCCESS) return EXIT_FAILURE; //check for sane topology in new mesh if (surface_check(mesh_old, mesh_new) != EXIT_SUCCESS) return EXIT_FAILURE; //check for same surface if (volume_check(mesh_old, mesh_new) != EXIT_SUCCESS) return EXIT_FAILURE; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/** * @file * @author Mamadou Babaei <info@babaei.net> * @version 0.1.0 * * @section LICENSE * * (The MIT License) * * Copyright (c) 2016 - 2019 Mamadou Babaei * * 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. * * @section DESCRIPTION * * A tiny utility program to fetch and update GeoIP database. * You might want to run this as a cron job. */ #include <iostream> #include <string> #include <csignal> #include <cstdlib> #include <boost/algorithm/string.hpp> #include <boost/exception/diagnostic_information.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <CoreLib/Archiver.hpp> #include <CoreLib/CoreLib.hpp> #include <CoreLib/Defines.hpp> #include <CoreLib/Exception.hpp> #include <CoreLib/FileSystem.hpp> #include <CoreLib/Http.hpp> #include <CoreLib/Log.hpp> #include <CoreLib/System.hpp> #define UNKNOWN_ERROR "Unknown error!" #define CITY_DATABASE_NAME "GeoLite2-City.mmdb" #define CITY_DATABASE_PATH_USR "/usr/share/GeoIP/" CITY_DATABASE_NAME #define CITY_DATABASE_PATH_USR_LOCAL "/usr/local/share/GeoIP/" CITY_DATABASE_NAME #define COUNTRY_DATABASE_NAME "GeoLite2-Country.mmdb" #define COUNTRY_DATABASE_PATH_USR "/usr/share/GeoIP/" COUNTRY_DATABASE_NAME #define COUNTRY_DATABASE_PATH_USR_LOCAL "/usr/local/share/GeoIP/" COUNTRY_DATABASE_NAME #define ASN_DATABASE_NAME "GeoLite2-ASN.mmdb" #define ASN_DATABASE_PATH_USR "/usr/share/GeoIP/" ASN_DATABASE_NAME #define ASN_DATABASE_PATH_USR_LOCAL "/usr/local/share/GeoIP/" ASN_DATABASE_NAME [[ noreturn ]] void Terminate(int signo); FORCEINLINE static const char* GetGeoLite2CityDatabase() { #if defined ( __FreeBSD__ ) static const char* database = CITY_DATABASE_PATH_USR_LOCAL; #elif defined ( __gnu_linux__ ) || defined ( __linux__ ) static const char* database = CITY_DATABASE_PATH_USR; #else /* defined ( __FreeBSD__ ) */ static const char* database = CoreLib::FileSystem::FileExists(CITY_DATABASE_PATH_USR_LOCAL) ? CoreLib::FileSystem::FileExists(CITY_DATABASE_PATH_USR_LOCAL) : CoreLib::FileSystem::FileExists(CITY_DATABASE_PATH_USR); #endif /* defined ( __FreeBSD__ ) */ return database; } FORCEINLINE static const char* GetGeoLite2CountryDatabase() { #if defined ( __FreeBSD__ ) static const char* database = COUNTRY_DATABASE_PATH_USR_LOCAL; #elif defined ( __gnu_linux__ ) || defined ( __linux__ ) static const char* database = COUNTRY_DATABASE_PATH_USR; #else /* defined ( __FreeBSD__ ) */ static const char* database = CoreLib::FileSystem::FileExists(COUNTRY_DATABASE_PATH_USR_LOCAL) ? CoreLib::FileSystem::FileExists(COUNTRY_DATABASE_PATH_USR_LOCAL) : CoreLib::FileSystem::FileExists(COUNTRY_DATABASE_PATH_USR); #endif /* defined ( __FreeBSD__ ) */ return database; } FORCEINLINE static const char* GetGeoLite2ASNDatabase() { #if defined ( __FreeBSD__ ) static const char* database = ASN_DATABASE_PATH_USR_LOCAL; #elif defined ( __gnu_linux__ ) || defined ( __linux__ ) static const char* database = ASN_DATABASE_PATH_USR; #else /* defined ( __FreeBSD__ ) */ static const char* database = CoreLib::FileSystem::FileExists(ASN_DATABASE_PATH_USR_LOCAL) ? CoreLib::FileSystem::FileExists(ASN_DATABASE_PATH_USR_LOCAL) : CoreLib::FileSystem::FileExists(ASN_DATABASE_PATH_USR); #endif /* defined ( __FreeBSD__ ) */ return database; } void UpdateDatabase(const std::string &url, const std::string &tag, const std::string &dbFile); int main(int argc, char **argv) { try { /// Gracefully handling SIGTERM void (*prev_fn)(int); prev_fn = signal(SIGTERM, Terminate); if (prev_fn == SIG_IGN) signal(SIGTERM, SIG_IGN); /// Extract the executable path and name boost::filesystem::path path(boost::filesystem::initial_path<boost::filesystem::path>()); if (argc > 0 && argv[0] != NULL) path = boost::filesystem::system_complete(boost::filesystem::path(argv[0])); std::string appId(path.filename().string()); std::string appPath(boost::algorithm::replace_last_copy(path.string(), appId, "")); /// Force changing the current path to executable path boost::filesystem::current_path(appPath); /// Initializing CoreLib CoreLib::CoreLibInitialize(argc, argv); /// Initializing log system CoreLib::Log::Initialize(std::cout, (boost::filesystem::path(appPath) / boost::filesystem::path("..") / boost::filesystem::path("log")).string(), "SpawnWtHttpd"); /// Acquiring process lock std::string lockId; #if defined ( __unix__ ) int lock; lockId = (boost::filesystem::path(appPath) / boost::filesystem::path("..") / boost::filesystem::path("tmp") / (appId + ".lock")).string(); #elif defined ( _WIN32 ) HANDLE lock; lockId = appId; #endif // defined ( __unix__ ) if(!CoreLib::System::GetLock(lockId, lock)) { std::cerr << "Could not get lock!" << std::endl; std::cerr << "Probably process is already running!" << std::endl; return EXIT_FAILURE; } else { LOG_INFO("Got the process lock!"); } const std::string cityTag("GeoLite2-City"); const std::string countryTag("GeoLite2-Country"); const std::string asnTag("GeoLite2-ASN"); UpdateDatabase(GEOLITE2_CITY_MMDB_URL, cityTag, GetGeoLite2CityDatabase()); UpdateDatabase(GEOLITE2_COUNTRY_MMDB_URL, countryTag, GetGeoLite2CountryDatabase()); UpdateDatabase(GEOLITE2_ASN_MMDB_URL, asnTag, GetGeoLite2ASNDatabase()); } catch (CoreLib::Exception<std::string> &ex) { LOG_ERROR(ex.What()); } catch (boost::exception &ex) { LOG_ERROR(boost::diagnostic_information(ex)); } catch (std::exception &ex) { LOG_ERROR(ex.what()); } catch (...) { LOG_ERROR(UNKNOWN_ERROR); } return EXIT_SUCCESS; } void Terminate(int signo) { std::clog << "Terminating...." << std::endl; exit(signo); } void UpdateDatabase(const std::string &url, const std::string &tag, const std::string &targetMmdbFile) { const std::string tempDir(CoreLib::FileSystem::CreateTempDir()); const std::string gzipFile((boost::filesystem::path(tempDir) / boost::filesystem::path(tag)).string() + ".tar.gz"); { LOG_INFO(url, gzipFile, "Downloading..."); if (CoreLib::Http::Download(url, gzipFile)) { LOG_INFO(url, gzipFile, "Download operation succeeded!"); } else { LOG_ERROR(url, gzipFile, "Download operation failed!"); return; } } const std::string tarFile((boost::filesystem::path(tempDir) / boost::filesystem::path(tag)).string() + ".tar"); { LOG_INFO(gzipFile, tarFile, "Uncompressing..."); std::string err; if (CoreLib::Archiver::UnGzip(gzipFile, tarFile, err)) { LOG_INFO(gzipFile, tarFile, "Uncompress operation succeeded!"); } else { LOG_INFO(gzipFile, tarFile, err, "Uncompress operation failed!"); return; } } { LOG_INFO(tarFile, tempDir, "Extacting tar archive..."); std::string err; if (CoreLib::Archiver::UnTar(tarFile, tempDir, err)) { LOG_INFO(tarFile, tempDir, "Tar archive exraction succeeded!"); } else { LOG_INFO(tarFile, tempDir, err, "Tar archive exraction failed!"); return; } } { LOG_INFO(tempDir, targetMmdbFile, "Copying mmdb file..."); boost::filesystem::directory_iterator it{ boost::filesystem::path(tempDir)}; BOOST_FOREACH(const boost::filesystem::path &p, std::make_pair( it, boost::filesystem::directory_iterator{})) { if(boost::filesystem::is_directory(p)) { std::string targetPath(boost::filesystem::path( targetMmdbFile).parent_path().string()); if (!CoreLib::FileSystem::DirExists(targetPath)) { if (!CoreLib::FileSystem::CreateDir(targetPath)) { LOG_INFO(targetPath, targetMmdbFile, "Failed to create target path!"); CoreLib::FileSystem::Erase(tempDir, true); return; } } std::string sourceMmdbFile( (p / boost::filesystem::path(tag + ".mmdb")).string()); if (CoreLib::FileSystem::FileExists(sourceMmdbFile)) { if (CoreLib::FileSystem::CopyFile( sourceMmdbFile, targetMmdbFile, true)) { LOG_INFO(sourceMmdbFile, targetMmdbFile, "Copying mmdb file succeeded!"); } else { LOG_INFO(sourceMmdbFile, targetMmdbFile, "Copying mmdb file failed!"); } } } } } LOG_INFO(targetMmdbFile, "Successfully updated!"); CoreLib::FileSystem::Erase(tempDir, true); } <commit_msg>fix wrong log file name<commit_after>/** * @file * @author Mamadou Babaei <info@babaei.net> * @version 0.1.0 * * @section LICENSE * * (The MIT License) * * Copyright (c) 2016 - 2019 Mamadou Babaei * * 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. * * @section DESCRIPTION * * A tiny utility program to fetch and update GeoIP database. * You might want to run this as a cron job. */ #include <iostream> #include <string> #include <csignal> #include <cstdlib> #include <boost/algorithm/string.hpp> #include <boost/exception/diagnostic_information.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <CoreLib/Archiver.hpp> #include <CoreLib/CoreLib.hpp> #include <CoreLib/Defines.hpp> #include <CoreLib/Exception.hpp> #include <CoreLib/FileSystem.hpp> #include <CoreLib/Http.hpp> #include <CoreLib/Log.hpp> #include <CoreLib/System.hpp> #define UNKNOWN_ERROR "Unknown error!" #define CITY_DATABASE_NAME "GeoLite2-City.mmdb" #define CITY_DATABASE_PATH_USR "/usr/share/GeoIP/" CITY_DATABASE_NAME #define CITY_DATABASE_PATH_USR_LOCAL "/usr/local/share/GeoIP/" CITY_DATABASE_NAME #define COUNTRY_DATABASE_NAME "GeoLite2-Country.mmdb" #define COUNTRY_DATABASE_PATH_USR "/usr/share/GeoIP/" COUNTRY_DATABASE_NAME #define COUNTRY_DATABASE_PATH_USR_LOCAL "/usr/local/share/GeoIP/" COUNTRY_DATABASE_NAME #define ASN_DATABASE_NAME "GeoLite2-ASN.mmdb" #define ASN_DATABASE_PATH_USR "/usr/share/GeoIP/" ASN_DATABASE_NAME #define ASN_DATABASE_PATH_USR_LOCAL "/usr/local/share/GeoIP/" ASN_DATABASE_NAME [[ noreturn ]] void Terminate(int signo); FORCEINLINE static const char* GetGeoLite2CityDatabase() { #if defined ( __FreeBSD__ ) static const char* database = CITY_DATABASE_PATH_USR_LOCAL; #elif defined ( __gnu_linux__ ) || defined ( __linux__ ) static const char* database = CITY_DATABASE_PATH_USR; #else /* defined ( __FreeBSD__ ) */ static const char* database = CoreLib::FileSystem::FileExists(CITY_DATABASE_PATH_USR_LOCAL) ? CoreLib::FileSystem::FileExists(CITY_DATABASE_PATH_USR_LOCAL) : CoreLib::FileSystem::FileExists(CITY_DATABASE_PATH_USR); #endif /* defined ( __FreeBSD__ ) */ return database; } FORCEINLINE static const char* GetGeoLite2CountryDatabase() { #if defined ( __FreeBSD__ ) static const char* database = COUNTRY_DATABASE_PATH_USR_LOCAL; #elif defined ( __gnu_linux__ ) || defined ( __linux__ ) static const char* database = COUNTRY_DATABASE_PATH_USR; #else /* defined ( __FreeBSD__ ) */ static const char* database = CoreLib::FileSystem::FileExists(COUNTRY_DATABASE_PATH_USR_LOCAL) ? CoreLib::FileSystem::FileExists(COUNTRY_DATABASE_PATH_USR_LOCAL) : CoreLib::FileSystem::FileExists(COUNTRY_DATABASE_PATH_USR); #endif /* defined ( __FreeBSD__ ) */ return database; } FORCEINLINE static const char* GetGeoLite2ASNDatabase() { #if defined ( __FreeBSD__ ) static const char* database = ASN_DATABASE_PATH_USR_LOCAL; #elif defined ( __gnu_linux__ ) || defined ( __linux__ ) static const char* database = ASN_DATABASE_PATH_USR; #else /* defined ( __FreeBSD__ ) */ static const char* database = CoreLib::FileSystem::FileExists(ASN_DATABASE_PATH_USR_LOCAL) ? CoreLib::FileSystem::FileExists(ASN_DATABASE_PATH_USR_LOCAL) : CoreLib::FileSystem::FileExists(ASN_DATABASE_PATH_USR); #endif /* defined ( __FreeBSD__ ) */ return database; } void UpdateDatabase(const std::string &url, const std::string &tag, const std::string &dbFile); int main(int argc, char **argv) { try { /// Gracefully handling SIGTERM void (*prev_fn)(int); prev_fn = signal(SIGTERM, Terminate); if (prev_fn == SIG_IGN) signal(SIGTERM, SIG_IGN); /// Extract the executable path and name boost::filesystem::path path(boost::filesystem::initial_path<boost::filesystem::path>()); if (argc > 0 && argv[0] != NULL) path = boost::filesystem::system_complete(boost::filesystem::path(argv[0])); std::string appId(path.filename().string()); std::string appPath(boost::algorithm::replace_last_copy(path.string(), appId, "")); /// Force changing the current path to executable path boost::filesystem::current_path(appPath); /// Initializing CoreLib CoreLib::CoreLibInitialize(argc, argv); /// Initializing log system CoreLib::Log::Initialize(std::cout, (boost::filesystem::path(appPath) / boost::filesystem::path("..") / boost::filesystem::path("log")).string(), "GeoUpdater"); /// Acquiring process lock std::string lockId; #if defined ( __unix__ ) int lock; lockId = (boost::filesystem::path(appPath) / boost::filesystem::path("..") / boost::filesystem::path("tmp") / (appId + ".lock")).string(); #elif defined ( _WIN32 ) HANDLE lock; lockId = appId; #endif // defined ( __unix__ ) if(!CoreLib::System::GetLock(lockId, lock)) { std::cerr << "Could not get lock!" << std::endl; std::cerr << "Probably process is already running!" << std::endl; return EXIT_FAILURE; } else { LOG_INFO("Got the process lock!"); } const std::string cityTag("GeoLite2-City"); const std::string countryTag("GeoLite2-Country"); const std::string asnTag("GeoLite2-ASN"); UpdateDatabase(GEOLITE2_CITY_MMDB_URL, cityTag, GetGeoLite2CityDatabase()); UpdateDatabase(GEOLITE2_COUNTRY_MMDB_URL, countryTag, GetGeoLite2CountryDatabase()); UpdateDatabase(GEOLITE2_ASN_MMDB_URL, asnTag, GetGeoLite2ASNDatabase()); } catch (CoreLib::Exception<std::string> &ex) { LOG_ERROR(ex.What()); } catch (boost::exception &ex) { LOG_ERROR(boost::diagnostic_information(ex)); } catch (std::exception &ex) { LOG_ERROR(ex.what()); } catch (...) { LOG_ERROR(UNKNOWN_ERROR); } return EXIT_SUCCESS; } void Terminate(int signo) { std::clog << "Terminating...." << std::endl; exit(signo); } void UpdateDatabase(const std::string &url, const std::string &tag, const std::string &targetMmdbFile) { const std::string tempDir(CoreLib::FileSystem::CreateTempDir()); const std::string gzipFile((boost::filesystem::path(tempDir) / boost::filesystem::path(tag)).string() + ".tar.gz"); { LOG_INFO(url, gzipFile, "Downloading..."); if (CoreLib::Http::Download(url, gzipFile)) { LOG_INFO(url, gzipFile, "Download operation succeeded!"); } else { LOG_ERROR(url, gzipFile, "Download operation failed!"); return; } } const std::string tarFile((boost::filesystem::path(tempDir) / boost::filesystem::path(tag)).string() + ".tar"); { LOG_INFO(gzipFile, tarFile, "Uncompressing..."); std::string err; if (CoreLib::Archiver::UnGzip(gzipFile, tarFile, err)) { LOG_INFO(gzipFile, tarFile, "Uncompress operation succeeded!"); } else { LOG_INFO(gzipFile, tarFile, err, "Uncompress operation failed!"); return; } } { LOG_INFO(tarFile, tempDir, "Extacting tar archive..."); std::string err; if (CoreLib::Archiver::UnTar(tarFile, tempDir, err)) { LOG_INFO(tarFile, tempDir, "Tar archive exraction succeeded!"); } else { LOG_INFO(tarFile, tempDir, err, "Tar archive exraction failed!"); return; } } { LOG_INFO(tempDir, targetMmdbFile, "Copying mmdb file..."); boost::filesystem::directory_iterator it{ boost::filesystem::path(tempDir)}; BOOST_FOREACH(const boost::filesystem::path &p, std::make_pair( it, boost::filesystem::directory_iterator{})) { if(boost::filesystem::is_directory(p)) { std::string targetPath(boost::filesystem::path( targetMmdbFile).parent_path().string()); if (!CoreLib::FileSystem::DirExists(targetPath)) { if (!CoreLib::FileSystem::CreateDir(targetPath)) { LOG_INFO(targetPath, targetMmdbFile, "Failed to create target path!"); CoreLib::FileSystem::Erase(tempDir, true); return; } } std::string sourceMmdbFile( (p / boost::filesystem::path(tag + ".mmdb")).string()); if (CoreLib::FileSystem::FileExists(sourceMmdbFile)) { if (CoreLib::FileSystem::CopyFile( sourceMmdbFile, targetMmdbFile, true)) { LOG_INFO(sourceMmdbFile, targetMmdbFile, "Copying mmdb file succeeded!"); } else { LOG_INFO(sourceMmdbFile, targetMmdbFile, "Copying mmdb file failed!"); } } } } } LOG_INFO(targetMmdbFile, "Successfully updated!"); CoreLib::FileSystem::Erase(tempDir, true); } <|endoftext|>
<commit_before>#include "catch.hpp" #include "yaml-cpp/yaml.h" #include "scene/sceneLoader.h" #include "style/style.h" #include "scene/scene.h" #include "platform.h" #include "tangram.h" using YAML::Node; using namespace Tangram; const char* path = "scene.yaml"; TEST_CASE("Scene update tests") { Scene scene("scene.yaml"); auto sceneString = stringFromFile(setResourceRoot(path).c_str(), PathType::resource); REQUIRE(!sceneString.empty()); Node root; REQUIRE(SceneLoader::loadScene(sceneString, scene, root)); // Update scene.setComponent("lights.light1.ambient", "0.9"); scene.setComponent("lights.light1.type", "spotlight"); scene.setComponent("lights.light1.origin", "ground"); scene.setComponent("layers.poi_icons.draw.icons.interactive", "false"); scene.setComponent("styles.heightglow.shaders.uniforms.u_time_expand", "5.0"); scene.setComponent("cameras.iso-camera.active", "true"); scene.setComponent("cameras.iso-camera.type", "perspective"); scene.setComponent("global.default_order", "function() { return 0.0; }"); // Tangram apply scene updates, reload the scene REQUIRE(SceneLoader::loadScene(sceneString, scene, root)); scene.clearUserDefines(); REQUIRE(root["lights"]["light1"]["ambient"].Scalar() == "0.9"); REQUIRE(root["lights"]["light1"]["type"].Scalar() == "spotlight"); REQUIRE(root["lights"]["light1"]["origin"].Scalar() == "ground"); REQUIRE(root["layers"]["poi_icons"]["draw"]["icons"]["interactive"].Scalar() == "false"); REQUIRE(root["styles"]["heightglow"]["shaders"]["uniforms"]["u_time_expand"].Scalar() == "5.0"); REQUIRE(root["styles"]["heightglowline"]["shaders"]["uniforms"]["u_time_expand"].Scalar() == "5.0"); REQUIRE(root["cameras"]["iso-camera"]["active"].Scalar() == "true"); REQUIRE(root["cameras"]["iso-camera"]["type"].Scalar() == "perspective"); REQUIRE(root["global"]["default_order"].Scalar() == "function() { return 0.0; }"); } <commit_msg>Unit tests for non-existing YAML property node<commit_after>#include "catch.hpp" #include "yaml-cpp/yaml.h" #include "scene/sceneLoader.h" #include "style/style.h" #include "scene/scene.h" #include "platform.h" #include "tangram.h" using YAML::Node; using namespace Tangram; const char* path = "scene.yaml"; TEST_CASE("Scene update tests") { Scene scene("scene.yaml"); auto sceneString = stringFromFile(setResourceRoot(path).c_str(), PathType::resource); REQUIRE(!sceneString.empty()); Node root; REQUIRE(SceneLoader::loadScene(sceneString, scene, root)); // Update scene.setComponent("lights.light1.ambient", "0.9"); scene.setComponent("lights.light1.type", "spotlight"); scene.setComponent("lights.light1.origin", "ground"); scene.setComponent("layers.poi_icons.draw.icons.interactive", "false"); scene.setComponent("styles.heightglow.shaders.uniforms.u_time_expand", "5.0"); scene.setComponent("cameras.iso-camera.active", "true"); scene.setComponent("cameras.iso-camera.type", "perspective"); scene.setComponent("global.default_order", "function() { return 0.0; }"); scene.setComponent("global.non_existing_property0", "true"); scene.setComponent("global.non_existing_property1.non_existing_property_deep", "true"); // Tangram apply scene updates, reload the scene REQUIRE(SceneLoader::loadScene(sceneString, scene, root)); scene.clearUserDefines(); REQUIRE(root["lights"]["light1"]["ambient"].Scalar() == "0.9"); REQUIRE(root["lights"]["light1"]["type"].Scalar() == "spotlight"); REQUIRE(root["lights"]["light1"]["origin"].Scalar() == "ground"); REQUIRE(root["layers"]["poi_icons"]["draw"]["icons"]["interactive"].Scalar() == "false"); REQUIRE(root["styles"]["heightglow"]["shaders"]["uniforms"]["u_time_expand"].Scalar() == "5.0"); REQUIRE(root["styles"]["heightglowline"]["shaders"]["uniforms"]["u_time_expand"].Scalar() == "5.0"); REQUIRE(root["cameras"]["iso-camera"]["active"].Scalar() == "true"); REQUIRE(root["cameras"]["iso-camera"]["type"].Scalar() == "perspective"); REQUIRE(root["global"]["default_order"].Scalar() == "function() { return 0.0; }"); REQUIRE(root["global"]["non_existing_property0"].Scalar() == "true"); REQUIRE(!root["global"]["non_existing_property1"]); } <|endoftext|>
<commit_before>/* ** Copyright 2012-2013 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker 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 Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <cerrno> #include <cstdlib> #include <cstring> #include <fcntl.h> #include <iomanip> #include <QMutexLocker> #include <poll.h> #include <sstream> #include <unistd.h> #include "com/centreon/broker/config/applier/endpoint.hh" #include "com/centreon/broker/config/applier/modules.hh" #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/logging/logging.hh" #include "com/centreon/broker/stats/worker.hh" using namespace com::centreon::broker::stats; /************************************** * * * Public Methods * * * **************************************/ /** * Default constructor. */ worker::worker() : _fd(-1) {} /** * Destructor. */ worker::~worker() throw () {} /** * Set the exit flag. */ void worker::exit() { _should_exit = true; return ; } /** * Run the statistics thread. * * @param[in] fifo_file Path to the FIFO file. */ void worker::run(QString const& fifo_file) { // Close FD. _close(); // Set FIFO file. _fifo = fifo_file; // Set exit flag. _should_exit = false; // Launch thread. start(); return ; } /************************************** * * * Private Methods * * * **************************************/ /** * Close FIFO fd. */ void worker::_close() { if (_fd >= 0) { close(_fd); _fd = -1; } return ; } /** * Generate statistics. */ void worker::_generate_stats() { // Modules. config::applier::modules& mod_applier(config::applier::modules::instance()); for (config::applier::modules::iterator it = mod_applier.begin(), end = mod_applier.end(); it != end; ++it) { _buffer.append("module "); _buffer.append(it.key().toStdString()); _buffer.append("\nstate=loaded\n"); _buffer.append("\n"); } // Endpoint applier. config::applier::endpoint& endp_applier(config::applier::endpoint::instance()); // Print input endpoints. { QMutexLocker lock(&endp_applier.input_mutex()); for (config::applier::endpoint::iterator it = endp_applier.input_begin(), end = endp_applier.input_end(); it != end; ++it) { _generate_stats_for_endpoint(*it, _buffer, false); _buffer.append("\n"); } } // Print output endpoints. { QMutexLocker lock(&endp_applier.output_mutex()); for (config::applier::endpoint::iterator it = endp_applier.output_begin(), end = endp_applier.output_end(); it != end; ++it) { _generate_stats_for_endpoint(*it, _buffer, true); _buffer.append("\n"); } } return ; } /** * Generate statistics for an endpoint. * * @param[in] fo Failover thread of the endpoint. * @param[out] buffer Buffer in which data will be printed. * @param[in] is_out true if fo manage an output endpoint. */ void worker::_generate_stats_for_endpoint( processing::failover* fo, std::string& buffer, bool is_out) { // Header. buffer.append(is_out ? "output " : "input "); buffer.append(fo->_name.toStdString()); buffer.append("\n"); // Choose stream we will work on. QReadWriteLock* first_rwl; misc::shared_ptr<io::stream>* first_s; QReadWriteLock* second_rwl; misc::shared_ptr<io::stream>* second_s; if (is_out) { first_rwl = &fo->_tom; first_s = &fo->_to; second_rwl = &fo->_fromm; second_s = &fo->_from; } else { first_rwl = &fo->_fromm; first_s = &fo->_from; second_rwl = &fo->_tom; second_s = &fo->_to; } { // Get primary state. buffer.append("state="); QReadLocker rl(first_rwl); if (first_s->isNull()) { if (!fo->_last_error.isEmpty()) { buffer.append("disconnected"); buffer.append(" ("); buffer.append(fo->_last_error.toStdString()); buffer.append(")\n"); } else if (!fo->_endpoint.isNull() && !fo->_endpoint->is_acceptor()) buffer.append("connecting\n"); else buffer.append("listening\n"); } else if (!fo->_failover.isNull() && fo->_failover->isRunning()) { buffer.append("replaying\n"); (*first_s)->statistics(buffer); } else { buffer.append("connected\n"); (*first_s)->statistics(buffer); } } { // Get secondary state. QReadLocker rl(second_rwl); if (!second_s->isNull()) (*second_s)->statistics(buffer); } { // Event processing stats. std::ostringstream oss; oss << "last event at=" << fo->get_last_event() << "\n" << "event processing speed=" << std::fixed << std::setprecision(1) << fo->get_event_processing_speed() << " events/s\n"; buffer.append(oss.str()); } // Endpoint stats. if (!fo->_endpoint.isNull()) fo->_endpoint->stats(buffer); { // Last connection times. std::ostringstream oss; oss << "last connection attempt=" << fo->_last_connect_attempt << "\n" << "last connection success=" << fo->_last_connect_success << "\n"; buffer.append(oss.str()); } // Failover. if (!fo->_failover.isNull() && fo->_failover->isRunning()) { buffer.append("failover\n"); std::string subbuffer; _generate_stats_for_endpoint( fo->_failover.data(), subbuffer, is_out); subbuffer.insert(0, " "); size_t pos(subbuffer.find('\n')); while ((pos != subbuffer.size() - 1) && (pos != std::string::npos)) { subbuffer.replace(pos, 1, "\n "); pos = subbuffer.find('\n', pos + 3); } buffer.append(subbuffer); } return ; } /** * Open FIFO. * * @return true on success. */ bool worker::_open() { bool retval; _fd = open(qPrintable(_fifo), O_WRONLY | O_NONBLOCK); if (_fd < 0) { if (errno != ENXIO) { char const* msg(strerror(errno)); throw (exceptions::msg() << "cannot open FIFO file: " << msg); } else retval = false; } else retval = true; return (retval); } /** * Thread entry point. */ void worker::run() { try { while (!_should_exit) { // Check file opening. if (_buffer.empty()) { _close(); usleep(100000); if (!_open()) continue ; } // FD sets. pollfd fds; fds.fd = _fd; fds.events = POLLOUT; fds.revents = 0; // Multiplexing. int flagged(poll(&fds, 1, 1000)); // Error. if (flagged < 0) { // Unrecoverable. if (errno != EINTR) { char const* msg(strerror(errno)); throw (exceptions::msg() << "multiplexing failure: " << msg); } } else if (flagged > 0) { // FD error. if ((fds.revents & (POLLERR | POLLNVAL | POLLHUP))) throw (exceptions::msg() << "FIFO fd has pending error"); // Readable. else if ((fds.revents & POLLOUT)) { if (_buffer.empty()) // Generate statistics. _generate_stats(); // Write data. ssize_t wb(write(_fd, _buffer.c_str(), _buffer.size())); if (wb > 0) _buffer.erase(0, wb); else _buffer.clear(); } } } } catch (std::exception const& e) { logging::error(logging::high) << "stats: thread will exit due to the following error: " << e.what(); } catch (...) { logging::error(logging::high) << "stats: thread will exit due to an unknown error"; } ::unlink(qPrintable(_fifo)); return ; } <commit_msg>stats: add the new 'blocked' state for endpoints. This prevent stalled reading for the statistics pipe. This fixes #4151.<commit_after>/* ** Copyright 2012-2013 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker 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 Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <cerrno> #include <cstdlib> #include <cstring> #include <fcntl.h> #include <iomanip> #include <QMutexLocker> #include <poll.h> #include <sstream> #include <unistd.h> #include "com/centreon/broker/config/applier/endpoint.hh" #include "com/centreon/broker/config/applier/modules.hh" #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/logging/logging.hh" #include "com/centreon/broker/stats/worker.hh" using namespace com::centreon::broker::stats; /************************************** * * * Public Methods * * * **************************************/ /** * Default constructor. */ worker::worker() : _fd(-1) {} /** * Destructor. */ worker::~worker() throw () {} /** * Set the exit flag. */ void worker::exit() { _should_exit = true; return ; } /** * Run the statistics thread. * * @param[in] fifo_file Path to the FIFO file. */ void worker::run(QString const& fifo_file) { // Close FD. _close(); // Set FIFO file. _fifo = fifo_file; // Set exit flag. _should_exit = false; // Launch thread. start(); return ; } /************************************** * * * Private Methods * * * **************************************/ /** * Close FIFO fd. */ void worker::_close() { if (_fd >= 0) { close(_fd); _fd = -1; } return ; } /** * Generate statistics. */ void worker::_generate_stats() { // Modules. config::applier::modules& mod_applier(config::applier::modules::instance()); for (config::applier::modules::iterator it = mod_applier.begin(), end = mod_applier.end(); it != end; ++it) { _buffer.append("module "); _buffer.append(it.key().toStdString()); _buffer.append("\nstate=loaded\n"); _buffer.append("\n"); } // Endpoint applier. config::applier::endpoint& endp_applier(config::applier::endpoint::instance()); // Print input endpoints. { QMutexLocker lock(&endp_applier.input_mutex()); for (config::applier::endpoint::iterator it = endp_applier.input_begin(), end = endp_applier.input_end(); it != end; ++it) { _generate_stats_for_endpoint(*it, _buffer, false); _buffer.append("\n"); } } // Print output endpoints. { QMutexLocker lock(&endp_applier.output_mutex()); for (config::applier::endpoint::iterator it = endp_applier.output_begin(), end = endp_applier.output_end(); it != end; ++it) { _generate_stats_for_endpoint(*it, _buffer, true); _buffer.append("\n"); } } return ; } /** * Generate statistics for an endpoint. * * @param[in] fo Failover thread of the endpoint. * @param[out] buffer Buffer in which data will be printed. * @param[in] is_out true if fo manage an output endpoint. */ void worker::_generate_stats_for_endpoint( processing::failover* fo, std::string& buffer, bool is_out) { // Header. buffer.append(is_out ? "output " : "input "); buffer.append(fo->_name.toStdString()); buffer.append("\n"); // Choose stream we will work on. QReadWriteLock* first_rwl; misc::shared_ptr<io::stream>* first_s; QReadWriteLock* second_rwl; misc::shared_ptr<io::stream>* second_s; if (is_out) { first_rwl = &fo->_tom; first_s = &fo->_to; second_rwl = &fo->_fromm; second_s = &fo->_from; } else { first_rwl = &fo->_fromm; first_s = &fo->_from; second_rwl = &fo->_tom; second_s = &fo->_to; } { // Get primary state. buffer.append("state="); bool locked(false); for (unsigned int i(0); i < 10000; ++i) { if (first_rwl->tryLockForRead()) { locked = true; break ; } usleep(1); } try { // Could lock RWL. if (locked) { if (first_s->isNull()) { if (!fo->_last_error.isEmpty()) { buffer.append("disconnected"); buffer.append(" ("); buffer.append(fo->_last_error.toStdString()); buffer.append(")\n"); } else if (!fo->_endpoint.isNull() && !fo->_endpoint->is_acceptor()) buffer.append("connecting\n"); else buffer.append("listening\n"); } else if (!fo->_failover.isNull() && fo->_failover->isRunning()) { buffer.append("replaying\n"); (*first_s)->statistics(buffer); } else { buffer.append("connected\n"); (*first_s)->statistics(buffer); } } // Could not lock RWL. else buffer.append("blocked\n"); } catch (...) { if (locked) first_rwl->unlock(); throw ; } if (locked) first_rwl->unlock(); } { // Get secondary state. QReadLocker rl(second_rwl); if (!second_s->isNull()) (*second_s)->statistics(buffer); } { // Event processing stats. std::ostringstream oss; oss << "last event at=" << fo->get_last_event() << "\n" << "event processing speed=" << std::fixed << std::setprecision(1) << fo->get_event_processing_speed() << " events/s\n"; buffer.append(oss.str()); } // Endpoint stats. if (!fo->_endpoint.isNull()) fo->_endpoint->stats(buffer); { // Last connection times. std::ostringstream oss; oss << "last connection attempt=" << fo->_last_connect_attempt << "\n" << "last connection success=" << fo->_last_connect_success << "\n"; buffer.append(oss.str()); } // Failover. if (!fo->_failover.isNull() && fo->_failover->isRunning()) { buffer.append("failover\n"); std::string subbuffer; _generate_stats_for_endpoint( fo->_failover.data(), subbuffer, is_out); subbuffer.insert(0, " "); size_t pos(subbuffer.find('\n')); while ((pos != subbuffer.size() - 1) && (pos != std::string::npos)) { subbuffer.replace(pos, 1, "\n "); pos = subbuffer.find('\n', pos + 3); } buffer.append(subbuffer); } return ; } /** * Open FIFO. * * @return true on success. */ bool worker::_open() { bool retval; _fd = open(qPrintable(_fifo), O_WRONLY | O_NONBLOCK); if (_fd < 0) { if (errno != ENXIO) { char const* msg(strerror(errno)); throw (exceptions::msg() << "cannot open FIFO file: " << msg); } else retval = false; } else retval = true; return (retval); } /** * Thread entry point. */ void worker::run() { try { while (!_should_exit) { // Check file opening. if (_buffer.empty()) { _close(); usleep(100000); if (!_open()) continue ; } // FD sets. pollfd fds; fds.fd = _fd; fds.events = POLLOUT; fds.revents = 0; // Multiplexing. int flagged(poll(&fds, 1, 1000)); // Error. if (flagged < 0) { // Unrecoverable. if (errno != EINTR) { char const* msg(strerror(errno)); throw (exceptions::msg() << "multiplexing failure: " << msg); } } else if (flagged > 0) { // FD error. if ((fds.revents & (POLLERR | POLLNVAL | POLLHUP))) throw (exceptions::msg() << "FIFO fd has pending error"); // Readable. else if ((fds.revents & POLLOUT)) { if (_buffer.empty()) // Generate statistics. _generate_stats(); // Write data. ssize_t wb(write(_fd, _buffer.c_str(), _buffer.size())); if (wb > 0) _buffer.erase(0, wb); else _buffer.clear(); } } } } catch (std::exception const& e) { logging::error(logging::high) << "stats: thread will exit due to the following error: " << e.what(); } catch (...) { logging::error(logging::high) << "stats: thread will exit due to an unknown error"; } ::unlink(qPrintable(_fifo)); return ; } <|endoftext|>
<commit_before>/******************************************************************************* Tchê Media Player Copyright (c) 2016, Fábio Pichler All rights reserved. License: BSD 3-Clause License (http://fabiopichler.net/bsd-3-license/) Author: Fábio Pichler Website: http://fabiopichler.net *******************************************************************************/ #include "Update.h" #include "../Core/Database.h" #include <iostream> #include <QFileInfo> #include <QProcess> UpdateApp::UpdateApp(QObject *parent, QSettings *iniSettings) : QObject(parent) { this->iniSettings = iniSettings; blockRequest = false; playlistFile = nullptr; currentDate = QDate::currentDate(); updateManager = new QNetworkAccessManager(this); downloadManager = new QNetworkAccessManager(this); startTimer = new QTimer(this); startTimer->setSingleShot(true); connect(updateManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(finishedChecking(QNetworkReply*))); connect(startTimer, SIGNAL(timeout()), this, SLOT(startChecking())); connect(this, SIGNAL(showNotification(QString)), parent, SLOT(showNotification(QString))); int checkUpdate = Database::value("Version", "updates_check", 1).toInt(); if (checkUpdate == 0) return; if (checkUpdate == 2) checkUpdate = 7; QDate lastCheck(QDate::fromString(Database::value("Version", "updates_lastCheck").toString(), "yyyy-MM-dd")); lastCheck = lastCheck.addDays(checkUpdate); if (lastCheck < currentDate) startTimer->start(1000); } UpdateApp::~UpdateApp() { requestAborted = true; delete updateManager; delete downloadManager; delete startTimer; if (playlistFile) { playlistFile->close(); playlistFile->remove(); delete playlistFile; } } //================================================================================================================ // public slots //================================================================================================================ void UpdateApp::startChecking(const bool &arg) { stdCout("Checking for updates..."); if (arg) emit showNotification("Verificando por atualizações. Aguarde..."); alert = arg; QString p("?version="+CurrentVersion); QNetworkRequest request; request.setUrl(QUrl((newURL.isEmpty() ? CheckUpdate+p : (newURL.contains("version=") ? newURL : newURL+p)))); request.setRawHeader("User-Agent", QString(AppNameId+"-"+CurrentVersion).toLocal8Bit()); updateManager->get(request); } //================================================================================================================ // private //================================================================================================================ void UpdateApp::downloadPlaylist(const QUrl &url) { QString fileName = "RadioList_" + newPlaylistDate + ".7z"; playlistFile = new QFile(Global::getConfigPath(fileName)); if (!playlistFile->open(QIODevice::WriteOnly)) { qDebug() << "Error: " << playlistFile->errorString(); delete playlistFile; playlistFile = nullptr; return; } requestAborted = false; blockRequest = true; QNetworkRequest request; request.setUrl(url); request.setRawHeader("User-Agent", QString(AppNameId+"-"+CurrentVersion).toLocal8Bit()); downloadReply = downloadManager->get(request); connect(downloadReply, SIGNAL(readyRead()), this, SLOT(readyRead())); connect(downloadReply, SIGNAL(finished()), this, SLOT(downloadFinished())); } //================================================================================================================ // private slots //================================================================================================================ void UpdateApp::readyRead() { if (playlistFile) playlistFile->write(downloadReply->readAll()); } void UpdateApp::finishedChecking(QNetworkReply *reply) { int code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); const QByteArray data = reply->readAll(); if (code == 200) { QJsonObject json = QJsonDocument::fromJson(data).object(); QJsonObject app = json.value("app").toObject(); QJsonObject radioPlaylist = json.value("radioPlaylist").toObject(); QString version = app["currentVersion"].toString(); newPlaylistName = radioPlaylist["fileName"].toString(); newPlaylistDate = radioPlaylist["date"].toString(); QUrl radiolistUrl = radioPlaylist["url"].toString(); if (!version.isEmpty()) { stdCout("Checking update is completed"); Database::setValue("Version", "updates_lastCheck", currentDate.toString("yyyy-MM-dd")); QDate listInstalled(QDate::fromString(iniSettings->value("Radiolist/Date").toString(), "yyyy-MM-dd")); QDate dateChecked(QDate::fromString(newPlaylistDate, "yyyy-MM-dd")); if (!blockRequest && !radiolistUrl.isEmpty() && listInstalled < dateChecked) downloadPlaylist(radiolistUrl); if (version == CurrentVersion && alert) { QMessageBox::information(nullptr,"Info",QString("<h3>O %1 está atualizado.</h3>Versão atual: %2").arg(AppName,version)); } else if (version != CurrentVersion) { stdCout("New version available: " + version + "\n"); if (QMessageBox::warning(nullptr,"Info",QString("<h3>Nova versão disponível</h3>Uma nova versão do <strong>%1</strong> " "está disponível,<br>é altamente recomendável que instale a atualização," "<br>pois contém várias melhorias e correções de bugs.<br><br>" "<strong>Versão instalada:</strong> %2<br>" "<strong>Nova versão:</strong> %3<br><br>Deseja acessar a internet e " "baixar a última versão?").arg(AppName,CurrentVersion,version), QMessageBox::Yes|QMessageBox::No) == QMessageBox::Yes) QDesktopServices::openUrl(QUrl(DownloadUpdate)); } reply->deleteLater(); return; } } else if (code == 301 || code == 302) { newURL = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toString(); startChecking(alert); reply->deleteLater(); return; } stdCout("Unable to check for updates. Code: " + QString::number(code)); reply->deleteLater(); if (alert) QMessageBox::warning(nullptr,"Info",QString("Não foi possível verificar se há atualizações.\nVerifique sua conexão à " "internet e tente novamente.\nCódigo do erro: %1").arg(code)); } void UpdateApp::downloadFinished() { int code = downloadReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); playlistFile->flush(); playlistFile->close(); if (!requestAborted && downloadReply->error() == QNetworkReply::NoError) { QString args("\""+Global::getAppPath()+"7zr\" x -y \""+playlistFile->fileName() +"\" -o\""+Global::getConfigPath()+"\""); if (QProcess::execute(args) == 0) { iniSettings->setValue("Radiolist/NewFileName", newPlaylistName); iniSettings->setValue("Radiolist/NewDate", newPlaylistDate); emit showNotification("A Lista de Rádios foi atualizada e\nserá ativada, após reiniciar o programa."); } else { qDebug() << "Erro ao Extrair o novo RadioList"; } } downloadReply->deleteLater(); playlistFile->remove(); delete playlistFile; playlistFile = nullptr; if (!requestAborted && (code == 301 || code == 302)) { downloadPlaylist(downloadReply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl()); return; } blockRequest = false; } <commit_msg>atualizado<commit_after>/******************************************************************************* Tchê Media Player Copyright (c) 2016, Fábio Pichler All rights reserved. License: BSD 3-Clause License (http://fabiopichler.net/bsd-3-license/) Author: Fábio Pichler Website: http://fabiopichler.net *******************************************************************************/ #include "Update.h" #include "../Core/Database.h" #include <iostream> #include <QFileInfo> #include <QProcess> UpdateApp::UpdateApp(QObject *parent, QSettings *iniSettings) : QObject(parent) { this->iniSettings = iniSettings; blockRequest = false; playlistFile = nullptr; currentDate = QDate::currentDate(); updateManager = new QNetworkAccessManager(this); downloadManager = new QNetworkAccessManager(this); startTimer = new QTimer(this); startTimer->setSingleShot(true); connect(updateManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(finishedChecking(QNetworkReply*))); connect(startTimer, SIGNAL(timeout()), this, SLOT(startChecking())); connect(this, SIGNAL(showNotification(QString)), parent, SLOT(showNotification(QString))); int checkUpdate = Database::value("Version", "updates_check", 1).toInt(); if (checkUpdate == 0) return; if (checkUpdate == 2) checkUpdate = 6; QDate lastCheck(QDate::fromString(Database::value("Version", "updates_lastCheck").toString(), "yyyy-MM-dd")); lastCheck = lastCheck.addDays(checkUpdate); if (lastCheck < currentDate) startTimer->start(1000); } UpdateApp::~UpdateApp() { requestAborted = true; delete updateManager; delete downloadManager; delete startTimer; if (playlistFile) { playlistFile->close(); playlistFile->remove(); delete playlistFile; } } //================================================================================================================ // public slots //================================================================================================================ void UpdateApp::startChecking(const bool &arg) { stdCout("Checking for updates..."); if (arg) emit showNotification("Verificando por atualizações. Aguarde..."); alert = arg; QString p("?version="+CurrentVersion); QNetworkRequest request; request.setUrl(QUrl((newURL.isEmpty() ? CheckUpdate+p : (newURL.contains("version=") ? newURL : newURL+p)))); request.setRawHeader("User-Agent", QString(AppNameId+"-"+CurrentVersion).toLocal8Bit()); updateManager->get(request); } //================================================================================================================ // private //================================================================================================================ void UpdateApp::downloadPlaylist(const QUrl &url) { QString fileName = "RadioList_" + newPlaylistDate + ".7z"; playlistFile = new QFile(Global::getConfigPath(fileName)); if (!playlistFile->open(QIODevice::WriteOnly)) { qDebug() << "Error: " << playlistFile->errorString(); delete playlistFile; playlistFile = nullptr; return; } requestAborted = false; blockRequest = true; QNetworkRequest request; request.setUrl(url); request.setRawHeader("User-Agent", QString(AppNameId+"-"+CurrentVersion).toLocal8Bit()); downloadReply = downloadManager->get(request); connect(downloadReply, SIGNAL(readyRead()), this, SLOT(readyRead())); connect(downloadReply, SIGNAL(finished()), this, SLOT(downloadFinished())); } //================================================================================================================ // private slots //================================================================================================================ void UpdateApp::readyRead() { if (playlistFile) playlistFile->write(downloadReply->readAll()); } void UpdateApp::finishedChecking(QNetworkReply *reply) { int code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); const QByteArray data = reply->readAll(); if (code == 200) { QJsonObject json = QJsonDocument::fromJson(data).object(); QJsonObject app = json.value("app").toObject(); QJsonObject radioPlaylist = json.value("radioPlaylist").toObject(); QString version = app["currentVersion"].toString(); newPlaylistName = radioPlaylist["fileName"].toString(); newPlaylistDate = radioPlaylist["date"].toString(); QUrl radiolistUrl = radioPlaylist["url"].toString(); if (!version.isEmpty()) { stdCout("Checking update is completed"); Database::setValue("Version", "updates_lastCheck", currentDate.toString("yyyy-MM-dd")); QDate listInstalled(QDate::fromString(iniSettings->value("Radiolist/Date").toString(), "yyyy-MM-dd")); QDate dateChecked(QDate::fromString(newPlaylistDate, "yyyy-MM-dd")); if (!blockRequest && !radiolistUrl.isEmpty() && listInstalled < dateChecked) downloadPlaylist(radiolistUrl); if (version == CurrentVersion && alert) { QMessageBox::information(nullptr,"Info",QString("<h3>O %1 está atualizado.</h3>Versão atual: %2").arg(AppName,version)); } else if (version != CurrentVersion) { stdCout("New version available: " + version + "\n"); if (QMessageBox::warning(nullptr,"Info",QString("<h3>Nova versão disponível</h3>Uma nova versão do <strong>%1</strong> " "está disponível,<br>é altamente recomendável que instale a atualização," "<br>pois contém várias melhorias e correções de bugs.<br><br>" "<strong>Versão instalada:</strong> %2<br>" "<strong>Nova versão:</strong> %3<br><br>Deseja acessar a internet e " "baixar a última versão?").arg(AppName,CurrentVersion,version), QMessageBox::Yes|QMessageBox::No) == QMessageBox::Yes) QDesktopServices::openUrl(QUrl(DownloadUpdate)); } reply->deleteLater(); return; } } else if (code == 301 || code == 302) { newURL = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toString(); startChecking(alert); reply->deleteLater(); return; } stdCout("Unable to check for updates. Code: " + QString::number(code)); reply->deleteLater(); if (alert) QMessageBox::warning(nullptr,"Info",QString("Não foi possível verificar se há atualizações.\nVerifique sua conexão à " "internet e tente novamente.\nCódigo do erro: %1").arg(code)); } void UpdateApp::downloadFinished() { int code = downloadReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); playlistFile->flush(); playlistFile->close(); if (!requestAborted && downloadReply->error() == QNetworkReply::NoError) { QString args("\""+Global::getAppPath()+"7zr\" x -y \""+playlistFile->fileName() +"\" -o\""+Global::getConfigPath()+"\""); if (QProcess::execute(args) == 0) { iniSettings->setValue("Radiolist/NewFileName", newPlaylistName); iniSettings->setValue("Radiolist/NewDate", newPlaylistDate); emit showNotification("A Lista de Rádios foi atualizada e\nserá ativada, após reiniciar o programa."); } else { qDebug() << "Erro ao Extrair o novo RadioList"; } } downloadReply->deleteLater(); playlistFile->remove(); delete playlistFile; playlistFile = nullptr; if (!requestAborted && (code == 301 || code == 302)) { downloadPlaylist(downloadReply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl()); return; } blockRequest = false; } <|endoftext|>
<commit_before> #include <vector> #include <string> #include <memory> #include <algorithm> #include <cstring> #include "utils.h" #include "logging.h" #include "DeviceIndex.h" #include "Error.h" #if HAVE_ARAVIS #include "aravis_utils.h" #endif #if HAVE_USB #include "v4l2_utils.h" #endif using namespace tcam; std::vector<DeviceInfo> DeviceIndex::getDeviceList () const { return device_list; } DeviceIndex::DeviceIndex () : continue_thread(false), wait_period(2) { continue_thread = true; std::thread (&DeviceIndex::run, this).detach(); device_list = std::vector<DeviceInfo>(); } DeviceIndex::~DeviceIndex () { continue_thread = false; } void DeviceIndex::register_device_lost (dev_callback c) { callbacks.push_back(c); } void DeviceIndex::updateDeviceList () { std::vector<DeviceInfo> tmp_dev_list; #if HAVE_ARAVIS auto aravis_dev_list = get_aravis_device_list(); tmp_dev_list.insert(tmp_dev_list.end(), aravis_dev_list.begin(), aravis_dev_list.end()); #endif #if HAVE_USB auto v4l2_dev_list = get_v4l2_device_list(); tmp_dev_list.insert(tmp_dev_list.end(), v4l2_dev_list.begin(), v4l2_dev_list.end()); #endif for (const auto& d : device_list) { auto f = [&d] (const DeviceInfo& info) { if (d.getSerial().compare( info.getSerial()) == 0) return true; return false; }; auto found = std::find_if(tmp_dev_list.begin(), tmp_dev_list.end(), f); if (found == tmp_dev_list.end()) { fire_device_lost(d); } } mtx.lock(); device_list.clear(); device_list.insert(device_list.end(), tmp_dev_list.begin(), tmp_dev_list.end()); mtx.unlock(); } void DeviceIndex::run () { while (continue_thread) { updateDeviceList(); std::this_thread::sleep_for(std::chrono::seconds(wait_period)); } } void DeviceIndex::fire_device_lost (const DeviceInfo& d) { for (auto& c : callbacks) { c(d); } } bool DeviceIndex::fillDeviceInfo (DeviceInfo& info) { if (!info.getSerial().empty()) { for (const auto& d : device_list) { if (info.getSerial() == d.getSerial()) { info = d; return true; } } return false; } if (!info.getIdentifier().empty()) { for (const auto& d : device_list) { if (info.getIdentifier() == d.getIdentifier()) { info = d; return true; } } return false; } return false; } std::shared_ptr<DeviceIndex> tcam::getDeviceIndex () { return std::make_shared<DeviceIndex>(); } <commit_msg>DeviceIndex updated<commit_after> #include <vector> #include <string> #include <memory> #include <algorithm> #include <cstring> #include "utils.h" #include "logging.h" #include "DeviceIndex.h" #include "Error.h" #if HAVE_ARAVIS #include "aravis_utils.h" #endif #if HAVE_USB #include "v4l2_utils.h" #endif using namespace tcam; DeviceIndex::DeviceIndex () : continue_thread(false), wait_period(2), device_list(std::vector<DeviceInfo>()), callbacks(std::vector<dev_callback>()) { continue_thread = true; std::thread (&DeviceIndex::run, this).detach(); } DeviceIndex::~DeviceIndex () { continue_thread = false; } void DeviceIndex::register_device_lost (dev_callback c) { tcam_log(TCAM_LOG_DEBUG, "Registered device lost callback"); mtx.lock(); callbacks.push_back(c); mtx.unlock(); } void DeviceIndex::updateDeviceList () { std::vector<DeviceInfo> tmp_dev_list = std::vector<DeviceInfo>(); tmp_dev_list.reserve(10); #if HAVE_ARAVIS auto aravis_dev_list = get_aravis_device_list(); if (!aravis_dev_list.empty()) tmp_dev_list.insert(tmp_dev_list.end(), aravis_dev_list.begin(), aravis_dev_list.end()); #endif #if HAVE_USB auto v4l2_dev_list = get_v4l2_device_list(); if (!v4l2_dev_list.empty()) tmp_dev_list.insert(tmp_dev_list.end(), v4l2_dev_list.begin(), v4l2_dev_list.end()); #endif for (const auto& d : device_list) { auto f = [&d] (const DeviceInfo& info) { if (d.getSerial().compare( info.getSerial()) == 0) return true; return false; }; auto found = std::find_if(tmp_dev_list.begin(), tmp_dev_list.end(), f); if (found == tmp_dev_list.end()) { fire_device_lost(d); } } mtx.lock(); device_list.clear(); device_list.insert(device_list.end(), tmp_dev_list.begin(), tmp_dev_list.end()); mtx.unlock(); } void DeviceIndex::run () { while (continue_thread) { updateDeviceList(); std::this_thread::sleep_for(std::chrono::seconds(wait_period)); } } void DeviceIndex::fire_device_lost (const DeviceInfo& d) { mtx.lock(); for (auto& c : callbacks) { c(d); } mtx.unlock(); } bool DeviceIndex::fillDeviceInfo (DeviceInfo& info) { if (!info.getSerial().empty()) { for (const auto& d : device_list) { if (info.getSerial() == d.getSerial()) { info = d; return true; } } return false; } if (!info.getIdentifier().empty()) { for (const auto& d : device_list) { if (info.getIdentifier() == d.getIdentifier()) { info = d; return true; } } } return false; } std::vector<DeviceInfo> DeviceIndex::getDeviceList () const { return device_list; } std::shared_ptr<DeviceIndex> tcam::getDeviceIndex () { return std::make_shared<DeviceIndex>(); } <|endoftext|>
<commit_before>/* Copyright (c) 2016, Dan Bethell, Johannes Saam, Vahan Sosoyan, Brian Scherbinski. All rights reserved. See COPYING.txt for more details. */ #include <ai.h> #include "Data.h" #include "Client.h" using boost::asio::ip::tcp; AI_DRIVER_NODE_EXPORT_METHODS(AtonDriverMtd); const char* getHost() { const char* aton_host = getenv("ATON_HOST"); if (aton_host == NULL) aton_host = "127.0.0.1"; char* host = new char[strlen(aton_host) + 1]; strcpy(host, aton_host); aton_host = host; return aton_host; } int getPort() { const char* def_port = getenv("ATON_PORT"); int aton_port; if (def_port == NULL) aton_port = 9201; else aton_port = atoi(def_port); return aton_port; } struct ShaderData { aton::Client* client; int xres, yres, min_x, min_y, max_x, max_y; }; node_parameters { AiParameterINT("port", getPort()); AiParameterSTR("host", getHost()); AiMetaDataSetStr(mds, NULL, "maya.translator", "aton"); AiMetaDataSetStr(mds, NULL, "maya.attr_prefix", ""); AiMetaDataSetBool(mds, NULL, "display_driver", true); AiMetaDataSetBool(mds, NULL, "single_layer_driver", false); } node_initialize { ShaderData* data = (ShaderData*)AiMalloc(sizeof(ShaderData)); data->client = NULL, AiDriverInitialize(node, true, data); } node_update {} driver_supports_pixel_type { return true; } driver_extension { return NULL; } driver_open { // Construct full version number char arch[3], major[3], minor[3], fix[3]; AiGetVersion(arch, major, minor, fix); const int version = atoi(arch) * 1000000 + atoi(major) * 10000 + atoi(minor) * 100 + atoi(fix); ShaderData* data = (ShaderData*)AiDriverGetLocalData(node); // Get Frame number AtNode* options = AiUniverseGetOptions(); const float currentFrame = AiNodeGetFlt(options, "frame"); // Get Host and Port const char* host = AiNodeGetStr(node, "host"); const int port = AiNodeGetInt(node, "port"); // Get Camera AtNode* camera = (AtNode*)AiNodeGetPtr(options, "camera"); AtMatrix cMat; AiNodeGetMatrix(camera, "matrix", cMat); const float cam_fov = AiNodeGetFlt(camera, "fov"); const float cam_matrix[16] = {cMat[0][0], cMat[1][0], cMat[2][0], cMat[3][0], cMat[0][1], cMat[1][1], cMat[2][1], cMat[3][1], cMat[0][2], cMat[1][2], cMat[2][2], cMat[3][2], cMat[0][3], cMat[1][3], cMat[2][3], cMat[3][3]}; // Get Resolution const int xres = AiNodeGetInt(options, "xres"); const int yres = AiNodeGetInt(options, "yres"); // Get Regions const int min_x = AiNodeGetInt(options, "region_min_x"); const int min_y = AiNodeGetInt(options, "region_min_y"); const int max_x = AiNodeGetInt(options, "region_max_x"); const int max_y = AiNodeGetInt(options, "region_max_y"); // Setting Origin data->min_x = (min_x == INT_MIN) ? 0 : min_x; data->min_y = (min_y == INT_MIN) ? 0 : min_y; data->max_x = (max_x == INT_MIN) ? 0 : max_x; data->max_y = (max_y == INT_MIN) ? 0 : max_y; // Setting X Resolution if (data->min_x < 0 && data->max_x >= xres) data->xres = data->max_x - data->min_x + 1; else if (data->min_x >= 0 && data->max_x < xres) data->xres = xres; else if (data->min_x < 0 && data->max_x < xres) data->xres = xres - min_x; else if(data->min_x >= 0 && data->max_x >= xres) data->xres = xres + (max_x - xres + 1); // Setting Y Resolution if (data->min_y < 0 && data->max_y >= yres) data->yres = data->max_y - data->min_y + 1; else if (data->min_y >= 0 && data->max_y < yres) data->yres = yres; else if (data->min_y < 0 && data->max_y < yres) data->yres = yres - min_y; else if(data->min_y >= 0 && data->max_y >= yres) data->yres = yres + (max_y - yres + 1); // Get area of region const long long rArea = data->xres * data->yres; // Make image header & send to server aton::Data header(data->xres, data->yres, 0, 0, 0, 0, rArea, version, currentFrame, cam_fov, cam_matrix); try // Now we can connect to the server and start rendering { if (data->client == NULL) { data->client = new aton::Client(host, port); } data->client->openImage(header); } catch(const std::exception &e) { const char* err = e.what(); AiMsgError("Aton display driver %s", err); } } driver_needs_bucket { return true; } driver_prepare_bucket { AiMsgDebug("[Aton] prepare bucket (%d, %d)", bucket_xo, bucket_yo); } driver_process_bucket { } driver_write_bucket { ShaderData* data = (ShaderData*)AiDriverGetLocalData(node); int pixel_type; int spp = 0; const void* bucket_data; const char* aov_name; if (data->min_x < 0) bucket_xo = bucket_xo - data->min_x; if (data->min_y < 0) bucket_yo = bucket_yo - data->min_y; while (AiOutputIteratorGetNext(iterator, &aov_name, &pixel_type, &bucket_data)) { const float* ptr = reinterpret_cast<const float*>(bucket_data); const long long ram = AiMsgUtilGetUsedMemory(); const unsigned int time = AiMsgUtilGetElapsedTime(); switch (pixel_type) { case(AI_TYPE_FLOAT): spp = 1; break; case(AI_TYPE_RGBA): spp = 4; break; default: spp = 3; } // Create our data object aton::Data packet(data->xres, data->yres, bucket_xo, bucket_yo, bucket_size_x, bucket_size_y, 0, 0, 0, 0, 0, spp, ram, time, aov_name, ptr); // Send it to the server data->client->sendPixels(packet); } } driver_close { AiMsgInfo("[Aton] driver close"); ShaderData* data = (ShaderData*)AiDriverGetLocalData(node); try { data->client->closeImage(); } catch (const std::exception& e) { AiMsgError("Error occured when trying to close connection"); } } node_finish { AiMsgInfo("[Aton] driver finish"); // Release the driver ShaderData* data = (ShaderData*)AiDriverGetLocalData(node); delete data->client; AiFree(data); AiDriverDestroy(node); } node_loader { sprintf(node->version, AI_VERSION); switch (i) { case 0: node->methods = (AtNodeMethods*) AtonDriverMtd; node->output_type = AI_TYPE_RGBA; node->name = "driver_aton"; node->node_type = AI_NODE_DRIVER; break; default: return false; } return true; } <commit_msg>Adds host check<commit_after>/* Copyright (c) 2016, Dan Bethell, Johannes Saam, Vahan Sosoyan, Brian Scherbinski. All rights reserved. See COPYING.txt for more details. */ #include <ai.h> #include "Data.h" #include "Client.h" using boost::asio::ip::tcp; AI_DRIVER_NODE_EXPORT_METHODS(AtonDriverMtd); const char* getHost() { const char* aton_host = getenv("ATON_HOST"); if (aton_host == NULL) aton_host = "127.0.0.1"; char* host = new char[strlen(aton_host) + 1]; strcpy(host, aton_host); aton_host = host; return aton_host; } int getPort() { const char* def_port = getenv("ATON_PORT"); int aton_port; if (def_port == NULL) aton_port = 9201; else aton_port = atoi(def_port); return aton_port; } struct ShaderData { aton::Client* client; int xres, yres, min_x, min_y, max_x, max_y; }; node_parameters { AiParameterSTR("host", getHost()); AiParameterINT("port", getPort()); AiMetaDataSetStr(mds, NULL, "maya.translator", "aton"); AiMetaDataSetStr(mds, NULL, "maya.attr_prefix", ""); AiMetaDataSetBool(mds, NULL, "display_driver", true); AiMetaDataSetBool(mds, NULL, "single_layer_driver", false); } node_initialize { ShaderData* data = (ShaderData*)AiMalloc(sizeof(ShaderData)); data->client = NULL, AiDriverInitialize(node, true, data); } node_update {} driver_supports_pixel_type { return true; } driver_extension { return NULL; } driver_open { // Construct full version number char arch[3], major[3], minor[3], fix[3]; AiGetVersion(arch, major, minor, fix); const int version = atoi(arch) * 1000000 + atoi(major) * 10000 + atoi(minor) * 100 + atoi(fix); ShaderData* data = (ShaderData*)AiDriverGetLocalData(node); // Get Frame number AtNode* options = AiUniverseGetOptions(); const float currentFrame = AiNodeGetFlt(options, "frame"); // Get Host and Port const char* host = AiNodeGetStr(node, "host"); const int port = AiNodeGetInt(node, "port"); // Get Camera AtNode* camera = (AtNode*)AiNodeGetPtr(options, "camera"); AtMatrix cMat; AiNodeGetMatrix(camera, "matrix", cMat); const float cam_fov = AiNodeGetFlt(camera, "fov"); const float cam_matrix[16] = {cMat[0][0], cMat[1][0], cMat[2][0], cMat[3][0], cMat[0][1], cMat[1][1], cMat[2][1], cMat[3][1], cMat[0][2], cMat[1][2], cMat[2][2], cMat[3][2], cMat[0][3], cMat[1][3], cMat[2][3], cMat[3][3]}; // Get Resolution const int xres = AiNodeGetInt(options, "xres"); const int yres = AiNodeGetInt(options, "yres"); // Get Regions const int min_x = AiNodeGetInt(options, "region_min_x"); const int min_y = AiNodeGetInt(options, "region_min_y"); const int max_x = AiNodeGetInt(options, "region_max_x"); const int max_y = AiNodeGetInt(options, "region_max_y"); // Setting Origin data->min_x = (min_x == INT_MIN) ? 0 : min_x; data->min_y = (min_y == INT_MIN) ? 0 : min_y; data->max_x = (max_x == INT_MIN) ? 0 : max_x; data->max_y = (max_y == INT_MIN) ? 0 : max_y; // Setting X Resolution if (data->min_x < 0 && data->max_x >= xres) data->xres = data->max_x - data->min_x + 1; else if (data->min_x >= 0 && data->max_x < xres) data->xres = xres; else if (data->min_x < 0 && data->max_x < xres) data->xres = xres - min_x; else if(data->min_x >= 0 && data->max_x >= xres) data->xres = xres + (max_x - xres + 1); // Setting Y Resolution if (data->min_y < 0 && data->max_y >= yres) data->yres = data->max_y - data->min_y + 1; else if (data->min_y >= 0 && data->max_y < yres) data->yres = yres; else if (data->min_y < 0 && data->max_y < yres) data->yres = yres - min_y; else if(data->min_y >= 0 && data->max_y >= yres) data->yres = yres + (max_y - yres + 1); // Get area of region const long long rArea = data->xres * data->yres; // Make image header & send to server aton::Data header(data->xres, data->yres, 0, 0, 0, 0, rArea, version, currentFrame, cam_fov, cam_matrix); try // Now we can connect to the server and start rendering { if (data->client == NULL) { boost::system::error_code ec; boost::asio::ip::address::from_string(host, ec); if (!ec) data->client = new aton::Client(host, port); } data->client->openImage(header); } catch(const std::exception &e) { const char* err = e.what(); AiMsgError("ATON | %s", err); } } driver_needs_bucket { return true; } driver_prepare_bucket { AiMsgDebug("[Aton] prepare bucket (%d, %d)", bucket_xo, bucket_yo); } driver_process_bucket { } driver_write_bucket { ShaderData* data = (ShaderData*)AiDriverGetLocalData(node); int pixel_type; int spp = 0; const void* bucket_data; const char* aov_name; if (data->min_x < 0) bucket_xo = bucket_xo - data->min_x; if (data->min_y < 0) bucket_yo = bucket_yo - data->min_y; while (AiOutputIteratorGetNext(iterator, &aov_name, &pixel_type, &bucket_data)) { const float* ptr = reinterpret_cast<const float*>(bucket_data); const long long ram = AiMsgUtilGetUsedMemory(); const unsigned int time = AiMsgUtilGetElapsedTime(); switch (pixel_type) { case(AI_TYPE_FLOAT): spp = 1; break; case(AI_TYPE_RGBA): spp = 4; break; default: spp = 3; } // Create our data object aton::Data packet(data->xres, data->yres, bucket_xo, bucket_yo, bucket_size_x, bucket_size_y, 0, 0, 0, 0, 0, spp, ram, time, aov_name, ptr); // Send it to the server data->client->sendPixels(packet); } } driver_close { AiMsgInfo("[Aton] driver close"); ShaderData* data = (ShaderData*)AiDriverGetLocalData(node); try { data->client->closeImage(); } catch (const std::exception& e) { AiMsgError("ATON | Error occured when trying to close connection"); } } node_finish { AiMsgInfo("[Aton] driver finish"); // Release the driver ShaderData* data = (ShaderData*)AiDriverGetLocalData(node); delete data->client; AiFree(data); AiDriverDestroy(node); } node_loader { sprintf(node->version, AI_VERSION); switch (i) { case 0: node->methods = (AtNodeMethods*) AtonDriverMtd; node->output_type = AI_TYPE_RGBA; node->name = "driver_aton"; node->node_type = AI_NODE_DRIVER; break; default: return false; } return true; } <|endoftext|>
<commit_before> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2011 Francois Beaune // // 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. // // Interface header. #include "aosurfaceshader.h" // appleseed.renderer headers. #include "renderer/kernel/shading/ambientocclusion.h" #include "renderer/kernel/shading/shadingcontext.h" #include "renderer/kernel/shading/shadingpoint.h" #include "renderer/kernel/shading/shadingresult.h" #include "renderer/modeling/input/inputarray.h" #include "renderer/modeling/input/source.h" #include "renderer/modeling/surfaceshader/surfaceshader.h" // appleseed.foundation headers. #include "foundation/image/colorspace.h" #include "foundation/utility/containers/specializedarrays.h" using namespace foundation; using namespace std; namespace renderer { namespace { // // Ambient occlusion surface shader. // const char* Model = "ao_surface_shader"; class AOSurfaceShader : public SurfaceShader { public: AOSurfaceShader( const char* name, const ParamArray& params) : SurfaceShader(name, params) , m_samples(m_params.get_required<size_t>("samples", 16)) , m_max_distance(m_params.get_required<double>("max_distance", 1.0)) { } virtual void release() override { delete this; } virtual const char* get_model() const override { return Model; } virtual void evaluate( SamplingContext& sampling_context, const ShadingContext& shading_context, const ShadingPoint& shading_point, ShadingResult& shading_result) const override { // Compute ambient occlusion. const double occlusion = compute_ambient_occlusion( sampling_context, sample_hemisphere_cosine<double>, shading_context.get_intersector(), shading_point.get_point(), shading_point.get_geometric_normal(), shading_point.get_shading_basis(), m_max_distance, m_samples, &shading_point); // Return a gray scale value proportional to the accessibility. const float accessibility = static_cast<float>(1.0 - occlusion); shading_result.set_to_linear_rgb(Color3f(accessibility)); } private: const size_t m_samples; const double m_max_distance; }; } // // AOSurfaceShaderFactory class implementation. // const char* AOSurfaceShaderFactory::get_model() const { return Model; } const char* AOSurfaceShaderFactory::get_human_readable_model() const { return "Ambient Occlusion"; } DictionaryArray AOSurfaceShaderFactory::get_widget_definitions() const { DictionaryArray definitions; { Dictionary widget; widget.insert("name", "samples"); widget.insert("label", "Samples"); widget.insert("widget", "text_box"); widget.insert("use", "required"); widget.insert("default", "16"); definitions.push_back(widget); } { Dictionary widget; widget.insert("name", "max_distance"); widget.insert("label", "Maximum Occlusion Distance"); widget.insert("widget", "text_box"); widget.insert("use", "required"); widget.insert("default", "1.0"); definitions.push_back(widget); } return definitions; } auto_release_ptr<SurfaceShader> AOSurfaceShaderFactory::create( const char* name, const ParamArray& params) const { return auto_release_ptr<SurfaceShader>( new AOSurfaceShader(name, params)); } } // namespace renderer <commit_msg>the ambient occlusion surface shader now allows to choose between uniform sampling and cosine-weighted sampling.<commit_after> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2011 Francois Beaune // // 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. // // Interface header. #include "aosurfaceshader.h" // appleseed.renderer headers. #include "renderer/kernel/shading/ambientocclusion.h" #include "renderer/kernel/shading/shadingcontext.h" #include "renderer/kernel/shading/shadingpoint.h" #include "renderer/kernel/shading/shadingresult.h" #include "renderer/modeling/input/inputarray.h" #include "renderer/modeling/input/source.h" #include "renderer/modeling/surfaceshader/surfaceshader.h" // appleseed.foundation headers. #include "foundation/image/colorspace.h" #include "foundation/utility/containers/specializedarrays.h" using namespace foundation; using namespace std; namespace renderer { namespace { // // Ambient occlusion surface shader. // const char* Model = "ao_surface_shader"; class AOSurfaceShader : public SurfaceShader { public: AOSurfaceShader( const char* name, const ParamArray& params) : SurfaceShader(name, params) , m_samples(m_params.get_required<size_t>("samples", 16)) , m_max_distance(m_params.get_required<double>("max_distance", 1.0)) { const string sampling_method = m_params.get_required<string>("sampling_method", "uniform"); if (sampling_method == "uniform") m_sampling_method = UniformSampling; else if (sampling_method == "cosine") m_sampling_method = CosineWeightedSampling; else { RENDERER_LOG_ERROR( "invalid value \"%s\" for parameter \"sampling_method\", " "using default value \"uniform\"", sampling_method.c_str()); m_sampling_method = UniformSampling; } } virtual void release() override { delete this; } virtual const char* get_model() const override { return Model; } virtual void evaluate( SamplingContext& sampling_context, const ShadingContext& shading_context, const ShadingPoint& shading_point, ShadingResult& shading_result) const override { double occlusion; if (m_sampling_method == UniformSampling) { occlusion = compute_ambient_occlusion( sampling_context, sample_hemisphere_uniform<double>, shading_context.get_intersector(), shading_point.get_point(), shading_point.get_geometric_normal(), shading_point.get_shading_basis(), m_max_distance, m_samples, &shading_point); } else { occlusion = compute_ambient_occlusion( sampling_context, sample_hemisphere_cosine<double>, shading_context.get_intersector(), shading_point.get_point(), shading_point.get_geometric_normal(), shading_point.get_shading_basis(), m_max_distance, m_samples, &shading_point); } const float accessibility = static_cast<float>(1.0 - occlusion); shading_result.set_to_linear_rgb(Color3f(accessibility)); } private: enum SamplingMethod { UniformSampling, CosineWeightedSampling }; const size_t m_samples; const double m_max_distance; SamplingMethod m_sampling_method; }; } // // AOSurfaceShaderFactory class implementation. // const char* AOSurfaceShaderFactory::get_model() const { return Model; } const char* AOSurfaceShaderFactory::get_human_readable_model() const { return "Ambient Occlusion"; } DictionaryArray AOSurfaceShaderFactory::get_widget_definitions() const { DictionaryArray definitions; definitions.push_back( Dictionary() .insert("name", "sampling_method") .insert("label", "Sampling Method") .insert("widget", "dropdown_list") .insert("dropdown_items", Dictionary() .insert("Uniform Sampling", "uniform") .insert("Cosine-Weighted Sampling", "cosine")) .insert("use", "required") .insert("default", "uniform")); definitions.push_back( Dictionary() .insert("name", "samples") .insert("label", "Samples") .insert("widget", "text_box") .insert("use", "required") .insert("default", "16")); definitions.push_back( Dictionary() .insert("name", "max_distance") .insert("label", "Maximum Occlusion Distance") .insert("widget", "text_box") .insert("use", "required") .insert("default", "1.0")); return definitions; } auto_release_ptr<SurfaceShader> AOSurfaceShaderFactory::create( const char* name, const ParamArray& params) const { return auto_release_ptr<SurfaceShader>( new AOSurfaceShader(name, params)); } } // namespace renderer <|endoftext|>
<commit_before>//===- subzero/src/IceCompiler.cpp - Driver for bitcode translation -------===// // // The Subzero Code Generator // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Defines a driver for translating PNaCl bitcode into native code. /// /// The driver can either directly parse the binary bitcode file, or use LLVM /// routines to parse a textual bitcode file into LLVM IR and then convert LLVM /// IR into ICE. In either case, the high-level ICE is then compiled down to /// native code, as either an ELF object file or a textual asm file. /// //===----------------------------------------------------------------------===// #include "IceCompiler.h" #include "IceBuildDefs.h" #include "IceCfg.h" #include "IceClFlags.h" #include "IceClFlagsExtra.h" #include "IceConverter.h" #include "IceELFObjectWriter.h" #include "PNaClTranslator.h" #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-parameter" #include "llvm/ADT/STLExtras.h" #include "llvm/Bitcode/NaCl/NaClReaderWriter.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IRReader/IRReader.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/StreamingMemoryObject.h" #pragma clang diagnostic pop namespace Ice { namespace { struct { const char *FlagName; int FlagValue; } ConditionalBuildAttributes[] = { {"dump", BuildDefs::dump()}, {"llvm_cl", BuildDefs::llvmCl()}, {"llvm_ir", BuildDefs::llvmIr()}, {"llvm_ir_as_input", BuildDefs::llvmIrAsInput()}, {"minimal_build", BuildDefs::minimal()}, {"browser_mode", BuildDefs::browser()}}; // Validates values of build attributes. Prints them to Stream if Stream is // non-null. void validateAndGenerateBuildAttributes(Ostream *Stream) { // List the supported targets. if (Stream) { #define SUBZERO_TARGET(TARGET) *Stream << "target_" #TARGET << "\n"; #include "llvm/Config/SZTargets.def" } for (size_t i = 0; i < llvm::array_lengthof(ConditionalBuildAttributes); ++i) { switch (ConditionalBuildAttributes[i].FlagValue) { case 0: if (Stream) *Stream << "no_" << ConditionalBuildAttributes[i].FlagName << "\n"; break; case 1: if (Stream) *Stream << "allow_" << ConditionalBuildAttributes[i].FlagName << "\n"; break; default: { std::string Buffer; llvm::raw_string_ostream StrBuf(Buffer); StrBuf << "Flag " << ConditionalBuildAttributes[i].FlagName << " must be defined as 0/1. Found: " << ConditionalBuildAttributes[i].FlagValue; llvm::report_fatal_error(StrBuf.str()); } } } } } // end of anonymous namespace void Compiler::run(const Ice::ClFlagsExtra &ExtraFlags, GlobalContext &Ctx, std::unique_ptr<llvm::DataStreamer> &&InputStream) { validateAndGenerateBuildAttributes( ExtraFlags.getGenerateBuildAtts() ? &Ctx.getStrDump() : nullptr); if (ExtraFlags.getGenerateBuildAtts()) return Ctx.getErrorStatus()->assign(EC_None); // The Minimal build (specifically, when dump()/emit() are not implemented) // allows only --filetype=obj. Check here to avoid cryptic error messages // downstream. if (!BuildDefs::dump() && Ctx.getFlags().getOutFileType() != FT_Elf) { // TODO(stichnot): Access the actual command-line argument via // llvm::Option.ArgStr and .ValueStr . Ctx.getStrError() << "Error: only --filetype=obj is supported in this build.\n"; return Ctx.getErrorStatus()->assign(EC_Args); } // Force -build-on-read=0 for .ll files. const std::string LLSuffix = ".ll"; const IceString &IRFilename = ExtraFlags.getIRFilename(); bool BuildOnRead = ExtraFlags.getBuildOnRead(); if (BuildDefs::llvmIrAsInput() && IRFilename.length() >= LLSuffix.length() && IRFilename.compare(IRFilename.length() - LLSuffix.length(), LLSuffix.length(), LLSuffix) == 0) BuildOnRead = false; TimerMarker T(Ice::TimerStack::TT_szmain, &Ctx); Ctx.emitFileHeader(); Ctx.startWorkerThreads(); std::unique_ptr<Translator> Translator; if (BuildOnRead) { std::unique_ptr<PNaClTranslator> PTranslator(new PNaClTranslator(&Ctx)); std::unique_ptr<llvm::StreamingMemoryObject> MemObj( new llvm::StreamingMemoryObjectImpl(InputStream.release())); PTranslator->translate(IRFilename, std::move(MemObj)); Translator.reset(PTranslator.release()); } else if (BuildDefs::llvmIr()) { if (BuildDefs::browser()) { Ctx.getStrError() << "non BuildOnRead is not supported w/ PNACL_BROWSER_TRANSLATOR\n"; return Ctx.getErrorStatus()->assign(EC_Args); } // Parse the input LLVM IR file into a module. llvm::SMDiagnostic Err; TimerMarker T1(Ice::TimerStack::TT_parse, &Ctx); llvm::DiagnosticHandlerFunction DiagnosticHandler = ExtraFlags.getLLVMVerboseErrors() ? redirectNaClDiagnosticToStream(llvm::errs()) : nullptr; std::unique_ptr<llvm::Module> Mod = NaClParseIRFile(IRFilename, ExtraFlags.getInputFileFormat(), Err, llvm::getGlobalContext(), DiagnosticHandler); if (!Mod) { Err.print(ExtraFlags.getAppName().c_str(), llvm::errs()); return Ctx.getErrorStatus()->assign(EC_Bitcode); } std::unique_ptr<Converter> Converter(new class Converter(Mod.get(), &Ctx)); Converter->convertToIce(); Translator.reset(Converter.release()); } else { Ctx.getStrError() << "Error: Build doesn't allow LLVM IR, " << "--build-on-read=0 not allowed\n"; return Ctx.getErrorStatus()->assign(EC_Args); } Ctx.waitForWorkerThreads(); if (Translator->getErrorStatus()) { Ctx.getErrorStatus()->assign(Translator->getErrorStatus().value()); } else { Ctx.lowerGlobals("last"); Ctx.lowerProfileData(); Ctx.lowerConstants(); Ctx.lowerJumpTables(); if (Ctx.getFlags().getOutFileType() == FT_Elf) { TimerMarker T1(Ice::TimerStack::TT_emit, &Ctx); Ctx.getObjectWriter()->setUndefinedSyms(Ctx.getConstantExternSyms()); Ctx.getObjectWriter()->writeNonUserSections(); } } if (Ctx.getFlags().getSubzeroTimingEnabled()) Ctx.dumpTimers(); if (Ctx.getFlags().getTimeEachFunction()) { constexpr bool DumpCumulative = false; Ctx.dumpTimers(GlobalContext::TSK_Funcs, DumpCumulative); } constexpr bool FinalStats = true; Ctx.dumpStats("_FINAL_", FinalStats); } } // end of namespace Ice <commit_msg>cleanup and rename validateAndGenerateBuildAttributes<commit_after>//===- subzero/src/IceCompiler.cpp - Driver for bitcode translation -------===// // // The Subzero Code Generator // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Defines a driver for translating PNaCl bitcode into native code. /// /// The driver can either directly parse the binary bitcode file, or use LLVM /// routines to parse a textual bitcode file into LLVM IR and then convert LLVM /// IR into ICE. In either case, the high-level ICE is then compiled down to /// native code, as either an ELF object file or a textual asm file. /// //===----------------------------------------------------------------------===// #include "IceCompiler.h" #include "IceBuildDefs.h" #include "IceCfg.h" #include "IceClFlags.h" #include "IceClFlagsExtra.h" #include "IceConverter.h" #include "IceELFObjectWriter.h" #include "PNaClTranslator.h" #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-parameter" #include "llvm/ADT/STLExtras.h" #include "llvm/Bitcode/NaCl/NaClReaderWriter.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IRReader/IRReader.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/StreamingMemoryObject.h" #pragma clang diagnostic pop namespace Ice { namespace { struct { const char *FlagName; bool FlagValue; } ConditionalBuildAttributes[] = { {"dump", BuildDefs::dump()}, {"llvm_cl", BuildDefs::llvmCl()}, {"llvm_ir", BuildDefs::llvmIr()}, {"llvm_ir_as_input", BuildDefs::llvmIrAsInput()}, {"minimal_build", BuildDefs::minimal()}, {"browser_mode", BuildDefs::browser()}}; /// Dumps values of build attributes to Stream if Stream is non-null. void dumpBuildAttributes(Ostream *Stream) { if (Stream == nullptr) return; // List the supported targets. #define SUBZERO_TARGET(TARGET) *Stream << "target_" #TARGET << "\n"; #include "llvm/Config/SZTargets.def" const char *Prefix[2] = {"no", "allow"}; for (size_t i = 0; i < llvm::array_lengthof(ConditionalBuildAttributes); ++i) { const auto &A = ConditionalBuildAttributes[i]; *Stream << Prefix[A.FlagValue] << "_" << A.FlagName << "\n"; } } } // end of anonymous namespace void Compiler::run(const Ice::ClFlagsExtra &ExtraFlags, GlobalContext &Ctx, std::unique_ptr<llvm::DataStreamer> &&InputStream) { dumpBuildAttributes(ExtraFlags.getGenerateBuildAtts() ? &Ctx.getStrDump() : nullptr); if (ExtraFlags.getGenerateBuildAtts()) return Ctx.getErrorStatus()->assign(EC_None); // The Minimal build (specifically, when dump()/emit() are not implemented) // allows only --filetype=obj. Check here to avoid cryptic error messages // downstream. if (!BuildDefs::dump() && Ctx.getFlags().getOutFileType() != FT_Elf) { // TODO(stichnot): Access the actual command-line argument via // llvm::Option.ArgStr and .ValueStr . Ctx.getStrError() << "Error: only --filetype=obj is supported in this build.\n"; return Ctx.getErrorStatus()->assign(EC_Args); } // Force -build-on-read=0 for .ll files. const std::string LLSuffix = ".ll"; const IceString &IRFilename = ExtraFlags.getIRFilename(); bool BuildOnRead = ExtraFlags.getBuildOnRead(); if (BuildDefs::llvmIrAsInput() && IRFilename.length() >= LLSuffix.length() && IRFilename.compare(IRFilename.length() - LLSuffix.length(), LLSuffix.length(), LLSuffix) == 0) BuildOnRead = false; TimerMarker T(Ice::TimerStack::TT_szmain, &Ctx); Ctx.emitFileHeader(); Ctx.startWorkerThreads(); std::unique_ptr<Translator> Translator; if (BuildOnRead) { std::unique_ptr<PNaClTranslator> PTranslator(new PNaClTranslator(&Ctx)); std::unique_ptr<llvm::StreamingMemoryObject> MemObj( new llvm::StreamingMemoryObjectImpl(InputStream.release())); PTranslator->translate(IRFilename, std::move(MemObj)); Translator.reset(PTranslator.release()); } else if (BuildDefs::llvmIr()) { if (BuildDefs::browser()) { Ctx.getStrError() << "non BuildOnRead is not supported w/ PNACL_BROWSER_TRANSLATOR\n"; return Ctx.getErrorStatus()->assign(EC_Args); } // Parse the input LLVM IR file into a module. llvm::SMDiagnostic Err; TimerMarker T1(Ice::TimerStack::TT_parse, &Ctx); llvm::DiagnosticHandlerFunction DiagnosticHandler = ExtraFlags.getLLVMVerboseErrors() ? redirectNaClDiagnosticToStream(llvm::errs()) : nullptr; std::unique_ptr<llvm::Module> Mod = NaClParseIRFile(IRFilename, ExtraFlags.getInputFileFormat(), Err, llvm::getGlobalContext(), DiagnosticHandler); if (!Mod) { Err.print(ExtraFlags.getAppName().c_str(), llvm::errs()); return Ctx.getErrorStatus()->assign(EC_Bitcode); } std::unique_ptr<Converter> Converter(new class Converter(Mod.get(), &Ctx)); Converter->convertToIce(); Translator.reset(Converter.release()); } else { Ctx.getStrError() << "Error: Build doesn't allow LLVM IR, " << "--build-on-read=0 not allowed\n"; return Ctx.getErrorStatus()->assign(EC_Args); } Ctx.waitForWorkerThreads(); if (Translator->getErrorStatus()) { Ctx.getErrorStatus()->assign(Translator->getErrorStatus().value()); } else { Ctx.lowerGlobals("last"); Ctx.lowerProfileData(); Ctx.lowerConstants(); Ctx.lowerJumpTables(); if (Ctx.getFlags().getOutFileType() == FT_Elf) { TimerMarker T1(Ice::TimerStack::TT_emit, &Ctx); Ctx.getObjectWriter()->setUndefinedSyms(Ctx.getConstantExternSyms()); Ctx.getObjectWriter()->writeNonUserSections(); } } if (Ctx.getFlags().getSubzeroTimingEnabled()) Ctx.dumpTimers(); if (Ctx.getFlags().getTimeEachFunction()) { constexpr bool DumpCumulative = false; Ctx.dumpTimers(GlobalContext::TSK_Funcs, DumpCumulative); } constexpr bool FinalStats = true; Ctx.dumpStats("_FINAL_", FinalStats); } } // end of namespace Ice <|endoftext|>
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. 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. #ifndef IOX_POSH_POPO_BUILDING_BLOCKS_CHUNK_DISTRIBUTOR_DATA_INL #define IOX_POSH_POPO_BUILDING_BLOCKS_CHUNK_DISTRIBUTOR_DATA_INL namespace iox { namespace popo { /// @todo Add min() without reference to algorithms?! C++11 needs a declaration for constexpr! template <typename T> constexpr T min(const T left, const T right) { return (left < right) ? left : right; } template <typename ChunkDistributorDataProperties, typename LockingPolicy, typename ChunkQueuePusherType> inline ChunkDistributorData<ChunkDistributorDataProperties, LockingPolicy, ChunkQueuePusherType>::ChunkDistributorData( const uint64_t historyCapacity) noexcept : LockingPolicy() , m_historyCapacity(min(historyCapacity, ChunkDistributorDataProperties_t::MAX_HISTORY_CAPACITY)) { if (m_historyCapacity != historyCapacity) { LogWarn() << "Chunk history too large, reducing from " << historyCapacity << " to " << ChunkDistributorDataProperties_t::MAX_HISTORY_CAPACITY; } } } // namespace popo } // namespace iox #endif // IOX_POSH_POPO_BUILDING_BLOCKS_CHUNK_DISTRIBUTOR_DATA_INL <commit_msg>iox-#25: Add more comments regarding constexpr usage with references<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. 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. #ifndef IOX_POSH_POPO_BUILDING_BLOCKS_CHUNK_DISTRIBUTOR_DATA_INL #define IOX_POSH_POPO_BUILDING_BLOCKS_CHUNK_DISTRIBUTOR_DATA_INL namespace iox { namespace popo { /// @todo Add min() without reference to iox::algorithm?! C++11 needs a declaration for constexpr! /// Ex.: constexpr uint32_t DefaultChunkDistributorConfig::MAX_HISTORY_CAPACITY; /// This wouldn't be an issue in C++17. template <typename T> constexpr T min(const T left, const T right) { return (left < right) ? left : right; } template <typename ChunkDistributorDataProperties, typename LockingPolicy, typename ChunkQueuePusherType> inline ChunkDistributorData<ChunkDistributorDataProperties, LockingPolicy, ChunkQueuePusherType>::ChunkDistributorData( const uint64_t historyCapacity) noexcept : LockingPolicy() , m_historyCapacity(min(historyCapacity, ChunkDistributorDataProperties_t::MAX_HISTORY_CAPACITY)) { if (m_historyCapacity != historyCapacity) { LogWarn() << "Chunk history too large, reducing from " << historyCapacity << " to " << ChunkDistributorDataProperties_t::MAX_HISTORY_CAPACITY; } } } // namespace popo } // namespace iox #endif // IOX_POSH_POPO_BUILDING_BLOCKS_CHUNK_DISTRIBUTOR_DATA_INL <|endoftext|>
<commit_before>// Copyright (c) 2008, 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 "SkPaintContext.h" #include "SkColorPriv.h" #include "SkShader.h" #include "SkDashPathEffect.h" namespace { int RoundToInt(float x) { // Android uses roundf which VC doesn't have, emulate that function. if (fmodf(x, 1.0f) >= 0.5f) return (int)ceilf(x); return (int)floorf(x); } } /* TODO / questions mAlpha: how does this interact with the alpha in Color? multiply them together? mPorterDuffMode: do I always respect this? If so, then the rgb() & 0xFF000000 check will abort drawing too often Is Color premultiplied or not? If it is, then I can't blindly pass it to paint.setColor() */ struct SkPaintContext::State { float mMiterLimit; float mAlpha; SkDrawLooper* mLooper; SkPaint::Cap mLineCap; SkPaint::Join mLineJoin; SkPorterDuff::Mode mPorterDuffMode; // Ratio of the length of a dash to its width. int mDashRatio; SkColor mFillColor; StrokeStyle mStrokeStyle; SkColor mStrokeColor; float mStrokeThickness; bool mUseAntialiasing; SkDashPathEffect* mDash; SkShader* mGradient; SkShader* mPattern; // Note: Keep theses default values in sync with GraphicsContextState. State() : mMiterLimit(4), mAlpha(1), mLooper(NULL), mLineCap(SkPaint::kDefault_Cap), mLineJoin(SkPaint::kDefault_Join), mPorterDuffMode(SkPorterDuff::kSrcOver_Mode), mDashRatio(3), mFillColor(0xFF000000), mStrokeStyle(SolidStroke), mStrokeColor(0x0FF000000), mStrokeThickness(0), mUseAntialiasing(true), mDash(NULL), mGradient(NULL), mPattern(NULL) { } State(const State& other) { other.mLooper->safeRef(); memcpy(this, &other, sizeof(State)); mDash->safeRef(); mGradient->safeRef(); mPattern->safeRef(); } ~State() { mLooper->safeUnref(); mDash->safeUnref(); mGradient->safeUnref(); mPattern->safeUnref(); } SkDrawLooper* setDrawLooper(SkDrawLooper* dl) { SkRefCnt_SafeAssign(mLooper, dl); return dl; } SkColor applyAlpha(SkColor c) const { int s = RoundToInt(mAlpha * 256); if (s >= 256) return c; if (s < 0) return 0; int a = SkAlphaMul(SkColorGetA(c), s); return (c & 0x00FFFFFF) | (a << 24); } private: // Not supported yet. void operator=(const State&); }; // Context will be NULL if painting should be disabled. SkPaintContext::SkPaintContext(gfx::PlatformCanvas* context) : canvas_(context), state_stack_(sizeof(State)) { State* state = reinterpret_cast<State*>(state_stack_.push_back()); new (state) State(); state_ = state; } SkPaintContext::~SkPaintContext() { // we force restores so we don't leak any subobjects owned by our // stack of State records. while (state_stack_.count() > 0) { reinterpret_cast<State*>(state_stack_.back())->~State(); state_stack_.pop_back(); } } void SkPaintContext::save() { State* newState = reinterpret_cast<State*>(state_stack_.push_back()); new (newState) State(*state_); state_ = newState; // Save our native canvas. canvas()->save(); } void SkPaintContext::restore() { // Restore our native canvas. canvas()->restore(); state_->~State(); state_stack_.pop_back(); state_ = reinterpret_cast<State*>(state_stack_.back()); } void SkPaintContext::drawRect(SkRect rect) { SkPaint paint; int fillcolor_not_transparent = state_->mFillColor & 0xFF000000; if (fillcolor_not_transparent) { setup_paint_fill(&paint); canvas()->drawRect(rect, paint); } if (state_->mStrokeStyle != NoStroke && (state_->mStrokeColor & 0xFF000000)) { if (fillcolor_not_transparent) { // This call is expensive so don't call it unnecessarily. paint.reset(); } setup_paint_stroke(&paint, &rect, 0); canvas()->drawRect(rect, paint); } } void SkPaintContext::setup_paint_common(SkPaint* paint) const { #ifdef SK_DEBUGx { SkPaint defaultPaint; SkASSERT(*paint == defaultPaint); } #endif paint->setAntiAlias(state_->mUseAntialiasing); paint->setPorterDuffXfermode(state_->mPorterDuffMode); paint->setLooper(state_->mLooper); if(state_->mGradient) { paint->setShader(state_->mGradient); } else if (state_->mPattern) { paint->setShader(state_->mPattern); } } void SkPaintContext::setup_paint_fill(SkPaint* paint) const { setup_paint_common(paint); paint->setColor(state_->applyAlpha(state_->mFillColor)); } int SkPaintContext::setup_paint_stroke(SkPaint* paint, SkRect* rect, int length) { setup_paint_common(paint); float width = state_->mStrokeThickness; //this allows dashing and dotting to work properly for hairline strokes if (0 == width) width = 1; paint->setColor(state_->applyAlpha(state_->mStrokeColor)); paint->setStyle(SkPaint::kStroke_Style); paint->setStrokeWidth(SkFloatToScalar(width)); paint->setStrokeCap(state_->mLineCap); paint->setStrokeJoin(state_->mLineJoin); paint->setStrokeMiter(SkFloatToScalar(state_->mMiterLimit)); if (rect != NULL && (RoundToInt(width) & 1)) { rect->inset(-SK_ScalarHalf, -SK_ScalarHalf); } if (state_->mDash) { paint->setPathEffect(state_->mDash); } else { switch (state_->mStrokeStyle) { case NoStroke: case SolidStroke: break; case DashedStroke: width = state_->mDashRatio * width; /* no break */ case DottedStroke: SkScalar dashLength; if (length) { //determine about how many dashes or dots we should have int numDashes = length/RoundToInt(width); if (!(numDashes & 1)) numDashes++; //make it odd so we end on a dash/dot //use the number of dashes to determine the length of a dash/dot, which will be approximately width dashLength = SkScalarDiv(SkIntToScalar(length), SkIntToScalar(numDashes)); } else { dashLength = SkFloatToScalar(width); } SkScalar intervals[2] = { dashLength, dashLength }; paint->setPathEffect(new SkDashPathEffect(intervals, 2, 0))->unref(); } } return RoundToInt(width); } SkDrawLooper* SkPaintContext::setDrawLooper(SkDrawLooper* dl) { return state_->setDrawLooper(dl); } void SkPaintContext::setMiterLimit(float ml) { state_->mMiterLimit = ml; } void SkPaintContext::setAlpha(float alpha) { state_->mAlpha = alpha; } void SkPaintContext::setLineCap(SkPaint::Cap lc) { state_->mLineCap = lc; } void SkPaintContext::setLineJoin(SkPaint::Join lj) { state_->mLineJoin = lj; } void SkPaintContext::setPorterDuffMode(SkPorterDuff::Mode pdm) { state_->mPorterDuffMode = pdm; } void SkPaintContext::setFillColor(SkColor color) { state_->mFillColor = color; } void SkPaintContext::setStrokeStyle(StrokeStyle strokestyle) { state_->mStrokeStyle = strokestyle; } void SkPaintContext::setStrokeColor(SkColor strokecolor) { state_->mStrokeColor = strokecolor; } void SkPaintContext::setStrokeThickness(float thickness) { state_->mStrokeThickness = thickness; } void SkPaintContext::setUseAntialiasing(bool enable) { state_->mUseAntialiasing = enable; } SkColor SkPaintContext::fillColor() const { return state_->mFillColor; } void SkPaintContext::beginPath() { path_.reset(); } void SkPaintContext::addPath(const SkPath& path) { path_.addPath(path); } SkPath* SkPaintContext::currentPath() { return &path_; } void SkPaintContext::setFillRule(SkPath::FillType fr) { path_.setFillType(fr); } void SkPaintContext::setGradient(SkShader* gradient) { if (gradient != state_->mGradient) { state_->mGradient->safeUnref(); state_->mGradient=gradient; } } void SkPaintContext::setPattern(SkShader* pattern) { if (pattern != state_->mPattern) { state_->mPattern->safeUnref(); state_->mPattern=pattern; } } void SkPaintContext::setDashPathEffect(SkDashPathEffect* dash) { if (dash != state_->mDash) { state_->mDash->safeUnref(); state_->mDash=dash; } } <commit_msg>Roll back r2882 to see if it reduces the crash rate.<commit_after>// Copyright (c) 2008, 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 <new> #include "SkPaintContext.h" #include "SkColorPriv.h" #include "SkShader.h" #include "SkDashPathEffect.h" namespace { int RoundToInt(float x) { // Android uses roundf which VC doesn't have, emulate that function. if (fmodf(x, 1.0f) >= 0.5f) return (int)ceilf(x); return (int)floorf(x); } } /* TODO / questions mAlpha: how does this interact with the alpha in Color? multiply them together? mPorterDuffMode: do I always respect this? If so, then the rgb() & 0xFF000000 check will abort drawing too often Is Color premultiplied or not? If it is, then I can't blindly pass it to paint.setColor() */ struct SkPaintContext::State { float mMiterLimit; float mAlpha; SkDrawLooper* mLooper; SkPaint::Cap mLineCap; SkPaint::Join mLineJoin; SkPorterDuff::Mode mPorterDuffMode; // Ratio of the length of a dash to its width. int mDashRatio; SkColor mFillColor; StrokeStyle mStrokeStyle; SkColor mStrokeColor; float mStrokeThickness; bool mUseAntialiasing; SkDashPathEffect* mDash; SkShader* mGradient; SkShader* mPattern; // Note: Keep theses default values in sync with GraphicsContextState. State() : mMiterLimit(4), mAlpha(1), mLooper(NULL), mLineCap(SkPaint::kDefault_Cap), mLineJoin(SkPaint::kDefault_Join), mPorterDuffMode(SkPorterDuff::kSrcOver_Mode), mDashRatio(3), mFillColor(0xFF000000), mStrokeStyle(SolidStroke), mStrokeColor(0x0FF000000), mStrokeThickness(0), mUseAntialiasing(true), mDash(NULL), mGradient(NULL), mPattern(NULL) { } State(const State& other) { other.mLooper->safeRef(); memcpy(this, &other, sizeof(State)); mDash->safeRef(); mGradient->safeRef(); mPattern->safeRef(); } ~State() { mLooper->safeUnref(); mDash->safeUnref(); mGradient->safeUnref(); mPattern->safeUnref(); } SkDrawLooper* setDrawLooper(SkDrawLooper* dl) { SkRefCnt_SafeAssign(mLooper, dl); return dl; } SkColor applyAlpha(SkColor c) const { int s = RoundToInt(mAlpha * 256); if (s >= 256) return c; if (s < 0) return 0; int a = SkAlphaMul(SkColorGetA(c), s); return (c & 0x00FFFFFF) | (a << 24); } private: // Not supported yet. void operator=(const State&); }; // Context will be NULL if painting should be disabled. SkPaintContext::SkPaintContext(gfx::PlatformCanvas* context) : canvas_(context), state_stack_(sizeof(State)) { State* state = reinterpret_cast<State*>(state_stack_.push_back()); new (state) State(); state_ = state; } SkPaintContext::~SkPaintContext() { // we force restores so we don't leak any subobjects owned by our // stack of State records. while (state_stack_.count() > 0) { reinterpret_cast<State*>(state_stack_.back())->~State(); state_stack_.pop_back(); } } void SkPaintContext::save() { State* newState = reinterpret_cast<State*>(state_stack_.push_back()); new (newState) State(*state_); state_ = newState; // Save our native canvas. canvas()->save(); } void SkPaintContext::restore() { // Restore our native canvas. canvas()->restore(); state_->~State(); state_stack_.pop_back(); state_ = reinterpret_cast<State*>(state_stack_.back()); } void SkPaintContext::drawRect(SkRect rect) { SkPaint paint; int fillcolor_not_transparent = state_->mFillColor & 0xFF000000; if (fillcolor_not_transparent) { setup_paint_fill(&paint); canvas()->drawRect(rect, paint); } if (state_->mStrokeStyle != NoStroke && (state_->mStrokeColor & 0xFF000000)) { if (fillcolor_not_transparent) { // This call is expensive so don't call it unnecessarily. paint.reset(); } setup_paint_stroke(&paint, &rect, 0); canvas()->drawRect(rect, paint); } } void SkPaintContext::setup_paint_common(SkPaint* paint) const { #ifdef SK_DEBUGx { SkPaint defaultPaint; SkASSERT(*paint == defaultPaint); } #endif paint->setAntiAlias(state_->mUseAntialiasing); paint->setPorterDuffXfermode(state_->mPorterDuffMode); paint->setLooper(state_->mLooper); if(state_->mGradient) { paint->setShader(state_->mGradient); } else if (state_->mPattern) { paint->setShader(state_->mPattern); } } void SkPaintContext::setup_paint_fill(SkPaint* paint) const { setup_paint_common(paint); paint->setColor(state_->applyAlpha(state_->mFillColor)); } int SkPaintContext::setup_paint_stroke(SkPaint* paint, SkRect* rect, int length) { setup_paint_common(paint); float width = state_->mStrokeThickness; //this allows dashing and dotting to work properly for hairline strokes if (0 == width) width = 1; paint->setColor(state_->applyAlpha(state_->mStrokeColor)); paint->setStyle(SkPaint::kStroke_Style); paint->setStrokeWidth(SkFloatToScalar(width)); paint->setStrokeCap(state_->mLineCap); paint->setStrokeJoin(state_->mLineJoin); paint->setStrokeMiter(SkFloatToScalar(state_->mMiterLimit)); if (rect != NULL && (RoundToInt(width) & 1)) { rect->inset(-SK_ScalarHalf, -SK_ScalarHalf); } if (state_->mDash) { paint->setPathEffect(state_->mDash); } else { switch (state_->mStrokeStyle) { case NoStroke: case SolidStroke: break; case DashedStroke: width = state_->mDashRatio * width; /* no break */ case DottedStroke: SkScalar dashLength; if (length) { //determine about how many dashes or dots we should have int numDashes = length/RoundToInt(width); if (!(numDashes & 1)) numDashes++; //make it odd so we end on a dash/dot //use the number of dashes to determine the length of a dash/dot, which will be approximately width dashLength = SkScalarDiv(SkIntToScalar(length), SkIntToScalar(numDashes)); } else { dashLength = SkFloatToScalar(width); } SkScalar intervals[2] = { dashLength, dashLength }; paint->setPathEffect(new SkDashPathEffect(intervals, 2, 0))->unref(); } } return RoundToInt(width); } SkDrawLooper* SkPaintContext::setDrawLooper(SkDrawLooper* dl) { return state_->setDrawLooper(dl); } void SkPaintContext::setMiterLimit(float ml) { state_->mMiterLimit = ml; } void SkPaintContext::setAlpha(float alpha) { state_->mAlpha = alpha; } void SkPaintContext::setLineCap(SkPaint::Cap lc) { state_->mLineCap = lc; } void SkPaintContext::setLineJoin(SkPaint::Join lj) { state_->mLineJoin = lj; } void SkPaintContext::setPorterDuffMode(SkPorterDuff::Mode pdm) { state_->mPorterDuffMode = pdm; } void SkPaintContext::setFillColor(SkColor color) { state_->mFillColor = color; } void SkPaintContext::setStrokeStyle(StrokeStyle strokestyle) { state_->mStrokeStyle = strokestyle; } void SkPaintContext::setStrokeColor(SkColor strokecolor) { state_->mStrokeColor = strokecolor; } void SkPaintContext::setStrokeThickness(float thickness) { state_->mStrokeThickness = thickness; } void SkPaintContext::setUseAntialiasing(bool enable) { state_->mUseAntialiasing = enable; } SkColor SkPaintContext::fillColor() const { return state_->mFillColor; } void SkPaintContext::beginPath() { path_.reset(); } void SkPaintContext::addPath(const SkPath& path) { path_.addPath(path); } SkPath* SkPaintContext::currentPath() { return &path_; } void SkPaintContext::setFillRule(SkPath::FillType fr) { path_.setFillType(fr); } void SkPaintContext::setGradient(SkShader* gradient) { if (gradient != state_->mGradient) { state_->mGradient->safeUnref(); state_->mGradient=gradient; } } void SkPaintContext::setPattern(SkShader* pattern) { if (pattern != state_->mPattern) { state_->mPattern->safeUnref(); state_->mPattern=pattern; } } void SkPaintContext::setDashPathEffect(SkDashPathEffect* dash) { if (dash != state_->mDash) { state_->mDash->safeUnref(); state_->mDash=dash; } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: PersAttrListTContext.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2007-06-27 16:22:44 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _XMLOFF_PERSATTRLISTTCONTEXT_HXX #define _XMLOFF_PERSATTRLISTTCONTEXT_HXX #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_TRANSFORMERCONTEXT_HXX #include "TransformerContext.hxx" #endif class XMLPersAttrListTContext : public XMLTransformerContext { ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > m_xAttrList; ::rtl::OUString m_aElemQName; sal_uInt16 m_nActionMap; protected: void SetExportQName( const ::rtl::OUString& r ) { m_aElemQName = r; } public: TYPEINFO(); // A contexts constructor does anything that is required if an element // starts. Namespace processing has been done already. // Note that virtual methods cannot be used inside constructors. Use // StartElement instead if this is required. XMLPersAttrListTContext( XMLTransformerBase& rTransformer, const ::rtl::OUString& rQName ); // attr list persistence + attribute processing XMLPersAttrListTContext( XMLTransformerBase& rTransformer, const ::rtl::OUString& rQName, sal_uInt16 nActionMap ); // attr list persistence + renaming XMLPersAttrListTContext( XMLTransformerBase& rTransformer, const ::rtl::OUString& rQName, sal_uInt16 nPrefix, ::xmloff::token::XMLTokenEnum eToken ); // attr list persistence + renaming + attribute processing XMLPersAttrListTContext( XMLTransformerBase& rTransformer, const ::rtl::OUString& rQName, sal_uInt16 nPrefix, ::xmloff::token::XMLTokenEnum eToken, sal_uInt16 nActionMap ); // A contexts destructor does anything that is required if an element // ends. By default, nothing is done. // Note that virtual methods cannot be used inside destructors. Use // EndElement instead if this is required. virtual ~XMLPersAttrListTContext(); // Create a childs element context. By default, the import's // CreateContext method is called to create a new default context. virtual XMLTransformerContext *CreateChildContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::rtl::OUString& rQName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList ); // StartElement is called after a context has been constructed and // before a elements context is parsed. It may be used for actions that // require virtual methods. The default is to do nothing. virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList ); // EndElement is called before a context will be destructed, but // after a elements context has been parsed. It may be used for actions // that require virtual methods. The default is to do nothing. virtual void EndElement(); // This method is called for all characters that are contained in the // current element. virtual void Characters( const ::rtl::OUString& rChars ); virtual sal_Bool IsPersistent() const; virtual void Export(); virtual void ExportContent(); const ::rtl::OUString& GetExportQName() const { return m_aElemQName; } void AddAttribute( sal_uInt16 nAPrefix, ::xmloff::token::XMLTokenEnum eAToken, ::xmloff::token::XMLTokenEnum eVToken ); void AddAttribute( sal_uInt16 nAPrefix, ::xmloff::token::XMLTokenEnum eAToken, const ::rtl::OUString & rValue ); ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > GetAttrList() const; }; #endif // _XMLOFF_PERSATTRLISTTCONTEXT_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.6.162); FILE MERGED 2008/04/01 13:05:48 thb 1.6.162.2: #i85898# Stripping all external header guards 2008/03/31 16:28:52 rt 1.6.162.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: PersAttrListTContext.hxx,v $ * $Revision: 1.7 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _XMLOFF_PERSATTRLISTTCONTEXT_HXX #define _XMLOFF_PERSATTRLISTTCONTEXT_HXX #include <xmloff/xmltoken.hxx> #include "TransformerContext.hxx" class XMLPersAttrListTContext : public XMLTransformerContext { ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > m_xAttrList; ::rtl::OUString m_aElemQName; sal_uInt16 m_nActionMap; protected: void SetExportQName( const ::rtl::OUString& r ) { m_aElemQName = r; } public: TYPEINFO(); // A contexts constructor does anything that is required if an element // starts. Namespace processing has been done already. // Note that virtual methods cannot be used inside constructors. Use // StartElement instead if this is required. XMLPersAttrListTContext( XMLTransformerBase& rTransformer, const ::rtl::OUString& rQName ); // attr list persistence + attribute processing XMLPersAttrListTContext( XMLTransformerBase& rTransformer, const ::rtl::OUString& rQName, sal_uInt16 nActionMap ); // attr list persistence + renaming XMLPersAttrListTContext( XMLTransformerBase& rTransformer, const ::rtl::OUString& rQName, sal_uInt16 nPrefix, ::xmloff::token::XMLTokenEnum eToken ); // attr list persistence + renaming + attribute processing XMLPersAttrListTContext( XMLTransformerBase& rTransformer, const ::rtl::OUString& rQName, sal_uInt16 nPrefix, ::xmloff::token::XMLTokenEnum eToken, sal_uInt16 nActionMap ); // A contexts destructor does anything that is required if an element // ends. By default, nothing is done. // Note that virtual methods cannot be used inside destructors. Use // EndElement instead if this is required. virtual ~XMLPersAttrListTContext(); // Create a childs element context. By default, the import's // CreateContext method is called to create a new default context. virtual XMLTransformerContext *CreateChildContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::rtl::OUString& rQName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList ); // StartElement is called after a context has been constructed and // before a elements context is parsed. It may be used for actions that // require virtual methods. The default is to do nothing. virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList ); // EndElement is called before a context will be destructed, but // after a elements context has been parsed. It may be used for actions // that require virtual methods. The default is to do nothing. virtual void EndElement(); // This method is called for all characters that are contained in the // current element. virtual void Characters( const ::rtl::OUString& rChars ); virtual sal_Bool IsPersistent() const; virtual void Export(); virtual void ExportContent(); const ::rtl::OUString& GetExportQName() const { return m_aElemQName; } void AddAttribute( sal_uInt16 nAPrefix, ::xmloff::token::XMLTokenEnum eAToken, ::xmloff::token::XMLTokenEnum eVToken ); void AddAttribute( sal_uInt16 nAPrefix, ::xmloff::token::XMLTokenEnum eAToken, const ::rtl::OUString & rValue ); ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > GetAttrList() const; }; #endif // _XMLOFF_PERSATTRLISTTCONTEXT_HXX <|endoftext|>
<commit_before>// // Created by 理 傅 on 16/7/9. // #include "sess.h" #include <sys/socket.h> #include <sys/fcntl.h> #include <arpa/inet.h> #include <sys/time.h> #include <unistd.h> #include <string.h> UDPSession * UDPSession::Dial(const char *ip, uint16_t port) { int sockfd = socket(PF_INET, SOCK_DGRAM, 0); if (sockfd == -1) { return 0; } int flags = fcntl(sockfd, F_GETFL, 0); fcntl(sockfd, F_SETFL, flags | O_NONBLOCK); struct sockaddr_in saddr; saddr.sin_family = AF_INET; saddr.sin_port = htons(port); saddr.sin_addr.s_addr = inet_addr(ip); memset(&saddr.sin_zero, 0, 8); if (connect(sockfd, (struct sockaddr *) &saddr, sizeof(struct sockaddr)) < 0) { return 0; } void *buf = malloc(UDPSession::mtuLimit); if (buf == 0) { return 0; } UDPSession *sess = new(UDPSession); sess->m_sockfd = sockfd; sess->m_kcp = ikcp_create(IUINT32(rand()), sess); sess->m_kcp->output = sess->out_wrapper; sess->m_buf = buf; return sess; } void UDPSession::Update() { while (1) { ssize_t ret = recv(m_sockfd, m_buf, m_bufsiz, 0); if (ret > 0) { ikcp_input(m_kcp, static_cast<const char *>(m_buf), ret); } else { break; } } ikcp_update(m_kcp, iclock()); } void UDPSession::Close() { if (m_sockfd != 0) { close(m_sockfd); } if (m_buf != 0) { free(m_buf); } if (m_kcp != 0) { ikcp_release(m_kcp); } delete this; } int UDPSession::out_wrapper(const char *buf, int len, struct IKCPCB *kcp, void *user) { UDPSession *sess = static_cast<UDPSession *>(user); return sess->output(buf, len); } ssize_t UDPSession::output(const void *buffer, size_t length) { return ::send(m_sockfd, buffer, length, 0); } void UDPSession::itimeofday(long *sec, long *usec) { #if defined(__unix) struct timeval time; gettimeofday(&time, NULL); if (sec) *sec = time.tv_sec; if (usec) *usec = time.tv_usec; #else static long mode = 0, addsec = 0; BOOL retval; static IINT64 freq = 1; IINT64 qpc; if (mode == 0) { retval = QueryPerformanceFrequency((LARGE_INTEGER*)&freq); freq = (freq == 0)? 1 : freq; retval = QueryPerformanceCounter((LARGE_INTEGER*)&qpc); addsec = (long)time(NULL); addsec = addsec - (long)((qpc / freq) & 0x7fffffff); mode = 1; } retval = QueryPerformanceCounter((LARGE_INTEGER*)&qpc); retval = retval * 2; if (sec) *sec = (long)(qpc / freq) + addsec; if (usec) *usec = (long)((qpc % freq) * 1000000 / freq); #endif } IUINT64 UDPSession::iclock64(void) { long s, u; IUINT64 value; itimeofday(&s, &u); value = ((IUINT64) s) * 1000 + (u / 1000); return value; } IUINT32 UDPSession::iclock() { return (IUINT32) (iclock64() & 0xfffffffful); } <commit_msg>update<commit_after>// // Created by 理 傅 on 16/7/9. // #include "sess.h" #include <sys/socket.h> #include <sys/fcntl.h> #include <arpa/inet.h> #include <sys/time.h> #include <unistd.h> #include <string.h> UDPSession * UDPSession::Dial(const char *ip, uint16_t port) { int sockfd = socket(PF_INET, SOCK_DGRAM, 0); if (sockfd == -1) { return 0; } int flags = fcntl(sockfd, F_GETFL, 0); fcntl(sockfd, F_SETFL, flags | O_NONBLOCK); struct sockaddr_in saddr; saddr.sin_family = AF_INET; saddr.sin_port = htons(port); saddr.sin_addr.s_addr = inet_addr(ip); memset(&saddr.sin_zero, 0, 8); if (connect(sockfd, (struct sockaddr *) &saddr, sizeof(struct sockaddr)) < 0) { return 0; } void *buf = malloc(UDPSession::mtuLimit); if (buf == 0) { return 0; } UDPSession *sess = new(UDPSession); sess->m_sockfd = sockfd; sess->m_kcp = ikcp_create(IUINT32(rand()), sess); sess->m_kcp->output = sess->out_wrapper; sess->m_buf = buf; sess->m_bufsiz = UDPSession::mtuLimit; ikcp_wndsize(sess->m_kcp, 128,128); return sess; } void UDPSession::Update() { while (1) { ssize_t n = recv(m_sockfd, m_buf, m_bufsiz, 0); if (n > 0) { ikcp_input(m_kcp, static_cast<const char *>(m_buf), n); } else { break; } } ikcp_update(m_kcp, iclock()); } void UDPSession::Close() { if (m_sockfd != 0) { close(m_sockfd); } if (m_buf != 0) { free(m_buf); } if (m_kcp != 0) { ikcp_release(m_kcp); } delete this; } int UDPSession::out_wrapper(const char *buf, int len, struct IKCPCB *kcp, void *user) { UDPSession *sess = static_cast<UDPSession *>(user); return sess->output(buf, len); } ssize_t UDPSession::output(const void *buffer, size_t length) { ssize_t n = send(m_sockfd, buffer, length, 0); return n; } void UDPSession::itimeofday(long *sec, long *usec) { #if defined(__unix) struct timeval time; gettimeofday(&time, NULL); if (sec) *sec = time.tv_sec; if (usec) *usec = time.tv_usec; #else static long mode = 0, addsec = 0; BOOL retval; static IINT64 freq = 1; IINT64 qpc; if (mode == 0) { retval = QueryPerformanceFrequency((LARGE_INTEGER*)&freq); freq = (freq == 0)? 1 : freq; retval = QueryPerformanceCounter((LARGE_INTEGER*)&qpc); addsec = (long)time(NULL); addsec = addsec - (long)((qpc / freq) & 0x7fffffff); mode = 1; } retval = QueryPerformanceCounter((LARGE_INTEGER*)&qpc); retval = retval * 2; if (sec) *sec = (long)(qpc / freq) + addsec; if (usec) *usec = (long)((qpc % freq) * 1000000 / freq); #endif } IUINT64 UDPSession::iclock64(void) { long s, u; IUINT64 value; itimeofday(&s, &u); value = ((IUINT64) s) * 1000 + (u / 1000); return value; } IUINT32 UDPSession::iclock() { return (IUINT32) (iclock64() & 0xfffffffful); } <|endoftext|>
<commit_before>// Copyright (c) 2014, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE source in the root of the Project. #include <boost/python.hpp> #include <boost/optional.hpp> #include <nix.hpp> #include <accessors.hpp> #include <transmorgify.hpp> //we want only the newest and freshest API #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <numpy/arrayobject.h> #include <numpy/ndarrayobject.h> #include <PyEntity.hpp> #include <stdexcept> using namespace nix; using namespace boost::python; namespace nixpy { // Label void setLabel(DataArray& da, const boost::optional<std::string>& label) { if (label) da.label(*label); else da.label(boost::none); } // Unit void setUnit(DataArray& da, const boost::optional<std::string> &unit) { if (unit) da.unit(*unit); else da.unit(boost::none); } // Expansion origin void setExpansionOrigin(DataArray& da, const boost::optional<double>& eo) { if (eo) da.expansionOrigin(*eo); else da.expansionOrigin(boost::none); } // Polynom coefficients void setPolynomCoefficients(DataArray& da, const std::vector<double>& pc) { if (!pc.empty()) da.polynomCoefficients(pc); else da.polynomCoefficients(boost::none); } // Data std::vector<double> getData(DataArray& da) { std::vector<double> data; da.getData(data); return data; } void setData(DataArray& da, const std::vector<double>& data) { if (!data.empty()) da.setData(data); else // TODO How do I remove data? da.dataExtent(NDSize()); } static nix::DataType py_dtype_to_nix_dtype(const PyArray_Descr *dtype) { if (dtype == nullptr) { return nix::DataType::Nothing; } if (dtype->byteorder != '=' && dtype->byteorder != '|') { //TODO: Handle case where specified byteorder *is* //the native byteorder (via BOOST_BIG_ENDIAN macros) return nix::DataType::Nothing; } switch (dtype->kind) { case 'u': switch (dtype->elsize) { case 1: return nix::DataType::UInt8; case 2: return nix::DataType::UInt16; case 4: return nix::DataType::UInt32; case 8: return nix::DataType::UInt64; } break; case 'i': switch (dtype->elsize) { case 1: return nix::DataType::Int8; case 2: return nix::DataType::Int16; case 4: return nix::DataType::Int32; case 8: return nix::DataType::Int64; } break; case 'f': switch (dtype->elsize) { case 4: return nix::DataType::Float; case 8: return nix::DataType::Double; } break; default: break; } return nix::DataType::Nothing; } static PyArrayObject *make_array(PyObject *data, int requirements) { if (! PyArray_Check(data)) { throw std::invalid_argument("Data not a NumPy array"); } PyArrayObject *array = reinterpret_cast<PyArrayObject *>(data); if (! PyArray_CHKFLAGS(array, requirements)) { throw std::invalid_argument("data must be c-contiguous and aligned"); } return array; } static void readData(DataArray& da, PyObject *data) { PyArrayObject *array = make_array(data, NPY_ARRAY_CARRAY); nix::DataType nix_dtype = py_dtype_to_nix_dtype(PyArray_DESCR(array)); if (nix_dtype == nix::DataType::Nothing) { throw std::invalid_argument("Unsupported dtype for data"); } int array_rank = PyArray_NDIM(array); npy_intp *array_shape = PyArray_SHAPE(array); nix::NDSize data_shape(array_rank); for (int i = 0; i < array_rank; i++) { data_shape[i] = array_shape[i]; } nix::NDSize offset(array_rank, 0); da.getData(nix_dtype, PyArray_DATA(array), data_shape, offset); } static void writeData(DataArray& da, PyObject *data) { PyArrayObject *array = make_array(data, NPY_ARRAY_CARRAY_RO); nix::DataType nix_dtype = py_dtype_to_nix_dtype(PyArray_DESCR(array)); if (nix_dtype == nix::DataType::Nothing) { throw std::invalid_argument("Unsupported dtype for data"); } int array_rank = PyArray_NDIM(array); npy_intp *array_shape = PyArray_SHAPE(array); nix::NDSize data_shape(array_rank); for (int i = 0; i < array_rank; i++) { data_shape[i] = array_shape[i]; } nix::NDSize offset(array_rank, 0); da.setData(nix_dtype, PyArray_DATA(array), data_shape, offset); } static void createData(DataArray& da, const NDSize &shape, PyObject *dtype_obj, PyObject *data) { PyArray_Descr* py_dtype = nullptr; if (! PyArray_DescrConverter(dtype_obj, &py_dtype)) { throw std::invalid_argument("Invalid dtype"); } nix::DataType nix_dtype = py_dtype_to_nix_dtype(py_dtype); if (nix_dtype == nix::DataType::Nothing) { throw std::invalid_argument("Unsupported dtype"); } da.createData(nix_dtype, shape); if (data != Py_None) { writeData(da, data); } Py_DECREF(py_dtype); } // Dimensions PyObject* getDimension(const DataArray& da, size_t index) { Dimension dim = da.getDimension(index); SetDimension set; RangeDimension range; SampledDimension sample; DimensionType type = dim.dimensionType(); switch(type) { case DimensionType::Set: set = dim; return incref(object(set).ptr()); case DimensionType::Range: range = dim; return incref(object(range).ptr()); case DimensionType::Sample: sample = dim; return incref(object(sample).ptr()); default: Py_RETURN_NONE; } } void PyDataArray::do_export() { // For numpy to work import_array(); PyEntityWithSources<base::IDataArray>::do_export("DataArray"); class_<DataArray, bases<base::EntityWithSources<base::IDataArray>>>("DataArray") .add_property("label", OPT_GETTER(std::string, DataArray, label), setLabel, doc::data_array_label) .add_property("unit", OPT_GETTER(std::string, DataArray, unit), setUnit, doc::data_array_unit) .add_property("expansion_origin", OPT_GETTER(double, DataArray, expansionOrigin), setExpansionOrigin, doc::data_array_expansion_origin) .add_property("polynom_coefficients", GETTER(std::vector<double>, DataArray, polynomCoefficients), setPolynomCoefficients, doc::data_array_polynom_coefficients) .add_property("data_extent", GETTER(NDSize, DataArray, dataExtent), SETTER(NDSize&, DataArray, dataExtent), doc::data_array_data_extent) // Data .add_property("data_type", &DataArray::dataType, doc::data_array_data_type) .add_property("data", getData, setData, doc::data_array_data) .def("has_data", &DataArray::hasData, doc::data_array_has_data) .def("_create_data", createData) .def("_write_data", writeData) .def("_read_data", readData) // Dimensions .def("create_set_dimension", &DataArray::createSetDimension, doc::data_array_create_set_dimension) .def("create_sampled_dimension", &DataArray::createSampledDimension, doc::data_array_create_sampled_dimension) .def("create_reange_dimension", &DataArray::createRangeDimension, doc::data_array_create_range_dimension) .def("append_set_dimension", &DataArray::appendSetDimension, doc::data_array_append_set_dimension) .def("append_sampled_dimension", &DataArray::appendSampledDimension, doc::data_array_append_sampled_dimension) .def("append_range_dimension", &DataArray::appendRangeDimension, doc::data_array_append_range_dimension) .def("_dimension_count", &DataArray::dimensionCount) .def("_delete_dimension_by_pos", &DataArray::deleteDimension) .def("_get_dimension_by_pos", getDimension) // Other .def("__str__", &toStr<DataArray>) .def("__repr__", &toStr<DataArray>) ; to_python_converter<std::vector<DataArray>, vector_transmogrify<DataArray>>(); vector_transmogrify<DataArray>::register_from_python(); to_python_converter<boost::optional<DataArray>, option_transmogrify<DataArray>>(); } } <commit_msg>PyDataArray: new array_shape_as_ndsize<commit_after>// Copyright (c) 2014, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE source in the root of the Project. #include <boost/python.hpp> #include <boost/optional.hpp> #include <nix.hpp> #include <accessors.hpp> #include <transmorgify.hpp> //we want only the newest and freshest API #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <numpy/arrayobject.h> #include <numpy/ndarrayobject.h> #include <PyEntity.hpp> #include <stdexcept> using namespace nix; using namespace boost::python; namespace nixpy { // Label void setLabel(DataArray& da, const boost::optional<std::string>& label) { if (label) da.label(*label); else da.label(boost::none); } // Unit void setUnit(DataArray& da, const boost::optional<std::string> &unit) { if (unit) da.unit(*unit); else da.unit(boost::none); } // Expansion origin void setExpansionOrigin(DataArray& da, const boost::optional<double>& eo) { if (eo) da.expansionOrigin(*eo); else da.expansionOrigin(boost::none); } // Polynom coefficients void setPolynomCoefficients(DataArray& da, const std::vector<double>& pc) { if (!pc.empty()) da.polynomCoefficients(pc); else da.polynomCoefficients(boost::none); } // Data std::vector<double> getData(DataArray& da) { std::vector<double> data; da.getData(data); return data; } void setData(DataArray& da, const std::vector<double>& data) { if (!data.empty()) da.setData(data); else // TODO How do I remove data? da.dataExtent(NDSize()); } static nix::DataType py_dtype_to_nix_dtype(const PyArray_Descr *dtype) { if (dtype == nullptr) { return nix::DataType::Nothing; } if (dtype->byteorder != '=' && dtype->byteorder != '|') { //TODO: Handle case where specified byteorder *is* //the native byteorder (via BOOST_BIG_ENDIAN macros) return nix::DataType::Nothing; } switch (dtype->kind) { case 'u': switch (dtype->elsize) { case 1: return nix::DataType::UInt8; case 2: return nix::DataType::UInt16; case 4: return nix::DataType::UInt32; case 8: return nix::DataType::UInt64; } break; case 'i': switch (dtype->elsize) { case 1: return nix::DataType::Int8; case 2: return nix::DataType::Int16; case 4: return nix::DataType::Int32; case 8: return nix::DataType::Int64; } break; case 'f': switch (dtype->elsize) { case 4: return nix::DataType::Float; case 8: return nix::DataType::Double; } break; default: break; } return nix::DataType::Nothing; } static PyArrayObject *make_array(PyObject *data, int requirements) { if (! PyArray_Check(data)) { throw std::invalid_argument("Data not a NumPy array"); } PyArrayObject *array = reinterpret_cast<PyArrayObject *>(data); if (! PyArray_CHKFLAGS(array, requirements)) { throw std::invalid_argument("data must be c-contiguous and aligned"); } return array; } static NDSize array_shape_as_ndsize(PyArrayObject *array) { int array_rank = PyArray_NDIM(array); npy_intp *array_shape = PyArray_SHAPE(array); nix::NDSize data_shape(array_rank); for (int i = 0; i < array_rank; i++) { data_shape[i] = array_shape[i]; } return data_shape; } static void readData(DataArray& da, PyObject *data) { PyArrayObject *array = make_array(data, NPY_ARRAY_CARRAY); nix::DataType nix_dtype = py_dtype_to_nix_dtype(PyArray_DESCR(array)); if (nix_dtype == nix::DataType::Nothing) { throw std::invalid_argument("Unsupported dtype for data"); } nix::NDSize data_shape = array_shape_as_ndsize(array); nix::NDSize offset(data_shape.size(), 0); da.getData(nix_dtype, PyArray_DATA(array), data_shape, offset); } static void writeData(DataArray& da, PyObject *data) { PyArrayObject *array = make_array(data, NPY_ARRAY_CARRAY_RO); nix::DataType nix_dtype = py_dtype_to_nix_dtype(PyArray_DESCR(array)); if (nix_dtype == nix::DataType::Nothing) { throw std::invalid_argument("Unsupported dtype for data"); } nix::NDSize data_shape = array_shape_as_ndsize(array); nix::NDSize offset(data_shape.size(), 0); da.setData(nix_dtype, PyArray_DATA(array), data_shape, offset); } static void createData(DataArray& da, const NDSize &shape, PyObject *dtype_obj, PyObject *data) { PyArray_Descr* py_dtype = nullptr; if (! PyArray_DescrConverter(dtype_obj, &py_dtype)) { throw std::invalid_argument("Invalid dtype"); } nix::DataType nix_dtype = py_dtype_to_nix_dtype(py_dtype); if (nix_dtype == nix::DataType::Nothing) { throw std::invalid_argument("Unsupported dtype"); } da.createData(nix_dtype, shape); if (data != Py_None) { writeData(da, data); } Py_DECREF(py_dtype); } // Dimensions PyObject* getDimension(const DataArray& da, size_t index) { Dimension dim = da.getDimension(index); SetDimension set; RangeDimension range; SampledDimension sample; DimensionType type = dim.dimensionType(); switch(type) { case DimensionType::Set: set = dim; return incref(object(set).ptr()); case DimensionType::Range: range = dim; return incref(object(range).ptr()); case DimensionType::Sample: sample = dim; return incref(object(sample).ptr()); default: Py_RETURN_NONE; } } void PyDataArray::do_export() { // For numpy to work import_array(); PyEntityWithSources<base::IDataArray>::do_export("DataArray"); class_<DataArray, bases<base::EntityWithSources<base::IDataArray>>>("DataArray") .add_property("label", OPT_GETTER(std::string, DataArray, label), setLabel, doc::data_array_label) .add_property("unit", OPT_GETTER(std::string, DataArray, unit), setUnit, doc::data_array_unit) .add_property("expansion_origin", OPT_GETTER(double, DataArray, expansionOrigin), setExpansionOrigin, doc::data_array_expansion_origin) .add_property("polynom_coefficients", GETTER(std::vector<double>, DataArray, polynomCoefficients), setPolynomCoefficients, doc::data_array_polynom_coefficients) .add_property("data_extent", GETTER(NDSize, DataArray, dataExtent), SETTER(NDSize&, DataArray, dataExtent), doc::data_array_data_extent) // Data .add_property("data_type", &DataArray::dataType, doc::data_array_data_type) .add_property("data", getData, setData, doc::data_array_data) .def("has_data", &DataArray::hasData, doc::data_array_has_data) .def("_create_data", createData) .def("_write_data", writeData) .def("_read_data", readData) // Dimensions .def("create_set_dimension", &DataArray::createSetDimension, doc::data_array_create_set_dimension) .def("create_sampled_dimension", &DataArray::createSampledDimension, doc::data_array_create_sampled_dimension) .def("create_reange_dimension", &DataArray::createRangeDimension, doc::data_array_create_range_dimension) .def("append_set_dimension", &DataArray::appendSetDimension, doc::data_array_append_set_dimension) .def("append_sampled_dimension", &DataArray::appendSampledDimension, doc::data_array_append_sampled_dimension) .def("append_range_dimension", &DataArray::appendRangeDimension, doc::data_array_append_range_dimension) .def("_dimension_count", &DataArray::dimensionCount) .def("_delete_dimension_by_pos", &DataArray::deleteDimension) .def("_get_dimension_by_pos", getDimension) // Other .def("__str__", &toStr<DataArray>) .def("__repr__", &toStr<DataArray>) ; to_python_converter<std::vector<DataArray>, vector_transmogrify<DataArray>>(); vector_transmogrify<DataArray>::register_from_python(); to_python_converter<boost::optional<DataArray>, option_transmogrify<DataArray>>(); } } <|endoftext|>
<commit_before>#include "XsdType.hpp" #include "XsdChecker.hpp" #include <sstream> #include "../Utils.hpp" namespace Xsd { const std::string TYPE_SUFFIX = "TYPE"; const std::string UNBOUNDED = "unbounded"; const std::string UNBOUNDED_EXP_REG = "*"; Type::Type(const Xml::Element * const xmlElement, const std::string & name) { mRegex = parseComplexType(*xmlElement, "", false, mAttributes); Checker::getInstance()->addType(name, this); } Type::Type(const std::string & name, const std::string & regex, std::list<Attribute *> attrs): mRegex(regex), mAttributes(attrs) { Checker::getInstance()->addType(name, this); } Type::~Type() { } bool Type::isValid(const std::string & str) { return RE2::FullMatch(str, mRegex); } void Type::checkValidity(const Xml::Element * const element) { //TODO: add function attributes() which returns the mAttributes map in Xml::Element for (auto iterAttr = element->attributesValue().begin(); iterAttr != element->attributesValue().end(); ++iterAttr) { //pour chaque attibut d'un element // obtenir l'attribut xsd avec une map depuis le type (map attribut de type) // xsdAttribute->checkValidity(iterAttr->second) // mAttributes.find(iterAttr->first) // iterAttr->checkValidity(iterAttr->second); } if(!RE2::FullMatch(childrenToString(element->elements()), mRegex)) { throw new XSDValidationException("Invalid element: " + element->name()); } for (auto iter = element->elements().begin(); iter != element->elements().end(); ++iter) { Checker * checker = Checker::getInstance(); Type * typePt = checker-> getElementType((*iter)->name()); typePt->checkValidity(*iter); } } std::string Type::childrenToString(std::vector<Xml::Element const *> childrenElt) { std::string str = ""; for (auto iter = childrenElt.begin(); iter != childrenElt.end(); ++iter) { str += "<" + (*iter)->name() + ">"; } return str; } //Should work, still have to check the algorithm for choice or sequence inside choice or sequence std::string Type::parseComplexType(const Xml::Element * const xmlElement, std::string separator, bool eltSeqChoice, std::list<Attribute *> & attributes) { bool eltParsed = false; std::string regex = "("; if(xmlElement->attribute(Checker::MIXED_ATTR).compare("true") == 0) { separator += ".*"; } for (auto ci = xmlElement->elements().begin(); ci != xmlElement->elements().end(); ++ci) { if((*ci)->name().compare(Checker::SEQUENCE_ELT) == 0) { regex += getRegexFromOccurs(*ci, parseComplexType(ci, "", true, attributes)) + separator; } else if((*ci)->name().compare(Checker::CHOICE_ELT) == 0) { regex += getRegexFromOccurs(*ci, parseComplexType(ci, "|", true, attributes)) + separator; } else if((*ci)->name().compare(Checker::ELEMENT_ELT) == 0) { if(eltSeqChoice || !eltParsed) { eltParsed = true; regex += parseElement(*ci) + separator; } else { Checker::throwInvalidElementException(Checker::ELEMENT_ELT, getNameOrRef(*ci)); } } else if((*ci)->name().compare(Checker::ATTRIBUTE_ELT) == 0) { attributes.push_back(Xsd::Attribute::parseAttribute(*ci)); } else { Checker::throwInvalidElementException(Checker::COMPLEX_TYP_ELT, ci->name()); } } if(regex.back() == '|') { regex = regex.substr(0, regex.size()-1); } return regex + ")"; } bool Type::isSimpleType(const std::string & type) { //throw new NotImplementedException("Not implemented yet"); return (type.compare(Checker::STRING_TYPE) == 0) || (type.compare(Checker::DATE_TYPE) == 0); } std::string Type::getOccursFromElement(const Xml::Element & xmlElement, const std::string & occursAttrName, const std::string & occursAttrValue) { if(occursAttrValue.compare(UNBOUNDED) == 0) { return UNBOUNDED_EXP_REG; } try { if(std::stoi(occursAttrValue) < 0) { throw new XSDConstructionException("Invalid value for " + occursAttrName + "attribute in element " + xmlElement.name() + ": " + occursAttrValue); } } catch(const std::exception& e) { Checker::throwInvalidAttributeValueException(Checker::ELEMENT_ELT, occursAttrName, occursAttrValue); } return occursAttrValue; } std::string Type::getNameOrRef(const Xml::Element * const xmlElement) { if(isReference(xmlElement)) { return xmlElement->attribute(Checker::REF_ATTR); } return xmlElement->attribute(Checker::NAME_ATTR); } bool Type::isReference(const Xml::Element * const xmlElement) { std::string notFound = ""; std::string name = xmlElement->attribute(Checker::NAME_ATTR); std::string ref = xmlElement->attribute(Checker::REF_ATTR); // Name and ref attributes if((name.compare(notFound) == 0) && (ref.compare(notFound) != 0)) { return true; } else { Checker::throwMissingAttributeException(Checker::ELEMENT_ELT, Checker::NAME_ATTR); } return false; } /** * Returns the regex of an element, adds its type and type relation to the maps if it's not a ref * The regex does not contain the validation for the element children, it's only about the element name or ref itself */ std::string Type::parseElement(const Xml::Element * const xmlElement) { bool ref = false; std::string regex, name; // Name and ref attributes if(isReference(*xmlElement)) { name = xmlElement->attribute(Checker::REF_ATTR); ref = true; } else { name = xmlElement->attribute(Checker::NAME_ATTR); } regex = getRegexFromOccurs(*xmlElement, name); if(!ref) { //Type manaement std::string type = xmlElement->attribute(Checker::TYPE_ATTR); if(!type.compare("") && isSimpleType(type)) { std::vector<std::string> tokens; //throw new NotImplementedException("Not implemented yet"); tokens = NULL; //todo remove //tokens = Utils::split(type, ':')); Checker::getInstance()->addTypedElement(name, tokens.back()); } else if(xmlElement->elements().size() > 0) { Xml::Element * typeElement = xmlElement->elements().front(); if(typeElement->name().compare(Checker::COMPLEX_TYP_ELT) == 0) { std::string typeName = name + "Type"; new Type(typeElement, typeName); Checker::getInstance()->addTypedElement(name, typeName); } else { throw new XSDConstructionException("Error: type attribute or element cannot be found for " + Checker::ELEMENT_ELT + " element"); } } else { throw new XSDConstructionException("Error: type attribute or element cannot be found for " + Checker::ELEMENT_ELT + " element"); } } return regex; } /** * Modify and returns the element regex given in parameter in order to add * regex expression for the occurs attributes values */ std::string Type::getRegexFromOccurs(const Xml::Element * const xmlElement, const std::string & eltRegex) { std::string notFound = "", regex; std::string name = xmlElement.attribute(Xsd::Checker::NAME_ATTR); std::string ref = xmlElement.attribute(Xsd::Checker::REF_ATTR); std::string minOccurs = xmlElement.attribute(Checker::MIN_OCC_ATTR); std::string supOccurs = xmlElement.attribute(Checker::MAX_OCC_ATTR); // Min and max occurs attributes if(!(minOccurs.compare(notFound) == 0)) { minOccurs = getOccursFromElement(*xmlElement, Checker::MIN_OCC_ATTR, minOccurs); } else { minOccurs = "1"; } if(!(supOccurs.compare(notFound) == 0)) { supOccurs = getOccursFromElement(*xmlElement, Checker::MAX_OCC_ATTR, supOccurs); } else { supOccurs = "0"; } if((minOccurs.compare(UNBOUNDED_EXP_REG) == 0 && supOccurs.compare(UNBOUNDED_EXP_REG) != 0) || (supOccurs.compare(UNBOUNDED_EXP_REG) !=0 && std::stoi(supOccurs) < std::stoi(minOccurs))) { throw new XSDConstructionException("Error: " + Checker::MIN_OCC_ATTR + " attribute value is higher than " + Checker::MAX_OCC_ATTR + " value"); } if((minOccurs.compare(UNBOUNDED_EXP_REG) == 0) && (supOccurs.compare(UNBOUNDED_EXP_REG) == 0)) { std::stringstream out; out << (std::stoi(supOccurs) - std::stoi(minOccurs)); supOccurs = out.str(); } // Name and ref attributes if(isReference(xmlElement)) { name = ref; } // Create the regex regex = "(<" + eltRegex + ">){" + minOccurs + "}"; if(!(supOccurs.compare("0") == 0)) { regex += "((<" + eltRegex + ">?){" + supOccurs + "})"; } return regex; } std::list<Attribute *> Type::attributes() const { return mAttributes; } } <commit_msg>as usual<commit_after>#include "XsdType.hpp" #include "XsdChecker.hpp" #include <sstream> #include "../Utils.hpp" namespace Xsd { const std::string TYPE_SUFFIX = "TYPE"; const std::string UNBOUNDED = "unbounded"; const std::string UNBOUNDED_EXP_REG = "*"; Type::Type(const Xml::Element * const xmlElement, const std::string & name) { mRegex = parseComplexType(xmlElement, "", false, mAttributes); Checker::getInstance()->addType(name, this); } Type::Type(const std::string & name, const std::string & regex, std::list<Attribute *> attrs): mRegex(regex), mAttributes(attrs) { Checker::getInstance()->addType(name, this); } Type::~Type() { } bool Type::isValid(const std::string & str) { return RE2::FullMatch(str, mRegex); } void Type::checkValidity(const Xml::Element * const element) { //TODO: add function attributes() which returns the mAttributes map in Xml::Element for (auto iterAttr = element->attributesValue().begin(); iterAttr != element->attributesValue().end(); ++iterAttr) { //pour chaque attibut d'un element // obtenir l'attribut xsd avec une map depuis le type (map attribut de type) // xsdAttribute->checkValidity(iterAttr->second) // mAttributes.find(iterAttr->first) // iterAttr->checkValidity(iterAttr->second); } if(!RE2::FullMatch(childrenToString(element->elements()), mRegex)) { throw new XSDValidationException("Invalid element: " + element->name()); } for (auto iter = element->elements().begin(); iter != element->elements().end(); ++iter) { Checker * checker = Checker::getInstance(); Type * typePt = checker-> getElementType((*iter)->name()); typePt->checkValidity(*iter); } } std::string Type::childrenToString(std::vector<Xml::Element const *> childrenElt) { std::string str = ""; for (auto iter = childrenElt.begin(); iter != childrenElt.end(); ++iter) { str += "<" + (*iter)->name() + ">"; } return str; } //Should work, still have to check the algorithm for choice or sequence inside choice or sequence std::string Type::parseComplexType(const Xml::Element * const xmlElement, std::string separator, bool eltSeqChoice, std::list<Attribute *> & attributes) { bool eltParsed = false; std::string regex = "("; if(xmlElement->attribute(Checker::MIXED_ATTR).compare("true") == 0) { separator += ".*"; } for (auto ci = xmlElement->elements().begin(); ci != xmlElement->elements().end(); ++ci) { if((*ci)->name().compare(Checker::SEQUENCE_ELT) == 0) { const Xml::Element * const xmlElement = *ci; regex += getRegexFromOccurs(xmlElement, parseComplexType(ci, "", true, attributes)) + separator; } else if((*ci)->name().compare(Checker::CHOICE_ELT) == 0) { const Xml::Element * const xmlElement = *ci; regex += getRegexFromOccurs(xmlElement, parseComplexType(ci, "|", true, attributes)) + separator; } else if((*ci)->name().compare(Checker::ELEMENT_ELT) == 0) { if(eltSeqChoice || !eltParsed) { eltParsed = true; regex += parseElement(*ci) + separator; } else { Checker::throwInvalidElementException(Checker::ELEMENT_ELT, getNameOrRef(*ci)); } } else if((*ci)->name().compare(Checker::ATTRIBUTE_ELT) == 0) { attributes.push_back(Xsd::Attribute::parseAttribute(*ci)); } else { Checker::throwInvalidElementException(Checker::COMPLEX_TYP_ELT, ci->name()); } } if(regex.back() == '|') { regex = regex.substr(0, regex.size()-1); } return regex + ")"; } bool Type::isSimpleType(const std::string & type) { //throw new NotImplementedException("Not implemented yet"); return (type.compare(Checker::STRING_TYPE) == 0) || (type.compare(Checker::DATE_TYPE) == 0); } std::string Type::getOccursFromElement(const Xml::Element & xmlElement, const std::string & occursAttrName, const std::string & occursAttrValue) { if(occursAttrValue.compare(UNBOUNDED) == 0) { return UNBOUNDED_EXP_REG; } try { if(std::stoi(occursAttrValue) < 0) { throw new XSDConstructionException("Invalid value for " + occursAttrName + "attribute in element " + xmlElement.name() + ": " + occursAttrValue); } } catch(const std::exception& e) { Checker::throwInvalidAttributeValueException(Checker::ELEMENT_ELT, occursAttrName, occursAttrValue); } return occursAttrValue; } std::string Type::getNameOrRef(const Xml::Element * const xmlElement) { if(isReference(xmlElement)) { return xmlElement->attribute(Checker::REF_ATTR); } return xmlElement->attribute(Checker::NAME_ATTR); } bool Type::isReference(const Xml::Element * const xmlElement) { std::string notFound = ""; std::string name = xmlElement->attribute(Checker::NAME_ATTR); std::string ref = xmlElement->attribute(Checker::REF_ATTR); // Name and ref attributes if((name.compare(notFound) == 0) && (ref.compare(notFound) != 0)) { return true; } else { Checker::throwMissingAttributeException(Checker::ELEMENT_ELT, Checker::NAME_ATTR); } return false; } /** * Returns the regex of an element, adds its type and type relation to the maps if it's not a ref * The regex does not contain the validation for the element children, it's only about the element name or ref itself */ std::string Type::parseElement(const Xml::Element * const xmlElement) { bool ref = false; std::string regex, name; // Name and ref attributes if(isReference(*xmlElement)) { name = xmlElement->attribute(Checker::REF_ATTR); ref = true; } else { name = xmlElement->attribute(Checker::NAME_ATTR); } regex = getRegexFromOccurs(xmlElement, name); if(!ref) { //Type manaement std::string type = xmlElement->attribute(Checker::TYPE_ATTR); if(!type.compare("") && isSimpleType(type)) { std::vector<std::string> tokens; //throw new NotImplementedException("Not implemented yet"); tokens = NULL; //todo remove //tokens = Utils::split(type, ':')); Checker::getInstance()->addTypedElement(name, tokens.back()); } else if(xmlElement->elements().size() > 0) { Xml::Element * typeElement = xmlElement->elements().front(); if(typeElement->name().compare(Checker::COMPLEX_TYP_ELT) == 0) { std::string typeName = name + "Type"; new Type(typeElement, typeName); Checker::getInstance()->addTypedElement(name, typeName); } else { throw new XSDConstructionException("Error: type attribute or element cannot be found for " + Checker::ELEMENT_ELT + " element"); } } else { throw new XSDConstructionException("Error: type attribute or element cannot be found for " + Checker::ELEMENT_ELT + " element"); } } return regex; } /** * Modify and returns the element regex given in parameter in order to add * regex expression for the occurs attributes values */ std::string Type::getRegexFromOccurs(const Xml::Element * const xmlElement, const std::string & eltRegex) { std::string notFound = "", regex; std::string name = xmlElement->attribute(Xsd::Checker::NAME_ATTR); std::string ref = xmlElement->attribute(Xsd::Checker::REF_ATTR); std::string minOccurs = xmlElement->attribute(Checker::MIN_OCC_ATTR); std::string supOccurs = xmlElement->attribute(Checker::MAX_OCC_ATTR); // Min and max occurs attributes if(!(minOccurs.compare(notFound) == 0)) { minOccurs = getOccursFromElement(*xmlElement, Checker::MIN_OCC_ATTR, minOccurs); } else { minOccurs = "1"; } if(!(supOccurs.compare(notFound) == 0)) { supOccurs = getOccursFromElement(*xmlElement, Checker::MAX_OCC_ATTR, supOccurs); } else { supOccurs = "0"; } if((minOccurs.compare(UNBOUNDED_EXP_REG) == 0 && supOccurs.compare(UNBOUNDED_EXP_REG) != 0) || (supOccurs.compare(UNBOUNDED_EXP_REG) !=0 && std::stoi(supOccurs) < std::stoi(minOccurs))) { throw new XSDConstructionException("Error: " + Checker::MIN_OCC_ATTR + " attribute value is higher than " + Checker::MAX_OCC_ATTR + " value"); } if((minOccurs.compare(UNBOUNDED_EXP_REG) == 0) && (supOccurs.compare(UNBOUNDED_EXP_REG) == 0)) { std::stringstream out; out << (std::stoi(supOccurs) - std::stoi(minOccurs)); supOccurs = out.str(); } // Name and ref attributes if(isReference(xmlElement)) { name = ref; } // Create the regex regex = "(<" + eltRegex + ">){" + minOccurs + "}"; if(!(supOccurs.compare("0") == 0)) { regex += "((<" + eltRegex + ">?){" + supOccurs + "})"; } return regex; } std::list<Attribute *> Type::attributes() const { return mAttributes; } } <|endoftext|>
<commit_before>/* * Copyright 2015 Aldebaran * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <iostream> /* * NAOQI */ #include <qi/anyobject.hpp> #include <alvision/alvisiondefinitions.h> // for kTop... /* * BOOST */ #include <boost/foreach.hpp> #include <boost/make_shared.hpp> #define foreach BOOST_FOREACH /* * ROS */ #include <std_msgs/Int32.h> /* * PUBLIC INTERFACE */ #include <alrosbridge/alrosbridge.hpp> /* * publishers */ #include "publishers/camera.hpp" #include "publishers/diagnostics.hpp" #include "publishers/int.hpp" #include "publishers/info.hpp" #include "publishers/joint_state.hpp" #include "publishers/nao_joint_state.hpp" #include "publishers/odometry.hpp" #include "publishers/laser.hpp" #include "publishers/log.hpp" #include "publishers/sonar.hpp" #include "publishers/string.hpp" /* * subscribers */ #include "subscribers/teleop.hpp" #include "subscribers/moveto.hpp" /* * STATIC FUNCTIONS INCLUDE */ #include "ros_env.hpp" #include "helpers.hpp" namespace alros { Bridge::Bridge( qi::SessionPtr& session ) : sessionPtr_( session ), freq_(15), publish_enabled_(false), publish_cancelled_(false), _recorder(boost::make_shared<Recorder>()) { //_recorder = std::make_shared<Recorder>(); std::cout << "application path "<< std::endl; } Bridge::~Bridge() { std::cout << "ALRosBridge is shutting down.." << std::endl; publish_cancelled_ = true; stop(); if (publisherThread_.get_id() != boost::thread::id()) publisherThread_.join(); // destroy nodehandle? nhPtr_->shutdown(); ros::shutdown(); } void Bridge::rosLoop() { while( !publish_cancelled_ ) { { boost::mutex::scoped_lock lock( mutex_reinit_ ); if (publish_enabled_) { // Wait for the next Publisher to be ready size_t pub_index = pub_queue_.top().pub_index_; publisher::Publisher& pub = publishers_[pub_index]; ros::Time schedule = pub_queue_.top().schedule_; ros::Duration(schedule - ros::Time::now()).sleep(); if ( pub.isSubscribed() && pub.isInitialized()) { pub.publish(); if (_recorder->isRecording()) { std_msgs::Int32 i; i.data = 32; geometry_msgs::PointStamped ps; ps.point.x = 2; ps.point.y = 4; ps.point.z = 6; _recorder->write(pub.name(), ps); } } // Schedule for a future time or not pub_queue_.pop(); if ( pub.frequency() != 0 ) pub_queue_.push(ScheduledPublish(schedule + ros::Duration(1.0f / pub.frequency()), pub_index)); } else // sleep one second ros::Duration(1).sleep(); } ros::spinOnce(); } } // public interface here void Bridge::registerPublisher( publisher::Publisher pub ) { std::vector<publisher::Publisher>::iterator it; it = std::find( publishers_.begin(), publishers_.end(), pub ); // if publisher is not found, register it! if (it == publishers_.end() ) { publishers_.push_back( pub ); it = publishers_.end() - 1; std::cout << "registered publisher:\t" << pub.name() << std::endl; } // if found, re-init them else { std::cout << "re-initialized existing publisher:\t" << it->name() << std::endl; } } void Bridge::registerDefaultPublisher() { if (!publishers_.empty()) return; // Info should be at 0 (latched) but somehow that does not work ... publisher::Publisher info = alros::publisher::InfoPublisher("info", "info", 0.1, sessionPtr_); registerPublisher( info ); registerPublisher( alros::publisher::OdometryPublisher( "odometry", "/odom", 15, sessionPtr_) ); registerPublisher( alros::publisher::CameraPublisher("front_camera", "camera/front", 10, sessionPtr_, AL::kTopCamera, AL::kQVGA) ); registerPublisher( alros::publisher::DiagnosticsPublisher("diagnostics", 1, sessionPtr_) ); registerPublisher( alros::publisher::SonarPublisher("sonar", "sonar", 10, sessionPtr_) ); registerPublisher( alros::publisher::LogPublisher("logger", "", 5, sessionPtr_) ); // Pepper specific publishers if (info.robot() == alros::PEPPER) { registerPublisher( alros::publisher::JointStatePublisher("joint_states", "/joint_states", 15, sessionPtr_) ); registerPublisher( alros::publisher::LaserPublisher("laser", "laser", 10, sessionPtr_) ); registerPublisher( alros::publisher::CameraPublisher("depth_camera", "camera/depth", 10, sessionPtr_, AL::kDepthCamera, AL::kQVGA) ); } if (info.robot() == alros::NAO) { registerPublisher( alros::publisher::NaoJointStatePublisher( "nao_joint_states", "/joint_states", 15, sessionPtr_) ); } } // public interface here void Bridge::registerSubscriber( subscriber::Subscriber sub ) { std::vector<subscriber::Subscriber>::iterator it; it = std::find( subscribers_.begin(), subscribers_.end(), sub ); size_t sub_index = 0; // if subscriber is not found, register it! if (it == subscribers_.end() ) { sub_index = subscribers_.size(); subscribers_.push_back( sub ); std::cout << "registered subscriber:\t" << sub.name() << std::endl; } // if found, re-init them else { std::cout << "re-initialized existing subscriber:\t" << it->name() << std::endl; } } void Bridge::registerDefaultSubscriber() { if (!subscribers_.empty()) return; registerSubscriber( alros::subscriber::TeleopSubscriber("teleop", "/cmd_vel", sessionPtr_) ); registerSubscriber( alros::subscriber::MovetoSubscriber("moveto", "/move_base_simple/goal", sessionPtr_) ); } void Bridge::init() { pub_queue_ = std::priority_queue<ScheduledPublish>(); size_t pub_index = 0; foreach( publisher::Publisher& pub, publishers_ ) { pub.reset( *nhPtr_ ); // Schedule it for the next publish pub_queue_.push(ScheduledPublish(ros::Time::now(), pub_index)); ++pub_index; } foreach( subscriber::Subscriber& sub, subscribers_ ) { sub.reset( *nhPtr_ ); } } /* * EXPOSED FUNCTIONS */ std::string Bridge::getMasterURI() const { return ros_env::getMasterURI(); } void Bridge::setMasterURI( const std::string& uri) { setMasterURINet(uri, "eth0"); } void Bridge::setMasterURINet( const std::string& uri, const std::string& network_interface) { // Stopping publishing stop(); // Reinitializing ROS boost::mutex::scoped_lock lock( mutex_reinit_ ); nhPtr_.reset(); std::cout << "nodehandle reset " << std::endl; ros_env::setMasterURI( uri, network_interface ); nhPtr_.reset( new ros::NodeHandle("~") ); lock.unlock(); // Create the publishing thread if needed if (publisherThread_.get_id() == boost::thread::id()) publisherThread_ = boost::thread( &Bridge::rosLoop, this ); // register publishers, that will not start them registerDefaultPublisher(); registerDefaultSubscriber(); // initialize the publishers and subscribers with nodehandle init(); // Start publishing again start(); } void Bridge::start() { boost::mutex::scoped_lock lock( mutex_reinit_ ); publish_enabled_ = true; } void Bridge::stop() { boost::mutex::scoped_lock lock( mutex_reinit_ ); publish_enabled_ = false; } void Bridge::startRecord() { _recorder->startRecord(); } void Bridge::stopRecord() { _recorder->stopRecord(); } QI_REGISTER_OBJECT( Bridge, start, stop, getMasterURI, setMasterURI, setMasterURINet, startRecord, stopRecord ); } //alros <commit_msg>Avoid segfault when quiting without having set a Master URI<commit_after>/* * Copyright 2015 Aldebaran * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <iostream> /* * NAOQI */ #include <qi/anyobject.hpp> #include <alvision/alvisiondefinitions.h> // for kTop... /* * BOOST */ #include <boost/foreach.hpp> #include <boost/make_shared.hpp> #define foreach BOOST_FOREACH /* * ROS */ #include <std_msgs/Int32.h> /* * PUBLIC INTERFACE */ #include <alrosbridge/alrosbridge.hpp> /* * publishers */ #include "publishers/camera.hpp" #include "publishers/diagnostics.hpp" #include "publishers/int.hpp" #include "publishers/info.hpp" #include "publishers/joint_state.hpp" #include "publishers/nao_joint_state.hpp" #include "publishers/odometry.hpp" #include "publishers/laser.hpp" #include "publishers/log.hpp" #include "publishers/sonar.hpp" #include "publishers/string.hpp" /* * subscribers */ #include "subscribers/teleop.hpp" #include "subscribers/moveto.hpp" /* * STATIC FUNCTIONS INCLUDE */ #include "ros_env.hpp" #include "helpers.hpp" namespace alros { Bridge::Bridge( qi::SessionPtr& session ) : sessionPtr_( session ), freq_(15), publish_enabled_(false), publish_cancelled_(false), _recorder(boost::make_shared<Recorder>()) { //_recorder = std::make_shared<Recorder>(); std::cout << "application path "<< std::endl; } Bridge::~Bridge() { std::cout << "ALRosBridge is shutting down.." << std::endl; publish_cancelled_ = true; stop(); if (publisherThread_.get_id() != boost::thread::id()) publisherThread_.join(); // destroy nodehandle? if(nhPtr_) { nhPtr_->shutdown(); ros::shutdown(); } } void Bridge::rosLoop() { while( !publish_cancelled_ ) { { boost::mutex::scoped_lock lock( mutex_reinit_ ); if (publish_enabled_) { // Wait for the next Publisher to be ready size_t pub_index = pub_queue_.top().pub_index_; publisher::Publisher& pub = publishers_[pub_index]; ros::Time schedule = pub_queue_.top().schedule_; ros::Duration(schedule - ros::Time::now()).sleep(); if ( pub.isSubscribed() && pub.isInitialized()) { pub.publish(); if (_recorder->isRecording()) { std_msgs::Int32 i; i.data = 32; geometry_msgs::PointStamped ps; ps.point.x = 2; ps.point.y = 4; ps.point.z = 6; _recorder->write(pub.name(), ps); } } // Schedule for a future time or not pub_queue_.pop(); if ( pub.frequency() != 0 ) pub_queue_.push(ScheduledPublish(schedule + ros::Duration(1.0f / pub.frequency()), pub_index)); } else // sleep one second ros::Duration(1).sleep(); } ros::spinOnce(); } } // public interface here void Bridge::registerPublisher( publisher::Publisher pub ) { std::vector<publisher::Publisher>::iterator it; it = std::find( publishers_.begin(), publishers_.end(), pub ); // if publisher is not found, register it! if (it == publishers_.end() ) { publishers_.push_back( pub ); it = publishers_.end() - 1; std::cout << "registered publisher:\t" << pub.name() << std::endl; } // if found, re-init them else { std::cout << "re-initialized existing publisher:\t" << it->name() << std::endl; } } void Bridge::registerDefaultPublisher() { if (!publishers_.empty()) return; // Info should be at 0 (latched) but somehow that does not work ... publisher::Publisher info = alros::publisher::InfoPublisher("info", "info", 0.1, sessionPtr_); registerPublisher( info ); registerPublisher( alros::publisher::OdometryPublisher( "odometry", "/odom", 15, sessionPtr_) ); registerPublisher( alros::publisher::CameraPublisher("front_camera", "camera/front", 10, sessionPtr_, AL::kTopCamera, AL::kQVGA) ); registerPublisher( alros::publisher::DiagnosticsPublisher("diagnostics", 1, sessionPtr_) ); registerPublisher( alros::publisher::SonarPublisher("sonar", "sonar", 10, sessionPtr_) ); registerPublisher( alros::publisher::LogPublisher("logger", "", 5, sessionPtr_) ); // Pepper specific publishers if (info.robot() == alros::PEPPER) { registerPublisher( alros::publisher::JointStatePublisher("joint_states", "/joint_states", 15, sessionPtr_) ); registerPublisher( alros::publisher::LaserPublisher("laser", "laser", 10, sessionPtr_) ); registerPublisher( alros::publisher::CameraPublisher("depth_camera", "camera/depth", 10, sessionPtr_, AL::kDepthCamera, AL::kQVGA) ); } if (info.robot() == alros::NAO) { registerPublisher( alros::publisher::NaoJointStatePublisher( "nao_joint_states", "/joint_states", 15, sessionPtr_) ); } } // public interface here void Bridge::registerSubscriber( subscriber::Subscriber sub ) { std::vector<subscriber::Subscriber>::iterator it; it = std::find( subscribers_.begin(), subscribers_.end(), sub ); size_t sub_index = 0; // if subscriber is not found, register it! if (it == subscribers_.end() ) { sub_index = subscribers_.size(); subscribers_.push_back( sub ); std::cout << "registered subscriber:\t" << sub.name() << std::endl; } // if found, re-init them else { std::cout << "re-initialized existing subscriber:\t" << it->name() << std::endl; } } void Bridge::registerDefaultSubscriber() { if (!subscribers_.empty()) return; registerSubscriber( alros::subscriber::TeleopSubscriber("teleop", "/cmd_vel", sessionPtr_) ); registerSubscriber( alros::subscriber::MovetoSubscriber("moveto", "/move_base_simple/goal", sessionPtr_) ); } void Bridge::init() { pub_queue_ = std::priority_queue<ScheduledPublish>(); size_t pub_index = 0; foreach( publisher::Publisher& pub, publishers_ ) { pub.reset( *nhPtr_ ); // Schedule it for the next publish pub_queue_.push(ScheduledPublish(ros::Time::now(), pub_index)); ++pub_index; } foreach( subscriber::Subscriber& sub, subscribers_ ) { sub.reset( *nhPtr_ ); } } /* * EXPOSED FUNCTIONS */ std::string Bridge::getMasterURI() const { return ros_env::getMasterURI(); } void Bridge::setMasterURI( const std::string& uri) { setMasterURINet(uri, "eth0"); } void Bridge::setMasterURINet( const std::string& uri, const std::string& network_interface) { // Stopping publishing stop(); // Reinitializing ROS boost::mutex::scoped_lock lock( mutex_reinit_ ); nhPtr_.reset(); std::cout << "nodehandle reset " << std::endl; ros_env::setMasterURI( uri, network_interface ); nhPtr_.reset( new ros::NodeHandle("~") ); lock.unlock(); // Create the publishing thread if needed if (publisherThread_.get_id() == boost::thread::id()) publisherThread_ = boost::thread( &Bridge::rosLoop, this ); // register publishers, that will not start them registerDefaultPublisher(); registerDefaultSubscriber(); // initialize the publishers and subscribers with nodehandle init(); // Start publishing again start(); } void Bridge::start() { boost::mutex::scoped_lock lock( mutex_reinit_ ); publish_enabled_ = true; } void Bridge::stop() { boost::mutex::scoped_lock lock( mutex_reinit_ ); publish_enabled_ = false; } void Bridge::startRecord() { _recorder->startRecord(); } void Bridge::stopRecord() { _recorder->stopRecord(); } QI_REGISTER_OBJECT( Bridge, start, stop, getMasterURI, setMasterURI, setMasterURINet, startRecord, stopRecord ); } //alros <|endoftext|>
<commit_before>#include <node.h> #include <stdint.h> #include <cstring> #include <string> #include "../argon2/include/argon2.h" #include "argon2_node.h" namespace NodeArgon2 { const auto ENCODED_LEN = 108u; const auto HASH_LEN = 32u; HashAsyncWorker::HashAsyncWorker(const std::string& plain, const std::string& salt, uint32_t time_cost, uint32_t memory_cost, uint32_t parallelism, argon2_type type): Nan::AsyncWorker{nullptr}, plain{plain}, salt{salt}, time_cost{time_cost}, memory_cost{memory_cost}, parallelism{parallelism}, type{type}, output{} { } void HashAsyncWorker::Execute() { char encoded[ENCODED_LEN]; auto result = argon2_hash(time_cost, memory_cost, parallelism, plain.c_str(), plain.size(), salt.c_str(), salt.size(), nullptr, HASH_LEN, encoded, ENCODED_LEN, type); if (result != ARGON2_OK) { /* LCOV_EXCL_START */ SetErrorMessage(argon2_error_message(result)); return; /* LCOV_EXCL_STOP */ } output = std::string{encoded}; } void HashAsyncWorker::HandleOKCallback() { using v8::Promise; Nan::HandleScope scope; auto promise = GetFromPersistent("resolver").As<Promise::Resolver>(); promise->Resolve(Nan::Encode(output.c_str(), output.size())); } /* LCOV_EXCL_START */ void HashAsyncWorker::HandleErrorCallback() { using v8::Exception; using v8::Promise; Nan::HandleScope scope; auto promise = GetFromPersistent("resolver").As<Promise::Resolver>(); auto reason = Nan::New(ErrorMessage()).ToLocalChecked(); promise->Reject(Exception::Error(reason)); } /* LCOV_EXCL_STOP */ NAN_METHOD(Hash) { using namespace node; using v8::Promise; if (info.Length() < 6) { /* LCOV_EXCL_START */ Nan::ThrowTypeError("6 arguments expected"); return; /* LCOV_EXCL_STOP */ } auto raw_plain = info[0]->ToObject(); auto raw_salt = info[1]->ToObject(); auto time_cost = info[2]->Uint32Value(); auto memory_cost = info[3]->Uint32Value(); auto parallelism = info[4]->Uint32Value(); argon2_type type = info[5]->BooleanValue() ? Argon2_d : Argon2_i; std::string salt{Buffer::Data(raw_salt), Buffer::Length(raw_salt)}; std::string plain{Buffer::Data(raw_plain), Buffer::Length(raw_plain)}; auto worker = new HashAsyncWorker{plain, salt, time_cost, 1u << memory_cost, parallelism, type}; auto resolver = Promise::Resolver::New(info.GetIsolate()); worker->SaveToPersistent("resolver", resolver); Nan::AsyncQueueWorker(worker); info.GetReturnValue().Set(resolver->GetPromise()); } NAN_METHOD(HashSync) { using namespace node; if (info.Length() < 6) { /* LCOV_EXCL_START */ Nan::ThrowTypeError("6 arguments expected"); return; /* LCOV_EXCL_STOP */ } auto raw_plain = info[0]->ToObject(); auto raw_salt = info[1]->ToObject(); auto time_cost = info[2]->Uint32Value(); auto memory_cost = info[3]->Uint32Value(); auto parallelism = info[4]->Uint32Value(); argon2_type type = info[5]->BooleanValue() ? Argon2_d : Argon2_i; char encoded[ENCODED_LEN]; auto salt = std::string{Buffer::Data(raw_salt), Buffer::Length(raw_salt)}; auto result = argon2_hash(time_cost, 1 << memory_cost, parallelism, Buffer::Data(raw_plain), Buffer::Length(raw_plain), salt.c_str(), salt.size(), nullptr, HASH_LEN, encoded, ENCODED_LEN, type); if (result != ARGON2_OK) { /* LCOV_EXCL_START */ Nan::ThrowError(argon2_error_message(result)); return; /* LCOV_EXCL_STOP */ } info.GetReturnValue().Set(Nan::Encode(encoded, std::strlen(encoded))); } VerifyAsyncWorker::VerifyAsyncWorker(const std::string& hash, const std::string& plain, argon2_type type): Nan::AsyncWorker{nullptr}, hash{hash}, plain{plain}, type{type} { } void VerifyAsyncWorker::Execute() { auto result = argon2_verify(hash.c_str(), plain.c_str(), plain.size(), type); if (result != ARGON2_OK) { SetErrorMessage(argon2_error_message(result)); } } void VerifyAsyncWorker::HandleOKCallback() { using v8::Promise; Nan::HandleScope scope; auto promise = GetFromPersistent("resolver").As<Promise::Resolver>(); promise->Resolve(Nan::Undefined()); } void VerifyAsyncWorker::HandleErrorCallback() { using v8::Exception; using v8::Promise; Nan::HandleScope scope; auto promise = GetFromPersistent("resolver").As<Promise::Resolver>(); promise->Reject(Nan::New(ErrorMessage()).ToLocalChecked()); } NAN_METHOD(Verify) { using v8::Promise; using namespace node; if (info.Length() < 3) { /* LCOV_EXCL_START */ Nan::ThrowTypeError("3 arguments expected"); return; /* LCOV_EXCL_STOP */ } Nan::Utf8String hash{info[0]->ToString()}; auto raw_plain = info[1]->ToObject(); argon2_type type = info[2]->BooleanValue() ? Argon2_d : Argon2_i; std::string plain{Buffer::Data(raw_plain), Buffer::Length(raw_plain)}; auto worker = new VerifyAsyncWorker(*hash, plain, type); auto resolver = Promise::Resolver::New(info.GetIsolate()); worker->SaveToPersistent("resolver", resolver); Nan::AsyncQueueWorker(worker); info.GetReturnValue().Set(resolver->GetPromise()); } NAN_METHOD(VerifySync) { using namespace node; if (info.Length() < 3) { /* LCOV_EXCL_START */ Nan::ThrowTypeError("3 arguments expected"); return; /* LCOV_EXCL_STOP */ } Nan::Utf8String hash{info[0]->ToString()}; auto raw_plain = info[1]->ToObject(); argon2_type type = info[2]->BooleanValue() ? Argon2_d : Argon2_i; auto result = argon2_verify(*hash, Buffer::Data(raw_plain), Buffer::Length(raw_plain), type); info.GetReturnValue().Set(result == ARGON2_OK); } constexpr uint32_t log(uint32_t number, uint32_t base = 2u) { return (number > 1) ? 1u + log(number / base, base) : 0u; } } NAN_MODULE_INIT(init) { using namespace NodeArgon2; using NodeArgon2::log; using v8::Number; using v8::Object; auto limits = Nan::New<Object>(); { auto memoryCost = Nan::New<Object>(); Nan::Set(memoryCost, Nan::New("max").ToLocalChecked(), Nan::New<Number>(log(ARGON2_MAX_MEMORY))); Nan::Set(memoryCost, Nan::New("min").ToLocalChecked(), Nan::New<Number>(log(ARGON2_MIN_MEMORY))); Nan::Set(limits, Nan::New("memoryCost").ToLocalChecked(), memoryCost); } { auto timeCost = Nan::New<Object>(); Nan::Set(timeCost, Nan::New("max").ToLocalChecked(), Nan::New<Number>(ARGON2_MAX_TIME)); Nan::Set(timeCost, Nan::New("min").ToLocalChecked(), Nan::New<Number>(ARGON2_MIN_TIME)); Nan::Set(limits, Nan::New("timeCost").ToLocalChecked(), timeCost); } { auto parallelism = Nan::New<Object>(); Nan::Set(parallelism, Nan::New("max").ToLocalChecked(), Nan::New<Number>(ARGON2_MAX_LANES)); Nan::Set(parallelism, Nan::New("min").ToLocalChecked(), Nan::New<Number>(ARGON2_MIN_LANES)); Nan::Set(limits, Nan::New("parallelism").ToLocalChecked(), parallelism); } Nan::Set(target, Nan::New("limits").ToLocalChecked(), limits); Nan::Export(target, "hash", Hash); Nan::Export(target, "hashSync", HashSync); Nan::Export(target, "verify", Verify); Nan::Export(target, "verifySync", VerifySync); } NODE_MODULE(argon2_lib, init) <commit_msg>Standardize to always auto and move constructors<commit_after>#include <node.h> #include <stdint.h> #include <cstring> #include <string> #include "../argon2/include/argon2.h" #include "argon2_node.h" namespace NodeArgon2 { const auto ENCODED_LEN = 108u; const auto HASH_LEN = 32u; HashAsyncWorker::HashAsyncWorker(const std::string& plain, const std::string& salt, uint32_t time_cost, uint32_t memory_cost, uint32_t parallelism, argon2_type type): Nan::AsyncWorker{nullptr}, plain{plain}, salt{salt}, time_cost{time_cost}, memory_cost{memory_cost}, parallelism{parallelism}, type{type}, output{} { } void HashAsyncWorker::Execute() { char encoded[ENCODED_LEN]; auto result = argon2_hash(time_cost, memory_cost, parallelism, plain.c_str(), plain.size(), salt.c_str(), salt.size(), nullptr, HASH_LEN, encoded, ENCODED_LEN, type); if (result != ARGON2_OK) { /* LCOV_EXCL_START */ SetErrorMessage(argon2_error_message(result)); return; /* LCOV_EXCL_STOP */ } output = std::string{encoded}; } void HashAsyncWorker::HandleOKCallback() { using v8::Promise; Nan::HandleScope scope; auto promise = GetFromPersistent("resolver").As<Promise::Resolver>(); promise->Resolve(Nan::Encode(output.c_str(), output.size())); } /* LCOV_EXCL_START */ void HashAsyncWorker::HandleErrorCallback() { using v8::Exception; using v8::Promise; Nan::HandleScope scope; auto promise = GetFromPersistent("resolver").As<Promise::Resolver>(); auto reason = Nan::New(ErrorMessage()).ToLocalChecked(); promise->Reject(Exception::Error(reason)); } /* LCOV_EXCL_STOP */ NAN_METHOD(Hash) { using namespace node; using v8::Promise; if (info.Length() < 6) { /* LCOV_EXCL_START */ Nan::ThrowTypeError("6 arguments expected"); return; /* LCOV_EXCL_STOP */ } auto raw_plain = info[0]->ToObject(); auto raw_salt = info[1]->ToObject(); auto time_cost = info[2]->Uint32Value(); auto memory_cost = info[3]->Uint32Value(); auto parallelism = info[4]->Uint32Value(); auto type = info[5]->BooleanValue() ? Argon2_d : Argon2_i; auto plain = std::string{Buffer::Data(raw_plain), Buffer::Length(raw_plain)}; auto salt = std::string{Buffer::Data(raw_salt), Buffer::Length(raw_salt)}; auto worker = new HashAsyncWorker{plain, salt, time_cost, 1u << memory_cost, parallelism, type}; auto resolver = Promise::Resolver::New(info.GetIsolate()); worker->SaveToPersistent("resolver", resolver); Nan::AsyncQueueWorker(worker); info.GetReturnValue().Set(resolver->GetPromise()); } NAN_METHOD(HashSync) { using namespace node; if (info.Length() < 6) { /* LCOV_EXCL_START */ Nan::ThrowTypeError("6 arguments expected"); return; /* LCOV_EXCL_STOP */ } auto raw_plain = info[0]->ToObject(); auto raw_salt = info[1]->ToObject(); auto time_cost = info[2]->Uint32Value(); auto memory_cost = info[3]->Uint32Value(); auto parallelism = info[4]->Uint32Value(); auto type = info[5]->BooleanValue() ? Argon2_d : Argon2_i; char encoded[ENCODED_LEN]; auto result = argon2_hash(time_cost, 1 << memory_cost, parallelism, Buffer::Data(raw_plain), Buffer::Length(raw_plain), Buffer::Data(raw_salt), Buffer::Length(raw_salt), nullptr, HASH_LEN, encoded, ENCODED_LEN, type); if (result != ARGON2_OK) { /* LCOV_EXCL_START */ Nan::ThrowError(argon2_error_message(result)); return; /* LCOV_EXCL_STOP */ } info.GetReturnValue().Set(Nan::Encode(encoded, std::strlen(encoded))); } VerifyAsyncWorker::VerifyAsyncWorker(const std::string& hash, const std::string& plain, argon2_type type): Nan::AsyncWorker{nullptr}, hash{hash}, plain{plain}, type{type} { } void VerifyAsyncWorker::Execute() { auto result = argon2_verify(hash.c_str(), plain.c_str(), plain.size(), type); if (result != ARGON2_OK) { SetErrorMessage(argon2_error_message(result)); } } void VerifyAsyncWorker::HandleOKCallback() { using v8::Promise; Nan::HandleScope scope; auto promise = GetFromPersistent("resolver").As<Promise::Resolver>(); promise->Resolve(Nan::Undefined()); } void VerifyAsyncWorker::HandleErrorCallback() { using v8::Exception; using v8::Promise; Nan::HandleScope scope; auto promise = GetFromPersistent("resolver").As<Promise::Resolver>(); promise->Reject(Nan::New(ErrorMessage()).ToLocalChecked()); } NAN_METHOD(Verify) { using v8::Promise; using namespace node; if (info.Length() < 3) { /* LCOV_EXCL_START */ Nan::ThrowTypeError("3 arguments expected"); return; /* LCOV_EXCL_STOP */ } Nan::Utf8String hash{info[0]->ToString()}; auto raw_plain = info[1]->ToObject(); auto type = info[2]->BooleanValue() ? Argon2_d : Argon2_i; auto plain = std::string{Buffer::Data(raw_plain), Buffer::Length(raw_plain)}; auto worker = new VerifyAsyncWorker(*hash, plain, type); auto resolver = Promise::Resolver::New(info.GetIsolate()); worker->SaveToPersistent("resolver", resolver); Nan::AsyncQueueWorker(worker); info.GetReturnValue().Set(resolver->GetPromise()); } NAN_METHOD(VerifySync) { using namespace node; if (info.Length() < 3) { /* LCOV_EXCL_START */ Nan::ThrowTypeError("3 arguments expected"); return; /* LCOV_EXCL_STOP */ } Nan::Utf8String hash{info[0]->ToString()}; auto raw_plain = info[1]->ToObject(); auto type = info[2]->BooleanValue() ? Argon2_d : Argon2_i; auto result = argon2_verify(*hash, Buffer::Data(raw_plain), Buffer::Length(raw_plain), type); info.GetReturnValue().Set(result == ARGON2_OK); } constexpr uint32_t log(uint32_t number, uint32_t base = 2u) { return (number > 1) ? 1u + log(number / base, base) : 0u; } } NAN_MODULE_INIT(init) { using namespace NodeArgon2; using NodeArgon2::log; using v8::Number; using v8::Object; auto limits = Nan::New<Object>(); { auto memoryCost = Nan::New<Object>(); Nan::Set(memoryCost, Nan::New("max").ToLocalChecked(), Nan::New<Number>(log(ARGON2_MAX_MEMORY))); Nan::Set(memoryCost, Nan::New("min").ToLocalChecked(), Nan::New<Number>(log(ARGON2_MIN_MEMORY))); Nan::Set(limits, Nan::New("memoryCost").ToLocalChecked(), memoryCost); } { auto timeCost = Nan::New<Object>(); Nan::Set(timeCost, Nan::New("max").ToLocalChecked(), Nan::New<Number>(ARGON2_MAX_TIME)); Nan::Set(timeCost, Nan::New("min").ToLocalChecked(), Nan::New<Number>(ARGON2_MIN_TIME)); Nan::Set(limits, Nan::New("timeCost").ToLocalChecked(), timeCost); } { auto parallelism = Nan::New<Object>(); Nan::Set(parallelism, Nan::New("max").ToLocalChecked(), Nan::New<Number>(ARGON2_MAX_LANES)); Nan::Set(parallelism, Nan::New("min").ToLocalChecked(), Nan::New<Number>(ARGON2_MIN_LANES)); Nan::Set(limits, Nan::New("parallelism").ToLocalChecked(), parallelism); } Nan::Set(target, Nan::New("limits").ToLocalChecked(), limits); Nan::Export(target, "hash", Hash); Nan::Export(target, "hashSync", HashSync); Nan::Export(target, "verify", Verify); Nan::Export(target, "verifySync", VerifySync); } NODE_MODULE(argon2_lib, init) <|endoftext|>
<commit_before>/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "perfetto/base/logging.h" #include <stdarg.h> #include <stdio.h> #if !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) #include <unistd.h> // For isatty() #endif #include <atomic> #include <memory> #include "perfetto/base/build_config.h" #include "perfetto/base/time.h" #include "perfetto/ext/base/crash_keys.h" #include "perfetto/ext/base/string_utils.h" #include "perfetto/ext/base/string_view.h" #include "src/base/log_ring_buffer.h" #if PERFETTO_ENABLE_LOG_RING_BUFFER() && PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) #include <android/set_abort_message.h> #endif namespace perfetto { namespace base { namespace { const char kReset[] = "\x1b[0m"; const char kDefault[] = "\x1b[39m"; const char kDim[] = "\x1b[2m"; const char kRed[] = "\x1b[31m"; const char kBoldGreen[] = "\x1b[1m\x1b[32m"; const char kLightGray[] = "\x1b[90m"; std::atomic<LogMessageCallback> g_log_callback{}; #if PERFETTO_BUILDFLAG(PERFETTO_STDERR_CRASH_DUMP) // __attribute__((constructor)) causes a static initializer that automagically // early runs this function before the main(). void PERFETTO_EXPORT_COMPONENT __attribute__((constructor)) InitDebugCrashReporter() { // This function is defined in debug_crash_stack_trace.cc. // The dynamic initializer is in logging.cc because logging.cc is included // in virtually any target that depends on base. Having it in // debug_crash_stack_trace.cc would require figuring out -Wl,whole-archive // which is not worth it. EnableStacktraceOnCrashForDebug(); } #endif #if PERFETTO_ENABLE_LOG_RING_BUFFER() LogRingBuffer g_log_ring_buffer{}; // This is global to avoid allocating memory or growing too much the stack // in MaybeSerializeLastLogsForCrashReporting(), which is called from // arbitrary code paths hitting PERFETTO_CHECK()/FATAL(). char g_crash_buf[kLogRingBufEntries * kLogRingBufMsgLen]; #endif } // namespace void SetLogMessageCallback(LogMessageCallback callback) { g_log_callback.store(callback, std::memory_order_relaxed); } void LogMessage(LogLev level, const char* fname, int line, const char* fmt, ...) { char stack_buf[512]; std::unique_ptr<char[]> large_buf; char* log_msg = &stack_buf[0]; size_t log_msg_len = 0; // By default use a stack allocated buffer because most log messages are quite // short. In rare cases they can be larger (e.g. --help). In those cases we // pay the cost of allocating the buffer on the heap. for (size_t max_len = sizeof(stack_buf);;) { va_list args; va_start(args, fmt); int res = vsnprintf(log_msg, max_len, fmt, args); va_end(args); // If for any reason the print fails, overwrite the message but still print // it. The code below will attach the filename and line, which is still // useful. if (res < 0) { snprintf(log_msg, max_len, "%s", "[printf format error]"); break; } // if res == max_len, vsnprintf saturated the input buffer. Retry with a // larger buffer in that case (within reasonable limits). if (res < static_cast<int>(max_len) || max_len >= 128 * 1024) { // In case of truncation vsnprintf returns the len that "would have been // written if the string was longer", not the actual chars written. log_msg_len = std::min(static_cast<size_t>(res), max_len - 1); break; } max_len *= 4; large_buf.reset(new char[max_len]); log_msg = &large_buf[0]; } LogMessageCallback cb = g_log_callback.load(std::memory_order_relaxed); if (cb) { cb({level, line, fname, log_msg}); return; } const char* color = kDefault; switch (level) { case kLogDebug: color = kDim; break; case kLogInfo: color = kDefault; break; case kLogImportant: color = kBoldGreen; break; case kLogError: color = kRed; break; } #if !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) && \ !PERFETTO_BUILDFLAG(PERFETTO_OS_WASM) && \ !PERFETTO_BUILDFLAG(PERFETTO_CHROMIUM_BUILD) static const bool use_colors = isatty(STDERR_FILENO); #else static const bool use_colors = false; #endif // Formats file.cc:line as a space-padded fixed width string. If the file name // |fname| is too long, truncate it on the left-hand side. StackString<10> line_str("%d", line); // 24 will be the width of the file.cc:line column in the log event. static constexpr size_t kMaxNameAndLine = 24; size_t fname_len = strlen(fname); size_t fname_max = kMaxNameAndLine - line_str.len() - 2; // 2 = ':' + '\0'. size_t fname_offset = fname_len <= fname_max ? 0 : fname_len - fname_max; StackString<kMaxNameAndLine> file_and_line( "%*s:%s", static_cast<int>(fname_max), &fname[fname_offset], line_str.c_str()); #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) // Logcat has already timestamping, don't re-emit it. __android_log_print(ANDROID_LOG_DEBUG + level, "perfetto", "%s %s", file_and_line.c_str(), log_msg); #endif // When printing on stderr, print also the timestamp. We don't really care // about the actual time. We just need some reference clock that can be used // to correlated events across differrent processses (e.g. traced and // traced_probes). The wall time % 1000 is good enough. uint32_t t_ms = static_cast<uint32_t>(GetWallTimeMs().count()); uint32_t t_sec = t_ms / 1000; t_ms -= t_sec * 1000; t_sec = t_sec % 1000; StackString<32> timestamp("[%03u.%03u] ", t_sec, t_ms); if (use_colors) { fprintf(stderr, "%s%s%s%s %s%s%s\n", kLightGray, timestamp.c_str(), file_and_line.c_str(), kReset, color, log_msg, kReset); } else { fprintf(stderr, "%s%s %s\n", timestamp.c_str(), file_and_line.c_str(), log_msg); } #if PERFETTO_ENABLE_LOG_RING_BUFFER() // Append the message to the ring buffer for crash reporting postmortems. StringView timestamp_sv = timestamp.string_view(); StringView file_and_line_sv = file_and_line.string_view(); StringView log_msg_sv(log_msg, static_cast<size_t>(log_msg_len)); g_log_ring_buffer.Append(timestamp_sv, file_and_line_sv, log_msg_sv); #else ignore_result(log_msg_len); #endif } #if PERFETTO_ENABLE_LOG_RING_BUFFER() void MaybeSerializeLastLogsForCrashReporting() { // Keep this function minimal. This is called from the watchdog thread, often // when the system is thrashing. // This is racy because two threads could hit a CHECK/FATAL at the same time. // But if that happens we have bigger problems, not worth designing around it. // The behaviour is still defined in the race case (the string attached to // the crash report will contain a mixture of log strings). size_t wr = 0; wr += SerializeCrashKeys(&g_crash_buf[wr], sizeof(g_crash_buf) - wr); wr += g_log_ring_buffer.Read(&g_crash_buf[wr], sizeof(g_crash_buf) - wr); // Read() null-terminates the string properly. This is just to avoid UB when // two threads race on each other (T1 writes a shorter string, T2 // overwrites the \0 writing a longer string. T1 continues here before T2 // finishes writing the longer string with the \0 -> boom. g_crash_buf[sizeof(g_crash_buf) - 1] = '\0'; #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) // android_set_abort_message() will cause debuggerd to report the message // in the tombstone and in the crash log in logcat. // NOTE: android_set_abort_message() can be called only once. This should // be called only when we are sure we are about to crash. android_set_abort_message(g_crash_buf); #else // Print out the message on stderr on Linux/Mac/Win. fputs("\n-----BEGIN PERFETTO PRE-CRASH LOG-----\n", stderr); fputs(g_crash_buf, stderr); fputs("\n-----END PERFETTO PRE-CRASH LOG-----\n", stderr); #endif } #endif // PERFETTO_ENABLE_LOG_RING_BUFFER } // namespace base } // namespace perfetto <commit_msg>C++20 fixes.<commit_after>/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "perfetto/base/logging.h" #include <stdarg.h> #include <stdio.h> #if !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) #include <unistd.h> // For isatty() #endif #include <atomic> #include <memory> #include "perfetto/base/build_config.h" #include "perfetto/base/time.h" #include "perfetto/ext/base/crash_keys.h" #include "perfetto/ext/base/string_utils.h" #include "perfetto/ext/base/string_view.h" #include "src/base/log_ring_buffer.h" #if PERFETTO_ENABLE_LOG_RING_BUFFER() && PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) #include <android/set_abort_message.h> #endif namespace perfetto { namespace base { namespace { const char kReset[] = "\x1b[0m"; const char kDefault[] = "\x1b[39m"; const char kDim[] = "\x1b[2m"; const char kRed[] = "\x1b[31m"; const char kBoldGreen[] = "\x1b[1m\x1b[32m"; const char kLightGray[] = "\x1b[90m"; std::atomic<LogMessageCallback> g_log_callback{}; #if PERFETTO_BUILDFLAG(PERFETTO_STDERR_CRASH_DUMP) // __attribute__((constructor)) causes a static initializer that automagically // early runs this function before the main(). void PERFETTO_EXPORT_COMPONENT __attribute__((constructor)) InitDebugCrashReporter() { // This function is defined in debug_crash_stack_trace.cc. // The dynamic initializer is in logging.cc because logging.cc is included // in virtually any target that depends on base. Having it in // debug_crash_stack_trace.cc would require figuring out -Wl,whole-archive // which is not worth it. EnableStacktraceOnCrashForDebug(); } #endif #if PERFETTO_ENABLE_LOG_RING_BUFFER() LogRingBuffer g_log_ring_buffer{}; // This is global to avoid allocating memory or growing too much the stack // in MaybeSerializeLastLogsForCrashReporting(), which is called from // arbitrary code paths hitting PERFETTO_CHECK()/FATAL(). char g_crash_buf[kLogRingBufEntries * kLogRingBufMsgLen]; #endif } // namespace void SetLogMessageCallback(LogMessageCallback callback) { g_log_callback.store(callback, std::memory_order_relaxed); } void LogMessage(LogLev level, const char* fname, int line, const char* fmt, ...) { char stack_buf[512]; std::unique_ptr<char[]> large_buf; char* log_msg = &stack_buf[0]; size_t log_msg_len = 0; // By default use a stack allocated buffer because most log messages are quite // short. In rare cases they can be larger (e.g. --help). In those cases we // pay the cost of allocating the buffer on the heap. for (size_t max_len = sizeof(stack_buf);;) { va_list args; va_start(args, fmt); int res = vsnprintf(log_msg, max_len, fmt, args); va_end(args); // If for any reason the print fails, overwrite the message but still print // it. The code below will attach the filename and line, which is still // useful. if (res < 0) { snprintf(log_msg, max_len, "%s", "[printf format error]"); break; } // if res == max_len, vsnprintf saturated the input buffer. Retry with a // larger buffer in that case (within reasonable limits). if (res < static_cast<int>(max_len) || max_len >= 128 * 1024) { // In case of truncation vsnprintf returns the len that "would have been // written if the string was longer", not the actual chars written. log_msg_len = std::min(static_cast<size_t>(res), max_len - 1); break; } max_len *= 4; large_buf.reset(new char[max_len]); log_msg = &large_buf[0]; } LogMessageCallback cb = g_log_callback.load(std::memory_order_relaxed); if (cb) { cb({level, line, fname, log_msg}); return; } const char* color = kDefault; switch (level) { case kLogDebug: color = kDim; break; case kLogInfo: color = kDefault; break; case kLogImportant: color = kBoldGreen; break; case kLogError: color = kRed; break; } #if !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) && \ !PERFETTO_BUILDFLAG(PERFETTO_OS_WASM) && \ !PERFETTO_BUILDFLAG(PERFETTO_CHROMIUM_BUILD) static const bool use_colors = isatty(STDERR_FILENO); #else static const bool use_colors = false; #endif // Formats file.cc:line as a space-padded fixed width string. If the file name // |fname| is too long, truncate it on the left-hand side. StackString<10> line_str("%d", line); // 24 will be the width of the file.cc:line column in the log event. static constexpr size_t kMaxNameAndLine = 24; size_t fname_len = strlen(fname); size_t fname_max = kMaxNameAndLine - line_str.len() - 2; // 2 = ':' + '\0'. size_t fname_offset = fname_len <= fname_max ? 0 : fname_len - fname_max; StackString<kMaxNameAndLine> file_and_line( "%*s:%s", static_cast<int>(fname_max), &fname[fname_offset], line_str.c_str()); #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) // Logcat has already timestamping, don't re-emit it. __android_log_print(int{ANDROID_LOG_DEBUG} + level, "perfetto", "%s %s", file_and_line.c_str(), log_msg); #endif // When printing on stderr, print also the timestamp. We don't really care // about the actual time. We just need some reference clock that can be used // to correlated events across differrent processses (e.g. traced and // traced_probes). The wall time % 1000 is good enough. uint32_t t_ms = static_cast<uint32_t>(GetWallTimeMs().count()); uint32_t t_sec = t_ms / 1000; t_ms -= t_sec * 1000; t_sec = t_sec % 1000; StackString<32> timestamp("[%03u.%03u] ", t_sec, t_ms); if (use_colors) { fprintf(stderr, "%s%s%s%s %s%s%s\n", kLightGray, timestamp.c_str(), file_and_line.c_str(), kReset, color, log_msg, kReset); } else { fprintf(stderr, "%s%s %s\n", timestamp.c_str(), file_and_line.c_str(), log_msg); } #if PERFETTO_ENABLE_LOG_RING_BUFFER() // Append the message to the ring buffer for crash reporting postmortems. StringView timestamp_sv = timestamp.string_view(); StringView file_and_line_sv = file_and_line.string_view(); StringView log_msg_sv(log_msg, static_cast<size_t>(log_msg_len)); g_log_ring_buffer.Append(timestamp_sv, file_and_line_sv, log_msg_sv); #else ignore_result(log_msg_len); #endif } #if PERFETTO_ENABLE_LOG_RING_BUFFER() void MaybeSerializeLastLogsForCrashReporting() { // Keep this function minimal. This is called from the watchdog thread, often // when the system is thrashing. // This is racy because two threads could hit a CHECK/FATAL at the same time. // But if that happens we have bigger problems, not worth designing around it. // The behaviour is still defined in the race case (the string attached to // the crash report will contain a mixture of log strings). size_t wr = 0; wr += SerializeCrashKeys(&g_crash_buf[wr], sizeof(g_crash_buf) - wr); wr += g_log_ring_buffer.Read(&g_crash_buf[wr], sizeof(g_crash_buf) - wr); // Read() null-terminates the string properly. This is just to avoid UB when // two threads race on each other (T1 writes a shorter string, T2 // overwrites the \0 writing a longer string. T1 continues here before T2 // finishes writing the longer string with the \0 -> boom. g_crash_buf[sizeof(g_crash_buf) - 1] = '\0'; #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) // android_set_abort_message() will cause debuggerd to report the message // in the tombstone and in the crash log in logcat. // NOTE: android_set_abort_message() can be called only once. This should // be called only when we are sure we are about to crash. android_set_abort_message(g_crash_buf); #else // Print out the message on stderr on Linux/Mac/Win. fputs("\n-----BEGIN PERFETTO PRE-CRASH LOG-----\n", stderr); fputs(g_crash_buf, stderr); fputs("\n-----END PERFETTO PRE-CRASH LOG-----\n", stderr); #endif } #endif // PERFETTO_ENABLE_LOG_RING_BUFFER } // namespace base } // namespace perfetto <|endoftext|>
<commit_before>// Copyright 2010-2013 Google // 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 "base/numbers.h" #include <cctype> #include <cstdlib> namespace operations_research { bool safe_strtof(const char* str, float* value) { char* endptr; #ifdef _MSC_VER // has no strtof() *value = strtod(str, &endptr); #else *value = strtof(str, &endptr); #endif if (endptr != str) { while (isspace(*endptr)) ++endptr; } // Ignore range errors from strtod/strtof. // The values it returns on underflow and // overflow are the right fallback in a // robust setting. return *str != '\0' && *endptr == '\0'; } bool safe_strtod(const char* str, double* value) { char* endptr; *value = strtod(str, &endptr); if (endptr != str) { while (isspace(*endptr)) ++endptr; } // Ignore range errors from strtod. The values it // returns on underflow and overflow are the right // fallback in a robust setting. return *str != '\0' && *endptr == '\0'; } bool safe_strtof(const std::string& str, float* value) { return safe_strtof(str.c_str(), value); } bool safe_strtod(const std::string& str, double* value) { return safe_strtod(str.c_str(), value); } bool safe_strto64(const std::string& str, int64* value) { if (str.empty()) return false; char* endptr; *value = strtoll(str.c_str(), &endptr, /*base=*/10); // NOLINT return *endptr == '\0' && str[0] != '\0'; } } // namespace operations_research <commit_msg>fix for visual studio 2012<commit_after>// Copyright 2010-2013 Google // 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 "base/numbers.h" #include <cctype> #include <cstdlib> namespace operations_research { bool safe_strtof(const char* str, float* value) { char* endptr; #ifdef _MSC_VER // has no strtof() *value = strtod(str, &endptr); #else *value = strtof(str, &endptr); #endif if (endptr != str) { while (isspace(*endptr)) ++endptr; } // Ignore range errors from strtod/strtof. // The values it returns on underflow and // overflow are the right fallback in a // robust setting. return *str != '\0' && *endptr == '\0'; } bool safe_strtod(const char* str, double* value) { char* endptr; *value = strtod(str, &endptr); if (endptr != str) { while (isspace(*endptr)) ++endptr; } // Ignore range errors from strtod. The values it // returns on underflow and overflow are the right // fallback in a robust setting. return *str != '\0' && *endptr == '\0'; } bool safe_strtof(const std::string& str, float* value) { return safe_strtof(str.c_str(), value); } bool safe_strtod(const std::string& str, double* value) { return safe_strtod(str.c_str(), value); } bool safe_strto64(const std::string& str, int64* value) { if (str.empty()) return false; char* endptr; #if defined(_MSV_VER) *value = _strtoll(str.c_str(), &endptr, /*base=*/10); // NOLINT #else *value = strtoll(str.c_str(), &endptr, /*base=*/10); // NOLINT #endif return *endptr == '\0' && str[0] != '\0'; } } // namespace operations_research <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "process_memory_stats.h" #include <vespa/vespalib/stllike/asciistream.h> #include <fstream> #include <sstream> #include <algorithm> #include <vespa/log/log.h> LOG_SETUP(".vespalib.util.process_memory_stats"); namespace vespalib { namespace { /* * Check if line specifies an address range. * * address perms offset dev inode pathname * * 00400000-00420000 r-xp 00000000 fd:04 16545041 /usr/bin/less */ bool isRange(const std::string &line) { for (char c : line) { if (c == ' ') { return true; } if (c == ':') { return false; } } return false; } /* * Check if address range is anonymous, e.g. not mapped from file. * inode number is 0 in that case. * * address perms offset dev inode pathname * * 00400000-00420000 r-xp 00000000 fd:04 16545041 /usr/bin/less * 00625000-00628000 rw-p 00000000 00:00 0 * * The range starting at 00400000 is not anonymous. * The range starting at 00625000 is anonymous. */ bool isAnonymous(const std::string &line) { int delims = 0; for (char c : line) { if (delims >= 4) { return (c == '0'); } if (c == ' ') { ++delims; } } return true; } /* * Lines not containing an address range contains a header and a * value, e.g. * * Size: 128 kB * Rss: 96 kB * Anonymous: 0 kB * * The lines with header Anonymous are ignored, thus anonymous pages * caused by mmap() of a file with MAP_PRIVATE flags are counted as * mapped pages. */ std::string getLineHeader(const std::string &line) { size_t len = 0; for (char c : line) { if (c == ':') { return line.substr(0, len); } ++len; } LOG_ABORT("should not be reached"); } } ProcessMemoryStats ProcessMemoryStats::createStatsFromSmaps() { ProcessMemoryStats ret; std::ifstream smaps("/proc/self/smaps"); std::string line; std::string lineHeader; bool anonymous = true; uint64_t lineVal = 0; while (smaps.good()) { std::getline(smaps, line); if (isRange(line)) { ret._mappings_count += 1; anonymous = isAnonymous(line); } else if (!line.empty()) { lineHeader = getLineHeader(line); std::istringstream is(line.substr(lineHeader.size() + 1)); is >> lineVal; if (lineHeader == "Size") { if (anonymous) { ret._anonymous_virt += lineVal * 1024; } else { ret._mapped_virt += lineVal * 1024; } } else if (lineHeader == "Rss") { if (anonymous) { ret._anonymous_rss += lineVal * 1024; } else { ret._mapped_rss += lineVal * 1024; } } } } return ret; } ProcessMemoryStats::ProcessMemoryStats() : _mapped_virt(0), _mapped_rss(0), _anonymous_virt(0), _anonymous_rss(0), _mappings_count(0) { } ProcessMemoryStats::ProcessMemoryStats(uint64_t mapped_virt, uint64_t mapped_rss, uint64_t anonymous_virt, uint64_t anonymous_rss, uint64_t mappings_cnt) : _mapped_virt(mapped_virt), _mapped_rss(mapped_rss), _anonymous_virt(anonymous_virt), _anonymous_rss(anonymous_rss), _mappings_count(mappings_cnt) { } namespace { bool similar(uint64_t lhs, uint64_t rhs, uint64_t epsilon) { return (lhs < rhs) ? ((rhs - lhs) <= epsilon) : ((lhs - rhs) <= epsilon); } } bool ProcessMemoryStats::similarTo(const ProcessMemoryStats &rhs, uint64_t sizeEpsilon) const { return similar(_mapped_virt, rhs._mapped_virt, sizeEpsilon) && similar(_mapped_rss, rhs._mapped_rss, sizeEpsilon) && similar(_anonymous_virt, rhs._anonymous_virt, sizeEpsilon) && similar(_anonymous_rss, rhs._anonymous_rss, sizeEpsilon) && (_mappings_count == rhs._mappings_count); } vespalib::string ProcessMemoryStats::toString() const { vespalib::asciistream stream; stream << "_mapped_virt=" << _mapped_virt << ", " << "_mapped_rss=" << _mapped_rss << ", " << "_anonymous_virt=" << _anonymous_virt << ", " << "_anonymous_rss=" << _anonymous_rss << ", " << "_mappings_count=" << _mappings_count; return stream.str(); } ProcessMemoryStats ProcessMemoryStats::create(uint64_t sizeEpsilon) { constexpr size_t NUM_TRIES = 10; std::vector<ProcessMemoryStats> samples; samples.reserve(NUM_TRIES); samples.push_back(createStatsFromSmaps()); for (size_t i = 0; i < NUM_TRIES; ++i) { samples.push_back(createStatsFromSmaps()); if (samples.back().similarTo(*(samples.rbegin()+1), sizeEpsilon)) { return samples.back(); } LOG(debug, "create(): Memory stats have changed, trying to read smaps file again: i=%zu, prevStats={%s}, currStats={%s}", i, (samples.rbegin()+1)->toString().c_str(), samples.back().toString().c_str()); } std::sort(samples.begin(), samples.end()); LOG(warning, "We failed to find 2 consecutive samples that where similar with epsilon of %lu.\nSmallest is '%s',\n median is '%s',\n largest is '%s'", sizeEpsilon, samples.front().toString().c_str(), samples[samples.size()/2].toString().c_str(), samples.back().toString().c_str()); return samples[samples.size()/2]; } } <commit_msg>Fix format string in ProcessMemoryStats::create method.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "process_memory_stats.h" #include <vespa/vespalib/stllike/asciistream.h> #include <fstream> #include <sstream> #include <algorithm> #include <vespa/log/log.h> LOG_SETUP(".vespalib.util.process_memory_stats"); namespace vespalib { namespace { /* * Check if line specifies an address range. * * address perms offset dev inode pathname * * 00400000-00420000 r-xp 00000000 fd:04 16545041 /usr/bin/less */ bool isRange(const std::string &line) { for (char c : line) { if (c == ' ') { return true; } if (c == ':') { return false; } } return false; } /* * Check if address range is anonymous, e.g. not mapped from file. * inode number is 0 in that case. * * address perms offset dev inode pathname * * 00400000-00420000 r-xp 00000000 fd:04 16545041 /usr/bin/less * 00625000-00628000 rw-p 00000000 00:00 0 * * The range starting at 00400000 is not anonymous. * The range starting at 00625000 is anonymous. */ bool isAnonymous(const std::string &line) { int delims = 0; for (char c : line) { if (delims >= 4) { return (c == '0'); } if (c == ' ') { ++delims; } } return true; } /* * Lines not containing an address range contains a header and a * value, e.g. * * Size: 128 kB * Rss: 96 kB * Anonymous: 0 kB * * The lines with header Anonymous are ignored, thus anonymous pages * caused by mmap() of a file with MAP_PRIVATE flags are counted as * mapped pages. */ std::string getLineHeader(const std::string &line) { size_t len = 0; for (char c : line) { if (c == ':') { return line.substr(0, len); } ++len; } LOG_ABORT("should not be reached"); } } ProcessMemoryStats ProcessMemoryStats::createStatsFromSmaps() { ProcessMemoryStats ret; std::ifstream smaps("/proc/self/smaps"); std::string line; std::string lineHeader; bool anonymous = true; uint64_t lineVal = 0; while (smaps.good()) { std::getline(smaps, line); if (isRange(line)) { ret._mappings_count += 1; anonymous = isAnonymous(line); } else if (!line.empty()) { lineHeader = getLineHeader(line); std::istringstream is(line.substr(lineHeader.size() + 1)); is >> lineVal; if (lineHeader == "Size") { if (anonymous) { ret._anonymous_virt += lineVal * 1024; } else { ret._mapped_virt += lineVal * 1024; } } else if (lineHeader == "Rss") { if (anonymous) { ret._anonymous_rss += lineVal * 1024; } else { ret._mapped_rss += lineVal * 1024; } } } } return ret; } ProcessMemoryStats::ProcessMemoryStats() : _mapped_virt(0), _mapped_rss(0), _anonymous_virt(0), _anonymous_rss(0), _mappings_count(0) { } ProcessMemoryStats::ProcessMemoryStats(uint64_t mapped_virt, uint64_t mapped_rss, uint64_t anonymous_virt, uint64_t anonymous_rss, uint64_t mappings_cnt) : _mapped_virt(mapped_virt), _mapped_rss(mapped_rss), _anonymous_virt(anonymous_virt), _anonymous_rss(anonymous_rss), _mappings_count(mappings_cnt) { } namespace { bool similar(uint64_t lhs, uint64_t rhs, uint64_t epsilon) { return (lhs < rhs) ? ((rhs - lhs) <= epsilon) : ((lhs - rhs) <= epsilon); } } bool ProcessMemoryStats::similarTo(const ProcessMemoryStats &rhs, uint64_t sizeEpsilon) const { return similar(_mapped_virt, rhs._mapped_virt, sizeEpsilon) && similar(_mapped_rss, rhs._mapped_rss, sizeEpsilon) && similar(_anonymous_virt, rhs._anonymous_virt, sizeEpsilon) && similar(_anonymous_rss, rhs._anonymous_rss, sizeEpsilon) && (_mappings_count == rhs._mappings_count); } vespalib::string ProcessMemoryStats::toString() const { vespalib::asciistream stream; stream << "_mapped_virt=" << _mapped_virt << ", " << "_mapped_rss=" << _mapped_rss << ", " << "_anonymous_virt=" << _anonymous_virt << ", " << "_anonymous_rss=" << _anonymous_rss << ", " << "_mappings_count=" << _mappings_count; return stream.str(); } ProcessMemoryStats ProcessMemoryStats::create(uint64_t sizeEpsilon) { constexpr size_t NUM_TRIES = 10; std::vector<ProcessMemoryStats> samples; samples.reserve(NUM_TRIES); samples.push_back(createStatsFromSmaps()); for (size_t i = 0; i < NUM_TRIES; ++i) { samples.push_back(createStatsFromSmaps()); if (samples.back().similarTo(*(samples.rbegin()+1), sizeEpsilon)) { return samples.back(); } LOG(debug, "create(): Memory stats have changed, trying to read smaps file again: i=%zu, prevStats={%s}, currStats={%s}", i, (samples.rbegin()+1)->toString().c_str(), samples.back().toString().c_str()); } std::sort(samples.begin(), samples.end()); LOG(warning, "We failed to find 2 consecutive samples that where similar with epsilon of %" PRIu64 ".\nSmallest is '%s',\n median is '%s',\n largest is '%s'", sizeEpsilon, samples.front().toString().c_str(), samples[samples.size()/2].toString().c_str(), samples.back().toString().c_str()); return samples[samples.size()/2]; } } <|endoftext|>
<commit_before>#include "board_graph.hpp" namespace Quoridor { FilterEdges::FilterEdges() : edges_() { } FilterEdges::~FilterEdges() { } void FilterEdges::add_edge(const edge_descriptor &e) { edges_.insert(e); } void FilterEdges::clear() { edges_.clear(); } template <typename EdgeDesc> bool FilterEdges::operator()(const EdgeDesc &e) const { return edges_.find(e) == edges_.end(); } BoardGraph::BoardGraph() : g_(), nodes_(), edges_(), fe_() { } BoardGraph::~BoardGraph() { } int BoardGraph::set_size(int row_num, int col_num) { if ((row_num <= 0) || (col_num <= 0)) { return -1; } g_ = graph_t(row_num * col_num); for (int i = 0; i < row_num * col_num; ++i) { nodes_.push_back(i); } int nidx; for (int i = 0; i < row_num; ++i) { for (int j = 0; j < col_num; ++j) { if (j != 0) { nidx = i * col_num + j - 1; edges_.insert(edge(nodes_[i * col_num + j], nodes_[nidx])); } if (j != col_num - 1) { nidx = i * col_num + j + 1; edges_.insert(edge(nodes_[i * col_num + j], nodes_[nidx])); } if (i != 0) { nidx = (i - 1) * col_num + j; edges_.insert(edge(nodes_[i * col_num + j], nodes_[nidx])); } if (i != row_num - 1) { nidx = (i + 1) * col_num + j; edges_.insert(edge(nodes_[i * col_num + j], nodes_[nidx])); } } } WeightMap weightmap = boost::get(boost::edge_weight, g_); edge_descriptor e; bool b; for (auto &it : edges_) { boost::tie(e, b) = boost::add_edge(it.first, it.second, g_); weightmap[e] = 1; } return 0; } void BoardGraph::remove_edges(int node1, int node2) { edge_descriptor ed; bool b; boost::tie(ed, b) = boost::edge(node1, node2, g_); if (b) { g_.remove_edge(ed); } boost::tie(ed, b) = boost::edge(node2, node1, g_); if (b) { g_.remove_edge(ed); } edges_.erase(edge(node1, node2)); edges_.erase(edge(node2, node1)); } bool BoardGraph::find_path(int start_node, int end_node, std::list<int> *path) const { std::vector<vertex> p(boost::num_vertices(g_)); std::vector<int> d(boost::num_vertices(g_)); vertex start = boost::vertex(start_node, g_); vertex end = boost::vertex(end_node, g_); try { astar_search(g_, start, boost::astar_heuristic<graph_t, int>(), boost::predecessor_map(&p[0]).distance_map(&d[0]).visitor(astar_goal_visitor<vertex>(end))); } catch (found_goal fg) { for (vertex v = end_node;; v = p[v]) { path->push_front(v); if (p[v] == v) break; } std::cout << "shortes path is "; std::list<int>::iterator spi = path->begin(); std::cout << (start_node / 9) << ":" << (start_node % 9); for (++spi; spi != path->end(); ++spi) std::cout << " -> " << (nodes_[*spi] / 9) << ":" << (nodes_[*spi] % 9); std::cout << std::endl << "Total travel time: " << d[end_node] << std::endl; return true; } return false; } bool BoardGraph::is_neighbours(int node1, int node2) const { return (edges_.count(edge(node1, node2)) > 0); } void BoardGraph::filter_edges(int node1, int node2) { edge_descriptor ed; bool b; boost::tie(ed, b) = boost::edge(node1, node2, g_); if (b) { fe_.add_edge(ed); } boost::tie(ed, b) = boost::edge(node2, node1, g_); if (b) { fe_.add_edge(ed); } } void BoardGraph::reset_filters() { fe_.clear(); } bool BoardGraph::is_path_exists(int start_node, int end_node) const { boost::filtered_graph<graph_t, FilterEdges> fg(g_, fe_); std::vector<boost::filtered_graph<graph_t, FilterEdges>::vertex_descriptor> p(boost::num_vertices(fg)); std::vector<int> d(boost::num_vertices(fg)); boost::filtered_graph<graph_t, FilterEdges>::vertex_descriptor start = boost::vertex(start_node, g_); boost::filtered_graph<graph_t, FilterEdges>::vertex_descriptor end = boost::vertex(end_node, g_); try { astar_search(fg, start, boost::astar_heuristic<boost::filtered_graph<graph_t, FilterEdges>, int>(), boost::predecessor_map(&p[0]).distance_map(&d[0]).visitor(astar_goal_visitor<vertex>(end))); } catch (found_goal fg) { return true; } return false; } } /* namespace Quoridor */ <commit_msg>Remove debugging couts from BoardGraph.<commit_after>#include "board_graph.hpp" namespace Quoridor { FilterEdges::FilterEdges() : edges_() { } FilterEdges::~FilterEdges() { } void FilterEdges::add_edge(const edge_descriptor &e) { edges_.insert(e); } void FilterEdges::clear() { edges_.clear(); } template <typename EdgeDesc> bool FilterEdges::operator()(const EdgeDesc &e) const { return edges_.find(e) == edges_.end(); } BoardGraph::BoardGraph() : g_(), nodes_(), edges_(), fe_() { } BoardGraph::~BoardGraph() { } int BoardGraph::set_size(int row_num, int col_num) { if ((row_num <= 0) || (col_num <= 0)) { return -1; } g_ = graph_t(row_num * col_num); for (int i = 0; i < row_num * col_num; ++i) { nodes_.push_back(i); } int nidx; for (int i = 0; i < row_num; ++i) { for (int j = 0; j < col_num; ++j) { if (j != 0) { nidx = i * col_num + j - 1; edges_.insert(edge(nodes_[i * col_num + j], nodes_[nidx])); } if (j != col_num - 1) { nidx = i * col_num + j + 1; edges_.insert(edge(nodes_[i * col_num + j], nodes_[nidx])); } if (i != 0) { nidx = (i - 1) * col_num + j; edges_.insert(edge(nodes_[i * col_num + j], nodes_[nidx])); } if (i != row_num - 1) { nidx = (i + 1) * col_num + j; edges_.insert(edge(nodes_[i * col_num + j], nodes_[nidx])); } } } WeightMap weightmap = boost::get(boost::edge_weight, g_); edge_descriptor e; bool b; for (auto &it : edges_) { boost::tie(e, b) = boost::add_edge(it.first, it.second, g_); weightmap[e] = 1; } return 0; } void BoardGraph::remove_edges(int node1, int node2) { edge_descriptor ed; bool b; boost::tie(ed, b) = boost::edge(node1, node2, g_); if (b) { g_.remove_edge(ed); } boost::tie(ed, b) = boost::edge(node2, node1, g_); if (b) { g_.remove_edge(ed); } edges_.erase(edge(node1, node2)); edges_.erase(edge(node2, node1)); } bool BoardGraph::find_path(int start_node, int end_node, std::list<int> *path) const { std::vector<vertex> p(boost::num_vertices(g_)); std::vector<int> d(boost::num_vertices(g_)); vertex start = boost::vertex(start_node, g_); vertex end = boost::vertex(end_node, g_); try { astar_search(g_, start, boost::astar_heuristic<graph_t, int>(), boost::predecessor_map(&p[0]).distance_map(&d[0]).visitor(astar_goal_visitor<vertex>(end))); } catch (found_goal fg) { for (vertex v = end_node;; v = p[v]) { path->push_front(v); if (p[v] == v) break; } return true; } return false; } bool BoardGraph::is_neighbours(int node1, int node2) const { return (edges_.count(edge(node1, node2)) > 0); } void BoardGraph::filter_edges(int node1, int node2) { edge_descriptor ed; bool b; boost::tie(ed, b) = boost::edge(node1, node2, g_); if (b) { fe_.add_edge(ed); } boost::tie(ed, b) = boost::edge(node2, node1, g_); if (b) { fe_.add_edge(ed); } } void BoardGraph::reset_filters() { fe_.clear(); } bool BoardGraph::is_path_exists(int start_node, int end_node) const { boost::filtered_graph<graph_t, FilterEdges> fg(g_, fe_); std::vector<boost::filtered_graph<graph_t, FilterEdges>::vertex_descriptor> p(boost::num_vertices(fg)); std::vector<int> d(boost::num_vertices(fg)); boost::filtered_graph<graph_t, FilterEdges>::vertex_descriptor start = boost::vertex(start_node, g_); boost::filtered_graph<graph_t, FilterEdges>::vertex_descriptor end = boost::vertex(end_node, g_); try { astar_search(fg, start, boost::astar_heuristic<boost::filtered_graph<graph_t, FilterEdges>, int>(), boost::predecessor_map(&p[0]).distance_map(&d[0]).visitor(astar_goal_visitor<vertex>(end))); } catch (found_goal fg) { return true; } return false; } } /* namespace Quoridor */ <|endoftext|>