hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
b6da25115e8d06f7f7a19cba441ac79b2c914308
126,976
cpp
C++
src/js/wasm/WasmIonCompile.cpp
fengjixuchui/blazefox
d5c732ac7305a79fe20704c2d134c130f14eca83
[ "MIT" ]
149
2018-12-23T09:08:00.000Z
2022-02-02T09:18:38.000Z
src/js/wasm/WasmIonCompile.cpp
fengjixuchui/blazefox
d5c732ac7305a79fe20704c2d134c130f14eca83
[ "MIT" ]
null
null
null
src/js/wasm/WasmIonCompile.cpp
fengjixuchui/blazefox
d5c732ac7305a79fe20704c2d134c130f14eca83
[ "MIT" ]
56
2018-12-23T18:11:40.000Z
2021-11-30T13:18:17.000Z
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * vim: set ts=8 sts=4 et sw=4 tw=99: * * Copyright 2015 Mozilla Foundation * * 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 "wasm/WasmIonCompile.h" #include "mozilla/MathAlgorithms.h" #include "jit/CodeGenerator.h" #include "wasm/WasmBaselineCompile.h" #include "wasm/WasmGenerator.h" #include "wasm/WasmOpIter.h" #include "wasm/WasmSignalHandlers.h" #include "wasm/WasmValidate.h" using namespace js; using namespace js::jit; using namespace js::wasm; using mozilla::IsPowerOfTwo; using mozilla::Maybe; using mozilla::Nothing; using mozilla::Some; namespace { typedef Vector<MBasicBlock*, 8, SystemAllocPolicy> BlockVector; struct IonCompilePolicy { // We store SSA definitions in the value stack. typedef MDefinition* Value; // We store loop headers and then/else blocks in the control flow stack. typedef MBasicBlock* ControlItem; }; typedef OpIter<IonCompilePolicy> IonOpIter; class FunctionCompiler; // CallCompileState describes a call that is being compiled. Due to expression // nesting, multiple calls can be in the middle of compilation at the same time // and these are tracked in a stack by FunctionCompiler. class CallCompileState { // The line or bytecode of the call. uint32_t lineOrBytecode_; // A generator object that is passed each argument as it is compiled. ABIArgGenerator abi_; // The maximum number of bytes used by "child" calls, i.e., calls that occur // while evaluating the arguments of the call represented by this // CallCompileState. uint32_t maxChildStackBytes_; // Set by FunctionCompiler::finishCall(), tells the MWasmCall by how // much to bump the stack pointer before making the call. See // FunctionCompiler::startCall() comment below. uint32_t spIncrement_; // Accumulates the register arguments while compiling arguments. MWasmCall::Args regArgs_; // Reserved argument for passing Instance* to builtin instance method calls. ABIArg instanceArg_; // Accumulates the stack arguments while compiling arguments. This is only // necessary to track when childClobbers_ is true so that the stack offsets // can be updated. Vector<MWasmStackArg*, 0, SystemAllocPolicy> stackArgs_; // Set by child calls (i.e., calls that execute while evaluating a parent's // operands) to indicate that the child and parent call cannot reuse the // same stack space -- the parent must store its stack arguments below the // child's and increment sp when performing its call. bool childClobbers_; // Only FunctionCompiler should be directly manipulating CallCompileState. friend class FunctionCompiler; public: CallCompileState(FunctionCompiler& f, uint32_t lineOrBytecode) : lineOrBytecode_(lineOrBytecode), maxChildStackBytes_(0), spIncrement_(0), childClobbers_(false) { } }; // Encapsulates the compilation of a single function in an asm.js module. The // function compiler handles the creation and final backend compilation of the // MIR graph. class FunctionCompiler { struct ControlFlowPatch { MControlInstruction* ins; uint32_t index; ControlFlowPatch(MControlInstruction* ins, uint32_t index) : ins(ins), index(index) {} }; typedef Vector<ControlFlowPatch, 0, SystemAllocPolicy> ControlFlowPatchVector; typedef Vector<ControlFlowPatchVector, 0, SystemAllocPolicy> ControlFlowPatchsVector; typedef Vector<CallCompileState*, 0, SystemAllocPolicy> CallCompileStateVector; const ModuleEnvironment& env_; IonOpIter iter_; const FuncCompileInput& func_; const ValTypeVector& locals_; size_t lastReadCallSite_; TempAllocator& alloc_; MIRGraph& graph_; const CompileInfo& info_; MIRGenerator& mirGen_; MBasicBlock* curBlock_; CallCompileStateVector callStack_; uint32_t maxStackArgBytes_; uint32_t loopDepth_; uint32_t blockDepth_; ControlFlowPatchsVector blockPatches_; // TLS pointer argument to the current function. MWasmParameter* tlsPointer_; public: FunctionCompiler(const ModuleEnvironment& env, Decoder& decoder, ExclusiveDeferredValidationState& dvs, const FuncCompileInput& func, const ValTypeVector& locals, MIRGenerator& mirGen) : env_(env), iter_(env, decoder, dvs), func_(func), locals_(locals), lastReadCallSite_(0), alloc_(mirGen.alloc()), graph_(mirGen.graph()), info_(mirGen.info()), mirGen_(mirGen), curBlock_(nullptr), maxStackArgBytes_(0), loopDepth_(0), blockDepth_(0), tlsPointer_(nullptr) {} const ModuleEnvironment& env() const { return env_; } IonOpIter& iter() { return iter_; } TempAllocator& alloc() const { return alloc_; } const FuncType& funcType() const { return *env_.funcTypes[func_.index]; } BytecodeOffset bytecodeOffset() const { return iter_.bytecodeOffset(); } BytecodeOffset bytecodeIfNotAsmJS() const { return env_.isAsmJS() ? BytecodeOffset() : iter_.bytecodeOffset(); } bool init() { // Prepare the entry block for MIR generation: const ValTypeVector& args = funcType().args(); if (!mirGen_.ensureBallast()) { return false; } if (!newBlock(/* prev */ nullptr, &curBlock_)) { return false; } for (ABIArgIter<ValTypeVector> i(args); !i.done(); i++) { MWasmParameter* ins = MWasmParameter::New(alloc(), *i, i.mirType()); curBlock_->add(ins); curBlock_->initSlot(info().localSlot(i.index()), ins); if (!mirGen_.ensureBallast()) { return false; } } // Set up a parameter that receives the hidden TLS pointer argument. tlsPointer_ = MWasmParameter::New(alloc(), ABIArg(WasmTlsReg), MIRType::Pointer); curBlock_->add(tlsPointer_); if (!mirGen_.ensureBallast()) { return false; } for (size_t i = args.length(); i < locals_.length(); i++) { MInstruction* ins = nullptr; switch (locals_[i].code()) { case ValType::I32: ins = MConstant::New(alloc(), Int32Value(0), MIRType::Int32); break; case ValType::I64: ins = MConstant::NewInt64(alloc(), 0); break; case ValType::F32: ins = MConstant::New(alloc(), Float32Value(0.f), MIRType::Float32); break; case ValType::F64: ins = MConstant::New(alloc(), DoubleValue(0.0), MIRType::Double); break; case ValType::Ref: case ValType::AnyRef: MOZ_CRASH("ion support for ref/anyref value NYI"); break; } curBlock_->add(ins); curBlock_->initSlot(info().localSlot(i), ins); if (!mirGen_.ensureBallast()) { return false; } } return true; } void finish() { mirGen().initWasmMaxStackArgBytes(maxStackArgBytes_); MOZ_ASSERT(callStack_.empty()); MOZ_ASSERT(loopDepth_ == 0); MOZ_ASSERT(blockDepth_ == 0); #ifdef DEBUG for (ControlFlowPatchVector& patches : blockPatches_) { MOZ_ASSERT(patches.empty()); } #endif MOZ_ASSERT(inDeadCode()); MOZ_ASSERT(done(), "all bytes must be consumed"); MOZ_ASSERT(func_.callSiteLineNums.length() == lastReadCallSite_); } /************************* Read-only interface (after local scope setup) */ MIRGenerator& mirGen() const { return mirGen_; } MIRGraph& mirGraph() const { return graph_; } const CompileInfo& info() const { return info_; } MDefinition* getLocalDef(unsigned slot) { if (inDeadCode()) { return nullptr; } return curBlock_->getSlot(info().localSlot(slot)); } const ValTypeVector& locals() const { return locals_; } /***************************** Code generation (after local scope setup) */ MDefinition* constant(const Value& v, MIRType type) { if (inDeadCode()) { return nullptr; } MConstant* constant = MConstant::New(alloc(), v, type); curBlock_->add(constant); return constant; } MDefinition* constant(float f) { if (inDeadCode()) { return nullptr; } auto* cst = MWasmFloatConstant::NewFloat32(alloc(), f); curBlock_->add(cst); return cst; } MDefinition* constant(double d) { if (inDeadCode()) { return nullptr; } auto* cst = MWasmFloatConstant::NewDouble(alloc(), d); curBlock_->add(cst); return cst; } MDefinition* constant(int64_t i) { if (inDeadCode()) { return nullptr; } MConstant* constant = MConstant::NewInt64(alloc(), i); curBlock_->add(constant); return constant; } template <class T> MDefinition* unary(MDefinition* op) { if (inDeadCode()) { return nullptr; } T* ins = T::New(alloc(), op); curBlock_->add(ins); return ins; } template <class T> MDefinition* unary(MDefinition* op, MIRType type) { if (inDeadCode()) { return nullptr; } T* ins = T::New(alloc(), op, type); curBlock_->add(ins); return ins; } template <class T> MDefinition* binary(MDefinition* lhs, MDefinition* rhs) { if (inDeadCode()) { return nullptr; } T* ins = T::New(alloc(), lhs, rhs); curBlock_->add(ins); return ins; } template <class T> MDefinition* binary(MDefinition* lhs, MDefinition* rhs, MIRType type) { if (inDeadCode()) { return nullptr; } T* ins = T::New(alloc(), lhs, rhs, type); curBlock_->add(ins); return ins; } bool mustPreserveNaN(MIRType type) { return IsFloatingPointType(type) && !env().isAsmJS(); } MDefinition* sub(MDefinition* lhs, MDefinition* rhs, MIRType type) { if (inDeadCode()) { return nullptr; } // wasm can't fold x - 0.0 because of NaN with custom payloads. MSub* ins = MSub::New(alloc(), lhs, rhs, type, mustPreserveNaN(type)); curBlock_->add(ins); return ins; } MDefinition* nearbyInt(MDefinition* input, RoundingMode roundingMode) { if (inDeadCode()) { return nullptr; } auto* ins = MNearbyInt::New(alloc(), input, input->type(), roundingMode); curBlock_->add(ins); return ins; } MDefinition* minMax(MDefinition* lhs, MDefinition* rhs, MIRType type, bool isMax) { if (inDeadCode()) { return nullptr; } if (mustPreserveNaN(type)) { // Convert signaling NaN to quiet NaNs. MDefinition* zero = constant(DoubleValue(0.0), type); lhs = sub(lhs, zero, type); rhs = sub(rhs, zero, type); } MMinMax* ins = MMinMax::NewWasm(alloc(), lhs, rhs, type, isMax); curBlock_->add(ins); return ins; } MDefinition* mul(MDefinition* lhs, MDefinition* rhs, MIRType type, MMul::Mode mode) { if (inDeadCode()) { return nullptr; } // wasm can't fold x * 1.0 because of NaN with custom payloads. auto* ins = MMul::NewWasm(alloc(), lhs, rhs, type, mode, mustPreserveNaN(type)); curBlock_->add(ins); return ins; } MDefinition* div(MDefinition* lhs, MDefinition* rhs, MIRType type, bool unsignd) { if (inDeadCode()) { return nullptr; } bool trapOnError = !env().isAsmJS(); if (!unsignd && type == MIRType::Int32) { // Enforce the signedness of the operation by coercing the operands // to signed. Otherwise, operands that "look" unsigned to Ion but // are not unsigned to Baldr (eg, unsigned right shifts) may lead to // the operation being executed unsigned. Applies to mod() as well. // // Do this for Int32 only since Int64 is not subject to the same // issues. // // Note the offsets passed to MTruncateToInt32 are wrong here, but // it doesn't matter: they're not codegen'd to calls since inputs // already are int32. auto* lhs2 = MTruncateToInt32::New(alloc(), lhs); curBlock_->add(lhs2); lhs = lhs2; auto* rhs2 = MTruncateToInt32::New(alloc(), rhs); curBlock_->add(rhs2); rhs = rhs2; } auto* ins = MDiv::New(alloc(), lhs, rhs, type, unsignd, trapOnError, bytecodeOffset(), mustPreserveNaN(type)); curBlock_->add(ins); return ins; } MDefinition* mod(MDefinition* lhs, MDefinition* rhs, MIRType type, bool unsignd) { if (inDeadCode()) { return nullptr; } bool trapOnError = !env().isAsmJS(); if (!unsignd && type == MIRType::Int32) { // See block comment in div(). auto* lhs2 = MTruncateToInt32::New(alloc(), lhs); curBlock_->add(lhs2); lhs = lhs2; auto* rhs2 = MTruncateToInt32::New(alloc(), rhs); curBlock_->add(rhs2); rhs = rhs2; } auto* ins = MMod::New(alloc(), lhs, rhs, type, unsignd, trapOnError, bytecodeOffset()); curBlock_->add(ins); return ins; } MDefinition* bitnot(MDefinition* op) { if (inDeadCode()) { return nullptr; } auto* ins = MBitNot::NewInt32(alloc(), op); curBlock_->add(ins); return ins; } MDefinition* select(MDefinition* trueExpr, MDefinition* falseExpr, MDefinition* condExpr) { if (inDeadCode()) { return nullptr; } auto* ins = MWasmSelect::New(alloc(), trueExpr, falseExpr, condExpr); curBlock_->add(ins); return ins; } MDefinition* extendI32(MDefinition* op, bool isUnsigned) { if (inDeadCode()) { return nullptr; } auto* ins = MExtendInt32ToInt64::New(alloc(), op, isUnsigned); curBlock_->add(ins); return ins; } MDefinition* signExtend(MDefinition* op, uint32_t srcSize, uint32_t targetSize) { if (inDeadCode()) { return nullptr; } MInstruction* ins; switch (targetSize) { case 4: { MSignExtendInt32::Mode mode; switch (srcSize) { case 1: mode = MSignExtendInt32::Byte; break; case 2: mode = MSignExtendInt32::Half; break; default: MOZ_CRASH("Bad sign extension"); } ins = MSignExtendInt32::New(alloc(), op, mode); break; } case 8: { MSignExtendInt64::Mode mode; switch (srcSize) { case 1: mode = MSignExtendInt64::Byte; break; case 2: mode = MSignExtendInt64::Half; break; case 4: mode = MSignExtendInt64::Word; break; default: MOZ_CRASH("Bad sign extension"); } ins = MSignExtendInt64::New(alloc(), op, mode); break; } default: { MOZ_CRASH("Bad sign extension"); } } curBlock_->add(ins); return ins; } MDefinition* convertI64ToFloatingPoint(MDefinition* op, MIRType type, bool isUnsigned) { if (inDeadCode()) { return nullptr; } auto* ins = MInt64ToFloatingPoint::New(alloc(), op, type, bytecodeOffset(), isUnsigned); curBlock_->add(ins); return ins; } MDefinition* rotate(MDefinition* input, MDefinition* count, MIRType type, bool left) { if (inDeadCode()) { return nullptr; } auto* ins = MRotate::New(alloc(), input, count, type, left); curBlock_->add(ins); return ins; } template <class T> MDefinition* truncate(MDefinition* op, TruncFlags flags) { if (inDeadCode()) { return nullptr; } auto* ins = T::New(alloc(), op, flags, bytecodeOffset()); curBlock_->add(ins); return ins; } MDefinition* compare(MDefinition* lhs, MDefinition* rhs, JSOp op, MCompare::CompareType type) { if (inDeadCode()) { return nullptr; } auto* ins = MCompare::New(alloc(), lhs, rhs, op, type); curBlock_->add(ins); return ins; } void assign(unsigned slot, MDefinition* def) { if (inDeadCode()) { return; } curBlock_->setSlot(info().localSlot(slot), def); } private: MWasmLoadTls* maybeLoadMemoryBase() { MWasmLoadTls* load = nullptr; #ifdef JS_CODEGEN_X86 AliasSet aliases = env_.maxMemoryLength.isSome() ? AliasSet::None() : AliasSet::Load(AliasSet::WasmHeapMeta); load = MWasmLoadTls::New(alloc(), tlsPointer_, offsetof(wasm::TlsData, memoryBase), MIRType::Pointer, aliases); curBlock_->add(load); #endif return load; } MWasmLoadTls* maybeLoadBoundsCheckLimit() { #ifdef WASM_HUGE_MEMORY if (!env_.isAsmJS()) { return nullptr; } #endif AliasSet aliases = env_.maxMemoryLength.isSome() ? AliasSet::None() : AliasSet::Load(AliasSet::WasmHeapMeta); auto load = MWasmLoadTls::New(alloc(), tlsPointer_, offsetof(wasm::TlsData, boundsCheckLimit), MIRType::Int32, aliases); curBlock_->add(load); return load; } // Only sets *mustAdd if it also returns true. bool needAlignmentCheck(MemoryAccessDesc* access, MDefinition* base, bool* mustAdd) { MOZ_ASSERT(!*mustAdd); // asm.js accesses are always aligned and need no checks. if (env_.isAsmJS() || !access->isAtomic()) { return false; } if (base->isConstant()) { int32_t ptr = base->toConstant()->toInt32(); // OK to wrap around the address computation here. if (((ptr + access->offset()) & (access->byteSize() - 1)) == 0) { return false; } } *mustAdd = (access->offset() & (access->byteSize() - 1)) != 0; return true; } void checkOffsetAndAlignmentAndBounds(MemoryAccessDesc* access, MDefinition** base) { MOZ_ASSERT(!inDeadCode()); // Fold a constant base into the offset (so the base is 0 in which case // the codegen is optimized), if it doesn't wrap or trigger an // MWasmAddOffset. if ((*base)->isConstant()) { uint32_t basePtr = (*base)->toConstant()->toInt32(); uint32_t offset = access->offset(); static_assert(OffsetGuardLimit < UINT32_MAX, "checking for overflow against OffsetGuardLimit is enough."); if (offset < OffsetGuardLimit && basePtr < OffsetGuardLimit - offset) { auto* ins = MConstant::New(alloc(), Int32Value(0), MIRType::Int32); curBlock_->add(ins); *base = ins; access->setOffset(access->offset() + basePtr); } } bool mustAdd = false; bool alignmentCheck = needAlignmentCheck(access, *base, &mustAdd); // If the offset is bigger than the guard region, a separate instruction // is necessary to add the offset to the base and check for overflow. // // Also add the offset if we have a Wasm atomic access that needs // alignment checking and the offset affects alignment. if (access->offset() >= OffsetGuardLimit || mustAdd || !JitOptions.wasmFoldOffsets) { *base = computeEffectiveAddress(*base, access); } if (alignmentCheck) { curBlock_->add(MWasmAlignmentCheck::New(alloc(), *base, access->byteSize(), bytecodeOffset())); } MWasmLoadTls* boundsCheckLimit = maybeLoadBoundsCheckLimit(); if (boundsCheckLimit) { auto* ins = MWasmBoundsCheck::New(alloc(), *base, boundsCheckLimit, bytecodeOffset()); curBlock_->add(ins); if (JitOptions.spectreIndexMasking) { *base = ins; } } } bool isSmallerAccessForI64(ValType result, const MemoryAccessDesc* access) { if (result == ValType::I64 && access->byteSize() <= 4) { // These smaller accesses should all be zero-extending. MOZ_ASSERT(!isSignedIntType(access->type())); return true; } return false; } public: MDefinition* computeEffectiveAddress(MDefinition* base, MemoryAccessDesc* access) { if (inDeadCode()) { return nullptr; } if (!access->offset()) { return base; } auto* ins = MWasmAddOffset::New(alloc(), base, access->offset(), bytecodeOffset()); curBlock_->add(ins); access->clearOffset(); return ins; } bool checkI32NegativeMeansFailedResult(MDefinition* value) { if (inDeadCode()) { return true; } auto* zero = constant(Int32Value(0), MIRType::Int32); auto* cond = compare(value, zero, JSOP_LT, MCompare::Compare_Int32); MBasicBlock* failBlock; if (!newBlock(curBlock_, &failBlock)) { return false; } MBasicBlock* okBlock; if (!newBlock(curBlock_, &okBlock)) { return false; } curBlock_->end(MTest::New(alloc(), cond, failBlock, okBlock)); failBlock->end(MWasmTrap::New(alloc(), wasm::Trap::ThrowReported, bytecodeOffset())); curBlock_ = okBlock; return true; } MDefinition* load(MDefinition* base, MemoryAccessDesc* access, ValType result) { if (inDeadCode()) { return nullptr; } MWasmLoadTls* memoryBase = maybeLoadMemoryBase(); MInstruction* load = nullptr; if (env_.isAsmJS()) { MOZ_ASSERT(access->offset() == 0); MWasmLoadTls* boundsCheckLimit = maybeLoadBoundsCheckLimit(); load = MAsmJSLoadHeap::New(alloc(), memoryBase, base, boundsCheckLimit, access->type()); } else { checkOffsetAndAlignmentAndBounds(access, &base); load = MWasmLoad::New(alloc(), memoryBase, base, *access, ToMIRType(result)); } if (!load) { return nullptr; } curBlock_->add(load); return load; } void store(MDefinition* base, MemoryAccessDesc* access, MDefinition* v) { if (inDeadCode()) { return; } MWasmLoadTls* memoryBase = maybeLoadMemoryBase(); MInstruction* store = nullptr; if (env_.isAsmJS()) { MOZ_ASSERT(access->offset() == 0); MWasmLoadTls* boundsCheckLimit = maybeLoadBoundsCheckLimit(); store = MAsmJSStoreHeap::New(alloc(), memoryBase, base, boundsCheckLimit, access->type(), v); } else { checkOffsetAndAlignmentAndBounds(access, &base); store = MWasmStore::New(alloc(), memoryBase, base, *access, v); } if (!store) { return; } curBlock_->add(store); } MDefinition* atomicCompareExchangeHeap(MDefinition* base, MemoryAccessDesc* access, ValType result, MDefinition* oldv, MDefinition* newv) { if (inDeadCode()) { return nullptr; } checkOffsetAndAlignmentAndBounds(access, &base); if (isSmallerAccessForI64(result, access)) { auto* cvtOldv = MWrapInt64ToInt32::New(alloc(), oldv, /*bottomHalf=*/ true); curBlock_->add(cvtOldv); oldv = cvtOldv; auto* cvtNewv = MWrapInt64ToInt32::New(alloc(), newv, /*bottomHalf=*/ true); curBlock_->add(cvtNewv); newv = cvtNewv; } MWasmLoadTls* memoryBase = maybeLoadMemoryBase(); MInstruction* cas = MWasmCompareExchangeHeap::New(alloc(), bytecodeOffset(), memoryBase, base, *access, oldv, newv, tlsPointer_); if (!cas) { return nullptr; } curBlock_->add(cas); if (isSmallerAccessForI64(result, access)) { cas = MExtendInt32ToInt64::New(alloc(), cas, true); curBlock_->add(cas); } return cas; } MDefinition* atomicExchangeHeap(MDefinition* base, MemoryAccessDesc* access, ValType result, MDefinition* value) { if (inDeadCode()) { return nullptr; } checkOffsetAndAlignmentAndBounds(access, &base); if (isSmallerAccessForI64(result, access)) { auto* cvtValue = MWrapInt64ToInt32::New(alloc(), value, /*bottomHalf=*/ true); curBlock_->add(cvtValue); value = cvtValue; } MWasmLoadTls* memoryBase = maybeLoadMemoryBase(); MInstruction* xchg = MWasmAtomicExchangeHeap::New(alloc(), bytecodeOffset(), memoryBase, base, *access, value, tlsPointer_); if (!xchg) { return nullptr; } curBlock_->add(xchg); if (isSmallerAccessForI64(result, access)) { xchg = MExtendInt32ToInt64::New(alloc(), xchg, true); curBlock_->add(xchg); } return xchg; } MDefinition* atomicBinopHeap(AtomicOp op, MDefinition* base, MemoryAccessDesc* access, ValType result, MDefinition* value) { if (inDeadCode()) { return nullptr; } checkOffsetAndAlignmentAndBounds(access, &base); if (isSmallerAccessForI64(result, access)) { auto* cvtValue = MWrapInt64ToInt32::New(alloc(), value, /*bottomHalf=*/ true); curBlock_->add(cvtValue); value = cvtValue; } MWasmLoadTls* memoryBase = maybeLoadMemoryBase(); MInstruction* binop = MWasmAtomicBinopHeap::New(alloc(), bytecodeOffset(), op, memoryBase, base, *access, value, tlsPointer_); if (!binop) { return nullptr; } curBlock_->add(binop); if (isSmallerAccessForI64(result, access)) { binop = MExtendInt32ToInt64::New(alloc(), binop, true); curBlock_->add(binop); } return binop; } MDefinition* loadGlobalVar(unsigned globalDataOffset, bool isConst, bool isIndirect, MIRType type) { if (inDeadCode()) { return nullptr; } MInstruction* load; if (isIndirect) { // Pull a pointer to the value out of TlsData::globalArea, then // load from that pointer. Note that the pointer is immutable // even though the value it points at may change, hence the use of // |true| for the first node's |isConst| value, irrespective of // the |isConst| formal parameter to this method. The latter // applies to the denoted value as a whole. auto* cellPtr = MWasmLoadGlobalVar::New(alloc(), MIRType::Pointer, globalDataOffset, /*isConst=*/true, tlsPointer_); curBlock_->add(cellPtr); load = MWasmLoadGlobalCell::New(alloc(), type, cellPtr); } else { // Pull the value directly out of TlsData::globalArea. load = MWasmLoadGlobalVar::New(alloc(), type, globalDataOffset, isConst, tlsPointer_); } curBlock_->add(load); return load; } void storeGlobalVar(uint32_t globalDataOffset, bool isIndirect, MDefinition* v) { if (inDeadCode()) { return; } MInstruction* store; if (isIndirect) { // Pull a pointer to the value out of TlsData::globalArea, then // store through that pointer. auto* cellPtr = MWasmLoadGlobalVar::New(alloc(), MIRType::Pointer, globalDataOffset, /*isConst=*/true, tlsPointer_); curBlock_->add(cellPtr); store = MWasmStoreGlobalCell::New(alloc(), v, cellPtr); } else { // Store the value directly in TlsData::globalArea. store = MWasmStoreGlobalVar::New(alloc(), globalDataOffset, v, tlsPointer_); } curBlock_->add(store); } void addInterruptCheck() { if (inDeadCode()) { return; } curBlock_->add(MWasmInterruptCheck::New(alloc(), tlsPointer_, bytecodeOffset())); } /***************************************************************** Calls */ // The IonMonkey backend maintains a single stack offset (from the stack // pointer to the base of the frame) by adding the total amount of spill // space required plus the maximum stack required for argument passing. // Since we do not use IonMonkey's MPrepareCall/MPassArg/MCall, we must // manually accumulate, for the entire function, the maximum required stack // space for argument passing. (This is passed to the CodeGenerator via // MIRGenerator::maxWasmStackArgBytes.) Naively, this would just be the // maximum of the stack space required for each individual call (as // determined by the call ABI). However, as an optimization, arguments are // stored to the stack immediately after evaluation (to decrease live // ranges and reduce spilling). This introduces the complexity that, // between evaluating an argument and making the call, another argument // evaluation could perform a call that also needs to store to the stack. // When this occurs childClobbers_ = true and the parent expression's // arguments are stored above the maximum depth clobbered by a child // expression. bool startCall(CallCompileState* call) { // Always push calls to maintain the invariant that if we're inDeadCode // in finishCall, we have something to pop. return callStack_.append(call); } bool passInstance(CallCompileState* args) { if (inDeadCode()) { return true; } // Should only pass an instance once. MOZ_ASSERT(args->instanceArg_ == ABIArg()); args->instanceArg_ = args->abi_.next(MIRType::Pointer); return true; } bool passArg(MDefinition* argDef, ValType type, CallCompileState* call) { if (inDeadCode()) { return true; } ABIArg arg = call->abi_.next(ToMIRType(type)); switch (arg.kind()) { #ifdef JS_CODEGEN_REGISTER_PAIR case ABIArg::GPR_PAIR: { auto mirLow = MWrapInt64ToInt32::New(alloc(), argDef, /* bottomHalf = */ true); curBlock_->add(mirLow); auto mirHigh = MWrapInt64ToInt32::New(alloc(), argDef, /* bottomHalf = */ false); curBlock_->add(mirHigh); return call->regArgs_.append(MWasmCall::Arg(AnyRegister(arg.gpr64().low), mirLow)) && call->regArgs_.append(MWasmCall::Arg(AnyRegister(arg.gpr64().high), mirHigh)); } #endif case ABIArg::GPR: case ABIArg::FPU: return call->regArgs_.append(MWasmCall::Arg(arg.reg(), argDef)); case ABIArg::Stack: { auto* mir = MWasmStackArg::New(alloc(), arg.offsetFromArgBase(), argDef); curBlock_->add(mir); return call->stackArgs_.append(mir); } case ABIArg::Uninitialized: MOZ_ASSERT_UNREACHABLE("Uninitialized ABIArg kind"); } MOZ_CRASH("Unknown ABIArg kind."); } void propagateMaxStackArgBytes(uint32_t stackBytes) { if (callStack_.empty()) { // Outermost call maxStackArgBytes_ = Max(maxStackArgBytes_, stackBytes); return; } // Non-outermost call CallCompileState* outer = callStack_.back(); outer->maxChildStackBytes_ = Max(outer->maxChildStackBytes_, stackBytes); if (stackBytes && !outer->stackArgs_.empty()) { outer->childClobbers_ = true; } } bool finishCall(CallCompileState* call) { MOZ_ALWAYS_TRUE(callStack_.popCopy() == call); if (inDeadCode()) { propagateMaxStackArgBytes(call->maxChildStackBytes_); return true; } if (!call->regArgs_.append(MWasmCall::Arg(AnyRegister(WasmTlsReg), tlsPointer_))) { return false; } uint32_t stackBytes = call->abi_.stackBytesConsumedSoFar(); if (call->childClobbers_) { call->spIncrement_ = AlignBytes(call->maxChildStackBytes_, WasmStackAlignment); for (MWasmStackArg* stackArg : call->stackArgs_) { stackArg->incrementOffset(call->spIncrement_); } // If instanceArg_ is not initialized then instanceArg_.kind() != ABIArg::Stack if (call->instanceArg_.kind() == ABIArg::Stack) { call->instanceArg_ = ABIArg(call->instanceArg_.offsetFromArgBase() + call->spIncrement_); } stackBytes += call->spIncrement_; } else { call->spIncrement_ = 0; stackBytes = Max(stackBytes, call->maxChildStackBytes_); } propagateMaxStackArgBytes(stackBytes); return true; } bool callDirect(const FuncType& funcType, uint32_t funcIndex, const CallCompileState& call, MDefinition** def) { if (inDeadCode()) { *def = nullptr; return true; } CallSiteDesc desc(call.lineOrBytecode_, CallSiteDesc::Func); MIRType ret = ToMIRType(funcType.ret()); auto callee = CalleeDesc::function(funcIndex); auto* ins = MWasmCall::New(alloc(), desc, callee, call.regArgs_, ret, call.spIncrement_); if (!ins) { return false; } curBlock_->add(ins); *def = ins; return true; } bool callIndirect(uint32_t funcTypeIndex, MDefinition* index, const CallCompileState& call, MDefinition** def) { if (inDeadCode()) { *def = nullptr; return true; } const FuncTypeWithId& funcType = env_.types[funcTypeIndex].funcType(); CalleeDesc callee; if (env_.isAsmJS()) { MOZ_ASSERT(funcType.id.kind() == FuncTypeIdDescKind::None); const TableDesc& table = env_.tables[env_.asmJSSigToTableIndex[funcTypeIndex]]; MOZ_ASSERT(IsPowerOfTwo(table.limits.initial)); MOZ_ASSERT(!table.external); MConstant* mask = MConstant::New(alloc(), Int32Value(table.limits.initial - 1)); curBlock_->add(mask); MBitAnd* maskedIndex = MBitAnd::New(alloc(), index, mask, MIRType::Int32); curBlock_->add(maskedIndex); index = maskedIndex; callee = CalleeDesc::asmJSTable(table); } else { MOZ_ASSERT(funcType.id.kind() != FuncTypeIdDescKind::None); MOZ_ASSERT(env_.tables.length() == 1); const TableDesc& table = env_.tables[0]; callee = CalleeDesc::wasmTable(table, funcType.id); } CallSiteDesc desc(call.lineOrBytecode_, CallSiteDesc::Dynamic); auto* ins = MWasmCall::New(alloc(), desc, callee, call.regArgs_, ToMIRType(funcType.ret()), call.spIncrement_, index); if (!ins) { return false; } curBlock_->add(ins); *def = ins; return true; } bool callImport(unsigned globalDataOffset, const CallCompileState& call, ExprType ret, MDefinition** def) { if (inDeadCode()) { *def = nullptr; return true; } CallSiteDesc desc(call.lineOrBytecode_, CallSiteDesc::Dynamic); auto callee = CalleeDesc::import(globalDataOffset); auto* ins = MWasmCall::New(alloc(), desc, callee, call.regArgs_, ToMIRType(ret), call.spIncrement_); if (!ins) { return false; } curBlock_->add(ins); *def = ins; return true; } bool builtinCall(SymbolicAddress builtin, const CallCompileState& call, ValType ret, MDefinition** def) { if (inDeadCode()) { *def = nullptr; return true; } CallSiteDesc desc(call.lineOrBytecode_, CallSiteDesc::Symbolic); auto callee = CalleeDesc::builtin(builtin); auto* ins = MWasmCall::New(alloc(), desc, callee, call.regArgs_, ToMIRType(ret), call.spIncrement_); if (!ins) { return false; } curBlock_->add(ins); *def = ins; return true; } bool builtinInstanceMethodCall(SymbolicAddress builtin, const CallCompileState& call, ValType ret, MDefinition** def) { if (inDeadCode()) { *def = nullptr; return true; } CallSiteDesc desc(call.lineOrBytecode_, CallSiteDesc::Symbolic); auto* ins = MWasmCall::NewBuiltinInstanceMethodCall(alloc(), desc, builtin, call.instanceArg_, call.regArgs_, ToMIRType(ret), call.spIncrement_); if (!ins) { return false; } curBlock_->add(ins); *def = ins; return true; } /*********************************************** Control flow generation */ inline bool inDeadCode() const { return curBlock_ == nullptr; } void returnExpr(MDefinition* operand) { if (inDeadCode()) { return; } MWasmReturn* ins = MWasmReturn::New(alloc(), operand); curBlock_->end(ins); curBlock_ = nullptr; } void returnVoid() { if (inDeadCode()) { return; } MWasmReturnVoid* ins = MWasmReturnVoid::New(alloc()); curBlock_->end(ins); curBlock_ = nullptr; } void unreachableTrap() { if (inDeadCode()) { return; } auto* ins = MWasmTrap::New(alloc(), wasm::Trap::Unreachable, bytecodeOffset()); curBlock_->end(ins); curBlock_ = nullptr; } private: static bool hasPushed(MBasicBlock* block) { uint32_t numPushed = block->stackDepth() - block->info().firstStackSlot(); MOZ_ASSERT(numPushed == 0 || numPushed == 1); return numPushed; } public: void pushDef(MDefinition* def) { if (inDeadCode()) { return; } MOZ_ASSERT(!hasPushed(curBlock_)); if (def && def->type() != MIRType::None) { curBlock_->push(def); } } MDefinition* popDefIfPushed() { if (!hasPushed(curBlock_)) { return nullptr; } MDefinition* def = curBlock_->pop(); MOZ_ASSERT(def->type() != MIRType::Value); return def; } private: void addJoinPredecessor(MDefinition* def, MBasicBlock** joinPred) { *joinPred = curBlock_; if (inDeadCode()) { return; } pushDef(def); } public: bool branchAndStartThen(MDefinition* cond, MBasicBlock** elseBlock) { if (inDeadCode()) { *elseBlock = nullptr; } else { MBasicBlock* thenBlock; if (!newBlock(curBlock_, &thenBlock)) { return false; } if (!newBlock(curBlock_, elseBlock)) { return false; } curBlock_->end(MTest::New(alloc(), cond, thenBlock, *elseBlock)); curBlock_ = thenBlock; mirGraph().moveBlockToEnd(curBlock_); } return startBlock(); } bool switchToElse(MBasicBlock* elseBlock, MBasicBlock** thenJoinPred) { MDefinition* ifDef; if (!finishBlock(&ifDef)) { return false; } if (!elseBlock) { *thenJoinPred = nullptr; } else { addJoinPredecessor(ifDef, thenJoinPred); curBlock_ = elseBlock; mirGraph().moveBlockToEnd(curBlock_); } return startBlock(); } bool joinIfElse(MBasicBlock* thenJoinPred, MDefinition** def) { MDefinition* elseDef; if (!finishBlock(&elseDef)) { return false; } if (!thenJoinPred && inDeadCode()) { *def = nullptr; } else { MBasicBlock* elseJoinPred; addJoinPredecessor(elseDef, &elseJoinPred); mozilla::Array<MBasicBlock*, 2> blocks; size_t numJoinPreds = 0; if (thenJoinPred) { blocks[numJoinPreds++] = thenJoinPred; } if (elseJoinPred) { blocks[numJoinPreds++] = elseJoinPred; } if (numJoinPreds == 0) { *def = nullptr; return true; } MBasicBlock* join; if (!goToNewBlock(blocks[0], &join)) { return false; } for (size_t i = 1; i < numJoinPreds; ++i) { if (!goToExistingBlock(blocks[i], join)) { return false; } } curBlock_ = join; *def = popDefIfPushed(); } return true; } bool startBlock() { MOZ_ASSERT_IF(blockDepth_ < blockPatches_.length(), blockPatches_[blockDepth_].empty()); blockDepth_++; return true; } bool finishBlock(MDefinition** def) { MOZ_ASSERT(blockDepth_); uint32_t topLabel = --blockDepth_; return bindBranches(topLabel, def); } bool startLoop(MBasicBlock** loopHeader) { *loopHeader = nullptr; blockDepth_++; loopDepth_++; if (inDeadCode()) { return true; } // Create the loop header. MOZ_ASSERT(curBlock_->loopDepth() == loopDepth_ - 1); *loopHeader = MBasicBlock::New(mirGraph(), info(), curBlock_, MBasicBlock::PENDING_LOOP_HEADER); if (!*loopHeader) { return false; } (*loopHeader)->setLoopDepth(loopDepth_); mirGraph().addBlock(*loopHeader); curBlock_->end(MGoto::New(alloc(), *loopHeader)); MBasicBlock* body; if (!goToNewBlock(*loopHeader, &body)) { return false; } curBlock_ = body; return true; } private: void fixupRedundantPhis(MBasicBlock* b) { for (size_t i = 0, depth = b->stackDepth(); i < depth; i++) { MDefinition* def = b->getSlot(i); if (def->isUnused()) { b->setSlot(i, def->toPhi()->getOperand(0)); } } } bool setLoopBackedge(MBasicBlock* loopEntry, MBasicBlock* loopBody, MBasicBlock* backedge) { if (!loopEntry->setBackedgeWasm(backedge)) { return false; } // Flag all redundant phis as unused. for (MPhiIterator phi = loopEntry->phisBegin(); phi != loopEntry->phisEnd(); phi++) { MOZ_ASSERT(phi->numOperands() == 2); if (phi->getOperand(0) == phi->getOperand(1)) { phi->setUnused(); } } // Fix up phis stored in the slots Vector of pending blocks. for (ControlFlowPatchVector& patches : blockPatches_) { for (ControlFlowPatch& p : patches) { MBasicBlock* block = p.ins->block(); if (block->loopDepth() >= loopEntry->loopDepth()) { fixupRedundantPhis(block); } } } // The loop body, if any, might be referencing recycled phis too. if (loopBody) { fixupRedundantPhis(loopBody); } // Discard redundant phis and add to the free list. for (MPhiIterator phi = loopEntry->phisBegin(); phi != loopEntry->phisEnd(); ) { MPhi* entryDef = *phi++; if (!entryDef->isUnused()) { continue; } entryDef->justReplaceAllUsesWith(entryDef->getOperand(0)); loopEntry->discardPhi(entryDef); mirGraph().addPhiToFreeList(entryDef); } return true; } public: bool closeLoop(MBasicBlock* loopHeader, MDefinition** loopResult) { MOZ_ASSERT(blockDepth_ >= 1); MOZ_ASSERT(loopDepth_); uint32_t headerLabel = blockDepth_ - 1; if (!loopHeader) { MOZ_ASSERT(inDeadCode()); MOZ_ASSERT(headerLabel >= blockPatches_.length() || blockPatches_[headerLabel].empty()); blockDepth_--; loopDepth_--; *loopResult = nullptr; return true; } // Op::Loop doesn't have an implicit backedge so temporarily set // aside the end of the loop body to bind backedges. MBasicBlock* loopBody = curBlock_; curBlock_ = nullptr; // As explained in bug 1253544, Ion apparently has an invariant that // there is only one backedge to loop headers. To handle wasm's ability // to have multiple backedges to the same loop header, we bind all those // branches as forward jumps to a single backward jump. This is // unfortunate but the optimizer is able to fold these into single jumps // to backedges. MDefinition* _; if (!bindBranches(headerLabel, &_)) { return false; } MOZ_ASSERT(loopHeader->loopDepth() == loopDepth_); if (curBlock_) { // We're on the loop backedge block, created by bindBranches. if (hasPushed(curBlock_)) { curBlock_->pop(); } MOZ_ASSERT(curBlock_->loopDepth() == loopDepth_); curBlock_->end(MGoto::New(alloc(), loopHeader)); if (!setLoopBackedge(loopHeader, loopBody, curBlock_)) { return false; } } curBlock_ = loopBody; loopDepth_--; // If the loop depth still at the inner loop body, correct it. if (curBlock_ && curBlock_->loopDepth() != loopDepth_) { MBasicBlock* out; if (!goToNewBlock(curBlock_, &out)) { return false; } curBlock_ = out; } blockDepth_ -= 1; *loopResult = inDeadCode() ? nullptr : popDefIfPushed(); return true; } bool addControlFlowPatch(MControlInstruction* ins, uint32_t relative, uint32_t index) { MOZ_ASSERT(relative < blockDepth_); uint32_t absolute = blockDepth_ - 1 - relative; if (absolute >= blockPatches_.length() && !blockPatches_.resize(absolute + 1)) { return false; } return blockPatches_[absolute].append(ControlFlowPatch(ins, index)); } bool br(uint32_t relativeDepth, MDefinition* maybeValue) { if (inDeadCode()) { return true; } MGoto* jump = MGoto::New(alloc()); if (!addControlFlowPatch(jump, relativeDepth, MGoto::TargetIndex)) { return false; } pushDef(maybeValue); curBlock_->end(jump); curBlock_ = nullptr; return true; } bool brIf(uint32_t relativeDepth, MDefinition* maybeValue, MDefinition* condition) { if (inDeadCode()) { return true; } MBasicBlock* joinBlock = nullptr; if (!newBlock(curBlock_, &joinBlock)) { return false; } MTest* test = MTest::New(alloc(), condition, joinBlock); if (!addControlFlowPatch(test, relativeDepth, MTest::TrueBranchIndex)) { return false; } pushDef(maybeValue); curBlock_->end(test); curBlock_ = joinBlock; return true; } bool brTable(MDefinition* operand, uint32_t defaultDepth, const Uint32Vector& depths, MDefinition* maybeValue) { if (inDeadCode()) { return true; } size_t numCases = depths.length(); MOZ_ASSERT(numCases <= INT32_MAX); MOZ_ASSERT(numCases); MTableSwitch* table = MTableSwitch::New(alloc(), operand, 0, int32_t(numCases - 1)); size_t defaultIndex; if (!table->addDefault(nullptr, &defaultIndex)) { return false; } if (!addControlFlowPatch(table, defaultDepth, defaultIndex)) { return false; } typedef HashMap<uint32_t, uint32_t, DefaultHasher<uint32_t>, SystemAllocPolicy> IndexToCaseMap; IndexToCaseMap indexToCase; if (!indexToCase.put(defaultDepth, defaultIndex)) { return false; } for (size_t i = 0; i < numCases; i++) { uint32_t depth = depths[i]; size_t caseIndex; IndexToCaseMap::AddPtr p = indexToCase.lookupForAdd(depth); if (!p) { if (!table->addSuccessor(nullptr, &caseIndex)) { return false; } if (!addControlFlowPatch(table, depth, caseIndex)) { return false; } if (!indexToCase.add(p, depth, caseIndex)) { return false; } } else { caseIndex = p->value(); } if (!table->addCase(caseIndex)) { return false; } } pushDef(maybeValue); curBlock_->end(table); curBlock_ = nullptr; return true; } /************************************************************ DECODING ***/ uint32_t readCallSiteLineOrBytecode() { if (!func_.callSiteLineNums.empty()) { return func_.callSiteLineNums[lastReadCallSite_++]; } return iter_.lastOpcodeOffset(); } #if DEBUG bool done() const { return iter_.done(); } #endif /*************************************************************************/ private: bool newBlock(MBasicBlock* pred, MBasicBlock** block) { *block = MBasicBlock::New(mirGraph(), info(), pred, MBasicBlock::NORMAL); if (!*block) { return false; } mirGraph().addBlock(*block); (*block)->setLoopDepth(loopDepth_); return true; } bool goToNewBlock(MBasicBlock* pred, MBasicBlock** block) { if (!newBlock(pred, block)) { return false; } pred->end(MGoto::New(alloc(), *block)); return true; } bool goToExistingBlock(MBasicBlock* prev, MBasicBlock* next) { MOZ_ASSERT(prev); MOZ_ASSERT(next); prev->end(MGoto::New(alloc(), next)); return next->addPredecessor(alloc(), prev); } bool bindBranches(uint32_t absolute, MDefinition** def) { if (absolute >= blockPatches_.length() || blockPatches_[absolute].empty()) { *def = inDeadCode() ? nullptr : popDefIfPushed(); return true; } ControlFlowPatchVector& patches = blockPatches_[absolute]; MControlInstruction* ins = patches[0].ins; MBasicBlock* pred = ins->block(); MBasicBlock* join = nullptr; if (!newBlock(pred, &join)) { return false; } pred->mark(); ins->replaceSuccessor(patches[0].index, join); for (size_t i = 1; i < patches.length(); i++) { ins = patches[i].ins; pred = ins->block(); if (!pred->isMarked()) { if (!join->addPredecessor(alloc(), pred)) { return false; } pred->mark(); } ins->replaceSuccessor(patches[i].index, join); } MOZ_ASSERT_IF(curBlock_, !curBlock_->isMarked()); for (uint32_t i = 0; i < join->numPredecessors(); i++) { join->getPredecessor(i)->unmark(); } if (curBlock_ && !goToExistingBlock(curBlock_, join)) { return false; } curBlock_ = join; *def = popDefIfPushed(); patches.clear(); return true; } }; template <> MDefinition* FunctionCompiler::unary<MToFloat32>(MDefinition* op) { if (inDeadCode()) { return nullptr; } auto* ins = MToFloat32::New(alloc(), op, mustPreserveNaN(op->type())); curBlock_->add(ins); return ins; } template <> MDefinition* FunctionCompiler::unary<MTruncateToInt32>(MDefinition* op) { if (inDeadCode()) { return nullptr; } auto* ins = MTruncateToInt32::New(alloc(), op, bytecodeOffset()); curBlock_->add(ins); return ins; } template <> MDefinition* FunctionCompiler::unary<MNot>(MDefinition* op) { if (inDeadCode()) { return nullptr; } auto* ins = MNot::NewInt32(alloc(), op); curBlock_->add(ins); return ins; } template <> MDefinition* FunctionCompiler::unary<MAbs>(MDefinition* op, MIRType type) { if (inDeadCode()) { return nullptr; } auto* ins = MAbs::NewWasm(alloc(), op, type); curBlock_->add(ins); return ins; } } // end anonymous namespace static bool EmitI32Const(FunctionCompiler& f) { int32_t i32; if (!f.iter().readI32Const(&i32)) { return false; } f.iter().setResult(f.constant(Int32Value(i32), MIRType::Int32)); return true; } static bool EmitI64Const(FunctionCompiler& f) { int64_t i64; if (!f.iter().readI64Const(&i64)) { return false; } f.iter().setResult(f.constant(i64)); return true; } static bool EmitF32Const(FunctionCompiler& f) { float f32; if (!f.iter().readF32Const(&f32)) { return false; } f.iter().setResult(f.constant(f32)); return true; } static bool EmitF64Const(FunctionCompiler& f) { double f64; if (!f.iter().readF64Const(&f64)) { return false; } f.iter().setResult(f.constant(f64)); return true; } static bool EmitBlock(FunctionCompiler& f) { return f.iter().readBlock() && f.startBlock(); } static bool EmitLoop(FunctionCompiler& f) { if (!f.iter().readLoop()) { return false; } MBasicBlock* loopHeader; if (!f.startLoop(&loopHeader)) { return false; } f.addInterruptCheck(); f.iter().controlItem() = loopHeader; return true; } static bool EmitIf(FunctionCompiler& f) { MDefinition* condition = nullptr; if (!f.iter().readIf(&condition)) { return false; } MBasicBlock* elseBlock; if (!f.branchAndStartThen(condition, &elseBlock)) { return false; } f.iter().controlItem() = elseBlock; return true; } static bool EmitElse(FunctionCompiler& f) { ExprType thenType; MDefinition* thenValue; if (!f.iter().readElse(&thenType, &thenValue)) { return false; } if (!IsVoid(thenType)) { f.pushDef(thenValue); } if (!f.switchToElse(f.iter().controlItem(), &f.iter().controlItem())) { return false; } return true; } static bool EmitEnd(FunctionCompiler& f) { LabelKind kind; ExprType type; MDefinition* value; if (!f.iter().readEnd(&kind, &type, &value)) { return false; } MBasicBlock* block = f.iter().controlItem(); f.iter().popEnd(); if (!IsVoid(type)) { f.pushDef(value); } MDefinition* def = nullptr; switch (kind) { case LabelKind::Block: if (!f.finishBlock(&def)) { return false; } break; case LabelKind::Loop: if (!f.closeLoop(block, &def)) { return false; } break; case LabelKind::Then: // If we didn't see an Else, create a trivial else block so that we create // a diamond anyway, to preserve Ion invariants. if (!f.switchToElse(block, &block)) { return false; } if (!f.joinIfElse(block, &def)) { return false; } break; case LabelKind::Else: if (!f.joinIfElse(block, &def)) { return false; } break; } if (!IsVoid(type)) { MOZ_ASSERT_IF(!f.inDeadCode(), def); f.iter().setResult(def); } return true; } static bool EmitBr(FunctionCompiler& f) { uint32_t relativeDepth; ExprType type; MDefinition* value; if (!f.iter().readBr(&relativeDepth, &type, &value)) { return false; } if (IsVoid(type)) { if (!f.br(relativeDepth, nullptr)) { return false; } } else { if (!f.br(relativeDepth, value)) { return false; } } return true; } static bool EmitBrIf(FunctionCompiler& f) { uint32_t relativeDepth; ExprType type; MDefinition* value; MDefinition* condition; if (!f.iter().readBrIf(&relativeDepth, &type, &value, &condition)) { return false; } if (IsVoid(type)) { if (!f.brIf(relativeDepth, nullptr, condition)) { return false; } } else { if (!f.brIf(relativeDepth, value, condition)) { return false; } } return true; } static bool EmitBrTable(FunctionCompiler& f) { Uint32Vector depths; uint32_t defaultDepth; ExprType branchValueType; MDefinition* branchValue; MDefinition* index; if (!f.iter().readBrTable(&depths, &defaultDepth, &branchValueType, &branchValue, &index)) { return false; } // If all the targets are the same, or there are no targets, we can just // use a goto. This is not just an optimization: MaybeFoldConditionBlock // assumes that tables have more than one successor. bool allSameDepth = true; for (uint32_t depth : depths) { if (depth != defaultDepth) { allSameDepth = false; break; } } if (allSameDepth) { return f.br(defaultDepth, branchValue); } return f.brTable(index, defaultDepth, depths, branchValue); } static bool EmitReturn(FunctionCompiler& f) { MDefinition* value; if (!f.iter().readReturn(&value)) { return false; } if (IsVoid(f.funcType().ret())) { f.returnVoid(); return true; } f.returnExpr(value); return true; } static bool EmitUnreachable(FunctionCompiler& f) { if (!f.iter().readUnreachable()) { return false; } f.unreachableTrap(); return true; } typedef IonOpIter::ValueVector DefVector; static bool EmitCallArgs(FunctionCompiler& f, const FuncType& funcType, const DefVector& args, CallCompileState* call) { if (!f.startCall(call)) { return false; } for (size_t i = 0, n = funcType.args().length(); i < n; ++i) { if (!f.mirGen().ensureBallast()) { return false; } if (!f.passArg(args[i], funcType.args()[i], call)) { return false; } } return f.finishCall(call); } static bool EmitCall(FunctionCompiler& f, bool asmJSFuncDef) { uint32_t lineOrBytecode = f.readCallSiteLineOrBytecode(); uint32_t funcIndex; DefVector args; if (asmJSFuncDef) { if (!f.iter().readOldCallDirect(f.env().numFuncImports(), &funcIndex, &args)) { return false; } } else { if (!f.iter().readCall(&funcIndex, &args)) { return false; } } if (f.inDeadCode()) { return true; } const FuncType& funcType = *f.env().funcTypes[funcIndex]; CallCompileState call(f, lineOrBytecode); if (!EmitCallArgs(f, funcType, args, &call)) { return false; } MDefinition* def; if (f.env().funcIsImport(funcIndex)) { uint32_t globalDataOffset = f.env().funcImportGlobalDataOffsets[funcIndex]; if (!f.callImport(globalDataOffset, call, funcType.ret(), &def)) { return false; } } else { if (!f.callDirect(funcType, funcIndex, call, &def)) { return false; } } if (IsVoid(funcType.ret())) { return true; } f.iter().setResult(def); return true; } static bool EmitCallIndirect(FunctionCompiler& f, bool oldStyle) { uint32_t lineOrBytecode = f.readCallSiteLineOrBytecode(); uint32_t funcTypeIndex; MDefinition* callee; DefVector args; if (oldStyle) { if (!f.iter().readOldCallIndirect(&funcTypeIndex, &callee, &args)) { return false; } } else { if (!f.iter().readCallIndirect(&funcTypeIndex, &callee, &args)) { return false; } } if (f.inDeadCode()) { return true; } const FuncType& funcType = f.env().types[funcTypeIndex].funcType(); CallCompileState call(f, lineOrBytecode); if (!EmitCallArgs(f, funcType, args, &call)) { return false; } MDefinition* def; if (!f.callIndirect(funcTypeIndex, callee, call, &def)) { return false; } if (IsVoid(funcType.ret())) { return true; } f.iter().setResult(def); return true; } static bool EmitGetLocal(FunctionCompiler& f) { uint32_t id; if (!f.iter().readGetLocal(f.locals(), &id)) { return false; } f.iter().setResult(f.getLocalDef(id)); return true; } static bool EmitSetLocal(FunctionCompiler& f) { uint32_t id; MDefinition* value; if (!f.iter().readSetLocal(f.locals(), &id, &value)) { return false; } f.assign(id, value); return true; } static bool EmitTeeLocal(FunctionCompiler& f) { uint32_t id; MDefinition* value; if (!f.iter().readTeeLocal(f.locals(), &id, &value)) { return false; } f.assign(id, value); return true; } static bool EmitGetGlobal(FunctionCompiler& f) { uint32_t id; if (!f.iter().readGetGlobal(&id)) { return false; } const GlobalDesc& global = f.env().globals[id]; if (!global.isConstant()) { f.iter().setResult(f.loadGlobalVar(global.offset(), !global.isMutable(), global.isIndirect(), ToMIRType(global.type()))); return true; } LitVal value = global.constantValue(); MIRType mirType = ToMIRType(value.type()); MDefinition* result; switch (value.type().code()) { case ValType::I32: result = f.constant(Int32Value(value.i32()), mirType); break; case ValType::I64: result = f.constant(int64_t(value.i64())); break; case ValType::F32: result = f.constant(value.f32()); break; case ValType::F64: result = f.constant(value.f64()); break; default: MOZ_CRASH("unexpected type in EmitGetGlobal"); } f.iter().setResult(result); return true; } static bool EmitSetGlobal(FunctionCompiler& f) { uint32_t id; MDefinition* value; if (!f.iter().readSetGlobal(&id, &value)) { return false; } const GlobalDesc& global = f.env().globals[id]; MOZ_ASSERT(global.isMutable()); f.storeGlobalVar(global.offset(), global.isIndirect(), value); return true; } static bool EmitTeeGlobal(FunctionCompiler& f) { uint32_t id; MDefinition* value; if (!f.iter().readTeeGlobal(&id, &value)) { return false; } const GlobalDesc& global = f.env().globals[id]; MOZ_ASSERT(global.isMutable()); f.storeGlobalVar(global.offset(), global.isIndirect(), value); return true; } template <typename MIRClass> static bool EmitUnary(FunctionCompiler& f, ValType operandType) { MDefinition* input; if (!f.iter().readUnary(operandType, &input)) { return false; } f.iter().setResult(f.unary<MIRClass>(input)); return true; } template <typename MIRClass> static bool EmitConversion(FunctionCompiler& f, ValType operandType, ValType resultType) { MDefinition* input; if (!f.iter().readConversion(operandType, resultType, &input)) { return false; } f.iter().setResult(f.unary<MIRClass>(input)); return true; } template <typename MIRClass> static bool EmitUnaryWithType(FunctionCompiler& f, ValType operandType, MIRType mirType) { MDefinition* input; if (!f.iter().readUnary(operandType, &input)) { return false; } f.iter().setResult(f.unary<MIRClass>(input, mirType)); return true; } template <typename MIRClass> static bool EmitConversionWithType(FunctionCompiler& f, ValType operandType, ValType resultType, MIRType mirType) { MDefinition* input; if (!f.iter().readConversion(operandType, resultType, &input)) { return false; } f.iter().setResult(f.unary<MIRClass>(input, mirType)); return true; } static bool EmitTruncate(FunctionCompiler& f, ValType operandType, ValType resultType, bool isUnsigned, bool isSaturating) { MDefinition* input; if (!f.iter().readConversion(operandType, resultType, &input)) { return false; } TruncFlags flags = 0; if (isUnsigned) { flags |= TRUNC_UNSIGNED; } if (isSaturating) { flags |= TRUNC_SATURATING; } if (resultType == ValType::I32) { if (f.env().isAsmJS()) { f.iter().setResult(f.unary<MTruncateToInt32>(input)); } else { f.iter().setResult(f.truncate<MWasmTruncateToInt32>(input, flags)); } } else { MOZ_ASSERT(resultType == ValType::I64); MOZ_ASSERT(!f.env().isAsmJS()); f.iter().setResult(f.truncate<MWasmTruncateToInt64>(input, flags)); } return true; } static bool EmitSignExtend(FunctionCompiler& f, uint32_t srcSize, uint32_t targetSize) { MDefinition* input; ValType type = targetSize == 4 ? ValType::I32 : ValType::I64; if (!f.iter().readConversion(type, type, &input)) { return false; } f.iter().setResult(f.signExtend(input, srcSize, targetSize)); return true; } static bool EmitExtendI32(FunctionCompiler& f, bool isUnsigned) { MDefinition* input; if (!f.iter().readConversion(ValType::I32, ValType::I64, &input)) { return false; } f.iter().setResult(f.extendI32(input, isUnsigned)); return true; } static bool EmitConvertI64ToFloatingPoint(FunctionCompiler& f, ValType resultType, MIRType mirType, bool isUnsigned) { MDefinition* input; if (!f.iter().readConversion(ValType::I64, resultType, &input)) { return false; } f.iter().setResult(f.convertI64ToFloatingPoint(input, mirType, isUnsigned)); return true; } static bool EmitReinterpret(FunctionCompiler& f, ValType resultType, ValType operandType, MIRType mirType) { MDefinition* input; if (!f.iter().readConversion(operandType, resultType, &input)) { return false; } f.iter().setResult(f.unary<MWasmReinterpret>(input, mirType)); return true; } static bool EmitAdd(FunctionCompiler& f, ValType type, MIRType mirType) { MDefinition* lhs; MDefinition* rhs; if (!f.iter().readBinary(type, &lhs, &rhs)) { return false; } f.iter().setResult(f.binary<MAdd>(lhs, rhs, mirType)); return true; } static bool EmitSub(FunctionCompiler& f, ValType type, MIRType mirType) { MDefinition* lhs; MDefinition* rhs; if (!f.iter().readBinary(type, &lhs, &rhs)) { return false; } f.iter().setResult(f.sub(lhs, rhs, mirType)); return true; } static bool EmitRotate(FunctionCompiler& f, ValType type, bool isLeftRotation) { MDefinition* lhs; MDefinition* rhs; if (!f.iter().readBinary(type, &lhs, &rhs)) { return false; } MDefinition* result = f.rotate(lhs, rhs, ToMIRType(type), isLeftRotation); f.iter().setResult(result); return true; } static bool EmitBitNot(FunctionCompiler& f, ValType operandType) { MDefinition* input; if (!f.iter().readUnary(operandType, &input)) { return false; } f.iter().setResult(f.bitnot(input)); return true; } template <typename MIRClass> static bool EmitBitwise(FunctionCompiler& f, ValType operandType, MIRType mirType) { MDefinition* lhs; MDefinition* rhs; if (!f.iter().readBinary(operandType, &lhs, &rhs)) { return false; } f.iter().setResult(f.binary<MIRClass>(lhs, rhs, mirType)); return true; } static bool EmitMul(FunctionCompiler& f, ValType operandType, MIRType mirType) { MDefinition* lhs; MDefinition* rhs; if (!f.iter().readBinary(operandType, &lhs, &rhs)) { return false; } f.iter().setResult(f.mul(lhs, rhs, mirType, mirType == MIRType::Int32 ? MMul::Integer : MMul::Normal)); return true; } static bool EmitDiv(FunctionCompiler& f, ValType operandType, MIRType mirType, bool isUnsigned) { MDefinition* lhs; MDefinition* rhs; if (!f.iter().readBinary(operandType, &lhs, &rhs)) { return false; } f.iter().setResult(f.div(lhs, rhs, mirType, isUnsigned)); return true; } static bool EmitRem(FunctionCompiler& f, ValType operandType, MIRType mirType, bool isUnsigned) { MDefinition* lhs; MDefinition* rhs; if (!f.iter().readBinary(operandType, &lhs, &rhs)) { return false; } f.iter().setResult(f.mod(lhs, rhs, mirType, isUnsigned)); return true; } static bool EmitMinMax(FunctionCompiler& f, ValType operandType, MIRType mirType, bool isMax) { MDefinition* lhs; MDefinition* rhs; if (!f.iter().readBinary(operandType, &lhs, &rhs)) { return false; } f.iter().setResult(f.minMax(lhs, rhs, mirType, isMax)); return true; } static bool EmitCopySign(FunctionCompiler& f, ValType operandType) { MDefinition* lhs; MDefinition* rhs; if (!f.iter().readBinary(operandType, &lhs, &rhs)) { return false; } f.iter().setResult(f.binary<MCopySign>(lhs, rhs, ToMIRType(operandType))); return true; } static bool EmitComparison(FunctionCompiler& f, ValType operandType, JSOp compareOp, MCompare::CompareType compareType) { MDefinition* lhs; MDefinition* rhs; if (!f.iter().readComparison(operandType, &lhs, &rhs)) { return false; } f.iter().setResult(f.compare(lhs, rhs, compareOp, compareType)); return true; } static bool EmitSelect(FunctionCompiler& f) { StackType type; MDefinition* trueValue; MDefinition* falseValue; MDefinition* condition; if (!f.iter().readSelect(&type, &trueValue, &falseValue, &condition)) { return false; } f.iter().setResult(f.select(trueValue, falseValue, condition)); return true; } static bool EmitLoad(FunctionCompiler& f, ValType type, Scalar::Type viewType) { LinearMemoryAddress<MDefinition*> addr; if (!f.iter().readLoad(type, Scalar::byteSize(viewType), &addr)) { return false; } MemoryAccessDesc access(viewType, addr.align, addr.offset, f.bytecodeIfNotAsmJS()); auto* ins = f.load(addr.base, &access, type); if (!f.inDeadCode() && !ins) { return false; } f.iter().setResult(ins); return true; } static bool EmitStore(FunctionCompiler& f, ValType resultType, Scalar::Type viewType) { LinearMemoryAddress<MDefinition*> addr; MDefinition* value; if (!f.iter().readStore(resultType, Scalar::byteSize(viewType), &addr, &value)) { return false; } MemoryAccessDesc access(viewType, addr.align, addr.offset, f.bytecodeIfNotAsmJS()); f.store(addr.base, &access, value); return true; } static bool EmitTeeStore(FunctionCompiler& f, ValType resultType, Scalar::Type viewType) { LinearMemoryAddress<MDefinition*> addr; MDefinition* value; if (!f.iter().readTeeStore(resultType, Scalar::byteSize(viewType), &addr, &value)) { return false; } MemoryAccessDesc access(viewType, addr.align, addr.offset, f.bytecodeIfNotAsmJS()); f.store(addr.base, &access, value); return true; } static bool EmitTeeStoreWithCoercion(FunctionCompiler& f, ValType resultType, Scalar::Type viewType) { LinearMemoryAddress<MDefinition*> addr; MDefinition* value; if (!f.iter().readTeeStore(resultType, Scalar::byteSize(viewType), &addr, &value)) { return false; } if (resultType == ValType::F32 && viewType == Scalar::Float64) { value = f.unary<MToDouble>(value); } else if (resultType == ValType::F64 && viewType == Scalar::Float32) { value = f.unary<MToFloat32>(value); } else { MOZ_CRASH("unexpected coerced store"); } MemoryAccessDesc access(viewType, addr.align, addr.offset, f.bytecodeIfNotAsmJS()); f.store(addr.base, &access, value); return true; } static bool TryInlineUnaryBuiltin(FunctionCompiler& f, SymbolicAddress callee, MDefinition* input) { if (!input) { return false; } MOZ_ASSERT(IsFloatingPointType(input->type())); RoundingMode mode; if (!IsRoundingFunction(callee, &mode)) { return false; } if (!MNearbyInt::HasAssemblerSupport(mode)) { return false; } f.iter().setResult(f.nearbyInt(input, mode)); return true; } static bool EmitUnaryMathBuiltinCall(FunctionCompiler& f, SymbolicAddress callee, ValType operandType) { uint32_t lineOrBytecode = f.readCallSiteLineOrBytecode(); MDefinition* input; if (!f.iter().readUnary(operandType, &input)) { return false; } if (TryInlineUnaryBuiltin(f, callee, input)) { return true; } CallCompileState call(f, lineOrBytecode); if (!f.startCall(&call)) { return false; } if (!f.passArg(input, operandType, &call)) { return false; } if (!f.finishCall(&call)) { return false; } MDefinition* def; if (!f.builtinCall(callee, call, operandType, &def)) { return false; } f.iter().setResult(def); return true; } static bool EmitBinaryMathBuiltinCall(FunctionCompiler& f, SymbolicAddress callee, ValType operandType) { uint32_t lineOrBytecode = f.readCallSiteLineOrBytecode(); CallCompileState call(f, lineOrBytecode); if (!f.startCall(&call)) { return false; } MDefinition* lhs; MDefinition* rhs; if (!f.iter().readBinary(operandType, &lhs, &rhs)) { return false; } if (!f.passArg(lhs, operandType, &call)) { return false; } if (!f.passArg(rhs, operandType, &call)) { return false; } if (!f.finishCall(&call)) { return false; } MDefinition* def; if (!f.builtinCall(callee, call, operandType, &def)) { return false; } f.iter().setResult(def); return true; } static bool EmitGrowMemory(FunctionCompiler& f) { uint32_t lineOrBytecode = f.readCallSiteLineOrBytecode(); CallCompileState args(f, lineOrBytecode); if (!f.startCall(&args)) { return false; } if (!f.passInstance(&args)) { return false; } MDefinition* delta; if (!f.iter().readGrowMemory(&delta)) { return false; } if (!f.passArg(delta, ValType::I32, &args)) { return false; } f.finishCall(&args); MDefinition* ret; if (!f.builtinInstanceMethodCall(SymbolicAddress::GrowMemory, args, ValType::I32, &ret)) { return false; } f.iter().setResult(ret); return true; } static bool EmitCurrentMemory(FunctionCompiler& f) { uint32_t lineOrBytecode = f.readCallSiteLineOrBytecode(); CallCompileState args(f, lineOrBytecode); if (!f.iter().readCurrentMemory()) { return false; } if (!f.startCall(&args)) { return false; } if (!f.passInstance(&args)) { return false; } f.finishCall(&args); MDefinition* ret; if (!f.builtinInstanceMethodCall(SymbolicAddress::CurrentMemory, args, ValType::I32, &ret)) { return false; } f.iter().setResult(ret); return true; } #ifdef ENABLE_WASM_THREAD_OPS static bool EmitAtomicCmpXchg(FunctionCompiler& f, ValType type, Scalar::Type viewType) { LinearMemoryAddress<MDefinition*> addr; MDefinition* oldValue; MDefinition* newValue; if (!f.iter().readAtomicCmpXchg(&addr, type, byteSize(viewType), &oldValue, &newValue)) { return false; } MemoryAccessDesc access(viewType, addr.align, addr.offset, f.bytecodeOffset(), Synchronization::Full()); auto* ins = f.atomicCompareExchangeHeap(addr.base, &access, type, oldValue, newValue); if (!f.inDeadCode() && !ins) { return false; } f.iter().setResult(ins); return true; } static bool EmitAtomicLoad(FunctionCompiler& f, ValType type, Scalar::Type viewType) { LinearMemoryAddress<MDefinition*> addr; if (!f.iter().readAtomicLoad(&addr, type, byteSize(viewType))) { return false; } MemoryAccessDesc access(viewType, addr.align, addr.offset, f.bytecodeOffset(), Synchronization::Load()); auto* ins = f.load(addr.base, &access, type); if (!f.inDeadCode() && !ins) { return false; } f.iter().setResult(ins); return true; } static bool EmitAtomicRMW(FunctionCompiler& f, ValType type, Scalar::Type viewType, jit::AtomicOp op) { LinearMemoryAddress<MDefinition*> addr; MDefinition* value; if (!f.iter().readAtomicRMW(&addr, type, byteSize(viewType), &value)) { return false; } MemoryAccessDesc access(viewType, addr.align, addr.offset, f.bytecodeOffset(), Synchronization::Full()); auto* ins = f.atomicBinopHeap(op, addr.base, &access, type, value); if (!f.inDeadCode() && !ins) { return false; } f.iter().setResult(ins); return true; } static bool EmitAtomicStore(FunctionCompiler& f, ValType type, Scalar::Type viewType) { LinearMemoryAddress<MDefinition*> addr; MDefinition* value; if (!f.iter().readAtomicStore(&addr, type, byteSize(viewType), &value)) { return false; } MemoryAccessDesc access(viewType, addr.align, addr.offset, f.bytecodeOffset(), Synchronization::Store()); f.store(addr.base, &access, value); return true; } static bool EmitWait(FunctionCompiler& f, ValType type, uint32_t byteSize) { uint32_t lineOrBytecode = f.readCallSiteLineOrBytecode(); CallCompileState args(f, lineOrBytecode); if (!f.startCall(&args)) { return false; } if (!f.passInstance(&args)) { return false; } LinearMemoryAddress<MDefinition*> addr; MDefinition* expected; MDefinition* timeout; if (!f.iter().readWait(&addr, type, byteSize, &expected, &timeout)) { return false; } MemoryAccessDesc access(type == ValType::I32 ? Scalar::Int32 : Scalar::Int64, addr.align, addr.offset, f.bytecodeOffset()); MDefinition* ptr = f.computeEffectiveAddress(addr.base, &access); if (!f.inDeadCode() && !ptr) { return false; } if (!f.passArg(ptr, ValType::I32, &args)) { return false; } if (!f.passArg(expected, type, &args)) { return false; } if (!f.passArg(timeout, ValType::I64, &args)) { return false; } if (!f.finishCall(&args)) { return false; } SymbolicAddress callee = type == ValType::I32 ? SymbolicAddress::WaitI32 : SymbolicAddress::WaitI64; MDefinition* ret; if (!f.builtinInstanceMethodCall(callee, args, ValType::I32, &ret)) { return false; } if (!f.checkI32NegativeMeansFailedResult(ret)) { return false; } f.iter().setResult(ret); return true; } static bool EmitWake(FunctionCompiler& f) { uint32_t lineOrBytecode = f.readCallSiteLineOrBytecode(); CallCompileState args(f, lineOrBytecode); if (!f.startCall(&args)) { return false; } if (!f.passInstance(&args)) { return false; } LinearMemoryAddress<MDefinition*> addr; MDefinition* count; if (!f.iter().readWake(&addr, &count)) { return false; } MemoryAccessDesc access(Scalar::Int32, addr.align, addr.offset, f.bytecodeOffset()); MDefinition* ptr = f.computeEffectiveAddress(addr.base, &access); if (!f.inDeadCode() && !ptr) { return false; } if (!f.passArg(ptr, ValType::I32, &args)) { return false; } if (!f.passArg(count, ValType::I32, &args)) { return false; } if (!f.finishCall(&args)) { return false; } MDefinition* ret; if (!f.builtinInstanceMethodCall(SymbolicAddress::Wake, args, ValType::I32, &ret)) { return false; } if (!f.checkI32NegativeMeansFailedResult(ret)) { return false; } f.iter().setResult(ret); return true; } static bool EmitAtomicXchg(FunctionCompiler& f, ValType type, Scalar::Type viewType) { LinearMemoryAddress<MDefinition*> addr; MDefinition* value; if (!f.iter().readAtomicRMW(&addr, type, byteSize(viewType), &value)) { return false; } MemoryAccessDesc access(viewType, addr.align, addr.offset, f.bytecodeOffset(), Synchronization::Full()); MDefinition* ins = f.atomicExchangeHeap(addr.base, &access, type, value); if (!f.inDeadCode() && !ins) { return false; } f.iter().setResult(ins); return true; } #endif // ENABLE_WASM_THREAD_OPS #ifdef ENABLE_WASM_BULKMEM_OPS static bool EmitMemOrTableCopy(FunctionCompiler& f, bool isMem) { MDefinition* dst, *src, *len; if (!f.iter().readMemOrTableCopy(isMem, &dst, &src, &len)) { return false; } if (f.inDeadCode()) { return false; } uint32_t lineOrBytecode = f.readCallSiteLineOrBytecode(); CallCompileState args(f, lineOrBytecode); if (!f.startCall(&args)) { return false; } if (!f.passInstance(&args)) { return false; } if (!f.passArg(dst, ValType::I32, &args)) { return false; } if (!f.passArg(src, ValType::I32, &args)) { return false; } if (!f.passArg(len, ValType::I32, &args)) { return false; } if (!f.finishCall(&args)) { return false; } SymbolicAddress callee = isMem ? SymbolicAddress::MemCopy : SymbolicAddress::TableCopy; MDefinition* ret; if (!f.builtinInstanceMethodCall(callee, args, ValType::I32, &ret)) { return false; } if (!f.checkI32NegativeMeansFailedResult(ret)) { return false; } return true; } static bool EmitMemOrTableDrop(FunctionCompiler& f, bool isMem) { uint32_t segIndexVal = 0; if (!f.iter().readMemOrTableDrop(isMem, &segIndexVal)) { return false; } if (f.inDeadCode()) { return false; } uint32_t lineOrBytecode = f.readCallSiteLineOrBytecode(); CallCompileState args(f, lineOrBytecode); if (!f.startCall(&args)) { return false; } if (!f.passInstance(&args)) { return false; } MDefinition* segIndex = f.constant(Int32Value(int32_t(segIndexVal)), MIRType::Int32); if (!f.passArg(segIndex, ValType::I32, &args)) { return false; } if (!f.finishCall(&args)) { return false; } SymbolicAddress callee = isMem ? SymbolicAddress::MemDrop : SymbolicAddress::TableDrop; MDefinition* ret; if (!f.builtinInstanceMethodCall(callee, args, ValType::I32, &ret)) { return false; } if (!f.checkI32NegativeMeansFailedResult(ret)) { return false; } return true; } static bool EmitMemFill(FunctionCompiler& f) { MDefinition* start, *val, *len; if (!f.iter().readMemFill(&start, &val, &len)) { return false; } if (f.inDeadCode()) { return false; } uint32_t lineOrBytecode = f.readCallSiteLineOrBytecode(); CallCompileState args(f, lineOrBytecode); if (!f.startCall(&args)) { return false; } if (!f.passInstance(&args)) { return false; } if (!f.passArg(start, ValType::I32, &args)) { return false; } if (!f.passArg(val, ValType::I32, &args)) { return false; } if (!f.passArg(len, ValType::I32, &args)) { return false; } if (!f.finishCall(&args)) { return false; } MDefinition* ret; if (!f.builtinInstanceMethodCall(SymbolicAddress::MemFill, args, ValType::I32, &ret)) { return false; } if (!f.checkI32NegativeMeansFailedResult(ret)) { return false; } return true; } static bool EmitMemOrTableInit(FunctionCompiler& f, bool isMem) { uint32_t segIndexVal = 0; MDefinition* dstOff, *srcOff, *len; if (!f.iter().readMemOrTableInit(isMem, &segIndexVal, &dstOff, &srcOff, &len)) { return false; } if (f.inDeadCode()) { return false; } uint32_t lineOrBytecode = f.readCallSiteLineOrBytecode(); CallCompileState args(f, lineOrBytecode); if (!f.startCall(&args)) { return false; } if (!f.passInstance(&args)) { return false; } if (!f.passArg(dstOff, ValType::I32, &args)) { return false; } if (!f.passArg(srcOff, ValType::I32, &args)) { return false; } if (!f.passArg(len, ValType::I32, &args)) { return false; } MDefinition* segIndex = f.constant(Int32Value(int32_t(segIndexVal)), MIRType::Int32); if (!f.passArg(segIndex, ValType::I32, &args)) { return false; } if (!f.finishCall(&args)) { return false; } SymbolicAddress callee = isMem ? SymbolicAddress::MemInit : SymbolicAddress::TableInit; MDefinition* ret; if (!f.builtinInstanceMethodCall(callee, args, ValType::I32, &ret)) { return false; } if (!f.checkI32NegativeMeansFailedResult(ret)) { return false; } return true; } #endif // ENABLE_WASM_BULKMEM_OPS static bool EmitBodyExprs(FunctionCompiler& f) { if (!f.iter().readFunctionStart(f.funcType().ret())) { return false; } #define CHECK(c) \ if (!(c)) \ return false; \ break while (true) { if (!f.mirGen().ensureBallast()) { return false; } OpBytes op; if (!f.iter().readOp(&op)) { return false; } switch (op.b0) { case uint16_t(Op::End): if (!EmitEnd(f)) { return false; } if (f.iter().controlStackEmpty()) { if (f.inDeadCode() || IsVoid(f.funcType().ret())) { f.returnVoid(); } else { f.returnExpr(f.iter().getResult()); } return f.iter().readFunctionEnd(f.iter().end()); } break; // Control opcodes case uint16_t(Op::Unreachable): CHECK(EmitUnreachable(f)); case uint16_t(Op::Nop): CHECK(f.iter().readNop()); case uint16_t(Op::Block): CHECK(EmitBlock(f)); case uint16_t(Op::Loop): CHECK(EmitLoop(f)); case uint16_t(Op::If): CHECK(EmitIf(f)); case uint16_t(Op::Else): CHECK(EmitElse(f)); case uint16_t(Op::Br): CHECK(EmitBr(f)); case uint16_t(Op::BrIf): CHECK(EmitBrIf(f)); case uint16_t(Op::BrTable): CHECK(EmitBrTable(f)); case uint16_t(Op::Return): CHECK(EmitReturn(f)); // Calls case uint16_t(Op::Call): CHECK(EmitCall(f, /* asmJSFuncDef = */ false)); case uint16_t(Op::CallIndirect): CHECK(EmitCallIndirect(f, /* oldStyle = */ false)); // Parametric operators case uint16_t(Op::Drop): CHECK(f.iter().readDrop()); case uint16_t(Op::Select): CHECK(EmitSelect(f)); // Locals and globals case uint16_t(Op::GetLocal): CHECK(EmitGetLocal(f)); case uint16_t(Op::SetLocal): CHECK(EmitSetLocal(f)); case uint16_t(Op::TeeLocal): CHECK(EmitTeeLocal(f)); case uint16_t(Op::GetGlobal): CHECK(EmitGetGlobal(f)); case uint16_t(Op::SetGlobal): CHECK(EmitSetGlobal(f)); // Memory-related operators case uint16_t(Op::I32Load): CHECK(EmitLoad(f, ValType::I32, Scalar::Int32)); case uint16_t(Op::I64Load): CHECK(EmitLoad(f, ValType::I64, Scalar::Int64)); case uint16_t(Op::F32Load): CHECK(EmitLoad(f, ValType::F32, Scalar::Float32)); case uint16_t(Op::F64Load): CHECK(EmitLoad(f, ValType::F64, Scalar::Float64)); case uint16_t(Op::I32Load8S): CHECK(EmitLoad(f, ValType::I32, Scalar::Int8)); case uint16_t(Op::I32Load8U): CHECK(EmitLoad(f, ValType::I32, Scalar::Uint8)); case uint16_t(Op::I32Load16S): CHECK(EmitLoad(f, ValType::I32, Scalar::Int16)); case uint16_t(Op::I32Load16U): CHECK(EmitLoad(f, ValType::I32, Scalar::Uint16)); case uint16_t(Op::I64Load8S): CHECK(EmitLoad(f, ValType::I64, Scalar::Int8)); case uint16_t(Op::I64Load8U): CHECK(EmitLoad(f, ValType::I64, Scalar::Uint8)); case uint16_t(Op::I64Load16S): CHECK(EmitLoad(f, ValType::I64, Scalar::Int16)); case uint16_t(Op::I64Load16U): CHECK(EmitLoad(f, ValType::I64, Scalar::Uint16)); case uint16_t(Op::I64Load32S): CHECK(EmitLoad(f, ValType::I64, Scalar::Int32)); case uint16_t(Op::I64Load32U): CHECK(EmitLoad(f, ValType::I64, Scalar::Uint32)); case uint16_t(Op::I32Store): CHECK(EmitStore(f, ValType::I32, Scalar::Int32)); case uint16_t(Op::I64Store): CHECK(EmitStore(f, ValType::I64, Scalar::Int64)); case uint16_t(Op::F32Store): CHECK(EmitStore(f, ValType::F32, Scalar::Float32)); case uint16_t(Op::F64Store): CHECK(EmitStore(f, ValType::F64, Scalar::Float64)); case uint16_t(Op::I32Store8): CHECK(EmitStore(f, ValType::I32, Scalar::Int8)); case uint16_t(Op::I32Store16): CHECK(EmitStore(f, ValType::I32, Scalar::Int16)); case uint16_t(Op::I64Store8): CHECK(EmitStore(f, ValType::I64, Scalar::Int8)); case uint16_t(Op::I64Store16): CHECK(EmitStore(f, ValType::I64, Scalar::Int16)); case uint16_t(Op::I64Store32): CHECK(EmitStore(f, ValType::I64, Scalar::Int32)); case uint16_t(Op::CurrentMemory): CHECK(EmitCurrentMemory(f)); case uint16_t(Op::GrowMemory): CHECK(EmitGrowMemory(f)); // Constants case uint16_t(Op::I32Const): CHECK(EmitI32Const(f)); case uint16_t(Op::I64Const): CHECK(EmitI64Const(f)); case uint16_t(Op::F32Const): CHECK(EmitF32Const(f)); case uint16_t(Op::F64Const): CHECK(EmitF64Const(f)); // Comparison operators case uint16_t(Op::I32Eqz): CHECK(EmitConversion<MNot>(f, ValType::I32, ValType::I32)); case uint16_t(Op::I32Eq): CHECK(EmitComparison(f, ValType::I32, JSOP_EQ, MCompare::Compare_Int32)); case uint16_t(Op::I32Ne): CHECK(EmitComparison(f, ValType::I32, JSOP_NE, MCompare::Compare_Int32)); case uint16_t(Op::I32LtS): CHECK(EmitComparison(f, ValType::I32, JSOP_LT, MCompare::Compare_Int32)); case uint16_t(Op::I32LtU): CHECK(EmitComparison(f, ValType::I32, JSOP_LT, MCompare::Compare_UInt32)); case uint16_t(Op::I32GtS): CHECK(EmitComparison(f, ValType::I32, JSOP_GT, MCompare::Compare_Int32)); case uint16_t(Op::I32GtU): CHECK(EmitComparison(f, ValType::I32, JSOP_GT, MCompare::Compare_UInt32)); case uint16_t(Op::I32LeS): CHECK(EmitComparison(f, ValType::I32, JSOP_LE, MCompare::Compare_Int32)); case uint16_t(Op::I32LeU): CHECK(EmitComparison(f, ValType::I32, JSOP_LE, MCompare::Compare_UInt32)); case uint16_t(Op::I32GeS): CHECK(EmitComparison(f, ValType::I32, JSOP_GE, MCompare::Compare_Int32)); case uint16_t(Op::I32GeU): CHECK(EmitComparison(f, ValType::I32, JSOP_GE, MCompare::Compare_UInt32)); case uint16_t(Op::I64Eqz): CHECK(EmitConversion<MNot>(f, ValType::I64, ValType::I32)); case uint16_t(Op::I64Eq): CHECK(EmitComparison(f, ValType::I64, JSOP_EQ, MCompare::Compare_Int64)); case uint16_t(Op::I64Ne): CHECK(EmitComparison(f, ValType::I64, JSOP_NE, MCompare::Compare_Int64)); case uint16_t(Op::I64LtS): CHECK(EmitComparison(f, ValType::I64, JSOP_LT, MCompare::Compare_Int64)); case uint16_t(Op::I64LtU): CHECK(EmitComparison(f, ValType::I64, JSOP_LT, MCompare::Compare_UInt64)); case uint16_t(Op::I64GtS): CHECK(EmitComparison(f, ValType::I64, JSOP_GT, MCompare::Compare_Int64)); case uint16_t(Op::I64GtU): CHECK(EmitComparison(f, ValType::I64, JSOP_GT, MCompare::Compare_UInt64)); case uint16_t(Op::I64LeS): CHECK(EmitComparison(f, ValType::I64, JSOP_LE, MCompare::Compare_Int64)); case uint16_t(Op::I64LeU): CHECK(EmitComparison(f, ValType::I64, JSOP_LE, MCompare::Compare_UInt64)); case uint16_t(Op::I64GeS): CHECK(EmitComparison(f, ValType::I64, JSOP_GE, MCompare::Compare_Int64)); case uint16_t(Op::I64GeU): CHECK(EmitComparison(f, ValType::I64, JSOP_GE, MCompare::Compare_UInt64)); case uint16_t(Op::F32Eq): CHECK(EmitComparison(f, ValType::F32, JSOP_EQ, MCompare::Compare_Float32)); case uint16_t(Op::F32Ne): CHECK(EmitComparison(f, ValType::F32, JSOP_NE, MCompare::Compare_Float32)); case uint16_t(Op::F32Lt): CHECK(EmitComparison(f, ValType::F32, JSOP_LT, MCompare::Compare_Float32)); case uint16_t(Op::F32Gt): CHECK(EmitComparison(f, ValType::F32, JSOP_GT, MCompare::Compare_Float32)); case uint16_t(Op::F32Le): CHECK(EmitComparison(f, ValType::F32, JSOP_LE, MCompare::Compare_Float32)); case uint16_t(Op::F32Ge): CHECK(EmitComparison(f, ValType::F32, JSOP_GE, MCompare::Compare_Float32)); case uint16_t(Op::F64Eq): CHECK(EmitComparison(f, ValType::F64, JSOP_EQ, MCompare::Compare_Double)); case uint16_t(Op::F64Ne): CHECK(EmitComparison(f, ValType::F64, JSOP_NE, MCompare::Compare_Double)); case uint16_t(Op::F64Lt): CHECK(EmitComparison(f, ValType::F64, JSOP_LT, MCompare::Compare_Double)); case uint16_t(Op::F64Gt): CHECK(EmitComparison(f, ValType::F64, JSOP_GT, MCompare::Compare_Double)); case uint16_t(Op::F64Le): CHECK(EmitComparison(f, ValType::F64, JSOP_LE, MCompare::Compare_Double)); case uint16_t(Op::F64Ge): CHECK(EmitComparison(f, ValType::F64, JSOP_GE, MCompare::Compare_Double)); // Numeric operators case uint16_t(Op::I32Clz): CHECK(EmitUnaryWithType<MClz>(f, ValType::I32, MIRType::Int32)); case uint16_t(Op::I32Ctz): CHECK(EmitUnaryWithType<MCtz>(f, ValType::I32, MIRType::Int32)); case uint16_t(Op::I32Popcnt): CHECK(EmitUnaryWithType<MPopcnt>(f, ValType::I32, MIRType::Int32)); case uint16_t(Op::I32Add): CHECK(EmitAdd(f, ValType::I32, MIRType::Int32)); case uint16_t(Op::I32Sub): CHECK(EmitSub(f, ValType::I32, MIRType::Int32)); case uint16_t(Op::I32Mul): CHECK(EmitMul(f, ValType::I32, MIRType::Int32)); case uint16_t(Op::I32DivS): case uint16_t(Op::I32DivU): CHECK(EmitDiv(f, ValType::I32, MIRType::Int32, Op(op.b0) == Op::I32DivU)); case uint16_t(Op::I32RemS): case uint16_t(Op::I32RemU): CHECK(EmitRem(f, ValType::I32, MIRType::Int32, Op(op.b0) == Op::I32RemU)); case uint16_t(Op::I32And): CHECK(EmitBitwise<MBitAnd>(f, ValType::I32, MIRType::Int32)); case uint16_t(Op::I32Or): CHECK(EmitBitwise<MBitOr>(f, ValType::I32, MIRType::Int32)); case uint16_t(Op::I32Xor): CHECK(EmitBitwise<MBitXor>(f, ValType::I32, MIRType::Int32)); case uint16_t(Op::I32Shl): CHECK(EmitBitwise<MLsh>(f, ValType::I32, MIRType::Int32)); case uint16_t(Op::I32ShrS): CHECK(EmitBitwise<MRsh>(f, ValType::I32, MIRType::Int32)); case uint16_t(Op::I32ShrU): CHECK(EmitBitwise<MUrsh>(f, ValType::I32, MIRType::Int32)); case uint16_t(Op::I32Rotl): case uint16_t(Op::I32Rotr): CHECK(EmitRotate(f, ValType::I32, Op(op.b0) == Op::I32Rotl)); case uint16_t(Op::I64Clz): CHECK(EmitUnaryWithType<MClz>(f, ValType::I64, MIRType::Int64)); case uint16_t(Op::I64Ctz): CHECK(EmitUnaryWithType<MCtz>(f, ValType::I64, MIRType::Int64)); case uint16_t(Op::I64Popcnt): CHECK(EmitUnaryWithType<MPopcnt>(f, ValType::I64, MIRType::Int64)); case uint16_t(Op::I64Add): CHECK(EmitAdd(f, ValType::I64, MIRType::Int64)); case uint16_t(Op::I64Sub): CHECK(EmitSub(f, ValType::I64, MIRType::Int64)); case uint16_t(Op::I64Mul): CHECK(EmitMul(f, ValType::I64, MIRType::Int64)); case uint16_t(Op::I64DivS): case uint16_t(Op::I64DivU): CHECK(EmitDiv(f, ValType::I64, MIRType::Int64, Op(op.b0) == Op::I64DivU)); case uint16_t(Op::I64RemS): case uint16_t(Op::I64RemU): CHECK(EmitRem(f, ValType::I64, MIRType::Int64, Op(op.b0) == Op::I64RemU)); case uint16_t(Op::I64And): CHECK(EmitBitwise<MBitAnd>(f, ValType::I64, MIRType::Int64)); case uint16_t(Op::I64Or): CHECK(EmitBitwise<MBitOr>(f, ValType::I64, MIRType::Int64)); case uint16_t(Op::I64Xor): CHECK(EmitBitwise<MBitXor>(f, ValType::I64, MIRType::Int64)); case uint16_t(Op::I64Shl): CHECK(EmitBitwise<MLsh>(f, ValType::I64, MIRType::Int64)); case uint16_t(Op::I64ShrS): CHECK(EmitBitwise<MRsh>(f, ValType::I64, MIRType::Int64)); case uint16_t(Op::I64ShrU): CHECK(EmitBitwise<MUrsh>(f, ValType::I64, MIRType::Int64)); case uint16_t(Op::I64Rotl): case uint16_t(Op::I64Rotr): CHECK(EmitRotate(f, ValType::I64, Op(op.b0) == Op::I64Rotl)); case uint16_t(Op::F32Abs): CHECK(EmitUnaryWithType<MAbs>(f, ValType::F32, MIRType::Float32)); case uint16_t(Op::F32Neg): CHECK(EmitUnaryWithType<MWasmNeg>(f, ValType::F32, MIRType::Float32)); case uint16_t(Op::F32Ceil): CHECK(EmitUnaryMathBuiltinCall(f, SymbolicAddress::CeilF, ValType::F32)); case uint16_t(Op::F32Floor): CHECK(EmitUnaryMathBuiltinCall(f, SymbolicAddress::FloorF, ValType::F32)); case uint16_t(Op::F32Trunc): CHECK(EmitUnaryMathBuiltinCall(f, SymbolicAddress::TruncF, ValType::F32)); case uint16_t(Op::F32Nearest): CHECK(EmitUnaryMathBuiltinCall(f, SymbolicAddress::NearbyIntF, ValType::F32)); case uint16_t(Op::F32Sqrt): CHECK(EmitUnaryWithType<MSqrt>(f, ValType::F32, MIRType::Float32)); case uint16_t(Op::F32Add): CHECK(EmitAdd(f, ValType::F32, MIRType::Float32)); case uint16_t(Op::F32Sub): CHECK(EmitSub(f, ValType::F32, MIRType::Float32)); case uint16_t(Op::F32Mul): CHECK(EmitMul(f, ValType::F32, MIRType::Float32)); case uint16_t(Op::F32Div): CHECK(EmitDiv(f, ValType::F32, MIRType::Float32, /* isUnsigned = */ false)); case uint16_t(Op::F32Min): case uint16_t(Op::F32Max): CHECK(EmitMinMax(f, ValType::F32, MIRType::Float32, Op(op.b0) == Op::F32Max)); case uint16_t(Op::F32CopySign): CHECK(EmitCopySign(f, ValType::F32)); case uint16_t(Op::F64Abs): CHECK(EmitUnaryWithType<MAbs>(f, ValType::F64, MIRType::Double)); case uint16_t(Op::F64Neg): CHECK(EmitUnaryWithType<MWasmNeg>(f, ValType::F64, MIRType::Double)); case uint16_t(Op::F64Ceil): CHECK(EmitUnaryMathBuiltinCall(f, SymbolicAddress::CeilD, ValType::F64)); case uint16_t(Op::F64Floor): CHECK(EmitUnaryMathBuiltinCall(f, SymbolicAddress::FloorD, ValType::F64)); case uint16_t(Op::F64Trunc): CHECK(EmitUnaryMathBuiltinCall(f, SymbolicAddress::TruncD, ValType::F64)); case uint16_t(Op::F64Nearest): CHECK(EmitUnaryMathBuiltinCall(f, SymbolicAddress::NearbyIntD, ValType::F64)); case uint16_t(Op::F64Sqrt): CHECK(EmitUnaryWithType<MSqrt>(f, ValType::F64, MIRType::Double)); case uint16_t(Op::F64Add): CHECK(EmitAdd(f, ValType::F64, MIRType::Double)); case uint16_t(Op::F64Sub): CHECK(EmitSub(f, ValType::F64, MIRType::Double)); case uint16_t(Op::F64Mul): CHECK(EmitMul(f, ValType::F64, MIRType::Double)); case uint16_t(Op::F64Div): CHECK(EmitDiv(f, ValType::F64, MIRType::Double, /* isUnsigned = */ false)); case uint16_t(Op::F64Min): case uint16_t(Op::F64Max): CHECK(EmitMinMax(f, ValType::F64, MIRType::Double, Op(op.b0) == Op::F64Max)); case uint16_t(Op::F64CopySign): CHECK(EmitCopySign(f, ValType::F64)); // Conversions case uint16_t(Op::I32WrapI64): CHECK(EmitConversion<MWrapInt64ToInt32>(f, ValType::I64, ValType::I32)); case uint16_t(Op::I32TruncSF32): case uint16_t(Op::I32TruncUF32): CHECK(EmitTruncate(f, ValType::F32, ValType::I32, Op(op.b0) == Op::I32TruncUF32, false)); case uint16_t(Op::I32TruncSF64): case uint16_t(Op::I32TruncUF64): CHECK(EmitTruncate(f, ValType::F64, ValType::I32, Op(op.b0) == Op::I32TruncUF64, false)); case uint16_t(Op::I64ExtendSI32): case uint16_t(Op::I64ExtendUI32): CHECK(EmitExtendI32(f, Op(op.b0) == Op::I64ExtendUI32)); case uint16_t(Op::I64TruncSF32): case uint16_t(Op::I64TruncUF32): CHECK(EmitTruncate(f, ValType::F32, ValType::I64, Op(op.b0) == Op::I64TruncUF32, false)); case uint16_t(Op::I64TruncSF64): case uint16_t(Op::I64TruncUF64): CHECK(EmitTruncate(f, ValType::F64, ValType::I64, Op(op.b0) == Op::I64TruncUF64, false)); case uint16_t(Op::F32ConvertSI32): CHECK(EmitConversion<MToFloat32>(f, ValType::I32, ValType::F32)); case uint16_t(Op::F32ConvertUI32): CHECK(EmitConversion<MWasmUnsignedToFloat32>(f, ValType::I32, ValType::F32)); case uint16_t(Op::F32ConvertSI64): case uint16_t(Op::F32ConvertUI64): CHECK(EmitConvertI64ToFloatingPoint(f, ValType::F32, MIRType::Float32, Op(op.b0) == Op::F32ConvertUI64)); case uint16_t(Op::F32DemoteF64): CHECK(EmitConversion<MToFloat32>(f, ValType::F64, ValType::F32)); case uint16_t(Op::F64ConvertSI32): CHECK(EmitConversion<MToDouble>(f, ValType::I32, ValType::F64)); case uint16_t(Op::F64ConvertUI32): CHECK(EmitConversion<MWasmUnsignedToDouble>(f, ValType::I32, ValType::F64)); case uint16_t(Op::F64ConvertSI64): case uint16_t(Op::F64ConvertUI64): CHECK(EmitConvertI64ToFloatingPoint(f, ValType::F64, MIRType::Double, Op(op.b0) == Op::F64ConvertUI64)); case uint16_t(Op::F64PromoteF32): CHECK(EmitConversion<MToDouble>(f, ValType::F32, ValType::F64)); // Reinterpretations case uint16_t(Op::I32ReinterpretF32): CHECK(EmitReinterpret(f, ValType::I32, ValType::F32, MIRType::Int32)); case uint16_t(Op::I64ReinterpretF64): CHECK(EmitReinterpret(f, ValType::I64, ValType::F64, MIRType::Int64)); case uint16_t(Op::F32ReinterpretI32): CHECK(EmitReinterpret(f, ValType::F32, ValType::I32, MIRType::Float32)); case uint16_t(Op::F64ReinterpretI64): CHECK(EmitReinterpret(f, ValType::F64, ValType::I64, MIRType::Double)); #ifdef ENABLE_WASM_GC case uint16_t(Op::RefEq): case uint16_t(Op::RefNull): case uint16_t(Op::RefIsNull): // Not yet supported return f.iter().unrecognizedOpcode(&op); #endif // Sign extensions case uint16_t(Op::I32Extend8S): CHECK(EmitSignExtend(f, 1, 4)); case uint16_t(Op::I32Extend16S): CHECK(EmitSignExtend(f, 2, 4)); case uint16_t(Op::I64Extend8S): CHECK(EmitSignExtend(f, 1, 8)); case uint16_t(Op::I64Extend16S): CHECK(EmitSignExtend(f, 2, 8)); case uint16_t(Op::I64Extend32S): CHECK(EmitSignExtend(f, 4, 8)); // Miscellaneous operations case uint16_t(Op::MiscPrefix): { switch (op.b1) { case uint16_t(MiscOp::I32TruncSSatF32): case uint16_t(MiscOp::I32TruncUSatF32): CHECK(EmitTruncate(f, ValType::F32, ValType::I32, MiscOp(op.b1) == MiscOp::I32TruncUSatF32, true)); case uint16_t(MiscOp::I32TruncSSatF64): case uint16_t(MiscOp::I32TruncUSatF64): CHECK(EmitTruncate(f, ValType::F64, ValType::I32, MiscOp(op.b1) == MiscOp::I32TruncUSatF64, true)); case uint16_t(MiscOp::I64TruncSSatF32): case uint16_t(MiscOp::I64TruncUSatF32): CHECK(EmitTruncate(f, ValType::F32, ValType::I64, MiscOp(op.b1) == MiscOp::I64TruncUSatF32, true)); case uint16_t(MiscOp::I64TruncSSatF64): case uint16_t(MiscOp::I64TruncUSatF64): CHECK(EmitTruncate(f, ValType::F64, ValType::I64, MiscOp(op.b1) == MiscOp::I64TruncUSatF64, true)); #ifdef ENABLE_WASM_BULKMEM_OPS case uint16_t(MiscOp::MemCopy): CHECK(EmitMemOrTableCopy(f, /*isMem=*/true)); case uint16_t(MiscOp::MemDrop): CHECK(EmitMemOrTableDrop(f, /*isMem=*/true)); case uint16_t(MiscOp::MemFill): CHECK(EmitMemFill(f)); case uint16_t(MiscOp::MemInit): CHECK(EmitMemOrTableInit(f, /*isMem=*/true)); case uint16_t(MiscOp::TableCopy): CHECK(EmitMemOrTableCopy(f, /*isMem=*/false)); case uint16_t(MiscOp::TableDrop): CHECK(EmitMemOrTableDrop(f, /*isMem=*/false)); case uint16_t(MiscOp::TableInit): CHECK(EmitMemOrTableInit(f, /*isMem=*/false)); #endif #ifdef ENABLE_WASM_GC case uint16_t(MiscOp::StructNew): case uint16_t(MiscOp::StructGet): case uint16_t(MiscOp::StructSet): case uint16_t(MiscOp::StructNarrow): // Not yet supported return f.iter().unrecognizedOpcode(&op); #endif default: return f.iter().unrecognizedOpcode(&op); } break; } // Thread operations case uint16_t(Op::ThreadPrefix): { #ifdef ENABLE_WASM_THREAD_OPS switch (op.b1) { case uint16_t(ThreadOp::Wake): CHECK(EmitWake(f)); case uint16_t(ThreadOp::I32Wait): CHECK(EmitWait(f, ValType::I32, 4)); case uint16_t(ThreadOp::I64Wait): CHECK(EmitWait(f, ValType::I64, 8)); case uint16_t(ThreadOp::I32AtomicLoad): CHECK(EmitAtomicLoad(f, ValType::I32, Scalar::Int32)); case uint16_t(ThreadOp::I64AtomicLoad): CHECK(EmitAtomicLoad(f, ValType::I64, Scalar::Int64)); case uint16_t(ThreadOp::I32AtomicLoad8U): CHECK(EmitAtomicLoad(f, ValType::I32, Scalar::Uint8)); case uint16_t(ThreadOp::I32AtomicLoad16U): CHECK(EmitAtomicLoad(f, ValType::I32, Scalar::Uint16)); case uint16_t(ThreadOp::I64AtomicLoad8U): CHECK(EmitAtomicLoad(f, ValType::I64, Scalar::Uint8)); case uint16_t(ThreadOp::I64AtomicLoad16U): CHECK(EmitAtomicLoad(f, ValType::I64, Scalar::Uint16)); case uint16_t(ThreadOp::I64AtomicLoad32U): CHECK(EmitAtomicLoad(f, ValType::I64, Scalar::Uint32)); case uint16_t(ThreadOp::I32AtomicStore): CHECK(EmitAtomicStore(f, ValType::I32, Scalar::Int32)); case uint16_t(ThreadOp::I64AtomicStore): CHECK(EmitAtomicStore(f, ValType::I64, Scalar::Int64)); case uint16_t(ThreadOp::I32AtomicStore8U): CHECK(EmitAtomicStore(f, ValType::I32, Scalar::Uint8)); case uint16_t(ThreadOp::I32AtomicStore16U): CHECK(EmitAtomicStore(f, ValType::I32, Scalar::Uint16)); case uint16_t(ThreadOp::I64AtomicStore8U): CHECK(EmitAtomicStore(f, ValType::I64, Scalar::Uint8)); case uint16_t(ThreadOp::I64AtomicStore16U): CHECK(EmitAtomicStore(f, ValType::I64, Scalar::Uint16)); case uint16_t(ThreadOp::I64AtomicStore32U): CHECK(EmitAtomicStore(f, ValType::I64, Scalar::Uint32)); case uint16_t(ThreadOp::I32AtomicAdd): CHECK(EmitAtomicRMW(f, ValType::I32, Scalar::Int32, AtomicFetchAddOp)); case uint16_t(ThreadOp::I64AtomicAdd): CHECK(EmitAtomicRMW(f, ValType::I64, Scalar::Int64, AtomicFetchAddOp)); case uint16_t(ThreadOp::I32AtomicAdd8U): CHECK(EmitAtomicRMW(f, ValType::I32, Scalar::Uint8, AtomicFetchAddOp)); case uint16_t(ThreadOp::I32AtomicAdd16U): CHECK(EmitAtomicRMW(f, ValType::I32, Scalar::Uint16, AtomicFetchAddOp)); case uint16_t(ThreadOp::I64AtomicAdd8U): CHECK(EmitAtomicRMW(f, ValType::I64, Scalar::Uint8, AtomicFetchAddOp)); case uint16_t(ThreadOp::I64AtomicAdd16U): CHECK(EmitAtomicRMW(f, ValType::I64, Scalar::Uint16, AtomicFetchAddOp)); case uint16_t(ThreadOp::I64AtomicAdd32U): CHECK(EmitAtomicRMW(f, ValType::I64, Scalar::Uint32, AtomicFetchAddOp)); case uint16_t(ThreadOp::I32AtomicSub): CHECK(EmitAtomicRMW(f, ValType::I32, Scalar::Int32, AtomicFetchSubOp)); case uint16_t(ThreadOp::I64AtomicSub): CHECK(EmitAtomicRMW(f, ValType::I64, Scalar::Int64, AtomicFetchSubOp)); case uint16_t(ThreadOp::I32AtomicSub8U): CHECK(EmitAtomicRMW(f, ValType::I32, Scalar::Uint8, AtomicFetchSubOp)); case uint16_t(ThreadOp::I32AtomicSub16U): CHECK(EmitAtomicRMW(f, ValType::I32, Scalar::Uint16, AtomicFetchSubOp)); case uint16_t(ThreadOp::I64AtomicSub8U): CHECK(EmitAtomicRMW(f, ValType::I64, Scalar::Uint8, AtomicFetchSubOp)); case uint16_t(ThreadOp::I64AtomicSub16U): CHECK(EmitAtomicRMW(f, ValType::I64, Scalar::Uint16, AtomicFetchSubOp)); case uint16_t(ThreadOp::I64AtomicSub32U): CHECK(EmitAtomicRMW(f, ValType::I64, Scalar::Uint32, AtomicFetchSubOp)); case uint16_t(ThreadOp::I32AtomicAnd): CHECK(EmitAtomicRMW(f, ValType::I32, Scalar::Int32, AtomicFetchAndOp)); case uint16_t(ThreadOp::I64AtomicAnd): CHECK(EmitAtomicRMW(f, ValType::I64, Scalar::Int64, AtomicFetchAndOp)); case uint16_t(ThreadOp::I32AtomicAnd8U): CHECK(EmitAtomicRMW(f, ValType::I32, Scalar::Uint8, AtomicFetchAndOp)); case uint16_t(ThreadOp::I32AtomicAnd16U): CHECK(EmitAtomicRMW(f, ValType::I32, Scalar::Uint16, AtomicFetchAndOp)); case uint16_t(ThreadOp::I64AtomicAnd8U): CHECK(EmitAtomicRMW(f, ValType::I64, Scalar::Uint8, AtomicFetchAndOp)); case uint16_t(ThreadOp::I64AtomicAnd16U): CHECK(EmitAtomicRMW(f, ValType::I64, Scalar::Uint16, AtomicFetchAndOp)); case uint16_t(ThreadOp::I64AtomicAnd32U): CHECK(EmitAtomicRMW(f, ValType::I64, Scalar::Uint32, AtomicFetchAndOp)); case uint16_t(ThreadOp::I32AtomicOr): CHECK(EmitAtomicRMW(f, ValType::I32, Scalar::Int32, AtomicFetchOrOp)); case uint16_t(ThreadOp::I64AtomicOr): CHECK(EmitAtomicRMW(f, ValType::I64, Scalar::Int64, AtomicFetchOrOp)); case uint16_t(ThreadOp::I32AtomicOr8U): CHECK(EmitAtomicRMW(f, ValType::I32, Scalar::Uint8, AtomicFetchOrOp)); case uint16_t(ThreadOp::I32AtomicOr16U): CHECK(EmitAtomicRMW(f, ValType::I32, Scalar::Uint16, AtomicFetchOrOp)); case uint16_t(ThreadOp::I64AtomicOr8U): CHECK(EmitAtomicRMW(f, ValType::I64, Scalar::Uint8, AtomicFetchOrOp)); case uint16_t(ThreadOp::I64AtomicOr16U): CHECK(EmitAtomicRMW(f, ValType::I64, Scalar::Uint16, AtomicFetchOrOp)); case uint16_t(ThreadOp::I64AtomicOr32U): CHECK(EmitAtomicRMW(f, ValType::I64, Scalar::Uint32, AtomicFetchOrOp)); case uint16_t(ThreadOp::I32AtomicXor): CHECK(EmitAtomicRMW(f, ValType::I32, Scalar::Int32, AtomicFetchXorOp)); case uint16_t(ThreadOp::I64AtomicXor): CHECK(EmitAtomicRMW(f, ValType::I64, Scalar::Int64, AtomicFetchXorOp)); case uint16_t(ThreadOp::I32AtomicXor8U): CHECK(EmitAtomicRMW(f, ValType::I32, Scalar::Uint8, AtomicFetchXorOp)); case uint16_t(ThreadOp::I32AtomicXor16U): CHECK(EmitAtomicRMW(f, ValType::I32, Scalar::Uint16, AtomicFetchXorOp)); case uint16_t(ThreadOp::I64AtomicXor8U): CHECK(EmitAtomicRMW(f, ValType::I64, Scalar::Uint8, AtomicFetchXorOp)); case uint16_t(ThreadOp::I64AtomicXor16U): CHECK(EmitAtomicRMW(f, ValType::I64, Scalar::Uint16, AtomicFetchXorOp)); case uint16_t(ThreadOp::I64AtomicXor32U): CHECK(EmitAtomicRMW(f, ValType::I64, Scalar::Uint32, AtomicFetchXorOp)); case uint16_t(ThreadOp::I32AtomicXchg): CHECK(EmitAtomicXchg(f, ValType::I32, Scalar::Int32)); case uint16_t(ThreadOp::I64AtomicXchg): CHECK(EmitAtomicXchg(f, ValType::I64, Scalar::Int64)); case uint16_t(ThreadOp::I32AtomicXchg8U): CHECK(EmitAtomicXchg(f, ValType::I32, Scalar::Uint8)); case uint16_t(ThreadOp::I32AtomicXchg16U): CHECK(EmitAtomicXchg(f, ValType::I32, Scalar::Uint16)); case uint16_t(ThreadOp::I64AtomicXchg8U): CHECK(EmitAtomicXchg(f, ValType::I64, Scalar::Uint8)); case uint16_t(ThreadOp::I64AtomicXchg16U): CHECK(EmitAtomicXchg(f, ValType::I64, Scalar::Uint16)); case uint16_t(ThreadOp::I64AtomicXchg32U): CHECK(EmitAtomicXchg(f, ValType::I64, Scalar::Uint32)); case uint16_t(ThreadOp::I32AtomicCmpXchg): CHECK(EmitAtomicCmpXchg(f, ValType::I32, Scalar::Int32)); case uint16_t(ThreadOp::I64AtomicCmpXchg): CHECK(EmitAtomicCmpXchg(f, ValType::I64, Scalar::Int64)); case uint16_t(ThreadOp::I32AtomicCmpXchg8U): CHECK(EmitAtomicCmpXchg(f, ValType::I32, Scalar::Uint8)); case uint16_t(ThreadOp::I32AtomicCmpXchg16U): CHECK(EmitAtomicCmpXchg(f, ValType::I32, Scalar::Uint16)); case uint16_t(ThreadOp::I64AtomicCmpXchg8U): CHECK(EmitAtomicCmpXchg(f, ValType::I64, Scalar::Uint8)); case uint16_t(ThreadOp::I64AtomicCmpXchg16U): CHECK(EmitAtomicCmpXchg(f, ValType::I64, Scalar::Uint16)); case uint16_t(ThreadOp::I64AtomicCmpXchg32U): CHECK(EmitAtomicCmpXchg(f, ValType::I64, Scalar::Uint32)); default: return f.iter().unrecognizedOpcode(&op); } #else return f.iter().unrecognizedOpcode(&op); #endif // ENABLE_WASM_THREAD_OPS break; } // asm.js-specific operators case uint16_t(Op::MozPrefix): { if (!f.env().isAsmJS()) { return f.iter().unrecognizedOpcode(&op); } switch (op.b1) { case uint16_t(MozOp::TeeGlobal): CHECK(EmitTeeGlobal(f)); case uint16_t(MozOp::I32Min): case uint16_t(MozOp::I32Max): CHECK(EmitMinMax(f, ValType::I32, MIRType::Int32, MozOp(op.b1) == MozOp::I32Max)); case uint16_t(MozOp::I32Neg): CHECK(EmitUnaryWithType<MWasmNeg>(f, ValType::I32, MIRType::Int32)); case uint16_t(MozOp::I32BitNot): CHECK(EmitBitNot(f, ValType::I32)); case uint16_t(MozOp::I32Abs): CHECK(EmitUnaryWithType<MAbs>(f, ValType::I32, MIRType::Int32)); case uint16_t(MozOp::F32TeeStoreF64): CHECK(EmitTeeStoreWithCoercion(f, ValType::F32, Scalar::Float64)); case uint16_t(MozOp::F64TeeStoreF32): CHECK(EmitTeeStoreWithCoercion(f, ValType::F64, Scalar::Float32)); case uint16_t(MozOp::I32TeeStore8): CHECK(EmitTeeStore(f, ValType::I32, Scalar::Int8)); case uint16_t(MozOp::I32TeeStore16): CHECK(EmitTeeStore(f, ValType::I32, Scalar::Int16)); case uint16_t(MozOp::I64TeeStore8): CHECK(EmitTeeStore(f, ValType::I64, Scalar::Int8)); case uint16_t(MozOp::I64TeeStore16): CHECK(EmitTeeStore(f, ValType::I64, Scalar::Int16)); case uint16_t(MozOp::I64TeeStore32): CHECK(EmitTeeStore(f, ValType::I64, Scalar::Int32)); case uint16_t(MozOp::I32TeeStore): CHECK(EmitTeeStore(f, ValType::I32, Scalar::Int32)); case uint16_t(MozOp::I64TeeStore): CHECK(EmitTeeStore(f, ValType::I64, Scalar::Int64)); case uint16_t(MozOp::F32TeeStore): CHECK(EmitTeeStore(f, ValType::F32, Scalar::Float32)); case uint16_t(MozOp::F64TeeStore): CHECK(EmitTeeStore(f, ValType::F64, Scalar::Float64)); case uint16_t(MozOp::F64Mod): CHECK(EmitRem(f, ValType::F64, MIRType::Double, /* isUnsigned = */ false)); case uint16_t(MozOp::F64Sin): CHECK(EmitUnaryMathBuiltinCall(f, SymbolicAddress::SinD, ValType::F64)); case uint16_t(MozOp::F64Cos): CHECK(EmitUnaryMathBuiltinCall(f, SymbolicAddress::CosD, ValType::F64)); case uint16_t(MozOp::F64Tan): CHECK(EmitUnaryMathBuiltinCall(f, SymbolicAddress::TanD, ValType::F64)); case uint16_t(MozOp::F64Asin): CHECK(EmitUnaryMathBuiltinCall(f, SymbolicAddress::ASinD, ValType::F64)); case uint16_t(MozOp::F64Acos): CHECK(EmitUnaryMathBuiltinCall(f, SymbolicAddress::ACosD, ValType::F64)); case uint16_t(MozOp::F64Atan): CHECK(EmitUnaryMathBuiltinCall(f, SymbolicAddress::ATanD, ValType::F64)); case uint16_t(MozOp::F64Exp): CHECK(EmitUnaryMathBuiltinCall(f, SymbolicAddress::ExpD, ValType::F64)); case uint16_t(MozOp::F64Log): CHECK(EmitUnaryMathBuiltinCall(f, SymbolicAddress::LogD, ValType::F64)); case uint16_t(MozOp::F64Pow): CHECK(EmitBinaryMathBuiltinCall(f, SymbolicAddress::PowD, ValType::F64)); case uint16_t(MozOp::F64Atan2): CHECK(EmitBinaryMathBuiltinCall(f, SymbolicAddress::ATan2D, ValType::F64)); case uint16_t(MozOp::OldCallDirect): CHECK(EmitCall(f, /* asmJSFuncDef = */ true)); case uint16_t(MozOp::OldCallIndirect): CHECK(EmitCallIndirect(f, /* oldStyle = */ true)); default: return f.iter().unrecognizedOpcode(&op); } break; } default: return f.iter().unrecognizedOpcode(&op); } } MOZ_CRASH("unreachable"); #undef CHECK } bool wasm::IonCompileFunctions(const ModuleEnvironment& env, LifoAlloc& lifo, const FuncCompileInputVector& inputs, CompiledCode* code, ExclusiveDeferredValidationState& dvs, UniqueChars* error) { MOZ_ASSERT(env.tier() == Tier::Optimized); MOZ_ASSERT(env.optimizedBackend() == OptimizedBackend::Ion); TempAllocator alloc(&lifo); JitContext jitContext(&alloc); MOZ_ASSERT(IsCompilingWasm()); WasmMacroAssembler masm(alloc); // Swap in already-allocated empty vectors to avoid malloc/free. MOZ_ASSERT(code->empty()); if (!code->swap(masm)) { return false; } for (const FuncCompileInput& func : inputs) { Decoder d(func.begin, func.end, func.lineOrBytecode, error); // Build the local types vector. ValTypeVector locals; if (!locals.appendAll(env.funcTypes[func.index]->args())) { return false; } if (!DecodeLocalEntries(d, env.kind, env.types, env.gcTypesEnabled(), &locals)) { return false; } // Set up for Ion compilation. const JitCompileOptions options; MIRGraph graph(&alloc); CompileInfo compileInfo(locals.length()); MIRGenerator mir(nullptr, options, &alloc, &graph, &compileInfo, IonOptimizations.get(OptimizationLevel::Wasm)); mir.initMinWasmHeapLength(env.minMemoryLength); // Build MIR graph { FunctionCompiler f(env, d, dvs, func, locals, mir); if (!f.init()) { return false; } if (!f.startBlock()) { return false; } if (!EmitBodyExprs(f)) { return false; } f.finish(); } // Compile MIR graph { jit::SpewBeginFunction(&mir, nullptr); jit::AutoSpewEndFunction spewEndFunction(&mir); if (!OptimizeMIR(&mir)) { return false; } LIRGraph* lir = GenerateLIR(&mir); if (!lir) { return false; } FuncTypeIdDesc funcTypeId = env.funcTypes[func.index]->id; CodeGenerator codegen(&mir, lir, &masm); BytecodeOffset prologueTrapOffset(func.lineOrBytecode); FuncOffsets offsets; if (!codegen.generateWasm(funcTypeId, prologueTrapOffset, &offsets)) { return false; } if (!code->codeRanges.emplaceBack(func.index, func.lineOrBytecode, offsets)) { return false; } } } masm.finish(); if (masm.oom()) { return false; } return code->swap(masm); } bool js::wasm::IonCanCompile() { #if !defined(JS_CODEGEN_NONE) && !defined(JS_CODEGEN_ARM64) return true; #else return false; #endif }
31.839519
117
0.580149
[ "object", "vector" ]
b6dd202fa715038faea0f4e4c367d5e359adad39
3,225
cpp
C++
solutions/1806/20111111T164028Z-3967114.cpp
Mistereo/timus-solutions
062540304c33312b75e0e8713c4b36c80fb220ab
[ "MIT" ]
11
2019-10-29T15:34:53.000Z
2022-03-14T14:45:09.000Z
solutions/1806/20111111T164028Z-3967114.cpp
Mistereo/timus-solutions
062540304c33312b75e0e8713c4b36c80fb220ab
[ "MIT" ]
null
null
null
solutions/1806/20111111T164028Z-3967114.cpp
Mistereo/timus-solutions
062540304c33312b75e0e8713c4b36c80fb220ab
[ "MIT" ]
6
2018-06-30T12:06:55.000Z
2021-03-20T08:46:33.000Z
#include <iostream> #include <string> #include <vector> #include <map> #include <algorithm> #include <set> using namespace std; const int INF = 1000000000; int n; vector<pair<int, int> > *G; pair<string, int> *T; void addToG(string s, int index, int xxx); int binarySearch(int left, int right, string s); int main (int argc, const char * argv[]) { scanf("%d", &n); int time[10]; T = new pair<string, int>[n]; for (int i=0; i<10; i++) scanf("%d", &time[i]); for (int i=0; i<n; i++) { char tmp[11]; scanf("%s", tmp); T[i].first = tmp; T[i].second = i; } sort(T, T+n); G = new vector<pair<int, int> >[n]; for (int i=0; i<n; i++) { addToG(T[i].first, T[i].second, i); } int *d = new int[n]; int *p = new int[n]; fill(p, p+n, -1); fill(d, d+n, INF); d[0] = 0; set<pair<int, int> > S; S.insert(make_pair(d[0],0)); while (!S.empty()) { int v = S.begin()->second; S.erase(S.begin()); if (d[v] == INF) { break; } for (int i=0; i<G[v].size(); i++) { int to = G[v][i].first; int weight = time[(G[v][i].second)]; if (d[v] + weight < d[to]) { S.erase(make_pair(d[to], to)); d[to] = d[v] + time[(G[v][i].second)]; p[to] = v; S.insert(make_pair(d[to], to)); } } } if (d[n-1]==INF) { printf("-1"); return 0; } else { vector<int> path; for (int i=n-1; i!=0; i=p[i]) path.push_back(i+1); path.push_back(1); printf("%d\n%d\n", d[n-1], (int)path.size()); for (int i=(int)path.size()-1; i>=0; i--) printf("%d ", path[i]); } return 0; } void addToG(string s, int index, int xxx) { for (int i=0; i<10; i++) { char d = '0'; for (int j=0; j<10; j++) { if ((d+j)!=s[i]) { string tmp = s; tmp[i] = d + j; int result = binarySearch(xxx + 1, n-1, tmp); if (result != -1) { G[index].push_back(make_pair(result, i)); G[result].push_back(make_pair(index, i)); } } if (i < j && s[i] != s[j]) { string tmp = s; char x = tmp[i]; tmp[i] = tmp[j]; tmp[j] = x; int result = binarySearch(xxx + 1, n-1, tmp); if (result != -1) { G[index].push_back(make_pair(result, i)); G[result].push_back(make_pair(index, i)); } } } } } int binarySearch(int left, int right, string s) { while (left < right) { int middle = (left+right)/2; if (s <= T[middle].first) { right = middle; } else { left = middle + 1; } } if (T[right].first == s) { return T[right].second; } else { return -1; } }
26.652893
74
0.40031
[ "vector" ]
b6e2e5c7e6c65d718b1bc4fb4be33f5b47d4c53b
3,579
cpp
C++
yolox/ops/onnxruntime/rotated_nms/cpu/rotated_nms.cpp
DDGRCF/YOLOX_OBB
27b80953306492b8bc83b86b1353d8cee01ef9b6
[ "Apache-2.0" ]
39
2021-11-09T12:12:06.000Z
2022-03-28T13:45:20.000Z
yolox/ops/onnxruntime/rotated_nms/cpu/rotated_nms.cpp
DDGRCF/YOLOX_OBB
27b80953306492b8bc83b86b1353d8cee01ef9b6
[ "Apache-2.0" ]
12
2021-11-09T11:33:29.000Z
2022-03-25T17:00:14.000Z
yolox/ops/onnxruntime/rotated_nms/cpu/rotated_nms.cpp
DDGRCF/YOLOX_OBB
27b80953306492b8bc83b86b1353d8cee01ef9b6
[ "Apache-2.0" ]
1
2022-03-24T06:53:39.000Z
2022-03-24T06:53:39.000Z
#include <algorithm> #include <cmath> #include <iostream> #include <iterator> #include <numeric> // std::iota #include <vector> #include "ort_utils.h" #include "rotated_nms.h" #include "rotated_utils.hpp" RotatedNmsKernel::RotatedNmsKernel(OrtApi api, const OrtKernelInfo *info) : api_(api), ort_(api_), info_(info) { iou_threshold_ = ort_.KernelInfoGetAttribute<float>(info, "iou_threshold"); score_threshold_ = ort_.KernelInfoGetAttribute<float>(info, "score_threshold"); small_threshold_ = ort_.KernelInfoGetAttribute<float>(info, "small_threshold"); max_num_ = ort_.KernelInfoGetAttribute<int64_t>(info, "max_num"); // create allocator allocator_ = Ort::AllocatorWithDefaultOptions(); } void RotatedNmsKernel::Compute(OrtKernelContext *context) { const int64_t max_num = max_num_; const float small_threshold = small_threshold_; const float score_threshold = score_threshold_; const float iou_threshold = iou_threshold_; const OrtValue *boxes = ort_.KernelContext_GetInput(context, 0); const float *boxes_data = reinterpret_cast<const float *>(ort_.GetTensorData<float>(boxes)); const OrtValue *scores = ort_.KernelContext_GetInput(context, 1); const float *scores_data = reinterpret_cast<const float *>(ort_.GetTensorData<float>(scores)); OrtTensorDimensions boxes_dim(ort_, boxes); OrtTensorDimensions scores_dim(ort_, scores); int64_t nboxes = boxes_dim[0]; assert(boxes_dim[1] == 5); // allocate tmp memory float *tmp_boxes = (float *)allocator_.Alloc(sizeof(float) * nboxes * 5); float *sc = (float *)allocator_.Alloc(sizeof(float) * nboxes); bool *select = (bool *)allocator_.Alloc(sizeof(bool) * nboxes); for (int64_t i = 0; i < nboxes; i++) { select[i] = true; } memcpy(tmp_boxes, boxes_data, sizeof(float) * nboxes * 5); memcpy(sc, scores_data, sizeof(float) * nboxes); // sort scores std::vector<float> tmp_sc; for (int i = 0; i < nboxes; i++) { tmp_sc.push_back(sc[i]); } std::vector<int64_t> order(tmp_sc.size()); std::iota(order.begin(), order.end(), 0); std::sort(order.begin(), order.end(), [&tmp_sc](int64_t id1, int64_t id2) { return tmp_sc[id1] > tmp_sc[id2]; }); for (int64_t _i = 0; _i < nboxes; _i++) { if (select[_i] == false) continue; auto i = order[_i]; if (sc[i] < score_threshold){ select[_i] = false; continue; } auto tmp_box1 = tmp_boxes + i * 5; for (int64_t _j = _i + 1; _j < nboxes; _j++) { if (select[_j] == false) continue; auto j = order[_j]; if (sc[j] < score_threshold){ select[_j] = false; continue; } auto tmp_box2 = tmp_boxes + j * 5; auto ovr = single_box_iou_rotated(tmp_box1, tmp_box2, small_threshold); if (ovr > iou_threshold) select[_j] = false; } } std::vector<int64_t> res_order; for (int i = 0; i < nboxes; i++) { if (select[i]) { res_order.push_back(order[i]); } } auto len_res_data = std::min(static_cast<int64_t>(res_order.size()), max_num); std::vector<int64_t> inds_dims({len_res_data}); OrtValue *res = ort_.KernelContext_GetOutput(context, 0, inds_dims.data(), inds_dims.size()); int64_t *res_data = ort_.GetTensorMutableData<int64_t>(res); memcpy(res_data, res_order.data(), sizeof(int64_t) * inds_dims.size()); }
35.79
83
0.628667
[ "vector" ]
b6ea959e0018e53f5e29937b9f79c844f1e1bab9
4,310
hpp
C++
src/Common/SharedLibrary.hpp
mlaszko/DisCODe
0042280ae6c1ace8c6e0fa25ae4d440512c113f6
[ "MIT" ]
1
2017-02-17T13:01:13.000Z
2017-02-17T13:01:13.000Z
src/Common/SharedLibrary.hpp
mlaszko/DisCODe
0042280ae6c1ace8c6e0fa25ae4d440512c113f6
[ "MIT" ]
null
null
null
src/Common/SharedLibrary.hpp
mlaszko/DisCODe
0042280ae6c1ace8c6e0fa25ae4d440512c113f6
[ "MIT" ]
1
2018-07-23T00:05:58.000Z
2018-07-23T00:05:58.000Z
/*! * \file SharedLibrary.hpp * \brief * * \author mstefanc * \date 2010-05-02 */ #ifndef SHAREDLIBRARY_HPP_ #define SHAREDLIBRARY_HPP_ #include <string> #include <dlfcn.h> #include "SharedLibraryCommon.hpp" namespace Common { /*! * \class SharedLibrary * \brief Class representing shared object. * * It's responsible for loading and unloading library files and retrieving functions from them. * * \author mstefanc */ class SharedLibrary { public: /*! * SharedLibrary constructor. * \param fname library filename, on some systems it should also have path included (even if it's * located in the same directory as executable - then fname should be ./file.so) * \param auto_cl if set to true unload will be called in destructor, if false unload must be called explicitly. */ SharedLibrary(const std::string & fname = "", bool auto_cl = true) : handle(0), auto_close(auto_cl), location(fname) {}; /*! * Destructor. * * If automatic library closing was set to true in constructor and library is loaded then destructor * unloads it from memory, in other situation it does nothing. */ ~SharedLibrary() { if (handle && auto_close) dlclose(handle); } /*! * Set location of library. * * Useful if empty constructor was used during initialization. * \param fname library filename, on some systems it should also have path included (even if it's * located in the same directory as executable - then fname should be ./file.so) * \param auto_open if set to true then library will be immediately loaded * \return * - false if auto_open was set but library can't be loaded * - true otherwise */ bool setLocation(const std::string& fname, bool auto_open = false) { location = fname; if (auto_open) { return load(); } else { return true; } } /*! * Load shared library. * * If library is already loaded then unload is called and then library is reloaded. * * \return true if load was successful, false if some error occurs (invalid file name, unsuccessful * library unload etc) */ bool load() { if (location == "") return false; if (handle && !unload()) return false; handle = dlopen(location.c_str(), RTLD_LAZY); return (handle != 0); } /*! * Check if library is loaded * \return true if library is loaded, false otherwise */ bool loaded() const { return (handle != 0); } /*! * Unload library from memory. * * \return true if library was unloaded, false otherwise */ bool unload() { if (!dlclose(handle)) { handle = 0; return true; } else { return false; } } /*! * Return error from last call. * * \return pointer to textual description of last call error (if there was any) or NULL * when last call was successful. */ char * error() { return dlerror(); } // If Doxygen is being run, use more readable definitions for the documentation. #ifdef DOXYGEN_INVOKED /** * \brief Get a function reference. * * A template function taking as template arguments the * type of the return value and parameters of a function * to look up in the shared library. * * This function must have been declared with the same * parameters and return type and marked as extern "C". * * Depending on platform and compiler settings, it may also * be necessary to prefix the function with BOOST_EXTENSION_DECL, * to make it externally visible. * * \warning If the function signature does not match, strange errors can occur. * \pre loaded() == true. * \post None. */ template <class RetValue, class Params...> FunctionPtr<ReturnValue (Params...)> get(const std::string& name) const { } #else /* DOXYGEN_INVOKED */ #define BOOST_PP_ITERATION_LIMITS (0, BOOST_PP_INC(SHARED_LIBRARY_MAX_FUNCTOR_PARAMS) - 1) #define BOOST_PP_FILENAME_1 <SharedLibrary.inc> #include BOOST_PP_ITERATE() #endif /* DOXYGEN_INVOKED */ protected: /// internal handle to opened library object library_handle handle; /// automatic library close flag bool auto_close; /// location of library std::string location; }; } //: namespace Common #endif /* SHAREDLIBRARY_HPP_ */
25.808383
113
0.665893
[ "object" ]
b6eaaf0939bb83f5bb3f3f7720eefbb2617b6d23
2,644
cpp
C++
tests/functional_tests/exec_test.cpp
wiryls/uncat
3df67408c1887b15ceccca8bf1301bdb7a065aa4
[ "MIT" ]
null
null
null
tests/functional_tests/exec_test.cpp
wiryls/uncat
3df67408c1887b15ceccca8bf1301bdb7a065aa4
[ "MIT" ]
null
null
null
tests/functional_tests/exec_test.cpp
wiryls/uncat
3df67408c1887b15ceccca8bf1301bdb7a065aa4
[ "MIT" ]
1
2021-06-17T23:23:40.000Z
2021-06-17T23:23:40.000Z
#include <algorithm> #include <vector> #include <mutex> #include <catch2/catch_test_macros.hpp> #include <uncat/exec/executor.hpp> TEST_CASE("executor(0) is dead silence", "[exec]") { SECTION("push back experiment") { auto v = std::vector<int>(); { auto ex = uncat::exec::executor(0); auto ok = ex([&v] { v.push_back(0); }); REQUIRE(!ok); } REQUIRE(v.empty()); } } TEST_CASE("executor(1) is strictly ordered", "[exec]") { SECTION("push back experiment") { auto n = std::size_t(100); auto v = std::vector<std::size_t>(); { auto ex = uncat::exec::executor(1); for (auto i = std::size_t(); i < n; ++i) ex([&v, i = i] { v.push_back(i); }); } for (auto i = std::size_t(); i < n; ++i) REQUIRE(v[i] == i); } SECTION("with std::bind") { auto m = std::size_t(4); auto n = std::size_t(8); auto v = std::vector<std::size_t>(); { auto xs = std::vector<std::size_t>{ 0, 1, 2, 3, 4, 5, 6, 7 }; auto ex = uncat::exec::executor(1); { using ctyp = std::vector<std::size_t>; using iter = ctyp::const_iterator; using bier = std::back_insert_iterator<ctyp>; for (auto i = std::size_t(); i < m; ++i) { ex(std::bind ( std::copy<iter, bier>, xs.begin(), xs.end(), std::back_inserter(v) )); } } } REQUIRE(v.size() == m * n); for (auto i = std::size_t(); i < v.size(); ++i) REQUIRE(v[i] == (i % n)); } } TEST_CASE("executor(n, n >= 2) is a mess", "[exec]") { SECTION("push back experiment") { auto x = std::size_t(30); auto y = std::size_t(30); auto v = std::vector<std::size_t>(); auto m = std::mutex(); { auto ex = uncat::exec::executor(8); for (auto i = std::size_t(); i < x * y; i += x) { auto l = i; auto r = i + x; ex([&v, &m, l, r] { std::scoped_lock _(m); for (auto i = l; i < r; ++i) v.push_back(i); }); } } std::sort(v.begin(), v.end()); for (auto i = std::size_t(); i < x * y; ++i) REQUIRE(v[i] == i); } }
27.257732
73
0.39826
[ "vector" ]
b6ebf21c8557b24f779c73a49b0eb8892fb06e08
2,456
cc
C++
RAVL2/3D/Mesh/HEMeshVertex.cc
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/3D/Mesh/HEMeshVertex.cc
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/3D/Mesh/HEMeshVertex.cc
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
// This file is part of RAVL, Recognition And Vision Library // Copyright (C) 2002, University of Surrey // This code may be redistributed under the terms of the GNU Lesser // General Public License (LGPL). See the lgpl.licence file for details or // see http://www.gnu.org/copyleft/lesser.html // file-header-ends-here //! rcsid="$Id: HEMeshVertex.cc 1533 2002-08-08 16:03:23Z craftit $" //! lib=Ravl3D //! file="Ravl/3D/Mesh/HEMeshVertex.cc" #include "Ravl/3D/HEMeshVertex.hh" #include "Ravl/3D/HEMeshEdge.hh" #include "Ravl/3D/HEMeshFace.hh" namespace Ravl3DN { //: Look for a connection from this vertex to oth. // Returns an invalid handle if ones is not found. HEMeshEdgeC HEMeshVertexBodyC::FindEdge(const HEMeshVertexC &oth) const { if(edge == 0) // None ? return HEMeshEdgeC(); #if 0 HEMeshEdgeC at(edge); while(at) { if(at.Vertex() == oth) return at; if(!at.HasPair()) break; at = at.Pair().Next(); } #else RavlAssert(0); #endif return HEMeshEdgeC(); } //: Link this vertex to newVert on indicated face // Both vertexes must share the face. This will effectively // split the face in two. HEMeshEdgeC HEMeshVertexBodyC::Link(HEMeshVertexC vert,HEMeshFaceC face) { HEMeshEdgeC toVert = face.FindEdge(vert); RavlAssert(toVert.IsValid()); HEMeshEdgeC toThis = face.FindEdge(vert); RavlAssert(toThis.IsValid()); // Construct edges. HEMeshEdgeC newEdge1(vert,face); HEMeshEdgeC newEdge2(*this,face); newEdge1.SetPair(newEdge2); newEdge2.SetPair(newEdge1); newEdge1.SetFace(face); // Split boundry into two faces. newEdge1.LinkAfter(toThis); newEdge2.CutPaste(newEdge1.Next(),toVert.Next()); face.SetEdge(newEdge1); // Make sure face edge ptrs are correct. HEMeshFaceC newFace(newEdge2); face.Body().LinkAft(newFace.Body()); // Put it in the face list. // Update all edges with new face. HEMeshEdgeC at = newEdge2; newEdge2.SetFace(newFace); for(at = at.Next();at != newEdge2;at = at.Next()) at.SetFace(newFace); return newEdge1; } //: Get the number of edges/faces linking to this vertexs. // This assumes this is a closed mesh. UIntT HEMeshVertexBodyC::Valence() const { UIntT count = 0; for(HEMeshVertexEdgeIterC it(const_cast<HEMeshVertexBodyC &>(*this));it;it++) count++; return count; } }
27.909091
81
0.664495
[ "mesh", "3d" ]
b6ecbe54fe7b2b64bbccfe5532f293da4d16c062
1,816
cpp
C++
sunfish_joypad/src/JoypadMain.cpp
Gallard88/sunfish_control
8d0ebdab6360a2244cd80dc81f135deaeeab4c6b
[ "MIT" ]
null
null
null
sunfish_joypad/src/JoypadMain.cpp
Gallard88/sunfish_control
8d0ebdab6360a2244cd80dc81f135deaeeab4c6b
[ "MIT" ]
null
null
null
sunfish_joypad/src/JoypadMain.cpp
Gallard88/sunfish_control
8d0ebdab6360a2244cd80dc81f135deaeeab4c6b
[ "MIT" ]
null
null
null
#include "ros/ros.h" #include "sensor_msgs/Joy.h" #include "geometry_msgs/Twist.h" // Twist /* ------------------------------------------------------- */ static ros::Subscriber joySub_; static ros::Publisher vecPub_; static ros::Timer updateTimer; static geometry_msgs::Twist cmdVector_; static bool diveInc_, diveDec_; static double depth_; static const double depthInc_ = 0.1; /* ------------------------------------------------------- */ static void joystickUpdate(const sensor_msgs::Joy & update) { if (( diveInc_ == false ) && ( update.buttons[5] != 0 )) { depth_ += depthInc_; if ( depth_ > 0.0 ) depth_ = 0.0; } if (( diveDec_ == false ) && ( update.buttons[4] != 0 )) { depth_ -= depthInc_; if ( depth_ < -1.0 ) depth_ = -1.0; } diveInc_ = update.buttons[5]; diveDec_ = update.buttons[4]; cmdVector_.linear.x = update.axes[1]; cmdVector_.linear.y = update.axes[3] * -1.0; cmdVector_.linear.z = depth_; cmdVector_.angular.x = 0.0; cmdVector_.angular.y = 0.0; cmdVector_.angular.z = update.axes[0] * -1.0; } static void callbackTimer(const ros::TimerEvent & e) { vecPub_.publish(cmdVector_); } /* ------------------------------------------------------- */ int main(int argc, char **argv) { ros::init(argc, argv, "sunfish_joypad"); ros::NodeHandle n; diveInc_ = diveDec_ = false; depth_ = 0.0; ROS_INFO("Sunfish Joypad online"); joySub_ = n.subscribe("/joy", 1, joystickUpdate); vecPub_ = n.advertise<geometry_msgs::Twist>("/sunfish/ecu/vector", 2); double update; n.param("/sunfish/joy_update", update, 10.0); if ( update < 1.0 ) { update = 1.0; } else if ( update > 50.0 ) { update = 50.0; } updateTimer = n.createTimer(ros::Duration(1.0/update), &callbackTimer); ros::spin(); return 0; }
25.222222
73
0.577643
[ "vector" ]
b6ee3dbe6dc8070d2d07eb3f3af869fc5fc63559
4,808
hpp
C++
include/dcps/C++/isocpp2/dds/core/cond/detail/TStatusConditionImpl.hpp
lsst-ts/ts_opensplice_community
28032928681f015c4233effcc9c68b2655901d61
[ "Apache-2.0" ]
null
null
null
include/dcps/C++/isocpp2/dds/core/cond/detail/TStatusConditionImpl.hpp
lsst-ts/ts_opensplice_community
28032928681f015c4233effcc9c68b2655901d61
[ "Apache-2.0" ]
null
null
null
include/dcps/C++/isocpp2/dds/core/cond/detail/TStatusConditionImpl.hpp
lsst-ts/ts_opensplice_community
28032928681f015c4233effcc9c68b2655901d61
[ "Apache-2.0" ]
null
null
null
/* * Vortex OpenSplice * * This software and documentation are Copyright 2006 to ADLINK * Technology Limited, its affiliated companies and licensors. 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 OSPL_DDS_CORE_COND_TSTATUSCONDITION_IMPL_HPP_ #define OSPL_DDS_CORE_COND_TSTATUSCONDITION_IMPL_HPP_ /** * @file */ /* * OMG PSM class declaration */ #include <dds/core/cond/TStatusCondition.hpp> #include <org/opensplice/core/cond/StatusConditionDelegate.hpp> #include <org/opensplice/core/ReportUtils.hpp> // Implementation namespace dds { namespace core { namespace cond { template <typename DELEGATE> TStatusCondition<DELEGATE>::TStatusCondition(const dds::core::Entity& e) { ISOCPP_REPORT_STACK_DDS_BEGIN(e); dds::core::Reference<DELEGATE>::impl_= OSPL_CXX11_STD_MODULE::dynamic_pointer_cast<org::opensplice::core::cond::StatusConditionDelegate>( e.delegate()->get_statusCondition()); } /** @cond * Somehow, these cause functions duplicates in doxygen documentation. */ template <typename DELEGATE> template <typename FUN> TStatusCondition<DELEGATE>::TStatusCondition(const dds::core::Entity& e, FUN& functor) { ISOCPP_REPORT_STACK_DDS_BEGIN(e); dds::core::Reference<DELEGATE>::impl_= OSPL_CXX11_STD_MODULE::dynamic_pointer_cast<org::opensplice::core::cond::StatusConditionDelegate>( e.delegate()->get_statusCondition()); this->delegate()->set_handler(functor); } template <typename DELEGATE> template <typename FUN> TStatusCondition<DELEGATE>::TStatusCondition(const dds::core::Entity& e, const FUN& functor) { ISOCPP_REPORT_STACK_DDS_BEGIN(e); dds::core::Reference<DELEGATE>::impl_= OSPL_CXX11_STD_MODULE::dynamic_pointer_cast<org::opensplice::core::cond::StatusConditionDelegate>( e.delegate()->get_statusCondition()); this->delegate()->set_handler(functor); } /** @endcond */ template <typename DELEGATE> TStatusCondition<DELEGATE>::~TStatusCondition() { } template <typename DELEGATE> void TStatusCondition<DELEGATE>::enabled_statuses(const dds::core::status::StatusMask& status) const { ISOCPP_REPORT_STACK_DDS_BEGIN(*this); this->delegate()->enabled_statuses(status); } template <typename DELEGATE> const dds::core::status::StatusMask TStatusCondition<DELEGATE>::enabled_statuses() const { ISOCPP_REPORT_STACK_DDS_BEGIN(*this); return this->delegate()->enabled_statuses(); } template <typename DELEGATE> const dds::core::Entity& TStatusCondition<DELEGATE>::entity() const { ISOCPP_REPORT_STACK_DDS_BEGIN(*this); return this->delegate()->entity(); } template <typename DELEGATE> TCondition<DELEGATE>::TCondition(const dds::core::cond::TStatusCondition<org::opensplice::core::cond::StatusConditionDelegate>& h) { if (h.is_nil()) { /* We got a null object and are not really able to do a typecheck here. */ /* So, just set a null object. */ *this = dds::core::null; } else { ISOCPP_REPORT_STACK_DDS_BEGIN(h); this->::dds::core::Reference<DELEGATE>::impl_ = OSPL_CXX11_STD_MODULE::dynamic_pointer_cast<DELEGATE_T>(h.delegate()); if (h.delegate() != this->::dds::core::Reference<DELEGATE>::impl_) { throw dds::core::IllegalOperationError(std::string("Attempted invalid cast: ") + typeid(h).name() + " to " + typeid(*this).name()); } } } template <typename DELEGATE> TCondition<DELEGATE>& TCondition<DELEGATE>::operator=(const dds::core::cond::TStatusCondition<org::opensplice::core::cond::StatusConditionDelegate>& rhs) { if (this != (TCondition*)&rhs) { if (rhs.is_nil()) { /* We got a null object and are not really able to do a typecheck here. */ /* So, just set a null object. */ *this = dds::core::null; } else { TCondition other(rhs); /* Dont have to copy when the delegate is the same. */ if (other.delegate() != this->::dds::core::Reference<DELEGATE>::impl_) { *this = other; } } } return *this; } } } } // End of implementation #endif /* OSPL_DDS_CORE_COND_TSTATUSCONDITION_IMPL_HPP_ */
32.707483
143
0.686564
[ "object" ]
8e00290ffc3fc0c20786f9d38f7245b00395ed96
2,620
cpp
C++
gst/elements/gvafpscounter/fpscounter_c.cpp
maksimvlasov/dlstreamer_gst
747878fe2de3380fab7f4a5a4932623aaf1622a8
[ "MIT" ]
125
2020-09-18T10:50:27.000Z
2022-02-10T06:20:59.000Z
gst/elements/gvafpscounter/fpscounter_c.cpp
maksimvlasov/dlstreamer_gst
747878fe2de3380fab7f4a5a4932623aaf1622a8
[ "MIT" ]
155
2020-09-10T23:32:29.000Z
2022-02-05T07:10:26.000Z
gst/elements/gvafpscounter/fpscounter_c.cpp
maksimvlasov/dlstreamer_gst
747878fe2de3380fab7f4a5a4932623aaf1622a8
[ "MIT" ]
41
2020-09-15T08:49:17.000Z
2022-01-24T10:39:36.000Z
/******************************************************************************* * Copyright (C) 2020 Intel Corporation * * SPDX-License-Identifier: MIT ******************************************************************************/ #include "fpscounter_c.h" #include "config.h" #include "fpscounter.h" #include "inference_backend/logger.h" #include "utils.h" #include <assert.h> #include <exception> #include <map> #include <memory> #include <mutex> static std::map<std::string, std::shared_ptr<FpsCounter>> fps_counters; static std::mutex channels_mutex; static FILE *output = stdout; ////////////////////////////////////////////////////////////////////////// // C interface void fps_counter_create_iterative(const char *intervals) { try { std::lock_guard<std::mutex> lock(channels_mutex); std::vector<std::string> intervals_list = Utils::splitString(intervals, ','); for (const std::string &interval : intervals_list) if (not fps_counters.count(interval)) { std::shared_ptr<FpsCounter> fps_counter = std::shared_ptr<FpsCounter>(new IterativeFpsCounter(std::stoi(interval))); fps_counters.insert({interval, fps_counter}); } } catch (std::exception &e) { std::string msg = std::string("Error during creation iterative fpscounter: ") + e.what(); GVA_ERROR(msg.c_str()); } } void fps_counter_create_average(unsigned int starting_frame) { try { if (not fps_counters.count("average")) fps_counters.insert({"average", std::shared_ptr<FpsCounter>(new AverageFpsCounter(starting_frame))}); } catch (std::exception &e) { std::string msg = std::string("Error during creation average fpscounter: ") + e.what(); GVA_ERROR(msg.c_str()); } } void fps_counter_new_frame(GstBuffer *, const char *element_name) { try { for (auto counter = fps_counters.begin(); counter != fps_counters.end(); ++counter) counter->second->NewFrame(element_name, output); } catch (std::exception &e) { std::string msg = std::string("Error during adding new frame: ") + e.what(); GVA_ERROR(msg.c_str()); } } void fps_counter_eos() { try { for (auto counter = fps_counters.begin(); counter != fps_counters.end(); ++counter) counter->second->EOS(output); } catch (std::exception &e) { std::string msg = std::string("Error during handling EOS : ") + e.what(); GVA_ERROR(msg.c_str()); } } void fps_counter_set_output(FILE *out) { if (out != nullptr) output = out; }
35.890411
113
0.583588
[ "vector" ]
8e0b5ed0d1b1b27e0a474d00cb59b0fc7615105a
41,423
cpp
C++
src/game/server/portal/npc_rocket_turret.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/game/server/portal/npc_rocket_turret.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/game/server/portal/npc_rocket_turret.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //===========================================================================// #include "cbase.h" #include "ai_basenpc.h" #include "ai_senses.h" #include "ai_memory.h" #include "engine/IEngineSound.h" #include "Sprite.h" #include "IEffects.h" #include "prop_portal_shared.h" #include "te.h" #include "te_effect_dispatch.h" #include "soundenvelope.h" // for looping sound effects #include "portal_gamerules.h" // for difficulty settings #include "weapon_rpg.h" #include "explode.h" #include "smoke_trail.h" // smoke trailers on the rocket #include "physics_bone_follower.h" // For bone follower manager #include "physicsshadowclone.h" // For translating hit entities shadow clones to real ent //#include "ndebugoverlay.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define ROCKET_TURRET_RANGE 8192 #define ROCKET_TURRET_EMITER_OFFSET 0.0 #define ROCKET_TURRET_THINK_RATE 0.05 #define ROCKET_TURRET_DEATH_EFFECT_TIME 1.5f #define ROCKET_TURRET_LOCKON_TIME 2.0f #define ROCKET_TURRET_HALF_LOCKON_TIME 1.0f #define ROCKET_TURRET_QUARTER_LOCKON_TIME 0.5f #define ROCKET_TURRET_ROCKET_FIRE_COOLDOWN_TIME 4.0f // For search thinks #define MAX_DIVERGENCE_X 30.0f #define MAX_DIVERGENCE_Y 15.0f #define ROCKET_TURRET_DECAL_NAME "decals/scorchfade" #define ROCKET_TURRET_MODEL_NAME "models/props_bts/rocket_sentry.mdl" #define ROCKET_TURRET_PROJECTILE_NAME "models/props_bts/rocket.mdl" #define ROCKET_TURRET_SOUND_LOCKING "NPC_RocketTurret.LockingBeep" #define ROCKET_TURRET_SOUND_LOCKED "NPC_FloorTurret.LockedBeep" #define ROCKET_PROJECTILE_FIRE_SOUND "NPC_FloorTurret.RocketFire" #define ROCKET_PROJECTILE_LOOPING_SOUND "NPC_FloorTurret.RocketFlyLoop" #define ROCKET_PROJECTILE_DEFAULT_LIFE 20.0 //Spawnflags #define SF_ROCKET_TURRET_START_INACTIVE 0x00000001 // These bones have physics shadows const char *pRocketTurretFollowerBoneNames[] = { "Root", "Base", "Arm_1", "Arm_2", "Arm_3", "Arm_4", "Rot_LR", "Rot_UD", "Gun_casing", "Gun_Barrel_01", "gun_barrel_02", "loader", "missle_01", "missle_02", "panel", }; class CNPC_RocketTurret : public CAI_BaseNPC { DECLARE_CLASS( CNPC_RocketTurret, CAI_BaseNPC ); DECLARE_SERVERCLASS(); DECLARE_DATADESC(); public: CNPC_RocketTurret( void ); ~CNPC_RocketTurret( void ); void Precache( void ); void Spawn( void ); virtual void Activate( void ); virtual ITraceFilter* GetBeamTraceFilter( void ); void UpdateOnRemove( void ); bool CreateVPhysics( void ); // Think functions void SearchThink( void ); // Lost Target, spaz out void FollowThink( void ); // Found target, chase it void LockingThink( void ); // Charge up effects void FiringThink( void ); // Currently has rocket out void DyingThink( void ); // Overloading, blowing up void DeathThink( void ); // Destroyed, sparking void OpeningThink ( void ); // Finish open/close animation before using pose params void ClosingThink ( void ); // Inputs void InputToggle( inputdata_t &inputdata ); void InputEnable( inputdata_t &inputdata ); void InputDisable( inputdata_t &inputdata ); void InputSetTarget( inputdata_t &inputdata ); void InputDestroy( inputdata_t &inputdata ); void RocketDied( void ); // After rocket hits something and self-destructs (or times out) Class_T Classify( void ) { if( m_bEnabled ) return CLASS_COMBINE; return CLASS_NONE; } bool FVisible( CBaseEntity *pEntity, int traceMask = MASK_BLOCKLOS, CBaseEntity **ppBlocker = NULL ); Vector EyeOffset( Activity nActivity ) { return vec3_origin; } Vector EyePosition( void ) { Vector vMuzzlePos; GetAttachment( m_iMuzzleAttachment, vMuzzlePos, NULL, NULL, NULL ); return vMuzzlePos; } protected: bool PreThink( void ); void Toggle( void ); void Enable( void ); void Disable( void ); void SetTarget( CBaseEntity* pTarget ); void Destroy ( void ); float UpdateFacing( void ); void UpdateAimPoint( void ); void FireRocket( void ); void UpdateSkin( int nSkin ); void UpdateMuzzleMatrix ( void ); bool TestLOS( const Vector& vAimPoint ); bool TestPortalsForLOS( Vector* pOutVec, bool bConsiderNonPortalAimPoint ); bool FindAimPointThroughPortal( const CProp_Portal* pPortal, Vector* pVecOut ); void SyncPoseToAimAngles ( void ); void LaserOn ( void ); void LaserOff ( void ); bool m_bEnabled; bool m_bHasSightOfEnemy; QAngle m_vecGoalAngles; CNetworkVar( QAngle, m_vecCurrentAngles ); QAngle m_vecAnglesToEnemy; enum { ROCKET_SKIN_IDLE=0, ROCKET_SKIN_LOCKING, ROCKET_SKIN_LOCKED, ROCKET_SKIN_COUNT, }; Vector m_vecDirToEnemy; float m_flDistToEnemy; float m_flTimeSpentDying; float m_flTimeLocking; // Period spent locking on to target float m_flTimeLastFired; // Cooldown time between attacks float m_flTimeSpentPaused; // for search think's movements float m_flPauseLength; float m_flTotalDivergenceX; float m_flTotalDivergenceY; matrix3x4_t m_muzzleToWorld; int m_muzzleToWorldTick; int m_iPosePitch; int m_iPoseYaw; // Contained Bone Follower manager CBoneFollowerManager m_BoneFollowerManager; // Model indices for effects CNetworkVar( int, m_iLaserState ); CNetworkVar( int, m_nSiteHalo ); // Target indicator sprite info int m_iMuzzleAttachment; int m_iLightAttachment; COutputEvent m_OnFoundTarget; COutputEvent m_OnLostTarget; CTraceFilterSkipTwoEntities m_filterBeams; EHANDLE m_hCurRocket; }; //Datatable BEGIN_DATADESC( CNPC_RocketTurret ) DEFINE_FIELD( m_bEnabled, FIELD_BOOLEAN ), DEFINE_FIELD( m_vecGoalAngles, FIELD_VECTOR ), DEFINE_FIELD( m_vecCurrentAngles, FIELD_VECTOR ), DEFINE_FIELD( m_bHasSightOfEnemy, FIELD_BOOLEAN ), DEFINE_FIELD( m_vecAnglesToEnemy, FIELD_VECTOR ), DEFINE_FIELD( m_vecDirToEnemy, FIELD_VECTOR ), DEFINE_FIELD( m_flDistToEnemy, FIELD_FLOAT ), DEFINE_FIELD( m_flTimeSpentDying, FIELD_FLOAT ), DEFINE_FIELD( m_flTimeLocking, FIELD_FLOAT ), DEFINE_FIELD( m_flTimeLastFired, FIELD_FLOAT ), DEFINE_FIELD( m_iLaserState, FIELD_INTEGER ), DEFINE_FIELD( m_nSiteHalo, FIELD_INTEGER ), DEFINE_FIELD( m_flTimeSpentPaused, FIELD_FLOAT ), DEFINE_FIELD( m_flPauseLength, FIELD_FLOAT ), DEFINE_FIELD( m_flTotalDivergenceX, FIELD_FLOAT ), DEFINE_FIELD( m_flTotalDivergenceY, FIELD_FLOAT ), DEFINE_FIELD( m_iPosePitch, FIELD_INTEGER ), DEFINE_FIELD( m_iPoseYaw, FIELD_INTEGER ), DEFINE_FIELD( m_hCurRocket, FIELD_EHANDLE ), DEFINE_FIELD( m_iMuzzleAttachment, FIELD_INTEGER ), DEFINE_FIELD( m_iLightAttachment, FIELD_INTEGER ), DEFINE_FIELD( m_muzzleToWorldTick, FIELD_INTEGER ), DEFINE_FIELD( m_muzzleToWorld, FIELD_MATRIX3X4_WORLDSPACE ), // DEFINE_FIELD( m_filterBeams, CTraceFilterSkipTwoEntities ), DEFINE_EMBEDDED( m_BoneFollowerManager ), DEFINE_THINKFUNC( SearchThink ), DEFINE_THINKFUNC( FollowThink ), DEFINE_THINKFUNC( LockingThink ), DEFINE_THINKFUNC( FiringThink ), DEFINE_THINKFUNC( DyingThink ), DEFINE_THINKFUNC( DeathThink ), DEFINE_THINKFUNC( OpeningThink ), DEFINE_THINKFUNC( ClosingThink ), // Inputs DEFINE_INPUTFUNC( FIELD_VOID, "Toggle", InputToggle ), DEFINE_INPUTFUNC( FIELD_VOID, "Enable", InputEnable ), DEFINE_INPUTFUNC( FIELD_VOID, "Disable", InputDisable ), DEFINE_INPUTFUNC( FIELD_STRING, "SetTarget", InputSetTarget ), DEFINE_INPUTFUNC( FIELD_VOID, "Destroy", InputDestroy ), DEFINE_OUTPUT( m_OnFoundTarget, "OnFoundTarget" ), DEFINE_OUTPUT( m_OnLostTarget, "OnLostTarget" ), END_DATADESC() IMPLEMENT_SERVERCLASS_ST(CNPC_RocketTurret, DT_NPC_RocketTurret) SendPropInt( SENDINFO( m_iLaserState ), 2 ), SendPropInt( SENDINFO( m_nSiteHalo ) ), SendPropVector( SENDINFO( m_vecCurrentAngles ) ), END_SEND_TABLE() LINK_ENTITY_TO_CLASS( npc_rocket_turret, CNPC_RocketTurret ); // Projectile class for this weapon, a rocket class CRocket_Turret_Projectile : public CMissile { DECLARE_CLASS( CRocket_Turret_Projectile, CMissile ); DECLARE_DATADESC(); public: void Precache( void ); void Spawn( void ); virtual void NotifyLauncherOnDeath( void ); virtual void NotifySystemEvent( CBaseEntity *pNotify, notify_system_event_t eventType, const notify_system_event_params_t &params ); virtual void SetLauncher( EHANDLE hLauncher ); virtual void CreateSmokeTrail( void ); // overloaded from base virtual void MissileTouch( CBaseEntity *pOther ); EHANDLE m_hLauncher; CSoundPatch *m_pAmbientSound; protected: virtual void DoExplosion( void ); virtual void CreateSounds( void ); virtual void StopLoopingSounds ( void ); }; BEGIN_DATADESC( CRocket_Turret_Projectile ) DEFINE_FIELD( m_hLauncher, FIELD_EHANDLE ), DEFINE_FUNCTION( MissileTouch ), DEFINE_SOUNDPATCH( m_pAmbientSound ), END_DATADESC() LINK_ENTITY_TO_CLASS( rocket_turret_projectile, CRocket_Turret_Projectile ); //----------------------------------------------------------------------------- // Constructor //----------------------------------------------------------------------------- CNPC_RocketTurret::CNPC_RocketTurret( void ) : m_filterBeams( NULL, NULL, COLLISION_GROUP_DEBRIS ) { m_bEnabled = false; m_bHasSightOfEnemy = false; m_vecGoalAngles.Init(); m_vecAnglesToEnemy.Init(); m_vecDirToEnemy.Init(); m_flTimeLastFired = m_flTimeLocking = m_flDistToEnemy = m_flTimeSpentDying = 0.0f; m_iLightAttachment = m_iMuzzleAttachment = m_nSiteHalo = 0; m_flTimeSpentPaused = m_flPauseLength = m_flTotalDivergenceX = m_flTotalDivergenceY = 0.0f; m_hCurRocket = NULL; } CNPC_RocketTurret::~CNPC_RocketTurret( void ) { } //----------------------------------------------------------------------------- // Purpose: Precache //----------------------------------------------------------------------------- void CNPC_RocketTurret::Precache( void ) { PrecacheModel("effects/bluelaser1.vmt"); m_nSiteHalo = PrecacheModel("sprites/light_glow03.vmt"); PrecacheScriptSound ( ROCKET_TURRET_SOUND_LOCKING ); PrecacheScriptSound ( ROCKET_TURRET_SOUND_LOCKED ); PrecacheScriptSound ( ROCKET_PROJECTILE_FIRE_SOUND ); PrecacheScriptSound ( ROCKET_PROJECTILE_LOOPING_SOUND ); UTIL_PrecacheDecal( ROCKET_TURRET_DECAL_NAME ); PrecacheModel( ROCKET_TURRET_MODEL_NAME ); PrecacheModel ( ROCKET_TURRET_PROJECTILE_NAME ); BaseClass::Precache(); } //----------------------------------------------------------------------------- // Purpose: the entity //----------------------------------------------------------------------------- void CNPC_RocketTurret::Spawn( void ) { Precache(); BaseClass::Spawn(); SetViewOffset( vec3_origin ); AddEFlags( EFL_NO_DISSOLVE ); SetModel( ROCKET_TURRET_MODEL_NAME ); SetSolid( SOLID_VPHYSICS ); m_iMuzzleAttachment = LookupAttachment ( "barrel" ); m_iLightAttachment = LookupAttachment ( "eye" ); m_iPosePitch = LookupPoseParameter( "aim_pitch" ); m_iPoseYaw = LookupPoseParameter( "aim_yaw" ); m_vecCurrentAngles = m_vecGoalAngles = GetAbsAngles(); CreateVPhysics(); //Set our autostart state m_bEnabled = ( ( m_spawnflags & SF_ROCKET_TURRET_START_INACTIVE ) == false ); // Set Locked sprite if ( m_bEnabled ) { m_iLaserState = 1; SetSequence(LookupSequence("idle")); } else { m_iLaserState = 0; SetSequence(LookupSequence("inactive")); } SetCycle(1.0f); UpdateSkin( ROCKET_SKIN_IDLE ); SetPoseParameter( "aim_pitch", 0 ); SetPoseParameter( "aim_yaw", -180 ); if ( m_bEnabled ) { SetThink( &CNPC_RocketTurret::FollowThink ); } SetNextThink( gpGlobals->curtime + ROCKET_TURRET_THINK_RATE ); } bool CNPC_RocketTurret::CreateVPhysics( void ) { m_BoneFollowerManager.InitBoneFollowers( this, ARRAYSIZE(pRocketTurretFollowerBoneNames), pRocketTurretFollowerBoneNames ); BaseClass::CreateVPhysics(); return true; } void CNPC_RocketTurret::Activate( void ) { m_filterBeams.SetPassEntity( this ); m_filterBeams.SetPassEntity2( UTIL_GetLocalPlayer() ); BaseClass::Activate(); } ITraceFilter* CNPC_RocketTurret::GetBeamTraceFilter( void ) { return &m_filterBeams; } void CNPC_RocketTurret::UpdateOnRemove( void ) { m_BoneFollowerManager.DestroyBoneFollowers(); BaseClass::UpdateOnRemove(); } //----------------------------------------------------------------------------- // Purpose: // Input : *pEntity - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CNPC_RocketTurret::FVisible( CBaseEntity *pEntity, int traceMask, CBaseEntity **ppBlocker ) { CBaseEntity *pHitEntity = NULL; if ( BaseClass::FVisible( pEntity, traceMask, &pHitEntity ) ) return true; if (ppBlocker) { *ppBlocker = pHitEntity; } return false; } //----------------------------------------------------------------------------- // Purpose: // Output : void CNPC_RocketTurret::UpdateAimPoint //----------------------------------------------------------------------------- void CNPC_RocketTurret::UpdateAimPoint ( void ) { //If we've become inactive if ( ( m_bEnabled == false ) || ( GetEnemy() == NULL ) ) { SetEnemy( NULL ); SetNextThink( TICK_NEVER_THINK ); m_vecGoalAngles = GetAbsAngles(); return; } //Get our shot positions Vector vecMid = EyePosition(); Vector vecMidEnemy = GetEnemy()->GetAbsOrigin() + (GetEnemy()->WorldAlignMins() + GetEnemy()->WorldAlignMaxs()) * 0.5f; //Calculate dir and dist to enemy m_vecDirToEnemy = vecMidEnemy - vecMid; m_flDistToEnemy = VectorNormalize( m_vecDirToEnemy ); VectorAngles( m_vecDirToEnemy, m_vecAnglesToEnemy ); bool bEnemyVisible = false; if ( !(GetEnemy()->GetFlags() & FL_NOTARGET) ) { bool bEnemyVisibleInWorld = FVisible( GetEnemy() ); // Test portals in our view as possible ways to view the player bool bEnemyVisibleThroughPortal = TestPortalsForLOS( &vecMidEnemy, bEnemyVisibleInWorld ); bEnemyVisible = bEnemyVisibleInWorld || bEnemyVisibleThroughPortal; } //Store off our last seen location UpdateEnemyMemory( GetEnemy(), vecMidEnemy ); if ( bEnemyVisible ) { m_vecDirToEnemy = vecMidEnemy - vecMid; m_flDistToEnemy = VectorNormalize( m_vecDirToEnemy ); VectorAngles( m_vecDirToEnemy, m_vecAnglesToEnemy ); } //Current enemy is not visible if ( ( bEnemyVisible == false ) || ( m_flDistToEnemy > ROCKET_TURRET_RANGE ) ) { // Had LOS, just lost it if ( m_bHasSightOfEnemy ) { m_OnLostTarget.FireOutput( GetEnemy(), this ); } m_bHasSightOfEnemy = false; } //If we can see our enemy if ( bEnemyVisible ) { // Had no LOS, just gained it if ( !m_bHasSightOfEnemy ) { m_OnFoundTarget.FireOutput( GetEnemy(), this ); } m_bHasSightOfEnemy = true; } } bool SignDiffers ( float f1, float f2 ) { return !( Sign(f1) == Sign(f2) ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CNPC_RocketTurret::SearchThink() { if ( PreThink() || GetEnemy() == NULL ) return; SetSequence ( LookupSequence( "idle" ) ); UpdateAimPoint(); //Update our think time SetNextThink( gpGlobals->curtime + ROCKET_TURRET_THINK_RATE ); // Still can't see enemy, zip around frantically if ( !m_bHasSightOfEnemy ) { if ( m_flTimeSpentPaused >= m_flPauseLength ) { float flOffsetX = RandomFloat( -5.0f, 5.0f ); float flOffsetY = RandomFloat( -5.0f, 5.0f ); if ( fabs(m_flTotalDivergenceX) <= MAX_DIVERGENCE_X || SignDiffers( m_flTotalDivergenceX, flOffsetX ) ) { m_flTotalDivergenceX += flOffsetX; m_vecGoalAngles.x += flOffsetX; } if ( fabs(m_flTotalDivergenceY) <= MAX_DIVERGENCE_Y || SignDiffers( m_flTotalDivergenceY, flOffsetY ) ) { m_flTotalDivergenceY += flOffsetY; m_vecGoalAngles.y += flOffsetY; } // Reset pause timer m_flTimeSpentPaused = 0.0f; m_flPauseLength = RandomFloat( 0.3f, 2.5f ); } m_flTimeSpentPaused += ROCKET_TURRET_THINK_RATE; } else { // Found target, go back to following it SetThink( &CNPC_RocketTurret::FollowThink ); SetNextThink( gpGlobals->curtime + ROCKET_TURRET_THINK_RATE ); } // Move beam towards goal angles UpdateFacing(); } //----------------------------------------------------------------------------- // Purpose: Allows the turret to fire on targets if they're visible //----------------------------------------------------------------------------- void CNPC_RocketTurret::FollowThink( void ) { // Default to player as enemy if ( GetEnemy() == NULL ) { SetEnemy( UTIL_GetLocalPlayer() ); } SetSequence ( LookupSequence( "idle" ) ); //Allow descended classes a chance to do something before the think function if ( PreThink() || GetEnemy() == NULL ) { return; } //Update our think time SetNextThink( gpGlobals->curtime + ROCKET_TURRET_THINK_RATE ); UpdateAimPoint(); m_vecGoalAngles = m_vecAnglesToEnemy; // Chase enemy if ( !m_bHasSightOfEnemy ) { // Aim at the last known location m_vecGoalAngles = m_vecCurrentAngles; // Lost sight, move to search think SetThink( &CNPC_RocketTurret::SearchThink ); } //Turn to face UpdateFacing(); // If our facing direction hits our enemy, fire the beam Ray_t rayDmg; Vector vForward; AngleVectors( m_vecCurrentAngles, &vForward, NULL, NULL ); Vector vEndPoint = EyePosition() + vForward*ROCKET_TURRET_RANGE; rayDmg.Init( EyePosition(), vEndPoint ); rayDmg.m_IsRay = true; trace_t traceDmg; // This version reorients through portals CTraceFilterSimple subfilter( this, COLLISION_GROUP_NONE ); CTraceFilterTranslateClones filter ( &subfilter ); float flRequiredParameter = 2.0f; CProp_Portal* pFirstPortal = UTIL_Portal_FirstAlongRay( rayDmg, flRequiredParameter ); UTIL_Portal_TraceRay_Bullets( pFirstPortal, rayDmg, MASK_VISIBLE_AND_NPCS, &filter, &traceDmg, false ); if ( traceDmg.m_pEnt ) { // This thing we're hurting is our enemy if ( traceDmg.m_pEnt == GetEnemy() ) { // If we're past the cooldown time, fire another rocket if ( (gpGlobals->curtime - m_flTimeLastFired) > ROCKET_TURRET_ROCKET_FIRE_COOLDOWN_TIME ) { SetThink( &CNPC_RocketTurret::LockingThink ); } } } } //----------------------------------------------------------------------------- // Purpose: Charge up, prepare to fire and give player time to dodge //----------------------------------------------------------------------------- void CNPC_RocketTurret::LockingThink( void ) { //Allow descended classes a chance to do something before the think function if ( PreThink() ) return; //Turn to face UpdateFacing(); SetNextThink( gpGlobals->curtime + ROCKET_TURRET_THINK_RATE ); if ( m_flTimeLocking == 0.0f ) { // Play lockon sound EmitSound ( ROCKET_TURRET_SOUND_LOCKING ); EmitSound ( ROCKET_TURRET_SOUND_LOCKING, gpGlobals->curtime + ROCKET_TURRET_QUARTER_LOCKON_TIME ); EmitSound ( ROCKET_TURRET_SOUND_LOCKED, gpGlobals->curtime + ROCKET_TURRET_HALF_LOCKON_TIME ); ResetSequence(LookupSequence("load")); // Change lockon sprite UpdateSkin( ROCKET_SKIN_LOCKING ); } m_flTimeLocking += ROCKET_TURRET_THINK_RATE; if ( m_flTimeLocking > ROCKET_TURRET_LOCKON_TIME ) { // Set Locked sprite to 'rocket out' color UpdateSkin( ROCKET_SKIN_LOCKED ); FireRocket(); SetThink ( &CNPC_RocketTurret::FiringThink ); m_flTimeLocking = 0.0f; } } //----------------------------------------------------------------------------- // Purpose: Charge up, deal damage along our facing direction. //----------------------------------------------------------------------------- void CNPC_RocketTurret::FiringThink( void ) { //Allow descended classes a chance to do something before the think function if ( PreThink() ) return; SetNextThink( gpGlobals->curtime + ROCKET_TURRET_THINK_RATE ); CRocket_Turret_Projectile* pRocket = dynamic_cast<CRocket_Turret_Projectile*>(m_hCurRocket.Get()); if ( pRocket ) { // If this rocket has been out too long, detonate it and launch a new one if ( (gpGlobals->curtime - m_flTimeLastFired) > ROCKET_PROJECTILE_DEFAULT_LIFE ) { pRocket->ShotDown(); m_flTimeLastFired = gpGlobals->curtime; SetThink( &CNPC_RocketTurret::FollowThink ); } } else { // Set Locked sprite UpdateSkin( ROCKET_SKIN_IDLE ); // Rocket dead, or never created. Revert to follow think m_flTimeLastFired = gpGlobals->curtime; SetThink( &CNPC_RocketTurret::FollowThink ); } } void CNPC_RocketTurret::FireRocket ( void ) { UTIL_Remove( m_hCurRocket ); CRocket_Turret_Projectile *pRocket = (CRocket_Turret_Projectile *) CBaseEntity::Create( "rocket_turret_projectile", EyePosition(), m_vecCurrentAngles, this ); if ( !pRocket ) return; m_hCurRocket = pRocket; Vector vForward; AngleVectors( m_vecCurrentAngles, &vForward, NULL, NULL ); m_flTimeLastFired = gpGlobals->curtime; EmitSound ( ROCKET_PROJECTILE_FIRE_SOUND ); ResetSequence(LookupSequence("fire")); pRocket->SetThink( NULL ); pRocket->SetMoveType( MOVETYPE_FLY ); pRocket->CreateSmokeTrail(); pRocket->SetModel( ROCKET_TURRET_PROJECTILE_NAME ); UTIL_SetSize( pRocket, vec3_origin, vec3_origin ); pRocket->SetAbsVelocity( vForward * 550 ); pRocket->SetLauncher ( this ); } void CNPC_RocketTurret::UpdateSkin( int nSkin ) { m_nSkin = nSkin; } //----------------------------------------------------------------------------- // Purpose: Rocket destructed, resume search behavior //----------------------------------------------------------------------------- void CNPC_RocketTurret::RocketDied( void ) { // Set Locked sprite UpdateSkin( ROCKET_SKIN_IDLE ); // Rocket dead, return to follow think m_flTimeLastFired = gpGlobals->curtime; SetThink( &CNPC_RocketTurret::FollowThink ); } //----------------------------------------------------------------------------- // Purpose: Show this rocket turret has overloaded with effects and noise for a period of time //----------------------------------------------------------------------------- void CNPC_RocketTurret::DyingThink( void ) { // Make the beam graphics freak out a bit m_iLaserState = 2; UpdateSkin( ROCKET_SKIN_IDLE ); // If we've freaked out for long enough, be dead if ( m_flTimeSpentDying > ROCKET_TURRET_DEATH_EFFECT_TIME ) { Vector vForward; AngleVectors( m_vecCurrentAngles, &vForward, NULL, NULL ); g_pEffects->EnergySplash( EyePosition(), vForward, true ); m_OnDeath.FireOutput( this, this ); SetThink( &CNPC_RocketTurret::DeathThink ); SetNextThink( gpGlobals->curtime + 1.0f ); m_flTimeSpentDying = 0.0f; } SetNextThink( gpGlobals->curtime + ROCKET_TURRET_THINK_RATE ); m_flTimeSpentDying += ROCKET_TURRET_THINK_RATE; } //----------------------------------------------------------------------------- // Purpose: Sparks and fizzes to show it's broken. //----------------------------------------------------------------------------- void CNPC_RocketTurret::DeathThink( void ) { Vector vForward; AngleVectors( m_vecCurrentAngles, &vForward, NULL, NULL ); m_iLaserState = 0; SetEnemy( NULL ); g_pEffects->Sparks( EyePosition(), 1, 1, &vForward ); g_pEffects->Smoke( EyePosition(), 0, 6.0f, 20 ); SetNextThink( gpGlobals->curtime + RandomFloat( 2.0f, 8.0f ) ); } void CNPC_RocketTurret::UpdateMuzzleMatrix() { if ( gpGlobals->tickcount != m_muzzleToWorldTick ) { m_muzzleToWorldTick = gpGlobals->tickcount; GetAttachment( m_iMuzzleAttachment, m_muzzleToWorld ); } } //----------------------------------------------------------------------------- // Purpose: Avoid aiming/drawing beams while opening and closing // Input : - //----------------------------------------------------------------------------- void CNPC_RocketTurret::OpeningThink() { StudioFrameAdvance(); // Require these poses for this animation QAngle vecNeutralAngles ( 0, 90, 0 ); m_vecGoalAngles = m_vecCurrentAngles = vecNeutralAngles; SyncPoseToAimAngles(); // Start following player after we're fully opened float flCurProgress = GetCycle(); if ( flCurProgress >= 0.99f ) { LaserOn(); SetThink( &CNPC_RocketTurret::FollowThink ); } SetNextThink( gpGlobals->curtime + 0.1f ); } //----------------------------------------------------------------------------- // Purpose: Avoid aiming/drawing beams while opening and closing // Input : - //----------------------------------------------------------------------------- void CNPC_RocketTurret::ClosingThink() { LaserOff(); // Require these poses for this animation QAngle vecNeutralAngles ( 0, 90, 0 ); m_vecGoalAngles = vecNeutralAngles; // Once we're within 10 degrees of the neutral pose, start close animation. if ( UpdateFacing() <= 10.0f ) { StudioFrameAdvance(); } SetNextThink( gpGlobals->curtime + ROCKET_TURRET_THINK_RATE ); // Start following player after we're fully opened float flCurProgress = GetCycle(); if ( flCurProgress >= 0.99f ) { SetThink( NULL ); SetNextThink( TICK_NEVER_THINK ); } } //----------------------------------------------------------------------------- // Purpose: // Output : void SyncPoseToAimAngles //----------------------------------------------------------------------------- void CNPC_RocketTurret::SyncPoseToAimAngles ( void ) { QAngle localAngles = TransformAnglesToLocalSpace( m_vecCurrentAngles.Get(), EntityToWorldTransform() ); // Update pitch SetPoseParameter( m_iPosePitch, localAngles.x ); // Update yaw -- NOTE: This yaw movement is screwy for this model, we must invert the yaw delta and also skew an extra 90 deg to // get the 'forward face' of the turret to match up with the look direction. If the model and it's pose parameters change, this will be wrong. SetPoseParameter( m_iPoseYaw, AngleNormalize( -localAngles.y - 90 ) ); InvalidateBoneCache(); } //----------------------------------------------------------------------------- // Purpose: Causes the turret to face its desired angles // Returns distance current and goal angles the angles in degrees. //----------------------------------------------------------------------------- float CNPC_RocketTurret::UpdateFacing( void ) { Quaternion qtCurrent ( m_vecCurrentAngles.Get() ); Quaternion qtGoal ( m_vecGoalAngles ); Quaternion qtOut; float flDiff = QuaternionAngleDiff( qtCurrent, qtGoal ); // 1/10th degree is all the granularity we need, gives rocket player hit box width accuracy at 18k game units. if ( flDiff < 0.1 ) return flDiff; // Slerp 5% of the way to goal (distance dependant speed, but torque minimial and no euler wrapping issues). QuaternionSlerp( qtCurrent, qtGoal, 0.05, qtOut ); QAngle vNewAngles; QuaternionAngles( qtOut, vNewAngles ); m_vecCurrentAngles = vNewAngles; SyncPoseToAimAngles(); return flDiff; } //----------------------------------------------------------------------------- // Purpose: Tests if this prop's front point will have direct line of sight to it's target entity once the pose parameters are set to face it // Input : vAimPoint - The point to aim at // Output : Returns true if target is in direct line of sight, false otherwise. //----------------------------------------------------------------------------- bool CNPC_RocketTurret::TestLOS( const Vector& vAimPoint ) { // Snap to face (for accurate traces) QAngle vecOldAngles = m_vecCurrentAngles.m_Value; Vector vecToAimPoint = vAimPoint - EyePosition(); VectorAngles( vecToAimPoint, m_vecCurrentAngles.m_Value ); SyncPoseToAimAngles(); Vector vFaceOrigin = EyePosition(); trace_t trTarget; Ray_t ray; ray.Init( vFaceOrigin, vAimPoint ); ray.m_IsRay = true; // This aim point does hit target, now make sure there are no blocking objects in the way CTraceFilterSimple filter ( this, COLLISION_GROUP_NONE ); UTIL_Portal_TraceRay( ray, MASK_VISIBLE_AND_NPCS, &filter, &trTarget, false ); // Set model back to current facing m_vecCurrentAngles = vecOldAngles; SyncPoseToAimAngles(); return ( trTarget.m_pEnt == GetEnemy() ); } //----------------------------------------------------------------------------- // Purpose: Tests all portals in the turret's vis for possible routes to see it's target point // Input : pOutVec - The location to aim at in order to hit the target ent, choosing least rotation if multiple // bConsiderNonPortalAimPoint - Output in pOutVec the non portal (direct) aimpoint if it requires the least rotation // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CNPC_RocketTurret::TestPortalsForLOS( Vector* pOutVec, bool bConsiderNonPortalAimPoint = false ) { // Aim at the target through the world CBaseEntity* pTarget = GetEnemy(); if ( !pTarget ) { return false; } Vector vAimPoint = pTarget->GetAbsOrigin() + (pTarget->WorldAlignMins() + pTarget->WorldAlignMaxs()) * 0.5f; int iPortalCount = CProp_Portal_Shared::AllPortals.Count(); if( iPortalCount == 0 ) { *pOutVec = vAimPoint; return false; } Vector vCurAim; AngleVectors( m_vecCurrentAngles.m_Value, &vCurAim ); vCurAim.NormalizeInPlace(); CProp_Portal **pPortals = CProp_Portal_Shared::AllPortals.Base(); Vector *portalAimPoints = (Vector *)stackalloc( sizeof( Vector ) * iPortalCount ); bool *bUsable = (bool *)stackalloc( sizeof( bool ) * iPortalCount ); float *fPortalDot = (float *)stackalloc( sizeof( float ) * iPortalCount ); // Test through any active portals: This may be a shorter distance to the target for( int i = 0; i != iPortalCount; ++i ) { CProp_Portal *pTempPortal = pPortals[i]; if( !pTempPortal->m_bActivated || (pTempPortal->m_hLinkedPortal.Get() == NULL) ) { //portalAimPoints[i] = vec3_invalid; bUsable[i] = false; continue; } bUsable[i] = FindAimPointThroughPortal( pPortals[ i ], &portalAimPoints[ i ] ); if ( 1 ) { QAngle goalAngles; Vector vecToEnemy = portalAimPoints[ i ] - EyePosition(); vecToEnemy.NormalizeInPlace(); // This value is for choosing the easiest aim point for the turret to see through. // 'Easiest' is the least rotation needed. fPortalDot[i] = DotProduct( vecToEnemy, vCurAim ); } } int iCountPortalsThatSeeTarget = 0; float fHighestDot = -1.0; if ( bConsiderNonPortalAimPoint ) { QAngle enemyRotToFace; Vector vecToEnemy = vAimPoint - EyePosition(); vecToEnemy.NormalizeInPlace(); fHighestDot = DotProduct( vecToEnemy, vCurAim ); } // Compare aim points, use the closest aim point which has direct LOS for( int i = 0; i != iPortalCount; ++i ) { if( bUsable[i] ) { // This aim point has direct LOS if ( TestLOS( portalAimPoints[ i ] ) && fHighestDot < fPortalDot[ i ] ) { *pOutVec = portalAimPoints[ i ]; fHighestDot = fPortalDot[ i ]; ++iCountPortalsThatSeeTarget; } } } return (iCountPortalsThatSeeTarget != 0); } //----------------------------------------------------------------------------- // Purpose: Find the center of the target entity as seen through the specified portal // Input : pPortal - The portal to look through // Output : Vector& output point in world space where the target *appears* to be as seen through the portal //----------------------------------------------------------------------------- bool CNPC_RocketTurret::FindAimPointThroughPortal( const CProp_Portal* pPortal, Vector* pVecOut ) { if ( pPortal && pPortal->m_bActivated ) { CProp_Portal* pLinked = pPortal->m_hLinkedPortal.Get(); CBaseEntity* pTarget = GetEnemy(); // Require that the portal is facing towards the beam to test through it Vector vRocketToPortal, vPortalForward; VectorSubtract ( pPortal->GetAbsOrigin(), EyePosition(), vRocketToPortal ); pPortal->GetVectors( &vPortalForward, NULL, NULL); float fDot = DotProduct( vRocketToPortal, vPortalForward ); // Portal must be facing the turret, and have a linked partner if ( fDot < 0.0f && pLinked && pLinked->m_bActivated && pTarget ) { VMatrix matToPortalView = pLinked->m_matrixThisToLinked; Vector vTargetAimPoint = pTarget->GetAbsOrigin() + (pTarget->WorldAlignMins() + pTarget->WorldAlignMaxs()) * 0.5f; *pVecOut = matToPortalView * vTargetAimPoint; return true; } } // Bad portal pointer, not linked, no target or otherwise failed return false; } void CNPC_RocketTurret::LaserOn( void ) { // Set Locked sprite m_iLaserState = 1; } void CNPC_RocketTurret::LaserOff( void ) { // Set Locked sprite; m_iLaserState = 0; } //----------------------------------------------------------------------------- // Purpose: Allows a generic think function before the others are called // Input : state - which state the turret is currently in //----------------------------------------------------------------------------- bool CNPC_RocketTurret::PreThink( void ) { StudioFrameAdvance(); CheckPVSCondition(); //Do not interrupt current think function return false; } //----------------------------------------------------------------------------- // Purpose: Toggle the turret's state //----------------------------------------------------------------------------- void CNPC_RocketTurret::Toggle( void ) { //Toggle the state if ( m_bEnabled ) { Disable(); } else { Enable(); } } //----------------------------------------------------------------------------- // Purpose: Enable the turret and deploy //----------------------------------------------------------------------------- void CNPC_RocketTurret::Enable( void ) { if ( m_bEnabled ) return; m_bEnabled = true; ResetSequence( LookupSequence("open") ); SetThink( &CNPC_RocketTurret::OpeningThink ); SetNextThink( gpGlobals->curtime + 0.05 ); } //----------------------------------------------------------------------------- // Purpose: Retire the turret until enabled again //----------------------------------------------------------------------------- void CNPC_RocketTurret::Disable( void ) { if ( !m_bEnabled ) return; UpdateSkin( ROCKET_SKIN_IDLE ); m_bEnabled = false; ResetSequence(LookupSequence("close")); SetThink( &CNPC_RocketTurret::ClosingThink ); SetNextThink( gpGlobals->curtime + 0.05 ); SetEnemy( NULL ); } //----------------------------------------------------------------------------- // Purpose: Sets the enemy of this rocket // Input : pTarget - the enemy to set //----------------------------------------------------------------------------- void CNPC_RocketTurret::SetTarget( CBaseEntity* pTarget ) { SetEnemy( pTarget ); } //----------------------------------------------------------------------------- // Purpose: Explode and set death think //----------------------------------------------------------------------------- void CNPC_RocketTurret::Destroy( void ) { SetThink( &CNPC_RocketTurret::DyingThink ); SetNextThink( gpGlobals->curtime + 0.1f ); } void CNPC_RocketTurret::InputToggle( inputdata_t &inputdata ) { Toggle(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CNPC_RocketTurret::InputEnable( inputdata_t &inputdata ) { Enable(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CNPC_RocketTurret::InputDisable( inputdata_t &inputdata ) { Disable(); } void CNPC_RocketTurret::InputSetTarget( inputdata_t &inputdata ) { CBaseEntity *pTarget = gEntList.FindEntityByName( NULL, inputdata.value.String(), NULL, NULL ); SetTarget( pTarget ); } //----------------------------------------------------------------------------- // Purpose: Plays some 'death' effects and sets the destroy think // Input : &inputdata - //----------------------------------------------------------------------------- void CNPC_RocketTurret::InputDestroy( inputdata_t &inputdata ) { Destroy(); } //----------------------------------------------------------------------------- // Projectile methods //----------------------------------------------------------------------------- void CRocket_Turret_Projectile::Spawn( void ) { Precache(); BaseClass::Spawn(); SetTouch ( &CRocket_Turret_Projectile::MissileTouch ); CreateSounds(); } //----------------------------------------------------------------------------- // Purpose: // Input : *pOther - //----------------------------------------------------------------------------- void CRocket_Turret_Projectile::MissileTouch( CBaseEntity *pOther ) { Assert( pOther ); Vector vVel = GetAbsVelocity(); // Touched a launcher, and is heading towards that launcher if ( FClassnameIs( pOther, "npc_rocket_turret" ) ) { Dissolve( NULL, gpGlobals->curtime + 0.1f, false, ENTITY_DISSOLVE_NORMAL ); Vector vBounceVel = Vector( -vVel.x, -vVel.y, 200 ); SetAbsVelocity ( vBounceVel * 0.1f ); QAngle vBounceAngles; VectorAngles( vBounceVel, vBounceAngles ); SetAbsAngles ( vBounceAngles ); SetLocalAngularVelocity ( QAngle ( 180, 90, 45 ) ); UTIL_Remove ( m_hRocketTrail ); SetSolid ( SOLID_NONE ); if( m_hRocketTrail ) { m_hRocketTrail->SetLifetime(0.1f); m_hRocketTrail = NULL; } return; } // Don't touch triggers (but DO hit weapons) if ( pOther->IsSolidFlagSet(FSOLID_TRIGGER|FSOLID_VOLUME_CONTENTS) && pOther->GetCollisionGroup() != COLLISION_GROUP_WEAPON ) return; Explode(); } void CRocket_Turret_Projectile::Precache( void ) { BaseClass::Precache(); PrecacheScriptSound( ROCKET_PROJECTILE_LOOPING_SOUND ); } void CRocket_Turret_Projectile::NotifyLauncherOnDeath( void ) { CNPC_RocketTurret* pLauncher = (CNPC_RocketTurret*)m_hLauncher.Get(); if ( pLauncher ) { pLauncher->RocketDied(); } } // When teleported (usually by portal) void CRocket_Turret_Projectile::NotifySystemEvent(CBaseEntity *pNotify, notify_system_event_t eventType, const notify_system_event_params_t &params ) { // On teleport, we record a pointer to the portal we are arriving at if ( eventType == NOTIFY_EVENT_TELEPORT ) { // HACK: Clearing the owner allows collisions with launcher. // Players have had trouble realizing a launcher's own rockets don't kill it // because they didn't ever collide. We do this after a portal teleport so it avoids self-collisions on launch. SetOwnerEntity( NULL ); // Restart smoke trail UTIL_Remove( m_hRocketTrail ); m_hRocketTrail = NULL; // This shouldn't leak cause the pointer has been handed to the delete list CreateSmokeTrail(); } } void CRocket_Turret_Projectile::SetLauncher ( EHANDLE hLauncher ) { m_hLauncher = hLauncher; } void CRocket_Turret_Projectile::DoExplosion( void ) { NotifyLauncherOnDeath(); StopLoopingSounds(); // Explode ExplosionCreate( GetAbsOrigin(), GetAbsAngles(), GetOwnerEntity(), 200, 25, SF_ENVEXPLOSION_NOSPARKS | SF_ENVEXPLOSION_NODLIGHTS | SF_ENVEXPLOSION_NOSMOKE, 100.0f, this); // Hackish: Knock turrets in the area CBaseEntity* pTurretIter = NULL; while ( (pTurretIter = gEntList.FindEntityByClassnameWithin( pTurretIter, "npc_portal_turret_floor", GetAbsOrigin(), 128 )) != NULL ) { CTakeDamageInfo info( this, this, 200, DMG_BLAST ); info.SetDamagePosition( GetAbsOrigin() ); CalculateExplosiveDamageForce( &info, (pTurretIter->GetAbsOrigin() - GetAbsOrigin()), GetAbsOrigin() ); pTurretIter->VPhysicsTakeDamage( info ); } } void CRocket_Turret_Projectile::CreateSounds() { if (!m_pAmbientSound) { CSoundEnvelopeController &controller = CSoundEnvelopeController::GetController(); CPASAttenuationFilter filter( this ); m_pAmbientSound = controller.SoundCreate( filter, entindex(), ROCKET_PROJECTILE_LOOPING_SOUND ); controller.Play( m_pAmbientSound, 1.0, 100 ); } } void CRocket_Turret_Projectile::StopLoopingSounds() { CSoundEnvelopeController &controller = CSoundEnvelopeController::GetController(); controller.SoundDestroy( m_pAmbientSound ); m_pAmbientSound = NULL; BaseClass::StopLoopingSounds(); } void CRocket_Turret_Projectile::CreateSmokeTrail( void ) { if ( m_hRocketTrail ) return; // Smoke trail. if ( (m_hRocketTrail = RocketTrail::CreateRocketTrail()) != NULL ) { m_hRocketTrail->m_Opacity = 0.2f; m_hRocketTrail->m_SpawnRate = 100; m_hRocketTrail->m_ParticleLifetime = 0.8f; m_hRocketTrail->m_StartColor.Init( 0.65f, 0.65f , 0.65f ); m_hRocketTrail->m_EndColor.Init( 0.0, 0.0, 0.0 ); m_hRocketTrail->m_StartSize = 8; m_hRocketTrail->m_EndSize = 32; m_hRocketTrail->m_SpawnRadius = 4; m_hRocketTrail->m_MinSpeed = 2; m_hRocketTrail->m_MaxSpeed = 16; m_hRocketTrail->SetLifetime( 999 ); m_hRocketTrail->FollowEntity( this, "0" ); } } static void fire_rocket_projectile_f( void ) { CBasePlayer *pPlayer = (CBasePlayer *)UTIL_GetCommandClient(); Vector ptEyes, vForward; QAngle vLookAng; ptEyes = pPlayer->EyePosition(); pPlayer->EyeVectors( &vForward ); vLookAng = pPlayer->EyeAngles(); CRocket_Turret_Projectile *pRocket = (CRocket_Turret_Projectile *) CBaseEntity::Create( "rocket_turret_projectile", ptEyes, vLookAng, pPlayer ); if ( !pRocket ) return; pRocket->SetThink( NULL ); pRocket->SetMoveType( MOVETYPE_FLY ); pRocket->SetModel( ROCKET_TURRET_PROJECTILE_NAME ); UTIL_SetSize( pRocket, vec3_origin, vec3_origin ); pRocket->CreateSmokeTrail(); pRocket->SetAbsVelocity( vForward * 550 ); pRocket->SetLauncher ( NULL ); } ConCommand fire_rocket_projectile( "fire_rocket_projectile", fire_rocket_projectile_f, "Fires a rocket turret projectile from the player's eyes for testing.", FCVAR_CHEAT );
29.378014
173
0.654274
[ "vector", "model" ]
8e0d6ad049f7092e111381e280c540d39cdd26cb
7,784
cc
C++
shear_energy.cc
katiana22/GrassmannianEGO
6cd2c7225cf46aac1b08380d6c362f17b3a69a83
[ "MIT" ]
3
2021-09-09T13:05:06.000Z
2022-02-18T20:54:17.000Z
shear_energy.cc
katiana22/GrassmannianEGO
6cd2c7225cf46aac1b08380d6c362f17b3a69a83
[ "MIT" ]
null
null
null
shear_energy.cc
katiana22/GrassmannianEGO
6cd2c7225cf46aac1b08380d6c362f17b3a69a83
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <sys/types.h> #include <sys/stat.h> #include "common.hh" #include "extra.hh" #include "shear_sim.hh" // Temperature scale that is used to non-dimensionalize temperatures const double TZ=21000; // STZ formation energy, eZ/kB [K] const double kB=1.3806503e-23; // Boltzmann constant [J/K] const double kB_metal=8.617330350e-5; // Boltzmann constant [eV/K] const double eV_per_J=6.241509e18; // Converts eV to Joules const double Ez=TZ*kB*eV_per_J; // STZ formation Energy [eV] void syntax_message() { fputs("Syntax: ./shear_energy_Adam <run_type> <input_file> <beta> <u0> [additional arguments]\n\n" "<run_type> is either:\n" " \"direct\" for direct simulation,or\n" " \"qs\" for quasi-statc simulation\n\n" "<input_file> expects the relative path for a text file containing potential energy data\n\n" "<beta> is the initial energy scaling parameter [1/eV]\n\n" "<u0> is an energy offset value [eV]\n",stderr); exit(1); } int main(int argc,char **argv) { // Check command-line arguments if(argc<5) syntax_message(); bool qs=true; if(strcmp(argv[1],"direct") == 0) qs=false; else if(strcmp(argv[1],"qs") != 0) syntax_message(); double beta=atof(argv[3]),u0=atof(argv[4]); printf("Beta is set to %g 1/eV\n", beta); printf("u0 is set to %g eV\n", u0); // Set default values of parameters double rho0=6125; // Density (kg/m^3) double s_y=0.85; // Yield stress (GPa) double l_chi=4.01; double c0=0.3; // Plastic work fraction double ep=10; double chi_inf=2730; //char dfn_default[]="sct_d.out"; //char qfn_default[]="sct_q.out"; char er_default[]="pe.Cu.MD.100.txt"; char* endref=er_default; //char* qfn_=qfn_default; //char* dfn_=dfn_default; // Read additional command-line arguments to override default parameter values int i=5; while(i<argc) { if(read_arg(argv,"chi_inf",i,argc,chi_inf,"steady-state effective temperature"," K")) {} else if(read_arg(argv,"chi_len",i,argc,l_chi,"chi diffusion length scale"," Angstroms")) {} else if(read_arg(argv,"c0",i,argc,c0,"plastic work fraction","")) {} else if(read_arg(argv,"ep",i,argc,ep,"STZ size","")) {} else if(read_arg(argv,"s_y",i,argc,s_y,"yield stress","")) {} //else if(se(argv[i],"outdir")) { // if(++i==argc) { // fputs("Error reading command-line arguments\n", stderr); // return 1; // } // qfn_ = argv[i]; //} else if(se(argv[i],"endref")) { if(++i==argc) { fputs("Error reading command-line arguments\n",stderr); return 1; } printf("Reading final state from file %s\n",endref=argv[i]); } else { fprintf(stderr,"Command-line argument '%s' not recognized\n",argv[i]); } i++; } // If chi_inf was specified on the command line, then use that value. if(chi_inf>0) { printf("\nThe upper-limiting effective temperature was set using a user-defined value.\n" "The effective temperature is %g K.\n",chi_inf); chi_inf/=TZ; } else { // Open final MD PE reference file and determine maximum PE FILE *fp=safe_fopen(endref,"r"); double PE,maxPE=0; while(fscanf(fp,"%lf",&PE)) { if(PE>maxPE) maxPE=PE; } fclose(fp); // Compute value of chi_infinity from maximum potential energy chi_inf=0.95*beta*(maxPE-u0)*Ez/kB_metal/TZ; printf("\nThe maximum PE from the final snapshot is %g eV.\n" "For beta=%g and E0=%g the corresponding dimensionless value of" "chi_inf is %g. This is %g K.\n",maxPE,beta,u0,chi_inf,chi_inf*TZ); } // Rescaled elasticity parameters const double mu_phys = 20; const double mu = mu_phys/s_y; // Shear modulus (GPa) const double nu = 0.35; // Poisson's ratio (--) const double K = 2*mu*(1+nu)/(3*(1-2*nu)); // Bulk modulus (GPa) // STZ model parameters (based on Vitreloy 1 BMG) const double tau0=1e-13; // Vibration timescale (s) // Output filenames const char dfn[]="sct_d.out",qfn[]="sct_q.out"; //const char* dfn=dfn_; //const char* qfn=qfn_; // Output fields and miscellaneous flags. 1-u,2-v,4-p,8-q,16-s,32-tau, // 64-chi,128-tem,256-dev,512-X,1024-Y,2048-(total strain components), // 4096-(total strain invariants),8192-(Lagrangian tracer output). const unsigned int fflags=4|8|16|32|64|128|256|512|1024|2048|8192; // Other parameters. The scale factor applies a scaling to the rate of // plasticity and the applied strain. It is used to allow for comparison // between the explicit and quasi-static models. const double le=1e-10; // Length scale (m) const double sca=2e4; // Scale factor [only used in non-periodic test] const double visc=0; // Viscous damping // const double chi_len=l_chi*1e-10; // Dpl-mediated diffusion (m) const double chi_len=l_chi; // Dpl-mediated diffusion (m) const double adapt_fac=2e-3; // Adaptivity factor // MD simulation-based continuum parameters const int x_grid=32; // Grid points in x-direction const int y_grid=32; // Grid points in y-direction const double x_beg=0.0; // x-origin (m) const double x_end=4e-8; // x-terminus (m) const double y_beg=0.0; // y-origin (m) const double y_end=4e-8; // y-terminus (m) const double gam_max=0.5; // MD max strain // Compute conversion factor from simulation time to physical time. This // enters into the plasticity model. This value is determined automatically // from the length scale, density, and shear modulus in order to make shear // waves move at speed 1 in the simulation units. const double t_scale=le/sqrt(mu*s_y/rho0); // Set parameters for either a periodic or non-periodic test const bool y_prd=true; double u_bdry,lamb,lamb_phys,tf; if(y_prd) { // Periodic test u_bdry=0.; lamb_phys=1e8; // Strain rate (1/s) lamb=1e8*t_scale; // Strain rate in simulation units tf=gam_max/lamb; // Final time } else { // Non-periodic test u_bdry=1e-7*sca; lamb=0;tf=3e6/sca; } // Make the output directory if it doesn't already exist mkdir(qs?qfn:dfn,S_IRWXU|S_IRWXG|S_IROTH|S_IXOTH); // Initialize an STZ plasticity model stz_dynamics_adam stz(TZ,chi_inf,tau0,ep,c0); // Initialize the simulation shear_sim sim(x_grid,y_grid,x_beg/le,x_end/le,y_beg/le,y_end/le,mu,K, visc,chi_len,t_scale,adapt_fac,u_bdry,lamb,&stz,y_prd,fflags,qs? qfn : dfn); sim.init_fields(0,580,220); //sim.initialize_tracers(32,32); // Open the input file and read in the grid dimensions and scaling read_chi_from_file(argv[2],sim,u0,beta*Ez/kB_metal,TZ); //sim.initialize_random(5,580,20); // Carry out the simulation using the selected simulation method int n_frames=100,steps=60; printf("Simulation time unit : %g s\n",t_scale); printf("Final time : %g (%g s) \n",tf,tf*t_scale); printf("Quasi-static step size : %g \n",tf/(n_frames*steps)); qs?sim.solve_quasistatic(tf,n_frames,steps):sim.solve(tf,160); }
40.541667
103
0.603546
[ "model" ]
8e0e2e1f1c2003766c21a4de391b50b6a74d313d
38,798
cpp
C++
util/cpu-dir/ChiaSigScaled/CCCsig/CCCStatistics.cpp
ultimateabhi719/ChIA-PIPE
9bf89dd399eeef3e039f5bd1319f90e00ff763b7
[ "MIT" ]
14
2020-04-27T06:40:25.000Z
2022-02-17T04:57:07.000Z
util/cpu-dir/ChiaSigScaled/CCCsig/CCCStatistics.cpp
ultimateabhi719/ChIA-PIPE
9bf89dd399eeef3e039f5bd1319f90e00ff763b7
[ "MIT" ]
2
2020-09-03T16:52:41.000Z
2020-11-23T17:04:53.000Z
util/cpu-dir/ChiaSigScaled/CCCsig/CCCStatistics.cpp
ultimateabhi719/ChIA-PIPE
9bf89dd399eeef3e039f5bd1319f90e00ff763b7
[ "MIT" ]
7
2020-09-02T08:50:58.000Z
2021-12-03T16:21:48.000Z
// ChiaSig: detection of significant interactions in ChIA-PET data using Non-central hypergeometric distribution (NCHG) // This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package. // Copyright (2014) Jonas Paulsen #include "CCCStatistics.h" #include <iomanip> #include <iostream> #include <fstream> #include <assert.h> #include <errno.h> #include "bar.h" using namespace std; extern "C" { double cputime(); double realtime(); } // TODO: WCH [pending] void printPositives(ostream& ostr, string& chr, CCCMatrixInteraction& cpemat, double alpha, uint32_t cutoff, bool printNij /*=false*/, bool printAll /*=false*/) { assert(cpemat.isIntra); cpemat.printPositives(ostr, chr, alpha, cutoff, printNij, printAll); } // Utils: // WCH: loop does not terminate template<typename T> vector<T> getSequence(T from, T to, uint32_t length) { #if 0 assert(to > from); #else assert(to >= from); #endif vector<T> res; T stepSize=(to-from)/(length-1); T i = from; for(uint32_t c=0; c<length; c++) { res.push_back(i); i+=stepSize; } return res; } pair<double, double> getAlphaRange(map<double, double> alpha2FDR, double minFDR) { typedef map<double, double>::iterator it2; //WCH double alpha=0, FDR=0; pair<double, double> res; res.first = 0; res.second = 0; for(it2 iter = alpha2FDR.begin(); iter != alpha2FDR.end(); iter++) { alpha = iter->first; FDR = iter->second; //cout << "alpha/FDR: " << alpha << " " << FDR << endl; fprintf(stderr, "[M::%s:%d] Re-estimating alpha/FDR=%.6e, FDR=%.6e%s\n", __func__, __LINE__, alpha, FDR, (FDR<minFDR)?" (*)":""); if(FDR > minFDR) { if(res.first != 0 ) { res.second = alpha; fprintf(stderr, "[M::%s:%d] success! FDR(%.6e)>minFDR(%.6e)\n", __func__, __LINE__, FDR, minFDR); return res; // success! minFDR is within the range } else { // minFDR is not within the range. C res.first = 0; res.second = alpha; fprintf(stderr, "[M::%s:%d] minFDR(%.6e) is not within range\n", __func__, __LINE__, minFDR); return res; // the right alpha must be somewhere between 0 and minFDR } } res.first = alpha; } // At this point, the right alpha must be somewhere between alpha and minFDR fprintf(stderr, "[M::%s:%d] right alpha is between alpha(%.6e) and minFDR(%.6e)\n", __func__, __LINE__, alpha, minFDR); res.second = minFDR; return res; } // TODO: WCH [coded] static int G_nThreads = 1; void setThreads(int n) { G_nThreads = n; } void kt_for(int n_threads, void (*func)(void*,int,int), void *data, int n); bool chromSegmentCountDesc(const pair<ChromosomeIndexType, uint32_t >& a, const pair<ChromosomeIndexType, uint32_t >& b) { return b.second < a.second; } // this routine will estimate the largest alpha such that the FDR<fdr map<double, double> estimateFDRAlpha(const char *szDataFile, vector<string>& chromosomes, vector<pair<ChromosomeIndexType, uint64_t > >&chromosomesRows, map<ChromosomeIndexType, CCCMatrixInteraction>& cmpmat, double fdr, uint32_t refinesteps, bool noEarlyTermination/*=false*/, uint32_t cutoff /*=3*/, uint32_t deltaCutoff /*=8000*/, uint32_t maxDelta /*=MAXDELTA*/) { double t_diff; double t_start = realtime(); double t_start_iter; map<double, pair<uint64_t, double> > tmp; map<double, double> res; double alphaLower = 0.0; double alphaUpper = fdr / 100.0; double alpha = alphaUpper; uint32_t numStep = 1; uint64_t maxAlphaPositives = 0; uint64_t numPositives = 0; double numFalsePositives = 0.0; bool maxAlphaPositivesIncreasing = true; uint64_t cutoffMaxPositive = 0; string szTmpDataFile(szDataFile); szTmpDataFile.append(".tmp"); // let's attempt to restore if we may bool bResumedOperation = false; { ifstream fdrPersistence(szDataFile, ios::in); if (fdrPersistence.is_open()) { double savedFDR; fdrPersistence >> savedFDR; uint32_t savedNumStep; fdrPersistence >> savedNumStep; // TODO: there is a need to set alpha, alphaLower, alphaUpper, maxAlphaPositives uint32_t numFDRs = 0; while (true) { // read in the line of data double savedAlpha; uint64_t savedNumPositives; double savedNumFalsePositives; double savedFDR; fdrPersistence >> savedAlpha >> savedNumPositives >> savedNumFalsePositives >> savedFDR; if (fdrPersistence.eof()) break; // process the line of data tmp[savedAlpha] = make_pair(savedNumPositives, savedNumFalsePositives); // TODO: if there is NO savedFDR double alphaFDR = (0==savedNumPositives) ? 0.0 : savedNumFalsePositives / savedNumPositives; res[savedAlpha] = alphaFDR; numFDRs++; } // TODO: let's set up the progressive logic to make sure that we do NOT perform an additional run! if (numFDRs>0) { if (numFDRs != savedNumStep) { savedNumStep = numFDRs; } double savedAlphaLower = 0.0; double savedAlphaUpper = fdr; //WCH: original is fdr / 100.0; uint64_t savedMaxAlphaPositives = 0; for(map<double, pair<uint64_t, double> >::iterator iter = tmp.begin(); iter != tmp.end(); iter++) { double savedAlpha = iter->first; uint64_t savedNumPositives = iter->second.first; double savedNumFalsePositives = iter->second.second; double savedFDR = (0==savedNumPositives) ? 0.0 : savedNumFalsePositives / savedNumPositives; if (savedFDR<fdr) { if (savedAlpha>savedAlphaLower) { savedAlphaLower = savedAlpha; if (savedNumPositives>savedMaxAlphaPositives) savedMaxAlphaPositives = savedNumPositives; else maxAlphaPositivesIncreasing = false; } } else { if (savedAlpha<savedAlphaUpper) { savedAlphaUpper = savedAlpha; if (savedNumPositives<=savedMaxAlphaPositives) maxAlphaPositivesIncreasing = false; break; } } } // set up the bounds and conditions alphaLower = savedAlphaLower; alphaUpper = savedAlphaUpper; numStep = savedNumStep; maxAlphaPositives = savedMaxAlphaPositives; alpha = 0.5 * (alphaLower + alphaUpper); bResumedOperation = true; if (maxAlphaPositivesIncreasing) { // there are more work to do fprintf(stderr, "[M::%s:%d] estimateFDR %u iteraction results RESTORED.\n", __func__, __LINE__, numStep); } else { // result improvement impossible fprintf(stderr, "[M::%s:%d] estimateFDR %u iteraction results RESTORED. NO further iteraction needed.\n", __func__, __LINE__, numStep); } } } fdrPersistence.close(); } // get the first FDR estimation if (!bResumedOperation) { t_start_iter = realtime(); numPositives = 0; numFalsePositives = 0.0; for(vector<pair<ChromosomeIndexType, uint64_t > >::iterator itChrom = chromosomesRows.begin(); itChrom!=chromosomesRows.end(); ++itChrom) { double t_chrStart = realtime(); numPositives += cmpmat[itChrom->first].getNumberOfPositives(alpha, cutoff); numFalsePositives += cmpmat[itChrom->first].estimateFalsePositives(alpha, cutoff, deltaCutoff, maxDelta); t_diff = realtime() - t_chrStart; fprintf(stderr, "[M::%s:%d] estimateFDR %s FP:%.2f P:%llu rtmin:%.2f..\n", __func__, __LINE__, chromosomes[itChrom->first].c_str(), numFalsePositives, numPositives, t_diff/60.0); } tmp[alpha] = make_pair(numPositives, numFalsePositives); double alphaFDR = (0==numPositives) ? 0.0 : numFalsePositives / numPositives; res[alpha] = alphaFDR; t_diff = realtime() - t_start_iter; fprintf(stderr, "[M::%s:%d] step:%d alpha:%.6e FDR:%.6e FP:%.2f P:%llu rtmin:%.2f%s\n", __func__, __LINE__, numStep, alpha, alphaFDR, numFalsePositives, numPositives, t_diff/60.0, ((alphaFDR<fdr)?" (*)":"")); // let's attempt to persist for resumability { ofstream fdrPersistence(szTmpDataFile.c_str(), ios::out); fdrPersistence << scientific << setprecision(6) << fdr << endl; fdrPersistence << numStep << endl; for(map<double, pair<uint64_t, double> >::iterator iter = tmp.begin(); iter != tmp.end(); iter++) { double savedAlpha = iter->first; uint64_t savedNumPositives = iter->second.first; double savedNumFalsePositives = iter->second.second; double savedFDR = (0==savedNumPositives) ? 0.0 : savedNumFalsePositives / savedNumPositives; fdrPersistence << scientific << setprecision(6) << savedAlpha << "\t" << savedNumPositives << "\t" << scientific << setprecision(6) << savedNumFalsePositives << "\t" << scientific << setprecision(6) << savedFDR << endl; } fdrPersistence.close(); if (0!=remove(szDataFile)) { if (2!=errno) fprintf(stderr, "[M::%s:%d] step:%d FAILED to remove earlier progress file, errno=%d.\n", __func__, __LINE__, numStep, errno); } if (0!=rename(szTmpDataFile.c_str(), szDataFile)) { fprintf(stderr, "[M::%s:%d] step:%d FAILED to rename latest progress file, errno=%d.\n", __func__, __LINE__, numStep, errno); } else { fprintf(stderr, "[M::%s:%d] step:%d progress saved.\n", __func__, __LINE__, numStep); } } if (alphaFDR >= fdr) { // we still have much larger FDR, so we need a more stringent alpha alphaUpper = alpha; alpha = 0.5 * (alphaLower + alphaUpper); // new smallest positives which FDR is exceeded } else if (alphaFDR < fdr) { // there are more positives that we can report, relax the alpha alphaLower = alpha; alphaUpper = fdr; // we set the Upper bound to a higher alpha alpha = 0.5 * (alphaLower + alphaUpper); // new lower bound of the attainable positives maxAlphaPositives = numPositives; } } if (numStep<=refinesteps && maxAlphaPositivesIncreasing) { // attempt to establish possible range to start iteration t_start_iter = realtime(); // let's attempt to estimate a better alpha cutoffMaxPositive = 0; for(vector<pair<ChromosomeIndexType, uint64_t > >::iterator itChrom = chromosomesRows.begin(); itChrom!=chromosomesRows.end(); ++itChrom) { double t_chrStart = realtime(); cmpmat[itChrom->first].getPositivesBound(cutoff, cutoffMaxPositive); t_diff = realtime() - t_chrStart; fprintf(stderr, "[M::%s:%d] estimateAlpha %s cutoff=%u positives=%llu rtmin:%.2f\n", __func__, __LINE__, chromosomes[itChrom->first].c_str(), cutoff, cutoffMaxPositive, t_diff/60.0); } t_diff = realtime() - t_start_iter; fprintf(stderr, "[M::%s:%d] estimateAlpha genome took %.2f\n", __func__, __LINE__, t_diff/60.0); } // iterate on FDR estimation until the specified number of steps or no better result possible numStep++; while(numStep<=refinesteps && maxAlphaPositivesIncreasing) { double t_start_iter = realtime(); uint64_t numPositives = 0; double numFalsePositives = 0.0; for(vector<pair<ChromosomeIndexType, uint64_t > >::iterator itChrom = chromosomesRows.begin(); itChrom!=chromosomesRows.end(); ++itChrom) { double t_chrStart = realtime(); numPositives += cmpmat[itChrom->first].getNumberOfPositives(alpha, cutoff); numFalsePositives += cmpmat[itChrom->first].estimateFalsePositives(alpha, cutoff, deltaCutoff, maxDelta); t_diff = realtime() - t_chrStart; fprintf(stderr, "[M::%s:%d] estimateFDR %s FP:%.2f P:%llu rtmin:%.2f..\n", __func__, __LINE__, chromosomes[itChrom->first].c_str(), numFalsePositives, numPositives, t_diff/60.0); } tmp[alpha] = make_pair(numPositives, numFalsePositives); double alphaFDR = (0==numPositives) ? 0.0 : numFalsePositives / numPositives; res[alpha] = alphaFDR; t_diff = realtime() - t_start_iter; fprintf(stderr, "[M::%s:%d] step:%u alpha:%.6e FDR:%.6e FP:%.2f P:%llu rtmin:%.2f%s\n", __func__, __LINE__, numStep, alpha, alphaFDR, numFalsePositives, numPositives, t_diff/60.0, ((alphaFDR<fdr)?" (*)":"")); // let's attempt to persist for resumability { ofstream fdrPersistence(szTmpDataFile.c_str(), ios::out); fdrPersistence << scientific << setprecision(6) << fdr << endl; fdrPersistence << numStep << endl; for(map<double, pair<uint64_t, double> >::iterator iter = tmp.begin(); iter != tmp.end(); iter++) { double savedAlpha = iter->first; uint64_t savedNumPositives = iter->second.first; double savedNumFalsePositives = iter->second.second; double savedFDR = (0==savedNumPositives) ? 0.0 : savedNumFalsePositives / savedNumPositives; fdrPersistence << scientific << setprecision(6) << savedAlpha << "\t" << savedNumPositives << "\t" << scientific << setprecision(6) << savedNumFalsePositives << "\t" << scientific << setprecision(6) << savedFDR << endl; } fdrPersistence.close(); if (0!=remove(szDataFile)) { if (2!=errno) fprintf(stderr, "[M::%s:%d] step:%d FAILED to remove earlier progress file, errno=%d.\n", __func__, __LINE__, numStep, errno); } if (0!=rename(szTmpDataFile.c_str(), szDataFile)) { fprintf(stderr, "[M::%s:%d] step:%d FAILED to rename latest progress file, errno=%d.\n", __func__, __LINE__, numStep, errno); } else { fprintf(stderr, "[M::%s:%d] step:%d progress saved.\n", __func__, __LINE__, numStep); } } // let's decide on the next alpha to try if (alphaFDR >= fdr) { // we still have much larger FDR, so we need a more stringent alpha alphaUpper = alpha; alpha = 0.5 * (alphaLower + alphaUpper); } else if (alphaFDR < fdr) { // there are more positives that we can report, relax the alpha alphaLower = alpha; alpha = 0.5 * (alphaLower + alphaUpper); // early termination if (numPositives>maxAlphaPositives) { maxAlphaPositives = numPositives; if (maxAlphaPositives==cutoffMaxPositive) { fprintf(stderr, "[M::%s:%d] #Positives reached maximum (%llu) attainable for cutoff>=%u at step#%u\n", __func__, __LINE__, cutoffMaxPositive, cutoff, numStep); if (!noEarlyTermination) maxAlphaPositivesIncreasing = false; if (numStep<refinesteps) fprintf(stderr, "[M::%s:%d] Results will not improve further. Terminating iterative process..\n", __func__, __LINE__); } } else { // TODO: for testing purpsoes; TO turn on afterward if (!noEarlyTermination) maxAlphaPositivesIncreasing = false; if (numStep<refinesteps) fprintf(stderr, "[M::%s:%d] Results will not improve further. Terminating iterative process..\n", __func__, __LINE__); } } numStep++; } t_diff = realtime() - t_start; fprintf(stderr, "[M::%s:%d] estimateFDR took %.2f min..\n", __func__, __LINE__, t_diff/60.0); return res; } struct delta_quantile_precompute_worker_t { delta_quantile_precompute_worker_t(uint32_t *pds, uint32_t cs, uint32_t qi) : pDeltas(pds), chunkStart(cs), quantileIndex(qi) {} uint32_t *pDeltas; uint32_t chunkStart; uint32_t quantileIndex; }; struct delta_quantile_chunk_precompute_worker_t { delta_quantile_chunk_precompute_worker_t(uint32_t *pds, vector<uint32_t>& cs, vector<uint32_t>& ce) : pDeltas(pds), chunkStarts(cs), chunkEnds(ce) {} uint32_t *pDeltas; vector<uint32_t>& chunkStarts; vector<uint32_t>& chunkEnds; }; /* static void delta_quantile_chunk_precompute_worker(void *data, int idx, int tid) { delta_quantile_chunk_precompute_worker_t *w = (delta_quantile_chunk_precompute_worker_t*)data; for(uint32_t i=w->chunkStarts[idx]; i<=w->chunkEnds[idx]; ++i) w->pDeltas[i] = idx; } */ struct delta_quantile_statistics_worker_t { delta_quantile_statistics_worker_t(uint32_t *pds, uint32_t *pss, vector<uint32_t>& cs, vector<uint32_t>& ce, vector<DeltaStatistics >& dss) : pDeltas(pds), pSums(pss), chunkStarts(cs), chunkEnds(ce), deltasStats(dss) {} uint32_t *pDeltas; uint32_t *pSums; vector<uint32_t>& chunkStarts; vector<uint32_t>& chunkEnds; vector<DeltaStatistics >& deltasStats; }; static void delta_quantile_statistics_worker(void *data, int idx, int tid) { delta_quantile_statistics_worker_t *w = (delta_quantile_statistics_worker_t*)data; for(uint32_t i=w->chunkStarts[idx]; i<=w->chunkEnds[idx]; ++i) { w->deltasStats[idx].count += w->pDeltas[i]; w->deltasStats[idx].sum += w->pSums[i]; } } // experimental function: under optimization testing void estimateDeltaSpline(const char *szDataFile, spline& s, vector<double>& sx, DeltaCountSums& deltaCountSums, vector<string>& chromosomes, vector<pair<ChromosomeIndexType, uint64_t > >&chromosomesRows, map<ChromosomeIndexType, CCCMatrixInteraction>& cmpmat, uint32_t minDelta /*=8000*/, uint32_t maxDelta /*=MAXDELTA*/, bool masking /*=false*/, uint32_t percentiles /*=1000*/, bool dumpSpline/*=false*/) { ofstream fileDump; if (dumpSpline) fileDump.open(masking ? "deltas.refined.xls" : "deltas.exact.xls"); double t_diff; // Get all deltas for all chromosomes: QuantileMapper quantileMapper; // deltas allocations if (0==deltaCountSums.nMaxSpan) { uint32_t nMaxSpan = 0; for(ChromosomeIndexType i=0; i<chromosomes.size(); ++i) { uint32_t maxChromSpan = cmpmat[i].getWidestInteractionSpan(); if (maxChromSpan>nMaxSpan) nMaxSpan = maxChromSpan; } nMaxSpan++; // 0-based index, so need 1 more allocation fprintf(stderr, "[M::%s:%d] max span = %u\n", __func__, __LINE__, nMaxSpan); // NOTE: deltas stores count, the index is actually the span deltaCountSums.init(nMaxSpan); } double t_start = realtime(); // attempt to restore from persistence // in event that persistence is incomplete, repeat the process bool bResumedOperation = false; if (!masking) { ifstream deltaPersistence(szDataFile, ios::in | ios::binary); if (deltaPersistence.is_open()) { // for sanity check uint32_t nMaxSpan; deltaPersistence.read((char *)(&nMaxSpan), sizeof(nMaxSpan)); if (deltaPersistence) { if (deltaCountSums.nMaxSpan==nMaxSpan) { // read the rest of the summary deltaPersistence.read((char *)(&(deltaCountSums.ulTotalDeltas)), sizeof(deltaCountSums.ulTotalDeltas)); if (deltaPersistence) { // read the rest of the elements value deltaPersistence.read((char *)(deltaCountSums.pDeltas), nMaxSpan*sizeof(*deltaCountSums.pDeltas)); if (deltaPersistence) { deltaPersistence.read((char *)(deltaCountSums.pSums), nMaxSpan*sizeof(*deltaCountSums.pSums)); if (deltaPersistence) { // sanity check on BIT_ARRAY bit_index_t num_of_bits; deltaPersistence.read((char *)(&num_of_bits), sizeof(num_of_bits)); if (deltaPersistence) { if (deltaCountSums.deltaPresences->num_of_bits==num_of_bits) { word_addr_t num_of_words; deltaPersistence.read((char *)(&num_of_words), sizeof(num_of_words)); if (deltaPersistence) { if (deltaCountSums.deltaPresences->num_of_words==num_of_words) { // okie to read in the data now! deltaPersistence.read((char *)(deltaCountSums.deltaPresences->words), deltaCountSums.deltaPresences->num_of_words*sizeof(*deltaCountSums.deltaPresences->words)); if (deltaPersistence) { bResumedOperation = true; } else { // fail to read all the deltas presence bits fprintf(stderr, "[M::%s:%d] FAILED to restore Deltas' presence bits. Will recompute..\n", __func__, __LINE__); } } else { // bits configration does not agree!! fprintf(stderr, "[M::%s:%d] FAILED to restore. Inconsistent word configuration (recorded: %llu vs computed: %llu). Will recompute..\n", __func__, __LINE__, num_of_words, deltaCountSums.deltaPresences->num_of_words); } } else { // fail to read all the deltas presence word configuration fprintf(stderr, "[M::%s:%d] FAILED to restore Deltas' word configuration. Will recompute..\n", __func__, __LINE__); } } else { // bits configration does not agree!! fprintf(stderr, "[M::%s:%d] FAILED to restore. Inconsistent bit configuration (recorded: %llu vs computed: %llu). Will recompute..\n", __func__, __LINE__, num_of_bits, deltaCountSums.deltaPresences->num_of_bits); } } else { // fail to read all the deltas presence bit configuration fprintf(stderr, "[M::%s:%d] FAILED to restore Deltas' bit configuration. Will recompute..\n", __func__, __LINE__); } } else { // fail to read all the deltas sum fprintf(stderr, "[M::%s:%d] FAILED to restore Deltas' sum. Will recompute..\n", __func__, __LINE__); } } else { // fail to read all the deltas count fprintf(stderr, "[M::%s:%d] FAILED to restore Deltas' count. Will recompute..\n", __func__, __LINE__); } } else { // fail to read the total number of deltas fprintf(stderr, "[M::%s:%d] FAILED to restore TotalDeltas. Will recompute..\n", __func__, __LINE__); } } else { // MaxSpan does not agree!! fprintf(stderr, "[M::%s:%d] FAILED to restore. Inconsistent MaxSpan (recorded: %u vs computed: %u). Will recompute..\n", __func__, __LINE__, nMaxSpan, deltaCountSums.nMaxSpan); } } else { // fail to read the number of unique deltas fprintf(stderr, "[M::%s:%d] FAILED to restore MaxSpan. Will recompute..\n", __func__, __LINE__); } deltaPersistence.close(); // if we cannot resume, it is safer to re-initialize if (!bResumedOperation) { deltaCountSums.terminate(); deltaCountSums.init(nMaxSpan); } else { t_diff = realtime() - t_start; fprintf(stderr, "[M::%s:%d] #deltas(genome)=%llu RESTORED, %.2f min..\n", __func__, __LINE__, deltaCountSums.ulTotalDeltas, t_diff/60.0); } } } // work horse: getting all the possible deltas from the contact matrix if (!bResumedOperation) { t_start = realtime(); deltaCountSums.ulTotalDeltas = 0; if (masking) { for(ChromosomeIndexType i=0; i<chromosomes.size(); ++i) { double t_subStart = realtime(); ChromosomeIndexType nChrIdx = chromosomesRows[i].first; uint64_t ulDeltas = cmpmat[nChrIdx].maskDeltasCountSum(deltaCountSums.pDeltas, deltaCountSums.pSums, deltaCountSums.deltaPresences, deltaCountSums.nMaxSpan+1, minDelta, maxDelta); deltaCountSums.ulTotalDeltas += ulDeltas; t_diff = realtime() - t_subStart; fprintf(stderr, "[M::%s:%d] #deltas(%s)=%llu collected, %.2f min..\n", __func__, __LINE__, chromosomes[nChrIdx].c_str(), ulDeltas, t_diff/60.0); } } else { for(ChromosomeIndexType i=0; i<chromosomes.size(); ++i) { double t_subStart = realtime(); ChromosomeIndexType nChrIdx = chromosomesRows[i].first; uint64_t ulDeltas = cmpmat[nChrIdx].getDeltasCountSum(deltaCountSums.pDeltas, deltaCountSums.pSums, deltaCountSums.deltaPresences, deltaCountSums.nMaxSpan+1, minDelta, maxDelta, masking); deltaCountSums.ulTotalDeltas += ulDeltas; t_diff = realtime() - t_subStart; fprintf(stderr, "[M::%s:%d] #deltas(%s)=%llu collected, %.2f min..\n", __func__, __LINE__, chromosomes[nChrIdx].c_str(), ulDeltas, t_diff/60.0); } } t_diff = realtime() - t_start; fprintf(stderr, "[M::%s:%d] #deltas(genome)=%llu collected, %.2f min..\n", __func__, __LINE__, deltaCountSums.ulTotalDeltas, t_diff/60.0); } // Let's save these delta summary into persistence if (!(masking || bResumedOperation)) { t_start = realtime(); bool persisted = false; ofstream deltaPersistence(szDataFile, ios::out | ios::binary); // 1st object if (deltaPersistence.write((char *)(&(deltaCountSums.nMaxSpan)), sizeof(deltaCountSums.nMaxSpan))) { // 2nd object if (deltaPersistence.write((char *)(&(deltaCountSums.ulTotalDeltas)), sizeof(deltaCountSums.ulTotalDeltas))) { // 3rd object - deltas if (deltaPersistence.write((char *)(deltaCountSums.pDeltas), deltaCountSums.nMaxSpan*sizeof(*deltaCountSums.pDeltas))) { // 3rd object - sums if (deltaPersistence.write((char *)(deltaCountSums.pSums), deltaCountSums.nMaxSpan*sizeof(*deltaCountSums.pSums))) { // 3rd object - msking if (deltaPersistence.write((char *)(&(deltaCountSums.deltaPresences->num_of_bits)), sizeof(deltaCountSums.deltaPresences->num_of_bits))) { if (deltaPersistence.write((char *)(&(deltaCountSums.deltaPresences->num_of_words)), sizeof(deltaCountSums.deltaPresences->num_of_words))) { if (deltaPersistence.write((char *)(deltaCountSums.deltaPresences->words), deltaCountSums.deltaPresences->num_of_words*sizeof(*deltaCountSums.deltaPresences->words))) { persisted = true; } else { fprintf(stderr, "[M::%s:%d] FAILED to save Deltas' presence bits. Non-resumable in future..\n", __func__, __LINE__); } } else { fprintf(stderr, "[M::%s:%d] FAILED to save Deltas' word configuration. Non-resumable in future..\n", __func__, __LINE__); } } else { fprintf(stderr, "[M::%s:%d] FAILED to save Deltas' bit configuration. Non-resumable in future..\n", __func__, __LINE__); } } else { fprintf(stderr, "[M::%s:%d] FAILED to save Deltas' sum. Non-resumable in future..\n", __func__, __LINE__); } } else { fprintf(stderr, "[M::%s:%d] FAILED to save Deltas' count. Non-resumable in future..\n", __func__, __LINE__); } } else { fprintf(stderr, "[M::%s:%d] FAILED to save TotalDeltas. Non-resumable in future..\n", __func__, __LINE__); } } else { fprintf(stderr, "[M::%s:%d] FAILED to save MaxSpan. Non-resumable in future..\n", __func__, __LINE__); } deltaPersistence.close(); if (persisted) { t_diff = realtime() - t_start; fprintf(stderr, "[M::%s:%d] #deltas(genome)=%llu PERSISTED, %.2f min..\n", __func__, __LINE__, deltaCountSums.ulTotalDeltas, t_diff/60.0); } } /* // DEBUG: WCH - for deltas checking { ofstream fileDump2; fileDump2.open(masking ? "deltas.refined.xls.baseline.opt19.4.14n" : "deltas.exact.xls.baseline.opt19.4.14n"); //unsigned int z=0; unsigned long nCurrCount = 0; for(int i=0; nCurrCount<ulTotalDeltas; ++i) { if (pDeltas[i]>0) { //for(int x=0; x<pDeltas[i]; x++) { fileDump2 << i << "\t" << pDeltas[i] << endl; //z++; //if (1000000==z) break; //} //if (1000000==z) break; nCurrCount += pDeltas[i]; } } fileDump2.close(); } // END - DEBUG: WCH - for deltas checking */ // NOTE: pDeltas needs to hold the count for quantile computation to work // NOTE: pDelta = indicator + count; but ONLY count is needed here!!! double t_subStart = realtime(); quantileMapper.computeDeltaCountQuantile(deltaCountSums.ulTotalDeltas, deltaCountSums.pDeltas, percentiles, (dumpSpline ? &fileDump : NULL)); t_diff = realtime() - t_subStart; fprintf(stderr, "[M::%s:%d] delta quantiles computation deltas took %.2f min..\n", __func__, __LINE__, t_diff/60.0); if (dumpSpline) { fileDump << endl; fileDump << "Deltas statistics" << endl; fileDump << "quantileUpper\tquantileRep" << endl; vector<uint32_t>& quantileDeltas = quantileMapper.getQuantileDeltas(); for(vector<uint32_t>::iterator it=quantileDeltas.begin(); it!=quantileDeltas.end(); ++it) { fileDump << (*it) << "\t" << quantileMapper.getDeltaQuantile(*it) << endl; } } t_start = realtime(); vector<DeltaStatistics > deltasStats; { vector<uint32_t>& quantileDeltas = quantileMapper.getQuantileDeltas(); deltasStats.resize(quantileDeltas.size()); // multithreading version vector<uint32_t> chunkStarts; chunkStarts.resize(quantileDeltas.size()); chunkStarts[0] = minDelta; for(uint32_t idx=1; idx<quantileDeltas.size(); ++idx) { chunkStarts[idx] = quantileDeltas[idx-1]+1; } // NOTE: pDelta = indicator + count ==> indicator + qunatile delta_quantile_statistics_worker_t w(deltaCountSums.pDeltas, deltaCountSums.pSums, chunkStarts, quantileDeltas, deltasStats); kt_for(G_nThreads, delta_quantile_statistics_worker, &w, (int)quantileDeltas.size()); } t_diff = realtime() - t_start; fprintf(stderr, "[M::%s:%d] delta quantiles statistics computation (genome) took %.2f min..\n", __func__, __LINE__, t_diff/60.0); if (dumpSpline) { fileDump << endl; fileDump << "Deltas statistics" << endl; fileDump << "deltaRep\tsum\tcount\tmean" << endl; vector<uint32_t>& quantiless = quantileMapper.getQuantiles(); for(uint32_t idx=0; idx<quantiless.size(); ++idx) { uint32_t deltaQuantileRep = quantiless[idx]; fileDump << deltaQuantileRep << "\t" << deltasStats[idx].sum << "\t" << deltasStats[idx].count << "\t" << deltasStats[idx].getMean() << endl; } } //vector<double> delta_x; // x-object for spline generation sx.clear(); vector<double> exp_y; // y-object for spline generation { vector<uint32_t>& quantiless = quantileMapper.getQuantiles(); for(uint32_t idx=0; idx<quantiless.size(); ++idx) { sx.push_back((double)(quantiless[idx])); exp_y.push_back((double)(deltasStats[idx].getMean())); } } //spline s; // If x is not sorted, an error will occur. //s.set_points(delta_x,exp_y); // currently it is required that X is already sorted s.set_points(sx,exp_y); // currently it is required that X is already sorted // NOTE: pDeltas needs to indicate if the precomputation for a particular delta value should be carried out // pre-compute the appropriate deltas t_subStart = realtime(); s.precompute(deltaCountSums.nMaxSpan, deltaCountSums.deltaPresences); t_diff = realtime() - t_subStart; fprintf(stderr, "[M::%s:%d] delta expectation pre-computation took %.2f min..\n", __func__, __LINE__, t_diff/60.0); //free(pDeltas); //free(pSums); //bardestroy(deltaPresences); if (dumpSpline) { fileDump << endl; fileDump << "Spline data points" << endl; fileDump << "x\ty\ta\tb\tc" << endl; for(vector<double>::size_type e = 0 ; e<s.m_x.size(); ++e) { fileDump << s.m_x[e] << "\t" << s.m_y[e] << "\t" << s.m_a[e] << "\t" << s.m_b[e] << "\t" << s.m_c[e] << endl; } fileDump.close(); } } void estimateResources(string& filename, vector<string>& chromosomes, vector<pair<ChromosomeIndexType, uint64_t > >&chromosomesRows, map<ChromosomeIndexType, CCCMatrixInteraction>& cmpmat, uint32_t minDelta/*=8000*/, uint32_t maxDelta/*=MAXDELTA*/, bool masking/*=false*/) { double t_diff; double t_start = realtime(); // Get all deltas for all chromosomes: vector<uint64_t> chromDeltaCounts; uint64_t ulTotalDeltas = 0; for(ChromosomeIndexType i=0; i<chromosomes.size(); ++i) { double t_subStart = realtime(); ChromosomeIndexType nChrIdx = chromosomesRows[i].first; uint64_t ulDeltas = cmpmat[nChrIdx].getDeltasCount(NULL, NULL, 0, minDelta, maxDelta, masking); ulTotalDeltas += ulDeltas; t_diff = realtime() - t_subStart; fprintf(stderr, "[M::%s:%d] #deltas(%s)=%llu collected, %.2f min..\n", __func__, __LINE__, chromosomes[nChrIdx].c_str(), ulDeltas, t_diff/60.0); } t_diff = realtime() - t_start; fprintf(stderr, "[M::%s:%d] #deltas(genome)=%llu collected, %.2f min..\n", __func__, __LINE__, ulTotalDeltas, t_diff/60.0); // loop as table grid!!! { string ofile(filename); ofile.append(".resource.xls"); ofstream fileDump; fileDump.open(ofile.c_str()); unsigned long totalSegments = 0; unsigned long totalInteractions = 0; unsigned long totalDeltas = 0; fileDump << "#filename\t" << filename.c_str() << endl; fileDump << "#chr\tanchors\tinteractions\tdeltas" << endl; for(ChromosomeIndexType i=0; i<chromosomes.size(); ++i) { totalSegments += cmpmat[i].getSegmentCount(); totalInteractions += cmpmat[i].getInteractionCount(); totalDeltas += chromDeltaCounts[i]; fileDump << chromosomes[i]; fileDump << "\t" << cmpmat[i].getSegmentCount(); fileDump << "\t" << cmpmat[i].getInteractionCount(); fileDump << "\t" << chromDeltaCounts[i]; fileDump << endl; } fileDump << "GRAND TOTAL"; fileDump << "\t" << totalSegments; fileDump << "\t" << totalInteractions; fileDump << "\t" << totalDeltas; fileDump << endl; fileDump.close(); } } void getChromosomesDataSizeDesc(vector<string>& chromosomes, map<ChromosomeIndexType, CCCMatrixInteraction>& cmpmat, vector<pair<ChromosomeIndexType, uint64_t > >& chromosomesRows) { chromosomesRows.clear(); chromosomesRows.reserve(chromosomes.size()); for(ChromosomeIndexType i=0; i<chromosomes.size(); ++i) { chromosomesRows.push_back(make_pair(i, cmpmat[i].getSegmentCount())); } sort(chromosomesRows.begin(), chromosomesRows.end(), chromSegmentCountDesc); } void sweepQunatilesDeltaSpline(string& filename, vector<string>& chromosomes, vector<pair<ChromosomeIndexType, uint64_t > >&chromosomesRows, map<ChromosomeIndexType, CCCMatrixInteraction>& cmpmat, vector<uint32_t >& percentilesList, uint32_t minDelta/*=8000*/, uint32_t maxDelta/*=MAXDELTA*/, bool masking/*=false*/) { double t_diff; // Get all deltas for all chromosomes: vector<map<ChromosomeIndexType, DeltaStatistics > > chromDeltasStats; chromDeltasStats.resize(chromosomes.size()); std::sort(percentilesList.begin(), percentilesList.end(), std::greater<unsigned int>()); // deltas allocations uint32_t nMaxSpan = 0; { for(ChromosomeIndexType i=0; i<chromosomes.size(); ++i) { uint32_t maxChromSpan = cmpmat[i].getWidestInteractionSpan(); if (maxChromSpan>nMaxSpan) nMaxSpan = maxChromSpan; } nMaxSpan++; // 0-based index, so need 1 more allocation //cerr << "Largest span " << nMaxSpan << endl; } uint32_t* pDeltas = (uint32_t*) calloc(nMaxSpan+1, sizeof(uint32_t)); BIT_ARRAY *deltaPresences = barcreate(nMaxSpan+1); vector<vector<precomputeType > > cells; cells.resize(percentilesList.size()); //int dmax = (maxDelta == MAXDELTA) ? deltas.back() / 100 : maxDelta; uint32_t dmax = (maxDelta == MAXDELTA) ? nMaxSpan / 100 : maxDelta; vector<double> d = getSequence((double)minDelta, (double)dmax, 2000); for(unsigned int percentileIdx = 0; percentileIdx<percentilesList.size(); ++percentileIdx) { cells[percentileIdx].resize(d.size()); } double t_start = realtime(); uint64_t ulTotalDeltas = 0; for(ChromosomeIndexType i=0; i<chromosomes.size(); ++i) { double t_subStart = realtime(); ChromosomeIndexType nChrIdx = chromosomesRows[i].first; uint64_t ulDeltas = cmpmat[nChrIdx].getDeltasCount(pDeltas, deltaPresences, nMaxSpan+1, minDelta, maxDelta, masking); ulTotalDeltas += ulDeltas; t_diff = realtime() - t_subStart; fprintf(stderr, "[M::%s:%d] #deltas(%s)=%llu collected, %.2f min..\n", __func__, __LINE__, chromosomes[nChrIdx].c_str(), ulDeltas, t_diff/60.0); } t_diff = realtime() - t_start; fprintf(stderr, "[M::%s:%d] #deltas(genome)=%llu collected, %.2f min..\n", __func__, __LINE__, ulTotalDeltas, t_diff/60.0); for(unsigned int percentileIdx = 0; percentileIdx<percentilesList.size(); ++percentileIdx) { double t_subStart = realtime(); QuantileMapper qtm; spline s; qtm.computeDeltaCountQuantile(ulTotalDeltas, pDeltas, percentilesList[percentileIdx], NULL); t_diff = realtime() - t_subStart; fprintf(stderr, "[M::%s:%d] delta quantiles(%u) computation deltas took %.2f min..\n", __func__, __LINE__, percentilesList[percentileIdx], t_diff/60.0); t_subStart = realtime(); map<uint32_t, DeltaStatistics > deltasStats; { vector<uint32_t>& quantileDeltas = qtm.getQuantileDeltas(); for(vector<uint32_t>::iterator it=quantileDeltas.begin(); it!=quantileDeltas.end(); ++it) { uint32_t deltaQuantile = qtm.getDeltaQuantile(*it); deltasStats[deltaQuantile] = DeltaStatistics(); } } for(ChromosomeIndexType i=0; i<chromosomesRows.size(); i++) { double t_subStart = realtime(); int nChrIdx = chromosomesRows[i].first; #if 0 // // TODO: IMPORTANT : FIX AFTER CHECKING THE SINGLE SWEEP OPERATION ABOVE // cmpmat[nChrIdx].getStatisticsPerDelta(deltasStats, &qtm, minDelta, maxDelta, masking); #endif t_diff = realtime() - t_subStart; fprintf(stderr, "[M::%s:%d] delta quantiles statistics computation (%s), %.2f min..\n", __func__, __LINE__, chromosomes[nChrIdx].c_str(), t_diff/60.0); } t_diff = realtime() - t_subStart; fprintf(stderr, "[M::%s:%d] delta quantiles(%u) statistics computation deltas took %.2f min..\n", __func__, __LINE__, percentilesList[percentileIdx], t_diff/60.0); vector<double> delta_x; // x-object for spline generation vector<double> exp_y; // y-object for spline generation for(map<uint32_t, DeltaStatistics>::iterator iter = deltasStats.begin(); iter != deltasStats.end(); iter++) { delta_x.push_back((double)(iter->first)); exp_y.push_back((double)(iter->second.getMean())); //cout << iter->first << " " << iter->second << endl; } // If x is not sorted, an error will occur. s.set_points(delta_x,exp_y); // currently it is required that X is already sorted // keep results for(unsigned int i=0; i < d.size(); i++) { cells[percentileIdx][i] = s.at(d[i]) ; } } free(pDeltas); bardestroy(deltaPresences); // write result in a table grid if (percentilesList.size()>0) { string ofile(filename); ofile.append(".quantiles.sweep.xls"); ofstream fileDump; fileDump.open(ofile.c_str()); // print header fileDump << "delta"; for(unsigned int percentileIdx = 0; percentileIdx<percentilesList.size(); ++percentileIdx) { fileDump << "\tsmoothed-" << percentilesList[percentileIdx] ; } fileDump << endl; for(unsigned int i=0; i < d.size(); i++) { fileDump << d[i]; for(unsigned int percentileIdx = 0; percentileIdx<percentilesList.size(); ++percentileIdx) { fileDump << "\t" << cells[percentileIdx][i]; } fileDump << endl; } fileDump.close(); } } void computeInteractionsPvalues(vector<string>& chromosomes, vector<pair<ChromosomeIndexType, uint64_t > >&chromosomesRows, map<ChromosomeIndexType, CCCMatrixInteraction>& cmpmat, spline& s, uint32_t deltaCutoff, uint32_t minDelta/*=8000*/, uint32_t maxDelta/*=MAXDELTA*/) { // [exp{chromsome}, pval{chromosome}] is faster than [chromosome{exp, pval}] for(ChromosomeIndexType j=0; j<chromosomesRows.size(); j++) { int nChrIdx = chromosomesRows[j].first; string chr=chromosomes[nChrIdx]; double t_loopStart = realtime(); cmpmat[nChrIdx].setDeltaToExpectationMapper(s, minDelta, MAXDELTA); double t_diff = realtime() - t_loopStart; fprintf(stderr, "[M::%s:%d] createExpectationMatrix %s N:%u L:%g rtmin:%.2f\n", __func__, __LINE__, chr.c_str(), cmpmat[nChrIdx].getN(), cmpmat[nChrIdx].getExpectN(), t_diff/60.0); } for(ChromosomeIndexType j=0; j<chromosomesRows.size(); j++) { int nChrIdx = chromosomesRows[j].first; string chr=chromosomes[nChrIdx]; double t_loopStart = realtime(); cmpmat[nChrIdx].calculatePvalues(deltaCutoff, MAXDELTA);// During refinement, all P-values for all deltas are considered! double t_diff = realtime() - t_loopStart; fprintf(stderr, "[M::%s:%d] calculatePvalues %s rtmin:%.2f\n", __func__, __LINE__, chr.c_str(), t_diff/60.0); } } // Add the possible template classes explicitly, to allow linker to find them: // These are the only allowed: template vector<double> getSequence(double from, double to, uint32_t length); template vector<uint32_t> getSequence(uint32_t from, uint32_t to, uint32_t length); //template vector<float> getSequence(float from, float to, uint32_t length);
42.309706
407
0.691221
[ "object", "vector" ]
8e1cf88919a1bc09fed321a924645e68a550178e
3,213
cpp
C++
clang-tools-extra/clangd/DraftStore.cpp
nickbabcock/EECS381StyleCheck
271a15140229e5dbc1798328edfe6ca8c632a7be
[ "MIT" ]
171
2018-09-17T13:15:12.000Z
2022-03-18T03:47:04.000Z
clang-tools-extra/clangd/DraftStore.cpp
nickbabcock/EECS381StyleCheck
271a15140229e5dbc1798328edfe6ca8c632a7be
[ "MIT" ]
7
2018-10-05T04:54:18.000Z
2020-10-02T07:58:13.000Z
clang-tools-extra/clangd/DraftStore.cpp
nickbabcock/EECS381StyleCheck
271a15140229e5dbc1798328edfe6ca8c632a7be
[ "MIT" ]
35
2018-09-18T07:46:53.000Z
2022-03-27T07:59:48.000Z
//===--- DraftStore.cpp - File contents container ---------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "DraftStore.h" #include "SourceCode.h" #include "llvm/Support/Errc.h" using namespace clang; using namespace clang::clangd; llvm::Optional<std::string> DraftStore::getDraft(PathRef File) const { std::lock_guard<std::mutex> Lock(Mutex); auto It = Drafts.find(File); if (It == Drafts.end()) return llvm::None; return It->second; } std::vector<Path> DraftStore::getActiveFiles() const { std::lock_guard<std::mutex> Lock(Mutex); std::vector<Path> ResultVector; for (auto DraftIt = Drafts.begin(); DraftIt != Drafts.end(); DraftIt++) ResultVector.push_back(DraftIt->getKey()); return ResultVector; } void DraftStore::addDraft(PathRef File, StringRef Contents) { std::lock_guard<std::mutex> Lock(Mutex); Drafts[File] = Contents; } llvm::Expected<std::string> DraftStore::updateDraft( PathRef File, llvm::ArrayRef<TextDocumentContentChangeEvent> Changes) { std::lock_guard<std::mutex> Lock(Mutex); auto EntryIt = Drafts.find(File); if (EntryIt == Drafts.end()) { return llvm::make_error<llvm::StringError>( "Trying to do incremental update on non-added document: " + File, llvm::errc::invalid_argument); } std::string Contents = EntryIt->second; for (const TextDocumentContentChangeEvent &Change : Changes) { if (!Change.range) { Contents = Change.text; continue; } const Position &Start = Change.range->start; llvm::Expected<size_t> StartIndex = positionToOffset(Contents, Start, false); if (!StartIndex) return StartIndex.takeError(); const Position &End = Change.range->end; llvm::Expected<size_t> EndIndex = positionToOffset(Contents, End, false); if (!EndIndex) return EndIndex.takeError(); if (*EndIndex < *StartIndex) return llvm::make_error<llvm::StringError>( llvm::formatv( "Range's end position ({0}) is before start position ({1})", End, Start), llvm::errc::invalid_argument); if (Change.rangeLength && (ssize_t)(*EndIndex - *StartIndex) != *Change.rangeLength) return llvm::make_error<llvm::StringError>( llvm::formatv("Change's rangeLength ({0}) doesn't match the " "computed range length ({1}).", *Change.rangeLength, *EndIndex - *StartIndex), llvm::errc::invalid_argument); std::string NewContents; NewContents.reserve(*StartIndex + Change.text.length() + (Contents.length() - *EndIndex)); NewContents = Contents.substr(0, *StartIndex); NewContents += Change.text; NewContents += Contents.substr(*EndIndex); Contents = std::move(NewContents); } EntryIt->second = Contents; return Contents; } void DraftStore::removeDraft(PathRef File) { std::lock_guard<std::mutex> Lock(Mutex); Drafts.erase(File); }
29.75
80
0.631497
[ "vector" ]
8e21458032a5fad9d30e0217eef212a38c62527a
1,288
cpp
C++
leet_code_training/src/pb_011.cpp
Piggyknight/leetcode_training
2d7563fc6083ae1238f4b60e3339363db07346e2
[ "MIT" ]
null
null
null
leet_code_training/src/pb_011.cpp
Piggyknight/leetcode_training
2d7563fc6083ae1238f4b60e3339363db07346e2
[ "MIT" ]
null
null
null
leet_code_training/src/pb_011.cpp
Piggyknight/leetcode_training
2d7563fc6083ae1238f4b60e3339363db07346e2
[ "MIT" ]
null
null
null
/* 给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。 在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线, 使得它们与 x 轴共同构成的容器可以容纳最多的水。 说明:你不能倾斜容器,且 n 的值至少为 2。 输入: [1,8,6,2,5,4,8,3,7] 输出: 49 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/container-with-most-water 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ #include "pb_011.h" #include <assert.h> #include <iostream> #include <algorithm> void PB011::Test() { cout << "Start testing pb 011..."<<endl; vector<int> height{1,8,6,2,5,4,8,3,7}; int ret = maxArea(height); assert(49 == ret); cout << "finished test pb 011." << endl; return; } //Solution 1: //1. loop from start and end together //2. cal area = min(height[start],height[end]) * (start - end) //3. if height[start] > height[end], then we move the end one index back //4. vise visa if height[start] < height[end] // //the provement of this solution could be found on leetcode.com not the leetcode-cn.com // //time: 24ms //memory: 16MB //42.94% int PB011::maxArea(vector<int>& height) { int max_area = 0; for(size_t start = 0, end =height.size()-1; start < end; ) { int area = min(height[start], height[end]) * (end-start); max_area = max(area, max_area); if(height[start] > height[end]) { --end; } else { ++start; } } return max_area; }
19.223881
87
0.645963
[ "vector" ]
8e23ac46986cb4215fdcca245c3c56a683251a19
37,480
cpp
C++
orchagent/fdborch.cpp
anilkpandey/sonic-swss
47bcce99654296032bbfa1bc581d0470b1f85195
[ "Apache-2.0" ]
null
null
null
orchagent/fdborch.cpp
anilkpandey/sonic-swss
47bcce99654296032bbfa1bc581d0470b1f85195
[ "Apache-2.0" ]
null
null
null
orchagent/fdborch.cpp
anilkpandey/sonic-swss
47bcce99654296032bbfa1bc581d0470b1f85195
[ "Apache-2.0" ]
null
null
null
#include <assert.h> #include <iostream> #include <vector> #include <unordered_map> #include <utility> #include <inttypes.h> #include "logger.h" #include "tokenize.h" #include "fdborch.h" #include "crmorch.h" #include "notifier.h" #include "sai_serialize.h" extern sai_fdb_api_t *sai_fdb_api; extern sai_object_id_t gSwitchId; extern PortsOrch* gPortsOrch; extern CrmOrch * gCrmOrch; const int fdborch_pri = 20; FdbOrch::FdbOrch(TableConnector applDbConnector, TableConnector stateDbConnector, PortsOrch *port) : Orch(applDbConnector.first, applDbConnector.second, fdborch_pri), m_portsOrch(port), m_table(applDbConnector.first, applDbConnector.second), m_fdbStateTable(stateDbConnector.first, stateDbConnector.second) { m_portsOrch->attach(this); m_flushNotificationsConsumer = new NotificationConsumer(applDbConnector.first, "FLUSHFDBREQUEST"); auto flushNotifier = new Notifier(m_flushNotificationsConsumer, this, "FLUSHFDBREQUEST"); Orch::addExecutor(flushNotifier); /* Add FDB notifications support from ASIC */ DBConnector *notificationsDb = new DBConnector("ASIC_DB", 0); m_fdbNotificationConsumer = new swss::NotificationConsumer(notificationsDb, "NOTIFICATIONS"); auto fdbNotifier = new Notifier(m_fdbNotificationConsumer, this, "FDB_NOTIFICATIONS"); Orch::addExecutor(fdbNotifier); } bool FdbOrch::bake() { Orch::bake(); auto consumer = dynamic_cast<Consumer *>(getExecutor(APP_FDB_TABLE_NAME)); if (consumer == NULL) { SWSS_LOG_ERROR("No consumer %s in Orch", APP_FDB_TABLE_NAME); return false; } size_t refilled = consumer->refillToSync(&m_fdbStateTable); SWSS_LOG_NOTICE("Add warm input FDB State: %s, %zd", APP_FDB_TABLE_NAME, refilled); return true; } bool FdbOrch::storeFdbEntryState(const FdbUpdate& update) { const FdbEntry& entry = update.entry; const FdbData fdbdata = {update.port.m_bridge_port_id, update.type}; const Port& port = update.port; const MacAddress& mac = entry.mac; string portName = port.m_alias; Port vlan; if (!m_portsOrch->getPort(entry.bv_id, vlan)) { SWSS_LOG_NOTICE("FdbOrch notification: Failed to locate \ vlan port from bv_id 0x%" PRIx64, entry.bv_id); return false; } // ref: https://github.com/Azure/sonic-swss/blob/master/doc/swss-schema.md#fdb_table string key = "Vlan" + to_string(vlan.m_vlan_info.vlan_id) + ":" + mac.to_string(); if (update.add) { bool mac_move = false; auto it = m_entries.find(entry); if (it != m_entries.end()) { if (port.m_bridge_port_id == it->second.bridge_port_id) { SWSS_LOG_INFO("FdbOrch notification: mac %s is duplicate", entry.mac.to_string().c_str()); return false; } mac_move = true; } m_entries[entry] = fdbdata; SWSS_LOG_DEBUG("FdbOrch notification: mac %s was inserted into bv_id 0x%" PRIx64, entry.mac.to_string().c_str(), entry.bv_id); SWSS_LOG_DEBUG("m_entries size=%lu mac=%s port=0x%" PRIx64, m_entries.size(), entry.mac.to_string().c_str(), m_entries[entry].bridge_port_id); // Write to StateDb std::vector<FieldValueTuple> fvs; fvs.push_back(FieldValueTuple("port", portName)); fvs.push_back(FieldValueTuple("type", update.type)); m_fdbStateTable.set(key, fvs); if (!mac_move) { gCrmOrch->incCrmResUsedCounter(CrmResourceType::CRM_FDB_ENTRY); } return true; } else { size_t erased = m_entries.erase(entry); SWSS_LOG_DEBUG("FdbOrch notification: mac %s was removed from bv_id 0x%" PRIx64, entry.mac.to_string().c_str(), entry.bv_id); if (erased == 0) { return false; } // Remove in StateDb m_fdbStateTable.del(key); gCrmOrch->decCrmResUsedCounter(CrmResourceType::CRM_FDB_ENTRY); return true; } } void FdbOrch::update(sai_fdb_event_t type, const sai_fdb_entry_t* entry, sai_object_id_t bridge_port_id) { SWSS_LOG_ENTER(); FdbUpdate update; update.entry.mac = entry->mac_address; update.entry.bv_id = entry->bv_id; update.type = "dynamic"; Port vlan; SWSS_LOG_INFO("FDB event:%d, MAC: %s , BVID: 0x%" PRIx64 " , \ bridge port ID: 0x%" PRIx64 ".", type, update.entry.mac.to_string().c_str(), entry->bv_id, bridge_port_id); if (bridge_port_id && !m_portsOrch->getPortByBridgePortId(bridge_port_id, update.port)) { SWSS_LOG_ERROR("Failed to get port by bridge port ID 0x%" PRIx64 ".", bridge_port_id); return; } switch (type) { case SAI_FDB_EVENT_LEARNED: { SWSS_LOG_INFO("Received LEARN event for bvid=0x%" PRIx64 "mac=%s port=0x%" PRIx64, entry->bv_id, update.entry.mac.to_string().c_str(), bridge_port_id); if (!m_portsOrch->getPort(entry->bv_id, vlan)) { SWSS_LOG_ERROR("FdbOrch LEARN notification: Failed to locate vlan port from bv_id 0x%" PRIx64, entry->bv_id); return; } if (!m_portsOrch->getPortByBridgePortId(bridge_port_id, update.port)) { SWSS_LOG_ERROR("FdbOrch LEARN notification: Failed to get port by bridge port ID 0x%" PRIx64, bridge_port_id); return; } // we already have such entries auto existing_entry = m_entries.find(update.entry); if (existing_entry != m_entries.end()) { SWSS_LOG_INFO("FdbOrch LEARN notification: mac %s is already in bv_id 0x%" PRIx64 "existing-bp 0x%" PRIx64 "new-bp:0x%" PRIx64, update.entry.mac.to_string().c_str(), entry->bv_id, existing_entry->second.bridge_port_id, bridge_port_id); break; } update.add = true; update.type = "dynamic"; update.entry.port_name = update.port.m_alias; storeFdbEntryState(update); update.port.m_fdb_count++; m_portsOrch->setPort(update.port.m_alias, update.port); vlan.m_fdb_count++; m_portsOrch->setPort(vlan.m_alias, vlan); SWSS_LOG_INFO("Notifying observers of FDB entry LEARN"); for (auto observer: m_observers) { observer->update(SUBJECT_TYPE_FDB_CHANGE, &update); } break; } case SAI_FDB_EVENT_AGED: { SWSS_LOG_INFO("Received AGE event for bvid=%lx mac=%s port=%lx", entry->bv_id, update.entry.mac.to_string().c_str(), bridge_port_id); if (!m_portsOrch->getPort(entry->bv_id, vlan)) { SWSS_LOG_NOTICE("FdbOrch AGE notification: Failed to locate vlan port from bv_id 0x%lx", entry->bv_id); } auto existing_entry = m_entries.find(update.entry); // we don't have such entries if (existing_entry == m_entries.end()) { SWSS_LOG_INFO("FdbOrch AGE notification: mac %s is not present in bv_id 0x%lx bp 0x%lx", update.entry.mac.to_string().c_str(), entry->bv_id, bridge_port_id); break; } if (!m_portsOrch->getPortByBridgePortId(bridge_port_id, update.port)) { SWSS_LOG_NOTICE("FdbOrch AGE notification: Failed to get port by bridge port ID 0x%lx", bridge_port_id); } if (existing_entry->second.bridge_port_id != bridge_port_id) { SWSS_LOG_NOTICE("FdbOrch AGE notification: Stale aging event received for mac-bv_id %s-0x%lx with bp=0x%lx existing bp=0x%lx", update.entry.mac.to_string().c_str(), entry->bv_id, bridge_port_id, existing_entry->second.bridge_port_id); // We need to get the port for bridge-port in existing fdb if (!m_portsOrch->getPortByBridgePortId(existing_entry->second.bridge_port_id, update.port)) { SWSS_LOG_NOTICE("FdbOrch AGE notification: Failed to get port by bridge port ID 0x%lx", existing_entry->second.bridge_port_id); } // dont return, let it delete just to bring SONiC and SAI in sync // return; } if (existing_entry->second.type == "static") { if (vlan.m_members.find(update.port.m_alias) == vlan.m_members.end()) { update.type = "static"; saved_fdb_entries[update.port.m_alias].push_back({existing_entry->first.mac, vlan.m_vlan_info.vlan_id, "static"}); } else { /*port added back to vlan before we receive delete notification for flush from SAI. Re-add entry to SAI */ sai_attribute_t attr; vector<sai_attribute_t> attrs; attr.id = SAI_FDB_ENTRY_ATTR_TYPE; attr.value.s32 = SAI_FDB_ENTRY_TYPE_STATIC; attrs.push_back(attr); attr.id = SAI_FDB_ENTRY_ATTR_BRIDGE_PORT_ID; attr.value.oid = bridge_port_id; attrs.push_back(attr); auto status = sai_fdb_api->create_fdb_entry(entry, (uint32_t)attrs.size(), attrs.data()); if (status != SAI_STATUS_SUCCESS) { SWSS_LOG_ERROR("Failed to create FDB %s on %s, rv:%d", existing_entry->first.mac.to_string().c_str(), update.port.m_alias.c_str(), status); return; } return; } } update.add = false; storeFdbEntryState(update); if (!update.port.m_alias.empty()) { update.port.m_fdb_count--; m_portsOrch->setPort(update.port.m_alias, update.port); } if (!vlan.m_alias.empty()) { vlan.m_fdb_count--; m_portsOrch->setPort(vlan.m_alias, vlan); } SWSS_LOG_INFO("Notifying observers of FDB entry removal on AGED/MOVED"); for (auto observer: m_observers) { observer->update(SUBJECT_TYPE_FDB_CHANGE, &update); } break; } case SAI_FDB_EVENT_MOVE: { Port port_old; auto existing_entry = m_entries.find(update.entry); SWSS_LOG_INFO("Received MOVE event for bvid=%lx mac=%s port=%lx", entry->bv_id, update.entry.mac.to_string().c_str(), bridge_port_id); update.add = true; if (!m_portsOrch->getPort(entry->bv_id, vlan)) { SWSS_LOG_ERROR("FdbOrch MOVE notification: Failed to locate vlan port from bv_id 0x%lx", entry->bv_id); return; } if (!m_portsOrch->getPortByBridgePortId(bridge_port_id, update.port)) { SWSS_LOG_ERROR("FdbOrch MOVE notification: Failed to get port by bridge port ID 0x%lx", bridge_port_id); return; } // We should already have such entry if (existing_entry == m_entries.end()) { SWSS_LOG_WARN("FdbOrch MOVE notification: mac %s is not found in bv_id 0x%lx", update.entry.mac.to_string().c_str(), entry->bv_id); } else if (!m_portsOrch->getPortByBridgePortId(existing_entry->second.bridge_port_id, port_old)) { SWSS_LOG_ERROR("FdbOrch MOVE notification: Failed to get port by bridge port ID 0x%lx", existing_entry->second.bridge_port_id); return; } if (!port_old.m_alias.empty()) { port_old.m_fdb_count--; m_portsOrch->setPort(port_old.m_alias, port_old); } update.port.m_fdb_count++; m_portsOrch->setPort(update.port.m_alias, update.port); storeFdbEntryState(update); for (auto observer: m_observers) { observer->update(SUBJECT_TYPE_FDB_CHANGE, &update); } break; } case SAI_FDB_EVENT_FLUSHED: SWSS_LOG_INFO("Received FLUSH event for bvid=%lx mac=%s port=%lx", entry->bv_id, update.entry.mac.to_string().c_str(), bridge_port_id); for (auto itr = m_entries.begin(); itr != m_entries.end();) { if (itr->second.type == "static") { itr++; continue; } if (((bridge_port_id == SAI_NULL_OBJECT_ID) && (entry->bv_id == SAI_NULL_OBJECT_ID)) // Flush all DYNAMIC || ((bridge_port_id == itr->second.bridge_port_id) && (entry->bv_id == SAI_NULL_OBJECT_ID)) // flush all DYN on a port || ((bridge_port_id == SAI_NULL_OBJECT_ID) && (entry->bv_id == itr->first.bv_id))) // flush all DYN on a vlan { if (!m_portsOrch->getPortByBridgePortId(itr->second.bridge_port_id, update.port)) { SWSS_LOG_ERROR("FdbOrch FLUSH notification: Failed to get port by bridge port ID 0x%lx", itr->second.bridge_port_id); itr++; continue; } if (!m_portsOrch->getPort(itr->first.bv_id, vlan)) { SWSS_LOG_NOTICE("FdbOrch FLUSH notification: Failed to locate vlan port from bv_id 0x%lx", itr->first.bv_id); itr++; continue; } update.entry.mac = itr->first.mac; update.entry.bv_id = itr->first.bv_id; update.add = false; update.vlan_id = vlan.m_vlan_info.vlan_id; itr++; update.port.m_fdb_count--; m_portsOrch->setPort(update.port.m_alias, update.port); vlan.m_fdb_count--; m_portsOrch->setPort(vlan.m_alias, vlan); /* This will invalidate the current iterator hence itr++ is done before */ storeFdbEntryState(update); SWSS_LOG_DEBUG("FdbOrch FLUSH notification: mac %s was removed", update.entry.mac.to_string().c_str()); notify(SUBJECT_TYPE_FDB_CHANGE, &update); } else { itr++; } } break; } return; } void FdbOrch::update(SubjectType type, void *cntx) { SWSS_LOG_ENTER(); assert(cntx); switch(type) { case SUBJECT_TYPE_VLAN_MEMBER_CHANGE: { VlanMemberUpdate *update = reinterpret_cast<VlanMemberUpdate *>(cntx); updateVlanMember(*update); break; } case SUBJECT_TYPE_PORT_OPER_STATE_CHANGE: { PortOperStateUpdate *update = reinterpret_cast<PortOperStateUpdate *>(cntx); updatePortOperState(*update); break; } default: break; } return; } bool FdbOrch::getPort(const MacAddress& mac, uint16_t vlan, Port& port) { SWSS_LOG_ENTER(); if (!m_portsOrch->getVlanByVlanId(vlan, port)) { SWSS_LOG_ERROR("Failed to get vlan by vlan ID %d", vlan); return false; } sai_fdb_entry_t entry; entry.switch_id = gSwitchId; memcpy(entry.mac_address, mac.getMac(), sizeof(sai_mac_t)); entry.bv_id = port.m_vlan_info.vlan_oid; sai_attribute_t attr; attr.id = SAI_FDB_ENTRY_ATTR_BRIDGE_PORT_ID; sai_status_t status = sai_fdb_api->get_fdb_entry_attribute(&entry, 1, &attr); if (status != SAI_STATUS_SUCCESS) { SWSS_LOG_ERROR("Failed to get bridge port ID for FDB entry %s, rv:%d", mac.to_string().c_str(), status); return false; } if (!m_portsOrch->getPortByBridgePortId(attr.value.oid, port)) { SWSS_LOG_ERROR("Failed to get port by bridge port ID 0x%" PRIx64, attr.value.oid); return false; } return true; } void FdbOrch::doTask(Consumer& consumer) { SWSS_LOG_ENTER(); if (!gPortsOrch->allPortsReady()) { return; } auto it = consumer.m_toSync.begin(); while (it != consumer.m_toSync.end()) { KeyOpFieldsValuesTuple t = it->second; /* format: <VLAN_name>:<MAC_address> */ vector<string> keys = tokenize(kfvKey(t), ':', 1); string op = kfvOp(t); Port vlan; if (!m_portsOrch->getPort(keys[0], vlan)) { SWSS_LOG_INFO("Failed to locate %s", keys[0].c_str()); if(op == DEL_COMMAND) { /* Delete if it is in saved_fdb_entry */ unsigned short vlan_id; try { vlan_id = (unsigned short) stoi(keys[0].substr(4)); } catch(exception &e) { it = consumer.m_toSync.erase(it); continue; } deleteFdbEntryFromSavedFDB(MacAddress(keys[1]), vlan_id, ""); it = consumer.m_toSync.erase(it); } else { it++; } continue; } FdbEntry entry; entry.mac = MacAddress(keys[1]); entry.bv_id = vlan.m_vlan_info.vlan_oid; if (op == SET_COMMAND) { string port; string type; for (auto i : kfvFieldsValues(t)) { if (fvField(i) == "port") { port = fvValue(i); } if (fvField(i) == "type") { type = fvValue(i); } } entry.port_name = port; /* FDB type is either dynamic or static */ assert(type == "dynamic" || type == "static"); if (addFdbEntry(entry, port, type)) it = consumer.m_toSync.erase(it); else it++; /* Remove corresponding APP_DB entry if type is 'dynamic' */ // FIXME: The modification of table is not thread safe. // Uncomment this after this issue is fixed. // if (type == "dynamic") // { // m_table.del(kfvKey(t)); // } } else if (op == DEL_COMMAND) { if (removeFdbEntry(entry)) it = consumer.m_toSync.erase(it); else it++; } else { SWSS_LOG_ERROR("Unknown operation type %s", op.c_str()); it = consumer.m_toSync.erase(it); } } } void FdbOrch::doTask(NotificationConsumer& consumer) { SWSS_LOG_ENTER(); if (!gPortsOrch->allPortsReady()) { return; } std::string op; std::string data; std::vector<swss::FieldValueTuple> values; consumer.pop(op, data, values); if (&consumer == m_flushNotificationsConsumer) { if (op == "ALL") { flushFdbAll(0); return; } else if (op == "PORT") { flushFdbByPort(data, 0); return; } else if (op == "VLAN") { flushFdbByVlan(data, 0); return; } else { SWSS_LOG_ERROR("Received unknown flush fdb request"); return; } } else if (&consumer == m_fdbNotificationConsumer && op == "fdb_event") { uint32_t count; sai_fdb_event_notification_data_t *fdbevent = nullptr; sai_deserialize_fdb_event_ntf(data, count, &fdbevent); for (uint32_t i = 0; i < count; ++i) { sai_object_id_t oid = SAI_NULL_OBJECT_ID; for (uint32_t j = 0; j < fdbevent[i].attr_count; ++j) { if (fdbevent[i].attr[j].id == SAI_FDB_ENTRY_ATTR_BRIDGE_PORT_ID) { oid = fdbevent[i].attr[j].value.oid; break; } } this->update(fdbevent[i].event_type, &fdbevent[i].fdb_entry, oid); } sai_deserialize_free_fdb_event_ntf(count, fdbevent); } } /* * Name: flushFDBEntries * Params: * bridge_port_oid - SAI object ID of bridge port associated with the port * vlan_oid - SAI object ID of the VLAN * Description: * Flushes FDB entries based on bridge_port_oid, or vlan_oid or both. * This function is called in three cases. * 1. Port is reoved from VLAN (via SUBJECT_TYPE_VLAN_MEMBER_CHANGE) * 2. Bridge port OID is removed (Direct call) * 3. Port is shut down (via SUBJECT_TYPE_ */ void FdbOrch::flushFDBEntries(sai_object_id_t bridge_port_oid, sai_object_id_t vlan_oid) { vector<sai_attribute_t> attrs; sai_attribute_t attr; sai_status_t rv = SAI_STATUS_SUCCESS; SWSS_LOG_ENTER(); if (SAI_NULL_OBJECT_ID == bridge_port_oid && SAI_NULL_OBJECT_ID == vlan_oid) { SWSS_LOG_WARN("Couldn't flush FDB. Bridge port OID: 0x%" PRIx64 " bvid:%" PRIx64 ",", bridge_port_oid, vlan_oid); return; } if (SAI_NULL_OBJECT_ID != bridge_port_oid) { attr.id = SAI_FDB_FLUSH_ATTR_BRIDGE_PORT_ID; attr.value.oid = bridge_port_oid; attrs.push_back(attr); } if (SAI_NULL_OBJECT_ID != vlan_oid) { attr.id = SAI_FDB_FLUSH_ATTR_BV_ID; attr.value.oid = vlan_oid; attrs.push_back(attr); } SWSS_LOG_INFO("Flushing FDB bridge_port_oid: 0x%" PRIx64 ", and bvid_oid:0x%" PRIx64 ".", bridge_port_oid, vlan_oid); rv = sai_fdb_api->flush_fdb_entries(gSwitchId, (uint32_t)attrs.size(), attrs.data()); if (SAI_STATUS_SUCCESS != rv) { SWSS_LOG_ERROR("Flushing FDB failed. rv:%d", rv); } } void FdbOrch::notifyObserversFDBFlush(Port &port, sai_object_id_t& bvid) { FdbFlushUpdate flushUpdate; flushUpdate.port = port; for (auto itr = m_entries.begin(); itr != m_entries.end(); ++itr) { if ((itr->second.bridge_port_id == port.m_bridge_port_id) && (itr->first.bv_id == bvid)) { SWSS_LOG_INFO("Adding MAC learnt on [ port:%s , bvid:0x%" PRIx64 "]\ to ARP flush", port.m_alias.c_str(), bvid); FdbEntry entry; entry.mac = itr->first.mac; entry.bv_id = itr->first.bv_id; flushUpdate.entries.push_back(entry); } } if (!flushUpdate.entries.empty()) { for (auto observer: m_observers) { observer->update(SUBJECT_TYPE_FDB_FLUSH_CHANGE, &flushUpdate); } } } void FdbOrch::updatePortOperState(const PortOperStateUpdate& update) { SWSS_LOG_ENTER(); if (update.operStatus == SAI_PORT_OPER_STATUS_DOWN) { swss::Port p = update.port; flushFDBEntries(p.m_bridge_port_id, SAI_NULL_OBJECT_ID); // Get BVID of each VLAN that this port is a member of // and call notifyObserversFDBFlush for (const auto& vlan_member: p.m_vlan_members) { swss::Port vlan; string vlan_alias = VLAN_PREFIX + to_string(vlan_member.first); if (!m_portsOrch->getPort(vlan_alias, vlan)) { SWSS_LOG_INFO("Failed to locate VLAN %s", vlan_alias.c_str()); continue; } notifyObserversFDBFlush(p, vlan.m_vlan_info.vlan_oid); } } return; } void FdbOrch::updateVlanMember(const VlanMemberUpdate& update) { SWSS_LOG_ENTER(); if (!update.add) { swss::Port vlan = update.vlan; swss::Port port = update.member; flushFdbByPortVlan(port.m_alias, vlan.m_alias, 1); notifyObserversFDBFlush(port, vlan.m_vlan_info.vlan_oid); return; } string port_name = update.member.m_alias; auto fdb_list = std::move(saved_fdb_entries[port_name]); saved_fdb_entries[port_name].clear(); for (const auto& fdb: fdb_list) { if(fdb.vlanId == update.vlan.m_vlan_info.vlan_id) { FdbEntry entry; entry.mac = fdb.mac; entry.bv_id = update.vlan.m_vlan_info.vlan_oid; (void)addFdbEntry(entry, port_name, fdb.type); } else { saved_fdb_entries[port_name].push_back(fdb); } } } bool FdbOrch::addFdbEntry(const FdbEntry& entry, const string& port_name, const string& type) { Port vlan; Port port; SWSS_LOG_ENTER(); SWSS_LOG_INFO("mac=%s bv_id=0x%lx port_name %s type %s", entry.mac.to_string().c_str(), entry.bv_id, port_name.c_str(), type.c_str()); if (!m_portsOrch->getPort(entry.bv_id, vlan)) { SWSS_LOG_NOTICE("addFdbEntry: Failed to locate vlan port from bv_id 0x%lx", entry.bv_id); return false; } /* Retry until port is created */ if (!m_portsOrch->getPort(port_name, port) || (port.m_bridge_port_id == SAI_NULL_OBJECT_ID)) { SWSS_LOG_INFO("Saving a fdb entry until port %s becomes active", port_name.c_str()); saved_fdb_entries[port_name].push_back({entry.mac, vlan.m_vlan_info.vlan_id, type}); return true; } /* Retry until port is member of vlan*/ if (vlan.m_members.find(port_name) == vlan.m_members.end()) { SWSS_LOG_INFO("Saving a fdb entry until port %s becomes vlan %s member", port_name.c_str(), vlan.m_alias.c_str()); saved_fdb_entries[port_name].push_back({entry.mac, vlan.m_vlan_info.vlan_id, type}); return true; } sai_status_t status; sai_fdb_entry_t fdb_entry; fdb_entry.switch_id = gSwitchId; memcpy(fdb_entry.mac_address, entry.mac.getMac(), sizeof(sai_mac_t)); fdb_entry.bv_id = entry.bv_id; Port oldPort; string oldType; bool macUpdate = false; auto it = m_entries.find(entry); if(it != m_entries.end()) { if(port.m_bridge_port_id == it->second.bridge_port_id) { if((it->second.type == type)) { SWSS_LOG_INFO("FdbOrch: mac=%s %s port=%s type=%s is duplicate", entry.mac.to_string().c_str(), vlan.m_alias.c_str(), port_name.c_str(), type.c_str()); return true; } } /* get existing port and type */ oldType = it->second.type; if (!m_portsOrch->getPortByBridgePortId(it->second.bridge_port_id, oldPort)) { SWSS_LOG_ERROR("Existing port 0x%lx details not found", it->second.bridge_port_id); return false; } macUpdate = true; } sai_attribute_t attr; vector<sai_attribute_t> attrs; attr.id = SAI_FDB_ENTRY_ATTR_TYPE; attr.value.s32 = (type == "dynamic") ? SAI_FDB_ENTRY_TYPE_DYNAMIC : SAI_FDB_ENTRY_TYPE_STATIC; attrs.push_back(attr); attr.id = SAI_FDB_ENTRY_ATTR_BRIDGE_PORT_ID; attr.value.oid = port.m_bridge_port_id; attrs.push_back(attr); attr.id = SAI_FDB_ENTRY_ATTR_PACKET_ACTION; attr.value.s32 = SAI_PACKET_ACTION_FORWARD; attrs.push_back(attr); string key = "Vlan" + to_string(vlan.m_vlan_info.vlan_id) + ":" + entry.mac.to_string(); if(macUpdate) { /* delete and re-add fdb entry instead of update, * as entry may age out in HW/ASIC_DB before * update, causing the update request to fail. */ SWSS_LOG_INFO("MAC-Update FDB %s in %s on from-%s:to-%s from-%s:to-%s", entry.mac.to_string().c_str(), vlan.m_alias.c_str(), oldPort.m_alias.c_str(), port_name.c_str(), oldType.c_str(), type.c_str()); status = sai_fdb_api->remove_fdb_entry(&fdb_entry); if (status != SAI_STATUS_SUCCESS) { SWSS_LOG_WARN("FdbOrch RemoveFDBEntry: Failed to remove FDB entry. mac=%s, bv_id=0x%lx", entry.mac.to_string().c_str(), entry.bv_id); } else { oldPort.m_fdb_count--; m_portsOrch->setPort(oldPort.m_alias, oldPort); if (oldPort.m_bridge_port_id == port.m_bridge_port_id) { port.m_fdb_count--; m_portsOrch->setPort(port.m_alias, port); } vlan.m_fdb_count--; m_portsOrch->setPort(vlan.m_alias, vlan); (void)m_entries.erase(entry); // Remove in StateDb m_fdbStateTable.del(key); gCrmOrch->decCrmResUsedCounter(CrmResourceType::CRM_FDB_ENTRY); FdbUpdate update = {entry, port, vlan.m_vlan_info.vlan_id, type, true}; for (auto observer: m_observers) { observer->update(SUBJECT_TYPE_FDB_CHANGE, &update); } } } SWSS_LOG_INFO("MAC-Create %s FDB %s in %s on %s", type.c_str(), entry.mac.to_string().c_str(), vlan.m_alias.c_str(), port_name.c_str()); status = sai_fdb_api->create_fdb_entry(&fdb_entry, (uint32_t)attrs.size(), attrs.data()); if (status != SAI_STATUS_SUCCESS) { SWSS_LOG_ERROR("Failed to create %s FDB %s on %s, rv:%d", type.c_str(), entry.mac.to_string().c_str(), entry.port_name.c_str(), status); return false; //FIXME: it should be based on status. Some could be retried, some not } port.m_fdb_count++; m_portsOrch->setPort(port.m_alias, port); vlan.m_fdb_count++; m_portsOrch->setPort(vlan.m_alias, vlan); const FdbData fdbdata = {port.m_bridge_port_id, type}; m_entries[entry] = fdbdata; // Write to StateDb std::vector<FieldValueTuple> fvs; fvs.push_back(FieldValueTuple("port", port_name)); fvs.push_back(FieldValueTuple("type", type)); m_fdbStateTable.set(key, fvs); if(!macUpdate) { gCrmOrch->incCrmResUsedCounter(CrmResourceType::CRM_FDB_ENTRY); } FdbUpdate update = {entry, port, vlan.m_vlan_info.vlan_id, type, true}; for (auto observer: m_observers) { observer->update(SUBJECT_TYPE_FDB_CHANGE, &update); } return true; } bool FdbOrch::removeFdbEntry(const FdbEntry& entry) { Port vlan; Port port; SWSS_LOG_ENTER(); if (!m_portsOrch->getPort(entry.bv_id, vlan)) { SWSS_LOG_NOTICE("FdbOrch notification: Failed to locate vlan port from bv_id 0x%lx", entry.bv_id); return false; } auto it= m_entries.find(entry); if(it == m_entries.end()) { SWSS_LOG_INFO("FdbOrch RemoveFDBEntry: FDB entry isn't found. mac=%s bv_id=0x%lx", entry.mac.to_string().c_str(), entry.bv_id); /* check whether the entry is in the saved fdb, if so delete it from there. */ deleteFdbEntryFromSavedFDB(entry.mac, vlan.m_vlan_info.vlan_id, ""); return true; } FdbData fdbData = it->second; if (!m_portsOrch->getPortByBridgePortId(fdbData.bridge_port_id, port)) { SWSS_LOG_NOTICE("FdbOrch RemoveFDBEntry: Failed to locate port from bridge_port_id 0x%lx", fdbData.bridge_port_id); return false; } string key = "Vlan" + to_string(vlan.m_vlan_info.vlan_id) + ":" + entry.mac.to_string(); sai_status_t status; sai_fdb_entry_t fdb_entry; fdb_entry.switch_id = gSwitchId; memcpy(fdb_entry.mac_address, entry.mac.getMac(), sizeof(sai_mac_t)); fdb_entry.bv_id = entry.bv_id; status = sai_fdb_api->remove_fdb_entry(&fdb_entry); if (status != SAI_STATUS_SUCCESS) { SWSS_LOG_ERROR("FdbOrch RemoveFDBEntry: Failed to remove FDB entry. mac=%s, bv_id=0x%lx", entry.mac.to_string().c_str(), entry.bv_id); return true; //FIXME: it should be based on status. Some could be retried. some not } port.m_fdb_count--; m_portsOrch->setPort(port.m_alias, port); vlan.m_fdb_count--; m_portsOrch->setPort(vlan.m_alias, vlan); (void)m_entries.erase(entry); // Remove in StateDb m_fdbStateTable.del(key); gCrmOrch->decCrmResUsedCounter(CrmResourceType::CRM_FDB_ENTRY); FdbUpdate update = {entry, port, vlan.m_vlan_info.vlan_id, fdbData.type, false}; for (auto observer: m_observers) { observer->update(SUBJECT_TYPE_FDB_CHANGE, &update); } return true; } bool FdbOrch::flushFdbAll(bool flush_static) { sai_status_t status; sai_attribute_t port_attr; if (!flush_static) { port_attr.id = SAI_FDB_FLUSH_ATTR_ENTRY_TYPE; port_attr.value.s32 = SAI_FDB_FLUSH_ENTRY_TYPE_DYNAMIC; status = sai_fdb_api->flush_fdb_entries(gSwitchId, 1, &port_attr); } else { status = sai_fdb_api->flush_fdb_entries(gSwitchId, 0, NULL); } if (status != SAI_STATUS_SUCCESS) { SWSS_LOG_ERROR("Flush fdb failed, return code %x", status); return false; } return true; } bool FdbOrch::flushFdbByPort(const string &alias, bool flush_static) { sai_status_t status; Port port; sai_attribute_t port_attr[2]; if (!m_portsOrch->getPort(alias, port)) { SWSS_LOG_ERROR("could not locate port from alias %s", alias.c_str()); return false; } if ((port.m_bridge_port_id == SAI_NULL_OBJECT_ID) || !port.m_fdb_count) { /* port is not an L2 port or no macs to flush */ return true; } SWSS_LOG_NOTICE("m_bridge_port_id 0x%lx flush_static %d m_fdb_count %u", port.m_bridge_port_id, flush_static, port.m_fdb_count); port_attr[0].id = SAI_FDB_FLUSH_ATTR_BRIDGE_PORT_ID; port_attr[0].value.oid = port.m_bridge_port_id; if (!flush_static) { port_attr[1].id = SAI_FDB_FLUSH_ATTR_ENTRY_TYPE; port_attr[1].value.s32 = SAI_FDB_FLUSH_ENTRY_TYPE_DYNAMIC; status = sai_fdb_api->flush_fdb_entries(gSwitchId, 2, port_attr); } else { status = sai_fdb_api->flush_fdb_entries(gSwitchId, 1, port_attr); } if (status != SAI_STATUS_SUCCESS) { SWSS_LOG_ERROR("Flush fdb failed, return code %x", status); return false; } return true; } bool FdbOrch::flushFdbByVlan(const string &alias, bool flush_static) { sai_status_t status; Port vlan; sai_attribute_t vlan_attr[2]; if (!m_portsOrch->getPort(alias, vlan)) { SWSS_LOG_ERROR("could not locate vlan from alias %s", alias.c_str()); return false; } SWSS_LOG_NOTICE("vlan_oid 0x%lx flush_static %d", vlan.m_vlan_info.vlan_oid, flush_static); vlan_attr[0].id = SAI_FDB_FLUSH_ATTR_BV_ID; vlan_attr[0].value.oid = vlan.m_vlan_info.vlan_oid; if (!flush_static) { vlan_attr[1].id = SAI_FDB_FLUSH_ATTR_ENTRY_TYPE; vlan_attr[1].value.s32 = SAI_FDB_FLUSH_ENTRY_TYPE_DYNAMIC; status = sai_fdb_api->flush_fdb_entries(gSwitchId, 2, vlan_attr); } else { status = sai_fdb_api->flush_fdb_entries(gSwitchId, 1, vlan_attr); } if (status != SAI_STATUS_SUCCESS) { SWSS_LOG_ERROR("Flush fdb failed, return code %x", status); return false; } return true; } bool FdbOrch::flushFdbByPortVlan(const string &port_alias, const string &vlan_alias, bool flush_static) { sai_status_t status; Port vlan; Port port; sai_attribute_t port_vlan_attr[3]; SWSS_LOG_NOTICE("port %s vlan %s", port_alias.c_str(), vlan_alias.c_str()); if (!m_portsOrch->getPort(port_alias, port)) { SWSS_LOG_ERROR("could not locate port from alias %s", port_alias.c_str()); return false; } if (!m_portsOrch->getPort(vlan_alias, vlan)) { SWSS_LOG_NOTICE("FdbOrch notification: Failed to locate vlan %s", vlan_alias.c_str()); return false; } if ((port.m_bridge_port_id == SAI_NULL_OBJECT_ID) || !port.m_fdb_count) { /* port is not an L2 port or no macs to flush */ return true; } SWSS_LOG_NOTICE("vlan_oid 0x%lx m_bridge_port_id 0x%lx flush_static %d m_fdb_count %u", vlan.m_vlan_info.vlan_oid, port.m_bridge_port_id, flush_static, port.m_fdb_count); port_vlan_attr[0].id = SAI_FDB_FLUSH_ATTR_BV_ID; port_vlan_attr[0].value.oid = vlan.m_vlan_info.vlan_oid; port_vlan_attr[1].id = SAI_FDB_FLUSH_ATTR_BRIDGE_PORT_ID; port_vlan_attr[1].value.oid = port.m_bridge_port_id; if (!flush_static) { port_vlan_attr[2].id = SAI_FDB_FLUSH_ATTR_ENTRY_TYPE; port_vlan_attr[2].value.s32 = SAI_FDB_FLUSH_ENTRY_TYPE_DYNAMIC; status = sai_fdb_api->flush_fdb_entries(gSwitchId, 3, port_vlan_attr); } else { status = sai_fdb_api->flush_fdb_entries(gSwitchId, 2, port_vlan_attr); } if (status != SAI_STATUS_SUCCESS) { SWSS_LOG_ERROR("Flush fdb failed, return code %x", status); return false; } return true; } void FdbOrch::deleteFdbEntryFromSavedFDB(const MacAddress &mac, const unsigned short &vlanId, const string portName) { bool found=false; SavedFdbEntry entry = {mac, vlanId, "static"}; for (auto& itr: saved_fdb_entries) { if(portName.empty() || (portName == itr.first)) { auto iter = saved_fdb_entries[itr.first].begin(); while(iter != saved_fdb_entries[itr.first].end()) { if (*iter == entry) { SWSS_LOG_INFO("FDB entry found in saved fdb. deleting... mac=%s vlan_id=0x%x", mac.to_string().c_str(), vlanId); saved_fdb_entries[itr.first].erase(iter); found=true; break; } iter++; } } if(found) break; } }
32.648084
246
0.59928
[ "object", "vector" ]
8e32461edf4fbbb38461da3b88c9d98eac98c3b5
3,019
cpp
C++
Flight Simulator/Flight Simulator/Skybox.cpp
mihaitudor17/Flight-Simulator
05cd6368f2c75eefac51731a4d81bf71664f6bb5
[ "MIT" ]
null
null
null
Flight Simulator/Flight Simulator/Skybox.cpp
mihaitudor17/Flight-Simulator
05cd6368f2c75eefac51731a4d81bf71664f6bb5
[ "MIT" ]
null
null
null
Flight Simulator/Flight Simulator/Skybox.cpp
mihaitudor17/Flight-Simulator
05cd6368f2c75eefac51731a4d81bf71664f6bb5
[ "MIT" ]
null
null
null
#include "Skybox.h" #include "Shader.h" #include "Camera.h" #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> #include <glfw3.h> static Shader* skyboxShader = nullptr; static float skyboxVertices[] = { -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f }; static unsigned int skyboxIndices[] = { 1, 2, 6, 6, 5, 1, 0, 4, 7, 7, 3, 0, 4, 5, 6, 6, 7, 4, 0, 3, 2, 2, 1, 0, 0, 1, 5, 5, 4, 0, 3, 7, 6, 6, 2, 3 }; static unsigned int loadCubemap(std::vector<std::string> faces) { unsigned int textureID; glGenTextures(1, &textureID); glBindTexture(GL_TEXTURE_CUBE_MAP, textureID); stbi_set_flip_vertically_on_load(false); int width, height, nrChannels; for (unsigned int i = 0; i < faces.size(); i++) { unsigned char* data = stbi_load(faces[i].c_str(), &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); stbi_image_free(data); } else { std::cout << "Cubemap tex failed to load at path: " << faces[i] << std::endl; stbi_image_free(data); } } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); return textureID; } Skybox::Skybox(std::vector<std::string>& faceImages) { texture = loadCubemap(faceImages); glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(skyboxVertices), &skyboxVertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(skyboxIndices), &skyboxIndices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } void Skybox::Draw(Camera* camera) { if (skyboxShader == nullptr) skyboxShader = new Shader("..\\Shaders\\Skybox.vs", "..\\Shaders\\Skybox.frag"); auto proj_mat = camera->GetProjectionMatrix(); auto view_mat = glm::mat4(glm::mat3(camera->GetViewMatrix())); glDisable(GL_DEPTH_TEST); skyboxShader->Use(); skyboxShader->SetMat4("projection", proj_mat); skyboxShader->SetMat4("view", view_mat); skyboxShader->SetFloat("skyNight", (glm::sin(glfwGetTime()*0.1+1) * glm::sin(glfwGetTime()*0.1+1)+0.4)*0.8); glBindVertexArray(VAO); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP, texture); glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0); glBindVertexArray(0); glEnable(GL_DEPTH_TEST); }
26.025862
113
0.7158
[ "vector" ]
8e3579782d3bd45fc3ad6255c58374c28ac538cb
7,626
cpp
C++
flexcore/extended/visualization/visualization.cpp
vacing/flexcore
08c08e98556f92d1993e2738cbcb975b3764fa2d
[ "Apache-2.0" ]
47
2016-09-23T10:27:17.000Z
2021-12-14T07:31:40.000Z
flexcore/extended/visualization/visualization.cpp
vacing/flexcore
08c08e98556f92d1993e2738cbcb975b3764fa2d
[ "Apache-2.0" ]
10
2016-12-04T16:40:29.000Z
2020-04-28T08:46:50.000Z
flexcore/extended/visualization/visualization.cpp
vacing/flexcore
08c08e98556f92d1993e2738cbcb975b3764fa2d
[ "Apache-2.0" ]
20
2016-09-23T17:14:41.000Z
2021-10-09T18:24:47.000Z
#include "visualization.hpp" #include <flexcore/scheduler/parallelregion.hpp> #include <flexcore/extended/graph/graph.hpp> #include <boost/algorithm/string/replace.hpp> #include <cassert> #include <map> #include <ostream> #include <string> #include <vector> namespace fc { struct visualization::impl { impl(const graph::connection_graph& g, const forest_t& f, const std::set<graph::graph_properties>& p) : graph_(g) , forest_(f) , ports_(p) { } static graph::graph_port_properties::port_type merge_property_types( const graph::graph_properties& source_node, const graph::graph_properties& sink_node); std::vector<graph::graph_properties> find_node_ports( graph::unique_id node_id) const; std::vector<graph::graph_properties> find_connectables( graph::unique_id node_id) const; std::string get_color(const parallel_region* region); void print_subgraph(typename forest_t::const_iterator node, std::ostream& stream); void print_ports(const std::vector<graph::graph_properties>& ports, unsigned long owner_hash, std::ostream& stream); static std::string escape_label(const std::string& label); const graph::connection_graph& graph_; const forest_t& forest_; const std::set<graph::graph_properties>& ports_; std::map<std::string, unsigned int> color_map_ {}; unsigned int current_color_index_ = 0U; }; graph::graph_port_properties::port_type visualization::impl::merge_property_types( const graph::graph_properties& source_node, const graph::graph_properties& sink_node) { using port_type = graph::graph_port_properties::port_type; port_type result = source_node.port_properties.type(); if (result == port_type::UNDEFINED) { auto sink_type = sink_node.port_properties.type(); assert(sink_type != port_type::UNDEFINED); result = sink_type; } return result; } std::vector<graph::graph_properties> visualization::impl::find_node_ports( graph::unique_id node_id) const { std::vector<graph::graph_properties> result; std::copy_if(std::begin(ports_), std::end(ports_), std::back_inserter(result), [&node_id](auto& port) { return port.port_properties.owning_node() == node_id; }); return result; } std::vector<graph::graph_properties> visualization::impl::find_connectables( graph::unique_id node_id) const { std::vector<graph::graph_properties> result; for (auto& edge : graph_.edges()) { auto& source_props = edge.source.port_properties; if (source_props.id() == node_id && edge.sink.node_properties.is_pure()) { result.push_back(edge.sink); } } return result; } void visualization::impl::print_subgraph(forest_t::const_iterator node, std::ostream& stream) { const auto graph_info = (*node)->graph_info(); const auto uuid = hash_value(graph_info.get_id()); const auto& name = graph_info.name(); stream << "subgraph cluster_" << uuid << " {\n"; stream << "label=\"" << escape_label(name) << "\";\n"; stream << "style=\"filled, bold, rounded\";\n"; stream << "fillcolor=\"" << get_color(graph_info.region()) << "\";\n"; const auto ports = find_node_ports(graph_info.get_id()); if (ports.empty()) { stream << uuid << "[shape=\"plaintext\", label=\"\", width=0, height=0];\n"; } else { print_ports(ports, uuid, stream); } for (auto iter = adobe::child_begin(node); iter != adobe::child_end(node); ++iter) { print_subgraph(iter.base(), stream); } stream << "}\n"; for (auto& port : ports) { for (auto& connectable : find_connectables(port.port_properties.id())) { print_ports({connectable}, hash_value(connectable.node_properties.get_id()), stream); } } } std::string visualization::impl::get_color(const parallel_region* region) { static constexpr auto no_region_color = "#ffffff"; static constexpr auto out_of_color = "#000000"; static constexpr auto colors = {"#809cda", "#e0eb5a", "#50bb3e", "#ed5690", "#64e487", "#ef5954", "#5ae5ac", "#ce76b5", "#48ab52", "#d8a4e7", "#76a73b", "#df8cb0", "#ceec77", "#58b1e1", "#e28f26", "#50d9e1", "#e27130", "#77e3c6", "#e2815e", "#42a68f", "#e7ba3b", "#de7c7f", "#a6e495", "#bc844e", "#5daa6e", "#c49739", "#dfeca1", "#999d31", "#e8b17c", "#9dbc70", "#dcd069", "#959551", "#d5c681", "#98ec6b", "#4a8bf0", "#98c234", "#9485dd", "#c2bf34", "#b875e7", "#e267cb"}; if (region == nullptr) { return no_region_color; } const auto key = region->get_id().key; auto iter = color_map_.find(key); if (iter == std::end(color_map_)) { if (current_color_index_ >= colors.size()) return out_of_color; iter = color_map_.emplace(key, current_color_index_).first; ++current_color_index_; } assert(iter->second < colors.size()); const auto color_iter = begin(colors) + iter->second; return *color_iter; } void visualization::impl::print_ports(const std::vector<graph::graph_properties>& ports, unsigned long owner_hash, std::ostream& stream) { if (ports.empty()) { return; } // named ports with pseudo node if (ports.size() == 1 && ports.front().node_properties.is_pure()) { for (auto& port : ports) { stream << hash_value(port.node_properties.get_id()); stream << "[shape=\"record\", style=\"dashed, filled, bold\", fillcolor=\"white\" " "label=\""; stream << "<" << hash_value(port.port_properties.id()) << ">"; stream << escape_label(port.port_properties.description()); stream << "\"];\n"; } } else // extended ports { const auto printer = [&stream](auto&& port) { stream << "<" << hash_value(port.port_properties.id()) << ">"; stream << escape_label(port.port_properties.description()); }; stream << owner_hash << "[shape=\"record\", label=\""; printer(ports.front()); for (auto iter = ++std::begin(ports); iter != std::end(ports); ++iter) { stream << "|"; printer(*iter); } stream << "\"]\n"; } } std::string visualization::impl::escape_label(const std::string& label) { std::string s = boost::replace_all_copy(label, "<", "\\<"); boost::replace_all(s, ">", "\\>"); return s; } visualization::visualization(const graph::connection_graph& graph, const forest_t& forest) : pimpl{std::make_unique<impl>(graph, forest, graph.ports())} { assert(pimpl); } void visualization::visualize(std::ostream& stream) { pimpl->current_color_index_ = 0U; // nodes with their ports that are part of the forest stream << "digraph G {\n"; stream << "rankdir=\"LR\"\n"; pimpl->print_subgraph(pimpl->forest_.begin(), stream); // these are the ports wich are not part of the forest (ad hoc created) std::vector<graph::graph_properties> named_ports; std::copy_if(std::begin(pimpl->ports_), std::end(pimpl->ports_), std::back_inserter(named_ports), [this](auto&& graph_properties) { return graph_properties.node_properties.is_pure(); }); for (auto& port : named_ports) { pimpl->print_ports({port}, hash_value(port.node_properties.get_id()), stream); } for (auto& edge : pimpl->graph_.edges()) { const auto source_node = hash_value(edge.source.node_properties.get_id()); const auto sink_node = hash_value(edge.sink.node_properties.get_id()); const auto source_port = hash_value(edge.source.port_properties.id()); const auto sink_port = hash_value(edge.sink.port_properties.id()); using port_type = graph::graph_port_properties::port_type; stream << source_node << ":" << source_port << "->" << sink_node << ":" << sink_port; // draw arrow differently based on whether it is an event or state const auto merged_type = pimpl->merge_property_types(edge.source, edge.sink); if (merged_type == port_type::STATE) { stream << "[arrowhead=\"dot\"]"; } stream << ";\n"; } stream << "}\n"; } visualization::~visualization() = default; }
30.75
98
0.688565
[ "shape", "vector" ]
8e35e34539a347d6d6a1a8a4a051dfb87b4c5277
11,828
cpp
C++
src/thunderbots/software/network_input/backend.cpp
qgolsteyn/Software
08beaa44059519b1ed2954079e436790393da6db
[ "MIT" ]
null
null
null
src/thunderbots/software/network_input/backend.cpp
qgolsteyn/Software
08beaa44059519b1ed2954079e436790393da6db
[ "MIT" ]
null
null
null
src/thunderbots/software/network_input/backend.cpp
qgolsteyn/Software
08beaa44059519b1ed2954079e436790393da6db
[ "MIT" ]
null
null
null
#include "network_input/backend.h" #include "network_input/util/ros_messages.h" #include "proto/messages_robocup_ssl_detection.pb.h" #include "proto/messages_robocup_ssl_geometry.pb.h" #include "shared/constants.h" #include "util/constants.h" Backend::Backend() : ball_filter(), friendly_team_filter(), enemy_team_filter() {} std::optional<thunderbots_msgs::Field> Backend::getFieldMsg( const SSL_WrapperPacket &packet) { if (packet.has_geometry()) { const SSL_GeometryData &geom = packet.geometry(); const SSL_GeometryFieldSize &field = geom.field(); thunderbots_msgs::Field field_msg = MessageUtil::createFieldMsgFromFieldGeometry(field); return std::optional<thunderbots_msgs::Field>(field_msg); } return std::nullopt; } std::optional<thunderbots_msgs::Ball> Backend::getFilteredBallMsg( const SSL_WrapperPacket &packet) { if (packet.has_detection()) { const SSL_DetectionFrame &detection = packet.detection(); if (!detection.balls().empty()) { std::vector<SSLBallData> ball_detections = std::vector<SSLBallData>(); for (const SSL_DetectionBall &ball : detection.balls()) { // Convert all data to meters and radians SSLBallData ball_data; ball_data.position = Point(ball.x() * METERS_PER_MILLIMETER, ball.y() * METERS_PER_MILLIMETER); ball_data.confidence = ball.confidence(); ball_data.timestamp = detection.t_capture(); ball_detections.push_back(ball_data); } FilteredBallData filtered_ball_data = ball_filter.getFilteredData(ball_detections); thunderbots_msgs::Ball ball_msg = MessageUtil::createBallMsgFromFilteredBallData(filtered_ball_data); return ball_msg; } } return std::nullopt; } std::optional<thunderbots_msgs::Team> Backend::getFilteredFriendlyTeamMsg( const SSL_WrapperPacket &packet) { if (packet.has_detection()) { const SSL_DetectionFrame &detection = packet.detection(); std::vector<SSLRobotData> friendly_team_robot_data = std::vector<SSLRobotData>(); auto ssl_robots = detection.robots_yellow(); if (Util::Constants::FRIENDLY_TEAM_COLOUR == BLUE) { ssl_robots = detection.robots_blue(); } if (!ssl_robots.empty()) { for (const SSL_DetectionRobot &friendly_robot : ssl_robots) { SSLRobotData new_robot_data; new_robot_data.id = friendly_robot.robot_id(); new_robot_data.position = Point(friendly_robot.x() * METERS_PER_MILLIMETER, friendly_robot.y() * METERS_PER_MILLIMETER); new_robot_data.orientation = Angle::ofRadians(friendly_robot.orientation()); new_robot_data.confidence = friendly_robot.confidence(); new_robot_data.timestamp = Timestamp::fromSeconds(detection.t_capture()); friendly_team_robot_data.emplace_back(new_robot_data); } std::vector<FilteredRobotData> filtered_friendly_team_data = friendly_team_filter.getFilteredData(friendly_team_robot_data); thunderbots_msgs::Team friendly_team_msg = MessageUtil::createTeamMsgFromFilteredRobotData( filtered_friendly_team_data); return friendly_team_msg; } } return std::nullopt; } std::optional<thunderbots_msgs::Team> Backend::getFilteredEnemyTeamMsg( const SSL_WrapperPacket &packet) { if (packet.has_detection()) { const SSL_DetectionFrame &detection = packet.detection(); std::vector<SSLRobotData> enemy_team_robot_data = std::vector<SSLRobotData>(); auto ssl_robots = detection.robots_yellow(); if (Util::Constants::FRIENDLY_TEAM_COLOUR == YELLOW) { ssl_robots = detection.robots_blue(); } if (!ssl_robots.empty()) { for (const SSL_DetectionRobot &enemy_robot : ssl_robots) { SSLRobotData new_robot_data; new_robot_data.id = enemy_robot.robot_id(); new_robot_data.position = Point(enemy_robot.x() * METERS_PER_MILLIMETER, enemy_robot.y() * METERS_PER_MILLIMETER); new_robot_data.orientation = Angle::ofRadians(enemy_robot.orientation()); new_robot_data.confidence = enemy_robot.confidence(); new_robot_data.timestamp = Timestamp::fromSeconds(detection.t_capture()); enemy_team_robot_data.emplace_back(new_robot_data); } std::vector<FilteredRobotData> filtered_enemy_team_data = enemy_team_filter.getFilteredData(enemy_team_robot_data); thunderbots_msgs::Team enemy_team_msg = MessageUtil::createTeamMsgFromFilteredRobotData(filtered_enemy_team_data); return enemy_team_msg; } } return std::nullopt; } std::optional<thunderbots_msgs::RefboxData> Backend::getRefboxDataMsg( const Referee &packet) { thunderbots_msgs::RefboxData refbox_data; refbox_data.command.command = getTeamCommand(packet.command()); setOurFieldSide(packet.blue_team_on_positive_half()); auto designated_position = refboxGlobalToLocalPoint(packet.designated_position()); refbox_data.ball_placement_point.x = designated_position.x(); refbox_data.ball_placement_point.y = designated_position.y(); refbox_data.packet_timestamp = packet.packet_timestamp(); refbox_data.command_timestamp = packet.command_timestamp(); thunderbots_msgs::RefboxTeamInfo blue = getTeamInfo(packet.blue()); thunderbots_msgs::RefboxTeamInfo yellow = getTeamInfo(packet.yellow()); if (Util::Constants::FRIENDLY_TEAM_COLOUR == TeamColour::BLUE) { refbox_data.us = blue; refbox_data.them = yellow; } else { refbox_data.us = yellow; refbox_data.them = blue; } return std::make_optional<thunderbots_msgs::RefboxData>(refbox_data); } // this maps a protobuf Referee_Command enum to its ROS message equivalent // this map is used when we are on the blue team const static std::unordered_map<Referee::Command, int> blue_team_command_map = { {Referee_Command_HALT, thunderbots_msgs::RefboxCommand::HALT}, {Referee_Command_STOP, thunderbots_msgs::RefboxCommand::STOP}, {Referee_Command_NORMAL_START, thunderbots_msgs::RefboxCommand::NORMAL_START}, {Referee_Command_FORCE_START, thunderbots_msgs::RefboxCommand::FORCE_START}, {Referee_Command_PREPARE_KICKOFF_BLUE, thunderbots_msgs::RefboxCommand::PREPARE_KICKOFF_US}, {Referee_Command_PREPARE_KICKOFF_YELLOW, thunderbots_msgs::RefboxCommand::PREPARE_KICKOFF_THEM}, {Referee_Command_PREPARE_PENALTY_BLUE, thunderbots_msgs::RefboxCommand::PREPARE_PENALTY_US}, {Referee_Command_PREPARE_PENALTY_YELLOW, thunderbots_msgs::RefboxCommand::PREPARE_PENALTY_THEM}, {Referee_Command_DIRECT_FREE_BLUE, thunderbots_msgs::RefboxCommand::DIRECT_FREE_US}, {Referee_Command_DIRECT_FREE_YELLOW, thunderbots_msgs::RefboxCommand::DIRECT_FREE_THEM}, {Referee_Command_INDIRECT_FREE_BLUE, thunderbots_msgs::RefboxCommand::INDIRECT_FREE_US}, {Referee_Command_INDIRECT_FREE_YELLOW, thunderbots_msgs::RefboxCommand::INDIRECT_FREE_THEM}, {Referee_Command_TIMEOUT_BLUE, thunderbots_msgs::RefboxCommand::TIMEOUT_US}, {Referee_Command_TIMEOUT_YELLOW, thunderbots_msgs::RefboxCommand::TIMEOUT_THEM}, {Referee_Command_GOAL_BLUE, thunderbots_msgs::RefboxCommand::GOAL_US}, {Referee_Command_GOAL_YELLOW, thunderbots_msgs::RefboxCommand::GOAL_THEM}, {Referee_Command_BALL_PLACEMENT_BLUE, thunderbots_msgs::RefboxCommand::BALL_PLACEMENT_US}, {Referee_Command_BALL_PLACEMENT_YELLOW, thunderbots_msgs::RefboxCommand::BALL_PLACEMENT_THEM}}; // this maps a protobuf Referee_Command enum to its ROS message equivalent // this map is used when we are on the yellow team const static std::unordered_map<Referee::Command, int> yellow_team_command_map = { {Referee_Command_HALT, thunderbots_msgs::RefboxCommand::HALT}, {Referee_Command_STOP, thunderbots_msgs::RefboxCommand::STOP}, {Referee_Command_NORMAL_START, thunderbots_msgs::RefboxCommand::NORMAL_START}, {Referee_Command_FORCE_START, thunderbots_msgs::RefboxCommand::FORCE_START}, {Referee_Command_PREPARE_KICKOFF_BLUE, thunderbots_msgs::RefboxCommand::PREPARE_KICKOFF_THEM}, {Referee_Command_PREPARE_KICKOFF_YELLOW, thunderbots_msgs::RefboxCommand::PREPARE_KICKOFF_US}, {Referee_Command_PREPARE_PENALTY_BLUE, thunderbots_msgs::RefboxCommand::PREPARE_PENALTY_THEM}, {Referee_Command_PREPARE_PENALTY_YELLOW, thunderbots_msgs::RefboxCommand::PREPARE_PENALTY_US}, {Referee_Command_DIRECT_FREE_BLUE, thunderbots_msgs::RefboxCommand::DIRECT_FREE_THEM}, {Referee_Command_DIRECT_FREE_YELLOW, thunderbots_msgs::RefboxCommand::DIRECT_FREE_US}, {Referee_Command_INDIRECT_FREE_BLUE, thunderbots_msgs::RefboxCommand::INDIRECT_FREE_THEM}, {Referee_Command_INDIRECT_FREE_YELLOW, thunderbots_msgs::RefboxCommand::INDIRECT_FREE_US}, {Referee_Command_TIMEOUT_BLUE, thunderbots_msgs::RefboxCommand::TIMEOUT_THEM}, {Referee_Command_TIMEOUT_YELLOW, thunderbots_msgs::RefboxCommand::TIMEOUT_US}, {Referee_Command_GOAL_BLUE, thunderbots_msgs::RefboxCommand::GOAL_THEM}, {Referee_Command_GOAL_YELLOW, thunderbots_msgs::RefboxCommand::GOAL_US}, {Referee_Command_BALL_PLACEMENT_BLUE, thunderbots_msgs::RefboxCommand::BALL_PLACEMENT_THEM}, {Referee_Command_BALL_PLACEMENT_YELLOW, thunderbots_msgs::RefboxCommand::BALL_PLACEMENT_US}}; int32_t Backend::getTeamCommand(const Referee::Command &command) { auto our_team_colour = Util::Constants::FRIENDLY_TEAM_COLOUR; if (our_team_colour == TeamColour::BLUE) { return blue_team_command_map.at(command); } else { return yellow_team_command_map.at(command); } } Point Backend::refboxGlobalToLocalPoint(const Referee::Point &point) { if (our_field_side == FieldSide::WEST) { return Point(-point.x(), -point.y()); } else { return Point(point.x(), point.y()); } } void Backend::setOurFieldSide(bool blue_team_on_positive_half) { if (blue_team_on_positive_half) { if (Util::Constants::FRIENDLY_TEAM_COLOUR == TeamColour::BLUE) { our_field_side = FieldSide::WEST; } else { our_field_side = FieldSide::EAST; } } else { if (Util::Constants::FRIENDLY_TEAM_COLOUR == TeamColour::BLUE) { our_field_side = FieldSide::EAST; } else { our_field_side = FieldSide::WEST; } } } thunderbots_msgs::RefboxTeamInfo Backend::getTeamInfo(const Referee::TeamInfo &team_info) { thunderbots_msgs::RefboxTeamInfo refbox_team_info; refbox_team_info.team_name = team_info.name(); refbox_team_info.score = team_info.score(); refbox_team_info.red_cards = team_info.red_cards(); for (auto card_time : team_info.yellow_card_times()) { refbox_team_info.yellow_card_times.push_back(card_time); } refbox_team_info.timeouts = team_info.timeouts(); refbox_team_info.timeout_time = team_info.timeout_time(); refbox_team_info.goalie = team_info.goalkeeper(); return refbox_team_info; }
38.780328
90
0.695722
[ "geometry", "vector" ]
8e3f1ec722922da02e403006581927e6dd693f98
298,112
cpp
C++
src/kuka_kr6_r900/ikfast0x1000004a.Transform6D.0_1_2_3_4_5.cpp
Simon-Steinmann/ikfast_pybind
e7606df267e1e37beaa88b58e691d4975abca2e6
[ "MIT" ]
18
2019-08-21T03:06:03.000Z
2022-02-16T03:42:34.000Z
src/kuka_kr6_r900/ikfast0x1000004a.Transform6D.0_1_2_3_4_5.cpp
Simon-Steinmann/ikfast_pybind
e7606df267e1e37beaa88b58e691d4975abca2e6
[ "MIT" ]
6
2020-09-17T10:41:06.000Z
2021-04-21T15:48:58.000Z
src/kuka_kr6_r900/ikfast0x1000004a.Transform6D.0_1_2_3_4_5.cpp
Simon-Steinmann/ikfast_pybind
e7606df267e1e37beaa88b58e691d4975abca2e6
[ "MIT" ]
5
2020-11-29T17:59:05.000Z
2022-03-25T08:17:20.000Z
/// autogenerated analytical inverse kinematics code from ikfast program part of OpenRAVE /// \author Rosen Diankov /// /// 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. /// /// ikfast version 0x1000004a generated on 2018-11-21 10:02:40.045769 /// Generated using solver transform6d /// To compile with gcc: /// gcc -lstdc++ ik.cpp /// To compile without any main function as a shared object (might need -llapack): /// gcc -fPIC -lstdc++ -DIKFAST_NO_MAIN -DIKFAST_CLIBRARY -shared -Wl,-soname,libik.so -o libik.so ik.cpp #define IKFAST_HAS_LIBRARY #include "ikfast.h" // found inside share/openrave-X.Y/python/ikfast.h using namespace ikfast; // check if the included ikfast version matches what this file was compiled with //#define IKFAST_COMPILE_ASSERT(x) extern int __dummy[(int)x] //IKFAST_COMPILE_ASSERT(IKFAST_VERSION==0x1000004a); #include <cmath> #include <vector> #include <limits> #include <algorithm> #include <complex> #ifndef IKFAST_ASSERT #include <stdexcept> #include <sstream> #include <iostream> #ifdef _MSC_VER #ifndef __PRETTY_FUNCTION__ #define __PRETTY_FUNCTION__ __FUNCDNAME__ #endif #endif #ifndef __PRETTY_FUNCTION__ #define __PRETTY_FUNCTION__ __func__ #endif #define IKFAST_ASSERT(b) { if( !(b) ) { std::stringstream ss; ss << "ikfast exception: " << __FILE__ << ":" << __LINE__ << ": " <<__PRETTY_FUNCTION__ << ": Assertion '" << #b << "' failed"; throw std::runtime_error(ss.str()); } } #endif #if defined(_MSC_VER) #define IKFAST_ALIGNED16(x) __declspec(align(16)) x #else #define IKFAST_ALIGNED16(x) x __attribute((aligned(16))) #endif #define IK2PI ((IkReal)6.28318530717959) #define IKPI ((IkReal)3.14159265358979) #define IKPI_2 ((IkReal)1.57079632679490) #ifdef _MSC_VER #ifndef isnan // #define isnan _isnan #define isnan std::isnan #endif #ifndef isinf // #define isinf _isinf #define isinf std::isinf #endif //#ifndef isfinite //#define isfinite _isfinite //#endif #endif // _MSC_VER // lapack routines extern "C" { void dgetrf_ (const int* m, const int* n, double* a, const int* lda, int* ipiv, int* info); void zgetrf_ (const int* m, const int* n, std::complex<double>* a, const int* lda, int* ipiv, int* info); void dgetri_(const int* n, const double* a, const int* lda, int* ipiv, double* work, const int* lwork, int* info); void dgesv_ (const int* n, const int* nrhs, double* a, const int* lda, int* ipiv, double* b, const int* ldb, int* info); void dgetrs_(const char *trans, const int *n, const int *nrhs, double *a, const int *lda, int *ipiv, double *b, const int *ldb, int *info); void dgeev_(const char *jobvl, const char *jobvr, const int *n, double *a, const int *lda, double *wr, double *wi,double *vl, const int *ldvl, double *vr, const int *ldvr, double *work, const int *lwork, int *info); } using namespace std; // necessary to get std math routines #ifdef IKFAST_NAMESPACE namespace IKFAST_NAMESPACE { #endif inline float IKabs(float f) { return fabsf(f); } inline double IKabs(double f) { return fabs(f); } inline float IKsqr(float f) { return f*f; } inline double IKsqr(double f) { return f*f; } inline float IKlog(float f) { return logf(f); } inline double IKlog(double f) { return log(f); } // allows asin and acos to exceed 1. has to be smaller than thresholds used for branch conds and evaluation #ifndef IKFAST_SINCOS_THRESH #define IKFAST_SINCOS_THRESH ((IkReal)1e-7) #endif // used to check input to atan2 for degenerate cases. has to be smaller than thresholds used for branch conds and evaluation #ifndef IKFAST_ATAN2_MAGTHRESH #define IKFAST_ATAN2_MAGTHRESH ((IkReal)1e-7) #endif // minimum distance of separate solutions #ifndef IKFAST_SOLUTION_THRESH #define IKFAST_SOLUTION_THRESH ((IkReal)1e-6) #endif // there are checkpoints in ikfast that are evaluated to make sure they are 0. This threshold speicfies by how much they can deviate #ifndef IKFAST_EVALCOND_THRESH #define IKFAST_EVALCOND_THRESH ((IkReal)0.00001) #endif inline float IKasin(float f) { IKFAST_ASSERT( f > -1-IKFAST_SINCOS_THRESH && f < 1+IKFAST_SINCOS_THRESH ); // any more error implies something is wrong with the solver if( f <= -1 ) return float(-IKPI_2); else if( f >= 1 ) return float(IKPI_2); return asinf(f); } inline double IKasin(double f) { IKFAST_ASSERT( f > -1-IKFAST_SINCOS_THRESH && f < 1+IKFAST_SINCOS_THRESH ); // any more error implies something is wrong with the solver if( f <= -1 ) return -IKPI_2; else if( f >= 1 ) return IKPI_2; return asin(f); } // return positive value in [0,y) inline float IKfmod(float x, float y) { while(x < 0) { x += y; } return fmodf(x,y); } // return positive value in [0,y) inline double IKfmod(double x, double y) { while(x < 0) { x += y; } return fmod(x,y); } inline float IKacos(float f) { IKFAST_ASSERT( f > -1-IKFAST_SINCOS_THRESH && f < 1+IKFAST_SINCOS_THRESH ); // any more error implies something is wrong with the solver if( f <= -1 ) return float(IKPI); else if( f >= 1 ) return float(0); return acosf(f); } inline double IKacos(double f) { IKFAST_ASSERT( f > -1-IKFAST_SINCOS_THRESH && f < 1+IKFAST_SINCOS_THRESH ); // any more error implies something is wrong with the solver if( f <= -1 ) return IKPI; else if( f >= 1 ) return 0; return acos(f); } inline float IKsin(float f) { return sinf(f); } inline double IKsin(double f) { return sin(f); } inline float IKcos(float f) { return cosf(f); } inline double IKcos(double f) { return cos(f); } inline float IKtan(float f) { return tanf(f); } inline double IKtan(double f) { return tan(f); } inline float IKsqrt(float f) { if( f <= 0.0f ) return 0.0f; return sqrtf(f); } inline double IKsqrt(double f) { if( f <= 0.0 ) return 0.0; return sqrt(f); } inline float IKatan2Simple(float fy, float fx) { return atan2f(fy,fx); } inline float IKatan2(float fy, float fx) { if( isnan(fy) ) { IKFAST_ASSERT(!isnan(fx)); // if both are nan, probably wrong value will be returned return float(IKPI_2); } else if( isnan(fx) ) { return 0; } return atan2f(fy,fx); } inline double IKatan2Simple(double fy, double fx) { return atan2(fy,fx); } inline double IKatan2(double fy, double fx) { if( isnan(fy) ) { IKFAST_ASSERT(!isnan(fx)); // if both are nan, probably wrong value will be returned return IKPI_2; } else if( isnan(fx) ) { return 0; } return atan2(fy,fx); } template <typename T> struct CheckValue { T value; bool valid; }; template <typename T> inline CheckValue<T> IKatan2WithCheck(T fy, T fx, T epsilon) { CheckValue<T> ret; ret.valid = false; ret.value = 0; if( !isnan(fy) && !isnan(fx) ) { if( IKabs(fy) >= IKFAST_ATAN2_MAGTHRESH || IKabs(fx) > IKFAST_ATAN2_MAGTHRESH ) { ret.value = IKatan2Simple(fy,fx); ret.valid = true; } } return ret; } inline float IKsign(float f) { if( f > 0 ) { return float(1); } else if( f < 0 ) { return float(-1); } return 0; } inline double IKsign(double f) { if( f > 0 ) { return 1.0; } else if( f < 0 ) { return -1.0; } return 0; } template <typename T> inline CheckValue<T> IKPowWithIntegerCheck(T f, int n) { CheckValue<T> ret; ret.valid = true; if( n == 0 ) { ret.value = 1.0; return ret; } else if( n == 1 ) { ret.value = f; return ret; } else if( n < 0 ) { if( f == 0 ) { ret.valid = false; ret.value = (T)1.0e30; return ret; } if( n == -1 ) { ret.value = T(1.0)/f; return ret; } } int num = n > 0 ? n : -n; if( num == 2 ) { ret.value = f*f; } else if( num == 3 ) { ret.value = f*f*f; } else { ret.value = 1.0; while(num>0) { if( num & 1 ) { ret.value *= f; } num >>= 1; f *= f; } } if( n < 0 ) { ret.value = T(1.0)/ret.value; } return ret; } /// solves the forward kinematics equations. /// \param pfree is an array specifying the free joints of the chain. IKFAST_API void ComputeFk(const IkReal* j, IkReal* eetrans, IkReal* eerot) { IkReal x0,x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17,x18,x19,x20,x21,x22,x23,x24,x25,x26,x27,x28,x29,x30,x31,x32,x33,x34,x35,x36,x37,x38,x39,x40,x41,x42,x43,x44,x45; x0=IKcos(j[0]); x1=IKcos(j[1]); x2=IKcos(j[2]); x3=IKsin(j[1]); x4=IKsin(j[2]); x5=IKsin(j[0]); x6=IKsin(j[3]); x7=IKcos(j[3]); x8=IKcos(j[5]); x9=IKsin(j[5]); x10=IKcos(j[4]); x11=IKsin(j[4]); x12=((0.42)*x5); x13=((1.0)*x7); x14=((0.035)*x5); x15=((1.0)*x5); x16=((0.035)*x0); x17=((1.0)*x0); x18=((0.42)*x0); x19=((0.455)*x1); x20=((0.08)*x5); x21=((0.08)*x0); x22=((0.08)*x7); x23=(x2*x3); x24=(x0*x6); x25=(x3*x4); x26=(x1*x2); x27=(x1*x4); x28=((-1.0)*x6); x29=(x5*x7); x30=(x11*x7); x31=(x15*x6); x32=(x0*x13); x33=((1.0)*x26); x34=(x15*x25); x35=((((-1.0)*x33))+x25); x36=(x35*x7); x37=(((x0*x26))+(((-1.0)*x17*x25))); x38=(x17*(((((-1.0)*x23))+(((-1.0)*x27))))); x39=(x15*(((((-1.0)*x23))+(((-1.0)*x27))))); x40=(x11*(((((-1.0)*x34))+((x26*x5))))); x41=(x38*x6); x42=(x39*x7); x43=((((-1.0)*x17*x6))+(((-1.0)*x13*x39))); x44=(((x10*x36))+((x11*((x27+x23))))); x45=(((x10*(((((-1.0)*x31))+(((1.0)*x13*x38))))))+(((-1.0)*x11*x37))); eerot[0]=(((x9*(((((-1.0)*x29))+((x28*x38))))))+((x45*x8))); eerot[1]=(((x8*((x41+x29))))+((x45*x9))); eerot[2]=(((x10*x37))+((x11*(((((-1.0)*x31))+((x38*x7))))))); IkReal x46=((1.0)*x25); eetrans[0]=(((x10*((((x21*x26))+(((-1.0)*x21*x46))))))+((x18*x26))+(((0.025)*x0))+((x11*((((x22*x38))+(((-1.0)*x20*x6))))))+((x0*x19))+(((-1.0)*x18*x46))+((x16*x27))+((x16*x23))); eerot[3]=(((x8*((x40+((x10*(((((-1.0)*x42))+(((-1.0)*x24))))))))))+((x9*(((((-1.0)*x32))+((x39*x6))))))); eerot[4]=(((x8*((((x28*x39))+x32))))+((x9*((((x10*x43))+x40))))); eerot[5]=(((x11*x43))+((x10*(((((-1.0)*x15*x26))+x34))))); IkReal x47=((1.0)*x26); IkReal x48=((1.0)*x14); eetrans[1]=((((-1.0)*x23*x48))+(((-1.0)*x19*x5))+(((-0.025)*x5))+(((-1.0)*x27*x48))+((x11*(((((-1.0)*x21*x6))+(((-1.0)*x22*x39))))))+((x12*x25))+(((-1.0)*x12*x47))+((x10*(((((-1.0)*x20*x47))+((x20*x25))))))); eerot[6]=(((x6*x9*(((((-1.0)*x25))+x33))))+((x44*x8))); eerot[7]=(((x44*x9))+((x35*x6*x8))); eerot[8]=(((x10*(((((-1.0)*x23))+(((-1.0)*x27))))))+((x30*x35))); eetrans[2]=((0.4)+((x10*(((((-0.08)*x23))+(((-0.08)*x27))))))+((x30*(((((-0.08)*x26))+(((0.08)*x25))))))+(((-0.035)*x25))+(((-0.455)*x3))+(((-0.42)*x23))+(((-0.42)*x27))+(((0.035)*x26))); } IKFAST_API int GetNumFreeParameters() { return 0; } IKFAST_API int* GetFreeParameters() { return NULL; } IKFAST_API int GetNumJoints() { return 6; } IKFAST_API int GetIkRealSize() { return sizeof(IkReal); } IKFAST_API int GetIkType() { return 0x67000001; } class IKSolver { public: IkReal j0,cj0,sj0,htj0,j0mul,j1,cj1,sj1,htj1,j1mul,j2,cj2,sj2,htj2,j2mul,j3,cj3,sj3,htj3,j3mul,j4,cj4,sj4,htj4,j4mul,j5,cj5,sj5,htj5,j5mul,new_r00,r00,rxp0_0,new_r01,r01,rxp0_1,new_r02,r02,rxp0_2,new_r10,r10,rxp1_0,new_r11,r11,rxp1_1,new_r12,r12,rxp1_2,new_r20,r20,rxp2_0,new_r21,r21,rxp2_1,new_r22,r22,rxp2_2,new_px,px,npx,new_py,py,npy,new_pz,pz,npz,pp; unsigned char _ij0[2], _nj0,_ij1[2], _nj1,_ij2[2], _nj2,_ij3[2], _nj3,_ij4[2], _nj4,_ij5[2], _nj5; IkReal j100, cj100, sj100; unsigned char _ij100[2], _nj100; bool ComputeIk(const IkReal* eetrans, const IkReal* eerot, const IkReal* pfree, IkSolutionListBase<IkReal>& solutions) { j0=numeric_limits<IkReal>::quiet_NaN(); _ij0[0] = -1; _ij0[1] = -1; _nj0 = -1; j1=numeric_limits<IkReal>::quiet_NaN(); _ij1[0] = -1; _ij1[1] = -1; _nj1 = -1; j2=numeric_limits<IkReal>::quiet_NaN(); _ij2[0] = -1; _ij2[1] = -1; _nj2 = -1; j3=numeric_limits<IkReal>::quiet_NaN(); _ij3[0] = -1; _ij3[1] = -1; _nj3 = -1; j4=numeric_limits<IkReal>::quiet_NaN(); _ij4[0] = -1; _ij4[1] = -1; _nj4 = -1; j5=numeric_limits<IkReal>::quiet_NaN(); _ij5[0] = -1; _ij5[1] = -1; _nj5 = -1; for(int dummyiter = 0; dummyiter < 1; ++dummyiter) { solutions.Clear(); r00 = eerot[0*3+0]; r01 = eerot[0*3+1]; r02 = eerot[0*3+2]; r10 = eerot[1*3+0]; r11 = eerot[1*3+1]; r12 = eerot[1*3+2]; r20 = eerot[2*3+0]; r21 = eerot[2*3+1]; r22 = eerot[2*3+2]; px = eetrans[0]; py = eetrans[1]; pz = eetrans[2]; new_r00=((-1.0)*r00); new_r01=r01; new_r02=((-1.0)*r02); new_px=((((-0.08)*r02))+px); new_r10=r10; new_r11=((-1.0)*r11); new_r12=r12; new_py=((((-1.0)*py))+(((0.08)*r12))); new_r20=r20; new_r21=((-1.0)*r21); new_r22=r22; new_pz=((0.4)+(((-1.0)*pz))+(((0.08)*r22))); r00 = new_r00; r01 = new_r01; r02 = new_r02; r10 = new_r10; r11 = new_r11; r12 = new_r12; r20 = new_r20; r21 = new_r21; r22 = new_r22; px = new_px; py = new_py; pz = new_pz; IkReal x49=((1.0)*px); IkReal x50=((1.0)*pz); IkReal x51=((1.0)*py); pp=((px*px)+(py*py)+(pz*pz)); npx=(((px*r00))+((py*r10))+((pz*r20))); npy=(((px*r01))+((py*r11))+((pz*r21))); npz=(((px*r02))+((py*r12))+((pz*r22))); rxp0_0=((((-1.0)*r20*x51))+((pz*r10))); rxp0_1=(((px*r20))+(((-1.0)*r00*x50))); rxp0_2=((((-1.0)*r10*x49))+((py*r00))); rxp1_0=((((-1.0)*r21*x51))+((pz*r11))); rxp1_1=(((px*r21))+(((-1.0)*r01*x50))); rxp1_2=((((-1.0)*r11*x49))+((py*r01))); rxp2_0=(((pz*r12))+(((-1.0)*r22*x51))); rxp2_1=(((px*r22))+(((-1.0)*r02*x50))); rxp2_2=((((-1.0)*r12*x49))+((py*r02))); { IkReal j0eval[1]; j0eval[0]=((IKabs(px))+(IKabs(py))); if( IKabs(j0eval[0]) < 0.0000010000000000 ) { continue; // no branches [j0, j1, j2] } else { { IkReal j0array[2], cj0array[2], sj0array[2]; bool j0valid[2]={false}; _nj0 = 2; CheckValue<IkReal> x53 = IKatan2WithCheck(IkReal(py),IkReal(((-1.0)*px)),IKFAST_ATAN2_MAGTHRESH); if(!x53.valid){ continue; } IkReal x52=x53.value; j0array[0]=((-1.0)*x52); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); j0array[1]=((3.14159265358979)+(((-1.0)*x52))); sj0array[1]=IKsin(j0array[1]); cj0array[1]=IKcos(j0array[1]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; if( j0array[1] > IKPI ) { j0array[1]-=IK2PI; } else if( j0array[1] < -IKPI ) { j0array[1]+=IK2PI; } j0valid[1] = true; for(int ij0 = 0; ij0 < 2; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 2; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal j2array[2], cj2array[2], sj2array[2]; bool j2valid[2]={false}; _nj2 = 2; if( (((1.00130425120353)+(((0.130369670100063)*py*sj0))+(((0.130369670100063)*cj0*px))+(((-2.60739340200126)*pp)))) < -1-IKFAST_SINCOS_THRESH || (((1.00130425120353)+(((0.130369670100063)*py*sj0))+(((0.130369670100063)*cj0*px))+(((-2.60739340200126)*pp)))) > 1+IKFAST_SINCOS_THRESH ) continue; IkReal x54=IKasin(((1.00130425120353)+(((0.130369670100063)*py*sj0))+(((0.130369670100063)*cj0*px))+(((-2.60739340200126)*pp)))); j2array[0]=((-1.48765509490646)+(((-1.0)*x54))); sj2array[0]=IKsin(j2array[0]); cj2array[0]=IKcos(j2array[0]); j2array[1]=((1.65393755868334)+x54); sj2array[1]=IKsin(j2array[1]); cj2array[1]=IKcos(j2array[1]); if( j2array[0] > IKPI ) { j2array[0]-=IK2PI; } else if( j2array[0] < -IKPI ) { j2array[0]+=IK2PI; } j2valid[0] = true; if( j2array[1] > IKPI ) { j2array[1]-=IK2PI; } else if( j2array[1] < -IKPI ) { j2array[1]+=IK2PI; } j2valid[1] = true; for(int ij2 = 0; ij2 < 2; ++ij2) { if( !j2valid[ij2] ) { continue; } _ij2[0] = ij2; _ij2[1] = -1; for(int iij2 = ij2+1; iij2 < 2; ++iij2) { if( j2valid[iij2] && IKabs(cj2array[ij2]-cj2array[iij2]) < IKFAST_SOLUTION_THRESH && IKabs(sj2array[ij2]-sj2array[iij2]) < IKFAST_SOLUTION_THRESH ) { j2valid[iij2]=false; _ij2[1] = iij2; break; } } j2 = j2array[ij2]; cj2 = cj2array[ij2]; sj2 = sj2array[ij2]; { IkReal j1eval[3]; IkReal x55=cj2*cj2; IkReal x56=(py*sj0); IkReal x57=((40.0)*cj2); IkReal x58=(cj0*px); IkReal x59=((480.0)*sj2); IkReal x60=((0.42)*sj2); IkReal x61=(cj2*sj2); IkReal x62=(cj2*pz); IkReal x63=((0.035)*cj2); IkReal x64=(pz*sj2); j1eval[0]=((((-12.0)*sj2))+(((-1.0)*x56*x57))+cj2+((x58*x59))+(((480.0)*x62))+(((520.0)*pz))+((x56*x59))+(((-1.0)*x57*x58))+(((40.0)*x64))); j1eval[1]=IKsign(((((-1.0)*x56*x63))+(((0.42)*x62))+(((0.035)*x64))+(((0.455)*pz))+((x58*x60))+(((-1.0)*x58*x63))+((x56*x60))+(((-0.0105)*sj2))+(((0.000875)*cj2)))); j1eval[2]=((IKabs(((-0.1764)+(pz*pz)+(((0.0294)*x61))+(((0.175175)*x55)))))+(IKabs(((0.0147)+(((0.1911)*sj2))+(((0.175175)*x61))+(((-0.0294)*x55))+((pz*x56))+((pz*x58))+(((-0.015925)*cj2))+(((-0.025)*pz)))))); if( IKabs(j1eval[0]) < 0.0000010000000000 || IKabs(j1eval[1]) < 0.0000010000000000 || IKabs(j1eval[2]) < 0.0000010000000000 ) { { IkReal j1eval[2]; IkReal x65=(py*sj0); IkReal x66=((0.035)*sj2); IkReal x67=(cj0*px); IkReal x68=((0.42)*cj2); IkReal x69=((40.0)*sj2); IkReal x70=(cj2*pz); IkReal x71=(pz*sj2); IkReal x72=((480.0)*cj2); j1eval[0]=((13.0)+(((12.0)*cj2))+sj2+(((-1.0)*x67*x69))+(((-40.0)*x70))+(((-1.0)*x67*x72))+(((-1.0)*x65*x69))+(((480.0)*x71))+(((-520.0)*x65))+(((-520.0)*x67))+(((-1.0)*x65*x72))); j1eval[1]=IKsign(((0.011375)+(((-1.0)*x66*x67))+(((-1.0)*x67*x68))+(((-0.035)*x70))+(((0.42)*x71))+(((0.0105)*cj2))+(((0.000875)*sj2))+(((-1.0)*x65*x66))+(((-1.0)*x65*x68))+(((-0.455)*x67))+(((-0.455)*x65)))); if( IKabs(j1eval[0]) < 0.0000010000000000 || IKabs(j1eval[1]) < 0.0000010000000000 ) { { IkReal j1eval[2]; IkReal x73=cj0*cj0; IkReal x74=py*py; IkReal x75=px*px; IkReal x76=pz*pz; IkReal x77=(cj0*px); IkReal x78=(py*sj0); IkReal x79=((1600.0)*x74); IkReal x80=(x73*x75); j1eval[0]=((-1.0)+(((-1.0)*x79))+(((-1600.0)*x80))+(((-3200.0)*x77*x78))+(((80.0)*x77))+(((80.0)*x78))+((x73*x79))+(((-1600.0)*x76))); j1eval[1]=IKsign(((-0.000625)+(((-2.0)*x77*x78))+(((-1.0)*x80))+(((-1.0)*x74))+(((-1.0)*x76))+(((0.05)*x77))+(((0.05)*x78))+((x73*x74)))); if( IKabs(j1eval[0]) < 0.0000010000000000 || IKabs(j1eval[1]) < 0.0000010000000000 ) { continue; // no branches [j1] } else { { IkReal j1array[1], cj1array[1], sj1array[1]; bool j1valid[1]={false}; _nj1 = 1; IkReal x81=py*py; IkReal x82=cj0*cj0; IkReal x83=(py*sj0); IkReal x84=(cj0*px); IkReal x85=((0.42)*cj2); IkReal x86=((0.035)*sj2); IkReal x87=((0.42)*sj2); IkReal x88=((0.035)*cj2); CheckValue<IkReal> x89 = IKatan2WithCheck(IkReal((((x84*x87))+(((-1.0)*x83*x88))+(((-0.455)*pz))+(((-1.0)*x84*x88))+((x83*x87))+(((-0.0105)*sj2))+(((-1.0)*pz*x86))+(((-1.0)*pz*x85))+(((0.000875)*cj2)))),IkReal(((0.011375)+(((-1.0)*x83*x85))+(((-1.0)*x83*x86))+(((-0.455)*x84))+(((-0.455)*x83))+((pz*x88))+(((-1.0)*x84*x86))+(((-1.0)*x84*x85))+(((0.0105)*cj2))+(((0.000875)*sj2))+(((-1.0)*pz*x87)))),IKFAST_ATAN2_MAGTHRESH); if(!x89.valid){ continue; } CheckValue<IkReal> x90=IKPowWithIntegerCheck(IKsign(((-0.000625)+(((0.05)*x83))+(((0.05)*x84))+((x81*x82))+(((-2.0)*x83*x84))+(((-1.0)*x81))+(((-1.0)*(pz*pz)))+(((-1.0)*x82*(px*px))))),-1); if(!x90.valid){ continue; } j1array[0]=((-1.5707963267949)+(x89.value)+(((1.5707963267949)*(x90.value)))); sj1array[0]=IKsin(j1array[0]); cj1array[0]=IKcos(j1array[0]); if( j1array[0] > IKPI ) { j1array[0]-=IK2PI; } else if( j1array[0] < -IKPI ) { j1array[0]+=IK2PI; } j1valid[0] = true; for(int ij1 = 0; ij1 < 1; ++ij1) { if( !j1valid[ij1] ) { continue; } _ij1[0] = ij1; _ij1[1] = -1; for(int iij1 = ij1+1; iij1 < 1; ++iij1) { if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH ) { j1valid[iij1]=false; _ij1[1] = iij1; break; } } j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1]; { IkReal evalcond[5]; IkReal x91=IKsin(j1); IkReal x92=IKcos(j1); IkReal x93=(cj0*px); IkReal x94=((0.035)*sj2); IkReal x95=(py*sj0); IkReal x96=((0.42)*sj2); IkReal x97=((1.0)*pz); IkReal x98=((0.035)*cj2); IkReal x99=((0.42)*x91); IkReal x100=((1.0)*x92); IkReal x101=((0.91)*x92); IkReal x102=(cj2*x92); evalcond[0]=((((-0.025)*x91))+x96+(((-1.0)*x92*x97))+(((-1.0)*x98))+((x91*x93))+((x91*x95))); evalcond[1]=((0.455)+(((0.025)*x92))+(((-1.0)*x91*x97))+x94+(((0.42)*cj2))+(((-1.0)*x100*x95))+(((-1.0)*x100*x93))); evalcond[2]=((((0.455)*x91))+((x92*x96))+((cj2*x99))+(((-1.0)*x92*x98))+(((-1.0)*x97))+((x91*x94))); evalcond[3]=((-0.030025)+(((0.05)*x95))+(((0.05)*x93))+((x101*x95))+((x101*x93))+(((-0.02275)*x92))+(((-1.0)*pp))+(((0.91)*pz*x91))); evalcond[4]=((0.025)+(((0.455)*x92))+((x92*x94))+(((-1.0)*x91*x96))+(((-1.0)*x95))+(((-1.0)*x93))+(((0.42)*x102))+((x91*x98))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } rotationfunction0(solutions); } } } } } else { { IkReal j1array[1], cj1array[1], sj1array[1]; bool j1valid[1]={false}; _nj1 = 1; IkReal x605=cj2*cj2; IkReal x606=(py*sj0); IkReal x607=(cj0*px); IkReal x608=((0.42)*cj2); IkReal x609=(cj2*sj2); IkReal x610=((0.035)*sj2); IkReal x611=((1.0)*pz); CheckValue<IkReal> x612=IKPowWithIntegerCheck(IKsign(((0.011375)+(((-0.035)*cj2*pz))+(((0.42)*pz*sj2))+(((-0.455)*x606))+(((-0.455)*x607))+(((-1.0)*x606*x610))+(((-1.0)*x607*x610))+(((0.0105)*cj2))+(((0.000875)*sj2))+(((-1.0)*x606*x608))+(((-1.0)*x607*x608)))),-1); if(!x612.valid){ continue; } CheckValue<IkReal> x613 = IKatan2WithCheck(IkReal(((0.0147)+(((0.1911)*sj2))+(((0.025)*pz))+(((-1.0)*x606*x611))+(((-1.0)*x607*x611))+(((0.175175)*x609))+(((-0.015925)*cj2))+(((-0.0294)*x605)))),IkReal(((-0.20825)+(((-0.3822)*cj2))+(((-0.03185)*sj2))+(pz*pz)+(((-0.175175)*x605))+(((-0.0294)*x609)))),IKFAST_ATAN2_MAGTHRESH); if(!x613.valid){ continue; } j1array[0]=((-1.5707963267949)+(((1.5707963267949)*(x612.value)))+(x613.value)); sj1array[0]=IKsin(j1array[0]); cj1array[0]=IKcos(j1array[0]); if( j1array[0] > IKPI ) { j1array[0]-=IK2PI; } else if( j1array[0] < -IKPI ) { j1array[0]+=IK2PI; } j1valid[0] = true; for(int ij1 = 0; ij1 < 1; ++ij1) { if( !j1valid[ij1] ) { continue; } _ij1[0] = ij1; _ij1[1] = -1; for(int iij1 = ij1+1; iij1 < 1; ++iij1) { if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH ) { j1valid[iij1]=false; _ij1[1] = iij1; break; } } j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1]; { IkReal evalcond[5]; IkReal x614=IKsin(j1); IkReal x615=IKcos(j1); IkReal x616=(cj0*px); IkReal x617=((0.035)*sj2); IkReal x618=(py*sj0); IkReal x619=((0.42)*sj2); IkReal x620=((1.0)*pz); IkReal x621=((0.035)*cj2); IkReal x622=((0.42)*x614); IkReal x623=((1.0)*x615); IkReal x624=((0.91)*x615); IkReal x625=(cj2*x615); evalcond[0]=((((-1.0)*x621))+(((-0.025)*x614))+((x614*x618))+((x614*x616))+x619+(((-1.0)*x615*x620))); evalcond[1]=((0.455)+(((0.025)*x615))+(((-1.0)*x614*x620))+x617+(((0.42)*cj2))+(((-1.0)*x618*x623))+(((-1.0)*x616*x623))); evalcond[2]=((((0.455)*x614))+(((-1.0)*x620))+((x614*x617))+((x615*x619))+(((-1.0)*x615*x621))+((cj2*x622))); evalcond[3]=((-0.030025)+(((-0.02275)*x615))+((x616*x624))+((x618*x624))+(((-1.0)*pp))+(((0.05)*x618))+(((0.05)*x616))+(((0.91)*pz*x614))); evalcond[4]=((0.025)+(((0.42)*x625))+(((-1.0)*x614*x619))+((x614*x621))+(((0.455)*x615))+(((-1.0)*x616))+(((-1.0)*x618))+((x615*x617))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } rotationfunction0(solutions); } } } } } else { { IkReal j1array[1], cj1array[1], sj1array[1]; bool j1valid[1]={false}; _nj1 = 1; IkReal x626=cj2*cj2; IkReal x627=(py*sj0); IkReal x628=((0.42)*sj2); IkReal x629=(cj0*px); IkReal x630=((0.035)*cj2); IkReal x631=(cj2*sj2); CheckValue<IkReal> x632 = IKatan2WithCheck(IkReal(((-0.1764)+(((0.175175)*x626))+(pz*pz)+(((0.0294)*x631)))),IkReal(((0.0147)+(((0.1911)*sj2))+((pz*x627))+((pz*x629))+(((0.175175)*x631))+(((-0.0294)*x626))+(((-0.015925)*cj2))+(((-0.025)*pz)))),IKFAST_ATAN2_MAGTHRESH); if(!x632.valid){ continue; } CheckValue<IkReal> x633=IKPowWithIntegerCheck(IKsign(((((-1.0)*x629*x630))+(((0.455)*pz))+((x628*x629))+(((-1.0)*x627*x630))+(((0.42)*cj2*pz))+(((-0.0105)*sj2))+(((0.035)*pz*sj2))+((x627*x628))+(((0.000875)*cj2)))),-1); if(!x633.valid){ continue; } j1array[0]=((-1.5707963267949)+(x632.value)+(((1.5707963267949)*(x633.value)))); sj1array[0]=IKsin(j1array[0]); cj1array[0]=IKcos(j1array[0]); if( j1array[0] > IKPI ) { j1array[0]-=IK2PI; } else if( j1array[0] < -IKPI ) { j1array[0]+=IK2PI; } j1valid[0] = true; for(int ij1 = 0; ij1 < 1; ++ij1) { if( !j1valid[ij1] ) { continue; } _ij1[0] = ij1; _ij1[1] = -1; for(int iij1 = ij1+1; iij1 < 1; ++iij1) { if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH ) { j1valid[iij1]=false; _ij1[1] = iij1; break; } } j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1]; { IkReal evalcond[5]; IkReal x634=IKsin(j1); IkReal x635=IKcos(j1); IkReal x636=(cj0*px); IkReal x637=((0.035)*sj2); IkReal x638=(py*sj0); IkReal x639=((0.42)*sj2); IkReal x640=((1.0)*pz); IkReal x641=((0.035)*cj2); IkReal x642=((0.42)*x634); IkReal x643=((1.0)*x635); IkReal x644=((0.91)*x635); IkReal x645=(cj2*x635); evalcond[0]=(((x634*x636))+((x634*x638))+(((-0.025)*x634))+(((-1.0)*x641))+(((-1.0)*x635*x640))+x639); evalcond[1]=((0.455)+(((0.025)*x635))+x637+(((-1.0)*x636*x643))+(((0.42)*cj2))+(((-1.0)*x634*x640))+(((-1.0)*x638*x643))); evalcond[2]=(((x634*x637))+((x635*x639))+(((-1.0)*x640))+(((-1.0)*x635*x641))+((cj2*x642))+(((0.455)*x634))); evalcond[3]=((-0.030025)+((x638*x644))+(((0.05)*x636))+(((0.05)*x638))+((x636*x644))+(((0.91)*pz*x634))+(((-1.0)*pp))+(((-0.02275)*x635))); evalcond[4]=((0.025)+((x635*x637))+(((-1.0)*x634*x639))+((x634*x641))+(((0.42)*x645))+(((0.455)*x635))+(((-1.0)*x638))+(((-1.0)*x636))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } rotationfunction0(solutions); } } } } } } } } } } } return solutions.GetNumSolutions()>0; } inline void rotationfunction0(IkSolutionListBase<IkReal>& solutions) { for(int rotationiter = 0; rotationiter < 1; ++rotationiter) { IkReal x103=((1.0)*cj0); IkReal x104=(r11*sj0); IkReal x105=(r10*sj0); IkReal x106=((1.0)*cj2); IkReal x107=(cj1*sj2); IkReal x108=(r12*sj0); IkReal x109=(((cj2*sj1))+x107); IkReal x110=((((-1.0)*cj1*x106))+((sj1*sj2))); IkReal x111=(sj0*x110); IkReal x112=(cj0*x109); IkReal x113=(cj0*x110); IkReal x114=((((-1.0)*x107))+(((-1.0)*sj1*x106))); new_r00=(((r20*x110))+((r00*x112))+((x105*x109))); new_r01=(((r21*x110))+((r01*x112))+((x104*x109))); new_r02=(((r22*x110))+((r02*x112))+((x108*x109))); new_r10=(((r00*sj0))+(((-1.0)*r10*x103))); new_r11=((((-1.0)*r11*x103))+((r01*sj0))); new_r12=((((-1.0)*r12*x103))+((r02*sj0))); new_r20=(((r20*x114))+((r00*x113))+((x105*x110))); new_r21=(((r21*x114))+((r01*x113))+((x104*x110))); new_r22=(((r22*x114))+((r02*x113))+((x108*x110))); { IkReal j4array[2], cj4array[2], sj4array[2]; bool j4valid[2]={false}; _nj4 = 2; cj4array[0]=new_r22; if( cj4array[0] >= -1-IKFAST_SINCOS_THRESH && cj4array[0] <= 1+IKFAST_SINCOS_THRESH ) { j4valid[0] = j4valid[1] = true; j4array[0] = IKacos(cj4array[0]); sj4array[0] = IKsin(j4array[0]); cj4array[1] = cj4array[0]; j4array[1] = -j4array[0]; sj4array[1] = -sj4array[0]; } else if( isnan(cj4array[0]) ) { // probably any value will work j4valid[0] = true; cj4array[0] = 1; sj4array[0] = 0; j4array[0] = 0; } for(int ij4 = 0; ij4 < 2; ++ij4) { if( !j4valid[ij4] ) { continue; } _ij4[0] = ij4; _ij4[1] = -1; for(int iij4 = ij4+1; iij4 < 2; ++iij4) { if( j4valid[iij4] && IKabs(cj4array[ij4]-cj4array[iij4]) < IKFAST_SOLUTION_THRESH && IKabs(sj4array[ij4]-sj4array[iij4]) < IKFAST_SOLUTION_THRESH ) { j4valid[iij4]=false; _ij4[1] = iij4; break; } } j4 = j4array[ij4]; cj4 = cj4array[ij4]; sj4 = sj4array[ij4]; { IkReal j3eval[3]; j3eval[0]=sj4; j3eval[1]=IKsign(sj4); j3eval[2]=((IKabs(new_r12))+(IKabs(new_r02))); if( IKabs(j3eval[0]) < 0.0000010000000000 || IKabs(j3eval[1]) < 0.0000010000000000 || IKabs(j3eval[2]) < 0.0000010000000000 ) { { IkReal j5eval[3]; j5eval[0]=sj4; j5eval[1]=IKsign(sj4); j5eval[2]=((IKabs(new_r20))+(IKabs(new_r21))); if( IKabs(j5eval[0]) < 0.0000010000000000 || IKabs(j5eval[1]) < 0.0000010000000000 || IKabs(j5eval[2]) < 0.0000010000000000 ) { { IkReal j3eval[2]; j3eval[0]=new_r12; j3eval[1]=sj4; if( IKabs(j3eval[0]) < 0.0000010000000000 || IKabs(j3eval[1]) < 0.0000010000000000 ) { { IkReal evalcond[5]; bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(j4))), 6.28318530717959))); evalcond[1]=new_r20; evalcond[2]=new_r02; evalcond[3]=new_r12; evalcond[4]=new_r21; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 && IKabs(evalcond[2]) < 0.0000050000000000 && IKabs(evalcond[3]) < 0.0000050000000000 && IKabs(evalcond[4]) < 0.0000050000000000 ) { bgotonextstatement=false; IkReal j5mul = 1; j5=0; j3mul=-1.0; if( IKabs(((-1.0)*new_r01)) < IKFAST_ATAN2_MAGTHRESH && IKabs(new_r00) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((-1.0)*new_r01))+IKsqr(new_r00)-1) <= IKFAST_SINCOS_THRESH ) continue; j3=IKatan2(((-1.0)*new_r01), new_r00); { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].fmul = j3mul; vinfos[3].freeind = 0; vinfos[3].maxsolutions = 0; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].fmul = j5mul; vinfos[5].freeind = 0; vinfos[5].maxsolutions = 0; std::vector<int> vfree(1); vfree[0] = 5; solutions.AddSolution(vinfos,vfree); } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-3.14159265358979)+j4)))), 6.28318530717959))); evalcond[1]=new_r20; evalcond[2]=new_r02; evalcond[3]=new_r12; evalcond[4]=new_r21; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 && IKabs(evalcond[2]) < 0.0000050000000000 && IKabs(evalcond[3]) < 0.0000050000000000 && IKabs(evalcond[4]) < 0.0000050000000000 ) { bgotonextstatement=false; IkReal j5mul = 1; j5=0; j3mul=1.0; if( IKabs(((-1.0)*new_r01)) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r00)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((-1.0)*new_r01))+IKsqr(((-1.0)*new_r00))-1) <= IKFAST_SINCOS_THRESH ) continue; j3=IKatan2(((-1.0)*new_r01), ((-1.0)*new_r00)); { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].fmul = j3mul; vinfos[3].freeind = 0; vinfos[3].maxsolutions = 0; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].fmul = j5mul; vinfos[5].freeind = 0; vinfos[5].maxsolutions = 0; std::vector<int> vfree(1); vfree[0] = 5; solutions.AddSolution(vinfos,vfree); } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((IKabs(new_r12))+(IKabs(new_r02))); if( IKabs(evalcond[0]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j3eval[1]; new_r02=0; new_r12=0; new_r20=0; new_r21=0; IkReal x115=new_r22*new_r22; IkReal x116=((16.0)*new_r10); IkReal x117=((16.0)*new_r01); IkReal x118=((16.0)*new_r22); IkReal x119=((8.0)*new_r11); IkReal x120=((8.0)*new_r00); IkReal x121=(x115*x116); IkReal x122=(x115*x117); j3eval[0]=((IKabs((((new_r11*x118))+(((16.0)*new_r00))+(((-32.0)*new_r00*x115)))))+(IKabs(((((-1.0)*x121))+x116)))+(IKabs(((((-1.0)*new_r22*x120))+((x115*x119)))))+(IKabs(((((-1.0)*x122))+x117)))+(IKabs(((((-1.0)*x116))+x121)))+(IKabs(((((-1.0)*x117))+x122)))+(IKabs((((new_r22*x119))+(((-1.0)*x120)))))+(IKabs(((((32.0)*new_r11))+(((-1.0)*new_r00*x118))+(((-16.0)*new_r11*x115)))))); if( IKabs(j3eval[0]) < 0.0000000100000000 ) { continue; // no branches [j3, j5] } else { IkReal op[4+1], zeror[4]; int numroots; IkReal j3evalpoly[1]; IkReal x123=new_r22*new_r22; IkReal x124=((16.0)*new_r10); IkReal x125=(new_r11*new_r22); IkReal x126=(x123*x124); IkReal x127=((((-8.0)*new_r00))+(((8.0)*x125))); op[0]=x127; op[1]=((((-1.0)*x126))+x124); op[2]=((((16.0)*x125))+(((16.0)*new_r00))+(((-32.0)*new_r00*x123))); op[3]=((((-1.0)*x124))+x126); op[4]=x127; polyroots4(op,zeror,numroots); IkReal j3array[4], cj3array[4], sj3array[4], tempj3array[1]; int numsolutions = 0; for(int ij3 = 0; ij3 < numroots; ++ij3) { IkReal htj3 = zeror[ij3]; tempj3array[0]=((2.0)*(atan(htj3))); for(int kj3 = 0; kj3 < 1; ++kj3) { j3array[numsolutions] = tempj3array[kj3]; if( j3array[numsolutions] > IKPI ) { j3array[numsolutions]-=IK2PI; } else if( j3array[numsolutions] < -IKPI ) { j3array[numsolutions]+=IK2PI; } sj3array[numsolutions] = IKsin(j3array[numsolutions]); cj3array[numsolutions] = IKcos(j3array[numsolutions]); numsolutions++; } } bool j3valid[4]={true,true,true,true}; _nj3 = 4; for(int ij3 = 0; ij3 < numsolutions; ++ij3) { if( !j3valid[ij3] ) { continue; } j3 = j3array[ij3]; cj3 = cj3array[ij3]; sj3 = sj3array[ij3]; htj3 = IKtan(j3/2); IkReal x128=new_r22*new_r22; IkReal x129=((16.0)*new_r01); IkReal x130=(new_r00*new_r22); IkReal x131=((8.0)*x130); IkReal x132=(new_r11*x128); IkReal x133=((8.0)*x132); IkReal x134=(x128*x129); j3evalpoly[0]=((((htj3*htj3*htj3*htj3)*((x133+(((-1.0)*x131))))))+(((htj3*htj3)*(((((32.0)*new_r11))+(((-16.0)*x130))+(((-16.0)*x132))))))+x133+(((-1.0)*x131))+(((htj3*htj3*htj3)*(((((-1.0)*x129))+x134))))+((htj3*((x129+(((-1.0)*x134))))))); if( IKabs(j3evalpoly[0]) > 0.0000001000000000 ) { continue; } _ij3[0] = ij3; _ij3[1] = -1; for(int iij3 = ij3+1; iij3 < numsolutions; ++iij3) { if( j3valid[iij3] && IKabs(cj3array[ij3]-cj3array[iij3]) < IKFAST_SOLUTION_THRESH && IKabs(sj3array[ij3]-sj3array[iij3]) < IKFAST_SOLUTION_THRESH ) { j3valid[iij3]=false; _ij3[1] = iij3; break; } } { IkReal j5eval[3]; new_r02=0; new_r12=0; new_r20=0; new_r21=0; IkReal x135=cj3*cj3; IkReal x136=(cj3*new_r22); IkReal x137=((-1.0)+(((-1.0)*x135*(new_r22*new_r22)))+x135); j5eval[0]=x137; j5eval[1]=((IKabs((((new_r01*sj3))+(((-1.0)*new_r00*x136)))))+(IKabs((((new_r01*x136))+((new_r00*sj3)))))); j5eval[2]=IKsign(x137); if( IKabs(j5eval[0]) < 0.0000010000000000 || IKabs(j5eval[1]) < 0.0000010000000000 || IKabs(j5eval[2]) < 0.0000010000000000 ) { { IkReal j5eval[1]; new_r02=0; new_r12=0; new_r20=0; new_r21=0; j5eval[0]=new_r22; if( IKabs(j5eval[0]) < 0.0000010000000000 ) { { IkReal j5eval[2]; new_r02=0; new_r12=0; new_r20=0; new_r21=0; IkReal x138=new_r22*new_r22; j5eval[0]=(((cj3*x138))+(((-1.0)*cj3))); j5eval[1]=((((-1.0)*sj3))+((sj3*x138))); if( IKabs(j5eval[0]) < 0.0000010000000000 || IKabs(j5eval[1]) < 0.0000010000000000 ) { { IkReal evalcond[1]; bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-1.5707963267949)+j3)))), 6.28318530717959))); if( IKabs(evalcond[0]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(((-1.0)*new_r00)) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r01)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((-1.0)*new_r00))+IKsqr(((-1.0)*new_r01))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((-1.0)*new_r00), ((-1.0)*new_r01)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[4]; IkReal x139=IKsin(j5); IkReal x140=IKcos(j5); evalcond[0]=x140; evalcond[1]=((-1.0)*x139); evalcond[2]=((((-1.0)*x139))+(((-1.0)*new_r00))); evalcond[3]=((((-1.0)*x140))+(((-1.0)*new_r01))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((1.5707963267949)+j3)))), 6.28318530717959))); if( IKabs(evalcond[0]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(new_r00) < IKFAST_ATAN2_MAGTHRESH && IKabs(new_r01) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(new_r00)+IKsqr(new_r01)-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(new_r00, new_r01); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[4]; IkReal x141=IKsin(j5); IkReal x142=IKcos(j5); evalcond[0]=x142; evalcond[1]=((-1.0)*x141); evalcond[2]=((((-1.0)*x141))+new_r00); evalcond[3]=((((-1.0)*x142))+new_r01); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(j3))), 6.28318530717959))); if( IKabs(evalcond[0]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(new_r10) < IKFAST_ATAN2_MAGTHRESH && IKabs(new_r11) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(new_r10)+IKsqr(new_r11)-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(new_r10, new_r11); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[4]; IkReal x143=IKsin(j5); IkReal x144=IKcos(j5); evalcond[0]=x144; evalcond[1]=((-1.0)*x143); evalcond[2]=((((-1.0)*x143))+new_r10); evalcond[3]=((((-1.0)*x144))+new_r11); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-3.14159265358979)+j3)))), 6.28318530717959))); if( IKabs(evalcond[0]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(((-1.0)*new_r10)) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r11)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((-1.0)*new_r10))+IKsqr(((-1.0)*new_r11))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((-1.0)*new_r10), ((-1.0)*new_r11)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[4]; IkReal x145=IKsin(j5); IkReal x146=IKcos(j5); evalcond[0]=x146; evalcond[1]=((-1.0)*x145); evalcond[2]=((((-1.0)*x145))+(((-1.0)*new_r10))); evalcond[3]=((((-1.0)*x146))+(((-1.0)*new_r11))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { CheckValue<IkReal> x147=IKPowWithIntegerCheck(((1.0)+(((-1.0)*(new_r22*new_r22)))),-1); if(!x147.valid){ continue; } if((x147.value) < -0.00001) continue; IkReal gconst6=((-1.0)*(IKsqrt(x147.value))); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-1.0)+(IKsign(sj3)))))+(IKabs((cj3+(((-1.0)*gconst6)))))), 6.28318530717959))); if( IKabs(evalcond[0]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5eval[1]; new_r02=0; new_r12=0; new_r20=0; new_r21=0; if((((1.0)+(((-1.0)*(gconst6*gconst6))))) < -0.00001) continue; sj3=IKsqrt(((1.0)+(((-1.0)*(gconst6*gconst6))))); cj3=gconst6; if( (gconst6) < -1-IKFAST_SINCOS_THRESH || (gconst6) > 1+IKFAST_SINCOS_THRESH ) continue; j3=IKacos(gconst6); CheckValue<IkReal> x148=IKPowWithIntegerCheck(((1.0)+(((-1.0)*(new_r22*new_r22)))),-1); if(!x148.valid){ continue; } if((x148.value) < -0.00001) continue; IkReal gconst6=((-1.0)*(IKsqrt(x148.value))); j5eval[0]=((IKabs(new_r11))+(IKabs(new_r10))); if( IKabs(j5eval[0]) < 0.0000010000000000 ) { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if((((1.0)+(((-1.0)*(gconst6*gconst6))))) < -0.00001) continue; CheckValue<IkReal> x149=IKPowWithIntegerCheck(gconst6,-1); if(!x149.valid){ continue; } if( IKabs((((gconst6*new_r10))+(((-1.0)*new_r00*(IKsqrt(((1.0)+(((-1.0)*(gconst6*gconst6)))))))))) < IKFAST_ATAN2_MAGTHRESH && IKabs((new_r11*(x149.value))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr((((gconst6*new_r10))+(((-1.0)*new_r00*(IKsqrt(((1.0)+(((-1.0)*(gconst6*gconst6))))))))))+IKsqr((new_r11*(x149.value)))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2((((gconst6*new_r10))+(((-1.0)*new_r00*(IKsqrt(((1.0)+(((-1.0)*(gconst6*gconst6))))))))), (new_r11*(x149.value))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x150=IKcos(j5); IkReal x151=IKsin(j5); IkReal x152=((1.0)*x151); IkReal x153=((1.0)*x150); if((((1.0)+(((-1.0)*(gconst6*gconst6))))) < -0.00001) continue; IkReal x154=IKsqrt(((1.0)+(((-1.0)*(gconst6*gconst6))))); IkReal x155=((1.0)*x154); evalcond[0]=x150; evalcond[1]=((-1.0)*x151); evalcond[2]=((((-1.0)*gconst6*x153))+new_r11); evalcond[3]=((((-1.0)*gconst6*x152))+new_r10); evalcond[4]=(((x150*x154))+new_r01); evalcond[5]=(((x151*x154))+new_r00); evalcond[6]=((((-1.0)*x152))+((gconst6*new_r10))+(((-1.0)*new_r00*x155))); evalcond[7]=((((-1.0)*x153))+((gconst6*new_r11))+(((-1.0)*new_r01*x155))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x156 = IKatan2WithCheck(IkReal(new_r10),IkReal(new_r11),IKFAST_ATAN2_MAGTHRESH); if(!x156.valid){ continue; } CheckValue<IkReal> x157=IKPowWithIntegerCheck(IKsign(gconst6),-1); if(!x157.valid){ continue; } j5array[0]=((-1.5707963267949)+(x156.value)+(((1.5707963267949)*(x157.value)))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x158=IKcos(j5); IkReal x159=IKsin(j5); IkReal x160=((1.0)*x159); IkReal x161=((1.0)*x158); if((((1.0)+(((-1.0)*(gconst6*gconst6))))) < -0.00001) continue; IkReal x162=IKsqrt(((1.0)+(((-1.0)*(gconst6*gconst6))))); IkReal x163=((1.0)*x162); evalcond[0]=x158; evalcond[1]=((-1.0)*x159); evalcond[2]=((((-1.0)*gconst6*x161))+new_r11); evalcond[3]=((((-1.0)*gconst6*x160))+new_r10); evalcond[4]=(new_r01+((x158*x162))); evalcond[5]=(new_r00+((x159*x162))); evalcond[6]=((((-1.0)*new_r00*x163))+(((-1.0)*x160))+((gconst6*new_r10))); evalcond[7]=((((-1.0)*x161))+((gconst6*new_r11))+(((-1.0)*new_r01*x163))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { CheckValue<IkReal> x164=IKPowWithIntegerCheck(((1.0)+(((-1.0)*(new_r22*new_r22)))),-1); if(!x164.valid){ continue; } if((x164.value) < -0.00001) continue; IkReal gconst6=((-1.0)*(IKsqrt(x164.value))); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs((cj3+(((-1.0)*gconst6)))))+(IKabs(((1.0)+(IKsign(sj3)))))), 6.28318530717959))); if( IKabs(evalcond[0]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5eval[1]; new_r02=0; new_r12=0; new_r20=0; new_r21=0; if((((1.0)+(((-1.0)*(gconst6*gconst6))))) < -0.00001) continue; sj3=((-1.0)*(IKsqrt(((1.0)+(((-1.0)*(gconst6*gconst6))))))); cj3=gconst6; if( (gconst6) < -1-IKFAST_SINCOS_THRESH || (gconst6) > 1+IKFAST_SINCOS_THRESH ) continue; j3=((-1.0)*(IKacos(gconst6))); CheckValue<IkReal> x165=IKPowWithIntegerCheck(((1.0)+(((-1.0)*(new_r22*new_r22)))),-1); if(!x165.valid){ continue; } if((x165.value) < -0.00001) continue; IkReal gconst6=((-1.0)*(IKsqrt(x165.value))); j5eval[0]=((IKabs(new_r11))+(IKabs(new_r10))); if( IKabs(j5eval[0]) < 0.0000010000000000 ) { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if((((1.0)+(((-1.0)*(gconst6*gconst6))))) < -0.00001) continue; CheckValue<IkReal> x166=IKPowWithIntegerCheck(gconst6,-1); if(!x166.valid){ continue; } if( IKabs((((new_r00*(IKsqrt(((1.0)+(((-1.0)*(gconst6*gconst6))))))))+((gconst6*new_r10)))) < IKFAST_ATAN2_MAGTHRESH && IKabs((new_r11*(x166.value))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr((((new_r00*(IKsqrt(((1.0)+(((-1.0)*(gconst6*gconst6))))))))+((gconst6*new_r10))))+IKsqr((new_r11*(x166.value)))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2((((new_r00*(IKsqrt(((1.0)+(((-1.0)*(gconst6*gconst6))))))))+((gconst6*new_r10))), (new_r11*(x166.value))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x167=IKcos(j5); IkReal x168=IKsin(j5); IkReal x169=((1.0)*x167); IkReal x170=((1.0)*x168); if((((1.0)+(((-1.0)*(gconst6*gconst6))))) < -0.00001) continue; IkReal x171=IKsqrt(((1.0)+(((-1.0)*(gconst6*gconst6))))); IkReal x172=((1.0)*x171); evalcond[0]=x167; evalcond[1]=((-1.0)*x168); evalcond[2]=((((-1.0)*gconst6*x169))+new_r11); evalcond[3]=((((-1.0)*gconst6*x170))+new_r10); evalcond[4]=(new_r01+(((-1.0)*x169*x171))); evalcond[5]=((((-1.0)*x170*x171))+new_r00); evalcond[6]=(((new_r00*x171))+(((-1.0)*x170))+((gconst6*new_r10))); evalcond[7]=(((new_r01*x171))+(((-1.0)*x169))+((gconst6*new_r11))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x173 = IKatan2WithCheck(IkReal(new_r10),IkReal(new_r11),IKFAST_ATAN2_MAGTHRESH); if(!x173.valid){ continue; } CheckValue<IkReal> x174=IKPowWithIntegerCheck(IKsign(gconst6),-1); if(!x174.valid){ continue; } j5array[0]=((-1.5707963267949)+(x173.value)+(((1.5707963267949)*(x174.value)))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x175=IKcos(j5); IkReal x176=IKsin(j5); IkReal x177=((1.0)*x175); IkReal x178=((1.0)*x176); if((((1.0)+(((-1.0)*(gconst6*gconst6))))) < -0.00001) continue; IkReal x179=IKsqrt(((1.0)+(((-1.0)*(gconst6*gconst6))))); IkReal x180=((1.0)*x179); evalcond[0]=x175; evalcond[1]=((-1.0)*x176); evalcond[2]=((((-1.0)*gconst6*x177))+new_r11); evalcond[3]=((((-1.0)*gconst6*x178))+new_r10); evalcond[4]=((((-1.0)*x177*x179))+new_r01); evalcond[5]=((((-1.0)*x178*x179))+new_r00); evalcond[6]=(((new_r00*x179))+(((-1.0)*x178))+((gconst6*new_r10))); evalcond[7]=(((new_r01*x179))+(((-1.0)*x177))+((gconst6*new_r11))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { CheckValue<IkReal> x181=IKPowWithIntegerCheck(((1.0)+(((-1.0)*(new_r22*new_r22)))),-1); if(!x181.valid){ continue; } if((x181.value) < -0.00001) continue; IkReal gconst7=IKsqrt(x181.value); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-1.0)+(IKsign(sj3)))))+(IKabs((cj3+(((-1.0)*gconst7)))))), 6.28318530717959))); if( IKabs(evalcond[0]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5eval[1]; new_r02=0; new_r12=0; new_r20=0; new_r21=0; if((((1.0)+(((-1.0)*(gconst7*gconst7))))) < -0.00001) continue; sj3=IKsqrt(((1.0)+(((-1.0)*(gconst7*gconst7))))); cj3=gconst7; if( (gconst7) < -1-IKFAST_SINCOS_THRESH || (gconst7) > 1+IKFAST_SINCOS_THRESH ) continue; j3=IKacos(gconst7); CheckValue<IkReal> x182=IKPowWithIntegerCheck(((1.0)+(((-1.0)*(new_r22*new_r22)))),-1); if(!x182.valid){ continue; } if((x182.value) < -0.00001) continue; IkReal gconst7=IKsqrt(x182.value); j5eval[0]=((IKabs(new_r11))+(IKabs(new_r10))); if( IKabs(j5eval[0]) < 0.0000010000000000 ) { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if((((1.0)+(((-1.0)*(gconst7*gconst7))))) < -0.00001) continue; CheckValue<IkReal> x183=IKPowWithIntegerCheck(gconst7,-1); if(!x183.valid){ continue; } if( IKabs(((((-1.0)*new_r00*(IKsqrt(((1.0)+(((-1.0)*(gconst7*gconst7))))))))+((gconst7*new_r10)))) < IKFAST_ATAN2_MAGTHRESH && IKabs((new_r11*(x183.value))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((((-1.0)*new_r00*(IKsqrt(((1.0)+(((-1.0)*(gconst7*gconst7))))))))+((gconst7*new_r10))))+IKsqr((new_r11*(x183.value)))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((((-1.0)*new_r00*(IKsqrt(((1.0)+(((-1.0)*(gconst7*gconst7))))))))+((gconst7*new_r10))), (new_r11*(x183.value))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x184=IKcos(j5); IkReal x185=IKsin(j5); IkReal x186=((1.0)*x185); IkReal x187=((1.0)*x184); if((((1.0)+(((-1.0)*(gconst7*gconst7))))) < -0.00001) continue; IkReal x188=IKsqrt(((1.0)+(((-1.0)*(gconst7*gconst7))))); IkReal x189=((1.0)*x188); evalcond[0]=x184; evalcond[1]=((-1.0)*x185); evalcond[2]=(new_r11+(((-1.0)*gconst7*x187))); evalcond[3]=(new_r10+(((-1.0)*gconst7*x186))); evalcond[4]=(((x184*x188))+new_r01); evalcond[5]=(((x185*x188))+new_r00); evalcond[6]=((((-1.0)*x186))+(((-1.0)*new_r00*x189))+((gconst7*new_r10))); evalcond[7]=((((-1.0)*x187))+(((-1.0)*new_r01*x189))+((gconst7*new_r11))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x190=IKPowWithIntegerCheck(IKsign(gconst7),-1); if(!x190.valid){ continue; } CheckValue<IkReal> x191 = IKatan2WithCheck(IkReal(new_r10),IkReal(new_r11),IKFAST_ATAN2_MAGTHRESH); if(!x191.valid){ continue; } j5array[0]=((-1.5707963267949)+(((1.5707963267949)*(x190.value)))+(x191.value)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x192=IKcos(j5); IkReal x193=IKsin(j5); IkReal x194=((1.0)*x193); IkReal x195=((1.0)*x192); if((((1.0)+(((-1.0)*(gconst7*gconst7))))) < -0.00001) continue; IkReal x196=IKsqrt(((1.0)+(((-1.0)*(gconst7*gconst7))))); IkReal x197=((1.0)*x196); evalcond[0]=x192; evalcond[1]=((-1.0)*x193); evalcond[2]=(new_r11+(((-1.0)*gconst7*x195))); evalcond[3]=(new_r10+(((-1.0)*gconst7*x194))); evalcond[4]=(((x192*x196))+new_r01); evalcond[5]=(((x193*x196))+new_r00); evalcond[6]=((((-1.0)*x194))+(((-1.0)*new_r00*x197))+((gconst7*new_r10))); evalcond[7]=((((-1.0)*x195))+(((-1.0)*new_r01*x197))+((gconst7*new_r11))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { CheckValue<IkReal> x198=IKPowWithIntegerCheck(((1.0)+(((-1.0)*(new_r22*new_r22)))),-1); if(!x198.valid){ continue; } if((x198.value) < -0.00001) continue; IkReal gconst7=IKsqrt(x198.value); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs((cj3+(((-1.0)*gconst7)))))+(IKabs(((1.0)+(IKsign(sj3)))))), 6.28318530717959))); if( IKabs(evalcond[0]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5eval[1]; new_r02=0; new_r12=0; new_r20=0; new_r21=0; if((((1.0)+(((-1.0)*(gconst7*gconst7))))) < -0.00001) continue; sj3=((-1.0)*(IKsqrt(((1.0)+(((-1.0)*(gconst7*gconst7))))))); cj3=gconst7; if( (gconst7) < -1-IKFAST_SINCOS_THRESH || (gconst7) > 1+IKFAST_SINCOS_THRESH ) continue; j3=((-1.0)*(IKacos(gconst7))); CheckValue<IkReal> x199=IKPowWithIntegerCheck(((1.0)+(((-1.0)*(new_r22*new_r22)))),-1); if(!x199.valid){ continue; } if((x199.value) < -0.00001) continue; IkReal gconst7=IKsqrt(x199.value); j5eval[0]=((IKabs(new_r11))+(IKabs(new_r10))); if( IKabs(j5eval[0]) < 0.0000010000000000 ) { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if((((1.0)+(((-1.0)*(gconst7*gconst7))))) < -0.00001) continue; CheckValue<IkReal> x200=IKPowWithIntegerCheck(gconst7,-1); if(!x200.valid){ continue; } if( IKabs((((gconst7*new_r10))+((new_r00*(IKsqrt(((1.0)+(((-1.0)*(gconst7*gconst7)))))))))) < IKFAST_ATAN2_MAGTHRESH && IKabs((new_r11*(x200.value))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr((((gconst7*new_r10))+((new_r00*(IKsqrt(((1.0)+(((-1.0)*(gconst7*gconst7))))))))))+IKsqr((new_r11*(x200.value)))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2((((gconst7*new_r10))+((new_r00*(IKsqrt(((1.0)+(((-1.0)*(gconst7*gconst7))))))))), (new_r11*(x200.value))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x201=IKcos(j5); IkReal x202=IKsin(j5); IkReal x203=((1.0)*x202); IkReal x204=((1.0)*x201); if((((1.0)+(((-1.0)*(gconst7*gconst7))))) < -0.00001) continue; IkReal x205=IKsqrt(((1.0)+(((-1.0)*(gconst7*gconst7))))); evalcond[0]=x201; evalcond[1]=((-1.0)*x202); evalcond[2]=(new_r11+(((-1.0)*gconst7*x204))); evalcond[3]=(new_r10+(((-1.0)*gconst7*x203))); evalcond[4]=((((-1.0)*x204*x205))+new_r01); evalcond[5]=((((-1.0)*x203*x205))+new_r00); evalcond[6]=(((new_r00*x205))+(((-1.0)*x203))+((gconst7*new_r10))); evalcond[7]=(((new_r01*x205))+(((-1.0)*x204))+((gconst7*new_r11))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x206=IKPowWithIntegerCheck(IKsign(gconst7),-1); if(!x206.valid){ continue; } CheckValue<IkReal> x207 = IKatan2WithCheck(IkReal(new_r10),IkReal(new_r11),IKFAST_ATAN2_MAGTHRESH); if(!x207.valid){ continue; } j5array[0]=((-1.5707963267949)+(((1.5707963267949)*(x206.value)))+(x207.value)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x208=IKcos(j5); IkReal x209=IKsin(j5); IkReal x210=((1.0)*x209); IkReal x211=((1.0)*x208); if((((1.0)+(((-1.0)*(gconst7*gconst7))))) < -0.00001) continue; IkReal x212=IKsqrt(((1.0)+(((-1.0)*(gconst7*gconst7))))); evalcond[0]=x208; evalcond[1]=((-1.0)*x209); evalcond[2]=((((-1.0)*gconst7*x211))+new_r11); evalcond[3]=((((-1.0)*gconst7*x210))+new_r10); evalcond[4]=((((-1.0)*x211*x212))+new_r01); evalcond[5]=((((-1.0)*x210*x212))+new_r00); evalcond[6]=(((new_r00*x212))+(((-1.0)*x210))+((gconst7*new_r10))); evalcond[7]=(((new_r01*x212))+(((-1.0)*x211))+((gconst7*new_r11))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j5] } } while(0); if( bgotonextstatement ) { } } } } } } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; IkReal x213=new_r22*new_r22; CheckValue<IkReal> x214=IKPowWithIntegerCheck((((cj3*x213))+(((-1.0)*cj3))),-1); if(!x214.valid){ continue; } CheckValue<IkReal> x215=IKPowWithIntegerCheck(((((-1.0)*sj3))+((sj3*x213))),-1); if(!x215.valid){ continue; } if( IKabs(((x214.value)*(((((-1.0)*new_r01*new_r22))+(((-1.0)*new_r10)))))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((x215.value)*((((new_r10*new_r22))+new_r01)))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((x214.value)*(((((-1.0)*new_r01*new_r22))+(((-1.0)*new_r10))))))+IKsqr(((x215.value)*((((new_r10*new_r22))+new_r01))))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((x214.value)*(((((-1.0)*new_r01*new_r22))+(((-1.0)*new_r10))))), ((x215.value)*((((new_r10*new_r22))+new_r01)))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[10]; IkReal x216=IKsin(j5); IkReal x217=IKcos(j5); IkReal x218=((1.0)*sj3); IkReal x219=((1.0)*x216); IkReal x220=((1.0)*cj3*new_r22); IkReal x221=(sj3*x216); IkReal x222=((1.0)*x217); IkReal x223=(new_r22*x216); evalcond[0]=(((new_r11*sj3))+x223+((cj3*new_r01))); evalcond[1]=(((cj3*new_r10))+(((-1.0)*x219))+(((-1.0)*new_r00*x218))); evalcond[2]=((((-1.0)*new_r01*x218))+((cj3*new_r11))+(((-1.0)*x222))); evalcond[3]=(((cj3*x223))+((sj3*x217))+new_r01); evalcond[4]=(((new_r10*sj3))+((cj3*new_r00))+(((-1.0)*new_r22*x222))); evalcond[5]=(x221+(((-1.0)*x217*x220))+new_r00); evalcond[6]=(((new_r22*x221))+(((-1.0)*cj3*x222))+new_r11); evalcond[7]=(x217+(((-1.0)*new_r00*x220))+(((-1.0)*new_r10*new_r22*x218))); evalcond[8]=((((-1.0)*cj3*x219))+new_r10+(((-1.0)*new_r22*x217*x218))); evalcond[9]=((((-1.0)*new_r01*x220))+(((-1.0)*new_r11*new_r22*x218))+(((-1.0)*x219))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[8]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[9]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; IkReal x224=((1.0)*new_r01); CheckValue<IkReal> x225=IKPowWithIntegerCheck(new_r22,-1); if(!x225.valid){ continue; } if( IKabs(((x225.value)*(((((-1.0)*cj3*x224))+(((-1.0)*new_r11*sj3)))))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((((-1.0)*sj3*x224))+((cj3*new_r11)))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((x225.value)*(((((-1.0)*cj3*x224))+(((-1.0)*new_r11*sj3))))))+IKsqr(((((-1.0)*sj3*x224))+((cj3*new_r11))))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((x225.value)*(((((-1.0)*cj3*x224))+(((-1.0)*new_r11*sj3))))), ((((-1.0)*sj3*x224))+((cj3*new_r11)))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[10]; IkReal x226=IKsin(j5); IkReal x227=IKcos(j5); IkReal x228=((1.0)*sj3); IkReal x229=((1.0)*x226); IkReal x230=((1.0)*cj3*new_r22); IkReal x231=(sj3*x226); IkReal x232=((1.0)*x227); IkReal x233=(new_r22*x226); evalcond[0]=(((new_r11*sj3))+x233+((cj3*new_r01))); evalcond[1]=(((cj3*new_r10))+(((-1.0)*x229))+(((-1.0)*new_r00*x228))); evalcond[2]=((((-1.0)*new_r01*x228))+(((-1.0)*x232))+((cj3*new_r11))); evalcond[3]=(((cj3*x233))+((sj3*x227))+new_r01); evalcond[4]=((((-1.0)*new_r22*x232))+((new_r10*sj3))+((cj3*new_r00))); evalcond[5]=((((-1.0)*x227*x230))+x231+new_r00); evalcond[6]=(((new_r22*x231))+(((-1.0)*cj3*x232))+new_r11); evalcond[7]=(x227+(((-1.0)*new_r10*new_r22*x228))+(((-1.0)*new_r00*x230))); evalcond[8]=((((-1.0)*new_r22*x227*x228))+(((-1.0)*cj3*x229))+new_r10); evalcond[9]=((((-1.0)*new_r11*new_r22*x228))+(((-1.0)*new_r01*x230))+(((-1.0)*x229))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[8]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[9]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; IkReal x234=cj3*cj3; IkReal x235=(cj3*new_r22); CheckValue<IkReal> x236 = IKatan2WithCheck(IkReal((((new_r01*x235))+((new_r00*sj3)))),IkReal(((((-1.0)*new_r00*x235))+((new_r01*sj3)))),IKFAST_ATAN2_MAGTHRESH); if(!x236.valid){ continue; } CheckValue<IkReal> x237=IKPowWithIntegerCheck(IKsign(((-1.0)+(((-1.0)*x234*(new_r22*new_r22)))+x234)),-1); if(!x237.valid){ continue; } j5array[0]=((-1.5707963267949)+(x236.value)+(((1.5707963267949)*(x237.value)))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[10]; IkReal x238=IKsin(j5); IkReal x239=IKcos(j5); IkReal x240=((1.0)*sj3); IkReal x241=((1.0)*x238); IkReal x242=((1.0)*cj3*new_r22); IkReal x243=(sj3*x238); IkReal x244=((1.0)*x239); IkReal x245=(new_r22*x238); evalcond[0]=(((new_r11*sj3))+x245+((cj3*new_r01))); evalcond[1]=((((-1.0)*new_r00*x240))+((cj3*new_r10))+(((-1.0)*x241))); evalcond[2]=((((-1.0)*new_r01*x240))+((cj3*new_r11))+(((-1.0)*x244))); evalcond[3]=(new_r01+((cj3*x245))+((sj3*x239))); evalcond[4]=(((new_r10*sj3))+(((-1.0)*new_r22*x244))+((cj3*new_r00))); evalcond[5]=(x243+new_r00+(((-1.0)*x239*x242))); evalcond[6]=(((new_r22*x243))+(((-1.0)*cj3*x244))+new_r11); evalcond[7]=((((-1.0)*new_r10*new_r22*x240))+(((-1.0)*new_r00*x242))+x239); evalcond[8]=((((-1.0)*cj3*x241))+(((-1.0)*new_r22*x239*x240))+new_r10); evalcond[9]=((((-1.0)*new_r11*new_r22*x240))+(((-1.0)*new_r01*x242))+(((-1.0)*x241))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[8]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[9]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j3, j5] } } while(0); if( bgotonextstatement ) { } } } } } } else { { IkReal j3array[1], cj3array[1], sj3array[1]; bool j3valid[1]={false}; _nj3 = 1; CheckValue<IkReal> x247=IKPowWithIntegerCheck(sj4,-1); if(!x247.valid){ continue; } IkReal x246=x247.value; CheckValue<IkReal> x248=IKPowWithIntegerCheck(new_r12,-1); if(!x248.valid){ continue; } if( IKabs((x246*(x248.value)*(((1.0)+(((-1.0)*(cj4*cj4)))+(((-1.0)*(new_r02*new_r02))))))) < IKFAST_ATAN2_MAGTHRESH && IKabs((new_r02*x246)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr((x246*(x248.value)*(((1.0)+(((-1.0)*(cj4*cj4)))+(((-1.0)*(new_r02*new_r02)))))))+IKsqr((new_r02*x246))-1) <= IKFAST_SINCOS_THRESH ) continue; j3array[0]=IKatan2((x246*(x248.value)*(((1.0)+(((-1.0)*(cj4*cj4)))+(((-1.0)*(new_r02*new_r02)))))), (new_r02*x246)); sj3array[0]=IKsin(j3array[0]); cj3array[0]=IKcos(j3array[0]); if( j3array[0] > IKPI ) { j3array[0]-=IK2PI; } else if( j3array[0] < -IKPI ) { j3array[0]+=IK2PI; } j3valid[0] = true; for(int ij3 = 0; ij3 < 1; ++ij3) { if( !j3valid[ij3] ) { continue; } _ij3[0] = ij3; _ij3[1] = -1; for(int iij3 = ij3+1; iij3 < 1; ++iij3) { if( j3valid[iij3] && IKabs(cj3array[ij3]-cj3array[iij3]) < IKFAST_SOLUTION_THRESH && IKabs(sj3array[ij3]-sj3array[iij3]) < IKFAST_SOLUTION_THRESH ) { j3valid[iij3]=false; _ij3[1] = iij3; break; } } j3 = j3array[ij3]; cj3 = cj3array[ij3]; sj3 = sj3array[ij3]; { IkReal evalcond[8]; IkReal x249=IKcos(j3); IkReal x250=IKsin(j3); IkReal x251=((1.0)*sj4); IkReal x252=((1.0)*cj4); IkReal x253=(new_r12*x250); IkReal x254=(new_r02*x249); evalcond[0]=((((-1.0)*x249*x251))+new_r02); evalcond[1]=((((-1.0)*x250*x251))+new_r12); evalcond[2]=(((new_r12*x249))+(((-1.0)*new_r02*x250))); evalcond[3]=(x254+x253+(((-1.0)*x251))); evalcond[4]=((((-1.0)*x252*x254))+(((-1.0)*x252*x253))+((new_r22*sj4))); evalcond[5]=((((-1.0)*new_r10*x250*x251))+(((-1.0)*new_r00*x249*x251))+(((-1.0)*new_r20*x252))); evalcond[6]=((((-1.0)*new_r21*x252))+(((-1.0)*new_r01*x249*x251))+(((-1.0)*new_r11*x250*x251))); evalcond[7]=((1.0)+(((-1.0)*x251*x253))+(((-1.0)*x251*x254))+(((-1.0)*new_r22*x252))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { IkReal j5eval[3]; j5eval[0]=sj4; j5eval[1]=IKsign(sj4); j5eval[2]=((IKabs(new_r20))+(IKabs(new_r21))); if( IKabs(j5eval[0]) < 0.0000010000000000 || IKabs(j5eval[1]) < 0.0000010000000000 || IKabs(j5eval[2]) < 0.0000010000000000 ) { { IkReal j5eval[2]; j5eval[0]=sj3; j5eval[1]=sj4; if( IKabs(j5eval[0]) < 0.0000010000000000 || IKabs(j5eval[1]) < 0.0000010000000000 ) { { IkReal j5eval[3]; j5eval[0]=cj3; j5eval[1]=cj4; j5eval[2]=sj4; if( IKabs(j5eval[0]) < 0.0000010000000000 || IKabs(j5eval[1]) < 0.0000010000000000 || IKabs(j5eval[2]) < 0.0000010000000000 ) { { IkReal evalcond[5]; bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-1.5707963267949)+j3)))), 6.28318530717959))); evalcond[1]=new_r02; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5eval[3]; sj3=1.0; cj3=0; j3=1.5707963267949; j5eval[0]=sj4; j5eval[1]=IKsign(sj4); j5eval[2]=((IKabs(new_r20))+(IKabs(new_r21))); if( IKabs(j5eval[0]) < 0.0000010000000000 || IKabs(j5eval[1]) < 0.0000010000000000 || IKabs(j5eval[2]) < 0.0000010000000000 ) { { IkReal j5eval[3]; sj3=1.0; cj3=0; j3=1.5707963267949; j5eval[0]=cj4; j5eval[1]=IKsign(cj4); j5eval[2]=((IKabs(new_r11))+(IKabs(new_r10))); if( IKabs(j5eval[0]) < 0.0000010000000000 || IKabs(j5eval[1]) < 0.0000010000000000 || IKabs(j5eval[2]) < 0.0000010000000000 ) { { IkReal j5eval[1]; sj3=1.0; cj3=0; j3=1.5707963267949; j5eval[0]=sj4; if( IKabs(j5eval[0]) < 0.0000010000000000 ) { { IkReal evalcond[4]; bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(j4))), 6.28318530717959))); evalcond[1]=new_r20; evalcond[2]=new_r12; evalcond[3]=new_r21; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 && IKabs(evalcond[2]) < 0.0000050000000000 && IKabs(evalcond[3]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(((-1.0)*new_r11)) < IKFAST_ATAN2_MAGTHRESH && IKabs(new_r10) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((-1.0)*new_r11))+IKsqr(new_r10)-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((-1.0)*new_r11), new_r10); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[4]; IkReal x255=IKsin(j5); IkReal x256=((1.0)*(IKcos(j5))); evalcond[0]=(x255+new_r11); evalcond[1]=(new_r10+(((-1.0)*x256))); evalcond[2]=((((-1.0)*new_r00))+(((-1.0)*x255))); evalcond[3]=((((-1.0)*new_r01))+(((-1.0)*x256))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-3.14159265358979)+j4)))), 6.28318530717959))); evalcond[1]=new_r20; evalcond[2]=new_r12; evalcond[3]=new_r21; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 && IKabs(evalcond[2]) < 0.0000050000000000 && IKabs(evalcond[3]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(new_r11) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r10)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(new_r11)+IKsqr(((-1.0)*new_r10))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(new_r11, ((-1.0)*new_r10)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[4]; IkReal x257=IKcos(j5); IkReal x258=((1.0)*(IKsin(j5))); evalcond[0]=(x257+new_r10); evalcond[1]=(new_r11+(((-1.0)*x258))); evalcond[2]=((((-1.0)*new_r00))+(((-1.0)*x258))); evalcond[3]=((((-1.0)*new_r01))+(((-1.0)*x257))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-1.5707963267949)+j4)))), 6.28318530717959))); evalcond[1]=new_r22; evalcond[2]=new_r11; evalcond[3]=new_r10; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 && IKabs(evalcond[2]) < 0.0000050000000000 && IKabs(evalcond[3]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(new_r21) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r20)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(new_r21)+IKsqr(((-1.0)*new_r20))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(new_r21, ((-1.0)*new_r20)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[4]; IkReal x259=IKcos(j5); IkReal x260=((1.0)*(IKsin(j5))); evalcond[0]=(x259+new_r20); evalcond[1]=(new_r21+(((-1.0)*x260))); evalcond[2]=((((-1.0)*new_r00))+(((-1.0)*x260))); evalcond[3]=((((-1.0)*new_r01))+(((-1.0)*x259))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((1.5707963267949)+j4)))), 6.28318530717959))); evalcond[1]=new_r22; evalcond[2]=new_r11; evalcond[3]=new_r10; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 && IKabs(evalcond[2]) < 0.0000050000000000 && IKabs(evalcond[3]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(((-1.0)*new_r21)) < IKFAST_ATAN2_MAGTHRESH && IKabs(new_r20) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((-1.0)*new_r21))+IKsqr(new_r20)-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((-1.0)*new_r21), new_r20); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[4]; IkReal x261=IKsin(j5); IkReal x262=((1.0)*(IKcos(j5))); evalcond[0]=(x261+new_r21); evalcond[1]=(new_r20+(((-1.0)*x262))); evalcond[2]=((((-1.0)*x261))+(((-1.0)*new_r00))); evalcond[3]=((((-1.0)*new_r01))+(((-1.0)*x262))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((IKabs(new_r20))+(IKabs(new_r21))); if( IKabs(evalcond[0]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(((-1.0)*new_r00)) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r01)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((-1.0)*new_r00))+IKsqr(((-1.0)*new_r01))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((-1.0)*new_r00), ((-1.0)*new_r01)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[6]; IkReal x263=IKsin(j5); IkReal x264=IKcos(j5); evalcond[0]=x264; evalcond[1]=(new_r22*x263); evalcond[2]=((-1.0)*x263); evalcond[3]=((-1.0)*new_r22*x264); evalcond[4]=((((-1.0)*x263))+(((-1.0)*new_r00))); evalcond[5]=((((-1.0)*x264))+(((-1.0)*new_r01))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j5] } } while(0); if( bgotonextstatement ) { } } } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x265=IKPowWithIntegerCheck(sj4,-1); if(!x265.valid){ continue; } if( IKabs(((-1.0)*new_r00)) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r20*(x265.value))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((-1.0)*new_r00))+IKsqr(((-1.0)*new_r20*(x265.value)))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((-1.0)*new_r00), ((-1.0)*new_r20*(x265.value))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x266=IKsin(j5); IkReal x267=IKcos(j5); IkReal x268=((1.0)*cj4); IkReal x269=((1.0)*x266); evalcond[0]=(new_r20+((sj4*x267))); evalcond[1]=(((cj4*x266))+new_r11); evalcond[2]=((((-1.0)*sj4*x269))+new_r21); evalcond[3]=((((-1.0)*x267*x268))+new_r10); evalcond[4]=((((-1.0)*new_r00))+(((-1.0)*x269))); evalcond[5]=((((-1.0)*x267))+(((-1.0)*new_r01))); evalcond[6]=(((new_r20*sj4))+x267+(((-1.0)*new_r10*x268))); evalcond[7]=((((-1.0)*new_r11*x268))+((new_r21*sj4))+(((-1.0)*x269))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x270=IKPowWithIntegerCheck(IKsign(cj4),-1); if(!x270.valid){ continue; } CheckValue<IkReal> x271 = IKatan2WithCheck(IkReal(((-1.0)*new_r11)),IkReal(new_r10),IKFAST_ATAN2_MAGTHRESH); if(!x271.valid){ continue; } j5array[0]=((-1.5707963267949)+(((1.5707963267949)*(x270.value)))+(x271.value)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x272=IKsin(j5); IkReal x273=IKcos(j5); IkReal x274=((1.0)*cj4); IkReal x275=((1.0)*x272); evalcond[0]=(new_r20+((sj4*x273))); evalcond[1]=(((cj4*x272))+new_r11); evalcond[2]=((((-1.0)*sj4*x275))+new_r21); evalcond[3]=((((-1.0)*x273*x274))+new_r10); evalcond[4]=((((-1.0)*x275))+(((-1.0)*new_r00))); evalcond[5]=((((-1.0)*x273))+(((-1.0)*new_r01))); evalcond[6]=(((new_r20*sj4))+x273+(((-1.0)*new_r10*x274))); evalcond[7]=((((-1.0)*new_r11*x274))+(((-1.0)*x275))+((new_r21*sj4))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x276=IKPowWithIntegerCheck(IKsign(sj4),-1); if(!x276.valid){ continue; } CheckValue<IkReal> x277 = IKatan2WithCheck(IkReal(new_r21),IkReal(((-1.0)*new_r20)),IKFAST_ATAN2_MAGTHRESH); if(!x277.valid){ continue; } j5array[0]=((-1.5707963267949)+(((1.5707963267949)*(x276.value)))+(x277.value)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x278=IKsin(j5); IkReal x279=IKcos(j5); IkReal x280=((1.0)*cj4); IkReal x281=((1.0)*x278); evalcond[0]=(new_r20+((sj4*x279))); evalcond[1]=(((cj4*x278))+new_r11); evalcond[2]=((((-1.0)*sj4*x281))+new_r21); evalcond[3]=(new_r10+(((-1.0)*x279*x280))); evalcond[4]=((((-1.0)*x281))+(((-1.0)*new_r00))); evalcond[5]=((((-1.0)*x279))+(((-1.0)*new_r01))); evalcond[6]=(((new_r20*sj4))+x279+(((-1.0)*new_r10*x280))); evalcond[7]=((((-1.0)*new_r11*x280))+(((-1.0)*x281))+((new_r21*sj4))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((1.5707963267949)+j3)))), 6.28318530717959))); evalcond[1]=new_r02; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(new_r00) < IKFAST_ATAN2_MAGTHRESH && IKabs(new_r01) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(new_r00)+IKsqr(new_r01)-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(new_r00, new_r01); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x282=IKcos(j5); IkReal x283=IKsin(j5); IkReal x284=((1.0)*x283); IkReal x285=((1.0)*x282); evalcond[0]=(new_r20+((sj4*x282))); evalcond[1]=((((-1.0)*x284))+new_r00); evalcond[2]=((((-1.0)*x285))+new_r01); evalcond[3]=((((-1.0)*sj4*x284))+new_r21); evalcond[4]=((((-1.0)*new_r11))+((cj4*x283))); evalcond[5]=((((-1.0)*cj4*x285))+(((-1.0)*new_r10))); evalcond[6]=(((new_r20*sj4))+((cj4*new_r10))+x282); evalcond[7]=(((cj4*new_r11))+(((-1.0)*x284))+((new_r21*sj4))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-1.5707963267949)+j4)))), 6.28318530717959))); evalcond[1]=new_r22; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(new_r21) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r20)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(new_r21)+IKsqr(((-1.0)*new_r20))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(new_r21, ((-1.0)*new_r20)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x286=IKcos(j5); IkReal x287=IKsin(j5); IkReal x288=((1.0)*sj3); IkReal x289=((1.0)*x287); IkReal x290=((1.0)*x286); evalcond[0]=(x286+new_r20); evalcond[1]=((((-1.0)*x289))+new_r21); evalcond[2]=(((sj3*x286))+new_r01); evalcond[3]=(((sj3*x287))+new_r00); evalcond[4]=((((-1.0)*cj3*x290))+new_r11); evalcond[5]=((((-1.0)*new_r02*x289))+new_r10); evalcond[6]=((((-1.0)*new_r00*x288))+((cj3*new_r10))+(((-1.0)*x289))); evalcond[7]=((((-1.0)*x290))+(((-1.0)*new_r01*x288))+((cj3*new_r11))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((1.5707963267949)+j4)))), 6.28318530717959))); evalcond[1]=new_r22; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(((-1.0)*new_r21)) < IKFAST_ATAN2_MAGTHRESH && IKabs(new_r20) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((-1.0)*new_r21))+IKsqr(new_r20)-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((-1.0)*new_r21), new_r20); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x291=IKcos(j5); IkReal x292=IKsin(j5); IkReal x293=((1.0)*sj3); IkReal x294=((1.0)*x291); evalcond[0]=(x292+new_r21); evalcond[1]=((((-1.0)*x294))+new_r20); evalcond[2]=(new_r01+((sj3*x291))); evalcond[3]=(new_r00+((sj3*x292))); evalcond[4]=(((new_r02*x292))+new_r10); evalcond[5]=((((-1.0)*cj3*x294))+new_r11); evalcond[6]=((((-1.0)*x292))+((cj3*new_r10))+(((-1.0)*new_r00*x293))); evalcond[7]=((((-1.0)*new_r01*x293))+(((-1.0)*x294))+((cj3*new_r11))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(j4))), 6.28318530717959))); evalcond[1]=new_r20; evalcond[2]=new_r02; evalcond[3]=new_r12; evalcond[4]=new_r21; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 && IKabs(evalcond[2]) < 0.0000050000000000 && IKabs(evalcond[3]) < 0.0000050000000000 && IKabs(evalcond[4]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; IkReal x295=((1.0)*new_r01); if( IKabs(((((-1.0)*cj3*x295))+(((-1.0)*new_r00*sj3)))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((((-1.0)*sj3*x295))+((cj3*new_r00)))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((((-1.0)*cj3*x295))+(((-1.0)*new_r00*sj3))))+IKsqr(((((-1.0)*sj3*x295))+((cj3*new_r00))))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((((-1.0)*cj3*x295))+(((-1.0)*new_r00*sj3))), ((((-1.0)*sj3*x295))+((cj3*new_r00)))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x296=IKsin(j5); IkReal x297=IKcos(j5); IkReal x298=((1.0)*sj3); IkReal x299=((1.0)*x297); IkReal x300=(sj3*x296); IkReal x301=((1.0)*x296); IkReal x302=(cj3*x299); evalcond[0]=(((new_r11*sj3))+x296+((cj3*new_r01))); evalcond[1]=(((cj3*x296))+new_r01+((sj3*x297))); evalcond[2]=(((new_r10*sj3))+(((-1.0)*x299))+((cj3*new_r00))); evalcond[3]=(((cj3*new_r10))+(((-1.0)*new_r00*x298))+(((-1.0)*x301))); evalcond[4]=((((-1.0)*new_r01*x298))+(((-1.0)*x299))+((cj3*new_r11))); evalcond[5]=(x300+new_r00+(((-1.0)*x302))); evalcond[6]=(x300+new_r11+(((-1.0)*x302))); evalcond[7]=((((-1.0)*cj3*x301))+(((-1.0)*x297*x298))+new_r10); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-3.14159265358979)+j4)))), 6.28318530717959))); evalcond[1]=new_r20; evalcond[2]=new_r02; evalcond[3]=new_r12; evalcond[4]=new_r21; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 && IKabs(evalcond[2]) < 0.0000050000000000 && IKabs(evalcond[3]) < 0.0000050000000000 && IKabs(evalcond[4]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; IkReal x303=((1.0)*sj3); if( IKabs((((cj3*new_r01))+(((-1.0)*new_r00*x303)))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((((-1.0)*cj3*new_r00))+(((-1.0)*new_r01*x303)))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr((((cj3*new_r01))+(((-1.0)*new_r00*x303))))+IKsqr(((((-1.0)*cj3*new_r00))+(((-1.0)*new_r01*x303))))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2((((cj3*new_r01))+(((-1.0)*new_r00*x303))), ((((-1.0)*cj3*new_r00))+(((-1.0)*new_r01*x303)))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x304=IKsin(j5); IkReal x305=IKcos(j5); IkReal x306=((1.0)*sj3); IkReal x307=((1.0)*x304); IkReal x308=(sj3*x305); IkReal x309=((1.0)*x305); IkReal x310=(cj3*x307); evalcond[0]=(((new_r10*sj3))+x305+((cj3*new_r00))); evalcond[1]=(((new_r11*sj3))+((cj3*new_r01))+(((-1.0)*x307))); evalcond[2]=(((sj3*x304))+((cj3*x305))+new_r00); evalcond[3]=(((cj3*new_r10))+(((-1.0)*new_r00*x306))+(((-1.0)*x307))); evalcond[4]=((((-1.0)*new_r01*x306))+((cj3*new_r11))+(((-1.0)*x309))); evalcond[5]=(x308+(((-1.0)*x310))+new_r01); evalcond[6]=(x308+(((-1.0)*x310))+new_r10); evalcond[7]=((((-1.0)*cj3*x309))+(((-1.0)*x304*x306))+new_r11); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(j3))), 6.28318530717959))); evalcond[1]=new_r12; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(new_r10) < IKFAST_ATAN2_MAGTHRESH && IKabs(new_r11) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(new_r10)+IKsqr(new_r11)-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(new_r10, new_r11); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x311=IKcos(j5); IkReal x312=IKsin(j5); IkReal x313=((1.0)*cj4); IkReal x314=((1.0)*x312); evalcond[0]=(((new_r02*x311))+new_r20); evalcond[1]=((((-1.0)*x314))+new_r10); evalcond[2]=((((-1.0)*x311))+new_r11); evalcond[3]=(((cj4*x312))+new_r01); evalcond[4]=((((-1.0)*new_r02*x314))+new_r21); evalcond[5]=(new_r00+(((-1.0)*x311*x313))); evalcond[6]=((((-1.0)*new_r00*x313))+((new_r20*sj4))+x311); evalcond[7]=((((-1.0)*x314))+((new_r21*sj4))+(((-1.0)*new_r01*x313))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-3.14159265358979)+j3)))), 6.28318530717959))); evalcond[1]=new_r12; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5eval[3]; sj3=0; cj3=-1.0; j3=3.14159265358979; j5eval[0]=new_r02; j5eval[1]=IKsign(new_r02); j5eval[2]=((IKabs(new_r20))+(IKabs(new_r21))); if( IKabs(j5eval[0]) < 0.0000010000000000 || IKabs(j5eval[1]) < 0.0000010000000000 || IKabs(j5eval[2]) < 0.0000010000000000 ) { { IkReal j5eval[1]; sj3=0; cj3=-1.0; j3=3.14159265358979; j5eval[0]=new_r02; if( IKabs(j5eval[0]) < 0.0000010000000000 ) { { IkReal j5eval[2]; sj3=0; cj3=-1.0; j3=3.14159265358979; j5eval[0]=new_r02; j5eval[1]=cj4; if( IKabs(j5eval[0]) < 0.0000010000000000 || IKabs(j5eval[1]) < 0.0000010000000000 ) { { IkReal evalcond[4]; bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-1.5707963267949)+j4)))), 6.28318530717959))); evalcond[1]=new_r22; evalcond[2]=new_r01; evalcond[3]=new_r00; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 && IKabs(evalcond[2]) < 0.0000050000000000 && IKabs(evalcond[3]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(new_r21) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r20)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(new_r21)+IKsqr(((-1.0)*new_r20))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(new_r21, ((-1.0)*new_r20)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[4]; IkReal x315=IKcos(j5); IkReal x316=((1.0)*(IKsin(j5))); evalcond[0]=(x315+new_r20); evalcond[1]=((((-1.0)*x316))+new_r21); evalcond[2]=((((-1.0)*x316))+(((-1.0)*new_r10))); evalcond[3]=((((-1.0)*new_r11))+(((-1.0)*x315))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((1.5707963267949)+j4)))), 6.28318530717959))); evalcond[1]=new_r22; evalcond[2]=new_r01; evalcond[3]=new_r00; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 && IKabs(evalcond[2]) < 0.0000050000000000 && IKabs(evalcond[3]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(((-1.0)*new_r21)) < IKFAST_ATAN2_MAGTHRESH && IKabs(new_r20) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((-1.0)*new_r21))+IKsqr(new_r20)-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((-1.0)*new_r21), new_r20); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[4]; IkReal x317=IKsin(j5); IkReal x318=((1.0)*(IKcos(j5))); evalcond[0]=(x317+new_r21); evalcond[1]=((((-1.0)*x318))+new_r20); evalcond[2]=((((-1.0)*new_r10))+(((-1.0)*x317))); evalcond[3]=((((-1.0)*x318))+(((-1.0)*new_r11))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=IKabs(new_r02); evalcond[1]=new_r20; evalcond[2]=new_r21; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 && IKabs(evalcond[2]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(((-1.0)*new_r10)) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*cj4*new_r00)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((-1.0)*new_r10))+IKsqr(((-1.0)*cj4*new_r00))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((-1.0)*new_r10), ((-1.0)*cj4*new_r00)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[6]; IkReal x319=IKcos(j5); IkReal x320=IKsin(j5); IkReal x321=((1.0)*x320); IkReal x322=((1.0)*x319); evalcond[0]=(((cj4*new_r00))+x319); evalcond[1]=((((-1.0)*x321))+(((-1.0)*new_r10))); evalcond[2]=((((-1.0)*x322))+(((-1.0)*new_r11))); evalcond[3]=(((cj4*x320))+(((-1.0)*new_r01))); evalcond[4]=(((cj4*new_r01))+(((-1.0)*x321))); evalcond[5]=((((-1.0)*new_r00))+(((-1.0)*cj4*x322))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((IKabs(new_r20))+(IKabs(new_r21))); if( IKabs(evalcond[0]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(((-1.0)*new_r10)) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r11)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((-1.0)*new_r10))+IKsqr(((-1.0)*new_r11))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((-1.0)*new_r10), ((-1.0)*new_r11)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[6]; IkReal x323=IKsin(j5); IkReal x324=IKcos(j5); evalcond[0]=x324; evalcond[1]=(new_r22*x323); evalcond[2]=((-1.0)*x323); evalcond[3]=((-1.0)*new_r22*x324); evalcond[4]=((((-1.0)*x323))+(((-1.0)*new_r10))); evalcond[5]=((((-1.0)*x324))+(((-1.0)*new_r11))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j5] } } while(0); if( bgotonextstatement ) { } } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x325=IKPowWithIntegerCheck(new_r02,-1); if(!x325.valid){ continue; } CheckValue<IkReal> x326=IKPowWithIntegerCheck(cj4,-1); if(!x326.valid){ continue; } if( IKabs(((-1.0)*new_r21*(x325.value))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r00*(x326.value))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((-1.0)*new_r21*(x325.value)))+IKsqr(((-1.0)*new_r00*(x326.value)))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((-1.0)*new_r21*(x325.value)), ((-1.0)*new_r00*(x326.value))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x327=IKsin(j5); IkReal x328=IKcos(j5); IkReal x329=((1.0)*x327); IkReal x330=((1.0)*x328); evalcond[0]=(new_r21+((new_r02*x327))); evalcond[1]=(new_r20+(((-1.0)*new_r02*x330))); evalcond[2]=((((-1.0)*x329))+(((-1.0)*new_r10))); evalcond[3]=((((-1.0)*new_r11))+(((-1.0)*x330))); evalcond[4]=(((cj4*x327))+(((-1.0)*new_r01))); evalcond[5]=((((-1.0)*cj4*x330))+(((-1.0)*new_r00))); evalcond[6]=(((new_r20*sj4))+((cj4*new_r00))+x328); evalcond[7]=(((cj4*new_r01))+(((-1.0)*x329))+((new_r21*sj4))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x331=IKPowWithIntegerCheck(new_r02,-1); if(!x331.valid){ continue; } if( IKabs(((-1.0)*new_r10)) < IKFAST_ATAN2_MAGTHRESH && IKabs((new_r20*(x331.value))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((-1.0)*new_r10))+IKsqr((new_r20*(x331.value)))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((-1.0)*new_r10), (new_r20*(x331.value))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x332=IKsin(j5); IkReal x333=IKcos(j5); IkReal x334=((1.0)*x332); IkReal x335=((1.0)*x333); evalcond[0]=(((new_r02*x332))+new_r21); evalcond[1]=(new_r20+(((-1.0)*new_r02*x335))); evalcond[2]=((((-1.0)*new_r10))+(((-1.0)*x334))); evalcond[3]=((((-1.0)*new_r11))+(((-1.0)*x335))); evalcond[4]=(((cj4*x332))+(((-1.0)*new_r01))); evalcond[5]=((((-1.0)*cj4*x335))+(((-1.0)*new_r00))); evalcond[6]=(((new_r20*sj4))+((cj4*new_r00))+x333); evalcond[7]=(((cj4*new_r01))+(((-1.0)*x334))+((new_r21*sj4))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x336 = IKatan2WithCheck(IkReal(((-1.0)*new_r21)),IkReal(new_r20),IKFAST_ATAN2_MAGTHRESH); if(!x336.valid){ continue; } CheckValue<IkReal> x337=IKPowWithIntegerCheck(IKsign(new_r02),-1); if(!x337.valid){ continue; } j5array[0]=((-1.5707963267949)+(x336.value)+(((1.5707963267949)*(x337.value)))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x338=IKsin(j5); IkReal x339=IKcos(j5); IkReal x340=((1.0)*x338); IkReal x341=((1.0)*x339); evalcond[0]=(((new_r02*x338))+new_r21); evalcond[1]=((((-1.0)*new_r02*x341))+new_r20); evalcond[2]=((((-1.0)*new_r10))+(((-1.0)*x340))); evalcond[3]=((((-1.0)*new_r11))+(((-1.0)*x341))); evalcond[4]=(((cj4*x338))+(((-1.0)*new_r01))); evalcond[5]=((((-1.0)*cj4*x341))+(((-1.0)*new_r00))); evalcond[6]=(((new_r20*sj4))+((cj4*new_r00))+x339); evalcond[7]=(((cj4*new_r01))+((new_r21*sj4))+(((-1.0)*x340))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((IKabs(new_r20))+(IKabs(new_r21))); if( IKabs(evalcond[0]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5eval[1]; new_r21=0; new_r20=0; new_r02=0; new_r12=0; j5eval[0]=1.0; if( IKabs(j5eval[0]) < 0.0000000100000000 ) { continue; // no branches [j5] } else { IkReal op[2+1], zeror[2]; int numroots; op[0]=-1.0; op[1]=0; op[2]=1.0; polyroots2(op,zeror,numroots); IkReal j5array[2], cj5array[2], sj5array[2], tempj5array[1]; int numsolutions = 0; for(int ij5 = 0; ij5 < numroots; ++ij5) { IkReal htj5 = zeror[ij5]; tempj5array[0]=((2.0)*(atan(htj5))); for(int kj5 = 0; kj5 < 1; ++kj5) { j5array[numsolutions] = tempj5array[kj5]; if( j5array[numsolutions] > IKPI ) { j5array[numsolutions]-=IK2PI; } else if( j5array[numsolutions] < -IKPI ) { j5array[numsolutions]+=IK2PI; } sj5array[numsolutions] = IKsin(j5array[numsolutions]); cj5array[numsolutions] = IKcos(j5array[numsolutions]); numsolutions++; } } bool j5valid[2]={true,true}; _nj5 = 2; for(int ij5 = 0; ij5 < numsolutions; ++ij5) { if( !j5valid[ij5] ) { continue; } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; htj5 = IKtan(j5/2); _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < numsolutions; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j5] } } while(0); if( bgotonextstatement ) { } } } } } } } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x343=IKPowWithIntegerCheck(sj4,-1); if(!x343.valid){ continue; } IkReal x342=x343.value; CheckValue<IkReal> x344=IKPowWithIntegerCheck(cj3,-1); if(!x344.valid){ continue; } CheckValue<IkReal> x345=IKPowWithIntegerCheck(cj4,-1); if(!x345.valid){ continue; } if( IKabs((x342*(x344.value)*(x345.value)*((((new_r20*sj3))+(((-1.0)*new_r01*sj4)))))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r20*x342)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr((x342*(x344.value)*(x345.value)*((((new_r20*sj3))+(((-1.0)*new_r01*sj4))))))+IKsqr(((-1.0)*new_r20*x342))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2((x342*(x344.value)*(x345.value)*((((new_r20*sj3))+(((-1.0)*new_r01*sj4))))), ((-1.0)*new_r20*x342)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[12]; IkReal x346=IKsin(j5); IkReal x347=IKcos(j5); IkReal x348=(cj3*new_r00); IkReal x349=(cj3*cj4); IkReal x350=((1.0)*sj3); IkReal x351=((1.0)*x346); IkReal x352=(sj3*x346); IkReal x353=((1.0)*x347); evalcond[0]=(((sj4*x347))+new_r20); evalcond[1]=(new_r21+(((-1.0)*sj4*x351))); evalcond[2]=(((new_r11*sj3))+((cj4*x346))+((cj3*new_r01))); evalcond[3]=((((-1.0)*x351))+((cj3*new_r10))+(((-1.0)*new_r00*x350))); evalcond[4]=((((-1.0)*x353))+(((-1.0)*new_r01*x350))+((cj3*new_r11))); evalcond[5]=(((sj3*x347))+((x346*x349))+new_r01); evalcond[6]=(((new_r10*sj3))+x348+(((-1.0)*cj4*x353))); evalcond[7]=((((-1.0)*x349*x353))+x352+new_r00); evalcond[8]=((((-1.0)*cj3*x353))+((cj4*x352))+new_r11); evalcond[9]=((((-1.0)*cj3*x351))+(((-1.0)*cj4*x347*x350))+new_r10); evalcond[10]=(((new_r20*sj4))+x347+(((-1.0)*cj4*x348))+(((-1.0)*cj4*new_r10*x350))); evalcond[11]=((((-1.0)*x351))+(((-1.0)*cj4*new_r11*x350))+(((-1.0)*new_r01*x349))+((new_r21*sj4))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[8]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[9]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[10]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[11]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x355=IKPowWithIntegerCheck(sj4,-1); if(!x355.valid){ continue; } IkReal x354=x355.value; CheckValue<IkReal> x356=IKPowWithIntegerCheck(sj3,-1); if(!x356.valid){ continue; } if( IKabs((x354*(x356.value)*(((((-1.0)*cj3*cj4*new_r20))+(((-1.0)*new_r00*sj4)))))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r20*x354)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr((x354*(x356.value)*(((((-1.0)*cj3*cj4*new_r20))+(((-1.0)*new_r00*sj4))))))+IKsqr(((-1.0)*new_r20*x354))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2((x354*(x356.value)*(((((-1.0)*cj3*cj4*new_r20))+(((-1.0)*new_r00*sj4))))), ((-1.0)*new_r20*x354)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[12]; IkReal x357=IKsin(j5); IkReal x358=IKcos(j5); IkReal x359=(cj3*new_r00); IkReal x360=(cj3*cj4); IkReal x361=((1.0)*sj3); IkReal x362=((1.0)*x357); IkReal x363=(sj3*x357); IkReal x364=((1.0)*x358); evalcond[0]=(((sj4*x358))+new_r20); evalcond[1]=((((-1.0)*sj4*x362))+new_r21); evalcond[2]=(((new_r11*sj3))+((cj4*x357))+((cj3*new_r01))); evalcond[3]=((((-1.0)*new_r00*x361))+(((-1.0)*x362))+((cj3*new_r10))); evalcond[4]=((((-1.0)*x364))+((cj3*new_r11))+(((-1.0)*new_r01*x361))); evalcond[5]=(((sj3*x358))+new_r01+((x357*x360))); evalcond[6]=((((-1.0)*cj4*x364))+((new_r10*sj3))+x359); evalcond[7]=((((-1.0)*x360*x364))+x363+new_r00); evalcond[8]=(((cj4*x363))+new_r11+(((-1.0)*cj3*x364))); evalcond[9]=((((-1.0)*cj4*x358*x361))+new_r10+(((-1.0)*cj3*x362))); evalcond[10]=(((new_r20*sj4))+x358+(((-1.0)*cj4*new_r10*x361))+(((-1.0)*cj4*x359))); evalcond[11]=((((-1.0)*x362))+(((-1.0)*cj4*new_r11*x361))+((new_r21*sj4))+(((-1.0)*new_r01*x360))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[8]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[9]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[10]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[11]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x365=IKPowWithIntegerCheck(IKsign(sj4),-1); if(!x365.valid){ continue; } CheckValue<IkReal> x366 = IKatan2WithCheck(IkReal(new_r21),IkReal(((-1.0)*new_r20)),IKFAST_ATAN2_MAGTHRESH); if(!x366.valid){ continue; } j5array[0]=((-1.5707963267949)+(((1.5707963267949)*(x365.value)))+(x366.value)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[12]; IkReal x367=IKsin(j5); IkReal x368=IKcos(j5); IkReal x369=(cj3*new_r00); IkReal x370=(cj3*cj4); IkReal x371=((1.0)*sj3); IkReal x372=((1.0)*x367); IkReal x373=(sj3*x367); IkReal x374=((1.0)*x368); evalcond[0]=(((sj4*x368))+new_r20); evalcond[1]=((((-1.0)*sj4*x372))+new_r21); evalcond[2]=(((new_r11*sj3))+((cj4*x367))+((cj3*new_r01))); evalcond[3]=((((-1.0)*new_r00*x371))+(((-1.0)*x372))+((cj3*new_r10))); evalcond[4]=((((-1.0)*x374))+((cj3*new_r11))+(((-1.0)*new_r01*x371))); evalcond[5]=(((x367*x370))+((sj3*x368))+new_r01); evalcond[6]=(((new_r10*sj3))+(((-1.0)*cj4*x374))+x369); evalcond[7]=((((-1.0)*x370*x374))+x373+new_r00); evalcond[8]=(((cj4*x373))+(((-1.0)*cj3*x374))+new_r11); evalcond[9]=((((-1.0)*cj4*x368*x371))+(((-1.0)*cj3*x372))+new_r10); evalcond[10]=(((new_r20*sj4))+x368+(((-1.0)*cj4*x369))+(((-1.0)*cj4*new_r10*x371))); evalcond[11]=((((-1.0)*x372))+(((-1.0)*cj4*new_r11*x371))+((new_r21*sj4))+(((-1.0)*new_r01*x370))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[8]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[9]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[10]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[11]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x375=IKPowWithIntegerCheck(IKsign(sj4),-1); if(!x375.valid){ continue; } CheckValue<IkReal> x376 = IKatan2WithCheck(IkReal(new_r21),IkReal(((-1.0)*new_r20)),IKFAST_ATAN2_MAGTHRESH); if(!x376.valid){ continue; } j5array[0]=((-1.5707963267949)+(((1.5707963267949)*(x375.value)))+(x376.value)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[2]; evalcond[0]=(((sj4*(IKcos(j5))))+new_r20); evalcond[1]=((((-1.0)*sj4*(IKsin(j5))))+new_r21); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH ) { continue; } } { IkReal j3eval[3]; j3eval[0]=sj4; j3eval[1]=IKsign(sj4); j3eval[2]=((IKabs(new_r12))+(IKabs(new_r02))); if( IKabs(j3eval[0]) < 0.0000010000000000 || IKabs(j3eval[1]) < 0.0000010000000000 || IKabs(j3eval[2]) < 0.0000010000000000 ) { { IkReal j3eval[2]; j3eval[0]=cj5; j3eval[1]=sj4; if( IKabs(j3eval[0]) < 0.0000010000000000 || IKabs(j3eval[1]) < 0.0000010000000000 ) { { IkReal evalcond[5]; bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-1.5707963267949)+j5)))), 6.28318530717959))); evalcond[1]=new_r20; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j3array[1], cj3array[1], sj3array[1]; bool j3valid[1]={false}; _nj3 = 1; if( IKabs(((-1.0)*new_r00)) < IKFAST_ATAN2_MAGTHRESH && IKabs(new_r10) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((-1.0)*new_r00))+IKsqr(new_r10)-1) <= IKFAST_SINCOS_THRESH ) continue; j3array[0]=IKatan2(((-1.0)*new_r00), new_r10); sj3array[0]=IKsin(j3array[0]); cj3array[0]=IKcos(j3array[0]); if( j3array[0] > IKPI ) { j3array[0]-=IK2PI; } else if( j3array[0] < -IKPI ) { j3array[0]+=IK2PI; } j3valid[0] = true; for(int ij3 = 0; ij3 < 1; ++ij3) { if( !j3valid[ij3] ) { continue; } _ij3[0] = ij3; _ij3[1] = -1; for(int iij3 = ij3+1; iij3 < 1; ++iij3) { if( j3valid[iij3] && IKabs(cj3array[ij3]-cj3array[iij3]) < IKFAST_SOLUTION_THRESH && IKabs(sj3array[ij3]-sj3array[iij3]) < IKFAST_SOLUTION_THRESH ) { j3valid[iij3]=false; _ij3[1] = iij3; break; } } j3 = j3array[ij3]; cj3 = cj3array[ij3]; sj3 = sj3array[ij3]; { IkReal evalcond[18]; IkReal x377=IKsin(j3); IkReal x378=IKcos(j3); IkReal x379=((1.0)*sj4); IkReal x380=((1.0)*new_r22); IkReal x381=(new_r00*x378); IkReal x382=(new_r11*x377); IkReal x383=(new_r01*x378); IkReal x384=(new_r02*x378); IkReal x385=(new_r12*x377); IkReal x386=((1.0)*x377); IkReal x387=(new_r10*x377); IkReal x388=(x377*x380); evalcond[0]=(x377+new_r00); evalcond[1]=(new_r01+((new_r22*x378))); evalcond[2]=(new_r11+((new_r22*x377))); evalcond[3]=((((-1.0)*x378))+new_r10); evalcond[4]=((((-1.0)*x378*x379))+new_r02); evalcond[5]=((((-1.0)*x377*x379))+new_r12); evalcond[6]=(x387+x381); evalcond[7]=(((new_r12*x378))+(((-1.0)*new_r02*x386))); evalcond[8]=((((-1.0)*new_r01*x386))+((new_r11*x378))); evalcond[9]=(x382+x383+new_r22); evalcond[10]=((-1.0)+(((-1.0)*new_r00*x386))+((new_r10*x378))); evalcond[11]=((((-1.0)*x379))+x384+x385); evalcond[12]=((((-1.0)*x379*x381))+(((-1.0)*x379*x387))); evalcond[13]=((((-1.0)*x380*x387))+(((-1.0)*x380*x381))); evalcond[14]=((((-1.0)*x380*x385))+(((-1.0)*x380*x384))+((new_r22*sj4))); evalcond[15]=((((-1.0)*cj4*new_r21))+(((-1.0)*x379*x383))+(((-1.0)*x379*x382))); evalcond[16]=((-1.0)+(((-1.0)*x380*x383))+(((-1.0)*x380*x382))+(sj4*sj4)); evalcond[17]=((1.0)+(((-1.0)*x379*x385))+(((-1.0)*x379*x384))+(((-1.0)*new_r22*x380))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[8]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[9]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[10]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[11]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[12]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[13]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[14]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[15]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[16]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[17]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((1.5707963267949)+j5)))), 6.28318530717959))); evalcond[1]=new_r20; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j3array[1], cj3array[1], sj3array[1]; bool j3valid[1]={false}; _nj3 = 1; if( IKabs(new_r00) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r10)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(new_r00)+IKsqr(((-1.0)*new_r10))-1) <= IKFAST_SINCOS_THRESH ) continue; j3array[0]=IKatan2(new_r00, ((-1.0)*new_r10)); sj3array[0]=IKsin(j3array[0]); cj3array[0]=IKcos(j3array[0]); if( j3array[0] > IKPI ) { j3array[0]-=IK2PI; } else if( j3array[0] < -IKPI ) { j3array[0]+=IK2PI; } j3valid[0] = true; for(int ij3 = 0; ij3 < 1; ++ij3) { if( !j3valid[ij3] ) { continue; } _ij3[0] = ij3; _ij3[1] = -1; for(int iij3 = ij3+1; iij3 < 1; ++iij3) { if( j3valid[iij3] && IKabs(cj3array[ij3]-cj3array[iij3]) < IKFAST_SOLUTION_THRESH && IKabs(sj3array[ij3]-sj3array[iij3]) < IKFAST_SOLUTION_THRESH ) { j3valid[iij3]=false; _ij3[1] = iij3; break; } } j3 = j3array[ij3]; cj3 = cj3array[ij3]; sj3 = sj3array[ij3]; { IkReal evalcond[18]; IkReal x389=IKcos(j3); IkReal x390=IKsin(j3); IkReal x391=(new_r22*sj4); IkReal x392=((1.0)*sj4); IkReal x393=((1.0)*new_r22); IkReal x394=(new_r00*x389); IkReal x395=(new_r11*x390); IkReal x396=(new_r01*x389); IkReal x397=(new_r02*x389); IkReal x398=(new_r12*x390); IkReal x399=((1.0)*x390); IkReal x400=(new_r10*x390); IkReal x401=(x390*x393); evalcond[0]=(x389+new_r10); evalcond[1]=((((-1.0)*x399))+new_r00); evalcond[2]=((((-1.0)*x389*x392))+new_r02); evalcond[3]=((((-1.0)*x390*x392))+new_r12); evalcond[4]=((((-1.0)*x389*x393))+new_r01); evalcond[5]=(new_r11+(((-1.0)*x401))); evalcond[6]=(x394+x400); evalcond[7]=(((new_r12*x389))+(((-1.0)*new_r02*x399))); evalcond[8]=((((-1.0)*new_r01*x399))+((new_r11*x389))); evalcond[9]=((1.0)+((new_r10*x389))+(((-1.0)*new_r00*x399))); evalcond[10]=((((-1.0)*x392))+x397+x398); evalcond[11]=((((-1.0)*x393))+x395+x396); evalcond[12]=((((-1.0)*x392*x400))+(((-1.0)*x392*x394))); evalcond[13]=((((-1.0)*x393*x400))+(((-1.0)*x393*x394))); evalcond[14]=(x391+(((-1.0)*x393*x398))+(((-1.0)*x393*x397))); evalcond[15]=(x391+(((-1.0)*x392*x395))+(((-1.0)*x392*x396))); evalcond[16]=((1.0)+(((-1.0)*new_r22*x393))+(((-1.0)*x392*x398))+(((-1.0)*x392*x397))); evalcond[17]=((1.0)+(((-1.0)*sj4*x392))+(((-1.0)*x393*x395))+(((-1.0)*x393*x396))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[8]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[9]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[10]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[11]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[12]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[13]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[14]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[15]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[16]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[17]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(j4))), 6.28318530717959))); evalcond[1]=new_r20; evalcond[2]=new_r02; evalcond[3]=new_r12; evalcond[4]=new_r21; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 && IKabs(evalcond[2]) < 0.0000050000000000 && IKabs(evalcond[3]) < 0.0000050000000000 && IKabs(evalcond[4]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j3array[1], cj3array[1], sj3array[1]; bool j3valid[1]={false}; _nj3 = 1; IkReal x402=((1.0)*new_r01); if( IKabs(((((-1.0)*cj5*x402))+(((-1.0)*new_r00*sj5)))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((((-1.0)*sj5*x402))+((cj5*new_r00)))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((((-1.0)*cj5*x402))+(((-1.0)*new_r00*sj5))))+IKsqr(((((-1.0)*sj5*x402))+((cj5*new_r00))))-1) <= IKFAST_SINCOS_THRESH ) continue; j3array[0]=IKatan2(((((-1.0)*cj5*x402))+(((-1.0)*new_r00*sj5))), ((((-1.0)*sj5*x402))+((cj5*new_r00)))); sj3array[0]=IKsin(j3array[0]); cj3array[0]=IKcos(j3array[0]); if( j3array[0] > IKPI ) { j3array[0]-=IK2PI; } else if( j3array[0] < -IKPI ) { j3array[0]+=IK2PI; } j3valid[0] = true; for(int ij3 = 0; ij3 < 1; ++ij3) { if( !j3valid[ij3] ) { continue; } _ij3[0] = ij3; _ij3[1] = -1; for(int iij3 = ij3+1; iij3 < 1; ++iij3) { if( j3valid[iij3] && IKabs(cj3array[ij3]-cj3array[iij3]) < IKFAST_SOLUTION_THRESH && IKabs(sj3array[ij3]-sj3array[iij3]) < IKFAST_SOLUTION_THRESH ) { j3valid[iij3]=false; _ij3[1] = iij3; break; } } j3 = j3array[ij3]; cj3 = cj3array[ij3]; sj3 = sj3array[ij3]; { IkReal evalcond[8]; IkReal x403=IKcos(j3); IkReal x404=IKsin(j3); IkReal x405=((1.0)*cj5); IkReal x406=(sj5*x404); IkReal x407=(sj5*x403); IkReal x408=((1.0)*x404); IkReal x409=(x403*x405); evalcond[0]=(sj5+((new_r11*x404))+((new_r01*x403))); evalcond[1]=(((cj5*x404))+x407+new_r01); evalcond[2]=(x406+new_r00+(((-1.0)*x409))); evalcond[3]=(x406+new_r11+(((-1.0)*x409))); evalcond[4]=(((new_r10*x404))+(((-1.0)*x405))+((new_r00*x403))); evalcond[5]=((((-1.0)*x404*x405))+new_r10+(((-1.0)*x407))); evalcond[6]=((((-1.0)*sj5))+((new_r10*x403))+(((-1.0)*new_r00*x408))); evalcond[7]=(((new_r11*x403))+(((-1.0)*new_r01*x408))+(((-1.0)*x405))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-3.14159265358979)+j4)))), 6.28318530717959))); evalcond[1]=new_r20; evalcond[2]=new_r02; evalcond[3]=new_r12; evalcond[4]=new_r21; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 && IKabs(evalcond[2]) < 0.0000050000000000 && IKabs(evalcond[3]) < 0.0000050000000000 && IKabs(evalcond[4]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j3array[1], cj3array[1], sj3array[1]; bool j3valid[1]={false}; _nj3 = 1; IkReal x410=((1.0)*cj5); if( IKabs(((((-1.0)*new_r00*sj5))+(((-1.0)*new_r01*x410)))) < IKFAST_ATAN2_MAGTHRESH && IKabs((((new_r01*sj5))+(((-1.0)*new_r00*x410)))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((((-1.0)*new_r00*sj5))+(((-1.0)*new_r01*x410))))+IKsqr((((new_r01*sj5))+(((-1.0)*new_r00*x410))))-1) <= IKFAST_SINCOS_THRESH ) continue; j3array[0]=IKatan2(((((-1.0)*new_r00*sj5))+(((-1.0)*new_r01*x410))), (((new_r01*sj5))+(((-1.0)*new_r00*x410)))); sj3array[0]=IKsin(j3array[0]); cj3array[0]=IKcos(j3array[0]); if( j3array[0] > IKPI ) { j3array[0]-=IK2PI; } else if( j3array[0] < -IKPI ) { j3array[0]+=IK2PI; } j3valid[0] = true; for(int ij3 = 0; ij3 < 1; ++ij3) { if( !j3valid[ij3] ) { continue; } _ij3[0] = ij3; _ij3[1] = -1; for(int iij3 = ij3+1; iij3 < 1; ++iij3) { if( j3valid[iij3] && IKabs(cj3array[ij3]-cj3array[iij3]) < IKFAST_SOLUTION_THRESH && IKabs(sj3array[ij3]-sj3array[iij3]) < IKFAST_SOLUTION_THRESH ) { j3valid[iij3]=false; _ij3[1] = iij3; break; } } j3 = j3array[ij3]; cj3 = cj3array[ij3]; sj3 = sj3array[ij3]; { IkReal evalcond[8]; IkReal x411=IKsin(j3); IkReal x412=IKcos(j3); IkReal x413=((1.0)*sj5); IkReal x414=((1.0)*cj5); IkReal x415=(cj5*x411); IkReal x416=((1.0)*x411); IkReal x417=(x412*x413); evalcond[0]=(cj5+((new_r10*x411))+((new_r00*x412))); evalcond[1]=(((sj5*x411))+((cj5*x412))+new_r00); evalcond[2]=(x415+new_r01+(((-1.0)*x417))); evalcond[3]=(x415+new_r10+(((-1.0)*x417))); evalcond[4]=(((new_r11*x411))+(((-1.0)*x413))+((new_r01*x412))); evalcond[5]=((((-1.0)*x412*x414))+(((-1.0)*x411*x413))+new_r11); evalcond[6]=(((new_r10*x412))+(((-1.0)*new_r00*x416))+(((-1.0)*x413))); evalcond[7]=(((new_r11*x412))+(((-1.0)*x414))+(((-1.0)*new_r01*x416))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((IKabs(new_r12))+(IKabs(new_r02))); if( IKabs(evalcond[0]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j3eval[1]; new_r02=0; new_r12=0; new_r20=0; new_r21=0; j3eval[0]=((IKabs(new_r11))+(IKabs(new_r01))); if( IKabs(j3eval[0]) < 0.0000010000000000 ) { { IkReal j3eval[1]; new_r02=0; new_r12=0; new_r20=0; new_r21=0; j3eval[0]=((IKabs(new_r10))+(IKabs(new_r00))); if( IKabs(j3eval[0]) < 0.0000010000000000 ) { { IkReal j3eval[1]; new_r02=0; new_r12=0; new_r20=0; new_r21=0; j3eval[0]=((IKabs((new_r10*new_r22)))+(IKabs((new_r00*new_r22)))); if( IKabs(j3eval[0]) < 0.0000010000000000 ) { continue; // no branches [j3] } else { { IkReal j3array[2], cj3array[2], sj3array[2]; bool j3valid[2]={false}; _nj3 = 2; IkReal x418=((-1.0)*new_r22); CheckValue<IkReal> x420 = IKatan2WithCheck(IkReal((new_r00*x418)),IkReal((new_r10*x418)),IKFAST_ATAN2_MAGTHRESH); if(!x420.valid){ continue; } IkReal x419=x420.value; j3array[0]=((-1.0)*x419); sj3array[0]=IKsin(j3array[0]); cj3array[0]=IKcos(j3array[0]); j3array[1]=((3.14159265358979)+(((-1.0)*x419))); sj3array[1]=IKsin(j3array[1]); cj3array[1]=IKcos(j3array[1]); if( j3array[0] > IKPI ) { j3array[0]-=IK2PI; } else if( j3array[0] < -IKPI ) { j3array[0]+=IK2PI; } j3valid[0] = true; if( j3array[1] > IKPI ) { j3array[1]-=IK2PI; } else if( j3array[1] < -IKPI ) { j3array[1]+=IK2PI; } j3valid[1] = true; for(int ij3 = 0; ij3 < 2; ++ij3) { if( !j3valid[ij3] ) { continue; } _ij3[0] = ij3; _ij3[1] = -1; for(int iij3 = ij3+1; iij3 < 2; ++iij3) { if( j3valid[iij3] && IKabs(cj3array[ij3]-cj3array[iij3]) < IKFAST_SOLUTION_THRESH && IKabs(sj3array[ij3]-sj3array[iij3]) < IKFAST_SOLUTION_THRESH ) { j3valid[iij3]=false; _ij3[1] = iij3; break; } } j3 = j3array[ij3]; cj3 = cj3array[ij3]; sj3 = sj3array[ij3]; { IkReal evalcond[5]; IkReal x421=IKsin(j3); IkReal x422=IKcos(j3); IkReal x423=((1.0)*new_r22); IkReal x424=(new_r11*x421); IkReal x425=(new_r01*x422); IkReal x426=((1.0)*x421); evalcond[0]=(x425+x424); evalcond[1]=(((new_r10*x421))+((new_r00*x422))); evalcond[2]=((((-1.0)*new_r00*x426))+((new_r10*x422))); evalcond[3]=(((new_r11*x422))+(((-1.0)*new_r01*x426))); evalcond[4]=((((-1.0)*x423*x424))+(((-1.0)*x423*x425))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j3array[2], cj3array[2], sj3array[2]; bool j3valid[2]={false}; _nj3 = 2; CheckValue<IkReal> x428 = IKatan2WithCheck(IkReal(new_r00),IkReal(new_r10),IKFAST_ATAN2_MAGTHRESH); if(!x428.valid){ continue; } IkReal x427=x428.value; j3array[0]=((-1.0)*x427); sj3array[0]=IKsin(j3array[0]); cj3array[0]=IKcos(j3array[0]); j3array[1]=((3.14159265358979)+(((-1.0)*x427))); sj3array[1]=IKsin(j3array[1]); cj3array[1]=IKcos(j3array[1]); if( j3array[0] > IKPI ) { j3array[0]-=IK2PI; } else if( j3array[0] < -IKPI ) { j3array[0]+=IK2PI; } j3valid[0] = true; if( j3array[1] > IKPI ) { j3array[1]-=IK2PI; } else if( j3array[1] < -IKPI ) { j3array[1]+=IK2PI; } j3valid[1] = true; for(int ij3 = 0; ij3 < 2; ++ij3) { if( !j3valid[ij3] ) { continue; } _ij3[0] = ij3; _ij3[1] = -1; for(int iij3 = ij3+1; iij3 < 2; ++iij3) { if( j3valid[iij3] && IKabs(cj3array[ij3]-cj3array[iij3]) < IKFAST_SOLUTION_THRESH && IKabs(sj3array[ij3]-sj3array[iij3]) < IKFAST_SOLUTION_THRESH ) { j3valid[iij3]=false; _ij3[1] = iij3; break; } } j3 = j3array[ij3]; cj3 = cj3array[ij3]; sj3 = sj3array[ij3]; { IkReal evalcond[5]; IkReal x429=IKcos(j3); IkReal x430=IKsin(j3); IkReal x431=((1.0)*x430); IkReal x432=(new_r22*x431); IkReal x433=((1.0)*new_r22*x429); evalcond[0]=(((new_r11*x430))+((new_r01*x429))); evalcond[1]=((((-1.0)*new_r00*x431))+((new_r10*x429))); evalcond[2]=((((-1.0)*new_r01*x431))+((new_r11*x429))); evalcond[3]=((((-1.0)*new_r00*x433))+(((-1.0)*new_r10*x432))); evalcond[4]=((((-1.0)*new_r01*x433))+(((-1.0)*new_r11*x432))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j3array[2], cj3array[2], sj3array[2]; bool j3valid[2]={false}; _nj3 = 2; CheckValue<IkReal> x435 = IKatan2WithCheck(IkReal(new_r01),IkReal(new_r11),IKFAST_ATAN2_MAGTHRESH); if(!x435.valid){ continue; } IkReal x434=x435.value; j3array[0]=((-1.0)*x434); sj3array[0]=IKsin(j3array[0]); cj3array[0]=IKcos(j3array[0]); j3array[1]=((3.14159265358979)+(((-1.0)*x434))); sj3array[1]=IKsin(j3array[1]); cj3array[1]=IKcos(j3array[1]); if( j3array[0] > IKPI ) { j3array[0]-=IK2PI; } else if( j3array[0] < -IKPI ) { j3array[0]+=IK2PI; } j3valid[0] = true; if( j3array[1] > IKPI ) { j3array[1]-=IK2PI; } else if( j3array[1] < -IKPI ) { j3array[1]+=IK2PI; } j3valid[1] = true; for(int ij3 = 0; ij3 < 2; ++ij3) { if( !j3valid[ij3] ) { continue; } _ij3[0] = ij3; _ij3[1] = -1; for(int iij3 = ij3+1; iij3 < 2; ++iij3) { if( j3valid[iij3] && IKabs(cj3array[ij3]-cj3array[iij3]) < IKFAST_SOLUTION_THRESH && IKabs(sj3array[ij3]-sj3array[iij3]) < IKFAST_SOLUTION_THRESH ) { j3valid[iij3]=false; _ij3[1] = iij3; break; } } j3 = j3array[ij3]; cj3 = cj3array[ij3]; sj3 = sj3array[ij3]; { IkReal evalcond[5]; IkReal x436=IKcos(j3); IkReal x437=IKsin(j3); IkReal x438=((1.0)*new_r22); IkReal x439=(new_r10*x437); IkReal x440=(new_r00*x436); IkReal x441=((1.0)*x437); evalcond[0]=(x439+x440); evalcond[1]=((((-1.0)*new_r00*x441))+((new_r10*x436))); evalcond[2]=((((-1.0)*new_r01*x441))+((new_r11*x436))); evalcond[3]=((((-1.0)*x438*x440))+(((-1.0)*x438*x439))); evalcond[4]=((((-1.0)*new_r01*x436*x438))+(((-1.0)*new_r11*x437*x438))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j3] } } while(0); if( bgotonextstatement ) { } } } } } } } } else { { IkReal j3array[1], cj3array[1], sj3array[1]; bool j3valid[1]={false}; _nj3 = 1; CheckValue<IkReal> x443=IKPowWithIntegerCheck(sj4,-1); if(!x443.valid){ continue; } IkReal x442=x443.value; CheckValue<IkReal> x444=IKPowWithIntegerCheck(cj5,-1); if(!x444.valid){ continue; } if( IKabs((x442*(x444.value)*(((((-1.0)*cj4*new_r02*sj5))+(((-1.0)*new_r01*sj4)))))) < IKFAST_ATAN2_MAGTHRESH && IKabs((new_r02*x442)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr((x442*(x444.value)*(((((-1.0)*cj4*new_r02*sj5))+(((-1.0)*new_r01*sj4))))))+IKsqr((new_r02*x442))-1) <= IKFAST_SINCOS_THRESH ) continue; j3array[0]=IKatan2((x442*(x444.value)*(((((-1.0)*cj4*new_r02*sj5))+(((-1.0)*new_r01*sj4))))), (new_r02*x442)); sj3array[0]=IKsin(j3array[0]); cj3array[0]=IKcos(j3array[0]); if( j3array[0] > IKPI ) { j3array[0]-=IK2PI; } else if( j3array[0] < -IKPI ) { j3array[0]+=IK2PI; } j3valid[0] = true; for(int ij3 = 0; ij3 < 1; ++ij3) { if( !j3valid[ij3] ) { continue; } _ij3[0] = ij3; _ij3[1] = -1; for(int iij3 = ij3+1; iij3 < 1; ++iij3) { if( j3valid[iij3] && IKabs(cj3array[ij3]-cj3array[iij3]) < IKFAST_SOLUTION_THRESH && IKabs(sj3array[ij3]-sj3array[iij3]) < IKFAST_SOLUTION_THRESH ) { j3valid[iij3]=false; _ij3[1] = iij3; break; } } j3 = j3array[ij3]; cj3 = cj3array[ij3]; sj3 = sj3array[ij3]; { IkReal evalcond[18]; IkReal x445=IKcos(j3); IkReal x446=IKsin(j3); IkReal x447=((1.0)*sj5); IkReal x448=((1.0)*cj4); IkReal x449=((1.0)*sj4); IkReal x450=(cj4*sj5); IkReal x451=(new_r10*x446); IkReal x452=(cj5*x445); IkReal x453=(cj5*x446); IkReal x454=(new_r11*x446); IkReal x455=(new_r01*x445); IkReal x456=(new_r02*x445); IkReal x457=(new_r12*x446); IkReal x458=(new_r00*x445); IkReal x459=((1.0)*x446); evalcond[0]=((((-1.0)*x445*x449))+new_r02); evalcond[1]=(new_r12+(((-1.0)*x446*x449))); evalcond[2]=(((new_r12*x445))+(((-1.0)*new_r02*x459))); evalcond[3]=(x453+((x445*x450))+new_r01); evalcond[4]=((((-1.0)*x449))+x456+x457); evalcond[5]=(x454+x455+x450); evalcond[6]=(((sj5*x446))+new_r00+(((-1.0)*x448*x452))); evalcond[7]=((((-1.0)*x452))+((x446*x450))+new_r11); evalcond[8]=((((-1.0)*x447))+(((-1.0)*new_r00*x459))+((new_r10*x445))); evalcond[9]=((((-1.0)*new_r01*x459))+((new_r11*x445))+(((-1.0)*cj5))); evalcond[10]=((((-1.0)*cj5*x448))+x458+x451); evalcond[11]=((((-1.0)*x445*x447))+new_r10+(((-1.0)*x448*x453))); evalcond[12]=(((new_r22*sj4))+(((-1.0)*x448*x456))+(((-1.0)*x448*x457))); evalcond[13]=((((-1.0)*new_r20*x448))+(((-1.0)*x449*x458))+(((-1.0)*x449*x451))); evalcond[14]=((((-1.0)*new_r21*x448))+(((-1.0)*x449*x454))+(((-1.0)*x449*x455))); evalcond[15]=(((new_r20*sj4))+cj5+(((-1.0)*x448*x451))+(((-1.0)*x448*x458))); evalcond[16]=((1.0)+(((-1.0)*x449*x456))+(((-1.0)*x449*x457))+(((-1.0)*new_r22*x448))); evalcond[17]=((((-1.0)*x447))+((new_r21*sj4))+(((-1.0)*x448*x454))+(((-1.0)*x448*x455))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[8]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[9]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[10]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[11]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[12]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[13]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[14]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[15]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[16]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[17]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j3array[1], cj3array[1], sj3array[1]; bool j3valid[1]={false}; _nj3 = 1; CheckValue<IkReal> x460=IKPowWithIntegerCheck(IKsign(sj4),-1); if(!x460.valid){ continue; } CheckValue<IkReal> x461 = IKatan2WithCheck(IkReal(new_r12),IkReal(new_r02),IKFAST_ATAN2_MAGTHRESH); if(!x461.valid){ continue; } j3array[0]=((-1.5707963267949)+(((1.5707963267949)*(x460.value)))+(x461.value)); sj3array[0]=IKsin(j3array[0]); cj3array[0]=IKcos(j3array[0]); if( j3array[0] > IKPI ) { j3array[0]-=IK2PI; } else if( j3array[0] < -IKPI ) { j3array[0]+=IK2PI; } j3valid[0] = true; for(int ij3 = 0; ij3 < 1; ++ij3) { if( !j3valid[ij3] ) { continue; } _ij3[0] = ij3; _ij3[1] = -1; for(int iij3 = ij3+1; iij3 < 1; ++iij3) { if( j3valid[iij3] && IKabs(cj3array[ij3]-cj3array[iij3]) < IKFAST_SOLUTION_THRESH && IKabs(sj3array[ij3]-sj3array[iij3]) < IKFAST_SOLUTION_THRESH ) { j3valid[iij3]=false; _ij3[1] = iij3; break; } } j3 = j3array[ij3]; cj3 = cj3array[ij3]; sj3 = sj3array[ij3]; { IkReal evalcond[18]; IkReal x462=IKcos(j3); IkReal x463=IKsin(j3); IkReal x464=((1.0)*sj5); IkReal x465=((1.0)*cj4); IkReal x466=((1.0)*sj4); IkReal x467=(cj4*sj5); IkReal x468=(new_r10*x463); IkReal x469=(cj5*x462); IkReal x470=(cj5*x463); IkReal x471=(new_r11*x463); IkReal x472=(new_r01*x462); IkReal x473=(new_r02*x462); IkReal x474=(new_r12*x463); IkReal x475=(new_r00*x462); IkReal x476=((1.0)*x463); evalcond[0]=((((-1.0)*x462*x466))+new_r02); evalcond[1]=((((-1.0)*x463*x466))+new_r12); evalcond[2]=(((new_r12*x462))+(((-1.0)*new_r02*x476))); evalcond[3]=(x470+new_r01+((x462*x467))); evalcond[4]=((((-1.0)*x466))+x474+x473); evalcond[5]=(x467+x471+x472); evalcond[6]=((((-1.0)*x465*x469))+new_r00+((sj5*x463))); evalcond[7]=(((x463*x467))+(((-1.0)*x469))+new_r11); evalcond[8]=(((new_r10*x462))+(((-1.0)*new_r00*x476))+(((-1.0)*x464))); evalcond[9]=(((new_r11*x462))+(((-1.0)*new_r01*x476))+(((-1.0)*cj5))); evalcond[10]=((((-1.0)*cj5*x465))+x468+x475); evalcond[11]=((((-1.0)*x462*x464))+new_r10+(((-1.0)*x465*x470))); evalcond[12]=(((new_r22*sj4))+(((-1.0)*x465*x474))+(((-1.0)*x465*x473))); evalcond[13]=((((-1.0)*x466*x468))+(((-1.0)*new_r20*x465))+(((-1.0)*x466*x475))); evalcond[14]=((((-1.0)*new_r21*x465))+(((-1.0)*x466*x472))+(((-1.0)*x466*x471))); evalcond[15]=((((-1.0)*x465*x468))+((new_r20*sj4))+cj5+(((-1.0)*x465*x475))); evalcond[16]=((1.0)+(((-1.0)*new_r22*x465))+(((-1.0)*x466*x473))+(((-1.0)*x466*x474))); evalcond[17]=((((-1.0)*x464))+((new_r21*sj4))+(((-1.0)*x465*x471))+(((-1.0)*x465*x472))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[8]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[9]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[10]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[11]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[12]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[13]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[14]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[15]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[16]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[17]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } } } } else { { IkReal j3array[1], cj3array[1], sj3array[1]; bool j3valid[1]={false}; _nj3 = 1; CheckValue<IkReal> x477=IKPowWithIntegerCheck(IKsign(sj4),-1); if(!x477.valid){ continue; } CheckValue<IkReal> x478 = IKatan2WithCheck(IkReal(new_r12),IkReal(new_r02),IKFAST_ATAN2_MAGTHRESH); if(!x478.valid){ continue; } j3array[0]=((-1.5707963267949)+(((1.5707963267949)*(x477.value)))+(x478.value)); sj3array[0]=IKsin(j3array[0]); cj3array[0]=IKcos(j3array[0]); if( j3array[0] > IKPI ) { j3array[0]-=IK2PI; } else if( j3array[0] < -IKPI ) { j3array[0]+=IK2PI; } j3valid[0] = true; for(int ij3 = 0; ij3 < 1; ++ij3) { if( !j3valid[ij3] ) { continue; } _ij3[0] = ij3; _ij3[1] = -1; for(int iij3 = ij3+1; iij3 < 1; ++iij3) { if( j3valid[iij3] && IKabs(cj3array[ij3]-cj3array[iij3]) < IKFAST_SOLUTION_THRESH && IKabs(sj3array[ij3]-sj3array[iij3]) < IKFAST_SOLUTION_THRESH ) { j3valid[iij3]=false; _ij3[1] = iij3; break; } } j3 = j3array[ij3]; cj3 = cj3array[ij3]; sj3 = sj3array[ij3]; { IkReal evalcond[8]; IkReal x479=IKcos(j3); IkReal x480=IKsin(j3); IkReal x481=((1.0)*sj4); IkReal x482=((1.0)*cj4); IkReal x483=(new_r12*x480); IkReal x484=(new_r02*x479); evalcond[0]=((((-1.0)*x479*x481))+new_r02); evalcond[1]=((((-1.0)*x480*x481))+new_r12); evalcond[2]=(((new_r12*x479))+(((-1.0)*new_r02*x480))); evalcond[3]=((((-1.0)*x481))+x483+x484); evalcond[4]=(((new_r22*sj4))+(((-1.0)*x482*x484))+(((-1.0)*x482*x483))); evalcond[5]=((((-1.0)*new_r10*x480*x481))+(((-1.0)*new_r20*x482))+(((-1.0)*new_r00*x479*x481))); evalcond[6]=((((-1.0)*new_r21*x482))+(((-1.0)*new_r11*x480*x481))+(((-1.0)*new_r01*x479*x481))); evalcond[7]=((1.0)+(((-1.0)*x481*x483))+(((-1.0)*x481*x484))+(((-1.0)*new_r22*x482))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { IkReal j5eval[3]; j5eval[0]=sj4; j5eval[1]=IKsign(sj4); j5eval[2]=((IKabs(new_r20))+(IKabs(new_r21))); if( IKabs(j5eval[0]) < 0.0000010000000000 || IKabs(j5eval[1]) < 0.0000010000000000 || IKabs(j5eval[2]) < 0.0000010000000000 ) { { IkReal j5eval[2]; j5eval[0]=sj3; j5eval[1]=sj4; if( IKabs(j5eval[0]) < 0.0000010000000000 || IKabs(j5eval[1]) < 0.0000010000000000 ) { { IkReal j5eval[3]; j5eval[0]=cj3; j5eval[1]=cj4; j5eval[2]=sj4; if( IKabs(j5eval[0]) < 0.0000010000000000 || IKabs(j5eval[1]) < 0.0000010000000000 || IKabs(j5eval[2]) < 0.0000010000000000 ) { { IkReal evalcond[5]; bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-1.5707963267949)+j3)))), 6.28318530717959))); evalcond[1]=new_r02; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5eval[3]; sj3=1.0; cj3=0; j3=1.5707963267949; j5eval[0]=sj4; j5eval[1]=IKsign(sj4); j5eval[2]=((IKabs(new_r20))+(IKabs(new_r21))); if( IKabs(j5eval[0]) < 0.0000010000000000 || IKabs(j5eval[1]) < 0.0000010000000000 || IKabs(j5eval[2]) < 0.0000010000000000 ) { { IkReal j5eval[3]; sj3=1.0; cj3=0; j3=1.5707963267949; j5eval[0]=cj4; j5eval[1]=IKsign(cj4); j5eval[2]=((IKabs(new_r11))+(IKabs(new_r10))); if( IKabs(j5eval[0]) < 0.0000010000000000 || IKabs(j5eval[1]) < 0.0000010000000000 || IKabs(j5eval[2]) < 0.0000010000000000 ) { { IkReal j5eval[1]; sj3=1.0; cj3=0; j3=1.5707963267949; j5eval[0]=sj4; if( IKabs(j5eval[0]) < 0.0000010000000000 ) { { IkReal evalcond[4]; bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(j4))), 6.28318530717959))); evalcond[1]=new_r20; evalcond[2]=new_r12; evalcond[3]=new_r21; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 && IKabs(evalcond[2]) < 0.0000050000000000 && IKabs(evalcond[3]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(((-1.0)*new_r11)) < IKFAST_ATAN2_MAGTHRESH && IKabs(new_r10) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((-1.0)*new_r11))+IKsqr(new_r10)-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((-1.0)*new_r11), new_r10); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[4]; IkReal x485=IKsin(j5); IkReal x486=((1.0)*(IKcos(j5))); evalcond[0]=(x485+new_r11); evalcond[1]=((((-1.0)*x486))+new_r10); evalcond[2]=((((-1.0)*x485))+(((-1.0)*new_r00))); evalcond[3]=((((-1.0)*x486))+(((-1.0)*new_r01))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-3.14159265358979)+j4)))), 6.28318530717959))); evalcond[1]=new_r20; evalcond[2]=new_r12; evalcond[3]=new_r21; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 && IKabs(evalcond[2]) < 0.0000050000000000 && IKabs(evalcond[3]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(new_r11) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r10)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(new_r11)+IKsqr(((-1.0)*new_r10))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(new_r11, ((-1.0)*new_r10)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[4]; IkReal x487=IKcos(j5); IkReal x488=((1.0)*(IKsin(j5))); evalcond[0]=(x487+new_r10); evalcond[1]=((((-1.0)*x488))+new_r11); evalcond[2]=((((-1.0)*x488))+(((-1.0)*new_r00))); evalcond[3]=((((-1.0)*x487))+(((-1.0)*new_r01))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-1.5707963267949)+j4)))), 6.28318530717959))); evalcond[1]=new_r22; evalcond[2]=new_r11; evalcond[3]=new_r10; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 && IKabs(evalcond[2]) < 0.0000050000000000 && IKabs(evalcond[3]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(new_r21) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r20)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(new_r21)+IKsqr(((-1.0)*new_r20))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(new_r21, ((-1.0)*new_r20)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[4]; IkReal x489=IKcos(j5); IkReal x490=((1.0)*(IKsin(j5))); evalcond[0]=(x489+new_r20); evalcond[1]=((((-1.0)*x490))+new_r21); evalcond[2]=((((-1.0)*x490))+(((-1.0)*new_r00))); evalcond[3]=((((-1.0)*x489))+(((-1.0)*new_r01))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((1.5707963267949)+j4)))), 6.28318530717959))); evalcond[1]=new_r22; evalcond[2]=new_r11; evalcond[3]=new_r10; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 && IKabs(evalcond[2]) < 0.0000050000000000 && IKabs(evalcond[3]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(((-1.0)*new_r21)) < IKFAST_ATAN2_MAGTHRESH && IKabs(new_r20) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((-1.0)*new_r21))+IKsqr(new_r20)-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((-1.0)*new_r21), new_r20); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[4]; IkReal x491=IKsin(j5); IkReal x492=((1.0)*(IKcos(j5))); evalcond[0]=(x491+new_r21); evalcond[1]=((((-1.0)*x492))+new_r20); evalcond[2]=((((-1.0)*x491))+(((-1.0)*new_r00))); evalcond[3]=((((-1.0)*x492))+(((-1.0)*new_r01))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((IKabs(new_r20))+(IKabs(new_r21))); if( IKabs(evalcond[0]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(((-1.0)*new_r00)) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r01)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((-1.0)*new_r00))+IKsqr(((-1.0)*new_r01))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((-1.0)*new_r00), ((-1.0)*new_r01)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[6]; IkReal x493=IKsin(j5); IkReal x494=IKcos(j5); evalcond[0]=x494; evalcond[1]=(new_r22*x493); evalcond[2]=((-1.0)*x493); evalcond[3]=((-1.0)*new_r22*x494); evalcond[4]=((((-1.0)*x493))+(((-1.0)*new_r00))); evalcond[5]=((((-1.0)*x494))+(((-1.0)*new_r01))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j5] } } while(0); if( bgotonextstatement ) { } } } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x495=IKPowWithIntegerCheck(sj4,-1); if(!x495.valid){ continue; } if( IKabs(((-1.0)*new_r00)) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r20*(x495.value))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((-1.0)*new_r00))+IKsqr(((-1.0)*new_r20*(x495.value)))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((-1.0)*new_r00), ((-1.0)*new_r20*(x495.value))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x496=IKsin(j5); IkReal x497=IKcos(j5); IkReal x498=((1.0)*cj4); IkReal x499=((1.0)*x496); evalcond[0]=(((sj4*x497))+new_r20); evalcond[1]=(((cj4*x496))+new_r11); evalcond[2]=((((-1.0)*sj4*x499))+new_r21); evalcond[3]=((((-1.0)*x497*x498))+new_r10); evalcond[4]=((((-1.0)*x499))+(((-1.0)*new_r00))); evalcond[5]=((((-1.0)*x497))+(((-1.0)*new_r01))); evalcond[6]=(((new_r20*sj4))+(((-1.0)*new_r10*x498))+x497); evalcond[7]=((((-1.0)*x499))+(((-1.0)*new_r11*x498))+((new_r21*sj4))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x500=IKPowWithIntegerCheck(IKsign(cj4),-1); if(!x500.valid){ continue; } CheckValue<IkReal> x501 = IKatan2WithCheck(IkReal(((-1.0)*new_r11)),IkReal(new_r10),IKFAST_ATAN2_MAGTHRESH); if(!x501.valid){ continue; } j5array[0]=((-1.5707963267949)+(((1.5707963267949)*(x500.value)))+(x501.value)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x502=IKsin(j5); IkReal x503=IKcos(j5); IkReal x504=((1.0)*cj4); IkReal x505=((1.0)*x502); evalcond[0]=(((sj4*x503))+new_r20); evalcond[1]=(((cj4*x502))+new_r11); evalcond[2]=((((-1.0)*sj4*x505))+new_r21); evalcond[3]=((((-1.0)*x503*x504))+new_r10); evalcond[4]=((((-1.0)*x505))+(((-1.0)*new_r00))); evalcond[5]=((((-1.0)*new_r01))+(((-1.0)*x503))); evalcond[6]=(((new_r20*sj4))+x503+(((-1.0)*new_r10*x504))); evalcond[7]=((((-1.0)*x505))+(((-1.0)*new_r11*x504))+((new_r21*sj4))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x506=IKPowWithIntegerCheck(IKsign(sj4),-1); if(!x506.valid){ continue; } CheckValue<IkReal> x507 = IKatan2WithCheck(IkReal(new_r21),IkReal(((-1.0)*new_r20)),IKFAST_ATAN2_MAGTHRESH); if(!x507.valid){ continue; } j5array[0]=((-1.5707963267949)+(((1.5707963267949)*(x506.value)))+(x507.value)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x508=IKsin(j5); IkReal x509=IKcos(j5); IkReal x510=((1.0)*cj4); IkReal x511=((1.0)*x508); evalcond[0]=(((sj4*x509))+new_r20); evalcond[1]=(((cj4*x508))+new_r11); evalcond[2]=(new_r21+(((-1.0)*sj4*x511))); evalcond[3]=(new_r10+(((-1.0)*x509*x510))); evalcond[4]=((((-1.0)*new_r00))+(((-1.0)*x511))); evalcond[5]=((((-1.0)*new_r01))+(((-1.0)*x509))); evalcond[6]=(((new_r20*sj4))+(((-1.0)*new_r10*x510))+x509); evalcond[7]=((((-1.0)*new_r11*x510))+((new_r21*sj4))+(((-1.0)*x511))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((1.5707963267949)+j3)))), 6.28318530717959))); evalcond[1]=new_r02; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(new_r00) < IKFAST_ATAN2_MAGTHRESH && IKabs(new_r01) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(new_r00)+IKsqr(new_r01)-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(new_r00, new_r01); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x512=IKcos(j5); IkReal x513=IKsin(j5); IkReal x514=((1.0)*x513); IkReal x515=((1.0)*x512); evalcond[0]=(((sj4*x512))+new_r20); evalcond[1]=(new_r00+(((-1.0)*x514))); evalcond[2]=(new_r01+(((-1.0)*x515))); evalcond[3]=(new_r21+(((-1.0)*sj4*x514))); evalcond[4]=(((cj4*x513))+(((-1.0)*new_r11))); evalcond[5]=((((-1.0)*new_r10))+(((-1.0)*cj4*x515))); evalcond[6]=(((new_r20*sj4))+((cj4*new_r10))+x512); evalcond[7]=(((cj4*new_r11))+((new_r21*sj4))+(((-1.0)*x514))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-1.5707963267949)+j4)))), 6.28318530717959))); evalcond[1]=new_r22; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(new_r21) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r20)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(new_r21)+IKsqr(((-1.0)*new_r20))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(new_r21, ((-1.0)*new_r20)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x516=IKcos(j5); IkReal x517=IKsin(j5); IkReal x518=((1.0)*sj3); IkReal x519=((1.0)*x517); IkReal x520=((1.0)*x516); evalcond[0]=(x516+new_r20); evalcond[1]=(new_r21+(((-1.0)*x519))); evalcond[2]=(((sj3*x516))+new_r01); evalcond[3]=(((sj3*x517))+new_r00); evalcond[4]=((((-1.0)*cj3*x520))+new_r11); evalcond[5]=((((-1.0)*new_r02*x519))+new_r10); evalcond[6]=(((cj3*new_r10))+(((-1.0)*new_r00*x518))+(((-1.0)*x519))); evalcond[7]=((((-1.0)*x520))+(((-1.0)*new_r01*x518))+((cj3*new_r11))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((1.5707963267949)+j4)))), 6.28318530717959))); evalcond[1]=new_r22; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(((-1.0)*new_r21)) < IKFAST_ATAN2_MAGTHRESH && IKabs(new_r20) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((-1.0)*new_r21))+IKsqr(new_r20)-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((-1.0)*new_r21), new_r20); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x521=IKcos(j5); IkReal x522=IKsin(j5); IkReal x523=((1.0)*sj3); IkReal x524=((1.0)*x521); evalcond[0]=(x522+new_r21); evalcond[1]=((((-1.0)*x524))+new_r20); evalcond[2]=(((sj3*x521))+new_r01); evalcond[3]=(((sj3*x522))+new_r00); evalcond[4]=(((new_r02*x522))+new_r10); evalcond[5]=((((-1.0)*cj3*x524))+new_r11); evalcond[6]=((((-1.0)*x522))+(((-1.0)*new_r00*x523))+((cj3*new_r10))); evalcond[7]=((((-1.0)*x524))+(((-1.0)*new_r01*x523))+((cj3*new_r11))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(j4))), 6.28318530717959))); evalcond[1]=new_r20; evalcond[2]=new_r02; evalcond[3]=new_r12; evalcond[4]=new_r21; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 && IKabs(evalcond[2]) < 0.0000050000000000 && IKabs(evalcond[3]) < 0.0000050000000000 && IKabs(evalcond[4]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; IkReal x525=((1.0)*new_r01); if( IKabs(((((-1.0)*cj3*x525))+(((-1.0)*new_r00*sj3)))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((((-1.0)*sj3*x525))+((cj3*new_r00)))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((((-1.0)*cj3*x525))+(((-1.0)*new_r00*sj3))))+IKsqr(((((-1.0)*sj3*x525))+((cj3*new_r00))))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((((-1.0)*cj3*x525))+(((-1.0)*new_r00*sj3))), ((((-1.0)*sj3*x525))+((cj3*new_r00)))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x526=IKsin(j5); IkReal x527=IKcos(j5); IkReal x528=((1.0)*sj3); IkReal x529=((1.0)*x527); IkReal x530=(sj3*x526); IkReal x531=((1.0)*x526); IkReal x532=(cj3*x529); evalcond[0]=(((new_r11*sj3))+x526+((cj3*new_r01))); evalcond[1]=(((sj3*x527))+new_r01+((cj3*x526))); evalcond[2]=(((new_r10*sj3))+(((-1.0)*x529))+((cj3*new_r00))); evalcond[3]=((((-1.0)*new_r00*x528))+(((-1.0)*x531))+((cj3*new_r10))); evalcond[4]=((((-1.0)*x529))+(((-1.0)*new_r01*x528))+((cj3*new_r11))); evalcond[5]=((((-1.0)*x532))+x530+new_r00); evalcond[6]=((((-1.0)*x532))+x530+new_r11); evalcond[7]=((((-1.0)*x527*x528))+(((-1.0)*cj3*x531))+new_r10); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-3.14159265358979)+j4)))), 6.28318530717959))); evalcond[1]=new_r20; evalcond[2]=new_r02; evalcond[3]=new_r12; evalcond[4]=new_r21; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 && IKabs(evalcond[2]) < 0.0000050000000000 && IKabs(evalcond[3]) < 0.0000050000000000 && IKabs(evalcond[4]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; IkReal x533=((1.0)*sj3); if( IKabs(((((-1.0)*new_r00*x533))+((cj3*new_r01)))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((((-1.0)*cj3*new_r00))+(((-1.0)*new_r01*x533)))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((((-1.0)*new_r00*x533))+((cj3*new_r01))))+IKsqr(((((-1.0)*cj3*new_r00))+(((-1.0)*new_r01*x533))))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((((-1.0)*new_r00*x533))+((cj3*new_r01))), ((((-1.0)*cj3*new_r00))+(((-1.0)*new_r01*x533)))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x534=IKsin(j5); IkReal x535=IKcos(j5); IkReal x536=((1.0)*sj3); IkReal x537=((1.0)*x534); IkReal x538=(sj3*x535); IkReal x539=((1.0)*x535); IkReal x540=(cj3*x537); evalcond[0]=(((new_r10*sj3))+x535+((cj3*new_r00))); evalcond[1]=(((new_r11*sj3))+(((-1.0)*x537))+((cj3*new_r01))); evalcond[2]=(((sj3*x534))+new_r00+((cj3*x535))); evalcond[3]=((((-1.0)*new_r00*x536))+(((-1.0)*x537))+((cj3*new_r10))); evalcond[4]=((((-1.0)*x539))+(((-1.0)*new_r01*x536))+((cj3*new_r11))); evalcond[5]=((((-1.0)*x540))+x538+new_r01); evalcond[6]=((((-1.0)*x540))+x538+new_r10); evalcond[7]=((((-1.0)*x534*x536))+(((-1.0)*cj3*x539))+new_r11); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(j3))), 6.28318530717959))); evalcond[1]=new_r12; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(new_r10) < IKFAST_ATAN2_MAGTHRESH && IKabs(new_r11) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(new_r10)+IKsqr(new_r11)-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(new_r10, new_r11); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x541=IKcos(j5); IkReal x542=IKsin(j5); IkReal x543=((1.0)*cj4); IkReal x544=((1.0)*x542); evalcond[0]=(((new_r02*x541))+new_r20); evalcond[1]=((((-1.0)*x544))+new_r10); evalcond[2]=((((-1.0)*x541))+new_r11); evalcond[3]=(((cj4*x542))+new_r01); evalcond[4]=(new_r21+(((-1.0)*new_r02*x544))); evalcond[5]=((((-1.0)*x541*x543))+new_r00); evalcond[6]=(((new_r20*sj4))+(((-1.0)*new_r00*x543))+x541); evalcond[7]=((((-1.0)*new_r01*x543))+(((-1.0)*x544))+((new_r21*sj4))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-3.14159265358979)+j3)))), 6.28318530717959))); evalcond[1]=new_r12; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5eval[3]; sj3=0; cj3=-1.0; j3=3.14159265358979; j5eval[0]=new_r02; j5eval[1]=IKsign(new_r02); j5eval[2]=((IKabs(new_r20))+(IKabs(new_r21))); if( IKabs(j5eval[0]) < 0.0000010000000000 || IKabs(j5eval[1]) < 0.0000010000000000 || IKabs(j5eval[2]) < 0.0000010000000000 ) { { IkReal j5eval[1]; sj3=0; cj3=-1.0; j3=3.14159265358979; j5eval[0]=new_r02; if( IKabs(j5eval[0]) < 0.0000010000000000 ) { { IkReal j5eval[2]; sj3=0; cj3=-1.0; j3=3.14159265358979; j5eval[0]=new_r02; j5eval[1]=cj4; if( IKabs(j5eval[0]) < 0.0000010000000000 || IKabs(j5eval[1]) < 0.0000010000000000 ) { { IkReal evalcond[4]; bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-1.5707963267949)+j4)))), 6.28318530717959))); evalcond[1]=new_r22; evalcond[2]=new_r01; evalcond[3]=new_r00; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 && IKabs(evalcond[2]) < 0.0000050000000000 && IKabs(evalcond[3]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(new_r21) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r20)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(new_r21)+IKsqr(((-1.0)*new_r20))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(new_r21, ((-1.0)*new_r20)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[4]; IkReal x545=IKcos(j5); IkReal x546=((1.0)*(IKsin(j5))); evalcond[0]=(x545+new_r20); evalcond[1]=((((-1.0)*x546))+new_r21); evalcond[2]=((((-1.0)*x546))+(((-1.0)*new_r10))); evalcond[3]=((((-1.0)*x545))+(((-1.0)*new_r11))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((1.5707963267949)+j4)))), 6.28318530717959))); evalcond[1]=new_r22; evalcond[2]=new_r01; evalcond[3]=new_r00; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 && IKabs(evalcond[2]) < 0.0000050000000000 && IKabs(evalcond[3]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(((-1.0)*new_r21)) < IKFAST_ATAN2_MAGTHRESH && IKabs(new_r20) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((-1.0)*new_r21))+IKsqr(new_r20)-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((-1.0)*new_r21), new_r20); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[4]; IkReal x547=IKsin(j5); IkReal x548=((1.0)*(IKcos(j5))); evalcond[0]=(x547+new_r21); evalcond[1]=((((-1.0)*x548))+new_r20); evalcond[2]=((((-1.0)*x547))+(((-1.0)*new_r10))); evalcond[3]=((((-1.0)*x548))+(((-1.0)*new_r11))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=IKabs(new_r02); evalcond[1]=new_r20; evalcond[2]=new_r21; if( IKabs(evalcond[0]) < 0.0000050000000000 && IKabs(evalcond[1]) < 0.0000050000000000 && IKabs(evalcond[2]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(((-1.0)*new_r10)) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*cj4*new_r00)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((-1.0)*new_r10))+IKsqr(((-1.0)*cj4*new_r00))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((-1.0)*new_r10), ((-1.0)*cj4*new_r00)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[6]; IkReal x549=IKcos(j5); IkReal x550=IKsin(j5); IkReal x551=((1.0)*x550); IkReal x552=((1.0)*x549); evalcond[0]=(((cj4*new_r00))+x549); evalcond[1]=((((-1.0)*x551))+(((-1.0)*new_r10))); evalcond[2]=((((-1.0)*x552))+(((-1.0)*new_r11))); evalcond[3]=(((cj4*x550))+(((-1.0)*new_r01))); evalcond[4]=(((cj4*new_r01))+(((-1.0)*x551))); evalcond[5]=((((-1.0)*new_r00))+(((-1.0)*cj4*x552))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((IKabs(new_r20))+(IKabs(new_r21))); if( IKabs(evalcond[0]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(((-1.0)*new_r10)) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r11)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((-1.0)*new_r10))+IKsqr(((-1.0)*new_r11))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((-1.0)*new_r10), ((-1.0)*new_r11)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[6]; IkReal x553=IKsin(j5); IkReal x554=IKcos(j5); evalcond[0]=x554; evalcond[1]=(new_r22*x553); evalcond[2]=((-1.0)*x553); evalcond[3]=((-1.0)*new_r22*x554); evalcond[4]=((((-1.0)*x553))+(((-1.0)*new_r10))); evalcond[5]=((((-1.0)*x554))+(((-1.0)*new_r11))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j5] } } while(0); if( bgotonextstatement ) { } } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x555=IKPowWithIntegerCheck(new_r02,-1); if(!x555.valid){ continue; } CheckValue<IkReal> x556=IKPowWithIntegerCheck(cj4,-1); if(!x556.valid){ continue; } if( IKabs(((-1.0)*new_r21*(x555.value))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r00*(x556.value))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((-1.0)*new_r21*(x555.value)))+IKsqr(((-1.0)*new_r00*(x556.value)))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((-1.0)*new_r21*(x555.value)), ((-1.0)*new_r00*(x556.value))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x557=IKsin(j5); IkReal x558=IKcos(j5); IkReal x559=((1.0)*x557); IkReal x560=((1.0)*x558); evalcond[0]=(((new_r02*x557))+new_r21); evalcond[1]=((((-1.0)*new_r02*x560))+new_r20); evalcond[2]=((((-1.0)*x559))+(((-1.0)*new_r10))); evalcond[3]=((((-1.0)*new_r11))+(((-1.0)*x560))); evalcond[4]=(((cj4*x557))+(((-1.0)*new_r01))); evalcond[5]=((((-1.0)*cj4*x560))+(((-1.0)*new_r00))); evalcond[6]=(((new_r20*sj4))+((cj4*new_r00))+x558); evalcond[7]=(((cj4*new_r01))+(((-1.0)*x559))+((new_r21*sj4))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x561=IKPowWithIntegerCheck(new_r02,-1); if(!x561.valid){ continue; } if( IKabs(((-1.0)*new_r10)) < IKFAST_ATAN2_MAGTHRESH && IKabs((new_r20*(x561.value))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((-1.0)*new_r10))+IKsqr((new_r20*(x561.value)))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((-1.0)*new_r10), (new_r20*(x561.value))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x562=IKsin(j5); IkReal x563=IKcos(j5); IkReal x564=((1.0)*x562); IkReal x565=((1.0)*x563); evalcond[0]=(((new_r02*x562))+new_r21); evalcond[1]=((((-1.0)*new_r02*x565))+new_r20); evalcond[2]=((((-1.0)*new_r10))+(((-1.0)*x564))); evalcond[3]=((((-1.0)*new_r11))+(((-1.0)*x565))); evalcond[4]=((((-1.0)*new_r01))+((cj4*x562))); evalcond[5]=((((-1.0)*cj4*x565))+(((-1.0)*new_r00))); evalcond[6]=(((new_r20*sj4))+((cj4*new_r00))+x563); evalcond[7]=(((cj4*new_r01))+((new_r21*sj4))+(((-1.0)*x564))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x566 = IKatan2WithCheck(IkReal(((-1.0)*new_r21)),IkReal(new_r20),IKFAST_ATAN2_MAGTHRESH); if(!x566.valid){ continue; } CheckValue<IkReal> x567=IKPowWithIntegerCheck(IKsign(new_r02),-1); if(!x567.valid){ continue; } j5array[0]=((-1.5707963267949)+(x566.value)+(((1.5707963267949)*(x567.value)))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x568=IKsin(j5); IkReal x569=IKcos(j5); IkReal x570=((1.0)*x568); IkReal x571=((1.0)*x569); evalcond[0]=(((new_r02*x568))+new_r21); evalcond[1]=((((-1.0)*new_r02*x571))+new_r20); evalcond[2]=((((-1.0)*x570))+(((-1.0)*new_r10))); evalcond[3]=((((-1.0)*x571))+(((-1.0)*new_r11))); evalcond[4]=((((-1.0)*new_r01))+((cj4*x568))); evalcond[5]=((((-1.0)*cj4*x571))+(((-1.0)*new_r00))); evalcond[6]=(((new_r20*sj4))+((cj4*new_r00))+x569); evalcond[7]=(((cj4*new_r01))+(((-1.0)*x570))+((new_r21*sj4))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((IKabs(new_r20))+(IKabs(new_r21))); if( IKabs(evalcond[0]) < 0.0000050000000000 ) { bgotonextstatement=false; { IkReal j5eval[1]; new_r21=0; new_r20=0; new_r02=0; new_r12=0; j5eval[0]=1.0; if( IKabs(j5eval[0]) < 0.0000000100000000 ) { continue; // no branches [j5] } else { IkReal op[2+1], zeror[2]; int numroots; op[0]=-1.0; op[1]=0; op[2]=1.0; polyroots2(op,zeror,numroots); IkReal j5array[2], cj5array[2], sj5array[2], tempj5array[1]; int numsolutions = 0; for(int ij5 = 0; ij5 < numroots; ++ij5) { IkReal htj5 = zeror[ij5]; tempj5array[0]=((2.0)*(atan(htj5))); for(int kj5 = 0; kj5 < 1; ++kj5) { j5array[numsolutions] = tempj5array[kj5]; if( j5array[numsolutions] > IKPI ) { j5array[numsolutions]-=IK2PI; } else if( j5array[numsolutions] < -IKPI ) { j5array[numsolutions]+=IK2PI; } sj5array[numsolutions] = IKsin(j5array[numsolutions]); cj5array[numsolutions] = IKcos(j5array[numsolutions]); numsolutions++; } } bool j5valid[2]={true,true}; _nj5 = 2; for(int ij5 = 0; ij5 < numsolutions; ++ij5) { if( !j5valid[ij5] ) { continue; } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; htj5 = IKtan(j5/2); _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < numsolutions; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j5] } } while(0); if( bgotonextstatement ) { } } } } } } } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x573=IKPowWithIntegerCheck(sj4,-1); if(!x573.valid){ continue; } IkReal x572=x573.value; CheckValue<IkReal> x574=IKPowWithIntegerCheck(cj3,-1); if(!x574.valid){ continue; } CheckValue<IkReal> x575=IKPowWithIntegerCheck(cj4,-1); if(!x575.valid){ continue; } if( IKabs((x572*(x574.value)*(x575.value)*((((new_r20*sj3))+(((-1.0)*new_r01*sj4)))))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r20*x572)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr((x572*(x574.value)*(x575.value)*((((new_r20*sj3))+(((-1.0)*new_r01*sj4))))))+IKsqr(((-1.0)*new_r20*x572))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2((x572*(x574.value)*(x575.value)*((((new_r20*sj3))+(((-1.0)*new_r01*sj4))))), ((-1.0)*new_r20*x572)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[12]; IkReal x576=IKsin(j5); IkReal x577=IKcos(j5); IkReal x578=(cj3*new_r00); IkReal x579=(cj3*cj4); IkReal x580=((1.0)*sj3); IkReal x581=((1.0)*x576); IkReal x582=(sj3*x576); IkReal x583=((1.0)*x577); evalcond[0]=(((sj4*x577))+new_r20); evalcond[1]=((((-1.0)*sj4*x581))+new_r21); evalcond[2]=(((new_r11*sj3))+((cj3*new_r01))+((cj4*x576))); evalcond[3]=(((cj3*new_r10))+(((-1.0)*x581))+(((-1.0)*new_r00*x580))); evalcond[4]=((((-1.0)*new_r01*x580))+((cj3*new_r11))+(((-1.0)*x583))); evalcond[5]=(((x576*x579))+((sj3*x577))+new_r01); evalcond[6]=(((new_r10*sj3))+(((-1.0)*cj4*x583))+x578); evalcond[7]=((((-1.0)*x579*x583))+x582+new_r00); evalcond[8]=(((cj4*x582))+new_r11+(((-1.0)*cj3*x583))); evalcond[9]=((((-1.0)*cj4*x577*x580))+new_r10+(((-1.0)*cj3*x581))); evalcond[10]=(((new_r20*sj4))+x577+(((-1.0)*cj4*x578))+(((-1.0)*cj4*new_r10*x580))); evalcond[11]=((((-1.0)*cj4*new_r11*x580))+((new_r21*sj4))+(((-1.0)*x581))+(((-1.0)*new_r01*x579))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[8]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[9]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[10]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[11]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x585=IKPowWithIntegerCheck(sj4,-1); if(!x585.valid){ continue; } IkReal x584=x585.value; CheckValue<IkReal> x586=IKPowWithIntegerCheck(sj3,-1); if(!x586.valid){ continue; } if( IKabs((x584*(x586.value)*(((((-1.0)*cj3*cj4*new_r20))+(((-1.0)*new_r00*sj4)))))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r20*x584)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr((x584*(x586.value)*(((((-1.0)*cj3*cj4*new_r20))+(((-1.0)*new_r00*sj4))))))+IKsqr(((-1.0)*new_r20*x584))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2((x584*(x586.value)*(((((-1.0)*cj3*cj4*new_r20))+(((-1.0)*new_r00*sj4))))), ((-1.0)*new_r20*x584)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[12]; IkReal x587=IKsin(j5); IkReal x588=IKcos(j5); IkReal x589=(cj3*new_r00); IkReal x590=(cj3*cj4); IkReal x591=((1.0)*sj3); IkReal x592=((1.0)*x587); IkReal x593=(sj3*x587); IkReal x594=((1.0)*x588); evalcond[0]=(((sj4*x588))+new_r20); evalcond[1]=((((-1.0)*sj4*x592))+new_r21); evalcond[2]=(((new_r11*sj3))+((cj4*x587))+((cj3*new_r01))); evalcond[3]=((((-1.0)*new_r00*x591))+(((-1.0)*x592))+((cj3*new_r10))); evalcond[4]=((((-1.0)*new_r01*x591))+(((-1.0)*x594))+((cj3*new_r11))); evalcond[5]=(((sj3*x588))+new_r01+((x587*x590))); evalcond[6]=((((-1.0)*cj4*x594))+((new_r10*sj3))+x589); evalcond[7]=((((-1.0)*x590*x594))+x593+new_r00); evalcond[8]=((((-1.0)*cj3*x594))+new_r11+((cj4*x593))); evalcond[9]=((((-1.0)*cj4*x588*x591))+(((-1.0)*cj3*x592))+new_r10); evalcond[10]=((((-1.0)*cj4*new_r10*x591))+((new_r20*sj4))+x588+(((-1.0)*cj4*x589))); evalcond[11]=((((-1.0)*cj4*new_r11*x591))+(((-1.0)*x592))+((new_r21*sj4))+(((-1.0)*new_r01*x590))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[8]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[9]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[10]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[11]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x595=IKPowWithIntegerCheck(IKsign(sj4),-1); if(!x595.valid){ continue; } CheckValue<IkReal> x596 = IKatan2WithCheck(IkReal(new_r21),IkReal(((-1.0)*new_r20)),IKFAST_ATAN2_MAGTHRESH); if(!x596.valid){ continue; } j5array[0]=((-1.5707963267949)+(((1.5707963267949)*(x595.value)))+(x596.value)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[12]; IkReal x597=IKsin(j5); IkReal x598=IKcos(j5); IkReal x599=(cj3*new_r00); IkReal x600=(cj3*cj4); IkReal x601=((1.0)*sj3); IkReal x602=((1.0)*x597); IkReal x603=(sj3*x597); IkReal x604=((1.0)*x598); evalcond[0]=(((sj4*x598))+new_r20); evalcond[1]=((((-1.0)*sj4*x602))+new_r21); evalcond[2]=(((new_r11*sj3))+((cj3*new_r01))+((cj4*x597))); evalcond[3]=(((cj3*new_r10))+(((-1.0)*x602))+(((-1.0)*new_r00*x601))); evalcond[4]=(((cj3*new_r11))+(((-1.0)*x604))+(((-1.0)*new_r01*x601))); evalcond[5]=(((x597*x600))+new_r01+((sj3*x598))); evalcond[6]=(((new_r10*sj3))+x599+(((-1.0)*cj4*x604))); evalcond[7]=((((-1.0)*x600*x604))+x603+new_r00); evalcond[8]=((((-1.0)*cj3*x604))+new_r11+((cj4*x603))); evalcond[9]=((((-1.0)*cj3*x602))+(((-1.0)*cj4*x598*x601))+new_r10); evalcond[10]=(((new_r20*sj4))+(((-1.0)*cj4*new_r10*x601))+x598+(((-1.0)*cj4*x599))); evalcond[11]=((((-1.0)*new_r01*x600))+(((-1.0)*x602))+((new_r21*sj4))+(((-1.0)*cj4*new_r11*x601))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[8]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[9]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[10]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[11]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } } } } } } }static inline void polyroots3(IkReal rawcoeffs[3+1], IkReal rawroots[3], int& numroots) { using std::complex; if( rawcoeffs[0] == 0 ) { // solve with one reduced degree polyroots2(&rawcoeffs[1], &rawroots[0], numroots); return; } IKFAST_ASSERT(rawcoeffs[0] != 0); const IkReal tol = 128.0*std::numeric_limits<IkReal>::epsilon(); const IkReal tolsqrt = sqrt(std::numeric_limits<IkReal>::epsilon()); complex<IkReal> coeffs[3]; const int maxsteps = 110; for(int i = 0; i < 3; ++i) { coeffs[i] = complex<IkReal>(rawcoeffs[i+1]/rawcoeffs[0]); } complex<IkReal> roots[3]; IkReal err[3]; roots[0] = complex<IkReal>(1,0); roots[1] = complex<IkReal>(0.4,0.9); // any complex number not a root of unity works err[0] = 1.0; err[1] = 1.0; for(int i = 2; i < 3; ++i) { roots[i] = roots[i-1]*roots[1]; err[i] = 1.0; } for(int step = 0; step < maxsteps; ++step) { bool changed = false; for(int i = 0; i < 3; ++i) { if ( err[i] >= tol ) { changed = true; // evaluate complex<IkReal> x = roots[i] + coeffs[0]; for(int j = 1; j < 3; ++j) { x = roots[i] * x + coeffs[j]; } for(int j = 0; j < 3; ++j) { if( i != j ) { if( roots[i] != roots[j] ) { x /= (roots[i] - roots[j]); } } } roots[i] -= x; err[i] = abs(x); } } if( !changed ) { break; } } numroots = 0; bool visited[3] = {false}; for(int i = 0; i < 3; ++i) { if( !visited[i] ) { // might be a multiple root, in which case it will have more error than the other roots // find any neighboring roots, and take the average complex<IkReal> newroot=roots[i]; int n = 1; for(int j = i+1; j < 3; ++j) { // care about error in real much more than imaginary if( abs(real(roots[i])-real(roots[j])) < tolsqrt && abs(imag(roots[i])-imag(roots[j])) < 0.002 ) { newroot += roots[j]; n += 1; visited[j] = true; } } if( n > 1 ) { newroot /= n; } // there are still cases where even the mean is not accurate enough, until a better multi-root algorithm is used, need to use the sqrt if( IKabs(imag(newroot)) < tolsqrt ) { rawroots[numroots++] = real(newroot); } } } } static inline void polyroots2(IkReal rawcoeffs[2+1], IkReal rawroots[2], int& numroots) { IkReal det = rawcoeffs[1]*rawcoeffs[1]-4*rawcoeffs[0]*rawcoeffs[2]; if( det < 0 ) { numroots=0; } else if( det == 0 ) { rawroots[0] = -0.5*rawcoeffs[1]/rawcoeffs[0]; numroots = 1; } else { det = IKsqrt(det); rawroots[0] = (-rawcoeffs[1]+det)/(2*rawcoeffs[0]); rawroots[1] = (-rawcoeffs[1]-det)/(2*rawcoeffs[0]);//rawcoeffs[2]/(rawcoeffs[0]*rawroots[0]); numroots = 2; } } static inline void polyroots4(IkReal rawcoeffs[4+1], IkReal rawroots[4], int& numroots) { using std::complex; if( rawcoeffs[0] == 0 ) { // solve with one reduced degree polyroots3(&rawcoeffs[1], &rawroots[0], numroots); return; } IKFAST_ASSERT(rawcoeffs[0] != 0); const IkReal tol = 128.0*std::numeric_limits<IkReal>::epsilon(); const IkReal tolsqrt = sqrt(std::numeric_limits<IkReal>::epsilon()); complex<IkReal> coeffs[4]; const int maxsteps = 110; for(int i = 0; i < 4; ++i) { coeffs[i] = complex<IkReal>(rawcoeffs[i+1]/rawcoeffs[0]); } complex<IkReal> roots[4]; IkReal err[4]; roots[0] = complex<IkReal>(1,0); roots[1] = complex<IkReal>(0.4,0.9); // any complex number not a root of unity works err[0] = 1.0; err[1] = 1.0; for(int i = 2; i < 4; ++i) { roots[i] = roots[i-1]*roots[1]; err[i] = 1.0; } for(int step = 0; step < maxsteps; ++step) { bool changed = false; for(int i = 0; i < 4; ++i) { if ( err[i] >= tol ) { changed = true; // evaluate complex<IkReal> x = roots[i] + coeffs[0]; for(int j = 1; j < 4; ++j) { x = roots[i] * x + coeffs[j]; } for(int j = 0; j < 4; ++j) { if( i != j ) { if( roots[i] != roots[j] ) { x /= (roots[i] - roots[j]); } } } roots[i] -= x; err[i] = abs(x); } } if( !changed ) { break; } } numroots = 0; bool visited[4] = {false}; for(int i = 0; i < 4; ++i) { if( !visited[i] ) { // might be a multiple root, in which case it will have more error than the other roots // find any neighboring roots, and take the average complex<IkReal> newroot=roots[i]; int n = 1; for(int j = i+1; j < 4; ++j) { // care about error in real much more than imaginary if( abs(real(roots[i])-real(roots[j])) < tolsqrt && abs(imag(roots[i])-imag(roots[j])) < 0.002 ) { newroot += roots[j]; n += 1; visited[j] = true; } } if( n > 1 ) { newroot /= n; } // there are still cases where even the mean is not accurate enough, until a better multi-root algorithm is used, need to use the sqrt if( IKabs(imag(newroot)) < tolsqrt ) { rawroots[numroots++] = real(newroot); } } } } }; /// solves the inverse kinematics equations. /// \param pfree is an array specifying the free joints of the chain. IKFAST_API bool ComputeIk(const IkReal* eetrans, const IkReal* eerot, const IkReal* pfree, IkSolutionListBase<IkReal>& solutions) { IKSolver solver; return solver.ComputeIk(eetrans,eerot,pfree,solutions); } IKFAST_API bool ComputeIk2(const IkReal* eetrans, const IkReal* eerot, const IkReal* pfree, IkSolutionListBase<IkReal>& solutions, void* pOpenRAVEManip) { IKSolver solver; return solver.ComputeIk(eetrans,eerot,pfree,solutions); } IKFAST_API const char* GetKinematicsHash() { return "c7adf74e994bc2268228960d140bc863"; } IKFAST_API const char* GetIkFastVersion() { return "0x1000004a"; } #ifdef IKFAST_NAMESPACE } // end namespace #endif #ifndef IKFAST_NO_MAIN #include <stdio.h> #include <stdlib.h> #ifdef IKFAST_NAMESPACE using namespace IKFAST_NAMESPACE; #endif int main(int argc, char** argv) { if( argc != 12+GetNumFreeParameters()+1 ) { printf("\nUsage: ./ik r00 r01 r02 t0 r10 r11 r12 t1 r20 r21 r22 t2 free0 ...\n\n" "Returns the ik solutions given the transformation of the end effector specified by\n" "a 3x3 rotation R (rXX), and a 3x1 translation (tX).\n" "There are %d free parameters that have to be specified.\n\n",GetNumFreeParameters()); return 1; } IkSolutionList<IkReal> solutions; std::vector<IkReal> vfree(GetNumFreeParameters()); IkReal eerot[9],eetrans[3]; eerot[0] = atof(argv[1]); eerot[1] = atof(argv[2]); eerot[2] = atof(argv[3]); eetrans[0] = atof(argv[4]); eerot[3] = atof(argv[5]); eerot[4] = atof(argv[6]); eerot[5] = atof(argv[7]); eetrans[1] = atof(argv[8]); eerot[6] = atof(argv[9]); eerot[7] = atof(argv[10]); eerot[8] = atof(argv[11]); eetrans[2] = atof(argv[12]); for(std::size_t i = 0; i < vfree.size(); ++i) vfree[i] = atof(argv[13+i]); bool bSuccess = ComputeIk(eetrans, eerot, vfree.size() > 0 ? &vfree[0] : NULL, solutions); if( !bSuccess ) { //fprintf(stderr,"Failed to get ik solution\n"); return -1; } printf("Found %d ik solutions:\n", (int)solutions.GetNumSolutions()); std::vector<IkReal> solvalues(GetNumJoints()); for(std::size_t i = 0; i < solutions.GetNumSolutions(); ++i) { const IkSolutionBase<IkReal>& sol = solutions.GetSolution(i); printf("sol%d (free=%d): ", (int)i, (int)sol.GetFree().size()); std::vector<IkReal> vsolfree(sol.GetFree().size()); sol.GetSolution(&solvalues[0],vsolfree.size()>0?&vsolfree[0]:NULL); for( std::size_t j = 0; j < solvalues.size(); ++j) printf("%.15f, ", solvalues[j]); printf("\n"); } return 0; } #endif
30.0395
874
0.651621
[ "object", "vector" ]
8e4a1910ac4fbe81661b9c74ca3e2fa96643455c
1,289
cpp
C++
Competitive Programming/CF_1370.cpp
Brabec/Hacktoberfest2020
d3a85850a462ab24abf59d68b5142e0b61b5ce37
[ "MIT" ]
null
null
null
Competitive Programming/CF_1370.cpp
Brabec/Hacktoberfest2020
d3a85850a462ab24abf59d68b5142e0b61b5ce37
[ "MIT" ]
null
null
null
Competitive Programming/CF_1370.cpp
Brabec/Hacktoberfest2020
d3a85850a462ab24abf59d68b5142e0b61b5ce37
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define int long long #define quickie ios_base::sync_with_stdio(false); cin.tie(NULL); #define rep(i, a, b) for(int i=a; i<b; i++) #define rep1(i, a, b) for(int i=a; i<=b; i++) #define repp(i, a, b) for(int i=b-1; i>=a; i--) #define pb push_back #define mp make_pair #define fi first #define se second #define bn begin() #define en end() #define SZ(x) ((int)(x).size()) #define db double #define mi map<int, int> #define vi vector<int> #define qi queue<int> #define MI(x) power(x, mod-2) #define test int t; cin >> t; #define mod 1000000007 #define pi 3.141592653589 using namespace std; int power(int x, int y) ; int gcd(int a, int b) ; signed main() { quickie int n ; cin >> n ; string s, t ; cin >> s >> t ; int a = 0, b = 0, c = 0 ; rep(i, 0, n) { if(s[i] == '0' && t[i] == '1') c++ ; if(s[i] == '1' && t[i] == '0') c-- ; a = max(a, c) ; b = min(b, c) ; } if(c != 0) cout << "-1\n" ; else cout << abs(a-b) << "\n" ; } int power(int x, int y) { int res = 1; x %= mod; while (y > 0) { if (y & 1) res = (res*x) % mod; y = y>>1; x = (x*x) % mod; } return res%mod; } int gcd(int a,int b){ if(a==0) return b; return gcd(b%a,a); }
21.847458
64
0.511249
[ "vector" ]
8e4e8da593463372382942416ca6e763a759c919
942
cc
C++
leetcode/binary-tree-postorder-traversal.cc
Waywrong/leetcode-solution
55115aeab4040f5ff84bdce6ffcfe4a98f879616
[ "MIT" ]
null
null
null
leetcode/binary-tree-postorder-traversal.cc
Waywrong/leetcode-solution
55115aeab4040f5ff84bdce6ffcfe4a98f879616
[ "MIT" ]
null
null
null
leetcode/binary-tree-postorder-traversal.cc
Waywrong/leetcode-solution
55115aeab4040f5ff84bdce6ffcfe4a98f879616
[ "MIT" ]
null
null
null
// Binary Tree Postorder Traversal /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> postorderTraversal(TreeNode* root) { vector<int> res; if (!root) return res; stack<TreeNode *> st; TreeNode *p = root, *prev = nullptr; while (p) { st.push(p); p = p->left; } while (!st.empty()) { p = st.top(); if (!p->right || p->right==prev) { st.pop(); res.push_back(p->val); prev = p; } else { p = p->right; while (p) { st.push(p); p = p->left; } } } return res; } };
23.55
59
0.401274
[ "vector" ]
8e51f611b90faa883979da5fbad80aa61704a502
21,451
cxx
C++
main/sc/source/filter/rtf/eeimpars.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sc/source/filter/rtf/eeimpars.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sc/source/filter/rtf/eeimpars.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * 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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_scfilt.hxx" //------------------------------------------------------------------------ #include "scitems.hxx" #include <editeng/eeitem.hxx> #include <editeng/adjitem.hxx> #include <editeng/editobj.hxx> #include <editeng/editview.hxx> #include <editeng/escpitem.hxx> #include <editeng/langitem.hxx> #include <svx/svdograf.hxx> #include <svx/svdpage.hxx> #include <editeng/scripttypeitem.hxx> #include <svtools/htmlcfg.hxx> #include <sfx2/sfxhtml.hxx> #include <svtools/parhtml.hxx> #include <svl/zforlist.hxx> #include <vcl/virdev.hxx> #include <vcl/svapp.hxx> #include <unotools/syslocale.hxx> #include <unotools/charclass.hxx> #include "eeimport.hxx" #include "global.hxx" #include "document.hxx" #include "editutil.hxx" #include "stlsheet.hxx" #include "docpool.hxx" #include "attrib.hxx" #include "patattr.hxx" #include "cell.hxx" #include "eeparser.hxx" #include "drwlayer.hxx" #include "rangenam.hxx" #include "progress.hxx" #include "globstr.hrc" // in fuins1.cxx extern void ScLimitSizeOnDrawPage( Size& rSize, Point& rPos, const Size& rPage ); //------------------------------------------------------------------------ ScEEImport::ScEEImport( ScDocument* pDocP, const ScRange& rRange ) : maRange( rRange ), mpDoc( pDocP ), mpParser( NULL ), mpRowHeights( new Table ) { const ScPatternAttr* pPattern = mpDoc->GetPattern( maRange.aStart.Col(), maRange.aStart.Row(), maRange.aStart.Tab() ); mpEngine = new ScTabEditEngine( *pPattern, mpDoc->GetEditPool() ); mpEngine->SetUpdateMode( sal_False ); mpEngine->EnableUndo( sal_False ); } ScEEImport::~ScEEImport() { // Reihenfolge wichtig, sonst knallt's irgendwann irgendwo in irgendeinem Dtor! // Ist gewaehrleistet, da ScEEImport Basisklasse ist delete mpEngine; // nach Parser! delete mpRowHeights; } sal_uLong ScEEImport::Read( SvStream& rStream, const String& rBaseURL ) { sal_uLong nErr = mpParser->Read( rStream, rBaseURL ); SCCOL nEndCol; SCROW nEndRow; mpParser->GetDimensions( nEndCol, nEndRow ); if ( nEndCol != 0 ) { nEndCol += maRange.aStart.Col() - 1; if ( nEndCol > MAXCOL ) nEndCol = MAXCOL; } else nEndCol = maRange.aStart.Col(); if ( nEndRow != 0 ) { nEndRow += maRange.aStart.Row() - 1; if ( nEndRow > MAXROW ) nEndRow = MAXROW; } else nEndRow = maRange.aStart.Row(); maRange.aEnd.Set( nEndCol, nEndRow, maRange.aStart.Tab() ); return nErr; } void ScEEImport::WriteToDocument( sal_Bool bSizeColsRows, double nOutputFactor, SvNumberFormatter* pFormatter, bool bConvertDate ) { ScProgress* pProgress = new ScProgress( mpDoc->GetDocumentShell(), ScGlobal::GetRscString( STR_LOAD_DOC ), mpParser->Count() ); sal_uLong nProgress = 0; SCCOL nStartCol, nEndCol; SCROW nStartRow, nEndRow; SCTAB nTab; SCROW nOverlapRowMax, nLastMergedRow; SCCOL nMergeColAdd; nStartCol = maRange.aStart.Col(); nStartRow = maRange.aStart.Row(); nTab = maRange.aStart.Tab(); nEndCol = maRange.aEnd.Col(); nEndRow = maRange.aEnd.Row(); nOverlapRowMax = 0; nMergeColAdd = 0; nLastMergedRow = SCROW_MAX; sal_Bool bHasGraphics = sal_False; ScEEParseEntry* pE; if (!pFormatter) pFormatter = mpDoc->GetFormatTable(); bool bNumbersEnglishUS = false; if (pFormatter->GetLanguage() == LANGUAGE_SYSTEM) { // Automatic language option selected. Check for the global 'use US English' option. SvxHtmlOptions aOpt; bNumbersEnglishUS = aOpt.IsNumbersEnglishUS(); } ScDocumentPool* pDocPool = mpDoc->GetPool(); ScRangeName* pRangeNames = mpDoc->GetRangeName(); for ( pE = mpParser->First(); pE; pE = mpParser->Next() ) { SCROW nRow = nStartRow + pE->nRow; if ( nRow != nLastMergedRow ) nMergeColAdd = 0; SCCOL nCol = nStartCol + pE->nCol + nMergeColAdd; // RowMerge feststellen, pures ColMerge und ColMerge der ersten // MergeRow bereits beim parsen if ( nRow <= nOverlapRowMax ) { while ( nCol <= MAXCOL && mpDoc->HasAttrib( nCol, nRow, nTab, nCol, nRow, nTab, HASATTR_OVERLAPPED ) ) { nCol++; nMergeColAdd++; } nLastMergedRow = nRow; } // fuer zweiten Durchlauf eintragen pE->nCol = nCol; pE->nRow = nRow; if ( ValidCol(nCol) && ValidRow(nRow) ) { SfxItemSet aSet = mpEngine->GetAttribs( pE->aSel ); // Default raus, wir setzen selber links/rechts je nachdem ob Text // oder Zahl; EditView.GetAttribs liefert immer kompletten Set // mit Defaults aufgefuellt const SfxPoolItem& rItem = aSet.Get( EE_PARA_JUST ); if ( ((const SvxAdjustItem&)rItem).GetAdjust() == SVX_ADJUST_LEFT ) aSet.ClearItem( EE_PARA_JUST ); // Testen, ob einfacher String ohne gemischte Attribute sal_Bool bSimple = ( pE->aSel.nStartPara == pE->aSel.nEndPara ); for (sal_uInt16 nId = EE_CHAR_START; nId <= EE_CHAR_END && bSimple; nId++) { const SfxPoolItem* pItem = 0; SfxItemState eState = aSet.GetItemState( nId, sal_True, &pItem ); if (eState == SFX_ITEM_DONTCARE) bSimple = sal_False; else if (eState == SFX_ITEM_SET) { if ( nId == EE_CHAR_ESCAPEMENT ) // Hoch-/Tiefstellen immer ueber EE { if ( (SvxEscapement)((const SvxEscapementItem*)pItem)->GetEnumValue() != SVX_ESCAPEMENT_OFF ) bSimple = sal_False; } } } if ( bSimple ) { // Feldbefehle enthalten? SfxItemState eFieldState = aSet.GetItemState( EE_FEATURE_FIELD, sal_False ); if ( eFieldState == SFX_ITEM_DONTCARE || eFieldState == SFX_ITEM_SET ) bSimple = sal_False; } // HTML String aValStr, aNumStr; double fVal; sal_uInt32 nNumForm = 0; LanguageType eNumLang = LANGUAGE_NONE; if ( pE->pNumStr ) { // SDNUM muss sein wenn SDVAL aNumStr = *pE->pNumStr; if ( pE->pValStr ) aValStr = *pE->pValStr; fVal = SfxHTMLParser::GetTableDataOptionsValNum( nNumForm, eNumLang, aValStr, aNumStr, *pFormatter ); } // Attribute setzen ScPatternAttr aAttr( pDocPool ); aAttr.GetFromEditItemSet( &aSet ); SfxItemSet& rSet = aAttr.GetItemSet(); if ( aNumStr.Len() ) { rSet.Put( SfxUInt32Item( ATTR_VALUE_FORMAT, nNumForm ) ); rSet.Put( SvxLanguageItem( eNumLang, ATTR_LANGUAGE_FORMAT ) ); } const SfxItemSet& rESet = pE->aItemSet; if ( rESet.Count() ) { const SfxPoolItem* pItem; if ( rESet.GetItemState( ATTR_BACKGROUND, sal_False, &pItem) == SFX_ITEM_SET ) rSet.Put( *pItem ); if ( rESet.GetItemState( ATTR_BORDER, sal_False, &pItem) == SFX_ITEM_SET ) rSet.Put( *pItem ); if ( rESet.GetItemState( ATTR_SHADOW, sal_False, &pItem) == SFX_ITEM_SET ) rSet.Put( *pItem ); // HTML if ( rESet.GetItemState( ATTR_HOR_JUSTIFY, sal_False, &pItem) == SFX_ITEM_SET ) rSet.Put( *pItem ); if ( rESet.GetItemState( ATTR_VER_JUSTIFY, sal_False, &pItem) == SFX_ITEM_SET ) rSet.Put( *pItem ); if ( rESet.GetItemState( ATTR_LINEBREAK, sal_False, &pItem) == SFX_ITEM_SET ) rSet.Put( *pItem ); if ( rESet.GetItemState( ATTR_FONT_COLOR, sal_False, &pItem) == SFX_ITEM_SET ) rSet.Put( *pItem ); if ( rESet.GetItemState( ATTR_FONT_UNDERLINE, sal_False, &pItem) == SFX_ITEM_SET ) rSet.Put( *pItem ); // HTML LATIN/CJK/CTL script type dependent const SfxPoolItem* pFont; if ( rESet.GetItemState( ATTR_FONT, sal_False, &pFont) != SFX_ITEM_SET ) pFont = 0; const SfxPoolItem* pHeight; if ( rESet.GetItemState( ATTR_FONT_HEIGHT, sal_False, &pHeight) != SFX_ITEM_SET ) pHeight = 0; const SfxPoolItem* pWeight; if ( rESet.GetItemState( ATTR_FONT_WEIGHT, sal_False, &pWeight) != SFX_ITEM_SET ) pWeight = 0; const SfxPoolItem* pPosture; if ( rESet.GetItemState( ATTR_FONT_POSTURE, sal_False, &pPosture) != SFX_ITEM_SET ) pPosture = 0; if ( pFont || pHeight || pWeight || pPosture ) { String aStr( mpEngine->GetText( pE->aSel ) ); sal_uInt8 nScriptType = mpDoc->GetStringScriptType( aStr ); const sal_uInt8 nScripts[3] = { SCRIPTTYPE_LATIN, SCRIPTTYPE_ASIAN, SCRIPTTYPE_COMPLEX }; for ( sal_uInt8 i=0; i<3; ++i ) { if ( nScriptType & nScripts[i] ) { if ( pFont ) rSet.Put( *pFont, ScGlobal::GetScriptedWhichID( nScripts[i], ATTR_FONT )); if ( pHeight ) rSet.Put( *pHeight, ScGlobal::GetScriptedWhichID( nScripts[i], ATTR_FONT_HEIGHT )); if ( pWeight ) rSet.Put( *pWeight, ScGlobal::GetScriptedWhichID( nScripts[i], ATTR_FONT_WEIGHT )); if ( pPosture ) rSet.Put( *pPosture, ScGlobal::GetScriptedWhichID( nScripts[i], ATTR_FONT_POSTURE )); } } } } if ( pE->nColOverlap > 1 || pE->nRowOverlap > 1 ) { // merged cells, mit SfxItemSet Put schneller als mit // nachtraeglichem ScDocument DoMerge ScMergeAttr aMerge( pE->nColOverlap, pE->nRowOverlap ); rSet.Put( aMerge ); SCROW nRO = 0; if ( pE->nColOverlap > 1 ) mpDoc->ApplyFlagsTab( nCol+1, nRow, nCol + pE->nColOverlap - 1, nRow, nTab, SC_MF_HOR ); if ( pE->nRowOverlap > 1 ) { nRO = nRow + pE->nRowOverlap - 1; mpDoc->ApplyFlagsTab( nCol, nRow+1, nCol, nRO , nTab, SC_MF_VER ); if ( nRO > nOverlapRowMax ) nOverlapRowMax = nRO; } if ( pE->nColOverlap > 1 && pE->nRowOverlap > 1 ) mpDoc->ApplyFlagsTab( nCol+1, nRow+1, nCol + pE->nColOverlap - 1, nRO, nTab, SC_MF_HOR | SC_MF_VER ); } const ScStyleSheet* pStyleSheet = mpDoc->GetPattern( nCol, nRow, nTab )->GetStyleSheet(); aAttr.SetStyleSheet( (ScStyleSheet*)pStyleSheet ); mpDoc->SetPattern( nCol, nRow, nTab, aAttr, sal_True ); // Daten eintragen if (bSimple) { if ( aValStr.Len() ) mpDoc->SetValue( nCol, nRow, nTab, fVal ); else if ( !pE->aSel.HasRange() ) { // maybe ALT text of IMG or similar mpDoc->SetString( nCol, nRow, nTab, pE->aAltText, pFormatter ); // wenn SelRange komplett leer kann nachfolgender Text im gleichen Absatz liegen! } else { String aStr; if( pE->bEntirePara ) { aStr = mpEngine->GetText( pE->aSel.nStartPara ); } else { aStr = mpEngine->GetText( pE->aSel ); aStr.EraseLeadingAndTrailingChars(); } // TODO: RTF import should follow the language tag, // currently this follows the HTML options for both, HTML // and RTF. bool bEnUsRecognized = false; if (bNumbersEnglishUS) { pFormatter->ChangeIntl( LANGUAGE_ENGLISH_US); sal_uInt32 nIndex = pFormatter->GetStandardIndex( LANGUAGE_ENGLISH_US); double fEnVal = 0.0; if (pFormatter->IsNumberFormat( aStr, nIndex, fEnVal)) { bEnUsRecognized = true; sal_uInt32 nNewIndex = pFormatter->GetFormatForLanguageIfBuiltIn( nIndex, LANGUAGE_SYSTEM); DBG_ASSERT( nNewIndex != nIndex, "ScEEImport::WriteToDocument: NumbersEnglishUS not a built-in format?"); pFormatter->GetInputLineString( fEnVal, nNewIndex, aStr); } pFormatter->ChangeIntl( LANGUAGE_SYSTEM); } // #105460#, #i4180# String cells can't contain tabs or linebreaks // -> replace with spaces aStr.SearchAndReplaceAll( (sal_Unicode)'\t', (sal_Unicode)' ' ); aStr.SearchAndReplaceAll( (sal_Unicode)'\n', (sal_Unicode)' ' ); if (bNumbersEnglishUS && !bEnUsRecognized) mpDoc->PutCell( nCol, nRow, nTab, new ScStringCell( aStr)); else mpDoc->SetString( nCol, nRow, nTab, aStr, pFormatter, bConvertDate ); } } else { EditTextObject* pObject = mpEngine->CreateTextObject( pE->aSel ); mpDoc->PutCell( nCol, nRow, nTab, new ScEditCell( pObject, mpDoc, mpEngine->GetEditTextObjectPool() ) ); delete pObject; } if ( pE->pImageList ) bHasGraphics |= GraphicSize( nCol, nRow, nTab, pE ); if ( pE->pName ) { // Anchor Name => RangeName sal_uInt16 nIndex; if ( !pRangeNames->SearchName( *pE->pName, nIndex ) ) { ScRangeData* pData = new ScRangeData( mpDoc, *pE->pName, ScAddress( nCol, nRow, nTab ) ); pRangeNames->Insert( pData ); } } } pProgress->SetStateOnPercent( ++nProgress ); } if ( bSizeColsRows ) { // Spaltenbreiten Table* pColWidths = mpParser->GetColWidths(); if ( pColWidths->Count() ) { nProgress = 0; pProgress->SetState( nProgress, nEndCol - nStartCol + 1 ); for ( SCCOL nCol = nStartCol; nCol <= nEndCol; nCol++ ) { sal_uInt16 nWidth = (sal_uInt16)(sal_uLong) pColWidths->Get( nCol ); if ( nWidth ) mpDoc->SetColWidth( nCol, nTab, nWidth ); pProgress->SetState( ++nProgress ); } } DELETEZ( pProgress ); // SetOptimalHeight hat seinen eigenen ProgressBar // Zeilenhoehen anpassen, Basis 100% Zoom Fraction aZoom( 1, 1 ); double nPPTX = ScGlobal::nScreenPPTX * (double) aZoom / nOutputFactor; // Faktor ist Drucker zu Bildschirm double nPPTY = ScGlobal::nScreenPPTY * (double) aZoom; VirtualDevice aVirtDev; mpDoc->SetOptimalHeight( 0, nEndRow, 0, static_cast< sal_uInt16 >( ScGlobal::nLastRowHeightExtra ), &aVirtDev, nPPTX, nPPTY, aZoom, aZoom, sal_False ); if ( mpRowHeights->Count() ) { for ( SCROW nRow = nStartRow; nRow <= nEndRow; nRow++ ) { sal_uInt16 nHeight = (sal_uInt16)(sal_uLong) mpRowHeights->Get( nRow ); if ( nHeight > mpDoc->GetRowHeight( nRow, nTab ) ) mpDoc->SetRowHeight( nRow, nTab, nHeight ); } } } if ( bHasGraphics ) { // Grafiken einfuegen for ( pE = mpParser->First(); pE; pE = mpParser->Next() ) { if ( pE->pImageList ) { SCCOL nCol = pE->nCol; SCROW nRow = pE->nRow; if ( ValidCol(nCol) && ValidRow(nRow) ) InsertGraphic( nCol, nRow, nTab, pE ); } } } if ( pProgress ) delete pProgress; } sal_Bool ScEEImport::GraphicSize( SCCOL nCol, SCROW nRow, SCTAB /*nTab*/, ScEEParseEntry* pE ) { ScHTMLImageList* pIL = pE->pImageList; if ( !pIL || !pIL->Count() ) return sal_False; sal_Bool bHasGraphics = sal_False; OutputDevice* pDefaultDev = Application::GetDefaultDevice(); long nWidth, nHeight; nWidth = nHeight = 0; sal_Char nDir = nHorizontal; for ( ScHTMLImage* pI = pIL->First(); pI; pI = pIL->Next() ) { if ( pI->pGraphic ) bHasGraphics = sal_True; Size aSizePix = pI->aSize; aSizePix.Width() += 2 * pI->aSpace.X(); aSizePix.Height() += 2 * pI->aSpace.Y(); Size aLogicSize = pDefaultDev->PixelToLogic( aSizePix, MapMode( MAP_TWIP ) ); if ( nDir & nHorizontal ) nWidth += aLogicSize.Width(); else if ( nWidth < aLogicSize.Width() ) nWidth = aLogicSize.Width(); if ( nDir & nVertical ) nHeight += aLogicSize.Height(); else if ( nHeight < aLogicSize.Height() ) nHeight = aLogicSize.Height(); nDir = pI->nDir; } // Spaltenbreiten Table* pColWidths = mpParser->GetColWidths(); long nThisWidth = (long) pColWidths->Get( nCol ); long nColWidths = nThisWidth; SCCOL nColSpanCol = nCol + pE->nColOverlap; for ( SCCOL nC = nCol + 1; nC < nColSpanCol; nC++ ) { nColWidths += (long) pColWidths->Get( nC ); } if ( nWidth > nColWidths ) { // Differenz nur in der ersten Spalte eintragen if ( nThisWidth ) pColWidths->Replace( nCol, (void*)(nWidth - nColWidths + nThisWidth) ); else pColWidths->Insert( nCol, (void*)(nWidth - nColWidths) ); } // Zeilenhoehen, Differenz auf alle betroffenen Zeilen verteilen SCROW nRowSpan = pE->nRowOverlap; nHeight /= nRowSpan; if ( nHeight == 0 ) nHeight = 1; // fuer eindeutigen Vergleich for ( SCROW nR = nRow; nR < nRow + nRowSpan; nR++ ) { long nRowHeight = (long) mpRowHeights->Get( nR ); if ( nHeight > nRowHeight ) { if ( nRowHeight ) mpRowHeights->Replace( nR, (void*)nHeight ); else mpRowHeights->Insert( nR, (void*)nHeight ); } } return bHasGraphics; } void ScEEImport::InsertGraphic( SCCOL nCol, SCROW nRow, SCTAB nTab, ScEEParseEntry* pE ) { ScHTMLImageList* pIL = pE->pImageList; if ( !pIL || !pIL->Count() ) return ; ScDrawLayer* pModel = mpDoc->GetDrawLayer(); if (!pModel) { mpDoc->InitDrawLayer(); pModel = mpDoc->GetDrawLayer(); } SdrPage* pPage = pModel->GetPage( static_cast<sal_uInt16>(nTab) ); OutputDevice* pDefaultDev = Application::GetDefaultDevice(); Point aCellInsertPos( (long)((double) mpDoc->GetColOffset( nCol, nTab ) * HMM_PER_TWIPS), (long)((double) mpDoc->GetRowOffset( nRow, nTab ) * HMM_PER_TWIPS) ); Point aInsertPos( aCellInsertPos ); Point aSpace; Size aLogicSize; sal_Char nDir = nHorizontal; for ( ScHTMLImage* pI = pIL->First(); pI; pI = pIL->Next() ) { if ( nDir & nHorizontal ) { // horizontal aInsertPos.X() += aLogicSize.Width(); aInsertPos.X() += aSpace.X(); aInsertPos.Y() = aCellInsertPos.Y(); } else { // vertikal aInsertPos.X() = aCellInsertPos.X(); aInsertPos.Y() += aLogicSize.Height(); aInsertPos.Y() += aSpace.Y(); } // Offset des Spacings drauf aSpace = pDefaultDev->PixelToLogic( pI->aSpace, MapMode( MAP_100TH_MM ) ); aInsertPos += aSpace; Size aSizePix = pI->aSize; aLogicSize = pDefaultDev->PixelToLogic( aSizePix, MapMode( MAP_100TH_MM ) ); // Groesse begrenzen ::ScLimitSizeOnDrawPage( aLogicSize, aInsertPos, pPage->GetSize() ); if ( pI->pGraphic ) { Rectangle aRect ( aInsertPos, aLogicSize ); SdrGrafObj* pObj = new SdrGrafObj( *pI->pGraphic, aRect ); // #118522# calling SetGraphicLink here doesn't work pObj->SetName( pI->aURL ); pPage->InsertObject( pObj ); // #118522# SetGraphicLink has to be used after inserting the object, // otherwise an empty graphic is swapped in and the contact stuff crashes. // See #i37444#. pObj->SetGraphicLink( pI->aURL, pI->aFilterName ); pObj->SetLogicRect( aRect ); // erst nach InsertObject !!! } nDir = pI->nDir; } } ScEEParser::ScEEParser( EditEngine* pEditP ) : pEdit( pEditP ), pPool( EditEngine::CreatePool() ), pDocPool( new ScDocumentPool ), pList( new ScEEParseList ), pColWidths( new Table ), nLastToken(0), nColCnt(0), nRowCnt(0), nColMax(0), nRowMax(0) { // pPool wird spaeter bei RTFIMP_START dem SvxRTFParser untergejubelt pPool->SetSecondaryPool( pDocPool ); pPool->FreezeIdRanges(); NewActEntry( NULL ); } ScEEParser::~ScEEParser() { delete pActEntry; delete pColWidths; for ( ScEEParseEntry* pE = pList->First(); pE; pE = pList->Next() ) delete pE; delete pList; // Pool erst loeschen nachdem die Listen geloescht wurden pPool->SetSecondaryPool( NULL ); SfxItemPool::Free(pDocPool); SfxItemPool::Free(pPool); } void ScEEParser::NewActEntry( ScEEParseEntry* pE ) { // neuer freifliegender pActEntry pActEntry = new ScEEParseEntry( pPool ); pActEntry->aSel.nStartPara = (pE ? pE->aSel.nEndPara + 1 : 0); pActEntry->aSel.nStartPos = 0; }
33.887836
133
0.603422
[ "object" ]
8e5686991e2490e71f68972467aa7660af1d5959
2,862
cpp
C++
Source/cpp/question3.cpp
FWdarling/DS_homework
26f43a25aba400c214855a57b4e87fa53ae51d97
[ "MIT" ]
null
null
null
Source/cpp/question3.cpp
FWdarling/DS_homework
26f43a25aba400c214855a57b4e87fa53ae51d97
[ "MIT" ]
null
null
null
Source/cpp/question3.cpp
FWdarling/DS_homework
26f43a25aba400c214855a57b4e87fa53ae51d97
[ "MIT" ]
null
null
null
#include"../../Lab/vector.h" using std::cin; using std::cout; using std::endl; using std::pair; typedef pair<int32_t, int32_t> Point; void input(Vector<Vector<char> >& maze, Vector<Vector<Point> >& next, const int32_t row_size, const int32_t col_size,Point& start, Point& end){ char static_maze[10][11] = { "##########", "#XX XX XX#", "#XX X#", "# XXXXX#", "#XX XX#", "# X XXXX#", "#XXX XX#", "#XXXX #", "#XXX XXXX#", "##########" }; start = {1, 3}; end = {7, 8}; for(int32_t i = 0; i < row_size; i++){ for(int32_t j = 0; j < col_size; j++){ maze[i].push_back(static_maze[i][j]); Point p = {i, j}; next[i].push_back(p); } } } void produce(Vector<Vector<char> >& maze, Vector<Vector<Point> >& next, Point& start, Point& end){ const int32_t row_size = 10; const int32_t col_size = 10; for(int32_t i = 0; i < row_size; i++){ Vector<char> row(col_size); maze.push_back(row); Vector<Point> next_row(col_size); next.push_back(next_row); } input(maze, next, row_size, col_size, start, end); } void display(Vector<Vector<char> >& maze){ int32_t row_size = maze.get_len(); int32_t col_size = maze[0].get_len(); for(int32_t i = 0; i < row_size; i++){ for(int32_t j = 0; j < col_size; j++){ cout << maze[i][j]; } cout << endl; } } bool dfs(Vector<Vector<char> >& maze, Vector<Vector<Point> >& next,Point current_point, Point end){ if(current_point == end) return true; const int32_t dir[4][2] = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}}; for(int32_t i = 0; i < 4; i++){ int32_t x = current_point.first + dir[i][0]; int32_t y = current_point.second + dir[i][1]; if(maze[x][y] == ' ' && next[x][y] == (Point){x, y}) { next[current_point.first][current_point.second] = (Point){x, y}; if(dfs(maze, next, (Point){x, y}, end)) return true; } } return false; } void print_point(Point point){ cout << "(" << point.first << ", " << point.second << ") "; } void print(Vector<Vector<Point> >& next, Point& start, Point& end){ Point current_point = start; while(current_point != end){ int32_t x = current_point.first, y = current_point.second; print_point(current_point); cout << "-> "; current_point = next[x][y]; } print_point(current_point); cout << endl; } int main(){ Vector<Vector<char> > maze; Vector<Vector<Point> > next; Point start, end; produce(maze, next, start, end); display(maze); if(dfs(maze, next, start, end)){ print(next, start, end); }else{ cout << "The maze is unsolvable!" << endl; } }
28.62
99
0.530748
[ "vector" ]
8e60418d1a80ea770b3b61329a170ab23c3cb5f7
3,175
cpp
C++
Sources/Materials/DefaultMaterial.cpp
CarysT/Acid
ab81fd13ab288ceaa152e0f64f6d97daf032fc19
[ "MIT" ]
977
2019-05-23T01:53:42.000Z
2022-03-30T04:22:41.000Z
Sources/Materials/DefaultMaterial.cpp
CarysT/Acid
ab81fd13ab288ceaa152e0f64f6d97daf032fc19
[ "MIT" ]
44
2019-06-02T17:30:32.000Z
2022-03-27T14:22:40.000Z
Sources/Materials/DefaultMaterial.cpp
CarysT/Acid
ab81fd13ab288ceaa152e0f64f6d97daf032fc19
[ "MIT" ]
121
2019-05-23T05:18:01.000Z
2022-03-27T21:59:23.000Z
#include "DefaultMaterial.hpp" #include "Animations/AnimatedMesh.hpp" #include "Maths/Transform.hpp" namespace acid { DefaultMaterial::DefaultMaterial(const Colour &baseDiffuse, std::shared_ptr<Image2d> imageDiffuse, float metallic, float roughness, std::shared_ptr<Image2d> imageMaterial, std::shared_ptr<Image2d> imageNormal, bool castsShadows, bool ignoreLighting, bool ignoreFog) : baseDiffuse(baseDiffuse), imageDiffuse(std::move(imageDiffuse)), metallic(metallic), roughness(roughness), imageMaterial(std::move(imageMaterial)), imageNormal(std::move(imageNormal)), castsShadows(castsShadows), ignoreLighting(ignoreLighting), ignoreFog(ignoreFog) { } void DefaultMaterial::CreatePipeline(const Shader::VertexInput &vertexInput, bool animated) { this->animated = animated; // TODO: Remove pipelineMaterial = MaterialPipeline::Create({1, 0}, { {"Shaders/Defaults/Default.vert", "Shaders/Defaults/Default.frag"}, {vertexInput}, GetDefines(), PipelineGraphics::Mode::MRT }); } void DefaultMaterial::PushUniforms(UniformHandler &uniformObject, const Transform *transform) { if (transform) uniformObject.Push("transform", transform->GetWorldMatrix()); uniformObject.Push("baseDiffuse", baseDiffuse); uniformObject.Push("metallic", metallic); uniformObject.Push("roughness", roughness); uniformObject.Push("ignoreFog", static_cast<float>(ignoreFog)); uniformObject.Push("ignoreLighting", static_cast<float>(ignoreLighting)); } void DefaultMaterial::PushDescriptors(DescriptorsHandler &descriptorSet) { descriptorSet.Push("samplerDiffuse", imageDiffuse); descriptorSet.Push("samplerMaterial", imageMaterial); descriptorSet.Push("samplerNormal", imageNormal); } std::vector<Shader::Define> DefaultMaterial::GetDefines() const { return { {"DIFFUSE_MAPPING", String::To<int32_t>(imageDiffuse != nullptr)}, {"MATERIAL_MAPPING", String::To<int32_t>(imageMaterial != nullptr)}, {"NORMAL_MAPPING", String::To<int32_t>(imageNormal != nullptr)}, {"ANIMATED", String::To<int32_t>(animated)}, {"MAX_JOINTS", String::To(AnimatedMesh::MaxJoints)}, {"MAX_WEIGHTS", String::To(AnimatedMesh::MaxWeights)} }; } const Node &operator>>(const Node &node, DefaultMaterial &material) { node["baseDiffuse"].Get(material.baseDiffuse); node["imageDiffuse"].Get(material.imageDiffuse); node["metallic"].Get(material.metallic); node["roughness"].Get(material.roughness); node["imageMaterial"].Get(material.imageMaterial); node["imageNormal"].Get(material.imageNormal); node["castsShadows"].Get(material.castsShadows); node["ignoreLighting"].Get(material.ignoreLighting); node["ignoreFog"].Get(material.ignoreFog); return node; } Node &operator<<(Node &node, const DefaultMaterial &material) { node["baseDiffuse"].Set(material.baseDiffuse); node["imageDiffuse"].Set(material.imageDiffuse); node["metallic"].Set(material.metallic); node["roughness"].Set(material.roughness); node["imageMaterial"].Set(material.imageMaterial); node["imageNormal"].Set(material.imageNormal); node["castsShadows"].Set(material.castsShadows); node["ignoreLighting"].Set(material.ignoreLighting); node["ignoreFog"].Set(material.ignoreFog); return node; } }
38.719512
136
0.766929
[ "vector", "transform" ]
8e6144cf68d9b0eea03d8d5af7efd9e5fa63602a
216
cpp
C++
G_LongestPath.cpp
singhal-har/atcoderdptasks
aec1aa4f53cb026eec98cde7f30209df544a3986
[ "MIT" ]
1
2021-07-05T11:09:33.000Z
2021-07-05T11:09:33.000Z
G_LongestPath.cpp
singhal-har/atcoderdptasks
aec1aa4f53cb026eec98cde7f30209df544a3986
[ "MIT" ]
null
null
null
G_LongestPath.cpp
singhal-har/atcoderdptasks
aec1aa4f53cb026eec98cde7f30209df544a3986
[ "MIT" ]
2
2020-10-20T05:14:16.000Z
2020-10-20T16:46:16.000Z
#include<bits/stdc++.h> using namespace std; int main() { int n, m; cin>>n>>m; vector<vector<int>> adj[m]; for(int i=0;i<m;i++) { int a, b; cin>>a>>b; adj[a].push_back(b); } return 0; }
12.705882
29
0.513889
[ "vector" ]
769d25e2c1e17a60779591d3bd50cd987d879e3f
2,526
cpp
C++
Jetson/hbs2/src/nodes/hardware/SRF02.cpp
ROBOTICSENGINEER/social_humanoid_robots
318c4726ab8b713f588678f6a222d0c386b87aea
[ "BSD-4-Clause" ]
null
null
null
Jetson/hbs2/src/nodes/hardware/SRF02.cpp
ROBOTICSENGINEER/social_humanoid_robots
318c4726ab8b713f588678f6a222d0c386b87aea
[ "BSD-4-Clause" ]
null
null
null
Jetson/hbs2/src/nodes/hardware/SRF02.cpp
ROBOTICSENGINEER/social_humanoid_robots
318c4726ab8b713f588678f6a222d0c386b87aea
[ "BSD-4-Clause" ]
null
null
null
/* SRF02 sonar client node that calls upon i2c_mgr.cpp */ // System #include <unistd.h> #include <stdlib.h> #include <vector> // ROS #include "ros/ros.h" #include "hbs2/i2c_bus.h" #include "hbs2/sonar.h" // declare global NodeHandle ros::NodeHandlePtr n = NULL; bool status_req(ros::ServiceClient &client, hbs2::i2c_bus &srv) { srv.request.request.resize(4); srv.request.request = {0x00, 0x71, 0x00, 0x00}; usleep(1000); if (client.call(srv)) { return false; } else { return true; } } // Configure sensor and set range to centimeters bool write_init(ros::ServiceClient &client, hbs2::i2c_bus &srv) { srv.request.request.resize(4); srv.request.request = {0x02, 0x71, 0x00, 0x51}; srv.request.bus = 1; if (client.call(srv)) { /* wait for job to be served in the i2c manager. */ while(!status_req(client, srv)); return true; } ROS_ERROR("Failed to call service i2c_srv."); return false; } // Read range from register (result is 4 bytes) uint16_t read_range(ros::ServiceClient &client, hbs2::i2c_bus &srv) { if (write_init(client, srv)) { ROS_INFO("SRF02 is prepared to be read."); } srv.request.request.resize(6); srv.request.request = {0x01, 0x71, 0x00, 0x00, 0x00, 0x00}; srv.request.bus = 1; if (client.call(srv)) { /* wait for job to be served in the i2c manager. */ ROS_INFO("Request to i2c manager successful. Waiting to be served."); while(!status_req(client, srv)); uint16_t range = (uint16_t)srv.response.data.at(2); range <<= 8; range |= (uint16_t)srv.response.data.at(3); return range; } else { ROS_ERROR("Failed to call service i2c_srv"); return 1; } } bool report_range(hbs2::sonar::Request &req, hbs2::sonar::Response &res) { ros::ServiceClient i2c_client = n->serviceClient<hbs2::i2c_bus>("i2c_srv"); hbs2::i2c_bus srv_i2c; usleep(1000); uint16_t range = read_range(i2c_client, srv_i2c); res.data = range; ROS_DEBUG("Range in centimeters: %u", range); return true; } int main(int argc, char **argv) { // Initialize sonar sensor node ros::init(argc, argv, "srf02"); n = ros::NodeHandlePtr(new ros::NodeHandle); ros::ServiceClient client = n->serviceClient<hbs2::i2c_bus>("i2c_srv"); hbs2::i2c_bus srv_i2c; ros::ServiceServer srv = n->advertiseService("sonar_srv", report_range); ROS_INFO("ROS sonar service has started."); ros::spin(); return 0; }
27.16129
79
0.644101
[ "vector" ]
76a4ae6db751a57a5ac1433e50f9f0667ea6b2a1
12,659
cpp
C++
lib/analyzer/types/struct.cpp
reaver-project/vapor
17ddb5c60b483bd17a288319bfd3e8a43656859e
[ "Zlib" ]
4
2017-07-22T23:12:36.000Z
2022-01-13T23:57:06.000Z
lib/analyzer/types/struct.cpp
reaver-project/vapor
17ddb5c60b483bd17a288319bfd3e8a43656859e
[ "Zlib" ]
36
2016-11-26T17:46:16.000Z
2019-05-21T16:27:13.000Z
lib/analyzer/types/struct.cpp
reaver-project/vapor
17ddb5c60b483bd17a288319bfd3e8a43656859e
[ "Zlib" ]
3
2016-10-01T21:04:32.000Z
2021-03-20T06:57:53.000Z
/** * Vapor Compiler Licence * * Copyright © 2016-2019 Michał "Griwes" Dominiak * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation is required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. * **/ #include "vapor/analyzer/types/struct.h" #include "vapor/analyzer/expressions/member_access.h" #include "vapor/analyzer/expressions/runtime_value.h" #include "vapor/analyzer/expressions/struct.h" #include "vapor/analyzer/expressions/struct_literal.h" #include "vapor/analyzer/precontext.h" #include "vapor/analyzer/semantic/symbol.h" #include "vapor/analyzer/statements/declaration.h" #include "vapor/analyzer/types/unresolved.h" #include "vapor/parser/expr.h" #include "types/struct.pb.h" namespace reaver::vapor::analyzer { inline namespace _v1 { std::unique_ptr<struct_type> make_struct_type(precontext & ctx, const parser::struct_literal & parse, scope * lex_scope) { auto member_scope = lex_scope->clone_for_class(); std::vector<std::unique_ptr<declaration>> decls; fmap(parse.members, [&](auto && member) { fmap(member, make_overload_set( [&](const parser::declaration & decl) { auto scope = member_scope.get(); auto decl_stmt = preanalyze_member_declaration(ctx, decl, scope); assert(scope == member_scope.get()); decls.push_back(std::move(decl_stmt)); return unit{}; }, [&](const parser::function_definition & func) { assert(0); return unit{}; })); return unit{}; }); member_scope->close(); return std::make_unique<struct_type>(make_node(parse), std::move(member_scope), std::move(decls)); } std::unique_ptr<struct_type> import_struct_type(precontext & ctx, const proto::struct_type & str) { auto member_scope = ctx.current_lex_scope->clone_for_class(); std::vector<std::unique_ptr<declaration>> decls; for (auto && member : str.data_members()) { decls.push_back(std::make_unique<declaration>(ast_node{}, utf32(member.name()), std::nullopt, get_imported_type_ref_expr(ctx, member.type()), member_scope.get(), declaration_type::member)); } member_scope->close(); auto ret = std::make_unique<struct_type>(ast_node{}, std::move(member_scope), std::move(decls)); ret->mark_imported(); return ret; } struct_type::~struct_type() = default; struct_type::struct_type(ast_node parse, std::unique_ptr<scope> member_scope, std::vector<std::unique_ptr<declaration>> member_decls) : user_defined_type{ std::move(member_scope) }, _parse{ parse }, _data_member_declarations{ std::move(member_decls) } { auto ctor_pair = make_promise<function *>(); _aggregate_ctor_future = std::move(ctor_pair.future); _aggregate_ctor_promise = std::move(ctor_pair.promise); auto copy_pair = make_promise<function *>(); _aggregate_copy_ctor_future = std::move(copy_pair.future); _aggregate_copy_ctor_promise = std::move(copy_pair.promise); } void struct_type::generate_constructors() { _data_members = fmap(_data_member_declarations, [&](auto && member) { auto ret = member->declared_member(); ret->set_parent_type(this); return ret; }); _aggregate_ctor = make_function("struct type constructor"); _aggregate_ctor->set_return_type(get_expression()); _aggregate_ctor->set_parameters( fmap(_data_members, [](auto && member) -> expression * { return member; })); _aggregate_ctor->set_codegen([&](auto && ctx) -> codegen::ir::function { auto ir_type = this->codegen_type(ctx); auto args = fmap(_data_members, [&](auto && member) { return codegen::ir::make_variable(member->get_type()->codegen_type(ctx)); }); auto result = codegen::ir::make_variable(ir_type); auto scopes = this->get_scope()->codegen_ir(); scopes.emplace_back(get_name(), codegen::ir::scope_type::type); codegen::ir::function ret = { U"constructor", std::move(scopes), args, result, { codegen::ir::instruction{ std::nullopt, std::nullopt, { boost::typeindex::type_id<codegen::ir::aggregate_init_instruction>() }, fmap(args, [](auto && arg) -> codegen::ir::value { return arg; }), result }, codegen::ir::instruction{ std::nullopt, std::nullopt, { boost::typeindex::type_id<codegen::ir::return_instruction>() }, { result }, result } } }; ret.is_defined = !_is_imported; ret.is_exported = _is_exported; return ret; }); _aggregate_ctor->set_scopes_generator([this](auto && ctx) { return this->codegen_scopes(ctx); }); _aggregate_ctor->set_eval([this](auto &&, const std::vector<expression *> & args) { if (!std::equal(args.begin(), args.end(), _data_members.begin(), [](auto && arg, auto && member) { return arg->get_type() == member->get_type(); })) { assert(0); } if (!std::all_of(args.begin(), args.end(), [](auto && arg) { return arg->is_constant(); })) { return make_ready_future<expression *>(nullptr); } auto repl = replacements{}; auto arg_copies = fmap(args, [&](auto && arg) { return repl.claim(arg); }); return make_ready_future<expression *>( make_struct_expression(this->shared_from_this(), std::move(arg_copies)).release()); }); _aggregate_ctor->set_name(U"constructor"); _aggregate_ctor_promise->set(_aggregate_ctor.get()); auto data_members = fmap(_data_members, [&](auto && member) -> expression * { auto param = make_member_expression(this, member->get_name(), member->get_type()); auto def_value = make_member_access_expression(member->get_name(), member->get_type()); param->set_default_value(def_value.get()); auto param_ptr = param.get(); _member_copy_arguments.push_back(std::move(param)); _member_copy_arguments.push_back(std::move(def_value)); return param_ptr; }); _this_argument = make_runtime_value(this); data_members.insert(data_members.begin(), _this_argument.get()); _aggregate_copy_ctor = make_function("struct type copy replacement constructor"); _aggregate_copy_ctor->set_return_type(get_expression()); _aggregate_copy_ctor->set_parameters(data_members); _aggregate_copy_ctor->set_codegen([&](auto && ctx) -> codegen::ir::function { auto ir_type = this->codegen_type(ctx); auto args = fmap(_data_members, [&](auto && member) { auto ret = codegen::ir::make_variable(member->get_type()->codegen_type(ctx)); return ret; }); auto result = codegen::ir::make_variable(ir_type); auto scopes = this->get_scope()->codegen_ir(); scopes.emplace_back(get_name(), codegen::ir::scope_type::type); codegen::ir::function ret = { U"replacing_copy_constructor", std::move(scopes), args, result, { codegen::ir::instruction{ std::nullopt, std::nullopt, { boost::typeindex::type_id<codegen::ir::aggregate_init_instruction>() }, fmap(args, [](auto && arg) -> codegen::ir::value { return arg; }), result }, codegen::ir::instruction{ std::nullopt, std::nullopt, { boost::typeindex::type_id<codegen::ir::return_instruction>() }, { result }, result } } }; ret.is_defined = !_is_imported; ret.is_exported = _is_exported; return ret; }); _aggregate_copy_ctor->set_scopes_generator([this](auto && ctx) { return this->codegen_scopes(ctx); }); _aggregate_copy_ctor->set_eval([this](auto &&, std::vector<expression *> args) { auto base = args.front(); args.erase(args.begin()); if (base->get_type() != this || !std::equal( args.begin(), args.end(), _data_members.begin(), [](auto && arg, auto && member) { return arg->get_type() == member->get_type(); })) { logger::default_logger().sync(); assert(0); } for (auto && arg : args) { if (auto member_arg = arg->as<member_access_expression>()) { auto actual_arg = base->get_member(member_arg->get_name()); arg = actual_arg ? actual_arg : arg; } } if (!std::all_of(args.begin(), args.end(), [](auto && arg) { return arg->is_constant(); })) { return make_ready_future<expression *>(nullptr); } auto repl = replacements{}; for (std::size_t i = 0; i < _data_members.size(); ++i) { repl.add_replacement(base->get_member(_data_members[i]->get_name()), args[i]); } return make_ready_future(repl.claim(base->_get_replacement()).release()); }); _aggregate_copy_ctor->set_name(U"replacing_copy_constructor"); _aggregate_copy_ctor->make_member(); _aggregate_copy_ctor_promise->set(_aggregate_copy_ctor.get()); } void struct_type::_codegen_type(ir_generation_context & ctx, std::shared_ptr<codegen::ir::user_type> actual_type) const { auto type = codegen::ir::user_type{ get_name(), get_scope()->codegen_ir(), 0, {} }; auto members = fmap(_data_members, [&](auto && member) { return codegen::ir::member{ member->member_codegen_ir(ctx) }; }); auto scopes = this->get_scope()->codegen_ir(); scopes.emplace_back(type.name, codegen::ir::scope_type::type); auto add_fn = [&](auto && fn) { auto fn_ir = fn->codegen_ir(ctx); fn_ir.scopes = scopes; fn_ir.parent_type = actual_type; members.push_back(codegen::ir::member{ fn_ir }); ctx.add_generated_function(fn.get()); }; add_fn(_aggregate_ctor); add_fn(_aggregate_copy_ctor); type.members = std::move(members); *actual_type = std::move(type); } void struct_type::print(std::ostream & os, print_context ctx) const { os << styles::def << ctx << styles::type << "struct type"; print_address_range(os, this); os << '\n'; } std::unique_ptr<google::protobuf::Message> struct_type::_user_defined_interface() const { auto t = std::make_unique<proto::struct_type>(); for (auto && member : _data_members) { auto proto_member = t->add_data_members(); proto_member->set_name(utf8(member->get_name())); proto_member->set_allocated_type(member->get_type()->generate_interface_reference().release()); } return std::move(t); } } }
39.19195
110
0.573268
[ "vector" ]
76ab5add82bed8424a8a7e6adebd82d40eff6031
558
cpp
C++
HackerEarth/Basics/IO/Cost_Of_Balloons.cpp
GSri30/Competetive_programming
0dc1681500a80b6f0979d0dc9f749357ee07bcb8
[ "MIT" ]
22
2020-01-03T17:32:00.000Z
2021-11-07T09:31:44.000Z
HackerEarth/Basics/IO/Cost_Of_Balloons.cpp
GSri30/Competetive_programming
0dc1681500a80b6f0979d0dc9f749357ee07bcb8
[ "MIT" ]
10
2020-09-30T09:41:18.000Z
2020-10-11T11:25:09.000Z
HackerEarth/Basics/IO/Cost_Of_Balloons.cpp
GSri30/Competetive_programming
0dc1681500a80b6f0979d0dc9f749357ee07bcb8
[ "MIT" ]
25
2019-10-14T19:25:01.000Z
2021-05-26T08:12:20.000Z
// Sample code to perform I/O: #include <iostream> #include <algorithm> #include <vector> using namespace std; // Write your code here int main() { int test; cin >> test; while(test > 0) { int green,purple; int prob1 = 0; int prob2 = 0; cin >> green >> purple ; int peeps; cin >> peeps; while(peeps) { int first,second; cin >> first >> second; prob1 += first * 1; prob2 += second * 1; peeps --; } cout << min(green,purple) * max(prob1,prob2) + max(green,purple) * min(prob1,prob2) << endl; test --; } return 0; }
16.411765
94
0.59319
[ "vector" ]
76ac4519209f4c7d6840068db9921d9a29e2bf93
449
hpp
C++
ares/msx/psg/psg.hpp
moon-chilled/Ares
909fb098c292f8336d0502dc677050312d8b5c81
[ "0BSD" ]
7
2020-07-25T11:44:39.000Z
2021-01-29T13:21:31.000Z
ares/msx/psg/psg.hpp
jchw-forks/ares
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
[ "0BSD" ]
null
null
null
ares/msx/psg/psg.hpp
jchw-forks/ares
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
[ "0BSD" ]
1
2021-03-22T16:15:30.000Z
2021-03-22T16:15:30.000Z
struct PSG : AY38910, Thread { Node::Component node; Node::Stream stream; //psg.cpp auto load(Node::Object) -> void; auto unload() -> void; auto main() -> void; auto step(uint clocks) -> void; auto power() -> void; auto readIO(uint1 port) -> uint8 override; auto writeIO(uint1 port, uint8 data) -> void override; //serialization.cpp auto serialize(serializer&) -> void; private: double volume[16]; }; extern PSG psg;
18.708333
56
0.652561
[ "object" ]
76b12bd30153754e4b3d80b1811719b5007fbd13
36,942
cc
C++
modules/ris/src/ris.cc
SashkaHavr/motis
1e5633943d8441c720cfba53cc1bff5151c76e99
[ "MIT" ]
null
null
null
modules/ris/src/ris.cc
SashkaHavr/motis
1e5633943d8441c720cfba53cc1bff5151c76e99
[ "MIT" ]
58
2021-11-22T13:43:39.000Z
2022-03-18T21:49:04.000Z
modules/ris/src/ris.cc
SashkaHavr/motis
1e5633943d8441c720cfba53cc1bff5151c76e99
[ "MIT" ]
null
null
null
#include "motis/ris/ris.h" #include <cstdint> #include <atomic> #include <fstream> #include <limits> #include <optional> #include "boost/algorithm/string/predicate.hpp" #include "boost/filesystem.hpp" #include "utl/concat.h" #include "utl/parser/file.h" #include "utl/read_file.h" #include "net/http/client/url.h" #include "conf/date_time.h" #include "tar/file_reader.h" #include "tar/tar_reader.h" #include "tar/zstd_reader.h" #include "utl/overloaded.h" #include "utl/verify.h" #include "utl/zip.h" #include "lmdb/lmdb.hpp" #include "rabbitmq/amqp.hpp" #include "motis/core/common/logging.h" #include "motis/core/common/unixtime.h" #include "motis/core/access/time_access.h" #include "motis/core/conv/trip_conv.h" #include "motis/core/journey/print_trip.h" #include "motis/module/context/motis_http_req.h" #include "motis/module/context/motis_publish.h" #include "motis/module/context/motis_spawn.h" #include "motis/ris/gtfs-rt/common.h" #include "motis/ris/gtfs-rt/gtfsrt_parser.h" #include "motis/ris/gtfs-rt/util.h" #include "motis/ris/ribasis/ribasis_parser.h" #include "motis/ris/ris_message.h" #include "motis/ris/risml/risml_parser.h" #include "motis/ris/string_view_reader.h" #include "motis/ris/zip_reader.h" #ifdef GetMessage #undef GetMessage #endif namespace fs = boost::filesystem; namespace db = lmdb; using namespace motis::module; using namespace motis::logging; using tar::file_reader; using tar::tar_reader; using tar::zstd_reader; namespace motis::ris { // stores the list of files that were already parsed // key: path // value: empty constexpr auto const FILE_DB = "FILE_DB"; // messages, no specific order (unique id) // key: timestamp // value: buffer of messages: // 2 bytes message size, {message size} bytes message constexpr auto const MSG_DB = "MSG_DB"; // index for every day referenced by any message // key: day.begin (unix timestamp) // value: smallest message timestamp from MSG_DB that has // earliest <= day.end && latest >= day.begin constexpr auto const MIN_DAY_DB = "MIN_DAY_DB"; // index for every day referenced by any message // key: day.begin (unix timestamp) // value: largest message timestamp from MSG_DB that has // earliest <= day.end && latest >= day.begin constexpr auto const MAX_DAY_DB = "MAX_DAY_DB"; constexpr auto const BATCH_SIZE = unixtime{3600}; constexpr auto const WRITE_MSG_BUF_MAX_SIZE = 50000; template <typename T> constexpr T floor(T const i, T const multiple) { return (i / multiple) * multiple; } template <typename T> constexpr T ceil(T const i, T const multiple) { return ((i - 1) / multiple) * multiple + multiple; } using size_type = uint32_t; constexpr auto const SIZE_TYPE_SIZE = sizeof(size_type); constexpr unixtime day(unixtime t) { return (t / SECONDS_A_DAY) * SECONDS_A_DAY; } constexpr unixtime next_day(unixtime t) { return day(t) + SECONDS_A_DAY; } template <typename Fn> inline void for_each_day(ris_message const& m, Fn&& f) { auto const last = next_day(m.latest_); for (auto d = day(m.earliest_); d != last; d += SECONDS_A_DAY) { f(d); } } unixtime to_unixtime(std::string_view s) { return *reinterpret_cast<unixtime const*>(s.data()); } std::string_view from_unixtime(unixtime const& t) { return {reinterpret_cast<char const*>(&t), sizeof(t)}; } struct ris::impl { /** * Extracts the station prefix + directory path from a string formed * "${station-prefix}:${input-directory-path}" * * Contains an optional tag which is used as station id prefix to match * stations in multi-schedule mode and the path to the directory. * * In single-timetable mode, the tag should be omitted. */ struct input { using source_t = std::variant<net::http::client::request, fs::path>; enum class source_type { path, url }; input(schedule const& sched, std::string const& in) : input{sched, split(in)} {} std::string str() const { return std::visit( utl::overloaded{ [](fs::path const& p) { return "path: " + p.generic_string(); }, [](net::http::client::request const& u) { auto const auth_it = u.headers.find("Authorization"); return "url: " + u.address.str() + ", auth: " + (auth_it == end(u.headers) ? "none" : auth_it->second); }}, src_); } source_type source_type() const { return std::visit( utl::overloaded{[](fs::path const&) { return source_type::path; }, [](net::http::client::request const&) { return source_type::url; }}, src_); } fs::path get_path() const { utl::verify(std::holds_alternative<fs::path>(src_), "no path {}", str()); return std::get<fs::path>(src_); } net::http::client::request get_request() const { utl::verify(std::holds_alternative<net::http::client::request>(src_), "no url {}", str()); return std::get<net::http::client::request>(src_); } std::string const& tag() const { return tag_; } gtfsrt::knowledge_context& gtfs_knowledge() { return gtfs_knowledge_; } private: input(schedule const& sched, std::pair<source_t, std::string>&& path_and_tag) : src_{std::move(path_and_tag.first)}, tag_{path_and_tag.second}, gtfs_knowledge_{path_and_tag.second, sched} {} static std::pair<source_t, std::string> split(std::string const& in) { auto const is_url = [](std::string const& s) { return boost::starts_with(s, "http://") || boost::starts_with(s, "https://"); }; auto const parse_req = [](std::string const& s) { if (auto const delimiter_pos = s.find('|'); delimiter_pos != std::string::npos) { auto req = net::http::client::request{s.substr(0, delimiter_pos)}; req.headers.emplace("Authorization", s.substr(delimiter_pos + 1)); return req; } else { return net::http::client::request{s}; } }; std::string tag; if (auto const delimiter_pos = in.find('|'); delimiter_pos != std::string::npos) { tag = in.substr(0, delimiter_pos); tag = tag.empty() ? "" : tag + "_"; auto const src = in.substr(delimiter_pos + 1); return { is_url(src) ? source_t{parse_req(src)} : source_t{fs::path{src}}, tag}; } else { return {is_url(in) ? source_t{parse_req(in)} : source_t{fs::path{in}}, tag}; } } source_t src_; std::string tag_; gtfsrt::knowledge_context gtfs_knowledge_; std::unique_ptr<amqp::ssl_connection> con_; }; explicit impl(config& c) : config_{c}, rabbitmq_log_enabled_{!config_.rabbitmq_log_.empty()} { if (rabbitmq_log_enabled_) { LOG(info) << "Logging RabbitMQ messages to: " << config_.rabbitmq_log_; rabbitmq_log_file_.exceptions(std::ios_base::failbit | std::ios_base::badbit); rabbitmq_log_file_.open(config_.rabbitmq_log_, std::ios_base::app); } } void init_ribasis_receiver(dispatcher* d, schedule* sched) { utl::verify(config_.rabbitmq_.valid(), "invalid rabbitmq configuration"); if (config_.rabbitmq_.empty()) { return; } ribasis_receiver_ = std::make_unique<amqp::ssl_connection>( &config_.rabbitmq_, [](std::string const& log_msg) { LOG(info) << "rabbitmq: " << log_msg; }); ribasis_receiver_->run([this, d, sched, buffer = std::vector<amqp::msg>{}]( amqp::msg const& m) mutable { buffer.emplace_back(m); if (auto const n = now(); (n - ribasis_receiver_last_update_) < config_.update_interval_) { return; } else { ribasis_receiver_last_update_ = n; auto msgs_copy = buffer; buffer.clear(); d->enqueue( ctx_data{d}, [this, sched, msgs = std::move(msgs_copy)]() { publisher pub; pub.schedule_res_id_ = to_res_id(::motis::module::global_res_id::SCHEDULE); for (auto const& m : msgs) { if (rabbitmq_log_enabled_) { rabbitmq_log_file_ << "[" << motis::logging::time() << "] msg size=" << m.content_.size() << "\n" << m.content_ << "\n" << std::endl; } parse_str_and_write_to_db( *file_upload_, {m.content_.c_str(), m.content_.size()}, file_type::JSON, pub); } sched->system_time_ = pub.max_timestamp_; sched->last_update_timestamp_ = std::time(nullptr); if (rabbitmq_log_enabled_) { rabbitmq_log_file_ << "[" << motis::logging::time() << "] published " << msgs.size() << " messages, system_time=" << sched->system_time_ << " (" << format_unix_time(sched->system_time_) << ")" << std::endl; } publish_system_time_changed(pub.schedule_res_id_); }, ctx::op_id{"ribasis_receive", CTX_LOCATION, 0U}, ctx::op_type_t::IO, ctx::accesses_t{ctx::access_request{ to_res_id(::motis::module::global_res_id::SCHEDULE), ctx::access_t::WRITE}}); } }); } void update_gtfs_rt(schedule& sched) { auto futures = std::vector<http_future_t>{}; auto inputs = std::vector<input*>{}; for (auto& in : inputs_) { if (in.source_type() == input::source_type::url) { futures.emplace_back(motis_http(in.get_request())); inputs.emplace_back(&in); } } publisher pub; pub.schedule_res_id_ = to_res_id(::motis::module::global_res_id::SCHEDULE); for (auto const& [f, in] : utl::zip(futures, inputs)) { parse_str_and_write_to_db(*in, f->val().body, file_type::PROTOBUF, pub); } sched.system_time_ = pub.max_timestamp_; sched.last_update_timestamp_ = std::time(nullptr); publish_system_time_changed(pub.schedule_res_id_); } void init(dispatcher& d, schedule& sched) { inputs_ = utl::to_vec(config_.input_, [&](std::string const& in) { return input{sched, in}; }); file_upload_ = std::make_unique<input>(sched, ""); if (config_.clear_db_ && fs::exists(config_.db_path_)) { LOG(info) << "clearing database path " << config_.db_path_; fs::remove_all(config_.db_path_); } env_.set_maxdbs(4); env_.set_mapsize(config_.db_max_size_); try { env_.open(config_.db_path_.c_str(), lmdb::env_open_flags::NOSUBDIR | lmdb::env_open_flags::NOTLS); } catch (...) { l(logging::error, "ris: can't open database {}", config_.db_path_); throw; } db::txn t{env_}; t.dbi_open(FILE_DB, db::dbi_flags::CREATE); t.dbi_open(MSG_DB, db::dbi_flags::CREATE | db::dbi_flags::INTEGERKEY); t.dbi_open(MIN_DAY_DB, db::dbi_flags::CREATE | db::dbi_flags::INTEGERKEY); t.dbi_open(MAX_DAY_DB, db::dbi_flags::CREATE | db::dbi_flags::INTEGERKEY); t.commit(); std::vector<input> urls; for (auto& in : inputs_) { if (in.source_type() != input::source_type::path) { continue; } if (fs::exists(in.get_path())) { LOG(warn) << "parsing " << in.get_path(); if (config_.instant_forward_) { publisher pub; parse_sequential(sched, in, pub); } else { parse_sequential(sched, in, null_pub_); } } else { LOG(warn) << in.get_path() << " does not exist"; } } auto const has_urls = std::any_of( begin(inputs_), end(inputs_), [](auto&& in) { return in.source_type() == input::source_type::url; }); if (has_urls) { d.register_timer( "RIS GTFS-RT Update", boost::posix_time::seconds{config_.update_interval_}, [this, &sched]() { update_gtfs_rt(sched); }, ctx::accesses_t{ctx::access_request{ to_res_id(::motis::module::global_res_id::SCHEDULE), ctx::access_t::WRITE}}); } if (config_.init_time_.unix_time_ != 0) { forward(sched, 0U, config_.init_time_.unix_time_); } init_ribasis_receiver(&d, &sched); } static std::string_view get_content_type(HTTPRequest const* req) { for (auto const& h : *req->headers()) { if (std::string_view{h->name()->c_str(), h->name()->size()} == "Content-Type") { return {h->value()->c_str(), h->value()->size()}; } } return {}; } msg_ptr upload(schedule& sched, msg_ptr const& msg) { auto const req = motis_content(HTTPRequest, msg); auto const content = req->content(); auto const ft = guess_file_type(get_content_type(req), std::string_view{content->c_str(), content->size()}); publisher pub; parse_str_and_write_to_db(*file_upload_, {content->c_str(), content->size()}, ft, pub); sched.system_time_ = pub.max_timestamp_; sched.last_update_timestamp_ = std::time(nullptr); publish_system_time_changed(pub.schedule_res_id_); return {}; } msg_ptr read(schedule& sched, msg_ptr const&) { publisher pub; for (auto& in : inputs_) { if (in.source_type() == input::source_type::path) { parse_sequential(sched, in, pub); } } sched.system_time_ = pub.max_timestamp_; sched.last_update_timestamp_ = std::time(nullptr); publish_system_time_changed(pub.schedule_res_id_); return {}; } msg_ptr forward(module& mod, msg_ptr const& msg) { auto const req = motis_content(RISForwardTimeRequest, msg); auto const schedule_res_id = req->schedule() == 0U ? to_res_id(global_res_id::SCHEDULE) : static_cast<ctx::res_id_t>(req->schedule()); auto res_lock = mod.lock_resources({{schedule_res_id, ctx::access_t::WRITE}}); auto& sched = *res_lock.get<schedule_data>(schedule_res_id).schedule_; forward(sched, schedule_res_id, motis_content(RISForwardTimeRequest, msg)->new_time()); return {}; } msg_ptr purge(msg_ptr const& msg) { auto const until = static_cast<unixtime>(motis_content(RISPurgeRequest, msg)->until()); auto t = db::txn{env_}; auto db = t.dbi_open(MSG_DB); auto c = db::cursor{t, db}; auto bucket = c.get(db::cursor_op::SET_RANGE, until); while (bucket) { if (bucket->first <= until) { c.del(); } bucket = c.get(db::cursor_op::PREV, 0); } t.commit(); c.reset(); return {}; } msg_ptr apply(module& mod, msg_ptr const& msg) { auto const req = motis_content(RISApplyRequest, msg); auto const schedule_res_id = req->schedule() == 0U ? to_res_id(global_res_id::SCHEDULE) : static_cast<ctx::res_id_t>(req->schedule()); auto res_lock = mod.lock_resources({{schedule_res_id, ctx::access_t::WRITE}}); auto& sched = *res_lock.get<schedule_data>(schedule_res_id).schedule_; publisher pub{schedule_res_id}; for (auto const& rim : *req->input_messages()) { parse_and_publish_message(rim, pub); } pub.flush(); sched.system_time_ = std::max(sched.system_time_, pub.max_timestamp_); sched.last_update_timestamp_ = std::time(nullptr); publish_system_time_changed(schedule_res_id); return {}; } struct publisher { publisher() = default; explicit publisher(ctx::res_id_t schedule_res_id) : schedule_res_id_{schedule_res_id} {} publisher(publisher&&) = delete; publisher(publisher const&) = delete; publisher& operator=(publisher&&) = delete; publisher& operator=(publisher const&) = delete; ~publisher() { flush(); } void flush() { if (offsets_.empty()) { return; } fbb_.create_and_finish( MsgContent_RISBatch, CreateRISBatch(fbb_, fbb_.CreateVector(offsets_), schedule_res_id_) .Union(), "/ris/messages"); auto msg = make_msg(fbb_); fbb_.Clear(); offsets_.clear(); ctx::await_all(motis_publish(msg)); } void add(uint8_t const* ptr, size_t const size) { max_timestamp_ = std::max( max_timestamp_, static_cast<unixtime>( flatbuffers::GetRoot<Message>(reinterpret_cast<void const*>(ptr)) ->timestamp())); offsets_.push_back( CreateMessageHolder(fbb_, fbb_.CreateVector(ptr, size))); } size_t size() const { return offsets_.size(); } message_creator fbb_; std::vector<flatbuffers::Offset<MessageHolder>> offsets_; unixtime max_timestamp_ = 0; ctx::res_id_t schedule_res_id_{}; }; struct null_publisher { void flush() {} void add(uint8_t const*, size_t const) {} size_t size() const { return 0; } // NOLINT unixtime max_timestamp_ = 0; ctx::res_id_t schedule_res_id_{}; } null_pub_; void forward(schedule& sched, ctx::res_id_t schedule_res_id, unixtime const to) { auto const first_schedule_event_day = sched.first_event_schedule_time_ != std::numeric_limits<unixtime>::max() ? floor(sched.first_event_schedule_time_, static_cast<unixtime>(SECONDS_A_DAY)) : external_schedule_begin(sched); auto const last_schedule_event_day = sched.last_event_schedule_time_ != std::numeric_limits<unixtime>::min() ? ceil(sched.last_event_schedule_time_, static_cast<unixtime>(SECONDS_A_DAY)) : external_schedule_end(sched); auto const min_timestamp = get_min_timestamp(first_schedule_event_day, last_schedule_event_day); if (min_timestamp) { forward(sched, schedule_res_id, std::max(*min_timestamp, sched.system_time_ + 1), to); } else { LOG(info) << "ris database has no relevant data"; } } void forward(schedule& sched, ctx::res_id_t schedule_res_id, unixtime const from, unixtime const to) { LOG(info) << "forwarding from " << logging::time(from) << " to " << logging::time(to) << " [schedule " << schedule_res_id << "]"; auto t = db::txn{env_, db::txn_flags::RDONLY}; auto db = t.dbi_open(MSG_DB); auto c = db::cursor{t, db}; auto bucket = c.get(db::cursor_op::SET_RANGE, from); auto batch_begin = bucket ? bucket->first : 0; publisher pub{schedule_res_id}; while (true) { if (!bucket) { LOG(info) << "end of db reached"; break; } auto const& [timestamp, msgs] = *bucket; if (timestamp > to) { break; } auto ptr = msgs.data(); auto const end = ptr + msgs.size(); while (ptr < end) { size_type size = 0; std::memcpy(&size, ptr, SIZE_TYPE_SIZE); ptr += SIZE_TYPE_SIZE; if (size == 0) { continue; } utl::verify(ptr + size <= end, "ris: ptr + size > end"); if (auto const msg = GetMessage(ptr); msg->timestamp() <= to && msg->timestamp() >= from) { pub.add(reinterpret_cast<uint8_t const*>(ptr), size); } ptr += size; } if (timestamp - batch_begin > BATCH_SIZE) { LOG(logging::info) << "(" << logging::time(batch_begin) << " - " << logging::time(batch_begin + BATCH_SIZE) << ") flushing " << pub.size() << " messages"; pub.flush(); batch_begin = timestamp; } bucket = c.get(db::cursor_op::NEXT, 0); } pub.flush(); sched.system_time_ = to; publish_system_time_changed(pub.schedule_res_id_); } std::optional<unixtime> get_min_timestamp(unixtime const from_day, unixtime const to_day) { utl::verify(from_day % SECONDS_A_DAY == 0, "from not a day"); utl::verify(to_day % SECONDS_A_DAY == 0, "to not a day"); constexpr auto const max = std::numeric_limits<unixtime>::max(); auto min = max; auto t = db::txn{env_, db::txn_flags::RDONLY}; auto db = t.dbi_open(MIN_DAY_DB); for (auto d = from_day; d != to_day; d += SECONDS_A_DAY) { auto const r = t.get(db, d); if (r) { min = std::min(min, to_unixtime(*r)); } } return min != max ? std::make_optional(min) : std::nullopt; } enum class file_type { NONE, ZST, ZIP, XML, PROTOBUF, JSON }; static file_type get_file_type(fs::path const& p) { if (p.extension() == ".zst") { return file_type::ZST; } else if (p.extension() == ".zip") { return file_type::ZIP; } else if (p.extension() == ".xml") { return file_type::XML; } else if (p.extension() == ".pb") { return file_type::PROTOBUF; } else if (p.extension() == ".json") { return file_type::JSON; } else { return file_type::NONE; } } static file_type guess_file_type(std::string_view content_type, std::string_view content) { using boost::algorithm::iequals; using boost::algorithm::starts_with; if (iequals(content_type, "application/zip")) { return file_type::ZIP; } else if (iequals(content_type, "application/zstd")) { return file_type::ZST; } else if (iequals(content_type, "application/xml") || iequals(content_type, "text/xml")) { return file_type::XML; } else if (iequals(content_type, "application/json") || iequals(content_type, "application/x.ribasis")) { return file_type::JSON; } if (content.size() < 4) { return file_type::NONE; } else if (starts_with(content, "PK")) { return file_type::ZIP; } else if (starts_with(content, "\x28\xb5\x2f\xfd")) { return file_type::ZST; } else if (starts_with(content, "<")) { return file_type::XML; } else if (starts_with(content, "{")) { return file_type::JSON; } return file_type::NONE; } std::vector<std::tuple<unixtime, fs::path, file_type>> collect_files( fs::path const& p) { if (fs::is_regular_file(p)) { if (auto const t = get_file_type(p); t != file_type::NONE && !is_known_file(p)) { return {std::make_tuple(fs::last_write_time(p), p, t)}; } } else if (fs::is_directory(p)) { std::vector<std::tuple<unixtime, fs::path, file_type>> files; for (auto const& entry : fs::directory_iterator(p)) { utl::concat(files, collect_files(entry)); } std::sort(begin(files), end(files)); return files; } return {}; } template <typename Publisher> void parse_parallel(fs::path const& p, Publisher& pub) { ctx::await_all(utl::to_vec( collect_files(fs::canonical(p, p.root_path())), [&](auto&& e) { return spawn_job_void([e, this, &pub]() { parse_file_and_write_to_db(std::get<1>(e), std::get<2>(e), pub); }); })); env_.force_sync(); } template <typename Publisher> void parse_sequential(schedule& sched, input& in, Publisher& pub) { if (!fs::exists(in.get_path())) { l(logging::error, "ris input path {} does not exist", in.get_path()); return; } for (auto const& [t, path, type] : collect_files( fs::canonical(in.get_path(), in.get_path().root_path()))) { try { parse_file_and_write_to_db(in, path, type, pub); if (config_.instant_forward_) { sched.system_time_ = pub.max_timestamp_; sched.last_update_timestamp_ = std::time(nullptr); try { publish_system_time_changed(pub.schedule_res_id_); } catch (std::system_error& e) { LOG(info) << e.what(); } } } catch (std::exception const& e) { l(logging::error, "error parsing file {}", path); } } env_.force_sync(); } bool is_known_file(fs::path const& p) { auto t = db::txn{env_}; auto db = t.dbi_open(FILE_DB); return t.get(db, p.generic_string()).has_value(); } void add_to_known_files(fs::path const& p) { auto t = db::txn{env_}; auto db = t.dbi_open(FILE_DB); t.put(db, p.generic_string(), ""); t.commit(); } template <typename Publisher> void parse_file_and_write_to_db(input& in, fs::path const& p, file_type const type, Publisher& pub) { using tar_zst = tar_reader<zstd_reader>; auto const& cp = p.generic_string(); try { switch (type) { case file_type::ZST: parse_and_write_to_db(in, tar_zst(zstd_reader(cp.c_str())), type, pub); break; case file_type::ZIP: parse_and_write_to_db(in, zip_reader(cp.c_str()), type, pub); break; case file_type::XML: case file_type::PROTOBUF: case file_type::JSON: parse_and_write_to_db(in, file_reader(cp.c_str()), type, pub); break; default: assert(false); } } catch (...) { LOG(logging::error) << "failed to read " << p; } add_to_known_files(p); } template <typename Publisher> void parse_str_and_write_to_db(input& in, std::string_view sv, file_type const type, Publisher& pub) { switch (type) { case file_type::ZST: throw utl::fail("zst upload is not supported"); break; case file_type::ZIP: parse_and_write_to_db(in, zip_reader{sv.data(), sv.size()}, type, pub); break; case file_type::XML: case file_type::PROTOBUF: case file_type::JSON: parse_and_write_to_db(in, string_view_reader{sv}, type, pub); break; default: assert(false); } } template <typename Reader, typename Publisher> void parse_and_write_to_db(input& in, Reader&& reader, file_type const type, Publisher& pub) { auto const risml_fn = [&](std::string_view s, std::string_view, std::function<void(ris_message &&)> const& cb) { risml::to_ris_message(s, cb, in.tag()); }; auto const gtfsrt_fn = [&](std::string_view s, std::string_view, std::function<void(ris_message &&)> const& cb) { gtfsrt::to_ris_message(in.gtfs_knowledge(), config_.gtfs_is_addition_skip_allowed_, s, cb, in.tag()); }; auto const ribasis_fn = [&](std::string_view s, std::string_view, std::function<void(ris_message &&)> const& cb) { ribasis::to_ris_message(s, cb, in.tag()); }; auto const file_fn = [&](std::string_view s, std::string_view file_name, std::function<void(ris_message &&)> const& cb) { if (boost::ends_with(file_name, ".xml")) { return risml_fn(s, file_name, cb); } else if (boost::ends_with(file_name, ".json")) { return ribasis_fn(s, file_name, cb); } else if (boost::ends_with(file_name, ".pb")) { return gtfsrt_fn(s, file_name, cb); } }; switch (type) { case file_type::ZST: case file_type::ZIP: write_to_db(reader, file_fn, pub); break; case file_type::XML: write_to_db(reader, risml_fn, pub); break; case file_type::PROTOBUF: write_to_db(reader, gtfsrt_fn, pub); break; case file_type::JSON: write_to_db(reader, ribasis_fn, pub); break; default: assert(false); } } template <typename Reader, typename ParserFn, typename Publisher> void write_to_db(Reader&& reader, ParserFn parser_fn, Publisher& pub) { std::map<unixtime /* d.b */, unixtime /* min(t) : e <= d.e && l >= d.b */> min; std::map<unixtime /* d.b */, unixtime /* max(t) : e <= d.e && l >= d.b */> max; std::map<unixtime /* tout */, std::vector<char>> buf; auto buf_msg_count = 0U; auto flush_to_db = [&]() { if (buf.empty()) { return; } std::lock_guard<std::mutex> lock{merge_mutex_}; auto t = db::txn{env_}; auto db = t.dbi_open(MSG_DB); auto c = db::cursor{t, db}; for (auto& [timestamp, entry] : buf) { if (auto const v = c.get(lmdb::cursor_op::SET_RANGE, timestamp); v && v->first == timestamp) { entry.insert(end(entry), begin(v->second), end(v->second)); } c.put(timestamp, std::string_view{entry.data(), entry.size()}); } c.commit(); t.commit(); buf.clear(); }; auto write = [&](ris_message&& m) { if (buf_msg_count++ > WRITE_MSG_BUF_MAX_SIZE) { flush_to_db(); buf_msg_count = 0; } auto& buf_val = buf[m.timestamp_]; auto const base = buf_val.size(); buf_val.resize(buf_val.size() + SIZE_TYPE_SIZE + m.size()); auto const msg_size = static_cast<size_type>(m.size()); std::memcpy(buf_val.data() + base, &msg_size, SIZE_TYPE_SIZE); std::memcpy(buf_val.data() + base + SIZE_TYPE_SIZE, m.data(), m.size()); pub.add(m.data(), m.size()); for_each_day(m, [&](unixtime const d) { if (auto it = min.lower_bound(d); it != end(min) && it->first == d) { it->second = std::min(it->second, m.timestamp_); } else { min.emplace_hint(it, d, m.timestamp_); } if (auto it = max.lower_bound(d); it != end(max) && it->first == d) { it->second = std::max(it->second, m.timestamp_); } else { max.emplace_hint(it, d, m.timestamp_); } }); }; auto parse = std::forward<ParserFn>(parser_fn); std::optional<std::string_view> reader_content; while ((reader_content = reader.read())) { parse(*reader_content, reader.current_file_name(), [&](ris_message&& m) { write(std::move(m)); }); } flush_to_db(); update_min_max(min, max); pub.flush(); } void update_min_max(std::map<unixtime, unixtime> const& min, std::map<unixtime, unixtime> const& max) { std::lock_guard<std::mutex> lock{min_max_mutex_}; auto t = db::txn{env_}; auto min_db = t.dbi_open(MIN_DAY_DB); auto max_db = t.dbi_open(MAX_DAY_DB); for (auto const [day, min_timestamp] : min) { auto smallest = min_timestamp; if (auto entry = t.get(min_db, day); entry) { smallest = std::min(smallest, to_unixtime(*entry)); } t.put(min_db, day, from_unixtime(smallest)); } for (auto const [day, max_timestamp] : max) { auto largest = max_timestamp; if (auto entry = t.get(max_db, day); entry) { largest = std::max(largest, to_unixtime(*entry)); } t.put(max_db, day, from_unixtime(largest)); } t.commit(); } static void publish_system_time_changed(ctx::res_id_t schedule_res_id) { message_creator mc; mc.create_and_finish( MsgContent_RISSystemTimeChanged, CreateRISSystemTimeChanged(mc, schedule_res_id).Union(), "/ris/system_time_changed"); ctx::await_all(motis_publish(make_msg(mc))); } template <typename Publisher> void parse_and_publish_message(RISInputMessage const* rim, Publisher& pub) { auto content_sv = std::string_view{rim->content()->c_str(), rim->content()->size()}; auto const handle_message = [&](ris_message&& m) { pub.add(m.data(), m.size()); }; switch (rim->type()) { case RISContentType_RIBasis: { ribasis::to_ris_message(content_sv, handle_message); break; } case RISContentType_RISML: { risml::to_ris_message(content_sv, handle_message); break; } default: throw utl::fail("ris: unsupported message type"); } } void stop_io() const { if (ribasis_receiver_ != nullptr) { ribasis_receiver_->stop(); } } std::unique_ptr<amqp::ssl_connection> ribasis_receiver_; unixtime ribasis_receiver_last_update_{now()}; db::env env_; std::mutex min_max_mutex_; std::mutex merge_mutex_; config& config_; std::unique_ptr<input> file_upload_; std::vector<input> inputs_; bool rabbitmq_log_enabled_{false}; std::ofstream rabbitmq_log_file_; }; ris::ris() : module("RIS", "ris") { param(config_.db_path_, "db", "ris database path"); param(config_.input_, "input", "input paths. expected format [tag:]path (tag MUST match the " "timetable)"); param(config_.db_max_size_, "db_max_size", "virtual memory map size"); param(config_.init_time_, "init_time", "initial forward time"); param(config_.clear_db_, "clear_db", "clean db before init"); param(config_.instant_forward_, "instant_forward", "automatically forward after every file during read"); param(config_.gtfs_is_addition_skip_allowed_, "gtfsrt.is_addition_skip_allowed", "allow skips on additional trips"); param(config_.update_interval_, "update_interval", "RT update interval in seconds (RabbitMQ messages get buffered)"); param(config_.rabbitmq_.host_, "rabbitmq.host", "RabbitMQ remote host"); param(config_.rabbitmq_.port_, "rabbitmq.port", "RabbitMQ remote port"); param(config_.rabbitmq_.user_, "rabbitmq.username", "RabbitMQ username"); param(config_.rabbitmq_.pw_, "rabbitmq.password", "RabbitMQ password"); param(config_.rabbitmq_.vhost_, "rabbitmq.vhost", "RabbitMQ vhost"); param(config_.rabbitmq_.queue_, "rabbitmq.queue", "RabbitMQ queue name"); param(config_.rabbitmq_.ca_, "rabbitmq.ca", "RabbitMQ path to CA file"); param(config_.rabbitmq_.cert_, "rabbitmq.cert", "RabbitMQ path to client certificate"); param(config_.rabbitmq_.key_, "rabbitmq.key", "RabbitMQ path to client key file"); param(config_.rabbitmq_log_, "rabbitmq.log", "Path to log file for RabbitMQ messages (set to empty string to " "disable logging)"); } ris::~ris() = default; void ris::stop_io() { impl_->stop_io(); } void ris::reg_subc(motis::module::subc_reg& r) { r.register_cmd( "gtfsrt-json2pb", "json to protobuf", [](int argc, char const** argv) { if (argc != 3) { std::cout << "usage: " << argv[0] << " JSON_FILE PB_OUTPUT\n"; return 1; } auto const file = utl::read_file(argv[1]); if (!file.has_value()) { std::cout << "unable to read file " << argv[1] << "\n"; return 1; } auto const out = gtfsrt::json_to_protobuf(*file); utl::file{argv[2], "w"}.write(out.data(), out.size()); return 0; }); r.register_cmd("gtfsrt-pb2json", "protobuf to json", [](int argc, char const** argv) { if (argc != 2) { std::cout << "usage: " << argv[0] << " PB_FILE\n"; return 1; } auto const file = utl::read_file(argv[1]); if (!file.has_value()) { std::cout << "unable to read file " << argv[1] << "\n"; return 1; } std::cout << gtfsrt::protobuf_to_json(*file) << "\n"; return 0; }); } void ris::init(motis::module::registry& r) { impl_ = std::make_unique<impl>(config_); r.subscribe( "/init", [this]() { impl_->init(*shared_data_, const_cast<schedule&>(get_sched())); // NOLINT }, ctx::accesses_t{ctx::access_request{ to_res_id(::motis::module::global_res_id::SCHEDULE), ctx::access_t::WRITE}}); r.register_op( "/ris/upload", [this](auto&& m) { return impl_->upload(const_cast<schedule&>(get_sched()), m); // NOLINT }, ctx::accesses_t{ctx::access_request{ to_res_id(::motis::module::global_res_id::SCHEDULE), ctx::access_t::WRITE}}); r.register_op("/ris/forward", [this](auto&& m) { return impl_->forward(*this, m); }, {}); r.register_op( "/ris/read", [this](auto&& m) { return impl_->read(const_cast<schedule&>(get_sched()), m); // NOLINT }, ctx::accesses_t{ctx::access_request{ to_res_id(::motis::module::global_res_id::SCHEDULE), ctx::access_t::WRITE}}); r.register_op( "/ris/purge", [this](auto&& m) { return impl_->purge(m); }, ctx::accesses_t{ctx::access_request{ to_res_id(::motis::module::global_res_id::SCHEDULE), ctx::access_t::WRITE}}); r.register_op("/ris/apply", [this](auto&& m) { return impl_->apply(*this, m); }, {}); } } // namespace motis::ris
33.221223
80
0.593498
[ "vector" ]
76b22349a849a09c6e09651771b72d0cc45180a3
118
cpp
C++
src/calc/cache.cpp
mwthinker/Calculator
c6437b6d9a73b4f6afac80f35302d33bc8f76bfd
[ "MIT" ]
1
2015-10-28T20:14:39.000Z
2015-10-28T20:14:39.000Z
src/calc/cache.cpp
mwthinker/Calculator
c6437b6d9a73b4f6afac80f35302d33bc8f76bfd
[ "MIT" ]
null
null
null
src/calc/cache.cpp
mwthinker/Calculator
c6437b6d9a73b4f6afac80f35302d33bc8f76bfd
[ "MIT" ]
null
null
null
#include "cache.h" namespace calc { Cache::Cache(const std::vector<Symbol>& symbols) : symbols_{symbols} { } }
11.8
49
0.661017
[ "vector" ]
76b246c72308065391e1fe1383d2f8acc14237ae
1,513
hpp
C++
oanda_v20/include/oanda/v20/order/UnitsAvailableDetails.hpp
CodeRancher/offcenter_oanda
c7817299b2c7199508307b2379179923e3f60fdc
[ "Apache-2.0" ]
null
null
null
oanda_v20/include/oanda/v20/order/UnitsAvailableDetails.hpp
CodeRancher/offcenter_oanda
c7817299b2c7199508307b2379179923e3f60fdc
[ "Apache-2.0" ]
null
null
null
oanda_v20/include/oanda/v20/order/UnitsAvailableDetails.hpp
CodeRancher/offcenter_oanda
c7817299b2c7199508307b2379179923e3f60fdc
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2020 Scott Brauer * * 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 BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file UnitsAvailableDetails.hpp * @author Scott Brauer * * @date 12-07-2020 */ #ifndef OANDA_V20_ORDER_UNITSAVAILABLEDETAILS_HPP #define OANDA_V20_ORDER_UNITSAVAILABLEDETAILS_HPP #include <string> #include <vector> #include "oanda/v20/primitives/PrimitivesDefinitions.hpp" namespace oanda { namespace v20 { namespace order { /** * Representation of many units of an Instrument are available to be traded for both long and short Orders. * UnitsAvailableDetails is an application/json object with the following Schema: */ struct UnitsAvailableDetails { /** * @brief The units available for long Orders. */ oanda::v20::primitives::DecimalNumber longVal; /** * @brief The units available for short Orders. */ oanda::v20::primitives::DecimalNumber shortVal; }; } /* namespace order */ } /* namespace v20 */ } /* namespace oanda */ #endif /* OANDA_V20_ORDER_UNITSAVAILABLEDETAILS_HPP */
26.086207
107
0.738268
[ "object", "vector" ]
76be4bdfaa9a549bd9d3e4d551ef72a9e148d9bc
5,940
cpp
C++
src/cito/numdiff.cpp
aykutonol/cito
d8ee64a220929e1ffe7d5c91d934f8ff580bbd86
[ "BSD-3-Clause" ]
25
2019-03-07T18:10:21.000Z
2022-03-26T19:36:55.000Z
src/cito/numdiff.cpp
aykutonol/cito
d8ee64a220929e1ffe7d5c91d934f8ff580bbd86
[ "BSD-3-Clause" ]
1
2021-12-31T00:33:38.000Z
2022-01-29T23:31:38.000Z
src/cito/numdiff.cpp
aykutonol/cito
d8ee64a220929e1ffe7d5c91d934f8ff580bbd86
[ "BSD-3-Clause" ]
5
2019-03-12T20:53:24.000Z
2021-12-31T02:13:22.000Z
// ***** DESCRIPTION *********************************************************** // NumDiff defines methods for numerical differentiation of MuJoCo // dynamics including the forces imposed by the contact model. #include "cito/numdiff.h" // ***** CONSTRUCTOR *********************************************************** NumDiff::NumDiff(const mjModel *m_, Params *cp_, Control *cc_) : m(m_), cp(cp_), cc(cc_) { // initialize Eigen variables xNewTemp.resize(cp->n); xNewP.resize(cp->n); xNewN.resize(cp->n); uTemp.resize(cp->m); } // ***** FUNCTIONS ************************************************************* // copyTakeStep: sets xNew to the integration of data given a control input void NumDiff::copyTakeStep(const mjData *dMain, const eigVd &u, double *xNew, double compensateBias) { // create new data mjData *d; d = mj_makeData(m); // copy state and control from dMain to d d->time = dMain->time; mju_copy(d->qpos, dMain->qpos, m->nq); mju_copy(d->qvel, dMain->qvel, m->nv); mju_copy(d->qacc, dMain->qacc, m->nv); mju_copy(d->qacc_warmstart, dMain->qacc_warmstart, m->nv); mju_copy(d->qfrc_applied, dMain->qfrc_applied, m->nv); mju_copy(d->xfrc_applied, dMain->xfrc_applied, 6 * m->nbody); mju_copy(d->ctrl, dMain->ctrl, m->nu); // run full computation at center point (usually faster than copying dMain) mj_forward(m, d); cc->setControl(d, u, compensateBias); // take a full control step (i.e., tc/dt steps) cc->takeStep(d, u, 0, compensateBias); // get new state xNewTemp.setZero(); xNewTemp = cp->getState(d); mju_copy(xNew, xNewTemp.data(), cp->n); // delete data mj_deleteData(d); } // hardWorker: for full, slow finite-difference computation void NumDiff::hardWorker(const mjData *dMain, const eigVd &uMain, double *deriv, double compensateBias) { // create data mjData *d; d = mj_makeData(m); // copy state and control from dMain to d d->time = dMain->time; mju_copy(d->qpos, dMain->qpos, m->nq); mju_copy(d->qvel, dMain->qvel, m->nv); mju_copy(d->qacc, dMain->qacc, m->nv); mju_copy(d->qacc_warmstart, dMain->qacc_warmstart, m->nv); mju_copy(d->qfrc_applied, dMain->qfrc_applied, m->nv); mju_copy(d->xfrc_applied, dMain->xfrc_applied, 6 * m->nbody); mju_copy(d->ctrl, dMain->ctrl, m->nu); // finite-difference over positions for (int i = 0; i < m->nv; i++) { // get joint id for this dof int jID = m->dof_jntid[i]; // apply quaternion or simple perturbation if (cp->quatAdr[i] >= 0) { mjtNum angvel[3] = {0, 0, 0}; angvel[cp->dofAdr[i]] = eps; mju_quatIntegrate(d->qpos + cp->quatAdr[i], angvel, 1); } else { d->qpos[m->jnt_qposadr[jID] + i - m->jnt_dofadr[jID]] += eps; } // get the positive perturbed state xNewP.setZero(); this->copyTakeStep(d, uMain, xNewP.data(), compensateBias); // undo perturbation mju_copy(d->qpos, dMain->qpos, m->nq); // apply quaternion or simple perturbation if (cp->quatAdr[i] >= 0) { mjtNum angvel[3] = {0, 0, 0}; angvel[cp->dofAdr[i]] = -eps; mju_quatIntegrate(d->qpos + cp->quatAdr[i], angvel, 1); } else { d->qpos[m->jnt_qposadr[jID] + i - m->jnt_dofadr[jID]] -= eps; } // get the negative perturbed state xNewN.setZero(); this->copyTakeStep(d, uMain, xNewN.data(), compensateBias); // undo perturbation mju_copy(d->qpos, dMain->qpos, m->nq); // compute column i of dx/dqpos for (int j = 0; j < cp->n; j++) { deriv[i * cp->n + j] = (xNewP(j) - xNewN(j)) / (2 * eps); } } // finite-difference over velocities for (int i = 0; i < m->nv; i++) { // perturb velocity d->qvel[i] += eps; // get the positive perturbed state xNewP.setZero(); this->copyTakeStep(d, uMain, xNewP.data(), compensateBias); // perturb velocity d->qvel[i] = dMain->qvel[i] - eps; // get the negative perturbed state xNewN.setZero(); this->copyTakeStep(d, uMain, xNewN.data(), compensateBias); // undo perturbation d->qvel[i] = dMain->qvel[i]; // compute column i of dx/dqvel for (int j = 0; j < cp->n; j++) { deriv[cp->n * m->nv + i * cp->n + j] = (xNewP(j) - xNewN(j)) / (2 * eps); } } // finite-difference over control variables // copy uMain to uTemp for perturbations uTemp = uMain; for (int i = 0; i < cp->m; i++) { // perturbation in the positive direction uTemp(i) += eps; // get the positive perturbed state xNewP.setZero(); this->copyTakeStep(d, uTemp, xNewP.data(), compensateBias); // perturbation in the negative direction uTemp(i) -= 2 * eps; // get the negative perturbed state xNewN.setZero(); this->copyTakeStep(d, uTemp, xNewN.data(), compensateBias); // compute column i of dx/du for (int j = 0; j < cp->n; j++) { deriv[cp->n * cp->n + i * cp->n + j] = (xNewP(j) - xNewN(j)) / (2 * eps); } } // delete data mj_deleteData(d); } // linDyn: calculates derivatives of the state and control trajectories void NumDiff::linDyn(const mjData *dMain, const eigVd &uMain, double *Fxd, double *Fud, double compensateBias) { // TODO: consider doing the memory allocation/freeing in the constructor/destructor double *deriv = (double *)mju_malloc(sizeof(double) * cp->n * (cp->n + cp->m)); this->hardWorker(dMain, uMain, deriv, compensateBias); mju_copy(Fxd, deriv, cp->n * cp->n); mju_copy(Fud, deriv + cp->n * cp->n, cp->n * cp->m); mju_free(deriv); }
37.358491
110
0.561279
[ "model" ]
76c0acfea8a7ac2296f46f58f737e244dfff4af6
25,141
cpp
C++
cpp/gen/Speaker.cpp
ekke/c2gQtWS_x
665772f1ba8d2d175f343f250927a05cce1deafa
[ "Unlicense" ]
43
2016-10-16T08:16:42.000Z
2021-07-12T08:31:48.000Z
cpp/gen/Speaker.cpp
denis554/c2gQtWS_x
2a602efedd43a5942afb442d4e4862b3fe6af93e
[ "Unlicense" ]
7
2016-12-24T11:08:31.000Z
2022-03-02T08:19:04.000Z
cpp/gen/Speaker.cpp
denis554/c2gQtWS_x
2a602efedd43a5942afb442d4e4862b3fe6af93e
[ "Unlicense" ]
22
2016-10-18T05:39:36.000Z
2022-03-13T02:50:33.000Z
#include "Speaker.hpp" #include <QDebug> #include <quuid.h> // target also references to this #include "Session.hpp" // keys of QVariantMap used in this APP static const QString speakerIdKey = "speakerId"; static const QString isDeprecatedKey = "isDeprecated"; static const QString sortKeyKey = "sortKey"; static const QString sortGroupKey = "sortGroup"; static const QString nameKey = "name"; static const QString publicNameKey = "publicName"; static const QString titleKey = "title"; static const QString bioKey = "bio"; static const QString speakerImageKey = "speakerImage"; static const QString sessionsKey = "sessions"; static const QString conferencesKey = "conferences"; // keys used from Server API etc static const QString speakerIdForeignKey = "speakerId"; static const QString isDeprecatedForeignKey = "isDeprecated"; static const QString sortKeyForeignKey = "sortKey"; static const QString sortGroupForeignKey = "sortGroup"; static const QString nameForeignKey = "name"; static const QString publicNameForeignKey = "publicName"; static const QString titleForeignKey = "title"; static const QString bioForeignKey = "bio"; static const QString speakerImageForeignKey = "speakerImage"; static const QString sessionsForeignKey = "sessions"; static const QString conferencesForeignKey = "conferences"; /* * Default Constructor if Speaker not initialized from QVariantMap */ Speaker::Speaker(QObject *parent) : QObject(parent), mSpeakerId(-1), mIsDeprecated(false), mSortKey(""), mSortGroup(""), mName(""), mPublicName(""), mTitle(""), mBio("") { // lazy references: mSpeakerImage = -1; mSpeakerImageAsDataObject = 0; mSpeakerImageInvalid = false; // lazy Arrays where only keys are persisted mSessionsKeysResolved = false; mConferencesKeysResolved = false; } bool Speaker::isAllResolved() { if (hasSpeakerImage() && !isSpeakerImageResolvedAsDataObject()) { return false; } if(!areSessionsKeysResolved()) { return false; } if(!areConferencesKeysResolved()) { return false; } return true; } /* * initialize Speaker from QVariantMap * Map got from JsonDataAccess or so * includes also transient values * uses own property names * corresponding export method: toMap() */ void Speaker::fillFromMap(const QVariantMap& speakerMap) { mSpeakerId = speakerMap.value(speakerIdKey).toInt(); mIsDeprecated = speakerMap.value(isDeprecatedKey).toBool(); mSortKey = speakerMap.value(sortKeyKey).toString(); mSortGroup = speakerMap.value(sortGroupKey).toString(); mName = speakerMap.value(nameKey).toString(); mPublicName = speakerMap.value(publicNameKey).toString(); mTitle = speakerMap.value(titleKey).toString(); mBio = speakerMap.value(bioKey).toString(); // speakerImage lazy pointing to SpeakerImage* (domainKey: speakerId) if (speakerMap.contains(speakerImageKey)) { mSpeakerImage = speakerMap.value(speakerImageKey).toInt(); if (mSpeakerImage != -1) { // resolve the corresponding Data Object on demand from DataManager } } // mSessions is (lazy loaded) Array of Session* mSessionsKeys = speakerMap.value(sessionsKey).toStringList(); // mSessions must be resolved later if there are keys mSessionsKeysResolved = (mSessionsKeys.size() == 0); mSessions.clear(); // mConferences is (lazy loaded) Array of Conference* mConferencesKeys = speakerMap.value(conferencesKey).toStringList(); // mConferences must be resolved later if there are keys mConferencesKeysResolved = (mConferencesKeys.size() == 0); mConferences.clear(); } /* * initialize OrderData from QVariantMap * Map got from JsonDataAccess or so * includes also transient values * uses foreign property names - per ex. from Server API * corresponding export method: toForeignMap() */ void Speaker::fillFromForeignMap(const QVariantMap& speakerMap) { mSpeakerId = speakerMap.value(speakerIdForeignKey).toInt(); mIsDeprecated = speakerMap.value(isDeprecatedForeignKey).toBool(); mSortKey = speakerMap.value(sortKeyForeignKey).toString(); mSortGroup = speakerMap.value(sortGroupForeignKey).toString(); mName = speakerMap.value(nameForeignKey).toString(); mPublicName = speakerMap.value(publicNameForeignKey).toString(); mTitle = speakerMap.value(titleForeignKey).toString(); mBio = speakerMap.value(bioForeignKey).toString(); // speakerImage lazy pointing to SpeakerImage* (domainKey: speakerId) if (speakerMap.contains(speakerImageForeignKey)) { mSpeakerImage = speakerMap.value(speakerImageForeignKey).toInt(); if (mSpeakerImage != -1) { // resolve the corresponding Data Object on demand from DataManager } } // mSessions is (lazy loaded) Array of Session* mSessionsKeys = speakerMap.value(sessionsForeignKey).toStringList(); // mSessions must be resolved later if there are keys mSessionsKeysResolved = (mSessionsKeys.size() == 0); mSessions.clear(); // mConferences is (lazy loaded) Array of Conference* mConferencesKeys = speakerMap.value(conferencesForeignKey).toStringList(); // mConferences must be resolved later if there are keys mConferencesKeysResolved = (mConferencesKeys.size() == 0); mConferences.clear(); } /* * initialize OrderData from QVariantMap * Map got from JsonDataAccess or so * excludes transient values * uses own property names * corresponding export method: toCacheMap() */ void Speaker::fillFromCacheMap(const QVariantMap& speakerMap) { mSpeakerId = speakerMap.value(speakerIdKey).toInt(); mIsDeprecated = speakerMap.value(isDeprecatedKey).toBool(); mSortKey = speakerMap.value(sortKeyKey).toString(); mSortGroup = speakerMap.value(sortGroupKey).toString(); mName = speakerMap.value(nameKey).toString(); mPublicName = speakerMap.value(publicNameKey).toString(); mTitle = speakerMap.value(titleKey).toString(); mBio = speakerMap.value(bioKey).toString(); // speakerImage lazy pointing to SpeakerImage* (domainKey: speakerId) if (speakerMap.contains(speakerImageKey)) { mSpeakerImage = speakerMap.value(speakerImageKey).toInt(); if (mSpeakerImage != -1) { // resolve the corresponding Data Object on demand from DataManager } } // mSessions is (lazy loaded) Array of Session* mSessionsKeys = speakerMap.value(sessionsKey).toStringList(); // mSessions must be resolved later if there are keys mSessionsKeysResolved = (mSessionsKeys.size() == 0); mSessions.clear(); // mConferences is (lazy loaded) Array of Conference* mConferencesKeys = speakerMap.value(conferencesKey).toStringList(); // mConferences must be resolved later if there are keys mConferencesKeysResolved = (mConferencesKeys.size() == 0); mConferences.clear(); } void Speaker::prepareNew() { } /* * Checks if all mandatory attributes, all DomainKeys and uuid's are filled */ bool Speaker::isValid() { if (mSpeakerId == -1) { return false; } return true; } /* * Exports Properties from Speaker as QVariantMap * exports ALL data including transient properties * To store persistent Data in JsonDataAccess use toCacheMap() */ QVariantMap Speaker::toMap() { QVariantMap speakerMap; // speakerImage lazy pointing to SpeakerImage* (domainKey: speakerId) if (mSpeakerImage != -1) { speakerMap.insert(speakerImageKey, mSpeakerImage); } // mSessions points to Session* // lazy array: persist only keys // // if keys alreadyy resolved: clear them // otherwise reuse the keys and add objects from mPositions // this can happen if added to objects without resolving keys before if(mSessionsKeysResolved) { mSessionsKeys.clear(); } // add objects from mPositions for (int i = 0; i < mSessions.size(); ++i) { Session* session; session = mSessions.at(i); mSessionsKeys << QString::number(session->sessionId()); } speakerMap.insert(sessionsKey, mSessionsKeys); // mConferences points to Conference* // lazy array: persist only keys // // if keys alreadyy resolved: clear them // otherwise reuse the keys and add objects from mPositions // this can happen if added to objects without resolving keys before if(mConferencesKeysResolved) { mConferencesKeys.clear(); } // add objects from mPositions for (int i = 0; i < mConferences.size(); ++i) { Conference* conference; conference = mConferences.at(i); mConferencesKeys << QString::number(conference->id()); } speakerMap.insert(conferencesKey, mConferencesKeys); speakerMap.insert(speakerIdKey, mSpeakerId); speakerMap.insert(isDeprecatedKey, mIsDeprecated); speakerMap.insert(sortKeyKey, mSortKey); speakerMap.insert(sortGroupKey, mSortGroup); speakerMap.insert(nameKey, mName); speakerMap.insert(publicNameKey, mPublicName); speakerMap.insert(titleKey, mTitle); speakerMap.insert(bioKey, mBio); return speakerMap; } /* * Exports Properties from Speaker as QVariantMap * To send data as payload to Server * Makes it possible to use defferent naming conditions */ QVariantMap Speaker::toForeignMap() { QVariantMap speakerMap; // speakerImage lazy pointing to SpeakerImage* (domainKey: speakerId) if (mSpeakerImage != -1) { speakerMap.insert(speakerImageForeignKey, mSpeakerImage); } // mSessions points to Session* // lazy array: persist only keys // // if keys alreadyy resolved: clear them // otherwise reuse the keys and add objects from mPositions // this can happen if added to objects without resolving keys before if(mSessionsKeysResolved) { mSessionsKeys.clear(); } // add objects from mPositions for (int i = 0; i < mSessions.size(); ++i) { Session* session; session = mSessions.at(i); mSessionsKeys << QString::number(session->sessionId()); } speakerMap.insert(sessionsForeignKey, mSessionsKeys); // mConferences points to Conference* // lazy array: persist only keys // // if keys alreadyy resolved: clear them // otherwise reuse the keys and add objects from mPositions // this can happen if added to objects without resolving keys before if(mConferencesKeysResolved) { mConferencesKeys.clear(); } // add objects from mPositions for (int i = 0; i < mConferences.size(); ++i) { Conference* conference; conference = mConferences.at(i); mConferencesKeys << QString::number(conference->id()); } speakerMap.insert(conferencesForeignKey, mConferencesKeys); speakerMap.insert(speakerIdForeignKey, mSpeakerId); speakerMap.insert(isDeprecatedForeignKey, mIsDeprecated); speakerMap.insert(sortKeyForeignKey, mSortKey); speakerMap.insert(sortGroupForeignKey, mSortGroup); speakerMap.insert(nameForeignKey, mName); speakerMap.insert(publicNameForeignKey, mPublicName); speakerMap.insert(titleForeignKey, mTitle); speakerMap.insert(bioForeignKey, mBio); return speakerMap; } /* * Exports Properties from Speaker as QVariantMap * transient properties are excluded: * To export ALL data use toMap() */ QVariantMap Speaker::toCacheMap() { // no transient properties found from data model // use default toMao() return toMap(); } // REF // Lazy: speakerImage // Optional: speakerImage // speakerImage lazy pointing to SpeakerImage* (domainKey: speakerId) int Speaker::speakerImage() const { return mSpeakerImage; } SpeakerImage* Speaker::speakerImageAsDataObject() const { return mSpeakerImageAsDataObject; } void Speaker::setSpeakerImage(int speakerImage) { if (speakerImage != mSpeakerImage) { // remove old Data Object if one was resolved if (mSpeakerImageAsDataObject) { // reset pointer, don't delete the independent object ! mSpeakerImageAsDataObject = 0; } // set the new lazy reference mSpeakerImage = speakerImage; mSpeakerImageInvalid = false; emit speakerImageChanged(speakerImage); if (speakerImage != -1) { // resolve the corresponding Data Object on demand from DataManager } } } void Speaker::removeSpeakerImage() { if (mSpeakerImage != -1) { setSpeakerImage(-1); } } bool Speaker::hasSpeakerImage() { if (!mSpeakerImageInvalid && mSpeakerImage != -1) { return true; } else { return false; } } bool Speaker::isSpeakerImageResolvedAsDataObject() { if (!mSpeakerImageInvalid && mSpeakerImageAsDataObject) { return true; } else { return false; } } // lazy bound Data Object was resolved. overwrite speakerId if different void Speaker::resolveSpeakerImageAsDataObject(SpeakerImage* speakerImage) { if (speakerImage) { if (speakerImage->speakerId() != mSpeakerImage) { setSpeakerImage(speakerImage->speakerId()); } mSpeakerImageAsDataObject = speakerImage; mSpeakerImageInvalid = false; } } void Speaker::markSpeakerImageAsInvalid() { mSpeakerImageInvalid = true; } // ATT // Mandatory: speakerId // Domain KEY: speakerId int Speaker::speakerId() const { return mSpeakerId; } void Speaker::setSpeakerId(int speakerId) { if (speakerId != mSpeakerId) { mSpeakerId = speakerId; emit speakerIdChanged(speakerId); } } // ATT // Optional: isDeprecated bool Speaker::isDeprecated() const { return mIsDeprecated; } void Speaker::setIsDeprecated(bool isDeprecated) { if (isDeprecated != mIsDeprecated) { mIsDeprecated = isDeprecated; emit isDeprecatedChanged(isDeprecated); } } // ATT // Optional: sortKey QString Speaker::sortKey() const { return mSortKey; } void Speaker::setSortKey(QString sortKey) { if (sortKey != mSortKey) { mSortKey = sortKey; emit sortKeyChanged(sortKey); } } // ATT // Optional: sortGroup QString Speaker::sortGroup() const { return mSortGroup; } void Speaker::setSortGroup(QString sortGroup) { if (sortGroup != mSortGroup) { mSortGroup = sortGroup; emit sortGroupChanged(sortGroup); } } // ATT // Optional: name QString Speaker::name() const { return mName; } void Speaker::setName(QString name) { if (name != mName) { mName = name; emit nameChanged(name); } } // ATT // Optional: publicName QString Speaker::publicName() const { return mPublicName; } void Speaker::setPublicName(QString publicName) { if (publicName != mPublicName) { mPublicName = publicName; emit publicNameChanged(publicName); } } // ATT // Optional: title QString Speaker::title() const { return mTitle; } void Speaker::setTitle(QString title) { if (title != mTitle) { mTitle = title; emit titleChanged(title); } } // ATT // Optional: bio QString Speaker::bio() const { return mBio; } void Speaker::setBio(QString bio) { if (bio != mBio) { mBio = bio; emit bioChanged(bio); } } // ATT // Optional: sessions QVariantList Speaker::sessionsAsQVariantList() { QVariantList sessionsList; for (int i = 0; i < mSessions.size(); ++i) { sessionsList.append((mSessions.at(i))->toMap()); } return sessionsList; } QVariantList Speaker::sessionsAsCacheQVariantList() { QVariantList sessionsList; for (int i = 0; i < mSessions.size(); ++i) { sessionsList.append((mSessions.at(i))->toCacheMap()); } return sessionsList; } QVariantList Speaker::sessionsAsForeignQVariantList() { QVariantList sessionsList; for (int i = 0; i < mSessions.size(); ++i) { sessionsList.append((mSessions.at(i))->toForeignMap()); } return sessionsList; } // no create() or undoCreate() because dto is root object // see methods in DataManager /** * you can add sessions without resolving existing keys before * attention: before looping through the objects * you must resolveSessionsKeys */ void Speaker::addToSessions(Session* session) { mSessions.append(session); emit addedToSessions(session); emit sessionsPropertyListChanged(); } bool Speaker::removeFromSessions(Session* session) { bool ok = false; ok = mSessions.removeOne(session); if (!ok) { qDebug() << "Session* not found in sessions"; return false; } emit sessionsPropertyListChanged(); // sessions are independent - DON'T delete them return true; } void Speaker::clearSessions() { for (int i = mSessions.size(); i > 0; --i) { removeFromSessions(mSessions.last()); } mSessionsKeys.clear(); } /** * lazy Array of independent Data Objects: only keys are persited * so we get a list of keys (uuid or domain keys) from map * and we persist only the keys toMap() * after initializing the keys must be resolved: * - get the list of keys: sessionsKeys() * - resolve them from DataManager * - then resolveSessionsKeys() */ bool Speaker::areSessionsKeysResolved() { return mSessionsKeysResolved; } QStringList Speaker::sessionsKeys() { return mSessionsKeys; } /** * Objects from sessionsKeys will be added to existing sessions * This enables to use addToSessions() without resolving before * Hint: it's your responsibility to resolve before looping thru sessions */ void Speaker::resolveSessionsKeys(QList<Session*> sessions) { if(mSessionsKeysResolved){ return; } // don't clear mSessions (see above) for (int i = 0; i < sessions.size(); ++i) { addToSessions(sessions.at(i)); } mSessionsKeysResolved = true; } int Speaker::sessionsCount() { return mSessions.size(); } QList<Session*> Speaker::sessions() { return mSessions; } void Speaker::setSessions(QList<Session*> sessions) { if (sessions != mSessions) { mSessions = sessions; emit sessionsChanged(sessions); emit sessionsPropertyListChanged(); } } /** * to access lists from QML we're using QQmlListProperty * and implement methods to append, count and clear * now from QML we can use * speaker.sessionsPropertyList.length to get the size * speaker.sessionsPropertyList[2] to get Session* at position 2 * speaker.sessionsPropertyList = [] to clear the list * or get easy access to properties like * speaker.sessionsPropertyList[2].myPropertyName */ QQmlListProperty<Session> Speaker::sessionsPropertyList() { return QQmlListProperty<Session>(this, 0, &Speaker::appendToSessionsProperty, &Speaker::sessionsPropertyCount, &Speaker::atSessionsProperty, &Speaker::clearSessionsProperty); } void Speaker::appendToSessionsProperty(QQmlListProperty<Session> *sessionsList, Session* session) { Speaker *speakerObject = qobject_cast<Speaker *>(sessionsList->object); if (speakerObject) { speakerObject->mSessions.append(session); emit speakerObject->addedToSessions(session); } else { qWarning() << "cannot append Session* to sessions " << "Object is not of type Speaker*"; } } int Speaker::sessionsPropertyCount(QQmlListProperty<Session> *sessionsList) { Speaker *speaker = qobject_cast<Speaker *>(sessionsList->object); if (speaker) { return speaker->mSessions.size(); } else { qWarning() << "cannot get size sessions " << "Object is not of type Speaker*"; } return 0; } Session* Speaker::atSessionsProperty(QQmlListProperty<Session> *sessionsList, int pos) { Speaker *speaker = qobject_cast<Speaker *>(sessionsList->object); if (speaker) { if (speaker->mSessions.size() > pos) { return speaker->mSessions.at(pos); } qWarning() << "cannot get Session* at pos " << pos << " size is " << speaker->mSessions.size(); } else { qWarning() << "cannot get Session* at pos " << pos << "Object is not of type Speaker*"; } return 0; } void Speaker::clearSessionsProperty(QQmlListProperty<Session> *sessionsList) { Speaker *speaker = qobject_cast<Speaker *>(sessionsList->object); if (speaker) { // sessions are independent - DON'T delete them speaker->mSessions.clear(); } else { qWarning() << "cannot clear sessions " << "Object is not of type Speaker*"; } } // ATT // Optional: conferences QVariantList Speaker::conferencesAsQVariantList() { QVariantList conferencesList; for (int i = 0; i < mConferences.size(); ++i) { conferencesList.append((mConferences.at(i))->toMap()); } return conferencesList; } QVariantList Speaker::conferencesAsCacheQVariantList() { QVariantList conferencesList; for (int i = 0; i < mConferences.size(); ++i) { conferencesList.append((mConferences.at(i))->toCacheMap()); } return conferencesList; } QVariantList Speaker::conferencesAsForeignQVariantList() { QVariantList conferencesList; for (int i = 0; i < mConferences.size(); ++i) { conferencesList.append((mConferences.at(i))->toForeignMap()); } return conferencesList; } // no create() or undoCreate() because dto is root object // see methods in DataManager /** * you can add conferences without resolving existing keys before * attention: before looping through the objects * you must resolveConferencesKeys */ void Speaker::addToConferences(Conference* conference) { mConferences.append(conference); emit addedToConferences(conference); emit conferencesPropertyListChanged(); } bool Speaker::removeFromConferences(Conference* conference) { bool ok = false; ok = mConferences.removeOne(conference); if (!ok) { qDebug() << "Conference* not found in conferences"; return false; } emit conferencesPropertyListChanged(); // conferences are independent - DON'T delete them return true; } void Speaker::clearConferences() { for (int i = mConferences.size(); i > 0; --i) { removeFromConferences(mConferences.last()); } mConferencesKeys.clear(); } /** * lazy Array of independent Data Objects: only keys are persited * so we get a list of keys (uuid or domain keys) from map * and we persist only the keys toMap() * after initializing the keys must be resolved: * - get the list of keys: conferencesKeys() * - resolve them from DataManager * - then resolveConferencesKeys() */ bool Speaker::areConferencesKeysResolved() { return mConferencesKeysResolved; } QStringList Speaker::conferencesKeys() { return mConferencesKeys; } /** * Objects from conferencesKeys will be added to existing conferences * This enables to use addToConferences() without resolving before * Hint: it's your responsibility to resolve before looping thru conferences */ void Speaker::resolveConferencesKeys(QList<Conference*> conferences) { if(mConferencesKeysResolved){ return; } // don't clear mConferences (see above) for (int i = 0; i < conferences.size(); ++i) { addToConferences(conferences.at(i)); } mConferencesKeysResolved = true; } int Speaker::conferencesCount() { return mConferences.size(); } QList<Conference*> Speaker::conferences() { return mConferences; } void Speaker::setConferences(QList<Conference*> conferences) { if (conferences != mConferences) { mConferences = conferences; emit conferencesChanged(conferences); emit conferencesPropertyListChanged(); } } /** * to access lists from QML we're using QQmlListProperty * and implement methods to append, count and clear * now from QML we can use * speaker.conferencesPropertyList.length to get the size * speaker.conferencesPropertyList[2] to get Conference* at position 2 * speaker.conferencesPropertyList = [] to clear the list * or get easy access to properties like * speaker.conferencesPropertyList[2].myPropertyName */ QQmlListProperty<Conference> Speaker::conferencesPropertyList() { return QQmlListProperty<Conference>(this, 0, &Speaker::appendToConferencesProperty, &Speaker::conferencesPropertyCount, &Speaker::atConferencesProperty, &Speaker::clearConferencesProperty); } void Speaker::appendToConferencesProperty(QQmlListProperty<Conference> *conferencesList, Conference* conference) { Speaker *speakerObject = qobject_cast<Speaker *>(conferencesList->object); if (speakerObject) { speakerObject->mConferences.append(conference); emit speakerObject->addedToConferences(conference); } else { qWarning() << "cannot append Conference* to conferences " << "Object is not of type Speaker*"; } } int Speaker::conferencesPropertyCount(QQmlListProperty<Conference> *conferencesList) { Speaker *speaker = qobject_cast<Speaker *>(conferencesList->object); if (speaker) { return speaker->mConferences.size(); } else { qWarning() << "cannot get size conferences " << "Object is not of type Speaker*"; } return 0; } Conference* Speaker::atConferencesProperty(QQmlListProperty<Conference> *conferencesList, int pos) { Speaker *speaker = qobject_cast<Speaker *>(conferencesList->object); if (speaker) { if (speaker->mConferences.size() > pos) { return speaker->mConferences.at(pos); } qWarning() << "cannot get Conference* at pos " << pos << " size is " << speaker->mConferences.size(); } else { qWarning() << "cannot get Conference* at pos " << pos << "Object is not of type Speaker*"; } return 0; } void Speaker::clearConferencesProperty(QQmlListProperty<Conference> *conferencesList) { Speaker *speaker = qobject_cast<Speaker *>(conferencesList->object); if (speaker) { // conferences are independent - DON'T delete them speaker->mConferences.clear(); } else { qWarning() << "cannot clear conferences " << "Object is not of type Speaker*"; } } Speaker::~Speaker() { // place cleanUp code here }
29.85867
141
0.719343
[ "object", "model" ]
76c6a59b29a0779e28c7be08061f2842db9d179f
3,778
hpp
C++
include/STP/Core/Image.hpp
mustafmst/lost-dungeon
78eab777dc4ffeacca48e647cf5945628992ce7c
[ "MIT" ]
33
2015-06-26T19:39:40.000Z
2022-01-03T23:34:12.000Z
include/STP/Core/Image.hpp
arnavr23/STP
7c027a84d61137f092f4fac7d847a0085b156dbc
[ "MIT" ]
25
2015-02-17T17:02:51.000Z
2020-08-23T22:57:55.000Z
include/STP/Core/Image.hpp
arnavr23/STP
7c027a84d61137f092f4fac7d847a0085b156dbc
[ "MIT" ]
26
2015-02-14T18:21:14.000Z
2020-07-27T04:39:30.000Z
//////////////////////////////////////////////////////////// // // The MIT License (MIT) // // STP - SFML TMX Parser // Copyright (c) 2013-2014 Manuel Sabogal // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // //////////////////////////////////////////////////////////// #ifndef STP_IMAGE_HPP #define STP_IMAGE_HPP //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <string> #include <vector> #include "SFML/Graphics/Image.hpp" #include "SFML/Graphics/Texture.hpp" #include "STP/Config.hpp" namespace tmx { //////////////////////////////////////////////////////////// /// \brief Class for loading images /// //////////////////////////////////////////////////////////// class STP_API Image { public: //////////////////////////////////////////////////////////// /// \brief Default constructor /// //////////////////////////////////////////////////////////// Image(); //////////////////////////////////////////////////////////// /// \brief Load a image given a source /// /// \param source The reference to the tileset image file /// \param width The image width in pixels. (Defaults to 0) /// \param height The image height in pixels. (Defaults to 0) /// \param trans Defines a specific color that is treated as transparent (example value: 0xFF00FF for magenta) /// \param format Used for embedded images, in combination with a data child element /// //////////////////////////////////////////////////////////// Image(const std::string& source, unsigned int width = 0, unsigned int height = 0, int32_t trans = -1, const std::string& format = std::string()); public: //////////////////////////////////////////////////////////// /// \brief Return the image width /// /// \return The image width in pixels /// //////////////////////////////////////////////////////////// unsigned int GetWidth() const; //////////////////////////////////////////////////////////// /// \brief Return the image height /// /// \return The image height in pixels /// //////////////////////////////////////////////////////////// unsigned int GetHeight() const; //////////////////////////////////////////////////////////// /// \brief Return sf::Texture attached to the image /// /// \return Pointer to a constant sf::Texture /// //////////////////////////////////////////////////////////// const sf::Texture* GetTexture() const; private: std::string source_; int32_t trans_; unsigned int width_, height_; std::string format_; sf::Texture texture_; }; } // namespace tmx #endif // STP_IMAGE_HPP
36.326923
115
0.507676
[ "vector" ]
76ca0199bc94ccfafbc62f5d2de538c7466eca87
3,005
cpp
C++
android-28/java/util/zip/Inflater.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/java/util/zip/Inflater.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/java/util/zip/Inflater.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../../../JByteArray.hpp" #include "../../nio/ByteBuffer.hpp" #include "./Inflater.hpp" namespace java::util::zip { // Fields // QJniObject forward Inflater::Inflater(QJniObject obj) : JObject(obj) {} // Constructors Inflater::Inflater() : JObject( "java.util.zip.Inflater", "()V" ) {} Inflater::Inflater(jboolean arg0) : JObject( "java.util.zip.Inflater", "(Z)V", arg0 ) {} // Methods void Inflater::end() const { callMethod<void>( "end", "()V" ); } jboolean Inflater::finished() const { return callMethod<jboolean>( "finished", "()Z" ); } jint Inflater::getAdler() const { return callMethod<jint>( "getAdler", "()I" ); } jlong Inflater::getBytesRead() const { return callMethod<jlong>( "getBytesRead", "()J" ); } jlong Inflater::getBytesWritten() const { return callMethod<jlong>( "getBytesWritten", "()J" ); } jint Inflater::getRemaining() const { return callMethod<jint>( "getRemaining", "()I" ); } jint Inflater::getTotalIn() const { return callMethod<jint>( "getTotalIn", "()I" ); } jint Inflater::getTotalOut() const { return callMethod<jint>( "getTotalOut", "()I" ); } jint Inflater::inflate(JByteArray arg0) const { return callMethod<jint>( "inflate", "([B)I", arg0.object<jbyteArray>() ); } jint Inflater::inflate(java::nio::ByteBuffer arg0) const { return callMethod<jint>( "inflate", "(Ljava/nio/ByteBuffer;)I", arg0.object() ); } jint Inflater::inflate(JByteArray arg0, jint arg1, jint arg2) const { return callMethod<jint>( "inflate", "([BII)I", arg0.object<jbyteArray>(), arg1, arg2 ); } jboolean Inflater::needsDictionary() const { return callMethod<jboolean>( "needsDictionary", "()Z" ); } jboolean Inflater::needsInput() const { return callMethod<jboolean>( "needsInput", "()Z" ); } void Inflater::reset() const { callMethod<void>( "reset", "()V" ); } void Inflater::setDictionary(JByteArray arg0) const { callMethod<void>( "setDictionary", "([B)V", arg0.object<jbyteArray>() ); } void Inflater::setDictionary(java::nio::ByteBuffer arg0) const { callMethod<void>( "setDictionary", "(Ljava/nio/ByteBuffer;)V", arg0.object() ); } void Inflater::setDictionary(JByteArray arg0, jint arg1, jint arg2) const { callMethod<void>( "setDictionary", "([BII)V", arg0.object<jbyteArray>(), arg1, arg2 ); } void Inflater::setInput(JByteArray arg0) const { callMethod<void>( "setInput", "([B)V", arg0.object<jbyteArray>() ); } void Inflater::setInput(java::nio::ByteBuffer arg0) const { callMethod<void>( "setInput", "(Ljava/nio/ByteBuffer;)V", arg0.object() ); } void Inflater::setInput(JByteArray arg0, jint arg1, jint arg2) const { callMethod<void>( "setInput", "([BII)V", arg0.object<jbyteArray>(), arg1, arg2 ); } } // namespace java::util::zip
16.420765
74
0.614309
[ "object" ]
76cab5198f18265690f9e968a22a96faf602feaf
1,595
cpp
C++
Geeks For Geeks Solutions/Stack/Maximum Rectangular Area in a Histogram.cpp
bilwa496/Placement-Preparation
bd32ee717f671d95c17f524ed28b0179e0feb044
[ "MIT" ]
169
2021-05-30T10:02:19.000Z
2022-03-27T18:09:32.000Z
Geeks For Geeks Solutions/Stack/Maximum Rectangular Area in a Histogram.cpp
bilwa496/Placement-Preparation
bd32ee717f671d95c17f524ed28b0179e0feb044
[ "MIT" ]
1
2021-10-02T14:46:26.000Z
2021-10-02T14:46:26.000Z
Geeks For Geeks Solutions/Stack/Maximum Rectangular Area in a Histogram.cpp
bilwa496/Placement-Preparation
bd32ee717f671d95c17f524ed28b0179e0feb044
[ "MIT" ]
44
2021-05-30T19:56:29.000Z
2022-03-17T14:49:00.000Z
#define ll long long int #define pb push_back #define M 1000000007 #define fs for(int i=0;i<s.size();i++) using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); ll t; cin>>t; while(t--) { ll n; cin>>n; ll a[n]; ll sum=0; ll count=0; for(int i=0;i<n;i++) { cin>>a[i]; } vector<ll> right; stack<pair<ll,ll>> s; ll index=n; for(int i=n-1;i>=0;i--) { if(s.size()==0) { right.push_back(index); } else if(s.size() > 0 && s.top().first < a[i]) { right.push_back(s.top().second); } else if(s.size() > 0 && s.top().first >= a[i]) { while(s.size() > 0 && s.top().first >= a[i]) { s.pop(); } if(s.size() > 0) right.push_back(s.top().second); else right.push_back(index); } s.push({a[i],i}); } reverse(right.begin(),right.end()); vector<ll> left; stack<pair<ll,ll>> s2; ll index2=-1; for(int i=0;i<n;i++) { if(s2.size()==0) { left.push_back(index2); } else if(s2.size() > 0 && s2.top().first < a[i]) { left.push_back(s2.top().second); } else if(s2.size() > 0 && s2.top().first >= a[i]) { while(s2.size() > 0 && s2.top().first >= a[i]) { s2.pop(); } if(s2.size() > 0) left.push_back(s2.top().second); else left.push_back(index2); } s2.push({a[i],i}); } ll width[n]; ll maxi=0; for(int i=0;i<n;i++) { width[i]= right[i] - left[i] - 1; maxi = max(maxi,width[i]*a[i]); } cout << maxi << endl; } return 0 ; }
17.336957
54
0.485893
[ "vector" ]
76d309b51d6cbc3b9ef3e684dec6f259b3288ae4
4,445
cpp
C++
gpu.cpp
finkandreas/affinity
39107bf89826c675a03aa1e4d8d2af5767487fcd
[ "BSD-3-Clause" ]
3
2019-04-27T18:38:17.000Z
2020-05-19T08:35:03.000Z
gpu.cpp
finkandreas/affinity
39107bf89826c675a03aa1e4d8d2af5767487fcd
[ "BSD-3-Clause" ]
null
null
null
gpu.cpp
finkandreas/affinity
39107bf89826c675a03aa1e4d8d2af5767487fcd
[ "BSD-3-Clause" ]
3
2017-09-06T09:11:38.000Z
2021-06-09T15:42:45.000Z
#include <algorithm> #include <array> #include <cstring> #include <iomanip> #include <numeric> #include <ostream> #include <vector> #include <cuda_runtime.h> #include "gpu.hpp" #include <iostream> // Test GPU uids for equality bool operator==(const uuid& lhs, const uuid& rhs) { for (auto i=0u; i<lhs.bytes.size(); ++i) { if (lhs.bytes[i]!=rhs.bytes[i]) return false; } return true; } // Strict lexographical ordering of GPU uids bool operator<(const uuid& lhs, const uuid& rhs) { for (auto i=0u; i<lhs.bytes.size(); ++i) { if (lhs.bytes[i]<rhs.bytes[i]) return true; if (lhs.bytes[i]>lhs.bytes[i]) return false; } return false; } std::ostream& operator<<(std::ostream& o, const uuid& id) { o << std::hex << std::setfill('0'); bool first = true; int ranges[6] = {0, 4, 6, 8, 10, 16}; for (int i=0; i<5; ++i) { // because std::size isn't available till C++17 if (!first) o << "-"; for (auto j=ranges[i]; j<ranges[i+1]; ++j) { o << std::setw(2) << (int)id.bytes[j]; } first = false; } o << std::dec; return o; } // Split CUDA_VISIBLE_DEVICES variable string into a list of integers. // The environment variable can have spaces, and the order is important: // i.e. "0,1" is not the same as "1,0". // CUDA_VISIBLE_DEVICES="1,0" // CUDA_VISIBLE_DEVICES="0, 1" // The CUDA run time parses the list until it finds an error, then returns // the partial list. // i.e. // CUDA_VISIBLE_DEVICES="1, 0, hello" -> {1,0} // CUDA_VISIBLE_DEVICES="hello, 1" -> {} // All non-numeric characters appear to be ignored: // CUDA_VISIBLE_DEVICES="0a,1" -> {0,1} // This doesn't try too hard to check for all possible errors. std::vector<int> parse_visible_devices(std::string str, unsigned ngpu) { // Tokenize into a sequence of strings separated by commas std::vector<std::string> strings; std::size_t first = 0; std::size_t last = str.find(','); while (last != std::string::npos) { strings.push_back(str.substr(first, last - first)); first = last + 1; last = str.find(',', first); } strings.push_back(str.substr(first, last - first)); // Convert each token to an integer. // Return partial list of ids on first error: // - error converting token to string; // - invalid GPU id found. std::vector<int> values; for (auto& s: strings) { try { int v = std::stoi(s); if (v<0 || v>=ngpu) break; values.push_back(v); } catch (std::exception e) { break; } } return values; } // Take a uuid string with the format: // GPU-f1fd7811-e4d3-4d54-abb7-efc579fb1e28 // And convert to a 16 byte sequence // // Assume that the intput string is correctly formatted. uuid string_to_uuid(char* str) { uuid result; unsigned n = std::strlen(str); // Remove the "GPU" from front of string, and the '-' hyphens, e.g.: // GPU-f1fd7811-e4d3-4d54-abb7-efc579fb1e28 // becomes // f1fd7811e4d34d54abb7efc579fb1e28 auto pos = std::remove_if( str, str+n, [](char c){return !std::isxdigit(c);}); // Converts a single hex character, i.e. 0123456789abcdef, to int // Assumes that input is a valid hex character. auto hex_c2i = [](char c) -> unsigned char { return std::isalpha(c)? c-'a'+10: c-'0'; }; // Convert pairs of characters into single bytes. for (int i=0; i<16; ++i) { const char* s = str+2*i; result.bytes[i] = (hex_c2i(s[0])<<4) + hex_c2i(s[1]); } return result; } std::vector<uuid> get_gpu_uuids() { // get number of devices int ngpus = 0; if (cudaGetDeviceCount(&ngpus)!=cudaSuccess) return {}; // store the uuids std::vector<uuid> uuids(ngpus); // using CUDA 10 or later, determining uuid of GPUs is easy! for (int i=0; i<ngpus; ++i) { cudaDeviceProp props; if (cudaGetDeviceProperties(&props, i)!=cudaSuccess) return {}; uuids[i] = props.uuid; } return uuids; } using uuid_range = std::pair<std::vector<uuid>::const_iterator, std::vector<uuid>::const_iterator>; std::ostream& operator<<(std::ostream& o, uuid_range rng) { o << "["; for (auto i=rng.first; i!=rng.second; ++i) { o << " " << int(i->bytes[0]); } return o << "]"; }
29.437086
77
0.591001
[ "vector" ]
76d3a95c46b20bb1ff85d40c56897b73c6fea1a5
14,630
cpp
C++
vr/vr_common/src/vr/data/attributes_test.cpp
vladium/vrt
57394a630c306b7529dbe4574036ea71420d00cf
[ "MIT" ]
4
2019-09-09T22:08:40.000Z
2021-05-17T13:43:31.000Z
vr/vr_common/src/vr/data/attributes_test.cpp
vladium/vrt
57394a630c306b7529dbe4574036ea71420d00cf
[ "MIT" ]
null
null
null
vr/vr_common/src/vr/data/attributes_test.cpp
vladium/vrt
57394a630c306b7529dbe4574036ea71420d00cf
[ "MIT" ]
1
2019-09-09T15:46:20.000Z
2019-09-09T15:46:20.000Z
#include "vr/data/attributes.h" #include <boost/algorithm/string.hpp> #include "vr/test/utility.h" //---------------------------------------------------------------------------- namespace vr { namespace data { //............................................................................ TEST (attr_type, construction_numeric) { attr_type const at1 { atype::i4 }; attr_type const at2 { atype::i4 }; EXPECT_EQ (atype::i4, at1.atype ()); EXPECT_EQ (atype::i4, at2.atype ()); EXPECT_EQ (at1, at2); EXPECT_EQ (hash_value (at1), hash_value (at2)); attr_type const at3 { atype::f8 }; EXPECT_EQ (atype::f8, at3.atype ()); EXPECT_NE (at1, at3); EXPECT_NE (at2, at3); // copy construction: { attr_type const at3c { at3 }; EXPECT_EQ (at3, at3c); } // move construction: { attr_type at { atype::timestamp }; attr_type const atc { std::move (at) }; EXPECT_EQ (atype::timestamp, atc.atype ()); } // copy assignment: { attr_type at3c { atype::i4 }; at3c = at3; EXPECT_EQ (at3, at3c); } // move assignment: { attr_type at { atype::timestamp }; attr_type atc { atype::i8 }; atc = std::move (at); EXPECT_EQ (atype::timestamp, atc.atype ()); } // invalid input: EXPECT_THROW (attr_type { atype::category }, invalid_input); // invalid access: EXPECT_THROW (at1.labels<true> (), type_mismatch); } TEST (attr_type, construction_categorical) { attr_type const at1 { label_array::create_and_intern ({ "X", "Y", "Z" }) }; label_array const * const at1_la_addr = & at1.labels (); // capture for later stability check attr_type const at2 { at1.labels () }; EXPECT_EQ (atype::category, at1.atype ()); EXPECT_EQ (atype::category, at2.atype ()); ASSERT_EQ ("X", at1.labels ()[0]); ASSERT_EQ ("Y", at1.labels ()[1]); ASSERT_EQ ("Z", at1.labels ()[2]); ASSERT_EQ (& at1.labels (), & at2.labels ()); EXPECT_EQ (at1, at2); EXPECT_EQ (hash_value (at1), hash_value (at2)); attr_type const at3 { label_array::create_and_intern ({ "X", "Y" }) }; EXPECT_EQ (atype::category, at3.atype ()); EXPECT_NE (at1, at3); EXPECT_NE (at2, at3); // copy construction: { attr_type const at3c { at3 }; EXPECT_EQ (at3, at3c); EXPECT_EQ ("X", at3c.labels ()[0]); EXPECT_EQ ("Y", at3c.labels ()[1]); } // move construction: { attr_type at { label_array::create_and_intern ({ "L0", "L1" }) }; attr_type const atc { std::move (at) }; EXPECT_EQ (atype::category, atc.atype ()); EXPECT_EQ ("L0", atc.labels ()[0]); EXPECT_EQ ("L1", atc.labels ()[1]); } // copy assignment: { attr_type at3c { atype::i4 }; at3c = at3; EXPECT_EQ (at3, at3c); EXPECT_EQ ("X", at3c.labels ()[0]); EXPECT_EQ ("Y", at3c.labels ()[1]); } // move assignment { attr_type at { label_array::create_and_intern ({ "L0", "L1" }) }; attr_type atc { atype::i8 }; atc = std::move (at); EXPECT_EQ (atype::category, atc.atype ()); EXPECT_EQ ("L0", atc.labels ()[0]); EXPECT_EQ ("L1", atc.labels ()[1]); } label_array const * const la_addr = & label_array::create_and_intern ({ "X", "Y", "Z" }); ASSERT_EQ (at1_la_addr, la_addr); // stable addr EXPECT_EQ (at1_la_addr, & at1.labels ()); EXPECT_EQ (at1_la_addr, & at2.labels ()); } TEST (attr_type, construction_typesafe_enum) { attr_type const at1 { attr_type::for_enum<atype> () }; attr_type const at2 { attr_type::for_enum<atype> () }; EXPECT_EQ (atype::category, at1.atype ()); EXPECT_EQ (atype::category, at2.atype ()); ASSERT_EQ ("category", at1.labels ()[0]); ASSERT_EQ ("timestamp", at1.labels ()[1]); ASSERT_EQ (& at1.labels (), & at2.labels ()); EXPECT_EQ (at1, at2); EXPECT_EQ (hash_value (at1), hash_value (at2)); } //............................................................................ TEST (attribute, construction) { attribute const a1 { "a", atype::i4 }; attribute const a2 { "a", atype::i4 }; EXPECT_EQ (atype::i4, a1.type ().atype ()); EXPECT_EQ (atype::i4, a2.type ().atype ()); EXPECT_EQ ("a", a1.name ()); EXPECT_EQ ("a", a2.name ()); EXPECT_EQ (a1, a2); EXPECT_EQ (hash_value (a1), hash_value (a2)); attribute const a3 { "a", label_array::create_and_intern ({ "x", "y" }) }; // change atype attribute const a4 { "b", atype::i4 }; // change name EXPECT_NE (a1, a3); EXPECT_NE (a1, a4); // copy construction: { attribute const a3c { a3 }; EXPECT_EQ (a3, a3c); EXPECT_EQ ("x", a3c.type ().labels ()[0]); EXPECT_EQ ("y", a3c.type ().labels ()[1]); } // move construction: { attribute a { "c", label_array::create_and_intern ({ "l0", "l1" }) }; attribute const ac { std::move (a) }; EXPECT_EQ ("c", ac.name ()); EXPECT_EQ (atype::category, ac.type ().atype ()); EXPECT_EQ ("l0", ac.type ().labels ()[0]); EXPECT_EQ ("l1", ac.type ().labels ()[1]); } // copy assignment: { attribute a3c { "asdfasdf", atype::i4 }; a3c = a3; EXPECT_EQ (a3, a3c); EXPECT_EQ ("a", a3c.name ()); EXPECT_EQ ("x", a3c.type ().labels ()[0]); EXPECT_EQ ("y", a3c.type ().labels ()[1]); } // move assignment { attribute a { "d", label_array::create_and_intern ({ "l0", "l1" }) }; attribute ac { "ac", atype::i8 }; ac = std::move (a); EXPECT_EQ ("d", ac.name ()); EXPECT_EQ (atype::category, ac.type ().atype ()); EXPECT_EQ ("l0", ac.type ().labels ()[0]); EXPECT_EQ ("l1", ac.type ().labels ()[1]); } } //............................................................................ TEST (attr_schema, construction) { std::vector<attribute> const attrs { { "a0", atype::i4 }, { "a1", label_array::create_and_intern ({ "X", "Y" }) } }; attr_schema const as1 { attrs }; attr_schema const as2 { std::vector<attribute> { { "a0", atype::i4 }, { "a1", label_array::create_and_intern ({ "X", "Y" }) } } }; ASSERT_EQ (signed_cast (attrs.size ()), as1.size ()); ASSERT_EQ (signed_cast (attrs.size ()), as2.size ()); EXPECT_EQ (as1, as2); EXPECT_EQ (hash_value (as1), hash_value (as2)); // move construction: { std::vector<attribute> const attrs { { "a0", atype::i4 }, { "a1", atype::timestamp }, { "a2", label_array::create_and_intern ({ "X" }) } }; attr_schema as { attrs }; auto const h = hash_value (as); attr_schema const asc { std::move (as) }; ASSERT_EQ (3, asc.size ()); EXPECT_EQ (asc [0], attrs [0]); EXPECT_EQ (asc [1], attrs [1]); EXPECT_EQ (asc [2], attrs [2]); EXPECT_EQ (std::get<0> (asc ["a0"]), attrs [0]); EXPECT_EQ (std::get<0> (asc ["a1"]), attrs [1]); EXPECT_EQ (std::get<0> (asc ["a2"]), attrs [2]); EXPECT_EQ (hash_value (asc), h); } // invalid input: EXPECT_THROW ((attr_schema { std::vector<attribute> { { "a", atype::i4 }, { "B", atype::f4 }, { "a", atype::i8 } } }), invalid_input); // dup names } TEST (attr_schema, indexing) { std::vector<attribute> const attrs { { "a0", atype::i4 }, { "a1", label_array::create_and_intern ({ "X", "Y" }) } }; attr_schema const as1 { attrs }; attr_schema const as2 { std::vector<attribute> { { "a0", atype::i4 }, { "a1", label_array::create_and_intern ({ "X", "Y" }) } } }; ASSERT_EQ (signed_cast (attrs.size ()), as1.size ()); ASSERT_EQ (signed_cast (attrs.size ()), as2.size ()); // lookup by index: for (int32_t i = 0, i_limit = attrs.size (); i < i_limit; ++ i) { ASSERT_EQ (attrs [i], as1.at<true> (i)); ASSERT_EQ (attrs [i], as2.at<true> (i)); EXPECT_EQ (attrs [i], as1 [i]); EXPECT_EQ (attrs [i], as2 [i]); } // lookup by name: for (int32_t i = 0; i < as1.size (); ++ i) { { auto const ap1 = as1.at<true> ('a' + std::to_string (i)); ASSERT_EQ (& as1 [i], & std::get<0> (ap1)); ASSERT_EQ (i, std::get<1> (ap1)); auto const ap2 = as2.at<true> ('a' + std::to_string (i)); ASSERT_EQ (& as2 [i], & std::get<0> (ap2)); ASSERT_EQ (i, std::get<1> (ap2)); } { auto const ap1 = as1 ['a' + std::to_string (i)]; ASSERT_EQ (& as1 [i], & std::get<0> (ap1)); ASSERT_EQ (i, std::get<1> (ap1)); auto const ap2 = as2 ['a' + std::to_string (i)]; ASSERT_EQ (& as2 [i], & std::get<0> (ap2)); ASSERT_EQ (i, std::get<1> (ap2)); } } // iteration: int32_t count { }; for (attribute const & a : as1) { std::string const n_expected = 'a' + std::to_string (count); EXPECT_EQ (n_expected, a.name ()) << " failed for index " << count; EXPECT_EQ (attrs [count], a) << " wrong attribute at index " << count << ": " << a; ++ count; } EXPECT_EQ (signed_cast (attrs.size ()), count); } //............................................................................ //............................................................................ namespace { /* * a0, a1, A2: i4; * a3, a4: {l_q, l.r, l_S}; * a.5: f8; * A6: {l_q, l.r, l_S}; * 7_a: timestamp; */ void check_expected_schema (attr_schema const & as) { ASSERT_EQ (8, as.size ()); { attribute const & a = as [0]; EXPECT_EQ (a.name (), "a0"); EXPECT_EQ (a.atype (), atype::i4); } { attribute const & a = as [1]; EXPECT_EQ (a.name (), "a1"); EXPECT_EQ (a.atype (), atype::i4); } { attribute const & a = as [2]; EXPECT_EQ (a.name (), "A2"); EXPECT_EQ (a.atype (), atype::i4); } { attribute const & a = as [3]; EXPECT_EQ (a.name (), "a3"); ASSERT_EQ (a.atype (), atype::category); ASSERT_EQ (a.labels ().size (), 3); EXPECT_EQ (a.labels ()[0], "l_q"); EXPECT_EQ (a.labels ()[1], "l.r"); EXPECT_EQ (a.labels ()[2], "l_S"); } { attribute const & a = as [4]; EXPECT_EQ (a.name (), "a4"); EXPECT_EQ (a.type (), as [3].type ()); } { attribute const & a = as [5]; EXPECT_EQ (a.name (), "a.5"); EXPECT_EQ (a.atype (), atype::f8); } { attribute const & a = as [6]; EXPECT_EQ (a.name (), "A6"); EXPECT_EQ (a.type (), as [3].type ()); } { attribute const & a = as [7]; EXPECT_EQ (a.name (), "7_a"); EXPECT_EQ (a.atype (), atype::timestamp); } } } // end of anonymous //............................................................................ //............................................................................ TEST (attr_schema, parse_valid_input) { { attr_schema const as { "a0, a1, A2: i4; a3, a4: {l_q, l.r, l_S}; a.5: f8; A6: {l_q, l.r, l_S}; 7_a: ts;" }; check_expected_schema (as); } { attr_schema const as { "a0, a1, A2: i4;\n" "a3, a4: {l_q, l.r, l_S};\n" "a.5: f8;\tA6: {l_q, l.r, l_S};\n" "7_a:\tts;" }; check_expected_schema (as); } // trailing ';' is optional: { attr_schema const as { "a0, a1, A2: i4; a3, a4: {l_q, l.r, l_S}; a.5: f8; A6: {l_q, l.r, l_S}; 7_a: ts" }; check_expected_schema (as); } // leading, trailing whitespace: { attr_schema const as { " a0, a1, A2: i4; a3, a4: {l_q, l.r, l_S}; a.5: f8; A6: { l_q , l.r , l_S }; 7_a: ts " }; check_expected_schema (as); } // 'ts'/'time'/'timestamp' are all accepted as synonyms: { attr_schema const as { "a0, a1, A2: i4; a3, a4: {l_q, l.r, l_S}; a.5: f8; A6: {l_q, l.r, l_S}; 7_a: time" }; check_expected_schema (as); } { attr_schema const as { "a0, a1, A2: i4; a3, a4: {l_q, l.r, l_S}; a.5: f8; A6: {l_q, l.r, l_S}; 7_a: timestamp" }; check_expected_schema (as); } } TEST (attr_schema, parse_invalid_input) { EXPECT_THROW (attr_schema::parse ("a$0 : i4;"), parse_failure); // lexing error EXPECT_THROW (attr_schema::parse ("a0 : i$4;"), parse_failure); // lexing error EXPECT_THROW (attr_schema::parse ("a0 : i4; a1 : i$8;"), parse_failure); // lexing error EXPECT_THROW (attr_schema::parse ("a0 : i4; ;"), parse_failure); // trailing garbage EXPECT_THROW (attr_schema::parse ("a0 : i4; $"), parse_failure); // trailing garbage EXPECT_THROW (attr_schema::parse ("a0 : i4; a :"), parse_failure); // unfinished decl EXPECT_THROW (attr_schema::parse ("a0 : i4; a : i32"), parse_failure); // invalid atype } //............................................................................ TEST (attr_schema, print) { attr_schema const as { std::vector<attribute> { { "a0", atype::i4 }, { "a1", label_array::create_and_intern ({ "u", "v", "x", "y", "z" }) }, { "a2", atype::i8 }, { "a3", atype::f4 }, { "a4", atype::f8 }, { "a5", atype::timestamp }, { "a6", label_array::create_and_intern ({ "u", "v", "x", "y", "z" }) } } }; std::stringstream os; os << print (as); std::string const as_str = os.str (); // names: EXPECT_TRUE (boost::contains (as_str, "a0")); EXPECT_TRUE (boost::contains (as_str, "a1")); EXPECT_TRUE (boost::contains (as_str, "a2")); EXPECT_TRUE (boost::contains (as_str, "a3")); EXPECT_TRUE (boost::contains (as_str, "a4")); EXPECT_TRUE (boost::contains (as_str, "a5")); EXPECT_TRUE (boost::contains (as_str, "a6")); // types: EXPECT_TRUE (boost::contains (as_str, atype::name (atype::i4))); EXPECT_TRUE (boost::contains (as_str, atype::name (atype::category))); EXPECT_TRUE (boost::contains (as_str, atype::name (atype::i8))); EXPECT_TRUE (boost::contains (as_str, atype::name (atype::f4))); EXPECT_TRUE (boost::contains (as_str, atype::name (atype::f8))); EXPECT_TRUE (boost::contains (as_str, atype::name (atype::timestamp))); // [category labels may be shown in abbreviated form] } } // end of 'data' } // end of namespace //----------------------------------------------------------------------------
30.4158
151
0.505537
[ "vector" ]
76db36880a0b2b5f6e483dffe39f428aaaebc14f
1,852
cpp
C++
src/plugins/main/sampler/UniformSampler.cpp
PearCoding/PearRay
8654a7dcd55cc67859c7c057c7af64901bf97c35
[ "MIT" ]
19
2016-11-07T00:01:19.000Z
2021-12-29T05:35:14.000Z
src/plugins/main/sampler/UniformSampler.cpp
PearCoding/PearRay
8654a7dcd55cc67859c7c057c7af64901bf97c35
[ "MIT" ]
33
2016-07-06T21:58:05.000Z
2020-08-01T18:18:24.000Z
src/plugins/main/sampler/UniformSampler.cpp
PearCoding/PearRay
8654a7dcd55cc67859c7c057c7af64901bf97c35
[ "MIT" ]
null
null
null
#include "SceneLoadContext.h" #include "sampler/ISampler.h" #include "sampler/ISamplerFactory.h" #include "sampler/ISamplerPlugin.h" #include <vector> namespace PR { constexpr uint32 DEF_SAMPLE_COUNT = 128; /// A very bad sampler for test purposes class UniformSampler : public ISampler { public: explicit UniformSampler(uint32 samples) : ISampler(samples) { } virtual ~UniformSampler() = default; float generate1D(Random&, uint32) override { return 0.5f; } Vector2f generate2D(Random&, uint32) override { return Vector2f(0.5f, 0.5f); } }; class UniformSamplerFactory : public ISamplerFactory { public: explicit UniformSamplerFactory(const ParameterGroup& params) : mParams(params) { } uint32 requestedSampleCount() const override { return mParams.getUInt("sample_count", DEF_SAMPLE_COUNT); } std::shared_ptr<ISampler> createInstance(uint32 sample_count, Random&) const override { return std::make_shared<UniformSampler>(sample_count); } private: ParameterGroup mParams; }; class UniformSamplerPlugin : public ISamplerPlugin { public: std::shared_ptr<ISamplerFactory> create(const std::string&, const SceneLoadContext& ctx) override { return std::make_shared<UniformSamplerFactory>(ctx.parameters()); } const std::vector<std::string>& getNames() const override { const static std::vector<std::string> names({ "uniform" }); return names; } PluginSpecification specification(const std::string&) const override { return PluginSpecificationBuilder("Uniform Sampler", "A sampler with the worst quality we can provide. Use it only for debug purposes") .Identifiers(getNames()) .Inputs() .UInt("sample_count", "Sample count requested", DEF_SAMPLE_COUNT) .Specification() .get(); } }; } // namespace PR PR_PLUGIN_INIT(PR::UniformSamplerPlugin, _PR_PLUGIN_NAME, PR_PLUGIN_VERSION)
23.15
137
0.74946
[ "vector" ]
76dc03e874097541bf02ed8f6fb9873d22f247b9
1,687
cpp
C++
Olympiad Solutions/DMOJ/coci13c1p3.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
Olympiad Solutions/DMOJ/coci13c1p3.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
Olympiad Solutions/DMOJ/coci13c1p3.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
// Ivan Carvalho // Solution to https://dmoj.ca/problem/coci13c1p3 #include <bits/stdc++.h> using namespace std; const int MAXN = 51; int soma[MAXN][MAXN],n,resp,matriz[MAXN][MAXN],copia[MAXN][MAXN]; vector<int> mapa[MAXN][MAXN]; int calcula(int x1,int y1,int x2,int y2){ return soma[x2][y2] - soma[x1-1][y2] - soma[x2][y1-1] + soma[x1-1][y1 - 1]; } void precomputa(int x,int y){ for(int i = x;i <=n;i++){ for(int j = y;j <= n;j++){ mapa[x][y].push_back(calcula(x,y,i,j)); } } sort(mapa[x][y].begin(),mapa[x][y].end()); } void termina(int x,int y){ for(int i = x;i <=n;i++){ for(int j = y;j <= n;j++){ int val = calcula(x,y,i,j); if(i + 1 <= n && j + 1 <= n){ vector<int>::iterator it = lower_bound(mapa[i+1][j+1].begin(),mapa[i+1][j+1].end(),val); if(it != mapa[i+1][j+1].end() && (*it) == val) resp += upper_bound(mapa[i+1][j+1].begin(),mapa[i+1][j+1].end(),val) - it; } } } } int main(){ scanf("%d",&n); for(int i = 1;i<=n;i++){ for(int j = 1;j<=n;j++){ scanf("%d",&matriz[i][j]); copia[n - i + 1][j] = matriz[i][j]; soma[i][j] = matriz[i][j] + soma[i-1][j] + soma[i][j-1] - soma[i-1][j-1]; } } for(int i = 1;i<=n;i++){ for(int j = 1;j<=n;j++){ precomputa(i,j); } } for(int i = 1;i<=n;i++){ for(int j = 1;j<=n;j++){ termina(i,j); } } for(int i = 1;i<=n;i++){ for(int j = 1;j<=n;j++){ matriz[i][j] = copia[i][j]; soma[i][j] = matriz[i][j] + soma[i-1][j] + soma[i][j-1] - soma[i-1][j-1]; mapa[i][j].clear(); } } for(int i = 1;i<=n;i++){ for(int j = 1;j<=n;j++){ precomputa(i,j); } } for(int i = 1;i<=n;i++){ for(int j = 1;j<=n;j++){ termina(i,j); } } printf("%d\n",resp); return 0; }
24.808824
125
0.506224
[ "vector" ]
76e83a3ef7834299f3699ba2d62ff7ba1fbd5d77
6,576
cpp
C++
EncDecrypt/EncDecryptor.cpp
aliyavuzkahveci/encdecrypt
55336a55c9e0c28d036e8bd2da0f3ebe5cd7cf1f
[ "MIT" ]
null
null
null
EncDecrypt/EncDecryptor.cpp
aliyavuzkahveci/encdecrypt
55336a55c9e0c28d036e8bd2da0f3ebe5cd7cf1f
[ "MIT" ]
null
null
null
EncDecrypt/EncDecryptor.cpp
aliyavuzkahveci/encdecrypt
55336a55c9e0c28d036e8bd2da0f3ebe5cd7cf1f
[ "MIT" ]
null
null
null
#include "EncDecryptor.h" #include <aescommon.h> #include <windows.h> #include <process.h> #include <iostream> namespace EncDec { constexpr auto ASCII_NULL = 0x00; static char aeskey[17]; static HMODULE m_ModuleHandle; static bool m_IsLoaded = false; /* #define tgcry_cipher_open fgcry_cipher_open #define tgcry_cipher_close fgcry_cipher_close #define tgcry_cipher_encrypt fgcry_cipher_encrypt #define tgcry_cipher_decrypt fgcry_cipher_decrypt #define tgcry_cipher_ctl fgcry_cipher_ctl #define tgcry_strerror fgcry_strerror #define tgcry_randomize fgcry_randomize #define tgcry_check_version fgcry_check_version */ void setkey(const char *key, int keysize) { memset(aeskey, 0, 17); memcpy(aeskey, key, keysize); } int loadfuncs() { std::cout << "EncDecryptor::loadfuncs()" << std::endl; #ifdef _WIN32 m_ModuleHandle = LoadLibrary("libgcrypt.dll"); std::cout << "cipher library load handle: " << m_ModuleHandle << std::endl; if (!m_ModuleHandle) { std::cout << "EncDecryptor::loadfuncs() -> unable to load ecnryption library (libgcrypt.dll)" << std::endl; return 0; } fgcry_cipher_close = (tgcry_cipher_close)GetProcAddress(m_ModuleHandle, "gcry_cipher_close"); fgcry_cipher_encrypt = (tgcry_cipher_encrypt)GetProcAddress(m_ModuleHandle, "gcry_cipher_encrypt"); fgcry_cipher_decrypt = (tgcry_cipher_decrypt)GetProcAddress(m_ModuleHandle, "gcry_cipher_decrypt"); fgcry_cipher_ctl = (tgcry_cipher_ctl)GetProcAddress(m_ModuleHandle, "gcry_cipher_ctl"); fgcry_check_version = (tgcry_check_version)GetProcAddress(m_ModuleHandle, "gcry_check_version"); fgcry_randomize = (tgcry_randomize)GetProcAddress(m_ModuleHandle, "gcry_randomize"); fgcry_strerror = (tgcry_strerror)GetProcAddress(m_ModuleHandle, "gcry_strerror"); fgcry_cipher_open = (tgcry_cipher_open)GetProcAddress(m_ModuleHandle, "gcry_cipher_open"); #else #endif //_WIN32 m_IsLoaded = true; return 1; } void unloadfuncs() { std::cout << "EncDecryptor::unloadfuncs()" << std::endl; #ifdef _WIN32 FreeLibrary(m_ModuleHandle); m_ModuleHandle = NULL; fgcry_cipher_open = NULL; fgcry_cipher_close = NULL; fgcry_cipher_encrypt = NULL; fgcry_cipher_decrypt = NULL; fgcry_cipher_ctl = NULL; fgcry_strerror = NULL; fgcry_randomize = NULL; fgcry_check_version = NULL; #endif // m_IsLoaded = false; } #define Mfgcry_strerror(a) "crypt error" int decrypt(unsigned char * outbuf, int outlen, const unsigned char * crypted, int cryptedlen, const char *ciphername) { std::cout << "EncDecryptor::decrypt()" << std::endl; int rc; int cipher = GCRY_CIPHER_DES; int keylength = 16; gcry_error_t err; gcry_cipher_hd_t hd; unsigned char iv[33]; char *lkey; char des_key[9], aes_key[17]; //std::cout << "aes_ecb_decrypt( " << outbuf << ", " << crypted << ", " << cryptedlen << ")" << std::endl; memset(iv, ASCII_NULL, 33); if (!m_IsLoaded) { rc = loadfuncs(); std::cout << "EncDecryptor::decrypt() -> loadfuncs() Return Code = " << rc << std::endl; if (rc != 1) return EC_GCRYPT_LOAD_ERROR; } if (strcmp(ciphername, AES_STANDARD_NAME) == 0) { cipher = GCRY_CIPHER_AES; keylength = 16; lkey = aes_key; } else if (strcmp(ciphername, DES_STANDARD_NAME) == 0) { cipher = GCRY_CIPHER_DES; keylength = 8; lkey = des_key; } memset(lkey, 0, keylength + 1); memcpy(lkey, aeskey, keylength); err = fgcry_cipher_open(&hd, cipher, GCRY_CIPHER_MODE_ECB, 0); if (err) { std::cout << "EncDecryptor::decrypt() -> Failed opening AES cipher: " << Mfgcry_strerror(err) << std::endl; if (lkey != 0) { delete lkey; } return EC_ENCRYPT_DECRYPT; } err = fgcry_cipher_setkey(hd, lkey, keylength); if (err) { std::cout << "EncDecryptor::decrypt() -> Failed setkey: " << Mfgcry_strerror(err) << std::endl; return EC_ENCRYPT_DECRYPT; } err = fgcry_cipher_setiv(hd, iv, keylength); if (err) { std::cout << "EncDecryptor::decrypt() -> Failed setiv: " << Mfgcry_strerror(err) << std::endl; return EC_ENCRYPT_DECRYPT; } err = fgcry_cipher_decrypt(hd, outbuf, outlen, crypted, cryptedlen); if (err) { std::cout << "EncDecryptor::decrypt() -> Failed decrypt: " << Mfgcry_strerror(err) << std::endl; return EC_ENCRYPT_DECRYPT; } fgcry_cipher_close(hd); return EC_SUCCESS; } int encrypt(unsigned char * outbuf, int outlen, const unsigned char * plain, int plainlen, const char *ciphername) { std::cout << "EncDecryptor::encrypt()" << std::endl; int rc; gcry_error_t err; gcry_cipher_hd_t hd; int cipher = GCRY_CIPHER_DES; int keylength = 16; char *lkey; char des_key[9], aes_key[17]; unsigned char iv[33]; //std::cout << "aes_ecb_encrypt( " << outbuf << ", " << plain << ", " << plainlen << ")" << std::endl; if (m_IsLoaded == 0) { rc = loadfuncs(); std::cout << "EncDecryptor::encrypt() -> loadfuncs() Return Code = " << rc << std::endl; if (rc != 1) return EC_GCRYPT_LOAD_ERROR; } if (strcmp(ciphername, AES_STANDARD_NAME) == 0) { cipher = GCRY_CIPHER_AES; keylength = 16; lkey = aes_key; } else if (strcmp(ciphername, DES_STANDARD_NAME) == 0) { cipher = GCRY_CIPHER_DES; keylength = 8; lkey = des_key; } memset(lkey, 0, keylength + 1); memcpy(lkey, aeskey, keylength); memset(iv, ASCII_NULL, 33); err = fgcry_cipher_open(&hd, cipher, GCRY_CIPHER_MODE_ECB, 0); if (err) { std::cout << "EncDecryptor::encrypt() -> Failed opening AES cipher: " << Mfgcry_strerror(err) << std::endl; return EC_ENCRYPT_DECRYPT; } err = fgcry_cipher_setkey(hd, lkey, keylength); if (err) { std::cout << "EncDecryptor::encrypt() -> Failed setkey: " << Mfgcry_strerror(err) << std::endl; return EC_ENCRYPT_DECRYPT; } err = fgcry_cipher_setiv(hd, iv, keylength); if (err) { std::cout << "EncDecryptor::encrypt() -> Failed setiv(initialization vector): " << Mfgcry_strerror(err) << std::endl; return EC_ENCRYPT_DECRYPT; } err = fgcry_cipher_encrypt(hd, outbuf, outlen, plain, plainlen); if (err) { std::cout << "EncDecryptor::encrypt() -> Failed encrypt: " << Mfgcry_strerror(err) << std::endl; return EC_ENCRYPT_DECRYPT; } fgcry_cipher_close(hd); return EC_SUCCESS; } }
27.061728
121
0.654197
[ "vector" ]
76f68827ba1fbcb3174e6990d6cecf382ba6373a
1,266
cpp
C++
02-Sorting/selection-sort.cpp
ashleymays/Algorithms
c8a55f45bc3f1d0ab850546baedbfc3d98f148d7
[ "MIT" ]
1
2022-02-18T01:51:15.000Z
2022-02-18T01:51:15.000Z
02-Sorting/selection-sort.cpp
ashleymays/Algorithms
c8a55f45bc3f1d0ab850546baedbfc3d98f148d7
[ "MIT" ]
null
null
null
02-Sorting/selection-sort.cpp
ashleymays/Algorithms
c8a55f45bc3f1d0ab850546baedbfc3d98f148d7
[ "MIT" ]
null
null
null
/* Selection Sort Time Complexity: O(n^2) Space Complexity: O(1) */ #include <iostream> #include <vector> #include <cstdlib> using namespace std; void selectionSort(vector<int>& arr) { int min, tmp; for (int i = 0; i < arr.size() - 1; ++i) { min = i; // Assume that the minimum is at index i for (int j = i + 1; j < arr.size(); ++j) // Read all the elements after the one at index i { if (arr[min] > arr[j]) // If there is an element at index j that is smaller { // than the one at index i, we re-assign min min = j; } } tmp = arr[min]; // Swap the elements so that the smaller element gets arr[min] = arr[i]; // moved to its correct position in the array arr[i] = tmp; } } // Display the elements in the array void display(const vector<int>& arr) { for (int i = 0; i < arr.size(); ++i) { cout << arr[i] << ' '; } cout << endl; } // Initialize array void init(vector<int>& arr) { srand(time(NULL)); for (int i = 0; i < arr.size(); ++i) { arr[i] = rand() % (arr.size() * 4); } } int main() { int size; cout << "Enter size of the array: "; cin >> size; cout << endl; vector<int> arr(size); init(arr); display(arr); selectionSort(arr); display(arr); return 0; }
16.88
92
0.575039
[ "vector" ]
76f8c85063bae859b262de1ad5f95fb9e729398e
10,396
cpp
C++
dali-toolkit/internal/text/rendering/vector-based/vector-based-renderer.cpp
dalihub/dali-toolk
980728a7e35b8ddd28f70c090243e8076e21536e
[ "Apache-2.0", "BSD-3-Clause" ]
7
2016-11-18T10:26:51.000Z
2021-01-28T13:51:59.000Z
dali-toolkit/internal/text/rendering/vector-based/vector-based-renderer.cpp
dalihub/dali-toolk
980728a7e35b8ddd28f70c090243e8076e21536e
[ "Apache-2.0", "BSD-3-Clause" ]
13
2020-07-15T11:33:03.000Z
2021-04-09T21:29:23.000Z
dali-toolkit/internal/text/rendering/vector-based/vector-based-renderer.cpp
dalihub/dali-toolk
980728a7e35b8ddd28f70c090243e8076e21536e
[ "Apache-2.0", "BSD-3-Clause" ]
10
2019-05-17T07:15:09.000Z
2021-05-24T07:28:08.000Z
/* * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // CLASS HEADER #include <dali-toolkit/internal/text/rendering/vector-based/vector-based-renderer.h> // EXTERNAL INCLUDES #include <dali/devel-api/text-abstraction/font-client.h> #include <dali/integration-api/debug.h> #include <dali/public-api/rendering/geometry.h> #include <dali/public-api/rendering/renderer.h> // INTERNAL INCLUDES #include <dali-toolkit/internal/text/glyph-run.h> #include <dali-toolkit/internal/text/rendering/vector-based/glyphy-shader/glyphy-shader.h> #include <dali-toolkit/internal/text/rendering/vector-based/vector-blob-atlas-share.h> #include <dali-toolkit/internal/text/rendering/vector-based/vector-blob-atlas.h> #include <dali-toolkit/internal/text/text-view.h> using namespace Dali; using namespace Dali::Toolkit; using namespace Dali::Toolkit::Text; namespace { #if defined(DEBUG_ENABLED) Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_RENDERING"); #endif const float DEFAULT_POINT_SIZE = 13.f; struct Vertex2D { float x; float y; float u; float v; Vector4 color; }; void AddVertex(Vector<Vertex2D>& vertices, float x, float y, float u, float v, const Vector4& color) { Vertex2D meshVertex; meshVertex.x = x; meshVertex.y = y; meshVertex.u = u; meshVertex.v = v; meshVertex.color = color; vertices.PushBack(meshVertex); } void AddTriangle(Vector<unsigned short>& indices, unsigned int v0, unsigned int v1, unsigned int v2) { indices.PushBack(v0); indices.PushBack(v1); indices.PushBack(v2); } bool CreateGeometry(const Vector<GlyphInfo>& glyphs, unsigned int numberOfGlyphs, const Vector<Vector2>& positions, float xOffset, float yOffset, VectorBlobAtlas& atlas, Dali::TextAbstraction::FontClient& fontClient, Vector<Vertex2D>& vertices, Vector<unsigned short>& indices, const Vector4* const colorsBuffer, const ColorIndex* const colorIndicesBuffer, const Vector4& defaultColor) { // Whether the default color is used. const bool useDefaultColor = (NULL == colorsBuffer); bool atlasFull(false); for(unsigned int i = 0, idx = 0; i < numberOfGlyphs && !atlasFull; ++i) { if(glyphs[i].width > 0 && glyphs[i].height > 0) { bool foundBlob(true); BlobCoordinate blobCoords[4]; if(!atlas.FindGlyph(glyphs[i].fontId, glyphs[i].index, blobCoords)) { // Add blob to atlas VectorBlob* blob(NULL); unsigned int blobLength(0); unsigned int nominalWidth(0); unsigned int nominalHeight(0); fontClient.CreateVectorBlob(glyphs[i].fontId, glyphs[i].index, blob, blobLength, nominalWidth, nominalHeight); if(0 != blobLength) { bool glyphAdded = atlas.AddGlyph(glyphs[i].fontId, glyphs[i].index, blob, blobLength, nominalWidth, nominalHeight, blobCoords); foundBlob = glyphAdded; atlasFull = !glyphAdded; } else { foundBlob = false; } } if(foundBlob) { // Get the color of the character. const ColorIndex colorIndex = useDefaultColor ? 0u : *(colorIndicesBuffer + i); const Vector4& color = (useDefaultColor || (0u == colorIndex)) ? defaultColor : *(colorsBuffer + colorIndex - 1u); const float x1(xOffset + positions[i].x); const float x2(xOffset + positions[i].x + glyphs[i].width); const float y1(yOffset + positions[i].y); const float y2(yOffset + positions[i].y + glyphs[i].height); AddVertex(vertices, x1, y2, blobCoords[0].u, blobCoords[0].v, color); AddVertex(vertices, x1, y1, blobCoords[1].u, blobCoords[1].v, color); AddVertex(vertices, x2, y2, blobCoords[2].u, blobCoords[2].v, color); AddTriangle(indices, idx, idx + 1, idx + 2); idx += 3; AddVertex(vertices, x1, y1, blobCoords[1].u, blobCoords[1].v, color); AddVertex(vertices, x2, y2, blobCoords[2].u, blobCoords[2].v, color); AddVertex(vertices, x2, y1, blobCoords[3].u, blobCoords[3].v, color); AddTriangle(indices, idx, idx + 1, idx + 2); idx += 3; } } } // If the atlas is still partially empty, all the glyphs were added return !atlasFull; } } // unnamed namespace struct VectorBasedRenderer::Impl { Impl() { mFontClient = TextAbstraction::FontClient::Get(); mQuadVertexFormat["aPosition"] = Property::VECTOR2; mQuadVertexFormat["aTexCoord"] = Property::VECTOR2; mQuadVertexFormat["aColor"] = Property::VECTOR4; } Actor mActor; ///< The actor parent which renders the text TextAbstraction::FontClient mFontClient; ///> The font client used to supply glyph information Property::Map mQuadVertexFormat; ///> Describes the vertex format for text Shader mShaderEffect; IntrusivePtr<VectorBlobAtlas> mAtlas; }; Text::RendererPtr VectorBasedRenderer::New() { DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Text::VectorBasedRenderer::New()\n"); return Text::RendererPtr(new VectorBasedRenderer()); } Actor VectorBasedRenderer::Render(Text::ViewInterface& view, Actor textControl, Property::Index animatablePropertyIndex, float& alignmentOffset, int /*depth*/) { UnparentAndReset(mImpl->mActor); mImpl->mActor = Actor::New(); mImpl->mActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); mImpl->mActor.SetProperty(Actor::Property::SIZE, Vector2(view.GetControlSize())); mImpl->mActor.SetProperty(Actor::Property::COLOR, Color::WHITE); #if defined(DEBUG_ENABLED) mImpl->mActor.SetProperty(Dali::Actor::Property::NAME, "Text renderable actor"); #endif Length numberOfGlyphs = view.GetNumberOfGlyphs(); if(numberOfGlyphs > 0u) { Vector<GlyphInfo> glyphs; glyphs.Resize(numberOfGlyphs); Vector<Vector2> positions; positions.Resize(numberOfGlyphs); numberOfGlyphs = view.GetGlyphs(glyphs.Begin(), positions.Begin(), alignmentOffset, 0u, numberOfGlyphs); glyphs.Resize(numberOfGlyphs); positions.Resize(numberOfGlyphs); const Vector4* const colorsBuffer = view.GetColors(); const ColorIndex* const colorIndicesBuffer = view.GetColorIndices(); const Vector4& defaultColor = view.GetTextColor(); Vector<Vertex2D> vertices; Vector<unsigned short> indices; const Vector2& controlSize = view.GetControlSize(); float xOffset = -alignmentOffset + controlSize.width * -0.5f; float yOffset = controlSize.height * -0.5f; if(!mImpl->mAtlas || mImpl->mAtlas->IsFull()) { VectorBlobAtlasShare atlasShare = VectorBlobAtlasShare::Get(); mImpl->mAtlas = atlasShare.GetCurrentAtlas(); } // First try adding the glyphs to the previous shared atlas bool allGlyphsAdded = CreateGeometry(glyphs, numberOfGlyphs, positions, xOffset, yOffset, *mImpl->mAtlas, mImpl->mFontClient, vertices, indices, colorsBuffer, colorIndicesBuffer, defaultColor); if(!allGlyphsAdded) { // The current atlas is full, abandon it and use a new one mImpl->mAtlas.Reset(); vertices.Clear(); indices.Clear(); VectorBlobAtlasShare atlasShare = VectorBlobAtlasShare::Get(); mImpl->mAtlas = atlasShare.GetNewAtlas(); CreateGeometry(glyphs, numberOfGlyphs, positions, xOffset, yOffset, *mImpl->mAtlas, mImpl->mFontClient, vertices, indices, colorsBuffer, colorIndicesBuffer, defaultColor); // Return value ignored; using more than an entire new atlas is not supported } if(0 != vertices.Count()) { VertexBuffer quadVertices = VertexBuffer::New(mImpl->mQuadVertexFormat); quadVertices.SetData(&vertices[0], vertices.Size()); Geometry quadGeometry = Geometry::New(); quadGeometry.AddVertexBuffer(quadVertices); quadGeometry.SetIndexBuffer(&indices[0], indices.Size()); TextureSet texture = mImpl->mAtlas->GetTextureSet(); const Vector4 atlasInfo = mImpl->mAtlas->GetInfo(); mImpl->mShaderEffect = GlyphyShader::New(atlasInfo); Dali::Renderer renderer = Dali::Renderer::New(quadGeometry, mImpl->mShaderEffect); renderer.SetTextures(texture); mImpl->mActor.AddRenderer(renderer); } } return mImpl->mActor; } VectorBasedRenderer::VectorBasedRenderer() { mImpl = new Impl(); } VectorBasedRenderer::~VectorBasedRenderer() { delete mImpl; }
33.753247
137
0.59696
[ "geometry", "render", "vector" ]
76fbc3b153c7605eadb2276fb8f3e89a4ff69793
2,335
cpp
C++
aws-cpp-sdk-resiliencehub/source/model/RenderRecommendationType.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-resiliencehub/source/model/RenderRecommendationType.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-resiliencehub/source/model/RenderRecommendationType.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/resiliencehub/model/RenderRecommendationType.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace ResilienceHub { namespace Model { namespace RenderRecommendationTypeMapper { static const int Alarm_HASH = HashingUtils::HashString("Alarm"); static const int Sop_HASH = HashingUtils::HashString("Sop"); static const int Test_HASH = HashingUtils::HashString("Test"); RenderRecommendationType GetRenderRecommendationTypeForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == Alarm_HASH) { return RenderRecommendationType::Alarm; } else if (hashCode == Sop_HASH) { return RenderRecommendationType::Sop; } else if (hashCode == Test_HASH) { return RenderRecommendationType::Test; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<RenderRecommendationType>(hashCode); } return RenderRecommendationType::NOT_SET; } Aws::String GetNameForRenderRecommendationType(RenderRecommendationType enumValue) { switch(enumValue) { case RenderRecommendationType::Alarm: return "Alarm"; case RenderRecommendationType::Sop: return "Sop"; case RenderRecommendationType::Test: return "Test"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace RenderRecommendationTypeMapper } // namespace Model } // namespace ResilienceHub } // namespace Aws
29.935897
92
0.625696
[ "model" ]
76fc2e863fc52106500e7435890c6e74314b522f
437
cpp
C++
lecture11/exercise11-B/template.cpp
nd-cse-30872-fa21/cse-30872-fa21-examples
c3287ac8b49a0de3c9770aadfb77be9080b19277
[ "MIT" ]
1
2021-09-07T19:02:43.000Z
2021-09-07T19:02:43.000Z
lecture11/exercise11-B/template.cpp
nd-cse-30872-fa21/cse-30872-fa21-examples
c3287ac8b49a0de3c9770aadfb77be9080b19277
[ "MIT" ]
null
null
null
lecture11/exercise11-B/template.cpp
nd-cse-30872-fa21/cse-30872-fa21-examples
c3287ac8b49a0de3c9770aadfb77be9080b19277
[ "MIT" ]
6
2021-08-25T15:59:08.000Z
2021-11-12T16:32:11.000Z
// Exercise 11-B: Phone Combinations #include <iostream> #include <map> #include <string> #include <vector> using namespace std; // Globals // Functions void phone_combinations(string numbers, string letters) { // TODO: Recursively display combinations } // Main execution int main(int argc, char *argv[]) { string numbers; while (getline(cin, numbers)) { phone_combinations(numbers, ""); } return 0; }
15.068966
57
0.677346
[ "vector" ]
0a00eacc04053c68d81594c88311b15e79dfed3c
8,209
cpp
C++
released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/cpp/src/extract_bounded_neuron.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
1
2021-12-27T19:14:03.000Z
2021-12-27T19:14:03.000Z
released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/cpp/src/extract_bounded_neuron.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
1
2016-12-03T05:33:13.000Z
2016-12-03T05:33:13.000Z
released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/cpp/src/extract_bounded_neuron.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
null
null
null
#include <iostream> #include <sstream> #include <fstream> #include <string.h> #include <stdlib.h> #include "tz_utilities.h" #include "zsegmentmaparray.h" #include "zsuperpixelmaparray.h" #include "tz_stack_lib.h" #include "tz_image_io.h" #include "tz_stack_attribute.h" #include "tz_stack_document.h" #include "tz_xml_utils.h" #include "tz_stack_bwmorph.h" #include "tz_stack_objlabel.h" #include "tz_swc_tree.h" #include "zswctree.h" #include "zswcforest.h" #include "tz_sp_grow.h" #include "zspgrowparser.h" #include "tz_stack_stat.h" #include "tz_intpair_map.h" #include "tz_stack_utils.h" #include "zfilelist.h" #include "zstring.h" using namespace std; int main(int argc, char *argv[]) { if (Show_Version(argc, argv, "0.1") == 1) { return 0; } static char const *Spec[] = {"<input:string> -o <string>", "--body_id <int> [--isolate <int> <int>] [--ds <int>]", "[--final_ds <int>]", "[--compress <string>]", NULL}; Process_Arguments(argc, argv, const_cast<char**>(Spec), 1); char *dataDir = Get_String_Arg(const_cast<char*>("input")); int bodyId = Get_Int_Arg(const_cast<char*>("--body_id")); //Load compress map if (Is_Arg_Matched(const_cast<char*>("--compress"))) { FILE *fp = fopen(Get_String_Arg(const_cast<char*>("--compress")), "r"); ZString str; while (str.readLine(fp)) { vector<int> value = str.toIntegerArray(); if (value.size() == 2) { if (value[0] == bodyId) { bodyId = value[1]; break; } } } fclose(fp); } ZFileList fileList; fileList.load(dataDir, "tif", ZFileList::SORT_BY_LAST_NUMBER); int startPlane = fileList.startNumber(); int endPlane = fileList.endNumber(); int planeNumber = endPlane - startPlane + 1; ZFileList additionalFileList; additionalFileList.load(string(dataDir) + "/a", "tif", ZFileList::SORT_BY_LAST_NUMBER); int r = 250; int dr = 75; if (Is_Arg_Matched(const_cast<char*>("--isolate"))) { r = Get_Int_Arg(const_cast<char*>("--isolate"), 1); dr = Get_Int_Arg(const_cast<char*>("--isolate"), 2); } Stack *stack = Read_Stack_U(fileList.getFilePath(0)); int intv[3] = {0, 0, 0}; if (Is_Arg_Matched(const_cast<char*>("--ds"))) { intv[0] = Get_Int_Arg(const_cast<char*>("--ds")) - 1; intv[1] = intv[0]; //intv[1] = Get_Int_Arg(const_cast<char*>("--ds"), 2) - 1; //intv[2] = Get_Int_Arg(const_cast<char*>("--ds"), 3) - 1; stack = Downsample_Stack(stack, intv[0], intv[1], intv[2]); r /= intv[0] + 1; dr /= intv[0] + 1; } int width = stack->width; int height = stack->height; Stack *mip = Make_Stack(GREY, width, height, 1); Zero_Stack(mip); int planeSize = Stack_Voxel_Number(mip); char filePath[500]; Kill_Stack(stack); int zStart = -1; int zEnd = 0; //Estimate Z range cout << "Estimating Z range ..." << endl; for (int i = 0; i < planeNumber; i++) { cout << " " << i << "/" << planeNumber << endl; int bodyArea = 0; stack = Read_Stack_U(fileList.getFilePath(i)); Stack *additionalStack = NULL; if (additionalFileList.size() > 0) { additionalStack = Read_Stack_U(additionalFileList.getFilePath(i)); } if (Is_Arg_Matched(const_cast<char*>("--ds"))) { Stack *stack2 = Downsample_Stack(stack, intv[0], intv[1], intv[2]); Free_Stack(stack); stack = stack2; if (additionalStack != NULL) { stack2 = Downsample_Stack(additionalStack, intv[0], intv[1], intv[2]); Free_Stack(additionalStack); additionalStack = stack2; } } color_t *arrayc = (color_t*) stack->array; uint16_t *array16 = (uint16_t*) stack->array; if (stack->kind == COLOR) { for (int offset = 0; offset < planeSize; offset++) { int tmpBodyId = (int) Color_To_Value(arrayc[offset]); if (additionalStack != NULL) { uint32_t value = additionalStack->array[offset]; tmpBodyId += (int) (value << 24); } if (tmpBodyId == bodyId) { bodyArea++; mip->array[offset] = 1; } } } else { for (int offset = 0; offset < planeSize; offset++) { if (array16[offset] == bodyId) { bodyArea++; mip->array[offset] = 1; } } } if (bodyArea > 0) { if (zStart < 0) { zStart = i; } zEnd = i; } Free_Stack(stack); if (additionalStack != NULL) { Free_Stack(additionalStack); } } cout << " " << zStart << " " << zEnd << endl; cout << "Removing isolated objects ..." << endl; Stack *mipMask = Stack_Remove_Isolated_Object(mip, NULL, r, dr); cout << "Estimating bound box ..." << endl; Cuboid_I boundBox; Stack_Bound_Box(mipMask, &boundBox); cout << " (" << boundBox.cb[0] << "," << boundBox.cb[1] << "," << boundBox.cb[2] << ")" << "->" << "(" << boundBox.ce[0] << "," << boundBox.ce[1] << "," << boundBox.ce[2] << ")" << endl; int finalDs = 1; if (Is_Arg_Matched(const_cast<char*>("--final_ds"))) { finalDs = Get_Int_Arg(const_cast<char*>("--final_ds")); } int cropWidth = boundBox.ce[0] - boundBox.cb[0] + 1; int cropHeight = boundBox.ce[1] - boundBox.cb[1] + 1; int finalStackWidth, finalStackHeight, finalStackDepth; Downsample_Stack_Max_Size(cropWidth, cropHeight, 1, finalDs, finalDs, 1, &finalStackWidth, &finalStackHeight, &finalStackDepth); Stack *finalStack = Make_Stack(GREY, finalStackWidth, finalStackHeight, zEnd - zStart + 1); int finalPlaneArea = finalStackHeight * finalStackWidth; uint8_t *outArray = finalStack->array; Stack *bodyPlane = Make_Stack(GREY, mipMask->width, mipMask->height, 1); Stack *croppedBodyPlane = Make_Stack(GREY, cropWidth, cropHeight, 1); //Load images cout << "Extract planes ..." << endl; for (int i = zStart; i <= zEnd; i++) { cout << " " << i << "/" << zEnd << endl; stack = Read_Stack(fileList.getFilePath(i)); Stack *additionalStack = NULL; if (additionalFileList.size() > 0) { additionalStack = Read_Stack_U(additionalFileList.getFilePath(i)); } if (Is_Arg_Matched(const_cast<char*>("--ds"))) { Stack *stack2 = Downsample_Stack(stack, intv[0], intv[1], intv[2]); Free_Stack(stack); stack = stack2; if (additionalStack != NULL) { stack2 = Downsample_Stack(additionalStack, intv[0], intv[1], intv[2]); Free_Stack(additionalStack); additionalStack = stack2; } } color_t *arrayc = (color_t*) stack->array; uint16_t *array16 = (uint16_t*) stack->array; if (stack->kind == COLOR) { for (int offset = 0; offset < planeSize; offset++) { int tmpBodyId = (int) Color_To_Value(arrayc[offset]); if (additionalStack != NULL) { uint32_t value = additionalStack->array[offset]; tmpBodyId += (int) (value << 24); } if (tmpBodyId == bodyId && mipMask->array[offset] == 1) { bodyPlane->array[offset] = 1; } else { bodyPlane->array[offset] = 0; } } } else { for (int offset = 0; offset < planeSize; offset++) { if (array16[offset] == bodyId && mipMask->array[offset] == 1) { bodyPlane->array[offset] = 1; } else { bodyPlane->array[offset] = 0; } } } Stack dest; dest.width = finalStack->width; dest.height = finalStack->height; dest.depth = 1; dest.kind = GREY; dest.array = outArray; Crop_Stack(bodyPlane, boundBox.cb[0], boundBox.cb[1], 0, cropWidth, cropHeight, 1, croppedBodyPlane); //Downsample the plane Downsample_Stack_Max(croppedBodyPlane, finalDs, finalDs, 0, &dest); outArray += finalPlaneArea; Free_Stack(stack); if (additionalStack != NULL) { Free_Stack(additionalStack); } } //finalStack = Downsample_Stack_Max(finalStack, 1, 1, 0); Write_Stack(Get_String_Arg(const_cast<char*>("-o")), finalStack); sprintf(filePath, "%s.offset.txt", Get_String_Arg(const_cast<char*>("-o"))); FILE *fp = fopen(filePath, "w"); fprintf(fp, "%d %d %d", boundBox.cb[0], boundBox.cb[1], zStart); fclose(fp); return 0; }
29.109929
78
0.600804
[ "vector" ]
0a02ef1ec681c96b69e237e18ded65cb0213a819
3,461
cpp
C++
Cpp/DesignPatterns/MVC-MVP/01_MVP.cpp
Lecrapouille/BacASable
e7de7a7b6f21ee3180dc968a47cbd1515cb82de5
[ "Unlicense" ]
1
2019-09-16T11:09:25.000Z
2019-09-16T11:09:25.000Z
Cpp/DesignPatterns/MVC-MVP/01_MVP.cpp
Lecrapouille/BacASable
e7de7a7b6f21ee3180dc968a47cbd1515cb82de5
[ "Unlicense" ]
1
2019-09-08T19:10:54.000Z
2019-09-08T20:26:30.000Z
Cpp/DesignPatterns/MVC-MVP/01_MVP.cpp
Lecrapouille/BacASable
e7de7a7b6f21ee3180dc968a47cbd1515cb82de5
[ "Unlicense" ]
null
null
null
#include <iostream> //-------------------------------------------------------------- //! \file My personal implementation of the Model-View-Presenter. //! Contrary to Java, here, the Presenter and View do not interact //! together throw an Contract interface class. //-------------------------------------------------------------- //-------------------------------------------------------------- //! \brief Aka Model only modifiable by the Presenter. The View //! is not supposed to know this class but, here, it used it in //! read-only mode. //-------------------------------------------------------------- class Student { public: Student(std::string const& name) : m_name(name) { } //! \brief Getter std::string const& name() const { return m_name; } //! \brief Setter void name(std::string const& name) { m_name = name; } private: std::string m_name; }; //-------------------------------------------------------------- //! \brief View. We simulate a GUI with the console: //! - When the user edits the model we simulate by reading the cin //! - When the view display the model we write in cout. //-------------------------------------------------------------- class View { public: // Simulate the text refresh of an entry text widget by writing chars // in the console. void display(Student const& student) const { std::cout << "View disp Student: " << student.name() << std::endl; } // Simulate the user typing in an entry text widget by reading chars in // the console. void textEntry() { std::cout << "The user is typing some text in a textEntry" << std::endl; std::string txt; std::cin >> txt; onTextChanged(txt); } private: // Simulate the callback 'on key pressed event' of an entry text virtual void onTextChanged(std::string const& text) = 0; }; //-------------------------------------------------------------- //! \brief the Presenter is the mediator between the model and the //! view. It responds to the view callbacks and update the model. //-------------------------------------------------------------- class Presenter { public: // Presenter knows the View and the Model Presenter(View& view) : m_view(view), m_student("John Doe") { // Display "John Doe" on the console updateView(); } // Setter: update the model and display the // new name. void setStudentName(std::string const& name) { m_student.name(name); updateView(); } // Getter std::string const& getStudentName() { return m_student.name(); } private: void updateView() { m_view.display(m_student); } private: View& m_view; Student m_student; }; //-------------------------------------------------------------- //! \brief GUI implements a View and has a Presenter //-------------------------------------------------------------- class GUI: public View { public: GUI() : m_presenter(*this) { widget(); } private: virtual void onTextChanged(std::string const& text) override { m_presenter.setStudentName(text); } void widget() { std::cout << "Student Name:" << std::endl; } private: Presenter m_presenter; }; //-------------------------------------------------------------- //! \brief Simulate the GUI: the user is editing an text entry. //-------------------------------------------------------------- int main() { GUI gui; gui.textEntry(); return 0; }
24.034722
78
0.505056
[ "model" ]
0a0f8c6df1a0878ca161b7296e31cd144dffe8b1
1,869
cpp
C++
multiview/multiview_cpp/src/testcases/utils/intseq_tc.cpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
5
2021-09-03T23:12:08.000Z
2022-03-04T21:43:32.000Z
multiview/multiview_cpp/src/testcases/utils/intseq_tc.cpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
3
2021-09-08T02:57:46.000Z
2022-02-26T05:33:02.000Z
multiview/multiview_cpp/src/testcases/utils/intseq_tc.cpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
2
2021-09-26T03:14:40.000Z
2022-01-26T06:42:52.000Z
#define CATCH_CONFIG_PREFIX_ALL #include <algorithm> #include <deque> #include <iterator> #include "perceive/contrib/catch.hpp" #include "perceive/scene/scene-description.hpp" #include "perceive/utils/base64.hpp" namespace perceive { vector<unsigned> target_frame_to_video_frame_mapping(const real video_fps, const real target_fps, const int n_video_frames) noexcept { const auto xys = calc_frame_pairs(video_fps, target_fps, n_video_frames); vector<unsigned> ret; ret.reserve(xys.size()); int next_frame = 0; for(const auto& xy : xys) { if(xy.y == next_frame) { ret.push_back(unsigned(xy.x)); next_frame++; } } return ret; } static void run_sim(const real in_fps, const real target_fps, const int N) { INFO(format("SIM: fps {} ==> {}, N = {}", in_fps, target_fps, N)); const auto pairs = calc_frame_pairs(in_fps, target_fps, N); for(const auto ij : pairs) cout << format("{:2d}/{:2d} :: |{:8.5f} - {:8.5f}| = {:8.5f}", ij.x, ij.y, ij.x / in_fps, ij.y / target_fps, std::fabs(ij.x / in_fps - ij.y / target_fps)) << endl; { const auto ffs = target_frame_to_video_frame_mapping(in_fps, target_fps, N); int t_frame = 0; cout << "*" << endl; for(const auto o_frame : ffs) { cout << format("{:2d} => {:2d}", t_frame++, o_frame) << endl; } } } CATCH_TEST_CASE("Intseq", "[intseq]") { // This code should just finish without tripping the memory sanitizer CATCH_SECTION("intseq") { // run_sim(15.0, 15.0, 20); // run_sim(15.0, 7.5, 20); // run_sim(15.0, 10.0, 20); // run_sim(15.0, 20.0, 20); } } } // namespace perceive
25.958333
76
0.559658
[ "vector" ]
0a1035b5f9f512fcb49e3d27c9c8b186e4a00780
3,587
hpp
C++
environment/half_cheetah/include/HalfCheetahEnv.hpp
matthieu637/ddrl
a454d09a3ac9be5db960ff180b3d075c2f9e4a70
[ "MIT" ]
27
2017-11-27T09:32:41.000Z
2021-03-02T13:50:23.000Z
environment/half_cheetah/include/HalfCheetahEnv.hpp
matthieu637/ddrl
a454d09a3ac9be5db960ff180b3d075c2f9e4a70
[ "MIT" ]
10
2018-10-09T14:39:14.000Z
2020-11-10T15:01:00.000Z
environment/half_cheetah/include/HalfCheetahEnv.hpp
matthieu637/ddrl
a454d09a3ac9be5db960ff180b3d075c2f9e4a70
[ "MIT" ]
3
2019-05-16T09:14:15.000Z
2019-08-15T14:35:40.000Z
#ifndef HALTCHEETAHENV_H #define HALTCHEETAHENV_H #include <string> #include <vector> #include "bib/IniParser.hpp" #include "arch/AEnvironment.hpp" #include "HalfCheetahWorld.hpp" #include "HalfCheetahWorldView.hpp" class HalfCheetahEnv : public arch::AEnvironment<> { public: HalfCheetahEnv() { ODEFactory::getInstance(); instance = nullptr; } ~HalfCheetahEnv() { delete instance; } const std::vector<double>& perceptions() const override { return instance->state(); } double performance() const override { return instance->performance(); } bool final_state() const override { return instance->final_state(); } unsigned int number_of_actuators() const override { return instance->activated_motors(); } unsigned int number_of_sensors() const override { return instance->state().size(); } private: void _unique_invoke(boost::property_tree::ptree* pt, boost::program_options::variables_map* vm) override { hcheetah_physics init; init.apply_armature = pt->get<bool>("environment.apply_armature"); init.damping = pt->get<uint>("environment.damping"); init.control = pt->get<uint>("environment.control"); init.soft_cfm = pt->get<double>("environment.soft_cfm"); init.bounce = pt->get<double>("environment.bounce"); init.bounce_vel = 0; if (init.bounce >= 0.0000f) init.bounce_vel = pt->get<double>("environment.bounce_vel"); bool visible = vm->count("view"); bool capture = vm->count("capture"); init.predev = 0; try { init.predev = pt->get<uint>("environment.predev"); } catch(boost::exception const& ) { } init.from_predev = 0; try { init.from_predev = pt->get<uint>("environment.from_predev"); } catch(boost::exception const& ) { } init.pd_controller = true; try { init.pd_controller = pt->get<bool>("environment.pd_controller"); } catch(boost::exception const& ) { } ASSERT(init.predev == 0 || init.from_predev ==0, "for now only one dev"); init.lower_rigid = init.control == 1 && init.predev >= 1 && init.predev <= 9; init.higher_rigid = init.control == 1 && init.predev >= 10; if((init.lower_rigid || init.higher_rigid) && (init.predev == 3 || init.predev == 12)){ LOG_ERROR("control = 1 with predev 3/12 is the same as control = 1 with 2/11"); LOG_ERROR("3/12 forces sensors to 0 when they are defined (control=0)"); exit(1); } if (visible) instance = new HalfCheetahWorldView("data/textures", init, capture); else instance = new HalfCheetahWorld(init); } void _apply(const std::vector<double>& actuators) override { instance->step(actuators); } void _reset_episode(bool learning) override { std::vector<double> given_stoch={0,0}; if(!learning) given_stoch.clear(); instance->resetPositions(first_state_stochasticity, given_stoch); } void _reset_episode_choose(const std::vector<double>& given_stoch) override { instance->resetPositions(first_state_stochasticity, given_stoch); } void _next_instance(bool learning) override { std::vector<double> given_stoch={0,0}; if(!learning) given_stoch.clear(); instance->resetPositions(first_state_stochasticity, given_stoch); } void _next_instance_choose(const std::vector<double>& given_stoch) override { instance->resetPositions(first_state_stochasticity, given_stoch); } private: HalfCheetahWorld* instance; std::vector<double> internal_state; }; #endif // ADVANCEDACROBOTENV_H
29.401639
108
0.67438
[ "vector" ]
0a18eb6bcb5e4ba41962a8461887a1e802401544
1,780
cpp
C++
aws-cpp-sdk-ssm/source/model/ComplianceExecutionSummary.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-ssm/source/model/ComplianceExecutionSummary.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-ssm/source/model/ComplianceExecutionSummary.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T12:02:58.000Z
2021-11-09T12:02:58.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/ssm/model/ComplianceExecutionSummary.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace SSM { namespace Model { ComplianceExecutionSummary::ComplianceExecutionSummary() : m_executionTimeHasBeenSet(false), m_executionIdHasBeenSet(false), m_executionTypeHasBeenSet(false) { } ComplianceExecutionSummary::ComplianceExecutionSummary(JsonView jsonValue) : m_executionTimeHasBeenSet(false), m_executionIdHasBeenSet(false), m_executionTypeHasBeenSet(false) { *this = jsonValue; } ComplianceExecutionSummary& ComplianceExecutionSummary::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("ExecutionTime")) { m_executionTime = jsonValue.GetDouble("ExecutionTime"); m_executionTimeHasBeenSet = true; } if(jsonValue.ValueExists("ExecutionId")) { m_executionId = jsonValue.GetString("ExecutionId"); m_executionIdHasBeenSet = true; } if(jsonValue.ValueExists("ExecutionType")) { m_executionType = jsonValue.GetString("ExecutionType"); m_executionTypeHasBeenSet = true; } return *this; } JsonValue ComplianceExecutionSummary::Jsonize() const { JsonValue payload; if(m_executionTimeHasBeenSet) { payload.WithDouble("ExecutionTime", m_executionTime.SecondsWithMSPrecision()); } if(m_executionIdHasBeenSet) { payload.WithString("ExecutionId", m_executionId); } if(m_executionTypeHasBeenSet) { payload.WithString("ExecutionType", m_executionType); } return payload; } } // namespace Model } // namespace SSM } // namespace Aws
20
86
0.747191
[ "model" ]
0a1eb61756ecd4366000fe2bc307614d239d85f9
4,649
hpp
C++
SLAMWrapper/include/SLAMGUI/GUI_SLAM.hpp
Bovey0809/SCFusion
1d4a8f4eb0f330f5a69efd89fbf28686c1405471
[ "BSD-2-Clause" ]
30
2020-11-06T09:11:55.000Z
2022-03-11T06:56:57.000Z
SLAMWrapper/include/SLAMGUI/GUI_SLAM.hpp
ShunChengWu/SCFusion
1d4a8f4eb0f330f5a69efd89fbf28686c1405471
[ "BSD-2-Clause" ]
1
2021-12-17T07:03:01.000Z
2021-12-17T07:03:01.000Z
SLAMWrapper/include/SLAMGUI/GUI_SLAM.hpp
Bovey0809/SCFusion
1d4a8f4eb0f330f5a69efd89fbf28686c1405471
[ "BSD-2-Clause" ]
1
2021-12-17T07:02:47.000Z
2021-12-17T07:02:47.000Z
#pragma once #undef __AVX2__ #include "../../../libGUI3D/libGUI3D/GUI3D.h" #include <ImageLoader/ImageLoader.hpp> #include "../../../MainLib/Core/BasicSLAM/MainEngine.h" #include "../../../MainLib/Objects/Meshing/ITMMesh.h" #include <Utils/CUDAStreamHandler.hpp> #include <utility> #include "gui_kernel.hpp" #include "../SLAMTools/SLAMWrapper.h" #include "../../../libGUI3D/libGUI3D/ImageDrawer.h" #include <ft2build.h> #include FT_FREETYPE_H namespace SCFUSION { enum ProcessMode { STOP, STEPONCE, CONTINUE } ; template<class SLAMType> class SLAMGUI : public SC::GUI3D { public: SLAMGUI(SLAMWrapper<SLAMType> *slamWarpper, std::string outputPath); ~SLAMGUI(); virtual int initialization(); virtual void drawUI() override ; virtual void drawGL() override ; void run() override ; protected: bool bDrawBottomRightInfoPanel; virtual void DrawLeftPanel(); virtual void DrawMiddlePanel(); virtual void DrawTopRightPanel(); virtual void DrawBottomRightPanel(); virtual void DrawBottomRightOverlay(); protected: const unsigned int SHADOW_WIDTH = 1024, SHADOW_HEIGHT = 1024; std::string outputPath; std::string pth_to_log_file, pth_to_image_folder; ITMLib::ITMIntrinsics render_intrinsics; ITMLib::ITMIntrinsics camDepthParam, camColorParam; ProcessMode processmode_; cv::Mat cvDepthImage, cvColorImage; int iterSave; bool bRecordImage, bFollowGTPose; bool bShowPose,bCheckState; std::map<std::string, std::vector<double>> times_; std::fstream logFile_; std::unique_ptr<ITMUChar4Image> Block_ImageBuffer_; std::unique_ptr<glUtil::ImageDrawer> mImageDrawer; /// SLAM enum { camera_PoseView, camera_FreeView } cameraMode_; enum DisplayMode{ DisplayMode_FreeView_Surface, DisplayMode_FreeView_SurfaceLabel, DisplayMode_FreeView_ColoredLabel, DisplayMode_FreeView_Rendered_Height, }; DisplayMode displayMode_mesh; int displayMode_FreeView, displayMode_FollowView; SLAMWrapper<SLAMType> *slamWarpper_; SLAMType *slam_; int slam_getImageType; bool bNeedUpdate, bRenderMesh; CUDA_Stream_Handler<std::string> cuda_gui_streams_; /// Marching Cubes std::future<void> mc_thread_; std::mutex mutex_mc_; size_t mc_total_size; float mc_normal_sign_; std::unique_ptr<ORUtils::MemoryBlock<ITMLib::ITMMesh::Triangle>> mc_triangles; std::unique_ptr<ORUtils::MemoryBlock<ITMLib::ITMMesh::Normal>> mc_normals; std::unique_ptr<ORUtils::MemoryBlock<ITMLib::ITMMesh::Color>> mc_colors; std::unique_ptr<ORUtils::MemoryBlock<Vector4f>> points_location, points_color; std::atomic_int mc_vertices_size; bool bNeedUpdateSurface; int initMC(); virtual int NeedUpdateSurfaceConditions(); void copyMeshToGUI(SLAMType *slam); void updateVertexBuffer(size_t newSize, bool force = false); void drawMesh(glUtil::Shader *shader); void drawPointCloud(glUtil::Shader *shader); void ResetMCBuffer(); public: /// Multithreading function need to be public in order to be called from inherit classes virtual void extractGlobalMapSurface(); virtual void extractGlobalMapSurfaceLabel(); virtual void extractPoints(); protected: virtual void registerKeys(SC::GLFWWindowContainer *window); virtual void process_impl(); virtual bool process_slam(); virtual void recordImg(); virtual void renderImgFromSLAM(SLAMType *slam_); virtual void renderCamera(); virtual void calculateStatisticalTimes(std::ostream &os); virtual void printResultOnFile(std::ostream & os); virtual void alignToglCam(); int loadShaders(); /** * Camera refenrece frame: x: right, y: down, z: forward * OpenGL Reference frame: x: left, y: up z: forward */ void CameraRefenceToOpenGLReference(Eigen::Matrix4f *modelPose); /** * Camera refenrece frame: x: right, y: down, z: forward * OpenGL Reference frame: x: left, y: up z: forward */ void OpenGLReferenceToCameraRefence(ORUtils::Matrix4<float> *modelPose); void OpenGLReferenceToCameraRefence(Eigen::Map<Eigen::Matrix4f> *modelPose); void OpenGLReferenceToCameraRefence(Eigen::Matrix4f *modelPose); }; }
36.03876
100
0.665089
[ "vector" ]
0a1f16d7beb622b3d62c6caa1ab772fb63191290
468
cpp
C++
VehiclePhysicsSim/src/ICarModel.cpp
lbowes/A-Level-Computer-Science-NEA
0dd3f15a0b22a6622a962381089e8353c330680f
[ "MIT" ]
3
2019-09-07T02:05:47.000Z
2019-12-11T08:53:44.000Z
VehiclePhysicsSim/src/ICarModel.cpp
lbowes/vehicle-dynamics-simulation
0dd3f15a0b22a6622a962381089e8353c330680f
[ "MIT" ]
null
null
null
VehiclePhysicsSim/src/ICarModel.cpp
lbowes/vehicle-dynamics-simulation
0dd3f15a0b22a6622a962381089e8353c330680f
[ "MIT" ]
null
null
null
#include "ICarModel.h" #include "Car.h" namespace Visual { ICarModel::ICarModel(Internal::Car& carData, Framework::ResourceSet& resourceBucket) : /* Called by * - GameCarModel::GameCarModel * - DebugCarModel::DebugCarModel */ mResourceBucket(resourceBucket), mCarData(carData) { } void ICarModel::render(Framework::Graphics::Renderer& renderer) /* Called by VisualShell::renderAll */ { update(); mModel.sendRenderCommands(renderer); } }
20.347826
87
0.711538
[ "render" ]
0a284e99dfdd11d5fcd6654fde8fc42ec29c93f2
2,681
cpp
C++
SPOJ/SERVICE/dp.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2018-02-14T01:59:31.000Z
2018-03-28T03:30:45.000Z
SPOJ/SERVICE/dp.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
null
null
null
SPOJ/SERVICE/dp.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2017-12-30T02:46:35.000Z
2018-03-28T03:30:49.000Z
#include <iostream> #include <cstdio> #include <algorithm> #include <cmath> #include <cstring> #include <string> #include <climits> #include <iomanip> #include <vector> #include <queue> #include <set> #include <map> #include <stack> #include <functional> #include <iterator> #define SIZE 210 #define QSIZE 1010 using namespace std; int costArr[SIZE][SIZE]; int qArr[QSIZE]; int dp[2][SIZE][SIZE]; int main() { int caseNum; scanf("%d", &caseNum); while (caseNum--) { int len, qNum; scanf("%d%d", &len, &qNum); for (int i = 1; i <= len; i++) { for (int j = 1; j <= len; j++) { scanf("%d", costArr[i] + j); } } for (int i = 1; i <= qNum; i++) { scanf("%d", qArr + i); } qArr[0] = 3; for (int j = 1; j <= len; j++) { for (int k = 1; k <= len; k++) { dp[0][j][k] = INT_MAX; } } dp[0][1][2] = 0; for (int i = 0; i < qNum; i++) { for (int j = 1; j <= len; j++) { for (int k = 1; k <= len; k++) { dp[(i & 1) ^ 1][j][k] = INT_MAX; } } for (int j = 1; j <= len; j++) { for (int k = j + 1; k <= len; k++) { if (j == qArr[i] || k == qArr[i]) continue; if (dp[i & 1][j][k] == INT_MAX) continue; dp[(i & 1) ^ 1][j][k] = min(dp[(i & 1) ^ 1][j][k], dp[i & 1][j][k] + costArr[qArr[i]][qArr[i + 1]]); if (qArr[i] < k) dp[(i & 1) ^ 1][qArr[i]][k] = min(dp[(i & 1) ^ 1][qArr[i]][k], dp[i & 1][j][k] + costArr[j][qArr[i + 1]]); else dp[(i & 1) ^ 1][k][qArr[i]] = min(dp[(i & 1) ^ 1][k][qArr[i]], dp[i & 1][j][k] + costArr[j][qArr[i + 1]]); if (j < qArr[i]) dp[(i & 1) ^ 1][j][qArr[i]] = min(dp[(i & 1) ^ 1][j][qArr[i]], dp[i & 1][j][k] + costArr[k][qArr[i + 1]]); else dp[(i & 1) ^ 1][qArr[i]][j] = min(dp[(i & 1) ^ 1][qArr[i]][j], dp[i & 1][j][k] + costArr[k][qArr[i + 1]]); } } } int ans = INT_MAX; for (int j = 1; j <= len; j++) { for (int k = j + 1; k <= len; k++) { ans = min(ans, dp[qNum & 1][j][k]); } } printf("%d\n", ans); } return 0; }
26.81
143
0.34241
[ "vector" ]
0a306e0fa02a1429c80f26431bd33fe6d840d82a
2,039
cpp
C++
graph-source-code/141-D/12549808.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/141-D/12549808.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/141-D/12549808.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
//Language: GNU C++11 //be name khoda #include <bits/stdc++.h> using namespace std; #define pb push_back #define mp make_pair #define all(v) v.begin(),v.end() #define F first #define S second #define sz(x) (int)x.size() #define pii pair<int,int> typedef long long ll; const int MAXN=3*1000*100+100; struct edge{ int b,t,index; edge(int b,int t,int index) :b(b),t(t),index(index){} }; vector <edge> v[MAXN]; vector <int> a; ll n,l,dist[MAXN]; map <int,int> ma; bool mark[MAXN]; pii par[MAXN]; void checkrikht(int u) { if(u>=0 && !ma[u]) { ma[u]=a.size(); a.pb(u); } } int dijkstra() { priority_queue <pii> Q; fill(dist,dist+sz(a)+1,1e13); Q.push(mp(0,0)); // mark[0]=1; while(!Q.empty()) { pii x=Q.top(); Q.pop(); if(mark[x.S]) continue; // cout<<x.S<<" "<<x.F<<" "<<a[x.S]<<endl; mark[x.S]=1; dist[x.S]=-x.F; for(auto u:v[x.S]) if(dist[u.b]>dist[x.S]+u.t) { par[u.b]=mp(x.S,u.index); dist[u.b]=dist[x.S]+u.t; Q.push({-dist[u.b],u.b}); } } return dist[sz(a)-1]; } int main() { ios_base::sync_with_stdio(0); vector <pair<int ,edge> > vtemp; cin>>n>>l; a.pb(0); a.pb(l); for(int i=0;i<n;i++) { int x,t,p,l; cin>>x>>l>>t>>p; int u=x-p; int v=x+l; if(u>=0) a.pb(u); a.pb(v); if(u>=0) vtemp.push_back(mp(u,edge(v,t+p,i+1))); } sort(all(a)); a.resize(unique(all(a))-a.begin()); /* for(auto u:a) cout<<u<<" "; cout<<endl;//*/ for(int i=0;i<sz(a);i++){ ma[a[i]]=i; if(i<sz(a)-1){ v[i].pb(edge(i+1,a[i+1]-a[i],-1)); v[i+1].pb(edge(i,a[i+1]-a[i],-1));}} for(auto u:vtemp) v[ma[u.F]].pb(edge(ma[u.S.b],u.S.t,u.S.index)); /* for(int i=0;i<sz(a);i++) for(auto u:v[i]) cout<<i<<" "<<u.b<<" "<<u.t<<" "<<u.index<<endl;//*/ cout<<dijkstra()<<endl; /* for(int i=0;i<sz(a);i++) cout<<par[i].F<<" "<<par[i].S<<endl;*/ int t=sz(a)-1; vector <int> ans; par[0]={-1,-1}; while(t!=-1) { if(par[t].S!=-1) ans.pb(par[t].S); t=par[t].F; } cout<<sz(ans)<<endl; reverse(all(ans)); for(auto u:ans) cout<<u<<" "; cout<<endl; return 0; }
16.85124
55
0.533104
[ "vector" ]
0a3db83468569cf6cdfd9eb11432e12dc8efc283
13,476
cpp
C++
tools/sctk-2.4.10/src/asclite/core/sgml_reportgenerator.cpp
lonelybeansprouts/espnet
05ce03c00fb5cce98f2e0b0dfd177f4697f1b611
[ "Apache-2.0" ]
19
2015-03-19T10:53:38.000Z
2020-12-17T06:12:32.000Z
tools/sctk-2.4.10/src/asclite/core/sgml_reportgenerator.cpp
hongyuntw/ESPnet
44f78734034991fed4f42359f4d15f15504680bd
[ "Apache-2.0" ]
1
2018-12-18T17:43:44.000Z
2018-12-18T17:43:44.000Z
tools/sctk-2.4.10/src/asclite/core/sgml_reportgenerator.cpp
hongyuntw/ESPnet
44f78734034991fed4f42359f4d15f15504680bd
[ "Apache-2.0" ]
47
2015-01-27T06:22:57.000Z
2021-11-11T20:59:04.000Z
/* * ASCLITE * Author: Jerome Ajot, Jon Fiscus, Nicolas Radde, Chris Laprun * * This software was developed at the National Institute of Standards and Technology by * employees of the Federal Government in the course of their official duties. Pursuant * to title 17 Section 105 of the United States Code this software is not subject to * copyright protection and is in the public domain. ASCLITE is an experimental system. * NIST assumes no responsibility whatsoever for its use by other parties, and makes no * guarantees, expressed or implied, about its quality, reliability, or any other * characteristic. We would appreciate acknowledgement if the software is used. * * THIS SOFTWARE IS PROVIDED "AS IS." With regard to this software, NIST MAKES NO EXPRESS * OR IMPLIED WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING MERCHANTABILITY, * OR FITNESS FOR A PARTICULAR PURPOSE. */ #include "sgml_reportgenerator.h" // class's header file #include "alignedspeechiterator.h" #include "alignedsegmentiterator.h" #include "dateutils.h" #include "speechset.h" #include "tokenalignment.h" Logger* SGMLReportGenerator::m_pLogger = Logger::getLogger(); /** Generate the SGML report */ void SGMLReportGenerator::Generate(Alignment* alignment, int where) { for(size_t i=0; i<alignment->GetNbOfSystems(); ++i) { ofstream file; if(where == 1) { string filename; if(Properties::GetProperty("report.outputdir") == string("")) filename = alignment->GetSystemFilename(i) + ".sgml"; else filename = Properties::GetProperty("report.outputdir") + "/" + GetFileNameFromPath(alignment->GetSystemFilename(i)) + ".sgml"; file.open(filename.c_str()); if(! file.is_open()) { LOG_ERR(m_pLogger, "Could not open file '" + filename + "' for SGML report, the output will be redirected in the stdout to avoid any lost."); where = 1; } else { LOG_INFO(m_pLogger, "Generating SGML report file '" + filename + "'."); } } else { LOG_INFO(m_pLogger, "Generating SGML report in the stdout."); } ostream output(where == 1 ? file.rdbuf() : cout.rdbuf()); GenerateSystem(alignment, alignment->GetSystem(i), output); if(where == 1) file.close(); } } /** Generate the SGML report by system */ void SGMLReportGenerator::GenerateSystem(Alignment* alignment, const string& systm, ostream& output) { AlignedSpeechIterator* aAlignedSpeechs; AlignedSpeech* aAlignedSpeechCurrent; AlignedSegmentIterator* aAlignedSegments; AlignedSegment* aAlignedSegmentCurrent; typedef vector< Speaker* > Speakers; Speakers speakers; Speaker* speaker = NULL; string speakerId = ""; Speakers::iterator potentialSpeaker; SpeakerNamePredicate predicate; SpeechSet* parentSpeechSet = NULL; string ref_fname, hyp_fname; ref_fname = ""; hyp_fname = ""; bool fileNamesSet = false; // Prepare the speakers for output aAlignedSpeechs = alignment->AlignedSpeeches(); while(aAlignedSpeechs->Current(&aAlignedSpeechCurrent)) { aAlignedSegments = aAlignedSpeechCurrent->AlignedSegments(); if(!parentSpeechSet) parentSpeechSet = aAlignedSpeechCurrent->GetReferenceSpeech()->GetParentSpeechSet(); if(!fileNamesSet) ref_fname = aAlignedSpeechCurrent->GetReferenceSpeech()->GetParentSpeechSet()->GetSourceFileName(); while(aAlignedSegments->Current(&aAlignedSegmentCurrent)) { if(!fileNamesSet) { if (aAlignedSegmentCurrent->GetTokenAlignmentCount() != 0) { Token* token = aAlignedSegmentCurrent->GetTokenAlignmentAt(0)->GetAlignmentFor(systm)->GetToken(); if(token != NULL) { hyp_fname = token->GetParentSegment()->GetParentSpeech()->GetParentSpeechSet()->GetSourceFileName(); fileNamesSet = true; } } } // First try to get the speaker associated with the current reference segment speakerId = aAlignedSegmentCurrent->GetReferenceSegment()->GetSpeakerId(); predicate.SetWantedName(speakerId); potentialSpeaker = find_if(speakers.begin(), speakers.end(), predicate); // If we haven't created the speaker already, create it if(potentialSpeaker == speakers.end()) { speaker = new Speaker(speakerId, aAlignedSegmentCurrent->GetReferenceSegment()->GetSourceElementNum()); speakers.push_back(speaker); } else { speaker = *potentialSpeaker; } // Add the current AlignedSegment to the current speaker speaker->AddSegment(aAlignedSegmentCurrent); } // Sort by sequence order the AlignedSegments for this speaker speaker->SortSegments(); } // Re-order the speakers by sequence order sort(speakers.begin(), speakers.end(), SpeakerSequenceComparator()); string creation_date, format, frag_corr, opt_del, weight_ali, weight_filename; creation_date = DateUtils::GetDateString(); format = "2.4"; frag_corr = (Properties::GetProperty("align.fragment_are_correct") == "true") ? "TRUE" : "FALSE"; opt_del = (Properties::GetProperty("align.optionally") == "both") ? "TRUE" : "FALSE"; m_bCaseSensitive = (Properties::GetProperty("align.case_sensitive") == "true") ? true : false; weight_ali = "FALSE"; weight_filename = ""; output << "<SYSTEM"; output << " title=" << "\"" << GetFileNameFromPath(systm) << "\""; output << " ref_fname=" << "\"" << ref_fname << "\""; output << " hyp_fname=" << "\"" << hyp_fname << "\""; output << " creation_date=" << "\"" << creation_date << "\""; output << " format=" << "\"" << format << "\""; output << " frag_corr=" << "\"" << frag_corr << "\""; output << " opt_del=" << "\"" << opt_del << "\""; output << " weight_ali=" << "\"" << weight_ali << "\""; output << " weight_filename=" << "\"" << weight_filename << "\""; output << ">" << endl; GenerateCategoryLabel(parentSpeechSet, output); m_bRefHasTimes = m_bRefHasConf = m_bHypHasConf = m_bHypHasTimes = false; Speakers::iterator current = speakers.begin(); Speakers::iterator end = speakers.end(); while (current != end) { PreProcessWordAux(*current, systm); ++current; } // Output speakers current = speakers.begin(); while (current != end) { GenerateSpeaker(*current, systm, output); ++current; } output << "</SYSTEM>" << endl; } void SGMLReportGenerator::GenerateCategoryLabel(SpeechSet* speechSet, ostream& output) { for(size_t i=0; i<speechSet->GetNumberCategoryLabel(); ++i) { output << "<" << speechSet->GetCategoryLabelType(i); output << " id=\"" << speechSet->GetCategoryLabelID(i) << "\""; output << " title=\"" << speechSet->GetCategoryLabelTitle(i) << "\""; output << " desc=\"" << speechSet->GetCategoryLabelDesc(i) << "\""; output << ">" << endl; output << "</" << speechSet->GetCategoryLabelType(i) << ">" << endl; } } void SGMLReportGenerator::GenerateSpeaker(Speaker* speaker, const string& systm, ostream& output) { vector<AlignedSegment*> segments = speaker->GetSegments(); vector<AlignedSegment*>::iterator i = segments.begin(); vector<AlignedSegment*>::iterator ei = segments.end(); string speakerName = speaker->GetName(); output << "<SPEAKER"; output << " id=" << "\"" << speakerName << "\""; output << ">" << endl; while(i != ei) { GeneratePath(*i, systm, output); ++i; } output << "</SPEAKER>" << endl; } void SGMLReportGenerator::GeneratePath(AlignedSegment* alignedSegment, const string& systm, ostream& output) { //PreProcessPath(alignedSegment, systm, &refHasTimes, &refHasConf, &hypHasConf, &hypHasTimes); Segment* refSegment = alignedSegment->GetReferenceSegment(); output << "<PATH"; output << " id=\"" << refSegment->GetId() << "\""; output << " word_cnt=\"" << alignedSegment->GetTokenAlignmentCount() << "\""; if(refSegment->GetLabel() != "") output << " labels=\"" << refSegment->GetLabel() << "\""; if (refSegment->GetSource().compare("") != 0) output << " file=\"" << refSegment->GetSource() << "\""; if (refSegment->GetChannel().compare("") != 0) output << " channel=\"" << refSegment->GetChannel() << "\""; output << " sequence=\"" << refSegment->GetSourceElementNum() << "\""; if (refSegment->IsTimeReal()){ output.setf(ios::fixed); output << setprecision(3); output << " R_T1=\"" << ((double)(refSegment->GetStartTime()))/1000.0 << "\""; output << " R_T2=\"" << ((double)(refSegment->GetEndTime()))/1000.0 << "\""; } HandleWordAux(output); if(m_bCaseSensitive) output << " case_sense=\"1\""; output << ">" << endl; size_t tokenNumber = alignedSegment->GetTokenAlignmentCount(); if (tokenNumber > 0) { GenerateTokenAlignment(alignedSegment->GetTokenAlignmentAt(0), systm, output); for(size_t i = 1; i < tokenNumber; i++) { output << ":"; GenerateTokenAlignment(alignedSegment->GetTokenAlignmentAt(i), systm, output); } } output << endl << "</PATH>" << endl; } void SGMLReportGenerator::PreProcessWordAux(Speaker* speaker, const string& systm) { vector<AlignedSegment*> segments = speaker->GetSegments(); vector<AlignedSegment*>::iterator j = segments.begin(); vector<AlignedSegment*>::iterator ej = segments.end(); while(j != ej) { uint tokenNumber = (*j)->GetTokenAlignmentCount(); Token* ref; Token* hyp; TokenAlignment* ta; for(size_t i = 0; i < tokenNumber; i++) { ta = (*j)->GetTokenAlignmentAt(i); hyp = ta->GetTokenFor(systm); ref = ta->GetReferenceToken(); if(ref) { if(!m_bRefHasConf) m_bRefHasConf = ref->IsConfidenceSet(); if(!m_bRefHasTimes) m_bRefHasTimes = ref->IsTimeReal(); } if(hyp) { if (!m_bHypHasConf) m_bHypHasConf = hyp->IsConfidenceSet(); if(!m_bHypHasTimes) m_bHypHasTimes = hyp->IsTimeReal(); } } ++j; } } void SGMLReportGenerator::HandleWordAux(ostream& output) { // Ignores ref and hyp weight as Jon instructed... if(m_bRefHasTimes || m_bHypHasTimes || m_bRefHasConf || m_bHypHasConf || (string("true").compare(Properties::GetProperty("align.speakeroptimization")) == 0)) { output << " word_aux=\""; uint more = 0; if(m_bRefHasTimes) { output << "r_t1+t2"; more++; } if(m_bHypHasTimes) { if (more++ != 0) output << ","; output << "h_t1+t2"; } if(m_bRefHasConf) { if (more++ != 0) output << ","; output << "r_conf"; } if(m_bHypHasConf) { if (more++ != 0) output << ","; output << "h_conf"; } if (string("true").compare(Properties::GetProperty("align.speakeroptimization")) == 0) { if (more++ != 0) output << ","; output << "h_spkr,h_isSpkrSub"; } output << "\""; } } void SGMLReportGenerator::GenerateTokenAlignment(TokenAlignment* tokenAlign, const string& systm, ostream& output) { TokenAlignment::AlignmentEvaluation* evaluation = tokenAlign->GetAlignmentFor(systm); TokenAlignment::AlignmentResult aAlignmentResult = evaluation->GetResult(); if(aAlignmentResult == TokenAlignment::UNAVAILABLE) { cerr << "Scoring not set." << endl << "Report cannot be done!" << endl; return; } Token* hyp = evaluation->GetToken(); Token* ref = tokenAlign->GetReferenceToken(); if(aAlignmentResult == TokenAlignment::SPEAKERSUB) { output << ((TokenAlignment::AlignmentResult)(TokenAlignment::SUBSTITUTION)).GetShortName() << ","; } else { output << aAlignmentResult.GetShortName() << ","; } if(ref) { OutputTextFor(ref, output); } else if(aAlignmentResult == TokenAlignment::CORRECT) { output << "\"\""; } output << ","; if(hyp) { OutputTextFor(hyp, output); } else if(aAlignmentResult == TokenAlignment::CORRECT) { output << "\"\""; } if(m_bRefHasTimes) { output << ","; if(ref) { if(ref->IsTimeReal()) { output.setf(ios::fixed); output << setprecision(3); output << ((double)(ref->GetStartTime()))/1000.0 << "+" << ((double)(ref->GetEndTime()))/1000.0; } } } if(m_bHypHasTimes) { output << ","; if(hyp) { if(hyp->IsTimeReal()) { output.setf(ios::fixed); output << setprecision(3); output << ((double)(hyp->GetStartTime()))/1000.0 << "+" << ((double)(hyp->GetEndTime()))/1000.0; } } } if(m_bRefHasConf) { output << ","; if(ref) { if(ref->IsConfidenceSet()) { output.setf(ios::fixed); output << setprecision(6); output << ref->GetConfidence(); } } } if(m_bHypHasConf) { output << ","; if(hyp) { if(hyp->IsConfidenceSet()) { output.setf(ios::fixed); output << setprecision(6); output << hyp->GetConfidence(); } } } if (string("true").compare(Properties::GetProperty("align.speakeroptimization")) == 0) { output << ","; if(hyp) output << hyp->GetParentSegment()->GetSpeakerId(); output << ","; if(hyp) if (aAlignmentResult == TokenAlignment::SPEAKERSUB) output << "true"; else output << "false"; } } void SGMLReportGenerator::OutputTextFor(Token* token, ostream& output) { int fragStatus = token->GetFragmentStatus(); bool optional = token->IsOptional(); output << "\""; output << (optional ? "(" : ""); if(fragStatus == Token::END_FRAGMENT) output << "-"; if (m_bCaseSensitive) output << token->GetText(); else output << token->GetTextInLowerCase(); if(fragStatus == Token::BEGIN_FRAGMENT) output << "-"; output << (optional ? ")" : "") << "\""; }
26.579882
145
0.640472
[ "vector" ]
0a47f7275fc5accf2e69445ca5195ef257126839
3,229
cpp
C++
Prototype/src/GameObject/Component/gameplay/movement.cpp
ArneStenkrona/Prototype
2d53a0daf35ca7de676c90c7f193b38dc16d5230
[ "MIT" ]
null
null
null
Prototype/src/GameObject/Component/gameplay/movement.cpp
ArneStenkrona/Prototype
2d53a0daf35ca7de676c90c7f193b38dc16d5230
[ "MIT" ]
null
null
null
Prototype/src/GameObject/Component/gameplay/movement.cpp
ArneStenkrona/Prototype
2d53a0daf35ca7de676c90c7f193b38dc16d5230
[ "MIT" ]
null
null
null
#include "movement.h" #include "GameObject/gameObject.h" #include <iostream> #include "SDL.h" #include "System/IO/inputManager.h" #include <algorithm> #include "System\Physics\physicsEngine.h" #include "System\graphics\graphicsEngine.h" #include "System\sound\soundManager.h" Movement::Movement(GameObject *_object) : Component(_object), state(nullState), prevState(nullState), transitionCounter(0), grounded(false) { position = requireComponent<Position>(); velocity = requireComponent<Velocity>(); sprite = requireComponent<Sprite>(); animator = requireComponent<Animator>(); } void Movement::updateComponents() { position = (object->hasComponent<Position>()) ? object->getComponent<Position>() : position; velocity = (object->hasComponent<Velocity>()) ? object->getComponent<Velocity>() : velocity; sprite = (object->hasComponent<Sprite>()) ? object->getComponent<Sprite>() : sprite; animator = (object->hasComponent<Animator>()) ? object->getComponent<Animator>() : animator; } void Movement::onCollisionExit() { } void Movement::start() { } void Movement::update() { Point origin = position->position + Point(3, 39.7); grounded = PhysicsEngine::raycast(origin, origin + Point(26, 2), 0) || PhysicsEngine::raycast(origin + Point(26, 0), origin + Point(-26, 2), 0); //Initalize direction vector to 0,0 Point direction = Point(); if (abs(velocity->velocity.x) < 1) state = idle; if (getKey(INPUT_KEY_A)) { direction += Point::left; if (velocity->velocity.x < -2) state = running; } if (getKey(INPUT_KEY_D)) { direction += Point::right; if (velocity->velocity.x > 2) state = running; } if (getKey(INPUT_KEY_W)) { //direction += Point::down; } if (getKey(INPUT_KEY_S)) { //direction += Point::up; } if (!grounded) state = falling; //DIRTY HACK! SHOULD BE FIXED BY CREATING A PROPER ANIMATION DATA STRUCTURE switch (state) { case idle : animator->playClip("idle", prevState == running); animator->setSpeedFactor(1); break; case running : animator->setSpeedFactor(min(2.4, 5.8 / abs(velocity->velocity.x))); if (prevState != running) { animator->playClip("running", false); } if (getKey(INPUT_KEY_A)) sprite->setMirror(true, false); if (getKey(INPUT_KEY_D)) sprite->setMirror(false, false); break; case falling : animator->playClip("falling", false); animator->setSpeedFactor(1); break; } prevState = state; direction = direction.normalized(); Point deltaTerm = direction * acceleration; //Limit speed if ((velocity->velocity + deltaTerm).magnitude() < speed) { velocity->velocity += deltaTerm; } //Add drag velocity->velocity = Point(velocity->velocity.x * drag, velocity->velocity.y);// *drag); //Add gravity if (velocity->velocity.y < 10) { velocity->velocity += Point::up * 0.4; } if (getKeyDown(INPUT_KEY_SPACE)) { if (velocity->velocity.y > -1) { velocity->velocity -= Point::up * 10; } } }
27.836207
149
0.622793
[ "object", "vector" ]
0a4cd34535fcff840a847576965e9bd12ee59938
12,785
cpp
C++
model/PublicVolume.cpp
lighthouse-os/system_vold
a6410826bfb872d3b2a52cff063b271fef133e54
[ "Apache-2.0" ]
null
null
null
model/PublicVolume.cpp
lighthouse-os/system_vold
a6410826bfb872d3b2a52cff063b271fef133e54
[ "Apache-2.0" ]
null
null
null
model/PublicVolume.cpp
lighthouse-os/system_vold
a6410826bfb872d3b2a52cff063b271fef133e54
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2015 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 "PublicVolume.h" #include "AppFuseUtil.h" #include "Utils.h" #include "VolumeManager.h" #include "fs/Exfat.h" #include "fs/Ext4.h" #include "fs/F2fs.h" #include "fs/Ntfs.h" #include "fs/Vfat.h" #include <android-base/logging.h> #include <android-base/properties.h> #include <android-base/stringprintf.h> #include <cutils/fs.h> #include <private/android_filesystem_config.h> #include <utils/Timers.h> #include <fcntl.h> #include <stdlib.h> #include <sys/mount.h> #include <sys/stat.h> #include <sys/sysmacros.h> #include <sys/types.h> #include <sys/wait.h> using android::base::GetBoolProperty; using android::base::StringPrintf; namespace android { namespace vold { static const char* kSdcardFsPath = "/system/bin/sdcard"; static const char* kAsecPath = "/mnt/secure/asec"; PublicVolume::PublicVolume(dev_t device, const std::string& fstype /* = "" */, const std::string& mntopts /* = "" */) : VolumeBase(Type::kPublic), mDevice(device), mFsType(fstype), mMntOpts(mntopts) { setId(StringPrintf("public:%u,%u", major(device), minor(device))); mDevPath = StringPrintf("/dev/block/vold/%s", getId().c_str()); mFuseMounted = false; mUseSdcardFs = IsSdcardfsUsed(); } PublicVolume::~PublicVolume() {} status_t PublicVolume::readMetadata() { status_t res = ReadMetadataUntrusted(mDevPath, &mFsType, &mFsUuid, &mFsLabel); auto listener = getListener(); if (listener) listener->onVolumeMetadataChanged(getId(), mFsType, mFsUuid, mFsLabel); return res; } status_t PublicVolume::initAsecStage() { std::string legacyPath(mRawPath + "/android_secure"); std::string securePath(mRawPath + "/.android_secure"); // Recover legacy secure path if (!access(legacyPath.c_str(), R_OK | X_OK) && access(securePath.c_str(), R_OK | X_OK)) { if (rename(legacyPath.c_str(), securePath.c_str())) { PLOG(WARNING) << getId() << " failed to rename legacy ASEC dir"; } } if (TEMP_FAILURE_RETRY(mkdir(securePath.c_str(), 0700))) { if (errno != EEXIST) { PLOG(WARNING) << getId() << " creating ASEC stage failed"; return -errno; } } BindMount(securePath, kAsecPath); return OK; } status_t PublicVolume::doCreate() { return CreateDeviceNode(mDevPath, mDevice); } status_t PublicVolume::doDestroy() { return DestroyDeviceNode(mDevPath); } status_t PublicVolume::doMount() { bool isVisible = getMountFlags() & MountFlags::kVisible; readMetadata(); if (!IsFilesystemSupported(mFsType)) { LOG(ERROR) << getId() << " unsupported filesystem " << mFsType; return -EIO; } // Use UUID as stable name, if available std::string stableName = getId(); if (!mFsUuid.empty()) { stableName = mFsUuid; } mRawPath = StringPrintf("/mnt/media_rw/%s", stableName.c_str()); mSdcardFsDefault = StringPrintf("/mnt/runtime/default/%s", stableName.c_str()); mSdcardFsRead = StringPrintf("/mnt/runtime/read/%s", stableName.c_str()); mSdcardFsWrite = StringPrintf("/mnt/runtime/write/%s", stableName.c_str()); mSdcardFsFull = StringPrintf("/mnt/runtime/full/%s", stableName.c_str()); setInternalPath(mRawPath); if (isVisible) { setPath(StringPrintf("/storage/%s", stableName.c_str())); } else { setPath(mRawPath); } if (fs_prepare_dir(mRawPath.c_str(), 0700, AID_ROOT, AID_ROOT)) { PLOG(ERROR) << getId() << " failed to create mount points"; return -errno; } int ret = 0; if (mFsType == "exfat") { ret = exfat::Check(mDevPath); } else if (mFsType == "ext4") { ret = ext4::Check(mDevPath, mRawPath, false); } else if (mFsType == "f2fs") { ret = f2fs::Check(mDevPath, false); } else if (mFsType == "ntfs") { ret = ntfs::Check(mDevPath); } else if (mFsType == "vfat") { ret = vfat::Check(mDevPath); } else { LOG(WARNING) << getId() << " unsupported filesystem check, skipping"; } if (ret) { LOG(ERROR) << getId() << " failed filesystem check"; return -EIO; } if (mFsType == "exfat") { ret = exfat::Mount(mDevPath, mRawPath, AID_ROOT, (isVisible ? AID_MEDIA_RW : AID_EXTERNAL_STORAGE), 0007); } else if (mFsType == "ext4") { ret = ext4::Mount(mDevPath, mRawPath, false, false, true, mMntOpts, false, true); } else if (mFsType == "f2fs") { ret = f2fs::Mount(mDevPath, mRawPath, mMntOpts, false, true); } else if (mFsType == "ntfs") { ret = ntfs::Mount(mDevPath, mRawPath, AID_ROOT, (isVisible ? AID_MEDIA_RW : AID_EXTERNAL_STORAGE), 0007); } else if (mFsType == "vfat") { ret = vfat::Mount(mDevPath, mRawPath, false, false, false, AID_ROOT, (isVisible ? AID_MEDIA_RW : AID_EXTERNAL_STORAGE), 0007, true); } else { ret = ::mount(mDevPath.c_str(), mRawPath.c_str(), mFsType.c_str(), 0, NULL); } if (ret) { PLOG(ERROR) << getId() << " failed to mount " << mDevPath; return -EIO; } if (getMountFlags() & MountFlags::kPrimary) { initAsecStage(); } if (!isVisible) { // Not visible to apps, so no need to spin up sdcardfs or FUSE return OK; } if (mUseSdcardFs) { if (fs_prepare_dir(mSdcardFsDefault.c_str(), 0700, AID_ROOT, AID_ROOT) || fs_prepare_dir(mSdcardFsRead.c_str(), 0700, AID_ROOT, AID_ROOT) || fs_prepare_dir(mSdcardFsWrite.c_str(), 0700, AID_ROOT, AID_ROOT) || fs_prepare_dir(mSdcardFsFull.c_str(), 0700, AID_ROOT, AID_ROOT)) { PLOG(ERROR) << getId() << " failed to create sdcardfs mount points"; return -errno; } dev_t before = GetDevice(mSdcardFsFull); int sdcardFsPid; if (!(sdcardFsPid = fork())) { if (getMountFlags() & MountFlags::kPrimary) { // clang-format off if (execl(kSdcardFsPath, kSdcardFsPath, "-u", "1023", // AID_MEDIA_RW "-g", "1023", // AID_MEDIA_RW "-U", std::to_string(getMountUserId()).c_str(), "-w", mRawPath.c_str(), stableName.c_str(), NULL)) { // clang-format on PLOG(ERROR) << "Failed to exec"; } } else { // clang-format off if (execl(kSdcardFsPath, kSdcardFsPath, "-u", "1023", // AID_MEDIA_RW "-g", "1023", // AID_MEDIA_RW "-U", std::to_string(getMountUserId()).c_str(), mRawPath.c_str(), stableName.c_str(), NULL)) { // clang-format on PLOG(ERROR) << "Failed to exec"; } } LOG(ERROR) << "sdcardfs exiting"; _exit(1); } if (sdcardFsPid == -1) { PLOG(ERROR) << getId() << " failed to fork"; return -errno; } nsecs_t start = systemTime(SYSTEM_TIME_BOOTTIME); while (before == GetDevice(mSdcardFsFull)) { LOG(DEBUG) << "Waiting for sdcardfs to spin up..."; usleep(50000); // 50ms nsecs_t now = systemTime(SYSTEM_TIME_BOOTTIME); if (nanoseconds_to_milliseconds(now - start) > 5000) { LOG(WARNING) << "Timed out while waiting for sdcardfs to spin up"; return -ETIMEDOUT; } } /* sdcardfs will have exited already. The filesystem will still be running */ TEMP_FAILURE_RETRY(waitpid(sdcardFsPid, nullptr, 0)); } bool isFuse = base::GetBoolProperty(kPropFuse, false); if (isFuse) { // We need to mount FUSE *after* sdcardfs, since the FUSE daemon may depend // on sdcardfs being up. LOG(INFO) << "Mounting public fuse volume"; android::base::unique_fd fd; int user_id = getMountUserId(); int result = MountUserFuse(user_id, getInternalPath(), stableName, &fd); if (result != 0) { LOG(ERROR) << "Failed to mount public fuse volume"; doUnmount(); return -result; } mFuseMounted = true; auto callback = getMountCallback(); if (callback) { bool is_ready = false; callback->onVolumeChecking(std::move(fd), getPath(), getInternalPath(), &is_ready); if (!is_ready) { LOG(ERROR) << "Failed to complete public volume mount"; doUnmount(); return -EIO; } } ConfigureReadAheadForFuse(GetFuseMountPathForUser(user_id, stableName), 256u); // See comment in model/EmulatedVolume.cpp ConfigureMaxDirtyRatioForFuse(GetFuseMountPathForUser(user_id, stableName), 40u); } return OK; } status_t PublicVolume::doUnmount() { // Unmount the storage before we kill the FUSE process. If we kill // the FUSE process first, most file system operations will return // ENOTCONN until the unmount completes. This is an exotic and unusual // error code and might cause broken behaviour in applications. KillProcessesUsingPath(getPath()); if (mFuseMounted) { // Use UUID as stable name, if available std::string stableName = getId(); if (!mFsUuid.empty()) { stableName = mFsUuid; } if (UnmountUserFuse(getMountUserId(), getInternalPath(), stableName) != OK) { PLOG(INFO) << "UnmountUserFuse failed on public fuse volume"; return -errno; } mFuseMounted = false; } ForceUnmount(kAsecPath); if (mUseSdcardFs) { ForceUnmount(mSdcardFsDefault); ForceUnmount(mSdcardFsRead); ForceUnmount(mSdcardFsWrite); ForceUnmount(mSdcardFsFull); rmdir(mSdcardFsDefault.c_str()); rmdir(mSdcardFsRead.c_str()); rmdir(mSdcardFsWrite.c_str()); rmdir(mSdcardFsFull.c_str()); mSdcardFsDefault.clear(); mSdcardFsRead.clear(); mSdcardFsWrite.clear(); mSdcardFsFull.clear(); } ForceUnmount(mRawPath); rmdir(mRawPath.c_str()); mRawPath.clear(); return OK; } status_t PublicVolume::doFormat(const std::string& fsType) { bool useVfat = vfat::IsSupported(); bool useExfat = exfat::IsSupported(); status_t res = OK; // Resolve the target filesystem type if (fsType == "auto" && useVfat && useExfat) { uint64_t size = 0; res = GetBlockDevSize(mDevPath, &size); if (res != OK) { LOG(ERROR) << "Couldn't get device size " << mDevPath; return res; } // If both vfat & exfat are supported use exfat for SDXC (>~32GiB) cards if (size > 32896LL * 1024 * 1024) { useVfat = false; } else { useExfat = false; } } else if (fsType == "vfat") { useExfat = false; } else if (fsType == "exfat") { useVfat = false; } if (!IsFilesystemSupported(fsType) && !useVfat && !useExfat) { LOG(ERROR) << "Unsupported filesystem " << fsType; return -EINVAL; } if (WipeBlockDevice(mDevPath) != OK) { LOG(WARNING) << getId() << " failed to wipe"; } if (useVfat) { res = vfat::Format(mDevPath, 0); } else if (useExfat) { res = exfat::Format(mDevPath); } else if (fsType == "ext4") { res = ext4::Format(mDevPath, 0, mRawPath); } else if (fsType == "f2fs") { res = f2fs::Format(mDevPath); } else if (fsType == "ntfs") { res = ntfs::Format(mDevPath); } else { LOG(ERROR) << getId() << " unrecognized filesystem " << fsType; res = -1; errno = EIO; } if (res != OK) { LOG(ERROR) << getId() << " failed to format"; res = -errno; } return res; } } // namespace vold } // namespace android
32.285354
114
0.582088
[ "model" ]
aea6efec3ff84c61d2d65cb76eaed66b7109921e
3,261
hpp
C++
include/codegen/include/GlobalNamespace/GameScenesManager_--c__DisplayClass33_0.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/GlobalNamespace/GameScenesManager_--c__DisplayClass33_0.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/GlobalNamespace/GameScenesManager_--c__DisplayClass33_0.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: GameScenesManager #include "GlobalNamespace/GameScenesManager.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: List`1<T> template<typename T> class List_1; } // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: ScenesTransitionSetupDataSO class ScenesTransitionSetupDataSO; } // Forward declaring namespace: System namespace System { // Forward declaring type: Action class Action; // Forward declaring type: Action`1<T> template<typename T> class Action_1; } // Forward declaring namespace: Zenject namespace Zenject { // Forward declaring type: DiContainer class DiContainer; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Autogenerated type: GameScenesManager/<>c__DisplayClass33_0 class GameScenesManager::$$c__DisplayClass33_0 : public ::Il2CppObject { public: // public GameScenesManager <>4__this // Offset: 0x10 GlobalNamespace::GameScenesManager* $$4__this; // public System.Collections.Generic.List`1<System.String> newSceneNames // Offset: 0x18 System::Collections::Generic::List_1<::Il2CppString*>* newSceneNames; // public System.Collections.Generic.List`1<System.String> emptyTransitionSceneNameList // Offset: 0x20 System::Collections::Generic::List_1<::Il2CppString*>* emptyTransitionSceneNameList; // public GameScenesManager/ScenesStackData scenesStackData // Offset: 0x28 GlobalNamespace::GameScenesManager::ScenesStackData* scenesStackData; // public ScenesTransitionSetupDataSO scenesTransitionSetupData // Offset: 0x30 GlobalNamespace::ScenesTransitionSetupDataSO* scenesTransitionSetupData; // public System.Action finishCallback // Offset: 0x38 System::Action* finishCallback; // public System.Action`1<Zenject.DiContainer> <>9__1 // Offset: 0x40 System::Action_1<Zenject::DiContainer*>* $$9__1; // public System.Action <>9__2 // Offset: 0x48 System::Action* $$9__2; // System.Void <ClearAndOpenScenes>b__0() // Offset: 0xCB4EDC void $ClearAndOpenScenes$b__0(); // System.Void <ClearAndOpenScenes>b__1(Zenject.DiContainer container) // Offset: 0xCB5018 void $ClearAndOpenScenes$b__1(Zenject::DiContainer* container); // System.Void <ClearAndOpenScenes>b__2() // Offset: 0xCB50C0 void $ClearAndOpenScenes$b__2(); // public System.Void .ctor() // Offset: 0xCB3D88 // Implemented from: System.Object // Base method: System.Void Object::.ctor() static GameScenesManager::$$c__DisplayClass33_0* New_ctor(); }; // GameScenesManager/<>c__DisplayClass33_0 } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::GameScenesManager::$$c__DisplayClass33_0*, "", "GameScenesManager/<>c__DisplayClass33_0"); #pragma pack(pop)
38.364706
130
0.729837
[ "object" ]
aeb461502ac3acab687329d656d9116fc8e383ca
1,756
cpp
C++
structural/composite.cpp
idfumg/PatternsSynopsis
bc200596a95c464443bba8ed525d4c0ef2fa3c94
[ "MIT" ]
null
null
null
structural/composite.cpp
idfumg/PatternsSynopsis
bc200596a95c464443bba8ed525d4c0ef2fa3c94
[ "MIT" ]
null
null
null
structural/composite.cpp
idfumg/PatternsSynopsis
bc200596a95c464443bba8ed525d4c0ef2fa3c94
[ "MIT" ]
null
null
null
/* Паттерн Composite позволяет объединять группы схожих объектов и управлять ими. Объекты могут быть как примитивными, так и составными. (директория файловой системы). Код клиента работает с примитивными и составными объектами единообразно. */ #include <iostream> #include <vector> #include <assert.h> using namespace std; class Unit { public: virtual int getStrength() = 0; virtual void addUnit(Unit* p) { assert(false); } virtual ~Unit() {} }; class Infantryman : public Unit { public: virtual int getStrength() { return 1; } }; class Archer : public Unit { public: virtual int getStrength() { return 2; } }; class Horseman : public Unit { public: virtual int getStrength() { return 3; } }; class CompositeUnit : public Unit { public: int getStrength() { int total = 0; for (Unit* unit : units) total += unit->getStrength(); return total; } void addUnit(Unit* unit) { units.push_back(unit); } ~CompositeUnit() { for (Unit* unit : units) delete unit; } private: vector<Unit*> units; }; CompositeUnit* CreateLegion() { CompositeUnit* legion = new CompositeUnit; for (int i = 0; i < 3000; ++i) legion->addUnit(new Infantryman); for (int i = 0; i < 2000; ++i) legion->addUnit(new Archer); for (int i = 0; i < 1000; ++i) legion->addUnit(new Horseman); return legion; } int main() { CompositeUnit* army = new CompositeUnit; for (int i = 0; i < 4; ++i) army->addUnit(CreateLegion()); cout << "Roman army damaging strength is: " << army->getStrength() << endl; delete army; return 0; }
18.680851
54
0.594533
[ "vector" ]
aec39321a794a43eba9dc15b1a283993bc56f81a
3,341
cpp
C++
Greedy/646. Maximum Length of Pair Chain.cpp
beckswu/Leetcode
480e8dc276b1f65961166d66efa5497d7ff0bdfd
[ "MIT" ]
138
2020-02-08T05:25:26.000Z
2021-11-04T11:59:28.000Z
Greedy/646. Maximum Length of Pair Chain.cpp
beckswu/Leetcode
480e8dc276b1f65961166d66efa5497d7ff0bdfd
[ "MIT" ]
null
null
null
Greedy/646. Maximum Length of Pair Chain.cpp
beckswu/Leetcode
480e8dc276b1f65961166d66efa5497d7ff0bdfd
[ "MIT" ]
24
2021-01-02T07:18:43.000Z
2022-03-20T08:17:54.000Z
ps://leetcode.com/problems/maximum-length-of-pair-chain/description/ /* 根据end sort: 因为chain是要 下一个点的start > 上一个点的end,所以end由小到大sort,end逐渐增大,有利于一开始减小end, 可以放进更小的start,增加count 不用管start的position,因为不管start,只要start > end就可以加起来,否则免谈 比如 当前end = 3, 后面有点[2,6], [4,6], 如果[2,6]在前面,2 < 3; start < end, 不能加; 碰见[4,6] start >end; count + 1 比如[4,6] 先出现 start > end, count + 1, 再[2,6] 还是不能加; 还因为两个点的end 都是一样,所以不论谁,如果是end = 3; [4,6], [5,6]都只能加一个 */ class Solution { public: int findLongestChain(vector<vector<int>>& pairs) { sort(pairs.begin(), pairs.end(), [](const vector<int>&a, const vector<int>&b){return a[1]<b[1];}); long end = numeric_limits<long>::min() ; int count = 0; for(auto p: pairs) if(p[0]>end) end = p[1], count++; return count; } }; class Solution { public: int findLongestChain(vector<vector<int>>& pairs) { sort(pairs.begin(), pairs.end(), [](vector<int>&a, vector<int>&b){return a[1] < b[1];}); int count = 0, i = 0, n = pairs.size(); while (i < n) { count++; int curEnd = pairs[i][1]; while (i < n && pairs[i][0] <= curEnd) i++; } return count; } }; class Solution { public: int findLongestChain(vector<vector<int>>& pairs) { if(pairs.size()<=1) return pairs.size(); sort(pairs.begin(),pairs.end(), [](const vector<int> & a, const vector<int>&b){ if(a[1]==b[1]) return a[0]<b[0]; else return a[1]<b[1]; }); int count = 0, end = INT_MIN; for(int i = 0; i<pairs.size();i++){ if(pairs[i][0]>end){ count++; end = pairs[i][1]; } } return count; } }; /* 根据start 来sort */ class Solution { public: int findLongestChain(vector<vector<int>>& pairs) { sort(pairs.begin(), pairs.end()); long end = numeric_limits<long>::min() ; int count = 0; for(auto p: pairs) if(p[0]>end) end = p[1], count++; else end = min(static_cast<long>(p[1]), end); return count; } }; /* #1) sort by end: after sorting we know: s1<e1<e2 and s2<e2 #(in order to make it be easier, we do not consider about "="). #Then s2 has three possible positions. I am giving those three possibilities by "@". : @s1@e1@e2 #Then we have 3 cases. #case 1: s2<s1<e1 @<e2 (replace the first "@"by s2 and remove the rest "@") #s1****e1 #s2*****************************e2 #case 2:s1<s2<e1 <e2 #s1*****************e1 #s2*******************e2 #case 3:s1<e1< s2 <e2 #s1************e1 #s2**************e2 #2) sort by start(similar as sort by end): s1@s2@e2@ #case1: s1 <e1 <s2< e2 #s1******e1 #s2************e2 #case2: s1<s2<e1<e2 #s1***************e1 #s2**********************e2 #case3:s1<s2<e2<e1 #s1************************************e1 #s2********e2 */
29.307018
107
0.451063
[ "vector" ]
aec3bc971293f5497ab36b71a6122ef694b2fafa
8,332
cpp
C++
src/codegen_utils.cpp
Prashant446/GFCC
6feb2e95d2a8e2f2499b2cb4a66921e4b769c822
[ "MIT" ]
1
2021-06-11T03:51:00.000Z
2021-06-11T03:51:00.000Z
src/codegen_utils.cpp
Debarsho/GFCC
0b51d14d8010bc06952984f3554a56d60d3886cb
[ "MIT" ]
null
null
null
src/codegen_utils.cpp
Debarsho/GFCC
0b51d14d8010bc06952984f3554a56d60d3886cb
[ "MIT" ]
1
2021-06-11T03:50:07.000Z
2021-06-11T03:50:07.000Z
#include <vector> #include <ircodes.h> #include <codegen.h> #include <symtab.h> using namespace std; string loadArrAddr(ofstream & f, deltaOpd & Opd, string pos) { /* * pos: 0 for dst (use $a0, $a3) * 1 for src1 (use $a1, $a3) * 2 for src2 (use $a2, $a3) */ if(!Opd.Sym || Opd.Type == 0 ) { // cout << "string loadArrAddr: Called for non-array" << endl; return ""; } // flush all registers in stack string addrReg = "$a" + pos; // store address here if non-constant offset or "->" string symReg = reg2str[Opd.Sym->reg]; // base address of the base symbol bool allConst = true; int constOffset = 0; f << "\t #### <Load address> ###" << endl; bool first = true; if(Opd.Type == 2) { // struct: ".", "->" f << '\t' << "move "<< addrReg + ", " << symReg << endl; for(auto pfx: Opd.PfxOprs) { // cout << pfx.name << endl; if(pfx.type == ".") { if (pfx.symb->offset != 0) f << '\t' << "addu " + addrReg + ", " + addrReg + ", " << to_string(pfx.symb->offset) << " # offset calc" << endl; } else if(pfx.type == ">") { if(!first) // first pointer is by default loaded f << '\t' << "lw " << addrReg << ", " << "("+addrReg+")" << endl; if (pfx.symb->offset != 0) f << '\t' << "addu " + addrReg + ", " + addrReg + ", " << to_string(pfx.symb->offset) << " # offset calc" << endl; } else if (pfx.type == "[]") { // "[]" if(pfx.symb == NULL) { if (pfx.name != "0") f << '\t' << "addu " + addrReg + ", " + addrReg + ", " << pfx.name << " # offset calc" << endl; if(!first && pfx.isPtr) f << '\t' << "lw " << addrReg << ", " << "("+addrReg+")" << endl; } else { if(pfx.symb->reg != zero) f << '\t' << "move $a3, " + reg2str[pfx.symb->reg] << " # load " + pfx.symb->name << endl; else f << '\t' << "lw $a3, -" + to_string(pfx.symb->offset) + "($fp)" << " # load " + pfx.symb->name << endl; f << '\t' << "mul $a3, $a3, " + pfx.name << " # width calc" << endl; f << '\t' << "addu " + addrReg + ", " + addrReg + ", $a3" << " # offset calc" << endl; if(!first && pfx.isPtr) f << '\t' << "lw " << addrReg << ", " << "("+addrReg+")" << endl; } } if(first) first = false; } if(Opd.derefCnt > 0) { for(int i = 0; i< Opd.derefCnt -1 ; i++) f << '\t' << "lw " << addrReg << ", " << "("+addrReg+")" << " # dereference pointer" << endl; } } // Opd.Type == 2 return "("+addrReg+")"; /* for pointer part */ // TODO: pointer return "aa"; } void parseStruct(string & q, deltaOpd & Opd) { sym* st_sym = NULL; Type * st_type = NULL; // count '*' for(int i = 0; i < q.size(); i++) { if(q[i] == '*') { Opd.derefCnt++; } } if(Opd.derefCnt > 0) { Opd.Type = 2; q = q.substr(Opd.derefCnt); st_sym = SymRoot->gLookup(q); if(st_sym) st_type = st_sym->type; else { // cout << "can't find " + q + " in symtab" << endl; } } vector <string> tokens = {".", ">", "["}; int currPos = Find_first_of(q, tokens); if(currPos >= 0) { Opd.Type = 2; // cout <<"Struct parse " << q << endl; string tmp = q.substr(0, currPos); if(q[currPos] == '>')tmp.pop_back(); // cout << "Base: " + tmp << endl; /* search in sym table */ st_sym = SymRoot->gLookup(tmp); if(st_sym) st_type = st_sym->type; else { // cout << "can't find " + tmp + " in symtab" << endl; return; } /* push first symbol */ pfxOpr p; p.name = tmp; p.symb = st_sym; p.type = "---"; // Opd.PfxOprs.push_back(p); vector<int> dimSize; int counter = 0, dimCount = 0, dimWidth = 1; int nxtPos = Find_first_of(q, tokens, currPos+1); while(currPos >= 0){ pfxOpr p; p.type = q[currPos]; // ".", ">", "[" if(p.type == ">" || p.type == ".") { // ".", "->" p.name = q.substr(currPos+1, nxtPos-currPos-1); if(q[nxtPos] == '>') p.name.pop_back(); if(p.type == ">") { // pointer to struct if(!isPtr(st_type)) cout << "-> for non-pointer" << endl; st_type = ((Ptr *) st_type)->pt; } if(!isStruct(st_type)) cout << p.name + " is not an struct" << endl; st_sym = findStructChild(st_type, p.name); st_type = st_sym->type; p.symb = st_sym; } else if(p.type == "[") { // "[]" -- either array or pointer p.type = "[]"; int brkClosePos = q.find_first_of("]", currPos+1); if(brkClosePos == -1) cout << "parseStruct:: Error: can't find ']'" << endl; p.name = q.substr(currPos+1, brkClosePos-currPos-1); p.symb = SymRoot->gLookup(p.name); // NULL if constant nxtPos = Find_first_of(q, tokens, brkClosePos+1); if(dimCount == 0) { // start of array or pointer if(!isArr(st_type) && !isPtr(st_type)) cout << "-> for invalid type" << endl; if(isArr(st_type)) { Arr* a = (Arr *) st_type; st_type = a->item; dimSize = getDimSize(a); dimWidth = getWidth(dimSize); dimCount = dimSize.size(); counter = 1; } else { // element width == dimWidth dimWidth = 1; counter = 0; st_type = ptrChildType(st_type); p.isPtr = true; } } int dimOffs = getSize(st_type) * dimWidth; // dimWidth * elSize if(!p.symb) { // constant offset p.name = to_string(stoi(p.name) * dimOffs); } else p.name = to_string(dimOffs); if(counter == dimCount){ // end multidim array; counter = 0; dimCount = 0; } else { // carry on multi-dim array // get width of nxt dimension dimWidth /= dimSize[counter]; counter++; } } Opd.PfxOprs.push_back(p); // cout << p.type + " " + p.name + " " << counter << endl; //! currPos = nxtPos; nxtPos = Find_first_of(q, tokens, currPos + 1); } q = tmp; Opd.FinalType = st_type; } // currPos >= 0 if(Opd.derefCnt > 0) { if(!st_type) cout << "Can't deref Pointer" << endl; for(int i = 0; i<Opd.derefCnt; i++) st_type = ptrChildType(st_type); Opd.FinalType = st_type; } } void memCopy(std::ofstream &f, reg_t src, reg_t dst, int size) { if(size < 1) return; string srcReg = reg2str[src], dstReg = reg2str[dst], freeReg = "$a3"; string loadInstr[] = {"lw", "ls", "lb"}; string storeInstr[] = {"sw", "ss", "lb"}; f << '\t' << "### <memcopy> size = " + to_string(size) << " from " + reg2str[src] + " to " + reg2str[dst] + " ###"<< endl; int chnkSize = 4, instr = 0, remSize = size; while(remSize > 0) { if(remSize < chnkSize) { chnkSize /= 2; instr++; continue; } /* eg. lw $a3, 20($a0) */ f << '\t' << loadInstr[instr] + " " + freeReg + ", " << to_string(size-remSize) + "(" << srcReg + ")" << endl; /* eg. sw $a3, 20($a1) */ f << '\t' << storeInstr[instr] + " " + freeReg + ", " << to_string(size-remSize) + "(" << dstReg + ")" << endl; remSize -= chnkSize; } } sym* findStructChild(Type* st_type, string chName) { Base * b = (Base *) st_type; for (auto ch: b->subDef->syms) { if(ch->name == chName) return ch; } return NULL; } Type* ptrChildType(Type * t) { if(!isPtr(t)) return NULL; Ptr* p = (Ptr *) clone(t); if(p->ptrs.size()==1) return p->pt; else { p->ptrs.pop_back(); return p; } } vector<int> getDimSize(Arr* a) { vector<int> dimSize; for(auto dim: a->dims) { int * sizePtr = eval(dim); if(!sizePtr) { dimSize.push_back(INT16_MAX); } else dimSize.push_back(*sizePtr); } return dimSize; } int getWidth(vector<int> dimSize) { int width = 1; for(int i = 1; i < dimSize.size(); i++) { width *= dimSize[i]; } // cout << "width " << width << endl; return width; } size_t Find_first_of(string s, vector<string> tokens, size_t pos) { size_t nxtPos = -1; for(auto tok: tokens) { nxtPos = min(nxtPos, s.find_first_of(tok, pos)); } return nxtPos; }
28.930556
95
0.489438
[ "vector" ]
aec6b557e90a645286202135b00ed94c232fc834
986
cpp
C++
smacc/src/smacc/common.cpp
NEU-ZJX/SMACC
cac82a606a5456194e2ca1e404cf9fef66e78e6e
[ "BSD-3-Clause" ]
null
null
null
smacc/src/smacc/common.cpp
NEU-ZJX/SMACC
cac82a606a5456194e2ca1e404cf9fef66e78e6e
[ "BSD-3-Clause" ]
null
null
null
smacc/src/smacc/common.cpp
NEU-ZJX/SMACC
cac82a606a5456194e2ca1e404cf9fef66e78e6e
[ "BSD-3-Clause" ]
1
2020-04-30T00:10:52.000Z
2020-04-30T00:10:52.000Z
/***************************************************************************************************************** * ReelRobotix Inc. - Software License Agreement Copyright (c) 2018 * Authors: Pablo Inigo Blasco, Brett Aldrich * ******************************************************************************************************************/ #include "smacc/common.h" #include "smacc/interface_components/smacc_action_client_base.h" namespace smacc { actionlib::SimpleClientGoalState IActionResult::getResultState() const { return client->getState(); } std::string cleanShortTypeName(const std::type_info& tinfo) { std::string fullclassname = demangleSymbol(tinfo.name()); //ROS_INFO("State full classname: %s", fullclassname.c_str()); std::vector<std::string> strs; boost::split(strs,fullclassname,boost::is_any_of("::")); std::string classname = strs.back(); //ROS_INFO("State classname: %s", classname.c_str()); return classname; } }
35.214286
116
0.546653
[ "vector" ]
aed2f466cc9742aa3607ce505e226be68e5d95c2
3,300
cpp
C++
tools/Vitis-AI-Runtime/VART/vart/dpu-controller/src/dpu_controller_qnx.cpp
hito0512/Vitis-AI
996459fb96cb077ed2f7e789d515893b1cccbc95
[ "Apache-2.0" ]
848
2019-12-03T00:16:17.000Z
2022-03-31T22:53:17.000Z
tools/Vitis-AI-Runtime/VART/vart/dpu-controller/src/dpu_controller_qnx.cpp
wangyifan778/Vitis-AI
f61061eef7550d98bf02a171604c9a9f283a7c47
[ "Apache-2.0" ]
656
2019-12-03T00:48:46.000Z
2022-03-31T18:41:54.000Z
tools/Vitis-AI-Runtime/VART/vart/dpu-controller/src/dpu_controller_qnx.cpp
wangyifan778/Vitis-AI
f61061eef7550d98bf02a171604c9a9f283a7c47
[ "Apache-2.0" ]
506
2019-12-03T00:46:26.000Z
2022-03-30T10:34:56.000Z
/* * Copyright 2019 Xilinx Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "./dpu_controller_qnx.hpp" #include "vitis/ai/xxd.hpp" #include <fcntl.h> #include <glog/logging.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <sys/types.h> #include <vitis/ai/env_config.hpp> #include <vitis/ai/weak.hpp> DEF_ENV_PARAM(DEBUG_DPU_CONTROLLER, "0") namespace { unsigned long DpuControllerQnx::allocate_task_id() { // // it seems that task id is no use. return 1024; } DpuControllerQnx::DpuControllerQnx() : xir::DpuController{}, // dpu_{vitis::ai::QnxDpu::get_instance()}, // task_id_{0} { task_id_ = allocate_task_id(); // task id is not so useful. } DpuControllerQnx::~DpuControllerQnx() { // } void DpuControllerQnx::run(const uint64_t code, const std::vector<uint64_t> &gen_reg, int device_id /*not used*/) { struct ioc_kernel_run2_t ioc_kernel_run2; auto parameter = gen_reg[0]; auto workspace = gen_reg[1]; ioc_kernel_run2.handle_id = 0; ioc_kernel_run2.time_start = 0; ioc_kernel_run2.time_end = 0; ioc_kernel_run2.core_id = 0; // TODO: it support 64 bits register? ioc_kernel_run2.addr_code = code; ioc_kernel_run2.addr0 = parameter; ioc_kernel_run2.addr1 = workspace; ioc_kernel_run2.addr2 = 0x0; // ((uint32_t)code) & 0xFFFFFFFF; ioc_kernel_run2.addr3 = 0x0; ioc_kernel_run2.addr4 = 0x0; ioc_kernel_run2.addr5 = 0x0; ioc_kernel_run2.addr6 = 0x0; ioc_kernel_run2.addr7 = 0x0; LOG_IF(INFO, ENV_PARAM(DEBUG_DPU_CONTROLLER)) << "code " << std::hex << "0x" << code << " " // << "parameter " << std::hex << "0x" << parameter << " " // << "workspace " << std::hex << "0x" << workspace << " " // << std::dec << "dpu_->get_handle() " << dpu_->get_handle() << " " << vitis::ai::xxd((const unsigned char *)&ioc_kernel_run2, sizeof(ioc_kernel_run2), 16, 4); CHECK_EQ(0, qnx_ioctl(dpu_->get_handle(), DPU_IOCTL_RUN2, &ioc_kernel_run2, sizeof(ioc_kernel_run2))) << "dpu timeout?"; return; } static struct Registar { Registar() { auto fd = open("/dev/xdpu/0", O_RDWR); auto disabled = fd < 0; if (!disabled) { xir::DpuController::registar("01_qnx_dpu", []() { return std::shared_ptr<xir::DpuController>( vitis ::ai::WeakSingleton<DpuControllerQnx>::create()); }); LOG_IF(INFO, ENV_PARAM(DEBUG_DPU_CONTROLLER)) << "register the qnx dpu controller"; close(fd); } else { LOG_IF(INFO, ENV_PARAM(DEBUG_DPU_CONTROLLER)) << "cancel register the qnx dpu controller, because " "/dev/xdpu/0 is not opened"; } } } g_registar; } // namespace
33
77
0.642727
[ "vector" ]
aed3f31c929b39f13ebc5eec0db93af959f63f9f
1,010
hpp
C++
Sandbox/src/ParticleSystem.hpp
wexaris/pyre
9f4c1e64a2eeffd11f09ba9396d44c8b7e70f2b4
[ "Apache-2.0" ]
null
null
null
Sandbox/src/ParticleSystem.hpp
wexaris/pyre
9f4c1e64a2eeffd11f09ba9396d44c8b7e70f2b4
[ "Apache-2.0" ]
null
null
null
Sandbox/src/ParticleSystem.hpp
wexaris/pyre
9f4c1e64a2eeffd11f09ba9396d44c8b7e70f2b4
[ "Apache-2.0" ]
null
null
null
#pragma once #include <Pyre/Pyre.hpp> #include <glm/glm.hpp> struct ParticleProps { glm::vec2 Position; glm::vec2 Velocity, VelocityVariation; glm::vec4 ColorBegin, ColorEnd; float SizeBegin, SizeEnd, SizeVariation; float LifeTime = 1.0f; }; class ParticleSystem { public: ParticleSystem(uint32_t maxParticles = 100000); void Tick(float ts); void Draw(Pyre::OrthographicCamera& camera); void Emit(const ParticleProps& particleProps); private: struct Particle { glm::vec2 Position; glm::vec2 Velocity; glm::vec4 ColorBegin, ColorEnd; float Rotation = 0.0f; float SizeBegin, SizeEnd; float LifeTime = 1.0f; float LifeRemaining = 0.0f; bool Active = false; }; std::vector<Particle> m_ParticlePool; uint32_t m_PoolIndex; unsigned int m_QuadVA = 0; std::unique_ptr<Pyre::Shader> m_ParticleShader; int m_ParticleShaderViewProj, m_ParticleShaderTransform, m_ParticleShaderColor; };
24.634146
83
0.680198
[ "vector" ]
aed54674093b158e2b35f7f112452cd0aa205d92
11,033
cc
C++
src/visualisers/SimplePolylineVisualiser.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
41
2018-12-07T23:10:50.000Z
2022-02-19T03:01:49.000Z
src/visualisers/SimplePolylineVisualiser.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
59
2019-01-04T15:43:30.000Z
2022-03-31T09:48:15.000Z
src/visualisers/SimplePolylineVisualiser.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
13
2019-01-07T14:36:33.000Z
2021-09-06T14:48:36.000Z
/* * (C) Copyright 1996-2016 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation nor * does it submit to any jurisdiction. */ /*! \file BoxPlotVisualiser.cc \brief Implementation of the Template class BoxPlotVisualiser. Magics Team - ECMWF 2004 Started: Wed 5-May-2004 Changes: */ #include <limits> #include "SimplePolylineVisualiser.h" #include "Data.h" #include "LegendVisitor.h" #include "PointsHandler.h" #include "Polyline.h" #include "Symbol.h" using namespace magics; SimplePolylineVisualiser::SimplePolylineVisualiser() { map_["classic"] = &SimplePolylineVisualiser::basic; map_["trajectory"] = &SimplePolylineVisualiser::smooth; } SimplePolylineVisualiser::~SimplePolylineVisualiser() {} /*! Class information are given to the output-stream. */ void SimplePolylineVisualiser::print(ostream& out) const { out << "SimplePolylineVisualiser["; out << "]"; } void SimplePolylineVisualiser::basic(Data& data, BasicGraphicsObjectContainer& parent) { levelSelection_->set(*this); PointsHandler& points = data.points(parent.transformation(), true); points.setToFirst(); Polyline* line = 0; levelSelection_->calculate(points.min(), points.max(), false); if (shade_) { colourMethod_->set(*this); colourMethod_->prepare(*levelSelection_, *levelSelection_); } const Transformation& transformation = parent.transformation(); while (points.more()) { if (points.current().missing() || line == 0) { if (line) parent.transformation()(*line, parent); line = new Polyline(); line->setColour(*colour_); line->setLineStyle(style_); line->setThickness(thickness_); line->setFilled(shade_); } if (!points.current().missing()) { line->push_back(transformation(points.current())); if (shade_ && points.current().value() >= min_ && points.current().value() <= max_) { line->setFillColour(colourMethod_->colour(points.current().value())); FillShadingProperties* shading = new FillShadingProperties(); line->setShading(shading); } else line->setFilled(false); } points.advance(); } if (!line) { MagLog::warning() << "Could not find lines to plot " << endl; return; } if (!line->empty()) parent.transformation()(*line, parent); } void SimplePolylineVisualiser::operator()(Data& data, BasicGraphicsObjectContainer& parent) { map<string, Method>::iterator function = map_.find(method_); if (function != map_.end()) (this->*function->second)(data, parent); else { MagLog::warning() << "Could not find method " << method_ << ": Use default visualisation" << endl; basic(data, parent); } } void SimplePolylineVisualiser::setup() { if (colour_list_.empty()) colour_list_.push_back("blue"); if (style_list_.empty()) style_list_.push_back("solid"); if (thickness_list_.empty()) thickness_list_.push_back(2.); vector<string>::iterator colour = colour_list_.begin(); vector<string>::iterator style = style_list_.begin(); vector<double>::iterator thickness = thickness_list_.begin(); MagTranslator<string, LineStyle> translator; int max = colour_level_list_.empty() ? 0 : colour_level_list_.size() - 1; for (int i = 0; i < max; i++) { colour_map_[Interval(colour_level_list_[i], colour_level_list_[i + 1])] = Colour(*colour); ++colour; if (colour == colour_list_.end()) colour = (colour_policy_ == ListPolicy::CYCLE) ? colour_list_.begin() : --colour; } max = style_level_list_.empty() ? 0 : style_level_list_.size() - 1; for (int i = 0; i < max; i++) { style_map_[Interval(style_level_list_[i], style_level_list_[i + 1])] = translator(*style); ++style; if (style == style_list_.end()) style = (style_policy_ == ListPolicy::CYCLE) ? style_list_.begin() : --style; } max = thickness_level_list_.empty() ? 0 : thickness_level_list_.size() - 1; for (int i = 0; i < max; i++) { thickness_map_[Interval(thickness_level_list_[i], thickness_level_list_[i + 1])] = *thickness; ++thickness; if (thickness == thickness_list_.end()) thickness = (thickness_policy_ == ListPolicy::CYCLE) ? thickness_list_.begin() : --thickness; } max = transparency_level_list_.empty() ? 0 : transparency_level_list_.size() - 1; for (int i = 0; i < max; i++) { alpha_map_[Interval(transparency_level_list_[i], transparency_level_list_[i + 1])] = i; } } void SimplePolylineVisualiser::smooth(Data& data, BasicGraphicsObjectContainer& parent) { setup(); if (legend_only_) return; const Transformation& transformation = parent.transformation(); std::set<string> needs; needs.insert(pivot_key_); needs.insert(transparency_key_); needs.insert(colour_key_); needs.insert(style_key_); needs.insert(thickness_key_); double lastone = -std::numeric_limits<double>::max(); CustomisedPointsList points; data.customisedPoints(parent.transformation(), needs, points, true); setup(); map<double, vector<CustomisedPoint*> > work; map<double, vector<CustomisedPoint*> >::iterator where; for (auto& point : points) { double index = priority(*point); if (index > lastone) lastone = index; where = work.find(index); if (where == work.end()) { work.insert(make_pair(index, vector<CustomisedPoint*>())); where = work.find(index); } where->second.push_back(point.get()); } Symbol* marker = new Symbol(); bool add = false; if (pivot_marker_ == "all") add = true; for (map<double, vector<CustomisedPoint*> >::iterator where = work.begin(); where != work.end(); ++where) { for (int i = 1; i < where->second.size(); i++) { CustomisedPoint* last = where->second[i - 1]; CustomisedPoint* point = where->second[i]; if (point->missing() || last->missing()) continue; Polyline segment; segment.setLineStyle(style(*point)); segment.setThickness(thickness(*point)); Colour col = colour(*point); double a = alpha(*last); if (where->first == lastone) { if (pivot_marker_ == "lastone") add = true; if (pivot_marker_ != "none") col = *pivot_marker_colour_; } col.setAlpha(a); segment.setColour(col); UserPoint geo(point->longitude(), point->latitude()); UserPoint lastgeo(last->longitude(), last->latitude()); segment.push_back(transformation(geo)); segment.push_back(transformation(lastgeo)); parent.transformation()(segment, parent); // Add Symbol if needed if (add && alpha(*point) == 1) { CustomisedPoint::const_iterator value = point->find(colour_key_); double x = (value == point->end()) ? 0 : value->second; if (magCompare(pivot_marker_name_, "cyclone")) { string name; if (point->latitude() > 0) { name = (x < 117) ? "WMO_TropicalCycloneNHLT" : "WMO_TropicalCycloneNHGE"; } else { name = (x < 117) ? "WMO_TropicalCycloneSHLT" : "WMO_TropicalCycloneSHGE"; } marker->setSymbol(name); } else { marker->setSymbol(pivot_marker_name_); } marker->setHeight(pivot_marker_height_); marker->setColour(*pivot_marker_colour_); marker->push_back(transformation(geo)); } } } parent.push_back(marker); } void SimplePolylineVisualiser::visit(Data&, LegendVisitor& legend) { if (!legend_) return; if (shade_) colourMethod_->visit(legend); legend.newLegend(); if (colour_map_.empty()) { // no legend to plot return; } IntervalMap<Colour>::const_iterator interval; for (interval = colour_map_.begin(); interval != colour_map_.end(); ++interval) { Polyline* box = new Polyline(); double min = interval->first.min_; double max = interval->first.max_; box->setShading(new FillShadingProperties()); box->setFillColour(interval->second); box->setFilled(true); legend.add(new BoxEntry(min, max, box)); } legend.back()->last(); } Colour SimplePolylineVisualiser::colour(const CustomisedPoint& point) { Colour blue("blue"); CustomisedPoint::const_iterator value = point.find(colour_key_); if (value == point.end()) return blue; return colour_map_.find(value->second, blue); } LineStyle SimplePolylineVisualiser::style(const CustomisedPoint& point) { LineStyle solid = LineStyle::SOLID; CustomisedPoint::const_iterator value = point.find(style_key_); if (value == point.end()) return solid; return style_map_.find(value->second, solid); } double SimplePolylineVisualiser::thickness(const CustomisedPoint& point) { double thickness = (thickness_list_.size()) ? thickness_list_.front() : 4; CustomisedPoint::const_iterator value = point.find(thickness_key_); if (value == point.end()) return thickness; return thickness_map_.find(value->second, thickness); } double SimplePolylineVisualiser::priority(const CustomisedPoint& point) { double priority = 1; CustomisedPoint::const_iterator value = point.find(priority_key_); if (value == point.end()) return priority; return value->second; } double SimplePolylineVisualiser::alpha(const CustomisedPoint& point) { double alpha = 1; CustomisedPoint::const_iterator p = point.find(pivot_key_); if (p == point.end()) return alpha; int pivot = alpha_map_.find(p->second, -1); if (pivot == -1) return alpha; CustomisedPoint::const_iterator value = point.find(transparency_key_); if (value == point.end()) return alpha; int index = alpha_map_.find(value->second, -1); alpha = exp(-(abs(float(index - pivot)) / factor_)); return alpha; } void SimplePolylineVisualiser::visit(LegendVisitor& legend) {}
33.032934
111
0.607632
[ "vector", "solid" ]
aed6371deede16cb82e4a2b42e3f61799226a4b1
614
cpp
C++
Hard/Weekly Contest 20/526. Beautiful Arrangement/backtrack.cpp
yzhang37/LeetCode_Weekly_Contest
d46f8498f749ee7d53b5703bd1e3e2bbc5d44bf6
[ "MIT" ]
1
2017-02-19T07:46:23.000Z
2017-02-19T07:46:23.000Z
Hard/Weekly Contest 20/526. Beautiful Arrangement/backtrack.cpp
yzhang37/LeetCode_Weekly_Contest
d46f8498f749ee7d53b5703bd1e3e2bbc5d44bf6
[ "MIT" ]
null
null
null
Hard/Weekly Contest 20/526. Beautiful Arrangement/backtrack.cpp
yzhang37/LeetCode_Weekly_Contest
d46f8498f749ee7d53b5703bd1e3e2bbc5d44bf6
[ "MIT" ]
null
null
null
class Solution { public: int countArrangement(int N) { vector <int> vs; for (int i = 1; i <= N; ++i) vs.push_back(i); return counts(N, vs); } private: int counts(int n, vector<int> &vs) { if (n <= 0) return 1; int ans = 0; for (int i = 0; i < n; ++i) { //题目中的两种要求 if (vs[i] % n == 0 || n % vs[i] == 0) { swap(vs[i], vs[n - 1]); ans += counts(n - 1, vs); swap(vs[i], vs[n - 1]); } } return ans; } };
21.928571
49
0.350163
[ "vector" ]
aedd1310a5b4e701e857e7dc3594a469df13c782
574
cpp
C++
solutions/12XX/1278/1278B.cpp
AlexanderFadeev/codeforces
9e70a58e69fafe96604045e1e9ce1d3dab07e1e5
[ "MIT" ]
null
null
null
solutions/12XX/1278/1278B.cpp
AlexanderFadeev/codeforces
9e70a58e69fafe96604045e1e9ce1d3dab07e1e5
[ "MIT" ]
null
null
null
solutions/12XX/1278/1278B.cpp
AlexanderFadeev/codeforces
9e70a58e69fafe96604045e1e9ce1d3dab07e1e5
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> #include <string> using namespace std; void run() { int a, b; cin >> a >> b; int ans = 0; while (a != b) { if (a > b) { int c = a; a = b; b = c; } int d = b - a; if (d >= 2) { a += d / 2 * 2; ans += d / 2; } else { a += 1; ans += 1; } } cout << ans << endl; } int main() { // int t = 1; int t; cin >> t; while (t--) { run(); } }
14.35
27
0.325784
[ "vector" ]
aee50131a448d27495bba5379be20328403376f0
8,875
cpp
C++
LambdaEngine/Source/Debug/CPUProfiler.cpp
IbexOmega/CrazyCanvas
f60f01aaf9c988e4da8990dc1ef3caac20cecf7e
[ "MIT" ]
18
2020-09-04T08:00:54.000Z
2021-08-29T23:04:45.000Z
LambdaEngine/Source/Debug/CPUProfiler.cpp
IbexOmega/LambdaEngine
f60f01aaf9c988e4da8990dc1ef3caac20cecf7e
[ "MIT" ]
32
2020-09-12T19:24:50.000Z
2020-12-11T14:29:44.000Z
LambdaEngine/Source/Debug/CPUProfiler.cpp
IbexOmega/LambdaEngine
f60f01aaf9c988e4da8990dc1ef3caac20cecf7e
[ "MIT" ]
2
2020-12-15T15:36:13.000Z
2021-03-27T14:27:02.000Z
#include "PreCompiled.h" #include "Debug/CPUProfiler.h" #include "Input/API/Input.h" #include "Application/API/CommonApplication.h" #include "Engine/EngineLoop.h" #include <imgui.h> // Code modifed from: https://github.com/TheCherno/Hazel /* InstrumentationTimer class */ namespace LambdaEngine { InstrumentationTimer::InstrumentationTimer(const std::string& name, bool active) : m_Name(name), m_Active(active) { Start(); } InstrumentationTimer::~InstrumentationTimer() { Stop(); } void InstrumentationTimer::Start() { if (m_Active) m_StartTime = std::chrono::time_point_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now()).time_since_epoch().count(); } void InstrumentationTimer::Stop() { if (m_Active) { long long start = m_StartTime; long long end = std::chrono::time_point_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now()).time_since_epoch().count(); size_t tid = std::hash<std::thread::id>{}(std::this_thread::get_id()); CPUProfiler::Get()->Write({ m_Name, (uint64_t)start, (uint64_t)end, tid }); } } /* Instrumentation class */ bool CPUProfiler::g_RunProfilingSample = false; CPUProfiler::CPUProfiler() : m_Counter(0) { m_ProfilingTicks[0].Reset(); m_ProfilingTicks[1].Reset(); } CPUProfiler::~CPUProfiler() { } CPUProfiler* CPUProfiler::Get() { static CPUProfiler cpuProfiler; return &cpuProfiler; } void LambdaEngine::CPUProfiler::BeginProfilingSegment(const String& name) { std::scoped_lock<SpinLock> lock(m_ProfilingSegmentSpinlock); ProfilingTick& currentProfilingTick = m_ProfilingTicks[m_CurrentProfilingTick]; if (auto profilingSegmentIt = currentProfilingTick.ProfilingSegmentsMap.find(name); profilingSegmentIt != currentProfilingTick.ProfilingSegmentsMap.end()) { currentProfilingTick.ProfilingSegmentStack.PushBack(profilingSegmentIt->second); } else { uint32 profilingSegmentIndex = currentProfilingTick.LiveProfilingSegments.GetSize(); currentProfilingTick.ProfilingSegmentsMap[name] = profilingSegmentIndex; Clock clock; clock.Reset(); currentProfilingTick.LiveProfilingSegments.PushBack(LiveProfilingSegment{ .Clock = clock }); currentProfilingTick.ProfilingSegmentStack.PushBack(profilingSegmentIndex); } } void LambdaEngine::CPUProfiler::EndProfilingSegment(const String& name) { std::scoped_lock<SpinLock> lock(m_ProfilingSegmentSpinlock); ProfilingTick& currentProfilingTick = m_ProfilingTicks[m_CurrentProfilingTick]; if (auto profilingSegmentIt = currentProfilingTick.ProfilingSegmentsMap.find(name); profilingSegmentIt != currentProfilingTick.ProfilingSegmentsMap.end()) { LiveProfilingSegment& liveProfilingSegment = currentProfilingTick.LiveProfilingSegments[profilingSegmentIt->second]; Clock& clock = liveProfilingSegment.Clock; clock.Tick(); float64 deltaTime = clock.GetDeltaTime().AsMilliSeconds(); FinishedProfilingSegment finishedProfilingSegment { .Name = name, .DeltaTime = deltaTime, .ChildProfilingSegments = liveProfilingSegment.ChildProfilingSegments }; VALIDATE(profilingSegmentIt->second == currentProfilingTick.ProfilingSegmentStack.GetBack()); currentProfilingTick.ProfilingSegmentStack.PopBack(); if (!currentProfilingTick.ProfilingSegmentStack.IsEmpty()) { LiveProfilingSegment& liveParentProfilingSegment = currentProfilingTick.LiveProfilingSegments[currentProfilingTick.ProfilingSegmentStack.GetBack()]; liveParentProfilingSegment.ChildProfilingSegments.insert(finishedProfilingSegment); } else { currentProfilingTick.FinishedProfilingSegments.insert(finishedProfilingSegment); currentProfilingTick.TotalDeltaTime += deltaTime; } } else { LOG_ERROR("Profiling Segment with name %s ended but never begun", name.c_str()); } } void CPUProfiler::BeginSession(const std::string& name, const std::string& filePath) { UNREFERENCED_VARIABLE(name); m_Counter = 0; m_File.open(filePath); m_File << "{\"otherData\": {}, \"displayTimeUnit\": \"ms\", \"traceEvents\": ["; m_File.flush(); } void CPUProfiler::Write(ProfileData data) { if (data.PID == 0) { data.Start -= m_StartTime; data.End -= m_StartTime; } std::lock_guard<std::mutex> lock(m_Mutex); if (m_Counter++ > 0) m_File << ","; std::string name = data.Name; std::replace(name.begin(), name.end(), '"', '\''); m_File << "\n{"; m_File << "\"name\": \"" << name << "\","; m_File << "\"cat\": \"function\","; m_File << "\"ph\": \"X\","; m_File << "\"pid\": " << data.PID << ","; m_File << "\"tid\": " << data.TID << ","; m_File << "\"ts\": " << data.Start << ","; m_File << "\"dur\": " << (data.End - data.Start); m_File << "}"; m_File.flush(); } void CPUProfiler::SetStartTime(uint64_t time) { m_StartTime = time; } void CPUProfiler::ToggleSample(EKey key, uint32_t frameCount) { static uint32_t frameCounter = 0; if (Input::GetKeyboardState(EInputLayer::GAME).IsKeyDown(key)) { frameCounter = 0; CPUProfiler::g_RunProfilingSample = true; LOG_DEBUG("Start Profiling"); } if (CPUProfiler::g_RunProfilingSample) { frameCounter++; if (frameCounter > frameCount) { CPUProfiler::g_RunProfilingSample = false; LOG_DEBUG("End Profiling"); } } } void CPUProfiler::EndSession() { m_File << "]" << std::endl << "}"; m_File.close(); } void CPUProfiler::Tick(Timestamp delta) { m_PreviousProfilingTick = m_CurrentProfilingTick; m_CurrentProfilingTick++; if (m_CurrentProfilingTick >= ARR_SIZE(m_ProfilingTicks)) m_CurrentProfilingTick = 0; m_ProfilingTicks[m_CurrentProfilingTick].Reset(); m_TimeSinceUpdate += delta.AsSeconds(); m_Timestamp = delta; } void CPUProfiler::Render() { std::scoped_lock<SpinLock> lock(m_ProfilingSegmentSpinlock); if (m_TimeSinceUpdate > 1 / m_UpdateFrequency) { CommonApplication::Get()->GetPlatformApplication()->QueryCPUStatistics(&m_CPUStat); m_TimeSinceUpdate = 0.f; } ImGui::BulletText("FPS: %f", 1.0f / m_Timestamp.AsSeconds()); ImGui::BulletText("Frametime (ms): %f", m_Timestamp.AsMilliSeconds()); // Spacing ImGui::Dummy(ImVec2(0.0f, 20.0f)); if (ImGui::CollapsingHeader("CPU Statistics", ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::Indent(10.0f); static const char* items[] = { "B", "KB", "MB", "GB" }; static int itemSelected = 2; static float byteDivider = 1; ImGui::Combo("Memory suffix CPU", &itemSelected, items, 4, 4); if (itemSelected == 0) { byteDivider = 1.f; } if (itemSelected == 1) { byteDivider = 1024.f; } if (itemSelected == 2) { byteDivider = 1024.f * 1024.f; } if (itemSelected == 3) { byteDivider = 1024.f * 1024.f * 1024.f; } ImGui::SliderFloat("Update frequency (per second)", &m_UpdateFrequency, 0.1f, 20.0f, "%.2f"); float32 percentage = (float32)(m_CPUStat.PhysicalMemoryUsage / (float32)m_CPUStat.PhysicalMemoryAvailable); char buf[64]; sprintf(buf, "%.3f/%.3f (%s)", (float64)m_CPUStat.PhysicalMemoryUsage / byteDivider, (float64)m_CPUStat.PhysicalMemoryAvailable / byteDivider, items[itemSelected]); ImGui::Text("Memory usage for process"); ImGui::ProgressBar(percentage, ImVec2(-1.0f, 0.0f), buf); ImGui::Text("Peak memory usage: %.3f (%s)", m_CPUStat.PhysicalPeakMemoryUsage / byteDivider, items[itemSelected]); ImGui::Text("CPU Usage for process"); sprintf(buf, "%.3f%%", m_CPUStat.CPUPercentage); ImGui::ProgressBar((float)m_CPUStat.CPUPercentage / 100.f, ImVec2(-1.0f, 0.0f), buf); ImGui::NewLine(); ProfilingTick& profilingTick = m_ProfilingTicks[m_PreviousProfilingTick]; ImGui::Text("Profiling Segments - Total Profile Time %fms", profilingTick.TotalDeltaTime); for (auto profilingTickIt = profilingTick.FinishedProfilingSegments.rbegin(); profilingTickIt != profilingTick.FinishedProfilingSegments.rend(); profilingTickIt++) { RenderFinishedProfilingSegment(*profilingTickIt, profilingTick.TotalDeltaTime); } ImGui::Dummy(ImVec2(0.0f, 20.0f)); ImGui::Unindent(10.0f); } } void LambdaEngine::CPUProfiler::RenderFinishedProfilingSegment(const FinishedProfilingSegment& profilingSegment, float64 parentDeltaTime) { constexpr const float32 indent = 25.0f; ImGui::Indent(indent); glm::vec3 color = glm::lerp<glm::vec3>(glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(1.0f, 0.0f, 0.0f), glm::vec3(float32(profilingSegment.DeltaTime / parentDeltaTime))); ImGui::TextColored(ImVec4(color.x, color.y, color.z, 1.0f), "%s: %fms", profilingSegment.Name.c_str(), profilingSegment.DeltaTime); for (auto profilingTickIt = profilingSegment.ChildProfilingSegments.rbegin(); profilingTickIt != profilingSegment.ChildProfilingSegments.rend(); profilingTickIt++) { RenderFinishedProfilingSegment(*profilingTickIt, profilingSegment.DeltaTime); } ImGui::Unindent(indent); } }
31.58363
167
0.717859
[ "render" ]
aee5e2dadffa192fc88b3e63f1283cbd0a47cf9e
46,005
cpp
C++
source/compute_engine/cuda/cuda_engine.cpp
Knutakir/KTT
502a8588710e20adeff0a1c27b196aee2c206697
[ "MIT" ]
null
null
null
source/compute_engine/cuda/cuda_engine.cpp
Knutakir/KTT
502a8588710e20adeff0a1c27b196aee2c206697
[ "MIT" ]
null
null
null
source/compute_engine/cuda/cuda_engine.cpp
Knutakir/KTT
502a8588710e20adeff0a1c27b196aee2c206697
[ "MIT" ]
null
null
null
#ifdef KTT_PLATFORM_CUDA #include <stdexcept> #include <compute_engine/cuda/cuda_engine.h> #include <utility/ktt_utility.h> #include <utility/logger.h> #include <utility/timer.h> #ifdef KTT_PROFILING_CUPTI_LEGACY #include <compute_engine/cuda/cupti_legacy/cupti_profiling_subscription.h> #elif KTT_PROFILING_CUPTI #include <compute_engine/cuda/cupti/cupti_profiling_pass.h> #endif // KTT_PROFILING_CUPTI namespace ktt { CUDAEngine::CUDAEngine(const DeviceIndex deviceIndex, const uint32_t queueCount) : deviceIndex(deviceIndex), compilerOptions(std::string("--gpu-architecture=compute_30")), globalSizeType(GlobalSizeType::CUDA), globalSizeCorrection(false), kernelCacheFlag(true), kernelCacheCapacity(10), persistentBufferFlag(true), nextEventId(0) { Logger::logDebug("Initializing CUDA runtime"); checkCUDAError(cuInit(0), "cuInit"); auto devices = getCUDADevices(); if (deviceIndex >= devices.size()) { throw std::runtime_error(std::string("Invalid device index: ") + std::to_string(deviceIndex)); } Logger::logDebug("Initializing CUDA context"); context = std::make_unique<CUDAContext>(devices.at(deviceIndex).getDevice()); Logger::logDebug("Initializing CUDA streams"); for (uint32_t i = 0; i < queueCount; i++) { auto stream = std::make_unique<CUDAStream>(i, context->getContext(), devices.at(deviceIndex).getDevice()); streams.push_back(std::move(stream)); } #ifdef KTT_PROFILING_CUPTI_LEGACY Logger::logDebug("Initializing CUPTI profiling metric IDs"); const std::vector<std::string>& metricNames = getDefaultProfilingMetricNames(); profilingMetrics = getProfilingMetricsForCurrentDevice(metricNames); #elif KTT_PROFILING_CUPTI Logger::logDebug("Initializing CUPTI profiler"); profiler = std::make_unique<CUPTIProfiler>(); const std::string deviceName = profiler->getDeviceName(deviceIndex); metricInterface = std::make_unique<CUPTIMetricInterface>(deviceName); profilingCounters = getDefaultProfilingCounters(); #endif // KTT_PROFILING_CUPTI } KernelResult CUDAEngine::runKernel(const KernelRuntimeData& kernelData, const std::vector<KernelArgument*>& argumentPointers, const std::vector<OutputDescriptor>& outputDescriptors) { EventId eventId = runKernelAsync(kernelData, argumentPointers, getDefaultQueue()); KernelResult result = getKernelResult(eventId, outputDescriptors); return result; } EventId CUDAEngine::runKernelAsync(const KernelRuntimeData& kernelData, const std::vector<KernelArgument*>& argumentPointers, const QueueId queue) { Timer overheadTimer; overheadTimer.start(); CUDAKernel* kernel; std::unique_ptr<CUDAKernel> kernelUnique; if (kernelCacheFlag) { if (kernelCache.find(std::make_pair(kernelData.getName(), kernelData.getSource())) == kernelCache.end()) { if (kernelCache.size() >= kernelCacheCapacity) { clearKernelCache(); } std::unique_ptr<CUDAProgram> program = createAndBuildProgram(kernelData.getSource()); auto kernel = std::make_unique<CUDAKernel>(program->getPtxSource(), kernelData.getName()); kernelCache.insert(std::make_pair(std::make_pair(kernelData.getName(), kernelData.getSource()), std::move(kernel))); } auto cachePointer = kernelCache.find(std::make_pair(kernelData.getName(), kernelData.getSource())); kernel = cachePointer->second.get(); } else { std::unique_ptr<CUDAProgram> program = createAndBuildProgram(kernelData.getSource()); kernelUnique = std::make_unique<CUDAKernel>(program->getPtxSource(), kernelData.getName()); kernel = kernelUnique.get(); } std::vector<CUdeviceptr*> kernelArguments = getKernelArguments(argumentPointers); overheadTimer.stop(); return enqueueKernel(*kernel, kernelData.getGlobalSize(), kernelData.getLocalSize(), kernelArguments, getSharedMemorySizeInBytes(argumentPointers, kernelData.getLocalMemoryModifiers()), queue, overheadTimer.getElapsedTime()); } KernelResult CUDAEngine::getKernelResult(const EventId id, const std::vector<OutputDescriptor>& outputDescriptors) const { KernelResult result = createKernelResult(id); for (const auto& descriptor : outputDescriptors) { downloadArgument(descriptor.getArgumentId(), descriptor.getOutputDestination(), descriptor.getOutputSizeInBytes()); } return result; } uint64_t CUDAEngine::getKernelOverhead(const EventId id) const { auto eventPointer = kernelEvents.find(id); if (eventPointer == kernelEvents.end()) { throw std::runtime_error(std::string("Kernel event with following id does not exist or its result was already retrieved: ") + std::to_string(id)); } return eventPointer->second.first->getOverhead(); } void CUDAEngine::setCompilerOptions(const std::string& options) { compilerOptions = options; } void CUDAEngine::setGlobalSizeType(const GlobalSizeType type) { globalSizeType = type; } void CUDAEngine::setAutomaticGlobalSizeCorrection(const bool flag) { globalSizeCorrection = flag; } void CUDAEngine::setKernelCacheUsage(const bool flag) { if (!flag) { clearKernelCache(); } kernelCacheFlag = flag; } void CUDAEngine::setKernelCacheCapacity(const size_t capacity) { kernelCacheCapacity = capacity; } void CUDAEngine::clearKernelCache() { kernelCache.clear(); } QueueId CUDAEngine::getDefaultQueue() const { return 0; } std::vector<QueueId> CUDAEngine::getAllQueues() const { std::vector<QueueId> result; for (size_t i = 0; i < streams.size(); i++) { result.push_back(static_cast<QueueId>(i)); } return result; } void CUDAEngine::synchronizeQueue(const QueueId queue) { if (queue >= streams.size()) { throw std::runtime_error(std::string("Invalid stream index: ") + std::to_string(queue)); } checkCUDAError(cuStreamSynchronize(streams.at(queue)->getStream()), "cuStreamSynchronize"); } void CUDAEngine::synchronizeDevice() { for (auto& stream : streams) { checkCUDAError(cuStreamSynchronize(stream->getStream()), "cuStreamSynchronize"); } } void CUDAEngine::clearEvents() { kernelEvents.clear(); bufferEvents.clear(); #ifdef KTT_PROFILING_CUPTI_LEGACY kernelToEventMap.clear(); kernelProfilingInstances.clear(); #elif KTT_PROFILING_CUPTI kernelToEventMap.clear(); kernelProfilingInstances.clear(); #endif // KTT_PROFILING_CUPTI } uint64_t CUDAEngine::uploadArgument(KernelArgument& kernelArgument) { if (kernelArgument.getUploadType() != ArgumentUploadType::Vector) { return 0; } EventId eventId = uploadArgumentAsync(kernelArgument, getDefaultQueue()); return getArgumentOperationDuration(eventId); } EventId CUDAEngine::uploadArgumentAsync(KernelArgument& kernelArgument, const QueueId queue) { if (queue >= streams.size()) { throw std::runtime_error(std::string("Invalid stream index: ") + std::to_string(queue)); } if (findBuffer(kernelArgument.getId()) != nullptr) { throw std::runtime_error(std::string("Buffer with following id already exists: ") + std::to_string(kernelArgument.getId())); } if (kernelArgument.getUploadType() != ArgumentUploadType::Vector) { return UINT64_MAX; } std::unique_ptr<CUDABuffer> buffer = nullptr; EventId eventId = nextEventId; Logger::getLogger().log(LoggingLevel::Debug, "Uploading buffer for argument " + std::to_string(kernelArgument.getId()) + ", event id: " + std::to_string(eventId)); if (kernelArgument.getMemoryLocation() == ArgumentMemoryLocation::HostZeroCopy) { buffer = std::make_unique<CUDABuffer>(kernelArgument, true); bufferEvents.insert(std::make_pair(eventId, std::make_pair(std::make_unique<CUDAEvent>(eventId, false), std::make_unique<CUDAEvent>(eventId, false)))); } else { buffer = std::make_unique<CUDABuffer>(kernelArgument, false); auto startEvent = std::make_unique<CUDAEvent>(eventId, true); auto endEvent = std::make_unique<CUDAEvent>(eventId, true); buffer->uploadData(streams.at(queue)->getStream(), kernelArgument.getData(), kernelArgument.getDataSizeInBytes(), startEvent->getEvent(), endEvent->getEvent()); bufferEvents.insert(std::make_pair(eventId, std::make_pair(std::move(startEvent), std::move(endEvent)))); } buffers.insert(std::move(buffer)); // buffer data will be stolen nextEventId++; return eventId; } uint64_t CUDAEngine::updateArgument(const ArgumentId id, const void* data, const size_t dataSizeInBytes) { EventId eventId = updateArgumentAsync(id, data, dataSizeInBytes, getDefaultQueue()); return getArgumentOperationDuration(eventId); } EventId CUDAEngine::updateArgumentAsync(const ArgumentId id, const void* data, const size_t dataSizeInBytes, const QueueId queue) { if (queue >= streams.size()) { throw std::runtime_error(std::string("Invalid stream index: ") + std::to_string(queue)); } CUDABuffer* buffer = findBuffer(id); if (buffer == nullptr) { throw std::runtime_error(std::string("Buffer with following id was not found: ") + std::to_string(id)); } EventId eventId = nextEventId; auto startEvent = std::make_unique<CUDAEvent>(eventId, true); auto endEvent = std::make_unique<CUDAEvent>(eventId, true); Logger::getLogger().log(LoggingLevel::Debug, "Updating buffer for argument " + std::to_string(id) + ", event id: " + std::to_string(eventId)); if (dataSizeInBytes == 0) { buffer->uploadData(streams.at(queue)->getStream(), data, buffer->getBufferSize(), startEvent->getEvent(), endEvent->getEvent()); } else { buffer->uploadData(streams.at(queue)->getStream(), data, dataSizeInBytes, startEvent->getEvent(), endEvent->getEvent()); } bufferEvents.insert(std::make_pair(eventId, std::make_pair(std::move(startEvent), std::move(endEvent)))); nextEventId++; return eventId; } uint64_t CUDAEngine::downloadArgument(const ArgumentId id, void* destination, const size_t dataSizeInBytes) const { EventId eventId = downloadArgumentAsync(id, destination, dataSizeInBytes, getDefaultQueue()); return getArgumentOperationDuration(eventId); } EventId CUDAEngine::downloadArgumentAsync(const ArgumentId id, void* destination, const size_t dataSizeInBytes, const QueueId queue) const { if (queue >= streams.size()) { throw std::runtime_error(std::string("Invalid stream index: ") + std::to_string(queue)); } CUDABuffer* buffer = findBuffer(id); if (buffer == nullptr) { throw std::runtime_error(std::string("Buffer with following id was not found: ") + std::to_string(id)); } EventId eventId = nextEventId; auto startEvent = std::make_unique<CUDAEvent>(eventId, true); auto endEvent = std::make_unique<CUDAEvent>(eventId, true); Logger::getLogger().log(LoggingLevel::Debug, "Downloading buffer for argument " + std::to_string(id) + ", event id: " + std::to_string(eventId)); if (dataSizeInBytes == 0) { buffer->downloadData(streams.at(queue)->getStream(), destination, buffer->getBufferSize(), startEvent->getEvent(), endEvent->getEvent()); } else { buffer->downloadData(streams.at(queue)->getStream(), destination, dataSizeInBytes, startEvent->getEvent(), endEvent->getEvent()); } bufferEvents.insert(std::make_pair(eventId, std::make_pair(std::move(startEvent), std::move(endEvent)))); nextEventId++; return eventId; } KernelArgument CUDAEngine::downloadArgumentObject(const ArgumentId id, uint64_t* downloadDuration) const { CUDABuffer* buffer = findBuffer(id); if (buffer == nullptr) { throw std::runtime_error(std::string("Buffer with following id was not found: ") + std::to_string(id)); } KernelArgument argument(buffer->getKernelArgumentId(), buffer->getBufferSize() / buffer->getElementSize(), buffer->getElementSize(), buffer->getDataType(), buffer->getMemoryLocation(), buffer->getAccessType(), ArgumentUploadType::Vector); EventId eventId = nextEventId; auto startEvent = std::make_unique<CUDAEvent>(eventId, true); auto endEvent = std::make_unique<CUDAEvent>(eventId, true); Logger::getLogger().log(LoggingLevel::Debug, "Downloading buffer for argument " + std::to_string(id) + ", event id: " + std::to_string(eventId)); buffer->downloadData(streams.at(getDefaultQueue())->getStream(), argument.getData(), argument.getDataSizeInBytes(), startEvent->getEvent(), endEvent->getEvent()); bufferEvents.insert(std::make_pair(eventId, std::make_pair(std::move(startEvent), std::move(endEvent)))); nextEventId++; uint64_t duration = getArgumentOperationDuration(eventId); if (downloadDuration != nullptr) { *downloadDuration = duration; } return argument; } uint64_t CUDAEngine::copyArgument(const ArgumentId destination, const ArgumentId source, const size_t dataSizeInBytes) { EventId eventId = copyArgumentAsync(destination, source, dataSizeInBytes, getDefaultQueue()); return getArgumentOperationDuration(eventId); } EventId CUDAEngine::copyArgumentAsync(const ArgumentId destination, const ArgumentId source, const size_t dataSizeInBytes, const QueueId queue) { if (queue >= streams.size()) { throw std::runtime_error(std::string("Invalid stream index: ") + std::to_string(queue)); } CUDABuffer* destinationBuffer = findBuffer(destination); CUDABuffer* sourceBuffer = findBuffer(source); if (destinationBuffer == nullptr || sourceBuffer == nullptr) { throw std::runtime_error(std::string("One of the buffers with following ids does not exist: ") + std::to_string(destination) + ", " + std::to_string(source)); } if (sourceBuffer->getDataType() != destinationBuffer->getDataType()) { throw std::runtime_error("Data type for buffers during copying operation must match"); } EventId eventId = nextEventId; auto startEvent = std::make_unique<CUDAEvent>(eventId, true); auto endEvent = std::make_unique<CUDAEvent>(eventId, true); Logger::getLogger().log(LoggingLevel::Debug, "Copying buffer for argument " + std::to_string(source) + " into buffer for argument " + std::to_string(destination) + ", event id: " + std::to_string(eventId)); if (dataSizeInBytes == 0) { destinationBuffer->uploadData(streams.at(queue)->getStream(), sourceBuffer, sourceBuffer->getBufferSize(), startEvent->getEvent(), endEvent->getEvent()); } else { destinationBuffer->uploadData(streams.at(queue)->getStream(), sourceBuffer, dataSizeInBytes, startEvent->getEvent(), endEvent->getEvent()); } bufferEvents.insert(std::make_pair(eventId, std::make_pair(std::move(startEvent), std::move(endEvent)))); nextEventId++; return eventId; } uint64_t CUDAEngine::persistArgument(KernelArgument& kernelArgument, const bool flag) { bool bufferFound = false; auto iterator = persistentBuffers.cbegin(); while (iterator != persistentBuffers.cend()) { if (iterator->get()->getKernelArgumentId() == kernelArgument.getId()) { bufferFound = true; if (!flag) { persistentBuffers.erase(iterator); } break; } else { ++iterator; } } if (flag && !bufferFound) { std::unique_ptr<CUDABuffer> buffer = nullptr; EventId eventId = nextEventId; Logger::getLogger().log(LoggingLevel::Debug, "Uploading persistent buffer for argument " + std::to_string(kernelArgument.getId()) + ", event id: " + std::to_string(eventId)); if (kernelArgument.getMemoryLocation() == ArgumentMemoryLocation::HostZeroCopy) { buffer = std::make_unique<CUDABuffer>(kernelArgument, true); bufferEvents.insert(std::make_pair(eventId, std::make_pair(std::make_unique<CUDAEvent>(eventId, false), std::make_unique<CUDAEvent>(eventId, false)))); } else { buffer = std::make_unique<CUDABuffer>(kernelArgument, false); auto startEvent = std::make_unique<CUDAEvent>(eventId, true); auto endEvent = std::make_unique<CUDAEvent>(eventId, true); buffer->uploadData(streams.at(getDefaultQueue())->getStream(), kernelArgument.getData(), kernelArgument.getDataSizeInBytes(), startEvent->getEvent(), endEvent->getEvent()); bufferEvents.insert(std::make_pair(eventId, std::make_pair(std::move(startEvent), std::move(endEvent)))); } persistentBuffers.insert(std::move(buffer)); // buffer data will be stolen nextEventId++; return getArgumentOperationDuration(eventId); } return 0; } uint64_t CUDAEngine::getArgumentOperationDuration(const EventId id) const { auto eventPointer = bufferEvents.find(id); if (eventPointer == bufferEvents.end()) { throw std::runtime_error(std::string("Buffer event with following id does not exist or its result was already retrieved: ") + std::to_string(id)); } if (!eventPointer->second.first->isValid()) { bufferEvents.erase(id); return 0; } Logger::getLogger().log(LoggingLevel::Debug, "Performing buffer operation synchronization for event id: " + std::to_string(id)); // Wait until the second event in pair (the end event) finishes checkCUDAError(cuEventSynchronize(eventPointer->second.second->getEvent()), "cuEventSynchronize"); float duration = getEventCommandDuration(eventPointer->second.first->getEvent(), eventPointer->second.second->getEvent()); bufferEvents.erase(id); return static_cast<uint64_t>(duration); } void CUDAEngine::resizeArgument(const ArgumentId id, const size_t newSize, const bool preserveData) { CUDABuffer* buffer = findBuffer(id); if (buffer == nullptr) { throw std::runtime_error(std::string("Buffer with following id was not found: ") + std::to_string(id)); } Logger::getLogger().log(LoggingLevel::Debug, "Resizing buffer for argument " + std::to_string(id)); buffer->resize(newSize, preserveData); } void CUDAEngine::clearBuffer(const ArgumentId id) { auto iterator = buffers.cbegin(); while (iterator != buffers.cend()) { if (iterator->get()->getKernelArgumentId() == id) { buffers.erase(iterator); return; } else { ++iterator; } } } void CUDAEngine::setPersistentBufferUsage(const bool flag) { persistentBufferFlag = flag; } void CUDAEngine::clearBuffers() { buffers.clear(); } void CUDAEngine::clearBuffers(const ArgumentAccessType accessType) { auto iterator = buffers.cbegin(); while (iterator != buffers.cend()) { if (iterator->get()->getAccessType() == accessType) { iterator = buffers.erase(iterator); } else { ++iterator; } } } void CUDAEngine::printComputeAPIInfo(std::ostream& outputTarget) const { outputTarget << "Platform 0: " << "NVIDIA CUDA" << std::endl; auto devices = getCUDADevices(); for (size_t i = 0; i < devices.size(); i++) { outputTarget << "Device " << i << ": " << devices.at(i).getName() << std::endl; } outputTarget << std::endl; } std::vector<PlatformInfo> CUDAEngine::getPlatformInfo() const { int driverVersion; checkCUDAError(cuDriverGetVersion(&driverVersion), "cuDriverGetVersion"); PlatformInfo cuda(0, "NVIDIA CUDA"); cuda.setVendor("NVIDIA Corporation"); cuda.setVersion(std::to_string(driverVersion)); cuda.setExtensions("N/A"); return std::vector<PlatformInfo>{cuda}; } std::vector<DeviceInfo> CUDAEngine::getDeviceInfo(const PlatformIndex) const { std::vector<DeviceInfo> result; auto devices = getCUDADevices(); for (size_t i = 0; i < devices.size(); i++) { result.push_back(getCUDADeviceInfo(static_cast<DeviceIndex>(i))); } return result; } DeviceInfo CUDAEngine::getCurrentDeviceInfo() const { return getCUDADeviceInfo(deviceIndex); } void CUDAEngine::initializeKernelProfiling(const KernelRuntimeData& kernelData) { #ifdef KTT_PROFILING_CUPTI_LEGACY initializeKernelProfiling(kernelData.getName(), kernelData.getSource()); #elif KTT_PROFILING_CUPTI initializeKernelProfiling(kernelData.getName(), kernelData.getSource()); #else throw std::runtime_error("Support for kernel profiling is not included in this version of KTT framework"); #endif // KTT_PROFILING_CUPTI_LEGACY } EventId CUDAEngine::runKernelWithProfiling(const KernelRuntimeData& kernelData, const std::vector<KernelArgument*>& argumentPointers, const QueueId queue) { #ifdef KTT_PROFILING_CUPTI_LEGACY Timer overheadTimer; overheadTimer.start(); CUDAKernel* kernel; std::unique_ptr<CUDAKernel> kernelUnique; if (kernelCacheFlag) { if (kernelCache.find(std::make_pair(kernelData.getName(), kernelData.getSource())) == kernelCache.end()) { if (kernelCache.size() >= kernelCacheCapacity) { clearKernelCache(); } std::unique_ptr<CUDAProgram> program = createAndBuildProgram(kernelData.getSource()); auto kernel = std::make_unique<CUDAKernel>(program->getPtxSource(), kernelData.getName()); kernelCache.insert(std::make_pair(std::make_pair(kernelData.getName(), kernelData.getSource()), std::move(kernel))); } auto cachePointer = kernelCache.find(std::make_pair(kernelData.getName(), kernelData.getSource())); kernel = cachePointer->second.get(); } else { std::unique_ptr<CUDAProgram> program = createAndBuildProgram(kernelData.getSource()); kernelUnique = std::make_unique<CUDAKernel>(program->getPtxSource(), kernelData.getName()); kernel = kernelUnique.get(); } std::vector<CUdeviceptr*> kernelArguments = getKernelArguments(argumentPointers); overheadTimer.stop(); if (kernelProfilingInstances.find(std::make_pair(kernelData.getName(), kernelData.getSource())) == kernelProfilingInstances.end()) { initializeKernelProfiling(kernelData.getName(), kernelData.getSource()); } auto profilingInstance = kernelProfilingInstances.find(std::make_pair(kernelData.getName(), kernelData.getSource())); EventId id; if (!profilingInstance->second->hasValidKernelDuration()) // The first profiling run only captures kernel duration { id = enqueueKernel(*kernel, kernelData.getGlobalSize(), kernelData.getLocalSize(), kernelArguments, getSharedMemorySizeInBytes(argumentPointers, kernelData.getLocalMemoryModifiers()), queue, overheadTimer.getElapsedTime()); kernelToEventMap[std::make_pair(kernelData.getName(), kernelData.getSource())].push_back(id); Logger::logDebug("Performing kernel synchronization for event id: " + std::to_string(id)); auto eventPointer = kernelEvents.find(id); checkCUDAError(cuEventSynchronize(eventPointer->second.second->getEvent()), "cuEventSynchronize"); float duration = getEventCommandDuration(eventPointer->second.first->getEvent(), eventPointer->second.second->getEvent()); profilingInstance->second->updateState(static_cast<uint64_t>(duration)); } else { std::vector<CUPTIProfilingMetric>& metricData = profilingInstance->second->getProfilingMetrics(); auto subscription = std::make_unique<CUPTIProfilingSubscription>(metricData); id = enqueueKernel(*kernel, kernelData.getGlobalSize(), kernelData.getLocalSize(), kernelArguments, getSharedMemorySizeInBytes(argumentPointers, kernelData.getLocalMemoryModifiers()), queue, overheadTimer.getElapsedTime()); kernelToEventMap[std::make_pair(kernelData.getName(), kernelData.getSource())].push_back(id); profilingInstance->second->updateState(); } return id; #elif KTT_PROFILING_CUPTI Timer overheadTimer; overheadTimer.start(); CUDAKernel* kernel; std::unique_ptr<CUDAKernel> kernelUnique; auto key = std::make_pair(kernelData.getName(), kernelData.getSource()); if (kernelCacheFlag) { if (kernelCache.find(key) == kernelCache.end()) { if (kernelCache.size() >= kernelCacheCapacity) { clearKernelCache(); } std::unique_ptr<CUDAProgram> program = createAndBuildProgram(kernelData.getSource()); auto kernel = std::make_unique<CUDAKernel>(program->getPtxSource(), kernelData.getName()); kernelCache.insert(std::make_pair(key, std::move(kernel))); } auto cachePointer = kernelCache.find(key); kernel = cachePointer->second.get(); } else { std::unique_ptr<CUDAProgram> program = createAndBuildProgram(kernelData.getSource()); kernelUnique = std::make_unique<CUDAKernel>(program->getPtxSource(), kernelData.getName()); kernel = kernelUnique.get(); } std::vector<CUdeviceptr*> kernelArguments = getKernelArguments(argumentPointers); overheadTimer.stop(); if (kernelProfilingInstances.find(key) == kernelProfilingInstances.cend()) { initializeKernelProfiling(kernelData.getName(), kernelData.getSource()); } auto profilingInstance = kernelProfilingInstances.find(key); auto subscription = std::make_unique<CUPTIProfilingPass>(*profilingInstance->second); EventId id = enqueueKernel(*kernel, kernelData.getGlobalSize(), kernelData.getLocalSize(), kernelArguments, getSharedMemorySizeInBytes(argumentPointers, kernelData.getLocalMemoryModifiers()), queue, overheadTimer.getElapsedTime()); kernelToEventMap[key].push_back(id); auto eventPointer = kernelEvents.find(id); Logger::logDebug(std::string("Performing kernel synchronization for event id: ") + std::to_string(id)); checkCUDAError(cuEventSynchronize(eventPointer->second.second->getEvent()), "cuEventSynchronize"); return id; #else throw std::runtime_error("Support for kernel profiling is not included in this version of KTT framework"); #endif // KTT_PROFILING_CUPTI_LEGACY } uint64_t CUDAEngine::getRemainingKernelProfilingRuns(const std::string& kernelName, const std::string& kernelSource) { #ifdef KTT_PROFILING_CUPTI_LEGACY auto key = std::make_pair(kernelName, kernelSource); if (!containsKey(kernelProfilingInstances, key)) { return 0; } return kernelProfilingInstances.find(key)->second->getRemainingKernelRuns(); #elif KTT_PROFILING_CUPTI auto key = std::make_pair(kernelName, kernelSource); auto pair = kernelProfilingInstances.find(key); if (pair == kernelProfilingInstances.cend()) { return 0; } return pair->second->getRemainingPasses(); #else throw std::runtime_error("Support for kernel profiling is not included in this version of KTT framework"); #endif // KTT_PROFILING_CUPTI_LEGACY } bool CUDAEngine::hasAccurateRemainingKernelProfilingRuns() const { #ifdef KTT_PROFILING_CUPTI_LEGACY return true; #elif KTT_PROFILING_CUPTI return false; #else throw std::runtime_error("Support for kernel profiling is not included in this version of KTT framework"); #endif // KTT_PROFILING_CUPTI_LEGACY } KernelResult CUDAEngine::getKernelResultWithProfiling(const EventId id, const std::vector<OutputDescriptor>& outputDescriptors) { #ifdef KTT_PROFILING_CUPTI_LEGACY KernelResult result = createKernelResult(id); for (const auto& descriptor : outputDescriptors) { downloadArgument(descriptor.getArgumentId(), descriptor.getOutputDestination(), descriptor.getOutputSizeInBytes()); } const std::pair<std::string, std::string>& kernelKey = getKernelFromEvent(id); auto profilingInstance = kernelProfilingInstances.find(kernelKey); if (profilingInstance == kernelProfilingInstances.end()) { throw std::runtime_error(std::string("No profiling data exists for the following kernel in current configuration: " + kernelKey.first)); } KernelProfilingData profilingData = profilingInstance->second->generateProfilingData(); result.setProfilingData(profilingData); kernelProfilingInstances.erase(kernelKey); const std::vector<EventId>& eventIds = kernelToEventMap.find(kernelKey)->second; for (const auto eventId : eventIds) { kernelEvents.erase(eventId); } kernelToEventMap.erase(kernelKey); return result; #elif KTT_PROFILING_CUPTI KernelResult result = createKernelResult(id); for (const auto& descriptor : outputDescriptors) { downloadArgument(descriptor.getArgumentId(), descriptor.getOutputDestination(), descriptor.getOutputSizeInBytes()); } const std::pair<std::string, std::string>& kernelKey = getKernelFromEvent(id); auto profilingInstance = kernelProfilingInstances.find(kernelKey); if (profilingInstance == kernelProfilingInstances.end()) { throw std::runtime_error(std::string("No profiling data exists for the following kernel in current configuration: " + kernelKey.first)); } const CUPTIMetricConfiguration& configuration = profilingInstance->second->getMetricConfiguration(); std::vector<CUPTIMetric> metricData = metricInterface->getMetricData(configuration); KernelProfilingData profilingData; for (const auto& metric : metricData) { profilingData.addCounter(metric.getCounter()); } result.setProfilingData(profilingData); kernelProfilingInstances.erase(kernelKey); const std::vector<EventId>& eventIds = kernelToEventMap.find(kernelKey)->second; for (const auto eventId : eventIds) { kernelEvents.erase(eventId); } kernelToEventMap.erase(kernelKey); return result; #else throw std::runtime_error("Support for kernel profiling is not included in this version of KTT framework"); #endif // KTT_PROFILING_CUPTI_LEGACY } void CUDAEngine::setKernelProfilingCounters(const std::vector<std::string>& counterNames) { #ifdef KTT_PROFILING_CUPTI_LEGACY profilingMetrics.clear(); profilingMetrics = getProfilingMetricsForCurrentDevice(counterNames); #elif KTT_PROFILING_CUPTI profilingCounters = counterNames; #else throw std::runtime_error("Support for kernel profiling is not included in this version of KTT framework"); #endif // KTT_PROFILING_CUPTI_LEGACY } std::unique_ptr<CUDAProgram> CUDAEngine::createAndBuildProgram(const std::string& source) const { auto program = std::make_unique<CUDAProgram>(source); program->build(compilerOptions); return program; } EventId CUDAEngine::enqueueKernel(CUDAKernel& kernel, const std::vector<size_t>& globalSize, const std::vector<size_t>& localSize, const std::vector<CUdeviceptr*>& kernelArguments, const size_t localMemorySize, const QueueId queue, const uint64_t kernelLaunchOverhead) { if (queue >= streams.size()) { throw std::runtime_error(std::string("Invalid stream index: ") + std::to_string(queue)); } std::vector<void*> kernelArgumentsVoid; for (size_t i = 0; i < kernelArguments.size(); i++) { kernelArgumentsVoid.push_back((void*)kernelArguments.at(i)); } std::vector<size_t> correctedGlobalSize = globalSize; if (globalSizeCorrection) { correctedGlobalSize = roundUpGlobalSize(correctedGlobalSize, localSize); } if (globalSizeType == GlobalSizeType::OpenCL) { correctedGlobalSize.at(0) /= localSize.at(0); correctedGlobalSize.at(1) /= localSize.at(1); correctedGlobalSize.at(2) /= localSize.at(2); } EventId eventId = nextEventId; auto startEvent = std::make_unique<CUDAEvent>(eventId, kernel.getKernelName(), kernelLaunchOverhead, kernel.getCompilationData()); auto endEvent = std::make_unique<CUDAEvent>(eventId, kernel.getKernelName(), kernelLaunchOverhead, kernel.getCompilationData()); nextEventId++; Logger::getLogger().log(LoggingLevel::Debug, "Launching kernel " + kernel.getKernelName() + ", event id: " + std::to_string(eventId)); checkCUDAError(cuEventRecord(startEvent->getEvent(), streams.at(queue)->getStream()), "cuEventRecord"); checkCUDAError(cuLaunchKernel(kernel.getKernel(), static_cast<unsigned int>(correctedGlobalSize.at(0)), static_cast<unsigned int>(correctedGlobalSize.at(1)), static_cast<unsigned int>(correctedGlobalSize.at(2)), static_cast<unsigned int>(localSize.at(0)), static_cast<unsigned int>(localSize.at(1)), static_cast<unsigned int>(localSize.at(2)), static_cast<unsigned int>(localMemorySize), streams.at(queue)->getStream(), kernelArgumentsVoid.data(), nullptr), "cuLaunchKernel"); checkCUDAError(cuEventRecord(endEvent->getEvent(), streams.at(queue)->getStream()), "cuEventRecord"); kernelEvents.insert(std::make_pair(eventId, std::make_pair(std::move(startEvent), std::move(endEvent)))); return eventId; } KernelResult CUDAEngine::createKernelResult(const EventId id) const { auto eventPointer = kernelEvents.find(id); if (eventPointer == kernelEvents.end()) { throw std::runtime_error(std::string("Kernel event with following id does not exist or its result was already retrieved: ") + std::to_string(id)); } Logger::getLogger().log(LoggingLevel::Debug, std::string("Performing kernel synchronization for event id: ") + std::to_string(id)); // Wait until the second event in pair (the end event) finishes checkCUDAError(cuEventSynchronize(eventPointer->second.second->getEvent()), "cuEventSynchronize"); std::string name = eventPointer->second.first->getKernelName(); float duration = getEventCommandDuration(eventPointer->second.first->getEvent(), eventPointer->second.second->getEvent()); uint64_t overhead = eventPointer->second.first->getOverhead(); KernelCompilationData compilationData = eventPointer->second.first->getCompilationData(); kernelEvents.erase(id); KernelResult result(name, static_cast<uint64_t>(duration)); result.setOverhead(overhead); result.setCompilationData(compilationData); return result; } DeviceInfo CUDAEngine::getCUDADeviceInfo(const DeviceIndex deviceIndex) const { auto devices = getCUDADevices(); DeviceInfo result(deviceIndex, devices.at(deviceIndex).getName()); CUdevice id = devices.at(deviceIndex).getDevice(); result.setExtensions("N/A"); result.setVendor("NVIDIA Corporation"); size_t globalMemory; checkCUDAError(cuDeviceTotalMem(&globalMemory, id), "cuDeviceTotalMem"); result.setGlobalMemorySize(globalMemory); int localMemory; checkCUDAError(cuDeviceGetAttribute(&localMemory, CU_DEVICE_ATTRIBUTE_SHARED_MEMORY_PER_BLOCK, id), "cuDeviceGetAttribute"); result.setLocalMemorySize(localMemory); int constantMemory; checkCUDAError(cuDeviceGetAttribute(&constantMemory, CU_DEVICE_ATTRIBUTE_TOTAL_CONSTANT_MEMORY, id), "cuDeviceGetAttribute"); result.setMaxConstantBufferSize(constantMemory); int computeUnits; checkCUDAError(cuDeviceGetAttribute(&computeUnits, CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT, id), "cuDeviceGetAttribute"); result.setMaxComputeUnits(computeUnits); int workGroupSize; checkCUDAError(cuDeviceGetAttribute(&workGroupSize, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK, id), "cuDeviceGetAttribute"); result.setMaxWorkGroupSize(workGroupSize); result.setDeviceType(DeviceType::GPU); return result; } std::vector<CUDADevice> CUDAEngine::getCUDADevices() const { int deviceCount; checkCUDAError(cuDeviceGetCount(&deviceCount), "cuDeviceGetCount"); std::vector<CUdevice> deviceIds(deviceCount); for (int i = 0; i < deviceCount; i++) { checkCUDAError(cuDeviceGet(&deviceIds.at(i), i), "cuDeviceGet"); } std::vector<CUDADevice> devices; for (const auto deviceId : deviceIds) { char name[40]; checkCUDAError(cuDeviceGetName(name, 40, deviceId), "cuDeviceGetName"); devices.push_back(CUDADevice(deviceId, std::string(name))); } return devices; } std::vector<CUdeviceptr*> CUDAEngine::getKernelArguments(const std::vector<KernelArgument*>& argumentPointers) { std::vector<CUdeviceptr*> result; for (const auto argument : argumentPointers) { if (argument->getUploadType() == ArgumentUploadType::Local) { continue; } else if (argument->getUploadType() == ArgumentUploadType::Vector) { CUdeviceptr* cachedBuffer = loadBufferFromCache(argument->getId()); if (cachedBuffer == nullptr) { uploadArgument(*argument); cachedBuffer = loadBufferFromCache(argument->getId()); } result.push_back(cachedBuffer); } else if (argument->getUploadType() == ArgumentUploadType::Scalar) { result.push_back((CUdeviceptr*)argument->getData()); } } return result; } size_t CUDAEngine::getSharedMemorySizeInBytes(const std::vector<KernelArgument*>& argumentPointers, const std::vector<LocalMemoryModifier>& modifiers) const { for (const auto& modifier : modifiers) { bool modifierArgumentFound = false; for (const auto argument : argumentPointers) { if (modifier.getArgument() == argument->getId() && argument->getUploadType() == ArgumentUploadType::Local) { modifierArgumentFound = true; } } if (!modifierArgumentFound) { throw std::runtime_error(std::string("No matching local memory argument found for modifier, argument id in modifier: ") + std::to_string(modifier.getArgument())); } } size_t result = 0; for (const auto argument : argumentPointers) { if (argument->getUploadType() != ArgumentUploadType::Local) { continue; } size_t numberOfElements = argument->getNumberOfElements(); for (const auto& modifier : modifiers) { if (modifier.getArgument() != argument->getId()) { continue; } numberOfElements = modifier.getModifiedSize(numberOfElements); } size_t argumentSize = argument->getElementSizeInBytes() * numberOfElements; result += argumentSize; } return result; } CUDABuffer* CUDAEngine::findBuffer(const ArgumentId id) const { if (persistentBufferFlag) { for (const auto& buffer : persistentBuffers) { if (buffer->getKernelArgumentId() == id) { return buffer.get(); } } } for (const auto& buffer : buffers) { if (buffer->getKernelArgumentId() == id) { return buffer.get(); } } return nullptr; } CUdeviceptr* CUDAEngine::loadBufferFromCache(const ArgumentId id) const { CUDABuffer* buffer = findBuffer(id); if (buffer != nullptr) { return buffer->getBuffer(); } return nullptr; } #ifdef KTT_PROFILING_CUPTI_LEGACY void CUDAEngine::initializeKernelProfiling(const std::string& kernelName, const std::string& kernelSource) { auto key = std::make_pair(kernelName, kernelSource); if (!containsKey(kernelProfilingInstances, key)) { kernelProfilingInstances[key] = std::make_unique<CUPTIProfilingInstance>(context->getContext(), context->getDevice(), profilingMetrics); kernelToEventMap[key] = std::vector<EventId>{}; } } const std::pair<std::string, std::string>& CUDAEngine::getKernelFromEvent(const EventId id) const { for (const auto& entry : kernelToEventMap) { if (containsElement(entry.second, id)) { return entry.first; } } throw std::runtime_error(std::string("Corresponding kernel was not found for event with id: ") + std::to_string(id)); } CUpti_MetricID CUDAEngine::getMetricIdFromName(const std::string& metricName) { CUpti_MetricID metricId; const CUptiResult result = cuptiMetricGetIdFromName(context->getDevice(), metricName.c_str(), &metricId); switch (result) { case CUPTI_SUCCESS: return metricId; case CUPTI_ERROR_INVALID_METRIC_NAME: return std::numeric_limits<CUpti_MetricID>::max(); default: checkCUPTIError(result, "cuptiMetricGetIdFromName"); } return 0; } std::vector<std::pair<std::string, CUpti_MetricID>> CUDAEngine::getProfilingMetricsForCurrentDevice(const std::vector<std::string>& metricNames) { std::vector<std::pair<std::string, CUpti_MetricID>> collectedMetrics; for (const auto& metricName : metricNames) { CUpti_MetricID id = getMetricIdFromName(metricName); if (id != std::numeric_limits<CUpti_MetricID>::max()) { collectedMetrics.push_back(std::make_pair(metricName, id)); } } return collectedMetrics; } const std::vector<std::string>& CUDAEngine::getDefaultProfilingMetricNames() { static const std::vector<std::string> result { "achieved_occupancy", "alu_fu_utilization", "branch_efficiency", "double_precision_fu_utilization", "dram_read_transactions", "dram_utilization", "dram_write_transactions", "gld_efficiency", "gst_efficiency", "half_precision_fu_utilization", "inst_executed", "inst_fp_16", "inst_fp_32", "inst_fp_64", "inst_integer", "inst_inter_thread_communication", "inst_misc", "inst_replay_overhead", "l1_shared_utilization", "l2_utilization", "ldst_fu_utilization", "shared_efficiency", "shared_load_transactions", "shared_store_transactions", "shared_utilization", "single_precision_fu_utilization", "sm_efficiency", "special_fu_utilization", "tex_fu_utilization" }; return result; } #elif KTT_PROFILING_CUPTI void CUDAEngine::initializeKernelProfiling(const std::string& kernelName, const std::string& kernelSource) { auto key = std::make_pair(kernelName, kernelSource); auto profilingInstance = kernelProfilingInstances.find(key); if (profilingInstance == kernelProfilingInstances.end()) { if (!kernelProfilingInstances.empty()) { throw std::runtime_error("Profiling of multiple kernel instances is not supported for new CUPTI API"); } const CUPTIMetricConfiguration configuration = metricInterface->createMetricConfiguration(profilingCounters); kernelProfilingInstances.insert(std::make_pair(key, std::make_unique<CUPTIProfilingInstance>(context->getContext(), configuration))); kernelToEventMap.insert(std::make_pair(key, std::vector<EventId>{})); } } const std::pair<std::string, std::string>& CUDAEngine::getKernelFromEvent(const EventId id) const { for (const auto& entry : kernelToEventMap) { if (containsElement(entry.second, id)) { return entry.first; } } throw std::runtime_error(std::string("Corresponding kernel was not found for event with id: ") + std::to_string(id)); } const std::vector<std::string>& CUDAEngine::getDefaultProfilingCounters() { static const std::vector<std::string> result { "dram__sectors_read.sum", // dram_read_transactions "dram__sectors_write.sum", // dram_write_transactions "dram__throughput.avg.pct_of_peak_sustained_elapsed", // dram_utilization "l1tex__data_pipe_lsu_wavefronts_mem_shared.avg.pct_of_peak_sustained_elapsed", // shared_utilization "l1tex__data_pipe_lsu_wavefronts_mem_shared_op_ld.sum", // shared_load_transactions "l1tex__data_pipe_lsu_wavefronts_mem_shared_op_st.sum", // shared_store_transactions "lts__t_sectors.avg.pct_of_peak_sustained_elapsed", // l2_utilization "sm__warps_active.avg.pct_of_peak_sustained_active", // achieved_occupancy "smsp__cycles_active.avg.pct_of_peak_sustained_elapsed", // sm_efficiency "smsp__inst_executed_pipe_fp16.sum", // half_precision_fu_utilization "smsp__inst_executed_pipe_fp64.avg.pct_of_peak_sustained_active", // double_precision_fu_utilization "smsp__inst_executed_pipe_lsu.avg.pct_of_peak_sustained_active", // ldst_fu_utilization "smsp__inst_executed_pipe_tex.avg.pct_of_peak_sustained_active", // tex_fu_utilization "smsp__inst_executed_pipe_xu.avg.pct_of_peak_sustained_active", // special_fu_utilization "smsp__inst_executed.sum", // inst_executed "smsp__pipe_fma_cycles_active.avg.pct_of_peak_sustained_active", // single_precision_fu_utilization "smsp__sass_thread_inst_executed_op_fp16_pred_on.sum", // inst_fp_16 "smsp__sass_thread_inst_executed_op_fp32_pred_on.sum", // inst_fp_32 "smsp__sass_thread_inst_executed_op_fp64_pred_on.sum", // inst_fp_64 "smsp__sass_thread_inst_executed_op_integer_pred_on.sum", // inst_integer "smsp__sass_thread_inst_executed_op_inter_thread_communication_pred_on.sum", // inst_inter_thread_communication "smsp__sass_thread_inst_executed_op_misc_pred_on.sum" // inst_misc }; return result; } #endif // KTT_PROFILING_CUPTI } // namespace ktt #endif // KTT_PLATFORM_CUDA
35.662791
149
0.696381
[ "vector" ]
aee85111ed4770dc5d2d71f205d5a072798e9e5e
6,496
cpp
C++
Osiris/Hooks.cpp
Ivankvetoslav/Osiris
efbc96886f9d7e12444e156093075715764e8515
[ "MIT" ]
2
2019-01-27T14:46:50.000Z
2019-04-07T11:39:40.000Z
Osiris/Hooks.cpp
Ivankvetoslav/Osiris
efbc96886f9d7e12444e156093075715764e8515
[ "MIT" ]
null
null
null
Osiris/Hooks.cpp
Ivankvetoslav/Osiris
efbc96886f9d7e12444e156093075715764e8515
[ "MIT" ]
null
null
null
#include <Windows.h> #include <Psapi.h> #include "imgui/imgui.h" #include "imgui/imgui_impl_dx9.h" #include "imgui/imgui_impl_win32.h" #include "Config.h" #include "GUI.h" #include "Hacks/Misc.h" #include "Hooks.h" #include "Interfaces.h" #include "Memory.h" #include "SDK/UserCmd.h" #include "Hacks/Glow.h" #include "Hacks/Triggerbot.h" #include "Hacks/Chams.h" extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); static LRESULT __stdcall hookedWndProc(HWND window, UINT msg, WPARAM wParam, LPARAM lParam) noexcept { if (GetAsyncKeyState(VK_INSERT) & 1) gui.isOpen = !gui.isOpen; if (gui.isOpen && !ImGui_ImplWin32_WndProcHandler(window, msg, wParam, lParam)) return true; return CallWindowProc(hooks.originalWndProc, window, msg, wParam, lParam); } static HRESULT __stdcall hookedPresent(IDirect3DDevice9* device, const RECT* src, const RECT* dest, HWND windowOverride, const RGNDATA* dirtyRegion) noexcept { static bool isInitialised{ false }; if (!isInitialised) { ImGui::CreateContext(); ImGui_ImplWin32_Init(FindWindowA("Valve001", NULL)); ImGui_ImplDX9_Init(device); ImGui::StyleColorsDark(); ImGuiStyle& style = ImGui::GetStyle(); style.WindowRounding = 0.0f; style.WindowBorderSize = 0.0f; style.ChildBorderSize = 0.0f; ImGuiIO& io = ImGui::GetIO(); io.IniFilename = nullptr; io.LogFilename = nullptr; char buffer[MAX_PATH]; GetWindowsDirectoryA(buffer, MAX_PATH); io.Fonts->AddFontFromFileTTF(std::string{ buffer + std::string{ "\\Fonts\\Tahoma.ttf" } }.c_str(), 16.0f); hooks.originalWndProc = reinterpret_cast<WNDPROC>( SetWindowLongPtr(FindWindowA("Valve001", NULL), GWLP_WNDPROC, LONG_PTR(hookedWndProc)) ); isInitialised = true; } else if (gui.isOpen) { device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_RED | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_BLUE); IDirect3DVertexDeclaration9* vertexDeclaration; device->GetVertexDeclaration(&vertexDeclaration); ImGui_ImplDX9_NewFrame(); ImGui_ImplWin32_NewFrame(); ImGui::NewFrame(); gui.render(); ImGui::EndFrame(); ImGui::Render(); ImGui_ImplDX9_RenderDrawData(ImGui::GetDrawData()); device->SetVertexDeclaration(vertexDeclaration); } return hooks.originalPresent(device, src, dest, windowOverride, dirtyRegion); } static HRESULT __stdcall hookedReset(IDirect3DDevice9* device, D3DPRESENT_PARAMETERS* params) noexcept { ImGui_ImplDX9_InvalidateDeviceObjects(); auto result = hooks.originalReset(device, params); ImGui_ImplDX9_CreateDeviceObjects(); return result; } static bool __stdcall hookedCreateMove(float inputSampleTime, UserCmd* cmd) noexcept { hooks.clientMode.getOriginal<void(__thiscall*)(ClientMode*, float, UserCmd*)>(24)(memory.clientMode, inputSampleTime, cmd); if (interfaces.engineClient->isConnected() && interfaces.engineClient->isInGame()) { Misc::skybox(); Misc::bunnyHop(cmd); Misc::removeCrouchCooldown(cmd); Misc::clanTag(); Triggerbot::run(cmd); } return false; } static void __stdcall hookedLockCursor() noexcept { if (gui.isOpen) interfaces.surface->unlockCursor(); else hooks.surface.getOriginal<void(__thiscall*)(Surface*)>(67)(interfaces.surface); } static int __stdcall hookedDoPostScreenEffects(int param) noexcept { if (interfaces.engineClient->isConnected() && interfaces.engineClient->isInGame()) { Misc::inverseRagdollGravity(); Misc::removeBlood(); Misc::removeSmoke(); Misc::reduceFlashEffect(); Misc::disablePostProcessing(); Misc::colorWorld(); Glow::render(); Chams::render(); } return hooks.clientMode.getOriginal<int(__thiscall*)(ClientMode*, int)>(44)(memory.clientMode, param); } static float __stdcall hookedGetViewModelFov() noexcept { if (interfaces.engineClient->isConnected() && interfaces.engineClient->isInGame() && !(*memory.localPlayer)->isScoped()) return static_cast<float>(config.misc.viewmodelFov); else return 60.0f; } Hooks::Hooks() { originalPresent = **reinterpret_cast<decltype(&originalPresent)*>(memory.present); **reinterpret_cast<void***>(memory.present) = reinterpret_cast<void*>(&hookedPresent); originalReset = **reinterpret_cast<decltype(&originalReset)*>(memory.reset); **reinterpret_cast<void***>(memory.reset) = reinterpret_cast<void*>(&hookedReset); surface.hookAt(67, hookedLockCursor); clientMode.hookAt(24, hookedCreateMove); clientMode.hookAt(44, hookedDoPostScreenEffects); clientMode.hookAt(35, hookedGetViewModelFov); } Hooks::Vmt::Vmt(void* const base) { oldVmt = *reinterpret_cast<std::uintptr_t**>(base); length = calculateLength(oldVmt); newVmt = findFreeDataPage(base, length); std::copy(oldVmt, oldVmt + length, newVmt); *reinterpret_cast<std::uintptr_t**>(base) = newVmt; } std::uintptr_t* Hooks::Vmt::findFreeDataPage(void* const base, std::size_t vmtSize) { MEMORY_BASIC_INFORMATION mbi; VirtualQuery(base, &mbi, sizeof(mbi)); MODULEINFO moduleInfo; GetModuleInformation(GetCurrentProcess(), static_cast<HMODULE>(mbi.AllocationBase), &moduleInfo, sizeof(moduleInfo)); std::uintptr_t* moduleEnd{ reinterpret_cast<std::uintptr_t*>(static_cast<std::byte*>(moduleInfo.lpBaseOfDll) + moduleInfo.SizeOfImage) }; for (auto currentAddress = moduleEnd - vmtSize; currentAddress > moduleInfo.lpBaseOfDll; currentAddress--) if (!*currentAddress) { if (VirtualQuery(currentAddress, &mbi, sizeof(mbi)) && mbi.State == MEM_COMMIT && mbi.Protect == PAGE_READWRITE && mbi.RegionSize >= vmtSize * sizeof(std::uintptr_t) && std::all_of(currentAddress, currentAddress + vmtSize, [](std::uintptr_t a) { return !a; })) return currentAddress; } else currentAddress -= vmtSize; } std::size_t Hooks::Vmt::calculateLength(std::uintptr_t* vmt) const noexcept { std::size_t length{ 0 }; MEMORY_BASIC_INFORMATION memoryInfo; while (VirtualQuery(reinterpret_cast<LPCVOID>(vmt[length]), &memoryInfo, sizeof(memoryInfo)) && memoryInfo.Protect == PAGE_EXECUTE_READ) length++; return length; }
35.692308
157
0.69335
[ "render" ]
aee88bb92ff6a850bb3c06e14e665061ee757d66
3,243
cpp
C++
Source/ArchQOR/Z/HLAssembler/Emittables/Z_EJmp.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
9
2016-05-27T01:00:39.000Z
2021-04-01T08:54:46.000Z
Source/ArchQOR/Z/HLAssembler/Emittables/Z_EJmp.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
1
2016-03-03T22:54:08.000Z
2016-03-03T22:54:08.000Z
Source/ArchQOR/Z/HLAssembler/Emittables/Z_EJmp.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
4
2016-05-27T01:00:43.000Z
2018-08-19T08:47:49.000Z
//Z_EJmp.cpp // Copyright (c) 2008-2010, Petr Kobalicek <kobalicek.petr@gmail.com> // Copyright (c) Querysoft Limited 2012 // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. //Implement Z Jump emittable #include "ArchQOR.h" #if ( QOR_ARCH == QOR_ARCH_Z ) #include "ArchQOR/Zarch/HLAssembler/Emittables/Z_EJmp.h" #include "ArchQOR/Zarch/HLAssembler/ZHLAContext.h" #include <assert.h> //------------------------------------------------------------------------------ namespace nsArch { //------------------------------------------------------------------------------ namespace nsZ { //------------------------------------------------------------------------------ CEJmp::CEJmp( CZHLAIntrinsics* c, Cmp_unsigned__int32 code, COperand** paOperandsData, Cmp_unsigned__int32 operandsCount ) __QCMP_THROW : CEInstruction( c, code, paOperandsData, operandsCount ) { } //------------------------------------------------------------------------------ CEJmp::~CEJmp() __QCMP_THROW { } //------------------------------------------------------------------------------ void CEJmp::prepare( CHLAssemblerContextBase& hlac ) __QCMP_THROW { } //------------------------------------------------------------------------------ nsArch::CEmittable* CEJmp::translate( CHLAssemblerContextBase& hlac ) __QCMP_THROW { // Translate using EInstruction. nsArch::CEmittable* ret = 0; return ret; } //------------------------------------------------------------------------------ void CEJmp::emit( CHighLevelAssemblerBase& ab ) __QCMP_THROW { } //------------------------------------------------------------------------------ void CEJmp::DoJump( CZHLAContext& cc ) __QCMP_THROW { } //------------------------------------------------------------------------------ CETarget* CEJmp::getJumpTarget() const __QCMP_THROW { return m_pJumpTarget; } }//nsZ }//nsArch #endif//( QOR_ARCH == QOR_ARCH_Z )
36.852273
195
0.574468
[ "object" ]
aef19ee65fede4fa6a870a97c2df54383cae9796
2,427
hpp
C++
include/types/type.hpp
rationalis-petra/hydra
a1c14e560f5f1c64983468e5fd0be7b32824971d
[ "MIT" ]
2
2021-01-14T11:19:02.000Z
2021-03-07T03:08:08.000Z
include/types/type.hpp
rationalis-petra/hydra
a1c14e560f5f1c64983468e5fd0be7b32824971d
[ "MIT" ]
null
null
null
include/types/type.hpp
rationalis-petra/hydra
a1c14e560f5f1c64983468e5fd0be7b32824971d
[ "MIT" ]
null
null
null
#ifndef __MODULUS_TYPE_TYPE_HPP #define __MODULUS_TYPE_TYPE_HPP #include <list> #include <string> #include <vector> #include "expressions/object.hpp" #include "expressions/operation.hpp" namespace type { struct Type : public virtual expr::Object { public: virtual expr::Object *check_type(expr::Object *obj) = 0; virtual expr::Object *subtype(Type *ty) = 0; virtual expr::Object *equal(Type *ty); }; // TODO: TUPLE, UNION!!! struct Cons : public Type { Cons(); Cons(Type *tcar, Type *tcdr); virtual void mark_node(); std::string to_string(interp::LocalRuntime &r, interp::LexicalScope& s); expr::Object *check_type(expr::Object *obj); virtual expr::Object *subtype(Type *ty); Type *type_car; Type *type_cdr; }; struct Vector : public Type { Vector(); Vector(Type* t); Vector(Type* t, int i); virtual void mark_node(); std::string to_string(interp::LocalRuntime &r, interp::LexicalScope& s); expr::Object *check_type(expr::Object *obj); virtual expr::Object *subtype(Type *ty); Type *type_elt; }; struct List : public Type { List(); virtual void mark_node(); std::string to_string(interp::LocalRuntime &r, interp::LexicalScope& s); expr::Object *check_type(expr::Object *obj); virtual expr::Object *subtype(Type *ty); Type *elt_type; }; struct Tuple : public Type { Tuple(); Tuple(std::vector<Type *> types); virtual void mark_node(); std::string to_string(interp::LocalRuntime &r, interp::LexicalScope& s); expr::Object *check_type(expr::Object *obj); virtual expr::Object *subtype(Type *ty); std::vector<Type *> types; }; struct Union : public Type { virtual void mark_node(); std::string to_string(interp::LocalRuntime &r, interp::LexicalScope& s); expr::Object *check_type(expr::Object *obj); Type *constructor(std::list<expr::Object *> lst); virtual expr::Object *subtype(Type *ty); std::list<Type *> types; }; struct IsConstructor : public expr::Operator { void mark_node(); expr::Object *object; std::string to_string(interp::LocalRuntime &r, interp::LexicalScope& s); Type *constructor(std::list<expr::Object *> lst); }; struct Is : public Type { Is(expr::Object *v); void mark_node(); expr::Object *object; std::string to_string(interp::LocalRuntime &r, interp::LexicalScope& s); virtual expr::Object *subtype(Type *ty); virtual expr::Object *check_type(expr::Object *obj); }; } // namespace type #endif
25.28125
74
0.693449
[ "object", "vector" ]
4e132c96e29f57fb9cc9e8cf1b269a18498534ad
2,413
cpp
C++
tests/opencl_engine_tests.cpp
Knutakir/KTT
502a8588710e20adeff0a1c27b196aee2c206697
[ "MIT" ]
null
null
null
tests/opencl_engine_tests.cpp
Knutakir/KTT
502a8588710e20adeff0a1c27b196aee2c206697
[ "MIT" ]
null
null
null
tests/opencl_engine_tests.cpp
Knutakir/KTT
502a8588710e20adeff0a1c27b196aee2c206697
[ "MIT" ]
null
null
null
#include <catch.hpp> #include <compute_engine/opencl/opencl_engine.h> #include <kernel_argument/kernel_argument.h> std::string programSource(std::string("") + "__kernel void testKernel(float number, __global float* a, __global float* b, __global float* result)\n" + "{\n" + " int index = get_global_id(0);\n" + "\n" + " result[index] = a[index] + b[index] + number;\n" + "}\n"); TEST_CASE("Working with OpenCL program and kernel", "Component: OpenCLEngine") { ktt::OpenCLEngine engine(0, 0, 1); auto program = engine.createAndBuildProgram(programSource); REQUIRE(program->getSource() == programSource); auto kernel = std::make_unique<ktt::OpenCLKernel>(program->getDevices()[0], program->getProgram(), "testKernel"); REQUIRE(kernel->getArgumentsCount() == 0); REQUIRE(kernel->getKernelName() == "testKernel"); float value = 0.0f; kernel->setKernelArgumentScalar(&value, sizeof(float)); REQUIRE(kernel->getArgumentsCount() == 1); SECTION("Trying to build program with invalid source throws") { REQUIRE_THROWS(engine.createAndBuildProgram("Invalid")); } } TEST_CASE("Working with OpenCL buffer", "Component: OpenCLEngine") { ktt::OpenCLEngine engine(0, 0, 1); std::vector<float> data; for (size_t i = 0; i < 64; i++) { data.push_back(static_cast<float>(i)); } auto argument = ktt::KernelArgument(0, data.data(), data.size(), sizeof(float), ktt::ArgumentDataType::Float, ktt::ArgumentMemoryLocation::Device, ktt::ArgumentAccessType::ReadOnly, ktt::ArgumentUploadType::Vector, true); SECTION("Transfering argument to / from device") { engine.uploadArgument(argument); ktt::KernelArgument resultArgument = engine.downloadArgumentObject(argument.getId(), nullptr); REQUIRE(resultArgument.getDataType() == argument.getDataType()); REQUIRE(resultArgument.getMemoryLocation() == argument.getMemoryLocation()); REQUIRE(resultArgument.getAccessType() == argument.getAccessType()); REQUIRE(resultArgument.getUploadType() == argument.getUploadType()); REQUIRE(resultArgument.getDataSizeInBytes() == argument.getDataSizeInBytes()); const float* result = argument.getDataWithType<float>(); for (size_t i = 0; i < data.size(); ++i) { REQUIRE(result[i] == data[i]); } } }
37.123077
119
0.664733
[ "vector" ]
4e17ed9528b4f1993f636871d30302c93113aa7b
2,710
cpp
C++
ApplicationDemo/ballDetect&FeedbackSystem/main.cpp
studyHooligen/Driver-For-Jetson
812971ef002fbcd8dc274e723eb5ac86410a0172
[ "Apache-2.0" ]
null
null
null
ApplicationDemo/ballDetect&FeedbackSystem/main.cpp
studyHooligen/Driver-For-Jetson
812971ef002fbcd8dc274e723eb5ac86410a0172
[ "Apache-2.0" ]
null
null
null
ApplicationDemo/ballDetect&FeedbackSystem/main.cpp
studyHooligen/Driver-For-Jetson
812971ef002fbcd8dc274e723eb5ac86410a0172
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> #include <time.h> #include "opencv.hpp" //OpenCV(主)头文件 #include <Dense> #include "IMX219.hpp" using namespace std; //引入命名空间 using namespace cv; // #define __USER__DEBUG__ #define WIDTH 1280 #define HEIGHT 720 #define FPS 30 int main() { Mat capImg; //像素矩阵变量 std::string pipeline = get_tegra_pipeline(WIDTH, HEIGHT, FPS); cv::VideoCapture cam(pipeline, cv::CAP_GSTREAMER); if(!cam.isOpened()) //检查是否成功打开相机 { std::cout<<"Open Failed!"<<std::endl; return -1; } std::cout<<"open Success!"<<std::endl; Mat grayImg,fltImg,edgeImg; auto timePre = clock(); auto timeNow = timePre; Eigen::Vector3d detectPre(0,0,0); while(1) { cam >> capImg; //读取视频流 timeNow = clock(); //获取系统时间 #ifdef __USER__DEBUG__ imshow("camera",capImg); //显示图像 waitKey(1); //按键更新 #endif cvtColor(capImg,grayImg,COLOR_BGR2GRAY); //转灰度图 #ifdef __USER__DEBUG__ imshow("gray Image", grayImg); waitKey(0); destroyWindow("gray Image"); #endif GaussianBlur(grayImg,fltImg,Size(9,9),4,4); //高斯滤波 #ifdef __USER__DEBUG__ imshow("filter Image", fltImg); waitKey(0); destroyWindow("filter Image"); #endif Canny(fltImg,edgeImg,20,20); //边缘检测 #ifdef __USER__DEBUG__ imshow("edge detect",edgeImg); waitKey(0); destroyWindow("edge detect"); #endif vector<Vec3f> circles; HoughCircles(fltImg,circles, HOUGH_GRADIENT, 1,fltImg.rows/4, 10,20,0,fltImg.rows/4); //霍夫圆检测 if(circles.empty()) { cout<<"didn't detect circle"<<endl; return -1; } #ifdef __USER__DEBUG__ for(auto i = 0;i < circles.size(); i++) { Point center(cvRound(circles[i][0]),cvRound(circles[i][1])); int radius = cvRound(circles[i][2]); circle(capImg, center, 3, Scalar(0, 255, 0), -1, 8, 0); circle(capImg, center, radius, Scalar(155, 50, 255), 3, 8, 0); } imshow("resault",capImg); destroyAllWindows(); #endif Eigen::Vector3d position(circles[0][0],circles[0][1],1); //齐次像素坐标系[x,y,1]^T Eigen::Matrix3d cameraKmatrix; //内参矩阵K double z = 1; //物距z Eigen::Vector3d res = z*cameraKmatrix * position; //求解相机坐标系[X,Y,Z]^T auto timeDiv = timeNow - timePre; //时间差 Eigen::Vector3d distance = res - detectPre; //求解位移 auto velocity = distance.norm()/timeDiv; //求解速度 } return 0; }
25.327103
86
0.557934
[ "vector" ]
4e1aafe851b1594b9541ea065d35f66093ce4ff1
3,572
cpp
C++
redemption/tests/capture/test_redis_writer.cpp
DianaAssistant/DIANA
6a4c51c1861f6a936941b21c2c905fc291c229d7
[ "MIT" ]
null
null
null
redemption/tests/capture/test_redis_writer.cpp
DianaAssistant/DIANA
6a4c51c1861f6a936941b21c2c905fc291c229d7
[ "MIT" ]
null
null
null
redemption/tests/capture/test_redis_writer.cpp
DianaAssistant/DIANA
6a4c51c1861f6a936941b21c2c905fc291c229d7
[ "MIT" ]
null
null
null
/* 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. Product name: redemption, a FLOSS RDP proxy Copyright (C) Wallix 2021 Author(s): Proxies Team */ #include "test_only/test_framework/redemption_unit_tests.hpp" #include "capture/redis_writer.hpp" #include "core/listen.hpp" RED_AUTO_TEST_CASE(TestRedisSet) { RedisCmdSet cmd{"my_image_key"_av}; cmd.append("blabla"_av); cmd.append("tagadasouinsouin"_av); RED_CHECK(cmd.build_command() == "*3\r\n" "$3\r\nSET\r\n" "$12\r\nmy_image_key\r\n" "$22\r\nblablatagadasouinsouin\r\n"_av_ascii); cmd.clear(); cmd.append("tic tac toe"_av); RED_CHECK(cmd.build_command() == "*3\r\n" "$3\r\nSET\r\n" "$12\r\nmy_image_key\r\n" "$11\r\ntic tac toe\r\n"_av_ascii); } RED_AUTO_TEST_CASE(TestRedisServer) { auto addr = "127.0.0.1:4446"_sized_av; unique_fd sck_server = create_server(inet_addr("127.0.0.1"), 4446, EnableTransparentMode::No); RED_REQUIRE(sck_server.is_open()); fcntl(sck_server.fd(), F_SETFL, fcntl(sck_server.fd(), F_GETFL) & ~O_NONBLOCK); std::vector<uint8_t> message; using namespace std::chrono_literals; RedisWriter cmd(addr, 100ms, "admin"_sized_av, 0); // open -> close -> open -> close for (int i = 0; i < 2; ++i) { RED_TEST_CONTEXT("i = " << i) { RED_REQUIRE(cmd.open()); sockaddr s {}; socklen_t sin_size = sizeof(s); int sck = accept(sck_server.fd(), &s, &sin_size); RED_REQUIRE(sck != -1); auto recv = [&]{ message.clear(); char buff[100]; ssize_t r = ::recv(sck, buff, std::size(buff), 0); if (r > 0) { message.assign(buff, buff + r); } return bytes_view(message).as_chars(); }; auto send = [&](chars_view resp){ return ::send(sck, resp.data(), resp.size(), 0) == ssize_t(resp.size()); }; RED_REQUIRE(recv() == "*2\r\n$4\r\nAUTH\r\n$5\r\nadmin\r\n" "*2\r\n$6\r\nSELECT\r\n$1\r\n0\r\n"_av); RED_REQUIRE(send("+OK\r\n"_av)); RED_REQUIRE(send("+OK\r\n"_av)); RED_CHECK(cmd.send("bla bla"_av) == RedisWriter::IOResult::Ok); RED_REQUIRE(recv() == "bla bla"_av); RED_REQUIRE(send("+OK\r\n"_av)); RED_CHECK(cmd.send("bla bla bla"_av) == RedisWriter::IOResult::Ok); RED_REQUIRE(recv() == "bla bla bla"_av); RED_REQUIRE(send("+OK\r\n"_av)); RED_CHECK(cmd.send("bad"_av) == RedisWriter::IOResult::Ok); RED_REQUIRE(recv() == "bad"_av); RED_REQUIRE(send("-ERR\r\n"_av)); RED_CHECK(cmd.send("receive response"_av) == RedisWriter::IOResult::UnknownResponse); cmd.close(); ::close(sck); } } }
31.610619
98
0.592105
[ "vector" ]
4e1bbccf498cca356915b973cb4e13743e64e90c
6,785
cpp
C++
src/VoronoiDiagramMosaics.cpp
lemmingapex/VoronoiDiagramMosaics
dfb9af8abe3765804c114be12f6da53221af47b6
[ "MIT" ]
1
2019-01-10T06:44:22.000Z
2019-01-10T06:44:22.000Z
src/VoronoiDiagramMosaics.cpp
lemmingapex/VoronoiDiagramMosaics
dfb9af8abe3765804c114be12f6da53221af47b6
[ "MIT" ]
null
null
null
src/VoronoiDiagramMosaics.cpp
lemmingapex/VoronoiDiagramMosaics
dfb9af8abe3765804c114be12f6da53221af47b6
[ "MIT" ]
null
null
null
// Scott Wiedemann // CSCI 441 // 11/11/2009 #include <math.h> #include <stdlib.h> #include <cmath> #include <fstream> #include <iostream> #include <assert.h> #include <string> #include <vector> #include <time.h> #include <stdio.h> #include <stdlib.h> #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> using namespace std; #define VPD_MIN 200 #define VPD_DEFAULT 800 #define VPD_MAX 1024 #define MORE_SITES 1 #define FEWER_SITES 2 #define TOGGLE_SITES 3 #define RESET 4 #define MOVE_POINTS 5 #define GL_GLEXT_PROTOTYPES // GLUT window id GLint wid; // (square) viewport dimensions GLint vpd = VPD_DEFAULT; // display list ID GLuint sceneID; // show the sites? bool showsites = false; // rotation bool rotate = false; // resolution of image int x_resolution, y_resolution; class rgb { public: unsigned char r,g,b; }; // pixels in the image rgb *image_pixels; double fRand(double fMin, double fMax) { double f = (double)rand() / RAND_MAX; return fMin + f * (fMax - fMin); } const unsigned int INITAL_NUMBER_OF_SITES = 128; class Site { public: // position between -1 and 1 on the grid double x,y; // speed of the site double velocity; double currentangle; double r,g,b; Site() { x = fRand(-1,1); y = fRand(-1,1); velocity=fRand(-0.5,0.5); r = fRand(0,1); g = fRand(0,1); b = fRand(0,1); } }; vector<Site> sites; void addSites(unsigned int numberOfSitesToAdd) { for(unsigned int i=0; i<numberOfSitesToAdd; i++) { sites.push_back(Site()); } } void removeSites(unsigned int numberOfSitesToRemove) { for(unsigned int i=0; i<numberOfSitesToRemove && sites.size() > 0; i++) { sites.pop_back(); } } void draw_scene() { for(unsigned int i=0; i<sites.size(); i++) { glLoadIdentity(); if(rotate) { sites[i].currentangle += sites[i].velocity; } glRotated(sites[i].currentangle, 0, 0, 1); glTranslated(sites[i].x, sites[i].y, 0); glBegin(GL_TRIANGLE_FAN); double ix = floor(((sites[i].x+1.0)/2.0)*x_resolution); double iy = floor(((sites[i].y+1.0)/2.0)*y_resolution); ix = min(max(ix, 0.0), x_resolution-1.0); iy = min(max(iy, 0.0), y_resolution-1.0); int imageIndex = ix+(y_resolution-1-iy)*x_resolution; rgb rgbAtxy = image_pixels[imageIndex]; glColor3d( (double)rgbAtxy.r/255.0, (double)rgbAtxy.g/255.0, (double)rgbAtxy.b/255.0); //glColor3d(sites[i].r,sites[i].g,sites[i].b); glVertex3d(0,0,0); int res=35; for(int j=0; j<=res; j++) { double alpha = (j*360.0/res)*(M_PI / 180.0); glVertex4d(cos(alpha), sin(alpha), 1, 0); } glEnd(); if(showsites) { glLoadIdentity(); glRotated(sites[i].currentangle, 0, 0, 1); glBegin(GL_POINTS); glColor3d(0,0,0); glVertex3d(sites[i].x,sites[i].y,-0.5); glEnd(); } if(rotate) { glutPostRedisplay(); } } } void draw(void) { glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-1,-1,1,1,1,-3); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); /* ensure we're drawing to the correct GLUT window */ glutSetWindow(wid); /* clear the color buffers */ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); /* DRAW WHAT IS IN THE DISPLAY LIST */ draw_scene(); /* flush the pipeline */ glFlush(); /* look at our handiwork */ glutSwapBuffers(); } void reset() { showsites = false; rotate = false; sites.clear(); vector<Site>().swap(sites); addSites(INITAL_NUMBER_OF_SITES); } void keyboard(GLubyte key, GLint x, GLint y) { switch(key) { case 27: exit(0); default: break; } glutPostRedisplay(); } void menu(int value) { switch(value) { case MORE_SITES: addSites(sites.size()); break; case FEWER_SITES: removeSites(sites.size()/2); break; case TOGGLE_SITES: showsites=!showsites; break; case RESET: reset(); break; case MOVE_POINTS: rotate=!rotate; break; default: break; } glutPostRedisplay(); } /* handle resizing the glut window */ void reshape(GLint vpw, GLint vph) { glutSetWindow(wid); /* maintain a square viewport, not too small, not too big */ if( vpw < vph ) { vpd = vph; } else { vpd = vpw; } if( vpd < VPD_MIN ) vpd = VPD_MIN; if( vpd > VPD_MAX ) vpd = VPD_MAX; glViewport(0, 0, vpd, vpd); glutReshapeWindow(vpd, vpd); glutPostRedisplay(); } GLint init_glut(GLint *argc, char **argv) { GLint id; glutInit(argc,argv); /* size and placement hints to the window system */ glutInitWindowSize(vpd, vpd); glutInitWindowPosition(10,10); /* double buffered, RGB color mode */ glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); /* create a GLUT window (not drawn until glutMainLoop() is entered) */ id = glutCreateWindow("Voronoi Diagram Mosaics"); /* window size changes */ glutReshapeFunc(reshape); /* keypress handling when the current window has input focus */ glutKeyboardFunc(keyboard); /* window obscured/revealed event handler */ glutVisibilityFunc(NULL); /* handling of keyboard SHIFT, ALT, CTRL keys */ glutSpecialFunc(NULL); /* what to do when mouse cursor enters/exits the current window */ glutEntryFunc(NULL); /* what to do on each display loop iteration */ glutDisplayFunc(draw); /* create menu */ GLint menuID = glutCreateMenu(menu); glutAddMenuEntry("Double number of sites", MORE_SITES); glutAddMenuEntry("Half number of sites", FEWER_SITES); glutAddMenuEntry("Toggle sites", TOGGLE_SITES); glutAddMenuEntry("Reset", RESET); glutAddMenuEntry("Toggle movement", MOVE_POINTS); glutSetMenu(menuID); glutAttachMenu(GLUT_RIGHT_BUTTON); return id; } void init_opengl(void) { /* automatically scale normals to unit length after transformation */ glEnable(GL_NORMALIZE); /* clear to white */ glClearColor(1.0, 1.0, 1.0, 1.0); /* Enable depth test */ glEnable(GL_DEPTH_TEST); } void readFile(string Filename) { ifstream ifs(Filename.c_str()); if(!ifs) { cerr << "ERROR: Can't open file: " << Filename << endl; exit(1); } char c; ifs >> c; assert(c=='P'); ifs >> c; assert(c=='6'); // binary PPMs start with the magic code `P6' ifs >> x_resolution >> y_resolution; int i; ifs >> i; assert(i==255); // all images we'll use have 255 color levels ifs.get(); // need to skip one more byte image_pixels = new rgb[x_resolution*y_resolution]; ifs.read((char*)image_pixels,x_resolution*y_resolution*sizeof(rgb)); } int main(GLint argc, char **argv) { string inputFileName; if(argc != 2) { cerr << "ERROR: No imput file." << endl; cerr << "Usage: " << argv[0] << " <input.ppm>" << endl; exit(1); } else { inputFileName = argv[1]; } readFile(inputFileName); srand(time(0)); addSites(INITAL_NUMBER_OF_SITES); /* initialize GLUT: register callbacks, etc */ wid = init_glut(&argc, argv); /* any OpenGL state initialization we need to do */ init_opengl(); glutMainLoop(); return 0; }
20.314371
74
0.672218
[ "vector" ]
4e1db2ceabd2d48d8e506f4b178b8de683c382eb
3,651
cpp
C++
src/bt-luaengine/app-src/render/ScreenControlRenderer.cpp
puretekniq/batterytech
cc831b2835b7bf4826948831f0274e3d80921339
[ "MIT", "BSD-3-Clause-Clear", "Zlib", "BSD-3-Clause" ]
10
2015-04-07T22:23:31.000Z
2016-03-06T11:48:32.000Z
src/bt-luaengine/app-src/render/ScreenControlRenderer.cpp
robdoesstuff/batterytech
cc831b2835b7bf4826948831f0274e3d80921339
[ "MIT", "BSD-3-Clause-Clear", "Zlib", "BSD-3-Clause" ]
3
2015-05-17T10:45:48.000Z
2016-07-29T18:34:53.000Z
src/bt-luaengine/app-src/render/ScreenControlRenderer.cpp
puretekniq/batterytech
cc831b2835b7bf4826948831f0274e3d80921339
[ "MIT", "BSD-3-Clause-Clear", "Zlib", "BSD-3-Clause" ]
4
2015-05-03T03:00:48.000Z
2016-03-03T12:49:01.000Z
/* * BatteryTech * Copyright (c) 2010 Battery Powered Games LLC. * * This code is a component of BatteryTech and is subject to the 'BatteryTech * End User License Agreement'. Among other important provisions, this * license prohibits the distribution of source code to anyone other than * authorized parties. If you have any questions or would like an additional * copy of the license, please contact: support@batterypoweredgames.com */ #include "ScreenControlRenderer.h" #include <batterytech/render/GLResourceManager.h> #include <batterytech/render/RenderContext.h> #include "../World.h" #include "../ScreenControl.h" #include <batterytech/render/TextRasterRenderer.h> #include <batterytech/util/strx.h> #include "WorldRenderer.h" #include <batterytech/Logger.h> #include <stdio.h> #include "../GameContext.h" #include <batterytech/render/QuadRenderer.h> ScreenControlRenderer::ScreenControlRenderer(GameContext *context, const char *fontTag) { this->context = context; this->fontTag = strDuplicate(fontTag); } ScreenControlRenderer::~ScreenControlRenderer() { delete [] fontTag; } void ScreenControlRenderer::init(BOOL32 newContext) { if (!newContext) { return; } checkGLError("ScreenControlRenderer Init"); } void ScreenControlRenderer::render() { //glFrontFace(GL_CW); ManagedArray<ScreenControl> *controls = context->world->screenControls; context->quadRenderer->startBatch(); for (S32 i = 0; i < controls->getSize(); i++) { ScreenControl *control = controls->array[i]; if (!control->getTextureAssetName()) { continue; } Texture *texture = context->glResourceManager->getTexture(control->getTextureAssetName()); Vector4f &bounds = control->drawableBounds; F32 left = bounds.x; F32 top = bounds.y; F32 right = bounds.z; F32 bottom = bounds.w; F32 width = right-left; F32 height = bottom-top; context->quadRenderer->render(texture, Vector3f(left + width/2, top + height/2, 0), 0, control->textureUVs, Vector2f(width, height), Vector4f(1,1,1,1), TRUE, FALSE, Matrix4f()); } context->quadRenderer->endBatch(); BOOL32 hasLabels = FALSE; for (S32 i = 0; i < controls->getSize(); i++) { ScreenControl *control = controls->array[i]; if (!control->getTextureAssetName()) { continue; } if (control->getLabel() && strlen(control->getLabel()) > 0) { hasLabels = TRUE; } } if (hasLabels) { TextRasterRenderer *textRenderer = context->worldRenderer->getTextRenderer(fontTag); if (textRenderer) { textRenderer->startText(); F32 textHeight = textRenderer->getHeight(); for (S32 i = 0; i < controls->getSize(); i++) { ScreenControl *control = controls->array[i]; if (!control->getTextureAssetName() || !control->getLabel() || strlen(control->getLabel()) == 0) { continue; } F32 tw = textRenderer->measureWidth(control->getLabel()); Vector4f &bounds = control->drawableBounds; F32 left = bounds.x; F32 top = bounds.y; F32 right = bounds.z; F32 bottom = bounds.w; F32 diff = tw / (right - left); F32 scale = 1.0f; if (diff > .9f) { // reduce label to stay inside button scale = .9f / diff; tw = (right - left) * .9f; } F32 textX, textY; textX = left + ((right - left)/2) - tw/2; textY = top + (bottom - top)/2 + (textHeight*scale)/2; textRenderer->render(control->getLabel(), textX, textY, scale); } textRenderer->finishText(); } else { char buf[255]; sprintf(buf, "Error - ScreenControlRenderer can't find font tagged [%s]", fontTag); logmsg(buf); } } }
33.805556
180
0.667762
[ "render" ]
4e1e4d9197e30e3b3bd696ffb298922d8ee5d944
253
cpp
C++
DLLBody.cpp
cdinfosys/JITZ80
8b3e231ad0f78e97f9c5033ec6485e9d96ad521f
[ "MIT" ]
null
null
null
DLLBody.cpp
cdinfosys/JITZ80
8b3e231ad0f78e97f9c5033ec6485e9d96ad521f
[ "MIT" ]
null
null
null
DLLBody.cpp
cdinfosys/JITZ80
8b3e231ad0f78e97f9c5033ec6485e9d96ad521f
[ "MIT" ]
null
null
null
#include <Windows.h> #include <memory.h> #include "DLLBody.hpp" //JITZ80Lib::Emulator::CompiledBuffer gCompiledBuffer; //std::vector<uint8_t> gZ80CodeBuffer((size_t)(64u * 1024u), 0u); bool StartInstance() { return true; } void EndInstance() { }
15.8125
65
0.711462
[ "vector" ]
4e21a43236354c566ac18674e796a8242b8c2791
628
cpp
C++
C++/2016/S2.cpp
CallMeTwitch/CCC
94a57d7e68243e1cc6ca258b46d4e477934c301e
[ "MIT" ]
null
null
null
C++/2016/S2.cpp
CallMeTwitch/CCC
94a57d7e68243e1cc6ca258b46d4e477934c301e
[ "MIT" ]
null
null
null
C++/2016/S2.cpp
CallMeTwitch/CCC
94a57d7e68243e1cc6ca258b46d4e477934c301e
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #include <algorithm> using namespace std; int main() { int q, n, t;cin >> q >> n; vector<int> one, two; for (int w=0;w<n;w++) { cin >> t; one.push_back(t); } for (int w=0;w<n;w++) { cin >> t; two.push_back(t); } sort(one.begin(), one.end()); int output = 0; if (q == 1) sort(two.begin(), two.end()); else sort(two.begin(), two.end(), greater<int>()); for (int w=0;w<n;w++) { output += max(one.back(), two.back()); one.pop_back();two.pop_back(); } cout << output; }
19.625
55
0.455414
[ "vector" ]
4e23526ed08f253eea997bd2a61add06073ba378
2,186
cpp
C++
PROX/FOUNDATION/MESH_ARRAY/MESH_ARRAY/src/mesh_array_triangle_circulator.cpp
diku-dk/PROX
c6be72cc253ff75589a1cac28e4e91e788376900
[ "MIT" ]
2
2019-11-27T09:44:45.000Z
2020-01-13T00:24:21.000Z
PROX/FOUNDATION/MESH_ARRAY/MESH_ARRAY/src/mesh_array_triangle_circulator.cpp
erleben/matchstick
1cfdc32b95437bbb0063ded391c34c9ee9b9583b
[ "MIT" ]
null
null
null
PROX/FOUNDATION/MESH_ARRAY/MESH_ARRAY/src/mesh_array_triangle_circulator.cpp
erleben/matchstick
1cfdc32b95437bbb0063ded391c34c9ee9b9583b
[ "MIT" ]
null
null
null
#include <mesh_array_triangle_circulator.h> namespace mesh_array { TriangleCirculator<T3Mesh>::TriangleCirculator() { } TriangleCirculator<T3Mesh>::~TriangleCirculator() { } TriangleCirculator<T3Mesh>::TriangleCirculator(TriangleCirculator const & o) { (*this) = o; } TriangleCirculator<T3Mesh>::TriangleCirculator(VertexRing<T3Mesh> const & VR, Vertex const & v) { this->m_owner = &VR; if(this->m_owner->offset().size()> 0u) { this->m_cur = this->m_owner->offset()[ v.idx() ]; this->m_end = this->m_owner->offset()[ v.idx() + 1u ]; } else { this->m_cur = 0u; this->m_end = 0u; } } bool TriangleCirculator<T3Mesh>::operator==(TriangleCirculator const & o) const { return (this->m_owner == o.m_owner) && (this->m_cur == o.m_cur); } TriangleCirculator<T3Mesh> const & TriangleCirculator<T3Mesh>::operator=(TriangleCirculator<T3Mesh> const & o) { if( this != &o) { this->m_owner = o.m_owner; this->m_cur = o.m_cur; this->m_end = o.m_end; } return *this; } Triangle const * TriangleCirculator<T3Mesh>::operator->() const { return &(this->operator*()); } Triangle * TriangleCirculator<T3Mesh>::operator->() { return &(this->operator*()); } Triangle const & TriangleCirculator<T3Mesh>::operator*() const { if(this->m_cur < this->m_end) { size_t const idx = this->m_owner->V2T()[this->m_cur].second; return this->m_owner->mesh()->triangle( idx ); } return this->m_undefined; } Triangle & TriangleCirculator<T3Mesh>::operator*() { if(this->m_cur < this->m_end) { size_t const idx = this->m_owner->V2T()[this->m_cur].second; return const_cast< T3Mesh * >( this->m_owner->mesh())->triangle( idx ); } return this->m_undefined; } TriangleCirculator<T3Mesh> & TriangleCirculator<T3Mesh>::operator++() { ++(this->m_cur); return (*this); } bool TriangleCirculator<T3Mesh>::operator()() const { return this->m_cur < this->m_end; } } // end namespace mesh_array
23.010526
112
0.596066
[ "mesh" ]
89efa778421c3943240dc5f745f35737303b4c86
10,180
cc
C++
alljoyn_core/test/aservice.cc
liuxiang88/core-alljoyn
549c966482d9b89da84aa528117584e7049916cb
[ "Apache-2.0" ]
33
2018-01-12T00:37:43.000Z
2022-03-24T02:31:36.000Z
alljoyn_core/test/aservice.cc
liuxiang88/core-alljoyn
549c966482d9b89da84aa528117584e7049916cb
[ "Apache-2.0" ]
1
2020-01-05T05:51:27.000Z
2020-01-05T05:51:27.000Z
alljoyn_core/test/aservice.cc
liuxiang88/core-alljoyn
549c966482d9b89da84aa528117584e7049916cb
[ "Apache-2.0" ]
30
2017-12-13T23:24:00.000Z
2022-01-25T02:11:19.000Z
/****************************************************************************** * Copyright (c) Open Connectivity Foundation (OCF), AllJoyn Open Source * Project (AJOSP) Contributors and others. * * SPDX-License-Identifier: Apache-2.0 * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution, and is available at * http://www.apache.org/licenses/LICENSE-2.0 * * Copyright (c) Open Connectivity Foundation and Contributors to AllSeen * Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for * any purpose with or without fee is hereby granted, provided that the * above copyright notice and this permission notice appear in all * copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. ******************************************************************************/ #include <alljoyn/AboutIconObj.h> #include <alljoyn/AboutObj.h> #include <alljoyn/Init.h> #include <alljoyn/BusAttachment.h> #include <alljoyn/BusListener.h> #include <alljoyn/BusObject.h> #include <signal.h> #include <stdio.h> using namespace ajn; static volatile sig_atomic_t s_interrupt = false; static void CDECL_CALL SigIntHandler(int sig) { QCC_UNUSED(sig); s_interrupt = true; } static SessionPort ASSIGNED_SESSION_PORT = 900; class MySessionPortListener : public SessionPortListener { bool AcceptSessionJoiner(ajn::SessionPort sessionPort, const char* joiner, const ajn::SessionOpts& opts) { QCC_UNUSED(joiner); QCC_UNUSED(opts); if (sessionPort != ASSIGNED_SESSION_PORT) { printf("Rejecting join attempt on unexpected session port %d\n", sessionPort); return false; } // std::cout << "Accepting JoinSessionRequest from " << joiner << " (opts.proximity= " << opts.proximity // << ", opts.traffic=" << opts.traffic << ", opts.transports=" << opts.transports << ")." << std::endl; return true; } void SessionJoined(SessionPort sessionPort, SessionId id, const char* joiner) { QCC_UNUSED(sessionPort); QCC_UNUSED(joiner); printf("Session Joined SessionId = %u\n", id); } }; class AboutServiceSampleBusObject : public BusObject { public: AboutServiceSampleBusObject(BusAttachment& bus, const char* path) : BusObject(path) { const InterfaceDescription* test_iface = bus.GetInterface("org.alljoyn.test"); if (test_iface == NULL) { printf("The interfaceDescription pointer for org.alljoyn.test was NULL when it should not have been.\n"); return; } AddInterface(*test_iface, ANNOUNCED); const InterfaceDescription* game_iface = bus.GetInterface("org.alljoyn.game"); if (game_iface == NULL) { printf("The interfaceDescription pointer for org.alljoyn.game was NULL when it should not have been.\n"); return; } AddInterface(*game_iface, ANNOUNCED); const InterfaceDescription* mediaplayer_iface = bus.GetInterface("org.alljoyn.mediaplayer"); if (mediaplayer_iface == NULL) { printf("The interfaceDescription pointer for org.alljoyn.mediaplayer was NULL when it should not have been.\n"); return; } AddInterface(*mediaplayer_iface, ANNOUNCED); /* Register the method handlers with the object */ const MethodEntry methodEntries[] = { { test_iface->GetMember("Foo"), static_cast<MessageReceiver::MethodHandler>(&AboutServiceSampleBusObject::Foo) }, { game_iface->GetMember("Foo"), static_cast<MessageReceiver::MethodHandler>(&AboutServiceSampleBusObject::Foo) }, { mediaplayer_iface->GetMember("Foo"), static_cast<MessageReceiver::MethodHandler>(&AboutServiceSampleBusObject::Foo) } }; AddMethodHandlers(methodEntries, sizeof(methodEntries) / sizeof(methodEntries[0])); } void Foo(const InterfaceDescription::Member* member, Message& msg) { QCC_UNUSED(member); MethodReply(msg, (const MsgArg*)NULL, (size_t)0); } }; static void usage(void) { printf("Usage: aservice [-h <name>] \n\n"); printf("Options:\n"); printf(" -h = Print this help message\n"); printf(" -? = Print this help message\n"); printf(" -t = Advertise over TCP (enables selective advertising)\n"); printf(" -l = Advertise locally (enables selective advertising)\n"); printf(" -u = Advertise over UDP-based ARDP (enables selective advertising)\n"); printf("\n"); } /** Main entry point */ int CDECL_CALL main(int argc, char** argv) { SessionOpts opts(SessionOpts::TRAFFIC_MESSAGES, false, SessionOpts::PROXIMITY_ANY, TRANSPORT_NONE); /*Parse command line arguments */ for (int i = 1; i < argc; ++i) { if (0 == strcmp("-h", argv[i]) || 0 == strcmp("-?", argv[i])) { usage(); exit(0); } else if (0 == strcmp("-t", argv[i])) { opts.transports |= TRANSPORT_TCP; } else if (0 == strcmp("-l", argv[i])) { opts.transports |= TRANSPORT_LOCAL; } else if (0 == strcmp("-u", argv[i])) { opts.transports |= TRANSPORT_UDP; } } /* If no transport option was specifie, then make session options very open */ if (opts.transports == 0) { opts.transports = TRANSPORT_ANY; } printf("opts.transports = 0x%x\n", opts.transports); if (AllJoynInit() != ER_OK) { return 1; } #ifdef ROUTER if (AllJoynRouterInit() != ER_OK) { AllJoynShutdown(); return 1; } #endif /* Install SIGINT handler so Ctrl + C deallocates memory properly */ signal(SIGINT, SigIntHandler); QStatus status; BusAttachment* bus = new BusAttachment("AboutServiceTest", true); status = bus->Start(); if (ER_OK == status) { printf("BusAttachment started.\n"); } else { printf("FAILED to start BusAttachment (%s)\n", QCC_StatusText(status)); exit(1); } status = bus->Connect(); if (ER_OK == status) { printf("BusAttachment connect succeeded. BusAttachment Unique name is %s\n", bus->GetUniqueName().c_str()); } else { printf("FAILED to connect to router node (%s)\n", QCC_StatusText(status)); exit(1); } const char* interfaces = "<node>" "<interface name='org.alljoyn.test'>" " <method name='Foo'>" " </method>" "</interface>" "<interface name='org.alljoyn.game'>" " <method name='Foo'>" " </method>" "</interface>" "<interface name='org.alljoyn.mediaplayer'>" " <method name='Foo'>" " </method>" "</interface>" "</node>"; status = bus->CreateInterfacesFromXml(interfaces); AboutServiceSampleBusObject* aboutServiceSampleBusObject = new AboutServiceSampleBusObject(*bus, "/org/alljoyn/test"); bus->RegisterBusObject(*aboutServiceSampleBusObject); SessionPort sp = ASSIGNED_SESSION_PORT; MySessionPortListener sessionPortListener; status = bus->BindSessionPort(sp, opts, sessionPortListener); if (ER_OK == status) { printf("BindSessionPort succeeded.\n"); } else { printf("BindSessionPort failed (%s)\n", QCC_StatusText(status)); exit(1); } // Setup the about data AboutData aboutData("en"); uint8_t appId[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; status = aboutData.SetAppId(appId, 16); status = aboutData.SetDeviceName("My Device Name"); status = aboutData.SetDeviceId("fakeID"); status = aboutData.SetAppName("Application"); status = aboutData.SetManufacturer("Manufacturer"); status = aboutData.SetModelNumber("123456"); status = aboutData.SetDescription("A poetic description of this application"); status = aboutData.SetDateOfManufacture("2014-03-24"); status = aboutData.SetSoftwareVersion("0.1.2"); status = aboutData.SetHardwareVersion("0.0.1"); status = aboutData.SetSupportUrl("http://www.alljoyn.org"); if (!aboutData.IsValid()) { printf("failed to setup about data.\n"); } AboutIcon icon; status = icon.SetUrl("image/png", "http://www.example.com"); if (ER_OK != status) { printf("Failed to setup the AboutIcon.\n"); } AboutIconObj* aboutIconObj = new AboutIconObj(*bus, icon); // Announce about signal AboutObj* aboutObj = new AboutObj(*bus, BusObject::ANNOUNCED); status = aboutObj->Announce(ASSIGNED_SESSION_PORT, aboutData); if (ER_OK == status) { printf("AboutObj Announce Succeeded.\n"); } else { printf("AboutObj Announce failed (%s)\n", QCC_StatusText(status)); } /* Perform the service asynchronously until the user signals for an exit. */ if (ER_OK == status) { while (s_interrupt == false) { #ifdef _WIN32 Sleep(100); #else usleep(100 * 1000); #endif } } delete aboutObj; delete aboutIconObj; delete aboutServiceSampleBusObject; delete bus; #ifdef ROUTER AllJoynRouterShutdown(); #endif AllJoynShutdown(); return 0; }
37.564576
131
0.611591
[ "object" ]
89f55b284a6378dc2721a04b447742ed0e8819ca
1,106
cpp
C++
cpp/godot-cpp/src/gen/ConvexPolygonShape.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
1
2021-03-16T09:51:00.000Z
2021-03-16T09:51:00.000Z
cpp/godot-cpp/src/gen/ConvexPolygonShape.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
null
null
null
cpp/godot-cpp/src/gen/ConvexPolygonShape.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
null
null
null
#include "ConvexPolygonShape.hpp" #include <core/GodotGlobal.hpp> #include <core/CoreTypes.hpp> #include <core/Ref.hpp> #include <core/Godot.hpp> #include "__icalls.hpp" namespace godot { ConvexPolygonShape::___method_bindings ConvexPolygonShape::___mb = {}; void ConvexPolygonShape::___init_method_bindings() { ___mb.mb_get_points = godot::api->godot_method_bind_get_method("ConvexPolygonShape", "get_points"); ___mb.mb_set_points = godot::api->godot_method_bind_get_method("ConvexPolygonShape", "set_points"); } ConvexPolygonShape *ConvexPolygonShape::_new() { return (ConvexPolygonShape *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, godot::api->godot_get_class_constructor((char *)"ConvexPolygonShape")()); } PoolVector3Array ConvexPolygonShape::get_points() const { return ___godot_icall_PoolVector3Array(___mb.mb_get_points, (const Object *) this); } void ConvexPolygonShape::set_points(const PoolVector3Array points) { ___godot_icall_void_PoolVector3Array(___mb.mb_set_points, (const Object *) this, points); } }
30.722222
217
0.802893
[ "object" ]
89f7ce8ff2dbcc42cfe3363563e29418ea0c629e
505
cpp
C++
test/test_cs.cpp
nspo/compression-cpp
f5cf95830bfbba0a605001e0fea549fefdd94456
[ "BSD-3-Clause" ]
1
2021-11-08T03:17:36.000Z
2021-11-08T03:17:36.000Z
test/test_cs.cpp
nspo/compression-cpp
f5cf95830bfbba0a605001e0fea549fefdd94456
[ "BSD-3-Clause" ]
null
null
null
test/test_cs.cpp
nspo/compression-cpp
f5cf95830bfbba0a605001e0fea549fefdd94456
[ "BSD-3-Clause" ]
null
null
null
#include <gtest/gtest.h> #include <sstream> #include "CircularSuffix.h" TEST(cs, basic) { // NOLINT EXPECT_EQ(circular_suffix::sort<char>("ABRACADABRA!"), (std::vector<size_t>{11, 10, 7, 0, 3, 5, 8, 1, 4, 6, 9, 2})); EXPECT_EQ(circular_suffix::sort<char>("Z"), (std::vector<size_t>{0})); EXPECT_EQ(circular_suffix::sort<char>(""), (std::vector<size_t>{})); EXPECT_EQ(circular_suffix::sort<uint8_t>(std::basic_string<uint8_t>{0, 70, 30}), (std::vector<size_t>{0, 2, 1})); }
38.846154
120
0.631683
[ "vector" ]
89f9c594e2719393ae89560e14964c9f1c87b603
26,683
cpp
C++
src/Storages/RedisStreams/StorageRedisStreams.cpp
tchepavel/ClickHouse
5b9470992e9a45c4c7f669516db02c7e2aab982a
[ "Apache-2.0" ]
null
null
null
src/Storages/RedisStreams/StorageRedisStreams.cpp
tchepavel/ClickHouse
5b9470992e9a45c4c7f669516db02c7e2aab982a
[ "Apache-2.0" ]
null
null
null
src/Storages/RedisStreams/StorageRedisStreams.cpp
tchepavel/ClickHouse
5b9470992e9a45c4c7f669516db02c7e2aab982a
[ "Apache-2.0" ]
null
null
null
#include <Storages/RedisStreams/StorageRedisStreams.h> #include <DataTypes/DataTypeString.h> #include <DataTypes/DataTypesNumber.h> #include <Interpreters/Context.h> #include <Interpreters/InterpreterInsertQuery.h> #include <Interpreters/evaluateConstantExpression.h> #include <Parsers/ASTCreateQuery.h> #include <Parsers/ASTExpressionList.h> #include <Parsers/ASTIdentifier.h> #include <Parsers/ASTInsertQuery.h> #include <Parsers/ASTLiteral.h> #include <Processors/Executors/CompletedPipelineExecutor.h> #include <Storages/ExternalDataSourceConfiguration.h> #include <Storages/RedisStreams/ReadBufferFromRedisStreams.h> #include <Storages/RedisStreams/RedisStreamsSettings.h> #include <Storages/RedisStreams/RedisStreamsSink.h> #include <Storages/RedisStreams/RedisStreamsSource.h> #include <Storages/RedisStreams/WriteBufferToRedisStreams.h> #include <Storages/StorageFactory.h> #include <Storages/StorageMaterializedView.h> #include <base/getFQDNOrHostName.h> #include <Common/logger_useful.h> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string/trim.hpp> #include <Common/Exception.h> #include <Common/Macros.h> #include <Common/config_version.h> #include <Common/formatReadable.h> #include <Common/getNumberOfPhysicalCPUCores.h> #include <Common/parseAddress.h> #include <Common/quoteString.h> #include <Common/setThreadName.h> namespace DB { namespace ErrorCodes { extern const int NOT_IMPLEMENTED; extern const int BAD_ARGUMENTS; extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH; extern const int QUERY_NOT_ALLOWED; extern const int CANNOT_CONNECT_REDIS; } namespace { static const auto RESCHEDULE_MS = 500; static const auto BACKOFF_TRESHOLD = 32000; static const auto MAX_THREAD_WORK_DURATION_MS = 60000; } StorageRedisStreams::StorageRedisStreams( const StorageID & table_id_, ContextPtr context_, const ColumnsDescription & columns_, std::unique_ptr<RedisStreamsSettings> redis_settings_, const String & collection_name_, bool is_attach_) : IStorage(table_id_) , WithContext(context_->getGlobalContext()) , redis_settings(std::move(redis_settings_)) , streams(parseStreams(getContext()->getMacros()->expand(redis_settings->redis_stream_list.value))) , broker(getContext()->getMacros()->expand(redis_settings->redis_broker)) , group(getContext()->getMacros()->expand(redis_settings->redis_group_name.value)) , consumer_id( redis_settings->redis_common_consumer_id.value.empty() ? getDefaultConsumerId(table_id_) : getContext()->getMacros()->expand(redis_settings->redis_common_consumer_id.value)) , num_consumers(redis_settings->redis_num_consumers.value) , log(&Poco::Logger::get("StorageRedisStreams (" + table_id_.table_name + ")")) , semaphore(0, num_consumers) , intermediate_ack(redis_settings->redis_ack_every_batch.value) , ack_on_select(redis_settings->redis_ack_on_select.value) , settings_adjustments(createSettingsAdjustments()) , thread_per_consumer(redis_settings->redis_thread_per_consumer.value) , collection_name(collection_name_) , milliseconds_to_wait(RESCHEDULE_MS) , is_attach(is_attach_) { StorageInMemoryMetadata storage_metadata; storage_metadata.setColumns(columns_); setInMemoryMetadata(storage_metadata); auto parsed_address = parseAddress(broker, 6379); sw::redis::ConnectionOptions connect_options; connect_options.host = parsed_address.first; connect_options.port = parsed_address.second; connect_options.socket_timeout = std::chrono::seconds(1); auto redis_password = redis_settings->redis_password.value; if (redis_password.empty() && getContext()->getConfigRef().has("redis.password")) { redis_password = getContext()->getConfigRef().getString("redis.password"); } if (!redis_password.empty()) { connect_options.password = std::move(redis_password); } try { redis = std::make_shared<sw::redis::Redis>(connect_options); LOG_DEBUG(log, "Redis successfully pinged: {}", redis->ping()); if (redis_settings->redis_manage_consumer_groups.value) { for (const auto & stream : streams) { redis->xgroup_create(stream, group, redis_settings->redis_consumer_groups_start_id.value, true); } } } catch (const sw::redis::Error & e) { tryLogCurrentException(log); if (!is_attach) throw Exception(ErrorCodes::CANNOT_CONNECT_REDIS, "Cannot connect to Redis. Error message: {}", e.what()); } /// TODO: should I create consumer groups? auto task_count = thread_per_consumer ? num_consumers : 1; try { for (size_t i = 0; i < task_count; ++i) { auto task = getContext()->getMessageBrokerSchedulePool().createTask(log->name(), [this, i] { threadFunc(i); }); task->deactivate(); tasks.emplace_back(std::make_shared<TaskContext>(std::move(task))); } } catch (...) { tryLogCurrentException(__PRETTY_FUNCTION__); } } SettingsChanges StorageRedisStreams::createSettingsAdjustments() { SettingsChanges result; // Needed for backward compatibility if (!redis_settings->input_format_skip_unknown_fields.changed) { // Always skip unknown fields regardless of the context (JSON or TSKV) redis_settings->input_format_skip_unknown_fields = true; } if (!redis_settings->input_format_allow_errors_ratio.changed) { redis_settings->input_format_allow_errors_ratio = 0.; } for (const auto & setting : *redis_settings) { const auto & name = setting.getName(); if (name.find("redis_") == std::string::npos) result.emplace_back(name, setting.getValue()); } return result; } Names StorageRedisStreams::parseStreams(String stream_list) { Names result; boost::split(result, stream_list, [](char c) { return c == ','; }); for (String & stream : result) { boost::trim(stream); } return result; } String StorageRedisStreams::getDefaultConsumerId(const StorageID & table_id_) const { return fmt::format("{}-{}-{}-{}-{}", VERSION_NAME, getFQDNOrHostName(), table_id_.database_name, table_id_.table_name, group); } Pipe StorageRedisStreams::read( const Names & column_names, const StorageSnapshotPtr & storage_snapshot, SelectQueryInfo & /* query_info */, ContextPtr local_context, QueryProcessingStage::Enum /* processed_stage */, size_t /* max_block_size */, unsigned /* num_streams */) { if (num_created_consumers == 0) return {}; if (!local_context->getSettingsRef().stream_like_engine_allow_direct_select) throw Exception(ErrorCodes::QUERY_NOT_ALLOWED, "Direct select is not allowed. To enable use setting `stream_like_engine_allow_direct_select`"); if (mv_attached) throw Exception(ErrorCodes::QUERY_NOT_ALLOWED, "Cannot read from StorageRedisStreams with attached materialized views"); /// Always use all consumers at once, otherwise SELECT may not read messages from all partitions. Pipes pipes; std::vector<std::shared_ptr<RedisStreamsSource>> sources; sources.reserve(num_created_consumers); pipes.reserve(num_created_consumers); auto modified_context = Context::createCopy(local_context); modified_context->applySettingsChanges(settings_adjustments); // Claim as many consumers as requested, but don't block for (size_t i = 0; i < num_created_consumers; ++i) { const auto source = std::make_shared<RedisStreamsSource>(*this, storage_snapshot, modified_context, column_names, log, 1, ack_on_select); pipes.emplace_back(source); sources.emplace_back(source); } LOG_DEBUG(log, "Starting reading {} streams", pipes.size()); return Pipe::unitePipes(std::move(pipes)); } SinkToStoragePtr StorageRedisStreams::write(const ASTPtr &, const StorageMetadataPtr & metadata_snapshot, ContextPtr local_context) { auto modified_context = Context::createCopy(local_context); modified_context->applySettingsChanges(settings_adjustments); std::string stream = modified_context->getSettingsRef().stream_like_engine_insert_queue.changed ? modified_context->getSettingsRef().stream_like_engine_insert_queue.value : ""; if (stream.empty()) { if (streams.size() > 1) { throw Exception( ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH, "This Redis Streams engine reads from multiple streams. You must specify `stream_like_engine_insert_queue` to choose the stream to write to"); } else { stream = streams[0]; } } return std::make_shared<RedisStreamsSink>(*this, metadata_snapshot, modified_context, stream); } void StorageRedisStreams::startup() { try { for (size_t i = 0; i < num_consumers; ++i) { pushReadBuffer(createReadBuffer(consumer_id + "_" + std::to_string(i))); ++num_created_consumers; } for (auto & task : tasks) { task->holder->activateAndSchedule(); } } catch (...) { tryLogCurrentException(__PRETTY_FUNCTION__); } } void StorageRedisStreams::shutdown() { for (auto & task : tasks) { // Interrupt streaming thread task->stream_cancelled = true; LOG_TRACE(log, "Waiting for cleanup"); task->holder->deactivate(); } for (size_t i = 0; i < num_created_consumers; ++i) auto buffer = popReadBuffer(); if (redis_settings->redis_manage_consumer_groups.value) { for (const auto & stream : streams) { redis->xgroup_destroy(stream, group); } } } void StorageRedisStreams::pushReadBuffer(ConsumerBufferPtr buffer) { std::lock_guard lock(mutex); buffers.push_back(buffer); semaphore.set(); } ConsumerBufferPtr StorageRedisStreams::popReadBuffer() { return popReadBuffer(std::chrono::milliseconds::zero()); } ConsumerBufferPtr StorageRedisStreams::popReadBuffer(std::chrono::milliseconds timeout) { // Wait for the first free buffer if (timeout == std::chrono::milliseconds::zero()) semaphore.wait(); else { if (!semaphore.tryWait(timeout.count())) return nullptr; } // Take the first available buffer from the list std::lock_guard lock(mutex); auto buffer = buffers.back(); buffers.pop_back(); return buffer; } ProducerBufferPtr StorageRedisStreams::createWriteBuffer(const std::string & stream) { return std::make_shared<WriteBufferToRedisStreams>(redis, stream, std::nullopt, 1, 1024); } ConsumerBufferPtr StorageRedisStreams::createReadBuffer(const std::string & id) { return std::make_shared<ReadBufferFromRedisStreams>( redis, group, id, log, getPollMaxBatchSize(), getClaimMaxBatchSize(), getPollTimeoutMillisecond(), redis_settings->redis_min_time_for_claim.totalMilliseconds(), intermediate_ack, streams); } size_t StorageRedisStreams::getMaxBlockSize() const { return redis_settings->redis_max_block_size.changed ? redis_settings->redis_max_block_size.value : (getContext()->getSettingsRef().max_insert_block_size.value / num_consumers); } size_t StorageRedisStreams::getPollMaxBatchSize() const { size_t batch_size = redis_settings->redis_poll_max_batch_size.changed ? redis_settings->redis_poll_max_batch_size.value : getContext()->getSettingsRef().max_block_size.value; return std::min(batch_size, getMaxBlockSize()); } size_t StorageRedisStreams::getClaimMaxBatchSize() const { size_t batch_size = redis_settings->redis_claim_max_batch_size.changed ? redis_settings->redis_claim_max_batch_size.value : getContext()->getSettingsRef().max_block_size.value; return std::min(batch_size, getMaxBlockSize()); } size_t StorageRedisStreams::getPollTimeoutMillisecond() const { return redis_settings->redis_poll_timeout_ms.changed ? redis_settings->redis_poll_timeout_ms.totalMilliseconds() : getContext()->getSettingsRef().stream_poll_timeout_ms.totalMilliseconds(); } bool StorageRedisStreams::checkDependencies(const StorageID & table_id) { // Check if all dependencies are attached auto dependencies = DatabaseCatalog::instance().getDependencies(table_id); if (dependencies.empty()) return true; // Check the dependencies are ready? for (const auto & db_tab : dependencies) { auto table = DatabaseCatalog::instance().tryGetTable(db_tab, getContext()); if (!table) return false; // If it materialized view, check it's target table auto * materialized_view = dynamic_cast<StorageMaterializedView *>(table.get()); if (materialized_view && !materialized_view->tryGetTargetTable()) return false; // Check all its dependencies if (!checkDependencies(db_tab)) return false; } return true; } void StorageRedisStreams::threadFunc(size_t idx) { assert(idx < tasks.size()); auto task = tasks[idx]; try { auto table_id = getStorageID(); auto dependencies_count = DatabaseCatalog::instance().getDependencies(table_id).size(); if (dependencies_count) { auto start_time = std::chrono::steady_clock::now(); mv_attached.store(true); // Keep streaming as long as there are attached views and streaming is not cancelled while (!task->stream_cancelled) { if (!checkDependencies(table_id)) { /// For this case, we can not wait for watch thread to wake up break; } LOG_DEBUG(log, "Started streaming to {} attached views", dependencies_count); if (streamToViews()) { if (milliseconds_to_wait < BACKOFF_TRESHOLD) milliseconds_to_wait *= 2; break; } else { milliseconds_to_wait = RESCHEDULE_MS; } auto ts = std::chrono::steady_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(ts - start_time); if (duration.count() > MAX_THREAD_WORK_DURATION_MS) { LOG_TRACE(log, "Thread work duration limit exceeded. Reschedule."); break; } } } } catch (...) { tryLogCurrentException(__PRETTY_FUNCTION__); } mv_attached.store(false); // Wait for attached views if (!task->stream_cancelled) { task->holder->scheduleAfter(milliseconds_to_wait); } } bool StorageRedisStreams::streamToViews() { Stopwatch watch; auto table_id = getStorageID(); auto table = DatabaseCatalog::instance().getTable(table_id, getContext()); if (!table) throw Exception("Engine table " + table_id.getNameForLogs() + " doesn't exist.", ErrorCodes::LOGICAL_ERROR); auto storage_snapshot = getStorageSnapshot(getInMemoryMetadataPtr(), getContext()); // Create an INSERT query for streaming data auto insert = std::make_shared<ASTInsertQuery>(); insert->table_id = table_id; size_t block_size = getMaxBlockSize(); auto redis_context = Context::createCopy(getContext()); redis_context->makeQueryContext(); redis_context->applySettingsChanges(settings_adjustments); // Create a stream for each consumer and join them in a union stream // Only insert into dependent views and expect that input blocks contain virtual columns InterpreterInsertQuery interpreter(insert, redis_context, false, true, true); auto block_io = interpreter.execute(); // Create a stream for each consumer and join them in a union stream std::vector<std::shared_ptr<RedisStreamsSource>> sources; Pipes pipes; auto stream_count = thread_per_consumer ? 1 : num_created_consumers; sources.reserve(stream_count); pipes.reserve(stream_count); for (size_t i = 0; i < stream_count; ++i) { auto source = std::make_shared<RedisStreamsSource>( *this, storage_snapshot, redis_context, block_io.pipeline.getHeader().getNames(), log, block_size, ack_on_select); sources.emplace_back(source); pipes.emplace_back(source); // Limit read batch to maximum block size to allow DDL StreamLocalLimits limits; limits.speed_limits.max_execution_time = redis_settings->redis_flush_interval_ms.changed ? redis_settings->redis_flush_interval_ms : getContext()->getSettingsRef().stream_flush_interval_ms; limits.timeout_overflow_mode = OverflowMode::BREAK; source->setLimits(limits); } auto pipe = Pipe::unitePipes(std::move(pipes)); size_t rows = 0; { block_io.pipeline.complete(std::move(pipe)); block_io.pipeline.setProgressCallback([&](const Progress & progress) { rows += progress.read_rows.load(); }); CompletedPipelineExecutor executor(block_io.pipeline); executor.execute(); } bool some_stream_is_stalled = false; for (auto & source : sources) { some_stream_is_stalled = some_stream_is_stalled || source->isStalled(); source->ack(); } UInt64 milliseconds = watch.elapsedMilliseconds(); LOG_DEBUG(log, "Pushing {} rows to {} took {} ms.", formatReadableQuantity(rows), table_id.getNameForLogs(), milliseconds); return some_stream_is_stalled; } void registerStorageRedisStreams(StorageFactory & factory) { auto creator_fn = [](const StorageFactory::Arguments & args) { ASTs & engine_args = args.engine_args; size_t args_count = engine_args.size(); bool has_settings = args.storage_def->settings; auto redis_settings = std::make_unique<RedisStreamsSettings>(); auto named_collection = getExternalDataSourceConfiguration(args.engine_args, *redis_settings, args.getLocalContext()); if (has_settings) { redis_settings->loadFromQuery(*args.storage_def); } // Check arguments and settings #define CHECK_REDIS_STORAGE_ARGUMENT(ARG_NUM, PAR_NAME, EVAL) \ /* One of the four required arguments is not specified */ \ if (args_count < (ARG_NUM) && (ARG_NUM) <= 3 && \ !redis_settings->PAR_NAME.changed) \ { \ throw Exception( \ "Required parameter '" #PAR_NAME "' " \ "for storage Redis not specified", \ ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); \ } \ if (args_count >= (ARG_NUM)) \ { \ /* The same argument is given in two places */ \ if (has_settings && \ redis_settings->PAR_NAME.changed) \ { \ throw Exception( \ "The argument №" #ARG_NUM " of storage Redis " \ "and the parameter '" #PAR_NAME "' " \ "in SETTINGS cannot be specified at the same time", \ ErrorCodes::BAD_ARGUMENTS); \ } \ /* move engine args to settings */ \ else \ { \ if ((EVAL) == 1) \ { \ engine_args[(ARG_NUM)-1] = \ evaluateConstantExpressionAsLiteral( \ engine_args[(ARG_NUM)-1], \ args.getLocalContext()); \ } \ if ((EVAL) == 2) \ { \ engine_args[(ARG_NUM)-1] = \ evaluateConstantExpressionOrIdentifierAsLiteral( \ engine_args[(ARG_NUM)-1], \ args.getLocalContext()); \ } \ redis_settings->PAR_NAME = \ engine_args[(ARG_NUM)-1]->as<ASTLiteral &>().value; \ } \ } /** Arguments of engine is following: * - Redis broker list * - List of streams * - Group ID * - Common part of consumer Id (string) * - Number of consumers * - Create consumer groups on engine startup and delete them at the end. (bool) * - The id of message in stream from which the consumer groups start to read * - Do intermediate acks when the batch consumed and handled * - Ack messages after select query * - Timeout for single poll from Redis * - Maximum amount of messages to be polled in a single Redis poll * - Maximum amount of messages to be claimed from other consumers in a single Redis poll * - Minimum time in milliseconds after which consumers will start to claim messages * - Max block size for background consumption * - Timeout for flushing data from Redis * - Provide independent thread for each consumer * - Redis password */ String collection_name; if (named_collection) { collection_name = assert_cast<const ASTIdentifier *>(args.engine_args[0].get())->name(); } else { /* 0 = raw, 1 = evaluateConstantExpressionAsLiteral, 2=evaluateConstantExpressionOrIdentifierAsLiteral */ CHECK_REDIS_STORAGE_ARGUMENT(1, redis_broker, 0) CHECK_REDIS_STORAGE_ARGUMENT(2, redis_stream_list, 1) CHECK_REDIS_STORAGE_ARGUMENT(3, redis_group_name, 2) CHECK_REDIS_STORAGE_ARGUMENT(4, redis_common_consumer_id, 2) CHECK_REDIS_STORAGE_ARGUMENT(5, redis_num_consumers, 0) CHECK_REDIS_STORAGE_ARGUMENT(6, redis_manage_consumer_groups, 0) CHECK_REDIS_STORAGE_ARGUMENT(7, redis_consumer_groups_start_id, 2) CHECK_REDIS_STORAGE_ARGUMENT(8, redis_ack_every_batch, 0) CHECK_REDIS_STORAGE_ARGUMENT(9, redis_ack_on_select, 0) CHECK_REDIS_STORAGE_ARGUMENT(10, redis_poll_timeout_ms, 0) CHECK_REDIS_STORAGE_ARGUMENT(11, redis_poll_max_batch_size, 0) CHECK_REDIS_STORAGE_ARGUMENT(12, redis_claim_max_batch_size, 0) CHECK_REDIS_STORAGE_ARGUMENT(13, redis_min_time_for_claim, 0) CHECK_REDIS_STORAGE_ARGUMENT(14, redis_max_block_size, 0) CHECK_REDIS_STORAGE_ARGUMENT(15, redis_flush_interval_ms, 0) CHECK_REDIS_STORAGE_ARGUMENT(16, redis_thread_per_consumer, 0) CHECK_REDIS_STORAGE_ARGUMENT(17, redis_password, 2) } #undef CHECK_REDIS_STORAGE_ARGUMENT auto num_consumers = redis_settings->redis_num_consumers.value; auto physical_cpu_cores = getNumberOfPhysicalCPUCores(); if (num_consumers > physical_cpu_cores) { throw Exception(ErrorCodes::BAD_ARGUMENTS, "Number of consumers can not be bigger than {}", physical_cpu_cores); } else if (num_consumers < 1) { throw Exception("Number of consumers can not be lower than 1", ErrorCodes::BAD_ARGUMENTS); } if (redis_settings->redis_max_block_size.changed && redis_settings->redis_max_block_size.value < 1) { throw Exception("redis_max_block_size can not be lower than 1", ErrorCodes::BAD_ARGUMENTS); } if (redis_settings->redis_poll_max_batch_size.changed && redis_settings->redis_poll_max_batch_size.value < 1) { throw Exception("redis_poll_max_batch_size can not be lower than 1", ErrorCodes::BAD_ARGUMENTS); } return std::make_shared<StorageRedisStreams>(args.table_id, args.getContext(), args.columns, std::move(redis_settings), collection_name, args.attach); }; factory.registerStorage("RedisStreams", creator_fn, StorageFactory::StorageFeatures{ .supports_settings = true, }); } NamesAndTypesList StorageRedisStreams::getVirtuals() const { auto result = NamesAndTypesList{ {"_stream", std::make_shared<DataTypeString>()}, {"_key", std::make_shared<DataTypeString>()}, {"_timestamp", std::make_shared<DataTypeUInt64>()}, {"_sequence_number", std::make_shared<DataTypeUInt64>()}, {"_group", std::make_shared<DataTypeString>()}, {"_consumer", std::make_shared<DataTypeString>()} }; return result; } Names StorageRedisStreams::getVirtualColumnNames() const { auto result = Names { "_stream", "_key", "_timestamp", "_sequence_number", "_group", "_consumer" }; return result; } }
38.78343
158
0.618746
[ "vector" ]
89fcee8f806ac9fc29430806f521233890a6d8a2
1,784
cpp
C++
SimpleTests/SolverTests/ConjugateGradientUnpreconditioned.cpp
WenjieXu/ogs
0cd1b72ec824833bf949a8bbce073c82158ee443
[ "BSD-4-Clause" ]
1
2021-11-21T17:29:38.000Z
2021-11-21T17:29:38.000Z
SimpleTests/SolverTests/ConjugateGradientUnpreconditioned.cpp
WenjieXu/ogs
0cd1b72ec824833bf949a8bbce073c82158ee443
[ "BSD-4-Clause" ]
null
null
null
SimpleTests/SolverTests/ConjugateGradientUnpreconditioned.cpp
WenjieXu/ogs
0cd1b72ec824833bf949a8bbce073c82158ee443
[ "BSD-4-Clause" ]
null
null
null
#include <fstream> #include <iostream> #include "LinAlg/Solvers/CG.h" #include "LinAlg/Sparse/CRSMatrix.h" #include "sparse.h" #include "vector_io.h" //#include "timeMeasurement.h" #ifdef _OPENMP #include <omp.h> #endif int main(int argc, char *argv[]) { (void) argc; (void) argv; // *** reading matrix in crs format from file std::string fname("/work/Thomas Fischer/data/testmat.bin"); // std::ifstream in(fname.c_str(), std::ios::binary); MathLib::CRSMatrix<double, unsigned> *mat (new MathLib::CRSMatrix<double, unsigned>(fname)); /* double *A(NULL); unsigned *iA(NULL), *jA(NULL), n; if (in) { std::cout << "reading matrix from " << fname << " ... " << std::flush; CS_read(in, n, iA, jA, A); in.close(); std::cout << " ok" << std::endl; } unsigned nnz(iA[n]); */ unsigned n (mat->getNRows()); std::cout << "Parameters read: n=" << n << std::endl; double *x(new double[n]); double *b(new double[n]); // *** init start vector x for (size_t k(0); k<n; k++) { x[k] = 1.0; } // *** read rhs fname = "/work/Thomas Fischer/data/rhs.dat"; std::ifstream in(fname.c_str()); if (in) { read (in, n, b); in.close(); } else { std::cout << "problem reading rhs - initializing b with 1.0" << std::endl; for (size_t k(0); k<n; k++) { b[k] = 1.0; } } std::cout << "solving system with CG method ... " << std::flush; time_t start_time, end_time; time(&start_time); // double cg_time (cputime(0.0)); double eps (1.0e-6); unsigned steps (4000); CG (mat, b, x, eps, steps); // cg_time = cputime(cg_time); time(&end_time); std::cout << " in " << steps << " iterations (residuum is " << eps << ") took " << /*cg_time <<*/ " sec time and " << (end_time-start_time) << " sec" << std::endl; delete mat; delete [] x; delete [] b; return 0; }
24.438356
164
0.602018
[ "vector" ]
89ffaf9264d7f3ad868d2b08e9270e425c70dfb5
487
cpp
C++
atcoder-dp/frog2.cpp
rranjan14/cp-solutions
9614508efbed1e4ee8b970b5eed535d782a5783f
[ "MIT" ]
null
null
null
atcoder-dp/frog2.cpp
rranjan14/cp-solutions
9614508efbed1e4ee8b970b5eed535d782a5783f
[ "MIT" ]
null
null
null
atcoder-dp/frog2.cpp
rranjan14/cp-solutions
9614508efbed1e4ee8b970b5eed535d782a5783f
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int N, K; cin >> N >> K; vector<int> heights(N); vector<int> dp(N, INT_MAX); for (int &height : heights) { cin >> height; } dp[0] = 0; for (int i = 0; i < N; i++) { for (int j = i + 1; j <= i + K; j++) { if (j < N) dp[j] = min(dp[j], dp[i] + abs(heights[j] - heights[i])); } } cout << dp[N - 1] << "\n"; return 0; }
19.48
73
0.396304
[ "vector" ]
d60020e72e4c7c8960666ccd7d71a8605509d24b
1,046
cpp
C++
problemsets/UVA/UVA514.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/UVA/UVA514.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/UVA/UVA514.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
/** * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * */ #include <cstdio> #include <cstdlib> #include <cstring> #include <cctype> #include <cmath> #include <string> #include <algorithm> #include <sstream> #include <map> #include <set> #include <queue> using namespace std; vector<int> A, B, P; int N; int main() { while (scanf("%d", &N)) { if (!N) break; A.resize(N); B.resize(N); for (int i = 1; i <= N; i++) A[i-1] = i; while (1) { scanf("%d", &B[0]); if (!B[0]) break; for (int i = 1; i < N; i++) scanf("%d", &B[i]); int i, j; P.clear(); for (i = j = 0; j < N; ) { while (P.size() && B[j]==P.back()) j++, P.pop_back(); while (i < N && A[i]!=B[j]) P.push_back(A[i]), i++; if (i == N) break; i++, j++; } if (j < N) puts("No"); else puts("Yes"); } putchar('\n'); } return 0; }
20.92
69
0.426386
[ "vector" ]
d601923b6ec179522d3514dc1abc0da5b55a76dc
5,912
cc
C++
engines/ep/tests/module_tests/collections/manifest_test.cc
trondn/kv_engine
c0d4366e2feb8e7e64be7e3c6c9fc3cfd68a97c6
[ "BSD-3-Clause" ]
24
2015-03-17T02:41:27.000Z
2022-03-19T20:28:08.000Z
engines/ep/tests/module_tests/collections/manifest_test.cc
trondn/kv_engine
c0d4366e2feb8e7e64be7e3c6c9fc3cfd68a97c6
[ "BSD-3-Clause" ]
2
2016-06-14T23:17:06.000Z
2016-07-25T11:55:13.000Z
engines/ep/tests/module_tests/collections/manifest_test.cc
trondn/kv_engine
c0d4366e2feb8e7e64be7e3c6c9fc3cfd68a97c6
[ "BSD-3-Clause" ]
20
2015-01-27T09:36:16.000Z
2017-03-22T20:06:56.000Z
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2017 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "collections/manifest.h" #include <gtest/gtest.h> #include <limits> TEST(ManifestTest, validation) { std::vector<std::string> invalidManifests = { "", // empty "not json", "{\"revision\"", // short "{\"revision\":[]}", // illegal revision type "{\"revision\":0," // valid revision "\"separator\":0}", // illegal separator type "{\"revision\":0," // valid revision "\"separator\":\":\"," // valid separator "\"collections\":0}", // illegal collections type "{\"revision\":0," "\"separator\":\":\"," "\"collections\":[0]}", // illegal collection "{\"revision\":0," "\"separator\":\"\"," // invalid separator "\"collections\":[\"beer\"]}", "{\"revision\":0," // no separator "\"collections\":[\"beer\"]}", "{\"separator\":\"," // no revision "\"collections\":[\"beer\"]}", "{\"revision\":0," "\"separator\":\":\",", // no collections "{\"revision\":2147483648" // to large for int32 "\"separator\":\":\"," "\"collections\":[\"$default\",\"beer\",\"brewery\"]}" "{\"revision\":0," // separator > 250 "\"separator\":\"!-------------------------------------------------" "------------------------------------------------------------------" "------------------------------------------------------------------" "------------------------------------------------------------------" "---\"," "\"collections\":[\"beer\",\"brewery\"]}", "{\"revision\":0" "\"separator\":\":\"," // illegal $ prefixed name "\"collections\":[\"$magic\",\"beer\",\"brewery\"]}", "{\"revision\":0" "\"separator\":\":\"," // illegal _ prefixed name "\"collections\":[\"beer\",\"_brewery\"]}"}; std::vector<std::string> validManifests = { "{\"revision\":0," "\"separator\":\":\"," "\"collections\":[]}", "{\"revision\":0," "\"separator\":\":\"," "\"collections\":[\"$default\",\"beer\",\"brewery\"]}", "{\"revision\":0," "\"separator\":\":\"," "\"collections\":[\"beer\",\"brewery\"]}", "{\"revision\":0," "\"separator\":\"--------------------------------------------------" "------------------------------------------------------------------" "------------------------------------------------------------------" "------------------------------------------------------------------" "--\"," "\"collections\":[\"beer\",\"brewery\"]}"}; for (auto& manifest : invalidManifests) { EXPECT_THROW(Collections::Manifest m(manifest), std::invalid_argument) << "Didn't throw exception for an invalid manifest " + manifest; } for (auto& manifest : validManifests) { EXPECT_NO_THROW(Collections::Manifest m(manifest)) << "Exception thrown for valid manifest " + manifest; } } TEST(ManifestTest, defaultManifest) { // Default construction gives the default manifest // $default, rev 0 and separator of :: Collections::Manifest manifest; EXPECT_EQ(0, manifest.getRevision()); EXPECT_TRUE(manifest.doesDefaultCollectionExist()); EXPECT_EQ("::", manifest.getSeparator()); } TEST(ManifestTest, getRevision) { std::vector<std::pair<int32_t, std::string> > validManifests = { {0, "{\"revision\":0," "\"separator\":\":\"," "\"collections\":[\"$default\",\"beer\",\"brewery\"]}"}, {std::numeric_limits<int32_t>::max(), "{\"revision\":2147483647," "\"separator\":\":\"," "\"collections\":[\"$default\",\"beer\",\"brewery\"]}"}, }; for (auto& manifest : validManifests) { Collections::Manifest m(manifest.second); EXPECT_EQ(manifest.first, m.getRevision()); } } TEST(ManifestTest, getSeparator) { std::vector<std::pair<std::string, std::string> > validManifests = { {":", "{\"revision\":0," "\"separator\":\":\"," "\"collections\":[\"$default\",\"beer\",\"brewery\"]}"}}; for (auto& manifest : validManifests) { Collections::Manifest m(manifest.second); EXPECT_EQ(manifest.first, m.getSeparator()); } } TEST(ManifestTest, findCollection) { std::string manifest = "{\"revision\":0," "\"separator\":\":\"," "\"collections\":[\"$default\",\"beer\",\"brewery\"]}"; std::vector<std::string> collectionT = {"$default", "beer", "brewery"}; std::vector<std::string> collectionF = {"$Default", "cheese", "bees"}; Collections::Manifest m(manifest); for (auto& collection : collectionT) { EXPECT_NE(m.end(), m.find(collection)); } for (auto& collection : collectionF) { EXPECT_EQ(m.end(), m.find(collection)); } }
36.04878
80
0.463972
[ "vector" ]
d602bc82651f3caf59f3894f7ea8c34adbcd94b0
1,241
cpp
C++
cpp/leetcode95.cpp
A666AHL/WeChat_SmallApp
90138471d2e2020a80d4a51fc7e26f5359d445a9
[ "MIT" ]
1
2019-04-07T16:05:14.000Z
2019-04-07T16:05:14.000Z
cpp/leetcode95.cpp
A666AHL/writeLeetcode
90138471d2e2020a80d4a51fc7e26f5359d445a9
[ "MIT" ]
null
null
null
cpp/leetcode95.cpp
A666AHL/writeLeetcode
90138471d2e2020a80d4a51fc7e26f5359d445a9
[ "MIT" ]
null
null
null
// leetcode95.Unique Binary Search Trees II /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<TreeNode*> generate(int start, int end) { vector<TreeNode*> res; if(start > end) { res.emplace_back(nullptr); return res; } for(int i = start; i <= end; i++) { // 得到root=i的右子树 vector<TreeNode*> left_tree = generate(start, i-1); // 得到root=i的左子树 vector<TreeNode*> right_tree = generate(i+1, end); for(int j = 0; j < left_tree.size(); j++) { for(int k = 0; k < right_tree.size(); k++) { TreeNode* node = new TreeNode(i); //生成节点node=i res.emplace_back(node); node->left = left_tree[j]; node->right = right_tree[k]; } } } return res; } vector<TreeNode*> generateTrees(int n) { if(n == 0) return {}; return generate(1, n); } };
27.577778
66
0.460113
[ "vector" ]
d602c65b208fa1d36398b62bd7d6738c0d96ed32
3,390
cpp
C++
WitchEngine3/src/WE3/geometry/WEGeometryTriBuffer.cpp
jadnohra/World-Of-Football
fc4c9dd23e0b2d8381ae8f62b1c387af7f28fcfc
[ "MIT" ]
3
2018-12-02T14:09:22.000Z
2021-11-22T07:14:05.000Z
WitchEngine3/src/WE3/geometry/WEGeometryTriBuffer.cpp
jadnohra/World-Of-Football
fc4c9dd23e0b2d8381ae8f62b1c387af7f28fcfc
[ "MIT" ]
1
2018-12-03T22:54:38.000Z
2018-12-03T22:54:38.000Z
WitchEngine3/src/WE3/geometry/WEGeometryTriBuffer.cpp
jadnohra/World-Of-Football
fc4c9dd23e0b2d8381ae8f62b1c387af7f28fcfc
[ "MIT" ]
2
2020-09-22T21:04:14.000Z
2021-05-24T09:43:28.000Z
#include "WEGeometryTriBuffer.h" #include "WEGeometryTriBufferContainer.h" namespace WE { GeometryTriBuffer::Simplification::Simplification() { stepLimit = -1; mode = M_Planar; loopMode = LM_Iterate; considerAesthetics = true; useIslands = true; planarAngle = degToRad(2.5f); } void GeometryTriBuffer::destroy() { mTris.destroy(); } void GeometryTriBuffer::append(GeometryVertexBuffer& VB, GeometryIndexBuffer* pIB, const Matrix4x3Base* pTransf) { //destroy(); bool byFace = true; if (pIB == NULL) { assrt(false); return; } GeometryIndexBuffer& IB = *pIB; /* bool byFace = (pIB != NULL); if (byFace) { if (pIB->getElementCount() == 0) { byFace = false; } } if (VB.getElementCount() == 0) { return; } */ if ((VB.getElementCount() == 0) || (IB.getElementCount() == 0)) { return; } const RenderElementProfile& vprofile = VB.getProfile(); RenderUINT vertexCount = VB.getElementCount(); void* vb = VB.bufferPtr(); RenderSubElIndex el_position = vprofile.findSub(D3DDECLUSAGE_POSITION); if (el_position < 0) { return; } float* pos; Point points[3]; if (byFace) { RenderUINT faceCount = IB.getElementCount() / 3; const RenderElementProfile& iprofile = IB.getProfile(); void* ib = IB.bufferPtr(); RenderUINT oldCount = mTris.size; mTris.resize(oldCount + faceCount); TriangleEx1* el = mTris.el; RenderUINT indices[3]; for (RenderUINT f = oldCount, i = 0; f < mTris.size; f++, i += 3) { iprofile.face_get(ib, i, indices); for (int j = 0; j < 3; j++) { pos = vprofile.getF(vb, indices[j], el_position); el[f].vertices[j].set(MExpand3(pos)); } if (pTransf) { pTransf->transformPoint(el[f].vertices[0]); pTransf->transformPoint(el[f].vertices[1]); pTransf->transformPoint(el[f].vertices[2]); } el[f].initNormal(); } } } void GeometryTriBuffer::append(GeometryTriBuffer& container) { RenderUINT faceCount = container.mTris.size; RenderUINT oldCount = mTris.size; mTris.resize(oldCount + faceCount); for (RenderUINT f = oldCount, cf = 0; f < mTris.size; ++f, ++cf) { mTris.el[f] = container.mTris.el[cf]; } } void GeometryTriBuffer::transform(const Matrix4x3Base& transf) { for (TriBuffer::Index i = 0; i < mTris.size; ++i) { transf.transformPoint(mTris.el[i].vertices[0]); transf.transformPoint(mTris.el[i].vertices[1]); transf.transformPoint(mTris.el[i].vertices[2]); transf.transformVector(mTris.el[i].normal); } } void GeometryTriBuffer::render(Renderer& renderer, const RenderColor* pColor) { /* DebugBypass* pBypass = getDebugBypass(); for (TriBuffer::RenderUINT i = 0; i < mTris.size; ++i) { if (pBypass->currTri == pBypass->renderTri) { renderer.draw(mTris.el[i], &Matrix4x3Base::kIdentity, &RenderColor::kRed, false, false); } else { renderer.draw(mTris.el[i], &Matrix4x3Base::kIdentity, pColor, false, true); } ++pBypass->currTri; } */ for (TriBuffer::Index i = 0; i < mTris.size; ++i) { renderer.draw(mTris.el[i], &Matrix4x3Base::kIdentity, pColor, false, true); } } void GeometryTriBuffer::addToVol(AAB& vol) { for (TriBuffer::Index i = 0; i < mTris.size; ++i) { mTris.el[i].addTo(vol); } } }
19.371429
115
0.626254
[ "render", "transform" ]
d619a4702d50188b9d731c397eb0f4f74641672e
683
cpp
C++
AtCoder/ABC106/b.cpp
Takumi1122/data-structure-algorithm
6b9f26e4dbba981f034518a972ecfc698b86d837
[ "MIT" ]
null
null
null
AtCoder/ABC106/b.cpp
Takumi1122/data-structure-algorithm
6b9f26e4dbba981f034518a972ecfc698b86d837
[ "MIT" ]
null
null
null
AtCoder/ABC106/b.cpp
Takumi1122/data-structure-algorithm
6b9f26e4dbba981f034518a972ecfc698b86d837
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define rep(i, n) for (int i = 0; i < (n); ++i) using namespace std; using ll = long long; using P = pair<int, int>; using Graph = vector<vector<int>>; vector<ll> enum_divisors(ll n) { vector<ll> res; for (ll i = 1; i * i <= n; ++i) { if (n % i == 0) { res.push_back(i); // 重複しないならば i の相方である N/i も push if (n / i != i) res.push_back(n / i); } } // 小さい順に並び替える sort(res.begin(), res.end()); return res; } int main() { int n; cin >> n; int ans = 0; for (int i = 1; i <= n; i++) { if (i % 2 == 0) continue; auto a = enum_divisors(i); if (a.size() == 8) ans++; } cout << ans << endl; return 0; }
19.514286
47
0.508053
[ "vector" ]
d62123a6a09c8263d68c4eec912cf6e76aa50de7
677
cpp
C++
49 group-anagrams/c/main.v2.cpp
o-jules/LeetCode-Problems
e8b31d0dd93f6e49e385ef35689e51f6935cd7cb
[ "MIT" ]
null
null
null
49 group-anagrams/c/main.v2.cpp
o-jules/LeetCode-Problems
e8b31d0dd93f6e49e385ef35689e51f6935cd7cb
[ "MIT" ]
null
null
null
49 group-anagrams/c/main.v2.cpp
o-jules/LeetCode-Problems
e8b31d0dd93f6e49e385ef35689e51f6935cd7cb
[ "MIT" ]
null
null
null
vector<vector<string>> groupAnagrams(vector<string>& strs) { vector<vector<string>> result; if (!strs.empty()) { unordered_map<string, size_t> hashMap; for (string str : strs) { string s(str); sort(s.begin(), s.end()); unordered_map<string, size_t>::iterator got = hashMap.find(s); if (got == hashMap.end()) { vector<string> temp; temp.push_back(str); result.push_back(temp); hashMap.insert({s, result.size()-1}); } else { result[got->second].push_back(str); } } } return result; }
25.074074
72
0.496307
[ "vector" ]
d6244928752dddd2297195d2ccf01bbf45a170c9
7,495
hpp
C++
libraries/clchain/include/clchain/subchain.hpp
abitmore/Eden
90bf6c5c7297b1dc79745b0ea001e1c48e7ba170
[ "MIT" ]
35
2021-04-02T02:17:39.000Z
2021-11-23T17:46:50.000Z
libraries/clchain/include/clchain/subchain.hpp
abitmore/Eden
90bf6c5c7297b1dc79745b0ea001e1c48e7ba170
[ "MIT" ]
323
2021-04-07T15:07:39.000Z
2022-01-25T01:11:38.000Z
libraries/clchain/include/clchain/subchain.hpp
abitmore/Eden
90bf6c5c7297b1dc79745b0ea001e1c48e7ba170
[ "MIT" ]
8
2021-05-10T01:19:47.000Z
2022-01-24T23:05:00.000Z
#pragma once #include <clchain/graphql_connection.hpp> #include <eosio/bytes.hpp> #include <eosio/fixed_bytes.hpp> #include <eosio/name.hpp> #include <eosio/time.hpp> namespace subchain { struct creator_action { uint64_t seq; eosio::name receiver; }; EOSIO_REFLECT(creator_action, seq, receiver) struct action { uint64_t seq = 0; eosio::name firstReceiver; eosio::name receiver; eosio::name name; std::optional<creator_action> creatorAction; eosio::bytes hexData; }; EOSIO_REFLECT(action, seq, firstReceiver, receiver, name, creatorAction, hexData) struct transaction { eosio::checksum256 id; std::vector<action> actions; }; EOSIO_REFLECT(transaction, id, actions) struct eosio_block { uint32_t num = 0; eosio::checksum256 id; eosio::checksum256 previous; eosio::time_point timestamp; std::vector<transaction> transactions; }; EOSIO_REFLECT(eosio_block, num, id, previous, timestamp, transactions) struct block { uint32_t num = 0; eosio::checksum256 previous; eosio_block eosioBlock; }; EOSIO_REFLECT(block, num, previous, eosioBlock) struct block_with_id : block { eosio::checksum256 id; }; EOSIO_REFLECT(block_with_id, id, base block) inline const block& deref(const block& block) { return block; } inline const block& deref(const std::unique_ptr<block>& block) { return *block; } inline const block_with_id& deref(const block_with_id& block) { return block; } inline const block_with_id& deref(const std::unique_ptr<block_with_id>& block) { return *block; } inline uint32_t get_eosio_num(uint32_t num) { return num; } inline uint32_t get_eosio_num(const auto& block) { return deref(block).eosioBlock.num; } inline constexpr auto by_eosio_num = [](const auto& a, const auto& b) { return get_eosio_num(a) < get_eosio_num(b); }; struct block_log { enum status { appended, duplicate, unlinkable, }; static constexpr const char* status_str[] = { "appended", "duplicate", "unlinkable", }; std::vector<std::unique_ptr<block_with_id>> blocks; uint32_t irreversible = 0; auto lower_bound_by_num(uint32_t num) const { if (blocks.empty()) return blocks.end(); auto head = blocks.front()->num; if (num <= head) return blocks.begin(); if (num - head < blocks.size()) return blocks.begin() + (num - head); return blocks.end(); } auto upper_bound_by_num(uint32_t num) const { if (num == ~uint32_t(0)) return blocks.end(); return lower_bound_by_num(num + 1); } const block_with_id* head() const { if (blocks.empty()) return nullptr; return &*blocks.back(); } const block_with_id* block_by_num(uint32_t num) const { auto it = lower_bound_by_num(num); if (it != blocks.end() && (*it)->num == num) return &**it; return nullptr; } const block_with_id* block_by_eosio_num(uint32_t num) const { auto it = std::lower_bound(blocks.begin(), blocks.end(), num, by_eosio_num); if (it != blocks.end() && get_eosio_num(*it) == num) return &**it; return nullptr; } const block_with_id* block_before_num(uint32_t num) const { auto it = lower_bound_by_num(num); if (it != blocks.begin()) return &*it[-1]; return nullptr; } const block_with_id* block_before_eosio_num(uint32_t num) const { auto it = std::lower_bound(blocks.begin(), blocks.end(), num, by_eosio_num); if (it != blocks.begin()) return &*it[-1]; return nullptr; } std::pair<status, size_t> add_block(const block_with_id& block) { size_t num_forked = 0; auto it = lower_bound_by_num(block.num); if (it != blocks.end() && block.id == it[0]->id) return {duplicate, 0}; if (it == blocks.begin() && block.num != 1) return {unlinkable, 0}; if (it != blocks.begin()) if (block.previous != it[-1]->id || block.num != it[-1]->num + 1) return {unlinkable, 0}; if (it != blocks.end() && it[0]->num <= irreversible) return {unlinkable, 0}; num_forked = blocks.end() - it; blocks.erase(it, blocks.end()); blocks.push_back(std::make_unique<block_with_id>(block)); return {appended, num_forked}; } size_t undo(uint32_t block_num) { if (block_num <= irreversible) return 0; auto it = lower_bound_by_num(block_num); if (it == blocks.end() || it[0]->num != block_num) return 0; size_t num_removed = blocks.end() - it; blocks.erase(it, blocks.end()); return num_removed; } // Keep only 1 irreversible block void trim() { auto it = lower_bound_by_num(irreversible); blocks.erase(blocks.begin(), it); } }; EOSIO_REFLECT2(block_log, blocks, irreversible) constexpr inline const char BlockConnection_name[] = "BlockConnection"; constexpr inline const char BlockEdge_name[] = "BlockEdge"; using BlockConnection = clchain::Connection<clchain::ConnectionConfig<std::reference_wrapper<const block_with_id>, BlockConnection_name, BlockEdge_name>>; struct BlockLog { block_log& log; BlockConnection blocks(std::optional<uint32_t> gt, std::optional<uint32_t> ge, std::optional<uint32_t> lt, std::optional<uint32_t> le, std::optional<uint32_t> first, std::optional<uint32_t> last, std::optional<std::string> before, std::optional<std::string> after) const { return clchain::make_connection<BlockConnection, uint32_t>( gt, ge, lt, le, first, last, before, after, // log.blocks, // [](auto& block) { return block->num; }, // [](auto& block) { return std::cref(*block); }, // [&](auto& blocks, auto block_num) { return log.lower_bound_by_num(block_num); }, [&](auto& blocks, auto block_num) { return log.upper_bound_by_num(block_num); }); } const block_with_id* head() const { return log.head(); } const block_with_id* irreversible() const { return log.block_by_num(log.irreversible); } const block_with_id* blockByNum(uint32_t num) const { return log.block_by_num(num); } const block_with_id* blockByEosioNum(uint32_t num) const { return log.block_by_eosio_num(num); } }; EOSIO_REFLECT2(BlockLog, method(blocks, "gt", "ge", "lt", "le", "first", "last", "before", "after"), head, irreversible, method(blockByNum, "num"), method(blockByEosioNum, "num")) } // namespace subchain
32.445887
100
0.566778
[ "vector" ]
d627f6eaf535bec1c447f6cd524ae48df13970cb
2,906
cpp
C++
View/WorldDragWidget.cpp
bbgw/Klampt
3c022da372c81646ec9f7492fad499740431d38b
[ "BSD-3-Clause" ]
null
null
null
View/WorldDragWidget.cpp
bbgw/Klampt
3c022da372c81646ec9f7492fad499740431d38b
[ "BSD-3-Clause" ]
null
null
null
View/WorldDragWidget.cpp
bbgw/Klampt
3c022da372c81646ec9f7492fad499740431d38b
[ "BSD-3-Clause" ]
null
null
null
#include "WorldDragWidget.h" #include <GLdraw/drawextra.h> using namespace GLDraw; WorldDragWidget::WorldDragWidget(RobotWorld* _world) :world(_world),active(true),robotsActive(true),objectsActive(true),terrainsActive(false), highlightColor(1,1,1,0.3),lineColor(1,0.5,0),lineWidth(5.0),dragging(false),hoverID(-1),highlightID(-1) {} void WorldDragWidget::Set(RobotWorld* _world) { world = _world; } void WorldDragWidget::Enable(bool _active) { active = _active; } void WorldDragWidget::SetHighlight(bool value) { hasHighlight = value; if(hasHighlight && hoverID >= 0) { //update the object's color originalFaceColor = world->GetAppearance(hoverID).faceColor; world->GetAppearance(hoverID).faceColor.blend(originalFaceColor,highlightColor,highlightColor.rgba[3]); highlightID = hoverID; } else if(!hasHighlight && highlightID >= 0) { //restore the object's color world->GetAppearance(highlightID).faceColor = originalFaceColor; } } bool WorldDragWidget::Hover(int x,int y,Camera::Viewport& viewport,double& distance) { if(!active) return false; Ray3D r; viewport.getClickSource(x,y,r.source); viewport.getClickVector(x,y,r.direction); hoverID = -1; distance = Inf; if(robotsActive) { int body; Vector3 localpt; RobotInfo* rob = world->ClickRobot(r,body,localpt); if(rob) { hoverPt = localpt; hoverID = world->RobotLinkID(rob-&world->robots[0],body); const Geometry::AnyCollisionGeometry3D& geom = world->GetGeometry(hoverID); Vector3 worldpt = geom.GetTransform()*localpt; distance = worldpt.distance(r.source); dragPt = worldpt; } } if(objectsActive) { Vector3 localpt; RigidObjectInfo* obj = world->ClickObject(r,localpt); if(obj) { Vector3 worldpt = obj->object->T*localpt; Real d=worldpt.distance(r.source); if(d < distance) { distance = d; hoverPt = localpt; hoverID = world->RigidObjectID(obj-&world->rigidObjects[0]); dragPt = worldpt; } } } hoverDistance = distance; if(hoverID >= 0) { return true; } return false; } bool WorldDragWidget::BeginDrag(int x,int y,Camera::Viewport& viewport,double& distance) { if(!Hover(x,y,viewport,distance)) return false; dragging = true; return true; } void WorldDragWidget::Drag(int dx,int dy,Camera::Viewport& viewport) { Vector3 v; viewport.getMovementVectorAtDistance(dx,dy,hoverDistance,v); dragPt += v; } void WorldDragWidget::EndDrag() { dragging = false; } void WorldDragWidget::DrawGL(Camera::Viewport& viewport) { if(hoverID < 0) return; if(hasFocus) { const Geometry::AnyCollisionGeometry3D& geom = world->GetGeometry(hoverID); glDisable(GL_LIGHTING); lineColor.setCurrentGL(); glLineWidth(lineWidth); glBegin(GL_LINES); glVertex3v(geom.GetTransform()*hoverPt); glVertex3v(dragPt); glEnd(); glLineWidth(1); } }
26.18018
107
0.697178
[ "geometry", "object" ]
d63408636524f17b9e16d386f034a508ca72d545
3,508
hpp
C++
agency/cuda/execution/execution_policy/parallel_execution_policy.hpp
nerikhman/agency
966ac59101f2fc3561a86b11874fbe8de361d0e4
[ "BSD-3-Clause" ]
129
2016-08-18T23:24:15.000Z
2022-03-25T12:06:05.000Z
agency/cuda/execution/execution_policy/parallel_execution_policy.hpp
nerikhman/agency
966ac59101f2fc3561a86b11874fbe8de361d0e4
[ "BSD-3-Clause" ]
86
2016-08-19T03:43:33.000Z
2020-07-20T14:27:41.000Z
agency/cuda/execution/execution_policy/parallel_execution_policy.hpp
nerikhman/agency
966ac59101f2fc3561a86b11874fbe8de361d0e4
[ "BSD-3-Clause" ]
23
2016-08-18T23:52:13.000Z
2022-02-28T16:28:20.000Z
#pragma once #include <agency/detail/config.hpp> #include <agency/execution/execution_policy/basic_execution_policy.hpp> #include <agency/cuda/execution/executor/parallel_executor.hpp> #include <agency/cuda/execution/executor/grid_executor.hpp> #include <agency/cuda/execution/executor/multidevice_executor.hpp> #include <agency/cuda/device.hpp> namespace agency { namespace cuda { class parallel_execution_policy : public basic_execution_policy<parallel_agent, cuda::parallel_executor, parallel_execution_policy> { private: using super_t = basic_execution_policy<parallel_agent, cuda::parallel_executor, parallel_execution_policy>; public: using super_t::basic_execution_policy; }; const parallel_execution_policy par{}; class parallel_execution_policy_2d : public basic_execution_policy<parallel_agent_2d, cuda::parallel_executor, parallel_execution_policy_2d> { private: using super_t = basic_execution_policy<parallel_agent_2d, cuda::parallel_executor, parallel_execution_policy_2d>; public: using super_t::basic_execution_policy; }; const parallel_execution_policy_2d par2d{}; template<class Index> __AGENCY_ANNOTATION basic_execution_policy< agency::detail::basic_execution_agent<agency::bulk_guarantee_t::parallel_t,Index>, agency::cuda::parallel_executor > parnd(const agency::lattice<Index>& domain) { using policy_type = agency::basic_execution_policy< agency::detail::basic_execution_agent<agency::bulk_guarantee_t::parallel_t,Index>, agency::cuda::parallel_executor >; typename policy_type::param_type param(domain); return policy_type{param}; } template<class Shape> __AGENCY_ANNOTATION basic_execution_policy< agency::detail::basic_execution_agent<agency::bulk_guarantee_t::parallel_t,Shape>, agency::cuda::parallel_executor > parnd(const Shape& shape) { return cuda::parnd(agency::make_lattice(shape)); } template<class ParallelPolicy, __AGENCY_REQUIRES( agency::detail::policy_is_parallel<ParallelPolicy>::value )> __AGENCY_ANNOTATION auto replace_executor(const ParallelPolicy& policy, const grid_executor& exec) -> decltype(agency::replace_executor(policy, cuda::parallel_executor(exec))) { // create a parallel_executor from the grid_executor return agency::replace_executor(policy, cuda::parallel_executor(exec)); } // this overload is called on e.g. par.on(device(0)) template<class ParallelPolicy, __AGENCY_REQUIRES( agency::detail::policy_is_parallel<ParallelPolicy>::value )> __AGENCY_ANNOTATION auto replace_executor(const ParallelPolicy& policy, device_id device) -> decltype(agency::replace_executor(policy, cuda::grid_executor(device))) { // create a grid_executor from the device_id return agency::replace_executor(policy, cuda::grid_executor(device)); } // this overload is called on e.g. par.on(all_devices()) template<class ParallelPolicy, class Range, __AGENCY_REQUIRES( detail::is_range_of_device_id<Range>::value and agency::detail::policy_is_parallel<ParallelPolicy>::value )> auto replace_executor(const ParallelPolicy& policy, const Range& devices) -> decltype(agency::replace_executor(policy, multidevice_executor(detail::devices_to_grid_executors(devices)))) { // turn the range of device_id into a vector of grid_executors return agency::replace_executor(policy, multidevice_executor(detail::devices_to_grid_executors(devices))); } } // end cuda } // end agency
29.728814
140
0.777366
[ "shape", "vector" ]
d63414f5f3077388cc3b6f51d79bf391ceef03e3
4,248
hpp
C++
tm_kit/basic/transaction/v2/TransactionDataStore.hpp
cd606/tm_basic
ea2d13b561dd640161823a5e377f35fcb7fe5d48
[ "Apache-2.0" ]
1
2020-05-22T08:47:02.000Z
2020-05-22T08:47:02.000Z
tm_kit/basic/transaction/v2/TransactionDataStore.hpp
cd606/tm_basic
ea2d13b561dd640161823a5e377f35fcb7fe5d48
[ "Apache-2.0" ]
null
null
null
tm_kit/basic/transaction/v2/TransactionDataStore.hpp
cd606/tm_basic
ea2d13b561dd640161823a5e377f35fcb7fe5d48
[ "Apache-2.0" ]
null
null
null
#ifndef TM_KIT_BASIC_TRANSACTION_V2_TRANSACTION_DATA_STORE_HPP_ #define TM_KIT_BASIC_TRANSACTION_V2_TRANSACTION_DATA_STORE_HPP_ #include <unordered_map> #include <type_traits> #include <mutex> #include <thread> #include <chrono> namespace dev { namespace cd606 { namespace tm { namespace basic { namespace transaction { namespace v2 { template <class DI, class KeyHashType = std::hash<typename DI::Key>, bool MutexProtected=true> struct TransactionDataStore { static constexpr bool IsMutexProtected = MutexProtected; using KeyHash = KeyHashType; using Mutex = std::conditional_t<MutexProtected,std::mutex,bool>; using Lock = std::conditional_t<MutexProtected, std::lock_guard<std::mutex>, bool>; using GlobalVersion = std::conditional_t<(MutexProtected && std::is_integral_v<typename DI::GlobalVersion>),std::atomic<typename DI::GlobalVersion>,typename DI::GlobalVersion>; using DataMap = std::unordered_map< typename DI::Key , infra::VersionedData<typename DI::Version, std::optional<typename DI::Data>, typename DI::VersionCmp> , KeyHash >; mutable Mutex mutex_; DataMap dataMap_; GlobalVersion globalVersion_; void waitForGlobalVersion(typename DI::GlobalVersion const &v) { if constexpr (IsMutexProtected) { while (globalVersion_ < v) { ;//std::this_thread::sleep_for(std::chrono::microseconds(10)); } } } typename DI::Update createFullUpdateNotification(std::vector<typename DI::Key> const &keys) const { Lock _(mutex_); std::vector<typename DI::OneUpdateItem> updates; for (auto const &key : keys) { auto iter = dataMap_.find(key); if (iter == dataMap_.end()) { updates.push_back({typename DI::OneFullUpdateItem { infra::withtime_utils::makeValueCopy(key) , typename DI::Version {} , std::nullopt }}); } else { updates.push_back({typename DI::OneFullUpdateItem { infra::withtime_utils::makeValueCopy(key) , infra::withtime_utils::makeValueCopy(iter->second.version) , infra::withtime_utils::makeValueCopy(iter->second.data) }}); } } return typename DI::Update { globalVersion_ , std::move(updates) }; } typename DI::FullUpdate createFullUpdateNotificationWithoutVariant(std::vector<typename DI::Key> const &keys) const { Lock _(mutex_); std::vector<typename DI::OneFullUpdateItem> updates; for (auto const &key : keys) { auto iter = dataMap_.find(key); if (iter == dataMap_.end()) { updates.push_back(typename DI::OneFullUpdateItem { infra::withtime_utils::makeValueCopy(key) , typename DI::Version {} , std::nullopt }); } else { updates.push_back(typename DI::OneFullUpdateItem { infra::withtime_utils::makeValueCopy(key) , infra::withtime_utils::makeValueCopy(iter->second.version) , infra::withtime_utils::makeValueCopy(iter->second.data) }); } } return typename DI::FullUpdate { globalVersion_ , std::move(updates) }; } }; template <class DI, class KeyHashType = std::hash<typename DI::Key>, bool MutexProtected=true> using TransactionDataStorePtr = std::shared_ptr<TransactionDataStore<DI,KeyHashType,MutexProtected>>; template <class DI, class KeyHashType = std::hash<typename DI::Key>, bool MutexProtected=true> using TransactionDataStoreConstPtr = std::shared_ptr<TransactionDataStore<DI,KeyHashType,MutexProtected> const>; } } } } } } #endif
42.059406
184
0.576271
[ "vector" ]
d634b6ec79b5c47364ae6c3ac705e23d03354ae3
9,007
cpp
C++
examples/factory/src/main.cpp
Sciroccogti/my_project_with_aff3ct
9f1986f36324bbf1bef5fd08166958b11d32e96a
[ "MIT" ]
11
2017-06-06T13:59:34.000Z
2020-10-20T21:19:41.000Z
examples/factory/src/main.cpp
bonben/my_project_with_aff3ct
b866bbd4352a3baa89fdb673137383408038a206
[ "MIT" ]
17
2019-10-24T12:55:33.000Z
2022-03-24T08:41:09.000Z
examples/factory/src/main.cpp
bonben/my_project_with_aff3ct
b866bbd4352a3baa89fdb673137383408038a206
[ "MIT" ]
18
2019-01-28T20:40:41.000Z
2022-02-10T13:50:42.000Z
#include <functional> #include <exception> #include <iostream> #include <cstdlib> #include <memory> #include <vector> #include <string> #include <aff3ct.hpp> using namespace aff3ct; struct params { float ebn0_min = 0.00f; // minimum SNR value float ebn0_max = 10.01f; // maximum SNR value float ebn0_step = 1.00f; // SNR step float R; // code rate (R=K/N) std::unique_ptr<factory::Source ::parameters> source; std::unique_ptr<factory::Codec_repetition::parameters> codec; std::unique_ptr<factory::Modem ::parameters> modem; std::unique_ptr<factory::Channel ::parameters> channel; std::unique_ptr<factory::Monitor_BFER ::parameters> monitor; std::unique_ptr<factory::Terminal ::parameters> terminal; }; void init_params(int argc, char** argv, params &p); struct modules { std::unique_ptr<module::Source<>> source; std::unique_ptr<module::Codec_SIHO<>> codec; std::unique_ptr<module::Modem<>> modem; std::unique_ptr<module::Channel<>> channel; std::unique_ptr<module::Monitor_BFER<>> monitor; module::Encoder<>* encoder; module::Decoder_SIHO<>* decoder; std::vector<const module::Module*> list; // list of module pointers declared in this structure }; void init_modules(const params &p, modules &m); struct utils { std::unique_ptr<tools::Sigma<>> noise; // a sigma noise type std::vector<std::unique_ptr<tools::Reporter>> reporters; // list of reporters dispayed in the terminal std::unique_ptr<tools::Terminal> terminal; // manage the output text in the terminal }; void init_utils(const params &p, const modules &m, utils &u); int main(int argc, char** argv) { // get the AFF3CT version const std::string v = "v" + std::to_string(tools::version_major()) + "." + std::to_string(tools::version_minor()) + "." + std::to_string(tools::version_release()); std::cout << "#----------------------------------------------------------" << std::endl; std::cout << "# This is a basic program using the AFF3CT library (" << v << ")" << std::endl; std::cout << "# Feel free to improve it as you want to fit your needs." << std::endl; std::cout << "#----------------------------------------------------------" << std::endl; std::cout << "#" << std::endl; params p; init_params (argc, argv, p); // create and initialize the parameters from the command line with factories modules m; init_modules(p, m ); // create and initialize the modules utils u; init_utils (p, m, u ); // create and initialize the utils // display the legend in the terminal u.terminal->legend(); // sockets binding (connect the sockets of the tasks = fill the input sockets with the output sockets) using namespace module; (*m.encoder)[enc::sck::encode ::U_K ].bind((*m.source )[src::sck::generate ::U_K ]); (*m.modem )[mdm::sck::modulate ::X_N1].bind((*m.encoder)[enc::sck::encode ::X_N ]); (*m.channel)[chn::sck::add_noise ::X_N ].bind((*m.modem )[mdm::sck::modulate ::X_N2]); (*m.modem )[mdm::sck::demodulate ::Y_N1].bind((*m.channel)[chn::sck::add_noise ::Y_N ]); (*m.decoder)[dec::sck::decode_siho ::Y_N ].bind((*m.modem )[mdm::sck::demodulate ::Y_N2]); (*m.monitor)[mnt::sck::check_errors::U ].bind((*m.encoder)[enc::sck::encode ::U_K ]); (*m.monitor)[mnt::sck::check_errors::V ].bind((*m.decoder)[dec::sck::decode_siho::V_K ]); // loop over the various SNRs for (auto ebn0 = p.ebn0_min; ebn0 < p.ebn0_max; ebn0 += p.ebn0_step) { // compute the current sigma for the channel noise const auto esn0 = tools::ebn0_to_esn0 (ebn0, p.R); const auto sigma = tools::esn0_to_sigma(esn0 ); u.noise->set_noise(sigma, ebn0, esn0); // update the sigma of the modem and the channel m.codec ->set_noise(*u.noise); m.modem ->set_noise(*u.noise); m.channel->set_noise(*u.noise); // display the performance (BER and FER) in real time (in a separate thread) u.terminal->start_temp_report(); // run the simulation chain while (!m.monitor->fe_limit_achieved() && !u.terminal->is_interrupt()) { (*m.source )[src::tsk::generate ].exec(); (*m.encoder)[enc::tsk::encode ].exec(); (*m.modem )[mdm::tsk::modulate ].exec(); (*m.channel)[chn::tsk::add_noise ].exec(); (*m.modem )[mdm::tsk::demodulate ].exec(); (*m.decoder)[dec::tsk::decode_siho ].exec(); (*m.monitor)[mnt::tsk::check_errors].exec(); } // display the performance (BER and FER) in the terminal u.terminal->final_report(); // reset the monitor and the terminal for the next SNR m.monitor->reset(); u.terminal->reset(); // if user pressed Ctrl+c twice, exit the SNRs loop if (u.terminal->is_over()) break; } // display the statistics of the tasks (if enabled) std::cout << "#" << std::endl; tools::Stats::show(m.list, true); std::cout << "# End of the simulation" << std::endl; return 0; } void init_params(int argc, char** argv, params &p) { p.source = std::unique_ptr<factory::Source ::parameters>(new factory::Source ::parameters()); p.codec = std::unique_ptr<factory::Codec_repetition::parameters>(new factory::Codec_repetition::parameters()); p.modem = std::unique_ptr<factory::Modem ::parameters>(new factory::Modem ::parameters()); p.channel = std::unique_ptr<factory::Channel ::parameters>(new factory::Channel ::parameters()); p.monitor = std::unique_ptr<factory::Monitor_BFER ::parameters>(new factory::Monitor_BFER ::parameters()); p.terminal = std::unique_ptr<factory::Terminal ::parameters>(new factory::Terminal ::parameters()); std::vector<factory::Factory::parameters*> params_list = { p.source .get(), p.codec .get(), p.modem .get(), p.channel.get(), p.monitor.get(), p.terminal.get() }; // parse the command for the given parameters and fill them factory::Command_parser cp(argc, argv, params_list, true); if (cp.parsing_failed()) { cp.print_help (); cp.print_warnings(); cp.print_errors (); std::exit(1); } std::cout << "# Simulation parameters: " << std::endl; factory::Header::print_parameters(params_list); // display the headers (= print the AFF3CT parameters on the screen) std::cout << "#" << std::endl; cp.print_warnings(); p.R = (float)p.codec->enc->K / (float)p.codec->enc->N_cw; // compute the code rate } void init_modules(const params &p, modules &m) { m.source = std::unique_ptr<module::Source <>>(p.source ->build()); m.codec = std::unique_ptr<module::Codec_SIHO <>>(p.codec ->build()); m.modem = std::unique_ptr<module::Modem <>>(p.modem ->build()); m.channel = std::unique_ptr<module::Channel <>>(p.channel->build()); m.monitor = std::unique_ptr<module::Monitor_BFER<>>(p.monitor->build()); m.encoder = m.codec->get_encoder().get(); m.decoder = m.codec->get_decoder_siho().get(); m.list = { m.source.get(), m.modem.get(), m.channel.get(), m.monitor.get(), m.encoder, m.decoder }; // configuration of the module tasks for (auto& mod : m.list) for (auto& tsk : mod->tasks) { tsk->set_autoalloc (true ); // enable the automatic allocation of the data in the tasks tsk->set_autoexec (false); // disable the auto execution mode of the tasks tsk->set_debug (false); // disable the debug mode tsk->set_debug_limit(16 ); // display only the 16 first bits if the debug mode is enabled tsk->set_stats (true ); // enable the statistics // enable the fast mode (= disable the useless verifs in the tasks) if there is no debug and stats modes if (!tsk->is_debug() && !tsk->is_stats()) tsk->set_fast(true); } // reset the memory of the decoder after the end of each communication m.monitor->add_handler_check(std::bind(&module::Decoder::reset, m.decoder)); // initialize the interleaver if this code use an interleaver try { auto& interleaver = m.codec->get_interleaver(); interleaver->init(); } catch (const std::exception&) { /* do nothing if there is no interleaver */ } } void init_utils(const params &p, const modules &m, utils &u) { // create a sigma noise type u.noise = std::unique_ptr<tools::Sigma<>>(new tools::Sigma<>()); // report the noise values (Es/N0 and Eb/N0) u.reporters.push_back(std::unique_ptr<tools::Reporter>(new tools::Reporter_noise<>(*u.noise))); // report the bit/frame error rates u.reporters.push_back(std::unique_ptr<tools::Reporter>(new tools::Reporter_BFER<>(*m.monitor))); // report the simulation throughputs u.reporters.push_back(std::unique_ptr<tools::Reporter>(new tools::Reporter_throughput<>(*m.monitor))); // create a terminal that will display the collected data from the reporters u.terminal = std::unique_ptr<tools::Terminal>(p.terminal->build(u.reporters)); }
43.302885
117
0.636172
[ "vector" ]
d640a6a43e7825d3cbf66974167a5447d3bb673e
3,386
hpp
C++
RobWork/src/rwlibs/simulation/SimulatedSensor.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
1
2021-12-29T14:16:27.000Z
2021-12-29T14:16:27.000Z
RobWork/src/rwlibs/simulation/SimulatedSensor.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
RobWork/src/rwlibs/simulation/SimulatedSensor.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
/******************************************************************************** * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute, * Faculty of Engineering, University of Southern Denmark * * 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 RWLIBS_SIMULATION_SIMULATEDSENSOR_HPP_ #define RWLIBS_SIMULATION_SIMULATEDSENSOR_HPP_ //! @file SimulatedSensor.hpp #include "Simulator.hpp" #include <rw/core/Ptr.hpp> #include <rw/sensor/SensorModel.hpp> namespace rw { namespace kinematics { class Frame; }} // namespace rw::kinematics namespace rw { namespace kinematics { class State; }} // namespace rw::kinematics namespace rwlibs { namespace simulation { //! @addtogroup simulation // @{ /** * @brief simulated sensor interface */ class SimulatedSensor : public rw::kinematics::Stateless { public: //! @brief smart pointer type of this class typedef rw::core::Ptr< SimulatedSensor > Ptr; protected: //! constructor SimulatedSensor (rw::sensor::SensorModel::Ptr model) : _model (model) {} public: //! @brief destructor virtual ~SimulatedSensor (); /** * @brief get name of this simulated sensor */ const std::string& getName () const { return _model->getName (); } /** * @brief get frame that this sensor is attached to. * @return frame */ rw::kinematics::Frame* getFrame () const { return _model->getFrame (); } /** * @brief steps the the SimulatedSensor with time \b dt and saves any state * changes in \b state. * @param info [in] update information related to the time step. * @param state [out] changes of the SimulatedSensor is saved in state. */ virtual void update (const Simulator::UpdateInfo& info, rw::kinematics::State& state) = 0; /** * @brief Resets the state of the SimulatedSensor to that of \b state * @param state [in] the state that the sensor is reset too. */ virtual void reset (const rw::kinematics::State& state) = 0; /** * @brief get the sensor model of this simulated sensor. */ rw::sensor::SensorModel::Ptr getSensorModel () { return _model; } /** * @brief get a handle to controlling an instance of the simulated sensor in a specific * simulator * @param sim [in] the simulator in which the handle is active */ rw::sensor::Sensor::Ptr getSensorHandle (rwlibs::simulation::Simulator::Ptr sim); private: rw::sensor::SensorModel::Ptr _model; }; //! @} }} // namespace rwlibs::simulation #endif /* SIMULATEDSENSOR_HPP_ */
33.86
98
0.609864
[ "model" ]
d647a91850e0a7faad5a097a2cff56fbd5de50a9
2,499
cpp
C++
source/frontend/models/proxy_models/resource_details_proxy_model.cpp
GPUOpen-Tools/radeon_memory_visualizer
309ac5b04b870aef408603eaac4bd727d5d3e698
[ "MIT" ]
86
2020-05-14T17:20:22.000Z
2022-01-21T22:53:24.000Z
source/frontend/models/proxy_models/resource_details_proxy_model.cpp
GPUOpen-Tools/radeon_memory_visualizer
309ac5b04b870aef408603eaac4bd727d5d3e698
[ "MIT" ]
6
2020-05-16T18:50:00.000Z
2022-01-21T15:30:16.000Z
source/frontend/models/proxy_models/resource_details_proxy_model.cpp
GPUOpen-Tools/radeon_memory_visualizer
309ac5b04b870aef408603eaac4bd727d5d3e698
[ "MIT" ]
11
2020-10-15T15:55:56.000Z
2022-03-16T20:38:29.000Z
//============================================================================= // Copyright (c) 2019-2021 Advanced Micro Devices, Inc. All rights reserved. /// @author AMD Developer Tools Team /// @file /// @brief Implementation of a proxy filter that processes the resource details /// table in the resource details pane. //============================================================================= #include "models/proxy_models/resource_details_proxy_model.h" #include <QTableView> #include "rmt_assert.h" #include "models/snapshot/allocation_explorer_model.h" #include "models/snapshot/resource_timeline_item_model.h" namespace rmv { ResourceDetailsProxyModel::ResourceDetailsProxyModel(QObject* parent) : TableProxyModel(parent) { } ResourceDetailsProxyModel::~ResourceDetailsProxyModel() { } ResourceTimelineItemModel* ResourceDetailsProxyModel::InitializeResourceTableModels(QTableView* view, int num_rows, int num_columns) { ResourceTimelineItemModel* model = new ResourceTimelineItemModel(); model->SetRowCount(num_rows); model->SetColumnCount(num_columns); setSourceModel(model); SetFilterKeyColumns({kResourceHistoryTime, kResourceHistoryEvent}); view->setModel(this); return model; } bool ResourceDetailsProxyModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const { Q_UNUSED(source_row); Q_UNUSED(source_parent); bool pass = true; return pass; } bool ResourceDetailsProxyModel::lessThan(const QModelIndex& left, const QModelIndex& right) const { if ((left.column() == kResourceHistoryTime && right.column() == kResourceHistoryTime)) { const double left_data = left.data(Qt::UserRole).toULongLong(); const double right_data = right.data(Qt::UserRole).toULongLong(); return left_data < right_data; } if ((left.column() == kResourceHistoryEvent && right.column() == kResourceHistoryEvent)) { QModelIndex left_data = sourceModel()->index(left.row(), kResourceHistoryEvent, QModelIndex()); QModelIndex right_data = sourceModel()->index(right.row(), kResourceHistoryEvent, QModelIndex()); return QString::localeAwareCompare(left_data.data().toString(), right_data.data().toString()) < 0; } return QSortFilterProxyModel::lessThan(left, right); } } // namespace rmv
36.217391
136
0.64906
[ "model" ]