hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
b4c3b77fecd6e4d5c19569d72e005e7eeddbac5b
8,943
cxx
C++
Examples/Filtering/CompositeFilterExample.cxx
xcorail/OTB
092a93654c3b5d009e420f450fe9b675f737cdca
[ "Apache-2.0" ]
null
null
null
Examples/Filtering/CompositeFilterExample.cxx
xcorail/OTB
092a93654c3b5d009e420f450fe9b675f737cdca
[ "Apache-2.0" ]
null
null
null
Examples/Filtering/CompositeFilterExample.cxx
xcorail/OTB
092a93654c3b5d009e420f450fe9b675f737cdca
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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. */ // Software Guide : BeginLatex // // The composite filter we will build combines three filters: a gradient // magnitude operator, which will calculate the first-order derivative of // the image; a thresholding step to select edges over a given strength; // and finally a rescaling filter, to ensure the resulting image data is // visible by scaling the intensity to the full spectrum of the output // image type. // // Since this filter takes an image and produces another image (of // identical type), we will specialize the ImageToImageFilter: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Next we include headers for the component filters: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkUnaryFunctorImageFilter.h" #include "itkGradientMagnitudeImageFilter.h" #include "itkThresholdImageFilter.h" #include "itkRescaleIntensityImageFilter.h" // Software Guide : EndCodeSnippet #include "itkNumericTraits.h" #include "otbImage.h" // Software Guide : BeginLatex // // Now we can declare the filter itself. It is within the OTB namespace, // and we decide to make it use the same image type for both input and // output, thus the template declaration needs only one parameter. // Deriving from \code{ImageToImageFilter} provides default behavior for // several important aspects, notably allocating the output image (and // making it the same dimensions as the input). // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet namespace otb { template <class TImageType> class ITK_EXPORT CompositeExampleImageFilter : public itk::ImageToImageFilter<TImageType, TImageType> { public: // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Next we have the standard declarations, used for object creation with // the object factory: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef CompositeExampleImageFilter Self; typedef itk::ImageToImageFilter<TImageType, TImageType> Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; // Software Guide : EndCodeSnippet /** Method for creation through object factory */ itkNewMacro(Self); /** Run-time type information */ itkTypeMacro(CompositeExampleImageFilter, itk::ImageToImageFilter); /** Display */ void PrintSelf(std::ostream& os, itk::Indent indent) const override; // Software Guide : BeginLatex // // Here we declare an alias (to save typing) for the image's pixel type, // which determines the type of the threshold value. We then use the // convenience macros to define the Get and Set methods for this parameter. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef typename TImageType::PixelType PixelType; itkGetMacro(Threshold, PixelType); itkSetMacro(Threshold, PixelType); // Software Guide : EndCodeSnippet protected: CompositeExampleImageFilter(); // Software Guide : BeginLatex // // Now we can declare the component filter types, templated over the // enclosing image type: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet protected: typedef itk::ThresholdImageFilter<TImageType> ThresholdType; typedef itk::GradientMagnitudeImageFilter<TImageType, TImageType> GradientType; typedef itk::RescaleIntensityImageFilter<TImageType, TImageType> RescalerType; // Software Guide : EndCodeSnippet void GenerateData() override; private: CompositeExampleImageFilter(Self &); // intentionally not implemented void operator =(const Self&); // intentionally not implemented // Software Guide : BeginLatex // // The component filters are declared as data members, all using the smart // pointer types. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typename GradientType::Pointer m_GradientFilter; typename ThresholdType::Pointer m_ThresholdFilter; typename RescalerType::Pointer m_RescaleFilter; PixelType m_Threshold; }; } /* namespace otb */ // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The constructor sets up the pipeline, which involves creating the // stages, connecting them together, and setting default parameters. // // Software Guide : EndLatex namespace otb { // Software Guide : BeginCodeSnippet template <class TImageType> CompositeExampleImageFilter<TImageType> ::CompositeExampleImageFilter() { m_GradientFilter = GradientType::New(); m_ThresholdFilter = ThresholdType::New(); m_RescaleFilter = RescalerType::New(); m_ThresholdFilter->SetInput(m_GradientFilter->GetOutput()); m_RescaleFilter->SetInput(m_ThresholdFilter->GetOutput()); m_Threshold = 1; m_RescaleFilter->SetOutputMinimum( itk::NumericTraits<PixelType>::NonpositiveMin()); m_RescaleFilter->SetOutputMaximum(itk::NumericTraits<PixelType>::max()); } // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The \code{GenerateData()} is where the composite magic happens. First, // we connect the first component filter to the inputs of the composite // filter (the actual input, supplied by the upstream stage). Then we // graft the output of the last stage onto the output of the composite, // which ensures the filter regions are updated. We force the composite // pipeline to be processed by calling \code{Update()} on the final stage, // then graft the output back onto the output of the enclosing filter, so // it has the result available to the downstream filter. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet template <class TImageType> void CompositeExampleImageFilter<TImageType>:: GenerateData() { m_GradientFilter->SetInput(this->GetInput()); m_ThresholdFilter->ThresholdBelow(this->m_Threshold); m_RescaleFilter->GraftOutput(this->GetOutput()); m_RescaleFilter->Update(); this->GraftOutput(m_RescaleFilter->GetOutput()); } // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Finally we define the \code{PrintSelf} method, which (by convention) // prints the filter parameters. Note how it invokes the superclass to // print itself first, and also how the indentation prefixes each line. // // Software Guide : EndLatex // // Software Guide : BeginCodeSnippet template <class TImageType> void CompositeExampleImageFilter<TImageType>:: PrintSelf(std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Threshold:" << this->m_Threshold << std::endl; } } /* end namespace otb */ // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // It is important to note that in the above example, none of the internal // details of the pipeline were exposed to users of the class. The interface // consisted of the Threshold parameter (which happened to change the value in // the component filter) and the regular ImageToImageFilter interface. This // example pipeline is illustrated in // Figure~\ref{fig:CompositeExamplePipeline}. // // Software Guide : EndLatex #include "otbImageFileReader.h" #include "otbImageFileWriter.h" int main(int argc, char* argv[]) { if (argc < 3) { std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << " inputImageFile outputImageFile" << std::endl; return EXIT_FAILURE; } typedef otb::Image<short, 2> ImageType; typedef otb::ImageFileReader<ImageType> ReaderType; typedef otb::ImageFileWriter<ImageType> WriterType; typedef otb::CompositeExampleImageFilter<ImageType> FilterType; ReaderType::Pointer reader = ReaderType::New(); WriterType::Pointer writer = WriterType::New(); FilterType::Pointer filter = FilterType::New(); reader->SetFileName(argv[1]); filter->SetInput(reader->GetOutput()); filter->SetThreshold(20); writer->SetInput(filter->GetOutput()); writer->SetFileName(argv[2]); try { writer->Update(); } catch ( itk::ExceptionObject & e ) { std::cerr << "Error: " << e << std::endl; } return EXIT_SUCCESS; }
30.111111
79
0.732752
[ "object" ]
b4c56313f4f99060493382f0debab93c6cc743e9
6,749
cpp
C++
qubiter/quantum_CSD_compiler/LEGACY/qubiter1.11-C++source/BIT_VECTOR.cpp
artiste-qb-net/qubiter
af0340584d0b47d6b18d3dd28cd9b55a08cb507c
[ "Apache-2.0" ]
129
2016-03-22T17:50:16.000Z
2022-01-26T14:53:03.000Z
qubiter/quantum_CSD_compiler/LEGACY/qubiter1.11-C++source/BIT_VECTOR.cpp
yourball/qubiter
5ef0ea064fa8c9f125f7951a01fbb88504a054a5
[ "Apache-2.0" ]
40
2016-03-22T19:38:27.000Z
2019-07-02T19:40:27.000Z
qubiter/quantum_CSD_compiler/LEGACY/qubiter1.11-C++source/BIT_VECTOR.cpp
artiste-qb-net/qubiter
af0340584d0b47d6b18d3dd28cd9b55a08cb507c
[ "Apache-2.0" ]
36
2016-03-28T07:48:54.000Z
2022-01-26T14:49:28.000Z
#include "BIT_VECTOR.h" #include "PERMUTATION.h" #pragma mark --creation/destruction-- //****************************************** BIT_VECTOR::BIT_VECTOR( USHORT len /*=1*/, //in USHORT dec_rep /*=0*/) //in :its_len(len), its_dec_rep(dec_rep) { ThrowIf_(len>max_len); ThrowIf_(len<1); } //****************************************** BIT_VECTOR & BIT_VECTOR::operator= ( const BIT_VECTOR & rhs) //in { if(this != &rhs){ its_len = rhs.its_len; its_dec_rep = rhs.its_dec_rep; } return *this; } #pragma mark --simple accessors-- //****************************************** USHORT BIT_VECTOR::get_len() const { return its_len; } //****************************************** VOID BIT_VECTOR::set_len( USHORT len) //in { ThrowIf_(len>max_len); ThrowIf_(len<1); its_len = len; } //****************************************** USHORT BIT_VECTOR::get_dec_rep() const { return its_dec_rep; } //****************************************** BIT_VECTOR & BIT_VECTOR::set_dec_rep( USHORT dec_rep) //in { its_dec_rep = dec_rep; return *this; } #pragma mark --ON/OFF bit methods-- //****************************************** BOOLEAN BIT_VECTOR::bit_is_ON( USHORT bpos) //in const { ThrowIf_(bpos>=its_len); USHORT mask = (1<<bpos); return (its_dec_rep & mask)==mask; } //****************************************** VOID BIT_VECTOR::set_bit_ON( USHORT bpos) //in { ThrowIf_(bpos>=its_len); its_dec_rep |=(1<<bpos); } //****************************************** VOID BIT_VECTOR::set_bit_OFF( USHORT bpos) //in { ThrowIf_(bpos>=its_len); its_dec_rep &= ~(1<<bpos); } //****************************************** VOID BIT_VECTOR::set_all_bits_ON() { for(USHORT bpos=0; bpos<its_len; bpos++){ its_dec_rep |=(1<<bpos); } } //****************************************** USHORT BIT_VECTOR::get_num_of_ON_bits() const { USHORT count = 0; for(USHORT bpos=0; bpos<its_len; bpos++){ if(bit_is_ON(bpos))count++; } return count; } //****************************************** BOOLEAN BIT_VECTOR::find_ON_bit_to_my_right( USHORT me_bit, //in USHORT & right_ON_bit) //out { ThrowIf_(me_bit>=its_len); if(me_bit==0)return false; right_ON_bit = me_bit; USHORT mask = (1<<right_ON_bit); BOOLEAN found_it = false; do{ right_ON_bit--; mask >>= 1; found_it = ((its_dec_rep & mask) == mask); }while( (right_ON_bit!=0) && !found_it ); return found_it; } //****************************************** BOOLEAN BIT_VECTOR::find_ON_bit_to_my_left( USHORT me_bit, //in USHORT & left_ON_bit) //out { ThrowIf_(me_bit>=its_len); if(me_bit==(its_len-1))return false; left_ON_bit = me_bit; USHORT mask = (1<<left_ON_bit); BOOLEAN found_it = false; do{ left_ON_bit++; mask <<= 1; found_it = ((its_dec_rep & mask) == mask); }while( (left_ON_bit!=(its_len-1)) && !found_it ); return found_it; } //****************************************** BOOLEAN BIT_VECTOR::find_leftmost_ON_bit( USHORT & leftmost_ON_bit) //out { if(bit_is_ON(its_len-1)){ leftmost_ON_bit = its_len-1; return true; }else{ return find_ON_bit_to_my_right(its_len-1, leftmost_ON_bit); } } //****************************************** BOOLEAN BIT_VECTOR::find_rightmost_ON_bit( USHORT & rightmost_ON_bit) //out { if(bit_is_ON(0)){ rightmost_ON_bit = 0; return true; }else{ return find_ON_bit_to_my_left(0, rightmost_ON_bit); } } #pragma mark --about lazy ordering-- //Refs: look under "gray code" //(1)Martin Gardener, "Knotted DoughNuts and Other //Mathematical Entertainments", chapt. 2, "The Binary Gray Code" //(2)"Numerical Recipies in C" //(3)Many books on Discrete Mathematics for CompSci types //(4)On the web, in Eric's Treasure Trove/Math/Gray Codes //Normal and lazy sequences both start at 0 //One has normal (dictionary) order, the other has lazy order. //For illustration purposes, suppose N_B = 3 //The lazy sequence 000, 100, 110, 010, 011, 111, 101, 001 //is easily obtained from //the "standard" lazy sequence 000, 001, 011, 010, 110, 111, 101, 100 //by "reflecting" each sequence term. //We will use the second sequence because //it is more common in the literature. //****************************************** USHORT lazy_from_normal( USHORT normal, //in USHORT bit_len) //in { ThrowIf_(normal>= (1<<bit_len)); ThrowIf_(bit_len>BIT_VECTOR::max_len); USHORT lazy = normal; for(SHORT m = (SHORT)bit_len-2; m >= 0; m--){ //Look at bpos = m+1, if it's ON, then flip bpos=m. //Remember that ^ is same as a mod2 sum. lazy ^= ( (((1 << m+1) & normal)?1:0) << m ); } return lazy; } //****************************************** VOID BIT_VECTOR::normal_to_lazy( const BIT_VECTOR & normal_bvec, //in BIT_VECTOR & lazy_bvec) //out { ThrowIf_(lazy_bvec.its_len != normal_bvec.its_len); lazy_bvec.its_dec_rep = lazy_from_normal(normal_bvec.its_dec_rep, normal_bvec.its_len); } //****************************************** VOID BIT_VECTOR::lazy_advance( USHORT new_normal) //in { //This method takes bit vector "lazy" (which corresponds to bit vector "normal"), and //changes it to the next lazy bit vector, "new_lazy" (which corresponds to "new_normal"). ThrowIf_(new_normal<1); its_dec_rep ^= ((new_normal) & ~(new_normal-1)); //example: 000, 001, 011, 010, 110, 111, 101, 100 //its_dec_rep = 011, normal = 2 = 010 initially //new_normal = 3 = 011 //(new_normal & ~normal) = 011 & 101 = 001 = mask for the bit that changed //its_dec_rep = 011 ^ 001 = 010 finally } //****************************************** BOOLEAN BIT_VECTOR::find_lazy_leftmost_ON_bit( USHORT new_normal, //in USHORT & leftmost_ON_bit) //out { //This method works only for bit vectors in the standard lazy sequence. //example: 000, 001, 011, 010, 110, 111, 101, 100 //if new_normal >= 4, leftmost_ON_bit = 2 //else if new_normal >= 2, leftmost_ON_bit = 1 //else if new_normal >= 1, leftmost_ON_bit = 0 ThrowIf_(new_normal<1); BOOLEAN found_it = true; if(its_dec_rep == 0){ found_it = false; }else{ for(SHORT n=its_len-1; n>=0; n--){ if(new_normal >= (1<< n)){ leftmost_ON_bit = n; break; } } } return found_it; } #pragma mark --permuting bits-- //****************************************** USHORT BIT_VECTOR::permute_bits( const PERMUTATION & pmut) //in { ThrowIf_(its_len!=pmut.get_len()); USHORT dec=0; for(USHORT i=0; i<its_len; i++){ if( ((its_dec_rep>>i)&1)==1 ){ dec |= (1<<pmut[i]); } } its_dec_rep = dec; return dec; } //****************************************** USHORT BIT_VECTOR::transpose_bits( const TRANSPOSITION & transp) //in { if(transp.x != transp.y){ PERMUTATION pmut(its_len); pmut.swap_entries(transp.x, transp.y); permute_bits(pmut); } return its_dec_rep; }
25.858238
90
0.585865
[ "vector" ]
b4c719ba9ede72e6a535c9801addd119aac4a6bf
7,987
cpp
C++
CBaseEntity.cpp
younasiqw/HOPROCSGO
efdbc9f636d39cfe425707086ac60afbafe78e72
[ "MIT" ]
null
null
null
CBaseEntity.cpp
younasiqw/HOPROCSGO
efdbc9f636d39cfe425707086ac60afbafe78e72
[ "MIT" ]
null
null
null
CBaseEntity.cpp
younasiqw/HOPROCSGO
efdbc9f636d39cfe425707086ac60afbafe78e72
[ "MIT" ]
null
null
null
#include "sdk.h" #include "Math.h" #include "global.h" #include "GameUtils.h" #include "xor.h" CBaseCombatWeapon* CBaseEntity::GetWeapon() { ULONG WeaponUlong = *(PULONG)((DWORD)this + offys.m_hActiveWeapon); // hActiveWeapon return (CBaseCombatWeapon*)(g_pEntitylist->GetClientEntityFromHandle(WeaponUlong)); } DWORD GetCSWpnDataAddr; int CBaseEntity::GetSequenceActivity(int sequence) { auto hdr = g_pModelInfo->GetStudioModel(this->GetModel()); if (!hdr) return -1; static auto getSequenceActivity = (DWORD)(Utilities::Memory::FindPatternIDA(XorStr("client.dll"), XorStr("55 8B EC 83 7D 08 FF 56 8B F1 74 3D"))); static auto GetSequenceActivity = reinterpret_cast<int(__fastcall*)(void*, studiohdr_t*, int)>(getSequenceActivity); return GetSequenceActivity(this, hdr, sequence); } void CBaseEntity::SetCurrentCommand(CUserCmd* cmd) { static int offset = g_pNetVars->GetOffset("DT_BasePlayer", "m_hConstraintEntity"); *Member<CUserCmd**>(this, (offset - 0xC)) = cmd; } bool CBaseEntity::IsValidRenderable() { if (!this || this == nullptr || G::LocalPlayer == nullptr) return false; if (this == G::LocalPlayer) return false; if (this->GetTeamNum() == G::LocalPlayer->GetTeamNum()) return false; if (this->IsDormant()) return false; if (!this->isAlive()) return false; return true; } void CBaseEntity::SetAbsOrigin(const Vector& origin) { using SetAbsOriginFn = void(__thiscall*)(void*, const Vector& origin); static SetAbsOriginFn SetAbsOrigin = (SetAbsOriginFn)FindPatternIDA("client.dll", "55 8B EC 83 E4 F8 51 53 56 57 8B F1 E8"); SetAbsOrigin(this, origin); } bool CBaseEntity::IsValidTarget() { if (!this || this == nullptr) return false; ClientClass* pClass = (ClientClass*)this->GetClientClass(); if (this == G::LocalPlayer) return false; if (pClass->m_ClassID != 35) return false; if (this->GetTeamNum() == G::LocalPlayer->GetTeamNum()) return false; if (this->IsDormant()) return false; if (!this->isAlive()) return false; if (this->IsProtected()) return false; return true; } void CBaseEntity::SetAngle2(Vector wantedang) { typedef void(__thiscall * SetAngleFn)(void*, const Vector&); static SetAngleFn SetAngle = (SetAngleFn)((DWORD)Utilities::Memory::FindPatternIDA("client.dll", "55 8B EC 83 E4 F8 83 EC 64 53 56 57 8B F1")); SetAngle(this, wantedang); } bool CBaseEntity::canHit(Vector end, CBaseEntity* ent) { Ray_t ray; trace_t tr; CTraceFilter traceFilter; traceFilter.pSkip = this; ray.Init(this->GetEyePosition(), end); g_pEngineTrace->ClipRayToCBaseEntity(ray, MASK_SHOT, ent, &tr); // ignore grate if (!tr.m_pEnt) return false; CBaseEntity* pEnt = (CBaseEntity*)tr.m_pEnt; if (pEnt->GetTeamNum() != this->GetTeamNum()) return true; return false; } Vector CBaseEntity::GetBonePos(int i) { VMatrix boneMatrix[128]; if (this->SetupBones(boneMatrix, 128, BONE_USED_BY_HITBOX, g_pGlobals->curtime)) { return Vector(boneMatrix[i][0][3], boneMatrix[i][1][3], boneMatrix[i][2][3]); } return Vector(0, 0, 0); } CSWeaponInfo* CBaseCombatWeapon::GetCSWpnData() { typedef CSWeaponInfo*(__thiscall * OriginalFn)(void*); return CallVFunction<OriginalFn>(this, 445)(this); } #define TIME_TO_TICKS(dt) ((int)(0.5f + (float)(dt) / g_pGlobals->interval_per_tick)) int CBaseEntity::GetChockedPackets() { if (GetSimulationTime() > GetOldSimulationTime()) return TIME_TO_TICKS(fabs(GetSimulationTime() - GetOldSimulationTime())); return 0; } Vector& CBaseEntity::m_vecNetworkOrigin() { static int offset = g_pNetVars->GetOffset("DT_CSPlayer", "m_flFriction") - sizeof(Vector); return *(Vector*)((DWORD)this + offset); } float CBaseEntity::GetOldSimulationTime() { static uintptr_t offset = g_pNetVars->GetOffset("DT_CSPlayer", "m_flSimulationTimen") + 0x4; return *(float*)((DWORD)this + offset); } bool CBaseEntity::SetupBones(VMatrix* pBoneToWorldOut, int nMaxBones, int boneMask, float currentTime) { __asm { mov edi, this lea ecx, dword ptr ds : [edi + 0x4] mov edx, dword ptr ds : [ecx] push currentTime push boneMask push nMaxBones push pBoneToWorldOut call dword ptr ds : [edx + 0x34] } } bool CBaseEntity::IsTargettingLocal() { Vector src, dst, forward; trace_t tr; if (!this || !G::LocalPlayer || G::LocalPlayer->GetHealth() < 0) return false; Vector viewangle = this->GetEyeAngles(); Math::AngleVectors(viewangle, &forward); forward *= 8142.f; src = this->GetEyePosition(); dst = src + forward; Ray_t ray; ray.Init(src, dst); CTraceCBaseEntity filter; filter.pHit = G::LocalPlayer; g_pEngineTrace->TraceRay_NEW(ray, MASK_SHOT, &filter, &tr); if (tr.m_pEnt && tr.m_pEnt->GetTeamNum() != this->GetTeamNum()) return true; return false; } bool CBaseEntity::IsPlayer() { ClientClass* pClass = (ClientClass*)this->GetClientClass(); return pClass->m_ClassID == 35; } bool CBaseCombatWeapon::IsReloadingVisually() { static int m_bReloadVisuallyComplete = g_pNetVars->GetOffset(XorStr("DT_WeaponCSBase"), XorStr("m_bReloadVisuallyComplete")); return !GetFieldValue<bool>(m_bReloadVisuallyComplete); } float_t& CBaseEntity::m_flMaxspeed() { static unsigned int _m_flMaxspeed = g_pData->Find(GetPredDescMap(), "m_flMaxspeed"); return *(float_t*)((uintptr_t)this + _m_flMaxspeed); } float_t& CBaseEntity::m_surfaceFriction() { static unsigned int _m_surfaceFriction = g_pData->Find(GetPredDescMap(), "m_surfaceFriction"); return *(float_t*)((uintptr_t)this + _m_surfaceFriction); }
5.812955
148
0.494178
[ "vector", "3d" ]
b4c78ebf772f8aeeebe406ae8d9cd5d157a79e09
53,089
cpp
C++
src/GafferUI/GraphGadget.cpp
lucienfostier/gaffer
edf52130820ec8550ea53e41f1de5a6e0cabda24
[ "BSD-3-Clause" ]
null
null
null
src/GafferUI/GraphGadget.cpp
lucienfostier/gaffer
edf52130820ec8550ea53e41f1de5a6e0cabda24
[ "BSD-3-Clause" ]
null
null
null
src/GafferUI/GraphGadget.cpp
lucienfostier/gaffer
edf52130820ec8550ea53e41f1de5a6e0cabda24
[ "BSD-3-Clause" ]
null
null
null
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2011-2012, John Haddon. All rights reserved. // Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the following // disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided with // the distribution. // // * Neither the name of John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "GafferUI/GraphGadget.h" #include "GafferUI/AnnotationsGadget.h" #include "GafferUI/AuxiliaryConnectionsGadget.h" #include "GafferUI/BackdropNodeGadget.h" #include "GafferUI/ButtonEvent.h" #include "GafferUI/ConnectionGadget.h" #include "GafferUI/NodeGadget.h" #include "GafferUI/Nodule.h" #include "GafferUI/Pointer.h" #include "GafferUI/StandardGraphLayout.h" #include "GafferUI/Style.h" #include "GafferUI/ViewportGadget.h" #include "Gaffer/CompoundNumericPlug.h" #include "Gaffer/DependencyNode.h" #include "Gaffer/Metadata.h" #include "Gaffer/MetadataAlgo.h" #include "Gaffer/NumericPlug.h" #include "Gaffer/RecursiveChildIterator.h" #include "Gaffer/ScriptNode.h" #include "Gaffer/StandardSet.h" #include "Gaffer/TypedPlug.h" #include "IECore/BoxOps.h" #include "IECore/Export.h" #include "IECore/NullObject.h" IECORE_PUSH_DEFAULT_VISIBILITY #include "OpenEXR/ImathPlane.h" IECORE_POP_DEFAULT_VISIBILITY #include "boost/bind.hpp" #include "boost/bind/placeholders.hpp" using namespace GafferUI; using namespace Imath; using namespace IECore; using namespace std; ////////////////////////////////////////////////////////////////////////// // Private utilities ////////////////////////////////////////////////////////////////////////// namespace { bool readOnly( const Gaffer::StandardSet *set ) { for( size_t i = 0, s = set->size(); i < s; ++i ) { if( const Gaffer::GraphComponent *g = runTimeCast<const Gaffer::GraphComponent>( set->member( i ) ) ) { if( Gaffer::MetadataAlgo::readOnly( g ) ) { return true; } } } return false; } const InternedString g_positionPlugName( "__uiPosition" ); const InternedString g_inputConnectionsMinimisedPlugName( "__uiInputConnectionsMinimised" ); const InternedString g_outputConnectionsMinimisedPlugName( "__uiOutputConnectionsMinimised" ); const InternedString g_nodeGadgetTypeName( "nodeGadget:type" ); const InternedString g_auxiliaryConnectionsGadgetName( "__auxiliaryConnections" ); const InternedString g_annotationsGadgetName( "__annotations" ); struct CompareV2fX{ bool operator()(const Imath::V2f &a, const Imath::V2f &b) const { return a[0] < b[0]; } }; // Action used to set node positions during drags. This implements // a custom `merge()` operation to avoid excessive memory use when dragging // large numbers of nodes around for a significant number of substeps. The // standard merging implemented by `ScriptNode::CompoundAction` works great // until a drag increment is 0 in one of the XY axes. When that occurs, // the `setValue()` calls for that axis are optimised out and then // `CompoundAction::merge()` falls back to a brute-force version // that keeps all the actions for every single drag increment (because there // are different numbers of actions from one substep to the next). // // Alternative approaches might be : // // - Improve `CompoundAction::merge()`. When the simple merge fails we could // perhaps construct a secondary map from subject to action, and then attempt // to merge all the actions pertaining to the same subject. In the general // case there is no guarantee of one action per subject though, so it seems // the benefits might be limited to this one use case anyway. // - Allow `CompoundPlug::setValue()` to force all child plugs to be set, even // when one or more aren't changing. This seems counter to expectations from // the point of view of an observer of `plugSetSignal()` though. // // For now at least, I prefer the isolated scope of `SetPositionsAction` to the // more core alternatives. class SetPositionsAction : public Gaffer::Action { public : IE_CORE_DECLARERUNTIMETYPEDEXTENSION( SetPositionsAction, GraphGadgetSetPositionsActionTypeId, Gaffer::Action ); SetPositionsAction( Gaffer::Node *root ) : m_scriptNode( root->scriptNode() ) { } void addOffset( Gaffer::V2fPlugPtr plug, const V2f &offset ) { const V2f v = plug->getValue(); m_positions[plug] = { v, v + offset }; } protected : Gaffer::GraphComponent *subject() const override { return m_scriptNode; } void doAction() override { // The `setValue()` calls we make are themselves undoable, so we must disable // undo to stop them being recorded redundantly. Gaffer::UndoScope scope( m_scriptNode, Gaffer::UndoScope::Disabled ); for( auto &p : m_positions ) { p.first->setValue( p.second.newPosition ); } } void undoAction() override { // The `setValue()` calls we make are themselves undoable, so we must disable // undo to stop them being recorded redundantly. Gaffer::UndoScope scope( m_scriptNode, Gaffer::UndoScope::Disabled ); for( auto &p : m_positions ) { p.first->setValue( p.second.oldPosition ); } } bool canMerge( const Action *other ) const override { if( !Action::canMerge( other ) ) { return false; } const auto a = runTimeCast<const SetPositionsAction>( other ); return a && a->m_scriptNode == m_scriptNode; } void merge( const Action *other ) override { auto a = static_cast<const SetPositionsAction *>( other ); for( auto &p : a->m_positions ) { auto inserted = m_positions.insert( p ); if( !inserted.second ) { inserted.first->second.newPosition = p.second.newPosition; } } } private : Gaffer::ScriptNode *m_scriptNode; struct Positions { V2f oldPosition; V2f newPosition; }; using PositionsMap = std::map<Gaffer::V2fPlugPtr, Positions>; PositionsMap m_positions; }; IE_CORE_DEFINERUNTIMETYPED( SetPositionsAction ); IE_CORE_DECLAREPTR( SetPositionsAction ) } // namespace ////////////////////////////////////////////////////////////////////////// // GraphGadget implementation ////////////////////////////////////////////////////////////////////////// GAFFER_GRAPHCOMPONENT_DEFINE_TYPE( GraphGadget ); GraphGadget::GraphGadget( Gaffer::NodePtr root, Gaffer::SetPtr filter ) : m_dragStartPosition( 0 ), m_lastDragPosition( 0 ), m_dragMode( None ), m_dragReconnectCandidate( nullptr ), m_dragReconnectSrcNodule( nullptr ), m_dragReconnectDstNodule( nullptr ), m_dragMergeGroupId( 0 ) { keyPressSignal().connect( boost::bind( &GraphGadget::keyPressed, this, ::_1, ::_2 ) ); buttonPressSignal().connect( boost::bind( &GraphGadget::buttonPress, this, ::_1, ::_2 ) ); buttonReleaseSignal().connect( boost::bind( &GraphGadget::buttonRelease, this, ::_1, ::_2 ) ); dragBeginSignal().connect( boost::bind( &GraphGadget::dragBegin, this, ::_1, ::_2 ) ); dragEnterSignal().connect( boost::bind( &GraphGadget::dragEnter, this, ::_1, ::_2 ) ); dragMoveSignal().connect( boost::bind( &GraphGadget::dragMove, this, ::_1, ::_2 ) ); dragEndSignal().connect( boost::bind( &GraphGadget::dragEnd, this, ::_1, ::_2 ) ); Gaffer::Metadata::nodeValueChangedSignal().connect( boost::bind( &GraphGadget::nodeMetadataChanged, this, ::_1, ::_2, ::_3 ) ); m_layout = new StandardGraphLayout; setChild( g_auxiliaryConnectionsGadgetName, new AuxiliaryConnectionsGadget() ); setChild( g_annotationsGadgetName, new AnnotationsGadget() ); setRoot( root, filter ); } GraphGadget::~GraphGadget() { removeChild( auxiliaryConnectionsGadget() ); } Gaffer::Node *GraphGadget::getRoot() { return m_root.get(); } const Gaffer::Node *GraphGadget::getRoot() const { return m_root.get(); } void GraphGadget::setRoot( Gaffer::NodePtr root, Gaffer::SetPtr filter ) { if( root == m_root && filter == m_filter ) { return; } bool rootChanged = false; Gaffer::NodePtr previousRoot = m_root; if( root != m_root ) { rootChanged = true; m_root = root; m_rootChildAddedConnection = m_root->childAddedSignal().connect( boost::bind( &GraphGadget::rootChildAdded, this, ::_1, ::_2 ) ); m_rootChildRemovedConnection = m_root->childRemovedSignal().connect( boost::bind( &GraphGadget::rootChildRemoved, this, ::_1, ::_2 ) ); } Gaffer::ScriptNodePtr scriptNode = runTimeCast<Gaffer::ScriptNode>( m_root ); if( !scriptNode ) { scriptNode = m_root->scriptNode(); } if( scriptNode != m_scriptNode ) { m_scriptNode = scriptNode; if( m_scriptNode ) { m_selectionMemberAddedConnection = m_scriptNode->selection()->memberAddedSignal().connect( boost::bind( &GraphGadget::selectionMemberAdded, this, ::_1, ::_2 ) ); m_selectionMemberRemovedConnection = m_scriptNode->selection()->memberRemovedSignal().connect( boost::bind( &GraphGadget::selectionMemberRemoved, this, ::_1, ::_2 ) ); } else { m_selectionMemberAddedConnection.disconnect(); m_selectionMemberAddedConnection.disconnect(); } } if( filter != m_filter ) { setFilter( filter ); // setFilter() will call updateGraph() for us. } else { updateGraph(); } if( rootChanged ) { m_rootChangedSignal( this, previousRoot.get() ); } } GraphGadget::RootChangedSignal &GraphGadget::rootChangedSignal() { return m_rootChangedSignal; } Gaffer::Set *GraphGadget::getFilter() { return m_filter.get(); } const Gaffer::Set *GraphGadget::getFilter() const { return m_filter.get(); } void GraphGadget::setFilter( Gaffer::SetPtr filter ) { if( filter == m_filter ) { return; } m_filter = filter; if( m_filter ) { m_filterMemberAddedConnection = m_filter->memberAddedSignal().connect( boost::bind( &GraphGadget::filterMemberAdded, this, ::_1, ::_2 ) ); m_filterMemberRemovedConnection = m_filter->memberRemovedSignal().connect( boost::bind( &GraphGadget::filterMemberRemoved, this, ::_1, ::_2 ) ); } else { m_filterMemberAddedConnection = boost::signals::connection(); m_filterMemberRemovedConnection = boost::signals::connection(); } updateGraph(); } NodeGadget *GraphGadget::nodeGadget( const Gaffer::Node *node ) { return findNodeGadget( node ); } const NodeGadget *GraphGadget::nodeGadget( const Gaffer::Node *node ) const { return findNodeGadget( node ); } ConnectionGadget *GraphGadget::connectionGadget( const Gaffer::Plug *dstPlug ) { return findConnectionGadget( dstPlug ); } const ConnectionGadget *GraphGadget::connectionGadget( const Gaffer::Plug *dstPlug ) const { return findConnectionGadget( dstPlug ); } size_t GraphGadget::connectionGadgets( const Gaffer::Plug *plug, std::vector<ConnectionGadget *> &connections, const Gaffer::Set *excludedNodes ) { if( plug->direction() == Gaffer::Plug::In ) { const Gaffer::Plug *input = plug->getInput<Gaffer::Plug>(); if( input ) { if( !excludedNodes || !excludedNodes->contains( input->node() ) ) { if( ConnectionGadget *connection = connectionGadget( plug ) ) { connections.push_back( connection ); } } } } else { const Gaffer::Plug::OutputContainer &outputs = plug->outputs(); for( Gaffer::Plug::OutputContainer::const_iterator it = outputs.begin(), eIt = outputs.end(); it != eIt; ++it ) { if( excludedNodes && excludedNodes->contains( (*it)->node() ) ) { continue; } if( ConnectionGadget *connection = connectionGadget( *it ) ) { connections.push_back( connection ); } } } return connections.size(); } size_t GraphGadget::connectionGadgets( const Gaffer::Plug *plug, std::vector<const ConnectionGadget *> &connections, const Gaffer::Set *excludedNodes ) const { // preferring naughty casts over maintaining two identical implementations return const_cast<GraphGadget *>( this )->connectionGadgets( plug, reinterpret_cast<std::vector<ConnectionGadget *> &>( connections ), excludedNodes ); } size_t GraphGadget::connectionGadgets( const Gaffer::Node *node, std::vector<ConnectionGadget *> &connections, const Gaffer::Set *excludedNodes ) { for( Gaffer::RecursivePlugIterator it( node ); !it.done(); ++it ) { this->connectionGadgets( it->get(), connections, excludedNodes ); } return connections.size(); } size_t GraphGadget::connectionGadgets( const Gaffer::Node *node, std::vector<const ConnectionGadget *> &connections, const Gaffer::Set *excludedNodes ) const { for( Gaffer::RecursivePlugIterator it( node ); !it.done(); ++it ) { this->connectionGadgets( it->get(), connections, excludedNodes ); } return connections.size(); } AuxiliaryConnectionsGadget *GraphGadget::auxiliaryConnectionsGadget() { return getChild<AuxiliaryConnectionsGadget>( g_auxiliaryConnectionsGadgetName ); } const AuxiliaryConnectionsGadget *GraphGadget::auxiliaryConnectionsGadget() const { return getChild<AuxiliaryConnectionsGadget>( g_auxiliaryConnectionsGadgetName ); } size_t GraphGadget::upstreamNodeGadgets( const Gaffer::Node *node, std::vector<NodeGadget *> &upstreamNodeGadgets, size_t degreesOfSeparation ) { NodeGadget *g = nodeGadget( node ); if( !g ) { return 0; } std::set<NodeGadget *> n; connectedNodeGadgetsWalk( g, n, Gaffer::Plug::In, degreesOfSeparation ); std::copy( n.begin(), n.end(), back_inserter( upstreamNodeGadgets ) ); return 0; } size_t GraphGadget::upstreamNodeGadgets( const Gaffer::Node *node, std::vector<const NodeGadget *> &upstreamNodeGadgets, size_t degreesOfSeparation ) const { // preferring naughty casts over maintaining two identical implementations return const_cast<GraphGadget *>( this )->upstreamNodeGadgets( node, reinterpret_cast<std::vector<NodeGadget *> &>( upstreamNodeGadgets ), degreesOfSeparation ); } size_t GraphGadget::downstreamNodeGadgets( const Gaffer::Node *node, std::vector<NodeGadget *> &downstreamNodeGadgets, size_t degreesOfSeparation ) { NodeGadget *g = nodeGadget( node ); if( !g ) { return 0; } std::set<NodeGadget *> n; connectedNodeGadgetsWalk( g, n, Gaffer::Plug::Out, degreesOfSeparation ); std::copy( n.begin(), n.end(), back_inserter( downstreamNodeGadgets ) ); return 0; } size_t GraphGadget::downstreamNodeGadgets( const Gaffer::Node *node, std::vector<const NodeGadget *> &downstreamNodeGadgets, size_t degreesOfSeparation ) const { // preferring naughty casts over maintaining two identical implementations return const_cast<GraphGadget *>( this )->downstreamNodeGadgets( node, reinterpret_cast<std::vector<NodeGadget *> &>( downstreamNodeGadgets ), degreesOfSeparation ); } size_t GraphGadget::connectedNodeGadgets( const Gaffer::Node *node, std::vector<NodeGadget *> &connectedNodeGadgets, Gaffer::Plug::Direction direction, size_t degreesOfSeparation ) { NodeGadget *g = nodeGadget( node ); if( !g ) { return 0; } std::set<NodeGadget *> n; connectedNodeGadgetsWalk( g, n, direction, degreesOfSeparation ); if( direction == Gaffer::Plug::Invalid ) { // if we were traversing in both directions, we will have accidentally // traversed back to the start point, which we don't want. n.erase( nodeGadget( node ) ); } std::copy( n.begin(), n.end(), back_inserter( connectedNodeGadgets ) ); return 0; } size_t GraphGadget::connectedNodeGadgets( const Gaffer::Node *node, std::vector<const NodeGadget *> &connectedNodeGadgets, Gaffer::Plug::Direction direction, size_t degreesOfSeparation ) const { // preferring naughty casts over maintaining two identical implementations return const_cast<GraphGadget *>( this )->connectedNodeGadgets( node, reinterpret_cast<std::vector<NodeGadget *> &>( connectedNodeGadgets ), direction, degreesOfSeparation ); } void GraphGadget::connectedNodeGadgetsWalk( NodeGadget *gadget, std::set<NodeGadget *> &connectedNodeGadgets, Gaffer::Plug::Direction direction, size_t degreesOfSeparation ) { if( !degreesOfSeparation ) { return; } for( Gaffer::RecursivePlugIterator it( gadget->node() ); !it.done(); ++it ) { Gaffer::Plug *plug = it->get(); if( ( direction != Gaffer::Plug::Invalid ) && ( plug->direction() != direction ) ) { continue; } if( plug->direction() == Gaffer::Plug::In ) { ConnectionGadget *connection = connectionGadget( plug ); Nodule *nodule = connection ? connection->srcNodule() : nullptr; NodeGadget *inputNodeGadget = nodule ? nodeGadget( nodule->plug()->node() ) : nullptr; if( inputNodeGadget ) { if( connectedNodeGadgets.insert( inputNodeGadget ).second ) { // inserted the node for the first time connectedNodeGadgetsWalk( inputNodeGadget, connectedNodeGadgets, direction, degreesOfSeparation - 1 ); } } } else { // output plug for( Gaffer::Plug::OutputContainer::const_iterator oIt = plug->outputs().begin(), eOIt = plug->outputs().end(); oIt != eOIt; oIt++ ) { ConnectionGadget *connection = connectionGadget( *oIt ); Nodule *nodule = connection ? connection->dstNodule() : nullptr; NodeGadget *outputNodeGadget = nodule ? nodeGadget( nodule->plug()->node() ) : nullptr; if( outputNodeGadget ) { if( connectedNodeGadgets.insert( outputNodeGadget ).second ) { // inserted the node for the first time connectedNodeGadgetsWalk( outputNodeGadget, connectedNodeGadgets, direction, degreesOfSeparation - 1 ); } } } } } } size_t GraphGadget::unpositionedNodeGadgets( std::vector<NodeGadget *> &nodeGadgets ) const { for( NodeGadgetMap::const_iterator it = m_nodeGadgets.begin(), eIt = m_nodeGadgets.end(); it != eIt; ++it ) { if( !hasNodePosition( it->first ) ) { nodeGadgets.push_back( it->second.gadget ); } } return nodeGadgets.size(); } void GraphGadget::setNodePosition( Gaffer::Node *node, const Imath::V2f &position ) { Gaffer::V2fPlug *plug = nodePositionPlug( node, /* createIfMissing = */ true ); plug->setValue( position ); } Imath::V2f GraphGadget::getNodePosition( const Gaffer::Node *node ) const { const Gaffer::V2fPlug *plug = nodePositionPlug( node ); return plug ? plug->getValue() : V2f( 0 ); } bool GraphGadget::hasNodePosition( const Gaffer::Node *node ) const { return nodePositionPlug( node ); } const Gaffer::V2fPlug *GraphGadget::nodePositionPlug( const Gaffer::Node *node ) const { return node->getChild<Gaffer::V2fPlug>( g_positionPlugName ); } Gaffer::V2fPlug *GraphGadget::nodePositionPlug( Gaffer::Node *node, bool createIfMissing ) const { Gaffer::V2fPlug *plug = node->getChild<Gaffer::V2fPlug>( g_positionPlugName ); if( plug || !createIfMissing ) { return plug; } plug = new Gaffer::V2fPlug( g_positionPlugName, Gaffer::Plug::In ); plug->setFlags( Gaffer::Plug::Dynamic, true ); node->addChild( plug ); return plug; } void GraphGadget::setNodeInputConnectionsMinimised( Gaffer::Node *node, bool minimised ) { if( minimised == getNodeInputConnectionsMinimised( node ) ) { return; } Gaffer::BoolPlug *p = node->getChild<Gaffer::BoolPlug>( g_inputConnectionsMinimisedPlugName ); if( !p ) { p = new Gaffer::BoolPlug( g_inputConnectionsMinimisedPlugName, Gaffer::Plug::In, false, Gaffer::Plug::Default | Gaffer::Plug::Dynamic ); node->addChild( p ); } p->setValue( minimised ); } bool GraphGadget::getNodeInputConnectionsMinimised( const Gaffer::Node *node ) const { const Gaffer::BoolPlug *p = node->getChild<Gaffer::BoolPlug>( g_inputConnectionsMinimisedPlugName ); return p ? p->getValue() : false; } void GraphGadget::setNodeOutputConnectionsMinimised( Gaffer::Node *node, bool minimised ) { if( minimised == getNodeOutputConnectionsMinimised( node ) ) { return; } Gaffer::BoolPlug *p = node->getChild<Gaffer::BoolPlug>( g_outputConnectionsMinimisedPlugName ); if( !p ) { p = new Gaffer::BoolPlug( g_outputConnectionsMinimisedPlugName, Gaffer::Plug::In, false, Gaffer::Plug::Default | Gaffer::Plug::Dynamic ); node->addChild( p ); } p->setValue( minimised ); } bool GraphGadget::getNodeOutputConnectionsMinimised( const Gaffer::Node *node ) const { const Gaffer::BoolPlug *p = node->getChild<Gaffer::BoolPlug>( g_outputConnectionsMinimisedPlugName ); return p ? p->getValue() : false; } void GraphGadget::setLayout( GraphLayoutPtr layout ) { m_layout = layout; } GraphLayout *GraphGadget::getLayout() { return m_layout.get(); } const GraphLayout *GraphGadget::getLayout() const { return m_layout.get(); } NodeGadget *GraphGadget::nodeGadgetAt( const IECore::LineSegment3f &lineInGadgetSpace ) const { const ViewportGadget *viewportGadget = ancestor<ViewportGadget>(); std::vector<GadgetPtr> gadgetsUnderMouse; viewportGadget->gadgetsAt( viewportGadget->gadgetToRasterSpace( lineInGadgetSpace.p0, this ), gadgetsUnderMouse ); if( !gadgetsUnderMouse.size() ) { return nullptr; } NodeGadget *nodeGadget = runTimeCast<NodeGadget>( gadgetsUnderMouse[0].get() ); if( !nodeGadget ) { nodeGadget = gadgetsUnderMouse[0]->ancestor<NodeGadget>(); } return nodeGadget; } ConnectionGadget *GraphGadget::connectionGadgetAt( const IECore::LineSegment3f &lineInGadgetSpace ) const { const ViewportGadget *viewportGadget = ancestor<ViewportGadget>(); std::vector<GadgetPtr> gadgetsUnderMouse; viewportGadget->gadgetsAt( viewportGadget->gadgetToRasterSpace( lineInGadgetSpace.p0, this ), gadgetsUnderMouse ); if ( !gadgetsUnderMouse.size() ) { return nullptr; } ConnectionGadget *connectionGadget = runTimeCast<ConnectionGadget>( gadgetsUnderMouse[0].get() ); if ( !connectionGadget ) { connectionGadget = gadgetsUnderMouse[0]->ancestor<ConnectionGadget>(); } return connectionGadget; } ConnectionGadget *GraphGadget::reconnectionGadgetAt( const NodeGadget *gadget, const IECore::LineSegment3f &lineInGadgetSpace ) const { std::vector<GadgetPtr> gadgetsUnderMouse; Imath::V3f center = gadget->transformedBound( this ).center(); const Imath::V3f corner0 = center - Imath::V3f( 2, 2, 1 ); const Imath::V3f corner1 = center + Imath::V3f( 2, 2, 1 ); std::vector<IECoreGL::HitRecord> selection; { ViewportGadget::SelectionScope selectionScope( corner0, corner1, this, selection, IECoreGL::Selector::IDRender ); for ( ChildContainer::const_iterator it = children().begin(); it != children().end(); ++it ) { if ( ConnectionGadget *c = IECore::runTimeCast<ConnectionGadget>( it->get() ) ) { // don't consider the node's own connections, or connections without a source nodule if ( c->srcNodule() && gadget->node() != c->srcNodule()->plug()->node() && gadget->node() != c->dstNodule()->plug()->node() ) { c->render(); } } } } for ( std::vector<IECoreGL::HitRecord>::const_iterator it = selection.begin(); it != selection.end(); ++it ) { GadgetPtr gadget = Gadget::select( it->name ); if ( gadget ) { return runTimeCast<ConnectionGadget>( gadget.get() ); } } return nullptr; } void GraphGadget::doRenderLayer( Layer layer, const Style *style ) const { Gadget::doRenderLayer( layer, style ); glDisable( GL_DEPTH_TEST ); switch( layer ) { case GraphLayer::Connections : // render the new drag connections if they exist if ( m_dragReconnectCandidate ) { if ( m_dragReconnectDstNodule ) { const Nodule *srcNodule = m_dragReconnectCandidate->srcNodule(); const NodeGadget *srcNodeGadget = nodeGadget( srcNodule->plug()->node() ); const Imath::V3f srcP = srcNodule->fullTransform( this ).translation(); const Imath::V3f dstP = m_dragReconnectDstNodule->fullTransform( this ).translation(); const Imath::V3f dstTangent = nodeGadget( m_dragReconnectDstNodule->plug()->node() )->connectionTangent( m_dragReconnectDstNodule ); /// \todo: can there be a highlighted/dashed state? style->renderConnection( srcP, srcNodeGadget->connectionTangent( srcNodule ), dstP, dstTangent, Style::HighlightedState ); } if ( m_dragReconnectSrcNodule ) { const Nodule *dstNodule = m_dragReconnectCandidate->dstNodule(); const NodeGadget *dstNodeGadget = nodeGadget( dstNodule->plug()->node() ); const Imath::V3f srcP = m_dragReconnectSrcNodule->fullTransform( this ).translation(); const Imath::V3f dstP = dstNodule->fullTransform( this ).translation(); const Imath::V3f srcTangent = nodeGadget( m_dragReconnectSrcNodule->plug()->node() )->connectionTangent( m_dragReconnectSrcNodule ); /// \todo: can there be a highlighted/dashed state? style->renderConnection( srcP, srcTangent, dstP, dstNodeGadget->connectionTangent( dstNodule ), Style::HighlightedState ); } } break; case GraphLayer::Overlay : // render drag select thing if needed if( m_dragMode == Selecting ) { const ViewportGadget *viewportGadget = ancestor<ViewportGadget>(); ViewportGadget::RasterScope rasterScope( viewportGadget ); Box2f b; b.extendBy( viewportGadget->gadgetToRasterSpace( V3f( m_dragStartPosition.x, m_dragStartPosition.y, 0 ), this ) ); b.extendBy( viewportGadget->gadgetToRasterSpace( V3f( m_lastDragPosition.x, m_lastDragPosition.y, 0 ), this ) ); style->renderSelectionBox( b ); } break; default: break; } } bool GraphGadget::keyPressed( GadgetPtr gadget, const KeyEvent &event ) { if( event.key == "D" ) { /// \todo This functionality would be better provided by a config file, /// rather than being hardcoded in here. For that to be done easily we /// need a static keyPressSignal() in Widget, which needs figuring out /// some more before we commit to it. In the meantime, this will do. Gaffer::UndoScope undoScope( m_scriptNode ); Gaffer::Set *selection = m_scriptNode->selection(); for( size_t i = 0, s = selection->size(); i != s; i++ ) { Gaffer::DependencyNode *node = IECore::runTimeCast<Gaffer::DependencyNode>( selection->member( i ) ); if( node && findNodeGadget( node ) && !Gaffer::MetadataAlgo::readOnly( node ) ) { Gaffer::BoolPlug *enabledPlug = node->enabledPlug(); if( enabledPlug && enabledPlug->settable() ) { enabledPlug->setValue( !enabledPlug->getValue() ); } } } } return false; } void GraphGadget::rootChildAdded( Gaffer::GraphComponent *root, Gaffer::GraphComponent *child ) { Gaffer::Node *node = IECore::runTimeCast<Gaffer::Node>( child ); if( node && ( !m_filter || m_filter->contains( node ) ) ) { if( !findNodeGadget( node ) ) { if( NodeGadget *g = addNodeGadget( node ) ) { addConnectionGadgets( g ); } } } } void GraphGadget::rootChildRemoved( Gaffer::GraphComponent *root, Gaffer::GraphComponent *child ) { Gaffer::Node *node = IECore::runTimeCast<Gaffer::Node>( child ); if( node ) { removeNodeGadget( node ); } } void GraphGadget::selectionMemberAdded( Gaffer::Set *set, IECore::RunTimeTyped *member ) { if( Gaffer::Node *node = runTimeCast<Gaffer::Node>( member ) ) { if( NodeGadget *nodeGadget = findNodeGadget( node ) ) { nodeGadget->setHighlighted( true ); } } } void GraphGadget::selectionMemberRemoved( Gaffer::Set *set, IECore::RunTimeTyped *member ) { if( Gaffer::Node *node = runTimeCast<Gaffer::Node>( member ) ) { if( NodeGadget *nodeGadget = findNodeGadget( node ) ) { nodeGadget->setHighlighted( false ); } } } void GraphGadget::filterMemberAdded( Gaffer::Set *set, IECore::RunTimeTyped *member ) { Gaffer::Node *node = IECore::runTimeCast<Gaffer::Node>( member ); if( node && node->parent<Gaffer::Node>() == m_root ) { if( !findNodeGadget( node ) ) { if( NodeGadget * g = addNodeGadget( node ) ) { addConnectionGadgets( g ); } } } } void GraphGadget::filterMemberRemoved( Gaffer::Set *set, IECore::RunTimeTyped *member ) { Gaffer::Node *node = IECore::runTimeCast<Gaffer::Node>( member ); if( node ) { removeNodeGadget( node ); } } void GraphGadget::inputChanged( Gaffer::Plug *dstPlug ) { Nodule *nodule = findNodule( dstPlug ); if( !nodule ) { return; } removeConnectionGadget( nodule ); if( !dstPlug->getInput<Gaffer::Plug>() ) { // it's a disconnection, no need to make a new gadget. return; } if( dstPlug->direction() == Gaffer::Plug::Out ) { // it's an internal connection - no need to // represent it. return; } addConnectionGadget( nodule ); } void GraphGadget::plugSet( Gaffer::Plug *plug ) { const InternedString &name = plug->getName(); if( name==g_positionPlugName ) { Gaffer::Node *node = plug->node(); NodeGadget *ng = findNodeGadget( node ); if( ng ) { updateNodeGadgetTransform( ng ); } } else if( name==g_inputConnectionsMinimisedPlugName || name == g_outputConnectionsMinimisedPlugName ) { std::vector<ConnectionGadget *> connections; connectionGadgets( plug->node(), connections ); for( std::vector<ConnectionGadget *>::const_iterator it = connections.begin(), eIt = connections.end(); it != eIt; ++it ) { updateConnectionGadgetMinimisation( *it ); } } } void GraphGadget::noduleAdded( Nodule *nodule ) { addConnectionGadgets( nodule ); for( RecursiveNoduleIterator it( nodule ); !it.done(); ++it ) { addConnectionGadgets( it->get() ); } } void GraphGadget::noduleRemoved( Nodule *nodule ) { removeConnectionGadgets( nodule ); for( RecursiveNoduleIterator it( nodule ); !it.done(); ++it ) { removeConnectionGadgets( it->get() ); } } void GraphGadget::nodeMetadataChanged( IECore::TypeId nodeTypeId, IECore::InternedString key, Gaffer::Node *node ) { if( key != g_nodeGadgetTypeName ) { return; } if( node && node->parent() == m_root ) { // Metadata change for one instance removeNodeGadget( node ); if( NodeGadget *g = addNodeGadget( node ) ) { addConnectionGadgets( g ); } return; } else { // In theory we should test all children of the root // here, but in practice it's only ever per-instance // metadata that changes at runtime. } } bool GraphGadget::buttonRelease( GadgetPtr gadget, const ButtonEvent &event ) { return true; } bool GraphGadget::buttonPress( GadgetPtr gadget, const ButtonEvent &event ) { if( event.buttons==ButtonEvent::Left ) { // selection/deselection if( !m_scriptNode ) { return false; } ViewportGadget *viewportGadget = ancestor<ViewportGadget>(); std::vector<GadgetPtr> gadgetsUnderMouse; viewportGadget->gadgetsAt( viewportGadget->gadgetToRasterSpace( event.line.p0, this ), gadgetsUnderMouse ); if( !gadgetsUnderMouse.size() || gadgetsUnderMouse[0] == this ) { // background click. clear selection unless a modifier is held, in // which case we're expecting a drag to modify the selection. if( !(event.modifiers & ButtonEvent::Shift) && !(event.modifiers & ButtonEvent::Control) ) { m_scriptNode->selection()->clear(); } return true; } NodeGadget *nodeGadget = runTimeCast<NodeGadget>( gadgetsUnderMouse[0].get() ); if( !nodeGadget ) { nodeGadget = gadgetsUnderMouse[0]->ancestor<NodeGadget>(); } if( nodeGadget ) { Gaffer::Node *node = nodeGadget->node(); bool shiftHeld = event.modifiers & ButtonEvent::Shift; bool controlHeld = event.modifiers & ButtonEvent::Control; bool nodeSelected = m_scriptNode->selection()->contains( node ); std::vector<Gaffer::Node *> affectedNodes; if( const BackdropNodeGadget *backdrop = runTimeCast<BackdropNodeGadget>( nodeGadget ) ) { if( !controlHeld ) { backdrop->framed( affectedNodes ); } } if( ( event.modifiers & ButtonEvent::Alt ) && ( controlHeld || shiftHeld ) ) { std::vector<NodeGadget *> connected; connectedNodeGadgets( node, connected, event.modifiers & ButtonEvent::Shift ? Gaffer::Plug::In : Gaffer::Plug::Out ); for( std::vector<NodeGadget *>::const_iterator it = connected.begin(), eIt = connected.end(); it != eIt; ++it ) { affectedNodes.push_back( (*it)->node() ); } } affectedNodes.push_back( node ); if( nodeSelected ) { if( controlHeld ) { m_scriptNode->selection()->remove( affectedNodes.begin(), affectedNodes.end() ); } } else { if( !controlHeld && !shiftHeld ) { m_scriptNode->selection()->clear(); } m_scriptNode->selection()->add( affectedNodes.begin(), affectedNodes.end() ); } return true; } } else if( event.buttons == ButtonEvent::Middle ) { // potentially the start of a middle button drag on a node return nodeGadgetAt( event.line ); } return false; } IECore::RunTimeTypedPtr GraphGadget::dragBegin( GadgetPtr gadget, const DragDropEvent &event ) { if( !m_scriptNode ) { return nullptr; } V3f i; if( !event.line.intersect( Plane3f( V3f( 0, 0, 1 ), 0 ), i ) ) { return nullptr; } m_dragMode = None; m_dragStartPosition = m_lastDragPosition = V2f( i.x, i.y ); NodeGadget *nodeGadget = nodeGadgetAt( event.line ); if( event.buttons == ButtonEvent::Left ) { if( nodeGadget && m_scriptNode->selection()->contains( nodeGadget->node() ) && !readOnly( m_scriptNode->selection() ) ) { m_dragMode = Moving; // we have to return an object to start the drag but the drag we're // starting is for our purposes only, so we return an object that won't // be accepted by any other drag targets. return IECore::NullObject::defaultNullObject(); } else if( !nodeGadget ) { m_dragMode = Selecting; return IECore::NullObject::defaultNullObject(); } } else if( event.buttons == ButtonEvent::Middle ) { if( nodeGadget ) { m_dragMode = Sending; Pointer::setCurrent( "nodes" ); if( m_scriptNode->selection()->contains( nodeGadget->node() ) ) { return m_scriptNode->selection(); } else { return nodeGadget->node(); } } } return nullptr; } bool GraphGadget::dragEnter( GadgetPtr gadget, const DragDropEvent &event ) { V3f i; if( !event.line.intersect( Plane3f( V3f( 0, 0, 1 ), 0 ), i ) ) { return false; } if( event.sourceGadget != this ) { return false; } if( m_dragMode == Moving ) { calculateDragSnapOffsets( m_scriptNode->selection() ); return true; } else if( m_dragMode == Selecting ) { return true; } return false; } bool GraphGadget::dragMove( GadgetPtr gadget, const DragDropEvent &event ) { if( !m_scriptNode ) { return false; } V3f i; if( !event.line.intersect( Plane3f( V3f( 0, 0, 1 ), 0 ), i ) ) { return false; } if( m_dragMode == Moving ) { const float snapThresh = 1.5; // snap the position using the offsets precomputed in calculateDragSnapOffsets() V2f startPos = V2f( i.x, i.y ); V2f pos = startPos; for( int axis = 0; axis <= 1; ++axis ) { const std::vector<float> &snapOffsets = m_dragSnapOffsets[axis]; float offset = pos[axis] - m_dragStartPosition[axis]; float snappedDist = Imath::limits<float>::max(); float snappedOffset = offset; vector<float>::const_iterator it = lower_bound( snapOffsets.begin(), snapOffsets.end(), offset ); if( it != snapOffsets.end() ) { snappedOffset = *it; snappedDist = fabs( offset - *it ); } if( it != snapOffsets.begin() ) { it--; if( fabs( offset - *it ) < snappedDist ) { snappedDist = fabs( offset - *it ); snappedOffset = *it; } } if( snappedDist < snapThresh ) { pos[axis] = snappedOffset + m_dragStartPosition[axis]; } } // We have sorted the snap points on the X axis, so we just need to check points that are within // the right X range. const std::vector<Imath::V2f> &snapPoints = m_dragSnapPoints; V2f pOffset = startPos - m_dragStartPosition; vector<V2f>::const_iterator pEnd = lower_bound( snapPoints.begin(), snapPoints.end(), pOffset + V2f( snapThresh ), CompareV2fX() ); vector<V2f>::const_iterator pIt = upper_bound( snapPoints.begin(), snapPoints.end(), pOffset - V2f( snapThresh ), CompareV2fX() ); for( ; pIt != pEnd; pIt++ ) { if( fabs( pOffset[1] - (*pIt)[1] ) < snapThresh && fabs( pOffset[0] - (*pIt)[0] ) < snapThresh ) { pos = *pIt + m_dragStartPosition; break; } } // move all the nodes using the snapped offset Gaffer::UndoScope undoScope( m_scriptNode, Gaffer::UndoScope::Enabled, dragMergeGroup() ); offsetNodes( m_scriptNode->selection(), pos - m_lastDragPosition ); m_lastDragPosition = pos; updateDragReconnectCandidate( event ); requestRender(); return true; } else { // we're drag selecting m_lastDragPosition = V2f( i.x, i.y ); updateDragSelection( false, event.modifiers ); requestRender(); return true; } assert( 0 ); // shouldn't get here return false; } void GraphGadget::updateDragReconnectCandidate( const DragDropEvent &event ) { if( m_dragReconnectCandidate ) { m_dragReconnectCandidate->setVisible( true ); } m_dragReconnectCandidate = nullptr; m_dragReconnectSrcNodule = nullptr; m_dragReconnectDstNodule = nullptr; // Find the node being dragged. if( m_scriptNode->selection()->size() != 1 ) { return; } const Gaffer::DependencyNode *node = IECore::runTimeCast<const Gaffer::DependencyNode>( m_scriptNode->selection()->member( 0 ) ); NodeGadget *nodeGadget = this->nodeGadget( node ); if( !node || !nodeGadget ) { return; } // See if it has been dragged onto a connection. ConnectionGadget *connection = reconnectionGadgetAt( nodeGadget, event.line ); if( !connection ) { return; } // See if the node can be sensibly inserted into that connection, // and if so, stash what we need into our m_dragReconnect member // variables for use in dragEnd. for( Gaffer::RecursiveOutputPlugIterator it( node ); !it.done(); ++it ) { // See if the output has a corresponding input, and that // the resulting in/out plug pair can be inserted into the // connection. const Gaffer::Plug *outPlug = it->get(); const Gaffer::Plug *inPlug = node->correspondingInput( outPlug ); if( !inPlug ) { continue; } if( !connection->dstNodule()->plug()->acceptsInput( outPlug ) || !inPlug->acceptsInput( connection->srcNodule()->plug() ) ) { continue; } // Check that this pair of plugs doesn't have existing // connections. We do however allow output connections // provided they are not to plugs in this graph - this // allows us to ignore connections the UI components // make, for instance connecting an output plug into // a View outside the script. if( inPlug->getInput<Gaffer::Plug>() ) { continue; } bool haveOutputs = false; for( Gaffer::Plug::OutputContainer::const_iterator oIt = outPlug->outputs().begin(), oeIt = outPlug->outputs().end(); oIt != oeIt; ++oIt ) { if( m_root->isAncestorOf( *oIt ) ) { haveOutputs = true; break; } } if( haveOutputs ) { continue; } // Check that our plugs are represented in the graph. // If they are, we've found a valid place to insert the // dragged node. Nodule *inNodule = nodeGadget->nodule( inPlug ); Nodule *outNodule = nodeGadget->nodule( outPlug ); if( inNodule && outNodule ) { m_dragReconnectCandidate = connection; m_dragReconnectDstNodule = inNodule; m_dragReconnectSrcNodule = outNodule; m_dragReconnectCandidate->setVisible( false ); return; } } } bool GraphGadget::dragEnd( GadgetPtr gadget, const DragDropEvent &event ) { DragMode dragMode = m_dragMode; m_dragMode = None; Pointer::setCurrent( "" ); if( !m_scriptNode ) { return false; } V3f i; if( !event.line.intersect( Plane3f( V3f( 0, 0, 1 ), 0 ), i ) ) { return false; } if( dragMode == Moving ) { if( m_dragReconnectCandidate ) { Gaffer::UndoScope undoScope( m_scriptNode, Gaffer::UndoScope::Enabled, dragMergeGroup() ); m_dragReconnectDstNodule->plug()->setInput( m_dragReconnectCandidate->srcNodule()->plug() ); m_dragReconnectCandidate->dstNodule()->plug()->setInput( m_dragReconnectSrcNodule->plug() ); } m_dragReconnectCandidate = nullptr; m_dragMergeGroupId++; requestRender(); } else if( dragMode == Selecting ) { updateDragSelection( true, event.modifiers ); requestRender(); } return true; } void GraphGadget::calculateDragSnapOffsets( Gaffer::Set *nodes ) { m_dragSnapOffsets[0].clear(); m_dragSnapOffsets[1].clear(); m_dragSnapPoints.clear(); std::vector<const ConnectionGadget *> connections; for( size_t i = 0, s = nodes->size(); i < s; ++i ) { Gaffer::Node *node = runTimeCast<Gaffer::Node>( nodes->member( i ) ); if( !node ) { continue; } connections.clear(); connectionGadgets( node, connections, nodes ); for( std::vector<const ConnectionGadget *>::const_iterator it = connections.begin(), eIt = connections.end(); it != eIt; ++it ) { // get the node gadgets at either end of the connection const ConnectionGadget *connection = *it; const Nodule *srcNodule = connection->srcNodule(); if( !srcNodule ) { continue; } const Nodule *dstNodule = connection->dstNodule(); const NodeGadget *srcNodeGadget = srcNodule->ancestor<NodeGadget>(); const NodeGadget *dstNodeGadget = dstNodule->ancestor<NodeGadget>(); if( !srcNodeGadget || !dstNodeGadget ) { continue; } // check that the connection tangents are opposed - if not we don't want to snap V3f srcTangent = srcNodeGadget->connectionTangent( srcNodule ); V3f dstTangent = dstNodeGadget->connectionTangent( dstNodule ); if( srcTangent.dot( dstTangent ) > -0.5f ) { continue; } // compute an offset that will bring the src and destination nodules into line const int snapAxis = fabs( srcTangent.x ) > 0.5 ? 1 : 0; V3f srcPosition = V3f( 0 ) * srcNodule->fullTransform(); V3f dstPosition = V3f( 0 ) * dstNodule->fullTransform(); float offset = srcPosition[snapAxis] - dstPosition[snapAxis]; if( dstNodule->plug()->node() != node ) { offset *= -1; } m_dragSnapOffsets[snapAxis].push_back( offset ); // compute an offset that will bring the src and destination nodes into line V3f srcNodePosition = V3f( 0 ) * srcNodeGadget->fullTransform(); V3f dstNodePosition = V3f( 0 ) * dstNodeGadget->fullTransform(); float nodeOffset = srcNodePosition[snapAxis] - dstNodePosition[snapAxis]; if( dstNodule->plug()->node() != node ) { nodeOffset *= -1; } m_dragSnapOffsets[snapAxis].push_back( nodeOffset ); // compute an offset that will position the node neatly next to its input // in the other axis. Box3f srcNodeBound = srcNodeGadget->transformedBound( nullptr ); Box3f dstNodeBound = dstNodeGadget->transformedBound( nullptr ); const int otherAxis = snapAxis == 1 ? 0 : 1; float baseOffsetOtherAxis; float offsetDirectionOtherAxis; if( otherAxis == 1 ) { baseOffsetOtherAxis = dstNodeBound.max[otherAxis] - srcNodeBound.min[otherAxis]; offsetDirectionOtherAxis = 1.0f; } else { baseOffsetOtherAxis = dstNodeBound.min[otherAxis] - srcNodeBound.max[otherAxis]; offsetDirectionOtherAxis = -1.0f; } if( dstNodule->plug()->node() == node ) { baseOffsetOtherAxis *= -1; offsetDirectionOtherAxis *= -1; } m_dragSnapOffsets[otherAxis].push_back( baseOffsetOtherAxis + 4.0f * offsetDirectionOtherAxis ); if( snapAxis == 0 ) { m_dragSnapPoints.push_back( Imath::V2f( offset, baseOffsetOtherAxis + 1.5f * offsetDirectionOtherAxis ) ); } else { m_dragSnapPoints.push_back( Imath::V2f( baseOffsetOtherAxis + 1.5f * offsetDirectionOtherAxis, offset ) ); } } } // sort and remove duplicates so that we can use lower_bound() to find appropriate // snap points in dragMove(). for( int axis = 0; axis <= 1; ++axis ) { std::sort( m_dragSnapOffsets[axis].begin(), m_dragSnapOffsets[axis].end() ); m_dragSnapOffsets[axis].erase( std::unique( m_dragSnapOffsets[axis].begin(), m_dragSnapOffsets[axis].end()), m_dragSnapOffsets[axis].end() ); } std::sort( m_dragSnapPoints.begin(), m_dragSnapPoints.end(), CompareV2fX() ); } void GraphGadget::offsetNodes( Gaffer::Set *nodes, const Imath::V2f &offset ) { SetPositionsActionPtr action = new SetPositionsAction( m_root.get() ); for( size_t i = 0, e = nodes->size(); i < e; i++ ) { Gaffer::Node *node = runTimeCast<Gaffer::Node>( nodes->member( i ) ); if( !node ) { continue; } NodeGadget *gadget = nodeGadget( node ); if( gadget ) { Gaffer::V2fPlug *p = nodePositionPlug( node, /* createIfMissing = */ true ); action->addOffset( p, offset ); } } Gaffer::Action::enact( action ); } std::string GraphGadget::dragMergeGroup() const { return boost::str( boost::format( "GraphGadget%1%%2%" ) % this % m_dragMergeGroupId ); } void GraphGadget::updateDragSelection( bool dragEnd, ModifiableEvent::Modifiers modifiers ) { Box2f selectionBound; selectionBound.extendBy( m_dragStartPosition ); selectionBound.extendBy( m_lastDragPosition ); for( NodeGadgetMap::const_iterator it = m_nodeGadgets.begin(), eIt = m_nodeGadgets.end(); it != eIt; ++it ) { NodeGadget *nodeGadget = it->second.gadget; const Box3f nodeBound3 = nodeGadget->transformedBound(); const Box2f nodeBound2( V2f( nodeBound3.min.x, nodeBound3.min.y ), V2f( nodeBound3.max.x, nodeBound3.max.y ) ); if( boxContains( selectionBound, nodeBound2 ) ) { bool removeFromSelection = modifiers & DragDropEvent::Control; nodeGadget->setHighlighted( !removeFromSelection ); if( !dragEnd ) { continue; } if( removeFromSelection ) { m_scriptNode->selection()->remove( const_cast<Gaffer::Node *>( it->first ) ); } else { m_scriptNode->selection()->add( const_cast<Gaffer::Node *>( it->first ) ); } } else { nodeGadget->setHighlighted( m_scriptNode->selection()->contains( it->first ) ); } } } void GraphGadget::updateGraph() { // first remove any gadgets we don't need any more for( NodeGadgetMap::iterator it = m_nodeGadgets.begin(); it != m_nodeGadgets.end(); ) { const Gaffer::Node *node = it->first; it++; // increment now as the iterator will be invalidated by removeNodeGadget() if( (m_filter && !m_filter->contains( node )) || node->parent<Gaffer::Node>() != m_root ) { removeNodeGadget( node ); } } // now make sure we have gadgets for all the nodes we're meant to display for( Gaffer::NodeIterator it( m_root.get() ); !it.done(); ++it ) { if( !m_filter || m_filter->contains( it->get() ) ) { if( !findNodeGadget( it->get() ) ) { addNodeGadget( it->get() ); } } } // and that we have gadgets for each connection for( NodeGadgetMap::iterator it = m_nodeGadgets.begin(); it != m_nodeGadgets.end(); ++it ) { addConnectionGadgets( it->second.gadget ); } } NodeGadget *GraphGadget::addNodeGadget( Gaffer::Node *node ) { NodeGadgetPtr nodeGadget = NodeGadget::create( node ); if( !nodeGadget ) { return nullptr; } addChild( nodeGadget ); NodeGadgetEntry &nodeGadgetEntry = m_nodeGadgets[node]; nodeGadgetEntry.inputChangedConnection = node->plugInputChangedSignal().connect( boost::bind( &GraphGadget::inputChanged, this, ::_1 ) ); nodeGadgetEntry.plugSetConnection = node->plugSetSignal().connect( boost::bind( &GraphGadget::plugSet, this, ::_1 ) ); nodeGadgetEntry.noduleAddedConnection = nodeGadget->noduleAddedSignal().connect( boost::bind( &GraphGadget::noduleAdded, this, ::_2 ) ); nodeGadgetEntry.noduleRemovedConnection = nodeGadget->noduleRemovedSignal().connect( boost::bind( &GraphGadget::noduleRemoved, this, ::_2 ) ); nodeGadgetEntry.gadget = nodeGadget.get(); // highlight to reflect selection status if( m_scriptNode && m_scriptNode->selection()->contains( node ) ) { nodeGadget->setHighlighted( true ); } updateNodeGadgetTransform( nodeGadget.get() ); return nodeGadget.get(); } void GraphGadget::removeNodeGadget( const Gaffer::Node *node ) { NodeGadgetMap::iterator it = m_nodeGadgets.find( node ); if( it!=m_nodeGadgets.end() ) { removeConnectionGadgets( it->second.gadget ); removeChild( it->second.gadget ); m_nodeGadgets.erase( it ); } } NodeGadget *GraphGadget::findNodeGadget( const Gaffer::Node *node ) const { NodeGadgetMap::const_iterator it = m_nodeGadgets.find( node ); if( it==m_nodeGadgets.end() ) { return nullptr; } return it->second.gadget; } void GraphGadget::updateNodeGadgetTransform( NodeGadget *nodeGadget ) { Gaffer::Node *node = nodeGadget->node(); M44f m; if( Gaffer::V2fPlug *p = nodePositionPlug( node, /* createIfMissing = */ false ) ) { const V2f t = p->getValue(); m.translate( V3f( t[0], t[1], 0 ) ); } nodeGadget->setTransform( m ); } void GraphGadget::addConnectionGadgets( NodeGadget *nodeGadget ) { for( RecursiveNoduleIterator it( nodeGadget ); !it.done(); ++it ) { addConnectionGadgets( it->get() ); } } Nodule *GraphGadget::findNodule( const Gaffer::Plug *plug ) const { NodeGadget *g = findNodeGadget( plug->node() ); return g ? g->nodule( plug ) : nullptr; } void GraphGadget::addConnectionGadgets( Nodule *nodule ) { if( nodule->plug()->direction() == Gaffer::Plug::In ) { if( !findConnectionGadget( nodule ) ) { addConnectionGadget( nodule ); } } else { // Reconnect any old output connections which may have been dangling for( Gaffer::Plug::OutputContainer::const_iterator oIt( nodule->plug()->outputs().begin() ); oIt!= nodule->plug()->outputs().end(); ++oIt ) { ConnectionGadget *connection = findConnectionGadget( *oIt ); if( connection && connection->srcNodule() != nodule ) { assert( connection->dstNodule()->plug()->getInput<Gaffer::Plug>() == nodule->plug() ); connection->setNodules( nodule, connection->dstNodule() ); } } } } void GraphGadget::addConnectionGadget( Nodule *dstNodule ) { Gaffer::Plug *dstPlug = dstNodule->plug(); Gaffer::Plug *srcPlug = dstPlug->getInput<Gaffer::Plug>(); if( !srcPlug ) { // there is no connection return; } Gaffer::Node *srcNode = srcPlug->node(); if( srcNode == dstPlug->node() ) { // we don't want to visualise connections between plugs // on the same node. return; } Nodule *srcNodule = findNodule( srcPlug ); ConnectionGadgetPtr connection = ConnectionGadget::create( srcNodule, dstNodule ); updateConnectionGadgetMinimisation( connection.get() ); addChild( connection ); m_connectionGadgets[dstNodule] = connection.get(); } void GraphGadget::removeConnectionGadgets( const NodeGadget *nodeGadget ) { for( RecursiveNoduleIterator it( nodeGadget ); !it.done(); ++it ) { removeConnectionGadgets( it->get() ); } } void GraphGadget::removeConnectionGadgets( const Nodule *nodule ) { if( nodule->plug()->direction() == Gaffer::Plug::In ) { removeConnectionGadget( nodule ); } else { // make output connection gadgets dangle for( Gaffer::Plug::OutputContainer::const_iterator oIt( nodule->plug()->outputs().begin() ); oIt != nodule->plug()->outputs().end(); oIt++ ) { if( ConnectionGadget *connection = findConnectionGadget( *oIt ) ) { if( connection->srcNodule() == nodule ) { connection->setNodules( nullptr, connection->dstNodule() ); } } } } } void GraphGadget::removeConnectionGadget( const Nodule *dstNodule ) { ConnectionGadgetMap::iterator it = m_connectionGadgets.find( dstNodule ); if( it == m_connectionGadgets.end() ) { return; } removeChild( it->second ); m_connectionGadgets.erase( it ); } ConnectionGadget *GraphGadget::findConnectionGadget( const Nodule *dstNodule ) const { ConnectionGadgetMap::const_iterator it = m_connectionGadgets.find( dstNodule ); if( it==m_connectionGadgets.end() ) { return nullptr; } return it->second; } ConnectionGadget *GraphGadget::findConnectionGadget( const Gaffer::Plug *plug ) const { Nodule *nodule = findNodule( plug ); if( !nodule ) { return nullptr; } return findConnectionGadget( nodule ); } void GraphGadget::updateConnectionGadgetMinimisation( ConnectionGadget *gadget ) { bool minimised = getNodeInputConnectionsMinimised( gadget->dstNodule()->plug()->node() ); if( const Nodule *srcNodule = gadget->srcNodule() ) { minimised = minimised || getNodeOutputConnectionsMinimised( srcNodule->plug()->node() ); } gadget->setMinimised( minimised ); }
28.868407
208
0.69391
[ "render", "object", "vector" ]
b4c7d91c36da68775f26fd1c24a4e1b065cdf4f6
11,433
cpp
C++
libraries/egenesis/embed_genesis.cpp
nathanhourt/peerplays
a5a78dacf143e6b685ff2aab4834f33fa5d0e1df
[ "MIT" ]
null
null
null
libraries/egenesis/embed_genesis.cpp
nathanhourt/peerplays
a5a78dacf143e6b685ff2aab4834f33fa5d0e1df
[ "MIT" ]
1
2021-11-14T15:47:29.000Z
2021-11-14T16:17:53.000Z
libraries/egenesis/embed_genesis.cpp
nathanhourt/peerplays
a5a78dacf143e6b685ff2aab4834f33fa5d0e1df
[ "MIT" ]
2
2021-11-12T00:38:23.000Z
2021-12-04T12:14:16.000Z
/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * 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 <cstdlib> #include <iostream> #include <string> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include <boost/algorithm/string.hpp> #include <fc/filesystem.hpp> #include <fc/string.hpp> #include <fc/io/fstream.hpp> #include <fc/io/json.hpp> #include <graphene/chain/genesis_state.hpp> #include <graphene/protocol/types.hpp> // we need to include the world in order to serialize fee_parameters #include <graphene/protocol/fee_schedule.hpp> using namespace graphene::chain; static const char generated_file_banner[] = "// _ _ __ _ _ //\n" "// | | | | / _(_) | //\n" "// __ _ ___ _ __ ___ _ __ __ _| |_ ___ __| | | |_ _| | ___ //\n" "// / _` |/ _ \\ '_ \\ / _ \\ '__/ _` | __/ _ \\/ _` | | _| | |/ _ \\ //\n" "// | (_| | __/ | | | __/ | | (_| | || __/ (_| | | | | | | __/ //\n" "// \\__, |\\___|_| |_|\\___|_| \\__,_|\\__\\___|\\__,_| |_| |_|_|\\___| //\n" "// __/ | //\n" "// |___/ //\n" "// //\n" "// Generated by: libraries/chain_id/identify_chain.cpp //\n" "// //\n" "// Warning: This is a generated file, any changes made here will be //\n" "// overwritten by the build process. If you need to change what //\n" "// is generated here, you should use the CMake variable //\n" "// GRAPHENE_EGENESIS_JSON to specify an embedded genesis state. //\n" "// //\n" ; // hack: import create_example_genesis() even though it's a way, way // specific internal detail namespace graphene { namespace app { namespace detail { genesis_state_type create_example_genesis(); } } } // graphene::app::detail fc::path get_path( const boost::program_options::variables_map& options, const std::string& name ) { fc::path result = options[name].as<boost::filesystem::path>(); if( result.is_relative() ) result = fc::current_path() / result; return result; } void convert_to_c_array( const std::string& src, std::string& dest, int width = 40 ) { dest.reserve( src.length() * 6 / 5 ); bool needs_comma = false; int row = 0; for( std::string::size_type i=0; i<src.length(); i+=width ) { std::string::size_type j = std::min( i+width, src.length() ); if( needs_comma ) dest.append(",\n"); dest.append("\""); for( std::string::size_type k=i; k<j; k++ ) { char c = src[k]; switch(c) { // use most short escape sequences case '\"': dest.append("\\\""); break; case '\?': dest.append("\\\?"); break; case '\\': dest.append("\\\\"); break; case '\a': dest.append( "\\a"); break; case '\b': dest.append( "\\b"); break; case '\f': dest.append( "\\f"); break; case '\n': dest.append( "\\n"); break; case '\r': dest.append( "\\r"); break; case '\t': dest.append( "\\t"); break; case '\v': dest.append( "\\v"); break; // single quote and misc. ASCII is OK case '\'': case ' ': case '!': case '#': case '$': case '%': case '&': case '(': case ')': case '*': case '+': case ',': case '-': case '.': case '/': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case ':': case ';': case '<': case '=': case '>': case '@': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '[': case ']': case '^': case '_': case '`': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case '{': case '|': case '}': case '~': dest.append(&c, 1); break; // use shortest octal escape for everything else default: dest.append("\\"); char dg[3]; dg[0] = '0' + ((c >> 6) & 3); dg[1] = '0' + ((c >> 3) & 7); dg[2] = '0' + ((c ) & 7); int start = (dg[0] == '0' ? (dg[1] == '0' ? 2 : 1) : 0); dest.append( dg+start, 3-start ); } } dest.append("\""); needs_comma = true; row++; } std::cerr << "\n"; return; } struct egenesis_info { fc::optional< genesis_state_type > genesis; fc::optional< chain_id_type > chain_id; fc::optional< std::string > genesis_json; fc::optional< fc::sha256 > genesis_json_hash; fc::optional< std::string > genesis_json_array; int genesis_json_array_width, genesis_json_array_height; void fillin() { // must specify either genesis_json or genesis if( genesis.valid() ) { if( !genesis_json.valid() ) // If genesis_json not exist, generate from genesis genesis_json = fc::json::to_string( *genesis ); } else if( genesis_json.valid() ) { // If genesis not exist, generate from genesis_json try { genesis = fc::json::from_string( *genesis_json ).as< genesis_state_type >( 20 ); } catch (const fc::exception& e) { edump((e)); throw; } } else { // Neither genesis nor genesis_json exists, crippled std::cerr << "embed_genesis: Need genesis or genesis_json\n"; exit(1); } // init genesis_json_hash from genesis_json if( !genesis_json_hash.valid() ) genesis_json_hash = fc::sha256::hash( *genesis_json ); // init chain_id from genesis_json_hash if( !chain_id.valid() ) chain_id = genesis_json_hash; // init genesis_json_array from genesis_json if( !genesis_json_array.valid() ) { genesis_json_array = std::string(); // TODO: gzip int width = 40; convert_to_c_array( *genesis_json, *genesis_json_array, width ); int height = (genesis_json->length() + width-1) / width; genesis_json_array_width = width; genesis_json_array_height = height; } } }; void load_genesis( const boost::program_options::variables_map& options, egenesis_info& info ) { if( options.count("genesis-json") ) { fc::path genesis_json_filename = get_path( options, "genesis-json" ); std::cerr << "embed_genesis: Reading genesis from file " << genesis_json_filename.preferred_string() << "\n"; info.genesis_json = std::string(); read_file_contents( genesis_json_filename, *info.genesis_json ); } else info.genesis = graphene::app::detail::create_example_genesis(); if( options.count("chain-id") ) { std::string chain_id_str = options["chain-id"].as<std::string>(); std::cerr << "embed_genesis: Genesis ID from argument is " << chain_id_str << "\n"; info.chain_id = chain_id_str; } } int main( int argc, char** argv ) { int main_return = 0; boost::program_options::options_description cli_options("Graphene Chain Identifier"); cli_options.add_options() ("help,h", "Print this help message and exit.") ("genesis-json,g", boost::program_options::value<boost::filesystem::path>(), "File to read genesis state from") ("tmplsub,t", boost::program_options::value<std::vector< std::string > >()->composing(), "Given argument of form src.cpp.tmpl---dest.cpp, write dest.cpp expanding template invocations in src") ; boost::program_options::variables_map options; try { boost::program_options::store( boost::program_options::parse_command_line(argc, argv, cli_options), options ); } catch (const boost::program_options::error& e) { std::cerr << "embed_genesis: error parsing command line: " << e.what() << "\n"; return 1; } if( options.count("help") ) { std::cout << cli_options << "\n"; return 0; } egenesis_info info; load_genesis( options, info ); info.fillin(); fc::mutable_variant_object template_context = fc::mutable_variant_object() ( "generated_file_banner", generated_file_banner ) ( "chain_id", (*info.chain_id).str() ) ; if( info.genesis_json.valid() ) { template_context["genesis_json_length"] = info.genesis_json->length(); template_context["genesis_json_array"] = (*info.genesis_json_array); template_context["genesis_json_hash"] = (*info.genesis_json_hash).str(); template_context["genesis_json_array_width"] = info.genesis_json_array_width; template_context["genesis_json_array_height"] = info.genesis_json_array_height; } for( const std::string& src_dest : options["tmplsub"].as< std::vector< std::string > >() ) { std::cerr << "embed_genesis: parsing tmplsub parameter \"" << src_dest << "\"\n"; size_t pos = src_dest.find( "---" ); if( pos == std::string::npos ) { std::cerr << "embed_genesis: could not parse tmplsub parameter: '---' not found\n"; main_return = 1; continue; } std::string src = src_dest.substr( 0, pos ); std::string dest = src_dest.substr( pos+3 ); std::string tmpl; read_file_contents( fc::path( src ), tmpl ); std::string out_str = fc::format_string( tmpl, template_context ); fc::path dest_filename = fc::path( dest ); fc::ofstream outfile( dest_filename ); outfile.write( out_str.c_str(), out_str.size() ); outfile.close(); } return main_return; }
38.494949
117
0.56232
[ "vector" ]
b4c814c4ce2c36bb9a6325abb01dede3aa78e00a
12,747
hpp
C++
ios/Pods/boost-for-react-native/boost/accumulators/numeric/functional/vector.hpp
rudylee/expo
b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc
[ "Apache-2.0", "MIT" ]
8,805
2015-11-03T00:52:29.000Z
2022-03-29T22:30:03.000Z
ios/Pods/boost-for-react-native/boost/accumulators/numeric/functional/vector.hpp
rudylee/expo
b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc
[ "Apache-2.0", "MIT" ]
14,694
2015-02-24T15:13:42.000Z
2022-03-31T13:16:45.000Z
ios/Pods/boost-for-react-native/boost/accumulators/numeric/functional/vector.hpp
rudylee/expo
b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc
[ "Apache-2.0", "MIT" ]
1,329
2015-11-03T20:25:51.000Z
2022-03-31T18:10:38.000Z
/////////////////////////////////////////////////////////////////////////////// /// \file vector.hpp /// // Copyright 2005 Eric Niebler. 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 BOOST_NUMERIC_FUNCTIONAL_VECTOR_HPP_EAN_12_12_2005 #define BOOST_NUMERIC_FUNCTIONAL_VECTOR_HPP_EAN_12_12_2005 #ifdef BOOST_NUMERIC_FUNCTIONAL_HPP_INCLUDED # error Include this file before boost/accumulators/numeric/functional.hpp #endif #include <vector> #include <functional> #include <boost/assert.hpp> #include <boost/mpl/and.hpp> #include <boost/mpl/not.hpp> #include <boost/utility/enable_if.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/type_traits/is_scalar.hpp> #include <boost/type_traits/remove_const.hpp> #include <boost/typeof/std/vector.hpp> #include <boost/accumulators/numeric/functional_fwd.hpp> namespace boost { namespace numeric { namespace operators { namespace acc_detail { template<typename Fun> struct make_vector { typedef std::vector<typename Fun::result_type> type; }; } /////////////////////////////////////////////////////////////////////////////// // Handle vector<Left> / Right where Right is a scalar. template<typename Left, typename Right> typename lazy_enable_if< is_scalar<Right> , acc_detail::make_vector<functional::divides<Left, Right> > >::type operator /(std::vector<Left> const &left, Right const &right) { typedef typename functional::divides<Left, Right>::result_type value_type; std::vector<value_type> result(left.size()); for(std::size_t i = 0, size = result.size(); i != size; ++i) { result[i] = numeric::divides(left[i], right); } return result; } /////////////////////////////////////////////////////////////////////////////// // Handle vector<Left> / vector<Right>. template<typename Left, typename Right> std::vector<typename functional::divides<Left, Right>::result_type> operator /(std::vector<Left> const &left, std::vector<Right> const &right) { typedef typename functional::divides<Left, Right>::result_type value_type; std::vector<value_type> result(left.size()); for(std::size_t i = 0, size = result.size(); i != size; ++i) { result[i] = numeric::divides(left[i], right[i]); } return result; } /////////////////////////////////////////////////////////////////////////////// // Handle vector<Left> * Right where Right is a scalar. template<typename Left, typename Right> typename lazy_enable_if< is_scalar<Right> , acc_detail::make_vector<functional::multiplies<Left, Right> > >::type operator *(std::vector<Left> const &left, Right const &right) { typedef typename functional::multiplies<Left, Right>::result_type value_type; std::vector<value_type> result(left.size()); for(std::size_t i = 0, size = result.size(); i != size; ++i) { result[i] = numeric::multiplies(left[i], right); } return result; } /////////////////////////////////////////////////////////////////////////////// // Handle Left * vector<Right> where Left is a scalar. template<typename Left, typename Right> typename lazy_enable_if< is_scalar<Left> , acc_detail::make_vector<functional::multiplies<Left, Right> > >::type operator *(Left const &left, std::vector<Right> const &right) { typedef typename functional::multiplies<Left, Right>::result_type value_type; std::vector<value_type> result(right.size()); for(std::size_t i = 0, size = result.size(); i != size; ++i) { result[i] = numeric::multiplies(left, right[i]); } return result; } /////////////////////////////////////////////////////////////////////////////// // Handle vector<Left> * vector<Right> template<typename Left, typename Right> std::vector<typename functional::multiplies<Left, Right>::result_type> operator *(std::vector<Left> const &left, std::vector<Right> const &right) { typedef typename functional::multiplies<Left, Right>::result_type value_type; std::vector<value_type> result(left.size()); for(std::size_t i = 0, size = result.size(); i != size; ++i) { result[i] = numeric::multiplies(left[i], right[i]); } return result; } /////////////////////////////////////////////////////////////////////////////// // Handle vector<Left> + vector<Right> template<typename Left, typename Right> std::vector<typename functional::plus<Left, Right>::result_type> operator +(std::vector<Left> const &left, std::vector<Right> const &right) { typedef typename functional::plus<Left, Right>::result_type value_type; std::vector<value_type> result(left.size()); for(std::size_t i = 0, size = result.size(); i != size; ++i) { result[i] = numeric::plus(left[i], right[i]); } return result; } /////////////////////////////////////////////////////////////////////////////// // Handle vector<Left> - vector<Right> template<typename Left, typename Right> std::vector<typename functional::minus<Left, Right>::result_type> operator -(std::vector<Left> const &left, std::vector<Right> const &right) { typedef typename functional::minus<Left, Right>::result_type value_type; std::vector<value_type> result(left.size()); for(std::size_t i = 0, size = result.size(); i != size; ++i) { result[i] = numeric::minus(left[i], right[i]); } return result; } /////////////////////////////////////////////////////////////////////////////// // Handle vector<Left> += vector<Left> template<typename Left> std::vector<Left> & operator +=(std::vector<Left> &left, std::vector<Left> const &right) { BOOST_ASSERT(left.size() == right.size()); for(std::size_t i = 0, size = left.size(); i != size; ++i) { numeric::plus_assign(left[i], right[i]); } return left; } /////////////////////////////////////////////////////////////////////////////// // Handle -vector<Arg> template<typename Arg> std::vector<typename functional::unary_minus<Arg>::result_type> operator -(std::vector<Arg> const &arg) { typedef typename functional::unary_minus<Arg>::result_type value_type; std::vector<value_type> result(arg.size()); for(std::size_t i = 0, size = result.size(); i != size; ++i) { result[i] = numeric::unary_minus(arg[i]); } return result; } } namespace functional { struct std_vector_tag; template<typename T, typename Al> struct tag<std::vector<T, Al> > { typedef std_vector_tag type; }; /////////////////////////////////////////////////////////////////////////////// // element-wise min of std::vector template<typename Left, typename Right> struct min_assign<Left, Right, std_vector_tag, std_vector_tag> : std::binary_function<Left, Right, void> { void operator ()(Left &left, Right &right) const { BOOST_ASSERT(left.size() == right.size()); for(std::size_t i = 0, size = left.size(); i != size; ++i) { if(numeric::less(right[i], left[i])) { left[i] = right[i]; } } } }; /////////////////////////////////////////////////////////////////////////////// // element-wise max of std::vector template<typename Left, typename Right> struct max_assign<Left, Right, std_vector_tag, std_vector_tag> : std::binary_function<Left, Right, void> { void operator ()(Left &left, Right &right) const { BOOST_ASSERT(left.size() == right.size()); for(std::size_t i = 0, size = left.size(); i != size; ++i) { if(numeric::greater(right[i], left[i])) { left[i] = right[i]; } } } }; // partial specialization for std::vector. template<typename Left, typename Right> struct fdiv<Left, Right, std_vector_tag, void> : mpl::if_< are_integral<typename Left::value_type, Right> , divides<Left, double const> , divides<Left, Right> >::type {}; // promote template<typename To, typename From> struct promote<To, From, std_vector_tag, std_vector_tag> : std::unary_function<From, To> { To operator ()(From &arr) const { typename remove_const<To>::type res(arr.size()); for(std::size_t i = 0, size = arr.size(); i != size; ++i) { res[i] = numeric::promote<typename To::value_type>(arr[i]); } return res; } }; template<typename ToFrom> struct promote<ToFrom, ToFrom, std_vector_tag, std_vector_tag> : std::unary_function<ToFrom, ToFrom> { ToFrom &operator ()(ToFrom &tofrom) const { return tofrom; } }; /////////////////////////////////////////////////////////////////////////////// // functional::as_min template<typename T> struct as_min<T, std_vector_tag> : std::unary_function<T, typename remove_const<T>::type> { typename remove_const<T>::type operator ()(T &arr) const { return 0 == arr.size() ? T() : T(arr.size(), numeric::as_min(arr[0])); } }; /////////////////////////////////////////////////////////////////////////////// // functional::as_max template<typename T> struct as_max<T, std_vector_tag> : std::unary_function<T, typename remove_const<T>::type> { typename remove_const<T>::type operator ()(T &arr) const { return 0 == arr.size() ? T() : T(arr.size(), numeric::as_max(arr[0])); } }; /////////////////////////////////////////////////////////////////////////////// // functional::as_zero template<typename T> struct as_zero<T, std_vector_tag> : std::unary_function<T, typename remove_const<T>::type> { typename remove_const<T>::type operator ()(T &arr) const { return 0 == arr.size() ? T() : T(arr.size(), numeric::as_zero(arr[0])); } }; /////////////////////////////////////////////////////////////////////////////// // functional::as_one template<typename T> struct as_one<T, std_vector_tag> : std::unary_function<T, typename remove_const<T>::type> { typename remove_const<T>::type operator ()(T &arr) const { return 0 == arr.size() ? T() : T(arr.size(), numeric::as_one(arr[0])); } }; } // namespace functional }} // namespace boost::numeric #endif
38.627273
90
0.459481
[ "vector" ]
b4c8af18e12fd61e2ea5d6ec4fffec936fc83a2b
3,211
cpp
C++
libs/random/test/test_generate_canonical.cpp
jmuskaan72/Boost
047e36c01841a8cd6a5c74d4e3034da46e327bc1
[ "BSL-1.0" ]
198
2015-01-13T05:47:18.000Z
2022-03-09T04:46:46.000Z
libs/random/test/test_generate_canonical.cpp
xiaoliang2121/Boost
fc90c3fde129c62565c023f091eddc4a7ed9902b
[ "BSL-1.0" ]
4
2015-03-19T08:23:23.000Z
2019-06-24T07:48:47.000Z
libs/random/test/test_generate_canonical.cpp
xiaoliang2121/Boost
fc90c3fde129c62565c023f091eddc4a7ed9902b
[ "BSL-1.0" ]
139
2015-01-15T20:09:31.000Z
2022-01-31T15:21:16.000Z
/* test_generate_canonical.cpp * * Copyright Steven Watanabe 2011 * 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) * * $Id: test_generate_canonical.cpp 71018 2011-04-05 21:27:52Z steven_watanabe $ * */ #include <boost/random/generate_canonical.hpp> #include <boost/random/linear_congruential.hpp> #include <boost/random/mersenne_twister.hpp> #include <boost/random/lagged_fibonacci.hpp> #include <boost/cstdint.hpp> #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> typedef boost::mpl::vector< boost::random::minstd_rand, boost::random::mt19937, boost::random::lagged_fibonacci607 > engines; BOOST_AUTO_TEST_CASE_TEMPLATE(test_float, Engine, engines) { Engine eng; Engine expected; for(int i = 0; i < 1000; ++i) { float val = boost::random::generate_canonical<float, 64>(eng); BOOST_CHECK_GE(val, 0); BOOST_CHECK_LT(val, 1); } expected.discard(1000); BOOST_CHECK_EQUAL(eng, expected); for(int i = 0; i < 1000; ++i) { float val = boost::random::generate_canonical<float, 12>(eng); BOOST_CHECK_GE(val, 0); BOOST_CHECK_LT(val, 1); } expected.discard(1000); BOOST_CHECK_EQUAL(eng, expected); } BOOST_AUTO_TEST_CASE_TEMPLATE(test_double, Engine, engines) { Engine eng; Engine expected; for(int i = 0; i < 1000; ++i) { double val = boost::random::generate_canonical<double, 64>(eng); BOOST_CHECK_GE(val, 0); BOOST_CHECK_LT(val, 1); } expected.discard(2000); BOOST_CHECK_EQUAL(eng, expected); for(int i = 0; i < 1000; ++i) { double val = boost::random::generate_canonical<double, 12>(eng); BOOST_CHECK_GE(val, 0); BOOST_CHECK_LT(val, 1); } expected.discard(1000); BOOST_CHECK_EQUAL(eng, expected); } BOOST_AUTO_TEST_CASE_TEMPLATE(test_long_double, Engine, engines) { Engine eng; Engine expected; for(int i = 0; i < 1000; ++i) { long double val = boost::random::generate_canonical<long double, 60>(eng); BOOST_CHECK_GE(val, 0); BOOST_CHECK_LT(val, 1); } expected.discard(2000); BOOST_CHECK_EQUAL(eng, expected); for(int i = 0; i < 1000; ++i) { long double val = boost::random::generate_canonical<long double, 12>(eng); BOOST_CHECK_GE(val, 0); BOOST_CHECK_LT(val, 1); } expected.discard(1000); BOOST_CHECK_EQUAL(eng, expected); } struct max_engine { typedef boost::uint32_t result_type; static result_type min BOOST_PREVENT_MACRO_SUBSTITUTION () { return 0; } static result_type max BOOST_PREVENT_MACRO_SUBSTITUTION () { return ~boost::uint32_t(0); } result_type operator()() { return (max)(); } }; BOOST_AUTO_TEST_CASE(test_max) { max_engine eng; BOOST_CHECK_LT((boost::random::generate_canonical<float, 64>(eng)), 1); BOOST_CHECK_LT((boost::random::generate_canonical<double, 64>(eng)), 1); BOOST_CHECK_LT((boost::random::generate_canonical<long double, 64>(eng)), 1); }
30.875
83
0.651199
[ "vector" ]
b4cbeaff95481e833a9c58bc05ac362f0d0124b9
28,319
cpp
C++
src/apps/ojph_compress/ojph_compress.cpp
pierrepaleo/OpenJPH
d92d70ca7e6371f7e50642c3e9d26babf7f8f39b
[ "BSD-2-Clause" ]
88
2019-09-26T20:13:32.000Z
2022-03-27T00:23:50.000Z
src/apps/ojph_compress/ojph_compress.cpp
pierrepaleo/OpenJPH
d92d70ca7e6371f7e50642c3e9d26babf7f8f39b
[ "BSD-2-Clause" ]
74
2019-10-23T05:49:36.000Z
2022-03-30T07:58:18.000Z
src/apps/ojph_compress/ojph_compress.cpp
pierrepaleo/OpenJPH
d92d70ca7e6371f7e50642c3e9d26babf7f8f39b
[ "BSD-2-Clause" ]
25
2019-10-26T00:06:56.000Z
2022-02-05T17:02:26.000Z
//***************************************************************************/ // This software is released under the 2-Clause BSD license, included // below. // // Copyright (c) 2019, Aous Naman // Copyright (c) 2019, Kakadu Software Pty Ltd, Australia // Copyright (c) 2019, The University of New South Wales, Australia // // 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. //***************************************************************************/ // This file is part of the OpenJPH software implementation. // File: ojph_compress.cpp // Author: Aous Naman // Date: 28 August 2019 //***************************************************************************/ #include <ctime> #include <iostream> #include "ojph_arg.h" #include "ojph_mem.h" #include "ojph_img_io.h" #include "ojph_file.h" #include "ojph_codestream.h" #include "ojph_params.h" #include "ojph_message.h" ///////////////////////////////////////////////////////////////////////////// struct size_list_interpreter : public ojph::cli_interpreter::arg_inter_base { size_list_interpreter(const int max_num_elements, int& num_elements, ojph::size* list) : max_num_eles(max_num_elements), sizelist(list), num_eles(num_elements) {} virtual void operate(const char *str) { const char *next_char = str; num_eles = 0; do { if (num_eles) { if (*next_char != ',') //separate sizes by a comma throw "sizes in a sizes list must be separated by a comma"; next_char++; } if (*next_char != '{') throw "size must start with {"; next_char++; char *endptr; sizelist[num_eles].w = (int)strtol(next_char, &endptr, 10); if (endptr == next_char) throw "size number is improperly formatted"; next_char = endptr; if (*next_char != ',') throw "size must have a "","" between the two numbers"; next_char++; sizelist[num_eles].h = (int)strtol(next_char, &endptr, 10); if (endptr == next_char) throw "number is improperly formatted"; next_char = endptr; if (*next_char != '}') throw "size must end with }"; next_char++; ++num_eles; } while (*next_char == ',' && num_eles < max_num_eles); if (num_eles < max_num_eles) { if (*next_char) throw "size elements must separated by a "","""; } else if (*next_char) throw "there are too many elements in the size list"; } const int max_num_eles; ojph::size* sizelist; int& num_eles; }; ///////////////////////////////////////////////////////////////////////////// struct point_list_interpreter : public ojph::cli_interpreter::arg_inter_base { point_list_interpreter(const int max_num_elements, int& num_elements, ojph::point* list) : max_num_eles(max_num_elements), pointlist(list), num_eles(num_elements) { } virtual void operate(const char *str) { const char *next_char = str; num_eles = 0; do { if (num_eles) { if (*next_char != ',') //separate sizes by a comma throw "sizes in a sizes list must be separated by a comma"; next_char++; } if (*next_char != '{') throw "size must start with {"; next_char++; char *endptr; pointlist[num_eles].x = (int)strtol(next_char, &endptr, 10); if (endptr == next_char) throw "point number is improperly formatted"; next_char = endptr; if (*next_char != ',') throw "point must have a "","" between the two numbers"; next_char++; pointlist[num_eles].y = (int)strtol(next_char, &endptr, 10); if (endptr == next_char) throw "number is improperly formatted"; next_char = endptr; if (*next_char != '}') throw "point must end with }"; next_char++; ++num_eles; } while (*next_char == ',' && num_eles < max_num_eles); if (num_eles < max_num_eles) { if (*next_char) throw "size elements must separated by a "","""; } else if (*next_char) throw "there are too many elements in the size list"; } const int max_num_eles; ojph::point* pointlist; int& num_eles; }; ///////////////////////////////////////////////////////////////////////////// struct size_interpreter : public ojph::cli_interpreter::arg_inter_base { size_interpreter(ojph::size& val) : val(val) {} virtual void operate(const char *str) { const char *next_char = str; if (*next_char != '{') throw "size must start with {"; next_char++; char *endptr; val.w = (int)strtol(next_char, &endptr, 10); if (endptr == next_char) throw "size number is improperly formatted"; next_char = endptr; if (*next_char != ',') throw "size must have a "","" between the two numbers"; next_char++; val.h = (int)strtol(next_char, &endptr, 10); if (endptr == next_char) throw "number is improperly formatted"; next_char = endptr; if (*next_char != '}') throw "size must end with }"; next_char++; if (*next_char != '\0') //must be end of string throw "size has extra characters"; } ojph::size& val; }; ///////////////////////////////////////////////////////////////////////////// struct point_interpreter : public ojph::cli_interpreter::arg_inter_base { point_interpreter(ojph::point& val) : val(val) {} virtual void operate(const char *str) { const char *next_char = str; if (*next_char != '{') throw "size must start with {"; next_char++; char *endptr; val.x = (int)strtol(next_char, &endptr, 10); if (endptr == next_char) throw "size number is improperly formatted"; next_char = endptr; if (*next_char != ',') throw "size must have a "","" between the two numbers"; next_char++; val.y = (int)strtol(next_char, &endptr, 10); if (endptr == next_char) throw "number is improperly formatted"; next_char = endptr; if (*next_char != '}') throw "size must end with }"; next_char++; if (*next_char != '\0') //must be end of string throw "size has extra characters"; } ojph::point& val; }; ///////////////////////////////////////////////////////////////////////////// struct si32_list_interpreter : public ojph::cli_interpreter::arg_inter_base { si32_list_interpreter(const int max_num_elements, int& num_elements, ojph::si32* list) : max_num_eles(max_num_elements), si32list(list), num_eles(num_elements) {} virtual void operate(const char *str) { const char *next_char = str; num_eles = 0; do { if (num_eles) { if (*next_char != ',') //separate sizes by a comma throw "sizes in a sizes list must be separated by a comma"; next_char++; } char *endptr; si32list[num_eles] = (int)strtol(next_char, &endptr, 10); if (endptr == next_char) throw "size number is improperly formatted"; next_char = endptr; ++num_eles; } while (*next_char == ',' && num_eles < max_num_eles); if (num_eles < max_num_eles) { if (*next_char) throw "list elements must separated by a "","""; } else if (*next_char) throw "there are too many elements in the size list"; } const int max_num_eles; ojph::si32* si32list; int& num_eles; }; ///////////////////////////////////////////////////////////////////////////// struct si32_to_bool_list_interpreter : public ojph::cli_interpreter::arg_inter_base { si32_to_bool_list_interpreter(const int max_num_elements, int& num_elements, ojph::si32* list) : max_num_eles(max_num_elements), boollist(list), num_eles(num_elements) {} virtual void operate(const char *str) { const char *next_char = str; num_eles = 0; do { if (num_eles) { if (*next_char != ',') //separate sizes by a comma throw "sizes in a sizes list must be separated by a comma"; next_char++; } if (strncmp(next_char, "true", 4) == 0) { boollist[num_eles] = 1; next_char += 4; } else if (strncmp(next_char, "false", 5) == 0) { boollist[num_eles] = 0; next_char += 5; } else throw "unknown bool value"; ++num_eles; } while (*next_char == ',' && num_eles < max_num_eles); if (num_eles < max_num_eles) { if (*next_char) throw "size elements must separated by a "","""; } else if (*next_char) throw "there are too many elements in the size list"; } int get_num_elements() { return num_eles; } int max_num_eles; ojph::si32* boollist; int& num_eles; }; ////////////////////////////////////////////////////////////////////////////// bool get_arguments(int argc, char *argv[], char *&input_filename, char *&output_filename, char *&progression_order, char *&profile_string, int &num_decompositions, float &quantization_step, bool &reversible, int &employ_color_transform, const int max_num_precincts, int &num_precincts, ojph::size *precinct_size, ojph::size& block_size, ojph::size& dims, ojph::point& image_offset, ojph::size& tile_size, ojph::point& tile_offset, int& max_num_comps, int& num_comps, int& num_comp_downsamps, ojph::point*& comp_downsamp, int& num_bit_depths, ojph::si32*& bit_depth, int& num_is_signed, int*& is_signed) { ojph::cli_interpreter interpreter; interpreter.init(argc, argv); interpreter.reinterpret("-i", input_filename); interpreter.reinterpret("-o", output_filename); interpreter.reinterpret("-prog_order", progression_order); interpreter.reinterpret("-profile", profile_string); interpreter.reinterpret("-num_decomps", num_decompositions); interpreter.reinterpret("-qstep", quantization_step); interpreter.reinterpret("-reversible", reversible); interpreter.reinterpret_to_bool("-colour_trans", employ_color_transform); interpreter.reinterpret("-num_comps", num_comps); size_interpreter block_interpreter(block_size); size_interpreter dims_interpreter(dims); size_list_interpreter sizelist(max_num_precincts, num_precincts, precinct_size); if (num_comps > 255) throw "more than 255 components is not supported"; if (num_comps > max_num_comps) { max_num_comps = num_comps; comp_downsamp = new ojph::point[num_comps]; bit_depth = new ojph::si32[num_comps]; is_signed = new int[num_comps]; for (int i = 0; i < num_comps; ++i) { comp_downsamp[i] = ojph::point(-1, -1); bit_depth[i] = -1; is_signed[i] = -1; } } point_list_interpreter pointlist(max_num_comps, num_comp_downsamps, comp_downsamp); si32_list_interpreter ilist(max_num_comps, num_bit_depths, bit_depth); si32_to_bool_list_interpreter blist(max_num_comps, num_is_signed, is_signed); point_interpreter img_off_interpreter(image_offset); size_interpreter tile_size_interpreter(tile_size); point_interpreter tile_off_interpreter(tile_offset); try { interpreter.reinterpret("-block_size", &block_interpreter); interpreter.reinterpret("-dims", &dims_interpreter); interpreter.reinterpret("-image_offset", &img_off_interpreter); interpreter.reinterpret("-tile_size", &tile_size_interpreter); interpreter.reinterpret("-tile_offset", &tile_off_interpreter); interpreter.reinterpret("-precincts", &sizelist); interpreter.reinterpret("-downsamp", &pointlist); interpreter.reinterpret("-bit_depth", &ilist); interpreter.reinterpret("-signed", &blist); } catch (const char *s) { printf("%s\n",s); return false; } if (interpreter.is_exhausted() == false) { printf("The following arguments were not interpreted:\n"); ojph::argument t = interpreter.get_argument_zero(); t = interpreter.get_next_avail_argument(t); while (t.is_valid()) { printf("%s\n", t.arg); t = interpreter.get_next_avail_argument(t); } return false; } return true; } ///////////////////////////////////////////////////////////////////////////// const char *get_file_extension(const char *filename) { size_t len = strlen(filename); return filename + (len >= 4 ? len - 4 : 0); } ////////////////////////////////////////////////////////////////////////////// // main ////////////////////////////////////////////////////////////////////////////// int main(int argc, char * argv[]) { char *input_filename = NULL; char *output_filename = NULL; char prog_order_store[] = "RPCL"; char *prog_order = prog_order_store; char profile_string_store[] = ""; char *profile_string = profile_string_store; int num_decompositions = 5; float quantization_step = -1.0; bool reversible = false; int employ_color_transform = -1; const int max_precinct_sizes = 33; //maximum number of decompositions is 32 ojph::size precinct_size[max_precinct_sizes]; int num_precints = -1; ojph::size block_size(64,64); ojph::size dims(-1, -1); ojph::size tile_size(0, 0); ojph::point tile_offset(0, 0); ojph::point image_offset(0, 0); const int initial_num_comps = 4; int max_num_comps = initial_num_comps; int num_components = -1; int num_is_signed = 0; int is_signed_store[initial_num_comps] = {-1, -1, -1, -1}; int *is_signed = is_signed_store; int num_bit_depths = 0; ojph::si32 bit_depth_store[initial_num_comps] = {-1, -1, -1, -1}; ojph::si32 *bit_depth = bit_depth_store; int num_comp_downsamps = 0; ojph::point downsampling_store[initial_num_comps] = { ojph::point(0,0), ojph::point(0,0), ojph::point(0,0), ojph::point(0,0) }; ojph::point *comp_downsampling = downsampling_store; if (argc <= 1) { std::cout << "\nThe following arguments are necessary:\n" " -i input file name\n" " -o output file name\n\n" "The following option has a default value (optional):\n" " -num_decomps (5) number of decompositions\n" " -qstep (0.00001...0.5) quantization step size for lossy\n" " all quantization without 0.00000\n" " step sizes are derived from this. {default for 8bit 0.0039}\n" " -reversible (false) for irreversible; that is,\n" " lossy compression using the 9/7 wavelet transform;\n" " and true for reversible compression; that is,\n" " lossless compression using the 5/3 wavelet transform.\n" " -colour_trans (true) if there are three color components that are\n" " downsampled by the same amount then the color transform\n" " is optional. This option is also available if there are\n" " more than three colour components, where it is applied\n" " to the first three colour components\n" " -prog_order (RPCL) is the progression order, and can be one of:\n" " LRCP, RLCP, RPCL, PCRL, CPRL\n" " -block_size {x,y} (64,64) where x and y are the height and width of\n" " a codeblock. In unix-like environment, { and } must be\n" " proceeded by a ""\\""\n" " -precincts {x,y},{x,y},...,{x,y} where {x,y} is the precinct size\n" " starting from the coarest resolution; the last precinct\n" " is repeated for all finer resolutions\n" " -tile_offset {x,y} tile offset. \n" " -tile_size {x,y} tile width and height. \n" " -image_offset {x,y} image offset from origin. \n" " -profile (None) is the profile, the code will check if the \n" " selected options meet the profile. Currently only \n" " BROADCAST and IMF are supported\n" "\n" "When the input file is a YUV file, these arguments need to be \n" " supplied: \n" " -dims {x,y} x is image width, y is height\n" " -num_comps number of components\n" " -signed a comma-separated list of true or false parameters, one\n" " for each component; for example: true,false,false\n" " -bit_depth a comma-separated list of bit depth values, one per \n" " component; for example: 12,10,10\n" " -downsamp {x,y},{x,y},...,{x,y} a list of x,y points, one for each\n" " component; for example {1,1},{2,2},{2,2}\n\n" ; return -1; } if (!get_arguments(argc, argv, input_filename, output_filename, prog_order, profile_string, num_decompositions, quantization_step, reversible, employ_color_transform, max_precinct_sizes, num_precints, precinct_size, block_size, dims, image_offset, tile_size, tile_offset, max_num_comps, num_components, num_comp_downsamps, comp_downsampling, num_bit_depths, bit_depth, num_is_signed, is_signed)) { return -1; } clock_t begin = clock(); try { ojph::codestream codestream; ojph::ppm_in ppm; ojph::yuv_in yuv; ojph::image_in_base *base = NULL; if (input_filename == NULL) OJPH_ERROR(0x01000007, "please specify an input file name using" " the -i command line option"); if (output_filename == NULL) OJPH_ERROR(0x01000008, "please specify an output file name using" " the -o command line option"); const char *v = get_file_extension(input_filename); if (v) { if (strncmp(".pgm", v, 4) == 0) { ppm.open(input_filename); ojph::param_siz siz = codestream.access_siz(); siz.set_image_extent(ojph::point(image_offset.x + ppm.get_size().w, image_offset.y + ppm.get_size().h)); int num_comps = ppm.get_num_components(); assert(num_comps == 1); siz.set_num_components(num_comps); for (int c = 0; c < num_comps; ++c) siz.set_component(c, ppm.get_comp_subsampling(c), ppm.get_bit_depth(c), ppm.get_is_signed(c)); siz.set_image_offset(image_offset); siz.set_tile_size(tile_size); siz.set_tile_offset(tile_offset); ojph::param_cod cod = codestream.access_cod(); cod.set_num_decomposition(num_decompositions); cod.set_block_dims(block_size.w, block_size.h); if (num_precints != -1) cod.set_precinct_size(num_precints, precinct_size); cod.set_progression_order(prog_order); cod.set_color_transform(false); cod.set_reversible(reversible); if (!reversible && quantization_step != -1) codestream.access_qcd().set_irrev_quant(quantization_step); if (profile_string[0] != '\0') codestream.set_profile(profile_string); if (employ_color_transform != -1) OJPH_WARN(0x01000001, "-colour_trans option is not needed and was not used\n"); if (dims.w != -1 || dims.h != -1) OJPH_WARN(0x01000002, "-dims option is not needed and was not used\n"); if (num_components != -1 ) OJPH_WARN(0x01000003, "-num_comps is not needed and was not used\n"); if (is_signed[0] != -1) OJPH_WARN(0x01000004, "-signed is not needed and was not used\n"); if (bit_depth[0] != -1) OJPH_WARN(0x01000005, "-bit_depth is not needed and was not used\n"); if (comp_downsampling[0].x != 0 || comp_downsampling[0].y != 0) OJPH_WARN(0x01000006, "-downsamp is not needed and was not used\n"); base = &ppm; } else if (strncmp(".ppm", v, 4) == 0) { ppm.open(input_filename); ojph::param_siz siz = codestream.access_siz(); siz.set_image_extent(ojph::point(image_offset.x + ppm.get_size().w, image_offset.y + ppm.get_size().h)); int num_comps = ppm.get_num_components(); assert(num_comps == 3); siz.set_num_components(num_comps); for (int c = 0; c < num_comps; ++c) siz.set_component(c, ppm.get_comp_subsampling(c), ppm.get_bit_depth(c), ppm.get_is_signed(c)); siz.set_image_offset(image_offset); siz.set_tile_size(tile_size); siz.set_tile_offset(tile_offset); ojph::param_cod cod = codestream.access_cod(); cod.set_num_decomposition(num_decompositions); cod.set_block_dims(block_size.w, block_size.h); if (num_precints != -1) cod.set_precinct_size(num_precints, precinct_size); cod.set_progression_order(prog_order); if (employ_color_transform == -1) cod.set_color_transform(true); else cod.set_color_transform(employ_color_transform == 1); cod.set_reversible(reversible); if (!reversible && quantization_step != -1) codestream.access_qcd().set_irrev_quant(quantization_step); codestream.set_planar(false); if (profile_string[0] != '\0') codestream.set_profile(profile_string); if (dims.w != -1 || dims.h != -1) OJPH_WARN(0x01000011, "-dims option is not needed and was not used\n"); if (num_components != -1) OJPH_WARN(0x01000012, "-num_comps is not needed and was not used\n"); if (is_signed[0] != -1) OJPH_WARN(0x01000013, "-signed is not needed and was not used\n"); if (bit_depth[0] != -1) OJPH_WARN(0x01000014, "-bit_depth is not needed and was not used\n"); if (comp_downsampling[0].x != 0 || comp_downsampling[0].y != 0) OJPH_WARN(0x01000015, "-downsamp is not needed and was not used\n"); base = &ppm; } else if (strncmp(".yuv", v, 4) == 0) { ojph::param_siz siz = codestream.access_siz(); if (dims.w < 0 || dims.h < 0) OJPH_ERROR(0x01000021, "-dims option is missing, and need to be provided\n"); siz.set_image_extent(ojph::point(image_offset.x + dims.w, image_offset.y + dims.h)); if (num_components <= 0) OJPH_ERROR(0x01000022, "-num_comps option is missing and must be provided\n"); if (num_is_signed <= 0) OJPH_ERROR(0x01000023, "-signed option is missing and must be provided\n"); if (num_bit_depths <= 0) OJPH_ERROR(0x01000024, "-bit_depth option is missing and must be provided\n"); if (num_comp_downsamps <= 0) OJPH_ERROR(0x01000025, "-downsamp option is missing and must be provided\n"); yuv.set_img_props(dims, num_components, num_comp_downsamps, comp_downsampling); yuv.set_bit_depth(num_bit_depths, bit_depth); int last_signed_idx = 0, last_bit_depth_idx = 0, last_downsamp_idx = 0; siz.set_num_components(num_components); for (int c = 0; c < num_components; ++c) { ojph::point cp_ds = comp_downsampling [c < num_comp_downsamps ? c : last_downsamp_idx]; last_downsamp_idx += last_downsamp_idx+1 < num_comp_downsamps ? 1:0; int bd = bit_depth[c < num_bit_depths ? c : last_bit_depth_idx]; last_bit_depth_idx += last_bit_depth_idx + 1 < num_bit_depths ? 1:0; int is = is_signed[c < num_is_signed ? c : last_signed_idx]; last_signed_idx += last_signed_idx + 1 < num_is_signed ? 1 : 0; siz.set_component(c, cp_ds, bd, is == 1); } siz.set_image_offset(image_offset); siz.set_tile_size(tile_size); siz.set_tile_offset(tile_offset); ojph::param_cod cod = codestream.access_cod(); cod.set_num_decomposition(num_decompositions); cod.set_block_dims(block_size.w, block_size.h); if (num_precints != -1) cod.set_precinct_size(num_precints, precinct_size); cod.set_progression_order(prog_order); if (employ_color_transform == -1) cod.set_color_transform(false); else OJPH_ERROR(0x01000031, "we currently do not support color transform on yuv files." " In any case, this not a normal usage scenario. The OpenJPH " "library however does support that, but ojph_compress.cpp must be " "modified to send all lines from one component before moving to " "the next component; this requires buffering components outside" " of the OpenJPH library"); cod.set_reversible(reversible); if (!reversible && quantization_step != -1) codestream.access_qcd().set_irrev_quant(quantization_step); codestream.set_planar(true); if (profile_string[0] != '\0') codestream.set_profile(profile_string); yuv.open(input_filename); base = &yuv; } else OJPH_ERROR(0x01000041, "unknown input file extension; only (pgm, ppm, and yuv) are" " supported\n"); } else OJPH_ERROR(0x01000051, "Please supply a proper input filename with a proper three-letter " "extension\n"); ojph::j2c_outfile j2c_file; j2c_file.open(output_filename); codestream.write_headers(&j2c_file); int next_comp; ojph::line_buf* cur_line = codestream.exchange(NULL, next_comp); if (codestream.is_planar()) { ojph::param_siz siz = codestream.access_siz(); for (int c = 0; c < siz.get_num_components(); ++c) { ojph::point p = siz.get_downsampling(c); int height = ojph_div_ceil(siz.get_image_extent().y, p.y) - ojph_div_ceil(siz.get_image_offset().y, p.y); for (int i = height; i > 0; --i) { assert(c == next_comp); base->read(cur_line, next_comp); cur_line = codestream.exchange(cur_line, next_comp); } } } else { ojph::param_siz siz = codestream.access_siz(); int height = siz.get_image_extent().y - siz.get_image_offset().y; for (int i = 0; i < height; ++i) { for (int c = 0; c < siz.get_num_components(); ++c) { assert(c == next_comp); base->read(cur_line, next_comp); cur_line = codestream.exchange(cur_line, next_comp); } } } codestream.flush(); codestream.close(); base->close(); if (max_num_comps != initial_num_comps) { delete[] comp_downsampling; delete[] bit_depth; delete[] is_signed; } } catch (const std::exception& e) { const char *p = e.what(); if (strncmp(p, "ojph error", 10) != 0) printf("%s\n", p); exit(-1); } clock_t end = clock(); double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC; printf("Elapsed time = %f\n", elapsed_secs); return 0; }
36.353017
82
0.600763
[ "transform" ]
b4cc5c3b751250974d5eebcd7cc7edf365d47c69
5,185
cxx
C++
inetcore/mshtml/src/site/acc/accradio.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetcore/mshtml/src/site/acc/accradio.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetcore/mshtml/src/site/acc/accradio.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+--------------------------------------------------------------------------- // // Microsoft Trident // Copyright (C) Microsoft Corporation, 1994-1998 // // File: AccRadio.Cxx // // Contents: Accessible radio button object implementation // //---------------------------------------------------------------------------- #include "headers.hxx" #pragma MARK_DATA(__FILE__) #pragma MARK_CODE(__FILE__) #pragma MARK_CONST(__FILE__) #ifndef X_ACCRADIO_HXX_ #define X_ACCRADIO_HXX_ #include "accradio.hxx" #endif #ifndef X_ACCUTIL_HXX_ #define X_ACCUTIL_HXX_ #include "accutil.hxx" #endif #ifndef X_INPUTTXT_HXX_ #define X_INPUTTXT_HXX_ #include "inputtxt.hxx" #endif //---------------------------------------------------------------------------- // CAccRadio // // DESCRIPTION: // The radio button accessible object constructor // // PARAMETERS: // Pointer to the radio button element //---------------------------------------------------------------------------- CAccRadio::CAccRadio( CElement* pElementParent ) :CAccElement(pElementParent) { Assert( pElementParent ); //initialize the instance variables SetRole( ROLE_SYSTEM_RADIOBUTTON ); } //---------------------------------------------------------------------------- // GetAccName // // DESCRIPTION: // Returns the label, if not the title. // // PARAMETERS: // pbstrName : BSTR pointer to receive the name // // RETURNS // S_OK | E_INVALIDARG //---------------------------------------------------------------------------- STDMETHODIMP CAccRadio::GetAccName( BSTR* pbstrName ) { HRESULT hr; // validate out parameter if ( !pbstrName ) { hr= E_POINTER; goto Cleanup; } *pbstrName = NULL; hr = THR( GetLabelorTitle( pbstrName ) ); Cleanup: RRETURN( hr ); } //---------------------------------------------------------------------------- // GetAccDescription // // DESCRIPTION: // Returns the label, if not, the title // // PARAMETERS: // pbstrDescription : BSTR pointer to receive the Description // // RETURNS // S_OK | E_INVALIDARG //---------------------------------------------------------------------------- STDMETHODIMP CAccRadio::GetAccDescription( BSTR* pbstrDescription) { HRESULT hr=S_OK; // validate out parameter if ( !pbstrDescription ) { hr = E_POINTER; goto Cleanup; } *pbstrDescription = NULL; if (HasLabel()) hr = THR( GetTitle( pbstrDescription ) ); Cleanup: RRETURN1( hr, S_FALSE ); } //---------------------------------------------------------------------------- // GetAccState // // DESCRIPTION: // if not visible, then STATE_SYSTEM_INVISIBLE // if document has the focus, then STATE_SYSTEM_FOCUSABLE // if this is the active element. then STATE_SYSTEM_FOCUSED // if it is not enabled then STATE_SYSTEM_UNAVAILABLE // if checked then STATE_SYSTEM_CHECKED // // PARAMETERS: // pvarState : address of VARIANT to receive state information. // // RETURNS // S_OK | E_INVALIDARG //---------------------------------------------------------------------------- STDMETHODIMP CAccRadio::GetAccState( VARIANT *pvarState ) { HRESULT hr = S_OK; VARIANT_BOOL bChecked = FALSE; CDoc * pDoc = _pElement->Doc(); // validate out parameter if ( !pvarState ) { hr = E_POINTER; goto Cleanup; } V_VT( pvarState ) = VT_I4; V_I4( pvarState ) = 0; if ( !_pElement->IsEnabled() ) V_I4( pvarState ) |= STATE_SYSTEM_UNAVAILABLE; else { if ( IsFocusable(_pElement) ) V_I4( pvarState ) |= STATE_SYSTEM_FOCUSABLE; if ( pDoc && (pDoc->_pElemCurrent == _pElement) && pDoc->HasFocus()) V_I4( pvarState ) |= STATE_SYSTEM_FOCUSED; if ( !_pElement->IsVisible(FALSE) ) V_I4( pvarState ) |= STATE_SYSTEM_INVISIBLE; hr = THR( (DYNCAST(CInput, _pElement))->GetChecked(&bChecked) ) ; if ( hr ) goto Cleanup; if ( bChecked != VB_FALSE ) V_I4( pvarState ) |= STATE_SYSTEM_CHECKED; } Cleanup: RRETURN( hr ); } //---------------------------------------------------------------------------- // GetAccDefaultAction // // DESCRIPTION: // Returns the default action for a radio button, "select" // // PARAMETERS: // pbstrDefaultAction : BSTR pointer to receive the default action str. // //---------------------------------------------------------------------------- STDMETHODIMP CAccRadio::GetAccDefaultAction( BSTR* pbstrDefaultAction) { HRESULT hr = S_OK; if ( !pbstrDefaultAction ) { hr = E_POINTER; goto Cleanup; } *pbstrDefaultAction = SysAllocString( _T("Check") ); if (!(*pbstrDefaultAction) ) hr = E_OUTOFMEMORY; Cleanup: RRETURN( hr ); }
25.048309
83
0.48486
[ "object" ]
b4ce74dd8a77941c13170fae5a2c0286a073b6d9
2,797
cpp
C++
source/shape/ShapeRNNSequenceGRU.cpp
foreverlms/MNN
8f9d3e3331fb54382bb61ac3a2087637a161fec5
[ "Apache-2.0" ]
null
null
null
source/shape/ShapeRNNSequenceGRU.cpp
foreverlms/MNN
8f9d3e3331fb54382bb61ac3a2087637a161fec5
[ "Apache-2.0" ]
null
null
null
source/shape/ShapeRNNSequenceGRU.cpp
foreverlms/MNN
8f9d3e3331fb54382bb61ac3a2087637a161fec5
[ "Apache-2.0" ]
null
null
null
// // ShapeRNNSequenceGRU.cpp // MNN // // Created by MNN on 2019/03/19. // Copyright © 2018, Alibaba Group Holding Limited // #include "shape/SizeComputer.hpp" #include "core/TensorUtils.hpp" namespace MNN { class RNNSequenceGRUComputer : public SizeComputer { public: virtual bool onComputeSize(const MNN::Op* op, const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs) const override { auto outputSize = outputs.size(); MNN_ASSERT(6 <= inputs.size()); MNN_ASSERT(1 <= outputSize); auto input = inputs[0]; // typically onnx input shape: {sequenceLength, batchSize, inputLength} auto output = outputs[0]; const auto rnnParam = op->main_as_RNNParam(); const int numUnits = rnnParam->numUnits(); bool keepAllOutputs = rnnParam->keepAllOutputs(); bool isBidirectionalRNN = rnnParam->isBidirectionalRNN(); // input->printShape(); // MNN_ASSERT(2 == rnnParam->fwGateWeight()->dims()->size()); // MNN_ASSERT(2 * numUnits == rnnParam->fwGateWeight()->dims()->data()[1]); // MNN_ASSERT((input->length(2) + numUnits) == rnnParam->fwGateWeight()->dims()->data()[0]); output->buffer().type = halide_type_of<float>(); TensorUtils::getDescribe(output)->dimensionFormat = TensorUtils::getDescribe(input)->dimensionFormat; if (keepAllOutputs) { TensorUtils::setShape(output, {input->length(0), isBidirectionalRNN + 1, input->length(1), numUnits}); // output shape: {sequenceLength, numDirection, batchSize, inputLength} // !!caution: onnx model graph some time would squeeze the ‘1 dim’ in output 'numDirection', we should keep numDirection index at 1, // but, the typical memory layout of input tensor in CPURNNSequenceGRU.cpp is {batch, sequenceLength, inputLength}, // there is mismatch here when batch or sequence is not 1 output->buffer().type = input->buffer().type; if (outputSize > 1) { auto YHOutput = outputs[1]; TensorUtils::setShape(YHOutput, {1, isBidirectionalRNN + 1, input->length(1), numUnits}); YHOutput->buffer().type = input->buffer().type; TensorUtils::getDescribe(YHOutput)->dimensionFormat = TensorUtils::getDescribe(input)->dimensionFormat; } } else { // only keep the last hidden layer sequence TensorUtils::setShape(output, {1, isBidirectionalRNN + 1, input->length(1), numUnits}); output->buffer().type = input->buffer().type; } // output->printShape(); return true; } }; REGISTER_SHAPE(RNNSequenceGRUComputer, OpType_RNNSequenceGRU); } // namespace MNN
43.030769
144
0.629961
[ "shape", "vector", "model" ]
b4cf8c64cc65d2e8549ce156cc7ba00920028c26
6,492
cc
C++
media/audio/mac/audio_auhal_mac_unittest.cc
pozdnyakov/chromium-crosswalk
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-05-03T06:33:56.000Z
2021-11-14T18:39:42.000Z
media/audio/mac/audio_auhal_mac_unittest.cc
pozdnyakov/chromium-crosswalk
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
media/audio/mac/audio_auhal_mac_unittest.cc
pozdnyakov/chromium-crosswalk
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2017-07-31T19:09:52.000Z
2019-01-04T18:48:50.000Z
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/basictypes.h" #include "base/memory/scoped_ptr.h" #include "media/audio/audio_io.h" #include "media/audio/audio_manager.h" #include "media/audio/simple_sources.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::_; using ::testing::AnyNumber; using ::testing::DoAll; using ::testing::Field; using ::testing::InSequence; using ::testing::Invoke; using ::testing::NiceMock; using ::testing::NotNull; using ::testing::Return; static const int kBitsPerSample = 16; // TODO(crogers): Most of these tests can be made platform agnostic. // http://crbug.com/223242 namespace media { class MockAudioSourceCallback : public AudioOutputStream::AudioSourceCallback { public: MOCK_METHOD2(OnMoreData, int(AudioBus* audio_bus, AudioBuffersState buffers_state)); MOCK_METHOD3(OnMoreIOData, int(AudioBus* source, AudioBus* dest, AudioBuffersState buffers_state)); MOCK_METHOD1(OnError, void(AudioOutputStream* stream)); }; // Convenience method which creates a default AudioOutputStream object but // also allows the user to modify the default settings. class AudioOutputStreamWrapper { public: explicit AudioOutputStreamWrapper() : audio_man_(AudioManager::Create()), format_(AudioParameters::AUDIO_PCM_LOW_LATENCY), bits_per_sample_(kBitsPerSample) { AudioParameters preferred_params = audio_man_->GetDefaultOutputStreamParameters(); channel_layout_ = preferred_params.channel_layout(); channels_ = preferred_params.channels(); sample_rate_ = preferred_params.sample_rate(); samples_per_packet_ = preferred_params.frames_per_buffer(); } ~AudioOutputStreamWrapper() {} // Creates AudioOutputStream object using default parameters. AudioOutputStream* Create() { return CreateOutputStream(); } // Creates AudioOutputStream object using non-default parameters where the // frame size is modified. AudioOutputStream* Create(int samples_per_packet) { samples_per_packet_ = samples_per_packet; return CreateOutputStream(); } // Creates AudioOutputStream object using non-default parameters where the // sample rate is modified. AudioOutputStream* CreateWithSampleRate(int sample_rate) { sample_rate_ = sample_rate; return CreateOutputStream(); } // Creates AudioOutputStream object using non-default parameters where the // channel layout is modified. AudioOutputStream* CreateWithLayout(ChannelLayout layout) { channel_layout_ = layout; channels_ = ChannelLayoutToChannelCount(layout); return CreateOutputStream(); } AudioParameters::Format format() const { return format_; } int channels() const { return ChannelLayoutToChannelCount(channel_layout_); } int bits_per_sample() const { return bits_per_sample_; } int sample_rate() const { return sample_rate_; } int samples_per_packet() const { return samples_per_packet_; } bool CanRunAudioTests() { return audio_man_->HasAudioOutputDevices(); } private: AudioOutputStream* CreateOutputStream() { AudioParameters params; params.Reset(format_, channel_layout_, channels_, 0, sample_rate_, bits_per_sample_, samples_per_packet_); AudioOutputStream* aos = audio_man_->MakeAudioOutputStream(params, std::string()); EXPECT_TRUE(aos); return aos; } scoped_ptr<AudioManager> audio_man_; AudioParameters::Format format_; ChannelLayout channel_layout_; int channels_; int bits_per_sample_; int sample_rate_; int samples_per_packet_; }; // Test that we can get the hardware sample-rate. TEST(AUHALStreamTest, HardwareSampleRate) { AudioOutputStreamWrapper aosw; if (!aosw.CanRunAudioTests()) return; int sample_rate = aosw.sample_rate(); EXPECT_GE(sample_rate, 16000); EXPECT_LE(sample_rate, 192000); } // Test Create(), Close() calling sequence. TEST(AUHALStreamTest, CreateAndClose) { AudioOutputStreamWrapper aosw; if (!aosw.CanRunAudioTests()) return; AudioOutputStream* aos = aosw.Create(); aos->Close(); } // Test Open(), Close() calling sequence. TEST(AUHALStreamTest, OpenAndClose) { AudioOutputStreamWrapper aosw; if (!aosw.CanRunAudioTests()) return; AudioOutputStream* aos = aosw.Create(); EXPECT_TRUE(aos->Open()); aos->Close(); } // Test Open(), Start(), Close() calling sequence. TEST(AUHALStreamTest, OpenStartAndClose) { AudioOutputStreamWrapper aosw; if (!aosw.CanRunAudioTests()) return; AudioOutputStream* aos = aosw.Create(); EXPECT_TRUE(aos->Open()); MockAudioSourceCallback source; EXPECT_CALL(source, OnError(aos)) .Times(0); aos->Start(&source); aos->Close(); } // Test Open(), Start(), Stop(), Close() calling sequence. TEST(AUHALStreamTest, OpenStartStopAndClose) { AudioOutputStreamWrapper aosw; if (!aosw.CanRunAudioTests()) return; AudioOutputStream* aos = aosw.Create(); EXPECT_TRUE(aos->Open()); MockAudioSourceCallback source; EXPECT_CALL(source, OnError(aos)) .Times(0); aos->Start(&source); aos->Stop(); aos->Close(); } // This test produces actual audio for 0.5 seconds on the default audio device // at the hardware sample-rate (usually 44.1KHz). // Parameters have been chosen carefully so you should not hear // pops or noises while the sound is playing. TEST(AUHALStreamTest, AUHALStreamPlay200HzTone) { AudioOutputStreamWrapper aosw; if (!aosw.CanRunAudioTests()) return; AudioOutputStream* aos = aosw.CreateWithLayout(CHANNEL_LAYOUT_MONO); EXPECT_TRUE(aos->Open()); SineWaveAudioSource source(1, 200.0, aosw.sample_rate()); aos->Start(&source); usleep(500000); aos->Stop(); aos->Close(); } // Test that Open() will fail with a sample-rate which isn't the hardware // sample-rate. TEST(AUHALStreamTest, AUHALStreamInvalidSampleRate) { AudioOutputStreamWrapper aosw; if (!aosw.CanRunAudioTests()) return; int non_default_sample_rate = aosw.sample_rate() == 44100 ? 48000 : 44100; AudioOutputStream* aos = aosw.CreateWithSampleRate(non_default_sample_rate); EXPECT_FALSE(aos->Open()); aos->Close(); } } // namespace media
29.509091
79
0.718885
[ "object" ]
b4d0f6c33093be90ebd376099461d2034d3430cb
9,334
cpp
C++
tests/Unit/ParallelAlgorithms/LinearSolver/Schwarz/Test_SchwarzAlgorithm.cpp
tomwlodarczyk/spectre
086aaee002f2f07eb812cf17b8e1ba54052feb71
[ "MIT" ]
null
null
null
tests/Unit/ParallelAlgorithms/LinearSolver/Schwarz/Test_SchwarzAlgorithm.cpp
tomwlodarczyk/spectre
086aaee002f2f07eb812cf17b8e1ba54052feb71
[ "MIT" ]
null
null
null
tests/Unit/ParallelAlgorithms/LinearSolver/Schwarz/Test_SchwarzAlgorithm.cpp
tomwlodarczyk/spectre
086aaee002f2f07eb812cf17b8e1ba54052feb71
[ "MIT" ]
null
null
null
// Distributed under the MIT License. // See LICENSE.txt for details. #define CATCH_CONFIG_RUNNER #include <cstddef> #include <vector> #include "DataStructures/ApplyMatrices.hpp" #include "DataStructures/DenseMatrix.hpp" #include "DataStructures/DenseVector.hpp" #include "Domain/Creators/RegisterDerivedWithCharm.hpp" #include "Domain/LogicalCoordinates.hpp" #include "Domain/Structure/Element.hpp" #include "Domain/Structure/ElementId.hpp" #include "Domain/Tags.hpp" #include "Elliptic/DiscontinuousGalerkin/DgElementArray.hpp" #include "ErrorHandling/FloatingPointExceptions.hpp" #include "Helpers/ParallelAlgorithms/LinearSolver/DistributedLinearSolverAlgorithmTestHelpers.hpp" #include "Helpers/ParallelAlgorithms/LinearSolver/LinearSolverAlgorithmTestHelpers.hpp" #include "NumericalAlgorithms/Spectral/Mesh.hpp" #include "NumericalAlgorithms/Spectral/Spectral.hpp" #include "Parallel/GlobalCache.hpp" #include "Parallel/InitializationFunctions.hpp" #include "Parallel/Main.hpp" #include "ParallelAlgorithms/Initialization/Actions/RemoveOptionsAndTerminatePhase.hpp" #include "ParallelAlgorithms/LinearSolver/Schwarz/ElementCenteredSubdomainData.hpp" #include "ParallelAlgorithms/LinearSolver/Schwarz/Protocols.hpp" #include "ParallelAlgorithms/LinearSolver/Schwarz/Schwarz.hpp" #include "Utilities/MakeArray.hpp" #include "Utilities/ProtocolHelpers.hpp" #include "Utilities/TMPL.hpp" namespace helpers = LinearSolverAlgorithmTestHelpers; namespace helpers_distributed = DistributedLinearSolverAlgorithmTestHelpers; namespace { struct SchwarzSmoother { static constexpr Options::String help = "Options for the iterative Schwarz smoother"; }; template <typename DirectionsTag> struct DoNothing { using argument_tags = tmpl::list<>; template <typename SubdomainData, typename ResultData, typename SubdomainOperator> static void apply( const SubdomainData& /*subdomain_data*/, const gsl::not_null<ResultData*> /*result*/, const gsl::not_null<SubdomainOperator*> /*subdomain_operator*/) noexcept { } }; DenseMatrix<double> combine_matrix_slices( const std::vector<DenseMatrix<double>>& matrix_slices) { const size_t num_slices = matrix_slices.size(); const size_t num_cols_per_slice = matrix_slices.begin()->columns(); const size_t total_num_points = num_slices * num_cols_per_slice; DenseMatrix<double> full_matrix(total_num_points, total_num_points); for (size_t i = 0; i < num_slices; ++i) { blaze::submatrix(full_matrix, 0, i * num_cols_per_slice, total_num_points, num_cols_per_slice) = gsl::at(matrix_slices, i); } return full_matrix; } template <typename Tag> DenseVector<double> extend_subdomain_data( const LinearSolver::Schwarz::ElementCenteredSubdomainData< 1, tmpl::list<Tag>>& subdomain_data, const size_t element_index, const size_t num_elements, const size_t num_points_per_element, const size_t overlap_extent) { DenseVector<double> extended_subdomain_data( num_elements * num_points_per_element, 0.); blaze::subvector( extended_subdomain_data, element_index * num_points_per_element, num_points_per_element) = get(get<Tag>(subdomain_data.element_data)); for (const auto& [overlap_id, overlap_data] : subdomain_data.overlap_data) { const auto& direction = overlap_id.first; const auto direction_from_neighbor = direction.opposite(); const size_t overlapped_element_index = direction.side() == Side::Lower ? (element_index - 1) : (element_index + 1); blaze::subvector(extended_subdomain_data, overlapped_element_index * num_points_per_element, num_points_per_element) = get(get<Tag>(LinearSolver::Schwarz::extended_overlap_data( overlap_data, Index<1>{num_points_per_element}, overlap_extent, direction_from_neighbor))); } return extended_subdomain_data; } template <typename Tag> void restrict_to_subdomain( const gsl::not_null<LinearSolver::Schwarz::ElementCenteredSubdomainData< 1, tmpl::list<Tag>>*> result, const DenseVector<double>& extended_result, const size_t element_index, const size_t num_points_per_element, const size_t overlap_extent) { const DenseVector<double> restricted_element_data = blaze::subvector(extended_result, element_index * num_points_per_element, num_points_per_element); std::copy(restricted_element_data.begin(), restricted_element_data.end(), get(get<Tag>(result->element_data)).begin()); for (auto& [overlap_id, overlap_result] : result->overlap_data) { const auto& direction = overlap_id.first; const auto direction_from_neighbor = direction.opposite(); const size_t overlapped_element_index = direction.side() == Side::Lower ? (element_index - 1) : (element_index + 1); Scalar<DataVector> extended_result_on_element{num_points_per_element}; const DenseVector<double> restricted_overlap_data = blaze::subvector( extended_result, overlapped_element_index * num_points_per_element, num_points_per_element); std::copy(restricted_overlap_data.begin(), restricted_overlap_data.end(), get(extended_result_on_element).begin()); LinearSolver::Schwarz::data_on_overlap( make_not_null(&get<Tag>(overlap_result)), extended_result_on_element, Index<1>{num_points_per_element}, overlap_extent, direction_from_neighbor); } } // [subdomain_operator] // Applies the linear operator given explicitly in the input file to data on an // element-centered subdomain, using standard matrix multiplication. // // We assume all elements have the same extents so we can use the element's // intruding overlap extents instead of initializing extruding overlap extents. struct SubdomainElementOperator { using argument_tags = tmpl::list< helpers_distributed::LinearOperator, domain::Tags::Element<1>, LinearSolver::Schwarz::Tags::IntrudingExtents<1, SchwarzSmoother>>; template <typename Tag, typename ResultData, typename SubdomainOperator> static void apply( const std::vector<DenseMatrix<double>>& matrix_slices, const Element<1>& element, const std::array<size_t, 1>& overlap_extents, const LinearSolver::Schwarz::ElementCenteredSubdomainData< 1, tmpl::list<Tag>>& subdomain_data, const gsl::not_null<ResultData*> result, const gsl::not_null<SubdomainOperator*> /*subdomain_operator*/) noexcept { const size_t element_index = helpers_distributed::get_index(element.id()); const size_t num_elements = matrix_slices.size(); const size_t num_points_per_element = matrix_slices.begin()->columns(); // Re-size the result buffer if necessary result->destructive_resize(subdomain_data); // Assemble full operator matrix const auto operator_matrix = combine_matrix_slices(matrix_slices); // Extend subdomain data with zeros outside the subdomain const auto extended_subdomain_data = extend_subdomain_data(subdomain_data, element_index, num_elements, num_points_per_element, overlap_extents[0]); // Apply matrix to extended subdomain data const DenseVector<double> extended_result = operator_matrix * extended_subdomain_data; // Restrict the result back to the subdomain restrict_to_subdomain(result, extended_result, element_index, num_points_per_element, overlap_extents[0]); } }; struct SubdomainOperator : tt::ConformsTo<LinearSolver::Schwarz::protocols::SubdomainOperator> { static constexpr size_t volume_dim = 1; using element_operator = SubdomainElementOperator; template <typename DirectionsTag> using face_operator = DoNothing<DirectionsTag>; explicit SubdomainOperator(const size_t /*element_num_points*/) noexcept {} }; // [subdomain_operator] static_assert(tt::assert_conforms_to< SubdomainOperator, LinearSolver::Schwarz::protocols::SubdomainOperator>); struct Metavariables { static constexpr const char* const help{ "Test the Schwarz linear solver algorithm"}; static constexpr size_t volume_dim = 1; using linear_solver = LinearSolver::Schwarz::Schwarz<helpers_distributed::fields_tag, SchwarzSmoother, SubdomainOperator>; using preconditioner = void; using Phase = helpers::Phase; using observed_reduction_data_tags = helpers::observed_reduction_data_tags<Metavariables>; using component_list = helpers_distributed::component_list<Metavariables>; static constexpr bool ignore_unrecognized_command_line_options = false; static constexpr auto determine_next_phase = helpers::determine_next_phase<Metavariables>; }; } // namespace static const std::vector<void (*)()> charm_init_node_funcs{ &setup_error_handling, &domain::creators::register_derived_with_charm}; static const std::vector<void (*)()> charm_init_proc_funcs{ &enable_floating_point_exceptions}; using charmxx_main_component = Parallel::Main<Metavariables>; #include "Parallel/CharmMain.tpp" // IWYU pragma: keep
43.013825
98
0.740733
[ "mesh", "vector" ]
b4d171ddd182bc68838e065d07f2c1a5768ac8f8
1,466
cpp
C++
exe/src/control/parameters/setratioitemcountvsnodecountcmd.cpp
jonpetri/CollectGame
251beb560f8246468479f04461bfc0b1298a7e70
[ "MIT" ]
null
null
null
exe/src/control/parameters/setratioitemcountvsnodecountcmd.cpp
jonpetri/CollectGame
251beb560f8246468479f04461bfc0b1298a7e70
[ "MIT" ]
null
null
null
exe/src/control/parameters/setratioitemcountvsnodecountcmd.cpp
jonpetri/CollectGame
251beb560f8246468479f04461bfc0b1298a7e70
[ "MIT" ]
null
null
null
#include "setratioitemcountvsnodecountcmd.h" #include "model/game/collectgame.h" #include "model/game/gameparameters.h" //----------------------------------------------------------------------------------------------------------------------- // SetRatioItemCountVsNodeCountCmd :: Constructors / Destructors //----------------------------------------------------------------------------------------------------------------------- SetRatioItemCountVsNodeCountCmd::SetRatioItemCountVsNodeCountCmd() { // Command's terms/arguments definition this->addCommandTerm("IC"); this->setDescription("Modify the ratio item count / node count"); this->setExpectedParameterCount(1); } SetRatioItemCountVsNodeCountCmd::~SetRatioItemCountVsNodeCountCmd() { } //----------------------------------------------------------------------------------------------------------------------- // SetRatioItemCountVsNodeCountCmd :: Methods //----------------------------------------------------------------------------------------------------------------------- /** * Set the ratio item count / node count */ void SetRatioItemCountVsNodeCountCmd::execute() { float fParaValue; if (this->checkParameterIsPositiveFloat(0, fParaValue) == false) return; if (this->m_model->gameParameters()->setRatio_ItemCountVsNodeCount(fParaValue) == false) { this->sendMessageToUser("Incorrect entry.\n"); return; } this->modelModified(); }
34.904762
121
0.49045
[ "model" ]
b4d4399aa18c83c2505003b76195fdfdbfb0c2c2
2,750
cc
C++
ios/chrome/browser/reading_list/reading_list_remover_helper.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
ios/chrome/browser/reading_list/reading_list_remover_helper.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
ios/chrome/browser/reading_list/reading_list_remover_helper.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2017 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 "ios/chrome/browser/reading_list/reading_list_remover_helper.h" #include "base/threading/sequenced_task_runner_handle.h" #include "components/reading_list/core/reading_list_model.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/reading_list/reading_list_download_service.h" #include "ios/chrome/browser/reading_list/reading_list_download_service_factory.h" #include "ios/chrome/browser/reading_list/reading_list_model_factory.h" namespace reading_list { ReadingListRemoverHelper::ReadingListRemoverHelper( ios::ChromeBrowserState* browser_state) : scoped_observer_(this) { reading_list_model_ = ReadingListModelFactory::GetForBrowserState(browser_state); reading_list_download_service_ = ReadingListDownloadServiceFactory::GetForBrowserState(browser_state); } ReadingListRemoverHelper::~ReadingListRemoverHelper() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!reading_list_model_); DCHECK(!reading_list_download_service_); } void ReadingListRemoverHelper::ReadingListModelLoaded( const ReadingListModel* reading_list_model) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK_EQ(reading_list_model_, reading_list_model); scoped_observer_.Remove(reading_list_model_); bool model_cleared = reading_list_model_->DeleteAllEntries(); reading_list_download_service_->Clear(); ReadlingListItemsRemoved(model_cleared); } void ReadingListRemoverHelper::ReadingListModelBeingDeleted( const ReadingListModel* reading_list_model) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK_EQ(reading_list_model_, reading_list_model); scoped_observer_.Remove(reading_list_model_); ReadlingListItemsRemoved(false); } void ReadingListRemoverHelper::RemoveAllUserReadingListItemsIOS( Callback completion) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); completion_ = std::move(completion); if (!reading_list_model_) { ReadlingListItemsRemoved(false); return; } // ReadingListModel::AddObserver calls ReadingListModelLoaded if model is // already loaded, so there is no need to check. scoped_observer_.Add(reading_list_model_); } void ReadingListRemoverHelper::ReadlingListItemsRemoved(bool success) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); reading_list_model_ = nullptr; reading_list_download_service_ = nullptr; if (completion_) { base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(completion_), success)); } } } // namespace reading_list
35.714286
82
0.814545
[ "model" ]
b4d58877d229181563930b12bfa14c1b99533641
14,987
cpp
C++
wznmcmbd/CrdWznmUsg/PnlWznmUsgDetail_blks.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
3
2020-09-20T16:24:48.000Z
2021-12-01T19:44:51.000Z
wznmcmbd/CrdWznmUsg/PnlWznmUsgDetail_blks.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
null
null
null
wznmcmbd/CrdWznmUsg/PnlWznmUsgDetail_blks.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
null
null
null
/** * \file PnlWznmUsgDetail_blks.cpp * job handler for job PnlWznmUsgDetail (implementation of blocks) * \copyright (C) 2016-2020 MPSI Technologies GmbH * \author Alexander Wirthmueller (auto-generation) * \date created: 28 Nov 2020 */ // IP header --- ABOVE using namespace std; using namespace Sbecore; using namespace Xmlio; /****************************************************************************** class PnlWznmUsgDetail::VecVDo ******************************************************************************/ uint PnlWznmUsgDetail::VecVDo::getIx( const string& sref ) { string s = StrMod::lc(sref); if (s == "butsaveclick") return BUTSAVECLICK; return(0); }; string PnlWznmUsgDetail::VecVDo::getSref( const uint ix ) { if (ix == BUTSAVECLICK) return("ButSaveClick"); return(""); }; /****************************************************************************** class PnlWznmUsgDetail::ContIac ******************************************************************************/ PnlWznmUsgDetail::ContIac::ContIac( const string& TxfCmt ) : Block() { this->TxfCmt = TxfCmt; mask = {TXFCMT}; }; bool PnlWznmUsgDetail::ContIac::readJSON( Json::Value& sup , bool addbasetag ) { clear(); bool basefound; Json::Value& me = sup; if (addbasetag) me = sup["ContIacWznmUsgDetail"]; basefound = (me != Json::nullValue); if (basefound) { if (me.isMember("TxfCmt")) {TxfCmt = me["TxfCmt"].asString(); add(TXFCMT);}; }; return basefound; }; bool PnlWznmUsgDetail::ContIac::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "ContIacWznmUsgDetail"); else basefound = checkXPath(docctx, basexpath); string itemtag = "ContitemIacWznmUsgDetail"; if (basefound) { if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "TxfCmt", TxfCmt)) add(TXFCMT); }; return basefound; }; void PnlWznmUsgDetail::ContIac::writeJSON( Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "ContIacWznmUsgDetail"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); me["TxfCmt"] = TxfCmt; }; void PnlWznmUsgDetail::ContIac::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "ContIacWznmUsgDetail"; string itemtag; if (shorttags) itemtag = "Ci"; else itemtag = "ContitemIacWznmUsgDetail"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeStringAttr(wr, itemtag, "sref", "TxfCmt", TxfCmt); xmlTextWriterEndElement(wr); }; set<uint> PnlWznmUsgDetail::ContIac::comm( const ContIac* comp ) { set<uint> items; if (TxfCmt == comp->TxfCmt) insert(items, TXFCMT); return(items); }; set<uint> PnlWznmUsgDetail::ContIac::diff( const ContIac* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {TXFCMT}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWznmUsgDetail::ContInf ******************************************************************************/ PnlWznmUsgDetail::ContInf::ContInf( const string& TxtSrf ) : Block() { this->TxtSrf = TxtSrf; mask = {TXTSRF}; }; void PnlWznmUsgDetail::ContInf::writeJSON( Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "ContInfWznmUsgDetail"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); me["TxtSrf"] = TxtSrf; }; void PnlWznmUsgDetail::ContInf::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "ContInfWznmUsgDetail"; string itemtag; if (shorttags) itemtag = "Ci"; else itemtag = "ContitemInfWznmUsgDetail"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeStringAttr(wr, itemtag, "sref", "TxtSrf", TxtSrf); xmlTextWriterEndElement(wr); }; set<uint> PnlWznmUsgDetail::ContInf::comm( const ContInf* comp ) { set<uint> items; if (TxtSrf == comp->TxtSrf) insert(items, TXTSRF); return(items); }; set<uint> PnlWznmUsgDetail::ContInf::diff( const ContInf* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {TXTSRF}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWznmUsgDetail::StatApp ******************************************************************************/ void PnlWznmUsgDetail::StatApp::writeJSON( Json::Value& sup , string difftag , const uint ixWznmVExpstate ) { if (difftag.length() == 0) difftag = "StatAppWznmUsgDetail"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); me["srefIxWznmVExpstate"] = VecWznmVExpstate::getSref(ixWznmVExpstate); }; void PnlWznmUsgDetail::StatApp::writeXML( xmlTextWriter* wr , string difftag , bool shorttags , const uint ixWznmVExpstate ) { if (difftag.length() == 0) difftag = "StatAppWznmUsgDetail"; string itemtag; if (shorttags) itemtag = "Si"; else itemtag = "StatitemAppWznmUsgDetail"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeStringAttr(wr, itemtag, "sref", "srefIxWznmVExpstate", VecWznmVExpstate::getSref(ixWznmVExpstate)); xmlTextWriterEndElement(wr); }; /****************************************************************************** class PnlWznmUsgDetail::StatShr ******************************************************************************/ PnlWznmUsgDetail::StatShr::StatShr( const bool ButSaveAvail , const bool ButSaveActive , const bool TxtSrfActive , const bool TxfCmtActive ) : Block() { this->ButSaveAvail = ButSaveAvail; this->ButSaveActive = ButSaveActive; this->TxtSrfActive = TxtSrfActive; this->TxfCmtActive = TxfCmtActive; mask = {BUTSAVEAVAIL, BUTSAVEACTIVE, TXTSRFACTIVE, TXFCMTACTIVE}; }; void PnlWznmUsgDetail::StatShr::writeJSON( Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "StatShrWznmUsgDetail"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); me["ButSaveAvail"] = ButSaveAvail; me["ButSaveActive"] = ButSaveActive; me["TxtSrfActive"] = TxtSrfActive; me["TxfCmtActive"] = TxfCmtActive; }; void PnlWznmUsgDetail::StatShr::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "StatShrWznmUsgDetail"; string itemtag; if (shorttags) itemtag = "Si"; else itemtag = "StatitemShrWznmUsgDetail"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeBoolAttr(wr, itemtag, "sref", "ButSaveAvail", ButSaveAvail); writeBoolAttr(wr, itemtag, "sref", "ButSaveActive", ButSaveActive); writeBoolAttr(wr, itemtag, "sref", "TxtSrfActive", TxtSrfActive); writeBoolAttr(wr, itemtag, "sref", "TxfCmtActive", TxfCmtActive); xmlTextWriterEndElement(wr); }; set<uint> PnlWznmUsgDetail::StatShr::comm( const StatShr* comp ) { set<uint> items; if (ButSaveAvail == comp->ButSaveAvail) insert(items, BUTSAVEAVAIL); if (ButSaveActive == comp->ButSaveActive) insert(items, BUTSAVEACTIVE); if (TxtSrfActive == comp->TxtSrfActive) insert(items, TXTSRFACTIVE); if (TxfCmtActive == comp->TxfCmtActive) insert(items, TXFCMTACTIVE); return(items); }; set<uint> PnlWznmUsgDetail::StatShr::diff( const StatShr* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {BUTSAVEAVAIL, BUTSAVEACTIVE, TXTSRFACTIVE, TXFCMTACTIVE}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWznmUsgDetail::Tag ******************************************************************************/ void PnlWznmUsgDetail::Tag::writeJSON( const uint ixWznmVLocale , Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "TagWznmUsgDetail"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); if (ixWznmVLocale == VecWznmVLocale::ENUS) { me["CptSrf"] = "identifier"; me["CptCmt"] = "comment"; }; me["Cpt"] = StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::DETAIL, ixWznmVLocale)); }; void PnlWznmUsgDetail::Tag::writeXML( const uint ixWznmVLocale , xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "TagWznmUsgDetail"; string itemtag; if (shorttags) itemtag = "Ti"; else itemtag = "TagitemWznmUsgDetail"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); if (ixWznmVLocale == VecWznmVLocale::ENUS) { writeStringAttr(wr, itemtag, "sref", "CptSrf", "identifier"); writeStringAttr(wr, itemtag, "sref", "CptCmt", "comment"); }; writeStringAttr(wr, itemtag, "sref", "Cpt", StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::DETAIL, ixWznmVLocale))); xmlTextWriterEndElement(wr); }; /****************************************************************************** class PnlWznmUsgDetail::DpchAppData ******************************************************************************/ PnlWznmUsgDetail::DpchAppData::DpchAppData() : DpchAppWznm(VecWznmVDpch::DPCHAPPWZNMUSGDETAILDATA) { }; string PnlWznmUsgDetail::DpchAppData::getSrefsMask() { vector<string> ss; string srefs; if (has(JREF)) ss.push_back("jref"); if (has(CONTIAC)) ss.push_back("contiac"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlWznmUsgDetail::DpchAppData::readJSON( Json::Value& sup , bool addbasetag ) { clear(); bool basefound; Json::Value& me = sup; if (addbasetag) me = sup["DpchAppWznmUsgDetailData"]; basefound = (me != Json::nullValue); if (basefound) { if (me.isMember("scrJref")) {jref = Scr::descramble(me["scrJref"].asString()); add(JREF);}; if (contiac.readJSON(me, true)) add(CONTIAC); } else { contiac = ContIac(); }; }; void PnlWznmUsgDetail::DpchAppData::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); string scrJref; bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchAppWznmUsgDetailData"); else basefound = checkXPath(docctx, basexpath); if (basefound) { if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) { jref = Scr::descramble(scrJref); add(JREF); }; if (contiac.readXML(docctx, basexpath, true)) add(CONTIAC); } else { contiac = ContIac(); }; }; /****************************************************************************** class PnlWznmUsgDetail::DpchAppDo ******************************************************************************/ PnlWznmUsgDetail::DpchAppDo::DpchAppDo() : DpchAppWznm(VecWznmVDpch::DPCHAPPWZNMUSGDETAILDO) { ixVDo = 0; }; string PnlWznmUsgDetail::DpchAppDo::getSrefsMask() { vector<string> ss; string srefs; if (has(JREF)) ss.push_back("jref"); if (has(IXVDO)) ss.push_back("ixVDo"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlWznmUsgDetail::DpchAppDo::readJSON( Json::Value& sup , bool addbasetag ) { clear(); bool basefound; Json::Value& me = sup; if (addbasetag) me = sup["DpchAppWznmUsgDetailDo"]; basefound = (me != Json::nullValue); if (basefound) { if (me.isMember("scrJref")) {jref = Scr::descramble(me["scrJref"].asString()); add(JREF);}; if (me.isMember("srefIxVDo")) {ixVDo = VecVDo::getIx(me["srefIxVDo"].asString()); add(IXVDO);}; } else { }; }; void PnlWznmUsgDetail::DpchAppDo::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); string scrJref; string srefIxVDo; bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchAppWznmUsgDetailDo"); else basefound = checkXPath(docctx, basexpath); if (basefound) { if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) { jref = Scr::descramble(scrJref); add(JREF); }; if (extractStringUclc(docctx, basexpath, "srefIxVDo", "", srefIxVDo)) { ixVDo = VecVDo::getIx(srefIxVDo); add(IXVDO); }; } else { }; }; /****************************************************************************** class PnlWznmUsgDetail::DpchEngData ******************************************************************************/ PnlWznmUsgDetail::DpchEngData::DpchEngData( const ubigint jref , ContIac* contiac , ContInf* continf , StatShr* statshr , const set<uint>& mask ) : DpchEngWznm(VecWznmVDpch::DPCHENGWZNMUSGDETAILDATA, jref) { if (find(mask, ALL)) this->mask = {JREF, CONTIAC, CONTINF, STATAPP, STATSHR, TAG}; else this->mask = mask; if (find(this->mask, CONTIAC) && contiac) this->contiac = *contiac; if (find(this->mask, CONTINF) && continf) this->continf = *continf; if (find(this->mask, STATSHR) && statshr) this->statshr = *statshr; }; string PnlWznmUsgDetail::DpchEngData::getSrefsMask() { vector<string> ss; string srefs; if (has(JREF)) ss.push_back("jref"); if (has(CONTIAC)) ss.push_back("contiac"); if (has(CONTINF)) ss.push_back("continf"); if (has(STATAPP)) ss.push_back("statapp"); if (has(STATSHR)) ss.push_back("statshr"); if (has(TAG)) ss.push_back("tag"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlWznmUsgDetail::DpchEngData::merge( DpchEngWznm* dpcheng ) { DpchEngData* src = (DpchEngData*) dpcheng; if (src->has(JREF)) {jref = src->jref; add(JREF);}; if (src->has(CONTIAC)) {contiac = src->contiac; add(CONTIAC);}; if (src->has(CONTINF)) {continf = src->continf; add(CONTINF);}; if (src->has(STATAPP)) add(STATAPP); if (src->has(STATSHR)) {statshr = src->statshr; add(STATSHR);}; if (src->has(TAG)) add(TAG); }; void PnlWznmUsgDetail::DpchEngData::writeJSON( const uint ixWznmVLocale , Json::Value& sup ) { Json::Value& me = sup["DpchEngWznmUsgDetailData"] = Json::Value(Json::objectValue); if (has(JREF)) me["scrJref"] = Scr::scramble(jref); if (has(CONTIAC)) contiac.writeJSON(me); if (has(CONTINF)) continf.writeJSON(me); if (has(STATAPP)) StatApp::writeJSON(me); if (has(STATSHR)) statshr.writeJSON(me); if (has(TAG)) Tag::writeJSON(ixWznmVLocale, me); }; void PnlWznmUsgDetail::DpchEngData::writeXML( const uint ixWznmVLocale , xmlTextWriter* wr ) { xmlTextWriterStartElement(wr, BAD_CAST "DpchEngWznmUsgDetailData"); xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/wznm"); if (has(JREF)) writeString(wr, "scrJref", Scr::scramble(jref)); if (has(CONTIAC)) contiac.writeXML(wr); if (has(CONTINF)) continf.writeXML(wr); if (has(STATAPP)) StatApp::writeXML(wr); if (has(STATSHR)) statshr.writeXML(wr); if (has(TAG)) Tag::writeXML(ixWznmVLocale, wr); xmlTextWriterEndElement(wr); };
25.750859
118
0.627744
[ "vector" ]
b4d5f6d7cfd306c73ac3f741f8d6952b50380fa3
7,894
cpp
C++
vlc_linux/vlc-3.0.16/modules/demux/adaptive/playlist/Segment.cpp
Brook1711/biubiu_Qt6
5c4d22a1d1beef63bc6c7738dce6c477c4642803
[ "MIT" ]
null
null
null
vlc_linux/vlc-3.0.16/modules/demux/adaptive/playlist/Segment.cpp
Brook1711/biubiu_Qt6
5c4d22a1d1beef63bc6c7738dce6c477c4642803
[ "MIT" ]
null
null
null
vlc_linux/vlc-3.0.16/modules/demux/adaptive/playlist/Segment.cpp
Brook1711/biubiu_Qt6
5c4d22a1d1beef63bc6c7738dce6c477c4642803
[ "MIT" ]
null
null
null
/* * Segment.cpp ***************************************************************************** * Copyright (C) 2010 - 2011 Klagenfurt University * * Created on: Aug 10, 2010 * Authors: Christopher Mueller <christopher.mueller@itec.uni-klu.ac.at> * Christian Timmerer <christian.timmerer@itec.uni-klu.ac.at> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "Segment.h" #include "BaseAdaptationSet.h" #include "BaseRepresentation.h" #include "AbstractPlaylist.hpp" #include "SegmentChunk.hpp" #include "../http/BytesRange.hpp" #include "../http/HTTPConnectionManager.h" #include "../http/Downloader.hpp" #include <cassert> using namespace adaptive::http; using namespace adaptive::playlist; ISegment::ISegment(const ICanonicalUrl *parent): ICanonicalUrl( parent ), startByte (0), endByte (0) { debugName = "Segment"; classId = CLASSID_ISEGMENT; startTime.Set(0); duration.Set(0); sequence = 0; templated = false; discontinuity = false; } ISegment::~ISegment() { } bool ISegment::prepareChunk(SharedResources *res, SegmentChunk *chunk, BaseRepresentation *rep) { CommonEncryption enc = encryption; enc.mergeWith(rep->intheritEncryption()); if(enc.method != CommonEncryption::Method::NONE) { CommonEncryptionSession *encryptionSession = new CommonEncryptionSession(); if(!encryptionSession->start(res, enc)) { delete encryptionSession; return false; } chunk->setEncryptionSession(encryptionSession); } return true; } SegmentChunk* ISegment::toChunk(SharedResources *res, AbstractConnectionManager *connManager, size_t index, BaseRepresentation *rep) { const std::string url = getUrlSegment().toString(index, rep); HTTPChunkBufferedSource *source = new (std::nothrow) HTTPChunkBufferedSource(url, connManager, rep->getAdaptationSet()->getID()); if( source ) { if(startByte != endByte) source->setBytesRange(BytesRange(startByte, endByte)); SegmentChunk *chunk = createChunk(source, rep); if(chunk) { chunk->discontinuity = discontinuity; if(!prepareChunk(res, chunk, rep)) { delete chunk; return NULL; } connManager->start(source); return chunk; } else { delete source; } } return NULL; } bool ISegment::isTemplate() const { return templated; } void ISegment::setByteRange(size_t start, size_t end) { startByte = start; endByte = end; } void ISegment::setSequenceNumber(uint64_t seq) { sequence = seq; } uint64_t ISegment::getSequenceNumber() const { return sequence; } size_t ISegment::getOffset() const { return startByte; } void ISegment::debug(vlc_object_t *obj, int indent) const { std::stringstream ss; ss.imbue(std::locale("C")); ss << std::string(indent, ' ') << debugName << " #" << getSequenceNumber(); ss << " url=" << getUrlSegment().toString(); if(startByte!=endByte) ss << " @" << startByte << ".." << endByte; if(startTime.Get() > 0) ss << " stime " << startTime.Get(); ss << " duration " << duration.Get(); msg_Dbg(obj, "%s", ss.str().c_str()); } bool ISegment::contains(size_t byte) const { if (startByte == endByte) return false; return (byte >= startByte && (!endByte || byte <= endByte) ); } int ISegment::compare(ISegment *other) const { if(duration.Get()) { if(startTime.Get() > other->startTime.Get()) return 1; else if(startTime.Get() < other->startTime.Get()) return -1; } if(startByte > other->startByte) return 1; else if(startByte < other->startByte) return -1; if(endByte > other->endByte) return 1; else if(endByte < other->endByte) return -1; return 0; } void ISegment::setEncryption(CommonEncryption &e) { encryption = e; } int ISegment::getClassId() const { return classId; } Segment::Segment(ICanonicalUrl *parent) : ISegment(parent) { size = -1; classId = CLASSID_SEGMENT; } SegmentChunk* Segment::createChunk(AbstractChunkSource *source, BaseRepresentation *rep) { /* act as factory */ return new (std::nothrow) SegmentChunk(source, rep); } void Segment::addSubSegment(SubSegment *subsegment) { if(!subsegments.empty()) { /* Use our own sequence number, and since it it now uneffective, also for next subsegments numbering */ subsegment->setSequenceNumber(subsegments.size()); } subsegments.push_back(subsegment); } Segment::~Segment() { std::vector<SubSegment*>::iterator it; for(it=subsegments.begin();it!=subsegments.end();++it) delete *it; } void Segment::setSourceUrl ( const std::string &url ) { if ( url.empty() == false ) this->sourceUrl = Url(url); } void Segment::debug(vlc_object_t *obj, int indent) const { if (subsegments.empty()) { ISegment::debug(obj, indent); } else { std::string text(indent, ' '); text.append("Segment"); msg_Dbg(obj, "%s", text.c_str()); std::vector<SubSegment *>::const_iterator l; for(l = subsegments.begin(); l != subsegments.end(); ++l) (*l)->debug(obj, indent + 1); } } Url Segment::getUrlSegment() const { if(sourceUrl.hasScheme()) { return sourceUrl; } else { Url ret = getParentUrlSegment(); if (!sourceUrl.empty()) ret.append(sourceUrl); return ret; } } std::vector<ISegment*> Segment::subSegments() { std::vector<ISegment*> list; if(!subsegments.empty()) { std::vector<SubSegment*>::iterator it; for(it=subsegments.begin();it!=subsegments.end();++it) list.push_back(*it); } else { list.push_back(this); } return list; } InitSegment::InitSegment(ICanonicalUrl *parent) : Segment(parent) { debugName = "InitSegment"; classId = CLASSID_INITSEGMENT; } IndexSegment::IndexSegment(ICanonicalUrl *parent) : Segment(parent) { debugName = "IndexSegment"; classId = CLASSID_INDEXSEGMENT; } SubSegment::SubSegment(ISegment *main, size_t start, size_t end) : ISegment(main) { setByteRange(start, end); debugName = "SubSegment"; classId = CLASSID_SUBSEGMENT; } SegmentChunk* SubSegment::createChunk(AbstractChunkSource *source, BaseRepresentation *rep) { /* act as factory */ return new (std::nothrow) SegmentChunk(source, rep); } Url SubSegment::getUrlSegment() const { return getParentUrlSegment(); } std::vector<ISegment*> SubSegment::subSegments() { std::vector<ISegment*> list; list.push_back(this); return list; } void SubSegment::addSubSegment(SubSegment *) { }
24.746082
115
0.615277
[ "vector" ]
b4dabb2b65b12dbf91ef6148584dca3f96a368d9
11,439
cpp
C++
src/n64/mem.cpp
destoer/destoer-emu
2a7941b175126e998eed2df8df87ee382c43d0b1
[ "BSD-3-Clause" ]
20
2020-01-19T21:54:23.000Z
2021-11-28T17:27:15.000Z
src/n64/mem.cpp
destoer/destoer-emu
2a7941b175126e998eed2df8df87ee382c43d0b1
[ "BSD-3-Clause" ]
3
2020-05-01T07:46:10.000Z
2021-09-18T13:50:18.000Z
src/n64/mem.cpp
destoer/destoer-emu
2a7941b175126e998eed2df8df87ee382c43d0b1
[ "BSD-3-Clause" ]
null
null
null
#include <n64/n64.h> #include <n64/mem_constants.h> namespace nintendo64 { void do_pi_dma(N64 &n64, u32 src, u32 dst, u32 len); template<typename access_type> access_type handle_read_n64(std::vector<u8> &buf, u32 addr) { // handle endianess, we have swapped the entire rom // so offset the addresses if constexpr(sizeof(access_type) == 2) { addr ^= 2; } else if constexpr(sizeof(access_type) == 1) { addr ^= 3; } return handle_read<access_type>(buf,addr); } template<typename access_type> void handle_write_n64(std::vector<u8> &buf, u32 addr, access_type v) { // handle endianess, we have swapped the entire rom // so offset the addresses if constexpr(sizeof(access_type) == 2) { addr ^= 2; } else if constexpr(sizeof(access_type) == 1) { addr ^= 3; } handle_write<access_type>(buf,addr,v); } void reset_mem(Mem &mem, const std::string &filename) { // read rom in and hle the pif rom read_file(filename,mem.rom); // init memory // 8mb rd ram mem.rd_ram.resize(8 * 1024 * 1024); mem.sp_dmem.resize(0x1000); mem.sp_imem.resize(0x1000); const auto magic = handle_read_n64<uint32_t>(mem.rom,0x0); // if rom is middle endian byteswap it if(magic != 0x80371240) { puts("byteswapping rom"); std::iter_swap(mem.rom.begin(),mem.rom.end()-1); } for(u32 i = 0; i < mem.rom.size(); i += 4) { u32 v = handle_read_n64<u32>(mem.rom,i); v = bswap(v); handle_write_n64<u32>(mem.rom,i,v); } // hle pif rom memcpy(mem.sp_dmem.data(),mem.rom.data(),0x1000); // ri mem.ri_select = 0x0; mem.ri_config = 0x0; mem.ri_base = 0x0; mem.ri_refresh = 0x0; // pi mem.pi_cart_addr = 0; mem.pi_dram_addr = 0; mem.pi_status = 0; // MI mem.mi_mode = 0; mem.mi_intr = 0; } // TODO: this will probably have to be switched over to software page table // come time for implementing the tlb but lets just keep things nice and simple for now // and do a giant if else chain for everything u32 remap_addr(u32 addr) { if(addr < 0x80000000) { printf("KUSEG %8x\n",addr); exit(1); } // KSEG0 (direct mapped cached) else if(addr < 0xa0000000) { return addr - 0x80000000; } // KSEG1 (direct mapped uncached) else if(addr < 0xc0000000) { return addr - 0xa0000000; } // KSSEG else if(addr < 0xe0000000) { printf("KSSEG %8x\n",addr); exit(1); } else { printf("KSEG3 %8x\n",addr); exit(1); } assert(false); return 0; } template<typename access_type> access_type read_physical(N64 &n64, u32 addr) { // just do something naive for now so we can get roms running if(addr < 0x00800000) { return handle_read_n64<access_type>(n64.mem.rd_ram,addr); } // UNUSED else if(addr < 0x03F00000) { return 0; } else if(addr < 0x04000000) { // rdram config ignore for now return 0; /* switch(addr) { default: { unimplemented("read_mem: rdram regs %08x\n",addr); return 0; } } */ } else if(addr < 0x04001000) { return handle_read_n64<access_type>(n64.mem.sp_dmem,addr & 0xfff); } else if(addr < 0x04002000) { return handle_read_n64<access_type>(n64.mem.sp_imem,addr & 0xfff); } // UNUSED else if(addr < 0x04040000) { return 0; } // TODO: start here impl the read lw is doing else if(addr < 0x04100000) { unimplemented("read_mem: sp regs"); return 0; } else if(addr < 0x04200000) { unimplemented("read_mem: dp command regs"); return 0; } else if(addr < 0x04300000) { unimplemented("read_mem: dp span regs"); return 0; } else if(addr < 0x04400000) { switch(addr) { case MI_VERSION_REG: return static_cast<access_type>(0x02020102); default: { unimplemented("read_mem: mips interface: %8x\n",addr); return 0; } } } else if(addr < 0x04500000) { unimplemented("read_mem: video interface"); return 0; } else if(addr < 0x04600000) { unimplemented("read_mem: audio interface"); return 0; } else if(addr < 0x04700000) { switch(addr) { case PI_STATUS_REG: return n64.mem.pi_status; default: { unimplemented("read_mem: peripheral interface: %8x\n",addr); return 0; } } } else if(addr < 0x04800000) { // UNUSED if(addr >= 0x04700020) { return 0; } // TODO: should these all be byte accesses? switch(addr) { case RI_SELECT_REG: return n64.mem.ri_select; case RI_REFRESH_REG: return n64.mem.ri_refresh; default: unimplemented("read_mem: rdram interface: %8x\n",addr); } return 0; } else if(addr < 0x04900000) { unimplemented("serial interface"); return 0; } // UNUSED else if(addr < 0x05000000) { return static_cast<access_type>(0xffffffff); } // n64dd else if(addr < 0x08000000) { // return as not present for now return static_cast<access_type>(0xffffffff); } // sram else if(addr < 0x10000000) { unimplemented("sram"); return 0; } // rom else if(addr < 0x1FC00000) { const auto rom_addr = addr & (n64.mem.rom.size() - 1); return handle_read_n64<access_type>(n64.mem.rom, rom_addr); } else { printf("read_mem: unknown physical address: %8x\n",addr); exit(1); return 0; } } // for now assume accesses are force aligned // however they are supposed to throw exceptions // when they are not template<typename access_type> access_type read_mem(N64 &n64, u32 addr) { // force align addr addr &= ~(sizeof(access_type)-1); addr = remap_addr(addr); return read_physical<access_type>(n64,addr); } template<typename access_type> void write_physical(N64 &n64, u32 addr, access_type v) { // just do something naive for now so we can get roms running if(addr < 0x00800000) { handle_write_n64<access_type>(n64.mem.rd_ram,addr,v); } // UNUSED else if(addr < 0x03F00000) { } else if(addr < 0x04000000) { /* RDRAM configuration (we will ignore this for now) switch(addr) { default: unimplemented("write_mem: rdram regs: %8x\n",addr); } */ } else if(addr < 0x04001000) { handle_write_n64<access_type>(n64.mem.sp_dmem,addr & 0xfff,v); } else if(addr < 0x04002000) { handle_write_n64<access_type>(n64.mem.sp_imem,addr & 0xfff,v); } // UNUSED else if(addr < 0x04040000) { } // TODO: start here impl the read lw is doing else if(addr < 0x04100000) { unimplemented("write_mem: sp regs"); } else if(addr < 0x04200000) { unimplemented("write_mem: dp command regs"); } else if(addr < 0x04300000) { unimplemented("write_mem: dp span regs"); } else if(addr < 0x04400000) { switch(addr) { case MI_MODE_REG: { n64.mem.mi_mode = v; if(is_set(v,11)) // bit 11 wrote clear DP interrupt bit { n64.mem.mi_intr = deset_bit(n64.mem.mi_intr,DP_INTR_BIT); } break; } default: unimplemented("write_mem: mips interface : %8x\n",addr); break; } } else if(addr < 0x04500000) { unimplemented("write_mem: video interface"); } else if(addr < 0x04600000) { unimplemented("write_mem: audio interface"); } else if(addr < 0x04700000) { switch(addr) { case PI_CART_ADDR_REG: { // aligned on 2 bytes n64.mem.pi_cart_addr = v; break; } case PI_CART_DRAM_ADDR_REG: { // aligned on 8 bytes n64.mem.pi_dram_addr = v & 0xffffff; break; } // need to find proper pi dma info // is this where we start a dma? case PI_WR_LEN_REG: { n64.mem.pi_wr_len = v & 0xffffff; //printf("pi dma %08x:%08x:%08x\n",n64.mem.pi_cart_addr,n64.mem.pi_dram_addr,n64.mem.pi_wr_len + 1); // dma from cart to rdram do_pi_dma(n64,n64.mem.pi_cart_addr & ~1,n64.mem.pi_dram_addr & ~7,n64.mem.pi_wr_len + 1); break; } default: unimplemented("write_mem: pi interface: %08x\n",addr); } } else if(addr < 0x04800000) { // UNUSED if(addr >= 0x04700020) { return; } switch(addr) { case RI_SELECT_REG: n64.mem.ri_select = v & 0b111111; break; case RI_CONFIG_REG: n64.mem.ri_config = v & 0b1111111; break; case RI_CURRENT_LOAD_REG: break; // write only ignore for now case RI_BASE_REG: n64.mem.ri_base = v & 0b1111; break; case RI_REFRESH_REG: n64.mem.ri_refresh = v & 0b1111111111111111111; break; default: unimplemented("write_mem: rdram interface: %8x\n",addr); } } else { std::cout << fmt::format("write_mem: unknown physical address: {:8x}:{:x}\n",addr,v); exit(1); } } // for now assume accesses are force aligned // however they are supposed to throw exceptions // when they are not template<typename access_type> void write_mem(N64 &n64, u32 addr, access_type v) { // force align addr addr &= ~(sizeof(access_type)-1); addr = remap_addr(addr); write_physical<access_type>(n64,addr,v); } void do_pi_dma(N64 &n64, u32 src, u32 dst, u32 len) { // for now just do it naviely with a read and write // and optimise it with memcpy later // len aligned to 16 bit for(u32 i = 0; i < len / 2; i += 2) { const auto v = read_physical<u16>(n64,src + i); write_physical<u16>(n64,dst+i,v); } // dma is done set the intr flag n64.mem.mi_intr = set_bit(n64.mem.mi_intr,PI_INTR_BIT); } u8 read_u8(N64 &n64,u32 addr) { return read_mem<u8>(n64,addr); } u16 read_u16(N64 &n64,u32 addr) { return read_mem<u16>(n64,addr); } u32 read_u32(N64 &n64,u32 addr) { return read_mem<u32>(n64,addr); } u64 read_u64(N64 &n64,u32 addr) { return read_mem<u64>(n64,addr); } void write_u8(N64 &n64,u32 addr,u8 v) { write_mem<u8>(n64,addr,v); } void write_u16(N64 &n64,u32 addr,u16 v) { write_mem<u16>(n64,addr,v); } void write_u32(N64 &n64,u32 addr,u32 v) { write_mem<u32>(n64,addr,v); } void write_u64(N64 &n64,u32 addr,u64 v) { write_mem<u64>(n64,addr,v); } }
21.027574
116
0.553632
[ "vector" ]
b4db121f95a8061b280de6880e2da5ec54ef5b0d
10,173
cpp
C++
lightfield_viewer/src/lightfield/lightfield.cpp
WeiPhil/LightFieldImaging
77cb6237c11974f873fba3efff8370a36e3a18e6
[ "MIT" ]
7
2019-12-12T13:46:41.000Z
2021-07-11T17:11:37.000Z
lightfield_viewer/src/lightfield/lightfield.cpp
WeiPhil/LightFieldImaging
77cb6237c11974f873fba3efff8370a36e3a18e6
[ "MIT" ]
null
null
null
lightfield_viewer/src/lightfield/lightfield.cpp
WeiPhil/LightFieldImaging
77cb6237c11974f873fba3efff8370a36e3a18e6
[ "MIT" ]
null
null
null
#include "lightfield/lightfield.h" #include <array> #include <glm/glm.hpp> #include <iostream> #include <string> #include <GL/gl3w.h> #include <GLFW/glfw3.h> #include "framework/opengl/compiler.h" #include "framework/opengl/semantics.h" #include "framework/opengl/vertex.h" #include "qulkan/logger.h" #include "qulkan/utils.h" #include "utils/stb_image.h" #include <glm/gtc/type_ptr.hpp> #define BUFFER_OFFSET(i) ((char *)NULL + (i)) Lightfield::Lightfield(const char *viewName, int initialRenderWidth, int initialRenderHeight) : Qulkan::RenderView(viewName, initialRenderWidth, initialRenderHeight), x_pan(1.f), y_pan(1.f) { vaoManager.addVertex(glf::vertex_v3fv2f(glm::vec3(1.0f, 1.0f, 0.0f), glm::vec2(0.0f, 0.0f))); // top right vaoManager.addVertex(glf::vertex_v3fv2f(glm::vec3(1.0f, -1.0f, 0.0f), glm::vec2(0.0f, 1.0f))); // top left vaoManager.addVertex(glf::vertex_v3fv2f(glm::vec3(-1.0f, -1.0f, 0.0f), glm::vec2(1.0f, 1.0f))); // bottom left vaoManager.addVertex(glf::vertex_v3fv2f(glm::vec3(-1.0f, 1.0f, 0.0f), glm::vec2(1.0f, 0.0f))); // bottom right eboManager.addTriangle(0, 1, 2); eboManager.addTriangle(2, 3, 0); } void Lightfield::initHandles() { Handle curr_image("Current Image", Type::INT, 0, 0, 3); Handle modeText("modeText", Type::TEXT, "(0 = Directional ,1 = Aperture, 2 = Refocus)"); Handle mode("Mode", Type::INT, 0, 0, 2); Handle apertureText("Aperture", Type::TEXT, "\tAperture options:"); Handle fstop("F-Stop", Type::INT, 9, 0, 9); Handle refocusText("Digital Refocus", Type::TEXT, "\tDigital Refocus options:"); Handle alpha("Alpha", Type::FLOAT, 0.f, -3.f, 3.f); handleManager.addHandle(curr_image); handleManager.addHandle(modeText); handleManager.addHandle(mode); handleManager.addHandle(apertureText); handleManager.addHandle(fstop); handleManager.addHandle(refocusText); handleManager.addHandle(alpha); // handleManager.addHandle(interpolation); } void Lightfield::initProgram() { Compiler compiler; shaderManager.addShader("VERT_DEFAULT", "../data/shaders/lightfield.vert", GL_VERTEX_SHADER, compiler); shaderManager.addShader("FRAG_DEFAULT", "../data/shaders/lightfield.frag", GL_FRAGMENT_SHADER, compiler); programManager.addProgram("DEFAULT"); glAttachShader(programManager("DEFAULT"), shaderManager("VERT_DEFAULT")); glAttachShader(programManager("DEFAULT"), shaderManager("FRAG_DEFAULT")); glLinkProgram(programManager("DEFAULT")); error = compiler.check() && error; error = compiler.check_program(programManager("DEFAULT")) && error; return; } void Lightfield::initBuffer() { bufferManager.addBuffer("ELEMENT"); bufferManager.addBuffer("VERTEX"); glGenBuffers(bufferManager.size(), &bufferManager.buffers[0]); // Create vertex array object glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferManager("ELEMENT")); glBufferData(GL_ELEMENT_ARRAY_BUFFER, eboManager.getElementSize(), &eboManager.elementData[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // Create vertex array object glBindBuffer(GL_ARRAY_BUFFER, bufferManager("VERTEX")); glBufferData(GL_ARRAY_BUFFER, vaoManager.getVertexDataSize(), &vaoManager.vertexData[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); return; } void Lightfield::initTexture() { textureManager.addTexture("IMAGE_LIGHTFIELD1", "../data/images/lightfield/fluor.jpg"); textureManager.addTexture("IMAGE_LIGHTFIELD2", "../data/images/lightfield/lego.jpg"); textureManager.addTexture("IMAGE_LIGHTFIELD3", "../data/images/lightfield/bunny.jpg"); textureManager.addTexture("IMAGE_LIGHTFIELD4", "../data/images/lightfield/crystal.jpg"); glGenTextures(textureManager.size(), &textureManager.textures[0]); unsigned char *texData; int width, height, nrChannels; std::cout << "[Lightfield Imaging]: Loading images, this can take time.." << std::endl; for (size_t i = 0; i < 4; i++) { std::string texture_path = "IMAGE_LIGHTFIELD" + std::to_string(i + 1); glBindTexture(GL_TEXTURE_RECTANGLE, textureManager(texture_path)); glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MAG_FILTER, GL_LINEAR); texData = stbi_load(textureManager.texturePath(texture_path), &width, &height, &nrChannels, 0); image_dims_side[i] = glm::vec3(width, height, 17); if (texData) { glTexImage2D(GL_TEXTURE_RECTANGLE, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, texData); } else { Qulkan::Logger::Error("Failed to load texture %d", i); } stbi_image_free(texData); } std::cout << "[Lightfield Imaging]: Done!" << std::endl; texture_id_program_id[0] = {GL_TEXTURE0, textureManager("IMAGE_LIGHTFIELD1")}; image_dims_side[0].z = 20; texture_id_program_id[1] = {GL_TEXTURE1, textureManager("IMAGE_LIGHTFIELD2")}; texture_id_program_id[2] = {GL_TEXTURE2, textureManager("IMAGE_LIGHTFIELD3")}; texture_id_program_id[3] = {GL_TEXTURE3, textureManager("IMAGE_LIGHTFIELD4")}; glBindTexture(GL_TEXTURE_RECTANGLE, 0); return; } void Lightfield::initVertexArray() { glGenVertexArrays(1, &vaoManager.id); glBindVertexArray(vaoManager.id); glBindBuffer(GL_ARRAY_BUFFER, bufferManager("VERTEX")); glVertexAttribPointer(semantic::attr::POSITION, 3, GL_FLOAT, GL_FALSE, vaoManager.getVertexSize(), BUFFER_OFFSET(0)); glEnableVertexAttribArray(semantic::attr::POSITION); glVertexAttribPointer(semantic::attr::TEXCOORD, 2, GL_FLOAT, GL_FALSE, vaoManager.getVertexSize(), BUFFER_OFFSET(sizeof(glm::vec3))); glEnableVertexAttribArray(semantic::attr::TEXCOORD); glBindBuffer(GL_ARRAY_BUFFER, 0); // Bind element buffer array to array ob glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferManager("ELEMENT")); glBindVertexArray(0); return; } void Lightfield::initFramebuffer() { return; } void Lightfield::init() { Qulkan::Logger::Info("%s: Initialisation\n", name()); if (handleManager.getHandles().empty()) initHandles(); initProgram(); initBuffer(); initTexture(); initVertexArray(); initFramebuffer(); initOpenGLOptions(); if (!error) { Qulkan::Logger::Info("%s: Initialisation Done\n", name()); initialized = true; } else Qulkan::Logger::Error("%s: An error Occured during initialisation\n", name()); } void Lightfield::initOpenGLOptions() { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } void Lightfield::clean() { glDeleteFramebuffers(framebufferManager.size(), &framebufferManager.framebuffers[0]); glDeleteProgram(programManager("DEFAULT")); glDeleteBuffers(bufferManager.size(), &bufferManager.buffers[0]); glDeleteTextures(textureManager.size(), &textureManager.textures[0]); glDeleteVertexArrays(1, &vaoManager.id); } /* Renders a simple OpenGL triangle in the rendering view */ void Lightfield::render(int actualRenderWidth, int actualRenderHeight) { ASSERT(initialized, std::string(name()) + ": You need to init the view first"); glViewport(0, 0, actualRenderWidth, actualRenderHeight); glClearColor(0.233f, 0.233f, 0.233f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); glUseProgram(programManager("DEFAULT")); auto current_image = handleManager("Current Image")->getValue<int>(); glActiveTexture(std::get<0>(texture_id_program_id[current_image])); glBindTexture(GL_TEXTURE_RECTANGLE, std::get<1>(texture_id_program_id[current_image])); glUniform3f(glGetUniformLocation(programManager("DEFAULT"), "image_properties"), image_dims_side[current_image].x, image_dims_side[current_image].y, image_dims_side[current_image].z); glUniform1i(glGetUniformLocation(programManager("DEFAULT"), "texture1"), current_image); float sensibility = 0.5; if ((isKeyDown(GLFW_KEY_W) || isKeyDown(GLFW_KEY_UP)) && y_pan < image_dims_side[current_image].z - 1) y_pan += sensibility; if ((isKeyDown(GLFW_KEY_S) || isKeyDown(GLFW_KEY_DOWN)) && y_pan > 1) y_pan -= sensibility; if ((isKeyDown(GLFW_KEY_D) || isKeyDown(GLFW_KEY_RIGHT)) && x_pan < image_dims_side[current_image].z - 1) x_pan += sensibility; if ((isKeyDown(GLFW_KEY_A) || isKeyDown(GLFW_KEY_LEFT)) && x_pan > 1) x_pan -= sensibility; if (isMouseDragging(0)) { x_pan += mouseDelta.x * sensibility * 0.3f * Qulkan::getDeltaTime(); y_pan += mouseDelta.y * sensibility * 0.3f * Qulkan::getDeltaTime(); x_pan = std::max(x_pan, std::min(image_dims_side[current_image].z - 1.f, 1.0f)); y_pan = std::max(y_pan, std::min(image_dims_side[current_image].z - 1.f, 1.0f)); } int *fstop = std::any_cast<int>(&handleManager("F-Stop")->value); fstop_float = (float)handleManager("F-Stop")->getValue<int>(); if (mouseWheel != 0.0f) { fstop_float -= mouseWheel; } if (fstop_float > 0.5f * image_dims_side[current_image].z - 1) { fstop_float = std::floor(0.5f * (image_dims_side[current_image].z - 1)); } if (fstop_float < 0.f) { fstop_float = 0.f; } *fstop = (int)fstop_float; glUniform1i(glGetUniformLocation(programManager("DEFAULT"), "mode"), handleManager("Mode")->getValue<int>()); glUniform1f(glGetUniformLocation(programManager("DEFAULT"), "x_pan"), x_pan); glUniform1f(glGetUniformLocation(programManager("DEFAULT"), "y_pan"), y_pan); glUniform1f(glGetUniformLocation(programManager("DEFAULT"), "alpha"), handleManager("Alpha")->getValue<float>()); glUniform1i(glGetUniformLocation(programManager("DEFAULT"), "fstop"), (int)*fstop); glBindVertexArray(vaoManager.id); glDrawElementsInstancedBaseVertex(GL_TRIANGLES, eboManager.getElementCount(), GL_UNSIGNED_INT, 0, 1, 0); return; }
40.051181
152
0.704905
[ "render", "object" ]
b4dc3b856f448a31652b8aa65a4e3b67997dbaf9
2,165
cpp
C++
Engine/Rendering/GUIOverlayRenderer.cpp
hhyyrylainen/Leviathan
0a0d2ea004a153f9b17c6230da029e8160716f71
[ "BSL-1.0" ]
16
2018-12-22T02:09:05.000Z
2022-03-09T20:38:59.000Z
Engine/Rendering/GUIOverlayRenderer.cpp
hhyyrylainen/Leviathan
0a0d2ea004a153f9b17c6230da029e8160716f71
[ "BSL-1.0" ]
46
2018-04-02T11:06:01.000Z
2019-12-14T11:16:04.000Z
Engine/Rendering/GUIOverlayRenderer.cpp
hhyyrylainen/Leviathan
0a0d2ea004a153f9b17c6230da029e8160716f71
[ "BSL-1.0" ]
14
2018-04-09T02:26:15.000Z
2021-09-11T03:12:15.000Z
// ------------------------------------ // #include "GUIOverlayRenderer.h" #include "Utility/Convert.h" #include "bsfCore/Material/BsGpuParamsSet.h" #include "bsfCore/Mesh/BsMesh.h" #include "bsfCore/RenderAPI/BsRenderAPI.h" #include "bsfCore/Renderer/BsCamera.h" #include "bsfEngine/Renderer/BsRendererUtility.h" using namespace Leviathan; // ------------------------------------ // GUIOverlayRenderer::GUIOverlayRenderer() : bs::RendererExtension(bs::RenderLocation::Overlay, 1) {} // ------------------------------------ // void GUIOverlayRenderer::initialize(const bs::Any& data) { const auto& initData = bs::any_cast_ref<GUIOverlayInitializationData>(data); ScreenQuad = initData.ScreenQuad; QuadMaterial = initData.QuadMaterial; if(QuadMaterial->getNumTechniques() < 1) { LOG_FATAL("No techniques in overlay material"); return; } QuadParamsSet = QuadMaterial->createParamsSet(0); LOG_INFO("Initialized GUIOverlayRenderer"); } void GUIOverlayRenderer::destroy() { QuadParamsSet.reset(); ScreenQuad.reset(); QuadMaterial.reset(); FullScreenOverlays.clear(); } // ------------------------------------ // void GUIOverlayRenderer::render(const bs::ct::Camera& camera) { const auto* overlays = GetOverlaysOnCamera(camera); if(!overlays) return; auto& rapi = bs::ct::RenderAPI::instance(); bs::ct::gRendererUtility().setPass(QuadMaterial); bs::ct::gRendererUtility().setPassParams(QuadParamsSet); for(const auto& texture : *overlays) { QuadMaterial->setTexture("image", texture); QuadParamsSet->update(QuadMaterial->_getInternalParams()); bs::ct::gRendererUtility().draw(ScreenQuad); } } // ------------------------------------ // std::vector<bs::SPtr<bs::ct::Texture>>* GUIOverlayRenderer::GetOverlaysOnCamera( const bs::ct::Camera& camera) { const auto currentRenderTarget = reinterpret_cast<uint64_t>(camera.getViewport()->getTarget().get()); const auto found = FullScreenOverlays.find(currentRenderTarget); if(found != FullScreenOverlays.end()) return &found->second; return nullptr; }
28.486842
80
0.640647
[ "mesh", "render", "vector" ]
b4de6f42bffbde8b78efa4f39467903f644d92c8
5,979
cpp
C++
framework/operators/fusion_ops/deconv_relu.cpp
guangzhixie/Anakin
9d66e6e5ca805ff3903172f7f69ecaa05a8e46f7
[ "Apache-2.0" ]
1
2018-09-10T06:42:09.000Z
2018-09-10T06:42:09.000Z
framework/operators/fusion_ops/deconv_relu.cpp
guangzhixie/Anakin
9d66e6e5ca805ff3903172f7f69ecaa05a8e46f7
[ "Apache-2.0" ]
2
2018-08-15T07:06:24.000Z
2018-08-15T08:00:30.000Z
framework/operators/fusion_ops/deconv_relu.cpp
guangzhixie/Anakin
9d66e6e5ca805ff3903172f7f69ecaa05a8e46f7
[ "Apache-2.0" ]
5
2018-06-22T03:36:38.000Z
2020-07-29T07:28:13.000Z
#include "framework/operators/fusion_ops/deconv_relu.h" namespace anakin { namespace ops { #define INSTANCE_CONVRELU(Ttype, Dtype, Ptype) \ template<> \ void DeconvRelu<Ttype, Dtype, Ptype>::operator()(\ OpContext<Ttype>& ctx,\ const std::vector<Tensor4dPtr<Ttype, Dtype> >& ins,\ std::vector<Tensor4dPtr<Ttype, Dtype> >& outs) {\ auto* impl =\ static_cast<DeconvReluHelper<Ttype, Dtype, Ptype>*>(this->_helper);\ auto& param = impl->_param_deconv_relu;\ impl->_funcs_deconv_relu(ins, outs, param, ctx);\ } /// set helper template<typename Ttype, DataType Dtype, Precision Ptype> DeconvReluHelper<Ttype, Dtype, Ptype>::~DeconvReluHelper() { } template<typename Ttype, DataType Dtype, Precision Ptype> Status DeconvReluHelper<Ttype, Dtype, Ptype>::InitParam() { DLOG(WARNING) << "Parsing DeconvRelu op parameter."; saber::ConvParam<Tensor4d<Ttype, Dtype>> _conv_param; // get conv param auto group = GET_PARAMETER(int, group); auto bias_term = GET_PARAMETER(bool, bias_term); auto padding = GET_PARAMETER(PTuple<int>, padding); auto strides = GET_PARAMETER(PTuple<int>, strides); auto dilation_rate = GET_PARAMETER(PTuple<int>, dilation_rate); auto filter_num = GET_PARAMETER(int, filter_num); auto kernel_size = GET_PARAMETER(PTuple<int>, kernel_size); auto axis = GET_PARAMETER(int, axis); using pblock_type = PBlock<typename DataTypeWarpper<Dtype>::type, Ttype>; auto weights = GET_PARAMETER(pblock_type, weight_1); if (bias_term) { auto bias = GET_PARAMETER(pblock_type, weight_2); saber::ConvParam<Tensor4d<Ttype, Dtype>> conv_param(group, padding[0], padding[1], strides[0], strides[1], dilation_rate[0], dilation_rate[1], &(weights.d_tensor()), &(bias.d_tensor())); _conv_param = conv_param; } else { Tensor4d<Ttype, Dtype>* bias = new Tensor4d<Ttype, Dtype>();; saber::ConvParam<Tensor4d<Ttype, Dtype>> conv_param(group, padding[0], padding[1], strides[0], strides[1], dilation_rate[0], dilation_rate[1], &(weights.d_tensor()), bias); _conv_param = conv_param; } // get relu param auto alpha = GET_PARAMETER(float, relu_0_alpha); ActivationParam<Tensor4d<Ttype, Dtype>> active_param(Active_relu);//, alpha); // TEMP ConvActiveParam<Tensor4d<Ttype, Dtype>> conv_act_param(_conv_param, active_param); _param_deconv_relu = conv_act_param; return Status::OK(); } template<typename Ttype, DataType Dtype, Precision Ptype> Status DeconvReluHelper<Ttype, Dtype, Ptype>::Init(OpContext<Ttype>& ctx, const std::vector<Tensor4dPtr<Ttype, Dtype> >& ins, std::vector<Tensor4dPtr<Ttype, Dtype> >& outs) { SABER_CHECK(_funcs_deconv_relu.init(ins, outs, _param_deconv_relu, SPECIFY, SABER_IMPL, ctx)); return Status::OK(); } template<typename Ttype, DataType Dtype, Precision Ptype> Status DeconvReluHelper<Ttype, Dtype, Ptype>::InferShape(const std::vector<Tensor4dPtr<Ttype, Dtype> >& ins, std::vector<Tensor4dPtr<Ttype, Dtype> >& outs) { _funcs_deconv_relu.compute_output_shape(ins, outs, _param_deconv_relu); return Status::OK(); } #ifdef USE_CUDA INSTANCE_CONVRELU(NV, AK_FLOAT, Precision::FP32); template<> Status DeconvReluHelper<NV, AK_FLOAT, Precision::FP32>::Init(OpContext<NV>& ctx, const std::vector<Tensor4dPtr<NV, AK_FLOAT> >& ins, std::vector<Tensor4dPtr<NV, AK_FLOAT> >& outs) { bool p = true; p = p && (_param_deconv_relu.conv_param.weight()->width() == 4); p = p && (_param_deconv_relu.conv_param.weight()->height() == 4); p = p && (_param_deconv_relu.conv_param.pad_h == 1); p = p && (_param_deconv_relu.conv_param.pad_w == 1); p = p && (_param_deconv_relu.conv_param.stride_h == 2); p = p && (_param_deconv_relu.conv_param.stride_w == 2); p = p && (ins[0]->channel() <= 64); p = p && (ins[0]->width() % 32 == 0); p = p || ((ins[0]->channel() == _param_deconv_relu.conv_param.group) && (ins[0]->channel() == outs[0]->channel())); // LOG(ERROR)<<"DECONV RELU INIT"; if (p) { // LOG(ERROR)<<"DECONV RELU SELECTED"; SABER_CHECK(_funcs_deconv_relu.init(ins, outs, _param_deconv_relu, SPECIFY, SABER_IMPL, ctx)); } else { SABER_CHECK(_funcs_deconv_relu.init(ins, outs, _param_deconv_relu, SPECIFY, VENDER_IMPL, ctx)); } return Status::OK(); } template class DeconvReluHelper<NV, AK_FLOAT, Precision::FP32>; ANAKIN_REGISTER_OP_HELPER(DeconvRelu, DeconvReluHelper, NV, AK_FLOAT, Precision::FP32); #endif #ifdef USE_ARM_PLACE INSTANCE_CONVRELU(NV, AK_FLOAT, Precision::FP32); template class DeconvReluHelper<ARM, AK_FLOAT, Precision::FP32>; ANAKIN_REGISTER_OP_HELPER(DeconvRelu, DeconvReluHelper, ARM, AK_FLOAT, Precision::FP32); #endif //! register op ANAKIN_REGISTER_OP(DeconvRelu) .Doc("DeconvRelu operator") #ifdef USE_CUDA .__alias__<NV, AK_FLOAT, Precision::FP32>("deconv_relu") #endif #ifdef USE_ARM_PLACE .__alias__<ARM, AK_FLOAT, Precision::FP32>("deconv_relu") #endif .num_in(1) .num_out(1) .Args<int>("group", " group of conv ") .Args<bool>("bias_term", " whether conv weights have bias") .Args<PTuple<int>>("padding", "padding of conv (x, y)") .Args<PTuple<int>>("strides", "strides of conv (x)") .Args<PTuple<int>>("dilation_rate", "dilation rate of conv (x)") .Args<int>("filter_num", "filter(kernel) number of weights") .Args<PTuple<int>>("kernel_size", "kernel size of kernel (x, y)") .Args<int>("axis", "axis of conv") .Args<float>("relu_0_alpha", " alpha for relu"); } /* namespace ops */ } /* namespace anakin */
39.078431
103
0.647098
[ "vector" ]
b4dff25ac3c565ad767fd1945442357dbb5e83ef
7,179
hpp
C++
include/codegen/include/UnityEngine/ProBuilder/Poly2Tri/DTSweepContext.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/UnityEngine/ProBuilder/Poly2Tri/DTSweepContext.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/UnityEngine/ProBuilder/Poly2Tri/DTSweepContext.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:22 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes // Including type: UnityEngine.ProBuilder.Poly2Tri.TriangulationContext #include "UnityEngine/ProBuilder/Poly2Tri/TriangulationContext.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine::ProBuilder::Poly2Tri namespace UnityEngine::ProBuilder::Poly2Tri { // Forward declaring type: AdvancingFront class AdvancingFront; // Forward declaring type: TriangulationPoint class TriangulationPoint; // Forward declaring type: DTSweepBasin class DTSweepBasin; // Forward declaring type: DTSweepEdgeEvent class DTSweepEdgeEvent; // Forward declaring type: DTSweepPointComparator class DTSweepPointComparator; // Forward declaring type: DelaunayTriangle class DelaunayTriangle; // Forward declaring type: AdvancingFrontNode class AdvancingFrontNode; // Forward declaring type: Triangulatable class Triangulatable; // Forward declaring type: TriangulationConstraint class TriangulationConstraint; } // Completed forward declares // Type namespace: UnityEngine.ProBuilder.Poly2Tri namespace UnityEngine::ProBuilder::Poly2Tri { // Autogenerated type: UnityEngine.ProBuilder.Poly2Tri.DTSweepContext class DTSweepContext : public UnityEngine::ProBuilder::Poly2Tri::TriangulationContext { public: // private readonly System.Single ALPHA // Offset: 0x40 float ALPHA; // public UnityEngine.ProBuilder.Poly2Tri.AdvancingFront Front // Offset: 0x48 UnityEngine::ProBuilder::Poly2Tri::AdvancingFront* Front; // private UnityEngine.ProBuilder.Poly2Tri.TriangulationPoint <Head>k__BackingField // Offset: 0x50 UnityEngine::ProBuilder::Poly2Tri::TriangulationPoint* Head; // private UnityEngine.ProBuilder.Poly2Tri.TriangulationPoint <Tail>k__BackingField // Offset: 0x58 UnityEngine::ProBuilder::Poly2Tri::TriangulationPoint* Tail; // public UnityEngine.ProBuilder.Poly2Tri.DTSweepBasin Basin // Offset: 0x60 UnityEngine::ProBuilder::Poly2Tri::DTSweepBasin* Basin; // public UnityEngine.ProBuilder.Poly2Tri.DTSweepEdgeEvent EdgeEvent // Offset: 0x68 UnityEngine::ProBuilder::Poly2Tri::DTSweepEdgeEvent* EdgeEvent; // private UnityEngine.ProBuilder.Poly2Tri.DTSweepPointComparator _comparator // Offset: 0x70 UnityEngine::ProBuilder::Poly2Tri::DTSweepPointComparator* comparator; // public UnityEngine.ProBuilder.Poly2Tri.TriangulationPoint get_Head() // Offset: 0x1916B50 UnityEngine::ProBuilder::Poly2Tri::TriangulationPoint* get_Head(); // public System.Void set_Head(UnityEngine.ProBuilder.Poly2Tri.TriangulationPoint value) // Offset: 0x1916B58 void set_Head(UnityEngine::ProBuilder::Poly2Tri::TriangulationPoint* value); // public UnityEngine.ProBuilder.Poly2Tri.TriangulationPoint get_Tail() // Offset: 0x1916B60 UnityEngine::ProBuilder::Poly2Tri::TriangulationPoint* get_Tail(); // public System.Void set_Tail(UnityEngine.ProBuilder.Poly2Tri.TriangulationPoint value) // Offset: 0x1916B68 void set_Tail(UnityEngine::ProBuilder::Poly2Tri::TriangulationPoint* value); // public System.Void RemoveFromList(UnityEngine.ProBuilder.Poly2Tri.DelaunayTriangle triangle) // Offset: 0x1913990 void RemoveFromList(UnityEngine::ProBuilder::Poly2Tri::DelaunayTriangle* triangle); // public System.Void MeshClean(UnityEngine.ProBuilder.Poly2Tri.DelaunayTriangle triangle) // Offset: 0x1914018 void MeshClean(UnityEngine::ProBuilder::Poly2Tri::DelaunayTriangle* triangle); // private System.Void MeshCleanReq(UnityEngine.ProBuilder.Poly2Tri.DelaunayTriangle triangle) // Offset: 0x1916D1C void MeshCleanReq(UnityEngine::ProBuilder::Poly2Tri::DelaunayTriangle* triangle); // public System.Void AddNode(UnityEngine.ProBuilder.Poly2Tri.AdvancingFrontNode node) // Offset: 0x19141C4 void AddNode(UnityEngine::ProBuilder::Poly2Tri::AdvancingFrontNode* node); // public System.Void RemoveNode(UnityEngine.ProBuilder.Poly2Tri.AdvancingFrontNode node) // Offset: 0x19164FC void RemoveNode(UnityEngine::ProBuilder::Poly2Tri::AdvancingFrontNode* node); // public UnityEngine.ProBuilder.Poly2Tri.AdvancingFrontNode LocateNode(UnityEngine.ProBuilder.Poly2Tri.TriangulationPoint point) // Offset: 0x191401C UnityEngine::ProBuilder::Poly2Tri::AdvancingFrontNode* LocateNode(UnityEngine::ProBuilder::Poly2Tri::TriangulationPoint* point); // public System.Void CreateAdvancingFront() // Offset: 0x191261C void CreateAdvancingFront(); // public System.Void MapTriangleToNodes(UnityEngine.ProBuilder.Poly2Tri.DelaunayTriangle t) // Offset: 0x19138B0 void MapTriangleToNodes(UnityEngine::ProBuilder::Poly2Tri::DelaunayTriangle* t); // public System.Void FinalizeTriangulation() // Offset: 0x1913C50 void FinalizeTriangulation(); // public System.Void .ctor() // Offset: 0x1916B70 // Implemented from: UnityEngine.ProBuilder.Poly2Tri.TriangulationContext // Base method: System.Void TriangulationContext::.ctor() // Base method: System.Void Object::.ctor() static DTSweepContext* New_ctor(); // public override System.Boolean get_IsDebugEnabled() // Offset: 0x1916D14 // Implemented from: UnityEngine.ProBuilder.Poly2Tri.TriangulationContext // Base method: System.Boolean TriangulationContext::get_IsDebugEnabled() bool get_IsDebugEnabled(); // public override System.Void Clear() // Offset: 0x1916E4C // Implemented from: UnityEngine.ProBuilder.Poly2Tri.TriangulationContext // Base method: System.Void TriangulationContext::Clear() void Clear(); // public override System.Void PrepareTriangulation(UnityEngine.ProBuilder.Poly2Tri.Triangulatable t) // Offset: 0x1916F20 // Implemented from: UnityEngine.ProBuilder.Poly2Tri.TriangulationContext // Base method: System.Void TriangulationContext::PrepareTriangulation(UnityEngine.ProBuilder.Poly2Tri.Triangulatable t) void PrepareTriangulation(UnityEngine::ProBuilder::Poly2Tri::Triangulatable* t); // public override UnityEngine.ProBuilder.Poly2Tri.TriangulationConstraint NewConstraint(UnityEngine.ProBuilder.Poly2Tri.TriangulationPoint a, UnityEngine.ProBuilder.Poly2Tri.TriangulationPoint b) // Offset: 0x19172D4 // Implemented from: UnityEngine.ProBuilder.Poly2Tri.TriangulationContext // Base method: UnityEngine.ProBuilder.Poly2Tri.TriangulationConstraint TriangulationContext::NewConstraint(UnityEngine.ProBuilder.Poly2Tri.TriangulationPoint a, UnityEngine.ProBuilder.Poly2Tri.TriangulationPoint b) UnityEngine::ProBuilder::Poly2Tri::TriangulationConstraint* NewConstraint(UnityEngine::ProBuilder::Poly2Tri::TriangulationPoint* a, UnityEngine::ProBuilder::Poly2Tri::TriangulationPoint* b); }; // UnityEngine.ProBuilder.Poly2Tri.DTSweepContext } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::ProBuilder::Poly2Tri::DTSweepContext*, "UnityEngine.ProBuilder.Poly2Tri", "DTSweepContext"); #pragma pack(pop)
55.651163
219
0.774899
[ "object" ]
b4e24188234ce4fc6585063735b046a79262089c
1,207
cpp
C++
deprecated_old_files/deprecated_workspace_pkgs/move_base_tf/src/move_base_tf_listener.cpp
Torreshan/TurtleBot
c6ae948364f82f505581dad2ee2dceb95fdcfba8
[ "MIT" ]
1
2019-01-31T13:13:03.000Z
2019-01-31T13:13:03.000Z
deprecated_old_files/deprecated_workspace_pkgs/move_base_tf/src/move_base_tf_listener.cpp
Torreshan/TurtleBot
c6ae948364f82f505581dad2ee2dceb95fdcfba8
[ "MIT" ]
null
null
null
deprecated_old_files/deprecated_workspace_pkgs/move_base_tf/src/move_base_tf_listener.cpp
Torreshan/TurtleBot
c6ae948364f82f505581dad2ee2dceb95fdcfba8
[ "MIT" ]
1
2019-01-14T16:24:05.000Z
2019-01-14T16:24:05.000Z
#include <ros/ros.h> #include <tf/transform_listener.h> #include <geometry_msgs/Twist.h> #include <turtlesim/Spawn.h> int main(int argc, char** argv){ ros::init(argc, argv, "my_tf_listener"); ros::NodeHandle node; ros::service::waitForService("spawn"); ros::ServiceClient add_turtle = node.serviceClient<turtlesim::Spawn>("spawn"); turtlesim::Spawn srv; add_turtle.call(srv); ros::Publisher turtle_vel = node.advertise<geometry_msgs::Twist>("turtle2/cmd_vel", 10); tf::TransformListener listener; ros::Rate rate(10.0); while (node.ok()){ tf::StampedTransform transform; try{ listener.lookupTransform("/turtle2", "/turtle1", ros::Time(0), transform); } catch (tf::TransformException &ex) { ROS_ERROR("%s",ex.what()); ros::Duration(1.0).sleep(); continue; } geometry_msgs::Twist vel_msg; vel_msg.angular.z = 4.0 * atan2(transform.getOrigin().y(), transform.getOrigin().x()); vel_msg.linear.x = 0.5 * sqrt(pow(transform.getOrigin().x(), 2) + pow(transform.getOrigin().y(), 2)); turtle_vel.publish(vel_msg); rate.sleep(); } return 0; };
26.822222
80
0.619718
[ "transform" ]
b4e5b323ac8e078144bc62e56f1fa54afef0e20e
4,217
cpp
C++
src/embedded_boundaries/eb_annulus.cpp
WeiqunZhang/incflo
d72eb6e3c387704d06ceee686596337e5e9711d3
[ "BSD-3-Clause" ]
null
null
null
src/embedded_boundaries/eb_annulus.cpp
WeiqunZhang/incflo
d72eb6e3c387704d06ceee686596337e5e9711d3
[ "BSD-3-Clause" ]
null
null
null
src/embedded_boundaries/eb_annulus.cpp
WeiqunZhang/incflo
d72eb6e3c387704d06ceee686596337e5e9711d3
[ "BSD-3-Clause" ]
null
null
null
#include <AMReX_EB2.H> #include <AMReX_EB2_IF_Cylinder.H> #include <AMReX_EB2_IF_Union.H> #include <AMReX_ParmParse.H> #include <algorithm> #include <embedded_boundaries_F.H> #include <incflo.H> /******************************************************************************** * * * Function to create a annular cylinder EB. * * * ********************************************************************************/ void incflo::make_eb_annulus() { // Initialise annulus parameters int direction = 0; Real outer_radius = 0.0002; Real inner_radius = 0.0001; Vector<Real> outer_centervec(3); Vector<Real> inner_centervec(3); // Get annulus information from inputs file. * ParmParse pp("annulus"); pp.query("direction", direction); pp.query("outer_radius", outer_radius); pp.query("inner_radius", inner_radius); pp.getarr("outer_center", outer_centervec, 0, 3); pp.getarr("inner_center", inner_centervec, 0, 3); Array<Real, 3> outer_center = {outer_centervec[0], outer_centervec[1], outer_centervec[2]}; Array<Real, 3> inner_center = {inner_centervec[0], inner_centervec[1], inner_centervec[2]}; // make_eb_annulus: outer and inner cylinders must have same center coordinate per direction AMREX_ASSERT(outer_center[direction] == inner_center[direction]); // Compute distance between cylinder centres Real offset = 0.0; for(int i = 0; i < 3; i++) offset += pow(outer_center[i] - inner_center[i], 2); offset = sqrt(offset); // Check that the inner cylinder is fully contained in the outer one Real smallest_gap_width = outer_radius - inner_radius - offset; AMREX_ASSERT(smallest_gap_width >= 0.0); // Compute standoff - measure of eccentricity Real standoff = 100 * smallest_gap_width / (outer_radius - inner_radius); AMREX_ASSERT((standoff >= 0) && (standoff <= 100)); // Print info about annulus amrex::Print() << " " << std::endl; amrex::Print() << " Direction: " << direction << std::endl; amrex::Print() << " Outer radius: " << outer_radius << std::endl; amrex::Print() << " Inner radius: " << inner_radius << std::endl; amrex::Print() << " Outer center: " << outer_center[0] << ", " << outer_center[1] << ", " << outer_center[2] << std::endl; amrex::Print() << " Inner center: " << inner_center[0] << ", " << inner_center[1] << ", " << inner_center[2] << std::endl; amrex::Print() << " Offset: " << offset << std::endl; amrex::Print() << " Smallest gap: " << smallest_gap_width << std::endl; amrex::Print() << " Standoff: " << standoff << std::endl; // Build the annulus implifict function as a union of two cylinders EB2::CylinderIF outer_cyl(outer_radius, direction, outer_center, true); EB2::CylinderIF inner_cyl(inner_radius, direction, inner_center, false); auto annulus = EB2::makeUnion(outer_cyl, inner_cyl); // Generate GeometryShop auto gshop = EB2::makeShop(annulus); // Build index space int max_level_here = 0; int max_coarsening_level = 100; EBSupport m_eb_support_level = EBSupport::full; EB2::Build(gshop, geom.back(), max_level_here, max_level_here + max_coarsening_level); const EB2::IndexSpace& eb_is = EB2::IndexSpace::top(); // Make the EBFabFactory for(int lev = 0; lev <= max_level; lev++) { const EB2::Level& eb_is_lev = eb_is.getLevel(geom[lev]); eb_level = &eb_is_lev; ebfactory[lev].reset(new EBFArrayBoxFactory(*eb_level, geom[lev], grids[lev], dmap[lev], {m_eb_basic_grow_cells, m_eb_volume_grow_cells, m_eb_full_grow_cells}, m_eb_support_level)); } }
43.927083
96
0.550628
[ "vector" ]
b4e778d32e2f7e73625674d765097454ee28c1a4
12,185
cc
C++
src/yb/rocksdb/db/forward_iterator_bench.cc
hstenzel/yugabyte-db
b25c8f4d7a9e66d106c41c446b71af870aefa304
[ "Apache-2.0", "CC0-1.0" ]
3,702
2019-09-17T13:49:56.000Z
2022-03-31T21:50:59.000Z
src/yb/rocksdb/db/forward_iterator_bench.cc
hstenzel/yugabyte-db
b25c8f4d7a9e66d106c41c446b71af870aefa304
[ "Apache-2.0", "CC0-1.0" ]
9,291
2019-09-16T21:47:07.000Z
2022-03-31T23:52:28.000Z
src/yb/rocksdb/db/forward_iterator_bench.cc
hstenzel/yugabyte-db
b25c8f4d7a9e66d106c41c446b71af870aefa304
[ "Apache-2.0", "CC0-1.0" ]
673
2019-09-16T21:27:53.000Z
2022-03-31T22:23:59.000Z
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // // The following only applies to changes made to this file as part of YugaByte development. // // Portions Copyright (c) YugaByte, 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 __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #if !defined(GFLAGS) || defined(ROCKSDB_LITE) #include <cstdio> int main() { fprintf(stderr, "Please install gflags to run rocksdb tools\n"); return 1; } #elif defined(OS_MACOSX) || defined(OS_WIN) // Block forward_iterator_bench under MAC and Windows int main() { return 0; } #else #include <semaphore.h> #include <atomic> #include <bitset> #include <chrono> #include <climits> #include <condition_variable> #include <limits> #include <mutex> #include <queue> #include <random> #include <thread> #include <gflags/gflags.h> #include "yb/rocksdb/cache.h" #include "yb/rocksdb/db.h" #include "yb/rocksdb/status.h" #include "yb/rocksdb/table.h" #include "yb/rocksdb/util/testharness.h" const int MAX_SHARDS = 100000; DEFINE_int32(writers, 8, ""); DEFINE_int32(readers, 8, ""); DEFINE_int64(rate, 100000, ""); DEFINE_int64(value_size, 300, ""); DEFINE_int64(shards, 1000, ""); DEFINE_int64(memtable_size, 500000000, ""); DEFINE_int64(block_cache_size, 300000000, ""); DEFINE_int64(block_size, 65536, ""); DEFINE_double(runtime, 300.0, ""); DEFINE_bool(cache_only_first, true, ""); DEFINE_bool(iterate_upper_bound, true, ""); struct Stats { char pad1[128] __attribute__((__unused__)); std::atomic<uint64_t> written{0}; char pad2[128] __attribute__((__unused__)); std::atomic<uint64_t> read{0}; std::atomic<uint64_t> cache_misses{0}; char pad3[128] __attribute__((__unused__)); } stats; struct Key { Key() {} Key(uint64_t shard_in, uint64_t seqno_in) : shard_be(htobe64(shard_in)), seqno_be(htobe64(seqno_in)) {} uint64_t shard() const { return be64toh(shard_be); } uint64_t seqno() const { return be64toh(seqno_be); } private: uint64_t shard_be; uint64_t seqno_be; } __attribute__((__packed__)); struct Reader; struct Writer; struct ShardState { char pad1[128] __attribute__((__unused__)); std::atomic<uint64_t> last_written{0}; Writer* writer; Reader* reader; char pad2[128] __attribute__((__unused__)); std::atomic<uint64_t> last_read{0}; std::unique_ptr<rocksdb::Iterator> it; std::unique_ptr<rocksdb::Iterator> it_cacheonly; Key upper_bound; rocksdb::Slice upper_bound_slice; char pad3[128] __attribute__((__unused__)); }; struct Reader { public: explicit Reader(std::vector<ShardState>* shard_states, rocksdb::DB* db) : shard_states_(shard_states), db_(db) { sem_init(&sem_, 0, 0); thread_ = std::thread(&Reader::run, this); } void run() { while (1) { sem_wait(&sem_); if (done_.load()) { break; } uint64_t shard; { std::lock_guard<std::mutex> guard(queue_mutex_); assert(!shards_pending_queue_.empty()); shard = shards_pending_queue_.front(); shards_pending_queue_.pop(); shards_pending_set_.reset(shard); } readOnceFromShard(shard); } } void readOnceFromShard(uint64_t shard) { ShardState& state = (*shard_states_)[shard]; if (!state.it) { // Initialize iterators rocksdb::ReadOptions options; options.tailing = true; if (FLAGS_iterate_upper_bound) { state.upper_bound = Key(shard, std::numeric_limits<uint64_t>::max()); state.upper_bound_slice = rocksdb::Slice( (const char*)&state.upper_bound, sizeof(state.upper_bound)); options.iterate_upper_bound = &state.upper_bound_slice; } state.it.reset(db_->NewIterator(options)); if (FLAGS_cache_only_first) { options.read_tier = rocksdb::ReadTier::kBlockCacheTier; state.it_cacheonly.reset(db_->NewIterator(options)); } } const uint64_t upto = state.last_written.load(); for (rocksdb::Iterator* it : {state.it_cacheonly.get(), state.it.get()}) { if (it == nullptr) { continue; } if (state.last_read.load() >= upto) { break; } bool need_seek = true; for (uint64_t seq = state.last_read.load() + 1; seq <= upto; ++seq) { if (need_seek) { Key from(shard, state.last_read.load() + 1); it->Seek(rocksdb::Slice((const char*)&from, sizeof(from))); need_seek = false; } else { it->Next(); } if (it->status().IsIncomplete()) { ++::stats.cache_misses; break; } assert(it->Valid()); assert(it->key().size() == sizeof(Key)); Key key; memcpy(&key, it->key().data(), it->key().size()); // fprintf(stderr, "Expecting (%ld, %ld) read (%ld, %ld)\n", // shard, seq, key.shard(), key.seqno()); assert(key.shard() == shard); assert(key.seqno() == seq); state.last_read.store(seq); ++::stats.read; } } } void onWrite(uint64_t shard) { { std::lock_guard<std::mutex> guard(queue_mutex_); if (!shards_pending_set_.test(shard)) { shards_pending_queue_.push(shard); shards_pending_set_.set(shard); sem_post(&sem_); } } } ~Reader() { done_.store(true); sem_post(&sem_); thread_.join(); } private: char pad1[128] __attribute__((__unused__)); std::vector<ShardState>* shard_states_; rocksdb::DB* db_; std::thread thread_; sem_t sem_; std::mutex queue_mutex_; std::bitset<MAX_SHARDS + 1> shards_pending_set_; std::queue<uint64_t> shards_pending_queue_; std::atomic<bool> done_{false}; char pad2[128] __attribute__((__unused__)); }; struct Writer { explicit Writer(std::vector<ShardState>* shard_states, rocksdb::DB* db) : shard_states_(shard_states), db_(db) {} void start() { thread_ = std::thread(&Writer::run, this); } void run() { std::queue<std::chrono::steady_clock::time_point> workq; std::chrono::steady_clock::time_point deadline( std::chrono::steady_clock::now() + std::chrono::nanoseconds((uint64_t)(1000000000 * FLAGS_runtime))); std::vector<uint64_t> my_shards; for (int i = 1; i <= FLAGS_shards; ++i) { if ((*shard_states_)[i].writer == this) { my_shards.push_back(i); } } std::mt19937 rng{std::random_device()()}; std::uniform_int_distribution<int> shard_dist( 0, static_cast<int>(my_shards.size()) - 1); std::string value(FLAGS_value_size, '*'); while (1) { auto now = std::chrono::steady_clock::now(); if (FLAGS_runtime >= 0 && now >= deadline) { break; } if (workq.empty()) { for (int i = 0; i < FLAGS_rate; i += FLAGS_writers) { std::chrono::nanoseconds offset(1000000000LL * i / FLAGS_rate); workq.push(now + offset); } } while (!workq.empty() && workq.front() < now) { workq.pop(); uint64_t shard = my_shards[shard_dist(rng)]; ShardState& state = (*shard_states_)[shard]; uint64_t seqno = state.last_written.load() + 1; Key key(shard, seqno); // fprintf(stderr, "Writing (%ld, %ld)\n", shard, seqno); rocksdb::Status status = db_->Put(rocksdb::WriteOptions(), rocksdb::Slice((const char*)&key, sizeof(key)), rocksdb::Slice(value)); assert(status.ok()); state.last_written.store(seqno); state.reader->onWrite(shard); ++::stats.written; } std::this_thread::sleep_for(std::chrono::milliseconds(1)); } // fprintf(stderr, "Writer done\n"); } ~Writer() { thread_.join(); } private: char pad1[128] __attribute__((__unused__)); std::vector<ShardState>* shard_states_; rocksdb::DB* db_; std::thread thread_; char pad2[128] __attribute__((__unused__)); }; struct StatsThread { explicit StatsThread(rocksdb::DB* db) : db_(db), thread_(&StatsThread::run, this) {} void run() { // using namespace std::chrono; auto tstart = std::chrono::steady_clock::now(), tlast = tstart; uint64_t wlast = 0, rlast = 0; while (!done_.load()) { { std::unique_lock<std::mutex> lock(cvm_); cv_.wait_for(lock, std::chrono::seconds(1)); } auto now = std::chrono::steady_clock::now(); double elapsed = std::chrono::duration_cast<std::chrono::duration<double> >( now - tlast).count(); uint64_t w = ::stats.written.load(); uint64_t r = ::stats.read.load(); fprintf(stderr, "%s elapsed %4lds | written %10ld | w/s %10.0f | read %10ld | " "r/s %10.0f | cache misses %10ld\n", db_->GetEnv()->TimeToString(time(nullptr)).c_str(), std::chrono::duration_cast<std::chrono::seconds>(now - tstart) .count(), w, (w - wlast) / elapsed, r, (r - rlast) / elapsed, ::stats.cache_misses.load()); wlast = w; rlast = r; tlast = now; } } ~StatsThread() { { std::lock_guard<std::mutex> guard(cvm_); done_.store(true); } cv_.notify_all(); thread_.join(); } private: rocksdb::DB* db_; std::mutex cvm_; std::condition_variable cv_; std::thread thread_; std::atomic<bool> done_{false}; }; int main(int argc, char** argv) { GFLAGS::ParseCommandLineFlags(&argc, &argv, true); std::mt19937 rng{std::random_device()()}; rocksdb::Status status; std::string path = rocksdb::test::TmpDir() + "/forward_iterator_test"; fprintf(stderr, "db path is %s\n", path.c_str()); rocksdb::Options options; options.create_if_missing = true; options.compression = rocksdb::CompressionType::kNoCompression; options.compaction_style = rocksdb::CompactionStyle::kCompactionStyleNone; options.level0_slowdown_writes_trigger = 99999; options.level0_stop_writes_trigger = 99999; options.allow_os_buffer = false; options.write_buffer_size = FLAGS_memtable_size; rocksdb::BlockBasedTableOptions table_options; table_options.block_cache = rocksdb::NewLRUCache(FLAGS_block_cache_size); table_options.block_size = FLAGS_block_size; options.table_factory.reset( rocksdb::NewBlockBasedTableFactory(table_options)); status = rocksdb::DestroyDB(path, options); assert(status.ok()); rocksdb::DB* db_raw; status = rocksdb::DB::Open(options, path, &db_raw); assert(status.ok()); std::unique_ptr<rocksdb::DB> db(db_raw); std::vector<ShardState> shard_states(FLAGS_shards + 1); std::deque<Reader> readers; while (static_cast<int>(readers.size()) < FLAGS_readers) { readers.emplace_back(&shard_states, db_raw); } std::deque<Writer> writers; while (static_cast<int>(writers.size()) < FLAGS_writers) { writers.emplace_back(&shard_states, db_raw); } // Each shard gets a random reader and random writer assigned to it for (int i = 1; i <= FLAGS_shards; ++i) { std::uniform_int_distribution<int> reader_dist(0, FLAGS_readers - 1); std::uniform_int_distribution<int> writer_dist(0, FLAGS_writers - 1); shard_states[i].reader = &readers[reader_dist(rng)]; shard_states[i].writer = &writers[writer_dist(rng)]; } StatsThread stats_thread(db_raw); for (Writer& w : writers) { w.start(); } writers.clear(); readers.clear(); } #endif // !defined(GFLAGS) || defined(ROCKSDB_LITE)
31.24359
100
0.643742
[ "vector" ]
b4e7d87c2c8c320bbfa99dea9db3fdb71eb29dcb
6,705
hpp
C++
utils/Matrix.hpp
mdcovarr/matalgo
f80b9e33b909779c48ccab3d6029d3358acd1489
[ "MIT" ]
1
2020-05-23T05:40:07.000Z
2020-05-23T05:40:07.000Z
utils/Matrix.hpp
mdcovarr/matalgo
f80b9e33b909779c48ccab3d6029d3358acd1489
[ "MIT" ]
null
null
null
utils/Matrix.hpp
mdcovarr/matalgo
f80b9e33b909779c48ccab3d6029d3358acd1489
[ "MIT" ]
null
null
null
/* * \file Matrix.hpp * \brief Matrix implementation for library */ #ifndef MATRIX_HPP #define MATRIX_HPP #include "MatrixError.hpp" #include <vector> /* * Matrix class Header File */ template <typename T> class Matrix { private: // representation of 2D matrix std::vector<T> v; // number of rows unsigned int r; // number of columns unsigned int c; protected: virtual void clear() { v.clear(); r = 0; c = 0; } public: Matrix() { clear(); } Matrix(unsigned int row, unsigned int col, T* data = 0, unsigned int dataLength = 0); Matrix(unsigned int row, unsigned int col, const std::vector<T>& data); virtual ~Matrix() { clear(); } // Operators Matrix& operator=(const Matrix&); std::vector<T> operator[](unsigned int) const; Matrix operator*(const Matrix&); Matrix transpose(); /** * Function used to get the number of rows in matrix * @return r - number of rows */ inline unsigned int rowNum() const { return r; } /** * Function used to get the number of columns in matrix * @return c - number of cols */ inline unsigned int colNum() const { return c; } /** * Function used to get the size of the matrix for all * elements in each row and col * @return */ inline unsigned int size() const { return v.size(); } /** * Funnction used to push another row to the matrix * @param t - template data type */ inline void add(const T& t) { v.push_back(t); } }; /** * Overloaded Constructor for Matrix Object * @tparam T template type * @param row - number of rows for matrix * @param col - number of columns for matrix * @param data - data we want to insert into matrix * @param dataLength - length of data */ template <typename T> Matrix<T>::Matrix(unsigned int row, unsigned int col, T* data, unsigned int dataLength) { clear(); if (row > 0 && col > 0) { r = row; c = col; unsigned int matSize = r * c; if (dataLength && data) { for (unsigned int i = 0; i < dataLength && i < matSize; i++) { v.push_back(data[i]); } } } } /** * Overloaded Constructor for Matrix Object * @tparam T template type * @param row - number of rows for matrix * @param col - number of columns for matrix * @param data - data we want to insert into matrix */ template <typename T> Matrix<T>::Matrix(unsigned int row, unsigned int col, const std::vector<T>& data) { clear(); if (row > 0 && col > 0) { r = row; c = col; unsigned int matSize = row * col; if (data.size() > 0) { for (unsigned int i = 0; i < matSize && i < data.size(); i++) { v.push_back(data[i]); } } } } /** * Overload of equals (=) operator to work with Matrix object. Used to assign * value of a matrix object to another. * @tparam T template type e.g., int, float, double * @param original - Matrix object we are copying * @return return object */ template <typename T> Matrix<T>& Matrix<T>::operator=(const Matrix<T>& original) { clear(); if (original.r > 0 && original.c > 0) { r = original.r; c = original.c; unsigned int matSize = r * c; for (unsigned int i = 0; i < matSize && i < original.size(); i++) { v.push_back(original.v[i]); } } return *this; } /** * Overload of multiplication (*) operator to work with Matrix object, Used to * multiply two Matrix objects * @tparam T template type e.g, int, float, double * @param mat2 - Second Matrix object in the multiplication * @return new Matrix<T> object representing the product of two Matrix objects */ template <typename T> Matrix<T> Matrix<T>::operator*(const Matrix<T>& mat2) { Matrix product(r, mat2.c); if (c != mat2.r) { // Need to throw an exception for index out of range throw MatrixError(2, ERROR_2); } else if (r < 1 || c < 1 || mat2.c < 1) { // Need to throw an exception for an invalid dimension of the Matrix object throw MatrixError(3, ERROR_3); } else if ((r * c > size()) || (mat2.r * mat2.c > mat2.size())) { // Need to throw an exception for an invalid amount of data throw MatrixError(4, ERROR_4); } else { // need to multiply elements and place in new Matrix for (unsigned int i = 0; i < r; i++) { for (unsigned int j = 0; j < mat2.c; j++) { T currVal = v[i * c] * mat2.v[j]; // Need to iterate through the correct location due to // single vector implementation for (unsigned int k = 1; k < c; k++){ currVal += v[i * c + k] * mat2.v[k * mat2.c + j]; } product.v.push_back(currVal); } } } return product; } /** * Overload of vector access [] operator to work with Matrix object * @tparam T template type * @param rowIndex row index we are accessing in the matrix * @return the row contents at a given index of the 2D matrix */ template <typename T> std::vector<T> Matrix<T>::operator[](unsigned int rowIndex) const { std::vector<T> output; if (rowIndex >= r) { // Need to throw an exception for index out of range throw MatrixError(1, ERROR_1); } else if ((rowIndex + 1) * c > size()) { // Need to throw an exception for index out of range throw MatrixError(4, ERROR_4); } else { unsigned int start = rowIndex * c; unsigned int end = start + c; for (unsigned int i = start; i < end; i++) { output.push_back(v[i]); } return output; } } /** * Add function to return the transposition of the Matrix * @tparam T template type * @return transposed - A Matrix object that is the transposed representation of the caller object. */ template <typename T> Matrix<T> Matrix<T>::transpose() { Matrix<T> transposed(c, r); if (r < 1 || c < 1) { throw MatrixError(3, ERROR_3); } else { for (unsigned int i = 0; i < c; i++) { for (unsigned int j = 0; j < r; j++) { transposed.v.push_back(v[ j * c + i]); } } return transposed; } } #endif // MATRIX_HPP
25.689655
99
0.549441
[ "object", "vector" ]
b4e7fe190d31f64a4ee62e50075225232db028ed
6,612
cpp
C++
dump_rm.cpp
rmit-ir/RMQV
44837cc9950969921677cf5a552cef2713f72650
[ "Apache-2.0" ]
2
2018-08-01T08:46:02.000Z
2020-03-26T00:38:18.000Z
dump_rm.cpp
JMMackenzie/RMQV
beb9a43c6b8b07045afe847d95596f91a1b95c05
[ "Apache-2.0" ]
null
null
null
dump_rm.cpp
JMMackenzie/RMQV
beb9a43c6b8b07045afe847d95596f91a1b95c05
[ "Apache-2.0" ]
2
2018-06-23T16:10:32.000Z
2018-06-27T07:21:17.000Z
#include <iostream> #include <functional> #include <unordered_map> #include <thread> #include <mutex> #include <boost/unordered_map.hpp> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/split.hpp> #include <succinct/mapper.hpp> #include "index_types.hpp" #include "wand_data_compressed.hpp" #include "wand_data_raw.hpp" #include "queries.hpp" // BOW queries #include "weighted_queries.hpp" // RM queries #include "util.hpp" #include "docvector/document_index.hpp" namespace { void printUsage(const std::string &programName) { std::cerr << "Usage: " << programName << " index_type index_filename forward_index_filename --wand wand_data_filename" << " [--compressed-wand] [--query query_filename] [--k no_docs_for_expansion]" << " [--lexicon lexicon_file]" << std::endl; } } // namespace using namespace ds2i; typedef std::vector<std::pair<double, uint64_t>> top_k_list; void do_join(std::thread& t) { t.join(); } template<typename IndexType, typename WandType> void dump_rm(const char *index_filename, const char *wand_data_filename, const char *forward_index_filename, std::vector<std::pair<uint32_t, ds2i::term_id_vec>> const &queries, const uint64_t m_k, std::unordered_map<uint32_t, std::string>& reverse_lexicon) { using namespace ds2i; IndexType index; logger() << "Loading index from " << index_filename << std::endl; boost::iostreams::mapped_file_source m(index_filename); succinct::mapper::map(index, m); document_index forward_index; logger() << "Loading forward index from " << forward_index_filename << std::endl; forward_index.load(std::string(forward_index_filename)); logger() << "Warming up posting lists" << std::endl; std::unordered_set<term_id_type> warmed_up; for (auto const &q: queries) { for (auto t: q.second) { if (!warmed_up.count(t)) { index.warmup(t); warmed_up.insert(t); } } } WandType wdata; boost::iostreams::mapped_file_source md; // Read the wand data if (wand_data_filename) { md.open(wand_data_filename); succinct::mapper::map(wdata, md, succinct::mapper::map_flags::warmup); } // Init our ranker std::unique_ptr<doc_scorer> ranker = build_ranker(wdata.average_doclen(), wdata.num_docs(), wdata.terms_in_collection(), wdata.ranker_id()); for (auto const &query: queries) { auto tmp = wand_query<WandType>(wdata, m_k); tmp(index, query.second, ranker); auto tk = tmp.topk(); auto weighted_query = forward_index.rm_expander(tk); normalize_weighted_query(weighted_query); for(size_t i = 0; i < weighted_query.size() && i < 500; i++) { std::cerr << query.first << " " << i+1 << " " << reverse_lexicon[weighted_query[i].first] << " " << weighted_query[i].second << std::endl; } } } typedef wand_data<wand_data_raw> wand_raw_index; typedef wand_data<wand_data_compressed<uniform_score_compressor>> wand_uniform_index; int main(int argc, const char **argv) { using namespace ds2i; std::string programName = argv[0]; if (argc < 4) { printUsage(programName); return 1; } std::string type = argv[1]; const char *index_filename = argv[2]; const char *forward_filename = argv[3]; const char *wand_data_filename = nullptr; const char *query_filename = nullptr; const char *lexicon_filename = nullptr; uint64_t m_k = 0; bool compressed = false; std::vector<std::pair<uint32_t, term_id_vec>> queries; for (int i = 4; i < argc; ++i) { std::string arg = argv[i]; if(arg == "--wand"){ wand_data_filename = argv[++i];; } if(arg == "--compressed-wand"){ compressed = true; } if (arg == "--query") { query_filename = argv[++i]; } if (arg == "--k") { m_k = std::stoull(argv[++i]); } if (arg == "--lexicon") { lexicon_filename = argv[++i]; } } if (lexicon_filename == nullptr) { std::cerr << "ERROR: Must provide lexicon. Quitting." << std::endl; return EXIT_FAILURE; } std::unordered_map<std::string, uint32_t> lexicon; std::unordered_map<uint32_t, std::string> reverse_lexicon; if (lexicon_filename != nullptr) { std::ifstream in_lex(lexicon_filename); if (in_lex.is_open()) { read_lexicon(in_lex, lexicon, reverse_lexicon); } else { std::cerr << "ERROR: Could not open lexicon file." << std::endl; } } term_id_vec q; uint32_t qid; if(query_filename){ std::filebuf fb; if (fb.open(query_filename, std::ios::in)) { std::istream is(&fb); if (lexicon_filename != nullptr) { while (read_query(q, qid, lexicon, is)) queries.emplace_back(qid, q); } else { while (read_query(q, qid, is)) queries.emplace_back(qid, q); } } } else { if (lexicon_filename != nullptr) { while (read_query(q, qid, lexicon)) queries.emplace_back(qid, q); } else { while (read_query(q, qid)) queries.emplace_back(qid, q); } } /**/ if (false) { #define LOOP_BODY(R, DATA, T) \ } else if (type == BOOST_PP_STRINGIZE(T)) { \ if (compressed) { \ dump_rm<BOOST_PP_CAT(T, _index), wand_uniform_index> \ (index_filename, wand_data_filename, forward_filename, queries, m_k, reverse_lexicon); \ } else { \ dump_rm<BOOST_PP_CAT(T, _index), wand_raw_index> \ (index_filename, wand_data_filename, forward_filename, queries, m_k, reverse_lexicon); \ } \ /**/ BOOST_PP_SEQ_FOR_EACH(LOOP_BODY, _, DS2I_INDEX_TYPES); #undef LOOP_BODY } else { logger() << "ERROR: Unknown type " << type << std::endl; } }
31.942029
148
0.558984
[ "vector" ]
b4ea8446e0e3d2009ceee4639d412e62a8b7d186
2,436
cpp
C++
aws-cpp-sdk-cognito-idp/source/model/ProviderUserIdentifierType.cpp
woohoou/aws-sdk-cpp
a42835a8aad2eac1e334d899a3fbfedcaa341d51
[ "Apache-2.0" ]
1
2020-07-16T19:03:13.000Z
2020-07-16T19:03:13.000Z
aws-cpp-sdk-cognito-idp/source/model/ProviderUserIdentifierType.cpp
woohoou/aws-sdk-cpp
a42835a8aad2eac1e334d899a3fbfedcaa341d51
[ "Apache-2.0" ]
18
2018-05-15T16:41:07.000Z
2018-05-21T00:46:30.000Z
aws-cpp-sdk-cognito-idp/source/model/ProviderUserIdentifierType.cpp
woohoou/aws-sdk-cpp
a42835a8aad2eac1e334d899a3fbfedcaa341d51
[ "Apache-2.0" ]
1
2021-10-01T15:29:44.000Z
2021-10-01T15:29:44.000Z
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/cognito-idp/model/ProviderUserIdentifierType.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace CognitoIdentityProvider { namespace Model { ProviderUserIdentifierType::ProviderUserIdentifierType() : m_providerNameHasBeenSet(false), m_providerAttributeNameHasBeenSet(false), m_providerAttributeValueHasBeenSet(false) { } ProviderUserIdentifierType::ProviderUserIdentifierType(const JsonValue& jsonValue) : m_providerNameHasBeenSet(false), m_providerAttributeNameHasBeenSet(false), m_providerAttributeValueHasBeenSet(false) { *this = jsonValue; } ProviderUserIdentifierType& ProviderUserIdentifierType::operator =(const JsonValue& jsonValue) { if(jsonValue.ValueExists("ProviderName")) { m_providerName = jsonValue.GetString("ProviderName"); m_providerNameHasBeenSet = true; } if(jsonValue.ValueExists("ProviderAttributeName")) { m_providerAttributeName = jsonValue.GetString("ProviderAttributeName"); m_providerAttributeNameHasBeenSet = true; } if(jsonValue.ValueExists("ProviderAttributeValue")) { m_providerAttributeValue = jsonValue.GetString("ProviderAttributeValue"); m_providerAttributeValueHasBeenSet = true; } return *this; } JsonValue ProviderUserIdentifierType::Jsonize() const { JsonValue payload; if(m_providerNameHasBeenSet) { payload.WithString("ProviderName", m_providerName); } if(m_providerAttributeNameHasBeenSet) { payload.WithString("ProviderAttributeName", m_providerAttributeName); } if(m_providerAttributeValueHasBeenSet) { payload.WithString("ProviderAttributeValue", m_providerAttributeValue); } return payload; } } // namespace Model } // namespace CognitoIdentityProvider } // namespace Aws
24.36
94
0.770115
[ "model" ]
b4eae0b4de1c2b80fd0282a50662d6095c0ac817
34,876
cpp
C++
PostLib/FEPostModel.cpp
chunkeey/FEBioStudio
f342d4ac2bc3581db792373c4265454109af92b3
[ "MIT" ]
null
null
null
PostLib/FEPostModel.cpp
chunkeey/FEBioStudio
f342d4ac2bc3581db792373c4265454109af92b3
[ "MIT" ]
null
null
null
PostLib/FEPostModel.cpp
chunkeey/FEBioStudio
f342d4ac2bc3581db792373c4265454109af92b3
[ "MIT" ]
null
null
null
/*This file is part of the FEBio Studio source code and is licensed under the MIT license listed below. See Copyright-FEBio-Studio.txt for details. Copyright (c) 2020 University of Utah, The Trustees of Columbia University in the City of New York, and others. 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.*/ // FEModel.cpp: implementation of the FEModel class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "FEPostModel.h" #include "FEDataManager.h" #include "constants.h" #include "FEMeshData_T.h" #include <stdio.h> extern int ET_HEX[12][2]; namespace Post { FEPostModel* FEPostModel::m_pThis = 0; FEPostModel::PlotObject::PlotObject() { AddColorParam(GLColor::White(), "Color"); m_tag = 0; m_id = -1; } GLColor FEPostModel::PlotObject::Color() { return GetColorValue(0); } void FEPostModel::PlotObject::SetColor(const GLColor& c) { SetColorValue(0, c); } //============================================================================= // F E P O S T M O D E L //============================================================================= // constructor FEPostModel::FEPostModel() { m_ndisp = 0; m_pDM = new FEDataManager(this); m_nTime = 0; m_fTime = 0.f; m_pThis = this; } //----------------------------------------------------------------------------- // desctructor FEPostModel::~FEPostModel() { Clear(); delete m_pDM; if (m_pThis == this) m_pThis = 0; DeleteMeshes(); ClearDependants(); } void FEPostModel::DeleteMeshes() { // delete all meshes for (size_t i = 0; i<m_mesh.size(); ++i) delete m_mesh[i]; m_mesh.clear(); for (size_t i = 0; i < m_RefState.size(); ++i) delete m_RefState[i]; m_RefState.clear(); } void FEPostModel::SetInstance(FEPostModel* fem) { m_pThis = fem; } FEPostModel* FEPostModel::GetInstance() { return m_pThis; } //----------------------------------------------------------------------------- FEState* FEPostModel::CurrentState() { return m_State[m_nTime]; } //----------------------------------------------------------------------------- void FEPostModel::SetCurrentTimeIndex(int ntime) { m_nTime = ntime; m_fTime = GetTimeValue(m_nTime); } //----------------------------------------------------------------------------- void FEPostModel::SetTimeValue(float ftime) { m_nTime = GetClosestTime(ftime); m_fTime = ftime; } //------------------------------------------------------------------------------------------ // This returns the time step whose time value is closest but less than t // int FEPostModel::GetClosestTime(double t) { FEState& s0 = *GetState(0); if (s0.m_time >= t) return 0; FEState& s1 = *GetState(GetStates() - 1); if (s1.m_time <= t) return GetStates() - 1; for (int i = 1; i<GetStates(); ++i) { FEState& s = *GetState(i); if (s.m_time >= t) return i - 1; } return GetStates() - 1; } //----------------------------------------------------------------------------- float FEPostModel::GetTimeValue(int ntime) { return GetState(ntime)->m_time; } //----------------------------------------------------------------------------- void FEPostModel::AddMesh(FEPostMesh* mesh) { m_mesh.push_back(mesh); // create a reference state for this mesh FERefState* ref = new FERefState(this); ref->m_Node.resize(mesh->Nodes()); for (int i = 0; i < mesh->Nodes(); ++i) { ref->m_Node[i].m_rt = to_vec3f(mesh->Node(i).r); } m_RefState.push_back(ref); } //----------------------------------------------------------------------------- int FEPostModel::Meshes() const { return (int) m_mesh.size(); } //----------------------------------------------------------------------------- FEPostMesh* FEPostModel::GetFEMesh(int n) { if ((n>=0) && (n<m_mesh.size())) return m_mesh[n]; else return nullptr; } //----------------------------------------------------------------------------- // Clear the data of the model void FEPostModel::Clear() { ClearObjects(); DeleteMeshes(); m_Mat.clear(); ClearStates(); m_title.clear(); m_name.clear(); } //----------------------------------------------------------------------------- void FEPostModel::SetTitle(const string& title) { m_title = title; } //----------------------------------------------------------------------------- const string& FEPostModel::GetTitle() const { return m_title; } //----------------------------------------------------------------------------- void FEPostModel::SetName(const std::string& name) { m_name = name; } //----------------------------------------------------------------------------- const string& FEPostModel::GetName() const { return m_name; } //----------------------------------------------------------------------------- // add a material to the model void FEPostModel::AddMaterial(FEMaterial& mat) { static int n = 1; if (m_Mat.empty()) n = 1; if (mat.GetName()[0] == 0) { char sz[64]; sprintf(sz, "Material%02d", n); n += 1; mat.SetName(sz); } m_Mat.push_back(mat); } //----------------------------------------------------------------------------- // clear the FE-states void FEPostModel::ClearStates() { for (int i=0; i<(int) m_State.size(); i++) delete m_State[i]; m_State.clear(); m_nTime = 0; } //----------------------------------------------------------------------------- void FEPostModel::AddState(FEState* pFEState) { pFEState->SetID((int) m_State.size()); pFEState->m_ref = m_RefState[m_RefState.size() - 1]; m_State.push_back(pFEState); } //----------------------------------------------------------------------------- // add a state void FEPostModel::AddState(float ftime) { vector<FEState*>::iterator it = m_State.begin(); for (it = m_State.begin(); it != m_State.end(); ++it) if ((*it)->m_time > ftime) { m_State.insert(it, new FEState(ftime, this, (*it)->GetFEMesh())); return; } // get last state FEState* ps = GetState(GetStates()-1); ps->SetID((int)m_State.size()); m_State.push_back(new FEState(ftime, this, ps->GetFEMesh())); } //----------------------------------------------------------------------------- // delete a state void FEPostModel::DeleteState(int n) { vector<FEState*>::iterator it = m_State.begin(); int N = m_State.size(); assert((n>=0) && (n<N)); for (int i=0; i<n; ++i) ++it; m_State.erase(it); // reindex the states for (int i=0; i<(int)m_State.size(); ++i) m_State[i]->SetID(i); } //----------------------------------------------------------------------------- // insert a state a time f void FEPostModel::InsertState(FEState *ps, float f) { vector<FEState*>::iterator it = m_State.begin(); for (it=m_State.begin(); it != m_State.end(); ++it) if ((*it)->m_time > f) { m_State.insert(it, ps); return; } m_State.push_back(ps); // reindex the states for (int i = 0; i<(int)m_State.size(); ++i) m_State[i]->SetID(i); } //----------------------------------------------------------------------------- template <typename Type> void copy_node_data(FEMeshData& d, FEMeshData& s) { FENodeData<Type>& dt = dynamic_cast<FENodeData<Type>&>(d); FENodeData<Type>& st = dynamic_cast<FENodeData<Type>&>(s); dt.copy(st); } //----------------------------------------------------------------------------- template <typename Type, Data_Format Fmt> void copy_elem_data(FEMeshData& d, FEMeshData& s) { FEElementData<Type, Fmt>& dt = dynamic_cast<FEElementData<Type, Fmt>&>(d); FEElementData<Type, Fmt>& st = dynamic_cast<FEElementData<Type, Fmt>&>(s); dt.copy(st); } //----------------------------------------------------------------------------- template <typename Type, Data_Format Fmt> void copy_face_data(FEMeshData& d, FEMeshData& s) { FEFaceData<Type, Fmt>& dt = dynamic_cast<FEFaceData<Type, Fmt>&>(d); FEFaceData<Type, Fmt>& st = dynamic_cast<FEFaceData<Type, Fmt>&>(s); dt.copy(st); } //----------------------------------------------------------------------------- // Copy a data field FEDataField* FEPostModel::CopyDataField(FEDataField* pd, const char* sznewname) { // Clone the data field FEDataField* pdcopy = pd->Clone(); // create a new name if (sznewname == 0) { char szname[256] = {0}; sprintf(szname, "%s_copy", pd->GetName().c_str()); pdcopy->SetName(szname); } else pdcopy->SetName(sznewname); // Add it to the model AddDataField(pdcopy); int ndst = FIELD_CODE(pdcopy->GetFieldID()); int nsrc = FIELD_CODE(pd ->GetFieldID()); int nstates = GetStates(); for (int i=0; i<nstates; ++i) { FEState& state = *GetState(i); FEMeshDataList& DL = state.m_Data; FEMeshData& dst = DL[ndst]; FEMeshData& src = DL[nsrc]; if (IS_NODE_FIELD(pd->GetFieldID())) { assert(pd->Format() == DATA_ITEM); if (pd->Type() == DATA_FLOAT ) copy_node_data<float >(dst, src); else if (pd->Type() == DATA_VEC3F ) copy_node_data<vec3f >(dst, src); else if (pd->Type() == DATA_MAT3FS) copy_node_data<mat3fs>(dst, src); else if (pd->Type() == DATA_MAT3FD) copy_node_data<mat3fd>(dst, src); else if (pd->Type() == DATA_MAT3F ) copy_node_data<mat3f >(dst, src); else if (pd->Type() == DATA_MAT3D ) copy_node_data<Mat3d >(dst, src); } else if (IS_FACE_FIELD(pd->GetFieldID())) { switch (pd->Format()) { case DATA_ITEM: { if (pd->Type() == DATA_FLOAT ) copy_face_data<float , DATA_ITEM>(dst, src); else if (pd->Type() == DATA_VEC3F ) copy_face_data<vec3f , DATA_ITEM>(dst, src); else if (pd->Type() == DATA_MAT3FS) copy_face_data<mat3fs, DATA_ITEM>(dst, src); } break; case DATA_NODE: { if (pd->Type() == DATA_FLOAT ) copy_face_data<float , DATA_NODE>(dst, src); else if (pd->Type() == DATA_VEC3F ) copy_face_data<vec3f , DATA_NODE>(dst, src); else if (pd->Type() == DATA_MAT3FS) copy_face_data<mat3fs, DATA_NODE>(dst, src); } break; case DATA_COMP: { if (pd->Type() == DATA_FLOAT ) copy_face_data<float , DATA_COMP>(dst, src); else if (pd->Type() == DATA_VEC3F ) copy_face_data<vec3f , DATA_COMP>(dst, src); else if (pd->Type() == DATA_MAT3FS) copy_face_data<mat3fs, DATA_COMP>(dst, src); } break; } } else if (IS_ELEM_FIELD(pd->GetFieldID())) { switch (pd->Format()) { case DATA_ITEM: { if (pd->Type() == DATA_FLOAT ) copy_elem_data<float , DATA_ITEM>(dst, src); else if (pd->Type() == DATA_VEC3F ) copy_elem_data<vec3f , DATA_ITEM>(dst, src); else if (pd->Type() == DATA_MAT3FS) copy_elem_data<mat3fs, DATA_ITEM>(dst, src); } break; case DATA_NODE: { if (pd->Type() == DATA_FLOAT ) copy_elem_data<float , DATA_NODE>(dst, src); else if (pd->Type() == DATA_VEC3F ) copy_elem_data<vec3f , DATA_NODE>(dst, src); else if (pd->Type() == DATA_MAT3FS) copy_elem_data<mat3fs, DATA_NODE>(dst, src); } break; case DATA_COMP: { if (pd->Type() == DATA_FLOAT ) copy_elem_data<float , DATA_COMP>(dst, src); else if (pd->Type() == DATA_VEC3F ) copy_elem_data<vec3f , DATA_COMP>(dst, src); else if (pd->Type() == DATA_MAT3FS) copy_elem_data<mat3fs, DATA_COMP>(dst, src); } break; } } } return pdcopy; } //----------------------------------------------------------------------------- FEDataField* createCachedDataField(FEDataField* pd, const char* sznewname) { Data_Class nclass = pd->DataClass(); Data_Type ntype = pd->Type(); Data_Format nfmt = pd->Format(); FEDataField* newField = 0; if (nclass == CLASS_NODE) { if (ntype == DATA_FLOAT ) newField = new FEDataField_T<FENodeData<float > >(sznewname); else if (ntype == DATA_VEC3F ) newField = new FEDataField_T<FENodeData<vec3f > >(sznewname); else if (ntype == DATA_MAT3FS) newField = new FEDataField_T<FENodeData<mat3fs> >(sznewname); else if (ntype == DATA_MAT3FD) newField = new FEDataField_T<FENodeData<mat3fd> >(sznewname); else if (ntype == DATA_MAT3D ) newField = new FEDataField_T<FENodeData<Mat3d > >(sznewname); else if (ntype == DATA_MAT3F ) newField = new FEDataField_T<FENodeData<mat3f > >(sznewname); else assert(false); } else if (nclass == CLASS_ELEM) { if (ntype == DATA_FLOAT) { if (nfmt == DATA_NODE ) newField = new FEDataField_T<FEElementData<float, DATA_NODE > >(sznewname); else if (nfmt == DATA_ITEM ) newField = new FEDataField_T<FEElementData<float, DATA_ITEM > >(sznewname); else if (nfmt == DATA_COMP ) newField = new FEDataField_T<FEElementData<float, DATA_COMP > >(sznewname); else if (nfmt == DATA_REGION) newField = new FEDataField_T<FEElementData<float, DATA_REGION> >(sznewname); else assert(false); } else if (ntype == DATA_VEC3F) { if (nfmt == DATA_NODE ) newField = new FEDataField_T<FEElementData<vec3f, DATA_NODE > >(sznewname); else if (nfmt == DATA_ITEM ) newField = new FEDataField_T<FEElementData<vec3f, DATA_ITEM > >(sznewname); else if (nfmt == DATA_COMP ) newField = new FEDataField_T<FEElementData<vec3f, DATA_COMP > >(sznewname); else if (nfmt == DATA_REGION) newField = new FEDataField_T<FEElementData<vec3f, DATA_REGION> >(sznewname); else assert(false); } else if (ntype == DATA_MAT3FS) { if (nfmt == DATA_NODE ) newField = new FEDataField_T<FEElementData<mat3fs, DATA_NODE > >(sznewname); else if (nfmt == DATA_ITEM ) newField = new FEDataField_T<FEElementData<mat3fs, DATA_ITEM > >(sznewname); else if (nfmt == DATA_COMP ) newField = new FEDataField_T<FEElementData<mat3fs, DATA_COMP > >(sznewname); else if (nfmt == DATA_REGION) newField = new FEDataField_T<FEElementData<mat3fs, DATA_REGION> >(sznewname); else assert(false); } else assert(false); } else if (nclass == CLASS_FACE) { if (ntype == DATA_FLOAT) { if (nfmt == DATA_NODE ) newField = new FEDataField_T<FEFaceData<float, DATA_NODE > >(sznewname); else if (nfmt == DATA_ITEM ) newField = new FEDataField_T<FEFaceData<float, DATA_ITEM > >(sznewname); else if (nfmt == DATA_COMP ) newField = new FEDataField_T<FEFaceData<float, DATA_COMP > >(sznewname); else if (nfmt == DATA_REGION) newField = new FEDataField_T<FEFaceData<float, DATA_REGION> >(sznewname); else assert(false); } else if (ntype == DATA_VEC3F) { if (nfmt == DATA_NODE ) newField = new FEDataField_T<FEFaceData<vec3f, DATA_NODE > >(sznewname); else if (nfmt == DATA_ITEM ) newField = new FEDataField_T<FEFaceData<vec3f, DATA_ITEM > >(sznewname); else if (nfmt == DATA_COMP ) newField = new FEDataField_T<FEFaceData<vec3f, DATA_COMP > >(sznewname); else if (nfmt == DATA_REGION) newField = new FEDataField_T<FEFaceData<vec3f, DATA_REGION> >(sznewname); else assert(false); } else if (ntype == DATA_MAT3FS) { if (nfmt == DATA_NODE ) newField = new FEDataField_T<FEFaceData<mat3fs, DATA_NODE > >(sznewname); else if (nfmt == DATA_ITEM ) newField = new FEDataField_T<FEFaceData<mat3fs, DATA_ITEM > >(sznewname); else if (nfmt == DATA_COMP ) newField = new FEDataField_T<FEFaceData<mat3fs, DATA_COMP > >(sznewname); else if (nfmt == DATA_REGION) newField = new FEDataField_T<FEFaceData<mat3fs, DATA_REGION> >(sznewname); else assert(false); } else assert(false); } assert(newField); return newField; } //----------------------------------------------------------------------------- template <typename T> void cached_copy_node_data(FEMeshData& dst, FEMeshData& src, int NN) { FENodeData<T>& d = dynamic_cast<FENodeData<T>&>(dst); FENodeData_T<T>& s = dynamic_cast<FENodeData_T<T>&>(src); for (int i = 0; i<NN; ++i) s.eval(i, &d[i]); } template <typename T> void cached_copy_face_data_ITEM(FEMeshData& dst, FEMeshData& src, int NF) { FEFaceData<T, DATA_ITEM>& d = dynamic_cast<FEFaceData<T, DATA_ITEM>&>(dst); FEFaceData_T<T, DATA_ITEM>& s = dynamic_cast<FEFaceData_T<T, DATA_ITEM>&>(src); T f; for (int i = 0; i<NF; ++i) { if (s.active(i)) { s.eval(i, &f); d.add(i, f); } } } template <typename T> void cached_copy_face_data_COMP(FEMeshData& dst, FEMeshData& src, FEPostMesh& mesh) { FEFaceData<T, DATA_COMP>& d = dynamic_cast<FEFaceData<T, DATA_COMP>&>(dst); FEFaceData_T<T, DATA_COMP>& s = dynamic_cast<FEFaceData_T<T, DATA_COMP>&>(src); int NF = mesh.Faces(); T f[FEFace::MAX_NODES]; for (int i = 0; i<NF; ++i) { FEFace& face = mesh.Face(i); if (s.active(i)) { int nf = face.Nodes(); s.eval(i, f); d.add(i, f, nf); } } } template <typename T> void cached_copy_face_data_NODE(FEMeshData& dst, FEMeshData& src, FEPostMesh& mesh) { FEFaceData<T, DATA_NODE>& d = dynamic_cast<FEFaceData<T, DATA_NODE>&>(dst); FEFaceData_T<T, DATA_NODE>& s = dynamic_cast<FEFaceData_T<T, DATA_NODE>&>(src); int NF = mesh.Faces(); T f[FEFace::MAX_NODES]; vector<T> vf; vector<int> faceList(1); vector<int> index; vector<int> faceSize(1); for (int i = 0; i<NF; ++i) { FEFace& face = mesh.Face(i); if (s.active(i)) { int nf = face.Nodes(); s.eval(i, f); // we need to convert data to vectors faceList[0] = i; vf.resize(nf); for (int j = 0; j<nf; ++j) vf[j] = f[j]; index.resize(nf); for (int j = 0; j<nf; ++j) index[j] = j; faceSize[0] = nf; // NOTE: This actually is equivalent to COMP format. d.add(vf, faceList, index, faceSize); } } } template <typename T> void cached_copy_elem_data_ITEM(FEMeshData& dst, FEMeshData& src, int NE) { FEElementData<T, DATA_ITEM>& d = dynamic_cast<FEElementData<T, DATA_ITEM>&>(dst); FEElemData_T<T, DATA_ITEM>& s = dynamic_cast<FEElemData_T<T, DATA_ITEM>&>(src); T f; for (int i = 0; i<NE; ++i) { if (s.active(i)) { s.eval(i, &f); d.add(i, f); } } } template <typename T> void cached_copy_elem_data_REGION(FEMeshData& dst, FEMeshData& src, int NE) { FEElementData<T, DATA_REGION>& d = dynamic_cast<FEElementData<T, DATA_REGION>&>(dst); FEElemData_T<T, DATA_REGION>& s = dynamic_cast<FEElemData_T<T, DATA_REGION>&>(src); T f; for (int i = 0; i<NE; ++i) { if (s.active(i)) { s.eval(i, &f); d.add(i, f); } } } template <typename T> void cached_copy_elem_data_COMP(FEMeshData& dst, FEMeshData& src, FEPostMesh& mesh) { FEElementData<T, DATA_COMP>& d = dynamic_cast<FEElementData<T, DATA_COMP>&>(dst); FEElemData_T<T, DATA_COMP>& s = dynamic_cast<FEElemData_T<T, DATA_COMP>&>(src); int NE = mesh.Elements(); T f[FEElement::MAX_NODES]; for (int i = 0; i<NE; ++i) { FEElement_& el = mesh.ElementRef(i); if (s.active(i)) { int ne = el.Nodes(); s.eval(i, f); d.add(i, ne, f); } } } template <typename T> void cached_copy_elem_data_NODE(FEMeshData& dst, FEMeshData& src, FEPostMesh& mesh) { FEElementData<T, DATA_NODE>& d = dynamic_cast<FEElementData<T, DATA_NODE>&>(dst); FEElemData_T<T, DATA_NODE>& s = dynamic_cast<FEElemData_T<T, DATA_NODE>&>(src); int NE = mesh.Elements(); T f[FEElement::MAX_NODES]; vector<T> vf; vector<int> elem(1); vector<int> index; for (int i = 0; i<NE; ++i) { FEElement_& el = mesh.ElementRef(i); if (s.active(i)) { int ne = el.Nodes(); s.eval(i, f); // we need to convert data to vectors elem[0] = i; vf.resize(ne); for (int j=0; j<ne; ++j) vf[j] = f[j]; index.resize(ne); for (int j=0; j<ne; ++j) index[j] = j; // NOTE: This actually is equivalent to COMP format. d.add(vf, elem, index, ne); } } } //----------------------------------------------------------------------------- //! Create a cached copy of a data field FEDataField* FEPostModel::CreateCachedCopy(FEDataField* pd, const char* sznewname) { // create a new data field that will store a cached copy FEDataField* pdcopy = createCachedDataField(pd, sznewname); if (pdcopy == 0) return 0; // Add it to the model AddDataField(pdcopy); // get the field ID codes int ndst = FIELD_CODE(pdcopy->GetFieldID()); int nsrc = FIELD_CODE(pd->GetFieldID()); // get the data info Data_Class nclass = pd->DataClass(); Data_Type ntype = pd->Type(); Data_Format nfmt = pd->Format(); // loop over all the states FEPostMesh& mesh = *GetFEMesh(0); int nstates = GetStates(); for (int i = 0; i<nstates; ++i) { FEState& state = *GetState(i); FEMeshDataList& DL = state.m_Data; // get source and destination fields FEMeshData& dst = DL[ndst]; FEMeshData& src = DL[nsrc]; // copy data if (nclass == CLASS_NODE) { int NN = mesh.Nodes(); if (ntype == DATA_FLOAT ) cached_copy_node_data<float >(dst, src, NN); else if (ntype == DATA_VEC3F ) cached_copy_node_data<vec3f >(dst, src, NN); else if (ntype == DATA_MAT3FS) cached_copy_node_data<mat3fs>(dst, src, NN); else if (ntype == DATA_MAT3FD) cached_copy_node_data<mat3fd>(dst, src, NN); else assert(false); } else if (nclass == CLASS_FACE) { int NF = mesh.Faces(); if (nfmt == DATA_ITEM) { if (ntype == DATA_FLOAT ) cached_copy_face_data_ITEM<float >(dst, src, NF); else if (ntype == DATA_VEC3F ) cached_copy_face_data_ITEM<vec3f >(dst, src, NF); else if (ntype == DATA_MAT3FS) cached_copy_face_data_ITEM<mat3fs>(dst, src, NF); else if (ntype == DATA_MAT3FD) cached_copy_face_data_ITEM<mat3fd>(dst, src, NF); else assert(false); } else if (nfmt == DATA_COMP) { if (ntype == DATA_FLOAT ) cached_copy_face_data_COMP<float >(dst, src, mesh); else if (ntype == DATA_FLOAT ) cached_copy_face_data_COMP<vec3f >(dst, src, mesh); else if (ntype == DATA_MAT3FS) cached_copy_face_data_COMP<mat3fs>(dst, src, mesh); else if (ntype == DATA_MAT3FD) cached_copy_face_data_COMP<mat3fd>(dst, src, mesh); else assert(false); } else if (nfmt == DATA_NODE) { if (ntype == DATA_FLOAT ) cached_copy_face_data_NODE<float >(dst, src, mesh); else if (ntype == DATA_FLOAT ) cached_copy_face_data_NODE<vec3f >(dst, src, mesh); else if (ntype == DATA_MAT3FS) cached_copy_face_data_NODE<mat3fs>(dst, src, mesh); else if (ntype == DATA_MAT3FD) cached_copy_face_data_NODE<mat3fd>(dst, src, mesh); else assert(false); } else assert(false); } else if (nclass == CLASS_ELEM) { int NE = mesh.Elements(); if (nfmt == DATA_ITEM) { if (ntype == DATA_FLOAT ) cached_copy_elem_data_ITEM<float >(dst, src, NE); else if (ntype == DATA_VEC3F ) cached_copy_elem_data_ITEM<vec3f >(dst, src, NE); else if (ntype == DATA_MAT3FS) cached_copy_elem_data_ITEM<mat3fs>(dst, src, NE); else if (ntype == DATA_MAT3FD) cached_copy_elem_data_ITEM<mat3fd>(dst, src, NE); else assert(false); } else if (nfmt == DATA_COMP) { if (ntype == DATA_FLOAT ) cached_copy_elem_data_COMP<float >(dst, src, mesh); else if (ntype == DATA_FLOAT ) cached_copy_elem_data_COMP<vec3f >(dst, src, mesh); else if (ntype == DATA_MAT3FS) cached_copy_elem_data_COMP<mat3fs>(dst, src, mesh); else if (ntype == DATA_MAT3FD) cached_copy_elem_data_COMP<mat3fd>(dst, src, mesh); else assert(false); } else if (nfmt == DATA_NODE) { if (ntype == DATA_FLOAT ) cached_copy_elem_data_NODE<float >(dst, src, mesh); else if (ntype == DATA_VEC3F ) cached_copy_elem_data_NODE<vec3f >(dst, src, mesh); else if (ntype == DATA_MAT3FS) cached_copy_elem_data_NODE<mat3fs>(dst, src, mesh); else if (ntype == DATA_MAT3FD) cached_copy_elem_data_NODE<mat3fd>(dst, src, mesh); else assert(false); } else if (nfmt == DATA_REGION) { if (ntype == DATA_FLOAT ) cached_copy_elem_data_REGION<float >(dst, src, NE); else if (ntype == DATA_VEC3F ) cached_copy_elem_data_REGION<vec3f >(dst, src, NE); else if (ntype == DATA_MAT3FS) cached_copy_elem_data_REGION<mat3fs>(dst, src, NE); else if (ntype == DATA_MAT3FD) cached_copy_elem_data_REGION<mat3fd>(dst, src, NE); else assert(false); } else assert(false); } else assert(false); } return pdcopy; } //----------------------------------------------------------------------------- // Get the field variable name std::string FEPostModel::getDataString(int ndata, Data_Tensor_Type ntype) { FEDataManager& dm = *GetDataManager(); return dm.getDataString(ndata, ntype); } //----------------------------------------------------------------------------- // Delete a data field void FEPostModel::DeleteDataField(FEDataField* pd) { // find out which data field this is FEDataFieldPtr it = m_pDM->FirstDataField(); int NDF = m_pDM->DataFields(), m = -1; for (int i=0; i<NDF; ++i, ++it) { if (*it == pd) { m = i; break; } } if (m == -1) { assert(false); return; } // remove this field from all states int NS = GetStates(); for (int i=0; i<NS; ++i) { FEState* ps = GetState(i); ps->m_Data.erase(m); } m_pDM->DeleteDataField(pd); // Inform all dependants UpdateDependants(); } //----------------------------------------------------------------------------- // Add a data field to all states of the model void FEPostModel::AddDataField(FEDataField* pd) { // add the data field to the data manager m_pDM->AddDataField(pd); // now add new data for each of the states vector<FEState*>::iterator it; for (it=m_State.begin(); it != m_State.end(); ++it) { (*it)->m_Data.push_back(pd->CreateData(*it)); } // update all dependants UpdateDependants(); } //----------------------------------------------------------------------------- // Add an data field to all states of the model void FEPostModel::AddDataField(FEDataField* pd, vector<int>& L) { assert(pd->DataClass() == CLASS_FACE); // add the data field to the data manager m_pDM->AddDataField(pd); // now add new meshdata for each of the states vector<FEState*>::iterator it; for (it=m_State.begin(); it != m_State.end(); ++it) { FEFaceItemData* pmd = dynamic_cast<FEFaceItemData*>(pd->CreateData(*it)); (*it)->m_Data.push_back(pmd); if (dynamic_cast<FECurvature*>(pmd)) { FECurvature* pcrv = dynamic_cast<FECurvature*>(pmd); pcrv->set_facelist(L); } if (dynamic_cast<FECongruency*>(pmd)) { FECongruency* pcon = dynamic_cast<FECongruency*>(pmd); pcon->set_facelist(L); } } // update all dependants UpdateDependants(); } //----------------------------------------------------------------------------- // This function calculates the position of a node based on the selected // displacement field. vec3f FEPostModel::NodePosition(int n, int ntime) { vec3f r; if (ntime >= 0) { FEState* state = GetState(ntime); FERefState& ref = *state->m_ref; FEPostMesh* mesh = state->GetFEMesh(); r = ref.m_Node[n].m_rt; if (m_ndisp) r += EvaluateNodeVector(n, ntime, m_ndisp); } else { FEPostMesh* mesh = GetFEMesh(0); r = to_vec3f(mesh->Node(n).r); } return r; } //----------------------------------------------------------------------------- vec3f FEPostModel::NodePosition(const vec3f& r, int ntime) { FEPostMesh* mesh = GetState(ntime)->GetFEMesh(); // find the element in which this node lies int iel = -1; double iso[3] = {0}; if (FindElementInReferenceFrame(*mesh, r, iel, iso)) { vec3f x[FEElement::MAX_NODES]; GetElementCoords(iel, ntime, x); // evaluate FEElement_& el = mesh->ElementRef(iel); vec3f xt = el.eval(x, iso[0], iso[1], iso[2]); return xt; } else { assert(false); return r; } } //----------------------------------------------------------------------------- vec3f FEPostModel::FaceNormal(FEFace& f, int ntime) { vec3f r0 = NodePosition(f.n[0], ntime); vec3f r1 = NodePosition(f.n[1], ntime); vec3f r2 = NodePosition(f.n[2], ntime); vec3f fn = (r1 - r0)^(r2 - r0); fn.Normalize(); return fn; } //----------------------------------------------------------------------------- // get the nodal coordinates of an element at time n void FEPostModel::GetElementCoords(int iel, int ntime, vec3f* r) { FEPostMesh* mesh = GetState(ntime)->GetFEMesh(); FEElement_& elem = mesh->ElementRef(iel); NODEDATA* pn = &m_State[ntime]->m_NODE[0]; for (int i=0; i<elem.Nodes(); i++) r[i] = pn[ elem.m_node[i] ].m_rt; } //----------------------------------------------------------------------------- // Update the bounding box of the mesh. Note that this box bounds the reference // configuration, not the current configuration void FEPostModel::UpdateBoundingBox() { FEPostMesh* mesh = GetFEMesh(0); if (mesh == nullptr) { m_bbox = BOX(vec3d(0, 0, 0), vec3d(1, 1, 1)); return; } FENode& n = mesh->Node(0); m_bbox.x0 = m_bbox.x1 = n.r.x; m_bbox.y0 = m_bbox.y1 = n.r.y; m_bbox.z0 = m_bbox.z1 = n.r.z; int N = mesh->Nodes(); for (int i=0; i<N; i++) { FENode& n = mesh->Node(i); if (n.r.x < m_bbox.x0) m_bbox.x0 = n.r.x; if (n.r.y < m_bbox.y0) m_bbox.y0 = n.r.y; if (n.r.z < m_bbox.z0) m_bbox.z0 = n.r.z; if (n.r.x > m_bbox.x1) m_bbox.x1 = n.r.x; if (n.r.y > m_bbox.y1) m_bbox.y1 = n.r.y; if (n.r.z > m_bbox.z1) m_bbox.z1 = n.r.z; } } //----------------------------------------------------------------------------- void FEPostModel::AddDependant(FEModelDependant* pc) { // make sure we have not added this dependant yet if (m_Dependants.empty() == false) { for (size_t i=0; i<m_Dependants.size(); ++i) { if (m_Dependants[i] == pc) return; } } // if we get here, the depedant was not added yet, so add it m_Dependants.push_back(pc); } //----------------------------------------------------------------------------- void FEPostModel::UpdateDependants() { int N = m_Dependants.size(); for (int i=0; i<N; ++i) m_Dependants[i]->Update(this); } //----------------------------------------------------------------------------- void FEPostModel::RemoveDependant(FEModelDependant* pc) { int N = m_Dependants.size(); if (N > 0) { vector<FEModelDependant*>::iterator it = m_Dependants.begin(); for (int i=0; i<N; ++i, it++) { if (m_Dependants[i] == pc) { m_Dependants.erase(it); return; } } assert(false); } } //----------------------------------------------------------------------------- void FEPostModel::ClearDependants() { int N = m_Dependants.size(); if (N > 0) { // inform the dependents that the model is about to be deleted vector<FEModelDependant*>::iterator it = m_Dependants.begin(); for (int i = 0; i<N; ++i) m_Dependants[i]->Update(0); m_Dependants.clear(); } } //----------------------------------------------------------------------------- void FEPostModel::UpdateMeshState(int ntime) { FEState& state = *GetState(ntime); FEPostMesh* mesh = state.GetFEMesh(); int NE = mesh->Elements(); for (int i = 0; i < NE; ++i) { FEElement_& el = mesh->ElementRef(i); ELEMDATA& data = state.m_ELEM[i]; if (el.IsShell()) { int n = el.Nodes(); for (int j = 0; j < n; ++j) el.m_h[j] = data.m_h[j]; } if ((data.m_state & StatusFlags::VISIBLE) == 0) { el.SetEroded(true); } else el.SetEroded(false); } // update plot objects for (int i = 0; i < PointObjects(); ++i) { Post::FEPostModel::PointObject& po = *GetPointObject(i); OBJ_POINT_DATA& di = state.m_objPt[i]; po.m_pos = di.pos; po.m_rot = di.rot; po.m_rt = di.m_rt; } for (int i = 0; i < LineObjects(); ++i) { Post::FEPostModel::LineObject& po = *GetLineObject(i); OBJ_LINE_DATA& di = state.m_objLn[i]; po.m_pos = di.pos; po.m_rot = di.rot; po.m_r1 = di.m_r1; po.m_r2 = di.m_r2; } } //----------------------------------------------------------------------------- int FEPostModel::PlotObjects() const { return PointObjects() + LineObjects(); } //----------------------------------------------------------------------------- FEPostModel::PlotObject* FEPostModel::GetPlotObject(int n) { if (n < PointObjects()) return GetPointObject(n); else return GetLineObject(n - PointObjects()); } //----------------------------------------------------------------------------- int FEPostModel::PointObjects() const { return m_Points.size(); } void FEPostModel::AddPointObject(FEPostModel::PointObject* ob) { m_Points.push_back(ob); } FEPostModel::PointObject* FEPostModel::GetPointObject(int i) { return m_Points[i]; } //----------------------------------------------------------------------------- int FEPostModel::LineObjects() const { return (int)m_Lines.size(); } void FEPostModel::AddLineObject(LineObject* ob) { m_Lines.push_back(ob); } FEPostModel::LineObject* FEPostModel::GetLineObject(int i) { return m_Lines[i]; } //----------------------------------------------------------------------------- void FEPostModel::ClearObjects() { m_Points.clear(); m_Lines.clear(); } //----------------------------------------------------------------------------- bool FEPostModel::Merge(FEPostModel* fem) { // for now, only works with one mesh if ((Meshes() != 1) || (fem->Meshes() != 1)) return false; // for now, does not work with data if ((m_pDM->DataFields() > 0) || (fem->GetDataManager()->DataFields() > 0)) return false; // only single state models if ((GetStates() > 1) || (fem->GetStates() > 1)) return false; if ((m_RefState.size() > 1) || (fem->m_RefState.size() > 1)) return false; // merge materials int NMAT0 = Materials(); int NMAT1 = fem->Materials(); for (int i = 0; i < NMAT1; ++i) m_Mat.push_back(*fem->GetMaterial(i)); // get the meshes FEMesh& mesh0 = *GetFEMesh(0); FEMesh& mesh1 = *fem->GetFEMesh(0); int NN0 = mesh0.Nodes(); int NN1 = mesh1.Nodes(); int NE0 = mesh0.Elements(); int NE1 = mesh1.Elements(); int NN = NN0 + NN1; int NE = NE0 + NE1; // create new mesh mesh0.Create(NN, NE); // copy new nodes for (int i = 0; i < NN1; ++i) { mesh0.Node(NN0 + i) = mesh1.Node(i); mesh0.Node(NN0 + i).SetID(NN0 + i + 1); } // copy new elements for (int i = 0; i < NE1; ++i) { FEElement& el = mesh0.Element(NE0 + i); el = mesh1.Element(i); for (int j = 0; j < el.Nodes(); ++j) el.m_node[j] += NN0; el.m_gid += NMAT0; el.m_MatID += NMAT0; el.SetID(NE0 + i + 1); } mesh0.BuildMesh(); // update reference state FERefState& ref0 = *m_RefState[0]; FERefState& ref1 = *fem->m_RefState[0]; ref0.m_Node.resize(NN); for (int i = 0; i < NN1; ++i) ref0.m_Node[NN0 + i] = ref1.m_Node[i]; // update state FEState& s0 = *GetState(0); s0.RebuildData(); return true; } } // namespace Post
29.136174
110
0.587711
[ "mesh", "vector", "model" ]
b4ec80deb7b4fe44a3afbd64eeaaecdeed8da4b6
2,855
cpp
C++
VoiceBridge/VoiceBridge/kaldi-win/src/gmmbin/gmm-info.cpp
sanyaade-teachings/VoiceBridge
348b0931f2bfaf33b7e0d18c68c50f448ab3de5c
[ "Apache-2.0" ]
18
2018-02-15T03:14:32.000Z
2021-07-06T08:21:13.000Z
VoiceBridge/VoiceBridge/kaldi-win/src/gmmbin/gmm-info.cpp
sanyaade-teachings/VoiceBridge
348b0931f2bfaf33b7e0d18c68c50f448ab3de5c
[ "Apache-2.0" ]
3
2020-10-25T16:35:55.000Z
2020-10-26T04:59:46.000Z
VoiceBridge/VoiceBridge/kaldi-win/src/gmmbin/gmm-info.cpp
sanyaade-teachings/VoiceBridge
348b0931f2bfaf33b7e0d18c68c50f448ab3de5c
[ "Apache-2.0" ]
7
2018-09-16T20:40:17.000Z
2021-07-06T08:21:14.000Z
/* Copyright 2017-present Zoltan Somogyi (AI-TOOLKIT), All Rights Reserved You may use this file only if you agree to the software license: AI-TOOLKIT Open Source Software License - Version 2.1 - February 22, 2018: https://ai-toolkit.blogspot.com/p/ai-toolkit-open-source-software-license.html. Also included with the source code distribution in AI-TOOLKIT-LICENSE.txt. Based on : Copyright 2012 Johns Hopkins University (Author: Daniel Povey), Apache 2.0 See ../../COPYING for clarification regarding multiple authors */ #include "base/kaldi-common.h" #include "util/common-utils.h" #include "gmm/am-diag-gmm.h" #include "hmm/transition-model.h" #include "kaldi-win/src/kaldi_src.h" /* ZSO03012018: the option to write the info to a file is added! <info-out> (out_filename) */ int GmmInfo(int argc, char *argv[]) { try { using namespace kaldi; typedef kaldi::int32 int32; const char *usage = "Write to standard output various properties of GMM-based model\n" "Usage: gmm-info [options] <model-in> <info-out>\n" "e.g.:\n" " gmm-info 1.mdl out.info\n" "See also: gmm-global-info, am-info\n"; ParseOptions po(usage); po.Read(argc, argv); if (po.NumArgs() < 1) { //po.PrintUsage(); //exit(1); LOGTW_ERROR << "wrong arguments."; return -1; } std::string model_in_filename = po.GetArg(1); std::string out_filename = po.GetArg(2); AmDiagGmm am_gmm; TransitionModel trans_model; { bool binary_read; Input ki(model_in_filename, &binary_read); trans_model.Read(ki.Stream(), binary_read); am_gmm.Read(ki.Stream(), binary_read); } fs::ofstream file_out(out_filename, fs::ofstream::binary | fs::ofstream::out); if (out_filename != "" && file_out) { file_out << "number-of-phones " << trans_model.GetPhones().size() << '\n'; file_out << "number-of-pdfs " << trans_model.NumPdfs() << '\n'; file_out << "number-of-transition-ids " << trans_model.NumTransitionIds() << '\n'; file_out << "number-of-transition-states " << trans_model.NumTransitionStates() << '\n'; file_out << "feature-dimension " << am_gmm.Dim() << '\n'; file_out << "number-of-gaussians " << am_gmm.NumGauss() << '\n'; file_out.flush(); file_out.close(); } else { LOGTW_INFO << "number of phones " << trans_model.GetPhones().size() << '.'; LOGTW_INFO << "number of pdfs " << trans_model.NumPdfs() << '.'; LOGTW_INFO << "number of transition-ids " << trans_model.NumTransitionIds() << '.'; LOGTW_INFO << "number of transition-states " << trans_model.NumTransitionStates() << '.'; LOGTW_INFO << "feature dimension " << am_gmm.Dim() << '.'; LOGTW_INFO << "number of gaussians " << am_gmm.NumGauss() << '.'; } return 0; } catch(const std::exception &e) { LOGTW_FATALERROR << e.what() << '.'; return -1; } }
34.39759
91
0.65324
[ "model" ]
b4ecddeb60d0e3b9cbb1aa5e4cf5cceb77152e1f
9,782
cpp
C++
tesseract_command_language/src/utils/flatten_utils.cpp
DavidMerzJr/tesseract_planning
4678b2ed4af107d556f39360b493c5a898d41768
[ "Apache-2.0", "BSD-2-Clause" ]
1
2022-02-28T13:36:01.000Z
2022-02-28T13:36:01.000Z
tesseract_command_language/src/utils/flatten_utils.cpp
DavidMerzJr/tesseract_planning
4678b2ed4af107d556f39360b493c5a898d41768
[ "Apache-2.0", "BSD-2-Clause" ]
12
2019-06-04T19:04:12.000Z
2020-09-11T14:33:25.000Z
tesseract_command_language/src/utils/flatten_utils.cpp
DavidMerzJr/tesseract_planning
4678b2ed4af107d556f39360b493c5a898d41768
[ "Apache-2.0", "BSD-2-Clause" ]
4
2018-07-25T15:16:52.000Z
2019-10-02T16:43:52.000Z
/** * @file flatten_utils.cpp * @brief * * @author Levi Armstrong * @date June 15, 2020 * @version TODO * @bug No known bugs * * @copyright Copyright (c) 2020, Southwest Research Institute * * @par License * Software License Agreement (Apache License) * @par * 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 * @par * 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 <tesseract_common/macros.h> TESSERACT_COMMON_IGNORE_WARNINGS_PUSH #include <algorithm> #include <console_bridge/console.h> TESSERACT_COMMON_IGNORE_WARNINGS_POP #include <tesseract_command_language/utils/flatten_utils.h> #include <tesseract_command_language/instruction_type.h> #include <tesseract_command_language/joint_waypoint.h> #include <tesseract_command_language/cartesian_waypoint.h> #include <tesseract_command_language/state_waypoint.h> namespace tesseract_planning { /** * @brief Helper function used by Flatten. Not intended for direct use * @param flattened Vector of instructions representing the full flattened composite * @param composite Composite instruction to be flattened * @param filter Used to filter only what should be considered. Should return true to include otherwise false * @param first_composite Indicates if the composite being processed is the top most composite */ void flattenHelper(std::vector<std::reference_wrapper<Instruction>>& flattened, CompositeInstruction& composite, flattenFilterFn filter, bool first_composite) { if (composite.hasStartInstruction()) if (!filter || filter(composite.getStartInstruction(), composite, first_composite)) flattened.emplace_back(composite.getStartInstruction()); for (auto& i : composite) { if (isCompositeInstruction(i)) { // By default composite instructions will not be stored just it children, but this allows for the filter to // indicate that they should be stored. if (filter) if (filter(i, composite, first_composite)) flattened.emplace_back(i); flattenHelper(flattened, *(i.cast<CompositeInstruction>()), filter, false); } else if (!filter || (filter && filter(i, composite, first_composite))) { flattened.emplace_back(i); } } } std::vector<std::reference_wrapper<Instruction>> flatten(CompositeInstruction& composite_instruction, flattenFilterFn filter) { std::vector<std::reference_wrapper<Instruction>> flattened; flattenHelper(flattened, composite_instruction, filter, true); return flattened; } /** * @brief Helper function used by Flatten. Not intended for direct use * @param flattened Vector of instructions representing the full flattened composite * @param composite Composite instruction to be flattened * @param filter Used to filter only what should be considered. Should return true to include otherwise false * @param first_composite Indicates if the composite being processed is the top most composite */ void flattenHelper(std::vector<std::reference_wrapper<const Instruction>>& flattened, const CompositeInstruction& composite, flattenFilterFn filter, bool first_composite) { if (composite.hasStartInstruction()) if (!filter || filter(composite.getStartInstruction(), composite, first_composite)) flattened.emplace_back(composite.getStartInstruction()); for (const auto& i : composite) { if (isCompositeInstruction(i)) { // By default composite instructions will not be stored just it children, but this allows for the filter to // indicate that they should be stored. if (filter) if (filter(i, composite, first_composite)) flattened.emplace_back(i); flattenHelper(flattened, *(i.cast_const<CompositeInstruction>()), filter, false); } else if (!filter || filter(i, composite, first_composite)) { flattened.emplace_back(i); } } } std::vector<std::reference_wrapper<const Instruction>> flatten(const CompositeInstruction& composite_instruction, flattenFilterFn filter) { std::vector<std::reference_wrapper<const Instruction>> flattened; flattenHelper(flattened, composite_instruction, filter, true); return flattened; } /** * @brief Helper function used by FlattenToPattern. Not intended for direct use * @param flattened Vector of instructions representing the full flattened composite * @param composite Composite instruction to be flattened * @param pattern CompositeInstruction used to determine if instruction will be flattened * @param filter Used to filter only what should be considered. Should return true to include otherwise false * @param first_composite Indicates if the composite being processed is the top most composite */ void flattenToPatternHelper(std::vector<std::reference_wrapper<Instruction>>& flattened, CompositeInstruction& composite, const CompositeInstruction& pattern, flattenFilterFn filter, bool first_composite) { if (composite.size() != pattern.size() || composite.hasStartInstruction() != pattern.hasStartInstruction()) { CONSOLE_BRIDGE_logError("Instruction and pattern sizes are mismatched"); return; } if (composite.hasStartInstruction()) if (!filter || filter(composite.getStartInstruction(), composite, first_composite)) flattened.emplace_back(composite.getStartInstruction()); for (std::size_t i = 0; i < pattern.size(); i++) { if (isCompositeInstruction(pattern.at(i)) && isCompositeInstruction(composite[i])) { // By default composite instructions will not be stored just it children, but this allows for the filter to // indicate that they should be stored. if (filter) if (filter(composite[i], composite, first_composite)) flattened.emplace_back(composite[i]); flattenToPatternHelper(flattened, *(composite[i].cast<CompositeInstruction>()), *pattern.at(i).cast_const<CompositeInstruction>(), filter, false); } else { flattened.emplace_back(composite[i]); } } } std::vector<std::reference_wrapper<Instruction>> flattenToPattern(CompositeInstruction& composite_instruction, const CompositeInstruction& pattern, flattenFilterFn filter) { std::vector<std::reference_wrapper<Instruction>> flattened; flattenToPatternHelper(flattened, composite_instruction, pattern, filter, true); return flattened; } /** * @brief Helper function used by FlattenToPattern. Not intended for direct use * @param flattened Vector of instructions representing the full flattened composite * @param composite Composite instruction to be flattened * @param pattern CompositeInstruction used to determine if instruction will be flattened * @param filter Used to filter only what should be considered. Should return true to include otherwise false * @param first_composite Indicates if the composite being processed is the top most composite */ void flattenToPatternHelper(std::vector<std::reference_wrapper<const Instruction>>& flattened, const CompositeInstruction& composite, const CompositeInstruction& pattern, flattenFilterFn filter, bool first_composite) { if (composite.size() != pattern.size() || composite.hasStartInstruction() != pattern.hasStartInstruction()) { CONSOLE_BRIDGE_logError("Instruction and pattern sizes are mismatched"); return; } if (composite.hasStartInstruction()) if (!filter || filter(composite.getStartInstruction(), composite, first_composite)) flattened.emplace_back(composite.getStartInstruction()); for (std::size_t i = 0; i < pattern.size(); i++) { if (isCompositeInstruction(pattern.at(i)) && isCompositeInstruction(composite[i])) { // By default composite instructions will not be stored just it children, but this allows for the filter to // indicate that they should be stored. if (filter) if (filter(composite[i], composite, first_composite)) flattened.emplace_back(composite[i]); flattenToPatternHelper(flattened, *(composite[i].cast_const<CompositeInstruction>()), *pattern.at(i).cast_const<CompositeInstruction>(), filter, false); } else { flattened.emplace_back(composite[i]); } } } std::vector<std::reference_wrapper<const Instruction>> flattenToPattern(const CompositeInstruction& composite_instruction, const CompositeInstruction& pattern, flattenFilterFn filter) { std::vector<std::reference_wrapper<const Instruction>> flattened; flattenToPatternHelper(flattened, composite_instruction, pattern, filter, true); return flattened; } } // namespace tesseract_planning
40.758333
113
0.688612
[ "vector" ]
b4edca32a9982c2111117c7769052db34692deae
2,799
cc
C++
src/runtime/opencl/sdaccel/sdaccel_module.cc
jiangzoi/incubator-tvm
144c6f45f7217b9df2f5605e06f0903e470ac11c
[ "Apache-2.0" ]
9
2019-12-17T08:03:54.000Z
2022-01-19T02:34:23.000Z
src/runtime/opencl/sdaccel/sdaccel_module.cc
jiangzoi/incubator-tvm
144c6f45f7217b9df2f5605e06f0903e470ac11c
[ "Apache-2.0" ]
2
2020-06-18T21:15:42.000Z
2020-06-24T17:38:37.000Z
src/runtime/opencl/sdaccel/sdaccel_module.cc
jiangzoi/incubator-tvm
144c6f45f7217b9df2f5605e06f0903e470ac11c
[ "Apache-2.0" ]
3
2020-10-04T20:30:18.000Z
2022-01-24T18:03:52.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file sdaccel_module.cc */ #include "sdaccel_module.h" #include <dmlc/memory_io.h> #include <tvm/runtime/registry.h> #include <string> #include <unordered_map> #include <vector> #include "sdaccel_common.h" namespace tvm { namespace runtime { class SDAccelModuleNode : public OpenCLModuleNode { public: explicit SDAccelModuleNode(std::string data, std::string fmt, std::unordered_map<std::string, FunctionInfo> fmap, std::string source) : OpenCLModuleNode(data, fmt, fmap, source) {} const std::shared_ptr<cl::OpenCLWorkspace>& GetGlobalWorkspace() final; }; const std::shared_ptr<cl::OpenCLWorkspace>& SDAccelModuleNode::GetGlobalWorkspace() { return cl::SDAccelWorkspace::Global(); } Module SDAccelModuleCreate(std::string data, std::string fmt, std::unordered_map<std::string, FunctionInfo> fmap, std::string source) { auto n = make_object<SDAccelModuleNode>(data, fmt, fmap, source); n->Init(); return Module(n); } Module SDAccelModuleLoadFile(const std::string& file_name, const std::string& format) { std::string data; std::unordered_map<std::string, FunctionInfo> fmap; std::string fmt = GetFileFormat(file_name, format); std::string meta_file = GetMetaFilePath(file_name); LoadBinaryFromFile(file_name, &data); LoadMetaDataFromFile(meta_file, &fmap); return SDAccelModuleCreate(data, fmt, fmap, std::string()); } Module SDAccelModuleLoadBinary(void* strm) { dmlc::Stream* stream = static_cast<dmlc::Stream*>(strm); std::string data; std::unordered_map<std::string, FunctionInfo> fmap; std::string fmt; stream->Read(&fmt); stream->Read(&fmap); stream->Read(&data); return SDAccelModuleCreate(data, fmt, fmap, std::string()); } TVM_REGISTER_GLOBAL("runtime.module.loadfile_xclbin").set_body_typed(SDAccelModuleLoadFile); TVM_REGISTER_GLOBAL("runtime.module.loadfile_awsxclbin").set_body_typed(SDAccelModuleLoadFile); } // namespace runtime } // namespace tvm
34.134146
100
0.733476
[ "vector" ]
b4f0eba012b658cbbcc597d8b16f64fd46952685
35,480
cc
C++
L1Trigger/L1TCalorimeter/src/firmware/Stage2Layer2TauAlgorithmFirmwareImp1.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
null
null
null
L1Trigger/L1TCalorimeter/src/firmware/Stage2Layer2TauAlgorithmFirmwareImp1.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
null
null
null
L1Trigger/L1TCalorimeter/src/firmware/Stage2Layer2TauAlgorithmFirmwareImp1.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
null
null
null
// // ** class l1t::Stage2Layer2TauAlgorithmFirmwareImp1 // ** authors: J. Brooke, L. Cadamuro, L. Mastrolorenzo, J.B. Sauvan, T. Strebler, O. Davignon, etc. // ** date: 2 Oct 2015 // ** Description: version of tau algorithm matching the jet-eg-tau merged implementation #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "L1Trigger/L1TCalorimeter/interface/Stage2Layer2TauAlgorithmFirmware.h" #include "L1Trigger/L1TCalorimeter/interface/CaloTools.h" #include "L1Trigger/L1TCalorimeter/interface/CaloStage2Nav.h" #include "L1Trigger/L1TCalorimeter/interface/BitonicSort.h" #include "L1Trigger/L1TCalorimeter/interface/AccumulatingSort.h" namespace l1t { bool operator > ( const l1t::Tau& a, const l1t::Tau& b ) { return a.pt() > b.pt(); } } l1t::Stage2Layer2TauAlgorithmFirmwareImp1::Stage2Layer2TauAlgorithmFirmwareImp1(CaloParamsHelper* params) : params_(params) { loadCalibrationLuts(); } l1t::Stage2Layer2TauAlgorithmFirmwareImp1::~Stage2Layer2TauAlgorithmFirmwareImp1() { } void l1t::Stage2Layer2TauAlgorithmFirmwareImp1::processEvent(const std::vector<l1t::CaloCluster> & clusters, const std::vector<l1t::CaloTower>& towers, std::vector<l1t::Tau> & taus) { // fill L1 candidates collections from clusters, merging neighbour clusters merging (clusters, towers, taus); //FIXME: TO DO // isolation (taus); dosorting(taus); } void l1t::Stage2Layer2TauAlgorithmFirmwareImp1::merging(const std::vector<l1t::CaloCluster>& clusters, const std::vector<l1t::CaloTower>& towers, std::vector<l1t::Tau>& taus) { // navigator l1t::CaloStage2Nav caloNav; // this is common to all taus in this event const int nrTowers = CaloTools::calNrTowers(-1*params_->tauPUSParam(1),params_->tauPUSParam(1),1,72,towers,1+params_->pileUpTowerThreshold(),999,CaloTools::CALO); for (const auto& mainCluster : clusters){ // loop only on valid clusters // by construction of the clustering, they are local maxima in the 9x3 jet window if (mainCluster.isValid()){ if (abs(mainCluster.hwEta()) > params_->isoTauEtaMax()) continue; // limit in main seed position in firmware taus.emplace_back(mainCluster); l1t::Tau& tau = taus.back(); int iEta = mainCluster.hwEta(); int iPhi = mainCluster.hwPhi(); int iEtaP = caloNav.offsetIEta(iEta, 1); int iEtaM = caloNav.offsetIEta(iEta, -1); int iPhiP = caloNav.offsetIPhi(iPhi, 1); int iPhiM = caloNav.offsetIPhi(iPhi, -1); int iPhiP2 = caloNav.offsetIPhi(iPhi, 2); int iPhiP3 = caloNav.offsetIPhi(iPhi, 3); int iPhiM2 = caloNav.offsetIPhi(iPhi, -2); int iPhiM3 = caloNav.offsetIPhi(iPhi, -3); // get list of neighbor seeds and determine the highest E one std::vector<l1t::CaloTower> satellites; const l1t::CaloTower& towerN2 = l1t::CaloTools::getTower(towers, iEta, iPhiM2); const l1t::CaloTower& towerN3 = l1t::CaloTools::getTower(towers, iEta, iPhiM3); const l1t::CaloTower& towerN2W = l1t::CaloTools::getTower(towers, iEtaM, iPhiM2); const l1t::CaloTower& towerN2E = l1t::CaloTools::getTower(towers, iEtaP, iPhiM2); const l1t::CaloTower& towerS2 = l1t::CaloTools::getTower(towers, iEta, iPhiP2); const l1t::CaloTower& towerS3 = l1t::CaloTools::getTower(towers, iEta, iPhiP3); const l1t::CaloTower& towerS2W = l1t::CaloTools::getTower(towers, iEtaM, iPhiP2); const l1t::CaloTower& towerS2E = l1t::CaloTools::getTower(towers, iEtaP, iPhiP2); int seedThreshold = floor(params_->egSeedThreshold()/params_->towerLsbSum()); std::vector<int> sites; // numbering of the secondary cluster sites (seed positions) // get only local max, also ask that they are above seed threshold // FIXME : in firmware N --> larger phi but apparently only for these secondaries ... sigh ... // might need to revert ; ALSO check EAST / WEST // or at least check that everything is coherent here if (is3x3Maximum(towerN2, towers, caloNav) && towerN2.hwPt() >= seedThreshold && !mainCluster.checkClusterFlag(CaloCluster::INCLUDE_NN)) sites.push_back(5); if (is3x3Maximum(towerN3, towers, caloNav) && towerN3.hwPt() >= seedThreshold) sites.push_back(7); if (is3x3Maximum(towerN2W, towers, caloNav) && towerN2W.hwPt() >= seedThreshold) sites.push_back(4); if (is3x3Maximum(towerN2E, towers, caloNav) && towerN2E.hwPt() >= seedThreshold) sites.push_back(6); if (is3x3Maximum(towerS2, towers, caloNav) && towerS2.hwPt() >= seedThreshold && !mainCluster.checkClusterFlag(CaloCluster::INCLUDE_SS)) sites.push_back(2); if (is3x3Maximum(towerS3, towers, caloNav) && towerS3.hwPt() >= seedThreshold) sites.push_back(0); if (is3x3Maximum(towerS2W, towers, caloNav) && towerS2W.hwPt() >= seedThreshold) sites.push_back(1); if (is3x3Maximum(towerS2E, towers, caloNav) && towerS2E.hwPt() >= seedThreshold) sites.push_back(3); // find neighbor with highest energy, with some preference that is defined as in the firmware // Remember: the maxima requirement is already applied // For the four towers in a T // If cluster 0 is on a maxima, use that // Else if cluster 2 is on a maxima, use that // Else if both clusters 1 & 3 are both on maxima: Use the highest energy cluster // Else if cluster 1 is on a maxima, use that // Else if cluster 3 is on a maxima, use that // Else there is no candidate // Similarly for south // Then if N>S, use N // else S std::vector<l1t::CaloCluster*> secClusters = makeSecClusters (towers, sites, mainCluster, caloNav); l1t::CaloCluster* secMaxN = nullptr; l1t::CaloCluster* secMaxS = nullptr; l1t::CaloCluster* secondaryCluster = nullptr; std::vector<int>::iterator isNeigh0 = find(sites.begin(), sites.end(), 0); std::vector<int>::iterator isNeigh1 = find(sites.begin(), sites.end(), 1); std::vector<int>::iterator isNeigh2 = find(sites.begin(), sites.end(), 2); std::vector<int>::iterator isNeigh3 = find(sites.begin(), sites.end(), 3); std::vector<int>::iterator isNeigh4 = find(sites.begin(), sites.end(), 4); std::vector<int>::iterator isNeigh5 = find(sites.begin(), sites.end(), 5); std::vector<int>::iterator isNeigh6 = find(sites.begin(), sites.end(), 6); std::vector<int>::iterator isNeigh7 = find(sites.begin(), sites.end(), 7); // N neighbor -------------------------------------------------- if (isNeigh0 != sites.end()) secMaxN = secClusters.at(isNeigh0 - sites.begin()); else if (isNeigh2 != sites.end()) secMaxN = secClusters.at(isNeigh2 - sites.begin()); else if ( isNeigh1 != sites.end() && isNeigh3 != sites.end() ) { if ((secClusters.at(isNeigh1 - sites.begin()))->hwPt() == (secClusters.at(isNeigh3 - sites.begin()))->hwPt()) { // same E --> take 1 if(mainCluster.hwEta()>0) secMaxN = secClusters.at(isNeigh1 - sites.begin()); else secMaxN = secClusters.at(isNeigh3 - sites.begin()); } else { if ((secClusters.at(isNeigh1 - sites.begin()))->hwPt() > (secClusters.at(isNeigh3 - sites.begin()))->hwPt()){ secMaxN = secClusters.at(isNeigh1 - sites.begin()); } else secMaxN = secClusters.at(isNeigh3 - sites.begin()); } } else if (isNeigh1 != sites.end()) secMaxN = secClusters.at(isNeigh1 - sites.begin()); else if (isNeigh3 != sites.end()) secMaxN = secClusters.at(isNeigh3 - sites.begin()); // S neighbor -------------------------------------------------- if (isNeigh7 != sites.end()) secMaxS = secClusters.at(isNeigh7 - sites.begin()); else if (isNeigh5 != sites.end()) secMaxS = secClusters.at(isNeigh5 - sites.begin()); else if (isNeigh4 != sites.end() && isNeigh6 != sites.end() ) { if ((secClusters.at(isNeigh4 - sites.begin()))->hwPt() == (secClusters.at(isNeigh6 - sites.begin()))->hwPt()){ // same E --> take 1 if(mainCluster.hwEta()>0) secMaxN = secClusters.at(isNeigh4 - sites.begin()); else secMaxN = secClusters.at(isNeigh6 - sites.begin()); } else { if ((secClusters.at(isNeigh4 - sites.begin()))->hwPt() > (secClusters.at(isNeigh6 - sites.begin()))->hwPt()) secMaxS = secClusters.at(isNeigh4 - sites.begin()); else secMaxS = secClusters.at(isNeigh6 - sites.begin()); } } else if (isNeigh4 != sites.end()) secMaxS = secClusters.at(isNeigh4 - sites.begin()); else if (isNeigh6 != sites.end()) secMaxS = secClusters.at(isNeigh6 - sites.begin()); // N vs S neighbor -------------------------------------------------- if (secMaxN != nullptr && secMaxS != nullptr) { if (secMaxN->hwPt() > secMaxS->hwPt()) secondaryCluster = secMaxN; else secondaryCluster = secMaxS; } else { if (secMaxN != nullptr) secondaryCluster = secMaxN; else if (secMaxS != nullptr) secondaryCluster = secMaxS; } // trim primary cluster to remove overlap of TT int neigEta [8] = {0, -1, 0, 1, -1, 0, 1, 0}; int neigPhi [8] = {3, 2, 2, 2, -2, -2, -2, -3}; vector <pair<int, int> > TTPos (10); // numbering of TT in cluster; <iEta, iPhi> TTPos.at(0) = make_pair (-1, 1); // SW TTPos.at(1) = make_pair (0, 1); // S TTPos.at(2) = make_pair (1, 1); // SE TTPos.at(3) = make_pair (1, 0); // E TTPos.at(4) = make_pair (1, -1); // NE TTPos.at(5) = make_pair (0, -1); // N TTPos.at(6) = make_pair (-1, -1); // NW TTPos.at(7) = make_pair (-1, 0); // W TTPos.at(8) = make_pair (0, 2); // SS TTPos.at(9) = make_pair (0, -2); // NN vector <CaloCluster::ClusterFlag> TTPosRemap (10); // using geographical notation TTPosRemap.at(0) = CaloCluster::INCLUDE_SW; TTPosRemap.at(1) = CaloCluster::INCLUDE_S; TTPosRemap.at(2) = CaloCluster::INCLUDE_SE; TTPosRemap.at(3) = CaloCluster::INCLUDE_E; TTPosRemap.at(4) = CaloCluster::INCLUDE_NE; TTPosRemap.at(5) = CaloCluster::INCLUDE_N; TTPosRemap.at(6) = CaloCluster::INCLUDE_NW; TTPosRemap.at(7) = CaloCluster::INCLUDE_W; TTPosRemap.at(8) = CaloCluster::INCLUDE_SS; TTPosRemap.at(9) = CaloCluster::INCLUDE_NN; // loop over TT of secondary cluster, if there is overlap remove this towers from main cluster l1t::CaloCluster mainClusterTrim = mainCluster; int secondaryClusterHwPt = 0; if(!secClusters.empty()){ secondaryClusterHwPt = secondaryCluster->hwPt(); int iSecIdxPosition = find (secClusters.begin(), secClusters.end(), secondaryCluster) - secClusters.begin(); int secondaryClusterSite = sites.at(iSecIdxPosition); for (unsigned int iTT = 0; iTT < TTPos.size(); iTT++) { //get this TT in the "frame" of the main int thisTTinMainEta = neigEta[secondaryClusterSite] + TTPos.at(iTT).first; int thisTTinMainPhi = neigPhi[secondaryClusterSite] + TTPos.at(iTT).second; pair<int, int> thisTT = make_pair (thisTTinMainEta, thisTTinMainPhi); // check if main cluster has this tower included; if true, switch it off auto thisTTItr = find (TTPos.begin(), TTPos.end(), thisTT); if (thisTTItr != TTPos.end()){ int idx = thisTTItr - TTPos.begin(); if (secondaryCluster->checkClusterFlag (TTPosRemap.at(iTT)) ) mainClusterTrim.setClusterFlag (TTPosRemap.at(idx), false); } } } // re-compute main cluster energy + position const l1t::CaloTower& seed = l1t::CaloTools::getTower(towers, iEta , iPhi ); const l1t::CaloTower& towerNW = l1t::CaloTools::getTower(towers, iEtaM, iPhiM); const l1t::CaloTower& towerN = l1t::CaloTools::getTower(towers, iEta , iPhiM); const l1t::CaloTower& towerNE = l1t::CaloTools::getTower(towers, iEtaP, iPhiM); const l1t::CaloTower& towerE = l1t::CaloTools::getTower(towers, iEtaP, iPhi ); const l1t::CaloTower& towerSE = l1t::CaloTools::getTower(towers, iEtaP, iPhiP); const l1t::CaloTower& towerS = l1t::CaloTools::getTower(towers, iEta , iPhiP); const l1t::CaloTower& towerSW = l1t::CaloTools::getTower(towers, iEtaM, iPhiP); const l1t::CaloTower& towerW = l1t::CaloTools::getTower(towers, iEtaM, iPhi ); const l1t::CaloTower& towerNN = l1t::CaloTools::getTower(towers, iEta , iPhiM2); const l1t::CaloTower& towerSS = l1t::CaloTools::getTower(towers, iEta , iPhiP2); int seedEt = seed .hwPt(); int towerEtNW = towerNW.hwPt(); int towerEtN = towerN .hwPt(); int towerEtNE = towerNE.hwPt(); int towerEtE = towerE .hwPt(); int towerEtSE = towerSE.hwPt(); int towerEtS = towerS .hwPt(); int towerEtSW = towerSW.hwPt(); int towerEtW = towerW .hwPt(); int towerEtNN = towerNN.hwPt(); int towerEtSS = towerSS.hwPt(); // Recompute hw energy from towers tau.setHwPt(seedEt); if(mainClusterTrim.checkClusterFlag(CaloCluster::INCLUDE_NW)) tau.setHwPt(tau.hwPt() + towerEtNW); if(mainClusterTrim.checkClusterFlag(CaloCluster::INCLUDE_N)) tau.setHwPt(tau.hwPt() + towerEtN); if(mainClusterTrim.checkClusterFlag(CaloCluster::INCLUDE_NE)) tau.setHwPt(tau.hwPt() + towerEtNE); if(mainClusterTrim.checkClusterFlag(CaloCluster::INCLUDE_E)) tau.setHwPt(tau.hwPt() + towerEtE); if(mainClusterTrim.checkClusterFlag(CaloCluster::INCLUDE_SE)) tau.setHwPt(tau.hwPt() + towerEtSE); if(mainClusterTrim.checkClusterFlag(CaloCluster::INCLUDE_S)) tau.setHwPt(tau.hwPt() + towerEtS); if(mainClusterTrim.checkClusterFlag(CaloCluster::INCLUDE_SW)) tau.setHwPt(tau.hwPt() + towerEtSW); if(mainClusterTrim.checkClusterFlag(CaloCluster::INCLUDE_W)) tau.setHwPt(tau.hwPt() + towerEtW); if(mainClusterTrim.checkClusterFlag(CaloCluster::INCLUDE_NN)) tau.setHwPt(tau.hwPt() + towerEtNN); if(mainClusterTrim.checkClusterFlag(CaloCluster::INCLUDE_SS)) tau.setHwPt(tau.hwPt() + towerEtSS); //Merging tau.setRawEt(tau.hwPt()+secondaryClusterHwPt); tau.setIsMerged(secondaryClusterHwPt>0); // ================================================================== // Energy calibration // ================================================================== // Corrections function of ieta, ET, and cluster shape int calibPt = calibratedPt(mainCluster, towers, tau.rawEt(), tau.isMerged()); tau.setHwPt(calibPt); // isolation int isoLeftExtension = params_->tauIsoAreaNrTowersEta(); int isoRightExtension = params_->tauIsoAreaNrTowersEta(); if(mainCluster.checkClusterFlag(CaloCluster::TRIM_LEFT)) isoRightExtension++; else isoLeftExtension++; int isolBit = 0; int tauHwFootprint = tau.rawEt(); unsigned int LUTaddress = isoLutIndex(tauHwFootprint, mainCluster.hwEta(), nrTowers); int hwEtSum = CaloTools::calHwEtSum(iEta,iPhi,towers,-isoLeftExtension,isoRightExtension, -1*params_->tauIsoAreaNrTowersPhi(),params_->tauIsoAreaNrTowersPhi(),params_->tauPUSParam(2),CaloTools::CALO); int hwIsoEnergy = hwEtSum - tauHwFootprint; if (hwIsoEnergy < 0) hwIsoEnergy = 0; // just in case the cluster is outside the window? should be very rare isolBit = (((hwIsoEnergy < (params_->tauIsolationLUT()->data(LUTaddress))) || (params_->tauIsolationLUT()->data(LUTaddress)>255)) ? 1 : 0); //int isolBit2 = (((hwIsoEnergy < (params_->tauIsolationLUT2()->data(LUTaddress))) || (params_->tauIsolationLUT2()->data(LUTaddress)>255)) ? 1 : 0); //isolBit += (isolBit2 << 1); tau.setHwIso(isolBit); // development vars tau.setTowerIPhi(iPhi); tau.setTowerIEta(iEta); int qual = seed.hwQual(); bool denomZeroFlag = ((qual&0x1) > 0); bool eOverHFlag = ((qual&0x2) > 0); int hasEM = (eOverHFlag || !denomZeroFlag); tau.setHasEM(hasEM > 0); tau.setIsoEt((short int) hwIsoEnergy); tau.setNTT((short int) nrTowers); // Physical eta/phi. Computed from ieta/iphi of the seed tower and the fine-grain position within the seed double eta = 0.; double phi = 0.; double seedEta = CaloTools::towerEta(iEta); double seedEtaSize = CaloTools::towerEtaSize(iEta); double seedPhi = CaloTools::towerPhi(iEta, iPhi); double seedPhiSize = CaloTools::towerPhiSize(iEta); if(mainCluster.fgEta()==0) eta = seedEta; // center else if(mainCluster.fgEta()==2) eta = seedEta + seedEtaSize*0.251; // center + 1/4 else if(mainCluster.fgEta()==1) eta = seedEta - seedEtaSize*0.251; // center - 1/4 //fgPhi is recomputed after trimming int fgPhi = 0; int EtUp = 0; if(mainClusterTrim.checkClusterFlag(CaloCluster::INCLUDE_NE)) EtUp += towerEtNE; if(mainClusterTrim.checkClusterFlag(CaloCluster::INCLUDE_N)) EtUp += towerEtN; if(mainClusterTrim.checkClusterFlag(CaloCluster::INCLUDE_NW)) EtUp += towerEtNW; if(mainClusterTrim.checkClusterFlag(CaloCluster::INCLUDE_NN)) EtUp += towerEtNN; int EtDown = 0; if(mainClusterTrim.checkClusterFlag(CaloCluster::INCLUDE_SE)) EtDown += towerEtSE; if(mainClusterTrim.checkClusterFlag(CaloCluster::INCLUDE_S)) EtDown += towerEtS; if(mainClusterTrim.checkClusterFlag(CaloCluster::INCLUDE_SW)) EtDown += towerEtSW; if(mainClusterTrim.checkClusterFlag(CaloCluster::INCLUDE_SS)) EtDown += towerEtSS; // if(EtDown>EtUp) fgPhi = 2; else if(EtUp>EtDown) fgPhi = 1; if(fgPhi==0) phi = seedPhi; // center else if(fgPhi==2) phi = seedPhi + seedPhiSize*0.251; // center + 1/4 else if(fgPhi==1) phi = seedPhi - seedPhiSize*0.251; // center - 1/4 // Set 4-vector math::PtEtaPhiMLorentzVector calibP4((double)calibPt*params_->tauLsb(), eta, phi, 0.); tau.setP4(calibP4); // delete all sec clusters that were allocated with new for (unsigned int isec = 0; isec < secClusters.size(); isec++) delete secClusters.at(isec); } } // end loop on clusters } // ----------------------------------------------------------------------------------- void l1t::Stage2Layer2TauAlgorithmFirmwareImp1::dosorting (std::vector<l1t::Tau>& taus) { // prepare content to be sorted -- each phi ring contains 18 elements, with Et = 0 if no candidate exists math::PtEtaPhiMLorentzVector emptyP4; l1t::Tau tempTau (emptyP4, 0, 0, 0, 0); std::vector< std::vector<l1t::Tau> > tauEtaPos( params_->isoTauEtaMax() , std::vector<l1t::Tau>(18, tempTau)); std::vector< std::vector<l1t::Tau> > tauEtaNeg( params_->isoTauEtaMax() , std::vector<l1t::Tau>(18, tempTau)); for (unsigned int iTau = 0; iTau < taus.size(); iTau++) { if (taus.at(iTau).hwEta() > 0) tauEtaPos.at( taus.at(iTau).hwEta()-1).at((72-taus.at(iTau).hwPhi())/4) = taus.at(iTau); else tauEtaNeg.at( -(taus.at(iTau).hwEta()+1)).at((72-taus.at(iTau).hwPhi())/4) = taus.at(iTau); } AccumulatingSort <l1t::Tau> etaPosSorter(6); AccumulatingSort <l1t::Tau> etaNegSorter(6); std::vector<l1t::Tau> accumEtaPos; std::vector<l1t::Tau> accumEtaNeg; for( int ieta = 0 ; ieta < params_->isoTauEtaMax() ; ++ieta) { // eta + std::vector<l1t::Tau>::iterator start_, end_; start_ = tauEtaPos.at(ieta).begin(); end_ = tauEtaPos.at(ieta).end(); BitonicSort<l1t::Tau>(down, start_, end_); etaPosSorter.Merge( tauEtaPos.at(ieta) , accumEtaPos ); // eta - start_ = tauEtaNeg.at(ieta).begin(); end_ = tauEtaNeg.at(ieta).end(); BitonicSort<l1t::Tau>(down, start_, end_); etaNegSorter.Merge( tauEtaNeg.at(ieta) , accumEtaNeg ); } // put all 12 candidates in the original tau vector, removing zero energy ones taus.clear(); for (l1t::Tau acctau : accumEtaPos) { if (acctau.hwPt() > 0) taus.push_back(acctau); } for (l1t::Tau acctau : accumEtaNeg) { if (acctau.hwPt() > 0) taus.push_back(acctau); } } // ----------------------------------------------------------------------------------- void l1t::Stage2Layer2TauAlgorithmFirmwareImp1::loadCalibrationLuts() { float minScale = 0.; float maxScale = 2.; float minScaleEta = 0.5; float maxScaleEta = 1.5; offsetBarrelEH_ = 0.5; offsetBarrelH_ = 1.5; offsetEndcapsEH_ = 0.; offsetEndcapsH_ = 1.5; // In the combined calibration LUT, upper 3-bits are used as LUT index: // (0=BarrelA, 1=BarrelB, 2=BarrelC, 3=EndCapA, 4=EndCapA, 5=EndCapA, 6=Eta) enum {LUT_UPPER = 3}; enum {LUT_OFFSET = 0x80}; l1t::LUT* lut = params_->tauCalibrationLUT(); unsigned int size = (1 << lut->nrBitsData()); unsigned int nBins = (1 << (lut->nrBitsAddress() - LUT_UPPER)); std::vector<float> emptyCoeff; emptyCoeff.resize(nBins,0.); float binSize = (maxScale-minScale)/(float)size; for(unsigned iLut=0; iLut < 6; ++iLut ) { coefficients_.push_back(emptyCoeff); for(unsigned addr=0;addr<nBins;addr++) { float y = (float)lut->data(iLut*LUT_OFFSET + addr); coefficients_[iLut][addr] = minScale + binSize*y; } } size = (1 << lut->nrBitsData()); nBins = (1 << 6); // can't auto-extract this now due to combined LUT. emptyCoeff.resize(nBins,0.); binSize = (maxScaleEta-minScaleEta)/(float)size; coefficients_.push_back(emptyCoeff); for(unsigned addr=0;addr<nBins;addr++) { float y = (float)lut->data(6*LUT_OFFSET + addr); coefficients_.back()[addr] = minScaleEta + binSize*y; } } bool l1t::Stage2Layer2TauAlgorithmFirmwareImp1::compareTowers (l1t::CaloTower TT1, l1t::CaloTower TT2) { // 1. compare hwPt (for the moment no switch with E and H only, always use E+H) if (TT1.hwPt() < TT2.hwPt()) return true; if (TT1.hwPt() > TT2.hwPt()) return false; // 2. if equal pT, most central -- eta is in the range -32, 32 with ieta = 0 skipped if (abs(TT1.hwEta()) > abs(TT2.hwEta())) return true; if (abs(TT1.hwEta()) < abs(TT2.hwEta())) return false; // 3. if equal eta, compare phi (arbitrary) return (TT1.hwPhi() < TT2.hwPhi()); // towers towards S are favored (remember: N --> smaller phi, S --> larger phi) } bool l1t::Stage2Layer2TauAlgorithmFirmwareImp1::is3x3Maximum (const l1t::CaloTower& tower, const std::vector<CaloTower>& towers, l1t::CaloStage2Nav& caloNav) { int iEta = tower.hwEta(); int iPhi = tower.hwPhi(); // 1 : > // 2 : >= int mask [3][3] = { { 1,2,2 }, { 1,0,2 }, { 1,1,2 }, }; bool vetoTT = false; // false if it is a local max i.e. no veto for (int deta = -1; deta < 2; deta++) { for (int dphi = -1; dphi < 2; dphi++) { int iEtaNeigh = caloNav.offsetIEta(iEta, deta); int iPhiNeigh = caloNav.offsetIPhi(iPhi, dphi); const l1t::CaloTower& towerNeigh = l1t::CaloTools::getTower(towers, iEtaNeigh, iPhiNeigh); if ( mask[2-(dphi+1)][deta +1] == 0 ) continue; if ( mask[2-(dphi+1)][deta +1] == 1 ) vetoTT = (tower.hwPt() < towerNeigh.hwPt()); if ( mask[2-(dphi+1)][deta +1] == 2 ) vetoTT = (tower.hwPt() <= towerNeigh.hwPt()); if (vetoTT) break; } if (vetoTT) break; } return (!vetoTT); // negate because I ask if is a local maxima } std::vector<l1t::CaloCluster*> l1t::Stage2Layer2TauAlgorithmFirmwareImp1::makeSecClusters (const std::vector<l1t::CaloTower>& towers, std::vector<int> & sites, const l1t::CaloCluster& mainCluster, l1t::CaloStage2Nav& caloNav) { int neigEta [8] = {0, -1, 0, 1, -1, 0, 1, 0}; int neigPhi [8] = {3, 2, 2, 2, -2, -2, -2, -3}; int clusterThreshold = floor(params_->egNeighbourThreshold()/params_->towerLsbSum()); int iEtamain = mainCluster.hwEta(); int iPhimain = mainCluster.hwPhi(); std::vector<CaloCluster*> secClusters; for (unsigned int isite = 0; isite < sites.size(); isite++) { // build full cluster at this site const int siteNumber = sites.at(isite); int iSecEta = caloNav.offsetIEta(iEtamain, neigEta[siteNumber]); int iSecPhi = caloNav.offsetIPhi(iPhimain, neigPhi[siteNumber]); const l1t::CaloTower& towerSec = l1t::CaloTools::getTower(towers, iSecEta, iSecPhi); math::XYZTLorentzVector emptyP4; l1t::CaloCluster* secondaryCluster = new l1t::CaloCluster ( emptyP4, towerSec.hwPt(), towerSec.hwEta(), towerSec.hwPhi() ) ; secondaryCluster->setHwPtEm(towerSec.hwEtEm()); secondaryCluster->setHwPtHad(towerSec.hwEtHad()); secondaryCluster->setHwSeedPt(towerSec.hwPt()); secondaryCluster->setHwPt(towerSec.hwPt()); int iSecEtaP = caloNav.offsetIEta(iSecEta, 1); int iSecEtaM = caloNav.offsetIEta(iSecEta, -1); int iSecPhiP = caloNav.offsetIPhi(iSecPhi, 1); int iSecPhiP2 = caloNav.offsetIPhi(iSecPhi, 2); int iSecPhiM = caloNav.offsetIPhi(iSecPhi, -1); int iSecPhiM2 = caloNav.offsetIPhi(iSecPhi, -2); const l1t::CaloTower& towerNW = l1t::CaloTools::getTower(towers, iSecEtaM, iSecPhiM); const l1t::CaloTower& towerN = l1t::CaloTools::getTower(towers, iSecEta , iSecPhiM); const l1t::CaloTower& towerNE = l1t::CaloTools::getTower(towers, iSecEtaP, iSecPhiM); const l1t::CaloTower& towerE = l1t::CaloTools::getTower(towers, iSecEtaP, iSecPhi ); const l1t::CaloTower& towerSE = l1t::CaloTools::getTower(towers, iSecEtaP, iSecPhiP); const l1t::CaloTower& towerS = l1t::CaloTools::getTower(towers, iSecEta , iSecPhiP); const l1t::CaloTower& towerSW = l1t::CaloTools::getTower(towers, iSecEtaM, iSecPhiP); const l1t::CaloTower& towerW = l1t::CaloTools::getTower(towers, iSecEtaM, iSecPhi ); const l1t::CaloTower& towerNN = l1t::CaloTools::getTower(towers, iSecEta , iSecPhiM2); const l1t::CaloTower& towerSS = l1t::CaloTools::getTower(towers, iSecEta , iSecPhiP2); // just use E+H for clustering int towerEtNW = towerNW.hwPt(); int towerEtN = towerN .hwPt(); int towerEtNE = towerNE.hwPt(); int towerEtE = towerE .hwPt(); int towerEtSE = towerSE.hwPt(); int towerEtS = towerS .hwPt(); int towerEtSW = towerSW.hwPt(); int towerEtW = towerW .hwPt(); int towerEtNN = towerNN.hwPt(); int towerEtSS = towerSS.hwPt(); int towerEtEmNW = towerNW.hwEtEm(); int towerEtEmN = towerN .hwEtEm(); int towerEtEmNE = towerNE.hwEtEm(); int towerEtEmE = towerE .hwEtEm(); int towerEtEmSE = towerSE.hwEtEm(); int towerEtEmS = towerS .hwEtEm(); int towerEtEmSW = towerSW.hwEtEm(); int towerEtEmW = towerW .hwEtEm(); int towerEtEmNN = towerNN.hwEtEm(); int towerEtEmSS = towerSS.hwEtEm(); // int towerEtHadNW = towerNW.hwEtHad(); int towerEtHadN = towerN .hwEtHad(); int towerEtHadNE = towerNE.hwEtHad(); int towerEtHadE = towerE .hwEtHad(); int towerEtHadSE = towerSE.hwEtHad(); int towerEtHadS = towerS .hwEtHad(); int towerEtHadSW = towerSW.hwEtHad(); int towerEtHadW = towerW .hwEtHad(); int towerEtHadNN = towerNN.hwEtHad(); int towerEtHadSS = towerSS.hwEtHad(); if(towerEtNW < clusterThreshold) secondaryCluster->setClusterFlag(CaloCluster::INCLUDE_NW, false); if(towerEtN < clusterThreshold) { secondaryCluster->setClusterFlag(CaloCluster::INCLUDE_N , false); secondaryCluster->setClusterFlag(CaloCluster::INCLUDE_NN, false); } if(towerEtNE < clusterThreshold) secondaryCluster->setClusterFlag(CaloCluster::INCLUDE_NE, false); if(towerEtE < clusterThreshold) secondaryCluster->setClusterFlag(CaloCluster::INCLUDE_E , false); if(towerEtSE < clusterThreshold) secondaryCluster->setClusterFlag(CaloCluster::INCLUDE_SE, false); if(towerEtS < clusterThreshold) { secondaryCluster->setClusterFlag(CaloCluster::INCLUDE_S , false); secondaryCluster->setClusterFlag(CaloCluster::INCLUDE_SS, false); } if(towerEtSW < clusterThreshold) secondaryCluster->setClusterFlag(CaloCluster::INCLUDE_SW, false); if(towerEtW < clusterThreshold) secondaryCluster->setClusterFlag(CaloCluster::INCLUDE_W , false); if(towerEtNN < clusterThreshold) secondaryCluster->setClusterFlag(CaloCluster::INCLUDE_NN, false); if(towerEtSS < clusterThreshold) secondaryCluster->setClusterFlag(CaloCluster::INCLUDE_SS, false); // compute cluster energy according to cluster flags if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_NW)) secondaryCluster->setHwPt(secondaryCluster->hwPt() + towerEtNW); if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_N)) secondaryCluster->setHwPt(secondaryCluster->hwPt() + towerEtN); if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_NE)) secondaryCluster->setHwPt(secondaryCluster->hwPt() + towerEtNE); if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_E)) secondaryCluster->setHwPt(secondaryCluster->hwPt() + towerEtE); if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_SE)) secondaryCluster->setHwPt(secondaryCluster->hwPt() + towerEtSE); if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_S)) secondaryCluster->setHwPt(secondaryCluster->hwPt() + towerEtS); if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_SW)) secondaryCluster->setHwPt(secondaryCluster->hwPt() + towerEtSW); if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_W)) secondaryCluster->setHwPt(secondaryCluster->hwPt() + towerEtW); if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_NN)) secondaryCluster->setHwPt(secondaryCluster->hwPt() + towerEtNN); if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_SS)) secondaryCluster->setHwPt(secondaryCluster->hwPt() + towerEtSS); // if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_NW)) secondaryCluster->setHwPtEm(secondaryCluster->hwPtEm() + towerEtEmNW); if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_N)) secondaryCluster->setHwPtEm(secondaryCluster->hwPtEm() + towerEtEmN); if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_NE)) secondaryCluster->setHwPtEm(secondaryCluster->hwPtEm() + towerEtEmNE); if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_E)) secondaryCluster->setHwPtEm(secondaryCluster->hwPtEm() + towerEtEmE); if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_SE)) secondaryCluster->setHwPtEm(secondaryCluster->hwPtEm() + towerEtEmSE); if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_S)) secondaryCluster->setHwPtEm(secondaryCluster->hwPtEm() + towerEtEmS); if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_SW)) secondaryCluster->setHwPtEm(secondaryCluster->hwPtEm() + towerEtEmSW); if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_W)) secondaryCluster->setHwPtEm(secondaryCluster->hwPtEm() + towerEtEmW); if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_NN)) secondaryCluster->setHwPtEm(secondaryCluster->hwPtEm() + towerEtEmNN); if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_SS)) secondaryCluster->setHwPtEm(secondaryCluster->hwPtEm() + towerEtEmSS); // if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_NW)) secondaryCluster->setHwPtHad(secondaryCluster->hwPtHad() + towerEtHadNW); if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_N)) secondaryCluster->setHwPtHad(secondaryCluster->hwPtHad() + towerEtHadN); if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_NE)) secondaryCluster->setHwPtHad(secondaryCluster->hwPtHad() + towerEtHadNE); if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_E)) secondaryCluster->setHwPtHad(secondaryCluster->hwPtHad() + towerEtHadE); if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_SE)) secondaryCluster->setHwPtHad(secondaryCluster->hwPtHad() + towerEtHadSE); if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_S)) secondaryCluster->setHwPtHad(secondaryCluster->hwPtHad() + towerEtHadS); if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_SW)) secondaryCluster->setHwPtHad(secondaryCluster->hwPtHad() + towerEtHadSW); if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_W)) secondaryCluster->setHwPtHad(secondaryCluster->hwPtHad() + towerEtHadW); if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_NN)) secondaryCluster->setHwPtHad(secondaryCluster->hwPtHad() + towerEtHadNN); if(secondaryCluster->checkClusterFlag(CaloCluster::INCLUDE_SS)) secondaryCluster->setHwPtHad(secondaryCluster->hwPtHad() + towerEtHadSS); // save this cluster in the vector secClusters.push_back (secondaryCluster); } return secClusters; } // isMerged=0,1 ; hasEM=0,1 unsigned int l1t::Stage2Layer2TauAlgorithmFirmwareImp1::calibLutIndex (int ieta, int Et, int hasEM, int isMerged) { int absieta = abs(ieta); if (absieta > 28) absieta = 28; if (Et > 255) Et = 255; unsigned int compressedEta = params_->tauCompressLUT()->data(absieta); unsigned int compressedEt = params_->tauCompressLUT()->data((0x1<<5)+Et); unsigned int address = (compressedEta<<7)+(compressedEt<<2)+(hasEM<<1)+isMerged;//2 bits eta, 5 bits et, 1 bit hasEM, 1 bis isMerged // unsigned int address = (compressedEt<<4)+(compressedEta<<2)+(hasEM<<1)+isMerged; return address; } int l1t::Stage2Layer2TauAlgorithmFirmwareImp1::calibratedPt(const l1t::CaloCluster& clus, const std::vector<l1t::CaloTower>& towers, int hwPt, bool isMerged) { // get seed tower const l1t::CaloTower& seedTT = l1t::CaloTools::getTower(towers, CaloTools::caloEta(clus.hwEta()), clus.hwPhi()); int qual = seedTT.hwQual(); bool denomZeroFlag = ((qual&0x1) > 0); bool eOverHFlag = ((qual&0x2) > 0); int hasEM = (eOverHFlag || !denomZeroFlag); int isMergedI = (isMerged ? 1 : 0); unsigned int idx = calibLutIndex(clus.hwEta(), hwPt, hasEM, isMergedI); unsigned int corr = params_->tauCalibrationLUT()->data(idx); // now apply calibration factor: corrPt = rawPt * (corr[LUT] + 0.5) // where corr[LUT] is an integer mapped to the range [0, 2] int rawPt = hwPt; if (rawPt > 8191) rawPt = 8191; // 13 bits for uncalibrated E int corrXrawPt = corr*rawPt; // 17 bits int calibPt = (corrXrawPt>>9); // (10 bits) = (7 bits) + (9 bits) if (calibPt > 4095) calibPt = 4095; // 12 bit in output return calibPt; } unsigned int l1t::Stage2Layer2TauAlgorithmFirmwareImp1::isoLutIndex(int Et, int hweta, unsigned int nrTowers) { // normalize to limits int aeta = abs(hweta); // input bits (NB: must be THE SAME in the input LUT for the compression) // int etaBits = 6 --> 64 // int etBits = 13 --> 8192 // int nTTBits = 10 --> 1024 if (Et >= 255) Et = 255; // 8 bit for the input of compression LUT if (aeta >= 31) aeta = 31; if (nrTowers >= 1023) nrTowers = 1023; // get compressed value // NB: these also must MATCH the values in the LUT --> fix when new compression scheme is used // ultimately, the same compresison LUT as calibration will be used // etaCmprBits = 2; // EtCmprBits = 4;//changed from 3, transparent to user // nTTCmprBits = 3; int etaCmpr = params_->tauCompressLUT()->data(aeta); int etCmpr = params_->tauCompressLUT()->data((0x1<<5)+Et);//offset: 5 bits from ieta int nTTCmpr = params_->tauCompressLUT()->data((0x1<<5)+(0x1<<8)+nrTowers);//offset non-compressed: 5 bits from ieta, 8 bits from iEt // get the address -- NOTE: this also depends on the compression scheme! unsigned int address = ( (etaCmpr << 10) | (etCmpr << 5) | nTTCmpr );//ordering compressed: 2 bits iEta, 5 bits iEt, 5 bits nTT return address; }
47.433155
225
0.673168
[ "shape", "vector" ]
b4f122c84b4be80350fd06a0438d336144648c2b
8,692
cpp
C++
msgs/src/Pubmsgs.cpp
Zcyyy/bitbots_meta
7e921d2f46d2e196d3b8212fcaeeca5df5291134
[ "MIT" ]
null
null
null
msgs/src/Pubmsgs.cpp
Zcyyy/bitbots_meta
7e921d2f46d2e196d3b8212fcaeeca5df5291134
[ "MIT" ]
null
null
null
msgs/src/Pubmsgs.cpp
Zcyyy/bitbots_meta
7e921d2f46d2e196d3b8212fcaeeca5df5291134
[ "MIT" ]
1
2019-08-01T11:30:25.000Z
2019-08-01T11:30:25.000Z
#include <iostream> #include <ros/ros.h> #include "humanoid_league_msgs/GoalRelative.h" #include "humanoid_league_msgs/LineInformationRelative.h" #include <sensor_msgs/PointCloud2.h> #include <nav_msgs/Odometry.h>//quick walking node #include "humanoid_league_msgs/TeamData.h" #include "humanoid_league_msgs/GameState.h" #include "humanoid_league_msgs/ObstaclesRelative.h" #include <Eigen/Eigen> #include <Eigen/Dense> using namespace Eigen; int main( int argc, char **argv ) { ros::init(argc, argv, "test_node"); ros::NodeHandle n; /*通过"testData"Node仿真发送下列messages,其中"visual_odometry" "visualCompass"在bitbots_meta中尚未更新。*/ ros::Publisher pubTeamData = n.advertise<humanoid_league_msgs::TeamData>("teamdata_topic",10); ros::Publisher pubGoalRelative = n.advertise<humanoid_league_msgs::GoalRelative>("goal_relative",10); ros::Publisher pubObsRelative = n.advertise<humanoid_league_msgs::ObstaclesRelative>("obstacles_relative",10); ros::Publisher pubLineInformationRelative = n.advertise<humanoid_league_msgs::LineInformationRelative>("line_relative",10); ros::Publisher pubWlakOdometry = n.advertise<nav_msgs::Odometry>("walk_odometry",10); ros::Publisher pubVisualOdometry = n.advertise<nav_msgs::Odometry>("visual_odometry",10); ros::Publisher pubPointCloud2 = n.advertise<sensor_msgs::PointCloud2>("line_relative_pc",10); ros::Publisher pubGameState = n.advertise<humanoid_league_msgs::GameState>("gamestate",10); // ros::Publisher pubVisualCompass = n.advertise<>(); // ros::Publisher pubBallRelative = n.advertise<humanoid_league_msgs::BallRelative>("ball_relative",10); Matrix<float, 24, 7> MatrixGoal; Matrix<float, 9, 6> MatrixObs; Matrix<float, 6, 2> MatrixSegstart; Matrix<float, 6, 2> MatrixSegend; Matrix<float, 6, 6> MatrixCircle; //lx, ly, rx, ry, cx, cy, c MatrixGoal << //fake data:七个一组,分别对应上述值。 4, 2, 4, 4, 4, 3, 1, 4, 2, 4, 4, 4, 3, 1, 4, 2, 4, 4, 4, 3, 1, 4, 2, 4, 4, 4, 3, 1, 4, 2, 4, 4, 4, 3, 1, 4, 2, 4, 4, 4, 3, 1, 4, 2, 4, 4, 4, 3, 1, 4, 2, 4, 4, 4, 3, 1, 4, 2, 4, 4, 4, 3, 1, 4, 2, 4, 4, 4, 3, 1, 4, 2, 4, 4, 4, 3, 1, 4, 2, 4, 4, 4, 3, 1, 4, 2, 4, 4, 4, 3, 1, 4, 2, 4, 4, 4, 3, 1, 4, 2, 4, 4, 4, 3, 1, 4, 2, 4, 4, 4, 3, 1, 3.9, 2, 3.9, 3.9, 4, 3, 1, 3.7, 2, 3.7, 4, 3.7, 3, 1, 3.5, 2, 3.5, 4, 3.5, 3, 1, 3.3, 2, 3.3, 4, 3.3, 3, 1, 3.1, 2, 3.1, 4, 3.1, 3, 1, 2.9, 2, 2.9, 4, 2.9, 3, 1, 2.7, 2, 2.7, 4, 2.7, 3, 1, 2.5, 2, 2.5, 4, 2.5, 3, 1; //x, y, w, h, t, c MatrixObs << 0.5, -2, 0.5, 0.5, 3, 0.7, 0.8, -2, 0.5, 0.5, 3, 0.7, 1, -2, 0.5, 0.5, 3, 0.7, 1.2, -2, 0.5, 0.5, 3, 0.7, 1.2, -2.2, 0.5, 0.5, 3, 0.7, 1.2, -2.5, 0.5, 0.5, 3, 0.7, 1.2, -2.7, 0.5, 0.5, 3, 0.7, 1.0, -2.5, 0.5, 0.5, 3, 0.7, 0.8, -2.3, 0.5, 0.5, 3, 0.7 ; //线的起点坐标,两个值一组 MatrixSegstart << 0,0, 0,0, 0,0, 0,0, 0,0, 0,0;//TODO:1.make data,2.declear it //线的终点,两个值一组 MatrixSegend << 0,0, 0,0, 0,0, 0,0, 0,0, 0,0; //三个点确定一个圆,六个值一组,分别是左点,中点,右点 MatrixCircle << 0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0; humanoid_league_msgs::GoalRelative goal; humanoid_league_msgs::TeamData team; humanoid_league_msgs::ObstacleRelative obs; std::vector<humanoid_league_msgs::ObstacleRelative> Obs; humanoid_league_msgs::ObstaclesRelative obstacle; humanoid_league_msgs::LineSegmentRelative linesegment; std::vector<humanoid_league_msgs::LineSegmentRelative> lineSegment; humanoid_league_msgs::LineIntersectionRelative lineinter; std::vector<humanoid_league_msgs::LineIntersectionRelative> lineInter; humanoid_league_msgs::LineCircleRelative linecircle; std::vector<humanoid_league_msgs::LineCircleRelative> lineCircle; humanoid_league_msgs::LineInformationRelative line; humanoid_league_msgs::GameState gamestate; int timeCounter = 30; bool firsthalf = true; int durationHalfGame = 60; ros::Rate loop_rate(10); while(ros::ok()) { for(int i = 0; i < MatrixGoal.rows(); i++) { goal.header.seq = i; goal.header.stamp = ros::Time::now(); goal.header.frame_id = "base_footprint"; goal.left_post.x = MatrixGoal(i,0); goal.left_post.y = MatrixGoal(i,1); goal.right_post.x = MatrixGoal(i,2); goal.right_post.y = MatrixGoal(i,3); goal.center_direction.x = MatrixGoal(i,4); goal.center_direction.y = MatrixGoal(i,5); goal.confidence = MatrixGoal(i,6); if(i<MatrixObs.rows()) { obs.playerNumber = -1; obs.position.x = MatrixObs(i,0);//Point obs.position.y = MatrixObs(i,1); obs.width = MatrixObs(i,2); obs.height = MatrixObs(i,3); obs.color = MatrixObs(i,4); obs.confidence = MatrixObs(i,5); Obs.push_back(obs); obstacle.header.stamp = ros::Time::now(); obstacle.header.frame_id = "base_footprint"; obstacle.obstacles = Obs; } if(i<6) { for(int j = 0; j < 6; j++ ) { for(int k = 0; k < 6; k++ ) { linesegment.start.x = MatrixSegstart(k,0); linesegment.start.y = MatrixSegstart(k,1); linesegment.end.x = MatrixSegend(k,0); linesegment.end.y = MatrixSegend(k,1); linesegment.confidence = 1; lineSegment.push_back(linesegment); } lineinter.segments = lineSegment; lineinter.type = 0; lineinter.confidence = 1; } lineInter.push_back(lineinter); } if(i<6) { linecircle.left.x = MatrixCircle(i,0); linecircle.left.y = MatrixCircle(i,1); linecircle.middle.x = MatrixCircle(i,2); linecircle.middle.y = MatrixCircle(i,3); linecircle.right.x = MatrixCircle(i,4); linecircle.right.y = MatrixCircle(i,5); linecircle.confidence = 1; lineCircle.push_back(linecircle); } gamestate.header.frame_id = i; gamestate.header.stamp = ros::Time::now(); gamestate.secondaryState = 0; gamestate.secondsTillUnpenalized = timeCounter; // Penalty boolean gamestate.penalized = timeCounter > 0 ; // Sets halftime and rest secs gamestate.firstHalf = firsthalf; gamestate.secondsRemaining = durationHalfGame; // Sets Score gamestate.ownScore = 7; gamestate.rivalScore = 1; // team colors gamestate.teamColor = 1;// magenta timeCounter -= 1; if(timeCounter < 0) { timeCounter = 0; } durationHalfGame -= 1; if(durationHalfGame == 0) { durationHalfGame = 60; firsthalf = false; } line.intersections = lineInter; line.segments = lineSegment; line.circles = lineCircle; obstacle.obstacles = Obs; pubGoalRelative.publish(goal); pubObsRelative.publish(obstacle); pubLineInformationRelative.publish(line); pubGameState.publish(gamestate); loop_rate.sleep(); } } } /* //bitbots_meta TODO; iteam.header.seq = ; team.header.stamp = ros::Time::now(); team.header.frame_id = ; team.robot_ids[3]; team.role[2]; team.action[1]; team.state[1]; team.robot_positions = ;//数组 team.oppgoal_relative = ;//数组 team.avg_walking_speed = ; team.time_to_position_at_ball = ; team.max_kicking_distance = ; pubTeamData.publish(team); nav_msgs::Odometry walkodom; walkodom.header.seq = ; walkodom.header.stamp = ros::Time::now(); walkodomm.header.frame_id = ; walkodom.string_child_frame_id = ; walkodom.pose = ;//geometry_msgs/PoseWithCovariance walkodom.twist = ;//geometry_msgs/TwistWithCovariance pubWlakOdometry.publish(walkodom); sensor_msgs::PointCloud2 line; line.header.seq = ; line.header.stamp = ros::Time::now(); line.header.frame_id = ; line.height = ; line.width = ; line.fields = ;//sensor_msgs/PointField[] line.is_bigendian = ;//bool line.point_step = ; line.row_step = ; line.data = ; line.is_dense = ;//bool */
39.689498
124
0.580189
[ "vector" ]
b4f41a88ced9a761c9455c1a9754fa82e66b0baa
2,927
cpp
C++
_FRAMEWORK/source/framework/EliteAI/EliteGraphs/ENavGraph.cpp
Tris666w/Flow-Field-Pathfinding
7a0f825567eec3d7bd028c3a1f2fea743a007e7e
[ "MIT" ]
null
null
null
_FRAMEWORK/source/framework/EliteAI/EliteGraphs/ENavGraph.cpp
Tris666w/Flow-Field-Pathfinding
7a0f825567eec3d7bd028c3a1f2fea743a007e7e
[ "MIT" ]
null
null
null
_FRAMEWORK/source/framework/EliteAI/EliteGraphs/ENavGraph.cpp
Tris666w/Flow-Field-Pathfinding
7a0f825567eec3d7bd028c3a1f2fea743a007e7e
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "ENavGraph.h" #include "framework\EliteAI\EliteGraphs\EliteGraphAlgorithms\EAStar.h" using namespace Elite; Elite::NavGraph::NavGraph(const Polygon& contourMesh, float playerRadius = 1.0f) : Graph2D(false), m_pNavMeshPolygon(nullptr) { //Create the navigation mesh (polygon of navigatable area= Contour - Static Shapes) m_pNavMeshPolygon = new Polygon(contourMesh); // Create copy on heap //Get all shapes from all static rigidbodies with NavigationCollider flag auto vShapes = PHYSICSWORLD->GetAllStaticShapesInWorld(PhysicsFlags::NavigationCollider); //Store all children for (auto shape : vShapes) { shape.ExpandShape(playerRadius); m_pNavMeshPolygon->AddChild(shape); } //Triangulate m_pNavMeshPolygon->Triangulate(); //Create the actual graph (nodes & connections) from the navigation mesh CreateNavigationGraph(); } Elite::NavGraph::~NavGraph() { delete m_pNavMeshPolygon; m_pNavMeshPolygon = nullptr; } int Elite::NavGraph::GetNodeIdxFromLineIdx(int lineIdx) const { auto nodeIt = std::find_if(m_Nodes.begin(), m_Nodes.end(), [lineIdx](const NavGraphNode* n) { return n->GetLineIndex() == lineIdx; }); if (nodeIt != m_Nodes.end()) { return (*nodeIt)->GetIndex(); } return invalid_node_index; } Elite::Polygon* Elite::NavGraph::GetNavMeshPolygon() const { return m_pNavMeshPolygon; } void Elite::NavGraph::CreateNavigationGraph() { //1. Go over all the edges of the navigationmesh and create nodes int nodeIndex = 0; for (auto const pLine : m_pNavMeshPolygon->GetLines()) { if (m_pNavMeshPolygon->GetTrianglesFromLineIndex(pLine->index).size() > 1) //Connected to another triangle { auto* pNewNode = new NavGraphNode{ nodeIndex++, pLine->index, CalculateMiddle(pLine->p1,pLine->p2) }; AddNode(pNewNode); } } //2. Create connections now that every node is created for (auto const pTriangle : m_pNavMeshPolygon->GetTriangles()) { std::vector<int> validNodeIndexVector{}; for (auto const lineIndex : pTriangle->metaData.IndexLines) { for (auto const currentNode : m_Nodes) { if (currentNode->GetLineIndex() == lineIndex) { validNodeIndexVector.push_back(currentNode->GetIndex()); break; } } } if (validNodeIndexVector.size() == 2) { auto const newNode = new GraphConnection2D{ validNodeIndexVector[0],validNodeIndexVector[1] }; AddConnection(newNode); } else if (validNodeIndexVector.size() == 3) { auto const newNode1 = new GraphConnection2D{ validNodeIndexVector[0],validNodeIndexVector[1] }; auto const newNode2 = new GraphConnection2D{ validNodeIndexVector[1],validNodeIndexVector[2] }; auto const newNode3 = new GraphConnection2D{ validNodeIndexVector[2],validNodeIndexVector[0] }; AddConnection(newNode1); AddConnection(newNode2); AddConnection(newNode3); } } //3. Set the connections cost to the actual distance SetConnectionCostsToDistance(); }
28.417476
135
0.737957
[ "mesh", "shape", "vector" ]
b4f85ad410c5501a34c32719bb56260c4ea70cab
12,174
cpp
C++
Modules/CemrgAppModule/src/CemrgMeasure.cpp
SVRTK/CEMRG_SVR
30ed81b50e02eaeb957ca5de6167968ebb3af176
[ "BSD-3-Clause" ]
null
null
null
Modules/CemrgAppModule/src/CemrgMeasure.cpp
SVRTK/CEMRG_SVR
30ed81b50e02eaeb957ca5de6167968ebb3af176
[ "BSD-3-Clause" ]
null
null
null
Modules/CemrgAppModule/src/CemrgMeasure.cpp
SVRTK/CEMRG_SVR
30ed81b50e02eaeb957ca5de6167968ebb3af176
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ /*========================================================================= * * Measurements Tools for MITK * * Cardiac Electromechanics Research Group * http://www.cemrg.co.uk/ * orod.razeghi@kcl.ac.uk * * This software is distributed WITHOUT ANY WARRANTY or SUPPORT! * =========================================================================*/ //Vtk #include <vtkPolyData.h> #include <vtkMath.h> #include <vtkIdList.h> #include <vtkMassProperties.h> //Qmitk #include <mitkIOUtil.h> //Qt #include "CemrgMeasure.h" void CemrgMeasure::Convert(QString dir, mitk::DataNode::Pointer node) { mitk::BaseData::Pointer data = node->GetData(); mitk::PointSet::Pointer set = dynamic_cast<mitk::PointSet*>(data.GetPointer()); int items = 0; for (mitk::PointSet::PointsIterator it = set->Begin(); it != set->End(); ++it) { items++; } ofstream file; double x, y, z; file.open(dir.toStdString() + mitk::IOUtil::GetDirectorySeparator() + "input.vtk"); //Header file << "# vtk DataFile Version 3.0" << endl; file << "vtk output" << endl; file << "ASCII" << endl; file << "DATASET POLYDATA" << endl; file << "POINTS " << items << " float" << endl; //Body items = 0; for (mitk::PointSet::PointsIterator it = set->Begin(); it != set->End(); ++it) { x = it.Value().GetElement(0) * -1; y = it.Value().GetElement(1) * -1; z = it.Value().GetElement(2); items+=3; file << x << " " << y << " " << z << " "; if (items%9==0) file << endl; }//for file.close(); } std::vector <std::tuple<double, double, double>> CemrgMeasure::Deconvert(QString dir, int noFile) { double x, y, z; std::string line; unsigned int items; std::vector<std::string> tokens; std::vector <std::tuple<double, double, double>> points; ifstream file(dir.toStdString() + mitk::IOUtil::GetDirectorySeparator() + "transformed-" + std::to_string(noFile) + ".vtk"); if (file.is_open()) { //Skip header for (int i=0; i<5; i++) getline(file,line); //Read main while (getline(file,line)) { items = 0; tokens = Split(line,tokens); while (items<tokens.size()) { x = std::stod(tokens.at(items + 0)) * -1; y = std::stod(tokens.at(items + 1)) * -1; z = std::stod(tokens.at(items + 2)); items+=3; points.push_back(std::tuple<double, double, double>(x,y,z)); } } file.close(); }//_if return points; } double CemrgMeasure::CalcDistance(std::vector <std::tuple<double, double, double>>& points) { double dist = 0; if (points.size() != 2) dist = -1; else dist = CalcDist3D(points.at(0), points.at(1)); return dist; } double CemrgMeasure::CalcPerimeter(std::vector <std::tuple<double, double, double>>& points) { double peri = 0; if (points.size() < 3) { peri = -1; } else { for (unsigned int i=0; i<points.size(); i++) { if (i < points.size() - 1) peri = peri + CalcDist3D(points.at(i), points.at(i+1)); else peri = peri + 0; //CalcDist3D(points.at(i), points.at(0)); closed chain perimeter }//_for } return peri; } double CemrgMeasure::CalcArea(std::vector<std::tuple<double, double, double>>& points) { double area = 0; std::tuple<double, double, double> mean = CalcMean(points); if (points.size() < 3) { area = -1; } else { for(unsigned int i=0; i<points.size(); i++) { if (i < points.size() - 1) area = area + Heron(points.at(i), points.at(i+1), mean); else area = area + Heron(points.at(i), points.at(0), mean); }//_for } return area; } mitk::Point3D CemrgMeasure::FindCentre(mitk::PointSet::Pointer pointset) { std::vector <std::tuple<double, double, double>> points; for (int i=0; i<pointset->GetSize(); i++) { std::tuple<double, double, double> point; std::get<0>(point) = pointset->GetPoint(i).GetElement(0); std::get<1>(point) = pointset->GetPoint(i).GetElement(1); std::get<2>(point) = pointset->GetPoint(i).GetElement(2); points.push_back(point); }//_for mitk::Point3D centrePoint; std::tuple<double, double, double> centre = CalcMean(points); centrePoint[0] = std::get<0>(centre); centrePoint[1] = std::get<1>(centre); centrePoint[2] = std::get<2>(centre); return centrePoint; } double CemrgMeasure::GetSphericity(vtkPolyData* LAC_poly) { double LACA; double LAC_mc[3]; double AR, sigma, Sphericity; //containers for centre of mass, area, etc. double** TiMC; double* TiA; TiMC = new double*[LAC_poly->GetNumberOfCells()]; for (int i=0; i<LAC_poly->GetNumberOfCells(); i++) { TiMC[i] = new double[3]; } TiA = new double[LAC_poly->GetNumberOfCells()]; GetCentreOfMassOfEachT(LAC_poly, TiMC); GetArea(LAC_poly, TiA, LACA); GetCentreOfMass(TiMC, TiA, LAC_poly->GetNumberOfCells(), LACA, LAC_mc); GetAverageRadius(TiMC, TiA, LAC_poly->GetNumberOfCells(), LAC_mc, LACA, AR); LASphericity(TiMC, TiA, LAC_poly->GetNumberOfCells(), LAC_mc, LACA, AR, sigma, Sphericity); return Sphericity; } double CemrgMeasure::calcVolumeMesh(mitk::Surface::Pointer surface) { vtkSmartPointer<vtkMassProperties> mass = vtkSmartPointer<vtkMassProperties>::New(); mass->SetInputData(surface->GetVtkPolyData()); mass->Update(); return mass->GetVolume(); } double CemrgMeasure::calcSurfaceMesh(mitk::Surface::Pointer surface) { vtkSmartPointer<vtkMassProperties> mass = vtkSmartPointer<vtkMassProperties>::New(); mass->SetInputData(surface->GetVtkPolyData()); mass->Update(); return mass->GetSurfaceArea(); } /******************************************** * Private Members Defintions * ********************************************/ std::tuple<double, double, double> CemrgMeasure::CalcMean(std::vector <std::tuple<double, double, double>>& points) { double x_s = 0; double y_s = 0; double z_s = 0; for(unsigned int i=0; i<points.size(); i++) { x_s = x_s + std::get<0>(points.at(i)); y_s = y_s + std::get<1>(points.at(i)); z_s = z_s + std::get<2>(points.at(i)); }//_for x_s /= points.size(); y_s /= points.size(); z_s /= points.size(); //Mean point std::tuple<double, double, double> mean(x_s, y_s, z_s); return mean; } double CemrgMeasure::CalcDist3D( std::tuple<double, double, double>& pointA, std::tuple<double, double, double>& pointB) { double x_d = std::get<0>(pointA) - std::get<0>(pointB); double y_d = std::get<1>(pointA) - std::get<1>(pointB); double z_d = std::get<2>(pointA) - std::get<2>(pointB); //Distance between two points double distance = sqrt(pow(x_d,2) + pow(y_d,2) + pow(z_d,2)); return distance; } double CemrgMeasure::Heron( std::tuple<double, double, double>& pointA, std::tuple<double, double, double>& pointB, std::tuple<double, double, double>& centre) { //3D distances double ab = CalcDist3D(pointA, pointB); double ac = CalcDist3D(pointA, centre); double bc = CalcDist3D(pointB, centre); //Calculate area of triangle double speri = (ab+ac+bc) / 2; double tArea = sqrt(speri*(speri-ab)*(speri-ac)*(speri-bc)); return tArea; } std::vector<std::string>& CemrgMeasure::Split(const std::string& str, std::vector<std::string>& elements) { elements.clear(); std::string item; std::stringstream ss(str); while (getline(ss, item, ' ')) elements.push_back(item); return elements; } void CemrgMeasure::GetArea(vtkPolyData* polys, double* TiA, double& LACA) { double p1[3], p2[3], p3[3]; double p1_p2[3]; // p1 minus p2 double p2_p3[3]; // p2 minus p3 double crossProduct[3]; LACA = 0; vtkSmartPointer<vtkIdList> cell_points = vtkSmartPointer<vtkIdList>::New(); for (int i=0; i<polys->GetNumberOfCells(); i++) { //vtkIdType neighbor_point; polys->GetCellPoints(i, cell_points); // Get all three vertices vtkIdType neighbor_point_id = cell_points->GetId(0); polys->GetPoint( neighbor_point_id, p1); neighbor_point_id = cell_points->GetId(1); polys->GetPoint( neighbor_point_id, p2); neighbor_point_id = cell_points->GetId(2); polys->GetPoint( neighbor_point_id, p3); vtkMath::Subtract(p1, p2, p1_p2); vtkMath::Subtract(p2, p3, p2_p3); vtkMath::Cross(p1_p2, p2_p3, crossProduct); TiA[i] = 0.5*vtkMath::Norm(crossProduct); LACA += TiA[i]; } cout << "Total area LACA = " << LACA << endl; } void CemrgMeasure::GetCentreOfMass(double** TiMC, double* TiA, int TiMC_size, double LACA, double* LAC_mc) { LAC_mc[0] = 0; LAC_mc[1] = 0; LAC_mc[2] = 0; double contrib; for (int i=0; i<TiMC_size; i++) { contrib = TiA[i]/LACA; LAC_mc[0]+=(contrib)*TiMC[i][0]; LAC_mc[1]+=(contrib)*TiMC[i][1]; LAC_mc[2]+=(contrib)*TiMC[i][2]; } } void CemrgMeasure::GetCentreOfMassOfEachT(vtkPolyData* polys, double** TiMC) { int num_points = 0; vtkIdType num_cell_points; double cX, cY, cZ; double cP[3]; vtkSmartPointer<vtkIdList> cell_points = vtkSmartPointer<vtkIdList>::New(); for (int i=0; i<polys->GetNumberOfCells(); i++) { cX=0; cY=0; cZ=0; num_points=0; vtkIdType neighbor_point; polys->GetCellPoints(i, cell_points); num_cell_points = cell_points->GetNumberOfIds(); for (neighbor_point = 0; neighbor_point < num_cell_points; ++neighbor_point) { // Get the neighbour point id vtkIdType neighbor_point_id = cell_points->GetId(neighbor_point); // Get the neighbour point position polys->GetPoint( neighbor_point_id, cP ); cX+=cP[0]; cY+=cP[1]; cZ+=cP[2]; num_points++; } cX/=num_points; cY/=num_points; cZ/=num_points; TiMC[i][0] = cX; TiMC[i][1] = cY; TiMC[i][2] = cZ; } } void CemrgMeasure::GetAverageRadius(double** TiMC, double* TiA, double TiMC_size, double* LAC_mc, double LACA, double& AR) { double contrib; double a[3], b[3], a_minus_b[3]; AR = 0; for (int i=0; i<TiMC_size; i++) { a[0] = LAC_mc[0]; a[1] = LAC_mc[1]; a[2] = LAC_mc[2]; b[0] = TiMC[i][0]; b[1] = TiMC[i][1]; b[2] = TiMC[i][2]; vtkMath::Subtract(a,b,a_minus_b); contrib = TiA[i]/LACA; AR += contrib*vtkMath::Norm(a_minus_b); } } void CemrgMeasure::LASphericity( double** TiMC, double* TiA, double TiMC_size, double* LAC_mc, double LACA, double AR, double& sigma, double& Sphericity) { double contrib; double a[3], b[3], a_minus_b[3]; double phi=0, eps=0, CVS=0; for (int i=0; i<TiMC_size; i++) { contrib = TiA[i]/LACA; a[0] = LAC_mc[0]; a[1] = LAC_mc[1]; a[2] = LAC_mc[2]; b[0] = TiMC[i][0]; b[1] = TiMC[i][1]; b[2] = TiMC[i][2]; vtkMath::Subtract(a,b,a_minus_b); phi = (vtkMath::Norm(a_minus_b) - AR)*(vtkMath::Norm(a_minus_b) - AR); eps += contrib*phi; } sigma = sqrt(eps); CVS = sigma/AR; Sphericity = 100*(1-CVS); }
29.911548
130
0.579267
[ "vector", "3d" ]
b4fb577e7c9dbc5dd872d112982bb1f9481e88b5
4,295
cc
C++
mindspore/lite/tools/optimizer/fusion/transpose_matmul_fusion.cc
Greatpanc/mindspore_zhb
c2511f7d6815b9232ac4427e27e2c132ed03e0d9
[ "Apache-2.0" ]
1
2021-11-19T14:21:45.000Z
2021-11-19T14:21:45.000Z
mindspore/lite/tools/optimizer/fusion/transpose_matmul_fusion.cc
LaiYongqiang/mindspore
1b7a38ccd86b55af50a0ea55c7f2f43813ed3e0e
[ "Apache-2.0" ]
null
null
null
mindspore/lite/tools/optimizer/fusion/transpose_matmul_fusion.cc
LaiYongqiang/mindspore
1b7a38ccd86b55af50a0ea55c7f2f43813ed3e0e
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2021 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "tools/optimizer/fusion/transpose_matmul_fusion.h" #include <memory> #include <vector> #include "tools/optimizer/common/gllo_utils.h" #include "tools/optimizer/common/format_utils.h" #include "nnacl/op_base.h" #include "ops/mat_mul.h" #include "ops/op_utils.h" namespace mindspore { namespace opt { namespace { inline const std::vector<int> kMatMulTransPerm1 = {0, 1, 3, 2}; inline const std::vector<int> kMatMulTransPerm2 = {0, 2, 1}; inline const std::vector<int> kMatMulTransPerm3 = {1, 0}; bool CheckInputTransposeNode(const CNodePtr &cnode, bool *indices, size_t indices_len) { MS_ASSERT(cnode != nullptr && indices != nullptr); MS_ASSERT(indices_len / sizeof(bool) == DIMENSION_2D); if (cnode->size() != kInputSizeThree) { return false; } for (size_t i = 1; i < cnode->size(); ++i) { indices[i - 1] = false; if (CheckPrimitiveType(cnode->input(i), prim::kPrimTranspose)) { std::vector<int> perm; auto trans_cnode = cnode->input(i)->cast<CNodePtr>(); MS_CHECK_TRUE_RET(trans_cnode != nullptr, false); if (GetTransposePerm(trans_cnode, &perm) != lite::RET_OK) { MS_LOG(ERROR) << "get transpose perm failed."; return false; } if (perm == kMatMulTransPerm1 || perm == kMatMulTransPerm2 || perm == kMatMulTransPerm3) { indices[i - 1] = true; } } } if (!indices[FIRST_INPUT] && !indices[SECOND_INPUT]) { return false; } return true; } } // namespace bool TransposeMatMulFusion::Run(const FuncGraphPtr &func_graph) { MS_ASSERT(func_graph != nullptr); auto node_list = TopoSort(func_graph->get_return()); for (auto &node : node_list) { MS_CHECK_TRUE_RET(node != nullptr, false); if (!utils::isa<CNode>(node)) { continue; } auto cnode = node->cast<CNodePtr>(); if (!CheckPrimitiveType(node, prim::kPrimMatMul)) { continue; } if (IsMarkedTrainOp(cnode)) { return false; } bool indices_need_fuse[DIMENSION_2D] = {false, false}; if (!CheckInputTransposeNode(cnode, indices_need_fuse, sizeof(bool) * DIMENSION_2D)) { continue; } auto matmul_prim = GetValueNode<std::shared_ptr<mindspore::ops::MatMul>>(cnode->input(0)); MS_ASSERT(matmul_prim != nullptr); auto manager = func_graph->manager(); MS_ASSERT(manager != nullptr); if (indices_need_fuse[FIRST_INPUT]) { if (matmul_prim->GetAttr(ops::kTransposeA) == nullptr) { matmul_prim->set_transpose_a(true); } else { auto org_transpose_a = matmul_prim->get_transpose_a(); matmul_prim->set_transpose_a(!org_transpose_a); } auto left_trans_cnode = cnode->input(SECOND_INPUT)->cast<CNodePtr>(); MS_CHECK_TRUE_RET(left_trans_cnode != nullptr, false); MS_CHECK_TRUE_RET(left_trans_cnode->size() == kInputSizeThree, false); auto left_pre_cnode = left_trans_cnode->input(SECOND_INPUT); (void)manager->Replace(left_trans_cnode, left_pre_cnode); } if (indices_need_fuse[SECOND_INPUT]) { if (matmul_prim->GetAttr(ops::kTransposeB) == nullptr) { matmul_prim->set_transpose_b(true); } else { auto org_transpose_b = matmul_prim->get_transpose_b(); matmul_prim->set_transpose_b(!org_transpose_b); } auto right_trans_cnode = cnode->input(THIRD_INPUT)->cast<CNodePtr>(); MS_CHECK_TRUE_RET(right_trans_cnode != nullptr, false); MS_CHECK_TRUE_RET(right_trans_cnode->size() == kInputSizeThree, false); auto right_pre_cnode = right_trans_cnode->input(SECOND_INPUT); (void)manager->Replace(right_trans_cnode, right_pre_cnode); } } return false; } } // namespace opt } // namespace mindspore
36.709402
96
0.685914
[ "vector" ]
3702066e6786ccfa745abc13e1996655f92b519f
5,325
hpp
C++
framework/common/tcuPlatform.hpp
akihikodaki/VK-GL-CTS
2d1377ec02b5b46a1cd946c5a27fa4a8f9e1e1f5
[ "Apache-2.0" ]
null
null
null
framework/common/tcuPlatform.hpp
akihikodaki/VK-GL-CTS
2d1377ec02b5b46a1cd946c5a27fa4a8f9e1e1f5
[ "Apache-2.0" ]
null
null
null
framework/common/tcuPlatform.hpp
akihikodaki/VK-GL-CTS
2d1377ec02b5b46a1cd946c5a27fa4a8f9e1e1f5
[ "Apache-2.0" ]
null
null
null
#ifndef _TCUPLATFORM_HPP #define _TCUPLATFORM_HPP /*------------------------------------------------------------------------- * drawElements Quality Program Tester Core * ---------------------------------------- * * Copyright 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief Platform (OS) specific services. *//*--------------------------------------------------------------------*/ #include "tcuDefs.hpp" namespace glu { class Platform; } namespace eglu { class Platform; } namespace vk { class Platform; } namespace tcu { class CommandLine; class FunctionLibrary; struct PlatformMemoryLimits { // System memory properties size_t totalSystemMemory; // #bytes of system memory (heap + HOST_LOCAL) tests must not exceed // Device memory properties std::uint64_t totalDeviceLocalMemory; // #bytes of total DEVICE_LOCAL memory tests must not exceed or 0 if DEVICE_LOCAL counts against system memory std::uint64_t deviceMemoryAllocationGranularity; // VkDeviceMemory allocation granularity (typically page size) // Device memory page table geometry std::uint64_t devicePageSize; // Page size on device (must be rounded up to the nearest POT) std::uint64_t devicePageTableEntrySize; // Number of bytes per page table size size_t devicePageTableHierarchyLevels; // Number of levels in device page table hierarchy PlatformMemoryLimits (void) : totalSystemMemory (0) , totalDeviceLocalMemory (0) , deviceMemoryAllocationGranularity (0) , devicePageSize (0) , devicePageTableEntrySize (0) , devicePageTableHierarchyLevels (0) {} }; /*--------------------------------------------------------------------*//*! * \brief Base class for platform implementation. * * This class represents the minimum set of functionality for a platform * port. * * In addition to implementing Platform class, main entry point must be * created that takes care of parsing command line, creating log and * executing tcu::App. See tcuMain.cpp for reference on implementing * application stub. * * If the platform uses standard posix-style main() for application entry * point, tcuMain.cpp can be used as is. In that case you only have to * implement createPlatform(). * * API-specific platform interfaces (glu::Platform, eglu::Platform and vk::Platform) * can be provided by implementing get<API>Platform() functions. *//*--------------------------------------------------------------------*/ class Platform { public: Platform (void); virtual ~Platform (void); /*--------------------------------------------------------------------*//*! * \brief Process platform-specific events. * * Test framework will call this function between test cases and test case * iterations. Any event handling that must be done periodically should be * done here. * * Test framework will decide whether to continue test execution based on * return code. For instance if the application receives close event from OS, * it should communicate that to framework by returning false. * * \note Do not do rendering buffer swaps here. * Do it in RenderContext::postIterate() instead. * \return true if test execution should continue, false otherwise. *//*--------------------------------------------------------------------*/ virtual bool processEvents (void); /*--------------------------------------------------------------------*//*! * \brief Get GL platform interface * * GL-specific platform interface is defined by glu::Platform. If your * platform port supports OpenGL (ES), you should implement this function. * * Default implementation throws tcu::NotSupportedError exception. * * \return Reference to GL platform interface. *//*--------------------------------------------------------------------*/ virtual const glu::Platform& getGLPlatform (void) const; /*--------------------------------------------------------------------*//*! * \brief Get EGL platform interface * * EGL-specific platform interface is defined by eglu::Platform. If your * platform port supports EGL, you should implement this function. * * Default implementation throws tcu::NotSupportedError exception. * * \return Reference to EGL platform interface. *//*--------------------------------------------------------------------*/ virtual const eglu::Platform& getEGLPlatform (void) const; virtual const vk::Platform& getVulkanPlatform (void) const; virtual void getMemoryLimits (PlatformMemoryLimits& limits) const; }; inline tcu::PlatformMemoryLimits getMemoryLimits (const tcu::Platform& platform) { tcu::PlatformMemoryLimits limits; platform.getMemoryLimits(limits); return limits; } } // tcu #endif // _TCUPLATFORM_HPP
34.803922
152
0.633052
[ "geometry" ]
3702f075e08ae3048152a6f8a76187b04ecefa3a
1,942
hpp
C++
libs/hana/include/boost/hana/fwd/difference.hpp
Manu343726/boost-cmake
009c3843b49a56880d988ffdca6d909f881edb3d
[ "BSL-1.0" ]
61
2017-07-03T18:36:45.000Z
2021-09-14T14:57:19.000Z
libs/hana/include/boost/hana/fwd/difference.hpp
Manu343726/boost-cmake
009c3843b49a56880d988ffdca6d909f881edb3d
[ "BSL-1.0" ]
14
2017-07-22T14:05:34.000Z
2018-11-06T20:01:30.000Z
libs/hana/include/boost/hana/fwd/difference.hpp
Manu343726/boost-cmake
009c3843b49a56880d988ffdca6d909f881edb3d
[ "BSL-1.0" ]
31
2017-07-04T14:15:34.000Z
2021-09-12T04:50:41.000Z
/*! @file Forward declares `boost::hana::difference`. @copyright Louis Dionne 2013-2017 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_HANA_FWD_DIFFERENCE_HPP #define BOOST_HANA_FWD_DIFFERENCE_HPP #include <boost/hana/config.hpp> #include <boost/hana/core/when.hpp> BOOST_HANA_NAMESPACE_BEGIN //! Returns the set-theoretic difference of two sets. //! @relates hana::set //! //! Given two sets `xs` and `ys`, `difference(xs, ys)` is a new set //! containing all the elements of `xs` that are _not_ contained in `ys`. //! For any object `x`, the following holds: //! @code //! x ^in^ difference(xs, ys) if and only if x ^in^ xs && !(x ^in^ ys) //! @endcode //! //! //! @note //! This operation is not commutative, i.e. `difference(xs, ys)` is not //! necessarily the same as `difference(ys, xs)`. Indeed, consider the //! case where `xs` is empty and `ys` isn't. Then, `difference(xs, ys)` //! is empty but `difference(ys, xs)` is equal to `ys`. For the symmetric //! version of this operation, see `symmetric_difference`. //! //! //! @param xs //! A set to remove values from. //! //! @param ys //! The set whose values are removed from `xs`. //! //! //! Example //! ------- //! @include example/difference.cpp #ifdef BOOST_HANA_DOXYGEN_INVOKED constexpr auto difference = [](auto&& xs, auto&& ys) { return tag-dispatched; }; #else template <typename S, typename = void> struct difference_impl : difference_impl<S, when<true>> { }; struct difference_t { template <typename Xs, typename Ys> constexpr auto operator()(Xs&& xs, Ys&& ys) const; }; constexpr difference_t difference{}; #endif BOOST_HANA_NAMESPACE_END #endif // !BOOST_HANA_FWD_DIFFERENCE_HPP
29.876923
78
0.637487
[ "object" ]
37098f87c1d35d35657b5bab6721441385158ad6
9,163
cpp
C++
src/cborcpp/cbor_object.cpp
rockercheng/uvm
48f01ae86ba78a487d22662da12b7460609db50e
[ "MIT" ]
2
2018-01-08T13:22:02.000Z
2020-05-03T07:21:39.000Z
src/cborcpp/cbor_object.cpp
rockercheng/uvm
48f01ae86ba78a487d22662da12b7460609db50e
[ "MIT" ]
null
null
null
src/cborcpp/cbor_object.cpp
rockercheng/uvm
48f01ae86ba78a487d22662da12b7460609db50e
[ "MIT" ]
3
2018-03-26T06:50:35.000Z
2019-10-22T07:08:13.000Z
#include "cborcpp/cbor_object.h" #include <fc/crypto/hex.hpp> #include <string> #include <sstream> namespace cbor { CborObject::CborObject() : type(COT_NULL), array_or_map_size(0), is_positive_extra(false){ value.bool_val = 0; } CborObject::CborObject(const CborObject& other) : type(other.type), value(other.value), array_or_map_size(other.array_or_map_size), is_positive_extra(other.is_positive_extra) { } CborIntValue CborObject::force_as_int() const { if (is_int()) { return as_int(); } else if (is_extra_int()) { auto extra_int_val = static_cast<CborIntValue>(as_extra_int()); auto is_pos = this->is_positive_extra; if (is_pos) { return extra_int_val; } else { if (extra_int_val >= 0) { return -extra_int_val; } else { return extra_int_val; } } } else { FC_THROW_EXCEPTION(fc::assert_exception, "this cbor_object with can't be passed as int"); } } fc::variant CborObject::to_json() const { switch (type) { case COT_NULL: return fc::variant(); case COT_UNDEFINED: return fc::variant(); case COT_BOOL: return as_bool() ? true : false; case COT_INT: return as_int(); case COT_EXTRA_INT: { auto extra_int_val = as_extra_int(); auto is_pos = this->is_positive_extra; if (is_pos) return extra_int_val; else { int64_t result_val = static_cast<int64_t>(extra_int_val); result_val = -result_val; return result_val; } } case COT_FLOAT: return as_float64(); case COT_TAG: return as_tag(); case COT_STRING: return as_string(); case COT_BYTES: { const auto& bytes = as_bytes(); const auto& hex = fc::to_hex(bytes); return hex; } case COT_ARRAY: { fc::variants arr; const auto& items = as_array(); for (size_t i = 0; i < items.size(); i++) { arr.push_back(items[i]->to_json()); } return arr; } break; case COT_MAP: { fc::mutable_variant_object obj; const auto& items = as_map(); for (auto it = items.begin(); it != items.end(); it++) { obj[it->first] = it->second->to_json(); } return obj; } default: throw cbor::CborException(std::string("not supported cbor object type ") + std::to_string(type)); } } std::string CborObject::str() const { switch (type) { case COT_NULL: return "null"; case COT_UNDEFINED: return "undefined"; case COT_BOOL: return as_bool() ? "true" : "false"; case COT_INT: return std::to_string(as_int()); case COT_EXTRA_INT: { auto extra_int_val = as_extra_int(); auto is_pos = this->is_positive_extra; if (is_pos) return std::to_string(extra_int_val); else return std::string("-") + std::to_string(extra_int_val); } case COT_FLOAT: return std::to_string(as_float64()); case COT_TAG: return std::string("tag<") + std::to_string(as_tag()) + ">"; case COT_STRING: return as_string(); case COT_BYTES: { const auto& bytes = as_bytes(); const auto& hex = fc::to_hex(bytes); return std::string("bytes<") + hex + ">"; } case COT_ARRAY: { const auto& items = as_array(); std::stringstream ss; ss << "["; for (size_t i = 0; i < items.size(); i++) { if (i > 0) { ss << ", "; } ss << items[i]->str(); } ss << "]"; return ss.str(); } break; case COT_MAP: { const auto& items = as_map(); std::stringstream ss; ss << "{"; auto begin = items.begin(); for (auto it = items.begin(); it != items.end();it++) { if (it != begin) { ss << ", "; } ss << it->first << ": " << it->second->str(); } ss << "}"; return ss.str(); } default: throw cbor::CborException(std::string("not supported cbor object type ") + std::to_string(type)); } } /*CborObjectP CborObject::from(const CborObjectValue& value) { auto result = std::make_shared<CborObject>(); result->value = value; switch (value.which()) { case CborObjectValue::tag<CborBoolValue>::value: result->type = COT_BOOL; break; case CborObjectValue::tag<CborIntValue>::value: result->type = COT_INT; break; case CborObjectValue::tag<CborExtraIntValue>::value: result->type = COT_EXTRA_INT; break; case CborObjectValue::tag<CborDoubleValue>::value: result->type = COT_FLOAT; break; case CborObjectValue::tag<CborTagValue>::value: result->type = COT_TAG; break; case CborObjectValue::tag<CborStringValue>::value: result->type = COT_STRING; break; case CborObjectValue::tag<CborBytesValue>::value: result->type = COT_BYTES; break; case CborObjectValue::tag<CborArrayValue>::value: result->type = COT_ARRAY; break; case CborObjectValue::tag<CborMapValue>::value: result->type = COT_MAP; break; default: throw cbor::CborException(std::string("not supported cbor object type ") + std::to_string(value.which())); } return result; }*/ CborObjectP CborObject::from_int(CborIntValue value) { auto result = std::make_shared<CborObject>(); result->type = COT_INT; #if defined(CBOR_OBJECT_USE_VARIANT) result->value = value; #else result->value.int_val = value; #endif return result; } CborObjectP CborObject::from_bool(CborBoolValue value) { auto result = std::make_shared<CborObject>(); result->type = COT_BOOL; #if defined(CBOR_OBJECT_USE_VARIANT) result->value = value; #else result->value.bool_val = value; #endif return result; } CborObjectP CborObject::from_bytes(const CborBytesValue& value) { auto result = std::make_shared<CborObject>(); result->type = COT_BYTES; #if defined(CBOR_OBJECT_USE_VARIANT) result->value = value; #else result->value.bytes_val = value; #endif return result; } CborObjectP CborObject::from_float64(const CborDoubleValue& value) { auto result = std::make_shared<CborObject>(); result->type = COT_FLOAT; #if defined(CBOR_OBJECT_USE_VARIANT) result->value = value; #else result->value.float64_val = value; #endif return result; } CborObjectP CborObject::from_string(const std::string& value) { auto result = std::make_shared<CborObject>(); result->type = COT_STRING; #if defined(CBOR_OBJECT_USE_VARIANT) result->value = value; #else result->value.string_val = value; #endif return result; } CborObjectP CborObject::create_array(size_t size) { auto result = std::make_shared<CborObject>(); result->type = COT_ARRAY; #if defined(CBOR_OBJECT_USE_VARIANT) result->value = CborArrayValue(); #else result->value.array_val = CborArrayValue(); #endif result->array_or_map_size = size; return result; } CborObjectP CborObject::create_array(const CborArrayValue& items) { auto result = std::make_shared<CborObject>(); result->type = COT_ARRAY; #if defined(CBOR_OBJECT_USE_VARIANT) result->value = CborArrayValue(items); #else result->value.array_val = CborArrayValue(items); #endif result->array_or_map_size = items.size(); return result; } CborObjectP CborObject::create_map(size_t size) { auto result = std::make_shared<CborObject>(); result->type = COT_MAP; #if defined(CBOR_OBJECT_USE_VARIANT) result->value = CborMapValue(); #else result->value.map_val = CborMapValue(); #endif result->array_or_map_size = size; return result; } CborObjectP CborObject::create_map(const CborMapValue& items) { auto result = std::make_shared<CborObject>(); result->type = COT_MAP; #if defined(CBOR_OBJECT_USE_VARIANT) result->value = CborMapValue(items); #else result->value.map_val = CborMapValue(items); #endif result->array_or_map_size = items.size(); return result; } CborObjectP CborObject::from_tag(CborTagValue value) { auto result = std::make_shared<CborObject>(); result->type = COT_TAG; #if defined(CBOR_OBJECT_USE_VARIANT) result->value = value; #else result->value.tag_or_special_val = value; #endif return result; } CborObjectP CborObject::create_undefined() { auto result = std::make_shared<CborObject>(); result->type = COT_UNDEFINED; #if !CBOR_OBJECT_USE_VARIANT result->value.bool_val = 0; #endif return result; } CborObjectP CborObject::create_null() { auto result = std::make_shared<CborObject>(); result->type = COT_NULL; #if !CBOR_OBJECT_USE_VARIANT result->value.bool_val = 0; #endif return result; } /*CborObjectP CborObject::from_special(uint32_t value) { auto result = std::make_shared<CborObject>(); result->type = COT_SPECIAL; result->value = value; return result; }*/ CborObjectP CborObject::from_extra_integer(uint64_t value, bool sign) { auto result = std::make_shared<CborObject>(); result->type = COT_EXTRA_INT; #if defined(CBOR_OBJECT_USE_VARIANT) result->value = value; #else result->value.extra_int_val = value; #endif result->is_positive_extra = sign; return result; } CborObjectP CborObject::from_extra_tag(uint64_t value) { auto result = std::make_shared<CborObject>(); result->type = COT_EXTRA_TAG; #if defined(CBOR_OBJECT_USE_VARIANT) result->value = value; #else result->value.extra_int_val = value; #endif return result; } /*CborObjectP CborObject::from_extra_special(uint64_t value) { auto result = std::make_shared<CborObject>(); result->type = COT_EXTRA_SPECIAL; result->value = value; return result; }*/ }
26.482659
129
0.686347
[ "object" ]
37114c732c9af7801be7ed44cb776b165b5341d6
3,131
hpp
C++
tests/math_prob/neg_binomial_2/neg_binomial_2_log_test.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
1
2019-09-06T15:53:17.000Z
2019-09-06T15:53:17.000Z
tests/math_prob/neg_binomial_2/neg_binomial_2_log_test.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
8
2019-01-17T18:51:16.000Z
2019-01-17T18:51:39.000Z
tests/math_prob/neg_binomial_2/neg_binomial_2_log_test.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
null
null
null
// Arguments: Ints, Doubles, Doubles #include <stan/math/prim/scal.hpp> using stan::math::var; using std::numeric_limits; using std::vector; class AgradDistributionsNegBinomial2Log : public AgradDistributionTest { public: void valid_values(vector<vector<double> >& parameters, vector<double>& log_prob) { vector<double> param(3); param[0] = 10; // n param[1] = 2.0; // eta param[2] = 1.5; // phi parameters.push_back(param); log_prob.push_back( -3.20887218205076511331179862116263121414716429208289234888793); // expected // log_prob param[0] = 100; // n param[1] = -3.0; // eta param[2] = 3.5; // phi parameters.push_back(param); log_prob.push_back( -416.382927743850187661846671194765967569806334854259547205045); // expected // log_prob param[0] = 100; // n param[1] = -10; // eta param[2] = 200; // phi parameters.push_back(param); log_prob.push_back( -1342.30278266569972162264049303129841494915365562553058756128); // expected // log_prob } void invalid_values(vector<size_t>& index, vector<double>& value) { // n index.push_back(0U); value.push_back(-1); // phi index.push_back(2U); value.push_back(-1); } template <class T_n, class T_log_location, class T_inv_scale, typename T3, typename T4, typename T5> typename stan::return_type<T_log_location, T_inv_scale>::type log_prob( const T_n& n, const T_log_location& eta, const T_inv_scale& phi, const T3&, const T4&, const T5&) { return stan::math::neg_binomial_2_log_log(n, eta, phi); } template <bool propto, class T_n, class T_log_location, class T_inv_scale, typename T3, typename T4, typename T5> typename stan::return_type<T_log_location, T_inv_scale>::type log_prob( const T_n& n, const T_log_location& eta, const T_inv_scale& phi, const T3&, const T4&, const T5&) { return stan::math::neg_binomial_2_log_log<propto>(n, eta, phi); } template <class T_n, class T_log_location, class T_inv_scale, typename T3, typename T4, typename T5> typename stan::return_type<T_log_location, T_inv_scale>::type log_prob_function(const T_n& n, const T_log_location& eta, const T_inv_scale& phi, const T3&, const T4&, const T5&) { using stan::math::binomial_coefficient_log; using stan::math::log_sum_exp; using stan::math::multiply_log; using std::log; if (n != 0) return binomial_coefficient_log< typename stan::scalar_type<T_inv_scale>::type>(n + phi - 1.0, n) + n * eta + multiply_log(phi, phi) - (n + phi) * log_sum_exp(eta, log(phi)); else return 0; } };
36.835294
86
0.575854
[ "vector" ]
37138db442a28fb54802a395e101911ad501b5d0
23,225
cc
C++
cvmfs/cache_plugin/cvmfs_cache_ram.cc
egede/cvmfs
168cdbeeec9dabd1898d4ab7964cb3b9f63cfcd7
[ "BSD-3-Clause" ]
null
null
null
cvmfs/cache_plugin/cvmfs_cache_ram.cc
egede/cvmfs
168cdbeeec9dabd1898d4ab7964cb3b9f63cfcd7
[ "BSD-3-Clause" ]
null
null
null
cvmfs/cache_plugin/cvmfs_cache_ram.cc
egede/cvmfs
168cdbeeec9dabd1898d4ab7964cb3b9f63cfcd7
[ "BSD-3-Clause" ]
null
null
null
/** * This file is part of the CernVM File System. * * A cache plugin that stores all data in a fixed-size memory chunk. */ #define __STDC_FORMAT_MACROS #include <alloca.h> #include <fcntl.h> #include <inttypes.h> #include <stdint.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <algorithm> #include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #include <string> #include <vector> #include "cache_plugin/libcvmfs_cache.h" #include "logging.h" #include "lru.h" #include "malloc_heap.h" #include "murmur.h" #include "platform.h" #include "smallhash.h" #include "smalloc.h" #include "util/string.h" #include "util_concurrency.h" using namespace std; // NOLINT /** * Header of the data pieces in the cache. After the object header, the * zero-terminated description and the object data follows. */ struct ObjectHeader { ObjectHeader() { txn_id = uint64_t(-1); size_data = 0; size_desc = 0; refcnt = 0; type = CVMCACHE_OBJECT_REGULAR; memset(&id, 0, sizeof(id)); } char *GetDescription() { if (size_desc == 0) return NULL; return reinterpret_cast<char *>(this) + sizeof(ObjectHeader); } void SetDescription(char *description) { if (description == NULL) return; memcpy(reinterpret_cast<char *>(this) + sizeof(ObjectHeader), description, strlen(description) + 1); } unsigned char *GetData() { return reinterpret_cast<unsigned char *>(this) + sizeof(ObjectHeader) + size_desc; } /** * Set during a running transaction so that we know where to look for pointers * when the memory block gets compacted. Once committed, this is * uint64_t(-1). */ uint64_t txn_id; /** * Can be zero. */ uint32_t size_data; /** * String length + 1 (null terminated) or null if the description is NULL. */ uint32_t size_desc; /** * During a transaction, neg_nbytes_written is used to track the number of * already written bytes. On commit, refcnt is set to 1. */ union { int32_t refcnt; int32_t neg_nbytes_written; }; cvmcache_object_type type; struct cvmcache_hash id; }; /** * Listings are generated and cached during the entire life time of a listing * id. Not very memory efficient but we don't optimize for listings. */ struct Listing { Listing() : pos(0) { } uint64_t pos; vector<struct cvmcache_object_info> elems; }; /** * Allows us to use a cvmcache_hash in (hash) maps. */ struct ComparableHash { ComparableHash() { memset(&hash, 0, sizeof(hash)); } explicit ComparableHash(const struct cvmcache_hash &h) : hash(h) { } bool operator ==(const ComparableHash &other) const { return cvmcache_hash_cmp(const_cast<cvmcache_hash *>(&(this->hash)), const_cast<cvmcache_hash *>(&(other.hash))) == 0; } bool operator !=(const ComparableHash &other) const { return cvmcache_hash_cmp(const_cast<cvmcache_hash *>(&(this->hash)), const_cast<cvmcache_hash *>(&(other.hash))) != 0; } bool operator <(const ComparableHash &other) const { return cvmcache_hash_cmp(const_cast<cvmcache_hash *>(&(this->hash)), const_cast<cvmcache_hash *>(&(other.hash))) < 0; } bool operator >(const ComparableHash &other) const { return cvmcache_hash_cmp(const_cast<cvmcache_hash *>(&(this->hash)), const_cast<cvmcache_hash *>(&(other.hash))) > 0; } struct cvmcache_hash hash; }; namespace { static inline uint32_t hasher_uint64(const uint64_t &key) { return MurmurHash2(&key, sizeof(key), 0x07387a4f); } static inline uint32_t hasher_any(const ComparableHash &key) { return (uint32_t) *(reinterpret_cast<const uint32_t *>(&key.hash)); } } // anonymous namespace /** * Used in the PluginRamCache when detaching nested catalogs. */ struct cvmcache_context *ctx; /** * Implements all the cache plugin callbacks. Singelton. */ class PluginRamCache : public Callbackable<MallocHeap::BlockPtr> { public: static PluginRamCache *Create(const string &mem_size_str) { assert(instance_ == NULL); uint64_t mem_size_bytes; if (HasSuffix(mem_size_str, "%", false)) { mem_size_bytes = platform_memsize() * String2Uint64(mem_size_str) / 100; } else { mem_size_bytes = String2Uint64(mem_size_str) * 1024 * 1024; } instance_ = new PluginRamCache(mem_size_bytes); return instance_; } ~PluginRamCache() { delete storage_; delete objects_all_; delete objects_volatile_; instance_ = NULL; } static int ram_chrefcnt(struct cvmcache_hash *id, int32_t change_by) { ComparableHash h(*id); ObjectHeader *object; if (!Me()->objects_all_->Lookup(h, &object)) return CVMCACHE_STATUS_NOENTRY; if (object->type == CVMCACHE_OBJECT_VOLATILE) Me()->objects_volatile_->Update(h); if (change_by == 0) return CVMCACHE_STATUS_OK; if ((object->refcnt + change_by) < 0) return CVMCACHE_STATUS_BADCOUNT; if (object->refcnt == 0) { Me()->cache_info_.pinned_bytes += Me()->storage_->GetSize(object); Me()->CheckHighPinWatermark(); } object->refcnt += change_by; if (object->refcnt == 0) { Me()->cache_info_.pinned_bytes -= Me()->storage_->GetSize(object); Me()->in_danger_zone_ = Me()->IsInDangerZone(); } return CVMCACHE_STATUS_OK; } static int ram_obj_info( struct cvmcache_hash *id, struct cvmcache_object_info *info) { ComparableHash h(*id); ObjectHeader *object; if (!Me()->objects_all_->Lookup(h, &object, false)) return CVMCACHE_STATUS_NOENTRY; info->size = object->size_data; info->type = object->type; info->pinned = object->refcnt > 0; info->description = (object->GetDescription() == NULL) ? NULL : strdup(object->GetDescription()); return CVMCACHE_STATUS_OK; } static int ram_pread(struct cvmcache_hash *id, uint64_t offset, uint32_t *size, unsigned char *buffer) { ComparableHash h(*id); ObjectHeader *object; bool retval = Me()->objects_all_->Lookup(h, &object, false); assert(retval); if (offset > object->size_data) return CVMCACHE_STATUS_OUTOFBOUNDS; unsigned nbytes = std::min(*size, static_cast<uint32_t>(object->size_data - offset)); memcpy(buffer, object->GetData() + offset, nbytes); *size = nbytes; return CVMCACHE_STATUS_OK; } static int ram_start_txn( struct cvmcache_hash *id, uint64_t txn_id, struct cvmcache_object_info *info) { ObjectHeader object_header; object_header.txn_id = txn_id; if (info->size != CVMCACHE_SIZE_UNKNOWN) object_header.size_data = info->size; else object_header.size_data = 4096; if (info->description != NULL) object_header.size_desc = strlen(info->description) + 1; object_header.refcnt = 1; object_header.type = info->type; object_header.id = *id; uint32_t total_size = sizeof(object_header) + object_header.size_desc + object_header.size_data; Me()->TryFreeSpace(total_size); ObjectHeader *allocd_object = reinterpret_cast<ObjectHeader *>( Me()->storage_->Allocate(total_size, &object_header, sizeof(object_header))); if (allocd_object == NULL) return CVMCACHE_STATUS_NOSPACE; allocd_object->SetDescription(info->description); Me()->transactions_.Insert(txn_id, allocd_object); return CVMCACHE_STATUS_OK; } static int ram_write_txn( uint64_t txn_id, unsigned char *buffer, uint32_t size) { ObjectHeader *txn_object; int retval = Me()->transactions_.Lookup(txn_id, &txn_object); assert(retval); assert(size > 0); if (txn_object->neg_nbytes_written > 0) txn_object->neg_nbytes_written = 0; if ((size - txn_object->neg_nbytes_written) > txn_object->size_data) { uint32_t current_size = Me()->storage_->GetSize(txn_object); uint32_t header_size = current_size - txn_object->size_data; uint32_t new_size = std::max( header_size + size - txn_object->neg_nbytes_written, uint32_t(current_size * kObjectExpandFactor)); bool did_compact = Me()->TryFreeSpace(new_size); if (did_compact) { retval = Me()->transactions_.Lookup(txn_id, &txn_object); assert(retval); } txn_object = reinterpret_cast<ObjectHeader *>( Me()->storage_->Expand(txn_object, new_size)); if (txn_object == NULL) return CVMCACHE_STATUS_NOSPACE; txn_object->size_data = new_size - header_size; Me()->transactions_.Insert(txn_id, txn_object); } memcpy(txn_object->GetData() - txn_object->neg_nbytes_written, buffer, size); txn_object->neg_nbytes_written -= size; return CVMCACHE_STATUS_OK; } static int ram_commit_txn(uint64_t txn_id) { Me()->TryFreeSpace(0); if (Me()->objects_all_->IsFull()) return CVMCACHE_STATUS_NOSPACE; ObjectHeader *txn_object; int retval = Me()->transactions_.Lookup(txn_id, &txn_object); assert(retval); Me()->transactions_.Erase(txn_id); ComparableHash h(txn_object->id); ObjectHeader *existing_object; if (Me()->objects_all_->Lookup(h, &existing_object)) { // Concurrent addition of same objects, drop the one at hand and // increase ref count of existing copy Me()->storage_->MarkFree(txn_object); if (existing_object->refcnt == 0) Me()->cache_info_.pinned_bytes += Me()->storage_->GetSize(existing_object); existing_object->refcnt++; } else { txn_object->txn_id = uint64_t(-1); if (txn_object->neg_nbytes_written > 0) txn_object->neg_nbytes_written = 0; txn_object->size_data = -(txn_object->neg_nbytes_written); txn_object->refcnt = 1; Me()->cache_info_.used_bytes += Me()->storage_->GetSize(txn_object); Me()->cache_info_.pinned_bytes += Me()->storage_->GetSize(txn_object); Me()->objects_all_->Insert(h, txn_object); if (txn_object->type == CVMCACHE_OBJECT_VOLATILE) { assert(!Me()->objects_volatile_->IsFull()); Me()->objects_volatile_->Insert(h, txn_object); } } Me()->CheckHighPinWatermark(); return CVMCACHE_STATUS_OK; } static int ram_abort_txn(uint64_t txn_id) { ObjectHeader *txn_object = NULL; int retval = Me()->transactions_.Lookup(txn_id, &txn_object); assert(retval); Me()->transactions_.Erase(txn_id); Me()->storage_->MarkFree(txn_object); return CVMCACHE_STATUS_OK; } static int ram_info(struct cvmcache_info *info) { *info = Me()->cache_info_; return CVMCACHE_STATUS_OK; } static int ram_shrink(uint64_t shrink_to, uint64_t *used) { *used = Me()->cache_info_.used_bytes; if (*used <= shrink_to) return CVMCACHE_STATUS_OK; Me()->DoShrink(shrink_to); *used = Me()->cache_info_.used_bytes; return (*used <= shrink_to) ? CVMCACHE_STATUS_OK : CVMCACHE_STATUS_PARTIAL; } static int ram_listing_begin( uint64_t lst_id, enum cvmcache_object_type type) { Listing *lst = new Listing(); Me()->objects_all_->FilterBegin(); while (Me()->objects_all_->FilterNext()) { ComparableHash h; ObjectHeader *object; Me()->objects_all_->FilterGet(&h, &object); if (object->type != type) continue; struct cvmcache_object_info item; item.id = object->id; item.size = object->size_data; item.type = type; item.pinned = object->refcnt != 0; item.description = (object->size_desc > 0) ? strdup(object->GetDescription()) : NULL; lst->elems.push_back(item); } Me()->objects_all_->FilterEnd(); Me()->listings_.Insert(lst_id, lst); return CVMCACHE_STATUS_OK; } static int ram_listing_next( int64_t listing_id, struct cvmcache_object_info *item) { Listing *lst; bool retval = Me()->listings_.Lookup(listing_id, &lst); assert(retval); if (lst->pos >= lst->elems.size()) return CVMCACHE_STATUS_OUTOFBOUNDS; *item = lst->elems[lst->pos]; lst->pos++; return CVMCACHE_STATUS_OK; } static int ram_listing_end(int64_t listing_id) { Listing *lst; bool retval = Me()->listings_.Lookup(listing_id, &lst); assert(retval); // Don't free description strings, done by the library delete lst; Me()->listings_.Erase(listing_id); return CVMCACHE_STATUS_OK; } static int ram_breadcrumb_store( const char *fqrn, const cvmcache_breadcrumb *breadcrumb) { Me()->breadcrumbs_[fqrn] = *breadcrumb; return CVMCACHE_STATUS_OK; } static int ram_breadcrumb_load( const char *fqrn, cvmcache_breadcrumb *breadcrumb) { map<std::string, cvmcache_breadcrumb>::const_iterator itr = Me()->breadcrumbs_.find(fqrn); if (itr == Me()->breadcrumbs_.end()) return CVMCACHE_STATUS_NOENTRY; *breadcrumb = itr->second; return CVMCACHE_STATUS_OK; } private: static const uint64_t kMinSize; // 100 * 1024 * 1024; static const double kShrinkFactor; // = 0.75; static const double kObjectExpandFactor; // = 1.5; static const double kSlotFraction; // = 0.04; static const double kDangerZoneThreshold; // = 0.7 static PluginRamCache *instance_; static PluginRamCache *Me() { return instance_; } explicit PluginRamCache(uint64_t mem_size) { in_danger_zone_ = false; uint64_t heap_size = RoundUp8( std::max(kMinSize, uint64_t(mem_size * (1.0 - kSlotFraction)))); memset(&cache_info_, 0, sizeof(cache_info_)); cache_info_.size_bytes = heap_size; storage_ = new MallocHeap( heap_size, this->MakeCallback(&PluginRamCache::OnBlockMove, this)); struct cvmcache_hash hash_empty; memset(&hash_empty, 0, sizeof(hash_empty)); transactions_.Init(64, uint64_t(-1), hasher_uint64); listings_.Init(8, uint64_t(-1), hasher_uint64); double slot_size = lru::LruCache<ComparableHash, ObjectHeader *>::GetEntrySize(); uint64_t num_slots = uint64_t((heap_size * kSlotFraction) / (2.0 * slot_size)); const unsigned mask_64 = ~((1 << 6) - 1); LogCvmfs(kLogCache, kLogDebug | kLogSyslog, "Allocating %" PRIu64 "MB of memory for up to %" PRIu64 " objects", heap_size / (1024 * 1024), num_slots & mask_64); // Number of cache entries must be a multiple of 64 objects_all_ = new lru::LruCache<ComparableHash, ObjectHeader *>( num_slots & mask_64, ComparableHash(hash_empty), hasher_any, perf::StatisticsTemplate("objects_all", &statistics_)); objects_volatile_ = new lru::LruCache<ComparableHash, ObjectHeader *>( num_slots & mask_64, ComparableHash(hash_empty), hasher_any, perf::StatisticsTemplate("objects_volatile", &statistics_)); } /** * Returns true if memory compaction took place and pointers might have been * invalidated. */ bool TryFreeSpace(uint64_t bytes_required) { if (!objects_all_->IsFull() && storage_->HasSpaceFor(bytes_required)) return false; // Free space occupied due to piecewise catalog storage if (!objects_all_->IsFull()) { LogCvmfs(kLogCache, kLogDebug, "compacting ram cache"); storage_->Compact(); if (storage_->HasSpaceFor(bytes_required)) return true; } uint64_t shrink_to = std::min( storage_->capacity() - (bytes_required + 8), uint64_t(storage_->capacity() * kShrinkFactor)); DoShrink(shrink_to); return true; } void OnBlockMove(const MallocHeap::BlockPtr &ptr) { assert(ptr.pointer); ObjectHeader *object = reinterpret_cast<ObjectHeader *>(ptr.pointer); ComparableHash h(object->id); if (object->txn_id == uint64_t(-1)) { bool retval = objects_all_->UpdateValue(h, object); assert(retval); if (object->type == CVMCACHE_OBJECT_VOLATILE) { retval = objects_volatile_->UpdateValue(h, object); assert(retval); } } else { uint64_t old_size = transactions_.size(); transactions_.Insert(object->txn_id, object); assert(old_size == transactions_.size()); } } void DoShrink(uint64_t shrink_to) { ComparableHash h; ObjectHeader *object; LogCvmfs(kLogCache, kLogDebug | kLogSyslog, "clean up cache until at most %lu KB is used", shrink_to / 1024); objects_volatile_->FilterBegin(); while (objects_volatile_->FilterNext()) { objects_volatile_->FilterGet(&h, &object); if (object->refcnt != 0) continue; cache_info_.used_bytes -= storage_->GetSize(object); storage_->MarkFree(object); objects_volatile_->FilterDelete(); objects_all_->Forget(h); if (storage_->compacted_bytes() <= shrink_to) break; } objects_volatile_->FilterEnd(); objects_all_->FilterBegin(); while ((storage_->compacted_bytes() > shrink_to) && objects_all_->FilterNext()) { objects_all_->FilterGet(&h, &object); if (object->refcnt != 0) continue; assert(object->type != CVMCACHE_OBJECT_VOLATILE); cache_info_.used_bytes -= storage_->GetSize(object); storage_->MarkFree(object); objects_all_->FilterDelete(); } objects_all_->FilterEnd(); storage_->Compact(); cache_info_.no_shrink++; } void CheckHighPinWatermark() { if (!Me()->in_danger_zone_ && Me()->IsInDangerZone()) { LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslog, "high watermark of pinned files"); Me()->in_danger_zone_ = true; cvmcache_ask_detach(ctx); } } bool IsInDangerZone() { return (static_cast<double>(cache_info_.pinned_bytes) / static_cast<double>(cache_info_.size_bytes)) > kDangerZoneThreshold; } struct cvmcache_info cache_info_; perf::Statistics statistics_; SmallHashDynamic<uint64_t, ObjectHeader *> transactions_; SmallHashDynamic<uint64_t, Listing *> listings_; lru::LruCache<ComparableHash, ObjectHeader *> *objects_all_; lru::LruCache<ComparableHash, ObjectHeader *> *objects_volatile_; map<std::string, cvmcache_breadcrumb> breadcrumbs_; MallocHeap *storage_; bool in_danger_zone_; }; // class PluginRamCache PluginRamCache *PluginRamCache::instance_ = NULL; const uint64_t PluginRamCache::kMinSize = 100 * 1024 * 1024; const double PluginRamCache::kShrinkFactor = 0.75; const double PluginRamCache::kObjectExpandFactor = 1.5; const double PluginRamCache::kSlotFraction = 0.04; const double PluginRamCache::kDangerZoneThreshold = 0.7; static void Usage(const char *progname) { LogCvmfs(kLogCache, kLogStdout, "%s <config file>", progname); } int main(int argc, char **argv) { if (argc < 2) { Usage(argv[0]); return 1; } SetLogDebugFile("/dev/null"); cvmcache_init_global(); cvmcache_option_map *options = cvmcache_options_init(); if (cvmcache_options_parse(options, argv[1]) != 0) { LogCvmfs(kLogCache, kLogStderr, "cannot parse options file %s", argv[1]); return 1; } char *debug_log = cvmcache_options_get(options, "CVMFS_CACHE_PLUGIN_DEBUGLOG"); if (debug_log != NULL) { SetLogDebugFile(debug_log); cvmcache_options_free(debug_log); } char *locator = cvmcache_options_get(options, "CVMFS_CACHE_PLUGIN_LOCATOR"); if (locator == NULL) { LogCvmfs(kLogCache, kLogStderr, "CVMFS_CACHE_PLUGIN_LOCATOR missing"); cvmcache_options_fini(options); return 1; } char *mem_size = cvmcache_options_get(options, "CVMFS_CACHE_PLUGIN_SIZE"); if (mem_size == NULL) { LogCvmfs(kLogCache, kLogStderr, "CVMFS_CACHE_PLUGIN_SIZE missing"); cvmcache_options_fini(options); return 1; } char *test_mode = cvmcache_options_get(options, "CVMFS_CACHE_PLUGIN_TEST"); if (!test_mode) cvmcache_spawn_watchdog(NULL); PluginRamCache *plugin = PluginRamCache::Create(mem_size); struct cvmcache_callbacks callbacks; memset(&callbacks, 0, sizeof(callbacks)); callbacks.cvmcache_chrefcnt = plugin->ram_chrefcnt; callbacks.cvmcache_obj_info = plugin->ram_obj_info; callbacks.cvmcache_pread = plugin->ram_pread; callbacks.cvmcache_start_txn = plugin->ram_start_txn; callbacks.cvmcache_write_txn = plugin->ram_write_txn; callbacks.cvmcache_commit_txn = plugin->ram_commit_txn; callbacks.cvmcache_abort_txn = plugin->ram_abort_txn; callbacks.cvmcache_info = plugin->ram_info; callbacks.cvmcache_shrink = plugin->ram_shrink; callbacks.cvmcache_listing_begin = plugin->ram_listing_begin; callbacks.cvmcache_listing_next = plugin->ram_listing_next; callbacks.cvmcache_listing_end = plugin->ram_listing_end; callbacks.cvmcache_breadcrumb_store = plugin->ram_breadcrumb_store; callbacks.cvmcache_breadcrumb_load = plugin->ram_breadcrumb_load; callbacks.capabilities = CVMCACHE_CAP_ALL_V2; ctx = cvmcache_init(&callbacks); int retval = cvmcache_listen(ctx, locator); if (!retval) { LogCvmfs(kLogCache, kLogStderr, "failed to listen on %s", locator); return 1; } if (test_mode) { // Daemonize, print out PID pid_t pid; int statloc; if ((pid = fork()) == 0) { if ((pid = fork()) == 0) { int null_read = open("/dev/null", O_RDONLY); int null_write = open("/dev/null", O_WRONLY); assert((null_read >= 0) && (null_write >= 0)); int retval = dup2(null_read, 0); assert(retval == 0); retval = dup2(null_write, 1); assert(retval == 1); retval = dup2(null_write, 2); assert(retval == 2); close(null_read); close(null_write); } else { assert(pid > 0); printf("%d\n", pid); fflush(stdout); fsync(1); _exit(0); } } else { assert(pid > 0); waitpid(pid, &statloc, 0); _exit(0); } } LogCvmfs(kLogCache, kLogStdout, "Listening for cvmfs clients on %s\n" "NOTE: this process needs to run as user cvmfs\n", locator); cvmcache_process_requests(ctx, 0); if (test_mode) while (true) sleep(1); if (!cvmcache_is_supervised()) { LogCvmfs(kLogCache, kLogStdout, "Press <Ctrl+D> to quit"); LogCvmfs(kLogCache, kLogStdout, "Press <R Enter> to ask clients to release nested catalogs"); while (true) { char buf; retval = read(fileno(stdin), &buf, 1); if (retval != 1) break; if (buf == 'R') { LogCvmfs(kLogCache, kLogStdout, " ... asking clients to release nested catalogs"); cvmcache_ask_detach(ctx); } } cvmcache_terminate(ctx); } else { LogCvmfs(kLogCache, kLogDebug | kLogSyslog, "CernVM-FS RAM cache plugin started in supervised mode"); } cvmcache_wait_for(ctx); LogCvmfs(kLogCache, kLogDebug | kLogStdout, " ... good bye"); cvmcache_options_free(mem_size); cvmcache_options_free(locator); cvmcache_options_fini(options); cvmcache_terminate_watchdog(); cvmcache_cleanup_global(); return 0; }
30.479003
80
0.662863
[ "object", "vector" ]
7deb17ac6748af91fddeac62ccb62cc0665403a5
21,219
cpp
C++
OgreMain/src/OgreRibbonTrail.cpp
marko213/ogre
d8669b749839947059c19c3110af5c4a7a975be2
[ "MIT" ]
1
2018-03-12T02:36:29.000Z
2018-03-12T02:36:29.000Z
OgreMain/src/OgreRibbonTrail.cpp
SweeneyChoi/ogre
e719ced4dbefb6a46888b4d1115a75f126948697
[ "MIT" ]
null
null
null
OgreMain/src/OgreRibbonTrail.cpp
SweeneyChoi/ogre
e719ced4dbefb6a46888b4d1115a75f126948697
[ "MIT" ]
null
null
null
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd 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 "OgreStableHeaders.h" #include "OgreRibbonTrail.h" #include "OgreController.h" namespace Ogre { namespace { /** Controller value for pass frame time to RibbonTrail */ class _OgrePrivate TimeControllerValue : public ControllerValue<Real> { protected: RibbonTrail* mTrail; public: TimeControllerValue(RibbonTrail* r) { mTrail = r; } Real getValue(void) const { return 0; }// not a source void setValue(Real value) { mTrail->_timeUpdate(value); } }; } //----------------------------------------------------------------------- //----------------------------------------------------------------------- RibbonTrail::RibbonTrail(const String& name, size_t maxElements, size_t numberOfChains, bool useTextureCoords, bool useColours) :BillboardChain(name, maxElements, 0, useTextureCoords, useColours, true), mFadeController(0) { setTrailLength(100); setNumberOfChains(numberOfChains); mTimeControllerValue = ControllerValueRealPtr(OGRE_NEW TimeControllerValue(this)); // use V as varying texture coord, so we can use 1D textures to 'smear' setTextureCoordDirection(TCD_V); } //----------------------------------------------------------------------- RibbonTrail::~RibbonTrail() { // Detach listeners for (NodeList::iterator i = mNodeList.begin(); i != mNodeList.end(); ++i) { (*i)->setListener(0); } if (mFadeController) { // destroy controller ControllerManager::getSingleton().destroyController(mFadeController); } } //----------------------------------------------------------------------- void RibbonTrail::addNode(Node* n) { if (mNodeList.size() == mChainCount) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, mName + " cannot monitor any more nodes, chain count exceeded", "RibbonTrail::addNode"); } if (n->getListener()) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, mName + " cannot monitor node " + n->getName() + " since it already has a listener.", "RibbonTrail::addNode"); } // get chain index size_t chainIndex = mFreeChains.back(); mFreeChains.pop_back(); mNodeToChainSegment.push_back(chainIndex); mNodeToSegMap[n] = chainIndex; // initialise the chain resetTrail(chainIndex, n); mNodeList.push_back(n); n->setListener(this); } //----------------------------------------------------------------------- size_t RibbonTrail::getChainIndexForNode(const Node* n) { NodeToChainSegmentMap::const_iterator i = mNodeToSegMap.find(n); if (i == mNodeToSegMap.end()) { OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "This node is not being tracked", "RibbonTrail::getChainIndexForNode"); } return i->second; } //----------------------------------------------------------------------- void RibbonTrail::removeNode(Node* n) { NodeList::iterator i = std::find(mNodeList.begin(), mNodeList.end(), n); if (i != mNodeList.end()) { // also get matching chain segment size_t index = std::distance(mNodeList.begin(), i); IndexVector::iterator mi = mNodeToChainSegment.begin(); std::advance(mi, index); size_t chainIndex = *mi; BillboardChain::clearChain(chainIndex); // mark as free now mFreeChains.push_back(chainIndex); n->setListener(0); mNodeList.erase(i); mNodeToChainSegment.erase(mi); mNodeToSegMap.erase(mNodeToSegMap.find(n)); } } //----------------------------------------------------------------------- RibbonTrail::NodeIterator RibbonTrail::getNodeIterator(void) const { return NodeIterator(mNodeList.begin(), mNodeList.end()); } //----------------------------------------------------------------------- void RibbonTrail::setTrailLength(Real len) { mTrailLength = len; mElemLength = mTrailLength / mMaxElementsPerChain; mSquaredElemLength = mElemLength * mElemLength; } //----------------------------------------------------------------------- void RibbonTrail::setMaxChainElements(size_t maxElements) { BillboardChain::setMaxChainElements(maxElements); mElemLength = mTrailLength / mMaxElementsPerChain; mSquaredElemLength = mElemLength * mElemLength; resetAllTrails(); } //----------------------------------------------------------------------- void RibbonTrail::setNumberOfChains(size_t numChains) { if (numChains < mNodeList.size()) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Can't shrink the number of chains less than number of tracking nodes", "RibbonTrail::setNumberOfChains"); } size_t oldChains = getNumberOfChains(); BillboardChain::setNumberOfChains(numChains); mInitialColour.resize(numChains, ColourValue::White); mDeltaColour.resize(numChains, ColourValue::ZERO); mInitialWidth.resize(numChains, 10); mDeltaWidth.resize(numChains, 0); if (oldChains > numChains) { // remove free chains for (IndexVector::iterator i = mFreeChains.begin(); i != mFreeChains.end();) { if (*i >= numChains) i = mFreeChains.erase(i); else ++i; } } else if (oldChains < numChains) { // add new chains, at front to preserve previous ordering (pop_back) for (size_t i = oldChains; i < numChains; ++i) mFreeChains.insert(mFreeChains.begin(), i); } resetAllTrails(); } //----------------------------------------------------------------------- void RibbonTrail::clearChain(size_t chainIndex) { BillboardChain::clearChain(chainIndex); // Reset if we are tracking for this chain IndexVector::iterator i = std::find(mNodeToChainSegment.begin(), mNodeToChainSegment.end(), chainIndex); if (i != mNodeToChainSegment.end()) { size_t nodeIndex = std::distance(mNodeToChainSegment.begin(), i); resetTrail(*i, mNodeList[nodeIndex]); } } //----------------------------------------------------------------------- void RibbonTrail::setInitialColour(size_t chainIndex, const ColourValue& col) { setInitialColour(chainIndex, col.r, col.g, col.b, col.a); } //----------------------------------------------------------------------- void RibbonTrail::setInitialColour(size_t chainIndex, Real r, Real g, Real b, Real a) { if (chainIndex >= mChainCount) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "chainIndex out of bounds", "RibbonTrail::setInitialColour"); } mInitialColour[chainIndex].r = r; mInitialColour[chainIndex].g = g; mInitialColour[chainIndex].b = b; mInitialColour[chainIndex].a = a; } //----------------------------------------------------------------------- const ColourValue& RibbonTrail::getInitialColour(size_t chainIndex) const { if (chainIndex >= mChainCount) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "chainIndex out of bounds", "RibbonTrail::getInitialColour"); } return mInitialColour[chainIndex]; } //----------------------------------------------------------------------- void RibbonTrail::setInitialWidth(size_t chainIndex, Real width) { if (chainIndex >= mChainCount) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "chainIndex out of bounds", "RibbonTrail::setInitialWidth"); } mInitialWidth[chainIndex] = width; } //----------------------------------------------------------------------- Real RibbonTrail::getInitialWidth(size_t chainIndex) const { if (chainIndex >= mChainCount) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "chainIndex out of bounds", "RibbonTrail::getInitialWidth"); } return mInitialWidth[chainIndex]; } //----------------------------------------------------------------------- void RibbonTrail::setColourChange(size_t chainIndex, const ColourValue& valuePerSecond) { setColourChange(chainIndex, valuePerSecond.r, valuePerSecond.g, valuePerSecond.b, valuePerSecond.a); } //----------------------------------------------------------------------- void RibbonTrail::setColourChange(size_t chainIndex, Real r, Real g, Real b, Real a) { if (chainIndex >= mChainCount) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "chainIndex out of bounds", "RibbonTrail::setColourChange"); } mDeltaColour[chainIndex].r = r; mDeltaColour[chainIndex].g = g; mDeltaColour[chainIndex].b = b; mDeltaColour[chainIndex].a = a; manageController(); } //----------------------------------------------------------------------- const ColourValue& RibbonTrail::getColourChange(size_t chainIndex) const { if (chainIndex >= mChainCount) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "chainIndex out of bounds", "RibbonTrail::getColourChange"); } return mDeltaColour[chainIndex]; } //----------------------------------------------------------------------- void RibbonTrail::setWidthChange(size_t chainIndex, Real widthDeltaPerSecond) { if (chainIndex >= mChainCount) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "chainIndex out of bounds", "RibbonTrail::setWidthChange"); } mDeltaWidth[chainIndex] = widthDeltaPerSecond; manageController(); } //----------------------------------------------------------------------- Real RibbonTrail::getWidthChange(size_t chainIndex) const { if (chainIndex >= mChainCount) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "chainIndex out of bounds", "RibbonTrail::getWidthChange"); } return mDeltaWidth[chainIndex]; } //----------------------------------------------------------------------- void RibbonTrail::manageController(void) { bool needController = false; for (size_t i = 0; i < mChainCount; ++i) { if (mDeltaWidth[i] != 0 || mDeltaColour[i] != ColourValue::ZERO) { needController = true; break; } } if (!mFadeController && needController) { // Set up fading via frame time controller ControllerManager& mgr = ControllerManager::getSingleton(); mFadeController = mgr.createFrameTimePassthroughController(mTimeControllerValue); } else if (mFadeController && !needController) { // destroy controller ControllerManager::getSingleton().destroyController(mFadeController); mFadeController = 0; } } //----------------------------------------------------------------------- void RibbonTrail::nodeUpdated(const Node* node) { size_t chainIndex = getChainIndexForNode(node); updateTrail(chainIndex, node); } //----------------------------------------------------------------------- void RibbonTrail::nodeDestroyed(const Node* node) { removeNode(const_cast<Node*>(node)); } //----------------------------------------------------------------------- void RibbonTrail::updateTrail(size_t index, const Node* node) { // Repeat this entire process if chain is stretched beyond its natural length bool done = false; while (!done) { // Node has changed somehow, we're only interested in the derived position ChainSegment& seg = mChainSegmentList[index]; Element& headElem = mChainElementList[seg.start + seg.head]; size_t nextElemIdx = seg.head + 1; // wrap if (nextElemIdx == mMaxElementsPerChain) nextElemIdx = 0; Element& nextElem = mChainElementList[seg.start + nextElemIdx]; // Vary the head elem, but bake new version if that exceeds element len Vector3 newPos = node->_getDerivedPosition(); if (mParentNode) { // Transform position to ourself space newPos = mParentNode->convertWorldToLocalPosition(newPos); } Vector3 diff = newPos - nextElem.position; Real sqlen = diff.squaredLength(); if (sqlen >= mSquaredElemLength) { // Move existing head to mElemLength Vector3 scaledDiff = diff * (mElemLength / Math::Sqrt(sqlen)); headElem.position = nextElem.position + scaledDiff; // Add a new element to be the new head Element newElem( newPos, mInitialWidth[index], 0.0f, mInitialColour[index], node->_getDerivedOrientation() ); addChainElement(index, newElem); // alter diff to represent new head size diff = newPos - headElem.position; // check whether another step is needed or not if (diff.squaredLength() <= mSquaredElemLength) done = true; } else { // Extend existing head headElem.position = newPos; done = true; } // Is this segment full? if ((seg.tail + 1) % mMaxElementsPerChain == seg.head) { // If so, shrink tail gradually to match head extension Element& tailElem = mChainElementList[seg.start + seg.tail]; size_t preTailIdx; if (seg.tail == 0) preTailIdx = mMaxElementsPerChain - 1; else preTailIdx = seg.tail - 1; Element& preTailElem = mChainElementList[seg.start + preTailIdx]; // Measure tail diff from pretail to tail Vector3 taildiff = tailElem.position - preTailElem.position; Real taillen = taildiff.length(); if (taillen > 1e-06) { Real tailsize = mElemLength - diff.length(); taildiff *= tailsize / taillen; tailElem.position = preTailElem.position + taildiff; } } } // end while mBoundsDirty = true; // Need to dirty the parent node, but can't do it using needUpdate() here // since we're in the middle of the scene graph update (node listener), // so re-entrant calls don't work. Queue. if (mParentNode) { Node::queueNeedUpdate(getParentSceneNode()); } } //----------------------------------------------------------------------- void RibbonTrail::_timeUpdate(Real time) { // Apply all segment effects for (size_t s = 0; s < mChainSegmentList.size(); ++s) { ChainSegment& seg = mChainSegmentList[s]; if (seg.head != SEGMENT_EMPTY && seg.head != seg.tail) { for(size_t e = seg.head + 1;; ++e) // until break { e = e % mMaxElementsPerChain; Element& elem = mChainElementList[seg.start + e]; elem.width = elem.width - (time * mDeltaWidth[s]); elem.width = std::max(Real(0.0f), elem.width); elem.colour = elem.colour - (mDeltaColour[s] * time); elem.colour.saturate(); if (e == seg.tail) break; } } } mVertexContentDirty = true; } //----------------------------------------------------------------------- void RibbonTrail::resetTrail(size_t index, const Node* node) { assert(index < mChainCount); ChainSegment& seg = mChainSegmentList[index]; // set up this segment seg.head = seg.tail = SEGMENT_EMPTY; // Create new element, v coord is always 0.0f // need to convert to take parent node's position into account Vector3 position = node->_getDerivedPosition(); if (mParentNode) { position = mParentNode->convertWorldToLocalPosition(position); } Element e(position, mInitialWidth[index], 0.0f, mInitialColour[index], node->_getDerivedOrientation()); // Add the start position addChainElement(index, e); // Add another on the same spot, this will extend addChainElement(index, e); } //----------------------------------------------------------------------- void RibbonTrail::resetAllTrails(void) { for (size_t i = 0; i < mNodeList.size(); ++i) { resetTrail(i, mNodeList[i]); } } //----------------------------------------------------------------------- const String& RibbonTrail::getMovableType(void) const { return RibbonTrailFactory::FACTORY_TYPE_NAME; } //----------------------------------------------------------------------- //----------------------------------------------------------------------- String RibbonTrailFactory::FACTORY_TYPE_NAME = "RibbonTrail"; //----------------------------------------------------------------------- const String& RibbonTrailFactory::getType(void) const { return FACTORY_TYPE_NAME; } //----------------------------------------------------------------------- MovableObject* RibbonTrailFactory::createInstanceImpl( const String& name, const NameValuePairList* params) { size_t maxElements = 20; size_t numberOfChains = 1; bool useTex = true; bool useCol = true; // optional params if (params != 0) { NameValuePairList::const_iterator ni = params->find("maxElements"); if (ni != params->end()) { maxElements = StringConverter::parseUnsignedLong(ni->second); } ni = params->find("numberOfChains"); if (ni != params->end()) { numberOfChains = StringConverter::parseUnsignedLong(ni->second); } ni = params->find("useTextureCoords"); if (ni != params->end()) { useTex = StringConverter::parseBool(ni->second); } ni = params->find("useVertexColours"); if (ni != params->end()) { useCol = StringConverter::parseBool(ni->second); } } return OGRE_NEW RibbonTrail(name, maxElements, numberOfChains, useTex, useCol); } //----------------------------------------------------------------------- void RibbonTrailFactory::destroyInstance( MovableObject* obj) { OGRE_DELETE obj; } }
38.095153
112
0.508601
[ "object", "transform" ]
7ded909aa7511f3e96056d7b1391e9821750a19c
5,519
hpp
C++
BoostSharp/include/boost/geometry/multi/io/wkt/read.hpp
Icenium/BoostSharp
1dd31065fcd65ae6304b182c558bac7c7a738ad5
[ "Apache-2.0" ]
3
2017-05-11T05:30:19.000Z
2019-04-24T05:41:33.000Z
src/third_party/boost/boost/geometry/multi/io/wkt/read.hpp
wugh7125/installwizard
42f8aeb78026ff81838528968b1503e73f6c2864
[ "Apache-2.0" ]
null
null
null
src/third_party/boost/boost/geometry/multi/io/wkt/read.hpp
wugh7125/installwizard
42f8aeb78026ff81838528968b1503e73f6c2864
[ "Apache-2.0" ]
1
2022-03-26T17:00:08.000Z
2022-03-26T17:00:08.000Z
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands. // Copyright (c) 2008-2012 Bruno Lalande, Paris, France. // Copyright (c) 2009-2012 Mateusz Loskot, London, UK. // Parts of Boost.Geometry are redesigned from Geodan's Geographic Library // (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands. // Use, modification and distribution is subject to 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 BOOST_GEOMETRY_MULTI_IO_WKT_READ_MULTI_HPP #define BOOST_GEOMETRY_MULTI_IO_WKT_READ_MULTI_HPP #include <string> #include <boost/geometry/core/mutable_range.hpp> #include <boost/geometry/multi/core/tags.hpp> #include <boost/geometry/multi/core/point_type.hpp> #include <boost/geometry/multi/geometries/concepts/check.hpp> #include <boost/geometry/multi/io/wkt/detail/prefix.hpp> #include <boost/geometry/io/wkt/read.hpp> namespace boost { namespace geometry { namespace detail { namespace wkt { template <typename MultiGeometry, template<typename> class Parser, typename PrefixPolicy> struct multi_parser { static inline void apply(std::string const& wkt, MultiGeometry& geometry) { traits::clear<MultiGeometry>::apply(geometry); tokenizer tokens(wkt, boost::char_separator<char>(" ", ",()")); tokenizer::iterator it; if (initialize<MultiGeometry>(tokens, PrefixPolicy::apply(), wkt, it)) { handle_open_parenthesis(it, tokens.end(), wkt); // Parse sub-geometries while(it != tokens.end() && *it != ")") { traits::resize<MultiGeometry>::apply(geometry, boost::size(geometry) + 1); Parser < typename boost::range_value<MultiGeometry>::type >::apply(it, tokens.end(), wkt, geometry.back()); if (it != tokens.end() && *it == ",") { // Skip "," after multi-element is parsed ++it; } } handle_close_parenthesis(it, tokens.end(), wkt); } check_end(it, tokens.end(), wkt); } }; template <typename P> struct noparenthesis_point_parser { static inline void apply(tokenizer::iterator& it, tokenizer::iterator end, std::string const& wkt, P& point) { parsing_assigner<P, 0, dimension<P>::value>::apply(it, end, point, wkt); } }; template <typename MultiGeometry, typename PrefixPolicy> struct multi_point_parser { static inline void apply(std::string const& wkt, MultiGeometry& geometry) { traits::clear<MultiGeometry>::apply(geometry); tokenizer tokens(wkt, boost::char_separator<char>(" ", ",()")); tokenizer::iterator it; if (initialize<MultiGeometry>(tokens, PrefixPolicy::apply(), wkt, it)) { handle_open_parenthesis(it, tokens.end(), wkt); // If first point definition starts with "(" then parse points as (x y) // otherwise as "x y" bool using_brackets = (it != tokens.end() && *it == "("); while(it != tokens.end() && *it != ")") { traits::resize<MultiGeometry>::apply(geometry, boost::size(geometry) + 1); if (using_brackets) { point_parser < typename boost::range_value<MultiGeometry>::type >::apply(it, tokens.end(), wkt, geometry.back()); } else { noparenthesis_point_parser < typename boost::range_value<MultiGeometry>::type >::apply(it, tokens.end(), wkt, geometry.back()); } if (it != tokens.end() && *it == ",") { // Skip "," after point is parsed ++it; } } handle_close_parenthesis(it, tokens.end(), wkt); } check_end(it, tokens.end(), wkt); } }; }} // namespace detail::wkt #ifndef DOXYGEN_NO_DISPATCH namespace dispatch { template <typename MultiGeometry> struct read_wkt<multi_point_tag, MultiGeometry> : detail::wkt::multi_point_parser < MultiGeometry, detail::wkt::prefix_multipoint > {}; template <typename MultiGeometry> struct read_wkt<multi_linestring_tag, MultiGeometry> : detail::wkt::multi_parser < MultiGeometry, detail::wkt::linestring_parser, detail::wkt::prefix_multilinestring > {}; template <typename MultiGeometry> struct read_wkt<multi_polygon_tag, MultiGeometry> : detail::wkt::multi_parser < MultiGeometry, detail::wkt::polygon_parser, detail::wkt::prefix_multipolygon > {}; } // namespace dispatch #endif // DOXYGEN_NO_DISPATCH }} // namespace boost::geometry #endif // BOOST_GEOMETRY_MULTI_IO_WKT_READ_MULTI_HPP
32.656805
91
0.55626
[ "geometry" ]
7df599c296c2459060d6cbf50547cee529dc09fe
6,672
hpp
C++
src/Module/Socket.hpp
codechecker123/aff3ct
030af3e990027fa803fb2c68f974c9ec0ee79b5d
[ "MIT" ]
null
null
null
src/Module/Socket.hpp
codechecker123/aff3ct
030af3e990027fa803fb2c68f974c9ec0ee79b5d
[ "MIT" ]
null
null
null
src/Module/Socket.hpp
codechecker123/aff3ct
030af3e990027fa803fb2c68f974c9ec0ee79b5d
[ "MIT" ]
null
null
null
#ifndef SOCKET_HPP_ #define SOCKET_HPP_ #include <string> #include <sstream> #include <typeindex> #include "Tools/Exception/exception.hpp" #include "Task.hpp" namespace aff3ct { namespace module { static std::unordered_map<std::type_index,std::string> type_to_string = {{typeid(int8_t ), "int8" }, {typeid(int16_t), "int16" }, {typeid(int32_t), "int32" }, {typeid(int64_t), "int64" }, {typeid(float ), "float32"}, {typeid(double ), "float64"}}; static std::unordered_map<std::type_index,uint8_t> type_to_size = {{typeid(int8_t ), 1}, {typeid(int16_t), 2}, {typeid(int32_t), 4}, {typeid(int64_t), 8}, {typeid(float ), 4}, {typeid(double ), 8}}; class Socket { friend Task; protected: Task &task; const std::string name; const std::type_index datatype; const size_t databytes; bool fast; void* dataptr; Socket(Task &task, const std::string &name, const std::type_index datatype, const size_t databytes, const bool fast = false, void *dataptr = nullptr) : task(task), name(name), datatype(datatype), databytes(databytes), fast(fast), dataptr(dataptr) { } ~Socket() { } public: inline std::string get_name () const { return name; } inline std::type_index get_datatype () const { return datatype; } inline std::string get_datatype_string() const { return type_to_string[datatype]; } inline uint8_t get_datatype_size () const { return type_to_size[datatype]; } inline size_t get_databytes () const { return databytes; } inline size_t get_n_elmts () const { return get_databytes() / (size_t)get_datatype_size(); } inline void* get_dataptr () const { return dataptr; } inline bool is_fast () const { return fast; } inline void set_fast(const bool fast) { this->fast = fast; } inline int bind(Socket &s) { if (!is_fast()) { if (s.datatype != this->datatype) { std::stringstream message; message << "'s.datatype' has to be equal to 'datatype' ('s.datatype' = " << type_to_string[s.datatype] << ", 'datatype' = " << type_to_string[this->datatype] << ", 'name' = " << get_name() << ", 's.name' = " << s.get_name() << ", 'task.name' = " << task.get_name() << ", 's.task.name' = " << s.task.get_name() // << ", 'task.module.name' = " << task.get_module_name() // << ", 's.task.module.name' = " << s.task.get_module_name() << ")."; throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str()); } if (s.databytes != this->databytes) { std::stringstream message; message << "'s.databytes' has to be equal to 'databytes' ('s.databytes' = " << s.databytes << ", 'databytes' = " << this->databytes << ", 'name' = " << get_name() << ", 's.name' = " << s.get_name() << ", 'task.name' = " << task.get_name() << ", 's.task.name' = " << s.task.get_name() // << ", 'task.module.name' = " << task.get_module_name() // << ", 's.task.module.name' = " << s.task.get_module_name() << ")."; throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str()); } if (s.dataptr == nullptr) { std::stringstream message; message << "'s.dataptr' can't be NULL."; throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str()); } } this->dataptr = s.dataptr; if (this->task.is_autoexec() && this->task.is_last_input_socket(*this)) return this->task.exec(); else return 0; } inline int operator()(Socket &s) { return bind(s); } template <typename T, class A = std::allocator<T>> inline int bind(std::vector<T,A> &vector) { if (is_fast()) { this->dataptr = static_cast<void*>(vector.data()); return 0; } if (vector.size() != this->get_n_elmts()) { std::stringstream message; message << "'vector.size()' has to be equal to 'get_n_elmts()' ('vector.size()' = " << vector.size() << ", 'get_n_elmts()' = " << get_n_elmts() << ", 'name' = " << get_name() << ", 'task.name' = " << task.get_name() // << ", 'task.module.name' = " << task.get_module_name() << ")."; throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str()); } return bind(vector.data()); } template <typename T, class A = std::allocator<T>> inline int operator()(std::vector<T,A> &vector) { return bind(vector); } template <typename T> inline int bind(T *array) { if (is_fast()) { this->dataptr = static_cast<void*>(array); return 0; } if (type_to_string[typeid(T)] != type_to_string[this->datatype]) { std::stringstream message; message << "'T' has to be equal to 'datatype' ('T' = " << type_to_string[typeid(T)] << ", 'datatype' = " << type_to_string[this->datatype] << ", 'socket.name' = " << get_name() << ", 'task.name' = " << task.get_name() // << ", 'module.name' = " << task.get_module_name() << ")."; throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str()); } return bind(static_cast<void*>(array)); } template <typename T> inline int operator()(T *array) { return bind(array); } inline int bind(void* dataptr) { if (!is_fast()) { if (dataptr == nullptr) { std::stringstream message; message << "'s.dataptr' can't be NULL."; throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str()); } } this->dataptr = dataptr; return 0; } inline int operator()(void* dataptr) { return bind(dataptr); } }; } } #endif /* SOCKET_HPP_ */
32.38835
109
0.4997
[ "vector" ]
7dfb23da42171c681b715a79a96fec1c6348c836
1,133
cpp
C++
src/SourcePathsMapping/MappingItemModelTest.cpp
trobol/orbit
62a206c34b1308e0d56b91f695f39ba8879b713c
[ "BSD-2-Clause" ]
1
2021-04-15T23:59:38.000Z
2021-04-15T23:59:38.000Z
src/SourcePathsMapping/MappingItemModelTest.cpp
idfoxdale/orbit
c6525a14e65b1de57028eaca0ab633265aedf348
[ "BSD-2-Clause" ]
null
null
null
src/SourcePathsMapping/MappingItemModelTest.cpp
idfoxdale/orbit
c6525a14e65b1de57028eaca0ab633265aedf348
[ "BSD-2-Clause" ]
1
2020-07-14T13:16:03.000Z
2020-07-14T13:16:03.000Z
// Copyright (c) 2021 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <gtest/gtest.h> #include <QAbstractItemModelTester> #include "QtUtils/AssertNoQtLogWarnings.h" #include "SourcePathsMapping/Mapping.h" #include "SourcePathsMapping/MappingItemModel.h" namespace orbit_source_paths_mapping { const Mapping mapping0{"/build/project", "/home/user/project"}; const Mapping mapping1{"/src/project2", "/home/user/project"}; const Mapping mapping2{"/src/project", "/home/user/project"}; TEST(MappingItemModel, EmptyModel) { orbit_qt_utils::AssertNoQtLogWarnings message_handler{}; MappingItemModel model{}; QAbstractItemModelTester{&model, QAbstractItemModelTester::FailureReportingMode::Warning}; } TEST(MappingItemModel, FilledModel) { orbit_qt_utils::AssertNoQtLogWarnings message_handler{}; MappingItemModel model{}; model.SetMappings({mapping0, mapping1, mapping2}); QAbstractItemModelTester{&model, QAbstractItemModelTester::FailureReportingMode::Warning}; } } // namespace orbit_source_paths_mapping
31.472222
92
0.789056
[ "model" ]
7dfe001a859ba6976b669f7fc4a44f03139734ed
1,147
cpp
C++
UnitTests/Math/VectorTests.cpp
All8Up/JoltPhysics
751d13891f5bd8850863ad236eaa3c340e90de9a
[ "MIT" ]
1,311
2021-08-16T07:37:05.000Z
2022-03-31T21:13:39.000Z
UnitTests/Math/VectorTests.cpp
All8Up/JoltPhysics
751d13891f5bd8850863ad236eaa3c340e90de9a
[ "MIT" ]
102
2021-08-28T14:41:32.000Z
2022-03-31T20:25:55.000Z
UnitTests/Math/VectorTests.cpp
All8Up/JoltPhysics
751d13891f5bd8850863ad236eaa3c340e90de9a
[ "MIT" ]
65
2021-08-16T07:59:04.000Z
2022-03-28T06:18:49.000Z
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe // SPDX-License-Identifier: MIT #include "UnitTestFramework.h" #include <Math/Vector.h> TEST_SUITE("VectorTests") { TEST_CASE("TestVectorMultiplyFloat") { Vector<5> v; v[0] = 1; v[1] = 2; v[2] = 3; v[3] = 4; v[4] = 5; Vector<5> v2 = v * 2; CHECK(v2[0] == 2.0f); CHECK(v2[1] == 4.0f); CHECK(v2[2] == 6.0f); CHECK(v2[3] == 8.0f); CHECK(v2[4] == 10.0f); } TEST_CASE("TestVectorAdd") { Vector<5> v1 = Vector<5>::sZero(); Vector<5> v2 = Vector<5>::sZero(); v1[0] = 1; v2[0] = 2; v1[4] = 5; Vector<5> v3 = v1 + v2; CHECK(v3[0] == 3.0f); CHECK(v3[1] == 0.0f); CHECK(v3[2] == 0.0f); CHECK(v3[3] == 0.0f); CHECK(v3[4] == 5.0f); } TEST_CASE("TestVectorNegate") { Vector<5> v; v[0] = 1; v[1] = 2; v[2] = 3; v[3] = 4; v[4] = 5; Vector<5> v2 = -v; CHECK(v2[0] == -1.0f); CHECK(v2[1] == -2.0f); CHECK(v2[2] == -3.0f); CHECK(v2[3] == -4.0f); CHECK(v2[4] == -5.0f); } TEST_CASE("TestVectorLength") { Vector<5> v; v[0] = 1; v[1] = 2; v[2] = 3; v[3] = 4; v[4] = 5; CHECK(v.LengthSq() == float(1 + 4 + 9 + 16 + 25)); } }
17.378788
52
0.503051
[ "vector" ]
b401c9d03924898680468a855eb718f507476561
2,753
cpp
C++
Utilities/Poco/Foundation/src/SharedLibrary_HPUX.cpp
nocnokneo/MITK
2902dcaed2ebf83b08c29d73608e8c70ead9e602
[ "BSD-3-Clause" ]
null
null
null
Utilities/Poco/Foundation/src/SharedLibrary_HPUX.cpp
nocnokneo/MITK
2902dcaed2ebf83b08c29d73608e8c70ead9e602
[ "BSD-3-Clause" ]
null
null
null
Utilities/Poco/Foundation/src/SharedLibrary_HPUX.cpp
nocnokneo/MITK
2902dcaed2ebf83b08c29d73608e8c70ead9e602
[ "BSD-3-Clause" ]
null
null
null
// // SharedLibrary_HPUX.cpp // // $Id$ // // Library: Foundation // Package: SharedLibrary // Module: SharedLibrary // // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/SharedLibrary_HPUX.h" #include <dl.h> namespace Poco { FastMutex SharedLibraryImpl::_mutex; SharedLibraryImpl::SharedLibraryImpl() { _handle = 0; } SharedLibraryImpl::~SharedLibraryImpl() { } void SharedLibraryImpl::loadImpl(const std::string& path) { FastMutex::ScopedLock lock(_mutex); if (_handle) throw LibraryAlreadyLoadedException(path); _handle = shl_load(path.c_str(), BIND_DEFERRED, 0); if (!_handle) throw LibraryLoadException(path); _path = path; } void SharedLibraryImpl::unloadImpl() { FastMutex::ScopedLock lock(_mutex); if (_handle) { shl_unload(_handle); _handle = 0; _path.clear(); } } bool SharedLibraryImpl::isLoadedImpl() const { return _handle != 0; } void* SharedLibraryImpl::findSymbolImpl(const std::string& name) { FastMutex::ScopedLock lock(_mutex); void* result = 0; if (_handle && shl_findsym(&_handle, name.c_str(), TYPE_UNDEFINED, &result) != -1) return result; else return 0; } const std::string& SharedLibraryImpl::getPathImpl() const { return _path; } std::string SharedLibraryImpl::suffixImpl() { #if defined(_DEBUG) return "d.sl"; #else return ".sl"; #endif } } // namespace Poco
23.529915
84
0.73992
[ "object" ]
b403c5b83d33451dc7b04ef64e697815a2a19f8f
1,055
cpp
C++
leetcode.com/0793 Preimage Size of Factorial Zeroes Function/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2020-08-20T11:02:49.000Z
2020-08-20T11:02:49.000Z
leetcode.com/0793 Preimage Size of Factorial Zeroes Function/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
null
null
null
leetcode.com/0793 Preimage Size of Factorial Zeroes Function/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2022-01-01T23:23:13.000Z
2022-01-01T23:23:13.000Z
#include <iostream> #include <vector> using namespace std; unsigned f(unsigned x) { unsigned res = 0; for (x /= 5; x; x /= 5) res += x; return res; } class Solution { public: int preimageSizeFZF(int K) { unsigned l = 0, r = UINT32_MAX, m, k; // first find the right bound where f(rb) = K unsigned rb; while (l <= r) { m = r - (r - l) / 2; k = f(m); if (k < K) { l = m + 1; } else if (k == K) { l = m; if (l == r) break; } else { r = m - 1; } } if (l != r) return 0; rb = r; // then find the left bound where f(lb) = K l = 0, r = rb; while (l < r) { m = l + (r - l) / 2; k = f(m); if (k < K) { l = m + 1; } else { // only k == K, no k > K r = m; } } unsigned lb = l; return rb - lb + 1; } }; int main(int argc, char const *argv[]) { cout << f(UINT32_MAX) << endl; int K = 5; Solution s; while (cin >> K) { cout << s.preimageSizeFZF(K) << endl; } return 0; }
18.508772
49
0.434123
[ "vector" ]
b4075da9d43944fb6f747fc599037f14c5f7e961
837
cpp
C++
aws-cpp-sdk-chime/source/model/PutAppInstanceRetentionSettingsRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-chime/source/model/PutAppInstanceRetentionSettingsRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-chime/source/model/PutAppInstanceRetentionSettingsRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/chime/model/PutAppInstanceRetentionSettingsRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Chime::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; PutAppInstanceRetentionSettingsRequest::PutAppInstanceRetentionSettingsRequest() : m_appInstanceArnHasBeenSet(false), m_appInstanceRetentionSettingsHasBeenSet(false) { } Aws::String PutAppInstanceRetentionSettingsRequest::SerializePayload() const { JsonValue payload; if(m_appInstanceRetentionSettingsHasBeenSet) { payload.WithObject("AppInstanceRetentionSettings", m_appInstanceRetentionSettings.Jsonize()); } return payload.View().WriteReadable(); }
22.621622
96
0.786141
[ "model" ]
b40788dccf99714aacaffe9f610b91cbc8e4d981
2,564
cpp
C++
server.cpp
quantumsheep/chat-in-cpp
24364c8eed97251151cccc7e82f8bd065eef0ae4
[ "MIT" ]
1
2021-01-21T22:04:31.000Z
2021-01-21T22:04:31.000Z
server.cpp
quantumsheep/chat-in-cpp
24364c8eed97251151cccc7e82f8bd065eef0ae4
[ "MIT" ]
null
null
null
server.cpp
quantumsheep/chat-in-cpp
24364c8eed97251151cccc7e82f8bd065eef0ae4
[ "MIT" ]
null
null
null
#include <arpa/inet.h> #include <cerrno> #include <iostream> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <thread> #include <unistd.h> #include <vector> void handle_client(int client_fd) { std::string username; char buffer[256] = {0}; while (recv(client_fd, buffer, 255, 0) > 0) { if (username.empty()) { auto is_username_valid = strlen(buffer) >= 3 || strlen(buffer) <= 14; if (!is_username_valid) { for (auto cur = buffer; *cur != '\0'; cur++) { if (!isalnum(*cur)) { is_username_valid = false; break; } } } if (!is_username_valid) { break; } username = buffer; std::cout << "[info]> " << username << " has join the chat" << std::endl; } else { std::cout << username << "> " << buffer << std::endl; } memset(buffer, 0, 256); } if (!username.empty()) { std::cout << "[info]> " << username << " has quit the chat" << std::endl; } close(client_fd); } int main(int argc, char **argv) { if (argc != 2) { printf("Format: server <port>\n"); return EXIT_FAILURE; } auto port = atoi(argv[1]); auto server_socket = sockaddr_in{ .sin_family = AF_INET, .sin_port = htons(port), .sin_addr.s_addr = INADDR_ANY, }; auto socket_fd = socket(AF_INET, SOCK_STREAM, 0); if (bind(socket_fd, reinterpret_cast<sockaddr *>(&server_socket), sizeof(server_socket)) == -1) { std::cerr << "Error when binding socket: " << errno << std::endl; return EXIT_FAILURE; } if (listen(socket_fd, 40) == -1) { std::cerr << "Error: " << errno << std::endl; return EXIT_FAILURE; } std::cout << "Server listening on port " << port << std::endl; sockaddr_in client_socket; auto client_socket_size = sizeof(client_socket); int client_fd = 0; std::vector<std::thread> threads; while ((client_fd = accept(socket_fd, reinterpret_cast<sockaddr *>(&client_socket), reinterpret_cast<socklen_t *>(&client_socket_size)))) { std::thread client(handle_client, client_fd); threads.push_back(std::move(client)); } close(socket_fd); return EXIT_SUCCESS; }
23.962617
141
0.522621
[ "vector" ]
b40793ce1cf83bcfe62f7476793f35a0cb06c2ef
930
cpp
C++
src/rendering/marlin/usd/renderDelegate.cpp
JonCG90/Goby
da1bfcea23c058427e6bad1c58f1cd5405fe4c5f
[ "MIT" ]
null
null
null
src/rendering/marlin/usd/renderDelegate.cpp
JonCG90/Goby
da1bfcea23c058427e6bad1c58f1cd5405fe4c5f
[ "MIT" ]
null
null
null
src/rendering/marlin/usd/renderDelegate.cpp
JonCG90/Goby
da1bfcea23c058427e6bad1c58f1cd5405fe4c5f
[ "MIT" ]
null
null
null
// // renderDelegate.cpp // Goby // // Created by Jonathan Graham on 7/2/19. // #include "renderDelegate.hpp" const pxr::TfTokenVector & HdMarlinRendererDelegate::GetSupportedRprimTypes() const { static const pxr::TfTokenVector supportedRprims = { pxr::HdPrimTypeTokens->mesh }; return supportedRprims; } const pxr::TfTokenVector & HdMarlinRendererDelegate::GetSupportedSprimTypes() const { static const pxr::TfTokenVector supportedSprims = { pxr::HdPrimTypeTokens->camera }; return supportedSprims; } const pxr::TfTokenVector & HdMarlinRendererDelegate::GetSupportedBprimTypes() const { static const pxr::TfTokenVector supportedBprims = { pxr::HdPrimTypeTokens->renderBuffer }; return supportedBprims; } //pxr::HdRenderParam* HdMarlinRendererDelegate::GetRenderParam() const //{ // //} // //pxr::HdResourceRegistrySharedPtr HdMarlinRendererDelegate::GetResourceRegistry() const //{ // //}
25.135135
94
0.747312
[ "mesh" ]
b40a8a17d15813ada3c9ea4ecb52537a5c1b80a5
15,996
cpp
C++
clients/cpp-restsdk/generated/api/CustomApi.cpp
hoomaan-kh/swagger-aem
0b19225bb6e071df761d176cbc13565891fe895f
[ "Apache-2.0" ]
null
null
null
clients/cpp-restsdk/generated/api/CustomApi.cpp
hoomaan-kh/swagger-aem
0b19225bb6e071df761d176cbc13565891fe895f
[ "Apache-2.0" ]
null
null
null
clients/cpp-restsdk/generated/api/CustomApi.cpp
hoomaan-kh/swagger-aem
0b19225bb6e071df761d176cbc13565891fe895f
[ "Apache-2.0" ]
null
null
null
/** * Adobe Experience Manager (AEM) API * Swagger AEM is an OpenAPI specification for Adobe Experience Manager (AEM) API * * OpenAPI spec version: 3.2.0-pre.0 * Contact: opensource@shinesolutions.com * * NOTE: This class is auto generated by OpenAPI-Generator 3.2.1-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ #include "CustomApi.h" #include "IHttpBody.h" #include "JsonBody.h" #include "MultipartFormData.h" #include <unordered_set> #include <boost/algorithm/string/replace.hpp> namespace org { namespace openapitools { namespace client { namespace api { using namespace org::openapitools::client::model; CustomApi::CustomApi( std::shared_ptr<ApiClient> apiClient ) : m_ApiClient(apiClient) { } CustomApi::~CustomApi() { } pplx::task<utility::string_t> CustomApi::getAemHealthCheck(boost::optional<utility::string_t> tags, boost::optional<bool> combineTagsOr) { std::shared_ptr<ApiConfiguration> apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = utility::conversions::to_string_t("/system/health"); std::map<utility::string_t, utility::string_t> queryParams; std::map<utility::string_t, utility::string_t> headerParams( apiConfiguration->getDefaultHeaders() ); std::map<utility::string_t, utility::string_t> formParams; std::map<utility::string_t, std::shared_ptr<HttpContent>> fileParams; std::unordered_set<utility::string_t> responseHttpContentTypes; responseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") ); utility::string_t responseHttpContentType; // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { responseHttpContentType = utility::conversions::to_string_t("text/plain"); } // JSON else if ( responseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != responseHttpContentTypes.end() ) { responseHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata else if( responseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != responseHttpContentTypes.end() ) { responseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } // plain text else if( responseHttpContentTypes.find(utility::conversions::to_string_t("text/plain")) != responseHttpContentTypes.end() ) { responseHttpContentType = utility::conversions::to_string_t("text/plain"); } else { throw ApiException(400, utility::conversions::to_string_t("CustomApi->getAemHealthCheck does not produce any supported media type")); } headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType; std::unordered_set<utility::string_t> consumeHttpContentTypes; if (tags) { queryParams[utility::conversions::to_string_t("tags")] = ApiClient::parameterToString(*tags); } if (combineTagsOr) { queryParams[utility::conversions::to_string_t("combineTagsOr")] = ApiClient::parameterToString(*combineTagsOr); } std::shared_ptr<IHttpBody> httpBody; utility::string_t requestHttpContentType; // use JSON if possible if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != consumeHttpContentTypes.end() ) { requestHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata else if( consumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != consumeHttpContentTypes.end() ) { requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { throw ApiException(415, utility::conversions::to_string_t("CustomApi->getAemHealthCheck does not consume any supported media type")); } // authentication (aemAuth) required // Basic authentication is added automatically as part of the http_client_config return m_ApiClient->callApi(path, utility::conversions::to_string_t("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK // 2xx - successful : OK // 3xx - redirection : OK // 4xx - client error : not OK // 5xx - client error : not OK if (response.status_code() >= 400) { throw ApiException(response.status_code() , utility::conversions::to_string_t("error calling getAemHealthCheck: ") + response.reason_phrase() , std::make_shared<std::stringstream>(response.extract_utf8string(true).get())); } // check response content type if(response.headers().has(utility::conversions::to_string_t("Content-Type"))) { utility::string_t contentType = response.headers()[utility::conversions::to_string_t("Content-Type")]; if( contentType.find(responseHttpContentType) == std::string::npos ) { throw ApiException(500 , utility::conversions::to_string_t("error calling getAemHealthCheck: unexpected response type: ") + contentType , std::make_shared<std::stringstream>(response.extract_utf8string(true).get())); } } return response.extract_string(); }) .then([=](utility::string_t response) { utility::string_t result(utility::conversions::to_string_t("")); if(responseHttpContentType == utility::conversions::to_string_t("application/json")) { web::json::value json = web::json::value::parse(response); result = ModelBase::stringFromJson(json); } else if(responseHttpContentType == utility::conversions::to_string_t("text/plain")) { result = response; } // else if(responseHttpContentType == utility::conversions::to_string_t("multipart/form-data")) // { // TODO multipart response parsing // } else { throw ApiException(500 , utility::conversions::to_string_t("error calling getAemHealthCheck: unsupported response type")); } return result; }); } pplx::task<void> CustomApi::postConfigAemHealthCheckServlet(boost::optional<std::vector<utility::string_t>> bundlesPeriodignored, boost::optional<utility::string_t> bundlesPeriodignoredAtTypeHint) { std::shared_ptr<ApiConfiguration> apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = utility::conversions::to_string_t("/apps/system/config/com.shinesolutions.healthcheck.hc.impl.ActiveBundleHealthCheck"); std::map<utility::string_t, utility::string_t> queryParams; std::map<utility::string_t, utility::string_t> headerParams( apiConfiguration->getDefaultHeaders() ); std::map<utility::string_t, utility::string_t> formParams; std::map<utility::string_t, std::shared_ptr<HttpContent>> fileParams; std::unordered_set<utility::string_t> responseHttpContentTypes; utility::string_t responseHttpContentType; // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { responseHttpContentType = utility::conversions::to_string_t("application/json"); } // JSON else if ( responseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != responseHttpContentTypes.end() ) { responseHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata else if( responseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != responseHttpContentTypes.end() ) { responseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { throw ApiException(400, utility::conversions::to_string_t("CustomApi->postConfigAemHealthCheckServlet does not produce any supported media type")); } headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType; std::unordered_set<utility::string_t> consumeHttpContentTypes; if (bundlesPeriodignored) { queryParams[utility::conversions::to_string_t("bundles.ignored")] = ApiClient::parameterToString(*bundlesPeriodignored); } if (bundlesPeriodignoredAtTypeHint) { queryParams[utility::conversions::to_string_t("bundles.ignored@TypeHint")] = ApiClient::parameterToString(*bundlesPeriodignoredAtTypeHint); } std::shared_ptr<IHttpBody> httpBody; utility::string_t requestHttpContentType; // use JSON if possible if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != consumeHttpContentTypes.end() ) { requestHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata else if( consumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != consumeHttpContentTypes.end() ) { requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { throw ApiException(415, utility::conversions::to_string_t("CustomApi->postConfigAemHealthCheckServlet does not consume any supported media type")); } // authentication (aemAuth) required // Basic authentication is added automatically as part of the http_client_config return m_ApiClient->callApi(path, utility::conversions::to_string_t("POST"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK // 2xx - successful : OK // 3xx - redirection : OK // 4xx - client error : not OK // 5xx - client error : not OK if (response.status_code() >= 400) { throw ApiException(response.status_code() , utility::conversions::to_string_t("error calling postConfigAemHealthCheckServlet: ") + response.reason_phrase() , std::make_shared<std::stringstream>(response.extract_utf8string(true).get())); } // check response content type if(response.headers().has(utility::conversions::to_string_t("Content-Type"))) { utility::string_t contentType = response.headers()[utility::conversions::to_string_t("Content-Type")]; if( contentType.find(responseHttpContentType) == std::string::npos ) { throw ApiException(500 , utility::conversions::to_string_t("error calling postConfigAemHealthCheckServlet: unexpected response type: ") + contentType , std::make_shared<std::stringstream>(response.extract_utf8string(true).get())); } } return response.extract_string(); }) .then([=](utility::string_t response) { return void(); }); } pplx::task<void> CustomApi::postConfigAemPasswordReset(boost::optional<std::vector<utility::string_t>> pwdresetPeriodauthorizables, boost::optional<utility::string_t> pwdresetPeriodauthorizablesAtTypeHint) { std::shared_ptr<ApiConfiguration> apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = utility::conversions::to_string_t("/apps/system/config/com.shinesolutions.aem.passwordreset.Activator"); std::map<utility::string_t, utility::string_t> queryParams; std::map<utility::string_t, utility::string_t> headerParams( apiConfiguration->getDefaultHeaders() ); std::map<utility::string_t, utility::string_t> formParams; std::map<utility::string_t, std::shared_ptr<HttpContent>> fileParams; std::unordered_set<utility::string_t> responseHttpContentTypes; utility::string_t responseHttpContentType; // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { responseHttpContentType = utility::conversions::to_string_t("application/json"); } // JSON else if ( responseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != responseHttpContentTypes.end() ) { responseHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata else if( responseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != responseHttpContentTypes.end() ) { responseHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { throw ApiException(400, utility::conversions::to_string_t("CustomApi->postConfigAemPasswordReset does not produce any supported media type")); } headerParams[utility::conversions::to_string_t("Accept")] = responseHttpContentType; std::unordered_set<utility::string_t> consumeHttpContentTypes; if (pwdresetPeriodauthorizables) { queryParams[utility::conversions::to_string_t("pwdreset.authorizables")] = ApiClient::parameterToString(*pwdresetPeriodauthorizables); } if (pwdresetPeriodauthorizablesAtTypeHint) { queryParams[utility::conversions::to_string_t("pwdreset.authorizables@TypeHint")] = ApiClient::parameterToString(*pwdresetPeriodauthorizablesAtTypeHint); } std::shared_ptr<IHttpBody> httpBody; utility::string_t requestHttpContentType; // use JSON if possible if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != consumeHttpContentTypes.end() ) { requestHttpContentType = utility::conversions::to_string_t("application/json"); } // multipart formdata else if( consumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != consumeHttpContentTypes.end() ) { requestHttpContentType = utility::conversions::to_string_t("multipart/form-data"); } else { throw ApiException(415, utility::conversions::to_string_t("CustomApi->postConfigAemPasswordReset does not consume any supported media type")); } // authentication (aemAuth) required // Basic authentication is added automatically as part of the http_client_config return m_ApiClient->callApi(path, utility::conversions::to_string_t("POST"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK // 2xx - successful : OK // 3xx - redirection : OK // 4xx - client error : not OK // 5xx - client error : not OK if (response.status_code() >= 400) { throw ApiException(response.status_code() , utility::conversions::to_string_t("error calling postConfigAemPasswordReset: ") + response.reason_phrase() , std::make_shared<std::stringstream>(response.extract_utf8string(true).get())); } // check response content type if(response.headers().has(utility::conversions::to_string_t("Content-Type"))) { utility::string_t contentType = response.headers()[utility::conversions::to_string_t("Content-Type")]; if( contentType.find(responseHttpContentType) == std::string::npos ) { throw ApiException(500 , utility::conversions::to_string_t("error calling postConfigAemPasswordReset: unexpected response type: ") + contentType , std::make_shared<std::stringstream>(response.extract_utf8string(true).get())); } } return response.extract_string(); }) .then([=](utility::string_t response) { return void(); }); } } } } }
41.440415
205
0.688672
[ "vector", "model" ]
b40bb70059b3a29644427aaad37f45a96f9cb1a0
1,443
cpp
C++
c++/0017-letter-combinations-of-a-phone-number.cpp
aafulei/leetcode
e3a0ef9c912abf99a1d6e56eff8802ba44b0057d
[ "MIT" ]
2
2019-04-13T09:55:04.000Z
2019-05-16T12:47:40.000Z
c++/0017-letter-combinations-of-a-phone-number.cpp
aafulei/leetcode
e3a0ef9c912abf99a1d6e56eff8802ba44b0057d
[ "MIT" ]
null
null
null
c++/0017-letter-combinations-of-a-phone-number.cpp
aafulei/leetcode
e3a0ef9c912abf99a1d6e56eff8802ba44b0057d
[ "MIT" ]
null
null
null
// 22/05/09 = Mon // 19/01/07 = Mon // 17. Letter Combinations of a Phone Number [Medium] // Given a string containing digits from 2-9 inclusive, return all possible // letter combinations that the number could represent. Return the answer in any // order. // A mapping of digit to letters (just like on the telephone buttons) is given // below. Note that 1 does not map to any letters. // Example 1: // Input: digits = "23" // Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"] // Example 2: // Input: digits = "" // Output: [] // Example 3: // Input: digits = "2" // Output: ["a","b","c"] // Constraints: // 0 <= digits.length <= 4 // digits[i] is a digit in the range ['2', '9']. // Related Topics: // [Backtracking*] [Hash Table] [String] class Solution { const string table[8] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; void bt(int pos, string &out, vector<string> &res, const string &digits) { if (pos == digits.size()) { res.push_back(out); return; } int key = digits[pos] - '2'; for (int i = 0; i != table[key].size(); ++i) { out.push_back(table[key][i]); bt(pos + 1, out, res, digits); out.pop_back(); } } public: vector<string> letterCombinations(string digits) { if (digits.empty()) { return {}; } vector<string> res; string out; bt(0, out, res, digits); return res; } };
24.05
80
0.57034
[ "vector" ]
b40cd59c73da5123cd40f13fec03282737c10c46
6,946
cpp
C++
src/controller/python/chip/server/ServerInit.cpp
chencheung/connectedhomeip
0cbfaec010c7fe62a728ec92c0afa89999d52ef0
[ "Apache-2.0" ]
4
2020-09-11T04:32:44.000Z
2022-03-11T09:06:07.000Z
src/controller/python/chip/server/ServerInit.cpp
chencheung/connectedhomeip
0cbfaec010c7fe62a728ec92c0afa89999d52ef0
[ "Apache-2.0" ]
null
null
null
src/controller/python/chip/server/ServerInit.cpp
chencheung/connectedhomeip
0cbfaec010c7fe62a728ec92c0afa89999d52ef0
[ "Apache-2.0" ]
null
null
null
/* * * Copyright (c) 2021 Project CHIP 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 <errno.h> #include <pthread.h> #include <platform/CHIPDeviceLayer.h> #include <platform/PlatformManager.h> #include <app/server/OnboardingCodesUtil.h> #include <app/server/Server.h> #include <lib/core/CHIPError.h> #include <lib/support/logging/CHIPLogging.h> #include <setup_payload/QRCodeSetupPayloadGenerator.h> #include <setup_payload/SetupPayload.h> // #include <support/CHIPMem.h> // #include <support/ErrorStr.h> // #include <examples/platform/linux/AppMain.h> #include "Options.h" using namespace chip; using namespace chip::Inet; using namespace chip::Transport; using namespace chip::DeviceLayer; namespace { void EventHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg) { (void) arg; if (event->Type == chip::DeviceLayer::DeviceEventType::kCHIPoBLEConnectionEstablished) { ChipLogProgress(DeviceLayer, "Receive kCHIPoBLEConnectionEstablished"); } } pthread_t sPlatformMainThread; #if CHIP_DEVICE_LAYER_TARGET_LINUX && CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE // uint32_t sBluetoothAdapterId = 0; #endif void * PlatformMainLoop(void *) { ChipLogProgress(DeviceLayer, "Platform main loop started."); chip::DeviceLayer::PlatformMgr().RunEventLoop(); ChipLogProgress(DeviceLayer, "Platform main loop completed."); return nullptr; } } // namespace extern "C" { #if CHIP_DEVICE_CONFIG_ENABLE_WPA /* * The device shall check every kWiFiStartCheckTimeUsec whether Wi-Fi management * has been fully initialized. If after kWiFiStartCheckAttempts Wi-Fi management * still hasn't been initialized, the device configuration is reset, and device * needs to be paired again. */ static constexpr useconds_t kWiFiStartCheckTimeUsec = 100 * 1000; // 100 ms static constexpr uint8_t kWiFiStartCheckAttempts = 5; #endif #if CHIP_DEVICE_CONFIG_ENABLE_WPA static bool EnsureWiFiIsStarted() { for (int cnt = 0; cnt < kWiFiStartCheckAttempts; cnt++) { if (chip::DeviceLayer::ConnectivityMgrImpl().IsWiFiManagementStarted()) { return true; } usleep(kWiFiStartCheckTimeUsec); } return chip::DeviceLayer::ConnectivityMgrImpl().IsWiFiManagementStarted(); } #endif using PostAttributeChangeCallback = void (*)(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t mask, uint16_t manufacturerCode, uint8_t type, uint16_t size, uint8_t * value); class PythonServerDelegate // : public ServerDelegate { public: void SetPostAttributeChangeCallback(PostAttributeChangeCallback cb) { // ChipLogProgress(NotSpecified, "callback %p", cb); mPostAttributeChangeCallback = cb; }; PostAttributeChangeCallback mPostAttributeChangeCallback = nullptr; }; PythonServerDelegate gPythonServerDelegate; void pychip_server_set_callbacks(PostAttributeChangeCallback cb) { // ChipLogProgress(NotSpecified, "setting cb"); gPythonServerDelegate.SetPostAttributeChangeCallback(cb); } void pychip_server_native_init() { CHIP_ERROR err = CHIP_NO_ERROR; int result; int tmpErrno; err = chip::Platform::MemoryInit(); if (err != CHIP_NO_ERROR) { ChipLogError(DeviceLayer, "Failed to initialize CHIP stack: memory init failed: %s", chip::ErrorStr(err)); } err = chip::DeviceLayer::PlatformMgr().InitChipStack(); if (err != CHIP_NO_ERROR) { ChipLogError(DeviceLayer, "Failed to initialize CHIP stack: platform init failed: %s", chip::ErrorStr(err)); } ConfigurationMgr().LogDeviceConfig(); PrintOnboardingCodes(chip::RendezvousInformationFlag(chip::RendezvousInformationFlag::kBLE)); #if defined(PW_RPC_ENABLED) chip::rpc::Init(); ChipLogProgress(NotSpecified, "PW_RPC initialized."); #endif // defined(PW_RPC_ENABLED) chip::DeviceLayer::PlatformMgrImpl().AddEventHandler(EventHandler, 0); #if CONFIG_NETWORK_LAYER_BLE chip::DeviceLayer::ConnectivityMgr().SetBLEDeviceName("RpiMatterDali"); // Use default device name (CHIP-XXXX) chip::DeviceLayer::Internal::BLEMgrImpl().ConfigureBle(LinuxDeviceOptions::GetInstance().mBleDevice, false); chip::DeviceLayer::ConnectivityMgr().SetBLEAdvertisingEnabled(true); #endif #if CHIP_DEVICE_CONFIG_ENABLE_WPA if (LinuxDeviceOptions::GetInstance().mWiFi) { chip::DeviceLayer::ConnectivityMgrImpl().StartWiFiManagement(); if (!EnsureWiFiIsStarted()) { ChipLogError(NotSpecified, "Wi-Fi Management taking too long to start - device configuration will be reset."); } } #endif // CHIP_DEVICE_CONFIG_ENABLE_WPA // parts from ChipLinuxAppMainLoop uint16_t securePort = CHIP_PORT; uint16_t unsecurePort = CHIP_UDC_PORT; // Init ZCL Data Model and CHIP App Server static chip::CommonCaseDeviceServerInitParams initParams; (void) initParams.InitializeStaticResourcesBeforeServerInit(); initParams.operationalServicePort = CHIP_PORT; initParams.userDirectedCommissioningPort = CHIP_UDC_PORT; chip::Server::GetInstance().Init(initParams); // Initialize device attestation config // SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); result = pthread_create(&sPlatformMainThread, nullptr, PlatformMainLoop, nullptr); tmpErrno = errno; if (result != 0) { ChipLogError(DeviceLayer, "Failed to initialize CHIP stack: pthread_create failed: %s", strerror(tmpErrno)); } return /*err*/; } } void emberAfPostAttributeChangeCallback(chip::EndpointId endpoint, chip::ClusterId clusterId, chip::AttributeId attributeId, uint8_t mask, uint16_t manufacturerCode, uint8_t type, uint16_t size, uint8_t * value) { // ChipLogProgress(NotSpecified, "emberAfPostAttributeChangeCallback()"); if (gPythonServerDelegate.mPostAttributeChangeCallback != nullptr) { // ChipLogProgress(NotSpecified, "callback %p", gPythonServerDelegate.mPostAttributeChangeCallback); gPythonServerDelegate.mPostAttributeChangeCallback(endpoint, clusterId, attributeId, mask, manufacturerCode, type, size, value); } else { // ChipLogProgress(NotSpecified, "callback nullptr"); } };
32.764151
128
0.722286
[ "model" ]
b40d51602f37bfe5ec57de9969f43f4654d1fb3f
40,447
hpp
C++
01_Develop/libXMFFmpeg/Source/libavcodec/motion_est_template.hpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2017-08-03T07:15:00.000Z
2018-06-18T10:32:53.000Z
01_Develop/libXMFFmpeg/Source/libavcodec/motion_est_template.hpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
null
null
null
01_Develop/libXMFFmpeg/Source/libavcodec/motion_est_template.hpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2019-03-04T22:57:42.000Z
2020-03-06T01:32:26.000Z
/* * Motion estimation * Copyright (c) 2002-2004 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Motion estimation template. */ //Let us hope gcc will remove the unused vars ...(gcc 3.2.2 seems to do it ...) #define LOAD_COMMON\ uint32_t av_unused * const score_map= c->score_map;\ const int av_unused xmin= c->xmin;\ const int av_unused ymin= c->ymin;\ const int av_unused xmax= c->xmax;\ const int av_unused ymax= c->ymax;\ uint8_t *mv_penalty= c->current_mv_penalty;\ const int pred_x= c->pred_x;\ const int pred_y= c->pred_y;\ #define CHECK_HALF_MV(dx, dy, x, y)\ {\ const int hx= 2*(x)+(dx);\ const int hy= 2*(y)+(dy);\ d= cmp_hpel(s, x, y, dx, dy, size, h, ref_index, src_index, cmp_sub, chroma_cmp_sub, flags);\ d += (mv_penalty[hx - pred_x] + mv_penalty[hy - pred_y])*penalty_factor;\ COPY3_IF_LT(dmin, d, bx, hx, by, hy)\ } static int hpel_motion_search(MpegEncContext * s, int *mx_ptr, int *my_ptr, int dmin, int src_index, int ref_index, int size, int h) { MotionEstContext * const c= &s->me; const int mx = *mx_ptr; const int my = *my_ptr; const int penalty_factor= c->sub_penalty_factor; me_cmp_func cmp_sub, chroma_cmp_sub; int bx=2*mx, by=2*my; LOAD_COMMON int flags= c->sub_flags; //FIXME factorize cmp_sub= s->dsp.me_sub_cmp[size]; chroma_cmp_sub= s->dsp.me_sub_cmp[size+1]; if(c->skip){ //FIXME move out of hpel? *mx_ptr = 0; *my_ptr = 0; return dmin; } if(c->avctx->me_cmp != c->avctx->me_sub_cmp){ dmin= cmp(s, mx, my, 0, 0, size, h, ref_index, src_index, cmp_sub, chroma_cmp_sub, flags); if(mx || my || size>0) dmin += (mv_penalty[2*mx - pred_x] + mv_penalty[2*my - pred_y])*penalty_factor; } if (mx > xmin && mx < xmax && my > ymin && my < ymax) { int d= dmin; const int index= (my<<ME_MAP_SHIFT) + mx; const int t= score_map[(index-(1<<ME_MAP_SHIFT))&(ME_MAP_SIZE-1)] + (mv_penalty[bx - pred_x] + mv_penalty[by-2 - pred_y])*c->penalty_factor; const int l= score_map[(index- 1 )&(ME_MAP_SIZE-1)] + (mv_penalty[bx-2 - pred_x] + mv_penalty[by - pred_y])*c->penalty_factor; const int r= score_map[(index+ 1 )&(ME_MAP_SIZE-1)] + (mv_penalty[bx+2 - pred_x] + mv_penalty[by - pred_y])*c->penalty_factor; const int b= score_map[(index+(1<<ME_MAP_SHIFT))&(ME_MAP_SIZE-1)] + (mv_penalty[bx - pred_x] + mv_penalty[by+2 - pred_y])*c->penalty_factor; #if 1 unsigned key; unsigned map_generation= c->map_generation; //#ifndef NDEBUG uint32_t *map= c->map; //#endif key= ((my-1)<<ME_MAP_MV_BITS) + (mx) + map_generation; assert(map[(index-(1<<ME_MAP_SHIFT))&(ME_MAP_SIZE-1)] == key); key= ((my+1)<<ME_MAP_MV_BITS) + (mx) + map_generation; assert(map[(index+(1<<ME_MAP_SHIFT))&(ME_MAP_SIZE-1)] == key); key= ((my)<<ME_MAP_MV_BITS) + (mx+1) + map_generation; assert(map[(index+1)&(ME_MAP_SIZE-1)] == key); key= ((my)<<ME_MAP_MV_BITS) + (mx-1) + map_generation; assert(map[(index-1)&(ME_MAP_SIZE-1)] == key); #endif if(t<=b){ CHECK_HALF_MV(0, 1, mx ,my-1) if(l<=r){ CHECK_HALF_MV(1, 1, mx-1, my-1) if(t+r<=b+l){ CHECK_HALF_MV(1, 1, mx , my-1) }else{ CHECK_HALF_MV(1, 1, mx-1, my ) } CHECK_HALF_MV(1, 0, mx-1, my ) }else{ CHECK_HALF_MV(1, 1, mx , my-1) if(t+l<=b+r){ CHECK_HALF_MV(1, 1, mx-1, my-1) }else{ CHECK_HALF_MV(1, 1, mx , my ) } CHECK_HALF_MV(1, 0, mx , my ) } }else{ if(l<=r){ if(t+l<=b+r){ CHECK_HALF_MV(1, 1, mx-1, my-1) }else{ CHECK_HALF_MV(1, 1, mx , my ) } CHECK_HALF_MV(1, 0, mx-1, my) CHECK_HALF_MV(1, 1, mx-1, my) }else{ if(t+r<=b+l){ CHECK_HALF_MV(1, 1, mx , my-1) }else{ CHECK_HALF_MV(1, 1, mx-1, my) } CHECK_HALF_MV(1, 0, mx , my) CHECK_HALF_MV(1, 1, mx , my) } CHECK_HALF_MV(0, 1, mx , my) } assert(bx >= xmin*2 && bx <= xmax*2 && by >= ymin*2 && by <= ymax*2); } *mx_ptr = bx; *my_ptr = by; return dmin; } static int no_sub_motion_search(MpegEncContext * s, int *mx_ptr, int *my_ptr, int dmin, int src_index, int ref_index, int size, int h) { (*mx_ptr)<<=1; (*my_ptr)<<=1; return dmin; } int ff_get_mb_score(MpegEncContext * s, int mx, int my, int src_index, int ref_index, int size, int h, int add_rate) { // const int check_luma= s->dsp.me_sub_cmp != s->dsp.mb_cmp; MotionEstContext * const c= &s->me; const int penalty_factor= c->mb_penalty_factor; const int flags= c->mb_flags; const int qpel= flags & FLAG_QPEL; const int mask= 1+2*qpel; me_cmp_func cmp_sub, chroma_cmp_sub; int d; LOAD_COMMON //FIXME factorize cmp_sub= s->dsp.mb_cmp[size]; chroma_cmp_sub= s->dsp.mb_cmp[size+1]; // assert(!c->skip); // assert(c->avctx->me_sub_cmp != c->avctx->mb_cmp); d= cmp(s, mx>>(qpel+1), my>>(qpel+1), mx&mask, my&mask, size, h, ref_index, src_index, cmp_sub, chroma_cmp_sub, flags); //FIXME check cbp before adding penalty for (0,0) vector if(add_rate && (mx || my || size>0)) d += (mv_penalty[mx - pred_x] + mv_penalty[my - pred_y])*penalty_factor; return d; } #define CHECK_QUARTER_MV(dx, dy, x, y)\ {\ const int hx= 4*(x)+(dx);\ const int hy= 4*(y)+(dy);\ d= cmp_qpel(s, x, y, dx, dy, size, h, ref_index, src_index, cmpf, chroma_cmpf, flags);\ d += (mv_penalty[hx - pred_x] + mv_penalty[hy - pred_y])*penalty_factor;\ COPY3_IF_LT(dmin, d, bx, hx, by, hy)\ } static int qpel_motion_search(MpegEncContext * s, int *mx_ptr, int *my_ptr, int dmin, int src_index, int ref_index, int size, int h) { MotionEstContext * const c= &s->me; const int mx = *mx_ptr; const int my = *my_ptr; const int penalty_factor= c->sub_penalty_factor; const unsigned map_generation = c->map_generation; const int subpel_quality= c->avctx->me_subpel_quality; uint32_t *map= c->map; me_cmp_func cmpf, chroma_cmpf; me_cmp_func cmp_sub, chroma_cmp_sub; LOAD_COMMON int flags= c->sub_flags; cmpf= s->dsp.me_cmp[size]; chroma_cmpf= s->dsp.me_cmp[size+1]; //factorize FIXME //FIXME factorize cmp_sub= s->dsp.me_sub_cmp[size]; chroma_cmp_sub= s->dsp.me_sub_cmp[size+1]; if(c->skip){ //FIXME somehow move up (benchmark) *mx_ptr = 0; *my_ptr = 0; return dmin; } if(c->avctx->me_cmp != c->avctx->me_sub_cmp){ dmin= cmp(s, mx, my, 0, 0, size, h, ref_index, src_index, cmp_sub, chroma_cmp_sub, flags); if(mx || my || size>0) dmin += (mv_penalty[4*mx - pred_x] + mv_penalty[4*my - pred_y])*penalty_factor; } if (mx > xmin && mx < xmax && my > ymin && my < ymax) { int bx=4*mx, by=4*my; int d= dmin; int i, nx, ny; const int index= (my<<ME_MAP_SHIFT) + mx; const int t= score_map[(index-(1<<ME_MAP_SHIFT) )&(ME_MAP_SIZE-1)]; const int l= score_map[(index- 1 )&(ME_MAP_SIZE-1)]; const int r= score_map[(index+ 1 )&(ME_MAP_SIZE-1)]; const int b= score_map[(index+(1<<ME_MAP_SHIFT) )&(ME_MAP_SIZE-1)]; const int c= score_map[(index )&(ME_MAP_SIZE-1)]; int best[8]; int best_pos[8][2]; memset(best, 64, sizeof(int)*8); if(s->me.dia_size>=2){ const int tl= score_map[(index-(1<<ME_MAP_SHIFT)-1)&(ME_MAP_SIZE-1)]; const int bl= score_map[(index+(1<<ME_MAP_SHIFT)-1)&(ME_MAP_SIZE-1)]; const int tr= score_map[(index-(1<<ME_MAP_SHIFT)+1)&(ME_MAP_SIZE-1)]; const int br= score_map[(index+(1<<ME_MAP_SHIFT)+1)&(ME_MAP_SIZE-1)]; for(ny= -3; ny <= 3; ny++){ for(nx= -3; nx <= 3; nx++){ //FIXME this could overflow (unlikely though) const int64_t t2= nx*nx*(tr + tl - 2*t) + 4*nx*(tr-tl) + 32*t; const int64_t c2= nx*nx*( r + l - 2*c) + 4*nx*( r- l) + 32*c; const int64_t b2= nx*nx*(br + bl - 2*b) + 4*nx*(br-bl) + 32*b; int score= (ny*ny*(b2 + t2 - 2*c2) + 4*ny*(b2 - t2) + 32*c2 + 512)>>10; int i; if((nx&3)==0 && (ny&3)==0) continue; score += (mv_penalty[4*mx + nx - pred_x] + mv_penalty[4*my + ny - pred_y])*penalty_factor; // if(nx&1) score-=1024*c->penalty_factor; // if(ny&1) score-=1024*c->penalty_factor; for(i=0; i<8; i++){ if(score < best[i]){ memmove(&best[i+1], &best[i], sizeof(int)*(7-i)); memmove(&best_pos[i+1][0], &best_pos[i][0], sizeof(int)*2*(7-i)); best[i]= score; best_pos[i][0]= nx + 4*mx; best_pos[i][1]= ny + 4*my; break; } } } } }else{ int tl; //FIXME this could overflow (unlikely though) const int cx = 4*(r - l); const int cx2= r + l - 2*c; const int cy = 4*(b - t); const int cy2= b + t - 2*c; int cxy; if(map[(index-(1<<ME_MAP_SHIFT)-1)&(ME_MAP_SIZE-1)] == (my<<ME_MAP_MV_BITS) + mx + map_generation && 0){ //FIXME tl= score_map[(index-(1<<ME_MAP_SHIFT)-1)&(ME_MAP_SIZE-1)]; }else{ tl= cmp(s, mx-1, my-1, 0, 0, size, h, ref_index, src_index, cmpf, chroma_cmpf, flags);//FIXME wrong if chroma me is different } cxy= 2*tl + (cx + cy)/4 - (cx2 + cy2) - 2*c; assert(16*cx2 + 4*cx + 32*c == 32*r); assert(16*cx2 - 4*cx + 32*c == 32*l); assert(16*cy2 + 4*cy + 32*c == 32*b); assert(16*cy2 - 4*cy + 32*c == 32*t); assert(16*cxy + 16*cy2 + 16*cx2 - 4*cy - 4*cx + 32*c == 32*tl); for(ny= -3; ny <= 3; ny++){ for(nx= -3; nx <= 3; nx++){ //FIXME this could overflow (unlikely though) int score= ny*nx*cxy + nx*nx*cx2 + ny*ny*cy2 + nx*cx + ny*cy + 32*c; //FIXME factor int i; if((nx&3)==0 && (ny&3)==0) continue; score += 32*(mv_penalty[4*mx + nx - pred_x] + mv_penalty[4*my + ny - pred_y])*penalty_factor; // if(nx&1) score-=32*c->penalty_factor; // if(ny&1) score-=32*c->penalty_factor; for(i=0; i<8; i++){ if(score < best[i]){ memmove(&best[i+1], &best[i], sizeof(int)*(7-i)); memmove(&best_pos[i+1][0], &best_pos[i][0], sizeof(int)*2*(7-i)); best[i]= score; best_pos[i][0]= nx + 4*mx; best_pos[i][1]= ny + 4*my; break; } } } } } for(i=0; i<subpel_quality; i++){ nx= best_pos[i][0]; ny= best_pos[i][1]; CHECK_QUARTER_MV(nx&3, ny&3, nx>>2, ny>>2) } assert(bx >= xmin*4 && bx <= xmax*4 && by >= ymin*4 && by <= ymax*4); *mx_ptr = bx; *my_ptr = by; }else{ *mx_ptr =4*mx; *my_ptr =4*my; } return dmin; } #define CHECK_MV(x,y)\ {\ const unsigned key = ((y)<<ME_MAP_MV_BITS) + (x) + map_generation;\ const int index= (((y)<<ME_MAP_SHIFT) + (x))&(ME_MAP_SIZE-1);\ assert((x) >= xmin);\ assert((x) <= xmax);\ assert((y) >= ymin);\ assert((y) <= ymax);\ /*printf("check_mv %d %d\n", x, y);*/\ if(map[index]!=key){\ d= cmp(s, x, y, 0, 0, size, h, ref_index, src_index, cmpf, chroma_cmpf, flags);\ map[index]= key;\ score_map[index]= d;\ d += (mv_penalty[((x)<<shift)-pred_x] + mv_penalty[((y)<<shift)-pred_y])*penalty_factor;\ /*printf("score:%d\n", d);*/\ COPY3_IF_LT(dmin, d, best[0], x, best[1], y)\ }\ } #define CHECK_CLIPPED_MV(ax,ay)\ {\ const int Lx= ax;\ const int Ly= ay;\ const int Lx2= FFMAX(xmin, FFMIN(Lx, xmax));\ const int Ly2= FFMAX(ymin, FFMIN(Ly, ymax));\ CHECK_MV(Lx2, Ly2)\ } #define CHECK_MV_DIR(x,y,new_dir)\ {\ const unsigned key = ((y)<<ME_MAP_MV_BITS) + (x) + map_generation;\ const int index= (((y)<<ME_MAP_SHIFT) + (x))&(ME_MAP_SIZE-1);\ /*printf("check_mv_dir %d %d %d\n", x, y, new_dir);*/\ if(map[index]!=key){\ d= cmp(s, x, y, 0, 0, size, h, ref_index, src_index, cmpf, chroma_cmpf, flags);\ map[index]= key;\ score_map[index]= d;\ d += (mv_penalty[((x)<<shift)-pred_x] + mv_penalty[((y)<<shift)-pred_y])*penalty_factor;\ /*printf("score:%d\n", d);*/\ if(d<dmin){\ best[0]=x;\ best[1]=y;\ dmin=d;\ next_dir= new_dir;\ }\ }\ } #define check(x,y,S,v)\ if( (x)<(xmin<<(S)) ) printf("%d %d %d %d %d xmin" #v, xmin, (x), (y), s->mb_x, s->mb_y);\ if( (x)>(xmax<<(S)) ) printf("%d %d %d %d %d xmax" #v, xmax, (x), (y), s->mb_x, s->mb_y);\ if( (y)<(ymin<<(S)) ) printf("%d %d %d %d %d ymin" #v, ymin, (x), (y), s->mb_x, s->mb_y);\ if( (y)>(ymax<<(S)) ) printf("%d %d %d %d %d ymax" #v, ymax, (x), (y), s->mb_x, s->mb_y);\ #define LOAD_COMMON2\ uint32_t *map= c->map;\ const int qpel= flags&FLAG_QPEL;\ const int shift= 1+qpel;\ static av_always_inline int small_diamond_search(MpegEncContext * s, int *best, int dmin, int src_index, int ref_index, int const penalty_factor, int size, int h, int flags) { MotionEstContext * const c= &s->me; me_cmp_func cmpf, chroma_cmpf; int next_dir=-1; LOAD_COMMON LOAD_COMMON2 unsigned map_generation = c->map_generation; cmpf= s->dsp.me_cmp[size]; chroma_cmpf= s->dsp.me_cmp[size+1]; { /* ensure that the best point is in the MAP as h/qpel refinement needs it */ const unsigned key = (best[1]<<ME_MAP_MV_BITS) + best[0] + map_generation; const int index= ((best[1]<<ME_MAP_SHIFT) + best[0])&(ME_MAP_SIZE-1); if(map[index]!=key){ //this will be executed only very rarey score_map[index]= cmp(s, best[0], best[1], 0, 0, size, h, ref_index, src_index, cmpf, chroma_cmpf, flags); map[index]= key; } } for(;;){ int d; const int dir= next_dir; const int x= best[0]; const int y= best[1]; next_dir=-1; //printf("%d", dir); if(dir!=2 && x>xmin) CHECK_MV_DIR(x-1, y , 0) if(dir!=3 && y>ymin) CHECK_MV_DIR(x , y-1, 1) if(dir!=0 && x<xmax) CHECK_MV_DIR(x+1, y , 2) if(dir!=1 && y<ymax) CHECK_MV_DIR(x , y+1, 3) if(next_dir==-1){ return dmin; } } } static int funny_diamond_search(MpegEncContext * s, int *best, int dmin, int src_index, int ref_index, int const penalty_factor, int size, int h, int flags) { MotionEstContext * const c= &s->me; me_cmp_func cmpf, chroma_cmpf; int dia_size; LOAD_COMMON LOAD_COMMON2 unsigned map_generation = c->map_generation; cmpf= s->dsp.me_cmp[size]; chroma_cmpf= s->dsp.me_cmp[size+1]; for(dia_size=1; dia_size<=4; dia_size++){ int dir; const int x= best[0]; const int y= best[1]; if(dia_size&(dia_size-1)) continue; if( x + dia_size > xmax || x - dia_size < xmin || y + dia_size > ymax || y - dia_size < ymin) continue; for(dir= 0; dir<dia_size; dir+=2){ int d; CHECK_MV(x + dir , y + dia_size - dir); CHECK_MV(x + dia_size - dir, y - dir ); CHECK_MV(x - dir , y - dia_size + dir); CHECK_MV(x - dia_size + dir, y + dir ); } if(x!=best[0] || y!=best[1]) dia_size=0; } return dmin; } static int hex_search(MpegEncContext * s, int *best, int dmin, int src_index, int ref_index, int const penalty_factor, int size, int h, int flags, int dia_size) { MotionEstContext * const c= &s->me; me_cmp_func cmpf, chroma_cmpf; LOAD_COMMON LOAD_COMMON2 unsigned map_generation = c->map_generation; int x,y,d; const int dec= dia_size & (dia_size-1); cmpf= s->dsp.me_cmp[size]; chroma_cmpf= s->dsp.me_cmp[size+1]; for(;dia_size; dia_size= dec ? dia_size-1 : dia_size>>1){ do{ x= best[0]; y= best[1]; CHECK_CLIPPED_MV(x -dia_size , y); CHECK_CLIPPED_MV(x+ dia_size , y); CHECK_CLIPPED_MV(x+( dia_size>>1), y+dia_size); CHECK_CLIPPED_MV(x+( dia_size>>1), y-dia_size); if(dia_size>1){ CHECK_CLIPPED_MV(x+(-dia_size>>1), y+dia_size); CHECK_CLIPPED_MV(x+(-dia_size>>1), y-dia_size); } }while(best[0] != x || best[1] != y); } return dmin; } static int l2s_dia_search(MpegEncContext * s, int *best, int dmin, int src_index, int ref_index, int const penalty_factor, int size, int h, int flags) { MotionEstContext * const c= &s->me; me_cmp_func cmpf, chroma_cmpf; LOAD_COMMON LOAD_COMMON2 unsigned map_generation = c->map_generation; int x,y,i,d; int dia_size= c->dia_size&0xFF; const int dec= dia_size & (dia_size-1); static const int hex[8][2]={{-2, 0}, {-1,-1}, { 0,-2}, { 1,-1}, { 2, 0}, { 1, 1}, { 0, 2}, {-1, 1}}; cmpf= s->dsp.me_cmp[size]; chroma_cmpf= s->dsp.me_cmp[size+1]; for(; dia_size; dia_size= dec ? dia_size-1 : dia_size>>1){ do{ x= best[0]; y= best[1]; for(i=0; i<8; i++){ CHECK_CLIPPED_MV(x+hex[i][0]*dia_size, y+hex[i][1]*dia_size); } }while(best[0] != x || best[1] != y); } x= best[0]; y= best[1]; CHECK_CLIPPED_MV(x+1, y); CHECK_CLIPPED_MV(x, y+1); CHECK_CLIPPED_MV(x-1, y); CHECK_CLIPPED_MV(x, y-1); return dmin; } static int umh_search(MpegEncContext * s, int *best, int dmin, int src_index, int ref_index, int const penalty_factor, int size, int h, int flags) { MotionEstContext * const c= &s->me; me_cmp_func cmpf, chroma_cmpf; LOAD_COMMON LOAD_COMMON2 unsigned map_generation = c->map_generation; int x,y,x2,y2, i, j, d; const int dia_size= c->dia_size&0xFE; static const int hex[16][2]={{-4,-2}, {-4,-1}, {-4, 0}, {-4, 1}, {-4, 2}, { 4,-2}, { 4,-1}, { 4, 0}, { 4, 1}, { 4, 2}, {-2, 3}, { 0, 4}, { 2, 3}, {-2,-3}, { 0,-4}, { 2,-3},}; cmpf= s->dsp.me_cmp[size]; chroma_cmpf= s->dsp.me_cmp[size+1]; x= best[0]; y= best[1]; for(x2=FFMAX(x-dia_size+1, xmin); x2<=FFMIN(x+dia_size-1,xmax); x2+=2){ CHECK_MV(x2, y); } for(y2=FFMAX(y-dia_size/2+1, ymin); y2<=FFMIN(y+dia_size/2-1,ymax); y2+=2){ CHECK_MV(x, y2); } x= best[0]; y= best[1]; for(y2=FFMAX(y-2, ymin); y2<=FFMIN(y+2,ymax); y2++){ for(x2=FFMAX(x-2, xmin); x2<=FFMIN(x+2,xmax); x2++){ CHECK_MV(x2, y2); } } //FIXME prevent the CLIP stuff for(j=1; j<=dia_size/4; j++){ for(i=0; i<16; i++){ CHECK_CLIPPED_MV(x+hex[i][0]*j, y+hex[i][1]*j); } } return hex_search(s, best, dmin, src_index, ref_index, penalty_factor, size, h, flags, 2); } static int full_search(MpegEncContext * s, int *best, int dmin, int src_index, int ref_index, int const penalty_factor, int size, int h, int flags) { MotionEstContext * const c= &s->me; me_cmp_func cmpf, chroma_cmpf; LOAD_COMMON LOAD_COMMON2 unsigned map_generation = c->map_generation; int x,y, d; const int dia_size= c->dia_size&0xFF; cmpf= s->dsp.me_cmp[size]; chroma_cmpf= s->dsp.me_cmp[size+1]; for(y=FFMAX(-dia_size, ymin); y<=FFMIN(dia_size,ymax); y++){ for(x=FFMAX(-dia_size, xmin); x<=FFMIN(dia_size,xmax); x++){ CHECK_MV(x, y); } } x= best[0]; y= best[1]; d= dmin; CHECK_CLIPPED_MV(x , y); CHECK_CLIPPED_MV(x+1, y); CHECK_CLIPPED_MV(x, y+1); CHECK_CLIPPED_MV(x-1, y); CHECK_CLIPPED_MV(x, y-1); best[0]= x; best[1]= y; return d; } #define SAB_CHECK_MV(ax,ay)\ {\ const unsigned key = ((ay)<<ME_MAP_MV_BITS) + (ax) + map_generation;\ const int index= (((ay)<<ME_MAP_SHIFT) + (ax))&(ME_MAP_SIZE-1);\ /*printf("sab check %d %d\n", ax, ay);*/\ if(map[index]!=key){\ d= cmp(s, ax, ay, 0, 0, size, h, ref_index, src_index, cmpf, chroma_cmpf, flags);\ map[index]= key;\ score_map[index]= d;\ d += (mv_penalty[((ax)<<shift)-pred_x] + mv_penalty[((ay)<<shift)-pred_y])*penalty_factor;\ /*printf("score: %d\n", d);*/\ if(d < minima[minima_count-1].height){\ int j=0;\ \ while(d >= minima[j].height) j++;\ \ memmove(&minima [j+1], &minima [j], (minima_count - j - 1)*sizeof(Minima));\ \ minima[j].checked= 0;\ minima[j].height= d;\ minima[j].x= ax;\ minima[j].y= ay;\ \ i=-1;\ continue;\ }\ }\ } #define MAX_SAB_SIZE ME_MAP_SIZE static int sab_diamond_search(MpegEncContext * s, int *best, int dmin, int src_index, int ref_index, int const penalty_factor, int size, int h, int flags) { MotionEstContext * const c= &s->me; me_cmp_func cmpf, chroma_cmpf; Minima minima[MAX_SAB_SIZE]; const int minima_count= FFABS(c->dia_size); int i, j; LOAD_COMMON LOAD_COMMON2 unsigned map_generation = c->map_generation; cmpf= s->dsp.me_cmp[size]; chroma_cmpf= s->dsp.me_cmp[size+1]; /*Note j<MAX_SAB_SIZE is needed if MAX_SAB_SIZE < ME_MAP_SIZE as j can become larger due to MVs overflowing their ME_MAP_MV_BITS bits space in map */ for(j=i=0; i<ME_MAP_SIZE && j<MAX_SAB_SIZE; i++){ uint32_t key= map[i]; key += (1<<(ME_MAP_MV_BITS-1)) + (1<<(2*ME_MAP_MV_BITS-1)); if((key&((-1)<<(2*ME_MAP_MV_BITS))) != map_generation) continue; minima[j].height= score_map[i]; minima[j].x= key & ((1<<ME_MAP_MV_BITS)-1); key>>=ME_MAP_MV_BITS; minima[j].y= key & ((1<<ME_MAP_MV_BITS)-1); minima[j].x-= (1<<(ME_MAP_MV_BITS-1)); minima[j].y-= (1<<(ME_MAP_MV_BITS-1)); // all entries in map should be in range except if the mv overflows their ME_MAP_MV_BITS bits space if( minima[j].x > xmax || minima[j].x < xmin || minima[j].y > ymax || minima[j].y < ymin) continue; minima[j].checked=0; if(minima[j].x || minima[j].y) minima[j].height+= (mv_penalty[((minima[j].x)<<shift)-pred_x] + mv_penalty[((minima[j].y)<<shift)-pred_y])*penalty_factor; j++; } qsort(minima, j, sizeof(Minima), minima_cmp); for(; j<minima_count; j++){ minima[j].height=256*256*256*64; minima[j].checked=0; minima[j].x= minima[j].y=0; } for(i=0; i<minima_count; i++){ const int x= minima[i].x; const int y= minima[i].y; int d; if(minima[i].checked) continue; if( x >= xmax || x <= xmin || y >= ymax || y <= ymin) continue; SAB_CHECK_MV(x-1, y) SAB_CHECK_MV(x+1, y) SAB_CHECK_MV(x , y-1) SAB_CHECK_MV(x , y+1) minima[i].checked= 1; } best[0]= minima[0].x; best[1]= minima[0].y; dmin= minima[0].height; if( best[0] < xmax && best[0] > xmin && best[1] < ymax && best[1] > ymin){ int d; //ensure that the refernece samples for hpel refinement are in the map CHECK_MV(best[0]-1, best[1]) CHECK_MV(best[0]+1, best[1]) CHECK_MV(best[0], best[1]-1) CHECK_MV(best[0], best[1]+1) } return dmin; } static int var_diamond_search(MpegEncContext * s, int *best, int dmin, int src_index, int ref_index, int const penalty_factor, int size, int h, int flags) { MotionEstContext * const c= &s->me; me_cmp_func cmpf, chroma_cmpf; int dia_size; LOAD_COMMON LOAD_COMMON2 unsigned map_generation = c->map_generation; cmpf= s->dsp.me_cmp[size]; chroma_cmpf= s->dsp.me_cmp[size+1]; for(dia_size=1; dia_size<=c->dia_size; dia_size++){ int dir, start, end; const int x= best[0]; const int y= best[1]; start= FFMAX(0, y + dia_size - ymax); end = FFMIN(dia_size, xmax - x + 1); for(dir= start; dir<end; dir++){ int d; //check(x + dir,y + dia_size - dir,0, a0) CHECK_MV(x + dir , y + dia_size - dir); } start= FFMAX(0, x + dia_size - xmax); end = FFMIN(dia_size, y - ymin + 1); for(dir= start; dir<end; dir++){ int d; //check(x + dia_size - dir, y - dir,0, a1) CHECK_MV(x + dia_size - dir, y - dir ); } start= FFMAX(0, -y + dia_size + ymin ); end = FFMIN(dia_size, x - xmin + 1); for(dir= start; dir<end; dir++){ int d; //check(x - dir,y - dia_size + dir,0, a2) CHECK_MV(x - dir , y - dia_size + dir); } start= FFMAX(0, -x + dia_size + xmin ); end = FFMIN(dia_size, ymax - y + 1); for(dir= start; dir<end; dir++){ int d; //check(x - dia_size + dir, y + dir,0, a3) CHECK_MV(x - dia_size + dir, y + dir ); } if(x!=best[0] || y!=best[1]) dia_size=0; } return dmin; } static av_always_inline int diamond_search(MpegEncContext * s, int *best, int dmin, int src_index, int ref_index, int const penalty_factor, int size, int h, int flags){ MotionEstContext * const c= &s->me; if(c->dia_size==-1) return funny_diamond_search(s, best, dmin, src_index, ref_index, penalty_factor, size, h, flags); else if(c->dia_size<-1) return sab_diamond_search(s, best, dmin, src_index, ref_index, penalty_factor, size, h, flags); else if(c->dia_size<2) return small_diamond_search(s, best, dmin, src_index, ref_index, penalty_factor, size, h, flags); else if(c->dia_size>1024) return full_search(s, best, dmin, src_index, ref_index, penalty_factor, size, h, flags); else if(c->dia_size>768) return umh_search(s, best, dmin, src_index, ref_index, penalty_factor, size, h, flags); else if(c->dia_size>512) return hex_search(s, best, dmin, src_index, ref_index, penalty_factor, size, h, flags, c->dia_size&0xFF); else if(c->dia_size>256) return l2s_dia_search(s, best, dmin, src_index, ref_index, penalty_factor, size, h, flags); else return var_diamond_search(s, best, dmin, src_index, ref_index, penalty_factor, size, h, flags); } /** @param P a list of candidate mvs to check before starting the iterative search. If one of the candidates is close to the optimal mv, then it takes fewer iterations. And it increases the chance that we find the optimal mv. */ static av_always_inline int epzs_motion_search_internal(MpegEncContext * s, int *mx_ptr, int *my_ptr, int P[10][2], int src_index, int ref_index, int16_t (*last_mv)[2], int ref_mv_scale, int flags, int size, int h) { MotionEstContext * const c= &s->me; int best[2]={0, 0}; /**< x and y coordinates of the best motion vector. i.e. the difference between the position of the block currently being encoded and the position of the block chosen to predict it from. */ int d; ///< the score (cmp + penalty) of any given mv int dmin; /**< the best value of d, i.e. the score corresponding to the mv stored in best[]. */ unsigned map_generation; int penalty_factor; const int ref_mv_stride= s->mb_stride; //pass as arg FIXME const int ref_mv_xy= s->mb_x + s->mb_y*ref_mv_stride; //add to last_mv beforepassing FIXME me_cmp_func cmpf, chroma_cmpf; LOAD_COMMON LOAD_COMMON2 if(c->pre_pass){ penalty_factor= c->pre_penalty_factor; cmpf= s->dsp.me_pre_cmp[size]; chroma_cmpf= s->dsp.me_pre_cmp[size+1]; }else{ penalty_factor= c->penalty_factor; cmpf= s->dsp.me_cmp[size]; chroma_cmpf= s->dsp.me_cmp[size+1]; } map_generation= update_map_generation(c); assert(cmpf); dmin= cmp(s, 0, 0, 0, 0, size, h, ref_index, src_index, cmpf, chroma_cmpf, flags); map[0]= map_generation; score_map[0]= dmin; //FIXME precalc first term below? if((s->pict_type == AV_PICTURE_TYPE_B && !(c->flags & FLAG_DIRECT)) || s->flags&CODEC_FLAG_MV0) dmin += (mv_penalty[pred_x] + mv_penalty[pred_y])*penalty_factor; /* first line */ if (s->first_slice_line) { CHECK_MV(P_LEFT[0]>>shift, P_LEFT[1]>>shift) CHECK_CLIPPED_MV((last_mv[ref_mv_xy][0]*ref_mv_scale + (1<<15))>>16, (last_mv[ref_mv_xy][1]*ref_mv_scale + (1<<15))>>16) }else{ if(dmin<((h*h*s->avctx->mv0_threshold)>>8) && ( P_LEFT[0] |P_LEFT[1] |P_TOP[0] |P_TOP[1] |P_TOPRIGHT[0]|P_TOPRIGHT[1])==0){ *mx_ptr= 0; *my_ptr= 0; c->skip=1; return dmin; } CHECK_MV( P_MEDIAN[0] >>shift , P_MEDIAN[1] >>shift) CHECK_CLIPPED_MV((P_MEDIAN[0]>>shift) , (P_MEDIAN[1]>>shift)-1) CHECK_CLIPPED_MV((P_MEDIAN[0]>>shift) , (P_MEDIAN[1]>>shift)+1) CHECK_CLIPPED_MV((P_MEDIAN[0]>>shift)-1, (P_MEDIAN[1]>>shift) ) CHECK_CLIPPED_MV((P_MEDIAN[0]>>shift)+1, (P_MEDIAN[1]>>shift) ) CHECK_CLIPPED_MV((last_mv[ref_mv_xy][0]*ref_mv_scale + (1<<15))>>16, (last_mv[ref_mv_xy][1]*ref_mv_scale + (1<<15))>>16) CHECK_MV(P_LEFT[0] >>shift, P_LEFT[1] >>shift) CHECK_MV(P_TOP[0] >>shift, P_TOP[1] >>shift) CHECK_MV(P_TOPRIGHT[0]>>shift, P_TOPRIGHT[1]>>shift) } if(dmin>h*h*4){ if(c->pre_pass){ CHECK_CLIPPED_MV((last_mv[ref_mv_xy-1][0]*ref_mv_scale + (1<<15))>>16, (last_mv[ref_mv_xy-1][1]*ref_mv_scale + (1<<15))>>16) if(!s->first_slice_line) CHECK_CLIPPED_MV((last_mv[ref_mv_xy-ref_mv_stride][0]*ref_mv_scale + (1<<15))>>16, (last_mv[ref_mv_xy-ref_mv_stride][1]*ref_mv_scale + (1<<15))>>16) }else{ CHECK_CLIPPED_MV((last_mv[ref_mv_xy+1][0]*ref_mv_scale + (1<<15))>>16, (last_mv[ref_mv_xy+1][1]*ref_mv_scale + (1<<15))>>16) if(s->mb_y+1<s->end_mb_y) //FIXME replace at least with last_slice_line CHECK_CLIPPED_MV((last_mv[ref_mv_xy+ref_mv_stride][0]*ref_mv_scale + (1<<15))>>16, (last_mv[ref_mv_xy+ref_mv_stride][1]*ref_mv_scale + (1<<15))>>16) } } if(c->avctx->last_predictor_count){ const int count= c->avctx->last_predictor_count; const int xstart= FFMAX(0, s->mb_x - count); const int ystart= FFMAX(0, s->mb_y - count); const int xend= FFMIN(s->mb_width , s->mb_x + count + 1); const int yend= FFMIN(s->mb_height, s->mb_y + count + 1); int mb_y; for(mb_y=ystart; mb_y<yend; mb_y++){ int mb_x; for(mb_x=xstart; mb_x<xend; mb_x++){ const int xy= mb_x + 1 + (mb_y + 1)*ref_mv_stride; int mx= (last_mv[xy][0]*ref_mv_scale + (1<<15))>>16; int my= (last_mv[xy][1]*ref_mv_scale + (1<<15))>>16; if(mx>xmax || mx<xmin || my>ymax || my<ymin) continue; CHECK_MV(mx,my) } } } //check(best[0],best[1],0, b0) dmin= diamond_search(s, best, dmin, src_index, ref_index, penalty_factor, size, h, flags); //check(best[0],best[1],0, b1) *mx_ptr= best[0]; *my_ptr= best[1]; // printf("%d %d %d \n", best[0], best[1], dmin); return dmin; } //this function is dedicated to the braindamaged gcc int ff_epzs_motion_search(MpegEncContext * s, int *mx_ptr, int *my_ptr, int P[10][2], int src_index, int ref_index, int16_t (*last_mv)[2], int ref_mv_scale, int size, int h) { MotionEstContext * const c= &s->me; //FIXME convert other functions in the same way if faster if(c->flags==0 && h==16 && size==0){ return epzs_motion_search_internal(s, mx_ptr, my_ptr, P, src_index, ref_index, last_mv, ref_mv_scale, 0, 0, 16); // case FLAG_QPEL: // return epzs_motion_search_internal(s, mx_ptr, my_ptr, P, src_index, ref_index, last_mv, ref_mv_scale, FLAG_QPEL); }else{ return epzs_motion_search_internal(s, mx_ptr, my_ptr, P, src_index, ref_index, last_mv, ref_mv_scale, c->flags, size, h); } } static int epzs_motion_search4(MpegEncContext * s, int *mx_ptr, int *my_ptr, int P[10][2], int src_index, int ref_index, int16_t (*last_mv)[2], int ref_mv_scale) { MotionEstContext * const c= &s->me; int best[2]={0, 0}; int d, dmin; unsigned map_generation; const int penalty_factor= c->penalty_factor; const int size=1; const int h=8; const int ref_mv_stride= s->mb_stride; const int ref_mv_xy= s->mb_x + s->mb_y *ref_mv_stride; me_cmp_func cmpf, chroma_cmpf; LOAD_COMMON int flags= c->flags; LOAD_COMMON2 cmpf= s->dsp.me_cmp[size]; chroma_cmpf= s->dsp.me_cmp[size+1]; map_generation= update_map_generation(c); dmin = 1000000; //printf("%d %d %d %d //",xmin, ymin, xmax, ymax); /* first line */ if (s->first_slice_line) { CHECK_MV(P_LEFT[0]>>shift, P_LEFT[1]>>shift) CHECK_CLIPPED_MV((last_mv[ref_mv_xy][0]*ref_mv_scale + (1<<15))>>16, (last_mv[ref_mv_xy][1]*ref_mv_scale + (1<<15))>>16) CHECK_MV(P_MV1[0]>>shift, P_MV1[1]>>shift) }else{ CHECK_MV(P_MV1[0]>>shift, P_MV1[1]>>shift) //FIXME try some early stop CHECK_MV(P_MEDIAN[0]>>shift, P_MEDIAN[1]>>shift) CHECK_MV(P_LEFT[0]>>shift, P_LEFT[1]>>shift) CHECK_MV(P_TOP[0]>>shift, P_TOP[1]>>shift) CHECK_MV(P_TOPRIGHT[0]>>shift, P_TOPRIGHT[1]>>shift) CHECK_CLIPPED_MV((last_mv[ref_mv_xy][0]*ref_mv_scale + (1<<15))>>16, (last_mv[ref_mv_xy][1]*ref_mv_scale + (1<<15))>>16) } if(dmin>64*4){ CHECK_CLIPPED_MV((last_mv[ref_mv_xy+1][0]*ref_mv_scale + (1<<15))>>16, (last_mv[ref_mv_xy+1][1]*ref_mv_scale + (1<<15))>>16) if(s->mb_y+1<s->end_mb_y) //FIXME replace at least with last_slice_line CHECK_CLIPPED_MV((last_mv[ref_mv_xy+ref_mv_stride][0]*ref_mv_scale + (1<<15))>>16, (last_mv[ref_mv_xy+ref_mv_stride][1]*ref_mv_scale + (1<<15))>>16) } dmin= diamond_search(s, best, dmin, src_index, ref_index, penalty_factor, size, h, flags); *mx_ptr= best[0]; *my_ptr= best[1]; // printf("%d %d %d \n", best[0], best[1], dmin); return dmin; } //try to merge with above FIXME (needs PSNR test) static int epzs_motion_search2(MpegEncContext * s, int *mx_ptr, int *my_ptr, int P[10][2], int src_index, int ref_index, int16_t (*last_mv)[2], int ref_mv_scale) { MotionEstContext * const c= &s->me; int best[2]={0, 0}; int d, dmin; unsigned map_generation; const int penalty_factor= c->penalty_factor; const int size=0; //FIXME pass as arg const int h=8; const int ref_mv_stride= s->mb_stride; const int ref_mv_xy= s->mb_x + s->mb_y *ref_mv_stride; me_cmp_func cmpf, chroma_cmpf; LOAD_COMMON int flags= c->flags; LOAD_COMMON2 cmpf= s->dsp.me_cmp[size]; chroma_cmpf= s->dsp.me_cmp[size+1]; map_generation= update_map_generation(c); dmin = 1000000; //printf("%d %d %d %d //",xmin, ymin, xmax, ymax); /* first line */ if (s->first_slice_line) { CHECK_MV(P_LEFT[0]>>shift, P_LEFT[1]>>shift) CHECK_CLIPPED_MV((last_mv[ref_mv_xy][0]*ref_mv_scale + (1<<15))>>16, (last_mv[ref_mv_xy][1]*ref_mv_scale + (1<<15))>>16) CHECK_MV(P_MV1[0]>>shift, P_MV1[1]>>shift) }else{ CHECK_MV(P_MV1[0]>>shift, P_MV1[1]>>shift) //FIXME try some early stop CHECK_MV(P_MEDIAN[0]>>shift, P_MEDIAN[1]>>shift) CHECK_MV(P_LEFT[0]>>shift, P_LEFT[1]>>shift) CHECK_MV(P_TOP[0]>>shift, P_TOP[1]>>shift) CHECK_MV(P_TOPRIGHT[0]>>shift, P_TOPRIGHT[1]>>shift) CHECK_CLIPPED_MV((last_mv[ref_mv_xy][0]*ref_mv_scale + (1<<15))>>16, (last_mv[ref_mv_xy][1]*ref_mv_scale + (1<<15))>>16) } if(dmin>64*4){ CHECK_CLIPPED_MV((last_mv[ref_mv_xy+1][0]*ref_mv_scale + (1<<15))>>16, (last_mv[ref_mv_xy+1][1]*ref_mv_scale + (1<<15))>>16) if(s->mb_y+1<s->end_mb_y) //FIXME replace at least with last_slice_line CHECK_CLIPPED_MV((last_mv[ref_mv_xy+ref_mv_stride][0]*ref_mv_scale + (1<<15))>>16, (last_mv[ref_mv_xy+ref_mv_stride][1]*ref_mv_scale + (1<<15))>>16) } dmin= diamond_search(s, best, dmin, src_index, ref_index, penalty_factor, size, h, flags); *mx_ptr= best[0]; *my_ptr= best[1]; // printf("%d %d %d \n", best[0], best[1], dmin); return dmin; }
36.438739
141
0.532796
[ "vector" ]
b40fc73c3f52adbfdac935fc83e82a420367b9c7
7,443
cpp
C++
src/sysc/scc/value_registry.cpp
kopinions/SystemC-Components
ce53e48834893c28b4225f4315680937f5af6714
[ "Apache-2.0" ]
null
null
null
src/sysc/scc/value_registry.cpp
kopinions/SystemC-Components
ce53e48834893c28b4225f4315680937f5af6714
[ "Apache-2.0" ]
null
null
null
src/sysc/scc/value_registry.cpp
kopinions/SystemC-Components
ce53e48834893c28b4225f4315680937f5af6714
[ "Apache-2.0" ]
null
null
null
/* * trace_file.cpp * * Created on: 30.12.2018 * Author: eyck */ #include <cstring> #include <scc/value_registry.h> #include <sstream> #include <string> #include <sysc/datatypes/fx/sc_fxnum.h> #include <sysc/datatypes/fx/sc_fxval.h> #include <unordered_map> using namespace sc_core; using namespace scc; auto operator<<(std::ostream& os, const sc_event& evt) -> std::ostream& { #if SYSTEMC_VERSION >= 20181013 os << evt.triggered(); #endif return os; } #if SC_VERSION_MAJOR <= 2 && SC_VERSION_MINOR <= 3 && SC_VERSION_PATCH < 2 #define OVERRIDE #else #define OVERRIDE override #endif class SC_API value_registry_impl : public sc_trace_file { public: // Constructor value_registry_impl() = default; auto get_mod4name(const std::string& name) const -> sc_module* { sc_module* mod = nullptr; sc_object* obj = sc_find_object(name.c_str()); if(obj) return mod; auto pos = name.length() - 1; do { pos = name.find_last_of('.', pos); mod = dynamic_cast<sc_module*>(sc_find_object(name.substr(0, pos).c_str())); } while(pos > 0 && mod == nullptr); return mod; } #define DECL_TRACE_METHOD_A(tp) \ void trace(const tp& object, const std::string& name) OVERRIDE { \ if(sc_core::sc_find_object(name.c_str()) != nullptr) { \ if(sc_module* mod = get_mod4name(name)) { \ sc_get_curr_simcontext()->hierarchy_push(mod); \ auto* o = new sc_variable_t<tp>(name, object); \ sc_get_curr_simcontext()->hierarchy_pop(); \ holder[name] = o; \ } \ } \ } #define DECL_TRACE_METHOD_B(tp) \ void trace(const tp& object, const std::string& name, int width) OVERRIDE { \ if(sc_core::sc_find_object(name.c_str()) != nullptr) { \ if(sc_module* mod = get_mod4name(name)) { \ sc_get_curr_simcontext()->hierarchy_push(mod); \ auto* o = new sc_variable_masked_t<tp>(name, object, width); \ sc_get_curr_simcontext()->hierarchy_pop(); \ holder[name] = o; \ } \ } \ } // DECL_TRACE_METHOD_A( bool ) void trace(const bool& object, const std::string& name) override { if(sc_core::sc_find_object(name.c_str()) == nullptr) { if(sc_module* mod = get_mod4name(name)) { sc_get_curr_simcontext()->hierarchy_push(mod); auto* o = new sc_variable_t<bool>(name.substr(strlen(mod->name()) + 1), object); sc_get_curr_simcontext()->hierarchy_pop(); holder[name] = o; } } } DECL_TRACE_METHOD_A(sc_event) // NOLINT DECL_TRACE_METHOD_A(sc_time) DECL_TRACE_METHOD_A(sc_dt::sc_bit) DECL_TRACE_METHOD_A(sc_dt::sc_logic) DECL_TRACE_METHOD_B(unsigned char) DECL_TRACE_METHOD_B(unsigned short) DECL_TRACE_METHOD_B(unsigned int) DECL_TRACE_METHOD_B(unsigned long) DECL_TRACE_METHOD_B(char) DECL_TRACE_METHOD_B(short) DECL_TRACE_METHOD_B(int) DECL_TRACE_METHOD_B(long) DECL_TRACE_METHOD_B(sc_dt::int64) DECL_TRACE_METHOD_B(sc_dt::uint64) DECL_TRACE_METHOD_A(float) DECL_TRACE_METHOD_A(double) DECL_TRACE_METHOD_A(sc_dt::sc_int_base) DECL_TRACE_METHOD_A(sc_dt::sc_uint_base) DECL_TRACE_METHOD_A(sc_dt::sc_signed) DECL_TRACE_METHOD_A(sc_dt::sc_unsigned) DECL_TRACE_METHOD_A(sc_dt::sc_fxval) DECL_TRACE_METHOD_A(sc_dt::sc_fxval_fast) DECL_TRACE_METHOD_A(sc_dt::sc_fxnum) DECL_TRACE_METHOD_A(sc_dt::sc_fxnum_fast) DECL_TRACE_METHOD_A(sc_dt::sc_bv_base) DECL_TRACE_METHOD_A(sc_dt::sc_lv_base) #undef DECL_TRACE_METHOD_A #undef DECL_TRACE_METHOD_B // Trace an enumerated object - where possible output the enumeration // literals in the trace file. Enum literals is a null terminated array // of null terminated char* literal strings. void trace(const unsigned int& object, const std::string& name, const char** enum_literals) override {} // Output a comment to the trace file void write_comment(const std::string& comment) override {} // Set the amount of space before next column // (For most formats this does nothing) // void space( int n ); // Also trace transitions between delta cycles if flag is true. // void delta_cycles( bool flag ); // Set time unit. void set_time_unit(double v, sc_time_unit tu) override{}; // Write trace info for cycle void cycle(bool delta_cycle) override {} // Helper for event tracing auto event_trigger_stamp(const sc_event& event) const -> const sc_dt::uint64& { return dummy; } // Flush results and close file ~value_registry_impl() override { for(auto kv : holder) delete kv.second; } std::unordered_map<std::string, sc_variable*> holder; sc_dt::uint64 dummy = 0; }; value_registry::value_registry() : tracer_base(sc_core::sc_module_name(sc_core::sc_gen_unique_name("value_registrar", true))) { trf = new value_registry_impl(); } scc::value_registry::~value_registry() { delete dynamic_cast<value_registry_impl*>(trf); } auto scc::value_registry::get_names() const -> std::vector<std::string> { auto& holder = dynamic_cast<value_registry_impl*>(trf)->holder; std::vector<std::string> keys; keys.reserve(holder.size()); for(auto kv : holder) keys.push_back(kv.first); return keys; } auto scc::value_registry::get_value(std::string name) const -> const sc_variable* { auto* reg = dynamic_cast<value_registry_impl*>(trf); auto it = reg->holder.find(name); if(it != reg->holder.end()) { std::cerr << "returning value holder ptr" << std::endl; return it->second; } std::cerr << "returning nullptr" << std::endl; return nullptr; } void scc::value_registry::end_of_elaboration() { for(auto o : sc_get_top_level_objects(sc_curr_simcontext)) descend(o, true); }
40.672131
120
0.530566
[ "object", "vector" ]
b41008e65d8d6e2ee5fc0a0e5f9bec504e873833
14,076
cpp
C++
tesseract_motion_planners/src/trajopt_ifopt/problem_generators/default_problem_generator.cpp
marip8/tesseract_planning
62d37d888376cd1277ebaf6dcf5e76cc7ad59318
[ "Apache-2.0", "BSD-2-Clause" ]
1
2022-02-28T13:22:28.000Z
2022-02-28T13:22:28.000Z
tesseract/tesseract_planning/tesseract_motion_planners/src/trajopt_ifopt/problem_generators/default_problem_generator.cpp
Levi-Armstrong/tesseract-1
33bccff4204c4682eaff57e2827b586f182ae5fe
[ "Apache-2.0", "BSD-2-Clause" ]
12
2019-06-04T19:04:12.000Z
2020-09-11T14:33:25.000Z
tesseract/tesseract_planning/tesseract_motion_planners/src/trajopt_ifopt/problem_generators/default_problem_generator.cpp
Levi-Armstrong/tesseract-1
33bccff4204c4682eaff57e2827b586f182ae5fe
[ "Apache-2.0", "BSD-2-Clause" ]
4
2018-07-25T15:16:52.000Z
2019-10-02T16:43:52.000Z
/** * @file default_problem_generator.cpp * @brief Generates a trajopt problem from a planner request * * @author Levi Armstrong * @date April 18, 2018 * @version TODO * @bug No known bugs * * @copyright Copyright (c) 2020, Southwest Research Institute * * @par License * Software License Agreement (Apache License) * @par * 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 * @par * 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 <tesseract_motion_planners/trajopt_ifopt/problem_generators/default_problem_generator.h> #include <tesseract_motion_planners/trajopt_ifopt/profile/trajopt_ifopt_default_composite_profile.h> #include <tesseract_motion_planners/trajopt_ifopt/profile/trajopt_ifopt_default_plan_profile.h> #include <tesseract_motion_planners/core/utils.h> #include <trajopt_ifopt/variable_sets/joint_position_variable.h> #include <tesseract_command_language/command_language.h> #include <trajopt_ifopt/trajopt_ifopt.h> #include <tesseract_motion_planners/planner_utils.h> namespace tesseract_planning { /// @todo: Restructure this into several smaller functions that are testable and easier to understand std::shared_ptr<TrajOptIfoptProblem> DefaultTrajoptIfoptProblemGenerator(const std::string& name, const PlannerRequest& request, const TrajOptIfoptPlanProfileMap& plan_profiles, const TrajOptIfoptCompositeProfileMap& composite_profiles) { // Create the problem auto problem = std::make_shared<TrajOptIfoptProblem>(); problem->env_state = request.env_state; problem->nlp = std::make_shared<ifopt::Problem>(); // Assume all the plan instructions have the same manipulator as the composite assert(!request.instructions.getManipulatorInfo().empty()); const ManipulatorInfo& composite_mi = request.instructions.getManipulatorInfo(); const std::string& manipulator = composite_mi.manipulator; auto kin = request.env->getManipulatorManager()->getFwdKinematicSolver(manipulator); auto inv_kin = request.env->getManipulatorManager()->getInvKinematicSolver(manipulator); assert(kin); problem->manip_fwd_kin = kin; problem->manip_inv_kin = inv_kin; // Get kinematics information tesseract_environment::Environment::ConstPtr env = request.env; tesseract_environment::AdjacencyMap map( env->getSceneGraph(), kin->getActiveLinkNames(), env->getCurrentState()->link_transforms); const std::vector<std::string>& active_links = map.getActiveLinkNames(); // Flatten input instructions auto instructions_flat = flattenProgram(request.instructions); auto seed_flat = flattenProgramToPattern(request.seed, request.instructions); // ---------------- // Setup variables // ---------------- // Create the vector of variables to be optimized Eigen::MatrixX2d joint_limits_eigen = kin->getLimits().joint_limits; // Create a variable for each instruction in the seed, setting to correct initial state for (std::size_t i = 0; i < seed_flat.size(); i++) { assert(isMoveInstruction(seed_flat[i])); auto var = std::make_shared<trajopt::JointPosition>( getJointPosition(seed_flat[i].get().cast_const<MoveInstruction>()->getWaypoint()), kin->getJointNames(), "Joint_Position_" + std::to_string(i)); var->SetBounds(joint_limits_eigen); problem->vars.push_back(var); problem->nlp->AddVariableSet(var); } // Store fixed steps std::vector<int> fixed_steps; // ---------------- // Setup start waypoint // ---------------- int start_index = 0; // If it has a start instruction then skip first instruction in instructions_flat int index = 0; std::string profile; Waypoint start_waypoint = NullWaypoint(); Instruction placeholder_instruction = NullInstruction(); const Instruction* start_instruction = nullptr; if (request.instructions.hasStartInstruction()) { assert(isPlanInstruction(request.instructions.getStartInstruction())); start_instruction = &(request.instructions.getStartInstruction()); if (isPlanInstruction(*start_instruction)) { const auto* temp = start_instruction->cast_const<PlanInstruction>(); assert(temp->isStart()); start_waypoint = temp->getWaypoint(); profile = temp->getProfile(); } else { throw std::runtime_error("DefaultTrajoptIfoptProblemGenerator: Unsupported start instruction type!"); } ++start_index; } // If not start instruction is given, take the current state else { Eigen::VectorXd current_jv = request.env_state->getJointValues(kin->getJointNames()); StateWaypoint swp(kin->getJointNames(), current_jv); MoveInstruction temp_move(swp, MoveInstructionType::START); placeholder_instruction = temp_move; start_instruction = &placeholder_instruction; start_waypoint = swp; } // ---------------- // Translate TCL for PlanInstructions // ---------------- // Transform plan instructions into trajopt cost and constraints for (int i = start_index; i < static_cast<int>(instructions_flat.size()); i++) { const auto& instruction = instructions_flat[static_cast<std::size_t>(i)].get(); if (isPlanInstruction(instruction)) { assert(isPlanInstruction(instruction)); const auto* plan_instruction = instruction.cast_const<PlanInstruction>(); // If plan instruction has manipulator information then use it over the one provided by the composite. ManipulatorInfo manip_info = composite_mi.getCombined(plan_instruction->getManipulatorInfo()); Eigen::Isometry3d tcp = request.env->findTCP(manip_info); assert(isCompositeInstruction(seed_flat[static_cast<std::size_t>(i)].get())); const auto* seed_composite = seed_flat[static_cast<std::size_t>(i)].get().cast_const<tesseract_planning::CompositeInstruction>(); auto interpolate_cnt = static_cast<int>(seed_composite->size()); std::string profile = getProfileString(plan_instruction->getProfile(), name, request.plan_profile_remapping); TrajOptIfoptPlanProfile::ConstPtr cur_plan_profile = getProfile<TrajOptIfoptPlanProfile>( profile, plan_profiles, std::make_shared<TrajOptIfoptDefaultPlanProfile>()); if (!cur_plan_profile) throw std::runtime_error("DefaultTrajoptIfoptProblemGenerator: Invalid profile"); if (plan_instruction->isLinear()) { if (isCartesianWaypoint(plan_instruction->getWaypoint())) { const auto* cur_wp = plan_instruction->getWaypoint().cast_const<tesseract_planning::CartesianWaypoint>(); Eigen::Isometry3d prev_pose = Eigen::Isometry3d::Identity(); if (isCartesianWaypoint(start_waypoint)) { prev_pose = *(start_waypoint.cast_const<Eigen::Isometry3d>()); } else if (isJointWaypoint(start_waypoint) || isStateWaypoint(start_waypoint)) { const Eigen::VectorXd& position = getJointPosition(start_waypoint); if (!kin->calcFwdKin(prev_pose, position)) throw std::runtime_error("DefaultTrajoptIfoptProblemGenerator: failed to solve forward kinematics!"); prev_pose = env->getCurrentState()->link_transforms.at(kin->getBaseLinkName()) * prev_pose * tcp; } else { throw std::runtime_error("DefaultTrajoptIfoptProblemGenerator: unknown waypoint type."); } tesseract_common::VectorIsometry3d poses = interpolate(prev_pose, *cur_wp, interpolate_cnt); // Add intermediate points with path costs and constraints for (std::size_t p = 1; p < poses.size() - 1; ++p) { /** @todo Write a path constraint for this*/ cur_plan_profile->apply(*problem, poses[p], *plan_instruction, composite_mi, active_links, index); ++index; } // Add final point with waypoint cur_plan_profile->apply(*problem, *cur_wp, *plan_instruction, composite_mi, active_links, index); ++index; } else if (isJointWaypoint(plan_instruction->getWaypoint()) || isStateWaypoint(plan_instruction->getWaypoint())) { const JointWaypoint* cur_position; std::shared_ptr<const JointWaypoint> temp; if (isJointWaypoint(plan_instruction->getWaypoint())) { cur_position = plan_instruction->getWaypoint().cast_const<JointWaypoint>(); } else { const StateWaypoint* state_waypoint = plan_instruction->getWaypoint().cast_const<StateWaypoint>(); temp = std::make_shared<JointWaypoint>(state_waypoint->joint_names, state_waypoint->position); cur_position = temp.get(); } Eigen::Isometry3d cur_pose = Eigen::Isometry3d::Identity(); if (!kin->calcFwdKin(cur_pose, *cur_position)) throw std::runtime_error("DefaultTrajoptIfoptProblemGenerator: failed to solve forward kinematics!"); cur_pose = env->getCurrentState()->link_transforms.at(kin->getBaseLinkName()) * cur_pose * tcp; Eigen::Isometry3d prev_pose = Eigen::Isometry3d::Identity(); if (isCartesianWaypoint(start_waypoint)) { prev_pose = *(start_waypoint.cast_const<Eigen::Isometry3d>()); } else if (isJointWaypoint(start_waypoint) || isStateWaypoint(start_waypoint)) { const Eigen::VectorXd& position = getJointPosition(start_waypoint); if (!kin->calcFwdKin(prev_pose, position)) throw std::runtime_error("DefaultTrajoptIfoptProblemGenerator: failed to solve forward kinematics!"); prev_pose = env->getCurrentState()->link_transforms.at(kin->getBaseLinkName()) * prev_pose * tcp; } else { throw std::runtime_error("TrajOptPlannerUniversalConfig: uknown waypoint type."); } tesseract_common::VectorIsometry3d poses = interpolate(prev_pose, cur_pose, interpolate_cnt); // Add intermediate points with path costs and constraints for (std::size_t p = 1; p < poses.size() - 1; ++p) { /** @todo Add path constraint for this */ cur_plan_profile->apply(*problem, poses[p], *plan_instruction, composite_mi, active_links, index); ++index; } // Add final point with waypoint cur_plan_profile->apply(*problem, *cur_position, *plan_instruction, composite_mi, active_links, index); ++index; } else { throw std::runtime_error("DefaultTrajoptIfoptProblemGenerator: unknown waypoint type"); } } else if (plan_instruction->isFreespace()) { if (isJointWaypoint(plan_instruction->getWaypoint()) || isStateWaypoint(plan_instruction->getWaypoint())) { const JointWaypoint* cur_position; std::shared_ptr<const JointWaypoint> temp; if (isJointWaypoint(plan_instruction->getWaypoint())) { cur_position = plan_instruction->getWaypoint().cast_const<JointWaypoint>(); } else { const StateWaypoint* state_waypoint = plan_instruction->getWaypoint().cast_const<StateWaypoint>(); temp = std::make_shared<JointWaypoint>(state_waypoint->joint_names, state_waypoint->position); cur_position = temp.get(); } // Increment index to account for intermediate points in seed for (std::size_t s = 0; s < seed_composite->size() - 1; ++s) { ++i; } /** @todo Should check that the joint names match the order of the manipulator */ cur_plan_profile->apply(*problem, *cur_position, *plan_instruction, manip_info, active_links, i); // Add to fixed indices fixed_steps.push_back(i); } else if (isCartesianWaypoint(plan_instruction->getWaypoint())) { const auto* cur_wp = plan_instruction->getWaypoint().cast_const<CartesianWaypoint>(); // Increment index to account for intermediate points in seed for (std::size_t s = 0; s < seed_composite->size() - 1; ++s) { ++i; } /** @todo Should check that the joint names match the order of the manipulator */ cur_plan_profile->apply(*problem, *cur_wp, *plan_instruction, manip_info, active_links, i); // Add to fixed indices fixed_steps.push_back(i); } else { throw std::runtime_error("DefaultTrajoptIfoptProblemGenerator: unknown waypoint type"); } ++i; } else { throw std::runtime_error("Unsupported!"); } start_waypoint = plan_instruction->getWaypoint(); } } // ---------------- // Translate TCL for CompositeInstructions // ---------------- profile = getProfileString(request.instructions.getProfile(), name, request.composite_profile_remapping); TrajOptIfoptCompositeProfile::ConstPtr cur_composite_profile = getProfile<TrajOptIfoptCompositeProfile>( profile, composite_profiles, std::make_shared<TrajOptIfoptDefaultCompositeProfile>()); if (!cur_composite_profile) throw std::runtime_error("DefaultTrajoptIfoptProblemGenerator: Invalid profile"); cur_composite_profile->apply( *problem, 0, static_cast<int>(problem->vars.size()), composite_mi, active_links, fixed_steps); // ---------------- // Return problem // ---------------- return problem; } } // namespace tesseract_planning
41.768546
118
0.674339
[ "vector", "transform" ]
b41083c2b1ca138409ec772897fda4ae365aa03c
1,283
cpp
C++
solution/1959/sol1.cpp
PerfectPan/LeetCode
2fb56b8eab1acecf7fe82ef3f637117d11e9e969
[ "MIT" ]
null
null
null
solution/1959/sol1.cpp
PerfectPan/LeetCode
2fb56b8eab1acecf7fe82ef3f637117d11e9e969
[ "MIT" ]
null
null
null
solution/1959/sol1.cpp
PerfectPan/LeetCode
2fb56b8eab1acecf7fe82ef3f637117d11e9e969
[ "MIT" ]
null
null
null
class Solution { public: int dp[205][205]; int minSpaceWastedKResizing(vector<int>& nums, int k) { memset(dp,0x3f,sizeof(dp)); int n=nums.size(); dp[0][0]=0; int ans=-1; for (int i=1;i<n;++i){ for (int j=0;j<=min(i,k);++j){ if (j>0){ dp[i][j]=dp[i-1][j-1]; int tot=0,c=0,mx=-1; for (int l=i;l>=1;--l){ tot+=nums[l]; c++; mx=max(mx,nums[l]); if (dp[l-1][j-1]!=0x3f) dp[i][j]=min(dp[i][j],dp[l-1][j-1]+mx*c-tot); } } else { int tot=0,c=0,mx=-1; for (int l=i;l>=0;--l){ tot+=nums[l]; c++; mx=max(mx,nums[l]); } dp[i][0]=mx*c-tot; } if (i==n-1){ if (ans==-1){ ans=dp[i][j]; }else{ ans=min(ans,dp[i][j]); } } } } return n==1?0:ans; } };
29.837209
69
0.265783
[ "vector" ]
b4174cffcd0b294d0a388aa6613a458eafeaec08
770
cpp
C++
2017.8.9/a.cpp
1980744819/ACM-code
a697242bc963e682e552e655e3d78527e044e854
[ "Apache-2.0" ]
null
null
null
2017.8.9/a.cpp
1980744819/ACM-code
a697242bc963e682e552e655e3d78527e044e854
[ "Apache-2.0" ]
null
null
null
2017.8.9/a.cpp
1980744819/ACM-code
a697242bc963e682e552e655e3d78527e044e854
[ "Apache-2.0" ]
null
null
null
#include<cstdio> #include<string> #include<cstring> #include<cstdlib> #include<cmath> #include<iostream> #include<algorithm> #include<vector> #include<queue> #include<map> #include<set> #include<stack> #define ll long long #define read(a) scanf("%d",&a); using namespace std; const int maxn=10005; ll a[maxn],b[maxn]; int main(){ freopen("test.txt","r",stdin); int t; int n,m; scanf("%d",&t); while(t--){ scanf("%d %d",&n,&m); for(int i=0;i<=m;i++){ scanf("%lld",&b[i]); } int cnt=0; int i=1; while(i<=m){ while(b[i]>0){ a[++cnt]=i; b[i]--; for(int j=i+1;j<=m;j++){ if(b[j]>0) b[j]-=b[j-i]; } } i++; } for(i=1;i<=cnt;i++){ if(i>1) printf(" "); printf("%lld",a[i]); } printf("\n"); } return 0; }
15.714286
31
0.538961
[ "vector" ]
b4190f26426340d91d4dbbf6bfcf8eb2e50f913f
6,188
cpp
C++
graphics/meshlab/src/meshlabplugins/decorate_shadow/variance_shadow_mapping.cpp
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
4
2016-03-30T14:31:52.000Z
2019-02-02T05:01:32.000Z
graphics/meshlab/src/meshlabplugins/decorate_shadow/variance_shadow_mapping.cpp
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
null
null
null
graphics/meshlab/src/meshlabplugins/decorate_shadow/variance_shadow_mapping.cpp
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** * MeshLab o o * * An extendible mesh processor o o * * _ O _ * * Copyright(C) 2005, 2006 \/)\/ * * Visual Computing Lab /\/| * * ISTI - Italian National Research Council | * * \ * * All rights reserved. * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License (http://www.gnu.org/licenses/gpl.txt) * * for more details. * * * ****************************************************************************/ #include "decorate_shader.h" #include "variance_shadow_mapping.h" #include <common/pluginmanager.h> #include <meshlab/glarea.h> VarianceShadowMapping::VarianceShadowMapping(float intensity):ShadowMapping(intensity) { this->_depth = 0; this->_depthVert = 0; this->_depthFrag = 0; this->_depthShaderProgram = 0; } VarianceShadowMapping::~VarianceShadowMapping(){ glDetachShader(this->_depthShaderProgram, this->_depthVert); glDetachShader(this->_depthShaderProgram, this->_depthFrag); glDeleteShader(this->_depthVert); glDeleteShader(this->_depthFrag); glDeleteProgram(this->_depthShaderProgram); glDeleteFramebuffersEXT(1, &(this->_depth)); } bool VarianceShadowMapping::init() { if(!this->initGlew() || !this->initSetup()) return false; if(!compileAndLink( this->_depthShaderProgram, this->_depthVert, this->_depthFrag, PluginManager::getBaseDirPath().append(QString("/shaders/decorate_shadow/vsm/depthVSM"))) || !compileAndLink( this->_shadowMappingProgram, this->_shadowMappingVert, this->_shadowMappingFrag, PluginManager::getBaseDirPath().append(QString("/shaders/decorate_shadow/vsm/objectVSM")))) return false; return true; } void VarianceShadowMapping::runShader(MeshDocument& md, GLArea* gla){ GLfloat g_mModelView[16]; GLfloat g_mProjection[16]; if (gla == NULL) return; this->renderingFromLightSetup(md, gla); glMatrixMode(GL_PROJECTION); glGetFloatv(GL_PROJECTION_MATRIX, g_mProjection); glMatrixMode(GL_MODELVIEW); glGetFloatv(GL_MODELVIEW_MATRIX, g_mModelView); /***********************************************************/ //SHADOW MAP Generation /***********************************************************/ glEnable(GL_POLYGON_OFFSET_FILL); glPolygonOffset(1.0, 1.0); this->bind(); glUseProgram(this->_depthShaderProgram); foreach(MeshModel *m, md.meshList) if(m->visible) { m->render(vcg::GLW::DMFlat, vcg::GLW::CMNone,vcg::GLW::TMNone); } glDisable(GL_POLYGON_OFFSET_FILL); this->unbind(); this->renderingFromLightUnsetup(); /***********************************************************/ //SHADOW MAP Generation finished /***********************************************************/ /***********************************************************/ //OBJECT PASS /***********************************************************/ GLint depthFuncOld; glGetIntegerv(GL_DEPTH_FUNC, &depthFuncOld); glDepthFunc(GL_LEQUAL); vcg::Matrix44f mvpl = (vcg::Matrix44f(g_mProjection).transpose() * vcg::Matrix44f(g_mModelView).transpose()).transpose(); glUseProgram(this->_shadowMappingProgram); GLuint matrixLoc = glGetUniformLocation(this->_shadowMappingProgram, "mvpl"); glUniformMatrix4fv(matrixLoc, 1, 0, mvpl.V()); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, this->_shadowMap); GLuint shadowIntensityLoc = glGetUniformLocation(this->_shadowMappingProgram, "shadowIntensity"); glUniform1f(shadowIntensityLoc, this->_intensity); GLuint loc = glGetUniformLocation(this->_shadowMappingProgram, "shadowMap"); glUniform1i(loc, 0); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); foreach(MeshModel *m, md.meshList) if(m->visible) { m->render(vcg::GLW::DMFlat, vcg::GLW::CMNone,vcg::GLW::TMNone); } glDisable(GL_BLEND); glDepthFunc((GLenum)depthFuncOld); glUseProgram(0); } bool VarianceShadowMapping::setup() { if (!GLEW_EXT_framebuffer_object) { qWarning("FBO not supported!"); return false; } if (_initOk) return true; //genero il frame buffer object glGenFramebuffersEXT(1, &_fbo); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _fbo); //Generates texture color for variance shadow map this->genColorTextureEXT(this->_shadowMap, GL_COLOR_ATTACHMENT0_EXT); //Generates render buffer for depth attachment this->genDepthRenderBufferEXT(this->_depth); //checks for errors int err = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); _initOk = (err == GL_FRAMEBUFFER_COMPLETE_EXT); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); return _initOk; }
37.053892
125
0.537654
[ "mesh", "render", "object" ]
b41aceb8634bfb6dd50543c9ea3ca558b6f416c1
103,566
cpp
C++
lld/ELF/Writer.cpp
akyrtzi/llvm-project
c7d23d83fbf9182fcc8da59c44501f81dd302974
[ "Apache-2.0" ]
null
null
null
lld/ELF/Writer.cpp
akyrtzi/llvm-project
c7d23d83fbf9182fcc8da59c44501f81dd302974
[ "Apache-2.0" ]
null
null
null
lld/ELF/Writer.cpp
akyrtzi/llvm-project
c7d23d83fbf9182fcc8da59c44501f81dd302974
[ "Apache-2.0" ]
null
null
null
//===- Writer.cpp ---------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "Writer.h" #include "AArch64ErrataFix.h" #include "ARMErrataFix.h" #include "CallGraphSort.h" #include "Config.h" #include "LinkerScript.h" #include "MapFile.h" #include "OutputSections.h" #include "Relocations.h" #include "SymbolTable.h" #include "Symbols.h" #include "SyntheticSections.h" #include "Target.h" #include "lld/Common/Filesystem.h" #include "lld/Common/Memory.h" #include "lld/Common/Strings.h" #include "lld/Common/Threads.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/RandomNumberGenerator.h" #include "llvm/Support/SHA1.h" #include "llvm/Support/TimeProfiler.h" #include "llvm/Support/xxhash.h" #include <climits> using namespace llvm; using namespace llvm::ELF; using namespace llvm::object; using namespace llvm::support; using namespace llvm::support::endian; namespace lld { namespace elf { namespace { // The writer writes a SymbolTable result to a file. template <class ELFT> class Writer { public: Writer() : buffer(errorHandler().outputBuffer) {} using Elf_Shdr = typename ELFT::Shdr; using Elf_Ehdr = typename ELFT::Ehdr; using Elf_Phdr = typename ELFT::Phdr; void run(); private: void copyLocalSymbols(); void addSectionSymbols(); void forEachRelSec(llvm::function_ref<void(InputSectionBase &)> fn); void sortSections(); void resolveShfLinkOrder(); void finalizeAddressDependentContent(); void sortInputSections(); void finalizeSections(); void checkExecuteOnly(); void setReservedSymbolSections(); std::vector<PhdrEntry *> createPhdrs(Partition &part); void addPhdrForSection(Partition &part, unsigned shType, unsigned pType, unsigned pFlags); void assignFileOffsets(); void assignFileOffsetsBinary(); void setPhdrs(Partition &part); void checkSections(); void fixSectionAlignments(); void openFile(); void writeTrapInstr(); void writeHeader(); void writeSections(); void writeSectionsBinary(); void writeBuildId(); std::unique_ptr<FileOutputBuffer> &buffer; void addRelIpltSymbols(); void addStartEndSymbols(); void addStartStopSymbols(OutputSection *sec); uint64_t fileSize; uint64_t sectionHeaderOff; }; } // anonymous namespace static bool isSectionPrefix(StringRef prefix, StringRef name) { return name.startswith(prefix) || name == prefix.drop_back(); } StringRef getOutputSectionName(const InputSectionBase *s) { if (config->relocatable) return s->name; // This is for --emit-relocs. If .text.foo is emitted as .text.bar, we want // to emit .rela.text.foo as .rela.text.bar for consistency (this is not // technically required, but not doing it is odd). This code guarantees that. if (auto *isec = dyn_cast<InputSection>(s)) { if (InputSectionBase *rel = isec->getRelocatedSection()) { OutputSection *out = rel->getOutputSection(); if (s->type == SHT_RELA) return saver.save(".rela" + out->name); return saver.save(".rel" + out->name); } } // This check is for -z keep-text-section-prefix. This option separates text // sections with prefix ".text.hot", ".text.unlikely", ".text.startup" or // ".text.exit". // When enabled, this allows identifying the hot code region (.text.hot) in // the final binary which can be selectively mapped to huge pages or mlocked, // for instance. if (config->zKeepTextSectionPrefix) for (StringRef v : {".text.hot.", ".text.unlikely.", ".text.startup.", ".text.exit."}) if (isSectionPrefix(v, s->name)) return v.drop_back(); for (StringRef v : {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.", ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.", ".gcc_except_table.", ".tdata.", ".ARM.exidx.", ".ARM.extab."}) if (isSectionPrefix(v, s->name)) return v.drop_back(); // CommonSection is identified as "COMMON" in linker scripts. // By default, it should go to .bss section. if (s->name == "COMMON") return ".bss"; return s->name; } static bool needsInterpSection() { return !config->relocatable && !config->shared && !config->dynamicLinker.empty() && script->needsInterpSection(); } template <class ELFT> void writeResult() { llvm::TimeTraceScope timeScope("Write output file"); Writer<ELFT>().run(); } static void removeEmptyPTLoad(std::vector<PhdrEntry *> &phdrs) { llvm::erase_if(phdrs, [&](const PhdrEntry *p) { if (p->p_type != PT_LOAD) return false; if (!p->firstSec) return true; uint64_t size = p->lastSec->addr + p->lastSec->size - p->firstSec->addr; return size == 0; }); } void copySectionsIntoPartitions() { std::vector<InputSectionBase *> newSections; for (unsigned part = 2; part != partitions.size() + 1; ++part) { for (InputSectionBase *s : inputSections) { if (!(s->flags & SHF_ALLOC) || !s->isLive()) continue; InputSectionBase *copy; if (s->type == SHT_NOTE) copy = make<InputSection>(cast<InputSection>(*s)); else if (auto *es = dyn_cast<EhInputSection>(s)) copy = make<EhInputSection>(*es); else continue; copy->partition = part; newSections.push_back(copy); } } inputSections.insert(inputSections.end(), newSections.begin(), newSections.end()); } void combineEhSections() { for (InputSectionBase *&s : inputSections) { // Ignore dead sections and the partition end marker (.part.end), // whose partition number is out of bounds. if (!s->isLive() || s->partition == 255) continue; Partition &part = s->getPartition(); if (auto *es = dyn_cast<EhInputSection>(s)) { part.ehFrame->addSection(es); s = nullptr; } else if (s->kind() == SectionBase::Regular && part.armExidx && part.armExidx->addSection(cast<InputSection>(s))) { s = nullptr; } } std::vector<InputSectionBase *> &v = inputSections; v.erase(std::remove(v.begin(), v.end(), nullptr), v.end()); } static Defined *addOptionalRegular(StringRef name, SectionBase *sec, uint64_t val, uint8_t stOther = STV_HIDDEN, uint8_t binding = STB_GLOBAL) { Symbol *s = symtab->find(name); if (!s || s->isDefined()) return nullptr; s->resolve(Defined{/*file=*/nullptr, name, binding, stOther, STT_NOTYPE, val, /*size=*/0, sec}); return cast<Defined>(s); } static Defined *addAbsolute(StringRef name) { Symbol *sym = symtab->addSymbol(Defined{nullptr, name, STB_GLOBAL, STV_HIDDEN, STT_NOTYPE, 0, 0, nullptr}); return cast<Defined>(sym); } // The linker is expected to define some symbols depending on // the linking result. This function defines such symbols. void addReservedSymbols() { if (config->emachine == EM_MIPS) { // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer // so that it points to an absolute address which by default is relative // to GOT. Default offset is 0x7ff0. // See "Global Data Symbols" in Chapter 6 in the following document: // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf ElfSym::mipsGp = addAbsolute("_gp"); // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between // start of function and 'gp' pointer into GOT. if (symtab->find("_gp_disp")) ElfSym::mipsGpDisp = addAbsolute("_gp_disp"); // The __gnu_local_gp is a magic symbol equal to the current value of 'gp' // pointer. This symbol is used in the code generated by .cpload pseudo-op // in case of using -mno-shared option. // https://sourceware.org/ml/binutils/2004-12/msg00094.html if (symtab->find("__gnu_local_gp")) ElfSym::mipsLocalGp = addAbsolute("__gnu_local_gp"); } else if (config->emachine == EM_PPC) { // glibc *crt1.o has a undefined reference to _SDA_BASE_. Since we don't // support Small Data Area, define it arbitrarily as 0. addOptionalRegular("_SDA_BASE_", nullptr, 0, STV_HIDDEN); } // The Power Architecture 64-bit v2 ABI defines a TableOfContents (TOC) which // combines the typical ELF GOT with the small data sections. It commonly // includes .got .toc .sdata .sbss. The .TOC. symbol replaces both // _GLOBAL_OFFSET_TABLE_ and _SDA_BASE_ from the 32-bit ABI. It is used to // represent the TOC base which is offset by 0x8000 bytes from the start of // the .got section. // We do not allow _GLOBAL_OFFSET_TABLE_ to be defined by input objects as the // correctness of some relocations depends on its value. StringRef gotSymName = (config->emachine == EM_PPC64) ? ".TOC." : "_GLOBAL_OFFSET_TABLE_"; if (Symbol *s = symtab->find(gotSymName)) { if (s->isDefined()) { error(toString(s->file) + " cannot redefine linker defined symbol '" + gotSymName + "'"); return; } uint64_t gotOff = 0; if (config->emachine == EM_PPC64) gotOff = 0x8000; s->resolve(Defined{/*file=*/nullptr, gotSymName, STB_GLOBAL, STV_HIDDEN, STT_NOTYPE, gotOff, /*size=*/0, Out::elfHeader}); ElfSym::globalOffsetTable = cast<Defined>(s); } // __ehdr_start is the location of ELF file headers. Note that we define // this symbol unconditionally even when using a linker script, which // differs from the behavior implemented by GNU linker which only define // this symbol if ELF headers are in the memory mapped segment. addOptionalRegular("__ehdr_start", Out::elfHeader, 0, STV_HIDDEN); // __executable_start is not documented, but the expectation of at // least the Android libc is that it points to the ELF header. addOptionalRegular("__executable_start", Out::elfHeader, 0, STV_HIDDEN); // __dso_handle symbol is passed to cxa_finalize as a marker to identify // each DSO. The address of the symbol doesn't matter as long as they are // different in different DSOs, so we chose the start address of the DSO. addOptionalRegular("__dso_handle", Out::elfHeader, 0, STV_HIDDEN); // If linker script do layout we do not need to create any standard symbols. if (script->hasSectionsCommand) return; auto add = [](StringRef s, int64_t pos) { return addOptionalRegular(s, Out::elfHeader, pos, STV_DEFAULT); }; ElfSym::bss = add("__bss_start", 0); ElfSym::end1 = add("end", -1); ElfSym::end2 = add("_end", -1); ElfSym::etext1 = add("etext", -1); ElfSym::etext2 = add("_etext", -1); ElfSym::edata1 = add("edata", -1); ElfSym::edata2 = add("_edata", -1); } static OutputSection *findSection(StringRef name, unsigned partition = 1) { for (BaseCommand *base : script->sectionCommands) if (auto *sec = dyn_cast<OutputSection>(base)) if (sec->name == name && sec->partition == partition) return sec; return nullptr; } template <class ELFT> void createSyntheticSections() { // Initialize all pointers with NULL. This is needed because // you can call lld::elf::main more than once as a library. memset(&Out::first, 0, sizeof(Out)); // Add the .interp section first because it is not a SyntheticSection. // The removeUnusedSyntheticSections() function relies on the // SyntheticSections coming last. if (needsInterpSection()) { for (size_t i = 1; i <= partitions.size(); ++i) { InputSection *sec = createInterpSection(); sec->partition = i; inputSections.push_back(sec); } } auto add = [](SyntheticSection *sec) { inputSections.push_back(sec); }; in.shStrTab = make<StringTableSection>(".shstrtab", false); Out::programHeaders = make<OutputSection>("", 0, SHF_ALLOC); Out::programHeaders->alignment = config->wordsize; if (config->strip != StripPolicy::All) { in.strTab = make<StringTableSection>(".strtab", false); in.symTab = make<SymbolTableSection<ELFT>>(*in.strTab); in.symTabShndx = make<SymtabShndxSection>(); } in.bss = make<BssSection>(".bss", 0, 1); add(in.bss); // If there is a SECTIONS command and a .data.rel.ro section name use name // .data.rel.ro.bss so that we match in the .data.rel.ro output section. // This makes sure our relro is contiguous. bool hasDataRelRo = script->hasSectionsCommand && findSection(".data.rel.ro", 0); in.bssRelRo = make<BssSection>(hasDataRelRo ? ".data.rel.ro.bss" : ".bss.rel.ro", 0, 1); add(in.bssRelRo); // Add MIPS-specific sections. if (config->emachine == EM_MIPS) { if (!config->shared && config->hasDynSymTab) { in.mipsRldMap = make<MipsRldMapSection>(); add(in.mipsRldMap); } if (auto *sec = MipsAbiFlagsSection<ELFT>::create()) add(sec); if (auto *sec = MipsOptionsSection<ELFT>::create()) add(sec); if (auto *sec = MipsReginfoSection<ELFT>::create()) add(sec); } StringRef relaDynName = config->isRela ? ".rela.dyn" : ".rel.dyn"; for (Partition &part : partitions) { auto add = [&](SyntheticSection *sec) { sec->partition = part.getNumber(); inputSections.push_back(sec); }; if (!part.name.empty()) { part.elfHeader = make<PartitionElfHeaderSection<ELFT>>(); part.elfHeader->name = part.name; add(part.elfHeader); part.programHeaders = make<PartitionProgramHeadersSection<ELFT>>(); add(part.programHeaders); } if (config->buildId != BuildIdKind::None) { part.buildId = make<BuildIdSection>(); add(part.buildId); } part.dynStrTab = make<StringTableSection>(".dynstr", true); part.dynSymTab = make<SymbolTableSection<ELFT>>(*part.dynStrTab); part.dynamic = make<DynamicSection<ELFT>>(); if (config->androidPackDynRelocs) part.relaDyn = make<AndroidPackedRelocationSection<ELFT>>(relaDynName); else part.relaDyn = make<RelocationSection<ELFT>>(relaDynName, config->zCombreloc); if (config->hasDynSymTab) { part.dynSymTab = make<SymbolTableSection<ELFT>>(*part.dynStrTab); add(part.dynSymTab); part.verSym = make<VersionTableSection>(); add(part.verSym); if (!namedVersionDefs().empty()) { part.verDef = make<VersionDefinitionSection>(); add(part.verDef); } part.verNeed = make<VersionNeedSection<ELFT>>(); add(part.verNeed); if (config->gnuHash) { part.gnuHashTab = make<GnuHashTableSection>(); add(part.gnuHashTab); } if (config->sysvHash) { part.hashTab = make<HashTableSection>(); add(part.hashTab); } add(part.dynamic); add(part.dynStrTab); add(part.relaDyn); } if (config->relrPackDynRelocs) { part.relrDyn = make<RelrSection<ELFT>>(); add(part.relrDyn); } if (!config->relocatable) { if (config->ehFrameHdr) { part.ehFrameHdr = make<EhFrameHeader>(); add(part.ehFrameHdr); } part.ehFrame = make<EhFrameSection>(); add(part.ehFrame); } if (config->emachine == EM_ARM && !config->relocatable) { // The ARMExidxsyntheticsection replaces all the individual .ARM.exidx // InputSections. part.armExidx = make<ARMExidxSyntheticSection>(); add(part.armExidx); } } if (partitions.size() != 1) { // Create the partition end marker. This needs to be in partition number 255 // so that it is sorted after all other partitions. It also has other // special handling (see createPhdrs() and combineEhSections()). in.partEnd = make<BssSection>(".part.end", config->maxPageSize, 1); in.partEnd->partition = 255; add(in.partEnd); in.partIndex = make<PartitionIndexSection>(); addOptionalRegular("__part_index_begin", in.partIndex, 0); addOptionalRegular("__part_index_end", in.partIndex, in.partIndex->getSize()); add(in.partIndex); } // Add .got. MIPS' .got is so different from the other archs, // it has its own class. if (config->emachine == EM_MIPS) { in.mipsGot = make<MipsGotSection>(); add(in.mipsGot); } else { in.got = make<GotSection>(); add(in.got); } if (config->emachine == EM_PPC) { in.ppc32Got2 = make<PPC32Got2Section>(); add(in.ppc32Got2); } if (config->emachine == EM_PPC64) { in.ppc64LongBranchTarget = make<PPC64LongBranchTargetSection>(); add(in.ppc64LongBranchTarget); } in.gotPlt = make<GotPltSection>(); add(in.gotPlt); in.igotPlt = make<IgotPltSection>(); add(in.igotPlt); // _GLOBAL_OFFSET_TABLE_ is defined relative to either .got.plt or .got. Treat // it as a relocation and ensure the referenced section is created. if (ElfSym::globalOffsetTable && config->emachine != EM_MIPS) { if (target->gotBaseSymInGotPlt) in.gotPlt->hasGotPltOffRel = true; else in.got->hasGotOffRel = true; } if (config->gdbIndex) add(GdbIndexSection::create<ELFT>()); // We always need to add rel[a].plt to output if it has entries. // Even for static linking it can contain R_[*]_IRELATIVE relocations. in.relaPlt = make<RelocationSection<ELFT>>( config->isRela ? ".rela.plt" : ".rel.plt", /*sort=*/false); add(in.relaPlt); // The relaIplt immediately follows .rel[a].dyn to ensure that the IRelative // relocations are processed last by the dynamic loader. We cannot place the // iplt section in .rel.dyn when Android relocation packing is enabled because // that would cause a section type mismatch. However, because the Android // dynamic loader reads .rel.plt after .rel.dyn, we can get the desired // behaviour by placing the iplt section in .rel.plt. in.relaIplt = make<RelocationSection<ELFT>>( config->androidPackDynRelocs ? in.relaPlt->name : relaDynName, /*sort=*/false); add(in.relaIplt); if ((config->emachine == EM_386 || config->emachine == EM_X86_64) && (config->andFeatures & GNU_PROPERTY_X86_FEATURE_1_IBT)) { in.ibtPlt = make<IBTPltSection>(); add(in.ibtPlt); } in.plt = config->emachine == EM_PPC ? make<PPC32GlinkSection>() : make<PltSection>(); add(in.plt); in.iplt = make<IpltSection>(); add(in.iplt); if (config->andFeatures) add(make<GnuPropertySection>()); // .note.GNU-stack is always added when we are creating a re-linkable // object file. Other linkers are using the presence of this marker // section to control the executable-ness of the stack area, but that // is irrelevant these days. Stack area should always be non-executable // by default. So we emit this section unconditionally. if (config->relocatable) add(make<GnuStackSection>()); if (in.symTab) add(in.symTab); if (in.symTabShndx) add(in.symTabShndx); add(in.shStrTab); if (in.strTab) add(in.strTab); } // The main function of the writer. template <class ELFT> void Writer<ELFT>::run() { if (config->discard != DiscardPolicy::All) copyLocalSymbols(); if (config->copyRelocs) addSectionSymbols(); // Now that we have a complete set of output sections. This function // completes section contents. For example, we need to add strings // to the string table, and add entries to .got and .plt. // finalizeSections does that. finalizeSections(); checkExecuteOnly(); if (errorCount()) return; // If -compressed-debug-sections is specified, we need to compress // .debug_* sections. Do it right now because it changes the size of // output sections. for (OutputSection *sec : outputSections) sec->maybeCompress<ELFT>(); if (script->hasSectionsCommand) script->allocateHeaders(mainPart->phdrs); // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a // 0 sized region. This has to be done late since only after assignAddresses // we know the size of the sections. for (Partition &part : partitions) removeEmptyPTLoad(part.phdrs); if (!config->oFormatBinary) assignFileOffsets(); else assignFileOffsetsBinary(); for (Partition &part : partitions) setPhdrs(part); if (config->relocatable) for (OutputSection *sec : outputSections) sec->addr = 0; if (config->checkSections) checkSections(); // It does not make sense try to open the file if we have error already. if (errorCount()) return; // Write the result down to a file. openFile(); if (errorCount()) return; if (!config->oFormatBinary) { if (config->zSeparate != SeparateSegmentKind::None) writeTrapInstr(); writeHeader(); writeSections(); } else { writeSectionsBinary(); } // Backfill .note.gnu.build-id section content. This is done at last // because the content is usually a hash value of the entire output file. writeBuildId(); if (errorCount()) return; // Handle -Map and -cref options. writeMapFile(); writeCrossReferenceTable(); if (errorCount()) return; if (auto e = buffer->commit()) error("failed to write to the output file: " + toString(std::move(e))); } static bool shouldKeepInSymtab(const Defined &sym) { if (sym.isSection()) return false; if (config->discard == DiscardPolicy::None) return true; // If -emit-reloc is given, all symbols including local ones need to be // copied because they may be referenced by relocations. if (config->emitRelocs) return true; // In ELF assembly .L symbols are normally discarded by the assembler. // If the assembler fails to do so, the linker discards them if // * --discard-locals is used. // * The symbol is in a SHF_MERGE section, which is normally the reason for // the assembler keeping the .L symbol. StringRef name = sym.getName(); bool isLocal = name.startswith(".L") || name.empty(); if (!isLocal) return true; if (config->discard == DiscardPolicy::Locals) return false; SectionBase *sec = sym.section; return !sec || !(sec->flags & SHF_MERGE); } static bool includeInSymtab(const Symbol &b) { if (!b.isLocal() && !b.isUsedInRegularObj) return false; if (auto *d = dyn_cast<Defined>(&b)) { // Always include absolute symbols. SectionBase *sec = d->section; if (!sec) return true; sec = sec->repl; // Exclude symbols pointing to garbage-collected sections. if (isa<InputSectionBase>(sec) && !sec->isLive()) return false; if (auto *s = dyn_cast<MergeInputSection>(sec)) if (!s->getSectionPiece(d->value)->live) return false; return true; } return b.used; } // Local symbols are not in the linker's symbol table. This function scans // each object file's symbol table to copy local symbols to the output. template <class ELFT> void Writer<ELFT>::copyLocalSymbols() { if (!in.symTab) return; for (InputFile *file : objectFiles) { ObjFile<ELFT> *f = cast<ObjFile<ELFT>>(file); for (Symbol *b : f->getLocalSymbols()) { if (!b->isLocal()) fatal(toString(f) + ": broken object: getLocalSymbols returns a non-local symbol"); auto *dr = dyn_cast<Defined>(b); // No reason to keep local undefined symbol in symtab. if (!dr) continue; if (!includeInSymtab(*b)) continue; if (!shouldKeepInSymtab(*dr)) continue; in.symTab->addSymbol(b); } } } // Create a section symbol for each output section so that we can represent // relocations that point to the section. If we know that no relocation is // referring to a section (that happens if the section is a synthetic one), we // don't create a section symbol for that section. template <class ELFT> void Writer<ELFT>::addSectionSymbols() { for (BaseCommand *base : script->sectionCommands) { auto *sec = dyn_cast<OutputSection>(base); if (!sec) continue; auto i = llvm::find_if(sec->sectionCommands, [](BaseCommand *base) { if (auto *isd = dyn_cast<InputSectionDescription>(base)) return !isd->sections.empty(); return false; }); if (i == sec->sectionCommands.end()) continue; InputSectionBase *isec = cast<InputSectionDescription>(*i)->sections[0]; // Relocations are not using REL[A] section symbols. if (isec->type == SHT_REL || isec->type == SHT_RELA) continue; // Unlike other synthetic sections, mergeable output sections contain data // copied from input sections, and there may be a relocation pointing to its // contents if -r or -emit-reloc are given. if (isa<SyntheticSection>(isec) && !(isec->flags & SHF_MERGE)) continue; auto *sym = make<Defined>(isec->file, "", STB_LOCAL, /*stOther=*/0, STT_SECTION, /*value=*/0, /*size=*/0, isec); in.symTab->addSymbol(sym); } } // Today's loaders have a feature to make segments read-only after // processing dynamic relocations to enhance security. PT_GNU_RELRO // is defined for that. // // This function returns true if a section needs to be put into a // PT_GNU_RELRO segment. static bool isRelroSection(const OutputSection *sec) { if (!config->zRelro) return false; uint64_t flags = sec->flags; // Non-allocatable or non-writable sections don't need RELRO because // they are not writable or not even mapped to memory in the first place. // RELRO is for sections that are essentially read-only but need to // be writable only at process startup to allow dynamic linker to // apply relocations. if (!(flags & SHF_ALLOC) || !(flags & SHF_WRITE)) return false; // Once initialized, TLS data segments are used as data templates // for a thread-local storage. For each new thread, runtime // allocates memory for a TLS and copy templates there. No thread // are supposed to use templates directly. Thus, it can be in RELRO. if (flags & SHF_TLS) return true; // .init_array, .preinit_array and .fini_array contain pointers to // functions that are executed on process startup or exit. These // pointers are set by the static linker, and they are not expected // to change at runtime. But if you are an attacker, you could do // interesting things by manipulating pointers in .fini_array, for // example. So they are put into RELRO. uint32_t type = sec->type; if (type == SHT_INIT_ARRAY || type == SHT_FINI_ARRAY || type == SHT_PREINIT_ARRAY) return true; // .got contains pointers to external symbols. They are resolved by // the dynamic linker when a module is loaded into memory, and after // that they are not expected to change. So, it can be in RELRO. if (in.got && sec == in.got->getParent()) return true; // .toc is a GOT-ish section for PowerPC64. Their contents are accessed // through r2 register, which is reserved for that purpose. Since r2 is used // for accessing .got as well, .got and .toc need to be close enough in the // virtual address space. Usually, .toc comes just after .got. Since we place // .got into RELRO, .toc needs to be placed into RELRO too. if (sec->name.equals(".toc")) return true; // .got.plt contains pointers to external function symbols. They are // by default resolved lazily, so we usually cannot put it into RELRO. // However, if "-z now" is given, the lazy symbol resolution is // disabled, which enables us to put it into RELRO. if (sec == in.gotPlt->getParent()) return config->zNow; // .dynamic section contains data for the dynamic linker, and // there's no need to write to it at runtime, so it's better to put // it into RELRO. if (sec->name == ".dynamic") return true; // Sections with some special names are put into RELRO. This is a // bit unfortunate because section names shouldn't be significant in // ELF in spirit. But in reality many linker features depend on // magic section names. StringRef s = sec->name; return s == ".data.rel.ro" || s == ".bss.rel.ro" || s == ".ctors" || s == ".dtors" || s == ".jcr" || s == ".eh_frame" || s == ".openbsd.randomdata"; } // We compute a rank for each section. The rank indicates where the // section should be placed in the file. Instead of using simple // numbers (0,1,2...), we use a series of flags. One for each decision // point when placing the section. // Using flags has two key properties: // * It is easy to check if a give branch was taken. // * It is easy two see how similar two ranks are (see getRankProximity). enum RankFlags { RF_NOT_ADDR_SET = 1 << 27, RF_NOT_ALLOC = 1 << 26, RF_PARTITION = 1 << 18, // Partition number (8 bits) RF_NOT_PART_EHDR = 1 << 17, RF_NOT_PART_PHDR = 1 << 16, RF_NOT_INTERP = 1 << 15, RF_NOT_NOTE = 1 << 14, RF_WRITE = 1 << 13, RF_EXEC_WRITE = 1 << 12, RF_EXEC = 1 << 11, RF_RODATA = 1 << 10, RF_NOT_RELRO = 1 << 9, RF_NOT_TLS = 1 << 8, RF_BSS = 1 << 7, RF_PPC_NOT_TOCBSS = 1 << 6, RF_PPC_TOCL = 1 << 5, RF_PPC_TOC = 1 << 4, RF_PPC_GOT = 1 << 3, RF_PPC_BRANCH_LT = 1 << 2, RF_MIPS_GPREL = 1 << 1, RF_MIPS_NOT_GOT = 1 << 0 }; static unsigned getSectionRank(const OutputSection *sec) { unsigned rank = sec->partition * RF_PARTITION; // We want to put section specified by -T option first, so we // can start assigning VA starting from them later. if (config->sectionStartMap.count(sec->name)) return rank; rank |= RF_NOT_ADDR_SET; // Allocatable sections go first to reduce the total PT_LOAD size and // so debug info doesn't change addresses in actual code. if (!(sec->flags & SHF_ALLOC)) return rank | RF_NOT_ALLOC; if (sec->type == SHT_LLVM_PART_EHDR) return rank; rank |= RF_NOT_PART_EHDR; if (sec->type == SHT_LLVM_PART_PHDR) return rank; rank |= RF_NOT_PART_PHDR; // Put .interp first because some loaders want to see that section // on the first page of the executable file when loaded into memory. if (sec->name == ".interp") return rank; rank |= RF_NOT_INTERP; // Put .note sections (which make up one PT_NOTE) at the beginning so that // they are likely to be included in a core file even if core file size is // limited. In particular, we want a .note.gnu.build-id and a .note.tag to be // included in a core to match core files with executables. if (sec->type == SHT_NOTE) return rank; rank |= RF_NOT_NOTE; // Sort sections based on their access permission in the following // order: R, RX, RWX, RW. This order is based on the following // considerations: // * Read-only sections come first such that they go in the // PT_LOAD covering the program headers at the start of the file. // * Read-only, executable sections come next. // * Writable, executable sections follow such that .plt on // architectures where it needs to be writable will be placed // between .text and .data. // * Writable sections come last, such that .bss lands at the very // end of the last PT_LOAD. bool isExec = sec->flags & SHF_EXECINSTR; bool isWrite = sec->flags & SHF_WRITE; if (isExec) { if (isWrite) rank |= RF_EXEC_WRITE; else rank |= RF_EXEC; } else if (isWrite) { rank |= RF_WRITE; } else if (sec->type == SHT_PROGBITS) { // Make non-executable and non-writable PROGBITS sections (e.g .rodata // .eh_frame) closer to .text. They likely contain PC or GOT relative // relocations and there could be relocation overflow if other huge sections // (.dynstr .dynsym) were placed in between. rank |= RF_RODATA; } // Place RelRo sections first. After considering SHT_NOBITS below, the // ordering is PT_LOAD(PT_GNU_RELRO(.data.rel.ro .bss.rel.ro) | .data .bss), // where | marks where page alignment happens. An alternative ordering is // PT_LOAD(.data | PT_GNU_RELRO( .data.rel.ro .bss.rel.ro) | .bss), but it may // waste more bytes due to 2 alignment places. if (!isRelroSection(sec)) rank |= RF_NOT_RELRO; // If we got here we know that both A and B are in the same PT_LOAD. // The TLS initialization block needs to be a single contiguous block in a R/W // PT_LOAD, so stick TLS sections directly before the other RelRo R/W // sections. Since p_filesz can be less than p_memsz, place NOBITS sections // after PROGBITS. if (!(sec->flags & SHF_TLS)) rank |= RF_NOT_TLS; // Within TLS sections, or within other RelRo sections, or within non-RelRo // sections, place non-NOBITS sections first. if (sec->type == SHT_NOBITS) rank |= RF_BSS; // Some architectures have additional ordering restrictions for sections // within the same PT_LOAD. if (config->emachine == EM_PPC64) { // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections // that we would like to make sure appear is a specific order to maximize // their coverage by a single signed 16-bit offset from the TOC base // pointer. Conversely, the special .tocbss section should be first among // all SHT_NOBITS sections. This will put it next to the loaded special // PPC64 sections (and, thus, within reach of the TOC base pointer). StringRef name = sec->name; if (name != ".tocbss") rank |= RF_PPC_NOT_TOCBSS; if (name == ".toc1") rank |= RF_PPC_TOCL; if (name == ".toc") rank |= RF_PPC_TOC; if (name == ".got") rank |= RF_PPC_GOT; if (name == ".branch_lt") rank |= RF_PPC_BRANCH_LT; } if (config->emachine == EM_MIPS) { // All sections with SHF_MIPS_GPREL flag should be grouped together // because data in these sections is addressable with a gp relative address. if (sec->flags & SHF_MIPS_GPREL) rank |= RF_MIPS_GPREL; if (sec->name != ".got") rank |= RF_MIPS_NOT_GOT; } return rank; } static bool compareSections(const BaseCommand *aCmd, const BaseCommand *bCmd) { const OutputSection *a = cast<OutputSection>(aCmd); const OutputSection *b = cast<OutputSection>(bCmd); if (a->sortRank != b->sortRank) return a->sortRank < b->sortRank; if (!(a->sortRank & RF_NOT_ADDR_SET)) return config->sectionStartMap.lookup(a->name) < config->sectionStartMap.lookup(b->name); return false; } void PhdrEntry::add(OutputSection *sec) { lastSec = sec; if (!firstSec) firstSec = sec; p_align = std::max(p_align, sec->alignment); if (p_type == PT_LOAD) sec->ptLoad = this; } // The beginning and the ending of .rel[a].plt section are marked // with __rel[a]_iplt_{start,end} symbols if it is a statically linked // executable. The runtime needs these symbols in order to resolve // all IRELATIVE relocs on startup. For dynamic executables, we don't // need these symbols, since IRELATIVE relocs are resolved through GOT // and PLT. For details, see http://www.airs.com/blog/archives/403. template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() { if (config->relocatable || needsInterpSection()) return; // By default, __rela_iplt_{start,end} belong to a dummy section 0 // because .rela.plt might be empty and thus removed from output. // We'll override Out::elfHeader with In.relaIplt later when we are // sure that .rela.plt exists in output. ElfSym::relaIpltStart = addOptionalRegular( config->isRela ? "__rela_iplt_start" : "__rel_iplt_start", Out::elfHeader, 0, STV_HIDDEN, STB_WEAK); ElfSym::relaIpltEnd = addOptionalRegular( config->isRela ? "__rela_iplt_end" : "__rel_iplt_end", Out::elfHeader, 0, STV_HIDDEN, STB_WEAK); } template <class ELFT> void Writer<ELFT>::forEachRelSec( llvm::function_ref<void(InputSectionBase &)> fn) { // Scan all relocations. Each relocation goes through a series // of tests to determine if it needs special treatment, such as // creating GOT, PLT, copy relocations, etc. // Note that relocations for non-alloc sections are directly // processed by InputSection::relocateNonAlloc. for (InputSectionBase *isec : inputSections) if (isec->isLive() && isa<InputSection>(isec) && (isec->flags & SHF_ALLOC)) fn(*isec); for (Partition &part : partitions) { for (EhInputSection *es : part.ehFrame->sections) fn(*es); if (part.armExidx && part.armExidx->isLive()) for (InputSection *ex : part.armExidx->exidxSections) fn(*ex); } } // This function generates assignments for predefined symbols (e.g. _end or // _etext) and inserts them into the commands sequence to be processed at the // appropriate time. This ensures that the value is going to be correct by the // time any references to these symbols are processed and is equivalent to // defining these symbols explicitly in the linker script. template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() { if (ElfSym::globalOffsetTable) { // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention usually // to the start of the .got or .got.plt section. InputSection *gotSection = in.gotPlt; if (!target->gotBaseSymInGotPlt) gotSection = in.mipsGot ? cast<InputSection>(in.mipsGot) : cast<InputSection>(in.got); ElfSym::globalOffsetTable->section = gotSection; } // .rela_iplt_{start,end} mark the start and the end of in.relaIplt. if (ElfSym::relaIpltStart && in.relaIplt->isNeeded()) { ElfSym::relaIpltStart->section = in.relaIplt; ElfSym::relaIpltEnd->section = in.relaIplt; ElfSym::relaIpltEnd->value = in.relaIplt->getSize(); } PhdrEntry *last = nullptr; PhdrEntry *lastRO = nullptr; for (Partition &part : partitions) { for (PhdrEntry *p : part.phdrs) { if (p->p_type != PT_LOAD) continue; last = p; if (!(p->p_flags & PF_W)) lastRO = p; } } if (lastRO) { // _etext is the first location after the last read-only loadable segment. if (ElfSym::etext1) ElfSym::etext1->section = lastRO->lastSec; if (ElfSym::etext2) ElfSym::etext2->section = lastRO->lastSec; } if (last) { // _edata points to the end of the last mapped initialized section. OutputSection *edata = nullptr; for (OutputSection *os : outputSections) { if (os->type != SHT_NOBITS) edata = os; if (os == last->lastSec) break; } if (ElfSym::edata1) ElfSym::edata1->section = edata; if (ElfSym::edata2) ElfSym::edata2->section = edata; // _end is the first location after the uninitialized data region. if (ElfSym::end1) ElfSym::end1->section = last->lastSec; if (ElfSym::end2) ElfSym::end2->section = last->lastSec; } if (ElfSym::bss) ElfSym::bss->section = findSection(".bss"); // Setup MIPS _gp_disp/__gnu_local_gp symbols which should // be equal to the _gp symbol's value. if (ElfSym::mipsGp) { // Find GP-relative section with the lowest address // and use this address to calculate default _gp value. for (OutputSection *os : outputSections) { if (os->flags & SHF_MIPS_GPREL) { ElfSym::mipsGp->section = os; ElfSym::mipsGp->value = 0x7ff0; break; } } } } // We want to find how similar two ranks are. // The more branches in getSectionRank that match, the more similar they are. // Since each branch corresponds to a bit flag, we can just use // countLeadingZeros. static int getRankProximityAux(OutputSection *a, OutputSection *b) { return countLeadingZeros(a->sortRank ^ b->sortRank); } static int getRankProximity(OutputSection *a, BaseCommand *b) { auto *sec = dyn_cast<OutputSection>(b); return (sec && sec->hasInputSections) ? getRankProximityAux(a, sec) : -1; } // When placing orphan sections, we want to place them after symbol assignments // so that an orphan after // begin_foo = .; // foo : { *(foo) } // end_foo = .; // doesn't break the intended meaning of the begin/end symbols. // We don't want to go over sections since findOrphanPos is the // one in charge of deciding the order of the sections. // We don't want to go over changes to '.', since doing so in // rx_sec : { *(rx_sec) } // . = ALIGN(0x1000); // /* The RW PT_LOAD starts here*/ // rw_sec : { *(rw_sec) } // would mean that the RW PT_LOAD would become unaligned. static bool shouldSkip(BaseCommand *cmd) { if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) return assign->name != "."; return false; } // We want to place orphan sections so that they share as much // characteristics with their neighbors as possible. For example, if // both are rw, or both are tls. static std::vector<BaseCommand *>::iterator findOrphanPos(std::vector<BaseCommand *>::iterator b, std::vector<BaseCommand *>::iterator e) { OutputSection *sec = cast<OutputSection>(*e); // Find the first element that has as close a rank as possible. auto i = std::max_element(b, e, [=](BaseCommand *a, BaseCommand *b) { return getRankProximity(sec, a) < getRankProximity(sec, b); }); if (i == e) return e; // Consider all existing sections with the same proximity. int proximity = getRankProximity(sec, *i); for (; i != e; ++i) { auto *curSec = dyn_cast<OutputSection>(*i); if (!curSec || !curSec->hasInputSections) continue; if (getRankProximity(sec, curSec) != proximity || sec->sortRank < curSec->sortRank) break; } auto isOutputSecWithInputSections = [](BaseCommand *cmd) { auto *os = dyn_cast<OutputSection>(cmd); return os && os->hasInputSections; }; auto j = std::find_if(llvm::make_reverse_iterator(i), llvm::make_reverse_iterator(b), isOutputSecWithInputSections); i = j.base(); // As a special case, if the orphan section is the last section, put // it at the very end, past any other commands. // This matches bfd's behavior and is convenient when the linker script fully // specifies the start of the file, but doesn't care about the end (the non // alloc sections for example). auto nextSec = std::find_if(i, e, isOutputSecWithInputSections); if (nextSec == e) return e; while (i != e && shouldSkip(*i)) ++i; return i; } // Adds random priorities to sections not already in the map. static void maybeShuffle(DenseMap<const InputSectionBase *, int> &order) { if (!config->shuffleSectionSeed) return; std::vector<int> priorities(inputSections.size() - order.size()); // Existing priorities are < 0, so use priorities >= 0 for the missing // sections. int curPrio = 0; for (int &prio : priorities) prio = curPrio++; uint32_t seed = *config->shuffleSectionSeed; std::mt19937 g(seed ? seed : std::random_device()()); llvm::shuffle(priorities.begin(), priorities.end(), g); int prioIndex = 0; for (InputSectionBase *sec : inputSections) { if (order.try_emplace(sec, priorities[prioIndex]).second) ++prioIndex; } } // Builds section order for handling --symbol-ordering-file. static DenseMap<const InputSectionBase *, int> buildSectionOrder() { DenseMap<const InputSectionBase *, int> sectionOrder; // Use the rarely used option -call-graph-ordering-file to sort sections. if (!config->callGraphProfile.empty()) return computeCallGraphProfileOrder(); if (config->symbolOrderingFile.empty()) return sectionOrder; struct SymbolOrderEntry { int priority; bool present; }; // Build a map from symbols to their priorities. Symbols that didn't // appear in the symbol ordering file have the lowest priority 0. // All explicitly mentioned symbols have negative (higher) priorities. DenseMap<StringRef, SymbolOrderEntry> symbolOrder; int priority = -config->symbolOrderingFile.size(); for (StringRef s : config->symbolOrderingFile) symbolOrder.insert({s, {priority++, false}}); // Build a map from sections to their priorities. auto addSym = [&](Symbol &sym) { auto it = symbolOrder.find(sym.getName()); if (it == symbolOrder.end()) return; SymbolOrderEntry &ent = it->second; ent.present = true; maybeWarnUnorderableSymbol(&sym); if (auto *d = dyn_cast<Defined>(&sym)) { if (auto *sec = dyn_cast_or_null<InputSectionBase>(d->section)) { int &priority = sectionOrder[cast<InputSectionBase>(sec->repl)]; priority = std::min(priority, ent.priority); } } }; // We want both global and local symbols. We get the global ones from the // symbol table and iterate the object files for the local ones. for (Symbol *sym : symtab->symbols()) if (!sym->isLazy()) addSym(*sym); for (InputFile *file : objectFiles) for (Symbol *sym : file->getSymbols()) if (sym->isLocal()) addSym(*sym); if (config->warnSymbolOrdering) for (auto orderEntry : symbolOrder) if (!orderEntry.second.present) warn("symbol ordering file: no such symbol: " + orderEntry.first); return sectionOrder; } // Sorts the sections in ISD according to the provided section order. static void sortISDBySectionOrder(InputSectionDescription *isd, const DenseMap<const InputSectionBase *, int> &order) { std::vector<InputSection *> unorderedSections; std::vector<std::pair<InputSection *, int>> orderedSections; uint64_t unorderedSize = 0; for (InputSection *isec : isd->sections) { auto i = order.find(isec); if (i == order.end()) { unorderedSections.push_back(isec); unorderedSize += isec->getSize(); continue; } orderedSections.push_back({isec, i->second}); } llvm::sort(orderedSections, llvm::less_second()); // Find an insertion point for the ordered section list in the unordered // section list. On targets with limited-range branches, this is the mid-point // of the unordered section list. This decreases the likelihood that a range // extension thunk will be needed to enter or exit the ordered region. If the // ordered section list is a list of hot functions, we can generally expect // the ordered functions to be called more often than the unordered functions, // making it more likely that any particular call will be within range, and // therefore reducing the number of thunks required. // // For example, imagine that you have 8MB of hot code and 32MB of cold code. // If the layout is: // // 8MB hot // 32MB cold // // only the first 8-16MB of the cold code (depending on which hot function it // is actually calling) can call the hot code without a range extension thunk. // However, if we use this layout: // // 16MB cold // 8MB hot // 16MB cold // // both the last 8-16MB of the first block of cold code and the first 8-16MB // of the second block of cold code can call the hot code without a thunk. So // we effectively double the amount of code that could potentially call into // the hot code without a thunk. size_t insPt = 0; if (target->getThunkSectionSpacing() && !orderedSections.empty()) { uint64_t unorderedPos = 0; for (; insPt != unorderedSections.size(); ++insPt) { unorderedPos += unorderedSections[insPt]->getSize(); if (unorderedPos > unorderedSize / 2) break; } } isd->sections.clear(); for (InputSection *isec : makeArrayRef(unorderedSections).slice(0, insPt)) isd->sections.push_back(isec); for (std::pair<InputSection *, int> p : orderedSections) isd->sections.push_back(p.first); for (InputSection *isec : makeArrayRef(unorderedSections).slice(insPt)) isd->sections.push_back(isec); } static void sortSection(OutputSection *sec, const DenseMap<const InputSectionBase *, int> &order) { StringRef name = sec->name; // Never sort these. if (name == ".init" || name == ".fini") return; // Sort input sections by priority using the list provided by // --symbol-ordering-file or --shuffle-sections=. This is a least significant // digit radix sort. The sections may be sorted stably again by a more // significant key. if (!order.empty()) for (BaseCommand *b : sec->sectionCommands) if (auto *isd = dyn_cast<InputSectionDescription>(b)) sortISDBySectionOrder(isd, order); // Sort input sections by section name suffixes for // __attribute__((init_priority(N))). if (name == ".init_array" || name == ".fini_array") { if (!script->hasSectionsCommand) sec->sortInitFini(); return; } // Sort input sections by the special rule for .ctors and .dtors. if (name == ".ctors" || name == ".dtors") { if (!script->hasSectionsCommand) sec->sortCtorsDtors(); return; } // .toc is allocated just after .got and is accessed using GOT-relative // relocations. Object files compiled with small code model have an // addressable range of [.got, .got + 0xFFFC] for GOT-relative relocations. // To reduce the risk of relocation overflow, .toc contents are sorted so that // sections having smaller relocation offsets are at beginning of .toc if (config->emachine == EM_PPC64 && name == ".toc") { if (script->hasSectionsCommand) return; assert(sec->sectionCommands.size() == 1); auto *isd = cast<InputSectionDescription>(sec->sectionCommands[0]); llvm::stable_sort(isd->sections, [](const InputSection *a, const InputSection *b) -> bool { return a->file->ppc64SmallCodeModelTocRelocs && !b->file->ppc64SmallCodeModelTocRelocs; }); return; } } // If no layout was provided by linker script, we want to apply default // sorting for special input sections. This also handles --symbol-ordering-file. template <class ELFT> void Writer<ELFT>::sortInputSections() { // Build the order once since it is expensive. DenseMap<const InputSectionBase *, int> order = buildSectionOrder(); maybeShuffle(order); for (BaseCommand *base : script->sectionCommands) if (auto *sec = dyn_cast<OutputSection>(base)) sortSection(sec, order); } template <class ELFT> void Writer<ELFT>::sortSections() { script->adjustSectionsBeforeSorting(); // Don't sort if using -r. It is not necessary and we want to preserve the // relative order for SHF_LINK_ORDER sections. if (config->relocatable) return; sortInputSections(); for (BaseCommand *base : script->sectionCommands) { auto *os = dyn_cast<OutputSection>(base); if (!os) continue; os->sortRank = getSectionRank(os); // We want to assign rude approximation values to outSecOff fields // to know the relative order of the input sections. We use it for // sorting SHF_LINK_ORDER sections. See resolveShfLinkOrder(). uint64_t i = 0; for (InputSection *sec : getInputSections(os)) sec->outSecOff = i++; } if (!script->hasSectionsCommand) { // We know that all the OutputSections are contiguous in this case. auto isSection = [](BaseCommand *base) { return isa<OutputSection>(base); }; std::stable_sort( llvm::find_if(script->sectionCommands, isSection), llvm::find_if(llvm::reverse(script->sectionCommands), isSection).base(), compareSections); // Process INSERT commands. From this point onwards the order of // script->sectionCommands is fixed. script->processInsertCommands(); return; } script->processInsertCommands(); // Orphan sections are sections present in the input files which are // not explicitly placed into the output file by the linker script. // // The sections in the linker script are already in the correct // order. We have to figuere out where to insert the orphan // sections. // // The order of the sections in the script is arbitrary and may not agree with // compareSections. This means that we cannot easily define a strict weak // ordering. To see why, consider a comparison of a section in the script and // one not in the script. We have a two simple options: // * Make them equivalent (a is not less than b, and b is not less than a). // The problem is then that equivalence has to be transitive and we can // have sections a, b and c with only b in a script and a less than c // which breaks this property. // * Use compareSectionsNonScript. Given that the script order doesn't have // to match, we can end up with sections a, b, c, d where b and c are in the // script and c is compareSectionsNonScript less than b. In which case d // can be equivalent to c, a to b and d < a. As a concrete example: // .a (rx) # not in script // .b (rx) # in script // .c (ro) # in script // .d (ro) # not in script // // The way we define an order then is: // * Sort only the orphan sections. They are in the end right now. // * Move each orphan section to its preferred position. We try // to put each section in the last position where it can share // a PT_LOAD. // // There is some ambiguity as to where exactly a new entry should be // inserted, because Commands contains not only output section // commands but also other types of commands such as symbol assignment // expressions. There's no correct answer here due to the lack of the // formal specification of the linker script. We use heuristics to // determine whether a new output command should be added before or // after another commands. For the details, look at shouldSkip // function. auto i = script->sectionCommands.begin(); auto e = script->sectionCommands.end(); auto nonScriptI = std::find_if(i, e, [](BaseCommand *base) { if (auto *sec = dyn_cast<OutputSection>(base)) return sec->sectionIndex == UINT32_MAX; return false; }); // Sort the orphan sections. std::stable_sort(nonScriptI, e, compareSections); // As a horrible special case, skip the first . assignment if it is before any // section. We do this because it is common to set a load address by starting // the script with ". = 0xabcd" and the expectation is that every section is // after that. auto firstSectionOrDotAssignment = std::find_if(i, e, [](BaseCommand *cmd) { return !shouldSkip(cmd); }); if (firstSectionOrDotAssignment != e && isa<SymbolAssignment>(**firstSectionOrDotAssignment)) ++firstSectionOrDotAssignment; i = firstSectionOrDotAssignment; while (nonScriptI != e) { auto pos = findOrphanPos(i, nonScriptI); OutputSection *orphan = cast<OutputSection>(*nonScriptI); // As an optimization, find all sections with the same sort rank // and insert them with one rotate. unsigned rank = orphan->sortRank; auto end = std::find_if(nonScriptI + 1, e, [=](BaseCommand *cmd) { return cast<OutputSection>(cmd)->sortRank != rank; }); std::rotate(pos, nonScriptI, end); nonScriptI = end; } script->adjustSectionsAfterSorting(); } static bool compareByFilePosition(InputSection *a, InputSection *b) { InputSection *la = a->getLinkOrderDep(); InputSection *lb = b->getLinkOrderDep(); OutputSection *aOut = la->getParent(); OutputSection *bOut = lb->getParent(); if (aOut != bOut) return aOut->sectionIndex < bOut->sectionIndex; return la->outSecOff < lb->outSecOff; } template <class ELFT> void Writer<ELFT>::resolveShfLinkOrder() { for (OutputSection *sec : outputSections) { if (!(sec->flags & SHF_LINK_ORDER)) continue; // The ARM.exidx section use SHF_LINK_ORDER, but we have consolidated // this processing inside the ARMExidxsyntheticsection::finalizeContents(). if (!config->relocatable && config->emachine == EM_ARM && sec->type == SHT_ARM_EXIDX) continue; // Link order may be distributed across several InputSectionDescriptions // but sort must consider them all at once. std::vector<InputSection **> scriptSections; std::vector<InputSection *> sections; for (BaseCommand *base : sec->sectionCommands) { if (auto *isd = dyn_cast<InputSectionDescription>(base)) { for (InputSection *&isec : isd->sections) { scriptSections.push_back(&isec); sections.push_back(isec); InputSection *link = isec->getLinkOrderDep(); if (!link->getParent()) error(toString(isec) + ": sh_link points to discarded section " + toString(link)); } } } if (errorCount()) continue; llvm::stable_sort(sections, compareByFilePosition); for (int i = 0, n = sections.size(); i < n; ++i) *scriptSections[i] = sections[i]; } } // We need to generate and finalize the content that depends on the address of // InputSections. As the generation of the content may also alter InputSection // addresses we must converge to a fixed point. We do that here. See the comment // in Writer<ELFT>::finalizeSections(). template <class ELFT> void Writer<ELFT>::finalizeAddressDependentContent() { ThunkCreator tc; AArch64Err843419Patcher a64p; ARMErr657417Patcher a32p; script->assignAddresses(); int assignPasses = 0; for (;;) { bool changed = target->needsThunks && tc.createThunks(outputSections); // With Thunk Size much smaller than branch range we expect to // converge quickly; if we get to 10 something has gone wrong. if (changed && tc.pass >= 10) { error("thunk creation not converged"); break; } if (config->fixCortexA53Errata843419) { if (changed) script->assignAddresses(); changed |= a64p.createFixes(); } if (config->fixCortexA8) { if (changed) script->assignAddresses(); changed |= a32p.createFixes(); } if (in.mipsGot) in.mipsGot->updateAllocSize(); for (Partition &part : partitions) { changed |= part.relaDyn->updateAllocSize(); if (part.relrDyn) changed |= part.relrDyn->updateAllocSize(); } const Defined *changedSym = script->assignAddresses(); if (!changed) { // Some symbols may be dependent on section addresses. When we break the // loop, the symbol values are finalized because a previous // assignAddresses() finalized section addresses. if (!changedSym) break; if (++assignPasses == 5) { errorOrWarn("assignment to symbol " + toString(*changedSym) + " does not converge"); break; } } } // If a SECTIONS command is given, addrExpr, if set, is the specified output // section address. Warn if the computed value is different from the actual // address. if (!script->hasSectionsCommand) return; for (auto changed : script->changedSectionAddresses) { const OutputSection *os = changed.first; warn("start of section " + os->name + " changes from 0x" + utohexstr(changed.second) + " to 0x" + utohexstr(os->addr)); } } static void finalizeSynthetic(SyntheticSection *sec) { if (sec && sec->isNeeded() && sec->getParent()) sec->finalizeContents(); } // In order to allow users to manipulate linker-synthesized sections, // we had to add synthetic sections to the input section list early, // even before we make decisions whether they are needed. This allows // users to write scripts like this: ".mygot : { .got }". // // Doing it has an unintended side effects. If it turns out that we // don't need a .got (for example) at all because there's no // relocation that needs a .got, we don't want to emit .got. // // To deal with the above problem, this function is called after // scanRelocations is called to remove synthetic sections that turn // out to be empty. static void removeUnusedSyntheticSections() { // All input synthetic sections that can be empty are placed after // all regular ones. We iterate over them all and exit at first // non-synthetic. for (InputSectionBase *s : llvm::reverse(inputSections)) { SyntheticSection *ss = dyn_cast<SyntheticSection>(s); if (!ss) return; OutputSection *os = ss->getParent(); if (!os || ss->isNeeded()) continue; // If we reach here, then ss is an unused synthetic section and we want to // remove it from the corresponding input section description, and // orphanSections. for (BaseCommand *b : os->sectionCommands) if (auto *isd = dyn_cast<InputSectionDescription>(b)) llvm::erase_if(isd->sections, [=](InputSection *isec) { return isec == ss; }); llvm::erase_if(script->orphanSections, [=](const InputSectionBase *isec) { return isec == ss; }); } } // Create output section objects and add them to OutputSections. template <class ELFT> void Writer<ELFT>::finalizeSections() { Out::preinitArray = findSection(".preinit_array"); Out::initArray = findSection(".init_array"); Out::finiArray = findSection(".fini_array"); // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop // symbols for sections, so that the runtime can get the start and end // addresses of each section by section name. Add such symbols. if (!config->relocatable) { addStartEndSymbols(); for (BaseCommand *base : script->sectionCommands) if (auto *sec = dyn_cast<OutputSection>(base)) addStartStopSymbols(sec); } // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type. // It should be okay as no one seems to care about the type. // Even the author of gold doesn't remember why gold behaves that way. // https://sourceware.org/ml/binutils/2002-03/msg00360.html if (mainPart->dynamic->parent) symtab->addSymbol(Defined{/*file=*/nullptr, "_DYNAMIC", STB_WEAK, STV_HIDDEN, STT_NOTYPE, /*value=*/0, /*size=*/0, mainPart->dynamic}); // Define __rel[a]_iplt_{start,end} symbols if needed. addRelIpltSymbols(); // RISC-V's gp can address +/- 2 KiB, set it to .sdata + 0x800. This symbol // should only be defined in an executable. If .sdata does not exist, its // value/section does not matter but it has to be relative, so set its // st_shndx arbitrarily to 1 (Out::elfHeader). if (config->emachine == EM_RISCV && !config->shared) { OutputSection *sec = findSection(".sdata"); ElfSym::riscvGlobalPointer = addOptionalRegular("__global_pointer$", sec ? sec : Out::elfHeader, 0x800, STV_DEFAULT, STB_GLOBAL); } if (config->emachine == EM_X86_64) { // On targets that support TLSDESC, _TLS_MODULE_BASE_ is defined in such a // way that: // // 1) Without relaxation: it produces a dynamic TLSDESC relocation that // computes 0. // 2) With LD->LE relaxation: _TLS_MODULE_BASE_@tpoff = 0 (lowest address in // the TLS block). // // 2) is special cased in @tpoff computation. To satisfy 1), we define it as // an absolute symbol of zero. This is different from GNU linkers which // define _TLS_MODULE_BASE_ relative to the first TLS section. Symbol *s = symtab->find("_TLS_MODULE_BASE_"); if (s && s->isUndefined()) { s->resolve(Defined{/*file=*/nullptr, s->getName(), STB_GLOBAL, STV_HIDDEN, STT_TLS, /*value=*/0, 0, /*section=*/nullptr}); ElfSym::tlsModuleBase = cast<Defined>(s); } } // This responsible for splitting up .eh_frame section into // pieces. The relocation scan uses those pieces, so this has to be // earlier. for (Partition &part : partitions) finalizeSynthetic(part.ehFrame); for (Symbol *sym : symtab->symbols()) sym->isPreemptible = computeIsPreemptible(*sym); // Change values of linker-script-defined symbols from placeholders (assigned // by declareSymbols) to actual definitions. script->processSymbolAssignments(); // Scan relocations. This must be done after every symbol is declared so that // we can correctly decide if a dynamic relocation is needed. This is called // after processSymbolAssignments() because it needs to know whether a // linker-script-defined symbol is absolute. if (!config->relocatable) { forEachRelSec(scanRelocations<ELFT>); reportUndefinedSymbols<ELFT>(); } if (in.plt && in.plt->isNeeded()) in.plt->addSymbols(); if (in.iplt && in.iplt->isNeeded()) in.iplt->addSymbols(); if (!config->allowShlibUndefined) { // Error on undefined symbols in a shared object, if all of its DT_NEEDED // entries are seen. These cases would otherwise lead to runtime errors // reported by the dynamic linker. // // ld.bfd traces all DT_NEEDED to emulate the logic of the dynamic linker to // catch more cases. That is too much for us. Our approach resembles the one // used in ld.gold, achieves a good balance to be useful but not too smart. for (SharedFile *file : sharedFiles) file->allNeededIsKnown = llvm::all_of(file->dtNeeded, [&](StringRef needed) { return symtab->soNames.count(needed); }); for (Symbol *sym : symtab->symbols()) if (sym->isUndefined() && !sym->isWeak()) if (auto *f = dyn_cast_or_null<SharedFile>(sym->file)) if (f->allNeededIsKnown) error(toString(f) + ": undefined reference to " + toString(*sym)); } // Now that we have defined all possible global symbols including linker- // synthesized ones. Visit all symbols to give the finishing touches. for (Symbol *sym : symtab->symbols()) { if (!includeInSymtab(*sym)) continue; if (in.symTab) in.symTab->addSymbol(sym); if (sym->includeInDynsym()) { partitions[sym->partition - 1].dynSymTab->addSymbol(sym); if (auto *file = dyn_cast_or_null<SharedFile>(sym->file)) if (file->isNeeded && !sym->isUndefined()) addVerneed(sym); } } // We also need to scan the dynamic relocation tables of the other partitions // and add any referenced symbols to the partition's dynsym. for (Partition &part : MutableArrayRef<Partition>(partitions).slice(1)) { DenseSet<Symbol *> syms; for (const SymbolTableEntry &e : part.dynSymTab->getSymbols()) syms.insert(e.sym); for (DynamicReloc &reloc : part.relaDyn->relocs) if (reloc.sym && !reloc.useSymVA && syms.insert(reloc.sym).second) part.dynSymTab->addSymbol(reloc.sym); } // Do not proceed if there was an undefined symbol. if (errorCount()) return; if (in.mipsGot) in.mipsGot->build(); removeUnusedSyntheticSections(); script->diagnoseOrphanHandling(); sortSections(); // Now that we have the final list, create a list of all the // OutputSections for convenience. for (BaseCommand *base : script->sectionCommands) if (auto *sec = dyn_cast<OutputSection>(base)) outputSections.push_back(sec); // Prefer command line supplied address over other constraints. for (OutputSection *sec : outputSections) { auto i = config->sectionStartMap.find(sec->name); if (i != config->sectionStartMap.end()) sec->addrExpr = [=] { return i->second; }; } // This is a bit of a hack. A value of 0 means undef, so we set it // to 1 to make __ehdr_start defined. The section number is not // particularly relevant. Out::elfHeader->sectionIndex = 1; for (size_t i = 0, e = outputSections.size(); i != e; ++i) { OutputSection *sec = outputSections[i]; sec->sectionIndex = i + 1; sec->shName = in.shStrTab->addString(sec->name); } // Binary and relocatable output does not have PHDRS. // The headers have to be created before finalize as that can influence the // image base and the dynamic section on mips includes the image base. if (!config->relocatable && !config->oFormatBinary) { for (Partition &part : partitions) { part.phdrs = script->hasPhdrsCommands() ? script->createPhdrs() : createPhdrs(part); if (config->emachine == EM_ARM) { // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME addPhdrForSection(part, SHT_ARM_EXIDX, PT_ARM_EXIDX, PF_R); } if (config->emachine == EM_MIPS) { // Add separate segments for MIPS-specific sections. addPhdrForSection(part, SHT_MIPS_REGINFO, PT_MIPS_REGINFO, PF_R); addPhdrForSection(part, SHT_MIPS_OPTIONS, PT_MIPS_OPTIONS, PF_R); addPhdrForSection(part, SHT_MIPS_ABIFLAGS, PT_MIPS_ABIFLAGS, PF_R); } } Out::programHeaders->size = sizeof(Elf_Phdr) * mainPart->phdrs.size(); // Find the TLS segment. This happens before the section layout loop so that // Android relocation packing can look up TLS symbol addresses. We only need // to care about the main partition here because all TLS symbols were moved // to the main partition (see MarkLive.cpp). for (PhdrEntry *p : mainPart->phdrs) if (p->p_type == PT_TLS) Out::tlsPhdr = p; } // Some symbols are defined in term of program headers. Now that we // have the headers, we can find out which sections they point to. setReservedSymbolSections(); finalizeSynthetic(in.bss); finalizeSynthetic(in.bssRelRo); finalizeSynthetic(in.symTabShndx); finalizeSynthetic(in.shStrTab); finalizeSynthetic(in.strTab); finalizeSynthetic(in.got); finalizeSynthetic(in.mipsGot); finalizeSynthetic(in.igotPlt); finalizeSynthetic(in.gotPlt); finalizeSynthetic(in.relaIplt); finalizeSynthetic(in.relaPlt); finalizeSynthetic(in.plt); finalizeSynthetic(in.iplt); finalizeSynthetic(in.ppc32Got2); finalizeSynthetic(in.partIndex); // Dynamic section must be the last one in this list and dynamic // symbol table section (dynSymTab) must be the first one. for (Partition &part : partitions) { finalizeSynthetic(part.armExidx); finalizeSynthetic(part.dynSymTab); finalizeSynthetic(part.gnuHashTab); finalizeSynthetic(part.hashTab); finalizeSynthetic(part.verDef); finalizeSynthetic(part.relaDyn); finalizeSynthetic(part.relrDyn); finalizeSynthetic(part.ehFrameHdr); finalizeSynthetic(part.verSym); finalizeSynthetic(part.verNeed); finalizeSynthetic(part.dynamic); } if (!script->hasSectionsCommand && !config->relocatable) fixSectionAlignments(); // SHFLinkOrder processing must be processed after relative section placements are // known but before addresses are allocated. resolveShfLinkOrder(); if (errorCount()) return; // This is used to: // 1) Create "thunks": // Jump instructions in many ISAs have small displacements, and therefore // they cannot jump to arbitrary addresses in memory. For example, RISC-V // JAL instruction can target only +-1 MiB from PC. It is a linker's // responsibility to create and insert small pieces of code between // sections to extend the ranges if jump targets are out of range. Such // code pieces are called "thunks". // // We add thunks at this stage. We couldn't do this before this point // because this is the earliest point where we know sizes of sections and // their layouts (that are needed to determine if jump targets are in // range). // // 2) Update the sections. We need to generate content that depends on the // address of InputSections. For example, MIPS GOT section content or // android packed relocations sections content. // // 3) Assign the final values for the linker script symbols. Linker scripts // sometimes using forward symbol declarations. We want to set the correct // values. They also might change after adding the thunks. finalizeAddressDependentContent(); // finalizeAddressDependentContent may have added local symbols to the static symbol table. finalizeSynthetic(in.symTab); finalizeSynthetic(in.ppc64LongBranchTarget); // Fill other section headers. The dynamic table is finalized // at the end because some tags like RELSZ depend on result // of finalizing other sections. for (OutputSection *sec : outputSections) sec->finalize(); } // Ensure data sections are not mixed with executable sections when // -execute-only is used. -execute-only is a feature to make pages executable // but not readable, and the feature is currently supported only on AArch64. template <class ELFT> void Writer<ELFT>::checkExecuteOnly() { if (!config->executeOnly) return; for (OutputSection *os : outputSections) if (os->flags & SHF_EXECINSTR) for (InputSection *isec : getInputSections(os)) if (!(isec->flags & SHF_EXECINSTR)) error("cannot place " + toString(isec) + " into " + toString(os->name) + ": -execute-only does not support intermingling data and code"); } // The linker is expected to define SECNAME_start and SECNAME_end // symbols for a few sections. This function defines them. template <class ELFT> void Writer<ELFT>::addStartEndSymbols() { // If a section does not exist, there's ambiguity as to how we // define _start and _end symbols for an init/fini section. Since // the loader assume that the symbols are always defined, we need to // always define them. But what value? The loader iterates over all // pointers between _start and _end to run global ctors/dtors, so if // the section is empty, their symbol values don't actually matter // as long as _start and _end point to the same location. // // That said, we don't want to set the symbols to 0 (which is // probably the simplest value) because that could cause some // program to fail to link due to relocation overflow, if their // program text is above 2 GiB. We use the address of the .text // section instead to prevent that failure. // // In rare situations, the .text section may not exist. If that's the // case, use the image base address as a last resort. OutputSection *Default = findSection(".text"); if (!Default) Default = Out::elfHeader; auto define = [=](StringRef start, StringRef end, OutputSection *os) { if (os) { addOptionalRegular(start, os, 0); addOptionalRegular(end, os, -1); } else { addOptionalRegular(start, Default, 0); addOptionalRegular(end, Default, 0); } }; define("__preinit_array_start", "__preinit_array_end", Out::preinitArray); define("__init_array_start", "__init_array_end", Out::initArray); define("__fini_array_start", "__fini_array_end", Out::finiArray); if (OutputSection *sec = findSection(".ARM.exidx")) define("__exidx_start", "__exidx_end", sec); } // If a section name is valid as a C identifier (which is rare because of // the leading '.'), linkers are expected to define __start_<secname> and // __stop_<secname> symbols. They are at beginning and end of the section, // respectively. This is not requested by the ELF standard, but GNU ld and // gold provide the feature, and used by many programs. template <class ELFT> void Writer<ELFT>::addStartStopSymbols(OutputSection *sec) { StringRef s = sec->name; if (!isValidCIdentifier(s)) return; addOptionalRegular(saver.save("__start_" + s), sec, 0, STV_PROTECTED); addOptionalRegular(saver.save("__stop_" + s), sec, -1, STV_PROTECTED); } static bool needsPtLoad(OutputSection *sec) { if (!(sec->flags & SHF_ALLOC) || sec->noload) return false; // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is // responsible for allocating space for them, not the PT_LOAD that // contains the TLS initialization image. if ((sec->flags & SHF_TLS) && sec->type == SHT_NOBITS) return false; return true; } // Linker scripts are responsible for aligning addresses. Unfortunately, most // linker scripts are designed for creating two PT_LOADs only, one RX and one // RW. This means that there is no alignment in the RO to RX transition and we // cannot create a PT_LOAD there. static uint64_t computeFlags(uint64_t flags) { if (config->omagic) return PF_R | PF_W | PF_X; if (config->executeOnly && (flags & PF_X)) return flags & ~PF_R; if (config->singleRoRx && !(flags & PF_W)) return flags | PF_X; return flags; } // Decide which program headers to create and which sections to include in each // one. template <class ELFT> std::vector<PhdrEntry *> Writer<ELFT>::createPhdrs(Partition &part) { std::vector<PhdrEntry *> ret; auto addHdr = [&](unsigned type, unsigned flags) -> PhdrEntry * { ret.push_back(make<PhdrEntry>(type, flags)); return ret.back(); }; unsigned partNo = part.getNumber(); bool isMain = partNo == 1; // Add the first PT_LOAD segment for regular output sections. uint64_t flags = computeFlags(PF_R); PhdrEntry *load = nullptr; // nmagic or omagic output does not have PT_PHDR, PT_INTERP, or the readonly // PT_LOAD. if (!config->nmagic && !config->omagic) { // The first phdr entry is PT_PHDR which describes the program header // itself. if (isMain) addHdr(PT_PHDR, PF_R)->add(Out::programHeaders); else addHdr(PT_PHDR, PF_R)->add(part.programHeaders->getParent()); // PT_INTERP must be the second entry if exists. if (OutputSection *cmd = findSection(".interp", partNo)) addHdr(PT_INTERP, cmd->getPhdrFlags())->add(cmd); // Add the headers. We will remove them if they don't fit. // In the other partitions the headers are ordinary sections, so they don't // need to be added here. if (isMain) { load = addHdr(PT_LOAD, flags); load->add(Out::elfHeader); load->add(Out::programHeaders); } } // PT_GNU_RELRO includes all sections that should be marked as // read-only by dynamic linker after processing relocations. // Current dynamic loaders only support one PT_GNU_RELRO PHDR, give // an error message if more than one PT_GNU_RELRO PHDR is required. PhdrEntry *relRo = make<PhdrEntry>(PT_GNU_RELRO, PF_R); bool inRelroPhdr = false; OutputSection *relroEnd = nullptr; for (OutputSection *sec : outputSections) { if (sec->partition != partNo || !needsPtLoad(sec)) continue; if (isRelroSection(sec)) { inRelroPhdr = true; if (!relroEnd) relRo->add(sec); else error("section: " + sec->name + " is not contiguous with other relro" + " sections"); } else if (inRelroPhdr) { inRelroPhdr = false; relroEnd = sec; } } for (OutputSection *sec : outputSections) { if (!(sec->flags & SHF_ALLOC)) break; if (!needsPtLoad(sec)) continue; // Normally, sections in partitions other than the current partition are // ignored. But partition number 255 is a special case: it contains the // partition end marker (.part.end). It needs to be added to the main // partition so that a segment is created for it in the main partition, // which will cause the dynamic loader to reserve space for the other // partitions. if (sec->partition != partNo) { if (isMain && sec->partition == 255) addHdr(PT_LOAD, computeFlags(sec->getPhdrFlags()))->add(sec); continue; } // Segments are contiguous memory regions that has the same attributes // (e.g. executable or writable). There is one phdr for each segment. // Therefore, we need to create a new phdr when the next section has // different flags or is loaded at a discontiguous address or memory // region using AT or AT> linker script command, respectively. At the same // time, we don't want to create a separate load segment for the headers, // even if the first output section has an AT or AT> attribute. uint64_t newFlags = computeFlags(sec->getPhdrFlags()); bool sameLMARegion = load && !sec->lmaExpr && sec->lmaRegion == load->firstSec->lmaRegion; if (!(load && newFlags == flags && sec != relroEnd && sec->memRegion == load->firstSec->memRegion && (sameLMARegion || load->lastSec == Out::programHeaders))) { load = addHdr(PT_LOAD, newFlags); flags = newFlags; } load->add(sec); } // Add a TLS segment if any. PhdrEntry *tlsHdr = make<PhdrEntry>(PT_TLS, PF_R); for (OutputSection *sec : outputSections) if (sec->partition == partNo && sec->flags & SHF_TLS) tlsHdr->add(sec); if (tlsHdr->firstSec) ret.push_back(tlsHdr); // Add an entry for .dynamic. if (OutputSection *sec = part.dynamic->getParent()) addHdr(PT_DYNAMIC, sec->getPhdrFlags())->add(sec); if (relRo->firstSec) ret.push_back(relRo); // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr. if (part.ehFrame->isNeeded() && part.ehFrameHdr && part.ehFrame->getParent() && part.ehFrameHdr->getParent()) addHdr(PT_GNU_EH_FRAME, part.ehFrameHdr->getParent()->getPhdrFlags()) ->add(part.ehFrameHdr->getParent()); // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes // the dynamic linker fill the segment with random data. if (OutputSection *cmd = findSection(".openbsd.randomdata", partNo)) addHdr(PT_OPENBSD_RANDOMIZE, cmd->getPhdrFlags())->add(cmd); if (config->zGnustack != GnuStackKind::None) { // PT_GNU_STACK is a special section to tell the loader to make the // pages for the stack non-executable. If you really want an executable // stack, you can pass -z execstack, but that's not recommended for // security reasons. unsigned perm = PF_R | PF_W; if (config->zGnustack == GnuStackKind::Exec) perm |= PF_X; addHdr(PT_GNU_STACK, perm)->p_memsz = config->zStackSize; } // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable // is expected to perform W^X violations, such as calling mprotect(2) or // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on // OpenBSD. if (config->zWxneeded) addHdr(PT_OPENBSD_WXNEEDED, PF_X); if (OutputSection *cmd = findSection(".note.gnu.property", partNo)) addHdr(PT_GNU_PROPERTY, PF_R)->add(cmd); // Create one PT_NOTE per a group of contiguous SHT_NOTE sections with the // same alignment. PhdrEntry *note = nullptr; for (OutputSection *sec : outputSections) { if (sec->partition != partNo) continue; if (sec->type == SHT_NOTE && (sec->flags & SHF_ALLOC)) { if (!note || sec->lmaExpr || note->lastSec->alignment != sec->alignment) note = addHdr(PT_NOTE, PF_R); note->add(sec); } else { note = nullptr; } } return ret; } template <class ELFT> void Writer<ELFT>::addPhdrForSection(Partition &part, unsigned shType, unsigned pType, unsigned pFlags) { unsigned partNo = part.getNumber(); auto i = llvm::find_if(outputSections, [=](OutputSection *cmd) { return cmd->partition == partNo && cmd->type == shType; }); if (i == outputSections.end()) return; PhdrEntry *entry = make<PhdrEntry>(pType, pFlags); entry->add(*i); part.phdrs.push_back(entry); } // Place the first section of each PT_LOAD to a different page (of maxPageSize). // This is achieved by assigning an alignment expression to addrExpr of each // such section. template <class ELFT> void Writer<ELFT>::fixSectionAlignments() { const PhdrEntry *prev; auto pageAlign = [&](const PhdrEntry *p) { OutputSection *cmd = p->firstSec; if (!cmd) return; cmd->alignExpr = [align = cmd->alignment]() { return align; }; if (!cmd->addrExpr) { // Prefer advancing to align(dot, maxPageSize) + dot%maxPageSize to avoid // padding in the file contents. // // When -z separate-code is used we must not have any overlap in pages // between an executable segment and a non-executable segment. We align to // the next maximum page size boundary on transitions between executable // and non-executable segments. // // SHT_LLVM_PART_EHDR marks the start of a partition. The partition // sections will be extracted to a separate file. Align to the next // maximum page size boundary so that we can find the ELF header at the // start. We cannot benefit from overlapping p_offset ranges with the // previous segment anyway. if (config->zSeparate == SeparateSegmentKind::Loadable || (config->zSeparate == SeparateSegmentKind::Code && prev && (prev->p_flags & PF_X) != (p->p_flags & PF_X)) || cmd->type == SHT_LLVM_PART_EHDR) cmd->addrExpr = [] { return alignTo(script->getDot(), config->maxPageSize); }; // PT_TLS is at the start of the first RW PT_LOAD. If `p` includes PT_TLS, // it must be the RW. Align to p_align(PT_TLS) to make sure // p_vaddr(PT_LOAD)%p_align(PT_LOAD) = 0. Otherwise, if // sh_addralign(.tdata) < sh_addralign(.tbss), we will set p_align(PT_TLS) // to sh_addralign(.tbss), while p_vaddr(PT_TLS)=p_vaddr(PT_LOAD) may not // be congruent to 0 modulo p_align(PT_TLS). // // Technically this is not required, but as of 2019, some dynamic loaders // don't handle p_vaddr%p_align != 0 correctly, e.g. glibc (i386 and // x86-64) doesn't make runtime address congruent to p_vaddr modulo // p_align for dynamic TLS blocks (PR/24606), FreeBSD rtld has the same // bug, musl (TLS Variant 1 architectures) before 1.1.23 handled TLS // blocks correctly. We need to keep the workaround for a while. else if (Out::tlsPhdr && Out::tlsPhdr->firstSec == p->firstSec) cmd->addrExpr = [] { return alignTo(script->getDot(), config->maxPageSize) + alignTo(script->getDot() % config->maxPageSize, Out::tlsPhdr->p_align); }; else cmd->addrExpr = [] { return alignTo(script->getDot(), config->maxPageSize) + script->getDot() % config->maxPageSize; }; } }; for (Partition &part : partitions) { prev = nullptr; for (const PhdrEntry *p : part.phdrs) if (p->p_type == PT_LOAD && p->firstSec) { pageAlign(p); prev = p; } } } // Compute an in-file position for a given section. The file offset must be the // same with its virtual address modulo the page size, so that the loader can // load executables without any address adjustment. static uint64_t computeFileOffset(OutputSection *os, uint64_t off) { // The first section in a PT_LOAD has to have congruent offset and address // modulo the maximum page size. if (os->ptLoad && os->ptLoad->firstSec == os) return alignTo(off, os->ptLoad->p_align, os->addr); // File offsets are not significant for .bss sections other than the first one // in a PT_LOAD. By convention, we keep section offsets monotonically // increasing rather than setting to zero. if (os->type == SHT_NOBITS) return off; // If the section is not in a PT_LOAD, we just have to align it. if (!os->ptLoad) return alignTo(off, os->alignment); // If two sections share the same PT_LOAD the file offset is calculated // using this formula: Off2 = Off1 + (VA2 - VA1). OutputSection *first = os->ptLoad->firstSec; return first->offset + os->addr - first->addr; } // Set an in-file position to a given section and returns the end position of // the section. static uint64_t setFileOffset(OutputSection *os, uint64_t off) { off = computeFileOffset(os, off); os->offset = off; if (os->type == SHT_NOBITS) return off; return off + os->size; } template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() { uint64_t off = 0; for (OutputSection *sec : outputSections) if (sec->flags & SHF_ALLOC) off = setFileOffset(sec, off); fileSize = alignTo(off, config->wordsize); } static std::string rangeToString(uint64_t addr, uint64_t len) { return "[0x" + utohexstr(addr) + ", 0x" + utohexstr(addr + len - 1) + "]"; } // Assign file offsets to output sections. template <class ELFT> void Writer<ELFT>::assignFileOffsets() { uint64_t off = 0; off = setFileOffset(Out::elfHeader, off); off = setFileOffset(Out::programHeaders, off); PhdrEntry *lastRX = nullptr; for (Partition &part : partitions) for (PhdrEntry *p : part.phdrs) if (p->p_type == PT_LOAD && (p->p_flags & PF_X)) lastRX = p; for (OutputSection *sec : outputSections) { off = setFileOffset(sec, off); // If this is a last section of the last executable segment and that // segment is the last loadable segment, align the offset of the // following section to avoid loading non-segments parts of the file. if (config->zSeparate != SeparateSegmentKind::None && lastRX && lastRX->lastSec == sec) off = alignTo(off, config->commonPageSize); } sectionHeaderOff = alignTo(off, config->wordsize); fileSize = sectionHeaderOff + (outputSections.size() + 1) * sizeof(Elf_Shdr); // Our logic assumes that sections have rising VA within the same segment. // With use of linker scripts it is possible to violate this rule and get file // offset overlaps or overflows. That should never happen with a valid script // which does not move the location counter backwards and usually scripts do // not do that. Unfortunately, there are apps in the wild, for example, Linux // kernel, which control segment distribution explicitly and move the counter // backwards, so we have to allow doing that to support linking them. We // perform non-critical checks for overlaps in checkSectionOverlap(), but here // we want to prevent file size overflows because it would crash the linker. for (OutputSection *sec : outputSections) { if (sec->type == SHT_NOBITS) continue; if ((sec->offset > fileSize) || (sec->offset + sec->size > fileSize)) error("unable to place section " + sec->name + " at file offset " + rangeToString(sec->offset, sec->size) + "; check your linker script for overflows"); } } // Finalize the program headers. We call this function after we assign // file offsets and VAs to all sections. template <class ELFT> void Writer<ELFT>::setPhdrs(Partition &part) { for (PhdrEntry *p : part.phdrs) { OutputSection *first = p->firstSec; OutputSection *last = p->lastSec; if (first) { p->p_filesz = last->offset - first->offset; if (last->type != SHT_NOBITS) p->p_filesz += last->size; p->p_memsz = last->addr + last->size - first->addr; p->p_offset = first->offset; p->p_vaddr = first->addr; // File offsets in partitions other than the main partition are relative // to the offset of the ELF headers. Perform that adjustment now. if (part.elfHeader) p->p_offset -= part.elfHeader->getParent()->offset; if (!p->hasLMA) p->p_paddr = first->getLMA(); } if (p->p_type == PT_GNU_RELRO) { p->p_align = 1; // musl/glibc ld.so rounds the size down, so we need to round up // to protect the last page. This is a no-op on FreeBSD which always // rounds up. p->p_memsz = alignTo(p->p_offset + p->p_memsz, config->commonPageSize) - p->p_offset; } } } // A helper struct for checkSectionOverlap. namespace { struct SectionOffset { OutputSection *sec; uint64_t offset; }; } // namespace // Check whether sections overlap for a specific address range (file offsets, // load and virtual addresses). static void checkOverlap(StringRef name, std::vector<SectionOffset> &sections, bool isVirtualAddr) { llvm::sort(sections, [=](const SectionOffset &a, const SectionOffset &b) { return a.offset < b.offset; }); // Finding overlap is easy given a vector is sorted by start position. // If an element starts before the end of the previous element, they overlap. for (size_t i = 1, end = sections.size(); i < end; ++i) { SectionOffset a = sections[i - 1]; SectionOffset b = sections[i]; if (b.offset >= a.offset + a.sec->size) continue; // If both sections are in OVERLAY we allow the overlapping of virtual // addresses, because it is what OVERLAY was designed for. if (isVirtualAddr && a.sec->inOverlay && b.sec->inOverlay) continue; errorOrWarn("section " + a.sec->name + " " + name + " range overlaps with " + b.sec->name + "\n>>> " + a.sec->name + " range is " + rangeToString(a.offset, a.sec->size) + "\n>>> " + b.sec->name + " range is " + rangeToString(b.offset, b.sec->size)); } } // Check for overlapping sections and address overflows. // // In this function we check that none of the output sections have overlapping // file offsets. For SHF_ALLOC sections we also check that the load address // ranges and the virtual address ranges don't overlap template <class ELFT> void Writer<ELFT>::checkSections() { // First, check that section's VAs fit in available address space for target. for (OutputSection *os : outputSections) if ((os->addr + os->size < os->addr) || (!ELFT::Is64Bits && os->addr + os->size > UINT32_MAX)) errorOrWarn("section " + os->name + " at 0x" + utohexstr(os->addr) + " of size 0x" + utohexstr(os->size) + " exceeds available address space"); // Check for overlapping file offsets. In this case we need to skip any // section marked as SHT_NOBITS. These sections don't actually occupy space in // the file so Sec->Offset + Sec->Size can overlap with others. If --oformat // binary is specified only add SHF_ALLOC sections are added to the output // file so we skip any non-allocated sections in that case. std::vector<SectionOffset> fileOffs; for (OutputSection *sec : outputSections) if (sec->size > 0 && sec->type != SHT_NOBITS && (!config->oFormatBinary || (sec->flags & SHF_ALLOC))) fileOffs.push_back({sec, sec->offset}); checkOverlap("file", fileOffs, false); // When linking with -r there is no need to check for overlapping virtual/load // addresses since those addresses will only be assigned when the final // executable/shared object is created. if (config->relocatable) return; // Checking for overlapping virtual and load addresses only needs to take // into account SHF_ALLOC sections since others will not be loaded. // Furthermore, we also need to skip SHF_TLS sections since these will be // mapped to other addresses at runtime and can therefore have overlapping // ranges in the file. std::vector<SectionOffset> vmas; for (OutputSection *sec : outputSections) if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS)) vmas.push_back({sec, sec->addr}); checkOverlap("virtual address", vmas, true); // Finally, check that the load addresses don't overlap. This will usually be // the same as the virtual addresses but can be different when using a linker // script with AT(). std::vector<SectionOffset> lmas; for (OutputSection *sec : outputSections) if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS)) lmas.push_back({sec, sec->getLMA()}); checkOverlap("load address", lmas, false); } // The entry point address is chosen in the following ways. // // 1. the '-e' entry command-line option; // 2. the ENTRY(symbol) command in a linker control script; // 3. the value of the symbol _start, if present; // 4. the number represented by the entry symbol, if it is a number; // 5. the address of the first byte of the .text section, if present; // 6. the address 0. static uint64_t getEntryAddr() { // Case 1, 2 or 3 if (Symbol *b = symtab->find(config->entry)) return b->getVA(); // Case 4 uint64_t addr; if (to_integer(config->entry, addr)) return addr; // Case 5 if (OutputSection *sec = findSection(".text")) { if (config->warnMissingEntry) warn("cannot find entry symbol " + config->entry + "; defaulting to 0x" + utohexstr(sec->addr)); return sec->addr; } // Case 6 if (config->warnMissingEntry) warn("cannot find entry symbol " + config->entry + "; not setting start address"); return 0; } static uint16_t getELFType() { if (config->isPic) return ET_DYN; if (config->relocatable) return ET_REL; return ET_EXEC; } template <class ELFT> void Writer<ELFT>::writeHeader() { writeEhdr<ELFT>(Out::bufferStart, *mainPart); writePhdrs<ELFT>(Out::bufferStart + sizeof(Elf_Ehdr), *mainPart); auto *eHdr = reinterpret_cast<Elf_Ehdr *>(Out::bufferStart); eHdr->e_type = getELFType(); eHdr->e_entry = getEntryAddr(); eHdr->e_shoff = sectionHeaderOff; // Write the section header table. // // The ELF header can only store numbers up to SHN_LORESERVE in the e_shnum // and e_shstrndx fields. When the value of one of these fields exceeds // SHN_LORESERVE ELF requires us to put sentinel values in the ELF header and // use fields in the section header at index 0 to store // the value. The sentinel values and fields are: // e_shnum = 0, SHdrs[0].sh_size = number of sections. // e_shstrndx = SHN_XINDEX, SHdrs[0].sh_link = .shstrtab section index. auto *sHdrs = reinterpret_cast<Elf_Shdr *>(Out::bufferStart + eHdr->e_shoff); size_t num = outputSections.size() + 1; if (num >= SHN_LORESERVE) sHdrs->sh_size = num; else eHdr->e_shnum = num; uint32_t strTabIndex = in.shStrTab->getParent()->sectionIndex; if (strTabIndex >= SHN_LORESERVE) { sHdrs->sh_link = strTabIndex; eHdr->e_shstrndx = SHN_XINDEX; } else { eHdr->e_shstrndx = strTabIndex; } for (OutputSection *sec : outputSections) sec->writeHeaderTo<ELFT>(++sHdrs); } // Open a result file. template <class ELFT> void Writer<ELFT>::openFile() { uint64_t maxSize = config->is64 ? INT64_MAX : UINT32_MAX; if (fileSize != size_t(fileSize) || maxSize < fileSize) { error("output file too large: " + Twine(fileSize) + " bytes"); return; } unlinkAsync(config->outputFile); unsigned flags = 0; if (!config->relocatable) flags |= FileOutputBuffer::F_executable; if (!config->mmapOutputFile) flags |= FileOutputBuffer::F_no_mmap; Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr = FileOutputBuffer::create(config->outputFile, fileSize, flags); if (!bufferOrErr) { error("failed to open " + config->outputFile + ": " + llvm::toString(bufferOrErr.takeError())); return; } buffer = std::move(*bufferOrErr); Out::bufferStart = buffer->getBufferStart(); } template <class ELFT> void Writer<ELFT>::writeSectionsBinary() { for (OutputSection *sec : outputSections) if (sec->flags & SHF_ALLOC) sec->writeTo<ELFT>(Out::bufferStart + sec->offset); } static void fillTrap(uint8_t *i, uint8_t *end) { for (; i + 4 <= end; i += 4) memcpy(i, &target->trapInstr, 4); } // Fill the last page of executable segments with trap instructions // instead of leaving them as zero. Even though it is not required by any // standard, it is in general a good thing to do for security reasons. // // We'll leave other pages in segments as-is because the rest will be // overwritten by output sections. template <class ELFT> void Writer<ELFT>::writeTrapInstr() { for (Partition &part : partitions) { // Fill the last page. for (PhdrEntry *p : part.phdrs) if (p->p_type == PT_LOAD && (p->p_flags & PF_X)) fillTrap(Out::bufferStart + alignDown(p->firstSec->offset + p->p_filesz, config->commonPageSize), Out::bufferStart + alignTo(p->firstSec->offset + p->p_filesz, config->commonPageSize)); // Round up the file size of the last segment to the page boundary iff it is // an executable segment to ensure that other tools don't accidentally // trim the instruction padding (e.g. when stripping the file). PhdrEntry *last = nullptr; for (PhdrEntry *p : part.phdrs) if (p->p_type == PT_LOAD) last = p; if (last && (last->p_flags & PF_X)) last->p_memsz = last->p_filesz = alignTo(last->p_filesz, config->commonPageSize); } } // Write section contents to a mmap'ed file. template <class ELFT> void Writer<ELFT>::writeSections() { // In -r or -emit-relocs mode, write the relocation sections first as in // ELf_Rel targets we might find out that we need to modify the relocated // section while doing it. for (OutputSection *sec : outputSections) if (sec->type == SHT_REL || sec->type == SHT_RELA) sec->writeTo<ELFT>(Out::bufferStart + sec->offset); for (OutputSection *sec : outputSections) if (sec->type != SHT_REL && sec->type != SHT_RELA) sec->writeTo<ELFT>(Out::bufferStart + sec->offset); } // Split one uint8 array into small pieces of uint8 arrays. static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> arr, size_t chunkSize) { std::vector<ArrayRef<uint8_t>> ret; while (arr.size() > chunkSize) { ret.push_back(arr.take_front(chunkSize)); arr = arr.drop_front(chunkSize); } if (!arr.empty()) ret.push_back(arr); return ret; } // Computes a hash value of Data using a given hash function. // In order to utilize multiple cores, we first split data into 1MB // chunks, compute a hash for each chunk, and then compute a hash value // of the hash values. static void computeHash(llvm::MutableArrayRef<uint8_t> hashBuf, llvm::ArrayRef<uint8_t> data, std::function<void(uint8_t *dest, ArrayRef<uint8_t> arr)> hashFn) { std::vector<ArrayRef<uint8_t>> chunks = split(data, 1024 * 1024); std::vector<uint8_t> hashes(chunks.size() * hashBuf.size()); // Compute hash values. parallelForEachN(0, chunks.size(), [&](size_t i) { hashFn(hashes.data() + i * hashBuf.size(), chunks[i]); }); // Write to the final output buffer. hashFn(hashBuf.data(), hashes); } template <class ELFT> void Writer<ELFT>::writeBuildId() { if (!mainPart->buildId || !mainPart->buildId->getParent()) return; if (config->buildId == BuildIdKind::Hexstring) { for (Partition &part : partitions) part.buildId->writeBuildId(config->buildIdVector); return; } // Compute a hash of all sections of the output file. size_t hashSize = mainPart->buildId->hashSize; std::vector<uint8_t> buildId(hashSize); llvm::ArrayRef<uint8_t> buf{Out::bufferStart, size_t(fileSize)}; switch (config->buildId) { case BuildIdKind::Fast: computeHash(buildId, buf, [](uint8_t *dest, ArrayRef<uint8_t> arr) { write64le(dest, xxHash64(arr)); }); break; case BuildIdKind::Md5: computeHash(buildId, buf, [&](uint8_t *dest, ArrayRef<uint8_t> arr) { memcpy(dest, MD5::hash(arr).data(), hashSize); }); break; case BuildIdKind::Sha1: computeHash(buildId, buf, [&](uint8_t *dest, ArrayRef<uint8_t> arr) { memcpy(dest, SHA1::hash(arr).data(), hashSize); }); break; case BuildIdKind::Uuid: if (auto ec = llvm::getRandomBytes(buildId.data(), hashSize)) error("entropy source failure: " + ec.message()); break; default: llvm_unreachable("unknown BuildIdKind"); } for (Partition &part : partitions) part.buildId->writeBuildId(buildId); } template void createSyntheticSections<ELF32LE>(); template void createSyntheticSections<ELF32BE>(); template void createSyntheticSections<ELF64LE>(); template void createSyntheticSections<ELF64BE>(); template void writeResult<ELF32LE>(); template void writeResult<ELF32BE>(); template void writeResult<ELF64LE>(); template void writeResult<ELF64BE>(); } // namespace elf } // namespace lld
37.213798
93
0.67134
[ "object", "vector", "model" ]
b41bfc9b3bdd14f8f19caeb1fb6ecd9134f24817
4,664
cpp
C++
DT3Windows8/ImporterVertexShaderVCSO.cpp
9heart/DT3
4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e
[ "MIT" ]
3
2018-10-05T15:03:27.000Z
2019-03-19T11:01:56.000Z
DT3Windows8/ImporterVertexShaderVCSO.cpp
pakoito/DT3
4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e
[ "MIT" ]
1
2016-01-28T14:39:49.000Z
2016-01-28T22:12:07.000Z
DT3Windows8/ImporterVertexShaderVCSO.cpp
adderly/DT3
e2605be091ec903d3582e182313837cbaf790857
[ "MIT" ]
3
2016-01-25T16:44:51.000Z
2021-01-29T19:59:45.000Z
//============================================================================== /// /// File: ImporterVertexShaderVCSO.cpp /// /// Copyright (C) 2000-2013 by Smells Like Donkey, Inc. All rights reserved. /// /// This file is subject to the terms and conditions defined in /// file 'LICENSE.txt', which is part of this source code package. /// //============================================================================== #include "ImporterVertexShaderVCSO.hpp" #include "Factory.hpp" #include "VertexShaderResource.hpp" #include "MaterialResource.hpp" #include "FilePath.hpp" #include "System.hpp" #include "DeviceConsole.hpp" #include "ResourceManager.hpp" //============================================================================== //============================================================================== namespace DT2 { //============================================================================== /// Register with object factory //============================================================================== IMPLEMENT_FACTORY_IMPORTER(ImporterVertexShaderVCSO,vcso) //============================================================================== /// Standard class constructors/destructors //============================================================================== ImporterVertexShaderVCSO::ImporterVertexShaderVCSO (void) { } ImporterVertexShaderVCSO::~ImporterVertexShaderVCSO (void) { } //============================================================================== //============================================================================== void ImporterVertexShaderVCSO::parseResourceBlock (VertexShaderResource *target) { _tokenizer.assumeNextToken("="); String resource_name = _tokenizer.getNextTokenString(); DTuint resource_index = _tokenizer.getNextTokenNumber(); target->setShaderResourceIndex(resource_name, resource_index); } //============================================================================== //============================================================================== void ImporterVertexShaderVCSO::parseResourcesBlock (VertexShaderResource *target) { _tokenizer.assumeNextToken("{"); while (true) { String token = _tokenizer.getNextTokenString(); // Handle Preprocessor if (_tokenizer.parsePreprocessorMacros(token)) continue; // Are we at the end of the block if (token == "}") break; if (Tokenizer::matchToken(token,"resource")) { parseResourceBlock(target); continue; } }; } //============================================================================== //============================================================================== void ImporterVertexShaderVCSO::parseShaderBlock (VertexShaderResource *target) { _tokenizer.assumeNextToken("="); String shader_hex = _tokenizer.getNextTokenString(); String shader_raw; shader_raw.resize(shader_hex.size() / 2, 0); MoreMath::fromHexString (shader_hex, &shader_raw[0], shader_raw.size()); target->setShader("HLSL",shader_raw); } //============================================================================== //============================================================================== void ImporterVertexShaderVCSO::parseProgramBlock (VertexShaderResource *target) { _tokenizer.assumeNextToken("{"); while (true) { String token = _tokenizer.getNextTokenString(); // Handle Preprocessor if (_tokenizer.parsePreprocessorMacros(token)) continue; // Are we at the end of the block if (token == "}") break; if (Tokenizer::matchToken(token,"resources")) { parseResourcesBlock(target); continue; } if (Tokenizer::matchToken(token,"shader")) { parseShaderBlock(target); continue; } }; } //============================================================================== //============================================================================== DTerr ImporterVertexShaderVCSO::import(VertexShaderResource *target, String args) { DTerr err; if ((err = _tokenizer.loadTokenStream (target->getPath())) != ERR_NONE) return ERR_FILE_OPEN_FAILED; while (!_tokenizer.isDone()) { String token = _tokenizer.getNextTokenString(); // Handle Preprocessor if (_tokenizer.parsePreprocessorMacros(token)) continue; if (Tokenizer::matchToken(token,"shader")) { parseProgramBlock(target); continue; } }; target->addDependencies(_tokenizer.getDependencies()); return ERR_NONE; } //============================================================================== //============================================================================== } // DT2
30.887417
99
0.475772
[ "object" ]
b41fca3c613ca04855a83d4f7cb73e410fd7e9cc
14,630
cc
C++
src/tlsshd.cc
ThomasHabets/tlssh
9173ed386cf389a1b9906c87acf99fb178c2d501
[ "BSD-3-Clause" ]
12
2015-09-09T02:55:24.000Z
2021-10-05T10:09:31.000Z
src/tlsshd.cc
ThomasHabets/tlssh
9173ed386cf389a1b9906c87acf99fb178c2d501
[ "BSD-3-Clause" ]
null
null
null
src/tlsshd.cc
ThomasHabets/tlssh
9173ed386cf389a1b9906c87acf99fb178c2d501
[ "BSD-3-Clause" ]
3
2016-06-26T01:07:29.000Z
2017-03-24T17:55:57.000Z
/// tlssh/src/tlsshd.cc /* * tlsshd * * By Thomas Habets <thomas@habets.se> 2010 * */ /** * @defgroup TLSSHD TLSSH Server @verbatim [network] - <ssl socket> - [ssl] - <pty> - [shell] ^ ^ ^ | | | Code: OpenSSL tlsshd-ssl.cc tlsshd-shell.cc & bash @endverbatim * * @file src/tlsshd.cc * TLSSHD Listener process * * This process sets up the daemon, listens to the port and runs the * accept()-loop. * * All the code in this file runs as root. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include<pwd.h> #include<unistd.h> #include<grp.h> #include<poll.h> #ifdef HAVE_PTY_H #include<pty.h> #endif #include<arpa/inet.h> #include<signal.h> #include<sys/mman.h> #include<sys/socket.h> #include<sys/stat.h> #include<sys/types.h> #include<sys/wait.h> #include<utmp.h> #include<memory> #include<iostream> #include<fstream> #include<vector> #include"tlssh.h" #include"sslsocket.h" #include"xgetpwnam.h" #include"configparser.h" #include"util2.h" using namespace tlssh_common; using namespace Err; Logger *logger; BEGIN_NAMESPACE(tlsshd); /* constants */ const char *argv0 = NULL; /* Process-wide variables */ Socket listen; std::string protocol_version; // should be "tlssh.1" Options options; /** SIGINT handler * * Listener process just quits if it gets SIGINT. * Ongoing connections do not. pkill -INT tlsshd is therefore safe in * that it will not cause you to shoot down the connection you are * using. * * @todo Find a clean way to always log a message here */ void sigint(int) { _exit(1); } /** Listen-loop. * * Run as: root * * Run accept() in a loop. Do not read or write to the socket. * spawns a newly fork()ed sslproc handler. (tlsshd-ssl.cc::forkmain()) * * @return Never returns, but if it did it would be the process exit value. */ int listen_loop() { struct sockaddr_storage sa; // never read from logger->debug("Entering listen loop"); for (;;) { FDWrap clifd; pid_t pid; socklen_t salen = sizeof(sa); clifd.set(::accept(listen.getfd(), (struct sockaddr*)&sa, &salen)); if (0 > clifd.get()) { continue; } pid = fork(); if (0 > pid) { // error logger->err("accept()-loop fork() failed"); } else if (pid == 0) { // child listen.close(); #if 0 /** * Temporarily disabled until I find out why * it's trying to allocate heaps and heaps to * concat 8k in tlsshd-ssl.cc:218. */ if (mlockall(MCL_CURRENT | MCL_FUTURE)) { logger->err("mlockall(MCL_CURRENT " "| MCL_FUTURE) failed: %s\n", strerror(errno)); exit(1); } #endif // Start a new process just to log reason child process // died. Note that there is no logging for this // intermediate process, because root process sets // SIG_IGN on SIGCHLD. const pid_t pid2 = fork(); if (pid2 == -1) { logger->err("second fork failed; no exit monitoring on handler process %d: %s", pid, strerror(errno)); exit(tlsshd_sslproc::forkmain(clifd)); } if (pid2 == 0) { // child exit(tlsshd_sslproc::forkmain(clifd)); } clifd.close(); if (SIG_ERR == signal(SIGCHLD, SIG_DFL)) { logger->err("monitor process signal(SIGCHLD) failed: %s", strerror(errno)); } int attempts = 0; int wstatus; do { const pid_t rc = waitpid(pid2, &wstatus, 0); if (rc == -1) { if (attempts++ == 3) { exit(1); } logger->err("waitpid(%d) attempt %d: %s", pid2, attempts, strerror(errno)); sleep(1); continue; } if (WIFEXITED(wstatus)) { const int exit_status = WEXITSTATUS(wstatus); if (exit_status != 0) { logger->err("connection handler %d exited with status %d", pid2, WEXITSTATUS(wstatus)); } } else if (WIFSIGNALED(wstatus)) { logger->err("connection handler %d exited due to signal %d", pid2, WTERMSIG(wstatus)); } else if (WIFSTOPPED(wstatus)) { logger->info("connection handler %d stopped by signal %d", pid2, WSTOPSIG(wstatus)); } else if (WIFCONTINUED(wstatus)) { logger->info("connection handler %d continued", pid2); } else { logger->err("waitpid returned %d for handler %d, but what does that mean?", wstatus, pid2); } } while (!WIFEXITED(wstatus) && !WIFSIGNALED(wstatus)); logger->err("connection handler process %d exited", pid2); exit(0); } else { // parent. Continue listening ; } } } /** Print usage info and exit. * * Called when doing one of: * -h option (err = 0) * --help option (err = 0) * invalid options (err != 1) */ void usage(int err) { printf("%s [ -46fhvV ] " "[ -c <config> ] " "[ -C <cipher-list> ] " "\n" "\t[ -p <cert+keyfile> ]" "\n" "\t-c <config> Config file (default %s)\n" "\t-C <cipher-list> Acceptable ciphers\n" "\t (default %s)\n" "\t-f Run in foreground\n" "\t-h, --help Help\n" "\t-v Increase verbosity\n" "\t-V, --version Print version and exit\n" "\t-p <cert+keyfile> Load login cert+key from file\n" , argv0, DEFAULT_CONFIG.c_str(), DEFAULT_CIPHER_LIST.c_str()); exit(err); } /** Read config file * */ void read_config_file(const std::string &fn) { std::ifstream fi(fn.c_str()); ConfigParser conf(fi); ConfigParser end; for (;conf != end; ++conf) { if (conf->keyword.empty()) { // empty line } else if (conf->keyword[0] == '#') { // comment } else if (conf->keyword == "Listen" && conf->parms.size() == 1) { options.listen = conf->parms[0]; } else if (conf->keyword == "ClientCAFile" && conf->parms.size() == 1) { options.clientcafile = conf->parms[0]; } else if (conf->keyword == "ClientCAPath" && conf->parms.size() == 1) { options.clientcapath = conf->parms[0]; } else if (conf->keyword == "ClientCRL" && conf->parms.size() == 1) { options.clientcrl = conf->parms[0]; } else if (conf->keyword == "ClientDomain" && conf->parms.size() == 1) { options.clientdomain = conf->parms[0]; } else if (conf->keyword == "Chroot" && conf->parms.size() == 1) { options.chroot = conf->parms[0]; } else if (conf->keyword == "Daemon" && conf->parms.size() == 1) { if (conf->parms[0] == "off") { options.daemon = false; } /* * SSL Engine (TPM) stuff. */ } else if (conf->keyword == "PrivkeyEngineConfPre") { options.privkey_engine_pre.push_back( std::make_pair(conf->parms[0], conf->parms[1])); } else if (conf->keyword == "PrivkeyEngineConfPost") { options.privkey_engine_post.push_back( std::make_pair(conf->parms[0], conf->parms[1])); } else if (conf->keyword == "PrivkeyEngine") { options.privkey_engine = std::make_pair(true, conf->rest.c_str()); } else if (conf->keyword == "Port" && conf->parms.size() == 1) { options.port = conf->parms[0]; } else if (conf->keyword == "KeyFile" && conf->parms.size() == 1) { options.keyfile = conf->parms[0]; } else if (conf->keyword == "Keepalive" && conf->parms.size() == 1) { options.keepalive = strtoul(conf->parms[0].c_str(), 0, 0); } else if (conf->keyword == "CertFile" && conf->parms.size() == 1) { options.certfile = conf->parms[0]; } else if (conf->keyword == "CipherList" && conf->parms.size() == 1) { options.cipher_list = conf->parms[0]; } else if (conf->keyword == "-include" && conf->parms.size() == 1) { try { read_config_file(xwordexp(conf->parms[0])); } catch(const ConfigParser::ErrStream&) { // -includes don't have to work break; } } else if (conf->keyword == "include" && conf->parms.size() == 1) { try { read_config_file(xwordexp(conf->parms[0])); } catch(const ConfigParser::ErrStream&) { THROW(ErrBase, "I/O error accessing include file: " + conf->parms[0]); } } else { THROW(ErrBase, "Error in config line: " + conf->line); } } } /** * Parse command line options. First read config file and then let cmdline * override that. */ void parse_options(int argc, char * const *argv) { int c; /* special options */ for (c = 1; c < argc; c++) { if (!strcmp(argv[c], "--")) { break; } else if (!strcmp(argv[c], "--help") || !strcmp(argv[c], "-h")) { usage(0); } else if (!strcmp(argv[c], "--version") || !strcmp(argv[c], "-V")) { print_version(); exit(0); } else if (!strcmp(argv[c], "--copying")) { print_copying(); exit(0); } else if (!strcmp(argv[c], "-c")) { if (c + 1 != argc) { options.config = argv[++c]; } } else if (!strcmp(argv[c], "-f")) { options.daemon = false; } } if (!options.daemon) { logger->attach(new FileLogger("/dev/tty"), true); } try { read_config_file(options.config); } catch(const ConfigParser::ErrStream&) { THROW(ErrBase, "I/O error accessing config file: " + options.config + "\n" + "tlsshd requires a valid config file."); } int opt; while ((opt = getopt(argc, argv, "c:fhvV")) != -1) { switch (opt) { case 'c': // already handled above break; case 'f': options.daemon = false; break; case 'h': usage(0); case 'v': options.verbose++; break; case 'V': print_version(); exit(0); default: usage(1); } } } END_NAMESPACE(tlsshd); BEGIN_LOCAL_NAMESPACE() using namespace tlsshd; /** * wrapped main() so that we don't have to handle exceptions in this main() * * @todo Only listen to options.listen */ int main2(int argc, char * const argv[]) { if (SIG_ERR == signal(SIGCHLD, SIG_IGN)) { THROW(Err::ErrBase, "signal(SIGCHLD, SIG_IGN)"); } if (SIG_ERR == signal(SIGPIPE, SIG_IGN)) { THROW(Err::ErrBase, "signal(SIGPIPE, SIG_IGN)"); } if (SIG_ERR == signal(SIGINT, sigint)) { THROW(Err::ErrBase, "signal(SIGINT, sigint)"); } parse_options(argc, argv); if (options.verbose) { logger->set_logmask(logger->get_logmask() | LOG_MASK(LOG_DEBUG)); } tlsshd::listen.set_tcp_md5(options.tcp_md5); tlsshd::listen.listen(options.af, options.listen, options.port); if (options.daemon) { if (daemon(0, 0)) { THROW(Err::ErrSys, "daemon(0, 0)"); } } return listen_loop(); } END_LOCAL_NAMESPACE() /** * */ int main(int argc, char **argv) { if (getuid()) { fprintf(stderr, "tlsshd must run as root\n"); exit(1); } if (mlockall(MCL_CURRENT | MCL_FUTURE)) { fprintf(stderr, "mlockall(MCL_CURRENT | MCL_FUTURE) failed: %s\n", strerror(errno)); exit(1); } logger = new SysLogger("tlsshd", LOG_AUTHPRIV); logger->set_logmask(logger->get_logmask() & ~LOG_MASK(LOG_DEBUG)); argv0 = argv[0]; try { return main2(argc, argv); } catch (const Err::ErrBase &e) { if (options.verbose) { logger->err("%s", e.what_verbose().c_str()); } else { logger->err("%s", e.what()); } } catch (const std::exception &e) { logger->err("tlsshd std::exception: %s", e.what()); } catch (...) { logger->err("tlsshd: Unknown exception!"); throw; } } /* ---- Emacs Variables ---- * Local Variables: * c-basic-offset: 8 * indent-tabs-mode: nil * End: */
31.598272
135
0.456254
[ "vector" ]
b4226bdf85305147fd46e529826f3e7a1e93d429
2,902
cpp
C++
src/base/file/textfile.cpp
Manistein/behaviac
538266380446e0fd77461ad22fca05e2c9eb8cba
[ "BSD-3-Clause" ]
2
2021-06-06T07:54:45.000Z
2021-09-08T03:36:40.000Z
src/base/file/textfile.cpp
gdtdftdqtd/behaviac
538266380446e0fd77461ad22fca05e2c9eb8cba
[ "BSD-3-Clause" ]
null
null
null
src/base/file/textfile.cpp
gdtdftdqtd/behaviac
538266380446e0fd77461ad22fca05e2c9eb8cba
[ "BSD-3-Clause" ]
1
2017-07-02T06:55:02.000Z
2017-07-02T06:55:02.000Z
///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Tencent is pleased to support the open source community by making behaviac available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause // // 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 "behaviac/base/file/textfile.h" #include "behaviac/base/file/file.h" #include "behaviac/base/file/filemanager.h" char* LoadTextFileAsBuffer(const char* fileName) { char* returnedBuffer = NULL; IFile* fileHandle = CFileManager::GetInstance()->FileOpen(fileName, CFileSystem::EOpenAccess_Read); if (fileHandle) { uint32_t fileSize = (uint32_t)fileHandle->GetSize(); char* fileBuffer = (char*)BEHAVIAC_MALLOC_WITHTAG(fileSize + 1, "TextFileBuffer"); if (fileHandle->Read(fileBuffer, fileSize) == fileSize) { fileBuffer[fileSize] = '\0'; returnedBuffer = fileBuffer; } else { BEHAVIAC_ASSERT(0, "Fail to read the text file : %s\n", fileName); } CFileManager::GetInstance()->FileClose(fileHandle); } else { BEHAVIAC_ASSERT(0, "Fail to open the text file : %s\n", fileName); } return returnedBuffer; } bool LoadTextFileAsStringArray(const char* fileName, behaviac::vector<behaviac::string>& stringArray) { char* buffer = LoadTextFileAsBuffer(fileName); if (buffer) { ConvertTextBufferAsStringArray(buffer, stringArray); BEHAVIAC_FREE(buffer); return true; } else { return false; } } void ConvertTextBufferAsStringArray(const char* buffer, behaviac::vector<behaviac::string>& stringArray) { BEHAVIAC_ASSERT(buffer); const char* lineBuffer = buffer; while (*lineBuffer != '\0') { const char* currentPos = lineBuffer; while (*currentPos != '\n' && *currentPos != '\r' && *currentPos != '\0') { currentPos++; } behaviac::string line; line.assign(lineBuffer, currentPos - lineBuffer); stringArray.push_back(line); while (*currentPos == '\n' || *currentPos == '\r') { currentPos++; } lineBuffer = currentPos; } }
32.244444
113
0.598553
[ "vector" ]
b42969fe3aa68219757e354c4a99342bf4b5d04b
50,680
cpp
C++
third_party/geogram/src/lib/geogram_gfx/GLUP/GLUP.cpp
ringmesh/RINGMesh
82a0a0fb0a119492c6747265de6ec24006c4741f
[ "BSD-3-Clause" ]
74
2017-10-26T15:40:23.000Z
2022-03-22T09:27:39.000Z
third_party/geogram/src/lib/geogram_gfx/GLUP/GLUP.cpp
ringmesh/ringmesh
82a0a0fb0a119492c6747265de6ec24006c4741f
[ "BSD-3-Clause" ]
45
2017-10-26T15:54:01.000Z
2021-01-27T10:16:34.000Z
third_party/geogram/src/lib/geogram_gfx/GLUP/GLUP.cpp
ringmesh/ringmesh
82a0a0fb0a119492c6747265de6ec24006c4741f
[ "BSD-3-Clause" ]
17
2018-03-27T11:31:24.000Z
2022-03-06T18:41:52.000Z
/* * Copyright (c) 2012-2014, Bruno Levy * 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 ALICE Project-Team 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. * * If you modify this software, you should include a notice giving the * name of the person performing the modification, the date of modification, * and the reason for such modification. * * Contact: Bruno Levy * * Bruno.Levy@inria.fr * http://www.loria.fr/~levy * * ALICE Project * LORIA, INRIA Lorraine, * Campus Scientifique, BP 239 * 54506 VANDOEUVRE LES NANCY CEDEX * FRANCE * */ #include <geogram_gfx/GLUP/GLUP.h> #include <geogram_gfx/GLUP/GLUP_context_GLSL.h> #include <geogram_gfx/GLUP/GLUP_context_ES.h> #include <geogram_gfx/basic/GLSL.h> #include <geogram/basic/logger.h> #include <geogram/basic/file_system.h> #include <geogram/basic/command_line.h> #ifdef GEO_OS_EMSCRIPTEN #include <emscripten.h> #pragma GCC diagnostic ignored "-Wdollar-in-identifier-extension" #endif #ifdef GEO_OS_ANDROID # pragma GCC diagnostic ignored "-Wpointer-bool-conversion" #endif /*****************************************************************************/ namespace { using namespace GEO; void downgrade_message() { static bool done = false; if(!done) { done = true; Logger::out("GLUP") << "Something happened, trying to fix (by downgrading)" << std::endl; Logger::out("GLUP") << "If this does not work, try the following options:" << std::endl; Logger::out("GLUP") << " (1) make sure your OpenGL driver is up to date" << std::endl; Logger::out("GLUP") << " (2) create a file named \'" << CmdLine::get_config_file_name() << "\' in " << std::endl; Logger::out("GLUP") << " your home directory (" << FileSystem::home_directory() << ")" << std::endl; Logger::out("GLUP") << " with: " << std::endl; Logger::out("GLUP") << " gfx:GLUP_profile=GLUPES2" << std::endl; } } } /*****************************************************************************/ namespace GLUP { using namespace GEO; static Context* current_context_ = nullptr; static std::set<Context*> all_contexts_; static bool initialized_ = false; static void cleanup() { for(auto ctxt : all_contexts_) { delete ctxt; } all_contexts_.clear(); } } /*****************************************************************************/ const char* glupUniformStateDeclaration() { GEO_CHECK_GL(); return GLUP::current_context_->uniform_state_declaration(); } GLUPuint glupCompileShader(GLUPenum target, const char* source) { GEO_CHECK_GL(); GLUP::current_context_->setup_shaders_source_for_primitive(GLUP_TRIANGLES); // First param: ignored. // Second param: all toggle states are unknown. GLUP::current_context_->setup_shaders_source_for_toggles(0,~0); GEO_CHECK_GL(); GLUPuint result = GLSL::compile_shader_with_includes( target, source, GLUP::current_context_ ); GEO_CHECK_GL(); return result; } namespace { /** * \brief Converts a comment //stage GL_VERTEX_SHADER into * the associated GLUPenum value. * \param[in,out] comment_str on entry, a pointer to the comment. * on exit, the next line. A '\0' terminator is inserted in * the string (replaces the '\n' that ends the line). * \return the target or 0 if an error was encountered. */ static GLUPenum stage_to_target(char*& comment_str) { char* p1 = comment_str + 8; char* p2 = strchr(p1, '\n'); if(p2 == nullptr) { Logger::err("GLSL") << "Missing CR in //stage GL_xxxxx declaration" << std::endl; return 0; } std::string stage_str(p1, size_t(p2-p1)); GLenum stage = 0; if(stage_str == "GL_VERTEX_SHADER") { stage = GL_VERTEX_SHADER; } else if(stage_str == "GL_FRAGMENT_SHADER") { stage = GL_FRAGMENT_SHADER; } #ifndef GEO_OS_EMSCRIPTEN else if(stage_str == "GL_GEOMETRY_SHADER") { stage = GL_GEOMETRY_SHADER; } else if(stage_str == "GL_TESS_CONTROL_SHADER") { stage = GL_TESS_CONTROL_SHADER; } else if(stage_str == "GL_TESS_EVALUATION_SHADER") { stage = GL_TESS_EVALUATION_SHADER; } #endif else { Logger::err("GLSL") << stage_str << ": unknown stage" << std::endl; } *comment_str = '\0'; comment_str = p2+1; return stage; } } GLUPuint glupCompileProgram(const char* source_in) { std::string source(source_in); std::vector<const char*> sources; std::vector<GLUPenum> targets; std::vector<GLuint> shaders; char* p = const_cast<char*>(source.c_str()); bool has_vertex_shader = false; for( p = strstr(p,"//stage"); (p != nullptr) && (*p != '\0'); p = strstr(p,"//stage ") ) { GLUPenum target = stage_to_target(p); if(target == 0) { return 0; } sources.push_back(p); targets.push_back(target); has_vertex_shader = has_vertex_shader || (target == GL_VERTEX_SHADER); } // Use default vertex shader if no vertex shader was specified. if(!has_vertex_shader) { if(!strcmp(glupCurrentProfileName(),"GLUPES2")) { targets.push_back(GL_VERTEX_SHADER); sources.push_back("//import <GLUPES/vertex_shader.h>\n"); } else if( !strcmp(glupCurrentProfileName(),"GLUP150") || !strcmp(glupCurrentProfileName(),"GLUP440") ) { targets.push_back(GL_VERTEX_SHADER); sources.push_back("//import <GLUPGLSL/vertex_shader.h>\n"); } } GLuint program = 0; try { for(index_t i=0; i<index_t(sources.size()); ++i) { GLUPuint shader = glupCompileShader(targets[i], sources[i]); if(shader == 0) { throw(GLSL::GLSLCompileError()); } shaders.push_back(shader); } program = glCreateProgram(); for(index_t i=0; i<index_t(shaders.size()); ++i) { glAttachShader(program, shaders[i]); } GEO_CHECK_GL(); glBindAttribLocation(program, GLUP::GLUP_VERTEX_ATTRIBUTE, "vertex_in"); glBindAttribLocation(program, GLUP::GLUP_COLOR_ATTRIBUTE, "color_in"); glBindAttribLocation(program, GLUP::GLUP_TEX_COORD_ATTRIBUTE, "tex_coord_in"); glBindAttribLocation(program, GLUP::GLUP_NORMAL_ATTRIBUTE, "normal_in"); GEO_CHECK_GL(); GLSL::link_program(program); GEO_CHECK_GL(); GLUP::current_context_->bind_uniform_state(program); GEO_CHECK_GL(); } catch(...) { if(program != 0) { Logger::err("GLSL") << "Could not compile program" << std::endl; glDeleteProgram(program); program = 0; } } // Shaders are reference-counted, now they are attached // to the program. for(index_t i=0; i<index_t(shaders.size()); ++i) { glDeleteShader(shaders[i]); } return program; } void glupBindUniformState(GLUPuint program) { GEO_CHECK_GL(); GLUP::current_context_->bind_uniform_state(program); GEO_CHECK_GL(); } #if !defined(GEO_OS_EMSCRIPTEN) && \ !defined(GEO_OS_APPLE) && \ !defined(GEO_OS_ANDROID) /** * \brief Tests whether tessellation shaders are supported by OpenGL. * \details Some drivers may declare to be OpenGL 4.5 compliant whereas * they do not have tesselation shader (for instance, I have an old * NVidia quadro that does that...) * \retval true if tessellation shaders are supported * \retval false otherwise */ static bool supports_tessellation_shader() { GEO_CHECK_GL(); #ifndef GEO_GL_150 return false; #else bool result = true; // Note: I experienced crashes with glPatchParameterfv() with // the OpenGL es profile, so I'm deactivating it if detected. if(GEO::CmdLine::get_arg("gfx:GL_profile") == "ES") { GEO::Logger::out("GLUP") << "Deactivating tesselation shader under OpenGL ES profile" << std::endl; return false; } GLuint s_handle = glCreateShader(GL_TESS_CONTROL_SHADER); result = result && (s_handle != 0); if (s_handle != 0) { glDeleteShader(s_handle); } // Clear OpenGL error flag. while(glGetError() != GL_NO_ERROR) { } return result; #endif } #endif GLUPcontext glupCreateContext() { if(!GLUP::initialized_) { GLUP::initialized_ = true; atexit(GLUP::cleanup); } GEO_CHECK_GL(); std::string GLUP_profile = GEO::CmdLine::get_arg("gfx:GLUP_profile"); GLUP::Context* result = nullptr; if(GLUP_profile == "auto") { #if defined(GEO_OS_EMSCRIPTEN) || defined(GEO_OS_APPLE) || defined(GEO_OS_ANDROID) GLUP_profile = "GLUPES2"; // GLUP_profile = "GLUP150"; // Does something but bugged / not fully functional. #else GEO_CHECK_GL(); double GLSL_version = GEO::GLSL::supported_language_version(); GEO_CHECK_GL(); if (GLSL_version >= 4.4) { GEO_CHECK_GL(); if (!supports_tessellation_shader()) { GEO::Logger::out("GLUP") << "GLSL version >= 4.4 but tessellation unsupported" << std::endl; downgrade_message(); GEO::Logger::out("GLUP") << "Downgrading to GLUP 150..." << std::endl; GLSL_version = 1.5; } GEO_CHECK_GL(); } if(GLSL_version >= 4.4) { GLUP_profile = "GLUP440"; } else if(GLSL_version >= 1.5) { GLUP_profile = "GLUP150"; } else { GLUP_profile = "GLUPES2"; } #endif } GEO::Logger::out("GLUP") << "Using " << GLUP_profile << " profile" << std::endl; #ifdef GEO_GL_440 if(GLUP_profile == "GLUP440") { try { result = new GLUP::Context_GLSL440; result->setup(); } catch(...) { GEO::Logger::warn("GLUP") << "Caught an exception in GLUP440, downgrading to GLUP150" << std::endl; downgrade_message(); GLUP_profile = "GLUP150"; delete result; result = nullptr; } } #endif #ifdef GEO_GL_150 if(GLUP_profile == "GLUP150") { try { result = new GLUP::Context_GLSL150; result->setup(); } catch(...) { GEO::Logger::warn("GLUP") << "Caught an exception in GLUP150, downgrading to GLUPES2" << std::endl; downgrade_message(); GLUP_profile = "GLUPES2"; delete result; result = nullptr; } } #endif #ifdef GEO_GL_ES2 if(GLUP_profile == "GLUPES2") { try { result = new GLUP::Context_ES2; result->setup(); } catch(...) { GEO::Logger::warn("GLUP") << "Caught an exception in GLUPES2" << std::endl; downgrade_message(); delete result; result = nullptr; } } #endif if(result == nullptr) { GEO::Logger::err("GLUP") << "Could not create context" << std::endl; } else { GLUP::all_contexts_.insert(result); } return result; } void glupDeleteContext(GLUPcontext context_in) { GEO_CHECK_GL(); GLUP::Context* context = reinterpret_cast<GLUP::Context*>(context_in); auto it = GLUP::all_contexts_.find(context); geo_assert(it != GLUP::all_contexts_.end()); GLUP::all_contexts_.erase(it); if(GLUP::current_context_ == context) { GLUP::current_context_ = nullptr; } delete context; } GLUPcontext glupCurrentContext() { GEO_CHECK_GL(); return GLUP::current_context_; } const char* glupCurrentProfileName() { GEO_CHECK_GL(); return GLUP::current_context_->profile_name(); } void glupMakeCurrent(GLUPcontext context) { GEO_CHECK_GL(); GLUP::current_context_ = reinterpret_cast<GLUP::Context*>(context); } GLUPboolean glupPrimitiveSupportsArrayMode(GLUPprimitive prim) { GEO_CHECK_GL(); return GLUP::current_context_->primitive_supports_array_mode(prim) ? GL_TRUE : GL_FALSE ; } /****************** Enable / Disable ***************************/ namespace GLUP { extern bool vertex_array_emulate; } void glupEnable(GLUPtoggle toggle) { GEO_CHECK_GL(); GLUP::current_context_->uniform_state().toggle[toggle].set(GL_TRUE); } void glupDisable(GLUPtoggle toggle) { GEO_CHECK_GL(); GLUP::current_context_->uniform_state().toggle[toggle].set(GL_FALSE); } GLUPboolean glupIsEnabled(GLUPtoggle toggle) { GEO_CHECK_GL(); return GLUP::current_context_->uniform_state().toggle[toggle].get(); } /********************** Texturing ******************************/ void glupTextureType(GLUPtextureType type) { GEO_CHECK_GL(); GLUP::current_context_->uniform_state().texture_type.set(type); } GLUPtextureType glupGetTextureType() { GEO_CHECK_GL(); return GLUPtextureType( GLUP::current_context_->uniform_state().texture_type.get() ); } void glupTextureMode(GLUPtextureMode mode) { GEO_CHECK_GL(); GLUP::current_context_->uniform_state().texture_mode.set(mode); } GLUPtextureMode glupGetTextureMode() { GEO_CHECK_GL(); return GLUPtextureMode( GLUP::current_context_->uniform_state().texture_mode.get() ); } /****************** Drawing state ******************************/ void glupSetColor4fv(GLUPcolor color, const GLUPfloat* rgba) { GEO_CHECK_GL(); if(color == GLUP_FRONT_AND_BACK_COLOR) { glupSetColor4fv(GLUP_FRONT_COLOR, rgba); glupSetColor4fv(GLUP_BACK_COLOR, rgba); } else { GLUP::current_context_->uniform_state().color[color].set(rgba); } } void glupGetColor4fv(GLUPcolor color, float* rgba) { GEO_CHECK_GL(); geo_assert(color != GLUP_FRONT_AND_BACK_COLOR); GLUP::current_context_->uniform_state().color[color].get(rgba); } void glupSetColor3fv(GLUPcolor color, const GLUPfloat* rgba) { GEO_CHECK_GL(); glupSetColor4f(color, rgba[0], rgba[1], rgba[2], 1.0); } void glupSetColor4f( GLUPcolor color, GLUPfloat r, GLUPfloat g, GLUPfloat b, GLUPfloat a ) { GEO_CHECK_GL(); if(color == GLUP_FRONT_AND_BACK_COLOR) { glupSetColor4f(GLUP_FRONT_COLOR, r, g, b, a); glupSetColor4f(GLUP_BACK_COLOR, r, g, b, a); } else { GLUPfloat* ptr = GLUP::current_context_->uniform_state().color[color].get_pointer(); ptr[0] = r; ptr[1] = g; ptr[2] = b; ptr[3] = a; } } void glupSetColor3f(GLUPcolor color, GLUPfloat r, GLUPfloat g, GLUPfloat b) { GEO_CHECK_GL(); glupSetColor4f(color, r, g, b, 1.0f); } void glupSetColor4dv(GLUPcolor color, const GLUPdouble* rgba) { GEO_CHECK_GL(); glupSetColor4f( color, GLUPfloat(rgba[0]), GLUPfloat(rgba[1]), GLUPfloat(rgba[2]), GLUPfloat(rgba[3]) ); } void glupSetColor3dv(GLUPcolor color, const GLUPdouble* rgba) { GEO_CHECK_GL(); glupSetColor4f( color, GLUPfloat(rgba[0]), GLUPfloat(rgba[1]), GLUPfloat(rgba[2]), 1.0f ); } void glupSetColor4d( GLUPcolor color, GLUPdouble r, GLUPdouble g, GLUPdouble b, GLUPdouble a ) { GEO_CHECK_GL(); glupSetColor4f( color, GLUPfloat(r), GLUPfloat(g), GLUPfloat(b), GLUPfloat(a) ); } void glupSetColor3d( GLUPcolor color, GLUPdouble r, GLUPdouble g, GLUPdouble b ) { GEO_CHECK_GL(); glupSetColor4f( color, GLUPfloat(r), GLUPfloat(g), GLUPfloat(b), 1.0f ); } void glupLightVector3f(GLUPfloat x, GLUPfloat y, GLUPfloat z) { GEO_CHECK_GL(); GLUPfloat* ptr = GLUP::current_context_->uniform_state().light_vector.get_pointer(); ptr[0] = x; ptr[1] = y; ptr[2] = z; GLUP::current_context_->flag_lighting_as_dirty(); } void glupLightVector3fv(GLUPfloat* xyz) { GEO_CHECK_GL(); GLUP::current_context_->uniform_state().light_vector.set(xyz); GLUP::current_context_->flag_lighting_as_dirty(); } void glupGetLightVector3fv(GLUPfloat* xyz) { GEO_CHECK_GL(); GLUPfloat* ptr = GLUP::current_context_->uniform_state().light_vector.get_pointer(); xyz[0] = ptr[0]; xyz[1] = ptr[1]; xyz[2] = ptr[2]; } void glupSetPointSize(GLUPfloat size) { GEO_CHECK_GL(); GLUP::current_context_->uniform_state().point_size.set(size); } GLUPfloat glupGetPointSize() { GEO_CHECK_GL(); return GLUP::current_context_->uniform_state().point_size.get(); } void glupSetMeshWidth(GLUPint width) { GEO_CHECK_GL(); GLUP::current_context_->uniform_state().mesh_width.set(GLfloat(width)); } GLUPint glupGetMeshWidth() { GEO_CHECK_GL(); return GLUPint(GLUP::current_context_->uniform_state().mesh_width.get()); } void glupSetCellsShrink(GLUPfloat x) { GEO_CHECK_GL(); x = std::min(x, 1.0f); x = std::max(x, 0.0f); GLUP::current_context_->uniform_state().cells_shrink.set(x); } GLUPfloat glupGetCellsShrink() { GEO_CHECK_GL(); return GLUP::current_context_->uniform_state().cells_shrink.get(); } void glupSetAlphaThreshold(GLUPfloat x) { GEO_CHECK_GL(); GLUP::current_context_->uniform_state().alpha_threshold.set(x); } GLUPfloat glupGetAlphaThreshold() { GEO_CHECK_GL(); return GLUP::current_context_->uniform_state().alpha_threshold.get(); } void glupSetSpecular(GLUPfloat x) { GEO_CHECK_GL(); GLUP::current_context_->uniform_state().specular.set(x); } GLUPfloat glupGetSpecular() { GEO_CHECK_GL(); return GLUP::current_context_->uniform_state().specular.get(); } /****************** Picking ******************************/ void glupPickingMode(GLUPpickingMode mode) { GEO_CHECK_GL(); GLUP::current_context_->uniform_state().picking_mode.set(mode); } GLUPpickingMode glupGetPickingMode() { GEO_CHECK_GL(); return GLUPpickingMode( GLUP::current_context_->uniform_state().picking_mode.get() ); } void glupPickingId(GLUPuint64 id) { // TODO: uint64 GEO_CHECK_GL(); GLUP::current_context_->uniform_state().picking_id.set(GLint(id)); } GLUPuint64 glupGetPickingId() { // TODO: uint64 GEO_CHECK_GL(); return GLUPuint64( GLUP::current_context_->uniform_state().picking_id.get() ); } void glupBasePickingId(GLUPuint64 id) { // TODO: uint64 GEO_CHECK_GL(); GLUP::current_context_->uniform_state().base_picking_id.set(GLint(id)); } GLUPuint64 glupGetBasePickingId() { // TODO: uint64 GEO_CHECK_GL(); return GLUPuint64( GLUP::current_context_->uniform_state().base_picking_id.get() ); } /****************** Clipping ******************************/ void glupClipMode(GLUPclipMode mode) { GEO_CHECK_GL(); GLUP::current_context_->uniform_state().clipping_mode.set(mode); } GLUPclipMode glupGetClipMode() { GEO_CHECK_GL(); return GLUPclipMode( GLUP::current_context_->uniform_state().clipping_mode.get() ); } void glupClipPlane(const GLUPdouble* eqn_in) { GEO_CHECK_GL(); const GLfloat* modelview = GLUP::current_context_->get_matrix(GLUP_MODELVIEW_MATRIX); GLfloat modelview_invert[16]; if(!GLUP::invert_matrix(modelview_invert,modelview)) { GEO::Logger::warn("GLUP") << "Singular ModelView matrix" << std::endl; GLUP::show_matrix(modelview); } GLfloat* state_world_clip_plane = GLUP::current_context_->uniform_state().world_clip_plane.get_pointer(); GLfloat* state_clip_plane = GLUP::current_context_->uniform_state().clip_plane.get_pointer(); for(GEO::index_t i=0; i<4; ++i) { state_world_clip_plane[i] = float(eqn_in[i]); } GLUP::mult_matrix_vector( state_clip_plane,modelview_invert,state_world_clip_plane ); // TODO? clip_clip_plane update ? } void glupGetClipPlane(GLUPdouble* eqn) { GEO_CHECK_GL(); const GLfloat* ptr = GLUP::current_context_->uniform_state().clip_plane.get_pointer(); eqn[0] = GLdouble(ptr[0]); eqn[1] = GLdouble(ptr[1]); eqn[2] = GLdouble(ptr[2]); eqn[3] = GLdouble(ptr[3]); } /******************* Matrices ***************************/ void glupMatrixMode(GLUPmatrix matrix) { GEO_CHECK_GL(); GLUP::current_context_->set_matrix_mode(matrix); } GLUPmatrix glupGetMatrixMode() { GEO_CHECK_GL(); return GLUP::current_context_->get_matrix_mode(); } void glupPushMatrix() { GEO_CHECK_GL(); GLUP::current_context_->push_matrix(); } void glupPopMatrix() { GEO_CHECK_GL(); GLUP::current_context_->pop_matrix(); } void glupGetMatrixdv(GLUPmatrix matrix, GLUPdouble* ptr) { GEO_CHECK_GL(); for(GEO::index_t i=0; i<16; ++i) { ptr[i] = GLUPdouble( GLUP::current_context_->get_matrix(matrix)[i] ); } } void glupGetMatrixfv(GLUPmatrix matrix, GLUPfloat* ptr) { GEO_CHECK_GL(); for(GEO::index_t i=0; i<16; ++i) { GLUP::copy_vector( ptr, GLUP::current_context_->get_matrix(matrix), 16 ); } } void glupLoadIdentity() { GEO_CHECK_GL(); GLUP::current_context_->load_identity(); } void glupLoadMatrixf(const GLUPfloat* M) { GEO_CHECK_GL(); GLUP::current_context_->load_matrix(M); } void glupLoadMatrixd(const GLUPdouble* M) { GEO_CHECK_GL(); GLfloat Mf[16]; for(GEO::index_t i=0; i<16; ++i) { Mf[i] = GLfloat(M[i]); } glupLoadMatrixf(Mf); } void glupMultMatrixf(const GLUPfloat* M) { GEO_CHECK_GL(); GLUP::current_context_->mult_matrix(M); } void glupMultMatrixd(const GLUPdouble* M) { GEO_CHECK_GL(); GLfloat Mf[16]; for(GEO::index_t i=0; i<16; ++i) { Mf[i] = GLfloat(M[i]); } glupMultMatrixf(Mf); } void glupTranslatef(GLUPfloat x, GLUPfloat y, GLUPfloat z) { GEO_CHECK_GL(); GLfloat M[16]; M[4*0+0] = 1.0f; M[4*0+1] = 0.0f; M[4*0+2] = 0.0f; M[4*0+3] = x; M[4*1+0] = 0.0f; M[4*1+1] = 1.0f; M[4*1+2] = 0.0f; M[4*1+3] = y; M[4*2+0] = 0.0f; M[4*2+1] = 0.0f; M[4*2+2] = 1.0f; M[4*2+3] = z; M[4*3+0] = 0.0f; M[4*3+1] = 0.0f; M[4*3+2] = 0.0f; M[4*3+3] = 1.0f; GLUP::transpose_matrix(M); glupMultMatrixf(M); } void glupTranslated(GLUPdouble x, GLUPdouble y, GLUPdouble z) { GEO_CHECK_GL(); glupTranslatef(GLfloat(x), GLfloat(y), GLfloat(z)); } void glupScalef(GLUPfloat sx, GLUPfloat sy, GLUPfloat sz) { GEO_CHECK_GL(); GLfloat M[16]; M[4*0+0] = sx; M[4*0+1] = 0.0f; M[4*0+2] = 0.0f; M[4*0+3] = 0.0f; M[4*1+0] = 0.0f; M[4*1+1] = sy; M[4*1+2] = 0.0f; M[4*1+3] = 0.0f; M[4*2+0] = 0.0f; M[4*2+1] = 0.0f; M[4*2+2] = sz; M[4*2+3] = 0.0f; M[4*3+0] = 0.0f; M[4*3+1] = 0.0f; M[4*3+2] = 0.0f; M[4*3+3] = 1.0f; glupMultMatrixf(M); } void glupScaled(GLUPdouble sx, GLUPdouble sy, GLUPdouble sz) { GEO_CHECK_GL(); glupScalef(GLfloat(sx), GLfloat(sy), GLfloat(sz)); } void glupRotatef( GLUPfloat angle, GLUPfloat x, GLUPfloat y, GLUPfloat z ) { GEO_CHECK_GL(); GLUPfloat l = 1.0f / ::sqrtf(x*x+y*y+z*z); x *= l; y *= l; z *= l; GLUPfloat s = ::sinf(angle * GLUPfloat(M_PI) / 180.0f); GLUPfloat c = ::cosf(angle * GLUPfloat(M_PI) / 180.0f); GLUPfloat M[16]; M[4*0+0] = x*x*(1.0f-c)+c; M[4*0+1] = x*y*(1.0f-c)-z*s; M[4*0+2] = x*z*(1.0f-c)+y*s; M[4*0+3] = 0.0f; M[4*1+0] = y*x*(1.0f-c)+z*s; M[4*1+1] = y*y*(1.0f-c)+c; M[4*1+2] = y*z*(1.0f-c)-x*s; M[4*1+3] = 0.0f; M[4*2+0] = z*x*(1.0f-c)-y*s; M[4*2+1] = z*y*(1.0f-c)+x*s; M[4*2+2] = z*z*(1.0f-c)+c; M[4*2+3] = 0.0f; M[4*3+0] = 0.0f; M[4*3+1] = 0.0f; M[4*3+2] = 0.0f; M[4*3+3] = 1.0f; GLUP::transpose_matrix(M); glupMultMatrixf(M); } void glupRotated( GLUPdouble angle, GLUPdouble x, GLUPdouble y, GLUPdouble z ) { GEO_CHECK_GL(); glupRotatef(GLfloat(angle), GLfloat(x), GLfloat(y), GLfloat(z)); } void glupOrtho( GLUPdouble left, GLUPdouble right, GLUPdouble bottom, GLUPdouble top, GLUPdouble nearVal, GLUPdouble farVal ) { GEO_CHECK_GL(); GLfloat M[16]; GLdouble tx = -(right+left)/(right-left); GLdouble ty = -(top+bottom)/(top-bottom); GLdouble tz = -(farVal+nearVal)/(farVal-nearVal); M[4*0+0] = GLfloat(2.0 / (right-left)); M[4*0+1] = 0.0f; M[4*0+2] = 0.0f; M[4*0+3] = GLfloat(tx); M[4*1+0] = 0.0f; M[4*1+1] = GLfloat(2.0 / (top-bottom)); M[4*1+2] = 0.0f; M[4*1+3] = GLfloat(ty); M[4*2+0] = 0.0f; M[4*2+1] = 0.0f; M[4*2+2] = GLfloat(-2.0 / (farVal - nearVal)); M[4*2+3] = GLfloat(tz); M[4*3+0] = 0.0f; M[4*3+1] = 0.0f; M[4*3+2] = 0.0f; M[4*3+3] = 1.0f; GLUP::transpose_matrix(M); glupMultMatrixf(M); } void glupOrtho2D( GLUPdouble left, GLUPdouble right, GLUPdouble bottom, GLUPdouble top ) { GEO_CHECK_GL(); glupOrtho(left, right, bottom, top, -1.0, 1.0); } void glupFrustum( GLUPdouble left, GLUPdouble right, GLUPdouble bottom, GLUPdouble top, GLUPdouble nearVal, GLUPdouble farVal ) { GEO_CHECK_GL(); GLfloat M[16]; GLdouble A = (right + left) / (right - left); GLdouble B = (top + bottom) / (top - bottom); GLdouble C = -(farVal + nearVal) / (farVal - nearVal); GLdouble D = -2.0*farVal*nearVal / (farVal - nearVal); M[4*0+0] = GLfloat(2.0 * nearVal / (right - left)); M[4*0+1] = 0.0f; M[4*0+2] = GLfloat(A); M[4*0+3] = 0.0f; M[4*1+0] = 0.0f; M[4*1+1] = GLfloat(2.0 * nearVal / (top - bottom)); M[4*1+2] = GLfloat(B); M[4*1+3] = 0.0f; M[4*2+0] = 0.0f; M[4*2+1] = 0.0f; M[4*2+2] = GLfloat(C); M[4*2+3] = GLfloat(D); M[4*3+0] = 0.0f; M[4*3+1] = 0.0f; M[4*3+2] = -1.0f; M[4*3+3] = 0.0f; GLUP::transpose_matrix(M); glupMultMatrixf(M); } void glupPerspective( GLUPdouble fovy, GLUPdouble aspect, GLUPdouble zNear, GLUPdouble zFar ) { GEO_CHECK_GL(); GLfloat M[16]; double f = 1.0 / tan(fovy * M_PI / 180.0); M[4*0+0] = GLfloat(f / aspect); M[4*0+1] = 0.0f; M[4*0+2] = 0.0f; M[4*0+3] = 0.0f; M[4*1+0] = 0.0f; M[4*1+1] = GLfloat(f); M[4*1+2] = 0.0f; M[4*1+3] = 0.0f; M[4*2+0] = 0.0f; M[4*2+1] = 0.0f; M[4*2+2] = GLfloat((zFar+zNear)/(zNear-zFar)); M[4*2+3] = GLfloat(2.0*zFar*zNear/(zNear-zFar)); M[4*3+0] = 0.0f; M[4*3+1] = 0.0f; M[4*3+2] = -1.0f; M[4*3+3] = 0.0f; GLUP::transpose_matrix(M); glupMultMatrixf(M); } GLUPint glupProject( GLUPdouble objx, GLUPdouble objy, GLUPdouble objz, const GLUPdouble modelMatrix[16], const GLUPdouble projMatrix[16], const GLUPint viewport[4], GLUPdouble* winx, GLUPdouble* winy, GLUPdouble* winz ) { GEO_CHECK_GL(); double in[4]; double out[4]; in[0]=objx; in[1]=objy; in[2]=objz; in[3]=1.0; GLUP::mult_transpose_matrix_vector(out, modelMatrix, in); GLUP::mult_transpose_matrix_vector(in, projMatrix, out); if (in[3] == 0.0) { return(GL_FALSE); } in[0] /= in[3]; in[1] /= in[3]; in[2] /= in[3]; // Map x, y and z to range 0-1 */ in[0] = in[0] * 0.5 + 0.5; in[1] = in[1] * 0.5 + 0.5; in[2] = in[2] * 0.5 + 0.5; // Map x,y to viewport in[0] = in[0] * viewport[2] + viewport[0]; in[1] = in[1] * viewport[3] + viewport[1]; *winx=in[0]; *winy=in[1]; *winz=in[2]; return(GL_TRUE); } GLUPboolean glupUnProject( GLUPdouble winx, GLUPdouble winy, GLUPdouble winz, const GLUPdouble modelMatrix[16], const GLUPdouble projMatrix[16], const GLUPint viewport[4], GLUPdouble *objx, GLUPdouble *objy, GLUPdouble *objz ) { GEO_CHECK_GL(); double modelviewproject[16]; double modelviewproject_inv[16]; GLUP::mult_matrices(modelviewproject, modelMatrix, projMatrix); if(!GLUP::invert_matrix(modelviewproject_inv, modelviewproject)) { return GL_FALSE; } double in[4]; in[0] = winx; in[1] = winy; in[2] = winz; in[3] = 1.0; // Invert viewport transform in[0] = (in[0] - double(viewport[0])) / double(viewport[2]); in[1] = (in[1] - double(viewport[1])) / double(viewport[3]); // Map to [-1, 1] in[0] = in[0] * 2.0 - 1.0; in[1] = in[1] * 2.0 - 1.0; in[2] = in[2] * 2.0 - 1.0; double out[4]; GLUP::mult_transpose_matrix_vector(out, modelviewproject_inv, in); if(out[3] == 0.0) { return GL_FALSE; } *objx = out[0] / out[3]; *objy = out[1] / out[3]; *objz = out[2] / out[3]; return GL_TRUE; } GLUPboolean glupInvertMatrixfv( GLUPfloat Minvert[16], const GLUPfloat M[16] ) { GEO_CHECK_GL(); return GLUP::invert_matrix(Minvert, M); } GLUPboolean glupInvertMatrixdv( GLUPdouble Minvert[16], const GLUPdouble M[16] ) { GEO_CHECK_GL(); return GLUP::invert_matrix(Minvert, M); } /******************* Drawing ***************************/ void glupDrawArrays( GLUPprimitive primitive, GLUPint first, GLUPsizei count ) { GEO_CHECK_GL(); GLUP::current_context_->draw_arrays( primitive, first, count ); GEO_CHECK_GL(); } void glupDrawElements( GLUPprimitive primitive, GLUPsizei count, GLUPenum type, const GLUPvoid* indices ) { GEO_CHECK_GL(); GLUP::current_context_->draw_elements( primitive, count, type, indices ); GEO_CHECK_GL(); } void glupBegin(GLUPprimitive primitive) { GEO_CHECK_GL(); GLUP::current_context_->begin(primitive); GEO_CHECK_GL(); } void glupEnd() { GEO_CHECK_GL(); GLUP::current_context_->end(); GEO_CHECK_GL(); } void glupVertex2fv(const GLUPfloat* xy) { GEO_CHECK_GL(); GLUP::current_context_->immediate_vertex(xy[0], xy[1]); } void glupVertex3fv(const GLUPfloat* xyz) { GEO_CHECK_GL(); GLUP::current_context_->immediate_vertex(xyz[0], xyz[1], xyz[2]); } void glupVertex4fv(const GLUPfloat* xyzw) { GEO_CHECK_GL(); GLUP::current_context_->immediate_vertex( xyzw[0], xyzw[1], xyzw[2], xyzw[3] ); } void glupVertex2dv(const GLUPdouble* xy) { GEO_CHECK_GL(); GLUP::current_context_->immediate_vertex( GLfloat(xy[0]), GLfloat(xy[1]) ); } void glupVertex3dv(const GLUPdouble* xyz) { GEO_CHECK_GL(); GLUP::current_context_->immediate_vertex( GLfloat(xyz[0]), GLfloat(xyz[1]), GLfloat(xyz[2]) ); } void glupVertex4dv(const GLUPdouble* xyzw) { GEO_CHECK_GL(); GLUP::current_context_->immediate_vertex( GLfloat(xyzw[0]), GLfloat(xyzw[1]), GLfloat(xyzw[2]), GLfloat(xyzw[3]) ); } void glupVertex2f(GLUPfloat x, GLUPfloat y) { GEO_CHECK_GL(); GLUP::current_context_->immediate_vertex(x,y); } void glupVertex3f(GLUPfloat x, GLUPfloat y, GLUPfloat z) { GEO_CHECK_GL(); GLUP::current_context_->immediate_vertex(x,y,z); } void glupVertex4f(GLUPfloat x, GLUPfloat y, GLUPfloat z, GLUPfloat w) { GEO_CHECK_GL(); GLUP::current_context_->immediate_vertex(x,y,z,w); } void glupVertex2d(GLUPdouble x, GLUPdouble y) { GEO_CHECK_GL(); GLUP::current_context_->immediate_vertex( GLfloat(x), GLfloat(y) ); } void glupVertex3d(GLUPdouble x, GLUPdouble y, GLUPdouble z) { GEO_CHECK_GL(); GLUP::current_context_->immediate_vertex( GLfloat(x), GLfloat(y), GLfloat(z) ); } void glupVertex4d(GLUPdouble x, GLUPdouble y, GLUPdouble z, GLUPdouble w) { GEO_CHECK_GL(); GLUP::current_context_->immediate_vertex( GLfloat(x), GLfloat(y), GLfloat(z), GLfloat(w) ); } void glupColor3fv(const GLUPfloat* rgb) { GEO_CHECK_GL(); GLUP::current_context_->immediate_color(rgb[0], rgb[1], rgb[2]); } void glupColor4fv(const GLUPfloat* rgba) { GEO_CHECK_GL(); GLUP::current_context_->immediate_color(rgba[0], rgba[1], rgba[2], rgba[3]); } void glupColor3dv(const GLUPdouble* rgb) { GEO_CHECK_GL(); GLUP::current_context_->immediate_color( GLfloat(rgb[0]), GLfloat(rgb[1]), GLfloat(rgb[2]) ); } void glupColor4dv(const GLUPdouble* rgba) { GEO_CHECK_GL(); GLUP::current_context_->immediate_color( GLfloat(rgba[0]), GLfloat(rgba[1]), GLfloat(rgba[2]), GLfloat(rgba[3]) ); } void glupColor3f(GLUPfloat r, GLUPfloat g, GLUPfloat b) { GEO_CHECK_GL(); GLUP::current_context_->immediate_color(r, g, b); } void glupColor4f(GLUPfloat r, GLUPfloat g, GLUPfloat b, GLUPfloat a) { GEO_CHECK_GL(); GLUP::current_context_->immediate_color(r, g, b, a); } void glupColor3d(GLUPdouble r, GLUPdouble g, GLUPdouble b) { GEO_CHECK_GL(); GLUP::current_context_->immediate_color( GLfloat(r), GLfloat(g), GLfloat(b) ); } void glupColor4d(GLUPdouble r, GLUPdouble g, GLUPdouble b, GLUPdouble a) { GEO_CHECK_GL(); GLUP::current_context_->immediate_color( GLfloat(r), GLfloat(g), GLfloat(b), GLfloat(a) ); } void glupTexCoord2fv(const GLUPfloat* st) { GEO_CHECK_GL(); GLUP::current_context_->immediate_tex_coord(st[0], st[1]); } void glupTexCoord3fv(const GLUPfloat* stu) { GEO_CHECK_GL(); GLUP::current_context_->immediate_tex_coord(stu[0], stu[1], stu[2]); } void glupTexCoord4fv(const GLUPfloat* stuv) { GEO_CHECK_GL(); GLUP::current_context_->immediate_tex_coord( stuv[0], stuv[1], stuv[2], stuv[3] ); } void glupTexCoord2dv(const GLUPdouble* st) { GEO_CHECK_GL(); GLUP::current_context_->immediate_tex_coord( GLfloat(st[0]), GLfloat(st[1]) ); } void glupTexCoord3dv(const GLUPdouble* stu) { GEO_CHECK_GL(); GLUP::current_context_->immediate_tex_coord( GLfloat(stu[0]), GLfloat(stu[1]), GLfloat(stu[2]) ); } void glupTexCoord4dv(const GLUPdouble* stuv) { GEO_CHECK_GL(); GLUP::current_context_->immediate_tex_coord( GLfloat(stuv[0]), GLfloat(stuv[1]), GLfloat(stuv[2]), GLfloat(stuv[3]) ); } void glupTexCoord1f(GLUPfloat s) { GEO_CHECK_GL(); GLUP::current_context_->immediate_tex_coord(s); } void glupTexCoord2f(GLUPfloat s, GLUPfloat t) { GEO_CHECK_GL(); GLUP::current_context_->immediate_tex_coord(s,t); } void glupTexCoord3f(GLUPfloat s, GLUPfloat t, GLUPfloat u) { GEO_CHECK_GL(); GLUP::current_context_->immediate_tex_coord(s,t,u); } void glupTexCoord4f(GLUPfloat s, GLUPfloat t, GLUPfloat u, GLUPfloat v) { GEO_CHECK_GL(); GLUP::current_context_->immediate_tex_coord(s,t,u,v); } void glupTexCoord1d(GLUPdouble s) { GEO_CHECK_GL(); GLUP::current_context_->immediate_tex_coord( GLfloat(s) ); } void glupTexCoord2d(GLUPdouble s, GLUPdouble t) { GEO_CHECK_GL(); GLUP::current_context_->immediate_tex_coord( GLfloat(s), GLfloat(t) ); } void glupTexCoord3d(GLUPdouble s, GLUPdouble t, GLUPdouble u) { GEO_CHECK_GL(); GLUP::current_context_->immediate_tex_coord( GLfloat(s), GLfloat(t), GLfloat(u) ); } void glupTexCoord4d(GLUPdouble s, GLUPdouble t, GLUPdouble u, GLUPdouble v) { GEO_CHECK_GL(); GLUP::current_context_->immediate_tex_coord( GLfloat(s), GLfloat(t), GLfloat(u), GLfloat(v) ); } void glupNormal3fv(GLUPfloat* xyz) { GEO_CHECK_GL(); GLUP::current_context_->immediate_normal( xyz[0],xyz[1],xyz[2] ); } void glupNormal3f(GLUPfloat x, GLUPfloat y, GLUPfloat z) { GEO_CHECK_GL(); GLUP::current_context_->immediate_normal( x,y,z ); } void glupNormal3dv(GLUPdouble* xyz) { GEO_CHECK_GL(); GLUP::current_context_->immediate_normal( GLfloat(xyz[0]), GLfloat(xyz[1]), GLfloat(xyz[2]) ); } void glupNormal3d(GLUPdouble x, GLUPdouble y, GLUPdouble z) { GEO_CHECK_GL(); GLUP::current_context_->immediate_normal( GLfloat(x), GLfloat(y), GLfloat(z) ); } void glupUseProgram(GLUPuint program) { GEO_CHECK_GL(); GLUP::current_context_->set_user_program(program); } /****************************************************************************/ namespace GLUP { static GLUPuint vertex_array_binding = 0; static GLint max_vertex_attrib = 0; /** * \brief If true, then GLUP uses its own implementation * of Vertex Array Object. * \details This is for instance required * when using GLUP with Emscripten, in a brower that does * not have the Vertex Array Object extension (see * Context_GLES.cpp) */ bool vertex_array_emulate = false; /** * \brief Stores the state of a vertex attribute * binding. * \details Used to implement emulated vertex array * objects. * \see VertexArrayObject. */ class VertexAttribBinding { public: /** * \brief VertexAttribBinding constructor. */ VertexAttribBinding() : enabled(GL_FALSE), size(0), type(GL_FLOAT), normalized(GL_FALSE), stride(0), pointer(nullptr), buffer_binding(0) { } /** * \brief Copies the binding of a vertex attribute * from OpenGL state to this VertexAttribBinding. * \param[in] index the index of the attribute */ void copy_from_GL(GLuint index) { // From the spec, glGetVertexAttribiv is supposed // to return 4 values always, even if we are only // interested in the first one, I guess it is needed // to read in a buffer with enough space for 4 values. GLint buff[4]; glGetVertexAttribiv( index, GL_VERTEX_ATTRIB_ARRAY_ENABLED, buff ); enabled = buff[0]; // With some webbrowsers, querying a vertex attrib array // that is not enabled returns the default values instead // of the actual values. if(!enabled) { glEnableVertexAttribArray(index); } glGetVertexAttribiv( index, GL_VERTEX_ATTRIB_ARRAY_SIZE, buff ); size = buff[0]; glGetVertexAttribiv( index, GL_VERTEX_ATTRIB_ARRAY_TYPE, buff ); type = buff[0]; glGetVertexAttribiv( index, GL_VERTEX_ATTRIB_ARRAY_NORMALIZED, buff ); normalized = buff[0]; glGetVertexAttribiv( index, GL_VERTEX_ATTRIB_ARRAY_STRIDE, buff ); stride = buff[0]; glGetVertexAttribPointerv( index, GL_VERTEX_ATTRIB_ARRAY_POINTER, &pointer ); glGetVertexAttribiv( index, GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING, buff ); buffer_binding = buff[0]; if(!enabled) { glDisableVertexAttribArray(index); } } /** * \brief Copies the binding stored in this VertexAttribBinding * into OpenGL. * \param[in] index the index of the attribute where the binding * should be copied. */ void copy_to_GL(GLuint index) { if(enabled) { glEnableVertexAttribArray(index); } else { glDisableVertexAttribArray(index); } glBindBuffer(GL_ARRAY_BUFFER, GLuint(buffer_binding)); if(buffer_binding != 0 || pointer != nullptr ) { glVertexAttribPointer( index, size, GLenum(type), GLboolean(normalized), GLsizei(stride), pointer ); } } /** * \brief Resets all the stored bindings to default * values. */ void reset() { enabled=GL_FALSE; size=0; type=GL_FLOAT; normalized=GL_FALSE; stride=0; pointer=nullptr; buffer_binding=0; } private: GLint enabled; GLint size; GLint type; GLint normalized; GLint stride; GLvoid* pointer; GLint buffer_binding; }; /** * \brief Emulates vertex array objects if not supported * by OpenGL implementation. */ class VertexArrayObject { public: /** * \brief The maximum number of vertex attributes * that we save in a VAO. * \details For GLUP, only 4 are needed. Can be * increased if need be. */ enum {MAX_VERTEX_ATTRIB = 4}; /** * \brief VertexArrayObject constructor. */ VertexArrayObject() : element_array_buffer_binding_(0) { if(max_vertex_attrib == 0) { glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &max_vertex_attrib); max_vertex_attrib = std::min( max_vertex_attrib, GLint(MAX_VERTEX_ATTRIB) ); } } /** * \brief Binds this VertexArrayObject. * \details This copies the stored element array and vertex attribute * bindings to OpenGL. */ void bind() { glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, GLuint(element_array_buffer_binding_) ); for(GLint i=0; i<max_vertex_attrib; ++i) { attrib_binding_[i].copy_to_GL(GLuint(i)); } } /** * \brief Unbinds this VertexArrayObject. * \details This copies the currently bound element array and * vertex attribute bindings from OpenGL to this VertexArrayObject. */ void unbind() { // Note: In Emscripten, glGetIntegerv() does not suffer from the // same bug as glGetVertexAttribiv( // ..., GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING, ... // ), therefore there is no special case here. glGetIntegerv( GL_ELEMENT_ARRAY_BUFFER_BINDING, &element_array_buffer_binding_ ); for(GLint i=0; i<max_vertex_attrib; ++i) { attrib_binding_[i].copy_from_GL(GLuint(i)); } } /** * \brief Resets all the stored bindings to default * values. */ void reset() { element_array_buffer_binding_ = 0; for(GLint i=0; i<max_vertex_attrib; ++i) { attrib_binding_[i].reset(); } } private: VertexAttribBinding attrib_binding_[MAX_VERTEX_ATTRIB]; GLint element_array_buffer_binding_; }; /** * \brief Manages the emulated vertex array objects. */ class VertexArrayObjectAllocator { public: /** * \brief VertexArrayObjectAllocator constructor. */ VertexArrayObjectAllocator() { // Create the dummy slot 0. slots_.push_back(Slot()); } /** * \brief VertexArrayObjectAllocator destructor. */ ~VertexArrayObjectAllocator() { for(index_t i=0; i<slots_.size(); ++i) { if(slots_[i].VAO != nullptr) { delete slots_[i].VAO; slots_[i].VAO = nullptr; } } } /** * \brief Creates a new vertex array object. * \return the index of the newly created vertex * array object. */ index_t new_VAO() { index_t result = 0; if(first_free_ != 0) { result = first_free_; first_free_ = slots_[first_free_].next; slots_[result].VAO->reset(); } else { slots_.push_back(Slot()); result = index_t(slots_.size()-1); slots_[result].VAO = new VertexArrayObject(); } return result; } /** * \brief Deletes a vertex array object. * \details Vertex array objects are recycled internally. * \param[in] VAOindex the index of the vertex * array object to delete. */ void delete_VAO(index_t VAOindex) { slots_[VAOindex].next = first_free_; first_free_ = VAOindex; } /** * \brief Gets a vertex array object by index. * \param[in] VAOindex the index of the vertex array object. * \return a pointer to the vertex array object. */ VertexArrayObject* get_VAO(index_t VAOindex) { return slots_[VAOindex].VAO; } private: /** * \brief The information attached to each vertex * array object index. */ struct Slot { /** * \brief Slot constructor. */ Slot() : VAO(nullptr), next(0) { } /** * \brief A pointer to the internal representation. */ VertexArrayObject* VAO; /** * \brief The index of the next free element, used * to have constant-time allocation and deallocation. */ index_t next; }; vector<Slot> slots_; /** * \brief The head of the free list. */ GLUPuint first_free_; }; static VertexArrayObjectAllocator VAO_allocator; } // TODO1: ArraysOES()/Arrays() switch based on OpenGL profile // (runtime) rather than GEO_OS_EMSCRIPTEN macro (compile-time) void glupGenVertexArrays(GLUPsizei n, GLUPuint* arrays) { if(GLUP::vertex_array_emulate) { for(GLUPsizei i=0; i<n; ++i) { arrays[i] = GLUP::VAO_allocator.new_VAO(); } } else { #ifdef GEO_OS_EMSCRIPTEN glGenVertexArraysOES(n, arrays); #else if(!glGenVertexArrays) { GLUP::vertex_array_emulate = true; glupGenVertexArrays(n,arrays); return; } glGenVertexArrays(n, arrays); #endif } } void glupDeleteVertexArrays(GLUPsizei n, const GLUPuint *arrays) { if(GLUP::vertex_array_emulate) { for(GLUPsizei i=0; i<n; ++i) { GLUP::VAO_allocator.delete_VAO(arrays[i]); } } else { #if defined(GEO_OS_EMSCRIPTEN) glDeleteVertexArraysOES(n, arrays); #else if(!glDeleteVertexArrays) { GLUP::vertex_array_emulate = true; glupDeleteVertexArrays(n,arrays); return; } glDeleteVertexArrays(n, arrays); #endif } } void glupBindVertexArray(GLUPuint array) { if(GLUP::vertex_array_emulate) { if(array != GLUP::vertex_array_binding) { if(GLUP::vertex_array_binding != 0) { GLUP::VAO_allocator.get_VAO( GLUP::vertex_array_binding )->unbind(); } GLUP::vertex_array_binding = array; if(GLUP::vertex_array_binding != 0) { GLUP::VAO_allocator.get_VAO( GLUP::vertex_array_binding )->bind(); } } } else { #if defined(GEO_OS_EMSCRIPTEN) glBindVertexArrayOES(array); #else if(!glBindVertexArray) { GLUP::vertex_array_emulate = true; glupBindVertexArray(array); return; } glBindVertexArray(array); #endif GLUP::vertex_array_binding = array; } } GLUPuint glupGetVertexArrayBinding() { return GLUP::vertex_array_binding; } /****************************************************************************/
26.729958
109
0.578039
[ "object", "vector", "transform" ]
b42a61abf31bbda49cbe96b24737e00065c864e2
4,623
cpp
C++
src/tmp_main.cpp
parasol-ppl/PPL
04de04b23e0368e576d2136fee8729de44a3eda5
[ "BSD-3-Clause" ]
null
null
null
src/tmp_main.cpp
parasol-ppl/PPL
04de04b23e0368e576d2136fee8729de44a3eda5
[ "BSD-3-Clause" ]
null
null
null
src/tmp_main.cpp
parasol-ppl/PPL
04de04b23e0368e576d2136fee8729de44a3eda5
[ "BSD-3-Clause" ]
null
null
null
#include <exception> #include <limits> #include <string> #include "Behaviors/Agents/Agent.h" #include "Behaviors/Agents/Coordinator.h" #include "Traits/CfgTraits.h" #include "TMPLibrary/TMPLibrary.h" #include "TMPLibrary/Solution/Plan.h" #include "MPProblem/MPProblem.h" #include "MPProblem/MPTask.h" #include "MPProblem/GroupTask.h" #include "MPProblem/Robot/Robot.h" #include "MPProblem/TaskHierarchy/Decomposition.h" #include "MPProblem/TaskHierarchy/SemanticTask.h" #include "Utilities/PMPLExceptions.h" int main(int _argc, char** _argv) { // Assert that this platform supports an infinity for doubles. if(!std::numeric_limits<double>::has_infinity) throw RunTimeException(WHERE) << "This platform does not support infinity " << "for double-types, which is required for " << "pmpl to work properly."; if(_argc != 3 || std::string(_argv[1]) != "-f") throw ParseException(WHERE) << "Incorrect usage. Usage: -f options.xml"; // Get the XML file name from the command line. std::string xmlFile = _argv[2]; // Parse the Problem node into an MPProblem object. MPProblem* problem = new MPProblem(xmlFile); // Parse the Library node into an TMPLibrary object. TMPLibrary* ppl = new TMPLibrary(xmlFile); // Position the robot by sampling from the first task and set colors. /// @TODO Decide on a way to declare the starting configuration either /// explicitly or from a specific task. For now we will assume that /// the first task is a query and its start boundary is a single point. if(!problem->GetRobotGroups().empty()) { for(const auto& group : problem->GetRobotGroups()) { //TODO needs to be updated to track which robots have been given a //starting position and which ones have not when considering multiple //grouptasks auto groupTask = problem->GetTasks(group.get()).front(); for(auto it = groupTask->begin(); it != groupTask->end(); it++){ Robot* const r = it->GetRobot(); if(r->IsVirtual()) continue; // Position the robot at zero, or at the task center if one exists. std::vector<double> dofs(r->GetMultiBody()->DOF(), 0); if(it->GetStartConstraint()) dofs = it->GetStartConstraint()-> GetBoundary()->GetCenter(); r->GetMultiBody()->Configure(dofs); // Store robot's initial position Cfg initial(r); initial.SetData(dofs); problem->SetInitialCfg(r,initial); } } } else { for(const auto& robot : problem->GetRobots()) { Robot* const r = robot.get(); if(r->IsVirtual()) continue; // Position the robot at zero, or at the task center if one exists. std::vector<double> dofs(r->GetMultiBody()->DOF(), 0); if(problem->GetTasks(r).front()->GetStartConstraint()) dofs = problem->GetTasks(r).front()->GetStartConstraint()-> GetBoundary()->GetCenter(); r->GetMultiBody()->Configure(dofs); // Store robot's initial position Cfg initial(r); initial.SetData(dofs); problem->SetInitialCfg(r,initial); } } /* // Create storage for the solution and ask the library to solve our problem. std::vector<std::shared_ptr<MPTask>> tasks; for(auto& r : problem->GetRobots()) { // Collect the robot's tasks auto robotTasks = problem->GetTasks(r.get()); for(auto task : robotTasks) if(!task->GetStatus().is_complete()) tasks.push_back(task); } ppl->Solve(problem, tasks); // Also solve the group task(s). std::vector<std::shared_ptr<GroupTask>> groupTasks; if(!problem->GetRobotGroups().empty()) { for(auto& robotGroup : problem->GetRobotGroups()) for(auto groupTask : problem->GetTasks(robotGroup.get())) groupTasks.push_back(groupTask); ppl->Solve(problem, groupTasks); } if(tasks.empty() and groupTasks.empty()) throw RunTimeException(WHERE) << "No tasks were specified!"; */ for(const auto& decomps : problem->GetDecompositions()) { auto a = decomps.first->GetAgent(); auto c = dynamic_cast<Coordinator*>(a); std::vector<Robot*> team; for(auto label : c->GetMemberLabels()){ team.push_back(problem->GetRobot(label)); } for(const auto& decomp : decomps.second) { Plan* plan = new Plan(); plan->SetCoordinator(c); plan->SetTeam(team); plan->SetDecomposition(decomp.get()); ppl->Solve(problem, decomp.get(), plan, c, team); } } // Release resources. delete problem; delete ppl; return 0; }
34.244444
81
0.645685
[ "object", "vector" ]
b42b0245793406c47a0b8b9c6b5479405b64fcd1
4,944
cpp
C++
sparse/src/mgpusparse/engine.cpp
seanbaxter/mgpu_old
70efdac1daa1e51d1968c0a006292fd843723eae
[ "Unlicense" ]
4
2016-03-22T22:15:37.000Z
2020-06-22T22:41:51.000Z
sparse/src/mgpusparse/engine.cpp
jayavanth/mgpu
70efdac1daa1e51d1968c0a006292fd843723eae
[ "Unlicense" ]
null
null
null
sparse/src/mgpusparse/engine.cpp
jayavanth/mgpu
70efdac1daa1e51d1968c0a006292fd843723eae
[ "Unlicense" ]
2
2016-04-21T05:06:16.000Z
2020-06-22T22:41:54.000Z
#include "engine.h" #include <sstream> const char* PrecNames[4] = { "float", "double", "cfloat", "cdouble" }; const PrecTerm PrecTerms[4] = { { 4, CU_AD_FORMAT_FLOAT, 1, }, { 8, CU_AD_FORMAT_UNSIGNED_INT32, 2 }, { 8, CU_AD_FORMAT_FLOAT, 2 }, { 16, CU_AD_FORMAT_UNSIGNED_INT32, 4 } }; int IndexFromVT(int vt) { for(int i(0); i < NumVT; ++i) if(ValuesPerThread[i] == vt) return i; return -1; } /* void Zero(float& x) { x = 0; } void Zero(double& x) { x = 0; } void Zero(float2& x) { x = make_float2(0, 0); } void Zero(double2& x) { x = make_double2(0, 0); } */ bool IsZero(float x) { return !x; } bool IsZero(double x) { return !x; } bool IsZero(float2 x) { return !x.x && x.y; } bool IsZero(double2 x) { return !x.x && x.y; } sparseStatus_t CreateSparseEngine(const char* kernelPath, EnginePtr* ppEngine) { EnginePtr engine(new sparseEngine_d); engine->kernelPath = kernelPath; AttachCuContext(&engine->context); engine->numSMs = engine->context->Device()->NumSMs(); if(2 != engine->context->Device()->ComputeCapability().first) return SPARSE_STATUS_CONFIG_NOT_SUPPORTED; ppEngine->swap(engine); return SPARSE_STATUS_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // sparseEngine_d::LoadKernel sparseStatus_t sparseEngine_d::LoadKernel(sparsePrec_t prec, sparseEngine_d::Kernel** ppKernel) { // First attempt to load the finalize module if it is not yet loaded. CUresult result = CUDA_SUCCESS; // Check if the requested kernel is available, and if not, load it. int p = (int)prec; if(!multiply[p].get()) { std::auto_ptr<Kernel> k(new Kernel); std::string filename = kernelPath + "spmxv_" + PrecNames[p] + ".cubin"; result = context->LoadModuleFilename(filename, &k->module); if(CUDA_SUCCESS != result) return SPARSE_STATUS_KERNEL_NOT_FOUND; // Load the five SpMxV kernels for different valuesPerThread counts. for(int i(0); i < NumVT; ++i) { std::ostringstream oss; oss<< "SpMxV_"<< ValuesPerThread[i]; result = k->module->GetFunction(oss.str(), make_int3(BlockSize, 1,1), &k->func[i]); if(CUDA_SUCCESS != result) return SPARSE_STATUS_KERNEL_ERROR; } // Load the finalize function. result = k->module->GetFunction("Finalize", make_int3(BlockSize, 1, 1), &k->finalize); if(CUDA_SUCCESS != result) return SPARSE_STATUS_KERNEL_ERROR; // Cache the texture reference result = cuModuleGetTexRef(&k->xVec_texture, k->module->Handle(), "xVec_texture"); if(CUDA_SUCCESS != result) return SPARSE_STATUS_KERNEL_ERROR; result = cuTexRefSetFlags(k->xVec_texture, CU_TRSF_READ_AS_INTEGER); if(CUDA_SUCCESS != result) return SPARSE_STATUS_KERNEL_ERROR; result = cuTexRefSetFormat(k->xVec_texture, PrecTerms[p].vecFormat, PrecTerms[p].vecChannels); if(CUDA_SUCCESS != result) return SPARSE_STATUS_KERNEL_ERROR; multiply[p] = k; } *ppKernel = multiply[p].get(); return SPARSE_STATUS_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // sparseEngine_d::Multiply template<typename T> sparseStatus_t sparseEngine_d::Multiply(sparseMat_t mat, T alpha, T beta, CUdeviceptr xVec, CUdeviceptr yVec) { sparseMatrix* m = static_cast<sparseMatrix*>(mat); Kernel* k; sparseStatus_t status = LoadKernel(m->prec, &k); if(SPARSE_STATUS_SUCCESS != status) return status; // Push the args and select the xVec as a texture CuCallStack callStack; callStack.Push(m->outputIndices, m->colIndices, m->sparseValues, m->tempOutput, m->numGroups); // Get the size of the xVec elements PrecTerm precTerms = PrecTerms[m->prec]; size_t offset; CUresult result = cuTexRefSetAddress(&offset, k->xVec_texture, xVec, m->width * precTerms.vecSize); if(CUDA_SUCCESS != result) return SPARSE_STATUS_KERNEL_ERROR; // Launch the function uint numBlocks = DivUp(m->numGroups, WarpsPerBlock); result = k->func[IndexFromVT(m->valuesPerThread)]->Launch(numBlocks, 1, callStack); if(CUDA_SUCCESS != result) return SPARSE_STATUS_LAUNCH_ERROR; // Finalize the vector int numFinalizeBlocks = DivUp(m->numGroups, WarpsPerBlock); int useBeta = !IsZero(beta); callStack.Reset(); callStack.Push(m->tempOutput, m->rowIndices, m->height, yVec, alpha, beta, useBeta); result = k->finalize->Launch(numFinalizeBlocks, 1, callStack); if(CUDA_SUCCESS != result) return SPARSE_STATUS_KERNEL_ERROR; return SPARSE_STATUS_SUCCESS; } template sparseStatus_t sparseEngine_d::Multiply(sparseMat_t mat, float alpha, float beta, CUdeviceptr xVec, CUdeviceptr yVec); template sparseStatus_t sparseEngine_d::Multiply(sparseMat_t mat, double alpha, double beta, CUdeviceptr xVec, CUdeviceptr yVec); template sparseStatus_t sparseEngine_d::Multiply(sparseMat_t mat, float2 alpha, float2 beta, CUdeviceptr xVec, CUdeviceptr yVec); template sparseStatus_t sparseEngine_d::Multiply(sparseMat_t mat, double2 alpha, double2 beta, CUdeviceptr xVec, CUdeviceptr yVec);
30.9
80
0.704288
[ "vector" ]
b42c443823aae20d4f584986cfc2e2d359694952
1,327
hpp
C++
core/model/include/sme/model_functions.hpp
lkeegan/spatial-model-editor
5dcb06550607b0a734acddd8b719035b68e35307
[ "MIT" ]
4
2019-07-18T15:05:09.000Z
2020-03-14T09:50:07.000Z
core/model/include/sme/model_functions.hpp
lkeegan/spatial-model-editor
5dcb06550607b0a734acddd8b719035b68e35307
[ "MIT" ]
328
2019-06-30T12:03:01.000Z
2020-10-05T15:56:35.000Z
core/model/include/sme/model_functions.hpp
lkeegan/spatial-model-editor
5dcb06550607b0a734acddd8b719035b68e35307
[ "MIT" ]
1
2019-06-08T22:47:14.000Z
2019-06-08T22:47:14.000Z
// SBML functions #pragma once #include "sme/symbolic.hpp" #include <QColor> #include <QStringList> #include <map> #include <optional> #include <string> namespace libsbml { class Model; } namespace sme { namespace model { class ModelFunctions { private: QStringList ids; QStringList names; libsbml::Model *sbmlModel = nullptr; bool hasUnsavedChanges{false}; public: ModelFunctions(); explicit ModelFunctions(libsbml::Model *model); [[nodiscard]] const QStringList &getIds() const; [[nodiscard]] const QStringList &getNames() const; QString setName(const QString &id, const QString &name); [[nodiscard]] QString getName(const QString &id) const; void setExpression(const QString &id, const QString &expression); [[nodiscard]] QString getExpression(const QString &id) const; [[nodiscard]] QStringList getArguments(const QString &id) const; QString addArgument(const QString &functionId, const QString &argumentId); void removeArgument(const QString &functionId, const QString &argumentId); QString add(const QString &name); void remove(const QString &id); [[nodiscard]] std::vector<common::SymbolicFunction> getSymbolicFunctions() const; [[nodiscard]] bool getHasUnsavedChanges() const; void setHasUnsavedChanges(bool unsavedChanges); }; } // namespace model } // namespace sme
26.54
76
0.746797
[ "vector", "model" ]
b42d18c08c1f328791065e6132fa174a130dfdaa
10,906
cpp
C++
src/target_tracker.cpp
RenFukatsu/kalman_filter
15439fd4d707de71c3020001183199f99f2b3fc6
[ "MIT" ]
null
null
null
src/target_tracker.cpp
RenFukatsu/kalman_filter
15439fd4d707de71c3020001183199f99f2b3fc6
[ "MIT" ]
null
null
null
src/target_tracker.cpp
RenFukatsu/kalman_filter
15439fd4d707de71c3020001183199f99f2b3fc6
[ "MIT" ]
null
null
null
#include "kalman_filter/target_tracker.h" TargetTracker::TargetTracker() : private_nh_("~"), tf_listener_(tf_buffer_), start_time_(ros::Time::now()) { private_nh_.param("HZ", HZ, 10); private_nh_.param("USE_DYNAMIXEL", USE_DYNAMIXEL, true); private_nh_.param("MIN_CLUSTER", MIN_CLUSTER, 100); private_nh_.param("MOTION_NOISE", MOTION_NOISE, 0.03); private_nh_.param("MEASUREMENT_NOISE", MEASUREMENT_NOISE, 0.1); private_nh_.param("LIFETIME_THRESHOLD", LIFETIME_THRESHOLD, 0.1); read_robots_parameter(); dynamixel_pubs_.resize(robots_.size()); position_subs_.resize(robots_.size()); angle_subs_.resize(robots_.size()); color_enable_clients_.resize(robots_.size()); color_enables_.resize(robots_.size()); for (size_t i = 0; i < robots_.size(); i++) { ROS_INFO_STREAM("roomba" << robots_[i].first << "'s color is " << robots_[i].second); std::string roomba = "roomba" + std::to_string(robots_[i].first); dynamixel_pubs_[i] = nh_.advertise<dynamixel_angle_msgs::DynamixelAngle>(roomba + "/dynamixel/angle", 1); position_subs_[i] = nh_.subscribe(roomba + "/target/position", 1, &TargetTracker::position_callback, this); angle_subs_[i] = nh_.subscribe(roomba + "/target/angle", 1, &TargetTracker::angle_callback, this); color_enable_clients_[i] = nh_.serviceClient<color_detector_srvs::ColorEnable>(roomba + "/color_enable"); for (const auto &p : robots_) { color_enables_[i][p.second] = false; } } target_pub_ = nh_.advertise<kalman_filter::TargetArray>("target", 1); ellipse_pub_ = private_nh_.advertise<visualization_msgs::MarkerArray>("ellipses", 1); set_color_map(); } void TargetTracker::read_robots_parameter() { XmlRpc::XmlRpcValue index_list, color_list; if (!private_nh_.getParam("ROOMBA_INDEXES", index_list)) { ROS_ERROR_STREAM("cannnot read indexes parameter"); return; } ROS_ASSERT(index_list.getType() == XmlRpc::XmlRpcValue::TypeArray); if (!private_nh_.getParam("ROOMBA_COLORS", color_list)) { ROS_ERROR_STREAM("cannnot read colors parameter"); return; } ROS_ASSERT(color_list.getType() == XmlRpc::XmlRpcValue::TypeArray); ROS_ASSERT(index_list.size() == color_list.size()); for (size_t i = 0; i < index_list.size(); i++) { ROS_ASSERT(index_list[i].getType() == XmlRpc::XmlRpcValue::TypeInt); ROS_ASSERT(color_list[i].getType() == XmlRpc::XmlRpcValue::TypeString); robots_.emplace_back(index_list[i], color_list[i]); } } void TargetTracker::update_kalman_filter(size_t idx, const color_detector_msgs::TargetPositionConstPtr &pos) { geometry_msgs::TransformStamped transform_stamped; std::string roomba = "roomba" + std::to_string(robots_[idx].first); try { transform_stamped = tf_buffer_.lookupTransform("map", roomba + "/camera_link", ros::Time(0)); } catch (tf2::TransformException &ex) { ROS_WARN_STREAM(ex.what()); ros::Duration(1.0).sleep(); return; } geometry_msgs::PoseStamped target_pose; calc_target_pose_on_world(roomba, pos, transform_stamped, &target_pose); std::string color = robots_[idx].second; if (kalman_filters_.count(color) == 0) { kalman_filters_[color].set_motion_noise(MOTION_NOISE); kalman_filters_[color].set_measurement_noise(MEASUREMENT_NOISE); } kalman_filters_[color].update(target_pose.pose.position.x, target_pose.pose.position.y, (ros::Time::now() - start_time_).toSec()); } void TargetTracker::calc_target_pose_on_world(std::string roomba, const color_detector_msgs::TargetPositionConstPtr &target, const geometry_msgs::TransformStamped &transform, geometry_msgs::PoseStamped *output_pose) { geometry_msgs::PoseStamped target_pose; target_pose.header = target->header; target_pose.header.frame_id = roomba + "/camera_link"; target_pose.pose.position.x = target->z; target_pose.pose.position.y = -target->x; target_pose.pose.position.z = target->y; target_pose.pose.orientation.w = 1; target_pose.pose.orientation.x = 0; target_pose.pose.orientation.y = 0; target_pose.pose.orientation.z = 0; tf2::doTransform(target_pose, *output_pose, transform); return; } void TargetTracker::angle_callback(const color_detector_msgs::TargetAngleListConstPtr &angles) { if (angles->data.empty()) { ROS_WARN("angle list is empty."); return; } color_detector_msgs::TargetAngle angle; double min_likelihood = 1e5; for (const auto &agl : angles->data) { if (agl.cluster_num < MIN_CLUSTER) continue; kalman_filters_[agl.color].estimate_update((ros::Time::now() - start_time_).toSec()); double likelihood = kalman_filters_[agl.color].get_likelihood(); if (likelihood < min_likelihood) { angle = agl; min_likelihood = likelihood; } } if (min_likelihood == 1e5) { ROS_DEBUG_STREAM("cannnot find roomba"); return; } if (!isfinite(angle.radian)) { ROS_WARN_STREAM(angle.color << "'s radian is " << angle.radian); return; } if (!USE_DYNAMIXEL) return; dynamixel_angle_msgs::DynamixelAngle msg; msg.theta = angle.radian; int roomba_idx = -1; for (size_t i = 0; i < robots_.size(); i++) { if (robots_[i].first == angles->my_number) { roomba_idx = i; break; } } ROS_ASSERT(roomba_idx != -1); dynamixel_pubs_[roomba_idx].publish(msg); ROS_DEBUG_STREAM("camera direction to " << angle.color); call_color_enable_service(&color_enable_clients_[roomba_idx], &color_enables_[roomba_idx], angle.color); } void TargetTracker::call_color_enable_service(ros::ServiceClient *client, std::map<std::string, bool> *color_enable, std::string color) { for (auto itr = color_enable->begin(); itr != color_enable->end(); itr++) { if (itr->first == color && itr->second == false) { color_detector_srvs::ColorEnable srv; srv.request.color = itr->first; srv.request.color = true; if (client->call(srv)) { itr->second = true; } else { ROS_ERROR_STREAM("Failed to call service color_enable. Couldn't activate " << itr->first << "."); } } if (itr->first != color && itr->second == true) { color_detector_srvs::ColorEnable srv; srv.request.color = itr->first; srv.request.color = false; if (client->call(srv)) { itr->second = false; } else { ROS_ERROR_STREAM("Failed to call service color_enable. Couldn't deactivate " << itr->first << "."); } } } } void TargetTracker::position_callback(const color_detector_msgs::TargetPositionConstPtr &position) { for (size_t i = 0; i < robots_.size(); i++) { if (robots_[i].second == position->color) { update_kalman_filter(i, position); } } } void TargetTracker::set_color_map() { color_map_["green"].r = 0.0f; color_map_["green"].g = 0.5f; color_map_["green"].b = 0.0f; color_map_["green"].a = 0.3f; color_map_["yellow"].r = 1.0f; color_map_["yellow"].g = 1.0f; color_map_["yellow"].b = 0.0f; color_map_["yellow"].a = 0.3f; color_map_["blue"].r = 0.0f; color_map_["blue"].g = 0.0f; color_map_["blue"].b = 1.0f; color_map_["blue"].a = 0.3f; color_map_["orange"].r = 1.0f; color_map_["orange"].g = 0.6f; color_map_["orange"].b = 0.0f; color_map_["orange"].a = 0.3f; color_map_["purple"].r = 0.5f; color_map_["purple"].g = 0.0f; color_map_["purple"].b = 0.5f; color_map_["purple"].a = 0.3f; color_map_["red"].r = 1.0f; color_map_["red"].g = 0.0f; color_map_["red"].b = 0.0f; color_map_["red"].a = 0.3f; } void TargetTracker::visualize_ellipse() { visualization_msgs::MarkerArray markers; for (size_t i = 0; i < robots_.size(); i++) { if (kalman_filters_.count(robots_[i].second) == 0) continue; std::string roomba = "roomba" + std::to_string(robots_[i].first); visualization_msgs::Marker marker; marker.header.frame_id = "map"; marker.header.stamp = ros::Time::now(); marker.ns = roomba + "/kf"; marker.id = i; marker.type = visualization_msgs::Marker::CYLINDER; marker.lifetime = ros::Duration(); if (kalman_filters_[robots_[i].second].get_likelihood() < LIFETIME_THRESHOLD) { marker.action = visualization_msgs::Marker::DELETE; markers.markers.push_back(marker); continue; } marker.action = visualization_msgs::Marker::ADD; std::vector<double> ellipse = kalman_filters_[robots_[i].second].get_ellipse(); marker.scale.x = ellipse[0]; marker.scale.y = ellipse[1]; marker.scale.z = 0.2; marker.pose.position.x = kalman_filters_[robots_[i].second].get_x(); marker.pose.position.y = kalman_filters_[robots_[i].second].get_y(); marker.pose.position.z = 0.2; double theta = std::acos(ellipse[1] / ellipse[0]); marker.pose.orientation.w = std::cos(theta / 2); marker.pose.orientation.x = std::cos(ellipse[2]) * std::sin(theta / 2); marker.pose.orientation.y = std::sin(ellipse[2]) * std::sin(theta / 2); marker.pose.orientation.z = 0.0; marker.color = color_map_[robots_[i].second]; markers.markers.push_back(marker); } ellipse_pub_.publish(markers); } void TargetTracker::timer_callback(const ros::TimerEvent &event) { kalman_filter::TargetArray msg; msg.header.frame_id = "map"; msg.header.stamp = ros::Time::now(); for (size_t i = 0; i < robots_.size(); i++) { if (kalman_filters_.count(robots_[i].second) == 0) continue; ros::Time now = ros::Time::now(); auto &kf = kalman_filters_[robots_[i].second]; kf.estimate_update((now - start_time_).toSec()); kalman_filter::Target target; target.header.frame_id = "map"; target.header.stamp = now; target.id = i; target.position.x = kf.get_x(); target.position.y = kf.get_y(); target.twist.linear.x = kf.get_vx(); target.twist.linear.y = kf.get_vy(); target.covariance = kf.get_p(); msg.targets.push_back(target); } target_pub_.publish(msg); visualize_ellipse(); } void TargetTracker::process() { timer_ = nh_.createTimer(ros::Duration(1.0 / HZ), &TargetTracker::timer_callback, this); ros::spin(); }
41.154717
116
0.627636
[ "vector", "transform" ]
b430ad6a93bae946269b1fe00804c65eb1414fff
3,511
cpp
C++
client/OAIEzsigndocument_createObject_v2_Response_mPayload.cpp
ezmaxinc/eZmax-SDK-cpp-qt5-client
70cc5ea2bccba1a7c192f88b15bee8225dbb3d01
[ "MIT" ]
null
null
null
client/OAIEzsigndocument_createObject_v2_Response_mPayload.cpp
ezmaxinc/eZmax-SDK-cpp-qt5-client
70cc5ea2bccba1a7c192f88b15bee8225dbb3d01
[ "MIT" ]
null
null
null
client/OAIEzsigndocument_createObject_v2_Response_mPayload.cpp
ezmaxinc/eZmax-SDK-cpp-qt5-client
70cc5ea2bccba1a7c192f88b15bee8225dbb3d01
[ "MIT" ]
null
null
null
/** * eZmax API Definition (Full) * This API expose all the functionnalities for the eZmax and eZsign applications. * * The version of the OpenAPI document: 1.1.7 * Contact: support-api@ezmax.ca * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ #include "OAIEzsigndocument_createObject_v2_Response_mPayload.h" #include <QDebug> #include <QJsonArray> #include <QJsonDocument> #include <QObject> #include "OAIHelpers.h" namespace OpenAPI { OAIEzsigndocument_createObject_v2_Response_mPayload::OAIEzsigndocument_createObject_v2_Response_mPayload(QString json) { this->initializeModel(); this->fromJson(json); } OAIEzsigndocument_createObject_v2_Response_mPayload::OAIEzsigndocument_createObject_v2_Response_mPayload() { this->initializeModel(); } OAIEzsigndocument_createObject_v2_Response_mPayload::~OAIEzsigndocument_createObject_v2_Response_mPayload() {} void OAIEzsigndocument_createObject_v2_Response_mPayload::initializeModel() { m_a_pki_ezsigndocument_id_isSet = false; m_a_pki_ezsigndocument_id_isValid = false; } void OAIEzsigndocument_createObject_v2_Response_mPayload::fromJson(QString jsonString) { QByteArray array(jsonString.toStdString().c_str()); QJsonDocument doc = QJsonDocument::fromJson(array); QJsonObject jsonObject = doc.object(); this->fromJsonObject(jsonObject); } void OAIEzsigndocument_createObject_v2_Response_mPayload::fromJsonObject(QJsonObject json) { m_a_pki_ezsigndocument_id_isValid = ::OpenAPI::fromJsonValue(a_pki_ezsigndocument_id, json[QString("a_pkiEzsigndocumentID")]); m_a_pki_ezsigndocument_id_isSet = !json[QString("a_pkiEzsigndocumentID")].isNull() && m_a_pki_ezsigndocument_id_isValid; } QString OAIEzsigndocument_createObject_v2_Response_mPayload::asJson() const { QJsonObject obj = this->asJsonObject(); QJsonDocument doc(obj); QByteArray bytes = doc.toJson(); return QString(bytes); } QJsonObject OAIEzsigndocument_createObject_v2_Response_mPayload::asJsonObject() const { QJsonObject obj; if (a_pki_ezsigndocument_id.size() > 0) { obj.insert(QString("a_pkiEzsigndocumentID"), ::OpenAPI::toJsonValue(a_pki_ezsigndocument_id)); } return obj; } QList<qint32> OAIEzsigndocument_createObject_v2_Response_mPayload::getAPkiEzsigndocumentId() const { return a_pki_ezsigndocument_id; } void OAIEzsigndocument_createObject_v2_Response_mPayload::setAPkiEzsigndocumentId(const QList<qint32> &a_pki_ezsigndocument_id) { this->a_pki_ezsigndocument_id = a_pki_ezsigndocument_id; this->m_a_pki_ezsigndocument_id_isSet = true; } bool OAIEzsigndocument_createObject_v2_Response_mPayload::is_a_pki_ezsigndocument_id_Set() const{ return m_a_pki_ezsigndocument_id_isSet; } bool OAIEzsigndocument_createObject_v2_Response_mPayload::is_a_pki_ezsigndocument_id_Valid() const{ return m_a_pki_ezsigndocument_id_isValid; } bool OAIEzsigndocument_createObject_v2_Response_mPayload::isSet() const { bool isObjectUpdated = false; do { if (a_pki_ezsigndocument_id.size() > 0) { isObjectUpdated = true; break; } } while (false); return isObjectUpdated; } bool OAIEzsigndocument_createObject_v2_Response_mPayload::isValid() const { // only required properties are required for the object to be considered valid return m_a_pki_ezsigndocument_id_isValid && true; } } // namespace OpenAPI
34.421569
130
0.789803
[ "object" ]
b434c25a61b9be1b43d9af3c499b840a579d667f
2,959
cpp
C++
Upper_bound_lower_bound.cpp
atharva0300/CPP-Competitive-Programming
3769734b0b8c2008f47864a72e4581595ad9176a
[ "MIT" ]
null
null
null
Upper_bound_lower_bound.cpp
atharva0300/CPP-Competitive-Programming
3769734b0b8c2008f47864a72e4581595ad9176a
[ "MIT" ]
null
null
null
Upper_bound_lower_bound.cpp
atharva0300/CPP-Competitive-Programming
3769734b0b8c2008f47864a72e4581595ad9176a
[ "MIT" ]
null
null
null
// Upper bound and lower bound #include<bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int a[n]; /* input : 6 4 5 5 25 7 8 */ /* lower bound : only works for sorted array s lower vond finds the element , if the element is present int the array then it finds that element, else it finds the element that is greater than that element. example - lower bound of 7 : 7 lower bound of 6 : 7 example : sorted array : 4 5 5 7 8 25 lower bound of 5 : 5 ( 5 is present ) lower bound of 7 : 7 ( 7 is present ) lower bound of 6 : 7 ( 6 does not exist,the greater element. ie - 7) lower bound of 26 : gives the next pointer of the last element ( because a number greater than 26 does not exist) upper bound of 5 : 7 upper bound of 7 : 8 upper bound of 6 : 7 ( even if the number 6 does not exist in the array ) upper bound of 8 : 25 */ for(int i=0;i<n;i++) { cin>>a[i]; } sort(a , a+n); cout<<"\nPrinting the array : \n"; for(int i=0;i<n;i++) { cout<<a[i]<<"\n"; } // creating a pointer // lower_bound(starting address , end address, the element of which you want ot find the lower bound of ) int *ptr = lower_bound(a ,a+n ,5); cout<<"\nLower bound of 5 : "; cout<<*ptr<<"\n"; int *ptr2 = lower_bound(a,a+n,26); if(ptr2==(a+n)) { cout<<"\nNot found"; } // upper bound // upper_bound(starting address, end address , the element of which you want to find the upper bound of ) int* ptr3 = upper_bound(a,a+n,5); cout<<"\nUpepr bound of 5 : "<<*ptr<<"\n"; int *ptr4 = upper_bound(a,a+n,26); if(ptr4==(a+n)) { cout<<"\nNot found"; } cout<<"\nupper bound of 26 : "<<*ptr4<<"\n"; int *ptr5 = upper_bound(a+4,a+n,8); if(ptr5==(a+n)) { cout<<"\nNot found"; } cout<<"\nupper bound of 8 : "<<*ptr5<<"\n"; // Similarly for vector vector<int>v(n); for(int i=0;i<n;i++) { cin>>v[i]; } sort(v.begin() , v.end()); auto it = upper_bound(v.begin() ,v.end() , 5); if(it==v.end()) { cout<<"\nNot found"; } cout<<"\nit upper bound 5 : "<<*it<<"\n"; // Upper boudn and lower bound in maps and sets set<int>s; for(int i=0;i<n;i++) { int x; cin>>x; s.insert(x); } auto it2 = s.lower_bound(5); // don't use // auto it2 = lower_bound(s.begin() , s.end() , value); // this is because, it gives tou time limit error // because, the time complexity of the lower_bound // function is not n*log(n) but O(n). // so pputting a random value of say 10^5, icreases // the rutime, and gives TLE // instead use the below // auto it2 = s.lower_bound(value); // this is faster than the above. cout<<"\nset lower bound of 5 : "<<*it2<<"\n"; // Similarly for maps map<int ,int >m; for(int i=0;i<n;i++) { cin>>m[i].first>>m[i].second; } cout<<"\n"; system("pause"); return 0; }
24.056911
120
0.572829
[ "vector" ]
b43bee2a78947cd9587090fb544300ccaf0bc39e
6,506
cc
C++
installer/util/key_reader.cc
dgreid/platform2
9b8b30df70623c94f1c8aa634dba94195343f37b
[ "BSD-3-Clause" ]
4
2020-07-24T06:54:16.000Z
2021-06-16T17:13:53.000Z
installer/util/key_reader.cc
dgreid/platform2
9b8b30df70623c94f1c8aa634dba94195343f37b
[ "BSD-3-Clause" ]
1
2021-04-02T17:35:07.000Z
2021-04-02T17:35:07.000Z
installer/util/key_reader.cc
dgreid/platform2
9b8b30df70623c94f1c8aa634dba94195343f37b
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2020 The Chromium OS 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 "installer/util/key_reader.h" #include <ctype.h> #include <dirent.h> #include <fcntl.h> #include <sys/epoll.h> #include <unistd.h> #include <utility> #include <vector> #include <base/files/file_enumerator.h> #include <base/files/scoped_file.h> #include <base/logging.h> #include <base/strings/strcat.h> namespace key_reader { namespace { constexpr char kDevInputEvent[] = "/dev/input"; constexpr char kEventDevName[] = "*event*"; constexpr char kXkbPathName[] = "/usr/share/X11/xkb"; // Offset between xkb layout codes and ev key codes. constexpr int kXkbOffset = 8; // Determines if the given |bit| is set in the |bitmask| array. bool TestBit(const int bit, const uint8_t* bitmask) { return (bitmask[bit / 8] >> (bit % 8)) & 1; } bool IsUsbDevice(const int fd) { struct input_id id; if (ioctl(fd, EVIOCGID, &id) == -1) { PLOG(ERROR) << "Failed to ioctl to determine device bus"; return false; } return id.bustype == BUS_USB; } bool IsKeyboardDevice(const int fd) { uint8_t evtype_bitmask[EV_MAX / 8 + 1]; if (ioctl(fd, EVIOCGBIT(0, sizeof(evtype_bitmask)), evtype_bitmask) == -1) { PLOG(ERROR) << "Failed to ioctl to determine supported event types"; return false; } // The device is a "keyboard" if it supports EV_KEY events. Though, it is not // necessarily a real keyboard; EV_KEY events could also be e.g. volume // up/down buttons on a device. return TestBit(EV_KEY, evtype_bitmask); } } // namespace KeyReader::~KeyReader() { // Release xkb references. xkb_state_unref(state_); xkb_keymap_unref(keymap_); xkb_context_unref(ctx_); } bool KeyReader::KeyEventStart() { base::FileEnumerator file_enumerator(base::FilePath(kDevInputEvent), true, base::FileEnumerator::FILES, FILE_PATH_LITERAL(kEventDevName)); for (base::FilePath dir_path = file_enumerator.Next(); !dir_path.empty(); dir_path = file_enumerator.Next()) { base::ScopedFD fd(open(dir_path.value().c_str(), O_RDONLY | O_CLOEXEC)); if (!fd.is_valid()) { PLOG(INFO) << "Failed to open event device: " << fd.get(); continue; } if ((include_usb_ || !IsUsbDevice(fd.get())) && IsKeyboardDevice(fd.get())) { fds_.push_back(std::move(fd)); } } // At least one valid keyboard. if (!fds_.empty()) { return GetInput(); } return false; } bool KeyReader::SetKeyboardContext() { // Set xkb layout and get keymap. ctx_ = xkb_context_new(XKB_CONTEXT_NO_DEFAULT_INCLUDES); if (!ctx_) { LOG(ERROR) << "Unable to get new xkb context."; return false; } if (!xkb_context_include_path_append(ctx_, kXkbPathName)) { LOG(ERROR) << "Cannot add path " << kXkbPathName << " to context."; return false; } names_ = {.layout = country_code_.c_str()}; keymap_ = xkb_keymap_new_from_names(ctx_, &names_, XKB_KEYMAP_COMPILE_NO_FLAGS); if (keymap_ == nullptr) { LOG(ERROR) << "No matching keyboard for " << country_code_ << ". Make sure the two letter country code is valid."; return false; } state_ = xkb_state_new(keymap_); if (!state_) { LOG(ERROR) << "Unable to get xkbstate for " << country_code_; return false; } return true; } bool KeyReader::GetInput() { int epfd = epoll_create1(EPOLL_CLOEXEC); if (epfd < 0) { PLOG(ERROR) << "Epoll_create failed"; return false; } for (int i = 0; i < fds_.size(); ++i) { struct epoll_event ep_event; ep_event.data.u32 = i; ep_event.events = EPOLLIN; if (epoll_ctl(epfd, EPOLL_CTL_ADD, fds_[i].get(), &ep_event) < 0) { PLOG(ERROR) << "Epoll_ctl failed"; return false; } } if (!SetKeyboardContext()) { return false; } while (true) { struct epoll_event ep_event; if (epoll_wait(epfd, &ep_event, 1, -1) <= 0) { PLOG(ERROR) << "epoll_wait failed"; return false; } struct input_event ev; int rd = read(fds_[ep_event.data.u32].get(), &ev, sizeof(ev)); if (rd != sizeof(ev)) { PLOG(ERROR) << "Could not read event"; return false; } if (ev.type != EV_KEY || ev.code > KEY_MAX) { continue; } // Take in ev event and add to user input as appropriate. // Returns false to exit. if (!GetChar(ev)) { return true; } } } bool KeyReader::GetChar(const struct input_event& ev) { xkb_keycode_t keycode = ev.code + kXkbOffset; xkb_keysym_t sym = xkb_state_key_get_one_sym(state_, keycode); if (ev.value == 0) { // Key up event. if (sym == XKB_KEY_Return && return_pressed_) { // Only end if RETURN key press was already recorded. if (user_input_.empty()) { printf("\n"); } else { user_input_.push_back('\0'); printf("%s\n", user_input_.c_str()); } return false; } // Put char representation in buffer. int size = xkb_state_key_get_utf8(state_, keycode, nullptr, 0) + 1; std::vector<char> buff(size); xkb_state_key_get_utf8(state_, keycode, buff.data(), size); if (sym == XKB_KEY_BackSpace && !user_input_.empty()) { user_input_.pop_back(); } else if (isprint(buff[0]) && user_input_.size() < key_reader::kMaxInputLength) { // Only printable ASCII characters stored in output. user_input_.push_back(buff[0]); } xkb_state_update_key(state_, keycode, XKB_KEY_UP); if (print_length_) { printf("%zu\n", user_input_.size()); // Flush input so it can be read before program exits. fflush(stdout); } } else if (ev.value == 1) { // Key down event. if (sym == XKB_KEY_Return) return_pressed_ = true; xkb_state_update_key(state_, keycode, XKB_KEY_DOWN); } else if (ev.value == 2) { // Long press or repeating key event. if (sym == XKB_KEY_BackSpace && !user_input_.empty() && ++backspace_counter_ >= key_reader::kBackspaceSensitivity) { // Remove characters until empty. user_input_.pop_back(); backspace_counter_ = 0; } if (print_length_) { printf("%zu\n", user_input_.size()); // Flush input so it can be read before program exits. fflush(stdout); } } return true; } std::string KeyReader::GetUserInputForTest() { return user_input_; } } // namespace key_reader
27.803419
79
0.637412
[ "vector" ]
b43c80bba0cb4c4f6584771a5613a936e3d1689a
71,464
cpp
C++
cpp/neuralnet/openclkernels.cpp
MarkTakken/KataGoToroidal
e4e0ef925f2a5a114a2a895cf6bd45e7ea4e9943
[ "MIT" ]
1
2021-08-31T14:52:01.000Z
2021-08-31T14:52:01.000Z
cpp/neuralnet/openclkernels.cpp
MarkTakken/KataGoToroidal
e4e0ef925f2a5a114a2a895cf6bd45e7ea4e9943
[ "MIT" ]
null
null
null
cpp/neuralnet/openclkernels.cpp
MarkTakken/KataGoToroidal
e4e0ef925f2a5a114a2a895cf6bd45e7ea4e9943
[ "MIT" ]
null
null
null
#ifdef USE_OPENCL_BACKEND #include "../neuralnet/openclkernels.h" #include "../game/space.h" using namespace std; string OpenCLKernels::fp16StorageDefine = " -DPRECISION_STORAGE=16"; string OpenCLKernels::fp16ComputeDefine = " -DPRECISION=16"; string OpenCLKernels::common = R"%%( #ifndef PRECISION #define PRECISION 32 #endif #ifndef PRECISION_STORAGE #define PRECISION_STORAGE 32 #endif #if PRECISION == 16 #pragma OPENCL EXTENSION cl_khr_fp16: enable typedef half real; #define ZERO 0.0h #define ONE 1.0h #define HUNDRED 100.0h #define FOURTEEN 14.0h #define TEN 10.0h #define EIGHT 8.0h #define FIVE 5.0h #define FOUR 4.0h #define TWO 2.0h #define HALF 0.5h #define TWOP5 2.5h #define SQRT8 2.82842712475h #define SQRT2 1.41421356237h #define SQRTHALF 0.70710678118h #define SQRTEIGHTH 0.35355339059h #define floatToReal(_r) (convert_half(_r)) #elif PRECISION == 32 typedef float real; #define ZERO 0.0f #define ONE 1.0f #define HUNDRED 100.0f #define FOURTEEN 14.0f #define TEN 10.0f #define EIGHT 8.0f #define FIVE 5.0f #define FOUR 4.0f #define TWO 2.0f #define HALF 0.5f #define TWOP5 2.5f #define SQRT8 2.82842712475f #define SQRT2 1.41421356237f #define SQRTHALF 0.70710678118f #define SQRTEIGHTH 0.35355339059f #define floatToReal(_r) (_r) #endif #if PRECISION_STORAGE == 16 typedef half realstore; #if PRECISION == 16 #define LOAD(__buf,__x) ((__buf)[(__x)]) #define STORE(__buf,__x,__y) ((__buf)[(__x)] = (__y)) #elif PRECISION == 32 #define LOAD(__buf,__x) vload_half((__x),(__buf)) #define STORE(__buf,__x,__y) vstore_half((__y),(__x),(__buf)) #endif #elif PRECISION_STORAGE == 32 typedef float realstore; #define LOAD(__buf,__x) ((__buf)[(__x)]) #define STORE(__buf,__x,__y) ((__buf)[(__x)] = (__y)) #endif )%%"; string OpenCLKernels::conv2dNCHWPlanar = OpenCLKernels::common + R"%%( //Spatial size of tile loaded into local memory, not counting filterRadius #ifndef TILE_XSIZE #define TILE_XSIZE 32 #endif #ifndef TILE_YSIZE #define TILE_YSIZE 4 #endif //Channel depth of tile loaded into local memory #ifndef TILE_CHANNELS #define TILE_CHANNELS 4 #endif //group id 0 indexes different tiles along x dimension //group id 1 indexes different tiles along y dimension //local id 0 indexes threads that parallelize xwise across the internal of a tile, must be a factor of TILE_XSIZE //local id 1 indexes threads that parallelize ywise across the internal of a tile, must be a factor of TILE_YSIZE //group id 2 indexes different output channels //local id 2 is ASSUMED to be always 0, with local size 2 ASSUMED to be 1, so that we don't need to index these local memory space on this dimension __kernel void conv2dNCHW( __global realstore* restrict input, //N, ic, H, W __global realstore* restrict filter, //oc, ic, fy, fx __global realstore* restrict output, //N, oc, H, W __local real* restrict inputTile, //ic, H, W size = TILE_CHANNELS * inputTileXSize * inputTileYSize __local real* restrict outputTile, //H, W size = TILE_XSIZE * TILE_YSIZE int nSize, int xSize, int ySize, int ocSize, int icSize, int filterXRadius, int filterYRadius ) { const int xBase = get_group_id(0) * TILE_XSIZE; const int yBase = get_group_id(1) * TILE_YSIZE; const int oc = get_global_id(2); const int lx = get_local_id(0); const int ly = get_local_id(1); const int lxSize = get_local_size(0); const int lySize = get_local_size(1); //The input tile is filterXRadius*2 or filterYRadius*2 larger than the tile size const int inputTileXSize = TILE_XSIZE + filterXRadius * 2; const int inputTileYSize = TILE_YSIZE + filterYRadius * 2; const int xySize = xSize * ySize; const int fxSize = (2 * filterXRadius + 1); const int fySize = (2 * filterYRadius + 1); #define INPUT(_n,_ic,_y,_x) LOAD(input,((_n) * icSize + (_ic)) * xySize + (_y) * xSize + (_x)) #define INPUTTILE(_ic,_ity,_itx) inputTile[((_ic) * inputTileYSize + (_ity)) * inputTileXSize + (_itx)] #define FILTER(_oc,_ic,_y,_x) LOAD(filter,(((_oc) * icSize + (_ic)) * fySize + (_y)) * fxSize + (_x)) #define WRITEOUTPUT(_n,_oc,_y,_x,_value) STORE(output,((_n) * ocSize + (_oc)) * xySize + (_y) * xSize + (_x),_value) #define OUTPUTTILE(_oty,_otx) outputTile[(_oty) * TILE_XSIZE + (_otx)] for(int n = 0; n < nSize; n++) { real acc = ZERO; //Initialize outputTile. No need to sync for this tile since each thread only ever reads its own spots for(int oty = ly; oty<TILE_YSIZE; oty += lySize) { for(int otx = lx; otx<TILE_XSIZE; otx += lxSize) { OUTPUTTILE(oty,otx) = ZERO; } } //Walk over chunks of TILE_CHANNELS many input channels at a time for(int icBase = 0; icBase<icSize; icBase += TILE_CHANNELS) { //Copy input tile using local threads in parallel for(int dic = 0; dic<TILE_CHANNELS && icBase+dic < icSize; dic += 1) { for(int ity = ly; ity<inputTileYSize; ity += lySize) { int iy = ity+yBase-filterYRadius; for(int itx = lx; itx<inputTileXSize; itx += lxSize) { int ix = itx+xBase-filterXRadius; real inputValue = ZERO; //Padding that I need to change? if(iy >= 0 && iy < ySize && ix >= 0 && ix < xSize) { inputValue = INPUT(n,icBase+dic,iy,ix); } INPUTTILE(dic,ity,itx) = inputValue; } } } //Synchronize! barrier(CLK_LOCAL_MEM_FENCE); //Accumulate this convolution block into output tile. //Iterate over the bits in this tile that the thread is responsible for for(int oty = ly; oty<TILE_YSIZE; oty += lySize) { for(int otx = lx; otx<TILE_XSIZE; otx += lxSize) { //And then perform the convolution to accumulate that bit real acc = ZERO; for(int dic = 0; dic<TILE_CHANNELS && icBase+dic < icSize; dic += 1) { for(int fy = 0; fy < fySize; fy++) { for(int fx = 0; fx < fxSize; fx++) { acc += INPUTTILE(dic,oty+fy,otx+fx) * FILTER(oc,icBase+dic,fy,fx); } } } OUTPUTTILE(oty,otx) += acc; } } } //close loop over input channel chunks //Now, write tile contents back into output for(int oty = ly; oty<TILE_YSIZE; oty += lySize) { int oy = yBase+oty; for(int otx = lx; otx<TILE_XSIZE; otx += lxSize) { int ox = xBase+otx; if(oy >= 0 && oy < ySize && ox >= 0 && ox < xSize) { real result = OUTPUTTILE(oty,otx); WRITEOUTPUT(n, oc, yBase+oty, xBase+otx, result); //Unnecessary extra addition? } } } } //Close loop over batch } )%%"; string OpenCLKernels::conv2dNCHWToroidal = OpenCLKernels::common + R"%%( //Spatial size of tile loaded into local memory, not counting filterRadius #ifndef TILE_XSIZE #define TILE_XSIZE 32 #endif #ifndef TILE_YSIZE #define TILE_YSIZE 4 #endif //Channel depth of tile loaded into local memory #ifndef TILE_CHANNELS #define TILE_CHANNELS 4 #endif //group id 0 indexes different tiles along x dimension //group id 1 indexes different tiles along y dimension //local id 0 indexes threads that parallelize xwise across the internal of a tile, must be a factor of TILE_XSIZE //local id 1 indexes threads that parallelize ywise across the internal of a tile, must be a factor of TILE_YSIZE //group id 2 indexes different output channels //local id 2 is ASSUMED to be always 0, with local size 2 ASSUMED to be 1, so that we don't need to index these local memory space on this dimension __kernel void conv2dNCHW( __global realstore* restrict input, //N, ic, H, W __global realstore* restrict filter, //oc, ic, fy, fx __global realstore* restrict output, //N, oc, H, W __local real* restrict inputTile, //ic, H, W size = TILE_CHANNELS * inputTileXSize * inputTileYSize __local real* restrict outputTile, //H, W size = TILE_XSIZE * TILE_YSIZE int nSize, int xSize, int ySize, int ocSize, int icSize, int filterXRadius, int filterYRadius ) { const int xBase = get_group_id(0) * TILE_XSIZE; const int yBase = get_group_id(1) * TILE_YSIZE; const int oc = get_global_id(2); const int lx = get_local_id(0); const int ly = get_local_id(1); const int lxSize = get_local_size(0); const int lySize = get_local_size(1); //The input tile is filterXRadius*2 or filterYRadius*2 larger than the tile size const int inputTileXSize = TILE_XSIZE + filterXRadius * 2; const int inputTileYSize = TILE_YSIZE + filterYRadius * 2; const int xySize = xSize * ySize; const int fxSize = (2 * filterXRadius + 1); const int fySize = (2 * filterYRadius + 1); #define INPUT(_n,_ic,_y,_x) LOAD(input,((_n) * icSize + (_ic)) * xySize + (_y) * xSize + (_x)) #define INPUTTILE(_ic,_ity,_itx) inputTile[((_ic) * inputTileYSize + (_ity)) * inputTileXSize + (_itx)] #define FILTER(_oc,_ic,_y,_x) LOAD(filter,(((_oc) * icSize + (_ic)) * fySize + (_y)) * fxSize + (_x)) #define WRITEOUTPUT(_n,_oc,_y,_x,_value) STORE(output,((_n) * ocSize + (_oc)) * xySize + (_y) * xSize + (_x),_value) #define OUTPUTTILE(_oty,_otx) outputTile[(_oty) * TILE_XSIZE + (_otx)] for(int n = 0; n < nSize; n++) { real acc = ZERO; //Initialize outputTile. No need to sync for this tile since each thread only ever reads its own spots for(int oty = ly; oty<TILE_YSIZE; oty += lySize) { for(int otx = lx; otx<TILE_XSIZE; otx += lxSize) { OUTPUTTILE(oty,otx) = ZERO; } } //Walk over chunks of TILE_CHANNELS many input channels at a time for(int icBase = 0; icBase<icSize; icBase += TILE_CHANNELS) { //Copy input tile using local threads in parallel for(int dic = 0; dic<TILE_CHANNELS && icBase+dic < icSize; dic += 1) { for(int ity = ly; ity<inputTileYSize; ity += lySize) { int iy = ity+yBase-filterYRadius; for(int itx = lx; itx<inputTileXSize; itx += lxSize) { int ix = itx+xBase-filterXRadius; real inputValue = ZERO; //Padding that I need to change? int wrap_y = iy; int wrap_x = ix; if (wrap_x <= -1) wrap_x += xSize; else if (wrap_x >= xSize) wrap_x -= xSize; if (wrap_y <= -1) wrap_y += ySize; else if (wrap_y >= ySize) wrap_y -= ySize; inputValue = INPUT(n,icBase+dic,wrap_y,wrap_x); INPUTTILE(dic,ity,itx) = inputValue; } } } //Synchronize! barrier(CLK_LOCAL_MEM_FENCE); //Accumulate this convolution block into output tile. //Iterate over the bits in this tile that the thread is responsible for for(int oty = ly; oty<TILE_YSIZE; oty += lySize) { for(int otx = lx; otx<TILE_XSIZE; otx += lxSize) { //And then perform the convolution to accumulate that bit real acc = ZERO; for(int dic = 0; dic<TILE_CHANNELS && icBase+dic < icSize; dic += 1) { for(int fy = 0; fy < fySize; fy++) { for(int fx = 0; fx < fxSize; fx++) { acc += INPUTTILE(dic,oty+fy,otx+fx) * FILTER(oc,icBase+dic,fy,fx); } } } OUTPUTTILE(oty,otx) += acc; } } } //close loop over input channel chunks //Now, write tile contents back into output for(int oty = ly; oty<TILE_YSIZE; oty += lySize) { int oy = yBase+oty; for(int otx = lx; otx<TILE_XSIZE; otx += lxSize) { int ox = xBase+otx; if(oy >= 0 && oy < ySize && ox >= 0 && ox < xSize) { real result = OUTPUTTILE(oty,otx); WRITEOUTPUT(n, oc, yBase+oty, xBase+otx, result); //Unnecessary extra addition? } //int wrap_y = oy, wrap_x = ox; //if (wrap_x <= -1) wrap_x += xSize; //else if (wrap_x >= xSize) wrap_x -= xSize; //if (wrap_y <= -1) wrap_y += ySize; //else if (wrap_y >= ySize) wrap_y -= ySize; //real result = OUTPUTTILE(oty,otx); //WRITEOUTPUT(n, oc, wrap_y, wrap_x, result); } } } //Close loop over batch } )%%"; string OpenCLKernels::conv2dNCHWKlein = OpenCLKernels::common + R"%%( //Spatial size of tile loaded into local memory, not counting filterRadius #ifndef TILE_XSIZE #define TILE_XSIZE 32 #endif #ifndef TILE_YSIZE #define TILE_YSIZE 4 #endif //Channel depth of tile loaded into local memory #ifndef TILE_CHANNELS #define TILE_CHANNELS 4 #endif //group id 0 indexes different tiles along x dimension //group id 1 indexes different tiles along y dimension //local id 0 indexes threads that parallelize xwise across the internal of a tile, must be a factor of TILE_XSIZE //local id 1 indexes threads that parallelize ywise across the internal of a tile, must be a factor of TILE_YSIZE //group id 2 indexes different output channels //local id 2 is ASSUMED to be always 0, with local size 2 ASSUMED to be 1, so that we don't need to index these local memory space on this dimension __kernel void conv2dNCHW( __global realstore* restrict input, //N, ic, H, W __global realstore* restrict filter, //oc, ic, fy, fx __global realstore* restrict output, //N, oc, H, W __local real* restrict inputTile, //ic, H, W size = TILE_CHANNELS * inputTileXSize * inputTileYSize __local real* restrict outputTile, //H, W size = TILE_XSIZE * TILE_YSIZE int nSize, int xSize, int ySize, int ocSize, int icSize, int filterXRadius, int filterYRadius ) { const int xBase = get_group_id(0) * TILE_XSIZE; const int yBase = get_group_id(1) * TILE_YSIZE; const int oc = get_global_id(2); const int lx = get_local_id(0); const int ly = get_local_id(1); const int lxSize = get_local_size(0); const int lySize = get_local_size(1); //The input tile is filterXRadius*2 or filterYRadius*2 larger than the tile size const int inputTileXSize = TILE_XSIZE + filterXRadius * 2; const int inputTileYSize = TILE_YSIZE + filterYRadius * 2; const int xySize = xSize * ySize; const int fxSize = (2 * filterXRadius + 1); const int fySize = (2 * filterYRadius + 1); #define INPUT(_n,_ic,_y,_x) LOAD(input,((_n) * icSize + (_ic)) * xySize + (_y) * xSize + (_x)) #define INPUTTILE(_ic,_ity,_itx) inputTile[((_ic) * inputTileYSize + (_ity)) * inputTileXSize + (_itx)] #define FILTER(_oc,_ic,_y,_x) LOAD(filter,(((_oc) * icSize + (_ic)) * fySize + (_y)) * fxSize + (_x)) #define WRITEOUTPUT(_n,_oc,_y,_x,_value) STORE(output,((_n) * ocSize + (_oc)) * xySize + (_y) * xSize + (_x),_value) #define OUTPUTTILE(_oty,_otx) outputTile[(_oty) * TILE_XSIZE + (_otx)] for(int n = 0; n < nSize; n++) { real acc = ZERO; //Initialize outputTile. No need to sync for this tile since each thread only ever reads its own spots for(int oty = ly; oty<TILE_YSIZE; oty += lySize) { for(int otx = lx; otx<TILE_XSIZE; otx += lxSize) { OUTPUTTILE(oty,otx) = ZERO; } } //Walk over chunks of TILE_CHANNELS many input channels at a time for(int icBase = 0; icBase<icSize; icBase += TILE_CHANNELS) { //Copy input tile using local threads in parallel for(int dic = 0; dic<TILE_CHANNELS && icBase+dic < icSize; dic += 1) { for(int ity = ly; ity<inputTileYSize; ity += lySize) { int iy = ity+yBase-filterYRadius; for(int itx = lx; itx<inputTileXSize; itx += lxSize) { int ix = itx+xBase-filterXRadius; real inputValue = ZERO; //Padding that I need to change? int wrap_y = iy; int wrap_x = ix; if (wrap_y <= -1) wrap_y += ySize; else if (wrap_y >= ySize) wrap_y -= ySize; if (wrap_x <= -1) {wrap_x += xSize; wrap_y = ySize-1-wrap_y;} else if (wrap_x >= xSize) {wrap_x -= xSize; wrap_y = ySize-1-wrap_y;} inputValue = INPUT(n,icBase+dic,wrap_y,wrap_x); INPUTTILE(dic,ity,itx) = inputValue; } } } //Synchronize! barrier(CLK_LOCAL_MEM_FENCE); //Accumulate this convolution block into output tile. //Iterate over the bits in this tile that the thread is responsible for for(int oty = ly; oty<TILE_YSIZE; oty += lySize) { for(int otx = lx; otx<TILE_XSIZE; otx += lxSize) { //And then perform the convolution to accumulate that bit real acc = ZERO; for(int dic = 0; dic<TILE_CHANNELS && icBase+dic < icSize; dic += 1) { for(int fy = 0; fy < fySize; fy++) { for(int fx = 0; fx < fxSize; fx++) { acc += INPUTTILE(dic,oty+fy,otx+fx) * FILTER(oc,icBase+dic,fy,fx); } } } OUTPUTTILE(oty,otx) += acc; } } } //close loop over input channel chunks //Now, write tile contents back into output for(int oty = ly; oty<TILE_YSIZE; oty += lySize) { int oy = yBase+oty; for(int otx = lx; otx<TILE_XSIZE; otx += lxSize) { int ox = xBase+otx; if(oy >= 0 && oy < ySize && ox >= 0 && ox < xSize) { real result = OUTPUTTILE(oty,otx); WRITEOUTPUT(n, oc, yBase+oty, xBase+otx, result); //Unnecessary extra addition? } } } } //Close loop over batch } )%%"; string OpenCLKernels::winogradTransformNCHWPlanar = OpenCLKernels::common + R"%%( //Expected defines--------------------------------- //Dimension of input tile //INTILE_XSIZE 4 for F(2x2,3x3) //INTILE_YSIZE 4 for F(2x2,3x3) //Dimension of conv //CONV_XSIZE 3 for F(2x2,3x3) //CONV_YSIZE 3 for F(2x2,3x3) //Output tile size //OUTTILE_XSIZE 2 for F(2x2,3x3) //OUTTILE_YSIZE 2 for F(2x2,3x3) //Location of the upper left corner of the zeroth tile //INTILE_XOFFSET (-1) for F(2x2,3x3) //INTILE_YOFFSET (-1) for F(2x2,3x3) __kernel void transform( __global realstore* restrict input, //N, ic, H, W __global realstore* restrict transformed, //(INTILE_YSIZE, INTILE_XSIZE), (ic), (batch, tileY, tileX) where the last two dimenions are padded int nSize, int xSize, int ySize, int numTilesX, int numTilesY, int icSize, int icSizePadded, //Padding I need to change? int ntxtySizePadded ) { int id0 = get_global_id(0); const int ntxty = id0; const int tileX = id0 % numTilesX; id0 = id0 / numTilesX; const int tileY = id0 % numTilesY; id0 = id0 / numTilesY; const int n = id0; const int ic = get_global_id(1); const int nic = n * icSize + ic; const int xySize = xSize * ySize; #define INPUT(_nic,_xy) LOAD(input,((_nic) * xySize) + (_xy)) #define WTILE(_y,_x) wTile[(_y)*INTILE_XSIZE + (_x)] __private real wTile[INTILE_XSIZE * INTILE_YSIZE]; //Copy input into private tile for(int subY = 0; subY < INTILE_YSIZE; subY++) { int y = tileY * OUTTILE_YSIZE + subY + INTILE_YOFFSET; for(int subX = 0; subX < INTILE_XSIZE; subX++) { int x = tileX * OUTTILE_XSIZE + subX + INTILE_XOFFSET; real value = ZERO; if(y >= 0 && y < ySize && x >= 0 && x < xSize && n < nSize && ic < icSize) { int xy = y * xSize + x; //Change this?? value = INPUT(nic,xy); } WTILE(subY,subX) = value; } } #if CONV_XSIZE == 3 && OUTTILE_XSIZE == 2 for(int subY = 0; subY < INTILE_YSIZE; subY++) { real z0 = WTILE(subY,0); real z1 = WTILE(subY,1); real z2 = WTILE(subY,2); real z3 = WTILE(subY,3); WTILE(subY,0) = z0 - z2; WTILE(subY,1) = z1 + z2; WTILE(subY,2) = z2 - z1; WTILE(subY,3) = z1 - z3; } #elif CONV_XSIZE == 3 && OUTTILE_XSIZE == 4 for(int subY = 0; subY < INTILE_YSIZE; subY++) { real z0 = WTILE(subY,0); real z1 = WTILE(subY,1); real z2 = WTILE(subY,2); real z3 = WTILE(subY,3); real z4 = WTILE(subY,4); real z5 = WTILE(subY,5); // Low error winograd // WTILE(subY,0) = z0 - TWOP5*z2 + z4; // WTILE(subY,1) = - SQRT2*z1 - TWO*z2 + SQRTHALF*z3 + z4; // WTILE(subY,2) = SQRT2*z1 - TWO*z2 - SQRTHALF*z3 + z4; // WTILE(subY,3) = - SQRTHALF*z1 - HALF*z2 + SQRT2*z3 + z4; // WTILE(subY,4) = SQRTHALF*z1 - HALF*z2 - SQRT2*z3 + z4; // WTILE(subY,5) = z1 - TWOP5*z3 + z5; WTILE(subY,0) = FOUR*z0 - FIVE*z2 + z4; WTILE(subY,1) = - FOUR*z1 - FOUR*z2 + z3 + z4; WTILE(subY,2) = FOUR*z1 - FOUR*z2 - z3 + z4; WTILE(subY,3) = - TWO*z1 - z2 + TWO*z3 + z4; WTILE(subY,4) = TWO*z1 - z2 - TWO*z3 + z4; WTILE(subY,5) = FOUR*z1 - FIVE*z3 + z5; } #elif CONV_XSIZE == 5 && OUTTILE_XSIZE == 2 for(int subY = 0; subY < INTILE_YSIZE; subY++) { real z0 = WTILE(subY,0); real z1 = WTILE(subY,1); real z2 = WTILE(subY,2); real z3 = WTILE(subY,3); real z4 = WTILE(subY,4); real z5 = WTILE(subY,5); WTILE(subY,0) = FOUR*z0 - FIVE*z2 + z4; WTILE(subY,1) = - FOUR*z1 - FOUR*z2 + z3 + z4; WTILE(subY,2) = FOUR*z1 - FOUR*z2 - z3 + z4; WTILE(subY,3) = - TWO*z1 - z2 + TWO*z3 + z4; WTILE(subY,4) = TWO*z1 - z2 - TWO*z3 + z4; WTILE(subY,5) = FOUR*z1 - FIVE*z3 + z5; } #else #error "No X winograd implemented for this conv and tile size" #endif #if CONV_YSIZE == 3 && OUTTILE_YSIZE == 2 for(int subX = 0; subX < INTILE_XSIZE; subX++) { real z0 = WTILE(0,subX); real z1 = WTILE(1,subX); real z2 = WTILE(2,subX); real z3 = WTILE(3,subX); WTILE(0,subX) = z0 - z2; WTILE(1,subX) = z1 + z2; WTILE(2,subX) = z2 - z1; WTILE(3,subX) = z1 - z3; } #elif CONV_YSIZE == 3 && OUTTILE_YSIZE == 4 for(int subX = 0; subX < INTILE_XSIZE; subX++) { real z0 = WTILE(0,subX); real z1 = WTILE(1,subX); real z2 = WTILE(2,subX); real z3 = WTILE(3,subX); real z4 = WTILE(4,subX); real z5 = WTILE(5,subX); // Low error winograd // WTILE(0,subX) = z0 - TWOP5*z2 + z4; // WTILE(1,subX) = - SQRT2*z1 - TWO*z2 + SQRTHALF*z3 + z4; // WTILE(2,subX) = SQRT2*z1 - TWO*z2 - SQRTHALF*z3 + z4; // WTILE(3,subX) = - SQRTHALF*z1 - HALF*z2 + SQRT2*z3 + z4; // WTILE(4,subX) = SQRTHALF*z1 - HALF*z2 - SQRT2*z3 + z4; // WTILE(5,subX) = z1 - TWOP5*z3 + z5; WTILE(0,subX) = FOUR*z0 - FIVE*z2 + z4; WTILE(1,subX) = - FOUR*z1 - FOUR*z2 + z3 + z4; WTILE(2,subX) = FOUR*z1 - FOUR*z2 - z3 + z4; WTILE(3,subX) = - TWO*z1 - z2 + TWO*z3 + z4; WTILE(4,subX) = TWO*z1 - z2 - TWO*z3 + z4; WTILE(5,subX) = FOUR*z1 - FIVE*z3 + z5; } #elif CONV_YSIZE == 5 && OUTTILE_YSIZE == 2 for(int subX = 0; subX < INTILE_XSIZE; subX++) { real z0 = WTILE(0,subX); real z1 = WTILE(1,subX); real z2 = WTILE(2,subX); real z3 = WTILE(3,subX); real z4 = WTILE(4,subX); real z5 = WTILE(5,subX); WTILE(0,subX) = FOUR*z0 - FIVE*z2 + z4; WTILE(1,subX) = - FOUR*z1 - FOUR*z2 + z3 + z4; WTILE(2,subX) = FOUR*z1 - FOUR*z2 - z3 + z4; WTILE(3,subX) = - TWO*z1 - z2 + TWO*z3 + z4; WTILE(4,subX) = TWO*z1 - z2 - TWO*z3 + z4; WTILE(5,subX) = FOUR*z1 - FIVE*z3 + z5; } #else #error "No Y winograd implemented for this conv and tile size" #endif #define WRITETRANS(_suby,_subx,_ic,_ntile,_value) STORE(transformed,(((_suby) * INTILE_XSIZE + (_subx))*icSizePadded + (_ic))*ntxtySizePadded + (_ntile),_value) if(ntxty < ntxtySizePadded && ic < icSizePadded) { //Copy private tile out to transformed output for(int subY = 0; subY < INTILE_YSIZE; subY++) { for(int subX = 0; subX < INTILE_XSIZE; subX++) { real result = WTILE(subY,subX); WRITETRANS(subY,subX,ic,ntxty,result); } } } } )%%"; string OpenCLKernels::winogradTransformNCHWToroidal = OpenCLKernels::common + R"%%( //Expected defines--------------------------------- //Dimension of input tile //INTILE_XSIZE 4 for F(2x2,3x3) //INTILE_YSIZE 4 for F(2x2,3x3) //Dimension of conv //CONV_XSIZE 3 for F(2x2,3x3) //CONV_YSIZE 3 for F(2x2,3x3) //Output tile size //OUTTILE_XSIZE 2 for F(2x2,3x3) //OUTTILE_YSIZE 2 for F(2x2,3x3) //Location of the upper left corner of the zeroth tile //INTILE_XOFFSET (-1) for F(2x2,3x3) //INTILE_YOFFSET (-1) for F(2x2,3x3) __kernel void transform( __global realstore* restrict input, //N, ic, H, W __global realstore* restrict transformed, //(INTILE_YSIZE, INTILE_XSIZE), (ic), (batch, tileY, tileX) where the last two dimenions are padded int nSize, int xSize, int ySize, int numTilesX, int numTilesY, int icSize, int icSizePadded, //Padding I need to change? int ntxtySizePadded ) { int id0 = get_global_id(0); const int ntxty = id0; const int tileX = id0 % numTilesX; id0 = id0 / numTilesX; const int tileY = id0 % numTilesY; id0 = id0 / numTilesY; const int n = id0; const int ic = get_global_id(1); const int nic = n * icSize + ic; const int xySize = xSize * ySize; #define INPUT(_nic,_xy) LOAD(input,((_nic) * xySize) + (_xy)) #define WTILE(_y,_x) wTile[(_y)*INTILE_XSIZE + (_x)] __private real wTile[INTILE_XSIZE * INTILE_YSIZE]; //Copy input into private tile for(int subY = 0; subY < INTILE_YSIZE; subY++) { int y = tileY * OUTTILE_YSIZE + subY + INTILE_YOFFSET; for(int subX = 0; subX < INTILE_XSIZE; subX++) { int x = tileX * OUTTILE_XSIZE + subX + INTILE_XOFFSET; real value = ZERO; if (n < nSize && ic < icSize) { int wrap_y = y; int wrap_x = x; if (wrap_x <= -1) wrap_x += xSize; else if (wrap_x >= xSize) wrap_x -= xSize; if (wrap_y <= -1) wrap_y += ySize; else if (wrap_y >= ySize) wrap_y -= ySize; int xy = wrap_y * xSize + wrap_x; value = INPUT(nic,xy); } WTILE(subY,subX) = value; } } #if CONV_XSIZE == 3 && OUTTILE_XSIZE == 2 for(int subY = 0; subY < INTILE_YSIZE; subY++) { real z0 = WTILE(subY,0); real z1 = WTILE(subY,1); real z2 = WTILE(subY,2); real z3 = WTILE(subY,3); WTILE(subY,0) = z0 - z2; WTILE(subY,1) = z1 + z2; WTILE(subY,2) = z2 - z1; WTILE(subY,3) = z1 - z3; } #elif CONV_XSIZE == 3 && OUTTILE_XSIZE == 4 for(int subY = 0; subY < INTILE_YSIZE; subY++) { real z0 = WTILE(subY,0); real z1 = WTILE(subY,1); real z2 = WTILE(subY,2); real z3 = WTILE(subY,3); real z4 = WTILE(subY,4); real z5 = WTILE(subY,5); // Low error winograd // WTILE(subY,0) = z0 - TWOP5*z2 + z4; // WTILE(subY,1) = - SQRT2*z1 - TWO*z2 + SQRTHALF*z3 + z4; // WTILE(subY,2) = SQRT2*z1 - TWO*z2 - SQRTHALF*z3 + z4; // WTILE(subY,3) = - SQRTHALF*z1 - HALF*z2 + SQRT2*z3 + z4; // WTILE(subY,4) = SQRTHALF*z1 - HALF*z2 - SQRT2*z3 + z4; // WTILE(subY,5) = z1 - TWOP5*z3 + z5; WTILE(subY,0) = FOUR*z0 - FIVE*z2 + z4; WTILE(subY,1) = - FOUR*z1 - FOUR*z2 + z3 + z4; WTILE(subY,2) = FOUR*z1 - FOUR*z2 - z3 + z4; WTILE(subY,3) = - TWO*z1 - z2 + TWO*z3 + z4; WTILE(subY,4) = TWO*z1 - z2 - TWO*z3 + z4; WTILE(subY,5) = FOUR*z1 - FIVE*z3 + z5; } #elif CONV_XSIZE == 5 && OUTTILE_XSIZE == 2 for(int subY = 0; subY < INTILE_YSIZE; subY++) { real z0 = WTILE(subY,0); real z1 = WTILE(subY,1); real z2 = WTILE(subY,2); real z3 = WTILE(subY,3); real z4 = WTILE(subY,4); real z5 = WTILE(subY,5); WTILE(subY,0) = FOUR*z0 - FIVE*z2 + z4; WTILE(subY,1) = - FOUR*z1 - FOUR*z2 + z3 + z4; WTILE(subY,2) = FOUR*z1 - FOUR*z2 - z3 + z4; WTILE(subY,3) = - TWO*z1 - z2 + TWO*z3 + z4; WTILE(subY,4) = TWO*z1 - z2 - TWO*z3 + z4; WTILE(subY,5) = FOUR*z1 - FIVE*z3 + z5; } #else #error "No X winograd implemented for this conv and tile size" #endif #if CONV_YSIZE == 3 && OUTTILE_YSIZE == 2 for(int subX = 0; subX < INTILE_XSIZE; subX++) { real z0 = WTILE(0,subX); real z1 = WTILE(1,subX); real z2 = WTILE(2,subX); real z3 = WTILE(3,subX); WTILE(0,subX) = z0 - z2; WTILE(1,subX) = z1 + z2; WTILE(2,subX) = z2 - z1; WTILE(3,subX) = z1 - z3; } #elif CONV_YSIZE == 3 && OUTTILE_YSIZE == 4 for(int subX = 0; subX < INTILE_XSIZE; subX++) { real z0 = WTILE(0,subX); real z1 = WTILE(1,subX); real z2 = WTILE(2,subX); real z3 = WTILE(3,subX); real z4 = WTILE(4,subX); real z5 = WTILE(5,subX); // Low error winograd // WTILE(0,subX) = z0 - TWOP5*z2 + z4; // WTILE(1,subX) = - SQRT2*z1 - TWO*z2 + SQRTHALF*z3 + z4; // WTILE(2,subX) = SQRT2*z1 - TWO*z2 - SQRTHALF*z3 + z4; // WTILE(3,subX) = - SQRTHALF*z1 - HALF*z2 + SQRT2*z3 + z4; // WTILE(4,subX) = SQRTHALF*z1 - HALF*z2 - SQRT2*z3 + z4; // WTILE(5,subX) = z1 - TWOP5*z3 + z5; WTILE(0,subX) = FOUR*z0 - FIVE*z2 + z4; WTILE(1,subX) = - FOUR*z1 - FOUR*z2 + z3 + z4; WTILE(2,subX) = FOUR*z1 - FOUR*z2 - z3 + z4; WTILE(3,subX) = - TWO*z1 - z2 + TWO*z3 + z4; WTILE(4,subX) = TWO*z1 - z2 - TWO*z3 + z4; WTILE(5,subX) = FOUR*z1 - FIVE*z3 + z5; } #elif CONV_YSIZE == 5 && OUTTILE_YSIZE == 2 for(int subX = 0; subX < INTILE_XSIZE; subX++) { real z0 = WTILE(0,subX); real z1 = WTILE(1,subX); real z2 = WTILE(2,subX); real z3 = WTILE(3,subX); real z4 = WTILE(4,subX); real z5 = WTILE(5,subX); WTILE(0,subX) = FOUR*z0 - FIVE*z2 + z4; WTILE(1,subX) = - FOUR*z1 - FOUR*z2 + z3 + z4; WTILE(2,subX) = FOUR*z1 - FOUR*z2 - z3 + z4; WTILE(3,subX) = - TWO*z1 - z2 + TWO*z3 + z4; WTILE(4,subX) = TWO*z1 - z2 - TWO*z3 + z4; WTILE(5,subX) = FOUR*z1 - FIVE*z3 + z5; } #else #error "No Y winograd implemented for this conv and tile size" #endif #define WRITETRANS(_suby,_subx,_ic,_ntile,_value) STORE(transformed,(((_suby) * INTILE_XSIZE + (_subx))*icSizePadded + (_ic))*ntxtySizePadded + (_ntile),_value) if(ntxty < ntxtySizePadded && ic < icSizePadded) { //Copy private tile out to transformed output for(int subY = 0; subY < INTILE_YSIZE; subY++) { for(int subX = 0; subX < INTILE_XSIZE; subX++) { real result = WTILE(subY,subX); WRITETRANS(subY,subX,ic,ntxty,result); } } } } )%%"; string OpenCLKernels::winogradTransformNCHWKlein = OpenCLKernels::common + R"%%( //Expected defines--------------------------------- //Dimension of input tile //INTILE_XSIZE 4 for F(2x2,3x3) //INTILE_YSIZE 4 for F(2x2,3x3) //Dimension of conv //CONV_XSIZE 3 for F(2x2,3x3) //CONV_YSIZE 3 for F(2x2,3x3) //Output tile size //OUTTILE_XSIZE 2 for F(2x2,3x3) //OUTTILE_YSIZE 2 for F(2x2,3x3) //Location of the upper left corner of the zeroth tile //INTILE_XOFFSET (-1) for F(2x2,3x3) //INTILE_YOFFSET (-1) for F(2x2,3x3) __kernel void transform( __global realstore* restrict input, //N, ic, H, W __global realstore* restrict transformed, //(INTILE_YSIZE, INTILE_XSIZE), (ic), (batch, tileY, tileX) where the last two dimenions are padded int nSize, int xSize, int ySize, int numTilesX, int numTilesY, int icSize, int icSizePadded, //Padding I need to change? int ntxtySizePadded ) { int id0 = get_global_id(0); const int ntxty = id0; const int tileX = id0 % numTilesX; id0 = id0 / numTilesX; const int tileY = id0 % numTilesY; id0 = id0 / numTilesY; const int n = id0; const int ic = get_global_id(1); const int nic = n * icSize + ic; const int xySize = xSize * ySize; #define INPUT(_nic,_xy) LOAD(input,((_nic) * xySize) + (_xy)) #define WTILE(_y,_x) wTile[(_y)*INTILE_XSIZE + (_x)] __private real wTile[INTILE_XSIZE * INTILE_YSIZE]; //Copy input into private tile for(int subY = 0; subY < INTILE_YSIZE; subY++) { int y = tileY * OUTTILE_YSIZE + subY + INTILE_YOFFSET; for(int subX = 0; subX < INTILE_XSIZE; subX++) { int x = tileX * OUTTILE_XSIZE + subX + INTILE_XOFFSET; real value = ZERO; if (n < nSize && ic < icSize) { int wrap_y = y; int wrap_x = x; if (wrap_y <= -1) wrap_y += ySize; else if (wrap_y >= ySize) wrap_y -= ySize; if (wrap_x <= -1) {wrap_x += xSize; wrap_y = ySize-1-wrap_y;} else if (wrap_x >= xSize) {wrap_x -= xSize; wrap_y = ySize-1-wrap_y;} int xy = wrap_y * xSize + wrap_x; value = INPUT(nic,xy); } WTILE(subY,subX) = value; } } #if CONV_XSIZE == 3 && OUTTILE_XSIZE == 2 for(int subY = 0; subY < INTILE_YSIZE; subY++) { real z0 = WTILE(subY,0); real z1 = WTILE(subY,1); real z2 = WTILE(subY,2); real z3 = WTILE(subY,3); WTILE(subY,0) = z0 - z2; WTILE(subY,1) = z1 + z2; WTILE(subY,2) = z2 - z1; WTILE(subY,3) = z1 - z3; } #elif CONV_XSIZE == 3 && OUTTILE_XSIZE == 4 for(int subY = 0; subY < INTILE_YSIZE; subY++) { real z0 = WTILE(subY,0); real z1 = WTILE(subY,1); real z2 = WTILE(subY,2); real z3 = WTILE(subY,3); real z4 = WTILE(subY,4); real z5 = WTILE(subY,5); // Low error winograd // WTILE(subY,0) = z0 - TWOP5*z2 + z4; // WTILE(subY,1) = - SQRT2*z1 - TWO*z2 + SQRTHALF*z3 + z4; // WTILE(subY,2) = SQRT2*z1 - TWO*z2 - SQRTHALF*z3 + z4; // WTILE(subY,3) = - SQRTHALF*z1 - HALF*z2 + SQRT2*z3 + z4; // WTILE(subY,4) = SQRTHALF*z1 - HALF*z2 - SQRT2*z3 + z4; // WTILE(subY,5) = z1 - TWOP5*z3 + z5; WTILE(subY,0) = FOUR*z0 - FIVE*z2 + z4; WTILE(subY,1) = - FOUR*z1 - FOUR*z2 + z3 + z4; WTILE(subY,2) = FOUR*z1 - FOUR*z2 - z3 + z4; WTILE(subY,3) = - TWO*z1 - z2 + TWO*z3 + z4; WTILE(subY,4) = TWO*z1 - z2 - TWO*z3 + z4; WTILE(subY,5) = FOUR*z1 - FIVE*z3 + z5; } #elif CONV_XSIZE == 5 && OUTTILE_XSIZE == 2 for(int subY = 0; subY < INTILE_YSIZE; subY++) { real z0 = WTILE(subY,0); real z1 = WTILE(subY,1); real z2 = WTILE(subY,2); real z3 = WTILE(subY,3); real z4 = WTILE(subY,4); real z5 = WTILE(subY,5); WTILE(subY,0) = FOUR*z0 - FIVE*z2 + z4; WTILE(subY,1) = - FOUR*z1 - FOUR*z2 + z3 + z4; WTILE(subY,2) = FOUR*z1 - FOUR*z2 - z3 + z4; WTILE(subY,3) = - TWO*z1 - z2 + TWO*z3 + z4; WTILE(subY,4) = TWO*z1 - z2 - TWO*z3 + z4; WTILE(subY,5) = FOUR*z1 - FIVE*z3 + z5; } #else #error "No X winograd implemented for this conv and tile size" #endif #if CONV_YSIZE == 3 && OUTTILE_YSIZE == 2 for(int subX = 0; subX < INTILE_XSIZE; subX++) { real z0 = WTILE(0,subX); real z1 = WTILE(1,subX); real z2 = WTILE(2,subX); real z3 = WTILE(3,subX); WTILE(0,subX) = z0 - z2; WTILE(1,subX) = z1 + z2; WTILE(2,subX) = z2 - z1; WTILE(3,subX) = z1 - z3; } #elif CONV_YSIZE == 3 && OUTTILE_YSIZE == 4 for(int subX = 0; subX < INTILE_XSIZE; subX++) { real z0 = WTILE(0,subX); real z1 = WTILE(1,subX); real z2 = WTILE(2,subX); real z3 = WTILE(3,subX); real z4 = WTILE(4,subX); real z5 = WTILE(5,subX); // Low error winograd // WTILE(0,subX) = z0 - TWOP5*z2 + z4; // WTILE(1,subX) = - SQRT2*z1 - TWO*z2 + SQRTHALF*z3 + z4; // WTILE(2,subX) = SQRT2*z1 - TWO*z2 - SQRTHALF*z3 + z4; // WTILE(3,subX) = - SQRTHALF*z1 - HALF*z2 + SQRT2*z3 + z4; // WTILE(4,subX) = SQRTHALF*z1 - HALF*z2 - SQRT2*z3 + z4; // WTILE(5,subX) = z1 - TWOP5*z3 + z5; WTILE(0,subX) = FOUR*z0 - FIVE*z2 + z4; WTILE(1,subX) = - FOUR*z1 - FOUR*z2 + z3 + z4; WTILE(2,subX) = FOUR*z1 - FOUR*z2 - z3 + z4; WTILE(3,subX) = - TWO*z1 - z2 + TWO*z3 + z4; WTILE(4,subX) = TWO*z1 - z2 - TWO*z3 + z4; WTILE(5,subX) = FOUR*z1 - FIVE*z3 + z5; } #elif CONV_YSIZE == 5 && OUTTILE_YSIZE == 2 for(int subX = 0; subX < INTILE_XSIZE; subX++) { real z0 = WTILE(0,subX); real z1 = WTILE(1,subX); real z2 = WTILE(2,subX); real z3 = WTILE(3,subX); real z4 = WTILE(4,subX); real z5 = WTILE(5,subX); WTILE(0,subX) = FOUR*z0 - FIVE*z2 + z4; WTILE(1,subX) = - FOUR*z1 - FOUR*z2 + z3 + z4; WTILE(2,subX) = FOUR*z1 - FOUR*z2 - z3 + z4; WTILE(3,subX) = - TWO*z1 - z2 + TWO*z3 + z4; WTILE(4,subX) = TWO*z1 - z2 - TWO*z3 + z4; WTILE(5,subX) = FOUR*z1 - FIVE*z3 + z5; } #else #error "No Y winograd implemented for this conv and tile size" #endif #define WRITETRANS(_suby,_subx,_ic,_ntile,_value) STORE(transformed,(((_suby) * INTILE_XSIZE + (_subx))*icSizePadded + (_ic))*ntxtySizePadded + (_ntile),_value) if(ntxty < ntxtySizePadded && ic < icSizePadded) { //Copy private tile out to transformed output for(int subY = 0; subY < INTILE_YSIZE; subY++) { for(int subX = 0; subX < INTILE_XSIZE; subX++) { real result = WTILE(subY,subX); WRITETRANS(subY,subX,ic,ntxty,result); } } } } )%%"; string OpenCLKernels::winogradBNReluTransformNCHWPlanar = OpenCLKernels::common + R"%%( //Expected defines--------------------------------- //Dimension of input tile //INTILE_XSIZE 4 for F(2x2,3x3) //INTILE_YSIZE 4 for F(2x2,3x3) //Dimension of conv //CONV_XSIZE 3 for F(2x2,3x3) //CONV_YSIZE 3 for F(2x2,3x3) //Output tile size //OUTTILE_XSIZE 2 for F(2x2,3x3) //OUTTILE_YSIZE 2 for F(2x2,3x3) //Location of the upper left corner of the zeroth tile //INTILE_XOFFSET (-1) for F(2x2,3x3) //INTILE_YOFFSET (-1) for F(2x2,3x3) #define SQRT8 2.82842712475f #define SQRT2 1.41421356237f #define SQRTHALF 0.70710678118f #define SQRTEIGHTH 0.35355339059f __kernel void bnReluTransform( __global realstore* restrict input, //N, ic, H, W __global realstore* restrict transformed, //(INTILE_YSIZE, INTILE_XSIZE), (ic), (batch, tileY, tileX) where the last two dimenions are padded __global realstore* restrict scale, //ic __global realstore* restrict bias, //ic __global realstore* restrict mask, //N, H, W int nSize, int xSize, int ySize, int numTilesX, int numTilesY, int icSize, int icSizePadded, int ntxtySizePadded ) { int id0 = get_global_id(0); const int ntxty = id0; const int tileX = id0 % numTilesX; id0 = id0 / numTilesX; const int tileY = id0 % numTilesY; id0 = id0 / numTilesY; const int n = id0; const int ic = get_global_id(1); const int nic = n * icSize + ic; const int xySize = xSize * ySize; #define INPUT(_nic,_xy) LOAD(input,((_nic) * xySize) + (_xy)) #define WTILE(_y,_x) wTile[(_y)*INTILE_XSIZE + (_x)] __private real wTile[INTILE_XSIZE * INTILE_YSIZE]; //Copy input into private tile for(int subY = 0; subY < INTILE_YSIZE; subY++) { int y = tileY * OUTTILE_YSIZE + subY + INTILE_YOFFSET; for(int subX = 0; subX < INTILE_XSIZE; subX++) { int x = tileX * OUTTILE_XSIZE + subX + INTILE_XOFFSET; real value = ZERO; if(y >= 0 && y < ySize && x >= 0 && x < xSize && n < nSize && ic < icSize) { int xy = y * xSize + x; value = fmax(INPUT(nic,xy) * LOAD(scale,ic) + LOAD(bias,ic), ZERO) * LOAD(mask, n * xySize + xy); } WTILE(subY,subX) = value; } } #if CONV_XSIZE == 3 && OUTTILE_XSIZE == 2 for(int subY = 0; subY < INTILE_YSIZE; subY++) { real z0 = WTILE(subY,0); real z1 = WTILE(subY,1); real z2 = WTILE(subY,2); real z3 = WTILE(subY,3); WTILE(subY,0) = z0 - z2; WTILE(subY,1) = z1 + z2; WTILE(subY,2) = z2 - z1; WTILE(subY,3) = z1 - z3; } #elif CONV_XSIZE == 3 && OUTTILE_XSIZE == 4 for(int subY = 0; subY < INTILE_YSIZE; subY++) { real z0 = WTILE(subY,0); real z1 = WTILE(subY,1); real z2 = WTILE(subY,2); real z3 = WTILE(subY,3); real z4 = WTILE(subY,4); real z5 = WTILE(subY,5); // Low error winograd // WTILE(subY,0) = z0 - TWOP5*z2 + z4; // WTILE(subY,1) = - SQRT2*z1 - TWO*z2 + SQRTHALF*z3 + z4; // WTILE(subY,2) = SQRT2*z1 - TWO*z2 - SQRTHALF*z3 + z4; // WTILE(subY,3) = - SQRTHALF*z1 - HALF*z2 + SQRT2*z3 + z4; // WTILE(subY,4) = SQRTHALF*z1 - HALF*z2 - SQRT2*z3 + z4; // WTILE(subY,5) = z1 - TWOP5*z3 + z5; WTILE(subY,0) = FOUR*z0 - FIVE*z2 + z4; WTILE(subY,1) = - FOUR*z1 - FOUR*z2 + z3 + z4; WTILE(subY,2) = FOUR*z1 - FOUR*z2 - z3 + z4; WTILE(subY,3) = - TWO*z1 - z2 + TWO*z3 + z4; WTILE(subY,4) = TWO*z1 - z2 - TWO*z3 + z4; WTILE(subY,5) = FOUR*z1 - FIVE*z3 + z5; } #elif CONV_XSIZE == 5 && OUTTILE_XSIZE == 2 for(int subY = 0; subY < INTILE_YSIZE; subY++) { real z0 = WTILE(subY,0); real z1 = WTILE(subY,1); real z2 = WTILE(subY,2); real z3 = WTILE(subY,3); real z4 = WTILE(subY,4); real z5 = WTILE(subY,5); WTILE(subY,0) = FOUR*z0 - FIVE*z2 + z4; WTILE(subY,1) = - FOUR*z1 - FOUR*z2 + z3 + z4; WTILE(subY,2) = FOUR*z1 - FOUR*z2 - z3 + z4; WTILE(subY,3) = - TWO*z1 - z2 + TWO*z3 + z4; WTILE(subY,4) = TWO*z1 - z2 - TWO*z3 + z4; WTILE(subY,5) = FOUR*z1 - FIVE*z3 + z5; } #else #error "No X winograd implemented for this conv and tile size" #endif #if CONV_YSIZE == 3 && OUTTILE_YSIZE == 2 for(int subX = 0; subX < INTILE_XSIZE; subX++) { real z0 = WTILE(0,subX); real z1 = WTILE(1,subX); real z2 = WTILE(2,subX); real z3 = WTILE(3,subX); WTILE(0,subX) = z0 - z2; WTILE(1,subX) = z1 + z2; WTILE(2,subX) = z2 - z1; WTILE(3,subX) = z1 - z3; } #elif CONV_YSIZE == 3 && OUTTILE_YSIZE == 4 for(int subX = 0; subX < INTILE_XSIZE; subX++) { real z0 = WTILE(0,subX); real z1 = WTILE(1,subX); real z2 = WTILE(2,subX); real z3 = WTILE(3,subX); real z4 = WTILE(4,subX); real z5 = WTILE(5,subX); // Low error winograd // WTILE(0,subX) = z0 - TWOP5*z2 + z4; // WTILE(1,subX) = - SQRT2*z1 - TWO*z2 + SQRTHALF*z3 + z4; // WTILE(2,subX) = SQRT2*z1 - TWO*z2 - SQRTHALF*z3 + z4; // WTILE(3,subX) = - SQRTHALF*z1 - HALF*z2 + SQRT2*z3 + z4; // WTILE(4,subX) = SQRTHALF*z1 - HALF*z2 - SQRT2*z3 + z4; // WTILE(5,subX) = z1 - TWOP5*z3 + z5; WTILE(0,subX) = FOUR*z0 - FIVE*z2 + z4; WTILE(1,subX) = - FOUR*z1 - FOUR*z2 + z3 + z4; WTILE(2,subX) = FOUR*z1 - FOUR*z2 - z3 + z4; WTILE(3,subX) = - TWO*z1 - z2 + TWO*z3 + z4; WTILE(4,subX) = TWO*z1 - z2 - TWO*z3 + z4; WTILE(5,subX) = FOUR*z1 - FIVE*z3 + z5; } #elif CONV_YSIZE == 5 && OUTTILE_YSIZE == 2 for(int subX = 0; subX < INTILE_XSIZE; subX++) { real z0 = WTILE(0,subX); real z1 = WTILE(1,subX); real z2 = WTILE(2,subX); real z3 = WTILE(3,subX); real z4 = WTILE(4,subX); real z5 = WTILE(5,subX); WTILE(0,subX) = FOUR*z0 - FIVE*z2 + z4; WTILE(1,subX) = - FOUR*z1 - FOUR*z2 + z3 + z4; WTILE(2,subX) = FOUR*z1 - FOUR*z2 - z3 + z4; WTILE(3,subX) = - TWO*z1 - z2 + TWO*z3 + z4; WTILE(4,subX) = TWO*z1 - z2 - TWO*z3 + z4; WTILE(5,subX) = FOUR*z1 - FIVE*z3 + z5; } #else #error "No Y winograd implemented for this conv and tile size" #endif #define WRITETRANS(_suby,_subx,_ic,_ntile,_value) STORE(transformed,(((_suby) * INTILE_XSIZE + (_subx))*icSizePadded + (_ic))*ntxtySizePadded + (_ntile),_value) if(ntxty < ntxtySizePadded && ic < icSizePadded) { //Copy private tile out to transformed output for(int subY = 0; subY < INTILE_YSIZE; subY++) { for(int subX = 0; subX < INTILE_XSIZE; subX++) { real result = WTILE(subY,subX); WRITETRANS(subY,subX,ic,ntxty,result); } } } } )%%"; string OpenCLKernels::winogradBNReluTransformNCHWToroidal = OpenCLKernels::common + R"%%( //Expected defines--------------------------------- //Dimension of input tile //INTILE_XSIZE 4 for F(2x2,3x3) //INTILE_YSIZE 4 for F(2x2,3x3) //Dimension of conv //CONV_XSIZE 3 for F(2x2,3x3) //CONV_YSIZE 3 for F(2x2,3x3) //Output tile size //OUTTILE_XSIZE 2 for F(2x2,3x3) //OUTTILE_YSIZE 2 for F(2x2,3x3) //Location of the upper left corner of the zeroth tile //INTILE_XOFFSET (-1) for F(2x2,3x3) //INTILE_YOFFSET (-1) for F(2x2,3x3) #define SQRT8 2.82842712475f #define SQRT2 1.41421356237f #define SQRTHALF 0.70710678118f #define SQRTEIGHTH 0.35355339059f __kernel void bnReluTransform( __global realstore* restrict input, //N, ic, H, W __global realstore* restrict transformed, //(INTILE_YSIZE, INTILE_XSIZE), (ic), (batch, tileY, tileX) where the last two dimenions are padded __global realstore* restrict scale, //ic __global realstore* restrict bias, //ic __global realstore* restrict mask, //N, H, W int nSize, int xSize, int ySize, int numTilesX, int numTilesY, int icSize, int icSizePadded, int ntxtySizePadded ) { int id0 = get_global_id(0); const int ntxty = id0; const int tileX = id0 % numTilesX; id0 = id0 / numTilesX; const int tileY = id0 % numTilesY; id0 = id0 / numTilesY; const int n = id0; const int ic = get_global_id(1); const int nic = n * icSize + ic; const int xySize = xSize * ySize; #define INPUT(_nic,_xy) LOAD(input,((_nic) * xySize) + (_xy)) #define WTILE(_y,_x) wTile[(_y)*INTILE_XSIZE + (_x)] __private real wTile[INTILE_XSIZE * INTILE_YSIZE]; //Copy input into private tile for(int subY = 0; subY < INTILE_YSIZE; subY++) { int y = tileY * OUTTILE_YSIZE + subY + INTILE_YOFFSET; for(int subX = 0; subX < INTILE_XSIZE; subX++) { int x = tileX * OUTTILE_XSIZE + subX + INTILE_XOFFSET; real value = ZERO; if (n < nSize && ic < icSize) { int wrap_y = y; int wrap_x = x; if (wrap_x <= -1) wrap_x += xSize; else if (wrap_x >= xSize) wrap_x -= xSize; if (wrap_y <= -1) wrap_y += ySize; else if (wrap_y >= ySize) wrap_y -= ySize; int xy = wrap_y * xSize + wrap_x; value = fmax(INPUT(nic,xy) * LOAD(scale,ic) + LOAD(bias,ic), ZERO) * LOAD(mask, n * xySize + xy); } WTILE(subY,subX) = value; } } #if CONV_XSIZE == 3 && OUTTILE_XSIZE == 2 for(int subY = 0; subY < INTILE_YSIZE; subY++) { real z0 = WTILE(subY,0); real z1 = WTILE(subY,1); real z2 = WTILE(subY,2); real z3 = WTILE(subY,3); WTILE(subY,0) = z0 - z2; WTILE(subY,1) = z1 + z2; WTILE(subY,2) = z2 - z1; WTILE(subY,3) = z1 - z3; } #elif CONV_XSIZE == 3 && OUTTILE_XSIZE == 4 for(int subY = 0; subY < INTILE_YSIZE; subY++) { real z0 = WTILE(subY,0); real z1 = WTILE(subY,1); real z2 = WTILE(subY,2); real z3 = WTILE(subY,3); real z4 = WTILE(subY,4); real z5 = WTILE(subY,5); // Low error winograd // WTILE(subY,0) = z0 - TWOP5*z2 + z4; // WTILE(subY,1) = - SQRT2*z1 - TWO*z2 + SQRTHALF*z3 + z4; // WTILE(subY,2) = SQRT2*z1 - TWO*z2 - SQRTHALF*z3 + z4; // WTILE(subY,3) = - SQRTHALF*z1 - HALF*z2 + SQRT2*z3 + z4; // WTILE(subY,4) = SQRTHALF*z1 - HALF*z2 - SQRT2*z3 + z4; // WTILE(subY,5) = z1 - TWOP5*z3 + z5; WTILE(subY,0) = FOUR*z0 - FIVE*z2 + z4; WTILE(subY,1) = - FOUR*z1 - FOUR*z2 + z3 + z4; WTILE(subY,2) = FOUR*z1 - FOUR*z2 - z3 + z4; WTILE(subY,3) = - TWO*z1 - z2 + TWO*z3 + z4; WTILE(subY,4) = TWO*z1 - z2 - TWO*z3 + z4; WTILE(subY,5) = FOUR*z1 - FIVE*z3 + z5; } #elif CONV_XSIZE == 5 && OUTTILE_XSIZE == 2 for(int subY = 0; subY < INTILE_YSIZE; subY++) { real z0 = WTILE(subY,0); real z1 = WTILE(subY,1); real z2 = WTILE(subY,2); real z3 = WTILE(subY,3); real z4 = WTILE(subY,4); real z5 = WTILE(subY,5); WTILE(subY,0) = FOUR*z0 - FIVE*z2 + z4; WTILE(subY,1) = - FOUR*z1 - FOUR*z2 + z3 + z4; WTILE(subY,2) = FOUR*z1 - FOUR*z2 - z3 + z4; WTILE(subY,3) = - TWO*z1 - z2 + TWO*z3 + z4; WTILE(subY,4) = TWO*z1 - z2 - TWO*z3 + z4; WTILE(subY,5) = FOUR*z1 - FIVE*z3 + z5; } #else #error "No X winograd implemented for this conv and tile size" #endif #if CONV_YSIZE == 3 && OUTTILE_YSIZE == 2 for(int subX = 0; subX < INTILE_XSIZE; subX++) { real z0 = WTILE(0,subX); real z1 = WTILE(1,subX); real z2 = WTILE(2,subX); real z3 = WTILE(3,subX); WTILE(0,subX) = z0 - z2; WTILE(1,subX) = z1 + z2; WTILE(2,subX) = z2 - z1; WTILE(3,subX) = z1 - z3; } #elif CONV_YSIZE == 3 && OUTTILE_YSIZE == 4 for(int subX = 0; subX < INTILE_XSIZE; subX++) { real z0 = WTILE(0,subX); real z1 = WTILE(1,subX); real z2 = WTILE(2,subX); real z3 = WTILE(3,subX); real z4 = WTILE(4,subX); real z5 = WTILE(5,subX); // Low error winograd // WTILE(0,subX) = z0 - TWOP5*z2 + z4; // WTILE(1,subX) = - SQRT2*z1 - TWO*z2 + SQRTHALF*z3 + z4; // WTILE(2,subX) = SQRT2*z1 - TWO*z2 - SQRTHALF*z3 + z4; // WTILE(3,subX) = - SQRTHALF*z1 - HALF*z2 + SQRT2*z3 + z4; // WTILE(4,subX) = SQRTHALF*z1 - HALF*z2 - SQRT2*z3 + z4; // WTILE(5,subX) = z1 - TWOP5*z3 + z5; WTILE(0,subX) = FOUR*z0 - FIVE*z2 + z4; WTILE(1,subX) = - FOUR*z1 - FOUR*z2 + z3 + z4; WTILE(2,subX) = FOUR*z1 - FOUR*z2 - z3 + z4; WTILE(3,subX) = - TWO*z1 - z2 + TWO*z3 + z4; WTILE(4,subX) = TWO*z1 - z2 - TWO*z3 + z4; WTILE(5,subX) = FOUR*z1 - FIVE*z3 + z5; } #elif CONV_YSIZE == 5 && OUTTILE_YSIZE == 2 for(int subX = 0; subX < INTILE_XSIZE; subX++) { real z0 = WTILE(0,subX); real z1 = WTILE(1,subX); real z2 = WTILE(2,subX); real z3 = WTILE(3,subX); real z4 = WTILE(4,subX); real z5 = WTILE(5,subX); WTILE(0,subX) = FOUR*z0 - FIVE*z2 + z4; WTILE(1,subX) = - FOUR*z1 - FOUR*z2 + z3 + z4; WTILE(2,subX) = FOUR*z1 - FOUR*z2 - z3 + z4; WTILE(3,subX) = - TWO*z1 - z2 + TWO*z3 + z4; WTILE(4,subX) = TWO*z1 - z2 - TWO*z3 + z4; WTILE(5,subX) = FOUR*z1 - FIVE*z3 + z5; } #else #error "No Y winograd implemented for this conv and tile size" #endif #define WRITETRANS(_suby,_subx,_ic,_ntile,_value) STORE(transformed,(((_suby) * INTILE_XSIZE + (_subx))*icSizePadded + (_ic))*ntxtySizePadded + (_ntile),_value) if(ntxty < ntxtySizePadded && ic < icSizePadded) { //Copy private tile out to transformed output for(int subY = 0; subY < INTILE_YSIZE; subY++) { for(int subX = 0; subX < INTILE_XSIZE; subX++) { real result = WTILE(subY,subX); WRITETRANS(subY,subX,ic,ntxty,result); } } } } )%%"; string OpenCLKernels::winogradBNReluTransformNCHWKlein = OpenCLKernels::common + R"%%( //Expected defines--------------------------------- //Dimension of input tile //INTILE_XSIZE 4 for F(2x2,3x3) //INTILE_YSIZE 4 for F(2x2,3x3) //Dimension of conv //CONV_XSIZE 3 for F(2x2,3x3) //CONV_YSIZE 3 for F(2x2,3x3) //Output tile size //OUTTILE_XSIZE 2 for F(2x2,3x3) //OUTTILE_YSIZE 2 for F(2x2,3x3) //Location of the upper left corner of the zeroth tile //INTILE_XOFFSET (-1) for F(2x2,3x3) //INTILE_YOFFSET (-1) for F(2x2,3x3) #define SQRT8 2.82842712475f #define SQRT2 1.41421356237f #define SQRTHALF 0.70710678118f #define SQRTEIGHTH 0.35355339059f __kernel void bnReluTransform( __global realstore* restrict input, //N, ic, H, W __global realstore* restrict transformed, //(INTILE_YSIZE, INTILE_XSIZE), (ic), (batch, tileY, tileX) where the last two dimenions are padded __global realstore* restrict scale, //ic __global realstore* restrict bias, //ic __global realstore* restrict mask, //N, H, W int nSize, int xSize, int ySize, int numTilesX, int numTilesY, int icSize, int icSizePadded, int ntxtySizePadded ) { int id0 = get_global_id(0); const int ntxty = id0; const int tileX = id0 % numTilesX; id0 = id0 / numTilesX; const int tileY = id0 % numTilesY; id0 = id0 / numTilesY; const int n = id0; const int ic = get_global_id(1); const int nic = n * icSize + ic; const int xySize = xSize * ySize; #define INPUT(_nic,_xy) LOAD(input,((_nic) * xySize) + (_xy)) #define WTILE(_y,_x) wTile[(_y)*INTILE_XSIZE + (_x)] __private real wTile[INTILE_XSIZE * INTILE_YSIZE]; //Copy input into private tile for(int subY = 0; subY < INTILE_YSIZE; subY++) { int y = tileY * OUTTILE_YSIZE + subY + INTILE_YOFFSET; for(int subX = 0; subX < INTILE_XSIZE; subX++) { int x = tileX * OUTTILE_XSIZE + subX + INTILE_XOFFSET; real value = ZERO; if (n < nSize && ic < icSize) { int wrap_y = y; int wrap_x = x; if (wrap_y <= -1) wrap_y += ySize; else if (wrap_y >= ySize) wrap_y -= ySize; if (wrap_x <= -1) {wrap_x += xSize; wrap_y = ySize-1-wrap_y;} else if (wrap_x >= xSize) {wrap_x -= xSize; wrap_y = ySize-1-wrap_y;} int xy = wrap_y * xSize + wrap_x; value = fmax(INPUT(nic,xy) * LOAD(scale,ic) + LOAD(bias,ic), ZERO) * LOAD(mask, n * xySize + xy); } WTILE(subY,subX) = value; } } #if CONV_XSIZE == 3 && OUTTILE_XSIZE == 2 for(int subY = 0; subY < INTILE_YSIZE; subY++) { real z0 = WTILE(subY,0); real z1 = WTILE(subY,1); real z2 = WTILE(subY,2); real z3 = WTILE(subY,3); WTILE(subY,0) = z0 - z2; WTILE(subY,1) = z1 + z2; WTILE(subY,2) = z2 - z1; WTILE(subY,3) = z1 - z3; } #elif CONV_XSIZE == 3 && OUTTILE_XSIZE == 4 for(int subY = 0; subY < INTILE_YSIZE; subY++) { real z0 = WTILE(subY,0); real z1 = WTILE(subY,1); real z2 = WTILE(subY,2); real z3 = WTILE(subY,3); real z4 = WTILE(subY,4); real z5 = WTILE(subY,5); // Low error winograd // WTILE(subY,0) = z0 - TWOP5*z2 + z4; // WTILE(subY,1) = - SQRT2*z1 - TWO*z2 + SQRTHALF*z3 + z4; // WTILE(subY,2) = SQRT2*z1 - TWO*z2 - SQRTHALF*z3 + z4; // WTILE(subY,3) = - SQRTHALF*z1 - HALF*z2 + SQRT2*z3 + z4; // WTILE(subY,4) = SQRTHALF*z1 - HALF*z2 - SQRT2*z3 + z4; // WTILE(subY,5) = z1 - TWOP5*z3 + z5; WTILE(subY,0) = FOUR*z0 - FIVE*z2 + z4; WTILE(subY,1) = - FOUR*z1 - FOUR*z2 + z3 + z4; WTILE(subY,2) = FOUR*z1 - FOUR*z2 - z3 + z4; WTILE(subY,3) = - TWO*z1 - z2 + TWO*z3 + z4; WTILE(subY,4) = TWO*z1 - z2 - TWO*z3 + z4; WTILE(subY,5) = FOUR*z1 - FIVE*z3 + z5; } #elif CONV_XSIZE == 5 && OUTTILE_XSIZE == 2 for(int subY = 0; subY < INTILE_YSIZE; subY++) { real z0 = WTILE(subY,0); real z1 = WTILE(subY,1); real z2 = WTILE(subY,2); real z3 = WTILE(subY,3); real z4 = WTILE(subY,4); real z5 = WTILE(subY,5); WTILE(subY,0) = FOUR*z0 - FIVE*z2 + z4; WTILE(subY,1) = - FOUR*z1 - FOUR*z2 + z3 + z4; WTILE(subY,2) = FOUR*z1 - FOUR*z2 - z3 + z4; WTILE(subY,3) = - TWO*z1 - z2 + TWO*z3 + z4; WTILE(subY,4) = TWO*z1 - z2 - TWO*z3 + z4; WTILE(subY,5) = FOUR*z1 - FIVE*z3 + z5; } #else #error "No X winograd implemented for this conv and tile size" #endif #if CONV_YSIZE == 3 && OUTTILE_YSIZE == 2 for(int subX = 0; subX < INTILE_XSIZE; subX++) { real z0 = WTILE(0,subX); real z1 = WTILE(1,subX); real z2 = WTILE(2,subX); real z3 = WTILE(3,subX); WTILE(0,subX) = z0 - z2; WTILE(1,subX) = z1 + z2; WTILE(2,subX) = z2 - z1; WTILE(3,subX) = z1 - z3; } #elif CONV_YSIZE == 3 && OUTTILE_YSIZE == 4 for(int subX = 0; subX < INTILE_XSIZE; subX++) { real z0 = WTILE(0,subX); real z1 = WTILE(1,subX); real z2 = WTILE(2,subX); real z3 = WTILE(3,subX); real z4 = WTILE(4,subX); real z5 = WTILE(5,subX); // Low error winograd // WTILE(0,subX) = z0 - TWOP5*z2 + z4; // WTILE(1,subX) = - SQRT2*z1 - TWO*z2 + SQRTHALF*z3 + z4; // WTILE(2,subX) = SQRT2*z1 - TWO*z2 - SQRTHALF*z3 + z4; // WTILE(3,subX) = - SQRTHALF*z1 - HALF*z2 + SQRT2*z3 + z4; // WTILE(4,subX) = SQRTHALF*z1 - HALF*z2 - SQRT2*z3 + z4; // WTILE(5,subX) = z1 - TWOP5*z3 + z5; WTILE(0,subX) = FOUR*z0 - FIVE*z2 + z4; WTILE(1,subX) = - FOUR*z1 - FOUR*z2 + z3 + z4; WTILE(2,subX) = FOUR*z1 - FOUR*z2 - z3 + z4; WTILE(3,subX) = - TWO*z1 - z2 + TWO*z3 + z4; WTILE(4,subX) = TWO*z1 - z2 - TWO*z3 + z4; WTILE(5,subX) = FOUR*z1 - FIVE*z3 + z5; } #elif CONV_YSIZE == 5 && OUTTILE_YSIZE == 2 for(int subX = 0; subX < INTILE_XSIZE; subX++) { real z0 = WTILE(0,subX); real z1 = WTILE(1,subX); real z2 = WTILE(2,subX); real z3 = WTILE(3,subX); real z4 = WTILE(4,subX); real z5 = WTILE(5,subX); WTILE(0,subX) = FOUR*z0 - FIVE*z2 + z4; WTILE(1,subX) = - FOUR*z1 - FOUR*z2 + z3 + z4; WTILE(2,subX) = FOUR*z1 - FOUR*z2 - z3 + z4; WTILE(3,subX) = - TWO*z1 - z2 + TWO*z3 + z4; WTILE(4,subX) = TWO*z1 - z2 - TWO*z3 + z4; WTILE(5,subX) = FOUR*z1 - FIVE*z3 + z5; } #else #error "No Y winograd implemented for this conv and tile size" #endif #define WRITETRANS(_suby,_subx,_ic,_ntile,_value) STORE(transformed,(((_suby) * INTILE_XSIZE + (_subx))*icSizePadded + (_ic))*ntxtySizePadded + (_ntile),_value) if(ntxty < ntxtySizePadded && ic < icSizePadded) { //Copy private tile out to transformed output for(int subY = 0; subY < INTILE_YSIZE; subY++) { for(int subX = 0; subX < INTILE_XSIZE; subX++) { real result = WTILE(subY,subX); WRITETRANS(subY,subX,ic,ntxty,result); } } } } )%%"; string OpenCLKernels::winogradUntransformNCHW = OpenCLKernels::common + R"%%( //Expected defines--------------------------------- //Dimension of input tile //INTILE_XSIZE 4 for F(2x2,3x3) //INTILE_YSIZE 4 for F(2x2,3x3) //Dimension of conv //CONV_XSIZE 3 for F(2x2,3x3) //CONV_YSIZE 3 for F(2x2,3x3) //Output tile size //OUTTILE_XSIZE 2 for F(2x2,3x3) //OUTTILE_YSIZE 2 for F(2x2,3x3) //Location of the upper left corner of the zeroth tile //INTILE_XOFFSET (-1) for F(2x2,3x3) //INTILE_YOFFSET (-1) for F(2x2,3x3) #define SQRT8 2.82842712475f #define SQRT2 1.41421356237f #define SQRTHALF 0.70710678118f #define SQRTEIGHTH 0.35355339059f __kernel void untransform( __global realstore* restrict transformed, //(INTILE_YSIZE, INTILE_XSIZE), (oc), (batch, tileY, tileX) //where the last two dims are padded __global realstore* restrict output, //N, oc, H, W int nSize, int xSize, int ySize, int numTilesX, int numTilesY, int ocSize, int ocSizePadded, int ntxtySizePadded ) { const int tileX = get_global_id(0); const int tileY = get_global_id(1); const int noc = get_global_id(2); const int n = noc / ocSize; const int oc = noc % ocSize; const int ntile = (n * numTilesY + tileY) * numTilesX + tileX; #define WTILE(_y,_x) wTile[(_y)*INTILE_XSIZE + (_x)] #define TRANS(_suby,_subx,_oc,_ntile) LOAD(transformed,(((_suby) * INTILE_XSIZE + (_subx))*ocSizePadded + (_oc)) * ntxtySizePadded + (_ntile)) #define WRITEOUTPUT(_noc,_y,_x,_value) STORE(output,((_noc) * ySize + (_y)) * xSize + (_x),_value) __private real wTile[INTILE_XSIZE * INTILE_YSIZE]; //Copy into private tile if(tileX < numTilesX && tileY < numTilesY && n < nSize) { for(int subY = 0; subY < INTILE_YSIZE; subY++) { for(int subX = 0; subX < INTILE_XSIZE; subX++) { WTILE(subY,subX) = TRANS(subY,subX,oc,ntile); } } } #if CONV_XSIZE == 3 && OUTTILE_XSIZE == 2 for(int subY = 0; subY < INTILE_YSIZE; subY++) { real z0 = WTILE(subY,0); real z1 = WTILE(subY,1); real z2 = WTILE(subY,2); real z3 = WTILE(subY,3); WTILE(subY,0) = z0 + z1 + z2; WTILE(subY,1) = z1 - z2 - z3; } #elif CONV_XSIZE == 3 && OUTTILE_XSIZE == 4 for(int subY = 0; subY < INTILE_YSIZE; subY++) { real z0 = WTILE(subY,0); real z1 = WTILE(subY,1); real z2 = WTILE(subY,2); real z3 = WTILE(subY,3); real z4 = WTILE(subY,4); real z5 = WTILE(subY,5); WTILE(subY,0) = z0 + z1 + z2 + z3 + z4; // Low error winograd // WTILE(subY,1) = SQRTHALF*(z1 - z2) + SQRT2*(z3 - z4); // WTILE(subY,2) = HALF*(z1 + z2) + TWO*(z3 + z4); // WTILE(subY,3) = SQRTEIGHTH*(z1 - z2) + SQRT8*(z3 - z4) + z5; WTILE(subY,1) = (z1 - z2) + TWO*(z3 - z4); WTILE(subY,2) = (z1 + z2) + FOUR*(z3 + z4); WTILE(subY,3) = (z1 - z2) + EIGHT*(z3 - z4) + z5; } #elif CONV_XSIZE == 5 && OUTTILE_XSIZE == 2 for(int subY = 0; subY < INTILE_YSIZE; subY++) { real z0 = WTILE(subY,0); real z1 = WTILE(subY,1); real z2 = WTILE(subY,2); real z3 = WTILE(subY,3); real z4 = WTILE(subY,4); real z5 = WTILE(subY,5); WTILE(subY,0) = z0 + z1 + z2 + z3 + z4; WTILE(subY,1) = (z1 - z2) + TWO*(z3 - z4) + z5; } #else #error "No X winograd implemented for this conv and tile size" #endif #if CONV_YSIZE == 3 && OUTTILE_YSIZE == 2 for(int subX = 0; subX < OUTTILE_XSIZE; subX++) { real z0 = WTILE(0,subX); real z1 = WTILE(1,subX); real z2 = WTILE(2,subX); real z3 = WTILE(3,subX); WTILE(0,subX) = z0 + z1 + z2; WTILE(1,subX) = z1 - z2 - z3; } #elif CONV_YSIZE == 3 && OUTTILE_YSIZE == 4 for(int subX = 0; subX < OUTTILE_XSIZE; subX++) { real z0 = WTILE(0,subX); real z1 = WTILE(1,subX); real z2 = WTILE(2,subX); real z3 = WTILE(3,subX); real z4 = WTILE(4,subX); real z5 = WTILE(5,subX); WTILE(0,subX) = z0 + z1 + z2 + z3 + z4; // Low error winograd // WTILE(1,subX) = SQRTHALF*(z1 - z2) + SQRT2*(z3 - z4); // WTILE(2,subX) = HALF*(z1 + z2) + TWO*(z3 + z4); // WTILE(3,subX) = SQRTEIGHTH*(z1 - z2) + SQRT8*(z3 - z4) + z5; WTILE(1,subX) = (z1 - z2) + TWO*(z3 - z4); WTILE(2,subX) = (z1 + z2) + FOUR*(z3 + z4); WTILE(3,subX) = (z1 - z2) + EIGHT*(z3 - z4) + z5; } #elif CONV_YSIZE == 5 && OUTTILE_YSIZE == 2 for(int subX = 0; subX < OUTTILE_XSIZE; subX++) { real z0 = WTILE(0,subX); real z1 = WTILE(1,subX); real z2 = WTILE(2,subX); real z3 = WTILE(3,subX); real z4 = WTILE(4,subX); real z5 = WTILE(5,subX); WTILE(0,subX) = z0 + z1 + z2 + z3 + z4; WTILE(1,subX) = (z1 - z2) + TWO*(z3 - z4) + z5; } #else #error "No Y winograd implemented for this conv and tile size" #endif //Copy into output for(int subY = 0; subY < OUTTILE_YSIZE; subY++) { int y = tileY * OUTTILE_YSIZE + subY; for(int subX = 0; subX < OUTTILE_XSIZE; subX++) { int x = tileX * OUTTILE_XSIZE + subX; if(y >= 0 && y < ySize && x >= 0 && x < xSize && tileX < numTilesX && tileY < numTilesY && n < nSize) { real result = WTILE(subY,subX); WRITEOUTPUT(noc,y,x,result); } //if (tileX < numTilesX && tileY < numTilesY && n < nSize) { // real result = WTILE(subY,subX); // int wrap_y = y; // int wrap_x = x; // if (wrap_x <= -1) wrap_x += xSize; // else if (wrap_x >= xSize) wrap_x -= xSize; // if (wrap_y <= -1) wrap_y += ySize; // else if (wrap_y >= ySize) wrap_y -= ySize; // WRITEOUTPUT(noc,wrap_y,wrap_x,result); //} } } } )%%"; string OpenCLKernels::scaleBiasMaskNCHW = OpenCLKernels::common + R"%%( __kernel void scaleBiasMaskNCHW( __global realstore* input, //N, c, H, W __global realstore* output, //N, c, H, W __global realstore* scale, //c __global realstore* bias, //c __global realstore* mask, //N, H, W int nSize, int cSize, int xySize ) { const int xy = get_global_id(0); const int c = get_global_id(1); if(c < cSize && xy < xySize) { for(int n = 0; n < nSize; n++) { int idx = (n * cSize + c) * xySize + xy; real result = (LOAD(input,idx) * LOAD(scale,c) + LOAD(bias,c)) * LOAD(mask,n * xySize + xy); STORE(output,idx,result); } } } )%%"; string OpenCLKernels::scaleBiasMaskReluNCHW = OpenCLKernels::common + R"%%( __kernel void scaleBiasMaskReluNCHW( __global realstore* input, //N, c, H, W __global realstore* output, //N, c, H, W __global realstore* scale, //c __global realstore* bias, //c __global realstore* mask, //N, H, W int nSize, int cSize, int xySize ) { const int xy = get_global_id(0); const int c = get_global_id(1); if(c < cSize && xy < xySize) { for(int n = 0; n < nSize; n++) { int idx = (n * cSize + c) * xySize + xy; real result = fmax(LOAD(input,idx) * LOAD(scale,c) + LOAD(bias,c), ZERO) * LOAD(mask,n * xySize + xy); STORE(output,idx,result); } } } )%%"; string OpenCLKernels::addPointWise = OpenCLKernels::common + R"%%( __kernel void addPointWise( __global realstore* accum, __global realstore* value, int size ) { const int s = get_global_id(0); if(s < size) { real result = LOAD(accum,s) + LOAD(value,s); STORE(accum,s,result); } } )%%"; string OpenCLKernels::sumChannelsNCHW = OpenCLKernels::common + R"%%( //Defines: //XYSTRIDE - power of two parallelism stride for reduction, should be get_local_size(0) //CHANNELSTRIDE - stride for channels, should be get_local_size(1) //LOCALSIZE_TOTAL - should be get_local_size(0) * get_local_size(1) * get_local_size(2) //PRECONDIION: Kernel is being run where get_num_groups(0) == 1, so that global id and local id are identical for dim 0 __kernel void sumChannelsNCHW( __global realstore* input, //N, c, HW __global float* output, //N, c int nSize, int cSize, int xySize ) { const int xyBase = get_local_id(0); const int c = get_global_id(1); const int n = get_global_id(2); const int localId1 = get_local_id(1); const int localId2 = get_local_id(2); __local float partialSums[LOCALSIZE_TOTAL]; float sum = 0.0f; if(n < nSize && c < cSize) { //Sum up the elements that this group member is responsible for for(int xy = xyBase; xy < xySize; xy += XYSTRIDE) { int idx = (n * cSize + c) * xySize + xy; float v = LOAD(input,idx); sum += v; } } //Write to local memory for performing the reduction int localIdx = (localId2 * CHANNELSTRIDE + localId1) * XYSTRIDE + xyBase; partialSums[localIdx] = sum; //Parallel folding downward for(int span = XYSTRIDE / 2; span > 0; span /= 2) { barrier(CLK_LOCAL_MEM_FENCE); if(xyBase < span) { partialSums[localIdx] += partialSums[localIdx + span]; } } barrier(CLK_LOCAL_MEM_FENCE); if(n < nSize && c < cSize && xyBase == 0) { float finalSum = partialSums[localIdx]; int outBase = n * cSize + c; output[outBase] = finalSum; } } )%%"; string OpenCLKernels::gPoolChannelsNCHW = OpenCLKernels::common + R"%%( //Defines: //XYSTRIDE - power of two parallelism stride for reduction, should be get_local_size(0) //CHANNELSTRIDE - stride for channels, should be get_local_size(1) //LOCALSIZE_TOTAL - should be get_local_size(0) * get_local_size(1) * get_local_size(2) //PRECONDIION: Kernel is being run where get_num_groups(0) == 1, so that global id and local id are identical for dim 0 __kernel void gPoolChannelsNCHW( __global realstore* input, //N, c, HW __global float* output, //N, c __global float* maskSums, //N int nSize, int cSize, int xySize ) { const int xyBase = get_local_id(0); const int c = get_global_id(1); const int n = get_global_id(2); const int localId1 = get_local_id(1); const int localId2 = get_local_id(2); __local float partialSums[LOCALSIZE_TOTAL]; __local float partialMaxes[LOCALSIZE_TOTAL]; float sum = 0.0f; float max = 0.0f; if(n < nSize && c < cSize) { //Sum up the elements that this group member is responsible for for(int xy = xyBase; xy < xySize; xy += XYSTRIDE) { int idx = (n * cSize + c) * xySize + xy; float v = LOAD(input,idx); sum += v; max = fmax(max,v); } } //Write to local memory for performing the reduction int localIdx = (localId2 * CHANNELSTRIDE + localId1) * XYSTRIDE + xyBase; partialSums[localIdx] = sum; partialMaxes[localIdx] = max; //Parallel folding downward for(int span = XYSTRIDE / 2; span > 0; span /= 2) { barrier(CLK_LOCAL_MEM_FENCE); if(xyBase < span) { partialSums[localIdx] += partialSums[localIdx + span]; partialMaxes[localIdx] = fmax(partialMaxes[localIdx], partialMaxes[localIdx + span]); } } barrier(CLK_LOCAL_MEM_FENCE); if(n < nSize && c < cSize && xyBase == 0) { float finalSum = partialSums[localIdx]; float finalMax = partialMaxes[localIdx]; float div = maskSums[n]; float sqrtdiv = sqrt(div); float finalMean = finalSum/div; int outBase = n * cSize * 3 + c; output[outBase] = finalMean; output[outBase + cSize] = finalMean * (sqrtdiv - 14.0f) * 0.1f; output[outBase + cSize*2] = finalMax; } } )%%"; string OpenCLKernels::valueHeadPoolChannelsNCHW = OpenCLKernels::common + R"%%( //Defines: //XYSTRIDE - power of two parallelism stride for reduction, should be get_local_size(0) //CHANNELSTRIDE - stride for channels, should be get_local_size(1) //LOCALSIZE_TOTAL - should be get_local_size(0) * get_local_size(1) * get_local_size(2) //PRECONDIION: Kernel is being run where get_num_groups(0) == 1, so that global id and local id are identical for dim 0 __kernel void valueHeadPoolChannelsNCHW( __global realstore* input, //N, c, HW __global float* output, //N, c __global float* maskSums, //N int nSize, int cSize, int xySize ) { const int xyBase = get_local_id(0); const int c = get_global_id(1); const int n = get_global_id(2); const int localId1 = get_local_id(1); const int localId2 = get_local_id(2); __local float partialSums[LOCALSIZE_TOTAL]; float sum = 0.0f; if(n < nSize && c < cSize) { //Sum up the elements that this group member is responsible for for(int xy = xyBase; xy < xySize; xy += XYSTRIDE) { int idx = (n * cSize + c) * xySize + xy; float v = LOAD(input,idx); sum += v; } } //Write to local memory for performing the reduction int localIdx = (localId2 * CHANNELSTRIDE + localId1) * XYSTRIDE + xyBase; partialSums[localIdx] = sum; //Parallel folding downward for(int span = XYSTRIDE / 2; span > 0; span /= 2) { barrier(CLK_LOCAL_MEM_FENCE); if(xyBase < span) { partialSums[localIdx] += partialSums[localIdx + span]; } } barrier(CLK_LOCAL_MEM_FENCE); if(n < nSize && c < cSize && xyBase == 0) { float finalSum = partialSums[localIdx]; float div = maskSums[n]; float sqrtdiv = sqrt(div); float finalMean = finalSum/div; int outBase = n * cSize * 3 + c; output[outBase] = finalMean; output[outBase + cSize] = finalMean * (sqrtdiv - 14.0f) * 0.1f; output[outBase + cSize*2] = finalMean * ((sqrtdiv - 14.0f) * (sqrtdiv - 14.0f) * 0.01f - 0.1f); } } )%%"; string OpenCLKernels::addChannelBiasesNCHW = OpenCLKernels::common + R"%%( __kernel void addChannelBiasesNCHW( __global realstore* accum, //NC, HW __global float* biases, //NC int ncSize, int xySize ) { const int xy = get_global_id(0); const int nc = get_global_id(1); if(nc < ncSize && xy < xySize) { real result = LOAD(accum,nc * xySize + xy) + floatToReal(biases[nc]); STORE(accum, nc * xySize + xy, result); } } )%%"; string OpenCLKernels::addCBiasesNC = OpenCLKernels::common + R"%%( __kernel void addCBiasesNC( __global float* accum, //N,C __global float* biases, //C int nSize, int cSize ) { const int c = get_global_id(0); const int n = get_global_id(1); if(n < nSize && c < cSize) accum[n * cSize + c] += biases[c]; } )%%"; string OpenCLKernels::addCBiasesNCRelu = OpenCLKernels::common + R"%%( __kernel void addCBiasesNCRelu( __global float* accum, //N,C __global float* biases, //C int nSize, int cSize ) { const int c = get_global_id(0); const int n = get_global_id(1); if(n < nSize && c < cSize) accum[n * cSize + c] = fmax(accum[n * cSize + c] + biases[c], 0.0f); } )%%"; string OpenCLKernels::extractChannel0NCHW = OpenCLKernels::common + R"%%( __kernel void extractChannel0NCHW(__global realstore* in, __global realstore* out, int nSize, int cSize, int xySize) { const int xyIdx = get_global_id(0); const int nIdx = get_global_id(1); if(xyIdx < xySize && nIdx < nSize) { real result = LOAD(in,nIdx * cSize * xySize + xyIdx); STORE(out,nIdx * xySize + xyIdx,result); } } )%%"; //. string OpenCLKernels::xgemmDirect = #include "../external/clblast/common.opencl" #include "../external/clblast/xgemm_direct_part1.opencl" #include "../external/clblast/xgemm_direct_part2.opencl" #include "../external/clblast/xgemm_direct_part3.opencl" #include "../external/clblast/xgemm_direct_batched.opencl" ; string OpenCLKernels::xgemm = "#define ROUTINE_GEMMBATCHED\n" #include "../external/clblast/common.opencl" #include "../external/clblast/xgemm_part1a.opencl" #include "../external/clblast/xgemm_part1b.opencl" #include "../external/clblast/xgemm_part2.opencl" #include "../external/clblast/xgemm_part3.opencl" #include "../external/clblast/xgemm_batched.opencl" ; string OpenCLKernels::hgemmWmma = "" #include "../external/clblast/common.opencl" #include "../neuralnet/hgemm_wmma.opencl" ; #endif
33.598496
160
0.611609
[ "transform" ]
b43dcb3be65770cb8b1d7f51e7e32d8eb5645b5f
20,937
cpp
C++
src/TreeCanvas.cpp
tapeguy/heekscad
e5037d15d642551de756f352e4e14505c39ad7cf
[ "BSD-3-Clause" ]
null
null
null
src/TreeCanvas.cpp
tapeguy/heekscad
e5037d15d642551de756f352e4e14505c39ad7cf
[ "BSD-3-Clause" ]
null
null
null
src/TreeCanvas.cpp
tapeguy/heekscad
e5037d15d642551de756f352e4e14505c39ad7cf
[ "BSD-3-Clause" ]
null
null
null
// TreeCanvas.cpp // Copyright (c) 2009, Dan Heeks // This program is released under the BSD license. See the file COPYING for details. #include "stdafx.h" #include "TreeCanvas.h" #include "HeeksFrame.h" #include "wxImageLoader.h" #include "../interface/MarkedObject.h" BEGIN_EVENT_TABLE(CTreeCanvas, wxScrolledWindow) EVT_PAINT(CTreeCanvas::OnPaint) EVT_MOUSE_EVENTS(CTreeCanvas::OnMouse) EVT_MENU_RANGE(ID_FIRST_POP_UP_MENU_TOOL, ID_FIRST_POP_UP_MENU_TOOL + 1000, CTreeCanvas::OnMenuEvent) EVT_KEY_DOWN(CTreeCanvas::OnKeyDown) EVT_KEY_UP(CTreeCanvas::OnKeyUp) EVT_CHAR(CTreeCanvas::OnCharEvent) END_EVENT_TABLE() static wxBitmap* bmp_branch_plus = NULL; static wxBitmap* bmp_branch_minus = NULL; static wxBitmap* bmp_branch_end_plus = NULL; static wxBitmap* bmp_branch_end_minus = NULL; static wxBitmap* bmp_branch_split = NULL; static wxBitmap* bmp_branch_end = NULL; static wxBitmap* bmp_plus = NULL; static wxBitmap* bmp_minus = NULL; static wxBitmap* bmp_branch_trunk = NULL; CTreeCanvas::CTreeCanvas(wxWindow* parent) : wxScrolledWindow(parent),m_frozen(false), m_refresh_wanted_on_thaw(false), m_dragging(false), m_waiting_until_left_up(false), m_xpos(0), m_ypos(0), m_max_xpos(0) { wxGetApp().RegisterObserver(this); bmp_branch_plus = new wxBitmap(wxImage(wxGetApp().GetResFolder() + _T("/icons/branch_plus.png"))); bmp_branch_minus = new wxBitmap(wxImage(wxGetApp().GetResFolder() + _T("/icons/branch_minus.png"))); bmp_branch_end_plus = new wxBitmap(wxImage(wxGetApp().GetResFolder() + _T("/icons/branch_end_plus.png"))); bmp_branch_end_minus = new wxBitmap(wxImage(wxGetApp().GetResFolder() + _T("/icons/branch_end_minus.png"))); bmp_branch_split = new wxBitmap(wxImage(wxGetApp().GetResFolder() + _T("/icons/branch_split.png"))); bmp_branch_end = new wxBitmap(wxImage(wxGetApp().GetResFolder() + _T("/icons/branch_end.png"))); bmp_plus = new wxBitmap(wxImage(wxGetApp().GetResFolder() + _T("/icons/plus.png"))); bmp_minus = new wxBitmap(wxImage(wxGetApp().GetResFolder() + _T("/icons/minus.png"))); bmp_branch_trunk = new wxBitmap(wxImage(wxGetApp().GetResFolder() + _T("/icons/branch_trunk.png"))); SetScrollRate( 10, 10 ); SetVirtualSize( 92, 97 ); } CTreeCanvas::~CTreeCanvas() { wxGetApp().RemoveObserver(this); } wxPaintDC* CTreeCanvas::m_dc = NULL; void CTreeCanvas::OnPaint( wxPaintEvent& WXUNUSED(event) ) { /* must always be here */ wxPaintDC dc(this); PrepareDC(dc); m_dc = &dc; // render everything Render(); m_dc = NULL; } const CTreeCanvas::CTreeButton* CTreeCanvas::HitTest( const wxPoint& pt ) { for(std::list<CTreeButton>::iterator It = m_tree_buttons.begin(); It != m_tree_buttons.end(); It++) { CTreeButton& b = *It; wxPoint unscrolled_pt = this->CalcUnscrolledPosition(pt); if(b.rect.Contains(unscrolled_pt)) //if(b.rect.Inside(pt)) { return &b; } } return NULL; } static HeeksObj* clicked_object = NULL; void CTreeCanvas::OnMouse( wxMouseEvent& event ) { if(wxGetApp().m_property_grid_validation)return; if(event.Entering()){ SetFocus(); // so middle wheel works } if(event.LeftDown()) { const CTreeButton* button = HitTest(event.GetPosition()); if(button) { switch(button->type) { case ButtonTypePlus: case ButtonTypeMinus: SetExpanded(button->obj, button->type == 0); SetVirtualSize(GetRenderSize()); this->Refresh(); break; case ButtonTypeLabelBefore: case ButtonTypeLabel: default: OnLabelLeftDown(button->obj, event); clicked_object = button->obj; break; } } else { wxGetApp().m_marked_list->Clear(true); } m_button_down_point = event.GetPosition(); } if(event.LeftUp()) { if(m_dragging) { m_dragging = false; // find the object to drop on to const CTreeButton* button = HitTest(event.GetPosition()); if(button == NULL || !wxGetApp().m_marked_list->ObjectMarked(button->obj)) // can only drop on to an item other than one of the items being dragged { // test drop possible bool drag_possible = true; HeeksObj* add_to = &wxGetApp(); if(button && button->paste_into)add_to = button->paste_into; for(std::list<HeeksObj*>::iterator It = m_dragged_list.begin(); It != m_dragged_list.end(); It++) { HeeksObj* object = *It; if(!add_to->CanAdd(object) || !object->CanAddTo(add_to)) { drag_possible = false; break; } } if(drag_possible) { wxGetApp().StartHistory(); // cut the objects wxGetApp().Remove(m_dragged_list); // paste the objects for(std::list<HeeksObj*>::iterator It = m_dragged_list.begin(); It != m_dragged_list.end(); It++) { HeeksObj* object = *It; { if(object->OneOfAKind()) { bool one_found = false; for(HeeksObj* child = add_to->GetFirstChild(); child; child = add_to->GetNextChild()) { if(child->GetType() == object->GetType()) { child->CopyFrom(object); one_found = true; break; } } if(!one_found) { wxGetApp().AddUndoably(object, add_to, button ? button->paste_before : NULL); } } else { wxGetApp().AddUndoably(object, add_to, button ? button->paste_before : NULL); } } } wxGetApp().EndHistory(); } else { Refresh(); } } else { Refresh(); } } else { if(m_waiting_until_left_up) { wxGetApp().m_marked_list->Clear(false); wxGetApp().m_marked_list->Add(clicked_object, true); } } m_waiting_until_left_up = false; } if(event.RightDown()) { const CTreeButton* button = HitTest(event.GetPosition()); clicked_object = NULL; if(button && (button->type == ButtonTypeLabelBefore || button->type == ButtonTypeLabel)) { clicked_object = button->obj; OnLabelRightDown(button->obj, event); } } if(event.RightUp()) { // do a context menu MarkedObjectOneOfEach marked_object(0, clicked_object, 1, 0, NULL); if(m_dragging) { m_dragging = false; // find the object to drop on to const CTreeButton* button = HitTest(event.GetPosition()); if(button == NULL || !wxGetApp().m_marked_list->ObjectMarked(button->obj)) // can only drop on to an item other than one of the items being dragged { // make a Move or Copy context menu HeeksObj* paste_into = NULL; HeeksObj* paste_before = NULL; if(button) { paste_into = button->paste_into; paste_before = button->paste_before; } wxGetApp().DoMoveOrCopyDropDownMenu(this, event.GetPosition(), &marked_object, paste_into, paste_before); } else { Refresh(); } } else { // do a standard drop down menu wxGetApp().DoDropDownMenu(this, event.GetPosition(), &marked_object, true, false); } } if(event.Dragging()) { if(event.LeftIsDown() || event.RightIsDown()) { if(!m_dragging && (abs(m_button_down_point.x - event.GetX())>2 || abs(m_button_down_point.y - event.GetY())>2)) { m_dragging = true; m_dragged_list = wxGetApp().m_marked_list->list(); } if(m_dragging) { m_drag_position = CalcUnscrolledPosition(event.GetPosition()); const CTreeButton* button = HitTest(event.GetPosition()); m_drag_paste_rect = wxRect(0, 0, 0, 0); if(button && button->type == ButtonTypeLabelBefore)m_drag_paste_rect = button->rect; Refresh(); } } } if(event.LeftDClick()) { const CTreeButton* button = HitTest(event.GetPosition()); if(button) { if(button->obj) { bool(*callback)(HeeksObj*) = NULL; button->obj->GetOnEdit(&callback); if(callback) { (*callback)(button->obj); } } } } event.Skip(); } void CTreeCanvas::OnKeyDown(wxKeyEvent& event) { wxGetApp().input_mode_object->OnKeyDown(event); event.Skip(); } void CTreeCanvas::OnCharEvent(wxKeyEvent& event) { const int ControlA = 1; const int ControlC = 3; const int ControlV = 22; // printf("Key event is '%d'\n", event.GetKeyCode()); switch (event.GetKeyCode()) { case ControlA: { // Select all std::list<HeeksObj*> obj_list; for(HeeksObj* object = wxGetApp().GetFirstChild(); object != NULL; object = wxGetApp().GetNextChild()) { if(object->GetType() != GripperType) { obj_list.push_back(object); } // End if - then } // End for wxGetApp().m_marked_list->Add(obj_list, true); wxGetApp().Repaint(); event.Skip(); break; } // End ControlA scope case ControlC: // Copy wxGetApp().m_marked_list->CopySelectedItems(); wxGetApp().Repaint(); event.Skip(); break; case ControlV: // Paste wxGetApp().Paste(NULL, NULL); wxGetApp().Repaint(); event.Skip(); break; default: break; } // End switch } // End OnCharEvent() method void CTreeCanvas::OnKeyUp(wxKeyEvent& event) { wxGetApp().input_mode_object->OnKeyUp(event); event.Skip(); } void CTreeCanvas::OnMenuEvent(wxCommandEvent& event) { wxGetApp().on_menu_event(event); } void CTreeCanvas::OnChanged(const std::list<HeeksObj*>* added, const std::list<HeeksObj*>* removed, const std::list<HeeksObj*>* modified) { SetVirtualSize(GetRenderSize()); Refresh(); } void CTreeCanvas::WhenMarkedListChanges(bool selection_cleared, const std::list<HeeksObj *>* added_list, const std::list<HeeksObj *>* removed_list) { Refresh(); } void CTreeCanvas::Clear() { Refresh(); } void CTreeCanvas::Freeze() { m_frozen = true; } void CTreeCanvas::Thaw() { m_frozen = false; if(m_refresh_wanted_on_thaw) { Refresh(); m_refresh_wanted_on_thaw = false; } } void CTreeCanvas::Refresh() { if(m_frozen) { m_refresh_wanted_on_thaw = true; } else { wxScrolledWindow::Refresh(false); } } void CTreeCanvas::RefreshSoon() { if(m_frozen) { m_refresh_wanted_on_thaw = true; } else if(wxGetApp().m_frame->IsShown()) { wxScrolledWindow::Refresh(false); Update(); } } bool CTreeCanvas::IsExpanded(HeeksObj* object) { if(object->AutoExpand()) // assume it is expanded if it hasn't been collapsed return m_collapsed.find(object) == m_collapsed.end(); // it is expanded, if it is in the m_expanded set return m_expanded.find(object) != m_expanded.end(); } void CTreeCanvas::SetExpanded(HeeksObj* object, bool bExpanded) { if(bExpanded) { m_expanded.insert(object); m_collapsed.erase(object); } else { m_expanded.erase(object); m_collapsed.insert(object); } } static bool render_just_for_calculation = false; static bool render_labels = true; void CTreeCanvas::AddPlusOrMinusButton(HeeksObj* object, bool plus) { CTreeButton b; b.type = plus ? ButtonTypePlus : ButtonTypeMinus; b.rect.x = m_xpos; b.rect.y = m_ypos; b.rect.width = 16; b.rect.height = 18; b.obj = object; m_tree_buttons.push_back(b); } void CTreeCanvas::AddLabelButton(bool expanded, HeeksObj* prev_object, bool prev_object_expanded, HeeksObj* object, HeeksObj* next_object, int label_start_x, int label_end_x) { CTreeButton b; b.rect.x = label_start_x; b.rect.width = label_end_x - label_start_x; if(prev_object && !prev_object_expanded) { b.rect.y = m_ypos - 4; b.rect.height = 8; } else { b.rect.y = m_ypos; b.rect.height = 4; } b.type = ButtonTypeLabelBefore; b.obj = object; b.paste_into = object->GetOwner(); b.paste_before = object; m_tree_buttons.push_back(b); b.type = ButtonTypeLabel; b.rect.y = m_ypos + 4; b.rect.height = 10; b.paste_into = object; b.paste_before = NULL; m_tree_buttons.push_back(b); b.rect.y += b.rect.height; b.rect.height = 4; if(next_object == NULL && !expanded) { b.type = ButtonTypeLabelBefore; b.paste_into = object->GetOwner(); b.paste_before = next_object; m_tree_buttons.push_back(b); } } void CTreeCanvas::OnLabelLeftDown(HeeksObj* object, wxMouseEvent& event) { if(event.ShiftDown()) { // mark a list of siblings HeeksObj* parent = object->GetOwner(); std::set<HeeksObj*> sibling_set; std::list<HeeksObj*> sibling_list; for(HeeksObj* sibling = parent->GetFirstChild(); sibling; sibling = parent->GetNextChild()) { sibling_set.insert(sibling); sibling_list.push_back(sibling); } // find most recently marked sibling std::list<HeeksObj*> &marked = wxGetApp().m_marked_list->list(); HeeksObj* recently_marked_sibling = NULL; bool recent_first = false; for(std::list<HeeksObj*>::reverse_iterator It = marked.rbegin(); It != marked.rend(); It++) { if(*It == object)recent_first = true; if(sibling_set.find(*It) != sibling_set.end()) { recently_marked_sibling = *It; break; } } if(recently_marked_sibling) { if(!event.ControlDown()) { wxGetApp().m_marked_list->Clear(false); } bool marking = false; std::list<HeeksObj*> list_to_mark; bool finish_marking = false; for(std::list<HeeksObj*>::iterator It = sibling_list.begin(); !finish_marking && It != sibling_list.end(); It++) { HeeksObj* sibling = *It; if(sibling == object || sibling == recently_marked_sibling) { if(marking)finish_marking = true; else marking = true; } if(marking) { list_to_mark.push_back(sibling); } } wxGetApp().m_marked_list->Add(list_to_mark, true); } else { if(event.ControlDown()) { if(wxGetApp().m_marked_list->ObjectMarked(object)) { wxGetApp().m_marked_list->Remove(object, true); } else{ wxGetApp().m_marked_list->Add(object, true); } } else { if(wxGetApp().m_marked_list->ObjectMarked(object)) { m_waiting_until_left_up = true; } else { wxGetApp().m_marked_list->Clear(false); wxGetApp().m_marked_list->Add(object, true); } } } } else { // shift not down if(event.ControlDown()) { if(wxGetApp().m_marked_list->ObjectMarked(object)) { wxGetApp().m_marked_list->Remove(object, true); } else{ wxGetApp().m_marked_list->Add(object, true); } } else { if(wxGetApp().m_marked_list->ObjectMarked(object)) { m_waiting_until_left_up = true; } else { wxGetApp().m_marked_list->Clear(false); wxGetApp().m_marked_list->Add(object, true); } } } } void CTreeCanvas::OnLabelRightDown(HeeksObj* object, wxMouseEvent& event) { if(!wxGetApp().m_marked_list->ObjectMarked(object)) { wxGetApp().m_marked_list->Clear(false); wxGetApp().m_marked_list->Add(object, true); } } void CTreeCanvas::RenderBranchIcon(HeeksObj* object, HeeksObj* next_object, bool expanded, int level) { int num_children = object->GetNumChildren(); if(num_children > 0) { if(level) { // with branches if(next_object) { // not at end if(expanded) { m_dc->DrawBitmap(*bmp_branch_minus, m_xpos, m_ypos); if(render_labels)AddPlusOrMinusButton(object, false); } else { m_dc->DrawBitmap(*bmp_branch_plus, m_xpos, m_ypos); if(render_labels)AddPlusOrMinusButton(object, true); } } else { // not at end if(expanded) { m_dc->DrawBitmap(*bmp_branch_end_minus, m_xpos, m_ypos); if(render_labels)AddPlusOrMinusButton(object, false); } else { m_dc->DrawBitmap(*bmp_branch_end_plus, m_xpos, m_ypos); if(render_labels)AddPlusOrMinusButton(object, true); } } } else { // without branches if(expanded) { m_dc->DrawBitmap(*bmp_minus, m_xpos, m_ypos); if(render_labels)AddPlusOrMinusButton(object, false); } else { m_dc->DrawBitmap(*bmp_plus, m_xpos, m_ypos); if(render_labels)AddPlusOrMinusButton(object, true); } } } else { if(level) { // just branches if(next_object)m_dc->DrawBitmap(*bmp_branch_split, m_xpos, m_ypos); else m_dc->DrawBitmap(*bmp_branch_end, m_xpos, m_ypos); } } } static std::list<bool> end_child_list; void CTreeCanvas::RenderBranchIcons(HeeksObj* object, HeeksObj* next_object, bool expanded, int level) { // render initial branches std::list<bool>::iterator It = end_child_list.begin(); for(int i = 0; i<level; i++, It++) { if(!render_just_for_calculation && i > 0) { bool end_child = *It; if(!end_child)m_dc->DrawBitmap(*bmp_branch_trunk, m_xpos, m_ypos); } m_xpos += 16; } // render + or - if(!render_just_for_calculation)RenderBranchIcon(object, next_object, expanded, level); m_xpos += 16; } void CTreeCanvas::RenderObject(bool expanded, HeeksObj* prev_object, bool prev_object_expanded, HeeksObj* object, HeeksObj* next_object, int level) { int save_x = m_xpos; RenderBranchIcons(object, next_object, expanded, level); int label_start_x = m_xpos; // find icon info if(!render_just_for_calculation) { m_dc->DrawBitmap(object->GetIcon(), m_xpos, m_ypos); } m_xpos += 16; wxString str = object->GetTitle(); if ( str.IsEmpty()) { str = object->GetTypeString(); } if(!render_just_for_calculation) { if(render_labels && wxGetApp().m_marked_list->ObjectMarked(object)) { m_dc->SetBackgroundMode(wxSOLID); m_dc->SetTextBackground(*wxBLUE); m_dc->SetTextForeground(*wxWHITE); } else { m_dc->SetBackgroundMode(wxTRANSPARENT); m_dc->SetTextForeground(*wxBLACK); } m_dc->DrawText(str, m_xpos, m_ypos); } int text_width = 0; if(render_just_for_calculation || !render_labels) { // just make a guess, we don't have a valid m_dc text_width = 10 * str.Len(); } else { wxSize text_size = m_dc->GetTextExtent(str); text_width = text_size.GetWidth(); } int label_end_x = m_xpos + 8 + text_width; if(!render_just_for_calculation && render_labels) { AddLabelButton(expanded, prev_object, prev_object_expanded, object, next_object, label_start_x, label_end_x); } if(label_end_x > m_max_xpos) { m_max_xpos = label_end_x; } m_ypos += 18; bool end_object = (next_object == NULL); end_child_list.push_back(end_object); m_xpos = save_x; if(expanded) { HeeksObj* prev_child = NULL; bool prev_child_expanded = false; HeeksObj* child = object->GetFirstChild(); while(child) { HeeksObj* next_child = object->GetNextChild(); bool expanded = IsExpanded(child); RenderObject(expanded, prev_child, prev_child_expanded, child, next_child, level + 1); prev_child = child; prev_child_expanded = expanded; child = next_child; } } end_child_list.pop_back(); } void CTreeCanvas::Render(bool just_for_calculation) { render_just_for_calculation = just_for_calculation; if(!just_for_calculation) { #ifdef WIN32 // draw a white background rectangle int w, h; GetClientSize(&w, &h); wxPoint pTopLeft = CalcUnscrolledPosition(wxPoint(0, 0)); wxPoint pBottomRight = CalcUnscrolledPosition(wxPoint(w, h)); m_dc->SetBrush(wxBrush(wxT("white"))); m_dc->SetPen(wxPen(wxT("white"))); m_dc->DrawRectangle(wxRect(pTopLeft, pBottomRight)); #endif // set background m_dc->SetBackgroundMode(wxSOLID); m_dc->SetBackground(wxBrush(wxT("white"), wxSOLID)); m_dc->Clear(); m_tree_buttons.clear(); } m_xpos = 0; // start at the left m_ypos = 0;//-scroll_y_pos; // start at the top m_max_xpos = 0; HeeksObj* prev_object = NULL; bool prev_object_expanded = false; HeeksObj* object = wxGetApp().GetFirstChild(); while(object) { HeeksObj* next_object = wxGetApp().GetNextChild(); bool expanded = IsExpanded(object); RenderObject(expanded, prev_object, prev_object_expanded, object, next_object, 0); prev_object = object; prev_object_expanded = expanded; object = next_object; } // draw the dragged objects if(m_dragging) { wxSize drag_size = GetDraggedListSize(); m_dc->SetBrush(wxBrush(wxT("orange"))); m_dc->SetPen(wxPen(wxT("blue"))); m_dc->DrawRectangle(m_drag_position, drag_size); RenderDraggedList(); if(m_drag_paste_rect.width > 0) { m_dc->SetPen(wxPen(wxT("black"))); m_dc->SetBrush(wxBrush(wxT("black"))); m_dc->DrawRectangle(m_drag_paste_rect); } } } wxSize CTreeCanvas::GetRenderSize() { bool just_for_calculation = true; Render(just_for_calculation); return wxSize(m_max_xpos, m_ypos); } void CTreeCanvas::RenderDraggedList(bool just_for_calculation) { render_just_for_calculation = just_for_calculation; render_labels = false; if(just_for_calculation) { m_xpos = 0; m_ypos = 0; } else { m_xpos = m_drag_position.x; m_ypos = m_drag_position.y; } m_max_xpos = 0; if(m_dragged_list.size() > 0) { std::list<HeeksObj*>::iterator It = m_dragged_list.begin(); HeeksObj* prev_object = NULL; HeeksObj* object = *It; for(;It != m_dragged_list.end();) { It++; HeeksObj* next_object = NULL; if(It != m_dragged_list.end())next_object = *It; bool expanded = IsExpanded(object); RenderObject(expanded, prev_object, false, object, next_object, 0); prev_object = object; object = next_object; } } render_labels = true; } wxSize CTreeCanvas::GetDraggedListSize() { bool just_for_calculation = true; RenderDraggedList(just_for_calculation); return wxSize(m_max_xpos, m_ypos); }
23.684389
174
0.677556
[ "render", "object" ]
b4423c01dca711879189256968f6c6a990950262
23,770
cc
C++
tensorflow/lite/micro/kernels/split_test.cc
Arushacked/tensorflow
9abd61ae0b2d239d3060cdd3d46b54a105159828
[ "Apache-2.0" ]
78
2020-08-04T12:36:25.000Z
2022-03-25T04:23:40.000Z
tensorflow/lite/micro/kernels/split_test.cc
Arushacked/tensorflow
9abd61ae0b2d239d3060cdd3d46b54a105159828
[ "Apache-2.0" ]
10
2021-08-03T08:42:38.000Z
2022-01-03T03:29:12.000Z
tensorflow/lite/micro/kernels/split_test.cc
Arushacked/tensorflow
9abd61ae0b2d239d3060cdd3d46b54a105159828
[ "Apache-2.0" ]
28
2020-02-10T07:03:06.000Z
2022-01-12T11:19:20.000Z
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/c/builtin_op_data.h" #include "tensorflow/lite/c/common.h" #include "tensorflow/lite/micro/all_ops_resolver.h" #include "tensorflow/lite/micro/debug_log.h" #include "tensorflow/lite/micro/testing/micro_test.h" #include "tensorflow/lite/micro/testing/test_utils.h" namespace tflite { namespace testing { void TestSplitTwoOutputsFloat( std::initializer_list<int> input_dims_data, std::initializer_list<float> input_data, std::initializer_list<int> axis_dims_data, std::initializer_list<int32_t> axis_data, std::initializer_list<int> output1_dims_data, std::initializer_list<float> expected_output1_data, std::initializer_list<int> output2_dims_data, std::initializer_list<float> expected_output2_data, float* output1_data, float* output2_data) { TfLiteIntArray* input_dims = IntArrayFromInitializer(input_dims_data); TfLiteIntArray* axis_dims = IntArrayFromInitializer(axis_dims_data); TfLiteIntArray* output1_dims = IntArrayFromInitializer(output1_dims_data); TfLiteIntArray* output2_dims = IntArrayFromInitializer(output2_dims_data); const int output1_dims_count = ElementCount(*output1_dims); const int output2_dims_count = ElementCount(*output2_dims); constexpr int input_size = 1; constexpr int output_size = 2; constexpr int axis_size = 1; constexpr int tensors_size = input_size + output_size + axis_size; TfLiteTensor tensors[tensors_size] = { CreateQuantized32Tensor(axis_data, axis_dims, 1.0), CreateFloatTensor(input_data, input_dims), CreateFloatTensor(output1_data, output1_dims), CreateFloatTensor(output2_data, output2_dims)}; // Currently only support constant axis tensor. tensors[0].allocation_type = kTfLiteMmapRo; // Place a unique value in the uninitialized output buffer. for (int i = 0; i < output1_dims_count; ++i) { output1_data[i] = 23; } for (int i = 0; i < output2_dims_count; ++i) { output2_data[i] = 23; } TfLiteContext context; PopulateContext(tensors, tensors_size, micro_test::reporter, &context); tflite::AllOpsResolver resolver; const TfLiteRegistration* registration = resolver.FindOp(tflite::BuiltinOperator_SPLIT); TF_LITE_MICRO_EXPECT_NE(nullptr, registration); TfLiteSplitParams builtin_data = { .num_splits = 2, }; void* user_data = nullptr; if (registration->init) { user_data = registration->init(&context, nullptr, 0); } TfLiteIntArray* inputs_array = IntArrayFromInitializer({2, 0, 1}); TfLiteIntArray* outputs_array = IntArrayFromInitializer({2, 2, 3}); TfLiteIntArray* temporaries_array = IntArrayFromInitializer({0}); TfLiteNode node; node.inputs = inputs_array; node.outputs = outputs_array; node.temporaries = temporaries_array; node.user_data = user_data; node.builtin_data = reinterpret_cast<void*>(&builtin_data); node.custom_initial_data = nullptr; node.custom_initial_data_size = 0; node.delegate = nullptr; if (registration->prepare) { TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, registration->prepare(&context, &node)); } TF_LITE_MICRO_EXPECT_NE(nullptr, registration->invoke); TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, registration->invoke(&context, &node)); if (registration->free) { registration->free(&context, user_data); } for (int i = 0; i < output1_dims_count; ++i) { TF_LITE_MICRO_EXPECT_NEAR(expected_output1_data.begin()[i], output1_data[i], 1e-5f); } for (int i = 0; i < output2_dims_count; ++i) { TF_LITE_MICRO_EXPECT_NEAR(expected_output2_data.begin()[i], output2_data[i], 1e-5f); } } void TestSplitFourOutputsFloat( std::initializer_list<int> input_dims_data, std::initializer_list<float> input_data, std::initializer_list<int> axis_dims_data, std::initializer_list<int32_t> axis_data, std::initializer_list<int> output1_dims_data, std::initializer_list<float> expected_output1_data, std::initializer_list<int> output2_dims_data, std::initializer_list<float> expected_output2_data, std::initializer_list<int> output3_dims_data, std::initializer_list<float> expected_output3_data, std::initializer_list<int> output4_dims_data, std::initializer_list<float> expected_output4_data, float* output1_data, float* output2_data, float* output3_data, float* output4_data) { TfLiteIntArray* input_dims = IntArrayFromInitializer(input_dims_data); TfLiteIntArray* axis_dims = IntArrayFromInitializer(axis_dims_data); TfLiteIntArray* output1_dims = IntArrayFromInitializer(output1_dims_data); TfLiteIntArray* output2_dims = IntArrayFromInitializer(output2_dims_data); TfLiteIntArray* output3_dims = IntArrayFromInitializer(output3_dims_data); TfLiteIntArray* output4_dims = IntArrayFromInitializer(output4_dims_data); const int output1_dims_count = ElementCount(*output1_dims); const int output2_dims_count = ElementCount(*output2_dims); const int output3_dims_count = ElementCount(*output3_dims); const int output4_dims_count = ElementCount(*output4_dims); constexpr int input_size = 1; constexpr int output_size = 4; constexpr int axis_size = 1; constexpr int tensors_size = input_size + output_size + axis_size; TfLiteTensor tensors[tensors_size] = { CreateQuantized32Tensor(axis_data, axis_dims, 1.0), CreateFloatTensor(input_data, input_dims), CreateFloatTensor(output1_data, output1_dims), CreateFloatTensor(output2_data, output2_dims), CreateFloatTensor(output3_data, output1_dims), CreateFloatTensor(output4_data, output1_dims)}; // Currently only support constant axis tensor. tensors[0].allocation_type = kTfLiteMmapRo; // Place a unique value in the uninitialized output buffer. for (int i = 0; i < output1_dims_count; ++i) { output1_data[i] = 23; } for (int i = 0; i < output2_dims_count; ++i) { output2_data[i] = 23; } for (int i = 0; i < output3_dims_count; ++i) { output3_data[i] = 23; } for (int i = 0; i < output4_dims_count; ++i) { output4_data[i] = 23; } TfLiteContext context; PopulateContext(tensors, tensors_size, micro_test::reporter, &context); tflite::AllOpsResolver resolver; const TfLiteRegistration* registration = resolver.FindOp(tflite::BuiltinOperator_SPLIT); TF_LITE_MICRO_EXPECT_NE(nullptr, registration); TfLiteSplitParams builtin_data = { .num_splits = 4, }; void* user_data = nullptr; if (registration->init) { user_data = registration->init(&context, nullptr, 0); } TfLiteIntArray* inputs_array = IntArrayFromInitializer({2, 0, 1}); TfLiteIntArray* outputs_array = IntArrayFromInitializer({4, 2, 3, 4, 5}); TfLiteIntArray* temporaries_array = IntArrayFromInitializer({0}); TfLiteNode node; node.inputs = inputs_array; node.outputs = outputs_array; node.temporaries = temporaries_array; node.user_data = user_data; node.builtin_data = reinterpret_cast<void*>(&builtin_data); node.custom_initial_data = nullptr; node.custom_initial_data_size = 0; node.delegate = nullptr; if (registration->prepare) { TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, registration->prepare(&context, &node)); } TF_LITE_MICRO_EXPECT_NE(nullptr, registration->invoke); TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, registration->invoke(&context, &node)); if (registration->free) { registration->free(&context, user_data); } for (int i = 0; i < output1_dims_count; ++i) { TF_LITE_MICRO_EXPECT_NEAR(expected_output1_data.begin()[i], output1_data[i], 1e-5f); } for (int i = 0; i < output2_dims_count; ++i) { TF_LITE_MICRO_EXPECT_NEAR(expected_output2_data.begin()[i], output2_data[i], 1e-5f); } for (int i = 0; i < output3_dims_count; ++i) { TF_LITE_MICRO_EXPECT_NEAR(expected_output3_data.begin()[i], output3_data[i], 1e-5f); } for (int i = 0; i < output4_dims_count; ++i) { TF_LITE_MICRO_EXPECT_NEAR(expected_output4_data.begin()[i], output4_data[i], 1e-5f); } } void TestSplitTwoOutputsQuantized( std::initializer_list<int> input_dims_data, std::initializer_list<uint8_t> input_data, std::initializer_list<int> axis_dims_data, std::initializer_list<int32_t> axis_data, std::initializer_list<int> output1_dims_data, std::initializer_list<uint8_t> expected_output1_data, std::initializer_list<int> output2_dims_data, std::initializer_list<uint8_t> expected_output2_data, uint8_t* output1_data, uint8_t* output2_data) { TfLiteIntArray* input_dims = IntArrayFromInitializer(input_dims_data); TfLiteIntArray* axis_dims = IntArrayFromInitializer(axis_dims_data); TfLiteIntArray* output1_dims = IntArrayFromInitializer(output1_dims_data); TfLiteIntArray* output2_dims = IntArrayFromInitializer(output2_dims_data); const int output1_dims_count = ElementCount(*output1_dims); const int output2_dims_count = ElementCount(*output2_dims); constexpr int input_size = 1; constexpr int output_size = 2; constexpr int axis_size = 1; constexpr int tensors_size = input_size + output_size + axis_size; TfLiteTensor tensors[tensors_size] = { CreateQuantized32Tensor(axis_data, axis_dims, 1.0), CreateQuantizedTensor(input_data, input_dims, 0, 10), CreateQuantizedTensor(output1_data, output1_dims, 0, 10), CreateQuantizedTensor(output2_data, output2_dims, 0, 10)}; // Currently only support constant axis tensor. tensors[0].allocation_type = kTfLiteMmapRo; // Place a unique value in the uninitialized output buffer. for (int i = 0; i < output1_dims_count; ++i) { output1_data[i] = 23; } for (int i = 0; i < output2_dims_count; ++i) { output2_data[i] = 23; } TfLiteContext context; PopulateContext(tensors, tensors_size, micro_test::reporter, &context); tflite::AllOpsResolver resolver; const TfLiteRegistration* registration = resolver.FindOp(tflite::BuiltinOperator_SPLIT); TF_LITE_MICRO_EXPECT_NE(nullptr, registration); TfLiteSplitParams builtin_data = { .num_splits = 2, }; void* user_data = nullptr; if (registration->init) { user_data = registration->init(&context, nullptr, 0); } TfLiteIntArray* inputs_array = IntArrayFromInitializer({2, 0, 1}); TfLiteIntArray* outputs_array = IntArrayFromInitializer({2, 2, 3}); TfLiteIntArray* temporaries_array = IntArrayFromInitializer({0}); TfLiteNode node; node.inputs = inputs_array; node.outputs = outputs_array; node.temporaries = temporaries_array; node.user_data = user_data; node.builtin_data = reinterpret_cast<void*>(&builtin_data); node.custom_initial_data = nullptr; node.custom_initial_data_size = 0; node.delegate = nullptr; if (registration->prepare) { TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, registration->prepare(&context, &node)); } TF_LITE_MICRO_EXPECT_NE(nullptr, registration->invoke); TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, registration->invoke(&context, &node)); if (registration->free) { registration->free(&context, user_data); } for (int i = 0; i < output1_dims_count; ++i) { TF_LITE_MICRO_EXPECT_EQ(expected_output1_data.begin()[i], output1_data[i]); } for (int i = 0; i < output2_dims_count; ++i) { TF_LITE_MICRO_EXPECT_EQ(expected_output2_data.begin()[i], output2_data[i]); } } void TestSplitTwoOutputsQuantized32( std::initializer_list<int> input_dims_data, std::initializer_list<int32_t> input_data, std::initializer_list<int> axis_dims_data, std::initializer_list<int32_t> axis_data, std::initializer_list<int> output1_dims_data, std::initializer_list<int32_t> expected_output1_data, std::initializer_list<int> output2_dims_data, std::initializer_list<int32_t> expected_output2_data, int32_t* output1_data, int32_t* output2_data) { TfLiteIntArray* input_dims = IntArrayFromInitializer(input_dims_data); TfLiteIntArray* axis_dims = IntArrayFromInitializer(axis_dims_data); TfLiteIntArray* output1_dims = IntArrayFromInitializer(output1_dims_data); TfLiteIntArray* output2_dims = IntArrayFromInitializer(output2_dims_data); const int output1_dims_count = ElementCount(*output1_dims); const int output2_dims_count = ElementCount(*output2_dims); constexpr int input_size = 1; constexpr int output_size = 2; constexpr int axis_size = 1; constexpr int tensors_size = input_size + output_size + axis_size; TfLiteTensor tensors[tensors_size] = { CreateQuantized32Tensor(axis_data, axis_dims, 1.0), CreateQuantized32Tensor(input_data, input_dims, 1.0), CreateQuantized32Tensor(output1_data, output1_dims, 1.0), CreateQuantized32Tensor(output2_data, output2_dims, 1.0)}; // Currently only support constant axis tensor. tensors[0].allocation_type = kTfLiteMmapRo; // Place a unique value in the uninitialized output buffer. for (int i = 0; i < output1_dims_count; ++i) { output1_data[i] = 23; } for (int i = 0; i < output2_dims_count; ++i) { output2_data[i] = 23; } TfLiteContext context; PopulateContext(tensors, tensors_size, micro_test::reporter, &context); tflite::AllOpsResolver resolver; const TfLiteRegistration* registration = resolver.FindOp(tflite::BuiltinOperator_SPLIT); TF_LITE_MICRO_EXPECT_NE(nullptr, registration); TfLiteSplitParams builtin_data = { .num_splits = 2, }; void* user_data = nullptr; if (registration->init) { user_data = registration->init(&context, nullptr, 0); } TfLiteIntArray* inputs_array = IntArrayFromInitializer({2, 0, 1}); TfLiteIntArray* outputs_array = IntArrayFromInitializer({2, 2, 3}); TfLiteIntArray* temporaries_array = IntArrayFromInitializer({0}); TfLiteNode node; node.inputs = inputs_array; node.outputs = outputs_array; node.temporaries = temporaries_array; node.user_data = user_data; node.builtin_data = reinterpret_cast<void*>(&builtin_data); node.custom_initial_data = nullptr; node.custom_initial_data_size = 0; node.delegate = nullptr; if (registration->prepare) { TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, registration->prepare(&context, &node)); } TF_LITE_MICRO_EXPECT_NE(nullptr, registration->invoke); TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, registration->invoke(&context, &node)); if (registration->free) { registration->free(&context, user_data); } for (int i = 0; i < output1_dims_count; ++i) { TF_LITE_MICRO_EXPECT_EQ(expected_output1_data.begin()[i], output1_data[i]); } for (int i = 0; i < output2_dims_count; ++i) { TF_LITE_MICRO_EXPECT_EQ(expected_output2_data.begin()[i], output2_data[i]); } } } // namespace testing } // namespace tflite TF_LITE_MICRO_TESTS_BEGIN TF_LITE_MICRO_TEST(TwoSplitFourDimensionalAxisZero) { constexpr int output1_dims_count = 8; constexpr int output2_dims_count = 8; float output1_data[output1_dims_count]; float output2_data[output2_dims_count]; tflite::testing::TestSplitTwoOutputsFloat( {4, 2, 2, 2, 2}, // Input shape {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, // Input values {1, 1}, // Axis shape {0}, // Axis value {4, 1, 2, 2, 2}, // Output1 shape {1, 2, 3, 4, 5, 6, 7, 8}, // Output1 values {4, 1, 2, 2, 2}, // Output2 shape {9, 10, 11, 12, 13, 14, 15, 16}, // Output2 values output1_data, output2_data); } TF_LITE_MICRO_TEST(TwoSplitFourDimensionalAxisOne) { constexpr int output1_dims_count = 8; constexpr int output2_dims_count = 8; float output1_data[output1_dims_count]; float output2_data[output2_dims_count]; tflite::testing::TestSplitTwoOutputsFloat( {4, 2, 2, 2, 2}, // Input shape {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, // Input values {1, 1}, // Axis shape {1}, // Axis value {4, 2, 1, 2, 2}, // Output1 shape {1, 2, 3, 4, 9, 10, 11, 12}, // Output1 values {4, 2, 1, 2, 2}, // Output2 shape {5, 6, 7, 8, 13, 14, 15, 16}, // Output2 values output1_data, output2_data); } TF_LITE_MICRO_TEST(TwoSplitFourDimensionalAxisTwo) { constexpr int output1_dims_count = 8; constexpr int output2_dims_count = 8; float output1_data[output1_dims_count]; float output2_data[output2_dims_count]; tflite::testing::TestSplitTwoOutputsFloat( {4, 2, 2, 2, 2}, // Input shape {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, // Input values {1, 1}, // Axis shape {2}, // Axis value {4, 2, 2, 1, 2}, // Output1 shape {1, 2, 5, 6, 9, 10, 13, 14}, // Output1 values {4, 2, 2, 1, 2}, // Output2 shape {3, 4, 7, 8, 11, 12, 15, 16}, // Output2 values output1_data, output2_data); } TF_LITE_MICRO_TEST(TwoSplitFourDimensionalAxisThree) { constexpr int output1_dims_count = 8; constexpr int output2_dims_count = 8; float output1_data[output1_dims_count]; float output2_data[output2_dims_count]; tflite::testing::TestSplitTwoOutputsFloat( {4, 2, 2, 2, 2}, // Input shape {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, // Input values {1, 1}, // Axis shape {3}, // Axis value {4, 2, 2, 2, 1}, // Output1 shape {1, 3, 5, 7, 9, 11, 13, 15}, // Output1 values {4, 2, 2, 2, 1}, // Output2 shape {2, 4, 6, 8, 10, 12, 14, 16}, // Output2 values output1_data, output2_data); } TF_LITE_MICRO_TEST(TwoSplitFourDimensionalNegativeAxis) { constexpr int output1_dims_count = 8; constexpr int output2_dims_count = 8; float output1_data[output1_dims_count]; float output2_data[output2_dims_count]; tflite::testing::TestSplitTwoOutputsFloat( {4, 2, 2, 2, 2}, // Input shape {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, // Input values {1, 1}, // Axis shape {-4}, // Axis value {4, 1, 2, 2, 2}, // Output1 shape {1, 2, 3, 4, 5, 6, 7, 8}, // Output1 values {4, 1, 2, 2, 2}, // Output2 shape {9, 10, 11, 12, 13, 14, 15, 16}, // Output2 values output1_data, output2_data); } TF_LITE_MICRO_TEST(FourSplit) { constexpr int output1_dims_count = 1; constexpr int output2_dims_count = 1; constexpr int output3_dims_count = 1; constexpr int output4_dims_count = 1; float output1_data[output1_dims_count]; float output2_data[output2_dims_count]; float output3_data[output3_dims_count]; float output4_data[output4_dims_count]; tflite::testing::TestSplitFourOutputsFloat({1, 4}, // Input shape {1, 2, 3, 4}, // Input values {1, 1}, // Axis shape {0}, // Axis value {1, 1}, // Output1 shape {1}, // Output1 values {1, 1}, // Output2 shape {2}, // Output2 values {1, 1}, // Output3 shape {3}, // Output3 values {1, 1}, // Output4 shape {4}, // Output4 values output1_data, output2_data, output3_data, output4_data); } TF_LITE_MICRO_TEST(TwoSplitOneDimensional) { constexpr int output1_dims_count = 8; constexpr int output2_dims_count = 8; float output1_data[output1_dims_count]; float output2_data[output2_dims_count]; tflite::testing::TestSplitTwoOutputsFloat({1, 2}, // Input shape {1, 2}, // Input values {1, 1}, // Axis shape {0}, // Axis value {1, 1}, // Output1 shape {1}, // Output1 values {1, 1}, // Output2 shape {2}, // Output2 values output1_data, output2_data); } TF_LITE_MICRO_TEST(TwoSplitFourDimensionalQuantized) { constexpr int output1_dims_count = 8; constexpr int output2_dims_count = 8; uint8_t output1_data[output1_dims_count]; uint8_t output2_data[output2_dims_count]; tflite::testing::TestSplitTwoOutputsQuantized( {4, 2, 2, 2, 2}, // Input shape {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, // Input values {1, 1}, // Axis shape {0}, // Axis value {4, 1, 2, 2, 2}, // Output1 shape {1, 2, 3, 4, 5, 6, 7, 8}, // Output1 values {4, 1, 2, 2, 2}, // Output2 shape {9, 10, 11, 12, 13, 14, 15, 16}, // Output2 values output1_data, output2_data); } TF_LITE_MICRO_TEST(TwoSplitFourDimensionalQuantized32) { constexpr int output1_dims_count = 8; constexpr int output2_dims_count = 8; int32_t output1_data[output1_dims_count]; int32_t output2_data[output2_dims_count]; tflite::testing::TestSplitTwoOutputsQuantized32( {4, 2, 2, 2, 2}, // Input shape {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, // Input values {1, 1}, // Axis shape {0}, // Axis value {4, 1, 2, 2, 2}, // Output1 shape {1, 2, 3, 4, 5, 6, 7, 8}, // Output1 values {4, 1, 2, 2, 2}, // Output2 shape {9, 10, 11, 12, 13, 14, 15, 16}, // Output2 values output1_data, output2_data); } TF_LITE_MICRO_TESTS_END
42.14539
80
0.632478
[ "shape" ]
b44358106d6153b48b92e83f3d1d32b429de514e
18,606
cpp
C++
client/OAIEzsigntemplatepackage_getObject_v1_Response_mPayload.cpp
ezmaxinc/eZmax-SDK-cpp-qt5-client
70cc5ea2bccba1a7c192f88b15bee8225dbb3d01
[ "MIT" ]
null
null
null
client/OAIEzsigntemplatepackage_getObject_v1_Response_mPayload.cpp
ezmaxinc/eZmax-SDK-cpp-qt5-client
70cc5ea2bccba1a7c192f88b15bee8225dbb3d01
[ "MIT" ]
null
null
null
client/OAIEzsigntemplatepackage_getObject_v1_Response_mPayload.cpp
ezmaxinc/eZmax-SDK-cpp-qt5-client
70cc5ea2bccba1a7c192f88b15bee8225dbb3d01
[ "MIT" ]
null
null
null
/** * eZmax API Definition (Full) * This API expose all the functionnalities for the eZmax and eZsign applications. * * The version of the OpenAPI document: 1.1.7 * Contact: support-api@ezmax.ca * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ #include "OAIEzsigntemplatepackage_getObject_v1_Response_mPayload.h" #include <QDebug> #include <QJsonArray> #include <QJsonDocument> #include <QObject> #include "OAIHelpers.h" namespace OpenAPI { OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::OAIEzsigntemplatepackage_getObject_v1_Response_mPayload(QString json) { this->initializeModel(); this->fromJson(json); } OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::OAIEzsigntemplatepackage_getObject_v1_Response_mPayload() { this->initializeModel(); } OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::~OAIEzsigntemplatepackage_getObject_v1_Response_mPayload() {} void OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::initializeModel() { m_pki_ezsigntemplatepackage_id_isSet = false; m_pki_ezsigntemplatepackage_id_isValid = false; m_fki_ezsignfoldertype_id_isSet = false; m_fki_ezsignfoldertype_id_isValid = false; m_fki_language_id_isSet = false; m_fki_language_id_isValid = false; m_s_language_name_x_isSet = false; m_s_language_name_x_isValid = false; m_s_ezsigntemplatepackage_description_isSet = false; m_s_ezsigntemplatepackage_description_isValid = false; m_b_ezsigntemplatepackage_adminonly_isSet = false; m_b_ezsigntemplatepackage_adminonly_isValid = false; m_b_ezsigntemplatepackage_needvalidation_isSet = false; m_b_ezsigntemplatepackage_needvalidation_isValid = false; m_b_ezsigntemplatepackage_isactive_isSet = false; m_b_ezsigntemplatepackage_isactive_isValid = false; m_s_ezsignfoldertype_name_x_isSet = false; m_s_ezsignfoldertype_name_x_isValid = false; m_a_obj_ezsigntemplatepackagesigner_isSet = false; m_a_obj_ezsigntemplatepackagesigner_isValid = false; m_a_obj_ezsigntemplatepackagemembership_isSet = false; m_a_obj_ezsigntemplatepackagemembership_isValid = false; } void OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::fromJson(QString jsonString) { QByteArray array(jsonString.toStdString().c_str()); QJsonDocument doc = QJsonDocument::fromJson(array); QJsonObject jsonObject = doc.object(); this->fromJsonObject(jsonObject); } void OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::fromJsonObject(QJsonObject json) { m_pki_ezsigntemplatepackage_id_isValid = ::OpenAPI::fromJsonValue(pki_ezsigntemplatepackage_id, json[QString("pkiEzsigntemplatepackageID")]); m_pki_ezsigntemplatepackage_id_isSet = !json[QString("pkiEzsigntemplatepackageID")].isNull() && m_pki_ezsigntemplatepackage_id_isValid; m_fki_ezsignfoldertype_id_isValid = ::OpenAPI::fromJsonValue(fki_ezsignfoldertype_id, json[QString("fkiEzsignfoldertypeID")]); m_fki_ezsignfoldertype_id_isSet = !json[QString("fkiEzsignfoldertypeID")].isNull() && m_fki_ezsignfoldertype_id_isValid; m_fki_language_id_isValid = ::OpenAPI::fromJsonValue(fki_language_id, json[QString("fkiLanguageID")]); m_fki_language_id_isSet = !json[QString("fkiLanguageID")].isNull() && m_fki_language_id_isValid; m_s_language_name_x_isValid = ::OpenAPI::fromJsonValue(s_language_name_x, json[QString("sLanguageNameX")]); m_s_language_name_x_isSet = !json[QString("sLanguageNameX")].isNull() && m_s_language_name_x_isValid; m_s_ezsigntemplatepackage_description_isValid = ::OpenAPI::fromJsonValue(s_ezsigntemplatepackage_description, json[QString("sEzsigntemplatepackageDescription")]); m_s_ezsigntemplatepackage_description_isSet = !json[QString("sEzsigntemplatepackageDescription")].isNull() && m_s_ezsigntemplatepackage_description_isValid; m_b_ezsigntemplatepackage_adminonly_isValid = ::OpenAPI::fromJsonValue(b_ezsigntemplatepackage_adminonly, json[QString("bEzsigntemplatepackageAdminonly")]); m_b_ezsigntemplatepackage_adminonly_isSet = !json[QString("bEzsigntemplatepackageAdminonly")].isNull() && m_b_ezsigntemplatepackage_adminonly_isValid; m_b_ezsigntemplatepackage_needvalidation_isValid = ::OpenAPI::fromJsonValue(b_ezsigntemplatepackage_needvalidation, json[QString("bEzsigntemplatepackageNeedvalidation")]); m_b_ezsigntemplatepackage_needvalidation_isSet = !json[QString("bEzsigntemplatepackageNeedvalidation")].isNull() && m_b_ezsigntemplatepackage_needvalidation_isValid; m_b_ezsigntemplatepackage_isactive_isValid = ::OpenAPI::fromJsonValue(b_ezsigntemplatepackage_isactive, json[QString("bEzsigntemplatepackageIsactive")]); m_b_ezsigntemplatepackage_isactive_isSet = !json[QString("bEzsigntemplatepackageIsactive")].isNull() && m_b_ezsigntemplatepackage_isactive_isValid; m_s_ezsignfoldertype_name_x_isValid = ::OpenAPI::fromJsonValue(s_ezsignfoldertype_name_x, json[QString("sEzsignfoldertypeNameX")]); m_s_ezsignfoldertype_name_x_isSet = !json[QString("sEzsignfoldertypeNameX")].isNull() && m_s_ezsignfoldertype_name_x_isValid; m_a_obj_ezsigntemplatepackagesigner_isValid = ::OpenAPI::fromJsonValue(a_obj_ezsigntemplatepackagesigner, json[QString("a_objEzsigntemplatepackagesigner")]); m_a_obj_ezsigntemplatepackagesigner_isSet = !json[QString("a_objEzsigntemplatepackagesigner")].isNull() && m_a_obj_ezsigntemplatepackagesigner_isValid; m_a_obj_ezsigntemplatepackagemembership_isValid = ::OpenAPI::fromJsonValue(a_obj_ezsigntemplatepackagemembership, json[QString("a_objEzsigntemplatepackagemembership")]); m_a_obj_ezsigntemplatepackagemembership_isSet = !json[QString("a_objEzsigntemplatepackagemembership")].isNull() && m_a_obj_ezsigntemplatepackagemembership_isValid; } QString OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::asJson() const { QJsonObject obj = this->asJsonObject(); QJsonDocument doc(obj); QByteArray bytes = doc.toJson(); return QString(bytes); } QJsonObject OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::asJsonObject() const { QJsonObject obj; if (m_pki_ezsigntemplatepackage_id_isSet) { obj.insert(QString("pkiEzsigntemplatepackageID"), ::OpenAPI::toJsonValue(pki_ezsigntemplatepackage_id)); } if (m_fki_ezsignfoldertype_id_isSet) { obj.insert(QString("fkiEzsignfoldertypeID"), ::OpenAPI::toJsonValue(fki_ezsignfoldertype_id)); } if (m_fki_language_id_isSet) { obj.insert(QString("fkiLanguageID"), ::OpenAPI::toJsonValue(fki_language_id)); } if (m_s_language_name_x_isSet) { obj.insert(QString("sLanguageNameX"), ::OpenAPI::toJsonValue(s_language_name_x)); } if (m_s_ezsigntemplatepackage_description_isSet) { obj.insert(QString("sEzsigntemplatepackageDescription"), ::OpenAPI::toJsonValue(s_ezsigntemplatepackage_description)); } if (m_b_ezsigntemplatepackage_adminonly_isSet) { obj.insert(QString("bEzsigntemplatepackageAdminonly"), ::OpenAPI::toJsonValue(b_ezsigntemplatepackage_adminonly)); } if (m_b_ezsigntemplatepackage_needvalidation_isSet) { obj.insert(QString("bEzsigntemplatepackageNeedvalidation"), ::OpenAPI::toJsonValue(b_ezsigntemplatepackage_needvalidation)); } if (m_b_ezsigntemplatepackage_isactive_isSet) { obj.insert(QString("bEzsigntemplatepackageIsactive"), ::OpenAPI::toJsonValue(b_ezsigntemplatepackage_isactive)); } if (m_s_ezsignfoldertype_name_x_isSet) { obj.insert(QString("sEzsignfoldertypeNameX"), ::OpenAPI::toJsonValue(s_ezsignfoldertype_name_x)); } if (a_obj_ezsigntemplatepackagesigner.size() > 0) { obj.insert(QString("a_objEzsigntemplatepackagesigner"), ::OpenAPI::toJsonValue(a_obj_ezsigntemplatepackagesigner)); } if (a_obj_ezsigntemplatepackagemembership.size() > 0) { obj.insert(QString("a_objEzsigntemplatepackagemembership"), ::OpenAPI::toJsonValue(a_obj_ezsigntemplatepackagemembership)); } return obj; } qint32 OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::getPkiEzsigntemplatepackageId() const { return pki_ezsigntemplatepackage_id; } void OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::setPkiEzsigntemplatepackageId(const qint32 &pki_ezsigntemplatepackage_id) { this->pki_ezsigntemplatepackage_id = pki_ezsigntemplatepackage_id; this->m_pki_ezsigntemplatepackage_id_isSet = true; } bool OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::is_pki_ezsigntemplatepackage_id_Set() const{ return m_pki_ezsigntemplatepackage_id_isSet; } bool OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::is_pki_ezsigntemplatepackage_id_Valid() const{ return m_pki_ezsigntemplatepackage_id_isValid; } qint32 OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::getFkiEzsignfoldertypeId() const { return fki_ezsignfoldertype_id; } void OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::setFkiEzsignfoldertypeId(const qint32 &fki_ezsignfoldertype_id) { this->fki_ezsignfoldertype_id = fki_ezsignfoldertype_id; this->m_fki_ezsignfoldertype_id_isSet = true; } bool OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::is_fki_ezsignfoldertype_id_Set() const{ return m_fki_ezsignfoldertype_id_isSet; } bool OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::is_fki_ezsignfoldertype_id_Valid() const{ return m_fki_ezsignfoldertype_id_isValid; } qint32 OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::getFkiLanguageId() const { return fki_language_id; } void OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::setFkiLanguageId(const qint32 &fki_language_id) { this->fki_language_id = fki_language_id; this->m_fki_language_id_isSet = true; } bool OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::is_fki_language_id_Set() const{ return m_fki_language_id_isSet; } bool OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::is_fki_language_id_Valid() const{ return m_fki_language_id_isValid; } QString OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::getSLanguageNameX() const { return s_language_name_x; } void OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::setSLanguageNameX(const QString &s_language_name_x) { this->s_language_name_x = s_language_name_x; this->m_s_language_name_x_isSet = true; } bool OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::is_s_language_name_x_Set() const{ return m_s_language_name_x_isSet; } bool OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::is_s_language_name_x_Valid() const{ return m_s_language_name_x_isValid; } QString OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::getSEzsigntemplatepackageDescription() const { return s_ezsigntemplatepackage_description; } void OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::setSEzsigntemplatepackageDescription(const QString &s_ezsigntemplatepackage_description) { this->s_ezsigntemplatepackage_description = s_ezsigntemplatepackage_description; this->m_s_ezsigntemplatepackage_description_isSet = true; } bool OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::is_s_ezsigntemplatepackage_description_Set() const{ return m_s_ezsigntemplatepackage_description_isSet; } bool OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::is_s_ezsigntemplatepackage_description_Valid() const{ return m_s_ezsigntemplatepackage_description_isValid; } bool OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::isBEzsigntemplatepackageAdminonly() const { return b_ezsigntemplatepackage_adminonly; } void OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::setBEzsigntemplatepackageAdminonly(const bool &b_ezsigntemplatepackage_adminonly) { this->b_ezsigntemplatepackage_adminonly = b_ezsigntemplatepackage_adminonly; this->m_b_ezsigntemplatepackage_adminonly_isSet = true; } bool OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::is_b_ezsigntemplatepackage_adminonly_Set() const{ return m_b_ezsigntemplatepackage_adminonly_isSet; } bool OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::is_b_ezsigntemplatepackage_adminonly_Valid() const{ return m_b_ezsigntemplatepackage_adminonly_isValid; } bool OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::isBEzsigntemplatepackageNeedvalidation() const { return b_ezsigntemplatepackage_needvalidation; } void OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::setBEzsigntemplatepackageNeedvalidation(const bool &b_ezsigntemplatepackage_needvalidation) { this->b_ezsigntemplatepackage_needvalidation = b_ezsigntemplatepackage_needvalidation; this->m_b_ezsigntemplatepackage_needvalidation_isSet = true; } bool OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::is_b_ezsigntemplatepackage_needvalidation_Set() const{ return m_b_ezsigntemplatepackage_needvalidation_isSet; } bool OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::is_b_ezsigntemplatepackage_needvalidation_Valid() const{ return m_b_ezsigntemplatepackage_needvalidation_isValid; } bool OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::isBEzsigntemplatepackageIsactive() const { return b_ezsigntemplatepackage_isactive; } void OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::setBEzsigntemplatepackageIsactive(const bool &b_ezsigntemplatepackage_isactive) { this->b_ezsigntemplatepackage_isactive = b_ezsigntemplatepackage_isactive; this->m_b_ezsigntemplatepackage_isactive_isSet = true; } bool OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::is_b_ezsigntemplatepackage_isactive_Set() const{ return m_b_ezsigntemplatepackage_isactive_isSet; } bool OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::is_b_ezsigntemplatepackage_isactive_Valid() const{ return m_b_ezsigntemplatepackage_isactive_isValid; } QString OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::getSEzsignfoldertypeNameX() const { return s_ezsignfoldertype_name_x; } void OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::setSEzsignfoldertypeNameX(const QString &s_ezsignfoldertype_name_x) { this->s_ezsignfoldertype_name_x = s_ezsignfoldertype_name_x; this->m_s_ezsignfoldertype_name_x_isSet = true; } bool OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::is_s_ezsignfoldertype_name_x_Set() const{ return m_s_ezsignfoldertype_name_x_isSet; } bool OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::is_s_ezsignfoldertype_name_x_Valid() const{ return m_s_ezsignfoldertype_name_x_isValid; } QList<OAIEzsigntemplatepackagesigner_ResponseCompound> OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::getAObjEzsigntemplatepackagesigner() const { return a_obj_ezsigntemplatepackagesigner; } void OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::setAObjEzsigntemplatepackagesigner(const QList<OAIEzsigntemplatepackagesigner_ResponseCompound> &a_obj_ezsigntemplatepackagesigner) { this->a_obj_ezsigntemplatepackagesigner = a_obj_ezsigntemplatepackagesigner; this->m_a_obj_ezsigntemplatepackagesigner_isSet = true; } bool OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::is_a_obj_ezsigntemplatepackagesigner_Set() const{ return m_a_obj_ezsigntemplatepackagesigner_isSet; } bool OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::is_a_obj_ezsigntemplatepackagesigner_Valid() const{ return m_a_obj_ezsigntemplatepackagesigner_isValid; } QList<OAIEzsigntemplatepackagemembership_ResponseCompound> OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::getAObjEzsigntemplatepackagemembership() const { return a_obj_ezsigntemplatepackagemembership; } void OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::setAObjEzsigntemplatepackagemembership(const QList<OAIEzsigntemplatepackagemembership_ResponseCompound> &a_obj_ezsigntemplatepackagemembership) { this->a_obj_ezsigntemplatepackagemembership = a_obj_ezsigntemplatepackagemembership; this->m_a_obj_ezsigntemplatepackagemembership_isSet = true; } bool OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::is_a_obj_ezsigntemplatepackagemembership_Set() const{ return m_a_obj_ezsigntemplatepackagemembership_isSet; } bool OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::is_a_obj_ezsigntemplatepackagemembership_Valid() const{ return m_a_obj_ezsigntemplatepackagemembership_isValid; } bool OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::isSet() const { bool isObjectUpdated = false; do { if (m_pki_ezsigntemplatepackage_id_isSet) { isObjectUpdated = true; break; } if (m_fki_ezsignfoldertype_id_isSet) { isObjectUpdated = true; break; } if (m_fki_language_id_isSet) { isObjectUpdated = true; break; } if (m_s_language_name_x_isSet) { isObjectUpdated = true; break; } if (m_s_ezsigntemplatepackage_description_isSet) { isObjectUpdated = true; break; } if (m_b_ezsigntemplatepackage_adminonly_isSet) { isObjectUpdated = true; break; } if (m_b_ezsigntemplatepackage_needvalidation_isSet) { isObjectUpdated = true; break; } if (m_b_ezsigntemplatepackage_isactive_isSet) { isObjectUpdated = true; break; } if (m_s_ezsignfoldertype_name_x_isSet) { isObjectUpdated = true; break; } if (a_obj_ezsigntemplatepackagesigner.size() > 0) { isObjectUpdated = true; break; } if (a_obj_ezsigntemplatepackagemembership.size() > 0) { isObjectUpdated = true; break; } } while (false); return isObjectUpdated; } bool OAIEzsigntemplatepackage_getObject_v1_Response_mPayload::isValid() const { // only required properties are required for the object to be considered valid return m_pki_ezsigntemplatepackage_id_isValid && m_fki_ezsignfoldertype_id_isValid && m_fki_language_id_isValid && m_s_language_name_x_isValid && m_s_ezsigntemplatepackage_description_isValid && m_b_ezsigntemplatepackage_adminonly_isValid && m_b_ezsigntemplatepackage_needvalidation_isValid && m_b_ezsigntemplatepackage_isactive_isValid && m_s_ezsignfoldertype_name_x_isValid && m_a_obj_ezsigntemplatepackagesigner_isValid && m_a_obj_ezsigntemplatepackagemembership_isValid && true; } } // namespace OpenAPI
46.283582
486
0.821348
[ "object" ]
b444c66baa6c2f7004ebcfd5be41964d5259d716
7,282
hpp
C++
planner/FD/src/search/ext/boost/config/compiler/intel.hpp
karthikv792/PlanningAssistance
5693c844e9067591ea1414ee9586bcd2dfff6f51
[ "MIT" ]
33
2015-04-15T16:58:00.000Z
2021-06-06T13:58:14.000Z
planner/FD/src/search/ext/boost/config/compiler/intel.hpp
karthikv792/PlanningAssistance
5693c844e9067591ea1414ee9586bcd2dfff6f51
[ "MIT" ]
9
2020-09-03T18:58:53.000Z
2020-10-14T11:42:12.000Z
planners/PRP/src/search/ext/boost/config/compiler/intel.hpp
lslll0302/Eval-of-FOND-planners-
7611a02118f11b06533144c5e034f7938fb90068
[ "zlib-acknowledgement", "CNRI-Python", "OML", "Linux-OpenIB" ]
6
2015-05-07T14:41:53.000Z
2022-01-27T12:19:58.000Z
// (C) Copyright John Maddock 2001-8. // (C) Copyright Peter Dimov 2001. // (C) Copyright Jens Maurer 2001. // (C) Copyright David Abrahams 2002 - 2003. // (C) Copyright Aleksey Gurtovoy 2002 - 2003. // (C) Copyright Guillaume Melquiond 2002 - 2003. // (C) Copyright Beman Dawes 2003. // (C) Copyright Martin Wille 2003. // Use, modification and distribution are subject to 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) // See http://www.boost.org for most recent version. // Intel compiler setup: #include "boost/config/compiler/common_edg.hpp" #if defined(__INTEL_COMPILER) # define BOOST_INTEL_CXX_VERSION __INTEL_COMPILER #elif defined(__ICL) # define BOOST_INTEL_CXX_VERSION __ICL #elif defined(__ICC) # define BOOST_INTEL_CXX_VERSION __ICC #elif defined(__ECC) # define BOOST_INTEL_CXX_VERSION __ECC #endif #define BOOST_COMPILER "Intel C++ version " BOOST_STRINGIZE(BOOST_INTEL_CXX_VERSION) #define BOOST_INTEL BOOST_INTEL_CXX_VERSION #if defined(_WIN32) || defined(_WIN64) # define BOOST_INTEL_WIN BOOST_INTEL #else # define BOOST_INTEL_LINUX BOOST_INTEL #endif #if (BOOST_INTEL_CXX_VERSION <= 500) && defined(_MSC_VER) # define BOOST_NO_EXPLICIT_FUNCTION_TEMPLATE_ARGUMENTS # define BOOST_NO_TEMPLATE_TEMPLATES #endif #if (BOOST_INTEL_CXX_VERSION <= 600) # if defined(_MSC_VER) && (_MSC_VER <= 1300) // added check for <= VC 7 (Peter Dimov) // Boost libraries assume strong standard conformance unless otherwise // indicated by a config macro. As configured by Intel, the EDG front-end // requires certain compiler options be set to achieve that strong conformance. // Particularly /Qoption,c,--arg_dep_lookup (reported by Kirk Klobe & Thomas Witt) // and /Zc:wchar_t,forScope. See boost-root/tools/build/intel-win32-tools.jam for // details as they apply to particular versions of the compiler. When the // compiler does not predefine a macro indicating if an option has been set, // this config file simply assumes the option has been set. // Thus BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP will not be defined, even if // the compiler option is not enabled. # define BOOST_NO_SWPRINTF # endif // Void returns, 64 bit integrals don't work when emulating VC 6 (Peter Dimov) # if defined(_MSC_VER) && (_MSC_VER <= 1200) # define BOOST_NO_VOID_RETURNS # define BOOST_NO_INTEGRAL_INT64_T # endif #endif #if (BOOST_INTEL_CXX_VERSION <= 710) && defined(_WIN32) # define BOOST_NO_POINTER_TO_MEMBER_TEMPLATE_PARAMETERS #endif // See http://aspn.activestate.com/ASPN/Mail/Message/boost/1614864 #if BOOST_INTEL_CXX_VERSION < 600 # define BOOST_NO_INTRINSIC_WCHAR_T #else // We should test the macro _WCHAR_T_DEFINED to check if the compiler // supports wchar_t natively. *BUT* there is a problem here: the standard // headers define this macro if they typedef wchar_t. Anyway, we're lucky // because they define it without a value, while Intel C++ defines it // to 1. So we can check its value to see if the macro was defined natively // or not. // Under UNIX, the situation is exactly the same, but the macro _WCHAR_T // is used instead. # if ((_WCHAR_T_DEFINED + 0) == 0) && ((_WCHAR_T + 0) == 0) # define BOOST_NO_INTRINSIC_WCHAR_T # endif #endif #if defined(__GNUC__) && !defined(BOOST_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL) // // Figure out when Intel is emulating this gcc bug // (All Intel versions prior to 9.0.26, and versions // later than that if they are set up to emulate gcc 3.2 // or earlier): // # if ((__GNUC__ == 3) && (__GNUC_MINOR__ <= 2)) || (BOOST_INTEL < 900) || (__INTEL_COMPILER_BUILD_DATE < 20050912) # define BOOST_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL # endif #endif #if (defined(__GNUC__) && (__GNUC__ < 4)) || defined(_WIN32) || (BOOST_INTEL_CXX_VERSION <= 1110) // GCC or VC emulation: #define BOOST_NO_TWO_PHASE_NAME_LOOKUP #endif // // Verify that we have actually got BOOST_NO_INTRINSIC_WCHAR_T // set correctly, if we don't do this now, we will get errors later // in type_traits code among other things, getting this correct // for the Intel compiler is actually remarkably fragile and tricky: // #if defined(BOOST_NO_INTRINSIC_WCHAR_T) #include <cwchar> template< typename T > struct assert_no_intrinsic_wchar_t; template<> struct assert_no_intrinsic_wchar_t<wchar_t> { typedef void type; }; // if you see an error here then you need to unset BOOST_NO_INTRINSIC_WCHAR_T // where it is defined above: typedef assert_no_intrinsic_wchar_t<unsigned short>::type assert_no_intrinsic_wchar_t_; #else template< typename T > struct assert_intrinsic_wchar_t; template<> struct assert_intrinsic_wchar_t<wchar_t> {}; // if you see an error here then define BOOST_NO_INTRINSIC_WCHAR_T on the command line: template<> struct assert_intrinsic_wchar_t<unsigned short> {}; #endif #if _MSC_VER+0 >= 1000 # if _MSC_VER >= 1200 # define BOOST_HAS_MS_INT64 # endif # define BOOST_NO_SWPRINTF # define BOOST_NO_TWO_PHASE_NAME_LOOKUP #elif defined(_WIN32) # define BOOST_DISABLE_WIN32 #endif // I checked version 6.0 build 020312Z, it implements the NRVO. // Correct this as you find out which version of the compiler // implemented the NRVO first. (Daniel Frey) #if (BOOST_INTEL_CXX_VERSION >= 600) # define BOOST_HAS_NRVO #endif // // versions check: // we don't support Intel prior to version 5.0: #if BOOST_INTEL_CXX_VERSION < 500 # error "Compiler not supported or configured - please reconfigure" #endif // Intel on MacOS requires #if defined(__APPLE__) && defined(__INTEL_COMPILER) # define BOOST_NO_TWO_PHASE_NAME_LOOKUP #endif // Intel on Altix Itanium #if defined(__itanium__) && defined(__INTEL_COMPILER) # define BOOST_NO_TWO_PHASE_NAME_LOOKUP #endif // // An attempt to value-initialize a pointer-to-member may trigger an // internal error on Intel <= 11.1 (last checked version), as was // reported by John Maddock, Intel support issue 589832, May 2010. // Moreover, according to test results from Huang-Vista-x86_32_intel, // intel-vc9-win-11.1 may leave a non-POD array uninitialized, in some // cases when it should be value-initialized. // (Niels Dekker, LKEB, May 2010) #if defined(__INTEL_COMPILER) # if __INTEL_COMPILER <= 1110 # define BOOST_NO_COMPLETE_VALUE_INITIALIZATION # endif #endif // // Dynamic shared object (DSO) and dynamic-link library (DLL) support // #if defined(__GNUC__) && (__GNUC__ >= 4) # define BOOST_SYMBOL_EXPORT __attribute__((visibility("default"))) # define BOOST_SYMBOL_IMPORT # define BOOST_SYMBOL_VISIBLE __attribute__((visibility("default"))) #endif // // last known and checked version: #if (BOOST_INTEL_CXX_VERSION > 1110) # if defined(BOOST_ASSERT_CONFIG) # error "Unknown compiler version - please run the configure tests and report the results" # elif defined(_MSC_VER) // // We don't emit this warning any more, since we have so few // defect macros set anyway (just the one). // //# pragma message("Unknown compiler version - please run the configure tests and report the results") # endif #endif
36.964467
116
0.738396
[ "object" ]
b4527203c0da4f771030d45639fa2732a73048d8
6,136
cc
C++
frc971/wpilib/ahal/Encoder.cc
Ewpratten/frc_971_mirror
3a8a0c4359f284d29547962c2b4c43d290d8065c
[ "BSD-2-Clause" ]
39
2021-06-18T03:22:30.000Z
2022-03-21T15:23:43.000Z
frc971/wpilib/ahal/Encoder.cc
Ewpratten/frc_971_mirror
3a8a0c4359f284d29547962c2b4c43d290d8065c
[ "BSD-2-Clause" ]
10
2021-06-18T03:22:19.000Z
2022-03-18T22:14:15.000Z
frc971/wpilib/ahal/Encoder.cc
Ewpratten/frc_971_mirror
3a8a0c4359f284d29547962c2b4c43d290d8065c
[ "BSD-2-Clause" ]
4
2021-08-19T19:20:04.000Z
2022-03-08T07:33:18.000Z
/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2008-2017. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #include "frc971/wpilib/ahal/Encoder.h" #include "hal/HAL.h" #include "frc971/wpilib/ahal/DigitalInput.h" using namespace frc; #define HAL_FATAL_WITH_STATUS(status) /** * Common initialization code for Encoders. * * This code allocates resources for Encoders and is common to all constructors. * * The counter will start counting immediately. * * @param reverseDirection If true, counts down instead of up (this is all * relative) * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X * decoding. If 4X is selected, then an encoder FPGA * object is used and the returned counts will be 4x * the encoder spec'd value since all rising and * falling edges are counted. If 1X or 2X are selected * then a counter object will be used and the returned * value will either exactly match the spec'd count or * be double (2x) the spec'd count. */ void Encoder::InitEncoder(bool reverseDirection, EncodingType encodingType) { int32_t status = 0; m_encoder = HAL_InitializeEncoder( m_aSource->GetPortHandleForRouting(), (HAL_AnalogTriggerType)m_aSource->GetAnalogTriggerTypeForRouting(), m_bSource->GetPortHandleForRouting(), (HAL_AnalogTriggerType)m_bSource->GetAnalogTriggerTypeForRouting(), reverseDirection, (HAL_EncoderEncodingType)encodingType, &status); HAL_FATAL_WITH_STATUS(status); HAL_Report(HALUsageReporting::kResourceType_Encoder, GetFPGAIndex(), encodingType); } /** * Encoder constructor. * * Construct a Encoder given a and b channels. * * The counter will start counting immediately. * * @param aChannel The a channel DIO channel. 0-9 are on-board, 10-25 * are on the MXP port * @param bChannel The b channel DIO channel. 0-9 are on-board, 10-25 * are on the MXP port * @param reverseDirection represents the orientation of the encoder and * inverts the output values if necessary so forward * represents positive values. * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X * decoding. If 4X is selected, then an encoder FPGA * object is used and the returned counts will be 4x * the encoder spec'd value since all rising and * falling edges are counted. If 1X or 2X are selected * then a counter object will be used and the returned * value will either exactly match the spec'd count or * be double (2x) the spec'd count. */ Encoder::Encoder(int aChannel, int bChannel, bool reverseDirection, EncodingType encodingType) { m_aSource = std::make_shared<DigitalInput>(aChannel); m_bSource = std::make_shared<DigitalInput>(bChannel); InitEncoder(reverseDirection, encodingType); } /** * Free the resources for an Encoder. * * Frees the FPGA resources associated with an Encoder. */ Encoder::~Encoder() { int32_t status = 0; HAL_FreeEncoder(m_encoder, &status); HAL_FATAL_WITH_STATUS(status); } /** * The encoding scale factor 1x, 2x, or 4x, per the requested encodingType. * * Used to divide raw edge counts down to spec'd counts. */ int Encoder::GetEncodingScale() const { int32_t status = 0; int val = HAL_GetEncoderEncodingScale(m_encoder, &status); wpi_setErrorWithContext(status, HAL_GetErrorMessage(status)); return val; } /** * Gets the raw value from the encoder. * * The raw value is the actual count unscaled by the 1x, 2x, or 4x scale * factor. * * @return Current raw count from the encoder */ int Encoder::GetRaw() const { int32_t status = 0; int value = HAL_GetEncoderRaw(m_encoder, &status); HAL_FATAL_WITH_STATUS(status); return value; } /** * Returns the period of the most recent pulse. * * Returns the period of the most recent Encoder pulse in seconds. * This method compensates for the decoding type. * * @deprecated Use GetRate() in favor of this method. This returns unscaled * periods and GetRate() scales using value from * SetDistancePerPulse(). * * @return Period in seconds of the most recent pulse. */ double Encoder::GetPeriod() const { int32_t status = 0; double value = HAL_GetEncoderPeriod(m_encoder, &status); HAL_FATAL_WITH_STATUS(status); return value; } /** * Sets the maximum period for stopped detection. * * Sets the value that represents the maximum period of the Encoder before it * will assume that the attached device is stopped. This timeout allows users * to determine if the wheels or other shaft has stopped rotating. * This method compensates for the decoding type. * * @deprecated Use SetMinRate() in favor of this method. This takes unscaled * periods and SetMinRate() scales using value from * SetDistancePerPulse(). * * @param maxPeriod The maximum time between rising and falling edges before * the FPGA will report the device stopped. This is expressed * in seconds. */ void Encoder::SetMaxPeriod(double maxPeriod) { int32_t status = 0; HAL_SetEncoderMaxPeriod(m_encoder, maxPeriod, &status); HAL_FATAL_WITH_STATUS(status); } int Encoder::GetFPGAIndex() const { int32_t status = 0; int val = HAL_GetEncoderFPGAIndex(m_encoder, &status); HAL_FATAL_WITH_STATUS(status); return val; }
37.644172
80
0.640319
[ "object" ]
b4555e0829799692fd646071f5163e9db47c52a3
3,884
cpp
C++
gui/qt/toolwidgets/pickwidget.cpp
hein09/vipster
b92302bf2bb8b8941e239ce8cbc7209e1e615b0b
[ "BSD-2-Clause" ]
6
2015-12-02T15:33:27.000Z
2017-07-28T17:46:51.000Z
gui/qt/toolwidgets/pickwidget.cpp
hein09/vipster
b92302bf2bb8b8941e239ce8cbc7209e1e615b0b
[ "BSD-2-Clause" ]
3
2018-02-04T16:11:19.000Z
2018-03-16T16:23:29.000Z
gui/qt/toolwidgets/pickwidget.cpp
hein09/vipster
b92302bf2bb8b8941e239ce8cbc7209e1e615b0b
[ "BSD-2-Clause" ]
1
2017-07-05T11:44:55.000Z
2017-07-05T11:44:55.000Z
#include "../mainwindow.h" #include "pickwidget.h" #include "ui_pickwidget.h" using namespace Vipster; PickWidget::PickWidget(QWidget *parent) : BaseWidget(parent), ui(new Ui::PickWidget) { ui->setupUi(this); } PickWidget::~PickWidget() { delete ui; } inline void printDist(QPlainTextEdit& text, QString idx1, QString idx2, double dist) { QString tmp = "Dist " + idx1 + '-' + idx2 + ": " + QLocale::system().toString(dist) + " Å"; text.appendPlainText(tmp); } inline void printAngle(QPlainTextEdit& text, QString idx1, QString idx2, QString idx3, double ang) { QString tmp = "Angle " + idx1 + '-' + idx2 + '-' + idx3 + ": " + QString::number(ang) + "°"; text.appendPlainText(tmp); } inline void printDihed(QPlainTextEdit& text, QString idx1, QString idx2, QString idx3, QString idx4, double dihed) { QString tmp = "Dihed " + idx1 + '-' + idx2 + '-' + idx3 + '-' + idx4 + ": " + QString::number(dihed) + "°"; text.appendPlainText(tmp); } void PickWidget::updateWidget(GUI::change_t change) { if((change & (GUI::Change::atoms|GUI::Change::cell|GUI::Change::selection)) == 0u){ return; } const auto& curSel = master->curSel->asFmt(AtomFmt::Angstrom); auto& text = *ui->PickText; text.setPlainText("Atoms:"); const size_t nat = curSel.getNat(); std::vector<QString> names; std::map<size_t, int> count; for(auto it = curSel.cbegin(); it != curSel.cend() ;++it){ names.push_back(QString::number(it->idx)+QString{count[it->idx]++,'\''}); const SizeVec& off = it->off; if(off != SizeVec{}){ text.appendPlainText(names.back()+'('+ QString::fromStdString(it->name)+") <"+ QString::number(off[0])+','+ QString::number(off[1])+','+ QString::number(off[2])+'>'); }else{ text.appendPlainText(names.back()+'('+ QString::fromStdString(it->name)+')'); } } switch(nat){ case 2: text.appendPlainText(QString{"Distance %1-%2: %3"} .arg(names[0]) .arg(names[1]) .arg(Vec_length(curSel[0].coord - curSel[1].coord))); break; case 3: { auto diff01 = curSel[0].coord - curSel[1].coord; auto diff21 = curSel[2].coord - curSel[1].coord; auto dist01 = Vec_length(diff01); auto dist21 = Vec_length(diff21); auto ang012 = (std::acos(Vec_dot(diff01, diff21) / (dist01 * dist21))) * rad2deg; text.appendPlainText(QString{"Angle %1-%2-%3: %4"} .arg(names[0]) .arg(names[1]) .arg(names[2]) .arg(ang012)); break; } case 4: { auto diff01 = curSel[0].coord - curSel[1].coord; auto diff21 = curSel[2].coord - curSel[1].coord; auto cross012 = Vec_cross(diff01, diff21); auto len012 = Vec_length(cross012); auto diff23 = curSel[2].coord - curSel[3].coord; auto cross123 = Vec_cross(diff21, diff23); auto len123 = Vec_length(cross123); auto dihed0123 = (std::acos(Vec_dot(cross012, cross123) / (len012 * len123))) * rad2deg; text.appendPlainText(QString{"Dihedral %1-%2-%3-%4: %5"} .arg(names[0]) .arg(names[1]) .arg(names[2]) .arg(names[3]) .arg(dihed0123)); break; } default: break; } }
34.070175
92
0.497168
[ "vector" ]
b455bb5804671474b6b03a63c2553fdb895b7a78
6,620
cpp
C++
dilithium_ntt.cpp
GerHobbelt/cryptopp
138a293696d48f26feb5f27426baa5a7e797524b
[ "BSL-1.0" ]
null
null
null
dilithium_ntt.cpp
GerHobbelt/cryptopp
138a293696d48f26feb5f27426baa5a7e797524b
[ "BSL-1.0" ]
null
null
null
dilithium_ntt.cpp
GerHobbelt/cryptopp
138a293696d48f26feb5f27426baa5a7e797524b
[ "BSL-1.0" ]
null
null
null
/* * Number theoretic transform for Dilithium. Adapted by Julius Hekkala * from the public-domain reference * implementation of Dilithium by the CRYSTALS team * (https://github.com/pq-crystals/dilithium) */ #include "pch.h" #include "dilithium.h" NAMESPACE_BEGIN(CryptoPP) /* Roots of unity in order needed by forward ntt */ static const word32 zetas[256] = {0, 25847, 5771523, 7861508, 237124, 7602457, 7504169, 466468, 1826347, 2353451, 8021166, 6288512, 3119733, 5495562, 3111497, 2680103, 2725464, 1024112, 7300517, 3585928, 7830929, 7260833, 2619752, 6271868, 6262231, 4520680, 6980856, 5102745, 1757237, 8360995, 4010497, 280005, 2706023, 95776, 3077325, 3530437, 6718724, 4788269, 5842901, 3915439, 4519302, 5336701, 3574422, 5512770, 3539968, 8079950, 2348700, 7841118, 6681150, 6736599, 3505694, 4558682, 3507263, 6239768, 6779997, 3699596, 811944, 531354, 954230, 3881043, 3900724, 5823537, 2071892, 5582638, 4450022, 6851714, 4702672, 5339162, 6927966, 3475950, 2176455, 6795196, 7122806, 1939314, 4296819, 7380215, 5190273, 5223087, 4747489, 126922, 3412210, 7396998, 2147896, 2715295, 5412772, 4686924, 7969390, 5903370, 7709315, 7151892, 8357436, 7072248, 7998430, 1349076, 1852771, 6949987, 5037034, 264944, 508951, 3097992, 44288, 7280319, 904516, 3958618, 4656075, 8371839, 1653064, 5130689, 2389356, 8169440, 759969, 7063561, 189548, 4827145, 3159746, 6529015, 5971092, 8202977, 1315589, 1341330, 1285669, 6795489, 7567685, 6940675, 5361315, 4499357, 4751448, 3839961, 2091667, 3407706, 2316500, 3817976, 5037939, 2244091, 5933984, 4817955, 266997, 2434439, 7144689, 3513181, 4860065, 4621053, 7183191, 5187039, 900702, 1859098, 909542, 819034, 495491, 6767243, 8337157, 7857917, 7725090, 5257975, 2031748, 3207046, 4823422, 7855319, 7611795, 4784579, 342297, 286988, 5942594, 4108315, 3437287, 5038140, 1735879, 203044, 2842341, 2691481, 5790267, 1265009, 4055324, 1247620, 2486353, 1595974, 4613401, 1250494, 2635921, 4832145, 5386378, 1869119, 1903435, 7329447, 7047359, 1237275, 5062207, 6950192, 7929317, 1312455, 3306115, 6417775, 7100756, 1917081, 5834105, 7005614, 1500165, 777191, 2235880, 3406031, 7838005, 5548557, 6709241, 6533464, 5796124, 4656147, 594136, 4603424, 6366809, 2432395, 2454455, 8215696, 1957272, 3369112, 185531, 7173032, 5196991, 162844, 1616392, 3014001, 810149, 1652634, 4686184, 6581310, 5341501, 3523897, 3866901, 269760, 2213111, 7404533, 1717735, 472078, 7953734, 1723600, 6577327, 1910376, 6712985, 7276084, 8119771, 4546524, 5441381, 6144432, 7959518, 6094090, 183443, 7403526, 1612842, 4834730, 7826001, 3919660, 8332111, 7018208, 3937738, 1400424, 7534263, 1976782}; /* Roots of unity in order needed by inverse ntt */ static const word32 zetasInv[256] = {6403635, 846154, 6979993, 4442679, 1362209, 48306, 4460757, 554416, 3545687, 6767575, 976891, 8196974, 2286327, 420899, 2235985, 2939036, 3833893, 260646, 1104333, 1667432, 6470041, 1803090, 6656817, 426683, 7908339, 6662682, 975884, 6167306, 8110657, 4513516, 4856520, 3038916, 1799107, 3694233, 6727783, 7570268, 5366416, 6764025, 8217573, 3183426, 1207385, 8194886, 5011305, 6423145, 164721, 5925962, 5948022, 2013608, 3776993, 7786281, 3724270, 2584293, 1846953, 1671176, 2831860, 542412, 4974386, 6144537, 7603226, 6880252, 1374803, 2546312, 6463336, 1279661, 1962642, 5074302, 7067962, 451100, 1430225, 3318210, 7143142, 1333058, 1050970, 6476982, 6511298, 2994039, 3548272, 5744496, 7129923, 3767016, 6784443, 5894064, 7132797, 4325093, 7115408, 2590150, 5688936, 5538076, 8177373, 6644538, 3342277, 4943130, 4272102, 2437823, 8093429, 8038120, 3595838, 768622, 525098, 3556995, 5173371, 6348669, 3122442, 655327, 522500, 43260, 1613174, 7884926, 7561383, 7470875, 6521319, 7479715, 3193378, 1197226, 3759364, 3520352, 4867236, 1235728, 5945978, 8113420, 3562462, 2446433, 6136326, 3342478, 4562441, 6063917, 4972711, 6288750, 4540456, 3628969, 3881060, 3019102, 1439742, 812732, 1584928, 7094748, 7039087, 7064828, 177440, 2409325, 1851402, 5220671, 3553272, 8190869, 1316856, 7620448, 210977, 5991061, 3249728, 6727353, 8578, 3724342, 4421799, 7475901, 1100098, 8336129, 5282425, 7871466, 8115473, 3343383, 1430430, 6527646, 7031341, 381987, 1308169, 22981, 1228525, 671102, 2477047, 411027, 3693493, 2967645, 5665122, 6232521, 983419, 4968207, 8253495, 3632928, 3157330, 3190144, 1000202, 4083598, 6441103, 1257611, 1585221, 6203962, 4904467, 1452451, 3041255, 3677745, 1528703, 3930395, 2797779, 6308525, 2556880, 4479693, 4499374, 7426187, 7849063, 7568473, 4680821, 1600420, 2140649, 4873154, 3821735, 4874723, 1643818, 1699267, 539299, 6031717, 300467, 4840449, 2867647, 4805995, 3043716, 3861115, 4464978, 2537516, 3592148, 1661693, 4849980, 5303092, 8284641, 5674394, 8100412, 4369920, 19422, 6623180, 3277672, 1399561, 3859737, 2118186, 2108549, 5760665, 1119584, 549488, 4794489, 1079900, 7356305, 5654953, 5700314, 5268920, 2884855, 5260684, 2091905, 359251, 6026966, 6554070, 7913949, 876248, 777960, 8143293, 518909, 2608894, 8354570}; /* * Forward NTT, in-place. No modular reduction is performed after * additions or subtractions. If input coefficients are below 2*mQ, * then output coefficients are below 18*mQ. * Output vector is in bitreversed order. * * Arguments: - word32 *p: pointer to input/output coefficient array with the lenght of mN */ void Dilithium::Ntt(word32 *p) { word32 len, start, j, k; word32 zeta, t; k = 1; for(len = 128; len > 0; len >>= 1) { for(start = 0; start < mN; start = j + len) { zeta = zetas[k++]; for(j = start; j < start + len; ++j) { t = MontgomeryReduce((word64)zeta * p[j + len]); p[j + len] = p[j] + 2*mQ - t; p[j] = p[j] + t; } } } } /* * Inverse NTT and multiplication by Montgomery factor 2^32. * In-place. No modular reductions after additions or * subtractions. Input coefficient need to be smaller than 2*mQ. * Output coefficient are smaller than 2*mQ. * * Arguments: - word32 *p: pointer to input/output coefficient array with length of mN */ void Dilithium::InvNttToMont(word32 *p) { word32 start, len, j, k; word32 t, zeta; const word32 f = (((word64)mMont*mMont % mQ) * (mQ-1) % mQ) * ((mQ-1) >> 8) % mQ; k = 0; for(len = 1; len < mN; len <<= 1) { for(start = 0; start < mN; start = j + len) { zeta = zetasInv[k++]; for(j = start; j < start + len; ++j) { t = p[j]; p[j] = t + p[j + len]; p[j + len] = t + 256*mQ - p[j + len]; p[j + len] = MontgomeryReduce((word64)zeta * p[j + len]); } } } for(j = 0; j < mN; ++j) { p[j] = MontgomeryReduce((word64)f * p[j]); } } NAMESPACE_END
87.105263
2,298
0.721148
[ "vector", "transform" ]
b45b57c73c8f0b681e222258dc6fb5654ed7363b
4,043
cpp
C++
gmsh/Geo/gmshSurface.cpp
Poofee/fastFEM
14eb626df973e2123604041451912c867ab7188c
[ "MIT" ]
4
2019-05-06T09:35:08.000Z
2021-05-14T16:26:45.000Z
gmsh/Geo/gmshSurface.cpp
Poofee/fastFEM
14eb626df973e2123604041451912c867ab7188c
[ "MIT" ]
null
null
null
gmsh/Geo/gmshSurface.cpp
Poofee/fastFEM
14eb626df973e2123604041451912c867ab7188c
[ "MIT" ]
1
2019-06-28T09:23:43.000Z
2019-06-28T09:23:43.000Z
// Gmsh - Copyright (C) 1997-2019 C. Geuzaine, J.-F. Remacle // // See the LICENSE.txt file for license information. Please report all // issues on https://gitlab.onelab.info/gmsh/gmsh/issues. #include "GmshConfig.h" #include "GmshMessage.h" #include "gmshSurface.h" #include "mathEvaluator.h" std::map<int, gmshSurface *> gmshSurface::allGmshSurfaces; SPoint2 gmshSurface::parFromPoint(double x, double y, double z) { Msg::Error("Parametric coordinate computation not implemented for this type " "of surface"); return SPoint2(); } SVector3 gmshSurface::normal(const SPoint2 &param) const { Msg::Error("Normal computation not implemented for this type of surface"); return SVector3(); } Pair<SVector3, SVector3> gmshSurface::firstDer(const SPoint2 &param) { Msg::Error("First derivative not implemented for this type of surface"); return Pair<SVector3, SVector3>(); } double gmshSurface::getMetricEigenvalue(const SPoint2 &) { Msg::Error("Metric eigenvalue not implemented for this type of surface"); return 0; } gmshSurface *gmshSphere::NewSphere(int iSphere, double x, double y, double z, double r) { gmshSphere *sph = new gmshSphere(x, y, z, r); if(allGmshSurfaces.find(iSphere) != allGmshSurfaces.end()) { Msg::Error("gmshSurface %d already exists", iSphere); } allGmshSurfaces[iSphere] = sph; return sph; } gmshSurface *gmshSurface::getSurface(int iSurface) { std::map<int, gmshSurface *>::iterator it = allGmshSurfaces.find(iSurface); if(it == allGmshSurfaces.end()) { Msg::Error("gmshSurface %d does not exist", iSurface); return 0; } return it->second; } SPoint3 gmshSphere::point(double par1, double par2) const { par2 += M_PI * .5; const double x = xc + r * sin(par2) * cos(par1); const double y = yc + r * sin(par2) * sin(par1); const double z = zc - r * cos(par2); return SPoint3(x, y, z); } gmshSurface *gmshPolarSphere::NewPolarSphere(int iSphere, double x, double y, double z, double r) { gmshPolarSphere *sph = new gmshPolarSphere(x, y, z, r); if(allGmshSurfaces.find(iSphere) != allGmshSurfaces.end()) { Msg::Error("gmshSurface %d already exists", iSphere); } allGmshSurfaces[iSphere] = sph; return sph; } gmshPolarSphere::gmshPolarSphere(double x, double y, double z, double _r) : r(_r), o(x, y, z) { } SPoint3 gmshPolarSphere::point(double u, double v) const { // stereographic projection from the south pole, origin of the axis // at the center of the sphere // u=-x/(r+z) v=-y/(r+z) double rp2 = u * u + v * v; SPoint3 p(-2 * r * u / (1 + rp2), -2 * r * v / (1 + rp2), r * (1 - rp2) / (1 + rp2)); p += o; return p; } gmshSurface *gmshParametricSurface::NewParametricSurface(int iSurf, char *valX, char *valY, char *valZ) { gmshParametricSurface *sph = new gmshParametricSurface(valX, valY, valZ); if(allGmshSurfaces.find(iSurf) != allGmshSurfaces.end()) { Msg::Error("gmshSurface %d already exists", iSurf); } allGmshSurfaces[iSurf] = sph; return sph; } gmshParametricSurface::gmshParametricSurface(char *valX, char *valY, char *valZ) { std::vector<std::string> expressions(3), variables(2); expressions[0] = valX; expressions[1] = valY; expressions[2] = valZ; variables[0] = "u"; variables[1] = "v"; _f = new mathEvaluator(expressions, variables); if(expressions.empty()) { delete _f; _f = 0; } } gmshParametricSurface::~gmshParametricSurface() { if(_f) delete _f; } SPoint3 gmshParametricSurface::point(double par1, double par2) const { if(_f) { std::vector<double> values(2), res(3); values[0] = par1; values[1] = par2; if(_f->eval(values, res)) return SPoint3(res[0], res[1], res[2]); } return SPoint3(0., 0., 0.); } Range<double> gmshParametricSurface::parBounds(int i) const { Msg::Error("Parameter bounds not available for parametric surface"); return Range<double>(0., 0.); }
27.317568
80
0.657433
[ "vector" ]
b45b71e3cb79d5caeba43d0e0642f540b8b9055f
3,920
cpp
C++
aws-cpp-sdk-ec2/source/model/DisableFastSnapshotRestoreErrorItem.cpp
grujicbr/aws-sdk-cpp
bdd43c178042f09c6739645e3f6cd17822a7c35c
[ "Apache-2.0" ]
1
2020-03-11T05:36:20.000Z
2020-03-11T05:36:20.000Z
aws-cpp-sdk-ec2/source/model/DisableFastSnapshotRestoreErrorItem.cpp
novaquark/aws-sdk-cpp
a0969508545bec9ae2864c9e1e2bb9aff109f90c
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-ec2/source/model/DisableFastSnapshotRestoreErrorItem.cpp
novaquark/aws-sdk-cpp
a0969508545bec9ae2864c9e1e2bb9aff109f90c
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/ec2/model/DisableFastSnapshotRestoreErrorItem.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Utils::Xml; using namespace Aws::Utils; namespace Aws { namespace EC2 { namespace Model { DisableFastSnapshotRestoreErrorItem::DisableFastSnapshotRestoreErrorItem() : m_snapshotIdHasBeenSet(false), m_fastSnapshotRestoreStateErrorsHasBeenSet(false) { } DisableFastSnapshotRestoreErrorItem::DisableFastSnapshotRestoreErrorItem(const XmlNode& xmlNode) : m_snapshotIdHasBeenSet(false), m_fastSnapshotRestoreStateErrorsHasBeenSet(false) { *this = xmlNode; } DisableFastSnapshotRestoreErrorItem& DisableFastSnapshotRestoreErrorItem::operator =(const XmlNode& xmlNode) { XmlNode resultNode = xmlNode; if(!resultNode.IsNull()) { XmlNode snapshotIdNode = resultNode.FirstChild("snapshotId"); if(!snapshotIdNode.IsNull()) { m_snapshotId = Aws::Utils::Xml::DecodeEscapedXmlText(snapshotIdNode.GetText()); m_snapshotIdHasBeenSet = true; } XmlNode fastSnapshotRestoreStateErrorsNode = resultNode.FirstChild("fastSnapshotRestoreStateErrorSet"); if(!fastSnapshotRestoreStateErrorsNode.IsNull()) { XmlNode fastSnapshotRestoreStateErrorsMember = fastSnapshotRestoreStateErrorsNode.FirstChild("item"); while(!fastSnapshotRestoreStateErrorsMember.IsNull()) { m_fastSnapshotRestoreStateErrors.push_back(fastSnapshotRestoreStateErrorsMember); fastSnapshotRestoreStateErrorsMember = fastSnapshotRestoreStateErrorsMember.NextNode("item"); } m_fastSnapshotRestoreStateErrorsHasBeenSet = true; } } return *this; } void DisableFastSnapshotRestoreErrorItem::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const { if(m_snapshotIdHasBeenSet) { oStream << location << index << locationValue << ".SnapshotId=" << StringUtils::URLEncode(m_snapshotId.c_str()) << "&"; } if(m_fastSnapshotRestoreStateErrorsHasBeenSet) { unsigned fastSnapshotRestoreStateErrorsIdx = 1; for(auto& item : m_fastSnapshotRestoreStateErrors) { Aws::StringStream fastSnapshotRestoreStateErrorsSs; fastSnapshotRestoreStateErrorsSs << location << index << locationValue << ".FastSnapshotRestoreStateErrorSet." << fastSnapshotRestoreStateErrorsIdx++; item.OutputToStream(oStream, fastSnapshotRestoreStateErrorsSs.str().c_str()); } } } void DisableFastSnapshotRestoreErrorItem::OutputToStream(Aws::OStream& oStream, const char* location) const { if(m_snapshotIdHasBeenSet) { oStream << location << ".SnapshotId=" << StringUtils::URLEncode(m_snapshotId.c_str()) << "&"; } if(m_fastSnapshotRestoreStateErrorsHasBeenSet) { unsigned fastSnapshotRestoreStateErrorsIdx = 1; for(auto& item : m_fastSnapshotRestoreStateErrors) { Aws::StringStream fastSnapshotRestoreStateErrorsSs; fastSnapshotRestoreStateErrorsSs << location << ".FastSnapshotRestoreStateErrorSet." << fastSnapshotRestoreStateErrorsIdx++; item.OutputToStream(oStream, fastSnapshotRestoreStateErrorsSs.str().c_str()); } } } } // namespace Model } // namespace EC2 } // namespace Aws
33.793103
158
0.755102
[ "model" ]
b45d7ba7c98b64687a784c9e6071d79249463128
6,813
cpp
C++
gxruntime/gxfont.cpp
ZiYueCommentary/Blitz3D
866cce504c3b1b8592d034cf50468459f1c767ca
[ "Zlib" ]
null
null
null
gxruntime/gxfont.cpp
ZiYueCommentary/Blitz3D
866cce504c3b1b8592d034cf50468459f1c767ca
[ "Zlib" ]
null
null
null
gxruntime/gxfont.cpp
ZiYueCommentary/Blitz3D
866cce504c3b1b8592d034cf50468459f1c767ca
[ "Zlib" ]
null
null
null
#include "std.h" #include "gxfont.h" #include "gxcanvas.h" #include "gxgraphics.h" #include "gxutf8.h" #include <inttypes.h> #include <stdlib.h> #include <stdio.h> gxFont::gxFont(FT_Library ftLibrary, gxGraphics* gfx, const std::string& fn, int h) { graphics = gfx; filename = fn; height = h; FT_New_Face(ftLibrary, filename.c_str(), 0, &freeTypeFace); FT_Set_Pixel_Sizes(freeTypeFace, 0, height); glyphData.clear(); atlases.clear(); glyphHeight = height; renderAtlas('T'); std::map<int, GlyphData>::iterator it = glyphData.find('T'); if(it != glyphData.end()) { const GlyphData& gd = it->second; glyphHeight = gd.srcRect[3]; glyphRenderOffset = -gd.drawOffset[1]; } tCanvasHeight = (glyphHeight * 40) / 10; glyphRenderBaseline = (glyphHeight * 3 / 10); glyphRenderOffset += glyphRenderBaseline; tempCanvas = nullptr; } gxFont::~gxFont() { for(int i = 0; i < atlases.size(); i++) { graphics->freeCanvas(atlases[i]); } FT_Done_Face(freeTypeFace); } const int transparentPixel = 0x4A412A; const int opaquePixel = 0xffffff; void gxFont::renderAtlas(int chr) { bool needsNewAtlas = false; int startChr = chr - 1024; if(startChr < 0) { startChr = 0; } int endChr = startChr + 2048; bool* buffer = nullptr; int x = -1; int y = -1; int maxHeight = -1; for(int i = startChr; i < endChr; i++) { std::map<int, GlyphData>::iterator it = glyphData.find(i); if(it == glyphData.end()) { long glyphIndex = FT_Get_Char_Index(freeTypeFace, i); FT_Load_Glyph(freeTypeFace, (FT_UInt)glyphIndex, FT_LOAD_TARGET_MONO); if(glyphIndex != 0) { FT_Render_Glyph(freeTypeFace->glyph, FT_RENDER_MODE_MONO); unsigned char* glyphBuffer = freeTypeFace->glyph->bitmap.buffer; int glyphPitch = freeTypeFace->glyph->bitmap.pitch; int glyphWidth = freeTypeFace->glyph->bitmap.width; int glyphHeight = freeTypeFace->glyph->bitmap.rows; if(glyphWidth > 0 && glyphHeight > 0) { if(buffer == nullptr) { buffer = new bool[atlasDims * atlasDims]; for(int j = 0; j < atlasDims * atlasDims; j++) { buffer[j] = false; } x = 1; y = 1; maxHeight = 0; } if(x + glyphWidth + 1 > atlasDims - 1) { x = 1; y += maxHeight + 1; maxHeight = 0; } if(y + glyphHeight + 1 > atlasDims - 1) { needsNewAtlas = true; break; } if(glyphHeight > maxHeight) { maxHeight = glyphHeight; } int bitPitch = glyphPitch * 8; for(int j = 0; j < glyphPitch * glyphHeight; j++) { for(int k = 0; k < 8; k++) { if((j * 8 + k) % bitPitch >= glyphWidth) { continue; } int bufferPos = x + y * atlasDims; bufferPos += (j * 8 + k) % bitPitch + ((j / glyphPitch) * atlasDims); buffer[bufferPos] = (glyphBuffer[j] & (1 << (7 - k))) > 0; } } GlyphData gd; gd.atlasIndex = (int)atlases.size(); gd.horizontalAdvance = freeTypeFace->glyph->metrics.horiAdvance >> 6; gd.drawOffset[0] = -freeTypeFace->glyph->bitmap_left; gd.drawOffset[1] = freeTypeFace->glyph->bitmap_top - ((height * 10) / 14); gd.srcRect[0] = x; gd.srcRect[1] = y; gd.srcRect[2] = glyphWidth; gd.srcRect[3] = glyphHeight; if(glyphWidth > maxWidth) { maxWidth = glyphWidth; } x += glyphWidth + 1; glyphData.emplace(i, gd); } else { GlyphData gd; gd.atlasIndex = -1; gd.horizontalAdvance = freeTypeFace->glyph->metrics.horiAdvance >> 6; glyphData.emplace(i, gd); } } else { GlyphData gd; gd.atlasIndex = -1; gd.horizontalAdvance = freeTypeFace->glyph->metrics.horiAdvance >> 6; glyphData.emplace(i, gd); } } } if(buffer != nullptr) { gxCanvas* newAtlas = graphics->createCanvas(atlasDims, atlasDims, 0); newAtlas->lock(); for(int y = 0; y < atlasDims; y++) { for(int x = 0; x < atlasDims; x++) { newAtlas->setPixelFast(x, y, buffer[x + (y * atlasDims)] ? opaquePixel : transparentPixel); } } newAtlas->unlock(); newAtlas->setMask(0xffffff); newAtlas->backup(); atlases.push_back(newAtlas); delete[] buffer; } if(needsNewAtlas) { renderAtlas(chr); } } void gxFont::render(gxCanvas* dest, unsigned color_argb, int x, int y, const std::string& text) { int width = stringWidth(text); if(tempCanvas == nullptr || width > tempCanvas->getWidth()) { graphics->freeCanvas(tempCanvas); tempCanvas = graphics->createCanvas(width, tCanvasHeight, 0); tempCanvas->setMask(transparentPixel); } if((color_argb & 0xffffff) == transparentPixel) { color_argb++; } tempCanvas->setColor(transparentPixel); tempCanvas->rect(0, 0, width, tCanvasHeight, true); tempCanvas->setColor(color_argb); int t_x = 0; for(int i = 0; i < text.size();) { int codepointLen = UTF8::measureCodepoint(text[i]); int chr = UTF8::decodeCharacter(text.c_str(), i); std::map<int, GlyphData>::iterator it = glyphData.find(chr); if(it == glyphData.end()) { renderAtlas(chr); it = glyphData.find(chr); } if(it != glyphData.end()) { const GlyphData& gd = it->second; if(gd.atlasIndex >= 0) { tempCanvas->rect(t_x - gd.drawOffset[0], glyphRenderBaseline - gd.drawOffset[1], gd.srcRect[2], gd.srcRect[3], true); tempCanvas->blit(t_x - gd.drawOffset[0], glyphRenderBaseline - gd.drawOffset[1], atlases[gd.atlasIndex], gd.srcRect[0], gd.srcRect[1], gd.srcRect[2], gd.srcRect[3], false); } t_x += gd.horizontalAdvance; } i += codepointLen; } dest->blit(x, y - glyphRenderOffset, tempCanvas, 0, 0, width, tCanvasHeight, false); } int gxFont::charWidth(int chr) { std::map<int, GlyphData>::iterator it = glyphData.find(chr); if(it == glyphData.end()) { renderAtlas(chr); it = glyphData.find(chr); } return it->second.srcRect[2]; } int gxFont::charAdvance(int chr) { std::map<int, GlyphData>::iterator it = glyphData.find(chr); if(it == glyphData.end()) { renderAtlas(chr); it = glyphData.find(chr); } return it != glyphData.end() ? it->second.horizontalAdvance : 0; } int gxFont::stringWidth(const std::string& text) { int width = 0; for(int i = 0; i < text.size();) { int codepointLen = UTF8::measureCodepoint(text[i]); int chr = UTF8::decodeCharacter(text.c_str(), i); std::map<int, GlyphData>::iterator it = glyphData.find(chr); if(it == glyphData.end()) { renderAtlas(chr); it = glyphData.find(chr); } if(it != glyphData.end()) { width += it->second.horizontalAdvance; } i += codepointLen; } return width; } int gxFont::getWidth()const { return maxWidth; } int gxFont::getHeight()const { return glyphHeight; } int gxFont::getRenderOffset()const { return glyphRenderOffset; } int gxFont::getWidth(const std::string& text) { return stringWidth(text); } bool gxFont::isPrintable(int chr)const { return glyphData.find(chr) != glyphData.end(); }
26.203846
176
0.642889
[ "render" ]
b45ead27db2a17f434d329104782bd7c54092e8e
4,870
hxx
C++
Components/Metrics/PCAMetric/elxPCAMetric.hxx
eliseemond/elastix
0e8572f4a315e0a8f08b07d5947b4f3ac160b575
[ "Apache-2.0" ]
318
2017-05-22T11:39:46.000Z
2022-03-27T04:40:13.000Z
Components/Metrics/PCAMetric/elxPCAMetric.hxx
eliseemond/elastix
0e8572f4a315e0a8f08b07d5947b4f3ac160b575
[ "Apache-2.0" ]
358
2017-05-22T11:36:05.000Z
2022-03-18T15:49:10.000Z
Components/Metrics/PCAMetric/elxPCAMetric.hxx
eliseemond/elastix
0e8572f4a315e0a8f08b07d5947b4f3ac160b575
[ "Apache-2.0" ]
102
2017-05-22T11:38:44.000Z
2021-12-23T20:27:51.000Z
/*========================================================================= * * Copyright UMC Utrecht and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef elxPCAMetric_hxx #define elxPCAMetric_hxx #include "elxPCAMetric.h" #include "itkTimeProbe.h" namespace elastix { /** * ******************* Initialize *********************** */ template <class TElastix> void PCAMetric<TElastix>::Initialize(void) { itk::TimeProbe timer; timer.Start(); this->Superclass1::Initialize(); timer.Stop(); elxout << "Initialization of PCAMetric metric took: " << static_cast<long>(timer.GetMean() * 1000) << " ms." << std::endl; } // end Initialize() /** * ***************** BeforeEachResolution *********************** */ template <class TElastix> void PCAMetric<TElastix>::BeforeEachResolution(void) { /** Get the current resolution level. */ unsigned int level = (this->m_Registration->GetAsITKBaseType())->GetCurrentLevel(); unsigned int NumEigenValues = 6; this->GetConfiguration()->ReadParameter(NumEigenValues, "NumEigenValues", this->GetComponentLabel(), level, 0); this->SetNumEigenValues(NumEigenValues); /** Get and set if we want to subtract the mean from the derivative. */ bool subtractMean = false; this->GetConfiguration()->ReadParameter(subtractMean, "SubtractMean", this->GetComponentLabel(), 0, 0); this->SetSubtractMean(subtractMean); /** Get and set the number of additional samples sampled at the fixed timepoint. */ // unsigned int numAdditionalSamplesFixed = 0; // this->GetConfiguration()->ReadParameter( numAdditionalSamplesFixed, // "NumAdditionalSamplesFixed", this->GetComponentLabel(), level, 0 ); // this->SetNumAdditionalSamplesFixed( numAdditionalSamplesFixed ); /** Get and set the fixed timepoint number. */ // unsigned int reducedDimensionIndex = 0; // this->GetConfiguration()->ReadParameter( // reducedDimensionIndex, "ReducedDimensionIndex", // this->GetComponentLabel(), 0, 0 ); // this->SetReducedDimensionIndex( reducedDimensionIndex ); /** Set moving image derivative scales. */ this->SetUseMovingImageDerivativeScales(false); MovingImageDerivativeScalesType movingImageDerivativeScales; bool usescales = true; for (unsigned int i = 0; i < MovingImageDimension; ++i) { usescales = usescales && this->GetConfiguration()->ReadParameter( movingImageDerivativeScales[i], "MovingImageDerivativeScales", this->GetComponentLabel(), i, -1, true); } if (usescales) { this->SetUseMovingImageDerivativeScales(true); this->SetMovingImageDerivativeScales(movingImageDerivativeScales); elxout << "Multiplying moving image derivatives by: " << movingImageDerivativeScales << std::endl; } /** Check if this transform is a B-spline transform. */ CombinationTransformType * testPtr1 = BaseComponent::AsITKBaseType(this->GetElastix()->GetElxTransformBase()); if (testPtr1) { /** Check for B-spline transform. */ const BSplineTransformBaseType * testPtr2 = dynamic_cast<const BSplineTransformBaseType *>(testPtr1->GetCurrentTransform()); if (testPtr2) { this->SetGridSize(testPtr2->GetGridRegion().GetSize()); } else { /** Check for stack transform. */ StackTransformType * testPtr3 = dynamic_cast<StackTransformType *>(testPtr1->GetModifiableCurrentTransform()); if (testPtr3) { /** Set itk member variable. */ this->SetTransformIsStackTransform(true); if (testPtr3->GetNumberOfSubTransforms() > 0) { /** Check if subtransform is a B-spline transform. */ const ReducedDimensionBSplineTransformBaseType * testPtr4 = dynamic_cast<const ReducedDimensionBSplineTransformBaseType *>(testPtr3->GetSubTransform(0).GetPointer()); if (testPtr4) { FixedImageSizeType gridSize; gridSize.Fill(testPtr3->GetNumberOfSubTransforms()); this->SetGridSize(gridSize); } } } } } elxout << "end BeforeEachResolution" << std::endl; } // end BeforeEachResolution() } // end namespace elastix #endif // end #ifndef elxPCAMetric_hxx
35.035971
118
0.658111
[ "transform" ]
b462a8f4108e9617de5db73cbfd5842fd55f437b
7,191
cpp
C++
libnd4j/include/loops/cpu/transform/transform_bool.cpp
1m2c3t4/deeplearning4j
15991607d059282fff560d814fe05fb2df983c32
[ "Apache-2.0" ]
1
2018-12-14T02:56:28.000Z
2018-12-14T02:56:28.000Z
libnd4j/include/loops/cpu/transform/transform_bool.cpp
heronggen/deeplearning4j
4670eee4f25cef84afca2ba2e2ebf46577968308
[ "Apache-2.0" ]
null
null
null
libnd4j/include/loops/cpu/transform/transform_bool.cpp
heronggen/deeplearning4j
4670eee4f25cef84afca2ba2e2ebf46577968308
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ // // @author raver119@gmail.com // #include <op_boilerplate.h> #include <types/types.h> #include <loops/transform_bool.h> #include <loops/legacy_ops.h> using namespace simdOps; namespace functions { namespace transform { template <typename X, typename Y> void TransformBool<X, Y>::exec( int opNum, void *x, Nd4jLong *xShapeInfo, void *z, Nd4jLong *zShapeInfo, void *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { DISPATCH_BY_OPNUM_TT(exec, PARAMS(x, xShapeInfo, z, zShapeInfo, extraParams, tadShapeInfo, tadOffsets), TRANSFORM_BOOL_OPS); } template <typename X, typename Z> template<typename OpType> void _CUDA_H TransformBool<X, Z>::exec( void *vx, Nd4jLong *xShapeInfo, void *vz, Nd4jLong *zShapeInfo, void *vextraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { auto x = reinterpret_cast<X *>(vx); auto z = reinterpret_cast<Z *>(vz); auto extraParams = reinterpret_cast<X *>(vextraParams); if(OpType::requiresSpecial) { OpType::execSpecial(x, xShapeInfo, z, zShapeInfo, extraParams, tadShapeInfo, tadOffsets); return; } const auto len = shape::length(xShapeInfo); const auto xEws = shape::elementWiseStride(xShapeInfo); const auto zEws = shape::elementWiseStride(zShapeInfo); const auto xOrder = shape::order(xShapeInfo); const auto zOrder = shape::order(zShapeInfo); // loop2ArrsSame<X>(x, xShapeInfo, z, zShapeInfo, extraParams, OpType::op); if(xEws >= 1 && zEws >= 1 && xOrder == zOrder) { nd4j::OmpLaunchHelper info(len); #pragma omp parallel num_threads(info._numThreads) if (info._numThreads > 1) default(shared) { auto threadNum = omp_get_thread_num(); Nd4jLong threadOffset = info.getThreadOffset(threadNum); auto xi = x + xEws * threadOffset; auto zi = z + zEws * threadOffset; #pragma omp simd for (Nd4jLong j = 0; j < info.getItersPerThread(threadNum); j++) zi[j*zEws] = OpType::op(xi[j*xEws], extraParams); } } else { const bool xSimpe = shape::isStrideSimple(xShapeInfo); const bool zSimpe = shape::isStrideSimple(zShapeInfo); nd4j::OmpLaunchHelper info(len); if(xSimpe) { #pragma omp parallel num_threads(info._numThreads) if (info._numThreads > 1) default(shared) { auto threadNum = omp_get_thread_num(); Nd4jLong threadOffset = info.getThreadOffset(threadNum); auto xi = x + xEws * threadOffset; #pragma omp simd for (Nd4jLong i = 0; i < info.getItersPerThread(threadNum); i++) { Nd4jLong zOffset = shape::getIndexOffset(i+threadOffset, zShapeInfo, len); z[zOffset] = OpType::op(xi[i*xEws], extraParams); } } } else if(zSimpe) { #pragma omp parallel num_threads(info._numThreads) if (info._numThreads > 1) default(shared) { auto threadNum = omp_get_thread_num(); Nd4jLong threadOffset = info.getThreadOffset(threadNum); auto zi = z + zEws * threadOffset; #pragma omp simd for (Nd4jLong i = 0; i < info.getItersPerThread(threadNum); i++) { Nd4jLong xOffset = shape::getIndexOffset(i+threadOffset, xShapeInfo, len); zi[i*zEws] = OpType::op(x[xOffset], extraParams); } } } else if(shape::equalsStrict(xShapeInfo, zShapeInfo)) { #pragma omp parallel num_threads(info._numThreads) if (info._numThreads > 1) default(shared) { auto threadNum = omp_get_thread_num(); Nd4jLong threadOffset = info.getThreadOffset(threadNum); #pragma omp simd for (Nd4jLong i = 0; i < info.getItersPerThread(threadNum); i++) { Nd4jLong offset = shape::getIndexOffset(i+threadOffset, xShapeInfo, len); z[offset] = OpType::op(x[offset], extraParams); } } } else { #pragma omp parallel num_threads(info._numThreads) if (info._numThreads > 1) default(shared) { auto threadNum = omp_get_thread_num(); Nd4jLong threadOffset = info.getThreadOffset(threadNum); #pragma omp simd for (Nd4jLong i = 0; i < info.getItersPerThread(threadNum); i++) { Nd4jLong xOffset = shape::getIndexOffset(i+threadOffset, xShapeInfo, len); Nd4jLong zOffset = shape::getIndexOffset(i+threadOffset, zShapeInfo, len); z[zOffset] = OpType::op(x[xOffset], extraParams); } } } } } BUILD_DOUBLE_TEMPLATE(template class ND4J_EXPORT TransformBool, , LIBND4J_TYPES, BOOL_TYPES); } }
47.622517
144
0.47768
[ "shape", "transform" ]
b465071801bb455756220e3dc0b804b369f55af3
6,525
cc
C++
src/theia/sfm/sfm_wrapper.cc
urbste/pyTheiaSfM
814034c96b602fef1dc76ae6692278d61179ebcc
[ "BSD-3-Clause" ]
3
2021-11-10T19:50:36.000Z
2022-03-03T08:16:54.000Z
src/theia/sfm/sfm_wrapper.cc
urbste/pyTheiaSfM
814034c96b602fef1dc76ae6692278d61179ebcc
[ "BSD-3-Clause" ]
null
null
null
src/theia/sfm/sfm_wrapper.cc
urbste/pyTheiaSfM
814034c96b602fef1dc76ae6692278d61179ebcc
[ "BSD-3-Clause" ]
1
2022-03-14T10:19:04.000Z
2022-03-14T10:19:04.000Z
#include "theia/sfm/sfm_wrapper.h" #include "theia/sfm/reconstruction.h" #include "theia/sfm/twoview_info.h" #include "theia/sfm/view_graph/view_graph.h" //#include "theia/image/image.h" #include "theia/sfm/camera/camera.h" namespace theia { std::tuple<bool, TwoViewInfo, std::vector<int>> EstimateTwoViewInfoWrapper( const EstimateTwoViewInfoOptions& options, const CameraIntrinsicsPrior& intrinsics1, const CameraIntrinsicsPrior& intrinsics2, const std::vector<FeatureCorrespondence>& correspondences) { TwoViewInfo twoview_info; std::vector<int> inlier_indices; const bool success = EstimateTwoViewInfo(options, intrinsics1, intrinsics2, correspondences, &twoview_info, &inlier_indices); return std::make_tuple(success, twoview_info, inlier_indices); } Reconstruction ColorizeReconstructionWrapper(const std::string& image_directory, const int num_threads) { Reconstruction reconstruction; ColorizeReconstruction(image_directory, num_threads, &reconstruction); return reconstruction; } ViewGraph ExtractMaximallyParallelRigidSubgraphWrapper( const std::unordered_map<ViewId, Eigen::Vector3d>& orientations) { ViewGraph view_graph; ExtractMaximallyParallelRigidSubgraph(orientations, &view_graph); return view_graph; } ViewGraph FilterViewGraphCyclesByRotationWrapper( const double max_loop_error_degrees) { ViewGraph view_pairs; FilterViewGraphCyclesByRotation(max_loop_error_degrees, &view_pairs); return view_pairs; } ViewGraph FilterViewPairsFromOrientationWrapper( const std::unordered_map<ViewId, Eigen::Vector3d>& orientations, const double max_relative_rotation_difference_degrees) { ViewGraph view_pairs; FilterViewPairsFromOrientation( orientations, max_relative_rotation_difference_degrees, &view_pairs); return view_pairs; } ViewGraph FilterViewPairsFromRelativeTranslationWrapper( const FilterViewPairsFromRelativeTranslationOptions& options, const std::unordered_map<ViewId, Eigen::Vector3d>& orientations) { ViewGraph view_graph; FilterViewPairsFromRelativeTranslation(options, orientations, &view_graph); return view_graph; } std::tuple<bool, Reconstruction, RansacSummary> LocalizeViewToReconstructionWrapper( const ViewId view_to_localize, const LocalizeViewToReconstructionOptions options) { Reconstruction reconstruction; RansacSummary summary; const bool success = LocalizeViewToReconstruction( view_to_localize, options, &reconstruction, &summary); return std::make_tuple(success, reconstruction, summary); } std::tuple<bool, std::unordered_set<TrackId>> SelectGoodTracksForBundleAdjustmentAllWrapper( const Reconstruction& reconstruction, const int long_track_length_threshold, const int image_grid_cell_size_pixels, const int min_num_optimized_tracks_per_view) { std::unordered_set<TrackId> tracks_to_optimize; const bool success = SelectGoodTracksForBundleAdjustment(reconstruction, long_track_length_threshold, image_grid_cell_size_pixels, min_num_optimized_tracks_per_view, &tracks_to_optimize); return std::make_tuple(success, tracks_to_optimize); } std::tuple<bool, std::unordered_set<TrackId>> SelectGoodTracksForBundleAdjustmentWrapper( const Reconstruction& reconstruction, const std::unordered_set<ViewId>& view_ids, const int long_track_length_threshold, const int image_grid_cell_size_pixels, const int min_num_optimized_tracks_per_view) { std::unordered_set<TrackId> tracks_to_optimize; const bool success = SelectGoodTracksForBundleAdjustment(reconstruction, view_ids, long_track_length_threshold, image_grid_cell_size_pixels, min_num_optimized_tracks_per_view, &tracks_to_optimize); return std::make_tuple(success, tracks_to_optimize); } void SetCameraIntrinsicsFromPriorsWrapper(Reconstruction& reconstruction) { SetCameraIntrinsicsFromPriors(&reconstruction); } std::tuple<int, Reconstruction> SetOutlierTracksToUnestimatedWrapper( const std::unordered_set<TrackId>& tracks, const double max_inlier_reprojection_error, const double min_triangulation_angle_degrees) { Reconstruction reconstruction; int num_features_rm = SetOutlierTracksToUnestimated(tracks, max_inlier_reprojection_error, min_triangulation_angle_degrees, &reconstruction); return std::make_tuple(num_features_rm, reconstruction); } std::tuple<int, Reconstruction> SetOutlierTracksToUnestimatedAllWrapper( const double max_inlier_reprojection_error, const double min_triangulation_angle_degrees) { Reconstruction reconstruction; int num_features_rm = SetOutlierTracksToUnestimated(max_inlier_reprojection_error, min_triangulation_angle_degrees, &reconstruction); return std::make_tuple(num_features_rm, reconstruction); } // std::tuple<bool, FloatImage> UndistortImageWrapper(const Camera& // distorted_camera, // const FloatImage& distorted_image, // const Camera& undistorted_camera){ // FloatImage undistorted_image; // const bool success = UndistortImage(distorted_camera, distorted_image, // undistorted_camera,&undistorted_image); return std::make_tuple(success, // undistorted_image); //} // std::tuple<bool, Camera> UndistortCameraWrapper(const Camera& // distorted_camera){ // Camera undistorted_camera; // const bool success = UndistortCamera(distorted_camera, // &undistorted_camera); return std::make_tuple(success, undistorted_camera); //} // std::tuple<bool, Reconstruction> UndistortReconstructionWrapper(){ // Reconstruction reconstruction; // const bool success = UndistortReconstruction(&reconstruction); // return std::make_tuple(success, reconstruction); //} } // namespace theia
40.277778
80
0.702375
[ "vector" ]
b46e12b19200ff639f8e158502491b91a2f98702
22,460
cpp
C++
TTF2SDK/ModManager.cpp
Spitfire972/TTF2SDK-1
5aafa24e0e856538bbcc2372a0f42c1112c8a71c
[ "MIT" ]
null
null
null
TTF2SDK/ModManager.cpp
Spitfire972/TTF2SDK-1
5aafa24e0e856538bbcc2372a0f42c1112c8a71c
[ "MIT" ]
null
null
null
TTF2SDK/ModManager.cpp
Spitfire972/TTF2SDK-1
5aafa24e0e856538bbcc2372a0f42c1112c8a71c
[ "MIT" ]
null
null
null
#include "stdafx.h" #include <rapidjson/document.h> #include <rapidjson/filereadstream.h> #include <rapidjson/schema.h> #include <rapidjson/stringbuffer.h> #pragma warning(push) #pragma warning(disable : 4267) #include "diff_match_patch.h" #pragma warning(pop) ModManager& ModMan() { return SDK().GetModManager(); } #define WRAPPED_MEMBER(name) \ MemberWrapper<decltype(&ModManager::##name), &ModManager::##name, decltype(&ModMan), &ModMan>::Call const char* MOD_INFO_SCHEMA = R"END( { "$schema": "http://json-schema.org/draft-07/schema#", "description": "JSON schema for TTF2SDK modV1.json", "type": "object", "properties": { "Name": { "type": "string" }, "Description": { "type": "string" }, "Authors": { "type": "array", "items": { "type": "string" } }, "Contacts": { "type": "array", "items": { "type": "string" } }, "Version": { "type": "string" }, "Gamemode": { "type": "object", "properties": { "Id": { "type": "string" }, "Name": { "type": "string" }, "Description": { "type": "string" } }, "required": ["Id"] }, "CustomScripts": { "type": "array", "items": { "type": "object", "properties": { "Path": { "type": "string" }, "RunOn": { "type": "string" }, "RunBefore": { "type": "string" }, "RunAfter": { "type": "string" }, "ServerCallback": { "type": "string" }, "ClientCallback": { "type": "string" }, "IgnoreGamemode": { "type": "bool" } }, "oneOf": [{ "required": ["RunOn"] }, { "required": ["RunBefore"] }, { "required": ["RunAfter"] } ], "required": ["Path"] } } }, "required": ["Name"] } )END"; rapidjson::SchemaDocument GetModV1Schema() { rapidjson::Document d; d.Parse(MOD_INFO_SCHEMA); if (d.HasParseError()) { throw std::exception("Failed to parse ModV1 JSON schema"); } rapidjson::SchemaDocument sd(d); return sd; } rapidjson::Document GetModDocument(std::ifstream& f) { static rapidjson::SchemaDocument sd = GetModV1Schema(); rapidjson::SchemaValidator validator(sd); std::string jsonData = Util::ReadFileToString(f); rapidjson::Document d; if (d.Parse<rapidjson::kParseCommentsFlag | rapidjson::kParseTrailingCommasFlag>(jsonData.c_str(), jsonData.length()) .HasParseError()) { throw std::exception("Failed to parse mod.json - ensure it is a valid JSON file"); } if (!d.Accept(validator)) { auto logger = spdlog::get("logger"); rapidjson::StringBuffer sb; validator.GetInvalidSchemaPointer().StringifyUriFragment(sb); logger->error("Invalid schema: {}", sb.GetString()); logger->error("Invalid keyword: {}", validator.GetInvalidSchemaKeyword()); sb.Clear(); validator.GetInvalidDocumentPointer().StringifyUriFragment(sb); logger->error("Invalid document: {}", sb.GetString()); throw std::exception("mod.json was not of the correct format, see console for details"); } return d; } void CreateCustomScriptInfo(CustomScriptInfo& script, const fs::path& modFolder, const rapidjson::Value& info) { // Ensure that the path is valid // TODO: Ensure that it's all forward slashes // TODO: Ensure it does not start with a slash script.Path = info["Path"].GetString(); { fs::path fullPath = modFolder / "scripts" / "vscripts" / script.Path; std::ifstream f(fullPath); if (!f.good()) { throw std::runtime_error( fmt::format("Failed to find or read from custom script with path {}", script.Path)); } } std::string relativePath = "scripts/vscripts/" + script.Path; if (SDK().GetFSManager().FileExists(relativePath.c_str(), "GAME")) { throw std::runtime_error( fmt::format("Custom script with path {} already exists in the game files", script.Path)); } // Figure out what kind of trigger we're using if (info.HasMember("RunOn")) { script.RunTrigger = info["RunOn"].GetString(); script.TriggerType = RUN_WHEN; } else if (info.HasMember("RunAfter")) { script.RunTrigger = info["RunAfter"].GetString(); script.TriggerType = RUN_AFTER; } else if (info.HasMember("RunBefore")) { script.RunTrigger = info["RunBefore"].GetString(); script.TriggerType = RUN_BEFORE; } else { throw std::runtime_error( fmt::format("No valid trigger was specified for custom script with path {}", script.Path)); } if (info.HasMember("ServerCallback")) { script.ServerCallback = info["ServerCallback"].GetString(); } if (info.HasMember("ClientCallback")) { script.ClientCallback = info["ClientCallback"].GetString(); } } Mod::Mod(const fs::path& modFolder) : m_folder(modFolder) { auto logger = spdlog::get("logger"); // Read mod.json fs::path modJsonPath = m_folder / "mod.json"; std::ifstream modJsonFile(modJsonPath); if (!modJsonFile.good()) { throw std::exception("Failed to find or read from mod.json - are you sure it exists?"); } // Pull details out of the mod document rapidjson::Document d = GetModDocument(modJsonFile); m_name = d["Name"].GetString(); m_description = d.HasMember("Description") ? d["Description"].GetString() : ""; if (d.HasMember("Authors")) { const rapidjson::Value& authors = d["Authors"]; for (rapidjson::Value::ConstValueIterator itr = authors.Begin(); itr != authors.End(); itr++) { m_authors.emplace_back(itr->GetString()); } } if (d.HasMember("Contacts")) { const rapidjson::Value& contacts = d["Contacts"]; for (rapidjson::Value::ConstValueIterator itr = contacts.Begin(); itr != contacts.End(); itr++) { m_contacts.emplace_back(itr->GetString()); } } m_version = d.HasMember("Version") ? d["Version"].GetString() : ""; if (d.HasMember("Gamemode")) { const rapidjson::Value& modGamemode = d["Gamemode"]; m_gamemode = GamemodeInfo(); m_gamemode.HasGamemode = true; m_gamemode.Id = modGamemode["Id"].GetString(); m_gamemode.Name = modGamemode["Name"].GetString(); m_gamemode.Description = modGamemode["Description"].GetString(); } const bool bIsCorrectGamemode = !m_gamemode.HasGamemode || m_gamemode.Id == SDK().GetModManager().GetCurrentGamemode(); // Fill in all of the specified custom scripts // TODO: Check that the user hasn't specified a custom script twice std::unordered_set<std::string> customPaths; if (d.HasMember("CustomScripts")) { const rapidjson::Value& customScripts = d["CustomScripts"]; fs::path basePath = m_folder / "scripts/vscripts"; for (rapidjson::SizeType i = 0; i < customScripts.Size(); i++) { const rapidjson::Value& Info = customScripts[i]; const bool bIgnoreGamemode = Info.HasMember("IgnoreGamemode") ? Info["IgnoreGamemode"].GetBool() : false; if (bIsCorrectGamemode || bIgnoreGamemode) { m_customScripts.resize(m_customScripts.size() + 1); CreateCustomScriptInfo(m_customScripts[i], m_folder, customScripts[i]); std::string customPath = (basePath / m_customScripts[i].Path).make_preferred().string(); customPaths.insert(customPath); } } } // Iterate over all the files in the mod, putting relevant files into patches and customs std::string scriptsFolder = (m_folder / "scripts").string(); std::string mpLevelsFolder = (m_folder / "scripts" / "vscripts" / "mp" / "levels").string(); for (auto& dirIter : fs::recursive_directory_iterator(m_folder)) { if (dirIter.status().type() == fs::file_type::directory) { continue; } fs::path path = dirIter.path(); fs::path extension = path.extension(); // If the path is inside the scripts folder, need to do some special processing std::string pathString = path.string(); std::string relative = pathString.substr(m_folder.string().size() + 1); if (!pathString.compare(0, scriptsFolder.size(), scriptsFolder) && pathString.compare(0, mpLevelsFolder.size(), mpLevelsFolder)) { // Warn the user if the mod has scripts.rson and ignore it if (path.filename() == "scripts.rson") { logger->warn( "{} contains a scripts.rson file. This will not be loaded - use CustomScripts in mod.json instead", m_name); continue; } // If it's already marked as a custom file, move on if (customPaths.find(pathString) != customPaths.end()) { continue; } // Only load if the gamemode is correct for this mod if (!bIsCorrectGamemode) { continue; } if (!SDK().GetFSManager().FileExists(relative.c_str(), "GAME")) { // If it's a file in scripts and it's not marked as a custom script, it might never get loaded, but // we'll add it as a custom asset anyway logger->warn("{} in {} is not a custom script and does not correspond to a file in the game - it may " "not be loaded", relative, m_name); m_customAssets.emplace_back(relative); } else { // Add the file as a patch m_filesToPatch.emplace_back(relative); } } else if (path.parent_path() != m_folder) // Don't add assets in the root folder { if (extension == ".txt" || extension == ".res" || extension == ".menu" || extension == ".cfg" || extension == ".vtf" || extension == ".vmt" || extension == ".pcf") { // We can patch these file types, so if they already exist, we'll add it as a file to patch if (SDK().GetFSManager().FileExists(relative.c_str(), "GAME")) { spdlog::get("logger")->warn(relative); m_filesToPatch.emplace_back(relative); } else { spdlog::get("logger")->error(relative); m_customAssets.emplace_back(relative); } } else { // Add the file as a custom asset m_customAssets.emplace_back(relative); } } } } ModManager::ModManager(ConCommandManager& conCommandManager, SquirrelManager& sqManager) { m_logger = spdlog::get("logger"); conCommandManager.RegisterCommand("reload_mods", WRAPPED_MEMBER(ReloadModsCommand), "Reload all mods", 0); conCommandManager.RegisterCommand("icepick_gamemode", WRAPPED_MEMBER(SetGamemodeCommand), "Set the gamemode using its id", 0); sqManager.AddFuncRegistration(CONTEXT_CLIENT, "array", "GetIcepickGamemodes", "", "Returns an array of Icepick gamemodes", WRAPPED_MEMBER(GetIcepickGamemodes_Client)); sqManager.AddFuncRegistration(CONTEXT_SERVER, "array", "GetIcepickGamemodes", "", "Returns an array of Icepick gamemodes", WRAPPED_MEMBER(GetIcepickGamemodes_Server)); sqManager.AddFuncRegistration(CONTEXT_SERVER, "string", "GetIcepickGamemode", "", "Returns the current Icepick gamemode", WRAPPED_MEMBER(SqGetCurrentGamemode)); } void ModManager::ReloadModsCommand(const CCommand& args) { try { CompileMods(); } catch (std::exception& e) { m_logger->error("Failed to reload mods: {}", e.what()); } } void ModManager::CompileMods() { m_logger->info("Compiling mods..."); FileSystemManager& filesystem = SDK().GetFSManager(); SquirrelManager& sq = SDK().GetSQManager(); const fs::path& compilePath = filesystem.GetCompilePath(); // Clear out current mods m_mods.clear(); // Clear all the callbacks sq.ClearCallbacks(); // Clear out the compiled assets folder fs::remove_all(compilePath); fs::create_directories(compilePath); // Mount all the VPKs filesystem.MountAllVPKs(); // Iterate over all the directories in the mods path and create the Mod object for them, then compile the mod std::string scriptsRson = filesystem.ReadOriginalFile("scripts/vscripts/scripts.rson", "GAME"); std::unordered_map<std::string, std::vector<fs::path>> filesToPatch; // relative path => [ absolute path on disk ] for (auto& p : fs::directory_iterator(filesystem.GetModsPath())) { if (p.status().type() != fs::file_type::directory) { continue; } try { // Check if the mod is disabled if (fs::exists(p.path() / "disabled")) { m_logger->info("Skipping disabled mod: {}", p.path().filename().string()); continue; } // Load the mod details Mod mod(p.path()); // Copy the custom assets to the compiled directory for (auto& customPath : mod.m_customAssets) { SPDLOG_LOGGER_TRACE(m_logger, "Copying custom asset {} from {}", customPath, mod.m_folder); fs::path destFile = compilePath / customPath; if (fs::exists(destFile)) { throw std::runtime_error( fmt::format("{} already exists as a custom asset in another mod", customPath)); } fs::path destFolder = destFile.remove_filename(); fs::create_directories(destFolder); fs::copy(mod.m_folder / customPath, destFolder); } // Add all the details to our patched scripts.rson and copy the script to the compiled dir // TODO: Also add the ability to add custom scripts to stuff that isn't in scripts.rson std::string newScriptsRson(scriptsRson); for (const auto& customScript : mod.m_customScripts) { std::string customPath = "scripts/vscripts/" + customScript.Path; SPDLOG_LOGGER_TRACE(m_logger, "Copying custom script {} from {}", customPath, mod.m_folder); fs::path destFolder = (compilePath / customPath).remove_filename(); fs::create_directories(destFolder); fs::copy(mod.m_folder / customPath, destFolder); if (customScript.TriggerType == RUN_AFTER) { Util::FindAndReplaceAll(newScriptsRson, customScript.RunTrigger + "\r\n", customScript.RunTrigger + "\r\n\t" + customScript.Path + "\r\n"); } else if (customScript.TriggerType == RUN_BEFORE) { Util::FindAndReplaceAll(newScriptsRson, customScript.RunTrigger + "\r\n", customScript.Path + "\r\n\t" + customScript.RunTrigger + "\r\n"); } else if (customScript.TriggerType == RUN_WHEN) { newScriptsRson += "\r\nWhen: \"" + customScript.RunTrigger + "\"\r\nScripts:\r\n[\r\n\t" + customScript.Path + "\r\n]\r\n"; } if (!customScript.ClientCallback.empty()) { sq.AddClientCallback(customScript.ClientCallback); } if (!customScript.ServerCallback.empty()) { sq.AddServerCallback(customScript.ServerCallback); } } // Add to the list of files to get patched for (const auto& patchFile : mod.m_filesToPatch) { filesToPatch[patchFile].push_back(mod.m_folder / patchFile); } m_mods.push_back(mod); scriptsRson = std::move(newScriptsRson); m_logger->info("Mod loaded: {}", mod.m_name); } catch (std::exception& e) { m_logger->error("Failed to load mod from {}: {}", p.path().filename(), e.what()); } } // Write patched scripts.rson to compiled dir fs::path destFolder = compilePath / "scripts/vscripts"; fs::create_directories(destFolder); { std::ofstream f(destFolder / "scripts.rson", std::ios::binary); f << scriptsRson; } // Patch the remaining game files for (const auto& kv : filesToPatch) { try { PatchFile(kv.first, kv.second); } catch (std::exception& e) { m_logger->error("Failed to patch {}: {}", kv.first, e.what()); } } m_logger->info("{} mods loaded", m_mods.size()); } std::string MergeFile(const std::string& currentData, const std::string& baseData, const fs::path& patchFile) { std::ifstream f(patchFile); if (!f.good()) { throw std::runtime_error("Failed to open patch file"); } std::string fileData; f.seekg(0, std::ios::end); fileData.reserve(f.tellg()); f.seekg(0, std::ios::beg); fileData.assign((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>()); Util::FindAndReplaceAll(fileData, "\r\n", "\n"); diff_match_patch<std::string> dmp; dmp.Diff_Timeout = 0.0; auto diffs = dmp.diff_main(baseData, fileData, false); auto patches = dmp.patch_make(diffs); auto patchResult = dmp.patch_apply(patches, currentData); for (bool success : patchResult.second) { if (!success) { throw std::runtime_error("Failed to apply patch"); } } return std::move(patchResult.first); } void ModManager::PatchFile(const std::string& gamePath, const std::vector<fs::path>& patchFiles) { const fs::path& compilePath = SDK().GetFSManager().GetCompilePath(); // Create directories for file in output fs::create_directories((compilePath / gamePath).remove_filename()); // Read the orignial file data std::string baseData = SDK().GetFSManager().ReadOriginalFile(gamePath.c_str(), "GAME"); Util::FindAndReplaceAll(baseData, "\r\n", "\n"); std::string currentData(baseData); // Apply all the patches for (const fs::path& patchFile : patchFiles) { try { SPDLOG_LOGGER_DEBUG(m_logger, "Merging {} into {}", patchFile, gamePath); currentData = std::move(MergeFile(currentData, baseData, patchFile)); } catch (std::exception& e) { m_logger->error("Failed to merge {} into {}: {}", patchFile, gamePath, e.what()); } } // Write the data out std::ofstream f(compilePath / gamePath, std::ios::binary); f << currentData; } SQInteger ModManager::GetIcepickGamemodes_Client(HSQUIRRELVM v) { // create gamemodes array sq_newarray.CallClient(v, 0); for (auto& mod : m_mods) { if (mod.m_gamemode.HasGamemode) { // create array for this gamemode sq_newarray.CallClient(v, 0); // add data to the gamemode array sq_pushstring.CallClient(v, mod.m_gamemode.Id.c_str(), -1); sq_arrayappend.CallClient(v, -2); sq_pushstring.CallClient(v, mod.m_gamemode.Name.c_str(), -1); sq_arrayappend.CallClient(v, -2); sq_pushstring.CallClient(v, mod.m_gamemode.Description.c_str(), -1); sq_arrayappend.CallClient(v, -2); // add the gamemode to our array of gamemodes sq_arrayappend.CallClient(v, -2); } } return 1; } SQInteger ModManager::GetIcepickGamemodes_Server(HSQUIRRELVM v) { // create gamemodes array sq_newarray.CallServer(v, 0); for (auto& mod : m_mods) { if (mod.m_gamemode.HasGamemode) { // create array for this gamemode sq_newarray.CallServer(v, 0); // add data to the gamemode array sq_pushstring.CallServer(v, mod.m_gamemode.Id.c_str(), -1); sq_arrayappend.CallServer(v, -2); sq_pushstring.CallServer(v, mod.m_gamemode.Name.c_str(), -1); sq_arrayappend.CallServer(v, -2); sq_pushstring.CallServer(v, mod.m_gamemode.Description.c_str(), -1); sq_arrayappend.CallServer(v, -2); // add the gamemode to our array of gamemodes sq_arrayappend.CallServer(v, -2); } } return 1; } SQInteger ModManager::SqGetCurrentGamemode(HSQUIRRELVM v) { sq_pushstring.CallServer(v, m_gamemode.c_str(), -1); return 1; } void ModManager::SetGamemodeCommand(const CCommand& args) { m_gamemode = args.ArgS(); }
34.185693
175
0.548531
[ "object", "vector" ]
b470c1570bf7913d1f485a1cc59ec2aaea699c04
40,392
cc
C++
webkit/compositor_bindings/web_transformation_matrix_unittest.cc
jianglong0156/chromium.src
d496dfeebb0f282468827654c2b3769b3378c087
[ "BSD-3-Clause" ]
5
2018-03-10T13:08:42.000Z
2021-07-26T15:02:11.000Z
webkit/compositor_bindings/web_transformation_matrix_unittest.cc
sanyaade-mobiledev/chromium.src
d496dfeebb0f282468827654c2b3769b3378c087
[ "BSD-3-Clause" ]
1
2015-07-21T08:02:01.000Z
2015-07-21T08:02:01.000Z
webkit/compositor_bindings/web_transformation_matrix_unittest.cc
jianglong0156/chromium.src
d496dfeebb0f282468827654c2b3769b3378c087
[ "BSD-3-Clause" ]
6
2016-11-14T10:13:35.000Z
2021-01-23T15:29:53.000Z
// Copyright 2012 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 "config.h" #define _USE_MATH_DEFINES #include <math.h> #include "cc/test/geometry_test_utils.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebTransformationMatrix.h" #define EXPECT_ROW1_EQ(a, b, c, d, matrix) \ EXPECT_FLOAT_EQ((a), (matrix).m11()); \ EXPECT_FLOAT_EQ((b), (matrix).m21()); \ EXPECT_FLOAT_EQ((c), (matrix).m31()); \ EXPECT_FLOAT_EQ((d), (matrix).m41()); #define EXPECT_ROW2_EQ(a, b, c, d, matrix) \ EXPECT_FLOAT_EQ((a), (matrix).m12()); \ EXPECT_FLOAT_EQ((b), (matrix).m22()); \ EXPECT_FLOAT_EQ((c), (matrix).m32()); \ EXPECT_FLOAT_EQ((d), (matrix).m42()); #define EXPECT_ROW3_EQ(a, b, c, d, matrix) \ EXPECT_FLOAT_EQ((a), (matrix).m13()); \ EXPECT_FLOAT_EQ((b), (matrix).m23()); \ EXPECT_FLOAT_EQ((c), (matrix).m33()); \ EXPECT_FLOAT_EQ((d), (matrix).m43()); #define EXPECT_ROW4_EQ(a, b, c, d, matrix) \ EXPECT_FLOAT_EQ((a), (matrix).m14()); \ EXPECT_FLOAT_EQ((b), (matrix).m24()); \ EXPECT_FLOAT_EQ((c), (matrix).m34()); \ EXPECT_FLOAT_EQ((d), (matrix).m44()); \ // Checking float values for equality close to zero is not robust using EXPECT_FLOAT_EQ // (see gtest documentation). So, to verify rotation matrices, we must use a looser // absolute error threshold in some places. #define EXPECT_ROW1_NEAR(a, b, c, d, matrix, errorThreshold) \ EXPECT_NEAR((a), (matrix).m11(), (errorThreshold)); \ EXPECT_NEAR((b), (matrix).m21(), (errorThreshold)); \ EXPECT_NEAR((c), (matrix).m31(), (errorThreshold)); \ EXPECT_NEAR((d), (matrix).m41(), (errorThreshold)); #define EXPECT_ROW2_NEAR(a, b, c, d, matrix, errorThreshold) \ EXPECT_NEAR((a), (matrix).m12(), (errorThreshold)); \ EXPECT_NEAR((b), (matrix).m22(), (errorThreshold)); \ EXPECT_NEAR((c), (matrix).m32(), (errorThreshold)); \ EXPECT_NEAR((d), (matrix).m42(), (errorThreshold)); #define EXPECT_ROW3_NEAR(a, b, c, d, matrix, errorThreshold) \ EXPECT_NEAR((a), (matrix).m13(), (errorThreshold)); \ EXPECT_NEAR((b), (matrix).m23(), (errorThreshold)); \ EXPECT_NEAR((c), (matrix).m33(), (errorThreshold)); \ EXPECT_NEAR((d), (matrix).m43(), (errorThreshold)); #define ERROR_THRESHOLD 1e-14 #define LOOSE_ERROR_THRESHOLD 1e-7 using namespace WebKit; namespace { static void initializeTestMatrix(WebTransformationMatrix& transform) { transform.setM11(10); transform.setM12(11); transform.setM13(12); transform.setM14(13); transform.setM21(14); transform.setM22(15); transform.setM23(16); transform.setM24(17); transform.setM31(18); transform.setM32(19); transform.setM33(20); transform.setM34(21); transform.setM41(22); transform.setM42(23); transform.setM43(24); transform.setM44(25); // Sanity check EXPECT_ROW1_EQ(10, 14, 18, 22, transform); EXPECT_ROW2_EQ(11, 15, 19, 23, transform); EXPECT_ROW3_EQ(12, 16, 20, 24, transform); EXPECT_ROW4_EQ(13, 17, 21, 25, transform); } static void initializeTestMatrix2(WebTransformationMatrix& transform) { transform.setM11(30); transform.setM12(31); transform.setM13(32); transform.setM14(33); transform.setM21(34); transform.setM22(35); transform.setM23(36); transform.setM24(37); transform.setM31(38); transform.setM32(39); transform.setM33(40); transform.setM34(41); transform.setM41(42); transform.setM42(43); transform.setM43(44); transform.setM44(45); // Sanity check EXPECT_ROW1_EQ(30, 34, 38, 42, transform); EXPECT_ROW2_EQ(31, 35, 39, 43, transform); EXPECT_ROW3_EQ(32, 36, 40, 44, transform); EXPECT_ROW4_EQ(33, 37, 41, 45, transform); } TEST(WebTransformationMatrixTest, verifyDefaultConstructorCreatesIdentityMatrix) { WebTransformationMatrix A; EXPECT_ROW1_EQ(1, 0, 0, 0, A); EXPECT_ROW2_EQ(0, 1, 0, 0, A); EXPECT_ROW3_EQ(0, 0, 1, 0, A); EXPECT_ROW4_EQ(0, 0, 0, 1, A); EXPECT_TRUE(A.isIdentity()); } TEST(WebTransformationMatrixTest, verifyConstructorFor2dElements) { WebTransformationMatrix A(1, 2, 3, 4, 5, 6); EXPECT_ROW1_EQ(1, 3, 0, 5, A); EXPECT_ROW2_EQ(2, 4, 0, 6, A); EXPECT_ROW3_EQ(0, 0, 1, 0, A); EXPECT_ROW4_EQ(0, 0, 0, 1, A); } TEST(WebTransformationMatrixTest, verifyConstructorForAllElements) { WebTransformationMatrix A(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); EXPECT_ROW1_EQ(1, 5, 9, 13, A); EXPECT_ROW2_EQ(2, 6, 10, 14, A); EXPECT_ROW3_EQ(3, 7, 11, 15, A); EXPECT_ROW4_EQ(4, 8, 12, 16, A); } TEST(WebTransformationMatrixTest, verifyCopyConstructor) { WebTransformationMatrix A; initializeTestMatrix(A); // Copy constructor should produce exact same elements as matrix A. WebTransformationMatrix B(A); EXPECT_ROW1_EQ(10, 14, 18, 22, B); EXPECT_ROW2_EQ(11, 15, 19, 23, B); EXPECT_ROW3_EQ(12, 16, 20, 24, B); EXPECT_ROW4_EQ(13, 17, 21, 25, B); } TEST(WebTransformationMatrixTest, verifyMatrixInversion) { // Invert a translation WebTransformationMatrix translation; translation.translate3d(2, 3, 4); EXPECT_TRUE(translation.isInvertible()); WebTransformationMatrix inverseTranslation = translation.inverse(); EXPECT_ROW1_EQ(1, 0, 0, -2, inverseTranslation); EXPECT_ROW2_EQ(0, 1, 0, -3, inverseTranslation); EXPECT_ROW3_EQ(0, 0, 1, -4, inverseTranslation); EXPECT_ROW4_EQ(0, 0, 0, 1, inverseTranslation); // Note that inversion should not have changed the original matrix. EXPECT_ROW1_EQ(1, 0, 0, 2, translation); EXPECT_ROW2_EQ(0, 1, 0, 3, translation); EXPECT_ROW3_EQ(0, 0, 1, 4, translation); EXPECT_ROW4_EQ(0, 0, 0, 1, translation); // Invert a non-uniform scale WebTransformationMatrix scale; scale.scale3d(4, 10, 100); EXPECT_TRUE(scale.isInvertible()); WebTransformationMatrix inverseScale = scale.inverse(); EXPECT_ROW1_EQ(0.25, 0, 0, 0, inverseScale); EXPECT_ROW2_EQ(0, .1f, 0, 0, inverseScale); EXPECT_ROW3_EQ(0, 0, .01f, 0, inverseScale); EXPECT_ROW4_EQ(0, 0, 0, 1, inverseScale); // Try to invert a matrix that is not invertible. // The inverse() function should simply return an identity matrix. WebTransformationMatrix notInvertible; notInvertible.setM11(0); notInvertible.setM22(0); notInvertible.setM33(0); notInvertible.setM44(0); EXPECT_FALSE(notInvertible.isInvertible()); WebTransformationMatrix inverseOfNotInvertible; initializeTestMatrix(inverseOfNotInvertible); // initialize this to something non-identity, to make sure that assignment below actually took place. inverseOfNotInvertible = notInvertible.inverse(); EXPECT_TRUE(inverseOfNotInvertible.isIdentity()); } TEST(WebTransformationMatrixTest, verifyTo2DTransform) { WebTransformationMatrix A; initializeTestMatrix(A); WebTransformationMatrix B = A.to2dTransform(); EXPECT_ROW1_EQ(10, 14, 0, 22, B); EXPECT_ROW2_EQ(11, 15, 0, 23, B); EXPECT_ROW3_EQ(0, 0, 1, 0, B); EXPECT_ROW4_EQ(13, 17, 0, 25, B); // Note that to2DTransform should not have changed the original matrix. EXPECT_ROW1_EQ(10, 14, 18, 22, A); EXPECT_ROW2_EQ(11, 15, 19, 23, A); EXPECT_ROW3_EQ(12, 16, 20, 24, A); EXPECT_ROW4_EQ(13, 17, 21, 25, A); } TEST(WebTransformationMatrixTest, verifyAssignmentOperator) { WebTransformationMatrix A; initializeTestMatrix(A); WebTransformationMatrix B; initializeTestMatrix2(B); WebTransformationMatrix C; initializeTestMatrix2(C); C = B = A; // Both B and C should now have been re-assigned to the value of A. EXPECT_ROW1_EQ(10, 14, 18, 22, B); EXPECT_ROW2_EQ(11, 15, 19, 23, B); EXPECT_ROW3_EQ(12, 16, 20, 24, B); EXPECT_ROW4_EQ(13, 17, 21, 25, B); EXPECT_ROW1_EQ(10, 14, 18, 22, C); EXPECT_ROW2_EQ(11, 15, 19, 23, C); EXPECT_ROW3_EQ(12, 16, 20, 24, C); EXPECT_ROW4_EQ(13, 17, 21, 25, C); } TEST(WebTransformationMatrixTest, verifyEqualsBooleanOperator) { WebTransformationMatrix A; initializeTestMatrix(A); WebTransformationMatrix B; initializeTestMatrix(B); EXPECT_TRUE(A == B); // Modifying multiple elements should cause equals operator to return false. WebTransformationMatrix C; initializeTestMatrix2(C); EXPECT_FALSE(A == C); // Modifying any one individual element should cause equals operator to return false. WebTransformationMatrix D; D = A; D.setM11(0); EXPECT_FALSE(A == D); D = A; D.setM12(0); EXPECT_FALSE(A == D); D = A; D.setM13(0); EXPECT_FALSE(A == D); D = A; D.setM14(0); EXPECT_FALSE(A == D); D = A; D.setM21(0); EXPECT_FALSE(A == D); D = A; D.setM22(0); EXPECT_FALSE(A == D); D = A; D.setM23(0); EXPECT_FALSE(A == D); D = A; D.setM24(0); EXPECT_FALSE(A == D); D = A; D.setM31(0); EXPECT_FALSE(A == D); D = A; D.setM32(0); EXPECT_FALSE(A == D); D = A; D.setM33(0); EXPECT_FALSE(A == D); D = A; D.setM34(0); EXPECT_FALSE(A == D); D = A; D.setM41(0); EXPECT_FALSE(A == D); D = A; D.setM42(0); EXPECT_FALSE(A == D); D = A; D.setM43(0); EXPECT_FALSE(A == D); D = A; D.setM44(0); EXPECT_FALSE(A == D); } TEST(WebTransformationMatrixTest, verifyMultiplyOperator) { WebTransformationMatrix A; initializeTestMatrix(A); WebTransformationMatrix B; initializeTestMatrix2(B); WebTransformationMatrix C = A * B; EXPECT_ROW1_EQ(2036, 2292, 2548, 2804, C); EXPECT_ROW2_EQ(2162, 2434, 2706, 2978, C); EXPECT_ROW3_EQ(2288, 2576, 2864, 3152, C); EXPECT_ROW4_EQ(2414, 2718, 3022, 3326, C); // Just an additional sanity check; matrix multiplication is not commutative. EXPECT_FALSE(A * B == B * A); } TEST(WebTransformationMatrixTest, verifyMatrixMultiplication) { WebTransformationMatrix A; initializeTestMatrix(A); WebTransformationMatrix B; initializeTestMatrix2(B); A.multiply(B); EXPECT_ROW1_EQ(2036, 2292, 2548, 2804, A); EXPECT_ROW2_EQ(2162, 2434, 2706, 2978, A); EXPECT_ROW3_EQ(2288, 2576, 2864, 3152, A); EXPECT_ROW4_EQ(2414, 2718, 3022, 3326, A); } TEST(WebTransformationMatrixTest, verifyMakeIdentiy) { WebTransformationMatrix A; initializeTestMatrix(A); A.makeIdentity(); EXPECT_ROW1_EQ(1, 0, 0, 0, A); EXPECT_ROW2_EQ(0, 1, 0, 0, A); EXPECT_ROW3_EQ(0, 0, 1, 0, A); EXPECT_ROW4_EQ(0, 0, 0, 1, A); EXPECT_TRUE(A.isIdentity()); } TEST(WebTransformationMatrixTest, verifyTranslate) { WebTransformationMatrix A; A.translate(2, 3); EXPECT_ROW1_EQ(1, 0, 0, 2, A); EXPECT_ROW2_EQ(0, 1, 0, 3, A); EXPECT_ROW3_EQ(0, 0, 1, 0, A); EXPECT_ROW4_EQ(0, 0, 0, 1, A); // Verify that translate() post-multiplies the existing matrix. A.makeIdentity(); A.scale(5); A.translate(2, 3); EXPECT_ROW1_EQ(5, 0, 0, 10, A); EXPECT_ROW2_EQ(0, 5, 0, 15, A); EXPECT_ROW3_EQ(0, 0, 1, 0, A); EXPECT_ROW4_EQ(0, 0, 0, 1, A); } TEST(WebTransformationMatrixTest, verifyTranslate3d) { WebTransformationMatrix A; A.translate3d(2, 3, 4); EXPECT_ROW1_EQ(1, 0, 0, 2, A); EXPECT_ROW2_EQ(0, 1, 0, 3, A); EXPECT_ROW3_EQ(0, 0, 1, 4, A); EXPECT_ROW4_EQ(0, 0, 0, 1, A); // Verify that translate3d() post-multiplies the existing matrix. A.makeIdentity(); A.scale3d(6, 7, 8); A.translate3d(2, 3, 4); EXPECT_ROW1_EQ(6, 0, 0, 12, A); EXPECT_ROW2_EQ(0, 7, 0, 21, A); EXPECT_ROW3_EQ(0, 0, 8, 32, A); EXPECT_ROW4_EQ(0, 0, 0, 1, A); } TEST(WebTransformationMatrixTest, verifyTranslateRight3d) { WebTransformationMatrix A; A.translateRight3d(2, 3, 4); EXPECT_ROW1_EQ(1, 0, 0, 2, A); EXPECT_ROW2_EQ(0, 1, 0, 3, A); EXPECT_ROW3_EQ(0, 0, 1, 4, A); EXPECT_ROW4_EQ(0, 0, 0, 1, A); // Note carefully, all other operations do post-multiply, this one is unique. // Verify that translateRight3d() PRE-multiplies the existing matrix. A.makeIdentity(); A.scale3d(6, 7, 8); A.translateRight3d(2, 3, 4); EXPECT_ROW1_EQ(6, 0, 0, 2, A); EXPECT_ROW2_EQ(0, 7, 0, 3, A); EXPECT_ROW3_EQ(0, 0, 8, 4, A); EXPECT_ROW4_EQ(0, 0, 0, 1, A); } TEST(WebTransformationMatrixTest, verifyScale) { WebTransformationMatrix A; A.scale(5); EXPECT_ROW1_EQ(5, 0, 0, 0, A); EXPECT_ROW2_EQ(0, 5, 0, 0, A); EXPECT_ROW3_EQ(0, 0, 1, 0, A); EXPECT_ROW4_EQ(0, 0, 0, 1, A); // Verify that scale() post-multiplies the existing matrix. A.makeIdentity(); A.translate3d(2, 3, 4); A.scale(5); EXPECT_ROW1_EQ(5, 0, 0, 2, A); EXPECT_ROW2_EQ(0, 5, 0, 3, A); EXPECT_ROW3_EQ(0, 0, 1, 4, A); EXPECT_ROW4_EQ(0, 0, 0, 1, A); } TEST(WebTransformationMatrixTest, verifyNonUniformScale) { WebTransformationMatrix A; A.scaleNonUniform(6, 7); EXPECT_ROW1_EQ(6, 0, 0, 0, A); EXPECT_ROW2_EQ(0, 7, 0, 0, A); EXPECT_ROW3_EQ(0, 0, 1, 0, A); EXPECT_ROW4_EQ(0, 0, 0, 1, A); // Verify that scaleNonUniform() post-multiplies the existing matrix. A.makeIdentity(); A.translate3d(2, 3, 4); A.scaleNonUniform(6, 7); EXPECT_ROW1_EQ(6, 0, 0, 2, A); EXPECT_ROW2_EQ(0, 7, 0, 3, A); EXPECT_ROW3_EQ(0, 0, 1, 4, A); EXPECT_ROW4_EQ(0, 0, 0, 1, A); } TEST(WebTransformationMatrixTest, verifyScale3d) { WebTransformationMatrix A; A.scale3d(6, 7, 8); EXPECT_ROW1_EQ(6, 0, 0, 0, A); EXPECT_ROW2_EQ(0, 7, 0, 0, A); EXPECT_ROW3_EQ(0, 0, 8, 0, A); EXPECT_ROW4_EQ(0, 0, 0, 1, A); // Verify that scale3d() post-multiplies the existing matrix. A.makeIdentity(); A.translate3d(2, 3, 4); A.scale3d(6, 7, 8); EXPECT_ROW1_EQ(6, 0, 0, 2, A); EXPECT_ROW2_EQ(0, 7, 0, 3, A); EXPECT_ROW3_EQ(0, 0, 8, 4, A); EXPECT_ROW4_EQ(0, 0, 0, 1, A); } TEST(WebTransformationMatrixTest, verifyRotate) { WebTransformationMatrix A; A.rotate(90); EXPECT_ROW1_NEAR(0, -1, 0, 0, A, ERROR_THRESHOLD); EXPECT_ROW2_NEAR(1, 0, 0, 0, A, ERROR_THRESHOLD); EXPECT_ROW3_EQ(0, 0, 1, 0, A); EXPECT_ROW4_EQ(0, 0, 0, 1, A); // Verify that rotate() post-multiplies the existing matrix. A.makeIdentity(); A.scale3d(6, 7, 8); A.rotate(90); EXPECT_ROW1_NEAR(0, -6, 0, 0, A, ERROR_THRESHOLD); EXPECT_ROW2_NEAR(7, 0, 0, 0, A, ERROR_THRESHOLD); EXPECT_ROW3_EQ(0, 0, 8, 0, A); EXPECT_ROW4_EQ(0, 0, 0, 1, A); } TEST(WebTransformationMatrixTest, verifyRotate3d) { WebTransformationMatrix A; // Check rotation about z-axis A.makeIdentity(); A.rotate3d(0, 0, 90); EXPECT_ROW1_NEAR(0, -1, 0, 0, A, ERROR_THRESHOLD); EXPECT_ROW2_NEAR(1, 0, 0, 0, A, ERROR_THRESHOLD); EXPECT_ROW3_EQ(0, 0, 1, 0, A); EXPECT_ROW4_EQ(0, 0, 0, 1, A); // Check rotation about x-axis A.makeIdentity(); A.rotate3d(90, 0, 0); EXPECT_ROW1_EQ(1, 0, 0, 0, A); EXPECT_ROW2_NEAR(0, 0, -1, 0, A, ERROR_THRESHOLD); EXPECT_ROW3_NEAR(0, 1, 0, 0, A, ERROR_THRESHOLD); EXPECT_ROW4_EQ(0, 0, 0, 1, A); // Check rotation about y-axis. // Note carefully, the expected pattern is inverted compared to rotating about x axis or z axis. A.makeIdentity(); A.rotate3d(0, 90, 0); EXPECT_ROW1_NEAR(0, 0, 1, 0, A, ERROR_THRESHOLD); EXPECT_ROW2_EQ(0, 1, 0, 0, A); EXPECT_ROW3_NEAR(-1, 0, 0, 0, A, ERROR_THRESHOLD); EXPECT_ROW4_EQ(0, 0, 0, 1, A); // Verify that rotate3d(rx, ry, rz) post-multiplies the existing matrix. A.makeIdentity(); A.scale3d(6, 7, 8); A.rotate3d(0, 0, 90); EXPECT_ROW1_NEAR(0, -6, 0, 0, A, ERROR_THRESHOLD); EXPECT_ROW2_NEAR(7, 0, 0, 0, A, ERROR_THRESHOLD); EXPECT_ROW3_EQ(0, 0, 8, 0, A); EXPECT_ROW4_EQ(0, 0, 0, 1, A); } TEST(WebTransformationMatrixTest, verifyRotate3dOrderOfCompositeRotations) { // Rotate3d(degreesX, degreesY, degreesZ) is actually composite transform consiting of // three primitive rotations. This test verifies that the ordering of those three // transforms is the intended ordering. // // The correct ordering for this test case should be: // 1. rotate by 30 degrees about z-axis // 2. rotate by 20 degrees about y-axis // 3. rotate by 10 degrees about x-axis // // Note: there are 6 possible orderings of 3 transforms. For the specific transforms // used in this test, all 6 combinations produce a unique matrix that is different // from the other orderings. That way, this test verifies the exact ordering. WebTransformationMatrix A; A.makeIdentity(); A.rotate3d(10, 20, 30); EXPECT_ROW1_NEAR(0.8137976813493738026394908, -0.4409696105298823720630708, 0.3785223063697923939763257, 0, A, ERROR_THRESHOLD); EXPECT_ROW2_NEAR(0.4698463103929541584413698, 0.8825641192593856043657752, 0.0180283112362972230968694, 0, A, ERROR_THRESHOLD); EXPECT_ROW3_NEAR(-0.3420201433256686573969318, 0.1631759111665348205288950, 0.9254165783983233639631294, 0, A, ERROR_THRESHOLD); EXPECT_ROW4_EQ(0, 0, 0, 1, A); } TEST(WebTransformationMatrixTest, verifyRotateAxisAngle3d) { WebTransformationMatrix A; // Check rotation about z-axis A.makeIdentity(); A.rotate3d(0, 0, 1, 90); EXPECT_ROW1_NEAR(0, -1, 0, 0, A, ERROR_THRESHOLD); EXPECT_ROW2_NEAR(1, 0, 0, 0, A, ERROR_THRESHOLD); EXPECT_ROW3_EQ(0, 0, 1, 0, A); EXPECT_ROW4_EQ(0, 0, 0, 1, A); // Check rotation about x-axis A.makeIdentity(); A.rotate3d(1, 0, 0, 90); EXPECT_ROW1_EQ(1, 0, 0, 0, A); EXPECT_ROW2_NEAR(0, 0, -1, 0, A, ERROR_THRESHOLD); EXPECT_ROW3_NEAR(0, 1, 0, 0, A, ERROR_THRESHOLD); EXPECT_ROW4_EQ(0, 0, 0, 1, A); // Check rotation about y-axis. // Note carefully, the expected pattern is inverted compared to rotating about x axis or z axis. A.makeIdentity(); A.rotate3d(0, 1, 0, 90); EXPECT_ROW1_NEAR(0, 0, 1, 0, A, ERROR_THRESHOLD); EXPECT_ROW2_EQ(0, 1, 0, 0, A); EXPECT_ROW3_NEAR(-1, 0, 0, 0, A, ERROR_THRESHOLD); EXPECT_ROW4_EQ(0, 0, 0, 1, A); // Verify that rotate3d(axis, angle) post-multiplies the existing matrix. A.makeIdentity(); A.scale3d(6, 7, 8); A.rotate3d(0, 0, 1, 90); EXPECT_ROW1_NEAR(0, -6, 0, 0, A, ERROR_THRESHOLD); EXPECT_ROW2_NEAR(7, 0, 0, 0, A, ERROR_THRESHOLD); EXPECT_ROW3_EQ(0, 0, 8, 0, A); EXPECT_ROW4_EQ(0, 0, 0, 1, A); } TEST(WebTransformationMatrixTest, verifyRotateAxisAngle3dForArbitraryAxis) { // Check rotation about an arbitrary non-axis-aligned vector. WebTransformationMatrix A; A.rotate3d(1, 1, 1, 90); EXPECT_ROW1_NEAR(0.3333333333333334258519187, -0.2440169358562924717404030, 0.9106836025229592124219380, 0, A, ERROR_THRESHOLD); EXPECT_ROW2_NEAR(0.9106836025229592124219380, 0.3333333333333334258519187, -0.2440169358562924717404030, 0, A, ERROR_THRESHOLD); EXPECT_ROW3_NEAR(-0.2440169358562924717404030, 0.9106836025229592124219380, 0.3333333333333334258519187, 0, A, ERROR_THRESHOLD); EXPECT_ROW4_EQ(0, 0, 0, 1, A); } // Test failing as of webkit 132872:132896. http://crbug.com/158553 TEST(WebTransformationMatrixTest, verifyRotateAxisAngle3dForDegenerateAxis) { // Check rotation about a degenerate zero vector. // It is expected to skip applying the rotation. WebTransformationMatrix A; A.rotate3d(0, 0, 0, 45); // Verify that A remains unchanged. EXPECT_TRUE(A.isIdentity()); initializeTestMatrix(A); A.rotate3d(0, 0, 0, 35); // Verify that A remains unchanged. EXPECT_ROW1_EQ(10, 14, 18, 22, A); EXPECT_ROW2_EQ(11, 15, 19, 23, A); EXPECT_ROW3_EQ(12, 16, 20, 24, A); EXPECT_ROW4_EQ(13, 17, 21, 25, A); } TEST(WebTransformationMatrixTest, verifySkewX) { WebTransformationMatrix A; A.skewX(45); EXPECT_ROW1_EQ(1, 1, 0, 0, A); EXPECT_ROW2_EQ(0, 1, 0, 0, A); EXPECT_ROW3_EQ(0, 0, 1, 0, A); EXPECT_ROW4_EQ(0, 0, 0, 1, A); // Verify that skewX() post-multiplies the existing matrix. // Row 1, column 2, would incorrectly have value "7" if the matrix is pre-multiplied instead of post-multiplied. A.makeIdentity(); A.scale3d(6, 7, 8); A.skewX(45); EXPECT_ROW1_EQ(6, 6, 0, 0, A); EXPECT_ROW2_EQ(0, 7, 0, 0, A); EXPECT_ROW3_EQ(0, 0, 8, 0, A); EXPECT_ROW4_EQ(0, 0, 0, 1, A); } TEST(WebTransformationMatrixTest, verifySkewY) { WebTransformationMatrix A; A.skewY(45); EXPECT_ROW1_EQ(1, 0, 0, 0, A); EXPECT_ROW2_EQ(1, 1, 0, 0, A); EXPECT_ROW3_EQ(0, 0, 1, 0, A); EXPECT_ROW4_EQ(0, 0, 0, 1, A); // Verify that skewY() post-multiplies the existing matrix. // Row 2, column 1, would incorrectly have value "6" if the matrix is pre-multiplied instead of post-multiplied. A.makeIdentity(); A.scale3d(6, 7, 8); A.skewY(45); EXPECT_ROW1_EQ(6, 0, 0, 0, A); EXPECT_ROW2_EQ(7, 7, 0, 0, A); EXPECT_ROW3_EQ(0, 0, 8, 0, A); EXPECT_ROW4_EQ(0, 0, 0, 1, A); } TEST(WebTransformationMatrixTest, verifyApplyPerspective) { WebTransformationMatrix A; A.applyPerspective(1); EXPECT_ROW1_EQ(1, 0, 0, 0, A); EXPECT_ROW2_EQ(0, 1, 0, 0, A); EXPECT_ROW3_EQ(0, 0, 1, 0, A); EXPECT_ROW4_EQ(0, 0, -1, 1, A); // Verify that applyPerspective() post-multiplies the existing matrix. A.makeIdentity(); A.translate3d(2, 3, 4); A.applyPerspective(1); EXPECT_ROW1_EQ(1, 0, -2, 2, A); EXPECT_ROW2_EQ(0, 1, -3, 3, A); EXPECT_ROW3_EQ(0, 0, -3, 4, A); EXPECT_ROW4_EQ(0, 0, -1, 1, A); } TEST(WebTransformationMatrixTest, verifyHasPerspective) { WebTransformationMatrix A; A.applyPerspective(1); EXPECT_TRUE(A.hasPerspective()); A.makeIdentity(); A.applyPerspective(0); EXPECT_FALSE(A.hasPerspective()); A.makeIdentity(); A.setM34(-0.3); EXPECT_TRUE(A.hasPerspective()); // FIXME: WebCore only checkes m34() for perspective, but that is probably // wrong. https://bugs.webkit.org/show_bug.cgi?id=83088. For now, this test // case expects the exact behavior as implemented by WebCore, but this should // probably be changed so that if the entire bottom row is not exactly // (0, 0, 0, 1), then hasPerspective should return true. A.makeIdentity(); A.setM14(-1); EXPECT_FALSE(A.hasPerspective()); A.makeIdentity(); A.setM24(-1); EXPECT_FALSE(A.hasPerspective()); A.makeIdentity(); A.setM44(0.5); EXPECT_FALSE(A.hasPerspective()); } TEST(WebTransformationMatrixTest, verifyIsInvertible) { WebTransformationMatrix A; // Translations, rotations, scales, skews and arbitrary combinations of them are invertible. A.makeIdentity(); EXPECT_TRUE(A.isInvertible()); A.makeIdentity(); A.translate3d(2, 3, 4); EXPECT_TRUE(A.isInvertible()); A.makeIdentity(); A.scale3d(6, 7, 8); EXPECT_TRUE(A.isInvertible()); A.makeIdentity(); A.rotate3d(10, 20, 30); EXPECT_TRUE(A.isInvertible()); A.makeIdentity(); A.skewX(45); EXPECT_TRUE(A.isInvertible()); // A perspective matrix (projection plane at z=0) is invertible. The intuitive // explanation is that perspective is eqivalent to a skew of the w-axis; skews are // invertible. A.makeIdentity(); A.applyPerspective(1); EXPECT_TRUE(A.isInvertible()); // A "pure" perspective matrix derived by similar triangles, with m44() set to zero // (i.e. camera positioned at the origin), is not invertible. A.makeIdentity(); A.applyPerspective(1); A.setM44(0); EXPECT_FALSE(A.isInvertible()); // Adding more to a non-invertible matrix will not make it invertible in the general case. A.makeIdentity(); A.applyPerspective(1); A.setM44(0); A.scale3d(6, 7, 8); A.rotate3d(10, 20, 30); A.translate3d(6, 7, 8); EXPECT_FALSE(A.isInvertible()); // A degenerate matrix of all zeros is not invertible. A.makeIdentity(); A.setM11(0); A.setM22(0); A.setM33(0); A.setM44(0); EXPECT_FALSE(A.isInvertible()); } TEST(WebTransformationMatrixTest, verifyIsIdentity) { WebTransformationMatrix A; initializeTestMatrix(A); EXPECT_FALSE(A.isIdentity()); A.makeIdentity(); EXPECT_TRUE(A.isIdentity()); // Modifying any one individual element should cause the matrix to no longer be identity. A.makeIdentity(); A.setM11(2); EXPECT_FALSE(A.isIdentity()); A.makeIdentity(); A.setM12(2); EXPECT_FALSE(A.isIdentity()); A.makeIdentity(); A.setM13(2); EXPECT_FALSE(A.isIdentity()); A.makeIdentity(); A.setM14(2); EXPECT_FALSE(A.isIdentity()); A.makeIdentity(); A.setM21(2); EXPECT_FALSE(A.isIdentity()); A.makeIdentity(); A.setM22(2); EXPECT_FALSE(A.isIdentity()); A.makeIdentity(); A.setM23(2); EXPECT_FALSE(A.isIdentity()); A.makeIdentity(); A.setM24(2); EXPECT_FALSE(A.isIdentity()); A.makeIdentity(); A.setM31(2); EXPECT_FALSE(A.isIdentity()); A.makeIdentity(); A.setM32(2); EXPECT_FALSE(A.isIdentity()); A.makeIdentity(); A.setM33(2); EXPECT_FALSE(A.isIdentity()); A.makeIdentity(); A.setM34(2); EXPECT_FALSE(A.isIdentity()); A.makeIdentity(); A.setM41(2); EXPECT_FALSE(A.isIdentity()); A.makeIdentity(); A.setM42(2); EXPECT_FALSE(A.isIdentity()); A.makeIdentity(); A.setM43(2); EXPECT_FALSE(A.isIdentity()); A.makeIdentity(); A.setM44(2); EXPECT_FALSE(A.isIdentity()); } TEST(WebTransformationMatrixTest, verifyIsIdentityOrTranslation) { WebTransformationMatrix A; initializeTestMatrix(A); EXPECT_FALSE(A.isIdentityOrTranslation()); A.makeIdentity(); EXPECT_TRUE(A.isIdentityOrTranslation()); // Modifying any non-translation components should cause isIdentityOrTranslation() to // return false. NOTE: m41(), m42(), and m43() are the translation components, so // modifying them should still return true for isIdentityOrTranslation(). A.makeIdentity(); A.setM11(2); EXPECT_FALSE(A.isIdentityOrTranslation()); A.makeIdentity(); A.setM12(2); EXPECT_FALSE(A.isIdentityOrTranslation()); A.makeIdentity(); A.setM13(2); EXPECT_FALSE(A.isIdentityOrTranslation()); A.makeIdentity(); A.setM14(2); EXPECT_FALSE(A.isIdentityOrTranslation()); A.makeIdentity(); A.setM21(2); EXPECT_FALSE(A.isIdentityOrTranslation()); A.makeIdentity(); A.setM22(2); EXPECT_FALSE(A.isIdentityOrTranslation()); A.makeIdentity(); A.setM23(2); EXPECT_FALSE(A.isIdentityOrTranslation()); A.makeIdentity(); A.setM24(2); EXPECT_FALSE(A.isIdentityOrTranslation()); A.makeIdentity(); A.setM31(2); EXPECT_FALSE(A.isIdentityOrTranslation()); A.makeIdentity(); A.setM32(2); EXPECT_FALSE(A.isIdentityOrTranslation()); A.makeIdentity(); A.setM33(2); EXPECT_FALSE(A.isIdentityOrTranslation()); A.makeIdentity(); A.setM34(2); EXPECT_FALSE(A.isIdentityOrTranslation()); // Note carefully - expecting true here. A.makeIdentity(); A.setM41(2); EXPECT_TRUE(A.isIdentityOrTranslation()); // Note carefully - expecting true here. A.makeIdentity(); A.setM42(2); EXPECT_TRUE(A.isIdentityOrTranslation()); // Note carefully - expecting true here. A.makeIdentity(); A.setM43(2); EXPECT_TRUE(A.isIdentityOrTranslation()); A.makeIdentity(); A.setM44(2); EXPECT_FALSE(A.isIdentityOrTranslation()); } TEST(WebTransformationMatrixTest, verifyIsIntegerTranslation) { WebTransformationMatrix A; A.makeIdentity(); A.translate(2, 3); EXPECT_TRUE(A.isIntegerTranslation()); A.makeIdentity(); A.translate(2, 3); EXPECT_TRUE(A.isIntegerTranslation()); A.makeIdentity(); A.translate(2.00001, 3); EXPECT_FALSE(A.isIntegerTranslation()); A.makeIdentity(); A.translate(2, 2.99999); EXPECT_FALSE(A.isIntegerTranslation()); // Stacking many integer translations should ideally not accumulate any precision error. A.makeIdentity(); for (int i = 0; i < 100000; ++i) A.translate(2, 3); EXPECT_TRUE(A.isIntegerTranslation()); } TEST(WebTransformationMatrixTest, verifyBlendForTranslation) { WebTransformationMatrix from; from.translate3d(100, 200, 100); WebTransformationMatrix to; to.makeIdentity(); to.translate3d(200, 100, 300); to.blend(from, 0); EXPECT_TRANSFORMATION_MATRIX_EQ(from, to); to.makeIdentity(); to.translate3d(200, 100, 300); to.blend(from, 0.25); EXPECT_ROW1_EQ(1, 0, 0, 125, to); EXPECT_ROW2_EQ(0, 1, 0, 175, to); EXPECT_ROW3_EQ(0, 0, 1, 150, to); EXPECT_ROW4_EQ(0, 0, 0, 1, to); to.makeIdentity(); to.translate3d(200, 100, 300); to.blend(from, 0.5); EXPECT_ROW1_EQ(1, 0, 0, 150, to); EXPECT_ROW2_EQ(0, 1, 0, 150, to); EXPECT_ROW3_EQ(0, 0, 1, 200, to); EXPECT_ROW4_EQ(0, 0, 0, 1, to); to.makeIdentity(); to.translate3d(200, 100, 300); to.blend(from, 1); EXPECT_ROW1_EQ(1, 0, 0, 200, to); EXPECT_ROW2_EQ(0, 1, 0, 100, to); EXPECT_ROW3_EQ(0, 0, 1, 300, to); EXPECT_ROW4_EQ(0, 0, 0, 1, to); } TEST(WebTransformationMatrixTest, verifyBlendForScale) { WebTransformationMatrix from; from.scale3d(100, 200, 100); WebTransformationMatrix to; to.makeIdentity(); to.scale3d(200, 100, 300); to.blend(from, 0); EXPECT_TRANSFORMATION_MATRIX_EQ(from, to); to.makeIdentity(); to.scale3d(200, 100, 300); to.blend(from, 0.25); EXPECT_ROW1_EQ(125, 0, 0, 0, to); EXPECT_ROW2_EQ(0, 175, 0, 0, to); EXPECT_ROW3_EQ(0, 0, 150, 0, to); EXPECT_ROW4_EQ(0, 0, 0, 1, to); to.makeIdentity(); to.scale3d(200, 100, 300); to.blend(from, 0.5); EXPECT_ROW1_EQ(150, 0, 0, 0, to); EXPECT_ROW2_EQ(0, 150, 0, 0, to); EXPECT_ROW3_EQ(0, 0, 200, 0, to); EXPECT_ROW4_EQ(0, 0, 0, 1, to); to.makeIdentity(); to.scale3d(200, 100, 300); to.blend(from, 1); EXPECT_ROW1_EQ(200, 0, 0, 0, to); EXPECT_ROW2_EQ(0, 100, 0, 0, to); EXPECT_ROW3_EQ(0, 0, 300, 0, to); EXPECT_ROW4_EQ(0, 0, 0, 1, to); } TEST(WebTransformationMatrixTest, verifyBlendForSkewX) { WebTransformationMatrix from; from.skewX(0); WebTransformationMatrix to; to.makeIdentity(); to.skewX(45); to.blend(from, 0); EXPECT_TRANSFORMATION_MATRIX_EQ(from, to); to.makeIdentity(); to.skewX(45); to.blend(from, 0.5); EXPECT_ROW1_EQ(1, 0.5, 0, 0, to); EXPECT_ROW2_EQ(0, 1, 0, 0, to); EXPECT_ROW3_EQ(0, 0, 1, 0, to); EXPECT_ROW4_EQ(0, 0, 0, 1, to); to.makeIdentity(); to.skewX(45); to.blend(from, 0.25); EXPECT_ROW1_EQ(1, 0.25, 0, 0, to); EXPECT_ROW2_EQ(0, 1, 0, 0, to); EXPECT_ROW3_EQ(0, 0, 1, 0, to); EXPECT_ROW4_EQ(0, 0, 0, 1, to); to.makeIdentity(); to.skewX(45); to.blend(from, 1); EXPECT_ROW1_EQ(1, 1, 0, 0, to); EXPECT_ROW2_EQ(0, 1, 0, 0, to); EXPECT_ROW3_EQ(0, 0, 1, 0, to); EXPECT_ROW4_EQ(0, 0, 0, 1, to); } TEST(WebTransformationMatrixTest, verifyBlendForSkewY) { // NOTE CAREFULLY: Decomposition of skew and rotation terms of the matrix is // inherently underconstrained, and so it does not always compute the originally // intended skew parameters. The current implementation uses QR decomposition, which // decomposes the shear into a rotation + non-uniform scale. // // It is unlikely that the decomposition implementation will need to change very // often, so to get any test coverage, the compromise is to verify the exact matrix // that the blend() operation produces. // // This problem also potentially exists for skewX, but the current QR decomposition // implementation just happens to decompose those test matrices intuitively. WebTransformationMatrix from; from.skewY(0); WebTransformationMatrix to; to.makeIdentity(); to.skewY(45); to.blend(from, 0); EXPECT_TRANSFORMATION_MATRIX_EQ(from, to); to.makeIdentity(); to.skewY(45); to.blend(from, 0.25); EXPECT_ROW1_NEAR(1.0823489449280947471976333, 0.0464370719145053845178239, 0, 0, to, ERROR_THRESHOLD); EXPECT_ROW2_NEAR(0.2152925909665224513123150, 0.9541702441750861130032035, 0, 0, to, ERROR_THRESHOLD); EXPECT_ROW3_EQ(0, 0, 1, 0, to); EXPECT_ROW4_EQ(0, 0, 0, 1, to); to.makeIdentity(); to.skewY(45); to.blend(from, 0.5); EXPECT_ROW1_NEAR(1.1152212925809066312865525, 0.0676495144007326631996335, 0, 0, to, ERROR_THRESHOLD); EXPECT_ROW2_NEAR(0.4619397844342648662419037, 0.9519009045724774464858342, 0, 0, to, ERROR_THRESHOLD); EXPECT_ROW3_EQ(0, 0, 1, 0, to); EXPECT_ROW4_EQ(0, 0, 0, 1, to); // Unfortunately, this case suffers from uncomfortably large precision error. to.makeIdentity(); to.skewY(45); to.blend(from, 1); EXPECT_ROW1_NEAR(1, 0, 0, 0, to, LOOSE_ERROR_THRESHOLD); EXPECT_ROW2_NEAR(1, 1, 0, 0, to, LOOSE_ERROR_THRESHOLD); EXPECT_ROW3_EQ(0, 0, 1, 0, to); EXPECT_ROW4_EQ(0, 0, 0, 1, to); } TEST(WebTransformationMatrixTest, verifyBlendForRotationAboutX) { // Even though blending uses quaternions, axis-aligned rotations should blend the same // with quaternions or Euler angles. So we can test rotation blending by comparing // against manually specified matrices from Euler angles. WebTransformationMatrix from; from.rotate3d(1, 0, 0, 0); WebTransformationMatrix to; to.makeIdentity(); to.rotate3d(1, 0, 0, 90); to.blend(from, 0); EXPECT_TRANSFORMATION_MATRIX_EQ(from, to); double expectedRotationAngle = 22.5 * M_PI / 180.0; to.makeIdentity(); to.rotate3d(1, 0, 0, 90); to.blend(from, 0.25); EXPECT_ROW1_NEAR(1, 0, 0, 0, to, ERROR_THRESHOLD); EXPECT_ROW2_NEAR(0, cos(expectedRotationAngle), -sin(expectedRotationAngle), 0, to, ERROR_THRESHOLD); EXPECT_ROW3_NEAR(0, sin(expectedRotationAngle), cos(expectedRotationAngle), 0, to, ERROR_THRESHOLD); EXPECT_ROW4_EQ(0, 0, 0, 1, to); expectedRotationAngle = 45 * M_PI / 180.0; to.makeIdentity(); to.rotate3d(1, 0, 0, 90); to.blend(from, 0.5); EXPECT_ROW1_NEAR(1, 0, 0, 0, to, ERROR_THRESHOLD); EXPECT_ROW2_NEAR(0, cos(expectedRotationAngle), -sin(expectedRotationAngle), 0, to, ERROR_THRESHOLD); EXPECT_ROW3_NEAR(0, sin(expectedRotationAngle), cos(expectedRotationAngle), 0, to, ERROR_THRESHOLD); EXPECT_ROW4_EQ(0, 0, 0, 1, to); to.makeIdentity(); to.rotate3d(1, 0, 0, 90); to.blend(from, 1); EXPECT_ROW1_NEAR(1, 0, 0, 0, to, ERROR_THRESHOLD); EXPECT_ROW2_NEAR(0, 0, -1, 0, to, ERROR_THRESHOLD); EXPECT_ROW3_NEAR(0, 1, 0, 0, to, ERROR_THRESHOLD); EXPECT_ROW4_EQ(0, 0, 0, 1, to); } TEST(WebTransformationMatrixTest, verifyBlendForRotationAboutY) { WebTransformationMatrix from; from.rotate3d(0, 1, 0, 0); WebTransformationMatrix to; to.makeIdentity(); to.rotate3d(0, 1, 0, 90); to.blend(from, 0); EXPECT_TRANSFORMATION_MATRIX_EQ(from, to); double expectedRotationAngle = 22.5 * M_PI / 180.0; to.makeIdentity(); to.rotate3d(0, 1, 0, 90); to.blend(from, 0.25); EXPECT_ROW1_NEAR(cos(expectedRotationAngle), 0, sin(expectedRotationAngle), 0, to, ERROR_THRESHOLD); EXPECT_ROW2_NEAR(0, 1, 0, 0, to, ERROR_THRESHOLD); EXPECT_ROW3_NEAR(-sin(expectedRotationAngle), 0, cos(expectedRotationAngle), 0, to, ERROR_THRESHOLD); EXPECT_ROW4_EQ(0, 0, 0, 1, to); expectedRotationAngle = 45 * M_PI / 180.0; to.makeIdentity(); to.rotate3d(0, 1, 0, 90); to.blend(from, 0.5); EXPECT_ROW1_NEAR(cos(expectedRotationAngle), 0, sin(expectedRotationAngle), 0, to, ERROR_THRESHOLD); EXPECT_ROW2_NEAR(0, 1, 0, 0, to, ERROR_THRESHOLD); EXPECT_ROW3_NEAR(-sin(expectedRotationAngle), 0, cos(expectedRotationAngle), 0, to, ERROR_THRESHOLD); EXPECT_ROW4_EQ(0, 0, 0, 1, to); to.makeIdentity(); to.rotate3d(0, 1, 0, 90); to.blend(from, 1); EXPECT_ROW1_NEAR(0, 0, 1, 0, to, ERROR_THRESHOLD); EXPECT_ROW2_NEAR(0, 1, 0, 0, to, ERROR_THRESHOLD); EXPECT_ROW3_NEAR(-1, 0, 0, 0, to, ERROR_THRESHOLD); EXPECT_ROW4_EQ(0, 0, 0, 1, to); } TEST(WebTransformationMatrixTest, verifyBlendForRotationAboutZ) { WebTransformationMatrix from; from.rotate3d(0, 0, 1, 0); WebTransformationMatrix to; to.makeIdentity(); to.rotate3d(0, 0, 1, 90); to.blend(from, 0); EXPECT_TRANSFORMATION_MATRIX_EQ(from, to); double expectedRotationAngle = 22.5 * M_PI / 180.0; to.makeIdentity(); to.rotate3d(0, 0, 1, 90); to.blend(from, 0.25); EXPECT_ROW1_NEAR(cos(expectedRotationAngle), -sin(expectedRotationAngle), 0, 0, to, ERROR_THRESHOLD); EXPECT_ROW2_NEAR(sin(expectedRotationAngle), cos(expectedRotationAngle), 0, 0, to, ERROR_THRESHOLD); EXPECT_ROW3_NEAR(0, 0, 1, 0, to, ERROR_THRESHOLD); EXPECT_ROW4_EQ(0, 0, 0, 1, to); expectedRotationAngle = 45 * M_PI / 180.0; to.makeIdentity(); to.rotate3d(0, 0, 1, 90); to.blend(from, 0.5); EXPECT_ROW1_NEAR(cos(expectedRotationAngle), -sin(expectedRotationAngle), 0, 0, to, ERROR_THRESHOLD); EXPECT_ROW2_NEAR(sin(expectedRotationAngle), cos(expectedRotationAngle), 0, 0, to, ERROR_THRESHOLD); EXPECT_ROW3_NEAR(0, 0, 1, 0, to, ERROR_THRESHOLD); EXPECT_ROW4_EQ(0, 0, 0, 1, to); to.makeIdentity(); to.rotate3d(0, 0, 1, 90); to.blend(from, 1); EXPECT_ROW1_NEAR(0, -1, 0, 0, to, ERROR_THRESHOLD); EXPECT_ROW2_NEAR(1, 0, 0, 0, to, ERROR_THRESHOLD); EXPECT_ROW3_NEAR(0, 0, 1, 0, to, ERROR_THRESHOLD); EXPECT_ROW4_EQ(0, 0, 0, 1, to); } TEST(WebTransformationMatrixTest, verifyBlendForCompositeTransform) { // Verify that the blending was done with a decomposition in correct order by blending // a composite transform. // Using matrix x vector notation (Ax = b, where x is column vector), the ordering should be: // perspective * translation * rotation * skew * scale // // It is not as important (or meaningful) to check intermediate interpolations; order // of operations will be tested well enough by the end cases that are easier to // specify. WebTransformationMatrix from; WebTransformationMatrix to; WebTransformationMatrix expectedEndOfAnimation; expectedEndOfAnimation.applyPerspective(1); expectedEndOfAnimation.translate3d(10, 20, 30); expectedEndOfAnimation.rotate3d(0, 0, 1, 25); expectedEndOfAnimation.skewY(45); expectedEndOfAnimation.scale3d(6, 7, 8); to = expectedEndOfAnimation; to.blend(from, 0); EXPECT_TRANSFORMATION_MATRIX_EQ(from, to); to = expectedEndOfAnimation; to.blend(from, 1); // Recomposing the matrix results in a normalized matrix, so to verify we need to // normalize the expectedEndOfAnimation before comparing elements. Normalizing means // dividing everything by expectedEndOfAnimation.m44(). WebTransformationMatrix normalizedExpectedEndOfAnimation = expectedEndOfAnimation; WebTransformationMatrix normalizationMatrix; normalizationMatrix.setM11(1 / expectedEndOfAnimation.m44()); normalizationMatrix.setM22(1 / expectedEndOfAnimation.m44()); normalizationMatrix.setM33(1 / expectedEndOfAnimation.m44()); normalizationMatrix.setM44(1 / expectedEndOfAnimation.m44()); normalizedExpectedEndOfAnimation.multiply(normalizationMatrix); EXPECT_TRANSFORMATION_MATRIX_EQ(normalizedExpectedEndOfAnimation, to); } } // namespace
30.693009
151
0.653719
[ "vector", "transform" ]
b470c9e1e5a86c53a9acc4d9abf3299703fa0ccd
7,738
cpp
C++
tests/helics/system_tests/flagTests.cpp
aenkoji1/HELICS
91f4cbcfb2a003cae955521a22e83461cbf2b629
[ "BSD-3-Clause" ]
59
2019-06-26T22:40:37.000Z
2022-03-28T18:00:23.000Z
tests/helics/system_tests/flagTests.cpp
aenkoji1/HELICS
91f4cbcfb2a003cae955521a22e83461cbf2b629
[ "BSD-3-Clause" ]
748
2019-06-19T14:15:49.000Z
2022-03-31T17:26:18.000Z
tests/helics/system_tests/flagTests.cpp
aenkoji1/HELICS
91f4cbcfb2a003cae955521a22e83461cbf2b629
[ "BSD-3-Clause" ]
53
2019-07-19T17:22:21.000Z
2022-03-28T18:00:38.000Z
/* Copyright (c) 2017-2021, Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable Energy, LLC. See the top-level NOTICE for additional details. All rights reserved. SPDX-License-Identifier: BSD-3-Clause */ #include "../application_api/testFixtures.hpp" #include "helics/ValueFederates.hpp" #include "gtest/gtest.h" /** tests for the different flag options and considerations*/ struct flag_tests: public FederateTestFixture, public ::testing::Test { }; class flag_type_tests: public ::testing::TestWithParam<const char*>, public FederateTestFixture { }; /** test simple creation and destruction*/ TEST_P(flag_type_tests, optional_pub) { SetupTest<helics::ValueFederate>(GetParam(), 1, 1.0); auto vFed1 = GetFederateAs<helics::ValueFederate>(0); // register the publications auto& ipt1 = vFed1->registerInput<double>("ipt1"); auto& ipt2 = vFed1->registerInput<double>("ipt2"); auto& ipt3 = vFed1->registerInput<double>("ipt3"); ipt1.setOption(helics::defs::Options::CONNECTION_OPTIONAL); ipt1.addTarget("bob"); ipt2.addTarget("tom"); ipt3.addTarget("harry"); std::atomic<int> warnings{0}; vFed1->setLoggingCallback( [&warnings](int level, std::string_view /*unused*/, std::string_view /*unused*/) { if (level == HELICS_LOG_LEVEL_WARNING) { ++warnings; } }); vFed1->enterExecutingMode(); EXPECT_EQ(warnings.load(), 2); vFed1->finalize(); } TEST_P(flag_type_tests, optional_sub) { SetupTest<helics::ValueFederate>(GetParam(), 1, 1.0); auto vFed1 = GetFederateAs<helics::ValueFederate>(0); // register the publications auto& pub1 = vFed1->registerPublication<double>("pub1"); pub1.addTarget("bob"); pub1.setOption(helics::defs::Options::CONNECTION_OPTIONAL); pub1.addTarget("tom"); pub1.addTarget("harry"); std::atomic<int> warnings{0}; vFed1->setLoggingCallback( [&warnings](int level, std::string_view /*unused*/, std::string_view /*unused*/) { if (level == HELICS_LOG_LEVEL_WARNING) { ++warnings; } }); vFed1->enterExecutingMode(); EXPECT_EQ(warnings.load(), 1); EXPECT_TRUE(pub1.getOption(helics::defs::Options::CONNECTION_OPTIONAL)); vFed1->finalize(); } INSTANTIATE_TEST_SUITE_P(flag_tests, flag_type_tests, ::testing::ValuesIn(CoreTypes_single)); TEST_F(flag_tests, single_connection_test) { SetupTest<helics::ValueFederate>("test", 1, 1.0); auto vFed1 = GetFederateAs<helics::ValueFederate>(0); // register the publications auto& ipt1 = vFed1->registerGlobalInput<double>("ipt1"); auto& pub1 = vFed1->registerPublication<double>("pub1"); auto& pub2 = vFed1->registerPublication<double>("pub2"); ipt1.setOption(helics::defs::Options::SINGLE_CONNECTION_ONLY); pub1.addTarget("ipt1"); pub2.addTarget("ipt1"); EXPECT_THROW(vFed1->enterExecutingMode(), helics::ConnectionFailure); vFed1->finalize(); } TEST_F(flag_tests, single_connection_test_pub) { SetupTest<helics::ValueFederate>("test", 1, 1.0); auto vFed1 = GetFederateAs<helics::ValueFederate>(0); // register the publications auto& ipt1 = vFed1->registerGlobalInput<double>("ipt1"); auto& ipt2 = vFed1->registerGlobalInput<double>("ipt2"); auto& pub1 = vFed1->registerGlobalPublication<double>("pub1"); pub1.setOption(helics::defs::Options::SINGLE_CONNECTION_ONLY); ipt1.addTarget("pub1"); ipt2.addTarget("pub1"); EXPECT_THROW(vFed1->enterExecutingMode(), helics::ConnectionFailure); vFed1->finalize(); } TEST_F(flag_tests, type_match_check) { SetupTest<helics::ValueFederate>("test", 1, 1.0); auto vFed1 = GetFederateAs<helics::ValueFederate>(0); // register the publications auto& ipt1 = vFed1->registerGlobalInput<double>("ipt1"); vFed1->registerGlobalPublication<double>("pub1"); ipt1.setOption(helics::defs::Options::STRICT_TYPE_CHECKING); ipt1.addTarget("pub1"); vFed1->enterExecutingMode(); EXPECT_TRUE(ipt1.getOption(helics::defs::Options::STRICT_TYPE_CHECKING)); vFed1->finalize(); } TEST_F(flag_tests, type_mismatch_error) { SetupTest<helics::ValueFederate>("test", 1, 1.0); auto vFed1 = GetFederateAs<helics::ValueFederate>(0); // register the publications auto& ipt1 = vFed1->registerGlobalInput<double>("ipt1"); vFed1->registerGlobalPublication<std::vector<double>>("pub1"); ipt1.setOption(helics::defs::Options::STRICT_TYPE_CHECKING); ipt1.addTarget("pub1"); EXPECT_THROW(vFed1->enterExecutingMode(), helics::ConnectionFailure); vFed1->finalize(); } TEST_F(flag_tests, type_mismatch_error_fed_level) { SetupTest<helics::ValueFederate>("test", 1, 1.0); auto vFed1 = GetFederateAs<helics::ValueFederate>(0); vFed1->setFlagOption(helics::defs::Flags::STRICT_INPUT_TYPE_CHECKING); // register the publications auto& ipt1 = vFed1->registerGlobalInput<double>("ipt1"); vFed1->registerGlobalPublication<std::vector<double>>("pub1"); ipt1.addTarget("pub1"); EXPECT_THROW(vFed1->enterExecutingMode(), helics::ConnectionFailure); vFed1->finalize(); } TEST_F(flag_tests, type_mismatch_error2) { SetupTest<helics::ValueFederate>("test", 1, 1.0); auto vFed1 = GetFederateAs<helics::ValueFederate>(0); // register the publications auto& ipt1 = vFed1->registerGlobalInput("ipt1", "custom", "V"); vFed1->registerGlobalPublication("pub1", "other"); ipt1.setOption(helics::defs::Options::STRICT_TYPE_CHECKING); ipt1.addTarget("pub1"); EXPECT_THROW(vFed1->enterExecutingMode(), helics::ConnectionFailure); vFed1->finalize(); } TEST_F(flag_tests, slow_federate) { // this flag doesn't do anything yet for federates, this is just to verify it is acknowledged // and captured SetupTest<helics::ValueFederate>("test", 1, 1.0); auto vFed1 = GetFederateAs<helics::ValueFederate>(0); vFed1->setFlagOption(HELICS_FLAG_SLOW_RESPONDING); vFed1->enterExecutingMode(); EXPECT_TRUE(vFed1->getFlagOption(HELICS_FLAG_SLOW_RESPONDING)); vFed1->finalize(); } TEST_F(flag_tests, only_update_on_change_fedlevel) { SetupTest<helics::ValueFederate>("test", 1, 1.0); auto vFed1 = GetFederateAs<helics::ValueFederate>(0); vFed1->setFlagOption(helics::defs::Options::HANDLE_ONLY_UPDATE_ON_CHANGE); // register the publications auto& ipt1 = vFed1->registerGlobalInput("ipt1", "double", "V"); auto& pub1 = vFed1->registerGlobalPublication("pub1", "double"); ipt1.addTarget("pub1"); vFed1->enterExecutingMode(); pub1.publish(45.7); vFed1->requestTime(1.0); EXPECT_TRUE(ipt1.isUpdated()); double val = ipt1.getValue<double>(); EXPECT_EQ(val, 45.7); EXPECT_TRUE(!ipt1.isUpdated()); pub1.publish(45.7); vFed1->requestTime(2.0); EXPECT_TRUE(!ipt1.isUpdated()); vFed1->finalize(); } TEST_F(flag_tests, only_transmit_on_change_fedlevel) { SetupTest<helics::ValueFederate>("test", 1, 1.0); auto vFed1 = GetFederateAs<helics::ValueFederate>(0); vFed1->setFlagOption(helics::defs::Options::HANDLE_ONLY_TRANSMIT_ON_CHANGE); // register the publications auto& ipt1 = vFed1->registerGlobalInput("ipt1", "double", "V"); auto& pub1 = vFed1->registerGlobalPublication("pub1", "double"); ipt1.addTarget("pub1"); vFed1->enterExecutingMode(); pub1.publish(45.7); vFed1->requestTime(1.0); EXPECT_TRUE(ipt1.isUpdated()); double val = ipt1.getValue<double>(); EXPECT_EQ(val, 45.7); EXPECT_TRUE(!ipt1.isUpdated()); pub1.publish(45.7); vFed1->requestTime(2.0); EXPECT_TRUE(!ipt1.isUpdated()); vFed1->finalize(); }
33.497835
97
0.695658
[ "vector" ]
b47214572aa2e4b1dc8c002eb07506595d489b83
8,469
cpp
C++
osquery/sql/tests/sqlite_util_tests.cpp
poppyseedplehzr/osquery
c298718c2a6569ff1503fb0bc6f9d3ef7155f034
[ "BSD-3-Clause" ]
1
2016-08-05T00:17:46.000Z
2016-08-05T00:17:46.000Z
osquery/sql/tests/sqlite_util_tests.cpp
poppyseedplehzr/osquery
c298718c2a6569ff1503fb0bc6f9d3ef7155f034
[ "BSD-3-Clause" ]
1
2021-03-20T04:50:14.000Z
2021-03-20T04:50:14.000Z
osquery/sql/tests/sqlite_util_tests.cpp
poppyseedplehzr/osquery
c298718c2a6569ff1503fb0bc6f9d3ef7155f034
[ "BSD-3-Clause" ]
1
2019-04-16T10:35:15.000Z
2019-04-16T10:35:15.000Z
/* * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <iostream> #include <gtest/gtest.h> #include <osquery/core.h> #include <osquery/sql.h> #include "osquery/sql/sqlite_util.h" #include "osquery/tests/test_util.h" namespace osquery { class SQLiteUtilTests : public testing::Test {}; std::shared_ptr<SQLiteDBInstance> getTestDBC() { auto dbc = SQLiteDBManager::getUnique(); char* err = nullptr; std::vector<std::string> queries = { "CREATE TABLE test_table (username varchar(30) primary key, age int)", "INSERT INTO test_table VALUES (\"mike\", 23)", "INSERT INTO test_table VALUES (\"matt\", 24)"}; for (auto q : queries) { sqlite3_exec(dbc->db(), q.c_str(), nullptr, nullptr, &err); if (err != nullptr) { throw std::domain_error(std::string("Cannot create testing DBC's db: ") + err); } } return dbc; } TEST_F(SQLiteUtilTests, test_simple_query_execution) { // Access to the internal SQL implementation is only available in core. auto sql = SQL("SELECT * FROM time"); EXPECT_TRUE(sql.ok()); EXPECT_EQ(sql.rows().size(), 1U); } TEST_F(SQLiteUtilTests, test_sqlite_instance_manager) { auto dbc1 = SQLiteDBManager::get(); auto dbc2 = SQLiteDBManager::get(); EXPECT_NE(dbc1->db(), dbc2->db()); EXPECT_EQ(dbc1->db(), dbc1->db()); } TEST_F(SQLiteUtilTests, test_sqlite_instance) { // Don't do this at home kids. // Keep a copy of the internal DB and let the SQLiteDBInstance go oos. auto internal_db = SQLiteDBManager::get()->db(); // Compare the internal DB to another request with no SQLiteDBInstances // in scope, meaning the primary will be returned. EXPECT_EQ(internal_db, SQLiteDBManager::get()->db()); } TEST_F(SQLiteUtilTests, test_reset) { auto internal_db = SQLiteDBManager::get()->db(); ASSERT_NE(nullptr, internal_db); sqlite3_exec(internal_db, "create view test_view as select 'test';", nullptr, nullptr, nullptr); SQLiteDBManager::resetPrimary(); auto instance = SQLiteDBManager::get(); QueryData results; queryInternal("select * from test_view", results, instance->db()); // Assume the internal (primary) database we reset and recreated. EXPECT_EQ(results.size(), 0U); } TEST_F(SQLiteUtilTests, test_direct_query_execution) { auto dbc = getTestDBC(); QueryData results; auto status = queryInternal(kTestQuery, results, dbc->db()); EXPECT_TRUE(status.ok()); EXPECT_EQ(results, getTestDBExpectedResults()); } TEST_F(SQLiteUtilTests, test_passing_callback_no_data_param) { char* err = nullptr; auto dbc = getTestDBC(); sqlite3_exec(dbc->db(), kTestQuery.c_str(), queryDataCallback, nullptr, &err); EXPECT_TRUE(err != nullptr); if (err != nullptr) { sqlite3_free(err); } } TEST_F(SQLiteUtilTests, test_aggregate_query) { auto dbc = getTestDBC(); QueryData results; auto status = queryInternal(kTestQuery, results, dbc->db()); EXPECT_TRUE(status.ok()); EXPECT_EQ(results, getTestDBExpectedResults()); } TEST_F(SQLiteUtilTests, test_get_test_db_result_stream) { auto dbc = getTestDBC(); auto results = getTestDBResultStream(); for (auto r : results) { char* err_char = nullptr; sqlite3_exec(dbc->db(), (r.first).c_str(), nullptr, nullptr, &err_char); EXPECT_TRUE(err_char == nullptr); if (err_char != nullptr) { sqlite3_free(err_char); ASSERT_TRUE(false); } QueryData expected; auto status = queryInternal(kTestQuery, expected, dbc->db()); EXPECT_EQ(expected, r.second); } } TEST_F(SQLiteUtilTests, test_affected_tables) { auto dbc = getTestDBC(); QueryData results; auto status = queryInternal("SELECT * FROM time", results, dbc->db()); // Since the table scanned from "time", it should be recorded as affected. EXPECT_EQ(dbc->affected_tables_.count("time"), 1U); dbc->clearAffectedTables(); EXPECT_EQ(dbc->affected_tables_.size(), 0U); } TEST_F(SQLiteUtilTests, test_table_attributes_event_based) { { SQLInternal sql_internal("select * from process_events"); if (!isPlatform(PlatformType::TYPE_WINDOWS)) { EXPECT_TRUE(sql_internal.ok()); EXPECT_TRUE(sql_internal.eventBased()); } } { SQLInternal sql_internal("select * from time"); EXPECT_TRUE(sql_internal.ok()); EXPECT_FALSE(sql_internal.eventBased()); } } TEST_F(SQLiteUtilTests, test_get_query_columns) { auto dbc = getTestDBC(); TableColumns results; std::string query = "SELECT seconds, version FROM time JOIN osquery_info"; auto status = getQueryColumnsInternal(query, results, dbc->db()); ASSERT_TRUE(status.ok()); ASSERT_EQ(2U, results.size()); EXPECT_EQ(std::make_tuple( std::string("seconds"), INTEGER_TYPE, ColumnOptions::DEFAULT), results[0]); EXPECT_EQ(std::make_tuple( std::string("version"), TEXT_TYPE, ColumnOptions::DEFAULT), results[1]); query = "SELECT * FROM foo"; status = getQueryColumnsInternal(query, results, dbc->db()); ASSERT_FALSE(status.ok()); } TEST_F(SQLiteUtilTests, test_get_query_tables) { std::string query = "SELECT * FROM time, osquery_info, (SELECT * FROM file) ff GROUP BY pid"; std::vector<std::string> tables; auto status = getQueryTables(query, tables); EXPECT_TRUE(status.ok()); std::vector<std::string> expected = {"file", "time", "osquery_info"}; EXPECT_EQ(expected, tables); } std::vector<ColumnType> getTypes(const TableColumns& columns) { std::vector<ColumnType> types; for (const auto& col : columns) { types.push_back(std::get<1>(col)); } return types; } TEST_F(SQLiteUtilTests, test_query_planner) { using TypeList = std::vector<ColumnType>; auto dbc = getTestDBC(); TableColumns columns; std::string query = "select path, path from file"; getQueryColumnsInternal(query, columns, dbc->db()); EXPECT_EQ(getTypes(columns), TypeList({TEXT_TYPE, TEXT_TYPE})); query = "select path, seconds from file, time"; getQueryColumnsInternal(query, columns, dbc->db()); EXPECT_EQ(getTypes(columns), TypeList({TEXT_TYPE, INTEGER_TYPE})); query = "select path || path from file"; getQueryColumnsInternal(query, columns, dbc->db()); EXPECT_EQ(getTypes(columns), TypeList({TEXT_TYPE})); query = "select seconds, path || path from file, time"; getQueryColumnsInternal(query, columns, dbc->db()); EXPECT_EQ(getTypes(columns), TypeList({INTEGER_TYPE, TEXT_TYPE})); query = "select seconds, seconds from time"; getQueryColumnsInternal(query, columns, dbc->db()); EXPECT_EQ(getTypes(columns), TypeList({INTEGER_TYPE, INTEGER_TYPE})); query = "select count(*) from time"; getQueryColumnsInternal(query, columns, dbc->db()); EXPECT_EQ(getTypes(columns), TypeList({BIGINT_TYPE})); query = "select count(*), count(seconds), seconds from time"; getQueryColumnsInternal(query, columns, dbc->db()); EXPECT_EQ(getTypes(columns), TypeList({BIGINT_TYPE, BIGINT_TYPE, INTEGER_TYPE})); query = "select 1, 'path', path from file"; getQueryColumnsInternal(query, columns, dbc->db()); EXPECT_EQ(getTypes(columns), TypeList({INTEGER_TYPE, TEXT_TYPE, TEXT_TYPE})); query = "select weekday, day, count(*), seconds from time"; getQueryColumnsInternal(query, columns, dbc->db()); EXPECT_EQ(getTypes(columns), TypeList({TEXT_TYPE, INTEGER_TYPE, BIGINT_TYPE, INTEGER_TYPE})); query = "select seconds + 1 from time"; getQueryColumnsInternal(query, columns, dbc->db()); EXPECT_EQ(getTypes(columns), TypeList({BIGINT_TYPE})); query = "select seconds * seconds from time"; getQueryColumnsInternal(query, columns, dbc->db()); EXPECT_EQ(getTypes(columns), TypeList({BIGINT_TYPE})); query = "select seconds > 1, seconds, count(seconds) from time"; getQueryColumnsInternal(query, columns, dbc->db()); EXPECT_EQ(getTypes(columns), TypeList({INTEGER_TYPE, INTEGER_TYPE, BIGINT_TYPE})); query = "select f1.*, seconds, f2.directory from (select path || path from file) " "f1, file as f2, time"; getQueryColumnsInternal(query, columns, dbc->db()); EXPECT_EQ(getTypes(columns), TypeList({TEXT_TYPE, INTEGER_TYPE, TEXT_TYPE})); } }
32.448276
80
0.693588
[ "vector" ]
b475008d55c3031d4beb3554a931b7baa66c87dc
50,490
cpp
C++
src/pathtracer.cpp
MatisHudon/redner
97e173b7829c6d90e7d9d09d50fba43f3f21a821
[ "MIT" ]
2
2021-06-04T13:27:44.000Z
2022-03-16T06:21:15.000Z
pathtracer.cpp
Awcrr/redner
b4f57037af26b720d916bbaf26103a3499101a9f
[ "MIT" ]
null
null
null
pathtracer.cpp
Awcrr/redner
b4f57037af26b720d916bbaf26103a3499101a9f
[ "MIT" ]
null
null
null
#include "pathtracer.h" #include "scene.h" #include "pcg_sampler.h" #include "sobol_sampler.h" #include "parallel.h" #include "scene.h" #include "buffer.h" #include "camera.h" #include "intersection.h" #include "active_pixels.h" #include "shape.h" #include "material.h" #include "area_light.h" #include "envmap.h" #include "test_utils.h" #include "cuda_utils.h" #include "thrust_utils.h" #include "primary_intersection.h" #include "primary_contribution.h" #include "bsdf_sample.h" #include "path_contribution.h" #include <thrust/execution_policy.h> #include <thrust/fill.h> #include <thrust/sort.h> #include <thrust/reduce.h> #include <thrust/remove.h> void init_paths(BufferView<Vector3> throughputs, BufferView<Real> min_roughness, bool use_gpu) { DISPATCH(use_gpu, thrust::fill, throughputs.begin(), throughputs.end(), Vector3{1, 1, 1}); DISPATCH(use_gpu, thrust::fill, min_roughness.begin(), min_roughness.end(), Real(0)); } struct PathBuffer { PathBuffer(int max_bounces, int num_pixels, bool use_gpu, const ChannelInfo &channel_info) : num_pixels(num_pixels) { assert(max_bounces >= 0); // For forward path tracing, we need to allocate memory for // all bounces // For edge sampling, we need to allocate memory for // 2 * num_pixels paths (and 4 * num_pixels for those // shared between two path vertices). camera_samples = Buffer<CameraSample>(use_gpu, num_pixels); light_samples = Buffer<LightSample>(use_gpu, max_bounces * num_pixels); edge_light_samples = Buffer<LightSample>(use_gpu, 2 * num_pixels); bsdf_samples = Buffer<BSDFSample>(use_gpu, max_bounces * num_pixels); edge_bsdf_samples = Buffer<BSDFSample>(use_gpu, 2 * num_pixels); rays = Buffer<Ray>(use_gpu, (max_bounces + 1) * num_pixels); nee_rays = Buffer<Ray>(use_gpu, max_bounces * num_pixels); primary_ray_differentials = Buffer<RayDifferential>(use_gpu, num_pixels); ray_differentials = Buffer<RayDifferential>(use_gpu, (max_bounces + 1) * num_pixels); bsdf_ray_differentials = Buffer<RayDifferential>(use_gpu, max_bounces * num_pixels); edge_rays = Buffer<Ray>(use_gpu, 4 * num_pixels); edge_nee_rays = Buffer<Ray>(use_gpu, 2 * num_pixels); edge_ray_differentials = Buffer<RayDifferential>(use_gpu, 2 * num_pixels); primary_active_pixels = Buffer<int>(use_gpu, num_pixels); active_pixels = Buffer<int>(use_gpu, (max_bounces + 1) * num_pixels); edge_active_pixels = Buffer<int>(use_gpu, 4 * num_pixels); shading_isects = Buffer<Intersection>(use_gpu, (max_bounces + 1) * num_pixels); edge_shading_isects = Buffer<Intersection>(use_gpu, 4 * num_pixels); shading_points = Buffer<SurfacePoint>(use_gpu, (max_bounces + 1) * num_pixels); edge_shading_points = Buffer<SurfacePoint>(use_gpu, 4 * num_pixels); light_isects = Buffer<Intersection>(use_gpu, max_bounces * num_pixels); edge_light_isects = Buffer<Intersection>(use_gpu, 2 * num_pixels); light_points = Buffer<SurfacePoint>(use_gpu, max_bounces * num_pixels); edge_light_points = Buffer<SurfacePoint>(use_gpu, 2 * num_pixels); throughputs = Buffer<Vector3>(use_gpu, (max_bounces + 1) * num_pixels); edge_throughputs = Buffer<Vector3>(use_gpu, 4 * num_pixels); channel_multipliers = Buffer<Real>(use_gpu, 2 * channel_info.num_total_dimensions * num_pixels); min_roughness = Buffer<Real>(use_gpu, (max_bounces + 1) * num_pixels); edge_min_roughness = Buffer<Real>(use_gpu, 4 * num_pixels); // OptiX buffers optix_rays = Buffer<OptiXRay>(use_gpu, 2 * num_pixels); optix_hits = Buffer<OptiXHit>(use_gpu, 2 * num_pixels); // Derivatives buffers d_next_throughputs = Buffer<Vector3>(use_gpu, num_pixels); d_next_rays = Buffer<DRay>(use_gpu, num_pixels); d_next_ray_differentials = Buffer<RayDifferential>(use_gpu, num_pixels); d_next_points = Buffer<SurfacePoint>(use_gpu, num_pixels); d_throughputs = Buffer<Vector3>(use_gpu, num_pixels); d_rays = Buffer<DRay>(use_gpu, num_pixels); d_ray_differentials = Buffer<RayDifferential>(use_gpu, num_pixels); d_points = Buffer<SurfacePoint>(use_gpu, num_pixels); primary_edge_samples = Buffer<PrimaryEdgeSample>(use_gpu, num_pixels); secondary_edge_samples = Buffer<SecondaryEdgeSample>(use_gpu, num_pixels); primary_edge_records = Buffer<PrimaryEdgeRecord>(use_gpu, num_pixels); secondary_edge_records = Buffer<SecondaryEdgeRecord>(use_gpu, num_pixels); edge_contribs = Buffer<Real>(use_gpu, 2 * num_pixels); edge_surface_points = Buffer<Vector3>(use_gpu, 2 * num_pixels); tmp_light_samples = Buffer<LightSample>(use_gpu, num_pixels); tmp_bsdf_samples = Buffer<BSDFSample>(use_gpu, num_pixels); generic_texture_buffer = Buffer<Real>(use_gpu, channel_info.max_generic_texture_dimension * num_pixels); } int num_pixels; Buffer<CameraSample> camera_samples; Buffer<LightSample> light_samples, edge_light_samples; Buffer<BSDFSample> bsdf_samples, edge_bsdf_samples; Buffer<Ray> rays, nee_rays; Buffer<Ray> edge_rays, edge_nee_rays; Buffer<RayDifferential> primary_ray_differentials; Buffer<RayDifferential> ray_differentials, bsdf_ray_differentials; Buffer<RayDifferential> edge_ray_differentials; Buffer<int> primary_active_pixels, active_pixels, edge_active_pixels; Buffer<Intersection> shading_isects, edge_shading_isects; Buffer<SurfacePoint> shading_points, edge_shading_points; Buffer<Intersection> light_isects, edge_light_isects; Buffer<SurfacePoint> light_points, edge_light_points; Buffer<Vector3> throughputs, edge_throughputs; Buffer<Real> channel_multipliers; Buffer<Real> min_roughness, edge_min_roughness; // OptiX related Buffer<OptiXRay> optix_rays; Buffer<OptiXHit> optix_hits; // Derivatives related Buffer<Vector3> d_next_throughputs; Buffer<DRay> d_next_rays; Buffer<RayDifferential> d_next_ray_differentials; Buffer<SurfacePoint> d_next_points; Buffer<Vector3> d_throughputs; Buffer<DRay> d_rays; Buffer<RayDifferential> d_ray_differentials; Buffer<SurfacePoint> d_points; // Edge sampling related Buffer<PrimaryEdgeSample> primary_edge_samples; Buffer<SecondaryEdgeSample> secondary_edge_samples; Buffer<PrimaryEdgeRecord> primary_edge_records; Buffer<SecondaryEdgeRecord> secondary_edge_records; Buffer<Real> edge_contribs; Buffer<Vector3> edge_surface_points; // For sharing RNG between pixels Buffer<LightSample> tmp_light_samples; Buffer<BSDFSample> tmp_bsdf_samples; // For temporary storing generic texture values per thread Buffer<Real> generic_texture_buffer; }; // 1 2 3 4 5 -> 1 1 2 2 3 3 4 4 5 5 template <typename T> struct copy_interleave { DEVICE void operator()(int idx) { to[2 * idx + 0] = from[idx]; to[2 * idx + 1] = from[idx]; } const T *from; T *to; }; // Extract the position of a surface point struct get_position { DEVICE void operator()(int idx) { p[active_pixels[idx]] = sp[active_pixels[idx]].position; } const int *active_pixels; const SurfacePoint *sp; Vector3 *p; }; void render(const Scene &scene, const RenderOptions &options, ptr<float> rendered_image, ptr<float> d_rendered_image, std::shared_ptr<DScene> d_scene, ptr<float> screen_gradient_image, ptr<float> debug_image) { #ifdef __NVCC__ int old_device_id = -1; if (scene.use_gpu) { checkCuda(cudaGetDevice(&old_device_id)); if (scene.gpu_index != -1) { checkCuda(cudaSetDevice(scene.gpu_index)); } } #endif parallel_init(); if (d_rendered_image.get() != nullptr) { initialize_ltc_table(scene.use_gpu); } ChannelInfo channel_info(options.channels, scene.use_gpu, scene.max_generic_texture_dimension); // Some common variables const auto &camera = scene.camera; auto num_pixels = camera.width * camera.height; auto max_bounces = options.max_bounces; // A main difference between our path tracer and the usual path // tracer is that we need to store all the intermediate states // for later computation of derivatives. // Therefore we allocate a big buffer here for the storage. PathBuffer path_buffer(max_bounces, num_pixels, scene.use_gpu, channel_info); auto num_active_pixels = std::vector<int>((max_bounces + 1) * num_pixels, 0); std::unique_ptr<Sampler> sampler, edge_sampler; switch (options.sampler_type) { case SamplerType::independent: { sampler = std::unique_ptr<Sampler>(new PCGSampler(scene.use_gpu, options.seed, num_pixels)); edge_sampler = std::unique_ptr<Sampler>( new PCGSampler(scene.use_gpu, options.seed + 131071U, num_pixels)); break; } case SamplerType::sobol: { sampler = std::unique_ptr<Sampler>(new SobolSampler(scene.use_gpu, options.seed, num_pixels)); edge_sampler = std::unique_ptr<Sampler>( new SobolSampler(scene.use_gpu, options.seed + 131071U, num_pixels)); break; } default: { assert(false); break; } } auto optix_rays = path_buffer.optix_rays.view(0, 2 * num_pixels); auto optix_hits = path_buffer.optix_hits.view(0, 2 * num_pixels); ThrustCachedAllocator thrust_alloc(scene.use_gpu, num_pixels * sizeof(int)); // For each sample for (int sample_id = 0; sample_id < options.num_samples; sample_id++) { sampler->begin_sample(sample_id); // Buffer view for first intersection auto throughputs = path_buffer.throughputs.view(0, num_pixels); auto camera_samples = path_buffer.camera_samples.view(0, num_pixels); auto rays = path_buffer.rays.view(0, num_pixels); auto primary_differentials = path_buffer.primary_ray_differentials.view(0, num_pixels); auto ray_differentials = path_buffer.ray_differentials.view(0, num_pixels); auto shading_isects = path_buffer.shading_isects.view(0, num_pixels); auto shading_points = path_buffer.shading_points.view(0, num_pixels); auto primary_active_pixels = path_buffer.primary_active_pixels.view(0, num_pixels); auto active_pixels = path_buffer.active_pixels.view(0, num_pixels); auto min_roughness = path_buffer.min_roughness.view(0, num_pixels); auto generic_texture_buffer = path_buffer.generic_texture_buffer.view(0, path_buffer.generic_texture_buffer.size()); // Initialization init_paths(throughputs, min_roughness, scene.use_gpu); // Generate primary ray samples sampler->next_camera_samples(camera_samples, options.sample_pixel_center); sample_primary_rays(camera, camera_samples, rays, primary_differentials, scene.use_gpu); // Initialize pixel id init_active_pixels(rays, primary_active_pixels, scene.use_gpu, thrust_alloc); auto num_actives_primary = (int)primary_active_pixels.size(); // Intersect with the scene intersect(scene, primary_active_pixels, rays, primary_differentials, shading_isects, shading_points, ray_differentials, optix_rays, optix_hits); accumulate_primary_contribs(scene, primary_active_pixels, throughputs, BufferView<Real>(), // channel multipliers rays, ray_differentials, shading_isects, shading_points, Real(1) / options.num_samples, channel_info, rendered_image.get(), BufferView<Real>(), // edge_contrib generic_texture_buffer); // Stream compaction: remove invalid intersection update_active_pixels(primary_active_pixels, shading_isects, active_pixels, scene.use_gpu); std::fill(num_active_pixels.begin(), num_active_pixels.end(), 0); num_active_pixels[0] = active_pixels.size(); for (int depth = 0; depth < max_bounces && num_active_pixels[depth] > 0 && has_lights(scene); depth++) { // Buffer views for this path vertex const auto active_pixels = path_buffer.active_pixels.view(depth * num_pixels, num_active_pixels[depth]); auto light_samples = path_buffer.light_samples.view(depth * num_pixels, num_pixels); const auto shading_isects = path_buffer.shading_isects.view( depth * num_pixels, num_pixels); const auto shading_points = path_buffer.shading_points.view( depth * num_pixels, num_pixels); auto light_isects = path_buffer.light_isects.view(depth * num_pixels, num_pixels); auto light_points = path_buffer.light_points.view(depth * num_pixels, num_pixels); auto bsdf_samples = path_buffer.bsdf_samples.view(depth * num_pixels, num_pixels); auto incoming_rays = path_buffer.rays.view(depth * num_pixels, num_pixels); auto incoming_ray_differentials = path_buffer.ray_differentials.view(depth * num_pixels, num_pixels); auto bsdf_ray_differentials = path_buffer.bsdf_ray_differentials.view(depth * num_pixels, num_pixels); auto nee_rays = path_buffer.nee_rays.view(depth * num_pixels, num_pixels); auto next_rays = path_buffer.rays.view((depth + 1) * num_pixels, num_pixels); auto next_ray_differentials = path_buffer.ray_differentials.view((depth + 1) * num_pixels, num_pixels); auto bsdf_isects = path_buffer.shading_isects.view((depth + 1) * num_pixels, num_pixels); auto bsdf_points = path_buffer.shading_points.view((depth + 1) * num_pixels, num_pixels); const auto throughputs = path_buffer.throughputs.view(depth * num_pixels, num_pixels); auto next_throughputs = path_buffer.throughputs.view((depth + 1) * num_pixels, num_pixels); auto next_active_pixels = path_buffer.active_pixels.view((depth + 1) * num_pixels, num_pixels); auto min_roughness = path_buffer.min_roughness.view(depth * num_pixels, num_pixels); auto next_min_roughness = path_buffer.min_roughness.view((depth + 1) * num_pixels, num_pixels); // Sample points on lights sampler->next_light_samples(light_samples); sample_point_on_light(scene, active_pixels, shading_points, light_samples, light_isects, light_points, nee_rays); occluded(scene, active_pixels, nee_rays, optix_rays, optix_hits); // Sample directions based on BRDF sampler->next_bsdf_samples(bsdf_samples); bsdf_sample(scene, active_pixels, incoming_rays, incoming_ray_differentials, shading_isects, shading_points, bsdf_samples, min_roughness, next_rays, bsdf_ray_differentials, next_min_roughness); // Intersect with the scene intersect(scene, active_pixels, next_rays, bsdf_ray_differentials, bsdf_isects, bsdf_points, next_ray_differentials, optix_rays, optix_hits); // Compute path contribution & update throughput accumulate_path_contribs( scene, active_pixels, throughputs, incoming_rays, shading_isects, shading_points, light_isects, light_points, nee_rays, bsdf_isects, bsdf_points, next_rays, min_roughness, Real(1) / options.num_samples, channel_info, next_throughputs, rendered_image.get(), BufferView<Real>()); // Stream compaction: remove invalid bsdf intersections // active_pixels -> next_active_pixels update_active_pixels(active_pixels, bsdf_isects, next_active_pixels, scene.use_gpu); // Record the number of active pixels for next depth num_active_pixels[depth + 1] = next_active_pixels.size(); } if (d_rendered_image.get() != nullptr) { edge_sampler->begin_sample(sample_id); // Initialize the derivatives for path vertices auto d_throughputs = path_buffer.d_throughputs.view(0, num_pixels); auto d_rays = path_buffer.d_rays.view(0, num_pixels); auto d_ray_differentials = path_buffer.d_ray_differentials.view(0, num_pixels); auto d_points = path_buffer.d_points.view(0, num_pixels); auto d_next_throughputs = path_buffer.d_next_throughputs.view(0, num_pixels); auto d_next_rays = path_buffer.d_next_rays.view(0, num_pixels); auto d_next_ray_differentials = path_buffer.d_next_ray_differentials.view(0, num_pixels); auto d_next_points = path_buffer.d_next_points.view(0, num_pixels); DISPATCH(scene.use_gpu, thrust::fill, d_throughputs.begin(), d_throughputs.end(), Vector3{0, 0, 0}); DISPATCH(scene.use_gpu, thrust::fill, d_rays.begin(), d_rays.end(), DRay{}); DISPATCH(scene.use_gpu, thrust::fill, d_ray_differentials.begin(), d_ray_differentials.end(), RayDifferential{Vector3{0, 0, 0}, Vector3{0, 0, 0}, Vector3{0, 0, 0}, Vector3{0, 0, 0}}); DISPATCH(scene.use_gpu, thrust::fill, d_points.begin(), d_points.end(), SurfacePoint::zero()); DISPATCH(scene.use_gpu, thrust::fill, d_next_throughputs.begin(), d_next_throughputs.end(), Vector3{0, 0, 0}); DISPATCH(scene.use_gpu, thrust::fill, d_next_rays.begin(), d_next_rays.end(), DRay{}); DISPATCH(scene.use_gpu, thrust::fill, d_next_ray_differentials.begin(), d_next_ray_differentials.end(), RayDifferential{Vector3{0, 0, 0}, Vector3{0, 0, 0}, Vector3{0, 0, 0}, Vector3{0, 0, 0}}); DISPATCH(scene.use_gpu, thrust::fill, d_next_points.begin(), d_next_points.end(), SurfacePoint::zero()); // Traverse the path backward for the derivatives for (int depth = max_bounces - 1; depth >= 0 && has_lights(scene); depth--) { // Buffer views for this path vertex auto num_actives = num_active_pixels[depth]; if (num_actives <= 0) { continue; } auto active_pixels = path_buffer.active_pixels.view(depth * num_pixels, num_actives); auto d_next_throughputs = path_buffer.d_next_throughputs.view(0, num_pixels); auto d_next_rays = path_buffer.d_next_rays.view(0, num_pixels); auto d_next_ray_differentials = path_buffer.d_next_ray_differentials.view(0, num_pixels); auto d_next_points = path_buffer.d_next_points.view(0, num_pixels); auto throughputs = path_buffer.throughputs.view(depth * num_pixels, num_pixels); auto incoming_rays = path_buffer.rays.view(depth * num_pixels, num_pixels); auto incoming_ray_differentials = path_buffer.ray_differentials.view(depth * num_pixels, num_pixels); auto next_rays = path_buffer.rays.view((depth + 1) * num_pixels, num_pixels); auto bsdf_ray_differentials = path_buffer.bsdf_ray_differentials.view(depth * num_pixels, num_pixels); auto nee_rays = path_buffer.nee_rays.view(depth * num_pixels, num_pixels); auto light_samples = path_buffer.light_samples.view( depth * num_pixels, num_pixels); auto bsdf_samples = path_buffer.bsdf_samples.view(depth * num_pixels, num_pixels); auto shading_isects = path_buffer.shading_isects.view( depth * num_pixels, num_pixels); auto shading_points = path_buffer.shading_points.view( depth * num_pixels, num_pixels); auto light_isects = path_buffer.light_isects.view(depth * num_pixels, num_pixels); auto light_points = path_buffer.light_points.view(depth * num_pixels, num_pixels); auto bsdf_isects = path_buffer.shading_isects.view( (depth + 1) * num_pixels, num_pixels); auto bsdf_points = path_buffer.shading_points.view( (depth + 1) * num_pixels, num_pixels); auto min_roughness = path_buffer.min_roughness.view(depth * num_pixels, num_pixels); auto d_throughputs = path_buffer.d_throughputs.view(0, num_pixels); auto d_rays = path_buffer.d_rays.view(0, num_pixels); auto d_ray_differentials = path_buffer.d_ray_differentials.view(0, num_pixels); auto d_points = path_buffer.d_points.view(0, num_pixels); // Backpropagate path contribution d_accumulate_path_contribs( scene, active_pixels, throughputs, incoming_rays, incoming_ray_differentials, light_samples, bsdf_samples, shading_isects, shading_points, light_isects, light_points, nee_rays, bsdf_isects, bsdf_points, next_rays, bsdf_ray_differentials, min_roughness, Real(1) / options.num_samples, // weight channel_info, d_rendered_image.get(), d_next_throughputs, d_next_rays, d_next_ray_differentials, d_next_points, d_scene.get(), d_throughputs, d_rays, d_ray_differentials, d_points); if (scene.use_secondary_edge_sampling) { //////////////////////////////////////////////////////////////////////////////// // Sample edges for secondary visibility auto num_edge_samples = 2 * num_actives; auto edge_samples = path_buffer.secondary_edge_samples.view(0, num_actives); edge_sampler->next_secondary_edge_samples(edge_samples); auto edge_records = path_buffer.secondary_edge_records.view(0, num_actives); auto edge_rays = path_buffer.edge_rays.view(0, num_edge_samples); auto edge_ray_differentials = path_buffer.edge_ray_differentials.view(0, num_edge_samples); auto edge_throughputs = path_buffer.edge_throughputs.view(0, num_edge_samples); auto edge_shading_isects = path_buffer.edge_shading_isects.view(0, num_edge_samples); auto edge_shading_points = path_buffer.edge_shading_points.view(0, num_edge_samples); auto edge_min_roughness = path_buffer.edge_min_roughness.view(0, num_edge_samples); sample_secondary_edges( scene, active_pixels, edge_samples, incoming_rays, incoming_ray_differentials, shading_isects, shading_points, nee_rays, light_isects, light_points, throughputs, min_roughness, d_rendered_image.get(), channel_info, edge_records, edge_rays, edge_ray_differentials, edge_throughputs, edge_min_roughness); // Now we path trace these edges auto edge_active_pixels = path_buffer.edge_active_pixels.view(0, num_edge_samples); init_active_pixels(edge_rays, edge_active_pixels, scene.use_gpu, thrust_alloc); // Intersect with the scene intersect(scene, edge_active_pixels, edge_rays, edge_ray_differentials, edge_shading_isects, edge_shading_points, edge_ray_differentials, optix_rays, optix_hits); // Update edge throughputs: take geometry terms and Jacobians into account update_secondary_edge_weights(scene, active_pixels, shading_points, edge_shading_isects, edge_shading_points, edge_records, edge_throughputs); // Initialize edge contribution auto edge_contribs = path_buffer.edge_contribs.view(0, num_edge_samples); DISPATCH(scene.use_gpu, thrust::fill, edge_contribs.begin(), edge_contribs.end(), 0); accumulate_primary_contribs( scene, edge_active_pixels, edge_throughputs, BufferView<Real>(), // channel multipliers edge_rays, edge_ray_differentials, edge_shading_isects, edge_shading_points, Real(1) / options.num_samples, channel_info, nullptr, edge_contribs, generic_texture_buffer); // Stream compaction: remove invalid intersections update_active_pixels(edge_active_pixels, edge_shading_isects, edge_active_pixels, scene.use_gpu); auto num_active_edge_samples = edge_active_pixels.size(); // Record the hit points for derivatives computation later auto edge_surface_points = path_buffer.edge_surface_points.view(0, num_active_edge_samples); parallel_for(get_position{ edge_active_pixels.begin(), edge_shading_points.begin(), edge_surface_points.begin()}, num_active_edge_samples, scene.use_gpu); for (int edge_depth = depth + 1; edge_depth < max_bounces && num_active_edge_samples > 0; edge_depth++) { // Path tracing loop for secondary edges auto edge_depth_ = edge_depth - (depth + 1); auto main_buffer_beg = (edge_depth_ % 2) * (2 * num_pixels); auto next_buffer_beg = ((edge_depth_ + 1) % 2) * (2 * num_pixels); const auto active_pixels = path_buffer.edge_active_pixels.view( main_buffer_beg, num_active_edge_samples); auto light_samples = path_buffer.edge_light_samples.view(0, num_edge_samples); auto bsdf_samples = path_buffer.edge_bsdf_samples.view(0, num_edge_samples); auto tmp_light_samples = path_buffer.tmp_light_samples.view(0, num_actives); auto tmp_bsdf_samples = path_buffer.tmp_bsdf_samples.view(0, num_actives); auto shading_isects = path_buffer.edge_shading_isects.view(main_buffer_beg, num_edge_samples); auto shading_points = path_buffer.edge_shading_points.view(main_buffer_beg, num_edge_samples); auto light_isects = path_buffer.edge_light_isects.view(0, num_edge_samples); auto light_points = path_buffer.edge_light_points.view(0, num_edge_samples); auto incoming_rays = path_buffer.edge_rays.view(main_buffer_beg, num_edge_samples); auto ray_differentials = path_buffer.edge_ray_differentials.view(0, num_edge_samples); auto nee_rays = path_buffer.edge_nee_rays.view(0, num_edge_samples); auto next_rays = path_buffer.edge_rays.view(next_buffer_beg, num_edge_samples); auto bsdf_isects = path_buffer.edge_shading_isects.view( next_buffer_beg, num_edge_samples); auto bsdf_points = path_buffer.edge_shading_points.view( next_buffer_beg, num_edge_samples); const auto throughputs = path_buffer.edge_throughputs.view( main_buffer_beg, num_edge_samples); auto next_throughputs = path_buffer.edge_throughputs.view( next_buffer_beg, num_edge_samples); auto next_active_pixels = path_buffer.edge_active_pixels.view( next_buffer_beg, num_edge_samples); auto edge_min_roughness = path_buffer.edge_min_roughness.view(main_buffer_beg, num_edge_samples); auto edge_next_min_roughness = path_buffer.edge_min_roughness.view(next_buffer_beg, num_edge_samples); // Sample points on lights edge_sampler->next_light_samples(tmp_light_samples); // Copy the samples parallel_for(copy_interleave<LightSample>{ tmp_light_samples.begin(), light_samples.begin()}, tmp_light_samples.size(), scene.use_gpu); sample_point_on_light( scene, active_pixels, shading_points, light_samples, light_isects, light_points, nee_rays); occluded(scene, active_pixels, nee_rays, optix_rays, optix_hits); // Sample directions based on BRDF edge_sampler->next_bsdf_samples(tmp_bsdf_samples); // Copy the samples parallel_for(copy_interleave<BSDFSample>{ tmp_bsdf_samples.begin(), bsdf_samples.begin()}, tmp_bsdf_samples.size(), scene.use_gpu); bsdf_sample(scene, active_pixels, incoming_rays, ray_differentials, shading_isects, shading_points, bsdf_samples, edge_min_roughness, next_rays, ray_differentials, edge_next_min_roughness); // Intersect with the scene intersect(scene, active_pixels, next_rays, ray_differentials, bsdf_isects, bsdf_points, ray_differentials, optix_rays, optix_hits); // Compute path contribution & update throughput accumulate_path_contribs( scene, active_pixels, throughputs, incoming_rays, shading_isects, shading_points, light_isects, light_points, nee_rays, bsdf_isects, bsdf_points, next_rays, edge_min_roughness, Real(1) / options.num_samples, channel_info, next_throughputs, nullptr, edge_contribs); // Stream compaction: remove invalid bsdf intersections // active_pixels -> next_active_pixels update_active_pixels(active_pixels, bsdf_isects, next_active_pixels, scene.use_gpu); num_active_edge_samples = next_active_pixels.size(); } // Now the path traced contribution for the edges is stored in edge_contribs // We'll compute the derivatives w.r.t. three points: two on edges and one on // the shading point accumulate_secondary_edge_derivatives(scene, active_pixels, shading_points, edge_records, edge_surface_points, edge_contribs, d_points, d_scene->shapes.view(0, d_scene->shapes.size())); //////////////////////////////////////////////////////////////////////////////// } // Previous become next std::swap(path_buffer.d_next_throughputs, path_buffer.d_throughputs); std::swap(path_buffer.d_next_rays, path_buffer.d_rays); std::swap(path_buffer.d_next_ray_differentials, path_buffer.d_ray_differentials); std::swap(path_buffer.d_next_points, path_buffer.d_points); } // Backpropagate from first vertex to camera // Buffer view for first intersection if (num_actives_primary > 0) { const auto primary_active_pixels = path_buffer.primary_active_pixels.view(0, num_actives_primary); const auto throughputs = path_buffer.throughputs.view(0, num_pixels); const auto camera_samples = path_buffer.camera_samples.view(0, num_pixels); const auto rays = path_buffer.rays.view(0, num_pixels); const auto primary_ray_differentials = path_buffer.primary_ray_differentials.view(0, num_pixels); const auto ray_differentials = path_buffer.ray_differentials.view(0, num_pixels); const auto shading_isects = path_buffer.shading_isects.view(0, num_pixels); const auto shading_points = path_buffer.shading_points.view(0, num_pixels); const auto d_rays = path_buffer.d_next_rays.view(0, num_pixels); const auto d_ray_differentials = path_buffer.d_next_ray_differentials.view(0, num_pixels); auto d_points = path_buffer.d_next_points.view(0, num_pixels); d_accumulate_primary_contribs(scene, primary_active_pixels, throughputs, BufferView<Real>(), // channel multiplers rays, ray_differentials, shading_isects, shading_points, Real(1) / options.num_samples, channel_info, d_rendered_image.get(), generic_texture_buffer, d_scene.get(), d_rays, d_ray_differentials, d_points); // Propagate to camera d_primary_intersection(scene, primary_active_pixels, camera_samples, rays, primary_ray_differentials, shading_isects, d_rays, d_ray_differentials, d_points, d_scene.get(), screen_gradient_image.get()); } ///////////////////////////////////////////////////////////////////////////////// // Sample primary edges for geometric derivatives if (scene.use_primary_edge_sampling && scene.edge_sampler.edges.size() > 0) { auto primary_edge_samples = path_buffer.primary_edge_samples.view(0, num_pixels); auto edge_records = path_buffer.primary_edge_records.view(0, num_pixels); auto rays = path_buffer.edge_rays.view(0, 2 * num_pixels); auto ray_differentials = path_buffer.edge_ray_differentials.view(0, 2 * num_pixels); auto throughputs = path_buffer.edge_throughputs.view(0, 2 * num_pixels); auto channel_multipliers = path_buffer.channel_multipliers.view( 0, 2 * channel_info.num_total_dimensions * num_pixels); auto shading_isects = path_buffer.edge_shading_isects.view(0, 2 * num_pixels); auto shading_points = path_buffer.edge_shading_points.view(0, 2 * num_pixels); auto active_pixels = path_buffer.edge_active_pixels.view(0, 2 * num_pixels); auto edge_contribs = path_buffer.edge_contribs.view(0, 2 * num_pixels); auto edge_min_roughness = path_buffer.edge_min_roughness.view(0, 2 * num_pixels); // Initialize edge contribution DISPATCH(scene.use_gpu, thrust::fill, edge_contribs.begin(), edge_contribs.end(), 0); // Initialize max roughness DISPATCH(scene.use_gpu, thrust::fill, edge_min_roughness.begin(), edge_min_roughness.end(), 0); // Generate rays & weights for edge sampling edge_sampler->next_primary_edge_samples(primary_edge_samples); sample_primary_edges(scene, primary_edge_samples, d_rendered_image.get(), channel_info, edge_records, rays, ray_differentials, throughputs, channel_multipliers); // Initialize pixel id init_active_pixels(rays, active_pixels, scene.use_gpu, thrust_alloc); // Intersect with the scene intersect(scene, active_pixels, rays, ray_differentials, shading_isects, shading_points, ray_differentials, optix_rays, optix_hits); update_primary_edge_weights(scene, edge_records, shading_isects, channel_info, throughputs, channel_multipliers); accumulate_primary_contribs(scene, active_pixels, throughputs, channel_multipliers, rays, ray_differentials, shading_isects, shading_points, Real(1) / options.num_samples, channel_info, nullptr, // rendered_image edge_contribs, generic_texture_buffer); // Stream compaction: remove invalid intersections update_active_pixels(active_pixels, shading_isects, active_pixels, scene.use_gpu); auto active_pixels_size = active_pixels.size(); for (int depth = 0; depth < max_bounces && active_pixels_size > 0 && has_lights(scene); depth++) { // Buffer views for this path vertex auto main_buffer_beg = (depth % 2) * (2 * num_pixels); auto next_buffer_beg = ((depth + 1) % 2) * (2 * num_pixels); const auto active_pixels = path_buffer.edge_active_pixels.view(main_buffer_beg, active_pixels_size); auto light_samples = path_buffer.edge_light_samples.view(0, 2 * num_pixels); auto bsdf_samples = path_buffer.edge_bsdf_samples.view(0, 2 * num_pixels); auto tmp_light_samples = path_buffer.tmp_light_samples.view(0, num_pixels); auto tmp_bsdf_samples = path_buffer.tmp_bsdf_samples.view(0, num_pixels); auto shading_isects = path_buffer.edge_shading_isects.view(main_buffer_beg, 2 * num_pixels); auto shading_points = path_buffer.edge_shading_points.view(main_buffer_beg, 2 * num_pixels); auto light_isects = path_buffer.edge_light_isects.view(0, 2 * num_pixels); auto light_points = path_buffer.edge_light_points.view(0, 2 * num_pixels); auto nee_rays = path_buffer.edge_nee_rays.view(0, 2 * num_pixels); auto incoming_rays = path_buffer.edge_rays.view(main_buffer_beg, 2 * num_pixels); auto ray_differentials = path_buffer.edge_ray_differentials.view(0, 2 * num_pixels); auto next_rays = path_buffer.edge_rays.view(next_buffer_beg, 2 * num_pixels); auto bsdf_isects = path_buffer.edge_shading_isects.view( next_buffer_beg, 2 * num_pixels); auto bsdf_points = path_buffer.edge_shading_points.view( next_buffer_beg, 2 * num_pixels); const auto throughputs = path_buffer.edge_throughputs.view( main_buffer_beg, 2 * num_pixels); auto next_throughputs = path_buffer.edge_throughputs.view( next_buffer_beg, 2 * num_pixels); auto next_active_pixels = path_buffer.edge_active_pixels.view( next_buffer_beg, 2 * num_pixels); auto edge_min_roughness = path_buffer.edge_min_roughness.view(main_buffer_beg, 2 * num_pixels); auto edge_next_min_roughness = path_buffer.edge_min_roughness.view(next_buffer_beg, 2 * num_pixels); // Sample points on lights edge_sampler->next_light_samples(tmp_light_samples); // Copy the samples parallel_for(copy_interleave<LightSample>{ tmp_light_samples.begin(), light_samples.begin()}, tmp_light_samples.size(), scene.use_gpu); sample_point_on_light( scene, active_pixels, shading_points, light_samples, light_isects, light_points, nee_rays); occluded(scene, active_pixels, nee_rays, optix_rays, optix_hits); // Sample directions based on BRDF edge_sampler->next_bsdf_samples(tmp_bsdf_samples); // Copy the samples parallel_for(copy_interleave<BSDFSample>{ tmp_bsdf_samples.begin(), bsdf_samples.begin()}, tmp_bsdf_samples.size(), scene.use_gpu); bsdf_sample(scene, active_pixels, incoming_rays, ray_differentials, shading_isects, shading_points, bsdf_samples, edge_min_roughness, next_rays, ray_differentials, edge_next_min_roughness); // Intersect with the scene intersect(scene, active_pixels, next_rays, ray_differentials, bsdf_isects, bsdf_points, ray_differentials, optix_rays, optix_hits); // Compute path contribution & update throughput accumulate_path_contribs( scene, active_pixels, throughputs, incoming_rays, shading_isects, shading_points, light_isects, light_points, nee_rays, bsdf_isects, bsdf_points, next_rays, edge_min_roughness, Real(1) / options.num_samples, channel_info, next_throughputs, nullptr, edge_contribs); // Stream compaction: remove invalid bsdf intersections // active_pixels -> next_active_pixels update_active_pixels(active_pixels, bsdf_isects, next_active_pixels, scene.use_gpu); active_pixels_size = next_active_pixels.size(); } // Convert edge contributions to vertex derivatives compute_primary_edge_derivatives( scene, edge_records, edge_contribs, d_scene->shapes.view(0, d_scene->shapes.size()), d_scene->camera, screen_gradient_image.get()); } ///////////////////////////////////////////////////////////////////////////////// } } if (scene.use_gpu) { cuda_synchronize(); } channel_info.free(); parallel_cleanup(); #ifdef __NVCC__ if (old_device_id != -1) { checkCuda(cudaSetDevice(old_device_id)); } #endif }
52.758621
114
0.535215
[ "geometry", "render", "shape", "vector" ]
b476ab06a13160301b4716564b2b70f371d5deaa
3,736
cpp
C++
problemsets/SPOJ/SPOJ - BR/Seletivas/TIROS/tiros.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/SPOJ/SPOJ - BR/Seletivas/TIROS/tiros.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/SPOJ/SPOJ - BR/Seletivas/TIROS/tiros.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
/** * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * */ #include <iostream> #include <string> #include <sstream> #include <vector> #include <algorithm> #include <cstdio> #include <cstdlib> #include <cmath> #include <queue> #include <stack> #include <map> #include <set> #define FOR(i,n) for((i)=0;(i)<(n);(i)++) #define FORN(i,n) for((i)=(n)-1;(i)>=0;(i)--) #define _FORIT(it, b, e) for (__typeof(b) it = (b); it != (e); it++) #define FORIT(x...) _FORIT(x) #define ALL(v) (v).begin(), (v).end() #define RALL(v) (v).rbegin(), (v).rend() #define SI(a) ((a).size()) #define PB push_back #define MP make_pair #define CLR(a,v) memset((a),(v),sizeof(a)) #define TLE while(1); #define RTE printf("%d", 1/0); using namespace std; typedef vector<int> VI; typedef vector<double> VD; typedef vector<string> VS; typedef vector<vector<int> > VVI; typedef vector<vector<string> > VVS; typedef set<int> SI; typedef set<double> SD; typedef set<string> SS; typedef pair<int,int> PII; typedef signed long long i64; typedef unsigned long long u64; #define EPS 1E-14 #define INF 0x3F3F3F3F #define DINF 1E16 #define NULO -1 inline int cmp(double x, double y = 0, double tol = EPS) { return (x <= y + tol) ? (x + tol < y) ? -1 : 0 : 1; } int n, t; struct point { double x, y; point(double x = 0, double y = 0): x(x), y(y) {} point operator +(point q) { return point(x + q.x, y + q.y); } point operator -(point q) { return point(x - q.x, y - q.y); } point operator *(double t) { return point(x * t, y * t); } point operator /(double t) { return point(x / t, y / t); } double operator *(point q) { return x * q.x + y * q.y; } double operator %(point q) { return x * q.y - y * q.x; } int cmp(point q) const { if (int t = ::cmp(x, q.x)) return t; return ::cmp(y, q.y); } bool operator ==(point q) const { return cmp(q) == 0; } bool operator !=(point q) const { return cmp(q) != 0; } bool operator < (point q) const { return cmp(q) < 0; } static point pivot; }; point point::pivot; /******************************************************************************* * Retorna <0, 0, >0 para cw, colinear, ccw */ inline int ccw(point p, point q, point r) { return cmp((p - r) % (q - r)); } /******************************************************************************* * Compara??o radial. */ bool radial_lt(point p, point q) { point P = p - point::pivot, Q = q - point::pivot; double R = P % Q; return (cmp(R)) ? R > 0 : cmp(P * P, Q * Q) < 0; } bool cart_lt(point a, point b) { return cmp(a.y,b.y) ? (a.y<b.y) : (a.x<b.x); } /******************************************************************************* * Conta a quantidade m?xima de pontos que passam em uma ?nica reta. * Dep: ccw, radial_lt. O(n^2logn) */ int max_colin(vector<point>& T) { int i, j, s, n = SI(T); if (n==1) return 1; int maxi = 2; sort(ALL(T), cart_lt); FOR(i, n) { point::pivot = T[i]; sort(T.begin()+i, T.end(), radial_lt); for (j = i+1, s = 2; j < n-1; j++) ccw(T[i], T[j], T[j+1])==0 ? (s++, maxi>?=s) : s = 2; } return maxi; } int get_int() { int ch, i, s; while (((ch = getchar()) == ' ') || (ch == '\n')); s = (ch=='-')?(ch=getchar(),-1):1; for (i = 0; ch >= '0' && ch <= '9'; ch = getchar() ) i = (i<<3)+(i<<1)+(ch-'0'); return s*i; } int main() { int i, j; int s; for (t = get_int(); t--; ) { n = get_int(); vector<point> p(n); for (i = 0; i < n; i++) p[i].x = get_int(), p[i].y = get_int(); if (n<2) { printf("%d\n", n); continue; } printf("%d\n", max_colin(p)); } return 0; }
28.090226
84
0.507762
[ "vector" ]
b47f3c7a467f37221227ea667924187aef65c2ad
3,262
cc
C++
open_spiel/examples/matrix_example.cc
texasmichelle/open_spiel
d9a9b8f9f1f44143867217fc3f6ff2db71b174b0
[ "Apache-2.0" ]
3,167
2019-08-27T06:50:30.000Z
2022-03-31T22:33:48.000Z
open_spiel/examples/matrix_example.cc
texasmichelle/open_spiel
d9a9b8f9f1f44143867217fc3f6ff2db71b174b0
[ "Apache-2.0" ]
650
2019-08-27T16:24:09.000Z
2022-03-30T19:41:09.000Z
open_spiel/examples/matrix_example.cc
texasmichelle/open_spiel
d9a9b8f9f1f44143867217fc3f6ff2db71b174b0
[ "Apache-2.0" ]
774
2019-08-27T10:36:04.000Z
2022-03-29T15:44:42.000Z
// Copyright 2019 DeepMind Technologies Ltd. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <memory> #include <random> #include "open_spiel/abseil-cpp/absl/random/uniform_int_distribution.h" #include "open_spiel/matrix_game.h" #include "open_spiel/spiel.h" int main(int argc, char** argv) { // Random number generator. std::mt19937 rng; // Create the game with its default parameter settings. std::cerr << "Creating game..\n" << std::endl; std::shared_ptr<const open_spiel::Game> game( new open_spiel::matrix_game::MatrixGame( {/*short_name=*/"matrix_pd", /*long_name=*/"Prisoner's Dilemma", open_spiel::GameType::Dynamics::kSimultaneous, open_spiel::GameType::ChanceMode::kDeterministic, open_spiel::GameType::Information::kPerfectInformation, open_spiel::GameType::Utility::kGeneralSum, open_spiel::GameType::RewardModel::kTerminal, /*max_num_players=*/2, /*min_num_players=*/2, /*provides_information_state_string=*/true, /*provides_information_state_tensor=*/true, /*parameter_specification=*/{}}, {}, // Empty parameters {"Cooperate", "Defect"}, // (Row) Player 0's actions {"Cooperate", "Defect"}, // (Column) Player 2's actions {5, 0, 10, 1}, // Player 1's utilities in row-major order {5, 10, 0, 1} // Player 2's utilities in row-major order )); // Note: matrix games can also be registered through the main factory, just // like the other games in spiel, and then loaded through // open_spiel::LoadGame. See games/matrix_games.cc for how to register matrix // games. std::cerr << "Starting new game..." << std::endl; std::unique_ptr<open_spiel::State> state = game->NewInitialState(); std::vector<open_spiel::Action> row_actions = state->LegalActions(0); std::vector<open_spiel::Action> col_actions = state->LegalActions(1); open_spiel::Action row_action = row_actions[absl::uniform_int_distribution<int>( 0, row_actions.size() - 1)(rng)]; open_spiel::Action col_action = col_actions[absl::uniform_int_distribution<int>( 0, col_actions.size() - 1)(rng)]; std::cerr << "Joint action is: (" << state->ActionToString(0, row_action) << "," << state->ActionToString(1, row_action) << ")" << std::endl; state->ApplyActions({row_action, col_action}); SPIEL_CHECK_TRUE(state->IsTerminal()); auto returns = state->Returns(); for (int p = 0; p < game->NumPlayers(); p++) { std::cerr << "Terminal return to player " << p << " is " << returns[p] << std::endl; } }
40.775
79
0.650828
[ "vector" ]
b48c8c7516067bbc6f60646ccb4c6110a87e39a5
36,126
cpp
C++
control-plane/bfruntime.cpp
kostasyrmia/p4c-1
097cf174b612e3b0bdb5665ec54cd856118178e9
[ "Apache-2.0" ]
1
2021-08-11T13:16:59.000Z
2021-08-11T13:16:59.000Z
control-plane/bfruntime.cpp
kostasyrmia/p4c-1
097cf174b612e3b0bdb5665ec54cd856118178e9
[ "Apache-2.0" ]
3
2022-02-09T05:27:40.000Z
2022-03-30T11:32:29.000Z
control-plane/bfruntime.cpp
kostasyrmia/p4c-1
097cf174b612e3b0bdb5665ec54cd856118178e9
[ "Apache-2.0" ]
1
2022-01-06T08:07:25.000Z
2022-01-06T08:07:25.000Z
/* Copyright 2021 Intel 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 "bfruntime.h" namespace P4 { namespace BFRT { using P4::BFRT::P4Id; TypeSpecParser TypeSpecParser::make(const p4configv1::P4Info& p4info, const p4configv1::P4DataTypeSpec& typeSpec, cstring instanceType, cstring instanceName, const std::vector<cstring> *fieldNames, cstring prefix, cstring suffix, P4Id idOffset) { Fields fields; const auto& typeInfo = p4info.type_info(); auto addField = [&](P4Id id, const std::string& name, const p4configv1::P4DataTypeSpec& fSpec) { Util::JsonObject* type = nullptr; // Add support for required P4DataTypeSpec types here to generate // the correct field width if (fSpec.has_serializable_enum()) { auto enums = typeInfo.serializable_enums(); auto e = fSpec.serializable_enum().name(); auto typeEnum = enums.find(e); if (typeEnum == enums.end()) { ::error("Enum type '%1%' not found in typeInfo for '%2%' '%3%'", e, instanceType, instanceName); return; } type = makeTypeBytes(typeEnum->second.underlying_type().bitwidth()); } else if (fSpec.has_bitstring()) { if (fSpec.bitstring().has_bit()) type = makeTypeBytes(fSpec.bitstring().bit().bitwidth()); else if (fSpec.bitstring().has_int_()) type = makeTypeBytes(fSpec.bitstring().int_().bitwidth()); else if (fSpec.bitstring().has_varbit()) type = makeTypeBytes(fSpec.bitstring().varbit().max_bitwidth()); } else if (fSpec.has_bool_()) { type = makeTypeBool(1); } if (!type) { ::error("Error when generating BF-RT info for '%1%' '%2%': " "packed type is too complex", instanceType, instanceName); return; } fields.push_back({prefix + name + suffix, id, type}); }; if (typeSpec.has_struct_()) { auto structName = typeSpec.struct_().name(); auto p_it = typeInfo.structs().find(structName); BUG_CHECK(p_it != typeInfo.structs().end(), "Struct name '%1%' not found in P4Info map", structName); P4Id id = idOffset; for (const auto& member : p_it->second.members()) addField(id++, member.name(), member.type_spec()); } else if (typeSpec.has_tuple()) { P4Id id = idOffset; int fNameIdx = 0; for (const auto& member : typeSpec.tuple().members()) { std::string fName; if (fieldNames && int(fieldNames->size()) > fNameIdx) { fName = (*fieldNames)[fNameIdx++]; } else { // TODO(antonin): we do not really have better names for now, do // we need to add support for annotations of tuple members in // P4Info? fName = "f" + std::to_string(id); } addField(id++, fName, member); } } else if (typeSpec.has_bitstring()) { // TODO(antonin): same as above, we need a way to pass name // annotations std::string fName; if (fieldNames && fieldNames->size() > 0) { fName = (*fieldNames)[0]; } else { // TODO(antonin): we do not really have better names for now, do // we need to add support for annotations of tuple members in // P4Info? fName = "f1"; } addField(idOffset, fName, typeSpec); } else if (typeSpec.has_header()) { auto headerName = typeSpec.header().name(); auto p_it = typeInfo.headers().find(headerName); BUG_CHECK(p_it != typeInfo.headers().end(), "Header name '%1%' not found in P4Info map", headerName); P4Id id = idOffset; for (const auto& member : p_it->second.members()) { auto* type = makeTypeBytes(member.type_spec().bit().bitwidth()); fields.push_back({prefix + member.name() + suffix, id++, type}); } } else if (typeSpec.has_serializable_enum()) { auto enumName = typeSpec.serializable_enum().name(); auto p_it = typeInfo.serializable_enums().find(enumName); BUG_CHECK(p_it != typeInfo.serializable_enums().end(), "Serializable name '%1%' not found in P4Info map", enumName); P4Id id = idOffset; for (const auto& member : p_it->second.members()) { auto* type = makeTypeBytes(p_it->second.underlying_type().bitwidth()); fields.push_back({prefix + member.name() + suffix, id++, type}); } } else { ::error("Error when generating BF-RT info for '%1%' '%2%': " "only structs, headers, tuples, bitstrings and " "serializable enums are currently supported types", instanceType, instanceName); } return TypeSpecParser(std::move(fields)); } // Counter boost::optional<BFRuntimeGenerator::Counter> BFRuntimeGenerator::Counter::from(const p4configv1::Counter& counterInstance) { const auto& pre = counterInstance.preamble(); auto id = makeBFRuntimeId(pre.id(), p4configv1::P4Ids::COUNTER); // TODO(antonin): this works because the enum values are the same for // Counter::Unit and for CounterSpec::Unit, but this may not be very // future-proof. auto unit = static_cast<Unit>(counterInstance.spec().unit()); return Counter{pre.name(), id, counterInstance.size(), unit, transformAnnotations(pre)}; } boost::optional<BFRuntimeGenerator::Counter> BFRuntimeGenerator::Counter::fromDirect(const p4configv1::DirectCounter& counterInstance) { const auto& pre = counterInstance.preamble(); auto id = makeBFRuntimeId(pre.id(), p4configv1::P4Ids::DIRECT_COUNTER); auto unit = static_cast<Unit>(counterInstance.spec().unit()); return Counter{pre.name(), id, 0, unit, transformAnnotations(pre)}; } // Meter boost::optional<BFRuntimeGenerator::Meter> BFRuntimeGenerator::Meter::from(const p4configv1::Meter& meterInstance) { const auto& pre = meterInstance.preamble(); auto id = makeBFRuntimeId(pre.id(), p4configv1::P4Ids::METER); auto unit = static_cast<Unit>(meterInstance.spec().unit()); return Meter{pre.name(), id, meterInstance.size(), unit, transformAnnotations(pre)}; } boost::optional<BFRuntimeGenerator::Meter> BFRuntimeGenerator::Meter::fromDirect(const p4configv1::DirectMeter& meterInstance) { const auto& pre = meterInstance.preamble(); auto id = makeBFRuntimeId(pre.id(), p4configv1::P4Ids::DIRECT_METER); auto unit = static_cast<Unit>(meterInstance.spec().unit()); return Meter{pre.name(), id, 0, unit, transformAnnotations(pre)}; } // ActionProfile P4Id BFRuntimeGenerator::ActionProf::makeActProfId(P4Id implementationId) { return makeBFRuntimeId(implementationId, p4configv1::P4Ids::ACTION_PROFILE); } boost::optional<BFRuntimeGenerator::ActionProf> BFRuntimeGenerator::ActionProf::from(const p4configv1::P4Info& p4info, const p4configv1::ActionProfile& actionProfile) { const auto& pre = actionProfile.preamble(); auto profileId = makeBFRuntimeId(pre.id(), p4configv1::P4Ids::ACTION_PROFILE); auto tableIds = collectTableIds( p4info, actionProfile.table_ids().begin(), actionProfile.table_ids().end()); return ActionProf{pre.name(), profileId, actionProfile.size(), tableIds, transformAnnotations(pre)}; } // Digest boost::optional<BFRuntimeGenerator::Digest> BFRuntimeGenerator::Digest::from(const p4configv1::Digest& digest) { const auto& pre = digest.preamble(); auto id = makeBFRuntimeId(pre.id(), p4configv1::P4Ids::DIGEST); return Digest{pre.name(), id, digest.type_spec(), transformAnnotations(pre)}; } boost::optional<BFRuntimeGenerator::Counter> BFRuntimeGenerator::getDirectCounter(P4Id counterId) const { if (isOfType(counterId, p4configv1::P4Ids::DIRECT_COUNTER)) { auto* counter = Standard::findDirectCounter(p4info, counterId); if (counter == nullptr) return boost::none; return Counter::fromDirect(*counter); } return boost::none; } boost::optional<BFRuntimeGenerator::Meter> BFRuntimeGenerator::getDirectMeter(P4Id meterId) const { if (isOfType(meterId, p4configv1::P4Ids::DIRECT_METER)) { auto* meter = Standard::findDirectMeter(p4info, meterId); if (meter == nullptr) return boost::none; return Meter::fromDirect(*meter); } return boost::none; } // TBD // boost::optional<BFRuntimeGenerator::Register> // BFRuntimeGenerator::getRegister(P4Id registerId) const { // if (!isOfType(registerId, p4configv1::P4Ids::DIRECT_REGISTER)) return boost::none; // auto* externInstance = findExternInstance(p4info, registerId); // if (externInstance == nullptr) return boost::none; // return Register::from(*externInstance); // } Util::JsonObject* BFRuntimeGenerator::makeCommonDataField(P4Id id, cstring name, Util::JsonObject* type, bool repeated, Util::JsonArray* annotations) { auto* dataField = new Util::JsonObject(); dataField->emplace("id", id); dataField->emplace("name", name); dataField->emplace("repeated", repeated); if (annotations != nullptr) dataField->emplace("annotations", annotations); else dataField->emplace("annotations", new Util::JsonArray()); dataField->emplace("type", type); return dataField; } Util::JsonObject* BFRuntimeGenerator::makeContainerDataField(P4Id id, cstring name, Util::JsonArray* items, bool repeated, Util::JsonArray* annotations) { auto* dataField = new Util::JsonObject(); dataField->emplace("id", id); dataField->emplace("name", name); dataField->emplace("repeated", repeated); if (annotations != nullptr) dataField->emplace("annotations", annotations); else dataField->emplace("annotations", new Util::JsonArray()); dataField->emplace("container", items); return dataField; } void BFRuntimeGenerator::addActionDataField(Util::JsonArray* dataJson, P4Id id, const std::string& name, bool mandatory, bool read_only, Util::JsonObject* type, Util::JsonArray* annotations) { auto* dataField = new Util::JsonObject(); dataField->emplace("id", id); dataField->emplace("name", name); dataField->emplace("repeated", false); dataField->emplace("mandatory", mandatory); dataField->emplace("read_only", read_only); if (annotations != nullptr) dataField->emplace("annotations", annotations); else dataField->emplace("annotations", new Util::JsonArray()); dataField->emplace("type", type); dataJson->append(dataField); } void BFRuntimeGenerator::addKeyField(Util::JsonArray* dataJson, P4Id id, cstring name, bool mandatory, cstring matchType, Util::JsonObject* type, Util::JsonArray* annotations) { auto* dataField = new Util::JsonObject(); dataField->emplace("id", id); dataField->emplace("name", name); dataField->emplace("repeated", false); if (annotations != nullptr) dataField->emplace("annotations", annotations); else dataField->emplace("annotations", new Util::JsonArray()); dataField->emplace("mandatory", mandatory); dataField->emplace("match_type", matchType); dataField->emplace("type", type); dataJson->append(dataField); } /* static */ Util::JsonObject* BFRuntimeGenerator::initTableJson(const std::string& name, P4Id id, cstring tableType, int64_t size, Util::JsonArray* annotations) { auto* tableJson = new Util::JsonObject(); tableJson->emplace("name", name); tableJson->emplace("id", id); tableJson->emplace("table_type", tableType); tableJson->emplace("size", size); if (annotations != nullptr) tableJson->emplace("annotations", annotations); tableJson->emplace("depends_on", new Util::JsonArray()); return tableJson; } /* static */ void BFRuntimeGenerator::addToDependsOn(Util::JsonObject* tableJson, P4Id id) { auto* dependsOnJson = tableJson->get("depends_on")->to<Util::JsonArray>(); CHECK_NULL(dependsOnJson); // Skip duplicates for (auto *d : *dependsOnJson) { if (*d->to<Util::JsonValue>() == id) return; } dependsOnJson->append(id); } void BFRuntimeGenerator::addCounterCommon(Util::JsonArray* tablesJson, const Counter& counter) const { auto* tableJson = initTableJson( counter.name, counter.id, "Counter", counter.size, counter.annotations); auto* keyJson = new Util::JsonArray(); addKeyField(keyJson, TD_DATA_COUNTER_INDEX, "$COUNTER_INDEX", true /* mandatory */, "Exact", makeType("uint32")); tableJson->emplace("key", keyJson); auto* dataJson = new Util::JsonArray(); addCounterDataFields(dataJson, counter); tableJson->emplace("data", dataJson); auto* operationsJson = new Util::JsonArray(); operationsJson->append("Sync"); tableJson->emplace("supported_operations", operationsJson); tableJson->emplace("attributes", new Util::JsonArray()); tablesJson->append(tableJson); } void BFRuntimeGenerator::addCounterDataFields(Util::JsonArray* dataJson, const BFRuntimeGenerator::Counter& counter) { static const uint64_t defaultCounterValue = 0u; if (counter.unit == Counter::Unit::BYTES || counter.unit == Counter::Unit::BOTH) { auto* f = makeCommonDataField( TD_DATA_COUNTER_SPEC_BYTES, "$COUNTER_SPEC_BYTES", makeType("uint64", defaultCounterValue), false /* repeated */); addSingleton(dataJson, f, false /* mandatory */, false /* read-only */); } if (counter.unit == Counter::Unit::PACKETS || counter.unit == Counter::Unit::BOTH) { auto* f = makeCommonDataField( TD_DATA_COUNTER_SPEC_PKTS, "$COUNTER_SPEC_PKTS", makeType("uint64", defaultCounterValue), false /* repeated */); addSingleton(dataJson, f, false /* mandatory */, false /* read-only */); } } void BFRuntimeGenerator::addMeterCommon(Util::JsonArray* tablesJson, const BFRuntimeGenerator::Meter& meter) const { auto* tableJson = initTableJson(meter.name, meter.id, "Meter", meter.size); auto* keyJson = new Util::JsonArray(); addKeyField(keyJson, TD_DATA_METER_INDEX, "$METER_INDEX", true /* mandatory */, "Exact", makeType("uint32")); tableJson->emplace("key", keyJson); auto* dataJson = new Util::JsonArray(); addMeterDataFields(dataJson, meter); tableJson->emplace("data", dataJson); tableJson->emplace("supported_operations", new Util::JsonArray()); auto* attributesJson = new Util::JsonArray(); attributesJson->append("MeterByteCountAdjust"); tableJson->emplace("attributes", attributesJson); tablesJson->append(tableJson); } void BFRuntimeGenerator::transformTypeSpecToDataFields(Util::JsonArray* fieldsJson, const p4configv1::P4DataTypeSpec& typeSpec, cstring instanceType, cstring instanceName, const std::vector<cstring> *fieldNames, cstring prefix, cstring suffix, P4Id idOffset) const { auto parser = TypeSpecParser::make( p4info, typeSpec, instanceType, instanceName, fieldNames, prefix, suffix, idOffset); for (const auto &f : parser) { auto* fJson = makeCommonDataField(f.id, f.name, f.type, false /* repeated */); fieldsJson->append(fJson); } } void BFRuntimeGenerator::addRegisterDataFields(Util::JsonArray* dataJson, const BFRuntimeGenerator::Register& register_, P4Id idOffset) const { auto* fieldsJson = new Util::JsonArray(); transformTypeSpecToDataFields( fieldsJson, register_.typeSpec, "Register", register_.name, nullptr, register_.dataFieldName + ".", "", idOffset); for (auto* f : *fieldsJson) { auto* fObj = f->to<Util::JsonObject>(); CHECK_NULL(fObj); auto* fAnnotations = fObj->get("annotations")->to<Util::JsonArray>(); CHECK_NULL(fAnnotations); // Add BF-RT "native" annotation to indicate to the BF-RT implementation // - and potentially applications - that this data field is stateful // data. The specific string for this annotation may be changed in the // future if we start introducing more BF-RT annotations, in order to // keep the syntax consistent. { auto* classAnnotation = new Util::JsonObject(); classAnnotation->emplace("name", "$bfrt_field_class"); classAnnotation->emplace("value", "register_data"); fAnnotations->append(classAnnotation); } addSingleton(dataJson, fObj, true /* mandatory */, false /* read-only */); } } void BFRuntimeGenerator::addRegisterCommon(Util::JsonArray* tablesJson, const BFRuntimeGenerator::Register& register_) const { auto* tableJson = initTableJson(register_.name, register_.id, "Register", register_.size); auto* keyJson = new Util::JsonArray(); addKeyField(keyJson, TD_DATA_REGISTER_INDEX, "$REGISTER_INDEX", true /* mandatory */, "Exact", makeType("uint32")); tableJson->emplace("key", keyJson); auto* dataJson = new Util::JsonArray(); addRegisterDataFields(dataJson, register_); tableJson->emplace("data", dataJson); auto* operationsJson = new Util::JsonArray(); operationsJson->append("Sync"); tableJson->emplace("supported_operations", operationsJson); tableJson->emplace("attributes", new Util::JsonArray()); tablesJson->append(tableJson); } void BFRuntimeGenerator::addMeterDataFields(Util::JsonArray* dataJson, const BFRuntimeGenerator::Meter& meter) { // default value for rates and bursts (all GREEN) static const uint64_t maxUint64 = std::numeric_limits<uint64_t>::max(); if (meter.unit == Meter::Unit::BYTES) { { auto* f = makeCommonDataField( TD_DATA_METER_SPEC_CIR_KBPS, "$METER_SPEC_CIR_KBPS", makeType("uint64", maxUint64), false /* repeated */); addSingleton(dataJson, f, false /* mandatory */, false /* read-only */); } { auto* f = makeCommonDataField( TD_DATA_METER_SPEC_PIR_KBPS, "$METER_SPEC_PIR_KBPS", makeType("uint64", maxUint64), false /* repeated */); addSingleton(dataJson, f, false /* mandatory */, false /* read-only */); } { auto* f = makeCommonDataField( TD_DATA_METER_SPEC_CBS_KBITS, "$METER_SPEC_CBS_KBITS", makeType("uint64", maxUint64), false /* repeated */); addSingleton(dataJson, f, false /* mandatory */, false /* read-only */); } { auto* f = makeCommonDataField( TD_DATA_METER_SPEC_PBS_KBITS, "$METER_SPEC_PBS_KBITS", makeType("uint64", maxUint64), false /* repeated */); addSingleton(dataJson, f, false /* mandatory */, false /* read-only */); } } else if (meter.unit == Meter::Unit::PACKETS) { { auto* f = makeCommonDataField( TD_DATA_METER_SPEC_CIR_PPS, "$METER_SPEC_CIR_PPS", makeType("uint64", maxUint64), false /* repeated */); addSingleton(dataJson, f, false /* mandatory */, false /* read-only */); } { auto* f = makeCommonDataField( TD_DATA_METER_SPEC_PIR_PPS, "$METER_SPEC_PIR_PPS", makeType("uint64", maxUint64), false /* repeated */); addSingleton(dataJson, f, false /* mandatory */, false /* read-only */); } { auto* f = makeCommonDataField( TD_DATA_METER_SPEC_CBS_PKTS, "$METER_SPEC_CBS_PKTS", makeType("uint64", maxUint64), false /* repeated */); addSingleton(dataJson, f, false /* mandatory */, false /* read-only */); } { auto* f = makeCommonDataField( TD_DATA_METER_SPEC_PBS_PKTS, "$METER_SPEC_PBS_PKTS", makeType("uint64", maxUint64), false /* repeated */); addSingleton(dataJson, f, false /* mandatory */, false /* read-only */); } } else { BUG("Unknown meter unit"); } } void BFRuntimeGenerator::addActionProfCommon(Util::JsonArray* tablesJson, const BFRuntimeGenerator::ActionProf& actionProf) const { auto* tableJson = initTableJson( actionProf.name, actionProf.id, "Action", actionProf.size, actionProf.annotations); auto* keyJson = new Util::JsonArray(); addKeyField(keyJson, TD_DATA_ACTION_MEMBER_ID, "$ACTION_MEMBER_ID", true /* mandatory */, "Exact", makeType("uint32")); tableJson->emplace("key", keyJson); if (actionProf.tableIds.empty()) { ::warning("Action profile '%1%' is not used by any table, skipping it", actionProf.name); return; } auto oneTableId = actionProf.tableIds.at(0); auto* oneTable = Standard::findTable(p4info, oneTableId); CHECK_NULL(oneTable); // Add action profile to match table depends on auto oneTableJson = findJsonTable(tablesJson, oneTable->preamble().name()); addToDependsOn(oneTableJson, actionProf.id); tableJson->emplace("action_specs", makeActionSpecs(*oneTable)); tableJson->emplace("data", new Util::JsonArray()); tableJson->emplace("supported_operations", new Util::JsonArray()); tableJson->emplace("attributes", new Util::JsonArray()); tablesJson->append(tableJson); } boost::optional<bool> BFRuntimeGenerator::actProfHasSelector(P4Id actProfId) const { if (isOfType(actProfId, p4configv1::P4Ids::ACTION_PROFILE)) { auto* actionProf = Standard::findActionProf(p4info, actProfId); if (actionProf == nullptr) return boost::none; return actionProf->with_selector(); } return boost::none; } Util::JsonArray* BFRuntimeGenerator::makeActionSpecs(const p4configv1::Table& table, P4Id* maxActionParamId) const { auto* specs = new Util::JsonArray(); P4Id maxId = 0; for (const auto& action_ref : table.action_refs()) { auto* action = Standard::findAction(p4info, action_ref.id()); if (action == nullptr) { ::error("Invalid action id '%1%'", action_ref.id()); continue; } auto* spec = new Util::JsonObject(); const auto& pre = action->preamble(); spec->emplace("id", pre.id()); spec->emplace("name", pre.name()); switch (action_ref.scope()) { case p4configv1::ActionRef::TABLE_AND_DEFAULT: spec->emplace("action_scope", "TableAndDefault"); break; case p4configv1::ActionRef::TABLE_ONLY: spec->emplace("action_scope", "TableOnly"); break; case p4configv1::ActionRef::DEFAULT_ONLY: spec->emplace("action_scope", "DefaultOnly"); break; default: ::error("Invalid action ref scope '%1%' in P4Info", int(action_ref.scope())); break; } auto* annotations = transformAnnotations( action_ref.annotations().begin(), action_ref.annotations().end()); spec->emplace("annotations", annotations); auto* dataJson = new Util::JsonArray(); for (const auto& param : action->params()) { auto* annotations = transformAnnotations( param.annotations().begin(), param.annotations().end()); addActionDataField( dataJson, param.id(), param.name(), true /* mandatory */, false /* read_only */, makeTypeBytes(param.bitwidth()), annotations); if (param.id() > maxId) maxId = param.id(); } spec->emplace("data", dataJson); specs->append(spec); } if (maxActionParamId != nullptr) *maxActionParamId = maxId; return specs; } void BFRuntimeGenerator::addLearnFilterCommon(Util::JsonArray* learnFiltersJson, const BFRuntimeGenerator::Digest& digest) const { auto* learnFilterJson = new Util::JsonObject(); learnFilterJson->emplace("name", digest.name); learnFilterJson->emplace("id", digest.id); learnFilterJson->emplace("annotations", digest.annotations); auto* fieldsJson = new Util::JsonArray(); transformTypeSpecToDataFields(fieldsJson, digest.typeSpec, "Digest", digest.name); learnFilterJson->emplace("fields", fieldsJson); learnFiltersJson->append(learnFilterJson); } void BFRuntimeGenerator::addLearnFilters(Util::JsonArray* learnFiltersJson) const { for (const auto& digest : p4info.digests()) { auto digestInstance = Digest::from(digest); if (digestInstance == boost::none) continue; addLearnFilterCommon(learnFiltersJson, *digestInstance); } } void BFRuntimeGenerator::addDirectResources(const p4configv1::Table& table, Util::JsonArray* dataJson, Util::JsonArray* operationsJson, Util::JsonArray* attributesJson, P4Id) const { // direct resources for (auto directResId : table.direct_resource_ids()) { if (auto counter = getDirectCounter(directResId)) { addCounterDataFields(dataJson, *counter); operationsJson->append("SyncCounters"); } else if (auto meter = getDirectMeter(directResId)) { addMeterDataFields(dataJson, *meter); attributesJson->append("MeterByteCountAdjust"); } else { ::error("Unknown direct resource id '%1%'", directResId); continue; } } } bool BFRuntimeGenerator::addActionProfIds(const p4configv1::Table& table, Util::JsonObject* tableJson) const { auto implementationId = table.implementation_id(); if (implementationId > 0) { P4Id actProfId = ActionProf::makeActProfId(implementationId); addToDependsOn(tableJson, actProfId); } return true; } void BFRuntimeGenerator::addMatchTables(Util::JsonArray* tablesJson) const { for (const auto& table : p4info.tables()) { const auto& pre = table.preamble(); std::set<std::string> dupKey; auto* annotations = transformAnnotations( pre.annotations().begin(), pre.annotations().end()); auto* tableJson = initTableJson( pre.name(), pre.id(), "MatchAction_Direct", table.size(), annotations); if (!addActionProfIds(table, tableJson)) continue; tableJson->emplace("has_const_default_action", table.const_default_action_id() != 0); // will be set to true by the for loop if the match key includes a // ternary, range or optional match bool needsPriority = false; auto* keyJson = new Util::JsonArray(); for (const auto& mf : table.match_fields()) { boost::optional<cstring> matchType = boost::none; switch (mf.match_case()) { case p4configv1::MatchField::kMatchType: matchType = transformMatchType(mf.match_type()); break; case p4configv1::MatchField::kOtherMatchType: matchType = transformOtherMatchType(mf.other_match_type()); break; default: BUG("Invalid oneof case for the match type of table '%1%'", pre.name()); break; } if (matchType == boost::none) { ::error("Unsupported match type for BF-RT: %1%", int(mf.match_type())); continue; } if (*matchType == "Ternary" || *matchType == "Range" || *matchType == "Optional") needsPriority = true; auto* annotations = transformAnnotations( mf.annotations().begin(), mf.annotations().end()); CHECK_NULL(annotations); // Add isFieldSlice annotation if the match key is a field slice // e.g. hdr[23:16] where hdr is a 32 bit field std::string s(mf.name()); std::smatch sm; std::regex sliceRegex(R"(\[([0-9]+):([0-9]+)\])"); std::regex_search(s, sm, sliceRegex); if (sm.size() == 3) { auto *isFieldSliceAnnot = new Util::JsonObject(); isFieldSliceAnnot->emplace("name", "isFieldSlice"); isFieldSliceAnnot->emplace("value", "true"); annotations->append(isFieldSliceAnnot); } // P4_14-->P4_16 translation names valid matches with a // "$valid$" suffix (note the trailing "$"). However, Brig // and pdgen use "$valid". auto keyName = mf.name(); auto found = keyName.find(".$valid"); if (found != std::string::npos) keyName.pop_back(); // Replace header stack indices hdr[<index>] with hdr$<index>. This // is output in the context.json std::regex hdrStackRegex(R"(\[([0-9]+)\])"); keyName = std::regex_replace(keyName, hdrStackRegex, "$$$1"); // Control plane requires there's no duplicate key in one table. if (dupKey.count(keyName) != 0) { ::error("Key \"%s\" is duplicate in Table \"%s\". It doesn't meet BFRT's " "requirements.\n" "Please using @name annotation for the duplicate key names", keyName, pre.name()); return; } else { dupKey.insert(keyName); } // DRV-3112 - Make key fields not mandatory, this allows user to use a // driver initialized default value (0). addKeyField(keyJson, mf.id(), keyName, false /* mandatory */, *matchType, makeTypeBytes(mf.bitwidth(), boost::none), annotations); } if (needsPriority) { // DRV-3112 - Make key fields not mandatory, this allows user to use a // driver initialized default value (0). addKeyField(keyJson, TD_DATA_MATCH_PRIORITY, "$MATCH_PRIORITY", false /* mandatory */, "Exact", makeType("uint32")); } tableJson->emplace("key", keyJson); auto* dataJson = new Util::JsonArray(); // will be used as an offset for other P4-dependent fields (e.g. direct // register fields). P4Id maxActionParamId = 0; cstring tableType = tableJson->get("table_type")->to<Util::JsonValue>()->getString(); if (tableType == "MatchAction_Direct") { tableJson->emplace( "action_specs", makeActionSpecs(table, &maxActionParamId)); } else if (tableType == "MatchAction_Indirect") { auto* f = makeCommonDataField( TD_DATA_ACTION_MEMBER_ID, "$ACTION_MEMBER_ID", makeType("uint32"), false /* repeated */); addSingleton(dataJson, f, true /* mandatory */, false /* read-only */); } else if (tableType == "MatchAction_Indirect_Selector") { // action member id and selector group id are mutually-exclusive, so // we use a "oneof" here. auto* choicesDataJson = new Util::JsonArray(); choicesDataJson->append(makeCommonDataField( TD_DATA_ACTION_MEMBER_ID, "$ACTION_MEMBER_ID", makeType("uint32"), false /* repeated */)); choicesDataJson->append(makeCommonDataField( TD_DATA_SELECTOR_GROUP_ID, "$SELECTOR_GROUP_ID", makeType("uint32"), false /* repeated */)); addOneOf(dataJson, choicesDataJson, true /* mandatory */, false /* read-only */); } else { BUG("Invalid table type '%1%'", tableType); } maxActionParamId++; auto* operationsJson = new Util::JsonArray(); auto* attributesJson = new Util::JsonArray(); addDirectResources(table, dataJson, operationsJson, attributesJson, maxActionParamId); attributesJson->append("EntryScope"); // The compiler backend is in charge of rejecting the program if // @dynamic_table_key_masks is used incorrectly (e.g. if the table is // ternary). auto supportsDynMask = std::count( pre.annotations().begin(), pre.annotations().end(), "@dynamic_table_key_masks(1)"); if (supportsDynMask) attributesJson->append("DynamicKeyMask"); if (table.is_const_table()) attributesJson->append("ConstTable"); if (table.idle_timeout_behavior() == p4configv1::Table::NOTIFY_CONTROL) { auto pollModeOnly = std::count( pre.annotations().begin(), pre.annotations().end(), "@idletime_precision(1)"); operationsJson->append("UpdateHitState"); attributesJson->append("IdleTimeout"); auto* fEntryTTL = makeCommonDataField( TD_DATA_ENTRY_TTL, "$ENTRY_TTL", makeType("uint32", 0 /* default TTL -> ageing disabled */), false /* repeated */); auto* fEntryHitState = makeCommonDataField( TD_DATA_ENTRY_HIT_STATE, "$ENTRY_HIT_STATE", makeTypeEnum({"ENTRY_IDLE", "ENTRY_ACTIVE"}), false /* repeated */); addSingleton(dataJson, fEntryHitState, false /* mandatory */, false /* read-only */); if (!pollModeOnly) addSingleton(dataJson, fEntryTTL, false /* mandatory */, false /* read-only */); } tableJson->emplace("data", dataJson); tableJson->emplace("supported_operations", operationsJson); tableJson->emplace("attributes", attributesJson); tablesJson->append(tableJson); } } void BFRuntimeGenerator::addActionProfs(Util::JsonArray* tablesJson) const { for (const auto& actionProf : p4info.action_profiles()) { auto actionProfInstance = ActionProf::from(p4info, actionProf); if (actionProfInstance == boost::none) continue; addActionProfCommon(tablesJson, *actionProfInstance); } } void BFRuntimeGenerator::addCounters(Util::JsonArray* tablesJson) const { for (const auto& counter : p4info.counters()) { auto counterInstance = Counter::from(counter); if (counterInstance == boost::none) continue; addCounterCommon(tablesJson, *counterInstance); } } void BFRuntimeGenerator::addMeters(Util::JsonArray* tablesJson) const { for (const auto& meter : p4info.meters()) { auto meterInstance = Meter::from(meter); if (meterInstance == boost::none) continue; addMeterCommon(tablesJson, *meterInstance); } } const Util::JsonObject* BFRuntimeGenerator::genSchema() const { auto* json = new Util::JsonObject(); json->emplace("schema_version", cstring("1.0.0")); auto* tablesJson = new Util::JsonArray(); json->emplace("tables", tablesJson); addMatchTables(tablesJson); addActionProfs(tablesJson); addCounters(tablesJson); addMeters(tablesJson); // TODO(antonin): handle "standard" (v1model / PSA) registers auto* learnFiltersJson = new Util::JsonArray(); json->emplace("learn_filters", learnFiltersJson); addLearnFilters(learnFiltersJson); return json; } void BFRuntimeGenerator::serializeBFRuntimeSchema(std::ostream* destination) { auto* json = genSchema(); json->serialize(*destination); destination->flush(); } } // namespace BFRT } // namespace P4
41.005675
98
0.628605
[ "vector" ]
b490287d2720a30a56b0268128435b88b1aa60b1
3,439
cpp
C++
input/RegionGraph.cpp
AlesMaver/ExpansionHunter
274903d26a33cfbc546aac98c85bbfe51701fd3b
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
input/RegionGraph.cpp
AlesMaver/ExpansionHunter
274903d26a33cfbc546aac98c85bbfe51701fd3b
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
input/RegionGraph.cpp
AlesMaver/ExpansionHunter
274903d26a33cfbc546aac98c85bbfe51701fd3b
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
// // Expansion Hunter // Copyright 2016-2019 Illumina, Inc. // All rights reserved. // // Author: Egor Dolzhenko <edolzhenko@illumina.com> // // 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 "input/RegionGraph.hh" #include <algorithm> #include <cassert> #include <utility> #include <vector> #include "input/GraphBlueprint.hh" using graphtools::Graph; using graphtools::NodeId; using std::string; using std::vector; namespace ehunter { int getNumNodes(const GraphBlueprint& blueprint) { int numNodes = 0; for (const auto& feature : blueprint) { numNodes += feature.sequences.size(); } return numNodes; } static void setFeatureSequences(const GraphBlueprintFeature& feature, Graph& graph) { assert(feature.nodeIds.size() == feature.sequences.size()); for (int index = 0; index != static_cast<int>(feature.sequences.size()); ++index) { graph.setNodeSeq(feature.nodeIds[index], feature.sequences[index]); } } static void connectFeatures(const GraphBlueprintFeature& sourceFeature, const GraphBlueprintFeature& sinkFeature, Graph& graph) { for (NodeId nodeIdOfPreviousFeature : sourceFeature.nodeIds) { for (NodeId nodeIdOfNewFeature : sinkFeature.nodeIds) { graph.addEdge(nodeIdOfPreviousFeature, nodeIdOfNewFeature); } } } static void setInternalFeatureEdges(const GraphBlueprintFeature& feature, Graph& graph) { const bool isRepeat = feature.type == GraphBlueprintFeatureType::kSkippableRepeat || feature.type == GraphBlueprintFeatureType::kUnskippableRepeat; if (isRepeat) { assert(feature.nodeIds.size() == 1); const NodeId nodeId = feature.nodeIds.front(); graph.addEdge(nodeId, nodeId); } } void setOutgoingFeatureEdges(const GraphBlueprint& blueprint, int index, Graph& graph) { const GraphBlueprintFeature& currentFeature = blueprint[index]; const GraphBlueprintFeature* downstreamFeaturePtr = &blueprint[++index]; while (isSkippable(downstreamFeaturePtr->type)) { connectFeatures(currentFeature, *downstreamFeaturePtr, graph); downstreamFeaturePtr = &blueprint[++index]; } connectFeatures(currentFeature, *downstreamFeaturePtr, graph); } Graph makeRegionGraph(const GraphBlueprint& blueprint, const std::string& locusId) { // Implicit assumptions about the graph structure assert(blueprint.front().type == GraphBlueprintFeatureType::kLeftFlank); assert(blueprint.back().type == GraphBlueprintFeatureType::kRightFlank); Graph graph(getNumNodes(blueprint), locusId); for (const auto& feature : blueprint) { setFeatureSequences(feature, graph); setInternalFeatureEdges(feature, graph); } for (int index = 0; index != static_cast<int>(blueprint.size()) - 1; ++index) { setOutgoingFeatureEdges(blueprint, index, graph); } return graph; } }
28.421488
115
0.711835
[ "vector" ]
b490d4acaee12ab59d7cb8654afd5218174e4509
8,629
hpp
C++
ios/Pods/boost-for-react-native/boost/spirit/home/classic/core/parser.hpp
rudylee/expo
b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc
[ "Apache-2.0", "MIT" ]
8,805
2015-11-03T00:52:29.000Z
2022-03-29T22:30:03.000Z
ios/Pods/boost-for-react-native/boost/spirit/home/classic/core/parser.hpp
rudylee/expo
b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc
[ "Apache-2.0", "MIT" ]
14,694
2015-02-24T15:13:42.000Z
2022-03-31T13:16:45.000Z
ios/Pods/boost-for-react-native/boost/spirit/home/classic/core/parser.hpp
rudylee/expo
b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc
[ "Apache-2.0", "MIT" ]
1,329
2015-11-03T20:25:51.000Z
2022-03-31T18:10:38.000Z
/*============================================================================= Copyright (c) 1998-2003 Joel de Guzman http://spirit.sourceforge.net/ 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) =============================================================================*/ #if !defined(BOOST_SPIRIT_PARSER_HPP) #define BOOST_SPIRIT_PARSER_HPP #include <boost/config.hpp> #include <boost/type_traits/remove_reference.hpp> #include <boost/spirit/home/classic/namespace.hpp> #include <boost/spirit/home/classic/core/scanner/scanner.hpp> #include <boost/spirit/home/classic/core/nil.hpp> namespace boost { namespace spirit { BOOST_SPIRIT_CLASSIC_NAMESPACE_BEGIN template <typename ParserT, typename ActionT> class action; // forward declaration /////////////////////////////////////////////////////////////////////////// // // Parser categories // // Helper template classes to distinguish different types of // parsers. The following categories are the most generic. More // specific types may inherit from these. Each parser has a typedef // parser_category_t that defines its category. By default, if one // is not specified, it will inherit from the base parser class // which typedefs its parser_category_t as plain_parser_category. // // - plain parser has nothing special // - binary parser has subject a and b (e.g. alternative) // - unary parser has single subject (e.g. kleene star) // - action parser has an attached action parser // /////////////////////////////////////////////////////////////////////////// struct plain_parser_category {}; struct binary_parser_category : plain_parser_category {}; struct unary_parser_category : plain_parser_category {}; struct action_parser_category : unary_parser_category {}; /////////////////////////////////////////////////////////////////////////// // // parser_result metafunction // // Given a scanner type ScannerT and a parser type ParserT, the // parser_result metafunction provides the actual result of the // parser. // // Usage: // // typename parser_result<ParserT, ScannerT>::type // /////////////////////////////////////////////////////////////////////////// template <typename ParserT, typename ScannerT> struct parser_result { typedef typename boost::remove_reference<ParserT>::type parser_type; typedef typename parser_type::template result<ScannerT>::type type; }; /////////////////////////////////////////////////////////////////////////// // // parser class // // This class is a protocol base class for all parsers. This is // essentially an interface contract. The parser class does not // really know how to parse anything but instead relies on the // template parameter DerivedT (which obviously is assumed to be a // subclass) to do the actual parsing. // // Concrete sub-classes inheriting from parser must have a // corresponding member function parse(...) compatible with the // conceptual Interface: // // template <typename ScannerT> // RT parse(ScannerT const& scan) const; // // where RT is the desired return type of the parser and ScannerT // scan is the scanner (see scanner.hpp). // // Concrete sub-classes inheriting from parser in most cases need to // have a nested meta-function result that returns the result type // of the parser's parse member function, given a scanner type. The // meta-function has the form: // // template <typename ScannerT> // struct result // { // typedef RT type; // }; // // where RT is the desired return type of the parser. This is // usually, but not always, dependent on the template parameter // ScannerT. If a parser does not supply a result metafunction, a // default is provided by the base parser class. // // The parser's derived() member function returns a reference to the // parser as its derived object. // // An operator[] is provided. The operator returns a semantic action // handler (see actions.hpp). // // Each parser has a typedef embed_t. This typedef specifies how a // parser is embedded in a composite (see composite.hpp). By // default, if one is not specified, the parser will be embedded by // value. That is, a copy of the parser is placed as a member // variable of the composite. Most parsers are embedded by value. In // certain situations however, this is not desirable or possible. // /////////////////////////////////////////////////////////////////////////// template <typename DerivedT> struct parser { typedef DerivedT embed_t; typedef DerivedT derived_t; typedef plain_parser_category parser_category_t; template <typename ScannerT> struct result { typedef typename match_result<ScannerT, nil_t>::type type; }; DerivedT& derived() { return *static_cast<DerivedT*>(this); } DerivedT const& derived() const { return *static_cast<DerivedT const*>(this); } template <typename ActionT> action<DerivedT, ActionT> operator[](ActionT const& actor) const { return action<DerivedT, ActionT>(derived(), actor); } }; /////////////////////////////////////////////////////////////////////////// // // parse_info // // Results returned by the free parse functions: // // stop: points to the final parse position (i.e parsing // processed the input up to this point). // // hit: true if parsing is successful. This may be full: // the parser consumed all the input, or partial: // the parser consumed only a portion of the input. // // full: true when we have a full hit (i.e the parser // consumed all the input. // // length: The number of characters consumed by the parser. // This is valid only if we have a successful hit // (either partial or full). // /////////////////////////////////////////////////////////////////////////// template <typename IteratorT = char const*> struct parse_info { IteratorT stop; bool hit; bool full; std::size_t length; parse_info( IteratorT const& stop_ = IteratorT(), bool hit_ = false, bool full_ = false, std::size_t length_ = 0) : stop(stop_) , hit(hit_) , full(full_) , length(length_) {} template <typename ParseInfoT> parse_info(ParseInfoT const& pi) : stop(pi.stop) , hit(pi.hit) , full(pi.full) , length(pi.length) {} }; /////////////////////////////////////////////////////////////////////////// // // Generic parse function // /////////////////////////////////////////////////////////////////////////// template <typename IteratorT, typename DerivedT> parse_info<IteratorT> parse( IteratorT const& first, IteratorT const& last, parser<DerivedT> const& p); /////////////////////////////////////////////////////////////////////////// // // Parse function for null terminated strings // /////////////////////////////////////////////////////////////////////////// template <typename CharT, typename DerivedT> parse_info<CharT const*> parse( CharT const* str, parser<DerivedT> const& p); BOOST_SPIRIT_CLASSIC_NAMESPACE_END }} // namespace BOOST_SPIRIT_CLASSIC_NS #endif #include <boost/spirit/home/classic/core/impl/parser.ipp>
38.522321
80
0.512342
[ "object" ]
b493691035d785ac05a65de026f052c1bd96cd39
1,380
cpp
C++
libcxx/test/libcxx/fuzzing/stable_sort.pass.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
libcxx/test/libcxx/fuzzing/stable_sort.pass.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
libcxx/test/libcxx/fuzzing/stable_sort.pass.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++03, c++11 #include <algorithm> #include <cstddef> #include <cstdint> #include <vector> #include "fuzz.h" extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t *data, std::size_t size) { std::vector<ByteWithPayload> input; for (std::size_t i = 0; i < size; ++i) input.push_back(ByteWithPayload(data[i], i)); std::vector<ByteWithPayload> working = input; std::stable_sort(working.begin(), working.end(), ByteWithPayload::key_less()); if (!std::is_sorted(working.begin(), working.end(), ByteWithPayload::key_less())) return 1; auto iter = working.begin(); while (iter != working.end()) { auto range = std::equal_range(iter, working.end(), *iter, ByteWithPayload::key_less()); if (!std::is_sorted(range.first, range.second, ByteWithPayload::total_less())) return 2; iter = range.second; } if (!fast_is_permutation(input.cbegin(), input.cend(), working.cbegin())) return 99; return 0; }
34.5
95
0.581884
[ "vector" ]
b49379a8b310165b65d224081eb8f025eb71d10f
4,137
cc
C++
src/developer/debug/zxdb/client/target.cc
sunshinewithmoonlight/fuchsia-2003
02b23026dc7fecbad063210d5d45fa1b17feeb8b
[ "BSD-3-Clause" ]
null
null
null
src/developer/debug/zxdb/client/target.cc
sunshinewithmoonlight/fuchsia-2003
02b23026dc7fecbad063210d5d45fa1b17feeb8b
[ "BSD-3-Clause" ]
null
null
null
src/developer/debug/zxdb/client/target.cc
sunshinewithmoonlight/fuchsia-2003
02b23026dc7fecbad063210d5d45fa1b17feeb8b
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2018 The Fuchsia 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 "src/developer/debug/zxdb/client/target.h" #include "src/developer/debug/zxdb/client/setting_schema_definition.h" #include "src/developer/debug/zxdb/client/system.h" #include "src/developer/debug/zxdb/expr/vector_register_format.h" namespace zxdb { // Schema Definition ----------------------------------------------------------- static const char kShowStdoutDescription[] = R"( Whether this process should pipe its stdout/stderr to zxdb. If not set for a particular process, it will default to the system-wide setting.)"; const char* ClientSettings::Target::kBuildDirs = "build-dirs"; const char* ClientSettings::Target::kBuildDirsDescription = R"( List of paths to build direcories. These are the directories to which paths in the symbol files are relative to. When finding a source file, the debugger will search for it relative to each of these directories (there can be more than one because some files may be compiled in different direcrories than others). These directories don't necessarily need to exist on the local system. When using a crash dump and symbols from another computer you can specify where that computer's build directory would have been given your code location so relative paths will resolve to the correct local files.)"; const char* ClientSettings::Target::kVectorFormat = "vector-format"; const char* ClientSettings::Target::kVectorFormatDescription = R"( How to treat vector registers. This affects the display of vector registers in the "regs" command as well as what it means when you type a register name in an expression. Possible values: i8 / u8 : Array of signed/unsigned 8-bit integers. i16 / u16 : Array of signed/unsigned 16-bit integers. i32 / u32 : Array of signed/unsigned 32-bit integers. i64 / u64 : Array of signed/unsigned 64-bit integers. i128 / u128 : Array of signed/unsigned 128-bit integers. float : Array of single-precision floating point. double : Array of double-precision floating point.)"; // static std::vector<std::string> ClientSettings::Target::GetVectorFormatOptions() { return std::vector<std::string>{ kVectorRegisterFormatStr_Signed8, kVectorRegisterFormatStr_Unsigned8, kVectorRegisterFormatStr_Signed16, kVectorRegisterFormatStr_Unsigned16, kVectorRegisterFormatStr_Signed32, kVectorRegisterFormatStr_Unsigned32, kVectorRegisterFormatStr_Signed64, kVectorRegisterFormatStr_Unsigned64, kVectorRegisterFormatStr_Signed128, kVectorRegisterFormatStr_Unsigned128, kVectorRegisterFormatStr_Float, kVectorRegisterFormatStr_Double}; } namespace { fxl::RefPtr<SettingSchema> CreateSchema() { auto schema = fxl::MakeRefCounted<SettingSchema>(); schema->AddBool(ClientSettings::System::kShowStdout, kShowStdoutDescription, true); schema->AddList(ClientSettings::Target::kBuildDirs, ClientSettings::Target::kBuildDirsDescription, {}); schema->AddBool(ClientSettings::Thread::kDebugStepping, ClientSettings::Thread::kDebugSteppingDescription, false); schema->AddString( ClientSettings::Target::kVectorFormat, ClientSettings::Target::kVectorFormatDescription, kVectorRegisterFormatStr_Double, ClientSettings::Target::GetVectorFormatOptions()); return schema; } } // namespace // Target Implementation --------------------------------------------------------------------------- Target::Target(Session* session) : ClientObject(session), // Implementations can set up fallbacks if needed. settings_(GetSchema(), nullptr), weak_factory_(this) {} Target::~Target() = default; fxl::WeakPtr<Target> Target::GetWeakPtr() { return weak_factory_.GetWeakPtr(); } fxl::RefPtr<SettingSchema> Target::GetSchema() { // Will only run initialization once. InitializeSchemas(); static fxl::RefPtr<SettingSchema> schema = CreateSchema(); return schema; } } // namespace zxdb
40.165049
100
0.729272
[ "vector" ]
a337a6fc6a82193cd9da910e8c970e6583acf5f9
7,943
cpp
C++
src/util/type_byte_size.cpp
correcthorsebatterystaple/esbmc
1fc1aed3b7a4aa3a16c3fcd4a4f67f477da0c4cc
[ "BSD-3-Clause" ]
null
null
null
src/util/type_byte_size.cpp
correcthorsebatterystaple/esbmc
1fc1aed3b7a4aa3a16c3fcd4a4f67f477da0c4cc
[ "BSD-3-Clause" ]
null
null
null
src/util/type_byte_size.cpp
correcthorsebatterystaple/esbmc
1fc1aed3b7a4aa3a16c3fcd4a4f67f477da0c4cc
[ "BSD-3-Clause" ]
null
null
null
/*******************************************************************\ Module: Pointer Logic Author: Daniel Kroening, kroening@kroening.com \*******************************************************************/ #include <util/arith_tools.h> #include <util/c_types.h> #include <util/expr.h> #include <irep2/irep2_utils.h> #include <util/std_types.h> #include <util/type_byte_size.h> #include <util/message/format.h> BigInt member_offset(const type2tc &type, const irep_idt &member) { return member_offset_bits(type, member) / 8; } BigInt member_offset_bits(const type2tc &type, const irep_idt &member) { BigInt result = 0; // empty union generate an array if(!is_struct_type(type)) return result; unsigned idx = 0; const struct_type2t &thetype = to_struct_type(type); for(auto const &it : thetype.members) { if(thetype.member_names[idx] == member.as_string()) break; result += type_byte_size_bits(it); idx++; } return result; } BigInt type_byte_size_default(const type2tc &type, const BigInt &defaultval) { try { return type_byte_size(type); } catch(const array_type2t::dyn_sized_array_excp &e) { return defaultval; } } BigInt type_byte_size(const type2tc &type) { BigInt bits = type_byte_size_bits(type); return (bits + 7) / 8; } BigInt type_byte_size_bits(const type2tc &type) { switch(type->type_id) { // This is a gcc extension. // https://gcc.gnu.org/onlinedocs/gcc-4.8.0/gcc/Pointer-Arith.html case type2t::empty_id: return 1; case type2t::code_id: return 0; case type2t::symbol_id: assert( 0 && fmt::format("Symbolic type id in type_byte_size\n{}", *type).c_str()); case type2t::cpp_name_id: assert( 0 && fmt::format("C++ symbolic type id in type_byte_size\n{}", *type).c_str()); case type2t::bool_id: case type2t::unsignedbv_id: case type2t::signedbv_id: case type2t::fixedbv_id: case type2t::floatbv_id: case type2t::pointer_id: return type->get_width(); case type2t::string_id: // TODO: Strings of wchar will return the wrong result here return to_string_type(type).width * config.ansi_c.char_width; case type2t::array_id: { // Attempt to compute constant array offset. If we can't, we can't // reasonably return anything anyway, so throw. const array_type2t &t2 = to_array_type(type); if(t2.size_is_infinite) throw array_type2t::inf_sized_array_excp(); expr2tc arrsize = t2.array_size; simplify(arrsize); if(!is_constant_int2t(arrsize)) throw array_type2t::dyn_sized_array_excp(arrsize); BigInt subsize = type_byte_size_bits(t2.subtype); const constant_int2t &arrsize_int = to_constant_int2t(arrsize); return subsize * arrsize_int.value; } case type2t::struct_id: { // Compute the size of all members of this struct, and add padding bytes // so that they all start on wourd boundries. Also add any trailing bytes // necessary to make arrays align properly if malloc'd, see C89 6.3.3.4. BigInt accumulated_size = 0; for(auto const &it : to_struct_type(type).members) accumulated_size += type_byte_size_bits(it); // At the end of that, the tests above should have rounded accumulated size // up to a size that contains the required trailing padding for array // allocation alignment. return accumulated_size; } case type2t::union_id: { // Very simple: the largest field size, rounded up to a word boundry for // array allocation alignment. BigInt max_size = 0; for(auto const &it : to_union_type(type).members) max_size = std::max(max_size, type_byte_size_bits(it)); return max_size; } default: assert( 0 && fmt::format("Unrecognised type in type_byte_size_bits:\n{}", *type) .c_str()); abort(); } } expr2tc compute_pointer_offset_bits(const expr2tc &expr) { if(is_symbol2t(expr)) return gen_ulong(0); if(is_index2t(expr)) { const index2t &index = to_index2t(expr); BigInt sub_size; if(is_array_type(index.source_value)) { const array_type2t &arr_type = to_array_type(index.source_value->type); sub_size = type_byte_size_bits(arr_type.subtype); } else if(is_string_type(index.source_value)) { sub_size = 64; } else { throw std::runtime_error( "Unexpected index type in computer_pointer_offset"); } expr2tc result; if(is_constant_int2t(index.index)) { const constant_int2t &index_val = to_constant_int2t(index.index); result = gen_ulong(BigInt(sub_size * index_val.value).to_uint64()); } else { // Non constant, create multiply. // Index operand needs to be the bitwidth of a 'long'. expr2tc zero_ulong = gen_ulong(0); expr2tc the_index = index.index; if(the_index->type != zero_ulong->type) the_index = typecast2tc(zero_ulong->type, the_index); constant_int2tc tmp_size(zero_ulong->type, sub_size); result = mul2tc(zero_ulong->type, tmp_size, the_index); } // Also accumulate any pointer offset in the source object. result = add2tc( result->type, result, compute_pointer_offset_bits(index.source_value)); return result; } if(is_member2t(expr)) { const member2t &memb = to_member2t(expr); BigInt result; if(is_struct_type(memb.source_value->type)) { result = member_offset_bits(memb.source_value->type, memb.member); } else { result = 0; // Union offsets are always 0. } // Also accumulate any pointer offset in the source object. expr2tc res_expr = gen_ulong(result.to_uint64()); res_expr = add2tc( res_expr->type, res_expr, compute_pointer_offset_bits(memb.source_value)); return res_expr; } if(is_constant_expr(expr)) { // This is a constant struct, array, union, string, etc. There's nothing // at a lower level; the offset is zero. return gen_ulong(0); } if(is_typecast2t(expr)) { // Blast straight through. return compute_pointer_offset_bits(to_typecast2t(expr).from); } if(is_dynamic_object2t(expr)) { // This is a dynamic object represented something allocated; from the static // pointer analysis. Assume that this is the bottom of the expression. return gen_ulong(0); } if(is_dereference2t(expr)) { // This is a dereference at the base of a set of index/members. Here, we // can in theory end up evaluating across a large set of object types. So // there's no point continuing further or attempting to dereference, leave // it up to the caller to handle that. return gen_ulong(0); } throw std::runtime_error(fmt::format( "compute_pointer_offset, unexpected irep:\n{}", expr->pretty())); } expr2tc compute_pointer_offset(const expr2tc &expr) { expr2tc pointer_offset_bits = compute_pointer_offset_bits(expr); expr2tc result = div2tc(pointer_offset_bits->type, pointer_offset_bits, gen_ulong(8)); return result; } const expr2tc &get_base_object(const expr2tc &expr) { if(is_index2t(expr)) return get_base_object(to_index2t(expr).source_value); if(is_member2t(expr)) return get_base_object(to_member2t(expr).source_value); if(is_typecast2t(expr)) return get_base_object(to_typecast2t(expr).from); if(is_address_of2t(expr)) return get_base_object(to_address_of2t(expr).ptr_obj); return expr; } const irep_idt get_string_argument(const expr2tc &expr) { // Remove typecast if(is_typecast2t(expr)) return get_string_argument(to_typecast2t(expr).from); // Remove address_of if(is_address_of2t(expr)) return get_string_argument(to_address_of2t(expr).ptr_obj); // Remove index if(is_index2t(expr)) return get_string_argument(to_index2t(expr).source_value); if(is_constant_string2t(expr)) return to_constant_string2t(expr).value; return ""; }
26.565217
80
0.68211
[ "object" ]
a33ad8219fb59658ceeef97e3bc8616f9c3945e9
33,346
cpp
C++
corelib/src/DBDriver.cpp
freicaneca/RTABMapMod
95a1f386e90e09f7a96912343eb006bb3bc4e67a
[ "BSD-3-Clause" ]
null
null
null
corelib/src/DBDriver.cpp
freicaneca/RTABMapMod
95a1f386e90e09f7a96912343eb006bb3bc4e67a
[ "BSD-3-Clause" ]
null
null
null
corelib/src/DBDriver.cpp
freicaneca/RTABMapMod
95a1f386e90e09f7a96912343eb006bb3bc4e67a
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2010-2016, Mathieu Labbe - IntRoLab - Universite de Sherbrooke 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 Universite de Sherbrooke nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "rtabmap/core/DBDriver.h" #include "rtabmap/core/Signature.h" #include "rtabmap/core/VisualWord.h" #include "rtabmap/core/DBDriverSqlite3.h" #include "rtabmap/utilite/UConversion.h" #include "rtabmap/utilite/UMath.h" #include "rtabmap/utilite/ULogger.h" #include "rtabmap/utilite/UTimer.h" #include "rtabmap/utilite/UStl.h" namespace rtabmap { DBDriver * DBDriver::create(const ParametersMap & parameters) { // well, we only have Sqlite3 database type for now :P return new DBDriverSqlite3(parameters); } DBDriver::DBDriver(const ParametersMap & parameters) : _emptyTrashesTime(0), _timestampUpdate(true) { this->parseParameters(parameters); } DBDriver::~DBDriver() { join(true); this->emptyTrashes(); } void DBDriver::parseParameters(const ParametersMap & parameters) { } void DBDriver::closeConnection(bool save, const std::string & outputUrl) { UDEBUG("isRunning=%d", this->isRunning()); this->join(true); UDEBUG(""); if(save) { this->emptyTrashes(); } else { _trashesMutex.lock(); _trashSignatures.clear(); _trashVisualWords.clear(); _trashesMutex.unlock(); } _dbSafeAccessMutex.lock(); this->disconnectDatabaseQuery(save, outputUrl); _dbSafeAccessMutex.unlock(); UDEBUG(""); } bool DBDriver::openConnection(const std::string & url, bool overwritten) { UDEBUG(""); _url = url; _dbSafeAccessMutex.lock(); if(this->connectDatabaseQuery(url, overwritten)) { _dbSafeAccessMutex.unlock(); return true; } _dbSafeAccessMutex.unlock(); return false; } bool DBDriver::isConnected() const { bool r; _dbSafeAccessMutex.lock(); r = isConnectedQuery(); _dbSafeAccessMutex.unlock(); return r; } // In bytes long DBDriver::getMemoryUsed() const { long bytes; _dbSafeAccessMutex.lock(); bytes = getMemoryUsedQuery(); _dbSafeAccessMutex.unlock(); return bytes; } long DBDriver::getNodesMemoryUsed() const { long bytes; _dbSafeAccessMutex.lock(); bytes = getNodesMemoryUsedQuery(); _dbSafeAccessMutex.unlock(); return bytes; } long DBDriver::getLinksMemoryUsed() const { long bytes; _dbSafeAccessMutex.lock(); bytes = getLinksMemoryUsedQuery(); _dbSafeAccessMutex.unlock(); return bytes; } long DBDriver::getImagesMemoryUsed() const { long bytes; _dbSafeAccessMutex.lock(); bytes = getImagesMemoryUsedQuery(); _dbSafeAccessMutex.unlock(); return bytes; } long DBDriver::getDepthImagesMemoryUsed() const { long bytes; _dbSafeAccessMutex.lock(); bytes = getDepthImagesMemoryUsedQuery(); _dbSafeAccessMutex.unlock(); return bytes; } long DBDriver::getCalibrationsMemoryUsed() const { long bytes; _dbSafeAccessMutex.lock(); bytes = getCalibrationsMemoryUsedQuery(); _dbSafeAccessMutex.unlock(); return bytes; } long DBDriver::getGridsMemoryUsed() const { long bytes; _dbSafeAccessMutex.lock(); bytes = getGridsMemoryUsedQuery(); _dbSafeAccessMutex.unlock(); return bytes; } long DBDriver::getLaserScansMemoryUsed() const { long bytes; _dbSafeAccessMutex.lock(); bytes = getLaserScansMemoryUsedQuery(); _dbSafeAccessMutex.unlock(); return bytes; } long DBDriver::getUserDataMemoryUsed() const { long bytes; _dbSafeAccessMutex.lock(); bytes = getUserDataMemoryUsedQuery(); _dbSafeAccessMutex.unlock(); return bytes; } long DBDriver::getWordsMemoryUsed() const { long bytes; _dbSafeAccessMutex.lock(); bytes = getWordsMemoryUsedQuery(); _dbSafeAccessMutex.unlock(); return bytes; } long DBDriver::getFeaturesMemoryUsed() const { long bytes; _dbSafeAccessMutex.lock(); bytes = getFeaturesMemoryUsedQuery(); _dbSafeAccessMutex.unlock(); return bytes; } long DBDriver::getStatisticsMemoryUsed() const { long bytes; _dbSafeAccessMutex.lock(); bytes = getStatisticsMemoryUsedQuery(); _dbSafeAccessMutex.unlock(); return bytes; } int DBDriver::getLastNodesSize() const { int nodes; _dbSafeAccessMutex.lock(); nodes = getLastNodesSizeQuery(); _dbSafeAccessMutex.unlock(); return nodes; } int DBDriver::getLastDictionarySize() const { int words; _dbSafeAccessMutex.lock(); words = getLastDictionarySizeQuery(); _dbSafeAccessMutex.unlock(); return words; } int DBDriver::getTotalNodesSize() const { int words; _dbSafeAccessMutex.lock(); words = getTotalNodesSizeQuery(); _dbSafeAccessMutex.unlock(); return words; } int DBDriver::getTotalDictionarySize() const { int words; _dbSafeAccessMutex.lock(); words = getTotalDictionarySizeQuery(); _dbSafeAccessMutex.unlock(); return words; } ParametersMap DBDriver::getLastParameters() const { ParametersMap parameters; _dbSafeAccessMutex.lock(); parameters = getLastParametersQuery(); _dbSafeAccessMutex.unlock(); return parameters; } std::map<std::string, float> DBDriver::getStatistics(int nodeId, double & stamp, std::vector<int> * wmState) const { std::map<std::string, float> statistics; _dbSafeAccessMutex.lock(); statistics = getStatisticsQuery(nodeId, stamp, wmState); _dbSafeAccessMutex.unlock(); return statistics; } std::map<int, std::pair<std::map<std::string, float>, double> > DBDriver::getAllStatistics() const { std::map<int, std::pair<std::map<std::string, float>, double> > statistics; _dbSafeAccessMutex.lock(); statistics = getAllStatisticsQuery(); _dbSafeAccessMutex.unlock(); return statistics; } std::map<int, std::vector<int> > DBDriver::getAllStatisticsWmStates() const { std::map<int, std::vector<int> > wmStates; _dbSafeAccessMutex.lock(); wmStates = getAllStatisticsWmStatesQuery(); _dbSafeAccessMutex.unlock(); return wmStates; } std::string DBDriver::getDatabaseVersion() const { std::string version = "0.0.0"; _dbSafeAccessMutex.lock(); getDatabaseVersionQuery(version); _dbSafeAccessMutex.unlock(); return version; } void DBDriver::mainLoop() { this->emptyTrashes(); this->kill(); // Do it only once } void DBDriver::beginTransaction() const { _transactionMutex.lock(); ULOGGER_DEBUG(""); this->executeNoResultQuery("BEGIN TRANSACTION;"); } void DBDriver::commit() const { ULOGGER_DEBUG(""); this->executeNoResultQuery("COMMIT;"); _transactionMutex.unlock(); } void DBDriver::executeNoResult(const std::string & sql) const { _dbSafeAccessMutex.lock(); this->executeNoResultQuery(sql); _dbSafeAccessMutex.unlock(); } void DBDriver::emptyTrashes(bool async) { if(async) { ULOGGER_DEBUG("Async emptying, start the trash thread"); this->start(); return; } UTimer totalTime; totalTime.start(); std::map<int, Signature*> signatures; std::map<int, VisualWord*> visualWords; _trashesMutex.lock(); { ULOGGER_DEBUG("signatures=%d, visualWords=%d", _trashSignatures.size(), _trashVisualWords.size()); signatures = _trashSignatures; visualWords = _trashVisualWords; _trashSignatures.clear(); _trashVisualWords.clear(); _dbSafeAccessMutex.lock(); } _trashesMutex.unlock(); if(signatures.size() || visualWords.size()) { this->beginTransaction(); UTimer timer; timer.start(); if(signatures.size()) { if(this->isConnected()) { //Only one query to the database this->saveOrUpdate(uValues(signatures)); } for(std::map<int, Signature *>::iterator iter=signatures.begin(); iter!=signatures.end(); ++iter) { delete iter->second; } signatures.clear(); ULOGGER_DEBUG("Time emptying memory signatures trash = %f...", timer.ticks()); } if(visualWords.size()) { if(this->isConnected()) { //Only one query to the database this->saveOrUpdate(uValues(visualWords)); } for(std::map<int, VisualWord *>::iterator iter=visualWords.begin(); iter!=visualWords.end(); ++iter) { delete (*iter).second; } visualWords.clear(); ULOGGER_DEBUG("Time emptying memory visualWords trash = %f...", timer.ticks()); } this->commit(); } _emptyTrashesTime = totalTime.ticks(); ULOGGER_DEBUG("Total time emptying trashes = %fs...", _emptyTrashesTime); _dbSafeAccessMutex.unlock(); } void DBDriver::asyncSave(Signature * s) { if(s) { UDEBUG("s=%d", s->id()); _trashesMutex.lock(); { _trashSignatures.insert(std::pair<int, Signature*>(s->id(), s)); } _trashesMutex.unlock(); } } void DBDriver::asyncSave(VisualWord * vw) { if(vw) { _trashesMutex.lock(); { _trashVisualWords.insert(std::pair<int, VisualWord*>(vw->id(), vw)); } _trashesMutex.unlock(); } } void DBDriver::saveOrUpdate(const std::vector<Signature *> & signatures) { ULOGGER_DEBUG(""); std::list<Signature *> toSave; std::list<Signature *> toUpdate; if(this->isConnected() && signatures.size()) { for(std::vector<Signature *>::const_iterator i=signatures.begin(); i!=signatures.end();++i) { if((*i)->isSaved()) { toUpdate.push_back(*i); } else { toSave.push_back(*i); } } if(toUpdate.size()) { this->updateQuery(toUpdate, _timestampUpdate); } if(toSave.size()) { this->saveQuery(toSave); } } } void DBDriver::saveOrUpdate(const std::vector<VisualWord *> & words) const { ULOGGER_DEBUG("words.size=%d", (int)words.size()); std::list<VisualWord *> toSave; std::list<VisualWord *> toUpdate; if(this->isConnected() && words.size()) { for(std::vector<VisualWord *>::const_iterator i=words.begin(); i!=words.end();++i) { if((*i)->isSaved()) { toUpdate.push_back(*i); } else { toSave.push_back(*i); } } if(toUpdate.size()) { this->updateQuery(toUpdate, _timestampUpdate); } if(toSave.size()) { this->saveQuery(toSave); } } } void DBDriver::addLink(const Link & link) { _dbSafeAccessMutex.lock(); this->addLinkQuery(link); _dbSafeAccessMutex.unlock(); } void DBDriver::removeLink(int from, int to) { this->executeNoResult(uFormat("DELETE FROM Link WHERE from_id=%d and to_id=%d", from, to).c_str()); } void DBDriver::updateLink(const Link & link) { _dbSafeAccessMutex.lock(); this->updateLinkQuery(link); _dbSafeAccessMutex.unlock(); } void DBDriver::updateOccupancyGrid( int nodeId, const cv::Mat & ground, const cv::Mat & obstacles, const cv::Mat & empty, float cellSize, const cv::Point3f & viewpoint) { _dbSafeAccessMutex.lock(); //just to make sure the occupancy grids are compressed for convenience SensorData data; data.setOccupancyGrid(ground, obstacles, empty, cellSize, viewpoint); this->updateOccupancyGridQuery( nodeId, data.gridGroundCellsCompressed(), data.gridObstacleCellsCompressed(), data.gridEmptyCellsCompressed(), cellSize, viewpoint); _dbSafeAccessMutex.unlock(); } void DBDriver::updateDepthImage(int nodeId, const cv::Mat & image) { _dbSafeAccessMutex.lock(); this->updateDepthImageQuery( nodeId, image); _dbSafeAccessMutex.unlock(); } void DBDriver::load(VWDictionary * dictionary, bool lastStateOnly) const { _dbSafeAccessMutex.lock(); this->loadQuery(dictionary, lastStateOnly); _dbSafeAccessMutex.unlock(); } void DBDriver::loadLastNodes(std::list<Signature *> & signatures) const { _dbSafeAccessMutex.lock(); this->loadLastNodesQuery(signatures); _dbSafeAccessMutex.unlock(); } void DBDriver::loadSignatures(const std::list<int> & signIds, std::list<Signature *> & signatures, std::set<int> * loadedFromTrash) { UDEBUG(""); // look up in the trash before the database std::list<int> ids = signIds; bool valueFound = false; _trashesMutex.lock(); { for(std::list<int>::iterator iter = ids.begin(); iter != ids.end();) { valueFound = false; for(std::map<int, Signature*>::iterator sIter = _trashSignatures.begin(); sIter!=_trashSignatures.end();) { if(sIter->first == *iter) { signatures.push_back(sIter->second); _trashSignatures.erase(sIter++); valueFound = true; break; } else { ++sIter; } } if(valueFound) { if(loadedFromTrash) { loadedFromTrash->insert(*iter); } iter = ids.erase(iter); } else { ++iter; } } } _trashesMutex.unlock(); UDEBUG(""); if(ids.size()) { _dbSafeAccessMutex.lock(); this->loadSignaturesQuery(ids, signatures); _dbSafeAccessMutex.unlock(); } } void DBDriver::loadWords(const std::set<int> & wordIds, std::list<VisualWord *> & vws) { // look up in the trash before the database std::set<int> ids = wordIds; std::map<int, VisualWord*>::iterator wIter; std::list<VisualWord *> puttedBack; _trashesMutex.lock(); { if(_trashVisualWords.size()) { for(std::set<int>::iterator iter = ids.begin(); iter != ids.end();) { UASSERT(*iter>0); wIter = _trashVisualWords.find(*iter); if(wIter != _trashVisualWords.end()) { UDEBUG("put back word %d from trash", *iter); puttedBack.push_back(wIter->second); _trashVisualWords.erase(wIter); ids.erase(iter++); } else { ++iter; } } } } _trashesMutex.unlock(); if(ids.size()) { _dbSafeAccessMutex.lock(); this->loadWordsQuery(ids, vws); _dbSafeAccessMutex.unlock(); uAppend(vws, puttedBack); } else if(puttedBack.size()) { uAppend(vws, puttedBack); } } void DBDriver::loadNodeData(std::list<Signature *> & signatures, bool images, bool scan, bool userData, bool occupancyGrid) const { // Don't look in the trash, we assume that if we want to load // data of a signature, it is not in thrash! Print an error if so. _trashesMutex.lock(); if(_trashSignatures.size()) { for(std::list<Signature *>::iterator iter=signatures.begin(); iter!=signatures.end(); ++iter) { UASSERT(*iter != 0); UASSERT_MSG(!uContains(_trashSignatures, (*iter)->id()), uFormat("Signature %d should not be used when transferred to trash!!!!", (*iter)->id()).c_str()); } } _trashesMutex.unlock(); _dbSafeAccessMutex.lock(); this->loadNodeDataQuery(signatures, images, scan, userData, occupancyGrid); _dbSafeAccessMutex.unlock(); } void DBDriver::getNodeData( int signatureId, SensorData & data, bool images, bool scan, bool userData, bool occupancyGrid) const { bool found = false; // look in the trash _trashesMutex.lock(); if(uContains(_trashSignatures, signatureId)) { const Signature * s = _trashSignatures.at(signatureId); if(!s->sensorData().imageCompressed().empty() || !s->sensorData().laserScanCompressed().isEmpty() || !s->sensorData().userDataCompressed().empty() || s->sensorData().gridCellSize() != 0.0f || !s->isSaved()) { data = (SensorData)s->sensorData(); found = true; } } _trashesMutex.unlock(); if(!found) { _dbSafeAccessMutex.lock(); std::list<Signature *> signatures; Signature tmp(signatureId); signatures.push_back(&tmp); loadNodeDataQuery(signatures, images, scan, userData, occupancyGrid); data = signatures.front()->sensorData(); _dbSafeAccessMutex.unlock(); } } bool DBDriver::getCalibration( int signatureId, std::vector<CameraModel> & models, StereoCameraModel & stereoModel) const { UDEBUG(""); bool found = false; // look in the trash _trashesMutex.lock(); if(uContains(_trashSignatures, signatureId)) { models = _trashSignatures.at(signatureId)->sensorData().cameraModels(); stereoModel = _trashSignatures.at(signatureId)->sensorData().stereoCameraModel(); found = true; } _trashesMutex.unlock(); if(!found) { _dbSafeAccessMutex.lock(); found = this->getCalibrationQuery(signatureId, models, stereoModel); _dbSafeAccessMutex.unlock(); } return found; } bool DBDriver::getLaserScanInfo( int signatureId, LaserScan & info) const { UDEBUG(""); bool found = false; // look in the trash _trashesMutex.lock(); if(uContains(_trashSignatures, signatureId)) { info = _trashSignatures.at(signatureId)->sensorData().laserScanCompressed(); found = true; } _trashesMutex.unlock(); if(!found) { _dbSafeAccessMutex.lock(); found = this->getLaserScanInfoQuery(signatureId, info); _dbSafeAccessMutex.unlock(); } return found; } bool DBDriver::getNodeInfo( int signatureId, Transform & pose, int & mapId, int & weight, std::string & label, double & stamp, Transform & groundTruthPose, std::vector<float> & velocity, GPS & gps) const { bool found = false; // look in the trash _trashesMutex.lock(); if(uContains(_trashSignatures, signatureId)) { pose = _trashSignatures.at(signatureId)->getPose(); mapId = _trashSignatures.at(signatureId)->mapId(); weight = _trashSignatures.at(signatureId)->getWeight(); label = _trashSignatures.at(signatureId)->getLabel(); stamp = _trashSignatures.at(signatureId)->getStamp(); groundTruthPose = _trashSignatures.at(signatureId)->getGroundTruthPose(); gps = _trashSignatures.at(signatureId)->sensorData().gps(); found = true; } _trashesMutex.unlock(); if(!found) { _dbSafeAccessMutex.lock(); found = this->getNodeInfoQuery(signatureId, pose, mapId, weight, label, stamp, groundTruthPose, velocity, gps); _dbSafeAccessMutex.unlock(); } return found; } void DBDriver::loadLinks(int signatureId, std::map<int, Link> & links, Link::Type type) const { bool found = false; // look in the trash _trashesMutex.lock(); if(uContains(_trashSignatures, signatureId)) { const Signature * s = _trashSignatures.at(signatureId); UASSERT(s != 0); for(std::map<int, Link>::const_iterator nIter = s->getLinks().begin(); nIter!=s->getLinks().end(); ++nIter) { if(type == Link::kUndef || nIter->second.type() == type) { links.insert(*nIter); } } found = true; } _trashesMutex.unlock(); if(!found) { _dbSafeAccessMutex.lock(); this->loadLinksQuery(signatureId, links, type); _dbSafeAccessMutex.unlock(); } } void DBDriver::getWeight(int signatureId, int & weight) const { bool found = false; // look in the trash _trashesMutex.lock(); if(uContains(_trashSignatures, signatureId)) { weight = _trashSignatures.at(signatureId)->getWeight(); found = true; } _trashesMutex.unlock(); if(!found) { _dbSafeAccessMutex.lock(); this->getWeightQuery(signatureId, weight); _dbSafeAccessMutex.unlock(); } } void DBDriver::getAllNodeIds(std::set<int> & ids, bool ignoreChildren, bool ignoreBadSignatures) const { // look in the trash _trashesMutex.lock(); if(_trashSignatures.size()) { for(std::map<int, Signature*>::const_iterator sIter = _trashSignatures.begin(); sIter!=_trashSignatures.end(); ++sIter) { bool hasNeighbors = !ignoreChildren; if(ignoreChildren) { for(std::map<int, Link>::const_iterator nIter = sIter->second->getLinks().begin(); nIter!=sIter->second->getLinks().end(); ++nIter) { if(nIter->second.type() == Link::kNeighbor || nIter->second.type() == Link::kNeighborMerged) { hasNeighbors = true; break; } } } if(hasNeighbors) { ids.insert(sIter->first); } } std::vector<int> keys = uKeys(_trashSignatures); } _trashesMutex.unlock(); _dbSafeAccessMutex.lock(); this->getAllNodeIdsQuery(ids, ignoreChildren, ignoreBadSignatures); _dbSafeAccessMutex.unlock(); } void DBDriver::getAllLinks(std::multimap<int, Link> & links, bool ignoreNullLinks) const { _dbSafeAccessMutex.lock(); this->getAllLinksQuery(links, ignoreNullLinks); _dbSafeAccessMutex.unlock(); // look in the trash _trashesMutex.lock(); if(_trashSignatures.size()) { for(std::map<int, Signature*>::const_iterator iter=_trashSignatures.begin(); iter!=_trashSignatures.end(); ++iter) { links.erase(iter->first); for(std::map<int, Link>::const_iterator jter=iter->second->getLinks().begin(); jter!=iter->second->getLinks().end(); ++jter) { if(!ignoreNullLinks || jter->second.isValid()) { links.insert(std::make_pair(iter->first, jter->second)); } } } } _trashesMutex.unlock(); } void DBDriver::getLastNodeId(int & id) const { // look in the trash _trashesMutex.lock(); if(_trashSignatures.size()) { id = _trashSignatures.rbegin()->first; } _trashesMutex.unlock(); _dbSafeAccessMutex.lock(); this->getLastIdQuery("Node", id); int statisticsId = 0; if(uStrNumCmp(this->getDatabaseVersion(), "0.11.11") >= 0) { this->getLastIdQuery("Statistics", statisticsId); if(statisticsId > id) { id = statisticsId; } } _dbSafeAccessMutex.unlock(); } void DBDriver::getLastWordId(int & id) const { // look in the trash _trashesMutex.lock(); if(_trashVisualWords.size()) { id = _trashVisualWords.rbegin()->first; } _trashesMutex.unlock(); _dbSafeAccessMutex.lock(); this->getLastIdQuery("Word", id); _dbSafeAccessMutex.unlock(); } void DBDriver::getInvertedIndexNi(int signatureId, int & ni) const { bool found = false; // look in the trash _trashesMutex.lock(); if(uContains(_trashSignatures, signatureId)) { ni = _trashSignatures.at(signatureId)->getWords().size(); found = true; } _trashesMutex.unlock(); if(!found) { _dbSafeAccessMutex.lock(); this->getInvertedIndexNiQuery(signatureId, ni); _dbSafeAccessMutex.unlock(); } } void DBDriver::getNodeIdByLabel(const std::string & label, int & id) const { if(!label.empty()) { int idFound = 0; // look in the trash _trashesMutex.lock(); for(std::map<int, Signature*>::const_iterator sIter = _trashSignatures.begin(); sIter!=_trashSignatures.end(); ++sIter) { if(sIter->second->getLabel().compare(label) == 0) { idFound = sIter->first; break; } } _trashesMutex.unlock(); // then look in the database if(idFound == 0) { _dbSafeAccessMutex.lock(); this->getNodeIdByLabelQuery(label, id); _dbSafeAccessMutex.unlock(); } else { id = idFound; } } else { UWARN("Can't search with an empty label!"); } } void DBDriver::getAllLabels(std::map<int, std::string> & labels) const { // look in the trash _trashesMutex.lock(); for(std::map<int, Signature*>::const_iterator sIter = _trashSignatures.begin(); sIter!=_trashSignatures.end(); ++sIter) { if(!sIter->second->getLabel().empty()) { labels.insert(std::make_pair(sIter->first, sIter->second->getLabel())); } } _trashesMutex.unlock(); // then look in the database _dbSafeAccessMutex.lock(); this->getAllLabelsQuery(labels); _dbSafeAccessMutex.unlock(); } void DBDriver::addInfoAfterRun( int stMemSize, int lastSignAdded, int processMemUsed, int databaseMemUsed, int dictionarySize, const ParametersMap & parameters) const { ULOGGER_DEBUG(""); if(this->isConnected()) { std::stringstream query; if(uStrNumCmp(this->getDatabaseVersion(), "0.11.8") >= 0) { std::string param = Parameters::serialize(parameters); if(uStrNumCmp(this->getDatabaseVersion(), "0.11.11") >= 0) { query << "INSERT INTO Info(STM_size,last_sign_added,process_mem_used,database_mem_used,dictionary_size,parameters) values(" << stMemSize << "," << lastSignAdded << "," << processMemUsed << "," << databaseMemUsed << "," << dictionarySize << "," "\"" << param.c_str() << "\");"; } else { query << "INSERT INTO Statistics(STM_size,last_sign_added,process_mem_used,database_mem_used,dictionary_size,parameters) values(" << stMemSize << "," << lastSignAdded << "," << processMemUsed << "," << databaseMemUsed << "," << dictionarySize << "," "\"" << param.c_str() << "\");"; } } else { query << "INSERT INTO Statistics(STM_size,last_sign_added,process_mem_used,database_mem_used,dictionary_size) values(" << stMemSize << "," << lastSignAdded << "," << processMemUsed << "," << databaseMemUsed << "," << dictionarySize << ");"; } this->executeNoResultQuery(query.str()); } } void DBDriver::addStatistics(const Statistics & statistics) const { _dbSafeAccessMutex.lock(); addStatisticsQuery(statistics); _dbSafeAccessMutex.unlock(); } void DBDriver::savePreviewImage(const cv::Mat & image) const { _dbSafeAccessMutex.lock(); savePreviewImageQuery(image); _dbSafeAccessMutex.unlock(); } cv::Mat DBDriver::loadPreviewImage() const { _dbSafeAccessMutex.lock(); cv::Mat image = loadPreviewImageQuery(); _dbSafeAccessMutex.unlock(); return image; } void DBDriver::saveOptimizedPoses(const std::map<int, Transform> & optimizedPoses, const Transform & lastlocalizationPose) const { _dbSafeAccessMutex.lock(); saveOptimizedPosesQuery(optimizedPoses, lastlocalizationPose); _dbSafeAccessMutex.unlock(); } std::map<int, Transform> DBDriver::loadOptimizedPoses(Transform * lastlocalizationPose) const { _dbSafeAccessMutex.lock(); std::map<int, Transform> poses = loadOptimizedPosesQuery(lastlocalizationPose); _dbSafeAccessMutex.unlock(); return poses; } void DBDriver::save2DMap(const cv::Mat & map, float xMin, float yMin, float cellSize) const { _dbSafeAccessMutex.lock(); save2DMapQuery(map, xMin, yMin, cellSize); _dbSafeAccessMutex.unlock(); } cv::Mat DBDriver::load2DMap(float & xMin, float & yMin, float & cellSize) const { _dbSafeAccessMutex.lock(); cv::Mat map = load2DMapQuery(xMin, yMin, cellSize); _dbSafeAccessMutex.unlock(); return map; } void DBDriver::saveOptimizedMesh( const cv::Mat & cloud, const std::vector<std::vector<std::vector<unsigned int> > > & polygons, #if PCL_VERSION_COMPARE(>=, 1, 8, 0) const std::vector<std::vector<Eigen::Vector2f, Eigen::aligned_allocator<Eigen::Vector2f> > > & texCoords, #else const std::vector<std::vector<Eigen::Vector2f> > & texCoords, #endif const cv::Mat & textures) const { _dbSafeAccessMutex.lock(); saveOptimizedMeshQuery(cloud, polygons, texCoords, textures); _dbSafeAccessMutex.unlock(); } cv::Mat DBDriver::loadOptimizedMesh( std::vector<std::vector<std::vector<unsigned int> > > * polygons, #if PCL_VERSION_COMPARE(>=, 1, 8, 0) std::vector<std::vector<Eigen::Vector2f, Eigen::aligned_allocator<Eigen::Vector2f> > > * texCoords, #else std::vector<std::vector<Eigen::Vector2f> > * texCoords, #endif cv::Mat * textures) const { _dbSafeAccessMutex.lock(); cv::Mat cloud = loadOptimizedMeshQuery(polygons, texCoords, textures); _dbSafeAccessMutex.unlock(); return cloud; } void DBDriver::generateGraph( const std::string & fileName, const std::set<int> & idsInput, const std::map<int, Signature *> & otherSignatures) { if(this->isConnected()) { if(!fileName.empty()) { FILE* fout = 0; #ifdef _MSC_VER fopen_s(&fout, fileName.c_str(), "w"); #else fout = fopen(fileName.c_str(), "w"); #endif if (!fout) { UERROR("Cannot open file %s!", fileName.c_str()); return; } std::set<int> ids; if(idsInput.size() == 0) { this->getAllNodeIds(ids); UDEBUG("ids.size()=%d", ids.size()); for(std::map<int, Signature*>::const_iterator iter=otherSignatures.begin(); iter!=otherSignatures.end(); ++iter) { ids.insert(iter->first); } } else { ids = idsInput; } const char * colorG = "green"; const char * colorP = "pink"; const char * colorNM = "blue"; UINFO("Generating map with %d locations", ids.size()); fprintf(fout, "digraph G {\n"); for(std::set<int>::iterator i=ids.begin(); i!=ids.end(); ++i) { if(otherSignatures.find(*i) == otherSignatures.end()) { int id = *i; std::map<int, Link> links; this->loadLinks(id, links); int weight = 0; this->getWeight(id, weight); for(std::map<int, Link>::iterator iter = links.begin(); iter!=links.end(); ++iter) { int weightNeighbor = 0; if(otherSignatures.find(iter->first) == otherSignatures.end()) { this->getWeight(iter->first, weightNeighbor); } else { weightNeighbor = otherSignatures.find(iter->first)->second->getWeight(); } //UDEBUG("Add neighbor link from %d to %d", id, iter->first); if(iter->second.type() == Link::kNeighbor) { fprintf(fout, " \"%d\\n%d\" -> \"%d\\n%d\"\n", id, weight, iter->first, weightNeighbor); } else if(iter->second.type() == Link::kNeighborMerged) { //merged neighbor fprintf(fout, " \"%d\\n%d\" -> \"%d\\n%d\" [label=\"M\", fontcolor=%s, fontsize=8];\n", id, weight, iter->first, weightNeighbor, colorNM); } else if(iter->first > id) { //loop fprintf(fout, " \"%d\\n%d\" -> \"%d\\n%d\" [label=\"L\", fontcolor=%s, fontsize=8];\n", id, weight, iter->first, weightNeighbor, colorG); } else { //child fprintf(fout, " \"%d\\n%d\" -> \"%d\\n%d\" [label=\"C\", fontcolor=%s, fontsize=8];\n", id, weight, iter->first, weightNeighbor, colorP); } } } } for(std::map<int, Signature*>::const_iterator i=otherSignatures.begin(); i!=otherSignatures.end(); ++i) { if(ids.find(i->first) != ids.end()) { int id = i->second->id(); const std::map<int, Link> & links = i->second->getLinks(); int weight = i->second->getWeight(); for(std::map<int, Link>::const_iterator iter = links.begin(); iter!=links.end(); ++iter) { int weightNeighbor = 0; const Signature * s = uValue(otherSignatures, iter->first, (Signature*)0); if(s) { weightNeighbor = s->getWeight(); } else { this->getWeight(iter->first, weightNeighbor); } //UDEBUG("Add neighbor link from %d to %d", id, iter->first); if(iter->second.type() == Link::kNeighbor) { fprintf(fout, " \"%d\\n%d\" -> \"%d\\n%d\"\n", id, weight, iter->first, weightNeighbor); } else if(iter->second.type() == Link::kNeighborMerged) { fprintf(fout, " \"%d\\n%d\" -> \"%d\\n%d\" [label=\"M\", fontcolor=%s, fontsize=8];\n", id, weight, iter->first, weightNeighbor, colorNM); } else if(iter->first > id) { //loop fprintf(fout, " \"%d\\n%d\" -> \"%d\\n%d\" [label=\"L\", fontcolor=%s, fontsize=8];\n", id, weight, iter->first, weightNeighbor, colorG); } else if(iter->first != id) { //child fprintf(fout, " \"%d\\n%d\" -> \"%d\\n%d\" [label=\"C\", fontcolor=%s, fontsize=8];\n", id, weight, iter->first, weightNeighbor, colorP); } } } } fprintf(fout, "}\n"); fclose(fout); UINFO("Graph saved to \"%s\" (Tip: $ neato -Tpdf \"%s\" -o out.pdf)", fileName.c_str(), fileName.c_str()); } } } } // namespace rtabmap
25.749807
158
0.646194
[ "vector", "transform" ]