hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
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
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
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
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
14c5028ed5cc6188928c31226565c539e32d5163
986
cpp
C++
src/interface/graphics/Buffer.cpp
FuriousProton/proton
1bb790932e730d119ad68266159a77ad93eeef99
[ "MIT" ]
null
null
null
src/interface/graphics/Buffer.cpp
FuriousProton/proton
1bb790932e730d119ad68266159a77ad93eeef99
[ "MIT" ]
null
null
null
src/interface/graphics/Buffer.cpp
FuriousProton/proton
1bb790932e730d119ad68266159a77ad93eeef99
[ "MIT" ]
null
null
null
// // Created by teeebor on 2017-10-05. // #include <glbinding/gl/gl.h> #include "../../../include/interface/Buffer.h" namespace proton{ using namespace gl; Buffer::Buffer(const void *data, int count, unsigned int componentCount) { load(data,count,componentCount); } void Buffer::load(const void *data, int count, unsigned int componentCount) { mComponentCount = componentCount; mCount = count; glGenBuffers(1, &mBufferId); glBindBuffer(GL_ARRAY_BUFFER, mBufferId); glBufferData(GL_ARRAY_BUFFER, count * sizeof(float), data, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); } Buffer::~Buffer() { glDeleteBuffers(1,&mBufferId); } void Buffer::bind() const { glBindBuffer(GL_ARRAY_BUFFER, mBufferId); } void Buffer::unbind() const { glBindBuffer(GL_ARRAY_BUFFER, 0); } unsigned int Buffer::getComponentCount() { return mComponentCount; } }
25.947368
83
0.64503
FuriousProton
14c7bb885d9faabbb4f4084bcebda111828df10e
7,774
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/widget/Filter.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/widget/Filter.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/widget/Filter.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos 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 "Elastos.Droid.Widget.h" #include "elastos/droid/widget/Filter.h" #include "elastos/droid/os/SystemClock.h" #include "elastos/droid/os/CHandlerThread.h" #include <elastos/core/AutoLock.h> #include <elastos/core/AutoLock.h> using Elastos::Core::AutoLock; using Elastos::Droid::Os::IHandlerThread; using Elastos::Droid::Os::CHandlerThread; using Elastos::Droid::Os::IProcess; using Elastos::Core::CString; using Elastos::Core::IThread; namespace Elastos { namespace Droid { namespace Widget { const String Filter::TAG("Filter"); const String Filter::THREAD_NAME = String("Filter"); const Int32 Filter::FILTER_TOKEN = 0xD0D0F00D; const Int32 Filter::FINISH_TOKEN = 0xDEADBEEF; //============================================================================== // Filter::FilterResults //============================================================================== CAR_INTERFACE_IMPL(Filter::FilterResults, Object, IFilterResults); Filter::FilterResults::FilterResults() : mCount(0) {} ECode Filter::FilterResults::SetCount( /* [in] */ Int32 count) { mCount = count; return NOERROR; } ECode Filter::FilterResults::GetCount( /* [out] */ Int32* count) { VALIDATE_NOT_NULL(count); *count = mCount; return NOERROR; } ECode Filter::FilterResults::SetValues( /* [in] */ IInterface* values) { mValues = values; return NOERROR; } ECode Filter::FilterResults::GetValues( /* [out] */ IInterface** values) { VALIDATE_NOT_NULL(values); *values = mValues; REFCOUNT_ADD(*values); return NOERROR; } //============================================================================== // Filter::RequestHandler //============================================================================== Filter::RequestHandler::RequestHandler( /* [in] */ ILooper* looper, /* [in] */ Filter* host) : Handler(looper) , mHost(host) { } ECode Filter::RequestHandler::HandleMessage( /* [in] */ IMessage* msg) { Int32 what; msg->GetWhat(&what); AutoPtr<IInterface> obj; msg->GetObj((IInterface**)&obj); switch (what) { case Filter::FILTER_TOKEN: { RequestArguments* args = (RequestArguments*)(IObject*)obj.Get(); mHost->HandleFilterMessage(args); break; } case Filter::FINISH_TOKEN: mHost->HandleFinishMessage(); break; } return NOERROR; } //============================================================================== // Filter::ResultsHandler //============================================================================== Filter::ResultsHandler::ResultsHandler( /* [in] */ Filter* host) : mHost(host) { } ECode Filter::ResultsHandler::HandleMessage( /* [in] */ IMessage* msg) { AutoPtr<IInterface> obj; msg->GetObj((IInterface**)&obj); RequestArguments* args = (RequestArguments*)(IObject*)obj.Get(); mHost->HandleResultsMessage(args); return NOERROR; } //============================================================================== // Filter //============================================================================== CAR_INTERFACE_IMPL(Filter, Object, IFilter); Filter::Filter() { mResultHandler = new ResultsHandler(this); } ECode Filter::SetDelayer( /* [in] */ IFilterDelayer* delayer) { { AutoLock syncLock(mLock); mDelayer = delayer; } return NOERROR; } ECode Filter::DoFilter( /* [in] */ ICharSequence* constraint) { return DoFilter(constraint, NULL); } ECode Filter::DoFilter( /* [in] */ ICharSequence* constraint, /* [in] */ IFilterListener* listener) { { AutoLock syncLock(mLock); if (mThreadHandler == NULL) { AutoPtr<IHandlerThread> thread; CHandlerThread::New(THREAD_NAME, IProcess::THREAD_PRIORITY_BACKGROUND, (IHandlerThread**)&thread); IThread::Probe(thread)->Start(); AutoPtr<ILooper> looper; thread->GetLooper((ILooper**)&looper); mThreadHandler = new RequestHandler(looper, this); } Int64 delay = 0; if (mDelayer != NULL) { mDelayer->GetPostingDelay(constraint, &delay); } AutoPtr<RequestArguments> args = new RequestArguments(); // make sure we use an immutable copy of the constraint, so that // it doesn't change while the filter operation is in progress // String str(""); if (constraint) { constraint->ToString(&str); } CString::New(str, (ICharSequence**)&args->mConstraint); args->mListener = listener; AutoPtr<IMessage> message; mThreadHandler->ObtainMessage(FILTER_TOKEN, args->Probe(EIID_IInterface), (IMessage**)&message); Boolean result; mThreadHandler->RemoveMessages(FILTER_TOKEN); mThreadHandler->RemoveMessages(FINISH_TOKEN); mThreadHandler->SendMessageDelayed(message, delay, &result); } return NOERROR; } ECode Filter::ConvertResultToString( /* [in] */ IInterface* resultValue, /* [out] */ ICharSequence** cs) { VALIDATE_NOT_NULL(cs); String str; if (resultValue && ICharSequence::Probe(resultValue)) { ICharSequence::Probe(resultValue)->ToString(&str); } return CString::New(str, cs); } ECode Filter::HandleFilterMessage( /* [in] */ RequestArguments* args) { assert(args != NULL); AutoPtr<IFilterResults> results; ECode ec = PerformFiltering(args->mConstraint, (IFilterResults**)&results); if (FAILED(ec)) { args->mResults = new FilterResults(); } else { args->mResults = results; } AutoPtr<IMessage> message; mResultHandler->ObtainMessage(FILTER_TOKEN, args->Probe(EIID_IInterface), (IMessage**)&message); message->SendToTarget(); { AutoLock syncLock(mLock); if (mThreadHandler != NULL) { AutoPtr<IMessage> finishMessage; mThreadHandler->ObtainMessage(FINISH_TOKEN, (IMessage**)&finishMessage); Boolean result; mThreadHandler->SendMessageDelayed(finishMessage, 3000, &result); } } return NOERROR; } ECode Filter::HandleFinishMessage() { { AutoLock syncLock(mLock); if (mThreadHandler != NULL) { AutoPtr<ILooper> looper; mThreadHandler->GetLooper((ILooper**)&looper); looper->Quit(); mThreadHandler = NULL; } } return NOERROR; } ECode Filter::HandleResultsMessage( /* [in] */ RequestArguments* args) { assert(args != NULL); PublishResults(args->mConstraint, args->mResults); if (args->mListener != NULL) { Int32 count = -1; if (args->mResults != NULL) { args->mResults->GetCount(&count); } args->mListener->OnFilterComplete(count); } return NOERROR; } } // namespace Widget } // namespace Droid } // namespace Elastos
28.580882
104
0.573064
jingcao80
14c921fdda223e050127c85ea61d0bba4216faf4
10,741
hpp
C++
lib/quasimo/base/qcor_qsim.hpp
moar55/qcor
e744642c3e87ededf60813a442b7cde502467de4
[ "BSD-3-Clause" ]
null
null
null
lib/quasimo/base/qcor_qsim.hpp
moar55/qcor
e744642c3e87ededf60813a442b7cde502467de4
[ "BSD-3-Clause" ]
null
null
null
lib/quasimo/base/qcor_qsim.hpp
moar55/qcor
e744642c3e87ededf60813a442b7cde502467de4
[ "BSD-3-Clause" ]
null
null
null
/******************************************************************************* * Copyright (c) 2018-, UT-Battelle, LLC. * All rights reserved. This program and the accompanying materials * are made available under the terms of the BSD 3-Clause License * which accompanies this distribution. * * Contributors: * Alexander J. McCaskey - initial API and implementation * Thien Nguyen - implementation *******************************************************************************/ #pragma once #include <memory> #include <qalloc> #include <xacc_internal_compiler.hpp> #include "Accelerator.hpp" #include "AcceleratorBuffer.hpp" #include "Circuit.hpp" #include "kernel_evaluator.hpp" #include "objective_function.hpp" #include "qcor_observable.hpp" #include "qcor_optimizer.hpp" #include "qcor_utils.hpp" #include "qrt.hpp" #include "quantum_kernel.hpp" using CompositeInstruction = xacc::CompositeInstruction; using Accelerator = xacc::Accelerator; using Identifiable = xacc::Identifiable; namespace qcor { namespace QuaSiMo { // Struct captures a state-preparation circuit. struct Ansatz { std::shared_ptr<CompositeInstruction> circuit; std::vector<std::string> symbol_names; size_t nb_qubits; }; // State-preparation method (i.e. ansatz): // For example, // - Real time Hamiltonian evolution with Trotter approximation (of various // orders) // - Real time Hamiltonian evolution with Taylor series/LCU approach // - Imaginary time evolution with QITE // - Thermo-field doubles state preparation // - Two-point correlation function measurements // - QFT class AnsatzGenerator : public Identifiable { public: virtual Ansatz create_ansatz(Operator *obs = nullptr, const HeterogeneousMap &params = {}) = 0; }; // CostFunctionEvaluator take an unknown quantum state (the circuit that // prepares the unknown state) and a target operator (e.g. Hamiltonian // Observable) as input and produce a estimation as output. class CostFunctionEvaluator : public Identifiable { public: // Evaluate the cost virtual double evaluate(std::shared_ptr<CompositeInstruction> state_prep) = 0; // Batching evaluation: observing multiple kernels in batches. // E.g. for non-vqe cases (Trotter), we have all kernels ready for observable // evaluation virtual std::vector<double> evaluate( std::vector<std::shared_ptr<CompositeInstruction>> state_prep_circuits) { // Default is one-by-one, subclass to provide batching if supported. std::vector<double> result; for (auto &circuit : state_prep_circuits) { result.emplace_back(evaluate(circuit)); } return result; } virtual bool initialize(Operator *observable, const HeterogeneousMap &params = {}); protected: Operator *target_operator; HeterogeneousMap hyperParams; }; // Trotter time-dependent simulation workflow // Time-dependent Hamiltonian is a function mapping from time t to Observable // operator. using TdObservable = std::function<Operator(double)>; // Capture a quantum chemistry problem. // TODO: generalize this to capture all potential use cases. struct QuantumSimulationModel { QuantumSimulationModel() : observable(nullptr) {} // Copy Constructor QuantumSimulationModel(QuantumSimulationModel &other) : name(other.name), observable(other.observable), hamiltonian(other.hamiltonian), user_defined_ansatz(other.user_defined_ansatz), owns_observable(other.owns_observable) { if (other.owns_observable) { // Transfer ownership. other.owns_observable = false; } } // Move Constructor QuantumSimulationModel(QuantumSimulationModel &&other) : name(other.name), observable(other.observable), hamiltonian(other.hamiltonian), user_defined_ansatz(other.user_defined_ansatz), owns_observable(other.owns_observable) { if (other.owns_observable) { // Transfer ownership. other.owns_observable = false; } } // Model name. std::string name; // The Observable operator that needs to be measured/minimized. Operator *observable; // The system Hamiltonian which can be static or dynamic (time-dependent). // This can be the same or different from the observable operator. TdObservable hamiltonian; // QuantumSimulationModel also support a user-defined (fixed) ansatz. std::shared_ptr<KernelFunctor> user_defined_ansatz; // clients can create raw operator pointers, and // provided them to this Model and indicate that // the Model owns the observable, and will delete it // upon destruction bool owns_observable = false; // Destructor, delete observable if we own it ~QuantumSimulationModel() { if (owns_observable) { printf("Deleting the raw ptr\n"); delete observable; } } }; // Generic model builder (factory) // Create a model which capture the problem description. class ModelFactory { public: // Generic Heisenberg model struct HeisenbergModel { double Jx = 0.0; double Jy = 0.0; double Jz = 0.0; double h_ext = 0.0; // Support for H_BAR normalization double H_BAR = 1.0; // "X", "Y", or "Z" std::string ext_dir = "Z"; int num_spins = 2; std::vector<int> initial_spins; // Time-dependent freq. // Default to using the cosine function. double freq = 0.0; // User-provided custom time-dependent function: std::function<double(double)> time_func; // Allows a simple Pythonic kwarg-style initialization. // i.e. all params have preset defaults, only update those that are // specified. void fromDict(const HeterogeneousMap &params); bool validateModel() const { const bool ext_dir_valid = (ext_dir == "X" || ext_dir == "Y" || ext_dir == "Z"); const bool initial_spins_valid = (initial_spins.empty() || (initial_spins.size() == num_spins)); return ext_dir_valid && initial_spins_valid; } }; // ======== Direct model builder ============== // Strongly-typed parameters/argument. // Build a simple Hamiltonian-based model: static Hamiltonian which is also // the observable of interest. static QuantumSimulationModel createModel( Operator *obs, const HeterogeneousMap &params = {}); static QuantumSimulationModel createModel( Operator &obs, const HeterogeneousMap &params = {}) { return createModel(&obs, params); } // Build a time-dependent problem model: // - obs: observable operator to measure. // - td_ham: time-dependent Hamiltonian to evolve the system. // e.g. a function to map from time to Hamiltonian operator. static QuantumSimulationModel createModel( Operator *obs, TdObservable td_ham, const HeterogeneousMap &params = {}); // Pauli operator overload: static QuantumSimulationModel createModel( Operator &obs, TdObservable td_ham, const HeterogeneousMap &params = {}) { return createModel(&obs, td_ham, params); } // ======== High-level model builder ============== // The idea here is to have contributed modules to translate problem // descriptions in various formats, e.g. PyScf, Psi4, broombridge, etc. into // QCOR's Observable type. Inputs: // - format: key to look up module/plugin to digest the input data. // - data: model descriptions in plain-text format, e.g. load from file. // - params: extra parameters to pass to the parser/generator, // e.g. any transformations required in order to generate the // Observable. static QuantumSimulationModel createModel( const std::string &format, const std::string &data, const HeterogeneousMap &params = {}); // Predefined model type that we support intrinsically. enum class ModelType { Heisenberg }; static QuantumSimulationModel createModel(ModelType type, const HeterogeneousMap &params); // ========== QuantumSimulationModel with a fixed (pre-defined) ansatz // ======== The ansatz is provided as a QCOR kernel. template <typename... Args> static inline QuantumSimulationModel createModel( void (*quantum_kernel_functor)(std::shared_ptr<CompositeInstruction>, Args...), Operator *obs, size_t nbQubits, size_t nbParams) { auto kernel_functor = createKernelFunctor(quantum_kernel_functor, nbQubits, nbParams); QuantumSimulationModel model; model.observable = obs; model.user_defined_ansatz = kernel_functor; return model; } template <typename... Args> static inline QuantumSimulationModel createModel( void (*quantum_kernel_functor)(std::shared_ptr<CompositeInstruction>, Args...), Operator &obs, size_t nbQubits, size_t nbParams) { return createModel(quantum_kernel_functor, &obs, nbQubits, nbParams); } // Passing the state-preparation ansatz as a CompositeInstruction static inline QuantumSimulationModel createModel( std::shared_ptr<CompositeInstruction> composite, Operator *obs) { QuantumSimulationModel model; model.observable = obs; model.user_defined_ansatz = createKernelFunctor(composite); return model; } static inline QuantumSimulationModel createModel( std::shared_ptr<CompositeInstruction> composite, Operator &obs) { return createModel(composite, &obs); } }; // Quantum Simulation Workflow (Protocol) // This can handle both variational workflow (optimization loop) // as well as simple Trotter evolution workflow. // Result is stored in a HetMap using QuantumSimulationResult = HeterogeneousMap; // Abstract workflow: class QuantumSimulationWorkflow : public Identifiable { public: virtual bool initialize(const HeterogeneousMap &params) = 0; virtual QuantumSimulationResult execute( const QuantumSimulationModel &model) = 0; protected: std::shared_ptr<CostFunctionEvaluator> evaluator; }; // Get workflow by name: std::shared_ptr<QuantumSimulationWorkflow> getWorkflow( const std::string &name, const HeterogeneousMap &init_params); // Get the Obj (cost) function evaluator: std::shared_ptr<CostFunctionEvaluator> getObjEvaluator( Operator *observable, const std::string &name = "default", const HeterogeneousMap &init_params = {}); inline std::shared_ptr<CostFunctionEvaluator> getObjEvaluator( Operator &obs, const std::string &name = "default", const HeterogeneousMap &init_params = {}) { return getObjEvaluator(&obs, name, init_params); } // Helper to apply optimization/placement before evaluation: void executePassManager( std::vector<std::shared_ptr<CompositeInstruction>> evalKernels); } // namespace QuaSiMo } // namespace qcor
36.534014
81
0.699935
moar55
14c9cda500cfb12a37e94ef483653a53c21f9ca9
3,898
hpp
C++
stan/math/gpu/multiply.hpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
null
null
null
stan/math/gpu/multiply.hpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
null
null
null
stan/math/gpu/multiply.hpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MATH_GPU_MULTIPLY_HPP #define STAN_MATH_GPU_MULTIPLY_HPP #ifdef STAN_OPENCL #include <stan/math/gpu/matrix_gpu.hpp> #include <stan/math/gpu/kernels/scalar_mul.hpp> #include <stan/math/gpu/kernels/matrix_multiply.hpp> #include <Eigen/Dense> namespace stan { namespace math { /** * Multiplies the specified matrix on the GPU * with the specified scalar. * * @param A matrix * @param scalar scalar * @return matrix multipled with scalar */ inline matrix_gpu multiply(const matrix_gpu& A, const double scalar) { matrix_gpu temp(A.rows(), A.cols()); if (A.size() == 0) return temp; try { opencl_kernels::scalar_mul(cl::NDRange(A.rows(), A.cols()), temp.buffer(), A.buffer(), scalar, A.rows(), A.cols()); } catch (const cl::Error& e) { check_opencl_error("multiply scalar", e); } return temp; } /** * Multiplies the specified matrix on the GPU * with the specified scalar. * * @param scalar scalar * @param A matrix * @return matrix multipled with scalar */ inline auto multiply(const double scalar, const matrix_gpu& A) { return multiply(A, scalar); } /** * Computes the product of the specified GPU matrices. * * Computes the matrix multiplication C[M, K] = A[M, N] x B[N, K] * * @param A first matrix * @param B second matrix * @return the product of the first and second matrix * * @throw <code>std::invalid_argument</code> if the * number of columns in A and rows in B do not match */ inline auto multiply(const matrix_gpu& A, const matrix_gpu& B) { check_size_match("multiply (GPU)", "A.cols()", A.cols(), "B.rows()", B.rows()); matrix_gpu temp(A.rows(), B.cols()); if (A.size() == 0 || B.size() == 0) { temp.zeros(); return temp; } int local = opencl_kernels::matrix_multiply.make_functor.get_opts().at( "THREAD_BLOCK_SIZE"); int Mpad = ((A.rows() + local - 1) / local) * local; int Npad = ((B.cols() + local - 1) / local) * local; int Kpad = ((A.cols() + local - 1) / local) * local; // padding the matrices so the dimensions are divisible with local // improves performance and readability because we can omit // if statements in the // multiply kernel matrix_gpu tempPad(Mpad, Npad); matrix_gpu Apad(Mpad, Kpad); matrix_gpu Bpad(Kpad, Npad); opencl_kernels::zeros(cl::NDRange(Mpad, Kpad), Apad.buffer(), Mpad, Kpad, TriangularViewGPU::Entire); opencl_kernels::zeros(cl::NDRange(Kpad, Npad), Bpad.buffer(), Kpad, Npad, TriangularViewGPU::Entire); Apad.sub_block(A, 0, 0, 0, 0, A.rows(), A.cols()); Bpad.sub_block(B, 0, 0, 0, 0, B.rows(), B.cols()); int wpt = opencl_kernels::matrix_multiply.make_functor.get_opts().at( "WORK_PER_THREAD"); try { opencl_kernels::matrix_multiply( cl::NDRange(Mpad, Npad / wpt), cl::NDRange(local, local / wpt), Apad.buffer(), Bpad.buffer(), tempPad.buffer(), Apad.rows(), Bpad.cols(), Bpad.rows()); } catch (cl::Error& e) { check_opencl_error("multiply", e); } // unpadding the result matrix temp.sub_block(tempPad, 0, 0, 0, 0, temp.rows(), temp.cols()); return temp; } /** * Templated product operator for GPU matrices. * * Computes the matrix multiplication C[M, K] = A[M, N] x B[N, K]. * * @param A A matrix or scalar * @param B A matrix or scalar * @return the product of the first and second arguments * * @throw <code>std::invalid_argument</code> if the * number of columns in A and rows in B do not match */ inline matrix_gpu operator*(const matrix_gpu& A, const matrix_gpu& B) { return multiply(A, B); } inline matrix_gpu operator*(const matrix_gpu& B, const double scalar) { return multiply(B, scalar); } inline matrix_gpu operator*(const double scalar, const matrix_gpu& B) { return multiply(scalar, B); } } // namespace math } // namespace stan #endif #endif
31.691057
78
0.65803
jrmie
14c9fce899e636ec1555150d0e5145862770f74d
15,557
cpp
C++
Source/SIMPLib/CoreFilters/CropVertexGeometry.cpp
mmarineBlueQuartz/SIMPL
834f9009944efe69d94b5b77a641d96db3e9543b
[ "NRL" ]
null
null
null
Source/SIMPLib/CoreFilters/CropVertexGeometry.cpp
mmarineBlueQuartz/SIMPL
834f9009944efe69d94b5b77a641d96db3e9543b
[ "NRL" ]
2
2019-02-23T20:46:12.000Z
2019-07-11T15:34:13.000Z
Source/SIMPLib/CoreFilters/CropVertexGeometry.cpp
mmarineBlueQuartz/SIMPL
834f9009944efe69d94b5b77a641d96db3e9543b
[ "NRL" ]
null
null
null
/* ============================================================================ * Copyright (c) 2009-2016 BlueQuartz Software, LLC * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of BlueQuartz Software, the US Air Force, nor the names of its * contributors may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The code contained herein was partially funded by the followig contracts: * United States Air Force Prime Contract FA8650-07-D-5800 * United States Air Force Prime Contract FA8650-10-D-5210 * United States Prime Contract Navy N00173-07-C-2068 * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ #include "CropVertexGeometry.h" #include <cassert> #include "SIMPLib/Common/Constants.h" #include "SIMPLib/Common/TemplateHelpers.h" #include "SIMPLib/FilterParameters/AbstractFilterParametersReader.h" #include "SIMPLib/FilterParameters/DataContainerSelectionFilterParameter.h" #include "SIMPLib/FilterParameters/FloatFilterParameter.h" #include "SIMPLib/FilterParameters/StringFilterParameter.h" #include "SIMPLib/Geometry/VertexGeom.h" #include "SIMPLib/SIMPLibVersion.h" // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- CropVertexGeometry::CropVertexGeometry() : m_DataContainerName(SIMPL::Defaults::VertexDataContainerName) , m_CroppedDataContainerName("CroppedDataContainer") , m_XMin(0) , m_YMin(0) , m_ZMin(0) , m_XMax(0) , m_YMax(0) , m_ZMax(0) { } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- CropVertexGeometry::~CropVertexGeometry() = default; // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CropVertexGeometry::setupFilterParameters() { FilterParameterVector parameters; DataContainerSelectionFilterParameter::RequirementType req; IGeometry::Types reqGeom = {IGeometry::Type::Vertex}; req.dcGeometryTypes = reqGeom; parameters.push_back(SIMPL_NEW_DC_SELECTION_FP("Vertex Geometry to Crop", DataContainerName, FilterParameter::RequiredArray, CropVertexGeometry, req)); parameters.push_back(SIMPL_NEW_FLOAT_FP("X Min", XMin, FilterParameter::Parameter, CropVertexGeometry)); parameters.push_back(SIMPL_NEW_FLOAT_FP("Y Min", YMin, FilterParameter::Parameter, CropVertexGeometry)); parameters.push_back(SIMPL_NEW_FLOAT_FP("Z Min", ZMin, FilterParameter::Parameter, CropVertexGeometry)); parameters.push_back(SIMPL_NEW_FLOAT_FP("X Max", XMax, FilterParameter::Parameter, CropVertexGeometry)); parameters.push_back(SIMPL_NEW_FLOAT_FP("Y Max", YMax, FilterParameter::Parameter, CropVertexGeometry)); parameters.push_back(SIMPL_NEW_FLOAT_FP("Z Max", ZMax, FilterParameter::Parameter, CropVertexGeometry)); parameters.push_back(SIMPL_NEW_STRING_FP("Cropped Data Container", CroppedDataContainerName, FilterParameter::CreatedArray, CropVertexGeometry)); setFilterParameters(parameters); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CropVertexGeometry::readFilterParameters(AbstractFilterParametersReader* reader, int index) { reader->openFilterGroup(this, index); setDataContainerName(reader->readString("DataContainerName", getDataContainerName())); setXMin(reader->readValue("XMin", getXMin())); setYMin(reader->readValue("YMin", getYMin())); setZMin(reader->readValue("ZMin", getZMin())); setXMax(reader->readValue("XMax", getXMax())); setYMax(reader->readValue("YMax", getYMax())); setZMax(reader->readValue("ZMax", getZMax())); setCroppedDataContainerName(reader->readString("CroppedDataContainerName", getCroppedDataContainerName())); reader->closeFilterGroup(); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CropVertexGeometry::initialize() { setErrorCondition(0); setWarningCondition(0); setCancel(false); m_AttrMatList.clear(); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CropVertexGeometry::dataCheck() { setErrorCondition(0); setWarningCondition(0); initialize(); getDataContainerArray()->getPrereqGeometryFromDataContainer<VertexGeom, AbstractFilter>(this, getDataContainerName()); if(getXMax() < getXMin()) { QString ss = QObject::tr("X Max (%1) less than X Min (%2)").arg(getXMax()).arg(getXMin()); setErrorCondition(-5550); notifyErrorMessage(getHumanLabel(), ss, getErrorCondition()); } if(getYMax() < getYMin()) { QString ss = QObject::tr("Y Max (%1) less than Y Min (%2)").arg(getYMax()).arg(getYMin()); setErrorCondition(-5550); notifyErrorMessage(getHumanLabel(), ss, getErrorCondition()); } if(getZMax() < getZMin()) { QString ss = QObject::tr("Z Max (%1) less than Z Min (%2)").arg(getZMax()).arg(getZMin()); setErrorCondition(-5550); notifyErrorMessage(getHumanLabel(), ss, getErrorCondition()); } DataContainer::Pointer dc = getDataContainerArray()->createNonPrereqDataContainer<AbstractFilter>(this, getCroppedDataContainerName()); if(getErrorCondition() < 0) { return; } VertexGeom::Pointer crop = VertexGeom::CreateGeometry(0, SIMPL::Geometry::VertexGeometry, !getInPreflight()); dc->setGeometry(crop); DataContainer::Pointer m = getDataContainerArray()->getDataContainer(getDataContainerName()); m_AttrMatList = m->getAttributeMatrixNames(); QVector<size_t> tDims(1, 0); QList<QString> tempDataArrayList; DataArrayPath tempPath; AttributeMatrix::Type tempAttrMatType = AttributeMatrix::Type::Vertex; if(getErrorCondition() < 0) { return; } for(auto&& attr_mat : m_AttrMatList) { AttributeMatrix::Pointer tmpAttrMat = m->getPrereqAttributeMatrix(this, attr_mat, -301); if(getErrorCondition() >= 0) { tempAttrMatType = tmpAttrMat->getType(); if(tempAttrMatType != AttributeMatrix::Type::Vertex) { AttributeMatrix::Pointer attrMat = tmpAttrMat->deepCopy(getInPreflight()); dc->addAttributeMatrix(attr_mat, attrMat); } else { dc->createNonPrereqAttributeMatrix(this, tmpAttrMat->getName(), tDims, AttributeMatrix::Type::Vertex); tempDataArrayList = tmpAttrMat->getAttributeArrayNames(); for(auto&& data_array : tempDataArrayList) { tempPath.update(getCroppedDataContainerName(), tmpAttrMat->getName(), data_array); IDataArray::Pointer tmpDataArray = tmpAttrMat->getPrereqIDataArray<IDataArray, AbstractFilter>(this, data_array, -90002); if(getErrorCondition() >= 0) { QVector<size_t> cDims = tmpDataArray->getComponentDimensions(); TemplateHelpers::CreateNonPrereqArrayFromArrayType()(this, tempPath, cDims, tmpDataArray); } } } } } } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CropVertexGeometry::preflight() { // These are the REQUIRED lines of CODE to make sure the filter behaves correctly setInPreflight(true); // Set the fact that we are preflighting. emit preflightAboutToExecute(); // Emit this signal so that other widgets can do one file update emit updateFilterParameters(this); // Emit this signal to have the widgets push their values down to the filter dataCheck(); // Run our DataCheck to make sure everthing is setup correctly emit preflightExecuted(); // We are done preflighting this filter setInPreflight(false); // Inform the system this filter is NOT in preflight mode anymore. } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- template <typename T> void copyDataToCroppedGeometry(IDataArray::Pointer inDataPtr, IDataArray::Pointer outDataPtr, std::vector<int64_t>& croppedPoints) { typename DataArray<T>::Pointer inputDataPtr = std::dynamic_pointer_cast<DataArray<T>>(inDataPtr); T* inputData = static_cast<T*>(inputDataPtr->getPointer(0)); typename DataArray<T>::Pointer croppedDataPtr = std::dynamic_pointer_cast<DataArray<T>>(outDataPtr); T* croppedData = static_cast<T*>(croppedDataPtr->getPointer(0)); size_t nComps = inDataPtr->getNumberOfComponents(); size_t tmpIndex = 0; size_t ptrIndex = 0; for(std::vector<int64_t>::size_type i = 0; i < croppedPoints.size(); i++) { for(size_t d = 0; d < nComps; d++) { tmpIndex = nComps * i + d; ptrIndex = nComps * croppedPoints[i] + d; croppedData[tmpIndex] = inputData[ptrIndex]; } } } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CropVertexGeometry::execute() { setErrorCondition(0); setWarningCondition(0); dataCheck(); if(getErrorCondition() < 0) { return; } DataContainer::Pointer m = getDataContainerArray()->getDataContainer(getDataContainerName()); DataContainer::Pointer dc = getDataContainerArray()->getDataContainer(getCroppedDataContainerName()); VertexGeom::Pointer vertices = getDataContainerArray()->getDataContainer(getDataContainerName())->getGeometryAs<VertexGeom>(); int64_t numVerts = vertices->getNumberOfVertices(); float* allVerts = vertices->getVertexPointer(0); std::vector<int64_t> croppedPoints; croppedPoints.reserve(numVerts); for(int64_t i = 0; i < numVerts; i++) { if(getCancel()) { return; } if(allVerts[3 * i + 0] >= m_XMin && allVerts[3 * i + 0] <= m_XMax && allVerts[3 * i + 1] >= m_YMin && allVerts[3 * i + 1] <= m_YMax && allVerts[3 * i + 2] >= m_ZMin && allVerts[3 * i + 2] <= m_ZMax) { croppedPoints.push_back(i); } } croppedPoints.shrink_to_fit(); VertexGeom::Pointer crop = dc->getGeometryAs<VertexGeom>(); crop->resizeVertexList(croppedPoints.size()); float coords[3] = {0.0f, 0.0f, 0.0f}; for(std::list<int64_t>::size_type i = 0; i < croppedPoints.size(); i++) { if(getCancel()) { return; } vertices->getCoords(croppedPoints[i], coords); crop->setCoords(i, coords); } QVector<size_t> tDims(1, croppedPoints.size()); for(auto&& attr_mat : m_AttrMatList) { AttributeMatrix::Pointer tmpAttrMat = dc->getPrereqAttributeMatrix(this, attr_mat, -301); if(getErrorCondition() >= 0) { AttributeMatrix::Type tempAttrMatType = tmpAttrMat->getType(); if(tempAttrMatType == AttributeMatrix::Type::Vertex) { tmpAttrMat->resizeAttributeArrays(tDims); QList<QString> srcDataArrays = tmpAttrMat->getAttributeArrayNames(); AttributeMatrix::Pointer srcAttrMat = m->getAttributeMatrix(tmpAttrMat->getName()); assert(srcAttrMat); for(auto&& data_array : srcDataArrays) { IDataArray::Pointer src = srcAttrMat->getAttributeArray(data_array); IDataArray::Pointer dest = tmpAttrMat->getAttributeArray(data_array); assert(src); assert(dest); assert(src->getNumberOfComponents() == dest->getNumberOfComponents()); EXECUTE_FUNCTION_TEMPLATE(this, copyDataToCroppedGeometry, src, src, dest, croppedPoints) } } } } } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- AbstractFilter::Pointer CropVertexGeometry::newFilterInstance(bool copyFilterParameters) const { CropVertexGeometry::Pointer filter = CropVertexGeometry::New(); if(copyFilterParameters) { copyFilterParameterInstanceVariables(filter.get()); } return filter; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- const QString CropVertexGeometry::getCompiledLibraryName() const { return Core::CoreBaseName; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- const QString CropVertexGeometry::getBrandingString() const { return "SIMPLib Core Filter"; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- const QString CropVertexGeometry::getFilterVersion() const { QString version; QTextStream vStream(&version); vStream << SIMPLib::Version::Major() << "." << SIMPLib::Version::Minor() << "." << SIMPLib::Version::Patch(); return version; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- const QString CropVertexGeometry::getGroupName() const { return SIMPL::FilterGroups::CoreFilters; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- const QUuid CropVertexGeometry::getUuid() { return QUuid("{f28cbf07-f15a-53ca-8c7f-b41a11dae6cc}"); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- const QString CropVertexGeometry::getSubGroupName() const { return SIMPL::FilterSubGroups::CropCutFilters; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- const QString CropVertexGeometry::getHumanLabel() const { return "Crop Geometry (Vertex)"; }
39.787724
171
0.588353
mmarineBlueQuartz
14c9fe8f249b93c1711aa7410d5ea6873577134b
181
cpp
C++
async_pool/test/test.foo.cpp
spjuanjoc/concurrency_cpp
50c25c89d202f945c2d6df7df341880b3b93f0b1
[ "MIT" ]
null
null
null
async_pool/test/test.foo.cpp
spjuanjoc/concurrency_cpp
50c25c89d202f945c2d6df7df341880b3b93f0b1
[ "MIT" ]
null
null
null
async_pool/test/test.foo.cpp
spjuanjoc/concurrency_cpp
50c25c89d202f945c2d6df7df341880b3b93f0b1
[ "MIT" ]
null
null
null
#include "catch2/catch.hpp" #include <optional> #include "ParallelAccumulate.hpp" TEST_CASE("test the execution of foo", "[foo]") { REQUIRE( 1 == 1); std::optional<int> var; }
18.1
47
0.679558
spjuanjoc
14ca452d2c14a4d2f80275281caaa38f78c4b4a9
790
cpp
C++
src/client/client/Command_Client_Thread.cpp
Kuga23/Projet-M2
85c879b8fd1ed4fdf89eedd9f89841cbd7a1e433
[ "MIT" ]
null
null
null
src/client/client/Command_Client_Thread.cpp
Kuga23/Projet-M2
85c879b8fd1ed4fdf89eedd9f89841cbd7a1e433
[ "MIT" ]
null
null
null
src/client/client/Command_Client_Thread.cpp
Kuga23/Projet-M2
85c879b8fd1ed4fdf89eedd9f89841cbd7a1e433
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <string.h> #include <sstream> #include <map> #include <memory> #include <unistd.h> #include <thread> #include <sys/socket.h> #include <netinet/in.h> #include <sys/types.h> #include <state.h> #include "render.h" #include "engine.h" #include "ai.h" #include "client.h" using namespace client; using namespace state; using namespace render; using namespace engine; using namespace std; using namespace client; using namespace std; Command_Client_Thread::Command_Client_Thread() { } void Command_Client_Thread::execute() { sf::RenderWindow window(sf::VideoMode(32*26+500,32*24), "Zorglub"); client::Client client(window,"game"); while (window.isOpen()) { client.run(); sleep(2); window.close(); } }
18.809524
71
0.694937
Kuga23
14d06e9385947693d8a114636e45d72fccd859db
2,074
cpp
C++
01-algorithmic-toolbox/week6/2_partitioning_souvenirs/partition3.cpp
olpotkin/ds_and_algos_modern_cpp
12876686a8fb26bc9358930378d235d4470bb6fc
[ "MIT" ]
null
null
null
01-algorithmic-toolbox/week6/2_partitioning_souvenirs/partition3.cpp
olpotkin/ds_and_algos_modern_cpp
12876686a8fb26bc9358930378d235d4470bb6fc
[ "MIT" ]
null
null
null
01-algorithmic-toolbox/week6/2_partitioning_souvenirs/partition3.cpp
olpotkin/ds_and_algos_modern_cpp
12876686a8fb26bc9358930378d235d4470bb6fc
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <cassert> #include <numeric> /// Partitioning Souvenirs /// /// Intro: You and two of your friends have just returned back home after visiting various countries. /// Now you would like to evenly split all the souvenirs that all three of you bought. /// /// Input: The first line contains an integer n. The second line contains integers v_1, v_2, ... , v_n /// separated by spaces. /// /// Output: Output 1, if it possible to partition v_1, v_2, ... , v_n into three subsets with equal sums, /// and 0 otherwise. int partition3(const std::vector<int>& A) { const int numParts = 3; int sum = std::accumulate(A.begin(), A.end(), 0); if (sum % numParts) return 0; // Descrete knapsack without repetitions int n = A.size(); std::vector<std::vector<int>> value(sum / numParts + 1, std::vector<int>(n+1, 0)); for (int i = 1; i <= n; ++i) { int w_i = A[i-1]; // Smaller problems for (int w = 1; w <= sum / numParts; ++w) { value[w][i] = value[w][i-1]; if (w >= w_i) { value[w][i] = std::max(value[w-w_i][i-1] + w_i, value[w][i-1]); } } } return (value[sum / numParts][n]) == (sum / numParts); } void test_solution() { assert(partition3(std::vector<int> {3, 3, 3, 3}) == 0); std::cout << "Test 01 passed..." << std::endl; assert(partition3(std::vector<int> {40}) == 0); std::cout << "Test 02 passed..." << std::endl; /// 34 + 67 + 17 = 23 + 59 + 1 + 17 + 18 = 59 + 2 + 57. assert(partition3(std::vector<int> {17, 59, 34, 57, 17, 23, 67, 1, 18, 2, 59}) == 1); std::cout << "Test 03 passed..." << std::endl; /// 1 + 3 + 7 + 25 = 2 + 4 + 5 + 7 + 8 + 10 = 5 + 12 + 19. assert(partition3(std::vector<int> {1, 2, 3, 4, 5, 5, 7, 7, 8, 10, 12, 19, 25}) == 1); std::cout << "Test 04 passed..." << std::endl; } int main() { // test_solution(); int n; std::cin >> n; std::vector<int> A(n); for (size_t i = 0; i < A.size(); ++i) { std::cin >> A[i]; } std::cout << partition3(A) << std::endl; return 0; }
26.589744
105
0.559306
olpotkin
14d1f462d942e498d312a7d094d7900683effd2b
97,164
cpp
C++
core/sql/executor/sql_buffer.cpp
liuyazhou/trafodion
0edae94106569f793c2ee964be068c44d824033c
[ "Apache-2.0" ]
null
null
null
core/sql/executor/sql_buffer.cpp
liuyazhou/trafodion
0edae94106569f793c2ee964be068c44d824033c
[ "Apache-2.0" ]
null
null
null
core/sql/executor/sql_buffer.cpp
liuyazhou/trafodion
0edae94106569f793c2ee964be068c44d824033c
[ "Apache-2.0" ]
null
null
null
/********************************************************************** // @@@ START COPYRIGHT @@@ // // 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. // // @@@ END COPYRIGHT @@@ **********************************************************************/ /* -*-C++-*- ***************************************************************************** * * File: sql_buffer.cpp * Description: * * * Created: 7/10/95 * Language: C++ * * * * ***************************************************************************** */ // // NOTE: Some of the code in this file is excluded from the UDR server // build using the UDRSERV_BUILD macro. The excluded code is: // - All of the sql_buffer_pool, SqlBufferOlt, and SqlBufferOltSmall code // - Code in the SqlBuffer class that deals with ATPs, expression // evaluation, and statistics // #ifdef UDRSERV_BUILD #include "sql_buffer.h" #else #include "Platform.h" #include "ex_stdh.h" #include "str.h" #include "ComQueue.h" #include "exp_expr.h" #include "ComTdb.h" #include "ExStats.h" #endif // UDRSERV_BUILD #include "sql_buffer_size.h" // to use msg_mon_dump_process_id #include "seabed/ms.h" // // Define a local assert macro. We define UdrExeAssert to something // other than ex_assert in the UDR Server build. // #ifdef UDRSERV_BUILD extern void udrAssert(const char *, Int32, const char *); #define UdrExeAssert(p, msg) \ if (!(p)) { udrAssert( __FILE__ , __LINE__ , msg); } #else #define UdrExeAssert(a,b) ex_assert(a,b) #endif // UDRSERV_BUILD //////////////////////////////////////////////////////////////////////////// // class SqlBufferBase //////////////////////////////////////////////////////////////////////////// SqlBufferBase::SqlBufferBase(BufferType bufType) : SqlBufferHeader(bufType), baseFlags_(0), sizeInBytes_(0) { }; void SqlBufferBase::init(ULng32 in_size_in_bytes, NABoolean clear) { baseFlags_ = 0; sizeInBytes_ = in_size_in_bytes; SqlBufferHeader::init(); } void SqlBufferBase::init() { baseFlags_ = 0; SqlBufferHeader::init(); } void SqlBufferBase::driveInit(ULng32 in_size_in_bytes, NABoolean clear, BufferType bt) { setBufType(bt); fixupVTblPtr(); init(in_size_in_bytes, clear); } void SqlBufferBase::driveInit() { fixupVTblPtr(); init(); } void SqlBufferBase::drivePack() { if (NOT packed()) pack(); setPacked(TRUE); } void SqlBufferBase::driveUnpack() { if (packed()) { fixupVTblPtr(); unpack(); } setPacked(FALSE); } NABoolean SqlBufferBase::driveVerify(ULng32 maxBytes) { fixupVTblPtr(); return verify(maxBytes); } void SqlBufferBase::fixupVTblPtr() { switch (bufType()) { #ifndef UDRSERV_BUILD case OLT_: { SqlBufferOlt sb; str_cpy_all ((char *)this, (char*)&sb, sizeof(char *)); } break; #endif // UDRSERV_BUILD case DENSE_: { SqlBufferDense sb; str_cpy_all ((char *)this, (char*)&sb, sizeof(char *)); } break; case NORMAL_: { SqlBufferNormal sb; str_cpy_all ((char *)this, (char*)&sb, sizeof(char *)); } break; default: { } break; } } void SqlBufferBase::pack() { } void SqlBufferBase::unpack() { } NABoolean SqlBufferBase::verify(ULng32 maxBytes) const { return TRUE; } // positions to the first tupp descriptor in the buffer. void SqlBufferBase::position() { } void * SqlBufferBase::operator new(size_t size, char*s) { return s; } SqlBufferBase::moveStatus SqlBufferBase::moveInSendOrReplyData(NABoolean isSend, // TRUE = send NABoolean doMoveControl, // TRUE = move // control always NABoolean doMoveData, // TRUE = move data. void * currQState, // up_state(reply) or // down_state(send) ULng32 controlInfoLen, ControlInfo ** controlInfo, ULng32 projRowLen, tupp_descriptor ** outTdesc, ComDiagsArea * diagsArea, tupp_descriptor ** diagsDesc, ex_expr_base * expr, atp_struct * atp1, atp_struct * workAtp, atp_struct * destAtp, unsigned short tuppIndex, NABoolean doMoveStats, ExStatisticsArea * statsArea, tupp_descriptor ** statsDesc, NABoolean useExternalDA, NABoolean callerHasExternalDA, tupp_descriptor * defragTd #if (defined(_DEBUG) ) ,ex_tcb * tcb #endif ,NABoolean noMoveWarnings ) { return MOVE_ERROR; } NABoolean SqlBufferBase::moveOutSendOrReplyData(NABoolean isSend, void * currQState, tupp &outTupp, ControlInfo ** controlInfo, ComDiagsArea ** diagsArea, ExStatisticsArea ** statsArea, Int64 * numStatsBytes, NABoolean noStateChange, NABoolean unpackDA, CollHeap * heap) { return FALSE; } // positions to the "tupp_desc_num"th tupp descriptor. void SqlBufferBase::position(Lng32 ){}; // returns the 'next' tupp descriptor. Increments the // position. Returns null, if none found. tupp_descriptor * SqlBufferBase::getNext(){return NULL;}; // returns the 'current' tupp descriptor. Does not increment // position. Returns null, if none found. tupp_descriptor * SqlBufferBase::getCurr(){return NULL;}; // advances the current tupp descriptor void SqlBufferBase::advance(){}; // add a new tuple descriptor to the end of the buffer tupp_descriptor *SqlBufferBase::add_tuple_desc(Lng32 tup_data_size) { return NULL; } // remove the tuple desc with the highest number from the buffer void SqlBufferBase::remove_tuple_desc() { } //////////////////////////////////////////////////////////////////////////// // class SqlBuffer //////////////////////////////////////////////////////////////////////////// void SqlBuffer::init(ULng32 in_size_in_bytes, NABoolean clear) { SqlBufferBase::init(in_size_in_bytes, clear); Lng32 sb_size = getClassSize(); freeSpace_ = sizeInBytes_ - ROUND8(sb_size); bufferStatus_ = EMPTY; maxTuppDesc_ = 0; tuppDescIndex_ = 0; srFlags_ = DEFAULT_; flags_ = 0; setPacked(FALSE); } void SqlBuffer::init() { Lng32 sb_size = getClassSize(); SqlBufferBase::init(); freeSpace_ = sizeInBytes_ - ROUND8(sb_size); bufferStatus_ = EMPTY; maxTuppDesc_ = 0; tuppDescIndex_ = 0; srFlags_ = DEFAULT_; flags_ = 0; setPacked(FALSE); } // RETURNS: -1 if this buffer is free and reinitialized, 0 if not. short SqlBuffer::freeBuffer() { // First check if the buffer is in use. If it is in use, do not call // isFree() or any other virtual method, as the vptr may not be valid, // i.e., the object may be in a packed state. if (bufferStatus_ == IN_USE) return 0; static SqlBufferOlt sv_sb_olt; static SqlBufferDense sv_sb_dense; static SqlBufferNormal sv_sb_normal; static SqlBufferOltSmall sv_sb_olt_small; if ((memcmp(this, &sv_sb_normal, sizeof(char *)) == 0) || (memcmp(this, &sv_sb_dense, sizeof(char *)) == 0) || (memcmp(this, &sv_sb_olt_small, sizeof(char *)) == 0) || (memcmp(this, &sv_sb_olt, sizeof(char *)) == 0)) { ; } else { printf("SQ: Buffer virtual function pointer not yet set\n");fflush(stdout); return 0; } short freeState = isFree(); if (freeState && (bufferStatus_ != EMPTY) ) init(sizeInBytes_); return freeState; } void SqlBuffer::compactBuffer() { } tupp_descriptor * SqlBuffer::getPrev(){return NULL;}; short SqlBuffer::space_available(Lng32 tup_data_size) { if (freeSpace_ >= (Lng32)(tup_data_size + sizeof(tupp_descriptor))) return -1; else return 0; }; tupp_descriptor * SqlBuffer::getTuppDescriptor(Lng32 tupp_desc_num) { return NULL; } // print buffer info. For debugging void SqlBuffer::printInfo() { cerr << this << " Status: " << bufferStatus_ << " maxTuppDesc: " << maxTuppDesc_ << " freeSpace: " << freeSpace_; Lng32 refcount = 0; Lng32 firstref = -1; for (Int32 i = 0; (i < maxTuppDesc_); i++) if (tupleDesc(i)->getReferenceCount()) { if (firstref == -1) firstref = i; refcount++; }; cerr << " ref tupps: " << refcount << " first: " << firstref << endl; }; //////////////////////////////////////////////////////////////////// // Moves control info to send(input) or reply buffer, if needed. // Moves control info if previous state is different than the // current state. As long as state doesn't change, all tuples // in the send/reply buffer are data tupps. A new control tupp is // added when state changed. // Allocates space for data, if needed (projRowLen > 0). Returns // pointer to allocated tupp_descriptor. // If diagsLen is greater than 0, allocates space for diags area. // The tupp_descriptor contains info // indicating whether it is a control or data tupp. // Returns TRUE if buffer is full, FALSE otherwise. //////////////////////////////////////////////////////////////////// SqlBuffer::moveStatus SqlBuffer::moveInSendOrReplyData(NABoolean isSend, NABoolean doMoveControl, NABoolean doMoveData, void * currQState, ULng32 controlInfoLen, ControlInfo ** controlInfo, ULng32 projRowLen, tupp_descriptor ** outTdesc, ComDiagsArea * diagsArea, tupp_descriptor ** diagsDesc, ex_expr_base * expr, atp_struct * atp1, atp_struct * workAtp, atp_struct * destAtp, unsigned short tuppIndex, NABoolean doMoveStats, ExStatisticsArea * statsArea, tupp_descriptor ** statsDesc, NABoolean useExternalDA, NABoolean callerHasExternalDA, tupp_descriptor * defragTd #if (defined(_DEBUG) ) ,ex_tcb * tcb #endif ,NABoolean noMoveWarnings ) { // if this is the first record to be moved in, // or current state is different than previous // state, then move in control info first. tupp_descriptor * cdesc = NULL; tupp_descriptor * tdesc = NULL; NABoolean controlInfoMoved = FALSE; Lng32 daMark = -1; Lng32 atpDaMark = -1; SqlBuffer::moveStatus retcode = MOVE_SUCCESS; NABoolean moveControlInfo = FALSE; NABoolean setUpStatusToError = FALSE; if ((srFlags() == REPLY_GET_UNIQUE_REQUEST) && (NOT doMoveData)) { doMoveData = TRUE; projRowLen = 0; } if ((getTotalTuppDescs() == 0) || (diagsArea != NULL) || ((isSend == TRUE) && (NOT (srControlInfo_.getDownState() == *((down_state *)currQState))))) { moveControlInfo = TRUE; } if (moveControlInfo == FALSE) { if (srFlags() == REPLY_GET_UNIQUE_REQUEST) { if ((((up_state *)currQState)->parentIndex - srControlInfo_.getUpState().parentIndex) == 1) { if (NOT doMoveData) { doMoveData = TRUE; projRowLen = 0; } } else if (((up_state *)currQState)->parentIndex != srControlInfo_.getUpState().parentIndex) { moveControlInfo = TRUE; } else { doMoveData = FALSE; } } else { if ((doMoveControl) || ((isSend == FALSE) && (NOT (srControlInfo_.getUpState() == *((up_state *)currQState))))) moveControlInfo = TRUE; } } NABoolean prevHadExternalDA = flags_ & CURR_HAS_EDA; if (callerHasExternalDA) { // External DiagsAreas always need a ControlInfo so that // moveOutSendOrReplyData will notice them. moveControlInfo = TRUE; flags_ |= CURR_HAS_EDA; } else if (!callerHasExternalDA && prevHadExternalDA) { // If previous entry in this buffer had an External DiagsAreas // but this one does not, make sure there is a ControlInfo so that // moveOutSendOrReplyData can reset srControlInfo_.flags_ moveControlInfo = TRUE; flags_ &= ~CURR_HAS_EDA; } else { // Have not changed state of SqlBuffer WRT whether curr entry has // an external diags area. Hence, no need to force a ControlInfo // to note absence of external DA. } if (moveControlInfo) { if (controlInfoLen > 0) { cdesc = add_tuple_desc(controlInfoLen); if (!cdesc) { return SqlBuffer::BUFFER_FULL; // buffer is full } // mark that this is a control tupp descriptor cdesc->setControlTupleType(); controlInfoMoved = TRUE; ControlInfo *ci; ci = (ControlInfo *)(cdesc->getTupleAddress()); ci->resetFlags(); // no constructor got called for ci ci->setIsExtDiagsAreaPresent(callerHasExternalDA); if (currQState) { if (isSend == TRUE) { ci->getDownState() = *(down_state *)currQState; } else { ci->getUpState() = *(up_state *)currQState; } if (controlInfo) *controlInfo = ci; } } // controlInfoLen > 0 } // now move data. Note that if space for data is to be allocated, // and the previous tupp moved was control, then this data MUST // be moved in the same reply buffer. In other words, the last // tuple in a reply buffer cannot be a control, if that control // has associated data. UInt32 defragLength = 0; UInt32 rowLen = projRowLen; UInt32 *rowLenPtr = &rowLen; #ifndef UDRSERV_BUILD ex_expr::exp_return_type expr_retcode = ex_expr::EXPR_OK; #endif if (doMoveData == TRUE) { #ifndef UDRSERV_BUILD if (defragTd && projRowLen > 0 && SqlBufferGetTuppSize(projRowLen, bufType()) > (ULng32)getFreeSpace() ) { // if we are here then there is not enough space to hold the max row size. // we apply the expression in the defrag buffer and get the actual length // which may be smaller then the max row size and may fit in the remaining // buffer space destAtp->getTupp(tuppIndex) = defragTd; defragTd->setReferenceCount(1); expr_retcode = expr->eval(atp1, workAtp, 0, -1, rowLenPtr); // if no errors then we allocate the actual size. If errors occur then we do not // allocate and skip the defragmentation for this row if (expr_retcode != ex_expr::EXPR_ERROR) { defragLength = rowLen; #if (defined(_DEBUG) ) char txt[] = "exchange"; sql_buffer_pool::logDefragInfo(txt, SqlBufferGetTuppSize(projRowLen, bufType()), SqlBufferGetTuppSize(rowLen, bufType()), getFreeSpace(), this, this->getTotalTuppDescs(), tcb); #endif } } #endif tdesc = add_tuple_desc(rowLen); if (! tdesc) { // no space to move data. Release the control // information, if moved, from the reply buffer. if (controlInfoMoved == TRUE) remove_tuple_desc(); return SqlBuffer::BUFFER_FULL; } // mark that this is a data tupp descriptor tdesc->setDataTupleType(); if (outTdesc != NULL) *outTdesc = tdesc; } #ifndef UDRSERV_BUILD if ((expr != NULL) && (tdesc != NULL)) { destAtp->getTupp(tuppIndex) = tdesc; if (diagsArea != NULL) daMark = diagsArea->mark(); NABoolean backoutAndRestart = FALSE; NABoolean atp1HadNoDiagsAreaBefore = TRUE; if (atp1->getDiagsArea() != NULL) { atpDaMark = atp1->getDiagsArea()->mark(); atp1HadNoDiagsAreaBefore = FALSE; } //Clear the last 4 bytes of row buffer. This is to ensure the last 4 //filler bytes are initialized to zero. Also check to make sure the //rowlength is >= 4 before clearing the bytes. if(rowLen >= 4) { char* fillerBytes = (char*)(tdesc->getTupleAddress() + (rowLen -4)); fillerBytes[0] = 0; fillerBytes[1] = 0; fillerBytes[2] = 0; fillerBytes[3] = 0; } if (defragLength != 0) { str_cpy_all(tdesc->getTupleAddress(), defragTd->getTupleAddress(), defragLength); } else { // get row length after evaluating the expression. If the rowlen is modified, // then this must be a CIF row and can be resized. // Initialize rowLen to projRowLen because if the expr evaluation // decides not to update the row length, there is no need to resize. expr_retcode = expr->eval(atp1, workAtp, 0, -1, rowLenPtr); if (expr_retcode == ex_expr::EXPR_ERROR) { if (isSend) { // No point flowing request down further. Back out and return the error. destAtp->getTupp(tuppIndex).release(); remove_tuple_desc(); if (controlInfoMoved == TRUE) remove_tuple_desc(); if (workAtp == destAtp) destAtp->release(); return MOVE_ERROR; } else { // Errors raised while replying have to be processed here... if (controlInfoMoved == FALSE) { // ... and we must have a ControlInfo to process errors. backoutAndRestart = TRUE; } } } else // success { // resize the row if needed if (rowLenPtr && (*rowLenPtr != projRowLen)) resize_tupp_desc(*rowLenPtr, tdesc->getTupleAddress()); } } if ( // Has a new diags area appeared? (atp1->getDiagsArea() != NULL) && (atp1HadNoDiagsAreaBefore) && // And we are sending diags areas externally? (useExternalDA) && // And state transistion from no DA to yes DA? ((flags_ & CURR_HAS_EDA) == FALSE) ) { backoutAndRestart = TRUE; if (prevHadExternalDA) { flags_ |= CURR_HAS_EDA; } else { flags_ &= ~CURR_HAS_EDA; } } // Sometimes we backout and restart, so that we guarantee a ControlInfo: // // 1. If an error condition is raised from the move expr, and we have no // ControlInfo into which we can record Q_SQLERROR; // 2. If a new diags area appears from the move expr, and the caller is using // external diags areas and the current tuple placed into the buffer did // not have an external diags area associated with it. // // Logic for this test is above. if (backoutAndRestart) { // Start over, this time ask for a new ctrl info. destAtp->getTupp(tuppIndex).release(); remove_tuple_desc(); if (controlInfoMoved == TRUE) remove_tuple_desc(); atp1->getDiagsArea()->rewind(atpDaMark); return moveInSendOrReplyData(isSend, TRUE, // force a new ctrl info doMoveData, currQState, controlInfoLen, controlInfo, projRowLen, outTdesc, NULL, diagsDesc, expr, atp1, workAtp, destAtp, tuppIndex, doMoveStats, statsArea, statsDesc, useExternalDA, useExternalDA, // always have ext. DA if used defragTd #if (defined(_DEBUG) ) ,tcb #endif ,noMoveWarnings ); } if (expr_retcode == ex_expr::EXPR_ERROR) { if (isSend == FALSE) { ((ControlInfo *)(cdesc->getTupleAddress()))->getUpState().status = ex_queue::Q_SQLERROR; setUpStatusToError = TRUE; retcode = MOVE_ERROR; } } if (diagsArea == NULL) { diagsArea = atp1->getDiagsArea(); } if (workAtp == destAtp) destAtp->release(); } // if ((expr != NULL) && (tdesc != NULL)) #endif // UDRSERV_BUILD // if warnings are not to be sent, dont send them. // this is done when a vsbb buffer is being shipped. // vsbb and sidetree eid code cannot handle input warnings. // one day we will teach it to handle them. if ((diagsArea != NULL && useExternalDA == FALSE) && (diagsArea->getNumber(DgSqlCode::ERROR_) == 0) && ((diagsArea->getNumber(DgSqlCode::WARNING_) > 0) && noMoveWarnings)) { // do nothing. } else if (diagsArea != NULL && useExternalDA == FALSE) { // allocate space for diags area. tupp_descriptor * tempDiagsDesc = add_tuple_desc( diagsArea->packedLength()); if (tempDiagsDesc == NULL) { // don't have enough space in this input buffer for diags. // remove the tuple data desc, if any. if (tdesc != NULL) remove_tuple_desc(); // remove the control desc. if (controlInfoMoved == TRUE) remove_tuple_desc(); if (daMark >= 0) diagsArea->rewind(daMark); return SqlBuffer::BUFFER_FULL; // not enough space. } // mark that this is a diags tupp descriptor (tempDiagsDesc)->setDiagsTupleType(); if (diagsDesc) *diagsDesc = tempDiagsDesc; } #ifndef UDRSERV_BUILD if ((doMoveStats) && (statsArea != NULL)) { // stats can only be returned with EOD. So no data should // be allocated at this time. ex_assert((tdesc == NULL), "Cannot have data with stats"); // allocate space for stats area. *statsDesc = add_tuple_desc(statsArea->packedLength()); if (*statsDesc == NULL) { // don't have enough space in this input buffer for stats. // remove the control desc. remove_tuple_desc(); return SqlBuffer::BUFFER_FULL; // not enough space. } // mark that this is a stats tupp descriptor (*statsDesc)->setStatsTupleType(); } #endif // UDRSERV_BUILD if (controlInfoMoved && currQState) { // Set srControlInfo_ to the queue state of the most recent // row in the SqlBuffer. Do this last, because only at this // point can we be sure that the row really fits into the // buffer. if (isSend) srControlInfo_.getDownState() = *(down_state *)currQState; else { srControlInfo_.getUpState() = *(up_state *)currQState; if (setUpStatusToError) srControlInfo_.getUpState().status = ex_queue::Q_SQLERROR; } } else if ((srFlags() == REPLY_GET_UNIQUE_REQUEST) && (doMoveData) && (NOT isSend) && (currQState)) { srControlInfo_.getUpState() = *(up_state *)currQState; } return retcode; } ///////////////////////////////////////////////////////////////////////// // This method returns pairs of control and data(outTupp). The data // returned may not be present for some cases, like Q_NO_DATA up state. // The control and data inside the SqlBuffer are stored in a packed // form while sending from/to one process to/from another. This method // unpacks the control and data depending on the format described by // srFlags_ field, and returns the control/data pair to caller. // // if noStateChange is set, then this moveOut is being called in read // mode and has not yet been shipped. State of tuppDescs // should not be changed in this case. // // See comments in sql_buffer.h too. // // In the following comments, // C means a control tuple. // D means a data tuple. // P means the parent index. Pn means parent index 'n'. // // Buffer Layout is how tuples were stored inside the buffer by // the method moveInSendOrReplyData. A NULL data tuple stored means // that this is a data entry of length zero. // // Returned Tuple Pair is how this method returns data. A NULL data // returned means no data was moved to outTupp. // // SEND_SAME_REQUEST: // Buffer Layout: C1 D11 D12 D13 C2 C3 D31 D32 // C1, C2 and C3 differ in their downState. // // Returned tuples: (C1 D11), (C1 D12), (C1 D13), (C2 NULL), // (C3 D31), (C3 D32) // // SEND_CONSECUTIVE_REQUEST: // Buffer Layout: C1P1 D11 D12 D13 C2P9 C3P2 D31 D32 // A new control tuple is moved if the difference in // parent index between two control is not equal to the // number of data tuples in between. // // Returned tuples: (C1P1 D11), (C1P2 D12), (C1P3 D13), (C2P9 NULL), // (C3P2 D31), (C3P3 D32) // // // REPLY_GET_UNIQUE_REQUEST: // Buffer Layout: C1P1 D11 D_NULL D13 C2P9 D_NULL C3P2 D31 D32 // // Returned tuples: (C1P1 D11), (C1P1_Q_NO_DATA NULL), // (C1P2_Q_NO_DATA NULL), // (C1P3 D13), (C1P3_Q_NO_DATA NULL), // (C2P9_Q_NO_DATA NULL), // (C3P2 D31), (C3P2_Q_NO_DATA NULL), // (C3P3 D32), (C3P2_Q_NO_DATA NULL) // // // REPLY_GET_SUBSET_REQUEST: // Buffer Layout: C1 D11 D12 D13 C2 C3 D31 D32 // C1, C2 and C3 differ in their downState. // Returned tuples: (C1M1 D11), (C1M2 D12), (C1M3 D13), // (C2 NULL), // (C3M1 D31), (C3M2 D32) // // // REPLY_VSBB_INSERT_REQUEST: // In the following comments, // N means a control tuple, standing for a Q_NO_DATA // E means a control tuple, standing for a Q_SQLERROR // D means a data tuple // C means a diags area // M means a matchNo, associated with a control tuple. // In the following example, VSBB Insert was asked to insert 7 rows. // Buffer Layout: N1M7 N2M0 // Returned Tuples: (N1M1), (N2M1), (N3M1), (N4M1), (N5M1), (N6M1), // (N7M1), (N8M0) // The astute reader may wonder about the presence of the extra (8th) // Q_NO_DATA. This is indeed present, probably to respond to the GET_EOD // that was sent by partition access. // // Q_SQLERROR control tuples use their matchNo member to generate Q_NO_DATA // returned tuples. In this way, the Q_SQLERROR is returned in proper order. // In the following example, VSBB Insert was asked to insert 7 rows, // but an error occurred on the 4th. // Buffer Layout: E1M3 D1 C1 N2M4 N2M0 // Returned Tuples: (N1M1), (N2M1), (N3M1), (E1M0 DATA DIAGS), // (N4M1), (N5M1), (N6M1), (N7M1), (N8M0) // ///////////////////////////////////////////////////////////////////////// NABoolean SqlBuffer::moveOutSendOrReplyData(NABoolean isSend, void * currQState, tupp &outTupp, ControlInfo ** controlInfo, ComDiagsArea ** diagsArea, ExStatisticsArea ** statsArea, Int64 * numStatsBytes, NABoolean noStateChange, NABoolean unpackDA, CollHeap * heap) { if (atEOTD()) return TRUE; // Locate consecutive tupps. tupp_descriptor *dataTuppDesc = 0; tupp_descriptor *diagsTuppDesc = 0; tupp_descriptor *statsTuppDesc = 0; tupp_descriptor *tuppDesc = 0; unsigned short dataDescIndex = 0; TupleDescInfo *dataTuppDescInfo = 0; ComDiagsArea * unpackedDiagsArea = NULL; if (tuppDescIndex_ < maxTuppDesc_) { switch (bufType()) { case NORMAL_: { tuppDesc = tupleDesc(tuppDescIndex_); if (tuppDesc->isControlTuple()) { if (flags_ & IGNORE_CONTROL_FLAG) break; // case done and break out. if (setupSrControlInfo( isSend, tuppDesc ) == DEFER_MORE_TUPPS) break; if (NOT noStateChange) tuppDesc->resetCommFlags(); if (++tuppDescIndex_ < maxTuppDesc_) tuppDesc = tupleDesc(tuppDescIndex_); else break; // tupp is control tuple. } if (tuppDesc->isDataTuple()) { dataTuppDesc = tuppDesc; dataDescIndex = tuppDescIndex_; if (++tuppDescIndex_ < maxTuppDesc_) tuppDesc = tupleDesc(tuppDescIndex_); else break; // tupp is data tuple. } if (tuppDesc->isDiagsTuple()) { if (NOT noStateChange) tuppDesc->resetCommFlags(); diagsTuppDesc = tuppDesc; if (++tuppDescIndex_ < maxTuppDesc_) tuppDesc = tupleDesc(tuppDescIndex_); else break; // tupp is diags tuple. } if (tuppDesc->isStatsTuple()) { if (NOT noStateChange) tuppDesc->resetCommFlags(); statsTuppDesc = tuppDesc; ++tuppDescIndex_; } break; } // case NORMAL_ case DENSE_: { SqlBufferDense* denseBuf = (SqlBufferDense*)(this); tuppDesc = denseBuf->getCurrDense(); if (tuppDesc && tuppDesc->isControlTuple()) { if (flags_ & IGNORE_CONTROL_FLAG) break; // case done and break out. if (setupSrControlInfo( isSend, tuppDesc ) == DEFER_MORE_TUPPS) break; if (NOT noStateChange) tuppDesc->resetCommFlags(); denseBuf->advanceDense(); tuppDesc = denseBuf->getCurrDense(); } if (tuppDesc && tuppDesc->isDataTuple()) { dataTuppDesc = tuppDesc; dataDescIndex = tuppDescIndex_; dataTuppDescInfo = castToSqlBufferDense()->currTupleDesc(); denseBuf->advanceDense(); tuppDesc = denseBuf->getCurrDense(); } if (tuppDesc && tuppDesc->isDiagsTuple()) { if (NOT noStateChange) tuppDesc->resetCommFlags(); diagsTuppDesc = tuppDesc; denseBuf->advanceDense(); tuppDesc = denseBuf->getCurrDense(); } if (tuppDesc && tuppDesc->isStatsTuple()) { if (NOT noStateChange) tuppDesc->resetCommFlags(); statsTuppDesc = tuppDesc; denseBuf->advanceDense(); tuppDesc = denseBuf->getCurrDense(); } break; } // case DENSE_ default: UdrExeAssert(0, "SqlBuffer::moveOutSendOrReplyData() invalid case"); } // switch } // more tupp descs if (controlInfo) { *controlInfo = &srControlInfo_; } srControlInfo_.setIsDataRowPresent(FALSE); if (isSend == TRUE) *(down_state *)currQState = srControlInfo_.getDownState(); else *(up_state *)currQState = srControlInfo_.getUpState(); switch (srFlags_) { case DEFAULT_: case SEND_SAME_REQUEST: { // if next tuple (if present) is data, return it. And advance // position. if (dataTuppDesc) { srControlInfo_.setIsDataRowPresent(TRUE); outTupp = dataTuppDesc; } } break; case SEND_CONSECUTIVE_REQUEST: { if (dataTuppDesc) { srControlInfo_.setIsDataRowPresent(TRUE); outTupp = dataTuppDesc; // advance the parent index srControlInfo_.getDownState().parentIndex++; } } break; case SEND_VSBB_WITH_EOD: { // if next tuple (if present) is data, return it. And advance // position. if (dataTuppDesc) { srControlInfo_.setIsDataRowPresent(TRUE); outTupp = dataTuppDesc; // need to send an EOD on the next call. flags_ |= IGNORE_CONTROL_FLAG; } else { ((down_state *)currQState)->request = ex_queue::GET_EOD; flags_ &= ~IGNORE_CONTROL_FLAG; } } break; case REPLY_GET_UNIQUE_REQUEST: { if (dataTuppDesc) { if (srControlInfo_.getUpState().status == ex_queue::Q_OK_MMORE) { srControlInfo_.setIsDataRowPresent(TRUE); outTupp = dataTuppDesc; // Restore dataDescIndex, dataTuppDesc. // Start at the same data tupple on the next call. // The elseif part will be executed on the next call. tuppDescIndex_ = dataDescIndex; if (castToSqlBufferDense()) // DENSE_ buffer castToSqlBufferDense()->currTupleDesc() = dataTuppDescInfo; statsTuppDesc = diagsTuppDesc = 0; srControlInfo_.getUpState().status = ex_queue::Q_NO_DATA; // We need to return two control info for each data row. // Ignore next tuple on next call to this proc. flags_ |= IGNORE_CONTROL_FLAG; } else if (srControlInfo_.getUpState().status == ex_queue::Q_NO_DATA) { srControlInfo_.getUpState().parentIndex++; srControlInfo_.getUpState().status = ex_queue::Q_OK_MMORE; flags_ &= ~IGNORE_CONTROL_FLAG; } } } break; case REPLY_GET_SUBSET_REQUEST: { if (dataTuppDesc) { srControlInfo_.setIsDataRowPresent(TRUE); outTupp = dataTuppDesc; // advance the match no if (srControlInfo_.getUpState().getMatchNo() != OverflowedMatchNo) { Int64 matchNo64 = srControlInfo_.getUpState().getMatchNo(); srControlInfo_.getUpState().setMatchNo(matchNo64 + 1); } } } break; case REPLY_VSBB_INSERT_REQUEST: { // if next tuple (if present) is data, return it. if (dataTuppDesc) { srControlInfo_.setIsDataRowPresent(TRUE); outTupp = dataTuppDesc; } if ((diagsTuppDesc) && (unpackDA) && (heap)) { ComDiagsArea * d = (ComDiagsArea *)(diagsTuppDesc->getTupleAddress()); unpackedDiagsArea = ComDiagsArea::allocate(heap); unpackedDiagsArea->unpackObj(d->getType(), d->getVersion(), TRUE, // sameEndianness, 0, // dummy for now... (IpcConstMessageBufferPtr) d); if (unpackedDiagsArea->containsRowCountFromEID()) { flags_ |= RETURN_ROWCOUNT; } if (controlInfo) { (*controlInfo)->setIsDiagsAreaUnpacked(TRUE); } } if (srControlInfo_.getUpState().matchNo > 0) { if (flags_ & RETURN_ROWCOUNT) { if (flags_ & ROWCOUNT_RETURNED) ((up_state *)currQState)->matchNo = 0; else { ((up_state *)currQState)->matchNo = (Lng32)unpackedDiagsArea->getRowCount(); unpackedDiagsArea->setContainsRowCountFromEID(FALSE); unpackedDiagsArea->setRowCount(0); flags_ |= ROWCOUNT_RETURNED; } } else ((up_state *)currQState)->matchNo = 1; ((up_state *)currQState)->status = ex_queue::Q_NO_DATA; } else { ((up_state *)currQState)->matchNo = 0; } srControlInfo_.getUpState().downIndex++; // We need to return matchNo control info tuples. // Ignore next tuple on next call to this proc. // It will be advanced after returning all control tuples. flags_ |= IGNORE_CONTROL_FLAG; if (srControlInfo_.getUpState().downIndex >= (queue_index) srControlInfo_.getUpState().matchNo) { flags_ &= ~IGNORE_CONTROL_FLAG; } } break; } // switch on srFlags_ // if next tuple (if present) is diags, return it. if (diagsTuppDesc) { srControlInfo_.setIsDiagsAreaPresent(TRUE); if (unpackedDiagsArea) { *diagsArea = unpackedDiagsArea; } else *diagsArea = (ComDiagsArea *)(diagsTuppDesc->getTupleAddress()); } else { srControlInfo_.setIsDiagsAreaPresent(FALSE); if (diagsArea) *diagsArea = NULL; } // if next tuple (if present) is stats, return it. if (statsArea != NULL) { if (statsTuppDesc) { *statsArea = (ExStatisticsArea *)(statsTuppDesc->getTupleAddress()); *numStatsBytes = sizeof(*statsTuppDesc) + statsTuppDesc->getAllocatedSize(); } else { *statsArea = NULL; *numStatsBytes = 0; } } return FALSE; } Int32 SqlBuffer::setupSrControlInfo( NABoolean isSend, tupp_descriptor *tuppDesc ) { // remember that flags_ were overloaded with relocatedAddress // in the tupp_descriptor (just trying to save some space). // Now that the buffer has reached its destination, the // flags_ field could not be used. ControlInfo *ci = (ControlInfo *)(tuppDesc->getTupleAddress()); srControlInfo_.copyFlags(*ci); if (isSend == TRUE) { srControlInfo_.getDownState() = ci->getDownState(); } else { srControlInfo_.getUpState() = ci->getUpState(); } if (srFlags_ == REPLY_VSBB_INSERT_REQUEST) { // Use downIndex to keep track of how many tuples have been // returned. srControlInfo_.getUpState().downIndex = 0; // SQLERROR reply implies fatal error and OK_MMORE reply implies // nonfatal error for VSBB insert if ((srControlInfo_.getUpState().status == ex_queue::Q_SQLERROR || srControlInfo_.getUpState().status == ex_queue::Q_OK_MMORE ) && srControlInfo_.getUpState().matchNo > 0) { // Will eventually process this ci again, so mark it // so that only one sequence of Q_NO_DATAs are unpacked. ci->getUpState().matchNo = 0; return DEFER_MORE_TUPPS; } } return PROCEED_MORE_TUPPS; } NABoolean SqlBuffer::findAndCancel( queue_index pindex, NABoolean startFromBeginning) { // start at the beginning or at curr, depending on argument. // for each tuple, see if it is a control tuple. // if so, see if downstate.parentIndex matches pindex. // if so, change downstate.request to GET_NOMORE & return TRUE, // if not found, return FALSE. // save and restore tuppDescIndex_, regardless of outcome. Lng32 saveTuppDescIndex = tuppDescIndex_; NABoolean wasFound = FALSE; if (startFromBeginning) position(); while ( ! atEOTD() ) { if (getCurr()->isControlTuple()) { down_state *ds = &((ControlInfo *)(getCurr()->getTupleAddress()))-> getDownState(); if (ds->parentIndex == pindex) { // eureka ds->request = ex_queue::GET_NOMORE; wasFound = TRUE; break; } } advance(); } position(saveTuppDescIndex); return wasFound; } unsigned short SqlBuffer::getNumInvalidTuplesUptoNow() { UdrExeAssert(0, "Do not call the base class method"); return 0; } void SqlBuffer::setNumInvalidTuplesUptoNow(Lng32 val) { UdrExeAssert(0, "Do not call the base class method"); } void SqlBuffer::incNumInvalidTuplesUptoNow() { UdrExeAssert(0, "Do not call the base class method"); } void SqlBuffer::decNumInvalidTuplesUptoNow() { UdrExeAssert(0, "Do not call the base class method"); } void SqlBuffer::advanceToNextValidTuple() { advance(); while ((!(atEOTD())) && getCurr()->isInvalidTuple()) { advance(); incNumInvalidTuplesUptoNow(); } } static Int64 debugCnt = 0; void SqlBuffer::setSignature() { signature_ = ++debugCnt; } NABoolean SqlBuffer::checkSignature(const Int32 nid, const Int32 pid, Int64 *signature, const Int32 action) { if (signature_ <= *signature) { if (action > 0) { char coreFile[512]; msg_mon_dump_process_id(NULL, nid, pid, coreFile); } return FALSE; } *signature = signature_; return TRUE; } //////////////////////////////////////////////////////////////////////////// // class SqlBuffer //////////////////////////////////////////////////////////////////////////// void SqlBufferNormal::init(ULng32 in_size_in_bytes, NABoolean clear) { SqlBuffer::init(in_size_in_bytes, clear); dataOffset_ = ROUND8(sizeof(*this)); // data starts after this object // last byte in buffer, rounded to previous 4 byte boundary tupleDescOffset_ = ROUND4(sizeInBytes_ - 3); numInvalidTuplesUptoCurrentPosition_ = (unsigned short) NO_INVALID_TUPLES; if (clear) memset((char*)this+dataOffset_, 0, freeSpace_); // adjust freeSpace_ to account for the unused bytes due to rounding. freeSpace_ = freeSpace_ - (sizeInBytes_ - tupleDescOffset_); normalBufFlags_ = 0; } void SqlBufferNormal::init() { SqlBuffer::init(); dataOffset_ = ROUND8(sizeof(*this)); // data starts after this object // last byte in buffer, rounded to previous 4 byte boundary tupleDescOffset_ = ROUND4(sizeInBytes_ - 3); numInvalidTuplesUptoCurrentPosition_ = (unsigned short) NO_INVALID_TUPLES; // adjust freeSpace_ to account for the unused bytes due to rounding. freeSpace_ = freeSpace_ - (sizeInBytes_ - tupleDescOffset_); normalBufFlags_ = 0; } // allocate a new tupp descriptor tupp_descriptor *SqlBufferNormal::allocate_tuple_desc(Lng32 tup_data_size) { // NOTE: SqlBufferNormal::allocate_tuple_desc and // SqlBufferNormal::remove_tuple_desc must be kept // consistent. remove_tuple_desc should correctly reverse any // modifications done by the most recent allocate_tuple_desc. UInt32 rounded_size = ROUND8(tup_data_size); Lng32 freeSpaceNeeded = rounded_size + sizeof(tupp_descriptor); if (freeSpace_ < freeSpaceNeeded) // no free space to allocate this tuple return NULL; freeSpace_ -= freeSpaceNeeded; tupp_descriptor * td = tupleDesc(maxTuppDesc_); maxTuppDesc_++; td->init((ULng32)tup_data_size, 0, &((char *)this)[dataOffset_]); dataOffset_ += rounded_size; // if buffer is empty, then change status to partially full. if (bufferStatus_ == EMPTY) bufferStatus_ = PARTIAL; return td; } // adds a tuple descriptor tupp_descriptor *SqlBufferNormal::add_tuple_desc(Lng32 tup_data_size) { return allocate_tuple_desc(tup_data_size); } // removes the last tuple descriptor. void SqlBufferNormal::remove_tuple_desc() { // NOTE: SqlBufferNormal::allocate_tuple_desc and // SqlBufferNormal::remove_tuple_desc must be kept // consistent. remove_tuple_desc should correctly reverse any // modifications done by the most recent allocate_tuple_desc. if (maxTuppDesc_ > 0) { maxTuppDesc_--; tupp_descriptor * td = tupleDesc(maxTuppDesc_); UInt32 rounded_size = ROUND8(td->getAllocatedSize()); dataOffset_ -= rounded_size; freeSpace_ += rounded_size + sizeof(tupp_descriptor); if (maxTuppDesc_ == 0) bufferStatus_ = EMPTY; } } // Resize the last allocated tuple in the Dense buffer. void SqlBufferDense::resize_tupp_desc(UInt32 tup_data_size, char *dataPointer) { #ifndef UDRSERV_BUILD ex_assert(lastTupleDesc(), "resizing non-existant td"); #endif tupp_descriptor * td = lastTupleDesc()->tupleDesc(); UInt32 rounded_new_size = ROUND8(tup_data_size); UInt32 rounded_old_size = ROUND8(td->getAllocatedSize()); Int32 diff = rounded_old_size - rounded_new_size; #ifndef UDRSERV_BUILD ex_assert((diff >= 0), "trying to increase tupp size"); ex_assert(dataPointer == td->getTupleAddress(), "Bad resize"); #endif freeSpace_ += diff; td->setAllocatedSize(tup_data_size); } // adjusts data size in the last tupp descriptor void SqlBufferNormal::resize_tupp_desc(UInt32 tup_data_size, char *dataPointer) { tupp_descriptor * td = tupleDesc(maxTuppDesc_ - 1); UInt32 rounded_new_size = ROUND8(tup_data_size); UInt32 rounded_old_size = ROUND8(td->getAllocatedSize()); Int32 diff = rounded_old_size - rounded_new_size; #ifndef UDRSERV_BUILD ex_assert((diff >= 0), "trying to increase tupp size"); ex_assert(dataPointer == td->getTupleAddress(), "Bad resize"); #endif dataOffset_ -= diff; freeSpace_ += diff; td->setAllocatedSize(tup_data_size); } // RETURNS: -1 if this buffer is free, 0 if not. short SqlBufferNormal::isFree() { // if this buffer is in use by an I/O operation // then don't free it. It has not been filled up yet. if (bufferStatus_ == IN_USE) return 0; // if the buffer is empty then it's free, of course if (bufferStatus_ == EMPTY) return -1; // if all tuple descriptors in this SqlBuffer are not being referenced, // then set the buffer status to EMPTY. // Backward search for efficiency. (eric) for (Int32 i = (maxTuppDesc_ - 1); i >= 0; i--) { if (tupleDesc(i)->getReferenceCount() != 0) // this tuple descriptor is still in use return 0; } return -1; } // positions to the first tuple descriptor in the buffer. void SqlBufferNormal::position() { tuppDescIndex_ = 0; } // positions to the "tupp_desc_num"th tupp descriptor. void SqlBufferNormal::position(Lng32 tupp_desc_num) { tuppDescIndex_ = (unsigned short)tupp_desc_num; } // print buffer info. For debugging void SqlBufferNormal::printInfo() { cerr << this << " Status: " << bufferStatus_ << " maxTuppDesc: " << maxTuppDesc_ << " freeSpace: " << freeSpace_ << " numInvalidTuplesUptoCurrentPosition: " << numInvalidTuplesUptoCurrentPosition_ ; Lng32 refcount = 0; Lng32 firstref = -1; for (Int32 i = 0; (i < maxTuppDesc_); i++) if (tupleDesc(i)->getReferenceCount()) { if (firstref == -1) firstref = i; refcount++; }; cerr << " ref tupps: " << refcount << " first: " << firstref << endl; }; // returns the 'next' tuple descriptor. Increments the // position. Returns null, if none found. tupp_descriptor * SqlBufferNormal::getNext() { if (tuppDescIndex_ < maxTuppDesc_) return tupleDesc(tuppDescIndex_++); else return 0; } // returns the 'prev' tuple descriptor. Decrements the // position. Returns null, if none found. tupp_descriptor * SqlBufferNormal::getPrev() { if (tuppDescIndex_ > 0) return tupleDesc(tuppDescIndex_--); else return 0; } // Returns the "tupp_desc_num"th tupp descriptor. The input // tupp_desc_num is 1-based, so the first tupp_descriptor // is tupp_desc_num = 1. // Returns NULL, if tupp_desc_num is greater than maxTuppDesc_. tupp_descriptor * SqlBufferNormal::getTuppDescriptor(Lng32 tupp_desc_num) { if (tupp_desc_num > maxTuppDesc_) return 0; else return tupleDesc(tupp_desc_num-1); } void SqlBufferNormal::pack() { UInt32 i = 0; while (i < maxTuppDesc_) { tupleDesc(i)->setTupleOffset((Lng32)( (char *)tupleDesc(i)->getTupleAddress() - (char *)this)); i++; } } void SqlBufferNormal::unpack() { UInt32 i = 0; while (i < maxTuppDesc_) { tupleDesc(i)->setTupleAddress((char *)this + tupleDesc(i)->getTupleOffset()); i++; } } // This verify() method will be called only on packed objects. It // should return FALSE if it detects that unpacking the object could // create any internal inconsistencies, or bad pointers that reference // memory outside the bounds of this object. Currently verify() is // only called by the ExUdrTcb class when it receives a data reply // from the non-trusted UDR server. NABoolean SqlBufferNormal::verify(ULng32 maxBytes) const { if ((ULng32) sizeInBytes_ > maxBytes) return FALSE; if (tupleDescOffset_ < sizeof(*this)) return FALSE; ULng32 bytesForTupps = (maxTuppDesc_ * sizeof(tupp_descriptor)); if (bytesForTupps > maxBytes) return FALSE; // We are going to loop through all the tuples and keep track of how // far their data buffers extend. If any data buffer extends beyond // maxBytes or beyond sizeInBytes_ then we must return // FALSE. bytesSeen will represent the end of the furthest reaching // data buffer seen so far. ULng32 bytesSeen = sizeof(*this); tupp_descriptor *tdBase = (tupp_descriptor *) ((char *) this + tupleDescOffset_); for (Int32 i = 0; i < (Int32)maxTuppDesc_; i++) { ULng32 offset = tdBase[-(i+1)].getTupleOffset(); if (offset > dataOffset_) return FALSE; ULng32 endOfData = offset + tdBase[-(i+1)].getAllocatedSize(); bytesSeen = MAXOF(bytesSeen, endOfData); } if (bytesSeen > dataOffset_) return FALSE; if (bytesSeen > maxBytes) return FALSE; if (bytesSeen > (ULng32) sizeInBytes_) return FALSE; return TRUE; } unsigned short SqlBufferNormal::getNumInvalidTuplesUptoNow() { return numInvalidTuplesUptoCurrentPosition_; } void SqlBufferNormal::setNumInvalidTuplesUptoNow(Lng32 val) { UdrExeAssert(val < USHRT_MAX, "total invalid tupps in buffer is larger than USHRT_MAX"); numInvalidTuplesUptoCurrentPosition_ = (unsigned short) val; } void SqlBufferNormal::incNumInvalidTuplesUptoNow() { UdrExeAssert(numInvalidTuplesUptoCurrentPosition_ < USHRT_MAX, "total invalid tupps in buffer is larger than USHRT_MAX"); numInvalidTuplesUptoCurrentPosition_++; } void SqlBufferNormal::decNumInvalidTuplesUptoNow() { numInvalidTuplesUptoCurrentPosition_--; } ///////////////////////////////////////////////////////////////////// // class SqlBufferDense ///////////////////////////////////////////////////////////////////// SqlBufferDense::SqlBufferDense() : SqlBuffer(DENSE_) { currTupleDesc() = NULL; lastTupleDesc() = NULL; numInvalidTuplesUptoCurrentPosition_ = (unsigned short) NO_INVALID_TUPLES; str_pad(filler_, 2, '\0'); } void SqlBufferDense::init(ULng32 in_size_in_bytes, NABoolean clear) { SqlBuffer::init(in_size_in_bytes, FALSE); lastTupleDesc_ = NULL; currTupleDesc_ = NULL; numInvalidTuplesUptoCurrentPosition_ = (unsigned short) NO_INVALID_TUPLES; str_pad(filler_, 2, '\0'); } void SqlBufferDense::init() { SqlBuffer::init(); lastTupleDesc_ = NULL; currTupleDesc_ = NULL; numInvalidTuplesUptoCurrentPosition_ = (unsigned short) NO_INVALID_TUPLES; str_pad(filler_, 2, '\0'); } tupp_descriptor *SqlBufferDense::add_tuple_desc(Lng32 tup_data_size) { ULng32 rounded_size = ROUND8(tup_data_size); short td_size = ROUND8(sizeof(TupleDescInfo)); Lng32 freeSpaceNeeded = td_size + rounded_size; if (freeSpace_ < freeSpaceNeeded) // no free space to allocate this tuple return NULL; maxTuppDesc_ += 1; freeSpace_ -= freeSpaceNeeded; // if buffer is empty, then change status to partially full. if (bufferStatus_ == EMPTY) bufferStatus_ = PARTIAL; TupleDescInfo * tdi = NULL; if (lastTupleDesc()) tdi = (TupleDescInfo *)(lastTupleDesc()->tupleDesc()->getTupleAddress() + ROUND8(lastTupleDesc()->tupleDesc()->getAllocatedSize())); else tdi = firstTupleDesc(); tupp_descriptor * td = tdi->tupleDesc(); td->init((unsigned short)tup_data_size, 0, (char *)td + td_size); setPrevTupleDesc(tdi, lastTupleDesc()); if (lastTupleDesc()) setNextTupleDesc(lastTupleDesc(), tdi); lastTupleDesc() = tdi; setNextTupleDesc(tdi, NULL); return td; } tupp_descriptor *SqlBufferDense::allocate_tuple_desc(Lng32 tup_data_size) { return add_tuple_desc(tup_data_size); } // removes the last tuple descriptor. void SqlBufferDense::remove_tuple_desc() { if (maxTuppDesc_ > 0) { // we got rid of the last tupp_descriptor maxTuppDesc_--; freeSpace_ += (ROUND8(sizeof(tupp_descriptor)) + ROUND8(lastTupleDesc()->tupleDesc()->getAllocatedSize())); if (lastTupleDesc() = getPrevTupleDesc(lastTupleDesc())) // =assignment, NOT == setNextTupleDesc(lastTupleDesc(), NULL); compactBuffer(); if (maxTuppDesc_ == 0) bufferStatus_ = EMPTY; } } short SqlBufferDense::isFree() { // if this buffer is in use by an I/O operation // then don't free it. It has not been filled up yet. if (bufferStatus_ == IN_USE) return 0; // if the buffer is empty then it's free, of course if (bufferStatus_ == EMPTY) return -1; // if all tuple descriptors in this SqlBuffer are not being referenced, // then set the buffer status to EMPTY. TupleDescInfo * tdi = lastTupleDesc(); while (tdi) { if (tdi->tupleDesc()->getReferenceCount() != 0) // this tuple descriptor is still in use return 0; tdi = getPrevTupleDesc(tdi); } return -1; } // positions to the first tuple descriptor in the buffer. void SqlBufferDense::position() { tuppDescIndex_ = 0; currTupleDesc() = firstTupleDesc(); } void SqlBufferDense::position(Lng32 tupp_desc_num) { position(); while ((tuppDescIndex_ != tupp_desc_num) && (tuppDescIndex_ < maxTuppDesc_)) advanceDense(); } // returns the 'next' tuple descriptor. Increments the // position. Returns null, if none found. tupp_descriptor * SqlBufferDense::getNext() { if (tuppDescIndex_ < maxTuppDesc_) { TupleDescInfo * tdi = currTupleDesc(); currTupleDesc() = getNextTupleDesc(tdi); tuppDescIndex_++; return tdi->tupleDesc(); } else return NULL; } // returns the 'prev' tuple descriptor. Decrements the // position. Returns null, if none found. tupp_descriptor * SqlBufferDense::getPrev() { if (tuppDescIndex_ > 0) { TupleDescInfo * tdi = currTupleDesc(); currTupleDesc() = getPrevTupleDesc(tdi); tuppDescIndex_--; return tdi->tupleDesc(); } else return NULL; } // Returns the "tupp_desc_num"th tupp descriptor. The input // tupp_desc_num is 1-based, so the first tupp_descriptor // is tupp_desc_num = 1. // Returns NULL, if tupp_desc_num is greater than maxTuppDesc_. tupp_descriptor * SqlBufferDense::getTuppDescriptor(Lng32 tupp_desc_num) { if (tupp_desc_num > maxTuppDesc_) return 0; else return tupleDesc(tupp_desc_num-1); } SqlBufferHeader::moveStatus SqlBufferDense::moveInVsbbEOD(void * down_q_state) { srFlags_ = SEND_VSBB_WITH_EOD; return MOVE_SUCCESS; } void TupleDescInfo::pack(Long base) { tupleDesc()->setTupleOffset ((Long)tupleDesc()->getTupleAddress() - base); } void TupleDescInfo::unpack(Long base) { tupleDesc()->setTupleAddress((char *)base + tupleDesc()->getTupleOffset()); } void SqlBufferDense::pack() { if (maxTuppDesc_ > 0) { TupleDescInfo * temp = firstTupleDesc(); while (temp) { TupleDescInfo * nextTDI = getNextTupleDesc(temp); temp->pack((Long)this); temp = nextTDI; } } if (lastTupleDesc()) lastTupleDesc() = (TupleDescInfo *)((char *)lastTupleDesc() - (char *)this); if (currTupleDesc()) currTupleDesc() = (TupleDescInfo *)((char *)currTupleDesc() - (char *)this); } void SqlBufferDense::unpack() { if (lastTupleDesc()) lastTupleDesc() = (TupleDescInfo *)((Long)lastTupleDesc() + (char *)this); if (currTupleDesc()) currTupleDesc() = (TupleDescInfo *)((Long)currTupleDesc() + (char *)this); if (maxTuppDesc_ > 0) { TupleDescInfo * temp = firstTupleDesc(); while (temp) { temp->unpack((Long)this); temp = getNextTupleDesc(temp); } } } unsigned short SqlBufferDense::getNumInvalidTuplesUptoNow() { return numInvalidTuplesUptoCurrentPosition_; } void SqlBufferDense::setNumInvalidTuplesUptoNow(Lng32 val) { UdrExeAssert(val < USHRT_MAX, "total invalid tupps in buffer is larger than USHRT_MAX"); numInvalidTuplesUptoCurrentPosition_ = (unsigned short) val; } void SqlBufferDense::incNumInvalidTuplesUptoNow() { UdrExeAssert(numInvalidTuplesUptoCurrentPosition_ < USHRT_MAX, "total invalid tupps in buffer is larger than USHRT_MAX"); numInvalidTuplesUptoCurrentPosition_++; } void SqlBufferDense::decNumInvalidTuplesUptoNow() { numInvalidTuplesUptoCurrentPosition_--; } #define FAILURE { DebugBreak(); } #ifdef DO_INTEGRITY_CHECK void SqlBuffer::integrityCheck( NABoolean ignore_omm_check) { const Lng32 savedTuppDescIndex = getProcessedTuppDescs(); tupp p; ControlInfo * ci = 0; ComDiagsArea * d = NULL; ExStatisticsArea * s = NULL; Int64 numStatsBytes = 0; up_state upState; enum okMMoreType { NOT_KNOWN_ = 0, YES_ = 1, NO_ = 3 } okMMoreHasData = NOT_KNOWN_; position(); while (atEOTD() != -1) { moveOutSendOrReplyData( FALSE, // reply data &upState, p, &ci, &d, &s, &numStatsBytes, TRUE, // noStateChange FALSE, // unpack DA if bufInBuf NULL // CollHeap (needed if unpack DA) ); switch (upState.status) { case ex_queue::Q_NO_DATA: { if (ci->getIsDataRowPresent()) FAILURE; break; } case ex_queue::Q_GET_DONE: case ex_queue::Q_REC_SKIPPED: { if (ci->getIsDataRowPresent()) FAILURE; if (ci->getIsDiagsAreaPresent()) FAILURE; break; } case ex_queue::Q_OK_MMORE: { if (ignore_omm_check) break; switch (okMMoreHasData) { case NOT_KNOWN_: { okMMoreHasData = p.isAllocated() ? YES_ : NO_; break; } case NO_: { if (p.isAllocated() == TRUE) FAILURE; break; } case YES_: { if (p.isAllocated() == FALSE) FAILURE; break; } default: { FAILURE; break; } } break; } case ex_queue::Q_STATS: { if (ci->getIsDataRowPresent()) FAILURE; if (ci->getIsDiagsAreaPresent()) FAILURE; break; } case ex_queue::Q_SQLERROR: { if (!(ci->getIsDiagsAreaPresent())) FAILURE; break; } case ex_queue::Q_INVALID: default: FAILURE; } } position(savedTuppDescIndex); return; } #else // See sql_buffer.h for SqlBufferBase no-op implementation. #endif #ifndef UDRSERV_BUILD //////////////////////////////////////////////////////////////////////////// // class sql_buffer_pool // // Allocate in_number_of_buffers each with a size of buffer_size. // Chain them anchored at buffer_list. //////////////////////////////////////////////////////////////////////////// sql_buffer_pool::sql_buffer_pool(Lng32 numberOfBuffers, Lng32 bufferSize, CollHeap * space, SqlBufferBase::BufferType bufType) : bufType_(bufType), defragBuffer_(NULL), defragTd_(NULL) { ex_assert((space != 0), "Must pass in a non-null Space pointer"); currNumberOfBuffers_ = 0; maxNumberOfBuffers_ = numberOfBuffers; memoryUsed_ = 0; staticBufferList_ = NULL; dynBufferList_ = NULL; space_ = space; defaultBufferSize_ = bufferSize; flags_ = 0; staticBufferList_ = new(space_) Queue(space_); dynBufferList_ = new(space_) Queue(space_); } sql_buffer_pool::~sql_buffer_pool() { char * currBuffer; if (staticBufferList_) { staticBufferList_->position(); while (currBuffer = (char *)(staticBufferList_->getCurr())) { space_->deallocateMemory(currBuffer); // move to the next entry staticBufferList_->advance(); } //delete staticBufferList_; NADELETE(staticBufferList_, Queue, space_); staticBufferList_ = NULL; } if (dynBufferList_) { dynBufferList_->position(); while (currBuffer = (char *)(dynBufferList_->getCurr())) { space_->deallocateMemory(currBuffer); // move to the next entry dynBufferList_->advance(); } //delete dynBufferList_; NADELETE(dynBufferList_, Queue, space_); dynBufferList_ = NULL; } if (defragBuffer_) { space_->deallocateMemory(defragBuffer_); } } SqlBufferBase * sql_buffer_pool::addBuffer(Lng32 totalBufferSize, SqlBufferBase::BufferType bufType, CollHeap * space) { // allocate a size that is divisible by 8, otherwise the data that // is allocated from the end of the buffer won't be aligned properly Lng32 rounded_size = ROUND8(totalBufferSize); // allocate a buffer of the right size char * buf = new(space) char[rounded_size]; SqlBufferBase *newBuffer = NULL; if (bufType == SqlBufferBase::NORMAL_) newBuffer = new(buf) SqlBufferNormal(); else if (bufType == SqlBufferBase::DENSE_) newBuffer = new(buf) SqlBufferDense(); else newBuffer = new(buf) SqlBufferOlt(); // now make the raw data buffer into an sql_buffer newBuffer->init(rounded_size); return newBuffer; } SqlBufferBase * sql_buffer_pool::addBuffer(Queue * bufferList, Lng32 totalBufferSize, SqlBufferBase::BufferType bufType, bool failureIsFatal) { // allocate a size that is divisible by 8, otherwise the data that // is allocated from the end of the buffer won't be aligned properly Lng32 rounded_size = ROUND8(totalBufferSize); // allocate a buffer of the right size char * buf = (char*)space_->allocateMemory(rounded_size, failureIsFatal); if (buf == NULL) { return NULL; } SqlBufferBase *newBuffer = NULL; if (bufType == SqlBufferBase::NORMAL_) newBuffer = new(buf) SqlBufferNormal(); else if (bufType == SqlBufferBase::DENSE_) newBuffer = new(buf) SqlBufferDense(); else newBuffer = new(buf) SqlBufferOlt(); // now make the raw data buffer into an sql_buffer newBuffer->init(rounded_size); // add the newly created buffer to the end of the queue bufferList->insert(newBuffer); // update # of buffers in this pool and memory usage if (bufferList == dynBufferList_) currNumberOfBuffers_++; memoryUsed_ += rounded_size; return newBuffer; } // create a new buffer that is used to hold row temporarily in order // to do defragmentation and create a tuple descriptor tupp_descriptor * sql_buffer_pool::addDefragTuppDescriptor(Lng32 dataSize ) { if (defragTd_) { return defragTd_; } if (!defragBuffer_) { Lng32 neededBufferSize = (Lng32) SqlBufferNeededSize( 1, dataSize ); // allocate a size that is divisible by 8, otherwise the data that // is allocated from the end of the buffer won't be aligned properly Lng32 rounded_size = ROUND8(neededBufferSize); // allocate a buffer of the right size char * buf = (char*)space_->allocateMemory(rounded_size, FALSE); if (buf == NULL) { return NULL; } SqlBufferBase *newBuffer = NULL; if (bufType_ == SqlBufferBase::NORMAL_) newBuffer = new(buf) SqlBufferNormal(); else if (bufType_ == SqlBufferBase::DENSE_) newBuffer = new(buf) SqlBufferDense(); else newBuffer = new(buf) SqlBufferOlt(); // now make the raw data buffer into an sql_buffer newBuffer->init(rounded_size); defragBuffer_ = newBuffer; } tupp_descriptor * td = defragBuffer_->add_tuple_desc(dataSize); defragTd_ = td; return defragTd_; } SqlBufferBase * sql_buffer_pool::addBuffer(Lng32 totalBufferSize, bool failureIsFatal) { return addBuffer(dynBufferList_, totalBufferSize, bufType_, failureIsFatal); } SqlBufferBase * sql_buffer_pool::addBuffer(Lng32 totalBufferSize, SqlBufferBase::BufferType bufType, bool failureIsFatal) { return addBuffer(dynBufferList_, totalBufferSize, bufType, failureIsFatal); } SqlBufferBase * sql_buffer_pool::addBuffer(Lng32 numTupps, Lng32 recordLength) { return addBuffer((Lng32) SqlBufferNeededSize(numTupps,recordLength, ((bufType_ == SqlBufferBase::DENSE_) ? SqlBuffer::DENSE_ : SqlBuffer::NORMAL_))); } SqlBufferBase *sql_buffer_pool::get_free_buffer(Lng32 freeSpace) { return getBuffer(freeSpace,-1); } // RETURNS: 0, if tuple found. -1, if not found. short sql_buffer_pool::get_free_tuple(tupp &tp, Lng32 tupDataSize, SqlBuffer **buf) { if(buf) *buf = NULL; // there is a bug in SqlBufferDense::add_tuple_desc(), when // tup_data_size is 0, the tuple address of next allocated // tupp_descriptor will overlap to the tuple address of // previous allocated tupp_descriptor. // Until fixed, set tupDataSize to 8 if it is 0 if (tupDataSize <= 0) tupDataSize = 8; Lng32 neededSpace = SqlBufferGetTuppSize(tupDataSize,bufType_); SqlBuffer *currBuffer; if (!(currBuffer =getCurrentBuffer(neededSpace))) { currBuffer = (SqlBuffer*)getBuffer(neededSpace); } if (currBuffer) // buffer found { tupp_descriptor *tuple_desc = currBuffer->allocate_tuple_desc(tupDataSize); // failed to set tp to a tuple_descriptor from the pool if (!tuple_desc) return -1; tuple_desc->setReferenceCount(0); tp = tuple_desc; if(buf) *buf = currBuffer; return 0; ///return tuple_desc; } // failed to set tp to a tuple_descriptor from the pool return -1; } //check if the current buffer in the pool has enough space short sql_buffer_pool::currentBufferHasEnoughSpace( Lng32 tupDataSize) { SqlBuffer * currBuffer; if (!(currBuffer = (SqlBuffer *)(activeBufferList()->getCurr()))) { return -1; } Lng32 neededSpace = SqlBufferGetTuppSize(tupDataSize,bufType_); if (neededSpace <= currBuffer->getFreeSpace()) { return 1; } else { return 0; } } SqlBuffer * sql_buffer_pool::getCurrentBuffer() { return ((SqlBuffer *)(activeBufferList()->getCurr())); } // returns a new tupp_descriptor in the pool // that has a data length of tupDataSize. // Sets the reference count to 1. // RETURNS: tupp_descriptor, if tuple found. NULL, otherwise. // If buf is non-Null, also sets buf to the buffer from which // the tupp_descriptor was allocated. This is used to later // resize the tuple if needed. tupp_descriptor * sql_buffer_pool::get_free_tupp_descriptor(Lng32 tupDataSize, SqlBuffer **buf) { if(buf) *buf = NULL; Lng32 neededSpace = SqlBufferGetTuppSize(tupDataSize,bufType_); // get a buffer which is not FULL and can allocate tup_data_size //SqlBuffer *currBuffer = (SqlBuffer*)getBuffer(neededSpace); // this change is not really related to CIF changes but it may imrove // performance. I did a similar change to get_free_tuple function // few years ago and it improved performance SqlBuffer *currBuffer; if (!(currBuffer =getCurrentBuffer(neededSpace))) { currBuffer = (SqlBuffer*)getBuffer(neededSpace); } if (currBuffer) // buffer found { // allocate a tuple_desc of the desired size and assign its // address to tp tupp_descriptor *tuple_desc = currBuffer->allocate_tuple_desc(tupDataSize); // failed to set tp to a tuple_descriptor from the pool if (!tuple_desc) return NULL; tuple_desc->setReferenceCount(1); if(buf) *buf = currBuffer; return tuple_desc; } else // failed to set tp to a tuple_descriptor from the pool return NULL; } void sql_buffer_pool::free_buffers() { SqlBuffer *currBuffer; // position to the first entry activeBufferList()->position(); while (currBuffer = ((SqlBuffer *)(activeBufferList()->getCurr()))) { if (!currBuffer->freeBuffer()) { // couldn't free up this buffer. // Well, at least compact it. currBuffer->compactBuffer(); } // move to the next entry activeBufferList()->advance(); } } void sql_buffer_pool::compact_buffers() { SqlBuffer *currBuffer; // position to the first entry activeBufferList()->position(); while (currBuffer = ((SqlBuffer *)(activeBufferList()->getCurr()))) { currBuffer->compactBuffer(); // move to the next entry activeBufferList()->advance(); } } // for debugging purposes void sql_buffer_pool::printAllBufferInfo() { staticBufferList_->position(); SqlBuffer * buf; while (buf = (SqlBuffer *)staticBufferList_->getNext()) buf->printInfo(); dynBufferList_->position(); while (buf = (SqlBuffer *)dynBufferList_->getNext()) buf->printInfo(); }; SqlBufferBase * sql_buffer_pool::findBuffer(Lng32 freeSpace, Int32 mustBeEmpty) { SqlBuffer *currBuffer; // walk the list until we find a buffer that we like. activeBufferList()->position(); while (currBuffer = ((SqlBuffer *)(activeBufferList()->getCurr()))) { // We like a buffer if it isn't in use by an I/O operation and // if it has enough space. Some callers also require that it must // be empty. if ((currBuffer->bufferStatus_ != SqlBuffer::IN_USE) && (!mustBeEmpty || (currBuffer->bufferStatus_ == SqlBuffer::EMPTY)) && (freeSpace <= currBuffer->getFreeSpace())) { return currBuffer; } else // move to the next entry activeBufferList()->advance(); } // out of luck return NULL; } SqlBuffer * sql_buffer_pool::getCurrentBuffer(Lng32 freeSpace,Int32 mustBeEmpty) { SqlBuffer * currBuffer; if ((currBuffer = (SqlBuffer *)(activeBufferList()->getCurr())) && (currBuffer->bufferStatus_ != SqlBuffer::IN_USE) && (!mustBeEmpty || (currBuffer->bufferStatus_ == SqlBuffer::EMPTY)) && (freeSpace <= currBuffer->getFreeSpace())) { return currBuffer; } else return NULL; } SqlBufferBase * sql_buffer_pool::getBuffer(Lng32 freeSpace, Int32 mustBeEmpty) { SqlBufferBase * result = findBuffer(freeSpace,mustBeEmpty); if (result) return result; // buffer not found. Free up buffers which do not have anyone // pointing to them and search again. free_buffers(); result = findBuffer(freeSpace,mustBeEmpty); if (! result) { if (staticMode()) { // allocate a buffer for some static data structures, // but try to use a denseer buffer size because it is // likely that there won't be a lot of such static structures // (guess that there are 10) Lng32 neededStaticBufferSize; if (freeSpace > 0) neededStaticBufferSize = MINOF((Lng32) SqlBufferNeededSize( 10, freeSpace, bufType_), defaultBufferSize_); else neededStaticBufferSize = defaultBufferSize_; result = addBuffer(staticBufferList_, neededStaticBufferSize, bufType_); } else if (currNumberOfBuffers_ < maxNumberOfBuffers_) { // The requested size may be wrong if the buffer size isn't computed // correctly in codegen. Lng32 bufferHeaderSize = (Lng32) SqlBufferHeaderSize(bufType_); // The space needed supplied by the caller (freeSpace) does not // account for the buffer header (buffer object) size. Add this // space to the needed space Lng32 buffSize = MAXOF(freeSpace+bufferHeaderSize, defaultBufferSize_); // just add another buffer to the dynamic buffer list result = addBuffer(dynBufferList_, buffSize, bufType_); // Possible we can't even get the first buffer due to memory pressure. UdrExeAssert((result != NULL) && (get_number_of_buffers() != 0), "Buffer size not computed correctly at codegen"); } } return result; } void sql_buffer_pool::getUsedMemorySize(UInt32 &staticMemSize, UInt32 &dynMemSize) { staticMemSize = sizeof(sql_buffer_pool); staticMemSize += 2 * sizeof(Queue); char * currBuffer; staticBufferList_->position(); while (currBuffer = (char *)(staticBufferList_->getCurr())) { staticMemSize += ((SqlBuffer *)currBuffer)->get_used_size(); // move to the next entry staticBufferList_->advance(); } dynBufferList_->position(); dynMemSize = 0; while (currBuffer = (char *)(dynBufferList_->getCurr())) { dynMemSize += ((SqlBuffer *)currBuffer)->get_used_size(); // move to the next entry dynBufferList_->advance(); } } void sql_buffer_pool::resizeLastTuple(UInt32 tup_data_size, char *dataPointer) { SqlBuffer *currBuffer = (SqlBuffer *)(activeBufferList()->getCurr()); currBuffer->resize_tupp_desc(tup_data_size, dataPointer); } SqlBufferHeader::moveStatus sql_buffer_pool::moveIn(atp_struct *atp1, atp_struct *atp2, UInt16 tuppIndex, Lng32 tupDataSize, ex_expr_base *moveExpr, NABoolean addBufferIfNeeded, Lng32 bufferSize) { if (defragTd_ && !currentBufferHasEnoughSpace(tupDataSize)) { // get row length after evaluating the expression and try to // to get new tuple with the actual row size. The actual row // size may be smaller that the max row size and may fit in the remaining // buffer space UInt32 defMaxRowLen = tupDataSize; UInt32 defRowLen = defMaxRowLen; defragTd_->setReferenceCount(1); atp2->getTupp(tuppIndex)= defragTd_; ex_expr::exp_return_type retCode; retCode = moveExpr->eval(atp1, atp2, 0, -1, &defRowLen); if (retCode == ex_expr::EXPR_ERROR) { return SqlBufferHeader::MOVE_ERROR; } if (!get_free_tuple(atp2->getTupp(tuppIndex), defRowLen)) { #if (defined(_DEBUG) ) char txt[] = "hashj"; SqlBuffer *buf = getCurrentBuffer(); sql_buffer_pool::logDefragInfo(txt, SqlBufferGetTuppSize(tupDataSize, buf->bufType()), SqlBufferGetTuppSize(defRowLen, buf->bufType()), buf->getFreeSpace(), buf, buf->getTotalTuppDescs()); #endif char * defragDataPointer = defragTd_->getTupleAddress(); char * dataPointer = atp2->getTupp(tuppIndex).getDataPointer(); str_cpy_all(dataPointer, defragDataPointer, defRowLen); return SqlBufferHeader::MOVE_SUCCESS; } } if (get_free_tuple(atp2->getTupp(tuppIndex), tupDataSize)) { if(addBufferIfNeeded) { addBuffer(bufferSize); if (get_free_tuple(atp2->getTupp(tuppIndex), tupDataSize)) { ex_assert(0, "sql_buffer_pool::moveIn() No more space for tuples"); } } else { return SqlBufferHeader::BUFFER_FULL; } } UInt32 maxRowLen = tupDataSize; UInt32 rowLen = maxRowLen; ex_expr::exp_return_type retCode; retCode = moveExpr->eval(atp1, atp2, 0, -1, &rowLen); if (retCode == ex_expr::EXPR_ERROR) { return SqlBufferHeader::MOVE_ERROR; } // Resize the row if the actual size is different from the max size (leftRowLen) if(rowLen != maxRowLen) { resizeLastTuple(rowLen, atp2->getTupp(tuppIndex).getDataPointer()); } return SqlBufferHeader::MOVE_SUCCESS; } SqlBufferHeader::moveStatus sql_buffer_pool::moveIn(atp_struct *atp, UInt16 tuppIndex, Lng32 tupDataSize, char *srcData, NABoolean addBufferIfNeeded, Lng32 bufferSize) { if (get_free_tuple(atp->getTupp(tuppIndex), tupDataSize)) { if(addBufferIfNeeded) { addBuffer(bufferSize); if (get_free_tuple(atp->getTupp(tuppIndex), tupDataSize)) { ex_assert(0, "sql_buffer_pool::moveIn() No more space for tuples"); } } else { return SqlBufferHeader::BUFFER_FULL; } } str_cpy_all(atp->getTupp(tuppIndex).getDataPointer(), srcData, tupDataSize); return SqlBufferHeader::MOVE_SUCCESS; } ///////////////////////////////////////////////////////////////////// // class SqlBufferOlt // // SqlBufferOlt is used to minimize the number of bytes replied // from dp2 to exe. A special version of this is SqlBufferOltSmall // which is used to send data from exe to dp2 and could also be used // during reply if certain conditions are met. // // An OLT buffer can send or reply atmost one data tuple. // No down or up state is sent in the buffer. The OLT PA node // remembers the down state info (parent index, etc) and returns // that to its parent along with data returned by DP2. // // SqlBufferOlt has a header that has send/reply, buffer and content flags. // For description of these flags, see the header file sql_buffer.h. // // Following the header, it can have data + warning diag or an error diag. // It can also have rows affected, row count or stats. Appropriate // flags are set in the header. A tupp descriptor is allocated for each // of the above. // // In the moveReply functions, the diagsArea can either be passed in // as a parameter or can be generated when evaluating an expression. // ///////////////////////////////////////////////////////////////////// void SqlBufferOlt::init(ULng32 in_size_in_bytes, NABoolean clear) { SqlBufferBase::init(in_size_in_bytes, clear); oltBufFlags_ = 0; contents_ = NOTHING_YET_; filler_ = 0; } // reinitialize data members; note that this version of init() // can only be used after a buffer has been initialized via // init(unsigned long). void SqlBufferOlt::init() { SqlBufferBase::init(); oltBufFlags_ = 0; contents_ = NOTHING_YET_; filler_ = 0; } // converts all pointers in tuple descriptors to offset relative // to the beginning of SqlBuffer. NOTE: SqlBuffer is not derived // from the ExGod class but has similar pack and unpack methods. void SqlBufferOlt::pack() { if (containsOltSmall()) return; Int32 numTupps = 0; switch (getContents()) { case ERROR_: case DATA_: case NODATA_ROWCOUNT_: case NODATA_WARNING_: case NODATA_ROWAFFECTED_WARNING_: numTupps = 1; break; case DATA_WARNING_: case NODATA_ROWCOUNT_WARNING_: numTupps = 2; break; } if (isStats()) numTupps++; tupp_descriptor * nextTdesc = NULL; tupp_descriptor * tdesc = getNextTuppDesc(NULL); Int32 i = 0; while (i++ < numTupps) { if (i < numTupps) nextTdesc = getNextTuppDesc(tdesc); tdesc->setTupleOffset((char *)tdesc->getTupleAddress() - (char *)this); tdesc = nextTdesc; } SqlBufferBase::pack(); } void SqlBufferOlt::unpack() { Int32 numTupps = 0; switch (getContents()) { case ERROR_: case DATA_: case NODATA_ROWCOUNT_: case NODATA_WARNING_: case NODATA_ROWAFFECTED_WARNING_: numTupps = 1; break; case DATA_WARNING_: case NODATA_ROWCOUNT_WARNING_: numTupps = 2; break; } if (isStats()) numTupps++; tupp_descriptor * tdesc = NULL; for (Int32 i = 0; i < numTupps; i++) { tdesc = getNextTuppDesc(tdesc); tdesc->setTupleAddress((char *)this + tdesc->getTupleOffset()); } SqlBufferBase::unpack(); } SqlBufferBase::moveStatus SqlBufferOlt::moveInSendData(ULng32 projRowLen, ex_expr_base * expr, atp_struct * atp1, atp_struct * workAtp, unsigned short tuppIndex) { SqlBufferOltSmall * smallBuf = (SqlBufferOltSmall*)getSendDataPtr(); smallBuf->setBufType(SqlBufferHeader::OLT_SMALL_); smallBuf->init(); if (projRowLen > 0) { smallBuf->setSendData(TRUE); tupp_descriptor td; td.init(projRowLen, NULL, smallBuf->sendDataPtr()); workAtp->getTupp(tuppIndex) = &td; ex_expr::exp_return_type rc = expr->eval(atp1, workAtp); workAtp->getTupp(tuppIndex).release(); if (rc == ex_expr::EXPR_ERROR) { return MOVE_ERROR; } // error } // since we are not allocating a tupp desc to indicate the input // row length, set this value in the sizeInBytes_ field. sizeInBytes_ = sizeof(SqlBufferOltSmall) + projRowLen; return MOVE_SUCCESS; } SqlBufferBase::moveStatus SqlBufferOlt::moveInReplyData(NABoolean doMoveControl, NABoolean doMoveData, void * currQState, ULng32 projRowLen, ComDiagsArea * diagsArea, tupp_descriptor ** diagsDesc, ex_expr_base * expr, atp_struct * atp1, atp_struct * workAtp, atp_struct * destAtp, unsigned short tuppIndex, NABoolean doMoveStats, ExStatisticsArea * statsArea, tupp_descriptor ** statsDesc) { if ((((up_state *)currQState)->matchNo > 1) || (diagsArea) || (getContents() == ERROR_) || (getContents() == DATA_WARNING_) || ((statsArea) && (NOT statsArea->smallStatsObj()))) { return moveInSendOrReplyData(FALSE, // reply doMoveControl, doMoveData, currQState, 0, NULL, projRowLen, NULL, diagsArea, diagsDesc, expr, atp1, workAtp, destAtp, tuppIndex, doMoveStats, statsArea, statsDesc); } if (doMoveData) setDataProcessed(TRUE); setContainsOltSmall(TRUE); SqlBufferOltSmall * smallBuf = (SqlBufferOltSmall*)getReplyDataPtr(); if ((doMoveData) || (doMoveControl && (NOT dataProcessed()))) { smallBuf->setBufType(SqlBufferHeader::OLT_SMALL_); smallBuf->init(); // since we are not allocating a tupp desc to indicate the input // row length, set this value in the sizeInBytes_ field. sizeInBytes_ = sizeof(SqlBufferOltSmall); } if (((up_state *)currQState)->status == ex_queue::Q_STATS) { smallBuf->setReplyStatsOnly(TRUE); UdrExeAssert(doMoveStats && statsArea && statsDesc && *statsDesc, "Incorrect parameters for Q_STATS"); } else if (((up_state *)currQState)->matchNo > 0) smallBuf->setReplyRowAffected(TRUE); if (doMoveData) { smallBuf->setReplyData(TRUE); if (expr) { atp_struct * atp = ((destAtp != workAtp) ? destAtp : workAtp); tupp_descriptor td; NABoolean tuppAllocated = FALSE; if (atp->getTupp(tuppIndex).isAllocated()) { atp->getTupp(tuppIndex).setDataPointer((char *)smallBuf+sizeInBytes_); } else { tuppAllocated = TRUE; td.init(projRowLen, NULL, (char *)smallBuf+sizeInBytes_); atp->getTupp(tuppIndex) = &td; } ex_expr::exp_return_type rc = ex_expr::EXPR_OK; if (expr) rc = expr->eval(atp1, workAtp); if (tuppAllocated) { atp->getTupp(tuppIndex).release(); } // an error or warning was returned by expr eval method. // Cannot use small olt buf. if (atp1->getDiagsArea()) { // clean diags area and call moveInSendOrReplyData. // It will reevaluate the expression. atp1->getDiagsArea()->clear(); setContainsOltSmall(FALSE); return moveInSendOrReplyData( FALSE, // reply doMoveControl, doMoveData, currQState, 0, NULL, projRowLen, NULL, atp1->getDiagsArea(), diagsDesc, expr, atp1, workAtp, destAtp, tuppIndex, doMoveStats, statsArea, statsDesc); } // error or warning } // expr passed in sizeInBytes_ += projRowLen; } if ((doMoveStats) && (statsArea) && (statsDesc) && (*statsDesc)) { // allocate space for stats area. short statsAreaLen = (short)statsArea->packedLength(); sizeInBytes_ = ROUND2(sizeInBytes_); *(short*)((char *)smallBuf + sizeInBytes_) = statsAreaLen; sizeInBytes_ += sizeof(short); char * statsAreaLoc = (statsArea->smallStatsObj() ? ((char *)smallBuf+sizeInBytes_) : (char*)( ROUND8 (Long((char*)smallBuf+sizeInBytes_) ) )); (*statsDesc)->init(statsAreaLen, 0, statsAreaLoc); sizeInBytes_ = (statsAreaLoc - (char *)smallBuf) + statsAreaLen; smallBuf->setReplyStats(TRUE); } return MOVE_SUCCESS; } SqlBufferBase::moveStatus SqlBufferOlt::moveInSendOrReplyData(NABoolean isSend, NABoolean doMoveControl, NABoolean doMoveData, void * currQState, ULng32 controlInfoLen, ControlInfo ** controlInfo, ULng32 projRowLen, tupp_descriptor ** outTdesc, ComDiagsArea * diagsArea, tupp_descriptor ** diagsDesc, ex_expr_base * expr, atp_struct * atp1, atp_struct * workAtp, atp_struct * destAtp, unsigned short tuppIndex, NABoolean doMoveStats, ExStatisticsArea * statsArea, tupp_descriptor ** statsDesc, NABoolean useExternalDA, NABoolean callerHasExternalDA, tupp_descriptor * defragTd #if (defined(_DEBUG) ) ,ex_tcb * tcb #endif ,NABoolean noMoveWarnings ) { // this should be used for reply only. if (isSend) return MOVE_ERROR; if ((! diagsArea) && (((up_state *)currQState)->matchNo <= 1) && (getContents() != ERROR_) && (getContents() != DATA_WARNING_) && ((! statsArea) || (statsArea->smallStatsObj()))) { return moveInReplyData(doMoveControl, doMoveData, currQState, projRowLen, diagsArea, diagsDesc, expr, atp1, workAtp, destAtp, tuppIndex, doMoveStats, statsArea, statsDesc); } setContainsOltSmall(FALSE); SqlBuffer::moveStatus retcode = MOVE_SUCCESS; tupp_descriptor * tdesc = NULL; // Genesis 10-040126-2683 and 10-040126-0354. // On entry into this function, sizeInBytes_ represents the max size of the // buffer. This function will later change it to the actual number of bytes // used. Note the max size so that we can ensure the number of bytes used does // not exceed this limit. ULng32 maxBufSize = sizeInBytes_; if ((! doMoveData) && (getContents() != NOTHING_YET_)) { // either one tupp(data or error) or two tupps (data + warning) // have been moved in. Skip them. tdesc = getNextTuppDesc(tdesc); // skip data or error if (getContents() == DATA_WARNING_) tdesc = getNextTuppDesc(tdesc); // skip the warning tupp } if (doMoveData) // (doMoveData) && (projLen > 0)) { setContents(DATA_); tdesc = getNextTuppDesc(tdesc, projRowLen); if (outTdesc != NULL) *outTdesc = tdesc; if (destAtp) destAtp->getTupp(tuppIndex) = tdesc; if ((expr != NULL) && ((expr->eval(atp1, workAtp)) == ex_expr::EXPR_ERROR)) { if ((destAtp) && (workAtp == destAtp)) destAtp->release(); retcode = MOVE_ERROR; } // expr present and error else setDataProcessed(TRUE); // the expr eval could have produced a warning or error diag. // copy it to the diagsArea parameter. A tupp for diag will // be allocated below based on the diagsArea. if (diagsArea == NULL) diagsArea = atp1->getDiagsArea(); } else if ((doMoveControl) && (getContents() == NOTHING_YET_)) // else if ((doMoveControl) && (NOT dataProcessed())) { if (((up_state *)currQState)->status == ex_queue::Q_STATS) { setContents(STATSONLY_); UdrExeAssert(doMoveStats && statsArea && statsDesc && *statsDesc, "Incorrect parameters for Q_STATS"); } else if (((up_state *)currQState)->matchNo == 0) setContents(NODATA_); else if (((up_state *)currQState)->matchNo == 1) setContents(NODATA_ROWAFFECTED_); else { setContents(NODATA_ROWCOUNT_); tdesc = getNextTuppDesc(tdesc, sizeof(Lng32)); *(Lng32*)tdesc->getTupleAddress() = ((up_state *)currQState)->matchNo; } } if (diagsArea != NULL) { if (diagsArea->mainSQLCODE() < 0) { setContents(ERROR_); // allocate space for error diags area. tdesc = getNextTuppDesc(NULL, diagsArea->packedLength()); } else { // Genesis 10-040126-2683 and 10-040126-0354. // When multiple warnings are generated, the total size of the packed // buffer sometimes exceeds the allocated size. When this happens, the // receiving mxci process gets only a partial buffer. And when this // partial buffer is unpacked, it causes an assertion failure. Since // the buffers cant be resized, we have to ensure the diags area // always fits into the space available. So, if there isnt enough // space, we will first try reducing the number of warnings to just // one. If there isnt space for even a single warning, the diags area // wont be packed at all. if ((UInt32) sizeInBytes_ == maxBufSize) { // No data rows are being returned. This diags area is the first // thing to be packed into the buffer. sizeInBytes_ = 0; } if (diagsArea->packedLength() + sizeInBytes_ > maxBufSize) { // We cannot fit all the warnings into the reply buffer. // Delete all but the first warning. while (diagsArea->getNumber(DgSqlCode::WARNING_) > 1) diagsArea->deleteWarning(1); if (diagsArea->packedLength() + sizeInBytes_ > maxBufSize) { // No space for any warnings. // Should never come here because the buffer should always be big // enough to contain at least one warning. diagsArea->deleteWarning(0); } } // move diags area plus warning(s) tdesc = getNextTuppDesc(tdesc, diagsArea->packedLength()); switch (getContents()) { case DATA_: setContents(DATA_WARNING_); break; case NODATA_: setContents(NODATA_WARNING_); break; case NODATA_ROWAFFECTED_: setContents(NODATA_ROWAFFECTED_WARNING_); break; case NODATA_ROWCOUNT_: setContents(NODATA_ROWCOUNT_WARNING_); break; } } if (diagsDesc) *diagsDesc = tdesc; } if ((doMoveStats) && (statsArea != NULL)) { // allocate space for stats area. tdesc = getNextTuppDesc(tdesc, statsArea->packedLength()); if (statsDesc) *statsDesc = tdesc; setIsStats(TRUE); } return retcode; } NABoolean SqlBufferOlt::moveOutSendOrReplyData(NABoolean isSend, void * currQState, tupp &outTupp, ControlInfo ** controlInfo, ComDiagsArea ** diagsArea, ExStatisticsArea ** statsArea, Int64 * numStatsBytes, NABoolean noStateChange, NABoolean unpackDA, CollHeap * heap) { tupp_descriptor * tDesc = NULL; switch (getContents()) { case ERROR_: { tDesc = getNextTuppDesc(tDesc); *diagsArea = (ComDiagsArea *)(tDesc->getTupleAddress()); ((up_state *)currQState)->status = ex_queue::Q_SQLERROR; } break; case DATA_: { tDesc = getNextTuppDesc(tDesc); outTupp = tDesc; ((up_state *)currQState)->status = ex_queue::Q_OK_MMORE; ((up_state *)currQState)->matchNo = 1; } break; case DATA_WARNING_: { tDesc = getNextTuppDesc(tDesc); outTupp = tDesc; ((up_state *)currQState)->status = ex_queue::Q_OK_MMORE; ((up_state *)currQState)->matchNo = 1; tDesc = getNextTuppDesc(tDesc); *diagsArea = (ComDiagsArea *)(tDesc->getTupleAddress()); } break; case NODATA_: { ((up_state *)currQState)->status = ex_queue::Q_NO_DATA; ((up_state *)currQState)->matchNo = 0; } break; case NODATA_ROWAFFECTED_: { ((up_state *)currQState)->status = ex_queue::Q_NO_DATA; ((up_state *)currQState)->matchNo = 1; } break; case NODATA_ROWCOUNT_: { ((up_state *)currQState)->status = ex_queue::Q_NO_DATA; tDesc = getNextTuppDesc(tDesc); ((up_state *)currQState)->matchNo = *(Lng32*)tDesc->getTupleAddress(); } break; case NODATA_WARNING_: { ((up_state *)currQState)->status = ex_queue::Q_NO_DATA; ((up_state *)currQState)->matchNo = 0; tDesc = getNextTuppDesc(tDesc); *diagsArea = (ComDiagsArea *)(tDesc->getTupleAddress()); } break; case NODATA_ROWAFFECTED_WARNING_: { ((up_state *)currQState)->status = ex_queue::Q_NO_DATA; ((up_state *)currQState)->matchNo = 1; tDesc = getNextTuppDesc(tDesc); *diagsArea = (ComDiagsArea *)(tDesc->getTupleAddress()); } break; case NODATA_ROWCOUNT_WARNING_: { ((up_state *)currQState)->status = ex_queue::Q_NO_DATA; tDesc = getNextTuppDesc(tDesc); ((up_state *)currQState)->matchNo = *(Lng32*)tDesc->getTupleAddress(); tDesc = getNextTuppDesc(tDesc); *diagsArea = (ComDiagsArea *)(tDesc->getTupleAddress()); } break; case STATSONLY_: { ((up_state *)currQState)->status = ex_queue::Q_STATS; } break; } if ((isStats()) && (statsArea)) { tDesc = getNextTuppDesc(tDesc); *statsArea = (ExStatisticsArea *)(tDesc->getTupleAddress()); *numStatsBytes = sizeof(*tDesc) + tDesc->getAllocatedSize(); } return FALSE; } // add a new tuple descriptor to the end of the buffer tupp_descriptor *SqlBufferOlt::add_tuple_desc(Lng32 tup_data_size) { return NULL; } // remove the tuple desc with the highest number from the buffer void SqlBufferOlt::remove_tuple_desc() { } //////////////////////////////////////////////////////////////////////////// // class SqlBufferOltSmall //////////////////////////////////////////////////////////////////////////// NABoolean SqlBufferOltSmall::moveOutSendData(tupp &outTupp, ULng32 returnedRowLen) { if (sendData()) { // this input value didn't come with a tupp descriptor. // Allocate one now in this buffer. tupp_descriptor * td = (tupp_descriptor *)((char*)this+ sizeof(SqlBufferOltSmall)+ ROUND8(returnedRowLen)); td->init(returnedRowLen, NULL, (char *)this+sizeof(SqlBufferOltSmall)); outTupp = td; } return FALSE; } NABoolean SqlBufferOltSmall::moveOutReplyData(void * currQState, tupp &outTupp, ULng32 returnedRowLen, ComDiagsArea ** diagsArea, ExStatisticsArea ** statsArea, Int64 * numStatsBytes) { Long replyDataLoc = 0; Long statsAreaLoc = 0; Long dataLoc = 0; short statsAreaLen = 0; if ((replyData()) || (replyStats())) { dataLoc = (Long)this + sizeof(SqlBufferOltSmall); if (replyData()) { replyDataLoc = dataLoc; if (replyStats()) dataLoc = dataLoc + ROUND2(returnedRowLen); else dataLoc = dataLoc + ROUND4(returnedRowLen); } if (replyStats()) { statsAreaLen = *(short*)dataLoc; statsAreaLoc = dataLoc + sizeof(short); // statsAreaLoc = ROUND8(statsAreaLoc); dataLoc = statsAreaLoc + ROUND8(statsAreaLen); } } if (replyData()) { // this reply value didn't come with a tupp descriptor. // Allocate one now in this buffer. tupp_descriptor * td = (tupp_descriptor *)((char*)dataLoc); td->init(returnedRowLen, NULL, (char *)replyDataLoc); outTupp = td; ((up_state *)currQState)->status = ex_queue::Q_OK_MMORE; } else if (replyStatsOnly()) { ((up_state *)currQState)->status = ex_queue::Q_STATS; } else { ((up_state *)currQState)->status = ex_queue::Q_NO_DATA; } if (replyRowAffected()) ((up_state *)currQState)->matchNo = 1; else ((up_state *)currQState)->matchNo = 0; if (replyStats()) { *statsArea = (ExStatisticsArea *)statsAreaLoc; *numStatsBytes = sizeof(short) + statsAreaLen; } return FALSE; } #if (defined(_DEBUG) ) void sql_buffer_pool::logDefragInfo(char * txt, Lng32 neededSpace, Lng32 actNeededSpace, Lng32 freeBuffSpace, void *p, Lng32 NumRowsInBuff, ex_tcb * tcb) { char * envCifLoggingLocation= getenv("CIF_DEFRAG_LOG_LOC"); if (envCifLoggingLocation) { char file2 [255]; snprintf(file2,255,"%s%s",envCifLoggingLocation,"/cif_defrag_logging.log"); FILE * p2 = NULL; p2 =fopen(file2, "a"); if (p2== NULL) { printf("Error in opening a file.."); // file2 } //fprintf(p2,"%s\n","defragmentation"); time_t rawtime; struct tm * timeinfo; time ( &rawtime ); timeinfo = localtime ( &rawtime ); fprintf(p2,"%s %s explainId: %d buffer: %p Neededspace: %d AcualSpace: %d freeSapce: %d NumRowsInBuff: %d\n", asctime (timeinfo), tcb ? tcb->getTdb()->getNodeName() : txt, tcb ? tcb->getTdb()->getExplainNodeId() : -1, p,neededSpace,actNeededSpace,freeBuffSpace,NumRowsInBuff); fclose(p2); } } #endif #endif //UDRSERV_BUILD
27.737368
119
0.620405
liuyazhou
14d6287cf9a4fb3b87856cf5b60c6159e1a453b6
3,420
hpp
C++
include/System/Security/Principal/WindowsImpersonationContext.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/Security/Principal/WindowsImpersonationContext.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/Security/Principal/WindowsImpersonationContext.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: System.IDisposable #include "System/IDisposable.hpp" // Including type: System.IntPtr #include "System/IntPtr.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Type namespace: System.Security.Principal namespace System::Security::Principal { // Size: 0x19 #pragma pack(push, 1) // Autogenerated type: System.Security.Principal.WindowsImpersonationContext // [ComVisibleAttribute] Offset: D7D6CC class WindowsImpersonationContext : public ::Il2CppObject/*, public System::IDisposable*/ { public: // private System.IntPtr _token // Size: 0x8 // Offset: 0x10 System::IntPtr token; // Field size check static_assert(sizeof(System::IntPtr) == 0x8); // private System.Boolean undo // Size: 0x1 // Offset: 0x18 bool undo; // Field size check static_assert(sizeof(bool) == 0x1); // Creating value type constructor for type: WindowsImpersonationContext WindowsImpersonationContext(System::IntPtr token_ = {}, bool undo_ = {}) noexcept : token{token_}, undo{undo_} {} // Creating interface conversion operator: operator System::IDisposable operator System::IDisposable() noexcept { return *reinterpret_cast<System::IDisposable*>(this); } // System.Void .ctor(System.IntPtr token) // Offset: 0x1AD88C8 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static WindowsImpersonationContext* New_ctor(System::IntPtr token) { static auto ___internal__logger = ::Logger::get().WithContext("System::Security::Principal::WindowsImpersonationContext::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<WindowsImpersonationContext*, creationType>(token))); } // public System.Void Dispose() // Offset: 0x1AD8E30 void Dispose(); // public System.Void Undo() // Offset: 0x1AD8E40 void Undo(); // static private System.Boolean CloseToken(System.IntPtr token) // Offset: 0x1AD8F04 static bool CloseToken(System::IntPtr token); // static private System.IntPtr DuplicateToken(System.IntPtr token) // Offset: 0x1AD8DF8 static System::IntPtr DuplicateToken(System::IntPtr token); // static private System.Boolean SetCurrentToken(System.IntPtr token) // Offset: 0x1AD8DFC static bool SetCurrentToken(System::IntPtr token); // static private System.Boolean RevertToSelf() // Offset: 0x1AD8F00 static bool RevertToSelf(); }; // System.Security.Principal.WindowsImpersonationContext #pragma pack(pop) static check_size<sizeof(WindowsImpersonationContext), 24 + sizeof(bool)> __System_Security_Principal_WindowsImpersonationContextSizeCheck; static_assert(sizeof(WindowsImpersonationContext) == 0x19); } DEFINE_IL2CPP_ARG_TYPE(System::Security::Principal::WindowsImpersonationContext*, "System.Security.Principal", "WindowsImpersonationContext");
46.849315
143
0.709942
darknight1050
14d6f2d5ba03d1e3a04bb3b24bc95652e7125096
426
cpp
C++
MODDING_API/src/ModdingAPI.cpp
MagicRB/MODDABLE_RPG
567f007b15eead07bac73608a6e980c138553761
[ "MIT" ]
null
null
null
MODDING_API/src/ModdingAPI.cpp
MagicRB/MODDABLE_RPG
567f007b15eead07bac73608a6e980c138553761
[ "MIT" ]
null
null
null
MODDING_API/src/ModdingAPI.cpp
MagicRB/MODDABLE_RPG
567f007b15eead07bac73608a6e980c138553761
[ "MIT" ]
null
null
null
#include "ModdingAPI.hpp" #include <cmath> #include <iostream> chunkified_pos<int> world_to_chunk(int px, int py) { chunkified_pos<int> ch; ch.chunk_x = floor(px / 64.0f); ch.chunk_y = floor(py / 64.0f); ch.x = abs(px) % 64; ch.y = abs(py) % 64; if (ch.chunk_x < 0) { ch.x = 64 - ch.x; } if (ch.chunk_y < 0) { ch.y = 64 - ch.y; } return ch; } modAPI::modAPI() { } modAPI::~modAPI() { }
14.689655
50
0.561033
MagicRB
14d733430d971b341d314683fcf38baac9a5ed93
5,887
cpp
C++
samples/face/lbf_facemark_detector.cpp
raymanfx/seraphim
4d388d21831d349fe1085bc3cb7c73f5d2b103a7
[ "MIT" ]
null
null
null
samples/face/lbf_facemark_detector.cpp
raymanfx/seraphim
4d388d21831d349fe1085bc3cb7c73f5d2b103a7
[ "MIT" ]
null
null
null
samples/face/lbf_facemark_detector.cpp
raymanfx/seraphim
4d388d21831d349fe1085bc3cb7c73f5d2b103a7
[ "MIT" ]
null
null
null
/* * (C) Copyright 2019 * The Seraphim Project Developers. * * SPDX-License-Identifier: MIT */ #include <csignal> #include <opencv2/imgproc.hpp> #include <opencv2/videoio.hpp> #include <optparse.h> #include <seraphim/polygon.h> #include <seraphim/face/lbf_facemark_detector.h> #include <seraphim/face/lbp_face_detector.h> #include <seraphim/gui.h> #include <seraphim/iop/opencv/mat.h> using namespace sph::face; static bool main_loop = true; void signal_handler(int signal) { switch (signal) { case SIGINT: std::cout << "[SIGNAL] SIGINT: Terminating application" << std::endl; main_loop = false; break; default: std::cout << "[SIGNAL] unknown: " << signal << std::endl; break; } } int main(int argc, char **argv) { int camera_index = 0; std::string model_path; std::string cascade_path; std::shared_ptr<LBPFaceDetector> face_detector = std::shared_ptr<LBPFaceDetector>(new LBPFaceDetector()); LBFFacemarkDetector facemark_detector; std::vector<sph::Polygon<int>> faces; std::vector<FacemarkDetector::Facemarks> facemarks; sph::CoreImage image; cv::Mat frame; std::chrono::high_resolution_clock::time_point t_loop_start; std::chrono::high_resolution_clock::time_point t_frame_captured; long frame_time; long process_time; long fps; long elapsed = 0; // register signal handler signal(SIGINT, signal_handler); // build args sph::cmd::OptionParser optparse; sph::cmd::Option inputOpt; inputOpt.name = "input"; inputOpt.shortname = "i"; inputOpt.description = "Camera index"; inputOpt.arg = true; optparse.add(inputOpt, [&](const std::string &val) { camera_index = std::stoi(val); }); sph::cmd::Option modelOpt; inputOpt.name = "model"; inputOpt.shortname = "m"; inputOpt.description = "File path"; inputOpt.arg = true; inputOpt.required = true; optparse.add(inputOpt, [&](const std::string &val) { model_path = val; }); sph::cmd::Option cascadeOpt; inputOpt.name = "cascade"; inputOpt.shortname = "c"; inputOpt.description = "File path"; inputOpt.arg = true; inputOpt.required = true; optparse.add(inputOpt, [&](const std::string &val) { cascade_path = val; }); sph::cmd::Option helpOpt; helpOpt.name = "help"; helpOpt.shortname = "h"; helpOpt.description = "Show help"; optparse.add(helpOpt, [&](const std::string&) { std::cout << "lbf_facemark_detector [args]" << std::endl << std::endl; for (const auto &str : optparse.help(true)) { std::cout << str << std::endl; } exit(0); }); try { optparse.parse(argc, argv); } catch (const std::exception &e) { std::cout << "[ERROR] " << e.what() << std::endl; return 0; } if (model_path.empty() || cascade_path.empty()) { std::cout << "[ERROR] Missing model or cascade path" << std::endl; return 1; } cv::VideoCapture cap; if (!cap.open(camera_index, cv::CAP_V4L2)) { if (!cap.open(camera_index)) { std::cout << "[ERROR] Failed to open camera: " << camera_index << std::endl; return 1; } } if (!face_detector->load_face_cascade(cascade_path)) { std::cout << "[ERROR Failed to read cascade" << std::endl; return 1; } face_detector->set_target(sph::Computable::Target::CPU); if (!facemark_detector.load_facemark_model(model_path)) { std::cout << "[ERROR Failed to read model" << std::endl; return 1; } facemark_detector.set_target(sph::Computable::Target::CPU); auto viewer = sph::gui::WindowFactory::create("LBF Facemark Detector"); while (main_loop) { t_loop_start = std::chrono::high_resolution_clock::now(); if (!cap.read(frame)) { std::cout << "[ERROR] Failed to read frame" << std::endl; break; } t_frame_captured = std::chrono::high_resolution_clock::now(); frame_time = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::high_resolution_clock::now() - t_loop_start) .count(); faces.clear(); facemarks.clear(); image = sph::iop::cv::to_image(frame); if (image.empty()) { std::cout << "[ERROR] Failed to convert Mat to Image" << std::endl; continue; } face_detector->detect(image, faces); if (faces.size() > 0) { facemark_detector.detect(image, faces, facemarks); } process_time = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::high_resolution_clock::now() - t_frame_captured) .count(); for (const auto &face : facemarks) { for (const auto &landmark : face.landmarks) { for (const auto &point : landmark.second) { cv::circle(frame, cv::Point(point.x, point.y), 1, cv::Scalar(0, 255, 0), 2); } } } fps = 1000 / std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::high_resolution_clock::now() - t_loop_start) .count(); elapsed += std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::high_resolution_clock::now() - t_loop_start) .count(); if (elapsed >= 500) { std::cout << "\r" << "[INFO] frame time: " << frame_time << " ms" << ", process time: " << process_time << " ms" << ", fps: " << fps << std::flush; elapsed = 0; } viewer->show(image); } }
31.31383
96
0.572278
raymanfx
14d83ad941e48001baf6ddca0f1e927411a145c8
2,652
cpp
C++
lib/Model.cpp
TurboCartPig/gfxprog
385c3c05cba4d102179f48b0c2b7abe0474293d6
[ "MIT" ]
1
2020-10-11T23:37:48.000Z
2020-10-11T23:37:48.000Z
lib/Model.cpp
TurboCartPig/gfxprog
385c3c05cba4d102179f48b0c2b7abe0474293d6
[ "MIT" ]
null
null
null
lib/Model.cpp
TurboCartPig/gfxprog
385c3c05cba4d102179f48b0c2b7abe0474293d6
[ "MIT" ]
null
null
null
#include <assimp/Importer.hpp> #include <assimp/postprocess.h> #include <assimp/scene.h> #include <glove/Model.h> #include <iostream> void process_node(const aiScene *scene, const aiNode *node, std::vector<Vertex3DNormTex> &vertices, std::vector<uint32_t> & indices) { for (size_t i = 0; i < node->mNumMeshes; ++i) { const auto *mesh = scene->mMeshes[node->mMeshes[i]]; for (size_t j = 0; j < mesh->mNumVertices; ++j) { assert(mesh->HasPositions()); assert(mesh->HasNormals()); assert(mesh->HasTextureCoords(0)); auto position = glm::vec3(mesh->mVertices[j].x, mesh->mVertices[j].y, mesh->mVertices[j].z); auto normal = glm::vec3(mesh->mNormals[j].x, mesh->mNormals[j].y, mesh->mNormals[j].z); auto uv = glm::vec2(mesh->mTextureCoords[0][j].x, mesh->mTextureCoords[0][j].y); vertices.push_back({position, normal, uv}); } for (size_t j = 0; j < mesh->mNumFaces; ++j) { const auto &face = mesh->mFaces[j]; for (size_t k = 0; k < face.mNumIndices; ++k) { indices.push_back(face.mIndices[k]); } } } for (size_t i = 0; i < node->mNumChildren; ++i) { process_node(scene, node->mChildren[i], vertices, indices); } } Model::Model(const std::string &model_path) { Assimp::Importer importer; const auto *scene = importer.ReadFile(model_path, aiProcessPreset_TargetRealtime_Quality); if (scene == nullptr) { std::cout << "Assimp Error: " << importer.GetErrorString() << std::endl; } assert(scene != nullptr); assert(scene->mRootNode != nullptr); assert(!(scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE)); assert(scene->HasMeshes()); std::vector<Vertex3DNormTex> vertices; std::vector<uint32_t> indices; process_node(scene, scene->mRootNode, vertices, indices); m_vbo = std::make_unique<VertexBuffer<Vertex3DNormTex>>(vertices, indices); } void Model::draw() { m_vbo->draw(); } // template <typename InstanceFormat> // void Model::setInstanceArray(const std::vector<InstanceFormat> &instances) { // m_vbo->setInstanceArray(instances); // } // template void // Model::setInstanceArray<glm::mat4>(const std::vector<glm::mat4> &); template <typename InstanceFormat> void Model::enableInstancing() { m_vbo->enableInstancing<InstanceFormat>(); } template <typename InstanceFormat> void Model::uploadInstanceData( const std::vector<InstanceFormat> &instance_data) { m_vbo->uploadInstanceData(instance_data); } template void Model::enableInstancing<glm::mat4>(); template void Model::uploadInstanceData<glm::mat4>(const std::vector<glm::mat4> &);
30.482759
79
0.662519
TurboCartPig
14d88a6e233c285ba189d1bc7fb2b4e3fc2c4b22
9,025
cpp
C++
serviceMain/src/serviceMain.cpp
epics-base/exampleCPP
bf816da88471171afc6c6b5ed6f912289336c30e
[ "MIT" ]
2
2015-02-09T08:58:06.000Z
2021-11-01T08:16:12.000Z
serviceMain/src/serviceMain.cpp
epics-base/exampleCPP
bf816da88471171afc6c6b5ed6f912289336c30e
[ "MIT" ]
26
2015-06-10T12:03:46.000Z
2021-06-22T15:50:43.000Z
serviceMain/src/serviceMain.cpp
epics-base/exampleCPP
bf816da88471171afc6c6b5ed6f912289336c30e
[ "MIT" ]
10
2015-08-03T20:28:29.000Z
2021-04-16T20:44:44.000Z
/* * Copyright information and license terms for this software can be * found in the file LICENSE that is included with the distribution */ /** * @author mrk */ /* Author: Marty Kraimer */ #include <cstddef> #include <cstdlib> #include <cstddef> #include <string> #include <cstdio> #include <memory> #include <vector> #include <iostream> #include <pv/standardField.h> #include <pv/standardPVField.h> #include <pv/timeStamp.h> #include <pv/pvTimeStamp.h> #include <pv/alarm.h> #include <pv/pvAlarm.h> #include <pv/pvDatabase.h> #include <pv/pvaClient.h> #include <pv/controlSupport.h> #include <pv/scalarAlarmSupport.h> #include <pv/pvAccess.h> #include <pv/serverContext.h> #include <pv/rpcService.h> #include <pv/channelProviderLocal.h> #include <pv/serverContext.h> #include <pv/pvdbcrScalarRecord.h> #include <pv/pvdbcrScalarArrayRecord.h> #include <pv/pvdbcrAddRecord.h> #include <pv/pvdbcrRemoveRecord.h> #include <pv/pvdbcrProcessRecord.h> #include <pv/pvdbcrTraceRecord.h> #include <scalarLimit/scalarLimitRecord.h> #include <powerSupply/powerSupplyRecord.h> #include <linkRecord/getLinkScalarRecord.h> #include <linkRecord/getLinkScalarArrayRecord.h> #include <linkRecord/putLinkScalarRecord.h> #include <linkRecord/putLinkScalarArrayRecord.h> #include <helloPutGet/helloPutGetRecord.h> #include <helloRPC/helloRPCRecord.h> #include <pvcontrol/controlRecord.h> // The following must be the last include for code database uses #include <epicsExport.h> #define epicsExportSharedSymbols using namespace std; using namespace epics::pvData; using namespace epics::pvAccess; using namespace epics::pvDatabase; int main(int argc,char *argv[]) { PVDatabasePtr master = PVDatabase::getMaster(); ChannelProviderLocalPtr channelProvider = getChannelProviderLocal(); std::vector<std::string> recordNames; std::vector<std::string> valueType; recordNames.push_back("PVRboolean"); valueType.push_back("boolean"); recordNames.push_back("PVRbyte"); valueType.push_back("byte"); recordNames.push_back("PVRshort"); valueType.push_back("short"); recordNames.push_back("PVRint"); valueType.push_back("int"); recordNames.push_back("PVRlong"); valueType.push_back("long"); recordNames.push_back("PVRubyte"); valueType.push_back("ubyte"); recordNames.push_back("PVRushort"); valueType.push_back("ushort"); recordNames.push_back("PVRuint"); valueType.push_back("uint"); recordNames.push_back("PVRulong"); valueType.push_back("ulong"); recordNames.push_back("PVRfloat"); valueType.push_back("float"); recordNames.push_back("PVRdouble"); valueType.push_back("double"); recordNames.push_back("PVRdouble01"); valueType.push_back("double"); recordNames.push_back("PVRdouble02"); valueType.push_back("double"); recordNames.push_back("PVRdouble03"); valueType.push_back("double"); recordNames.push_back("PVRdouble04"); valueType.push_back("double"); recordNames.push_back("PVRdouble05"); valueType.push_back("double"); recordNames.push_back("PVRstring"); valueType.push_back("string"); for(size_t i=0;i<recordNames.size(); ++i) { if(!master->addRecord(PvdbcrScalarRecord::create(recordNames[i],valueType[i]))) { cerr << "record " << recordNames[i] << " not added to master\n"; } } recordNames.clear(); valueType.clear(); recordNames.push_back("PVRbooleanArray"); valueType.push_back("boolean"); recordNames.push_back("PVRbyteArray"); valueType.push_back("byte"); recordNames.push_back("PVRshortArray"); valueType.push_back("short"); recordNames.push_back("PVRintArray"); valueType.push_back("int"); recordNames.push_back("PVRlongArray"); valueType.push_back("long"); recordNames.push_back("PVRubyteArray"); valueType.push_back("ubyte"); recordNames.push_back("PVRushortArray"); valueType.push_back("ushort"); recordNames.push_back("PVRuintArray"); valueType.push_back("uint"); recordNames.push_back("PVRulongArray"); valueType.push_back("ulong"); recordNames.push_back("PVRfloatArray"); valueType.push_back("float"); recordNames.push_back("PVRdoubleArray"); valueType.push_back("double"); recordNames.push_back("PVRdouble01Array"); valueType.push_back("double"); recordNames.push_back("PVRdouble02Array"); valueType.push_back("double"); recordNames.push_back("PVRdouble03Array"); valueType.push_back("double"); recordNames.push_back("PVRdouble04Array"); valueType.push_back("double"); recordNames.push_back("PVRdouble05Array"); valueType.push_back("double"); recordNames.push_back("PVRstringArray"); valueType.push_back("string"); for(size_t i=0;i<recordNames.size(); ++i) { if(!master->addRecord(PvdbcrScalarArrayRecord::create(recordNames[i],valueType[i]))) { cerr << "record " << recordNames[i] << " not added to master\n"; } } std::string recordName; recordName = "PVRaddRecord"; if(!master->addRecord(PvdbcrAddRecord::create(recordName))) { cerr << "record " << recordName << " not added to master\n"; } recordName = "PVRremoveRecord"; if(!master->addRecord(PvdbcrRemoveRecord::create(recordName))) { cerr << "record " << recordName << " not added to master\n"; } recordName = "PVRprocessRecord"; if(!master->addRecord(PvdbcrProcessRecord::create(recordName))) { cerr << "record " << recordName << " not added to master\n"; } recordName = "PVRtraceRecord"; if(!master->addRecord(PvdbcrTraceRecord::create(recordName))) { cerr << "record " << recordName << " not added to master\n"; } recordName = "PVRcontrolDouble"; epics::example::control::ControlRecordPtr controlRecordDouble = epics::example::control::ControlRecord::create(recordName,"double"); if(!master->addRecord(controlRecordDouble)) { cerr << "record " << recordName << " not added to master\n"; } recordName = "PVRcontrolUByte"; epics::example::control::ControlRecordPtr controlRecordUByte = epics::example::control::ControlRecord::create(recordName,"ubyte"); master->addRecord(controlRecordUByte); recordName = "PVRpowerSupply"; epics::example::powerSupply::PowerSupplyRecordPtr powerSupply = epics::example::powerSupply::PowerSupplyRecord::create(recordName); if(!master->addRecord(powerSupply)) { cerr << "record " << recordName << " not added to master\n"; } recordName = "PVRgetLinkScalar"; epics::example::linkRecord::GetLinkScalarRecordPtr getLinkScalar = epics::example::linkRecord::GetLinkScalarRecord::create(recordName); if(!master->addRecord(getLinkScalar)) { cerr << "record " << recordName << " not added to master\n"; } recordName = "PVRgetLinkScalarArray"; epics::example::linkRecord::GetLinkScalarArrayRecordPtr getLinkScalarArray = epics::example::linkRecord::GetLinkScalarArrayRecord::create(recordName); if(!master->addRecord(getLinkScalarArray)) { cerr << "record " << recordName << " not added to master\n"; } recordName = "PVRputLinkScalar"; epics::example::linkRecord::PutLinkScalarRecordPtr putLinkScalar = epics::example::linkRecord::PutLinkScalarRecord::create(recordName); if(!master->addRecord(putLinkScalar)) { cerr << "record " << recordName << " not added to master\n"; } recordName = "PVRputLinkScalarArray"; epics::example::linkRecord::PutLinkScalarArrayRecordPtr putLinkScalarArray = epics::example::linkRecord::PutLinkScalarArrayRecord::create(recordName); if(!master->addRecord(putLinkScalarArray)) { cerr << "record " << recordName << " not added to master\n"; } recordName = "PVRhelloPutGet"; epics::example::helloPutGet::HelloPutGetRecordPtr helloPutGet = epics::example::helloPutGet::HelloPutGetRecord::create(recordName); if(!master->addRecord(helloPutGet)) { cerr << recordName << " not added to master\n"; } recordName = "PVRhelloRPC"; epics::example::helloRPC::HelloRPCRecordPtr helloRPC = epics::example::helloRPC::HelloRPCRecord::create(recordName); if(!master->addRecord(helloRPC)) { cerr << recordName << " not added to master\n"; } recordName = "PVRscalarLimitUbyte"; epics::scalarLimit::ScalarLimitRecordCreate::create(recordName,"ubyte"); recordName = "PVRscalarLimitDouble"; epics::scalarLimit::ScalarLimitRecordCreate::create(recordName,"double"); ServerContext::shared_pointer ctx = startPVAServer("local",0,true,true); string str; while(true) { cout << "enter: pvdbl or exit \n"; getline(cin,str); if(str.compare("exit")==0) break; if(str.compare("pvdbl")==0) { PVStringArrayPtr pvNames = master->getRecordNames(); PVStringArray::const_svector xxx = pvNames->view(); for(size_t i=0; i<xxx.size(); ++i) cout<< xxx[i] << endl; } } return 0; }
41.022727
95
0.700831
epics-base
14dace89a156b992fc88b32eb5f5ebe04551b913
2,113
cpp
C++
llvm-2.9/tools/clang/test/CXX/temp/temp.arg/temp.arg.nontype/p1.cpp
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
1
2016-04-09T02:58:13.000Z
2016-04-09T02:58:13.000Z
llvm-2.9/tools/clang/test/CXX/temp/temp.arg/temp.arg.nontype/p1.cpp
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
null
null
null
llvm-2.9/tools/clang/test/CXX/temp/temp.arg/temp.arg.nontype/p1.cpp
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
null
null
null
// RUN: %clang_cc1 -fsyntax-only -verify %s // C++0x [temp.arg.nontype]p1: // // A template-argument for a non-type, non-template template-parameter shall // be one of: // -- an integral constant expression; or // -- the name of a non-type template-parameter ; or namespace non_type_tmpl_param { template <int N> struct X0 { X0(); }; template <int N> X0<N>::X0() { } template <int* N> struct X1 { X1(); }; template <int* N> X1<N>::X1() { } template <int& N> struct X3 { X3(); }; template <int& N> X3<N>::X3() { } template <int (*F)(int)> struct X4 { X4(); }; template <int (*F)(int)> X4<F>::X4() { } template <typename T, int (T::* M)(int)> struct X5 { X5(); }; template <typename T, int (T::* M)(int)> X5<T, M>::X5() { } } // -- the address of an object or function with external linkage, including // function templates and function template-ids but excluding non-static // class members, expressed as & id-expression where the & is optional if // the name refers to a function or array, or if the corresponding // template-parameter is a reference; or namespace addr_of_obj_or_func { template <int* p> struct X0 { }; template <int (*fp)(int)> struct X1 { }; // FIXME: Add reference template parameter tests. int i = 42; int iarr[10]; int f(int i); template <typename T> T f_tmpl(T t); void test() { X0<&i> x0a; X0<iarr> x0b; X1<&f> x1a; X1<f> x1b; X1<f_tmpl> x1c; X1<f_tmpl<int> > x1d; } } // -- a constant expression that evaluates to a null pointer value (4.10); or // -- a constant expression that evaluates to a null member pointer value // (4.11); or // -- a pointer to member expressed as described in 5.3.1. namespace bad_args { template <int* N> struct X0 { }; // expected-note 2{{template parameter is declared here}} int i = 42; X0<&i + 2> x0a; // expected-error{{non-type template argument does not refer to any declaration}} int* iptr = &i; X0<iptr> x0b; // expected-error{{non-type template argument for template parameter of pointer type 'int *' must have its address taken}} }
36.431034
138
0.635589
vidkidz
14db6b31e4a4b8e990d68887ddbc99eae9c16b18
9,281
cpp
C++
Sources/Core/Crypto/hash_functions.cpp
ValtoFrameworks/ClanLib
2d6b59386ce275742653b354a1daab42cab7cb3e
[ "Linux-OpenIB" ]
null
null
null
Sources/Core/Crypto/hash_functions.cpp
ValtoFrameworks/ClanLib
2d6b59386ce275742653b354a1daab42cab7cb3e
[ "Linux-OpenIB" ]
null
null
null
Sources/Core/Crypto/hash_functions.cpp
ValtoFrameworks/ClanLib
2d6b59386ce275742653b354a1daab42cab7cb3e
[ "Linux-OpenIB" ]
null
null
null
/* ** ClanLib SDK ** Copyright (c) 1997-2016 The ClanLib Team ** ** 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 would be ** appreciated but is not 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. ** ** Note: Some of the libraries ClanLib may link to may have additional ** requirements or restrictions. ** ** File Author(s): ** ** Mark Page */ #include "Core/precomp.h" #include "API/Core/Crypto/hash_functions.h" #include "API/Core/System/databuffer.h" #include "Core/Zip/miniz.h" namespace clan { uint32_t HashFunctions::crc32(const void *data, int size, uint32_t running_crc/*=0*/) { uint32_t crc = running_crc; if (crc == 0) crc = mz_crc32(0L, nullptr, 0); return mz_crc32(running_crc, (const unsigned char*)data, size);; } uint32_t HashFunctions::adler32(const void *data, int size, uint32_t running_adler32/*=0*/) { uint32_t adler = running_adler32; if (adler == 0) adler = mz_adler32(0L, nullptr, 0); return mz_adler32(adler, (const unsigned char*)data, size); } std::string HashFunctions::md5(const void *data, int size, bool uppercase) { SHA1 md5; md5.add(data, size); md5.calculate(); return md5.get_hash(uppercase); } std::string HashFunctions::md5(const std::string &data, bool uppercase) { return md5(data.data(), data.length(), uppercase); } std::string HashFunctions::md5(const DataBuffer &data, bool uppercase) { return md5(data.get_data(), data.get_size(), uppercase); } void HashFunctions::md5(const void *data, int size, unsigned char out_hash[16]) { SHA1 md5; md5.add(data, size); md5.calculate(); md5.get_hash(out_hash); } void HashFunctions::md5(const DataBuffer &data, unsigned char out_hash[16]) { md5(data.get_data(), data.get_size(), out_hash); } void HashFunctions::md5(const std::string &data, unsigned char out_hash[16]) { md5(data.data(), data.length(), out_hash); } std::string HashFunctions::sha1(const void *data, int size, bool uppercase) { SHA1 sha1; sha1.add(data, size); sha1.calculate(); return sha1.get_hash(uppercase); } std::string HashFunctions::sha1(const std::string &data, bool uppercase) { return sha1(data.data(), data.length(), uppercase); } std::string HashFunctions::sha1(const DataBuffer &data, bool uppercase) { return sha1(data.get_data(), data.get_size(), uppercase); } void HashFunctions::sha1(const void *data, int size, unsigned char out_hash[20]) { SHA1 sha1; sha1.add(data, size); sha1.calculate(); sha1.get_hash(out_hash); } void HashFunctions::sha1(const DataBuffer &data, unsigned char out_hash[20]) { sha1(data.get_data(), data.get_size(), out_hash); } void HashFunctions::sha1(const std::string &data, unsigned char out_hash[20]) { sha1(data.data(), data.length(), out_hash); } std::string HashFunctions::sha224(const void *data, int size, bool uppercase) { SHA224 sha224; sha224.add(data, size); sha224.calculate(); return sha224.get_hash(uppercase); } std::string HashFunctions::sha224(const std::string &data, bool uppercase) { return sha224(data.data(), data.length(), uppercase); } std::string HashFunctions::sha224(const DataBuffer &data, bool uppercase) { return sha224(data.get_data(), data.get_size(), uppercase); } void HashFunctions::sha224(const void *data, int size, unsigned char out_hash[28]) { SHA224 sha224; sha224.add(data, size); sha224.calculate(); sha224.get_hash(out_hash); } void HashFunctions::sha224(const DataBuffer &data, unsigned char out_hash[28]) { sha224(data.get_data(), data.get_size(), out_hash); } void HashFunctions::sha224(const std::string &data, unsigned char out_hash[28]) { sha224(data.data(), data.length(), out_hash); } std::string HashFunctions::sha256(const void *data, int size, bool uppercase) { SHA256 sha256; sha256.add(data, size); sha256.calculate(); return sha256.get_hash(uppercase); } std::string HashFunctions::sha256(const std::string &data, bool uppercase) { return sha256(data.data(), data.length(), uppercase); } std::string HashFunctions::sha256(const DataBuffer &data, bool uppercase) { return sha256(data.get_data(), data.get_size(), uppercase); } void HashFunctions::sha256(const void *data, int size, unsigned char out_hash[32]) { SHA256 sha256; sha256.add(data, size); sha256.calculate(); sha256.get_hash(out_hash); } void HashFunctions::sha256(const DataBuffer &data, unsigned char out_hash[32]) { sha256(data.get_data(), data.get_size(), out_hash); } void HashFunctions::sha256(const std::string &data, unsigned char out_hash[32]) { sha256(data.data(), data.length(), out_hash); } std::string HashFunctions::sha384(const void *data, int size, bool uppercase) { SHA384 sha384; sha384.add(data, size); sha384.calculate(); return sha384.get_hash(uppercase); } std::string HashFunctions::sha384(const std::string &data, bool uppercase) { return sha384(data.data(), data.length(), uppercase); } std::string HashFunctions::sha384(const DataBuffer &data, bool uppercase) { return sha384(data.get_data(), data.get_size(), uppercase); } void HashFunctions::sha384(const void *data, int size, unsigned char out_hash[48]) { SHA384 sha384; sha384.add(data, size); sha384.calculate(); sha384.get_hash(out_hash); } void HashFunctions::sha384(const DataBuffer &data, unsigned char out_hash[48]) { sha384(data.get_data(), data.get_size(), out_hash); } void HashFunctions::sha384(const std::string &data, unsigned char out_hash[48]) { sha384(data.data(), data.length(), out_hash); } std::string HashFunctions::sha512(const void *data, int size, bool uppercase) { SHA512 sha512; sha512.add(data, size); sha512.calculate(); return sha512.get_hash(uppercase); } std::string HashFunctions::sha512(const std::string &data, bool uppercase) { return sha512(data.data(), data.length(), uppercase); } std::string HashFunctions::sha512(const DataBuffer &data, bool uppercase) { return sha512(data.get_data(), data.get_size(), uppercase); } void HashFunctions::sha512(const void *data, int size, unsigned char out_hash[64]) { SHA512 sha512; sha512.add(data, size); sha512.calculate(); sha512.get_hash(out_hash); } void HashFunctions::sha512(const DataBuffer &data, unsigned char out_hash[64]) { sha512(data.get_data(), data.get_size(), out_hash); } void HashFunctions::sha512(const std::string &data, unsigned char out_hash[64]) { sha512(data.data(), data.length(), out_hash); } std::string HashFunctions::sha512_224(const void *data, int size, bool uppercase) { SHA512_224 sha512_224; sha512_224.add(data, size); sha512_224.calculate(); return sha512_224.get_hash(uppercase); } std::string HashFunctions::sha512_224(const std::string &data, bool uppercase) { return sha512_224(data.data(), data.length(), uppercase); } std::string HashFunctions::sha512_224(const DataBuffer &data, bool uppercase) { return sha512_224(data.get_data(), data.get_size(), uppercase); } void HashFunctions::sha512_224(const void *data, int size, unsigned char out_hash[28]) { SHA512_224 sha512_224; sha512_224.add(data, size); sha512_224.calculate(); sha512_224.get_hash(out_hash); } void HashFunctions::sha512_224(const DataBuffer &data, unsigned char out_hash[28]) { sha512_224(data.get_data(), data.get_size(), out_hash); } void HashFunctions::sha512_224(const std::string &data, unsigned char out_hash[28]) { sha512_224(data.data(), data.length(), out_hash); } std::string HashFunctions::sha512_256(const void *data, int size, bool uppercase) { SHA512_256 sha512_256; sha512_256.add(data, size); sha512_256.calculate(); return sha512_256.get_hash(uppercase); } std::string HashFunctions::sha512_256(const std::string &data, bool uppercase) { return sha512_256(data.data(), data.length(), uppercase); } std::string HashFunctions::sha512_256(const DataBuffer &data, bool uppercase) { return sha512_256(data.get_data(), data.get_size(), uppercase); } void HashFunctions::sha512_256(const void *data, int size, unsigned char out_hash[32]) { SHA512_256 sha512_256; sha512_256.add(data, size); sha512_256.calculate(); sha512_256.get_hash(out_hash); } void HashFunctions::sha512_256(const DataBuffer &data, unsigned char out_hash[32]) { sha512_256(data.get_data(), data.get_size(), out_hash); } void HashFunctions::sha512_256(const std::string &data, unsigned char out_hash[32]) { sha512_256(data.data(), data.length(), out_hash); } }
26.979651
92
0.715225
ValtoFrameworks
14db6e74a5db750e5d0085a2240a93f419041cfc
9,285
cpp
C++
cocos2dx/platform/CCFileUtils.cpp
wingver/cocos2d-x
1e7a0d18a90cc8bb859b876528677e7119b04a49
[ "Zlib", "MIT" ]
1
2019-10-22T07:32:45.000Z
2019-10-22T07:32:45.000Z
cocos2dx/platform/CCFileUtils.cpp
wingver/cocos2d-x
1e7a0d18a90cc8bb859b876528677e7119b04a49
[ "Zlib", "MIT" ]
null
null
null
cocos2dx/platform/CCFileUtils.cpp
wingver/cocos2d-x
1e7a0d18a90cc8bb859b876528677e7119b04a49
[ "Zlib", "MIT" ]
null
null
null
/**************************************************************************** Copyright (c) 2010 cocos2d-x.org http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "CCFileUtils.h" #if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) && (CC_TARGET_PLATFORM != CC_PLATFORM_AIRPLAY) #include <stack> #include <libxml/parser.h> #include <libxml/tree.h> #include <libxml/xmlmemory.h> #include "CCLibxml2.h" #include "CCString.h" #include "CCSAXParser.h" #include "support/zip_support/unzip.h" NS_CC_BEGIN; typedef enum { SAX_NONE = 0, SAX_KEY, SAX_DICT, SAX_INT, SAX_REAL, SAX_STRING }CCSAXState; class CCDictMaker : public CCSAXDelegator { public: CCDictionary<std::string, CCObject*> *m_pRootDict; CCDictionary<std::string, CCObject*> *m_pCurDict; std::stack<CCDictionary<std::string, CCObject*>*> m_tDictStack; std::string m_sCurKey;///< parsed key CCSAXState m_tState; bool m_bInArray; CCMutableArray<CCObject*> *m_pArray; public: CCDictMaker() : m_pRootDict(NULL), m_pCurDict(NULL), m_tState(SAX_NONE), m_pArray(NULL), m_bInArray(false) { } ~CCDictMaker() { } CCDictionary<std::string, CCObject*> *dictionaryWithContentsOfFile(const char *pFileName) { CCSAXParser parser; if (false == parser.init("UTF-8")) { return NULL; } parser.setDelegator(this); parser.parse(pFileName); return m_pRootDict; } void startElement(void *ctx, const char *name, const char **atts) { std::string sName((char*)name); if( sName == "dict" ) { CCDictionary<std::string, CCObject*> *pNewDict = new CCDictionary<std::string, CCObject*>(); if(! m_pRootDict) { m_pRootDict = pNewDict; pNewDict->autorelease(); } else { CCAssert(m_pCurDict && !m_sCurKey.empty(), ""); m_pCurDict->setObject(pNewDict, m_sCurKey); pNewDict->release(); m_sCurKey.clear(); } m_pCurDict = pNewDict; m_tDictStack.push(m_pCurDict); m_tState = SAX_DICT; } else if(sName == "key") { m_tState = SAX_KEY; } else if(sName == "integer") { m_tState = SAX_INT; } else if(sName == "real") { m_tState = SAX_REAL; } else if(sName == "string") { m_tState = SAX_STRING; } else { if (sName == "array") { m_bInArray = true; m_pArray = new CCMutableArray<CCObject*>(); } m_tState = SAX_NONE; } } void endElement(void *ctx, const char *name) { std::string sName((char*)name); if( sName == "dict" ) { m_tDictStack.pop(); if ( !m_tDictStack.empty() ) { m_pCurDict = (CCDictionary<std::string, CCObject*>*)(m_tDictStack.top()); } } else if (sName == "array") { CCAssert(m_bInArray, "The plist file is wrong!"); m_pCurDict->setObject(m_pArray, m_sCurKey); m_pArray->release(); m_pArray = NULL; m_bInArray = false; } else if (sName == "true") { CCString *str = new CCString("1"); if (m_bInArray) { m_pArray->addObject(str); } else { m_pCurDict->setObject(str, m_sCurKey); } str->release(); } else if (sName == "false") { CCString *str = new CCString("0"); if (m_bInArray) { m_pArray->addObject(str); } else { m_pCurDict->setObject(str, m_sCurKey); } str->release(); } m_tState = SAX_NONE; } void textHandler(void *ctx, const char *ch, int len) { if (m_tState == SAX_NONE) { return; } CCString *pText = new CCString(); pText->m_sString = std::string((char*)ch,0,len); switch(m_tState) { case SAX_KEY: m_sCurKey = pText->m_sString; break; case SAX_INT: case SAX_REAL: case SAX_STRING: { CCAssert(!m_sCurKey.empty(), "not found key : <integet/real>"); if (m_bInArray) { m_pArray->addObject(pText); } else { m_pCurDict->setObject(pText, m_sCurKey); } break; } } pText->release(); } }; std::string& CCFileUtils::ccRemoveHDSuffixFromFile(std::string& path) { #if CC_IS_RETINA_DISPLAY_SUPPORTED if( CC_CONTENT_SCALE_FACTOR() == 2 ) { std::string::size_type pos = path.rfind("/") + 1; // the begin index of last part of path std::string::size_type suffixPos = path.rfind(CC_RETINA_DISPLAY_FILENAME_SUFFIX); if (std::string::npos != suffixPos && suffixPos > pos) { CCLog("cocos2d: FilePath(%s) contains suffix(%s), remove it.", path.c_str(), CC_RETINA_DISPLAY_FILENAME_SUFFIX); path.replace(suffixPos, strlen(CC_RETINA_DISPLAY_FILENAME_SUFFIX), ""); } } #endif // CC_IS_RETINA_DISPLAY_SUPPORTED return path; } CCDictionary<std::string, CCObject*> *CCFileUtils::dictionaryWithContentsOfFile(const char *pFileName) { CCDictMaker tMaker; return tMaker.dictionaryWithContentsOfFile(pFileName); } unsigned char* CCFileUtils::getFileDataFromZip(const char* pszZipFilePath, const char* pszFileName, unsigned long * pSize) { unsigned char * pBuffer = NULL; unzFile pFile = NULL; *pSize = 0; do { CC_BREAK_IF(!pszZipFilePath || !pszFileName); CC_BREAK_IF(strlen(pszZipFilePath) == 0); pFile = unzOpen(pszZipFilePath); CC_BREAK_IF(!pFile); int nRet = unzLocateFile(pFile, pszFileName, 1); CC_BREAK_IF(UNZ_OK != nRet); char szFilePathA[260]; unz_file_info FileInfo; nRet = unzGetCurrentFileInfo(pFile, &FileInfo, szFilePathA, sizeof(szFilePathA), NULL, 0, NULL, 0); CC_BREAK_IF(UNZ_OK != nRet); nRet = unzOpenCurrentFile(pFile); CC_BREAK_IF(UNZ_OK != nRet); pBuffer = new unsigned char[FileInfo.uncompressed_size]; int nSize = 0; nSize = unzReadCurrentFile(pFile, pBuffer, FileInfo.uncompressed_size); CCAssert(nSize == 0 || nSize == FileInfo.uncompressed_size, "the file size is wrong"); *pSize = FileInfo.uncompressed_size; unzCloseCurrentFile(pFile); } while (0); if (pFile) { unzClose(pFile); } return pBuffer; } ////////////////////////////////////////////////////////////////////////// // Notification support when getFileData from invalid file path. ////////////////////////////////////////////////////////////////////////// static bool s_bPopupNotify = true; void CCFileUtils::setIsPopupNotify(bool bNotify) { s_bPopupNotify = bNotify; } bool CCFileUtils::getIsPopupNotify() { return s_bPopupNotify; } NS_CC_END; #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) #include "win32/CCFileUtils_win32.cpp" #endif #if (CC_TARGET_PLATFORM == CC_PLATFORM_WOPHONE) #include "wophone/CCFileUtils_wophone.cpp" #endif #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #include "android/CCFileUtils_android.cpp" #endif #endif // (CC_TARGET_PLATFORM != CC_PLATFORM_IOS && CC_TARGET_PLATFORM != CC_PLATFORM_AIRPLAY)
28.925234
123
0.548088
wingver
14dccff1101fa5ec14a714131603e19e95bb6f57
3,277
cc
C++
libcef_dll/ctocpp/zip_reader_ctocpp.cc
desura/desura-cef1
54106e0abdbbb362b4d547af3095faeb467500d3
[ "BSD-3-Clause" ]
1
2017-01-18T17:04:40.000Z
2017-01-18T17:04:40.000Z
libcef_dll/ctocpp/zip_reader_ctocpp.cc
desura/desura-cef1
54106e0abdbbb362b4d547af3095faeb467500d3
[ "BSD-3-Clause" ]
null
null
null
libcef_dll/ctocpp/zip_reader_ctocpp.cc
desura/desura-cef1
54106e0abdbbb362b4d547af3095faeb467500d3
[ "BSD-3-Clause" ]
1
2015-07-14T02:36:29.000Z
2015-07-14T02:36:29.000Z
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. // // --------------------------------------------------------------------------- // // A portion of this file was generated by the CEF translator tool. When // making changes by hand only do so within the body of existing static and // virtual method implementations. See the translator.README.txt file in the // tools directory for more information. // #include "libcef_dll/ctocpp/stream_reader_ctocpp.h" #include "libcef_dll/ctocpp/zip_reader_ctocpp.h" // STATIC METHODS - Body may be edited by hand. CefRefPtr<CefZipReader> CefZipReader::Create(CefRefPtr<CefStreamReader> stream) { cef_zip_reader_t* impl = cef_zip_reader_create( CefStreamReaderCToCpp::Unwrap(stream)); if(impl) return CefZipReaderCToCpp::Wrap(impl); return NULL; } // VIRTUAL METHODS - Body may be edited by hand. bool CefZipReaderCToCpp::MoveToFirstFile() { if(CEF_MEMBER_MISSING(struct_, move_to_first_file)) return false; return struct_->move_to_first_file(struct_) ? true : false; } bool CefZipReaderCToCpp::MoveToNextFile() { if(CEF_MEMBER_MISSING(struct_, move_to_next_file)) return false; return struct_->move_to_next_file(struct_) ? true : false; } bool CefZipReaderCToCpp::MoveToFile(const CefString& fileName, bool caseSensitive) { if(CEF_MEMBER_MISSING(struct_, move_to_file)) return false; return struct_->move_to_file(struct_, fileName.GetStruct(), caseSensitive) ? true : false; } bool CefZipReaderCToCpp::Close() { if(CEF_MEMBER_MISSING(struct_, close)) return false; return struct_->close(struct_) ? true : false; } CefString CefZipReaderCToCpp::GetFileName() { CefString str; if(CEF_MEMBER_MISSING(struct_, get_file_name)) return str; cef_string_userfree_t strPtr = struct_->get_file_name(struct_); str.AttachToUserFree(strPtr); return str; } long CefZipReaderCToCpp::GetFileSize() { if(CEF_MEMBER_MISSING(struct_, get_file_size)) return -1; return struct_->get_file_size(struct_); } time_t CefZipReaderCToCpp::GetFileLastModified() { if(CEF_MEMBER_MISSING(struct_, get_file_last_modified)) return 0; return struct_->get_file_last_modified(struct_); } bool CefZipReaderCToCpp::OpenFile(const CefString& password) { if(CEF_MEMBER_MISSING(struct_, open_file)) return 0; return struct_->open_file(struct_, password.GetStruct()) ? true : false; } bool CefZipReaderCToCpp::CloseFile() { if(CEF_MEMBER_MISSING(struct_, close_file)) return 0; return struct_->close_file(struct_) ? true : false; } int CefZipReaderCToCpp::ReadFile(void* buffer, size_t bufferSize) { if(CEF_MEMBER_MISSING(struct_, read_file)) return -1; return struct_->read_file(struct_, buffer, bufferSize); } long CefZipReaderCToCpp::Tell() { if(CEF_MEMBER_MISSING(struct_, tell)) return -1; return struct_->tell(struct_); } bool CefZipReaderCToCpp::Eof() { if(CEF_MEMBER_MISSING(struct_, eof)) return false; return struct_->eof(struct_) ? true : false; } #ifndef NDEBUG template<> long CefCToCpp<CefZipReaderCToCpp, CefZipReader, cef_zip_reader_t>::DebugObjCt = 0; #endif
23.746377
79
0.732072
desura
14dd6e9a9e101b9f91e2d0ac0255f434f62d4dcb
3,472
cpp
C++
Source/World/Generation/Structures/TreeGenerator.cpp
UglySwedishFish/MineCraft-One-Week-Challenge
2d8859a977224c1f3d184ab8f2d50f17e43ce6ba
[ "Apache-2.0" ]
1
2020-04-21T18:47:09.000Z
2020-04-21T18:47:09.000Z
Source/World/Generation/Structures/TreeGenerator.cpp
UglySwedishFish/MineCraft-One-Week-Challenge
2d8859a977224c1f3d184ab8f2d50f17e43ce6ba
[ "Apache-2.0" ]
null
null
null
Source/World/Generation/Structures/TreeGenerator.cpp
UglySwedishFish/MineCraft-One-Week-Challenge
2d8859a977224c1f3d184ab8f2d50f17e43ce6ba
[ "Apache-2.0" ]
null
null
null
#include "TreeGenerator.h" #include "../../Chunk/Chunk.h" #include "StructureBuilder.h" constexpr BlockId CACTUS = BlockId::Cactus; namespace { void makeCactus1 (Chunk& chunk, Random<std::minstd_rand>& rand, int x, int y, int z) { StructureBuilder builder; builder.makeColumn(x, z, y, rand.intInRange(4, 7), CACTUS); builder.build(chunk); } void makeCactus2 (Chunk& chunk, Random<std::minstd_rand>& rand, int x, int y, int z) { StructureBuilder builder; int height = rand.intInRange(6, 8); builder.makeColumn(x, z, y, height, CACTUS); int stem = height / 2; builder.makeRowX(x - 2, x + 2, stem + y, z, CACTUS); builder.addBlock(x - 2, stem + y + 1, z, CACTUS); builder.addBlock(x - 2, stem + y + 2, z, CACTUS); builder.addBlock(x + 2, stem + y + 1, z, CACTUS); builder.build(chunk); } void makeCactus3 (Chunk& chunk, Random<std::minstd_rand>& rand, int x, int y, int z) { StructureBuilder builder; int height = rand.intInRange(6, 8); builder.makeColumn(x, z, y, height, CACTUS); int stem = height / 2; builder.makeRowZ(z - 2, z + 2, x, stem + y, CACTUS); builder.addBlock(x, stem + y + 1, z - 2, CACTUS); builder.addBlock(x, stem + y + 2, z - 2, CACTUS); builder.addBlock(x, stem + y + 1, z + 2, CACTUS); builder.build(chunk); } }//name space void makeOakTree(Chunk& chunk, Random<std::minstd_rand>& rand, int x, int y, int z) { StructureBuilder builder; int h = rand.intInRange(4, 7); int leafSize = 2; int newY = h + y; builder.fill(newY, x - leafSize, x + leafSize, z - leafSize, z + leafSize, BlockId::OakLeaf); builder.fill(newY - 1, x - leafSize, x + leafSize, z - leafSize, z + leafSize, BlockId::OakLeaf); for (int32_t zLeaf = -leafSize + 1; zLeaf <= leafSize - 1; zLeaf++) { builder.addBlock(x, newY + 1, z + zLeaf, BlockId::OakLeaf); } for (int32_t xLeaf = -leafSize + 1; xLeaf <= leafSize - 1; xLeaf++) { builder.addBlock(x + xLeaf, newY + 1, z, BlockId::OakLeaf); } builder.makeColumn(x, z, y, h, BlockId::OakBark); builder.build(chunk); } void makePalmTree(Chunk& chunk, Random<std::minstd_rand>& rand, int x, int y, int z) { StructureBuilder builder; int height = rand.intInRange(7, 9); int diameter = rand.intInRange(4, 6); for (int xLeaf = -diameter; xLeaf < diameter; xLeaf++) { builder.addBlock(xLeaf + x, y + height, z, BlockId::OakLeaf); } for (int zLeaf = -diameter; zLeaf < diameter; zLeaf++) { builder.addBlock(x, y + height, zLeaf + z, BlockId::OakLeaf); } builder.addBlock(x, y + height - 1, z + diameter, BlockId::OakLeaf); builder.addBlock(x, y + height - 1, z - diameter, BlockId::OakLeaf); builder.addBlock(x + diameter, y + height - 1, z, BlockId::OakLeaf); builder.addBlock(x - diameter, y + height - 1, z, BlockId::OakLeaf); builder.addBlock(x, y + height + 1, z, BlockId::OakLeaf); builder.makeColumn(x, z, y, height, BlockId::OakBark); builder.build(chunk); } void makeCactus(Chunk& chunk, Random<std::minstd_rand>& rand, int x, int y, int z) { int cac = rand.intInRange(0, 2); switch (cac) { case 0: makeCactus1(chunk, rand, x, y, z); break; case 1: makeCactus2(chunk, rand, x, y, z); break; case 2: makeCactus3(chunk, rand, x, y, z); } }
30.191304
102
0.601094
UglySwedishFish
14df380632e44f767b2aae86c8fc5b4a9c599bd3
21,582
hpp
C++
3rdparty/stlsoft/include/stlsoft/obsolete/conversion_veneer.hpp
wohaaitinciu/zpublic
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
[ "Unlicense" ]
50
2015-01-07T01:54:54.000Z
2021-01-15T00:41:48.000Z
3rdparty/stlsoft/include/stlsoft/obsolete/conversion_veneer.hpp
lib1256/zpublic
64c2be9ef1abab878288680bb58122dcc25df81d
[ "Unlicense" ]
2
2016-01-08T19:32:57.000Z
2019-10-11T03:50:34.000Z
3rdparty/stlsoft/include/stlsoft/obsolete/conversion_veneer.hpp
lib1256/zpublic
64c2be9ef1abab878288680bb58122dcc25df81d
[ "Unlicense" ]
39
2015-01-07T02:03:15.000Z
2021-01-15T00:41:50.000Z
/* ///////////////////////////////////////////////////////////////////////// * File: stlsoft/obsolete/conversion_veneer.hpp * * Purpose: Raw conversion veneer class. * * Created: 30th July 2002 * Updated: 10th August 2009 * * Home: http://stlsoft.org/ * * Copyright (c) 2002-2009, Matthew Wilson and Synesis Software * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name(s) of Matthew Wilson and Synesis Software nor the names of * any contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * ////////////////////////////////////////////////////////////////////// */ /// \file stlsoft/obsolete/conversion_veneer.hpp /// /// Raw conversion veneer class. #ifndef STLSOFT_INCL_STLSOFT_OBSOLETE_HPP_CONVERSION_VENEER #define STLSOFT_INCL_STLSOFT_OBSOLETE_HPP_CONVERSION_VENEER #ifndef STLSOFT_DOCUMENTATION_SKIP_SECTION # define STLSOFT_VER_STLSOFT_OBSOLETE_HPP_CONVERSION_VENEER_MAJOR 3 # define STLSOFT_VER_STLSOFT_OBSOLETE_HPP_CONVERSION_VENEER_MINOR 2 # define STLSOFT_VER_STLSOFT_OBSOLETE_HPP_CONVERSION_VENEER_REVISION 2 # define STLSOFT_VER_STLSOFT_OBSOLETE_HPP_CONVERSION_VENEER_EDIT 47 #endif /* !STLSOFT_DOCUMENTATION_SKIP_SECTION */ /* ///////////////////////////////////////////////////////////////////////// * Includes */ #ifndef STLSOFT_INCL_STLSOFT_H_STLSOFT # include <stlsoft/stlsoft.h> #endif /* !STLSOFT_INCL_STLSOFT_H_STLSOFT */ #ifndef STLSOFT_INCL_STLSOFT_UTIL_HPP_CONSTRAINTS # include <stlsoft/util/constraints.hpp> #endif /* !STLSOFT_INCL_STLSOFT_UTIL_HPP_CONSTRAINTS */ /* ///////////////////////////////////////////////////////////////////////// * Namespace */ #ifndef _STLSOFT_NO_NAMESPACE namespace stlsoft { #endif /* _STLSOFT_NO_NAMESPACE */ /* ///////////////////////////////////////////////////////////////////////// * Classes */ // class invalid_conversion /** \brief Prevents any conversion * * \ingroup group__library__obsolete * * \param T The value type * \param C The conversion type */ template< ss_typename_param_k T , ss_typename_param_k C > struct invalid_conversion { protected: /// The invalid type typedef void invalid_type; public: /// The value type typedef T value_type; /// The conversion type typedef C conversion_type; public: /// Converts a pointer to the \c value_type to a pointer to the \c conversion_type static invalid_type convert_pointer(value_type * /* pv */) {} /// Converts a pointer-to-const to the \c value_type to a pointer-to-const to the \c conversion_type static invalid_type convert_const_pointer(value_type const* /* pv */) {} /// Converts a reference to the \c value_type to a reference to the \c conversion_type static invalid_type convert_reference(value_type &/* v */) {} /// Converts a reference-to-const to the \c value_type to a reference-to-const to the \c conversion_type static invalid_type convert_const_reference(value_type const& /* v */) {} /// Pointer conversion type struct pointer_conversion { invalid_type operator ()(value_type * /* pv */) {} }; /// Pointer-to-const conversion type struct pointer_const_conversion { invalid_type operator ()(value_type const* /* pv */) {} }; /// Reference conversion type struct reference_conversion { invalid_type operator ()(value_type &/* v */) {} }; /// Reference-to-const conversion type struct reference_const_conversion { invalid_type operator ()(value_type const& /* v */) {} }; }; // class static_conversion /** \brief Implements conversion via C++'s <code>static_cast</code> * * \ingroup group__library__obsolete * * \param T The value type * \param C The conversion type */ template< ss_typename_param_k T , ss_typename_param_k C > struct static_conversion { public: /// The value type typedef T value_type; /// The conversion type typedef C conversion_type; public: /// Converts a pointer to the \c value_type to a pointer to the \c conversion_type static conversion_type *convert_pointer(value_type *pv) { return static_cast<conversion_type*>(pv); } /// Converts a pointer-to-const to the \c value_type to a pointer-to-const to the \c conversion_type static conversion_type const* convert_const_pointer(value_type const* pv) { return static_cast<conversion_type const*>(pv); } /// Converts a reference to the \c value_type to a reference to the \c conversion_type static conversion_type &convert_reference(value_type &v) { return static_cast<conversion_type&>(v); } /// Converts a reference-to-const to the \c value_type to a reference-to-const to the \c conversion_type static conversion_type const& convert_const_reference(value_type const& v) { return static_cast<conversion_type const&>(v); } /// Pointer conversion type struct pointer_conversion { conversion_type *operator ()(value_type *pv) { return convert_pointer(pv); } }; /// Pointer-to-const conversion type struct pointer_const_conversion { conversion_type const* operator ()(value_type const* pv) { return convert_const_pointer(pv); } }; /// Reference conversion type struct reference_conversion { conversion_type& operator ()(value_type &v) { return convert_reference(v); } }; /// Reference-to-const conversion type struct reference_const_conversion { conversion_type const& operator ()(value_type const& v) { return convert_const_reference(v); } }; }; // class dynamic_conversion /** \brief Implements conversion via C++'s <code>dynamic_cast</code> * * \ingroup group__library__obsolete * * \param T The value type * \param C The conversion type */ template< ss_typename_param_k T , ss_typename_param_k C > struct dynamic_conversion { public: /// The value type typedef T value_type; /// The conversion type typedef C conversion_type; public: /// Converts a pointer to the \c value_type to a pointer to the \c conversion_type static conversion_type *convert_pointer(value_type *pv) { return dynamic_cast<conversion_type*>(pv); } /// Converts a pointer-to-const to the \c value_type to a pointer-to-const to the \c conversion_type static conversion_type const* convert_const_pointer(value_type const* pv) { return dynamic_cast<conversion_type const*>(pv); } /// Converts a reference to the \c value_type to a reference to the \c conversion_type static conversion_type &convert_reference(value_type &v) { return dynamic_cast<conversion_type&>(v); } /// Converts a reference-to-const to the \c value_type to a reference-to-const to the \c conversion_type static conversion_type const& convert_const_reference(value_type const& v) { return dynamic_cast<conversion_type const&>(v); } /// Pointer conversion type struct pointer_conversion { conversion_type *operator ()(value_type *pv) { return convert_pointer(pv); } }; /// Pointer-to-const conversion type struct pointer_const_conversion { conversion_type const* operator ()(value_type const* pv) { return convert_const_pointer(pv); } }; /// Reference conversion type struct reference_conversion { conversion_type& operator ()(value_type &v) { return convert_reference(v); } }; /// Reference-to-const conversion type struct reference_const_conversion { conversion_type const& operator ()(value_type const& v) { return convert_const_reference(v); } }; }; // class reinterpret_conversion /** \brief Implements conversion via C++'s <code>reinterpret_cast</code> * * \ingroup group__library__obsolete * * \param T The value type * \param C The conversion type */ template< ss_typename_param_k T , ss_typename_param_k C > struct reinterpret_conversion { public: /// The value type typedef T value_type; /// The conversion type typedef C conversion_type; public: /// Converts a pointer to the \c value_type to a pointer to the \c conversion_type static conversion_type *convert_pointer(value_type *pv) { return reinterpret_cast<conversion_type*>(pv); } /// Converts a pointer-to-const to the \c value_type to a pointer-to-const to the \c conversion_type static conversion_type const* convert_const_pointer(value_type const* pv) { return reinterpret_cast<conversion_type const*>(pv); } /// Converts a reference to the \c value_type to a reference to the \c conversion_type static conversion_type &convert_reference(value_type &v) { return reinterpret_cast<conversion_type&>(v); } /// Converts a reference-to-const to the \c value_type to a reference-to-const to the \c conversion_type static conversion_type const& convert_const_reference(value_type const& v) { return reinterpret_cast<conversion_type const&>(v); } /// Pointer conversion type struct pointer_conversion { conversion_type *operator ()(value_type *pv) { return convert_pointer(pv); } }; /// Pointer-to-const conversion type struct pointer_const_conversion { conversion_type const* operator ()(value_type const* pv) { return convert_const_pointer(pv); } }; /// Reference conversion type struct reference_conversion { conversion_type& operator ()(value_type &v) { return convert_reference(v); } }; /// Reference-to-const conversion type struct reference_const_conversion { conversion_type const& operator ()(value_type const& v) { return convert_const_reference(v); } }; }; // class c_conversion /** \brief Implements conversion via C-style casts * * \ingroup group__library__obsolete * * \param T The value type * \param C The conversion type */ template< ss_typename_param_k T , ss_typename_param_k C > struct c_conversion { public: /// The value type typedef T value_type; /// The conversion type typedef C conversion_type; public: /// Converts a pointer to the \c value_type to a pointer to the \c conversion_type static conversion_type *convert_pointer(value_type *pv) { return (conversion_type*)(pv); } /// Converts a pointer-to-const to the \c value_type to a pointer-to-const to the \c conversion_type static conversion_type const* convert_const_pointer(value_type const* pv) { return (conversion_type const*)(pv); } /// Converts a reference to the \c value_type to a reference to the \c conversion_type static conversion_type &convert_reference(value_type &v) { return (conversion_type&)(v); } /// Converts a reference-to-const to the \c value_type to a reference-to-const to the \c conversion_type static conversion_type const& convert_const_reference(value_type const& v) { return (conversion_type const&)(v); } /// Pointer conversion type struct pointer_conversion { conversion_type *operator ()(value_type *pv) { return convert_pointer(pv); } }; /// Pointer-to-const conversion type struct pointer_const_conversion { conversion_type const* operator ()(value_type const* pv) { return convert_const_pointer(pv); } }; /// Reference conversion type struct reference_conversion { conversion_type& operator ()(value_type &v) { return convert_reference(v); } }; /// Reference-to-const conversion type struct reference_const_conversion { conversion_type const& operator ()(value_type const& v) { return convert_const_reference(v); } }; }; // class conversion_veneer /** \brief This class allows policy-based control of the four conversions: pointer, non-mutable pointer, reference, non-mutable reference * * \param T The type that will be subjected to the <a href = "http://synesis.com.au/resources/articles/cpp/veneers.pdf">veneer</a> * \param C The type that T will be converted to * \param V The value type. On translators that support default template arguments this defaults to T. * \param P The type that controls the pointer conversion * \param R The type that controls the reference conversion * \param PC The type that controls the pointer-to-const conversion * \param RC The type that controls the reference-to-const conversion * * \ingroup concepts_veneer */ template< ss_typename_param_k T , ss_typename_param_k C #ifdef STLSOFT_CF_TEMPLATE_CLASS_DEFAULT_FUNDAMENTAL_ARGUMENT_SUPPORT , ss_typename_param_k V = T , ss_typename_param_k P = invalid_conversion<T, C> , ss_typename_param_k R = invalid_conversion<T, C> , ss_typename_param_k PC = P , ss_typename_param_k RC = R #else , ss_typename_param_k V , ss_typename_param_k P , ss_typename_param_k R , ss_typename_param_k PC , ss_typename_param_k RC #endif /* STLSOFT_CF_TEMPLATE_CLASS_DEFAULT_FUNDAMENTAL_ARGUMENT_SUPPORT */ > class conversion_veneer : public T { public: /// The parent class type typedef T parent_class_type; /// The conversion type typedef C conversion_type; /// The value type typedef V value_type; /// The pointer conversion type typedef ss_typename_type_k P::pointer_conversion pointer_conversion_type; /// The reference conversion type typedef ss_typename_type_k R::reference_conversion reference_conversion_type; /// The pointer-to-const conversion type typedef ss_typename_type_k PC::pointer_const_conversion pointer_const_conversion_type; /// The reference-to-const conversion type typedef ss_typename_type_k RC::reference_const_conversion reference_const_conversion_type; /// The current parameterisation of the type typedef conversion_veneer<T, C, V, P, R, PC, RC> class_type; // Construction public: /// The default constructor conversion_veneer() { stlsoft_constraint_must_be_same_size(T, class_type); } /// The copy constructor conversion_veneer(class_type const& rhs) : parent_class_type(rhs) { stlsoft_constraint_must_be_same_size(T, class_type); } /// Initialise from a value conversion_veneer(value_type const& rhs) : parent_class_type(rhs) { stlsoft_constraint_must_be_same_size(T, class_type); } #ifdef STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT // For compilers that support member templates, the following constructors // are provided. /// Single parameter constructor template <ss_typename_param_k N1> ss_explicit_k conversion_veneer(N1 &n1) : parent_class_type(n1) {} /// Single parameter constructor template <ss_typename_param_k N1> ss_explicit_k conversion_veneer(N1 *n1) : parent_class_type(n1) {} /// Two parameter constructor template <ss_typename_param_k N1, ss_typename_param_k N2> conversion_veneer(N1 n1, N2 n2) : parent_class_type(n1, n2) {} /// Three parameter constructor template <ss_typename_param_k N1, ss_typename_param_k N2, ss_typename_param_k N3> conversion_veneer(N1 n1, N2 n2, N3 n3) : parent_class_type(n1, n2, n3) {} /// Four parameter constructor template <ss_typename_param_k N1, ss_typename_param_k N2, ss_typename_param_k N3, ss_typename_param_k N4> conversion_veneer(N1 n1, N2 n2, N3 n3, N4 n4) : parent_class_type(n1, n2, n3, n4) {} /// Five parameter constructor template <ss_typename_param_k N1, ss_typename_param_k N2, ss_typename_param_k N3, ss_typename_param_k N4, ss_typename_param_k N5> conversion_veneer(N1 n1, N2 n2, N3 n3, N4 n4, N5 n5) : parent_class_type(n1, n2, n3, n4, n5) {} /// Six parameter constructor template <ss_typename_param_k N1, ss_typename_param_k N2, ss_typename_param_k N3, ss_typename_param_k N4, ss_typename_param_k N5, ss_typename_param_k N6> conversion_veneer(N1 n1, N2 n2, N3 n3, N4 n4, N5 n5, N6 n6) : parent_class_type(n1, n2, n3, n4, n5, n6) {} /// Seven parameter constructor template <ss_typename_param_k N1, ss_typename_param_k N2, ss_typename_param_k N3, ss_typename_param_k N4, ss_typename_param_k N5, ss_typename_param_k N6, ss_typename_param_k N7> conversion_veneer(N1 n1, N2 n2, N3 n3, N4 n4, N5 n5, N6 n6, N7 n7) : parent_class_type(n1, n2, n3, n4, n5, n6, n7) {} /// Eight parameter constructor template <ss_typename_param_k N1, ss_typename_param_k N2, ss_typename_param_k N3, ss_typename_param_k N4, ss_typename_param_k N5, ss_typename_param_k N6, ss_typename_param_k N7, ss_typename_param_k N8> conversion_veneer(N1 n1, N2 n2, N3 n3, N4 n4, N5 n5, N6 n6, N7 n7, N8 n8) : parent_class_type(n1, n2, n3, n4, n5, n6, n7, n8) {} #endif // STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT /// Copy assignment operator class_type& operator =(class_type const& rhs) { static_cast<parent_class_type&>(*this) = rhs; return *this; } /// Copy from a value class_type& operator =(value_type const& rhs) { static_cast<parent_class_type&>(*this) = rhs; return *this; } #ifdef STLSOFT_CF_MEMBER_TEMPLATE_FUNCTION_SUPPORT /// Copy from a value template <ss_typename_param_k T1> class_type& operator =(T1 rhs) { static_cast<parent_class_type&>(*this) = rhs; return *this; } #endif // STLSOFT_CF_MEMBER_TEMPLATE_FUNCTION_SUPPORT // Note that the copy constructor is not defined, and will NOT be defined copy ctor/operator not made // Conversions public: /// Implicit conversion to a reference to the conversion_type operator conversion_type &() { return reference_conversion_type()(*this); } /// Implicit conversion to a reference-to-const to the conversion_type operator conversion_type const& () const { return reference_const_conversion_type()(*this); } /// Address-of operator, returning a pointer to the conversion type conversion_type * operator &() { // Take a local reference, such that the application of the address-of // operator will allow user-defined conversions of the parent_class_type // to be applied. parent_class_type &_this = *this; return pointer_conversion_type()(&_this); } /// Address-of operator, returning a pointer-to-const to the conversion type conversion_type const* operator &() const { // Take a local reference, such that the application of the address-of // operator will allow user-defined conversions of the parent_class_type // to be applied. parent_class_type const& _this = *this; return pointer_const_conversion_type()(&_this); } }; /* ////////////////////////////////////////////////////////////////////// */ #ifndef _STLSOFT_NO_NAMESPACE } // namespace stlsoft #endif /* _STLSOFT_NO_NAMESPACE */ /* ////////////////////////////////////////////////////////////////////// */ #endif /* !STLSOFT_INCL_STLSOFT_OBSOLETE_HPP_CONVERSION_VENEER */ /* ///////////////////////////// end of file //////////////////////////// */
31.69163
205
0.660921
wohaaitinciu
14df72b15cb24dfe3065db9ce7c11d1c257a2752
1,677
cpp
C++
OpenCDMi/CENCParser.cpp
dautapankumardora/rdkservices
d8b60572bcb4ac549b3ab5a9cffa7fbdd0906e15
[ "BSD-2-Clause" ]
11
2020-06-19T15:23:36.000Z
2022-03-29T09:58:48.000Z
OpenCDMi/CENCParser.cpp
dautapankumardora/rdkservices
d8b60572bcb4ac549b3ab5a9cffa7fbdd0906e15
[ "BSD-2-Clause" ]
647
2020-04-07T18:40:51.000Z
2022-03-31T21:07:46.000Z
OpenCDMi/CENCParser.cpp
dautapankumardora/rdkservices
d8b60572bcb4ac549b3ab5a9cffa7fbdd0906e15
[ "BSD-2-Clause" ]
785
2020-03-18T01:47:46.000Z
2022-03-31T15:31:52.000Z
/* * If not stated otherwise in this file or this component's LICENSE file the * following copyright and licenses apply: * * Copyright 2020 RDK Management * * 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 "CENCParser.h" namespace WPEFramework { namespace Plugin { /* static */ const uint8_t CommonEncryptionData::PSSHeader[] = { 0x70, 0x73, 0x73, 0x68 }; /* static */ const uint8_t CommonEncryptionData::CommonEncryption[] = { 0x10, 0x77, 0xef, 0xec, 0xc0, 0xb2, 0x4d, 0x02, 0xac, 0xe3, 0x3c, 0x1e, 0x52, 0xe2, 0xfb, 0x4b }; /* static */ const uint8_t CommonEncryptionData::PlayReady[] = { 0x9a, 0x04, 0xf0, 0x79, 0x98, 0x40, 0x42, 0x86, 0xab, 0x92, 0xe6, 0x5b, 0xe0, 0x88, 0x5f, 0x95 }; /* static */ const uint8_t CommonEncryptionData::WideVine[] = { 0xed, 0xef, 0x8b, 0xa9, 0x79, 0xd6, 0x4a, 0xce, 0xa3, 0xc8, 0x27, 0xdc, 0xd5, 0x1d, 0x21, 0xed }; /* static */ const uint8_t CommonEncryptionData::ClearKey[] = { 0x58, 0x14, 0x7e, 0xc8, 0x04, 0x23, 0x46, 0x59, 0x92, 0xe6, 0xf5, 0x2c, 0x5c, 0xe8, 0xc3, 0xcc }; /* static */ const char CommonEncryptionData::JSONKeyIds[] = "{\"kids\":"; } } // namespace WPEFramework::Plugin
49.323529
173
0.702445
dautapankumardora
14e0fa9bf144ac034c73caec50fdca8ffac24f0e
2,089
cc
C++
engine/service/definition_list.cc
pikacuh/ink
08c2abb5a40a3c75fbaa636d39e572dea3547960
[ "Apache-2.0" ]
1
2021-03-02T22:22:38.000Z
2021-03-02T22:22:38.000Z
engine/service/definition_list.cc
pikacuh/ink
08c2abb5a40a3c75fbaa636d39e572dea3547960
[ "Apache-2.0" ]
null
null
null
engine/service/definition_list.cc
pikacuh/ink
08c2abb5a40a3c75fbaa636d39e572dea3547960
[ "Apache-2.0" ]
1
2021-03-02T22:23:12.000Z
2021-03-02T22:23:12.000Z
// Copyright 2018 Google LLC // // 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 "ink/engine/service/definition_list.h" #include <memory> #include <typeindex> #include "ink/engine/service/common_internal.h" #include "ink/engine/util/dbg/errors.h" namespace ink { namespace service { std::shared_ptr<void> DefinitionList::GetInstance( std::type_index type, const service_internal::TypePointerMap &type_map) const { auto definition_it = definitions_.find(type); if (definition_it != definitions_.end()) { for (const auto dep_type : definition_it->second->DirectDependencies()) { auto dep_it = type_map.find(dep_type); if (dep_it == type_map.end() || dep_it->second == nullptr) { RUNTIME_ERROR("Cannot instantiate service $0: unmet dependency: $1.", type.name(), dep_type.name()); } } return definition_it->second->GetInstance(type_map); } RUNTIME_ERROR("Service $0 is not defined", type.name()); } service_internal::TypeIndexSet DefinitionList::GetDefinedTypes() const { service_internal::TypeIndexSet types; types.reserve(definitions_.size()); for (const auto &pair : definitions_) types.insert(pair.first); return types; } service_internal::TypeIndexSet DefinitionList::GetDirectDependencies( std::type_index type) const { auto definition_it = definitions_.find(type); if (definition_it != definitions_.end()) return definition_it->second->DirectDependencies(); RUNTIME_ERROR("Service $0 is not defined", type.name()); } } // namespace service } // namespace ink
33.693548
77
0.721398
pikacuh
14e26e4628e22a4a8033745d60c59083df74d500
836
cpp
C++
codeforce3/552C. Vanya and Scales.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
codeforce3/552C. Vanya and Scales.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
codeforce3/552C. Vanya and Scales.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
#include <stdio.h> #include <vector> #include <algorithm> using namespace std; int w, m; vector<long long> powers, all[2]; void rec(int i, long long sum, int end, int idx) { if(i == end) { all[idx].push_back(sum); return; } rec(i + 1, sum, end, idx); rec(i + 1, sum + powers[i], end, idx); rec(i + 1, sum - powers[i], end, idx); } int main() { scanf("%d %d", &w, &m); if(w == 2) { puts("YES"); return 0; } long long cur = 1, sum = 0; do { powers.push_back(cur); sum += cur; cur *= w; } while (cur - sum <= m); rec(0, 0, powers.size() / 2, 0); rec(powers.size() / 2, 0, powers.size(), 1); sort(all[0].begin(), all[0].end()); for(int i = 0; i < (int)all[1].size(); ++i) if(binary_search(all[0].begin(), all[0].end(), m + all[1][i])) { puts("YES"); return 0; } puts("NO"); return 0; }
16.076923
66
0.535885
khaled-farouk
14ed2ce9f81b056d311963aef2187f8b0c469ed3
159
cc
C++
SimG4CMS/FP420/src/FP420HitsObject.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
SimG4CMS/FP420/src/FP420HitsObject.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
SimG4CMS/FP420/src/FP420HitsObject.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include "SimG4CMS/FP420/interface/FP420HitsObject.h" FP420HitsObject::FP420HitsObject(std::string n, TrackingSlaveSD::Collection& h) : _hits(h), _name(n) {}
39.75
103
0.773585
ckamtsikis
14ef66febc537f75f74c13bcd7779b5054b50de8
7,942
cpp
C++
src/armnn/backends/test/IsLayerSupportedTest.cpp
KevinRodrigues05/armnn_caffe2_parser
c577f2c6a3b4ddb6ba87a882723c53a248afbeba
[ "MIT" ]
null
null
null
src/armnn/backends/test/IsLayerSupportedTest.cpp
KevinRodrigues05/armnn_caffe2_parser
c577f2c6a3b4ddb6ba87a882723c53a248afbeba
[ "MIT" ]
null
null
null
src/armnn/backends/test/IsLayerSupportedTest.cpp
KevinRodrigues05/armnn_caffe2_parser
c577f2c6a3b4ddb6ba87a882723c53a248afbeba
[ "MIT" ]
null
null
null
// // Copyright © 2017 Arm Ltd. All rights reserved. // See LICENSE file in the project root for full license information. // #include <boost/test/unit_test.hpp> #include "test/TensorHelpers.hpp" #include "LayerTests.hpp" #include "backends/CpuTensorHandle.hpp" #include "backends/RefWorkloadFactory.hpp" #include <string> #include <iostream> #include <backends/ClWorkloadFactory.hpp> #include <backends/NeonWorkloadFactory.hpp> #include "IsLayerSupportedTestImpl.hpp" #include "ClContextControlFixture.hpp" #include "layers/ConvertFp16ToFp32Layer.hpp" #include "layers/ConvertFp32ToFp16Layer.hpp" BOOST_AUTO_TEST_SUITE(IsLayerSupported) BOOST_AUTO_TEST_CASE(IsLayerSupportedLayerTypeMatches) { LayerTypeMatchesTest(); } BOOST_AUTO_TEST_CASE(IsLayerSupportedFloat16Reference) { armnn::RefWorkloadFactory factory; IsLayerSupportedTests<armnn::RefWorkloadFactory, armnn::DataType::Float16>(&factory); } BOOST_AUTO_TEST_CASE(IsLayerSupportedFloat32Reference) { armnn::RefWorkloadFactory factory; IsLayerSupportedTests<armnn::RefWorkloadFactory, armnn::DataType::Float32>(&factory); } BOOST_AUTO_TEST_CASE(IsLayerSupportedUint8Reference) { armnn::RefWorkloadFactory factory; IsLayerSupportedTests<armnn::RefWorkloadFactory, armnn::DataType::QuantisedAsymm8>(&factory); } BOOST_AUTO_TEST_CASE(IsConvertFp16ToFp32SupportedReference) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::RefWorkloadFactory, armnn::ConvertFp16ToFp32Layer, armnn::DataType::Float16, armnn::DataType::Float32>(reasonIfUnsupported); BOOST_CHECK(result); } BOOST_AUTO_TEST_CASE(IsConvertFp16ToFp32SupportedFp32InputReference) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::RefWorkloadFactory, armnn::ConvertFp16ToFp32Layer, armnn::DataType::Float32, armnn::DataType::Float32>(reasonIfUnsupported); BOOST_CHECK(!result); BOOST_CHECK_EQUAL(reasonIfUnsupported, "Layer is not supported with float32 data type input"); } BOOST_AUTO_TEST_CASE(IsConvertFp16ToFp32SupportedFp16OutputReference) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::RefWorkloadFactory, armnn::ConvertFp16ToFp32Layer, armnn::DataType::Float16, armnn::DataType::Float16>(reasonIfUnsupported); BOOST_CHECK(!result); BOOST_CHECK_EQUAL(reasonIfUnsupported, "Layer is not supported with float16 data type output"); } BOOST_AUTO_TEST_CASE(IsConvertFp32ToFp16SupportedReference) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::RefWorkloadFactory, armnn::ConvertFp32ToFp16Layer, armnn::DataType::Float32, armnn::DataType::Float16>(reasonIfUnsupported); BOOST_CHECK(result); } BOOST_AUTO_TEST_CASE(IsConvertFp32ToFp16SupportedFp16InputReference) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::RefWorkloadFactory, armnn::ConvertFp32ToFp16Layer, armnn::DataType::Float16, armnn::DataType::Float16>(reasonIfUnsupported); BOOST_CHECK(!result); BOOST_CHECK_EQUAL(reasonIfUnsupported, "Layer is not supported with float16 data type input"); } BOOST_AUTO_TEST_CASE(IsConvertFp32ToFp16SupportedFp32OutputReference) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::RefWorkloadFactory, armnn::ConvertFp32ToFp16Layer, armnn::DataType::Float32, armnn::DataType::Float32>(reasonIfUnsupported); BOOST_CHECK(!result); BOOST_CHECK_EQUAL(reasonIfUnsupported, "Layer is not supported with float32 data type output"); } #ifdef ARMCOMPUTENEON_ENABLED BOOST_AUTO_TEST_CASE(IsLayerSupportedFloat16Neon) { armnn::NeonWorkloadFactory factory; IsLayerSupportedTests<armnn::NeonWorkloadFactory, armnn::DataType::Float16>(&factory); } BOOST_AUTO_TEST_CASE(IsLayerSupportedFloat32Neon) { armnn::NeonWorkloadFactory factory; IsLayerSupportedTests<armnn::NeonWorkloadFactory, armnn::DataType::Float32>(&factory); } BOOST_AUTO_TEST_CASE(IsLayerSupportedUint8Neon) { armnn::NeonWorkloadFactory factory; IsLayerSupportedTests<armnn::NeonWorkloadFactory, armnn::DataType::QuantisedAsymm8>(&factory); } BOOST_AUTO_TEST_CASE(IsConvertFp16ToFp32SupportedNeon) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::NeonWorkloadFactory, armnn::ConvertFp16ToFp32Layer, armnn::DataType::Float16, armnn::DataType::Float32>(reasonIfUnsupported); BOOST_CHECK(result); } BOOST_AUTO_TEST_CASE(IsConvertFp32ToFp16SupportedNeon) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::NeonWorkloadFactory, armnn::ConvertFp32ToFp16Layer, armnn::DataType::Float32, armnn::DataType::Float16>(reasonIfUnsupported); BOOST_CHECK(result); } #endif //#ifdef ARMCOMPUTENEON_ENABLED. #ifdef ARMCOMPUTECL_ENABLED BOOST_FIXTURE_TEST_CASE(IsLayerSupportedFloat16Cl, ClContextControlFixture) { armnn::ClWorkloadFactory factory; IsLayerSupportedTests<armnn::ClWorkloadFactory, armnn::DataType::Float16>(&factory); } BOOST_FIXTURE_TEST_CASE(IsLayerSupportedFloat32Cl, ClContextControlFixture) { armnn::ClWorkloadFactory factory; IsLayerSupportedTests<armnn::ClWorkloadFactory, armnn::DataType::Float32>(&factory); } BOOST_FIXTURE_TEST_CASE(IsLayerSupportedUint8Cl, ClContextControlFixture) { armnn::ClWorkloadFactory factory; IsLayerSupportedTests<armnn::ClWorkloadFactory, armnn::DataType::QuantisedAsymm8>(&factory); } BOOST_FIXTURE_TEST_CASE(IsConvertFp16ToFp32SupportedCl, ClContextControlFixture) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::ClWorkloadFactory, armnn::ConvertFp16ToFp32Layer, armnn::DataType::Float16, armnn::DataType::Float32>(reasonIfUnsupported); BOOST_CHECK(result); } BOOST_FIXTURE_TEST_CASE(IsConvertFp16ToFp32SupportedFp32InputCl, ClContextControlFixture) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::ClWorkloadFactory, armnn::ConvertFp16ToFp32Layer, armnn::DataType::Float32, armnn::DataType::Float32>(reasonIfUnsupported); BOOST_CHECK(!result); BOOST_CHECK_EQUAL(reasonIfUnsupported, "Input should be Float16"); } BOOST_FIXTURE_TEST_CASE(IsConvertFp16ToFp32SupportedFp16OutputCl, ClContextControlFixture) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::ClWorkloadFactory, armnn::ConvertFp16ToFp32Layer, armnn::DataType::Float16, armnn::DataType::Float16>(reasonIfUnsupported); BOOST_CHECK(!result); BOOST_CHECK_EQUAL(reasonIfUnsupported, "Output should be Float32"); } BOOST_FIXTURE_TEST_CASE(IsConvertFp32ToFp16SupportedCl, ClContextControlFixture) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::ClWorkloadFactory, armnn::ConvertFp32ToFp16Layer, armnn::DataType::Float32, armnn::DataType::Float16>(reasonIfUnsupported); BOOST_CHECK(result); } BOOST_FIXTURE_TEST_CASE(IsConvertFp32ToFp16SupportedFp16InputCl, ClContextControlFixture) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::ClWorkloadFactory, armnn::ConvertFp32ToFp16Layer, armnn::DataType::Float16, armnn::DataType::Float16>(reasonIfUnsupported); BOOST_CHECK(!result); BOOST_CHECK_EQUAL(reasonIfUnsupported, "Input should be Float32"); } BOOST_FIXTURE_TEST_CASE(IsConvertFp32ToFp16SupportedFp32OutputCl, ClContextControlFixture) { std::string reasonIfUnsupported; bool result = IsConvertLayerSupportedTests<armnn::ClWorkloadFactory, armnn::ConvertFp32ToFp16Layer, armnn::DataType::Float32, armnn::DataType::Float32>(reasonIfUnsupported); BOOST_CHECK(!result); BOOST_CHECK_EQUAL(reasonIfUnsupported, "Output should be Float16"); } #endif //#ifdef ARMCOMPUTECL_ENABLED. BOOST_AUTO_TEST_SUITE_END()
33.091667
105
0.801939
KevinRodrigues05
14f0a9f5fd1f54e4453bd514527bfdb524220753
5,466
cpp
C++
qt-creator-opensource-src-4.6.1/src/shared/qbs/src/lib/corelib/generators/generatordata.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
5
2018-12-22T14:49:13.000Z
2022-01-13T07:21:46.000Z
Src/shared/qbs/src/lib/corelib/generators/generatordata.cpp
kevinlq/QSD
b618fc63dc3aa5a18701c5b23e3ea3cdd253e89a
[ "MIT" ]
null
null
null
Src/shared/qbs/src/lib/corelib/generators/generatordata.cpp
kevinlq/QSD
b618fc63dc3aa5a18701c5b23e3ea3cdd253e89a
[ "MIT" ]
8
2018-07-17T03:55:48.000Z
2021-12-22T06:37:53.000Z
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qbs. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "generatordata.h" #include <tools/error.h> #include <tools/set.h> #include <QtCore/qdir.h> namespace qbs { QString GeneratableProductData::name() const { return uniqueValue<QString>(&ProductData::name, QLatin1String("Products with different names per configuration are not " "compatible with this generator. " "Consider using the targetName property instead.")); } CodeLocation GeneratableProductData::location() const { return uniqueValue<CodeLocation>(&ProductData::location, QLatin1String("GeneratableProductData::location: internal bug; this should not happen.")); } QStringList GeneratableProductData::dependencies() const { return uniqueValue<QStringList>(&ProductData::dependencies, QLatin1String("Products with different dependency lists per configuration are not " "compatible with this generator.")); } QStringList GeneratableProductData::type() const { return uniqueValue<QStringList>(&ProductData::type, QLatin1String("Products with different types per configuration are not " "compatible with this generator.")); } QString GeneratableProductData::buildDirectory() const { return uniqueValue<QString>(&ProductData::buildDirectory, QLatin1String("GeneratableProductData::buildDirectory: " "internal bug; this should not happen.")); } QString GeneratableProjectData::name() const { return uniqueValue<QString>(&ProjectData::name, QLatin1String("Projects with different names per configuration are not " "compatible with this generator.")); } CodeLocation GeneratableProjectData::location() const { CodeLocation location; QMapIterator<QString, ProjectData> it(data); while (it.hasNext()) { it.next(); CodeLocation oldLocation = location; location = it.value().location(); if (oldLocation.isValid() && oldLocation != location) throw ErrorInfo(QLatin1String("Projects with different code locations " "per configuration are not compatible with this " "generator.")); } return location; } GeneratableProjectData::Id GeneratableProjectData::uniqueName() const { GeneratableProjectData::Id id; id.value = name() + QLatin1Char('-') + location().toString(); return id; } QDir GeneratableProject::baseBuildDirectory() const { Internal::Set<QString> baseBuildDirectory; QMapIterator<QString, ProjectData> it(data); while (it.hasNext()) { it.next(); QDir dir(it.value().buildDirectory()); dir.cdUp(); baseBuildDirectory.insert(dir.absolutePath()); } Q_ASSERT(baseBuildDirectory.size() == 1); return *baseBuildDirectory.begin(); } QFileInfo GeneratableProject::filePath() const { Internal::Set<QString> filePath; QMapIterator<QString, ProjectData> it(data); while (it.hasNext()) { it.next(); filePath.insert(it.value().location().filePath()); } Q_ASSERT(filePath.size() == 1); return *filePath.begin(); } bool GeneratableProject::hasMultipleConfigurations() const { return projects.size() > 1; } QStringList GeneratableProject::commandLine() const { QStringList combinedCommandLine; QMapIterator<QString, QStringList> it(commandLines); while (it.hasNext()) { it.next(); combinedCommandLine << it.value(); } return combinedCommandLine; } } // namespace qbs
35.038462
98
0.677644
kevinlq
14f342ae30c8f9eeecb5589c60e4246f99a48a5f
3,772
hpp
C++
lib/geometry/kdtree.hpp
kuhaku-space/atcoder-lib
7fe1365e1be69d3eff11e122b2c7dff997a6c541
[ "Apache-2.0" ]
null
null
null
lib/geometry/kdtree.hpp
kuhaku-space/atcoder-lib
7fe1365e1be69d3eff11e122b2c7dff997a6c541
[ "Apache-2.0" ]
4
2022-01-05T14:40:40.000Z
2022-03-05T08:03:19.000Z
lib/geometry/kdtree.hpp
kuhaku-space/atcoder-lib
7fe1365e1be69d3eff11e122b2c7dff997a6c541
[ "Apache-2.0" ]
null
null
null
#include "template/template.hpp" /* * reference : * https://tjkendev.github.io/procon-library/cpp/range_query/kd-tree.html * verify : * https://onlinejudge.u-aizu.ac.jp/problems/DSL_2_C 21/03/29 * https://atcoder.jp/contests/arc010/tasks/arc010_4 21/03/30 */ struct kdtree { struct Point { int id; int x, y; }; struct Node { int left, right; Point p; }; vector<Point> points; vector<Node> nodes; kdtree() : points(), nodes() {} void add(int x, int y) { int id = points.size(); points.emplace_back(Point{id, x, y}); } int make(int l, int r, int depth) { if (l == r) { return -1; } if (r - l == 1) { int res = nodes.size(); nodes.emplace_back(Node{-1, -1, points[l]}); return res; } int mid = (l + r) >> 1; if (depth & 1) { sort(points.begin() + l, points.begin() + r, [](const Point &a, const Point &b) { return a.x < b.x; }); } else { sort(points.begin() + l, points.begin() + r, [](const Point &a, const Point &b) { return a.y < b.y; }); } int res = nodes.size(); nodes.emplace_back(Node{}); int left = make(l, mid, depth + 1); int right = make(mid + 1, r, depth + 1); nodes[res] = Node{left, right, points[mid]}; return res; } void build() { make(0, points.size(), 0); } int64_t find(int idx, int x, int y, int depth, int64_t r) { if (idx == -1) return r; Point &p = nodes[idx].p; int64_t d = int64_t(x - p.x) * (x - p.x) + int64_t(y - p.y) * (y - p.y); if (r == -1 || d < r) r = d; if (depth & 1) { if (nodes[idx].left != -1 && x - r <= p.x) { r = find(nodes[idx].left, x, y, depth + 1, r); } if (nodes[idx].right != -1 && p.x <= x + r) { r = find(nodes[idx].right, x, y, depth + 1, r); } } else { if (nodes[idx].left != -1 && y - r <= p.y) { r = find(nodes[idx].left, x, y, depth + 1, r); } if (nodes[idx].right != -1 && p.y <= y + r) { r = find(nodes[idx].right, x, y, depth + 1, r); } } return r; } int64_t find(int x, int y) { return find(0, x, y, 0, -1); } // [sx, tx) * [sy, ty) vector<int> find(int idx, int sx, int tx, int sy, int ty, int depth) { vector<int> res; Point &p = nodes[idx].p; if (sx <= p.x && p.x < tx && sy <= p.y && p.y < ty) { res.emplace_back(p.id); } if (depth & 1) { if (nodes[idx].left != -1 && sx <= p.x) { auto v = find(nodes[idx].left, sx, tx, sy, ty, depth + 1); res.insert(res.end(), v.begin(), v.end()); } if (nodes[idx].right != -1 && p.x < tx) { auto v = find(nodes[idx].right, sx, tx, sy, ty, depth + 1); res.insert(res.end(), v.begin(), v.end()); } } else { if (nodes[idx].left != -1 && sy <= p.y) { auto v = find(nodes[idx].left, sx, tx, sy, ty, depth + 1); res.insert(res.end(), v.begin(), v.end()); } if (nodes[idx].right != -1 && p.y < ty) { auto v = find(nodes[idx].right, sx, tx, sy, ty, depth + 1); res.insert(res.end(), v.begin(), v.end()); } } return res; } vector<int> find(int sx, int tx, int sy, int ty) { return find(0, sx, tx, sy, ty, 0); } };
34.290909
94
0.423383
kuhaku-space
14f3bc9e292df48bb32a96d981acff7f45cdee51
3,063
cpp
C++
plugins/pwdemos/src/AbstractTexQuartzRenderer.cpp
azuki-monster/megamol
f5d75ae5630f9a71a7fbf81624bfd4f6b253c655
[ "BSD-3-Clause" ]
2
2020-10-16T10:15:37.000Z
2021-01-21T13:06:00.000Z
plugins/pwdemos/src/AbstractTexQuartzRenderer.cpp
azuki-monster/megamol
f5d75ae5630f9a71a7fbf81624bfd4f6b253c655
[ "BSD-3-Clause" ]
null
null
null
plugins/pwdemos/src/AbstractTexQuartzRenderer.cpp
azuki-monster/megamol
f5d75ae5630f9a71a7fbf81624bfd4f6b253c655
[ "BSD-3-Clause" ]
1
2021-01-28T01:19:54.000Z
2021-01-28T01:19:54.000Z
/* * AbstractTexQuartzRenderer.cpp * * Copyright (C) 2018 by VISUS (Universitaet Stuttgart) * Alle Rechte vorbehalten. */ #include "stdafx.h" #include "AbstractTexQuartzRenderer.h" #include "vislib/graphics/gl/IncludeAllGL.h" #include <vector> namespace megamol { namespace demos { /* * AbstractTexQuartzRenderer::AbstractTexQuartzRenderer */ AbstractTexQuartzRenderer::AbstractTexQuartzRenderer(void) : AbstractQuartzRenderer(), typeTexture(0) { } /* * AbstractTexQuartzRenderer::~AbstractTexQuartzRenderer */ AbstractTexQuartzRenderer::~AbstractTexQuartzRenderer(void) { } /* * AbstractTexQuartzRenderer::assertTypeTexture */ void AbstractTexQuartzRenderer::assertTypeTexture(CrystalDataCall& types) { if ((this->typesDataHash != 0) && (this->typesDataHash == types.DataHash())) return; // all up to date this->typesDataHash = types.DataHash(); if (types.GetCount() == 0) { ::glDeleteTextures(1, &this->typeTexture); this->typeTexture = 0; return; } if (this->typeTexture == 0) { ::glGenTextures(1, &this->typeTexture); } unsigned mfc = 0; for (unsigned int i = 0; i < types.GetCount(); i++) { if (mfc < types.GetCrystals()[i].GetFaceCount()) { mfc = types.GetCrystals()[i].GetFaceCount(); } } std::vector<float> dat; dat.resize(types.GetCount() * mfc * 4); for (unsigned int y = 0; y < types.GetCount(); y++) { const CrystalDataCall::Crystal& c = types.GetCrystals()[y]; unsigned int x; for (x = 0; x < c.GetFaceCount(); x++) { vislib::math::Vector<float, 3> f = c.GetFace(x); dat[(x + y * mfc) * 4 + 3] = f.Normalise(); dat[(x + y * mfc) * 4 + 0] = f.X(); dat[(x + y * mfc) * 4 + 1] = f.Y(); dat[(x + y * mfc) * 4 + 2] = f.Z(); } for (; x < mfc; x++) { dat[(x + y * mfc) * 4 + 0] = 0.0f; dat[(x + y * mfc) * 4 + 1] = 0.0f; dat[(x + y * mfc) * 4 + 2] = 0.0f; dat[(x + y * mfc) * 4 + 3] = 0.0f; } } ::glBindTexture(GL_TEXTURE_2D, this->typeTexture); ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); GLint initial_pack_alignment = 0; ::glGetIntegerv(GL_PACK_ALIGNMENT, &initial_pack_alignment); ::glPixelStorei(GL_PACK_ALIGNMENT, 1); ::glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, mfc, types.GetCount(), 0, GL_RGBA, GL_FLOAT, dat.data()); ::glBindTexture(GL_TEXTURE_2D, 0); ::glPixelStorei(GL_PACK_ALIGNMENT, initial_pack_alignment); } /* * AbstractTexQuartzRenderer::releaseTypeTexture */ void AbstractTexQuartzRenderer::releaseTypeTexture(void) { ::glDeleteTextures(1, &this->typeTexture); this->typeTexture = 0; } } /* end namespace demos */ } /* end namespace megamol */
30.326733
106
0.624551
azuki-monster
14f50ed613594b1a2ea093e72960aba62108f45c
1,049
cc
C++
util/crypto_util/mac.cc
reMarkable/cobalt
3feead337a6bdf620df7a62abb72c910a566a38c
[ "BSD-3-Clause" ]
null
null
null
util/crypto_util/mac.cc
reMarkable/cobalt
3feead337a6bdf620df7a62abb72c910a566a38c
[ "BSD-3-Clause" ]
null
null
null
util/crypto_util/mac.cc
reMarkable/cobalt
3feead337a6bdf620df7a62abb72c910a566a38c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2016 The Fuchsia Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "util/crypto_util/mac.h" #include <openssl/digest.h> #include <openssl/hmac.h> namespace cobalt { namespace crypto { namespace hmac { bool HMAC(const byte *key , const size_t key_len, const byte *data, const size_t data_len, byte tag[TAG_SIZE]) { unsigned int out_len_unused; return HMAC(EVP_sha256(), key, key_len, data, data_len, tag, &out_len_unused); } } // namespace hmac } // namespace crypto } // namespace cobalt
27.605263
75
0.731173
reMarkable
14f689dd9f23ac8156584dcddb473a9d0edd1df0
220
hh
C++
include/model/usermodel.hh
MUCZ/meowings
5c691f0a2fb606dad2ddda44f946a94ff8ba3212
[ "Apache-2.0" ]
null
null
null
include/model/usermodel.hh
MUCZ/meowings
5c691f0a2fb606dad2ddda44f946a94ff8ba3212
[ "Apache-2.0" ]
null
null
null
include/model/usermodel.hh
MUCZ/meowings
5c691f0a2fb606dad2ddda44f946a94ff8ba3212
[ "Apache-2.0" ]
null
null
null
#ifndef USERMODEL #define USERMODEL #include "user.hh" class UserModel{ public: bool insert(User &user); User query(int id); bool updateState(User user); void resetState(); }; #endif /* USERMODEL */
12.941176
32
0.663636
MUCZ
14ff9bff8bce2f9903a8b29a82d16116d03dae0c
580
cpp
C++
Challenge18/src/main.cpp
GamesTrap/Challenges
6cfea7ec137fbba35cae6a29c4fc6b124eff07c8
[ "MIT" ]
1
2018-09-15T20:35:23.000Z
2018-09-15T20:35:23.000Z
Challenge18/src/main.cpp
GamesTrap/Challenges
6cfea7ec137fbba35cae6a29c4fc6b124eff07c8
[ "MIT" ]
null
null
null
Challenge18/src/main.cpp
GamesTrap/Challenges
6cfea7ec137fbba35cae6a29c4fc6b124eff07c8
[ "MIT" ]
null
null
null
#include <iostream> #include "GetType.h" int main() { const int i = 0; //Output: std::cout << getType(i) << '\n'; //int const unsigned int ui = 0; std::cout << getType(ui) << '\n'; //unsigned int const char c = 0; std::cout << getType(c) << '\n'; //char const bool b = false; std::cout << getType(b) << '\n'; //bool const float f = 0; //Assumption: float is not considered in getType(); std::cout << getType(f) << '\n'; //unknown type! std::cout << "Press Enter to continue . . . "; std::cin.get(); return 0; }
23.2
95
0.527586
GamesTrap
090221e48f082706e2d7383b62d0adb119fdb096
21,652
cpp
C++
Benchmarks/Applications/ObjectRecognition/FeatureExtractionAndClassification.cpp
jlclemon/MEVBench
da7621b9eb1e92eec37a77dd1c7b69320cffcee1
[ "BSD-3-Clause" ]
8
2015-03-16T18:16:35.000Z
2020-10-30T06:35:31.000Z
Benchmarks/Applications/ObjectRecognition/FeatureExtractionAndClassification.cpp
jlclemon/MEVBench
da7621b9eb1e92eec37a77dd1c7b69320cffcee1
[ "BSD-3-Clause" ]
null
null
null
Benchmarks/Applications/ObjectRecognition/FeatureExtractionAndClassification.cpp
jlclemon/MEVBench
da7621b9eb1e92eec37a77dd1c7b69320cffcee1
[ "BSD-3-Clause" ]
3
2016-03-17T08:27:13.000Z
2020-10-30T06:46:50.000Z
/* * Copyright (c) 2006-2009 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /* * FeatureExtractionAndClassification.cpp * * Created on: May 31, 2011 * Author: jlclemon */ #include <iostream> #include <sched.h> #include <unistd.h> #include <opencv2/features2d/features2d.hpp> #ifndef OPENCV_VER_2_3 #include <opencv2/nonfree/nonfree.hpp> #endif #include <opencv2/highgui/highgui.hpp> #include <opencv2/core/core.hpp> #include <opencv2/core/mat.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/calib3d/calib3d.hpp> #include <opencv2/objdetect/objdetect.hpp> #include "FeatureExtraction.hpp" #include "FeatureExtractionWorkerThreadInfo.h" #include "FeatureClassification.hpp" #include "WorkerThreadInfo.h" #ifdef USE_MARSS #warning "Using MARSS" #include "ptlcalls.h" #endif #ifdef USE_GEM5 #warning "Using GEM5" extern "C" { #include "m5op.h" } #endif #ifdef USE_GEM5 #include <fenv.h> #include <signal.h> #include <stdio.h> void classification_sig_handler(int signum); #endif #define TIMING_MAX_NUMBER_OF_THREADS 256 #ifdef TSC_TIMING #include "tsc_class.hpp" #endif //#define CLOCK_GETTIME_TIMING #ifdef CLOCK_GETTIME_TIMING #include "time.h" #ifndef GET_TIME_WRAPPER #define GET_TIME_WRAPPER(dataStruct) clock_gettime(CLOCK_THREAD_CPUTIME_ID, &dataStruct) #endif #endif #ifdef TSC_TIMING vector<TSC_VAL_w> fec_timingVector; #endif #ifdef CLOCK_GETTIME_TIMING vector<struct timespec> fec_timeStructVector; #endif using namespace std; using namespace cv; bool globalDone; bool globalDataReady; Mat globalCurrentImage; vector<Point2f> globalCurrentRefs; struct FeatureExtractionAndClassificationConfig { string featureExtractionConfigFile; string featureClassificationConfigFile; int configFileCount; bool noShowWindows; bool noWaitKey; int maxLoops; int currentLoop; }; void internalCallToTestExtractionAlone(int argc, const char * argv[], bool callDirect) { if(callDirect) { multiThreadFeatureExtraction_StandAloneTest(argc,argv); #ifdef TSC_TIMING //READ_TIMESTAMP_WITH_WRAPPER( fec_timingVector[genData->myThread->getThreadLogicalId()+ TIMING_MAX_NUMBER_OF_THREADS*2] ); #endif #ifdef CLOCK_GETTIME_TIMING //GET_TIME_WRAPPER(fec_timeStructVector[genData->myThread->getThreadLogicalId()+ TIMING_MAX_NUMBER_OF_THREADS*2]); #endif featureClassification_testSeperate(argc, argv); } else { cout << "That is false sir" << endl; } } void setExtractedDescriptorsAndKeyPointsToClassificationInput(void * featureExtractionDataPtr, void * featureClassificationDataPtr) { struct WorkerThreadInfo * featureClassificationData = reinterpret_cast<struct WorkerThreadInfo * >(featureClassificationDataPtr); struct FeatureExtractionWorkerThreadInfo *featureExtractionData = reinterpret_cast<FeatureExtractionWorkerThreadInfo *> (featureExtractionDataPtr); struct FeatureExtractionMultiThreadData * myMultiThreadExtractionData = reinterpret_cast<FeatureExtractionMultiThreadData *>(featureExtractionData->multiThreadAlgorithmData); featureClassificationData->queryImage = &((*(featureExtractionData->myFeatureExtractionData->inputImagesPerFrame))[FEATURE_DESC_IMAGE_SOURCE_LOCATION_LEFT_CAMERA]); featureClassificationData->allQueryDescriptors = (myMultiThreadExtractionData->descriptors); featureClassificationData->allQueryKeypoints = (myMultiThreadExtractionData->keypoints); #ifdef VERBOSE_DEBUG cout << "Info From Extraction" << "\n Number Of Extracted Keypoints: "<<featureClassificationData->allQueryKeypoints->size() << "\n Number of extracted descriptors: " << featureClassificationData->allQueryDescriptors->rows << endl; #endif } void * coordinatorThreadFunction(void * threadParam) { int currentLoop = 0; int maxLoops = 20; struct GeneralWorkerThreadData * genData = reinterpret_cast<struct GeneralWorkerThreadData *>(threadParam); struct FeatureExtractionWorkerThreadInfo *featureExtractionData = reinterpret_cast<FeatureExtractionWorkerThreadInfo *> (genData->featureExtractionData); struct WorkerThreadInfo * featureClassificationData = reinterpret_cast<struct WorkerThreadInfo * >(genData->featureClassificationData); //Setup the pieces featureExtractionCoordinatorThreadSetupFunctionStandAlone(genData,genData->featureExtractionData); classificationCoordinatorThreadSetupFunctionStandAlone(genData->featureClassificationData); #ifdef VERBOSE_DEBUG int counting = 0; #endif #ifdef USE_MARSS cout << "Switching to simulation in Object Recognition." << endl; ptlcall_switch_to_sim(); //ptlcall_single_enqueue("-logfile objRecog.log"); //ptlcall_single_enqueue("-stats objRecog.stats"); ptlcall_single_flush("-stats objRecog.stats"); //ptlcall_single_enqueue("-loglevel 0"); #endif #ifdef USE_GEM5 #ifdef GEM5_CHECKPOINT_WORK m5_checkpoint(0, 0); #endif // #ifdef GEM5_SWITCHCPU_AT_WORK // m5_switchcpu(); // #endif m5_dumpreset_stats(0, 0); #endif #ifdef TSC_TIMING READ_TIMESTAMP_WITH_WRAPPER( fec_timingVector[genData->myThread->getThreadLogicalId()] ); #endif #ifdef CLOCK_GETTIME_TIMING GET_TIME_WRAPPER(fec_timeStructVector[genData->myThread->getThreadLogicalId()]); #endif while(!globalDone) { //Call the pieces featureExtractionCoordinatorThreadFunctionStandAlone(genData,genData->featureExtractionData); #ifdef VERBOSE_DEBUG counting ++; cout << "Count: " << counting << endl; if(counting == 11) { cout << "debug here" << endl; } #endif #ifdef TSC_TIMING READ_TIMESTAMP_WITH_WRAPPER( fec_timingVector[genData->myThread->getThreadLogicalId()+ TIMING_MAX_NUMBER_OF_THREADS*2] ); #endif #ifdef CLOCK_GETTIME_TIMING GET_TIME_WRAPPER(fec_timeStructVector[genData->myThread->getThreadLogicalId()+ TIMING_MAX_NUMBER_OF_THREADS*2]); #endif if(featureExtractionData->featureExtractionInfo->outOfImages || featureExtractionData->myFeatureExtractionInfo->outOfImages) { break; } if(featureExtractionData->done) { globalDone = true; } currentLoop++; if(currentLoop >=maxLoops) { globalDone = true; } //Connect the two pieces here setExtractedDescriptorsAndKeyPointsToClassificationInput(genData->featureExtractionData, genData->featureClassificationData); //Run Classification classificationCoordinatorThreadFunctionStandAlone(genData->featureClassificationData); if(globalDataReady ==false) { globalCurrentImage = ((*(featureExtractionData->myFeatureExtractionData->inputImagesPerFrame))[FEATURE_DESC_IMAGE_SOURCE_LOCATION_LEFT_CAMERA]).clone(); globalCurrentRefs = reinterpret_cast<struct SparseFeaturePointObjectClassifier::SparseFeaturePointObjectClassifierMultiThreadData *>(featureClassificationData->multiThreadAlgorithmData)->estimatedRefPoints->getResultsVec(); globalDataReady = true; } } globalDone = true; #ifdef USE_MARSS ptlcall_kill(); #endif #ifdef USE_GEM5 m5_dumpreset_stats(0, 0); #ifdef GEM5_EXIT_AFTER_WORK m5_exit(0); #endif #endif #ifdef TSC_TIMING READ_TIMESTAMP_WITH_WRAPPER( fec_timingVector[genData->myThread->getThreadLogicalId()+ TIMING_MAX_NUMBER_OF_THREADS] ); #endif #ifdef CLOCK_GETTIME_TIMING GET_TIME_WRAPPER(fec_timeStructVector[genData->myThread->getThreadLogicalId()+ TIMING_MAX_NUMBER_OF_THREADS]); #endif cout << "Coordinator Complete" << endl; return NULL; } void * workerThreadFunction(void * threadParam) { struct GeneralWorkerThreadData * genData = reinterpret_cast<struct GeneralWorkerThreadData *>(threadParam); struct FeatureExtractionWorkerThreadInfo *featureExtractionData = reinterpret_cast<FeatureExtractionWorkerThreadInfo *> (genData->featureExtractionData); struct WorkerThreadInfo * featureClassificationData = reinterpret_cast<struct WorkerThreadInfo * >(genData->featureClassificationData); //Setup the pieces featureExtractionWorkerThreadSetupFunctionStandAlone(genData,genData->featureExtractionData); classificationWorkerThreadSetupFunctionStandAlone(genData->featureClassificationData); #ifdef TSC_TIMING READ_TIMESTAMP_WITH_WRAPPER( fec_timingVector[genData->myThread->getThreadLogicalId()] ); #endif #ifdef CLOCK_GETTIME_TIMING GET_TIME_WRAPPER(fec_timeStructVector[genData->myThread->getThreadLogicalId()]); #endif while(!globalDone) { //Run the functions featureExtractionWorkerThreadFunctionStandAlone(genData,genData->featureExtractionData); #ifdef TSC_TIMING READ_TIMESTAMP_WITH_WRAPPER( fec_timingVector[genData->myThread->getThreadLogicalId()+ TIMING_MAX_NUMBER_OF_THREADS*2] ); #endif #ifdef CLOCK_GETTIME_TIMING GET_TIME_WRAPPER(fec_timeStructVector[genData->myThread->getThreadLogicalId()+ TIMING_MAX_NUMBER_OF_THREADS*2]); #endif if(featureExtractionData->featureExtractionInfo->outOfImages || featureExtractionData->myFeatureExtractionInfo->outOfImages) { break; } classificationWorkerThreadFunctionStandAlone(genData->featureClassificationData); } #ifdef TSC_TIMING READ_TIMESTAMP_WITH_WRAPPER( fec_timingVector[genData->myThread->getThreadLogicalId()+ TIMING_MAX_NUMBER_OF_THREADS] ); #endif #ifdef CLOCK_GETTIME_TIMING GET_TIME_WRAPPER(fec_timeStructVector[genData->myThread->getThreadLogicalId()+ TIMING_MAX_NUMBER_OF_THREADS]); #endif globalDone = true; return NULL; } void parseConfigCommandVector(FeatureExtractionAndClassificationConfig & config, vector<string> & commandStringVector, vector <string> &extractionExtraParams, vector<string> &classificationExtraParams) { vector<string>::iterator it_start = commandStringVector.begin(); vector<string>::iterator it_end = commandStringVector.end(); vector<string>::iterator it_current; stringstream stringBuffer; //Set the defaults config.featureClassificationConfigFile = "classificationConfig.txt"; config.featureExtractionConfigFile = "extractionConfig.txt"; config.configFileCount = 0; config.currentLoop = 0; config.maxLoops = 5; config.noShowWindows = false; config.noWaitKey = false; //-desc sift -match knn_flann -classify linear_svm -queryDescFile test.yml -trainDescFile test.yml -loadClassificationStruct test.yml -loadMatchStruct test.yml for(it_current=it_start; it_current!=it_end; ++it_current) { if(!it_current->compare("-extractionConfig") || !it_current->compare("-ExractionConfig")) { config.featureExtractionConfigFile =*(it_current+1); config.configFileCount |= 1; } if(!it_current->compare("-classificationConfig") || !it_current->compare("-ClassificationConfig")) { config.featureClassificationConfigFile =*(it_current+1); config.configFileCount |= 2; } if(!it_current->compare("-noShowWindows") || !it_current->compare("-NoShowWindows")) { config.noShowWindows = true; } if(!it_current->compare("-noWaitKey") || !it_current->compare("-NoWaitKey")) { config.noWaitKey = true; } if(!it_current->compare("-extractXtraParams") || !it_current->compare("-ExtractXtraParams")) { vector<string> xtraParamsVec; string extraParams =*(it_current+1); char currentString[120]; strcpy(currentString, extraParams.c_str()); char * currentTokPointer = strtok(currentString,","); while(currentTokPointer != NULL) { string currentNewString(currentTokPointer); xtraParamsVec.push_back(currentNewString); currentTokPointer = strtok(NULL,","); } extractionExtraParams = xtraParamsVec; } if(!it_current->compare("-classifyXtraParams") || !it_current->compare("-ClassifyXtraParams")) { vector<string> xtraParamsVec; string extraParams =*(it_current+1); char currentString[120]; strcpy(currentString, extraParams.c_str()); char * currentTokPointer = strtok(currentString,","); while(currentTokPointer != NULL) { string currentNewString(currentTokPointer); xtraParamsVec.push_back(currentNewString); currentTokPointer = strtok(NULL,","); } classificationExtraParams = xtraParamsVec; } } if(config.configFileCount != 3) { cout << "Warning: Not enough config files given on command line" << endl; } } void runMultiThreadedFeatureExtractionAndClassification(int argc, const char * argv[]) { vector<string> commandLineArgs; for(int i = 0; i < argc; i++) { string currentString = argv[i]; commandLineArgs.push_back(currentString); } FeatureExtractionAndClassificationConfig config; vector <string> extractionExtraParams; vector <string> classificationExtraParams; parseConfigCommandVector(config, commandLineArgs,extractionExtraParams, classificationExtraParams); FeatureExtractionConfig featureExtractionConfig; FeatureClassificationConfig featureClassificationConfig; setupFeatureExtractionConfigFromFile(config.featureExtractionConfigFile,featureExtractionConfig,extractionExtraParams); featureClassificationConfig = setupFeatureClassificationConfigFromFile(config.featureClassificationConfigFile,classificationExtraParams); //They need to have the same number of threads featureClassificationConfig.numberOfHorizontalProcs = featureExtractionConfig.numberOfHorizontalProcs; featureClassificationConfig.numberOfVerticalProcs = featureExtractionConfig.numberOfVerticalProcs; //Setup Extraction Data******************************* FeatureExtractionData featureExtractionData; featureExtractionSetupFeatureExtractionData(featureExtractionConfig, featureExtractionData); //#define WAIT_FOR_STABLE_STREAM #ifdef WAIT_FOR_STABLE_STREAM if(!config.noShowWindows) { int key = -1; namedWindow("CurrentStream"); while(key ==-1) { getNextImages((*(featureExtractionData.inputImagesPerFrame)),featureExtractionConfig); imshow("CurrentStream",(*(featureExtractionData.inputImagesPerFrame))[0]); key = waitKey(33); } destroyWindow("CurrentStream"); } #endif //Setup classification Data************************ Mat trainDescriptors; Mat trainDescriptorsClasses; vector<KeyPoint> trainKeypoints; Mat trainImage; Mat queryDescriptors; Mat queryDescriptorsClasses; vector<KeyPoint> queryKeypoints; // vector<struct WorkerThreadInfo> workingThreads; MultiThreadedMatResult * multiThreadResultPtr; MultiThreadedMatchResult * multiThreadMatchResultPtr; vector <vector<DMatch> >matches; Mat queryDescriptorsClassesComputed; Mat queryDescriptorsClassesLoaded; Mat queryImage; handleDescLoading(trainDescriptors,trainDescriptorsClasses, queryDescriptors,queryDescriptorsClassesLoaded,featureClassificationConfig); handleKeyPointLoading(trainKeypoints,queryKeypoints,featureClassificationConfig); handleImageLoading(trainImage,queryImage,featureClassificationConfig); //Create thread Manager ThreadManager * threadManager; featureExtractionCreateThreadManager(threadManager,featureExtractionConfig.numberOfVerticalProcs, featureExtractionConfig.numberOfHorizontalProcs); //Create the general struct vector<GeneralWorkerThreadData> genData(featureExtractionConfig.numberOfVerticalProcs *featureExtractionConfig.numberOfHorizontalProcs); //Create the worker infos for extraction and classification vector<struct FeatureExtractionWorkerThreadInfo> extractionWorkingThreads(featureExtractionConfig.numberOfVerticalProcs *featureExtractionConfig.numberOfHorizontalProcs); vector<struct WorkerThreadInfo> classificationWorkingThreads(featureClassificationConfig.numberOfVerticalProcs *featureClassificationConfig.numberOfHorizontalProcs); //Connect the general data and the working threads data for extraction setFeatureExtractionWorkingThreadDataInGeneralWorkingData(genData,extractionWorkingThreads); //Connect the general data and the working threads data for classification setClassificationWorkingThreadDataInGeneralWorkingData(genData, classificationWorkingThreads); //Setup the Extraction featureExtractionMultiThreadedSetupOnly(featureExtractionConfig, featureExtractionData, threadManager,genData); //Setup the Classification multiThreadedSetupOnly(trainDescriptors, trainDescriptorsClasses,trainKeypoints,trainImage,queryDescriptors,queryDescriptorsClasses,queryKeypoints,featureClassificationConfig,threadManager,genData,multiThreadResultPtr,multiThreadMatchResultPtr);; vector<void * > threadArgs(genData.size()); for(int i =0; i< threadArgs.size(); i++) { threadArgs[i] = (void *)&genData[i]; } vector<thread_fptr> threadFunctions(genData.size()); threadFunctions[0] = coordinatorThreadFunction; for(int i = 1; i < threadArgs.size(); i++) { threadFunctions[i] = workerThreadFunction; } //Place the data in the Thread manager featureExtractionSetupThreadManager(threadManager,featureExtractionConfig, threadFunctions, threadArgs,featureExtractionConfig.numberOfVerticalProcs, featureExtractionConfig.numberOfHorizontalProcs); globalDone = false; globalDataReady = false; featureExtractionLaunchThreads(threadManager); // bool globalDone; // bool globalDataReady; // Mat globalCurrentImage; // vector<Point2f> globalCurrentRefs; if(!config.noShowWindows) { namedWindow("CurrentResults"); } Mat currentResults; currentResults.create(480,640,CV_8UC3); vector<Point2f> currentRefs; int mainKey = -1; while(mainKey != 'd' && mainKey != 27 && !globalDone) { if(globalDataReady) { if(!config.noShowWindows) { currentResults = globalCurrentImage.clone(); currentRefs = globalCurrentRefs; } globalDataReady = false; } if(!config.noShowWindows) { for(int i = 0; i < currentRefs.size(); i++) { circle(currentResults,currentRefs[i],5,Scalar(0,255,255),CV_FILLED); } imshow("CurrentResults", currentResults); } if(!config.noWaitKey) { mainKey = waitKey(33) & 0xff; } } globalDone = true; //cout << "Waiting for Threads." << endl; for(int i=0 ; i<threadManager->getNumberOfThreads() ; i++) { pthread_join(threadManager->getThread(i)->getThreadId(), NULL); } //#define SHOW_FEATURE_CLASSIFICATION_OUTPUT_GEOM #ifdef SHOW_FEATURE_CLASSIFICATION_OUTPUT_GEOM namedWindow("Show Where"); vector<Point2f> estimatedPoints = reinterpret_cast<struct SparseFeaturePointObjectClassifier::SparseFeaturePointObjectClassifierMultiThreadData *>(classificationWorkingThreads[0].multiThreadAlgorithmData)->estimatedRefPoints->getResultsVec(); Mat where = classificationWorkingThreads[0].queryImage->clone(); for(int i = 0; i < estimatedPoints.size(); i++) { circle(where,estimatedPoints[i],5,Scalar(0,255,255),CV_FILLED); } imshow("Show Where", where); waitKey(0); destroyWindow("Show Where"); #endif cout << "Multithreaded App complete" << endl; return; } #ifdef TSC_TIMING void fec_writeTimingToFile(vector<TSC_VAL_w> timingVector) { ofstream outputFile; outputFile.open("timing.csv"); outputFile << "Thread,Start,Finish,Mid" << endl; for(int i = 0; i<(TIMING_MAX_NUMBER_OF_THREADS); i++) { outputFile << i << "," << timingVector[i] << "," << timingVector[i+TIMING_MAX_NUMBER_OF_THREADS]<< ","<< timingVector[i+2*TIMING_MAX_NUMBER_OF_THREADS] << endl; } outputFile.close(); } #endif #ifdef CLOCK_GETTIME_TIMING void fec_writeTimingToFile(vector<struct timespec> timingVector) { ofstream outputFile; outputFile.open("timing.csv"); outputFile << "Thread,Start sec, Start nsec,Finish sec, Finish nsec,Mid sec, Mid nsec" << endl; for(int i = 0; i<(TIMING_MAX_NUMBER_OF_THREADS); i++) { outputFile << i << "," << timingVector[i].tv_sec<<","<< timingVector[i].tv_nsec << "," << timingVector[i+TIMING_MAX_NUMBER_OF_THREADS].tv_sec<<","<< timingVector[i+TIMING_MAX_NUMBER_OF_THREADS].tv_nsec<< "," << timingVector[i+2*TIMING_MAX_NUMBER_OF_THREADS].tv_sec<<","<< timingVector[i+2*TIMING_MAX_NUMBER_OF_THREADS].tv_nsec <<endl; } outputFile.close(); } #endif int main (int argc, const char * argv[]) { cout << "Hello world" << endl; #ifdef TSC_TIMING fec_timingVector.resize(TIMING_MAX_NUMBER_OF_THREADS*3); #endif #ifdef CLOCK_GETTIME_TIMING //fec_timeStructVector.resize(16); fec_timeStructVector.resize(TIMING_MAX_NUMBER_OF_THREADS*3); #endif internalCallToTestExtractionAlone(argc,argv,false); runMultiThreadedFeatureExtractionAndClassification(argc,argv); #ifdef TSC_TIMING fec_writeTimingToFile(fec_timingVector); #endif #ifdef CLOCK_GETTIME_TIMING fec_writeTimingToFile(fec_timeStructVector); #endif return 0; }
29.024129
338
0.787225
jlclemon
0904adf7cbbba585ae156ead415d792a96316750
4,027
cpp
C++
Source/MainComponent.cpp
modosc/ffGuiAttachments
7351d1944e5bcba9a7089c61bca333851ce3bc09
[ "BSD-3-Clause" ]
24
2016-07-04T07:17:24.000Z
2021-12-03T18:58:52.000Z
Source/MainComponent.cpp
modosc/ffGuiAttachments
7351d1944e5bcba9a7089c61bca333851ce3bc09
[ "BSD-3-Clause" ]
2
2018-01-27T11:11:26.000Z
2018-03-19T11:59:01.000Z
Source/MainComponent.cpp
modosc/ffGuiAttachments
7351d1944e5bcba9a7089c61bca333851ce3bc09
[ "BSD-3-Clause" ]
7
2017-01-04T16:35:57.000Z
2021-10-03T03:40:23.000Z
/* ============================================================================== This file was auto-generated! ============================================================================== */ #include "../JuceLibraryCode/JuceHeader.h" #include "ff_gui_attachments/ff_gui_attachments.h" #include "MainComponent.h" //============================================================================== MainContentComponent::MainContentComponent() { slider = new Slider(); slider2 = new Slider(); tree = ValueTree ("TestTree"); tree.setProperty ("number", 5.0, nullptr); debugListener = new ValueTreeDebugListener (tree, true); ValueTree select = tree.getOrCreateChildWithName ("ComboBox", nullptr); ValueTree option1 = ValueTree ("Option"); option1.setProperty ("name", "Anything", nullptr); select.addChild (option1, 0, nullptr); ValueTree option2 = ValueTree ("Option"); option2.setProperty ("name", "Something", nullptr); option2.setProperty ("selected", 1, nullptr); select.addChild (option2, 1, nullptr); ValueTree option3 = ValueTree ("Option"); option3.setProperty ("name", "Nothing", nullptr); select.addChild (option3, 2, nullptr); ValueTree labelTree = tree.getOrCreateChildWithName ("Label", nullptr); labelTree.setProperty ("labeltext", "test", nullptr); combo = new ComboBox(); combo1 = new ComboBox(); addAndMakeVisible (slider); addAndMakeVisible (slider2); addAndMakeVisible (combo); addAndMakeVisible (combo1); juce::Array<juce::Button*> btns; ToggleButton* b = new ToggleButton ("Anything"); b->setComponentID ("Anything"); b->setRadioGroupId (100); buttons.add (b); btns.add (b); addAndMakeVisible (b); b = new ToggleButton ("Something"); b->setComponentID ("Something"); b->setRadioGroupId (100); buttons.add (b); btns.add (b); addAndMakeVisible (b); b = new ToggleButton ("Nothing"); b->setComponentID ("Nothing"); b->setRadioGroupId (100); buttons.add (b); btns.add (b); addAndMakeVisible (b); label = new Label(); label->setEditable (true); label->setColour (Label::outlineColourId, Colours::lightgrey); label1 = new Label(); label1->setColour (Label::outlineColourId, Colours::lightgrey); addAndMakeVisible (label); addAndMakeVisible (label1); labelToCombo = new Label(); labelToCombo->setEditable (true); labelToCombo->setColour (Label::outlineColourId, Colours::lightgrey); addAndMakeVisible (labelToCombo); attachment = new ValueTreeSliderAttachment (tree, slider, "number"); attachment2 = new ValueTreeSliderAttachment (tree, slider2, "number"); comboAttachment = new ValueTreeComboBoxAttachment (select, combo, "name", true); comboAttachment1 = new ValueTreeComboBoxAttachment (select, combo1, "name", true); buttonGroupAttachment = new ValueTreeRadioButtonGroupAttachment (select, btns, "name", true); labelAttachment = new ValueTreeLabelAttachment (labelTree, label, "labeltext"); labelAttachment1 = new ValueTreeLabelAttachment (labelTree, label1, "labeltext"); labelToComboAttachment = new ValueTreeLabelAttachment (option1, labelToCombo, "name"); setSize (600, 400); } MainContentComponent::~MainContentComponent() { } void MainContentComponent::paint (Graphics& g) { g.fillAll (Colours::lightcoral); g.setFont (Font (16.0f)); g.setColour (Colours::white); g.drawText ("Hello World!", getLocalBounds(), Justification::centred, true); } void MainContentComponent::resized() { slider->setBounds (5, 5, 150, 60); slider2->setBounds(160, 5, 150, 60); combo->setBounds (5, 70, 150, 20); combo1->setBounds (5, 100, 150, 20); for (int i=0; i < buttons.size(); ++i) { buttons.getUnchecked (i)->setBounds (160, 70 + i * 30, 150, 25); } label->setBounds (330, 10, 150, 20); label1->setBounds (330, 40, 150, 20); labelToCombo->setBounds (330, 80, 150, 20); }
31.460938
97
0.636951
modosc
090895fbdd28dc01720017737b6a3197d303774a
1,953
cpp
C++
src/rlScheduler/configuration.cpp
Jacques-Florence/SchedSim
cd5f356ec1d177963d401b69996a19a68646d7af
[ "BSD-3-Clause" ]
1
2019-12-24T19:07:19.000Z
2019-12-24T19:07:19.000Z
src/rlScheduler/configuration.cpp
Jacques-Florence/SchedSim
cd5f356ec1d177963d401b69996a19a68646d7af
[ "BSD-3-Clause" ]
null
null
null
src/rlScheduler/configuration.cpp
Jacques-Florence/SchedSim
cd5f356ec1d177963d401b69996a19a68646d7af
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright 2017 Jacques Florence * All rights reserved. * See License.txt file * */ #include "configuration.h" #include "rlDiscipline.h" #include "maxTempEstimator/envelopeDetector.h" #include "maxTempEstimator/exponentialMaxTempEstimator.h" #include "maxTempEstimator/squareMaxTempEstimator.h" #include "maxTempEstimator/monomialMaxTempEstimator.h" #include <memory> using namespace RlScheduler; std::unique_ptr<Scheduler::SchedulingDiscipline> Configuration::getDisciplineFromFile() { std::unique_ptr<Scheduler::SchedulingDiscipline> discipline = SchedulerConfiguration::getDisciplineFromFile(); if (discipline == nullptr) { std::string value = getStringValue("scheduler", "discipline"); if (!value.compare(RlDiscipline::configKey)) discipline = std::make_unique<RlDiscipline>(std::dynamic_pointer_cast<Configuration>(shared_from_this())); } return discipline; } MaxTempEstimator *Configuration::getMaxTempEstimatorFromFile() { std::vector<std::string> str = getStringList("rlDiscipline", "maxTempEstimator"); if (str.size() == 0) return nullptr; if (!str[0].compare(EnvelopeDetector::configKey)) { double decayCoeff = getDoubleValue("rlDiscipline","peakDecaySpeed"); return new EnvelopeDetector(decayCoeff); } if (!str[0].compare(SquareMaxTempEstimator::configKey)) return new SquareMaxTempEstimator(); if (!str[0].compare(MonomialMaxTempEstimator::configKey)) { int order = 2; if (str.size() > 1) order = std::stoi(str[1]); return new MonomialMaxTempEstimator(order); } if (!str[0].compare(ExponentialMaxTempEstimator::configKey)) { double scaling = 1.0; double offset = 0.0; if (str.size() > 1) { scaling = std::stod(str[1]); offset = std::stod(str[2]); } return new ExponentialMaxTempEstimator(scaling, offset); } return nullptr; } double Configuration::getTempLimit() { double tempLimit = getDoubleValue("rlDiscipline", "tempLimit"); return tempLimit; }
23.53012
111
0.740911
Jacques-Florence
0908e52a400c8c065bc1b489e94b58c6bfe7c914
710
cpp
C++
models/processor/zesto/ZCOMPS-bpred/bpred-taken.cpp
Basseuph/manifold
99779998911ed7e8b8ff6adacc7f93080409a5fe
[ "BSD-3-Clause" ]
8
2016-01-22T18:28:48.000Z
2021-05-07T02:27:21.000Z
models/processor/zesto/ZCOMPS-bpred/bpred-taken.cpp
Basseuph/manifold
99779998911ed7e8b8ff6adacc7f93080409a5fe
[ "BSD-3-Clause" ]
3
2016-04-15T02:58:58.000Z
2017-01-19T17:07:34.000Z
models/processor/zesto/ZCOMPS-bpred/bpred-taken.cpp
Basseuph/manifold
99779998911ed7e8b8ff6adacc7f93080409a5fe
[ "BSD-3-Clause" ]
10
2015-12-11T04:16:55.000Z
2019-05-25T20:58:13.000Z
/* bpred-taken.cpp: Static always taken predictor */ /* * __COPYRIGHT__ GT */ #define COMPONENT_NAME "taken" #ifdef BPRED_PARSE_ARGS if(!strcasecmp(COMPONENT_NAME,type)) { return new bpred_taken_t(); } #else class bpred_taken_t:public bpred_dir_t { public: /* CREATE */ bpred_taken_t() { init(); name = strdup(COMPONENT_NAME); if(!name) fatal("couldn't malloc taken name (strdup)"); type = strdup("static taken"); if(!type) fatal("couldn't malloc taken type (strdup)"); bits = 0; } /* LOOKUP */ BPRED_LOOKUP_HEADER { BPRED_STAT(lookups++;) scvp->updated = false; return 1; } }; #endif /* BPRED_PARSE_ARGS */ #undef COMPONENT_NAME
15.106383
52
0.638028
Basseuph
090967581ab0c547e19fd46ac86d5fbc69c175be
3,110
hpp
C++
routing/world_graph.hpp
xblonde/omim
d940a4761786c994884d2488a469635a4ac76d28
[ "Apache-2.0" ]
1
2021-01-19T08:31:19.000Z
2021-01-19T08:31:19.000Z
routing/world_graph.hpp
frankiewb/omim
0d9302e7b1be470735655337f0183ad04c55b6ad
[ "Apache-2.0" ]
null
null
null
routing/world_graph.hpp
frankiewb/omim
0d9302e7b1be470735655337f0183ad04c55b6ad
[ "Apache-2.0" ]
null
null
null
#pragma once #include "routing/cross_mwm_graph.hpp" #include "routing/edge_estimator.hpp" #include "routing/geometry.hpp" #include "routing/index_graph.hpp" #include "routing/index_graph_loader.hpp" #include "routing/segment.hpp" #include <memory> #include <unordered_map> #include <utility> #include <vector> namespace routing { class WorldGraph final { public: // AStarAlgorithm types aliases: using TVertexType = IndexGraph::TVertexType; using TEdgeType = IndexGraph::TEdgeType; using TWeightType = IndexGraph::TWeightType; // CheckGraphConnectivity() types aliases: using Vertex = TVertexType; using Edge = TEdgeType; enum class Mode { LeapsOnly, // Mode for building a cross mwm route containing only leaps. In case of start and // finish they (start and finish) will be connected with all transition segments of // their mwm with leap (fake) edges. LeapsIfPossible, // Mode for building cross mwm and single mwm routes. In case of cross mwm route // if they are neighboring mwms the route will be made without leaps. // If not the route is made with leaps for intermediate mwms. NoLeaps, // Mode for building route and getting outgoing/ingoing edges without leaps at all. }; WorldGraph(std::unique_ptr<CrossMwmGraph> crossMwmGraph, std::unique_ptr<IndexGraphLoader> loader, std::shared_ptr<EdgeEstimator> estimator); void GetEdgeList(Segment const & segment, bool isOutgoing, bool isLeap, std::vector<SegmentEdge> & edges); IndexGraph & GetIndexGraph(NumMwmId numMwmId) { return m_loader->GetIndexGraph(numMwmId); } EdgeEstimator const & GetEstimator() const { return *m_estimator; } Junction const & GetJunction(Segment const & segment, bool front); m2::PointD const & GetPoint(Segment const & segment, bool front); RoadGeometry const & GetRoadGeometry(NumMwmId mwmId, uint32_t featureId); // Clear memory used by loaded index graphs. void ClearIndexGraphs() { m_loader->Clear(); } void SetMode(Mode mode) { m_mode = mode; } Mode GetMode() const { return m_mode; } // Interface for AStarAlgorithm: void GetOutgoingEdgesList(Segment const & segment, vector<SegmentEdge> & edges); void GetIngoingEdgesList(Segment const & segment, vector<SegmentEdge> & edges); RouteWeight HeuristicCostEstimate(Segment const & from, Segment const & to); template <typename Fn> void ForEachTransition(NumMwmId numMwmId, bool isEnter, Fn && fn) { m_crossMwmGraph->ForEachTransition(numMwmId, isEnter, std::forward<Fn>(fn)); } bool IsTransition(Segment const & s, bool isOutgoing) { return m_crossMwmGraph->IsTransition(s, isOutgoing); } private: void GetTwins(Segment const & s, bool isOutgoing, std::vector<SegmentEdge> & edges); std::unique_ptr<CrossMwmGraph> m_crossMwmGraph; std::unique_ptr<IndexGraphLoader> m_loader; std::shared_ptr<EdgeEstimator> m_estimator; std::vector<Segment> m_twins; Mode m_mode = Mode::NoLeaps; }; std::string DebugPrint(WorldGraph::Mode mode); } // namespace routing
36.162791
102
0.725402
xblonde
0909b53f5f3ba3f09d2bdc9945e45e6c7cb87f75
1,325
cc
C++
src/contest/misc/ZOJ_2860_Breaking_Strings.cc
anshika581/competitive-programming-1
c34fb89820cd7260661daa2283f492b07cd9f8d2
[ "Apache-2.0", "MIT" ]
83
2017-08-30T01:20:03.000Z
2022-02-12T13:50:27.000Z
src/contest/misc/ZOJ_2860_Breaking_Strings.cc
anshika581/competitive-programming-1
c34fb89820cd7260661daa2283f492b07cd9f8d2
[ "Apache-2.0", "MIT" ]
1
2015-08-20T13:37:59.000Z
2015-08-26T00:56:39.000Z
src/contest/misc/ZOJ_2860_Breaking_Strings.cc
anshika581/competitive-programming-1
c34fb89820cd7260661daa2283f492b07cd9f8d2
[ "Apache-2.0", "MIT" ]
41
2017-11-09T06:10:08.000Z
2022-01-11T14:10:25.000Z
#include <bits/stdc++.h> #define mp make_pair #define pb push_back #define INF 1 << 30 #define MOD 1000000007 #define rint(x) scanf("%d", &(x)) #define rlong(x) scanf("%lld", &(x)) #define SIZE 1005 #define l(x) x << 1 #define r(x) x << 1 | 1 #define m(x, y) (x + y) / 2 using namespace std; typedef long long ll; typedef pair<int, int> pi; typedef pair<ll, ll> pll; ll dp[SIZE][SIZE]; int mid[SIZE][SIZE]; int pos[SIZE]; int n, m; int main() { // freopen("in.txt", "r", stdin); // freopen("out.txt", "w", stdout); while (scanf("%d%d", &n, &m) != EOF) { for (int i = 1; i <= m; i++) rint(pos[i]); pos[0] = 0; pos[m + 1] = n; for (int i = 0; i <= m + 1; i++) { // length of section of cuts to compute for (int j = 0; j + i <= m + 1; j++) { // section of cuts to compute: [j, j + i] if (i < 2) { dp[j][j + i] = 0ll; mid[j][j + i] = j; continue; } dp[j][j + i] = 1ll << 60; for (int k = mid[j][i + j - 1]; k <= mid[j + 1][i + j]; k++) { // optimal place to cut ll next = dp[j][k] + dp[k][j + i] + pos[j + i] - pos[j]; if (next < dp[j][j + i]) { dp[j][j + i] = next; mid[j][j + i] = k; } } } } printf("%lld\n", dp[0][m + 1]); } return 0; }
23.660714
94
0.453585
anshika581
0909e18cd34a9a51ec677dd6746c0a2232c25038
145
hpp
C++
options/internal/include/mlibc/thread.hpp
vinix-os/mlibc
4cff8ea22e4dcd25bcce90d00ac5b93a6c51d9d8
[ "MIT" ]
null
null
null
options/internal/include/mlibc/thread.hpp
vinix-os/mlibc
4cff8ea22e4dcd25bcce90d00ac5b93a6c51d9d8
[ "MIT" ]
null
null
null
options/internal/include/mlibc/thread.hpp
vinix-os/mlibc
4cff8ea22e4dcd25bcce90d00ac5b93a6c51d9d8
[ "MIT" ]
null
null
null
#pragma once #include <mlibc/tcb.hpp> #include <stdint.h> namespace mlibc { Tcb *get_current_tcb(); uintptr_t get_sp(); } // namespace mlibc
12.083333
24
0.710345
vinix-os
0909ffb20f77ce06f1a6e30ed5c60373befc0468
1,845
hpp
C++
src/libs/dotparser/Expression.hpp
AirbusCyber/grap
dbb037c4e37926e182d0489295b7d901bd0c7c3b
[ "MIT" ]
171
2017-11-09T00:37:58.000Z
2021-10-20T08:58:44.000Z
src/libs/dotparser/Expression.hpp
QuoSecGmbH/grap
dbb037c4e37926e182d0489295b7d901bd0c7c3b
[ "MIT" ]
2
2018-01-09T12:13:39.000Z
2019-03-11T09:58:36.000Z
src/libs/dotparser/Expression.hpp
AirbusCyber/grap
dbb037c4e37926e182d0489295b7d901bd0c7c3b
[ "MIT" ]
18
2017-11-09T01:17:23.000Z
2020-04-23T07:02:32.000Z
/* * Expression.h * Definition of the structure used to build the syntax tree. */ #ifndef __EXPRESSION_H__ #define __EXPRESSION_H__ #include "graph.hpp" #include "graphIO.hpp" #include "node_info.hpp" #include <stddef.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <iostream> typedef struct GraphList { vsize_t size; graph_t** graphes; } GraphList; typedef struct Couple { vsize_t x; vsize_t y; bool is_numbered; bool is_wildcard; bool is_child1; } Couple; typedef struct CoupleList { vsize_t size; Couple** couples; } CoupleList; typedef struct Option { char* id; char* value; } Option; typedef struct OptionList { vsize_t size; Option** options; } OptionList; vsize_t hash_func(char* s); void debug_print(char* s); GraphList* createGraphList(); GraphList* addGraphToInput(graph_t* g, GraphList* gl); typedef std::list<graph_t*> GraphCppList; void freeGraphList(GraphList* gl, bool freeGraphs, bool free_info); void freeGraphList(GraphCppList gl, bool freeGraphs, bool free_info); GraphCppList MakeGraphList(GraphList* gl); CoupleList* createEdgeList(); void freeEdgeList(CoupleList* cl); char *removeQuotes(char *s); CoupleList* addEdgeToList(Couple* c, CoupleList* cl); Couple* createEdge(char* f, char* c, OptionList* ol); graph_t* addEdgesToGraph(char* name, CoupleList* cl, graph_t* g); node_t* updateNode(OptionList* ol, node_t* n); OptionList* createOptionList(); OptionList* addOptionToList(Option* o, OptionList* ol); Option* createOption(char* I, char* V); /** * @brief It creates a node * @param value The name of the node * @return The graph or NULL in case of no memory */ node_t *createNode(char* value); graph_t *createGraph(); graph_t* addNodeToGraph(node_t* n, graph_t* g); void freeOption(Option* o); void freeOptionList(OptionList* ol); #endif
19.21875
69
0.737127
AirbusCyber
090dcddd5f26674efa0d9183b86319b3f794d507
134,724
cpp
C++
boards/ip/hls/x-order_filter/solution1/syn/systemc/x_order_fir.cpp
xupsh/pynq_x_filter
af6dc348b34ede1c071d96a53e44f51fbb2a961c
[ "BSD-3-Clause" ]
1
2022-03-29T23:17:59.000Z
2022-03-29T23:17:59.000Z
boards/ip/hls/x-order_filter/solution1/syn/systemc/x_order_fir.cpp
xupsh/pynq_x_filter
af6dc348b34ede1c071d96a53e44f51fbb2a961c
[ "BSD-3-Clause" ]
null
null
null
boards/ip/hls/x-order_filter/solution1/syn/systemc/x_order_fir.cpp
xupsh/pynq_x_filter
af6dc348b34ede1c071d96a53e44f51fbb2a961c
[ "BSD-3-Clause" ]
null
null
null
// ============================================================== // RTL generated by Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC // Version: 2018.3 // Copyright (C) 1986-2018 Xilinx, Inc. All Rights Reserved. // // =========================================================== #include "x_order_fir.h" #include "AESL_pkg.h" using namespace std; namespace ap_rtl { const sc_logic x_order_fir::ap_const_logic_1 = sc_dt::Log_1; const sc_logic x_order_fir::ap_const_logic_0 = sc_dt::Log_0; const sc_lv<26> x_order_fir::ap_ST_fsm_state1 = "1"; const sc_lv<26> x_order_fir::ap_ST_fsm_state2 = "10"; const sc_lv<26> x_order_fir::ap_ST_fsm_state3 = "100"; const sc_lv<26> x_order_fir::ap_ST_fsm_state4 = "1000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state5 = "10000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state6 = "100000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state7 = "1000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state8 = "10000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_pp0_stage0 = "100000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state12 = "1000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state13 = "10000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state14 = "100000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state15 = "1000000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state16 = "10000000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state17 = "100000000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state18 = "1000000000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state19 = "10000000000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_pp1_stage0 = "100000000000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state23 = "1000000000000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_pp2_stage0 = "10000000000000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_pp2_stage1 = "100000000000000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state28 = "1000000000000000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state29 = "10000000000000000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state30 = "100000000000000000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state31 = "1000000000000000000000000"; const sc_lv<26> x_order_fir::ap_ST_fsm_state32 = "10000000000000000000000000"; const sc_lv<32> x_order_fir::ap_const_lv32_0 = "00000000000000000000000000000000"; const bool x_order_fir::ap_const_boolean_1 = true; const sc_lv<1> x_order_fir::ap_const_lv1_0 = "0"; const sc_lv<1> x_order_fir::ap_const_lv1_1 = "1"; const sc_lv<2> x_order_fir::ap_const_lv2_0 = "00"; const sc_lv<2> x_order_fir::ap_const_lv2_2 = "10"; const sc_lv<2> x_order_fir::ap_const_lv2_3 = "11"; const sc_lv<2> x_order_fir::ap_const_lv2_1 = "1"; const sc_lv<32> x_order_fir::ap_const_lv32_1 = "1"; const sc_lv<32> x_order_fir::ap_const_lv32_8 = "1000"; const bool x_order_fir::ap_const_boolean_0 = false; const sc_lv<32> x_order_fir::ap_const_lv32_A = "1010"; const sc_lv<32> x_order_fir::ap_const_lv32_11 = "10001"; const sc_lv<32> x_order_fir::ap_const_lv32_18 = "11000"; const sc_lv<32> x_order_fir::ap_const_lv32_19 = "11001"; const sc_lv<32> x_order_fir::ap_const_lv32_17 = "10111"; const int x_order_fir::C_S_AXI_DATA_WIDTH = "100000"; const int x_order_fir::C_M_AXI_GMEM_USER_VALUE = "0000000000000000000000000000000000000000000000000000000000000000"; const int x_order_fir::C_M_AXI_GMEM_PROT_VALUE = "0000000000000000000000000000000000000000000000000000000000000000"; const int x_order_fir::C_M_AXI_GMEM_CACHE_VALUE = "11"; const int x_order_fir::C_M_AXI_DATA_WIDTH = "100000"; const sc_lv<32> x_order_fir::ap_const_lv32_14 = "10100"; const sc_lv<32> x_order_fir::ap_const_lv32_16 = "10110"; const sc_lv<32> x_order_fir::ap_const_lv32_7 = "111"; const sc_lv<32> x_order_fir::ap_const_lv32_9 = "1001"; const sc_lv<32> x_order_fir::ap_const_lv32_13 = "10011"; const sc_lv<32> x_order_fir::ap_const_lv32_10 = "10000"; const sc_lv<32> x_order_fir::ap_const_lv32_12 = "10010"; const sc_lv<30> x_order_fir::ap_const_lv30_0 = "000000000000000000000000000000"; const sc_lv<32> x_order_fir::ap_const_lv32_2 = "10"; const sc_lv<3> x_order_fir::ap_const_lv3_0 = "000"; const sc_lv<4> x_order_fir::ap_const_lv4_0 = "0000"; const sc_lv<32> x_order_fir::ap_const_lv32_15 = "10101"; const sc_lv<10> x_order_fir::ap_const_lv10_0 = "0000000000"; const sc_lv<32> x_order_fir::ap_const_lv32_1F = "11111"; const sc_lv<32> x_order_fir::ap_const_lv32_4 = "100"; const sc_lv<30> x_order_fir::ap_const_lv30_1 = "1"; const sc_lv<32> x_order_fir::ap_const_lv32_FFFFFFFF = "11111111111111111111111111111111"; x_order_fir::x_order_fir(sc_module_name name) : sc_module(name), mVcdFile(0) { coef_U = new x_order_fir_coef("coef_U"); coef_U->clk(ap_clk); coef_U->reset(ap_rst_n_inv); coef_U->address0(coef_address0); coef_U->ce0(coef_ce0); coef_U->we0(coef_we0); coef_U->d0(gmem_addr_1_read_reg_555); coef_U->q0(coef_q0); shift_reg_U = new x_order_fir_coef("shift_reg_U"); shift_reg_U->clk(ap_clk); shift_reg_U->reset(ap_rst_n_inv); shift_reg_U->address0(shift_reg_address0); shift_reg_U->ce0(shift_reg_ce0); shift_reg_U->we0(shift_reg_we0); shift_reg_U->d0(shift_reg_d0); shift_reg_U->q0(shift_reg_q0); x_order_fir_AXILiteS_s_axi_U = new x_order_fir_AXILiteS_s_axi<C_S_AXI_AXILITES_ADDR_WIDTH,C_S_AXI_AXILITES_DATA_WIDTH>("x_order_fir_AXILiteS_s_axi_U"); x_order_fir_AXILiteS_s_axi_U->AWVALID(s_axi_AXILiteS_AWVALID); x_order_fir_AXILiteS_s_axi_U->AWREADY(s_axi_AXILiteS_AWREADY); x_order_fir_AXILiteS_s_axi_U->AWADDR(s_axi_AXILiteS_AWADDR); x_order_fir_AXILiteS_s_axi_U->WVALID(s_axi_AXILiteS_WVALID); x_order_fir_AXILiteS_s_axi_U->WREADY(s_axi_AXILiteS_WREADY); x_order_fir_AXILiteS_s_axi_U->WDATA(s_axi_AXILiteS_WDATA); x_order_fir_AXILiteS_s_axi_U->WSTRB(s_axi_AXILiteS_WSTRB); x_order_fir_AXILiteS_s_axi_U->ARVALID(s_axi_AXILiteS_ARVALID); x_order_fir_AXILiteS_s_axi_U->ARREADY(s_axi_AXILiteS_ARREADY); x_order_fir_AXILiteS_s_axi_U->ARADDR(s_axi_AXILiteS_ARADDR); x_order_fir_AXILiteS_s_axi_U->RVALID(s_axi_AXILiteS_RVALID); x_order_fir_AXILiteS_s_axi_U->RREADY(s_axi_AXILiteS_RREADY); x_order_fir_AXILiteS_s_axi_U->RDATA(s_axi_AXILiteS_RDATA); x_order_fir_AXILiteS_s_axi_U->RRESP(s_axi_AXILiteS_RRESP); x_order_fir_AXILiteS_s_axi_U->BVALID(s_axi_AXILiteS_BVALID); x_order_fir_AXILiteS_s_axi_U->BREADY(s_axi_AXILiteS_BREADY); x_order_fir_AXILiteS_s_axi_U->BRESP(s_axi_AXILiteS_BRESP); x_order_fir_AXILiteS_s_axi_U->ACLK(ap_clk); x_order_fir_AXILiteS_s_axi_U->ARESET(ap_rst_n_inv); x_order_fir_AXILiteS_s_axi_U->ACLK_EN(ap_var_for_const0); x_order_fir_AXILiteS_s_axi_U->ap_start(ap_start); x_order_fir_AXILiteS_s_axi_U->interrupt(interrupt); x_order_fir_AXILiteS_s_axi_U->ap_ready(ap_ready); x_order_fir_AXILiteS_s_axi_U->ap_done(ap_done); x_order_fir_AXILiteS_s_axi_U->ap_idle(ap_idle); x_order_fir_AXILiteS_s_axi_U->coe(coe); x_order_fir_AXILiteS_s_axi_U->ctrl(ctrl); x_order_fir_gmem_m_axi_U = new x_order_fir_gmem_m_axi<0,32,32,5,16,16,16,16,C_M_AXI_GMEM_ID_WIDTH,C_M_AXI_GMEM_ADDR_WIDTH,C_M_AXI_GMEM_DATA_WIDTH,C_M_AXI_GMEM_AWUSER_WIDTH,C_M_AXI_GMEM_ARUSER_WIDTH,C_M_AXI_GMEM_WUSER_WIDTH,C_M_AXI_GMEM_RUSER_WIDTH,C_M_AXI_GMEM_BUSER_WIDTH,C_M_AXI_GMEM_USER_VALUE,C_M_AXI_GMEM_PROT_VALUE,C_M_AXI_GMEM_CACHE_VALUE>("x_order_fir_gmem_m_axi_U"); x_order_fir_gmem_m_axi_U->AWVALID(m_axi_gmem_AWVALID); x_order_fir_gmem_m_axi_U->AWREADY(m_axi_gmem_AWREADY); x_order_fir_gmem_m_axi_U->AWADDR(m_axi_gmem_AWADDR); x_order_fir_gmem_m_axi_U->AWID(m_axi_gmem_AWID); x_order_fir_gmem_m_axi_U->AWLEN(m_axi_gmem_AWLEN); x_order_fir_gmem_m_axi_U->AWSIZE(m_axi_gmem_AWSIZE); x_order_fir_gmem_m_axi_U->AWBURST(m_axi_gmem_AWBURST); x_order_fir_gmem_m_axi_U->AWLOCK(m_axi_gmem_AWLOCK); x_order_fir_gmem_m_axi_U->AWCACHE(m_axi_gmem_AWCACHE); x_order_fir_gmem_m_axi_U->AWPROT(m_axi_gmem_AWPROT); x_order_fir_gmem_m_axi_U->AWQOS(m_axi_gmem_AWQOS); x_order_fir_gmem_m_axi_U->AWREGION(m_axi_gmem_AWREGION); x_order_fir_gmem_m_axi_U->AWUSER(m_axi_gmem_AWUSER); x_order_fir_gmem_m_axi_U->WVALID(m_axi_gmem_WVALID); x_order_fir_gmem_m_axi_U->WREADY(m_axi_gmem_WREADY); x_order_fir_gmem_m_axi_U->WDATA(m_axi_gmem_WDATA); x_order_fir_gmem_m_axi_U->WSTRB(m_axi_gmem_WSTRB); x_order_fir_gmem_m_axi_U->WLAST(m_axi_gmem_WLAST); x_order_fir_gmem_m_axi_U->WID(m_axi_gmem_WID); x_order_fir_gmem_m_axi_U->WUSER(m_axi_gmem_WUSER); x_order_fir_gmem_m_axi_U->ARVALID(m_axi_gmem_ARVALID); x_order_fir_gmem_m_axi_U->ARREADY(m_axi_gmem_ARREADY); x_order_fir_gmem_m_axi_U->ARADDR(m_axi_gmem_ARADDR); x_order_fir_gmem_m_axi_U->ARID(m_axi_gmem_ARID); x_order_fir_gmem_m_axi_U->ARLEN(m_axi_gmem_ARLEN); x_order_fir_gmem_m_axi_U->ARSIZE(m_axi_gmem_ARSIZE); x_order_fir_gmem_m_axi_U->ARBURST(m_axi_gmem_ARBURST); x_order_fir_gmem_m_axi_U->ARLOCK(m_axi_gmem_ARLOCK); x_order_fir_gmem_m_axi_U->ARCACHE(m_axi_gmem_ARCACHE); x_order_fir_gmem_m_axi_U->ARPROT(m_axi_gmem_ARPROT); x_order_fir_gmem_m_axi_U->ARQOS(m_axi_gmem_ARQOS); x_order_fir_gmem_m_axi_U->ARREGION(m_axi_gmem_ARREGION); x_order_fir_gmem_m_axi_U->ARUSER(m_axi_gmem_ARUSER); x_order_fir_gmem_m_axi_U->RVALID(m_axi_gmem_RVALID); x_order_fir_gmem_m_axi_U->RREADY(m_axi_gmem_RREADY); x_order_fir_gmem_m_axi_U->RDATA(m_axi_gmem_RDATA); x_order_fir_gmem_m_axi_U->RLAST(m_axi_gmem_RLAST); x_order_fir_gmem_m_axi_U->RID(m_axi_gmem_RID); x_order_fir_gmem_m_axi_U->RUSER(m_axi_gmem_RUSER); x_order_fir_gmem_m_axi_U->RRESP(m_axi_gmem_RRESP); x_order_fir_gmem_m_axi_U->BVALID(m_axi_gmem_BVALID); x_order_fir_gmem_m_axi_U->BREADY(m_axi_gmem_BREADY); x_order_fir_gmem_m_axi_U->BRESP(m_axi_gmem_BRESP); x_order_fir_gmem_m_axi_U->BID(m_axi_gmem_BID); x_order_fir_gmem_m_axi_U->BUSER(m_axi_gmem_BUSER); x_order_fir_gmem_m_axi_U->ACLK(ap_clk); x_order_fir_gmem_m_axi_U->ARESET(ap_rst_n_inv); x_order_fir_gmem_m_axi_U->ACLK_EN(ap_var_for_const0); x_order_fir_gmem_m_axi_U->I_ARVALID(gmem_ARVALID); x_order_fir_gmem_m_axi_U->I_ARREADY(gmem_ARREADY); x_order_fir_gmem_m_axi_U->I_ARADDR(gmem_ARADDR); x_order_fir_gmem_m_axi_U->I_ARID(ap_var_for_const1); x_order_fir_gmem_m_axi_U->I_ARLEN(gmem_ARLEN); x_order_fir_gmem_m_axi_U->I_ARSIZE(ap_var_for_const2); x_order_fir_gmem_m_axi_U->I_ARLOCK(ap_var_for_const3); x_order_fir_gmem_m_axi_U->I_ARCACHE(ap_var_for_const4); x_order_fir_gmem_m_axi_U->I_ARQOS(ap_var_for_const4); x_order_fir_gmem_m_axi_U->I_ARPROT(ap_var_for_const2); x_order_fir_gmem_m_axi_U->I_ARUSER(ap_var_for_const1); x_order_fir_gmem_m_axi_U->I_ARBURST(ap_var_for_const3); x_order_fir_gmem_m_axi_U->I_ARREGION(ap_var_for_const4); x_order_fir_gmem_m_axi_U->I_RVALID(gmem_RVALID); x_order_fir_gmem_m_axi_U->I_RREADY(gmem_RREADY); x_order_fir_gmem_m_axi_U->I_RDATA(gmem_RDATA); x_order_fir_gmem_m_axi_U->I_RID(gmem_RID); x_order_fir_gmem_m_axi_U->I_RUSER(gmem_RUSER); x_order_fir_gmem_m_axi_U->I_RRESP(gmem_RRESP); x_order_fir_gmem_m_axi_U->I_RLAST(gmem_RLAST); x_order_fir_gmem_m_axi_U->I_AWVALID(ap_var_for_const5); x_order_fir_gmem_m_axi_U->I_AWREADY(gmem_AWREADY); x_order_fir_gmem_m_axi_U->I_AWADDR(ap_var_for_const6); x_order_fir_gmem_m_axi_U->I_AWID(ap_var_for_const1); x_order_fir_gmem_m_axi_U->I_AWLEN(ap_var_for_const6); x_order_fir_gmem_m_axi_U->I_AWSIZE(ap_var_for_const2); x_order_fir_gmem_m_axi_U->I_AWLOCK(ap_var_for_const3); x_order_fir_gmem_m_axi_U->I_AWCACHE(ap_var_for_const4); x_order_fir_gmem_m_axi_U->I_AWQOS(ap_var_for_const4); x_order_fir_gmem_m_axi_U->I_AWPROT(ap_var_for_const2); x_order_fir_gmem_m_axi_U->I_AWUSER(ap_var_for_const1); x_order_fir_gmem_m_axi_U->I_AWBURST(ap_var_for_const3); x_order_fir_gmem_m_axi_U->I_AWREGION(ap_var_for_const4); x_order_fir_gmem_m_axi_U->I_WVALID(ap_var_for_const5); x_order_fir_gmem_m_axi_U->I_WREADY(gmem_WREADY); x_order_fir_gmem_m_axi_U->I_WDATA(ap_var_for_const6); x_order_fir_gmem_m_axi_U->I_WID(ap_var_for_const1); x_order_fir_gmem_m_axi_U->I_WUSER(ap_var_for_const1); x_order_fir_gmem_m_axi_U->I_WLAST(ap_var_for_const5); x_order_fir_gmem_m_axi_U->I_WSTRB(ap_var_for_const4); x_order_fir_gmem_m_axi_U->I_BVALID(gmem_BVALID); x_order_fir_gmem_m_axi_U->I_BREADY(ap_var_for_const5); x_order_fir_gmem_m_axi_U->I_BRESP(gmem_BRESP); x_order_fir_gmem_m_axi_U->I_BID(gmem_BID); x_order_fir_gmem_m_axi_U->I_BUSER(gmem_BUSER); SC_METHOD(thread_ap_clk_no_reset_); dont_initialize(); sensitive << ( ap_clk.pos() ); SC_METHOD(thread_acc_1_fu_472_p2); sensitive << ( acc_reg_290 ); sensitive << ( tmp_3_reg_609 ); SC_METHOD(thread_acc_2_fu_448_p2); sensitive << ( acc_reg_290 ); sensitive << ( tmp_8_reg_589 ); SC_METHOD(thread_ap_CS_fsm_pp0_stage0); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_pp1_stage0); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_pp2_stage0); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_pp2_stage1); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_state1); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_state12); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_state13); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_state19); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_state2); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_state23); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_state28); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_state29); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_state30); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_state31); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_state32); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_CS_fsm_state8); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_block_pp0_stage0); SC_METHOD(thread_ap_block_pp0_stage0_11001); sensitive << ( ap_enable_reg_pp0_iter1 ); sensitive << ( exitcond_reg_500 ); sensitive << ( gmem_RVALID ); SC_METHOD(thread_ap_block_pp0_stage0_subdone); sensitive << ( ap_enable_reg_pp0_iter1 ); sensitive << ( exitcond_reg_500 ); sensitive << ( gmem_RVALID ); SC_METHOD(thread_ap_block_pp1_stage0); SC_METHOD(thread_ap_block_pp1_stage0_11001); sensitive << ( ap_enable_reg_pp1_iter1 ); sensitive << ( exitcond1_reg_546 ); sensitive << ( gmem_RVALID ); SC_METHOD(thread_ap_block_pp1_stage0_subdone); sensitive << ( ap_enable_reg_pp1_iter1 ); sensitive << ( exitcond1_reg_546 ); sensitive << ( gmem_RVALID ); SC_METHOD(thread_ap_block_pp2_stage0); SC_METHOD(thread_ap_block_pp2_stage0_11001); SC_METHOD(thread_ap_block_pp2_stage0_subdone); SC_METHOD(thread_ap_block_pp2_stage1); SC_METHOD(thread_ap_block_pp2_stage1_11001); SC_METHOD(thread_ap_block_pp2_stage1_subdone); SC_METHOD(thread_ap_block_state10_pp0_stage0_iter1); sensitive << ( exitcond_reg_500 ); sensitive << ( gmem_RVALID ); SC_METHOD(thread_ap_block_state11_pp0_stage0_iter2); SC_METHOD(thread_ap_block_state20_pp1_stage0_iter0); SC_METHOD(thread_ap_block_state21_pp1_stage0_iter1); sensitive << ( exitcond1_reg_546 ); sensitive << ( gmem_RVALID ); SC_METHOD(thread_ap_block_state22_pp1_stage0_iter2); SC_METHOD(thread_ap_block_state24_pp2_stage0_iter0); SC_METHOD(thread_ap_block_state25_pp2_stage1_iter0); SC_METHOD(thread_ap_block_state26_pp2_stage0_iter1); SC_METHOD(thread_ap_block_state27_pp2_stage1_iter1); SC_METHOD(thread_ap_block_state32); sensitive << ( y_data_1_ack_in ); sensitive << ( y_user_V_1_ack_in ); sensitive << ( y_last_V_1_ack_in ); SC_METHOD(thread_ap_block_state9_pp0_stage0_iter0); SC_METHOD(thread_ap_condition_pp0_exit_iter0_state9); sensitive << ( exitcond_fu_345_p2 ); SC_METHOD(thread_ap_condition_pp1_exit_iter0_state20); sensitive << ( exitcond1_fu_405_p2 ); SC_METHOD(thread_ap_condition_pp2_exit_iter0_state24); sensitive << ( tmp_2_fu_421_p2 ); SC_METHOD(thread_ap_done); sensitive << ( y_data_1_ack_in ); sensitive << ( y_data_1_state ); sensitive << ( y_user_V_1_ack_in ); sensitive << ( y_user_V_1_state ); sensitive << ( y_last_V_1_ack_in ); sensitive << ( y_last_V_1_state ); sensitive << ( ap_CS_fsm_state32 ); SC_METHOD(thread_ap_enable_pp0); sensitive << ( ap_idle_pp0 ); SC_METHOD(thread_ap_enable_pp1); sensitive << ( ap_idle_pp1 ); SC_METHOD(thread_ap_enable_pp2); sensitive << ( ap_idle_pp2 ); SC_METHOD(thread_ap_idle); sensitive << ( ap_start ); sensitive << ( ap_CS_fsm_state1 ); SC_METHOD(thread_ap_idle_pp0); sensitive << ( ap_enable_reg_pp0_iter1 ); sensitive << ( ap_enable_reg_pp0_iter0 ); sensitive << ( ap_enable_reg_pp0_iter2 ); SC_METHOD(thread_ap_idle_pp1); sensitive << ( ap_enable_reg_pp1_iter1 ); sensitive << ( ap_enable_reg_pp1_iter0 ); sensitive << ( ap_enable_reg_pp1_iter2 ); SC_METHOD(thread_ap_idle_pp2); sensitive << ( ap_enable_reg_pp2_iter0 ); sensitive << ( ap_enable_reg_pp2_iter1 ); SC_METHOD(thread_ap_phi_mux_i1_phi_fu_283_p4); sensitive << ( i1_reg_280 ); sensitive << ( tmp_2_reg_560 ); sensitive << ( ap_CS_fsm_pp2_stage0 ); sensitive << ( i_1_reg_564 ); sensitive << ( ap_enable_reg_pp2_iter1 ); sensitive << ( ap_block_pp2_stage0 ); SC_METHOD(thread_ap_phi_mux_indvar1_phi_fu_272_p4); sensitive << ( ap_CS_fsm_pp1_stage0 ); sensitive << ( ap_enable_reg_pp1_iter1 ); sensitive << ( ap_block_pp1_stage0 ); sensitive << ( exitcond1_reg_546 ); sensitive << ( indvar1_reg_268 ); sensitive << ( indvar_next1_reg_550 ); SC_METHOD(thread_ap_ready); sensitive << ( y_data_1_ack_in ); sensitive << ( y_data_1_state ); sensitive << ( y_user_V_1_ack_in ); sensitive << ( y_user_V_1_state ); sensitive << ( y_last_V_1_ack_in ); sensitive << ( y_last_V_1_state ); sensitive << ( ap_CS_fsm_state32 ); SC_METHOD(thread_ap_rst_n_inv); sensitive << ( ap_rst_n ); SC_METHOD(thread_ap_sig_ioackin_gmem_ARREADY); sensitive << ( gmem_ARREADY ); sensitive << ( ap_reg_ioackin_gmem_ARREADY ); SC_METHOD(thread_coef_address0); sensitive << ( ap_block_pp1_stage0 ); sensitive << ( ap_enable_reg_pp2_iter0 ); sensitive << ( ap_CS_fsm_pp2_stage0 ); sensitive << ( tmp_7_fu_438_p1 ); sensitive << ( ap_enable_reg_pp1_iter2 ); sensitive << ( ap_block_pp2_stage0 ); sensitive << ( indvar2_fu_416_p1 ); sensitive << ( ap_CS_fsm_state28 ); SC_METHOD(thread_coef_ce0); sensitive << ( ap_block_pp1_stage0_11001 ); sensitive << ( ap_enable_reg_pp2_iter0 ); sensitive << ( ap_CS_fsm_pp2_stage0 ); sensitive << ( ap_block_pp2_stage0_11001 ); sensitive << ( ap_enable_reg_pp1_iter2 ); sensitive << ( ap_CS_fsm_state28 ); SC_METHOD(thread_coef_we0); sensitive << ( ap_block_pp1_stage0_11001 ); sensitive << ( exitcond1_reg_546_pp1_iter1_reg ); sensitive << ( ap_enable_reg_pp1_iter2 ); SC_METHOD(thread_exitcond1_fu_405_p2); sensitive << ( ap_CS_fsm_pp1_stage0 ); sensitive << ( ap_block_pp1_stage0_11001 ); sensitive << ( p_add7_i32_shr_reg_535 ); sensitive << ( ap_enable_reg_pp1_iter0 ); sensitive << ( ap_phi_mux_indvar1_phi_fu_272_p4 ); SC_METHOD(thread_exitcond_fu_345_p2); sensitive << ( ap_CS_fsm_pp0_stage0 ); sensitive << ( indvar_reg_257 ); sensitive << ( ap_block_pp0_stage0_11001 ); sensitive << ( ap_enable_reg_pp0_iter0 ); SC_METHOD(thread_fir_ctrl_1_1_fu_361_p3); sensitive << ( i_reg_233 ); sensitive << ( tmp_10_reg_509_pp0_iter1_reg ); sensitive << ( fir_ctrl_0_reg_515 ); SC_METHOD(thread_gmem_ARADDR); sensitive << ( ap_CS_fsm_state2 ); sensitive << ( ap_CS_fsm_state13 ); sensitive << ( gmem_addr_1_reg_494 ); sensitive << ( tmp_5_fu_326_p1 ); sensitive << ( ap_reg_ioackin_gmem_ARREADY ); SC_METHOD(thread_gmem_ARLEN); sensitive << ( ap_CS_fsm_state2 ); sensitive << ( ap_CS_fsm_state13 ); sensitive << ( tmp_s_fu_401_p1 ); sensitive << ( ap_reg_ioackin_gmem_ARREADY ); SC_METHOD(thread_gmem_ARVALID); sensitive << ( ap_CS_fsm_state2 ); sensitive << ( ap_CS_fsm_state13 ); sensitive << ( ap_reg_ioackin_gmem_ARREADY ); SC_METHOD(thread_gmem_RREADY); sensitive << ( ap_CS_fsm_pp0_stage0 ); sensitive << ( ap_enable_reg_pp0_iter1 ); sensitive << ( exitcond_reg_500 ); sensitive << ( ap_CS_fsm_pp1_stage0 ); sensitive << ( ap_enable_reg_pp1_iter1 ); sensitive << ( exitcond1_reg_546 ); sensitive << ( ap_block_pp1_stage0_11001 ); sensitive << ( ap_block_pp0_stage0_11001 ); SC_METHOD(thread_gmem_blk_n_AR); sensitive << ( m_axi_gmem_ARREADY ); sensitive << ( ap_CS_fsm_state2 ); sensitive << ( ap_CS_fsm_state13 ); SC_METHOD(thread_gmem_blk_n_R); sensitive << ( m_axi_gmem_RVALID ); sensitive << ( ap_CS_fsm_pp0_stage0 ); sensitive << ( ap_enable_reg_pp0_iter1 ); sensitive << ( ap_block_pp0_stage0 ); sensitive << ( exitcond_reg_500 ); sensitive << ( ap_CS_fsm_pp1_stage0 ); sensitive << ( ap_enable_reg_pp1_iter1 ); sensitive << ( ap_block_pp1_stage0 ); sensitive << ( exitcond1_reg_546 ); SC_METHOD(thread_i_1_fu_427_p2); sensitive << ( ap_phi_mux_i1_phi_fu_283_p4 ); SC_METHOD(thread_indvar2_fu_416_p1); sensitive << ( indvar1_reg_268_pp1_iter1_reg ); SC_METHOD(thread_indvar_next1_fu_410_p2); sensitive << ( ap_phi_mux_indvar1_phi_fu_272_p4 ); SC_METHOD(thread_indvar_next_fu_351_p2); sensitive << ( indvar_reg_257 ); SC_METHOD(thread_reload_1_fu_367_p3); sensitive << ( reload_reg_245 ); sensitive << ( tmp_10_reg_509_pp0_iter1_reg ); sensitive << ( fir_ctrl_0_reg_515 ); SC_METHOD(thread_shift_reg_address0); sensitive << ( ap_CS_fsm_state30 ); sensitive << ( ap_CS_fsm_pp2_stage1 ); sensitive << ( ap_enable_reg_pp2_iter0 ); sensitive << ( ap_CS_fsm_pp2_stage0 ); sensitive << ( tmp_7_reg_574 ); sensitive << ( ap_block_pp2_stage0 ); sensitive << ( tmp_6_fu_433_p1 ); sensitive << ( ap_block_pp2_stage1 ); SC_METHOD(thread_shift_reg_ce0); sensitive << ( x_data_0_vld_out ); sensitive << ( ap_CS_fsm_state30 ); sensitive << ( ap_CS_fsm_pp2_stage1 ); sensitive << ( ap_enable_reg_pp2_iter0 ); sensitive << ( ap_block_pp2_stage1_11001 ); sensitive << ( ap_CS_fsm_pp2_stage0 ); sensitive << ( ap_block_pp2_stage0_11001 ); SC_METHOD(thread_shift_reg_d0); sensitive << ( x_data_0_data_out ); sensitive << ( shift_reg_q0 ); sensitive << ( ap_CS_fsm_state30 ); sensitive << ( ap_CS_fsm_pp2_stage1 ); sensitive << ( ap_enable_reg_pp2_iter0 ); sensitive << ( ap_block_pp2_stage1 ); SC_METHOD(thread_shift_reg_we0); sensitive << ( x_data_0_vld_out ); sensitive << ( ap_CS_fsm_state30 ); sensitive << ( ap_CS_fsm_pp2_stage1 ); sensitive << ( ap_enable_reg_pp2_iter0 ); sensitive << ( ap_block_pp2_stage1_11001 ); sensitive << ( tmp_2_reg_560 ); SC_METHOD(thread_tmp_10_fu_357_p1); sensitive << ( indvar_reg_257 ); SC_METHOD(thread_tmp_12_fu_379_p2); sensitive << ( i_reg_233 ); SC_METHOD(thread_tmp_1_fu_385_p2); sensitive << ( tmp_12_fu_379_p2 ); SC_METHOD(thread_tmp_2_fu_421_p2); sensitive << ( ap_enable_reg_pp2_iter0 ); sensitive << ( ap_CS_fsm_pp2_stage0 ); sensitive << ( ap_block_pp2_stage0_11001 ); sensitive << ( ap_phi_mux_i1_phi_fu_283_p4 ); SC_METHOD(thread_tmp_3_fu_466_p1); sensitive << ( x_data_0_data_out ); sensitive << ( ap_CS_fsm_state30 ); SC_METHOD(thread_tmp_3_fu_466_p2); sensitive << ( reg_302 ); sensitive << ( tmp_3_fu_466_p1 ); SC_METHOD(thread_tmp_5_fu_326_p1); sensitive << ( ctrl3_reg_478 ); SC_METHOD(thread_tmp_6_fu_433_p1); sensitive << ( i_1_fu_427_p2 ); SC_METHOD(thread_tmp_7_fu_438_p1); sensitive << ( ap_phi_mux_i1_phi_fu_283_p4 ); SC_METHOD(thread_tmp_8_fu_443_p2); sensitive << ( reg_302 ); sensitive << ( shift_reg_load_reg_584 ); SC_METHOD(thread_tmp_9_fu_336_p1); sensitive << ( coe1_reg_483 ); SC_METHOD(thread_tmp_fu_373_p2); sensitive << ( reload_reg_245 ); sensitive << ( ap_CS_fsm_state12 ); SC_METHOD(thread_tmp_s_fu_401_p1); sensitive << ( p_add7_i32_shr_reg_535 ); SC_METHOD(thread_x_TDATA_blk_n); sensitive << ( x_data_0_state ); sensitive << ( ap_CS_fsm_state30 ); SC_METHOD(thread_x_TREADY); sensitive << ( x_last_V_0_state ); SC_METHOD(thread_x_data_0_ack_in); sensitive << ( x_data_0_state ); SC_METHOD(thread_x_data_0_ack_out); sensitive << ( x_data_0_vld_out ); sensitive << ( ap_CS_fsm_state30 ); SC_METHOD(thread_x_data_0_data_out); sensitive << ( x_data_0_payload_A ); sensitive << ( x_data_0_payload_B ); sensitive << ( x_data_0_sel ); SC_METHOD(thread_x_data_0_load_A); sensitive << ( x_data_0_sel_wr ); sensitive << ( x_data_0_state_cmp_full ); SC_METHOD(thread_x_data_0_load_B); sensitive << ( x_data_0_sel_wr ); sensitive << ( x_data_0_state_cmp_full ); SC_METHOD(thread_x_data_0_sel); sensitive << ( x_data_0_sel_rd ); SC_METHOD(thread_x_data_0_state_cmp_full); sensitive << ( x_data_0_state ); SC_METHOD(thread_x_data_0_vld_in); sensitive << ( x_TVALID ); SC_METHOD(thread_x_data_0_vld_out); sensitive << ( x_data_0_state ); SC_METHOD(thread_x_last_V_0_ack_in); sensitive << ( x_last_V_0_state ); SC_METHOD(thread_x_last_V_0_ack_out); sensitive << ( x_data_0_vld_out ); sensitive << ( ap_CS_fsm_state30 ); SC_METHOD(thread_x_last_V_0_data_out); sensitive << ( x_last_V_0_payload_A ); sensitive << ( x_last_V_0_payload_B ); sensitive << ( x_last_V_0_sel ); SC_METHOD(thread_x_last_V_0_load_A); sensitive << ( x_last_V_0_sel_wr ); sensitive << ( x_last_V_0_state_cmp_full ); SC_METHOD(thread_x_last_V_0_load_B); sensitive << ( x_last_V_0_sel_wr ); sensitive << ( x_last_V_0_state_cmp_full ); SC_METHOD(thread_x_last_V_0_sel); sensitive << ( x_last_V_0_sel_rd ); SC_METHOD(thread_x_last_V_0_state_cmp_full); sensitive << ( x_last_V_0_state ); SC_METHOD(thread_x_last_V_0_vld_in); sensitive << ( x_TVALID ); SC_METHOD(thread_x_last_V_0_vld_out); sensitive << ( x_last_V_0_state ); SC_METHOD(thread_x_user_V_0_ack_in); sensitive << ( x_user_V_0_state ); SC_METHOD(thread_x_user_V_0_ack_out); sensitive << ( x_data_0_vld_out ); sensitive << ( ap_CS_fsm_state30 ); SC_METHOD(thread_x_user_V_0_data_out); sensitive << ( x_user_V_0_payload_A ); sensitive << ( x_user_V_0_payload_B ); sensitive << ( x_user_V_0_sel ); SC_METHOD(thread_x_user_V_0_load_A); sensitive << ( x_user_V_0_sel_wr ); sensitive << ( x_user_V_0_state_cmp_full ); SC_METHOD(thread_x_user_V_0_load_B); sensitive << ( x_user_V_0_sel_wr ); sensitive << ( x_user_V_0_state_cmp_full ); SC_METHOD(thread_x_user_V_0_sel); sensitive << ( x_user_V_0_sel_rd ); SC_METHOD(thread_x_user_V_0_state_cmp_full); sensitive << ( x_user_V_0_state ); SC_METHOD(thread_x_user_V_0_vld_in); sensitive << ( x_TVALID ); SC_METHOD(thread_x_user_V_0_vld_out); sensitive << ( x_user_V_0_state ); SC_METHOD(thread_y_TDATA); sensitive << ( y_data_1_data_out ); SC_METHOD(thread_y_TDATA_blk_n); sensitive << ( y_data_1_state ); sensitive << ( ap_CS_fsm_state31 ); sensitive << ( ap_CS_fsm_state32 ); SC_METHOD(thread_y_TLAST); sensitive << ( y_last_V_1_data_out ); SC_METHOD(thread_y_TUSER); sensitive << ( y_user_V_1_data_out ); SC_METHOD(thread_y_TVALID); sensitive << ( y_last_V_1_state ); SC_METHOD(thread_y_data_1_ack_in); sensitive << ( y_data_1_state ); SC_METHOD(thread_y_data_1_ack_out); sensitive << ( y_TREADY ); SC_METHOD(thread_y_data_1_data_out); sensitive << ( y_data_1_payload_A ); sensitive << ( y_data_1_payload_B ); sensitive << ( y_data_1_sel ); SC_METHOD(thread_y_data_1_load_A); sensitive << ( y_data_1_sel_wr ); sensitive << ( y_data_1_state_cmp_full ); SC_METHOD(thread_y_data_1_load_B); sensitive << ( y_data_1_sel_wr ); sensitive << ( y_data_1_state_cmp_full ); SC_METHOD(thread_y_data_1_sel); sensitive << ( y_data_1_sel_rd ); SC_METHOD(thread_y_data_1_state_cmp_full); sensitive << ( y_data_1_state ); SC_METHOD(thread_y_data_1_vld_in); sensitive << ( y_data_1_ack_in ); sensitive << ( ap_CS_fsm_state31 ); SC_METHOD(thread_y_data_1_vld_out); sensitive << ( y_data_1_state ); SC_METHOD(thread_y_last_V_1_ack_in); sensitive << ( y_last_V_1_state ); SC_METHOD(thread_y_last_V_1_ack_out); sensitive << ( y_TREADY ); SC_METHOD(thread_y_last_V_1_data_out); sensitive << ( y_last_V_1_payload_A ); sensitive << ( y_last_V_1_payload_B ); sensitive << ( y_last_V_1_sel ); SC_METHOD(thread_y_last_V_1_load_A); sensitive << ( y_last_V_1_sel_wr ); sensitive << ( y_last_V_1_state_cmp_full ); SC_METHOD(thread_y_last_V_1_load_B); sensitive << ( y_last_V_1_sel_wr ); sensitive << ( y_last_V_1_state_cmp_full ); SC_METHOD(thread_y_last_V_1_sel); sensitive << ( y_last_V_1_sel_rd ); SC_METHOD(thread_y_last_V_1_state_cmp_full); sensitive << ( y_last_V_1_state ); SC_METHOD(thread_y_last_V_1_vld_in); sensitive << ( y_data_1_ack_in ); sensitive << ( ap_CS_fsm_state31 ); SC_METHOD(thread_y_last_V_1_vld_out); sensitive << ( y_last_V_1_state ); SC_METHOD(thread_y_user_V_1_ack_in); sensitive << ( y_user_V_1_state ); SC_METHOD(thread_y_user_V_1_ack_out); sensitive << ( y_TREADY ); SC_METHOD(thread_y_user_V_1_data_out); sensitive << ( y_user_V_1_payload_A ); sensitive << ( y_user_V_1_payload_B ); sensitive << ( y_user_V_1_sel ); SC_METHOD(thread_y_user_V_1_load_A); sensitive << ( y_user_V_1_sel_wr ); sensitive << ( y_user_V_1_state_cmp_full ); SC_METHOD(thread_y_user_V_1_load_B); sensitive << ( y_user_V_1_sel_wr ); sensitive << ( y_user_V_1_state_cmp_full ); SC_METHOD(thread_y_user_V_1_sel); sensitive << ( y_user_V_1_sel_rd ); SC_METHOD(thread_y_user_V_1_state_cmp_full); sensitive << ( y_user_V_1_state ); SC_METHOD(thread_y_user_V_1_vld_in); sensitive << ( y_data_1_ack_in ); sensitive << ( ap_CS_fsm_state31 ); SC_METHOD(thread_y_user_V_1_vld_out); sensitive << ( y_user_V_1_state ); SC_METHOD(thread_ap_NS_fsm); sensitive << ( ap_start ); sensitive << ( ap_CS_fsm ); sensitive << ( ap_CS_fsm_state1 ); sensitive << ( y_data_1_ack_in ); sensitive << ( y_data_1_state ); sensitive << ( y_user_V_1_ack_in ); sensitive << ( y_user_V_1_state ); sensitive << ( y_last_V_1_ack_in ); sensitive << ( y_last_V_1_state ); sensitive << ( x_data_0_vld_out ); sensitive << ( ap_CS_fsm_state2 ); sensitive << ( ap_enable_reg_pp0_iter1 ); sensitive << ( ap_CS_fsm_state13 ); sensitive << ( ap_enable_reg_pp1_iter1 ); sensitive << ( ap_CS_fsm_state31 ); sensitive << ( ap_CS_fsm_state32 ); sensitive << ( ap_CS_fsm_state30 ); sensitive << ( ap_CS_fsm_pp2_stage1 ); sensitive << ( ap_enable_reg_pp2_iter0 ); sensitive << ( ap_sig_ioackin_gmem_ARREADY ); sensitive << ( exitcond_fu_345_p2 ); sensitive << ( ap_enable_reg_pp0_iter0 ); sensitive << ( ap_enable_reg_pp0_iter2 ); sensitive << ( tmp_fu_373_p2 ); sensitive << ( ap_CS_fsm_state12 ); sensitive << ( exitcond1_fu_405_p2 ); sensitive << ( ap_enable_reg_pp1_iter0 ); sensitive << ( tmp_2_fu_421_p2 ); sensitive << ( ap_enable_reg_pp2_iter1 ); sensitive << ( ap_block_pp0_stage0_subdone ); sensitive << ( ap_block_pp1_stage0_subdone ); sensitive << ( ap_enable_reg_pp1_iter2 ); sensitive << ( ap_block_pp2_stage0_subdone ); sensitive << ( ap_block_pp2_stage1_subdone ); SC_THREAD(thread_hdltv_gen); sensitive << ( ap_clk.pos() ); SC_THREAD(thread_ap_var_for_const0); SC_THREAD(thread_ap_var_for_const5); SC_THREAD(thread_ap_var_for_const6); SC_THREAD(thread_ap_var_for_const1); SC_THREAD(thread_ap_var_for_const3); SC_THREAD(thread_ap_var_for_const2); SC_THREAD(thread_ap_var_for_const4); ap_CS_fsm = "00000000000000000000000001"; y_data_1_sel_rd = SC_LOGIC_0; y_data_1_sel_wr = SC_LOGIC_0; y_data_1_state = "00"; y_user_V_1_sel_rd = SC_LOGIC_0; y_user_V_1_sel_wr = SC_LOGIC_0; y_user_V_1_state = "00"; y_last_V_1_sel_rd = SC_LOGIC_0; y_last_V_1_sel_wr = SC_LOGIC_0; y_last_V_1_state = "00"; x_data_0_sel_rd = SC_LOGIC_0; x_data_0_sel_wr = SC_LOGIC_0; x_data_0_state = "00"; x_user_V_0_sel_rd = SC_LOGIC_0; x_user_V_0_sel_wr = SC_LOGIC_0; x_user_V_0_state = "00"; x_last_V_0_sel_rd = SC_LOGIC_0; x_last_V_0_sel_wr = SC_LOGIC_0; x_last_V_0_state = "00"; ap_enable_reg_pp0_iter1 = SC_LOGIC_0; ap_enable_reg_pp1_iter1 = SC_LOGIC_0; ap_enable_reg_pp2_iter0 = SC_LOGIC_0; ap_enable_reg_pp0_iter0 = SC_LOGIC_0; ap_enable_reg_pp0_iter2 = SC_LOGIC_0; ap_enable_reg_pp1_iter0 = SC_LOGIC_0; ap_enable_reg_pp2_iter1 = SC_LOGIC_0; ap_enable_reg_pp1_iter2 = SC_LOGIC_0; ap_reg_ioackin_gmem_ARREADY = SC_LOGIC_0; static int apTFileNum = 0; stringstream apTFilenSS; apTFilenSS << "x_order_fir_sc_trace_" << apTFileNum ++; string apTFn = apTFilenSS.str(); mVcdFile = sc_create_vcd_trace_file(apTFn.c_str()); mVcdFile->set_time_unit(1, SC_PS); if (1) { #ifdef __HLS_TRACE_LEVEL_PORT__ sc_trace(mVcdFile, ap_clk, "(port)ap_clk"); sc_trace(mVcdFile, ap_rst_n, "(port)ap_rst_n"); sc_trace(mVcdFile, m_axi_gmem_AWVALID, "(port)m_axi_gmem_AWVALID"); sc_trace(mVcdFile, m_axi_gmem_AWREADY, "(port)m_axi_gmem_AWREADY"); sc_trace(mVcdFile, m_axi_gmem_AWADDR, "(port)m_axi_gmem_AWADDR"); sc_trace(mVcdFile, m_axi_gmem_AWID, "(port)m_axi_gmem_AWID"); sc_trace(mVcdFile, m_axi_gmem_AWLEN, "(port)m_axi_gmem_AWLEN"); sc_trace(mVcdFile, m_axi_gmem_AWSIZE, "(port)m_axi_gmem_AWSIZE"); sc_trace(mVcdFile, m_axi_gmem_AWBURST, "(port)m_axi_gmem_AWBURST"); sc_trace(mVcdFile, m_axi_gmem_AWLOCK, "(port)m_axi_gmem_AWLOCK"); sc_trace(mVcdFile, m_axi_gmem_AWCACHE, "(port)m_axi_gmem_AWCACHE"); sc_trace(mVcdFile, m_axi_gmem_AWPROT, "(port)m_axi_gmem_AWPROT"); sc_trace(mVcdFile, m_axi_gmem_AWQOS, "(port)m_axi_gmem_AWQOS"); sc_trace(mVcdFile, m_axi_gmem_AWREGION, "(port)m_axi_gmem_AWREGION"); sc_trace(mVcdFile, m_axi_gmem_AWUSER, "(port)m_axi_gmem_AWUSER"); sc_trace(mVcdFile, m_axi_gmem_WVALID, "(port)m_axi_gmem_WVALID"); sc_trace(mVcdFile, m_axi_gmem_WREADY, "(port)m_axi_gmem_WREADY"); sc_trace(mVcdFile, m_axi_gmem_WDATA, "(port)m_axi_gmem_WDATA"); sc_trace(mVcdFile, m_axi_gmem_WSTRB, "(port)m_axi_gmem_WSTRB"); sc_trace(mVcdFile, m_axi_gmem_WLAST, "(port)m_axi_gmem_WLAST"); sc_trace(mVcdFile, m_axi_gmem_WID, "(port)m_axi_gmem_WID"); sc_trace(mVcdFile, m_axi_gmem_WUSER, "(port)m_axi_gmem_WUSER"); sc_trace(mVcdFile, m_axi_gmem_ARVALID, "(port)m_axi_gmem_ARVALID"); sc_trace(mVcdFile, m_axi_gmem_ARREADY, "(port)m_axi_gmem_ARREADY"); sc_trace(mVcdFile, m_axi_gmem_ARADDR, "(port)m_axi_gmem_ARADDR"); sc_trace(mVcdFile, m_axi_gmem_ARID, "(port)m_axi_gmem_ARID"); sc_trace(mVcdFile, m_axi_gmem_ARLEN, "(port)m_axi_gmem_ARLEN"); sc_trace(mVcdFile, m_axi_gmem_ARSIZE, "(port)m_axi_gmem_ARSIZE"); sc_trace(mVcdFile, m_axi_gmem_ARBURST, "(port)m_axi_gmem_ARBURST"); sc_trace(mVcdFile, m_axi_gmem_ARLOCK, "(port)m_axi_gmem_ARLOCK"); sc_trace(mVcdFile, m_axi_gmem_ARCACHE, "(port)m_axi_gmem_ARCACHE"); sc_trace(mVcdFile, m_axi_gmem_ARPROT, "(port)m_axi_gmem_ARPROT"); sc_trace(mVcdFile, m_axi_gmem_ARQOS, "(port)m_axi_gmem_ARQOS"); sc_trace(mVcdFile, m_axi_gmem_ARREGION, "(port)m_axi_gmem_ARREGION"); sc_trace(mVcdFile, m_axi_gmem_ARUSER, "(port)m_axi_gmem_ARUSER"); sc_trace(mVcdFile, m_axi_gmem_RVALID, "(port)m_axi_gmem_RVALID"); sc_trace(mVcdFile, m_axi_gmem_RREADY, "(port)m_axi_gmem_RREADY"); sc_trace(mVcdFile, m_axi_gmem_RDATA, "(port)m_axi_gmem_RDATA"); sc_trace(mVcdFile, m_axi_gmem_RLAST, "(port)m_axi_gmem_RLAST"); sc_trace(mVcdFile, m_axi_gmem_RID, "(port)m_axi_gmem_RID"); sc_trace(mVcdFile, m_axi_gmem_RUSER, "(port)m_axi_gmem_RUSER"); sc_trace(mVcdFile, m_axi_gmem_RRESP, "(port)m_axi_gmem_RRESP"); sc_trace(mVcdFile, m_axi_gmem_BVALID, "(port)m_axi_gmem_BVALID"); sc_trace(mVcdFile, m_axi_gmem_BREADY, "(port)m_axi_gmem_BREADY"); sc_trace(mVcdFile, m_axi_gmem_BRESP, "(port)m_axi_gmem_BRESP"); sc_trace(mVcdFile, m_axi_gmem_BID, "(port)m_axi_gmem_BID"); sc_trace(mVcdFile, m_axi_gmem_BUSER, "(port)m_axi_gmem_BUSER"); sc_trace(mVcdFile, y_TDATA, "(port)y_TDATA"); sc_trace(mVcdFile, y_TVALID, "(port)y_TVALID"); sc_trace(mVcdFile, y_TREADY, "(port)y_TREADY"); sc_trace(mVcdFile, y_TUSER, "(port)y_TUSER"); sc_trace(mVcdFile, y_TLAST, "(port)y_TLAST"); sc_trace(mVcdFile, x_TDATA, "(port)x_TDATA"); sc_trace(mVcdFile, x_TVALID, "(port)x_TVALID"); sc_trace(mVcdFile, x_TREADY, "(port)x_TREADY"); sc_trace(mVcdFile, x_TUSER, "(port)x_TUSER"); sc_trace(mVcdFile, x_TLAST, "(port)x_TLAST"); sc_trace(mVcdFile, s_axi_AXILiteS_AWVALID, "(port)s_axi_AXILiteS_AWVALID"); sc_trace(mVcdFile, s_axi_AXILiteS_AWREADY, "(port)s_axi_AXILiteS_AWREADY"); sc_trace(mVcdFile, s_axi_AXILiteS_AWADDR, "(port)s_axi_AXILiteS_AWADDR"); sc_trace(mVcdFile, s_axi_AXILiteS_WVALID, "(port)s_axi_AXILiteS_WVALID"); sc_trace(mVcdFile, s_axi_AXILiteS_WREADY, "(port)s_axi_AXILiteS_WREADY"); sc_trace(mVcdFile, s_axi_AXILiteS_WDATA, "(port)s_axi_AXILiteS_WDATA"); sc_trace(mVcdFile, s_axi_AXILiteS_WSTRB, "(port)s_axi_AXILiteS_WSTRB"); sc_trace(mVcdFile, s_axi_AXILiteS_ARVALID, "(port)s_axi_AXILiteS_ARVALID"); sc_trace(mVcdFile, s_axi_AXILiteS_ARREADY, "(port)s_axi_AXILiteS_ARREADY"); sc_trace(mVcdFile, s_axi_AXILiteS_ARADDR, "(port)s_axi_AXILiteS_ARADDR"); sc_trace(mVcdFile, s_axi_AXILiteS_RVALID, "(port)s_axi_AXILiteS_RVALID"); sc_trace(mVcdFile, s_axi_AXILiteS_RREADY, "(port)s_axi_AXILiteS_RREADY"); sc_trace(mVcdFile, s_axi_AXILiteS_RDATA, "(port)s_axi_AXILiteS_RDATA"); sc_trace(mVcdFile, s_axi_AXILiteS_RRESP, "(port)s_axi_AXILiteS_RRESP"); sc_trace(mVcdFile, s_axi_AXILiteS_BVALID, "(port)s_axi_AXILiteS_BVALID"); sc_trace(mVcdFile, s_axi_AXILiteS_BREADY, "(port)s_axi_AXILiteS_BREADY"); sc_trace(mVcdFile, s_axi_AXILiteS_BRESP, "(port)s_axi_AXILiteS_BRESP"); sc_trace(mVcdFile, interrupt, "(port)interrupt"); #endif #ifdef __HLS_TRACE_LEVEL_INT__ sc_trace(mVcdFile, ap_rst_n_inv, "ap_rst_n_inv"); sc_trace(mVcdFile, ap_start, "ap_start"); sc_trace(mVcdFile, ap_done, "ap_done"); sc_trace(mVcdFile, ap_idle, "ap_idle"); sc_trace(mVcdFile, ap_CS_fsm, "ap_CS_fsm"); sc_trace(mVcdFile, ap_CS_fsm_state1, "ap_CS_fsm_state1"); sc_trace(mVcdFile, ap_ready, "ap_ready"); sc_trace(mVcdFile, y_data_1_data_out, "y_data_1_data_out"); sc_trace(mVcdFile, y_data_1_vld_in, "y_data_1_vld_in"); sc_trace(mVcdFile, y_data_1_vld_out, "y_data_1_vld_out"); sc_trace(mVcdFile, y_data_1_ack_in, "y_data_1_ack_in"); sc_trace(mVcdFile, y_data_1_ack_out, "y_data_1_ack_out"); sc_trace(mVcdFile, y_data_1_payload_A, "y_data_1_payload_A"); sc_trace(mVcdFile, y_data_1_payload_B, "y_data_1_payload_B"); sc_trace(mVcdFile, y_data_1_sel_rd, "y_data_1_sel_rd"); sc_trace(mVcdFile, y_data_1_sel_wr, "y_data_1_sel_wr"); sc_trace(mVcdFile, y_data_1_sel, "y_data_1_sel"); sc_trace(mVcdFile, y_data_1_load_A, "y_data_1_load_A"); sc_trace(mVcdFile, y_data_1_load_B, "y_data_1_load_B"); sc_trace(mVcdFile, y_data_1_state, "y_data_1_state"); sc_trace(mVcdFile, y_data_1_state_cmp_full, "y_data_1_state_cmp_full"); sc_trace(mVcdFile, y_user_V_1_data_out, "y_user_V_1_data_out"); sc_trace(mVcdFile, y_user_V_1_vld_in, "y_user_V_1_vld_in"); sc_trace(mVcdFile, y_user_V_1_vld_out, "y_user_V_1_vld_out"); sc_trace(mVcdFile, y_user_V_1_ack_in, "y_user_V_1_ack_in"); sc_trace(mVcdFile, y_user_V_1_ack_out, "y_user_V_1_ack_out"); sc_trace(mVcdFile, y_user_V_1_payload_A, "y_user_V_1_payload_A"); sc_trace(mVcdFile, y_user_V_1_payload_B, "y_user_V_1_payload_B"); sc_trace(mVcdFile, y_user_V_1_sel_rd, "y_user_V_1_sel_rd"); sc_trace(mVcdFile, y_user_V_1_sel_wr, "y_user_V_1_sel_wr"); sc_trace(mVcdFile, y_user_V_1_sel, "y_user_V_1_sel"); sc_trace(mVcdFile, y_user_V_1_load_A, "y_user_V_1_load_A"); sc_trace(mVcdFile, y_user_V_1_load_B, "y_user_V_1_load_B"); sc_trace(mVcdFile, y_user_V_1_state, "y_user_V_1_state"); sc_trace(mVcdFile, y_user_V_1_state_cmp_full, "y_user_V_1_state_cmp_full"); sc_trace(mVcdFile, y_last_V_1_data_out, "y_last_V_1_data_out"); sc_trace(mVcdFile, y_last_V_1_vld_in, "y_last_V_1_vld_in"); sc_trace(mVcdFile, y_last_V_1_vld_out, "y_last_V_1_vld_out"); sc_trace(mVcdFile, y_last_V_1_ack_in, "y_last_V_1_ack_in"); sc_trace(mVcdFile, y_last_V_1_ack_out, "y_last_V_1_ack_out"); sc_trace(mVcdFile, y_last_V_1_payload_A, "y_last_V_1_payload_A"); sc_trace(mVcdFile, y_last_V_1_payload_B, "y_last_V_1_payload_B"); sc_trace(mVcdFile, y_last_V_1_sel_rd, "y_last_V_1_sel_rd"); sc_trace(mVcdFile, y_last_V_1_sel_wr, "y_last_V_1_sel_wr"); sc_trace(mVcdFile, y_last_V_1_sel, "y_last_V_1_sel"); sc_trace(mVcdFile, y_last_V_1_load_A, "y_last_V_1_load_A"); sc_trace(mVcdFile, y_last_V_1_load_B, "y_last_V_1_load_B"); sc_trace(mVcdFile, y_last_V_1_state, "y_last_V_1_state"); sc_trace(mVcdFile, y_last_V_1_state_cmp_full, "y_last_V_1_state_cmp_full"); sc_trace(mVcdFile, x_data_0_data_out, "x_data_0_data_out"); sc_trace(mVcdFile, x_data_0_vld_in, "x_data_0_vld_in"); sc_trace(mVcdFile, x_data_0_vld_out, "x_data_0_vld_out"); sc_trace(mVcdFile, x_data_0_ack_in, "x_data_0_ack_in"); sc_trace(mVcdFile, x_data_0_ack_out, "x_data_0_ack_out"); sc_trace(mVcdFile, x_data_0_payload_A, "x_data_0_payload_A"); sc_trace(mVcdFile, x_data_0_payload_B, "x_data_0_payload_B"); sc_trace(mVcdFile, x_data_0_sel_rd, "x_data_0_sel_rd"); sc_trace(mVcdFile, x_data_0_sel_wr, "x_data_0_sel_wr"); sc_trace(mVcdFile, x_data_0_sel, "x_data_0_sel"); sc_trace(mVcdFile, x_data_0_load_A, "x_data_0_load_A"); sc_trace(mVcdFile, x_data_0_load_B, "x_data_0_load_B"); sc_trace(mVcdFile, x_data_0_state, "x_data_0_state"); sc_trace(mVcdFile, x_data_0_state_cmp_full, "x_data_0_state_cmp_full"); sc_trace(mVcdFile, x_user_V_0_data_out, "x_user_V_0_data_out"); sc_trace(mVcdFile, x_user_V_0_vld_in, "x_user_V_0_vld_in"); sc_trace(mVcdFile, x_user_V_0_vld_out, "x_user_V_0_vld_out"); sc_trace(mVcdFile, x_user_V_0_ack_in, "x_user_V_0_ack_in"); sc_trace(mVcdFile, x_user_V_0_ack_out, "x_user_V_0_ack_out"); sc_trace(mVcdFile, x_user_V_0_payload_A, "x_user_V_0_payload_A"); sc_trace(mVcdFile, x_user_V_0_payload_B, "x_user_V_0_payload_B"); sc_trace(mVcdFile, x_user_V_0_sel_rd, "x_user_V_0_sel_rd"); sc_trace(mVcdFile, x_user_V_0_sel_wr, "x_user_V_0_sel_wr"); sc_trace(mVcdFile, x_user_V_0_sel, "x_user_V_0_sel"); sc_trace(mVcdFile, x_user_V_0_load_A, "x_user_V_0_load_A"); sc_trace(mVcdFile, x_user_V_0_load_B, "x_user_V_0_load_B"); sc_trace(mVcdFile, x_user_V_0_state, "x_user_V_0_state"); sc_trace(mVcdFile, x_user_V_0_state_cmp_full, "x_user_V_0_state_cmp_full"); sc_trace(mVcdFile, x_last_V_0_data_out, "x_last_V_0_data_out"); sc_trace(mVcdFile, x_last_V_0_vld_in, "x_last_V_0_vld_in"); sc_trace(mVcdFile, x_last_V_0_vld_out, "x_last_V_0_vld_out"); sc_trace(mVcdFile, x_last_V_0_ack_in, "x_last_V_0_ack_in"); sc_trace(mVcdFile, x_last_V_0_ack_out, "x_last_V_0_ack_out"); sc_trace(mVcdFile, x_last_V_0_payload_A, "x_last_V_0_payload_A"); sc_trace(mVcdFile, x_last_V_0_payload_B, "x_last_V_0_payload_B"); sc_trace(mVcdFile, x_last_V_0_sel_rd, "x_last_V_0_sel_rd"); sc_trace(mVcdFile, x_last_V_0_sel_wr, "x_last_V_0_sel_wr"); sc_trace(mVcdFile, x_last_V_0_sel, "x_last_V_0_sel"); sc_trace(mVcdFile, x_last_V_0_load_A, "x_last_V_0_load_A"); sc_trace(mVcdFile, x_last_V_0_load_B, "x_last_V_0_load_B"); sc_trace(mVcdFile, x_last_V_0_state, "x_last_V_0_state"); sc_trace(mVcdFile, x_last_V_0_state_cmp_full, "x_last_V_0_state_cmp_full"); sc_trace(mVcdFile, coe, "coe"); sc_trace(mVcdFile, ctrl, "ctrl"); sc_trace(mVcdFile, coef_address0, "coef_address0"); sc_trace(mVcdFile, coef_ce0, "coef_ce0"); sc_trace(mVcdFile, coef_we0, "coef_we0"); sc_trace(mVcdFile, coef_q0, "coef_q0"); sc_trace(mVcdFile, shift_reg_address0, "shift_reg_address0"); sc_trace(mVcdFile, shift_reg_ce0, "shift_reg_ce0"); sc_trace(mVcdFile, shift_reg_we0, "shift_reg_we0"); sc_trace(mVcdFile, shift_reg_d0, "shift_reg_d0"); sc_trace(mVcdFile, shift_reg_q0, "shift_reg_q0"); sc_trace(mVcdFile, gmem_blk_n_AR, "gmem_blk_n_AR"); sc_trace(mVcdFile, ap_CS_fsm_state2, "ap_CS_fsm_state2"); sc_trace(mVcdFile, gmem_blk_n_R, "gmem_blk_n_R"); sc_trace(mVcdFile, ap_CS_fsm_pp0_stage0, "ap_CS_fsm_pp0_stage0"); sc_trace(mVcdFile, ap_enable_reg_pp0_iter1, "ap_enable_reg_pp0_iter1"); sc_trace(mVcdFile, ap_block_pp0_stage0, "ap_block_pp0_stage0"); sc_trace(mVcdFile, exitcond_reg_500, "exitcond_reg_500"); sc_trace(mVcdFile, ap_CS_fsm_state13, "ap_CS_fsm_state13"); sc_trace(mVcdFile, ap_CS_fsm_pp1_stage0, "ap_CS_fsm_pp1_stage0"); sc_trace(mVcdFile, ap_enable_reg_pp1_iter1, "ap_enable_reg_pp1_iter1"); sc_trace(mVcdFile, ap_block_pp1_stage0, "ap_block_pp1_stage0"); sc_trace(mVcdFile, exitcond1_reg_546, "exitcond1_reg_546"); sc_trace(mVcdFile, y_TDATA_blk_n, "y_TDATA_blk_n"); sc_trace(mVcdFile, ap_CS_fsm_state31, "ap_CS_fsm_state31"); sc_trace(mVcdFile, ap_CS_fsm_state32, "ap_CS_fsm_state32"); sc_trace(mVcdFile, x_TDATA_blk_n, "x_TDATA_blk_n"); sc_trace(mVcdFile, ap_CS_fsm_state30, "ap_CS_fsm_state30"); sc_trace(mVcdFile, gmem_AWREADY, "gmem_AWREADY"); sc_trace(mVcdFile, gmem_WREADY, "gmem_WREADY"); sc_trace(mVcdFile, gmem_ARVALID, "gmem_ARVALID"); sc_trace(mVcdFile, gmem_ARREADY, "gmem_ARREADY"); sc_trace(mVcdFile, gmem_ARADDR, "gmem_ARADDR"); sc_trace(mVcdFile, gmem_ARLEN, "gmem_ARLEN"); sc_trace(mVcdFile, gmem_RVALID, "gmem_RVALID"); sc_trace(mVcdFile, gmem_RREADY, "gmem_RREADY"); sc_trace(mVcdFile, gmem_RDATA, "gmem_RDATA"); sc_trace(mVcdFile, gmem_RLAST, "gmem_RLAST"); sc_trace(mVcdFile, gmem_RID, "gmem_RID"); sc_trace(mVcdFile, gmem_RUSER, "gmem_RUSER"); sc_trace(mVcdFile, gmem_RRESP, "gmem_RRESP"); sc_trace(mVcdFile, gmem_BVALID, "gmem_BVALID"); sc_trace(mVcdFile, gmem_BRESP, "gmem_BRESP"); sc_trace(mVcdFile, gmem_BID, "gmem_BID"); sc_trace(mVcdFile, gmem_BUSER, "gmem_BUSER"); sc_trace(mVcdFile, i_reg_233, "i_reg_233"); sc_trace(mVcdFile, reload_reg_245, "reload_reg_245"); sc_trace(mVcdFile, indvar_reg_257, "indvar_reg_257"); sc_trace(mVcdFile, indvar1_reg_268, "indvar1_reg_268"); sc_trace(mVcdFile, indvar1_reg_268_pp1_iter1_reg, "indvar1_reg_268_pp1_iter1_reg"); sc_trace(mVcdFile, ap_block_state20_pp1_stage0_iter0, "ap_block_state20_pp1_stage0_iter0"); sc_trace(mVcdFile, ap_block_state21_pp1_stage0_iter1, "ap_block_state21_pp1_stage0_iter1"); sc_trace(mVcdFile, ap_block_state22_pp1_stage0_iter2, "ap_block_state22_pp1_stage0_iter2"); sc_trace(mVcdFile, ap_block_pp1_stage0_11001, "ap_block_pp1_stage0_11001"); sc_trace(mVcdFile, i1_reg_280, "i1_reg_280"); sc_trace(mVcdFile, acc_reg_290, "acc_reg_290"); sc_trace(mVcdFile, reg_302, "reg_302"); sc_trace(mVcdFile, ap_CS_fsm_pp2_stage1, "ap_CS_fsm_pp2_stage1"); sc_trace(mVcdFile, ap_enable_reg_pp2_iter0, "ap_enable_reg_pp2_iter0"); sc_trace(mVcdFile, ap_block_state25_pp2_stage1_iter0, "ap_block_state25_pp2_stage1_iter0"); sc_trace(mVcdFile, ap_block_state27_pp2_stage1_iter1, "ap_block_state27_pp2_stage1_iter1"); sc_trace(mVcdFile, ap_block_pp2_stage1_11001, "ap_block_pp2_stage1_11001"); sc_trace(mVcdFile, tmp_2_reg_560, "tmp_2_reg_560"); sc_trace(mVcdFile, ap_CS_fsm_state29, "ap_CS_fsm_state29"); sc_trace(mVcdFile, ctrl3_reg_478, "ctrl3_reg_478"); sc_trace(mVcdFile, coe1_reg_483, "coe1_reg_483"); sc_trace(mVcdFile, ap_sig_ioackin_gmem_ARREADY, "ap_sig_ioackin_gmem_ARREADY"); sc_trace(mVcdFile, gmem_addr_1_reg_494, "gmem_addr_1_reg_494"); sc_trace(mVcdFile, ap_CS_fsm_state8, "ap_CS_fsm_state8"); sc_trace(mVcdFile, exitcond_fu_345_p2, "exitcond_fu_345_p2"); sc_trace(mVcdFile, ap_block_state9_pp0_stage0_iter0, "ap_block_state9_pp0_stage0_iter0"); sc_trace(mVcdFile, ap_block_state10_pp0_stage0_iter1, "ap_block_state10_pp0_stage0_iter1"); sc_trace(mVcdFile, ap_block_state11_pp0_stage0_iter2, "ap_block_state11_pp0_stage0_iter2"); sc_trace(mVcdFile, ap_block_pp0_stage0_11001, "ap_block_pp0_stage0_11001"); sc_trace(mVcdFile, exitcond_reg_500_pp0_iter1_reg, "exitcond_reg_500_pp0_iter1_reg"); sc_trace(mVcdFile, indvar_next_fu_351_p2, "indvar_next_fu_351_p2"); sc_trace(mVcdFile, ap_enable_reg_pp0_iter0, "ap_enable_reg_pp0_iter0"); sc_trace(mVcdFile, tmp_10_fu_357_p1, "tmp_10_fu_357_p1"); sc_trace(mVcdFile, tmp_10_reg_509, "tmp_10_reg_509"); sc_trace(mVcdFile, tmp_10_reg_509_pp0_iter1_reg, "tmp_10_reg_509_pp0_iter1_reg"); sc_trace(mVcdFile, fir_ctrl_0_reg_515, "fir_ctrl_0_reg_515"); sc_trace(mVcdFile, fir_ctrl_1_1_fu_361_p3, "fir_ctrl_1_1_fu_361_p3"); sc_trace(mVcdFile, ap_enable_reg_pp0_iter2, "ap_enable_reg_pp0_iter2"); sc_trace(mVcdFile, reload_1_fu_367_p3, "reload_1_fu_367_p3"); sc_trace(mVcdFile, tmp_fu_373_p2, "tmp_fu_373_p2"); sc_trace(mVcdFile, ap_CS_fsm_state12, "ap_CS_fsm_state12"); sc_trace(mVcdFile, p_add7_i32_shr_reg_535, "p_add7_i32_shr_reg_535"); sc_trace(mVcdFile, tmp_s_fu_401_p1, "tmp_s_fu_401_p1"); sc_trace(mVcdFile, exitcond1_fu_405_p2, "exitcond1_fu_405_p2"); sc_trace(mVcdFile, exitcond1_reg_546_pp1_iter1_reg, "exitcond1_reg_546_pp1_iter1_reg"); sc_trace(mVcdFile, indvar_next1_fu_410_p2, "indvar_next1_fu_410_p2"); sc_trace(mVcdFile, indvar_next1_reg_550, "indvar_next1_reg_550"); sc_trace(mVcdFile, ap_enable_reg_pp1_iter0, "ap_enable_reg_pp1_iter0"); sc_trace(mVcdFile, gmem_addr_1_read_reg_555, "gmem_addr_1_read_reg_555"); sc_trace(mVcdFile, tmp_2_fu_421_p2, "tmp_2_fu_421_p2"); sc_trace(mVcdFile, ap_CS_fsm_pp2_stage0, "ap_CS_fsm_pp2_stage0"); sc_trace(mVcdFile, ap_block_state24_pp2_stage0_iter0, "ap_block_state24_pp2_stage0_iter0"); sc_trace(mVcdFile, ap_block_state26_pp2_stage0_iter1, "ap_block_state26_pp2_stage0_iter1"); sc_trace(mVcdFile, ap_block_pp2_stage0_11001, "ap_block_pp2_stage0_11001"); sc_trace(mVcdFile, tmp_2_reg_560_pp2_iter1_reg, "tmp_2_reg_560_pp2_iter1_reg"); sc_trace(mVcdFile, i_1_fu_427_p2, "i_1_fu_427_p2"); sc_trace(mVcdFile, i_1_reg_564, "i_1_reg_564"); sc_trace(mVcdFile, tmp_7_fu_438_p1, "tmp_7_fu_438_p1"); sc_trace(mVcdFile, tmp_7_reg_574, "tmp_7_reg_574"); sc_trace(mVcdFile, shift_reg_load_reg_584, "shift_reg_load_reg_584"); sc_trace(mVcdFile, tmp_8_fu_443_p2, "tmp_8_fu_443_p2"); sc_trace(mVcdFile, tmp_8_reg_589, "tmp_8_reg_589"); sc_trace(mVcdFile, acc_2_fu_448_p2, "acc_2_fu_448_p2"); sc_trace(mVcdFile, ap_enable_reg_pp2_iter1, "ap_enable_reg_pp2_iter1"); sc_trace(mVcdFile, x_user_V_tmp_reg_599, "x_user_V_tmp_reg_599"); sc_trace(mVcdFile, x_last_V_tmp_reg_604, "x_last_V_tmp_reg_604"); sc_trace(mVcdFile, tmp_3_fu_466_p2, "tmp_3_fu_466_p2"); sc_trace(mVcdFile, tmp_3_reg_609, "tmp_3_reg_609"); sc_trace(mVcdFile, acc_1_fu_472_p2, "acc_1_fu_472_p2"); sc_trace(mVcdFile, ap_block_pp0_stage0_subdone, "ap_block_pp0_stage0_subdone"); sc_trace(mVcdFile, ap_condition_pp0_exit_iter0_state9, "ap_condition_pp0_exit_iter0_state9"); sc_trace(mVcdFile, ap_CS_fsm_state19, "ap_CS_fsm_state19"); sc_trace(mVcdFile, ap_block_pp1_stage0_subdone, "ap_block_pp1_stage0_subdone"); sc_trace(mVcdFile, ap_condition_pp1_exit_iter0_state20, "ap_condition_pp1_exit_iter0_state20"); sc_trace(mVcdFile, ap_enable_reg_pp1_iter2, "ap_enable_reg_pp1_iter2"); sc_trace(mVcdFile, ap_CS_fsm_state23, "ap_CS_fsm_state23"); sc_trace(mVcdFile, ap_block_pp2_stage0_subdone, "ap_block_pp2_stage0_subdone"); sc_trace(mVcdFile, ap_condition_pp2_exit_iter0_state24, "ap_condition_pp2_exit_iter0_state24"); sc_trace(mVcdFile, ap_block_pp2_stage1_subdone, "ap_block_pp2_stage1_subdone"); sc_trace(mVcdFile, ap_phi_mux_indvar1_phi_fu_272_p4, "ap_phi_mux_indvar1_phi_fu_272_p4"); sc_trace(mVcdFile, ap_phi_mux_i1_phi_fu_283_p4, "ap_phi_mux_i1_phi_fu_283_p4"); sc_trace(mVcdFile, ap_block_pp2_stage0, "ap_block_pp2_stage0"); sc_trace(mVcdFile, indvar2_fu_416_p1, "indvar2_fu_416_p1"); sc_trace(mVcdFile, tmp_6_fu_433_p1, "tmp_6_fu_433_p1"); sc_trace(mVcdFile, ap_block_pp2_stage1, "ap_block_pp2_stage1"); sc_trace(mVcdFile, tmp_5_fu_326_p1, "tmp_5_fu_326_p1"); sc_trace(mVcdFile, tmp_9_fu_336_p1, "tmp_9_fu_336_p1"); sc_trace(mVcdFile, ap_reg_ioackin_gmem_ARREADY, "ap_reg_ioackin_gmem_ARREADY"); sc_trace(mVcdFile, ap_CS_fsm_state28, "ap_CS_fsm_state28"); sc_trace(mVcdFile, tmp_12_fu_379_p2, "tmp_12_fu_379_p2"); sc_trace(mVcdFile, tmp_1_fu_385_p2, "tmp_1_fu_385_p2"); sc_trace(mVcdFile, tmp_3_fu_466_p1, "tmp_3_fu_466_p1"); sc_trace(mVcdFile, ap_block_state32, "ap_block_state32"); sc_trace(mVcdFile, ap_NS_fsm, "ap_NS_fsm"); sc_trace(mVcdFile, ap_idle_pp0, "ap_idle_pp0"); sc_trace(mVcdFile, ap_enable_pp0, "ap_enable_pp0"); sc_trace(mVcdFile, ap_idle_pp1, "ap_idle_pp1"); sc_trace(mVcdFile, ap_enable_pp1, "ap_enable_pp1"); sc_trace(mVcdFile, ap_idle_pp2, "ap_idle_pp2"); sc_trace(mVcdFile, ap_enable_pp2, "ap_enable_pp2"); #endif } mHdltvinHandle.open("x_order_fir.hdltvin.dat"); mHdltvoutHandle.open("x_order_fir.hdltvout.dat"); } x_order_fir::~x_order_fir() { if (mVcdFile) sc_close_vcd_trace_file(mVcdFile); mHdltvinHandle << "] " << endl; mHdltvoutHandle << "] " << endl; mHdltvinHandle.close(); mHdltvoutHandle.close(); delete coef_U; delete shift_reg_U; delete x_order_fir_AXILiteS_s_axi_U; delete x_order_fir_gmem_m_axi_U; } void x_order_fir::thread_ap_var_for_const0() { ap_var_for_const0 = ap_const_logic_1; } void x_order_fir::thread_ap_var_for_const5() { ap_var_for_const5 = ap_const_logic_0; } void x_order_fir::thread_ap_var_for_const6() { ap_var_for_const6 = ap_const_lv32_0; } void x_order_fir::thread_ap_var_for_const1() { ap_var_for_const1 = ap_const_lv1_0; } void x_order_fir::thread_ap_var_for_const3() { ap_var_for_const3 = ap_const_lv2_0; } void x_order_fir::thread_ap_var_for_const2() { ap_var_for_const2 = ap_const_lv3_0; } void x_order_fir::thread_ap_var_for_const4() { ap_var_for_const4 = ap_const_lv4_0; } void x_order_fir::thread_ap_clk_no_reset_() { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage1.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage1_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter1.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, tmp_2_reg_560_pp2_iter1_reg.read()))) { acc_reg_290 = acc_2_fu_448_p2.read(); } else if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state23.read())) { acc_reg_290 = ap_const_lv32_0; } if ( ap_rst_n_inv.read() == ap_const_logic_1) { ap_CS_fsm = ap_ST_fsm_state1; } else { ap_CS_fsm = ap_NS_fsm.read(); } if ( ap_rst_n_inv.read() == ap_const_logic_1) { ap_enable_reg_pp0_iter0 = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_condition_pp0_exit_iter0_state9.read()))) { ap_enable_reg_pp0_iter0 = ap_const_logic_0; } else if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state8.read())) { ap_enable_reg_pp0_iter0 = ap_const_logic_1; } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { ap_enable_reg_pp0_iter1 = ap_const_logic_0; } else { if (esl_seteq<1,1,1>(ap_block_pp0_stage0_subdone.read(), ap_const_boolean_0)) { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_condition_pp0_exit_iter0_state9.read())) { ap_enable_reg_pp0_iter1 = (ap_condition_pp0_exit_iter0_state9.read() ^ ap_const_logic_1); } else if (esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1)) { ap_enable_reg_pp0_iter1 = ap_enable_reg_pp0_iter0.read(); } } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { ap_enable_reg_pp0_iter2 = ap_const_logic_0; } else { if (esl_seteq<1,1,1>(ap_block_pp0_stage0_subdone.read(), ap_const_boolean_0)) { ap_enable_reg_pp0_iter2 = ap_enable_reg_pp0_iter1.read(); } else if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state8.read())) { ap_enable_reg_pp0_iter2 = ap_const_logic_0; } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { ap_enable_reg_pp1_iter0 = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp1_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp1_stage0_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_condition_pp1_exit_iter0_state20.read()))) { ap_enable_reg_pp1_iter0 = ap_const_logic_0; } else if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state19.read())) { ap_enable_reg_pp1_iter0 = ap_const_logic_1; } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { ap_enable_reg_pp1_iter1 = ap_const_logic_0; } else { if (esl_seteq<1,1,1>(ap_block_pp1_stage0_subdone.read(), ap_const_boolean_0)) { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_condition_pp1_exit_iter0_state20.read())) { ap_enable_reg_pp1_iter1 = (ap_condition_pp1_exit_iter0_state20.read() ^ ap_const_logic_1); } else if (esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1)) { ap_enable_reg_pp1_iter1 = ap_enable_reg_pp1_iter0.read(); } } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { ap_enable_reg_pp1_iter2 = ap_const_logic_0; } else { if (esl_seteq<1,1,1>(ap_block_pp1_stage0_subdone.read(), ap_const_boolean_0)) { ap_enable_reg_pp1_iter2 = ap_enable_reg_pp1_iter1.read(); } else if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state19.read())) { ap_enable_reg_pp1_iter2 = ap_const_logic_0; } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { ap_enable_reg_pp2_iter0 = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage0_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_condition_pp2_exit_iter0_state24.read()))) { ap_enable_reg_pp2_iter0 = ap_const_logic_0; } else if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state23.read())) { ap_enable_reg_pp2_iter0 = ap_const_logic_1; } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { ap_enable_reg_pp2_iter1 = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage1.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage1_subdone.read(), ap_const_boolean_0))) { ap_enable_reg_pp2_iter1 = ap_enable_reg_pp2_iter0.read(); } else if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state23.read())) { ap_enable_reg_pp2_iter1 = ap_const_logic_0; } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { ap_reg_ioackin_gmem_ARREADY = ap_const_logic_0; } else { if (((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read()) && esl_seteq<1,1,1>(ap_sig_ioackin_gmem_ARREADY.read(), ap_const_logic_1)) || (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state13.read()) && esl_seteq<1,1,1>(ap_sig_ioackin_gmem_ARREADY.read(), ap_const_logic_1)))) { ap_reg_ioackin_gmem_ARREADY = ap_const_logic_0; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read()) && esl_seteq<1,1,1>(ap_const_logic_1, gmem_ARREADY.read())) || (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state13.read()) && esl_seteq<1,1,1>(ap_const_logic_1, gmem_ARREADY.read())))) { ap_reg_ioackin_gmem_ARREADY = ap_const_logic_1; } } if ((esl_seteq<1,1,1>(ap_const_lv1_0, tmp_2_reg_560.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage0_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter1.read()))) { i1_reg_280 = i_1_reg_564.read(); } else if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state23.read())) { i1_reg_280 = i_reg_233.read(); } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp1_stage0.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter1.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_reg_546.read()) && esl_seteq<1,1,1>(ap_block_pp1_stage0_11001.read(), ap_const_boolean_0))) { indvar1_reg_268 = indvar_next1_reg_550.read(); } else if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state19.read())) { indvar1_reg_268 = ap_const_lv30_0; } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter0.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond_fu_345_p2.read()))) { indvar_reg_257 = indvar_next_fu_351_p2.read(); } else if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state8.read())) { indvar_reg_257 = ap_const_lv2_0; } if ( ap_rst_n_inv.read() == ap_const_logic_1) { x_data_0_sel_rd = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, x_data_0_ack_out.read()) && esl_seteq<1,1,1>(ap_const_logic_1, x_data_0_vld_out.read()))) { x_data_0_sel_rd = (sc_logic) (~x_data_0_sel_rd.read()); } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { x_data_0_sel_wr = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, x_data_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, x_data_0_ack_in.read()))) { x_data_0_sel_wr = (sc_logic) (~x_data_0_sel_wr.read()); } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { x_data_0_state = ap_const_lv2_0; } else { if (((esl_seteq<1,1,1>(ap_const_logic_0, x_data_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, x_data_0_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_3, x_data_0_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_0, x_data_0_vld_in.read()) && esl_seteq<1,2,2>(ap_const_lv2_2, x_data_0_state.read())))) { x_data_0_state = ap_const_lv2_2; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, x_data_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_0, x_data_0_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_3, x_data_0_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_0, x_data_0_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_1, x_data_0_state.read())))) { x_data_0_state = ap_const_lv2_1; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, x_data_0_vld_in.read()) && esl_seteq<1,2,2>(ap_const_lv2_2, x_data_0_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_1, x_data_0_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_1, x_data_0_state.read())) || (esl_seteq<1,2,2>(ap_const_lv2_3, x_data_0_state.read()) && !(esl_seteq<1,1,1>(ap_const_logic_1, x_data_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_0, x_data_0_ack_out.read())) && !(esl_seteq<1,1,1>(ap_const_logic_0, x_data_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, x_data_0_ack_out.read()))))) { x_data_0_state = ap_const_lv2_3; } else { x_data_0_state = ap_const_lv2_2; } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { x_last_V_0_sel_rd = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, x_last_V_0_ack_out.read()) && esl_seteq<1,1,1>(ap_const_logic_1, x_last_V_0_vld_out.read()))) { x_last_V_0_sel_rd = (sc_logic) (~x_last_V_0_sel_rd.read()); } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { x_last_V_0_sel_wr = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, x_last_V_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, x_last_V_0_ack_in.read()))) { x_last_V_0_sel_wr = (sc_logic) (~x_last_V_0_sel_wr.read()); } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { x_last_V_0_state = ap_const_lv2_0; } else { if (((esl_seteq<1,1,1>(ap_const_logic_0, x_last_V_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, x_last_V_0_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_3, x_last_V_0_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_0, x_last_V_0_vld_in.read()) && esl_seteq<1,2,2>(ap_const_lv2_2, x_last_V_0_state.read())))) { x_last_V_0_state = ap_const_lv2_2; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, x_last_V_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_0, x_last_V_0_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_3, x_last_V_0_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_0, x_last_V_0_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_1, x_last_V_0_state.read())))) { x_last_V_0_state = ap_const_lv2_1; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, x_last_V_0_vld_in.read()) && esl_seteq<1,2,2>(ap_const_lv2_2, x_last_V_0_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_1, x_last_V_0_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_1, x_last_V_0_state.read())) || (esl_seteq<1,2,2>(ap_const_lv2_3, x_last_V_0_state.read()) && !(esl_seteq<1,1,1>(ap_const_logic_1, x_last_V_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_0, x_last_V_0_ack_out.read())) && !(esl_seteq<1,1,1>(ap_const_logic_0, x_last_V_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, x_last_V_0_ack_out.read()))))) { x_last_V_0_state = ap_const_lv2_3; } else { x_last_V_0_state = ap_const_lv2_2; } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { x_user_V_0_sel_rd = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, x_user_V_0_ack_out.read()) && esl_seteq<1,1,1>(ap_const_logic_1, x_user_V_0_vld_out.read()))) { x_user_V_0_sel_rd = (sc_logic) (~x_user_V_0_sel_rd.read()); } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { x_user_V_0_sel_wr = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, x_user_V_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, x_user_V_0_ack_in.read()))) { x_user_V_0_sel_wr = (sc_logic) (~x_user_V_0_sel_wr.read()); } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { x_user_V_0_state = ap_const_lv2_0; } else { if (((esl_seteq<1,1,1>(ap_const_logic_0, x_user_V_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, x_user_V_0_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_3, x_user_V_0_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_0, x_user_V_0_vld_in.read()) && esl_seteq<1,2,2>(ap_const_lv2_2, x_user_V_0_state.read())))) { x_user_V_0_state = ap_const_lv2_2; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, x_user_V_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_0, x_user_V_0_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_3, x_user_V_0_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_0, x_user_V_0_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_1, x_user_V_0_state.read())))) { x_user_V_0_state = ap_const_lv2_1; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, x_user_V_0_vld_in.read()) && esl_seteq<1,2,2>(ap_const_lv2_2, x_user_V_0_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_1, x_user_V_0_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_1, x_user_V_0_state.read())) || (esl_seteq<1,2,2>(ap_const_lv2_3, x_user_V_0_state.read()) && !(esl_seteq<1,1,1>(ap_const_logic_1, x_user_V_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_0, x_user_V_0_ack_out.read())) && !(esl_seteq<1,1,1>(ap_const_logic_0, x_user_V_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, x_user_V_0_ack_out.read()))))) { x_user_V_0_state = ap_const_lv2_3; } else { x_user_V_0_state = ap_const_lv2_2; } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { y_data_1_sel_rd = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, y_data_1_ack_out.read()) && esl_seteq<1,1,1>(ap_const_logic_1, y_data_1_vld_out.read()))) { y_data_1_sel_rd = (sc_logic) (~y_data_1_sel_rd.read()); } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { y_data_1_sel_wr = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, y_data_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, y_data_1_ack_in.read()))) { y_data_1_sel_wr = (sc_logic) (~y_data_1_sel_wr.read()); } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { y_data_1_state = ap_const_lv2_0; } else { if (((esl_seteq<1,1,1>(ap_const_logic_0, y_data_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, y_data_1_ack_out.read()) && esl_seteq<1,2,2>(y_data_1_state.read(), ap_const_lv2_3)) || (esl_seteq<1,1,1>(ap_const_logic_0, y_data_1_vld_in.read()) && esl_seteq<1,2,2>(y_data_1_state.read(), ap_const_lv2_2)))) { y_data_1_state = ap_const_lv2_2; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, y_data_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_0, y_data_1_ack_out.read()) && esl_seteq<1,2,2>(y_data_1_state.read(), ap_const_lv2_3)) || (esl_seteq<1,1,1>(ap_const_logic_0, y_data_1_ack_out.read()) && esl_seteq<1,2,2>(y_data_1_state.read(), ap_const_lv2_1)))) { y_data_1_state = ap_const_lv2_1; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, y_data_1_vld_in.read()) && esl_seteq<1,2,2>(y_data_1_state.read(), ap_const_lv2_2)) || (esl_seteq<1,1,1>(ap_const_logic_1, y_data_1_ack_out.read()) && esl_seteq<1,2,2>(y_data_1_state.read(), ap_const_lv2_1)) || (esl_seteq<1,2,2>(y_data_1_state.read(), ap_const_lv2_3) && !(esl_seteq<1,1,1>(ap_const_logic_1, y_data_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_0, y_data_1_ack_out.read())) && !(esl_seteq<1,1,1>(ap_const_logic_0, y_data_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, y_data_1_ack_out.read()))))) { y_data_1_state = ap_const_lv2_3; } else { y_data_1_state = ap_const_lv2_2; } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { y_last_V_1_sel_rd = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, y_last_V_1_ack_out.read()) && esl_seteq<1,1,1>(ap_const_logic_1, y_last_V_1_vld_out.read()))) { y_last_V_1_sel_rd = (sc_logic) (~y_last_V_1_sel_rd.read()); } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { y_last_V_1_sel_wr = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, y_last_V_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, y_last_V_1_ack_in.read()))) { y_last_V_1_sel_wr = (sc_logic) (~y_last_V_1_sel_wr.read()); } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { y_last_V_1_state = ap_const_lv2_0; } else { if (((esl_seteq<1,1,1>(ap_const_logic_0, y_last_V_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, y_last_V_1_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_3, y_last_V_1_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_0, y_last_V_1_vld_in.read()) && esl_seteq<1,2,2>(ap_const_lv2_2, y_last_V_1_state.read())))) { y_last_V_1_state = ap_const_lv2_2; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, y_last_V_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_0, y_last_V_1_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_3, y_last_V_1_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_0, y_last_V_1_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_1, y_last_V_1_state.read())))) { y_last_V_1_state = ap_const_lv2_1; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, y_last_V_1_vld_in.read()) && esl_seteq<1,2,2>(ap_const_lv2_2, y_last_V_1_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_1, y_last_V_1_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_1, y_last_V_1_state.read())) || (esl_seteq<1,2,2>(ap_const_lv2_3, y_last_V_1_state.read()) && !(esl_seteq<1,1,1>(ap_const_logic_1, y_last_V_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_0, y_last_V_1_ack_out.read())) && !(esl_seteq<1,1,1>(ap_const_logic_0, y_last_V_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, y_last_V_1_ack_out.read()))))) { y_last_V_1_state = ap_const_lv2_3; } else { y_last_V_1_state = ap_const_lv2_2; } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { y_user_V_1_sel_rd = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, y_user_V_1_ack_out.read()) && esl_seteq<1,1,1>(ap_const_logic_1, y_user_V_1_vld_out.read()))) { y_user_V_1_sel_rd = (sc_logic) (~y_user_V_1_sel_rd.read()); } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { y_user_V_1_sel_wr = ap_const_logic_0; } else { if ((esl_seteq<1,1,1>(ap_const_logic_1, y_user_V_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, y_user_V_1_ack_in.read()))) { y_user_V_1_sel_wr = (sc_logic) (~y_user_V_1_sel_wr.read()); } } if ( ap_rst_n_inv.read() == ap_const_logic_1) { y_user_V_1_state = ap_const_lv2_0; } else { if (((esl_seteq<1,1,1>(ap_const_logic_0, y_user_V_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, y_user_V_1_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_3, y_user_V_1_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_0, y_user_V_1_vld_in.read()) && esl_seteq<1,2,2>(ap_const_lv2_2, y_user_V_1_state.read())))) { y_user_V_1_state = ap_const_lv2_2; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, y_user_V_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_0, y_user_V_1_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_3, y_user_V_1_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_0, y_user_V_1_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_1, y_user_V_1_state.read())))) { y_user_V_1_state = ap_const_lv2_1; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, y_user_V_1_vld_in.read()) && esl_seteq<1,2,2>(ap_const_lv2_2, y_user_V_1_state.read())) || (esl_seteq<1,1,1>(ap_const_logic_1, y_user_V_1_ack_out.read()) && esl_seteq<1,2,2>(ap_const_lv2_1, y_user_V_1_state.read())) || (esl_seteq<1,2,2>(ap_const_lv2_3, y_user_V_1_state.read()) && !(esl_seteq<1,1,1>(ap_const_logic_1, y_user_V_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_0, y_user_V_1_ack_out.read())) && !(esl_seteq<1,1,1>(ap_const_logic_0, y_user_V_1_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, y_user_V_1_ack_out.read()))))) { y_user_V_1_state = ap_const_lv2_3; } else { y_user_V_1_state = ap_const_lv2_2; } } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state1.read()) && esl_seteq<1,1,1>(ap_start.read(), ap_const_logic_1))) { coe1_reg_483 = coe.read().range(31, 2); ctrl3_reg_478 = ctrl.read().range(31, 2); } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp1_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp1_stage0_11001.read(), ap_const_boolean_0))) { exitcond1_reg_546 = exitcond1_fu_405_p2.read(); exitcond1_reg_546_pp1_iter1_reg = exitcond1_reg_546.read(); indvar1_reg_268_pp1_iter1_reg = indvar1_reg_268.read(); } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0_11001.read(), ap_const_boolean_0))) { exitcond_reg_500 = exitcond_fu_345_p2.read(); exitcond_reg_500_pp0_iter1_reg = exitcond_reg_500.read(); tmp_10_reg_509_pp0_iter1_reg = tmp_10_reg_509.read(); } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond_reg_500.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0_11001.read(), ap_const_boolean_0))) { fir_ctrl_0_reg_515 = gmem_RDATA.read(); } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp1_stage0.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_reg_546.read()) && esl_seteq<1,1,1>(ap_block_pp1_stage0_11001.read(), ap_const_boolean_0))) { gmem_addr_1_read_reg_555 = gmem_RDATA.read(); } if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state8.read())) { gmem_addr_1_reg_494 = (sc_lv<32>) (tmp_9_fu_336_p1.read()); } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage0_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_0, tmp_2_fu_421_p2.read()))) { i_1_reg_564 = i_1_fu_427_p2.read(); } if ((esl_seteq<1,1,1>(ap_block_pp0_stage0_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter2.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond_reg_500_pp0_iter1_reg.read()))) { i_reg_233 = fir_ctrl_1_1_fu_361_p3.read(); reload_reg_245 = reload_1_fu_367_p3.read(); } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp1_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp1_stage0_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter0.read()))) { indvar_next1_reg_550 = indvar_next1_fu_410_p2.read(); } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state12.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, tmp_fu_373_p2.read()))) { p_add7_i32_shr_reg_535 = tmp_1_fu_385_p2.read().range(31, 2); } if (((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage1.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage1_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_0, tmp_2_reg_560.read())) || esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state29.read()))) { reg_302 = coef_q0.read(); } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage1.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage1_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_0, tmp_2_reg_560.read()))) { shift_reg_load_reg_584 = shift_reg_q0.read(); } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond_fu_345_p2.read()))) { tmp_10_reg_509 = tmp_10_fu_357_p1.read(); } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage0_11001.read(), ap_const_boolean_0))) { tmp_2_reg_560 = tmp_2_fu_421_p2.read(); tmp_2_reg_560_pp2_iter1_reg = tmp_2_reg_560.read(); } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state30.read()) && esl_seteq<1,1,1>(x_data_0_vld_out.read(), ap_const_logic_1))) { tmp_3_reg_609 = tmp_3_fu_466_p2.read(); x_last_V_tmp_reg_604 = x_last_V_0_data_out.read(); x_user_V_tmp_reg_599 = x_user_V_0_data_out.read(); } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage0_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_0, tmp_2_fu_421_p2.read()))) { tmp_7_reg_574 = tmp_7_fu_438_p1.read(); } if ((esl_seteq<1,1,1>(ap_const_lv1_0, tmp_2_reg_560.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage0_11001.read(), ap_const_boolean_0))) { tmp_8_reg_589 = tmp_8_fu_443_p2.read(); } if (esl_seteq<1,1,1>(ap_const_logic_1, x_data_0_load_A.read())) { x_data_0_payload_A = x_TDATA.read(); } if (esl_seteq<1,1,1>(ap_const_logic_1, x_data_0_load_B.read())) { x_data_0_payload_B = x_TDATA.read(); } if (esl_seteq<1,1,1>(ap_const_logic_1, x_last_V_0_load_A.read())) { x_last_V_0_payload_A = x_TLAST.read(); } if (esl_seteq<1,1,1>(ap_const_logic_1, x_last_V_0_load_B.read())) { x_last_V_0_payload_B = x_TLAST.read(); } if (esl_seteq<1,1,1>(ap_const_logic_1, x_user_V_0_load_A.read())) { x_user_V_0_payload_A = x_TUSER.read(); } if (esl_seteq<1,1,1>(ap_const_logic_1, x_user_V_0_load_B.read())) { x_user_V_0_payload_B = x_TUSER.read(); } if (esl_seteq<1,1,1>(ap_const_logic_1, y_data_1_load_A.read())) { y_data_1_payload_A = acc_1_fu_472_p2.read(); } if (esl_seteq<1,1,1>(ap_const_logic_1, y_data_1_load_B.read())) { y_data_1_payload_B = acc_1_fu_472_p2.read(); } if (esl_seteq<1,1,1>(ap_const_logic_1, y_last_V_1_load_A.read())) { y_last_V_1_payload_A = x_last_V_tmp_reg_604.read(); } if (esl_seteq<1,1,1>(ap_const_logic_1, y_last_V_1_load_B.read())) { y_last_V_1_payload_B = x_last_V_tmp_reg_604.read(); } if (esl_seteq<1,1,1>(ap_const_logic_1, y_user_V_1_load_A.read())) { y_user_V_1_payload_A = x_user_V_tmp_reg_599.read(); } if (esl_seteq<1,1,1>(ap_const_logic_1, y_user_V_1_load_B.read())) { y_user_V_1_payload_B = x_user_V_tmp_reg_599.read(); } } void x_order_fir::thread_acc_1_fu_472_p2() { acc_1_fu_472_p2 = (!tmp_3_reg_609.read().is_01() || !acc_reg_290.read().is_01())? sc_lv<32>(): (sc_biguint<32>(tmp_3_reg_609.read()) + sc_biguint<32>(acc_reg_290.read())); } void x_order_fir::thread_acc_2_fu_448_p2() { acc_2_fu_448_p2 = (!tmp_8_reg_589.read().is_01() || !acc_reg_290.read().is_01())? sc_lv<32>(): (sc_biguint<32>(tmp_8_reg_589.read()) + sc_biguint<32>(acc_reg_290.read())); } void x_order_fir::thread_ap_CS_fsm_pp0_stage0() { ap_CS_fsm_pp0_stage0 = ap_CS_fsm.read()[8]; } void x_order_fir::thread_ap_CS_fsm_pp1_stage0() { ap_CS_fsm_pp1_stage0 = ap_CS_fsm.read()[17]; } void x_order_fir::thread_ap_CS_fsm_pp2_stage0() { ap_CS_fsm_pp2_stage0 = ap_CS_fsm.read()[19]; } void x_order_fir::thread_ap_CS_fsm_pp2_stage1() { ap_CS_fsm_pp2_stage1 = ap_CS_fsm.read()[20]; } void x_order_fir::thread_ap_CS_fsm_state1() { ap_CS_fsm_state1 = ap_CS_fsm.read()[0]; } void x_order_fir::thread_ap_CS_fsm_state12() { ap_CS_fsm_state12 = ap_CS_fsm.read()[9]; } void x_order_fir::thread_ap_CS_fsm_state13() { ap_CS_fsm_state13 = ap_CS_fsm.read()[10]; } void x_order_fir::thread_ap_CS_fsm_state19() { ap_CS_fsm_state19 = ap_CS_fsm.read()[16]; } void x_order_fir::thread_ap_CS_fsm_state2() { ap_CS_fsm_state2 = ap_CS_fsm.read()[1]; } void x_order_fir::thread_ap_CS_fsm_state23() { ap_CS_fsm_state23 = ap_CS_fsm.read()[18]; } void x_order_fir::thread_ap_CS_fsm_state28() { ap_CS_fsm_state28 = ap_CS_fsm.read()[21]; } void x_order_fir::thread_ap_CS_fsm_state29() { ap_CS_fsm_state29 = ap_CS_fsm.read()[22]; } void x_order_fir::thread_ap_CS_fsm_state30() { ap_CS_fsm_state30 = ap_CS_fsm.read()[23]; } void x_order_fir::thread_ap_CS_fsm_state31() { ap_CS_fsm_state31 = ap_CS_fsm.read()[24]; } void x_order_fir::thread_ap_CS_fsm_state32() { ap_CS_fsm_state32 = ap_CS_fsm.read()[25]; } void x_order_fir::thread_ap_CS_fsm_state8() { ap_CS_fsm_state8 = ap_CS_fsm.read()[7]; } void x_order_fir::thread_ap_block_pp0_stage0() { ap_block_pp0_stage0 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_pp0_stage0_11001() { ap_block_pp0_stage0_11001 = (esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter1.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond_reg_500.read()) && esl_seteq<1,1,1>(ap_const_logic_0, gmem_RVALID.read())); } void x_order_fir::thread_ap_block_pp0_stage0_subdone() { ap_block_pp0_stage0_subdone = (esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter1.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond_reg_500.read()) && esl_seteq<1,1,1>(ap_const_logic_0, gmem_RVALID.read())); } void x_order_fir::thread_ap_block_pp1_stage0() { ap_block_pp1_stage0 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_pp1_stage0_11001() { ap_block_pp1_stage0_11001 = (esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter1.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_reg_546.read()) && esl_seteq<1,1,1>(ap_const_logic_0, gmem_RVALID.read())); } void x_order_fir::thread_ap_block_pp1_stage0_subdone() { ap_block_pp1_stage0_subdone = (esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter1.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_reg_546.read()) && esl_seteq<1,1,1>(ap_const_logic_0, gmem_RVALID.read())); } void x_order_fir::thread_ap_block_pp2_stage0() { ap_block_pp2_stage0 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_pp2_stage0_11001() { ap_block_pp2_stage0_11001 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_pp2_stage0_subdone() { ap_block_pp2_stage0_subdone = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_pp2_stage1() { ap_block_pp2_stage1 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_pp2_stage1_11001() { ap_block_pp2_stage1_11001 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_pp2_stage1_subdone() { ap_block_pp2_stage1_subdone = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_state10_pp0_stage0_iter1() { ap_block_state10_pp0_stage0_iter1 = (esl_seteq<1,1,1>(ap_const_lv1_0, exitcond_reg_500.read()) && esl_seteq<1,1,1>(ap_const_logic_0, gmem_RVALID.read())); } void x_order_fir::thread_ap_block_state11_pp0_stage0_iter2() { ap_block_state11_pp0_stage0_iter2 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_state20_pp1_stage0_iter0() { ap_block_state20_pp1_stage0_iter0 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_state21_pp1_stage0_iter1() { ap_block_state21_pp1_stage0_iter1 = (esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_reg_546.read()) && esl_seteq<1,1,1>(ap_const_logic_0, gmem_RVALID.read())); } void x_order_fir::thread_ap_block_state22_pp1_stage0_iter2() { ap_block_state22_pp1_stage0_iter2 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_state24_pp2_stage0_iter0() { ap_block_state24_pp2_stage0_iter0 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_state25_pp2_stage1_iter0() { ap_block_state25_pp2_stage1_iter0 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_state26_pp2_stage0_iter1() { ap_block_state26_pp2_stage0_iter1 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_state27_pp2_stage1_iter1() { ap_block_state27_pp2_stage1_iter1 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_block_state32() { ap_block_state32 = (esl_seteq<1,1,1>(ap_const_logic_0, y_data_1_ack_in.read()) || esl_seteq<1,1,1>(ap_const_logic_0, y_user_V_1_ack_in.read()) || esl_seteq<1,1,1>(ap_const_logic_0, y_last_V_1_ack_in.read())); } void x_order_fir::thread_ap_block_state9_pp0_stage0_iter0() { ap_block_state9_pp0_stage0_iter0 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1); } void x_order_fir::thread_ap_condition_pp0_exit_iter0_state9() { if (esl_seteq<1,1,1>(ap_const_lv1_1, exitcond_fu_345_p2.read())) { ap_condition_pp0_exit_iter0_state9 = ap_const_logic_1; } else { ap_condition_pp0_exit_iter0_state9 = ap_const_logic_0; } } void x_order_fir::thread_ap_condition_pp1_exit_iter0_state20() { if (esl_seteq<1,1,1>(ap_const_lv1_1, exitcond1_fu_405_p2.read())) { ap_condition_pp1_exit_iter0_state20 = ap_const_logic_1; } else { ap_condition_pp1_exit_iter0_state20 = ap_const_logic_0; } } void x_order_fir::thread_ap_condition_pp2_exit_iter0_state24() { if (esl_seteq<1,1,1>(ap_const_lv1_1, tmp_2_fu_421_p2.read())) { ap_condition_pp2_exit_iter0_state24 = ap_const_logic_1; } else { ap_condition_pp2_exit_iter0_state24 = ap_const_logic_0; } } void x_order_fir::thread_ap_done() { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state32.read()) && esl_seteq<1,1,1>(ap_const_logic_0, y_data_1_state.read()[0]) && esl_seteq<1,1,1>(ap_const_logic_0, y_user_V_1_state.read()[0]) && esl_seteq<1,1,1>(ap_const_logic_0, y_last_V_1_state.read()[0]) && !(esl_seteq<1,1,1>(ap_const_logic_0, y_data_1_ack_in.read()) || esl_seteq<1,1,1>(ap_const_logic_0, y_user_V_1_ack_in.read()) || esl_seteq<1,1,1>(ap_const_logic_0, y_last_V_1_ack_in.read())))) { ap_done = ap_const_logic_1; } else { ap_done = ap_const_logic_0; } } void x_order_fir::thread_ap_enable_pp0() { ap_enable_pp0 = (ap_idle_pp0.read() ^ ap_const_logic_1); } void x_order_fir::thread_ap_enable_pp1() { ap_enable_pp1 = (ap_idle_pp1.read() ^ ap_const_logic_1); } void x_order_fir::thread_ap_enable_pp2() { ap_enable_pp2 = (ap_idle_pp2.read() ^ ap_const_logic_1); } void x_order_fir::thread_ap_idle() { if ((esl_seteq<1,1,1>(ap_const_logic_0, ap_start.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state1.read()))) { ap_idle = ap_const_logic_1; } else { ap_idle = ap_const_logic_0; } } void x_order_fir::thread_ap_idle_pp0() { if ((esl_seteq<1,1,1>(ap_const_logic_0, ap_enable_reg_pp0_iter0.read()) && esl_seteq<1,1,1>(ap_const_logic_0, ap_enable_reg_pp0_iter1.read()) && esl_seteq<1,1,1>(ap_const_logic_0, ap_enable_reg_pp0_iter2.read()))) { ap_idle_pp0 = ap_const_logic_1; } else { ap_idle_pp0 = ap_const_logic_0; } } void x_order_fir::thread_ap_idle_pp1() { if ((esl_seteq<1,1,1>(ap_const_logic_0, ap_enable_reg_pp1_iter0.read()) && esl_seteq<1,1,1>(ap_const_logic_0, ap_enable_reg_pp1_iter1.read()) && esl_seteq<1,1,1>(ap_const_logic_0, ap_enable_reg_pp1_iter2.read()))) { ap_idle_pp1 = ap_const_logic_1; } else { ap_idle_pp1 = ap_const_logic_0; } } void x_order_fir::thread_ap_idle_pp2() { if ((esl_seteq<1,1,1>(ap_const_logic_0, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_const_logic_0, ap_enable_reg_pp2_iter1.read()))) { ap_idle_pp2 = ap_const_logic_1; } else { ap_idle_pp2 = ap_const_logic_0; } } void x_order_fir::thread_ap_phi_mux_i1_phi_fu_283_p4() { if ((esl_seteq<1,1,1>(ap_const_lv1_0, tmp_2_reg_560.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage0.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter1.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage0.read(), ap_const_boolean_0))) { ap_phi_mux_i1_phi_fu_283_p4 = i_1_reg_564.read(); } else { ap_phi_mux_i1_phi_fu_283_p4 = i1_reg_280.read(); } } void x_order_fir::thread_ap_phi_mux_indvar1_phi_fu_272_p4() { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp1_stage0.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter1.read()) && esl_seteq<1,1,1>(ap_block_pp1_stage0.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_reg_546.read()))) { ap_phi_mux_indvar1_phi_fu_272_p4 = indvar_next1_reg_550.read(); } else { ap_phi_mux_indvar1_phi_fu_272_p4 = indvar1_reg_268.read(); } } void x_order_fir::thread_ap_ready() { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state32.read()) && esl_seteq<1,1,1>(ap_const_logic_0, y_data_1_state.read()[0]) && esl_seteq<1,1,1>(ap_const_logic_0, y_user_V_1_state.read()[0]) && esl_seteq<1,1,1>(ap_const_logic_0, y_last_V_1_state.read()[0]) && !(esl_seteq<1,1,1>(ap_const_logic_0, y_data_1_ack_in.read()) || esl_seteq<1,1,1>(ap_const_logic_0, y_user_V_1_ack_in.read()) || esl_seteq<1,1,1>(ap_const_logic_0, y_last_V_1_ack_in.read())))) { ap_ready = ap_const_logic_1; } else { ap_ready = ap_const_logic_0; } } void x_order_fir::thread_ap_rst_n_inv() { ap_rst_n_inv = (sc_logic) (~ap_rst_n.read()); } void x_order_fir::thread_ap_sig_ioackin_gmem_ARREADY() { if (esl_seteq<1,1,1>(ap_const_logic_0, ap_reg_ioackin_gmem_ARREADY.read())) { ap_sig_ioackin_gmem_ARREADY = gmem_ARREADY.read(); } else { ap_sig_ioackin_gmem_ARREADY = ap_const_logic_1; } } void x_order_fir::thread_coef_address0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state28.read())) { coef_address0 = ap_const_lv10_0; } else if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage0.read(), ap_const_boolean_0))) { coef_address0 = (sc_lv<10>) (tmp_7_fu_438_p1.read()); } else if ((esl_seteq<1,1,1>(ap_block_pp1_stage0.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter2.read()))) { coef_address0 = (sc_lv<10>) (indvar2_fu_416_p1.read()); } else { coef_address0 = "XXXXXXXXXX"; } } void x_order_fir::thread_coef_ce0() { if (((esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage0_11001.read(), ap_const_boolean_0)) || (esl_seteq<1,1,1>(ap_block_pp1_stage0_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter2.read())) || esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state28.read()))) { coef_ce0 = ap_const_logic_1; } else { coef_ce0 = ap_const_logic_0; } } void x_order_fir::thread_coef_we0() { if ((esl_seteq<1,1,1>(ap_block_pp1_stage0_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter2.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_reg_546_pp1_iter1_reg.read()))) { coef_we0 = ap_const_logic_1; } else { coef_we0 = ap_const_logic_0; } } void x_order_fir::thread_exitcond1_fu_405_p2() { exitcond1_fu_405_p2 = (!ap_phi_mux_indvar1_phi_fu_272_p4.read().is_01() || !p_add7_i32_shr_reg_535.read().is_01())? sc_lv<1>(): sc_lv<1>(ap_phi_mux_indvar1_phi_fu_272_p4.read() == p_add7_i32_shr_reg_535.read()); } void x_order_fir::thread_exitcond_fu_345_p2() { exitcond_fu_345_p2 = (!indvar_reg_257.read().is_01() || !ap_const_lv2_2.is_01())? sc_lv<1>(): sc_lv<1>(indvar_reg_257.read() == ap_const_lv2_2); } void x_order_fir::thread_fir_ctrl_1_1_fu_361_p3() { fir_ctrl_1_1_fu_361_p3 = (!tmp_10_reg_509_pp0_iter1_reg.read()[0].is_01())? sc_lv<32>(): ((tmp_10_reg_509_pp0_iter1_reg.read()[0].to_bool())? fir_ctrl_0_reg_515.read(): i_reg_233.read()); } void x_order_fir::thread_gmem_ARADDR() { if (esl_seteq<1,1,1>(ap_const_logic_0, ap_reg_ioackin_gmem_ARREADY.read())) { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state13.read())) { gmem_ARADDR = gmem_addr_1_reg_494.read(); } else if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read())) { gmem_ARADDR = (sc_lv<32>) (tmp_5_fu_326_p1.read()); } else { gmem_ARADDR = (sc_lv<32>) ("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); } } else { gmem_ARADDR = (sc_lv<32>) ("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); } } void x_order_fir::thread_gmem_ARLEN() { if (esl_seteq<1,1,1>(ap_const_logic_0, ap_reg_ioackin_gmem_ARREADY.read())) { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state13.read())) { gmem_ARLEN = tmp_s_fu_401_p1.read(); } else if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read())) { gmem_ARLEN = ap_const_lv32_2; } else { gmem_ARLEN = (sc_lv<32>) ("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); } } else { gmem_ARLEN = (sc_lv<32>) ("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); } } void x_order_fir::thread_gmem_ARVALID() { if (((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read()) && esl_seteq<1,1,1>(ap_const_logic_0, ap_reg_ioackin_gmem_ARREADY.read())) || (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state13.read()) && esl_seteq<1,1,1>(ap_const_logic_0, ap_reg_ioackin_gmem_ARREADY.read())))) { gmem_ARVALID = ap_const_logic_1; } else { gmem_ARVALID = ap_const_logic_0; } } void x_order_fir::thread_gmem_RREADY() { if (((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp1_stage0.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter1.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_reg_546.read()) && esl_seteq<1,1,1>(ap_block_pp1_stage0_11001.read(), ap_const_boolean_0)) || (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter1.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond_reg_500.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0_11001.read(), ap_const_boolean_0)))) { gmem_RREADY = ap_const_logic_1; } else { gmem_RREADY = ap_const_logic_0; } } void x_order_fir::thread_gmem_blk_n_AR() { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read()) || esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state13.read()))) { gmem_blk_n_AR = m_axi_gmem_ARREADY.read(); } else { gmem_blk_n_AR = ap_const_logic_1; } } void x_order_fir::thread_gmem_blk_n_R() { if (((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter1.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond_reg_500.read())) || (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp1_stage0.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter1.read()) && esl_seteq<1,1,1>(ap_block_pp1_stage0.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_reg_546.read())))) { gmem_blk_n_R = m_axi_gmem_RVALID.read(); } else { gmem_blk_n_R = ap_const_logic_1; } } void x_order_fir::thread_i_1_fu_427_p2() { i_1_fu_427_p2 = (!ap_phi_mux_i1_phi_fu_283_p4.read().is_01() || !ap_const_lv32_FFFFFFFF.is_01())? sc_lv<32>(): (sc_bigint<32>(ap_phi_mux_i1_phi_fu_283_p4.read()) + sc_bigint<32>(ap_const_lv32_FFFFFFFF)); } void x_order_fir::thread_indvar2_fu_416_p1() { indvar2_fu_416_p1 = esl_zext<64,30>(indvar1_reg_268_pp1_iter1_reg.read()); } void x_order_fir::thread_indvar_next1_fu_410_p2() { indvar_next1_fu_410_p2 = (!ap_phi_mux_indvar1_phi_fu_272_p4.read().is_01() || !ap_const_lv30_1.is_01())? sc_lv<30>(): (sc_biguint<30>(ap_phi_mux_indvar1_phi_fu_272_p4.read()) + sc_biguint<30>(ap_const_lv30_1)); } void x_order_fir::thread_indvar_next_fu_351_p2() { indvar_next_fu_351_p2 = (!indvar_reg_257.read().is_01() || !ap_const_lv2_1.is_01())? sc_lv<2>(): (sc_biguint<2>(indvar_reg_257.read()) + sc_biguint<2>(ap_const_lv2_1)); } void x_order_fir::thread_reload_1_fu_367_p3() { reload_1_fu_367_p3 = (!tmp_10_reg_509_pp0_iter1_reg.read()[0].is_01())? sc_lv<32>(): ((tmp_10_reg_509_pp0_iter1_reg.read()[0].to_bool())? reload_reg_245.read(): fir_ctrl_0_reg_515.read()); } void x_order_fir::thread_shift_reg_address0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state30.read())) { shift_reg_address0 = ap_const_lv10_0; } else if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage1.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage1.read(), ap_const_boolean_0))) { shift_reg_address0 = (sc_lv<10>) (tmp_7_reg_574.read()); } else if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage0.read(), ap_const_boolean_0))) { shift_reg_address0 = (sc_lv<10>) (tmp_6_fu_433_p1.read()); } else { shift_reg_address0 = "XXXXXXXXXX"; } } void x_order_fir::thread_shift_reg_ce0() { if (((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage1.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage1_11001.read(), ap_const_boolean_0)) || (esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage0_11001.read(), ap_const_boolean_0)) || (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state30.read()) && esl_seteq<1,1,1>(x_data_0_vld_out.read(), ap_const_logic_1)))) { shift_reg_ce0 = ap_const_logic_1; } else { shift_reg_ce0 = ap_const_logic_0; } } void x_order_fir::thread_shift_reg_d0() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state30.read())) { shift_reg_d0 = x_data_0_data_out.read(); } else if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage1.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage1.read(), ap_const_boolean_0))) { shift_reg_d0 = shift_reg_q0.read(); } else { shift_reg_d0 = (sc_lv<32>) ("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); } } void x_order_fir::thread_shift_reg_we0() { if (((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage1.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage1_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_0, tmp_2_reg_560.read())) || (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state30.read()) && esl_seteq<1,1,1>(x_data_0_vld_out.read(), ap_const_logic_1)))) { shift_reg_we0 = ap_const_logic_1; } else { shift_reg_we0 = ap_const_logic_0; } } void x_order_fir::thread_tmp_10_fu_357_p1() { tmp_10_fu_357_p1 = indvar_reg_257.read().range(1-1, 0); } void x_order_fir::thread_tmp_12_fu_379_p2() { tmp_12_fu_379_p2 = (!ap_const_lv32_2.is_01())? sc_lv<32>(): i_reg_233.read() << (unsigned short)ap_const_lv32_2.to_uint(); } void x_order_fir::thread_tmp_1_fu_385_p2() { tmp_1_fu_385_p2 = (!ap_const_lv32_4.is_01() || !tmp_12_fu_379_p2.read().is_01())? sc_lv<32>(): (sc_biguint<32>(ap_const_lv32_4) + sc_biguint<32>(tmp_12_fu_379_p2.read())); } void x_order_fir::thread_tmp_2_fu_421_p2() { tmp_2_fu_421_p2 = (!ap_phi_mux_i1_phi_fu_283_p4.read().is_01() || !ap_const_lv32_0.is_01())? sc_lv<1>(): sc_lv<1>(ap_phi_mux_i1_phi_fu_283_p4.read() == ap_const_lv32_0); } void x_order_fir::thread_tmp_3_fu_466_p1() { tmp_3_fu_466_p1 = x_data_0_data_out.read(); } void x_order_fir::thread_tmp_3_fu_466_p2() { tmp_3_fu_466_p2 = (!reg_302.read().is_01() || !tmp_3_fu_466_p1.read().is_01())? sc_lv<32>(): sc_bigint<32>(reg_302.read()) * sc_bigint<32>(tmp_3_fu_466_p1.read()); } void x_order_fir::thread_tmp_5_fu_326_p1() { tmp_5_fu_326_p1 = esl_zext<64,30>(ctrl3_reg_478.read()); } void x_order_fir::thread_tmp_6_fu_433_p1() { tmp_6_fu_433_p1 = esl_sext<64,32>(i_1_fu_427_p2.read()); } void x_order_fir::thread_tmp_7_fu_438_p1() { tmp_7_fu_438_p1 = esl_sext<64,32>(ap_phi_mux_i1_phi_fu_283_p4.read()); } void x_order_fir::thread_tmp_8_fu_443_p2() { tmp_8_fu_443_p2 = (!reg_302.read().is_01() || !shift_reg_load_reg_584.read().is_01())? sc_lv<32>(): sc_bigint<32>(reg_302.read()) * sc_bigint<32>(shift_reg_load_reg_584.read()); } void x_order_fir::thread_tmp_9_fu_336_p1() { tmp_9_fu_336_p1 = esl_zext<64,30>(coe1_reg_483.read()); } void x_order_fir::thread_tmp_fu_373_p2() { tmp_fu_373_p2 = (!reload_reg_245.read().is_01() || !ap_const_lv32_0.is_01())? sc_lv<1>(): sc_lv<1>(reload_reg_245.read() == ap_const_lv32_0); } void x_order_fir::thread_tmp_s_fu_401_p1() { tmp_s_fu_401_p1 = esl_zext<32,30>(p_add7_i32_shr_reg_535.read()); } void x_order_fir::thread_x_TDATA_blk_n() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state30.read())) { x_TDATA_blk_n = x_data_0_state.read()[0]; } else { x_TDATA_blk_n = ap_const_logic_1; } } void x_order_fir::thread_x_TREADY() { x_TREADY = x_last_V_0_state.read()[1]; } void x_order_fir::thread_x_data_0_ack_in() { x_data_0_ack_in = x_data_0_state.read()[1]; } void x_order_fir::thread_x_data_0_ack_out() { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state30.read()) && esl_seteq<1,1,1>(x_data_0_vld_out.read(), ap_const_logic_1))) { x_data_0_ack_out = ap_const_logic_1; } else { x_data_0_ack_out = ap_const_logic_0; } } void x_order_fir::thread_x_data_0_data_out() { if (esl_seteq<1,1,1>(ap_const_logic_1, x_data_0_sel.read())) { x_data_0_data_out = x_data_0_payload_B.read(); } else { x_data_0_data_out = x_data_0_payload_A.read(); } } void x_order_fir::thread_x_data_0_load_A() { x_data_0_load_A = (x_data_0_state_cmp_full.read() & ~x_data_0_sel_wr.read()); } void x_order_fir::thread_x_data_0_load_B() { x_data_0_load_B = (x_data_0_sel_wr.read() & x_data_0_state_cmp_full.read()); } void x_order_fir::thread_x_data_0_sel() { x_data_0_sel = x_data_0_sel_rd.read(); } void x_order_fir::thread_x_data_0_state_cmp_full() { x_data_0_state_cmp_full = (sc_logic) ((!x_data_0_state.read().is_01() || !ap_const_lv2_1.is_01())? sc_lv<1>(): sc_lv<1>(x_data_0_state.read() != ap_const_lv2_1))[0]; } void x_order_fir::thread_x_data_0_vld_in() { x_data_0_vld_in = x_TVALID.read(); } void x_order_fir::thread_x_data_0_vld_out() { x_data_0_vld_out = x_data_0_state.read()[0]; } void x_order_fir::thread_x_last_V_0_ack_in() { x_last_V_0_ack_in = x_last_V_0_state.read()[1]; } void x_order_fir::thread_x_last_V_0_ack_out() { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state30.read()) && esl_seteq<1,1,1>(x_data_0_vld_out.read(), ap_const_logic_1))) { x_last_V_0_ack_out = ap_const_logic_1; } else { x_last_V_0_ack_out = ap_const_logic_0; } } void x_order_fir::thread_x_last_V_0_data_out() { if (esl_seteq<1,1,1>(ap_const_logic_1, x_last_V_0_sel.read())) { x_last_V_0_data_out = x_last_V_0_payload_B.read(); } else { x_last_V_0_data_out = x_last_V_0_payload_A.read(); } } void x_order_fir::thread_x_last_V_0_load_A() { x_last_V_0_load_A = (x_last_V_0_state_cmp_full.read() & ~x_last_V_0_sel_wr.read()); } void x_order_fir::thread_x_last_V_0_load_B() { x_last_V_0_load_B = (x_last_V_0_sel_wr.read() & x_last_V_0_state_cmp_full.read()); } void x_order_fir::thread_x_last_V_0_sel() { x_last_V_0_sel = x_last_V_0_sel_rd.read(); } void x_order_fir::thread_x_last_V_0_state_cmp_full() { x_last_V_0_state_cmp_full = (sc_logic) ((!x_last_V_0_state.read().is_01() || !ap_const_lv2_1.is_01())? sc_lv<1>(): sc_lv<1>(x_last_V_0_state.read() != ap_const_lv2_1))[0]; } void x_order_fir::thread_x_last_V_0_vld_in() { x_last_V_0_vld_in = x_TVALID.read(); } void x_order_fir::thread_x_last_V_0_vld_out() { x_last_V_0_vld_out = x_last_V_0_state.read()[0]; } void x_order_fir::thread_x_user_V_0_ack_in() { x_user_V_0_ack_in = x_user_V_0_state.read()[1]; } void x_order_fir::thread_x_user_V_0_ack_out() { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state30.read()) && esl_seteq<1,1,1>(x_data_0_vld_out.read(), ap_const_logic_1))) { x_user_V_0_ack_out = ap_const_logic_1; } else { x_user_V_0_ack_out = ap_const_logic_0; } } void x_order_fir::thread_x_user_V_0_data_out() { if (esl_seteq<1,1,1>(ap_const_logic_1, x_user_V_0_sel.read())) { x_user_V_0_data_out = x_user_V_0_payload_B.read(); } else { x_user_V_0_data_out = x_user_V_0_payload_A.read(); } } void x_order_fir::thread_x_user_V_0_load_A() { x_user_V_0_load_A = (x_user_V_0_state_cmp_full.read() & ~x_user_V_0_sel_wr.read()); } void x_order_fir::thread_x_user_V_0_load_B() { x_user_V_0_load_B = (x_user_V_0_sel_wr.read() & x_user_V_0_state_cmp_full.read()); } void x_order_fir::thread_x_user_V_0_sel() { x_user_V_0_sel = x_user_V_0_sel_rd.read(); } void x_order_fir::thread_x_user_V_0_state_cmp_full() { x_user_V_0_state_cmp_full = (sc_logic) ((!x_user_V_0_state.read().is_01() || !ap_const_lv2_1.is_01())? sc_lv<1>(): sc_lv<1>(x_user_V_0_state.read() != ap_const_lv2_1))[0]; } void x_order_fir::thread_x_user_V_0_vld_in() { x_user_V_0_vld_in = x_TVALID.read(); } void x_order_fir::thread_x_user_V_0_vld_out() { x_user_V_0_vld_out = x_user_V_0_state.read()[0]; } void x_order_fir::thread_y_TDATA() { y_TDATA = y_data_1_data_out.read(); } void x_order_fir::thread_y_TDATA_blk_n() { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state31.read()) || esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state32.read()))) { y_TDATA_blk_n = y_data_1_state.read()[1]; } else { y_TDATA_blk_n = ap_const_logic_1; } } void x_order_fir::thread_y_TLAST() { y_TLAST = y_last_V_1_data_out.read(); } void x_order_fir::thread_y_TUSER() { y_TUSER = y_user_V_1_data_out.read(); } void x_order_fir::thread_y_TVALID() { y_TVALID = y_last_V_1_state.read()[0]; } void x_order_fir::thread_y_data_1_ack_in() { y_data_1_ack_in = y_data_1_state.read()[1]; } void x_order_fir::thread_y_data_1_ack_out() { y_data_1_ack_out = y_TREADY.read(); } void x_order_fir::thread_y_data_1_data_out() { if (esl_seteq<1,1,1>(ap_const_logic_1, y_data_1_sel.read())) { y_data_1_data_out = y_data_1_payload_B.read(); } else { y_data_1_data_out = y_data_1_payload_A.read(); } } void x_order_fir::thread_y_data_1_load_A() { y_data_1_load_A = (y_data_1_state_cmp_full.read() & ~y_data_1_sel_wr.read()); } void x_order_fir::thread_y_data_1_load_B() { y_data_1_load_B = (y_data_1_sel_wr.read() & y_data_1_state_cmp_full.read()); } void x_order_fir::thread_y_data_1_sel() { y_data_1_sel = y_data_1_sel_rd.read(); } void x_order_fir::thread_y_data_1_state_cmp_full() { y_data_1_state_cmp_full = (sc_logic) ((!y_data_1_state.read().is_01() || !ap_const_lv2_1.is_01())? sc_lv<1>(): sc_lv<1>(y_data_1_state.read() != ap_const_lv2_1))[0]; } void x_order_fir::thread_y_data_1_vld_in() { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state31.read()) && esl_seteq<1,1,1>(y_data_1_ack_in.read(), ap_const_logic_1))) { y_data_1_vld_in = ap_const_logic_1; } else { y_data_1_vld_in = ap_const_logic_0; } } void x_order_fir::thread_y_data_1_vld_out() { y_data_1_vld_out = y_data_1_state.read()[0]; } void x_order_fir::thread_y_last_V_1_ack_in() { y_last_V_1_ack_in = y_last_V_1_state.read()[1]; } void x_order_fir::thread_y_last_V_1_ack_out() { y_last_V_1_ack_out = y_TREADY.read(); } void x_order_fir::thread_y_last_V_1_data_out() { if (esl_seteq<1,1,1>(ap_const_logic_1, y_last_V_1_sel.read())) { y_last_V_1_data_out = y_last_V_1_payload_B.read(); } else { y_last_V_1_data_out = y_last_V_1_payload_A.read(); } } void x_order_fir::thread_y_last_V_1_load_A() { y_last_V_1_load_A = (y_last_V_1_state_cmp_full.read() & ~y_last_V_1_sel_wr.read()); } void x_order_fir::thread_y_last_V_1_load_B() { y_last_V_1_load_B = (y_last_V_1_sel_wr.read() & y_last_V_1_state_cmp_full.read()); } void x_order_fir::thread_y_last_V_1_sel() { y_last_V_1_sel = y_last_V_1_sel_rd.read(); } void x_order_fir::thread_y_last_V_1_state_cmp_full() { y_last_V_1_state_cmp_full = (sc_logic) ((!y_last_V_1_state.read().is_01() || !ap_const_lv2_1.is_01())? sc_lv<1>(): sc_lv<1>(y_last_V_1_state.read() != ap_const_lv2_1))[0]; } void x_order_fir::thread_y_last_V_1_vld_in() { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state31.read()) && esl_seteq<1,1,1>(y_data_1_ack_in.read(), ap_const_logic_1))) { y_last_V_1_vld_in = ap_const_logic_1; } else { y_last_V_1_vld_in = ap_const_logic_0; } } void x_order_fir::thread_y_last_V_1_vld_out() { y_last_V_1_vld_out = y_last_V_1_state.read()[0]; } void x_order_fir::thread_y_user_V_1_ack_in() { y_user_V_1_ack_in = y_user_V_1_state.read()[1]; } void x_order_fir::thread_y_user_V_1_ack_out() { y_user_V_1_ack_out = y_TREADY.read(); } void x_order_fir::thread_y_user_V_1_data_out() { if (esl_seteq<1,1,1>(ap_const_logic_1, y_user_V_1_sel.read())) { y_user_V_1_data_out = y_user_V_1_payload_B.read(); } else { y_user_V_1_data_out = y_user_V_1_payload_A.read(); } } void x_order_fir::thread_y_user_V_1_load_A() { y_user_V_1_load_A = (y_user_V_1_state_cmp_full.read() & ~y_user_V_1_sel_wr.read()); } void x_order_fir::thread_y_user_V_1_load_B() { y_user_V_1_load_B = (y_user_V_1_sel_wr.read() & y_user_V_1_state_cmp_full.read()); } void x_order_fir::thread_y_user_V_1_sel() { y_user_V_1_sel = y_user_V_1_sel_rd.read(); } void x_order_fir::thread_y_user_V_1_state_cmp_full() { y_user_V_1_state_cmp_full = (sc_logic) ((!y_user_V_1_state.read().is_01() || !ap_const_lv2_1.is_01())? sc_lv<1>(): sc_lv<1>(y_user_V_1_state.read() != ap_const_lv2_1))[0]; } void x_order_fir::thread_y_user_V_1_vld_in() { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state31.read()) && esl_seteq<1,1,1>(y_data_1_ack_in.read(), ap_const_logic_1))) { y_user_V_1_vld_in = ap_const_logic_1; } else { y_user_V_1_vld_in = ap_const_logic_0; } } void x_order_fir::thread_y_user_V_1_vld_out() { y_user_V_1_vld_out = y_user_V_1_state.read()[0]; } void x_order_fir::thread_ap_NS_fsm() { switch (ap_CS_fsm.read().to_uint64()) { case 1 : if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state1.read()) && esl_seteq<1,1,1>(ap_start.read(), ap_const_logic_1))) { ap_NS_fsm = ap_ST_fsm_state2; } else { ap_NS_fsm = ap_ST_fsm_state1; } break; case 2 : if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read()) && esl_seteq<1,1,1>(ap_sig_ioackin_gmem_ARREADY.read(), ap_const_logic_1))) { ap_NS_fsm = ap_ST_fsm_state3; } else { ap_NS_fsm = ap_ST_fsm_state2; } break; case 4 : ap_NS_fsm = ap_ST_fsm_state4; break; case 8 : ap_NS_fsm = ap_ST_fsm_state5; break; case 16 : ap_NS_fsm = ap_ST_fsm_state6; break; case 32 : ap_NS_fsm = ap_ST_fsm_state7; break; case 64 : ap_NS_fsm = ap_ST_fsm_state8; break; case 128 : ap_NS_fsm = ap_ST_fsm_pp0_stage0; break; case 256 : if ((!(esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter2.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_enable_reg_pp0_iter1.read(), ap_const_logic_0)) && !(esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter0.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_1, exitcond_fu_345_p2.read()) && esl_seteq<1,1,1>(ap_enable_reg_pp0_iter1.read(), ap_const_logic_0)))) { ap_NS_fsm = ap_ST_fsm_pp0_stage0; } else if (((esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter2.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_enable_reg_pp0_iter1.read(), ap_const_logic_0)) || (esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter0.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_1, exitcond_fu_345_p2.read()) && esl_seteq<1,1,1>(ap_enable_reg_pp0_iter1.read(), ap_const_logic_0)))) { ap_NS_fsm = ap_ST_fsm_state12; } else { ap_NS_fsm = ap_ST_fsm_pp0_stage0; } break; case 512 : if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state12.read()) && esl_seteq<1,1,1>(ap_const_lv1_1, tmp_fu_373_p2.read()))) { ap_NS_fsm = ap_ST_fsm_state23; } else { ap_NS_fsm = ap_ST_fsm_state13; } break; case 1024 : if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state13.read()) && esl_seteq<1,1,1>(ap_sig_ioackin_gmem_ARREADY.read(), ap_const_logic_1))) { ap_NS_fsm = ap_ST_fsm_state14; } else { ap_NS_fsm = ap_ST_fsm_state13; } break; case 2048 : ap_NS_fsm = ap_ST_fsm_state15; break; case 4096 : ap_NS_fsm = ap_ST_fsm_state16; break; case 8192 : ap_NS_fsm = ap_ST_fsm_state17; break; case 16384 : ap_NS_fsm = ap_ST_fsm_state18; break; case 32768 : ap_NS_fsm = ap_ST_fsm_state19; break; case 65536 : ap_NS_fsm = ap_ST_fsm_pp1_stage0; break; case 131072 : if ((!(esl_seteq<1,1,1>(ap_block_pp1_stage0_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter2.read()) && esl_seteq<1,1,1>(ap_enable_reg_pp1_iter1.read(), ap_const_logic_0)) && !(esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter0.read()) && esl_seteq<1,1,1>(ap_block_pp1_stage0_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_1, exitcond1_fu_405_p2.read()) && esl_seteq<1,1,1>(ap_enable_reg_pp1_iter1.read(), ap_const_logic_0)))) { ap_NS_fsm = ap_ST_fsm_pp1_stage0; } else if (((esl_seteq<1,1,1>(ap_block_pp1_stage0_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter2.read()) && esl_seteq<1,1,1>(ap_enable_reg_pp1_iter1.read(), ap_const_logic_0)) || (esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp1_iter0.read()) && esl_seteq<1,1,1>(ap_block_pp1_stage0_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_1, exitcond1_fu_405_p2.read()) && esl_seteq<1,1,1>(ap_enable_reg_pp1_iter1.read(), ap_const_logic_0)))) { ap_NS_fsm = ap_ST_fsm_state23; } else { ap_NS_fsm = ap_ST_fsm_pp1_stage0; } break; case 262144 : ap_NS_fsm = ap_ST_fsm_pp2_stage0; break; case 524288 : if ((esl_seteq<1,1,1>(ap_block_pp2_stage0_subdone.read(), ap_const_boolean_0) && !(esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage0_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_1, tmp_2_fu_421_p2.read()) && esl_seteq<1,1,1>(ap_enable_reg_pp2_iter1.read(), ap_const_logic_0)))) { ap_NS_fsm = ap_ST_fsm_pp2_stage1; } else if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter0.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage0_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_const_lv1_1, tmp_2_fu_421_p2.read()) && esl_seteq<1,1,1>(ap_enable_reg_pp2_iter1.read(), ap_const_logic_0))) { ap_NS_fsm = ap_ST_fsm_state28; } else { ap_NS_fsm = ap_ST_fsm_pp2_stage0; } break; case 1048576 : if ((esl_seteq<1,1,1>(ap_block_pp2_stage1_subdone.read(), ap_const_boolean_0) && !(esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage1.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter1.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage1_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_enable_reg_pp2_iter0.read(), ap_const_logic_0)))) { ap_NS_fsm = ap_ST_fsm_pp2_stage0; } else if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp2_stage1.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp2_iter1.read()) && esl_seteq<1,1,1>(ap_block_pp2_stage1_subdone.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_enable_reg_pp2_iter0.read(), ap_const_logic_0))) { ap_NS_fsm = ap_ST_fsm_state28; } else { ap_NS_fsm = ap_ST_fsm_pp2_stage1; } break; case 2097152 : ap_NS_fsm = ap_ST_fsm_state29; break; case 4194304 : ap_NS_fsm = ap_ST_fsm_state30; break; case 8388608 : if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state30.read()) && esl_seteq<1,1,1>(x_data_0_vld_out.read(), ap_const_logic_1))) { ap_NS_fsm = ap_ST_fsm_state31; } else { ap_NS_fsm = ap_ST_fsm_state30; } break; case 16777216 : if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state31.read()) && esl_seteq<1,1,1>(y_data_1_ack_in.read(), ap_const_logic_1))) { ap_NS_fsm = ap_ST_fsm_state32; } else { ap_NS_fsm = ap_ST_fsm_state31; } break; case 33554432 : if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state32.read()) && esl_seteq<1,1,1>(ap_const_logic_0, y_data_1_state.read()[0]) && esl_seteq<1,1,1>(ap_const_logic_0, y_user_V_1_state.read()[0]) && esl_seteq<1,1,1>(ap_const_logic_0, y_last_V_1_state.read()[0]) && !(esl_seteq<1,1,1>(ap_const_logic_0, y_data_1_ack_in.read()) || esl_seteq<1,1,1>(ap_const_logic_0, y_user_V_1_ack_in.read()) || esl_seteq<1,1,1>(ap_const_logic_0, y_last_V_1_ack_in.read())))) { ap_NS_fsm = ap_ST_fsm_state1; } else { ap_NS_fsm = ap_ST_fsm_state32; } break; default : ap_NS_fsm = (sc_lv<26>) ("XXXXXXXXXXXXXXXXXXXXXXXXXX"); break; } } void x_order_fir::thread_hdltv_gen() { const char* dump_tv = std::getenv("AP_WRITE_TV"); if (!(dump_tv && string(dump_tv) == "on")) return; wait(); mHdltvinHandle << "[ " << endl; mHdltvoutHandle << "[ " << endl; int ap_cycleNo = 0; while (1) { wait(); const char* mComma = ap_cycleNo == 0 ? " " : ", " ; mHdltvinHandle << mComma << "{" << " \"ap_rst_n\" : \"" << ap_rst_n.read() << "\" "; mHdltvoutHandle << mComma << "{" << " \"m_axi_gmem_AWVALID\" : \"" << m_axi_gmem_AWVALID.read() << "\" "; mHdltvinHandle << " , " << " \"m_axi_gmem_AWREADY\" : \"" << m_axi_gmem_AWREADY.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_AWADDR\" : \"" << m_axi_gmem_AWADDR.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_AWID\" : \"" << m_axi_gmem_AWID.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_AWLEN\" : \"" << m_axi_gmem_AWLEN.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_AWSIZE\" : \"" << m_axi_gmem_AWSIZE.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_AWBURST\" : \"" << m_axi_gmem_AWBURST.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_AWLOCK\" : \"" << m_axi_gmem_AWLOCK.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_AWCACHE\" : \"" << m_axi_gmem_AWCACHE.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_AWPROT\" : \"" << m_axi_gmem_AWPROT.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_AWQOS\" : \"" << m_axi_gmem_AWQOS.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_AWREGION\" : \"" << m_axi_gmem_AWREGION.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_AWUSER\" : \"" << m_axi_gmem_AWUSER.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_WVALID\" : \"" << m_axi_gmem_WVALID.read() << "\" "; mHdltvinHandle << " , " << " \"m_axi_gmem_WREADY\" : \"" << m_axi_gmem_WREADY.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_WDATA\" : \"" << m_axi_gmem_WDATA.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_WSTRB\" : \"" << m_axi_gmem_WSTRB.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_WLAST\" : \"" << m_axi_gmem_WLAST.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_WID\" : \"" << m_axi_gmem_WID.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_WUSER\" : \"" << m_axi_gmem_WUSER.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_ARVALID\" : \"" << m_axi_gmem_ARVALID.read() << "\" "; mHdltvinHandle << " , " << " \"m_axi_gmem_ARREADY\" : \"" << m_axi_gmem_ARREADY.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_ARADDR\" : \"" << m_axi_gmem_ARADDR.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_ARID\" : \"" << m_axi_gmem_ARID.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_ARLEN\" : \"" << m_axi_gmem_ARLEN.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_ARSIZE\" : \"" << m_axi_gmem_ARSIZE.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_ARBURST\" : \"" << m_axi_gmem_ARBURST.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_ARLOCK\" : \"" << m_axi_gmem_ARLOCK.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_ARCACHE\" : \"" << m_axi_gmem_ARCACHE.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_ARPROT\" : \"" << m_axi_gmem_ARPROT.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_ARQOS\" : \"" << m_axi_gmem_ARQOS.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_ARREGION\" : \"" << m_axi_gmem_ARREGION.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_ARUSER\" : \"" << m_axi_gmem_ARUSER.read() << "\" "; mHdltvinHandle << " , " << " \"m_axi_gmem_RVALID\" : \"" << m_axi_gmem_RVALID.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_RREADY\" : \"" << m_axi_gmem_RREADY.read() << "\" "; mHdltvinHandle << " , " << " \"m_axi_gmem_RDATA\" : \"" << m_axi_gmem_RDATA.read() << "\" "; mHdltvinHandle << " , " << " \"m_axi_gmem_RLAST\" : \"" << m_axi_gmem_RLAST.read() << "\" "; mHdltvinHandle << " , " << " \"m_axi_gmem_RID\" : \"" << m_axi_gmem_RID.read() << "\" "; mHdltvinHandle << " , " << " \"m_axi_gmem_RUSER\" : \"" << m_axi_gmem_RUSER.read() << "\" "; mHdltvinHandle << " , " << " \"m_axi_gmem_RRESP\" : \"" << m_axi_gmem_RRESP.read() << "\" "; mHdltvinHandle << " , " << " \"m_axi_gmem_BVALID\" : \"" << m_axi_gmem_BVALID.read() << "\" "; mHdltvoutHandle << " , " << " \"m_axi_gmem_BREADY\" : \"" << m_axi_gmem_BREADY.read() << "\" "; mHdltvinHandle << " , " << " \"m_axi_gmem_BRESP\" : \"" << m_axi_gmem_BRESP.read() << "\" "; mHdltvinHandle << " , " << " \"m_axi_gmem_BID\" : \"" << m_axi_gmem_BID.read() << "\" "; mHdltvinHandle << " , " << " \"m_axi_gmem_BUSER\" : \"" << m_axi_gmem_BUSER.read() << "\" "; mHdltvoutHandle << " , " << " \"y_TDATA\" : \"" << y_TDATA.read() << "\" "; mHdltvoutHandle << " , " << " \"y_TVALID\" : \"" << y_TVALID.read() << "\" "; mHdltvinHandle << " , " << " \"y_TREADY\" : \"" << y_TREADY.read() << "\" "; mHdltvoutHandle << " , " << " \"y_TUSER\" : \"" << y_TUSER.read() << "\" "; mHdltvoutHandle << " , " << " \"y_TLAST\" : \"" << y_TLAST.read() << "\" "; mHdltvinHandle << " , " << " \"x_TDATA\" : \"" << x_TDATA.read() << "\" "; mHdltvinHandle << " , " << " \"x_TVALID\" : \"" << x_TVALID.read() << "\" "; mHdltvoutHandle << " , " << " \"x_TREADY\" : \"" << x_TREADY.read() << "\" "; mHdltvinHandle << " , " << " \"x_TUSER\" : \"" << x_TUSER.read() << "\" "; mHdltvinHandle << " , " << " \"x_TLAST\" : \"" << x_TLAST.read() << "\" "; mHdltvinHandle << " , " << " \"s_axi_AXILiteS_AWVALID\" : \"" << s_axi_AXILiteS_AWVALID.read() << "\" "; mHdltvoutHandle << " , " << " \"s_axi_AXILiteS_AWREADY\" : \"" << s_axi_AXILiteS_AWREADY.read() << "\" "; mHdltvinHandle << " , " << " \"s_axi_AXILiteS_AWADDR\" : \"" << s_axi_AXILiteS_AWADDR.read() << "\" "; mHdltvinHandle << " , " << " \"s_axi_AXILiteS_WVALID\" : \"" << s_axi_AXILiteS_WVALID.read() << "\" "; mHdltvoutHandle << " , " << " \"s_axi_AXILiteS_WREADY\" : \"" << s_axi_AXILiteS_WREADY.read() << "\" "; mHdltvinHandle << " , " << " \"s_axi_AXILiteS_WDATA\" : \"" << s_axi_AXILiteS_WDATA.read() << "\" "; mHdltvinHandle << " , " << " \"s_axi_AXILiteS_WSTRB\" : \"" << s_axi_AXILiteS_WSTRB.read() << "\" "; mHdltvinHandle << " , " << " \"s_axi_AXILiteS_ARVALID\" : \"" << s_axi_AXILiteS_ARVALID.read() << "\" "; mHdltvoutHandle << " , " << " \"s_axi_AXILiteS_ARREADY\" : \"" << s_axi_AXILiteS_ARREADY.read() << "\" "; mHdltvinHandle << " , " << " \"s_axi_AXILiteS_ARADDR\" : \"" << s_axi_AXILiteS_ARADDR.read() << "\" "; mHdltvoutHandle << " , " << " \"s_axi_AXILiteS_RVALID\" : \"" << s_axi_AXILiteS_RVALID.read() << "\" "; mHdltvinHandle << " , " << " \"s_axi_AXILiteS_RREADY\" : \"" << s_axi_AXILiteS_RREADY.read() << "\" "; mHdltvoutHandle << " , " << " \"s_axi_AXILiteS_RDATA\" : \"" << s_axi_AXILiteS_RDATA.read() << "\" "; mHdltvoutHandle << " , " << " \"s_axi_AXILiteS_RRESP\" : \"" << s_axi_AXILiteS_RRESP.read() << "\" "; mHdltvoutHandle << " , " << " \"s_axi_AXILiteS_BVALID\" : \"" << s_axi_AXILiteS_BVALID.read() << "\" "; mHdltvinHandle << " , " << " \"s_axi_AXILiteS_BREADY\" : \"" << s_axi_AXILiteS_BREADY.read() << "\" "; mHdltvoutHandle << " , " << " \"s_axi_AXILiteS_BRESP\" : \"" << s_axi_AXILiteS_BRESP.read() << "\" "; mHdltvoutHandle << " , " << " \"interrupt\" : \"" << interrupt.read() << "\" "; mHdltvinHandle << "}" << std::endl; mHdltvoutHandle << "}" << std::endl; ap_cycleNo++; } } }
46.94216
519
0.69364
xupsh
090e06e8b0eaf77d05e52509ce378d68547f6c49
10,990
cpp
C++
src/cost/configuration_space_cost.cpp
z8674558/idocp
946524db7ae4591b578be2409ca619961572e7be
[ "BSD-3-Clause" ]
43
2020-10-13T03:43:45.000Z
2021-09-23T05:29:48.000Z
src/cost/configuration_space_cost.cpp
z8674558/idocp
946524db7ae4591b578be2409ca619961572e7be
[ "BSD-3-Clause" ]
32
2020-10-21T09:40:16.000Z
2021-10-24T00:00:04.000Z
src/cost/configuration_space_cost.cpp
z8674558/idocp
946524db7ae4591b578be2409ca619961572e7be
[ "BSD-3-Clause" ]
4
2020-10-08T05:47:16.000Z
2021-10-15T12:15:26.000Z
#include "idocp/cost/configuration_space_cost.hpp" #include <iostream> #include <stdexcept> namespace idocp { ConfigurationSpaceCost::ConfigurationSpaceCost(const Robot& robot) : CostFunctionComponentBase(), dimq_(robot.dimq()), dimv_(robot.dimv()), dimu_(robot.dimu()), q_ref_(Eigen::VectorXd::Zero(robot.dimq())), v_ref_(Eigen::VectorXd::Zero(robot.dimv())), u_ref_(Eigen::VectorXd::Zero(robot.dimu())), q_weight_(Eigen::VectorXd::Zero(robot.dimv())), v_weight_(Eigen::VectorXd::Zero(robot.dimv())), a_weight_(Eigen::VectorXd::Zero(robot.dimv())), u_weight_(Eigen::VectorXd::Zero(robot.dimu())), qf_weight_(Eigen::VectorXd::Zero(robot.dimv())), vf_weight_(Eigen::VectorXd::Zero(robot.dimv())), qi_weight_(Eigen::VectorXd::Zero(robot.dimv())), vi_weight_(Eigen::VectorXd::Zero(robot.dimv())), dvi_weight_(Eigen::VectorXd::Zero(robot.dimv())) { if (robot.hasFloatingBase()) { robot.normalizeConfiguration(q_ref_); } } ConfigurationSpaceCost::ConfigurationSpaceCost() : CostFunctionComponentBase(), dimq_(0), dimv_(0), dimu_(), q_ref_(), v_ref_(), u_ref_(), q_weight_(), v_weight_(), a_weight_(), u_weight_(), qf_weight_(), vf_weight_(), qi_weight_(), vi_weight_(), dvi_weight_() { } ConfigurationSpaceCost::~ConfigurationSpaceCost() { } void ConfigurationSpaceCost::set_q_ref(const Eigen::VectorXd& q_ref) { try { if (q_ref.size() != dimq_) { throw std::invalid_argument( "invalid size: q_ref.size() must be " + std::to_string(dimq_) + "!"); } } catch(const std::exception& e) { std::cerr << e.what() << '\n'; std::exit(EXIT_FAILURE); } q_ref_ = q_ref; } void ConfigurationSpaceCost::set_v_ref(const Eigen::VectorXd& v_ref) { try { if (v_ref.size() != dimv_) { throw std::invalid_argument( "invalid size: v_ref.size() must be " + std::to_string(dimv_) + "!"); } } catch(const std::exception& e) { std::cerr << e.what() << '\n'; std::exit(EXIT_FAILURE); } v_ref_ = v_ref; } void ConfigurationSpaceCost::set_u_ref(const Eigen::VectorXd& u_ref) { try { if (u_ref.size() != dimu_) { throw std::invalid_argument( "invalid size: u_ref.size() must be " + std::to_string(dimu_) + "!"); } } catch(const std::exception& e) { std::cerr << e.what() << '\n'; std::exit(EXIT_FAILURE); } u_ref_ = u_ref; } void ConfigurationSpaceCost::set_q_weight(const Eigen::VectorXd& q_weight) { try { if (q_weight.size() != dimv_) { throw std::invalid_argument( "invalid size: q_weight.size() must be " + std::to_string(dimv_) + "!"); } } catch(const std::exception& e) { std::cerr << e.what() << '\n'; std::exit(EXIT_FAILURE); } q_weight_ = q_weight; } void ConfigurationSpaceCost::set_v_weight(const Eigen::VectorXd& v_weight) { try { if (v_weight.size() != dimv_) { throw std::invalid_argument( "invalid size: v_weight.size() must be " + std::to_string(dimv_) + "!"); } } catch(const std::exception& e) { std::cerr << e.what() << '\n'; std::exit(EXIT_FAILURE); } v_weight_ = v_weight; } void ConfigurationSpaceCost::set_a_weight(const Eigen::VectorXd& a_weight) { try { if (a_weight.size() != dimv_) { throw std::invalid_argument( "invalid size: a_weight.size() must be " + std::to_string(dimv_) + "!"); } } catch(const std::exception& e) { std::cerr << e.what() << '\n'; std::exit(EXIT_FAILURE); } a_weight_ = a_weight; } void ConfigurationSpaceCost::set_u_weight(const Eigen::VectorXd& u_weight) { try { if (u_weight.size() != dimu_) { throw std::invalid_argument( "invalid size: u_weight.size() must be " + std::to_string(dimu_) + "!"); } } catch(const std::exception& e) { std::cerr << e.what() << '\n'; std::exit(EXIT_FAILURE); } u_weight_ = u_weight; } void ConfigurationSpaceCost::set_qf_weight(const Eigen::VectorXd& qf_weight) { try { if (qf_weight.size() != dimv_) { throw std::invalid_argument( "invalid size: qf_weight.size() must be " + std::to_string(dimv_) + "!"); } } catch(const std::exception& e) { std::cerr << e.what() << '\n'; std::exit(EXIT_FAILURE); } qf_weight_ = qf_weight; } void ConfigurationSpaceCost::set_vf_weight(const Eigen::VectorXd& vf_weight) { try { if (vf_weight.size() != dimv_) { throw std::invalid_argument( "invalid size: vf_weight.size() must be " + std::to_string(dimv_) + "!"); } } catch(const std::exception& e) { std::cerr << e.what() << '\n'; std::exit(EXIT_FAILURE); } vf_weight_ = vf_weight; } void ConfigurationSpaceCost::set_qi_weight(const Eigen::VectorXd& qi_weight) { try { if (qi_weight.size() != dimv_) { throw std::invalid_argument( "invalid size: qi_weight.size() must be " + std::to_string(dimv_) + "!"); } } catch(const std::exception& e) { std::cerr << e.what() << '\n'; std::exit(EXIT_FAILURE); } qi_weight_ = qi_weight; } void ConfigurationSpaceCost::set_vi_weight(const Eigen::VectorXd& vi_weight) { try { if (vi_weight.size() != dimv_) { throw std::invalid_argument( "invalid size: vi_weight.size() must be " + std::to_string(dimv_) + "!"); } } catch(const std::exception& e) { std::cerr << e.what() << '\n'; std::exit(EXIT_FAILURE); } vi_weight_ = vi_weight; } void ConfigurationSpaceCost::set_dvi_weight(const Eigen::VectorXd& dvi_weight) { try { if (dvi_weight.size() != dimv_) { throw std::invalid_argument( "invalid size: dvi_weight.size() must be " + std::to_string(dimv_) + "!"); } } catch(const std::exception& e) { std::cerr << e.what() << '\n'; std::exit(EXIT_FAILURE); } dvi_weight_ = dvi_weight; } bool ConfigurationSpaceCost::useKinematics() const { return false; } double ConfigurationSpaceCost::computeStageCost( Robot& robot, CostFunctionData& data, const double t, const double dt, const SplitSolution& s) const { double l = 0; robot.subtractConfiguration(s.q, q_ref_, data.qdiff); l += (q_weight_.array()*(data.qdiff).array()*(data.qdiff).array()).sum(); l += (v_weight_.array()*(s.v-v_ref_).array()*(s.v-v_ref_).array()).sum(); l += (a_weight_.array()*s.a.array()*s.a.array()).sum(); l += (u_weight_.array()*(s.u-u_ref_).array()*(s.u-u_ref_).array()).sum(); return 0.5 * dt * l; } void ConfigurationSpaceCost::computeStageCostDerivatives( Robot& robot, CostFunctionData& data, const double t, const double dt, const SplitSolution& s, SplitKKTResidual& kkt_residual) const { if (robot.hasFloatingBase()) { robot.dSubtractConfiguration_dqf(s.q, q_ref_, data.J_qdiff); kkt_residual.lq().noalias() += dt * data.J_qdiff.transpose() * q_weight_.asDiagonal() * data.qdiff; } else { kkt_residual.lq().array() += dt * q_weight_.array() * data.qdiff.array(); } kkt_residual.lv().array() += dt * v_weight_.array() * (s.v.array()-v_ref_.array()); kkt_residual.la.array() += dt * a_weight_.array() * s.a.array(); kkt_residual.lu.array() += dt * u_weight_.array() * (s.u.array()-u_ref_.array()); } void ConfigurationSpaceCost::computeStageCostHessian( Robot& robot, CostFunctionData& data, const double t, const double dt, const SplitSolution& s, SplitKKTMatrix& kkt_matrix) const { if (robot.hasFloatingBase()) { kkt_matrix.Qqq().noalias() += dt * data.J_qdiff.transpose() * q_weight_.asDiagonal() * data.J_qdiff; } else { kkt_matrix.Qqq().diagonal().noalias() += dt * q_weight_; } kkt_matrix.Qvv().diagonal().noalias() += dt * v_weight_; kkt_matrix.Qaa.diagonal().noalias() += dt * a_weight_; kkt_matrix.Quu.diagonal().noalias() += dt * u_weight_; } double ConfigurationSpaceCost::computeTerminalCost( Robot& robot, CostFunctionData& data, const double t, const SplitSolution& s) const { double l = 0; robot.subtractConfiguration(s.q, q_ref_, data.qdiff); l += (qf_weight_.array()*(data.qdiff).array()*(data.qdiff).array()).sum(); l += (vf_weight_.array()*(s.v-v_ref_).array()*(s.v-v_ref_).array()).sum(); return 0.5 * l; } void ConfigurationSpaceCost::computeTerminalCostDerivatives( Robot& robot, CostFunctionData& data, const double t, const SplitSolution& s, SplitKKTResidual& kkt_residual) const { if (robot.hasFloatingBase()) { robot.dSubtractConfiguration_dqf(s.q, q_ref_, data.J_qdiff); kkt_residual.lq().noalias() += data.J_qdiff.transpose() * qf_weight_.asDiagonal() * data.qdiff; } else { kkt_residual.lq().array() += qf_weight_.array() * data.qdiff.array(); } kkt_residual.lv().array() += vf_weight_.array() * (s.v.array()-v_ref_.array()); } void ConfigurationSpaceCost::computeTerminalCostHessian( Robot& robot, CostFunctionData& data, const double t, const SplitSolution& s, SplitKKTMatrix& kkt_matrix) const { if (robot.hasFloatingBase()) { kkt_matrix.Qqq().noalias() += data.J_qdiff.transpose() * qf_weight_.asDiagonal() * data.J_qdiff; } else { kkt_matrix.Qqq().diagonal().noalias() += qf_weight_; } kkt_matrix.Qvv().diagonal().noalias() += vf_weight_; } double ConfigurationSpaceCost::computeImpulseCost( Robot& robot, CostFunctionData& data, const double t, const ImpulseSplitSolution& s) const { double l = 0; robot.subtractConfiguration(s.q, q_ref_, data.qdiff); l += (qi_weight_.array()*(data.qdiff).array()*(data.qdiff).array()).sum(); l += (vi_weight_.array()*(s.v-v_ref_).array()*(s.v-v_ref_).array()).sum(); l += (dvi_weight_.array()*s.dv.array()*s.dv.array()).sum(); return 0.5 * l; } void ConfigurationSpaceCost::computeImpulseCostDerivatives( Robot& robot, CostFunctionData& data, const double t, const ImpulseSplitSolution& s, ImpulseSplitKKTResidual& kkt_residual) const { if (robot.hasFloatingBase()) { robot.dSubtractConfiguration_dqf(s.q, q_ref_, data.J_qdiff); kkt_residual.lq().noalias() += data.J_qdiff.transpose() * qi_weight_.asDiagonal() * data.qdiff; } else { kkt_residual.lq().array() += qi_weight_.array() * data.qdiff.array(); } kkt_residual.lv().array() += vi_weight_.array() * (s.v.array()-v_ref_.array()); kkt_residual.ldv.array() += dvi_weight_.array() * s.dv.array(); } void ConfigurationSpaceCost::computeImpulseCostHessian( Robot& robot, CostFunctionData& data, const double t, const ImpulseSplitSolution& s, ImpulseSplitKKTMatrix& kkt_matrix) const { if (robot.hasFloatingBase()) { kkt_matrix.Qqq().noalias() += data.J_qdiff.transpose() * qi_weight_.asDiagonal() * data.J_qdiff; } else { kkt_matrix.Qqq().diagonal().noalias() += qi_weight_; } kkt_matrix.Qvv().diagonal().noalias() += vi_weight_; kkt_matrix.Qdvdv.diagonal().noalias() += dvi_weight_; } } // namespace idocp
29.385027
84
0.643676
z8674558
090fd6e6ba328840af358250e489abbf6db83d71
817
cpp
C++
4.27/PlayFabPlugin/PlayFab/Source/PlayFabCommon/Private/PlayFabCommonSettings.cpp
parnic-sks/UnrealMarketplacePlugin
87a9d392de53d2031a3ceafbc79ab86d86ca3a33
[ "Apache-2.0" ]
null
null
null
4.27/PlayFabPlugin/PlayFab/Source/PlayFabCommon/Private/PlayFabCommonSettings.cpp
parnic-sks/UnrealMarketplacePlugin
87a9d392de53d2031a3ceafbc79ab86d86ca3a33
[ "Apache-2.0" ]
null
null
null
4.27/PlayFabPlugin/PlayFab/Source/PlayFabCommon/Private/PlayFabCommonSettings.cpp
parnic-sks/UnrealMarketplacePlugin
87a9d392de53d2031a3ceafbc79ab86d86ca3a33
[ "Apache-2.0" ]
null
null
null
////////////////////////////////////////////////////// // Copyright (C) Microsoft. 2018. All rights reserved. ////////////////////////////////////////////////////// #include "PlayFabCommonSettings.h" namespace PlayFabCommon { const FString PlayFabCommonSettings::sdkVersion = "1.70.211209"; const FString PlayFabCommonSettings::buildIdentifier = "jbuild_unrealmarketplaceplugin_sdk-unrealslave-6_0"; const FString PlayFabCommonSettings::versionString = "UE4MKPL-1.70.211209"; FString PlayFabCommonSettings::clientSessionTicket; FString PlayFabCommonSettings::entityToken; FString PlayFabCommonSettings::connectionString; FString PlayFabCommonSettings::photonRealtimeAppId; FString PlayFabCommonSettings::photonTurnbasedAppId; FString PlayFabCommonSettings::photonChatAppId; }
37.136364
112
0.69645
parnic-sks
09102ed991acec6383ecdecda5e7412b631308c3
38,522
hxx
C++
include/opengm/functions/constraint_functions/label_order_function.hxx
jasjuang/opengm
3c098e91244c98dbd3aafdc5e3a54dad67b7dfd9
[ "MIT" ]
318
2015-01-07T15:22:02.000Z
2022-01-22T10:10:29.000Z
include/opengm/functions/constraint_functions/label_order_function.hxx
jasjuang/opengm
3c098e91244c98dbd3aafdc5e3a54dad67b7dfd9
[ "MIT" ]
89
2015-03-24T14:33:01.000Z
2020-07-10T13:59:13.000Z
include/opengm/functions/constraint_functions/label_order_function.hxx
jasjuang/opengm
3c098e91244c98dbd3aafdc5e3a54dad67b7dfd9
[ "MIT" ]
119
2015-01-13T08:35:03.000Z
2022-03-01T01:49:08.000Z
#ifndef OPENGM_LABEL_ORDER_FUNCTION_HXX_ #define OPENGM_LABEL_ORDER_FUNCTION_HXX_ #include <algorithm> #include <vector> #include <cmath> #include <opengm/opengm.hxx> #include <opengm/functions/function_registration.hxx> #include <opengm/utilities/subsequence_iterator.hxx> #include <opengm/functions/constraint_functions/linear_constraint_function_base.hxx> #include <opengm/datastructures/linear_constraint.hxx> namespace opengm { /********************* * class definition * *********************/ template<class VALUE_TYPE, class INDEX_TYPE = size_t, class LABEL_TYPE = size_t> class LabelOrderFunction : public LinearConstraintFunctionBase<LabelOrderFunction<VALUE_TYPE,INDEX_TYPE, LABEL_TYPE> > { public: // public function properties static const bool useSingleConstraint_ = true; static const bool useMultipleConstraints_ = false; // typedefs typedef LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE> LinearConstraintFunctionType; typedef LinearConstraintFunctionBase<LinearConstraintFunctionType> LinearConstraintFunctionBaseType; typedef LinearConstraintFunctionTraits<LinearConstraintFunctionType> LinearConstraintFunctionTraitsType; typedef typename LinearConstraintFunctionTraitsType::ValueType ValueType; typedef typename LinearConstraintFunctionTraitsType::IndexType IndexType; typedef typename LinearConstraintFunctionTraitsType::LabelType LabelType; typedef std::vector<ValueType> LabelOrderType; typedef typename LinearConstraintFunctionTraitsType::LinearConstraintType LinearConstraintType; typedef typename LinearConstraintFunctionTraitsType::LinearConstraintsContainerType LinearConstraintsContainerType; typedef typename LinearConstraintFunctionTraitsType::LinearConstraintsIteratorType LinearConstraintsIteratorType; typedef typename LinearConstraintFunctionTraitsType::IndicatorVariablesContainerType IndicatorVariablesContainerType; typedef typename LinearConstraintFunctionTraitsType::IndicatorVariablesIteratorType IndicatorVariablesIteratorType; typedef typename LinearConstraintFunctionTraitsType::VariableLabelPairsIteratorType VariableLabelPairsIteratorType; typedef typename LinearConstraintFunctionTraitsType::ViolatedLinearConstraintsIteratorType ViolatedLinearConstraintsIteratorType; typedef typename LinearConstraintFunctionTraitsType::ViolatedLinearConstraintsWeightsContainerType ViolatedLinearConstraintsWeightsContainerType; typedef typename LinearConstraintFunctionTraitsType::ViolatedLinearConstraintsWeightsIteratorType ViolatedLinearConstraintsWeightsIteratorType; // constructors LabelOrderFunction(); LabelOrderFunction(const LabelType numLabelsVar1, const LabelType numLabelsVar2, const LabelOrderType& labelOrder, const ValueType returnValid = 0.0, const ValueType returnInvalid = 1.0); template <class ITERATOR_TYPE> LabelOrderFunction(const LabelType numLabelsVar1, const LabelType numLabelsVar2, ITERATOR_TYPE labelOrderBegin, const ValueType returnValid = 0.0, const ValueType returnInvalid = 1.0); ~LabelOrderFunction(); // function access template<class Iterator> ValueType operator()(Iterator statesBegin) const; // function evaluation size_t shape(const size_t i) const; // number of labels of the indicated input variable size_t dimension() const; // number of input variables size_t size() const; // number of parameters // specializations ValueType min() const; ValueType max() const; MinMaxFunctor<ValueType> minMax() const; protected: // storage static const size_t dimension_ = 2; LabelType numLabelsVar1_; LabelType numLabelsVar2_; size_t size_; LabelOrderType labelOrder_; ValueType returnValid_; ValueType returnInvalid_; LinearConstraintsContainerType constraints_; mutable std::vector<size_t> violatedConstraintsIds_; mutable ViolatedLinearConstraintsWeightsContainerType violatedConstraintsWeights_; IndicatorVariablesContainerType indicatorVariableList_; // implementations for LinearConstraintFunctionBase LinearConstraintsIteratorType linearConstraintsBegin_impl() const; LinearConstraintsIteratorType linearConstraintsEnd_impl() const; IndicatorVariablesIteratorType indicatorVariablesOrderBegin_impl() const; IndicatorVariablesIteratorType indicatorVariablesOrderEnd_impl() const; template <class LABEL_ITERATOR> void challenge_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance = 0.0) const; template <class LABEL_ITERATOR> void challengeRelaxed_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance = 0.0) const; // sanity check bool checkLabelOrder() const; // helper functions void fillIndicatorVariableList(); void createConstraints(); // friends friend class FunctionSerialization<LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE> >; friend class opengm::LinearConstraintFunctionBase<LabelOrderFunction<VALUE_TYPE,INDEX_TYPE, LABEL_TYPE> >; }; template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> struct LinearConstraintFunctionTraits<LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE> > { // typedefs typedef VALUE_TYPE ValueType; typedef INDEX_TYPE IndexType; typedef LABEL_TYPE LabelType; typedef LinearConstraint<ValueType, IndexType, LabelType> LinearConstraintType; typedef std::vector<LinearConstraintType> LinearConstraintsContainerType; typedef typename LinearConstraintsContainerType::const_iterator LinearConstraintsIteratorType; typedef typename LinearConstraintType::IndicatorVariablesContainerType IndicatorVariablesContainerType; typedef typename LinearConstraintType::IndicatorVariablesIteratorType IndicatorVariablesIteratorType; typedef typename LinearConstraintType::VariableLabelPairsIteratorType VariableLabelPairsIteratorType; typedef SubsequenceIterator<LinearConstraintsIteratorType, typename std::vector<size_t>::const_iterator> ViolatedLinearConstraintsIteratorType; typedef std::vector<double> ViolatedLinearConstraintsWeightsContainerType; typedef typename ViolatedLinearConstraintsWeightsContainerType::const_iterator ViolatedLinearConstraintsWeightsIteratorType; }; /// \cond HIDDEN_SYMBOLS /// FunctionRegistration template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> struct FunctionRegistration<LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE> > { enum ID { // TODO set final Id Id = opengm::FUNCTION_TYPE_ID_OFFSET - 2 }; }; /// FunctionSerialization template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> class FunctionSerialization<LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE> > { public: typedef typename LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::ValueType ValueType; static size_t indexSequenceSize(const LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>&); static size_t valueSequenceSize(const LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>&); template<class INDEX_OUTPUT_ITERATOR, class VALUE_OUTPUT_ITERATOR> static void serialize(const LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>&, INDEX_OUTPUT_ITERATOR, VALUE_OUTPUT_ITERATOR); template<class INDEX_INPUT_ITERATOR, class VALUE_INPUT_ITERATOR> static void deserialize( INDEX_INPUT_ITERATOR, VALUE_INPUT_ITERATOR, LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>&); }; /// \endcond /*********************** * class documentation * ***********************/ /*! \file label_order_function.hxx * \brief Provides implementation of a label order function. */ /*! \class LabelOrderFunction * \brief A linear constraint function class ensuring the correct label order * for two variables. * * This class implements a linear constraint function which ensures the correct * label order for two variables. Each label is associated with a weight and * the function checks the condition \f$w(l_1) \leq w(l_2)\f$ where * \f$w(l_1)\f$ is the weight of the label of the first variable and * \f$w(l_2)\f$ is the weight of the label of the second variable. * * \tparam VALUE_TYPE Value type. * \tparam INDEX_TYPE Index type. * \tparam LABEL_TYPE Label type. * * \ingroup functions */ /*! \var LabelOrderFunction::useSingleConstraint_ * \brief Describe the label order constraint in one single linear constraint. * * The label order constraint is described by the following linear constraint: * \f[ * \sum_i c_i \cdot v^0_i - \sum_j c_j \cdot v^1_j \quad \leq \quad 0. * \f] * Where \f$c_i\f$ is the weight for label i, \f$v^0_i\f$ is the indicator * variable of variable 0 which is 1 if variable 0 is set to label i and 0 * otherwise and \f$v^1_j\f$ is the indicator variable of variable 1. * * \note LabelOrderFunction::useSingleConstraint_ can be used in combination * with LabelOrderFunction::useMultipleConstraints_ in this case both * descriptions of the label order constraint are considered. At least * one of both variables has to be set to true. */ /*! \var LabelOrderFunction::useMultipleConstraints_ * \brief Describe the label order constraint in multiple linear constraints. * * The label order constraint is described by the following set of linear * constraints: * \f[ * c_i \cdot v^0_i - \sum_j c_j \cdot v^1_j \quad \leq \quad 0 \qquad \forall i \in \{0, ..., n - 1\}. * \f] * Where \f$c_i\f$ is the weight for label i, \f$v^0_i\f$ is the indicator * variable of variable 0 which is 1 if variable 0 is set to label i and 0 * otherwise, \f$v^1_j\f$ is the indicator variable of variable 1 and n is the * number of labels of variable 0. * * \note LabelOrderFunction::useMultipleConstraints_ can be used in combination * with LabelOrderFunction::useSingleConstraint_ in this case both * descriptions of the label order constraint are considered. At least * one of both variables has to be set to true. */ /*! \typedef LabelOrderFunction::LinearConstraintFunctionType * \brief Typedef of the LabelOrderFunction class with appropriate * template parameter. */ /*! \typedef LabelOrderFunction::LinearConstraintFunctionBaseType * \brief Typedef of the LinearConstraintFunctionBase class with appropriate * template parameter. */ /*! \typedef LabelOrderFunction::LinearConstraintFunctionTraitsType * \brief Typedef of the LinearConstraintFunctionTraits class with appropriate * template parameter. */ /*! \typedef LabelOrderFunction::ValueType * \brief Typedef of the VALUE_TYPE template parameter type from the class * LabelOrderFunction. */ /*! \typedef LabelOrderFunction::IndexType * \brief Typedef of the INDEX_TYPE template parameter type from the class * LabelOrderFunction. */ /*! \typedef LabelOrderFunction::LabelType * \brief Typedef of the LABEL_TYPE template parameter type from the class * LabelOrderFunction. */ /*! \typedef LabelOrderFunction::LabelOrderType * \brief Type to store the weights of the label order. */ /*! \typedef LabelOrderFunction::LinearConstraintType * \brief Typedef of the LinearConstraint class which is used to represent * linear constraints. */ /*! \typedef LabelOrderFunction::LinearConstraintsContainerType * \brief Defines the linear constraints container type which is used to store * multiple linear constraints. */ /*! \typedef LabelOrderFunction::LinearConstraintsIteratorType * \brief Defines the linear constraints container iterator type which is used * to iterate over the set of linear constraints. */ /*! \typedef LabelOrderFunction::IndicatorVariablesContainerType * \brief Defines the indicator variables container type which is used to store * the indicator variables used by the linear constraint function. */ /*! \typedef LabelOrderFunction::IndicatorVariablesIteratorType * \brief Defines the indicator variables container iterator type which is used * to iterate over the indicator variables used by the linear constraint * function. */ /*! \typedef LabelOrderFunction::VariableLabelPairsIteratorType * \brief Defines the variable label pairs iterator type which is used * to iterate over the variable label pairs of an indicator variable. */ /*! \typedef LabelOrderFunction::ViolatedLinearConstraintsIteratorType * \brief Defines the violated linear constraints iterator type which is used * to iterate over the set of violated linear constraints. */ /*! \typedef LabelOrderFunction::ViolatedLinearConstraintsWeightsContainerType * \brief Defines the violated linear constraints weights container type which * is used to store the weights of the violated linear constraints. */ /*! \typedef LabelOrderFunction::ViolatedLinearConstraintsWeightsIteratorType * \brief Defines the violated linear constraints weights iterator type which * is used to iterate over the weights of the violated linear * constraints. */ /*! \fn LabelOrderFunction::LabelOrderFunction() * \brief LabelOrderFunction constructor. * * This constructor will create an empty LabelOrderFunction. */ /*! \fn LabelOrderFunction::LabelOrderFunction(const LabelType numLabelsVar1, const LabelType numLabelsVar2, const LabelOrderType& labelOrder, const ValueType returnValid = 0.0, const ValueType returnInvalid = 1.0) * \brief LabelOrderFunction constructor. * * This constructor will create a LabelOrderFunction. * * \param[in] numLabelsVar1 Number of labels for the first variable. * \param[in] numLabelsVar2 Number of labels for the second variable. * \param[in] labelOrder Weights for the label order. * \param[in] returnValid The value which will be returned by the function * evaluation if no constraint is violated. * \param[in] returnInvalid The value which will be returned by the function * evaluation if at least one constraint is violated. */ /*! \fn LabelOrderFunction::LabelOrderFunction(const LabelType numLabelsVar1, const LabelType numLabelsVar2, ITERATOR_TYPE labelOrderBegin, const ValueType returnValid = 0.0, const ValueType returnInvalid = 1.0) * \brief LabelOrderFunction constructor. * * This constructor will create a LabelOrderFunction. * * \tparam ITERATOR_TYPE Iterator to iterate over the weights of the label * order. * * \param[in] numLabelsVar1 Number of labels for the first variable. * \param[in] numLabelsVar2 Number of labels for the second variable. * \param[in] labelOrderBegin Iterator pointing to the begin of the weights for * the label order. * \param[in] labelOrderBegin Iterator pointing to the end of the weights for * the label order. * \param[in] returnValid The value which will be returned by the function * evaluation if no constraint is violated. * \param[in] returnInvalid The value which will be returned by the function * evaluation if at least one constraint is violated. */ /*! \fn LabelOrderFunction::~LabelOrderFunction() * \brief LabelOrderFunction destructor. */ /*! \fn LabelOrderFunction::ValueType LabelOrderFunction::operator()(Iterator statesBegin) const * \brief Function evaluation. * * \param[in] statesBegin Iterator pointing to the begin of a sequence of * labels for the variables of the function. * * \return LabelOrderFunction::returnValid_ if no constraint is violated * by the labeling. LabelOrderFunction::returnInvalid_ if at * least one constraint is violated by the labeling. */ /*! \fn size_t LabelOrderFunction::shape(const size_t i) const * \brief Number of labels of the indicated input variable. * * \param[in] i Index of the variable. * * \return Returns the number of labels of the i-th variable. */ /*! \fn size_t LabelOrderFunction::dimension() const * \brief Number of input variables. * * \return Returns the number of variables. */ /*! \fn size_t LabelOrderFunction::size() const * \brief Number of parameters. * * \return Returns the number of parameters. */ /*! \fn LabelOrderFunction::ValueType LabelOrderFunction::min() const * \brief Minimum value of the label order function. * * \return Returns the minimum value of LabelOrderFunction::returnValid_ * and LabelOrderFunction::returnInvalid_. */ /*! \fn LabelOrderFunction::ValueType LabelOrderFunction::max() const * \brief Maximum value of the label order function. * * \return Returns the maximum value of LabelOrderFunction::returnValid_ * and LabelOrderFunction::returnInvalid_. */ /*! \fn MinMaxFunctor LabelOrderFunction::minMax() const * \brief Get minimum and maximum at the same time. * * \return Returns a functor containing the minimum and the maximum value of * the label order function. */ /*! \var LabelOrderFunction::dimension_ * \brief The dimension of the label order function. */ /*! \var LabelOrderFunction::numLabelsVar1_ * \brief The number of labels of the first variable. */ /*! \var LabelOrderFunction::numLabelsVar2_ * \brief The number of labels of the second variable. */ /*! \var LabelOrderFunction::size_ * \brief Stores the size of the label order function. */ /*! \var LabelOrderFunction::labelOrder_ * \brief The weights defining the label order. */ /*! \var LabelOrderFunction::returnValid_ * \brief Stores the return value of LabelOrderFunction::operator() if no * constraint is violated. */ /*! \var LabelOrderFunction::returnInvalid_ * \brief Stores the return value of LabelOrderFunction::operator() if at * least one constraint is violated. */ /*! \var LabelOrderFunction::constraints_ * \brief Stores the linear constraints of the label order function. */ /*! \var LabelOrderFunction::violatedConstraintsIds_ * \brief Stores the indices of the violated constraints which are detected by * LabelOrderFunction::challenge and * LabelOrderFunction::challengeRelaxed. */ /*! \var LabelOrderFunction::violatedConstraintsWeights_ * \brief Stores the weights of the violated constraints which are detected by * LabelOrderFunction::challenge and * LabelOrderFunction::challengeRelaxed. */ /*! \var LabelOrderFunction::indicatorVariableList_ * \brief A list of all indicator variables present in the label order * function. */ /*! \fn LabelOrderFunction::LinearConstraintsIteratorType LabelOrderFunction::linearConstraintsBegin_impl() const * \brief Implementation of * LinearConstraintFunctionBase::linearConstraintsBegin. */ /*! \fn LabelOrderFunction::LinearConstraintsIteratorType LabelOrderFunction::linearConstraintsEnd_impl() const * \brief Implementation of LinearConstraintFunctionBase::linearConstraintsEnd. */ /*! \fn LabelOrderFunction::IndicatorVariablesIteratorType LabelOrderFunction::indicatorVariablesOrderBegin_impl() const * \brief Implementation of * LinearConstraintFunctionBase::indicatorVariablesOrderBegin. */ /*! \fn LabelOrderFunction::IndicatorVariablesIteratorType LabelOrderFunction::indicatorVariablesOrderEnd_impl() const * \brief Implementation of * LinearConstraintFunctionBase::indicatorVariablesOrderEnd. */ /*! \fn void LabelOrderFunction::challenge_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance = 0.0) const * \brief Implementation of LinearConstraintFunctionBase::challenge. */ /*! \fn void LabelOrderFunction::challengeRelaxed_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance = 0.0) const * \brief Implementation of LinearConstraintFunctionBase::challengeRelaxed. */ /*! \fn bool LabelOrderFunction::checkLabelOrder() const * \brief Check label order weights. Only used for assertion in debug mode. * * \return Returns true if the number of weights is large enough to define a * weight for each label of both variables. False otherwise. */ /*! \fn bool LabelOrderFunction::fillIndicatorVariableList() * \brief Helper function to fill LabelOrderFunction::indicatorVariableList_ * with all indicator variables used by the label order function. */ /*! \fn bool LabelOrderFunction::createConstraints() * \brief Helper function to create all linear constraints which are implied by * the label order function. */ /****************** * implementation * ******************/ template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::LabelOrderFunction() : numLabelsVar1_(), numLabelsVar2_(), size_(), labelOrder_(), returnValid_(), returnInvalid_(), constraints_(), violatedConstraintsIds_(), violatedConstraintsWeights_(), indicatorVariableList_() { if(!(useSingleConstraint_ || useMultipleConstraints_)) { throw opengm::RuntimeError("Unsupported configuration for label order function. At least one of LabelOrderFunction::useSingleConstraint_ and LabelOrderFunction::useMultipleConstraints_ has to be set to true."); } } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::LabelOrderFunction(const LabelType numLabelsVar1, const LabelType numLabelsVar2, const LabelOrderType& labelOrder, const ValueType returnValid, const ValueType returnInvalid) : numLabelsVar1_(numLabelsVar1), numLabelsVar2_(numLabelsVar2), size_(numLabelsVar1_ * numLabelsVar2_), labelOrder_(labelOrder), returnValid_(returnValid), returnInvalid_(returnInvalid), constraints_((useSingleConstraint_ ? 1 : 0) + (useMultipleConstraints_ ? numLabelsVar1_ : 0)), violatedConstraintsIds_((useSingleConstraint_ ? 1 : 0) + (useMultipleConstraints_ ? numLabelsVar1_ : 0)), violatedConstraintsWeights_((useSingleConstraint_ ? 1 : 0) + (useMultipleConstraints_ ? numLabelsVar1_ : 0)), indicatorVariableList_(numLabelsVar1_ + numLabelsVar2_) { OPENGM_ASSERT(checkLabelOrder()); if(!(useSingleConstraint_ || useMultipleConstraints_)) { throw opengm::RuntimeError("Unsupported configuration for label order function. At least one of LabelOrderFunction::useSingleConstraint_ and LabelOrderFunction::useMultipleConstraints_ has to be set to true."); } // fill indicator variable list fillIndicatorVariableList(); // create linear constraints createConstraints(); } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> template <class ITERATOR_TYPE> inline LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::LabelOrderFunction(const LabelType numLabelsVar1, const LabelType numLabelsVar2, ITERATOR_TYPE labelOrderBegin, const ValueType returnValid, const ValueType returnInvalid) : numLabelsVar1_(numLabelsVar1), numLabelsVar2_(numLabelsVar2), size_(numLabelsVar1_ * numLabelsVar2_), labelOrder_(labelOrderBegin, labelOrderBegin + std::max(numLabelsVar1_, numLabelsVar2_)), returnValid_(returnValid), returnInvalid_(returnInvalid), constraints_((useSingleConstraint_ ? 1 : 0) + (useMultipleConstraints_ ? numLabelsVar1_ : 0)), violatedConstraintsIds_((useSingleConstraint_ ? 1 : 0) + (useMultipleConstraints_ ? numLabelsVar1_ : 0)), violatedConstraintsWeights_((useSingleConstraint_ ? 1 : 0) + (useMultipleConstraints_ ? numLabelsVar1_ : 0)), indicatorVariableList_(numLabelsVar1_ + numLabelsVar2_) { OPENGM_ASSERT(checkLabelOrder()); if(!(useSingleConstraint_ || useMultipleConstraints_)) { throw opengm::RuntimeError("Unsupported configuration for label order function. At least one of LabelOrderFunction::useSingleConstraint_ and LabelOrderFunction::useMultipleConstraints_ has to be set to true."); } // fill indicator variable list fillIndicatorVariableList(); // create linear constraints createConstraints(); } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::~LabelOrderFunction() { } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> template<class Iterator> inline typename LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::ValueType LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::operator()(Iterator statesBegin) const { if(labelOrder_[statesBegin[0]] <= labelOrder_[statesBegin[1]]) { return returnValid_; } else { return returnInvalid_; } } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline size_t LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::shape(const size_t i) const { OPENGM_ASSERT(i < dimension_); return (i==0 ? numLabelsVar1_ : numLabelsVar2_); } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline size_t LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::dimension() const { return dimension_; } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline size_t LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::size() const { return size_; } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline typename LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::ValueType LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::min() const { return returnValid_ < returnInvalid_ ? returnValid_ : returnInvalid_; } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline typename LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::ValueType LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::max() const { return returnValid_ > returnInvalid_ ? returnValid_ : returnInvalid_; } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline MinMaxFunctor<typename LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::ValueType> LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::minMax() const { if(returnValid_ < returnInvalid_) { return MinMaxFunctor<VALUE_TYPE>(returnValid_, returnInvalid_); } else { return MinMaxFunctor<VALUE_TYPE>(returnInvalid_, returnValid_); } } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline typename LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::LinearConstraintsIteratorType LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::linearConstraintsBegin_impl() const { return constraints_.begin(); } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline typename LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::LinearConstraintsIteratorType LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::linearConstraintsEnd_impl() const { return constraints_.end(); } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline typename LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::IndicatorVariablesIteratorType LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::indicatorVariablesOrderBegin_impl() const { return indicatorVariableList_.begin(); } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline typename LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::IndicatorVariablesIteratorType LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::indicatorVariablesOrderEnd_impl() const { return indicatorVariableList_.end(); } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> template <class LABEL_ITERATOR> inline void LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::challenge_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance) const { const ValueType weight = labelOrder_[labelingBegin[0]] - labelOrder_[labelingBegin[1]]; if(weight <= tolerance) { violatedConstraintsBegin = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), 0); violatedConstraintsEnd = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), 0); violatedConstraintsWeightsBegin = violatedConstraintsWeights_.begin(); return; } else { if(useSingleConstraint_) { violatedConstraintsIds_[0] = 0; violatedConstraintsWeights_[0] = weight; } if(useMultipleConstraints_) { violatedConstraintsIds_[(useSingleConstraint_ ? 1 : 0)] = labelingBegin[0] + (useSingleConstraint_ ? 1 : 0); violatedConstraintsWeights_[(useSingleConstraint_ ? 1 : 0)] = weight; } violatedConstraintsBegin = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), 0); violatedConstraintsEnd = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), (useSingleConstraint_ ? 1 : 0) + (useMultipleConstraints_ ? 1 : 0)); violatedConstraintsWeightsBegin = violatedConstraintsWeights_.begin(); return; } } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> template <class LABEL_ITERATOR> inline void LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::challengeRelaxed_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance) const { size_t numViolatedConstraints = 0; double weightVar2 = 0.0; for(IndexType i = 0; i < numLabelsVar2_; ++i) { weightVar2 -= labelOrder_[i] * labelingBegin[numLabelsVar1_ + i]; } double totalWeight = weightVar2; for(IndexType i = 0; i < numLabelsVar1_; ++i) { double currentWeight = (labelOrder_[i] * labelingBegin[i]); // - (); if(useSingleConstraint_) { totalWeight += currentWeight; } if(useMultipleConstraints_) { currentWeight += weightVar2; if(currentWeight > tolerance) { violatedConstraintsIds_[numViolatedConstraints] = i + (useSingleConstraint_ ? 1 : 0); violatedConstraintsWeights_[numViolatedConstraints] = currentWeight; ++numViolatedConstraints; } } } if(useSingleConstraint_) { if(totalWeight > tolerance) { violatedConstraintsIds_[numViolatedConstraints] = 0; violatedConstraintsWeights_[numViolatedConstraints] = totalWeight; ++numViolatedConstraints; } } violatedConstraintsBegin = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), 0); violatedConstraintsEnd = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), numViolatedConstraints); violatedConstraintsWeightsBegin = violatedConstraintsWeights_.begin(); } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline bool LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::checkLabelOrder() const { if(labelOrder_.size() < std::max(numLabelsVar1_, numLabelsVar2_)) { return false; } else { return true; } } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline void LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::fillIndicatorVariableList() { for(size_t i = 0; i < numLabelsVar1_; ++i) { indicatorVariableList_[i] = typename LinearConstraintType::IndicatorVariableType(IndexType(0), LabelType(i)); } for(size_t i = 0; i < numLabelsVar2_; ++i) { indicatorVariableList_[numLabelsVar1_ + i] = typename LinearConstraintType::IndicatorVariableType(IndexType(1), LabelType(i)); } } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline void LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::createConstraints() { if(useSingleConstraint_) { constraints_[0].setBound(0.0); constraints_[0].setConstraintOperator(LinearConstraintType::LinearConstraintOperatorType::LessEqual); for(size_t i = 0; i < numLabelsVar1_; ++i) { constraints_[0].add(typename LinearConstraintType::IndicatorVariableType(IndexType(0), LabelType(i)), labelOrder_[i]); } for(size_t i = 0; i < numLabelsVar2_; ++i) { constraints_[0].add(typename LinearConstraintType::IndicatorVariableType(IndexType(1), LabelType(i)), -labelOrder_[i]); } } if(useMultipleConstraints_) { for(size_t i = 0; i < numLabelsVar1_; ++i) { constraints_[i + (useSingleConstraint_ ? 1 : 0)].add(typename LinearConstraintType::IndicatorVariableType(IndexType(0), LabelType(i)), labelOrder_[i]); constraints_[i + (useSingleConstraint_ ? 1 : 0)].setBound(0.0); constraints_[i + (useSingleConstraint_ ? 1 : 0)].setConstraintOperator(LinearConstraintType::LinearConstraintOperatorType::LessEqual); for(size_t j = 0; j < numLabelsVar2_; ++j) { constraints_[i + (useSingleConstraint_ ? 1 : 0)].add(typename LinearConstraintType::IndicatorVariableType(IndexType(1), LabelType(j)), -labelOrder_[j]); } } } } /// \cond HIDDEN_SYMBOLS template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline size_t FunctionSerialization<LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE> >::indexSequenceSize(const LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>& src) { const size_t shapeSize = 2; // numLabelsVar1 and numLabelsVar2 const size_t labelOrderSize = 1; const size_t totalIndexSize = shapeSize + labelOrderSize; return totalIndexSize; } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> inline size_t FunctionSerialization<LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE> >::valueSequenceSize(const LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>& src) { const size_t labelOrderSize = src.labelOrder_.size(); const size_t returnSize = 2; //returnValid and returnInvalid const size_t totalValueSize = labelOrderSize + returnSize; return totalValueSize; } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> template<class INDEX_OUTPUT_ITERATOR, class VALUE_OUTPUT_ITERATOR> inline void FunctionSerialization<LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE> >::serialize(const LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>& src, INDEX_OUTPUT_ITERATOR indexOutIterator, VALUE_OUTPUT_ITERATOR valueOutIterator) { // index output // shape *indexOutIterator = src.numLabelsVar1_; ++indexOutIterator; *indexOutIterator = src.numLabelsVar2_; ++indexOutIterator; // label order size *indexOutIterator = src.labelOrder_.size(); // value output // label order for(size_t i = 0; i < src.labelOrder_.size(); ++i) { *valueOutIterator = src.labelOrder_[i]; ++valueOutIterator; } // return values *valueOutIterator = src.returnValid_; ++valueOutIterator; *valueOutIterator = src.returnInvalid_; } template<class VALUE_TYPE, class INDEX_TYPE, class LABEL_TYPE> template<class INDEX_INPUT_ITERATOR, class VALUE_INPUT_ITERATOR> inline void FunctionSerialization<LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE> >::deserialize( INDEX_INPUT_ITERATOR indexInIterator, VALUE_INPUT_ITERATOR valueInIterator, LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>& dst) { // index input // shape const size_t numLabelsVar1 = *indexInIterator; ++indexInIterator; const size_t numLabelsVar2 = *indexInIterator; ++indexInIterator; // label order size const size_t labelOrderSize = *indexInIterator; // value input typename LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>::LabelOrderType labelOrder(valueInIterator, valueInIterator + labelOrderSize); valueInIterator += labelOrderSize; // valid value VALUE_TYPE returnValid = *valueInIterator; ++valueInIterator; // invalid value VALUE_TYPE returnInvalid = *valueInIterator; dst = LabelOrderFunction<VALUE_TYPE, INDEX_TYPE, LABEL_TYPE>(numLabelsVar1, numLabelsVar2, labelOrder, returnValid, returnInvalid); } /// \endcond } // namespace opengm #endif /* OPENGM_LABEL_ORDER_FUNCTION_HXX_ */
48.885787
361
0.741005
jasjuang
091037d464c88f3b2609bbc9a494b4f1ac29dd5d
4,219
cpp
C++
src/RayTracerLib/shapes/Box.cpp
CantTouchDis/ElTrazadoDeRayos
8975f76bcf990b94364e595b3b9f0b4128f6c56e
[ "MIT", "BSL-1.0", "MIT-0", "BSD-3-Clause" ]
null
null
null
src/RayTracerLib/shapes/Box.cpp
CantTouchDis/ElTrazadoDeRayos
8975f76bcf990b94364e595b3b9f0b4128f6c56e
[ "MIT", "BSL-1.0", "MIT-0", "BSD-3-Clause" ]
null
null
null
src/RayTracerLib/shapes/Box.cpp
CantTouchDis/ElTrazadoDeRayos
8975f76bcf990b94364e595b3b9f0b4128f6c56e
[ "MIT", "BSL-1.0", "MIT-0", "BSD-3-Clause" ]
1
2021-05-05T08:37:05.000Z
2021-05-05T08:37:05.000Z
/* The MIT License (MIT) Copyright (c) 2014 CantTouchDis <bauschp@informatik.uni-freiburg.de> Copyright (c) 2014 brio1009 <christoph1009@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "./Box.h" #include <glm/glm.hpp> #include <algorithm> #include <cstdio> #include <limits> #include <utility> #include <vector> #include "./Constants.h" #include "../Solver.h" #include "./Ray.h" using std::vector; const char* Box::name = "Box"; // _____________________________________________________________________________ Box::Box(REAL x, REAL y, REAL z) : _rX(x), _rY(y), _rZ(z) { } // _____________________________________________________________________________ vector<REAL> Box::intersect(const Ray& ray) const { // Bring vector to unit space. Ray transRay = _inverseTransform * ray; // This is the slab method. const glm::vec4& rayDir = transRay.direction(); glm::vec4 invRayDir; invRayDir.x = (!solve::isZero(rayDir.x)) ? (1.0f / rayDir.x) : std::numeric_limits<float>::max(); invRayDir.y = (!solve::isZero(rayDir.y)) ? (1.0f / rayDir.y) : std::numeric_limits<float>::max(); invRayDir.z = (!solve::isZero(rayDir.z)) ? (1.0f / rayDir.z) : std::numeric_limits<float>::max(); invRayDir.w = 0.0f; glm::vec4 t1 = (getMinPosition() - transRay.origin()) * invRayDir; glm::vec4 t2 = (getMaxPosition() - transRay.origin()) * invRayDir; glm::vec4 tMin = glm::min(t1, t2); glm::vec4 tMax = glm::max(t1, t2); vector<REAL> hits(2); hits[0] = std::max(tMin.x, std::max(tMin.y, tMin.z)); hits[1] = std::min(tMax.x, std::min(tMax.y, tMax.z)); if (hits[1] >= hits[0]) return hits; // Else. return vector<REAL>(); } // _____________________________________________________________________________ glm::vec4 Box::getNormalAt(const glm::vec4& p) const { glm::vec4 pInObjectCoord = _inverseTransform * p; // We just have six cases (three real ones + the inverse). // Just check where we are the closest. glm::vec3 extent(_rX, _rY, _rZ); glm::vec3 dis = 0.5f * extent - glm::abs(glm::vec3(pInObjectCoord)); glm::vec4 out; if (dis.x < dis.y && dis.x < dis.z) { // Normal in x direction. if (pInObjectCoord.x <= 0) { out = glm::vec4(-1, 0, 0, 0); } else { out = glm::vec4(1, 0, 0, 0); } } else if (dis.y < dis.x && dis.y < dis.z) { // Normal in y direction. if (pInObjectCoord.y <= 0) { out = glm::vec4(0, -1, 0, 0); } else { out = glm::vec4(0, 1, 0, 0); } } else { // Normal in z direction. if (pInObjectCoord.z <= 0) { out = glm::vec4(0, 0, -1, 0); } else { out = glm::vec4(0, 0, 1, 0); } } return glm::normalize(_transformation * out); } // _____________________________________________________________________________ glm::vec4 Box::getMinPosition() const { // We just calculate the position. return glm::vec4(-0.5 * _rX, -0.5 * _rY, -0.5 * _rZ, 1.0); } // _____________________________________________________________________________ glm::vec4 Box::getMaxPosition() const { // We just calculate the position. return glm::vec4(0.5 * _rX, 0.5 * _rY, 0.5 * _rZ, 1.0); }
33.220472
80
0.670301
CantTouchDis
09155d5072ad449f01b8bb4097ab3d71f88d27bf
2,165
hpp
C++
Code/GraphicsCore/Pipeline.hpp
DhirajWishal/Flint
0750bd515de0b5cc3d23f7c2282c50ca483dff24
[ "Apache-2.0" ]
null
null
null
Code/GraphicsCore/Pipeline.hpp
DhirajWishal/Flint
0750bd515de0b5cc3d23f7c2282c50ca483dff24
[ "Apache-2.0" ]
1
2021-10-30T11:19:53.000Z
2021-10-30T11:19:54.000Z
Code/GraphicsCore/Pipeline.hpp
DhirajWishal/Flint
0750bd515de0b5cc3d23f7c2282c50ca483dff24
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 Dhiraj Wishal // SPDX-License-Identifier: Apache-2.0 #pragma once #include "DeviceBoundObject.hpp" namespace Flint { class RenderTarget; class ResourcePackager; class ResourcePackage; /** * Flint pipeline object. * This object is used to store information about a rendering or compute pipeline. */ class Pipeline : public DeviceBoundObject { friend RenderTarget; public: /** * Default constructor. * * @param pDevice The device pointer. * @param pipelineName The name of the pipeline. This name is given to the pipeline cache object created upon destruction. Make sure that this name is unique. * If you wish to not save cache externally, keep this field empty (""). */ Pipeline(const std::shared_ptr<Device>& pDevice, const std::string& pipelineName) : DeviceBoundObject(pDevice), mPipelineName(pipelineName) {} /** * Reload the shaders. * NOTE: This will only reload the shaders and will perform reflection on the shader code. If any input, output or uniform was changed, make sure to reflect them in * input data. */ virtual void ReloadShaders() = 0; protected: /** * Create the resource packagers. */ virtual void CreateResourcePackagers() = 0; /** * Write the pipeline cache data to an external file. * If the file does not exist, this creates a new file. The file name is "<pipeline name>.fpc". The FPC extension is Flint Pipeline Cache. * * @param size The size of the data block. * @param pData The data to be written. */ void WriteDataToCacheFile(const uint64 size, unsigned char* pData) const; /** * Read the pipeline cache data from an external file. * * @return The pair of size and data. */ std::pair<uint64, unsigned char*> ReadDataFromCacheFile() const; public: /** * Create a new resource package. * * @param index The set index. * @return The package. */ std::shared_ptr<ResourcePackage> CreateResourcePackage(const uint64 index); protected: std::string mPipelineName = ""; std::vector<std::shared_ptr<ResourcePackager>> pResourcePackagers = {}; bool bShouldPrepareResources = true; }; }
28.486842
166
0.705312
DhirajWishal
09175a1772e49e91cbe95ac21f6acd5fc93d53db
6,153
hpp
C++
src/math/multiprecision.hpp
yDMhaven/pinocchio
fabed17d5ad0dc1c8d251c64cfa656a0215469a5
[ "BSD-2-Clause-FreeBSD" ]
1
2020-04-07T07:23:34.000Z
2020-04-07T07:23:34.000Z
src/math/multiprecision.hpp
yDMhaven/pinocchio
fabed17d5ad0dc1c8d251c64cfa656a0215469a5
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/math/multiprecision.hpp
yDMhaven/pinocchio
fabed17d5ad0dc1c8d251c64cfa656a0215469a5
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
// // Copyright (c) 2020 INRIA // #ifndef __pinocchio_math_mutliprecision_hpp__ #define __pinocchio_math_mutliprecision_hpp__ #include "pinocchio/math/fwd.hpp" #include <boost/multiprecision/number.hpp> #include <Eigen/Dense> namespace Eigen { namespace internal { template <class Backend, boost::multiprecision::expression_template_option ExpressionTemplates, typename Scalar> struct cast_impl<boost::multiprecision::number<Backend, ExpressionTemplates>,Scalar> { #if EIGEN_VERSION_AT_LEAST(3,2,90) EIGEN_DEVICE_FUNC #endif static inline Scalar run(const boost::multiprecision::number<Backend, ExpressionTemplates> & x) { return x.template convert_to<Scalar>(); } }; } } //namespace Eigen #ifndef BOOST_MP_EIGEN_HPP // Code adapted from <boost/multiprecision/eigen.hpp> // Copyright 2018 John Maddock. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) namespace Eigen { template <class Backend, boost::multiprecision::expression_template_option ExpressionTemplates> struct NumTraits<boost::multiprecision::number<Backend, ExpressionTemplates> > { typedef boost::multiprecision::number<Backend, ExpressionTemplates> self_type; #if BOOST_VERSION / 100 % 1000 >= 68 typedef typename boost::multiprecision::scalar_result_from_possible_complex<self_type>::type Real; #else typedef self_type Real; #endif typedef self_type NonInteger; // Not correct but we can't do much better?? typedef double Literal; typedef self_type Nested; enum { #if BOOST_VERSION / 100 % 1000 >= 68 IsComplex = boost::multiprecision::number_category<self_type>::value == boost::multiprecision::number_kind_complex, #else IsComplex = 0, #endif IsInteger = boost::multiprecision::number_category<self_type>::value == boost::multiprecision::number_kind_integer, ReadCost = 1, AddCost = 4, MulCost = 8, IsSigned = std::numeric_limits<self_type>::is_specialized ? std::numeric_limits<self_type>::is_signed : true, RequireInitialization = 1 }; static Real epsilon() { return std::numeric_limits<Real>::epsilon(); } static Real dummy_precision() { return 1000 * epsilon(); } static Real highest() { return (std::numeric_limits<Real>::max)(); } static Real lowest() { return (std::numeric_limits<Real>::min)(); } static int digits10_imp(const boost::mpl::true_&) { return std::numeric_limits<Real>::digits10; } template <bool B> static int digits10_imp(const boost::mpl::bool_<B>&) { return Real::default_precision(); } static int digits10() { return digits10_imp(boost::mpl::bool_ < std::numeric_limits<Real>::digits10 && (std::numeric_limits<Real>::digits10 != INT_MAX) ? true : false > ()); } }; template <class tag, class Arg1, class Arg2, class Arg3, class Arg4> struct NumTraits<boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4> > : public NumTraits<typename boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type> { }; namespace internal { template <class Backend, boost::multiprecision::expression_template_option ExpressionTemplates, class tag, class Arg1, class Arg2, class Arg3, class Arg4> struct scalar_product_traits<boost::multiprecision::number<Backend, ExpressionTemplates>, boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4> > { // BOOST_STATIC_ASSERT(boost::is_convertible<typename boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type, boost::multiprecision::number<Backend, ExpressionTemplates> >::value, "Interoperability with this arithmetic type is not supported."); typedef boost::multiprecision::number<Backend, ExpressionTemplates> ReturnType; }; template <class tag, class Arg1, class Arg2, class Arg3, class Arg4, class Backend, boost::multiprecision::expression_template_option ExpressionTemplates> struct scalar_product_traits<boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>, boost::multiprecision::number<Backend, ExpressionTemplates> > { // BOOST_STATIC_ASSERT(boost::is_convertible<typename boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type, boost::multiprecision::number<Backend, ExpressionTemplates> >::value, "Interoperability with this arithmetic type is not supported."); typedef boost::multiprecision::number<Backend, ExpressionTemplates> ReturnType; }; template <typename Scalar> struct conj_retval; template <typename Scalar, bool IsComplex> struct conj_impl; template <class tag, class Arg1, class Arg2, class Arg3, class Arg4> struct conj_retval<boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4> > { typedef typename boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type type; }; template <class tag, class Arg1, class Arg2, class Arg3, class Arg4> struct conj_impl<boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>, true> { #if EIGEN_VERSION_AT_LEAST(3,2,90) EIGEN_DEVICE_FUNC #endif static inline typename boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>::result_type run(const typename boost::multiprecision::detail::expression<tag, Arg1, Arg2, Arg3, Arg4>& x) { return conj(x); } }; } // namespace internal } // namespace Eigen #endif // ifndef BOOST_MP_EIGEN_HPP #endif // ifndef __pinocchio_math_mutliprecision_hpp__
41.295302
278
0.671705
yDMhaven
091bdd16b600da8268d9fca5284b072e5e926705
1,803
hpp
C++
include/variadic/detail/numerate.hpp
AnatoliyProjects/variadic
f34a973e527218e3ba0f8146ccbf478d351f6cb2
[ "BSL-1.0" ]
null
null
null
include/variadic/detail/numerate.hpp
AnatoliyProjects/variadic
f34a973e527218e3ba0f8146ccbf478d351f6cb2
[ "BSL-1.0" ]
null
null
null
include/variadic/detail/numerate.hpp
AnatoliyProjects/variadic
f34a973e527218e3ba0f8146ccbf478d351f6cb2
[ "BSL-1.0" ]
2
2020-05-31T11:50:35.000Z
2020-06-07T18:38:12.000Z
// Copyright 2020 Anatoliy Petrov // (apetrov.projects@gmail.com) // // Distributed under the Boost Software License, Version 1.0. // // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt #ifndef VARIADIC_DETAIL_NUMERATE_HPP #define VARIADIC_DETAIL_NUMERATE_HPP /* variadic */ #include <variadic/token.hpp> //token getters /* boost */ #include <boost/preprocessor/seq/to_list.hpp> #include <boost/preprocessor/list/for_each.hpp> #include <boost/preprocessor/control/if.hpp> #include <boost/preprocessor/facilities/expand.hpp> #include <boost/preprocessor/facilities/expand.hpp> #include <boost/preprocessor/cat.hpp> // Conversion to the list is necessary to bypass the restriction on the depth // of nesting BOOST_PP_FOR loop (especially in case where VDC_EXPAND calls // directly from VDC_HANDLER) #define VDC_DETAIL_NUMERATE(expr, pos) \ BOOST_PP_LIST_FOR_EACH( \ VDC_DETAIL_NUMERATOR, \ pos, \ BOOST_PP_SEQ_TO_LIST(expr) \ ) #define VDC_DETAIL_NUMERATOR(unspec, pos, token) \ BOOST_PP_IF( \ VDC_DETAIL_GET_FLAG(token), \ VDC_DETAIL_TOKEN_NUMERATOR(token, pos), \ VDC_DETAIL_TOKEN_FN_NUMERATOR(token, pos) \ ) #define VDC_DETAIL_PAIR(a, b) a, b #define VDC_DETAIL_TOKEN_NUMERATOR(token, pos) \ BOOST_PP_IF( \ VDC_DETAIL_IS_NUMBERED(token), \ BOOST_PP_CAT( \ VDC_DETAIL_GET_STR(token), \ VDC_DETAIL_GET_POS(token, pos) \ ), \ VDC_DETAIL_GET_STR(token) \ ) #define VDC_DETAIL_TOKEN_FN_NUMERATOR(token, pos) \ BOOST_PP_IF( \ VDC_DETAIL_IS_NUMBERED(token), \ VDC_DETAIL_GET_FN(token)( VDC_DETAIL_GET_POS(token, pos) ), \ VDC_DETAIL_GET_FN(token)() \ ) #endif /* VARIADIC_DETAIL_NUMERATE_HPP */
29.557377
77
0.707709
AnatoliyProjects
091c0069064b6f7c73f3dd9088f2728cbd3aefbc
5,478
cpp
C++
src/utils/xrLC_Light/Lightmap.cpp
acidicMercury8/xray-1.5
ae094d82b76a8ce916e196654c163894bbf00146
[ "Linux-OpenIB" ]
5
2021-10-30T09:36:07.000Z
2021-12-30T08:14:32.000Z
src/utils/xrLC_Light/Lightmap.cpp
Samsuper12/ixray-1.5
8070f833f8216d4ead294a9f19b7cd123bb76ba3
[ "Linux-OpenIB" ]
null
null
null
src/utils/xrLC_Light/Lightmap.cpp
Samsuper12/ixray-1.5
8070f833f8216d4ead294a9f19b7cd123bb76ba3
[ "Linux-OpenIB" ]
2
2020-08-04T17:23:16.000Z
2020-10-16T16:53:38.000Z
// Lightmap.cpp: implementation of the CLightmap class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" //#include "build.h" #include "Lightmap.h" #include "xrDeflector.h" #include "xrDXTC.h" #include "xrImage_Filter.h" #include "xrface.h" #include "serialize.h" #include "ETextureParams.h" #pragma comment(lib,"dxt.lib") extern "C" bool __declspec(dllimport) __stdcall DXTCompress(LPCSTR out_name, u8* raw_data, u8* normal_map, u32 w, u32 h, u32 pitch, STextureParams* fmt, u32 depth); //extern BOOL ApplyBorders (lm_layer &lm, u32 ref); ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CLightmap::CLightmap() { } CLightmap::~CLightmap() { } CLightmap* CLightmap::read_create ( ) { return xr_new<CLightmap>(); } void CLightmap::Capture (CDeflector *D, int b_u, int b_v, int s_u, int s_v, BOOL bRotated) { // Allocate 512x512 texture if needed if (lm.surface.empty()) lm.create(c_LMAP_size,c_LMAP_size); // Addressing xr_vector<UVtri> tris; D->RemapUV (tris,b_u+BORDER,b_v+BORDER,s_u-2*BORDER,s_v-2*BORDER,c_LMAP_size,c_LMAP_size,bRotated); // Capture faces and setup their coords for (UVIt T=tris.begin(); T!=tris.end(); T++) { UVtri& P = *T; Face *F = P.owner; F->lmap_layer = this; F->AddChannel (P.uv[0], P.uv[1], P.uv[2]); } // Perform BLIT lm_layer& L = D->layer; if (!bRotated) { u32 real_H = (L.height + 2*BORDER); u32 real_W = (L.width + 2*BORDER); blit (lm,c_LMAP_size,c_LMAP_size,L,real_W,real_H,b_u,b_v,254-BORDER); } else { u32 real_H = (L.height + 2*BORDER); u32 real_W = (L.width + 2*BORDER); blit_r (lm,c_LMAP_size,c_LMAP_size,L,real_W,real_H,b_u,b_v,254-BORDER); } } ////////////////////////////////////////////////////////////////////// IC u32 convert(float a) { if (a<=0) return 0; else if (a>=1) return 255; else return iFloor(a*255.f); } IC void pixel (int x, int y, b_texture* T, u32 C=color_rgba(0,255,0,0)) { if (x<0) return; else if (x>=(int)T->dwWidth) return; if (y<0) return; else if (y>=(int)T->dwHeight) return; T->pSurface[y*T->dwWidth+x] = C; } IC void line ( int x1, int y1, int x2, int y2, b_texture* T ) { int dx = _abs(x2 - x1); int dy = _abs(y2 - y1); int sx = x2 >= x1 ? 1 : -1; int sy = y2 >= y1 ? 1 : -1; if ( dy <= dx ){ int d = ( dy << 1 ) - dx; int d1 = dy << 1; int d2 = ( dy - dx ) << 1; pixel(x1,y1,T); for (int x = x1 + sx, y = y1, i = 1; i <= dx; i++, x += sx){ if ( d > 0){ d += d2; y += sy; }else d += d1; pixel(x,y,T); } }else{ int d = ( dx << 1 ) - dy; int d1 = dx << 1; int d2 = ( dx - dy ) << 1; pixel(x1,y1,T); for (int x = x1, y = y1 + sy, i = 1; i <= dy; i++, y += sy ){ if ( d > 0){ d += d2; x += sx; }else d += d1; pixel(x,y,T); } } } void CLightmap::Save( LPCSTR path ) { static int lmapNameID = 0; ++lmapNameID; Phase ("Saving..."); // Borders correction Status ("Borders..."); for (u32 _y=0; _y<c_LMAP_size; _y++) { for (u32 _x=0; _x<c_LMAP_size; _x++) { u32 offset = _y*c_LMAP_size+_x; if (lm.marker[offset]>=(254-BORDER)) lm.marker[offset]=255; else lm.marker[offset]=0; } } for (u32 ref=254; ref>(254-16); ref--) { ApplyBorders (lm,ref); Progress (1.f - float(ref)/float(254-16)); } Progress (1.f); // Saving (DXT5.dds) Status ("Compression base..."); { xr_vector<u32> packed; lm.Pack (packed); string_path FN; sprintf (lm_texture.name,"lmap#%d",lmapNameID ); sprintf (FN,"%s%s_1.dds", path,lm_texture.name); BYTE* raw_data = LPBYTE(&*packed.begin()); u32 w = lm.width; u32 h = lm.height; u32 pitch = w*4; STextureParams fmt; fmt.fmt = STextureParams::tfDXT5; fmt.flags.set (STextureParams::flDitherColor, FALSE); fmt.flags.set (STextureParams::flGenerateMipMaps, FALSE); fmt.flags.set (STextureParams::flBinaryAlpha, FALSE); DXTCompress (FN,raw_data,0,w,h,pitch,&fmt,4); } Status ("Compression hemi..."); //. { xr_vector<u32> packed; lm.Pack_hemi (packed); u32 w = lm.width; u32 h = lm.height; u32 pitch = w*4; string_path FN; sprintf (lm_texture.name,"lmap#%d",lmapNameID ); sprintf (FN,"%s%s_2.dds", path, lm_texture.name); BYTE* raw_data = LPBYTE(&*packed.begin()); STextureParams fmt; fmt.fmt = STextureParams::tfDXT5; fmt.flags.set (STextureParams::flDitherColor, FALSE); fmt.flags.set (STextureParams::flGenerateMipMaps, FALSE); fmt.flags.set (STextureParams::flBinaryAlpha, FALSE); DXTCompress (FN,raw_data,0,w,h,pitch,&fmt,4); } lm_texture.bHasAlpha = TRUE; lm_texture.dwWidth = lm.width; lm_texture.dwHeight = lm.height; lm_texture.pSurface = NULL; lm.destroy (); } /* lm_layer lm; b_texture lm_texture; */ void CLightmap::read ( INetReader &r ) { lm.read( r ); ::read(r, lm_texture); } void CLightmap::write ( IWriter &w )const { lm.write( w ); ::write( w, lm_texture ); }
26.721951
165
0.53797
acidicMercury8
091f18e0ba1f8dbb57b3151dcacdd3982b303e3b
11,739
cpp
C++
util/test/demos/d3d11/d3d11_amd_shader_extensions.cpp
orsonbraines/renderdoc
ed9ac9f7bf594f79f834ce8fa0b9717b69d13b0e
[ "MIT" ]
1
2022-02-17T21:18:24.000Z
2022-02-17T21:18:24.000Z
util/test/demos/d3d11/d3d11_amd_shader_extensions.cpp
orsonbraines/renderdoc
ed9ac9f7bf594f79f834ce8fa0b9717b69d13b0e
[ "MIT" ]
null
null
null
util/test/demos/d3d11/d3d11_amd_shader_extensions.cpp
orsonbraines/renderdoc
ed9ac9f7bf594f79f834ce8fa0b9717b69d13b0e
[ "MIT" ]
null
null
null
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2019-2022 Baldur Karlsson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include "d3d11_test.h" #include "3rdparty/ags/ags_shader_intrinsics_dx11.hlsl.h" #include "3rdparty/ags/amd_ags.h" RD_TEST(D3D11_AMD_Shader_Extensions, D3D11GraphicsTest) { static constexpr const char *Description = "Tests using AMD shader extensions on D3D11."; AGS_INITIALIZE dyn_agsInitialize = NULL; AGS_DEINITIALIZE dyn_agsDeInitialize = NULL; AGS_DRIVEREXTENSIONSDX11_CREATEDEVICE dyn_agsDriverExtensionsDX11_CreateDevice = NULL; AGS_DRIVEREXTENSIONSDX11_DESTROYDEVICE dyn_agsDriverExtensionsDX11_DestroyDevice = NULL; AGSContext *ags = NULL; std::string BaryCentricPixel = R"EOSHADER( float4 main() : SV_Target0 { float2 bary = AmdDxExtShaderIntrinsics_IjBarycentricCoords( AmdDxExtShaderIntrinsicsBarycentric_LinearCenter ); float3 bary3 = float3(bary.x, bary.y, 1.0 - (bary.x + bary.y)); if(bary3.x > bary3.y && bary3.x > bary3.z) return float4(1.0f, 0.0f, 0.0f, 1.0f); else if(bary3.y > bary3.x && bary3.y > bary3.z) return float4(0.0f, 1.0f, 0.0f, 1.0f); else return float4(0.0f, 0.0f, 1.0f, 1.0f); } )EOSHADER"; std::string MaxCompute = R"EOSHADER( RWByteAddressBuffer inUAV : register(u0); RWByteAddressBuffer outUAV : register(u1); [numthreads(256, 1, 1)] void main(uint3 threadID : SV_DispatchThreadID) { // read input from source uint2 input; input.x = inUAV.Load(threadID.x * 8); input.y = inUAV.Load(threadID.x * 8 + 4); AmdDxExtShaderIntrinsics_AtomicMaxU64(outUAV, 0, input); } )EOSHADER"; void Prepare(int argc, char **argv) { D3D11GraphicsTest::Prepare(argc, argv); if(!Avail.empty()) return; std::string agsname = sizeof(void *) == 8 ? "amd_ags_x64.dll" : "amd_ags_x86.dll"; HMODULE agsLib = LoadLibraryA(agsname.c_str()); // try in local plugins folder if(!agsLib) { agsLib = LoadLibraryA( ("../../" + std::string(sizeof(void *) == 8 ? "plugins-win64/" : "plugins/win32/") + "amd/ags/" + agsname) .c_str()); } if(!agsLib) { // try in plugins folder next to renderdoc.dll HMODULE rdocmod = GetModuleHandleA("renderdoc.dll"); char path[MAX_PATH + 1] = {}; if(rdocmod) { GetModuleFileNameA(rdocmod, path, MAX_PATH); std::string tmp = path; tmp.resize(tmp.size() - (sizeof("/renderdoc.dll") - 1)); agsLib = LoadLibraryA((tmp + "/plugins/amd/ags/" + agsname).c_str()); } } if(!agsLib) { Avail = "Couldn't load AGS dll"; return; } dyn_agsInitialize = (AGS_INITIALIZE)GetProcAddress(agsLib, "agsInitialize"); dyn_agsDeInitialize = (AGS_DEINITIALIZE)GetProcAddress(agsLib, "agsDeInitialize"); dyn_agsDriverExtensionsDX11_CreateDevice = (AGS_DRIVEREXTENSIONSDX11_CREATEDEVICE)GetProcAddress( agsLib, "agsDriverExtensionsDX11_CreateDevice"); dyn_agsDriverExtensionsDX11_DestroyDevice = (AGS_DRIVEREXTENSIONSDX11_DESTROYDEVICE)GetProcAddress( agsLib, "agsDriverExtensionsDX11_DestroyDevice"); if(!dyn_agsInitialize || !dyn_agsDeInitialize || !dyn_agsDriverExtensionsDX11_CreateDevice || !dyn_agsDriverExtensionsDX11_DestroyDevice) { Avail = "AGS didn't have all necessary entry points - too old?"; return; } AGSReturnCode agsret = dyn_agsInitialize( AGS_MAKE_VERSION(AMD_AGS_VERSION_MAJOR, AMD_AGS_VERSION_MINOR, AMD_AGS_VERSION_PATCH), NULL, &ags, NULL); if(agsret != AGS_SUCCESS || ags == NULL) { Avail = "AGS couldn't initialise"; return; } ID3D11Device *ags_devHandle = NULL; ID3D11DeviceContext *ags_ctxHandle = NULL; CreateExtendedDevice(&ags_devHandle, &ags_ctxHandle); // once we've checked that we can create an extension device on an adapter, we can release it // and return ready to run if(ags_devHandle) { Avail = ""; unsigned int dummy = 0; dyn_agsDriverExtensionsDX11_DestroyDevice(ags, ags_devHandle, &dummy, ags_ctxHandle, &dummy); return; } Avail = "AGS couldn't create device on any selected adapter."; } void CreateExtendedDevice(ID3D11Device * *ags_devHandle, ID3D11DeviceContext * *ags_ctxHandle) { std::vector<IDXGIAdapterPtr> adapters = GetAdapters(); for(IDXGIAdapterPtr a : adapters) { AGSDX11DeviceCreationParams devCreate = {}; AGSDX11ExtensionParams extCreate = {}; AGSDX11ReturnedParams ret = {}; devCreate.pAdapter = a.GetInterfacePtr(); devCreate.DriverType = D3D_DRIVER_TYPE_UNKNOWN; devCreate.Flags = createFlags | (debugDevice ? D3D11_CREATE_DEVICE_DEBUG : 0); devCreate.pFeatureLevels = &feature_level; devCreate.FeatureLevels = 1; devCreate.SDKVersion = D3D11_SDK_VERSION; extCreate.uavSlot = 7; extCreate.crossfireMode = AGS_CROSSFIRE_MODE_DISABLE; extCreate.pAppName = L"RenderDoc demos"; extCreate.pEngineName = L"RenderDoc demos"; AGSReturnCode agsret = dyn_agsDriverExtensionsDX11_CreateDevice(ags, &devCreate, &extCreate, &ret); if(agsret == AGS_SUCCESS && ret.pDevice) { // don't accept devices that don't support the intrinsics we want if(!ret.extensionsSupported.intrinsics16 || !ret.extensionsSupported.intrinsics19) { unsigned int dummy = 0; dyn_agsDriverExtensionsDX11_DestroyDevice(ags, ret.pDevice, &dummy, ret.pImmediateContext, &dummy); } else { *ags_devHandle = ret.pDevice; *ags_ctxHandle = ret.pImmediateContext; return; } } } } int main() { // initialise, create window, create device, etc if(!Init()) return 3; // release the old device and swapchain dev = NULL; ctx = NULL; dev1 = NULL; dev2 = NULL; dev3 = NULL; dev4 = NULL; dev5 = NULL; ctx1 = NULL; ctx2 = NULL; ctx3 = NULL; ctx4 = NULL; annot = NULL; swapBlitVS = NULL; swapBlitPS = NULL; // and swapchain & related swap = NULL; bbTex = NULL; bbRTV = NULL; // we don't use these directly, just copy them into the real device so we know that ags is the // one to destroy the last reference to the device ID3D11Device *ags_devHandle = NULL; ID3D11DeviceContext *ags_ctxHandle = NULL; CreateExtendedDevice(&ags_devHandle, &ags_ctxHandle); dev = ags_devHandle; ctx = ags_ctxHandle; annot = ctx; // create the swapchain on the new AGS-extended device DXGI_SWAP_CHAIN_DESC swapDesc = MakeSwapchainDesc(mainWindow); HRESULT hr = fact->CreateSwapChain(dev, &swapDesc, &swap); if(FAILED(hr)) { TEST_ERROR("Couldn't create swapchain"); return 4; } hr = swap->GetBuffer(0, __uuidof(ID3D11Texture2D), (void **)&bbTex); if(FAILED(hr)) { TEST_ERROR("Couldn't get swapchain backbuffer"); return 4; } hr = dev->CreateRenderTargetView(bbTex, NULL, &bbRTV); if(FAILED(hr)) { TEST_ERROR("Couldn't create swapchain RTV"); return 4; } std::string ags_header = ags_shader_intrinsics_dx11_hlsl(); ID3DBlobPtr vsblob = Compile(D3DDefaultVertex, "main", "vs_4_0"); // can't skip optimising and still have the extensions work, sadly ID3DBlobPtr psblob = Compile(ags_header + BaryCentricPixel, "main", "ps_5_0", false); ID3DBlobPtr csblob = Compile(ags_header + MaxCompute, "main", "cs_5_0", false); CreateDefaultInputLayout(vsblob); ID3D11VertexShaderPtr vs = CreateVS(vsblob); ID3D11PixelShaderPtr ps = CreatePS(psblob); ID3D11ComputeShaderPtr cs = CreateCS(csblob); SetDebugName(cs, "cs"); ID3D11BufferPtr vb = MakeBuffer().Vertex().Data(DefaultTri); // make a simple texture so that the structured data includes texture initial states ID3D11Texture2DPtr fltTex = MakeTexture(DXGI_FORMAT_R32G32B32A32_FLOAT, 4, 4).RTV(); ID3D11RenderTargetViewPtr fltRT = MakeRTV(fltTex); const int numInputValues = 16384; std::vector<uint64_t> values; values.resize(numInputValues); uint64_t cpuMax = 0; for(uint64_t &v : values) { v = 0; for(uint32_t byte = 0; byte < 8; byte++) { uint64_t b = (rand() & 0xff0) >> 4; v |= b << (byte * 8); } cpuMax = std::max(v, cpuMax); } ID3D11BufferPtr inBuf = MakeBuffer() .UAV() .ByteAddressed() .Data(values.data()) .Size(UINT(sizeof(uint64_t) * values.size())); ID3D11BufferPtr outBuf = MakeBuffer().UAV().ByteAddressed().Size(32); SetDebugName(outBuf, "outBuf"); ID3D11UnorderedAccessViewPtr inUAV = MakeUAV(inBuf).Format(DXGI_FORMAT_R32_TYPELESS); ID3D11UnorderedAccessViewPtr outUAV = MakeUAV(outBuf).Format(DXGI_FORMAT_R32_TYPELESS); while(Running()) { ctx->ClearState(); uint32_t zero[4] = {}; ctx->ClearUnorderedAccessViewUint(outUAV, zero); ClearRenderTargetView(bbRTV, {0.2f, 0.2f, 0.2f, 1.0f}); ClearRenderTargetView(fltRT, {0.2f, 0.2f, 0.2f, 1.0f}); IASetVertexBuffer(vb, sizeof(DefaultA2V), 0); ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); ctx->IASetInputLayout(defaultLayout); ctx->VSSetShader(vs, NULL, 0); ctx->PSSetShader(ps, NULL, 0); RSSetViewport({0.0f, 0.0f, (float)screenWidth, (float)screenHeight, 0.0f, 1.0f}); ctx->OMSetRenderTargets(1, &bbRTV.GetInterfacePtr(), NULL); ctx->Draw(3, 0); ctx->CSSetShader(cs, NULL, 0); ctx->CSSetUnorderedAccessViews(0, 1, &inUAV.GetInterfacePtr(), NULL); ctx->CSSetUnorderedAccessViews(1, 1, &outUAV.GetInterfacePtr(), NULL); ctx->Dispatch(numInputValues / 256, 1, 1); ctx->Flush(); std::vector<byte> output = GetBufferData(outBuf, 0, 8); uint64_t gpuMax = 0; memcpy(&gpuMax, output.data(), sizeof(uint64_t)); setMarker("cpuMax: " + std::to_string(cpuMax)); setMarker("gpuMax: " + std::to_string(gpuMax)); Present(); } dev = NULL; ctx = NULL; annot = NULL; unsigned int dummy = 0; dyn_agsDriverExtensionsDX11_DestroyDevice(ags, ags_devHandle, &dummy, ags_ctxHandle, &dummy); dyn_agsDeInitialize(ags); return 0; } }; REGISTER_TEST();
30.973615
113
0.653037
orsonbraines
091f417e8628b6a0ce95fef5ed62303fb56b3e5d
895
cpp
C++
C-Plus-Plus/cp/remove_spaces_from_a_string.cpp
zhcet19/NeoAlgo-1
c534a23307109280bda0e4867d6e8e490002a4ee
[ "MIT" ]
897
2020-06-25T00:12:52.000Z
2022-03-24T00:49:31.000Z
C-Plus-Plus/cp/remove_spaces_from_a_string.cpp
zhcet19/NeoAlgo-1
c534a23307109280bda0e4867d6e8e490002a4ee
[ "MIT" ]
5,707
2020-06-24T17:53:28.000Z
2022-01-22T05:03:15.000Z
C-Plus-Plus/cp/remove_spaces_from_a_string.cpp
zhcet19/NeoAlgo-1
c534a23307109280bda0e4867d6e8e490002a4ee
[ "MIT" ]
1,817
2020-06-25T03:51:05.000Z
2022-03-29T05:14:07.000Z
/* Given a string , remove spaces from it and then return new string. We can solve it By using getline function in C++ and then get a new string. */ #include <bits/stdc++.h> using namespace std; string new_string(string s) { stringstream s2(s); string tem; // Making the string empty s = ""; // Running loop till end of stream // and getting every word while (getline(s2, tem, ' ')) { s += tem; } return s; } int main() { cout << "Enter the string\n"; string s; getline(cin , s); cout << "After Removing Spaces the New String is : "; cout << new_string(s) << endl; } /* Standard Input and Output Input : I am a Open Source Contributor in GSSoC'21 Output : IamaOpenSourceContributorinGSSoC'21 Time Complexity : O(N) // String size Space Complexity : O(N) // an intermediate string */
21.309524
143
0.611173
zhcet19
091f4406216dd8f9ec0b6f5bd1801b12107496b4
316
cpp
C++
skia/src/core/SkQuadTreePicture.cpp
bonescreater/bones
618ced87a9a2061b0a7879be32b2fea263880f1b
[ "MIT" ]
16
2015-09-02T17:47:53.000Z
2022-03-01T19:12:53.000Z
src/core/SkQuadTreePicture.cpp
rgraebert/skia
33a4b46e9f24be6268855478b5c895f883fb4ac5
[ "BSD-3-Clause" ]
null
null
null
src/core/SkQuadTreePicture.cpp
rgraebert/skia
33a4b46e9f24be6268855478b5c895f883fb4ac5
[ "BSD-3-Clause" ]
6
2015-11-11T13:22:59.000Z
2022-03-01T19:13:02.000Z
/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkQuadTreePicture.h" #include "SkQuadTree.h" SkBBoxHierarchy* SkQuadTreePicture::createBBoxHierarchy() const { return SkNEW_ARGS(SkQuadTree, (fBounds)); }
21.066667
73
0.731013
bonescreater
092021ae9945b23983b43648047e7c9260a918b2
1,531
cpp
C++
src/logic/syntax/ELSentence.cpp
JunLi-Galios/repel
e4e7f4ffc95f8d65dd478861080c9c77bab9b797
[ "MIT" ]
null
null
null
src/logic/syntax/ELSentence.cpp
JunLi-Galios/repel
e4e7f4ffc95f8d65dd478861080c9c77bab9b797
[ "MIT" ]
null
null
null
src/logic/syntax/ELSentence.cpp
JunLi-Galios/repel
e4e7f4ffc95f8d65dd478861080c9c77bab9b797
[ "MIT" ]
null
null
null
/* * ELSentence.cpp * * Created on: Dec 19, 2011 * Author: joe */ #include "ELSentence.h" #include "../Domain.h" bool operator==(const ELSentence& a, const ELSentence& b) { if (*a.s_ != *b.s_) return false; if (a.hasInfWeight_ != b.hasInfWeight_) return false; if (!a.hasInfWeight_ && a.w_ != b.w_) return false; if ((a.quantification_ == 0 && b.quantification_ != 0) || (a.quantification_ == 0 && b.quantification_ != 0)) return false; if (a.quantification_ != 0 && b.quantification_ != 0 && *a.quantification_ != *b.quantification_) return false; return true; }; std::string ELSentence::toString() const { std::stringstream str; str << *this; return str.str(); }; SISet ELSentence::dSatisfied(const Model& m, const Domain& d) const { if (isQuantified()) return s_->dSatisfied(m, d, *quantification_); else return s_->dSatisfied(m, d); } SISet ELSentence::dNotSatisfied(const Model& m, const Domain& d) const { if (isQuantified()) return s_->dNotSatisfied(m, d, *quantification_); else return s_->dNotSatisfied(m, d); } bool ELSentence::fullySatisfied(const Model& m, const Domain& d) const { SISet satisfiedAt = dSatisfied(m, d); SISet toSatisfyAt(false, d.maxInterval()); if (quantification_ != 0) { toSatisfyAt = *quantification_; } else { toSatisfyAt = SISet(d.maxSpanInterval(), false, d.maxInterval()); } toSatisfyAt.subtract(satisfiedAt); if (toSatisfyAt.empty()) return true; return false; }
30.62
115
0.647943
JunLi-Galios
0926ecc53d84b320e1f4c0f74bdb29549382911e
16,609
cc
C++
project2/solution/solution2.cc
nbdhhzh/CompilerProject-2020Spring
a41a09d4116a3715414f2ffba0f832cf34692736
[ "MIT" ]
null
null
null
project2/solution/solution2.cc
nbdhhzh/CompilerProject-2020Spring
a41a09d4116a3715414f2ffba0f832cf34692736
[ "MIT" ]
null
null
null
project2/solution/solution2.cc
nbdhhzh/CompilerProject-2020Spring
a41a09d4116a3715414f2ffba0f832cf34692736
[ "MIT" ]
null
null
null
// this is a silly solution // just to show you how different // components of this framework work // please bring your wise to write // a 'real' solution :) #include <iostream> #include <fstream> #include <string> #include <vector> #include <sstream> #include <map> #include "json/json.h" #include "IR.h" #include "IRMutator.h" #include "IRVisitor.h" #include "IRPrinter.h" #include "type.h" using namespace Boost::Internal; using namespace std; class mydom{ public: string name; int l, r; }; class myvar{ public: string name; vector<size_t>shape; int use; }nowvar, LHSvar; map<string, bool> usedom, LHSusedom; vector<Expr>domlist, LHSdomlist, *gradvarlist; map<string, myvar> myvarlist; map<string, mydom> mydomlist; vector<Stmt>mycode; vector<string>grad_to; Type data_type; int cntgrad; int nowgrad; string gradname; Type index_type = Type::int_scalar(32); int tempcnt = 0; Expr *now_grad_to; Expr *res_LHS; void build_Clist(const string &str, vector<size_t> *&ret); template <class stnTP> stnTP strToNum(const string& str) { istringstream iss(str); stnTP num; iss >> num; return num; } int findfirst(const string &str, char ch){ int n = str.length(); for(int i = 0; i < n; i++) if(str[i] == ch)return i; return -1; } int findlast(const string &str, char ch){ int n = str.length(); for(int i = n - 1; i >= 0; i--) if(str[i] == ch)return i; return -1; } int fix_expr_size(const string &str, int l, int r){ //cout << "fix_expr "<< str << " " << l << " " << r << endl; int n = str.length(), cnt = 0, i; bool quo = true; for(i = n - 1; i >= 0; i--){ if(str[i] == ')')cnt++; if(cnt == 0){ quo = false; if(str[i] == '+' || str[i] == '-')break; } if(str[i] == '(')cnt--; } if(quo) return fix_expr_size(str.substr(1, n - 2), l, r); if(i >= 0){ int sum, ssum; sum = fix_expr_size(str.substr(i + 1), l, r); //cout << sum << endl; if(str[i] == '-')sum = -sum; ssum = fix_expr_size(str.substr(0, i), l - sum, r - sum); if(ssum != 0 && str[i] == '+') fix_expr_size(str.substr(i + 1), l - ssum, r - ssum); return ssum + sum; } for(i = n - 1; i >= 0; i--){ if(str[i] == ')')cnt++; if(cnt == 0) if(str[i] == '*' || str[i] == '/' || str[i] == '%')break; if(str[i] == '(')cnt--; } if(i >= 0){ int sum, ssum; sum = fix_expr_size(str.substr(i + 1), l, r); if(str[i] == '*')ssum = fix_expr_size(str.substr(0, i), l / max((int)1, sum), (r - 1) / max((int)1, sum) + 1); else if(str[i] == '/')ssum = fix_expr_size(str.substr(0, i - 1), l * sum, r * sum); else ssum = fix_expr_size(str.substr(0, i), -1000000000, 1000000000); if(str[i] == '*')return ssum * sum; else if(str[i] == '/') return ssum / max((int)1, sum); else return ssum % max((int)1, sum); } if(str[n - 1] >= '0' && str[n - 1] <= '9')return strToNum<int>(str); if(mydomlist.find(str) == mydomlist.end()){ mydom a({str, l, r}); mydomlist[str] = a; } mydomlist[str].l = max(mydomlist[str].l, l); mydomlist[str].r = min(mydomlist[str].r, r); return 0; } void fix_list_size(const string &str, vector<size_t> *&_size){ string st = str; for(auto i : *_size){ int t = findfirst(st, ','); fix_expr_size(st.substr(0, t), 0, (int)i); st = st.substr(t + 1); } } void fix_size(const string &str){ string st = str; for(int t = findlast(st, ']'); t >= 0; t = findlast(st, ']')){ st = st.substr(0, t); int s = findlast(st, '['); int r = findlast(st, '<'); vector<size_t> *res_Clist; build_Clist(st.substr(r + 1, s - r - 2), res_Clist); fix_list_size(st.substr(s + 1, t - s - 1), res_Clist); st = st.substr(0, r); } } void deluse(const string &str){ string st = str; for(int t = findlast(st, ']'); t >= 0; t = findlast(st, ']')){ st = st.substr(0, t); int r = findlast(st, '<'); int s = r - 1; while((st[s] >= 'A' && st[s] <='Z') || (st[s] >= 'a' && st[s] <= 'z'))s--; string name = st.substr(s + 1, r - s - 1); myvarlist[name].use--; } } void build_IdExpr(const string &str, Expr *&ret, Expr *&varret){ //cout << "build_IdExpr " << str << endl; int n = str.length(), cnt = 0, i; bool quo = true; for(i = n - 1; i >= 0; i--){ if(str[i] == ')')cnt++; if(cnt == 0){ quo = false; if(str[i] == '+' || str[i] == '-')break; } if(str[i] == '(')cnt--; } if(quo){ Expr *res_IdExpr, *res_varExpr; build_IdExpr(str.substr(1, n - 2), res_IdExpr, res_varExpr); ret = new Expr(Unary::make(data_type, UnaryOpType::Not, *res_IdExpr)); varret = new Expr(Unary::make(data_type, UnaryOpType::Not, *res_varExpr)); return; } if(i >= 0){ Expr *LIdExpr, *RIdExpr, *LvarExpr, *RvarExpr; build_IdExpr(str.substr(0, i), LIdExpr, LvarExpr); build_IdExpr(str.substr(i + 1), RIdExpr, RvarExpr); if(str[i] == '+') ret = new Expr(Binary::make(data_type, BinaryOpType::Add, *LIdExpr, *RIdExpr)), varret = new Expr(Binary::make(data_type, BinaryOpType::Add, *LvarExpr, *RvarExpr)); else ret = new Expr(Binary::make(data_type, BinaryOpType::Sub, *LIdExpr, *RIdExpr)), varret = new Expr(Binary::make(data_type, BinaryOpType::Sub, *LvarExpr, *RvarExpr)); return; } for(i = n - 1; i >= 0; i--){ if(str[i] == ')')cnt++; if(cnt == 0) if(str[i] == '*' || str[i] == '/' || str[i] == '%')break; if(str[i] == '(')cnt--; } if(i >= 0){ Expr *LIdExpr, *RIdExpr, *LvarExpr, *RvarExpr; build_IdExpr(str.substr(0, i - (str[i - 1] == '/')), LIdExpr, LvarExpr); build_IdExpr(str.substr(i + 1), RIdExpr, RvarExpr); if(str[i] == '*') ret = new Expr(Binary::make(data_type, BinaryOpType::Mul, *LIdExpr, *RIdExpr)), varret = new Expr(Binary::make(data_type, BinaryOpType::Mul, *LvarExpr, *RvarExpr)); else if(str[i] == '/') ret = new Expr(Binary::make(data_type, BinaryOpType::Div, *LIdExpr, *RIdExpr)), varret = new Expr(Binary::make(data_type, BinaryOpType::Div, *LvarExpr, *RvarExpr)); else ret = new Expr(Binary::make(data_type, BinaryOpType::Mod, *LIdExpr, *RIdExpr)), varret = new Expr(Binary::make(data_type, BinaryOpType::Mod, *LvarExpr, *RvarExpr)); return; } if(str[n - 1] >= '0' && str[n - 1] <= '9'){ ret = new Expr(strToNum<int>(str)); varret = new Expr(strToNum<int>(str)); return; } Expr thisdom = Dom::make(index_type, max(0, mydomlist[str].l), max(0, mydomlist[str].r)); ret = new Expr(Index::make(index_type, str, thisdom, IndexType::Spatial)); varret = new Expr(Var::make(index_type, str, {}, {})); if(!usedom[str]){ usedom[str] = 1; domlist.push_back(*ret); } return; } void build_Clist(const string &str, vector<size_t> *&ret){ //cout << "build_Clist " << str << endl; int t = findlast(str, ','); if(t < 0) ret = new vector<size_t>({strToNum<size_t>(str)}); else{ build_Clist(str.substr(0, t), ret); ret->push_back(strToNum<size_t>(str.substr(t + 1))); } } void build_Alist(const string &str, vector<Expr> *&ret, vector<Expr> *&varret){ //cout << "build_Alist " << str << endl; int t = findlast(str, ','); if(t < 0){ Expr *res_IdExpr, *res_varExpr; build_IdExpr(str, res_IdExpr, res_varExpr); ret = new vector<Expr>({*res_IdExpr}); varret = new vector<Expr>({*res_varExpr}); }else{ build_Alist(str.substr(0, t), ret, varret); Expr *res_IdExpr, *res_varExpr; build_IdExpr(str.substr(t + 1), res_IdExpr, res_varExpr); ret->push_back(*res_IdExpr); varret->push_back(*res_varExpr); } //cout << "build_Alist_finish " << str << endl; } void build_SRef(const string &str, Expr *&ret){ //cout << "build_SRef " << str << endl; int r = findfirst(str, '<'); string name = str.substr(0, r); nowvar.name = name; nowvar.shape.clear(); if(myvarlist.find(name) == myvarlist.end()) myvarlist[name] = nowvar; ret = new Expr(Var::make(data_type, name, {}, {})); } void build_TRef(const string &str, Expr *&ret, bool d = false){ // int n = str.length(); int s = findfirst(str, '['); int r = findfirst(str, '<'); string name = str.substr(0, r); bool e = false; if(!d){ for(int i = 0; i < grad_to.size(); i++) if(name == grad_to[i]){ cntgrad++; if(cntgrad == nowgrad)e = true; } } if(d || e)name = "d" + name; //cout << "build_TRef " << name << endl; vector<size_t> *res_Clist; vector<Expr> *res_Alist; vector<Expr> *res_varlist; build_Clist(str.substr(r + 1, s - r - 2), res_Clist); build_Alist(str.substr(s + 1, n - s - 2), res_Alist, res_varlist); nowvar.name = name; nowvar.shape = *res_Clist; if(myvarlist.find(name) == myvarlist.end()) myvarlist[name] = nowvar; myvarlist[name].use++; ret = new Expr(Var::make(data_type, name, *res_Alist, *res_Clist)); if(e){ gradname = name; gradvarlist = res_varlist; ret = new Expr(1); } } void build_LHS(const string &str, Expr *&ret){ //cout << "build_LHS " << str << endl; usedom.clear(); domlist.clear(); build_TRef(str, ret, true); LHSvar = nowvar; LHSvar.name = "d" + LHSvar.name; LHSdomlist.clear(); for(auto i : domlist) LHSdomlist.push_back(i); LHSusedom.clear(); for(auto i : usedom) LHSusedom[i.first] = 1; } void build_RHS(const string &str, Expr *&ret){ //cout << "build_RHS " << str << endl; int n = str.length(), cnt = 0, i; bool quo = true; for(i = n - 1; i >= 0; i--){ if(str[i] == ')' || str[i] == ']')cnt++; if(cnt == 0){ quo = false; if(str[i] == '+' || str[i] == '-')break; } if(str[i] == '(' || str[i] == '[')cnt--; } if(quo){ Expr *res_IdExpr; build_RHS(str.substr(1, n - 2), res_IdExpr); ret = new Expr(Unary::make(data_type, UnaryOpType::Not, *res_IdExpr)); return; } if(i >= 0){ Expr *res_LRHS, *res_RRHS; int tr = 0; if(cntgrad >= nowgrad)tr = 1; build_RHS(str.substr(0, i), res_LRHS); if(cntgrad >= nowgrad && (!tr))tr = 2; build_RHS(str.substr(i + 1), res_RRHS); if(cntgrad >= nowgrad && (!tr))tr = 3; if(tr == 2){ deluse(str.substr(i + 1)); ret = res_LRHS; } else if(tr == 3){ ret = res_RRHS; deluse(str.substr(0, i)); } else{ if(str[i] == '+') ret = new Expr(Binary::make(data_type, BinaryOpType::Add, *res_LRHS, *res_RRHS)); else ret = new Expr(Binary::make(data_type, BinaryOpType::Sub, *res_LRHS, *res_RRHS)); } return; } for(i = n - 1; i >= 0; i--){ if(str[i] == ')' || str[i] == ']')cnt++; if(cnt == 0)if(str[i] == '*' || str[i] == '/' || str[i] == '%')break; if(str[i] == '(' || str[i] == '[')cnt--; } if(i >= 0){ Expr *res_LRHS, *res_RRHS; build_RHS(str.substr(0, i - (str[i - 1] == '/')), res_LRHS); build_RHS(str.substr(i + 1), res_RRHS); if(str[i] == '*') ret = new Expr(Binary::make(data_type, BinaryOpType::Mul, *res_LRHS, *res_RRHS)); else if(str[i] == '/') ret = new Expr(Binary::make(data_type, BinaryOpType::Div, *res_LRHS, *res_RRHS)); else ret = new Expr(Binary::make(data_type, BinaryOpType::Mod, *res_LRHS, *res_RRHS)); return; } if(str[n - 1] == ']'){ build_TRef(str, ret); return; } if(str[n - 1] == '>'){ build_SRef(str, ret); return; } if(data_type == Type::float_scalar(32)) ret = new Expr(strToNum<float>(str)); else ret = new Expr(strToNum<int>(str)); return; } void build_RHS_list(const string &str, vector<Stmt> *&ret){ //cout << "build_RHS_list " << str << endl; ret = new vector<Stmt>({}); for(nowgrad = 1;; nowgrad++){ usedom.clear(); for(auto i : LHSusedom) usedom[i.first] = 1; domlist.clear(); cntgrad = 0; Expr *res_RHS; build_RHS(str, res_RHS); //IRPrinter printer; vector<Expr>tempdomlist; string s = "a"; //cout << graddomlist->size() << endl; for(int i = 0; i < gradvarlist->size(); i++){ for(s[0]++; mydomlist.find(s) != mydomlist.end(); s[0]++); Expr thisdom = Dom::make(index_type, gradvarlist->at(i), Binary::make(data_type, BinaryOpType::Add, gradvarlist->at(i), 1)); //Expr thisdom = Dom::make(index_type, 0, 10); tempdomlist.push_back(Index::make(index_type, s, thisdom, IndexType::Spatial)); } now_grad_to = new Expr(Var::make(data_type, gradname, tempdomlist, myvarlist[gradname].shape)); Stmt tem = LoopNest::make(tempdomlist, {Move::make(*now_grad_to, Binary::make(data_type, BinaryOpType::Add, *now_grad_to, Binary::make(data_type, BinaryOpType::Mul, *res_LHS, *res_RHS)), MoveType::MemToMem)}); /*Stmt tem = Move::make(*now_grad_to, Binary::make(data_type, BinaryOpType::Add, *now_grad_to, Binary::make(data_type, BinaryOpType::Mul, *res_LHS, *res_RHS)), MoveType::MemToMem);*/ if(domlist.size()) ret->push_back(LoopNest::make(domlist, {tem})); else{ ret->push_back(tem); } //cout << nowgrad << " " << cntgrad << endl; if(cntgrad == nowgrad)break; } return; } void build_S(const string &str){ int n = str.length(); //cout << "build_S " << str << endl; mydomlist.clear(); fix_size(str); /*for(auto i : mydomlist) cout << i.second.name << " " << i.second.l << " " << i.second.r << endl;*/ int t = findfirst(str, '='); build_LHS(str.substr(0, t), res_LHS); vector<Stmt> *res_RHS; build_RHS_list(str.substr(t + 1, n - t - 2), res_RHS); mycode.push_back(LoopNest::make(LHSdomlist, *res_RHS)); } void build_P(const string &str){ //cout << "build_P " << str << endl; int n = str.length(), t = findfirst(str, ';'); if(t == n - 1) build_S(str); else{ build_S(str.substr(0, t + 1)); build_P(str.substr(t + 1)); } } bool Input(int cnt, string &name, vector<string>&ins, vector<string>&outs, string &data_type, string &kernel, vector<string> &grad_to){ string st; if(cnt == 0)st = "./cases/example.json"; else st = "./cases/case" + to_string(cnt) + ".json"; ifstream ifile(st, std::ios::in); if(!ifile.good())return false; Json::Reader reader; Json::Value root; if (reader.parse(ifile, root)) { name = root["name"].asString(); data_type = root["data_type"].asString(); kernel = root["kernel"].asString(); Json::Value object = root["ins"]; for (int i = 0; i < object.size(); i++) ins.push_back(object[i].asString()); object = root["outs"]; for (int i = 0; i < object.size(); i++) outs.push_back(object[i].asString()); object = root["grad_to"]; for (int i = 0; i < object.size(); i++) grad_to.push_back(object[i].asString()); } else return false; ifile.close(); return true; } int main() { for(int i = 1; i <= 10; i++){ string name, type, kernel; vector<string> ins, outs; grad_to.clear(); if(!Input(i, name, ins, outs, type, kernel, grad_to)){ cout<< "case" + to_string(i) + " missed!" << endl; continue; } //cout << name <<endl; //cout << kernel <<endl; if(type[0] == 'f')data_type = Type::float_scalar(32); else data_type = Type::int_scalar(32); int n = kernel.length(); string st = ""; for(int i = 0; i < n; i++) if(kernel[i] != ' ')st += kernel[i]; usedom.clear(); LHSusedom.clear(); domlist.clear(); LHSdomlist.clear(); myvarlist.clear(); mydomlist.clear(); mycode.clear(); //grad_to.clear(); tempcnt = 0; build_P(st); for(auto t : grad_to){ vector<Expr> domli; string str = "i"; for(auto s : myvarlist["d" + t].shape){ Expr thisdom = Dom::make(index_type, 0, (int)s); domli.push_back(Index::make(index_type, str, thisdom, IndexType::Spatial)); str[0] = str[0] + 1; } mycode.insert(mycode.begin(), LoopNest::make(domli, {Move::make(Var::make(data_type, "d" + t, domli, myvarlist["d" + t].shape), 0, MoveType::MemToMem)})); } vector<Expr>input; vector<Expr>output; for(auto i : ins)if(myvarlist.find(i) != myvarlist.end() && myvarlist[i].use) input.push_back(Var::make(data_type, i, {}, myvarlist[i].shape)); for(auto i : outs) output.push_back(Var::make(data_type, "d" + i, {}, myvarlist["d" + i].shape)); for(auto i : grad_to) output.push_back(Var::make(data_type, "d" + i, {}, myvarlist["d" + i].shape)); Group _kernel = Kernel::make(name, input, output, mycode, KernelType::CPU); IRPrinter printer; string code = printer.print(_kernel); //cout << code; if(i > 0){ ofstream ofile("./kernels/grad_case" + to_string(i) + ".cc", std::ios::out); ofile << code; ofile.close(); }else{ ofstream ofile("./kernels/kernel_example.cc", std::ios::out); ofile << code; ofile.close(); } //cout<< code; cout<< "case" + to_string(i) + " finished!" <<endl; } return 0; }
31.396975
158
0.582756
nbdhhzh
0926f29c7e79b4e506b54c27e4dd1b9957316334
4,676
hh
C++
include/ignition/utils/detail/ImplPtr.hh
srmainwaring/ign-utils
268d2e645563a0ed8fccd7d14088e87056917d7e
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
include/ignition/utils/detail/ImplPtr.hh
srmainwaring/ign-utils
268d2e645563a0ed8fccd7d14088e87056917d7e
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
include/ignition/utils/detail/ImplPtr.hh
srmainwaring/ign-utils
268d2e645563a0ed8fccd7d14088e87056917d7e
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2018 Open Source Robotics 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. * */ #ifndef IGNITION_UTILS__DETAIL__IMPLPTR_HH_ #define IGNITION_UTILS__DETAIL__IMPLPTR_HH_ #include <ignition/utils/ImplPtr.hh> #include <utility> namespace ignition { namespace utils { namespace detail { ////////////////////////////////////////////////// template <class T, class CopyConstruct, class CopyAssign> // cppcheck-suppress syntaxError template <class C, class A> CopyMoveDeleteOperations<T, CopyConstruct, CopyAssign>:: CopyMoveDeleteOperations(C &&_construct, A &&_assign) : construct(_construct), assign(_assign) { // Do nothing } } // namespace detail ////////////////////////////////////////////////// template <class T, class Deleter, class Operations> template <typename Ptr, class D, class Ops> ImplPtr<T, Deleter, Operations>::ImplPtr( Ptr *_ptr, D &&_deleter, Ops &&_ops) : ptr(_ptr, std::forward<D>(_deleter)), ops(std::forward<Ops>(_ops)) { // Do nothing } ////////////////////////////////////////////////// template <class T, class Deleter, class Operations> ImplPtr<T, Deleter, Operations>::ImplPtr(const ImplPtr &_other) // Delegate to the move constructor after cloning : ImplPtr(_other.Clone()) { // Do nothing } ////////////////////////////////////////////////// template <class T, class Deleter, class Operations> auto ImplPtr<T, Deleter, Operations>::operator=( const ImplPtr &_other) -> ImplPtr& { if (this->ptr) this->ops.assign(*this->ptr, *_other.ptr); else this->ptr.reset(this->ops.construct(*_other.ptr)); return *this; } ////////////////////////////////////////////////// template <class T, class Deleter, class Operations> auto ImplPtr<T, Deleter, Operations>::Clone() const -> ImplPtr { return ImplPtr(this->ptr ? this->ops.construct(*this->ptr) : nullptr, this->ptr.get_deleter(), this->ops); } ////////////////////////////////////////////////// template <class T, class Deleter, class Operations> T &ImplPtr<T, Deleter, Operations>::operator*() { return *ptr; } ////////////////////////////////////////////////// template <class T, class Deleter, class Operations> const T &ImplPtr<T, Deleter, Operations>::operator*() const { return *ptr; } ////////////////////////////////////////////////// template <class T, class Deleter, class Operations> T *ImplPtr<T, Deleter, Operations>::operator->() { return ptr.get(); } ////////////////////////////////////////////////// template <class T, class Deleter, class Operations> const T *ImplPtr<T, Deleter, Operations>::operator->() const { return ptr.get(); } ////////////////////////////////////////////////// template <class T, class Deleter, class Operations> T *ImplPtr<T, Deleter, Operations>::Get() { return ptr.get(); } ////////////////////////////////////////////////// template <class T, class Deleter, class Operations> const T *ImplPtr<T, Deleter, Operations>::Get() const { return ptr.get(); } ////////////////////////////////////////////////// template <class T, typename... Args> ImplPtr<T> MakeImpl(Args &&..._args) { return ImplPtr<T>( new T{std::forward<Args>(_args)...}, &detail::DefaultDelete<T>, detail::CopyMoveDeleteOperations<T>( &detail::DefaultCopyConstruct<T>, &detail::DefaultCopyAssign<T>)); } ////////////////////////////////////////////////// template <class T, typename... Args> UniqueImplPtr<T> MakeUniqueImpl(Args &&...args) { return UniqueImplPtr<T>( new T{std::forward<Args>(args)...}, &detail::DefaultDelete<T>); } } // namespace utils } // namespace ignition #endif // IGNITION_UTILS__DETAIL__IMPLPTR_HH_
30.763158
75
0.531865
srmainwaring
092734362d089f28b986ea8a7a86fa36e070fdf2
11,087
cpp
C++
src/modules/processes/contrib/nvolkov/SplitCFA/MergeCFAInstance.cpp
fmeschia/pixinsight-class-library
11b956e27d6eee3e119a7b1c337d090d7a03f436
[ "JasPer-2.0", "libtiff" ]
null
null
null
src/modules/processes/contrib/nvolkov/SplitCFA/MergeCFAInstance.cpp
fmeschia/pixinsight-class-library
11b956e27d6eee3e119a7b1c337d090d7a03f436
[ "JasPer-2.0", "libtiff" ]
null
null
null
src/modules/processes/contrib/nvolkov/SplitCFA/MergeCFAInstance.cpp
fmeschia/pixinsight-class-library
11b956e27d6eee3e119a7b1c337d090d7a03f436
[ "JasPer-2.0", "libtiff" ]
null
null
null
// ____ ______ __ // / __ \ / ____// / // / /_/ // / / / // / ____// /___ / /___ PixInsight Class Library // /_/ \____//_____/ PCL 2.4.9 // ---------------------------------------------------------------------------- // Standard SplitCFA Process Module Version 1.0.6 // ---------------------------------------------------------------------------- // MergeCFAInstance.cpp - Released 2021-04-09T19:41:49Z // ---------------------------------------------------------------------------- // This file is part of the standard SplitCFA PixInsight module. // // Copyright (c) 2013-2020 Nikolay Volkov // Copyright (c) 2003-2020 Pleiades Astrophoto S.L. // // Redistribution and use in both source and binary forms, with or without // modification, is permitted provided that the following conditions are met: // // 1. All redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. All redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the names "PixInsight" and "Pleiades Astrophoto", nor the names // of their contributors, may be used to endorse or promote products derived // from this software without specific prior written permission. For written // permission, please contact info@pixinsight.com. // // 4. All products derived from this software, in any form whatsoever, must // reproduce the following acknowledgment in the end-user documentation // and/or other materials provided with the product: // // "This product is based on software from the PixInsight project, developed // by Pleiades Astrophoto and its contributors (https://pixinsight.com/)." // // Alternatively, if that is where third-party acknowledgments normally // appear, this acknowledgment must be reproduced in the product itself. // // THIS SOFTWARE IS PROVIDED BY PLEIADES ASTROPHOTO AND ITS CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL PLEIADES ASTROPHOTO OR ITS // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, BUSINESS // INTERRUPTION; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; AND LOSS OF USE, // DATA OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ---------------------------------------------------------------------------- #include "MergeCFAInstance.h" #include "MergeCFAParameters.h" #include <pcl/AutoPointer.h> #include <pcl/AutoViewLock.h> #include <pcl/Console.h> #include <pcl/StandardStatus.h> #include <pcl/View.h> namespace pcl { // ---------------------------------------------------------------------------- MergeCFAInstance::MergeCFAInstance( const MetaProcess* m ) : ProcessImplementation( m ) { } // ---------------------------------------------------------------------------- MergeCFAInstance::MergeCFAInstance( const MergeCFAInstance& x ) : ProcessImplementation( x ) { Assign( x ); } // ---------------------------------------------------------------------------- void MergeCFAInstance::Assign( const ProcessImplementation& p ) { const MergeCFAInstance* x = dynamic_cast<const MergeCFAInstance*>( &p ); if ( x != nullptr ) { p_viewId = x->p_viewId; o_outputViewId = x->o_outputViewId; } } // ---------------------------------------------------------------------------- bool MergeCFAInstance::CanExecuteOn( const View&, pcl::String& whyNot ) const { whyNot = "MergeCFA can only be executed in the global context."; return false; } // ---------------------------------------------------------------------------- bool MergeCFAInstance::CanExecuteGlobal( String& whyNot ) const { return true; } // ---------------------------------------------------------------------------- View MergeCFAInstance::GetView( int n ) { const String id = p_viewId[n]; if ( id.IsEmpty() ) throw Error( "MergeCFA: Source image #" + String( n ) + " not set." ); ImageWindow w = ImageWindow::WindowById( id ); if ( w.IsNull() ) throw Error( "MergeCFA: Source image not found: " + id ); ImageVariant image = w.MainView().Image(); if ( n == 0 ) { m_width = image.Width(); m_height = image.Height(); m_isColor = image.IsColor(); m_isFloatSample = image.IsFloatSample(); m_bitsPerSample = image.BitsPerSample(); m_numberOfChannels = image.NumberOfChannels(); } else { const String str = "MergeCFA: Incompatible source image "; if ( image.Width() != m_width || image.Height() != m_height || image.NumberOfChannels() != m_numberOfChannels ) throw Error( str + "geometry: " + id ); if ( image.BitsPerSample() != m_bitsPerSample || image.IsFloatSample() != m_isFloatSample ) throw Error( str + "sample type : " + id ); if ( image.IsColor() != m_isColor ) throw Error( str + "color space: " + id ); } return w.MainView(); } // ---------------------------------------------------------------------------- template <class P> static void MergeCFAImage( GenericImage<P>& outputImage, const GenericImage<P>& inputImage0, const GenericImage<P>& inputImage1, const GenericImage<P>& inputImage2, const GenericImage<P>& inputImage3 ) { for ( int c = 0; c < outputImage.NumberOfChannels(); ++c ) for ( int sY = 0, tY = 0; tY < outputImage.Height(); tY += 2, ++sY ) { for ( int sX = 0, tX = 0; tX < outputImage.Width(); tX += 2, ++sX ) { outputImage( tX, tY, c ) = inputImage0( sX, sY, c ); outputImage( tX, tY + 1, c ) = inputImage1( sX, sY, c ); outputImage( tX + 1, tY, c ) = inputImage2( sX, sY, c ); outputImage( tX + 1, tY + 1, c ) = inputImage3( sX, sY, c ); } outputImage.Status() += outputImage.Width() / 2; } } // ---------------------------------------------------------------------------- bool MergeCFAInstance::ExecuteGlobal() { o_outputViewId.Clear(); Array<View> sourceView; for ( int i = 0; i < 4; ++i ) sourceView << GetView( i ); ImageWindow outputWindow( m_width * 2, m_height * 2, m_numberOfChannels, m_bitsPerSample, m_isFloatSample, m_isColor, true ); if ( outputWindow.IsNull() ) throw Error( "MergeCFA: Unable to create target image." ); View outputView = outputWindow.MainView(); try { volatile AutoViewLock outputLock( outputView ); Array<AutoPointer<AutoViewWriteLock>> sourceViewLock; sourceViewLock << new AutoViewWriteLock( sourceView[0] ); for ( int i = 1; i < 4; ++i ) if ( sourceView[i].CanWrite() ) // allow the same view selected for several input channels sourceViewLock << new AutoViewWriteLock( sourceView[i] ); ImageVariant outputImage = outputView.Image(); Array<ImageVariant> inputImage; for ( int i = 0; i < 4; ++i ) inputImage << sourceView[i].Image(); StandardStatus status; outputImage.SetStatusCallback( &status ); outputImage.Status().Initialize( "Merging CFA components", outputImage.NumberOfSamples() / 4 ); Console().EnableAbort(); #define MERGE_CFA_IMAGE( I ) \ MergeCFAImage( static_cast<I&>( *outputImage ), \ static_cast<const I&>( *inputImage[0] ), \ static_cast<const I&>( *inputImage[1] ), \ static_cast<const I&>( *inputImage[2] ), \ static_cast<const I&>( *inputImage[3] ) ) if ( outputImage.IsFloatSample() ) switch ( outputImage.BitsPerSample() ) { case 32: MERGE_CFA_IMAGE( Image ); break; case 64: MERGE_CFA_IMAGE( DImage ); break; } else switch ( outputImage.BitsPerSample() ) { case 8: MERGE_CFA_IMAGE( UInt8Image ); break; case 16: MERGE_CFA_IMAGE( UInt16Image ); break; case 32: MERGE_CFA_IMAGE( UInt32Image ); break; } #undef MERGE_CFA_IMAGE Console().DisableAbort(); o_outputViewId = outputView.Id(); outputWindow.Show(); return true; } catch ( ... ) { outputWindow.Close(); throw; } } // ---------------------------------------------------------------------------- void* MergeCFAInstance::LockParameter( const MetaParameter* p, size_type /*tableRow*/ ) { if ( p == TheMergeCFASourceImage0Parameter ) return p_viewId[0].Begin(); if ( p == TheMergeCFASourceImage1Parameter ) return p_viewId[1].Begin(); if ( p == TheMergeCFASourceImage2Parameter ) return p_viewId[2].Begin(); if ( p == TheMergeCFASourceImage3Parameter ) return p_viewId[3].Begin(); if ( p == TheMergeCFAOutputViewIdParameter ) return o_outputViewId.Begin(); return nullptr; } // ---------------------------------------------------------------------------- bool MergeCFAInstance::AllocateParameter( size_type length, const MetaParameter* p, size_type /*tableRow*/ ) { StringList::iterator s; if ( p == TheMergeCFASourceImage0Parameter ) s = p_viewId.At( 0 ); else if ( p == TheMergeCFASourceImage1Parameter ) s = p_viewId.At( 1 ); else if ( p == TheMergeCFASourceImage2Parameter ) s = p_viewId.At( 2 ); else if ( p == TheMergeCFASourceImage3Parameter ) s = p_viewId.At( 3 ); else if ( p == TheMergeCFAOutputViewIdParameter ) s = &o_outputViewId; else return false; s->Clear(); if ( length > 0 ) s->SetLength( length ); return true; } // ---------------------------------------------------------------------------- size_type MergeCFAInstance::ParameterLength( const MetaParameter* p, size_type /*tableRow*/ ) const { if ( p == TheMergeCFASourceImage0Parameter ) return p_viewId[0].Length(); if ( p == TheMergeCFASourceImage1Parameter ) return p_viewId[1].Length(); if ( p == TheMergeCFASourceImage2Parameter ) return p_viewId[2].Length(); if ( p == TheMergeCFASourceImage3Parameter ) return p_viewId[3].Length(); if ( p == TheMergeCFAOutputViewIdParameter ) return o_outputViewId.Length(); return 0; } // ---------------------------------------------------------------------------- } // namespace pcl // ---------------------------------------------------------------------------- // EOF MergeCFAInstance.cpp - Released 2021-04-09T19:41:49Z
35.308917
128
0.56697
fmeschia
092b110851dc5cd23d9ed75fc2c018a176cf66eb
7,744
hpp
C++
svntrunk/src/BlueMatter/util/include/xyz2ziterator.hpp
Bhaskers-Blu-Org1/BlueMatter
1ab2c41af870c19e2e1b1095edd1d5c85eeb9b5e
[ "BSD-2-Clause" ]
7
2020-02-25T15:46:18.000Z
2022-02-25T07:04:47.000Z
svntrunk/src/BlueMatter/util/include/xyz2ziterator.hpp
IBM/BlueMatter
5243c0ef119e599fc3e9b7c4213ecfe837de59f3
[ "BSD-2-Clause" ]
null
null
null
svntrunk/src/BlueMatter/util/include/xyz2ziterator.hpp
IBM/BlueMatter
5243c0ef119e599fc3e9b7c4213ecfe837de59f3
[ "BSD-2-Clause" ]
5
2019-06-06T16:30:21.000Z
2020-11-16T19:43:01.000Z
/* Copyright 2001, 2019 IBM Corporation * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // ********************************************************************* // File: xyz2ziterator.hpp // Author: RSG // Date: July 19, 2003 // Class: XYZ2ZIterator // Description: Class encapsulating iteration over portions of // subvolume contained on a single node that are // destined for a particular processor z-coordinate. // ********************************************************************* #ifndef INCLUDE_FFT_XYZ2ZITERATOR_HPP #define INCLUDE_FFT_XYZ2ZITERATOR_HPP #include <cassert> #include <cstdlib> #include <iostream> #include <utility> namespace fft { template <class TSubVolume> class XYZ2ZRouter; template<class TSubVolume> class XYZ2ZIterator { friend class XYZ2ZRouter<TSubVolume>; public: typedef TSubVolume subVol_type; typedef typename TSubVolume::elt_type elt_type; typedef typename TSubVolume::fftmesh_type fftmesh_type; typedef typename TSubVolume::procmesh_type procmesh_type; enum {DNX = TSubVolume::DNX, DNY = TSubVolume::DNY, DNZ = TSubVolume::DNZ}; enum {DXY = (DNX*DNY)/procmesh_type::PZ, DXZ = (DNX*DNZ)/procmesh_type::PY, DYZ = (DNY*DNZ)/procmesh_type::PX}; private: elt_type (&d_xyz)[DNX][DNY][DNZ]; int d_dx; int d_dy; int d_dz; int d_offset; inline XYZ2ZIterator<TSubVolume>& operator=(const XYZ2ZIterator<TSubVolume>&); public: inline XYZ2ZIterator(TSubVolume&); inline XYZ2ZIterator(const XYZ2ZIterator<TSubVolume>&); inline bool operator==(const XYZ2ZIterator<TSubVolume>&) const; inline bool operator!=(const XYZ2ZIterator<TSubVolume>&) const; inline elt_type& operator*(); inline XYZ2ZIterator<TSubVolume>& operator++(); inline int dx() const; inline int dy() const; inline int dz() const; inline bool isEndOfZ() const; // returns true if iterator is at // last elt of current run of // consecutive z vals // once items are routed to appropriate destination nodes, we need // to be able decipher which x and y values have been placed where. static inline std::pair<int,int> xyFromOffset(int, int, int, int); // args are px, py, pz, dxy }; template <class TSubVolume> std::pair<int,int> XYZ2ZIterator<TSubVolume>::xyFromOffset(int px, int py, int pz, int dxy) { std::pair<int, int> xy; int offset = TSubVolume::DXY*pz + dxy; xy.second = offset % TSubVolume::DNY; xy.first = ((offset - xy.second)/TSubVolume::DNY) + px*TSubVolume::DNX; xy.second = xy.second + py*TSubVolume::DNY; // convert to absolute y return xy; } template <class TSubVolume> class XYZ2ZRouter { private: TSubVolume& d_subV; XYZ2ZIterator<TSubVolume>* d_begin[TSubVolume::procmesh_type::PZ + 1]; public: XYZ2ZRouter(TSubVolume&); inline TSubVolume& subVolume(); // the integer arg is the target pz node coordinate (0 <= pz < PZ) inline const XYZ2ZIterator<TSubVolume>& begin(int) const; inline const XYZ2ZIterator<TSubVolume>& end(int) const; }; template <class TSubVolume> TSubVolume& XYZ2ZRouter<TSubVolume>::subVolume() { return d_subV; } template <class TSubVolume> XYZ2ZRouter<TSubVolume>::XYZ2ZRouter(TSubVolume& subV) : d_subV(subV) { for (int i = 0; i <= TSubVolume::procmesh_type::PZ; ++i) { d_begin[i] = new XYZ2ZIterator<TSubVolume>(subV); assert(d_begin[i] != NULL); if (d_begin[i] == NULL) { std::cerr << "Unable to allocate memory for XYZ2ZIterator" << std::endl; std::exit(-1); } } d_begin[0]->d_dz = 0; d_begin[0]->d_dy = 0; d_begin[0]->d_dx = 0; d_begin[0]->d_offset = 0; int offset = TSubVolume::DXY*TSubVolume::DNZ; for (int i = 1; i <= TSubVolume::procmesh_type::PZ; ++i) { d_begin[i]->d_offset = offset; d_begin[i]->d_dz = offset % TSubVolume::DNZ; int off1 = (offset - d_begin[i]->d_dz)/TSubVolume::DNZ; d_begin[i]->d_dy = off1 % TSubVolume::DNY; d_begin[i]->d_dx = (off1 - d_begin[i]->d_dy)/TSubVolume::DNY; offset = offset + TSubVolume::DXY*TSubVolume::DNZ; } } template <class TSubVolume> const XYZ2ZIterator<TSubVolume>& XYZ2ZRouter<TSubVolume>::begin(int idx) const { assert((idx >= 0) && (idx < TSubVolume::procmesh_type::PZ)); return *d_begin[idx]; } template <class TSubVolume> const XYZ2ZIterator<TSubVolume>& XYZ2ZRouter<TSubVolume>::end(int idx) const { assert((idx >= 0) && (idx < TSubVolume::procmesh_type::PZ)); return *d_begin[idx + 1]; } template<class TSubVolume> XYZ2ZIterator<TSubVolume>::XYZ2ZIterator(TSubVolume& sVol) : d_xyz(sVol.d_xyz), d_dx(-1), d_dy(-1), d_dz(-1), d_offset(-1) { } template<class TSubVolume> XYZ2ZIterator<TSubVolume>::XYZ2ZIterator(const XYZ2ZIterator<TSubVolume>& proto) : d_xyz(proto.d_xyz), d_dx(proto.d_dx), d_dy(proto.d_dy), d_dz(proto.d_dz), d_offset(proto.d_offset) { } template<class TSubVolume> XYZ2ZIterator<TSubVolume>& XYZ2ZIterator<TSubVolume>::operator=(const XYZ2ZIterator<TSubVolume>& other) { return *this; } template<class TSubVolume> bool XYZ2ZIterator<TSubVolume>::operator==(const XYZ2ZIterator<TSubVolume>& other) const { return((&d_xyz == &other.d_xyz) && (d_offset == other.d_offset)); } template<class TSubVolume> bool XYZ2ZIterator<TSubVolume>::operator!=(const XYZ2ZIterator<TSubVolume>& other) const { return(!(*this == other)); } template<class TSubVolume> typename XYZ2ZIterator<TSubVolume>::elt_type& XYZ2ZIterator<TSubVolume>::operator*() { return d_xyz[d_dx][d_dy][d_dz]; } template<class TSubVolume> int XYZ2ZIterator<TSubVolume>::dx() const { return(d_dx); } template<class TSubVolume> int XYZ2ZIterator<TSubVolume>::dy() const { return(d_dy); } template<class TSubVolume> int XYZ2ZIterator<TSubVolume>::dz() const { return(d_dz); } template<class TSubVolume> XYZ2ZIterator<TSubVolume>& XYZ2ZIterator<TSubVolume>::operator++() { d_dz = (++d_dz) % DNZ; if (d_dz == 0) { d_dy = (++d_dy) % DNY; if (d_dy == 0) { d_dx = (++d_dx) % DNX; } } ++d_offset; return *this; } template<class TSubVolume> bool XYZ2ZIterator<TSubVolume>::isEndOfZ() const { return ((d_dz + 1) % DNZ == 0); } } #endif
29.899614
118
0.664773
Bhaskers-Blu-Org1
092cc8fb137d57a9aa8a1af54cbe1913ebfef4c7
772
cpp
C++
CodeForces-Contest/1433/D.cpp
Tech-Intellegent/CodeForces-Solution
2f291a38b80b8ff2a2595b2e526716468ff26bf8
[ "MIT" ]
1
2022-01-23T07:18:07.000Z
2022-01-23T07:18:07.000Z
CodeForces-Contest/1433/D.cpp
Tech-Intellegent/CodeForces-Solution
2f291a38b80b8ff2a2595b2e526716468ff26bf8
[ "MIT" ]
null
null
null
CodeForces-Contest/1433/D.cpp
Tech-Intellegent/CodeForces-Solution
2f291a38b80b8ff2a2595b2e526716468ff26bf8
[ "MIT" ]
1
2022-02-05T11:53:04.000Z
2022-02-05T11:53:04.000Z
#include<bits/stdc++.h> using namespace std; int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; vector<pair<int, int>> a; for (int i = 1; i <= n; i++) { int k; cin >> k; a.push_back({k, i}); } sort(a.begin(), a.end()); if (a[0].first == a[n - 1].first) { cout << "NO\n"; } else { cout << "YES\n"; for (int i = 0; i < n - 1; i++) { if (a[i].first != a[n - 1].first) { cout << a[i].second << ' ' << a[n - 1].second << '\n'; } } for (int i = n - 2; i >= 0; i--) { if (a[i].first == a[n - 1].first) { cout << a[i].second << ' ' << a[0].second << '\n'; } } } } return 0; }
22.705882
64
0.392487
Tech-Intellegent
092d511caf89f0dfdfe395abed1f9bfbe9c430a1
9,954
cpp
C++
src/Entities/Entity.cpp
Mac1512/engge
50c203c09b57c0fbbcdf6284c60886c8db471e07
[ "MIT" ]
null
null
null
src/Entities/Entity.cpp
Mac1512/engge
50c203c09b57c0fbbcdf6284c60886c8db471e07
[ "MIT" ]
null
null
null
src/Entities/Entity.cpp
Mac1512/engge
50c203c09b57c0fbbcdf6284c60886c8db471e07
[ "MIT" ]
null
null
null
#include <memory> #include <optional> #include <utility> #include "Entities/Entity.hpp" #include "Scripting/ScriptEngine.hpp" #include "Audio/SoundTrigger.hpp" #include "Engine/Camera.hpp" #include "Engine/Trigger.hpp" #include "Actor/_TalkingState.hpp" namespace ng { struct Entity::Impl { Engine &_engine; std::map<int, Trigger *> _triggers; std::vector<std::unique_ptr<SoundTrigger>> _soundTriggers; std::optional<sf::Vector2f> _usePos; std::optional<UseDirection> _useDir; sf::Vector2f _offset; bool _isLit{true}; bool _isVisible{true}; bool _isTouchable{true}; sf::Vector2i _renderOffset; Motor _offsetTo, _scaleTo, _rotateTo, _moveTo, _alphaTo; sf::Color _color{sf::Color::White}; bool _objectBumperCycle{true}; sf::Color _talkColor; sf::Vector2i _talkOffset; _TalkingState _talkingState; std::string _key; Impl() : _engine(ng::Locator<ng::Engine>::get()) { _talkingState.setEngine(&_engine); } static std::optional<int> getDefaultVerb(const Entity *pEntity) { if(!pEntity) return std::nullopt; const char *dialog = nullptr; if (ScriptEngine::rawGet(pEntity, "dialog", dialog)) return std::make_optional(VerbConstants::VERB_TALKTO); int value = 0; if(ScriptEngine::rawGet(pEntity, "defaultVerb", value)) return std::make_optional(value); return std::nullopt; } }; Entity::Entity() : pImpl(std::make_unique<Entity::Impl>()) { } Entity::~Entity() = default; void Entity::objectBumperCycle(bool enabled) { pImpl->_objectBumperCycle = enabled; } bool Entity::objectBumperCycle() const { return pImpl->_objectBumperCycle; } void Entity::update(const sf::Time &elapsed) { pImpl->_talkingState.update(elapsed); update(pImpl->_offsetTo, elapsed); update(pImpl->_scaleTo, elapsed); update(pImpl->_rotateTo, elapsed); update(pImpl->_moveTo, elapsed); update(pImpl->_alphaTo, elapsed); } void Entity::update(Motor &motor, const sf::Time &elapsed) { if (motor.isEnabled) { (*motor.function)(elapsed); if (motor.isEnabled && motor.function->isElapsed()) { motor.isEnabled = false; } } } void Entity::setLit(bool isLit) { pImpl->_isLit = isLit; } bool Entity::isLit() const { return pImpl->_isLit; } void Entity::setVisible(bool isVisible) { pImpl->_isVisible = isVisible; } bool Entity::isVisible() const { return pImpl->_isVisible; } void Entity::setUsePosition(std::optional<sf::Vector2f> pos) { pImpl->_usePos = pos; } void Entity::setUseDirection(std::optional<UseDirection> direction) { pImpl->_useDir = direction; } std::optional<UseDirection> Entity::getUseDirection() const { return pImpl->_useDir; } void Entity::setPosition(const sf::Vector2f &pos) { _transform.setPosition(pos); pImpl->_moveTo.isEnabled = false; } sf::Vector2f Entity::getPosition() const { return _transform.getPosition(); } sf::Vector2f Entity::getRealPosition() const { return getPosition() + pImpl->_offset; } void Entity::setOffset(const sf::Vector2f &offset) { pImpl->_offset = offset; pImpl->_offsetTo.isEnabled = false; } sf::Vector2f Entity::getOffset() const { return pImpl->_offset; } void Entity::setRotation(float angle) { _transform.setRotation(angle); } float Entity::getRotation() const { // SFML give rotation in degree between [0, 360] float angle = _transform.getRotation(); // convert it to [-180, 180] if (angle > 180) angle -= 360; return angle; } void Entity::setColor(const sf::Color &color) { pImpl->_color = color; pImpl->_alphaTo.isEnabled = false; } const sf::Color &Entity::getColor() const { return pImpl->_color; } void Entity::setScale(float s) { _transform.setScale(s, s); pImpl->_scaleTo.isEnabled = false; } float Entity::getScale() const { return _transform.getScale().x; } sf::Transformable Entity::getTransform() const { auto transform = _transform; transform.move(pImpl->_offset.x, pImpl->_offset.y); return transform; } std::optional<sf::Vector2f> Entity::getUsePosition() const { return pImpl->_usePos; } void Entity::setTrigger(int triggerNumber, Trigger *pTrigger) { pImpl->_triggers[triggerNumber] = pTrigger; } void Entity::removeTrigger(int triggerNumber) { pImpl->_triggers.erase(triggerNumber); } void Entity::trig(int triggerNumber) { auto it = pImpl->_triggers.find(triggerNumber); if (it != pImpl->_triggers.end()) { it->second->trig(); } } void Entity::trigSound(const std::string &) { } void Entity::drawForeground(sf::RenderTarget &target, sf::RenderStates s) const { if (!pImpl->_talkingState.isTalking()) return; target.draw(pImpl->_talkingState, s); } SoundTrigger *Entity::createSoundTrigger(Engine &engine, const std::vector<SoundDefinition *> &sounds) { auto trigger = std::make_unique<SoundTrigger>(engine, sounds, this->getId()); SoundTrigger *pTrigger = trigger.get(); pImpl->_soundTriggers.push_back(std::move(trigger)); return pTrigger; } void Entity::setKey(const std::string &key) { pImpl->_key = key; } const std::string &Entity::getKey() const { return pImpl->_key; } uint32_t Entity::getFlags() const { int flags = 0; ScriptEngine::rawGet(this, "flags", flags); return (uint32_t) flags; } void Entity::setTouchable(bool isTouchable) { pImpl->_isTouchable = isTouchable; } bool Entity::isTouchable() const { if (!isVisible()) return false; return pImpl->_isTouchable; } void Entity::setRenderOffset(const sf::Vector2i &offset) { pImpl->_renderOffset = offset; } sf::Vector2i Entity::getRenderOffset() const { return pImpl->_renderOffset; } void Entity::alphaTo(float destination, sf::Time time, InterpolationMethod method) { auto getAlpha = [this] { return static_cast<float>(getColor().a) / 255.f; }; auto setAlpha = [this](const float &a) { pImpl->_color.a = static_cast<sf::Uint8>(a * 255.f); }; auto alphaTo = std::make_unique<ChangeProperty<float>>(getAlpha, setAlpha, destination, time, method); pImpl->_alphaTo.function = std::move(alphaTo); pImpl->_alphaTo.isEnabled = true; } void Entity::offsetTo(sf::Vector2f destination, sf::Time time, InterpolationMethod method) { auto get = [this] { return pImpl->_offset; }; auto set = [this](const sf::Vector2f &value) { pImpl->_offset = value; }; auto offsetTo = std::make_unique<ChangeProperty<sf::Vector2f>>(get, set, destination, time, method); pImpl->_offsetTo.function = std::move(offsetTo); pImpl->_offsetTo.isEnabled = true; } void Entity::moveTo(sf::Vector2f destination, sf::Time time, InterpolationMethod method) { auto get = [this] { return getPosition(); }; auto set = [this](const sf::Vector2f &value) { _transform.setPosition(value); }; auto moveTo = std::make_unique<ChangeProperty<sf::Vector2f>>(get, set, destination, time, method); pImpl->_moveTo.function = std::move(moveTo); pImpl->_moveTo.isEnabled = true; } void Entity::rotateTo(float destination, sf::Time time, InterpolationMethod method) { auto get = [this] { return getRotation(); }; auto set = [this](const float &value) { _transform.setRotation(value); }; auto rotateTo = std::make_unique<ChangeProperty<float>>(get, set, destination, time, method); pImpl->_rotateTo.function = std::move(rotateTo); pImpl->_rotateTo.isEnabled = true; } void Entity::scaleTo(float destination, sf::Time time, InterpolationMethod method) { auto get = [this] { return _transform.getScale().x; }; auto set = [this](const float &s) { _transform.setScale(s, s); }; auto scalteTo = std::make_unique<ChangeProperty<float>>(get, set, destination, time, method); pImpl->_scaleTo.function = std::move(scalteTo); pImpl->_scaleTo.isEnabled = true; } void Entity::setName(const std::string &name) { ScriptEngine::set(getTable(), "name", name.c_str()); } std::string Entity::getName() const { const char *name = nullptr; ScriptEngine::get(getTable(), "name", name); if (!name) return std::string(); return name; } void Entity::stopObjectMotors() { pImpl->_offsetTo.isEnabled = false; pImpl->_scaleTo.isEnabled = false; pImpl->_rotateTo.isEnabled = false; pImpl->_moveTo.isEnabled = false; pImpl->_alphaTo.isEnabled = false; } void Entity::setTalkColor(sf::Color color) { pImpl->_talkColor = color; } sf::Color Entity::getTalkColor() const { return pImpl->_talkColor; } void Entity::setTalkOffset(const sf::Vector2i &offset) { pImpl->_talkOffset = offset; } sf::Vector2i Entity::getTalkOffset() const { return pImpl->_talkOffset; } void Entity::say(const std::string &text, bool mumble) { pImpl->_talkingState.loadLip(text, this, mumble); sf::Vector2f pos; auto screenSize = pImpl->_engine.getRoom()->getScreenSize(); if (getRoom() == pImpl->_engine.getRoom()) { auto at = pImpl->_engine.getCamera().getAt(); pos = getRealPosition(); pos = {pos.x - at.x + pImpl->_talkOffset.x, screenSize.y - pos.y - at.y - pImpl->_talkOffset.y}; } else { // TODO: the position in this case is wrong, don't know what to do yet pos = (sf::Vector2f) pImpl->_talkOffset; pos = {pos.x, screenSize.y + pos.y}; } pos = toDefaultView((sf::Vector2i) pos, pImpl->_engine.getRoom()->getScreenSize()); pImpl->_talkingState.setPosition(pos); } void Entity::stopTalking() { pImpl->_talkingState.stop(); } bool Entity::isTalking() const { return pImpl->_talkingState.isTalking(); } int Entity::getDefaultVerb(int defaultVerbId) const { auto result = pImpl->getDefaultVerb(this); if(result.has_value()) return result.value(); result = pImpl->getDefaultVerb(getActor(this)); return result.value_or(defaultVerbId); } Actor *Entity::getActor(const Entity *pEntity) { // if an actor has the same name then get its flags auto &actors = Locator<Engine>::get().getActors(); auto itActor = std::find_if(actors.begin(), actors.end(), [pEntity](auto &pActor) -> bool { return pActor->getName() == pEntity->getName(); }); if (itActor != actors.end()) { return itActor->get(); } return nullptr; } } // namespace ng
29.713433
104
0.703335
Mac1512
092ddcb732ca5a2361c9dd48e6a35c5f50853686
350
hpp
C++
PolyDock/PolyDock/src/pd/ecs/cmp/tabbedWindow/Closing.hpp
PolyEngineTeam/PolyDock
27a105b2cc80db4286e03a2a1e5bee64438d37c8
[ "MIT" ]
3
2020-05-16T16:33:51.000Z
2021-08-05T18:48:13.000Z
PolyDock/PolyDock/src/pd/ecs/cmp/tabbedWindow/Closing.hpp
Qt-Widgets/PolyDock
f32def214753ca0f6bab9968bc2bb5e451cb6e4f
[ "MIT" ]
30
2020-03-25T17:22:51.000Z
2020-08-17T00:33:04.000Z
PolyDock/PolyDock/src/pd/ecs/cmp/tabbedWindow/Closing.hpp
Qt-Widgets/PolyDock
f32def214753ca0f6bab9968bc2bb5e451cb6e4f
[ "MIT" ]
5
2020-03-26T17:12:34.000Z
2021-03-05T08:08:39.000Z
#pragma once namespace pd::ecs::cmp::tabbedWindow { // --------------------------------------------------------------------------------------------------------- class CloseRequest { public: }; // --------------------------------------------------------------------------------------------------------- class RemoveRequest { public: }; }
20.588235
109
0.245714
PolyEngineTeam
09310aca8e08455b103a30295e0d982738ab13ed
2,871
cpp
C++
src/packet.cpp
fossabot/caracal
2707faec995b6cf87baae1554d8f29fa47c86aa6
[ "MIT" ]
null
null
null
src/packet.cpp
fossabot/caracal
2707faec995b6cf87baae1554d8f29fa47c86aa6
[ "MIT" ]
null
null
null
src/packet.cpp
fossabot/caracal
2707faec995b6cf87baae1554d8f29fa47c86aa6
[ "MIT" ]
null
null
null
#include <net/ethernet.h> #include <netinet/ip.h> #include <netinet/ip6.h> #include <netinet/udp.h> #include <caracal/constants.hpp> #include <caracal/packet.hpp> #include <span> #include <stdexcept> namespace caracal { Packet::Packet(const std::span<std::byte> buffer, const uint8_t l2_protocol, const uint8_t l3_protocol, const uint8_t l4_protocol, const size_t payload_size) { l2_protocol_ = l2_protocol; l3_protocol_ = l3_protocol; l4_protocol_ = l4_protocol; size_t l2_header_size; size_t l3_header_size; size_t l4_header_size; // Pad the beginning of the packet to align on a four-byte boundary. // See https://lwn.net/Articles/89597/. size_t padding; switch (l2_protocol) { case L2PROTO_BSDLOOPBACK: l2_header_size = sizeof(uint32_t); padding = 0; break; case L2PROTO_ETHERNET: l2_header_size = sizeof(ether_header); padding = 2; break; case L2PROTO_NONE: l2_header_size = 0; padding = 0; break; default: throw std::invalid_argument{"Unsupported L2 protocol"}; } switch (l3_protocol) { case IPPROTO_IP: l3_header_size = sizeof(ip); break; case IPPROTO_IPV6: l3_header_size = sizeof(ip6_hdr); break; default: throw std::invalid_argument{"Unsupported L3 protocol"}; } switch (l4_protocol) { case IPPROTO_ICMPV6: l4_header_size = ICMPV6_HEADER_SIZE; break; case IPPROTO_ICMP: l4_header_size = ICMP_HEADER_SIZE; break; case IPPROTO_UDP: l4_header_size = sizeof(udphdr); break; default: throw std::invalid_argument{"Unsupported L4 protocol"}; } begin_ = buffer.data(); l2_ = begin_ + padding; l3_ = l2_ + l2_header_size; l4_ = l3_ + l3_header_size; payload_ = l4_ + l4_header_size; end_ = payload_ + payload_size; if (buffer.size() < static_cast<uint64_t>(end_ - begin_)) { throw std::invalid_argument{"Packet buffer is too small"}; } } std::byte* Packet::begin() const noexcept { return begin_; } std::byte* Packet::end() const noexcept { return end_; } std::byte* Packet::l2() const noexcept { return l2_; } std::byte* Packet::l3() const noexcept { return l3_; } std::byte* Packet::l4() const noexcept { return l4_; } std::byte* Packet::payload() const noexcept { return payload_; } size_t Packet::l2_size() const noexcept { return end_ - l2_; } size_t Packet::l3_size() const noexcept { return end_ - l3_; } size_t Packet::l4_size() const noexcept { return end_ - l4_; } size_t Packet::payload_size() const noexcept { return end_ - payload_; } uint8_t Packet::l2_protocol() const noexcept { return l2_protocol_; } uint8_t Packet::l3_protocol() const noexcept { return l3_protocol_; } uint8_t Packet::l4_protocol() const noexcept { return l4_protocol_; } } // namespace caracal
24.538462
76
0.680599
fossabot
09341207e208e5874f8eb2ea1c598eb265e9033e
864
cpp
C++
307. Range Sum Query - Mutable/main.cpp
Competitive-Programmers-Community/LeetCode
841fdee805b1a626e9f1cd0e12398d25054638af
[ "MIT" ]
2
2019-10-05T09:48:20.000Z
2019-10-05T15:40:01.000Z
307. Range Sum Query - Mutable/main.cpp
Competitive-Programmers-Community/LeetCode
841fdee805b1a626e9f1cd0e12398d25054638af
[ "MIT" ]
null
null
null
307. Range Sum Query - Mutable/main.cpp
Competitive-Programmers-Community/LeetCode
841fdee805b1a626e9f1cd0e12398d25054638af
[ "MIT" ]
3
2020-09-27T05:48:30.000Z
2021-08-13T10:07:08.000Z
class NumArray { private: const int N = 1e5; int n; vector<int> t = vector<int>(2*N); public: void build(){ for(int i=n-1;i>0;i--) t[i] = t[i<<1] +t[i<<1 | 1]; } NumArray(vector<int> nums) { n=nums.size(); for(int i=0; i<n; i++) t[n+i]=nums[i]; build(); } void update(int p, int value) { for(t[p += n] = value; p>1; p>>=1) t[p>>1] = t[p] +t[p^1]; } int sumRange(int l, int r) { r+=1; int res=0; for(l += n, r += n; l<r; l >>= 1, r >>= 1){ if(l&1) res += t[l++]; if(r&1) res += t[--r]; } return res; } }; /** * Your NumArray object will be instantiated and called as such: * NumArray obj = new NumArray(nums); * obj.update(i,val); * int param_2 = obj.sumRange(i,j); */
20.571429
66
0.431713
Competitive-Programmers-Community
09397e65e69a15cd883f4dbf77802cee6d966d6a
1,372
cpp
C++
ROS/dextrobot_ws/src/dextrobot_controller/src/arduino/base_controller/src/Imu.cpp
AntoBrandi/Dextro-Bot
533f873485b1c8d816c6ed368b63c03e476102b9
[ "MIT", "Unlicense" ]
3
2021-07-02T15:40:32.000Z
2022-01-09T15:09:51.000Z
ROS/dextrobot_ws/src/dextrobot_controller/src/arduino/simplified_controller/src/Imu.cpp
AntoBrandi/DextroBot
533f873485b1c8d816c6ed368b63c03e476102b9
[ "MIT", "Unlicense" ]
null
null
null
ROS/dextrobot_ws/src/dextrobot_controller/src/arduino/simplified_controller/src/Imu.cpp
AntoBrandi/DextroBot
533f873485b1c8d816c6ed368b63c03e476102b9
[ "MIT", "Unlicense" ]
1
2021-05-22T09:14:18.000Z
2021-05-22T09:14:18.000Z
#include <Imu.h> Imu::Imu(/* args */) { } Imu::~Imu() { } // convert RPY degrees angles to Radians float Imu::toRadians(float degree){ return degree*PI/180; } // reads the value coming from the IMU sensor and update the class parameters void Imu::sense(){ Vector normAccel = mpu.readNormalizeAccel(); Vector normGyro = mpu.readNormalizeGyro(); // Calculate Pitch & Roll pitch = -(atan2(normAccel.XAxis, sqrt(normAccel.YAxis*normAccel.YAxis + normAccel.ZAxis*normAccel.ZAxis))*180.0)/M_PI; roll = (atan2(normAccel.YAxis, normAccel.ZAxis)*180.0)/M_PI; //Ignore the gyro if our angular velocity does not meet our threshold if (normGyro.ZAxis > 1 || normGyro.ZAxis < -1) { normGyro.ZAxis /= 100; yaw += normGyro.ZAxis; } //Keep our angle between 0-359 degrees if (yaw < 0) yaw += 360; else if (yaw > 359) yaw -= 360; AcX = normAccel.XAxis; AcY = normAccel.YAxis; AcZ = normAccel.ZAxis; } // Get the data coming from the IMU sensor and arrange those in a ROS string message String Imu::composeStringMessage(){ String data = String(AcX) + "," + String(AcY) + "," + String(AcZ) + "," + String(toRadians(roll)) + ","+ String(toRadians(pitch)) + "," + String(toRadians(yaw)); return data; }
27.44
165
0.605685
AntoBrandi
093a589217357fd94267135d51c8dfe8c0db74a2
9,098
cpp
C++
Backend/VitisAI-MicroApps/vitis_ai_image_lane_detect.cpp
bluetiger9/VCK5000-AIaaS
5857fbc43db01c7665e8534278a8be3337136768
[ "Apache-2.0" ]
null
null
null
Backend/VitisAI-MicroApps/vitis_ai_image_lane_detect.cpp
bluetiger9/VCK5000-AIaaS
5857fbc43db01c7665e8534278a8be3337136768
[ "Apache-2.0" ]
null
null
null
Backend/VitisAI-MicroApps/vitis_ai_image_lane_detect.cpp
bluetiger9/VCK5000-AIaaS
5857fbc43db01c7665e8534278a8be3337136768
[ "Apache-2.0" ]
null
null
null
/* * Copyright © 2022 Attila Tőkés. * * Licensed under the Apache License, Version 2.0 (the "License"). */ #include <cstddef> #include <glog/logging.h> #include <iostream> #include <ostream> #include <memory> #include <cmath> #include <opencv2/core.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/imgcodecs.hpp> #include <vitis/ai/lanedetect.hpp> void output_result(vitis::ai::RoadLineResult &result) { std::cout << "{" << std::endl << " \"results\": [" << std::endl; for (auto it = begin(result.lines); it != end(result.lines); ++it) { auto r = *it; std::cout << " { \"type\": " << r.type << ", \"points\": [" << std::endl; for (auto itPoint = begin(r.points_cluster); itPoint != end(r.points_cluster); ++itPoint) { auto point = *itPoint; std::cout << " { \"x\": " << point.x << ", \"y\": " << point.y << " }"; if (itPoint != end(r.points_cluster) - 1) { std::cout << ","; } std::cout << std::endl; } std::cout << " ]" << std::endl << " }"; if (it != end(result.lines) - 1) { std::cout << ","; } std::cout << std::endl; } std::cout << " ]" << std::endl << "}" << std::endl; } void classify(std::string model_name, std::string image_file_name) { auto model = vitis::ai::RoadLine::create(model_name); auto image = cv::imread(image_file_name); if (image.empty()) { LOG(FATAL) << "cannot load " << image_file_name << std::endl; abort(); } auto result = model->run(image); output_result(result); } int main(int argc, char *argv[]) { google::InitGoogleLogging(argv[0]); if (argc != 3) { LOG(FATAL) << "Usage: " << argv[0] << " <model> <image-path>" << std::endl; return -1; } LOG(INFO) << "Vitis AI Lane Detect MicroApp" << std::endl;; std::string model = argv[1]; std::string image_path = argv[2]; #if !defined VITIS_DUMMY_RESULTS classify(model, image_path); return 0; #else // dummy results mode vitis::ai::RoadLineResult result; std::vector< cv::Point > points_cluster_1 = { { 164, 377 }, { 165, 376 }, { 166, 375 }, { 167, 373 }, { 168, 372 }, { 169, 371 }, { 170, 369 }, { 171, 368 }, { 172, 367 }, { 173, 365 }, { 174, 364 }, { 175, 363 }, { 176, 362 }, { 177, 360 }, { 178, 359 }, { 179, 358 }, { 180, 356 }, { 181, 355 }, { 182, 354 }, { 183, 352 }, { 184, 351 }, { 185, 350 }, { 186, 348 }, { 187, 347 }, { 188, 346 }, { 189, 345 }, { 190, 343 }, { 191, 342 }, { 192, 341 }, { 193, 339 }, { 194, 338 }, { 195, 337 }, { 196, 335 }, { 197, 334 }, { 198, 333 }, { 199, 332 }, { 200, 330 }, { 201, 329 }, { 202, 328 }, { 203, 326 }, { 204, 325 }, { 205, 324 }, { 206, 322 }, { 207, 321 }, { 208, 320 }, { 209, 319 }, { 210, 317 }, { 211, 316 }, { 212, 315 }, { 213, 313 }, { 214, 312 }, { 215, 311 }, { 216, 309 }, { 217, 308 }, { 218, 307 }, { 219, 305 }, { 220, 304 }, { 221, 303 }, { 222, 302 }, { 223, 300 }, { 224, 299 }, { 225, 298 }, { 226, 296 }, { 227, 295 }, { 228, 294 }, { 229, 292 }, { 230, 291 }, { 231, 290 }, { 232, 289 }, { 233, 287 }, { 234, 286 }, { 235, 285 }, { 236, 283 }, { 237, 282 }, { 238, 281 }, { 239, 279 }, { 240, 278 }, { 241, 277 }, { 242, 276 }, { 243, 274 }, { 244, 273 }, { 245, 272 }, { 246, 270 }, { 247, 269 }, { 248, 268 }, { 249, 266 }, { 250, 265 }, { 251, 264 }, { 252, 262 }, { 253, 261 }, { 254, 260 }, { 255, 259 }, { 256, 257 }, { 257, 256 }, { 258, 255 }, { 259, 253 }, { 260, 252 }, { 261, 251 }, { 262, 249 }, { 263, 248 }, { 264, 247 }, { 265, 246 }, { 266, 244 }, { 267, 243 }, { 268, 242 }, { 269, 240 }, { 270, 239 }, { 271, 238 }, { 272, 236 }, { 273, 235 }, { 274, 234 }, { 275, 233 }, { 276, 231 }, { 277, 230 }, { 278, 229 }, { 279, 227 }, { 280, 226 }, { 281, 225 }, { 282, 223 }, { 283, 222 }, { 284, 221 }, { 285, 219 }, { 286, 218 }, { 287, 217 }, { 288, 216 }, { 289, 214 }, { 290, 213 }, { 291, 212 }, { 292, 210 }, { 293, 209 }, { 294, 208 }, { 295, 206 }, { 296, 205 }, { 297, 204 }, { 298, 203 }, { 299, 201 }, { 300, 200 } }; result.lines.push_back({ 3, points_cluster_1 }); std::vector< cv::Point > points_cluster_2 = { { 340, 202 }, { 341, 203 }, { 342, 205 }, { 343, 206 }, { 344, 207 }, { 345, 209 }, { 346, 210 }, { 347, 211 }, { 348, 213 }, { 349, 214 }, { 350, 215 }, { 351, 217 }, { 352, 218 }, { 353, 219 }, { 354, 221 }, { 355, 222 }, { 356, 224 }, { 357, 225 }, { 358, 226 }, { 359, 228 }, { 360, 229 }, { 361, 230 }, { 362, 232 }, { 363, 233 }, { 364, 234 }, { 365, 236 }, { 366, 237 }, { 367, 239 }, { 368, 240 }, { 369, 241 }, { 370, 243 }, { 371, 244 }, { 372, 245 }, { 373, 247 }, { 374, 248 }, { 375, 249 }, { 376, 251 }, { 377, 252 }, { 378, 253 }, { 379, 255 }, { 380, 256 }, { 381, 258 }, { 382, 259 }, { 383, 260 }, { 384, 262 }, { 385, 263 }, { 386, 264 }, { 387, 266 }, { 388, 267 }, { 389, 268 }, { 390, 270 }, { 391, 271 }, { 392, 273 }, { 393, 274 }, { 394, 275 }, { 395, 277 }, { 396, 278 }, { 397, 279 }, { 398, 281 }, { 399, 282 }, { 400, 283 }, { 401, 285 }, { 402, 286 }, { 403, 287 }, { 404, 289 }, { 405, 290 }, { 406, 292 }, { 407, 293 }, { 408, 294 }, { 409, 296 }, { 410, 297 }, { 411, 298 }, { 412, 300 }, { 413, 301 }, { 414, 302 }, { 415, 304 }, { 416, 305 }, { 417, 307 }, { 418, 308 }, { 419, 309 }, { 420, 311 }, { 421, 312 }, { 422, 313 }, { 423, 315 }, { 424, 316 }, { 425, 317 }, { 426, 319 }, { 427, 320 }, { 428, 321 } }; result.lines.push_back({ 1, points_cluster_2 }); std::vector< cv::Point > points_cluster_3 = { { 396, 212 }, { 397, 213 }, { 398, 213 }, { 399, 214 }, { 400, 214 }, { 401, 215 }, { 402, 215 }, { 403, 216 }, { 404, 216 }, { 405, 217 }, { 406, 217 }, { 407, 218 }, { 408, 218 }, { 409, 219 }, { 410, 220 }, { 411, 220 }, { 412, 221 }, { 413, 221 }, { 414, 222 }, { 415, 222 }, { 416, 223 }, { 417, 223 }, { 418, 224 }, { 419, 224 }, { 420, 225 }, { 421, 225 }, { 422, 226 }, { 423, 226 }, { 424, 227 }, { 425, 228 }, { 426, 228 }, { 427, 229 }, { 428, 229 }, { 429, 230 }, { 430, 230 }, { 431, 231 }, { 432, 231 }, { 433, 232 }, { 434, 232 }, { 435, 233 }, { 436, 233 }, { 437, 234 }, { 438, 234 }, { 439, 235 }, { 440, 236 }, { 441, 236 }, { 442, 237 }, { 443, 237 }, { 444, 238 }, { 445, 238 }, { 446, 239 }, { 447, 239 }, { 448, 240 }, { 449, 240 }, { 450, 241 }, { 451, 241 }, { 452, 242 }, { 453, 242 }, { 454, 243 }, { 455, 244 }, { 456, 244 }, { 457, 245 }, { 458, 245 }, { 459, 246 }, { 460, 246 }, { 461, 247 }, { 462, 247 }, { 463, 248 }, { 464, 248 }, { 465, 249 }, { 466, 249 }, { 467, 250 }, { 468, 250 }, { 469, 251 }, { 470, 252 }, { 471, 252 }, { 472, 253 }, { 473, 253 }, { 474, 254 }, { 475, 254 }, { 476, 255 }, { 477, 255 }, { 478, 256 }, { 479, 256 }, { 480, 257 }, { 481, 257 }, { 482, 258 }, { 483, 258 }, { 484, 259 }, { 485, 259 }, { 486, 260 }, { 487, 261 }, { 488, 261 }, { 489, 262 }, { 490, 262 }, { 491, 263 }, { 492, 263 }, { 493, 264 }, { 494, 264 }, { 495, 265 }, { 496, 265 }, { 497, 266 }, { 498, 266 }, { 499, 267 }, { 500, 267 }, { 501, 268 }, { 502, 269 }, { 503, 269 }, { 504, 270 }, { 505, 270 }, { 506, 271 }, { 507, 271 }, { 508, 272 }, { 509, 272 }, { 510, 273 }, { 511, 273 }, { 512, 274 }, { 513, 274 }, { 514, 275 }, { 515, 275 }, { 516, 276 }, { 517, 277 }, { 518, 277 }, { 519, 278 }, { 520, 278 }, { 521, 279 }, { 522, 279 }, { 523, 280 }, { 524, 280 }, { 525, 281 }, { 526, 281 }, { 527, 282 }, { 528, 282 }, { 529, 283 }, { 530, 283 }, { 531, 284 }, { 532, 285 }, { 533, 285 }, { 534, 286 }, { 535, 286 }, { 536, 287 }, { 537, 287 }, { 538, 288 }, { 539, 288 }, { 540, 289 }, { 541, 289 }, { 542, 290 }, { 543, 290 }, { 544, 291 }, { 545, 291 }, { 546, 292 }, { 547, 293 }, { 548, 293 }, { 549, 294 }, { 550, 294 }, { 551, 295 }, { 552, 295 }, { 553, 296 }, { 554, 296 }, { 555, 297 }, { 556, 297 }, { 557, 298 }, { 558, 298 }, { 559, 299 }, { 560, 299 }, { 561, 300 }, { 562, 301 }, { 563, 301 }, { 564, 302 } }; result.lines.push_back({ 2, points_cluster_3 }); std::vector< cv::Point > points_cluster_4 = { { 52, 292 }, { 53, 291 }, { 54, 291 }, { 55, 290 }, { 56, 290 }, { 57, 289 }, { 58, 289 }, { 59, 288 }, { 60, 288 }, { 61, 287 }, { 62, 287 }, { 63, 286 }, { 64, 286 }, { 65, 285 }, { 66, 285 }, { 67, 284 }, { 68, 284 }, { 69, 283 }, { 70, 283 }, { 71, 282 }, { 72, 282 }, { 73, 281 }, { 74, 281 }, { 75, 280 }, { 76, 280 }, { 77, 279 }, { 78, 279 }, { 79, 278 }, { 80, 278 }, { 81, 277 }, { 82, 277 }, { 83, 276 }, { 84, 276 } }; result.lines.push_back({ 1, points_cluster_4 }); std::vector< cv::Point > points_cluster_5 = { { 172, 236 }, { 173, 235 }, { 174, 235 }, { 175, 234 }, { 176, 234 }, { 177, 233 }, { 178, 232 }, { 179, 232 }, { 180, 231 }, { 181, 231 }, { 182, 230 }, { 183, 230 }, { 184, 229 }, { 185, 228 }, { 186, 228 }, { 187, 227 }, { 188, 227 }, { 189, 226 }, { 190, 226 }, { 191, 225 }, { 192, 224 }, { 193, 224 }, { 194, 223 }, { 195, 223 }, { 196, 222 }, { 197, 222 }, { 198, 221 }, { 199, 220 }, { 200, 220 }, { 201, 219 }, { 202, 219 }, { 203, 218 }, { 204, 218 }, { 205, 217 }, { 206, 216 }, { 207, 216 }, { 208, 215 }, { 209, 215 }, { 210, 214 }, { 211, 214 }, { 212, 213 } }; result.lines.push_back({ 1, points_cluster_5 }); output_result(result); return 0 ; #endif }
94.770833
2,415
0.473511
bluetiger9
093a5c8529da37820921fdc210541b64d309227e
25,284
cpp
C++
mcts-xboard/eleeye/preeval.cpp
milkpku/BetaElephant
0db6140d328355ac0a3c7f9f667ca760f5096711
[ "MIT" ]
28
2016-05-25T11:49:24.000Z
2021-12-06T15:21:52.000Z
mcts-xboard/eleeye/preeval.cpp
milkpku/BetaElephant
0db6140d328355ac0a3c7f9f667ca760f5096711
[ "MIT" ]
3
2016-09-21T11:55:45.000Z
2021-11-27T16:20:04.000Z
mcts-xboard/eleeye/preeval.cpp
milkpku/BetaElephant
0db6140d328355ac0a3c7f9f667ca760f5096711
[ "MIT" ]
16
2016-05-03T06:42:37.000Z
2021-06-26T17:03:15.000Z
/* preeval.h/preeval.cpp - Source Code for ElephantEye, Part X ElephantEye - a Chinese Chess Program (UCCI Engine) Designed by Morning Yellow, Version: 3.3, Last Modified: Mar. 2012 Copyright (C) 2004-2012 www.xqbase.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../base/base.h" #include "pregen.h" #include "position.h" #include "preeval.h" /* ElephantEye源程序使用的匈牙利记号约定: * * sq: 格子序号(整数,从0到255,参阅"pregen.cpp") * pc: 棋子序号(整数,从0到47,参阅"position.cpp") * pt: 棋子类型序号(整数,从0到6,参阅"position.cpp") * mv: 着法(整数,从0到65535,参阅"position.cpp") * sd: 走子方(整数,0代表红方,1代表黑方) * vl: 局面价值(整数,从"-MATE_VALUE"到"MATE_VALUE",参阅"position.cpp") * (注:以上五个记号可与uc、dw等代表整数的记号配合使用) * pos: 局面(PositionStruct类型,参阅"position.h") * sms: 位行和位列的着法生成预置结构(参阅"pregen.h") * smv: 位行和位列的着法判断预置结构(参阅"pregen.h") */ /* 子力位置价值表 * ElephantEye的子力位置价值表对局面评价的导向起了很大的作用,在参照“梦入神蛋”程序的基础上,作了如下改动: * 1. 把棋力基本分和位置相关分组合在一起,以利于快速运算; * 2. 一九路的兵(卒)在巡河位置分值减少了5分,以减少盲目进边兵(卒)的情况; * 3. 过河兵(卒)(底线除外)多加10分,以减少过河兵(卒)盲目换仕(士)相(象)的情况; * 4. 一九路车在横车的位置分值减少了5分,以减少上仕(士)时还起无意义的横车的情况。 */ // 1. 开中局、有进攻机会的帅(将)和兵(卒),参照“梦入神蛋” static const uint8_t cucvlKingPawnMidgameAttacking[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 11, 13, 11, 9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 39, 49, 69, 84, 89, 84, 69, 49, 39, 0, 0, 0, 0, 0, 0, 0, 39, 49, 64, 74, 74, 74, 64, 49, 39, 0, 0, 0, 0, 0, 0, 0, 39, 46, 54, 59, 61, 59, 54, 46, 39, 0, 0, 0, 0, 0, 0, 0, 29, 37, 41, 54, 59, 54, 41, 37, 29, 0, 0, 0, 0, 0, 0, 0, 7, 0, 13, 0, 16, 0, 13, 0, 7, 0, 0, 0, 0, 0, 0, 0, 7, 0, 7, 0, 15, 0, 7, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 15, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 2. 开中局、没有进攻机会的帅(将)和兵(卒) static const uint8_t cucvlKingPawnMidgameAttackless[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 11, 13, 11, 9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 19, 24, 34, 42, 44, 42, 34, 24, 19, 0, 0, 0, 0, 0, 0, 0, 19, 24, 32, 37, 37, 37, 32, 24, 19, 0, 0, 0, 0, 0, 0, 0, 19, 23, 27, 29, 30, 29, 27, 23, 19, 0, 0, 0, 0, 0, 0, 0, 14, 18, 20, 27, 29, 27, 20, 18, 14, 0, 0, 0, 0, 0, 0, 0, 7, 0, 13, 0, 16, 0, 13, 0, 7, 0, 0, 0, 0, 0, 0, 0, 7, 0, 7, 0, 15, 0, 7, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 15, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 3. 残局、有进攻机会的帅(将)和兵(卒) static const uint8_t cucvlKingPawnEndgameAttacking[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 15, 15, 15, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 50, 55, 60, 85,100, 85, 60, 55, 50, 0, 0, 0, 0, 0, 0, 0, 65, 70, 70, 75, 75, 75, 70, 70, 65, 0, 0, 0, 0, 0, 0, 0, 75, 80, 80, 80, 80, 80, 80, 80, 75, 0, 0, 0, 0, 0, 0, 0, 70, 70, 65, 70, 70, 70, 65, 70, 70, 0, 0, 0, 0, 0, 0, 0, 45, 0, 40, 45, 45, 45, 40, 0, 45, 0, 0, 0, 0, 0, 0, 0, 40, 0, 35, 40, 40, 40, 35, 0, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 15, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 13, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 11, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 4. 残局、没有进攻机会的帅(将)和兵(卒) static const uint8_t cucvlKingPawnEndgameAttackless[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 15, 15, 15, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 10, 15, 20, 45, 60, 45, 20, 15, 10, 0, 0, 0, 0, 0, 0, 0, 25, 30, 30, 35, 35, 35, 30, 30, 25, 0, 0, 0, 0, 0, 0, 0, 35, 40, 40, 45, 45, 45, 40, 40, 35, 0, 0, 0, 0, 0, 0, 0, 25, 30, 30, 35, 35, 35, 30, 30, 25, 0, 0, 0, 0, 0, 0, 0, 25, 0, 25, 25, 25, 25, 25, 0, 25, 0, 0, 0, 0, 0, 0, 0, 20, 0, 20, 20, 20, 20, 20, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 13, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 12, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 11, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 5. 没受威胁的仕(士)和相(象) static const uint8_t cucvlAdvisorBishopThreatless[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 0, 0, 20, 23, 20, 0, 0, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 23, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 20, 0, 20, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 5'. 可升变的,没受威胁的仕(士)和相(象) static const uint8_t cucvlAdvisorBishopPromotionThreatless[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 30, 0, 0, 0, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 0, 0, 30, 33, 30, 0, 0, 28, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 30, 30, 0, 30, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 6. 受到威胁的仕(士)和相(象),参照“梦入神蛋” static const uint8_t cucvlAdvisorBishopThreatened[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 40, 0, 0, 0, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 38, 0, 0, 40, 43, 40, 0, 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 43, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 40, 40, 0, 40, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 7. 开中局的马,参照“梦入神蛋” static const uint8_t cucvlKnightMidgame[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 90, 90, 90, 96, 90, 96, 90, 90, 90, 0, 0, 0, 0, 0, 0, 0, 90, 96,103, 97, 94, 97,103, 96, 90, 0, 0, 0, 0, 0, 0, 0, 92, 98, 99,103, 99,103, 99, 98, 92, 0, 0, 0, 0, 0, 0, 0, 93,108,100,107,100,107,100,108, 93, 0, 0, 0, 0, 0, 0, 0, 90,100, 99,103,104,103, 99,100, 90, 0, 0, 0, 0, 0, 0, 0, 90, 98,101,102,103,102,101, 98, 90, 0, 0, 0, 0, 0, 0, 0, 92, 94, 98, 95, 98, 95, 98, 94, 92, 0, 0, 0, 0, 0, 0, 0, 93, 92, 94, 95, 92, 95, 94, 92, 93, 0, 0, 0, 0, 0, 0, 0, 85, 90, 92, 93, 78, 93, 92, 90, 85, 0, 0, 0, 0, 0, 0, 0, 88, 85, 90, 88, 90, 88, 90, 85, 88, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 8. 残局的马 static const uint8_t cucvlKnightEndgame[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 92, 94, 96, 96, 96, 96, 96, 94, 92, 0, 0, 0, 0, 0, 0, 0, 94, 96, 98, 98, 98, 98, 98, 96, 94, 0, 0, 0, 0, 0, 0, 0, 96, 98,100,100,100,100,100, 98, 96, 0, 0, 0, 0, 0, 0, 0, 96, 98,100,100,100,100,100, 98, 96, 0, 0, 0, 0, 0, 0, 0, 96, 98,100,100,100,100,100, 98, 96, 0, 0, 0, 0, 0, 0, 0, 94, 96, 98, 98, 98, 98, 98, 96, 94, 0, 0, 0, 0, 0, 0, 0, 94, 96, 98, 98, 98, 98, 98, 96, 94, 0, 0, 0, 0, 0, 0, 0, 92, 94, 96, 96, 96, 96, 96, 94, 92, 0, 0, 0, 0, 0, 0, 0, 90, 92, 94, 92, 92, 92, 94, 92, 90, 0, 0, 0, 0, 0, 0, 0, 88, 90, 92, 90, 90, 90, 92, 90, 88, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 9. 开中局的车,参照“梦入神蛋” static const uint8_t cucvlRookMidgame[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,206,208,207,213,214,213,207,208,206, 0, 0, 0, 0, 0, 0, 0,206,212,209,216,233,216,209,212,206, 0, 0, 0, 0, 0, 0, 0,206,208,207,214,216,214,207,208,206, 0, 0, 0, 0, 0, 0, 0,206,213,213,216,216,216,213,213,206, 0, 0, 0, 0, 0, 0, 0,208,211,211,214,215,214,211,211,208, 0, 0, 0, 0, 0, 0, 0,208,212,212,214,215,214,212,212,208, 0, 0, 0, 0, 0, 0, 0,204,209,204,212,214,212,204,209,204, 0, 0, 0, 0, 0, 0, 0,198,208,204,212,212,212,204,208,198, 0, 0, 0, 0, 0, 0, 0,200,208,206,212,200,212,206,208,200, 0, 0, 0, 0, 0, 0, 0,194,206,204,212,200,212,204,206,194, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 10. 残局的车 static const uint8_t cucvlRookEndgame[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,182,182,182,184,186,184,182,182,182, 0, 0, 0, 0, 0, 0, 0,184,184,184,186,190,186,184,184,184, 0, 0, 0, 0, 0, 0, 0,182,182,182,184,186,184,182,182,182, 0, 0, 0, 0, 0, 0, 0,180,180,180,182,184,182,180,180,180, 0, 0, 0, 0, 0, 0, 0,180,180,180,182,184,182,180,180,180, 0, 0, 0, 0, 0, 0, 0,180,180,180,182,184,182,180,180,180, 0, 0, 0, 0, 0, 0, 0,180,180,180,182,184,182,180,180,180, 0, 0, 0, 0, 0, 0, 0,180,180,180,182,184,182,180,180,180, 0, 0, 0, 0, 0, 0, 0,180,180,180,182,184,182,180,180,180, 0, 0, 0, 0, 0, 0, 0,180,180,180,182,184,182,180,180,180, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 11. 开中局的炮,参照“梦入神蛋” static const uint8_t cucvlCannonMidgame[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,100,100, 96, 91, 90, 91, 96,100,100, 0, 0, 0, 0, 0, 0, 0, 98, 98, 96, 92, 89, 92, 96, 98, 98, 0, 0, 0, 0, 0, 0, 0, 97, 97, 96, 91, 92, 91, 96, 97, 97, 0, 0, 0, 0, 0, 0, 0, 96, 99, 99, 98,100, 98, 99, 99, 96, 0, 0, 0, 0, 0, 0, 0, 96, 96, 96, 96,100, 96, 96, 96, 96, 0, 0, 0, 0, 0, 0, 0, 95, 96, 99, 96,100, 96, 99, 96, 95, 0, 0, 0, 0, 0, 0, 0, 96, 96, 96, 96, 96, 96, 96, 96, 96, 0, 0, 0, 0, 0, 0, 0, 97, 96,100, 99,101, 99,100, 96, 97, 0, 0, 0, 0, 0, 0, 0, 96, 97, 98, 98, 98, 98, 98, 97, 96, 0, 0, 0, 0, 0, 0, 0, 96, 96, 97, 99, 99, 99, 97, 96, 96, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 12. 残局的炮 static const uint8_t cucvlCannonEndgame[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,100,100,100,100,100,100,100,100,100, 0, 0, 0, 0, 0, 0, 0,100,100,100,100,100,100,100,100,100, 0, 0, 0, 0, 0, 0, 0,100,100,100,100,100,100,100,100,100, 0, 0, 0, 0, 0, 0, 0,100,100,100,102,104,102,100,100,100, 0, 0, 0, 0, 0, 0, 0,100,100,100,102,104,102,100,100,100, 0, 0, 0, 0, 0, 0, 0,100,100,100,102,104,102,100,100,100, 0, 0, 0, 0, 0, 0, 0,100,100,100,102,104,102,100,100,100, 0, 0, 0, 0, 0, 0, 0,100,100,100,102,104,102,100,100,100, 0, 0, 0, 0, 0, 0, 0,100,100,100,104,106,104,100,100,100, 0, 0, 0, 0, 0, 0, 0,100,100,100,104,106,104,100,100,100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 空头炮的威胁分值,指标是对红方来说的行号(即黑方要用15去减),大体上空头炮位置越高威胁越大。进入残局时,该值要相应减少。 static const int cvlHollowThreat[16] = { 0, 0, 0, 0, 0, 0, 60, 65, 70, 75, 80, 80, 80, 0, 0, 0 }; // 炮镇窝心马的威胁分值,指标同上,大体上高度越低威胁越大,没有窝心马时可取四分之一。进入残局时,取值似乎不应变化。 static const int cvlCentralThreat[16] = { 0, 0, 0, 0, 0, 0, 50, 45, 40, 35, 30, 30, 30, 0, 0, 0 }; // 沉底炮的威胁分值,指标是列号,大体上越靠近边线威胁越大。威胁减少时,该值要相应减少。 static const int cvlBottomThreat[16] = { 0, 0, 0, 40, 30, 0, 0, 0, 0, 0, 30, 40, 0, 0, 0, 0 }; // 本模块只涉及到"PositionStruct"中的"ucsqPieces"、"dwBitPiece/wBitPiece"、"vlWhite"和"vlBlack"四个成员,故省略前面的"this->" /* 局面预评价就是初始化局面预评价数据(PreEval和PreEvalEx)的过程。 * ElephantEye的局面预评价主要分以下两个方面: * 1. 判断局势处于开中局还是残局阶段; * 2. 判断每一方是否对对方形成威胁。 */ const int ROOK_MIDGAME_VALUE = 6; const int KNIGHT_CANNON_MIDGAME_VALUE = 3; const int OTHER_MIDGAME_VALUE = 1; const int TOTAL_MIDGAME_VALUE = ROOK_MIDGAME_VALUE * 4 + KNIGHT_CANNON_MIDGAME_VALUE * 8 + OTHER_MIDGAME_VALUE * 18; const int TOTAL_ADVANCED_VALUE = 4; const int TOTAL_ATTACK_VALUE = 8; const int ADVISOR_BISHOP_ATTACKLESS_VALUE = 80; const int TOTAL_ADVISOR_LEAKAGE = 80; static bool bInit = false; PreEvalStructEx PreEvalEx; void PositionStruct::PreEvaluate(void) { int i, sq, nMidgameValue, nWhiteAttacks, nBlackAttacks, nWhiteSimpleValue, nBlackSimpleValue; uint8_t ucvlPawnPiecesAttacking[256], ucvlPawnPiecesAttackless[256]; if (!bInit) { bInit = true; // 初始化"PreEvalEx.cPopCnt16"数组,只需要初始化一次 for (i = 0; i < 65536; i ++) { PreEvalEx.cPopCnt16[i] = PopCnt16(i); } } // 首先判断局势处于开中局还是残局阶段,方法是计算各种棋子的数量,按照车=6、马炮=3、其它=1相加。 nMidgameValue = PopCnt32(this->dwBitPiece & BOTH_BITPIECE(ADVISOR_BITPIECE | BISHOP_BITPIECE | PAWN_BITPIECE)) * OTHER_MIDGAME_VALUE; nMidgameValue += PopCnt32(this->dwBitPiece & BOTH_BITPIECE(KNIGHT_BITPIECE | CANNON_BITPIECE)) * KNIGHT_CANNON_MIDGAME_VALUE; nMidgameValue += PopCnt32(this->dwBitPiece & BOTH_BITPIECE(ROOK_BITPIECE)) * ROOK_MIDGAME_VALUE; // 使用二次函数,子力很少时才认为接近残局 nMidgameValue = (2 * TOTAL_MIDGAME_VALUE - nMidgameValue) * nMidgameValue / TOTAL_MIDGAME_VALUE; __ASSERT_BOUND(0, nMidgameValue, TOTAL_MIDGAME_VALUE); PreEval.vlAdvanced = (TOTAL_ADVANCED_VALUE * nMidgameValue + TOTAL_ADVANCED_VALUE / 2) / TOTAL_MIDGAME_VALUE; __ASSERT_BOUND(0, PreEval.vlAdvanced, TOTAL_ADVANCED_VALUE); for (sq = 0; sq < 256; sq ++) { if (IN_BOARD(sq)) { PreEval.ucvlWhitePieces[0][sq] = PreEval.ucvlBlackPieces[0][SQUARE_FLIP(sq)] = (uint8_t) ((cucvlKingPawnMidgameAttacking[sq] * nMidgameValue + cucvlKingPawnEndgameAttacking[sq] * (TOTAL_MIDGAME_VALUE - nMidgameValue)) / TOTAL_MIDGAME_VALUE); PreEval.ucvlWhitePieces[3][sq] = PreEval.ucvlBlackPieces[3][SQUARE_FLIP(sq)] = (uint8_t) ((cucvlKnightMidgame[sq] * nMidgameValue + cucvlKnightEndgame[sq] * (TOTAL_MIDGAME_VALUE - nMidgameValue)) / TOTAL_MIDGAME_VALUE); PreEval.ucvlWhitePieces[4][sq] = PreEval.ucvlBlackPieces[4][SQUARE_FLIP(sq)] = (uint8_t) ((cucvlRookMidgame[sq] * nMidgameValue + cucvlRookEndgame[sq] * (TOTAL_MIDGAME_VALUE - nMidgameValue)) / TOTAL_MIDGAME_VALUE); PreEval.ucvlWhitePieces[5][sq] = PreEval.ucvlBlackPieces[5][SQUARE_FLIP(sq)] = (uint8_t) ((cucvlCannonMidgame[sq] * nMidgameValue + cucvlCannonEndgame[sq] * (TOTAL_MIDGAME_VALUE - nMidgameValue)) / TOTAL_MIDGAME_VALUE); ucvlPawnPiecesAttacking[sq] = PreEval.ucvlWhitePieces[0][sq]; ucvlPawnPiecesAttackless[sq] = (uint8_t) ((cucvlKingPawnMidgameAttackless[sq] * nMidgameValue + cucvlKingPawnEndgameAttackless[sq] * (TOTAL_MIDGAME_VALUE - nMidgameValue)) / TOTAL_MIDGAME_VALUE); } } for (i = 0; i < 16; i ++) { PreEvalEx.vlHollowThreat[i] = cvlHollowThreat[i] * (nMidgameValue + TOTAL_MIDGAME_VALUE) / (TOTAL_MIDGAME_VALUE * 2); __ASSERT_BOUND(0, PreEvalEx.vlHollowThreat[i], cvlHollowThreat[i]); PreEvalEx.vlCentralThreat[i] = cvlCentralThreat[i]; } // 然后判断各方是否处于进攻状态,方法是计算各种过河棋子的数量,按照车马2炮兵1相加。 nWhiteAttacks = nBlackAttacks = 0; for (i = SIDE_TAG(0) + KNIGHT_FROM; i <= SIDE_TAG(0) + ROOK_TO; i ++) { if (this->ucsqPieces[i] != 0 && BLACK_HALF(this->ucsqPieces[i])) { nWhiteAttacks += 2; } } for (i = SIDE_TAG(0) + CANNON_FROM; i <= SIDE_TAG(0) + PAWN_TO; i ++) { if (this->ucsqPieces[i] != 0 && BLACK_HALF(this->ucsqPieces[i])) { nWhiteAttacks ++; } } for (i = SIDE_TAG(1) + KNIGHT_FROM; i <= SIDE_TAG(1) + ROOK_TO; i ++) { if (this->ucsqPieces[i] != 0 && WHITE_HALF(this->ucsqPieces[i])) { nBlackAttacks += 2; } } for (i = SIDE_TAG(1) + CANNON_FROM; i <= SIDE_TAG(1) + PAWN_TO; i ++) { if (this->ucsqPieces[i] != 0 && WHITE_HALF(this->ucsqPieces[i])) { nBlackAttacks ++; } } // 如果本方轻子数比对方多,那么每多一个轻子(车算2个轻子)威胁值加2。威胁值最多不超过8。 nWhiteSimpleValue = PopCnt16(this->wBitPiece[0] & ROOK_BITPIECE) * 2 + PopCnt16(this->wBitPiece[0] & (KNIGHT_BITPIECE | CANNON_BITPIECE)); nBlackSimpleValue = PopCnt16(this->wBitPiece[1] & ROOK_BITPIECE) * 2 + PopCnt16(this->wBitPiece[1] & (KNIGHT_BITPIECE | CANNON_BITPIECE)); if (nWhiteSimpleValue > nBlackSimpleValue) { nWhiteAttacks += (nWhiteSimpleValue - nBlackSimpleValue) * 2; } else { nBlackAttacks += (nBlackSimpleValue - nWhiteSimpleValue) * 2; } nWhiteAttacks = MIN(nWhiteAttacks, TOTAL_ATTACK_VALUE); nBlackAttacks = MIN(nBlackAttacks, TOTAL_ATTACK_VALUE); PreEvalEx.vlBlackAdvisorLeakage = TOTAL_ADVISOR_LEAKAGE * nWhiteAttacks / TOTAL_ATTACK_VALUE; PreEvalEx.vlWhiteAdvisorLeakage = TOTAL_ADVISOR_LEAKAGE * nBlackAttacks / TOTAL_ATTACK_VALUE; __ASSERT_BOUND(0, nWhiteAttacks, TOTAL_ATTACK_VALUE); __ASSERT_BOUND(0, nBlackAttacks, TOTAL_ATTACK_VALUE); __ASSERT_BOUND(0, PreEvalEx.vlBlackAdvisorLeakage, TOTAL_ADVISOR_LEAKAGE); __ASSERT_BOUND(0, PreEvalEx.vlBlackAdvisorLeakage, TOTAL_ADVISOR_LEAKAGE); for (sq = 0; sq < 256; sq ++) { if (IN_BOARD(sq)) { PreEval.ucvlWhitePieces[1][sq] = PreEval.ucvlWhitePieces[2][sq] = (uint8_t) ((cucvlAdvisorBishopThreatened[sq] * nBlackAttacks + (PreEval.bPromotion ? cucvlAdvisorBishopPromotionThreatless[sq] : cucvlAdvisorBishopThreatless[sq]) * (TOTAL_ATTACK_VALUE - nBlackAttacks)) / TOTAL_ATTACK_VALUE); PreEval.ucvlBlackPieces[1][sq] = PreEval.ucvlBlackPieces[2][sq] = (uint8_t) ((cucvlAdvisorBishopThreatened[SQUARE_FLIP(sq)] * nWhiteAttacks + (PreEval.bPromotion ? cucvlAdvisorBishopPromotionThreatless[SQUARE_FLIP(sq)] : cucvlAdvisorBishopThreatless[SQUARE_FLIP(sq)]) * (TOTAL_ATTACK_VALUE - nWhiteAttacks)) / TOTAL_ATTACK_VALUE); PreEval.ucvlWhitePieces[6][sq] = (uint8_t) ((ucvlPawnPiecesAttacking[sq] * nWhiteAttacks + ucvlPawnPiecesAttackless[sq] * (TOTAL_ATTACK_VALUE - nWhiteAttacks)) / TOTAL_ATTACK_VALUE); PreEval.ucvlBlackPieces[6][sq] = (uint8_t) ((ucvlPawnPiecesAttacking[SQUARE_FLIP(sq)] * nBlackAttacks + ucvlPawnPiecesAttackless[SQUARE_FLIP(sq)] * (TOTAL_ATTACK_VALUE - nBlackAttacks)) / TOTAL_ATTACK_VALUE); } } for (i = 0; i < 16; i ++) { PreEvalEx.vlWhiteBottomThreat[i] = cvlBottomThreat[i] * nBlackAttacks / TOTAL_ATTACK_VALUE; PreEvalEx.vlBlackBottomThreat[i] = cvlBottomThreat[i] * nWhiteAttacks / TOTAL_ATTACK_VALUE; } // 检查预评价是否对称 #ifndef NDEBUG for (sq = 0; sq < 256; sq ++) { if (IN_BOARD(sq)) { for (i = 0; i < 7; i ++) { __ASSERT(PreEval.ucvlWhitePieces[i][sq] == PreEval.ucvlWhitePieces[i][SQUARE_MIRROR(sq)]); __ASSERT(PreEval.ucvlBlackPieces[i][sq] == PreEval.ucvlBlackPieces[i][SQUARE_MIRROR(sq)]); } } } for (i = FILE_LEFT; i <= FILE_RIGHT; i ++) { __ASSERT(PreEvalEx.vlWhiteBottomThreat[i] == PreEvalEx.vlWhiteBottomThreat[FILE_FLIP(i)]); __ASSERT(PreEvalEx.vlBlackBottomThreat[i] == PreEvalEx.vlBlackBottomThreat[FILE_FLIP(i)]); } #endif // 调整不受威胁方少掉的仕(士)相(象)分值 this->vlWhite = ADVISOR_BISHOP_ATTACKLESS_VALUE * (TOTAL_ATTACK_VALUE - nBlackAttacks) / TOTAL_ATTACK_VALUE; this->vlBlack = ADVISOR_BISHOP_ATTACKLESS_VALUE * (TOTAL_ATTACK_VALUE - nWhiteAttacks) / TOTAL_ATTACK_VALUE; // 如果允许升变,那么不受威胁的仕(士)相(象)分值就少了一半 if (PreEval.bPromotion) { this->vlWhite /= 2; this->vlBlack /= 2; } // 最后重新计算子力位置分 for (i = 16; i < 32; i ++) { sq = this->ucsqPieces[i]; if (sq != 0) { __ASSERT_SQUARE(sq); this->vlWhite += PreEval.ucvlWhitePieces[PIECE_TYPE(i)][sq]; } } for (i = 32; i < 48; i ++) { sq = this->ucsqPieces[i]; if (sq != 0) { __ASSERT_SQUARE(sq); this->vlBlack += PreEval.ucvlBlackPieces[PIECE_TYPE(i)][sq]; } } }
52.347826
199
0.493751
milkpku
093a9732f4dc30e95c2741783225bbf7fee37491
2,881
hpp
C++
libtbag/tiled/details/TmxPolyline.hpp
osom8979/tbag
c31e2d884907d946df0836a70d8d5d69c4bf3c27
[ "MIT" ]
21
2016-04-05T06:08:41.000Z
2022-03-28T10:20:22.000Z
libtbag/tiled/details/TmxPolyline.hpp
osom8979/tbag
c31e2d884907d946df0836a70d8d5d69c4bf3c27
[ "MIT" ]
null
null
null
libtbag/tiled/details/TmxPolyline.hpp
osom8979/tbag
c31e2d884907d946df0836a70d8d5d69c4bf3c27
[ "MIT" ]
2
2019-07-16T00:37:21.000Z
2021-11-10T06:14:09.000Z
/** * @file TmxPolyline.hpp * @brief TmxPolyline class prototype. * @author zer0 * @date 2019-06-23 */ #ifndef __INCLUDE_LIBTBAG__LIBTBAG_TILED_DETAILS_TMXPOLYLINE_HPP__ #define __INCLUDE_LIBTBAG__LIBTBAG_TILED_DETAILS_TMXPOLYLINE_HPP__ // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif #include <libtbag/config.h> #include <libtbag/predef.hpp> #include <libtbag/tiled/details/TmxPointsCommon.hpp> // ------------------- NAMESPACE_LIBTBAG_OPEN // ------------------- namespace tiled { namespace details { /** * TmxPolyline class prototype. * * @author zer0 * @date 2019-06-23 * * @remarks * A polyline follows the same placement definition as a polygon object. */ struct TBAG_API TmxPolyline : protected libtbag::tiled::details::TmxPointsCommon { TBAG_CONSTEXPR static char const * const TAG_NAME = "polyline"; Points points; TmxPolyline(); TmxPolyline(Points const & p); ~TmxPolyline(); using iterator = typename Points::iterator; using const_iterator = typename Points::const_iterator; using reverse_iterator = typename Points::reverse_iterator; using const_reverse_iterator = typename Points::const_reverse_iterator; iterator begin() TBAG_NOEXCEPT_SP_OP(points.begin()) { return points.begin(); } iterator end() TBAG_NOEXCEPT_SP_OP(points.end()) { return points.end(); } const_iterator begin() const TBAG_NOEXCEPT_SP_OP(points.begin()) { return points.begin(); } const_iterator end() const TBAG_NOEXCEPT_SP_OP(points.end()) { return points.end(); } const_iterator cbegin() const TBAG_NOEXCEPT_SP_OP(points.cbegin()) { return points.cbegin(); } const_iterator cend() const TBAG_NOEXCEPT_SP_OP(points.cend()) { return points.cend(); } reverse_iterator rbegin() TBAG_NOEXCEPT_SP_OP(points.rbegin()) { return points.rbegin(); } reverse_iterator rend() TBAG_NOEXCEPT_SP_OP(points.rend()) { return points.rend(); } const_reverse_iterator rbegin() const TBAG_NOEXCEPT_SP_OP(points.rbegin()) { return points.rbegin(); } const_reverse_iterator rend() const TBAG_NOEXCEPT_SP_OP(points.rend()) { return points.rend(); } const_reverse_iterator crbegin() const TBAG_NOEXCEPT_SP_OP(points.crbegin()) { return points.crbegin(); } const_reverse_iterator crend() const TBAG_NOEXCEPT_SP_OP(points.crend()) { return points.crend(); } bool empty() const; std::size_t size() const; void clear(); Err read(Element const & elem); Err read(std::string const & xml); Err write(Element & elem) const; Err write(std::string & xml) const; }; } // namespace details } // namespace tiled // -------------------- NAMESPACE_LIBTBAG_CLOSE // -------------------- #endif // __INCLUDE_LIBTBAG__LIBTBAG_TILED_DETAILS_TMXPOLYLINE_HPP__
28.524752
80
0.696286
osom8979
093b3fca4883fb98169ba8001ff1444991746728
3,097
cpp
C++
lib/libcpp/Mesh/boundarymeshinfo.cpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
null
null
null
lib/libcpp/Mesh/boundarymeshinfo.cpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
1
2019-01-31T10:59:11.000Z
2019-01-31T10:59:11.000Z
lib/libcpp/Mesh/boundarymeshinfo.cpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
null
null
null
#include "Mesh/boundarymeshinfo.hpp" #include <cassert> #include <mpi.h> using namespace mesh; /*--------------------------------------------------------------------------*/ BoundaryMeshInfo::~BoundaryMeshInfo() {} BoundaryMeshInfo::BoundaryMeshInfo(): GeometryObject(){} BoundaryMeshInfo::BoundaryMeshInfo( const BoundaryMeshInfo& boundarymeshinfo): GeometryObject(boundarymeshinfo) { _nodes_to_parent = boundarymeshinfo._nodes_to_parent; _cells_to_parent = boundarymeshinfo._cells_to_parent; } BoundaryMeshInfo& BoundaryMeshInfo::operator=( const BoundaryMeshInfo& boundarymeshinfo) { assert(0); GeometryObject::operator=(boundarymeshinfo); return *this; } std::string BoundaryMeshInfo::getClassName() const { return "BoundaryMeshInfo"; } std::unique_ptr<GeometryObject> BoundaryMeshInfo::clone() const { return std::unique_ptr<mesh::GeometryObject>(new BoundaryMeshInfo(*this)); } /*--------------------------------------------------------------------------*/ const alat::armaivec& BoundaryMeshInfo::getNodesToParent() const {return _nodes_to_parent;} alat::armaivec& BoundaryMeshInfo::getNodesToParent() {return _nodes_to_parent;} const alat::armaimat& BoundaryMeshInfo::getCellsToParent() const {return _cells_to_parent;} alat::armaimat& BoundaryMeshInfo::getCellsToParent() {return _cells_to_parent;} /*--------------------------------------------------------------------------*/ alat::armaivec BoundaryMeshInfo::getSizes() const { alat::armaivec sizes(3); sizes[0] = _nodes_to_parent.size(); sizes[1] = _cells_to_parent.n_rows; sizes[2] = _cells_to_parent.n_cols; return sizes; } void BoundaryMeshInfo::setSizes(alat::armaivec::const_iterator sizes) { _nodes_to_parent.set_size(sizes[0]); _cells_to_parent.set_size(sizes[1], sizes[2]); } void BoundaryMeshInfo::send(int neighbor, int tag) const { MPI_Request request; MPI_Isend(_nodes_to_parent.begin(), _nodes_to_parent.size(), MPI_INT, neighbor, tag, MPI_COMM_WORLD, &request); MPI_Isend(_cells_to_parent.begin(), _cells_to_parent.size(), MPI_INT, neighbor, tag, MPI_COMM_WORLD, &request); } void BoundaryMeshInfo::recv(int neighbor, int tag) { MPI_Status status; MPI_Request request; MPI_Irecv(_nodes_to_parent.begin(), _nodes_to_parent.size(), MPI_INT, neighbor, tag, MPI_COMM_WORLD, &request); MPI_Wait(&request, &status); MPI_Irecv(_cells_to_parent.begin(), _cells_to_parent.size(), MPI_INT, neighbor, tag, MPI_COMM_WORLD, &request); MPI_Wait(&request, &status); } /*--------------------------------------------------------------------------*/ void BoundaryMeshInfo::loadH5(const arma::hdf5_name& spec) { _nodes_to_parent.load(arma::hdf5_name(spec.filename, spec.dsname+"/nodes_to_parent", spec.opts)); _cells_to_parent.load(arma::hdf5_name(spec.filename, spec.dsname+"/cells_to_parent", spec.opts)); } void BoundaryMeshInfo::saveH5(const arma::hdf5_name& spec) const { _nodes_to_parent.save(arma::hdf5_name(spec.filename, spec.dsname+"/nodes_to_parent", spec.opts)); _cells_to_parent.save(arma::hdf5_name(spec.filename, spec.dsname+"/cells_to_parent", spec.opts)); }
40.220779
113
0.699387
beckerrh
093c76d4ad9c7d42ffe7c20552c4a98f31df2d8b
7,085
cpp
C++
Honeycomb GE/src/math/Vector3f.cpp
antverdovsky/Honeycomb-Game-Engine
0ccfcf9bc57d63e948325ac89ad0de0497206f94
[ "MIT" ]
42
2016-12-13T21:59:59.000Z
2022-03-03T07:17:18.000Z
Honeycomb GE/src/math/Vector3f.cpp
antverdovsky/Honeycomb-Game-Engine
0ccfcf9bc57d63e948325ac89ad0de0497206f94
[ "MIT" ]
6
2016-12-13T21:58:39.000Z
2021-05-08T08:38:35.000Z
Honeycomb GE/src/math/Vector3f.cpp
antverdovsky/Honeycomb-Game-Engine
0ccfcf9bc57d63e948325ac89ad0de0497206f94
[ "MIT" ]
2
2020-07-24T18:13:30.000Z
2021-03-13T15:47:42.000Z
#include "../../include/math/Vector3f.h" #include <math.h> #include "../../include/math/Quaternion.h" namespace Honeycomb { namespace Math { const Vector3f& Vector3f::getGlobalForward() { static Vector3f forward{ 0.0F, 0.0F, -1.0F }; return forward; } const Vector3f& Vector3f::getGlobalRight() { static Vector3f right{ 1.0F, 0.0F, 0.0F }; return right; } const Vector3f& Vector3f::getGlobalUp() { static Vector3f up{ 0.0F, 1.0F, 0.0F }; return up; } Vector3f::Vector3f() : Vector3f(0.0F, 0.0F, 0.0F) { } Vector3f::Vector3f(const float &all) : Vector3f(all, all, all) { } Vector3f::Vector3f(const float &x, const float &y, const float &z) { this->x = x; this->y = y; this->z = z; } Vector3f Vector3f::add(const Vector3f& v2) const { return Vector3f(this->x + v2.x, this->y + v2.y, this->z + v2.z); } Vector3f& Vector3f::addTo(const Vector3f& v2) { Vector3f resultant = this->add(v2); this->set(resultant.x, resultant.y, resultant.z); return *this; } float Vector3f::angle(const Vector3f& v2) const { // Calculate cos(theta) = (v1 . v2) / (|v1||v2|) float dot = this->dot(v2); float magMult = this->magnitude() * v2.magnitude(); float cosTheta = dot / magMult; return (float)acos(cosTheta); } Vector3f Vector3f::cross(const Vector3f& v2) const { // Calculate the cross product using the determinant of the cross // product matrix of this and the second vector. return Vector3f( this->y * v2.z - v2.y * this->z, this->z * v2.x - v2.z * this->x, this->x * v2.y - v2.x * this->y); } Vector3f& Vector3f::crossTo(const Vector3f& v2) { Vector3f crossed = this->cross(v2); this->set(crossed.x, crossed.y, crossed.z); return *this; } Vector3f Vector3f::divide(const float &scale) const { return Vector3f(this->x / scale, this->y / scale, this->z / scale); } Vector3f Vector3f::divide(const Vector3f &v2) const { return Vector3f(this->x / v2.x, this->y / v2.y, this->z / v2.z); } Vector3f& Vector3f::divideTo(const float &scale) { Vector3f divided = this->divide(scale); this->set(divided.x, divided.y, divided.z); return *this; } Vector3f& Vector3f::divideTo(const Vector3f &v2) { Vector3f divided = this->divide(v2); this->set(divided.x, divided.y, divided.z); return *this; } float Vector3f::dot(const Vector3f& v2) const { return this->x * v2.x + this->y * v2.y + this->z * v2.z; } void Vector3f::get(float &x, float &y, float &z) const { x = this->x; y = this->y; z = this->z; } float& Vector3f::getX() { return this->x; } const float& Vector3f::getX() const { return this->x; } float& Vector3f::getY() { return this->y; } const float& Vector3f::getY() const { return this->y; } float& Vector3f::getZ() { return this->z; } const float& Vector3f::getZ() const { return this->z; } float Vector3f::magnitude() const { return (float)sqrt(this->magnitude2()); } float Vector3f::magnitude2() const { return x * x + y * y + z * z; } Vector3f Vector3f::multiply(const Matrix4f &mat) const { return mat.multiply(*this); } Vector3f Vector3f::multiply(const Vector3f &vec) const { return Vector3f(this->x * vec.x, this->y * vec.y, this->z * vec.z); } Vector3f& Vector3f::multiplyTo(const Matrix4f &mat) { Vector3f prod = this->multiply(mat); this->set(prod.x, prod.y, prod.z); return *this; } Vector3f& Vector3f::multiplyTo(const Vector3f &vec) { Vector3f prod = this->multiply(vec); this->set(prod.x, prod.y, prod.z); return *this; } Vector3f& Vector3f::normalize() { Vector3f normalized = this->normalized(); this->set(normalized.x, normalized.y, normalized.z); return *this; } Vector3f Vector3f::normalized() const { float mag = this->magnitude(); return Vector3f(this->x / mag, this->y / mag, this->z / mag); } Vector3f Vector3f::rotate(const Vector3f &axis, const float &rad) const { // Construct a Rotation Quaternion which will rotate the vector. Quaternion rotQuat = Quaternion(axis, rad); Quaternion rotQuatConj = rotQuat.conjugated(); // Multiply the Quaternion by this Vector instance to get the resulting // rotated Quaternion, and multiply by conjugate to cancel out the // imaginary components. Quaternion result = rotQuat * (*this) * rotQuatConj; // All components of the rotated vector lie within the Quaternion. return Vector3f(result.getX(), result.getY(), result.getZ()); } Vector3f Vector3f::rotate(const Quaternion &quat) const { Quaternion rotated = quat * (*this) * quat.conjugated(); return Vector3f(rotated.getX(), rotated.getY(), rotated.getZ()); } Vector3f& Vector3f::rotateTo(const Vector3f &axis, const float &rad) { Vector3f rotated = this->rotate(axis, rad); this->set(rotated.x, rotated.y, rotated.z); return *this; } Vector3f& Vector3f::rotateTo(const Quaternion &quat) { Vector3f rotated = this->rotate(quat); this->set(rotated.x, rotated.y, rotated.z); return *this; } Vector3f Vector3f::scale(const float &scale) const { return Vector3f(this->x * scale, this->y * scale, this->z * scale); } Vector3f& Vector3f::scaleTo(const float &scale) { Vector3f scaled = this->scale(scale); this->set(scaled.x, scaled.y, scaled.z); return *this; } void Vector3f::set(const float &x, const float &y, const float &z) { this->x = x; this->y = y; this->z = z; } void Vector3f::setX(const float &x) { this->x = x; } void Vector3f::setY(const float &y) { this->y = y; } void Vector3f::setZ(const float &z) { this->z = z; } Vector3f Vector3f::operator*(const float &scale) const { return this->scale(scale); } Vector3f Vector3f::operator*(const Matrix4f &mat) const { return this->multiply(mat); } Vector3f Vector3f::operator*(const Vector3f &v2) const { return this->multiply(v2); } Vector3f& Vector3f::operator*=(const float &scale) { return this->scaleTo(scale); } Vector3f& Vector3f::operator*=(const Matrix4f &mat) { return this->multiplyTo(mat); } Vector3f& Vector3f::operator*=(const Vector3f &v2) { return this->multiplyTo(v2); } Vector3f Vector3f::operator/(const float &scale) const { return this->scale(1.0F / scale); } Vector3f& Vector3f::operator/=(const float &scale) { return this->scaleTo(1.0F / scale); } Vector3f Vector3f::operator+(const Vector3f &v2) const { return this->add(v2); } Vector3f& Vector3f::operator+=(const Vector3f &v2) { return this->addTo(v2); } Vector3f Vector3f::operator-() const { return this->scale(-1.0F); } Vector3f Vector3f::operator-(const Vector3f &v2) const { return this->add(-v2); } Vector3f& Vector3f::operator-=(const Vector3f &v2) { return this->addTo(-v2); } bool Vector3f::operator<(const Vector3f &v2) const { return this->magnitude2() < v2.magnitude2(); } bool Vector3f::operator>(const Vector3f &v2) const { return this->magnitude2() > v2.magnitude2(); } std::ostream& operator<<(std::ostream &stream, const Vector3f &vec) { return stream << "(" << vec.getX() << ", " << vec.getY() << ", " << vec.getZ() << ")"; } } }
23.616667
74
0.655752
antverdovsky
093f08509d481524d8ae4aa5c308632a3ebf7aef
356
cpp
C++
solutions/525.contiguous-array.324108882.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
78
2020-10-22T11:31:53.000Z
2022-02-22T13:27:49.000Z
solutions/525.contiguous-array.324108882.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
null
null
null
solutions/525.contiguous-array.324108882.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
26
2020-10-23T15:10:44.000Z
2021-11-07T16:13:50.000Z
class Solution { public: int findMaxLength(vector<int> &nums) { int n = nums.size(); unordered_map<int, int> dp; int c = 0; int ans = 0; dp[0] = -1; for (int i = 0; i < n; i++) { c += nums[i] ? 1 : -1; if (dp.count(c)) ans = max(ans, i - dp[c]); else dp[c] = i; } return ans; } };
14.833333
40
0.438202
satu0king
0948608a7b29eaae18fdb49ef752352d112ed26c
12,232
cpp
C++
framework/private/test/bundle_archive_test.cpp
rwalraven343/celix
353ac0d2e0f819f8f59d4cdf8ea1dfd701201d74
[ "Apache-2.0" ]
1
2019-03-17T06:06:19.000Z
2019-03-17T06:06:19.000Z
framework/private/test/bundle_archive_test.cpp
rwalraven343/celix
353ac0d2e0f819f8f59d4cdf8ea1dfd701201d74
[ "Apache-2.0" ]
13
2019-02-21T21:27:44.000Z
2019-02-28T22:47:13.000Z
framework/private/test/bundle_archive_test.cpp
rwalraven343/celix
353ac0d2e0f819f8f59d4cdf8ea1dfd701201d74
[ "Apache-2.0" ]
null
null
null
/** *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. */ /* * bundle_archive_test.cpp * * \date Feb 11, 2013 * \author <a href="mailto:dev@celix.apache.org">Apache Celix Project Team</a> * \copyright Apache License, Version 2.0 */ #include <stdlib.h> #include <stdio.h> #include <sys/stat.h> #include <dirent.h> #include <unistd.h> #include <string.h> #include "CppUTest/TestHarness.h" #include "CppUTest/TestHarness_c.h" #include "CppUTest/CommandLineTestRunner.h" #include "CppUTestExt/MockSupport.h" extern "C" { #include "bundle_archive.h" framework_logger_pt logger = (framework_logger_pt) 0x42; } int main(int argc, char** argv) { return RUN_ALL_TESTS(argc, argv); } //----------------------TESTGROUP DEFINES---------------------- TEST_GROUP(bundle_archive) { bundle_archive_pt bundle_archive; char * bundle_path; //uses the default build shell bundle char * alternate_bundle_path;//alternative bundle, if shell bundle not found char cache_path[512]; //a local cache folder void setup(void) { char cwd[512]; bundle_archive = NULL; bundle_path = (char*) "../shell/shell.zip"; //uses the default build shell bundle alternate_bundle_path = (char*) "../log_service/log_service.zip"; //alternative bundle, if shell bundle not found snprintf(cache_path, sizeof(cache_path), "%s/.cache", getcwd(cwd, sizeof(cwd))); //a local cache folder struct stat file_stat; if (stat(bundle_path, &file_stat) < 0) { if (stat(alternate_bundle_path, &file_stat) < 0) { FAIL("failed to find needed test bundle"); } else { bundle_path = alternate_bundle_path; } } } void teardown() { mock().checkExpectations(); mock().clear(); } }; //----------------------TEST DEFINES---------------------- //WARNING: if one test fails, it does not clean up properly, //causing most if not all of the subsequent tests to also fail TEST(bundle_archive, create) { mock().expectOneCall("framework_logCode").withParameter("code", CELIX_ILLEGAL_ARGUMENT); bundle_archive = (bundle_archive_pt) 0x42; LONGS_EQUAL(CELIX_ILLEGAL_ARGUMENT, bundleArchive_create(cache_path, 5, bundle_path, NULL, &bundle_archive)); bundle_archive = NULL; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_create(cache_path, 5, bundle_path, NULL, &bundle_archive)); CHECK(bundle_archive != NULL); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); } TEST(bundle_archive, createSystemBundleArchive) { mock().expectOneCall("framework_logCode").withParameter("code", CELIX_ILLEGAL_ARGUMENT); bundle_archive = (bundle_archive_pt) 0x42; LONGS_EQUAL(CELIX_ILLEGAL_ARGUMENT, bundleArchive_createSystemBundleArchive(&bundle_archive )); bundle_archive = NULL; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_createSystemBundleArchive(&bundle_archive)); CHECK(bundle_archive != NULL); //LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); } TEST(bundle_archive, recreate) { char * get_root; char * get_location; bundle_archive_pt recr_archive = NULL; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_create(cache_path, 5, bundle_path, NULL, &bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_recreate(cache_path, &recr_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getArchiveRoot(recr_archive, &get_root)); STRCMP_EQUAL(cache_path, get_root); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getLocation(recr_archive, &get_location)); STRCMP_EQUAL(bundle_path, get_location); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(recr_archive)); } TEST(bundle_archive, getId) { long get_id; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_create(cache_path, -42, bundle_path, NULL, &bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getId(bundle_archive, &get_id)); LONGS_EQUAL(-42, get_id); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); bundle_archive = NULL; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_create(cache_path, 666, bundle_path, NULL, &bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getId(bundle_archive, &get_id)); LONGS_EQUAL(666, get_id); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); } TEST(bundle_archive, getLocation) { char * get_loc; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_create(cache_path, 1, bundle_path, NULL, &bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getLocation(bundle_archive, &get_loc)); STRCMP_EQUAL(bundle_path, get_loc); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); } TEST(bundle_archive, getArchiveRoot) { char * get_root; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_create(cache_path, 1, bundle_path, NULL, &bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getArchiveRoot(bundle_archive, &get_root)); STRCMP_EQUAL(cache_path, get_root); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); } TEST(bundle_archive, getCurrentRevisionNumber) { long get_rev_num; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_create(cache_path, 1, bundle_path, NULL, &bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getCurrentRevisionNumber(bundle_archive, &get_rev_num)); LONGS_EQUAL(0, get_rev_num); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_revise(bundle_archive, bundle_path, NULL)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getCurrentRevisionNumber(bundle_archive, &get_rev_num)); LONGS_EQUAL(1, get_rev_num); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_revise(bundle_archive, bundle_path, NULL)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getCurrentRevisionNumber(bundle_archive, &get_rev_num)); LONGS_EQUAL(2, get_rev_num); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); } TEST(bundle_archive, getCurrentRevision) { long get_rev_num; bundle_revision_pt get_rev; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_create(cache_path, 1, bundle_path, NULL, &bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getCurrentRevision(bundle_archive, &get_rev)); bundleRevision_getNumber(get_rev, &get_rev_num); LONGS_EQUAL(0, get_rev_num); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_revise(bundle_archive, bundle_path, NULL)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getCurrentRevision(bundle_archive, &get_rev)); bundleRevision_getNumber(get_rev, &get_rev_num); LONGS_EQUAL(1, get_rev_num); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); } TEST(bundle_archive, getRevision) { long get_rev_num; bundle_revision_pt get_rev; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_create(cache_path, 1, bundle_path, NULL, &bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_revise(bundle_archive, bundle_path, NULL)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_revise(bundle_archive, bundle_path, NULL)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getRevision(bundle_archive, 0, &get_rev)); bundleRevision_getNumber(get_rev, &get_rev_num); LONGS_EQUAL(0, get_rev_num); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getRevision(bundle_archive, 2, &get_rev)); bundleRevision_getNumber(get_rev, &get_rev_num); LONGS_EQUAL(2, get_rev_num); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getRevision(bundle_archive, 1, &get_rev)); bundleRevision_getNumber(get_rev, &get_rev_num); LONGS_EQUAL(1, get_rev_num); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); } TEST(bundle_archive, set_getPersistentState) { bundle_state_e get; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_create(cache_path, 1, bundle_path, NULL, &bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_setPersistentState(bundle_archive, OSGI_FRAMEWORK_BUNDLE_UNKNOWN)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getPersistentState(bundle_archive, &get)); LONGS_EQUAL(OSGI_FRAMEWORK_BUNDLE_INSTALLED, get); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_setPersistentState(bundle_archive, OSGI_FRAMEWORK_BUNDLE_ACTIVE)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getPersistentState(bundle_archive, &get)); LONGS_EQUAL(OSGI_FRAMEWORK_BUNDLE_ACTIVE, get); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_setPersistentState(bundle_archive, OSGI_FRAMEWORK_BUNDLE_STARTING)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getPersistentState(bundle_archive, &get)); LONGS_EQUAL(OSGI_FRAMEWORK_BUNDLE_STARTING, get); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_setPersistentState(bundle_archive, OSGI_FRAMEWORK_BUNDLE_UNINSTALLED)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getPersistentState(bundle_archive, &get)); LONGS_EQUAL(OSGI_FRAMEWORK_BUNDLE_UNINSTALLED, get); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); } TEST(bundle_archive, set_getRefreshCount) { long get_refresh_num; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_create(cache_path, 1, bundle_path, NULL, &bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getRefreshCount(bundle_archive, &get_refresh_num)); LONGS_EQUAL(0, get_refresh_num); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_setRefreshCount(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getRefreshCount(bundle_archive, &get_refresh_num)); LONGS_EQUAL(0, get_refresh_num); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); } TEST(bundle_archive, get_setLastModified) { time_t set_time; time_t get_time; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_create(cache_path, 1, bundle_path, NULL, &bundle_archive)); time(&set_time); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_setLastModified(bundle_archive, set_time)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getLastModified(bundle_archive, &get_time)); CHECK(set_time == get_time); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); } //CANT seem to find a way to test this static function /*TEST(bundle_archive, readLastModified) { mock().expectOneCall("framework_logCode"); time_t set_time; time_t get_time; bundle_archive_pt recr_archive = NULL; LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_create(cache_path, 1, bundle_path, NULL, &bundle_archive)); time(&set_time); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_setLastModified(bundle_archive, set_time)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_recreate(cache_path, &recr_archive)); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_getLastModified(recr_archive, &get_time)); LONGS_EQUAL(set_time, get_time); LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_closeAndDelete(bundle_archive)); //LONGS_EQUAL(CELIX_SUCCESS, bundleArchive_destroy(bundle_archive)); }*/ TEST(bundle_archive, rollbackRevise) { bool get; bundleArchive_rollbackRevise(NULL, &get); LONGS_EQUAL(true, get); }
39.079872
115
0.805347
rwalraven343
094b05ca1bfdaef50c964e7dda8ac06f8ed3a7db
396
cpp
C++
test/what_print.cpp
xdanielsb/OperatingSystems
23bf014fae9644d4512b2337739e52adcd1087d6
[ "MIT" ]
null
null
null
test/what_print.cpp
xdanielsb/OperatingSystems
23bf014fae9644d4512b2337739e52adcd1087d6
[ "MIT" ]
null
null
null
test/what_print.cpp
xdanielsb/OperatingSystems
23bf014fae9644d4512b2337739e52adcd1087d6
[ "MIT" ]
null
null
null
#include <sys/types.h> #include <sys/wait.h> // wait #include <stdio.h> #include <unistd.h> //fork int value = 5; int main(){ pid_t pid; pid = fork(); if (pid == 0) { /* child process */ value += 15; return 0; } else if (pid > 0) { /* parent process */ wait(NULL); printf("PARENT: value = %d\n",value); /* LINE A */ return 0; } }
19.8
58
0.494949
xdanielsb
094d3141328f988eef54456acd4d36168c361e9a
8,596
cpp
C++
lualib-src/fixmath/bounce/Dynamics/Contacts/b3ContactSolver.cpp
ChestnutGames/chestnut
720cf88779f480191ae16fb1ba4da4597e5797d9
[ "MIT" ]
null
null
null
lualib-src/fixmath/bounce/Dynamics/Contacts/b3ContactSolver.cpp
ChestnutGames/chestnut
720cf88779f480191ae16fb1ba4da4597e5797d9
[ "MIT" ]
null
null
null
lualib-src/fixmath/bounce/Dynamics/Contacts/b3ContactSolver.cpp
ChestnutGames/chestnut
720cf88779f480191ae16fb1ba4da4597e5797d9
[ "MIT" ]
1
2019-11-07T16:06:03.000Z
2019-11-07T16:06:03.000Z
/* * Copyright (c) 2015-2015 Irlan Robson http://www.irlans.wordpress.com * * 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 would be * appreciated but is not 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 "b3ContactSolver.h" #include "b3Contact.h" #include "..\..\Collision\Shapes\b3Shape.h" #include "..\..\Dynamics\b3Body.h" #include "..\..\Common\Memory\b3StackAllocator.h" #include "..\..\Common\b3Time.h" b3ContactSolver::b3ContactSolver(const b3ContactSolverDef* def) { m_allocator = def->allocator; m_contacts = def->contacts; m_count = def->count; m_invDt = def->dt > B3_ZERO ? B3_ONE / def->dt : B3_ZERO; m_positions = def->positions; m_velocities = def->velocities; m_velocityConstraints = (b3ContactVelocityConstraint*)m_allocator->Allocate(m_count * sizeof(b3ContactVelocityConstraint)); for (u32 i = 0; i < m_count; ++i) { b3Contact* c = m_contacts[i]; b3ContactVelocityConstraint* vc = m_velocityConstraints + i; b3Body* bodyA = c->m_shapeA->GetBody(); b3Body* bodyB = c->m_shapeB->GetBody(); u32 pointCount = c->m_manifold.pointCount; b3Assert(pointCount > 0); vc->normal = c->m_manifold.normal; vc->invMassA = bodyA->m_invMass; vc->invMassB = bodyB->m_invMass; vc->invIA = bodyA->m_invWorldInertia; vc->invIB = bodyB->m_invWorldInertia; vc->friction = c->m_friction; vc->restitution = c->m_restitution; vc->indexA = bodyA->m_islandID; vc->indexB = bodyB->m_islandID; vc->pointCount = pointCount; for (u32 j = 0; j < pointCount; ++j) { b3ContactPoint* cp = c->m_manifold.points + j; b3VelocityConstraintPoint* vcp = vc->points + j; // Setup warm start. vcp->normalImpulse = cp->normalImpulse; vcp->tangentImpulse[0] = cp->tangentImpulse[0]; vcp->tangentImpulse[1] = cp->tangentImpulse[1]; vcp->tangents[0] = cp->tangents[0]; vcp->tangents[1] = cp->tangents[1]; } } } b3ContactSolver::~b3ContactSolver() { m_allocator->Free(m_velocityConstraints); } void b3ContactSolver::InitializeVelocityConstraints() { for (u32 i = 0; i < m_count; ++i) { b3Contact* c = m_contacts[i]; b3ContactVelocityConstraint* vc = m_velocityConstraints + i; r32 mA = vc->invMassA; r32 mB = vc->invMassB; b3Mat33 iA = vc->invIA; b3Mat33 iB = vc->invIB; u32 indexA = vc->indexA; u32 indexB = vc->indexB; u32 pointCount = c->m_manifold.pointCount; b3Vec3 vA = m_velocities[indexA].v; b3Vec3 wA = m_velocities[indexA].w; b3Vec3 xA = m_positions[indexA].x; b3Quaternion qA = m_positions[indexA].q; b3Vec3 vB = m_velocities[indexB].v; b3Vec3 wB = m_velocities[indexB].w; b3Vec3 xB = m_positions[indexB].x; b3Quaternion qB = m_positions[indexB].q; for (u32 j = 0; j < pointCount; ++j) { b3ContactPoint* cp = c->m_manifold.points + j; b3VelocityConstraintPoint* vcp = vc->points + j; vcp->rA = cp->position - xA; vcp->rB = cp->position - xB; // Compute tangent mass. b3Vec3 rt1A = b3Cross(vcp->rA, vcp->tangents[0]); b3Vec3 rt1B = b3Cross(vcp->rB, vcp->tangents[0]); b3Vec3 rt2A = b3Cross(vcp->rA, vcp->tangents[1]); b3Vec3 rt2B = b3Cross(vcp->rB, vcp->tangents[1]); r32 kTangent1 = mA + mB + b3Dot(rt1A, iA * rt1A) + b3Dot(rt1B, iB * rt1B); r32 kTangent2 = mA + mB + b3Dot(rt2A, iA * rt2A) + b3Dot(rt2B, iB * rt2B); vcp->tangentMass[0] = B3_ONE / kTangent1; vcp->tangentMass[1] = B3_ONE / kTangent2; // Compute normal mass. b3Vec3 rnA = b3Cross(vcp->rA, vc->normal); b3Vec3 rnB = b3Cross(vcp->rB, vc->normal); r32 kNormal = mA + mB + b3Dot(rnA, iA * rnA) + b3Dot(rnB, iB * rnB); vcp->normalMass = B3_ONE / kNormal; r32 C = b3Min(B3_ZERO, c->m_manifold.distances[j] + B3_LINEAR_SLOP); vcp->velocityBias = -m_invDt * B3_BAUMGARTE * C; // Add restitution in the velocity constraint. r32 vn = b3Dot(vB + b3Cross(wB, vcp->rB) - vA - b3Cross(wA, vcp->rA), vc->normal); if (vn < -B3_ONE) { vcp->velocityBias += -(c->m_restitution) * vn; } } } } void b3ContactSolver::WarmStart() { // Warm start. for (u32 i = 0; i < m_count; ++i) { b3ContactVelocityConstraint* vc = m_velocityConstraints + i; b3Vec3 normal = vc->normal; r32 mA = vc->invMassA; r32 mB = vc->invMassB; b3Mat33 iA = vc->invIA; b3Mat33 iB = vc->invIB; u32 indexA = vc->indexA; u32 indexB = vc->indexB; u32 pointCount = vc->pointCount; b3Vec3 vA = m_velocities[indexA].v; b3Vec3 wA = m_velocities[indexA].w; b3Vec3 vB = m_velocities[indexB].v; b3Vec3 wB = m_velocities[indexB].w; for (u32 j = 0; j < pointCount; ++j) { // Project old solutions into the new transposed Jacobians. b3VelocityConstraintPoint* vcp = vc->points + j; r32 lastNormalLambda = vcp->normalImpulse; r32 lastTangentLambda1 = vcp->tangentImpulse[0]; r32 lastTangentLambda2 = vcp->tangentImpulse[1]; b3Vec3 normalImpulse = lastNormalLambda * normal; b3Vec3 tangentImpulse1 = lastTangentLambda1 * vcp->tangents[0]; b3Vec3 tangentImpulse2 = lastTangentLambda2 * vcp->tangents[1]; b3Vec3 impulse = normalImpulse + tangentImpulse1 + tangentImpulse2; vA -= mA * impulse; wA -= iA * b3Cross(vcp->rA, impulse); vB += mB * impulse; wB += iB * b3Cross(vcp->rB, impulse); } m_velocities[indexA].v = vA; m_velocities[indexA].w = wA; m_velocities[indexB].v = vB; m_velocities[indexB].w = wB; } } void b3ContactSolver::SolveVelocityConstraints() { for (u32 i = 0; i < m_count; ++i) { b3ContactVelocityConstraint* vc = m_velocityConstraints + i; b3Vec3 normal = vc->normal; r32 mA = vc->invMassA; r32 mB = vc->invMassB; b3Mat33 iA = vc->invIA; b3Mat33 iB = vc->invIB; u32 indexA = vc->indexA; u32 indexB = vc->indexB; u32 pointCount = vc->pointCount; b3Vec3 vA = m_velocities[indexA].v; b3Vec3 wA = m_velocities[indexA].w; b3Vec3 vB = m_velocities[indexB].v; b3Vec3 wB = m_velocities[indexB].w; for (u32 j = 0; j < pointCount; ++j) { b3VelocityConstraintPoint* vcp = vc->points + j; { // Compute J * u. b3Vec3 dv = vB + b3Cross(wB, vcp->rB) - vA - b3Cross(wA, vcp->rA); r32 dCdt = b3Dot(dv, normal); // Compute new lambda values. r32 lambda = vcp->normalMass * (-dCdt + vcp->velocityBias); r32 newLambda = b3Max(vcp->normalImpulse + lambda, B3_ZERO); r32 deltaLambda = newLambda - vcp->normalImpulse; vcp->normalImpulse = newLambda; b3Vec3 deltaImpulse = deltaLambda * normal; vA -= mA * deltaImpulse; wA -= iA * b3Cross(vcp->rA, deltaImpulse); vB += mB * deltaImpulse; wB += iB * b3Cross(vcp->rB, deltaImpulse); } for (u32 k = 0; k < 2; ++k) { // Compute tangential impulse. r32 hi = vc->friction * vcp->normalImpulse; r32 lo = -hi; // Compute J * u. b3Vec3 dv = vB + b3Cross(wB, vcp->rB) - vA - b3Cross(wA, vcp->rA); r32 dCdt = b3Dot(dv, vcp->tangents[k]); // Compute new lambda values. r32 lambda = vcp->tangentMass[k] * -dCdt; r32 newLambda = b3Clamp(vcp->tangentImpulse[k] + lambda, lo, hi); r32 deltaLambda = newLambda - vcp->tangentImpulse[k]; vcp->tangentImpulse[k] = newLambda; b3Vec3 deltaImpulse = deltaLambda * vcp->tangents[k]; vA -= mA * deltaImpulse; wA -= iA * b3Cross(vcp->rA, deltaImpulse); vB += mB * deltaImpulse; wB += iB * b3Cross(vcp->rB, deltaImpulse); } } m_velocities[indexA].v = vA; m_velocities[indexA].w = wA; m_velocities[indexB].v = vB; m_velocities[indexB].w = wB; } } void b3ContactSolver::StoreImpulses() { for (u32 i = 0; i < m_count; ++i) { b3Contact* c = m_contacts[i]; b3ContactVelocityConstraint* vc = m_velocityConstraints + i; for (u32 j = 0; j < vc->pointCount; ++j) { b3VelocityConstraintPoint* vcp = vc->points + j; b3ContactPoint* cp = c->m_manifold.points + j; cp->normalImpulse = vcp->normalImpulse; cp->tangentImpulse[0] = vcp->tangentImpulse[0]; cp->tangentImpulse[1] = vcp->tangentImpulse[1]; } } }
31.487179
124
0.668334
ChestnutGames
094d3b91bd05a021fa12aca922b78938a74076e6
1,400
cpp
C++
src/core/win32/thread.cpp
mitchdowd/native
a690e0d5957953b3a8d0f7bb5f193292fa9feb28
[ "MIT" ]
11
2016-05-26T01:36:52.000Z
2020-07-21T03:41:42.000Z
src/core/win32/thread.cpp
mitchdowd/native
a690e0d5957953b3a8d0f7bb5f193292fa9feb28
[ "MIT" ]
75
2016-05-17T04:59:08.000Z
2018-04-08T09:50:42.000Z
src/core/win32/thread.cpp
mitchdowd/native
a690e0d5957953b3a8d0f7bb5f193292fa9feb28
[ "MIT" ]
2
2017-08-11T06:23:23.000Z
2019-11-13T06:54:07.000Z
#define NO_STRICT 1 // System Dependencies #include <Windows.h> // Module Dependencies #include "../include/exception.h" #include "../include/thread.h" namespace native { static thread_local Thread* _current = nullptr; Thread::Thread(const Function<void>& func) : _handle(nullptr), _func(func), _started(false), _id(0) { start(_func); } Thread::~Thread() { while (_handle != nullptr && !_started) yield(); } void Thread::start(const Function<void>& func) { if (_handle != nullptr) throw InvalidStateException(); _func = func; // Create the Thread resource with the OS. _handle = ::CreateThread(NULL, 0, LPTHREAD_START_ROUTINE(&entryPoint), this, 0, NULL); if (_handle == NULL) throw InsufficientResourcesException(); } void Thread::join() const { ::WaitForSingleObject(_handle, INFINITE); } void Thread::sleep(uint32_t milliSeconds) { if (milliSeconds > MAXDWORD) milliSeconds = MAXDWORD; ::Sleep(milliSeconds); } void Thread::yield() { ::YieldProcessor(); } Thread* Thread::getCurrent() { return _current; } int64_t Thread::getCurrentId() { return ::GetCurrentThreadId(); } ptrint_t Thread::entryPoint(Thread* thread) { _current = thread; thread->_started = true; try { // Execute the Thread's Function. thread->_func(); } catch (...) { return 1; } _current = nullptr; return 0; } }
16.091954
100
0.662143
mitchdowd
094e7d4d63b969d6c59fc9f57618a0d6dfe99bd5
10,799
cpp
C++
plugins/unifiedvideoinertialtracker/ImageSources/UVCImageSource.cpp
rpavlik/OSVR-UVBI-Tracker
d988cf2aad846f5cabbfb221c612c406d8d45e1b
[ "Apache-2.0" ]
369
2015-03-08T03:12:41.000Z
2022-02-08T22:15:39.000Z
plugins/unifiedvideoinertialtracker/ImageSources/UVCImageSource.cpp
DavidoRotho/OSVR-Core
b2fbb44e7979d9ebdf4bd8f00267cc267edbb465
[ "Apache-2.0" ]
486
2015-03-09T13:29:00.000Z
2020-10-16T00:41:26.000Z
plugins/unifiedvideoinertialtracker/ImageSources/UVCImageSource.cpp
DavidoRotho/OSVR-Core
b2fbb44e7979d9ebdf4bd8f00267cc267edbb465
[ "Apache-2.0" ]
166
2015-03-08T12:03:56.000Z
2021-12-03T13:56:21.000Z
/** @file @brief Header @date 2016 @author Sensics, Inc. <http://sensics.com> */ // Copyright 2016 Sensics, 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. #ifndef INCLUDED_UVCImageSource_cpp_GUID_2563F019_11B6_4F61_9E8C_C3ED2A573AF6 #define INCLUDED_UVCImageSource_cpp_GUID_2563F019_11B6_4F61_9E8C_C3ED2A573AF6 // Internal Includes #include "ImageSource.h" #include "ImageSourceFactories.h" // Library/third-party includes #include <libuvc/libuvc.h> #include <opencv2/core/core_c.h> // Standard includes #include <condition_variable> #include <cstdio> #include <iostream> #include <memory> #include <mutex> #include <queue> #include <stdexcept> #include <string> #include <unistd.h> namespace osvr { namespace vbtracker { class UVCImageSource : public ImageSource { public: /// Constructor UVCImageSource(int vendor_id = 0, int product_id = 0, const char *serial_number = nullptr); /// Destructor virtual ~UVCImageSource(); /// @return true if the camera/image source is OK virtual bool ok() const override; /// Trigger camera capture. May not necessarily include retrieval. /// Blocks until an image is available. or failure occurs. /// /// Timestamp after this call returns. /// /// @return false if the camera failed. virtual bool grab() override; /// Get resolution of the images from this source. virtual cv::Size resolution() const override; /// For those devices that naturally read a non-corrupt color image, /// overriding just this method will let the default implementation of /// retrieve() do the RGB to Gray for you. virtual void retrieveColor(cv::Mat &color, osvr::util::time::TimeValue &timestamp) override; protected: /// This callback function is called each time a new frame is received /// from the video stream. //@{ static void callback(uvc_frame_t *frame, void *ptr); void callback(uvc_frame_t *frame); //@} private: template <class T, void (*func_addr)(T *)> struct StatelessDeleter { void operator()(T *ptr) const { func_addr(ptr); } }; using Frame_ptr = std::unique_ptr<uvc_frame_t, StatelessDeleter<uvc_frame_t, &uvc_free_frame> >; std::unique_ptr<uvc_context_t, StatelessDeleter<uvc_context_t, &uvc_exit> > uvcContext_; std::unique_ptr<uvc_device_t, StatelessDeleter<uvc_device_t, &uvc_unref_device> > camera_; std::unique_ptr<uvc_device_handle_t, StatelessDeleter<uvc_device_handle_t, &uvc_close> > cameraHandle_; uvc_stream_ctrl_t streamControl_; osvr::util::time::TimeValue m_timestamp = {}; cv::Size resolution_; //< resolution of camera std::queue<Frame_ptr> frames_; //< raw UVC frames std::mutex mutex_; //< to protect frames_ std::condition_variable frames_available_; //< To allow grab() to wait //for frames to become //available }; using UVCImageSourcePtr = std::unique_ptr<UVCImageSource>; UVCImageSource::UVCImageSource(int vendor_id, int product_id, const char *serial_number) : streamControl_{}, resolution_{0, 0} { { // Initialize the libuvc context uvc_context_t *context; const auto init_res = uvc_init(&context, nullptr); if (UVC_SUCCESS != init_res) { throw std::runtime_error("Error initializing UVC context: " + std::string(uvc_strerror(init_res))); } uvcContext_.reset(context); } { // Find the requested camera uvc_device_t *device; const auto find_res = uvc_find_device(uvcContext_.get(), &device, vendor_id, product_id, serial_number); if (UVC_SUCCESS != find_res) { throw std::runtime_error("Error finding requested camera: " + std::string(uvc_strerror(find_res))); } camera_.reset(device); } { // Try to open the device -- requires exclusive access uvc_device_handle_t *device_handle; const auto open_res = uvc_open(camera_.get(), &device_handle); if (UVC_SUCCESS != open_res) { throw std::runtime_error("Error opening camera: " + std::string(uvc_strerror(open_res))); } cameraHandle_.reset(device_handle); //uvc_print_diag(cameraHandle_.get(), stdout); } // Setup streaming parameters const int resolution_x = 640; // pixels const int resolution_y = 480; // pixels resolution_ = cvSize(resolution_x, resolution_y); const int frame_rate = 100; // fps const auto setup_res = uvc_get_stream_ctrl_format_size( cameraHandle_.get(), &streamControl_, UVC_FRAME_FORMAT_MJPEG, resolution_x, resolution_y, frame_rate); // uvc_print_stream_ctrl(&streamControl_, stdout); if (UVC_SUCCESS != setup_res) { std::cerr << "Error setting up requested stream format. " + std::string(uvc_strerror(setup_res)); } // Start streaming video. const auto stream_res = uvc_start_streaming(cameraHandle_.get(), &streamControl_, &UVCImageSource::callback, this, 0); if (UVC_SUCCESS != stream_res) { throw std::runtime_error("Error streaming from camera: " + std::string(uvc_strerror(stream_res))); } } UVCImageSource::~UVCImageSource() { // Stop streaming video (if required) if (cameraHandle_) { uvc_stop_streaming(cameraHandle_.get()); } } bool UVCImageSource::ok() const { // TODO return true; } bool UVCImageSource::grab() { // Gain access to frames_ queue std::unique_lock<std::mutex> lock(mutex_); // Wait until there are any frames available frames_available_.wait(lock, [this]() { return !frames_.empty(); }); // Good to go! if (!frames_.empty()) { m_timestamp = util::time::getNow(); } return !frames_.empty(); } cv::Size UVCImageSource::resolution() const { return resolution_; } void osvr::vbtracker::UVCImageSource::retrieveColor(cv::Mat& color, util::time::TimeValue& timestamp) { // Grab a frame from the queue, but don't keep the queue locked! Frame_ptr current_frame; { std::unique_lock<std::mutex> lock(mutex_); if (frames_.empty()) { throw std::runtime_error("Error: There's no frames available."); } current_frame.reset(frames_.front().release()); frames_.pop(); } timestamp = m_timestamp; // Convert the image to at cv::Mat color = cv::Mat(current_frame->height, current_frame->width, CV_8UC3, current_frame->data) .clone(); } void UVCImageSource::callback(uvc_frame_t *frame, void *ptr) { auto me = static_cast<UVCImageSource *>(ptr); me->callback(frame); } void UVCImageSource::callback(uvc_frame_t *frame) { // Must be quick here, cannot delay the callback or it will fail to // respond to usb events // We can either copy the frame, and convert to rgb later, or // just convert and save one copy (and allocation) in the server // thread. As the conversion can't be much more expensive than a // copy, we perform it here. Frame_ptr rgb_frame( uvc_allocate_frame(frame->width * frame->height * 3)); if (!rgb_frame) { throw std::runtime_error( "Error: Unable to allocate the rgb frame."); } auto convert_ret = uvc_mjpeg2rgb(frame, rgb_frame.get()); if (UVC_SUCCESS != convert_ret) { // Try any2rgb() instead auto any_ret = uvc_any2rgb(frame, rgb_frame.get()); if (UVC_SUCCESS != any_ret) { throw std::runtime_error( "Error: Unable to convert frame to rgb: " + std::string(uvc_strerror(convert_ret))); } } std::lock_guard<std::mutex> lock(mutex_); frames_.emplace(rgb_frame.release()); if (frames_.size() > 100) { std::cerr << "WARNING! Dropping frames from video tracker as they " "are not being processed fast enough! This will " "disrupt tracking." << std::endl; frames_ = std::queue<Frame_ptr>(); //< clear the queue } frames_available_.notify_one(); } /// Factory method to open a USB video class (UVC) device as an image /// source. ImageSourcePtr openUVCCamera(int vendor_id, int product_id, const char *serial_number) { auto ret = ImageSourcePtr{}; try { auto source = new UVCImageSource(vendor_id, product_id, serial_number); ret.reset(source); } catch (const std::exception &e) { std::cerr << "Caught exception initializing UVC camera image source: " << e.what() << std::endl; } return ret; } /// Factory method to open the HDK camera as an image source via libuvc. ImageSourcePtr openHDKCameraUVC() { const int vendor_id = 0x0bda; const int product_id = 0x57e8; return openUVCCamera(vendor_id, product_id); } } // namespace vbtracker } // namespace osvr #endif // INCLUDED_UVCImageSource_cpp_GUID_2563F019_11B6_4F61_9E8C_C3ED2A573AF6
35.877076
105
0.587554
rpavlik
0959eded48ad3f2cf9e3c83095eff3cf19ee341f
4,582
cxx
C++
src/ozw/zwNode.cxx
whpenner/upm
3168c61d8613da62ecc7598517a1decf533d5fe7
[ "MIT" ]
null
null
null
src/ozw/zwNode.cxx
whpenner/upm
3168c61d8613da62ecc7598517a1decf533d5fe7
[ "MIT" ]
null
null
null
src/ozw/zwNode.cxx
whpenner/upm
3168c61d8613da62ecc7598517a1decf533d5fe7
[ "MIT" ]
null
null
null
/* * Author: Jon Trulson <jtrulson@ics.com> * Copyright (c) 2015-2016 Intel Corporation. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdint.h> #include <string> #include <cinttypes> #include "zwNode.hpp" #include "Node.h" using namespace upm; using namespace std; using namespace OpenZWave; zwNode::zwNode(uint32_t homeId, uint8_t nodeId) { m_homeId = homeId; m_nodeId = nodeId; m_vindex = 0; m_list.clear(); m_values.clear(); m_autoUpdate = false; } zwNode::~zwNode() { } uint8_t zwNode::nodeId() { return m_nodeId; } uint32_t zwNode::homeId() { return m_homeId; } void zwNode::addValueID(ValueID vid) { m_list.push_back(vid); if (m_autoUpdate) updateVIDMap(); } void zwNode::removeValueID(ValueID vid) { m_list.remove(vid); if (m_autoUpdate) updateVIDMap(); } void zwNode::updateVIDMap() { m_values.clear(); m_vindex = 0; m_list.sort(); for (auto it = m_list.cbegin(); it != m_list.cend(); ++it) { // We need to use insert since ValueID's default ctor is private m_values.insert(std::pair<int, ValueID>(m_vindex++, *it)); } } bool zwNode::indexToValueID(int index, ValueID *vid) { valueMap_t::iterator it; it = m_values.find(index); if (it == m_values.end()) { // not found, return false return false; } else *vid = (*it).second; return true; } void zwNode::dumpNode(bool all) { for (auto it = m_values.cbegin(); it != m_values.cend(); ++it) { int vindex = it->first; ValueID vid = it->second; string label = Manager::Get()->GetValueLabel(vid); string valueAsStr; Manager::Get()->GetValueAsString(vid, &valueAsStr); string valueUnits = Manager::Get()->GetValueUnits(vid); ValueID::ValueType vType = vid.GetType(); string vTypeStr; string perms; if (Manager::Get()->IsValueWriteOnly(vid)) perms = "WO"; else if (Manager::Get()->IsValueReadOnly(vid)) perms = "RO"; else perms = "RW"; switch (vType) { case ValueID::ValueType_Bool: vTypeStr = "bool"; break; case ValueID::ValueType_Byte: vTypeStr = "byte"; break; case ValueID::ValueType_Decimal: vTypeStr = "float"; break; case ValueID::ValueType_Int: vTypeStr = "int32"; break; case ValueID::ValueType_List: vTypeStr = "list"; break; case ValueID::ValueType_Schedule: vTypeStr = "schedule"; break; case ValueID::ValueType_Short: vTypeStr = "int16"; break; case ValueID::ValueType_String: vTypeStr = "string"; break; case ValueID::ValueType_Button: vTypeStr = "button"; break; case ValueID::ValueType_Raw: vTypeStr = "raw"; break; default: vTypeStr = "undefined"; break; } // by default we only want user values, unless 'all' is true if (all || (vid.GetGenre() == ValueID::ValueGenre_User)) { fprintf(stderr, "\t Index: %d, Type: %s, Label: %s, Value: %s %s (%s)\n", vindex, vTypeStr.c_str(), label.c_str(), valueAsStr.c_str(), valueUnits.c_str(), perms.c_str()); fprintf(stderr, "\t\t VID: %016" PRIx64 "\n", vid.GetId()); } } }
23.141414
83
0.606285
whpenner
0959f0c4e1b8fd7238398cf8b691ed44e495d065
2,953
hpp
C++
include/System/Xml/Schema/RangePositionInfo.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Xml/Schema/RangePositionInfo.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Xml/Schema/RangePositionInfo.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.ValueType #include "System/ValueType.hpp" // Including type: System.Decimal #include "System/Decimal.hpp" #include "beatsaber-hook/shared/utils/typedefs-array.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Xml::Schema namespace System::Xml::Schema { // Forward declaring type: BitSet class BitSet; } // Completed forward declares // Type namespace: System.Xml.Schema namespace System::Xml::Schema { // Forward declaring type: RangePositionInfo struct RangePositionInfo; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(::System::Xml::Schema::RangePositionInfo, "System.Xml.Schema", "RangePositionInfo"); // Type namespace: System.Xml.Schema namespace System::Xml::Schema { // Size: 0x10 #pragma pack(push, 1) // WARNING Layout: Sequential may not be correctly taken into account! // Autogenerated type: System.Xml.Schema.RangePositionInfo // [TokenAttribute] Offset: FFFFFFFF struct RangePositionInfo/*, public ::System::ValueType*/ { public: public: // public System.Xml.Schema.BitSet curpos // Size: 0x8 // Offset: 0x0 ::System::Xml::Schema::BitSet* curpos; // Field size check static_assert(sizeof(::System::Xml::Schema::BitSet*) == 0x8); // public System.Decimal[] rangeCounters // Size: 0x8 // Offset: 0x8 ::ArrayW<::System::Decimal> rangeCounters; // Field size check static_assert(sizeof(::ArrayW<::System::Decimal>) == 0x8); public: // Creating value type constructor for type: RangePositionInfo constexpr RangePositionInfo(::System::Xml::Schema::BitSet* curpos_ = {}, ::ArrayW<::System::Decimal> rangeCounters_ = ::ArrayW<::System::Decimal>(static_cast<void*>(nullptr))) noexcept : curpos{curpos_}, rangeCounters{rangeCounters_} {} // Creating interface conversion operator: operator ::System::ValueType operator ::System::ValueType() noexcept { return *reinterpret_cast<::System::ValueType*>(this); } // Get instance field reference: public System.Xml.Schema.BitSet curpos [[deprecated("Use field access instead!")]] ::System::Xml::Schema::BitSet*& dyn_curpos(); // Get instance field reference: public System.Decimal[] rangeCounters [[deprecated("Use field access instead!")]] ::ArrayW<::System::Decimal>& dyn_rangeCounters(); }; // System.Xml.Schema.RangePositionInfo #pragma pack(pop) static check_size<sizeof(RangePositionInfo), 8 + sizeof(::ArrayW<::System::Decimal>)> __System_Xml_Schema_RangePositionInfoSizeCheck; static_assert(sizeof(RangePositionInfo) == 0x10); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
44.074627
240
0.709448
v0idp
095a7b30837fe2e296d01cf71c341c322ad91b94
4,679
cpp
C++
cpp/example_code/dynamodb/query_items.cpp
brmur/aws-doc-sdk-examples
9158f493ee2c016f0b4a2260e8f43acc7b0b49e6
[ "Apache-2.0" ]
null
null
null
cpp/example_code/dynamodb/query_items.cpp
brmur/aws-doc-sdk-examples
9158f493ee2c016f0b4a2260e8f43acc7b0b49e6
[ "Apache-2.0" ]
1
2020-03-18T17:00:15.000Z
2020-03-18T17:04:05.000Z
cpp/example_code/dynamodb/query_items.cpp
brmur/aws-doc-sdk-examples
9158f493ee2c016f0b4a2260e8f43acc7b0b49e6
[ "Apache-2.0" ]
null
null
null
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX - License - Identifier: Apache - 2.0 /* Purpose: query_items.cpp demonstrates how to perfrom Query operation and retrieve items from an Amazon DynamoDB table. */ //snippet-start:[dynamodb.cpp.query_items.inc] #include <aws/core/Aws.h> #include <aws/core/utils/Outcome.h> #include <aws/dynamodb/DynamoDBClient.h> #include <aws/dynamodb/model/AttributeDefinition.h> #include <aws/dynamodb/model/QueryRequest.h> #include <iostream> //snippet-end:[dynamodb.cpp.query_items.inc] /** * Perform query on a DynamoDB Table and retrieve item(s). * * Takes the name of the table and partition key attribute name and value to query. * * The partition key attribute is searched with the specified value. By default, all fields and values * contained in the item are returned. If an optional projection expression is * specified on the command line, only the specified fields and values are * returned. * */ int main(int argc, char** argv) { const std::string USAGE = "\n" \ "Usage:\n" " query_items <table> <partitionKeyAttributeName>=<partitionKeyValue> [projection_expression]\n\n" "Where:\n" " table - the table to get an item from.\n" " partitionKeyAttributeName - Partition Key attribute of the table.\n" " partitionKeyValue - Partition Key value to query.\n\n" "You can add an optional projection expression (a quote-delimited,\n" "comma-separated list of attributes to retrieve) to limit the\n" "fields returned from the table.\n\n" "Example:\n" " query_items HelloTable Name=Namaste\n" " query_items Players FirstName=Mike\n" " query_items SiteColors Background=white \"default, bold\"\n"; if (argc < 3) { std::cout << USAGE; return 1; } Aws::SDKOptions options; Aws::InitAPI(options); { const Aws::String table(argv[1]); const Aws::String partitionKeyNameAndValue(argv[2]); Aws::String partitionKeyAttributeName(""); Aws::String partitionKeyAttributeValue(""); // Split and get partitionKeyAttributeName and partitionKeyAttributeValue const Aws::Vector<Aws::String>& flds = Aws::Utils::StringUtils::Split(partitionKeyNameAndValue, '='); if (flds.size() == 2) { partitionKeyAttributeName = flds[0]; partitionKeyAttributeValue = flds[1]; } else { std::cout << "Invalid argument: " << partitionKeyNameAndValue << std::endl << USAGE; return 1; } const Aws::String projection(argc > 3 ? argv[3] : ""); // snippet-start:[dynamodb.cpp.query_items.code] Aws::Client::ClientConfiguration clientConfig; Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfig); Aws::DynamoDB::Model::QueryRequest req; req.SetTableName(table); // Set query key condition expression req.SetKeyConditionExpression(partitionKeyAttributeName + "= :valueToMatch"); // Set Expression AttributeValues Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> attributeValues; attributeValues.emplace(":valueToMatch", partitionKeyAttributeValue); req.SetExpressionAttributeValues(attributeValues); // Perform Query operation const Aws::DynamoDB::Model::QueryOutcome& result = dynamoClient.Query(req); if (result.IsSuccess()) { // Reference the retrieved items const Aws::Vector<Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue>>& items = result.GetResult().GetItems(); if(items.size() > 0) { std::cout << "Number of items retrieved from Query: " << items.size() << std::endl; //Iterate each item and print for(const auto &item: items) { std::cout << "******************************************************" << std::endl; // Output each retrieved field and its value for (const auto& i : item) std::cout << i.first << ": " << i.second.GetS() << std::endl; } } else { std::cout << "No item found in table: " << table << std::endl; } } else { std::cout << "Failed to Query items: " << result.GetError().GetMessage(); } // snippet-end:[dynamodb.cpp.query_items.code] } Aws::ShutdownAPI(options); return 0; }
36.554688
130
0.60312
brmur
095a954b9b931effd33d133383a2ae1d34574731
4,391
cpp
C++
test/datetime/main.cpp
HanixNicolas/app-mesh
8ee77a6adb1091b3a0afcbc34d271b4b9508840e
[ "MIT" ]
90
2020-06-06T12:11:33.000Z
2022-01-04T11:30:24.000Z
test/datetime/main.cpp
HanixNicolas/app-mesh
8ee77a6adb1091b3a0afcbc34d271b4b9508840e
[ "MIT" ]
80
2020-05-19T14:33:34.000Z
2022-03-25T08:00:54.000Z
test/datetime/main.cpp
HanixNicolas/app-mesh
8ee77a6adb1091b3a0afcbc34d271b4b9508840e
[ "MIT" ]
14
2020-07-16T11:35:47.000Z
2022-01-04T03:10:44.000Z
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include "../../src/common/DateTime.h" #include "../../src/common/Utility.h" #include "../catch.hpp" #include <ace/Init_ACE.h> #include <ace/OS.h> #include <chrono> #include <fstream> #include <iostream> #include <log4cpp/Appender.hh> #include <log4cpp/Category.hh> #include <log4cpp/FileAppender.hh> #include <log4cpp/OstreamAppender.hh> #include <log4cpp/PatternLayout.hh> #include <log4cpp/Priority.hh> #include <log4cpp/RollingFileAppender.hh> #include <set> #include <string> #include <thread> #include <time.h> void init() { static bool initialized = false; if (!initialized) { initialized = true; ACE::init(); using namespace log4cpp; auto logDir = Utility::stringFormat("%s", Utility::getSelfDir().c_str()); auto consoleLayout = new PatternLayout(); consoleLayout->setConversionPattern("%d [%t] %p %c: %m%n"); auto consoleAppender = new OstreamAppender("console", &std::cout); consoleAppender->setLayout(consoleLayout); auto rollingFileAppender = new RollingFileAppender( "rollingFileAppender", logDir.append("/unittest.log"), 20 * 1024 * 1024, 5, true, 00664); auto pLayout = new PatternLayout(); pLayout->setConversionPattern("%d [%t] %p %c: %m%n"); rollingFileAppender->setLayout(pLayout); Category &root = Category::getRoot(); root.addAppender(rollingFileAppender); root.addAppender(consoleAppender); // Log level Utility::setLogLevel("DEBUG"); LOG_INF << "Logging process ID:" << getpid(); } } TEST_CASE("DateTime Class Test", "[DateTime]") { init(); // covert now to seconds auto now = std::chrono::system_clock::now(); std::string timeStr = "2020-10-08T14:14:00+08"; LOG_DBG << timeStr << " is " << DateTime::formatISO8601Time(DateTime::parseISO8601DateTime(timeStr, "")); auto localTime = std::chrono::system_clock::from_time_t(std::chrono::system_clock::to_time_t(now)); LOG_DBG << "now: " << DateTime::formatISO8601Time(localTime); REQUIRE(localTime == DateTime::parseISO8601DateTime(DateTime::formatISO8601Time(localTime), "")); // parseISO8601DateTime try { DateTime::parseISO8601DateTime("123"); } catch (...) { REQUIRE(true); } REQUIRE(DateTime::parseISO8601DateTime("") == std::chrono::system_clock::from_time_t(0)); auto iso8601 = "2020-10-07T21:19:00+08"; auto iso8601TimePoint = DateTime::parseISO8601DateTime(iso8601, ""); REQUIRE(iso8601TimePoint == DateTime::parseISO8601DateTime("2020-10-07T21:19:00+8", "")); REQUIRE_FALSE(DateTime::parseISO8601DateTime("2020-10-07T21:19:00", "") == DateTime::parseISO8601DateTime("2020-10-07T21:19:00+07", "")); // formatRFC3339Time auto rfc3339 = "2020-10-07T13:19:00Z"; LOG_DBG << DateTime::formatRFC3339Time(iso8601TimePoint); REQUIRE(DateTime::formatRFC3339Time(iso8601TimePoint) == rfc3339); // getLocalZoneUTCOffset LOG_DBG << DateTime::getLocalZoneUTCOffset(); REQUIRE(boost::posix_time::to_simple_string(DateTime::parseDayTimeUtcDuration("20:33:00", "+08")) == "12:33:00"); // time in different zone REQUIRE(DateTime::parseISO8601DateTime("2020-10-07T21:19:00+07", "") == DateTime::parseISO8601DateTime("2020-10-07T22:19:00+08", "")); } TEST_CASE("Boost Date Time Test", "[Boost]") { init(); LOG_DBG << "get_std_zone_abbrev: " << machine_time_zone::get_std_zone_abbrev(); LOG_DBG << "get_utc_offset: " << machine_time_zone::get_utc_offset(); REQUIRE(boost::posix_time::to_simple_string(boost::posix_time::duration_from_string("-08:00")) == "-08:00:00"); REQUIRE(boost::posix_time::to_simple_string(boost::posix_time::duration_from_string("08:00")) == "08:00:00"); REQUIRE(boost::posix_time::to_simple_string(boost::posix_time::duration_from_string("+20:01:00")) == "20:01:00"); REQUIRE(boost::posix_time::to_simple_string(boost::posix_time::duration_from_string("-20:01")) == "-20:01:00"); REQUIRE(boost::posix_time::to_simple_string(boost::posix_time::duration_from_string("8")) == "08:00:00"); REQUIRE(boost::posix_time::to_simple_string(boost::posix_time::duration_from_string("+8")) == "08:00:00"); }
38.858407
141
0.669551
HanixNicolas
095a9f4ba64148dadce2bc756c03e8ab9972ae13
2,168
cpp
C++
for c++/data/sfatima/usetsm.cpp
aerolalit/Auto-Testing-Python-Programs
dd49ab266c9f0fd8e34278f68f8af017711942e3
[ "MIT" ]
4
2019-10-03T21:16:51.000Z
2019-10-04T01:28:08.000Z
for c++/data/sfatima/usetsm.cpp
aerolalit/Auto-Testing
dd49ab266c9f0fd8e34278f68f8af017711942e3
[ "MIT" ]
null
null
null
for c++/data/sfatima/usetsm.cpp
aerolalit/Auto-Testing
dd49ab266c9f0fd8e34278f68f8af017711942e3
[ "MIT" ]
null
null
null
/* CH08-320143 a4_p3.cpp Syeda Alizae Fatima s.fatima@jacobs-university.de */ #include <iostream> #include <cstdlib> #include <set> #include <algorithm> using namespace std; int main(){ int n; set <int> A; multiset <int> B; multiset <int> uni; set <int> intersection; set <int> difference; set <int> symmetric; set<int>::iterator si; multiset<int>::iterator mi; cin >> n; while(1) { if(n<0) break; A.insert(n); B.insert(n); cin >> n; } cout << endl << "A: "; for(si = A.begin(); si != A.end(); si++) cout << *si << " "; cout << endl << endl; cout << "B: "; for(mi = B.begin(); mi != B.end(); mi++) cout << *mi << " "; cout << endl; A.erase(5); B.erase(5); cout << endl << "A: "; for(si = A.begin(); si != A.end(); si++) cout << *si << " "; cout << endl << endl; cout << "B: "; for(mi = B.begin(); mi != B.end(); mi++) cout << *mi << " "; cout << endl; A.insert(14); A.insert(198); set_union(A.begin(),A.end(),B.begin(),B.end(),inserter(uni,uni.begin())); cout << endl << "Union:"; for(mi = uni.begin(); mi != uni.end(); mi++) cout << *mi << " "; cout << endl; set_intersection(A.begin(),A.end(),B.begin(),B.end(),inserter(intersection,intersection.begin())); cout << endl << "Intersection:"; for(si = intersection.begin(); si != intersection.end(); si++) cout << *si << " "; cout << endl; set_difference(A.begin(),A.end(),B.begin(),B.end(),inserter(difference,difference.begin())); cout << endl << "Difference:"; for(si = difference.begin(); si != difference.end(); si++) cout << *si << " "; cout << endl; set_symmetric_difference(A.begin(),A.end(),B.begin(),B.end(),inserter(symmetric,symmetric.begin())); cout << endl << "Symmetric difference:"; for(si = symmetric.begin(); si != symmetric.end(); si++) cout << *si << " "; cout << endl; return 0; }
22.821053
105
0.480627
aerolalit
095f1354b8a02f6f329d7736e4bb603f5ed9f2b4
710
cpp
C++
p14889.cpp
sjnov11/Baekjoon-Online-Judge
a95df8a62e181d86a97d0e8969d139a3dae2be74
[ "MIT" ]
null
null
null
p14889.cpp
sjnov11/Baekjoon-Online-Judge
a95df8a62e181d86a97d0e8969d139a3dae2be74
[ "MIT" ]
null
null
null
p14889.cpp
sjnov11/Baekjoon-Online-Judge
a95df8a62e181d86a97d0e8969d139a3dae2be74
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> #include <algorithm> using namespace std; int N; int S[21][21]; int A[21]; int answer = 99999999; void go(int idx, int cnt) { if (cnt == N / 2) { int A_score = 0; int B_score = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (A[i] == 1 && A[j] == 1) A_score += S[i][j]; if (A[i] == 0 && A[j] == 0) B_score += S[i][j]; } } answer = min(answer, abs(A_score - B_score)); return; } if (idx == N) return; go(idx + 1, cnt); A[idx] = 1; go(idx + 1, cnt + 1); A[idx] = 0; } int main() { cin >> N; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cin >> S[i][j]; } } go(0, 0); cout << answer << endl; }
16.904762
51
0.473239
sjnov11
095feab036982b34e11aea96d4377a8f1939e700
967
cpp
C++
bzoj/2464.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
3
2017-09-17T09:12:50.000Z
2018-04-06T01:18:17.000Z
bzoj/2464.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
bzoj/2464.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
#include <bits/stdc++.h> #define ll long long using namespace std; int n, m, mp[502][502], a[4]={0,1,0,-1}, sx, sy, ex, ey, ans[505][505]; char c[505]; struct node{ int x, y, time; }; queue<node> q; void dfs(){ node s; while(!q.empty()){ s = q.front();q.pop(); if(ans[s.x][s.y] <= s.time) continue; ans[s.x][s.y] = s.time; for(int i = 0; i < 4; i++){ if(s.x+a[i]>n||s.x+a[i]<1||s.y+a[3-i]>m||s.y+a[3-i]<1)continue; if(mp[s.x][s.y] == mp[s.x+a[i]][s.y+a[3-i]]) q.push((node){s.x+a[i], s.y+a[3-i], s.time}); else q.push((node){s.x+a[i], s.y+a[3-i], s.time+1}); } } printf("%d\n", ans[ex][ey]); } int main(){ while(~scanf("%d%d", &n, &m) && n && m){ memset(mp, 0, sizeof mp); memset(ans, 127/3, sizeof ans); for(int i = 1; i <= n; i++){ scanf("%s", c); for(int j = 0; j < m; j++) mp[i][j+1] = (c[j] == '@'); } scanf("%d%d%d%d", &sx, &sy, &ex, &ey); ex++,ey++; q.push((node){sx+1, sy+1, 0}); dfs(); } return 0; }
23.02381
71
0.4788
swwind
8231328deb968f632cee6436163ddb145cf4a364
1,093
cpp
C++
libvast/test/index/enumeration_index.cpp
lava/vast
0bc9e3c12eb31ec50dd0270626d55e84b2255899
[ "BSD-3-Clause" ]
1
2021-05-14T02:03:17.000Z
2021-05-14T02:03:17.000Z
libvast/test/index/enumeration_index.cpp
5l1v3r1/vast
a2cb4be879a13cef855da2c1d73083204aed4dff
[ "BSD-3-Clause" ]
null
null
null
libvast/test/index/enumeration_index.cpp
5l1v3r1/vast
a2cb4be879a13cef855da2c1d73083204aed4dff
[ "BSD-3-Clause" ]
null
null
null
// _ _____ __________ // | | / / _ | / __/_ __/ Visibility // | |/ / __ |_\ \ / / Across // |___/_/ |_/___/ /_/ Space and Time // // SPDX-FileCopyrightText: (c) 2020 The VAST Contributors // SPDX-License-Identifier: BSD-3-Clause #define SUITE value_index #include "vast/index/enumeration_index.hpp" #include "vast/concept/printable/to_string.hpp" #include "vast/concept/printable/vast/bitmap.hpp" #include "vast/test/test.hpp" #include <caf/test/dsl.hpp> using namespace vast; using namespace std::string_literals; TEST(enumeration) { auto e = enumeration_type{{"foo", "bar"}}; auto idx = enumeration_index(e); REQUIRE(idx.append(enumeration{0})); REQUIRE(idx.append(enumeration{0})); REQUIRE(idx.append(enumeration{1})); REQUIRE(idx.append(enumeration{0})); auto foo = idx.lookup(relational_operator::equal, make_data_view(enumeration{0})); CHECK_EQUAL(to_string(foo), "1101"); auto bar = idx.lookup(relational_operator::not_equal, make_data_view(enumeration{0})); CHECK_EQUAL(to_string(bar), "0010"); }
30.361111
77
0.673376
lava
823750c6409705dec4d157c552c86bf6c118d0b3
1,012
cpp
C++
src/caches/lhd/lhd_variants.cpp
xiaohu4313888/lrb
fb03d938f405abc0aa14ac6171c9e57b43e19072
[ "BSD-2-Clause" ]
56
2020-02-13T23:22:55.000Z
2022-01-30T20:46:14.000Z
src/caches/lhd/lhd_variants.cpp
xiaohu4313888/lrb
fb03d938f405abc0aa14ac6171c9e57b43e19072
[ "BSD-2-Clause" ]
10
2020-04-26T00:55:48.000Z
2021-07-30T15:56:20.000Z
src/caches/lhd/lhd_variants.cpp
xiaohu4313888/lrb
fb03d938f405abc0aa14ac6171c9e57b43e19072
[ "BSD-2-Clause" ]
20
2020-04-16T22:15:56.000Z
2021-12-29T00:36:09.000Z
#include <unordered_map> #include <random> #include <cmath> #include <cassert> #include "lhd_variants.h" #include "cache.hpp" #include "repl.hpp" #include "parser.hpp" #include "lhd.hpp" #include "constants.hpp" /* LHD variants impl */ LHD::LHD() { lhdcache = new cache::Cache(); lhdcache->repl = new repl::LHD(assoc, admissionSamples, lhdcache); } void LHD::setSize(const uint64_t &cs) { _cacheSize = cs; lhdcache->availableCapacity = cs; dynamic_cast<repl::LHD *>(lhdcache->repl)->explorerBudget = lhdcache->availableCapacity * repl::LHD::EXPLORER_BUDGET_FRACTION; } bool LHD::lookup(const SimpleRequest &req) { // fixme -> app id // const parser::PartialRequest preq {1, (int64_t)req.size, (int64_t)req.id}; // pr.appId - 1 const parser::Request preq { 0., 1, parser::GET, 0, (int64_t)req.size, (int64_t)req.id, false }; return(lhdcache->access(preq)); } void LHD::admit(const SimpleRequest &req) { // nop } void LHD::evict() { // nop }
21.083333
100
0.658103
xiaohu4313888
82375faee2505d17fdd5800bfc7c7b69f49302b5
2,309
cpp
C++
src/HRI.cpp
qqzz0xx/bgfx-with-imgui-example-cmake
18add8dedd11fbfe0f644f0693adfb21f5cc4606
[ "BSD-2-Clause" ]
null
null
null
src/HRI.cpp
qqzz0xx/bgfx-with-imgui-example-cmake
18add8dedd11fbfe0f644f0693adfb21f5cc4606
[ "BSD-2-Clause" ]
null
null
null
src/HRI.cpp
qqzz0xx/bgfx-with-imgui-example-cmake
18add8dedd11fbfe0f644f0693adfb21f5cc4606
[ "BSD-2-Clause" ]
null
null
null
#include "HRI.h" #include "bgfx/bgfx.h" #include "bx/math.h" #include <array> #include <vector> #include <memory_resource> using mat4 = std::array<float, 16>; struct HRIContext; static mat4 makeMat4(); struct HRIContext { std::vector<mat4> modelMatrixs; std::vector<mat4> viewMatrixs; std::vector<mat4> projectMatrixs; HRIContext() { modelMatrixs.push_back(makeMat4()); viewMatrixs.push_back(makeMat4()); projectMatrixs.push_back(makeMat4()); } }; static HRIContext s_ctx; static mat4 makeMat4() { mat4 res = { 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 }; return res; } void HRI::push_viewTarget(uint16_t viewId) { } void HRI::pop_viewTarget() { } void HRI::push_matrix() { s_ctx.modelMatrixs.push_back(makeMat4()); } void HRI::pop_matrix() { s_ctx.modelMatrixs.pop_back(); } void HRI::setMatrix(float m[16]) { auto& cur = s_ctx.modelMatrixs.back(); memcpy(cur.data(), m, 16 * sizeof(float)); } void HRI::push_viewMatrix() { s_ctx.viewMatrixs.push_back(makeMat4()); } void HRI::pop_viewMatrix() { s_ctx.viewMatrixs.pop_back(); } void HRI::push_projectMatrix() { s_ctx.projectMatrixs.push_back(makeMat4()); } void HRI::pop_projectMatrix() { s_ctx.projectMatrixs.pop_back(); } void HRI::ortho(float _left, float _right, float _bottom, float _top, float _near, float _far, float _offset) { auto& cur = s_ctx.projectMatrixs.back(); auto caps = bgfx::getCaps(); bx::mtxOrtho(cur.data(), _left, _right, _bottom, _top, _near, _far, _offset, caps->homogeneousDepth); } void HRI::perspective(float _fovy, float _aspect, float _near, float _far) { auto& cur = s_ctx.projectMatrixs.back(); auto caps = bgfx::getCaps(); bx::mtxProj(cur.data(), _fovy, _aspect, _near, _far, caps->homogeneousDepth); } void HRI::push_MVP() { push_matrix(); push_viewMatrix(); push_projectMatrix(); } void HRI::updateMVP(uint16_t viewId) { const auto& curModel = s_ctx.modelMatrixs.back(); const auto& curView = s_ctx.viewMatrixs.back(); const auto& curProj = s_ctx.projectMatrixs.back(); bgfx::setTransform(curModel.data()); bgfx::setViewTransform(viewId, curView.data(), curProj.data()); } void HRI::pop_MVP() { pop_matrix(); pop_viewMatrix(); pop_projectMatrix(); } void HRI::draw_rect(float x, float y, int w, int h) { }
18.181102
109
0.689476
qqzz0xx
823fe001846cb897c6e03c1bcafbfd0174863601
8,053
cc
C++
chrome/browser/optimization_guide/android/optimization_guide_tab_url_provider_android_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/browser/optimization_guide/android/optimization_guide_tab_url_provider_android_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
chrome/browser/optimization_guide/android/optimization_guide_tab_url_provider_android_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/optimization_guide/android/optimization_guide_tab_url_provider_android.h" #include "chrome/browser/android/tab_android.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/android/tab_model/tab_model.h" #include "chrome/browser/ui/android/tab_model/tab_model_list.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "content/public/test/web_contents_tester.h" #include "testing/gmock/include/gmock/gmock.h" namespace optimization_guide { namespace android { namespace { using FakeTab = std::pair<GURL, absl::optional<base::TimeTicks>>; using ::testing::ElementsAre; // FakeTabModel that can be used for testing Android tab behavior. class FakeTabModel : public TabModel { public: explicit FakeTabModel( Profile* profile, const std::vector<content::WebContents*>& web_contents_list) : TabModel(profile, chrome::android::ActivityType::kCustomTab), web_contents_list_(web_contents_list) {} int GetTabCount() const override { return static_cast<int>(web_contents_list_.size()); } int GetActiveIndex() const override { return 0; } content::WebContents* GetWebContentsAt(int index) const override { if (index < static_cast<int>(web_contents_list_.size())) return web_contents_list_[index]; return nullptr; } base::android::ScopedJavaLocalRef<jobject> GetJavaObject() const override { return nullptr; } void CreateTab(TabAndroid* parent, content::WebContents* web_contents) override {} void HandlePopupNavigation(TabAndroid* parent, NavigateParams* params) override {} content::WebContents* CreateNewTabForDevTools(const GURL& url) override { return nullptr; } bool IsSessionRestoreInProgress() const override { return false; } bool IsActiveModel() const override { return false; } TabAndroid* GetTabAt(int index) const override { return nullptr; } void SetActiveIndex(int index) override {} void CloseTabAt(int index) override {} void AddObserver(TabModelObserver* observer) override {} void RemoveObserver(TabModelObserver* observer) override {} private: std::vector<content::WebContents*> web_contents_list_; }; } // namespace class OptimizationGuideTabUrlProviderAndroidTest : public ChromeRenderViewHostTestHarness { public: OptimizationGuideTabUrlProviderAndroidTest() = default; ~OptimizationGuideTabUrlProviderAndroidTest() override = default; void SetUp() override { ChromeRenderViewHostTestHarness::SetUp(); tab_url_provider_ = std::make_unique<OptimizationGuideTabUrlProviderAndroid>(profile()); } void TearDown() override { tab_url_provider_.reset(); ChromeRenderViewHostTestHarness::TearDown(); } OptimizationGuideTabUrlProviderAndroid* tab_url_provider() const { return tab_url_provider_.get(); } std::vector<GURL> GetSortedURLsForTabs( const std::vector<std::vector<FakeTab>>& fake_tabs) { std::vector<OptimizationGuideTabUrlProviderAndroid::TabRepresentation> tabs; for (size_t tab_model_idx = 0; tab_model_idx < fake_tabs.size(); tab_model_idx++) { for (size_t tab_idx = 0; tab_idx < fake_tabs[tab_model_idx].size(); tab_idx++) { OptimizationGuideTabUrlProviderAndroid::TabRepresentation tab; tab.tab_model_index = tab_model_idx; tab.tab_index = tab_idx; std::pair<GURL, absl::optional<base::TimeTicks>> fake_tab = fake_tabs[tab_model_idx][tab_idx]; tab.url = fake_tab.first; tab.last_active_time = fake_tab.second; tabs.push_back(tab); } } tab_url_provider_->SortTabs(&tabs); std::vector<GURL> sorted_urls; sorted_urls.reserve(tabs.size()); for (const auto& tab : tabs) { sorted_urls.push_back(tab.url); } return sorted_urls; } private: std::unique_ptr<OptimizationGuideTabUrlProviderAndroid> tab_url_provider_; }; TEST_F(OptimizationGuideTabUrlProviderAndroidTest, GetUrlsOfActiveTabsNoOpenTabs) { std::vector<GURL> urls = tab_url_provider()->GetUrlsOfActiveTabs(base::Days(90)); EXPECT_TRUE(urls.empty()); } TEST_F(OptimizationGuideTabUrlProviderAndroidTest, GetUrlsOfActiveTabsFiltersOutTabs) { std::unique_ptr<content::WebContents> web_contents = content::WebContentsTester::CreateTestWebContents( browser_context(), content::SiteInstance::Create(browser_context())); content::WebContentsTester* web_contents_tester = content::WebContentsTester::For(web_contents.get()); web_contents_tester->SetLastCommittedURL(GURL("https://example.com/a")); web_contents_tester->SetLastActiveTime(base::TimeTicks::Now() - base::Days(3)); std::unique_ptr<content::WebContents> web_contents2 = content::WebContentsTester::CreateTestWebContents( browser_context(), content::SiteInstance::Create(browser_context())); content::WebContentsTester* web_contents_tester2 = content::WebContentsTester::For(web_contents2.get()); web_contents_tester2->SetLastCommittedURL(GURL("https://example.com/b")); web_contents_tester2->SetLastActiveTime(base::TimeTicks::Now() - base::Days(2)); std::unique_ptr<content::WebContents> stale_web_contents = content::WebContentsTester::CreateTestWebContents( browser_context(), content::SiteInstance::Create(browser_context())); content::WebContentsTester* stale_web_contents_tester = content::WebContentsTester::For(stale_web_contents.get()); stale_web_contents_tester->SetLastActiveTime(base::TimeTicks::Now() - base::Days(100)); stale_web_contents_tester->SetLastCommittedURL(GURL("https://stale.com")); FakeTabModel tab_model(profile(), {web_contents.get(), web_contents2.get(), stale_web_contents.get(), nullptr}); TabModelList::AddTabModel(&tab_model); std::unique_ptr<content::WebContents> otr_web_contents = content::WebContentsTester::CreateTestWebContents( browser_context(), content::SiteInstance::Create(browser_context())); content::WebContentsTester* otr_web_contents_tester = content::WebContentsTester::For(otr_web_contents.get()); otr_web_contents_tester->SetLastCommittedURL(GURL("https://incognito.com")); FakeTabModel otr_tab_model( profile()->GetPrimaryOTRProfile(/*create_if_needed=*/true), {otr_web_contents.get()}); TabModelList::AddTabModel(&otr_tab_model); std::vector<GURL> urls = tab_url_provider()->GetUrlsOfActiveTabs(base::Days(90)); EXPECT_THAT(urls, ElementsAre(GURL("https://example.com/b"), GURL("https://example.com/a"))); } TEST_F(OptimizationGuideTabUrlProviderAndroidTest, SortsTabsCorrectly) { std::vector<std::vector<FakeTab>> fake_tabs; fake_tabs.push_back({ std::make_pair(GURL("https://example.com/third"), base::TimeTicks::Now() - base::Days(3)), std::make_pair(GURL("https://example.com/second"), base::TimeTicks::Now() - base::Days(2)), std::make_pair(GURL("https://example.com/0-2"), absl::nullopt), }); fake_tabs.push_back({ std::make_pair(GURL("https://example.com/first"), base::TimeTicks::Now() - base::Days(1)), std::make_pair(GURL("https://example.com/1-1"), absl::nullopt), }); EXPECT_THAT(GetSortedURLsForTabs(fake_tabs), ElementsAre(GURL("https://example.com/first"), GURL("https://example.com/second"), GURL("https://example.com/third"), GURL("https://example.com/0-2"), GURL("https://example.com/1-1"))); } } // namespace android } // namespace optimization_guide
40.878173
98
0.699615
zealoussnow
8241064a3f5a7dda0e51a9eb5b4445052ec28ea7
13,483
cpp
C++
bftclient/test/bft_client_test.cpp
definitelyNotFBI/utt
1695e3a1f81848e19b042cdc4db9cf1d263c26a9
[ "Apache-2.0" ]
340
2018-08-27T16:30:45.000Z
2022-03-28T14:31:44.000Z
bftclient/test/bft_client_test.cpp
definitelyNotFBI/utt
1695e3a1f81848e19b042cdc4db9cf1d263c26a9
[ "Apache-2.0" ]
706
2018-09-02T17:50:32.000Z
2022-03-31T13:03:15.000Z
bftclient/test/bft_client_test.cpp
glevkovich/concord-bft
a1b7b57472f5375230428d16c613a760b33233fa
[ "Apache-2.0" ]
153
2018-08-29T05:37:25.000Z
2022-03-23T14:08:45.000Z
// Concord // // Copyright (c) 2020 VMware, Inc. All Rights Reserved. // // This product is licensed to you under the Apache 2.0 license (the 'License"). // You may not use this product except in compliance with the Apache 2.0 License. // // This product may include a number of subcomponents with separate copyright // notices and license terms. Your use of these subcomponents is subject to the // terms and conditions of the sub-component's license, as noted in the // LICENSE file. #include "gtest/gtest.h" #include "assertUtils.hpp" #include "bftengine/ClientMsgs.hpp" #include "msg_receiver.h" #include "bftclient/bft_client.h" using namespace bft::client; TEST(msg_receiver_tests, unmatched_replies_returned_no_rsi) { MsgReceiver receiver; receiver.activate(64 * 1024); auto data_len = 20u; std::vector<char> reply(sizeof(bftEngine::ClientReplyMsgHeader) + data_len); // Fill in the header part of the reply auto* header = reinterpret_cast<bftEngine::ClientReplyMsgHeader*>(reply.data()); header->msgType = REPLY_MSG_TYPE; header->currentPrimaryId = 1; header->reqSeqNum = 100; header->replyLength = data_len; header->replicaSpecificInfoLength = 0; // Handle the message auto source = 1; receiver.onNewMessage(source, reply.data(), reply.size()); // Wait to see that the message gets properly unpacked and delivered. auto replies = receiver.wait(1ms); ASSERT_EQ(1, replies.size()); ASSERT_EQ(header->currentPrimaryId, replies[0].metadata.primary->val); ASSERT_EQ(header->reqSeqNum, replies[0].metadata.seq_num); ASSERT_EQ(Msg(data_len), replies[0].data); ASSERT_EQ(1, replies[0].rsi.from.val); ASSERT_EQ(0, replies[0].rsi.data.size()); } TEST(msg_receiver_tests, unmatched_replies_with_rsi) { MsgReceiver receiver; receiver.activate(64 * 1024); auto data_len = 20u; std::vector<char> reply(sizeof(bftEngine::ClientReplyMsgHeader) + data_len); // Fill in the header part of the reply auto* header = reinterpret_cast<bftEngine::ClientReplyMsgHeader*>(reply.data()); header->msgType = REPLY_MSG_TYPE; header->currentPrimaryId = 1; header->reqSeqNum = 100; header->replyLength = data_len; header->replicaSpecificInfoLength = 5; // Handle the message auto source = 1; receiver.onNewMessage(source, reply.data(), reply.size()); // Wait to see that the message gets properly unpacked and delivered. auto replies = receiver.wait(1ms); ASSERT_EQ(1, replies.size()); ASSERT_EQ(header->currentPrimaryId, replies[0].metadata.primary->val); ASSERT_EQ(header->reqSeqNum, replies[0].metadata.seq_num); ASSERT_EQ(Msg(data_len - header->replicaSpecificInfoLength), replies[0].data); ASSERT_EQ(1, replies[0].rsi.from.val); ASSERT_EQ(Msg(header->replicaSpecificInfoLength), replies[0].rsi.data); } TEST(msg_receiver_tests, no_replies_small_msg) { MsgReceiver receiver; receiver.activate(64 * 1024); std::vector<char> reply(sizeof(bftEngine::ClientReplyMsgHeader) - 1); // Handle the message auto source = 1; receiver.onNewMessage(source, reply.data(), reply.size()); // Wait to see that the message gets properly unpacked and delivered. auto replies = receiver.wait(1ms); ASSERT_EQ(0, replies.size()); } TEST(msg_receiver_tests, no_replies_bad_msg_type) { MsgReceiver receiver; receiver.activate(64 * 1024); std::vector<char> reply(sizeof(bftEngine::ClientReplyMsgHeader) + 20); // Fill in the header part of the reply auto* header = reinterpret_cast<bftEngine::ClientReplyMsgHeader*>(reply.data()); header->msgType = REQUEST_MSG_TYPE; // Handle the message auto source = 1; receiver.onNewMessage(source, reply.data(), reply.size()); // Wait to see that the message gets properly unpacked and delivered. auto replies = receiver.wait(1ms); ASSERT_EQ(0, replies.size()); } std::set<ReplicaId> destinations(uint16_t n) { std::set<ReplicaId> replicas; for (uint16_t i = 0; i < n; i++) { replicas.insert(ReplicaId{i}); } return replicas; } std::set<ReplicaId> ro_destinations(uint16_t n, uint16_t start_index) { std::set<ReplicaId> replicas; for (uint16_t i = start_index; i < start_index + n; i++) { replicas.insert(ReplicaId{i}); } return replicas; } std::vector<ReplicaSpecificInfo> create_rsi(uint16_t n) { std::vector<ReplicaSpecificInfo> rsi; for (uint16_t i = 0; i < n; i++) { rsi.push_back(ReplicaSpecificInfo{ReplicaId{i}, {(uint8_t)i}}); } return rsi; } std::vector<UnmatchedReply> unmatched_replies(uint16_t n, const ReplyMetadata& metadata, const Msg& msg, const std::vector<ReplicaSpecificInfo>& rsi) { ConcordAssert(n <= rsi.size()); std::vector<UnmatchedReply> replies; for (uint16_t i = 0; i < n; i++) { replies.emplace_back(UnmatchedReply{metadata, msg, rsi[i]}); } return replies; } TEST(matcher_tests, wait_for_1_out_of_1) { ReplicaId source{1}; uint64_t seq_num = 5; MatchConfig config{MofN{1, {source}}, seq_num}; Matcher matcher(config); Msg msg = {'h', 'e', 'l', 'l', 'o'}; auto rsi = ReplicaSpecificInfo{source, {'r', 's', 'i'}}; ReplicaId primary{1}; UnmatchedReply reply{ReplyMetadata{primary, seq_num}, msg, rsi}; auto match = matcher.onReply(std::move(reply)); ASSERT_TRUE(match.has_value()); ASSERT_EQ(match.value().reply.matched_data, msg); ASSERT_EQ(match.value().reply.rsi[source], rsi.data); ASSERT_EQ(match.value().primary.value(), primary); } TEST(matcher_tests, wait_for_3_out_of_4) { uint64_t seq_num = 5; auto sources = destinations(4); MatchConfig config{MofN{3, sources}, seq_num}; Matcher matcher(config); ReplicaId primary{1}; Msg msg = {'h', 'e', 'l', 'l', 'o'}; auto unmatched = unmatched_replies(4, ReplyMetadata{primary, seq_num}, msg, create_rsi(4)); // The first two replies don't have quorum. So we get back a nullopt; ASSERT_EQ(std::nullopt, matcher.onReply(std::move(unmatched[0]))); ASSERT_EQ(std::nullopt, matcher.onReply(std::move(unmatched[1]))); // The third matching reply should trigger success auto match = matcher.onReply(std::move(unmatched[2])); ASSERT_TRUE(match.has_value()); ASSERT_EQ(match.value().reply.matched_data, msg); ASSERT_EQ(match.value().primary.value(), primary); ASSERT_EQ(3, match.value().reply.rsi.size()); for (auto i = 0u; i < match.value().reply.rsi.size(); i++) { const auto& rsi_data = match.value().reply.rsi[ReplicaId{(uint16_t)i}]; Msg expected{(uint8_t)i}; ASSERT_EQ(expected, rsi_data); } } TEST(matcher_tests, wait_for_3_out_of_4_with_mismatches_and_dupes) { uint64_t seq_num = 5; auto sources = destinations(4); MatchConfig config{MofN{3, sources}, seq_num}; Matcher matcher(config); ReplicaId primary{1}; Msg msg = {'h', 'e', 'l', 'l', 'o'}; auto unmatched = unmatched_replies(4, ReplyMetadata{primary, seq_num}, msg, create_rsi(4)); auto dup = unmatched[1]; auto diff_rsi = dup; diff_rsi.rsi.data = {'x'}; auto bad_seq_num = dup; bad_seq_num.metadata.seq_num = 4; auto non_matching_data = unmatched[3]; non_matching_data.data.push_back('x'); // The first two replies don't have quorum. So we get back a nullopt; ASSERT_EQ(std::nullopt, matcher.onReply(std::move(unmatched[0]))); ASSERT_EQ(std::nullopt, matcher.onReply(std::move(unmatched[1]))); // Inserting a duplicate of the last message doesn't trigger quorum. ASSERT_EQ(std::nullopt, matcher.onReply(std::move(dup))); // Inserting the same message but with different rsi doesn't trigger quorum (it overwrites). ASSERT_EQ(std::nullopt, matcher.onReply(std::move(diff_rsi))); // Inserting the same message but with diff sequence number doesn't trigger quorum ASSERT_EQ(std::nullopt, matcher.onReply(std::move(bad_seq_num))); // Inserting a message from a new replica, but where the data doesn't match doesn't trigger quorum ASSERT_EQ(std::nullopt, matcher.onReply(std::move(non_matching_data))); // Finally, inserting a 3rd match triggers success auto match = matcher.onReply(std::move(unmatched[2])); ASSERT_TRUE(match.has_value()); ASSERT_EQ(match.value().reply.matched_data, msg); ASSERT_EQ(match.value().primary.value(), primary); ASSERT_EQ(3, match.value().reply.rsi.size()); for (auto i = 0u; i < match.value().reply.rsi.size(); i++) { const auto& rsi_data = match.value().reply.rsi[ReplicaId{(uint16_t)i}]; Msg expected{(uint8_t)i}; if (i == 1) { ASSERT_EQ(Msg{'x'}, rsi_data); } else { ASSERT_EQ(expected, rsi_data); } } } TEST(matcher_tests, wait_for_replies_with_ignoring_primary) { auto sources = destinations(3); uint64_t seq_num = 5; MatchConfig config{MofN{4, destinations(4)}, seq_num, false}; Matcher matcher(config); Msg msg = {'h', 'e', 'l', 'l', 'o'}; for (const auto& r : sources) { auto rsi = ReplicaSpecificInfo{r, {'r', 's', 'i'}}; UnmatchedReply reply{ReplyMetadata{r, seq_num}, msg, rsi}; matcher.onReply(std::move(reply)); } auto last_rep = ReplicaId{3}; auto rsi = ReplicaSpecificInfo{last_rep, {'r', 's', 'i'}}; UnmatchedReply reply{ReplyMetadata{last_rep, seq_num}, msg, rsi}; auto match = matcher.onReply(std::move(reply)); ASSERT_TRUE(match.has_value()); ASSERT_EQ(match.value().reply.matched_data, msg); ASSERT_EQ(match.value().reply.rsi[last_rep], rsi.data); ASSERT_FALSE(match.value().primary.has_value()); } TEST(quorum_tests, valid_quorums_without_destinations) { auto all_replicas = destinations(4); // Even that we have ro replicas, empty destinations should include only committers. To issue a request to ro replica // the user should explicity specify them in the quorum auto ro_replicas = ro_destinations(2, 4); uint16_t f_val = 1; uint16_t c_val = 0; QuorumConverter qc(all_replicas, ro_replicas, f_val, c_val); // Quorums without destinations should always work, unless they are MofN. { auto quorum = LinearizableQuorum{}; auto output = qc.toMofN(quorum); ASSERT_EQ(3, output.wait_for); ASSERT_EQ(all_replicas, output.destinations); } { auto quorum = ByzantineSafeQuorum{}; auto output = qc.toMofN(quorum); ASSERT_EQ(2, output.wait_for); ASSERT_EQ(all_replicas, output.destinations); } { auto quorum = All{}; auto output = qc.toMofN(quorum); ASSERT_EQ(4, output.wait_for); ASSERT_EQ(all_replicas, output.destinations); } // MofN Quorums must have destinations { auto quorum = MofN{}; ASSERT_THROW(qc.toMofN(quorum), InvalidDestinationException); } } TEST(quorum_tests, valid_quorums_with_destinations) { auto all_replicas = destinations(4); auto ro_replicas = ro_destinations(2, 4); uint16_t f_val = 1; uint16_t c_val = 0; QuorumConverter qc(all_replicas, ro_replicas, f_val, c_val); { auto quorum = LinearizableQuorum{destinations(3)}; auto output = qc.toMofN(quorum); ASSERT_EQ(3, output.wait_for); ASSERT_EQ(destinations(3), output.destinations); } { auto quorum = ByzantineSafeQuorum{destinations(2)}; auto output = qc.toMofN(quorum); ASSERT_EQ(2, output.wait_for); ASSERT_EQ(destinations(2), output.destinations); } { // Test a quorum with ro replicas auto quorum = All{all_replicas}; quorum.destinations.insert(ro_replicas.begin(), ro_replicas.end()); auto output = qc.toMofN(quorum); ASSERT_EQ(6, output.wait_for); ASSERT_EQ(quorum.destinations, output.destinations); } { auto quorum = All{destinations(1)}; auto output = qc.toMofN(quorum); ASSERT_EQ(1, output.wait_for); ASSERT_EQ(destinations(1), output.destinations); } { auto quorum = MofN{2, destinations(3)}; auto output = qc.toMofN(quorum); ASSERT_EQ(2, output.wait_for); ASSERT_EQ(destinations(3), output.destinations); } } TEST(quorum_tests, invalid_destinations) { auto all_replicas = destinations(4); auto ro_replicas = ro_destinations(2, 4); uint16_t f_val = 1; uint16_t c_val = 0; QuorumConverter qc(all_replicas, ro_replicas, f_val, c_val); auto invalid_replicas = destinations(2); invalid_replicas.insert(ReplicaId{7}); { auto quorum = LinearizableQuorum{invalid_replicas}; ASSERT_THROW(qc.toMofN(quorum), InvalidDestinationException); } { auto quorum = ByzantineSafeQuorum{invalid_replicas}; ASSERT_THROW(qc.toMofN(quorum), InvalidDestinationException); } { auto quorum = All{invalid_replicas}; ASSERT_THROW(qc.toMofN(quorum), InvalidDestinationException); } { auto quorum = MofN{1, invalid_replicas}; ASSERT_THROW(qc.toMofN(quorum), InvalidDestinationException); } } TEST(quorum_tests, bad_quorum_configs) { auto all_replicas = destinations(4); uint16_t f_val = 1; uint16_t c_val = 0; QuorumConverter qc(all_replicas, {}, f_val, c_val); { // Destinations is less than 2F + C + 1 auto quorum = LinearizableQuorum{destinations(2)}; ASSERT_THROW(qc.toMofN(quorum), BadQuorumConfigException); } { // Destinations is less than F + 1 auto quorum = ByzantineSafeQuorum{destinations(1)}; ASSERT_THROW(qc.toMofN(quorum), BadQuorumConfigException); } { // wait_for > destinations.size() auto wait_for = 3u; auto quorum = MofN{wait_for, destinations(1)}; ASSERT_THROW(qc.toMofN(quorum), BadQuorumConfigException); } } int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
33.046569
119
0.701921
definitelyNotFBI
8241cba0d258a27076a85a09fb31795eaae60bd6
3,995
hpp
C++
tlx/thread_barrier_spin.hpp
mullovc/tlx
e7c17b5981cbd7912b689fa0ad993e18424e26fe
[ "BSL-1.0" ]
284
2017-02-26T08:49:15.000Z
2022-03-30T21:55:37.000Z
tlx/thread_barrier_spin.hpp
xiao2mo/tlx
b311126e670753897c1defceeaa75c83d2d9531a
[ "BSL-1.0" ]
24
2017-09-05T21:02:41.000Z
2022-03-07T10:09:59.000Z
tlx/thread_barrier_spin.hpp
xiao2mo/tlx
b311126e670753897c1defceeaa75c83d2d9531a
[ "BSL-1.0" ]
62
2017-02-23T12:29:27.000Z
2022-03-31T07:45:59.000Z
/******************************************************************************* * tlx/thread_barrier_spin.hpp * * Part of tlx - http://panthema.net/tlx * * Copyright (C) 2015-2019 Timo Bingmann <tb@panthema.net> * * All rights reserved. Published under the Boost Software License, Version 1.0 ******************************************************************************/ #ifndef TLX_THREAD_BARRIER_SPIN_HEADER #define TLX_THREAD_BARRIER_SPIN_HEADER #include <tlx/meta/no_operation.hpp> #include <atomic> #include <thread> namespace tlx { /*! * Implements a thread barrier using atomics and a spin lock that can be used to * synchronize threads. * * This ThreadBarrier implementation was a lot faster in tests than * ThreadBarrierMutex, but ThreadSanitizer shows data races (probably due to the * generation counter). */ class ThreadBarrierSpin { public: /*! * Creates a new barrier that waits for n threads. */ explicit ThreadBarrierSpin(size_t thread_count) : thread_count_(thread_count - 1) { } /*! * Waits for n threads to arrive. When they have arrive, execute lambda on * the one thread, which arrived last. After lambda, step the generation * counter. * * This method blocks and returns as soon as n threads are waiting inside * the method. */ template <typename Lambda = NoOperation<void> > void wait(Lambda lambda = Lambda()) { // get synchronization generation step counter. size_t this_step = step_.load(std::memory_order_acquire); if (waiting_.fetch_add(1, std::memory_order_acq_rel) == thread_count_) { // we are the last thread to wait() -> reset and increment step. waiting_.store(0, std::memory_order_release); // step other generation counters. lambda(); // the following statement releases all threads from busy waiting. step_.fetch_add(1, std::memory_order_acq_rel); } else { // spin lock awaiting the last thread to increment the step counter. while (step_.load(std::memory_order_acquire) == this_step) { // busy spinning loop } } } /*! * Waits for n threads to arrive, yield thread while spinning. When they * have arrive, execute lambda on the one thread, which arrived last. After * lambda, step the generation counter. * * This method blocks and returns as soon as n threads are waiting inside * the method. */ template <typename Lambda = NoOperation<void> > void wait_yield(Lambda lambda = Lambda()) { // get synchronization generation step counter. size_t this_step = step_.load(std::memory_order_acquire); if (waiting_.fetch_add(1, std::memory_order_acq_rel) == thread_count_) { // we are the last thread to wait() -> reset and increment step. waiting_.store(0, std::memory_order_release); // step other generation counters. lambda(); // the following statement releases all threads from busy waiting. step_.fetch_add(1, std::memory_order_acq_rel); } else { // spin lock awaiting the last thread to increment the step counter. while (step_.load(std::memory_order_acquire) == this_step) { std::this_thread::yield(); } } } //! Return generation step counter size_t step() const { return step_.load(std::memory_order_acquire); } protected: //! number of threads, minus one due to comparison needed in loop const size_t thread_count_; //! number of threads in spin lock std::atomic<size_t> waiting_ { 0 }; //! barrier synchronization generation std::atomic<size_t> step_ { 0 }; }; } // namespace tlx #endif // !TLX_THREAD_BARRIER_SPIN_HEADER /******************************************************************************/
34.145299
80
0.609262
mullovc
824371cda611fe93cf77a99f7ec01745a6c3883b
1,982
cpp
C++
Engine/Source/Runtime/XmlParser/Private/XmlNode.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Runtime/XmlParser/Private/XmlNode.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Runtime/XmlParser/Private/XmlNode.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "XmlNode.h" const FString& FXmlAttribute::GetTag() const { return Tag; } const FString& FXmlAttribute::GetValue() const { return Value; } void FXmlNode::Delete() { const int32 ChildCount = Children.Num(); for(int32 ChildIndex = 0; ChildIndex < ChildCount; ++ChildIndex) { check(Children[ChildIndex] != nullptr); Children[ChildIndex]->Delete(); delete Children[ChildIndex]; } Children.Empty(); } const FXmlNode* FXmlNode::GetNextNode() const { return NextNode; } const TArray<FXmlNode*>& FXmlNode::GetChildrenNodes() const { return Children; } const FXmlNode* FXmlNode::GetFirstChildNode() const { if(Children.Num() > 0) { return Children[0]; } else { return nullptr; } } const FXmlNode* FXmlNode::FindChildNode(const FString& InTag) const { const int32 ChildCount = Children.Num(); for(int32 ChildIndex = 0; ChildIndex < ChildCount; ++ChildIndex) { if(Children[ChildIndex] != nullptr && Children[ChildIndex]->GetTag() == InTag) { return Children[ChildIndex]; } } return nullptr; } FXmlNode* FXmlNode::FindChildNode(const FString& InTag) { return const_cast<FXmlNode*>(const_cast<const FXmlNode*>(this)->FindChildNode(InTag)); } const FString& FXmlNode::GetTag() const { return Tag; } const FString& FXmlNode::GetContent() const { return Content; } void FXmlNode::SetContent( const FString& InContent ) { Content = InContent; } FString FXmlNode::GetAttribute(const FString& InTag) const { for(auto Iter(Attributes.CreateConstIterator()); Iter; Iter++) { if(Iter->GetTag() == InTag) { return Iter->GetValue(); } } return FString(); } void FXmlNode::AppendChildNode(const FString& InTag, const FString& InContent) { auto NewNode = new FXmlNode; NewNode->Tag = InTag; NewNode->Content = InContent; auto NumChildren = Children.Num(); if (NumChildren != 0) { Children[NumChildren - 1]->NextNode = NewNode; } Children.Push(NewNode); }
18.018182
87
0.706862
windystrife
82450868873c8ef8d2b6bbbe2e481dc5b7857c12
1,530
hxx
C++
include/jsservice.hxx
ostosh/jsbinder
fa75fe5ff31501ca1513a8a77e851c437978e26d
[ "BSD-3-Clause" ]
7
2015-04-29T20:38:59.000Z
2021-06-02T11:47:37.000Z
include/jsservice.hxx
ostosh/jsbinder
fa75fe5ff31501ca1513a8a77e851c437978e26d
[ "BSD-3-Clause" ]
null
null
null
include/jsservice.hxx
ostosh/jsbinder
fa75fe5ff31501ca1513a8a77e851c437978e26d
[ "BSD-3-Clause" ]
2
2016-02-02T07:13:45.000Z
2020-10-18T21:39:15.000Z
/* * Copyright (C) 2015,2017 Opersys 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. */ #ifndef _JSSERVICE_HXX #define _JSSERVICE_HXX #include <nan.h> #include <binder/Parcel.h> using namespace android; class JsService : public Nan::ObjectWrap { public: static NAN_MODULE_INIT(Init); void setService(sp<IBinder> sv) { assert(sv != 0); this->sv = sv; } private: friend class JsServiceManager; static Nan::Persistent<v8::Function> & constructor() { static Nan::Persistent<v8::Function> jsServiceConstructor; return jsServiceConstructor; } static NAN_METHOD(New); static NAN_METHOD(Ping); static NAN_METHOD(Transact); static NAN_METHOD(GetInterface); static NAN_METHOD(Dump); // The memory that is reserved for dumpMem calls on the service. const int dumpAreaSize = 4096000; void *dumpArea; int dumpFd; sp<IBinder> sv; explicit JsService(); ~JsService(); }; #endif // _JSSERVICE_HXX
25.5
75
0.690196
ostosh
824807aa61de45279699d54000a67066639c10e8
1,404
cpp
C++
test/example/custom_identifier.cpp
lambdaxymox/entt
0b3e3fd19adbb8b56b92908493559a7eda7ce644
[ "MIT" ]
null
null
null
test/example/custom_identifier.cpp
lambdaxymox/entt
0b3e3fd19adbb8b56b92908493559a7eda7ce644
[ "MIT" ]
null
null
null
test/example/custom_identifier.cpp
lambdaxymox/entt
0b3e3fd19adbb8b56b92908493559a7eda7ce644
[ "MIT" ]
null
null
null
#include <type_traits> #include <gtest/gtest.h> #include <entt/entity/entity.hpp> #include <entt/entity/registry.hpp> struct entity_id { using entity_type = typename entt::entt_traits<entt::entity>::entity_type; static constexpr auto null = entt::null; constexpr entity_id(entity_type value = null) : entt{value} {} constexpr entity_id(const entity_id &other) : entt{other.entt} {} constexpr operator entity_type() const { return entt; } private: entity_type entt; }; template<> struct entt::entt_traits<entity_id>: entt::entt_traits<entt::entity> {}; TEST(Example, CustomIdentifier) { entt::basic_registry<entity_id> registry{}; entity_id entity{}; ASSERT_FALSE(registry.valid(entity)); ASSERT_TRUE(entity == entt::null); entity = registry.create(); ASSERT_TRUE(registry.valid(entity)); ASSERT_TRUE(entity != entt::null); ASSERT_FALSE((registry.all_of<int, char>(entity))); ASSERT_EQ(registry.try_get<int>(entity), nullptr); registry.emplace<int>(entity, 42); ASSERT_TRUE((registry.any_of<int, char>(entity))); ASSERT_EQ(registry.get<int>(entity), 42); registry.destroy(entity); ASSERT_FALSE(registry.valid(entity)); ASSERT_TRUE(entity != entt::null); entity = registry.create(); ASSERT_TRUE(registry.valid(entity)); ASSERT_TRUE(entity != entt::null); }
23.79661
78
0.680199
lambdaxymox
824afca41ba01026ae5a840d80d20113822a46ed
300
cpp
C++
deep_ptr_test.cpp
jbcoe/deep_ptr
ba76ed1d64dc47edd23020441c165a579734c638
[ "MIT" ]
2
2021-03-19T17:42:04.000Z
2021-03-19T18:10:42.000Z
deep_ptr_test.cpp
jbcoe/deep_ptr
ba76ed1d64dc47edd23020441c165a579734c638
[ "MIT" ]
19
2016-01-10T23:01:30.000Z
2020-03-05T10:54:06.000Z
deep_ptr_test.cpp
jbcoe/deep_ptr
ba76ed1d64dc47edd23020441c165a579734c638
[ "MIT" ]
2
2020-02-28T23:42:41.000Z
2021-03-19T17:42:05.000Z
#define CATCH_CONFIG_MAIN #include <catch2/catch.hpp> #include "deep_ptr.h" using namespace jbcoe; TEST_CASE("Ensure that deep_ptr default construction produces a default initialised deep_ptr", "[deep_ptr.constructor]") { deep_ptr<int> instance; REQUIRE(instance.operator->() == nullptr); }
27.272727
120
0.76
jbcoe
82502b5efb095f696d705a99b0e69570d2a5f736
5,604
cpp
C++
src/main/cpp/Commands/AutoSlalom.cpp
1828Boxerbots/AllRobotsInOneCode
95814c320517ff3cc53cade380c25bca4a3b1914
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/Commands/AutoSlalom.cpp
1828Boxerbots/AllRobotsInOneCode
95814c320517ff3cc53cade380c25bca4a3b1914
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/Commands/AutoSlalom.cpp
1828Boxerbots/AllRobotsInOneCode
95814c320517ff3cc53cade380c25bca4a3b1914
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #include "Commands/AutoSlalom.h" AutoSlalom::AutoSlalom(DriveTrainSubsystemBase *pDrive) { // Use Requires() here to declare subsystem dependencies // eg. Requires(Robot::chassis.get()); m_pDrive = pDrive; AddRequirements(pDrive); //bruh } // Called just before this Command runs the first time void AutoSlalom::Initialize() { timer.Start(); m_pDrive->SetLookingColorV(OldCameraVision::GREEN_CONE_A); } // Called repeatedly when this Command is scheduled to run void AutoSlalom::Execute() { if (m_pDrive != nullptr) { /* SwitchColor(DriveTrainSubsystemBase::BROWN); loop1(); loop2(); loop3(); SwitchColor(DriveTrainSubsystemBase::BLUE); loop4(); loop5(); loop6(); */ /* if (m_loopsUpdate != 0) { m_state++; m_loopsUpdate = 0; //m_result = 0; } */ //Color 1 is Green //Color 2 is Red Util::Log("Auto2021 State", m_state); m_result = m_pDrive->WhereToTurn(m_center, 25); switch (m_state) { case 0: loop0(); break; /* case 1: m_pDrive->SetLookingColorV(OldCameraVision::GREEN_CONE_N); loop1(); break; case 2: loop2(); break; case 3: loop3(); break; case 4: loop4(); break; case 5: m_pDrive->SetLookingColorV(OldCameraVision::PURPLE_BOTTLE_N); loop5(); break; case 6: loop6(); break; */ default: m_pDrive->Stop(); break; } } } bool AutoSlalom::IsFinished() { if (m_IsFinished) { Util::Log("Auto2021 Finished", "IsFinished = true"); m_pDrive->Stop(); } else { Util::Log("Auto2021 Finished", "IsFinished = false"); } return m_IsFinished; } void AutoSlalom::loop0() { //Forward, left, forward, right m_pDrive->TimedArcade(0.6, -0.2, 1.15); m_pDrive->TimedArcade(0.6, 0.2, 1.17); //Move the 10 feet or so m_pDrive->ForwardInInch(107, 0, 0.8); //Loop around the cone m_pDrive->TimedArcade(0.6, 0.2, 1.20); m_pDrive->TimedArcade(0.6, -0.24, 3.8); //Go back the 10 feet ///m_pDrive->TurnInDegreesGyro(90, 0); m_pDrive->TimedArcade(0.6, 0.2, 1.3); m_pDrive->ForwardInInch(95, 0, 0.8); //Go back around the initial cone ///m_pDrive->ForwardInInch(45, 0, 0.3); ///m_pDrive->TurnInDegreesGyro(-90, 0.4); ///m_pDrive->ForwardInInch(45, 0, 0.3); ///m_pDrive->TurnInDegreesGyro(90, 0.4); m_pDrive->TimedArcade(0.6, 0.2, 1.3); m_pDrive->TimedArcade(0.6, -0.24, 1.0); m_pDrive->ForwardInInch(10,0,0.5); //Move forward a little bit //No state check because this function is shared by other cases //m_pDrive->ForwardInSeconds(0.25, 0.5); //m_state = 1; m_IsFinished = true; } void AutoSlalom::loop1() { //Rotate until Color1 on right side m_center = 0.50; if (m_state != 1) //Return if state is not 1 { return; } double direction; if (m_result < -2.0 || m_result < 0.0) //If I can't see the cone or it is on the left side of the center { Util::Log("Auto2021 S1 State", "Turning Left"); direction = -0.2; } else if (m_result > 0.0) //If the cone is on the right side of the center { Util::Log("Auto2021 S1 State", "Turning Right"); direction = 0.2; } else //If cone is in the center { direction = 0.0; m_state = 2; //Increment state } //m_pDrive->MoveTank(direction, -direction); m_pDrive->MoveArcade(0, direction); //Move } void AutoSlalom::loop2() { //Move forward until I can't see color1 m_center = 0.0; //Center is in the center double speed = 0.0; if (m_state != 2) //Return if state is not 2 { return; } if (m_result > -3) //If I see the cone { if (m_result > 0) //If cone is on the right { speed = -0.2; } else if (m_result < 0) //If cone is on the left { speed = 0.2; } } else //If I don't see the cone { m_state = 3; //Increment state } m_pDrive->MoveArcade(0.2, speed); //Move } void AutoSlalom::loop3() { //Move forward a little bit //No state check because this function is shared by other cases m_pDrive->ForwardInInch(49, 0, 0.2); m_state = 4; } void AutoSlalom::loop4() { //Rotate Right until color1 is on the right side m_center = 0.50; if (m_state != 4) { return; } double direction; if (m_result < -2.0 || m_result < 0.0) { direction = -0.2; } else { direction = 0.0; m_state = 5; } m_pDrive->MoveArcade(0, direction); } void AutoSlalom::loop5() { //Rotate until Color2 on left side m_center = -0.75; //left side if (m_state != 5) { return; } double direction; if(m_result < -2.0 || m_result < 0.0) { direction = -0.2; } else if (m_result > 0.0) { direction = 0.2; } else { direction = 0.0; m_state = 6; } m_pDrive->MoveArcade(0, direction); } void AutoSlalom::loop6() { //Move forward until I can't see color2 m_center = 0.0; //Center is in the center double speed = 0.0; if (m_state != 6) //Return if state is not 2 { return; } if (m_result > -3) //If I see the cone { if (m_result > 0) //If cone is on the right { speed = -0.2; } else if (m_result < 0) //If cone is on the left { speed = 0.2; } } else //If I don't see the cone { m_state = 3; //Increment state } m_pDrive->MoveArcade(0.2, speed); //Move }
19.257732
106
0.601713
1828Boxerbots
82514f2c72fa441a8101d2c52b132f4a07918596
6,737
cpp
C++
Engine/Source/GameBase/src/PhysicsSystem.cpp
AnkurSheel/RoutePlanner
a50b6ccb735db42ff4e5b2f4c87e710819c4564b
[ "CC-BY-4.0" ]
null
null
null
Engine/Source/GameBase/src/PhysicsSystem.cpp
AnkurSheel/RoutePlanner
a50b6ccb735db42ff4e5b2f4c87e710819c4564b
[ "CC-BY-4.0" ]
null
null
null
Engine/Source/GameBase/src/PhysicsSystem.cpp
AnkurSheel/RoutePlanner
a50b6ccb735db42ff4e5b2f4c87e710819c4564b
[ "CC-BY-4.0" ]
null
null
null
#include "stdafx.h" #include "PhysicsSystem.h" #include "EntityManager.hxx" #include "PhysicsComponent.h" #include "TransformComponent.h" #include "physics.hxx" #include "EventManager.hxx" #include "EntityInitializedEventData.h" #include "EntityScaledEventData.h" #include "BaseEntity.hxx" using namespace GameBase; using namespace Utilities; using namespace Base; using namespace Physics; const cHashedString cPhysicsSystem::m_Type = cHashedString("physicssystem"); // ******************************************************************************************************************* cPhysicsSystem::cPhysicsSystem() { VInitialize(); } // ******************************************************************************************************************* cPhysicsSystem::~cPhysicsSystem() { m_pPhysics.reset(); m_pEntityManager.reset(); shared_ptr<IEventManager> pEventManager = MakeStrongPtr(cServiceLocator::GetInstance()->GetService<IEventManager>()); if (pEventManager != NULL) { EventListenerCallBackFn listener = bind(&cPhysicsSystem::ActorInitializedListener, this, _1); pEventManager->VRemoveListener(listener, cEntityInitializedEventData::m_Name); listener = bind(&cPhysicsSystem::ActorScaledListener, this, _1); pEventManager->VRemoveListener(listener, cEntityScaledEventData::m_Name); } } // ******************************************************************************************************************* void cPhysicsSystem::VInitialize() { cProcess::VInitialize(); shared_ptr<IEventManager> pEventManager = MakeStrongPtr(cServiceLocator::GetInstance()->GetService<IEventManager>()); if (pEventManager != NULL) { EventListenerCallBackFn listener = bind(&cPhysicsSystem::ActorInitializedListener, this, _1); pEventManager->VAddListener(listener, cEntityInitializedEventData::m_Name); listener = bind(&cPhysicsSystem::ActorScaledListener, this, _1); pEventManager->VAddListener(listener, cEntityScaledEventData::m_Name); } m_pEntityManager = cServiceLocator::GetInstance()->GetService<IEntityManager>(); m_pPhysics = (MakeStrongPtr<IPhysics>(cServiceLocator::GetInstance()->GetService<IPhysics>())); if(m_pPhysics != NULL) { m_pPhysics->VInitialize("Physics"); } } // ******************************************************************************************************************* void cPhysicsSystem::VUpdate(const float deltaTime) { cProcess::VUpdate(deltaTime); shared_ptr<IEntityManager> pEntityManager = MakeStrongPtr(m_pEntityManager); if (pEntityManager == NULL) { return; } IEntityManager::EntityList entityList; pEntityManager->VGetEntitiesWithComponent(cPhysicsComponent::GetName(), entityList); for(auto enityIter = entityList.begin(); enityIter != entityList.end(); enityIter++) { IBaseEntity * pEntity = *enityIter; cPhysicsComponent* pPhysicsComponent = CastToPhysicsComponent(pEntity); if (pPhysicsComponent != NULL) { pPhysicsComponent->Update((int)(deltaTime * 10000)); } } if(m_pPhysics != NULL) { m_pPhysics->VUpdate(deltaTime); } for(auto enityIter = entityList.begin(); enityIter != entityList.end(); enityIter++) { IBaseEntity * pEntity = *enityIter; cTransformComponent * pTransformComponent = dynamic_cast<cTransformComponent*>(pEntityManager->VGetComponent(pEntity, cTransformComponent::GetName())); cPhysicsComponent * pPhysicsComponent = CastToPhysicsComponent(pEntity); if (pTransformComponent != NULL && pPhysicsComponent != NULL) { pTransformComponent->SetPosition(pPhysicsComponent->GetPosition()); } } CollisionPairs triggerpairs; if(m_pPhysics != NULL) { triggerpairs = m_pPhysics->VGetTriggerPairs(); } for(auto Iter = triggerpairs.begin(); Iter != triggerpairs.end(); Iter++) { const CollisionPair pair = *Iter; IBaseEntity * pEntity = pEntityManager->VGetEntityFromID(pair.first); IBaseEntity * pTrigger = pEntityManager->VGetEntityFromID(pair.second); if(pEntity != NULL && pTrigger != NULL) { pEntity->VOnEnteredTrigger(pTrigger); } } CollisionPairs collisionpairs; if(m_pPhysics != NULL) { collisionpairs = m_pPhysics->VGetCollisionPairs(); } for(auto Iter = collisionpairs.begin(); Iter != collisionpairs.end(); Iter++) { const CollisionPair pair = *Iter; IBaseEntity * pEntity1 = pEntityManager->VGetEntityFromID(pair.first); IBaseEntity * pEntity2 = pEntityManager->VGetEntityFromID(pair.second); if(pEntity1 != NULL && pEntity2 != NULL) { pEntity1->VOnCollided(pEntity2); pEntity2->VOnCollided(pEntity1); } } } // ******************************************************************************************************************* void cPhysicsSystem::ActorInitializedListener(IEventDataPtr pEventData) { shared_ptr<IEntityManager> pEntityManager = MakeStrongPtr(m_pEntityManager); if (pEntityManager == NULL) { return; } shared_ptr<cEntityInitializedEventData> pCastEventData = static_pointer_cast<cEntityInitializedEventData>(pEventData); int id = pCastEventData->GetActorID(); IBaseEntity * pEntity = pEntityManager->VGetEntityFromID(id); cPhysicsComponent * pPhysicsComponent = CastToPhysicsComponent(pEntity); if(pPhysicsComponent != NULL) { if(pCastEventData->IsReInitializing()) { pPhysicsComponent->ReInitialize(pCastEventData->GetPosition(), pCastEventData->GetRotation(), pCastEventData->GetSize()); } else { pPhysicsComponent->Initialize(pCastEventData->GetPosition(), pCastEventData->GetRotation(), pCastEventData->GetSize()); } } } // ******************************************************************************************************************* void cPhysicsSystem::ActorScaledListener(IEventDataPtr pEventData) { shared_ptr<IEntityManager> pEntityManager = MakeStrongPtr(m_pEntityManager); if (pEntityManager == NULL) { return; } shared_ptr<cEntityScaledEventData> pCastEventData = static_pointer_cast<cEntityScaledEventData>(pEventData); int id = pCastEventData->GetActorID(); cVector3 size = pCastEventData->GetSize(); IBaseEntity * pEntity = pEntityManager->VGetEntityFromID(id); if(pEntity != NULL) { cPhysicsComponent * pPhysicsComponent = CastToPhysicsComponent(pEntity); if(pPhysicsComponent != NULL) { pPhysicsComponent->OnSizeUpdated(); } } } // ******************************************************************************************************************* cPhysicsComponent* const GameBase::cPhysicsSystem::CastToPhysicsComponent(const IBaseEntity * const pEntity) { shared_ptr<IEntityManager> pEntityManager = MakeStrongPtr(m_pEntityManager); if (pEntityManager == NULL) { return NULL; } return (dynamic_cast<cPhysicsComponent*>(pEntityManager->VGetComponent(pEntity, cPhysicsComponent::GetName()))); }
32.545894
153
0.669586
AnkurSheel
825528b594bc12591413bcd8e9dc92c68f6b3c3d
3,742
cc
C++
cpp/src/precompiled/epoch_time_point_test.cc
ZMZ91/gandiva
6f11d4ef79b38074151e3107d46477f45ed21d11
[ "Apache-2.0" ]
479
2018-06-21T18:28:52.000Z
2022-03-12T07:55:56.000Z
cpp/src/precompiled/epoch_time_point_test.cc
ZMZ91/gandiva
6f11d4ef79b38074151e3107d46477f45ed21d11
[ "Apache-2.0" ]
11
2018-06-22T06:01:47.000Z
2018-10-01T11:56:24.000Z
cpp/src/precompiled/epoch_time_point_test.cc
ZMZ91/gandiva
6f11d4ef79b38074151e3107d46477f45ed21d11
[ "Apache-2.0" ]
65
2018-06-22T06:05:30.000Z
2022-02-08T22:39:13.000Z
// Copyright (C) 2017-2018 Dremio Corporation // // 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 <time.h> #include <gtest/gtest.h> #include "./epoch_time_point.h" #include "precompiled/types.h" namespace gandiva { timestamp StringToTimestamp(const char *buf) { struct tm tm; strptime(buf, "%Y-%m-%d %H:%M:%S", &tm); return timegm(&tm) * 1000; // to millis } TEST(TestEpochTimePoint, TestTm) { auto ts = StringToTimestamp("2015-05-07 10:20:34"); EpochTimePoint tp(ts); struct tm tm; time_t tsec = ts / 1000; gmtime_r(&tsec, &tm); EXPECT_EQ(tp.TmYear(), tm.tm_year); EXPECT_EQ(tp.TmMon(), tm.tm_mon); EXPECT_EQ(tp.TmYday(), tm.tm_yday); EXPECT_EQ(tp.TmMday(), tm.tm_mday); EXPECT_EQ(tp.TmWday(), tm.tm_wday); EXPECT_EQ(tp.TmHour(), tm.tm_hour); EXPECT_EQ(tp.TmMin(), tm.tm_min); EXPECT_EQ(tp.TmSec(), tm.tm_sec); } TEST(TestEpochTimePoint, TestAddYears) { EXPECT_EQ(EpochTimePoint(StringToTimestamp("2015-05-05 10:20:34")).AddYears(2), EpochTimePoint(StringToTimestamp("2017-05-05 10:20:34"))); EXPECT_EQ(EpochTimePoint(StringToTimestamp("2015-05-05 10:20:34")).AddYears(0), EpochTimePoint(StringToTimestamp("2015-05-05 10:20:34"))); EXPECT_EQ(EpochTimePoint(StringToTimestamp("2015-05-05 10:20:34")).AddYears(-1), EpochTimePoint(StringToTimestamp("2014-05-05 10:20:34"))); } TEST(TestEpochTimePoint, TestAddMonths) { EXPECT_EQ(EpochTimePoint(StringToTimestamp("2015-05-05 10:20:34")).AddMonths(2), EpochTimePoint(StringToTimestamp("2015-07-05 10:20:34"))); EXPECT_EQ(EpochTimePoint(StringToTimestamp("2015-05-05 10:20:34")).AddMonths(11), EpochTimePoint(StringToTimestamp("2016-04-05 10:20:34"))); EXPECT_EQ(EpochTimePoint(StringToTimestamp("2015-05-05 10:20:34")).AddMonths(0), EpochTimePoint(StringToTimestamp("2015-05-05 10:20:34"))); EXPECT_EQ(EpochTimePoint(StringToTimestamp("2015-05-05 10:20:34")).AddMonths(-1), EpochTimePoint(StringToTimestamp("2015-04-05 10:20:34"))); EXPECT_EQ(EpochTimePoint(StringToTimestamp("2015-05-05 10:20:34")).AddMonths(-10), EpochTimePoint(StringToTimestamp("2014-07-05 10:20:34"))); } TEST(TestEpochTimePoint, TestAddDays) { EXPECT_EQ(EpochTimePoint(StringToTimestamp("2015-05-05 10:20:34")).AddDays(2), EpochTimePoint(StringToTimestamp("2015-05-07 10:20:34"))); EXPECT_EQ(EpochTimePoint(StringToTimestamp("2015-05-05 10:20:34")).AddDays(11), EpochTimePoint(StringToTimestamp("2015-05-16 10:20:34"))); EXPECT_EQ(EpochTimePoint(StringToTimestamp("2015-05-05 10:20:34")).AddDays(0), EpochTimePoint(StringToTimestamp("2015-05-05 10:20:34"))); EXPECT_EQ(EpochTimePoint(StringToTimestamp("2015-05-05 10:20:34")).AddDays(-1), EpochTimePoint(StringToTimestamp("2015-05-04 10:20:34"))); EXPECT_EQ(EpochTimePoint(StringToTimestamp("2015-05-05 10:20:34")).AddDays(-10), EpochTimePoint(StringToTimestamp("2015-04-25 10:20:34"))); } TEST(TestEpochTimePoint, TestClearTimeOfDay) { EXPECT_EQ(EpochTimePoint(StringToTimestamp("2015-05-05 10:20:34")).ClearTimeOfDay(), EpochTimePoint(StringToTimestamp("2015-05-05 00:00:00"))); } } // namespace gandiva
38.183673
86
0.70604
ZMZ91
82567b36f40b6c056828f7aaa27de5c3a6d187a0
514
cpp
C++
Cpp_Q03.cpp
Samad-Cyber01/CPP_Practical_Project
4f5107b343e2b144e59f90a0bd859d53c65a9b17
[ "Unlicense" ]
null
null
null
Cpp_Q03.cpp
Samad-Cyber01/CPP_Practical_Project
4f5107b343e2b144e59f90a0bd859d53c65a9b17
[ "Unlicense" ]
null
null
null
Cpp_Q03.cpp
Samad-Cyber01/CPP_Practical_Project
4f5107b343e2b144e59f90a0bd859d53c65a9b17
[ "Unlicense" ]
null
null
null
#include <iostream> #include <string> #include <algorithm> using namespace std; int main(int argc, char *argv[]) { string s = ""; for (int i = 1; i < argc; i++) { s += argv[i]; } cout << s << endl; int freq[26] = {0}; // because we have 26 alphabets. for (int i = 0; i < s.size(); i++) { freq[s[i] - 'a']++; } for (int i = 0; i < 26; i++) { cout << char(i + 'a') << ", " << freq[i] << endl; } return 0; }
17.724138
58
0.414397
Samad-Cyber01
8257da4d1c96b8d8cd36cb5c1d094df49cab0ce8
1,437
hpp
C++
libtest/src/test_ntcsensor.hpp
rvt/bbq-controller
6ff1591b238e180dc0431a5829a9f0f6eaa7c08d
[ "MIT" ]
13
2019-02-26T20:14:32.000Z
2022-01-12T23:54:00.000Z
libtest/src/test_ntcsensor.hpp
rvt/bbq-controller
6ff1591b238e180dc0431a5829a9f0f6eaa7c08d
[ "MIT" ]
null
null
null
libtest/src/test_ntcsensor.hpp
rvt/bbq-controller
6ff1591b238e180dc0431a5829a9f0f6eaa7c08d
[ "MIT" ]
2
2021-09-21T22:44:06.000Z
2022-03-11T01:08:50.000Z
#include <catch2/catch.hpp> #include "arduinostubs.hpp" #include <memory> #include <NTCSensor.h> #include <array> TEST_CASE("Should Calculate steinHartValues", "[ntcsensor]") { float r, r1, r2, r3, t1, t2, t3, ka, kb, kc; r = 10000; r1 = 25415; t1 = 5; r2 = 10021; t2 = 25; r3 = 6545; t3 = 35; NTCSensor::calculateSteinhart(r, r1, t1, r2, t2, r3, t3, ka, kb, kc); REQUIRE(ka == Approx(0.00113836653)); REQUIRE(kb == Approx(0.000232453211)); REQUIRE(kc == Approx(0.0000000948887404)); SECTION("Should measure temperature upstream") { NTCSensor sensor(0, true, 0.0f, 1.0f, r, ka, kb, kc); // https://ohmslawcalculator.com/voltage-divider-calculator analogReadStubbed = (1023 * r) / (r + r2); sensor.handle(); REQUIRE(sensor.get() == Approx(24.91409f)); analogReadStubbed = (1023 * r) / (r + r3); sensor.handle(); REQUIRE(sensor.get() == Approx(34.96906)); analogReadStubbed = (1023 * r) / (r + r1); sensor.handle(); REQUIRE(sensor.get() == Approx(4.91589)); } SECTION("Should measure temperature downstream") { NTCSensor sensor(0, false, 0.0f, 1.0f, r, ka, kb, kc); // https://ohmslawcalculator.com/voltage-divider-calculator analogReadStubbed = (1023 * r2) / (r + r2); sensor.handle(); REQUIRE(sensor.get() == Approx(25.00327f)); } }
27.634615
73
0.583159
rvt
8258d9ba9e21abb2b458d06808ab37cfa85e032b
1,250
cpp
C++
class_kitap.cpp
fuatbakkal/Cplusplus_Examples
5615a6dfe0386df68cb311ccb7c4ff1206c37c27
[ "Unlicense" ]
null
null
null
class_kitap.cpp
fuatbakkal/Cplusplus_Examples
5615a6dfe0386df68cb311ccb7c4ff1206c37c27
[ "Unlicense" ]
null
null
null
class_kitap.cpp
fuatbakkal/Cplusplus_Examples
5615a6dfe0386df68cb311ccb7c4ff1206c37c27
[ "Unlicense" ]
null
null
null
#include <iostream> #include <cstring> using namespace std; class kitap { private: char kitap_adi[50], yazar_adi[30]; static int nesne_sayisi; int sayfa_sayisi, basim_yili, stok_no=nesne_sayisi; public: kitap(); virtual ~kitap(); kitap(char ka[50], char ya[30], int ss, int by, int sn) { strcpy(kitap_adi, ka); strcpy(yazar_adi, ya); sayfa_sayisi=ss; basim_yili=by; stok_no=sn; } void bilgileri_yazdir() { cout<<"Kitap adi: "<<kitap_adi<<endl <<"Yazar adi: "<<yazar_adi<<endl <<"Sayfa sayisi: "<<sayfa_sayisi<<endl <<"Basim yili: "<<basim_yili<<endl <<"Stok no: "<<stok_no; } }; int kitap::nesne_sayisi = 0; kitap::kitap(){ cout<<"There are "<<++nesne_sayisi<<" FirstClass objects!"<<endl; } kitap::~kitap(){ if(--nesne_sayisi) cout<<"There are "<<nesne_sayisi<<" FirstClass objects!"<<endl; else cout<<"There are no FirstClass objects!"<<endl; } int main(void) { kitap k1, k2; /* zaman t1, t2(4, 59, 59); t1.deger_al(); cout<<endl<<"t1 - Toplam saniye cinsinden degeri: "<<t1.saniyeye_cevir(); cout<<endl<<"t2 - Toplam saniye cinsinden degeri: "<<t2.saniyeye_cevir(); */ return 0; }
19.84127
75
0.6016
fuatbakkal
825a36a5130925c6036ee9326fbe0dfe7cfd4f10
823
hpp
C++
Siv3D/include/Siv3D/None.hpp
tas9n/OpenSiv3D
c561cba1d88eb9cd9606ba983fcc1120192d5615
[ "MIT" ]
2
2021-11-22T00:52:48.000Z
2021-12-24T09:33:55.000Z
Siv3D/include/Siv3D/None.hpp
tas9n/OpenSiv3D
c561cba1d88eb9cd9606ba983fcc1120192d5615
[ "MIT" ]
32
2021-10-09T10:04:11.000Z
2022-02-25T06:10:13.000Z
Siv3D/include/Siv3D/None.hpp
tas9n/OpenSiv3D
c561cba1d88eb9cd9606ba983fcc1120192d5615
[ "MIT" ]
1
2021-12-31T05:08:00.000Z
2021-12-31T05:08:00.000Z
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2022 Ryo Suzuki // Copyright (c) 2016-2022 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include <ostream> # include <optional> # include "Common.hpp" # include "FormatData.hpp" namespace s3d { /// @brief 無効値の型 using None_t = std::nullopt_t; template <class CharType> inline std::basic_ostream<CharType>& operator <<(std::basic_ostream<CharType>& output, const None_t&) { const CharType no[] = { 'n','o','n','e','\0' }; return output << no; } inline void Formatter(FormatData& formatData, None_t) { formatData.string.append(U"none"_sv); } /// @brief 無効値 inline constexpr None_t none = std::nullopt; }
21.657895
102
0.594168
tas9n
825aa08ac6b51c0e0febce909c6767b5f24509b5
967
cc
C++
tests/t_protocol.cc
yahoo/UDPing
9186b9884459b9f93bbb47e2b2d74aa868a895b5
[ "Apache-2.0" ]
54
2017-05-31T04:16:54.000Z
2022-02-05T11:55:36.000Z
tests/t_protocol.cc
yahoo/UDPing
9186b9884459b9f93bbb47e2b2d74aa868a895b5
[ "Apache-2.0" ]
5
2017-06-15T13:01:43.000Z
2021-04-22T15:33:05.000Z
tests/t_protocol.cc
yahoo/UDPing
9186b9884459b9f93bbb47e2b2d74aa868a895b5
[ "Apache-2.0" ]
12
2017-06-13T04:15:12.000Z
2022-03-04T10:09:10.000Z
#include <cppunit/extensions/HelperMacros.h> #include "protocol.h" #include <string.h> #include <stdio.h> #include "maclist.h" class ProtocolTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE( ProtocolTest ); CPPUNIT_TEST( testProtocol ); CPPUNIT_TEST_SUITE_END(); public: void setUp () {}; void tearDown () {}; void testProtocol (); }; void ProtocolTest::testProtocol () { printf ("Testing Protocol ...\n"); CPPUNIT_ASSERT_EQUAL((int)checksum((uint16_t *)"aaaaaa", 6), 0xdbdb); CPPUNIT_ASSERT_EQUAL((int)checksum((uint16_t *)"AAAAAAAA", 8), 0xfafa); CPPUNIT_ASSERT_EQUAL((int)checksum((uint16_t *)"AAAAAAA", 7), 0x3bfb); MacList ml("aa:bb:cc:dd:ee:ff"); struct frame f; buildFrame(&f, ml.nextMac(), ml.nextMac(), 12345, 12345, 12345, 12345, "Hello, World!", 14, 14); CPPUNIT_ASSERT_EQUAL((int)checksum((uint16_t *)&f, 100), 21661); } CPPUNIT_TEST_SUITE_REGISTRATION( ProtocolTest );
30.21875
100
0.673216
yahoo
825aa0b3e26d8f6c30a8aa0b33723c3481a559e3
375
cpp
C++
source/node/Divide.cpp
xzrunner/sop
80f84765548fde33d990663d4a4b8054bb6714d1
[ "MIT" ]
null
null
null
source/node/Divide.cpp
xzrunner/sop
80f84765548fde33d990663d4a4b8054bb6714d1
[ "MIT" ]
null
null
null
source/node/Divide.cpp
xzrunner/sop
80f84765548fde33d990663d4a4b8054bb6714d1
[ "MIT" ]
null
null
null
#include "sop/node/Divide.h" #include "sop/GeometryImpl.h" #include "sop/NodeHelper.h" namespace sop { namespace node { void Divide::Execute(const ur::Device& dev, Evaluator& eval) { m_geo_impl.reset(); auto prev_geo = NodeHelper::GetInputGeo(*this, 0); if (!prev_geo) { return; } m_geo_impl = std::make_shared<GeometryImpl>(*prev_geo); } } }
16.304348
60
0.664
xzrunner
825e6b1444eb8a73f45e7c79dd3e7504efa1198a
50,952
cpp
C++
VirtualBox-5.0.0/src/bldprogs/scmsubversion.cpp
egraba/vbox_openbsd
6cb82f2eed1fa697d088cecc91722b55b19713c2
[ "MIT" ]
1
2015-04-30T14:18:45.000Z
2015-04-30T14:18:45.000Z
VirtualBox-5.0.0/src/bldprogs/scmsubversion.cpp
egraba/vbox_openbsd
6cb82f2eed1fa697d088cecc91722b55b19713c2
[ "MIT" ]
null
null
null
VirtualBox-5.0.0/src/bldprogs/scmsubversion.cpp
egraba/vbox_openbsd
6cb82f2eed1fa697d088cecc91722b55b19713c2
[ "MIT" ]
null
null
null
/* $Id: scmsubversion.cpp $ */ /** @file * IPRT Testcase / Tool - Source Code Massager, Subversion Access. */ /* * Copyright (C) 2010-2015 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #define SCM_WITH_DYNAMIC_LIB_SVN /******************************************************************************* * Header Files * *******************************************************************************/ #include <iprt/assert.h> #include <iprt/ctype.h> #include <iprt/dir.h> #include <iprt/env.h> #include <iprt/err.h> #include <iprt/file.h> #include <iprt/getopt.h> #include <iprt/handle.h> #include <iprt/initterm.h> #include <iprt/ldr.h> #include <iprt/mem.h> #include <iprt/message.h> #include <iprt/param.h> #include <iprt/path.h> #include <iprt/pipe.h> #include <iprt/poll.h> #include <iprt/process.h> #include <iprt/stream.h> #include <iprt/string.h> #include "scm.h" #if defined(SCM_WITH_DYNAMIC_LIB_SVN) && defined(SCM_WITH_SVN_HEADERS) # include <svn_client.h> #endif /******************************************************************************* * Defined Constants And Macros * *******************************************************************************/ #ifdef SCM_WITH_DYNAMIC_LIB_SVN # if defined(RT_OS_WINDOWS) && defined(RT_ARCH_X86) # define APR_CALL __stdcall # define SVN_CALL /* __stdcall ?? */ # else # define APR_CALL # define SVN_CALL # endif #endif #if defined(SCM_WITH_DYNAMIC_LIB_SVN) && !defined(SCM_WITH_SVN_HEADERS) # define SVN_ERR_MISC_CATEGORY_START 200000 # define SVN_ERR_UNVERSIONED_RESOURCE (SVN_ERR_MISC_CATEGORY_START + 5) #endif /******************************************************************************* * Structures and Typedefs * *******************************************************************************/ #if defined(SCM_WITH_DYNAMIC_LIB_SVN) && !defined(SCM_WITH_SVN_HEADERS) typedef int apr_status_t; typedef int64_t apr_time_t; typedef struct apr_pool_t apr_pool_t; typedef struct apr_hash_t apr_hash_t; typedef struct apr_hash_index_t apr_hash_index_t; typedef struct apr_array_header_t apr_array_header_t; typedef struct svn_error_t { apr_status_t apr_err; const char *_dbgr_message; struct svn_error_t *_dbgr_child; apr_pool_t *_dbgr_pool; const char *_dbgr_file; long _dbgr_line; } svn_error_t; typedef int svn_boolean_t; typedef long int svn_revnum_t; typedef struct svn_client_ctx_t svn_client_ctx_t; typedef enum svn_opt_revision_kind { svn_opt_revision_unspecified = 0, svn_opt_revision_number, svn_opt_revision_date, svn_opt_revision_committed, svn_opt_revision_previous, svn_opt_revision_base, svn_opt_revision_working, svn_opt_revision_head } svn_opt_revision_kind; typedef union svn_opt_revision_value_t { svn_revnum_t number; apr_time_t date; } svn_opt_revision_value_t; typedef struct svn_opt_revision_t { svn_opt_revision_kind kind; svn_opt_revision_value_t value; } svn_opt_revision_t; typedef enum svn_depth_t { svn_depth_unknown = -2, svn_depth_exclude, svn_depth_empty, svn_depth_files, svn_depth_immediates, svn_depth_infinity } svn_depth_t; #endif /* SCM_WITH_DYNAMIC_LIB_SVN && !SCM_WITH_SVN_HEADERS */ /******************************************************************************* * Global Variables * *******************************************************************************/ static char g_szSvnPath[RTPATH_MAX]; static enum { kScmSvnVersion_Ancient = 1, kScmSvnVersion_1_6, kScmSvnVersion_1_7, kScmSvnVersion_1_8, kScmSvnVersion_End } g_enmSvnVersion = kScmSvnVersion_Ancient; #ifdef SCM_WITH_DYNAMIC_LIB_SVN /** Set if all the function pointers are valid. */ static bool g_fSvnFunctionPointersValid; /** @name SVN and APR imports. * @{ */ static apr_status_t (APR_CALL *g_pfnAprInitialize)(void); static apr_hash_index_t * (APR_CALL *g_pfnAprHashFirst)(apr_pool_t *pPool, apr_hash_t *pHashTab); static apr_hash_index_t * (APR_CALL *g_pfnAprHashNext)(apr_hash_index_t *pCurIdx); static void * (APR_CALL *g_pfnAprHashThisVal)(apr_hash_index_t *pHashIdx); static apr_pool_t * (SVN_CALL *g_pfnSvnPoolCreateEx)(apr_pool_t *pParent, void *pvAllocator); static void (APR_CALL *g_pfnAprPoolClear)(apr_pool_t *pPool); static void (APR_CALL *g_pfnAprPoolDestroy)(apr_pool_t *pPool); static svn_error_t * (SVN_CALL *g_pfnSvnClientCreateContext)(svn_client_ctx_t **ppCtx, apr_pool_t *pPool); static svn_error_t * (SVN_CALL *g_pfnSvnClientPropGet4)(apr_hash_t **ppHashProps, const char *pszPropName, const char *pszTarget, const svn_opt_revision_t *pPeggedRev, const svn_opt_revision_t *pRevision, svn_revnum_t *pActualRev, svn_depth_t enmDepth, const apr_array_header_t *pChangeList, svn_client_ctx_t *pCtx, apr_pool_t *pResultPool, apr_pool_t *pScratchPool); /**@} */ #endif /** * Callback that is call for each path to search. */ static DECLCALLBACK(int) scmSvnFindSvnBinaryCallback(char const *pchPath, size_t cchPath, void *pvUser1, void *pvUser2) { char *pszDst = (char *)pvUser1; size_t cchDst = (size_t)pvUser2; if (cchDst > cchPath) { memcpy(pszDst, pchPath, cchPath); pszDst[cchPath] = '\0'; #if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2) int rc = RTPathAppend(pszDst, cchDst, "svn.exe"); #else int rc = RTPathAppend(pszDst, cchDst, "svn"); #endif if ( RT_SUCCESS(rc) && RTFileExists(pszDst)) return VINF_SUCCESS; } return VERR_TRY_AGAIN; } /** * Reads from a pipe. * * @returns @a rc or other status code. * @param rc The current status of the operation. Error status * are preserved and returned. * @param phPipeR Pointer to the pipe handle. * @param pcbAllocated Pointer to the buffer size variable. * @param poffCur Pointer to the buffer offset variable. * @param ppszBuffer Pointer to the buffer pointer variable. */ static int rtProcProcessOutput(int rc, PRTPIPE phPipeR, size_t *pcbAllocated, size_t *poffCur, char **ppszBuffer, RTPOLLSET hPollSet, uint32_t idPollSet) { size_t cbRead; char szTmp[_4K - 1]; for (;;) { int rc2 = RTPipeRead(*phPipeR, szTmp, sizeof(szTmp), &cbRead); if (RT_SUCCESS(rc2) && cbRead) { /* Resize the buffer. */ if (*poffCur + cbRead >= *pcbAllocated) { if (*pcbAllocated >= _1G) { RTPollSetRemove(hPollSet, idPollSet); rc2 = RTPipeClose(*phPipeR); AssertRC(rc2); *phPipeR = NIL_RTPIPE; return RT_SUCCESS(rc) ? VERR_TOO_MUCH_DATA : rc; } size_t cbNew = *pcbAllocated ? *pcbAllocated * 2 : sizeof(szTmp) + 1; Assert(*poffCur + cbRead < cbNew); rc2 = RTStrRealloc(ppszBuffer, cbNew); if (RT_FAILURE(rc2)) { RTPollSetRemove(hPollSet, idPollSet); rc2 = RTPipeClose(*phPipeR); AssertRC(rc2); *phPipeR = NIL_RTPIPE; return RT_SUCCESS(rc) ? rc2 : rc; } *pcbAllocated = cbNew; } /* Append the new data, terminating it. */ memcpy(*ppszBuffer + *poffCur, szTmp, cbRead); *poffCur += cbRead; (*ppszBuffer)[*poffCur] = '\0'; /* Check for null terminators in the string. */ if (RT_SUCCESS(rc) && memchr(szTmp, '\0', cbRead)) rc = VERR_NO_TRANSLATION; /* If we read a full buffer, try read some more. */ if (RT_SUCCESS(rc) && cbRead == sizeof(szTmp)) continue; } else if (rc2 != VINF_TRY_AGAIN) { if (RT_FAILURE(rc) && rc2 != VERR_BROKEN_PIPE) rc = rc2; RTPollSetRemove(hPollSet, idPollSet); rc2 = RTPipeClose(*phPipeR); AssertRC(rc2); *phPipeR = NIL_RTPIPE; } return rc; } } /** @name RTPROCEXEC_FLAGS_XXX - flags for RTProcExec and RTProcExecToString. * @{ */ /** Redirect /dev/null to standard input. */ #define RTPROCEXEC_FLAGS_STDIN_NULL RT_BIT_32(0) /** Redirect standard output to /dev/null. */ #define RTPROCEXEC_FLAGS_STDOUT_NULL RT_BIT_32(1) /** Redirect standard error to /dev/null. */ #define RTPROCEXEC_FLAGS_STDERR_NULL RT_BIT_32(2) /** Redirect all standard output to /dev/null as well as directing /dev/null * to standard input. */ #define RTPROCEXEC_FLAGS_STD_NULL ( RTPROCEXEC_FLAGS_STDIN_NULL \ | RTPROCEXEC_FLAGS_STDOUT_NULL \ | RTPROCEXEC_FLAGS_STDERR_NULL) /** Mask containing the valid flags. */ #define RTPROCEXEC_FLAGS_VALID_MASK UINT32_C(0x00000007) /** @} */ /** * Runs a process, collecting the standard output and/or standard error. * * * @returns IPRT status code * @retval VERR_NO_TRANSLATION if the output of the program isn't valid UTF-8 * or contains a nul character. * @retval VERR_TOO_MUCH_DATA if the process produced too much data. * * @param pszExec Executable image to use to create the child process. * @param papszArgs Pointer to an array of arguments to the child. The * array terminated by an entry containing NULL. * @param hEnv Handle to the environment block for the child. * @param fFlags A combination of RTPROCEXEC_FLAGS_XXX. The @a * ppszStdOut and @a ppszStdErr parameters takes precedence * over redirection flags. * @param pStatus Where to return the status on success. * @param ppszStdOut Where to return the text written to standard output. If * NULL then standard output will not be collected and go * to the standard output handle of the process. * Free with RTStrFree, regardless of return status. * @param ppszStdErr Where to return the text written to standard error. If * NULL then standard output will not be collected and go * to the standard error handle of the process. * Free with RTStrFree, regardless of return status. */ int RTProcExecToString(const char *pszExec, const char * const *papszArgs, RTENV hEnv, uint32_t fFlags, PRTPROCSTATUS pStatus, char **ppszStdOut, char **ppszStdErr) { int rc2; /* * Clear output arguments (no returning failure here, simply crash!). */ AssertPtr(pStatus); pStatus->enmReason = RTPROCEXITREASON_ABEND; pStatus->iStatus = RTEXITCODE_FAILURE; AssertPtrNull(ppszStdOut); if (ppszStdOut) *ppszStdOut = NULL; AssertPtrNull(ppszStdOut); if (ppszStdErr) *ppszStdErr = NULL; /* * Check input arguments. */ AssertReturn(!(fFlags & ~RTPROCEXEC_FLAGS_VALID_MASK), VERR_INVALID_PARAMETER); /* * Do we need a standard input bitbucket? */ int rc = VINF_SUCCESS; PRTHANDLE phChildStdIn = NULL; RTHANDLE hChildStdIn; hChildStdIn.enmType = RTHANDLETYPE_FILE; hChildStdIn.u.hFile = NIL_RTFILE; if ((fFlags & RTPROCEXEC_FLAGS_STDIN_NULL) && RT_SUCCESS(rc)) { phChildStdIn = &hChildStdIn; rc = RTFileOpenBitBucket(&hChildStdIn.u.hFile, RTFILE_O_READ); } /* * Create the output pipes / bitbuckets. */ RTPIPE hPipeStdOutR = NIL_RTPIPE; PRTHANDLE phChildStdOut = NULL; RTHANDLE hChildStdOut; hChildStdOut.enmType = RTHANDLETYPE_PIPE; hChildStdOut.u.hPipe = NIL_RTPIPE; if (ppszStdOut && RT_SUCCESS(rc)) { phChildStdOut = &hChildStdOut; rc = RTPipeCreate(&hPipeStdOutR, &hChildStdOut.u.hPipe, 0 /*fFlags*/); } else if ((fFlags & RTPROCEXEC_FLAGS_STDOUT_NULL) && RT_SUCCESS(rc)) { phChildStdOut = &hChildStdOut; hChildStdOut.enmType = RTHANDLETYPE_FILE; hChildStdOut.u.hFile = NIL_RTFILE; rc = RTFileOpenBitBucket(&hChildStdOut.u.hFile, RTFILE_O_WRITE); } RTPIPE hPipeStdErrR = NIL_RTPIPE; PRTHANDLE phChildStdErr = NULL; RTHANDLE hChildStdErr; hChildStdErr.enmType = RTHANDLETYPE_PIPE; hChildStdErr.u.hPipe = NIL_RTPIPE; if (ppszStdErr && RT_SUCCESS(rc)) { phChildStdErr = &hChildStdErr; rc = RTPipeCreate(&hPipeStdErrR, &hChildStdErr.u.hPipe, 0 /*fFlags*/); } else if ((fFlags & RTPROCEXEC_FLAGS_STDERR_NULL) && RT_SUCCESS(rc)) { phChildStdErr = &hChildStdErr; hChildStdErr.enmType = RTHANDLETYPE_FILE; hChildStdErr.u.hFile = NIL_RTFILE; rc = RTFileOpenBitBucket(&hChildStdErr.u.hFile, RTFILE_O_WRITE); } if (RT_SUCCESS(rc)) { RTPOLLSET hPollSet; rc = RTPollSetCreate(&hPollSet); if (RT_SUCCESS(rc)) { if (hPipeStdOutR != NIL_RTPIPE && RT_SUCCESS(rc)) rc = RTPollSetAddPipe(hPollSet, hPipeStdOutR, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR, 1); if (hPipeStdErrR != NIL_RTPIPE) rc = RTPollSetAddPipe(hPollSet, hPipeStdErrR, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR, 2); } if (RT_SUCCESS(rc)) { /* * Create the process. */ RTPROCESS hProc; rc = RTProcCreateEx(g_szSvnPath, papszArgs, RTENV_DEFAULT, 0 /*fFlags*/, NULL /*phStdIn*/, phChildStdOut, phChildStdErr, NULL /*pszAsUser*/, NULL /*pszPassword*/, &hProc); rc2 = RTHandleClose(&hChildStdErr); AssertRC(rc2); rc2 = RTHandleClose(&hChildStdOut); AssertRC(rc2); if (RT_SUCCESS(rc)) { /* * Process output and wait for the process to finish. */ size_t cbStdOut = 0; size_t offStdOut = 0; size_t cbStdErr = 0; size_t offStdErr = 0; for (;;) { if (hPipeStdOutR != NIL_RTPIPE) rc = rtProcProcessOutput(rc, &hPipeStdOutR, &cbStdOut, &offStdOut, ppszStdOut, hPollSet, 1); if (hPipeStdErrR != NIL_RTPIPE) rc = rtProcProcessOutput(rc, &hPipeStdErrR, &cbStdErr, &offStdErr, ppszStdErr, hPollSet, 2); if (hPipeStdOutR == NIL_RTPIPE && hPipeStdErrR == NIL_RTPIPE) break; if (hProc != NIL_RTPROCESS) { rc2 = RTProcWait(hProc, RTPROCWAIT_FLAGS_NOBLOCK, pStatus); if (rc2 != VERR_PROCESS_RUNNING) { if (RT_FAILURE(rc2)) rc = rc2; hProc = NIL_RTPROCESS; } } rc2 = RTPoll(hPollSet, 10000, NULL, NULL); Assert(RT_SUCCESS(rc2) || rc2 == VERR_TIMEOUT); } if (RT_SUCCESS(rc)) { if ( (ppszStdOut && *ppszStdOut && !RTStrIsValidEncoding(*ppszStdOut)) || (ppszStdErr && *ppszStdErr && !RTStrIsValidEncoding(*ppszStdErr)) ) rc = VERR_NO_TRANSLATION; } /* * No more output, just wait for it to finish. */ if (hProc != NIL_RTPROCESS) { rc2 = RTProcWait(hProc, RTPROCWAIT_FLAGS_BLOCK, pStatus); if (RT_FAILURE(rc2)) rc = rc2; } } RTPollSetDestroy(hPollSet); } } rc2 = RTHandleClose(&hChildStdErr); AssertRC(rc2); rc2 = RTHandleClose(&hChildStdOut); AssertRC(rc2); rc2 = RTHandleClose(&hChildStdIn); AssertRC(rc2); rc2 = RTPipeClose(hPipeStdErrR); AssertRC(rc2); rc2 = RTPipeClose(hPipeStdOutR); AssertRC(rc2); return rc; } /** * Runs a process, waiting for it to complete. * * @returns IPRT status code * * @param pszExec Executable image to use to create the child process. * @param papszArgs Pointer to an array of arguments to the child. The * array terminated by an entry containing NULL. * @param hEnv Handle to the environment block for the child. * @param fFlags A combination of RTPROCEXEC_FLAGS_XXX. * @param pStatus Where to return the status on success. */ int RTProcExec(const char *pszExec, const char * const *papszArgs, RTENV hEnv, uint32_t fFlags, PRTPROCSTATUS pStatus) { int rc; /* * Clear output argument (no returning failure here, simply crash!). */ AssertPtr(pStatus); pStatus->enmReason = RTPROCEXITREASON_ABEND; pStatus->iStatus = RTEXITCODE_FAILURE; /* * Check input arguments. */ AssertReturn(!(fFlags & ~RTPROCEXEC_FLAGS_VALID_MASK), VERR_INVALID_PARAMETER); /* * Set up /dev/null redirections. */ PRTHANDLE aph[3] = { NULL, NULL, NULL }; RTHANDLE ah[3]; for (uint32_t i = 0; i < 3; i++) { ah[i].enmType = RTHANDLETYPE_FILE; ah[i].u.hFile = NIL_RTFILE; } rc = VINF_SUCCESS; if ((fFlags & RTPROCEXEC_FLAGS_STDIN_NULL) && RT_SUCCESS(rc)) { aph[0] = &ah[0]; rc = RTFileOpenBitBucket(&ah[0].u.hFile, RTFILE_O_READ); } if ((fFlags & RTPROCEXEC_FLAGS_STDOUT_NULL) && RT_SUCCESS(rc)) { aph[1] = &ah[1]; rc = RTFileOpenBitBucket(&ah[1].u.hFile, RTFILE_O_WRITE); } if ((fFlags & RTPROCEXEC_FLAGS_STDERR_NULL) && RT_SUCCESS(rc)) { aph[2] = &ah[2]; rc = RTFileOpenBitBucket(&ah[2].u.hFile, RTFILE_O_WRITE); } /* * Create the process. */ RTPROCESS hProc; if (RT_SUCCESS(rc)) rc = RTProcCreateEx(g_szSvnPath, papszArgs, RTENV_DEFAULT, 0 /*fFlags*/, aph[0], aph[1], aph[2], NULL /*pszAsUser*/, NULL /*pszPassword*/, &hProc); for (uint32_t i = 0; i < 3; i++) RTFileClose(ah[i].u.hFile); if (RT_SUCCESS(rc)) rc = RTProcWait(hProc, RTPROCWAIT_FLAGS_BLOCK, pStatus); return rc; } /** * Executes SVN and gets the output. * * Standard error is suppressed. * * @returns VINF_SUCCESS if the command executed successfully. * @param pState The rewrite state to work on. Can be NULL. * @param papszArgs The SVN argument. * @param fNormalFailureOk Whether normal failure is ok. * @param ppszStdOut Where to return the output on success. */ static int scmSvnRunAndGetOutput(PSCMRWSTATE pState, const char **papszArgs, bool fNormalFailureOk, char **ppszStdOut) { *ppszStdOut = NULL; char *pszCmdLine = NULL; int rc = RTGetOptArgvToString(&pszCmdLine, papszArgs, RTGETOPTARGV_CNV_QUOTE_BOURNE_SH); if (RT_FAILURE(rc)) return rc; ScmVerbose(pState, 2, "executing: %s\n", pszCmdLine); RTPROCSTATUS Status; rc = RTProcExecToString(g_szSvnPath, papszArgs, RTENV_DEFAULT, RTPROCEXEC_FLAGS_STD_NULL, &Status, ppszStdOut, NULL); if ( RT_SUCCESS(rc) && ( Status.enmReason != RTPROCEXITREASON_NORMAL || Status.iStatus != 0) ) { if (fNormalFailureOk || Status.enmReason != RTPROCEXITREASON_NORMAL) RTMsgError("%s: %s -> %s %u\n", pszCmdLine, Status.enmReason == RTPROCEXITREASON_NORMAL ? "exit code" : Status.enmReason == RTPROCEXITREASON_SIGNAL ? "signal" : Status.enmReason == RTPROCEXITREASON_ABEND ? "abnormal end" : "abducted by alien", Status.iStatus); rc = VERR_GENERAL_FAILURE; } else if (RT_FAILURE(rc)) { if (pState) RTMsgError("%s: executing: %s => %Rrc\n", pState->pszFilename, pszCmdLine, rc); else RTMsgError("executing: %s => %Rrc\n", pszCmdLine, rc); } if (RT_FAILURE(rc)) { RTStrFree(*ppszStdOut); *ppszStdOut = NULL; } RTStrFree(pszCmdLine); return rc; } /** * Executes SVN. * * Standard error and standard output is suppressed. * * @returns VINF_SUCCESS if the command executed successfully. * @param pState The rewrite state to work on. * @param papszArgs The SVN argument. * @param fNormalFailureOk Whether normal failure is ok. */ static int scmSvnRun(PSCMRWSTATE pState, const char **papszArgs, bool fNormalFailureOk) { char *pszCmdLine = NULL; int rc = RTGetOptArgvToString(&pszCmdLine, papszArgs, RTGETOPTARGV_CNV_QUOTE_BOURNE_SH); if (RT_FAILURE(rc)) return rc; ScmVerbose(pState, 2, "executing: %s\n", pszCmdLine); /* Lazy bird uses RTProcExecToString. */ RTPROCSTATUS Status; rc = RTProcExec(g_szSvnPath, papszArgs, RTENV_DEFAULT, RTPROCEXEC_FLAGS_STD_NULL, &Status); if ( RT_SUCCESS(rc) && ( Status.enmReason != RTPROCEXITREASON_NORMAL || Status.iStatus != 0) ) { if (fNormalFailureOk || Status.enmReason != RTPROCEXITREASON_NORMAL) RTMsgError("%s: %s -> %s %u\n", pState->pszFilename, pszCmdLine, Status.enmReason == RTPROCEXITREASON_NORMAL ? "exit code" : Status.enmReason == RTPROCEXITREASON_SIGNAL ? "signal" : Status.enmReason == RTPROCEXITREASON_ABEND ? "abnormal end" : "abducted by alien", Status.iStatus); rc = VERR_GENERAL_FAILURE; } else if (RT_FAILURE(rc)) RTMsgError("%s: %s -> %Rrc\n", pState->pszFilename, pszCmdLine, rc); RTStrFree(pszCmdLine); return rc; } #ifdef SCM_WITH_DYNAMIC_LIB_SVN /** * Attempts to resolve the necessary subversion and apache portable runtime APIs * we require dynamically. * * Will set all global function pointers and g_fSvnFunctionPointersValid to true * on success. */ static void scmSvnTryResolveFunctions(void) { char szPath[RTPATH_MAX]; int rc = RTStrCopy(szPath, sizeof(szPath), g_szSvnPath); if (RT_SUCCESS(rc)) { RTPathStripFilename(szPath); char *pszEndPath = strchr(szPath, '\0'); # ifdef RT_OS_WINDOWS RTPathChangeToDosSlashes(szPath, false); # endif /* * Try various prefixes/suffxies/locations. */ static struct { const char *pszPrefix; const char *pszSuffix; } const s_aVariations[] = { # ifdef RT_OS_WINDOWS { "SlikSvn-lib", "-1.dll" }, /* SlikSVN */ { "lib", "-1.dll" }, /* Win32Svn,CollabNet,++ */ # elif defined(RT_OS_DARWIN) { "../lib/lib", "-1.dylib" }, # else { "../lib/lib", ".so" }, { "../lib/lib", "-1.so" }, # endif }; for (unsigned iVar = 0; RT_ELEMENTS(s_aVariations); iVar++) { /* * Try load the svn_client library ... */ static const char * const s_apszLibraries[] = { "svn_client", "svn_subr", "apr" }; RTLDRMOD ahMods[RT_ELEMENTS(s_apszLibraries)] = { NIL_RTLDRMOD, NIL_RTLDRMOD, NIL_RTLDRMOD }; rc = VINF_SUCCESS; unsigned iLib; for (iLib = 0; iLib < RT_ELEMENTS(s_apszLibraries) && RT_SUCCESS(rc); iLib++) { *pszEndPath = '\0'; rc = RTPathAppend(szPath, sizeof(szPath), s_aVariations[iVar].pszPrefix); if (RT_SUCCESS(rc)) rc = RTStrCat(szPath, sizeof(szPath), s_apszLibraries[iLib]); if (RT_SUCCESS(rc)) rc = RTStrCat(szPath, sizeof(szPath), s_aVariations[iVar].pszSuffix); if (RT_SUCCESS(rc)) { # ifdef RT_OS_WINDOWS RTPathChangeToDosSlashes(pszEndPath, false); # endif rc = RTLdrLoadEx(szPath, &ahMods[iLib], RTLDRLOAD_FLAGS_NT_SEARCH_DLL_LOAD_DIR , NULL); } } if (iLib == RT_ELEMENTS(s_apszLibraries) && RT_SUCCESS(rc)) { static const struct { unsigned iLib; const char *pszSymbol; PFNRT *ppfn; } s_aSymbols[] = { { 2, "apr_initialize", (PFNRT *)&g_pfnAprInitialize }, { 2, "apr_hash_first", (PFNRT *)&g_pfnAprHashFirst }, { 2, "apr_hash_next", (PFNRT *)&g_pfnAprHashNext }, { 2, "apr_hash_this_val", (PFNRT *)&g_pfnAprHashThisVal }, { 1, "svn_pool_create_ex", (PFNRT *)&g_pfnSvnPoolCreateEx }, { 2, "apr_pool_clear", (PFNRT *)&g_pfnAprPoolClear }, { 2, "apr_pool_destroy", (PFNRT *)&g_pfnAprPoolDestroy }, { 0, "svn_client_create_context", (PFNRT *)&g_pfnSvnClientCreateContext }, { 0, "svn_client_propget4", (PFNRT *)&g_pfnSvnClientPropGet4 }, }; for (unsigned i = 0; i < RT_ELEMENTS(s_aSymbols); i++) { rc = RTLdrGetSymbol(ahMods[s_aSymbols[i].iLib], s_aSymbols[i].pszSymbol, (void **)(uintptr_t)s_aSymbols[i].ppfn); if (RT_FAILURE(rc)) { ScmVerbose(NULL, 0, "Failed to resolve '%s' in '%s'", s_aSymbols[i].pszSymbol, s_apszLibraries[s_aSymbols[i].iLib]); break; } } if (RT_SUCCESS(rc)) { apr_status_t rcApr = g_pfnAprInitialize(); if (rcApr == 0) { ScmVerbose(NULL, 1, "Found subversion APIs.\n"); g_fSvnFunctionPointersValid = true; } else { ScmVerbose(NULL, 0, "apr_initialize failed: %#x (%d)\n", rcApr, rcApr); AssertMsgFailed(("%#x (%d)\n", rc, rc)); } return; } } while (iLib-- > 0) RTLdrClose(ahMods[iLib]); } } } #endif /* SCM_WITH_DYNAMIC_LIB_SVN */ /** * Finds the svn binary, updating g_szSvnPath and g_enmSvnVersion. */ static void scmSvnFindSvnBinary(PSCMRWSTATE pState) { /* Already been called? */ if (g_szSvnPath[0] != '\0') return; /* * Locate it. */ /** @todo code page fun... */ #ifdef RT_OS_WINDOWS const char *pszEnvVar = RTEnvGet("Path"); #else const char *pszEnvVar = RTEnvGet("PATH"); #endif if (pszEnvVar) { #if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2) int rc = RTPathTraverseList(pszEnvVar, ';', scmSvnFindSvnBinaryCallback, g_szSvnPath, (void *)sizeof(g_szSvnPath)); #else int rc = RTPathTraverseList(pszEnvVar, ':', scmSvnFindSvnBinaryCallback, g_szSvnPath, (void *)sizeof(g_szSvnPath)); #endif if (RT_FAILURE(rc)) strcpy(g_szSvnPath, "svn"); } else strcpy(g_szSvnPath, "svn"); /* * Check the version. */ const char *apszArgs[] = { g_szSvnPath, "--version", "--quiet", NULL }; char *pszVersion; int rc = scmSvnRunAndGetOutput(pState, apszArgs, false, &pszVersion); if (RT_SUCCESS(rc)) { char *pszStripped = RTStrStrip(pszVersion); if (RTStrVersionCompare(pszVersion, "1.8") >= 0) g_enmSvnVersion = kScmSvnVersion_1_8; else if (RTStrVersionCompare(pszVersion, "1.7") >= 0) g_enmSvnVersion = kScmSvnVersion_1_7; else if (RTStrVersionCompare(pszVersion, "1.6") >= 0) g_enmSvnVersion = kScmSvnVersion_1_6; else g_enmSvnVersion = kScmSvnVersion_Ancient; RTStrFree(pszVersion); } else g_enmSvnVersion = kScmSvnVersion_Ancient; #ifdef SCM_WITH_DYNAMIC_LIB_SVN /* * If we got version 1.8 or later, try see if we can locate a few of the * simpler SVN APIs. */ g_fSvnFunctionPointersValid = false; if (g_enmSvnVersion >= kScmSvnVersion_1_8) scmSvnTryResolveFunctions(); #endif } /** * Construct a dot svn filename for the file being rewritten. * * @returns IPRT status code. * @param pState The rewrite state (for the name). * @param pszDir The directory, including ".svn/". * @param pszSuff The filename suffix. * @param pszDst The output buffer. RTPATH_MAX in size. */ static int scmSvnConstructName(PSCMRWSTATE pState, const char *pszDir, const char *pszSuff, char *pszDst) { strcpy(pszDst, pState->pszFilename); /* ASSUMES sizeof(szBuf) <= sizeof(szPath) */ RTPathStripFilename(pszDst); int rc = RTPathAppend(pszDst, RTPATH_MAX, pszDir); if (RT_SUCCESS(rc)) { rc = RTPathAppend(pszDst, RTPATH_MAX, RTPathFilename(pState->pszFilename)); if (RT_SUCCESS(rc)) { size_t cchDst = strlen(pszDst); size_t cchSuff = strlen(pszSuff); if (cchDst + cchSuff < RTPATH_MAX) { memcpy(&pszDst[cchDst], pszSuff, cchSuff + 1); return VINF_SUCCESS; } else rc = VERR_BUFFER_OVERFLOW; } } return rc; } /** * Interprets the specified string as decimal numbers. * * @returns true if parsed successfully, false if not. * @param pch The string (not terminated). * @param cch The string length. * @param pu Where to return the value. */ static bool scmSvnReadNumber(const char *pch, size_t cch, size_t *pu) { size_t u = 0; while (cch-- > 0) { char ch = *pch++; if (ch < '0' || ch > '9') return false; u *= 10; u += ch - '0'; } *pu = u; return true; } #ifdef SCM_WITH_DYNAMIC_LIB_SVN /** * Wrapper around RTPathAbs. * @returns Same as RTPathAbs. * @param pszPath The relative path. * @param pszAbsPath Where to return the absolute path. * @param cbAbsPath Size of the @a pszAbsPath buffer. */ static int scmSvnAbsPath(const char *pszPath, char *pszAbsPath, size_t cbAbsPath) { int rc = RTPathAbs(pszPath, pszAbsPath, cbAbsPath); # if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2) if (RT_SUCCESS(rc)) RTPathChangeToUnixSlashes(pszAbsPath, true /*fForce*/); # endif return rc; } /** * Checks if @a pszPath exists in the current WC. * * @returns true, false or -1. In the latter case, please use the fallback. * @param pszPath Path to the object that should be investigated. */ static int scmSvnIsObjectInWorkingCopy(const char *pszPath) { int rc = -1; /* svn_client_propget4 and later requires absolute target path. */ char szAbsPath[RTPATH_MAX]; int rc2 = scmSvnAbsPath(pszPath, szAbsPath, sizeof(szAbsPath)); if (RT_SUCCESS(rc2)) { /* Create calling context. */ apr_pool_t *pPool = g_pfnSvnPoolCreateEx(NULL, NULL); if (pPool) { svn_client_ctx_t *pCtx = NULL; svn_error_t *pErr = g_pfnSvnClientCreateContext(&pCtx, pPool); if (!pErr) { /* Make the call. */ apr_hash_t *pHash = NULL; svn_opt_revision_t Rev; RT_ZERO(Rev); Rev.kind = svn_opt_revision_base; Rev.value.number = -1L; pErr = g_pfnSvnClientPropGet4(&pHash, "svn:no-such-property", szAbsPath, &Rev, &Rev, NULL /*pActualRev*/, svn_depth_empty, NULL /*pChangeList*/, pCtx, pPool, pPool); if (!pErr) rc = true; else if (pErr->apr_err == SVN_ERR_UNVERSIONED_RESOURCE) rc = false; } g_pfnAprPoolDestroy(pPool); } } return rc; } #endif /* SCM_WITH_DYNAMIC_LIB_SVN */ /** * Checks if the file we're operating on is part of a SVN working copy. * * @returns true if it is, false if it isn't or we cannot tell. * @param pState The rewrite state to work on. */ bool ScmSvnIsInWorkingCopy(PSCMRWSTATE pState) { scmSvnFindSvnBinary(pState); #ifdef SCM_WITH_DYNAMIC_LIB_SVN if (g_fSvnFunctionPointersValid) { int rc = scmSvnIsObjectInWorkingCopy(pState->pszFilename); if (rc == (int)true || rc == (int)false) return rc == (int)true; } /* Fallback: */ #endif if (g_enmSvnVersion < kScmSvnVersion_1_7) { /* * Hack: check if the .svn/text-base/<file>.svn-base file exists. */ char szPath[RTPATH_MAX]; int rc = scmSvnConstructName(pState, ".svn/text-base/", ".svn-base", szPath); if (RT_SUCCESS(rc)) return RTFileExists(szPath); } else { const char *apszArgs[] = { g_szSvnPath, "propget", "svn:no-such-property", pState->pszFilename, NULL }; char *pszValue; int rc = scmSvnRunAndGetOutput(pState, apszArgs, true, &pszValue); if (RT_SUCCESS(rc)) { RTStrFree(pszValue); return true; } } return false; } /** * Checks if the specified directory is part of a SVN working copy. * * @returns true if it is, false if it isn't or we cannot tell. * @param pszDir The directory in question. */ bool ScmSvnIsDirInWorkingCopy(const char *pszDir) { scmSvnFindSvnBinary(NULL); #ifdef SCM_WITH_DYNAMIC_LIB_SVN if (g_fSvnFunctionPointersValid) { int rc = scmSvnIsObjectInWorkingCopy(pszDir); if (rc == (int)true || rc == (int)false) return rc == (int)true; } /* Fallback: */ #endif if (g_enmSvnVersion < kScmSvnVersion_1_7) { /* * Hack: check if the .svn/ dir exists. */ char szPath[RTPATH_MAX]; int rc = RTPathJoin(szPath, sizeof(szPath), pszDir, ".svn"); if (RT_SUCCESS(rc)) return RTDirExists(szPath); } else { const char *apszArgs[] = { g_szSvnPath, "propget", "svn:no-such-property", pszDir, NULL }; char *pszValue; int rc = scmSvnRunAndGetOutput(NULL, apszArgs, true, &pszValue); if (RT_SUCCESS(rc)) { RTStrFree(pszValue); return true; } } return false; } #ifdef SCM_WITH_DYNAMIC_LIB_SVN /** * Checks if @a pszPath exists in the current WC. * * @returns IPRT status code - VERR_NOT_SUPPORT if fallback should be attempted. * @param pszPath Path to the object that should be investigated. * @param pszProperty The property name. * @param ppszValue Where to return the property value. Optional. */ static int scmSvnQueryPropertyUsingApi(const char *pszPath, const char *pszProperty, char **ppszValue) { int rc = VERR_NOT_SUPPORTED; /* svn_client_propget4 and later requires absolute target path. */ char szAbsPath[RTPATH_MAX]; int rc2 = scmSvnAbsPath(pszPath, szAbsPath, sizeof(szAbsPath)); if (RT_SUCCESS(rc2)) { /* Create calling context. */ apr_pool_t *pPool = g_pfnSvnPoolCreateEx(NULL, NULL); if (pPool) { svn_client_ctx_t *pCtx = NULL; svn_error_t *pErr = g_pfnSvnClientCreateContext(&pCtx, pPool); if (!pErr) { /* Make the call. */ apr_hash_t *pHash = NULL; svn_opt_revision_t Rev; RT_ZERO(Rev); Rev.kind = svn_opt_revision_base; Rev.value.number = -1L; pErr = g_pfnSvnClientPropGet4(&pHash, pszProperty, szAbsPath, &Rev, &Rev, NULL /*pActualRev*/, svn_depth_empty, NULL /*pChangeList*/, pCtx, pPool, pPool); if (!pErr) { /* Get the first value, if any. */ rc = VERR_NOT_FOUND; apr_hash_index_t *pHashIdx = g_pfnAprHashFirst(pPool, pHash); if (pHashIdx) { const char **ppszFirst = (const char **)g_pfnAprHashThisVal(pHashIdx); if (ppszFirst && *ppszFirst) { if (ppszValue) rc = RTStrDupEx(ppszValue, *ppszFirst); else rc = VINF_SUCCESS; } } } else if (pErr->apr_err == SVN_ERR_UNVERSIONED_RESOURCE) rc = VERR_INVALID_STATE; else rc = VERR_GENERAL_FAILURE; } g_pfnAprPoolDestroy(pPool); } } return rc; } #endif /* SCM_WITH_DYNAMIC_LIB_SVN */ /** * Queries the value of an SVN property. * * This will automatically adjust for scheduled changes. * * @returns IPRT status code. * @retval VERR_INVALID_STATE if not a SVN WC file. * @retval VERR_NOT_FOUND if the property wasn't found. * @param pState The rewrite state to work on. * @param pszName The property name. * @param ppszValue Where to return the property value. Free this * using RTStrFree. Optional. */ int ScmSvnQueryProperty(PSCMRWSTATE pState, const char *pszName, char **ppszValue) { int rc; /* * Look it up in the scheduled changes. */ size_t i = pState->cSvnPropChanges; while (i-- > 0) if (!strcmp(pState->paSvnPropChanges[i].pszName, pszName)) { const char *pszValue = pState->paSvnPropChanges[i].pszValue; if (!pszValue) return VERR_NOT_FOUND; if (ppszValue) return RTStrDupEx(ppszValue, pszValue); return VINF_SUCCESS; } scmSvnFindSvnBinary(pState); #ifdef SCM_WITH_DYNAMIC_LIB_SVN if (g_fSvnFunctionPointersValid) { rc = scmSvnQueryPropertyUsingApi(pState->pszFilename, pszName, ppszValue); if (rc != VERR_NOT_SUPPORTED) return rc; /* Fallback: */ } #endif if (g_enmSvnVersion < kScmSvnVersion_1_7) { /* * Hack: Read the .svn/props/<file>.svn-work file exists. */ char szPath[RTPATH_MAX]; rc = scmSvnConstructName(pState, ".svn/props/", ".svn-work", szPath); if (RT_SUCCESS(rc) && !RTFileExists(szPath)) rc = scmSvnConstructName(pState, ".svn/prop-base/", ".svn-base", szPath); if (RT_SUCCESS(rc)) { SCMSTREAM Stream; rc = ScmStreamInitForReading(&Stream, szPath); if (RT_SUCCESS(rc)) { /* * The current format is K len\n<name>\nV len\n<value>\n" ... END. */ rc = VERR_NOT_FOUND; size_t const cchName = strlen(pszName); SCMEOL enmEol; size_t cchLine; const char *pchLine; while ((pchLine = ScmStreamGetLine(&Stream, &cchLine, &enmEol)) != NULL) { /* * Parse the 'K num' / 'END' line. */ if ( cchLine == 3 && !memcmp(pchLine, "END", 3)) break; size_t cchKey; if ( cchLine < 3 || pchLine[0] != 'K' || pchLine[1] != ' ' || !scmSvnReadNumber(&pchLine[2], cchLine - 2, &cchKey) || cchKey == 0 || cchKey > 4096) { RTMsgError("%s:%u: Unexpected data '%.*s'\n", szPath, ScmStreamTellLine(&Stream), cchLine, pchLine); rc = VERR_PARSE_ERROR; break; } /* * Match the key and skip to the value line. Don't bother with * names containing EOL markers. */ size_t const offKey = ScmStreamTell(&Stream); bool fMatch = cchName == cchKey; if (fMatch) { pchLine = ScmStreamGetLine(&Stream, &cchLine, &enmEol); if (!pchLine) break; fMatch = cchLine == cchName && !memcmp(pchLine, pszName, cchName); } if (RT_FAILURE(ScmStreamSeekAbsolute(&Stream, offKey + cchKey))) break; if (RT_FAILURE(ScmStreamSeekByLine(&Stream, ScmStreamTellLine(&Stream) + 1))) break; /* * Read and Parse the 'V num' line. */ pchLine = ScmStreamGetLine(&Stream, &cchLine, &enmEol); if (!pchLine) break; size_t cchValue; if ( cchLine < 3 || pchLine[0] != 'V' || pchLine[1] != ' ' || !scmSvnReadNumber(&pchLine[2], cchLine - 2, &cchValue) || cchValue > _1M) { RTMsgError("%s:%u: Unexpected data '%.*s'\n", szPath, ScmStreamTellLine(&Stream), cchLine, pchLine); rc = VERR_PARSE_ERROR; break; } /* * If we have a match, allocate a return buffer and read the * value into it. Otherwise skip this value and continue * searching. */ if (fMatch) { if (!ppszValue) rc = VINF_SUCCESS; else { char *pszValue; rc = RTStrAllocEx(&pszValue, cchValue + 1); if (RT_SUCCESS(rc)) { rc = ScmStreamRead(&Stream, pszValue, cchValue); if (RT_SUCCESS(rc)) *ppszValue = pszValue; else RTStrFree(pszValue); } } break; } if (RT_FAILURE(ScmStreamSeekRelative(&Stream, cchValue))) break; if (RT_FAILURE(ScmStreamSeekByLine(&Stream, ScmStreamTellLine(&Stream) + 1))) break; } if (RT_FAILURE(ScmStreamGetStatus(&Stream))) { rc = ScmStreamGetStatus(&Stream); RTMsgError("%s: stream error %Rrc\n", szPath, rc); } ScmStreamDelete(&Stream); } } if (rc == VERR_FILE_NOT_FOUND) rc = VERR_NOT_FOUND; } else { const char *apszArgs[] = { g_szSvnPath, "propget", "--strict", pszName, pState->pszFilename, NULL }; char *pszValue; rc = scmSvnRunAndGetOutput(pState, apszArgs, false, &pszValue); if (RT_SUCCESS(rc)) { if (pszValue && *pszValue) { if (ppszValue) { *ppszValue = pszValue; pszValue = NULL; } } else rc = VERR_NOT_FOUND; RTStrFree(pszValue); } } return rc; } /** * Schedules the setting of a property. * * @returns IPRT status code. * @retval VERR_INVALID_STATE if not a SVN WC file. * @param pState The rewrite state to work on. * @param pszName The name of the property to set. * @param pszValue The value. NULL means deleting it. */ int ScmSvnSetProperty(PSCMRWSTATE pState, const char *pszName, const char *pszValue) { /* * Update any existing entry first. */ size_t i = pState->cSvnPropChanges; while (i-- > 0) if (!strcmp(pState->paSvnPropChanges[i].pszName, pszName)) { if (!pszValue) { RTStrFree(pState->paSvnPropChanges[i].pszValue); pState->paSvnPropChanges[i].pszValue = NULL; } else { char *pszCopy; int rc = RTStrDupEx(&pszCopy, pszValue); if (RT_FAILURE(rc)) return rc; pState->paSvnPropChanges[i].pszValue = pszCopy; } return VINF_SUCCESS; } /* * Insert a new entry. */ i = pState->cSvnPropChanges; if ((i % 32) == 0) { void *pvNew = RTMemRealloc(pState->paSvnPropChanges, (i + 32) * sizeof(SCMSVNPROP)); if (!pvNew) return VERR_NO_MEMORY; pState->paSvnPropChanges = (PSCMSVNPROP)pvNew; } pState->paSvnPropChanges[i].pszName = RTStrDup(pszName); pState->paSvnPropChanges[i].pszValue = pszValue ? RTStrDup(pszValue) : NULL; if ( pState->paSvnPropChanges[i].pszName && (pState->paSvnPropChanges[i].pszValue || !pszValue) ) pState->cSvnPropChanges = i + 1; else { RTStrFree(pState->paSvnPropChanges[i].pszName); pState->paSvnPropChanges[i].pszName = NULL; RTStrFree(pState->paSvnPropChanges[i].pszValue); pState->paSvnPropChanges[i].pszValue = NULL; return VERR_NO_MEMORY; } return VINF_SUCCESS; } /** * Schedules a property deletion. * * @returns IPRT status code. * @param pState The rewrite state to work on. * @param pszName The name of the property to delete. */ int ScmSvnDelProperty(PSCMRWSTATE pState, const char *pszName) { return ScmSvnSetProperty(pState, pszName, NULL); } /** * Applies any SVN property changes to the work copy of the file. * * @returns IPRT status code. * @param pState The rewrite state which SVN property changes * should be applied. */ int ScmSvnDisplayChanges(PSCMRWSTATE pState) { size_t i = pState->cSvnPropChanges; while (i-- > 0) { const char *pszName = pState->paSvnPropChanges[i].pszName; const char *pszValue = pState->paSvnPropChanges[i].pszValue; if (pszValue) ScmVerbose(pState, 0, "svn propset '%s' '%s' %s\n", pszName, pszValue, pState->pszFilename); else ScmVerbose(pState, 0, "svn propdel '%s' %s\n", pszName, pState->pszFilename); } return VINF_SUCCESS; } /** * Applies any SVN property changes to the work copy of the file. * * @returns IPRT status code. * @param pState The rewrite state which SVN property changes * should be applied. */ int ScmSvnApplyChanges(PSCMRWSTATE pState) { scmSvnFindSvnBinary(pState); #ifdef SCM_WITH_LATER if (0) { return ...; } /* Fallback: */ #endif /* * Iterate thru the changes and apply them by starting the svn client. */ for (size_t i = 0; i < pState->cSvnPropChanges; i++) { const char *apszArgv[6]; apszArgv[0] = g_szSvnPath; apszArgv[1] = pState->paSvnPropChanges[i].pszValue ? "propset" : "propdel"; apszArgv[2] = pState->paSvnPropChanges[i].pszName; int iArg = 3; if (pState->paSvnPropChanges[i].pszValue) apszArgv[iArg++] = pState->paSvnPropChanges[i].pszValue; apszArgv[iArg++] = pState->pszFilename; apszArgv[iArg++] = NULL; int rc = scmSvnRun(pState, apszArgv, false); if (RT_FAILURE(rc)) return rc; } return VINF_SUCCESS; }
35.090909
126
0.536623
egraba