hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequencelengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequencelengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequencelengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
816278711cb11e8e796b3a24f2135f307fb43b95
7,671
hpp
C++
src/base/command/NonlinearConstraint.hpp
supalogix/GMAT
eea9987ef0978b3e6702e70b587a098b2cbce14e
[ "Apache-2.0" ]
null
null
null
src/base/command/NonlinearConstraint.hpp
supalogix/GMAT
eea9987ef0978b3e6702e70b587a098b2cbce14e
[ "Apache-2.0" ]
null
null
null
src/base/command/NonlinearConstraint.hpp
supalogix/GMAT
eea9987ef0978b3e6702e70b587a098b2cbce14e
[ "Apache-2.0" ]
null
null
null
//$Id$ //------------------------------------------------------------------------------ // NonlinearConstraint //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool. // // Copyright (c) 2002 - 2017 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. // All Other 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. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract // number NNG04CC06P // // Author: Wendy Shoan (GSFC/MAB) // Created: 2006.08.14 // /** * Definition for the NonlinearConstraint command class */ //------------------------------------------------------------------------------ #ifndef NonlinearConstraint_hpp #define NonlinearConstraint_hpp #include "SolverSequenceCommand.hpp" #include "Solver.hpp" #include "Parameter.hpp" #include "ElementWrapper.hpp" /** * Command that manages processing for targeter goals. */ class GMAT_API NonlinearConstraint : public SolverSequenceCommand { public: NonlinearConstraint(); NonlinearConstraint(const NonlinearConstraint& nlc); NonlinearConstraint& operator=(const NonlinearConstraint& nlc); virtual ~NonlinearConstraint(); // inherited from GmatBase virtual GmatBase* Clone() const; virtual bool RenameRefObject(const Gmat::ObjectType type, const std::string &oldName, const std::string &newName); virtual const ObjectTypeArray& GetRefObjectTypeArray(); virtual const StringArray& GetRefObjectNameArray(const Gmat::ObjectType type); // Parameter accessors virtual std::string GetParameterText(const Integer id) const; virtual Integer GetParameterID(const std::string &str) const; virtual Gmat::ParameterType GetParameterType(const Integer id) const; virtual std::string GetParameterTypeString(const Integer id) const; virtual Real GetRealParameter(const Integer id) const; virtual Real SetRealParameter(const Integer id, const Real value); virtual std::string GetStringParameter(const Integer id) const; virtual bool SetStringParameter(const Integer id, const char *value); virtual bool SetStringParameter(const Integer id, const std::string &value); virtual bool SetRefObject(GmatBase *obj, const Gmat::ObjectType type, const std::string &name = ""); // Inherited methods overridden from the base class virtual bool InterpretAction(); virtual const StringArray& GetWrapperObjectNameArray(bool completeSet = false); virtual bool SetElementWrapper(ElementWrapper* toWrapper, const std::string &withName); virtual void ClearWrappers(); virtual bool Initialize(); virtual bool Execute(); virtual void RunComplete(); virtual const std::string& GetGeneratingString(Gmat::WriteMode mode, const std::string &prefix, const std::string &useName); DEFAULT_TO_NO_CLONES protected: // Parameter IDs enum { OPTIMIZER_NAME = SolverSequenceCommandParamCount, CONSTRAINT_ARG1, OPERATOR, CONSTRAINT_ARG2, TOLERANCE, NonlinearConstraintParamCount }; static const std::string PARAMETER_TEXT[NonlinearConstraintParamCount - SolverSequenceCommandParamCount]; static const Gmat::ParameterType PARAMETER_TYPE[NonlinearConstraintParamCount - SolverSequenceCommandParamCount]; enum Operator { LESS_THAN_OR_EQUAL = 0, GREATER_THAN_OR_EQUAL, EQUAL }; static const std::string OP_STRINGS[3]; /// The name of the spacecraft that gets maneuvered std::string optimizerName; /// The optimizer instance used to manage the optimizer state machine Solver *optimizer; /// Name of the variable to be constrained std::string arg1Name; // pointer to the Variable that is to be minimized //Parameter *constraint; ElementWrapper *arg1; /// most recent value of the variable Real constraintValue; // do I still need this? /// name of the parameter part of the right-hand-side std::string arg2Name; //Parameter *nlcParm; ElementWrapper *arg2; /// String of value array name // I don't think I need any of this stuff //std::string nlcArrName; /// constraint array row index variable name //std::string nlcArrRowStr; /// constraint array column index variable name //std::string nlcArrColStr; /// constraint array row index //Integer nlcArrRow; /// constraint array column index //Integer nlcArrCol; //Parameter *nlcArrRowParm; //Parameter *nlcArrColParm; /// flag indicating whether or not the constraint is an inequality /// constraint bool isInequality; /// string to send into the optimizer, based on isInequality std::string isIneqString; /// the desired value (right hand side of the constraint equation) Real desiredValue; /// indicates what type of operator was passed in for the generating /// string Operator op; /// tolerance for the constraint <future> Real tolerance; // <future> /// Flag used to finalize the targeter data during execution bool optimizerDataFinalized; /// ID for this constraint (returned from the optimizer) Integer constraintId; /// is the right hand side a parameter? //bool isNlcParm; /// is the right hand side an array? //bool isNlcArray; /// Pointer to the object that owns the goal //GmatBase *constraintObject; /// Object ID for the parameter //Integer parmId; /// flag indicating whether or not the generating string has been interpreted bool interpreted; std::string panelDescriptor; // Shows "(<=) Sat.SMA" or whatever Real panelDesired; Real panelAchieved; //bool InterpretParameter(const std::string text, // std::string &paramType, // std::string &paramObj, // std::string &parmSystem); //bool ConstructConstraint(const char* str); }; #endif // NonlinearConstraint_hpp
38.355
103
0.589754
supalogix
816420d3307460a8cacc078101748f9e1e32d1ba
3,003
cpp
C++
test-suite/generated-src/wasm/NativeConstantsInterface.cpp
paulo-coutinho/djinni
72fc4f08e77338bd80f1f47071c5b541d89b9bc9
[ "Apache-2.0" ]
null
null
null
test-suite/generated-src/wasm/NativeConstantsInterface.cpp
paulo-coutinho/djinni
72fc4f08e77338bd80f1f47071c5b541d89b9bc9
[ "Apache-2.0" ]
null
null
null
test-suite/generated-src/wasm/NativeConstantsInterface.cpp
paulo-coutinho/djinni
72fc4f08e77338bd80f1f47071c5b541d89b9bc9
[ "Apache-2.0" ]
null
null
null
// AUTOGENERATED FILE - DO NOT MODIFY! // This file was generated by Djinni from constants.djinni #include "NativeConstantsInterface.hpp" // my header #include "NativeConstantRecord.hpp" namespace djinni_generated { em::val NativeConstantsInterface::cppProxyMethods() { static const em::val methods = em::val::array(std::vector<std::string> { "dummy", }); return methods; } void NativeConstantsInterface::dummy(const CppType& self) { self->dummy(); } EMSCRIPTEN_BINDINGS(testsuite_constants_interface) { ::djinni::DjinniClass_<::testsuite::ConstantsInterface>("testsuite_ConstantsInterface", "testsuite.ConstantsInterface") .smart_ptr<std::shared_ptr<::testsuite::ConstantsInterface>>("testsuite_ConstantsInterface") .function("nativeDestroy", &NativeConstantsInterface::nativeDestroy) .function("dummy", NativeConstantsInterface::dummy) ; } namespace { EM_JS(void, djinni_init_testsuite_constants_interface_consts, (), { if (!('testsuite_ConstantsInterface' in Module)) { Module.testsuite_ConstantsInterface = {}; } Module.testsuite_ConstantsInterface.BOOL_CONSTANT = true; Module.testsuite_ConstantsInterface.I8_CONSTANT = 1; Module.testsuite_ConstantsInterface.I16_CONSTANT = 2; Module.testsuite_ConstantsInterface.I32_CONSTANT = 3; Module.testsuite_ConstantsInterface.I64_CONSTANT = BigInt("4"); Module.testsuite_ConstantsInterface.F32_CONSTANT = 5.0; Module.testsuite_ConstantsInterface.F64_CONSTANT = 5.0; Module.testsuite_ConstantsInterface.OPT_BOOL_CONSTANT = true; Module.testsuite_ConstantsInterface.OPT_I8_CONSTANT = 1; Module.testsuite_ConstantsInterface.OPT_I16_CONSTANT = 2; Module.testsuite_ConstantsInterface.OPT_I32_CONSTANT = 3; Module.testsuite_ConstantsInterface.OPT_I64_CONSTANT = 4; Module.testsuite_ConstantsInterface.OPT_F32_CONSTANT = 5.0; Module.testsuite_ConstantsInterface.OPT_F64_CONSTANT = 5.0; Module.testsuite_ConstantsInterface.STRING_CONSTANT = "string-constant"; Module.testsuite_ConstantsInterface.OPT_STRING_CONSTANT = "string-constant"; Module.testsuite_ConstantsInterface.OBJECT_CONSTANT = { someInteger: Module.testsuite_ConstantsInterface.I32_CONSTANT, someString: Module.testsuite_ConstantsInterface.STRING_CONSTANT } ; Module.testsuite_ConstantsInterface.UPPER_CASE_CONSTANT = "upper-case-constant"; }) } void NativeConstantsInterface::staticInitializeConstants() { static std::once_flag initOnce; std::call_once(initOnce, [] { djinni_init_testsuite_constants_interface_consts(); ::djinni::djinni_register_name_in_ns("testsuite_ConstantsInterface", "testsuite.ConstantsInterface"); }); } EMSCRIPTEN_BINDINGS(testsuite_constants_interface_consts) { NativeConstantsInterface::staticInitializeConstants(); } } // namespace djinni_generated
42.9
123
0.744589
paulo-coutinho
81652283efc7751d4048f500d3d3bf43791cba7d
882
cpp
C++
D3D9_Renderer/D3D9_Renderer/source/utils/Time.cpp
codenameone-akshat/D3D9_Renderer
9925a827e45f987639f144aebd53974b27ddfb18
[ "MIT" ]
null
null
null
D3D9_Renderer/D3D9_Renderer/source/utils/Time.cpp
codenameone-akshat/D3D9_Renderer
9925a827e45f987639f144aebd53974b27ddfb18
[ "MIT" ]
null
null
null
D3D9_Renderer/D3D9_Renderer/source/utils/Time.cpp
codenameone-akshat/D3D9_Renderer
9925a827e45f987639f144aebd53974b27ddfb18
[ "MIT" ]
null
null
null
#include <sstream> #include <cmath> #include <windows.h> #include "Time.h" #include "Logger.h" namespace renderer { Time::Time() :m_tStart(), m_tEnd(), m_dt(0), m_systemTimer(0), m_numFrames(0), m_fps(0) { } Time::~Time() { } void Time::OnTimerEndCalled() { m_dt = abs(std::chrono::duration_cast<std::chrono::milliseconds>(m_tEnd - m_tStart).count()); if (m_systemTimer >= 1000) //1 second = 1000 milliseconds { OnSystemTimeStep(); } m_systemTimer += m_dt; ++m_numFrames; } void Time::OnSystemTimeStep() { m_fps = m_numFrames; //record number of frames passed in a second. m_systemTimer = 0; m_numFrames = 0; Logger::GetInstance().LogInfo(std::to_string(m_fps).c_str()); } }
21.512195
101
0.540816
codenameone-akshat
816619a9af82fa50d1964046d8dbb038685819f7
1,300
hpp
C++
source/vulkan/reshade_api_swapchain.hpp
Moroque/reshade
bf1d263780a817130f6547dca0432dfe64c8beda
[ "BSD-3-Clause" ]
1
2017-11-27T14:50:39.000Z
2017-11-27T14:50:39.000Z
source/vulkan/reshade_api_swapchain.hpp
kingeric1992/reshade
22f57c10ea87ee83ceb7a5d0cb737cdfb02dedb2
[ "BSD-3-Clause" ]
null
null
null
source/vulkan/reshade_api_swapchain.hpp
kingeric1992/reshade
22f57c10ea87ee83ceb7a5d0cb737cdfb02dedb2
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2014 Patrick Mours. All rights reserved. * License: https://github.com/crosire/reshade#license */ #pragma once #include "runtime.hpp" namespace reshade::vulkan { class device_impl; class command_queue_impl; class swapchain_impl : public api::api_object_impl<VkSwapchainKHR, runtime> { static const uint32_t NUM_SYNC_SEMAPHORES = 4; public: swapchain_impl(device_impl *device, command_queue_impl *graphics_queue); ~swapchain_impl(); void get_back_buffer(uint32_t index, api::resource *out) final; uint32_t get_back_buffer_count() const final; uint32_t get_current_back_buffer_index() const final; bool on_init(VkSwapchainKHR swapchain, const VkSwapchainCreateInfoKHR &desc, HWND hwnd); void on_reset(); void on_present(VkQueue queue, const uint32_t swapchain_image_index, std::vector<VkSemaphore> &wait); bool on_layer_submit(uint32_t eye, VkImage source, const VkExtent2D &source_extent, VkFormat source_format, VkSampleCountFlags source_samples, uint32_t source_layer_index, const float bounds[4], VkImage *target_image); private: VkQueue _queue = VK_NULL_HANDLE; uint32_t _queue_sync_index = 0; VkSemaphore _queue_sync_semaphores[NUM_SYNC_SEMAPHORES] = {}; uint32_t _swap_index = 0; std::vector<VkImage> _swapchain_images; }; }
30.952381
220
0.783077
Moroque
8167278acbb28ce040a314106f24dfd1162a1142
963
cpp
C++
src/burner/sdl/stringset.cpp
tt-arcade/fba-pi
10407847a98f0d315b05e44f0ecf01824f4558aa
[ "Apache-2.0" ]
null
null
null
src/burner/sdl/stringset.cpp
tt-arcade/fba-pi
10407847a98f0d315b05e44f0ecf01824f4558aa
[ "Apache-2.0" ]
null
null
null
src/burner/sdl/stringset.cpp
tt-arcade/fba-pi
10407847a98f0d315b05e44f0ecf01824f4558aa
[ "Apache-2.0" ]
null
null
null
// StringSet C++ class #include "burner.h" int __cdecl StringSet::Add(TCHAR* szFormat,...) { TCHAR szAdd[256]; int nAddLen = 0; TCHAR* NewMem; va_list Arg; va_start(Arg, szFormat); _vstprintf(szAdd, szFormat, Arg); nAddLen = _tcslen(szAdd); // find out the length of the new text NewMem = (TCHAR*)realloc(szText, (nLen + nAddLen + 1) * sizeof(TCHAR)); if (NewMem) { szText = NewMem; // copy the new text to the end _tcsncpy(szText + nLen, szAdd, nAddLen); nLen += nAddLen; szText[nLen] = 0; // zero-terminate } va_end(Arg); return 0; } int StringSet::Reset() { // Reset the text nLen = 0; szText= (TCHAR*)realloc(szText, sizeof(TCHAR)); if (szText == NULL) { return 1; } szText[0] = 0; return 0; } StringSet::StringSet() { szText = NULL; nLen = 0; Reset(); // reset string to nothing } StringSet::~StringSet() { realloc(szText, 0); // Free BZip text }
18.169811
73
0.598131
tt-arcade
8168533dc2ae946cecfb421b7b282272ac0b17b4
7,492
cxx
C++
src/vw/Image/tests/TestConvolution.cxx
tkeemon/visionworkbench
df59fcb31191e1fc4fecfe1901963da1614a52b1
[ "NASA-1.3" ]
1
2020-06-02T04:06:43.000Z
2020-06-02T04:06:43.000Z
src/vw/Image/tests/TestConvolution.cxx
tkeemon/visionworkbench
df59fcb31191e1fc4fecfe1901963da1614a52b1
[ "NASA-1.3" ]
null
null
null
src/vw/Image/tests/TestConvolution.cxx
tkeemon/visionworkbench
df59fcb31191e1fc4fecfe1901963da1614a52b1
[ "NASA-1.3" ]
null
null
null
// __BEGIN_LICENSE__ // Copyright (C) 2006-2010 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ // TestConvolution.h #include <gtest/gtest.h> #include <vw/Image/Convolution.h> #include <vw/Image/ImageView.h> #include <vw/Image/PixelTypes.h> #include <vw/Image/Algorithms.h> #include <vw/Image/ImageViewRef.h> #include <vw/Image/Filter.h> #include <test/Helpers.h> using namespace vw; // Simple Comparison template <template<class> class TraitT, class T> static bool bool_trait( T const& /*arg*/ ) { return TraitT<T>::value; } template <class T1, class T2> static bool is_of_type( T2 ) { return boost::is_same<T1,T2>::value; } template <class T1, class T2> static bool has_pixel_type( T2 ) { return boost::is_same<T1,typename T2::pixel_type>::value; } TEST( Convolution, Point1D ) { ImageView<double> src(3,1); src(0,0)=1; src(1,0)=2; src(2,0)=3; double kernel[] = {2,3,-1}; EXPECT_EQ( correlate_1d_at_point(src.origin(), (double*)kernel,3), 5 ); ASSERT_TRUE( is_of_type<double>( correlate_1d_at_point( ImageView<double>().origin(), (double*)0, 0 ) ) ); ASSERT_TRUE( is_of_type<PixelRGB<float> >( correlate_1d_at_point( ImageView<PixelRGB<uint8> >().origin(), (float*)0, 0 ) ) ); } TEST( Convolution, Point2D ) { ImageView<double> src(2,2); src(0,0)=1; src(1,0)=2; src(0,1)=3; src(1,1)=4; ImageView<double> krn(2,2); krn(0,0)=2; krn(1,0)=-1; krn(0,1)=0; krn(1,1)=3; EXPECT_EQ( correlate_2d_at_point(src.origin(),krn.origin(),2,2), 12 ); ASSERT_TRUE( is_of_type<double>( correlate_2d_at_point( ImageView<double>().origin(), ImageView<double>().origin(), 0, 0 ) ) ); ASSERT_TRUE( is_of_type<PixelRGB<float> >( correlate_2d_at_point( ImageView<PixelRGB<uint8> >().origin(), ImageView<float>().origin(), 0, 0 ) ) ); } TEST( Convolution, View ) { ImageView<double> src(2,2); src(0,0)=1; src(1,0)=2; src(0,1)=3; src(1,1)=4; ImageView<double> krn(2,2); krn(0,0)=2; krn(1,0)=-1; krn(0,1)=0; krn(1,1)=3; ConvolutionView<ImageView<double>,ImageView<double>,ZeroEdgeExtension> cnv( src, krn ); // Test individual pixel access EXPECT_EQ( cnv.cols(), 2 ); EXPECT_EQ( cnv.rows(), 2 ); EXPECT_EQ( cnv.planes(), 1 ); EXPECT_EQ( cnv(0,0), 2 ); EXPECT_EQ( cnv(1,0), 3 ); EXPECT_EQ( cnv(0,1), 6 ); EXPECT_EQ( cnv(1,1), 8 ); // Test rasterization ImageView<double> dst = cnv; EXPECT_EQ( dst.cols(), 2 ); EXPECT_EQ( dst.rows(), 2 ); EXPECT_EQ( dst(0,0), 2 ); EXPECT_EQ( dst(1,0), 3 ); EXPECT_EQ( dst(0,1), 6 ); EXPECT_EQ( dst(1,1), 8 ); // Test the traits ASSERT_TRUE( is_of_type<double>( cnv(0,0) ) ); ASSERT_TRUE( is_of_type<double>( *(cnv.origin()) ) ); ASSERT_FALSE( bool_trait<IsResizable>( cnv ) ); ASSERT_FALSE( bool_trait<IsMultiplyAccessible>( cnv ) ); ASSERT_FALSE( bool_trait<IsFloatingPointIndexable>( cnv ) ); ASSERT_TRUE( bool_trait<IsImageView>( cnv ) ); } TEST( Convolution, SeparableView ) { ImageView<double> src(2,2); src(0,0)=1; src(1,0)=2; src(0,1)=3; src(1,1)=4; std::vector<double> krn; krn.push_back(1); krn.push_back(-1); SeparableConvolutionView<ImageView<double>,double,ZeroEdgeExtension> cnv( src, krn, krn ); // Test individual pixel access EXPECT_EQ( cnv.cols(), 2 ); EXPECT_EQ( cnv.rows(), 2 ); EXPECT_EQ( cnv.planes(), 1 ); EXPECT_EQ( cnv(0,0), 1 ); EXPECT_EQ( cnv(0,1), 2 ); EXPECT_EQ( cnv(1,0), 1 ); EXPECT_EQ( cnv(1,1), 0 ); // Test rasterization ImageView<double> dst = cnv; EXPECT_EQ( dst.cols(), 2 ); EXPECT_EQ( dst.rows(), 2 ); EXPECT_EQ( dst.planes(), 1 ); EXPECT_EQ( dst(0,0), 1 ); EXPECT_EQ( dst(0,1), 2 ); EXPECT_EQ( dst(1,0), 1 ); EXPECT_EQ( dst(1,1), 0 ); // Test the traits ASSERT_TRUE( is_of_type<double>( cnv(0,0) ) ); ASSERT_TRUE( is_of_type<double>( *(cnv.origin()) ) ); ASSERT_FALSE( bool_trait<IsResizable>( cnv ) ); ASSERT_FALSE( bool_trait<IsMultiplyAccessible>( cnv ) ); ASSERT_FALSE( bool_trait<IsFloatingPointIndexable>( cnv ) ); ASSERT_TRUE( bool_trait<IsImageView>( cnv ) ); } TEST( Convolution, SeparableView_0x2 ) { ImageView<double> src(2,2); src(0,0)=1; src(1,0)=2; src(0,1)=4; src(1,1)=6; std::vector<double> krnx; std::vector<double> krny; krny.push_back(1); krny.push_back(-1); SeparableConvolutionView<ImageView<double>,double,ZeroEdgeExtension> cnv( src, krnx, krny ); // Test individual pixel access EXPECT_EQ( cnv.cols(), 2 ); EXPECT_EQ( cnv.rows(), 2 ); EXPECT_EQ( cnv.planes(), 1 ); EXPECT_EQ( cnv(0,0), 1 ); EXPECT_EQ( cnv(0,1), 3 ); EXPECT_EQ( cnv(1,0), 2 ); EXPECT_EQ( cnv(1,1), 4 ); // Test rasterization ImageView<double> dst = cnv; EXPECT_EQ( dst.cols(), 2 ); EXPECT_EQ( dst.rows(), 2 ); EXPECT_EQ( dst.planes(), 1 ); EXPECT_EQ( dst(0,0), 1 ); EXPECT_EQ( dst(0,1), 3 ); EXPECT_EQ( dst(1,0), 2 ); EXPECT_EQ( dst(1,1), 4 ); // Test the traits ASSERT_TRUE( is_of_type<double>( cnv(0,0) ) ); ASSERT_TRUE( is_of_type<double>( *(cnv.origin()) ) ); ASSERT_FALSE( bool_trait<IsResizable>( cnv ) ); ASSERT_FALSE( bool_trait<IsMultiplyAccessible>( cnv ) ); ASSERT_FALSE( bool_trait<IsFloatingPointIndexable>( cnv ) ); ASSERT_TRUE( bool_trait<IsImageView>( cnv ) ); } TEST( Convolution, SeparableView_2x0 ) { ImageView<double> src(2,2); src(0,0)=1; src(1,0)=2; src(0,1)=3; src(1,1)=4; std::vector<double> krnx; krnx.push_back(1); krnx.push_back(-1); std::vector<double> krny; SeparableConvolutionView<ImageView<double>,double,ZeroEdgeExtension> cnv( src, krnx, krny ); // Test individual pixel access EXPECT_EQ( cnv.cols(), 2 ); EXPECT_EQ( cnv.rows(), 2 ); EXPECT_EQ( cnv.planes(), 1 ); EXPECT_EQ( cnv(0,0), 1 ); EXPECT_EQ( cnv(1,0), 1 ); EXPECT_EQ( cnv(0,1), 3 ); EXPECT_EQ( cnv(1,1), 1 ); // Test rasterization ImageView<double> dst = cnv; EXPECT_EQ( dst.cols(), 2 ); EXPECT_EQ( dst.rows(), 2 ); EXPECT_EQ( dst.planes(), 1 ); EXPECT_EQ( dst(0,0), 1 ); EXPECT_EQ( dst(1,0), 1 ); EXPECT_EQ( dst(0,1), 3 ); EXPECT_EQ( dst(1,1), 1 ); // Test the traits ASSERT_TRUE( is_of_type<double>( cnv(0,0) ) ); ASSERT_TRUE( is_of_type<double>( *(cnv.origin()) ) ); ASSERT_FALSE( bool_trait<IsResizable>( cnv ) ); ASSERT_FALSE( bool_trait<IsMultiplyAccessible>( cnv ) ); ASSERT_FALSE( bool_trait<IsFloatingPointIndexable>( cnv ) ); ASSERT_TRUE( bool_trait<IsImageView>( cnv ) ); } TEST( Convolution, SeparableView_Compound ) { ImageView<PixelGray<float32> > src(2,2); src(0,0)=1; src(1,0)=0.2; src(0,1)=0.3; src(1,1)=0.4; std::vector<double> krn; krn.push_back(1); krn.push_back(-1); SeparableConvolutionView<ImageView<PixelGray<float32> >,double,ZeroEdgeExtension> cnv( src, krn, krn ); PixelGray<float32> monkey = cnv(0,1); ASSERT_TRUE( is_of_type<PixelGray<float32> >( cnv(0,0) ) ); } // This unit test catches a bug in the separable convolution code // that was causing the shift due to a crop operation to be applied // twice to image view operations that included two layers of edge // extension or convolution. TEST( Convolution, Prerasterize ) { ImageView<float> test_image(1024,1024); fill(test_image,1.0); ImageViewRef<float> two_edge_extend_operations = edge_extend(gaussian_filter(channel_cast<float>(channels_to_planes(test_image)),1.5), ZeroEdgeExtension()); BBox2i bbox(100,0,1024,1024); ImageView<float> right_buf = crop( two_edge_extend_operations, bbox ); EXPECT_EQ(right_buf(1000,100), 0.0); EXPECT_EQ(right_buf(900,100), 1.0); }
35.507109
158
0.672317
tkeemon
816cc674d3229bf23f354530cd930799620878d1
1,417
hpp
C++
src/private/qhttpserverrequest_private.hpp
Targoman/qhttp
2351076d2e23c8820e6e94d064de689d99edb22f
[ "MIT" ]
2
2020-07-03T06:34:15.000Z
2020-07-03T19:19:09.000Z
src/private/qhttpserverrequest_private.hpp
Targoman/QHttp
55df46aab918a1f923e8b1b79674cf9f82490bc5
[ "MIT" ]
null
null
null
src/private/qhttpserverrequest_private.hpp
Targoman/QHttp
55df46aab918a1f923e8b1b79674cf9f82490bc5
[ "MIT" ]
null
null
null
/** private imeplementation. * https://github.com/azadkuh/qhttp * * @author amir zamani * @version 2.0.0 * @date 2014-07-11 */ #ifndef QHTTPSERVER_REQUEST_PRIVATE_HPP #define QHTTPSERVER_REQUEST_PRIVATE_HPP /////////////////////////////////////////////////////////////////////////////// #include "httpreader.hxx" #include "qhttpserverrequest.hpp" #include "qhttpserverconnection.hpp" /////////////////////////////////////////////////////////////////////////////// namespace qhttp { namespace server { /////////////////////////////////////////////////////////////////////////////// class QHttpRequestPrivate : public details::HttpReader<details::HttpRequestBase> { protected: Q_DECLARE_PUBLIC(QHttpRequest) QHttpRequest* const q_ptr; public: explicit QHttpRequestPrivate(QHttpConnection* conn, QHttpRequest* q) : q_ptr(q), iconnection(conn) { QHTTP_LINE_DEEPLOG } virtual ~QHttpRequestPrivate(); void initialize() { } public: QString iremoteAddress; quint16 iremotePort = 0; QList<QPair<QString, QString>> iuserDefinedValues; QHttpConnection* const iconnection = nullptr; }; /////////////////////////////////////////////////////////////////////////////// } // namespace server } // namespace qhttp /////////////////////////////////////////////////////////////////////////////// #endif // QHTTPSERVER_REQUEST_PRIVATE_HPP
27.784314
107
0.515879
Targoman
816de890b819e1b27644a6e004949cfcf5075d9f
1,957
cpp
C++
src/board/agp01/Agp01Relays.cpp
amsobr/iotool
233ec320ee25c96d34332fe847663682c4aa0a91
[ "MIT" ]
null
null
null
src/board/agp01/Agp01Relays.cpp
amsobr/iotool
233ec320ee25c96d34332fe847663682c4aa0a91
[ "MIT" ]
4
2022-03-13T23:07:12.000Z
2022-03-13T23:10:09.000Z
src/board/agp01/Agp01Relays.cpp
amsobr/iotool
233ec320ee25c96d34332fe847663682c4aa0a91
[ "MIT" ]
null
null
null
#include <thread> #include <Poco/Format.h> #include <common/DigitalOut.hpp> #include "Agp01Relays.hpp" using namespace std; Agp01Relays::Agp01Relays( int id ) : DigitalOut(id) , myEN{gpiod::find_line("pioB21") } , myOHCL{ gpiod::find_line("pioB20") } , myOLCH{ gpiod::find_line("pioB19") } , mySel{ "relaySel" , {"pioB16","pioB17","pioB18"} , GpioBus::Direction::OUTPUT , 0 } { /* Populate the relay entries. * Note that the very first AGP01 board had a bug that inverted * the order of the Yn contacts. * For these versions, the software can circumvent the issue by * inverting the numerical order to put on the relay_sel bus, * which is most likely seen below in '7-i'. * With no bug the line should simply have 'i' */ myRelays.reserve(8); for ( int i=0 ; i<8 ; i++ ) { myRelays.emplace_back(Poco::format("Y%d",i+1),false,7-i); } gpiod::line_request req; req.request_type = gpiod::line_request::DIRECTION_OUTPUT; req.consumer = "agp01/relays/en"; myEN.request(req,1); req.consumer = "agp01/relays/ol_ch"; myOLCH.request(req,0); req.consumer = "agp01/relays/oh_cl"; myOHCL.request(req,0); mySel.setValue(0); } std::vector<DigitalOut::Output> Agp01Relays::getOutputs() const { std::vector<Output> outs; outs.reserve(myRelays.size()); for ( auto const& relay : myRelays ) { outs.emplace_back(relay.name,relay.state); } return outs; } int Agp01Relays::setOut( string name , bool value ) { for ( auto const&relay : myRelays ) { if ( relay.name==name ) { mySel.setValue(relay.id); myOLCH.set_value(value?1:0); myOHCL.set_value(value?0:1); myEN.set_value(0); std::this_thread::sleep_for(std::chrono::milliseconds{50}); myEN.set_value(1); } } return -1; }
26.808219
87
0.605008
amsobr
816f6d613d21c4f5bbf3317030577af202971215
5,297
cpp
C++
FileDialogEx.cpp
matthias-christen/CdCoverCreator
edb223c2cf33ab3fb72d84ce2a9bce8500408c2a
[ "MIT" ]
null
null
null
FileDialogEx.cpp
matthias-christen/CdCoverCreator
edb223c2cf33ab3fb72d84ce2a9bce8500408c2a
[ "MIT" ]
null
null
null
FileDialogEx.cpp
matthias-christen/CdCoverCreator
edb223c2cf33ab3fb72d84ce2a9bce8500408c2a
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////// // MSDN -- August 2000 // If this code works, it was written by Paul DiLascia. // If not, I don't know who wrote it. // Largely based on original implementation by Michael Lemley. // Compiles with Visual C++ 6.0, runs on Windows 98 and probably NT too. // // CFileDialogEx implements a CFileDialog that uses the new Windows // 2000 style open/save dialog. Use companion class CDocManagerEx in an // MFC framework app. // #include "stdafx.h" #include <afxpriv.h> #include "FileDialogEx.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif static BOOL IsWin2000(); IMPLEMENT_DYNAMIC(CFileDialogEx, CFileDialog) CFileDialogEx::CFileDialogEx(BOOL bOpenFileDialog, LPCTSTR lpszDefExt, LPCTSTR lpszFileName, DWORD dwFlags, LPCTSTR lpszFilter, CWnd* pParentWnd) : CFileDialog(bOpenFileDialog, lpszDefExt, lpszFileName, dwFlags, lpszFilter, pParentWnd) { } BEGIN_MESSAGE_MAP(CFileDialogEx, CFileDialog) //{{AFX_MSG_MAP(CFileDialogEx) //}}AFX_MSG_MAP END_MESSAGE_MAP() BOOL IsWin2000() { OSVERSIONINFOEX osvi; BOOL bOsVersionInfoEx; // Try calling GetVersionEx using the OSVERSIONINFOEX structure, // which is supported on Windows 2000. // // If that fails, try using the OSVERSIONINFO structure. ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi)) ) { // If OSVERSIONINFOEX doesn't work, try OSVERSIONINFO. osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO); if (! GetVersionEx ( (OSVERSIONINFO *) &osvi) ) return FALSE; } switch (osvi.dwPlatformId) { case VER_PLATFORM_WIN32_NT: if ( osvi.dwMajorVersion >= 5 ) return TRUE; break; } return FALSE; } ////////////////// // DoModal override copied mostly from MFC, with modification to use // m_ofnEx instead of m_ofn. // int CFileDialogEx::DoModal() { ASSERT_VALID(this); ASSERT(m_ofn.Flags & OFN_ENABLEHOOK); ASSERT(m_ofn.lpfnHook != NULL); // can still be a user hook // zero out the file buffer for consistent parsing later ASSERT(AfxIsValidAddress(m_ofn.lpstrFile, m_ofn.nMaxFile)); DWORD nOffset = lstrlen(m_ofn.lpstrFile)+1; ASSERT(nOffset <= m_ofn.nMaxFile); memset(m_ofn.lpstrFile+nOffset, 0, (m_ofn.nMaxFile-nOffset)*sizeof(TCHAR)); // WINBUG: This is a special case for the file open/save dialog, // which sometimes pumps while it is coming up but before it has // disabled the main window. HWND hWndFocus = ::GetFocus(); BOOL bEnableParent = FALSE; m_ofn.hwndOwner = PreModal(); AfxUnhookWindowCreate(); if (m_ofn.hwndOwner != NULL && ::IsWindowEnabled(m_ofn.hwndOwner)) { bEnableParent = TRUE; ::EnableWindow(m_ofn.hwndOwner, FALSE); } _AFX_THREAD_STATE* pThreadState = AfxGetThreadState(); ASSERT(pThreadState->m_pAlternateWndInit == NULL); if (m_ofn.Flags & OFN_EXPLORER) pThreadState->m_pAlternateWndInit = this; else AfxHookWindowCreate(this); memset(&m_ofnEx, 0, sizeof(m_ofnEx)); memcpy(&m_ofnEx, &m_ofn, sizeof(m_ofn)); if (IsWin2000()) m_ofnEx.lStructSize = sizeof(m_ofnEx); int nResult; if (m_bOpenFileDialog) nResult = ::GetOpenFileName((OPENFILENAME*)&m_ofnEx); else nResult = ::GetSaveFileName((OPENFILENAME*)&m_ofnEx); memcpy(&m_ofn, &m_ofnEx, sizeof(m_ofn)); m_ofn.lStructSize = sizeof(m_ofn); if (nResult) ASSERT(pThreadState->m_pAlternateWndInit == NULL); pThreadState->m_pAlternateWndInit = NULL; // WINBUG: Second part of special case for file open/save dialog. if (bEnableParent) ::EnableWindow(m_ofnEx.hwndOwner, TRUE); if (::IsWindow(hWndFocus)) ::SetFocus(hWndFocus); PostModal(); return nResult ? nResult : IDCANCEL; } ////////////////// // When the open dialog sends a notification, copy m_ofnEx to m_ofn in // case handler function is expecting updated information in the // OPENFILENAME struct. // BOOL CFileDialogEx::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult) { memcpy(&m_ofn, &m_ofnEx, sizeof(m_ofn)); m_ofn.lStructSize = sizeof(m_ofn); return CFileDialog::OnNotify( wParam, lParam, pResult); } //////////////////////////////////////////////////////////////// // The following functions are provided for testing purposes, to // demonstrate that they in fact called; ie, that MFC's internal dialog // proc is hooked up properly. Delete them if you like. // BOOL CFileDialogEx::OnFileNameOK() { TRACE(_T("CFileDialogEx::OnFileNameOK\n")); return CFileDialog::OnFileNameOK(); } void CFileDialogEx::OnInitDone() { TRACE(_T("CFileDialogEx::OnInitDone\n")); CFileDialog::OnInitDone(); } void CFileDialogEx::OnFileNameChange() { TRACE(_T("CFileDialogEx::OnFileNameChange\n")); CFileDialog::OnFileNameChange(); } void CFileDialogEx::OnFolderChange() { TRACE(_T("CFileDialogEx::OnFolderChange\n")); CFileDialog::OnFolderChange(); } void CFileDialogEx::OnTypeChange() { TRACE(_T("OnTypeChange(), index = %d\n"), m_ofn.nFilterIndex); CFileDialog::OnTypeChange(); }
28.326203
78
0.67963
matthias-christen
40c4660d7340fe6a5a09bd932db657d0c16bfe07
737
cpp
C++
Genome_Antivirus_10.0/thread.cpp
Rossterrrr/Qt
3e5c2934ce19675390d2ad6d513a14964d8cbe50
[ "MIT" ]
3
2019-09-02T05:17:08.000Z
2021-01-07T11:21:34.000Z
Genome_Antivirus_10.0/thread.cpp
Jhongesell/Qt
3fc548731435d3f6fffbaec1bdfd19371232088e
[ "MIT" ]
null
null
null
Genome_Antivirus_10.0/thread.cpp
Jhongesell/Qt
3fc548731435d3f6fffbaec1bdfd19371232088e
[ "MIT" ]
null
null
null
#include "thread.h" #include <QDebug> Thread::Thread(QStringList list, QStringList vList, QThread *parent) : QThread(parent), directories(list),virusList(vList) { } void Thread::run() { emit scanStart(); foreach (QString element, directories) { QDirIterator directory(element, QDirIterator::Subdirectories); while (directory.hasNext()) { if(!stopThread){ directory.next(); foreach (const QString &str, virusList) { if (directory.fileName() == str){ emit infectedFiles(directory.filePath()); } } } } } emit scanComplete(); }
24.566667
125
0.523745
Rossterrrr
40c63246f25bda155cd0ecd4ff9be5eda870da0f
3,514
cc
C++
src/RTT_Format_Reader/CellFlags.cc
hppritcha/Draco
6baa5688865eb6c6f38ce6ad1a40eb5ce943cf5c
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
src/RTT_Format_Reader/CellFlags.cc
hppritcha/Draco
6baa5688865eb6c6f38ce6ad1a40eb5ce943cf5c
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
src/RTT_Format_Reader/CellFlags.cc
hppritcha/Draco
6baa5688865eb6c6f38ce6ad1a40eb5ce943cf5c
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
//--------------------------------------------*-C++-*---------------------------------------------// /*! * \file RTT_Format_Reader/CellFlags.cc * \author B.T. Adams * \date Mon Jun 7 10:33:26 2000 * \brief Implementation file for RTT_Format_Reader/CellFlags class * \note Copyright (C) 2016-2020 Triad National Security, LLC., All rights reserved. */ //------------------------------------------------------------------------------------------------// #include "CellFlags.hh" namespace rtt_RTT_Format_Reader { //------------------------------------------------------------------------------------------------// /*! * \brief Parses the cell_flags data block of the mesh file via calls to private member functions. * \param meshfile Mesh file name. */ void CellFlags::readCellFlags(ifstream &meshfile) { readKeyword(meshfile); readFlagTypes(meshfile); readEndKeyword(meshfile); } //------------------------------------------------------------------------------------------------// /*! * \brief Reads and validates the cell_flags block keyword. * \param meshfile Mesh file name. */ void CellFlags::readKeyword(ifstream &meshfile) { string dummyString; meshfile >> dummyString; Insist(dummyString == "cell_flags", "Invalid mesh file: cell_flags block missing"); std::getline(meshfile, dummyString); } //------------------------------------------------------------------------------------------------// /*! * \brief Reads and validates the cell_flags block data. * \param meshfile Mesh file name. */ void CellFlags::readFlagTypes(ifstream &meshfile) { int flagTypeNum; string dummyString; for (size_t i = 0; i < static_cast<size_t>(dims.get_ncell_flag_types()); ++i) { meshfile >> flagTypeNum >> dummyString; Insist(static_cast<size_t>(flagTypeNum) == i + 1, "Invalid mesh file: cell flag type out of order"); Check(i < flagTypes.size()); Check(i < INT_MAX); flagTypes[i] = std::make_shared<Flags>(dims.get_ncell_flags(static_cast<int>(i)), dummyString); std::getline(meshfile, dummyString); flagTypes[i]->readFlags(meshfile); } } //------------------------------------------------------------------------------------------------// /*! * \brief Reads and validates the end_cell_flags block keyword. * \param meshfile Mesh file name. */ void CellFlags::readEndKeyword(ifstream &meshfile) { string dummyString; meshfile >> dummyString; Insist(dummyString == "end_cell_flags", "Invalid mesh file: cell_flags block missing end"); std::getline(meshfile, dummyString); // read and discard blank line. } //------------------------------------------------------------------------------------------------// /*! * \brief Returns the index to the cell flag type that contains the specified string. * \param desired_flag_type Flag type. * \return The cell flag type index. */ int CellFlags::get_flag_type_index(string &desired_flag_type) const { int flag_type_index = -1; for (size_t f = 0; f < dims.get_ncell_flag_types(); f++) { string flag_type = flagTypes[f]->getFlagType(); if (flag_type == desired_flag_type) { Check(f < INT_MAX); flag_type_index = static_cast<int>(f); } } return flag_type_index; } } // end namespace rtt_RTT_Format_Reader //------------------------------------------------------------------------------------------------// // end of RTT_Format_Reader/CellFlags.cc //------------------------------------------------------------------------------------------------//
36.989474
100
0.527604
hppritcha
40c88774a7c02cb268096c3107ab7d5a029ec234
3,816
hh
C++
src/BasicObjects.hh
hirdrac/rend
937fa3dc0eff23d831004766929c601862079791
[ "MIT" ]
2
2021-08-31T07:18:27.000Z
2021-11-15T22:02:26.000Z
src/BasicObjects.hh
hirdrac/rend
937fa3dc0eff23d831004766929c601862079791
[ "MIT" ]
null
null
null
src/BasicObjects.hh
hirdrac/rend
937fa3dc0eff23d831004766929c601862079791
[ "MIT" ]
null
null
null
// // BasicObjects.hh // Copyright (C) 2021 Richard Bradley // // Definitions for primitive object classes // #pragma once #include "Object.hh" // **** Types **** class Disc final : public Primitive { public: // SceneItem Functions std::string desc() const override { return "<Disc>"; } // Object Functions int init(Scene& s, const Transform* tr) override; BBox bound(const Matrix* t) const override; int intersect(const Ray& r, HitList& hl) const override; // Primitive Functions Flt hitCost(const HitCostInfo& hc) const override; Vec3 normal(const Ray& r, const HitInfo& h) const override; private: Vec3 _normal; }; class Cone final : public Primitive { public: // SceneItem Functions std::string desc() const override { return "<Cone>"; } // Object Functions int init(Scene& s, const Transform* tr) override; int intersect(const Ray& r, HitList& hl) const override; // Primitive Functions Flt hitCost(const HitCostInfo& hc) const override; Vec3 normal(const Ray& r, const HitInfo& h) const override; private: Vec3 _baseNormal; }; class Cube final : public Primitive { public: // SceneItem Functions std::string desc() const override { return "<Cube>"; } // Object Functions int init(Scene& s, const Transform* tr) override; int intersect(const Ray& r, HitList& hl) const override; // Primitive Functions Flt hitCost(const HitCostInfo& hc) const override; Vec3 normal(const Ray& r, const HitInfo& h) const override; private: Vec3 _sideNormal[6]; }; class Cylinder final : public Primitive { public: // SceneItem Functions std::string desc() const override { return "<Cylinder>"; } // Object Functions int init(Scene& s, const Transform* tr) override; int intersect(const Ray& r, HitList& hl) const override; // Primitive Functions Flt hitCost(const HitCostInfo& hc) const override; Vec3 normal(const Ray& r, const HitInfo& h) const override; private: Vec3 _endNormal[2]; }; class Paraboloid final : public Primitive { public: // SceneItem Functions std::string desc() const override { return "<Paraboloid>"; } // Object Functions int init(Scene& s, const Transform* tr) override; int intersect(const Ray& r, HitList& hl) const override; // Primitive Functions Flt hitCost(const HitCostInfo& hc) const override; Vec3 normal(const Ray& r, const HitInfo& h) const override; private: Vec3 _baseNormal; }; class Plane final : public Primitive { public: // SceneItem Functions std::string desc() const override { return "<Plane>"; } // Object Functions int init(Scene& s, const Transform* tr) override; BBox bound(const Matrix* t) const override; int intersect(const Ray& r, HitList& hl) const override; // Primitive Functions Flt hitCost(const HitCostInfo& hc) const override; Vec3 normal(const Ray& r, const HitInfo& h) const override; private: Vec3 _normal; }; class Sphere final : public Primitive { public: // SceneItem Functions std::string desc() const override { return "<Sphere>"; } // Object Functions int intersect(const Ray& r, HitList& hl) const override; // Primitive Functions Flt hitCost(const HitCostInfo& hc) const override; Vec3 normal(const Ray& r, const HitInfo& h) const override; }; class Torus final : public Primitive { public: // SceneItem Functions std::string desc() const override { return "<Torus>"; } int setRadius(Flt r) override { _radius = r; return 0; } // Object Functions int init(Scene& s, const Transform* tr) override; BBox bound(const Matrix* t) const override; int intersect(const Ray& r, HitList& hl) const override; // Primitive Functions Flt hitCost(const HitCostInfo& hc) const override; Vec3 normal(const Ray& r, const HitInfo& h) const override; private: Flt _radius = .5; };
24.461538
62
0.70414
hirdrac
40c98e19385b51a0f26c1f35a0bdcddc3234b7e7
423
cpp
C++
docs/mfc/codesnippet/CPP/implementing-working-areas-in-list-controls_2.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
965
2017-06-25T23:57:11.000Z
2022-03-31T14:17:32.000Z
docs/mfc/codesnippet/CPP/implementing-working-areas-in-list-controls_2.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
3,272
2017-06-24T00:26:34.000Z
2022-03-31T22:14:07.000Z
docs/mfc/codesnippet/CPP/implementing-working-areas-in-list-controls_2.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
951
2017-06-25T12:36:14.000Z
2022-03-26T22:49:06.000Z
// set insertion points for each work area CPoint rgptWork[4]; for (int i = 0; i < 4; i++) { rgptWork[i].x = rcWorkAreas[i].left + 10; rgptWork[i].y = rcWorkAreas[i].top + 10; } // now move all the items to the different quadrants for (int i = 0; i < 20; i++) { m_WorkAreaListCtrl.SetItemPosition(i, rgptWork[i % 4]); } // force the control to rearrange the shuffled items m_WorkAreaListCtrl.Arrange(LVA_DEFAULT);
28.2
58
0.683215
bobbrow
40cf717a9bf2f41129386946df187d083db7403a
303
cpp
C++
src/generator/ui/LitesqlMethodPanel.cpp
cshnick/liteSql_custom_generator
31f81ab13b689616672ab45805c3ffdfab3a1057
[ "BSD-3-Clause" ]
14
2018-04-20T03:11:34.000Z
2021-12-29T02:02:28.000Z
src/generator/ui/LitesqlMethodPanel.cpp
cshnick/liteSql_custom_generator
31f81ab13b689616672ab45805c3ffdfab3a1057
[ "BSD-3-Clause" ]
14
2016-05-24T00:20:42.000Z
2019-02-11T18:36:36.000Z
src/generator/ui/LitesqlMethodPanel.cpp
cshnick/liteSql_custom_generator
31f81ab13b689616672ab45805c3ffdfab3a1057
[ "BSD-3-Clause" ]
5
2019-08-31T17:07:08.000Z
2022-03-21T06:57:39.000Z
#include "LitesqlMethodPanel.h" #include "objectmodel.hpp" using namespace xml; LitesqlMethodPanel::LitesqlMethodPanel( wxWindow* parent , Method::Ptr& pMethod) : MethodPanel( parent ), m_pMethod(pMethod) { m_textCtrlName->SetValidator(StdStringValidator(wxFILTER_ALPHANUMERIC,&m_pMethod->name)); }
23.307692
91
0.79538
cshnick
40cfc6dceaf044e48a6a14da92c1e56a72526ce6
5,145
cpp
C++
src/items/items.cpp
Blackhawk-TA/GateKeeper
49a260bf7ba2304f1649b5ed487bc1e55028e672
[ "MIT" ]
1
2021-12-31T23:52:57.000Z
2021-12-31T23:52:57.000Z
src/items/items.cpp
Blackhawk-TA/GateKeeper
49a260bf7ba2304f1649b5ed487bc1e55028e672
[ "MIT" ]
null
null
null
src/items/items.cpp
Blackhawk-TA/GateKeeper
49a260bf7ba2304f1649b5ed487bc1e55028e672
[ "MIT" ]
null
null
null
// // Created by daniel on 24.09.21. // #include "items.hpp" namespace items { Listbox::Item create_inventory_item(INVENTORY_ITEM item_type) { Listbox::Item item; switch (item_type) { case INVENTORY_ITEM::GATE_PART: item = create_gate_part(INVENTORY_ITEM::GATE_PART); break; case INVENTORY_ITEM::APPLE: item = create_apple(INVENTORY_ITEM::APPLE); break; case INVENTORY_ITEM::CARROT: item = create_carrot(INVENTORY_ITEM::CARROT); break; case INVENTORY_ITEM::CARROT_SEED: item = create_carrot_seed(INVENTORY_ITEM::CARROT_SEED); break; case INVENTORY_ITEM::INVENTORY_BACK: item = create_back_entry(INVENTORY_ITEM::INVENTORY_BACK); break; } return item; } Listbox::Item create_sidemenu_item(SIDEMENU_ITEM item_type, uint8_t save_id) { Listbox::Item item; switch (item_type) { case SIDEMENU_ITEM::INVENTORY: item = create_inventory_entry(SIDEMENU_ITEM::INVENTORY); break; case SIDEMENU_ITEM::GEAR: item = create_gear_entry(SIDEMENU_ITEM::GEAR); break; case SIDEMENU_ITEM::SAVE: item = create_save_entry(SIDEMENU_ITEM::SAVE, save_id); break; case SIDEMENU_ITEM::SIDEMENU_OPTIONS: item = create_options_entry(SIDEMENU_ITEM::SIDEMENU_BACK, save_id); break; case SIDEMENU_ITEM::SIDEMENU_BACK: item = create_back_entry(SIDEMENU_ITEM::SIDEMENU_BACK); break; case SIDEMENU_ITEM::QUIT: item = create_quit_entry(SIDEMENU_ITEM::QUIT); break; } return item; } Listbox::Item create_menu_item(MENU_ITEM item_type, uint8_t save_id) { std::string save_id_str = std::to_string(save_id); Listbox::Item item; switch (item_type) { case MENU_ITEM::LOAD_SAVE: item = create_load_entry(MENU_ITEM::LOAD_SAVE, save_id); break; case MENU_ITEM::NEW_SAVE: item = create_new_save_entry(MENU_ITEM::NEW_SAVE, save_id); break; case MENU_ITEM::MENU_OPTIONS: item = create_options_entry(MENU_ITEM::MENU_OPTIONS); break; } return item; } Listbox::Item create_options_item(OPTIONS_ITEM item_type, uint8_t save_id) { Listbox::Item item; switch (item_type) { case OPTIONS_ITEM::SHOW_FPS: item = create_show_fps_entry(OPTIONS_ITEM::SHOW_FPS); break; case OPTIONS_ITEM::SHOW_TIME: item = create_show_time_entry(OPTIONS_ITEM::SHOW_TIME); break; case OPTIONS_ITEM::OPTIONS_BACK: item = create_options_exit_entry(OPTIONS_ITEM::OPTIONS_BACK, save_id); break; case RESET_ALL: item = create_reset_all_entries(OPTIONS_ITEM::RESET_ALL); break; } return item; } Listbox::Item create_combat_item(COMBAT_ITEM item_type, uint8_t save_id, combat::Player *player, combat::Enemy *enemy) { Listbox::Item item; switch (item_type) { case COMBAT_ITEM::ESCAPE: item = create_combat_escape(item_type, save_id); break; case ATTACK_SWORD: item = create_combat_attack_sword(item_type, player, enemy); break; case ATTACK_SPEAR: item = create_combat_attack_spear(item_type, player, enemy); break; case ATTACK_ARROW: item = create_combat_attack_arrow(item_type, player, enemy); break; case ATTACK_DAGGER: item = create_combat_attack_dagger(item_type, player, enemy); break; case ATTACK_MAGIC: item = create_combat_attack_magic(item_type, player, enemy); break; case ATTACK_FIRE: item = create_combat_attack_fire(item_type, player, enemy); break; case ATTACK_ICE: item = create_combat_attack_ice(item_type, player, enemy); break; case ATTACK_SHOCK: item = create_combat_attack_shock(item_type, player, enemy); break; } return item; } Listbox::Item create_gear_item(GEAR_TYPE item_type) { Listbox::Item item; switch (item_type) { case GEAR_SWORD: item = create_gear_sword(item_type); break; case GEAR_SPEAR: item = create_gear_spear(item_type); break; case GEAR_ARROW: item = create_gear_arrow(item_type); break; case GEAR_DAGGER: item = create_gear_dagger(item_type); break; case GEAR_MAGIC: item = create_gear_magic(item_type); break; case GEAR_FIRE: item = create_gear_fire(item_type); break; case GEAR_ICE: item = create_gear_ice(item_type); break; case GEAR_SHOCK: item = create_gear_shock(item_type); break; case GEAR_NAVIGATE_BACK: item = create_back_entry(item_type); break; default: break; } return item; } Listbox::Item create_shop_item(SHOP_ITEM item_type) { Listbox::Item item; switch (item_type) { case SHOP_APPLE: item = create_shop_apple(item_type); break; case SHOP_CARROT: item = create_shop_carrot(item_type); break; case SHOP_CARROT_SEED: item = create_shop_carrot_seed(item_type); break; case SHOP_SWORD: item = create_shop_sword(item_type); break; case SHOP_DAGGER: item = create_shop_dagger(item_type); break; case SHOP_ARROW: item = create_shop_arrow(item_type); break; case SHOP_SPEAR: item = create_shop_spear(item_type); break; case SHOP_BACK: item = create_back_entry(item_type); break; } return item; } }
24.975728
121
0.710982
Blackhawk-TA
40d092cfa1696d5905a37a26ae97ab2e05964f40
1,159
cpp
C++
src/ulib/FileFinder.cpp
vividos/UlibCpp
d96348844348a00523b7742b3e7a5c9764613877
[ "BSD-2-Clause" ]
null
null
null
src/ulib/FileFinder.cpp
vividos/UlibCpp
d96348844348a00523b7742b3e7a5c9764613877
[ "BSD-2-Clause" ]
null
null
null
src/ulib/FileFinder.cpp
vividos/UlibCpp
d96348844348a00523b7742b3e7a5c9764613877
[ "BSD-2-Clause" ]
null
null
null
// // ulib - a collection of useful classes // Copyright (C) 2008-2014,2017 Michael Fink // /// \file FileFinder.cpp File finder // // includes #include "stdafx.h" #include <ulib/FileFinder.hpp> #include <ulib/Path.hpp> std::vector<CString> FileFinder::FindAllInPath(const CString& path, const CString& fileSpec, bool findFolders, bool recursive) { std::vector<CString> filenamesList; FileFinder finder(path, fileSpec); if (finder.IsValid()) { do { if (finder.IsDot()) continue; if (recursive && finder.IsFolder()) { std::vector<CString> subfolderFilenamesList = FindAllInPath(finder.Filename(), fileSpec, findFolders, true); if (!subfolderFilenamesList.empty()) filenamesList.insert(filenamesList.end(), subfolderFilenamesList.begin(), subfolderFilenamesList.end()); } if (findFolders && finder.IsFile()) continue; if (!findFolders && finder.IsFolder()) continue; filenamesList.push_back(finder.Filename()); } while (finder.Next()); } return filenamesList; }
24.659574
126
0.620362
vividos
40d1852ec0aba78e9722ea095b77914a2264988c
4,657
cpp
C++
HCore/CCore/test/test4014.SysFile.cpp
SergeyStrukov/CCore-2-xx
118aa4011ee7cc587298d6373b6587540e044a83
[ "BSL-1.0" ]
8
2017-12-21T07:00:16.000Z
2020-04-02T09:05:55.000Z
HCore/CCore/test/test4014.SysFile.cpp
SergeyStrukov/CCore-2-99
1eca5b9b2de067bbab43326718b877465ae664fe
[ "BSL-1.0" ]
null
null
null
HCore/CCore/test/test4014.SysFile.cpp
SergeyStrukov/CCore-2-99
1eca5b9b2de067bbab43326718b877465ae664fe
[ "BSL-1.0" ]
1
2020-03-30T09:54:18.000Z
2020-03-30T09:54:18.000Z
/* test4014.SysFile.cpp */ //---------------------------------------------------------------------------------------- // // Project: CCore 2.00 // // Tag: HCore Mini // // License: Boost Software License - Version 1.0 - August 17th, 2003 // // see http://www.boost.org/LICENSE_1_0.txt or the local copy // // Copyright (c) 2015 Sergey Strukov. All rights reserved. // //---------------------------------------------------------------------------------------- #include <CCore/test/test.h> #include <CCore/inc/sys/SysFile.h> namespace App { namespace Private_4014 { /* class File */ class File : NoCopy { Sys::File file; bool ok; public: File() : ok(false) {} void open(StrLen file_name,FileOpenFlags oflags) { if( ok ) return; FileError fe=file.open(file_name,oflags); Printf(Con,"open(#.q;,#;) : #;\n",file_name,oflags,fe); ok=!fe; } void close(bool preserve_file=false) { if( !ok ) return; FileMultiError errout; file.close(errout,preserve_file); Printf(Con,"close(#;) : #;\n",preserve_file,errout); ok=false; } ulen write(const uint8 *buf,ulen len) { if( !ok ) return 0; auto result=file.write(buf,len); Printf(Con,"write(...,#;) : #; #;\n",len,result.error,result.len); return result.len; } ulen read(uint8 *buf,ulen len) { if( !ok ) return 0; auto result=file.read(buf,len); Printf(Con,"read(...,#;) : #; #;\n",len,result.error,result.len); return result.len; } FilePosType getLen() { if( !ok ) return 0; auto result=file.getLen(); Printf(Con,"getLen() : #; #;\n",result.error,result.pos); return result.pos; } FilePosType getPos() { if( !ok ) return 0; auto result=file.getPos(); Printf(Con,"getPos() : #; #;\n",result.error,result.pos); return result.pos; } void setPos(FilePosType pos) { if( !ok ) return; FileError fe=file.setPos(pos); Printf(Con,"setPos(#;) : #;\n",pos,fe); } }; /* test1() */ void test1() { File file; // 1 file.open("not_exist.txt",Open_Read); file.open("z:not_exist.txt",Open_Read); file.open("no_write.txt",Open_Write); file.open("no_write.txt",Open_Read); file.close(); // 2 file.open("no_read.txt",Open_Read); file.open("no_read.txt",Open_Write); file.close(); // 3 file.open("temp.txt",Open_Write|Open_AutoDelete|Open_New); file.close(); file.open("temp.txt",Open_Write|Open_AutoDelete); file.close(); file.open("temp.txt",Open_Write|Open_AutoDelete|Open_Create|Open_Pos); file.getLen(); file.close(); file.open("temp.txt",Open_Write|Open_AutoDelete|Open_Erase); file.close(); file.open("temp.txt",Open_Write|Open_AutoDelete|Open_Create|Open_Erase|Open_Pos); file.getLen(); file.close(); // 4 const ulen Len = 100 ; uint8 buf[Len]; Range(buf).set('1'); // 5 file.open("temp_saved.txt",Open_Write|Open_New); file.close(); file.open("temp_saved.txt",Open_Write|Open_Pos); file.write(buf,Len); file.getLen(); file.close(); file.open("temp_saved.txt",Open_Write|Open_Create|Open_Pos); file.getLen(); file.close(); file.open("temp_saved.txt",Open_Write|Open_Erase|Open_Pos); file.getLen(); file.write(buf,Len); file.close(); file.open("temp_saved.txt",Open_Write|Open_AutoDelete|Open_Create|Open_Erase|Open_Pos); file.getLen(); file.close(true); } /* test2() */ void test2() { const ulen WLen = 100 ; const ulen RLen = 200 ; uint8 wbuf[WLen]; uint8 rbuf[RLen]; Range(wbuf).set('1'); // file File file; file.open("temp.txt",Open_AutoDelete); file.close(); file.open("temp.txt",Open_Create|Open_Write); file.write(wbuf,WLen); file.read(rbuf,RLen); file.setPos(WLen/2); file.close(); file.open("temp.txt",Open_Read); file.read(rbuf,RLen); if( !Range(wbuf).equal(Range(rbuf,WLen)) ) Printf(Con,"not equal\n"); file.close(); } /* test3() */ void test3() { const ulen WLen = 100 ; uint8 wbuf[WLen]; Range(wbuf).set('1'); // file File file; file.open("temp.txt",Open_ToWrite|Open_Pos|Open_AutoDelete); file.write(wbuf,WLen); file.getLen(); file.setPos(WLen/2); file.getPos(); file.setPos(WLen); file.getPos(); file.setPos(0); file.getPos(); file.close(); } } // namespace Private_4014 using namespace Private_4014; /* Testit<4014> */ template<> const char *const Testit<4014>::Name="Test4014 SysFile"; template<> bool Testit<4014>::Main() { test1(); test2(); test3(); return true; } } // namespace App
15.680135
90
0.591797
SergeyStrukov
40d3362406b38275b0edb6490753fad9cf0c904f
15,657
cpp
C++
cfgmgr/vxlanmgr.cpp
antony-rheneus/sonic-swss
4bb9142edacf013bdbd613dc5f5e8b2aa1265584
[ "Apache-2.0" ]
null
null
null
cfgmgr/vxlanmgr.cpp
antony-rheneus/sonic-swss
4bb9142edacf013bdbd613dc5f5e8b2aa1265584
[ "Apache-2.0" ]
null
null
null
cfgmgr/vxlanmgr.cpp
antony-rheneus/sonic-swss
4bb9142edacf013bdbd613dc5f5e8b2aa1265584
[ "Apache-2.0" ]
null
null
null
#include <algorithm> #include <regex> #include <sstream> #include <string> #include <net/if.h> #include "logger.h" #include "producerstatetable.h" #include "macaddress.h" #include "vxlanmgr.h" #include "exec.h" #include "tokenize.h" #include "shellcmd.h" #include "warm_restart.h" using namespace std; using namespace swss; // Fields name #define VXLAN_TUNNEL "vxlan_tunnel" #define SOURCE_IP "src_ip" #define VNI "vni" #define VNET "vnet" #define VXLAN "vxlan" #define VXLAN_IF "vxlan_if" #define VXLAN_NAME_PREFIX "Vxlan" #define VXLAN_IF_NAME_PREFIX "Brvxlan" static std::string getVxlanName(const swss::VxlanMgr::VxlanInfo & info) { return std::string("") + VXLAN_NAME_PREFIX + info.m_vni; } static std::string getVxlanIfName(const swss::VxlanMgr::VxlanInfo & info) { return std::string("") + VXLAN_IF_NAME_PREFIX + info.m_vni; } // Commands #define RET_SUCCESS 0 #define EXECUTE(CMD, RESULT) swss::exec(std::string() + BASH_CMD + " -c \"" + CMD + "\"", RESULT); static int cmdCreateVxlan(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // ip link add {{VXLAN}} type vxlan id {{VNI}} [local {{SOURCE IP}}] dstport 4789 const std::string cmd = std::string("") + IP_CMD " link add " + info.m_vxlan + " type vxlan id " + info.m_vni + " " + (info.m_sourceIp.empty() ? "" : (" local " + info.m_sourceIp)) + " dstport 4789"; return EXECUTE(cmd, res); } static int cmdUpVxlan(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // ip link set dev {{VXLAN}} up const std::string cmd = std::string("") + IP_CMD " link set dev " + info.m_vxlan + " up"; return EXECUTE(cmd, res); } static int cmdCreateVxlanIf(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // ip link add {{VXLAN_IF}} type bridge const std::string cmd = std::string("") + IP_CMD " link add " + info.m_vxlanIf + " type bridge"; return EXECUTE(cmd, res); } static int cmdAddVxlanIntoVxlanIf(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // brctl addif {{VXLAN_IF}} {{VXLAN}} const std::string cmd = std::string("") + BRCTL_CMD " addif " + info.m_vxlanIf + " " + info.m_vxlan; return EXECUTE(cmd, res); } static int cmdAttachVxlanIfToVnet(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // ip link set dev {{VXLAN_IF}} master {{VNET}} const std::string cmd = std::string("") + IP_CMD " link set dev " + info.m_vxlanIf + " master " + info.m_vnet; return EXECUTE(cmd, res); } static int cmdUpVxlanIf(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // ip link set dev {{VXLAN_IF}} up const std::string cmd = std::string("") + IP_CMD " link set dev " + info.m_vxlanIf + " up"; return EXECUTE(cmd, res); } static int cmdDeleteVxlan(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // ip link del dev {{VXLAN}} const std::string cmd = std::string("") + IP_CMD " link del dev " + info.m_vxlan; return EXECUTE(cmd, res); } static int cmdDeleteVxlanFromVxlanIf(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // brctl delif {{VXLAN_IF}} {{VXLAN}} const std::string cmd = std::string("") + BRCTL_CMD " delif " + info.m_vxlanIf + " " + info.m_vxlan; return EXECUTE(cmd, res); } static int cmdDeleteVxlanIf(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // ip link del {{VXLAN_IF}} const std::string cmd = std::string("") + IP_CMD " link del " + info.m_vxlanIf; return EXECUTE(cmd, res); } static int cmdDetachVxlanIfFromVnet(const swss::VxlanMgr::VxlanInfo & info, std::string & res) { // ip link set dev {{VXLAN_IF}} nomaster const std::string cmd = std::string("") + IP_CMD " link set dev " + info.m_vxlanIf + " nomaster"; return EXECUTE(cmd, res); } // Vxlanmgr VxlanMgr::VxlanMgr(DBConnector *cfgDb, DBConnector *appDb, DBConnector *stateDb, const vector<std::string> &tables) : Orch(cfgDb, tables), m_appVxlanTunnelTable(appDb, APP_VXLAN_TUNNEL_TABLE_NAME), m_appVxlanTunnelMapTable(appDb, APP_VXLAN_TUNNEL_MAP_TABLE_NAME), m_cfgVxlanTunnelTable(cfgDb, CFG_VXLAN_TUNNEL_TABLE_NAME), m_cfgVnetTable(cfgDb, CFG_VNET_TABLE_NAME), m_stateVrfTable(stateDb, STATE_VRF_TABLE_NAME), m_stateVxlanTable(stateDb, STATE_VXLAN_TABLE_NAME) { // Clear old vxlan devices that were created at last time. clearAllVxlanDevices(); } VxlanMgr::~VxlanMgr() { clearAllVxlanDevices(); } void VxlanMgr::doTask(Consumer &consumer) { SWSS_LOG_ENTER(); const string & table_name = consumer.getTableName(); auto it = consumer.m_toSync.begin(); while (it != consumer.m_toSync.end()) { bool task_result = false; auto t = it->second; const std::string & op = kfvOp(t); if (op == SET_COMMAND) { if (table_name == CFG_VNET_TABLE_NAME) { task_result = doVxlanCreateTask(t); } else if (table_name == CFG_VXLAN_TUNNEL_TABLE_NAME) { task_result = doVxlanTunnelCreateTask(t); } else if (table_name == CFG_VXLAN_TUNNEL_MAP_TABLE_NAME) { task_result = doVxlanTunnelMapCreateTask(t); } else { SWSS_LOG_ERROR("Unknown table : %s", table_name.c_str()); } } else if (op == DEL_COMMAND) { if (table_name == CFG_VNET_TABLE_NAME) { task_result = doVxlanDeleteTask(t); } else if (table_name == CFG_VXLAN_TUNNEL_TABLE_NAME) { task_result = doVxlanTunnelDeleteTask(t); } else if (table_name == CFG_VXLAN_TUNNEL_MAP_TABLE_NAME) { task_result = doVxlanTunnelMapDeleteTask(t); } else { SWSS_LOG_ERROR("Unknown table : %s", table_name.c_str()); } } else { SWSS_LOG_ERROR("Unknown command : %s", op.c_str()); } if (task_result == true) { it = consumer.m_toSync.erase(it); } else { ++it; } } } bool VxlanMgr::doVxlanCreateTask(const KeyOpFieldsValuesTuple & t) { SWSS_LOG_ENTER(); VxlanInfo info; info.m_vnet = kfvKey(t); for (auto i : kfvFieldsValues(t)) { const std::string & field = fvField(i); const std::string & value = fvValue(i); if (field == VXLAN_TUNNEL) { info.m_vxlanTunnel = value; } else if (field == VNI) { info.m_vni = value; } } // If all information of vnet has been set if (info.m_vxlanTunnel.empty() || info.m_vni.empty()) { SWSS_LOG_DEBUG("Vnet %s information is incomplete", info.m_vnet.c_str()); // if the information is incomplete, just ignore this message // because all information will be sent if the information was // completely set. return true; } // If the vxlan tunnel has been created auto it = m_vxlanTunnelCache.find(info.m_vxlanTunnel); if (it == m_vxlanTunnelCache.end()) { SWSS_LOG_DEBUG("Vxlan tunnel %s has not been created", info.m_vxlanTunnel.c_str()); // Suspend this message util the vxlan tunnel is created return false; } // If the VRF(Vnet is a special VRF) has been created if (!isVrfStateOk(info.m_vnet)) { SWSS_LOG_DEBUG("Vrf %s has not been created", info.m_vnet.c_str()); // Suspend this message util the vrf is created return false; } auto sourceIp = std::find_if( it->second.begin(), it->second.end(), [](const FieldValueTuple & fvt){ return fvt.first == SOURCE_IP; }); if (sourceIp != it->second.end()) { info.m_sourceIp = sourceIp->second; } info.m_vxlan = getVxlanName(info); info.m_vxlanIf = getVxlanIfName(info); // If this vxlan has been created if (isVxlanStateOk(info.m_vxlan)) { // Because the vxlan has been create, so this message is to update // the information of vxlan. // This program just delete the old vxlan and create a new one // according to this message. doVxlanDeleteTask(t); } if (!createVxlan(info)) { SWSS_LOG_ERROR("Cannot create vxlan %s", info.m_vxlan.c_str()); return true; } m_vnetCache[info.m_vnet] = info; SWSS_LOG_INFO("Create vxlan %s", info.m_vxlan.c_str()); return true; } bool VxlanMgr::doVxlanDeleteTask(const KeyOpFieldsValuesTuple & t) { SWSS_LOG_ENTER(); const std::string & vnetName = kfvKey(t); auto it = m_vnetCache.find(vnetName); if (it == m_vnetCache.end()) { SWSS_LOG_WARN("Vxlan(Vnet %s) hasn't been created ", vnetName.c_str()); return true; } const VxlanInfo & info = it->second; if (isVxlanStateOk(info.m_vxlan)) { if ( ! deleteVxlan(info)) { SWSS_LOG_ERROR("Cannot delete vxlan %s", info.m_vxlan.c_str()); return false; } } else { SWSS_LOG_WARN("Vxlan %s hasn't been created ", info.m_vxlan.c_str()); } m_vnetCache.erase(it); SWSS_LOG_INFO("Delete vxlan %s", info.m_vxlan.c_str()); return true; } bool VxlanMgr::doVxlanTunnelCreateTask(const KeyOpFieldsValuesTuple & t) { SWSS_LOG_ENTER(); const std::string & vxlanTunnelName = kfvKey(t); m_appVxlanTunnelTable.set(vxlanTunnelName, kfvFieldsValues(t)); // Update vxlan tunnel cache m_vxlanTunnelCache[vxlanTunnelName] = kfvFieldsValues(t); SWSS_LOG_INFO("Create vxlan tunnel %s", vxlanTunnelName.c_str()); return true; } bool VxlanMgr::doVxlanTunnelDeleteTask(const KeyOpFieldsValuesTuple & t) { SWSS_LOG_ENTER(); const std::string & vxlanTunnelName = kfvKey(t); m_appVxlanTunnelTable.del(vxlanTunnelName); auto it = m_vxlanTunnelCache.find(vxlanTunnelName); if (it != m_vxlanTunnelCache.end()) { m_vxlanTunnelCache.erase(it); } SWSS_LOG_INFO("Delete vxlan tunnel %s", vxlanTunnelName.c_str()); return true; } bool VxlanMgr::doVxlanTunnelMapCreateTask(const KeyOpFieldsValuesTuple & t) { SWSS_LOG_ENTER(); std::string vxlanTunnelMapName = kfvKey(t); std::replace(vxlanTunnelMapName.begin(), vxlanTunnelMapName.end(), config_db_key_delimiter, delimiter); m_appVxlanTunnelMapTable.set(vxlanTunnelMapName, kfvFieldsValues(t)); SWSS_LOG_NOTICE("Create vxlan tunnel map %s", vxlanTunnelMapName.c_str()); return true; } bool VxlanMgr::doVxlanTunnelMapDeleteTask(const KeyOpFieldsValuesTuple & t) { SWSS_LOG_ENTER(); std::string vxlanTunnelMapName = kfvKey(t); std::replace(vxlanTunnelMapName.begin(), vxlanTunnelMapName.end(), config_db_key_delimiter, delimiter); m_appVxlanTunnelMapTable.del(vxlanTunnelMapName); SWSS_LOG_NOTICE("Delete vxlan tunnel map %s", vxlanTunnelMapName.c_str()); return true; } bool VxlanMgr::isVrfStateOk(const std::string & vrfName) { SWSS_LOG_ENTER(); std::vector<FieldValueTuple> temp; if (m_stateVrfTable.get(vrfName, temp)) { SWSS_LOG_DEBUG("Vrf %s is ready", vrfName.c_str()); return true; } SWSS_LOG_DEBUG("Vrf %s is not ready", vrfName.c_str()); return false; } bool VxlanMgr::isVxlanStateOk(const std::string & vxlanName) { SWSS_LOG_ENTER(); std::vector<FieldValueTuple> temp; if (m_stateVxlanTable.get(vxlanName, temp)) { SWSS_LOG_DEBUG("Vxlan %s is ready", vxlanName.c_str()); return true; } SWSS_LOG_DEBUG("Vxlan %s is not ready", vxlanName.c_str()); return false; } bool VxlanMgr::createVxlan(const VxlanInfo & info) { SWSS_LOG_ENTER(); std::string res; int ret = 0; // Create Vxlan ret = cmdCreateVxlan(info, res); if (ret != RET_SUCCESS) { SWSS_LOG_WARN( "Failed to create vxlan %s (vni: %s, source ip %s)", info.m_vxlan.c_str(), info.m_vni.c_str(), info.m_sourceIp.c_str()); return false; } // Up Vxlan ret = cmdUpVxlan(info, res); if (ret != RET_SUCCESS) { cmdDeleteVxlan(info, res); SWSS_LOG_WARN( "Fail to up vxlan %s", info.m_vxlan.c_str()); return false; } // Create Vxlan Interface ret = cmdCreateVxlanIf(info, res); if (ret != RET_SUCCESS) { cmdDeleteVxlan(info, res); SWSS_LOG_WARN( "Fail to create vxlan interface %s", info.m_vxlanIf.c_str()); return false; } // Add vxlan into vxlan interface ret = cmdAddVxlanIntoVxlanIf(info, res); if ( ret != RET_SUCCESS ) { cmdDeleteVxlanIf(info, res); cmdDeleteVxlan(info, res); SWSS_LOG_WARN( "Fail to add %s into %s", info.m_vxlan.c_str(), info.m_vxlanIf.c_str()); return false; } // Attach vxlan interface to vnet ret = cmdAttachVxlanIfToVnet(info, res); if ( ret != RET_SUCCESS ) { cmdDeleteVxlanFromVxlanIf(info, res); cmdDeleteVxlanIf(info, res); cmdDeleteVxlan(info, res); SWSS_LOG_WARN( "Fail to set %s master %s", info.m_vxlanIf.c_str(), info.m_vnet.c_str()); return false; } // Up Vxlan Interface ret = cmdUpVxlanIf(info, res); if ( ret != RET_SUCCESS ) { cmdDetachVxlanIfFromVnet(info, res); cmdDeleteVxlanFromVxlanIf(info, res); cmdDeleteVxlanIf(info, res); cmdDeleteVxlan(info, res); SWSS_LOG_WARN( "Fail to up bridge %s", info.m_vxlanIf.c_str()); return false; } std::vector<FieldValueTuple> fvVector; fvVector.emplace_back("state", "ok"); m_stateVxlanTable.set(info.m_vxlan, fvVector); return true; } bool VxlanMgr::deleteVxlan(const VxlanInfo & info) { SWSS_LOG_ENTER(); std::string res; cmdDetachVxlanIfFromVnet(info, res); cmdDeleteVxlanFromVxlanIf(info, res); cmdDeleteVxlanIf(info, res); cmdDeleteVxlan(info, res); m_stateVxlanTable.del(info.m_vxlan); return true; } void VxlanMgr::clearAllVxlanDevices() { std::string stdout; const std::string cmd = std::string("") + IP_CMD + " link"; int ret = EXECUTE(cmd, stdout); if (ret != 0) { SWSS_LOG_ERROR("Cannot get devices by command : %s", cmd.c_str()); return; } std::regex device_name_pattern("^\\d+:\\s+([^:]+)"); std::smatch match_result; auto lines = tokenize(stdout, '\n'); for (const std::string & line : lines) { if (!std::regex_search(line, match_result, device_name_pattern)) { continue; } std::string res; std::string device_name = match_result[1]; VxlanInfo info; if (device_name.find(VXLAN_NAME_PREFIX) == 0) { info.m_vxlan = device_name; cmdDeleteVxlan(info, res); } else if (device_name.find(VXLAN_IF_NAME_PREFIX) == 0) { info.m_vxlanIf = device_name; cmdDeleteVxlanIf(info, res); } } }
27.277003
117
0.605288
antony-rheneus
40d55c42fe669f510fc1d218f82bf4521d558aba
4,498
cpp
C++
Userland/userdel.cpp
howar6hill/serenity
3523071bb7527159f213d3710f4c74d10cf93b1a
[ "BSD-2-Clause" ]
null
null
null
Userland/userdel.cpp
howar6hill/serenity
3523071bb7527159f213d3710f4c74d10cf93b1a
[ "BSD-2-Clause" ]
null
null
null
Userland/userdel.cpp
howar6hill/serenity
3523071bb7527159f213d3710f4c74d10cf93b1a
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2019-2020, Fei Wu <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <AK/String.h> #include <AK/StringBuilder.h> #include <LibCore/ArgsParser.h> #include <ctype.h> #include <dirent.h> #include <errno.h> #include <pwd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> int main(int argc, char** argv) { const char* username = nullptr; bool remove_home = false; Core::ArgsParser args_parser; args_parser.add_option(remove_home, "Remove home directory", "remove", 'r'); args_parser.add_positional_argument(username, "Login user identity (username)", "login"); args_parser.parse(argc, argv); char temp_filename[] = "/etc/passwd.XXXXXX"; auto fd = mkstemp(temp_filename); if (fd == -1) { perror("failed to create temporary file"); return 1; } FILE* temp_file = fdopen(fd, "w"); if (!temp_file) { perror("fdopen"); if (unlink(temp_filename) < 0) { perror("unlink"); } return 1; } bool user_exists = false; String home_directory; int rc = 0; setpwent(); for (auto* pw = getpwent(); pw; pw = getpwent()) { if (strcmp(pw->pw_name, username)) { if (putpwent(pw, temp_file) != 0) { perror("failed to put an entry in the temporary passwd file"); rc = 1; break; } } else { user_exists = true; if (remove_home) home_directory = pw->pw_dir; } } endpwent(); if (fclose(temp_file)) { perror("fclose"); if (!rc) rc = 1; } if (rc == 0 && !user_exists) { fprintf(stderr, "specified user doesn't exist\n"); rc = 6; } if (rc == 0 && chmod(temp_filename, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) { perror("chmod"); rc = 1; } if (rc == 0 && rename(temp_filename, "/etc/passwd") < 0) { perror("failed to rename the temporary passwd file"); rc = 1; } if (rc) { if (unlink(temp_filename) < 0) { perror("unlink"); } return rc; } if (remove_home) { if (home_directory == "/") { fprintf(stderr, "home directory is /, not deleted!\n"); return 12; } if (access(home_directory.characters(), F_OK) != -1) { auto child = fork(); if (child < 0) { perror("fork"); return 12; } if (!child) { int rc = execl("/bin/rm", "rm", "-r", home_directory.characters(), nullptr); ASSERT(rc < 0); perror("execl"); exit(127); } int wstatus; if (waitpid(child, &wstatus, 0) < 0) { perror("waitpid"); return 12; } if (WEXITSTATUS(wstatus)) { fprintf(stderr, "failed to remove the home directory\n"); return 12; } } } return 0; }
29.592105
93
0.581147
howar6hill
40d65b0d5998de530a36e9fba1b2dbde81aa0165
228
cpp
C++
0006 - Beginner Series #3 Sum of Numbers/solution.cpp
dimitri-dev/CodeWars
da428b2f9da4e56080aac6196575e101b1395c6d
[ "MIT" ]
null
null
null
0006 - Beginner Series #3 Sum of Numbers/solution.cpp
dimitri-dev/CodeWars
da428b2f9da4e56080aac6196575e101b1395c6d
[ "MIT" ]
null
null
null
0006 - Beginner Series #3 Sum of Numbers/solution.cpp
dimitri-dev/CodeWars
da428b2f9da4e56080aac6196575e101b1395c6d
[ "MIT" ]
null
null
null
#include <iostream> using std::cin; using std::cout; int get_sum(int a, int b) { int n = (a < b ? b - a : a - b) + 1; return n * (a + b) / 2; } int main() { std::ios::sync_with_stdio(false); std::cin.tie(0); }
14.25
40
0.526316
dimitri-dev
40d742ae6cde6569ce9dd7d213a2241797716128
539
cpp
C++
Codeforces/1000~1999/1244/G.cpp
tiger0132/code-backup
9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7
[ "MIT" ]
6
2018-12-30T06:16:54.000Z
2022-03-23T08:03:33.000Z
Codeforces/1000~1999/1244/G.cpp
tiger0132/code-backup
9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7
[ "MIT" ]
null
null
null
Codeforces/1000~1999/1244/G.cpp
tiger0132/code-backup
9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7
[ "MIT" ]
null
null
null
#include <algorithm> #include <cstdio> #include <cstring> typedef long long ll; const int N = 1e6 + 61; int n, l, r, a[N]; ll k, c; int main() { scanf("%d%lld", &n, &k); if ((c = n * (n + 1ll) / 2) > k) return puts("-1"), 0; for (int i = 1; i <= n; i++) a[i] = i; l = 1, r = n; for (; l < r && c < k; l++, r--) { int rb = std::min((ll)r - l, k - c); std::swap(a[l], a[l + rb]), c += rb; } printf("%lld\n", c); for (int i = 1; i <= n; i++) printf("%d%c", i, " \n"[i == n]); for (int i = 1; i <= n; i++) printf("%d ", a[i]); }
24.5
63
0.445269
tiger0132
40d7a913383786c67a1d3eb9b5586bd8b0bb3050
3,482
cpp
C++
ReShade/Runtime/runtime_config.cpp
nipkownix/Silent-Hill-2-Enhancements
53f0990c0eb2ca1b81b6645d08a586075556bf64
[ "Zlib" ]
356
2017-11-24T21:59:54.000Z
2022-03-12T01:41:39.000Z
ReShade/Runtime/runtime_config.cpp
nipkownix/Silent-Hill-2-Enhancements
53f0990c0eb2ca1b81b6645d08a586075556bf64
[ "Zlib" ]
501
2017-11-24T23:32:16.000Z
2022-03-31T22:28:14.000Z
ReShade/Runtime/runtime_config.cpp
nipkownix/Silent-Hill-2-Enhancements
53f0990c0eb2ca1b81b6645d08a586075556bf64
[ "Zlib" ]
41
2018-04-22T19:24:56.000Z
2022-02-28T01:56:10.000Z
/** * Copyright (C) 2014 Patrick Mours. All rights reserved. * License: https://github.com/crosire/reshade#license * * Copyright (C) 2021 Elisha Riedlinger * * This software is provided 'as-is', without any express or implied warranty. In no event will the * authors be held liable for any damages arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, including commercial * applications, and to alter it and redistribute it freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not claim that you wrote the * original software. If you use this software in a product, an acknowledgment in the product * documentation would be appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be misrepresented as * being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #define RESHADE_FILE_LIST #include "runtime.hpp" #include "runtime_config.hpp" #include "runtime_objects.hpp" #include "Resources\sh2-enhce.h" #include <cassert> #include <fstream> #include <sstream> #include <iostream> extern DWORD GammaLevel; struct { bool loaded = false; reshade::ini_file cache; }g_ini_cache; reshade::ini_file::ini_file() { load(); } reshade::ini_file::~ini_file() {} void reshade::ini_file::load() { if (g_ini_cache.loaded) { return; } _sections.clear(); _modified = false; std::string GammaSection("[GammaLevel" + std::to_string(GammaLevel) + "]"); std::string file, section, line; g_ini_cache.loaded = read_resource(IDR_RESHADE_INI, file); std::istringstream s_file(file.c_str()); while (std::getline(s_file, line)) { trim(line); if (line.empty() || line[0] == ';' || line[0] == '/' || line[0] == '#') { continue; } if (line.compare(GammaSection) == 0) { line.assign("[" + GammaEffectName + ".fx]"); } // Read section name if (line[0] == '[') { section = trim(line.substr(0, line.find(']')), " \t[]"); continue; } // Read section content const auto assign_index = line.find('='); if (assign_index != std::string::npos) { const std::string key = trim(line.substr(0, assign_index)); const std::string value = trim(line.substr(assign_index + 1)); // Append to key if it already exists reshade::ini_file::value &elements = _sections[section][key]; for (size_t offset = 0, base = 0, len = value.size(); offset <= len;) { // Treat ",," as an escaped comma and only split on single "," const size_t found = std::min(value.find_first_of(',', offset), len); if (found + 1 < len && value[found + 1] == ',') { offset = found + 2; } else { std::string &element = elements.emplace_back(); element.reserve(found - base); while (base < found) { const char c = value[base++]; element += c; if (c == ',' && base < found && value[base] == ',') { base++; // Skip second comma in a ",," escape sequence } } base = offset = found + 1; } } } else { _sections[section].insert({ line, {} }); } } } void reshade::ini_file::reset_config() { g_ini_cache.loaded = false; g_ini_cache.cache.load(); } reshade::ini_file &reshade::ini_file::load_cache() { if (!g_ini_cache.loaded) { g_ini_cache.cache.load(); } return g_ini_cache.cache; }
25.985075
101
0.649339
nipkownix
40d8ff15adf3570c79c5f9e9a05603c15c8dd3a0
503
hpp
C++
addons/flag/CfgVehicles.hpp
61st-Cavalry-Regiment/61st-aux
bc6e956553fba774881c682a3f12c1b426256a30
[ "MIT" ]
2
2020-05-25T20:29:29.000Z
2020-05-26T21:11:23.000Z
addons/flag/CfgVehicles.hpp
61st-Cavalry-Regiment/61st-aux
bc6e956553fba774881c682a3f12c1b426256a30
[ "MIT" ]
3
2020-06-02T07:38:40.000Z
2021-11-13T04:54:28.000Z
addons/flag/CfgVehicles.hpp
61st-Cavalry-Regiment/61st-aux
bc6e956553fba774881c682a3f12c1b426256a30
[ "MIT" ]
1
2020-05-26T21:11:28.000Z
2020-05-26T21:11:28.000Z
class CfgVehicles { class Flag_White_F; class GVAR(Flag): Flag_White_F { author = ECSTRING(main, author); displayName = CSTRING(display); scopecurator = public; scope = public; class EventHandlers { init = QUOTE((_this select 0) setFlagTexture QUOTE(QPATHTOF(data\61stFlag.paa))); }; }; class GVAR(FlagYellow): GVAR(Flag){ displayName = CSTRING(displayYellow); class EventHandlers { init = QUOTE((_this select 0) setFlagTexture QUOTE(QPATHTOF(data\61stFlagY.paa))); }; }; };
27.944444
85
0.709742
61st-Cavalry-Regiment
40d96d3485682aa186723caedee313509a5f52f9
4,274
cpp
C++
modules/clientnotify.cpp
md-5/znc
39c741fcd2307d707a0d1bebbed3d80be9b1899b
[ "Apache-2.0" ]
null
null
null
modules/clientnotify.cpp
md-5/znc
39c741fcd2307d707a0d1bebbed3d80be9b1899b
[ "Apache-2.0" ]
null
null
null
modules/clientnotify.cpp
md-5/znc
39c741fcd2307d707a0d1bebbed3d80be9b1899b
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2004-2015 ZNC, see the NOTICE file for details. * * 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 <znc/znc.h> #include <znc/User.h> using std::set; class CClientNotifyMod : public CModule { protected: CString m_sMethod; bool m_bNewOnly; bool m_bOnDisconnect; set<CString> m_sClientsSeen; void SaveSettings() { SetNV("method", m_sMethod); SetNV("newonly", m_bNewOnly ? "1" : "0"); SetNV("ondisconnect", m_bOnDisconnect ? "1" : "0"); } void SendNotification(const CString& sMessage) { if(m_sMethod == "message") { GetUser()->PutStatus(sMessage, NULL, GetClient()); } else if(m_sMethod == "notice") { GetUser()->PutStatusNotice(sMessage, NULL, GetClient()); } } public: MODCONSTRUCTOR(CClientNotifyMod) { AddHelpCommand(); AddCommand("Method", static_cast<CModCommand::ModCmdFunc>(&CClientNotifyMod::OnMethodCommand), "<message|notice|off>", "Sets the notify method"); AddCommand("NewOnly", static_cast<CModCommand::ModCmdFunc>(&CClientNotifyMod::OnNewOnlyCommand), "<on|off>", "Turns notifies for unseen IP addresses only on or off"); AddCommand("OnDisconnect", static_cast<CModCommand::ModCmdFunc>(&CClientNotifyMod::OnDisconnectCommand), "<on|off>", "Turns notifies on disconnecting clients on or off"); AddCommand("Show", static_cast<CModCommand::ModCmdFunc>(&CClientNotifyMod::OnShowCommand), "", "Show the current settings"); } bool OnLoad(const CString& sArgs, CString& sMessage) override { m_sMethod = GetNV("method"); if(m_sMethod != "notice" && m_sMethod != "message" && m_sMethod != "off") { m_sMethod = "message"; } // default = off for these: m_bNewOnly = (GetNV("newonly") == "1"); m_bOnDisconnect = (GetNV("ondisconnect") == "1"); return true; } void OnClientLogin() override { CString sRemoteIP = GetClient()->GetRemoteIP(); if(!m_bNewOnly || m_sClientsSeen.find(sRemoteIP) == m_sClientsSeen.end()) { SendNotification("Another client authenticated as your user. " "Use the 'ListClients' command to see all " + CString(GetUser()->GetAllClients().size()) + " clients."); // the set<> will automatically disregard duplicates: m_sClientsSeen.insert(sRemoteIP); } } void OnClientDisconnect() override { if(m_bOnDisconnect) { SendNotification("A client disconnected from your user. " "Use the 'ListClients' command to see the " + CString(GetUser()->GetAllClients().size()) + " remaining client(s)."); } } void OnMethodCommand(const CString& sCommand) { const CString& sArg = sCommand.Token(1, true).AsLower(); if (sArg != "notice" && sArg != "message" && sArg != "off") { PutModule("Usage: Method <message|notice|off>"); return; } m_sMethod = sArg; SaveSettings(); PutModule("Saved."); } void OnNewOnlyCommand(const CString& sCommand) { const CString& sArg = sCommand.Token(1, true).AsLower(); if (sArg.empty()) { PutModule("Usage: NewOnly <on|off>"); return; } m_bNewOnly = sArg.ToBool(); SaveSettings(); PutModule("Saved."); } void OnDisconnectCommand(const CString& sCommand) { const CString& sArg = sCommand.Token(1, true).AsLower(); if (sArg.empty()) { PutModule("Usage: OnDisconnect <on|off>"); return; } m_bOnDisconnect = sArg.ToBool(); SaveSettings(); PutModule("Saved."); } void OnShowCommand(const CString& sLine) { PutModule("Current settings: Method: " + m_sMethod + ", for unseen IP addresses only: " + CString(m_bNewOnly) + ", notify on disconnecting clients: " + CString(m_bOnDisconnect)); } }; template<> void TModInfo<CClientNotifyMod>(CModInfo& Info) { Info.SetWikiPage("clientnotify"); } USERMODULEDEFS(CClientNotifyMod, "Notifies you when another IRC client logs into or out of your account. Configurable.")
30.528571
172
0.697005
md-5
40dbcfa342afd32f1a1720e306ca54d697957d1c
1,251
hpp
C++
PUTM_EV_TELEMETRY_2022/Core/Inc/Data_Handling.hpp
PUT-Motorsport/PUTM_EV_TELEMETRY_2022
808ed3e7c9b4263b541a804233e5905f6a9b4240
[ "Apache-2.0" ]
null
null
null
PUTM_EV_TELEMETRY_2022/Core/Inc/Data_Handling.hpp
PUT-Motorsport/PUTM_EV_TELEMETRY_2022
808ed3e7c9b4263b541a804233e5905f6a9b4240
[ "Apache-2.0" ]
null
null
null
PUTM_EV_TELEMETRY_2022/Core/Inc/Data_Handling.hpp
PUT-Motorsport/PUTM_EV_TELEMETRY_2022
808ed3e7c9b4263b541a804233e5905f6a9b4240
[ "Apache-2.0" ]
1
2021-11-22T20:06:58.000Z
2021-11-22T20:06:58.000Z
#ifndef INC_DATA_HANDLING_HPP_ #define INC_DATA_HANDLING_HPP_ #include <stdlib.h> #include <cstring> #include "stdio.h" #include "main.h" enum struct HeartBeat { Buffer1, Buffer2, Buffer3, DEFAULT, FRAME_BY_FRAME }; class Data_management { private: // Buffers containing data and states. uint8_t DataBuffer1[32] = {0}; uint8_t DataBuffer2[32] = {0}; uint8_t DataBuffer3[32] = {0}; uint8_t StateBuffer1[10] = { 0 }; uint8_t StateBuffer2[10] = { 0 }; uint8_t StateBuffer3[10] = { 0 }; public: // flags used to track arriving frames. Each bit represent corresponding frame. uint8_t DataBuffer1_flag = 0; uint8_t DataBuffer2_flag = 0; uint8_t DataBuffer3_flag = 0; // Const values indicating full state of a buffer. const uint8_t Buffer1_full = 63; const uint8_t Buffer2_full = 3; const uint8_t Buffer3_full = 255; /* Methods */ void Init(); uint8_t * Check_Buffer1(); uint8_t * Check_Buffer2(); uint8_t * Check_Buffer3(); uint8_t * return_state1_pointer() {return StateBuffer1;} uint8_t * return_state2_pointer() {return StateBuffer2;} uint8_t * return_state3_pointer() {return StateBuffer3;} void Clear_msg1(); void Clear_msg2(); void Clear_msg3(); }; void Send_Frame(); void Cycle_frames(); #endif
19.246154
80
0.723421
PUT-Motorsport
40dc24da71519bd60392ec90b5ecbbd3cae32a58
121,192
cpp
C++
src/game/shared/choreoevent.cpp
Planimeter/hl2sb-src
8ffdae584f8e4837b7a1bd90286d199d934e4b7d
[ "MIT" ]
15
2016-04-07T21:29:55.000Z
2022-03-18T08:03:31.000Z
src/game/shared/choreoevent.cpp
Planimeter/hl2sb-src
8ffdae584f8e4837b7a1bd90286d199d934e4b7d
[ "MIT" ]
1
2021-12-05T23:46:21.000Z
2021-12-06T15:48:33.000Z
src/game/shared/choreoevent.cpp
Planimeter/hl2sb-src
8ffdae584f8e4837b7a1bd90286d199d934e4b7d
[ "MIT" ]
4
2020-10-02T00:28:21.000Z
2021-12-12T16:40:01.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "tier0/dbg.h" #include <stdio.h> #include <string.h> #include <ctype.h> #include "choreoevent.h" #include "choreoactor.h" #include "choreochannel.h" #include "minmax.h" #include "mathlib/mathlib.h" #include "tier1/strtools.h" #include "choreoscene.h" #include "ichoreoeventcallback.h" #include "tier1/utlbuffer.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" int CChoreoEvent::s_nGlobalID = 1; //----------------------------------------------------------------------------- // Purpose: // Input : *owner - // *name - // percentage - //----------------------------------------------------------------------------- CEventRelativeTag::CEventRelativeTag( CChoreoEvent *owner, const char *name, float percentage ) { Assert( owner ); Assert( name ); Assert( percentage >= 0.0f ); Assert( percentage <= 1.0f ); m_Name = name; m_flPercentage = percentage; m_pOwner = owner; } //----------------------------------------------------------------------------- // Purpose: // Input : src - //----------------------------------------------------------------------------- CEventRelativeTag::CEventRelativeTag( const CEventRelativeTag& src ) { m_Name = src.m_Name; m_flPercentage = src.m_flPercentage; m_pOwner = src.m_pOwner; } //----------------------------------------------------------------------------- // Purpose: // Output : const char //----------------------------------------------------------------------------- const char *CEventRelativeTag::GetName( void ) { return m_Name.Get(); } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CEventRelativeTag::GetPercentage( void ) { return m_flPercentage; } //----------------------------------------------------------------------------- // Purpose: // Input : percentage - //----------------------------------------------------------------------------- void CEventRelativeTag::SetPercentage( float percentage ) { m_flPercentage = percentage; } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoEvent //----------------------------------------------------------------------------- CChoreoEvent *CEventRelativeTag::GetOwner( void ) { return m_pOwner; } //----------------------------------------------------------------------------- // Purpose: // Input : *event - //----------------------------------------------------------------------------- void CEventRelativeTag::SetOwner( CChoreoEvent *event ) { m_pOwner = event; } //----------------------------------------------------------------------------- // Purpose: Returns the corrected time based on the owner's length and start time // Output : float //----------------------------------------------------------------------------- float CEventRelativeTag::GetStartTime( void ) { Assert( m_pOwner ); if ( !m_pOwner ) { return 0.0f; } float ownerstart = m_pOwner->GetStartTime(); float ownerduration = m_pOwner->GetDuration(); return ( ownerstart + ownerduration * m_flPercentage ); } //----------------------------------------------------------------------------- // Purpose: // Input : *owner - // *name - // percentage - //----------------------------------------------------------------------------- CFlexTimingTag::CFlexTimingTag( CChoreoEvent *owner, const char *name, float percentage, bool locked ) : BaseClass( owner, name, percentage ) { m_bLocked = locked; } //----------------------------------------------------------------------------- // Purpose: // Input : src - //----------------------------------------------------------------------------- CFlexTimingTag::CFlexTimingTag( const CFlexTimingTag& src ) : BaseClass( src ) { m_bLocked = src.m_bLocked; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CFlexTimingTag::GetLocked( void ) { return m_bLocked; } //----------------------------------------------------------------------------- // Purpose: // Input : locked - //----------------------------------------------------------------------------- void CFlexTimingTag::SetLocked( bool locked ) { m_bLocked = locked; } //----------------------------------------------------------------------------- // Purpose: // Input : *owner - // *name - // percentage - //----------------------------------------------------------------------------- CEventAbsoluteTag::CEventAbsoluteTag( CChoreoEvent *owner, const char *name, float t ) { Assert( owner ); Assert( name ); Assert( t >= 0.0f ); m_Name = name; m_flPercentage = t; m_pOwner = owner; m_bLocked = false; m_bLinear = false; m_bEntry = false; m_bExit = false; } //----------------------------------------------------------------------------- // Purpose: // Input : src - //----------------------------------------------------------------------------- CEventAbsoluteTag::CEventAbsoluteTag( const CEventAbsoluteTag& src ) { m_Name = src.m_Name; m_flPercentage = src.m_flPercentage; m_pOwner = src.m_pOwner; m_bLocked = src.m_bLocked; m_bLinear = src.m_bLinear; m_bEntry = src.m_bEntry; m_bExit = src.m_bExit; } //----------------------------------------------------------------------------- // Purpose: // Output : const char //----------------------------------------------------------------------------- const char *CEventAbsoluteTag::GetName( void ) { return m_Name.Get(); } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CEventAbsoluteTag::GetPercentage( void ) { return m_flPercentage; } //----------------------------------------------------------------------------- // Purpose: // Input : percentage - //----------------------------------------------------------------------------- void CEventAbsoluteTag::SetPercentage( float percentage ) { m_flPercentage = percentage; } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CEventAbsoluteTag::GetEventTime( void ) { Assert( m_pOwner ); if ( !m_pOwner ) { return 0.0f; } float ownerduration = m_pOwner->GetDuration(); return (m_flPercentage * ownerduration); } //----------------------------------------------------------------------------- // Purpose: // Input : percentage - //----------------------------------------------------------------------------- void CEventAbsoluteTag::SetEventTime( float t ) { Assert( m_pOwner ); if ( !m_pOwner ) { return; } float ownerduration = m_pOwner->GetDuration(); m_flPercentage = (t / ownerduration); } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CEventAbsoluteTag::GetAbsoluteTime( void ) { Assert( m_pOwner ); if ( !m_pOwner ) { return 0.0f; } float ownerstart = m_pOwner->GetStartTime(); float ownerduration = m_pOwner->GetDuration(); return (ownerstart + m_flPercentage * ownerduration); } //----------------------------------------------------------------------------- // Purpose: // Input : percentage - //----------------------------------------------------------------------------- void CEventAbsoluteTag::SetAbsoluteTime( float t ) { Assert( m_pOwner ); if ( !m_pOwner ) { return; } float ownerstart = m_pOwner->GetStartTime(); float ownerduration = m_pOwner->GetDuration(); m_flPercentage = (t - ownerstart) / ownerduration; } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoEvent //----------------------------------------------------------------------------- CChoreoEvent *CEventAbsoluteTag::GetOwner( void ) { return m_pOwner; } //----------------------------------------------------------------------------- // Purpose: // Input : *event - //----------------------------------------------------------------------------- void CEventAbsoluteTag::SetOwner( CChoreoEvent *event ) { m_pOwner = event; } //----------------------------------------------------------------------------- // Purpose: // Input : *event - //----------------------------------------------------------------------------- void CEventAbsoluteTag::SetLocked( bool bLocked ) { m_bLocked = bLocked; } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoEvent //----------------------------------------------------------------------------- bool CEventAbsoluteTag::GetLocked( void ) { return m_bLocked; } //----------------------------------------------------------------------------- // Purpose: // Input : *event - //----------------------------------------------------------------------------- void CEventAbsoluteTag::SetLinear( bool bLinear ) { m_bLinear = bLinear; } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoEvent //----------------------------------------------------------------------------- bool CEventAbsoluteTag::GetLinear( void ) { return m_bLinear; } //----------------------------------------------------------------------------- // Purpose: // Input : *event - //----------------------------------------------------------------------------- void CEventAbsoluteTag::SetEntry( bool bEntry ) { m_bEntry = bEntry; } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoEvent //----------------------------------------------------------------------------- bool CEventAbsoluteTag::GetEntry( void ) { return m_bEntry; } //----------------------------------------------------------------------------- // Purpose: // Input : *event - //----------------------------------------------------------------------------- void CEventAbsoluteTag::SetExit( bool bExit ) { m_bExit = bExit; } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoEvent //----------------------------------------------------------------------------- bool CEventAbsoluteTag::GetExit( void ) { return m_bExit; } // FLEX ANIMATIONS //----------------------------------------------------------------------------- // Purpose: Constructor // Input : *event - //----------------------------------------------------------------------------- CFlexAnimationTrack::CFlexAnimationTrack( CChoreoEvent *event ) { m_pEvent = event; m_pControllerName = NULL; m_bActive = false; m_bCombo = false; m_bServerSide = false; m_nFlexControllerIndex[ 0 ] = m_nFlexControllerIndex[ 1 ] = -1; m_nFlexControllerIndexRaw[ 0 ] = m_nFlexControllerIndexRaw[ 1 ] = LocalFlexController_t(-1); // base track has range, combo is always 0..1 m_flMin = 0.0f; m_flMax = 0.0f; } //----------------------------------------------------------------------------- // Purpose: // Input : src - //----------------------------------------------------------------------------- CFlexAnimationTrack::CFlexAnimationTrack( const CFlexAnimationTrack* src ) { m_pControllerName = NULL; SetFlexControllerName( src->m_pControllerName ? src->m_pControllerName : "" ); m_bActive = src->m_bActive; m_bCombo = src->m_bCombo; m_bServerSide = src->m_bServerSide; for ( int t = 0; t < 2; t++ ) { m_Samples[ t ].Purge(); for ( int i = 0 ;i < src->m_Samples[ t ].Size(); i++ ) { CExpressionSample s = src->m_Samples[ t ][ i ]; m_Samples[ t ].AddToTail( s ); } } for ( int side = 0; side < 2; side++ ) { m_nFlexControllerIndex[ side ] = src->m_nFlexControllerIndex[ side ]; m_nFlexControllerIndexRaw[ side ] = src->m_nFlexControllerIndexRaw[ side ]; } m_flMin = src->m_flMin; m_flMax = src->m_flMax; m_EdgeInfo[ 0 ] = src->m_EdgeInfo[ 0 ]; m_EdgeInfo[ 1 ] = src->m_EdgeInfo[ 1 ]; m_pEvent = NULL; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CFlexAnimationTrack::~CFlexAnimationTrack( void ) { delete[] m_pControllerName; for ( int t = 0; t < 2; t++ ) { m_Samples[ t ].Purge(); } } //----------------------------------------------------------------------------- // Purpose: // Input : *event - //----------------------------------------------------------------------------- void CFlexAnimationTrack::SetEvent( CChoreoEvent *event ) { m_pEvent = event; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFlexAnimationTrack::Clear( void ) { for ( int t = 0; t < 2; t++ ) { m_Samples[ t ].RemoveAll(); } } //----------------------------------------------------------------------------- // Purpose: // Input : index - //----------------------------------------------------------------------------- void CFlexAnimationTrack::RemoveSample( int index, int type /*=0*/ ) { Assert( type == 0 || type == 1 ); m_Samples[ type ].Remove( index ); } //----------------------------------------------------------------------------- // Purpose: // Input : *name - //----------------------------------------------------------------------------- void CFlexAnimationTrack::SetFlexControllerName( const char *name ) { delete[] m_pControllerName; int len = Q_strlen( name ) + 1; m_pControllerName = new char[ len ]; Q_strncpy( m_pControllerName, name, len ); } //----------------------------------------------------------------------------- // Purpose: // Output : char const //----------------------------------------------------------------------------- const char *CFlexAnimationTrack::GetFlexControllerName( void ) { return m_pControllerName ? m_pControllerName : ""; } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int CFlexAnimationTrack::GetNumSamples( int type /*=0*/ ) { Assert( type == 0 || type == 1 ); return m_Samples[ type ].Size(); } //----------------------------------------------------------------------------- // Purpose: // Input : index - // Output : CExpressionSample //----------------------------------------------------------------------------- CExpressionSample *CFlexAnimationTrack::GetSample( int index, int type /*=0*/ ) { Assert( type == 0 || type == 1 ); if ( index < 0 || index >= GetNumSamples( type ) ) return NULL; return &m_Samples[ type ][ index ]; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CFlexAnimationTrack::IsTrackActive( void ) { return m_bActive; } //----------------------------------------------------------------------------- // Purpose: // Input : active - //----------------------------------------------------------------------------- void CFlexAnimationTrack::SetTrackActive( bool active ) { m_bActive = active; } void CFlexAnimationTrack::SetEdgeInfo( bool leftEdge, int curveType, float zero ) { int idx = leftEdge ? 0 : 1; m_EdgeInfo[ idx ].m_CurveType = curveType; m_EdgeInfo[ idx ].m_flZeroPos = zero; } void CFlexAnimationTrack::GetEdgeInfo( bool leftEdge, int& curveType, float& zero ) const { int idx = leftEdge ? 0 : 1; curveType = m_EdgeInfo[ idx ].m_CurveType; zero = m_EdgeInfo[ idx ].m_flZeroPos; } void CFlexAnimationTrack::SetEdgeActive( bool leftEdge, bool state ) { int idx = leftEdge ? 0 : 1; m_EdgeInfo[ idx ].m_bActive = state; } bool CFlexAnimationTrack::IsEdgeActive( bool leftEdge ) const { int idx = leftEdge ? 0 : 1; return m_EdgeInfo[ idx ].m_bActive; } int CFlexAnimationTrack::GetEdgeCurveType( bool leftEdge ) const { if ( !IsEdgeActive( leftEdge ) ) { return CURVE_DEFAULT; } int idx = leftEdge ? 0 : 1; return m_EdgeInfo[ idx ].m_CurveType; } float CFlexAnimationTrack::GetEdgeZeroValue( bool leftEdge ) const { if ( !IsEdgeActive( leftEdge ) ) { return 0.0f; } int idx = leftEdge ? 0 : 1; return m_EdgeInfo[ idx ].m_flZeroPos; } float CFlexAnimationTrack::GetDefaultEdgeZeroPos() const { float zero = 0.0f; if ( m_flMin != m_flMax ) { zero = ( 0.0f - m_flMin ) / ( m_flMax - m_flMin ); } return zero; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- float CFlexAnimationTrack::GetZeroValue( int type, bool leftSide ) { // Stereo track is always clamped to 0.5 and doesn't care about l/r settings if ( type == 1 ) { return 0.5f; } if ( IsEdgeActive( leftSide ) ) { return GetEdgeZeroValue( leftSide ); } return GetDefaultEdgeZeroPos(); } //----------------------------------------------------------------------------- // Purpose: // Input : number - // Output : CExpressionSample //----------------------------------------------------------------------------- CExpressionSample *CFlexAnimationTrack::GetBoundedSample( int number, bool& bClamped, int type /*=0*/ ) { Assert( type == 0 || type == 1 ); if ( number < 0 ) { // Search for two samples which span time f static CExpressionSample nullstart; nullstart.time = 0.0f; nullstart.value = GetZeroValue( type, true ); if ( type == 0 ) { nullstart.SetCurveType( GetEdgeCurveType( true ) ); } else { nullstart.SetCurveType( CURVE_DEFAULT ); } bClamped = true; return &nullstart; } else if ( number >= GetNumSamples( type ) ) { static CExpressionSample nullend; nullend.time = m_pEvent->GetDuration(); nullend.value = GetZeroValue( type, false ); if ( type == 0 ) { nullend.SetCurveType( GetEdgeCurveType( false ) ); } else { nullend.SetCurveType( CURVE_DEFAULT ); } bClamped = true; return &nullend; } bClamped = false; return GetSample( number, type ); } //----------------------------------------------------------------------------- // Purpose: // Input : time - // type - // Output : float //----------------------------------------------------------------------------- float CFlexAnimationTrack::GetIntensityInternal( float time, int type ) { Assert( type == 0 || type == 1 ); float retval = 0.0f; // find samples that span the time if ( !m_pEvent || !m_pEvent->HasEndTime() || time < m_pEvent->GetStartTime() ) { retval = GetZeroValue( type, true );; } else if ( time > m_pEvent->GetEndTime() ) { retval = GetZeroValue( type, false );; } else { float elapsed = time - m_pEvent->GetStartTime(); retval = GetFracIntensity( elapsed, type ); } // scale if (type == 0 && m_flMin != m_flMax) { retval = retval * (m_flMax - m_flMin) + m_flMin; } return retval; } //----------------------------------------------------------------------------- // Purpose: // Input : time - // type - // Output : float //----------------------------------------------------------------------------- float CFlexAnimationTrack::GetFracIntensity( float time, int type ) { float zeroValueLeft = GetZeroValue( type, true ); Assert( type == 0 || type == 1 ); // find samples that span the time if ( !m_pEvent || !m_pEvent->HasEndTime() ) return zeroValueLeft; int rampCount = GetNumSamples( type ); if ( rampCount < 1 ) { return zeroValueLeft; } CExpressionSample *esStart = NULL; CExpressionSample *esEnd = NULL; // do binary search for sample in time period int j = MAX( rampCount / 2, 1 ); int i = j; while ( i > -2 && i < rampCount + 1 ) { bool dummy; esStart = GetBoundedSample( i, dummy, type ); esEnd = GetBoundedSample( i + 1, dummy, type ); j = MAX( j / 2, 1 ); if ( time < esStart->time) { i -= j; } else if ( time > esEnd->time) { i += j; } else { if ( time == esEnd->time ) { ++i; esStart = GetBoundedSample( i, dummy, type ); esEnd = GetBoundedSample( i + 1, dummy, type ); } break; } } if (!esStart) { return zeroValueLeft; } int prev = i - 1; int next = i + 2; prev = MAX( -1, prev ); next = MIN( next, rampCount ); bool bclamp[ 2 ]; CExpressionSample *esPre = GetBoundedSample( prev, bclamp[ 0 ], type ); CExpressionSample *esNext = GetBoundedSample( next, bclamp[ 1 ], type ); float dt = esEnd->time - esStart->time; Vector vPre( esPre->time, esPre->value, 0 ); Vector vStart( esStart->time, esStart->value, 0 ); Vector vEnd( esEnd->time, esEnd->value, 0 ); Vector vNext( esNext->time, esNext->value, 0 ); float f2 = 0.0f; if ( dt > 0.0f ) { f2 = ( time - esStart->time ) / ( dt ); } f2 = clamp( f2, 0.0f, 1.0f ); Vector vOut; int dummy; int earlypart, laterpart; // Not holding out value of previous curve... Interpolator_CurveInterpolatorsForType( esStart->GetCurveType(), dummy, earlypart ); Interpolator_CurveInterpolatorsForType( esEnd->GetCurveType(), laterpart, dummy ); if ( earlypart == INTERPOLATE_HOLD ) { // Hold "out" of previous sample (can cause a discontinuity) VectorLerp( vStart, vEnd, f2, vOut ); vOut.y = vStart.y; } else if ( laterpart == INTERPOLATE_HOLD ) { // Hold "out" of previous sample (can cause a discontinuity) VectorLerp( vStart, vEnd, f2, vOut ); vOut.y = vEnd.y; } else { bool sameCurveType = earlypart == laterpart ? true : false; if ( sameCurveType ) { Interpolator_CurveInterpolate( laterpart, vPre, vStart, vEnd, vNext, f2, vOut ); } else // curves differ, sigh { Vector vOut1, vOut2; Interpolator_CurveInterpolate( earlypart, vPre, vStart, vEnd, vNext, f2, vOut1 ); Interpolator_CurveInterpolate( laterpart, vPre, vStart, vEnd, vNext, f2, vOut2 ); VectorLerp( vOut1, vOut2, f2, vOut ); } } float retval = clamp( vOut.y, 0.0f, 1.0f ); return retval; } //----------------------------------------------------------------------------- // Purpose: // Input : time - // Output : float //----------------------------------------------------------------------------- float CFlexAnimationTrack::GetSampleIntensity( float time ) { return GetIntensityInternal( time, 0 ); } //----------------------------------------------------------------------------- // Purpose: // Input : time - // Output : float //----------------------------------------------------------------------------- float CFlexAnimationTrack::GetBalanceIntensity( float time ) { if ( IsComboType() ) { return GetIntensityInternal( time, 1 ); } return 1.0f; } // For a given time, computes 0->1 intensity value for the slider //----------------------------------------------------------------------------- // Purpose: // Input : time - // Output : float //----------------------------------------------------------------------------- float CFlexAnimationTrack::GetIntensity( float time, int side ) { float mag = GetSampleIntensity( time ); float scale = 1.0f; if ( IsComboType() ) { float balance = GetBalanceIntensity( time ); // Asking for left but balance is to right, then fall off as we go // further right if ( side == 0 && balance > 0.5f ) { scale = (1.0f - balance ) / 0.5f; } // Asking for right, but balance is left, fall off as we go left. else if ( side == 1 && balance < 0.5f ) { scale = ( balance / 0.5f ); } } return mag * scale; } //----------------------------------------------------------------------------- // Purpose: // Input : time - // value - //----------------------------------------------------------------------------- CExpressionSample *CFlexAnimationTrack::AddSample( float time, float value, int type /*=0*/ ) { Assert( type == 0 || type == 1 ); CExpressionSample sample; sample.time = time; sample.value = value; sample.selected = false; int idx = m_Samples[ type ].AddToTail( sample ); // Resort( type ); return &m_Samples[ type ][ idx ]; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFlexAnimationTrack::Resort( int type /*=0*/ ) { Assert( type == 0 || type == 1 ); for ( int i = 0; i < m_Samples[ type ].Size(); i++ ) { for ( int j = i + 1; j < m_Samples[ type ].Size(); j++ ) { CExpressionSample src = m_Samples[ type ][ i ]; CExpressionSample dest = m_Samples[ type ][ j ]; if ( src.time > dest.time ) { m_Samples[ type ][ i ] = dest; m_Samples[ type ][ j ] = src; } } } // Make sure nothing is out of range RemoveOutOfRangeSamples( 0 ); RemoveOutOfRangeSamples( 1 ); } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoEvent //----------------------------------------------------------------------------- CChoreoEvent *CFlexAnimationTrack::GetEvent( void ) { return m_pEvent; } //----------------------------------------------------------------------------- // Purpose: // Input : side - // Output : int //----------------------------------------------------------------------------- int CFlexAnimationTrack::GetFlexControllerIndex( int side /*= 0*/ ) { Assert( side == 0 || side == 1 ); if ( IsComboType() ) { return m_nFlexControllerIndex[ side ]; } return m_nFlexControllerIndex[ 0 ]; } //----------------------------------------------------------------------------- // Purpose: // Input : side - // Output : int //----------------------------------------------------------------------------- LocalFlexController_t CFlexAnimationTrack::GetRawFlexControllerIndex( int side /*= 0*/ ) { Assert( side == 0 || side == 1 ); if ( IsComboType() ) { return m_nFlexControllerIndexRaw[ side ]; } return m_nFlexControllerIndexRaw[ 0 ]; } //----------------------------------------------------------------------------- // Purpose: // Input : index - // side - //----------------------------------------------------------------------------- void CFlexAnimationTrack::SetFlexControllerIndex( LocalFlexController_t raw, int index, int side /*= 0*/ ) { Assert( side == 0 || side == 1 ); m_nFlexControllerIndex[ side ] = index; // Model specific m_nFlexControllerIndexRaw[ side ] = raw; } //----------------------------------------------------------------------------- // Purpose: // Input : combo - //----------------------------------------------------------------------------- void CFlexAnimationTrack::SetComboType( bool combo ) { m_bCombo = combo; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CFlexAnimationTrack::IsComboType( void ) { return m_bCombo; } //----------------------------------------------------------------------------- // Purpose: True if this should be simulated on the server side always // Input : state - //----------------------------------------------------------------------------- void CFlexAnimationTrack::SetServerSide( bool state ) { m_bServerSide = state; } //----------------------------------------------------------------------------- // Purpose: // Input : - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CFlexAnimationTrack::IsServerSide() const { return m_bServerSide; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFlexAnimationTrack::SetMin( float value ) { m_flMin = value; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFlexAnimationTrack::SetMax( float value ) { m_flMax = value; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- float CFlexAnimationTrack::GetMin( int type ) { if (type == 0) return m_flMin; else return 0.0f; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- float CFlexAnimationTrack::GetMax( int type ) { if (type == 0) return m_flMax; else return 1.0f; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CFlexAnimationTrack::IsInverted( void ) { if (m_bInverted) return true; return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFlexAnimationTrack::SetInverted( bool isInverted ) { m_bInverted = isInverted; } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- void CFlexAnimationTrack::RemoveOutOfRangeSamples( int type ) { Assert( m_pEvent ); if ( !m_pEvent ) return; Assert( m_pEvent->HasEndTime() ); float duration = m_pEvent->GetDuration(); int c = m_Samples[ type ].Size(); for ( int i = c-1; i >= 0; i-- ) { CExpressionSample src = m_Samples[ type ][ i ]; if ( src.time < 0 || src.time > duration ) { m_Samples[ type ].Remove( i ); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CChoreoEvent::CChoreoEvent( CChoreoScene *scene ) { Init( scene ); } //----------------------------------------------------------------------------- // Purpose: // Input : type - // *name - //----------------------------------------------------------------------------- CChoreoEvent::CChoreoEvent( CChoreoScene *scene, EVENTTYPE type, const char *name ) { Init( scene ); SetType( type ); SetName( name ); } //----------------------------------------------------------------------------- // Purpose: // Input : type - // *name - // *param - //----------------------------------------------------------------------------- CChoreoEvent::CChoreoEvent( CChoreoScene *scene, EVENTTYPE type, const char *name, const char *param ) { Init( scene ); SetType( type ); SetName( name ); SetParameters( param ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CChoreoEvent::~CChoreoEvent( void ) { RemoveAllTracks(); ClearEventDependencies(); delete m_pSubScene; } //----------------------------------------------------------------------------- // Purpose: Assignment // Input : src - // Output : CChoreoEvent& //----------------------------------------------------------------------------- CChoreoEvent& CChoreoEvent::operator=( const CChoreoEvent& src ) { MEM_ALLOC_CREDIT(); // Copy global id when copying entity m_nGlobalID = src.m_nGlobalID; m_pActor = NULL; m_pChannel = NULL; m_nDefaultCurveType = src.m_nDefaultCurveType; m_fType = src.m_fType; m_Name = src.m_Name; m_Parameters = src.m_Parameters; m_Parameters2= src.m_Parameters2; m_Parameters3= src.m_Parameters3; m_flStartTime = src.m_flStartTime; m_flEndTime = src.m_flEndTime; m_bFixedLength = src.m_bFixedLength; m_flGestureSequenceDuration = src.m_flGestureSequenceDuration; m_bResumeCondition = src.m_bResumeCondition; m_bLockBodyFacing = src.m_bLockBodyFacing; m_flDistanceToTarget = src.m_flDistanceToTarget; m_bForceShortMovement = src.m_bForceShortMovement; m_bSyncToFollowingGesture = src.m_bSyncToFollowingGesture; m_bPlayOverScript = src.m_bPlayOverScript; m_bUsesTag = src.m_bUsesTag; m_TagName = src.m_TagName; m_TagWavName = src.m_TagWavName; ClearAllRelativeTags(); ClearAllTimingTags(); int t; for ( t = 0; t < NUM_ABS_TAG_TYPES; t++ ) { ClearAllAbsoluteTags( (AbsTagType)t ); } int i; for ( i = 0; i < src.m_RelativeTags.Size(); i++ ) { CEventRelativeTag newtag( src.m_RelativeTags[ i ] ); newtag.SetOwner( this ); m_RelativeTags.AddToTail( newtag ); } for ( i = 0; i < src.m_TimingTags.Size(); i++ ) { CFlexTimingTag newtag( src.m_TimingTags[ i ] ); newtag.SetOwner( this ); m_TimingTags.AddToTail( newtag ); } for ( t = 0; t < NUM_ABS_TAG_TYPES; t++ ) { for ( i = 0; i < src.m_AbsoluteTags[ t ].Size(); i++ ) { CEventAbsoluteTag newtag( src.m_AbsoluteTags[ t ][ i ] ); newtag.SetOwner( this ); m_AbsoluteTags[ t ].AddToTail( newtag ); } } RemoveAllTracks(); for ( i = 0 ; i < src.m_FlexAnimationTracks.Size(); i++ ) { CFlexAnimationTrack *newtrack = new CFlexAnimationTrack( src.m_FlexAnimationTracks[ i ] ); newtrack->SetEvent( this ); m_FlexAnimationTracks.AddToTail( newtrack ); } m_bTrackLookupSet = src.m_bTrackLookupSet; // FIXME: Use a safe handle? //m_pSubScene = src.m_pSubScene; m_bProcessing = src.m_bProcessing; m_pMixer = src.m_pMixer; m_pScene = src.m_pScene; m_nPitch = src.m_nPitch; m_nYaw = src.m_nYaw; m_nNumLoops = src.m_nNumLoops; m_nLoopsRemaining = src.m_nLoopsRemaining; // Copy ramp over m_Ramp = src.m_Ramp; m_ccType = src.m_ccType; m_CCToken = src.m_CCToken; m_bUsingCombinedSoundFile = src.m_bUsingCombinedSoundFile; m_uRequiredCombinedChecksum = src.m_uRequiredCombinedChecksum; m_nNumSlaves = src.m_nNumSlaves; m_flLastSlaveEndTime = src.m_flLastSlaveEndTime; m_bCCTokenValid = src.m_bCCTokenValid; m_bCombinedUsingGenderToken = src.m_bCombinedUsingGenderToken; m_bSuppressCaptionAttenuation = src.m_bSuppressCaptionAttenuation; m_bActive = src.m_bActive; return *this; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CChoreoEvent::Init( CChoreoScene *scene ) { m_nGlobalID = s_nGlobalID++; m_nDefaultCurveType = CURVE_CATMULL_ROM_TO_CATMULL_ROM; m_fType = UNSPECIFIED; m_Name.Set(""); m_Parameters.Set(""); m_Parameters2.Set(""); m_Parameters3.Set(""); m_flStartTime = 0.0f; m_flEndTime = -1.0f; m_pActor = NULL; m_pChannel = NULL; m_pScene = scene; m_bFixedLength = false; m_bResumeCondition = false; SetUsingRelativeTag( false, 0, 0 ); m_bTrackLookupSet = false; m_bLockBodyFacing = false; m_flDistanceToTarget = 0.0f; m_bForceShortMovement = false; m_bSyncToFollowingGesture = false; m_bPlayOverScript = false; m_pSubScene = NULL; m_bProcessing = false; m_pMixer = NULL; m_flGestureSequenceDuration = 0.0f; m_nPitch = m_nYaw = 0; m_nNumLoops = -1; m_nLoopsRemaining = 0; // Close captioning/localization support m_CCToken.Set(""); m_ccType = CC_MASTER; m_bUsingCombinedSoundFile = false; m_uRequiredCombinedChecksum = 0; m_nNumSlaves = 0; m_flLastSlaveEndTime = 0.0f; m_bCCTokenValid = false; m_bCombinedUsingGenderToken = false; m_bSuppressCaptionAttenuation = false; m_bActive = true; } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- CChoreoEvent::EVENTTYPE CChoreoEvent::GetType( void ) { return (EVENTTYPE)m_fType; } //----------------------------------------------------------------------------- // Purpose: // Input : type - //----------------------------------------------------------------------------- void CChoreoEvent::SetType( EVENTTYPE type ) { m_fType = type; if ( m_fType == SPEAK || m_fType == SUBSCENE ) { m_bFixedLength = true; } else { m_bFixedLength = false; } } //----------------------------------------------------------------------------- // Purpose: // Input : *name - //----------------------------------------------------------------------------- void CChoreoEvent::SetName( const char *name ) { m_Name = name; } //----------------------------------------------------------------------------- // Purpose: // Output : const char //----------------------------------------------------------------------------- const char *CChoreoEvent::GetName( void ) { return m_Name.Get(); } //----------------------------------------------------------------------------- // Purpose: // Input : *param - //----------------------------------------------------------------------------- void CChoreoEvent::SetParameters( const char *param ) { m_Parameters = param; } //----------------------------------------------------------------------------- // Purpose: // Output : const char //----------------------------------------------------------------------------- const char *CChoreoEvent::GetParameters( void ) { return m_Parameters.Get(); } //----------------------------------------------------------------------------- // Purpose: // Input : *param - //----------------------------------------------------------------------------- void CChoreoEvent::SetParameters2( const char *param ) { int iLength = Q_strlen( param ); m_Parameters2 = param; // HACK: Remove trailing " " until faceposer is fixed if ( iLength > 0 ) { if ( param[iLength-1] == ' ' ) { char tmp[1024]; Q_strncpy( tmp, param, sizeof(tmp) ); tmp[iLength-1] = 0; m_Parameters2.Set(tmp); } } } //----------------------------------------------------------------------------- // Purpose: // Output : const char //----------------------------------------------------------------------------- const char *CChoreoEvent::GetParameters2( void ) { return m_Parameters2.Get(); } //----------------------------------------------------------------------------- // Purpose: // Input : *param - //----------------------------------------------------------------------------- void CChoreoEvent::SetParameters3( const char *param ) { int iLength = Q_strlen( param ); m_Parameters3 = param; // HACK: Remove trailing " " until faceposer is fixed if ( iLength > 0 ) { if ( param[iLength-1] == ' ' ) { char tmp[1024]; Q_strncpy( tmp, param, sizeof(tmp) ); tmp[iLength-1] = 0; m_Parameters3.Set(tmp); } } } //----------------------------------------------------------------------------- // Purpose: // Output : const char //----------------------------------------------------------------------------- const char *CChoreoEvent::GetParameters3( void ) { return m_Parameters3.Get(); } //----------------------------------------------------------------------------- // Purpose: debugging description // Output : const char //----------------------------------------------------------------------------- const char *CChoreoEvent::GetDescription( void ) { static char description[ 256 ]; description[ 0 ] = 0; if ( !GetActor() ) { Q_snprintf( description,sizeof(description), "global %s", m_Name.Get() ); } else { Assert( m_pChannel ); Q_snprintf( description,sizeof(description), "%s : %s : %s -- %s \"%s\"", m_pActor->GetName(), m_pChannel->GetName(), GetName(), NameForType( GetType() ), GetParameters() ); if ( GetType() == EXPRESSION ) { char sz[ 256 ]; Q_snprintf( sz,sizeof(sz), " \"%s\"", GetParameters2() ); Q_strncat( description, sz, sizeof(description), COPY_ALL_CHARACTERS ); } } return description; } //----------------------------------------------------------------------------- // Purpose: // Input : starttime - //----------------------------------------------------------------------------- void CChoreoEvent::SetStartTime( float starttime ) { m_flStartTime = starttime; if ( m_flEndTime != -1.0f ) { if ( m_flEndTime < m_flStartTime ) { m_flEndTime = m_flStartTime; } } } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CChoreoEvent::GetStartTime( ) { return m_flStartTime; } //----------------------------------------------------------------------------- // Purpose: // Input : endtime - //----------------------------------------------------------------------------- void CChoreoEvent::SetEndTime( float endtime ) { bool changed = m_flEndTime != endtime; m_flEndTime = endtime; if ( endtime != -1.0f ) { if ( m_flEndTime < m_flStartTime ) { m_flEndTime = m_flStartTime; } if ( changed ) { OnEndTimeChanged(); } } } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CChoreoEvent::GetEndTime( ) { return m_flEndTime; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CChoreoEvent::HasEndTime( void ) { return m_flEndTime != -1.0f ? true : false; } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CChoreoEvent::GetCompletion( float time ) { float t = (time - GetStartTime()) / (GetEndTime() - GetStartTime()); if (t < 0.0f) return 0.0f; else if (t > 1.0f) return 1.0f; return t; } // ICurveDataAccessor method bool CChoreoEvent::CurveHasEndTime() { return HasEndTime(); } //----------------------------------------------------------------------------- // Default curve type //----------------------------------------------------------------------------- void CChoreoEvent::SetDefaultCurveType( int nCurveType ) { m_nDefaultCurveType = nCurveType; } int CChoreoEvent::GetDefaultCurveType() { return m_nDefaultCurveType; } float CCurveData::GetIntensity( ICurveDataAccessor *data, float time ) { float zeroValue = 0.0f; // find samples that span the time if ( !data->CurveHasEndTime() ) { return zeroValue; } int rampCount = GetCount(); if ( rampCount < 1 ) { // Full intensity return 1.0f; } CExpressionSample *esStart = NULL; CExpressionSample *esEnd = NULL; // do binary search for sample in time period int j = MAX( rampCount / 2, 1 ); int i = j; while ( i > -2 && i < rampCount + 1 ) { bool dummy; esStart = GetBoundedSample( data, i, dummy ); esEnd = GetBoundedSample( data, i + 1, dummy ); j = MAX( j / 2, 1 ); if ( time < esStart->time) { i -= j; } else if ( time > esEnd->time) { i += j; } else { break; } } if (!esStart) { return 1.0f; } int prev = i - 1; int next = i + 2; prev = MAX( -1, prev ); next = MIN( next, rampCount ); bool bclamp[ 2 ]; CExpressionSample *esPre = GetBoundedSample( data, prev, bclamp[ 0 ] ); CExpressionSample *esNext = GetBoundedSample( data, next, bclamp[ 1 ] ); float dt = esEnd->time - esStart->time; Vector vPre( esPre->time, esPre->value, 0 ); Vector vStart( esStart->time, esStart->value, 0 ); Vector vEnd( esEnd->time, esEnd->value, 0 ); Vector vNext( esNext->time, esNext->value, 0 ); if ( bclamp[ 0 ] ) { vPre.x = vStart.x; } if ( bclamp[ 1 ] ) { vNext.x = vEnd.x; } float f2 = 0.0f; if ( dt > 0.0f ) { f2 = ( time - esStart->time ) / ( dt ); } f2 = clamp( f2, 0.0f, 1.0f ); Vector vOut; int dummy; int earlypart, laterpart; int startCurve = esStart->GetCurveType(); int endCurve = esEnd->GetCurveType(); if ( startCurve == CURVE_DEFAULT ) { startCurve = data->GetDefaultCurveType(); } if ( endCurve == CURVE_DEFAULT ) { endCurve = data->GetDefaultCurveType(); } // Not holding out value of previous curve... Interpolator_CurveInterpolatorsForType( startCurve, dummy, earlypart ); Interpolator_CurveInterpolatorsForType( endCurve, laterpart, dummy ); if ( earlypart == INTERPOLATE_HOLD ) { // Hold "out" of previous sample (can cause a discontinuity) VectorLerp( vStart, vEnd, f2, vOut ); vOut.y = vStart.y; } else if ( laterpart == INTERPOLATE_HOLD ) { // Hold "out" of previous sample (can cause a discontinuity) VectorLerp( vStart, vEnd, f2, vOut ); vOut.y = vEnd.y; } else { bool sameCurveType = earlypart == laterpart ? true : false; if ( sameCurveType ) { Interpolator_CurveInterpolate( laterpart, vPre, vStart, vEnd, vNext, f2, vOut ); } else // curves differ, sigh { Vector vOut1, vOut2; Interpolator_CurveInterpolate( earlypart, vPre, vStart, vEnd, vNext, f2, vOut1 ); Interpolator_CurveInterpolate( laterpart, vPre, vStart, vEnd, vNext, f2, vOut2 ); VectorLerp( vOut1, vOut2, f2, vOut ); } } float retval = clamp( vOut.y, 0.0f, 1.0f ); return retval; } //----------------------------------------------------------------------------- // Purpose: Get intensity for event, bounded by scene global intensity // Output : float //----------------------------------------------------------------------------- float CChoreoEvent::GetIntensity( float scenetime ) { float global_intensity = 1.0f; if ( m_pScene ) { global_intensity = m_pScene->GetSceneRampIntensity( scenetime ); } else { Assert( 0 ); } float event_intensity = _GetIntensity( scenetime ); return global_intensity * event_intensity; } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CChoreoEvent::_GetIntensity( float scenetime ) { // Convert to event local time float time = scenetime - GetStartTime(); return m_Ramp.GetIntensity( this, time ); } float CChoreoEvent::GetIntensityArea( float scenetime ) { // Convert to event local time float time = scenetime - GetStartTime(); return m_Ramp.GetIntensityArea( this, time ); } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CCurveData::GetIntensityArea( ICurveDataAccessor *data, float time ) { float zeroValue = 0.0f; // find samples that span the time if ( !data->CurveHasEndTime() ) { return zeroValue; } int rampCount = GetCount(); if ( rampCount < 1 ) { // Full intensity return 1.0f; } CExpressionSample *esStart = NULL; CExpressionSample *esEnd = NULL; // do binary search for sample in time period int j = MAX( rampCount / 2, 1 ); int i = j; while ( i > -2 && i < rampCount + 1 ) { bool dummy; esStart = GetBoundedSample( data, i, dummy ); esEnd = GetBoundedSample( data, i + 1, dummy ); j = MAX( j / 2, 1 ); if ( time < esStart->time) { i -= j; } else if ( time > esEnd->time) { i += j; } else { break; } } UpdateIntensityArea( data ); float flTotal = 0.0f; flTotal = m_RampAccumulator[i+1]; int prev = i - 1; int next = i + 2; prev = MAX( -1, prev ); next = MIN( next, rampCount ); bool bclamp[ 2 ]; CExpressionSample *esPre = GetBoundedSample( data, prev, bclamp[ 0 ] ); CExpressionSample *esNext = GetBoundedSample( data, next, bclamp[ 1 ] ); float dt = esEnd->time - esStart->time; Vector vPre( esPre->time, esPre->value, 0 ); Vector vStart( esStart->time, esStart->value, 0 ); Vector vEnd( esEnd->time, esEnd->value, 0 ); Vector vNext( esNext->time, esNext->value, 0 ); if ( bclamp[ 0 ] ) { vPre.x = vStart.x; } if ( bclamp[ 1 ] ) { vNext.x = vEnd.x; } float f2 = 0.0f; if ( dt > 0.0f ) { f2 = ( time - esStart->time ) / ( dt ); } f2 = clamp( f2, 0.0f, 1.0f ); Vector vOut; int dummy; int earlypart, laterpart; int startCurve = esStart->GetCurveType(); int endCurve = esEnd->GetCurveType(); if ( startCurve == CURVE_DEFAULT ) { startCurve = data->GetDefaultCurveType(); } if ( endCurve == CURVE_DEFAULT ) { endCurve = data->GetDefaultCurveType(); } // Not holding out value of previous curve... Interpolator_CurveInterpolatorsForType( startCurve, dummy, earlypart ); Interpolator_CurveInterpolatorsForType( endCurve, laterpart, dummy ); // FIXME: needs other curve types Catmull_Rom_Spline_Integral_Normalize( vPre, vStart, vEnd, vNext, f2, vOut ); // Con_Printf( "Accum %f : Partial %f\n", flTotal, vOut.y * (vEnd.x - vStart.x) * f2 ); flTotal = flTotal + clamp( vOut.y, 0.0f, 1.0f ) * (vEnd.x - vStart.x); return flTotal; } void CCurveData::UpdateIntensityArea( ICurveDataAccessor *data ) { int rampCount = GetCount();; if ( rampCount < 1 ) { return; } if (m_RampAccumulator.Count() == rampCount + 2) { return; } m_RampAccumulator.SetCount( rampCount + 2 ); int i = -1; bool dummy; CExpressionSample *esPre = GetBoundedSample( data, i - 1, dummy ); CExpressionSample *esStart = GetBoundedSample( data, i, dummy ); CExpressionSample *esEnd = GetBoundedSample( data, MIN( i + 1, rampCount ), dummy ); Vector vPre( esPre->time, esPre->value, 0 ); Vector vStart( esStart->time, esStart->value, 0 ); Vector vEnd( esEnd->time, esEnd->value, 0 ); Vector vOut; for (i = -1; i < rampCount; i++) { CExpressionSample *esNext = GetBoundedSample( data, MIN( i + 2, rampCount ), dummy ); Vector vNext( esNext->time, esNext->value, 0 ); Catmull_Rom_Spline_Integral_Normalize( vPre, vStart, vEnd, vNext, 1.0f, vOut ); m_RampAccumulator[i+1] = clamp( vOut.y, 0.0f, 1.0f ) * (vEnd.x - vStart.x); vPre = vStart; vStart = vEnd; vEnd = vNext; } } //----------------------------------------------------------------------------- // Purpose: // Input : dt - //----------------------------------------------------------------------------- void CChoreoEvent::OffsetStartTime( float dt ) { SetStartTime( GetStartTime() + dt ); } //----------------------------------------------------------------------------- // Purpose: // Input : dt - //----------------------------------------------------------------------------- void CChoreoEvent::OffsetEndTime( float dt ) { if ( HasEndTime() ) { SetEndTime( GetEndTime() + dt ); } } //----------------------------------------------------------------------------- // Purpose: // Input : dt - //----------------------------------------------------------------------------- void CChoreoEvent::OffsetTime( float dt ) { if ( HasEndTime() ) { m_flEndTime += dt; } m_flStartTime += dt; } //----------------------------------------------------------------------------- // Purpose: // Input : *actor - //----------------------------------------------------------------------------- void CChoreoEvent::SetActor( CChoreoActor *actor ) { m_pActor = actor; } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoActor //----------------------------------------------------------------------------- CChoreoActor *CChoreoEvent::GetActor( void ) { return m_pActor; } //----------------------------------------------------------------------------- // Purpose: // Input : *channel - //----------------------------------------------------------------------------- void CChoreoEvent::SetChannel( CChoreoChannel *channel ) { m_pChannel = channel; } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoChannel //----------------------------------------------------------------------------- CChoreoChannel *CChoreoEvent::GetChannel( void ) { return m_pChannel; } //----------------------------------------------------------------------------- // Purpose: // Input : *scene - //----------------------------------------------------------------------------- void CChoreoEvent::SetSubScene( CChoreoScene *scene ) { m_pSubScene = scene; } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoScene //----------------------------------------------------------------------------- CChoreoScene *CChoreoEvent::GetSubScene( void ) { return m_pSubScene; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- struct EventNameMap_t { CChoreoEvent::EVENTTYPE type; char const *name; }; static EventNameMap_t g_NameMap[] = { { CChoreoEvent::UNSPECIFIED, "unspecified" }, // error condition!!! { CChoreoEvent::SECTION, "section" }, { CChoreoEvent::EXPRESSION, "expression" }, { CChoreoEvent::LOOKAT, "lookat" }, { CChoreoEvent::MOVETO, "moveto" }, { CChoreoEvent::SPEAK, "speak" }, { CChoreoEvent::GESTURE, "gesture" }, { CChoreoEvent::SEQUENCE, "sequence" }, { CChoreoEvent::FACE, "face" }, { CChoreoEvent::FIRETRIGGER, "firetrigger" }, { CChoreoEvent::FLEXANIMATION, "flexanimation" }, { CChoreoEvent::SUBSCENE, "subscene" }, { CChoreoEvent::LOOP, "loop" }, { CChoreoEvent::INTERRUPT, "interrupt" }, { CChoreoEvent::STOPPOINT, "stoppoint" }, { CChoreoEvent::PERMIT_RESPONSES, "permitresponses" }, { CChoreoEvent::GENERIC, "generic" }, }; //----------------------------------------------------------------------------- // Purpose: A simple class to verify the names data above at runtime //----------------------------------------------------------------------------- class CCheckEventNames { public: CCheckEventNames() { if ( ARRAYSIZE( g_NameMap ) != CChoreoEvent::NUM_TYPES ) { Error( "g_NameMap contains %llu entries, CChoreoEvent::NUM_TYPES == %i!", (uint64)(ARRAYSIZE( g_NameMap )), CChoreoEvent::NUM_TYPES ); } for ( int i = 0; i < CChoreoEvent::NUM_TYPES; ++i ) { if ( !g_NameMap[ i ].name ) { Error( "g_NameMap: Event type at %i has NULL name string!", i ); } if ( (CChoreoEvent::EVENTTYPE)(i) == g_NameMap[ i ].type ) continue; Error( "g_NameMap: Event type at %i has wrong value (%i)!", i, (int)g_NameMap[ i ].type ); } } }; static CCheckEventNames g_CheckNamesSingleton; //----------------------------------------------------------------------------- // Purpose: // Input : *name - // Output : int //----------------------------------------------------------------------------- CChoreoEvent::EVENTTYPE CChoreoEvent::TypeForName( const char *name ) { for ( int i = 0; i < NUM_TYPES; ++i ) { EventNameMap_t *slot = &g_NameMap[ i ]; if ( !Q_stricmp( name, slot->name ) ) return slot->type; } Assert( !"CChoreoEvent::TypeForName failed!!!" ); return UNSPECIFIED; } //----------------------------------------------------------------------------- // Purpose: // Input : type - // Output : const char //----------------------------------------------------------------------------- const char *CChoreoEvent::NameForType( EVENTTYPE type ) { int i = (int)type; if ( i < 0 || i >= NUM_TYPES ) { Assert( "!CChoreoEvent::NameForType: bogus type!" ); // returns "unspecified!!!"; return g_NameMap[ 0 ].name; } return g_NameMap[ i ].name; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- struct CCNameMap_t { CChoreoEvent::CLOSECAPTION type; char const *name; }; static CCNameMap_t g_CCNameMap[] = { { CChoreoEvent::CC_MASTER, "cc_master" }, // error condition!!! { CChoreoEvent::CC_SLAVE, "cc_slave" }, { CChoreoEvent::CC_DISABLED, "cc_disabled" }, }; //----------------------------------------------------------------------------- // Purpose: A simple class to verify the names data above at runtime //----------------------------------------------------------------------------- class CCheckCCNames { public: CCheckCCNames() { if ( ARRAYSIZE( g_CCNameMap ) != CChoreoEvent::NUM_CC_TYPES ) { Error( "g_CCNameMap contains %llu entries, CChoreoEvent::NUM_CC_TYPES == %i!", (uint64)(ARRAYSIZE( g_CCNameMap )), CChoreoEvent::NUM_CC_TYPES ); } for ( int i = 0; i < CChoreoEvent::NUM_CC_TYPES; ++i ) { if ( !g_CCNameMap[ i ].name ) { Error( "g_NameMap: CC type at %i has NULL name string!", i ); } if ( (CChoreoEvent::CLOSECAPTION)(i) == g_CCNameMap[ i ].type ) continue; Error( "g_CCNameMap: Event type at %i has wrong value (%i)!", i, (int)g_CCNameMap[ i ].type ); } } }; static CCheckCCNames g_CheckCCNamesSingleton; //----------------------------------------------------------------------------- // Purpose: // Input : *name - // Output : CLOSECAPTION //----------------------------------------------------------------------------- CChoreoEvent::CLOSECAPTION CChoreoEvent::CCTypeForName( const char *name ) { for ( int i = 0; i < NUM_CC_TYPES; ++i ) { CCNameMap_t *slot = &g_CCNameMap[ i ]; if ( !Q_stricmp( name, slot->name ) ) return slot->type; } Assert( !"CChoreoEvent::TypeForName failed!!!" ); return CC_MASTER; } //----------------------------------------------------------------------------- // Purpose: // Input : type - // Output : const char //----------------------------------------------------------------------------- const char *CChoreoEvent::NameForCCType( CLOSECAPTION type ) { int i = (int)type; if ( i < 0 || i >= NUM_CC_TYPES ) { Assert( "!CChoreoEvent::NameForType: bogus type!" ); // returns "unspecified!!!"; return g_CCNameMap[ 0 ].name; } return g_CCNameMap[ i ].name; } //----------------------------------------------------------------------------- // Purpose: Is the event something that can be sized ( a wave file, e.g. ) // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CChoreoEvent::IsFixedLength( void ) { return m_bFixedLength; } //----------------------------------------------------------------------------- // Purpose: // Input : isfixedlength - //----------------------------------------------------------------------------- void CChoreoEvent::SetFixedLength( bool isfixedlength ) { m_bFixedLength = isfixedlength; } //----------------------------------------------------------------------------- // Purpose: // Input : resumecondition - //----------------------------------------------------------------------------- void CChoreoEvent::SetResumeCondition( bool resumecondition ) { m_bResumeCondition = resumecondition; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CChoreoEvent::IsResumeCondition( void ) { return m_bResumeCondition; } //----------------------------------------------------------------------------- // Purpose: // Input : lockbodyfacing - //----------------------------------------------------------------------------- void CChoreoEvent::SetLockBodyFacing( bool lockbodyfacing ) { m_bLockBodyFacing = lockbodyfacing; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CChoreoEvent::IsLockBodyFacing( void ) { return m_bLockBodyFacing; } //----------------------------------------------------------------------------- // Purpose: // Input : distancetotarget - //----------------------------------------------------------------------------- void CChoreoEvent::SetDistanceToTarget( float distancetotarget ) { m_flDistanceToTarget = distancetotarget; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns ideal distance to target //----------------------------------------------------------------------------- float CChoreoEvent::GetDistanceToTarget( void ) { return m_flDistanceToTarget; } //----------------------------------------------------------------------------- // Purpose: // Input : set if small (sub-1/2 bbox) movements are forced //----------------------------------------------------------------------------- void CChoreoEvent::SetForceShortMovement( bool bForceShortMovement ) { m_bForceShortMovement = bForceShortMovement; } //----------------------------------------------------------------------------- // Purpose: // Output : get if small (sub-1/2 bbox) movements are forced //----------------------------------------------------------------------------- bool CChoreoEvent::GetForceShortMovement( void ) { return m_bForceShortMovement; } //----------------------------------------------------------------------------- // Purpose: // Input : set if the gesture should sync its exit tag with the following gestures entry tag //----------------------------------------------------------------------------- void CChoreoEvent::SetSyncToFollowingGesture( bool bSyncToFollowingGesture ) { m_bSyncToFollowingGesture = bSyncToFollowingGesture; } //----------------------------------------------------------------------------- // Purpose: // Output : get if the gesture should sync its exit tag with the following gestures entry tag //----------------------------------------------------------------------------- bool CChoreoEvent::GetSyncToFollowingGesture( void ) { return m_bSyncToFollowingGesture; } //----------------------------------------------------------------------------- // Purpose: // Input : set if the sequence should player overtop of an underlying SS //----------------------------------------------------------------------------- void CChoreoEvent::SetPlayOverScript( bool bPlayOverScript ) { m_bPlayOverScript = bPlayOverScript; } //----------------------------------------------------------------------------- // Purpose: // Output : get if the sequence should player overtop of an underlying SS //----------------------------------------------------------------------------- bool CChoreoEvent::GetPlayOverScript( void ) { return m_bPlayOverScript; } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CChoreoEvent::GetDuration( void ) { if ( HasEndTime() ) { return GetEndTime() - GetStartTime(); } return 0.0f; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CChoreoEvent::ClearAllRelativeTags( void ) { m_RelativeTags.Purge(); } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int CChoreoEvent::GetNumRelativeTags( void ) { return m_RelativeTags.Size(); } //----------------------------------------------------------------------------- // Purpose: // Input : tagnum - // Output : CEventRelativeTag //----------------------------------------------------------------------------- CEventRelativeTag *CChoreoEvent::GetRelativeTag( int tagnum ) { Assert( tagnum >= 0 && tagnum < m_RelativeTags.Size() ); return &m_RelativeTags[ tagnum ]; } //----------------------------------------------------------------------------- // Purpose: // Input : *tagname - // percentage - //----------------------------------------------------------------------------- void CChoreoEvent::AddRelativeTag( const char *tagname, float percentage ) { CEventRelativeTag rt( this, tagname, percentage ); m_RelativeTags.AddToTail( rt ); } //----------------------------------------------------------------------------- // Purpose: // Input : *tagname - //----------------------------------------------------------------------------- void CChoreoEvent::RemoveRelativeTag( const char *tagname ) { for ( int i = 0; i < m_RelativeTags.Size(); i++ ) { CEventRelativeTag *prt = &m_RelativeTags[ i ]; if ( !prt ) continue; if ( !stricmp( prt->GetName(), tagname ) ) { m_RelativeTags.Remove( i ); return; } } } //----------------------------------------------------------------------------- // Purpose: // Input : *tagname - // Output : CEventRelativeTag * //----------------------------------------------------------------------------- CEventRelativeTag * CChoreoEvent::FindRelativeTag( const char *tagname ) { for ( int i = 0; i < m_RelativeTags.Size(); i++ ) { CEventRelativeTag *prt = &m_RelativeTags[ i ]; if ( !prt ) continue; if ( !stricmp( prt->GetName(), tagname ) ) { return prt; } } return NULL; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CChoreoEvent::IsUsingRelativeTag( void ) { return m_bUsesTag; } //----------------------------------------------------------------------------- // Purpose: // Input : usetag - // 0 - //----------------------------------------------------------------------------- void CChoreoEvent::SetUsingRelativeTag( bool usetag, const char *tagname /*= 0*/, const char *wavname /* = 0 */ ) { m_bUsesTag = usetag; if ( tagname ) { m_TagName = tagname; } else { m_TagName.Set(""); } if ( wavname ) { m_TagWavName = wavname; } else { m_TagWavName.Set(""); } } //----------------------------------------------------------------------------- // Purpose: // Output : const char //----------------------------------------------------------------------------- const char *CChoreoEvent::GetRelativeTagName( void ) { return m_TagName.Get(); } //----------------------------------------------------------------------------- // Purpose: // Output : const char //----------------------------------------------------------------------------- const char *CChoreoEvent::GetRelativeWavName( void ) { return m_TagWavName.Get(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CChoreoEvent::ClearAllTimingTags( void ) { m_TimingTags.Purge(); } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int CChoreoEvent::GetNumTimingTags( void ) { return m_TimingTags.Size(); } //----------------------------------------------------------------------------- // Purpose: // Input : tagnum - // Output : CEventRelativeTag //----------------------------------------------------------------------------- CFlexTimingTag *CChoreoEvent::GetTimingTag( int tagnum ) { Assert( tagnum >= 0 && tagnum < m_TimingTags.Size() ); return &m_TimingTags[ tagnum ]; } //----------------------------------------------------------------------------- // Purpose: // Input : *tagname - // percentage - //----------------------------------------------------------------------------- void CChoreoEvent::AddTimingTag( const char *tagname, float percentage, bool locked ) { CFlexTimingTag tt( this, tagname, percentage, locked ); m_TimingTags.AddToTail( tt ); // Sort tags CFlexTimingTag temp( (CChoreoEvent *)0x1, "", 0.0f, false ); // ugly bubble sort for ( int i = 0; i < m_TimingTags.Size(); i++ ) { for ( int j = i + 1; j < m_TimingTags.Size(); j++ ) { CFlexTimingTag *t1 = &m_TimingTags[ i ]; CFlexTimingTag *t2 = &m_TimingTags[ j ]; if ( t1->GetPercentage() > t2->GetPercentage() ) { temp = *t1; *t1 = *t2; *t2 = temp; } } } } //----------------------------------------------------------------------------- // Purpose: // Input : *tagname - //----------------------------------------------------------------------------- void CChoreoEvent::RemoveTimingTag( const char *tagname ) { for ( int i = 0; i < m_TimingTags.Size(); i++ ) { CFlexTimingTag *ptt = &m_TimingTags[ i ]; if ( !ptt ) continue; if ( !stricmp( ptt->GetName(), tagname ) ) { m_TimingTags.Remove( i ); return; } } } //----------------------------------------------------------------------------- // Purpose: // Input : *tagname - // Output : CEventRelativeTag * //----------------------------------------------------------------------------- CFlexTimingTag * CChoreoEvent::FindTimingTag( const char *tagname ) { for ( int i = 0; i < m_TimingTags.Size(); i++ ) { CFlexTimingTag *ptt = &m_TimingTags[ i ]; if ( !ptt ) continue; if ( !stricmp( ptt->GetName(), tagname ) ) { return ptt; } } return NULL; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CChoreoEvent::OnEndTimeChanged( void ) { int c = GetNumFlexAnimationTracks(); for ( int i = 0; i < c; i++ ) { CFlexAnimationTrack *track = GetFlexAnimationTrack( i ); Assert( track ); if ( !track ) continue; track->Resort( 0 ); } } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int CChoreoEvent::GetNumFlexAnimationTracks( void ) { return m_FlexAnimationTracks.Size(); } //----------------------------------------------------------------------------- // Purpose: // Input : index - // Output : CFlexAnimationTrack //----------------------------------------------------------------------------- CFlexAnimationTrack *CChoreoEvent::GetFlexAnimationTrack( int index ) { if ( index < 0 || index >= GetNumFlexAnimationTracks() ) return NULL; return m_FlexAnimationTracks[ index ]; } //----------------------------------------------------------------------------- // Purpose: // Input : *controllername - // Output : CFlexAnimationTrack //----------------------------------------------------------------------------- CFlexAnimationTrack *CChoreoEvent::AddTrack( const char *controllername ) { CFlexAnimationTrack *newTrack = new CFlexAnimationTrack( this ); newTrack->SetFlexControllerName( controllername ); m_FlexAnimationTracks.AddToTail( newTrack ); return newTrack; } //----------------------------------------------------------------------------- // Purpose: // Input : index - //----------------------------------------------------------------------------- void CChoreoEvent::RemoveTrack( int index ) { CFlexAnimationTrack *track = GetFlexAnimationTrack( index ); if ( !track ) return; m_FlexAnimationTracks.Remove( index ); delete track; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CChoreoEvent::RemoveAllTracks( void ) { while ( GetNumFlexAnimationTracks() > 0 ) { RemoveTrack( 0 ); } } //----------------------------------------------------------------------------- // Purpose: // Input : *controllername - // Output : CFlexAnimationTrack //----------------------------------------------------------------------------- CFlexAnimationTrack *CChoreoEvent::FindTrack( const char *controllername ) { for ( int i = 0; i < GetNumFlexAnimationTracks(); i++ ) { CFlexAnimationTrack *t = GetFlexAnimationTrack( i ); if ( t && !stricmp( t->GetFlexControllerName(), controllername ) ) { return t; } } return NULL; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CChoreoEvent::GetTrackLookupSet( void ) { return m_bTrackLookupSet; } //----------------------------------------------------------------------------- // Purpose: // Input : set - //----------------------------------------------------------------------------- void CChoreoEvent::SetTrackLookupSet( bool set ) { m_bTrackLookupSet = set; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CChoreoEvent::IsProcessing( void ) const { return m_bProcessing; } //----------------------------------------------------------------------------- // Purpose: // Input : *cb - // t - //----------------------------------------------------------------------------- void CChoreoEvent::StartProcessing( IChoreoEventCallback *cb, CChoreoScene *scene, float t ) { Assert( !m_bProcessing ); m_bProcessing = true; if ( cb ) { cb->StartEvent( t, scene, this ); } } //----------------------------------------------------------------------------- // Purpose: // Input : *cb - // t - //----------------------------------------------------------------------------- void CChoreoEvent::ContinueProcessing( IChoreoEventCallback *cb, CChoreoScene *scene, float t ) { Assert( m_bProcessing ); if ( cb ) { cb->ProcessEvent( t, scene, this ); } } //----------------------------------------------------------------------------- // Purpose: // Input : *cb - // t - //----------------------------------------------------------------------------- void CChoreoEvent::StopProcessing( IChoreoEventCallback *cb, CChoreoScene *scene, float t ) { Assert( m_bProcessing ); if ( cb ) { cb->EndEvent( t, scene, this ); } m_bProcessing = false; } //----------------------------------------------------------------------------- // Purpose: // Input : *cb - // t - //----------------------------------------------------------------------------- bool CChoreoEvent::CheckProcessing( IChoreoEventCallback *cb, CChoreoScene *scene, float t ) { //Assert( !m_bProcessing ); if ( cb ) { return cb->CheckEvent( t, scene, this ); } return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CChoreoEvent::ResetProcessing( void ) { if ( GetType() == LOOP ) { m_nLoopsRemaining = m_nNumLoops; } m_bProcessing = false; } //----------------------------------------------------------------------------- // Purpose: // Input : *mixer - //----------------------------------------------------------------------------- void CChoreoEvent::SetMixer( CAudioMixer *mixer ) { m_pMixer = mixer; } //----------------------------------------------------------------------------- // Purpose: // Output : CAudioMixer //----------------------------------------------------------------------------- CAudioMixer *CChoreoEvent::GetMixer( void ) const { return m_pMixer; } // Snap to scene framerate //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CChoreoEvent::SnapTimes() { if ( HasEndTime() && !IsFixedLength() ) { m_flEndTime = SnapTime( m_flEndTime ); } float oldstart = m_flStartTime; m_flStartTime = SnapTime( m_flStartTime ); // Don't snap end time for fixed length events, just set based on new start time if ( IsFixedLength() ) { float dt = m_flStartTime - oldstart; m_flEndTime += dt; } } //----------------------------------------------------------------------------- // Purpose: // Input : t - // Output : float //----------------------------------------------------------------------------- float CChoreoEvent::SnapTime( float t ) { CChoreoScene *scene = GetScene(); if ( !scene) { Assert( 0 ); return t; } return scene->SnapTime( t ); } //----------------------------------------------------------------------------- // Purpose: // Output : CChoreoScene //----------------------------------------------------------------------------- CChoreoScene *CChoreoEvent::GetScene( void ) { return m_pScene; } //----------------------------------------------------------------------------- // Purpose: // Input : *scene - //----------------------------------------------------------------------------- void CChoreoEvent::SetScene( CChoreoScene *scene ) { m_pScene = scene; } //----------------------------------------------------------------------------- // Purpose: // Input : t - // Output : char const //----------------------------------------------------------------------------- const char *CChoreoEvent::NameForAbsoluteTagType( AbsTagType t ) { switch ( t ) { case PLAYBACK: return "playback_time"; case ORIGINAL: return "shifted_time"; default: break; } return "AbsTagType(unknown)"; } //----------------------------------------------------------------------------- // Purpose: // Input : *name - // Output : AbsTagType //----------------------------------------------------------------------------- CChoreoEvent::AbsTagType CChoreoEvent::TypeForAbsoluteTagName( const char *name ) { if ( !Q_strcasecmp( name, "playback_time" ) ) { return PLAYBACK; } else if ( !Q_strcasecmp( name, "shifted_time" ) ) { return ORIGINAL; } return (AbsTagType)-1; } //----------------------------------------------------------------------------- // Purpose: // Input : type - //----------------------------------------------------------------------------- void CChoreoEvent::ClearAllAbsoluteTags( AbsTagType type ) { m_AbsoluteTags[ type ].Purge(); } //----------------------------------------------------------------------------- // Purpose: // Input : type - // Output : int //----------------------------------------------------------------------------- int CChoreoEvent::GetNumAbsoluteTags( AbsTagType type ) { return m_AbsoluteTags[ type ].Size(); } //----------------------------------------------------------------------------- // Purpose: // Input : type - // tagnum - // Output : CEventAbsoluteTag //----------------------------------------------------------------------------- CEventAbsoluteTag *CChoreoEvent::GetAbsoluteTag( AbsTagType type, int tagnum ) { Assert( tagnum >= 0 && tagnum < m_AbsoluteTags[ type ].Size() ); return &m_AbsoluteTags[ type ][ tagnum ]; } //----------------------------------------------------------------------------- // Purpose: // Input : type - // *tagname - // Output : CEventAbsoluteTag //----------------------------------------------------------------------------- CEventAbsoluteTag *CChoreoEvent::FindAbsoluteTag( AbsTagType type, const char *tagname ) { for ( int i = 0; i < m_AbsoluteTags[ type ].Size(); i++ ) { CEventAbsoluteTag *ptag = &m_AbsoluteTags[ type ][ i ]; if ( !ptag ) continue; if ( !stricmp( ptag->GetName(), tagname ) ) { return ptag; } } return NULL; } //----------------------------------------------------------------------------- // Purpose: // Input : type - // *tagname - // t - //----------------------------------------------------------------------------- void CChoreoEvent::AddAbsoluteTag( AbsTagType type, const char *tagname, float t ) { CEventAbsoluteTag at( this, tagname, t ); m_AbsoluteTags[ type ].AddToTail( at ); // Sort tags CEventAbsoluteTag temp( (CChoreoEvent *)0x1, "", 0.0f ); // ugly bubble sort for ( int i = 0; i < m_AbsoluteTags[ type ].Size(); i++ ) { for ( int j = i + 1; j < m_AbsoluteTags[ type ].Size(); j++ ) { CEventAbsoluteTag *t1 = &m_AbsoluteTags[ type ][ i ]; CEventAbsoluteTag *t2 = &m_AbsoluteTags[ type ][ j ]; if ( t1->GetPercentage() > t2->GetPercentage() ) { temp = *t1; *t1 = *t2; *t2 = temp; } } } } //----------------------------------------------------------------------------- // Purpose: // Input : type - // *tagname - //----------------------------------------------------------------------------- void CChoreoEvent::RemoveAbsoluteTag( AbsTagType type, const char *tagname ) { for ( int i = 0; i < m_AbsoluteTags[ type ].Size(); i++ ) { CEventAbsoluteTag *ptag = &m_AbsoluteTags[ type ][ i ]; if ( !ptag ) continue; if ( !stricmp( ptag->GetName(), tagname ) ) { m_AbsoluteTags[ type ].Remove( i ); return; } } } //----------------------------------------------------------------------------- // Purpose: makes sure tags in PLAYBACK are in the same order as ORIGINAL // Input : // Output : true if they were in order, false if it has to reorder them //----------------------------------------------------------------------------- bool CChoreoEvent::VerifyTagOrder( ) { bool bInOrder = true; // Sort tags CEventAbsoluteTag temp( (CChoreoEvent *)0x1, "", 0.0f ); for ( int i = 0; i < m_AbsoluteTags[ CChoreoEvent::ORIGINAL ].Size(); i++ ) { CEventAbsoluteTag *ptag = &m_AbsoluteTags[ CChoreoEvent::ORIGINAL ][ i ]; if ( !ptag ) continue; CEventAbsoluteTag *t1 = &m_AbsoluteTags[ CChoreoEvent::PLAYBACK ][ i ]; if ( stricmp( ptag->GetName(), t1->GetName() ) == 0) continue; bInOrder = false; for ( int j = i + 1; j < m_AbsoluteTags[ CChoreoEvent::PLAYBACK ].Size(); j++ ) { CEventAbsoluteTag *t2 = &m_AbsoluteTags[ CChoreoEvent::PLAYBACK ][ j ]; if ( stricmp( ptag->GetName(), t2->GetName() ) == 0 ) { temp = *t1; *t1 = *t2; *t2 = temp; break; } } } return bInOrder; } //----------------------------------------------------------------------------- // Purpose: // Input : type - // *tagname - //----------------------------------------------------------------------------- float CChoreoEvent::GetBoundedAbsoluteTagPercentage( AbsTagType type, int tagnum ) { if ( tagnum <= -2 ) { /* if (GetNumAbsoluteTags( type ) >= 1) { CEventAbsoluteTag *tag = GetAbsoluteTag( type, 0 ); Assert( tag ); return -tag->GetTime(); } */ return 0.0f; // -0.5f; } else if ( tagnum == -1 ) { return 0.0f; } else if ( tagnum == GetNumAbsoluteTags( type ) ) { return 1.0; } else if ( tagnum > GetNumAbsoluteTags( type ) ) { /* if (GetNumAbsoluteTags( type ) >= 1) { CEventAbsoluteTag *tag = GetAbsoluteTag( type, tagnum - 2 ); Assert( tag ); return 2.0 - tag->GetTime(); } */ return 1.0; // 1.5; } /* { float duration = GetDuration(); if ( type == SHIFTED ) { float seqduration; GetGestureSequenceDuration( seqduration ); return seqduration; } return duration; } */ CEventAbsoluteTag *tag = GetAbsoluteTag( type, tagnum ); Assert( tag ); return tag->GetPercentage(); } //----------------------------------------------------------------------------- // Purpose: // Input : t - // Output : float //----------------------------------------------------------------------------- float CChoreoEvent::GetOriginalPercentageFromPlaybackPercentage( float t ) { Assert( GetType() == GESTURE ); if ( GetType() != GESTURE ) return t; int count = GetNumAbsoluteTags( PLAYBACK ); if ( count != GetNumAbsoluteTags( ORIGINAL ) ) { return t; } if ( count <= 0 ) { return t; } if ( t <= 0.0f ) return 0.0f; float s = 0.0f, n = 0.0f; // find what tags this is between int i; for ( i = -1 ; i < count; i++ ) { s = GetBoundedAbsoluteTagPercentage( PLAYBACK, i ); n = GetBoundedAbsoluteTagPercentage( PLAYBACK, i + 1 ); if ( t >= s && t <= n ) { break; } } int prev = i - 1; int start = i; int end = i + 1; int next = i + 2; prev = MAX( -2, prev ); start = MAX( -1, start ); end = MIN( end, count ); next = MIN( next, count + 1 ); CEventAbsoluteTag *pStartTag = NULL; CEventAbsoluteTag *pEndTag = NULL; // check for linear portion of lookup if (start >= 0 && start < count) { pStartTag = GetAbsoluteTag( PLAYBACK, start ); } if (end >= 0 && end < count) { pEndTag = GetAbsoluteTag( PLAYBACK, end ); } if (pStartTag && pEndTag) { if (pStartTag->GetLinear() && pEndTag->GetLinear()) { CEventAbsoluteTag *pOrigStartTag = GetAbsoluteTag( ORIGINAL, start ); CEventAbsoluteTag *pOrigEndTag = GetAbsoluteTag( ORIGINAL, end ); if (pOrigStartTag && pOrigEndTag) { s = ( t - pStartTag->GetPercentage() ) / (pEndTag->GetPercentage() - pStartTag->GetPercentage()); return (1 - s) * pOrigStartTag->GetPercentage() + s * pOrigEndTag->GetPercentage(); } } } float dt = n - s; Vector vPre( GetBoundedAbsoluteTagPercentage( PLAYBACK, prev ), GetBoundedAbsoluteTagPercentage( ORIGINAL, prev ), 0 ); Vector vStart( GetBoundedAbsoluteTagPercentage( PLAYBACK, start ), GetBoundedAbsoluteTagPercentage( ORIGINAL, start ), 0 ); Vector vEnd( GetBoundedAbsoluteTagPercentage( PLAYBACK, end ), GetBoundedAbsoluteTagPercentage( ORIGINAL, end ), 0 ); Vector vNext( GetBoundedAbsoluteTagPercentage( PLAYBACK, next ), GetBoundedAbsoluteTagPercentage( ORIGINAL, next ), 0 ); // simulate sections of either side of "linear" portion of ramp as linear slope if (pStartTag && pStartTag->GetLinear()) { vPre.Init( vStart.x - (vEnd.x - vStart.x), vStart.y - (vEnd.y - vStart.y), 0 ); } if (pEndTag && pEndTag->GetLinear()) { vNext.Init( vEnd.x + (vEnd.x - vStart.x), vEnd.y + (vEnd.y - vStart.y), 0 ); } float f2 = 0.0f; if ( dt > 0.0f ) { f2 = ( t - s ) / ( dt ); } f2 = clamp( f2, 0.0f, 1.0f ); Vector vOut; Catmull_Rom_Spline_NormalizeX( vPre, vStart, vEnd, vNext, f2, vOut ); return vOut.y; /* float duration; GetGestureSequenceDuration( duration ); float retval = clamp( vOut.y, 0.0f, duration ); return retval; */ } //----------------------------------------------------------------------------- // Purpose: // Input : t - // Output : float //----------------------------------------------------------------------------- float CChoreoEvent::GetPlaybackPercentageFromOriginalPercentage( float t ) { Assert( GetType() == GESTURE ); if ( GetType() != GESTURE ) return t; int count = GetNumAbsoluteTags( PLAYBACK ); if ( count != GetNumAbsoluteTags( ORIGINAL ) ) { return t; } if ( count <= 0 ) { return t; } if ( t <= 0.0f ) return 0.0f; float s = 0.0f, n = 0.0f; // find what tags this is between int i; for ( i = -1 ; i < count; i++ ) { s = GetBoundedAbsoluteTagPercentage( PLAYBACK, i ); n = GetBoundedAbsoluteTagPercentage( PLAYBACK, i + 1 ); if ( t >= s && t <= n ) { break; } } int prev = i - 1; int start = i; int end = i + 1; int next = i + 2; prev = MAX( -2, prev ); start = MAX( -1, start ); end = MIN( end, count ); next = MIN( next, count + 1 ); CEventAbsoluteTag *pStartTag = NULL; CEventAbsoluteTag *pEndTag = NULL; // check for linear portion of lookup if (start >= 0 && start < count) { pStartTag = GetAbsoluteTag( ORIGINAL, start ); } if (end >= 0 && end < count) { pEndTag = GetAbsoluteTag( ORIGINAL, end ); } // check for linear portion of lookup if (pStartTag && pEndTag) { if (pStartTag->GetLinear() && pEndTag->GetLinear()) { CEventAbsoluteTag *pPlaybackStartTag = GetAbsoluteTag( PLAYBACK, start ); CEventAbsoluteTag *pPlaybackEndTag = GetAbsoluteTag( PLAYBACK, end ); if (pPlaybackStartTag && pPlaybackEndTag) { s = ( t - pStartTag->GetPercentage() ) / (pEndTag->GetPercentage() - pStartTag->GetPercentage()); return (1 - s) * pPlaybackStartTag->GetPercentage() + s * pPlaybackEndTag->GetPercentage(); } } } float dt = n - s; Vector vPre( GetBoundedAbsoluteTagPercentage( ORIGINAL, prev ), GetBoundedAbsoluteTagPercentage( PLAYBACK, prev ), 0 ); Vector vStart( GetBoundedAbsoluteTagPercentage( ORIGINAL, start ), GetBoundedAbsoluteTagPercentage( PLAYBACK, start ), 0 ); Vector vEnd( GetBoundedAbsoluteTagPercentage( ORIGINAL, end ), GetBoundedAbsoluteTagPercentage( PLAYBACK, end ), 0 ); Vector vNext( GetBoundedAbsoluteTagPercentage( ORIGINAL, next ), GetBoundedAbsoluteTagPercentage( PLAYBACK, next ), 0 ); // simulate sections of either side of "linear" portion of ramp as linear slope if (pStartTag && pStartTag->GetLinear()) { vPre.Init( vStart.x - (vEnd.x - vStart.x), vStart.y - (vEnd.y - vStart.y), 0 ); } if (pEndTag && pEndTag->GetLinear()) { vNext.Init( vEnd.x + (vEnd.x - vStart.x), vEnd.y + (vEnd.y - vStart.y), 0 ); } float f2 = 0.0f; if ( dt > 0.0f ) { f2 = ( t - s ) / ( dt ); } f2 = clamp( f2, 0.0f, 1.0f ); Vector vOut; Catmull_Rom_Spline_NormalizeX( vPre, vStart, vEnd, vNext, f2, vOut ); return vOut.y; /* float duration; GetGestureSequenceDuration( duration ); float retval = clamp( vOut.y, 0.0f, duration ); return retval; */ } //----------------------------------------------------------------------------- // Purpose: // Input : duration - //----------------------------------------------------------------------------- void CChoreoEvent::SetGestureSequenceDuration( float duration ) { m_flGestureSequenceDuration = duration; } //----------------------------------------------------------------------------- // Purpose: // Input : duration - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CChoreoEvent::GetGestureSequenceDuration( float& duration ) { bool valid = m_flGestureSequenceDuration != 0.0f; if ( !valid ) { duration = GetDuration(); } else { duration = m_flGestureSequenceDuration; } return valid; } //----------------------------------------------------------------------------- // Purpose: // Input : pitch - //----------------------------------------------------------------------------- int CChoreoEvent::GetPitch( void ) const { return m_nPitch; } //----------------------------------------------------------------------------- // Purpose: // Input : pitch - //----------------------------------------------------------------------------- void CChoreoEvent::SetPitch( int pitch ) { m_nPitch = pitch; } //----------------------------------------------------------------------------- // Purpose: // Input : yaw - //----------------------------------------------------------------------------- int CChoreoEvent::GetYaw( void ) const { return m_nYaw; } //----------------------------------------------------------------------------- // Purpose: // Input : yaw - //----------------------------------------------------------------------------- void CChoreoEvent::SetYaw( int yaw ) { m_nYaw = yaw; } //----------------------------------------------------------------------------- // Purpose: // Input : t - // -1 - //----------------------------------------------------------------------------- void CChoreoEvent::SetLoopCount( int numloops ) { Assert( GetType() == LOOP ); // Never below -1 m_nNumLoops = MAX( numloops, -1 ); } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int CChoreoEvent::GetNumLoopsRemaining( void ) { Assert( GetType() == LOOP ); return m_nLoopsRemaining; } //----------------------------------------------------------------------------- // Purpose: // Input : loops - //----------------------------------------------------------------------------- void CChoreoEvent::SetNumLoopsRemaining( int loops ) { Assert( GetType() == LOOP ); m_nLoopsRemaining = loops; } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int CChoreoEvent::GetLoopCount( void ) { Assert( GetType() == LOOP ); return m_nNumLoops; } EdgeInfo_t *CCurveData::GetEdgeInfo( int idx ) { return &m_RampEdgeInfo[ idx ]; } int CCurveData::GetCount( void ) { return m_Ramp.Count(); } CExpressionSample *CCurveData::Get( int index ) { if ( index < 0 || index >= GetCount() ) return NULL; return &m_Ramp[ index ]; } CExpressionSample *CCurveData::Add( float time, float value, bool selected ) { CExpressionSample sample; sample.time = time; sample.value = value; sample.selected = selected; int idx = m_Ramp.AddToTail( sample ); return &m_Ramp[ idx ]; } void CCurveData::Delete( int index ) { if ( index < 0 || index >= GetCount() ) return; m_Ramp.Remove( index ); } void CCurveData::Clear( void ) { m_Ramp.RemoveAll(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CCurveData::Resort( ICurveDataAccessor *data ) { for ( int i = 0; i < m_Ramp.Size(); i++ ) { for ( int j = i + 1; j < m_Ramp.Size(); j++ ) { CExpressionSample src = m_Ramp[ i ]; CExpressionSample dest = m_Ramp[ j ]; if ( src.time > dest.time ) { m_Ramp[ i ] = dest; m_Ramp[ j ] = src; } } } RemoveOutOfRangeSamples( data ); // m_RampAccumulator.RemoveAll(); } //----------------------------------------------------------------------------- // Purpose: // Input : number - // Output : CExpressionSample //----------------------------------------------------------------------------- CExpressionSample *CCurveData::GetBoundedSample( ICurveDataAccessor *data, int number, bool& bClamped ) { // Search for two samples which span time f if ( number < 0 ) { static CExpressionSample nullstart; nullstart.time = 0.0f; nullstart.value = GetEdgeZeroValue( true ); nullstart.SetCurveType( GetEdgeCurveType( true ) ); bClamped = true; return &nullstart; } else if ( number >= GetCount() ) { static CExpressionSample nullend; nullend.time = data->GetDuration(); nullend.value = GetEdgeZeroValue( false ); nullend.SetCurveType( GetEdgeCurveType( false ) ); bClamped = true; return &nullend; } bClamped = false; return Get( number ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CCurveData::RemoveOutOfRangeSamples( ICurveDataAccessor *data ) { float duration = data->GetDuration(); int c = GetCount(); for ( int i = c-1; i >= 0; i-- ) { CExpressionSample src = m_Ramp[ i ]; if ( src.time < 0 || src.time > duration + 0.01 ) { m_Ramp.Remove( i ); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CChoreoEvent::RescaleGestureTimes( float newstart, float newend, bool bMaintainAbsoluteTagPositions ) { if ( GetType() != CChoreoEvent::GESTURE ) return; // Did it actually change if ( newstart == GetStartTime() && newend == GetEndTime() ) { return; } float newduration = newend - newstart; float dt = 0.0f; //If the end is moving, leave tags stay where they are (dt == 0.0f) if ( newstart != GetStartTime() ) { // Otherwise, if the new start is later, then tags need to be shifted backwards dt -= ( newstart - GetStartTime() ); } if ( bMaintainAbsoluteTagPositions ) { int i; int count = GetNumAbsoluteTags( CChoreoEvent::PLAYBACK ); for ( i = 0; i < count; i++ ) { CEventAbsoluteTag *tag = GetAbsoluteTag( CChoreoEvent::PLAYBACK, i ); float tagtime = tag->GetPercentage() * GetDuration(); tagtime += dt; tagtime = clamp( tagtime / newduration, 0.0f, 1.0f ); tag->SetPercentage( tagtime ); } } } //----------------------------------------------------------------------------- // Purpose: Make sure tags aren't co-located or out of order //----------------------------------------------------------------------------- bool CChoreoEvent::PreventTagOverlap( void ) { bool bHadOverlap = false; // FIXME: limit to single frame? float minDp = 0.01; float minP = 1.00; int count = GetNumAbsoluteTags( CChoreoEvent::PLAYBACK ); for ( int i = count - 1; i >= 0; i-- ) { CEventAbsoluteTag *tag = GetAbsoluteTag( CChoreoEvent::PLAYBACK, i ); if (tag->GetPercentage() > minP) { tag->SetPercentage( minP ); minDp = MIN( 0.01, minP / (i + 1) ); bHadOverlap = true; } else { minP = tag->GetPercentage(); } minP = MAX( minP - minDp, 0 ); } return bHadOverlap; } //----------------------------------------------------------------------------- // Purpose: // Input : type - // Output : CEventAbsoluteTag //----------------------------------------------------------------------------- CEventAbsoluteTag *CChoreoEvent::FindEntryTag( AbsTagType type ) { for ( int i = 0; i < m_AbsoluteTags[ type ].Size(); i++ ) { CEventAbsoluteTag *ptag = &m_AbsoluteTags[ type ][ i ]; if ( !ptag ) continue; if ( ptag->GetEntry() ) { return ptag; } } return NULL; } //----------------------------------------------------------------------------- // Purpose: // Input : type - // Output : CEventAbsoluteTag //----------------------------------------------------------------------------- CEventAbsoluteTag *CChoreoEvent::FindExitTag( AbsTagType type ) { for ( int i = 0; i < m_AbsoluteTags[ type ].Size(); i++ ) { CEventAbsoluteTag *ptag = &m_AbsoluteTags[ type ][ i ]; if ( !ptag ) continue; if ( ptag->GetExit() ) { return ptag; } } return NULL; } //----------------------------------------------------------------------------- // Purpose: // Input : *style - // maxlen - //----------------------------------------------------------------------------- void CChoreoEvent::GetMovementStyle( char *style, int maxlen ) { Assert( GetType() == MOVETO ); style[0] = 0; const char *in = m_Parameters2.Get(); char *out = style; while ( *in && *in != '\0' && *in != ' ' ) { if ( out - style >= maxlen - 1 ) break; *out++ = *in++; } *out = 0; } //----------------------------------------------------------------------------- // Purpose: // Input : *style - // maxlen - //----------------------------------------------------------------------------- void CChoreoEvent::GetDistanceStyle( char *style, int maxlen ) { Assert( GetType() == MOVETO ); style[0]= 0; const char *in = Q_strstr( m_Parameters2.Get(), " " ); if ( !in ) return; in++; char *out = style; while ( *in && *in != '\0' ) { if ( out - style >= maxlen - 1 ) break; *out++ = *in++; } *out = 0; } void CChoreoEvent::SetCloseCaptionType( CLOSECAPTION type ) { Assert( m_fType == SPEAK ); m_ccType = type; } CChoreoEvent::CLOSECAPTION CChoreoEvent::GetCloseCaptionType() const { Assert( m_fType == SPEAK ); return (CLOSECAPTION)m_ccType; } void CChoreoEvent::SetCloseCaptionToken( char const *token ) { Assert( m_fType == SPEAK ); Assert( token ); m_CCToken = token; } char const *CChoreoEvent::GetCloseCaptionToken() const { Assert( m_fType == SPEAK ); return m_CCToken.Get(); } bool CChoreoEvent::GetPlaybackCloseCaptionToken( char *dest, int destlen ) { dest[0] = 0; Assert( m_fType == SPEAK ); switch ( m_ccType ) { default: case CC_DISABLED: { return false; } case CC_SLAVE: { // If it's a slave, then only disable if we're not using the combined wave if ( IsUsingCombinedFile() ) { return false; } if ( m_CCToken[ 0 ] != 0 ) { Q_strncpy( dest, m_CCToken.Get(), destlen ); } else { Q_strncpy( dest, m_Parameters.Get(), destlen ); } return true; } case CC_MASTER: { // Always use the override if we're the master, otherwise always use the default // parameter if ( m_CCToken[ 0 ] != 0 ) { Q_strncpy( dest, m_CCToken.Get(), destlen ); } else { Q_strncpy( dest, m_Parameters.Get(), destlen ); } return true; } } return false; } void CChoreoEvent::SetUsingCombinedFile( bool isusing ) { Assert( m_fType == SPEAK ); m_bUsingCombinedSoundFile = isusing; } bool CChoreoEvent::IsUsingCombinedFile() const { Assert( m_fType == SPEAK ); return m_bUsingCombinedSoundFile; } void CChoreoEvent::SetRequiredCombinedChecksum( unsigned int checksum ) { Assert( m_fType == SPEAK ); m_uRequiredCombinedChecksum = checksum; } unsigned int CChoreoEvent::GetRequiredCombinedChecksum() { Assert( m_fType == SPEAK ); return m_uRequiredCombinedChecksum; } void CChoreoEvent::SetNumSlaves( int num ) { Assert( m_fType == SPEAK ); Assert( num >= 0 ); m_nNumSlaves = num; } int CChoreoEvent::GetNumSlaves() const { Assert( m_fType == SPEAK ); return m_nNumSlaves; } void CChoreoEvent::SetLastSlaveEndTime( float t ) { Assert( m_fType == SPEAK ); m_flLastSlaveEndTime = t; } float CChoreoEvent::GetLastSlaveEndTime() const { Assert( m_fType == SPEAK ); return m_flLastSlaveEndTime; } void CChoreoEvent::SetCloseCaptionTokenValid( bool valid ) { Assert( m_fType == SPEAK ); m_bCCTokenValid = valid; } bool CChoreoEvent::GetCloseCaptionTokenValid() const { Assert( m_fType == SPEAK ); return m_bCCTokenValid; } //----------------------------------------------------------------------------- // Purpose: Removes characters which can't appear in windows filenames // Input : *in - // *dest - // destlen - // Output : static void //----------------------------------------------------------------------------- static void CleanupTokenName( char const *in, char *dest, int destlen ) { char *out = dest; while ( *in && ( out - dest ) < destlen ) { if ( V_isalnum( *in ) || // lowercase, uppercase, digits and underscore are valid *in == '_' ) { *out++ = *in; } else { *out++ = '_'; // Put underscores in for bogus characters } in++; } *out = 0; } bool CChoreoEvent::ComputeCombinedBaseFileName( char *dest, int destlen, bool creategenderwildcard ) { if ( m_fType != SPEAK ) return false; if ( m_ccType != CC_MASTER ) return false; if ( GetNumSlaves() == 0 ) return false; if ( !m_pScene ) return false; char vcdpath[ 512 ]; char cleanedtoken[ MAX_CCTOKEN_STRING ]; CleanupTokenName( m_CCToken.Get(), cleanedtoken, sizeof( cleanedtoken ) ); if ( Q_strlen( cleanedtoken ) <= 0 ) return false; Q_strncpy( vcdpath, m_pScene->GetFilename(), sizeof( vcdpath ) ); Q_StripFilename( vcdpath ); Q_FixSlashes( vcdpath, '/' ); char *pvcd = vcdpath; char *offset = Q_strstr( vcdpath, "scenes" ); if ( offset ) { pvcd = offset + 6; if ( *pvcd == '/' ) { ++pvcd; } } int len = Q_strlen( pvcd ); if ( len > 0 && ( len + 1 ) < ( sizeof( vcdpath ) - 1 ) ) { pvcd[ len ] = '/'; pvcd[ len + 1 ] = 0; } Assert( !Q_strstr( pvcd, ":" ) ); if ( creategenderwildcard ) { Q_snprintf( dest, destlen, "sound/combined/%s%s_$gender.wav", pvcd, cleanedtoken ); } else { Q_snprintf( dest, destlen, "sound/combined/%s%s.wav", pvcd, cleanedtoken ); } return true; } bool CChoreoEvent::IsCombinedUsingGenderToken() const { return m_bCombinedUsingGenderToken; } void CChoreoEvent::SetCombinedUsingGenderToken( bool using_gender ) { m_bCombinedUsingGenderToken = using_gender; } int CChoreoEvent::ValidateCombinedFile() { return 0; } bool CChoreoEvent::IsSuppressingCaptionAttenuation() const { return m_bSuppressCaptionAttenuation; } void CChoreoEvent::SetSuppressingCaptionAttenuation( bool suppress ) { m_bSuppressCaptionAttenuation = suppress; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CChoreoEvent::ClearEventDependencies() { m_Dependencies.RemoveAll(); } //----------------------------------------------------------------------------- // Purpose: // Input : *other - //----------------------------------------------------------------------------- void CChoreoEvent::AddEventDependency( CChoreoEvent *other ) { if ( m_Dependencies.Find( other ) == m_Dependencies.InvalidIndex() ) { m_Dependencies.AddToTail( other ); } } //----------------------------------------------------------------------------- // Purpose: // Input : list - //----------------------------------------------------------------------------- void CChoreoEvent::GetEventDependencies( CUtlVector< CChoreoEvent * >& list ) { int c = m_Dependencies.Count(); for ( int i = 0; i < c; ++i ) { list.AddToTail( m_Dependencies[ i ] ); } } void CCurveData::SetEdgeInfo( bool leftEdge, int curveType, float zero ) { int idx = leftEdge ? 0 : 1; m_RampEdgeInfo[ idx ].m_CurveType = curveType; m_RampEdgeInfo[ idx ].m_flZeroPos = zero; } void CCurveData::GetEdgeInfo( bool leftEdge, int& curveType, float& zero ) const { int idx = leftEdge ? 0 : 1; curveType = m_RampEdgeInfo[ idx ].m_CurveType; zero = m_RampEdgeInfo[ idx ].m_flZeroPos; } void CCurveData::SetEdgeActive( bool leftEdge, bool state ) { int idx = leftEdge ? 0 : 1; m_RampEdgeInfo[ idx ].m_bActive = state; } bool CCurveData::IsEdgeActive( bool leftEdge ) const { int idx = leftEdge ? 0 : 1; return m_RampEdgeInfo[ idx ].m_bActive; } int CCurveData::GetEdgeCurveType( bool leftEdge ) const { if ( !IsEdgeActive( leftEdge ) ) { return CURVE_DEFAULT; } int idx = leftEdge ? 0 : 1; return m_RampEdgeInfo[ idx ].m_CurveType; } float CCurveData::GetEdgeZeroValue( bool leftEdge ) const { if ( !IsEdgeActive( leftEdge ) ) { return 0.0f; } int idx = leftEdge ? 0 : 1; return m_RampEdgeInfo[ idx ].m_flZeroPos; } void CChoreoEvent::SaveToBuffer( CUtlBuffer& buf, CChoreoScene *pScene, IChoreoStringPool *pStringPool ) { buf.PutChar( GetType() ); buf.PutShort( pStringPool->FindOrAddString( GetName() ) ); float st = GetStartTime(); buf.PutFloat( st ); float et = GetEndTime(); buf.PutFloat( et ); buf.PutShort( pStringPool->FindOrAddString( GetParameters() ) ); buf.PutShort( pStringPool->FindOrAddString( GetParameters2() ) ); buf.PutShort( pStringPool->FindOrAddString( GetParameters3() ) ); m_Ramp.SaveToBuffer( buf, pStringPool ); int flags = 0; flags |= IsResumeCondition() ? 1<<0 : 0; flags |= IsLockBodyFacing() ? 1<<1 : 0; flags |= IsFixedLength() ? 1<<2 : 0; flags |= GetActive() ? 1<<3 : 0; flags |= GetForceShortMovement() ? 1<<4 : 0; flags |= GetPlayOverScript() ? 1<<5 : 0; buf.PutUnsignedChar( flags ); buf.PutFloat( GetDistanceToTarget() ); int numRelativeTags = GetNumRelativeTags(); Assert( numRelativeTags <= 255 ); buf.PutUnsignedChar( numRelativeTags ); for ( int t = 0; t < numRelativeTags; t++ ) { CEventRelativeTag *rt = GetRelativeTag( t ); Assert( rt ); buf.PutShort( pStringPool->FindOrAddString( rt->GetName() ) ); Assert( rt->GetPercentage() >= 0.0f && rt->GetPercentage() <= 1.0f ); unsigned char p = rt->GetPercentage() * 255.0f; buf.PutUnsignedChar( p ); } int numTimingTags = GetNumTimingTags(); Assert( numTimingTags <= 255 ); buf.PutUnsignedChar( numTimingTags ); for ( int t = 0; t < numTimingTags; t++ ) { CFlexTimingTag *tt = GetTimingTag( t ); Assert( tt ); buf.PutShort( pStringPool->FindOrAddString( tt->GetName() ) ); // save as u0.8 Assert( tt->GetPercentage() >= 0.0f && tt->GetPercentage() <= 1.0f ); unsigned char p = tt->GetPercentage() * 255.0f; buf.PutUnsignedChar( p ); // Don't save locked state, it's only used by the editor tt->GetLocked() } int tagtype; for ( tagtype = 0; tagtype < CChoreoEvent::NUM_ABS_TAG_TYPES; tagtype++ ) { int num = GetNumAbsoluteTags( (CChoreoEvent::AbsTagType)tagtype ); Assert( num <= 255 ); buf.PutUnsignedChar( num ); for ( int i = 0; i < num ; ++i ) { CEventAbsoluteTag *abstag = GetAbsoluteTag( (CChoreoEvent::AbsTagType)tagtype, i ); Assert( abstag ); buf.PutShort( pStringPool->FindOrAddString( abstag->GetName() ) ); // save as u4.12 Assert( abstag->GetPercentage() >= 0.0f && abstag->GetPercentage() <= 15.0f ); unsigned short p = abstag->GetPercentage() * 4096.0f; buf.PutUnsignedShort( p ); } } if ( GetType() == CChoreoEvent::GESTURE ) { float duration; if ( GetGestureSequenceDuration( duration ) ) { buf.PutFloat( duration ); } else { buf.PutFloat( -1.0f ); } } buf.PutChar( IsUsingRelativeTag() ? 1 : 0 ); if ( IsUsingRelativeTag() ) { buf.PutShort( pStringPool->FindOrAddString( GetRelativeTagName() ) ); buf.PutShort( pStringPool->FindOrAddString( GetRelativeWavName() ) ); } SaveFlexAnimationsToBuffer( buf, pStringPool ); if ( GetType() == LOOP ) { buf.PutChar( GetLoopCount() ); } if ( GetType() == CChoreoEvent::SPEAK ) { buf.PutChar( GetCloseCaptionType() ); buf.PutShort( pStringPool->FindOrAddString( GetCloseCaptionToken() ) ); flags = 0; if ( GetCloseCaptionType() != CChoreoEvent::CC_DISABLED && IsUsingCombinedFile() ) { flags |= ( 1<<0 ); } if ( IsCombinedUsingGenderToken() ) { flags |= ( 1<<1 ); } if ( IsSuppressingCaptionAttenuation() ) { flags |= ( 1<<2 ); } buf.PutChar( flags ); } } bool CChoreoEvent::RestoreFromBuffer( CUtlBuffer& buf, CChoreoScene *pScene, IChoreoStringPool *pStringPool ) { MEM_ALLOC_CREDIT(); SetType( (EVENTTYPE)buf.GetChar() ); char sz[ 256 ]; pStringPool->GetString( buf.GetShort(), sz, sizeof( sz ) ); SetName( sz ); SetStartTime( buf.GetFloat() ); SetEndTime( buf.GetFloat() ); char params[ 2048 ]; pStringPool->GetString( buf.GetShort(), params, sizeof( params ) ); SetParameters( params ); pStringPool->GetString( buf.GetShort(), params, sizeof( params ) ); SetParameters2( params ); pStringPool->GetString( buf.GetShort(), params, sizeof( params ) ); SetParameters3( params ); if ( !m_Ramp.RestoreFromBuffer( buf, pStringPool ) ) return false; int flags = buf.GetUnsignedChar(); SetResumeCondition( ( flags & ( 1<<0 ) ) ? true : false ); SetLockBodyFacing( ( flags & ( 1<<1 ) ) ? true : false ); SetFixedLength( ( flags & ( 1<<2 ) ) ? true : false ); SetActive( ( flags & ( 1<<3 ) ) ? true : false ); SetForceShortMovement( ( flags & ( 1<<4 ) ) ? true : false ); SetPlayOverScript( ( flags & ( 1<<5 ) ) ? true : false ); SetDistanceToTarget( buf.GetFloat() ); int numRelTags = buf.GetUnsignedChar(); for ( int i = 0; i < numRelTags; ++i ) { char tagName[ 256 ]; pStringPool->GetString( buf.GetShort(), tagName, sizeof( tagName ) ); float percentage = (float)buf.GetUnsignedChar() * 1.0f/255.0f; AddRelativeTag( tagName, percentage ); } int numTimingTags = buf.GetUnsignedChar(); for ( int i = 0; i < numTimingTags; ++i ) { char tagName[ 256 ]; pStringPool->GetString( buf.GetShort(), tagName, sizeof( tagName ) ); float percentage = (float)buf.GetUnsignedChar() * 1.0f/255.0f; // Don't parse locked state, only used by editors AddTimingTag( tagName, percentage, false ); } int tagtype; for ( tagtype = 0; tagtype < CChoreoEvent::NUM_ABS_TAG_TYPES; tagtype++ ) { int num = buf.GetUnsignedChar(); for ( int i = 0; i < num; ++i ) { char tagName[ 256 ]; pStringPool->GetString( buf.GetShort(), tagName, sizeof( tagName ) ); float percentage = (float)buf.GetUnsignedShort() * 1.0f/4096.0f; // Don't parse locked state, only used by editors AddAbsoluteTag( (CChoreoEvent::AbsTagType)tagtype, tagName, percentage ); } } if ( GetType() == CChoreoEvent::GESTURE ) { float duration = buf.GetFloat(); if ( duration != -1 ) { SetGestureSequenceDuration( duration ); } } if ( buf.GetChar() == 1 ) { char tagname[ 256 ]; char wavname[ 256 ]; pStringPool->GetString( buf.GetShort(), tagname, sizeof( tagname ) ); pStringPool->GetString( buf.GetShort(), wavname, sizeof( wavname ) ); SetUsingRelativeTag( true, tagname, wavname ); } if ( !RestoreFlexAnimationsFromBuffer( buf, pStringPool ) ) return false; if ( GetType() == LOOP ) { SetLoopCount( buf.GetChar() ); } if ( GetType() == CChoreoEvent::SPEAK ) { SetCloseCaptionType( (CLOSECAPTION)buf.GetChar() ); char cctoken[ 256 ]; pStringPool->GetString( buf.GetShort(), cctoken, sizeof( cctoken ) ); SetCloseCaptionToken( cctoken ); int flags = buf.GetChar(); if ( flags & ( 1<<0 ) ) { SetUsingCombinedFile( true ); } if ( flags & ( 1<<1 ) ) { SetCombinedUsingGenderToken( true ); } if ( flags & ( 1<<2 ) ) { SetSuppressingCaptionAttenuation( true ); } } return true; } void CCurveData::SaveToBuffer( CUtlBuffer& buf, IChoreoStringPool *pStringPool ) { int c = GetCount(); Assert( c <= 255 ); buf.PutUnsignedChar( c ); for ( int i = 0; i < c; i++ ) { CExpressionSample *sample = Get( i ); buf.PutFloat( sample->time ); Assert( sample->value >= 0.0f && sample->value <= 1.0f ); unsigned char v = sample->value * 255.0f; buf.PutUnsignedChar( v ); } } bool CCurveData::RestoreFromBuffer( CUtlBuffer& buf, IChoreoStringPool *pStringPool ) { int c = buf.GetUnsignedChar(); for ( int i = 0; i < c; i++ ) { float t, v; t = buf.GetFloat(); v = (float)buf.GetUnsignedChar() * 1.0f/255.0f; Add( t, v, false ); } return true; } void CChoreoEvent::SaveFlexAnimationsToBuffer( CUtlBuffer& buf, IChoreoStringPool *pStringPool ) { int numFlexAnimationTracks = GetNumFlexAnimationTracks(); Assert( numFlexAnimationTracks <= 255 ); buf.PutUnsignedChar( numFlexAnimationTracks ); for ( int i = 0; i < numFlexAnimationTracks; i++ ) { CFlexAnimationTrack *track = GetFlexAnimationTrack( i ); buf.PutShort( pStringPool->FindOrAddString( track->GetFlexControllerName() ) ); int flags = 0; flags |= track->IsTrackActive() ? 1<<0 : 0; flags |= track->IsComboType() ? 1<<1 : 0; buf.PutUnsignedChar( flags ); buf.PutFloat( track->GetMin() ); buf.PutFloat( track->GetMax() ); buf.PutShort( track->GetNumSamples( 0 ) ); for ( int j = 0 ; j < track->GetNumSamples( 0 ) ; j++ ) { CExpressionSample *s = track->GetSample( j, 0 ); if ( !s ) continue; buf.PutFloat( s->time ); Assert( s->value >= 0.0f && s->value <= 1.0f ); unsigned char v = s->value * 255.0f; buf.PutUnsignedChar( v ); buf.PutUnsignedShort( s->GetCurveType() ); } // Write out combo samples if ( track->IsComboType() ) { int numSamples = track->GetNumSamples( 1 ); Assert( numSamples <= 32767 ); buf.PutUnsignedShort( numSamples ); for ( int j = 0; j < numSamples; j++ ) { CExpressionSample *s = track->GetSample( j, 1 ); if ( !s ) continue; buf.PutFloat( s->time ); Assert( s->value >= 0.0f && s->value <= 1.0f ); unsigned char v = s->value * 255.0f; buf.PutUnsignedChar( v ); buf.PutUnsignedShort( s->GetCurveType() ); } } } } bool CChoreoEvent::RestoreFlexAnimationsFromBuffer( CUtlBuffer& buf, IChoreoStringPool *pStringPool ) { int numTracks = buf.GetUnsignedChar(); for ( int i = 0; i < numTracks; i++ ) { char name[ 256 ]; pStringPool->GetString( buf.GetShort(), name, sizeof( name ) ); CFlexAnimationTrack *track = AddTrack( name ); int flags = buf.GetUnsignedChar(); track->SetTrackActive( ( flags & ( 1<<0 ) ) ? true : false ); track->SetComboType( ( flags & ( 1<<1 ) ) ? true : false ); track->SetMin( buf.GetFloat() ); track->SetMax( buf.GetFloat() ); int s = buf.GetShort(); for ( int j = 0; j < s; ++j ) { float t, v; t = buf.GetFloat(); v = (float)buf.GetUnsignedChar() * 1.0f/255.0f; CExpressionSample *pSample = track->AddSample( t, v, 0 ); pSample->SetCurveType( buf.GetUnsignedShort() ); } if ( track->IsComboType() ) { int s = buf.GetUnsignedShort(); for ( int j = 0; j < s; ++j ) { float t, v; t = buf.GetFloat(); v = (float)buf.GetUnsignedChar() * 1.0f/255.0f; CExpressionSample *pSample = track->AddSample( t, v, 1 ); pSample->SetCurveType( buf.GetUnsignedShort() ); } } } return true; } //----------------------------------------------------------------------------- // Purpose: Marks the event as enabled/disabled // Input : state - //----------------------------------------------------------------------------- void CChoreoEvent::SetActive( bool state ) { m_bActive = state; } bool CChoreoEvent::GetActive() const { return m_bActive; }
26.842082
176
0.459494
Planimeter
40de540be43e454c19ddb6c11050259be9da9466
7,760
cpp
C++
root/stat.cpp
amcghie/watchman
27ed35666681a48df42fc9a22f863fa99a2e1c85
[ "Apache-2.0" ]
null
null
null
root/stat.cpp
amcghie/watchman
27ed35666681a48df42fc9a22f863fa99a2e1c85
[ "Apache-2.0" ]
2
2020-02-27T11:22:22.000Z
2021-05-20T10:23:12.000Z
root/stat.cpp
amcghie/watchman
27ed35666681a48df42fc9a22f863fa99a2e1c85
[ "Apache-2.0" ]
null
null
null
/* Copyright 2012-present Facebook, Inc. * Licensed under the Apache License, Version 2.0 */ #include "watchman.h" #include "InMemoryView.h" #include "watchman_error_category.h" namespace watchman { void InMemoryView::statPath( const std::shared_ptr<w_root_t>& root, SyncView::LockedPtr& view, PendingCollection::LockedPtr& coll, const w_string& full_path, struct timeval now, int flags, const watchman_dir_ent* pre_stat) { watchman::FileInformation st; std::error_code errcode; char path[WATCHMAN_NAME_MAX]; bool recursive = flags & W_PENDING_RECURSIVE; bool via_notify = flags & W_PENDING_VIA_NOTIFY; if (root->ignore.isIgnoreDir(full_path)) { w_log( W_LOG_DBG, "%.*s matches ignore_dir rules\n", int(full_path.size()), full_path.data()); return; } if (full_path.size() > sizeof(path) - 1) { w_log( W_LOG_FATAL, "path %.*s is too big\n", int(full_path.size()), full_path.data()); } memcpy(path, full_path.data(), full_path.size()); path[full_path.size()] = 0; auto dir_name = full_path.dirName(); auto file_name = full_path.baseName(); auto parentDir = resolveDir(view, dir_name, true); auto file = parentDir->getChildFile(file_name); auto dir_ent = parentDir->getChildDir(file_name); if (pre_stat && pre_stat->has_stat) { st = pre_stat->stat; } else { try { st = getFileInformation(path, root->case_sensitive); log(DBG, "getFileInformation(", path, ") file=", file, " dir=", dir_ent, "\n"); } catch (const std::system_error &exc) { errcode = exc.code(); log(DBG, "getFileInformation(", path, ") file=", file, " dir=", dir_ent, " failed: ", exc.what(), "\n"); } } if (errcode == watchman::error_code::no_such_file_or_directory || errcode == watchman::error_code::not_a_directory) { /* it's not there, update our state */ if (dir_ent) { markDirDeleted(view, dir_ent, now, true); watchman::log( watchman::DBG, "getFileInformation(", path, ") -> ", errcode.message(), " so stopping watch\n"); } if (file) { if (file->exists) { watchman::log( watchman::DBG, "getFileInformation(", path, ") -> ", errcode.message(), " so marking ", file->getName(), " deleted\n"); file->exists = false; markFileChanged(view, file, now); } } else { // It was created and removed before we could ever observe it // in the filesystem. We need to generate a deleted file // representation of it now, so that subscription clients can // be notified of this event file = getOrCreateChildFile(view, parentDir, file_name, now); log(DBG, "getFileInformation(", path, ") -> ", errcode.message(), " and file node was NULL. " "Generating a deleted node.\n"); file->exists = false; markFileChanged(view, file, now); } if (root->case_sensitive == CaseSensitivity::CaseInSensitive && !w_string_equal(dir_name, root->root_path) && parentDir->last_check_existed) { /* If we rejected the name because it wasn't canonical, * we need to ensure that we look in the parent dir to discover * the new item(s) */ w_log( W_LOG_DBG, "we're case insensitive, and %s is ENOENT, " "speculatively look at parent dir %.*s\n", path, int(dir_name.size()), dir_name.data()); coll->add(dir_name, now, W_PENDING_CRAWL_ONLY); } } else if (errcode.value()) { log(ERR, "getFileInformation(", path, ") failed and not handled! -> ", errcode.message(), " value=", errcode.value(), " category=", errcode.category().name(), "\n"); } else { if (!file) { file = getOrCreateChildFile(view, parentDir, file_name, now); } if (!file->exists) { /* we're transitioning from deleted to existing, * so we're effectively new again */ file->ctime.ticks = view->mostRecentTick; file->ctime.timestamp = now.tv_sec; /* if a dir was deleted and now exists again, we want * to crawl it again */ recursive = true; } if (!file->exists || via_notify || did_file_change(&file->stat, &st)) { w_log( W_LOG_DBG, "file changed exists=%d via_notify=%d stat-changed=%d isdir=%d %s\n", (int)file->exists, (int)via_notify, (int)(file->exists && !via_notify), st.isDir(), path); file->exists = true; markFileChanged(view, file, now); } memcpy(&file->stat, &st, sizeof(file->stat)); // check for symbolic link if (st.isSymlink()) { try { auto target = readSymbolicLink(path); bool symlink_changed = false; if (file->symlink_target != target) { symlink_changed = true; } file->symlink_target = target; if (symlink_changed && root->config.getBool("watch_symlinks", false)) { root->inner.pending_symlink_targets.wlock()->add(full_path, now, 0); } } catch (const std::system_error& exc) { log(ERR, "readlink(", path, ") failed: ", exc.what(), "\n"); file->symlink_target.reset(); } } else { file->symlink_target.reset(); } if (st.isDir()) { if (dir_ent == NULL) { recursive = true; } else { // Ensure that we believe that this node exists dir_ent->last_check_existed = true; } // Don't recurse if our parent is an ignore dir if (!root->ignore.isIgnoreVCS(dir_name) || // but do if we're looking at the cookie dir (stat_path is never // called for the root itself) w_string_equal(full_path, root->cookies.cookieDir())) { if (!(watcher_->flags & WATCHER_HAS_PER_FILE_NOTIFICATIONS)) { /* we always need to crawl, but may not need to be fully recursive */ coll->add( full_path, now, W_PENDING_CRAWL_ONLY | (recursive ? W_PENDING_RECURSIVE : 0)); } else { /* we get told about changes on the child, so we only * need to crawl if we've never seen the dir before. * An exception is that fsevents will only report the root * of a dir rename and not a rename event for all of its * children. */ if (recursive) { coll->add( full_path, now, W_PENDING_RECURSIVE | W_PENDING_CRAWL_ONLY); } } } } else if (dir_ent) { // We transitioned from dir to file (see fishy.php), so we should prune // our former tree here markDirDeleted(view, dir_ent, now, true); } if ((watcher_->flags & WATCHER_HAS_PER_FILE_NOTIFICATIONS) && !st.isDir() && !w_string_equal(dir_name, root->root_path) && parentDir->last_check_existed) { /* Make sure we update the mtime on the parent directory. * We're deliberately not propagating any of the flags through; we * definitely don't want this to be a recursive evaluation and we * won'd want to treat this as VIA_NOTIFY to avoid spuriously * marking the node as changed when only its atime was changed. * https://github.com/facebook/watchman/issues/305 and * https://github.com/facebook/watchman/issues/307 have more * context on why this is. */ coll->add(dir_name, now, 0); } } } } /* vim:ts=2:sw=2:et: */
32.605042
80
0.581959
amcghie
40e23dda4ca58a0ffe1944e246c378314124fa2a
15,458
cpp
C++
CPUT/CPUT/CPUTModelOGL.cpp
GameTechDev/OpenGLESTessellation
b504ec95be716d1671dd55a61aa142d0c133fd1b
[ "Apache-2.0" ]
13
2016-03-06T12:05:52.000Z
2021-07-24T21:17:46.000Z
CPUT/CPUT/CPUTModelOGL.cpp
GameTechDev/OpenGLESTessellation
b504ec95be716d1671dd55a61aa142d0c133fd1b
[ "Apache-2.0" ]
null
null
null
CPUT/CPUT/CPUTModelOGL.cpp
GameTechDev/OpenGLESTessellation
b504ec95be716d1671dd55a61aa142d0c133fd1b
[ "Apache-2.0" ]
8
2016-05-06T14:08:44.000Z
2022-03-17T09:37:20.000Z
///////////////////////////////////////////////////////////////////////////////////////////// // Copyright 2017 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 "CPUTModelOGL.h" #include "CPUTMaterialEffectOGL.h" #include "CPUTFrustum.h" #include "CPUTAssetLibraryOGL.h" #include "CPUTTextureOGL.h" DrawModelCallBackFunc CPUTModel::mDrawModelCallBackFunc = CPUTModelOGL::DrawModelCallBack; //----------------------------------------------------------------------------- CPUTMeshOGL* CPUTModelOGL::GetMesh(const UINT index) const { return ( 0==mMeshCount || index > mMeshCount) ? NULL : (CPUTMeshOGL*)mpMesh[index]; } // Set the render state before drawing this object //----------------------------------------------------------------------------- void CPUTModelOGL::UpdateShaderConstants(CPUTRenderParameters &renderParams) { float4x4 world(*GetWorldMatrix()); float4x4 NormalMatrix(*GetWorldMatrix()); //Local transform if node baked into animation if(mSkeleton && mpCurrentAnimation) { world = GetParentsWorldMatrix(); NormalMatrix = GetParentsWorldMatrix(); } if( renderParams.mpPerModelConstants ) { CPUTBufferOGL *pBuffer = (CPUTBufferOGL*)(renderParams.mpPerModelConstants); CPUTModelConstantBuffer cb; cb.World = world; cb.InverseWorld = cb.World; cb.InverseWorld.invert(); CPUTCamera *pCamera = renderParams.mpCamera; if(pCamera) { cb.WorldViewProjection = cb.World * *pCamera->GetViewMatrix() * *pCamera->GetProjectionMatrix(); } float4x4 shadowView, shadowProjection; CPUTCamera *pShadowCamera = gpSample->GetShadowCamera(); if( pShadowCamera ) { shadowView = *pShadowCamera->GetViewMatrix(); shadowProjection = *pShadowCamera->GetProjectionMatrix(); cb.LightWorldViewProjection = cb.World * shadowView * shadowProjection; } cb.BoundingBoxCenterWorldSpace = float4(mBoundingBoxCenterWorldSpace, 0); cb.BoundingBoxHalfWorldSpace = float4(mBoundingBoxHalfWorldSpace, 0); cb.BoundingBoxCenterObjectSpace = float4(mBoundingBoxCenterObjectSpace, 0); cb.BoundingBoxHalfObjectSpace = float4(mBoundingBoxHalfObjectSpace, 0); //TODO: Should this process if object not visible? //Only do this if Model has a skin and is animated if(mSkeleton && mpCurrentAnimation) { ASSERT(0, _L("Skinning constant buffer temporarily disabled")); //ASSERT(mSkeleton->mNumberOfJoints < 255, _L("Skin Exceeds maximum number of allowable joints: 255")); //for(UINT i = 0; i < mSkeleton->mNumberOfJoints; ++i) //{ // CPUTJoint *pJoint = &mSkeleton->mJointsList[i]; // cb.SkinMatrix[i] = pJoint->mInverseBindPoseMatrix * pJoint->mScaleMatrix * pJoint->mRTMatrix; // float4x4 skinNormalMatrix = cb.SkinMatrix[i]; // skinNormalMatrix.invert(); skinNormalMatrix.transpose(); // cb.SkinNormalMatrix[i] = skinNormalMatrix; //} } #ifndef CPUT_FOR_OGLES2 pBuffer->SetSubData(0, sizeof(CPUTModelConstantBuffer), &cb); #else #warning "Need to do something with uniform buffers here" #endif } } // Render - render this model (only) //----------------------------------------------------------------------------- void CPUTModelOGL::Render(CPUTRenderParameters &renderParams, int materialIndex) { UpdateShaderConstants(renderParams); // loop over all meshes in this model and draw them for(UINT ii=0; ii<mMeshCount; ii++) { UINT finalMaterialIndex = GetMaterialIndex(ii, materialIndex); ASSERT( finalMaterialIndex < mpLayoutCount[ii], _L("material index out of range.")); CPUTMaterialEffect *pMaterialEffect = (CPUTMaterialEffect*)(mpMaterialEffect[ii][finalMaterialIndex]); mDrawModelCallBackFunc(this, renderParams, mpMesh[ii], pMaterialEffect, NULL, NULL); } } //----------------------------------------------------------------------------- // DrawModelCallBack - default model rendering code can be overridden by a callback set in user side code //----------------------------------------------------------------------------- bool CPUTModelOGL::DrawModelCallBack(CPUTModel* pModel, CPUTRenderParameters &renderParams, CPUTMesh* pMesh, CPUTMaterialEffect* pMaterial, CPUTMaterialEffect* , void* ) { pMaterial->SetRenderStates(renderParams); if( ((CPUTMaterialEffectOGL*)pMaterial)->Tessellated() ) ((CPUTMeshOGL*)pMesh)->DrawPatches(renderParams, pModel); else ((CPUTMeshOGL*)pMesh)->Draw(renderParams, pModel); return true; } #ifdef SUPPORT_DRAWING_BOUNDING_BOXES //----------------------------------------------------------------------------- void CPUTModelOGL::DrawBoundingBox(CPUTRenderParameters &renderParams) { SetRenderStates(renderParams); CPUTMaterialOGL *pMaterial = (CPUTMaterialOGL*)mpBoundingBoxMaterial; mpBoundingBoxMaterial->SetRenderStates(renderParams); ((CPUTMeshOGL*)mpBoundingBoxMesh)->Draw(renderParams, this); } #endif // Load the set file definition of this object // 1. Parse the block of name/parent/transform info for model block // 2. Load the model's binary payload (i.e., the meshes) // 3. Assert the # of meshes matches # of materials // 4. Load each mesh's material //----------------------------------------------------------------------------- CPUTResult CPUTModelOGL::LoadModel(CPUTConfigBlock *pBlock, int *pParentID, CPUTModel *pMasterModel, int numSystemMaterials, cString *pSystemMaterialNames) { CPUTResult result = CPUT_SUCCESS; CPUTAssetLibraryOGL *pAssetLibrary = (CPUTAssetLibraryOGL*)CPUTAssetLibrary::GetAssetLibrary(); cString modelSuffix = ptoc(this); // set the model's name mName = pBlock->GetValueByName(_L("name"))->ValueAsString(); mName = mName + _L(".mdl"); // resolve the full path name cString modelLocation; cString resolvedPathAndFile; modelLocation = ((CPUTAssetLibraryOGL*)CPUTAssetLibrary::GetAssetLibrary())->GetModelDirectoryName(); modelLocation = modelLocation+mName; CPUTFileSystem::ResolveAbsolutePathAndFilename(modelLocation, &resolvedPathAndFile); // Get the parent ID. Note: the caller will use this to set the parent. *pParentID = pBlock->GetValueByName(_L("parent"))->ValueAsInt(); LoadParentMatrixFromParameterBlock( pBlock ); // Get the bounding box information float3 center(0.0f), half(0.0f); pBlock->GetValueByName(_L("BoundingBoxCenter"))->ValueAsFloatArray(center.f, 3); pBlock->GetValueByName(_L("BoundingBoxHalf"))->ValueAsFloatArray(half.f, 3); mBoundingBoxCenterObjectSpace = center; mBoundingBoxHalfObjectSpace = half; mMeshCount = pBlock->GetValueByName(_L("meshcount"))->ValueAsInt(); mpMesh = new CPUTMesh*[mMeshCount]; mpLayoutCount = new UINT[mMeshCount]; mpRootMaterial = new CPUTMaterial*[mMeshCount]; memset( mpRootMaterial, 0, mMeshCount * sizeof(CPUTMaterial*) ); mpMaterialEffect = new CPUTMaterialEffect**[mMeshCount]; memset( mpMaterialEffect, 0, mMeshCount * sizeof(CPUTMaterialEffect*) ); // get the material names, load them, and match them up with each mesh cString materialName,shadowMaterialName; char pNumber[4]; cString materialValueName; CPUTModelOGL *pMasterModelDX = (CPUTModelOGL*)pMasterModel; for(UINT ii=0; ii<mMeshCount; ii++) { if(pMasterModelDX) { // Reference the master model's mesh. Don't create a new one. mpMesh[ii] = pMasterModelDX->mpMesh[ii]; mpMesh[ii]->AddRef(); } else { mpMesh[ii] = new CPUTMeshOGL(); } } if( !pMasterModelDX ) { // Not a clone/instance. So, load the model's binary payload (i.e., vertex and index buffers) // TODO: Change to use GetModel() result = LoadModelPayload(resolvedPathAndFile); ASSERT( CPUTSUCCESS(result), _L("Failed loading model") ); } cString assetSetDirectoryName = pAssetLibrary->GetAssetSetDirectoryName(); cString modelDirectory = pAssetLibrary->GetModelDirectoryName(); cString materialDirectory = pAssetLibrary->GetMaterialDirectoryName(); cString textureDirectory = pAssetLibrary->GetTextureDirectoryName(); cString shaderDirectory = pAssetLibrary->GetShaderDirectoryName(); cString fontDirectory = pAssetLibrary->GetFontDirectoryName(); cString up2MediaDirName = assetSetDirectoryName + _L("../../"); pAssetLibrary->SetMediaDirectoryName( up2MediaDirName ); // mpShadowCastMaterial = pAssetLibrary->GetMaterial( _L("shadowCast"), false ); pAssetLibrary->SetAssetSetDirectoryName( assetSetDirectoryName ); pAssetLibrary->SetModelDirectoryName( modelDirectory ); pAssetLibrary->SetMaterialDirectoryName( materialDirectory ); pAssetLibrary->SetTextureDirectoryName( textureDirectory ); pAssetLibrary->SetShaderDirectoryName( shaderDirectory ); pAssetLibrary->SetFontDirectoryName( fontDirectory ); for(UINT ii=0; ii<mMeshCount; ii++) { // get the right material number ('material0', 'material1', 'material2', etc) materialValueName = _L("material"); snprintf(pNumber, 4, "%d", ii); // _itoa(ii, pNumber, 4, 10); materialValueName.append(s2ws(pNumber)); materialName = pBlock->GetValueByName(materialValueName)->ValueAsString(); shadowMaterialName = pBlock->GetValueByName(_L("shadowCast") + materialValueName)->ValueAsString(); bool isSkinned = pBlock->GetValueByName(_L("skeleton")) != &CPUTConfigEntry::sNullConfigValue; if( shadowMaterialName.length() == 0 ) { if(!isSkinned) { shadowMaterialName = _L("%shadowCast"); } else { shadowMaterialName = _L("%shadowCastSkinned"); } } // Get/load material for this mesh UINT totalNameCount = numSystemMaterials + NUM_GLOBAL_SYSTEM_MATERIALS; cString *pFinalSystemNames = new cString[totalNameCount]; // Copy "global" system materials to caller-supplied list for( int jj=0; jj<numSystemMaterials; jj++ ) { pFinalSystemNames[jj] = pSystemMaterialNames[jj]; } pFinalSystemNames[totalNameCount + CPUT_MATERIAL_INDEX_SHADOW_CAST] = shadowMaterialName; // pFinalSystemNames[totalNameCount + CPUT_MATERIAL_INDEX_BOUNDING_BOX] = _L("%BoundingBox"); int finalNumSystemMaterials = numSystemMaterials + NUM_GLOBAL_SYSTEM_MATERIALS; CPUTMaterial *pMaterial = pAssetLibrary->GetMaterial(materialName, false, this, ii, NULL, finalNumSystemMaterials, pFinalSystemNames); ASSERT( pMaterial, _L("Couldn't find material.") ); delete []pFinalSystemNames; mpLayoutCount[ii] = pMaterial->GetMaterialEffectCount(); SetMaterial(ii, pMaterial); // Release the extra refcount we're holding from the GetMaterial operation earlier // now the asset library, and this model have the only refcounts on that material pMaterial->Release(); // Create two ID3D11InputLayout objects, one for each material. // mpMesh[ii]->BindVertexShaderLayout( mpMaterial[ii], mpShadowCastMaterial); // mpShadowCastMaterial->Release() } return result; } // Set the material associated with this mesh and create/re-use a //----------------------------------------------------------------------------- void CPUTModelOGL::SetMaterial(UINT ii, CPUTMaterial *pMaterial) { CPUTModel::SetMaterial(ii, pMaterial); // Can't bind the layout if we haven't loaded the mesh yet. CPUTMeshOGL *pMesh = (CPUTMeshOGL*)mpMesh[ii]; // D3D11_INPUT_ELEMENT_DESC *pDesc = pMesh->GetLayoutDescription(); // if( pDesc ) { // pMesh->BindVertexShaderLayout(pMaterial, mpMaterial[ii]); } } #ifdef SUPPORT_DRAWING_BOUNDING_BOXES //----------------------------------------------------------------------------- void CPUTModelOGL::DrawBoundingBox(CPUTRenderParameters &renderParams) { UpdateShaderConstants(renderParams); UINT index = mpSubMaterialCount[0] + CPUT_MATERIAL_INDEX_BOUNDING_BOX; CPUTMaterialOGL *pMaterial = (CPUTMaterialOGL*)(mpMaterial[0][index]); pMaterial->SetRenderStates(renderParams); ((CPUTMeshOGL*)mpBoundingBoxMesh)->Draw(renderParams, mpInputLayout[0][index]); } // Note that we only need one of these. We don't need to re-create it for every model. //----------------------------------------------------------------------------- void CPUTModelDX11::CreateBoundingBoxMesh() { CPUTResult result = CPUT_SUCCESS; float3 pVertices[8] = { float3( 1.0f, 1.0f, 1.0f ), // 0 float3( 1.0f, 1.0f, -1.0f ), // 1 float3( -1.0f, 1.0f, 1.0f ), // 2 float3( -1.0f, 1.0f, -1.0f ), // 3 float3( 1.0f, -1.0f, 1.0f ), // 4 float3( 1.0f, -1.0f, -1.0f ), // 5 float3( -1.0f, -1.0f, 1.0f ), // 6 float3( -1.0f, -1.0f, -1.0f ) // 7 }; USHORT pIndices[24] = { 0,1, 1,3, 3,2, 2,0, // Top 4,5, 5,7, 7,6, 6,4, // Bottom 0,4, 1,5, 2,6, 3,7 // Verticals }; CPUTVertexElementDesc pVertexElements[] = { { CPUT_VERTEX_ELEMENT_POSITON, tFLOAT, 12, 0 }, }; CPUTMesh *pMesh = mpBoundingBoxMesh = new CPUTMeshDX11(); pMesh->SetMeshTopology(CPUT_TOPOLOGY_INDEXED_LINE_LIST); CPUTBufferElementInfo vertexElementInfo; vertexElementInfo.mpSemanticName = "POSITION"; vertexElementInfo.mSemanticIndex = 0; vertexElementInfo.mElementType = CPUT_F32; vertexElementInfo.mElementComponentCount = 3; vertexElementInfo.mElementSizeInBytes = 12; vertexElementInfo.mOffset = 0; CPUTBufferElementInfo indexDataInfo; indexDataInfo.mElementType = CPUT_U16; indexDataInfo.mElementComponentCount = 1; indexDataInfo.mElementSizeInBytes = sizeof(UINT16); indexDataInfo.mOffset = 0; indexDataInfo.mSemanticIndex = 0; indexDataInfo.mpSemanticName = NULL; result = pMesh->CreateNativeResources( this, -1, 1, &vertexElementInfo, 8, // vertexCount pVertices, &indexDataInfo, 24, // indexCount pIndices ); ASSERT( CPUTSUCCESS(result), _L("Failed building bounding box mesh") ); cString modelSuffix = ptoc(this); UINT index = mpSubMaterialCount[0] + CPUT_MATERIAL_INDEX_BOUNDING_BOX; CPUTMaterialOGL *pMaterial = (CPUTMaterialOGL*)(mpMaterial[0][index]); ((CPUTMeshOGL*)pMesh)->BindVertexShaderLayout( pMaterial, &mpInputLayout[0][index] ); } #endif
41.111702
169
0.64355
GameTechDev
40e2d5dd4597b18047d34d0bbba22d245005e884
2,697
cpp
C++
DirectX3D11/Objects/Model/Ninja.cpp
GyumLee/DirectX3D11
6158874aa12e790747e6fd8a53de608071c49574
[ "Apache-2.0" ]
null
null
null
DirectX3D11/Objects/Model/Ninja.cpp
GyumLee/DirectX3D11
6158874aa12e790747e6fd8a53de608071c49574
[ "Apache-2.0" ]
null
null
null
DirectX3D11/Objects/Model/Ninja.cpp
GyumLee/DirectX3D11
6158874aa12e790747e6fd8a53de608071c49574
[ "Apache-2.0" ]
null
null
null
#include "Framework.h" Ninja::Ninja(UINT instanceID) : instanceID(instanceID), state(IDLE) { collider = new SphereCollider(); collider->tag = "NinjaCollider"; collider->Load(); hpBar = new ProgressBar("Textures/UI/hp_bar.png", "Textures/UI/hp_bar_BG.png"); //hpBar->scale *= 0.1f; } Ninja::~Ninja() { delete collider; delete hpBar; } void Ninja::Update() { SetLeftHand(); SetHpBar(); //Trace(); Move(); collider->UpdateWorld(); } void Ninja::Render() { if (!ninja->isActive) return; float radius = ((SphereCollider*)collider)->Radius(); if (!FRUSTUM->ContainSphere(collider->GlobalPos(), radius)) return; collider->Render(); } void Ninja::PostRender() { if (!ninja->isActive) return; float radius = ((SphereCollider*)collider)->Radius(); if (!FRUSTUM->ContainSphere(collider->GlobalPos(), radius)) return; hpBar->Render(); } void Ninja::GUIRender() { collider->GUIRender(); } void Ninja::Move() { if (terrain) ninja->position.y = terrain->GetHeight(ninja->position); } void Ninja::Hit() { collider->isActive = false; hp -= 30.0f; hpBar->SetValue(hp); if (hp > 0) SetClip(HIT); else SetClip(DYING); } void Ninja::SetEvent() { instancing->AddEvent(instanceID, HIT, 0.8f, bind(&Ninja::EndHit, this)); } void Ninja::Trace() { if (!collider->isActive) return; if (!target) return; Vector3 dir = target->position - ninja->position; Vector3 cross = Vector3::Cross(dir, ninja->Forward()); if (cross.y > 0.01f) ninja->rotation.y += DELTA; else if (cross.y < -0.01f) ninja->rotation.y -= DELTA; ninja->position -= ninja->Forward() * DELTA; SetClip(RUN); } void Ninja::EndHit() { SetClip(IDLE); collider->isActive = true; } void Ninja::EndDie() { ninja->isActive = false; } void Ninja::SetHpBar() { float distance = Distance(CAM->position, ninja->position); hpBar->scale.x = 10 / distance; hpBar->scale.y = 10 / distance; Vector3 barPos = ninja->position + Vector3(0, 5, 0); hpBar->position = CAM->WorldToScreenPoint(barPos); lerpHp = LERP(lerpHp, hp, lerpSpeed * DELTA); hpBar->SetLerpValue(lerpHp); hpBar->Update(); } void Ninja::SetLeftHand() { leftHand = instancing->GetTransformByNode(instanceID, 11) * ninja->GetWorld(); } void Ninja::SetMotions() { //ReadClip("Idle"); //ReadClip("Run"); //ReadClip("Attack"); ////ReadClip("Hit"); // 1. BreakPoint here, Start Debugging, go to ReadClip() //ReadClip("Hit", 0, true); //ReadClip("Dying"); // //clips[HIT]->SetEvent(0.8f, bind(&Ninja::EndHit, this)); //clips[DYING]->SetEvent(0.9f, bind(&Ninja::EndDie, this)); } void Ninja::SetClip(AnimState state) { if (this->state != state) { this->state = state; instancing->PlayClip(instanceID, state); } }
17.860927
80
0.661846
GyumLee
40ede24a47a7e4ef4ea39f532d744d241801d6e5
1,572
cpp
C++
sunglasses/src/Scripting/LuaPrimitives.cpp
jonathanbuchanan/Sunglasses
ab82b66f32650a813234cee8963f9b598ef5c1c8
[ "MIT" ]
1
2016-04-01T02:21:27.000Z
2016-04-01T02:21:27.000Z
sunglasses/src/Scripting/LuaPrimitives.cpp
jonathanbuchanan/Sunglasses
ab82b66f32650a813234cee8963f9b598ef5c1c8
[ "MIT" ]
49
2015-07-08T13:48:06.000Z
2017-06-27T01:40:51.000Z
sunglasses/src/Scripting/LuaPrimitives.cpp
jonathanbuchanan/Sunglasses
ab82b66f32650a813234cee8963f9b598ef5c1c8
[ "MIT" ]
null
null
null
// Copyright 2016 Jonathan Buchanan. // This file is part of Sunglasses, which is licensed under the MIT License. // See LICENSE.md for details. #include <sunglasses/Scripting/LuaPrimitives.h> namespace sunglasses { namespace Scripting { template<> int getFromStack(lua_State *l, int index) { return lua_tointeger(l, index); } template<> double getFromStack(lua_State *l, int index) { return lua_tonumber(l, index); } template<> float getFromStack(lua_State *l, int index) { return (float)lua_tonumber(l, index); } template<> bool getFromStack(lua_State *l, int index) { return lua_toboolean(l, index); } template<> const char * getFromStack(lua_State *l, int index) { return lua_tostring(l, index); } template<> std::string getFromStack(lua_State *l, int index) { return std::string(lua_tostring(l, index)); } template<> void pushToStack(lua_State *l, int value) { lua_pushinteger(l, value); } template<> void pushToStack(lua_State *l, double value) { lua_pushnumber(l, value); } template<> void pushToStack(lua_State *l, float value) { lua_pushnumber(l, (double)value); } template<> void pushToStack(lua_State *l, bool value) { lua_pushboolean(l, value); } template<> void pushToStack(lua_State *l, const char *value) { lua_pushstring(l, value); } template<> void pushToStack(lua_State *l, std::string value) { lua_pushstring(l, value.c_str()); } } } // namespace
26.644068
76
0.646947
jonathanbuchanan
40f14e72764036e435e6ed78ad0b700bcb9b7d46
4,773
hh
C++
src/Distributed/VoronoiRedistributeNodes.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
22
2018-07-31T21:38:22.000Z
2020-06-29T08:58:33.000Z
src/Distributed/VoronoiRedistributeNodes.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
41
2020-09-28T23:14:27.000Z
2022-03-28T17:01:33.000Z
src/Distributed/VoronoiRedistributeNodes.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
7
2019-12-01T07:00:06.000Z
2020-09-15T21:12:39.000Z
//---------------------------------Spheral++----------------------------------// // VoronoiRedistributeNodes // // This algorithm uses the Voronoi tessellation to decide how to domain // decompose our points. The idea is to relax a set of generator points into // the SPH node distribution -- the generators are attracted to the SPH points // repelled by one and other. These generator points then become the seeds to // draw the Voronoi tessellation about, each cell of which then represents a // computational domain. // // Created by JMO, Fri Jan 15 09:56:56 PST 2010 //----------------------------------------------------------------------------// #ifndef VoronoiRedistributeNodes_HH #define VoronoiRedistributeNodes_HH #include "RedistributeNodes.hh" #include "Utilities/KeyTraits.hh" #include <vector> #include <map> #ifdef USE_MPI #include <mpi.h> #endif namespace Spheral { template<typename Dimension> class DataBase; template<typename Dimension> class NodeList; template<typename Dimension> class Boundary; template<typename Dimension> class VoronoiRedistributeNodes: public RedistributeNodes<Dimension> { public: //--------------------------- Public Interface ---------------------------// typedef typename Dimension::Scalar Scalar; typedef typename Dimension::Vector Vector; typedef typename Dimension::Tensor Tensor; typedef typename Dimension::SymTensor SymTensor; typedef KeyTraits::Key Key; // Constructors VoronoiRedistributeNodes(const double dummy, const bool workBalance, const bool balanceGenerators, const double tolerance, const unsigned maxIterations); // Destructor virtual ~VoronoiRedistributeNodes(); // Given a Spheral++ data base of NodeLists, repartition it among the processors. // This is the method required of all descendent classes. virtual void redistributeNodes(DataBase<Dimension>& dataBase, std::vector<Boundary<Dimension>*> boundaries = std::vector<Boundary<Dimension>*>()) override; // Given the set of DomainNodes with their domain assignments, compute the // (work weighted) domain centroids. void computeCentroids(const std::vector<DomainNode<Dimension> >& nodes, std::vector<Vector>& generators) const; // Assign the nodes to the given generator positions, simultaneously computing the total // generator work load. void assignNodesToGenerators(const std::vector<Vector>& generators, const std::vector<int>& generatorFlags, std::vector<double>& generatorWork, std::vector<DomainNode<Dimension> >& nodes, double& minWork, double& maxWork, unsigned& minNodes, unsigned& maxNodes) const; // Look for any generator that has too much work, and unassign it's most // distant nodes. void cullGeneratorNodesByWork(const std::vector<Vector>& generators, const std::vector<double>& generatorWork, const double targetWork, std::vector<int>& generatorFlags, std::vector<DomainNode<Dimension> >& nodes) const; // Find the adjacent generators in the Voronoi diagram. std::vector<size_t> findNeighborGenerators(const size_t igen, const std::vector<Vector>& generators) const; // Flag for whether we should compute the work per node or strictly balance by // node count. bool workBalance() const; void workBalance(bool val); // Should we try to work balance between generators? // node count. bool balanceGenerators() const; void balanceGenerators(bool val); // The tolerance we're using to check for convergence of the generators. double tolerance() const; void tolerance(double val); // The maximum number of iterations to try and converge the generator positions. unsigned maxIterations() const; void maxIterations(unsigned val); private: //--------------------------- Private Interface ---------------------------// bool mWorkBalance, mBalanceGenerators; double mTolerance; unsigned mMaxIterations; // No copy or assignment operations. VoronoiRedistributeNodes(const VoronoiRedistributeNodes& nodes); VoronoiRedistributeNodes& operator=(const VoronoiRedistributeNodes& rhs); }; } #else // Forward declare the VoronoiRedistributeNodes class. namespace Spheral { template<typename Dimension> class VoronoiRedistributeNodes; } #endif
38.184
90
0.635659
jmikeowen
40f1d837ef4f8597647e34528cac584fa16008e2
2,118
hpp
C++
include/toy/memory/Allocator01.hpp
ToyAuthor/ToyBox
f517a64d00e00ccaedd76e33ed5897edc6fde55e
[ "Unlicense" ]
4
2017-07-06T22:18:41.000Z
2021-05-24T21:28:37.000Z
include/toy/memory/Allocator01.hpp
ToyAuthor/ToyBox
f517a64d00e00ccaedd76e33ed5897edc6fde55e
[ "Unlicense" ]
null
null
null
include/toy/memory/Allocator01.hpp
ToyAuthor/ToyBox
f517a64d00e00ccaedd76e33ed5897edc6fde55e
[ "Unlicense" ]
1
2020-08-02T13:00:38.000Z
2020-08-02T13:00:38.000Z
#pragma once #include <cstdlib> #include <cstring> #include "toy/Math.hpp" namespace toy{ namespace memory{ // The memory size of Allocator01 always base of 2. template<typename T> class Allocator01 { public: Allocator01() { ; } ~Allocator01() { free(); } Allocator01(const Allocator01 &other) { copy_mykind(const_cast<Allocator01&>(other)); } Allocator01 operator = (const Allocator01 &other) { copy_mykind(const_cast<Allocator01&>(other)); return *this; } T* allocate(std::size_t n) { (void)n; } void deallocate(T* p, std::size_t n) { (void)n; (void)p; } private: bool copy(void *p,size_t s) { size(s); std::memcpy(_data,p,s); return 1; } void free() { if(_data) { std::free(_data); _data = nullptr; _size = 0; _trueSize = 0; } } // Allocate memory for user. bool size(size_t s) { _size = s; if ( s>_trueSize ) { size_t new_size = ::toy::math::Exp1<size_t>(s); if ( _data==nullptr ) { _data = std::malloc(new_size); } else { _data = std::realloc(_data,new_size); } _trueSize = new_size; } return 1; } // Allocate memory for user, and release the memory unused. bool fitSize(size_t s) { _size = s; size_t new_size = ::toy::math::Exp1<size_t>(s); if ( new_size>_trueSize ) { if(_data==nullptr) { _data = std::malloc(new_size); } else { _data = std::realloc(_data,new_size); } _trueSize = new_size; } else if ( new_size<_trueSize ) { _data = std::realloc(_data,new_size); _trueSize = new_size; } return 1; } void* data() const { return _data; } size_t size() const { return _size; } void* _data = nullptr; std::size_t _size = 0; std::size_t _trueSize = 0; inline void copy_mykind(Allocator01 &other) { free(); _size = other._size; _trueSize = other._trueSize; _data = std::malloc(_trueSize); std::memcpy(_data,other._data,_size); } }; }//namespace memory }//namespace toy
14.408163
61
0.580264
ToyAuthor
40f2d4edc294a2c8d6ce2e049e487625902b155e
1,488
cpp
C++
src/utils/random.cpp
Thanduriel/func-renderer
99582272d8e34cb6e2f6bc9735c8eba5076bb29c
[ "MIT" ]
1
2019-01-27T17:54:45.000Z
2019-01-27T17:54:45.000Z
src/utils/random.cpp
Thanduriel/func-renderer
99582272d8e34cb6e2f6bc9735c8eba5076bb29c
[ "MIT" ]
null
null
null
src/utils/random.cpp
Thanduriel/func-renderer
99582272d8e34cb6e2f6bc9735c8eba5076bb29c
[ "MIT" ]
null
null
null
#include "random.hpp" #include <assert.h> namespace Util{ Random::Random(uint32_t _seed) { m_state[0] = 0xaffeaffe ^ _seed; m_state[1] = 0xf9b2a750 ^ (_seed * 0x804c8a24 + 0x68f699be); m_state[2] = 0x485eac66 ^ (_seed * 0x0fe56638 + 0xc917c8ce); m_state[3] = 0xcbd02714 ^ (_seed * 0x57571dae + 0xce2b3bd1); // Warmup Xorshift128(); Xorshift128(); Xorshift128(); Xorshift128(); } // ********************************************************************* // float Random::uniform(float _min, float _max) { double scale = (_max - _min) / 0xffffffff; return float(_min + scale * Xorshift128()); } // ********************************************************************* // int32_t Random::uniform(int32_t _min, int32_t _max) { uint32_t interval = uint32_t(_max - _min + 1); assert(interval != 0 && "Do not use integer maximum bounds!"); uint32_t value = Xorshift128(); return _min + value % interval; } // ********************************************************************* // Math::ArgVec<float, 2> Random::vector() { // Math::ArgVec<float, 2> vec; return Math::AVec2(uniform(-1.f,1.f), uniform(-1.f, 1.f)); } // ********************************************************************* // uint32_t Random::Xorshift128() { uint32_t tmp = m_state[0] ^ (m_state[0] << 11); m_state[0] = m_state[1]; m_state[1] = m_state[2]; m_state[2] = m_state[3]; m_state[3] ^= (m_state[3] >> 19) ^ tmp ^ (tmp >> 8); return m_state[3]; } }
27.054545
76
0.508065
Thanduriel
40f5ed080c871109c885e4cd200331d257b41c20
10,502
cpp
C++
Hercules0.1/src/Hercules/Scene/Level/LevelManager.cpp
CletusG/Hercules-Engine
d2e2e5a04b5149fd7779f7a1598070593fcc574d
[ "Apache-2.0" ]
null
null
null
Hercules0.1/src/Hercules/Scene/Level/LevelManager.cpp
CletusG/Hercules-Engine
d2e2e5a04b5149fd7779f7a1598070593fcc574d
[ "Apache-2.0" ]
null
null
null
Hercules0.1/src/Hercules/Scene/Level/LevelManager.cpp
CletusG/Hercules-Engine
d2e2e5a04b5149fd7779f7a1598070593fcc574d
[ "Apache-2.0" ]
null
null
null
#include "hcpch.h" #include "LevelManager.h" namespace Hercules { LevelData levelData; const void Hercules::LevelManager::OpenLevel(const char* levelPath, std::string projectPath) { HC_STAT("Opening {0}", levelPath); levelData.matColors.clear(); levelData.matShinies.clear(); SceneManager::GetEntites().clear(); SceneManager::GetTransformComponentList().clear(); SceneManager::GetLightComponentList().clear(); SceneManager::GetDemoComponentList().clear(); SceneManager::GetMeshComponentList().clear(); SceneManager::GetDirectionalLightList().clear(); SceneManager::GetPointLightList().clear(); SceneManager::GetSpotLightList().clear(); SceneManager::GetMaterialComponentList().clear(); SceneManager::GetTextureList().clear(); std::string line; std::ifstream levelFile(levelPath); int lineNR = 1; unsigned int id = 1; std::string delimiter = "#"; std::string colon = ":"; std::string pos = "P"; std::string rot = "R"; std::string scale = "S"; std::string color = "C"; std::string tex = "T"; std::string shiny = "H"; std::string mesh = "V"; std::string mat = "M"; //Read materials HC_CORE_STAT("Loading materials..."); for (auto& i : std::filesystem::directory_iterator(projectPath + "Assets/Materials")) { std::string path = i.path().string(); std::ifstream material(path); std::string name = ""; bool currentType = 0; while (std::getline(material, line)) { if (line.find(delimiter) != std::string::npos) { line.erase(0, line.find(delimiter) + delimiter.length()); currentType = std::stoi(line); } else if (line.find(tex) != std::string::npos) { line.erase(0, line.find(tex) + tex.length()); name = i.path().filename().string().substr(0, i.path().filename().string().find(".")); std::string path = projectPath + line; SceneManager::NewTexture(name, path.c_str(), currentType); } else if (line.find(color) != std::string::npos) { if (line.substr(0, 1) == color) { line.erase(0, line.find(color) + color.length()); std::string r = line.substr(0, line.find("r")); line.erase(0, line.find("r") + color.length()); std::string g = line.substr(0, color.find("g")); line.erase(0, line.find("g") + color.length()); std::string b = line.substr(0, line.find("b")); levelData.matColors.insert(std::pair<std::string, glm::vec3> (name, glm::vec3(std::stof(r), std::stof(g), std::stof(b)))); } } else if (line.find(shiny) != std::string::npos) { if (line.substr(0, 1) == shiny) { line.erase(0, line.find(shiny) + shiny.length()); levelData.matShinies.insert(std::pair<std::string, float>(name, std::stof(line))); } } } } HC_CORE_SUCCESS("Materials loaded"); //Read level file HC_CORE_STAT("Loading {0}...", levelPath); while (std::getline(levelFile, line)) { if (line.find(delimiter) != std::string::npos) { line.erase(0, line.find(delimiter) + delimiter.length()); std::string name = line.substr(0, line.find(colon)); line.erase(0, line.find(colon) + colon.length()); id = std::stoi(line.substr(0, line.find(colon))); SceneManager::NewEntity(name); } else if (line.find(pos) != std::string::npos) { if (line.substr(0, 1) == pos) { //Position line.erase(0, line.find(pos) + pos.length()); std::string px = line.substr(0, line.find("x")); line.erase(0, line.find("x") + pos.length()); std::string py = line.substr(0, line.find("y")); line.erase(0, line.find("y") + pos.length()); std::string pz = line.substr(0, line.find("z")); //Scale line.erase(0, line.find(scale) + scale.length()); std::string sx = line.substr(0, line.find("x")); line.erase(0, line.find("x") + scale.length()); std::string sy = line.substr(0, line.find("y")); line.erase(0, line.find("y") + scale.length()); std::string sz = line.substr(0, line.find("z")); //Rotation line.erase(0, line.find(rot) + rot.length()); std::string rx = line.substr(0, line.find("x")); line.erase(0, line.find("x") + rot.length()); std::string ry = line.substr(0, line.find("y")); line.erase(0, line.find("y") + rot.length()); std::string rz = line.substr(0, line.find("z")); SceneManager::NewComponent(TransformComponent(glm::vec3(std::stof(px), std::stof(py), std::stof(pz)), glm::vec3(std::stof(sx), std::stof(sy), std::stof(sz)), glm::vec3(std::stof(rx), std::stof(ry), std::stof(rz))), SceneManager::GetEntites().size()); } } else if (line.find("DL") != std::string::npos) { SceneManager::NewComponent(DirectionalLight(), id); } else if (line.find("T") != std::string::npos) { SceneManager::NewComponent(DemoComponent(), id); } if (line.find(mesh) != std::string::npos) { if (line.substr(0, 1) == mesh) { line.erase(0, line.find(mesh) + mesh.length()); SceneManager::NewComponent(MeshComponent(projectPath + line), id); } } if (line.find(mat) != std::string::npos) { if (line.substr(0, 1) == mat) { line.erase(0, line.find(mat) + mat.length()); std::string m = line.substr(0, line.find(mat)); SceneManager::NewComponent(MaterialComponent( SceneManager::GetTexture(m.c_str()), *GetColor(m)), id); SceneManager::GetMaterialComponent(id)->SetName(m); } } if (line.find(color) != std::string::npos) { if (line.substr(0, 1) == color) { line.erase(0, line.find(color) + color.length()); std::string r = line.substr(0, line.find("r")); line.erase(0, line.find("r") + color.length()); std::string g = line.substr(0, color.find("g")); line.erase(0, line.find("g") + color.length()); std::string b = line.substr(0, line.find("b")); SceneManager::GetMaterialComponent(id)->SetColor(glm::vec3( std::stof(r), std::stof(g), std::stof(b))); } } if (line.find(shiny) != std::string::npos) { if (line.substr(0, 1) == shiny) { line.erase(0, line.find(shiny) + shiny.length()); SceneManager::GetMaterialComponent(id)->SetShininess(std::stof(line)); } } } levelFile.close(); HC_CORE_SUCCESS("{0} loaded", levelPath); //ProcessMaterials(levelPath); } void LevelManager::ProcessMaterials(const char* levelPath) { std::ifstream levelFile(levelPath); std::string line; std::string mat = "M"; std::string delimiter = "#"; std::string colon = ":"; std::string color = "C"; std::string shiny = "H"; unsigned int id = 0; while (std::getline(levelFile, line)) { if (line.find(delimiter) != std::string::npos) { line.erase(0, line.find(delimiter) + delimiter.length()); line.erase(0, line.find(colon) + colon.length()); id = std::stoi(line.substr(0, line.find(colon))); } else if (line.find(mat) != std::string::npos) { if (line.substr(0, 1) == mat) { line.erase(0, line.find(mat) + mat.length()); std::string m = line.substr(0, line.find(mat)); SceneManager::NewComponent(MaterialComponent( SceneManager::GetTexture(m.c_str()), *GetColor(m)), id); SceneManager::GetMaterialComponent(id)->SetName(m); } } else if (line.find(color) != std::string::npos) { line.erase(0, line.find(color) + color.length()); std::string r = line.substr(0, line.find("r")); line.erase(0, line.find("r") + color.length()); std::string g = line.substr(0, color.find("g")); line.erase(0, line.find("g") + color.length()); std::string b = line.substr(0, line.find("b")); SceneManager::GetMaterialComponent(id)->SetColor(glm::vec3( std::stof(r), std::stof(g), std::stof(b))); } else if (line.find(shiny) != std::string::npos) { if (line.substr(0, 1) == shiny) { line.erase(0, line.find(shiny) + shiny.length()); SceneManager::GetMaterialComponent(id)->SetShininess(std::stof(line)); } } } } //Saving level const void LevelManager::WriteLevel(const char* levelPath, std::string projectPath) { std::fstream file_out; file_out.open(levelPath, std::ios::out); if (!file_out.is_open()) { HC_CORE_ERROR("Failed to open level"); } else { for (auto &i : SceneManager::GetEntites()) { TransformComponent t = *SceneManager::GetTransformComponent(i.first); //Every entity will have a transform file_out << "\n#" << i.second << ":" << i.first << std::endl; file_out << "P" << t.GetPos().x << "x" << t.GetPos().y << "y" << t.GetPos().z << "z" << "S" << t.GetScale().x << "x" << t.GetScale().y << "y" << t.GetScale().z << "z" << "R" << t.GetRotation().x << "x" << t.GetRotation().y << "y" << t.GetRotation().z << "z" << std::endl; if (SceneManager::HasDirectionalLight(i.first)) file_out << "DL" << std::endl; if (SceneManager::HasTestComponent(i.first)) file_out << "T" << std::endl; if (SceneManager::HasMaterialComponent(i.first)) { file_out << "M" << SceneManager::GetMaterialComponent(i.first)->GetName() << std::endl; file_out << "H" << SceneManager::GetMaterialComponent(i.first)->GetShininess() << std::endl; file_out << "C" << SceneManager::GetMaterialComponent(i.first)->GetColor().x << "r" << SceneManager::GetMaterialComponent(i.first)->GetColor().y << "g" << SceneManager::GetMaterialComponent(i.first)->GetColor().z << "b" << std::endl; } if (SceneManager::HasMeshComponent(i.first)) { std::string relativePath = SceneManager::GetMeshComponent(i.first)->GetPath(); std::string absolutePath = relativePath.erase(0, relativePath.find(projectPath) + projectPath.length()); HC_CORE_INFO(absolutePath); file_out << "V" << absolutePath << std::endl; } } HC_CORE_SUCCESS("{0} Saved succesfully!", levelPath); } file_out.close(); } const void LevelManager::NewLevel(std::string levelName) { std::string path = "Levels/" + levelName + ".hclvl"; std::ofstream file_out(path); HC_CORE_SUCCESS("New Level: {0}", path); } glm::vec3* LevelManager::GetColor(std::string name) { for (auto& i : levelData.matColors) { if (i.first == name) { return &i.second; } } } float* LevelManager::GetShininess(std::string name) { for (auto& i : levelData.matShinies) { if (i.first == name) { return &i.second; } } } }
30.618076
109
0.602838
CletusG
40f99ccf7408edf201d3985d87537b535ed68eac
1,761
ipp
C++
implement/oglplus/enums/object_type_names.ipp
jnbrq/oglplus
2e072e91292643e0871565ae5147584403846290
[ "BSL-1.0" ]
null
null
null
implement/oglplus/enums/object_type_names.ipp
jnbrq/oglplus
2e072e91292643e0871565ae5147584403846290
[ "BSL-1.0" ]
null
null
null
implement/oglplus/enums/object_type_names.ipp
jnbrq/oglplus
2e072e91292643e0871565ae5147584403846290
[ "BSL-1.0" ]
null
null
null
// File implement/oglplus/enums/object_type_names.ipp // // Automatically generated file, DO NOT modify manually. // Edit the source 'source/enums/oglplus/object_type.txt' // or the 'source/enums/make_enum.py' script instead. // // Copyright 2010-2017 Matus Chochlik. // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // namespace enums { OGLPLUS_LIB_FUNC StrCRef ValueName_( ObjectType*, GLenum value ) #if (!OGLPLUS_LINK_LIBRARY || defined(OGLPLUS_IMPLEMENTING_LIBRARY)) && \ !defined(OGLPLUS_IMPL_EVN_OBJECTTYPE) #define OGLPLUS_IMPL_EVN_OBJECTTYPE { switch(value) { #if defined GL_BUFFER case GL_BUFFER: return StrCRef("BUFFER"); #endif #if defined GL_FRAMEBUFFER case GL_FRAMEBUFFER: return StrCRef("FRAMEBUFFER"); #endif #if defined GL_PROGRAM_PIPELINE case GL_PROGRAM_PIPELINE: return StrCRef("PROGRAM_PIPELINE"); #endif #if defined GL_PROGRAM case GL_PROGRAM: return StrCRef("PROGRAM"); #endif #if defined GL_QUERY case GL_QUERY: return StrCRef("QUERY"); #endif #if defined GL_RENDERBUFFER case GL_RENDERBUFFER: return StrCRef("RENDERBUFFER"); #endif #if defined GL_SAMPLER case GL_SAMPLER: return StrCRef("SAMPLER"); #endif #if defined GL_SHADER case GL_SHADER: return StrCRef("SHADER"); #endif #if defined GL_TEXTURE case GL_TEXTURE: return StrCRef("TEXTURE"); #endif #if defined GL_TRANSFORM_FEEDBACK case GL_TRANSFORM_FEEDBACK: return StrCRef("TRANSFORM_FEEDBACK"); #endif #if defined GL_VERTEX_ARRAY case GL_VERTEX_ARRAY: return StrCRef("VERTEX_ARRAY"); #endif #if defined GL_NONE case GL_NONE: return StrCRef("NONE"); #endif default:; } OGLPLUS_FAKE_USE(value); return StrCRef(); } #else ; #endif } // namespace enums
25.521739
73
0.776263
jnbrq
40fb78161ebbab40e852536757f7d8380de74454
118,110
cpp
C++
private/parser.cpp
kociap/vush2
4002afb9c86638ff9882a44b1010a13348eed664
[ "MIT" ]
6
2021-04-27T22:17:30.000Z
2021-12-31T12:42:44.000Z
private/parser.cpp
kociap/vush2
4002afb9c86638ff9882a44b1010a13348eed664
[ "MIT" ]
1
2021-05-11T10:50:52.000Z
2021-05-11T10:50:52.000Z
private/parser.cpp
kociap/vush2
4002afb9c86638ff9882a44b1010a13348eed664
[ "MIT" ]
null
null
null
#include <parser.hpp> #include <anton/optional.hpp> #include <anton/string7_stream.hpp> #include <anton/string7_view.hpp> // TODO: When matching keywords, ensure that the keyword is followed by non-identifier character (Find a cleaner way). // TODO: Figure out a way to match operators that use overlapping symbols (+ and +=) in a clean way. // TODO: const types. // TODO: add constructors (currently function call which will break if we use an array type). namespace vush { using namespace anton::literals; // keywords static constexpr anton::String7_View kw_if = u8"if"; static constexpr anton::String7_View kw_else = u8"else"; static constexpr anton::String7_View kw_switch = u8"switch"; static constexpr anton::String7_View kw_case = u8"case"; static constexpr anton::String7_View kw_default = u8"default"; static constexpr anton::String7_View kw_for = u8"for"; static constexpr anton::String7_View kw_while = u8"while"; static constexpr anton::String7_View kw_do = u8"do"; static constexpr anton::String7_View kw_return = u8"return"; static constexpr anton::String7_View kw_break = u8"break"; static constexpr anton::String7_View kw_continue = u8"continue"; static constexpr anton::String7_View kw_discard = u8"discard"; static constexpr anton::String7_View kw_true = u8"true"; static constexpr anton::String7_View kw_false = u8"false"; static constexpr anton::String7_View kw_from = u8"from"; static constexpr anton::String7_View kw_struct = u8"struct"; static constexpr anton::String7_View kw_import = u8"import"; static constexpr anton::String7_View kw_const = u8"const"; static constexpr anton::String7_View kw_settings = u8"settings"; static constexpr anton::String7_View kw_reinterpret = u8"reinterpret"; static constexpr anton::String7_View kw_invariant = u8"invariant"; static constexpr anton::String7_View kw_smooth = u8"smooth"; static constexpr anton::String7_View kw_flat = u8"flat"; static constexpr anton::String7_View kw_noperspective = u8"noperspective"; // attributes static constexpr anton::String7_View attrib_workgroup = u8"workgroup"; // stages static constexpr anton::String7_View stage_vertex = u8"vertex"; static constexpr anton::String7_View stage_fragment = u8"fragment"; static constexpr anton::String7_View stage_compute = u8"compute"; // separators and operators static constexpr anton::String7_View token_brace_open = u8"{"; static constexpr anton::String7_View token_brace_close = u8"}"; static constexpr anton::String7_View token_bracket_open = u8"["; static constexpr anton::String7_View token_bracket_close = u8"]"; static constexpr anton::String7_View token_paren_open = u8"("; static constexpr anton::String7_View token_paren_close = u8")"; static constexpr anton::String7_View token_angle_open = u8"<"; static constexpr anton::String7_View token_angle_close = u8">"; static constexpr anton::String7_View token_semicolon = u8";"; static constexpr anton::String7_View token_colon = u8":"; static constexpr anton::String7_View token_scope_resolution = u8"::"; static constexpr anton::String7_View token_arrow = u8"=>"; static constexpr anton::String7_View token_comma = u8","; // static constexpr anton::String7_View token_question = u8"?"; static constexpr anton::String7_View token_dot = u8"."; static constexpr anton::String7_View token_double_quote = u8"\""; static constexpr anton::String7_View token_plus = u8"+"; static constexpr anton::String7_View token_minus = u8"-"; static constexpr anton::String7_View token_multiply = u8"*"; static constexpr anton::String7_View token_divide = u8"/"; static constexpr anton::String7_View token_remainder = u8"%"; static constexpr anton::String7_View token_logic_and = u8"&&"; static constexpr anton::String7_View token_bit_and = u8"&"; static constexpr anton::String7_View token_logic_or = u8"||"; static constexpr anton::String7_View token_logic_xor = u8"^^"; static constexpr anton::String7_View token_bit_or = u8"|"; static constexpr anton::String7_View token_bit_xor = u8"^"; static constexpr anton::String7_View token_logic_not = u8"!"; static constexpr anton::String7_View token_bit_not = u8"~"; static constexpr anton::String7_View token_bit_lshift = u8"<<"; static constexpr anton::String7_View token_bit_rshift = u8">>"; static constexpr anton::String7_View token_equal = u8"=="; static constexpr anton::String7_View token_not_equal = u8"!="; static constexpr anton::String7_View token_less = u8"<"; static constexpr anton::String7_View token_greater = u8">"; static constexpr anton::String7_View token_less_equal = u8"<="; static constexpr anton::String7_View token_greater_equal = u8">="; static constexpr anton::String7_View token_assign = u8"="; static constexpr anton::String7_View token_increment = u8"++"; static constexpr anton::String7_View token_decrement = u8"--"; static constexpr anton::String7_View token_compound_plus = u8"+="; static constexpr anton::String7_View token_compound_minus = u8"-="; static constexpr anton::String7_View token_compound_multiply = u8"*="; static constexpr anton::String7_View token_compound_divide = u8"/="; static constexpr anton::String7_View token_compound_remainder = u8"%="; static constexpr anton::String7_View token_compound_bit_and = u8"&="; static constexpr anton::String7_View token_compound_bit_or = u8"|="; static constexpr anton::String7_View token_compound_bit_xor = u8"^="; static constexpr anton::String7_View token_compound_bit_lshift = u8"<<="; static constexpr anton::String7_View token_compound_bit_rshift = u8">>="; [[nodiscard]] static bool is_whitespace(char32 c) { return (c <= 32) | (c == 127); } [[nodiscard]] static bool is_binary_digit(char32 c) { return c == 48 || c == 49; } [[nodiscard]] static bool is_hexadecimal_digit(char32 c) { return (c >= 48 && c <= 57) || (c >= 65 && c <= 70) || (c >= 97 && c <= 102); } [[nodiscard]] static bool is_octal_digit(char32 c) { return c >= 48 && c <= 55; } [[nodiscard]] static bool is_digit(char32 c) { return c >= 48 && c <= 57; } [[nodiscard]] static bool is_alpha(char32 c) { return (c >= 97 && c < 123) || (c >= 65 && c < 91); } [[nodiscard]] static bool is_first_identifier_character(char32 c) { return c == '_' || is_alpha(c); } [[nodiscard]] static bool is_identifier_character(char32 c) { return c == '_' || is_digit(c) || is_alpha(c); } [[nodiscard]] static bool is_keyword(anton::String_View string) { static constexpr anton::String7_View keywords[] = { kw_if, kw_else, kw_switch, kw_case, kw_default, kw_for, kw_while, kw_do, kw_return, kw_break, kw_continue, kw_discard, kw_true, kw_false, kw_from, kw_struct, kw_import, kw_const, kw_settings, kw_reinterpret, }; anton::String7_View string7{string.bytes_begin(), string.bytes_end()}; constexpr i64 array_size = sizeof(keywords) / sizeof(anton::String7_View); for(anton::String7_View const *i = keywords, *end = keywords + array_size; i != end; ++i) { if(*i == string7) { return true; } } return false; } class Lexer_State { public: i64 stream_offset; i64 line; i64 column; }; constexpr char8 eof_char8 = (char8)EOF; constexpr char32 eof_char32 = (char32)EOF; // TODO: Place this comment somewhere // The source string is ASCII only, so String7 will be the exact same size as String, // but String7 will avoid all Unicode function calls and thus accelerate parsing. class Lexer { public: Lexer(anton::String_View source): _begin(source.bytes_begin()), _end(source.bytes_end()), _current(source.bytes_begin()) {} bool match(anton::String7_View const string, bool const must_not_be_followed_by_identifier_char = false) { Lexer_State const state_backup = get_current_state(); for(char8 c: string) { if(_current != _end && *_current == c) { ++_current; ++_column; } else { restore_state(state_backup); return false; } } if(must_not_be_followed_by_identifier_char) { char32 const c = peek_next(); if(is_identifier_character(c)) { restore_state(state_backup); return false; } else { return true; } } else { return true; } } bool match_identifier(anton::String& out) { ignore_whitespace_and_comments(); if(_current != _end && !is_first_identifier_character(*_current)) { return false; } char8 const* identifier_end = _current + 1; while(identifier_end != _end && is_identifier_character(*identifier_end)) { ++identifier_end; } out += anton::String_View{_current, identifier_end}; _column += identifier_end - _current; _current = identifier_end; return true; } bool match_eof() { ignore_whitespace_and_comments(); return _current == _end || *_current == eof_char8; } void ignore_whitespace_and_comments() { while(true) { while(_current != _end && is_whitespace(*_current)) { if(*_current == '\n') { _line += 1; _column = 1; } else { ++_column; } ++_current; } if(_current != _end && *_current == '/' && _current + 1 != _end) { char32 const next_char = *(_current + 1); if(next_char == U'/') { for(; _current != _end && *_current != '\n'; ++_current) {} // The loop stops at the newline. Skip the newline. _current += 1; _line += 1; _column = 1; continue; } else if(next_char == U'*') { _current += 2; _column += 2; for(char32 c1 = get_next(), c2 = peek_next(); c1 != U'*' || c2 != U'/'; c1 = get_next(), c2 = peek_next()) {} get_next(); continue; } else { // Not a comment. End skipping. break; } } break; } } Lexer_State get_current_state() { ignore_whitespace_and_comments(); return {_current - _begin, _line, _column}; } Lexer_State get_current_state_no_skip() { return {_current - _begin, _line, _column}; } void restore_state(Lexer_State const state) { _current = _begin + state.stream_offset; _line = state.line; _column = state.column; } char32 get_next() { if(_current != _end) { char32 const c = *_current; ++_current; if(c == '\n') { _line += 1; _column = 1; } else { _column += 1; } return c; } else { return eof_char32; } } char32 peek_next() { if(_current != _end) { return *_current; } else { return eof_char32; } } void unget() { if(_current != _begin) { --_current; } } private: char8 const* _begin; char8 const* _end; char8 const* _current; i64 _line = 1; i64 _column = 1; }; class Parser { public: Parser(anton::String_View source_code, anton::String_View source_name): _source_name(source_name), _lexer(source_code) {} anton::Expected<Declaration_List, Parse_Error> build_ast() { Declaration_List ast; while(!_lexer.match_eof()) { if(Owning_Ptr declaration = try_declaration()) { ast.emplace_back(ANTON_MOV(declaration)); } else { return {anton::expected_error, _last_error}; } } return {anton::expected_value, ANTON_MOV(ast)}; } anton::Expected<Declaration_List, Parse_Error> parse_builtin_functions() { Declaration_List builtin_functions; while(!_lexer.match_eof()) { if(Owning_Ptr fn = try_function_declaration()) { fn->builtin = true; fn->source_info.line = 1; fn->source_info.end_line = 1; builtin_functions.emplace_back(ANTON_MOV(fn)); } else { return {anton::expected_error, _last_error}; } } return {anton::expected_value, ANTON_MOV(builtin_functions)}; } private: anton::String_View _source_name; Lexer _lexer; Parse_Error _last_error; void set_error(anton::String_View const message, Lexer_State const& state) { if(state.stream_offset >= _last_error.stream_offset) { _last_error.message = message; _last_error.line = state.line; _last_error.column = state.column; _last_error.stream_offset = state.stream_offset; } } void set_error(anton::String_View const message) { Lexer_State const state = _lexer.get_current_state_no_skip(); if(state.stream_offset >= _last_error.stream_offset) { _last_error.message = message; _last_error.line = state.line; _last_error.column = state.column; _last_error.stream_offset = state.stream_offset; } } Source_Info src_info(Lexer_State const& start, Lexer_State const& end) { return Source_Info{_source_name, start.line, start.column, start.stream_offset, end.line, end.column, end.stream_offset}; } Owning_Ptr<Declaration> try_declaration() { if(Owning_Ptr declaration_if = try_declaration_if()) { return declaration_if; } if(Owning_Ptr import_declaration = try_import_declaration()) { return import_declaration; } if(Owning_Ptr settings_declaration = try_settings_declaration()) { return settings_declaration; } if(Owning_Ptr struct_declaration = try_struct_declaration()) { return struct_declaration; } if(Owning_Ptr pass_stage = try_pass_stage_declaration()) { return pass_stage; } if(Owning_Ptr function_declaration = try_function_declaration()) { return function_declaration; } if(Owning_Ptr variable_declaration = try_variable_declaration()) { return variable_declaration; } if(Owning_Ptr constant = try_constant_declaration()) { return constant; } set_error(u8"expected declaration"); return nullptr; } Owning_Ptr<Declaration_If> try_declaration_if() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_if, true)) { set_error(u8"expected 'if'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr condition = try_expression(); if(!condition) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return nullptr; } Declaration_List true_declarations; while(!_lexer.match(token_brace_close)) { if(_lexer.match_eof()) { set_error(u8"unexpected end of file"); _lexer.restore_state(state_backup); return nullptr; } if(Owning_Ptr declaration = try_declaration()) { true_declarations.emplace_back(ANTON_MOV(declaration)); } else { return nullptr; } } Declaration_List false_declarations; if(_lexer.match(kw_else, true)) { if(Owning_Ptr if_declaration = try_declaration_if()) { false_declarations.emplace_back(ANTON_MOV(if_declaration)); } else { if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return nullptr; } while(!_lexer.match(token_brace_close)) { if(Owning_Ptr declaration = try_declaration()) { false_declarations.emplace_back(ANTON_MOV(declaration)); } else { _lexer.restore_state(state_backup); return nullptr; } } } } return Owning_Ptr{ new Declaration_If(ANTON_MOV(condition), ANTON_MOV(true_declarations), ANTON_MOV(false_declarations), src_info(state_backup, state_backup))}; } Owning_Ptr<Import_Declaration> try_import_declaration() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_import, true)) { set_error(u8"expected 'import'"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); if(Owning_Ptr string = try_string_literal()) { return Owning_Ptr{new Import_Declaration(ANTON_MOV(string), src)}; } else { _lexer.restore_state(state_backup); return nullptr; } } Owning_Ptr<Variable_Declaration> try_variable_declaration() { Lexer_State const state_backup = _lexer.get_current_state(); Owning_Ptr var_type = try_type(); if(!var_type) { _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr var_name = try_identifier(); if(!var_name) { set_error(u8"expected variable name"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr<Expression> initializer = nullptr; if(_lexer.match(token_assign)) { initializer = try_expression(); if(!initializer) { _lexer.restore_state(state_backup); return nullptr; } } if(!_lexer.match(token_semicolon)) { set_error(u8"expected ';' after variable declaration"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Variable_Declaration(ANTON_MOV(var_type), ANTON_MOV(var_name), ANTON_MOV(initializer), src)}; } Owning_Ptr<Constant_Declaration> try_constant_declaration() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_const)) { set_error(u8"expected 'const'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr var_type = try_type(); if(!var_type) { set_error(u8"expected type"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr var_name = try_identifier(); if(!var_name) { set_error(u8"expected variable name"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr<Expression> initializer = nullptr; if(_lexer.match(token_assign)) { initializer = try_expression(); if(!initializer) { _lexer.restore_state(state_backup); return nullptr; } } if(!_lexer.match(token_semicolon)) { set_error(u8"expected ';' after constant declaration"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Constant_Declaration(ANTON_MOV(var_type), ANTON_MOV(var_name), ANTON_MOV(initializer), src)}; } Owning_Ptr<Struct_Member> try_struct_member() { Lexer_State const state_backup = _lexer.get_current_state(); bool has_invariant = false; bool has_interpolation = false; Interpolation interpolation = Interpolation::none; while(true) { if(_lexer.match(kw_invariant, true)) { if(has_invariant) { set_error(u8"multiple invariance qualifiers are not allowed"); _lexer.restore_state(state_backup); return nullptr; } has_invariant = true; continue; } if(_lexer.match(kw_smooth, true)) { if(has_interpolation) { set_error(u8"multiple interpolation qualifiers are not allowed"); _lexer.restore_state(state_backup); return nullptr; } interpolation = Interpolation::smooth; has_interpolation = true; continue; } if(_lexer.match(kw_flat, true)) { if(has_interpolation) { set_error(u8"multiple interpolation qualifiers are not allowed"); _lexer.restore_state(state_backup); return nullptr; } interpolation = Interpolation::flat; has_interpolation = true; continue; } if(_lexer.match(kw_noperspective, true)) { if(has_interpolation) { set_error(u8"multiple interpolation qualifiers are not allowed"); _lexer.restore_state(state_backup); return nullptr; } interpolation = Interpolation::noperspective; has_interpolation = true; continue; } break; } Owning_Ptr var_type = try_type(); if(!var_type) { _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr var_name = try_identifier(); if(!var_name) { set_error(u8"expected member name"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr<Expression> initializer = nullptr; if(_lexer.match(token_assign)) { initializer = try_expression(); if(!initializer) { _lexer.restore_state(state_backup); return nullptr; } } if(!_lexer.match(token_semicolon)) { set_error(u8"expected ';'"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Struct_Member(ANTON_MOV(var_type), ANTON_MOV(var_name), ANTON_MOV(initializer), interpolation, has_invariant, src)}; } Owning_Ptr<Struct_Declaration> try_struct_declaration() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_struct, true)) { set_error(u8"expected 'struct'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr struct_name = try_identifier(); if(!struct_name) { set_error(u8"expected struct name"); _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return nullptr; } anton::Array<Owning_Ptr<Struct_Member>> members; while(!_lexer.match(token_brace_close)) { if(Owning_Ptr decl = try_struct_member()) { members.emplace_back(ANTON_MOV(decl)); } else { _lexer.restore_state(state_backup); return nullptr; } } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Struct_Declaration(ANTON_MOV(struct_name), ANTON_MOV(members), src)}; } Owning_Ptr<Settings_Declaration> try_settings_declaration() { Lexer_State const state_backup = _lexer.get_current_state(); auto match_string = [this, &state_backup]() -> anton::Optional<anton::String> { _lexer.ignore_whitespace_and_comments(); anton::String string; while(true) { char32 next_char = _lexer.peek_next(); if(next_char == eof_char32) { set_error(u8"unexpected end of file"); _lexer.restore_state(state_backup); return anton::null_optional; } else if(is_whitespace(next_char) || next_char == U':' || next_char == U'}' || next_char == U'{') { return {ANTON_MOV(string)}; } else { string += next_char; _lexer.get_next(); } } }; auto match_nested_settings = [this, &state_backup, &match_string](auto match_nested_settings, anton::Array<Setting_Key_Value>& settings, anton::String const& setting_name) -> bool { while(true) { if(_lexer.match(token_brace_close)) { return true; } auto key_name = match_string(); if(!key_name) { _lexer.restore_state(state_backup); return false; } if(key_name.value().size_bytes() == 0) { set_error(u8"expected name"); _lexer.restore_state(state_backup); return false; } if(!_lexer.match(token_colon)) { set_error(u8"expected ':'"); _lexer.restore_state(state_backup); return false; } anton::String setting_key = setting_name; if(setting_key.size_bytes() > 0) { setting_key += u8"_"; } setting_key += key_name.value(); if(_lexer.match(token_brace_open)) { if(!match_nested_settings(match_nested_settings, settings, setting_key)) { _lexer.restore_state(state_backup); return false; } } else { auto value = match_string(); if(!value) { _lexer.restore_state(state_backup); return false; } if(value.value().size_bytes() == 0) { set_error(u8"expected value string after ':'"); _lexer.restore_state(state_backup); return false; } settings.emplace_back(Setting_Key_Value{ANTON_MOV(setting_key), ANTON_MOV(value.value())}); } } }; if(!_lexer.match(kw_settings, true)) { set_error(u8"expected 'settings'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr pass_name = try_identifier(); if(!pass_name) { _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr settings_declaration{new Settings_Declaration(ANTON_MOV(pass_name), src_info(state_backup, state_backup))}; if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return nullptr; } if(!match_nested_settings(match_nested_settings, settings_declaration->settings, anton::String{})) { _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); settings_declaration->source_info = src; return settings_declaration; } Owning_Ptr<Attribute> try_attribute() { Lexer_State const state_backup = _lexer.get_current_state(); // workgroup attribute if(_lexer.match(attrib_workgroup, true)) { if(!_lexer.match(token_paren_open)) { set_error(u8"expected '('"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr x = try_integer_literal(); if(!x) { _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr<Integer_Literal> y; Owning_Ptr<Integer_Literal> z; if(_lexer.match(token_comma)) { y = try_integer_literal(); if(!y) { _lexer.restore_state(state_backup); return nullptr; } if(_lexer.match(token_comma)) { z = try_integer_literal(); if(!z) { _lexer.restore_state(state_backup); return nullptr; } } } if(!_lexer.match(token_paren_close)) { set_error(u8"expected ')'"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Workgroup_Attribute(ANTON_MOV(x), ANTON_MOV(y), ANTON_MOV(z), src)}; } // TODO: Add a diagnostic for unrecognized attributes set_error(u8"expected identifier"); _lexer.restore_state(state_backup); return nullptr; } anton::Optional<Attribute_List> try_attribute_list() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(token_bracket_open)) { set_error(u8"expected '['"); _lexer.restore_state(state_backup); return anton::null_optional; } if(_lexer.match(token_bracket_close)) { set_error(u8"empty attribute list (TODO: PROVIDE A PROPER DIAGNOSTIC MESSAGE WITH EXACT LOCATION AND CODE SNIPPET)"); _lexer.restore_state(state_backup); return anton::null_optional; } Attribute_List attributes; while(true) { Owning_Ptr attribute = try_attribute(); if(!attribute) { _lexer.restore_state(state_backup); return anton::null_optional; } attributes.emplace_back(ANTON_MOV(attribute)); if(!_lexer.match(token_comma)) { break; } } if(!_lexer.match(token_bracket_close)) { _lexer.restore_state(state_backup); return anton::null_optional; } return ANTON_MOV(attributes); } Owning_Ptr<Image_Layout_Qualifier> try_image_layout_qualifier() { Image_Layout_Type qualifiers[] = {Image_Layout_Type::rgba32f, Image_Layout_Type::rgba16f, Image_Layout_Type::rg32f, Image_Layout_Type::rg16f, Image_Layout_Type::r11f_g11f_b10f, Image_Layout_Type::r32f, Image_Layout_Type::r16f, Image_Layout_Type::rgba16, Image_Layout_Type::rgb10_a2, Image_Layout_Type::rgba8, Image_Layout_Type::rg16, Image_Layout_Type::rg8, Image_Layout_Type::r16, Image_Layout_Type::r8, Image_Layout_Type::rgba16_snorm, Image_Layout_Type::rgba8_snorm, Image_Layout_Type::rg16_snorm, Image_Layout_Type::rg8_snorm, Image_Layout_Type::r16_snorm, Image_Layout_Type::r8_snorm, Image_Layout_Type::rgba32i, Image_Layout_Type::rgba16i, Image_Layout_Type::rgba8i, Image_Layout_Type::rg32i, Image_Layout_Type::rg16i, Image_Layout_Type::rg8i, Image_Layout_Type::r32i, Image_Layout_Type::r16i, Image_Layout_Type::r8i, Image_Layout_Type::rgba32ui, Image_Layout_Type::rgba16ui, Image_Layout_Type::rgb10_a2ui, Image_Layout_Type::rgba8ui, Image_Layout_Type::rg32ui, Image_Layout_Type::rg16ui, Image_Layout_Type::rg8ui, Image_Layout_Type::r32ui, Image_Layout_Type::r16ui, Image_Layout_Type::r8ui}; Lexer_State const state_backup = _lexer.get_current_state(); constexpr i64 array_size = sizeof(qualifiers) / sizeof(Image_Layout_Type); for(i64 i = 0; i < array_size; ++i) { anton::String_View const string{stringify(qualifiers[i])}; anton::String7_View const string7{string.bytes_begin(), string.bytes_end()}; if(_lexer.match(string7, true)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Image_Layout_Qualifier(qualifiers[i], src)}; } } return nullptr; } Owning_Ptr<Pass_Stage_Declaration> try_pass_stage_declaration() { Lexer_State const state_backup = _lexer.get_current_state(); // Parse the attribute lists. We allow many attribute lists // to be present on a stage declaration. We merge the lists into // a single attribute array. Attribute_List attributes; while(true) { anton::Optional<Attribute_List> attributes_result = try_attribute_list(); if(!attributes_result) { break; } for(auto& attribute: attributes_result.value()) { attributes.emplace_back(ANTON_MOV(attribute)); } } Owning_Ptr return_type = try_type(); if(!return_type) { set_error(u8"expected type"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr pass = try_identifier(); if(!pass) { set_error(u8"expected pass name"); _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_scope_resolution)) { set_error(u8"expected '::' after pass name"); _lexer.restore_state(state_backup); return nullptr; } static constexpr anton::String7_View stage_types_strings[] = {stage_vertex, stage_fragment, stage_compute}; static constexpr Stage_Type stage_types[] = {Stage_Type::vertex, Stage_Type::fragment, Stage_Type::compute}; Stage_Type stage_type; { bool found = false; for(i64 i = 0; i < 3; ++i) { if(_lexer.match(stage_types_strings[i], true)) { stage_type = stage_types[i]; found = true; break; } } if(!found) { set_error(u8"expected stage type"); _lexer.restore_state(state_backup); return nullptr; } } anton::Optional<Parameter_List> parameter_list = try_function_param_list(); if(!parameter_list) { _lexer.restore_state(state_backup); return nullptr; } anton::Optional<Statement_List> statements = try_braced_statement_list(); if(!statements) { _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Pass_Stage_Declaration(ANTON_MOV(attributes), ANTON_MOV(return_type), ANTON_MOV(pass), stage_type, ANTON_MOV(parameter_list.value()), ANTON_MOV(statements.value()), src)}; } Owning_Ptr<Function_Declaration> try_function_declaration() { Lexer_State const state_backup = _lexer.get_current_state(); // Parse the attribute lists. We allow many attribute lists // to be present on a function declaration. We merge the lists // into a single attribute array. Attribute_List attributes; while(true) { anton::Optional<Attribute_List> attributes_result = try_attribute_list(); if(!attributes_result) { break; } for(auto& attribute: attributes_result.value()) { attributes.emplace_back(ANTON_MOV(attribute)); } } Owning_Ptr return_type = try_type(); if(!return_type) { set_error(u8"expected type"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr name = try_identifier(); if(!name) { set_error(u8"expected function name"); _lexer.restore_state(state_backup); return nullptr; } auto param_list = try_function_param_list(); if(!param_list) { _lexer.restore_state(state_backup); return nullptr; } anton::Optional<Statement_List> statements = try_braced_statement_list(); if(!statements) { _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Function_Declaration(ANTON_MOV(attributes), ANTON_MOV(return_type), ANTON_MOV(name), ANTON_MOV(param_list.value()), ANTON_MOV(statements.value()), src)}; } anton::Optional<Parameter_List> try_function_param_list() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(token_paren_open)) { set_error(u8"expected '('"); _lexer.restore_state(state_backup); return anton::null_optional; } if(_lexer.match(token_paren_close)) { return Parameter_List{}; } Parameter_List param_list; // Match parameters do { Owning_Ptr param = try_function_parameter(); if(param) { param_list.emplace_back(ANTON_MOV(param)); } else { _lexer.restore_state(state_backup); return anton::null_optional; } } while(_lexer.match(token_comma)); if(!_lexer.match(token_paren_close)) { set_error(u8"expected ')' after function parameter list"); _lexer.restore_state(state_backup); return anton::null_optional; } return ANTON_MOV(param_list); } Owning_Ptr<Function_Parameter_Node> try_function_parameter() { Lexer_State const state_backup = _lexer.get_current_state(); if(Owning_Ptr param_if = try_function_param_if()) { return param_if; } Owning_Ptr image_layout = try_image_layout_qualifier(); Owning_Ptr parameter_type = try_type(); if(!parameter_type) { set_error(u8"expected parameter type"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr identifier = try_identifier(); if(!identifier) { set_error(u8"expected parameter name"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr<Identifier> source; if(_lexer.match(kw_from, true)) { source = try_identifier(); if(!source) { set_error(u8"expected parameter source after 'from'"); _lexer.restore_state(state_backup); return nullptr; } } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Function_Parameter(ANTON_MOV(identifier), ANTON_MOV(parameter_type), ANTON_MOV(source), ANTON_MOV(image_layout), src)}; } Owning_Ptr<Function_Param_If> try_function_param_if() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_if, true)) { set_error(u8"expected 'if'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr condition = try_expression(); if(!condition) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr true_param = try_function_parameter(); if(!true_param) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_brace_close)) { set_error(u8"expected '}'"); _lexer.restore_state(state_backup); return nullptr; } if(_lexer.match(kw_else, true)) { if(Owning_Ptr param_if = try_function_param_if()) { return Owning_Ptr{ new Function_Param_If(ANTON_MOV(condition), ANTON_MOV(true_param), ANTON_MOV(param_if), src_info(state_backup, state_backup))}; } else { if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr false_param = try_function_parameter(); if(!false_param) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_brace_close)) { set_error(u8"expected '}'"); _lexer.restore_state(state_backup); return nullptr; } return Owning_Ptr{ new Function_Param_If(ANTON_MOV(condition), ANTON_MOV(true_param), ANTON_MOV(false_param), src_info(state_backup, state_backup))}; } } else { return Owning_Ptr{new Function_Param_If(ANTON_MOV(condition), ANTON_MOV(true_param), nullptr, src_info(state_backup, state_backup))}; } } // try_empty_statament // Match empty statement ';'. // bool try_empty_statement() { return _lexer.match(token_semicolon); } Owning_Ptr<Statement> try_statement() { if(Owning_Ptr block_statement = try_block_statement()) { return block_statement; } if(Owning_Ptr if_statement = try_if_statement()) { return if_statement; } if(Owning_Ptr switch_statement = try_switch_statement()) { return switch_statement; } if(Owning_Ptr for_statement = try_for_statement()) { return for_statement; } if(Owning_Ptr while_statement = try_while_statement()) { return while_statement; } if(Owning_Ptr do_while_statement = try_do_while_statement()) { return do_while_statement; } if(Owning_Ptr return_statement = try_return_statement()) { return return_statement; } if(Owning_Ptr break_statement = try_break_statement()) { return break_statement; } if(Owning_Ptr continue_statement = try_continue_statement()) { return continue_statement; } if(Owning_Ptr discard_statement = try_discard_statement()) { return discard_statement; } if(Owning_Ptr decl = try_variable_declaration()) { Source_Info const src = decl->source_info; Owning_Ptr decl_stmt{new Declaration_Statement(ANTON_MOV(decl), src)}; return decl_stmt; } if(Owning_Ptr decl = try_constant_declaration()) { Source_Info const src = decl->source_info; Owning_Ptr decl_stmt{new Declaration_Statement(ANTON_MOV(decl), src)}; return decl_stmt; } if(Owning_Ptr expr_stmt = try_expression_statement()) { return expr_stmt; } set_error(u8"expected a statement"); return nullptr; } // try_braced_statement_list // Match '{' statements '}' anton::Optional<Statement_List> try_braced_statement_list() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return anton::null_optional; } Statement_List body; while(true) { if(_lexer.match(token_brace_close)) { return {ANTON_MOV(body)}; } if(try_empty_statement()) { continue; } Owning_Ptr<Statement> statement = try_statement(); if(statement) { body.emplace_back(ANTON_MOV(statement)); continue; } _lexer.restore_state(state_backup); return anton::null_optional; } } Owning_Ptr<Type> try_type() { Lexer_State const state_backup = _lexer.get_current_state(); anton::String type_name; if(!_lexer.match_identifier(type_name)) { set_error(u8"expected type identifier"); return nullptr; } if(is_keyword(type_name)) { anton::String msg = u8"expected type name, got '" + type_name + "' instead"; set_error(msg, state_backup); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr<Type> base_type; if(anton::Optional<Builtin_GLSL_Type> res = enumify_builtin_glsl_type(type_name); res) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); base_type = Owning_Ptr{new Builtin_Type(res.value(), src)}; } else { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); base_type = Owning_Ptr{new User_Defined_Type(ANTON_MOV(type_name), src)}; } if(!_lexer.match(token_bracket_open)) { return base_type; } else { Owning_Ptr array_size = try_integer_literal(); if(!_lexer.match(token_bracket_close)) { set_error(u8"expected ']'"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); // We don't support nested array types (yet), so we don't continue checking for brackets. return Owning_Ptr{new Array_Type(ANTON_MOV(base_type), ANTON_MOV(array_size), src)}; } } Owning_Ptr<Block_Statement> try_block_statement() { Lexer_State const state_backup = _lexer.get_current_state(); anton::Optional<Statement_List> statements = try_braced_statement_list(); if(!statements) { _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Block_Statement(ANTON_MOV(statements.value()), src)}; } Owning_Ptr<If_Statement> try_if_statement() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_if, true)) { set_error(u8"expected 'if'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr condition = try_expression(); if(!condition) { _lexer.restore_state(state_backup); return nullptr; } anton::Optional<Statement_List> true_statements = try_braced_statement_list(); if(!true_statements) { _lexer.restore_state(state_backup); return nullptr; } Statement_List false_statements; if(_lexer.match(kw_else, true)) { if(Owning_Ptr if_statement = try_if_statement()) { false_statements.emplace_back(ANTON_MOV(if_statement)); } else { anton::Optional<Statement_List> statements = try_braced_statement_list(); if(!statements) { _lexer.restore_state(state_backup); return nullptr; } false_statements = ANTON_MOV(statements.value()); } } return Owning_Ptr{ new If_Statement(ANTON_MOV(condition), ANTON_MOV(true_statements.value()), ANTON_MOV(false_statements), src_info(state_backup, state_backup))}; } Owning_Ptr<Switch_Statement> try_switch_statement() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_switch, true)) { set_error(u8"expected 'switch'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr match_expression = try_expression(); if(!match_expression) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return nullptr; } anton::Array<Owning_Ptr<Case_Statement>> cases; while(true) { Lexer_State const case_state = _lexer.get_current_state(); if(_lexer.match(token_brace_close)) { break; } Expression_List labels; do { Lexer_State const label_state = _lexer.get_current_state(); if(_lexer.match(kw_default, true)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(label_state, end_state); labels.emplace_back(Owning_Ptr{new Default_Expression(src)}); } else if(Owning_Ptr literal = try_integer_literal()) { labels.emplace_back(ANTON_MOV(literal)); } else { _lexer.restore_state(state_backup); return nullptr; } } while(_lexer.match(token_comma)); if(!_lexer.match(token_arrow)) { set_error(u8"expected '=>'"_sv); _lexer.restore_state(state_backup); return nullptr; } anton::Optional<Statement_List> statements = try_braced_statement_list(); if(!statements) { _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(case_state, end_state); Owning_Ptr case_statement = Owning_Ptr{new Case_Statement(ANTON_MOV(labels), ANTON_MOV(statements.value()), src)}; cases.emplace_back(ANTON_MOV(case_statement)); } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Switch_Statement(ANTON_MOV(match_expression), ANTON_MOV(cases), src)}; } Owning_Ptr<For_Statement> try_for_statement() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_for, true)) { set_error("expected 'for'"); _lexer.restore_state(state_backup); return nullptr; } if(_lexer.match(token_paren_open)) { set_error("unexpected '(' after 'for'"); _lexer.restore_state(state_backup); return nullptr; } // Match variable Owning_Ptr<Variable_Declaration> variable_declaration; if(!_lexer.match(token_semicolon)) { Lexer_State const var_decl_state = _lexer.get_current_state(); Owning_Ptr var_type = try_type(); if(!var_type) { _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr var_name = try_identifier(); if(!var_name) { set_error("expected variable name"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr<Expression> initializer; if(_lexer.match(token_assign)) { initializer = try_expression(); if(!initializer) { _lexer.restore_state(state_backup); return nullptr; } } if(!_lexer.match(token_semicolon)) { set_error("expected ';' in 'for' statement"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(var_decl_state, end_state); variable_declaration = Owning_Ptr{new Variable_Declaration(ANTON_MOV(var_type), ANTON_MOV(var_name), ANTON_MOV(initializer), src)}; } Owning_Ptr<Expression> condition; if(!_lexer.match(token_semicolon)) { condition = try_expression(); if(!condition) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_semicolon)) { set_error("expected ';' in 'for' statement"); _lexer.restore_state(state_backup); return nullptr; } } Owning_Ptr post_expression = try_expression(); anton::Optional<Statement_List> statements = try_braced_statement_list(); if(!statements) { _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{ new For_Statement(ANTON_MOV(variable_declaration), ANTON_MOV(condition), ANTON_MOV(post_expression), ANTON_MOV(statements.value()), src)}; } Owning_Ptr<While_Statement> try_while_statement() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_while, true)) { set_error("expected 'while'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr condition = try_expression(); if(!condition) { _lexer.restore_state(state_backup); return nullptr; } anton::Optional<Statement_List> statements = try_braced_statement_list(); if(!statements) { _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new While_Statement(ANTON_MOV(condition), ANTON_MOV(statements.value()), src)}; } Owning_Ptr<Do_While_Statement> try_do_while_statement() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_do, true)) { set_error("expected 'do'"); _lexer.restore_state(state_backup); return nullptr; } anton::Optional<Statement_List> statements = try_braced_statement_list(); if(!statements) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(kw_while, true)) { set_error("expected 'while'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr condition = try_expression(); if(!condition) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_semicolon)) { set_error("expected ';' after do-while statement"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Do_While_Statement(ANTON_MOV(condition), ANTON_MOV(statements.value()), src)}; } Owning_Ptr<Return_Statement> try_return_statement() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_return, true)) { set_error("expected 'return'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr return_expression = try_expression(); if(!_lexer.match(token_semicolon)) { set_error("expected ';' after return statement"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Return_Statement(ANTON_MOV(return_expression), src)}; } Owning_Ptr<Break_Statement> try_break_statement() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_break, true)) { set_error(u8"expected 'break'"); _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_semicolon)) { set_error(u8"expected ';' after break statement"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Break_Statement(src)}; } Owning_Ptr<Continue_Statement> try_continue_statement() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_continue, true)) { set_error(u8"expected 'continue'"); _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_semicolon)) { set_error(u8"expected ';' after continue statement"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Continue_Statement(src)}; } Owning_Ptr<Discard_Statement> try_discard_statement() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_discard, true)) { set_error(u8"expected 'discard'"); _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_semicolon)) { set_error(u8"expected ';' after discard statement"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Discard_Statement(src)}; } Owning_Ptr<Expression_Statement> try_expression_statement() { Lexer_State const state_backup = _lexer.get_current_state(); Owning_Ptr expression = try_expression(); if(!expression) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_semicolon)) { set_error("expected ';' at the end of statement"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Expression_Statement(ANTON_MOV(expression), src)}; } Owning_Ptr<Expression> try_expression() { return try_assignment_expression(); } Owning_Ptr<Expression> try_assignment_expression() { Lexer_State const state_backup = _lexer.get_current_state(); Owning_Ptr lhs = try_binary_expression(); if(!lhs) { _lexer.restore_state(state_backup); return nullptr; } Lexer_State const op_state = _lexer.get_current_state(); Arithmetic_Assignment_Type type; bool is_direct = false; if(_lexer.match(token_assign)) { is_direct = true; } else if(_lexer.match(token_compound_plus)) { type = Arithmetic_Assignment_Type::plus; } else if(_lexer.match(token_compound_minus)) { type = Arithmetic_Assignment_Type::minus; } else if(_lexer.match(token_compound_multiply)) { type = Arithmetic_Assignment_Type::multiply; } else if(_lexer.match(token_compound_divide)) { type = Arithmetic_Assignment_Type::divide; } else if(_lexer.match(token_compound_remainder)) { type = Arithmetic_Assignment_Type::remainder; } else if(_lexer.match(token_compound_bit_lshift)) { type = Arithmetic_Assignment_Type::lshift; } else if(_lexer.match(token_compound_bit_rshift)) { type = Arithmetic_Assignment_Type::rshift; } else if(_lexer.match(token_compound_bit_and)) { type = Arithmetic_Assignment_Type::bit_and; } else if(_lexer.match(token_compound_bit_or)) { type = Arithmetic_Assignment_Type::bit_or; } else if(_lexer.match(token_compound_bit_xor)) { type = Arithmetic_Assignment_Type::bit_xor; } else { return lhs; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr rhs = try_assignment_expression(); if(!rhs) { _lexer.restore_state(state_backup); return nullptr; } if(is_direct) { return Owning_Ptr{new Assignment_Expression(ANTON_MOV(lhs), ANTON_MOV(rhs), src)}; } else { return Owning_Ptr{new Arithmetic_Assignment_Expression(type, ANTON_MOV(lhs), ANTON_MOV(rhs), src)}; } } // Owning_Ptr<Expression> try_elvis_expression() { // Lexer_State const state_backup = _lexer.get_current_state(); // Owning_Ptr cond = try_logic_or_expr(); // if(!cond) { // _lexer.restore_state(state_backup); // return nullptr; // } // if(!_lexer.match(token_question)) { // return cond; // } // // TODO: is using try_expression here correct? // Owning_Ptr true_expression = try_expression(); // if(!true_expression) { // _lexer.restore_state(state_backup); // return nullptr; // } // if(!_lexer.match(token_colon)) { // set_error(u8"expected ':'"); // _lexer.restore_state(state_backup); // return nullptr; // } // Owning_Ptr false_expression = try_expression(); // if(!false_expression) { // _lexer.restore_state(state_backup); // return nullptr; // } // Lexer_State const end_state = _lexer.get_current_state_no_skip(); // Source_Info const src = src_info(state_backup, end_state); // return Owning_Ptr{new Elvis_Expression(ANTON_MOV(cond), ANTON_MOV(true_expression), ANTON_MOV(false_expression), src)}; // } Owning_Ptr<Expression> try_binary_expression() { auto insert_node = [](Owning_Ptr<Expression> root, Owning_Ptr<Binary_Expression> node) -> Owning_Ptr<Expression> { auto get_precedence = [](Binary_Expression& expression) -> i32 { switch(expression.type) { case Binary_Expression_Type::logic_or: return 11; case Binary_Expression_Type::logic_xor: return 10; case Binary_Expression_Type::logic_and: return 9; case Binary_Expression_Type::equal: return 5; case Binary_Expression_Type::unequal: return 5; case Binary_Expression_Type::greater_than: return 4; case Binary_Expression_Type::less_than: return 4; case Binary_Expression_Type::greater_equal: return 4; case Binary_Expression_Type::less_equal: return 4; case Binary_Expression_Type::bit_or: return 8; case Binary_Expression_Type::bit_xor: return 7; case Binary_Expression_Type::bit_and: return 6; case Binary_Expression_Type::lshift: return 3; case Binary_Expression_Type::rshift: return 3; case Binary_Expression_Type::add: return 2; case Binary_Expression_Type::sub: return 2; case Binary_Expression_Type::mul: return 1; case Binary_Expression_Type::div: return 1; case Binary_Expression_Type::mod: return 1; } }; i32 const node_precedence = get_precedence(*node); Owning_Ptr<Expression>* insertion_node = &root; while(true) { if((**insertion_node).node_type != AST_Node_Type::binary_expression) { break; } Binary_Expression& expression = static_cast<Binary_Expression&>(**insertion_node); i32 const expression_precedence = get_precedence(expression); if(expression_precedence < node_precedence) { // Precedence is smaller insertion_node = &expression.rhs; } else { break; } } node->lhs = ANTON_MOV(*insertion_node); *insertion_node = ANTON_MOV(node); return root; }; Owning_Ptr<Expression> root = try_unary_expression(); if(!root) { return nullptr; } while(true) { Lexer_State const op_state = _lexer.get_current_state(); if(_lexer.match(token_compound_bit_and) || _lexer.match(token_compound_bit_or) || _lexer.match(token_compound_bit_xor) || _lexer.match(token_compound_bit_lshift) || _lexer.match(token_compound_bit_rshift) || _lexer.match(token_compound_remainder) || _lexer.match(token_compound_divide) || _lexer.match(token_compound_multiply) || _lexer.match(token_compound_plus) || _lexer.match(token_compound_minus)) { _lexer.restore_state(op_state); return root; } if(_lexer.match(token_logic_or)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::logic_or, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_logic_xor)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::logic_xor, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_logic_and)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::logic_and, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_bit_or)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::bit_or, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_bit_xor)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::bit_xor, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_bit_and)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::bit_and, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_bit_lshift)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::lshift, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_bit_rshift)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::rshift, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_equal)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::equal, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_not_equal)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::unequal, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_less_equal)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::less_equal, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_greater_equal)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::greater_equal, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_greater)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::greater_than, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_less)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::less_than, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_plus)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::add, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_minus)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::sub, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_multiply)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::mul, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_divide)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::div, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else if(_lexer.match(token_remainder)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(op_state, end_state); Owning_Ptr<Expression> rhs = try_unary_expression(); if(!rhs) { return nullptr; } Owning_Ptr expression{new Binary_Expression{Binary_Expression_Type::mod, nullptr, ANTON_MOV(rhs), src}}; root = insert_node(ANTON_MOV(root), ANTON_MOV(expression)); } else { break; } } return root; } Owning_Ptr<Expression> try_unary_expression() { Lexer_State const state_backup = _lexer.get_current_state(); if(_lexer.match(token_increment)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); if(Owning_Ptr expr = try_unary_expression()) { return Owning_Ptr{new Prefix_Increment_Expression(ANTON_MOV(expr), src)}; } else { _lexer.restore_state(state_backup); return nullptr; } } else if(_lexer.match(token_decrement)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); if(Owning_Ptr expr = try_unary_expression()) { return Owning_Ptr{new Prefix_Decrement_Expression(ANTON_MOV(expr), src)}; } else { _lexer.restore_state(state_backup); return nullptr; } } else if(_lexer.match(token_plus)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); if(Owning_Ptr expr = try_unary_expression()) { return Owning_Ptr{new Unary_Expression(Unary_Type::plus, ANTON_MOV(expr), src)}; } else { _lexer.restore_state(state_backup); return nullptr; } } else if(_lexer.match(token_minus)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); if(Owning_Ptr expr = try_unary_expression()) { return Owning_Ptr{new Unary_Expression(Unary_Type::minus, ANTON_MOV(expr), src)}; } else { _lexer.restore_state(state_backup); return nullptr; } } else if(_lexer.match(token_logic_not)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); if(Owning_Ptr expr = try_unary_expression()) { return Owning_Ptr{new Unary_Expression(Unary_Type::logic_not, ANTON_MOV(expr), src)}; } else { _lexer.restore_state(state_backup); return nullptr; } } else if(_lexer.match(token_bit_not)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); if(Owning_Ptr expr = try_unary_expression()) { return Owning_Ptr{new Unary_Expression(Unary_Type::bit_not, ANTON_MOV(expr), src)}; } else { _lexer.restore_state(state_backup); return nullptr; } } else { return try_postfix_expression(); } } Owning_Ptr<Expression> try_postfix_expression() { Lexer_State const state_backup = _lexer.get_current_state(); Owning_Ptr primary_expr = try_primary_expression(); if(!primary_expr) { _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr<Expression> expr = ANTON_MOV(primary_expr); while(true) { if(_lexer.match(token_dot)) { if(Owning_Ptr member_name = try_identifier()) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); expr = Owning_Ptr{new Member_Access_Expression(ANTON_MOV(expr), ANTON_MOV(member_name), src)}; } else { set_error(u8"expected member name"); _lexer.restore_state(state_backup); return nullptr; } } else if(_lexer.match(token_bracket_open)) { Owning_Ptr index = try_expression(); if(!index) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_bracket_close)) { set_error(u8"expected ']'"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); expr = Owning_Ptr{new Array_Access_Expression(ANTON_MOV(expr), ANTON_MOV(index), src)}; } else if(_lexer.match(token_increment)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); expr = Owning_Ptr{new Postfix_Increment_Expression(ANTON_MOV(expr), src)}; } else if(_lexer.match(token_decrement)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); expr = Owning_Ptr{new Postfix_Decrement_Expression(ANTON_MOV(expr), src)}; } else { break; } } return expr; } Owning_Ptr<Expression> try_primary_expression() { if(Owning_Ptr parenthesised_expression = try_paren_expr()) { return parenthesised_expression; } if(Owning_Ptr expr = try_reinterpret_expr()) { return expr; } if(Owning_Ptr expression_if = try_expression_if()) { return expression_if; } if(Owning_Ptr float_literal = try_float_literal()) { return float_literal; } if(Owning_Ptr integer_literal = try_integer_literal()) { return integer_literal; } if(Owning_Ptr bool_literal = try_bool_literal()) { return bool_literal; } if(Owning_Ptr function_call = try_function_call_expression()) { return function_call; } if(Owning_Ptr identifier_expression = try_identifier_expression()) { return identifier_expression; } return nullptr; } Owning_Ptr<Parenthesised_Expression> try_paren_expr() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(token_paren_open)) { set_error(u8"expected '('"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr paren_expression = try_expression(); if(!paren_expression) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_paren_close)) { set_error(u8"expected ')'"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Parenthesised_Expression(ANTON_MOV(paren_expression), src)}; } Owning_Ptr<Reinterpret_Expression> try_reinterpret_expr() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_reinterpret, true)) { set_error(u8"expected 'reinterpret'"); _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_angle_open)) { set_error(u8"expected '<'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr target_type = try_type(); if(!target_type) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_angle_close)) { set_error(u8"expected '>'"); _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_paren_open)) { set_error(u8"expected '('"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr source = try_expression(); if(!source) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_comma)) { set_error(u8"expected ','"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr index = try_expression(); if(!index) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_paren_close)) { set_error(u8"expected ')'"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Reinterpret_Expression{ANTON_MOV(target_type), ANTON_MOV(source), ANTON_MOV(index), src}}; } Owning_Ptr<Expression_If> try_expression_if() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(kw_if, true)) { set_error(u8"expected 'if'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr condition = try_expression(); if(!condition) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return nullptr; } if(_lexer.match(token_brace_close)) { set_error(u8"expected an expression before '}'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr true_expression = try_expression(); if(!true_expression) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_brace_close)) { set_error(u8"expected '}' after expression"); _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(kw_else, true)) { set_error(u8"expected an 'else' branch"); _lexer.restore_state(state_backup); return nullptr; } if(Owning_Ptr expression_if = try_expression_if()) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Expression_If(ANTON_MOV(condition), ANTON_MOV(true_expression), ANTON_MOV(expression_if), src)}; } else { if(!_lexer.match(token_brace_open)) { set_error(u8"expected '{'"); _lexer.restore_state(state_backup); return nullptr; } if(_lexer.match(token_brace_close)) { set_error(u8"expected an expression before '}'"); _lexer.restore_state(state_backup); return nullptr; } Owning_Ptr false_expression = try_expression(); if(!false_expression) { _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_brace_close)) { set_error(u8"expected '}' after expression"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Expression_If(ANTON_MOV(condition), ANTON_MOV(true_expression), ANTON_MOV(false_expression), src)}; } } Owning_Ptr<Function_Call_Expression> try_function_call_expression() { Lexer_State const state_backup = _lexer.get_current_state(); Owning_Ptr identifier = try_identifier(); if(!identifier) { set_error(u8"expected function name"); _lexer.restore_state(state_backup); return nullptr; } if(!_lexer.match(token_paren_open)) { set_error(u8"expected '(' after function name"); _lexer.restore_state(state_backup); return nullptr; } anton::Array<Owning_Ptr<Expression>> arguments; if(_lexer.match(token_paren_close)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Function_Call_Expression(ANTON_MOV(identifier), ANTON_MOV(arguments), src)}; } do { if(Owning_Ptr expression = try_expression()) { arguments.emplace_back(ANTON_MOV(expression)); } else { _lexer.restore_state(state_backup); return nullptr; } } while(_lexer.match(token_comma)); if(!_lexer.match(token_paren_close)) { set_error(u8"expected ')'"); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Function_Call_Expression(ANTON_MOV(identifier), ANTON_MOV(arguments), src)}; } Owning_Ptr<Float_Literal> try_float_literal() { Lexer_State const state_backup = _lexer.get_current_state(); anton::String number; if(char32 const next_char = _lexer.peek_next(); next_char == '-' || next_char == U'+') { number += next_char; _lexer.get_next(); } i64 pre_point_digits = 0; for(char32 next_char = _lexer.peek_next(); is_digit(next_char); ++pre_point_digits) { number += next_char; _lexer.get_next(); next_char = _lexer.peek_next(); } // A decimal number must not have leading 0 except when the number is 0 if(number.size_bytes() > 1 && number.data()[0] == '0') { _lexer.restore_state(state_backup); return nullptr; } if(pre_point_digits == 0) { number += '0'; } bool has_period = false; i64 post_point_digits = 0; if(_lexer.peek_next() == '.') { has_period = true; number += '.'; _lexer.get_next(); for(char32 next_char = _lexer.peek_next(); is_digit(next_char); ++post_point_digits) { number += next_char; _lexer.get_next(); next_char = _lexer.peek_next(); } if(post_point_digits == 0) { number += '0'; } } if(pre_point_digits == 0 && post_point_digits == 0) { set_error(u8"not a floating point constant", state_backup); _lexer.restore_state(state_backup); return nullptr; } bool has_e = false; if(char32 const e = _lexer.peek_next(); e == U'e' || e == U'E') { has_e = true; number += 'E'; _lexer.get_next(); if(char32 const sign = _lexer.peek_next(); sign == '-' || sign == U'+') { number += sign; _lexer.get_next(); } i64 e_digits = 0; for(char32 next_char = _lexer.peek_next(); is_digit(next_char); ++e_digits) { number += next_char; _lexer.get_next(); next_char = _lexer.peek_next(); } if(e_digits == 0) { set_error("exponent has no digits"); _lexer.restore_state(state_backup); return nullptr; } } if(!has_e && !has_period) { set_error(u8"not a floating point constant", state_backup); _lexer.restore_state(state_backup); return nullptr; } Float_Literal_Type type = Float_Literal_Type::f32; Lexer_State const suffix_backup = _lexer.get_current_state_no_skip(); anton::String suffix; for(char32 next = _lexer.peek_next(); is_identifier_character(next); next = _lexer.peek_next()) { suffix += next; _lexer.get_next(); } if(suffix == u8"d" || suffix == u8"D") { type = Float_Literal_Type::f64; } else if(suffix != u8"") { set_error(u8"invalid suffix '" + suffix + u8"' on floating point literal", suffix_backup); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Float_Literal(ANTON_MOV(number), type, src)}; } Owning_Ptr<Integer_Literal> try_integer_literal() { // Section 4.1.3 of The OpenGL Shading Language 4.60.7 states that integer literals are never negative. // Instead the leading '-' is always interpreted as a unary minus operator. We follow the same convention. Lexer_State const state_backup = _lexer.get_current_state(); // Binary literal bool const has_bin_prefix = _lexer.match(u8"0b") || _lexer.match(u8"0B"); if(has_bin_prefix) { anton::String out; while(is_binary_digit(_lexer.peek_next())) { char32 const digit = _lexer.get_next(); out += digit; } if(char32 const next = _lexer.peek_next(); is_digit(next)) { set_error(u8"invalid digit '" + anton::String::from_utf32(&next, 4) + u8"' in binary integer literal"); _lexer.restore_state(state_backup); return nullptr; } Integer_Literal_Type type = Integer_Literal_Type::i32; Lexer_State const suffix_backup = _lexer.get_current_state_no_skip(); anton::String suffix; for(char32 next = _lexer.peek_next(); is_identifier_character(next); next = _lexer.peek_next()) { suffix += next; _lexer.get_next(); } if(suffix == u8"u" || suffix == u8"U") { type = Integer_Literal_Type::u32; } else if(suffix != u8"") { set_error(u8"invalid suffix '" + suffix + u8"' on integer literal", suffix_backup); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Integer_Literal{ANTON_MOV(out), type, Integer_Literal_Base::bin, src}}; } // Octal literal bool const has_oct_prefix = _lexer.match(u8"0o") || _lexer.match(u8"0O"); if(has_oct_prefix) { anton::String out; while(is_octal_digit(_lexer.peek_next())) { char32 const digit = _lexer.get_next(); out += digit; } if(char32 const next = _lexer.peek_next(); is_digit(next)) { set_error(u8"invalid digit '" + anton::String::from_utf32(&next, 4) + u8"' in octal integer literal"); _lexer.restore_state(state_backup); return nullptr; } Integer_Literal_Type type = Integer_Literal_Type::i32; Lexer_State const suffix_backup = _lexer.get_current_state_no_skip(); anton::String suffix; for(char32 next = _lexer.peek_next(); is_identifier_character(next); next = _lexer.peek_next()) { suffix += next; _lexer.get_next(); } if(suffix == u8"u" || suffix == u8"U") { type = Integer_Literal_Type::u32; } else if(suffix != u8"") { set_error(u8"invalid suffix '" + suffix + u8"' on integer literal", suffix_backup); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Integer_Literal{ANTON_MOV(out), type, Integer_Literal_Base::oct, src}}; } // Hexadecimal literal bool const has_hex_prefix = _lexer.match(u8"0x") || _lexer.match(u8"0X"); if(has_hex_prefix) { anton::String out; while(is_hexadecimal_digit(_lexer.peek_next())) { char32 const digit = _lexer.get_next(); out += digit; } Integer_Literal_Type type = Integer_Literal_Type::i32; Lexer_State const suffix_backup = _lexer.get_current_state_no_skip(); anton::String suffix; for(char32 next = _lexer.peek_next(); is_identifier_character(next); next = _lexer.peek_next()) { suffix += next; _lexer.get_next(); } if(suffix == u8"u" || suffix == u8"U") { type = Integer_Literal_Type::u32; } else if(suffix != u8"") { set_error(u8"invalid suffix '" + suffix + u8"' on integer literal", suffix_backup); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Integer_Literal{ANTON_MOV(out), type, Integer_Literal_Base::hex, src}}; } // Decimal literal anton::String out; if(char32 const next = _lexer.peek_next(); !is_digit(next)) { set_error(u8"expected integer literal"); _lexer.restore_state(state_backup); return nullptr; } while(is_digit(_lexer.peek_next())) { char32 const digit = _lexer.get_next(); out += digit; } Integer_Literal_Type type = Integer_Literal_Type::i32; Lexer_State const suffix_backup = _lexer.get_current_state_no_skip(); anton::String suffix; for(char32 next = _lexer.peek_next(); is_identifier_character(next); next = _lexer.peek_next()) { suffix += next; _lexer.get_next(); } if(suffix == u8"u" || suffix == u8"U") { type = Integer_Literal_Type::u32; } else if(suffix != u8"") { set_error(u8"invalid suffix '" + suffix + "' on integer literal", suffix_backup); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Integer_Literal{ANTON_MOV(out), type, Integer_Literal_Base::dec, src}}; } Owning_Ptr<Bool_Literal> try_bool_literal() { Lexer_State const state_backup = _lexer.get_current_state(); if(_lexer.match(kw_true, true)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Bool_Literal(true, src)}; } else if(_lexer.match(kw_false, true)) { Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Bool_Literal(false, src)}; } else { set_error("expected bool literal"); return nullptr; } } Owning_Ptr<String_Literal> try_string_literal() { Lexer_State const state_backup = _lexer.get_current_state(); if(!_lexer.match(token_double_quote)) { set_error(u8"expected \""); return nullptr; } anton::String string; while(true) { char32 next_char = _lexer.peek_next(); if(next_char == U'\n') { // We disallow newlines inside string literals set_error(u8"newlines are not allowed in string literals"); _lexer.restore_state(state_backup); return nullptr; } else if(next_char == eof_char32) { set_error(u8"unexpected end of file"); _lexer.restore_state(state_backup); return nullptr; } else if(next_char == U'\\') { string += _lexer.get_next(); string += _lexer.get_next(); } else if(next_char == U'\"') { _lexer.get_next(); break; } else { string += next_char; _lexer.get_next(); } } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new String_Literal(ANTON_MOV(string), src)}; } Owning_Ptr<Identifier> try_identifier() { Lexer_State const state_backup = _lexer.get_current_state(); anton::String identifier; if(!_lexer.match_identifier(identifier)) { set_error(u8"expected an identifier"); _lexer.restore_state(state_backup); return nullptr; } if(is_keyword(identifier)) { anton::String msg = u8"keyword '" + identifier + "' may not be used as identifier"; set_error(msg, state_backup); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Identifier(ANTON_MOV(identifier), src)}; } Owning_Ptr<Identifier_Expression> try_identifier_expression() { Lexer_State const state_backup = _lexer.get_current_state(); anton::String identifier; if(!_lexer.match_identifier(identifier)) { set_error(u8"expected an identifier"); _lexer.restore_state(state_backup); return nullptr; } if(is_keyword(identifier)) { anton::String msg = u8"keyword '" + identifier + "' may not be used as identifier"; set_error(msg, state_backup); _lexer.restore_state(state_backup); return nullptr; } Lexer_State const end_state = _lexer.get_current_state_no_skip(); Source_Info const src = src_info(state_backup, end_state); return Owning_Ptr{new Identifier_Expression(ANTON_MOV(identifier), src)}; } }; anton::Expected<Declaration_List, Parse_Error> parse_source(anton::String_View const source_name, anton::String_View const source_code) { Parser parser(source_code, source_name); anton::Expected<Declaration_List, Parse_Error> ast = parser.build_ast(); return ast; } anton::Expected<Declaration_List, Parse_Error> parse_builtin_functions(anton::String_View const source_name, anton::String_View const source_code) { Parser parser(source_code, source_name); anton::Expected<Declaration_List, Parse_Error> ast = parser.parse_builtin_functions(); return ast; } } // namespace vush
42.303009
159
0.53683
kociap
dc088ec29b504b6cba126846e4f5513a380338bd
2,191
hpp
C++
ReactNativeFrontend/ios/Pods/boost/boost/geometry/index/detail/rtree/node/pairs.hpp
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
ios/Pods/boost-for-react-native/boost/geometry/index/detail/rtree/node/pairs.hpp
c7yrus/alyson-v3
5ad95a8f782f5f5d2fd543d44ca6a8b093395965
[ "Apache-2.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
ios/Pods/boost-for-react-native/boost/geometry/index/detail/rtree/node/pairs.hpp
c7yrus/alyson-v3
5ad95a8f782f5f5d2fd543d44ca6a8b093395965
[ "Apache-2.0" ]
1,343
2017-12-08T19:47:19.000Z
2022-03-26T11:31:36.000Z
// Boost.Geometry Index // // Pairs intended to be used internally in nodes. // // Copyright (c) 2011-2013 Adam Wulkiewicz, Lodz, Poland. // // 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_INDEX_DETAIL_RTREE_NODE_PAIRS_HPP #define BOOST_GEOMETRY_INDEX_DETAIL_RTREE_NODE_PAIRS_HPP #include <boost/move/move.hpp> namespace boost { namespace geometry { namespace index { namespace detail { namespace rtree { template <typename First, typename Pointer> class ptr_pair { public: typedef First first_type; typedef Pointer second_type; ptr_pair(First const& f, Pointer s) : first(f), second(s) {} //ptr_pair(ptr_pair const& p) : first(p.first), second(p.second) {} //ptr_pair & operator=(ptr_pair const& p) { first = p.first; second = p.second; return *this; } first_type first; second_type second; }; template <typename First, typename Pointer> inline ptr_pair<First, Pointer> make_ptr_pair(First const& f, Pointer s) { return ptr_pair<First, Pointer>(f, s); } // TODO: It this will be used, rename it to unique_ptr_pair and possibly use unique_ptr. template <typename First, typename Pointer> class exclusive_ptr_pair { BOOST_MOVABLE_BUT_NOT_COPYABLE(exclusive_ptr_pair) public: typedef First first_type; typedef Pointer second_type; exclusive_ptr_pair(First const& f, Pointer s) : first(f), second(s) {} // INFO - members aren't really moved! exclusive_ptr_pair(BOOST_RV_REF(exclusive_ptr_pair) p) : first(p.first), second(p.second) { p.second = 0; } exclusive_ptr_pair & operator=(BOOST_RV_REF(exclusive_ptr_pair) p) { first = p.first; second = p.second; p.second = 0; return *this; } first_type first; second_type second; }; template <typename First, typename Pointer> inline exclusive_ptr_pair<First, Pointer> make_exclusive_ptr_pair(First const& f, Pointer s) { return exclusive_ptr_pair<First, Pointer>(f, s); } }} // namespace detail::rtree }}} // namespace boost::geometry::index #endif // BOOST_GEOMETRY_INDEX_DETAIL_RTREE_NODE_PAIRS_HPP
30.430556
138
0.740301
Harshitha91
dc099f9300c0294a933f125597250addf2186707
5,273
cpp
C++
src/Objects/Spiral.cpp
heyjoeway/CuckySonic
122ccc7319d117b977b5c019cedc6de6951bfc49
[ "MIT" ]
1
2019-12-16T16:32:46.000Z
2019-12-16T16:32:46.000Z
src/Objects/Spiral.cpp
heyjoeway/CuckySonic
122ccc7319d117b977b5c019cedc6de6951bfc49
[ "MIT" ]
null
null
null
src/Objects/Spiral.cpp
heyjoeway/CuckySonic
122ccc7319d117b977b5c019cedc6de6951bfc49
[ "MIT" ]
1
2019-12-13T22:04:02.000Z
2019-12-13T22:04:02.000Z
#include <stdint.h> #include "../Level.h" #include "../Game.h" #include "../Log.h" #include "../MathUtil.h" //#define SPIRAL_OFFSET_FIX //Fixes the radius offset to scale properly static const uint8_t FlipAngleTable[] = { 0x00,0x00, 0x01,0x01,0x16,0x16,0x16,0x16,0x2C,0x2C, 0x2C,0x2C,0x42,0x42,0x42,0x42,0x58,0x58, 0x58,0x58,0x6E,0x6E,0x6E,0x6E,0x84,0x84, 0x84,0x84,0x9A,0x9A,0x9A,0x9A,0xB0,0xB0, 0xB0,0xB0,0xC6,0xC6,0xC6,0xC6,0xDC,0xDC, 0xDC,0xDC,0xF2,0xF2,0xF2,0xF2,0x01,0x01, 0x00,0x00, }; static const int8_t CosineTable[] = { 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 30, 30, 30, 30, 29, 29, 29, 29, 29, 28, 28, 28, 28, 27, 27, 27, 27, 26, 26, 26, 25, 25, 25, 24, 24, 24, 23, 23, 22, 22, 21, 21, 20, 20, 19, 18, 18, 17, 16, 16, 15, 14, 14, 13, 12, 12, 11, 10, 10, 9, 8, 8, 7, 6, 6, 5, 4, 4, 3, 2, 2, 1, 0, -1, -2, -2, -3, -4, -4, -5, -6, -7, -7, -8, -9, -9,-10,-10, -11,-11,-12,-12,-13,-14,-14,-15, -15,-16,-16,-17,-17,-18,-18,-19, -19,-19,-20,-21,-21,-22,-22,-23, -23,-24,-24,-25,-25,-26,-26,-27, -27,-28,-28,-28,-29,-29,-30,-30, -30,-31,-31,-31,-32,-32,-32,-33, -33,-33,-33,-34,-34,-34,-35,-35, -35,-35,-35,-35,-35,-35,-36,-36, -36,-36,-36,-36,-36,-36,-36,-37, -37,-37,-37,-37,-37,-37,-37,-37, -37,-37,-37,-37,-37,-37,-37,-37, -37,-37,-37,-37,-37,-37,-37,-37, -37,-37,-37,-37,-36,-36,-36,-36, -36,-36,-36,-35,-35,-35,-35,-35, -35,-35,-35,-34,-34,-34,-33,-33, -33,-33,-32,-32,-32,-31,-31,-31, -30,-30,-30,-29,-29,-28,-28,-28, -27,-27,-26,-26,-25,-25,-24,-24, -23,-23,-22,-22,-21,-21,-20,-19, -19,-18,-18,-17,-16,-16,-15,-14, -14,-13,-12,-11,-11,-10, -9, -8, -7, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10, 10, 11, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 24, 25, 25, 25, 25, 26, 26, 26, 26, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 30, 30, 30, 30, 30, 30, 30, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, }; void ObjSpiral(OBJECT *object) //Also MTZ cylinder { //Set our routine based off of our subtype if (object->routine == 0) { object->routine = (object->subtype < 0x80) ? 1 : 2; object->widthPixels = 208; } switch (object->routine) { case 1: //EHZ Spiral { for (size_t i = 0; i < gLevel->playerList.size(); i++) { //Get the player PLAYER *player = gLevel->playerList[i]; if (object->playerContact[i].standing == false) //Not already on the spiral { if (player->status.inAir) //Don't run on corkscrew if in mid-air continue; //Check if we're at the sides of the spiral if (!player->status.shouldNotFall) //If not standing on an object (already on a spiral) { //Check if we're at the sides of the spiral int16_t xOff = player->x.pos - object->x.pos; if (player->xVel >= 0) //Moving in from the left { if (xOff < -0xD0 || xOff > -0xC0) continue; } else //Moving in from the right { if (xOff < 0xC0 || xOff > 0xD0) continue; } } else { //Check if we're at the sides of the spiral int16_t xOff = player->x.pos - object->x.pos; if (player->xVel >= 0) //Moving in from the left { if (xOff < -0xC0 || xOff > -0xB0) continue; } else //Moving in from the right { if (xOff < 0xB0 || xOff > 0xC0) continue; } } //Check if we're near the bottom and not already on an object controlling us int16_t yOff = player->y.pos - object->y.pos - 0x10; if (yOff < 0 || yOff >= 0x30 || player->objectControl.disableOurMovement) continue; //Set the player to run on the spiral player->AttachToObject(object, i); } else { //Running on the corkscrew if (!(abs(player->inertia) < 0x600 || player->status.inAir)) //If not slowed down or jumped off { int16_t xOff = player->x.pos - object->x.pos + 0xD0; if (xOff >= 0 && xOff < 0x1A0) //If still on the spiral { //Move across the spiral if (player->status.shouldNotFall) //If still running on the spiral { //Set our Y-position int8_t cosine = CosineTable[xOff]; #ifndef SPIRAL_OFFSET_FIX int16_t yOff = player->yRadius - 19; #else int16_t yOff = ((player->yRadius - 19) * cosine) / (cosine < 0 ? 37 : 32); #endif player->y.pos = (object->y.pos + cosine) - yOff; //Set our flip angle player->flipAngle = FlipAngleTable[(xOff / 8) & 0x3F]; } continue; } } //Fall off player->status.shouldNotFall = false; object->playerContact[i].standing = false; player->flipsRemaining = false; player->flipSpeed = 4; } } break; } case 2: //MTZ Cylinder { //None break; } } object->UnloadOffscreen(object->x.pos); }
26.497487
100
0.535938
heyjoeway
dc0a628b5b8c4cefbfa6addb955d5241025331d7
1,731
cc
C++
Codeforces/252 Division 2/Problem D/D.cc
VastoLorde95/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
170
2017-07-25T14:47:29.000Z
2022-01-26T19:16:31.000Z
Codeforces/252 Division 2/Problem D/D.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
null
null
null
Codeforces/252 Division 2/Problem D/D.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
55
2017-07-28T06:17:33.000Z
2021-10-31T03:06:22.000Z
#include<cstdio> #include<iostream> #include<cmath> #include<algorithm> #include<cstring> #include<map> #include<set> #include<vector> #include<utility> #include<queue> #include<stack> #define sd(x) scanf("%d",&x) #define sd2(x,y) scanf("%d%d",&x,&y) #define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z) #define fi first #define se second #define pb(x) push_back(x) #define mp(x,y) make_pair(x,y) #define LET(x, a) __typeof(a) x(a) #define foreach(it, v) for(LET(it, v.begin()); it != v.end(); it++) #define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); #define __ freopen("input.txt", "r", stdin);freopen("output.txt", "w", stdout); #define tr(x) cout<<x<<endl; #define tr2(x,y) cout<<x<<" "<<y<<endl; #define tr3(x,y,z) cout<<x<<" "<<y<<" "<<z<<endl; #define tr4(w,x,y,z) cout<<w<<" "<<x<<" "<<y<<" "<<z<<endl; using namespace std; int n, p[3001], v[3001], m, cnt; void visit(int cur){ if(v[cur]) return; v[cur] = 1; visit(p[cur]); return; } int main(){ sd(n); for(int i = 1; i <= n; i++){ sd(p[i]); } sd(m); for(int i = 1; i <= n; i++){ if(!v[i]){ visit(i); cnt++; } } memset(v, 0, sizeof v); m = n - m; // tr(cnt); printf("%d\n", abs(m-cnt)); if(m < cnt){ visit(1); for(int i = 2; i <= n and cnt > m; i++){ if(!v[i]){ visit(i); printf("%d %d ", 1, i); cnt--; } } } else if(m > cnt){ for(int i = 1; i <= n and m > cnt; i++){ vector<int> pos(n+1, -1); int cur = 0; for(int j = p[i]; j != i; j = p[j]) pos[j] = cur++; pos[i] = cur; cur = 0; for(int j = i+1; j <= n and m > cnt; j++){ if(pos[j] >= cur){ printf("%d %d ", i, j); m--; cur = pos[j]+1; swap(p[i], p[j]); } } } } return 0; }
18.612903
79
0.514731
VastoLorde95
dc0ddd3dc12fe6d5070d300b9baf89cb9ff7d362
1,436
cpp
C++
Cpp_Projects/HP_Calculator/hp_rechner.cpp
EderLukas/Portfolio
1c9adef3435129d26d3c6275a79ed363bf062e8f
[ "MIT" ]
null
null
null
Cpp_Projects/HP_Calculator/hp_rechner.cpp
EderLukas/Portfolio
1c9adef3435129d26d3c6275a79ed363bf062e8f
[ "MIT" ]
null
null
null
Cpp_Projects/HP_Calculator/hp_rechner.cpp
EderLukas/Portfolio
1c9adef3435129d26d3c6275a79ed363bf062e8f
[ "MIT" ]
null
null
null
/* * source code: hp_rechner.cpp * author: Lukas Eder * date: 28.12.2017 * * Descr.: * Grundlegende Rechnungen von Addition, Subtraktion, Multiplikation und Division nach dem HP-Rechner-Model. */ #include "hpFunktionen.h" #include <iostream> using namespace std; // Hauptprogramm int main() { // Variablen double resultat = 0.0, input1 = 0.0, input2 = 0.0; char menu = ' ', rep = ' '; // Titel cout << "***** HP-RECHNER *****\n" << endl; do { menu = menue(menu); // Input durch user if (rep == 'c') { input1 = resultat; } else { cout << "\nVariable 1:" << endl; cin >> input1; } cout << "Variable 2:" << endl; cin >> input2; // Berechnungen switch (menu) { case '+': resultat = addition(input1, input2); break; case '-': resultat = subtraktion(input1, input2); break; case '*': resultat = multiplikation(input1, input2); break; case '/': resultat = division(input1, input2); break; default: cout << "ERROR!" << endl; break; } // Output cout << "\n" << input1 << " " << menu << " " << input2 << " = " << resultat << endl; //Programmrepetition cout << "\n" << "y\tNeue Rechnung\n" << "c\tmit altem Resultat fortfahren\n" << "q\tBeenden\n\n" <<"Ihre Wahl:" << endl; cin >> rep; } while (rep != 'q'); cout << "\nWiedersehen!" << endl; }
18.894737
109
0.533426
EderLukas
dc0ee3e12e145c6957d7534a82041d2733c608e8
38,320
hpp
C++
include/armadillo_bits/wrapper_lapack.hpp
embarktrucks/armadillo-code
edfce747962f8ad508db660caa3892ed1a4069f8
[ "Apache-2.0" ]
16
2021-03-14T16:30:32.000Z
2022-03-18T13:41:53.000Z
include/armadillo_bits/wrapper_lapack.hpp
sinmx/armadillo
1314e433b09a77455647e84375292a2b0a16ac94
[ "Apache-2.0" ]
1
2018-01-08T09:16:37.000Z
2018-02-28T15:43:40.000Z
include/armadillo_bits/wrapper_lapack.hpp
sinmx/armadillo
1314e433b09a77455647e84375292a2b0a16ac94
[ "Apache-2.0" ]
4
2020-03-08T14:04:50.000Z
2020-12-03T08:51:04.000Z
// Copyright 2008-2016 Conrad Sanderson (http://conradsanderson.id.au) // Copyright 2008-2016 National ICT Australia (NICTA) // // 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. // ------------------------------------------------------------------------ #ifdef ARMA_USE_LAPACK //! \namespace lapack namespace for LAPACK functions namespace lapack { template<typename eT> inline void getrf(blas_int* m, blas_int* n, eT* a, blas_int* lda, blas_int* ipiv, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgetrf)(m, n, (T*)a, lda, ipiv, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgetrf)(m, n, (T*)a, lda, ipiv, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_cgetrf)(m, n, (T*)a, lda, ipiv, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zgetrf)(m, n, (T*)a, lda, ipiv, info); } } template<typename eT> inline void getri(blas_int* n, eT* a, blas_int* lda, blas_int* ipiv, eT* work, blas_int* lwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgetri)(n, (T*)a, lda, ipiv, (T*)work, lwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgetri)(n, (T*)a, lda, ipiv, (T*)work, lwork, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_cgetri)(n, (T*)a, lda, ipiv, (T*)work, lwork, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zgetri)(n, (T*)a, lda, ipiv, (T*)work, lwork, info); } } template<typename eT> inline void trtri(char* uplo, char* diag, blas_int* n, eT* a, blas_int* lda, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_strtri)(uplo, diag, n, (T*)a, lda, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dtrtri)(uplo, diag, n, (T*)a, lda, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_ctrtri)(uplo, diag, n, (T*)a, lda, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_ztrtri)(uplo, diag, n, (T*)a, lda, info); } } template<typename eT> inline void geev(char* jobvl, char* jobvr, blas_int* N, eT* a, blas_int* lda, eT* wr, eT* wi, eT* vl, blas_int* ldvl, eT* vr, blas_int* ldvr, eT* work, blas_int* lwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgeev)(jobvl, jobvr, N, (T*)a, lda, (T*)wr, (T*)wi, (T*)vl, ldvl, (T*)vr, ldvr, (T*)work, lwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgeev)(jobvl, jobvr, N, (T*)a, lda, (T*)wr, (T*)wi, (T*)vl, ldvl, (T*)vr, ldvr, (T*)work, lwork, info); } } template<typename eT> inline void cx_geev(char* jobvl, char* jobvr, blas_int* N, eT* a, blas_int* lda, eT* w, eT* vl, blas_int* ldvl, eT* vr, blas_int* ldvr, eT* work, blas_int* lwork, typename eT::value_type* rwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_supported_complex_float<eT>::value) { typedef float T; typedef typename std::complex<T> cx_T; arma_fortran(arma_cgeev)(jobvl, jobvr, N, (cx_T*)a, lda, (cx_T*)w, (cx_T*)vl, ldvl, (cx_T*)vr, ldvr, (cx_T*)work, lwork, (T*)rwork, info); } else if(is_supported_complex_double<eT>::value) { typedef double T; typedef typename std::complex<T> cx_T; arma_fortran(arma_zgeev)(jobvl, jobvr, N, (cx_T*)a, lda, (cx_T*)w, (cx_T*)vl, ldvl, (cx_T*)vr, ldvr, (cx_T*)work, lwork, (T*)rwork, info); } } template<typename eT> inline void syev(char* jobz, char* uplo, blas_int* n, eT* a, blas_int* lda, eT* w, eT* work, blas_int* lwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_ssyev)(jobz, uplo, n, (T*)a, lda, (T*)w, (T*)work, lwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dsyev)(jobz, uplo, n, (T*)a, lda, (T*)w, (T*)work, lwork, info); } } template<typename eT> inline void syevd(char* jobz, char* uplo, blas_int* n, eT* a, blas_int* lda, eT* w, eT* work, blas_int* lwork, blas_int* iwork, blas_int* liwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_ssyevd)(jobz, uplo, n, (T*)a, lda, (T*)w, (T*)work, lwork, iwork, liwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dsyevd)(jobz, uplo, n, (T*)a, lda, (T*)w, (T*)work, lwork, iwork, liwork, info); } } template<typename eT> inline void heev ( char* jobz, char* uplo, blas_int* n, eT* a, blas_int* lda, typename eT::value_type* w, eT* work, blas_int* lwork, typename eT::value_type* rwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_supported_complex_float<eT>::value) { typedef float T; typedef typename std::complex<T> cx_T; arma_fortran(arma_cheev)(jobz, uplo, n, (cx_T*)a, lda, (T*)w, (cx_T*)work, lwork, (T*)rwork, info); } else if(is_supported_complex_double<eT>::value) { typedef double T; typedef typename std::complex<T> cx_T; arma_fortran(arma_zheev)(jobz, uplo, n, (cx_T*)a, lda, (T*)w, (cx_T*)work, lwork, (T*)rwork, info); } } template<typename eT> inline void heevd ( char* jobz, char* uplo, blas_int* n, eT* a, blas_int* lda, typename eT::value_type* w, eT* work, blas_int* lwork, typename eT::value_type* rwork, blas_int* lrwork, blas_int* iwork, blas_int* liwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_supported_complex_float<eT>::value) { typedef float T; typedef typename std::complex<T> cx_T; arma_fortran(arma_cheevd)(jobz, uplo, n, (cx_T*)a, lda, (T*)w, (cx_T*)work, lwork, (T*)rwork, lrwork, iwork, liwork, info); } else if(is_supported_complex_double<eT>::value) { typedef double T; typedef typename std::complex<T> cx_T; arma_fortran(arma_zheevd)(jobz, uplo, n, (cx_T*)a, lda, (T*)w, (cx_T*)work, lwork, (T*)rwork, lrwork, iwork, liwork, info); } } template<typename eT> inline void ggev ( char* jobvl, char* jobvr, blas_int* n, eT* a, blas_int* lda, eT* b, blas_int* ldb, eT* alphar, eT* alphai, eT* beta, eT* vl, blas_int* ldvl, eT* vr, blas_int* ldvr, eT* work, blas_int* lwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sggev)(jobvl, jobvr, n, (T*)a, lda, (T*)b, ldb, (T*)alphar, (T*)alphai, (T*)beta, (T*)vl, ldvl, (T*)vr, ldvr, (T*)work, lwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dggev)(jobvl, jobvr, n, (T*)a, lda, (T*)b, ldb, (T*)alphar, (T*)alphai, (T*)beta, (T*)vl, ldvl, (T*)vr, ldvr, (T*)work, lwork, info); } } template<typename eT> inline void cx_ggev ( char* jobvl, char* jobvr, blas_int* n, eT* a, blas_int* lda, eT* b, blas_int* ldb, eT* alpha, eT* beta, eT* vl, blas_int* ldvl, eT* vr, blas_int* ldvr, eT* work, blas_int* lwork, typename eT::value_type* rwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_supported_complex_float<eT>::value) { typedef float T; typedef typename std::complex<T> cx_T; arma_fortran(arma_cggev)(jobvl, jobvr, n, (cx_T*)a, lda, (cx_T*)b, ldb, (cx_T*)alpha, (cx_T*)beta, (cx_T*)vl, ldvl, (cx_T*)vr, ldvr, (cx_T*)work, lwork, (T*)rwork, info); } else if(is_supported_complex_double<eT>::value) { typedef double T; typedef typename std::complex<T> cx_T; arma_fortran(arma_zggev)(jobvl, jobvr, n, (cx_T*)a, lda, (cx_T*)b, ldb, (cx_T*)alpha, (cx_T*)beta, (cx_T*)vl, ldvl, (cx_T*)vr, ldvr, (cx_T*)work, lwork, (T*)rwork, info); } } template<typename eT> inline void potrf(char* uplo, blas_int* n, eT* a, blas_int* lda, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_spotrf)(uplo, n, (T*)a, lda, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dpotrf)(uplo, n, (T*)a, lda, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_cpotrf)(uplo, n, (T*)a, lda, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zpotrf)(uplo, n, (T*)a, lda, info); } } template<typename eT> inline void potri(char* uplo, blas_int* n, eT* a, blas_int* lda, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_spotri)(uplo, n, (T*)a, lda, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dpotri)(uplo, n, (T*)a, lda, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_cpotri)(uplo, n, (T*)a, lda, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zpotri)(uplo, n, (T*)a, lda, info); } } template<typename eT> inline void geqrf(blas_int* m, blas_int* n, eT* a, blas_int* lda, eT* tau, eT* work, blas_int* lwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgeqrf)(m, n, (T*)a, lda, (T*)tau, (T*)work, lwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgeqrf)(m, n, (T*)a, lda, (T*)tau, (T*)work, lwork, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_cgeqrf)(m, n, (T*)a, lda, (T*)tau, (T*)work, lwork, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zgeqrf)(m, n, (T*)a, lda, (T*)tau, (T*)work, lwork, info); } } template<typename eT> inline void orgqr(blas_int* m, blas_int* n, blas_int* k, eT* a, blas_int* lda, eT* tau, eT* work, blas_int* lwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sorgqr)(m, n, k, (T*)a, lda, (T*)tau, (T*)work, lwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dorgqr)(m, n, k, (T*)a, lda, (T*)tau, (T*)work, lwork, info); } } template<typename eT> inline void ungqr(blas_int* m, blas_int* n, blas_int* k, eT* a, blas_int* lda, eT* tau, eT* work, blas_int* lwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_supported_complex_float<eT>::value) { typedef float T; arma_fortran(arma_cungqr)(m, n, k, (T*)a, lda, (T*)tau, (T*)work, lwork, info); } else if(is_supported_complex_double<eT>::value) { typedef double T; arma_fortran(arma_zungqr)(m, n, k, (T*)a, lda, (T*)tau, (T*)work, lwork, info); } } template<typename eT> inline void gesvd ( char* jobu, char* jobvt, blas_int* m, blas_int* n, eT* a, blas_int* lda, eT* s, eT* u, blas_int* ldu, eT* vt, blas_int* ldvt, eT* work, blas_int* lwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgesvd)(jobu, jobvt, m, n, (T*)a, lda, (T*)s, (T*)u, ldu, (T*)vt, ldvt, (T*)work, lwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgesvd)(jobu, jobvt, m, n, (T*)a, lda, (T*)s, (T*)u, ldu, (T*)vt, ldvt, (T*)work, lwork, info); } } template<typename T> inline void cx_gesvd ( char* jobu, char* jobvt, blas_int* m, blas_int* n, std::complex<T>* a, blas_int* lda, T* s, std::complex<T>* u, blas_int* ldu, std::complex<T>* vt, blas_int* ldvt, std::complex<T>* work, blas_int* lwork, T* rwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<T>::value == false )); arma_type_check(( is_supported_blas_type< std::complex<T> >::value == false )); if(is_float<T>::value) { typedef float bT; arma_fortran(arma_cgesvd) ( jobu, jobvt, m, n, (std::complex<bT>*)a, lda, (bT*)s, (std::complex<bT>*)u, ldu, (std::complex<bT>*)vt, ldvt, (std::complex<bT>*)work, lwork, (bT*)rwork, info ); } else if(is_double<T>::value) { typedef double bT; arma_fortran(arma_zgesvd) ( jobu, jobvt, m, n, (std::complex<bT>*)a, lda, (bT*)s, (std::complex<bT>*)u, ldu, (std::complex<bT>*)vt, ldvt, (std::complex<bT>*)work, lwork, (bT*)rwork, info ); } } template<typename eT> inline void gesdd ( char* jobz, blas_int* m, blas_int* n, eT* a, blas_int* lda, eT* s, eT* u, blas_int* ldu, eT* vt, blas_int* ldvt, eT* work, blas_int* lwork, blas_int* iwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgesdd)(jobz, m, n, (T*)a, lda, (T*)s, (T*)u, ldu, (T*)vt, ldvt, (T*)work, lwork, iwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgesdd)(jobz, m, n, (T*)a, lda, (T*)s, (T*)u, ldu, (T*)vt, ldvt, (T*)work, lwork, iwork, info); } } template<typename T> inline void cx_gesdd ( char* jobz, blas_int* m, blas_int* n, std::complex<T>* a, blas_int* lda, T* s, std::complex<T>* u, blas_int* ldu, std::complex<T>* vt, blas_int* ldvt, std::complex<T>* work, blas_int* lwork, T* rwork, blas_int* iwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<T>::value == false )); arma_type_check(( is_supported_blas_type< std::complex<T> >::value == false )); if(is_float<T>::value) { typedef float bT; arma_fortran(arma_cgesdd) ( jobz, m, n, (std::complex<bT>*)a, lda, (bT*)s, (std::complex<bT>*)u, ldu, (std::complex<bT>*)vt, ldvt, (std::complex<bT>*)work, lwork, (bT*)rwork, iwork, info ); } else if(is_double<T>::value) { typedef double bT; arma_fortran(arma_zgesdd) ( jobz, m, n, (std::complex<bT>*)a, lda, (bT*)s, (std::complex<bT>*)u, ldu, (std::complex<bT>*)vt, ldvt, (std::complex<bT>*)work, lwork, (bT*)rwork, iwork, info ); } } template<typename eT> inline void gesv(blas_int* n, blas_int* nrhs, eT* a, blas_int* lda, blas_int* ipiv, eT* b, blas_int* ldb, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgesv)(n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgesv)(n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_cgesv)(n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zgesv)(n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } } template<typename eT> inline void gesvx(char* fact, char* trans, blas_int* n, blas_int* nrhs, eT* a, blas_int* lda, eT* af, blas_int* ldaf, blas_int* ipiv, char* equed, eT* r, eT* c, eT* b, blas_int* ldb, eT* x, blas_int* ldx, eT* rcond, eT* ferr, eT* berr, eT* work, blas_int* iwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgesvx)(fact, trans, n, nrhs, (T*)a, lda, (T*)af, ldaf, ipiv, equed, (T*)r, (T*)c, (T*)b, ldb, (T*)x, ldx, (T*)rcond, (T*)ferr, (T*)berr, (T*)work, iwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgesvx)(fact, trans, n, nrhs, (T*)a, lda, (T*)af, ldaf, ipiv, equed, (T*)r, (T*)c, (T*)b, ldb, (T*)x, ldx, (T*)rcond, (T*)ferr, (T*)berr, (T*)work, iwork, info); } } template<typename T, typename eT> inline void cx_gesvx(char* fact, char* trans, blas_int* n, blas_int* nrhs, eT* a, blas_int* lda, eT* af, blas_int* ldaf, blas_int* ipiv, char* equed, T* r, T* c, eT* b, blas_int* ldb, eT* x, blas_int* ldx, T* rcond, T* ferr, T* berr, eT* work, T* rwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_supported_complex_float<eT>::value) { typedef float pod_T; typedef std::complex<float> cx_T; arma_fortran(arma_cgesvx)(fact, trans, n, nrhs, (cx_T*)a, lda, (cx_T*)af, ldaf, ipiv, equed, (pod_T*)r, (pod_T*)c, (cx_T*)b, ldb, (cx_T*)x, ldx, (pod_T*)rcond, (pod_T*)ferr, (pod_T*)berr, (cx_T*)work, (pod_T*)rwork, info); } else if(is_supported_complex_double<eT>::value) { typedef double pod_T; typedef std::complex<double> cx_T; arma_fortran(arma_zgesvx)(fact, trans, n, nrhs, (cx_T*)a, lda, (cx_T*)af, ldaf, ipiv, equed, (pod_T*)r, (pod_T*)c, (cx_T*)b, ldb, (cx_T*)x, ldx, (pod_T*)rcond, (pod_T*)ferr, (pod_T*)berr, (cx_T*)work, (pod_T*)rwork, info); } } template<typename eT> inline void gels(char* trans, blas_int* m, blas_int* n, blas_int* nrhs, eT* a, blas_int* lda, eT* b, blas_int* ldb, eT* work, blas_int* lwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgels)(trans, m, n, nrhs, (T*)a, lda, (T*)b, ldb, (T*)work, lwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgels)(trans, m, n, nrhs, (T*)a, lda, (T*)b, ldb, (T*)work, lwork, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_cgels)(trans, m, n, nrhs, (T*)a, lda, (T*)b, ldb, (T*)work, lwork, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zgels)(trans, m, n, nrhs, (T*)a, lda, (T*)b, ldb, (T*)work, lwork, info); } } template<typename eT> inline void gelsd(blas_int* m, blas_int* n, blas_int* nrhs, eT* a, blas_int* lda, eT* b, blas_int* ldb, eT* S, eT* rcond, blas_int* rank, eT* work, blas_int* lwork, blas_int* iwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgelsd)(m, n, nrhs, (T*)a, lda, (T*)b, ldb, (T*)S, (T*)rcond, rank, (T*)work, lwork, iwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgelsd)(m, n, nrhs, (T*)a, lda, (T*)b, ldb, (T*)S, (T*)rcond, rank, (T*)work, lwork, iwork, info); } } template<typename T> inline void cx_gelsd(blas_int* m, blas_int* n, blas_int* nrhs, std::complex<T>* a, blas_int* lda, std::complex<T>* b, blas_int* ldb, T* S, T* rcond, blas_int* rank, std::complex<T>* work, blas_int* lwork, T* rwork, blas_int* iwork, blas_int* info) { typedef typename std::complex<T> eT; arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_supported_complex_float<eT>::value) { typedef float pod_T; typedef std::complex<float> cx_T; arma_fortran(arma_cgelsd)(m, n, nrhs, (cx_T*)a, lda, (cx_T*)b, ldb, (pod_T*)S, (pod_T*)rcond, rank, (cx_T*)work, lwork, (pod_T*)rwork, iwork, info); } else if(is_supported_complex_double<eT>::value) { typedef double pod_T; typedef std::complex<double> cx_T; arma_fortran(arma_zgelsd)(m, n, nrhs, (cx_T*)a, lda, (cx_T*)b, ldb, (pod_T*)S, (pod_T*)rcond, rank, (cx_T*)work, lwork, (pod_T*)rwork, iwork, info); } } template<typename eT> inline void trtrs(char* uplo, char* trans, char* diag, blas_int* n, blas_int* nrhs, const eT* a, blas_int* lda, eT* b, blas_int* ldb, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_strtrs)(uplo, trans, diag, n, nrhs, (T*)a, lda, (T*)b, ldb, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dtrtrs)(uplo, trans, diag, n, nrhs, (T*)a, lda, (T*)b, ldb, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_ctrtrs)(uplo, trans, diag, n, nrhs, (T*)a, lda, (T*)b, ldb, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_ztrtrs)(uplo, trans, diag, n, nrhs, (T*)a, lda, (T*)b, ldb, info); } } template<typename eT> inline void gees(char* jobvs, char* sort, void* select, blas_int* n, eT* a, blas_int* lda, blas_int* sdim, eT* wr, eT* wi, eT* vs, blas_int* ldvs, eT* work, blas_int* lwork, blas_int* bwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgees)(jobvs, sort, select, n, (T*)a, lda, sdim, (T*)wr, (T*)wi, (T*)vs, ldvs, (T*)work, lwork, bwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgees)(jobvs, sort, select, n, (T*)a, lda, sdim, (T*)wr, (T*)wi, (T*)vs, ldvs, (T*)work, lwork, bwork, info); } } template<typename T> inline void cx_gees(char* jobvs, char* sort, void* select, blas_int* n, std::complex<T>* a, blas_int* lda, blas_int* sdim, std::complex<T>* w, std::complex<T>* vs, blas_int* ldvs, std::complex<T>* work, blas_int* lwork, T* rwork, blas_int* bwork, blas_int* info) { arma_type_check(( is_supported_blas_type<T>::value == false )); arma_type_check(( is_supported_blas_type< std::complex<T> >::value == false )); if(is_float<T>::value) { typedef float bT; typedef std::complex<bT> cT; arma_fortran(arma_cgees)(jobvs, sort, select, n, (cT*)a, lda, sdim, (cT*)w, (cT*)vs, ldvs, (cT*)work, lwork, (bT*)rwork, bwork, info); } else if(is_double<T>::value) { typedef double bT; typedef std::complex<bT> cT; arma_fortran(arma_zgees)(jobvs, sort, select, n, (cT*)a, lda, sdim, (cT*)w, (cT*)vs, ldvs, (cT*)work, lwork, (bT*)rwork, bwork, info); } } template<typename eT> inline void trsyl(char* transa, char* transb, blas_int* isgn, blas_int* m, blas_int* n, const eT* a, blas_int* lda, const eT* b, blas_int* ldb, eT* c, blas_int* ldc, eT* scale, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_strsyl)(transa, transb, isgn, m, n, (T*)a, lda, (T*)b, ldb, (T*)c, ldc, (T*)scale, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dtrsyl)(transa, transb, isgn, m, n, (T*)a, lda, (T*)b, ldb, (T*)c, ldc, (T*)scale, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_ctrsyl)(transa, transb, isgn, m, n, (T*)a, lda, (T*)b, ldb, (T*)c, ldc, (float*)scale, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_ztrsyl)(transa, transb, isgn, m, n, (T*)a, lda, (T*)b, ldb, (T*)c, ldc, (double*)scale, info); } } template<typename eT> inline void sytrf(char* uplo, blas_int* n, eT* a, blas_int* lda, blas_int* ipiv, eT* work, blas_int* lwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_ssytrf)(uplo, n, (T*)a, lda, ipiv, (T*)work, lwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dsytrf)(uplo, n, (T*)a, lda, ipiv, (T*)work, lwork, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_csytrf)(uplo, n, (T*)a, lda, ipiv, (T*)work, lwork, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zsytrf)(uplo, n, (T*)a, lda, ipiv, (T*)work, lwork, info); } } template<typename eT> inline void sytri(char* uplo, blas_int* n, eT* a, blas_int* lda, blas_int* ipiv, eT* work, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_ssytri)(uplo, n, (T*)a, lda, ipiv, (T*)work, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dsytri)(uplo, n, (T*)a, lda, ipiv, (T*)work, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_csytri)(uplo, n, (T*)a, lda, ipiv, (T*)work, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zsytri)(uplo, n, (T*)a, lda, ipiv, (T*)work, info); } } template<typename eT> inline void gges ( char* jobvsl, char* jobvsr, char* sort, void* selctg, blas_int* n, eT* a, blas_int* lda, eT* b, blas_int* ldb, blas_int* sdim, eT* alphar, eT* alphai, eT* beta, eT* vsl, blas_int* ldvsl, eT* vsr, blas_int* ldvsr, eT* work, blas_int* lwork, eT* bwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgges)(jobvsl, jobvsr, sort, selctg, n, (T*)a, lda, (T*)b, ldb, sdim, (T*)alphar, (T*)alphai, (T*)beta, (T*)vsl, ldvsl, (T*)vsr, ldvsr, (T*)work, lwork, (T*)bwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgges)(jobvsl, jobvsr, sort, selctg, n, (T*)a, lda, (T*)b, ldb, sdim, (T*)alphar, (T*)alphai, (T*)beta, (T*)vsl, ldvsl, (T*)vsr, ldvsr, (T*)work, lwork, (T*)bwork, info); } } template<typename eT> inline void cx_gges ( char* jobvsl, char* jobvsr, char* sort, void* selctg, blas_int* n, eT* a, blas_int* lda, eT* b, blas_int* ldb, blas_int* sdim, eT* alpha, eT* beta, eT* vsl, blas_int* ldvsl, eT* vsr, blas_int* ldvsr, eT* work, blas_int* lwork, typename eT::value_type* rwork, typename eT::value_type* bwork, blas_int* info ) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_supported_complex_float<eT>::value) { typedef float T; typedef typename std::complex<T> cx_T; arma_fortran(arma_cgges)(jobvsl, jobvsr, sort, selctg, n, (cx_T*)a, lda, (cx_T*)b, ldb, sdim, (cx_T*)alpha, (cx_T*)beta, (cx_T*)vsl, ldvsl, (cx_T*)vsr, ldvsr, (cx_T*)work, lwork, (T*)rwork, (T*)bwork, info); } else if(is_supported_complex_double<eT>::value) { typedef double T; typedef typename std::complex<T> cx_T; arma_fortran(arma_zgges)(jobvsl, jobvsr, sort, selctg, n, (cx_T*)a, lda, (cx_T*)b, ldb, sdim, (cx_T*)alpha, (cx_T*)beta, (cx_T*)vsl, ldvsl, (cx_T*)vsr, ldvsr, (cx_T*)work, lwork, (T*)rwork, (T*)bwork, info); } } template<typename eT> inline typename get_pod_type<eT>::result lange(char* norm, blas_int* m, blas_int* n, eT* a, blas_int* lda, typename get_pod_type<eT>::result* work) { arma_type_check(( is_supported_blas_type<eT>::value == false )); typedef typename get_pod_type<eT>::result out_T; if(is_float<eT>::value) { typedef float pod_T; typedef float T; return out_T( arma_fortran(arma_slange)(norm, m, n, (T*)a, lda, (pod_T*)work) ); } else if(is_double<eT>::value) { typedef double pod_T; typedef double T; return out_T( arma_fortran(arma_dlange)(norm, m, n, (T*)a, lda, (pod_T*)work) ); } else if(is_supported_complex_float<eT>::value) { typedef float pod_T; typedef std::complex<float> T; return out_T( arma_fortran(arma_clange)(norm, m, n, (T*)a, lda, (pod_T*)work) ); } else if(is_supported_complex_double<eT>::value) { typedef double pod_T; typedef std::complex<double> T; return out_T( arma_fortran(arma_zlange)(norm, m, n, (T*)a, lda, (pod_T*)work) ); } } template<typename eT> inline void gecon(char* norm, blas_int* n, eT* a, blas_int* lda, eT* anorm, eT* rcond, eT* work, blas_int* iwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgecon)(norm, n, (T*)a, lda, (T*)anorm, (T*)rcond, (T*)work, iwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgecon)(norm, n, (T*)a, lda, (T*)anorm, (T*)rcond, (T*)work, iwork, info); } } template<typename T> inline void cx_gecon(char* norm, blas_int* n, std::complex<T>* a, blas_int* lda, T* anorm, T* rcond, std::complex<T>* work, T* rwork, blas_int* info) { typedef typename std::complex<T> eT; arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_supported_complex_float<eT>::value) { typedef float pod_T; typedef typename std::complex<T> cx_T; arma_fortran(arma_cgecon)(norm, n, (cx_T*)a, lda, (pod_T*)anorm, (pod_T*)rcond, (cx_T*)work, (pod_T*)rwork, info); } else if(is_supported_complex_double<eT>::value) { typedef double pod_T; typedef typename std::complex<T> cx_T; arma_fortran(arma_zgecon)(norm, n, (cx_T*)a, lda, (pod_T*)anorm, (pod_T*)rcond, (cx_T*)work, (pod_T*)rwork, info); } } inline blas_int laenv(blas_int* ispec, char* name, char* opts, blas_int* n1, blas_int* n2, blas_int* n3, blas_int* n4) { return arma_fortran(arma_ilaenv)(ispec, name, opts, n1, n2, n3, n4); } template<typename eT> inline void sytrs(char* uplo, blas_int* n, blas_int* nrhs, eT* a, blas_int* lda, blas_int* ipiv, eT* b, blas_int* ldb, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_ssytrs)(uplo, n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dsytrs)(uplo, n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_csytrs)(uplo, n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zsytrs)(uplo, n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } } template<typename eT> inline void getrs(char* trans, blas_int* n, blas_int* nrhs, eT* a, blas_int* lda, blas_int* ipiv, eT* b, blas_int* ldb, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sgetrs)(trans, n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dgetrs)(trans, n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } else if(is_supported_complex_float<eT>::value) { typedef std::complex<float> T; arma_fortran(arma_cgetrs)(trans, n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } else if(is_supported_complex_double<eT>::value) { typedef std::complex<double> T; arma_fortran(arma_zgetrs)(trans, n, nrhs, (T*)a, lda, ipiv, (T*)b, ldb, info); } } template<typename eT> inline void lahqr(blas_int* wantt, blas_int* wantz, blas_int* n, blas_int* ilo, blas_int* ihi, eT* h, blas_int* ldh, eT* wr, eT* wi, blas_int* iloz, blas_int* ihiz, eT* z, blas_int* ldz, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_slahqr)(wantt, wantz, n, ilo, ihi, (T*)h, ldh, (T*)wr, (T*)wi, iloz, ihiz, (T*)z, ldz, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dlahqr)(wantt, wantz, n, ilo, ihi, (T*)h, ldh, (T*)wr, (T*)wi, iloz, ihiz, (T*)z, ldz, info); } } template<typename eT> inline void stedc(char* compz, blas_int* n, eT* d, eT* e, eT* z, blas_int* ldz, eT* work, blas_int* lwork, blas_int* iwork, blas_int* liwork, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_sstedc)(compz, n, (T*)d, (T*)e, (T*)z, ldz, (T*)work, lwork, iwork, liwork, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dstedc)(compz, n, (T*)d, (T*)e, (T*)z, ldz, (T*)work, lwork, iwork, liwork, info); } } template<typename eT> inline void trevc(char* side, char* howmny, blas_int* select, blas_int* n, eT* t, blas_int* ldt, eT* vl, blas_int* ldvl, eT* vr, blas_int* ldvr, blas_int* mm, blas_int* m, eT* work, blas_int* info) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_strevc)(side, howmny, select, n, (T*)t, ldt, (T*)vl, ldvl, (T*)vr, ldvr, mm, m, (T*)work, info); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dtrevc)(side, howmny, select, n, (T*)t, ldt, (T*)vl, ldvl, (T*)vr, ldvr, mm, m, (T*)work, info); } } template<typename eT> inline void larnv(blas_int* idist, blas_int* iseed, blas_int* n, eT* x) { arma_type_check(( is_supported_blas_type<eT>::value == false )); if(is_float<eT>::value) { typedef float T; arma_fortran(arma_slarnv)(idist, iseed, n, (T*)x); } else if(is_double<eT>::value) { typedef double T; arma_fortran(arma_dlarnv)(idist, iseed, n, (T*)x); } } } #endif
29.91413
268
0.582777
embarktrucks
dc133148e87e81cf79dcc080817d4377684ab185
12,250
hh
C++
third_party/OpenMesh-8.1/src/OpenMesh/Tools/Subdivider/Adaptive/Composite/RuleInterfaceT.hh
hporro/grafica_cpp
1427bb6e8926b44be474b906e9f52cca77b3df9d
[ "MIT" ]
62
2020-11-06T17:29:24.000Z
2022-03-21T19:21:16.000Z
third_party/OpenMesh-8.1/src/OpenMesh/Tools/Subdivider/Adaptive/Composite/RuleInterfaceT.hh
hporro/grafica_cpp
1427bb6e8926b44be474b906e9f52cca77b3df9d
[ "MIT" ]
134
2017-02-25T20:47:43.000Z
2022-03-14T06:54:58.000Z
third_party/OpenMesh-8.1/src/OpenMesh/Tools/Subdivider/Adaptive/Composite/RuleInterfaceT.hh
hporro/grafica_cpp
1427bb6e8926b44be474b906e9f52cca77b3df9d
[ "MIT" ]
6
2021-02-19T07:20:19.000Z
2021-12-27T09:07:27.000Z
/* ========================================================================= * * * * OpenMesh * * Copyright (c) 2001-2015, RWTH-Aachen University * * Department of Computer Graphics and Multimedia * * All rights reserved. * * www.openmesh.org * * * *---------------------------------------------------------------------------* * This file is part of OpenMesh. * *---------------------------------------------------------------------------* * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * * * 1. Redistributions of source code must retain the above copyright notice, * * this list of conditions and the following disclaimer. * * * * 2. Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * * * 3. Neither the name of the copyright holder nor the names of its * * contributors may be used to endorse or promote products derived from * * this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER * * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * * ========================================================================= */ //============================================================================= // // CLASS RuleInterfaceT // //============================================================================= #ifndef OPENMESH_SUBDIVIDER_ADAPTIVE_RULEINTERFACET_HH #define OPENMESH_SUBDIVIDER_ADAPTIVE_RULEINTERFACET_HH //== INCLUDES ================================================================= #include <string> #include <OpenMesh/Tools/Subdivider/Adaptive/Composite/CompositeTraits.hh> //== NAMESPACE ================================================================ namespace OpenMesh { // BEGIN_NS_OPENMESH namespace Subdivider { // BEGIN_NS_SUBDIVIDER namespace Adaptive { // BEGIN_NS_ADAPTIVE //== FORWARDS ================================================================= template <typename M> class CompositeT; template <typename M> class RuleInterfaceT; //== CLASS DEFINITION ========================================================= // ---------------------------------------------------------------------------- /** Handle template for adaptive composite subdividion rules * \internal * * Use typed handle of a rule, e.g. Tvv3<MyMesh>::Handle. */ template < typename R > struct RuleHandleT : public BaseHandle { explicit RuleHandleT(int _idx=-1) : BaseHandle(_idx) {} typedef R Rule; operator bool() const { return is_valid(); } }; /** Defines the method type() (RuleInterfaceT::type()) and the * typedefs Self and Handle. */ #define COMPOSITE_RULE( classname, mesh_type ) \ protected:\ friend class CompositeT<mesh_type>; \ public: \ const char *type() const override { return #classname; } \ typedef classname<mesh_type> Self; \ typedef RuleHandleT< Self > Handle // ---------------------------------------------------------------------------- /** Base class for adaptive composite subdivision rules * \see class CompositeT */ template <typename M> class RuleInterfaceT { public: typedef M Mesh; typedef RuleInterfaceT<M> Self; typedef RuleHandleT< Self > Rule; typedef typename M::Scalar scalar_t; protected: /// Default constructor RuleInterfaceT(Mesh& _mesh) : mesh_(_mesh),prev_rule_(nullptr),subdiv_rule_(nullptr),subdiv_type_(0),number_(0),n_rules_(0) {}; public: /// Destructor virtual ~RuleInterfaceT() {}; /// Returns the name of the rule. /// Use define COMPOSITE_RULE to overload this function in a derived class. virtual const char *type() const = 0; public: /// \name Raise item //@{ /// Raise item to target state \c _target_state. virtual void raise(typename M::FaceHandle& _fh, state_t _target_state) { if (mesh_.data(_fh).state() < _target_state) { update(_fh, _target_state); mesh_.data(_fh).inc_state(); } } virtual void raise(typename M::EdgeHandle& _eh, state_t _target_state) { if (mesh_.data(_eh).state() < _target_state) { update(_eh, _target_state); mesh_.data(_eh).inc_state(); } } virtual void raise(typename M::VertexHandle& _vh, state_t _target_state) { if (mesh_.data(_vh).state() < _target_state) { update(_vh, _target_state); mesh_.data(_vh).inc_state(); } } //@} void update(typename M::FaceHandle& _fh, state_t _target_state) { typename M::FaceHandle opp_fh; while (mesh_.data(_fh).state() < _target_state - 1) { prev_rule()->raise(_fh, _target_state - 1); } // Don't use unflipped / unfinal faces!!! if (subdiv_type() == 3) { if (mesh_.face_handle(mesh_.opposite_halfedge_handle(mesh_.halfedge_handle(_fh))).is_valid()) { while (!mesh_.data(_fh).final()) { opp_fh = mesh_.face_handle(mesh_.opposite_halfedge_handle(mesh_.halfedge_handle(_fh))); assert (mesh_.data(_fh).state() >= mesh_.data(opp_fh).state()); // different states: raise other face if (mesh_.data(_fh).state() > mesh_.data(opp_fh).state()){ // raise opposite face prev_rule()->raise(opp_fh, _target_state - 1); } else { // equal states // flip edge // typename M::EdgeHandle eh(mesh_.edge_handle(mesh_.halfedge_handle(_fh))); // if (mesh_.is_flip_ok(eh)) { // std::cout << "Flipping Edge...\n"; // mesh_.flip(eh); // mesh_.data(_fh).set_final(); // mesh_.data(opp_fh).set_final(); // } // else { // std::cout << "Flip not okay.\n"; // } } } } else { // mesh_.data(_fh).set_final(); } // std::cout << "Raising Face to Level " // << _target_state // << " with " // << type() // << ".\n"; } assert( subdiv_type() != 4 || mesh_.data(_fh).final() || _target_state%n_rules() == (subdiv_rule()->number() + 1)%n_rules() ); typename M::FaceEdgeIter fe_it; typename M::FaceVertexIter fv_it; typename M::EdgeHandle eh; typename M::VertexHandle vh; std::vector<typename M::FaceHandle> face_vector; face_vector.clear(); if (_target_state > 1) { for (fe_it = mesh_.fe_iter(_fh); fe_it.is_valid(); ++fe_it) { eh = *fe_it; prev_rule()->raise(eh, _target_state - 1); } for (fv_it = mesh_.fv_iter(_fh); fv_it.is_valid(); ++fv_it) { vh = *fv_it; prev_rule()->raise(vh, _target_state - 1); } } } void update(typename M::EdgeHandle& _eh, state_t _target_state) { state_t state(mesh_.data(_eh).state()); // raise edge to correct state if (state + 1 < _target_state && _target_state > 0) { prev_rule()->raise(_eh, _target_state - 1); } typename M::VertexHandle vh; typename M::FaceHandle fh; if (_target_state > 1) { vh = mesh_.to_vertex_handle(mesh_.halfedge_handle(_eh, 0)); prev_rule()->raise(vh, _target_state - 1); vh = mesh_.to_vertex_handle(mesh_.halfedge_handle(_eh, 1)); prev_rule()->raise(vh, _target_state - 1); fh = mesh_.face_handle(mesh_.halfedge_handle(_eh, 0)); if (fh.is_valid()) prev_rule()->raise(fh, _target_state - 1); fh = mesh_.face_handle(mesh_.halfedge_handle(_eh, 1)); if (fh.is_valid()) prev_rule()->raise(fh, _target_state - 1); } } void update(typename M::VertexHandle& _vh, state_t _target_state) { state_t state(mesh_.data(_vh).state()); // raise vertex to correct state if (state + 1 < _target_state) { prev_rule()->raise(_vh, _target_state - 1); } std::vector<typename M::HalfedgeHandle> halfedge_vector; halfedge_vector.clear(); typename M::VertexOHalfedgeIter voh_it; typename M::EdgeHandle eh; typename M::FaceHandle fh; if (_target_state > 1) { for (voh_it = mesh_.voh_iter(_vh); voh_it.is_valid(); ++voh_it) { halfedge_vector.push_back(*voh_it); } while ( !halfedge_vector.empty() ) { eh = mesh_.edge_handle(halfedge_vector.back()); halfedge_vector.pop_back(); prev_rule()->raise(eh, _target_state - 1); } for (voh_it = mesh_.voh_iter(_vh); voh_it.is_valid(); ++voh_it) { halfedge_vector.push_back(*voh_it); } while ( !halfedge_vector.empty() ) { fh = mesh_.face_handle(halfedge_vector.back()); halfedge_vector.pop_back(); if (fh.is_valid()) prev_rule()->raise(fh, _target_state - 1); } } } public: /// Type of split operation, if it is a topological operator int subdiv_type() const { return subdiv_type_; } /// Position in rule sequence int number() const { return number_; } /// \name Parameterization of rule //@{ /// Set coefficient - ignored by non-parameterized rules. virtual void set_coeff( scalar_t _coeff ) { coeff_ = _coeff; } /// Get coefficient - ignored by non-parameterized rules. scalar_t coeff() const { return coeff_; } //@} protected: void set_prev_rule(Self*& _p) { prev_rule_ = _p; } Self* prev_rule() { return prev_rule_; } void set_subdiv_rule(Self*& _n) { subdiv_rule_ = _n; } Self* subdiv_rule() const { return subdiv_rule_; } void set_number(int _n) { number_ = _n; } void set_n_rules(int _n) { n_rules_ = _n; } int n_rules() const { return n_rules_; } void set_subdiv_type(int _n) { assert(_n == 3 || _n == 4); subdiv_type_ = _n; } friend class CompositeT<M>; protected: Mesh& mesh_; private: Self* prev_rule_; Self* subdiv_rule_; int subdiv_type_; int number_; int n_rules_; scalar_t coeff_; private: // Noncopyable RuleInterfaceT(const RuleInterfaceT&); RuleInterfaceT& operator=(const RuleInterfaceT&); }; //============================================================================= } // END_NS_ADAPTIVE } // END_NS_SUBDIVIDER } // END_NS_OPENMESH //============================================================================= #endif // OPENMESH_SUBDIVIDER_ADAPTIVE_RULEINTERFACET_HH defined //=============================================================================
30.397022
129
0.533224
hporro
dc17e129762729e809cefe6f33c1e5dcee550e89
217
hh
C++
Include/Zion/Log.hh
zionmultiplayer/Client
291c027c4011cb1ab207c9b394fb5f4b1da8652c
[ "MIT" ]
4
2022-02-08T07:04:49.000Z
2022-02-09T23:43:49.000Z
Include/Zion/Log.hh
zionmultiplayer/Client
291c027c4011cb1ab207c9b394fb5f4b1da8652c
[ "MIT" ]
null
null
null
Include/Zion/Log.hh
zionmultiplayer/Client
291c027c4011cb1ab207c9b394fb5f4b1da8652c
[ "MIT" ]
null
null
null
#pragma once namespace Zion { class Log { public: static void Open(const char *filename); static void Close(); static void Write(const char *format, ...); }; };
18.083333
55
0.520737
zionmultiplayer
dc19b4bf11e668d5cf6fc8dd48356bd945c17f06
34,710
cpp
C++
src/AC3DPlugins/obj8_import.cpp
den-rain/xptools
4c39da8d44a4a92e9efb2538844d433496b38f07
[ "X11", "MIT" ]
null
null
null
src/AC3DPlugins/obj8_import.cpp
den-rain/xptools
4c39da8d44a4a92e9efb2538844d433496b38f07
[ "X11", "MIT" ]
null
null
null
src/AC3DPlugins/obj8_import.cpp
den-rain/xptools
4c39da8d44a4a92e9efb2538844d433496b38f07
[ "X11", "MIT" ]
null
null
null
/* * Copyright (c) 2007, Laminar Research. * * 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. * */ /** OBJ7 exporter for AC3D **/ /* ANDY SEZ ABOUT MATERIALS: There's: Prototype int ac_palette_get_new_material_index(ACMaterialTemplate *m) if this material exists then return it's index otherwise, allocate a new one, copy the contents from m and return it's index This calls: Prototype Boolean material_compare(ACMaterial *m, ACMaterialTemplate *m2) That checks each part of the material. So- you'll get a whole new material if there's the slightest difference. If you only need RGB, use: Prototype long rgb_to_index(long rgbcol) This only checks the rgb of existing materials - not all the other attributes. */ #include "TclStubs.h" #include "ac_plugin.h" #include "Undoable.h" #ifdef Boolean #undef Boolean #endif #include "obj8_import.h" #include "ac_utils.h" #include "XObjDefs.h" #include "XObjReadWrite.h" #include "ObjConvert.h" #include "obj_model.h" #include "obj_anim.h" #include "obj_panel.h" #include <list> using std::list; // Set this to 1 and each change in culling or flat/smooth shading pops another object. #define OBJ_FOR_ALL_ATTRS 0 /*************************************************************************************************** * OBJ8 IMPORT AND EXPORT ***************************************************************************************************/ ACObject * do_obj8_load(char *filename) { ACObject * group_obj = NULL; ACObject * lod_obj = NULL; ACObject * stuff_obj = NULL; list<ACObject *> anim_obj; char * tex_full_name = NULL; int tex_id = -1; char * panel_full_name = NULL; int panel_id = -1; // char anim_cmd[1024]; string anim_dat; // char * anim_old_cmd; // Point3 key1, key2; int i; material_template_t current_material; current_material.rgb.r = 1.0; current_material.rgb.g = 1.0; current_material.rgb.b = 1.0; current_material.ambient.r = 0.2; current_material.ambient.g = 0.2; current_material.ambient.b = 0.2; current_material.specular.r = 0.0; current_material.specular.g = 0.0; current_material.specular.b = 0.0; current_material.emissive.r = 0.0; current_material.emissive.g = 0.0; current_material.emissive.b = 0.0; current_material.shininess = 128; current_material.transparency = 0.0; int default_material = ac_palette_get_new_material_index(&current_material); Point3 p3; char strbuf[256]; // obj8.lods.clear(); XObj8 obj8; if (!XObj8Read(filename, obj8)) { XObj obj7; if (!XObjRead(filename, obj7)) return NULL; Obj7ToObj8(obj7, obj8); } set_std_panel(); for (int n = 0; n < obj8.regions.size(); ++n) { add_sub_panel(obj8.regions[n].left,obj8.regions[n].bottom,obj8.regions[n].right,obj8.regions[n].top); } group_obj = new_object(OBJECT_GROUP); string fname(filename); string::size_type p = fname.find_last_of("\\/"); string justName = (p == fname.npos) ? fname : fname.substr(p+1); string justPath = fname.substr(0,p+1); string::size_type p2 = obj8.texture.find_last_of("\\/:"); string texName = (p2 == obj8.texture.npos) ? obj8.texture : obj8.texture.substr(p2+1); if (texName.size() > 4) texName.erase(texName.size()-4); string texPath; if(p2 != obj8.texture.npos) texPath = obj8.texture.substr(0,p2+1); string texNameBmp = texName + ".bmp"; string texNamePng = texName + ".png"; string texNameDds = texName + ".dds"; string texNamePvr = texName + ".pvr"; string texPathBmp = texPath + texNameBmp; string texPathPng = texPath + texNamePng; string texPathDds = texPath + texNameDds; string texPathPvr = texPath + texNamePvr; const char * panel_names[] = { "cockpit_3d/-PANELS-/Panel_Preview.png", "cockpit_3d/-PANELS-/Panel.png", "cockpit_3d/-PANELS-/Panel_Airliner.png", "cockpit_3d/-PANELS-/Panel_Fighter.png", "cockpit_3d/-PANELS-/Panel_Glider.png", "cockpit_3d/-PANELS-/Panel_Helo.png", "cockpit_3d/-PANELS-/Panel_Autogyro.png", "cockpit_3d/-PANELS-/Panel_General_IFR.png", "cockpit_3d/-PANELS-/Panel_Autogyro_Twin.png", "cockpit_3d/-PANELS-/Panel_Fighter_IFR.png", "cockpit/-PANELS-/Panel_Preview.png", "cockpit/-PANELS-/Panel.png", "cockpit/-PANELS-/Panel_Airliner.png", "cockpit/-PANELS-/Panel_Fighter.png", "cockpit/-PANELS-/Panel_Glider.png", "cockpit/-PANELS-/Panel_Helo.png", "cockpit/-PANELS-/Panel_Autogyro.png", "cockpit/-PANELS-/Panel_General_IFR.png", "cockpit/-PANELS-/Panel_Autogyro_Twin.png", "cockpit/-PANELS-/Panel_Fighter_IFR.png", 0 }; bool has_cockpit_cmd = false; bool has_cockpit_reg = false; for(vector<XObjLOD8>::iterator lod = obj8.lods.begin(); lod != obj8.lods.end(); ++lod) for(vector<XObjCmd8>::iterator cmd = lod->cmds.begin(); cmd != lod->cmds.end(); ++cmd) { if (cmd->cmd == attr_Tex_Cockpit) has_cockpit_cmd = true; if (cmd->cmd == attr_Tex_Cockpit_Subregion) has_cockpit_reg = true; } object_set_name(group_obj,(char *) justName.c_str()); if (!texName.empty()) { if (tex_id == -1) tex_full_name = search_texture(filename, (char *) texNamePvr.c_str()); if (tex_full_name != NULL) tex_id = add_new_texture_opt(tex_full_name,tex_full_name); if (tex_id == -1) tex_full_name = search_texture(filename, (char *) texNamePng.c_str()); if (tex_full_name != NULL) tex_id = add_new_texture_opt(tex_full_name,tex_full_name); if (tex_id == -1) tex_full_name = search_texture(filename, (char *) texNameBmp.c_str()); if (tex_full_name != NULL) tex_id = add_new_texture_opt(tex_full_name,tex_full_name); if (tex_id == -1) tex_full_name = search_texture(filename, (char *) texNameDds.c_str()); if (tex_full_name != NULL) tex_id = add_new_texture_opt(tex_full_name,tex_full_name); if (tex_id == -1) tex_full_name = search_texture(filename, (char *) texPathPvr.c_str()); if (tex_full_name != NULL) tex_id = add_new_texture_opt(tex_full_name,tex_full_name); if (tex_id == -1) tex_full_name = search_texture(filename, (char *) texPathPng.c_str()); if (tex_full_name != NULL) tex_id = add_new_texture_opt(tex_full_name,tex_full_name); if (tex_id == -1) tex_full_name = search_texture(filename, (char *) texPathBmp.c_str()); if (tex_full_name != NULL) tex_id = add_new_texture_opt(tex_full_name,tex_full_name); if (tex_id == -1) tex_full_name = search_texture(filename, (char *) texPathDds.c_str()); if (tex_full_name != NULL) tex_id = add_new_texture_opt(tex_full_name,tex_full_name); } if (has_cockpit_cmd || has_cockpit_reg) { printf("Trying cockpit textures.\n"); int n = 0; while(panel_id == -1 && panel_names[n]) { panel_full_name = search_texture(filename, (char*)panel_names[n]); if(panel_full_name) panel_id = add_new_texture_opt(panel_full_name, (char*)panel_names[n]); ++n; } if(panel_id == -1 && has_cockpit_reg) { message_dialog((char*)"Warning: I was unable to find a panel texture to load, but you are using panel regions. Your texure coordinates may be incorrect after import."); } } for(vector<XObjLOD8>::iterator lod = obj8.lods.begin(); lod != obj8.lods.end(); ++lod) { lod_obj = new_object(OBJECT_GROUP); if (lod->lod_far != 0.0) sprintf(strbuf, "LOD %f/%f",lod->lod_near, lod->lod_far); else strcpy(strbuf, "Default LOD"); object_set_name(lod_obj, strbuf); if (lod->lod_far != 0.0) { OBJ_set_LOD_near(lod_obj, lod->lod_near); OBJ_set_LOD_far (lod_obj, lod->lod_far ); } object_add_child(group_obj, lod_obj); bool shade_flat = false; bool two_side = false; int panel_tex = tex_id; int last_reg = -1; float s_mul=1.0,t_mul=1.0,s_add=0.0,t_add=0.0; float no_blend = -1.0; string hard_poly; int deck = 0; float offset = 0; string light_level; float light_v1 = 0.0f, light_v2 = 1.0f; int draw_disable = 0; int wall = 0; int manip_type = manip_none; string manip_dref1, manip_dref2, manip_cursor, manip_tooltip; float manip_wheel = 0.0; float manip_drag_axis[3]; float manip_v1_min; float manip_v1_max; float manip_v2_min; float manip_v2_max; map<int, Vertex *> vmap; for(vector<XObjCmd8>::iterator cmd = lod->cmds.begin(); cmd != lod->cmds.end(); ++cmd) { switch(cmd->cmd) { case obj8_Tris: case obj8_Lines: if (stuff_obj == NULL) { stuff_obj = new_object(OBJECT_NORMAL); vmap.clear(); if (panel_tex != -1)object_texture_set(stuff_obj, panel_tex); object_add_child(anim_obj.empty() ? lod_obj : anim_obj.back(), stuff_obj); OBJ_set_poly_os(stuff_obj, offset); OBJ_set_blend(stuff_obj, no_blend); OBJ_set_hard(stuff_obj, hard_poly.c_str()); OBJ_set_deck(stuff_obj,deck); if(light_level.empty()) OBJ_set_mod_lit(stuff_obj,0); else { OBJ_set_mod_lit(stuff_obj,1); OBJ_set_lit_dataref(stuff_obj,light_level.c_str()); OBJ_set_lit_v1(stuff_obj, light_v1); OBJ_set_lit_v2(stuff_obj, light_v2); } OBJ_set_wall(stuff_obj,wall); OBJ_set_draw_disable(stuff_obj,draw_disable); OBJ_set_manip_type(stuff_obj,manip_type); switch(manip_type) { case manip_axis: case manip_axis_pix: OBJ_set_manip_v1_min(stuff_obj,manip_v1_min); OBJ_set_manip_v1_max(stuff_obj,manip_v1_max); OBJ_set_manip_dx(stuff_obj,manip_drag_axis[0]); OBJ_set_manip_dy(stuff_obj,manip_drag_axis[1]); OBJ_set_manip_dz(stuff_obj,manip_drag_axis[2]); OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_cursor(stuff_obj,manip_cursor.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); OBJ_set_manip_wheel(stuff_obj, manip_wheel); break; case manip_axis_2d: OBJ_set_manip_v1_min(stuff_obj,manip_v1_min); OBJ_set_manip_v1_max(stuff_obj,manip_v1_max); OBJ_set_manip_v2_min(stuff_obj,manip_v2_min); OBJ_set_manip_v2_max(stuff_obj,manip_v2_max); OBJ_set_manip_dx(stuff_obj,manip_drag_axis[0]); OBJ_set_manip_dy(stuff_obj,manip_drag_axis[1]); OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_dref2(stuff_obj,manip_dref2.c_str()); OBJ_set_manip_cursor(stuff_obj,manip_cursor.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); break; case manip_command: OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_cursor(stuff_obj,manip_cursor.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); break; case manip_command_axis: OBJ_set_manip_dx(stuff_obj,manip_drag_axis[0]); OBJ_set_manip_dy(stuff_obj,manip_drag_axis[1]); OBJ_set_manip_dz(stuff_obj,manip_drag_axis[2]); OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_dref2(stuff_obj,manip_dref2.c_str()); OBJ_set_manip_cursor(stuff_obj,manip_cursor.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); break; case manip_noop: OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); break; case manip_dref_push: case manip_dref_toggle: OBJ_set_manip_v1_min(stuff_obj,manip_v1_min); OBJ_set_manip_v1_max(stuff_obj,manip_v1_max); OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_cursor(stuff_obj,manip_cursor.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); OBJ_set_manip_wheel(stuff_obj, manip_wheel); break; case manip_dref_radio: OBJ_set_manip_v1_max(stuff_obj,manip_v1_max); OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_cursor(stuff_obj,manip_cursor.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); OBJ_set_manip_wheel(stuff_obj, manip_wheel); break; case manip_dref_delta: case manip_dref_wrap: OBJ_set_manip_v1_min(stuff_obj,manip_v1_min); OBJ_set_manip_v1_max(stuff_obj,manip_v1_max); OBJ_set_manip_v2_min(stuff_obj,manip_v2_min); OBJ_set_manip_v2_max(stuff_obj,manip_v2_max); OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_cursor(stuff_obj,manip_cursor.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); OBJ_set_manip_wheel(stuff_obj, manip_wheel); break; case manip_command_knob: case manip_command_switch_ud: case manip_command_switch_lr: OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_dref2(stuff_obj,manip_dref2.c_str()); OBJ_set_manip_cursor(stuff_obj,manip_cursor.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); break; case manip_dref_knob: case manip_dref_switch_ud: case manip_dref_switch_lr: OBJ_set_manip_dref1(stuff_obj,manip_dref1.c_str()); OBJ_set_manip_cursor(stuff_obj,manip_cursor.c_str()); OBJ_set_manip_tooltip(stuff_obj,manip_tooltip.c_str()); OBJ_set_manip_v1_min(stuff_obj,manip_v1_min); OBJ_set_manip_v1_max(stuff_obj,manip_v1_max); OBJ_set_manip_dx(stuff_obj,manip_drag_axis[0]); OBJ_set_manip_dy(stuff_obj,manip_drag_axis[1]); break; } sprintf(strbuf, "POLY_OS=%d HARD=%s BLEND=%s", (int) offset, hard_poly.c_str(), no_blend >= 0.0 ? "no":"yes"); object_set_name(stuff_obj, strbuf); } if (cmd->cmd == obj8_Tris) { int total_verts = 0; vector<Vertex *> verts; for (i = 0; i < cmd->idx_count; ++i) { map<int,Vertex *>::iterator idx_iter = vmap.find(obj8.indices[cmd->idx_offset + i]); if(idx_iter != vmap.end()) { verts.push_back(idx_iter->second); } else { ++total_verts; float * dat = obj8.geo_tri.get(obj8.indices[cmd->idx_offset + i]); p3.x = dat[0]; p3.y = dat[1]; p3.z = dat[2]; verts.push_back(object_add_new_vertex_head(stuff_obj, &p3)); vmap.insert(map<int,Vertex*>::value_type(obj8.indices[cmd->idx_offset + i],verts.back())); } } Surface * s = NULL; for (i = 0; i < cmd->idx_count; ++i) { if ((i % 3) == 0) { s = new_surface(); surface_set_type(s, SURFACE_POLYGON); surface_set_twosided(s, two_side); surface_set_shading(s, !shade_flat); object_add_surface_head(stuff_obj, s); int our_material = ac_palette_get_new_material_index(&current_material); surface_set_col(s, our_material); if (our_material != default_material) OBJ_set_use_materials(stuff_obj, 1); } float * dat = obj8.geo_tri.get(obj8.indices[cmd->idx_offset + i]); surface_add_vertex_head(s, verts[i], dat[6] * s_mul + s_add, dat[7] * t_mul + t_add); } } else { vector<Vertex *> verts; int i; for (i = 0; i < cmd->idx_count; ++i) { float * dat = obj8.geo_lines.get(obj8.indices[cmd->idx_offset + i]); p3.x = dat[0]; p3.y = dat[1]; p3.z = dat[2]; verts.push_back(object_add_new_vertex_head(stuff_obj, &p3)); } Surface * s = NULL; for (i = 0; i < cmd->idx_count; ++i) { float * dat = obj8.geo_lines.get(obj8.indices[cmd->idx_offset + i]); if ((i % 2) == 0) { s = new_surface(); surface_set_rgb_long(s, rgb_floats_to_long(dat[3], dat[4], dat[5])); surface_set_type(s, SURFACE_LINE); surface_set_twosided(s, two_side); surface_set_shading(s, !shade_flat); object_add_surface_head(stuff_obj, s); } surface_add_vertex_head(s, verts[i], 0.0, 0.0); } } break; case attr_Tex_Normal: if (panel_tex != tex_id) stuff_obj = NULL; panel_tex = tex_id; last_reg = -1; s_mul=1.0,t_mul=1.0,s_add=0.0,t_add=0.0; manip_type = manip_none; break; case attr_Tex_Cockpit: if (panel_tex != panel_id) stuff_obj = NULL; panel_tex = panel_id; last_reg = -1; s_mul=1.0,t_mul=1.0,s_add=0.0,t_add=0.0; manip_type = manip_panel; break; case attr_Tex_Cockpit_Subregion: if (panel_tex != panel_id) stuff_obj = NULL; if(last_reg != (int) cmd->params[0]) stuff_obj = NULL; panel_tex = panel_id; last_reg = (int) cmd->params[0]; manip_type = manip_panel; panel_get_import_scaling(panel_id,last_reg,&s_mul,&t_mul,&s_add,&t_add); break; case attr_No_Blend: if (!no_blend != cmd->params[0]) stuff_obj = NULL; no_blend = cmd->params[0]; break; case attr_Blend: if (no_blend != -1.0) stuff_obj = NULL; no_blend = -1.0; break; case attr_Hard: if (hard_poly != cmd->name) stuff_obj = NULL; if(deck == 1) stuff_obj = NULL; hard_poly = cmd->name; deck = 0; break; case attr_Hard_Deck: if (hard_poly != cmd->name) stuff_obj = NULL; if(deck == 0) stuff_obj = NULL; hard_poly = cmd->name; deck = 1; break; case attr_No_Hard: if (!hard_poly.empty()) stuff_obj = NULL; hard_poly.clear(); deck = 0; break; case attr_Offset: if (offset != cmd->params[0]) stuff_obj = NULL; offset = cmd->params[0]; break; case attr_Shade_Flat: #if OBJ_FOR_ALL_ATTRS if (!shade_flat) stuff_obj = NULL; #endif shade_flat = true; break; case attr_Shade_Smooth: #if OBJ_FOR_ALL_ATTRS if (shade_flat) stuff_obj = NULL; #endif shade_flat = false; break; case attr_Cull: #if OBJ_FOR_ALL_ATTRS if (two_side) stuff_obj = NULL; #endif two_side = false; break; case attr_NoCull: #if OBJ_FOR_ALL_ATTRS if (!two_side) stuff_obj = NULL; #endif two_side = true; break; case attr_Solid_Wall: if(!wall) stuff_obj = NULL; wall = 1; break; case attr_No_Solid_Wall: if(wall) stuff_obj = NULL; wall = 0; break; case attr_Draw_Disable: if(!draw_disable) stuff_obj = NULL; draw_disable = 1; break; case attr_Draw_Enable: if(draw_disable) stuff_obj = NULL; draw_disable = 0; break; case attr_Light_Level: if(light_level != cmd->name) stuff_obj = NULL; if(light_v1 != cmd->params[0]) stuff_obj = NULL; if(light_v2 != cmd->params[1]) stuff_obj = NULL; light_v1 = cmd->params[0]; light_v2 = cmd->params[1]; light_level = cmd->name; break; case attr_Light_Level_Reset: if(!light_level.empty()) stuff_obj = NULL; light_v1 = 0.0f; light_v2 = 1.0f; light_level.clear(); break; case attr_Layer_Group: OBJ_set_layer_group(group_obj, cmd->name.c_str()); OBJ_set_layer_group_offset(group_obj, cmd->params[0]); break; case attr_Manip_Drag_Axis: stuff_obj = NULL; manip_type = manip_axis; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_drag_axis[0] = obj8.manips[cmd->idx_offset].axis[0]; manip_drag_axis[1] = obj8.manips[cmd->idx_offset].axis[1]; manip_drag_axis[2] = obj8.manips[cmd->idx_offset].axis[2]; manip_wheel = obj8.manips[cmd->idx_offset].mouse_wheel_delta; break; case attr_Manip_Drag_2d: stuff_obj = NULL; manip_type = manip_axis_2d; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_dref2 = obj8.manips[cmd->idx_offset].dataref2; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_v2_min = obj8.manips[cmd->idx_offset].v2_min; manip_v2_max = obj8.manips[cmd->idx_offset].v2_max; manip_drag_axis[0] = obj8.manips[cmd->idx_offset].axis[0]; manip_drag_axis[1] = obj8.manips[cmd->idx_offset].axis[1]; break; case attr_Manip_Command: stuff_obj = NULL; manip_type = manip_command; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; break; case attr_Manip_Command_Axis: stuff_obj = NULL; manip_type = manip_command_axis; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_dref2 = obj8.manips[cmd->idx_offset].dataref2; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_drag_axis[0] = obj8.manips[cmd->idx_offset].axis[0]; manip_drag_axis[1] = obj8.manips[cmd->idx_offset].axis[1]; manip_drag_axis[2] = obj8.manips[cmd->idx_offset].axis[2]; break; case attr_Manip_Noop: stuff_obj = NULL; manip_type = manip_noop; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; break; case attr_Manip_Push: stuff_obj = NULL; manip_type = manip_dref_push; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_wheel = obj8.manips[cmd->idx_offset].mouse_wheel_delta; break; case attr_Manip_Radio: stuff_obj = NULL; manip_type = manip_dref_radio; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_wheel = obj8.manips[cmd->idx_offset].mouse_wheel_delta; break; case attr_Manip_Toggle: stuff_obj = NULL; manip_type = manip_dref_toggle; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_wheel = obj8.manips[cmd->idx_offset].mouse_wheel_delta; break; case attr_Manip_Delta: stuff_obj = NULL; manip_type = manip_dref_delta; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_v2_min = obj8.manips[cmd->idx_offset].v2_min; manip_v2_max = obj8.manips[cmd->idx_offset].v2_max; manip_wheel = obj8.manips[cmd->idx_offset].mouse_wheel_delta; break; case attr_Manip_Wrap: stuff_obj = NULL; manip_type = manip_dref_wrap; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_v2_min = obj8.manips[cmd->idx_offset].v2_min; manip_v2_max = obj8.manips[cmd->idx_offset].v2_max; manip_wheel = obj8.manips[cmd->idx_offset].mouse_wheel_delta; break; case attr_Manip_Drag_Axis_Pix: stuff_obj = NULL; manip_type = manip_axis_pix; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_drag_axis[0] = obj8.manips[cmd->idx_offset].axis[0]; manip_drag_axis[1] = obj8.manips[cmd->idx_offset].axis[1]; manip_drag_axis[2] = obj8.manips[cmd->idx_offset].axis[2]; manip_wheel = obj8.manips[cmd->idx_offset].mouse_wheel_delta; break; case attr_Manip_Command_Knob: stuff_obj = NULL; manip_type = manip_command_knob; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_dref2 = obj8.manips[cmd->idx_offset].dataref2; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; break; case attr_Manip_Command_Switch_Up_Down: stuff_obj = NULL; manip_type = manip_command_switch_ud; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_dref2 = obj8.manips[cmd->idx_offset].dataref2; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; break; case attr_Manip_Command_Switch_Left_Right: stuff_obj = NULL; manip_type = manip_command_switch_lr; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_dref2 = obj8.manips[cmd->idx_offset].dataref2; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; break; case attr_Manip_Axis_Knob: stuff_obj = NULL; manip_type = manip_dref_knob; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_drag_axis[0] = obj8.manips[cmd->idx_offset].axis[0]; manip_drag_axis[1] = obj8.manips[cmd->idx_offset].axis[1]; break; case attr_Manip_Axis_Switch_Up_Down: stuff_obj = NULL; manip_type = manip_dref_switch_ud; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_drag_axis[0] = obj8.manips[cmd->idx_offset].axis[0]; manip_drag_axis[1] = obj8.manips[cmd->idx_offset].axis[1]; break; case attr_Manip_Axis_Switch_Left_Right: stuff_obj = NULL; manip_type = manip_dref_switch_lr; manip_dref1 = obj8.manips[cmd->idx_offset].dataref1; manip_cursor = obj8.manips[cmd->idx_offset].cursor; manip_tooltip = obj8.manips[cmd->idx_offset].tooltip; manip_v1_min = obj8.manips[cmd->idx_offset].v1_min; manip_v1_max = obj8.manips[cmd->idx_offset].v1_max; manip_drag_axis[0] = obj8.manips[cmd->idx_offset].axis[0]; manip_drag_axis[1] = obj8.manips[cmd->idx_offset].axis[1]; break; case anim_Begin: { stuff_obj = NULL; ACObject * parent = anim_obj.empty() ? lod_obj : anim_obj.back(); anim_obj.push_back(new_object(OBJECT_GROUP)); object_add_child(parent, anim_obj.back()); object_set_name(anim_obj.back(), (char*)"ANIMATION"); OBJ_set_animation_group(anim_obj.back(),1); } break; case anim_End: stuff_obj = NULL; anim_obj.pop_back(); break; case anim_Translate: { stuff_obj = NULL; int root = 0; if (obj8.animation[cmd->idx_offset].keyframes[root].v[0] != 0.0 || obj8.animation[cmd->idx_offset].keyframes[root].v[1] != 0.0 || obj8.animation[cmd->idx_offset].keyframes[root].v[2] != 0.0) anim_add_static(anim_obj.back(), 0, obj8.animation[cmd->idx_offset].keyframes[root].v, obj8.animation[cmd->idx_offset].dataref.c_str(), "static translate"); if (obj8.animation[cmd->idx_offset].keyframes.size() > 2 || (obj8.animation[cmd->idx_offset].keyframes.size() == 2 && ( obj8.animation[cmd->idx_offset].keyframes[0].v[0] != obj8.animation[cmd->idx_offset].keyframes[1].v[0] || obj8.animation[cmd->idx_offset].keyframes[0].v[1] != obj8.animation[cmd->idx_offset].keyframes[1].v[1] || obj8.animation[cmd->idx_offset].keyframes[0].v[2] != obj8.animation[cmd->idx_offset].keyframes[1].v[2]))) anim_add_translate(anim_obj.back(), 0, obj8.animation[cmd->idx_offset].keyframes, obj8.animation[cmd->idx_offset].dataref.c_str(), "translate", obj8.animation[cmd->idx_offset].loop); } break; case anim_Rotate: { stuff_obj = NULL; float center[3] = { 0.0, 0.0, 0.0 }; anim_add_rotate(anim_obj.back(), 0, center, obj8.animation[cmd->idx_offset].axis, obj8.animation[cmd->idx_offset].keyframes, obj8.animation[cmd->idx_offset].dataref.c_str(), "rotate", obj8.animation[cmd->idx_offset].loop); } break; case anim_Show: stuff_obj = NULL; anim_add_show(anim_obj.back(), 0, obj8.animation[cmd->idx_offset].keyframes, obj8.animation[cmd->idx_offset].dataref.c_str(), "show"); break; case anim_Hide: stuff_obj = NULL; anim_add_hide(anim_obj.back(), 0, obj8.animation[cmd->idx_offset].keyframes, obj8.animation[cmd->idx_offset].dataref.c_str(), "show"); break; case obj8_Lights: for (i = 0; i < cmd->idx_count; ++i) { stuff_obj = NULL; ACObject * light = new_object(OBJECT_LIGHT); Point3 pt_ac3, col_ac3 = { 0.0, 0.0, 0.0 }; float * dat = obj8.geo_lights.get(cmd->idx_offset + i); pt_ac3.x = dat[0]; pt_ac3.y = dat[1]; pt_ac3.z = dat[2]; ac_entity_set_point_value(light, (char*)"loc", &pt_ac3); sprintf(strbuf, "RGB (%f,%f,%f)", dat[3], dat[4], dat[5]); ac_entity_set_point_value(light, (char*)"diffuse", &col_ac3); object_set_name(light, strbuf); object_add_child(anim_obj.empty() ? lod_obj : anim_obj.back(), light); OBJ_set_light_red(light, dat[3]); OBJ_set_light_green(light, dat[4]); OBJ_set_light_blue(light, dat[5]); OBJ_set_light_named(light, "rgb"); } break; case obj8_LightNamed: { stuff_obj = NULL; ACObject * light = new_object(OBJECT_LIGHT); Point3 pt_ac3, col_ac3 = { 0.0, 0.0, 0.0 }; pt_ac3.x = cmd->params[0]; pt_ac3.y = cmd->params[1]; pt_ac3.z = cmd->params[2]; ac_entity_set_point_value(light, (char*)"loc", &pt_ac3); ac_entity_set_point_value(light, (char*)"diffuse", &col_ac3); object_set_name(light, (char*) cmd->name.c_str()); object_add_child(anim_obj.empty() ? lod_obj : anim_obj.back(), light); OBJ_set_light_named(light, cmd->name.c_str()); } break; case obj8_LightCustom: { stuff_obj = NULL; ACObject * light = new_object(OBJECT_LIGHT); Point3 pt_ac3, col_ac3 = { 0.0, 0.0, 0.0 }; pt_ac3.x = cmd->params[0]; pt_ac3.y = cmd->params[1]; pt_ac3.z = cmd->params[2]; ac_entity_set_point_value(light, (char*)"loc", &pt_ac3); ac_entity_set_point_value(light, (char*)"diffuse", &col_ac3); object_add_child(anim_obj.empty() ? lod_obj : anim_obj.back(), light); OBJ_set_light_named(light, "custom"); OBJ_set_light_dataref(light, cmd->name.c_str()); OBJ_set_light_red (light,cmd->params[3]); OBJ_set_light_green (light,cmd->params[4]); OBJ_set_light_blue (light,cmd->params[5]); OBJ_set_light_alpha (light,cmd->params[6]); OBJ_set_light_size (light,cmd->params[7]); OBJ_set_light_s1 (light,cmd->params[8]); OBJ_set_light_t1 (light,cmd->params[9]); OBJ_set_light_s2 (light,cmd->params[10]); OBJ_set_light_t2 (light,cmd->params[11]); } break; case obj_Smoke_Black: { stuff_obj = NULL; ACObject * light = new_object(OBJECT_LIGHT); Point3 pt_ac3, col_ac3 = { 0.0, 0.0, 0.0 }; pt_ac3.x = cmd->params[0]; pt_ac3.y = cmd->params[1]; pt_ac3.z = cmd->params[2]; ac_entity_set_point_value(light, (char*)"loc", &pt_ac3); ac_entity_set_point_value(light, (char*)"diffuse", &col_ac3); object_set_name(light, (char*)"Black Smoke"); object_add_child(anim_obj.empty() ? lod_obj : anim_obj.back(), light); OBJ_set_light_smoke_size(light, cmd->params[3]); OBJ_set_light_named(light, "black smoke"); } break; case obj_Smoke_White: { stuff_obj = NULL; ACObject * light = new_object(OBJECT_LIGHT); Point3 pt_ac3, col_ac3 = { 0.0, 0.0, 0.0 }; pt_ac3.x = cmd->params[0]; pt_ac3.y = cmd->params[1]; pt_ac3.z = cmd->params[2]; ac_entity_set_point_value(light, (char*)"loc", &pt_ac3); ac_entity_set_point_value(light, (char*)"diffuse", &col_ac3); object_set_name(light, (char*)"White Smoke"); object_add_child(anim_obj.empty() ? lod_obj : anim_obj.back(), light); OBJ_set_light_smoke_size(light, cmd->params[3]); OBJ_set_light_named(light, "white smoke"); } break; case attr_Ambient_RGB: break; case attr_Diffuse_RGB: current_material.rgb.r = cmd->params[0]; current_material.rgb.g = cmd->params[1]; current_material.rgb.b = cmd->params[2]; break; case attr_Emission_RGB: current_material.emissive.r = cmd->params[0]; current_material.emissive.g = cmd->params[1]; current_material.emissive.b = cmd->params[2]; break; case attr_Specular_RGB: break; case attr_Shiny_Rat: current_material.specular.r = cmd->params[0]; current_material.specular.g = cmd->params[0]; current_material.specular.b = cmd->params[0]; break; case attr_Reset: current_material.rgb.r = 1.0; current_material.rgb.g = 1.0; current_material.rgb.b = 1.0; current_material.specular.r = 0.0; current_material.specular.g = 0.0; current_material.specular.b = 0.0; current_material.emissive.r = 0.0; current_material.emissive.g = 0.0; current_material.emissive.b = 0.0; break; } } } object_calc_normals_force(group_obj); bake_static_transitions(group_obj); purge_datarefs(); gather_datarefs(group_obj); sync_datarefs(); return group_obj; }
36.006224
172
0.681648
den-rain
dc1abdf77ef4738900b3dcc654db8e753608f195
28,436
cpp
C++
test/cxx/Core/SpawningKit/HandshakePerformTest.cpp
m5o/passenger
9640816af708867d0994bd2eddb80ac24399f855
[ "MIT" ]
2,728
2015-01-01T10:06:45.000Z
2022-03-30T18:12:58.000Z
test/cxx/Core/SpawningKit/HandshakePerformTest.cpp
m5o/passenger
9640816af708867d0994bd2eddb80ac24399f855
[ "MIT" ]
1,192
2015-01-01T06:03:19.000Z
2022-03-31T09:14:36.000Z
test/cxx/Core/SpawningKit/HandshakePerformTest.cpp
m5o/passenger
9640816af708867d0994bd2eddb80ac24399f855
[ "MIT" ]
334
2015-01-08T20:47:03.000Z
2022-02-18T07:07:01.000Z
#include <TestSupport.h> #include <Core/SpawningKit/Handshake/Prepare.h> #include <Core/SpawningKit/Handshake/Perform.h> #include <LoggingKit/Context.h> #include <SystemTools/UserDatabase.h> #include <boost/bind/bind.hpp> #include <cstdio> #include <IOTools/IOUtils.h> using namespace std; using namespace Passenger; using namespace Passenger::SpawningKit; namespace tut { struct Core_SpawningKit_HandshakePerformTest: public TestBase { WrapperRegistry::Registry wrapperRegistry; SpawningKit::Context::Schema schema; SpawningKit::Context context; SpawningKit::Config config; boost::shared_ptr<HandshakeSession> session; pid_t pid; Pipe stdoutAndErr; HandshakePerform::DebugSupport *debugSupport; AtomicInt counter; FileDescriptor server; Core_SpawningKit_HandshakePerformTest() : context(schema), pid(getpid()), debugSupport(NULL) { wrapperRegistry.finalize(); context.resourceLocator = resourceLocator; context.wrapperRegistry = &wrapperRegistry; context.integrationMode = "standalone"; context.spawnDir = getSystemTempDir(); config.appGroupName = "appgroup"; config.appRoot = "/tmp/myapp"; config.startCommand = "echo hi"; config.startupFile = "/tmp/myapp/app.py"; config.appType = "wsgi"; config.spawnMethod = "direct"; config.bindAddress = "127.0.0.1"; config.user = lookupSystemUsernameByUid(getuid()); config.group = lookupSystemGroupnameByGid(getgid()); config.internStrings(); } ~Core_SpawningKit_HandshakePerformTest() { Json::Value config; vector<ConfigKit::Error> errors; LoggingKit::ConfigChangeRequest req; config["level"] = DEFAULT_LOG_LEVEL_NAME; config["app_output_log_level"] = DEFAULT_APP_OUTPUT_LOG_LEVEL_NAME; if (LoggingKit::context->prepareConfigChange(config, errors, req)) { LoggingKit::context->commitConfigChange(req); } else { P_BUG("Error configuring LoggingKit: " << ConfigKit::toString(errors)); } } void init(JourneyType type) { vector<StaticString> errors; ensure("Config is valid", config.validate(errors)); context.finalize(); session = boost::make_shared<HandshakeSession>(context, config, type); session->journey.setStepInProgress(SPAWNING_KIT_PREPARATION); HandshakePrepare(*session).execute().finalize(); session->journey.setStepInProgress(SPAWNING_KIT_HANDSHAKE_PERFORM); session->journey.setStepInProgress(SUBPROCESS_BEFORE_FIRST_EXEC); } void execute() { HandshakePerform performer(*session, pid, FileDescriptor(), stdoutAndErr.first); performer.debugSupport = debugSupport; performer.execute(); counter++; } static Json::Value createGoodPropertiesJson() { Json::Value socket, doc; socket["address"] = "tcp://127.0.0.1:3000"; socket["protocol"] = "http"; socket["concurrency"] = 1; socket["accept_http_requests"] = true; doc["sockets"].append(socket); return doc; } void signalFinish() { writeFile(session->responseDir + "/finish", "1"); } void signalFinishWithError() { writeFile(session->responseDir + "/finish", "0"); } }; struct FreePortDebugSupport: public HandshakePerform::DebugSupport { Core_SpawningKit_HandshakePerformTest *test; HandshakeSession *session; AtomicInt expectedStartPort; virtual void beginWaitUntilSpawningFinished() { expectedStartPort = session->expectedStartPort; test->counter++; } }; struct CrashingDebugSupport: public HandshakePerform::DebugSupport { virtual void beginWaitUntilSpawningFinished() { throw RuntimeException("oh no!"); } }; DEFINE_TEST_GROUP_WITH_LIMIT(Core_SpawningKit_HandshakePerformTest, 80); /***** General logic *****/ TEST_METHOD(1) { set_test_name("If the app is generic, it finishes when the app is pingable"); FreePortDebugSupport debugSupport; this->debugSupport = &debugSupport; config.genericApp = true; init(SPAWN_DIRECTLY); debugSupport.test = this; debugSupport.session = session.get(); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::execute, this)); EVENTUALLY(1, result = counter == 1; ); server.assign(createTcpServer("127.0.0.1", debugSupport.expectedStartPort.get()), NULL, 0); EVENTUALLY(1, result = counter == 2; ); } TEST_METHOD(2) { set_test_name("If findFreePort is true, it finishes when the app is pingable"); FreePortDebugSupport debugSupport; this->debugSupport = &debugSupport; config.findFreePort = true; init(SPAWN_DIRECTLY); debugSupport.test = this; debugSupport.session = session.get(); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::execute, this)); EVENTUALLY(1, result = counter == 1; ); server.assign(createTcpServer("127.0.0.1", debugSupport.expectedStartPort.get()), NULL, 0); EVENTUALLY(1, result = counter == 2; ); } TEST_METHOD(3) { set_test_name("It finishes when the app has sent the finish signal"); init(SPAWN_DIRECTLY); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::execute, this)); SHOULD_NEVER_HAPPEN(100, result = counter > 0; ); createFile(session->responseDir + "/properties.json", createGoodPropertiesJson().toStyledString()); signalFinish(); EVENTUALLY(1, result = counter == 1; ); } TEST_METHOD(10) { set_test_name("It raises an error if the process exits prematurely"); init(SPAWN_DIRECTLY); pid = fork(); if (pid == 0) { // Exit child _exit(1); } try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals(StaticString(e.what()), "The application process exited prematurely."); } } TEST_METHOD(11) { set_test_name("It raises an error if the procedure took too long"); config.startTimeoutMsec = 50; init(SPAWN_DIRECTLY); pid = fork(); if (pid == 0) { // Exit child usleep(1000000); _exit(1); } try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals(StaticString(e.what()), "A timeout occurred while spawning an application process."); } } TEST_METHOD(15) { set_test_name("In the event of an error, it sets the SPAWNING_KIT_HANDSHAKE_PERFORM step to the errored state"); CrashingDebugSupport debugSupport; this->debugSupport = &debugSupport; init(SPAWN_DIRECTLY); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &) { ensure_equals(session->journey.getFirstFailedStep(), SPAWNING_KIT_HANDSHAKE_PERFORM); } } TEST_METHOD(16) { set_test_name("In the event of an error, the exception contains journey state information from the response directory"); CrashingDebugSupport debugSupport; this->debugSupport = &debugSupport; init(SPAWN_DIRECTLY); createFile(session->responseDir + "/steps/subprocess_listen/state", "STEP_ERRORED"); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &) { ensure_equals(session->journey.getStepInfo(SUBPROCESS_LISTEN).state, STEP_ERRORED); } } TEST_METHOD(17) { set_test_name("In the event of an error, the exception contains subprocess stdout and stderr data"); Pipe p = createPipe(__FILE__, __LINE__); CrashingDebugSupport debugSupport; init(SPAWN_DIRECTLY); HandshakePerform performer(*session, pid, FileDescriptor(), p.first); performer.debugSupport = &debugSupport; Json::Value config; vector<ConfigKit::Error> errors; LoggingKit::ConfigChangeRequest req; config["app_output_log_level"] = "debug"; if (LoggingKit::context->prepareConfigChange(config, errors, req)) { LoggingKit::context->commitConfigChange(req); } else { P_BUG("Error configuring LoggingKit: " << ConfigKit::toString(errors)); } writeExact(p.second, "hi\n"); try { performer.execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals(e.getStdoutAndErrData(), "hi\n"); } } TEST_METHOD(18) { set_test_name("In the event of an error caused by the subprocess, the exception contains messages from" " the subprocess as dumped in the response directory"); init(SPAWN_DIRECTLY); pid = fork(); if (pid == 0) { // Exit child _exit(1); } createFile(session->responseDir + "/error/summary", "the summary"); createFile(session->responseDir + "/error/problem_description.txt", "the <problem>"); createFile(session->responseDir + "/error/advanced_problem_details", "the advanced problem details"); createFile(session->responseDir + "/error/solution_description.html", "the <b>solution</b>"); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals(e.getSummary(), "the summary"); ensure_equals(e.getProblemDescriptionHTML(), "the &lt;problem&gt;"); ensure_equals(e.getAdvancedProblemDetails(), "the advanced problem details"); ensure_equals(e.getSolutionDescriptionHTML(), "the <b>solution</b>"); } } TEST_METHOD(19) { set_test_name("In the event of success, it loads the journey state information from the response directory"); init(SPAWN_DIRECTLY); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::execute, this)); createFile(session->responseDir + "/properties.json", createGoodPropertiesJson().toStyledString()); createFile(session->responseDir + "/steps/subprocess_listen/state", "STEP_PERFORMED"); signalFinish(); EVENTUALLY(5, result = counter == 1; ); ensure_equals(session->journey.getStepInfo(SUBPROCESS_LISTEN).state, STEP_PERFORMED); } TEST_METHOD(20) { // Limited test of whether the code mitigates symlink attacks. set_test_name("It does not read from symlinks"); init(SPAWN_DIRECTLY); createFile(session->responseDir + "/properties-real.json", createGoodPropertiesJson().toStyledString()); symlink("properties-real.json", (session->responseDir + "/properties.json").c_str()); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinish, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure(containsSubstring(e.getSummary(), "Cannot open 'properties.json'")); } } /***** Success response handling *****/ TEST_METHOD(30) { set_test_name("The result object contains basic information such as FDs and time"); init(SPAWN_DIRECTLY); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::execute, this)); createFile(session->responseDir + "/properties.json", createGoodPropertiesJson().toStyledString()); createFile(session->responseDir + "/steps/subprocess_listen/state", "STEP_PERFORMED"); signalFinish(); EVENTUALLY(5, result = counter == 1; ); ensure_equals(session->result.pid, pid); ensure(session->result.spawnStartTime != 0); ensure(session->result.spawnEndTime >= session->result.spawnStartTime); ensure(session->result.spawnStartTimeMonotonic != 0); ensure(session->result.spawnEndTimeMonotonic >= session->result.spawnStartTimeMonotonic); } TEST_METHOD(31) { set_test_name("The result object contains sockets specified in properties.json"); init(SPAWN_DIRECTLY); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::execute, this)); createFile(session->responseDir + "/properties.json", createGoodPropertiesJson().toStyledString()); createFile(session->responseDir + "/steps/subprocess_listen/state", "STEP_PERFORMED"); signalFinish(); EVENTUALLY(5, result = counter == 1; ); ensure_equals(session->result.sockets.size(), 1u); ensure_equals(session->result.sockets[0].address, "tcp://127.0.0.1:3000"); ensure_equals(session->result.sockets[0].protocol, "http"); ensure_equals(session->result.sockets[0].concurrency, 1); ensure(session->result.sockets[0].acceptHttpRequests); } TEST_METHOD(32) { set_test_name("If the app is generic, it automatically registers the free port as a request-handling socket"); FreePortDebugSupport debugSupport; this->debugSupport = &debugSupport; config.genericApp = true; init(SPAWN_DIRECTLY); debugSupport.test = this; debugSupport.session = session.get(); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::execute, this)); EVENTUALLY(1, result = counter == 1; ); server.assign(createTcpServer("127.0.0.1", debugSupport.expectedStartPort.get()), NULL, 0); EVENTUALLY(1, result = counter == 2; ); ensure_equals(session->result.sockets.size(), 1u); ensure_equals(session->result.sockets[0].address, "tcp://127.0.0.1:" + toString(session->expectedStartPort)); ensure_equals(session->result.sockets[0].protocol, "http"); ensure_equals(session->result.sockets[0].concurrency, -1); ensure(session->result.sockets[0].acceptHttpRequests); } TEST_METHOD(33) { set_test_name("If findFreePort is true, it automatically registers the free port as a request-handling socket"); FreePortDebugSupport debugSupport; this->debugSupport = &debugSupport; config.findFreePort = true; init(SPAWN_DIRECTLY); debugSupport.test = this; debugSupport.session = session.get(); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::execute, this)); EVENTUALLY(1, result = counter == 1; ); server.assign(createTcpServer("127.0.0.1", debugSupport.expectedStartPort.get()), NULL, 0); EVENTUALLY(1, result = counter == 2; ); ensure_equals(session->result.sockets.size(), 1u); ensure_equals(session->result.sockets[0].address, "tcp://127.0.0.1:" + toString(session->expectedStartPort)); ensure_equals(session->result.sockets[0].protocol, "http"); ensure_equals(session->result.sockets[0].concurrency, -1); ensure(session->result.sockets[0].acceptHttpRequests); } TEST_METHOD(34) { set_test_name("It raises an error if we expected the subprocess to create a properties.json," " but the file does not conform to the required format"); init(SPAWN_DIRECTLY); createFile(session->responseDir + "/properties.json", "{ \"sockets\": {} }"); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinish, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure(containsSubstring(e.getSummary(), "'sockets' must be an array")); } } TEST_METHOD(35) { set_test_name("It raises an error if we expected the subprocess to specify at" " least one request-handling socket in properties.json, yet the file does" " not specify any"); Json::Value socket, doc; socket["address"] = "tcp://127.0.0.1:3000"; socket["protocol"] = "http"; socket["concurrency"] = 1; doc["sockets"].append(socket); init(SPAWN_DIRECTLY); createFile(session->responseDir + "/properties.json", doc.toStyledString()); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinish, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure(containsSubstring(e.getSummary(), "the application did not report any sockets to receive requests on")); } } TEST_METHOD(36) { set_test_name("It raises an error if we expected the subprocess to specify at" " least one request-handling socket in properties.json, yet properties.json" " does not exist"); init(SPAWN_DIRECTLY); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinish, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure(containsSubstring(e.getSummary(), "sockets are not supplied")); } } TEST_METHOD(37) { set_test_name("It raises an error if we expected the subprocess to specify at" " least one preloader command socket in properties.json, yet the file does" " not specify any"); Json::Value socket, doc; socket["address"] = "tcp://127.0.0.1:3000"; socket["protocol"] = "http"; socket["concurrency"] = 1; doc["sockets"].append(socket); init(START_PRELOADER); createFile(session->responseDir + "/properties.json", doc.toStyledString()); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinish, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure(containsSubstring(e.getSummary(), "the application did not report any sockets to receive preloader commands on")); } } TEST_METHOD(38) { set_test_name("It raises an error if we expected the subprocess to specify at" " least one preloader command socket in properties.json, yet properties.json" " does not exist"); init(START_PRELOADER); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinish, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure(containsSubstring(e.getSummary(), "sockets are not supplied")); } } TEST_METHOD(39) { set_test_name("It raises an error if properties.json specifies a Unix domain socket" " that is not located in the apps.s subdir of the instance directory"); TempDir tmpDir("tmp.instance"); context.instanceDir = absolutizePath("tmp.instance"); init(SPAWN_DIRECTLY); Json::Value doc = createGoodPropertiesJson(); doc["sockets"][0]["address"] = "unix:/foo"; createFile(session->responseDir + "/properties.json", doc.toStyledString()); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinish, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure(containsSubstring(e.getSummary(), "must be an absolute path to a file in")); } } TEST_METHOD(40) { set_test_name("It raises an error if properties.json specifies a Unix domain socket" " that is not owned by the app"); if (geteuid() != 0) { return; } TempDir tmpDir("tmp.instance"); mkdir("tmp.instance/apps.s", 0700); string socketPath = absolutizePath("tmp.instance/apps.s/foo.sock"); init(SPAWN_DIRECTLY); Json::Value doc = createGoodPropertiesJson(); doc["sockets"][0]["address"] = "unix:" + socketPath; createFile(session->responseDir + "/properties.json", doc.toStyledString()); safelyClose(createUnixServer(socketPath)); chown(socketPath.c_str(), 1, 1); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinish, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure("(1)", containsSubstring(e.getSummary(), "must be owned by user")); } } /***** Error response handling *****/ TEST_METHOD(50) { set_test_name("It raises an error if the application responded with an error"); init(SPAWN_DIRECTLY); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinishWithError, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals(e.getSummary(), "The web application aborted with an error during startup."); } } TEST_METHOD(51) { set_test_name("The exception contains error messages provided by the application"); init(SPAWN_DIRECTLY); writeFile(session->workDir->getPath() + "/response/error/summary", "the summary"); writeFile(session->workDir->getPath() + "/response/error/problem_description.html", "the problem description"); writeFile(session->workDir->getPath() + "/response/error/solution_description.html", "the solution description"); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinishWithError, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals(e.getSummary(), "the summary"); ensure_equals(e.getProblemDescriptionHTML(), "the problem description"); ensure_equals(e.getSolutionDescriptionHTML(), "the solution description"); } } TEST_METHOD(52) { set_test_name("The exception describes which steps in the journey had failed"); init(SPAWN_DIRECTLY); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinishWithError, this)); try { execute(); } catch (const SpawnException &e) { ensure_equals(e.getJourney().getFirstFailedStep(), SUBPROCESS_BEFORE_FIRST_EXEC); } } TEST_METHOD(53) { set_test_name("The exception contains the subprocess' output"); Json::Value config; vector<ConfigKit::Error> errors; LoggingKit::ConfigChangeRequest req; config["app_output_log_level"] = "debug"; if (LoggingKit::context->prepareConfigChange(config, errors, req)) { LoggingKit::context->commitConfigChange(req); } else { P_BUG("Error configuring LoggingKit: " << ConfigKit::toString(errors)); } init(SPAWN_DIRECTLY); stdoutAndErr = createPipe(__FILE__, __LINE__); writeExact(stdoutAndErr.second, "oh no"); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinishWithError, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals(e.getStdoutAndErrData(), "oh no"); } } TEST_METHOD(54) { set_test_name("The exception contains the subprocess' environment variables dump"); init(SPAWN_DIRECTLY); writeFile(session->workDir->getPath() + "/envdump/envvars", "the env dump"); TempThread thr(boost::bind(&Core_SpawningKit_HandshakePerformTest::signalFinishWithError, this)); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals(e.getSubprocessEnvvars(), "the env dump"); } } TEST_METHOD(55) { set_test_name("If the subprocess fails without setting a specific" " journey step to the ERRORED state," " and there is a subprocess journey step in the IN_PROGRESS state," " then we set that latter step to the ERRORED state"); init(SPAWN_DIRECTLY); pid = fork(); if (pid == 0) { // Exit child _exit(1); } createFile(session->responseDir + "/steps/subprocess_before_first_exec/state", "STEP_PERFORMED"); createFile(session->responseDir + "/steps/subprocess_before_first_exec/duration", "1"); createFile(session->responseDir + "/steps/subprocess_spawn_env_setupper_before_shell/state", "STEP_IN_PROGRESS"); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals("SPAWNING_KIT_HANDSHAKE_PERFORM is in the IN_PROGRESS state", e.getJourney().getStepInfo(SPAWNING_KIT_HANDSHAKE_PERFORM).state, STEP_IN_PROGRESS); ensure_equals("SUBPROCESS_BEFORE_FIRST_EXEC is in the PERFORMED state", e.getJourney().getStepInfo(SUBPROCESS_BEFORE_FIRST_EXEC).state, STEP_PERFORMED); ensure_equals("SUBPROCESS_SPAWN_ENV_SETUPPER_BEFORE_SHELL is in the ERRORED state", e.getJourney().getStepInfo(SUBPROCESS_SPAWN_ENV_SETUPPER_BEFORE_SHELL).state, STEP_ERRORED); ensure_equals("SUBPROCESS_OS_SHELL is in the NOT_STARTED state", e.getJourney().getStepInfo(SUBPROCESS_OS_SHELL).state, STEP_NOT_STARTED); ensure_equals("SUBPROCESS_SPAWN_ENV_SETUPPER_AFTER_SHELL is in the NOT_STARTED state", e.getJourney().getStepInfo(SUBPROCESS_SPAWN_ENV_SETUPPER_AFTER_SHELL).state, STEP_NOT_STARTED); } } TEST_METHOD(56) { set_test_name("If the subprocess fails without setting a specific" " journey step to the ERRORED state," " and there is no subprocess journey step in the IN_PROGRESS state," " and no subprocess journey steps are in the PERFORMED state," " then we set the first subprocess journey step to the ERRORED state"); init(SPAWN_DIRECTLY); pid = fork(); if (pid == 0) { // Exit child _exit(1); } try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals("SPAWNING_KIT_HANDSHAKE_PERFORM is in the IN_PROGRESS state", e.getJourney().getStepInfo(SPAWNING_KIT_HANDSHAKE_PERFORM).state, STEP_IN_PROGRESS); ensure_equals("SUBPROCESS_BEFORE_FIRST_EXEC is in the ERRORED state", e.getJourney().getStepInfo(SUBPROCESS_BEFORE_FIRST_EXEC).state, STEP_ERRORED); ensure_equals("SUBPROCESS_SPAWN_ENV_SETUPPER_BEFORE_SHELL is in the NOT_STARTED state", e.getJourney().getStepInfo(SUBPROCESS_SPAWN_ENV_SETUPPER_BEFORE_SHELL).state, STEP_NOT_STARTED); } } TEST_METHOD(57) { set_test_name("If the subprocess fails without setting a specific" " journey step to the ERRORED state," " and there is no subprocess journey step in the IN_PROGRESS state," " and some but not all subprocess journey steps are in the PERFORMED state," " then we set the step that comes right after the last PERFORMED step," " to the ERRORED state"); init(SPAWN_DIRECTLY); pid = fork(); if (pid == 0) { // Exit child _exit(1); } createFile(session->responseDir + "/steps/subprocess_before_first_exec/state", "STEP_PERFORMED"); createFile(session->responseDir + "/steps/subprocess_before_first_exec/duration", "1"); try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals("SPAWNING_KIT_HANDSHAKE_PERFORM is in the IN_PROGRESS state", e.getJourney().getStepInfo(SPAWNING_KIT_HANDSHAKE_PERFORM).state, STEP_IN_PROGRESS); ensure_equals("SUBPROCESS_BEFORE_FIRST_EXEC is in the PERFORMED state", e.getJourney().getStepInfo(SUBPROCESS_BEFORE_FIRST_EXEC).state, STEP_PERFORMED); ensure_equals("SUBPROCESS_SPAWN_ENV_SETUPPER_BEFORE_SHELL is in the ERRORED state", e.getJourney().getStepInfo(SUBPROCESS_SPAWN_ENV_SETUPPER_BEFORE_SHELL).state, STEP_ERRORED); ensure_equals("SUBPROCESS_OS_SHELL is in the NOT_STARTED state", e.getJourney().getStepInfo(SUBPROCESS_OS_SHELL).state, STEP_NOT_STARTED); ensure_equals("SUBPROCESS_SPAWN_ENV_SETUPPER_AFTER_SHELL is in the NOT_STARTED state", e.getJourney().getStepInfo(SUBPROCESS_SPAWN_ENV_SETUPPER_AFTER_SHELL).state, STEP_NOT_STARTED); } } TEST_METHOD(58) { set_test_name("If the subprocess fails without setting a specific" " journey step to the ERRORED state," " and there is no subprocess journey step in the IN_PROGRESS state," " and all subprocess journey steps are in the PERFORMED state," " then we set the last subprocess step to the ERRORED state"); init(SPAWN_DIRECTLY); pid = fork(); if (pid == 0) { // Exit child _exit(1); } JourneyStep firstStep = getFirstSubprocessJourneyStep(); JourneyStep lastStep = getLastSubprocessJourneyStep(); JourneyStep step; for (step = firstStep; step < lastStep; step = JourneyStep((int) step + 1)) { if (!session->journey.hasStep(step)) { continue; } createFile(session->responseDir + "/steps/" + journeyStepToStringLowerCase(step) + "/state", "STEP_PERFORMED"); createFile(session->responseDir + "/steps/" + journeyStepToStringLowerCase(step) + "/duration", "1"); } try { execute(); fail("SpawnException expected"); } catch (const SpawnException &e) { ensure_equals("SPAWNING_KIT_HANDSHAKE_PERFORM is in the IN_PROGRESS state", e.getJourney().getStepInfo(SPAWNING_KIT_HANDSHAKE_PERFORM).state, STEP_IN_PROGRESS); ensure_equals("SUBPROCESS_BEFORE_FIRST_EXEC is in the PERFORMED state", e.getJourney().getStepInfo(SUBPROCESS_BEFORE_FIRST_EXEC).state, STEP_PERFORMED); ensure_equals("SUBPROCESS_SPAWN_ENV_SETUPPER_BEFORE_SHELL is in the PERFORMED state", e.getJourney().getStepInfo(SUBPROCESS_SPAWN_ENV_SETUPPER_BEFORE_SHELL).state, STEP_PERFORMED); ensure_equals("SUBPROCESS_OS_SHELL is in the PERFORMED state", e.getJourney().getStepInfo(SUBPROCESS_OS_SHELL).state, STEP_PERFORMED); ensure_equals("SUBPROCESS_SPAWN_ENV_SETUPPER_AFTER_SHELL is in the PERFORMED state", e.getJourney().getStepInfo(SUBPROCESS_SPAWN_ENV_SETUPPER_AFTER_SHELL).state, STEP_PERFORMED); ensure_equals("SUBPROCESS_APP_LOAD_OR_EXEC is in the PERFORMED state", e.getJourney().getStepInfo(SUBPROCESS_APP_LOAD_OR_EXEC).state, STEP_PERFORMED); ensure_equals("SUBPROCESS_APP_LOAD_OR_EXEC is in the PERFORMED state", e.getJourney().getStepInfo(SUBPROCESS_APP_LOAD_OR_EXEC).state, STEP_PERFORMED); ensure_equals("SUBPROCESS_LISTEN is in the PERFORMED state", e.getJourney().getStepInfo(SUBPROCESS_LISTEN).state, STEP_PERFORMED); ensure_equals("SUBPROCESS_FINISH is in the ERRORED state", e.getJourney().getStepInfo(SUBPROCESS_FINISH).state, STEP_ERRORED); } } }
31.630701
122
0.727247
m5o
dc218df738ec770a57a06c101e884a29706610e6
1,106
cpp
C++
homework/Propazhin/04/matrix.cpp
nkotelevskii/msu_cpp_spring_2018
b5d84447f9b8c7f3615b421c51cf4192f1b90342
[ "MIT" ]
12
2018-02-20T15:25:12.000Z
2022-02-15T03:31:55.000Z
homework/Propazhin/04/matrix.cpp
nkotelevskii/msu_cpp_spring_2018
b5d84447f9b8c7f3615b421c51cf4192f1b90342
[ "MIT" ]
1
2018-02-26T12:40:47.000Z
2018-02-26T12:40:47.000Z
homework/Propazhin/04/matrix.cpp
nkotelevskii/msu_cpp_spring_2018
b5d84447f9b8c7f3615b421c51cf4192f1b90342
[ "MIT" ]
33
2018-02-20T15:25:11.000Z
2019-02-13T22:33:36.000Z
#include "matrix.h" #include <iostream> Matrix::~Matrix() { for (size_t i = 0; i < cols; i++) delete[] arr[i]; delete[] arr; } Matrix& Matrix::operator *= (int k) { for (size_t i = 0; i < cols; i++) for (size_t j = 0; j < rows; j++) arr[i][j] *= k; return *this; } bool Matrix::operator == (const Matrix &m) { if (rows != m.rows || cols != m.cols) return false; for (size_t i = 0; i < cols; i++) for (size_t j = 0; j < rows; j++) if (arr[i][j] != m.arr[i][j]) return false; return true; } bool Matrix::operator != (const Matrix &m) { return !(*this == m); } Row Matrix::operator[](size_t j) { if (j >= cols) throw std::out_of_range(""); return Row(arr[j], rows); } const Row Matrix::operator[](size_t j) const { if (j >= cols) throw std::out_of_range(""); return Row(arr[j], rows); } int& Row::operator [](size_t i) { if (i >= rows) throw std::out_of_range(""); return row[i]; } const int& Row::operator [](size_t i) const { if (i >= rows) throw std::out_of_range(""); return row[i]; }
19.75
55
0.536166
nkotelevskii
dc25ac98836587fdbea428d73ec9a32938708afe
626
cpp
C++
Codeforces/contests/Codeforces Round #740 (Div. 2, based on VK Cup 2021 - Final (Engine))/D.cpp
LeKSuS-04/Competitive-Programming
fbc86a8c6febeef72587a8f94135e92197e1f99e
[ "WTFPL" ]
null
null
null
Codeforces/contests/Codeforces Round #740 (Div. 2, based on VK Cup 2021 - Final (Engine))/D.cpp
LeKSuS-04/Competitive-Programming
fbc86a8c6febeef72587a8f94135e92197e1f99e
[ "WTFPL" ]
null
null
null
Codeforces/contests/Codeforces Round #740 (Div. 2, based on VK Cup 2021 - Final (Engine))/D.cpp
LeKSuS-04/Competitive-Programming
fbc86a8c6febeef72587a8f94135e92197e1f99e
[ "WTFPL" ]
null
null
null
/* D. Up the Strip */ // https://codeforces.com/contest/1561/problem/D1 // Date: Aug/24/2021 18:29 (00:54:05) // Runtime: 6000 ms // Memory: 29160 KB // Verdict: TLE #include <iostream> #include <string.h> using namespace std; int n, m; int memo[4000010]; int count(int x) { if (memo[x] != -1) return memo[x]; if (x == 1) return 1; long long ans = 0; for (int y = 1; y <= x - 1; y++) ans = (ans + count(x - y)) % m; for (int z = 2; z <= x; z++) ans = (ans + count(x / z)) % m; return memo[x] = ans; } int main() { cin >> n >> m; memset(memo, -1, sizeof memo); cout << count(n); }
21.586207
68
0.535144
LeKSuS-04
dc25d7aff1fd976c19d99335e047bf0468cbcf07
4,090
hpp
C++
openstudiocore/src/project/ConcreteObjectRecords.hpp
ORNL-BTRIC/OpenStudio
878f94bebf6f025445d1373e8b2304ececac16d8
[ "blessing" ]
null
null
null
openstudiocore/src/project/ConcreteObjectRecords.hpp
ORNL-BTRIC/OpenStudio
878f94bebf6f025445d1373e8b2304ececac16d8
[ "blessing" ]
null
null
null
openstudiocore/src/project/ConcreteObjectRecords.hpp
ORNL-BTRIC/OpenStudio
878f94bebf6f025445d1373e8b2304ececac16d8
[ "blessing" ]
null
null
null
/********************************************************************** * Copyright (c) 2008-2014, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #ifndef PROJECT_CONCRETEOBJECTRECORDS_HPP #define PROJECT_CONCRETEOBJECTRECORDS_HPP // utilities #include <project/AttributeRecord.hpp> #include <project/CloudSessionRecord.hpp> #include <project/CloudSettingsRecord.hpp> #include <project/FileReferenceRecord.hpp> #include <project/TagRecord.hpp> #include <project/UrlRecord.hpp> #include <project/URLSearchPathRecord.hpp> #include <project/VagrantSessionRecord.hpp> #include <project/VagrantSettingsRecord.hpp> // runmanager #include <project/WorkflowRecord.hpp> // ruleset #include <project/OSArgumentRecord.hpp> // analysis #include <project/AnalysisRecord.hpp> #include <project/DataPointRecord.hpp> #include <project/DataPointValueRecord.hpp> #include <project/DDACEAlgorithmRecord.hpp> #include <project/DesignOfExperimentsRecord.hpp> #include <project/FSUDaceAlgorithmRecord.hpp> #include <project/LinearFunctionRecord.hpp> #include <project/MeasureGroupRecord.hpp> #include <project/NullMeasureRecord.hpp> #include <project/OptimizationDataPointRecord.hpp> #include <project/OptimizationProblemRecord.hpp> #include <project/OutputAttributeVariableRecord.hpp> #include <project/ParameterStudyAlgorithmRecord.hpp> #include <project/ProblemRecord.hpp> #include <project/PSUADEDaceAlgorithmRecord.hpp> #include <project/RubyContinuousVariableRecord.hpp> #include <project/RubyMeasureRecord.hpp> #include <project/SamplingAlgorithmRecord.hpp> #include <project/SequentialSearchRecord.hpp> // utilities #include <project/AttributeRecord_Impl.hpp> #include <project/CloudSessionRecord_Impl.hpp> #include <project/CloudSettingsRecord_Impl.hpp> #include <project/FileReferenceRecord_Impl.hpp> #include <project/TagRecord_Impl.hpp> #include <project/UrlRecord_Impl.hpp> #include <project/URLSearchPathRecord_Impl.hpp> #include <project/VagrantSessionRecord_Impl.hpp> #include <project/VagrantSettingsRecord_Impl.hpp> // runmanager #include <project/WorkflowRecord_Impl.hpp> // ruleset #include <project/OSArgumentRecord_Impl.hpp> // analysis #include <project/AnalysisRecord_Impl.hpp> #include <project/DataPointRecord_Impl.hpp> #include <project/DataPointValueRecord_Impl.hpp> #include <project/DDACEAlgorithmRecord_Impl.hpp> #include <project/DesignOfExperimentsRecord_Impl.hpp> #include <project/FSUDaceAlgorithmRecord_Impl.hpp> #include <project/LinearFunctionRecord_Impl.hpp> #include <project/MeasureGroupRecord_Impl.hpp> #include <project/NullMeasureRecord_Impl.hpp> #include <project/OptimizationDataPointRecord_Impl.hpp> #include <project/OptimizationProblemRecord_Impl.hpp> #include <project/OutputAttributeVariableRecord_Impl.hpp> #include <project/ParameterStudyAlgorithmRecord_Impl.hpp> #include <project/ProblemRecord_Impl.hpp> #include <project/PSUADEDaceAlgorithmRecord_Impl.hpp> #include <project/RubyContinuousVariableRecord_Impl.hpp> #include <project/RubyMeasureRecord_Impl.hpp> #include <project/SamplingAlgorithmRecord_Impl.hpp> #include <project/SequentialSearchRecord_Impl.hpp> #endif // PROJECT_CONCRETEOBJECTRECORDS_HPP
40.9
83
0.771394
ORNL-BTRIC
dc27846a28ec616352a0fc676d036a4916953736
357
hpp
C++
function.hpp
Kayasama/Mine-Sweeper-master
f7f6cb54cba1ee86ba6b84302be88bb949f99740
[ "MIT" ]
null
null
null
function.hpp
Kayasama/Mine-Sweeper-master
f7f6cb54cba1ee86ba6b84302be88bb949f99740
[ "MIT" ]
null
null
null
function.hpp
Kayasama/Mine-Sweeper-master
f7f6cb54cba1ee86ba6b84302be88bb949f99740
[ "MIT" ]
null
null
null
#ifndef _FUNCTION_HPP #define _FUNCTION_HPP #include <SDL2/SDL.h> #include <string> #include "block.hpp" void gameover(const std::string &message); block *XYtoArr(int x, int y); void dfs(block *it); block *mouseToArr(int _x, int _y); void setball(); void init(); inline void clock(const unsigned int frames_per_second); void my_time_update(bool); #endif
19.833333
56
0.747899
Kayasama
dc28d53b00a958fb711ad49fcc2ab21a0a8a650d
612
cpp
C++
Searching/1. Linear Search/Linear Search.cpp
kanitmann/DSA_mastery
9b006892f24c697aae98ede0be203b87ad67c16a
[ "MIT" ]
1
2021-03-03T19:07:41.000Z
2021-03-03T19:07:41.000Z
Searching/1. Linear Search/Linear Search.cpp
kanitmann/DSA_mastery
9b006892f24c697aae98ede0be203b87ad67c16a
[ "MIT" ]
null
null
null
Searching/1. Linear Search/Linear Search.cpp
kanitmann/DSA_mastery
9b006892f24c697aae98ede0be203b87ad67c16a
[ "MIT" ]
null
null
null
#include<iostream> #define MAX_SIZE 5 int sort(int arr[MAX_SIZE], int key) { int pos = 0; for(int i=0;i<MAX_SIZE;i++) { if(arr[i]==key) return(i); } return (-1); } int main() { int list[MAX_SIZE]; int ele; std::cout<<"Enter Array: "; for(int i = 0; i<MAX_SIZE;i++){ std::cin>>list[i]; } std::cout<<"\n\nEnter element to search: "; std::cin>>ele; int pos = sort(list,ele); if (pos==-1) std::cout<<"\nElement not found."; else std::cout<<"\nElement found at position "<<pos+1; return 0; }
20.4
54
0.503268
kanitmann
dc2ae9cd37386c66d6357345fa01b89e2cc54e02
4,899
hpp
C++
code/linear/tropical.hpp
Brunovsky/competitive
41cf49378e430ca20d844f97c67aa5059ab1e973
[ "MIT" ]
1
2020-02-10T09:15:59.000Z
2020-02-10T09:15:59.000Z
code/linear/tropical.hpp
Brunovsky/kickstart
41cf49378e430ca20d844f97c67aa5059ab1e973
[ "MIT" ]
null
null
null
code/linear/tropical.hpp
Brunovsky/kickstart
41cf49378e430ca20d844f97c67aa5059ab1e973
[ "MIT" ]
null
null
null
#pragma once #include <bits/stdc++.h> using namespace std; // Tropical matrix operations (max plus or min plus) template <typename T> struct tmat { using vec = vector<T>; using unit_type = T; static constexpr T inf = numeric_limits<T>::lowest() / 2; static const T add(const T& a, const T& b) { return max(a, b); } static const T mul(const T& a, const T& b) { return a + b; } int n, m; T* data = nullptr; tmat() : n(0), m(0) {} tmat(int n, int m, const T& v = inf) { assign(n, m, v); } tmat(const tmat& o) : n(o.n), m(o.m), data(new T[n * m]) { copy(o.data, o.data + n * m, data); } tmat(tmat&& o) : tmat() { *this = move(o); } tmat& operator=(const tmat& o) { return *this = tmat(o); } tmat& operator=(tmat&& o) noexcept { using std::swap; swap(n, o.n), swap(m, o.m), swap(data, o.data); return *this; } ~tmat() { delete[] data; } bool operator==(const tmat& o) const { return n == o.n && m == o.m && equal(data, data + n * m, o.data); } bool operator!=(const tmat& o) const { return !(*this == o); } void assign(int n, int m, const T& v) { this->n = n, this->m = m, delete[] data, data = new T[n * m]; std::fill(data, data + n * m, v); } array<int, 2> size() const { return {n, m}; } T* operator[](int x) const { return data + x * m; } T& operator[](array<int, 2> xy) const { return data + (xy[0] * m + xy[1]); } template <typename U> static tmat from(const vector<vector<U>>& vals) { int n = vals.size(), m = n ? vals[0].size() : 0; tmat a(n, m); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) a[i][j] = vals[i][j]; return a; } template <typename O = T> friend auto tovec(const tmat& a) { vector<vector<O>> m(a.n, vector<T>(a.m)); for (int i = 0; i < a.n; i++) for (int j = 0; j < a.m; j++) m[i][j] = a[i][j]; return m; } static tmat identity(int n) { tmat a(n, n, inf); for (int i = 0; i < n; i++) a[i][i] = 0; return a; } friend tmat transpose(const tmat& a) { tmat b(a.m, a.n); for (int i = 0; i < a.m; i++) for (int j = 0; j < a.n; j++) b[i][j] = a[j][i]; return b; } friend tmat& operator+=(tmat& a, const tmat& b) { assert(a.size() == b.size() && "Different matrix dimensions"); for (int i = 0, s = a.n * a.m; i < s; i++) a[i] = add(a[i], b[i]); return a; } friend tmat operator*(const tmat& a, const tmat& b) { assert(a.m == b.n && "Invalid proper matrix multiplication"); tmat c(a.n, b.m, inf); for (int i = 0; i < a.n; i++) for (int k = 0; k < a.m; k++) for (int j = 0; j < b.m; j++) c[i][j] = add(c[i][j], mul(a[i][k], b[k][j])); return c; } friend vec operator*(const tmat& a, const vec& b) { assert(a.m == int(b.size()) && "Invalid matrix/vector multiplication"); vec c(a.n, inf); for (int i = 0; i < a.n; i++) for (int j = 0; j < a.m; j++) c[i] = add(c[i], mul(a[i][j], b[j])); return c; } friend tmat operator^(tmat a, int64_t e) { assert(a.n == a.m && "Matrix exp operand is not square"); tmat c = tmat::identity(a.n); while (e > 0) { if (e & 1) c = c * a; if (e >>= 1) a = a * a; } return c; } friend tmat operator+(tmat a, const tmat& b) { return a += b; } tmat operator*=(const tmat& b) { return *this = *this * b; } tmat operator^=(int64_t e) { return *this = *this ^ e; } friend string to_string(const tmat& a) { vector<vector<string>> cell(a.n, vector<string>(a.m)); vector<size_t> w(a.m); for (int i = 0; i < a.n; i++) { for (int j = 0; j < a.m; j++) { using std::to_string; if constexpr (std::is_same<T, string>::value) { cell[i][j] = a[i][j]; } else { cell[i][j] = to_string(a[i][j]); } w[j] = max(w[j], cell[i][j].size()); } } string s; for (int i = 0; i < a.n; i++) { for (int j = 0; j < a.m; j++) { s += string(w[j] + 1 - cell[i][j].size(), ' '); s += cell[i][j]; } s += '\n'; } return s; } friend ostream& operator<<(ostream& out, const tmat& a) { return out << to_string(a); } friend istream& operator>>(istream& in, tmat& a) { for (int i = 0; i < a.n * a.m; i++) in >> a.data[i]; return in; } };
31.606452
80
0.441519
Brunovsky
dc2bedf536d5a1d5870e4417529522bcc453dcb7
1,234
cpp
C++
src/gfx/device.cpp
Necrys/engine
c4a69bcfa39d6410b7c24f142f692de1df145ffc
[ "Unlicense" ]
null
null
null
src/gfx/device.cpp
Necrys/engine
c4a69bcfa39d6410b7c24f142f692de1df145ffc
[ "Unlicense" ]
null
null
null
src/gfx/device.cpp
Necrys/engine
c4a69bcfa39d6410b7c24f142f692de1df145ffc
[ "Unlicense" ]
null
null
null
#include <glapi.h> #include <device.h> #include <config.h> #include <window.h> #include <GLFW/glfw3.h> #include <GL/gl.h> namespace engine { namespace gfx { Device::Device(Window& wnd): m_log("GFX_DEVICE"), m_window(wnd) { } bool Device::init() { m_log.debug("init"); if (!glapi::init()) { OGL_CHECK_ERRORS(); return false; } glClearColor(0.1f, 0.1f, 0.25f, 1.0f); glClearDepth(1.0f); glDisable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glFrontFace(GL_CW); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); return OGL_CHECK_ERRORS(); } void Device::swapBuffers() { glFinish(); glfwSwapBuffers(m_window.handle()); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); OGL_CHECK_ERRORS(); } void Device::onResize(const int width, const int height) { glViewport(0, 0, width, height); OGL_CHECK_ERRORS(); for (auto cb: m_resizeCallbacks) { cb(width, height); } } void Device::registerOnResizeCallback(ResizeCb cb) { m_resizeCallbacks.push_back(cb); } void Device::getFramebufferSize(int* width, int* height) { glfwGetFramebufferSize(m_window.handle(), width, height); } } //gfx } //engine
18.984615
61
0.664506
Necrys
dc2f19297e0c528f98ef5d47fc7902bac8ede3ca
2,151
hpp
C++
include/coco/combix/combinators/choice.hpp
agatan/coco
e19e74cf97d788b435351379296ea3ead901c576
[ "BSL-1.0" ]
1
2016-08-31T04:44:17.000Z
2016-08-31T04:44:17.000Z
include/coco/combix/combinators/choice.hpp
agatan/coco
e19e74cf97d788b435351379296ea3ead901c576
[ "BSL-1.0" ]
null
null
null
include/coco/combix/combinators/choice.hpp
agatan/coco
e19e74cf97d788b435351379296ea3ead901c576
[ "BSL-1.0" ]
null
null
null
#ifndef COCO_COMBIX_COMBINATORS_CHOICE_HPP_ #define COCO_COMBIX_COMBINATORS_CHOICE_HPP_ #include <type_traits> #include <utility> #include <coco/combix/error.hpp> #include <coco/combix/parser_traits.hpp> namespace coco { namespace combix { template <typename... P> struct choice_parser; template <typename P> struct choice_parser<P> { choice_parser(P const& p) : p(p) {} template <typename Stream> parse_result<parse_result_of_t<P, Stream>, Stream> parse(Stream& s) const { return coco::combix::parse(p, s); } template <typename Stream> void add_error(parse_error<Stream>& err) const { p.add_error(err); } private: P p; }; template <typename Head, typename... Tail> struct choice_parser<Head, Tail...> : choice_parser<Tail...> { using base_type = choice_parser<Tail...>; choice_parser(Head const& h, Tail const&... tail) : choice_parser<Tail...>(tail...), p(h) {} template <typename Stream> typename std::enable_if< std::is_same<parse_result_of_t<Head, Stream>, parse_result_of_t<base_type, Stream>>::value, parse_result<parse_result_of_t<Head, Stream>, Stream>>::type parse(Stream& s) const { auto res = coco::combix::parse(p, s); if (res) { return res; } else if (res.unwrap_error().consumed()) { return res.unwrap_error(); } auto tail_res = base_type::parse(s); if (tail_res) { return tail_res; } res.unwrap_error().merge(std::move(tail_res.unwrap_error())); return res.unwrap_error(); } template <typename Stream> void add_error(parse_error<Stream>& err) const { p.add_error(err); base_type::add_error(err); } private: Head p; }; template <typename... Args> choice_parser<std::decay_t<Args>...> choice(Args&&... args) { return choice_parser<std::decay_t<Args>...>(std::forward<Args>(args)...); } } // namespace combix } // namespace coco #endif
26.231707
79
0.598326
agatan
dc310cc44ed33e191a9bcd380ff199740ab2f7f8
8,593
hpp
C++
cmdstan/stan/lib/stan_math/stan/math/torsten/events_record.hpp
csetraynor/Torsten
55b59b8068e2a539346f566ec698c755a9e3536c
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/stan/math/torsten/events_record.hpp
csetraynor/Torsten
55b59b8068e2a539346f566ec698c755a9e3536c
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/stan/math/torsten/events_record.hpp
csetraynor/Torsten
55b59b8068e2a539346f566ec698c755a9e3536c
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MATH_TORSTEN_NONMEN_EVENTS_RECORD_HPP #define STAN_MATH_TORSTEN_NONMEN_EVENTS_RECORD_HPP #include <stan/math/torsten/dsolve/pk_vars.hpp> #include <stan/math/torsten/return_type.hpp> #include <boost/math/tools/promotion.hpp> #include <Eigen/Dense> #include <numeric> #include <string> #include <vector> namespace torsten { /* * Raw events record in the form of NONMEN, except that * for the population input @c len consisting of data record * length for each individual. * @tparam T0 type of scalar for time of events. * @tparam T1 type of scalar for amount at each event. * @tparam T2 type of scalar for rate at each event. * @tparam T3 type of scalar for inter-dose inteveral at each event. * @tparam T4 type of scalars for the model parameters. * @tparam T5 type of scalars for the bio-variability parameters. * @tparam T6 type of scalars for the model tlag parameters. */ template <typename T0, typename T1, typename T2, typename T3, typename T4_container, typename T5, typename T6> struct NONMENEventsRecord { using T4 = typename stan::math::value_type<T4_container>::type; using T_scalar = typename torsten::return_t<T0, T1, T2, T3, T4, T5, T6>::type; using T_time = typename torsten::return_t<T0, T1, T3, T6, T2>::type; using T_rate = typename torsten::return_t<T2, T5>::type; using T_amt = typename torsten::return_t<T1, T5>::type; using T_par = T4; using T_par_rate = T2; using T_par_ii = T3; private: const std::vector<int> len_1_; public: const int nev; const int ncmt; std::vector<int> begin_; const std::vector<int>& len_; const int total_num_event_times; const std::vector<T0>& time_; const std::vector<T1>& amt_; const std::vector<T2>& rate_; const std::vector<T3>& ii_; const std::vector<int>& evid_; const std::vector<int>& cmt_; const std::vector<int>& addl_; const std::vector<int>& ss_; const std::vector<T4_container>& pMatrix_; const std::vector<std::vector<T5> >& biovar_; const std::vector<std::vector<T6> >& tlag_; /* * Constructor using population data with parameter give as * matrix, such as in linear ODE models * @param[in] n number of compartments in model * @param[in] len record length for each individual. * @param[in] time times of events * @param[in] amt amount at each event * @param[in] rate rate at each event * @param[in] ii inter-dose interval at each event * @param[in] evid event identity: * (0) observation * (1) dosing * (2) other * (3) reset * (4) reset AND dosing * @param[in] cmt compartment number at each event * @param[in] addl additional dosing at each event * @param[in] ss steady state approximation at each event (0: no, 1: yes) * @param[in] pMatrix parameters at each event * @param[in] biovar bioavailability * @param[in] tlag lag time */ template <typename T0_, typename T1_, typename T2_, typename T3_, typename T4_container_, typename T5_, typename T6_> NONMENEventsRecord(int n, const std::vector<int>& len, const std::vector<T0_>& time, const std::vector<T1_>& amt, const std::vector<T2_>& rate, const std::vector<T3_>& ii, const std::vector<int>& evid, const std::vector<int>& cmt, const std::vector<int>& addl, const std::vector<int>& ss, const std::vector<T4_container_>& pMatrix, const std::vector<std::vector<T5_> >& biovar, const std::vector<std::vector<T6_> >& tlag) : len_1_(), nev(time.size()), ncmt(n), begin_(len.size()), len_(len), total_num_event_times(std::accumulate(len_.begin(), len_.end(), 0)), time_ (time ), amt_ (amt ), rate_ (rate ), ii_ (ii ), evid_ (evid ), cmt_ (cmt ), addl_ (addl ), ss_ (ss ), pMatrix_(pMatrix), biovar_ (biovar ), tlag_ (tlag ) { begin_[0] = 0; std::partial_sum(len.begin(), len.end() - 1, begin_.begin() + 1); } /* * Constructor using individual data with parameter give as * matrix, such as in linear ODE models * @param[in] n number of compartments in model * @param[in] len record length for each individual. * @param[in] time times of events * @param[in] amt amount at each event * @param[in] rate rate at each event * @param[in] ii inter-dose interval at each event * @param[in] evid event identity: * (0) observation * (1) dosing * (2) other * (3) reset * (4) reset AND dosing * @param[in] cmt compartment number at each event * @param[in] addl additional dosing at each event * @param[in] ss steady state approximation at each event (0: no, 1: yes) * @param[in] pMatrix parameters at each event * @param[in] biovar bioavailability * @param[in] tlag lag time */ template <typename T0_, typename T1_, typename T2_, typename T3_, typename T4_container_, typename T5_, typename T6_> NONMENEventsRecord(int n, const std::vector<T0_>& time, const std::vector<T1_>& amt, const std::vector<T2_>& rate, const std::vector<T3_>& ii, const std::vector<int>& evid, const std::vector<int>& cmt, const std::vector<int>& addl, const std::vector<int>& ss, const std::vector<T4_container_>& pMatrix, const std::vector<std::vector<T5_> >& biovar, const std::vector<std::vector<T6_> >& tlag) : len_1_(1, time.size()), nev(time.size()), ncmt(n), begin_{0}, len_(len_1_), total_num_event_times(std::accumulate(len_.begin(), len_.end(), 0)), time_ (time ), amt_ (amt ), rate_ (rate ), ii_ (ii ), evid_ (evid ), cmt_ (cmt ), addl_ (addl ), ss_ (ss ), pMatrix_(pMatrix), biovar_ (biovar ), tlag_ (tlag ) {} /* * begin of the parameters for individual @c id * in @c pMatrix. It is assumed that all the paramter are * either constant or time dependent. */ int begin_param(int id) const { return pMatrix_.size() == len_.size() ? id : begin_[id]; } /* * length of the parameters for individual @c id * in @c pMatrix. It is assumed that all the paramter are * either constant or time dependent. */ int len_param(int id) const { return pMatrix_.size() == len_.size() ? 1 : len_[id]; } int begin_biovar(int id) const { return biovar_.size() == len_.size() ? id : begin_[id]; } int len_biovar(int id) const { return biovar_.size() == len_.size() ? 1 : len_[id]; } int begin_tlag(int id) const { return tlag_.size() == len_.size() ? id : begin_[id]; } int len_tlag(int id) const { return tlag_.size() == len_.size() ? 1 : len_[id]; } inline bool has_ss_dosing() const { return has_ss_dosing(0); } /* * check the exisitence of steady state dosing events */ inline bool has_ss_dosing(int id) const { bool res = false; int begin = begin_[id]; int end = size_t(id + 1) == len_.size() ? time_.size() : begin_[id + 1]; for (int i = begin; i < end; ++i) { if ((evid_[i] == 1 || evid_[i] == 4) && ss_[i] != 0) { res = true; break; } } return res; } /* * check for the exisitence of lag time */ bool has_lag(int id) const { using stan::math::value_of; return std::any_of(tlag_.begin() + begin_tlag(id), tlag_.begin() + begin_tlag(id) + len_tlag(id), [](const std::vector<T6>& v) { return std::any_of(v.begin(), v.end(), [](const T6& x) { return std::abs(value_of(x)) > 1.E-10; }); }); } /* * check for the exisitence of lag time */ bool has_lag() const { return has_lag(0); } inline int parameter_size() const { return pMatrix_[0].size(); } inline int num_event_times(int id) const { return len_.at(id); } inline int num_event_times() const { return len_.at(0); } inline int num_subjects() const { return len_.size(); } }; } #endif
32.673004
124
0.584895
csetraynor
dc3280a3a76518bc325fbc6be30ddd3f46936cd0
2,793
hpp
C++
include/framework/Parser.hpp
Vitaliy-Grigoriev/Protocol-Analyzer
853aef9cfe355db481f558a2cdee298cc57d0ee4
[ "MIT" ]
14
2018-02-06T20:45:00.000Z
2020-06-23T06:53:51.000Z
include/framework/Parser.hpp
Vitaliy-Grigoriev/http2-analyzer
853aef9cfe355db481f558a2cdee298cc57d0ee4
[ "MIT" ]
null
null
null
include/framework/Parser.hpp
Vitaliy-Grigoriev/http2-analyzer
853aef9cfe355db481f558a2cdee298cc57d0ee4
[ "MIT" ]
6
2018-02-03T11:53:52.000Z
2020-05-07T03:10:29.000Z
// ============================================================================ // Copyright (c) 2017-2019, by Vitaly Grigoriev, <[email protected]>. // This file is part of ProtocolAnalyzer open source project under MIT License. // ============================================================================ #ifndef PROTOCOL_ANALYZER_PARSER_HPP #define PROTOCOL_ANALYZER_PARSER_HPP #include <vector> #include <string_view> namespace analyzer::framework::parser { /** * @class PortsParser Parser.hpp "include/framework/Parser.hpp" * @brief Class that parses the range of ports. */ class PortsParser { private: /** * @brief Variable that contains the current value of range. */ uint16_t rangeState = 0; /** * @brief Variable that contains the last value of range. */ uint16_t rangeEnd = 0; /** * @brief Vector of strings that contains the split values on input. */ std::vector<std::string_view> inputStates = { }; public: /** * @brief Default constructor of PortsParser class. */ PortsParser(void) = default; /** * @brief Default destructor of PortsParser class. */ ~PortsParser(void) = default; PortsParser (PortsParser &&) = delete; PortsParser (const PortsParser &) = delete; PortsParser & operator= (PortsParser &&) = delete; PortsParser & operator= (const PortsParser &) = delete; /** * @brief Static variable that indicates the end of parsing or error. */ static const uint16_t end = 0; /** * @brief Constructor of PortParser class. * @param [in] ports - The sequence of ports listed through a separator. * @param [in] delimiter - The separator. Default: ','. * * @note For example: 80,1-5,433,25-36,90. */ explicit PortsParser (std::string_view /*ports*/, char /*delimiter*/ = ',') noexcept; /** * @brief Method that sets internal state of port parser. * @param [in] ports - The sequence of ports listed through a separator. * @param [in] delimiter - The separator. Default: ','. */ void SetPorts (std::string_view /*ports*/, char /*delimiter*/ = ',') noexcept; /** * @brief Method that gets next port value in input range. * @return Port number or PortsParser::end value if port enumeration is complete or an error occurred. * * @note The program MUST check the return value for PortsParser::end value. */ uint16_t GetNextPort(void) noexcept; }; } // namespace parser. #endif // PROTOCOL_ANALYZER_PARSER_HPP
33.25
110
0.56212
Vitaliy-Grigoriev
dc37ebc2fe2e18f2e37f8402565df01993e2b02f
1,290
inl
C++
include/msstl/converted/xcharconv.h.inl
iboB/mscharconv
7c4bd58ebabda50140ee833c8b869d6ca1d11243
[ "Apache-2.0" ]
34
2021-04-17T14:25:24.000Z
2021-08-21T19:22:58.000Z
include/msstl/converted/xcharconv.h.inl
iboB/mscharconv
7c4bd58ebabda50140ee833c8b869d6ca1d11243
[ "Apache-2.0" ]
1
2021-11-19T00:30:13.000Z
2021-11-26T04:13:38.000Z
include/msstl/converted/xcharconv.h.inl
iboB/mscharconv
7c4bd58ebabda50140ee833c8b869d6ca1d11243
[ "Apache-2.0" ]
3
2021-04-17T14:25:27.000Z
2021-08-06T08:28:09.000Z
// xcharconv.h internal header // Copyright (c) Microsoft Corporation. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception //~ #pragma once #ifndef _XCHARCONV_H #define _XCHARCONV_H //~ #include <yvals_core.h> //~ #if _STL_COMPILER_PREPROCESSOR //~ #include <cstdint> //~ #include <type_traits> //~ #include <xerrc.h> #if 0 //~#if !_HAS_CXX17 #error The contents of <charconv> are only available with C++17. (Also, you should not include this internal header.) #endif // !_HAS_CXX17 //~ #pragma pack(push, _CRT_PACKING) //~ #pragma warning(push, _STL_WARNING_LEVEL) //~ #pragma warning(disable : _STL_DISABLED_WARNINGS) //~ _STL_DISABLE_CLANG_WARNINGS //~ #pragma push_macro("new") //~ #undef new //~ _STD_BEGIN enum class chars_format { scientific = 0b001, fixed = 0b010, hex = 0b100, general = fixed | scientific, }; //~ _BITMASK_OPS(chars_format) struct to_chars_result { char* ptr; std::errc ec; #if 0 //~#if _HAS_CXX20 [[nodiscard]] friend bool operator==(const to_chars_result&, const to_chars_result&) = default; #endif // _HAS_CXX20 }; //~ _STD_END //~ #pragma pop_macro("new") //~ _STL_RESTORE_CLANG_WARNINGS //~ #pragma warning(pop) //~ #pragma pack(pop) //~ #endif // _STL_COMPILER_PREPROCESSOR #endif // _XCHARCONV_H
23.888889
117
0.693798
iboB
dc3a411dcdb33e8e5a1608ec599746c217ea97e4
734
hpp
C++
include/nall/string/char/utility.hpp
wareya/kotareci
14c87d1364d442456f93cebe73a288f85b79ba74
[ "Libpng" ]
null
null
null
include/nall/string/char/utility.hpp
wareya/kotareci
14c87d1364d442456f93cebe73a288f85b79ba74
[ "Libpng" ]
null
null
null
include/nall/string/char/utility.hpp
wareya/kotareci
14c87d1364d442456f93cebe73a288f85b79ba74
[ "Libpng" ]
null
null
null
#ifdef NALL_STRING_INTERNAL_HPP namespace nall { template<bool Insensitive> bool chrequal(char x, char y) { if(Insensitive) return chrlower(x) == chrlower(y); return x == y; } template<bool Quoted, typename T> bool quoteskip(T*& p) { if(Quoted == false) return false; if(*p != '\'' && *p != '\"') return false; while(*p == '\'' || *p == '\"') { char x = *p++; while(*p && *p++ != x); } return true; } template<bool Quoted, typename T> bool quotecopy(char*& t, T*& p) { if(Quoted == false) return false; if(*p != '\'' && *p != '\"') return false; while(*p == '\'' || *p == '\"') { char x = *p++; *t++ = x; while(*p && *p != x) *t++ = *p++; *t++ = *p++; } return true; } } #endif
18.35
52
0.506812
wareya
dc40a7c67eb1603a55fdb5c56b0fe89b3c260e25
8,226
cpp
C++
openstudiocore/src/model/test/GroundHeatExchangerVertical_GTest.cpp
hongyuanjia/OpenStudio
6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0
[ "MIT" ]
1
2019-04-21T15:38:54.000Z
2019-04-21T15:38:54.000Z
openstudiocore/src/model/test/GroundHeatExchangerVertical_GTest.cpp
hongyuanjia/OpenStudio
6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0
[ "MIT" ]
null
null
null
openstudiocore/src/model/test/GroundHeatExchangerVertical_GTest.cpp
hongyuanjia/OpenStudio
6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0
[ "MIT" ]
1
2019-07-18T06:52:29.000Z
2019-07-18T06:52:29.000Z
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote * products derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative * works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without * specific prior written permission from Alliance for Sustainable Energy, LLC. * * 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, THE UNITED STATES GOVERNMENT, OR ANY 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 <gtest/gtest.h> #include "ModelFixture.hpp" #include "../GroundHeatExchangerVertical.hpp" #include "../GroundHeatExchangerVertical_Impl.hpp" #include "../AirLoopHVAC.hpp" #include "../PlantLoop.hpp" #include "../Node.hpp" #include "../Node_Impl.hpp" #include "../AirLoopHVACZoneSplitter.hpp" using namespace openstudio; using namespace openstudio::model; TEST_F(ModelFixture, GroundHeatExchangerVertical_DefaultConstructor) { ::testing::FLAGS_gtest_death_test_style = "threadsafe"; ASSERT_EXIT ( { Model model; GroundHeatExchangerVertical testObject = GroundHeatExchangerVertical(model); exit(0); } , ::testing::ExitedWithCode(0), "" ); } TEST_F(ModelFixture, GroundHeatExchangerVertical_Connections) { Model m; GroundHeatExchangerVertical testObject(m); Node inletNode(m); Node outletNode(m); m.connect(inletNode,inletNode.outletPort(),testObject,testObject.inletPort()); m.connect(testObject,testObject.outletPort(),outletNode,outletNode.inletPort()); ASSERT_TRUE( testObject.inletModelObject() ); ASSERT_TRUE( testObject.outletModelObject() ); EXPECT_EQ( inletNode.handle(), testObject.inletModelObject()->handle() ); EXPECT_EQ( outletNode.handle(), testObject.outletModelObject()->handle() ); } TEST_F(ModelFixture, GroundHeatExchangerVertical_addToNode) { Model m; GroundHeatExchangerVertical testObject(m); AirLoopHVAC airLoop(m); Node supplyOutletNode = airLoop.supplyOutletNode(); EXPECT_FALSE(testObject.addToNode(supplyOutletNode)); EXPECT_EQ( (unsigned)2, airLoop.supplyComponents().size() ); Node inletNode = airLoop.zoneSplitter().lastOutletModelObject()->cast<Node>(); EXPECT_FALSE(testObject.addToNode(inletNode)); EXPECT_EQ((unsigned)5, airLoop.demandComponents().size()); PlantLoop plantLoop(m); supplyOutletNode = plantLoop.supplyOutletNode(); EXPECT_TRUE(testObject.addToNode(supplyOutletNode)); EXPECT_EQ( (unsigned)7, plantLoop.supplyComponents().size() ); Node demandOutletNode = plantLoop.demandOutletNode(); EXPECT_FALSE(testObject.addToNode(demandOutletNode)); EXPECT_EQ( (unsigned)5, plantLoop.demandComponents().size() ); GroundHeatExchangerVertical testObjectClone = testObject.clone(m).cast<GroundHeatExchangerVertical>(); supplyOutletNode = plantLoop.supplyOutletNode(); EXPECT_TRUE(testObjectClone.addToNode(supplyOutletNode)); EXPECT_EQ( (unsigned)9, plantLoop.supplyComponents().size() ); } TEST_F(ModelFixture, GroundHeatExchangerVertical_AddRemoveSupplyBranchForComponent) { Model model; GroundHeatExchangerVertical testObject(model); PlantLoop plantLoop(model); EXPECT_TRUE(plantLoop.addSupplyBranchForComponent(testObject)); EXPECT_EQ((unsigned)7, plantLoop.supplyComponents().size()); EXPECT_NE((unsigned)9, plantLoop.supplyComponents().size()); EXPECT_TRUE(testObject.inletPort()); EXPECT_TRUE(testObject.outletPort()); EXPECT_TRUE(plantLoop.removeSupplyBranchWithComponent(testObject)); EXPECT_EQ((unsigned)5, plantLoop.supplyComponents().size()); EXPECT_NE((unsigned)7, plantLoop.supplyComponents().size()); } TEST_F(ModelFixture, GroundHeatExchangerVertical_AddDemandBranchForComponent) { Model model; GroundHeatExchangerVertical testObject(model); PlantLoop plantLoop(model); EXPECT_FALSE(plantLoop.addDemandBranchForComponent(testObject)); EXPECT_EQ((unsigned)5, plantLoop.demandComponents().size()); EXPECT_NE((unsigned)7, plantLoop.demandComponents().size()); } TEST_F(ModelFixture, GroundHeatExchangerVertical_AddToNodeTwoSameObjects) { Model model; GroundHeatExchangerVertical testObject(model); PlantLoop plantLoop(model); Node supplyOutletNode = plantLoop.supplyOutletNode(); testObject.addToNode(supplyOutletNode); supplyOutletNode = plantLoop.supplyOutletNode(); EXPECT_FALSE(testObject.addToNode(supplyOutletNode)); } TEST_F(ModelFixture, GroundHeatExchangerVertical_Remove) { Model model; GroundHeatExchangerVertical testObject(model); PlantLoop plantLoop(model); Node supplyOutletNode = plantLoop.supplyOutletNode(); testObject.addToNode(supplyOutletNode); EXPECT_EQ((unsigned)7, plantLoop.supplyComponents().size()); testObject.remove(); EXPECT_EQ((unsigned)5, plantLoop.supplyComponents().size()); } //test cloning the object TEST_F(ModelFixture, GroundHeatExchangerVertical_Clone){ Model m; //make an object to clone, and edit some property to make sure the clone worked GroundHeatExchangerVertical testObject(m); testObject.setMaximumFlowRate(3.14); //clone into the same model GroundHeatExchangerVertical testObjectClone = testObject.clone(m).cast<GroundHeatExchangerVertical>(); EXPECT_EQ(3.14,testObjectClone.maximumFlowRate()); //clone into another model Model m2; GroundHeatExchangerVertical testObjectClone2 = testObject.clone(m2).cast<GroundHeatExchangerVertical>(); EXPECT_EQ(3.14,testObjectClone2.maximumFlowRate()); EXPECT_NE(testObjectClone2, testObjectClone); EXPECT_NE(testObjectClone2.handle(), testObjectClone.handle()); } TEST_F(ModelFixture, GroundHeatExchangerVertical_GFunctions) { Model model; GroundHeatExchangerVertical testObject(model); std::vector< GFunction > gFunctions = testObject.gFunctions(); EXPECT_EQ(35, gFunctions.size()); testObject.removeAllGFunctions(); gFunctions = testObject.gFunctions(); EXPECT_EQ(0, gFunctions.size()); EXPECT_TRUE(testObject.addGFunction(1.0, 1.5)); gFunctions = testObject.gFunctions(); EXPECT_EQ(1, gFunctions.size()); testObject.addGFunction(2.0, 2.5); testObject.removeGFunction(0); gFunctions = testObject.gFunctions(); EXPECT_EQ(1, gFunctions.size()); EXPECT_DOUBLE_EQ(2.0, gFunctions[0].lnValue()); EXPECT_DOUBLE_EQ(2.5, gFunctions[0].gValue()); testObject.removeAllGFunctions(); for (int i=0; i<100; i++) { testObject.addGFunction(i, i + 0.5); } gFunctions = testObject.gFunctions(); EXPECT_EQ(100, gFunctions.size()); EXPECT_THROW(testObject.addGFunction(1.0, 1.5), openstudio::Exception); }
37.221719
120
0.752127
hongyuanjia
dc42d4f656d36b3228e4cc905fd4ae855bd88645
1,529
cpp
C++
test/function/leak/target.cpp
Jk-bit/stumpless
e7374b7b9f5618b335c5e657c759a5c47fb8499f
[ "Apache-2.0" ]
28
2019-03-20T22:33:11.000Z
2022-03-19T16:59:21.000Z
test/function/leak/target.cpp
Jk-bit/stumpless
e7374b7b9f5618b335c5e657c759a5c47fb8499f
[ "Apache-2.0" ]
204
2017-10-08T22:26:31.000Z
2022-03-26T16:16:51.000Z
test/function/leak/target.cpp
Jk-bit/stumpless
e7374b7b9f5618b335c5e657c759a5c47fb8499f
[ "Apache-2.0" ]
30
2020-01-17T17:48:49.000Z
2022-03-13T06:18:20.000Z
// SPDX-License-Identifier: Apache-2.0 /* * Copyright 2019-2020 Joel E. Anderson * * 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 <stddef.h> #include <stumpless.h> #include <gtest/gtest.h> #include "test/helper/memory_counter.hpp" #define TEST_BUFFER_LENGTH 2048 NEW_MEMORY_COUNTER( add_message_leak ) namespace { TEST( AddMessageLeakTest, TypicalUse ) { struct stumpless_target *target; char buffer[TEST_BUFFER_LENGTH]; int i; int add_result; INIT_MEMORY_COUNTER( add_message_leak ); target = stumpless_open_buffer_target( "add-message-leak-testing", buffer, sizeof( buffer ) ); ASSERT_TRUE( target != NULL ); for( i = 0; i < 1000; i++ ) { add_result = stumpless_add_message( target, "temp message %d", i ); ASSERT_GE( add_result, 0 ); } stumpless_close_buffer_target( target ); stumpless_free_all( ); ASSERT_NO_LEAK( add_message_leak ); } }
27.8
75
0.671681
Jk-bit
dc43ac26e14ecadfa5e82081eaa80a7b45c1a934
5,295
cpp
C++
Source/ObjectProxy.cpp
nolancs/OrangeMUD
3db3ddf73855bb76110d7a6a8e67271c36652b04
[ "MIT" ]
4
2020-01-25T04:20:07.000Z
2022-01-14T02:59:28.000Z
Source/ObjectProxy.cpp
nolancs/OrangeMUD
3db3ddf73855bb76110d7a6a8e67271c36652b04
[ "MIT" ]
null
null
null
Source/ObjectProxy.cpp
nolancs/OrangeMUD
3db3ddf73855bb76110d7a6a8e67271c36652b04
[ "MIT" ]
1
2020-04-01T04:36:48.000Z
2020-04-01T04:36:48.000Z
/****************************************************************************** Author: Matthew Nolan OrangeMUD Codebase Date: January 2001 [Crossplatform] License: 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. Copyright 2000-2019 Matthew Nolan, All Rights Reserved ******************************************************************************/ #include "CommonTypes.h" #include "ObjectIndex.h" #include "ObjectProxy.h" ObjectProxy::ObjectProxy() : mObject(NULL) { } ObjectProxy::~ObjectProxy() { } bool ObjectProxy::IsCustom() { return mCustomObject.IsNull() ? false : true; } void ObjectProxy::Customize() { if(mCustomObject.Ptr()) return; APtr<ObjectData> nCustom(new ObjectData(GetIndex())); mCustomObject = nCustom.Detach(); mObject = mCustomObject; } void ObjectProxy::Revert() { mCustomObject.Dispose(); mObject = GetIndex()->GetFlyweight(); ASSERT(mObject); } #if 0 //***************************************************************************// /////////////////////////////////////////////////////////////////////////////// //***************************************************************************// #pragma mark - #endif const STRINGCW& ObjectProxy::Name() const { return mObject->mName; } const STRINGCW& ObjectProxy::PName() const { return mObject->mPName; } const STRINGCW& ObjectProxy::Keywords() const { return mObject->mKeywords; } const STRINGCW& ObjectProxy::ShortDesc() const { return mObject->mShortDesc; } const STRINGCW& ObjectProxy::PShortDesc() const { return mObject->mPShortDesc; } const STRINGCW& ObjectProxy::Description() const { return mObject->mDescription; } LONG ObjectProxy::Value(SHORT hIndex) const { return mObject->mValue[hIndex]; } LONG ObjectProxy::WearFlags() const { return GetIndex()->mWearFlags; } SHORT ObjectProxy::ItemType() const { return GetIndex()->mItemType; } float ObjectProxy::Weight() const { return mObject->mWeight; } #if 0 //***************************************************************************// /////////////////////////////////////////////////////////////////////////////// //***************************************************************************// #pragma mark - #endif STRINGCW& ObjectProxy::xName() { Customize(); return mObject->mName; } STRINGCW& ObjectProxy::xPName() { Customize(); return mObject->mPName; } STRINGCW& ObjectProxy::xKeywords() { Customize(); return mObject->mKeywords; } STRINGCW& ObjectProxy::xShortDesc() { Customize(); return mObject->mShortDesc; } STRINGCW& ObjectProxy::xPShortDesc() { Customize(); return mObject->mPShortDesc; } STRINGCW& ObjectProxy::xDescription() { Customize(); return mObject->mDescription; } LONG& ObjectProxy::xValue(SHORT hIndex) { Customize(); return mObject->mValue[hIndex]; } #if 0 //***************************************************************************// /////////////////////////////////////////////////////////////////////////////// //***************************************************************************// #pragma mark - #endif ObjectData::ObjectData(ObjectIndex* hLikeObj) { ASSERT(hLikeObj); mName = hLikeObj->mName; mPName = hLikeObj->mPName; mKeywords = hLikeObj->mKeywords; mShortDesc = hLikeObj->mShortDesc; mPShortDesc = hLikeObj->mPShortDesc; mDescription = hLikeObj->mDescription; mItemType = hLikeObj->mItemType; mLevel = hLikeObj->mLevel; mWeight = hLikeObj->mWeight; mMaterials = hLikeObj->mMaterials; mAntiFlags = hLikeObj->mAntiFlags; mObjectFlags = hLikeObj->mObjectFlags; mValue[0] = hLikeObj->mValue[0]; mValue[1] = hLikeObj->mValue[1]; mValue[2] = hLikeObj->mValue[2]; mValue[3] = hLikeObj->mValue[3]; mValue[4] = hLikeObj->mValue[4]; //Only exist in Customized Objects: mAge = 0; mOwner = ""; mTimer = 0; mEnchantment = 0; } ObjectData::~ObjectData() { }
19.046763
79
0.552786
nolancs
dc465eb06aee5b46116e2c94acc01f27161d8217
5,761
cpp
C++
src/DialogManager/DialogManager/src/CExpressionPicker.cpp
xylsxyls/xueyelingshuan
61eb1c7c4f76c3eaf4cf26e4b2b37b6ed2abc5b9
[ "MIT" ]
3
2019-11-26T05:33:47.000Z
2020-05-18T06:49:41.000Z
src/DialogManager/DialogManager/src/CExpressionPicker.cpp
xylsxyls/xueyelingshuan
61eb1c7c4f76c3eaf4cf26e4b2b37b6ed2abc5b9
[ "MIT" ]
null
null
null
src/DialogManager/DialogManager/src/CExpressionPicker.cpp
xylsxyls/xueyelingshuan
61eb1c7c4f76c3eaf4cf26e4b2b37b6ed2abc5b9
[ "MIT" ]
null
null
null
#include "CExpressionPicker.h" #include <QHeaderView> #include <QMouseEvent> #include "CExpressionPickerDelegate.h" #include <QDebug> CExpressionPicker::CExpressionPicker(QWidget *parent) :QTableView(parent) ,mModel(new QStandardItemModel(this)) ,mPreView(new QLabel(this)) ,mShowPreView(false) ,mShowIconRect(true) ,mMaxColumnCount(12) ,mMaxRowCount(4) ,mMovie(new QMovie(this)) { this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); this->horizontalHeader()->setVisible(false); this->verticalHeader()->setVisible(false); this->horizontalHeader()->setDefaultSectionSize(33); this->verticalHeader()->setDefaultSectionSize(33); this->setEditTriggers(QTableView::NoEditTriggers); this->setSelectionMode(QTableView::SingleSelection); this->setShowGrid(false); this->setMouseTracking(true); this->setStyleSheet("QTableView{background-color:rgba(0,0,0,0);border:none;}"); this->setModel(mModel); connect(this, &CExpressionPicker::clicked, this, &CExpressionPicker::onClicked); //delegate CExpressionPickerDelegate* tdelegate = new CExpressionPickerDelegate; tdelegate->setParent(this); this->setItemDelegate(tdelegate); //pre viewer mPreView->setMouseTracking(true); mPreView->hide(); mPreView->resize(33*2,33*2); mPreView->setStyleSheet("background-color:white;"); mPreView->installEventFilter(this); mMovie->setScaledSize(mPreView->size()); mMovie->setCacheMode(QMovie::CacheAll); mPreView->setMovie(mMovie); } CExpressionPicker::~CExpressionPicker() { } void CExpressionPicker::setShowPreView(bool s) { mShowPreView = s; } bool CExpressionPicker::isShowPreView() { return mShowPreView; } void CExpressionPicker::setShowIconRect(bool s) { mShowIconRect = s; } bool CExpressionPicker::isShowIconRect() { return mShowIconRect; } void CExpressionPicker::setExpressionList(const CExpressionPicker::ExpressionList &li) { mExpressionList = li; mModel->clear(); int capacity = this->maxRowCount()*this->maxColumnCount(); int tSize = capacity <= li.count() ? capacity : li.count(); for(int i = 0; i < tSize; i++) { Expression exp = li[i]; QStandardItem* item = new QStandardItem("expression"); item->setData(exp.desc , ExpressionRole_Desc); item->setData(exp.fileName , ExpressionRole_FileName); item->setData(exp.groupid , ExpressionRole_GroupId); item->setData(exp.id , ExpressionRole_Id); item->setData(exp.shortcut , ExpressionRole_Shortcut); item->setData(exp.tooltip , ExpressionRole_Tooltip); item->setToolTip(exp.tooltip); int currentColumn = i % this->maxColumnCount(); int currentRow = i / this->maxColumnCount(); mModel->setItem(currentRow, currentColumn, item); } } CExpressionPicker::ExpressionList CExpressionPicker::expressionList() { return mExpressionList; } void CExpressionPicker::setMaxColumnCount(int n) { mMaxColumnCount = n; } void CExpressionPicker::setMaxRowCount(int n) { mMaxRowCount = n; } int CExpressionPicker::maxColumnCount() { return mMaxColumnCount; } int CExpressionPicker::maxRowCount() { return mMaxRowCount; } void CExpressionPicker::leaveEvent(QEvent *e) { QTableView::leaveEvent(e); mPreView->hide(); } void CExpressionPicker::mouseMoveEvent(QMouseEvent *e) { QTableView::mouseMoveEvent(e); if(!this->isShowPreView()) { mPreView->hide(); return; } //movie QModelIndex tindex = this->indexAt(e->pos()); if(!tindex.isValid() || !tindex.data(ExpressionRole_Id).isValid()) { mPreView->hide(); return; } if(e->x() <= mPreView->width()) { mPreView->move(this->width() - mPreView->width() - 1, 0 + 1); } else { mPreView->move(1,1); } mPreView->show(); QString filename = tindex.data(ExpressionRole_FileName).toString(); if(filename != mMovie->fileName()) { mMovie->stop(); mMovie->setFileName(filename); mMovie->start(); } } bool CExpressionPicker::eventFilter(QObject *obj, QEvent *e) { bool res = QTableView::eventFilter(obj,e); if (obj == nullptr || e == nullptr) { return res; } if(obj == mPreView) { if(e->type() == QEvent::MouseMove) { if(mPreView->pos() != QPoint(0,0)) { mPreView->move(0,0); } else { mPreView->move(this->width() - mPreView->width(), 0); } } if(e->type() == QEvent::Hide) { mMovie->stop(); } if(e->type() == QEvent::Show) { mMovie->start(); } } return res; } void CExpressionPicker::onClicked(const QModelIndex &index) { if(!index.isValid()) return; if(!index.data(ExpressionRole_Id).isValid()) return; Expression exp; exp.desc = index.data(ExpressionRole_Desc ).toString(); exp.fileName = index.data(ExpressionRole_FileName ).toString(); exp.groupid = index.data(ExpressionRole_GroupId ).toString(); exp.id = index.data(ExpressionRole_Id ).toString(); exp.shortcut = index.data(ExpressionRole_Shortcut ).toString(); exp.tooltip = index.data(ExpressionRole_Tooltip ).toString(); emit expressionClicked(exp); }
25.267544
87
0.619511
xylsxyls
dc469b8ca9fec546a251c4f9eb45ca3db0986ab9
2,777
cpp
C++
Source/Services/Misc/contextual_search_game_clip_uri_info.cpp
claytonv/xbox-live-api
d8db86cf930085c7547ae95999c9b301506de343
[ "MIT" ]
3
2020-07-15T17:50:24.000Z
2021-11-17T11:15:11.000Z
Source/Services/Misc/contextual_search_game_clip_uri_info.cpp
CameronGoodwin/xbox-live-api
ee0c3ee2413f2fed6a373df4b26035792e922fe2
[ "MIT" ]
null
null
null
Source/Services/Misc/contextual_search_game_clip_uri_info.cpp
CameronGoodwin/xbox-live-api
ee0c3ee2413f2fed6a373df4b26035792e922fe2
[ "MIT" ]
1
2021-02-01T01:56:08.000Z
2021-02-01T01:56:08.000Z
// Copyright (c) Microsoft Corporation // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "pch.h" #include "xsapi/contextual_search_service.h" NAMESPACE_MICROSOFT_XBOX_SERVICES_CONTEXTUAL_SEARCH_CPP_BEGIN contextual_search_game_clip_uri_info::contextual_search_game_clip_uri_info() : m_fileSize(0), m_uriType(contextual_search_game_clip_uri_type::none) { } contextual_search_game_clip_uri_info::contextual_search_game_clip_uri_info( _In_ web::uri url, _In_ uint64_t fileSize, _In_ contextual_search_game_clip_uri_type uriType, _In_ utility::datetime expiration ) : m_url(std::move(url)), m_fileSize(fileSize), m_uriType(uriType), m_expiration(std::move(expiration)) { } contextual_search_game_clip_uri_type contextual_search_game_clip_uri_info::convert_string_to_clip_uri_type(_In_ const string_t& value) { if (utils::str_icmp(value, _T("Original")) == 0) { return contextual_search_game_clip_uri_type::original; } else if (utils::str_icmp(value, _T("Download")) == 0) { return contextual_search_game_clip_uri_type::download; } else if (utils::str_icmp(value, _T("Ahls")) == 0) { return contextual_search_game_clip_uri_type::http_live_streaming; } else if (utils::str_icmp(value, _T("SmoothStreaming")) == 0) { return contextual_search_game_clip_uri_type::smooth_streaming; } return contextual_search_game_clip_uri_type::none; } xbox_live_result<contextual_search_game_clip_uri_info> contextual_search_game_clip_uri_info::_Deserialize(_In_ const web::json::value& inputJson) { if (inputJson.is_null()) return xbox_live_result<contextual_search_game_clip_uri_info>(); std::error_code errc = xbox_live_error_code::no_error; contextual_search_game_clip_uri_info result( utils::extract_json_string(inputJson, _T("Uri"), errc, false), utils::extract_json_uint52(inputJson, _T("FileSize"), errc, false), convert_string_to_clip_uri_type(utils::extract_json_string(inputJson, _T("UriType"), errc, false)), utils::extract_json_time(inputJson, _T("Expiration"), errc, false) ); return xbox_live_result<contextual_search_game_clip_uri_info>(result, errc); } const web::uri& contextual_search_game_clip_uri_info::url() const { return m_url; } uint64_t contextual_search_game_clip_uri_info::file_size() const { return m_fileSize; } contextual_search_game_clip_uri_type contextual_search_game_clip_uri_info::uri_type() const { return m_uriType; } const utility::datetime& contextual_search_game_clip_uri_info::expiration() const { return m_expiration; } NAMESPACE_MICROSOFT_XBOX_SERVICES_CONTEXTUAL_SEARCH_CPP_END
30.855556
107
0.764494
claytonv
dc4e683a355e65a3d1e39c1feca306c11c8830cb
8,329
cpp
C++
Source/FSD/Private/FSDWidgetBlueprintLibrary.cpp
Dr-Turtle/DRG_ModPresetManager
abd7ff98a820969504491a1fe68cf2f9302410dc
[ "MIT" ]
8
2021-07-10T20:06:05.000Z
2022-03-04T19:03:50.000Z
Source/FSD/Private/FSDWidgetBlueprintLibrary.cpp
Dr-Turtle/DRG_ModPresetManager
abd7ff98a820969504491a1fe68cf2f9302410dc
[ "MIT" ]
9
2022-01-13T20:49:44.000Z
2022-03-27T22:56:48.000Z
Source/FSD/Private/FSDWidgetBlueprintLibrary.cpp
Dr-Turtle/DRG_ModPresetManager
abd7ff98a820969504491a1fe68cf2f9302410dc
[ "MIT" ]
2
2021-07-10T20:05:42.000Z
2022-03-14T17:05:35.000Z
#include "FSDWidgetBlueprintLibrary.h" #include "Templates/SubclassOf.h" class UObject; class UWidget; class UHorizontalBox; class UUserWidget; class UWidgetAnimation; class USizeBox; class UPanelWidget; class UTextBlock; class UImage; class UWindowWidget; class AFSDPlayerState; class UFSDCheatManager; class APlayerController; class UVerticalBox; class USpacer; class UTexture2D; class UHorizontalBoxSlot; class UVerticalBoxSlot; class UUniformGridPanel; class UUniformGridSlot; void UFSDWidgetBlueprintLibrary::ToggleAnimationLooping(UObject* WorldContext, UWidgetAnimation* InAnimation, FWidgetAnimationSettings InSettings, bool InLoop, bool& OutPlayingChanged, bool& OutIsPlaying) { } bool UFSDWidgetBlueprintLibrary::TextSmallerThan(const FText& Text1, const FText& Text2) { return false; } bool UFSDWidgetBlueprintLibrary::TextGreaterThan(const FText& Text1, const FText& Text2) { return false; } TArray<UWidget*> UFSDWidgetBlueprintLibrary::SortWidgetArray(const TArray<UWidget*>& InWidgets, const FFSDWidgetBlueprintLibraryInCompareFunction& InCompareFunction) { return TArray<UWidget*>(); } void UFSDWidgetBlueprintLibrary::SimpleBox(FPaintContext& Context, FVector2D Position, FVector2D Size, FLinearColor Tint) { } FTimerHandle UFSDWidgetBlueprintLibrary::SetTimerForNextTick(UObject* WorldContext, const FFSDWidgetBlueprintLibraryTimerDelegate& TimerDelegate) { return FTimerHandle{}; } void UFSDWidgetBlueprintLibrary::SetSizeBoxSettings(USizeBox*& InSizeBox, const FSizeBoxSettings& InSettings) { } void UFSDWidgetBlueprintLibrary::SetMousePosition(UObject* WorldContextObject, int32 X, int32 Y) { } void UFSDWidgetBlueprintLibrary::SetChildrenVisibility(UPanelWidget* Panel, ESlateVisibility Visibility, int32 StartIndex, TSubclassOf<UUserWidget> OptionalClassFilter) { } void UFSDWidgetBlueprintLibrary::ScrubAnimation(UObject* WorldContext, UWidgetAnimation* InAnimation, float Progress01) { } void UFSDWidgetBlueprintLibrary::ScaleTextBlockToHeight(UTextBlock* TextBlock, float TargetHeight, bool SetMinimimumWidth) { } void UFSDWidgetBlueprintLibrary::ScaleImageToHeight(UImage* Image, float TargetHeight) { } void UFSDWidgetBlueprintLibrary::PrintStrings(UObject* WorldContextObject, const TArray<FString>& InStrings, bool bPrintToScreen, bool bPrintToLog, FLinearColor TextColor, float Duration) { } FString UFSDWidgetBlueprintLibrary::MidIgnoringWhiteSpace(const FString& Source, int32 Index, int32 count) { return TEXT(""); } FVector2D UFSDWidgetBlueprintLibrary::MeasureTextSize(const FText& Text, const FSlateFontInfo& Font) { return FVector2D{}; } FVector2D UFSDWidgetBlueprintLibrary::MeasureTextBlockSize(const UTextBlock* TextBlock) { return FVector2D{}; } void UFSDWidgetBlueprintLibrary::Line(FPaintContext& Context, FVector2D Pos1, FVector2D Pos2, FLinearColor Tint) { } FLinearColor UFSDWidgetBlueprintLibrary::LerpColors(const TArray<FLinearColor>& Colors, bool Interpolate, float Progress01) { return FLinearColor{}; } int32 UFSDWidgetBlueprintLibrary::LengthIgnoringWhitespace(const FString& Source) { return 0; } bool UFSDWidgetBlueprintLibrary::IsWindowsPlatform(UObject* WorldContextObject) { return false; } bool UFSDWidgetBlueprintLibrary::IsWhiteSpaceAt(const FString& Source, int32 Index) { return false; } bool UFSDWidgetBlueprintLibrary::IsWhiteSpace(const FString& Source) { return false; } bool UFSDWidgetBlueprintLibrary::IsHUDVisible(UObject* WorldContextObject) { return false; } FString UFSDWidgetBlueprintLibrary::IntToRomanNumeral(int32 Value) { return TEXT(""); } bool UFSDWidgetBlueprintLibrary::HasAnyVisibleChildren(UPanelWidget* Panel, int32 StartIndex, TSubclassOf<UUserWidget> OptionalClassFilter) { return false; } FString UFSDWidgetBlueprintLibrary::GetShortTimeString(int32 TotalSeconds, bool BlinkDelimiter) { return TEXT(""); } UWindowWidget* UFSDWidgetBlueprintLibrary::GetParentWindowWidget(UUserWidget* InWidget) { return NULL; } UUserWidget* UFSDWidgetBlueprintLibrary::GetParentUserWidget(UUserWidget* InWidget) { return NULL; } AFSDPlayerState* UFSDWidgetBlueprintLibrary::GetOwningFSDPlayerState(UWidget* Target) { return NULL; } FText UFSDWidgetBlueprintLibrary::GetKeyName(const FKey& Key) { return FText::GetEmpty(); } float UFSDWidgetBlueprintLibrary::GetFontMaxHeight(const FSlateFontInfo& Font) { return 0.0f; } float UFSDWidgetBlueprintLibrary::GetFontBaseline(const FSlateFontInfo& Font) { return 0.0f; } UWidget* UFSDWidgetBlueprintLibrary::GetFocusedWidget(UObject* WorldContextObject, APlayerController* Controller) { return NULL; } UUserWidget* UFSDWidgetBlueprintLibrary::GetFocusableParentUserWidget(UUserWidget* InWidget) { return NULL; } FVector2D UFSDWidgetBlueprintLibrary::GetDrawSize(FPaintContext& InContext) { return FVector2D{}; } UFSDCheatManager* UFSDWidgetBlueprintLibrary::GetCheatManager(UObject* WorldContextObject) { return NULL; } UWidget* UFSDWidgetBlueprintLibrary::FindChildWidget(UPanelWidget*& ParentWidget, TSubclassOf<UUserWidget> WidgetClass, bool SearchChildren) { return NULL; } UVerticalBox* UFSDWidgetBlueprintLibrary::CreateVerticalBox(UObject* WorldContext) { return NULL; } UTextBlock* UFSDWidgetBlueprintLibrary::CreateTextBlock(UObject* WorldContext, FText Text, FSlateFontInfo Font, TEnumAsByte<ETextJustify::Type> Justification, FLinearColor Color, bool WrapText) { return NULL; } USpacer* UFSDWidgetBlueprintLibrary::CreateSpacer(UObject* WorldContext, FVector2D Size) { return NULL; } TArray<UUserWidget*> UFSDWidgetBlueprintLibrary::CreateOrReuseChildrenWithCallbackEx(UPanelWidget* Panel, int32 count, TSubclassOf<UUserWidget> WidgetClass, const FFSDWidgetBlueprintLibraryOnCreatedOrReused& OnCreatedOrReused, const FFSDWidgetBlueprintLibraryOnCollapsed& OnCollapsed) { return TArray<UUserWidget*>(); } TArray<UUserWidget*> UFSDWidgetBlueprintLibrary::CreateOrReuseChildrenWithCallback(UPanelWidget* Panel, int32 count, TSubclassOf<UUserWidget> WidgetClass, const FFSDWidgetBlueprintLibraryOnCreatedOrReused& OnCreatedOrReused) { return TArray<UUserWidget*>(); } TArray<UUserWidget*> UFSDWidgetBlueprintLibrary::CreateOrReuseChildren(UPanelWidget* Panel, int32 count, TSubclassOf<UUserWidget> WidgetClass) { return TArray<UUserWidget*>(); } UImage* UFSDWidgetBlueprintLibrary::CreateImageSized(UObject* WorldContext, UTexture2D* Texture, FLinearColor Tint, FVector2D Size) { return NULL; } UImage* UFSDWidgetBlueprintLibrary::CreateImage(UObject* WorldContext, UTexture2D* Texture, FLinearColor Tint, bool AutoSize) { return NULL; } UHorizontalBox* UFSDWidgetBlueprintLibrary::CreateHorizontalBox(UObject* WorldContext) { return NULL; } FText UFSDWidgetBlueprintLibrary::ClampTextLength(const FText& Text, int32 MaxLength, const FText& CutOffIndicator) { return FText::GetEmpty(); } void UFSDWidgetBlueprintLibrary::Box(FPaintContext& Context, FVector2D Position, FVector2D Size, const FSlateBrush& Brush, FLinearColor Tint) { } UWidget* UFSDWidgetBlueprintLibrary::AddWidgetToRow(UVerticalBox* VerticalBox, UWidget* Widget, int32 MaxWidgetsPerRow, float WidgetSpacing, float RowSpacing, UHorizontalBoxSlot*& OutSlot, UHorizontalBox*& OutRow) { return NULL; } UWidget* UFSDWidgetBlueprintLibrary::AddChildToVerticalBoxEx(UVerticalBox* VerticalBox, UWidget* Widget, TEnumAsByte<EHorizontalAlignment> HorizontalAlignment, TEnumAsByte<EVerticalAlignment> VerticalAlignment, float Size, FMargin Padding, UVerticalBoxSlot*& OutSlot, UVerticalBox*& OutVerticalBox) { return NULL; } UWidget* UFSDWidgetBlueprintLibrary::AddChildToUniformGridEx(UUniformGridPanel* GridPanel, UWidget* Widget, TEnumAsByte<EHorizontalAlignment> HorizontalAlignment, TEnumAsByte<EVerticalAlignment> VerticalAlignment, int32 Column, int32 Row, UUniformGridSlot*& OutSlot, UUniformGridPanel*& OutGridPanel) { return NULL; } UWidget* UFSDWidgetBlueprintLibrary::AddChildToHorizontalBoxEx(UHorizontalBox* HorizontalBox, UWidget* Widget, TEnumAsByte<EHorizontalAlignment> HorizontalAlignment, TEnumAsByte<EVerticalAlignment> VerticalAlignment, float Size, FMargin Padding, UHorizontalBoxSlot*& OutSlot, UHorizontalBox*& OutHorizontalBox) { return NULL; } UFSDWidgetBlueprintLibrary::UFSDWidgetBlueprintLibrary() { }
37.017778
312
0.817505
Dr-Turtle
dc4e79d12722135d83cc445feee48bd77d308cff
4,491
cpp
C++
App.BeanOfLight/src/AnimalThirdPersonControler.cpp
BeanOfLight/BeanOfLight
ec8ae0d81fd548c2128d6e8ae8860e6e34c36e52
[ "MIT" ]
null
null
null
App.BeanOfLight/src/AnimalThirdPersonControler.cpp
BeanOfLight/BeanOfLight
ec8ae0d81fd548c2128d6e8ae8860e6e34c36e52
[ "MIT" ]
null
null
null
App.BeanOfLight/src/AnimalThirdPersonControler.cpp
BeanOfLight/BeanOfLight
ec8ae0d81fd548c2128d6e8ae8860e6e34c36e52
[ "MIT" ]
null
null
null
#include "AnimalThirdPersonControler.h" #include <OgreMath.h> #include "TerrainUtils.h" const float camDist = 900.f; AnimalThirdPersonControler::AnimalThirdPersonControler() : m_lookAround(false), m_camDistance(camDist), m_camAngularSpeed(0.0015f), m_camHeightOffset(0.f), m_pCamera(nullptr), m_pAnimal(nullptr), m_pTerrainGroup(nullptr) { } AnimalThirdPersonControler::~AnimalThirdPersonControler() { } void AnimalThirdPersonControler::attach(Animal* i_pAnimal, Ogre::Camera* i_pCamera, Ogre::TerrainGroup* i_pTerrainGroup) { m_pAnimal = i_pAnimal; m_pCamera = i_pCamera; m_pTerrainGroup = i_pTerrainGroup; m_camHeightOffset = i_pAnimal->m_heightOffset; if (!(m_pAnimal != nullptr && m_pCamera != nullptr)) return; m_pAnimal->dropOnTerrain(*i_pTerrainGroup); // Position camera m_pCamera->setPosition(m_pAnimal->m_pNode->getPosition() - m_camDistance * m_pAnimal->m_pNode->getOrientation().xAxis()); m_pCamera->lookAt(m_pAnimal->m_pNode->getPosition() + m_pAnimal->m_cameraLookAtOffset); } void AnimalThirdPersonControler::detach() { m_pAnimal = nullptr; m_pCamera = nullptr; } void AnimalThirdPersonControler::alignAnimalToCamera(double i_timeSinceLastFrame) { if (!(m_pAnimal != nullptr && m_pCamera != nullptr)) return; // Find new orientation of avatar Ogre::Vector3 camY = m_pCamera->getDirection(); Ogre::Vector3 aniX = m_pAnimal->m_pNode->getOrientation().xAxis(); Ogre::Vector3 aniY = m_pAnimal->m_pNode->getOrientation().yAxis(); Ogre::Vector3 newAniX = camY.dotProduct(aniX) * aniX + camY.dotProduct(aniY) * aniY; if (newAniX.isZeroLength()) return; newAniX.normalise(); m_pAnimal->turn(newAniX, i_timeSinceLastFrame); } void AnimalThirdPersonControler::move(int i_frontDir, int i_sideDir, bool i_run, double i_timeSinceLastFrame) { if (!(m_pAnimal != nullptr && m_pCamera != nullptr)) return; if (!(i_frontDir == 0 && i_sideDir == 0)) { Ogre::Vector3 oldAniPos = m_pAnimal->m_pNode->getPosition(); m_pAnimal->moveOnTerrain(i_frontDir, i_sideDir, i_run, i_timeSinceLastFrame, *m_pTerrainGroup); Ogre::Vector3 newAniPos = m_pAnimal->m_pNode->getPosition(); // Update cammera Ogre::Vector3 newCamPos = m_pCamera->getPosition() + newAniPos - oldAniPos; Ogre::Vector3 newAvatarToCamera = newCamPos - m_pAnimal->m_pNode->getPosition(); if (newAvatarToCamera.length() != m_camDistance) newAvatarToCamera = newAvatarToCamera.normalisedCopy() * m_camDistance; // Collide with terrain m_collideCamWithTerrain(newAvatarToCamera); } if (!m_lookAround) alignAnimalToCamera(i_timeSinceLastFrame); } void AnimalThirdPersonControler::orient(int i_xRel, int i_yRel, double i_timeSinceLastFrame) { if (!(m_pAnimal != nullptr && m_pCamera != nullptr)) return; Ogre::Vector3 camPos = m_pCamera->getPosition(); Ogre::Radian angleX(i_xRel * -m_camAngularSpeed); Ogre::Radian angleY(i_yRel * -m_camAngularSpeed); Ogre::Vector3 avatarToCamera = m_pCamera->getPosition() - m_pAnimal->m_pNode->getPosition(); // restore lenght if (avatarToCamera.length() != m_camDistance) avatarToCamera = avatarToCamera.normalisedCopy() * m_camDistance; // Do not go to the poles Ogre::Radian latitude = m_pAnimal->m_pNode->getOrientation().zAxis().angleBetween(avatarToCamera); if (latitude < Ogre::Radian(Ogre::Math::DegreesToRadians(10.f)) && angleY < Ogre::Radian(0.f)) angleY = Ogre::Radian(0.f); else if (latitude > Ogre::Radian(Ogre::Math::DegreesToRadians(170.f)) && angleY > Ogre::Radian(0.f)) angleY = Ogre::Radian(0.f); Ogre::Quaternion orient = Ogre::Quaternion(angleY, m_pCamera->getOrientation().xAxis()) * Ogre::Quaternion(angleX, m_pCamera->getOrientation().yAxis()); Ogre::Vector3 newAvatarToCamera = orient * avatarToCamera; // Move camera closer if collides with terrain m_collideCamWithTerrain(newAvatarToCamera); } void AnimalThirdPersonControler::m_collideCamWithTerrain(const Ogre::Vector3& i_avatarToCamera) { // Move camera closer if collides with terrain Ogre::Vector3 colPos, newCamPos; if (rayToTerrain(m_pAnimal->m_pNode->getPosition(), i_avatarToCamera, *m_pTerrainGroup, colPos) && ((m_pAnimal->m_pNode->getPosition() - colPos).length() < m_camDistance + m_camHeightOffset)) { newCamPos = colPos - i_avatarToCamera.normalisedCopy() * m_camHeightOffset; } else { newCamPos = m_pAnimal->m_pNode->getPosition() + i_avatarToCamera; } m_pCamera->setPosition(newCamPos); m_pCamera->lookAt(m_pAnimal->m_pNode->getPosition() + m_pAnimal->m_cameraLookAtOffset); }
32.543478
153
0.754843
BeanOfLight
dc51ab493c502205b7f761e6168f2ae218120cc9
59,189
cpp
C++
tests/juliet/testcases/CWE675_Duplicate_Operations_on_Resource/main.cpp
RanerL/analyzer
a401da4680f163201326881802ee535d6cf97f5a
[ "MIT" ]
28
2017-01-20T15:25:54.000Z
2020-03-17T00:28:31.000Z
tests/juliet/testcases/CWE675_Duplicate_Operations_on_Resource/main.cpp
RanerL/analyzer
a401da4680f163201326881802ee535d6cf97f5a
[ "MIT" ]
1
2021-07-12T02:57:17.000Z
2021-07-16T02:07:29.000Z
tests/juliet/testcases/CWE675_Duplicate_Operations_on_Resource/main.cpp
RanerL/analyzer
a401da4680f163201326881802ee535d6cf97f5a
[ "MIT" ]
2
2019-07-15T19:07:04.000Z
2019-09-07T14:21:04.000Z
/* NOTE - eventually this file will be automatically updated using a Perl script that understand * the naming of test case files, functions, and namespaces. */ #include <time.h> /* for time() */ #include <stdlib.h> /* for srand() */ #include "std_testcase.h" #include "testcases.h" int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); globalArgc = argc; globalArgv = argv; #ifndef OMITGOOD /* Calling C good functions */ /* BEGIN-AUTOGENERATED-C-GOOD-FUNCTION-CALLS */ printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_05_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_05_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_66_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_66_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_13_good();"); CWE675_Duplicate_Operations_on_Resource__open_13_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_21_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_21_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_44_good();"); CWE675_Duplicate_Operations_on_Resource__open_44_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_51_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_51_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_14_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_14_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_17_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_17_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_04_good();"); CWE675_Duplicate_Operations_on_Resource__open_04_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_10_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_10_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_17_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_17_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_64_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_64_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_16_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_16_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_64_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_64_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_11_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_11_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_34_good();"); CWE675_Duplicate_Operations_on_Resource__open_34_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_18_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_18_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_02_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_02_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_13_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_13_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_12_good();"); CWE675_Duplicate_Operations_on_Resource__open_12_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_53_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_53_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_44_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_44_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_65_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_65_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_21_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_21_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_31_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_31_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_04_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_04_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_68_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_68_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_22_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_22_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_12_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_12_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_03_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_03_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_54_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_54_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_31_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_31_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_45_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_45_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_45_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_45_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_14_good();"); CWE675_Duplicate_Operations_on_Resource__open_14_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_63_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_63_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_53_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_53_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_15_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_15_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_18_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_18_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_22_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_22_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_05_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_05_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_65_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_65_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_18_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_18_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_14_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_14_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_61_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_61_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_22_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_22_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_17_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_17_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_44_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_44_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_32_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_32_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_10_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_10_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_52_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_52_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_63_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_63_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_32_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_32_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_41_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_41_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_54_good();"); CWE675_Duplicate_Operations_on_Resource__open_54_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_21_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_21_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_08_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_08_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_05_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_05_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_41_good();"); CWE675_Duplicate_Operations_on_Resource__open_41_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_03_good();"); CWE675_Duplicate_Operations_on_Resource__open_03_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_53_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_53_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_05_good();"); CWE675_Duplicate_Operations_on_Resource__open_05_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_02_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_02_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_04_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_04_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_04_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_04_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_42_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_42_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_09_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_09_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_64_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_64_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_11_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_11_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_12_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_12_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_53_good();"); CWE675_Duplicate_Operations_on_Resource__open_53_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_01_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_01_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_10_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_10_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_54_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_54_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_09_good();"); CWE675_Duplicate_Operations_on_Resource__open_09_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_17_good();"); CWE675_Duplicate_Operations_on_Resource__open_17_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_63_good();"); CWE675_Duplicate_Operations_on_Resource__open_63_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_21_good();"); CWE675_Duplicate_Operations_on_Resource__open_21_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_09_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_09_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_61_good();"); CWE675_Duplicate_Operations_on_Resource__open_61_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_66_good();"); CWE675_Duplicate_Operations_on_Resource__open_66_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_07_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_07_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_41_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_41_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_11_good();"); CWE675_Duplicate_Operations_on_Resource__open_11_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_42_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_42_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_34_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_34_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_61_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_61_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_16_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_16_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_34_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_34_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_67_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_67_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_41_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_41_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_15_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_15_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_68_good();"); CWE675_Duplicate_Operations_on_Resource__open_68_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_02_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_02_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_06_good();"); CWE675_Duplicate_Operations_on_Resource__open_06_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_67_good();"); CWE675_Duplicate_Operations_on_Resource__open_67_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_32_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_32_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_54_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_54_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_06_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_06_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_67_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_67_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_03_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_03_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_61_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_61_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_42_good();"); CWE675_Duplicate_Operations_on_Resource__open_42_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_13_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_13_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_13_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_13_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_65_good();"); CWE675_Duplicate_Operations_on_Resource__open_65_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_16_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_16_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_01_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_01_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_01_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_01_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_34_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_34_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_65_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_65_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_11_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_11_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_52_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_52_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_51_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_51_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_16_good();"); CWE675_Duplicate_Operations_on_Resource__open_16_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_08_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_08_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_66_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_66_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_08_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_08_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_22_good();"); CWE675_Duplicate_Operations_on_Resource__open_22_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_12_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_12_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_44_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_44_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_52_good();"); CWE675_Duplicate_Operations_on_Resource__open_52_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_31_good();"); CWE675_Duplicate_Operations_on_Resource__open_31_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_14_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_14_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_07_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_07_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_64_good();"); CWE675_Duplicate_Operations_on_Resource__open_64_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_06_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_06_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_63_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_63_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_45_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_45_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_32_good();"); CWE675_Duplicate_Operations_on_Resource__open_32_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_06_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_06_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_07_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_07_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_52_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_52_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_67_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_67_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_07_good();"); CWE675_Duplicate_Operations_on_Resource__open_07_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_45_good();"); CWE675_Duplicate_Operations_on_Resource__open_45_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_03_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_03_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_02_good();"); CWE675_Duplicate_Operations_on_Resource__open_02_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_09_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_09_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_66_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_66_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_10_good();"); CWE675_Duplicate_Operations_on_Resource__open_10_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_08_good();"); CWE675_Duplicate_Operations_on_Resource__open_08_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_42_good();"); CWE675_Duplicate_Operations_on_Resource__fopen_42_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_68_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_68_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_68_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_68_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_31_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_31_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_01_good();"); CWE675_Duplicate_Operations_on_Resource__open_01_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_18_good();"); CWE675_Duplicate_Operations_on_Resource__open_18_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_15_good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_15_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_15_good();"); CWE675_Duplicate_Operations_on_Resource__open_15_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_51_good();"); CWE675_Duplicate_Operations_on_Resource__open_51_good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_51_good();"); CWE675_Duplicate_Operations_on_Resource__freopen_51_good(); /* END-AUTOGENERATED-C-GOOD-FUNCTION-CALLS */ #ifdef __cplusplus /* Calling C++ good functions */ /* BEGIN-AUTOGENERATED-CPP-GOOD-FUNCTION-CALLS */ printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_74::good();"); CWE675_Duplicate_Operations_on_Resource__open_74::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_84::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_84::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_62::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_62::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_73::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_73::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_62::good();"); CWE675_Duplicate_Operations_on_Resource__open_62::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_73::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_73::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_74::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_74::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_83::good();"); CWE675_Duplicate_Operations_on_Resource__open_83::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_84::good();"); CWE675_Duplicate_Operations_on_Resource__open_84::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_82::good();"); CWE675_Duplicate_Operations_on_Resource__open_82::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_83::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_83::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_73::good();"); CWE675_Duplicate_Operations_on_Resource__open_73::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_33::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_33::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_43::good();"); CWE675_Duplicate_Operations_on_Resource__open_43::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_74::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_74::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_81::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_81::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_83::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_83::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_84::good();"); CWE675_Duplicate_Operations_on_Resource__open_84::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_74::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_74::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_84::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_84::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_72::good();"); CWE675_Duplicate_Operations_on_Resource__open_72::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_62::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_62::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_72::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_72::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_84::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_84::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_33::good();"); CWE675_Duplicate_Operations_on_Resource__open_33::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_81::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_81::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_43::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_43::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_81::good();"); CWE675_Duplicate_Operations_on_Resource__open_81::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_84::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_84::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_62::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_62::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_84::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_84::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_83::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_83::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_83::good();"); CWE675_Duplicate_Operations_on_Resource__open_83::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_33::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_33::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_33::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_33::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_82::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_82::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_82::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_82::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_81::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_81::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_43::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_43::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_83::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_83::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_72::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_72::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_82::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_82::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_43::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_43::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_73::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_73::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_83::good();"); CWE675_Duplicate_Operations_on_Resource__fopen_83::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_84::good();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_84::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_72::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_72::good(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_83::good();"); CWE675_Duplicate_Operations_on_Resource__freopen_83::good(); /* END-AUTOGENERATED-CPP-GOOD-FUNCTION-CALLS */ #endif /* __cplusplus */ #endif /* OMITGOOD */ #ifndef OMITBAD /* Calling C bad functions */ /* BEGIN-AUTOGENERATED-C-BAD-FUNCTION-CALLS */ printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_05_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_05_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_66_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_66_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_13_bad();"); CWE675_Duplicate_Operations_on_Resource__open_13_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_21_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_21_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_44_bad();"); CWE675_Duplicate_Operations_on_Resource__open_44_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_51_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_51_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_14_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_14_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_17_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_17_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_04_bad();"); CWE675_Duplicate_Operations_on_Resource__open_04_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_10_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_10_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_17_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_17_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_64_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_64_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_16_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_16_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_64_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_64_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_11_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_11_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_34_bad();"); CWE675_Duplicate_Operations_on_Resource__open_34_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_18_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_18_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_02_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_02_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_13_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_13_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_12_bad();"); CWE675_Duplicate_Operations_on_Resource__open_12_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_53_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_53_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_44_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_44_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_65_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_65_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_21_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_21_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_31_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_31_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_04_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_04_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_68_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_68_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_22_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_22_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_12_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_12_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_03_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_03_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_54_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_54_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_31_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_31_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_45_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_45_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_45_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_45_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_14_bad();"); CWE675_Duplicate_Operations_on_Resource__open_14_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_63_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_63_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_53_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_53_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_15_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_15_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_18_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_18_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_22_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_22_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_05_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_05_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_65_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_65_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_18_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_18_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_14_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_14_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_61_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_61_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_22_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_22_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_17_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_17_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_44_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_44_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_32_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_32_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_10_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_10_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_52_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_52_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_63_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_63_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_32_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_32_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_41_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_41_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_54_bad();"); CWE675_Duplicate_Operations_on_Resource__open_54_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_21_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_21_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_08_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_08_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_05_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_05_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_41_bad();"); CWE675_Duplicate_Operations_on_Resource__open_41_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_03_bad();"); CWE675_Duplicate_Operations_on_Resource__open_03_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_53_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_53_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_05_bad();"); CWE675_Duplicate_Operations_on_Resource__open_05_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_02_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_02_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_04_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_04_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_04_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_04_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_42_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_42_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_09_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_09_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_64_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_64_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_11_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_11_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_12_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_12_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_53_bad();"); CWE675_Duplicate_Operations_on_Resource__open_53_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_01_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_01_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_10_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_10_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_54_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_54_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_09_bad();"); CWE675_Duplicate_Operations_on_Resource__open_09_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_17_bad();"); CWE675_Duplicate_Operations_on_Resource__open_17_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_63_bad();"); CWE675_Duplicate_Operations_on_Resource__open_63_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_21_bad();"); CWE675_Duplicate_Operations_on_Resource__open_21_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_09_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_09_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_61_bad();"); CWE675_Duplicate_Operations_on_Resource__open_61_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_66_bad();"); CWE675_Duplicate_Operations_on_Resource__open_66_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_07_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_07_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_41_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_41_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_11_bad();"); CWE675_Duplicate_Operations_on_Resource__open_11_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_42_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_42_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_34_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_34_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_61_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_61_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_16_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_16_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_34_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_34_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_67_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_67_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_41_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_41_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_15_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_15_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_68_bad();"); CWE675_Duplicate_Operations_on_Resource__open_68_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_02_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_02_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_06_bad();"); CWE675_Duplicate_Operations_on_Resource__open_06_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_67_bad();"); CWE675_Duplicate_Operations_on_Resource__open_67_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_32_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_32_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_54_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_54_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_06_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_06_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_67_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_67_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_03_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_03_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_61_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_61_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_42_bad();"); CWE675_Duplicate_Operations_on_Resource__open_42_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_13_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_13_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_13_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_13_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_65_bad();"); CWE675_Duplicate_Operations_on_Resource__open_65_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_16_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_16_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_01_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_01_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_01_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_01_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_34_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_34_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_65_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_65_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_11_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_11_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_52_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_52_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_51_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_51_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_16_bad();"); CWE675_Duplicate_Operations_on_Resource__open_16_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_08_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_08_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_66_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_66_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_08_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_08_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_22_bad();"); CWE675_Duplicate_Operations_on_Resource__open_22_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_12_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_12_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_44_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_44_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_52_bad();"); CWE675_Duplicate_Operations_on_Resource__open_52_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_31_bad();"); CWE675_Duplicate_Operations_on_Resource__open_31_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_14_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_14_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_07_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_07_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_64_bad();"); CWE675_Duplicate_Operations_on_Resource__open_64_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_06_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_06_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_63_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_63_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_45_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_45_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_32_bad();"); CWE675_Duplicate_Operations_on_Resource__open_32_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_06_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_06_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_07_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_07_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_52_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_52_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_67_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_67_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_07_bad();"); CWE675_Duplicate_Operations_on_Resource__open_07_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_45_bad();"); CWE675_Duplicate_Operations_on_Resource__open_45_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_03_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_03_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_02_bad();"); CWE675_Duplicate_Operations_on_Resource__open_02_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_09_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_09_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_66_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_66_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_10_bad();"); CWE675_Duplicate_Operations_on_Resource__open_10_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_08_bad();"); CWE675_Duplicate_Operations_on_Resource__open_08_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_42_bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_42_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_68_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_68_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_68_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_68_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_31_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_31_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_01_bad();"); CWE675_Duplicate_Operations_on_Resource__open_01_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_18_bad();"); CWE675_Duplicate_Operations_on_Resource__open_18_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_15_bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_15_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_15_bad();"); CWE675_Duplicate_Operations_on_Resource__open_15_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_51_bad();"); CWE675_Duplicate_Operations_on_Resource__open_51_bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_51_bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_51_bad(); /* END-AUTOGENERATED-C-BAD-FUNCTION-CALLS */ #ifdef __cplusplus /* Calling C++ bad functions */ /* BEGIN-AUTOGENERATED-CPP-BAD-FUNCTION-CALLS */ printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_74::bad();"); CWE675_Duplicate_Operations_on_Resource__open_74::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_84::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_84::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_62::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_62::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_73::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_73::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_62::bad();"); CWE675_Duplicate_Operations_on_Resource__open_62::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_73::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_73::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_74::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_74::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_83::bad();"); CWE675_Duplicate_Operations_on_Resource__open_83::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_84::bad();"); CWE675_Duplicate_Operations_on_Resource__open_84::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_82::bad();"); CWE675_Duplicate_Operations_on_Resource__open_82::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_83::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_83::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_73::bad();"); CWE675_Duplicate_Operations_on_Resource__open_73::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_33::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_33::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_43::bad();"); CWE675_Duplicate_Operations_on_Resource__open_43::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_74::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_74::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_81::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_81::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_83::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_83::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_84::bad();"); CWE675_Duplicate_Operations_on_Resource__open_84::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_74::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_74::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_84::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_84::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_72::bad();"); CWE675_Duplicate_Operations_on_Resource__open_72::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_62::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_62::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_72::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_72::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_84::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_84::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_33::bad();"); CWE675_Duplicate_Operations_on_Resource__open_33::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_81::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_81::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_43::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_43::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_81::bad();"); CWE675_Duplicate_Operations_on_Resource__open_81::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_84::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_84::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_62::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_62::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_84::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_84::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_83::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_83::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__open_83::bad();"); CWE675_Duplicate_Operations_on_Resource__open_83::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_33::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_33::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_33::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_33::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_82::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_82::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_82::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_82::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_81::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_81::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_43::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_43::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_83::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_83::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_72::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_72::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_82::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_82::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_43::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_43::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_73::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_73::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__fopen_83::bad();"); CWE675_Duplicate_Operations_on_Resource__fopen_83::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__w32CreateFile_84::bad();"); CWE675_Duplicate_Operations_on_Resource__w32CreateFile_84::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_72::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_72::bad(); printLine("Calling CWE675_Duplicate_Operations_on_Resource__freopen_83::bad();"); CWE675_Duplicate_Operations_on_Resource__freopen_83::bad(); /* END-AUTOGENERATED-CPP-BAD-FUNCTION-CALLS */ #endif /* __cplusplus */ #endif /* OMITBAD */ return 0; }
46.938144
97
0.871513
RanerL
dc57539f88602e33d29c83670d425b7994305558
4,469
hpp
C++
include/desola/profiling/EqualityCheckingVisitor.hpp
FrancisRussell/desola
a469428466e4849c7c0e2009a0c50b89184cae01
[ "Apache-2.0" ]
2
2021-12-17T10:46:20.000Z
2021-12-18T11:53:50.000Z
include/desola/profiling/EqualityCheckingVisitor.hpp
FrancisRussell/desola
a469428466e4849c7c0e2009a0c50b89184cae01
[ "Apache-2.0" ]
null
null
null
include/desola/profiling/EqualityCheckingVisitor.hpp
FrancisRussell/desola
a469428466e4849c7c0e2009a0c50b89184cae01
[ "Apache-2.0" ]
null
null
null
/****************************************************************************/ /* Copyright 2005-2006, Francis Russell */ /* */ /* 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 DESOLA_PROFILING_EQUALITY_CHECKING_VISITOR_HPP #define DESOLA_PROFILING_EQUALITY_CHECKING_VISITOR_HPP #include "Desola_profiling_fwd.hpp" #include <map> #include <cassert> #include <typeinfo> namespace desola { namespace detail { template<typename T_element> class PEqualityCheckingVisitor : public PExpressionNodeVisitor<T_element> { private: const std::map<const PExpressionNode<T_element>*, const PExpressionNode<T_element>*> mappings; bool equal; template<typename T_node> void checkMatch(const T_node& left) { assert(mappings.find(&left) != mappings.end()); const PExpressionNode<T_element>& right = *(mappings.find(&left)->second); if (typeid(left) == typeid(right)) { const T_node& castedRight = static_cast<const T_node&>(right); equal = equal && left.isEqual(castedRight, mappings); } else { equal = false; } } public: PEqualityCheckingVisitor(const std::map<const PExpressionNode<T_element>*, const PExpressionNode<T_element>*>& m) : mappings(m), equal(true) { } bool isEqual() const { return equal; } virtual void visit(PElementGet<vector, T_element>& e) { checkMatch(e); } virtual void visit(PElementGet<matrix, T_element>& e) { checkMatch(e); } virtual void visit(PElementSet<vector, T_element>& e) { checkMatch(e); } virtual void visit(PElementSet<matrix, T_element>& e) { checkMatch(e); } virtual void visit(PLiteral<scalar, T_element>& e) { checkMatch(e); } virtual void visit(PLiteral<vector, T_element>& e) { checkMatch(e); } virtual void visit(PLiteral<matrix, T_element>& e) { checkMatch(e); } virtual void visit(PMatrixMult<T_element>& e) { checkMatch(e); } virtual void visit(PMatrixVectorMult<T_element>& e) { checkMatch(e); } virtual void visit(PTransposeMatrixVectorMult<T_element>& e) { checkMatch(e); } virtual void visit(PVectorDot<T_element>& e) { checkMatch(e); } virtual void visit(PVectorCross<T_element>& e) { checkMatch(e); } virtual void visit(PVectorTwoNorm<T_element>& e) { checkMatch(e); } virtual void visit(PMatrixTranspose<T_element>& e) { checkMatch(e); } virtual void visit(PPairwise<scalar, T_element>& e) { checkMatch(e); } virtual void visit(PPairwise<vector, T_element>& e) { checkMatch(e); } virtual void visit(PPairwise<matrix, T_element>& e) { checkMatch(e); } virtual void visit(PScalarPiecewise<scalar, T_element>& e) { checkMatch(e); } virtual void visit(PScalarPiecewise<vector, T_element>& e) { checkMatch(e); } virtual void visit(PScalarPiecewise<matrix, T_element>& e) { checkMatch(e); } virtual void visit(PNegate<scalar, T_element>& e) { checkMatch(e); } virtual void visit(PNegate<vector, T_element>& e) { checkMatch(e); } virtual void visit(PNegate<matrix, T_element>& e) { checkMatch(e); } virtual void visit(PAbsolute<T_element>& e) { checkMatch(e); } virtual void visit(PSquareRoot<T_element>& e) { checkMatch(e); } }; } } #endif
22.685279
142
0.573059
FrancisRussell
dc58390656a009f243fd7e7855f84365afe22107
10,279
cpp
C++
src/raytracing/nvpro_core/nvvk/buffersuballocator_vk.cpp
zorofee/bgfx
56e69c858d56f452e8abe9902a760e5b4ba59747
[ "BSD-2-Clause" ]
null
null
null
src/raytracing/nvpro_core/nvvk/buffersuballocator_vk.cpp
zorofee/bgfx
56e69c858d56f452e8abe9902a760e5b4ba59747
[ "BSD-2-Clause" ]
null
null
null
src/raytracing/nvpro_core/nvvk/buffersuballocator_vk.cpp
zorofee/bgfx
56e69c858d56f452e8abe9902a760e5b4ba59747
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2014-2021, NVIDIA CORPORATION. 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. * * SPDX-FileCopyrightText: Copyright (c) 2014-2021 NVIDIA CORPORATION * SPDX-License-Identifier: Apache-2.0 */ #include <assert.h> #include "buffersuballocator_vk.h" #include "debug_util_vk.h" #include "error_vk.h" namespace bgfx { ////////////////////////////////////////////////////////////////////////// void BufferSubAllocator::init(MemAllocator* memAllocator, VkDeviceSize blockSize, VkBufferUsageFlags bufferUsageFlags, VkMemoryPropertyFlags memPropFlags, bool mapped, const std::vector<uint32_t>& sharingQueueFamilyIndices) { assert(!m_device); m_memAllocator = memAllocator; m_device = memAllocator->getDevice(); m_blockSize = std::min(blockSize, ((uint64_t(1) << Handle::BLOCKBITS) - 1) * uint64_t(BASE_ALIGNMENT)); m_bufferUsageFlags = bufferUsageFlags; m_memoryPropFlags = memPropFlags; m_memoryTypeIndex = ~0; m_keepLastBlock = true; m_mapped = mapped; m_sharingQueueFamilyIndices = sharingQueueFamilyIndices; m_freeBlockIndex = INVALID_ID_INDEX; m_usedSize = 0; m_allocatedSize = 0; } void BufferSubAllocator::deinit() { if(!m_memAllocator) return; free(false); m_blocks.clear(); m_memAllocator = nullptr; } BufferSubAllocator::Handle BufferSubAllocator::subAllocate(VkDeviceSize size, uint32_t align) { uint32_t usedOffset; uint32_t usedSize; uint32_t usedAligned; uint32_t blockIndex = INVALID_ID_INDEX; // if size either doesn't fit in the bits within the handle // or we are bigger than the default block size, we use a full dedicated block // for this allocation bool isDedicated = Handle::needsDedicated(size, align) || size > m_blockSize; if(!isDedicated) { // Find the first non-dedicated block that can fit the allocation for(uint32_t i = 0; i < (uint32_t)m_blocks.size(); i++) { Block& block = m_blocks[i]; if(!block.isDedicated && block.buffer && block.range.subAllocate((uint32_t)size, align, usedOffset, usedAligned, usedSize)) { blockIndex = block.index; break; } } } if(blockIndex == INVALID_ID_INDEX) { if(m_freeBlockIndex != INVALID_ID_INDEX) { Block& block = m_blocks[m_freeBlockIndex]; m_freeBlockIndex = setIndexValue(block.index, m_freeBlockIndex); blockIndex = block.index; } else { uint32_t newIndex = (uint32_t)m_blocks.size(); m_blocks.resize(m_blocks.size() + 1); Block& block = m_blocks[newIndex]; block.index = newIndex; blockIndex = newIndex; } Block& block = m_blocks[blockIndex]; block.size = std::max(m_blockSize, size); if(!isDedicated) { // only adjust size if not dedicated. // warning this lowers from 64 bit to 32 bit size, which should be fine given // such big allocations will trigger the dedicated path block.size = block.range.alignedSize((uint32_t)block.size); } VkResult result = allocBlock(block, blockIndex, block.size); NVVK_CHECK(result); if(result != VK_SUCCESS) { return Handle(); } block.isDedicated = isDedicated; if(!isDedicated) { // Dedicated blocks don't allow for subranges, so don't initialize the range allocator block.range.init((uint32_t)block.size); block.range.subAllocate((uint32_t)size, align, usedOffset, usedAligned, usedSize); m_regularBlocks++; } } Handle sub; if(!sub.setup(blockIndex, isDedicated ? 0 : usedOffset, isDedicated ? size : uint64_t(usedSize), isDedicated)) { return Handle(); } // append used space for stats m_usedSize += sub.getSize(); return sub; } void BufferSubAllocator::subFree(Handle sub) { if(!sub) return; Block& block = getBlock(sub.blockIndex); bool isDedicated = sub.isDedicated(); if(!isDedicated) { block.range.subFree(uint32_t(sub.getOffset()), uint32_t(sub.getSize())); } m_usedSize -= sub.getSize(); if(isDedicated || (block.range.isEmpty() && (!m_keepLastBlock || m_regularBlocks > 1))) { if(!isDedicated) { m_regularBlocks--; } freeBlock(block); } } float BufferSubAllocator::getUtilization(VkDeviceSize& allocatedSize, VkDeviceSize& usedSize) const { allocatedSize = m_allocatedSize; usedSize = m_usedSize; return float(double(usedSize) / double(allocatedSize)); } bool BufferSubAllocator::fitsInAllocated(VkDeviceSize size, uint32_t alignment) const { if(Handle::needsDedicated(size, alignment)) { return false; } for(const auto& block : m_blocks) { if(block.buffer && !block.isDedicated) { if(block.range.isAvailable((uint32_t)size, (uint32_t)alignment)) { return true; } } } return false; } void BufferSubAllocator::free(bool onlyEmpty) { for(uint32_t i = 0; i < (uint32_t)m_blocks.size(); i++) { Block& block = m_blocks[i]; if(block.buffer && (!onlyEmpty || (!block.isDedicated && block.range.isEmpty()))) { freeBlock(block); } } if(!onlyEmpty) { m_blocks.clear(); m_freeBlockIndex = INVALID_ID_INDEX; } } void BufferSubAllocator::freeBlock(Block& block) { m_allocatedSize -= block.size; BGFX_VKAPI(vkDestroyBuffer)(m_device, block.buffer, nullptr); if(block.mapping) { m_memAllocator->unmap(block.memory); } m_memAllocator->freeMemory(block.memory); if(!block.isDedicated) { block.range.deinit(); } block.memory = NullMemHandle; block.buffer = VK_NULL_HANDLE; block.mapping = nullptr; block.isDedicated = false; // update the block.index with the current head of the free list // pop its old value m_freeBlockIndex = setIndexValue(block.index, m_freeBlockIndex); } VkResult BufferSubAllocator::allocBlock(Block& block, uint32_t index, VkDeviceSize size) { std::string debugName = m_debugName + ":block:" + std::to_string(index); VkResult result; VkBufferCreateInfo createInfo = {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; createInfo.size = size; createInfo.usage = m_bufferUsageFlags; createInfo.sharingMode = m_sharingQueueFamilyIndices.size() > 1 ? VK_SHARING_MODE_CONCURRENT : VK_SHARING_MODE_EXCLUSIVE; createInfo.pQueueFamilyIndices = m_sharingQueueFamilyIndices.data(); createInfo.queueFamilyIndexCount = static_cast<uint32_t>(m_sharingQueueFamilyIndices.size()); VkBuffer buffer = VK_NULL_HANDLE; result = BGFX_VKAPI(vkCreateBuffer)(m_device, &createInfo, nullptr, &buffer); if(result != VK_SUCCESS) { NVVK_CHECK(result); return result; } bgfx::DebugUtil(m_device).setObjectName(buffer, debugName); VkMemoryRequirements2 memReqs = {VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2}; VkBufferMemoryRequirementsInfo2 bufferReqs = {VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2}; bufferReqs.buffer = buffer; BGFX_VKAPI(vkGetBufferMemoryRequirements2)(m_device, &bufferReqs, &memReqs); if(m_memoryTypeIndex == ~0) { VkPhysicalDeviceMemoryProperties memoryProperties; BGFX_VKAPI(vkGetPhysicalDeviceMemoryProperties)(m_memAllocator->getPhysicalDevice(), &memoryProperties); VkMemoryPropertyFlags memProps = m_memoryPropFlags; // Find an available memory type that satisfies the requested properties. for(uint32_t memoryTypeIndex = 0; memoryTypeIndex < memoryProperties.memoryTypeCount; ++memoryTypeIndex) { if((memReqs.memoryRequirements.memoryTypeBits & (1 << memoryTypeIndex)) && (memoryProperties.memoryTypes[memoryTypeIndex].propertyFlags & memProps) == memProps) { m_memoryTypeIndex = memoryTypeIndex; break; } } } if(m_memoryTypeIndex == ~0) { assert(0 && "could not find memoryTypeIndex\n"); BGFX_VKAPI(vkDestroyBuffer)(m_device, buffer, nullptr); return VK_ERROR_INCOMPATIBLE_DRIVER; } MemAllocateInfo memAllocateInfo(memReqs.memoryRequirements, m_memoryPropFlags, false); memAllocateInfo.setDebugName(debugName); MemHandle memory = m_memAllocator->allocMemory(memAllocateInfo); if(!memory) { assert(0 && "could not allocate buffer\n"); BGFX_VKAPI(vkDestroyBuffer)(m_device, buffer, nullptr); return VK_ERROR_OUT_OF_DEVICE_MEMORY; } MemAllocator::MemInfo memInfo = m_memAllocator->getMemoryInfo(memory); VkBindBufferMemoryInfo bindInfos = {VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO}; bindInfos.buffer = buffer; bindInfos.memory = memInfo.memory; bindInfos.memoryOffset = memInfo.offset; result = BGFX_VKAPI(vkBindBufferMemory2)(m_device, 1, &bindInfos); if(result == VK_SUCCESS) { if(m_mapped) { block.mapping = m_memAllocator->mapT<uint8_t>(memory); } else { block.mapping = nullptr; } if(!m_mapped || block.mapping) { if(m_bufferUsageFlags & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) { VkBufferDeviceAddressInfo info = {VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; info.buffer = buffer; block.address = BGFX_VKAPI(vkGetBufferDeviceAddress)(m_device, &info); } block.memory = memory; block.buffer = buffer; m_allocatedSize += block.size; return result; } } // error case NVVK_CHECK(result); BGFX_VKAPI(vkDestroyBuffer)(m_device, buffer, nullptr); m_memAllocator->freeMemory(memory); return result; } } // namespace bgfx
28.792717
129
0.67633
zorofee
dc5dd1a91bef80ba080bbcc5820c6b3ea8ac9b14
2,771
cpp
C++
src/listener.cpp
lydiazoghbi/beginner_tutorials
cbf5d5a7a44e8c6005b511ed0fc9a8a1dc937056
[ "Unlicense", "BSD-3-Clause" ]
null
null
null
src/listener.cpp
lydiazoghbi/beginner_tutorials
cbf5d5a7a44e8c6005b511ed0fc9a8a1dc937056
[ "Unlicense", "BSD-3-Clause" ]
null
null
null
src/listener.cpp
lydiazoghbi/beginner_tutorials
cbf5d5a7a44e8c6005b511ed0fc9a8a1dc937056
[ "Unlicense", "BSD-3-Clause" ]
null
null
null
/* * BSD License * * Copyright (c) Lydia Zoghbi 2019 * * 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 * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @file listener.cpp * @author Lydia Zoghbi * @copyright Copyright BSD License * @date 11/02/2019 * @version 1.0 * * @brief Listener file for the ENPM808X ROS Assignment * */ #include "ros/ros.h" #include "std_msgs/String.h" #include "beginner_tutorials/string_modifier.h" /** * @brief Callback function for the function outputting the string * * @param A constant string * * @return Nothing */ void chatterCallback(const std_msgs::String::ConstPtr& msg) { ROS_INFO("I am receiving: [%s]", msg->data.c_str()); } /** * @brief Main loop for the listener * * @param ROS argument count * @param ROS argument vector * * @return 0 exit status */ int main(int argc, char **argv) { // Initiates the listener node ros::init(argc, argv, "listener"); // Creates the nodehandle object, initiates the node, and closes it off at the end ros::NodeHandle n; // Creates the subscriber object auto sub = n.subscribe("chatter", 1000, chatterCallback); // Will enter a loop, exits only when Ctrl-C is pressed or node shutdown by Master ros::spin(); return 0; }
33.792683
82
0.716348
lydiazoghbi
dc5eba32b42ce287379b17be3d5bdf1d80ce1415
826
cc
C++
geometry/plane.cc
IJDykeman/experiments-1
22badf166b2ea441e953939463f751020b8c251b
[ "MIT" ]
1
2022-02-28T04:19:34.000Z
2022-02-28T04:19:34.000Z
geometry/plane.cc
IJDykeman/experiments-1
22badf166b2ea441e953939463f751020b8c251b
[ "MIT" ]
null
null
null
geometry/plane.cc
IJDykeman/experiments-1
22badf166b2ea441e953939463f751020b8c251b
[ "MIT" ]
null
null
null
#include "plane.hh" namespace geometry { bool Plane::intersect(const Line& line, Out<Vec3> point) const { constexpr double EPS = 1e-7; if (line.direction.cross(normal).norm() < EPS) { // Parallel return false; } const double d = (origin - line.point).dot(normal) / (line.direction.dot(normal)); *point = line.point + (d * line.direction); return true; } bool Plane::intersect(const Ray& ray, Out<Vec3> point) const { constexpr double EPS = 1e-7; if (ray.direction.cross(normal).norm() < EPS) { // Parallel return false; } const double d = (origin - ray.origin).dot(normal) / (ray.direction.dot(normal)); *point = ray.origin + (d * ray.direction); if (d < 0.0) { // Pointing in the wrong direction return false; } else { return true; } } } // namespace geometry
22.324324
84
0.634383
IJDykeman
dc6110aa5a8ab5613b01d86632d47725e2432275
2,918
cpp
C++
soccer/src/soccer/radio/radio.cpp
xiaoqingyu0113/robocup-software
6127d25fc455051ef47610d0e421b2ca7330b4fa
[ "Apache-2.0" ]
200
2015-01-26T01:45:34.000Z
2022-03-19T13:05:31.000Z
soccer/src/soccer/radio/radio.cpp
xiaoqingyu0113/robocup-software
6127d25fc455051ef47610d0e421b2ca7330b4fa
[ "Apache-2.0" ]
1,254
2015-01-03T01:57:35.000Z
2022-03-16T06:32:21.000Z
soccer/src/soccer/radio/radio.cpp
xiaoqingyu0113/robocup-software
6127d25fc455051ef47610d0e421b2ca7330b4fa
[ "Apache-2.0" ]
206
2015-01-21T02:03:18.000Z
2022-02-01T17:57:46.000Z
#include "radio.hpp" namespace radio { DEFINE_FLOAT64(kRadioParamModule, timeout, 0.25, "Timeout after which radio will assume a robot is disconnected. Seconds."); Radio::Radio() : Node{"radio", rclcpp::NodeOptions{} .automatically_declare_parameters_from_overrides(true) .allow_undeclared_parameters(true)}, param_provider_(this, kRadioParamModule) { team_color_sub_ = create_subscription<rj_msgs::msg::TeamColor>( referee::topics::kTeamColorPub, rclcpp::QoS(1).transient_local(), [this](rj_msgs::msg::TeamColor::SharedPtr color) { // NOLINT switch_team(color->is_blue); }); for (int i = 0; i < kNumShells; i++) { robot_status_pubs_.at(i) = create_publisher<rj_msgs::msg::RobotStatus>( topics::robot_status_pub(i), rclcpp::QoS(1)); manipulator_subs_.at(i) = create_subscription<rj_msgs::msg::ManipulatorSetpoint>( control::topics::manipulator_setpoint_pub(i), rclcpp::QoS(1), [this, i](rj_msgs::msg::ManipulatorSetpoint::SharedPtr manipulator) { // NOLINT manipulators_cached_.at(i) = *manipulator; }); motion_subs_.at(i) = create_subscription<rj_msgs::msg::MotionSetpoint>( control::topics::motion_setpoint_pub(i), rclcpp::QoS(1), [this, i](rj_msgs::msg::MotionSetpoint::SharedPtr motion) { // NOLINT last_updates_.at(i) = RJ::now(); send(i, *motion, manipulators_cached_.at(i)); }); } tick_timer_ = create_wall_timer(std::chrono::milliseconds(16), [this]() { tick(); }); } void Radio::publish(int robot_id, const rj_msgs::msg::RobotStatus& robot_status) { robot_status_pubs_.at(robot_id)->publish(robot_status); } void Radio::tick() { receive(); RJ::Time update_time = RJ::now(); for (int i = 0; i < kNumShells; i++) { if (last_updates_.at(i) + RJ::Seconds(PARAM_timeout) < update_time) { using rj_msgs::msg::ManipulatorSetpoint; using rj_msgs::msg::MotionSetpoint; // Send a NOP packet if we haven't got any updates. const auto motion = rj_msgs::build<MotionSetpoint>() .velocity_x_mps(0) .velocity_y_mps(0) .velocity_z_radps(0); const auto manipulator = rj_msgs::build<ManipulatorSetpoint>() .shoot_mode(ManipulatorSetpoint::SHOOT_MODE_KICK) .trigger_mode(ManipulatorSetpoint::TRIGGER_MODE_STAND_DOWN) .kick_speed(0) .dribbler_speed(0); last_updates_.at(i) = RJ::now(); send(i, motion, manipulator); } } } } // namespace radio
43.552239
100
0.577108
xiaoqingyu0113
dc62bad401397865017b61073ec57761399965c8
14,278
cpp
C++
openstudiocore/src/model/YearDescription.cpp
ORNL-BTRIC/OpenStudio
878f94bebf6f025445d1373e8b2304ececac16d8
[ "blessing" ]
null
null
null
openstudiocore/src/model/YearDescription.cpp
ORNL-BTRIC/OpenStudio
878f94bebf6f025445d1373e8b2304ececac16d8
[ "blessing" ]
null
null
null
openstudiocore/src/model/YearDescription.cpp
ORNL-BTRIC/OpenStudio
878f94bebf6f025445d1373e8b2304ececac16d8
[ "blessing" ]
null
null
null
/********************************************************************** * Copyright (c) 2008-2014, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include <model/YearDescription.hpp> #include <model/YearDescription_Impl.hpp> #include <model/RunPeriod.hpp> #include <model/RunPeriod_Impl.hpp> #include <model/RunPeriodControlDaylightSavingTime.hpp> #include <model/RunPeriodControlDaylightSavingTime_Impl.hpp> #include <model/RunPeriodControlSpecialDays.hpp> #include <model/RunPeriodControlSpecialDays_Impl.hpp> #include <model/SizingPeriod.hpp> #include <model/SizingPeriod_Impl.hpp> #include <model/ScheduleBase.hpp> #include <model/ScheduleBase_Impl.hpp> #include <model/ScheduleRule.hpp> #include <model/ScheduleRule_Impl.hpp> #include <model/LightingDesignDay.hpp> #include <model/LightingDesignDay_Impl.hpp> #include <model/Model.hpp> #include <model/Model_Impl.hpp> #include <utilities/idd/IddFactory.hxx> #include <utilities/idd/OS_YearDescription_FieldEnums.hxx> #include <utilities/time/Date.hpp> #include <utilities/core/Assert.hpp> namespace openstudio { namespace model { namespace detail { YearDescription_Impl::YearDescription_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle) : ParentObject_Impl(idfObject,model,keepHandle) { OS_ASSERT(idfObject.iddObject().type() == YearDescription::iddObjectType()); } YearDescription_Impl::YearDescription_Impl(const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle) : ParentObject_Impl(other,model,keepHandle) { OS_ASSERT(other.iddObject().type() == YearDescription::iddObjectType()); } YearDescription_Impl::YearDescription_Impl(const YearDescription_Impl& other, Model_Impl* model, bool keepHandle) : ParentObject_Impl(other,model,keepHandle) {} const std::vector<std::string>& YearDescription_Impl::outputVariableNames() const { static std::vector<std::string> result; if (result.empty()){ } return result; } IddObjectType YearDescription_Impl::iddObjectType() const { return YearDescription::iddObjectType(); } std::vector<ModelObject> YearDescription_Impl::children() const { std::vector<ModelObject> result; Model model = this->model(); boost::optional<RunPeriodControlDaylightSavingTime> dst = model.getOptionalUniqueModelObject<RunPeriodControlDaylightSavingTime>(); if (dst){ result.push_back(*dst); } BOOST_FOREACH(RunPeriodControlSpecialDays day, model.getConcreteModelObjects<RunPeriodControlSpecialDays>()){ result.push_back(day); } return result; } std::vector<IddObjectType> YearDescription_Impl::allowableChildTypes() const { IddObjectTypeVector result; result.push_back(RunPeriodControlDaylightSavingTime::iddObjectType()); result.push_back(RunPeriodControlSpecialDays::iddObjectType()); return result; } boost::optional<int> YearDescription_Impl::calendarYear() const { return getInt(OS_YearDescriptionFields::CalendarYear,true); } std::string YearDescription_Impl::dayofWeekforStartDay() const { boost::optional<int> calendarYear = this->calendarYear(); if (calendarYear){ openstudio::Date jan1(MonthOfYear::Jan, 1, *calendarYear); std::string result = jan1.dayOfWeek().valueName(); return result; } boost::optional<std::string> value = getString(OS_YearDescriptionFields::DayofWeekforStartDay,true); OS_ASSERT(value); return value.get(); } bool YearDescription_Impl::isDayofWeekforStartDayDefaulted() const { return isEmpty(OS_YearDescriptionFields::DayofWeekforStartDay); } bool YearDescription_Impl::isLeapYear() const { boost::optional<int> calendarYear = this->calendarYear(); if (calendarYear){ openstudio::Date jan1(MonthOfYear::Jan, 1, *calendarYear); bool result = jan1.isLeapYear(); return result; } boost::optional<std::string> value = getString(OS_YearDescriptionFields::IsLeapYear,true); OS_ASSERT(value); return openstudio::istringEqual(value.get(), "Yes"); } bool YearDescription_Impl::isIsLeapYearDefaulted() const { return isEmpty(OS_YearDescriptionFields::IsLeapYear); } void YearDescription_Impl::setCalendarYear(boost::optional<int> calendarYear) { bool wasLeapYear = this->isLeapYear(); bool result = false; if (calendarYear) { result = setInt(OS_YearDescriptionFields::CalendarYear, calendarYear.get()); this->resetDayofWeekforStartDay(); this->resetIsLeapYear(); } else { result = setString(OS_YearDescriptionFields::CalendarYear, ""); } OS_ASSERT(result); bool isLeapYear = this->isLeapYear(); updateModelLeapYear(wasLeapYear, isLeapYear); } void YearDescription_Impl::resetCalendarYear() { bool wasLeapYear = this->isLeapYear(); bool result = setString(OS_YearDescriptionFields::CalendarYear, ""); OS_ASSERT(result); bool isLeapYear = this->isLeapYear(); updateModelLeapYear(wasLeapYear, isLeapYear); } bool YearDescription_Impl::setDayofWeekforStartDay(std::string dayofWeekforStartDay) { bool result = false; if (!this->calendarYear()){ result = setString(OS_YearDescriptionFields::DayofWeekforStartDay, dayofWeekforStartDay); } return result; } void YearDescription_Impl::resetDayofWeekforStartDay() { bool result = setString(OS_YearDescriptionFields::DayofWeekforStartDay, ""); OS_ASSERT(result); } bool YearDescription_Impl::setIsLeapYear(bool isLeapYear) { bool result = false; bool wasLeapYear = this->isLeapYear(); if (!this->calendarYear()){ if (isLeapYear) { result = setString(OS_YearDescriptionFields::IsLeapYear, "Yes"); } else { result = setString(OS_YearDescriptionFields::IsLeapYear, "No"); } } if (result){ updateModelLeapYear(wasLeapYear, isLeapYear); } return result; } void YearDescription_Impl::resetIsLeapYear() { bool wasLeapYear = this->isLeapYear(); bool result = setString(OS_YearDescriptionFields::IsLeapYear, ""); OS_ASSERT(result); bool isLeapYear = this->isLeapYear(); updateModelLeapYear(wasLeapYear, isLeapYear); } int YearDescription_Impl::assumedYear() const { boost::optional<int> calendarYear = this->calendarYear(); if (calendarYear){ return *calendarYear; } openstudio::YearDescription yd; yd.isLeapYear = this->isLeapYear(); std::string dayofWeekforStartDay = this->dayofWeekforStartDay(); if (!dayofWeekforStartDay.empty()){ try{ openstudio::DayOfWeek dow(dayofWeekforStartDay); yd.yearStartsOnDayOfWeek = dow; }catch(const std::exception& ){ LOG(Error, "'" << dayofWeekforStartDay << "' is not yet a supported option for YearDescription"); } } return yd.assumedYear(); } openstudio::Date YearDescription_Impl::makeDate(openstudio::MonthOfYear monthOfYear, unsigned dayOfMonth) { boost::optional<int> calendarYear = this->calendarYear(); if (calendarYear){ return openstudio::Date(monthOfYear, dayOfMonth, *calendarYear); } openstudio::YearDescription yd; yd.isLeapYear = this->isLeapYear(); std::string dayofWeekforStartDay = this->dayofWeekforStartDay(); if (!dayofWeekforStartDay.empty()){ if (istringEqual(dayofWeekforStartDay, "UseWeatherFile")){ LOG(Info, "'UseWeatherFile' is not yet a supported option for YearDescription"); }else{ openstudio::DayOfWeek dow(dayofWeekforStartDay); yd.yearStartsOnDayOfWeek = dow; } } return openstudio::Date(monthOfYear, dayOfMonth, yd); } openstudio::Date YearDescription_Impl::makeDate(unsigned monthOfYear, unsigned dayOfMonth) { return makeDate(openstudio::MonthOfYear(monthOfYear), dayOfMonth); } openstudio::Date YearDescription_Impl::makeDate(openstudio::NthDayOfWeekInMonth n, openstudio::DayOfWeek dayOfWeek, openstudio::MonthOfYear monthOfYear) { boost::optional<int> year = this->calendarYear(); if (!year){ year = this->assumedYear(); } return openstudio::Date::fromNthDayOfMonth(n, dayOfWeek, monthOfYear, *year); } openstudio::Date YearDescription_Impl::makeDate(unsigned dayOfYear) { boost::optional<int> year = this->calendarYear(); if (!year){ year = this->assumedYear(); } return openstudio::Date::fromDayOfYear(dayOfYear, *year); } void YearDescription_Impl::updateModelLeapYear(bool wasLeapYear, bool isLeapYear) { if (wasLeapYear == isLeapYear){ return; } if (!wasLeapYear && isLeapYear){ return; } model::Model model = this->model(); if (wasLeapYear && !isLeapYear){ BOOST_FOREACH(RunPeriod runPeriod, model.getModelObjects<RunPeriod>()){ runPeriod.ensureNoLeapDays(); } BOOST_FOREACH(RunPeriodControlDaylightSavingTime runPeriodControlDaylightSavingTime, model.getModelObjects<RunPeriodControlDaylightSavingTime>()){ runPeriodControlDaylightSavingTime.ensureNoLeapDays(); } BOOST_FOREACH(RunPeriodControlSpecialDays runPeriodControlSpecialDays, model.getModelObjects<RunPeriodControlSpecialDays>()){ runPeriodControlSpecialDays.ensureNoLeapDays(); } BOOST_FOREACH(SizingPeriod sizingPeriod, model.getModelObjects<SizingPeriod>()){ sizingPeriod.ensureNoLeapDays(); } BOOST_FOREACH(ScheduleBase scheduleBase, model.getModelObjects<ScheduleBase>()){ scheduleBase.ensureNoLeapDays(); } BOOST_FOREACH(ScheduleRule scheduleRule, model.getModelObjects<ScheduleRule>()){ scheduleRule.ensureNoLeapDays(); } BOOST_FOREACH(LightingDesignDay lightingDesignDay, model.getModelObjects<LightingDesignDay>()){ lightingDesignDay.ensureNoLeapDays(); } } } } // detail IddObjectType YearDescription::iddObjectType() { IddObjectType result(IddObjectType::OS_YearDescription); return result; } std::vector<std::string> YearDescription::validDayofWeekforStartDayValues() { return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(), OS_YearDescriptionFields::DayofWeekforStartDay); } boost::optional<int> YearDescription::calendarYear() const { return getImpl<detail::YearDescription_Impl>()->calendarYear(); } std::string YearDescription::dayofWeekforStartDay() const { return getImpl<detail::YearDescription_Impl>()->dayofWeekforStartDay(); } bool YearDescription::isDayofWeekforStartDayDefaulted() const { return getImpl<detail::YearDescription_Impl>()->isDayofWeekforStartDayDefaulted(); } bool YearDescription::isLeapYear() const { return getImpl<detail::YearDescription_Impl>()->isLeapYear(); } bool YearDescription::isIsLeapYearDefaulted() const { return getImpl<detail::YearDescription_Impl>()->isIsLeapYearDefaulted(); } void YearDescription::setCalendarYear(int calendarYear) { getImpl<detail::YearDescription_Impl>()->setCalendarYear(calendarYear); } void YearDescription::resetCalendarYear() { getImpl<detail::YearDescription_Impl>()->resetCalendarYear(); } bool YearDescription::setDayofWeekforStartDay(std::string dayofWeekforStartDay) { return getImpl<detail::YearDescription_Impl>()->setDayofWeekforStartDay(dayofWeekforStartDay); } void YearDescription::resetDayofWeekforStartDay() { getImpl<detail::YearDescription_Impl>()->resetDayofWeekforStartDay(); } bool YearDescription::setIsLeapYear(bool isLeapYear) { return getImpl<detail::YearDescription_Impl>()->setIsLeapYear(isLeapYear); } void YearDescription::resetIsLeapYear() { getImpl<detail::YearDescription_Impl>()->resetIsLeapYear(); } int YearDescription::assumedYear() const { return getImpl<detail::YearDescription_Impl>()->assumedYear(); } openstudio::Date YearDescription::makeDate(openstudio::MonthOfYear monthOfYear, unsigned dayOfMonth) { return getImpl<detail::YearDescription_Impl>()->makeDate(monthOfYear, dayOfMonth); } openstudio::Date YearDescription::makeDate(unsigned monthOfYear, unsigned dayOfMonth) { return getImpl<detail::YearDescription_Impl>()->makeDate(monthOfYear, dayOfMonth); } openstudio::Date YearDescription::makeDate(openstudio::NthDayOfWeekInMonth n, openstudio::DayOfWeek dayOfWeek, openstudio::MonthOfYear monthOfYear) { return getImpl<detail::YearDescription_Impl>()->makeDate(n, dayOfWeek, monthOfYear); } openstudio::Date YearDescription::makeDate(unsigned dayOfYear) { return getImpl<detail::YearDescription_Impl>()->makeDate(dayOfYear); } /// @cond YearDescription::YearDescription(boost::shared_ptr<detail::YearDescription_Impl> impl) : ParentObject(impl) {} YearDescription::YearDescription(Model& model) : ParentObject(YearDescription::iddObjectType(),model) {} /// @endcond } // model } // openstudio
33.516432
155
0.698697
ORNL-BTRIC
dc64ff403dd7d036b83871e06a9e3282ee996373
5,488
cpp
C++
src/trace/DXInterceptor/dxcodegen/Generator/StructHelperGenerator.cpp
attila-sim/attila-sim
a64b57240b4e10dc4df7f21eff0232b28df09532
[ "BSD-3-Clause" ]
23
2016-01-14T04:47:13.000Z
2022-01-13T14:02:08.000Z
src/trace/DXInterceptor/dxcodegen/Generator/StructHelperGenerator.cpp
attila-sim/attila-sim
a64b57240b4e10dc4df7f21eff0232b28df09532
[ "BSD-3-Clause" ]
2
2018-03-25T14:39:20.000Z
2022-03-18T05:11:21.000Z
src/trace/DXInterceptor/dxcodegen/Generator/StructHelperGenerator.cpp
attila-sim/attila-sim
a64b57240b4e10dc4df7f21eff0232b28df09532
[ "BSD-3-Clause" ]
17
2016-02-13T05:35:35.000Z
2022-03-24T16:05:40.000Z
//////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Config/GeneratorConfiguration.h" #include "Items/StructSpecificCode.h" #include "Items/StructDescription.h" #include "Generator/StructHelperGenerator.h" using namespace std; using namespace dxcodegen::Config; using namespace dxcodegen::Items; using namespace dxcodegen::Generator; //////////////////////////////////////////////////////////////////////////////// StructHelperGenerator::StructHelperGenerator(GeneratorConfiguration& config, const std::vector<StructDescriptionPtr>& structures, const string& outputPath) : m_config(config), m_outputPath(outputPath), m_className("DXStructHelper"), IGenerator("class DXStructHelper") { m_structures = structures; } //////////////////////////////////////////////////////////////////////////////// StructHelperGenerator::~StructHelperGenerator() { } //////////////////////////////////////////////////////////////////////////////// void StructHelperGenerator::GenerateCode() { GenerateHpp(); GenerateCpp(); } //////////////////////////////////////////////////////////////////////////////// void StructHelperGenerator::GenerateHpp() { string filename = m_className + ".h"; ofstream* sortida = CreateFilename(m_outputPath + filename); if (sortida && sortida->is_open()) { cout << "Creating '" << filename << "'" << endl; GenerateDefinition(*sortida); } CloseFilename(sortida); } //////////////////////////////////////////////////////////////////////////////// void StructHelperGenerator::GenerateCpp() { string filename = m_className + ".cpp"; ofstream* sortida = CreateFilename(m_outputPath + filename); if (sortida && sortida->is_open()) { cout << "Creating '" << filename << "'" << endl; GenerateImplementation(*sortida); } CloseFilename(sortida); } //////////////////////////////////////////////////////////////////////////////// void StructHelperGenerator::GenerateDefinition(ofstream& sortida) { sortida << "#pragma once" << endl; sortida << endl; sortida << "namespace dxtraceman" << endl; sortida << "{" << endl; sortida << " class " << m_className << endl; sortida << " {" << endl; GenerateDefinitionMethods(sortida); sortida << " };" << endl; sortida << "}" << endl; } //////////////////////////////////////////////////////////////////////////////// void StructHelperGenerator::GenerateDefinitionMethods(ofstream& sortida) { sortida << " public:" << endl; sortida << endl; for (vector<StructDescriptionPtr>::iterator it = m_structures.begin(); it != m_structures.end(); it++) { sortida << " static int " << (*it)->GetName() << "_ToString(char* buffer, unsigned int size, " << (*it)->GetName() << "* value);" << endl; } sortida << endl; } //////////////////////////////////////////////////////////////////////////////// void StructHelperGenerator::GenerateImplementation(ofstream& sortida) { sortida << "#include \"stdafx.h\"" << endl; sortida << "#include \"arraystream.h\"" << endl; sortida << "#include \"DXTypeHelper.h\"" << endl; sortida << "#include \"" << m_className << ".h\"" << endl; sortida << endl; sortida << "using namespace dxtraceman;" << endl; sortida << endl; for (vector<StructDescriptionPtr>::iterator it = m_structures.begin(); it != m_structures.end(); it++) { GenerateImplementationMethod(sortida, *it); } } //////////////////////////////////////////////////////////////////////////////// void StructHelperGenerator::GenerateImplementationMethod(ofstream& sortida, StructDescriptionPtr structure) { StructSpecificCodePtr structSC = m_config.GetStructSpecificCode(structure->GetName()); // Begin generate method body sortida << "int " << m_className << "::" << structure->GetName() << "_ToString(char* buffer, unsigned int size, " << structure->GetName() << "* value)" << endl; sortida << "{" << endl; sortida << " char local_buffer[256];" << endl; sortida << " arraystream buf(buffer, size);" << endl; sortida << " std::ostream out(&buf);" << endl; sortida << endl; sortida << " out << \"# struct " << structure->GetName() << "\" << std::endl;" << endl; sortida << " out << \"# {\" << std::endl;" << endl; for (unsigned int i=0; i < structure->GetFieldCount(); i++) { string fieldType = structure->GetField(i)->GetType(); string fieldName = structure->GetField(i)->GetName(); if (structSC) { StructFieldSpecificCodePtr fieldSC = structSC->GetField(fieldName); if ((bool) fieldSC && (bool) fieldSC->GetPolicy(StructFieldSpecificCode::ChangeSaveType)) { StructFieldSpecificCode::StructFieldChangeSaveTypePolicy* fieldPolicy = (StructFieldSpecificCode::StructFieldChangeSaveTypePolicy*) (void*) fieldSC->GetPolicy(StructFieldSpecificCode::ChangeSaveType); fieldType = fieldPolicy->GetSaveType(); } } sortida << " DXTypeHelper::ToString(local_buffer, sizeof(local_buffer), (void*) &(value->" << fieldName << "), DXTypeHelper::TT_" << fieldType << ");" << endl; sortida << " out << \"# " << fieldName << " = \" << local_buffer << std::endl;" << endl; } sortida << " out << \"# }\";" << endl; sortida << endl; sortida << " buf.finalize();" << endl; sortida << " return buf.tellp();" << endl; // End generate method body sortida << "}" << endl; sortida << endl; } ////////////////////////////////////////////////////////////////////////////////
33.876543
208
0.552843
attila-sim
dc6678ef9afe543c5d5deced9af83b002c54688a
347
cpp
C++
src/package.cpp
michaelbrockus/ram-package-cpp
a7cfb37239c6cf49e15e9291c504175d7fac3c47
[ "Apache-2.0" ]
null
null
null
src/package.cpp
michaelbrockus/ram-package-cpp
a7cfb37239c6cf49e15e9291c504175d7fac3c47
[ "Apache-2.0" ]
1
2021-11-29T23:15:50.000Z
2021-11-29T23:15:50.000Z
src/package.cpp
michaelbrockus/ram-package-cpp
a7cfb37239c6cf49e15e9291c504175d7fac3c47
[ "Apache-2.0" ]
null
null
null
// // file: package.cpp // author: Michael Brockus // gmail: <[email protected]> // #include "hackazon/package.hpp" // // Should return a greeting message as it’s initial value // // Param list: // -> There is none to speak of at this time. // const char *hak::greet(void) { return "Hello, C++ Developer."; } // end of functions greet
19.277778
57
0.665706
michaelbrockus
dc68b8da5e55997fa812e97a16c0ff0cdf99d031
1,680
hpp
C++
src/BinaryBuffer.hpp
HU-ACTS/sensor-module
6277cba8eb41cf3ecb0aafd58ed25d58abff2d81
[ "Apache-2.0" ]
null
null
null
src/BinaryBuffer.hpp
HU-ACTS/sensor-module
6277cba8eb41cf3ecb0aafd58ed25d58abff2d81
[ "Apache-2.0" ]
null
null
null
src/BinaryBuffer.hpp
HU-ACTS/sensor-module
6277cba8eb41cf3ecb0aafd58ed25d58abff2d81
[ "Apache-2.0" ]
null
null
null
/** * @file binaryBuffer.hpp * @data 21 september, 2017 * * \class BinaryBuffer * * \brief Buffer between sensor and SPI SD write * * This class holds a finite amount of data and acts * as a FiFo. */ #pragma once #include <vector> #include "SystemVariables.hpp" #include "esp_log.h" class BinaryBuffer{ public: /*! * \brief BinaryBuffer constructor * * Clear the buffer and set state to write only. */ BinaryBuffer(); /*! * \brief readOnly method * * This method sets the buffer to read only mode. */ void readOnly(); /*! * \brief writeOnly method * * This method set the buffer to write only mode. */ void writeOnly(); /*! * \brief clear method * * This method clears the BinaryBuffer. */ void clear(); /*! * \brief add method * \param in SampleData structure * \return bool returns flase if state is read only * * This method adds a SampleData strcture * to the buffer. */ bool add( SampleData in ); /*! * \brief get method * \return SampleData buffer pointer * * This method returns a pointer to the * first sample of the buffer. */ const std::vector<SampleData>& get(); // should perhaps be a pointer, copy could be too slow on large scale operations? /*! * \brief isFull method * \return bool (true) if the buffer is full * * Returns true if the buffer is full */ bool isFull(); /*! * \brief BinaryBuffer deconstructor * * Empty, not implemented. */ ~BinaryBuffer(); private: bool readState(); bool state; std::vector<SampleData> buffer; const int BufferSize = BINARY_BUFFER_SIZE; };
19.310345
121
0.630357
HU-ACTS
dc6b1ac6b929f04af408a582bff1b04a643f3be5
496
cpp
C++
src/qt/ionspaymentprocessor.cpp
IOCoin/Chameleon-
6d4ad8e1dc7127fd992d65ce0c7039d0248f8b5a
[ "MIT" ]
3
2019-04-28T14:45:33.000Z
2021-04-15T09:04:32.000Z
src/qt/ionspaymentprocessor.cpp
IOCoin/Chameleon-
6d4ad8e1dc7127fd992d65ce0c7039d0248f8b5a
[ "MIT" ]
null
null
null
src/qt/ionspaymentprocessor.cpp
IOCoin/Chameleon-
6d4ad8e1dc7127fd992d65ce0c7039d0248f8b5a
[ "MIT" ]
1
2019-07-07T03:19:05.000Z
2019-07-07T03:19:05.000Z
#include "ionspaymentprocessor.h" #include <QString> #include <iostream> IONSPaymentProcessor::IONSPaymentProcessor(BitcoinGUI * gui, QObject * parent) : QObject(parent), gui(gui) { } void IONSPaymentProcessor::pay(QString address, QString fee) { QString uri("chameleon:" + address + "?amount=" + fee); gui->handleURI(uri); } void IONSPaymentProcessor::myUsernames() { gui->ionsMyUsernamesClicked(); } void IONSPaymentProcessor::Register() { gui->ionsRegisterClicked(); }
19.84
78
0.719758
IOCoin
dc6bd473fb4f511baf9097d7d38c69e7d537650f
4,209
cxx
C++
Source/Applications/AppCommon/pqCMBColorMapWidget.cxx
developkits/cmb
caaf9cd7ffe0b7c1ac3be9edbce0f9430068d2cb
[ "BSD-3-Clause" ]
null
null
null
Source/Applications/AppCommon/pqCMBColorMapWidget.cxx
developkits/cmb
caaf9cd7ffe0b7c1ac3be9edbce0f9430068d2cb
[ "BSD-3-Clause" ]
null
null
null
Source/Applications/AppCommon/pqCMBColorMapWidget.cxx
developkits/cmb
caaf9cd7ffe0b7c1ac3be9edbce0f9430068d2cb
[ "BSD-3-Clause" ]
null
null
null
//========================================================================= // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt 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 notice for more information. //========================================================================= #include "pqCMBColorMapWidget.h" #include "pqApplicationCore.h" #include "pqDataRepresentation.h" #include "pqProxyWidget.h" #include "vtkCommand.h" #include "vtkSMPVRepresentationProxy.h" #include "vtkSMProperty.h" #include "vtkSMPropertyHelper.h" #include "vtkSMTransferFunctionProxy.h" #include "vtkWeakPointer.h" #include <QPointer> #include <QVBoxLayout> class pqCMBColorMapWidget::pqInternals { public: QPointer<pqProxyWidget> ProxyWidget; QPointer<pqDataRepresentation> ActiveRepresentation; unsigned long ObserverId; pqInternals(pqCMBColorMapWidget* vtkNotUsed(self)) : ObserverId(0) { } ~pqInternals() {} }; pqCMBColorMapWidget::pqCMBColorMapWidget(QWidget* parentObject) : Superclass(parentObject) , Internals(new pqCMBColorMapWidget::pqInternals(this)) { // pqActiveObjects *activeObjects = &pqActiveObjects::instance(); // this->connect(activeObjects, SIGNAL(representationChanged(pqDataRepresentation*)), // this, SLOT(updateActive())); new QVBoxLayout(this); this->layout()->setMargin(0); this->updateRepresentation(); } pqCMBColorMapWidget::~pqCMBColorMapWidget() { delete this->Internals; this->Internals = NULL; } void pqCMBColorMapWidget::updatePanel() { if (this->Internals->ProxyWidget) { this->Internals->ProxyWidget->filterWidgets(true); } } void pqCMBColorMapWidget::updateRepresentation() { // pqDataRepresentation* repr = // pqActiveObjects::instance().activeRepresentation(); pqDataRepresentation* repr = this->Internals->ActiveRepresentation; // Set the current LUT proxy to edit. if (repr && vtkSMPVRepresentationProxy::GetUsingScalarColoring(repr->getProxy())) { this->setColorTransferFunction( vtkSMPropertyHelper(repr->getProxy(), "LookupTable", true).GetAsProxy()); } else { this->setColorTransferFunction(NULL); } } void pqCMBColorMapWidget::setDataRepresentation(pqDataRepresentation* repr) { // this method sets up hooks to ensure that when the repr's properties are // modified, the editor shows the correct LUT. if (this->Internals->ActiveRepresentation == repr) { return; } if (this->Internals->ActiveRepresentation) { // disconnect signals. if (this->Internals->ObserverId) { this->Internals->ActiveRepresentation->getProxy()->RemoveObserver( this->Internals->ObserverId); } } this->Internals->ObserverId = 0; this->Internals->ActiveRepresentation = repr; if (repr && repr->getProxy()) { this->Internals->ObserverId = repr->getProxy()->AddObserver( vtkCommand::PropertyModifiedEvent, this, &pqCMBColorMapWidget::updateRepresentation); } this->updateRepresentation(); } void pqCMBColorMapWidget::setColorTransferFunction(vtkSMProxy* ctf) { if (this->Internals->ProxyWidget == NULL && ctf == NULL) { return; } if (this->Internals->ProxyWidget && ctf && this->Internals->ProxyWidget->proxy() == ctf) { return; } if ((ctf == NULL && this->Internals->ProxyWidget) || (this->Internals->ProxyWidget && ctf && this->Internals->ProxyWidget->proxy() != ctf)) { this->layout()->removeWidget(this->Internals->ProxyWidget); delete this->Internals->ProxyWidget; } if (!ctf) { return; } pqProxyWidget* widget = new pqProxyWidget(ctf, this); widget->setObjectName("Properties"); widget->setApplyChangesImmediately(true); widget->filterWidgets(); this->layout()->addWidget(widget); this->Internals->ProxyWidget = widget; this->updatePanel(); QObject::connect(widget, SIGNAL(changeFinished()), this, SLOT(renderViews())); } void pqCMBColorMapWidget::renderViews() { if (this->Internals->ActiveRepresentation) { this->Internals->ActiveRepresentation->renderViewEventually(); } }
26.980769
91
0.692801
developkits
dc7096bc57120b88d88b63f377fb508eaa3183aa
5,104
cpp
C++
src/modules/twinkle.cpp
Cameloah/fairy-in-a-jar
a1ddc913664aff0bc7e9e71a1cd0a8cdecf44074
[ "MIT" ]
null
null
null
src/modules/twinkle.cpp
Cameloah/fairy-in-a-jar
a1ddc913664aff0bc7e9e71a1cd0a8cdecf44074
[ "MIT" ]
null
null
null
src/modules/twinkle.cpp
Cameloah/fairy-in-a-jar
a1ddc913664aff0bc7e9e71a1cd0a8cdecf44074
[ "MIT" ]
null
null
null
#include "modules/twinkle.h" // Background color for 'unlit' pixels // Can be set to CRGB::Black if desired. CRGB gBackgroundColor = CRGB::Black; // Example of dim incandescent fairy light background color // CRGB gBackgroundColor = CRGB(CRGB::FairyLight).nscale8_video(16); // Add or remove palette names from this list to control which color // palettes are used, and in what order. const TProgmemRGBPalette16* ActivePaletteList[] = { //&RetroC9_p, //&BlueWhite_p, //&RainbowColors_p, &HeatColors_p, //&LavaColors_p, &FairyLight_p, &RedGreenWhite_p, &ForestColors_p, &PartyColors_p, &RedWhite_p, &OceanColors_p, //&Snow_p, //&Holly_p, //&Ice_p }; CRGBPalette16 gCurrentPalette; CRGBPalette16 gTargetPalette; void twinkle_init() { delay( 1000 ); //safety startup delay chooseNextColorPalette(gTargetPalette); } void twinkle_update(CRGBSet& user_leds) { EVERY_N_SECONDS( SECONDS_PER_PALETTE ) { chooseNextColorPalette( gTargetPalette ); } EVERY_N_MILLISECONDS( 10 ) { nblendPaletteTowardPalette( gCurrentPalette, gTargetPalette, 12); } drawTwinkles( user_leds); } void drawTwinkles( CRGBSet& L) { // "PRNG16" is the pseudorandom number generator // It MUST be reset to the same starting value each time // this function is called, so that the sequence of 'random' // numbers that it generates is (paradoxically) stable. uint16_t PRNG16 = 11337; uint32_t clock32 = millis(); // Set up the background color, "bg". // if AUTO_SELECT_BACKGROUND_COLOR == 1, and the first two colors of // the current palette are identical, then a deeply faded version of // that color is used for the background color CRGB bg; if( (AUTO_SELECT_BACKGROUND_COLOR == 1) && (gCurrentPalette[0] == gCurrentPalette[1] )) { bg = gCurrentPalette[0]; uint8_t bglight = bg.getAverageLight(); if( bglight > 64) { bg.nscale8_video( 16); // very bright, so scale to 1/16th } else if( bglight > 16) { bg.nscale8_video( 64); // not that bright, so scale to 1/4th } else { bg.nscale8_video( 86); // dim, scale to 1/3rd. } } else { bg = gBackgroundColor; // just use the explicitly defined background color } uint8_t backgroundBrightness = bg.getAverageLight(); for( CRGB& pixel: L) { PRNG16 = (uint16_t)(PRNG16 * 2053) + 1384; // next 'random' number uint16_t myclockoffset16= PRNG16; // use that number as clock offset PRNG16 = (uint16_t)(PRNG16 * 2053) + 1384; // next 'random' number // use that number as clock speed adjustment factor (in 8ths, from 8/8ths to 23/8ths) uint8_t myspeedmultiplierQ5_3 = ((((PRNG16 & 0xFF)>>4) + (PRNG16 & 0x0F)) & 0x0F) + 0x08; uint32_t myclock30 = (uint32_t)((clock32 * myspeedmultiplierQ5_3) >> 3) + myclockoffset16; uint8_t myunique8 = PRNG16 >> 8; // get 'salt' value for this pixel // We now have the adjusted 'clock' for this pixel, now we call // the function that computes what color the pixel should be based // on the "brightness = f( time )" idea. CRGB c = computeOneTwinkle( myclock30, myunique8); uint8_t cbright = c.getAverageLight(); int16_t deltabright = cbright - backgroundBrightness; if( deltabright >= 32 || (!bg)) { // If the new pixel is significantly brighter than the background color, // use the new color. pixel = c; } else if( deltabright > 0 ) { // If the new pixel is just slightly brighter than the background color, // mix a blend of the new color and the background color pixel = blend( bg, c, deltabright * 8); } else { // if the new pixel is not at all brighter than the background color, // just use the background color. pixel = bg; } } } CRGB computeOneTwinkle( uint32_t ms, uint8_t salt) { uint16_t ticks = ms >> (8-TWINKLE_SPEED); uint8_t fastcycle8 = ticks; uint16_t slowcycle16 = (ticks >> 8) + salt; slowcycle16 += sin8( slowcycle16); slowcycle16 = (slowcycle16 * 2053) + 1384; uint8_t slowcycle8 = (slowcycle16 & 0xFF) + (slowcycle16 >> 8); uint8_t bright = 0; if( ((slowcycle8 & 0x0E)/2) < TWINKLE_DENSITY) { bright = attackDecayWave8( fastcycle8); } uint8_t hue = slowcycle8 - salt; CRGB c; if( bright > 0) { c = ColorFromPalette( gCurrentPalette, hue, bright, NOBLEND); if( COOL_LIKE_INCANDESCENT == 1 ) { coolLikeIncandescent( c, fastcycle8); } } else { c = CRGB::Black; } return c; } uint8_t attackDecayWave8( uint8_t i) { if( i < 86) { return i * 3; } else { i -= 86; return 255 - (i + (i/2)); } } void coolLikeIncandescent( CRGB& c, uint8_t phase) { if( phase < 128) return; uint8_t cooling = (phase - 128) >> 4; c.g = qsub8( c.g, cooling); c.b = qsub8( c.b, cooling * 2); } void chooseNextColorPalette( CRGBPalette16& pal) { const uint8_t numberOfPalettes = sizeof(ActivePaletteList) / sizeof(ActivePaletteList[0]); static uint8_t whichPalette = -1; whichPalette = addmod8( whichPalette, 1, numberOfPalettes); pal = *(ActivePaletteList[whichPalette]); }
28.513966
94
0.669867
Cameloah
dc70f7550217cfede7f560d4066f7d67f637bf1e
1,574
cpp
C++
src/elona/browser.cpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
null
null
null
src/elona/browser.cpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
null
null
null
src/elona/browser.cpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
null
null
null
#include "browser.hpp" #include <cstdlib> #include <string> #include "../util/range.hpp" #include "config/config.hpp" #ifdef ELONA_OS_WINDOWS #include <windows.h> #endif using namespace std::literals::string_literals; namespace { bool _is_trusted_url(const char* url) { const char* trusted_urls[] = { "http://ylvania.org/jp", "http://ylvania.org/en", "https://elonafoobar.com", }; return range::find(trusted_urls, url) != std::end(trusted_urls); } } // namespace namespace elona { void open_browser(const char* url) { if (Config::instance().is_test) { return; } if (!_is_trusted_url(url)) { throw std::runtime_error{"Try to open unknown URL!"}; } #if defined(ELONA_OS_WINDOWS) HWND parent = NULL; LPCWSTR operation = NULL; // `url` must be ascii only. const auto len = std::strlen(url); std::basic_string<WCHAR> url_(len, L'\0'); for (size_t i = 0; i < len; ++i) { url_[i] = url[i]; } LPCWSTR extra_parameter = NULL; LPCWSTR default_dir = NULL; INT show_command = SW_SHOWNORMAL; ::ShellExecute( parent, operation, url_.c_str(), extra_parameter, default_dir, show_command); #elif defined(ELONA_OS_MACOS) std::system(("open "s + url).c_str()); #elif defined(ELONA_OS_LINUX) std::system(("xdg-open "s + url).c_str()); #elif defined(ELONA_OS_ANDROID) // TODO: implement for android. (void)url; return; #else #error "Unsupported OS" #endif } } // namespace elona
18.963855
68
0.617535
XrosFade
dc78e1b955c29b261b2103479ea00bb836c0a31f
3,457
cc
C++
lite/kernels/arm/concat_compute.cc
xw-github/Paddle-Lite
3cbd1d375d89c4deb379d44cdbcdc32ee74634c5
[ "Apache-2.0" ]
null
null
null
lite/kernels/arm/concat_compute.cc
xw-github/Paddle-Lite
3cbd1d375d89c4deb379d44cdbcdc32ee74634c5
[ "Apache-2.0" ]
null
null
null
lite/kernels/arm/concat_compute.cc
xw-github/Paddle-Lite
3cbd1d375d89c4deb379d44cdbcdc32ee74634c5
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "lite/kernels/arm/concat_compute.h" #include <string> #include <vector> #include "lite/backends/arm/math/funcs.h" #include "lite/core/op_registry.h" #include "lite/core/tensor.h" #include "lite/core/type_system.h" namespace paddle { namespace lite { namespace kernels { namespace arm { std::vector<size_t> stride_numel(const DDim& ddim) { std::vector<size_t> strides(ddim.size()); strides[ddim.size() - 1] = ddim[ddim.size() - 1]; for (int i = ddim.size() - 2; i >= 0; --i) { strides[i] = strides[i + 1] * ddim[i]; } return strides; } template <typename T> void ConcatFunc(const std::vector<lite::Tensor*> inputs, int axis, lite::Tensor* out) { // Sometimes direct copies will be faster, this maybe need deeply analysis. if (axis == 0 && inputs.size() < 10) { size_t output_offset = 0; for (auto* in : inputs) { auto in_stride = stride_numel(in->dims()); auto out_stride = stride_numel(out->dims()); void* dst = out->mutable_data<T>() + output_offset; const void* src = in->data<T>(); // src and dst tensor should have the same dims size. CHECK(in_stride.size() == out_stride.size()); std::memcpy(dst, src, sizeof(T) * in_stride[0]); output_offset += in_stride[0]; } } else { std::vector<lite::Tensor*> inputs_concat(inputs.size()); for (int j = 0; j < inputs.size(); ++j) { inputs_concat[j] = inputs[j]; } lite::arm::math::concat_func<T>(inputs_concat, axis, out); } } void ConcatCompute::Run() { auto& param = Param<operators::ConcatParam>(); std::vector<lite::Tensor*> inputs = param.x; CHECK_GE(inputs.size(), 1); auto* out = param.output; int axis = param.axis; auto* axis_tensor = param.axis_tensor; if (axis_tensor != nullptr) { auto* axis_tensor_data = axis_tensor->data<int>(); axis = axis_tensor_data[0]; } switch (inputs.front()->precision()) { case PRECISION(kFloat): ConcatFunc<float>(inputs, axis, out); break; case PRECISION(kInt32): ConcatFunc<int32_t>(inputs, axis, out); break; case PRECISION(kInt64): ConcatFunc<int64_t>(inputs, axis, out); break; default: LOG(FATAL) << "Concat does not implement for the " << "input type:" << static_cast<int>(inputs.front()->precision()); } } } // namespace arm } // namespace kernels } // namespace lite } // namespace paddle REGISTER_LITE_KERNEL( concat, kARM, kAny, kNCHW, paddle::lite::kernels::arm::ConcatCompute, def) .BindInput("X", {LiteType::GetTensorTy(TARGET(kARM), PRECISION(kAny))}) .BindInput("AxisTensor", {LiteType::GetTensorTy(TARGET(kARM), PRECISION(kInt32))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kARM), PRECISION(kAny))}) .Finalize();
33.240385
78
0.649407
xw-github
dc7b9cfa26f956c189206b088a989af82ea64920
47,529
inl
C++
src/fonts/stb_font_consolas_bold_35_usascii.inl
stetre/moonfonts
5c8010c02ea62edcf42902e09478b0cd14af56ea
[ "MIT" ]
3
2018-03-13T12:51:57.000Z
2021-10-11T11:32:17.000Z
src/fonts/stb_font_consolas_bold_35_usascii.inl
stetre/moonfonts
5c8010c02ea62edcf42902e09478b0cd14af56ea
[ "MIT" ]
null
null
null
src/fonts/stb_font_consolas_bold_35_usascii.inl
stetre/moonfonts
5c8010c02ea62edcf42902e09478b0cd14af56ea
[ "MIT" ]
null
null
null
// Font generated by stb_font_inl_generator.c (4/1 bpp) // // Following instructions show how to use the only included font, whatever it is, in // a generic way so you can replace it with any other font by changing the include. // To use multiple fonts, replace STB_SOMEFONT_* below with STB_FONT_consolas_bold_35_usascii_*, // and separately install each font. Note that the CREATE function call has a // totally different name; it's just 'stb_font_consolas_bold_35_usascii'. // /* // Example usage: static stb_fontchar fontdata[STB_SOMEFONT_NUM_CHARS]; static void init(void) { // optionally replace both STB_SOMEFONT_BITMAP_HEIGHT with STB_SOMEFONT_BITMAP_HEIGHT_POW2 static unsigned char fontpixels[STB_SOMEFONT_BITMAP_HEIGHT][STB_SOMEFONT_BITMAP_WIDTH]; STB_SOMEFONT_CREATE(fontdata, fontpixels, STB_SOMEFONT_BITMAP_HEIGHT); ... create texture ... // for best results rendering 1:1 pixels texels, use nearest-neighbor sampling // if allowed to scale up, use bilerp } // This function positions characters on integer coordinates, and assumes 1:1 texels to pixels // Appropriate if nearest-neighbor sampling is used static void draw_string_integer(int x, int y, char *str) // draw with top-left point x,y { ... use texture ... ... turn on alpha blending and gamma-correct alpha blending ... glBegin(GL_QUADS); while (*str) { int char_codepoint = *str++; stb_fontchar *cd = &fontdata[char_codepoint - STB_SOMEFONT_FIRST_CHAR]; glTexCoord2f(cd->s0, cd->t0); glVertex2i(x + cd->x0, y + cd->y0); glTexCoord2f(cd->s1, cd->t0); glVertex2i(x + cd->x1, y + cd->y0); glTexCoord2f(cd->s1, cd->t1); glVertex2i(x + cd->x1, y + cd->y1); glTexCoord2f(cd->s0, cd->t1); glVertex2i(x + cd->x0, y + cd->y1); // if bilerping, in D3D9 you'll need a half-pixel offset here for 1:1 to behave correct x += cd->advance_int; } glEnd(); } // This function positions characters on float coordinates, and doesn't require 1:1 texels to pixels // Appropriate if bilinear filtering is used static void draw_string_float(float x, float y, char *str) // draw with top-left point x,y { ... use texture ... ... turn on alpha blending and gamma-correct alpha blending ... glBegin(GL_QUADS); while (*str) { int char_codepoint = *str++; stb_fontchar *cd = &fontdata[char_codepoint - STB_SOMEFONT_FIRST_CHAR]; glTexCoord2f(cd->s0f, cd->t0f); glVertex2f(x + cd->x0f, y + cd->y0f); glTexCoord2f(cd->s1f, cd->t0f); glVertex2f(x + cd->x1f, y + cd->y0f); glTexCoord2f(cd->s1f, cd->t1f); glVertex2f(x + cd->x1f, y + cd->y1f); glTexCoord2f(cd->s0f, cd->t1f); glVertex2f(x + cd->x0f, y + cd->y1f); // if bilerping, in D3D9 you'll need a half-pixel offset here for 1:1 to behave correct x += cd->advance; } glEnd(); } */ #ifndef STB_FONTCHAR__TYPEDEF #define STB_FONTCHAR__TYPEDEF typedef struct { // coordinates if using integer positioning float s0,t0,s1,t1; signed short x0,y0,x1,y1; int advance_int; // coordinates if using floating positioning float s0f,t0f,s1f,t1f; float x0f,y0f,x1f,y1f; float advance; } stb_fontchar; #endif #define STB_FONT_consolas_bold_35_usascii_BITMAP_WIDTH 256 #define STB_FONT_consolas_bold_35_usascii_BITMAP_HEIGHT 160 #define STB_FONT_consolas_bold_35_usascii_BITMAP_HEIGHT_POW2 256 #define STB_FONT_consolas_bold_35_usascii_FIRST_CHAR 32 #define STB_FONT_consolas_bold_35_usascii_NUM_CHARS 95 #define STB_FONT_consolas_bold_35_usascii_LINE_SPACING 23 static unsigned int stb__consolas_bold_35_usascii_pixels[]={ 0x0309fff3,0x00022000,0x300037ae,0x30000375,0x3ee7fdb9,0x3fffffff, 0xfffffffb,0x337be63f,0x3ba00002,0x99730005,0x10000035,0x0cccc333, 0x55553000,0x0aaaa600,0x884ccc00,0x88000999,0xfff99999,0x00017e44, 0xc8003ba2,0xb800ffff,0x05ffffff,0xfffff900,0x3ffffee7,0xfffb3fff, 0x263fffff,0x00dfffff,0x037fc400,0x3ffffee0,0x00001fff,0x7ecffff1, 0xf30002ff,0xfd005fff,0xf30009ff,0x3fff2dff,0xfffc8003,0x324fff9e, 0x10002fff,0x2001dffd,0x202fffff,0xffffffe8,0x7e4005ff,0xf73fffff, 0x7fffffff,0x3ffffff6,0xffff31ff,0xa8000dff,0xfb1005ff,0xffffffff, 0xf700007f,0x7ffcc7ff,0x3ffa0005,0x7ffcc05f,0xff98000f,0x07fff96f, 0x3dfff900,0x7fe49fff,0x744002ff,0x3a006fff,0xf102ffff,0xfd99dfff, 0x3e600dff,0x309adfff,0xfff95555,0x2abfff67,0x32a60aaa,0x0003ffff, 0x2009ff91,0xfffffffe,0x003fffff,0x207fffc0,0x0001fffe,0x401ffff7, 0x0005fffc,0x3f2dfff3,0xfb8003ff,0x4fff9dff,0x00ffffe4,0x01dfffb0, 0x037ffdc0,0xf707fffb,0xff9005ff,0x7fd4009f,0x00fffb3f,0x006fffa8, 0x3fffff6a,0xff504eff,0xf7315bff,0x4000ffff,0xfa84fffa,0xf10004ff, 0x7fc07fff,0xf30002ff,0x3fff2dff,0xfffb8003,0xd84fff9d,0xf7006fff, 0x30001dff,0x7ffdc079,0x017ff602,0x8003fff6,0xffb3fffa,0xfffd000f, 0xffffd300,0x0fffffff,0x5417fffa,0x0003ffff,0x3e03fffd,0x90000fff, 0x3ea0dfff,0x260007ff,0xfff96fff,0xfff50007,0x209fff39,0x4c04fffe, 0x0001ffff,0x09fff100,0x400fff98,0x54007ffe,0xfffb3fff,0x1fffb000, 0x7ffffc40,0x7fffffff,0x407fffb8,0x8006fffd,0x3206fff9,0x30003fff, 0xfb01ffff,0x4c0009ff,0xfff96fff,0xfff50007,0x209fff39,0x201ffffa, 0x5104fffe,0x55555555,0xfff70555,0x07fff001,0x4006fff8,0xffb3fffa, 0xfff9000f,0x7ffff401,0xdbafffbd,0x04fffd86,0x007fffd4,0x80bfff20, 0x0006fff8,0xf10ffffa,0x31003fff,0xfff99995,0x98ffff2d,0xf980abcb, 0x4fff9bff,0x417fff60,0x2a06fffa,0xffffffff,0x7fc0ffff,0x9110c43f, 0xfff809ff,0x7ffd4006,0x000fffb3,0x2201fff9,0xff33ffff,0x5fffd00b, 0x1ffff880,0x1fffe200,0x00bfff60,0x237ffdc0,0xa806fffa,0xffffffff, 0x7fff96ff,0xdfffffd1,0x9bfff981,0x3e204fff,0xffd80fff,0x3ffea02f, 0xffffffff,0x43ffea0f,0xcfefffe9,0x7fc05ffb,0x7fd4006f,0x00fffb3f, 0x201fff90,0xf50ffffa,0xffff009f,0x5ffff003,0x1fffdc00,0x02fffcc0, 0x1ffff880,0x880ffff6,0xfffffffd,0xff96ffff,0xfffffd9f,0x55443fff, 0x04fff98a,0x221fffec,0x75407fff,0xfeeeeeee,0x3ff20fff,0xffffff35, 0x80dff57f,0x54006fff,0xfffb3fff,0x3fff7000,0x4bfffe60,0x7c403ffb, 0xff800fff,0x3fa003ff,0xffd000ff,0x3f60001f,0xffff14ff,0x7fffec01, 0xffffdcdf,0xffffff96,0xbfffffdf,0x04fff980,0x2e37ffd4,0x40004fff, 0x3a0ffff8,0xffffd3ff,0xfff57fff,0x02fffc40,0x6cfffea0,0xfb8007ff, 0xfff104ff,0x05ffb9ff,0x00ffff98,0x004fffe8,0x400bfff5,0x0004fffb, 0x3eeffff3,0x3fea04ff,0xfff984ff,0xbfffff96,0x07fffec3,0x809fff30, 0x360ffff8,0x40002fff,0xf10ffff8,0x7fff53ff,0xff35fff1,0x1fffe40f, 0x4fffea00,0x98007ffd,0xfb00efff,0x3fffffff,0x0ffffa80,0x03fffe80, 0x003fffb0,0x000ffff8,0xfd5fffd0,0x7ffc03ff,0xdfff305f,0x41bffff2, 0x2603ffff,0xfd804fff,0x3fffa1ff,0x7fc40000,0x1fff50ff,0x3fe6dff9, 0x227ff99f,0x0ffffdba,0x9fffd400,0xb0007ffd,0x437bffff,0xffffffe8, 0xff301cff,0xfff003ff,0xfff3005f,0xfff9000d,0x3fee0007,0x206fffef, 0x301ffff9,0x3ff2dfff,0xfffb00ef,0x27ffcc0b,0xf17ffe40,0x10000fff, 0x3ee1ffff,0x2a9ffd6f,0x7ff98fff,0x3bffffea,0xfffa8001,0x000fffb3, 0x27ffff54,0x3fffff62,0x440dffff,0xf801ffff,0xfc801fff,0xf88002ff, 0xf10006ff,0x07ffffff,0x303fffd4,0x3ff2dfff,0x3ffee03f,0x13ffe606, 0x44ffff20,0x80006fff,0xf90ffff8,0x54fffebf,0x4dff57ff,0x00dffffa, 0x27fff500,0x20007ffd,0x04ffffda,0xffffffb5,0xfff81dff,0x7ffc403f, 0x7ffc400f,0x3ff60007,0xffb0001f,0x5c01ffff,0x3e606fff,0x7fff96ff, 0x03fffdc0,0x7009fff3,0x3fe69fff,0xf880005f,0x9ff90fff,0x3ee5fff1, 0x54dff57f,0x04fffffe,0xb3fffa80,0x2e000fff,0x03efffff,0x7fffffdc, 0x7fff46ff,0x3fffdc05,0x027ffdc0,0x0bfff500,0x3fffea00,0x7ffe404f, 0x5bffe605,0x2a03fffc,0x3e606fff,0xffb804ff,0x0dfff34f,0xffff1000, 0x3e33ff61,0x2dff92ff,0xeb885ffb,0x54002fff,0xfffb3fff,0xffff1000, 0x67fe4003,0x21fffffc,0x200ffffb,0xe803fffe,0x40000fff,0x0000fffe, 0x801ffffd,0x2605fffc,0xfff96fff,0x2fffdc07,0x009fff30,0x3e27fff7, 0x880007ff,0xffb0ffff,0x323fff17,0x09ff95ff,0x0027ffdc,0x7ecfffea, 0xffa8007f,0x7fec003f,0x47ffff51,0x80effff8,0x400ffffd,0x0005fffa, 0x004fffb8,0x00bffff0,0x540dfff7,0xfff96fff,0x27ffec07,0x009fff30, 0x7fc5fff9,0xf880007f,0x7ffb0fff,0x3fa5fff1,0x405ffd5f,0x4005fff8, 0xffb3fffa,0xfff7000f,0x0ffe8003,0xfb0ffffe,0xd97bdfff,0xb009ffff, 0x00003fff,0x000ffff1,0x003ffff7,0x101ffff5,0x3f2dfffd,0xfff103ff, 0x7ffcc05f,0x1fffd804,0x0007fffe,0x21ffff10,0x7fff4ffd,0xff3bfff7, 0x0dfff00f,0xb3fffa80,0xf9000fff,0xff8001ff,0x217fffc7,0xffffffe8, 0x805fffff,0x0006fff8,0x00bfff20,0x04ffffa8,0x07ffff10,0x32dffffd, 0xffb03fff,0x7fcc01ff,0x7ffc404f,0x0ffff60f,0xffff1000,0x7f57ff21, 0xffffffff,0xfff805ff,0x7ffd4006,0x000fffb3,0x2a01fff9,0x45bfe21b, 0x880ffffd,0xfffffffe,0xff9005ff,0x4c00007f,0x2aa06fff,0x06ffffda, 0x5ffffec0,0xffffffb9,0x41bfff96,0x03ffffd9,0x2027ffcc,0x7dc5fffa, 0x440006ff,0xff70ffff,0x3bfffeed,0x00effffd,0x4006fff8,0xffb3fffa, 0xfff9000f,0x3bffee01,0xfffdeffd,0x7f5404ff,0x002dffff,0x001ffff1, 0x1fffd800,0xfffffff0,0xff98001f,0xffffffff,0xfff96ffe,0xffffffff, 0xfff300bf,0x2fffd809,0x00ffffc4,0x1ffff100,0xffc9ffea,0x0dffe88e, 0x00dfff00,0xfb3fffa8,0xff9000ff,0x3ffee01f,0xffffffff,0x3ee005ff, 0x7dc004ff,0x800004ff,0xff05fffa,0x001bffff,0x3ffffee0,0x6ffd9fff, 0xfffffff9,0x0019ffff,0x4409fff3,0xffb06fff,0x7c40009f,0x3ffe67ff, 0x00020221,0x5001bffe,0x3ff67fff,0xfffc8007,0xfffff700,0x7fffffff, 0x6fff9800,0x3fffa010,0xfd000000,0xdfff01ff,0xd500005b,0x361bffff, 0xffb736ff,0x03bfffff,0x027ffcc0,0x2a07fffb,0x0001ffff,0xff8ffff5, 0xd000004f,0xfa800fff,0x0fffb3ff,0x01fffb00,0x3ffb2ea2,0x0002cdff, 0x13dffff1,0xfff30d93,0x5c00000b,0x09883fff,0x35100000,0x33310001, 0x3fe60001,0xdfff504f,0x37ffec01,0x5fffd800,0x0007ffe4,0x07ffec00, 0x27fff500,0xe8007ffd,0x7f4007ff,0xf900000f,0xffffffff,0x02fffd89, 0x3fe20000,0x0000007f,0x00000000,0x213ffe60,0x401ffff8,0x183ffff8, 0x13fffe20,0x300dfff3,0x5fffb800,0x4fffea00,0x5c007ffd,0x7c006fff, 0x7400007f,0xffffffff,0x0dfff10f,0xff900000,0x4ccccc5f,0x99999999, 0x10999999,0x11111111,0x00000011,0x444fff98,0x5004fffe,0xef85ffff, 0xffeb99ab,0xfffe80ff,0x0375c41d,0x3bfffe20,0x555531ac,0x3f67fff9, 0x0aaaaaff,0xffffb751,0x37fc4005,0x3ee20000,0x20dfffff,0x0002ccc9, 0x3ccc8800,0x3ffffffe,0xffffffff,0xff91ffff,0xdfffffff,0x98000000, 0x7ff44fff,0x7fe4006f,0x3fffe2ff,0x2fffffff,0xfffffd10,0x00dffffd, 0xffffff70,0x3ffffee7,0xfffb3fff,0x263fffff,0x06ffffff,0x002ffd40, 0x9aa98800,0x00000000,0xfffff800,0xffffffff,0x91ffffff,0xffffffff, 0x000000df,0x364fff98,0x8000efff,0xff1ffffd,0xffffffff,0xfffe8807, 0x05ffffff,0xfffff700,0x3ffffee7,0xfffb3fff,0x263fffff,0x00cfffff, 0x0004cc40,0x00000000,0x3e000000,0xffffffff,0xffffffff,0xffff91ff, 0x00dfffff,0xff980000,0x03bfea4f,0x24ffd800,0xefffffdb,0x3b2e000c, 0x001cefff,0x976e5440,0xeeeeeeea,0xddddd92e,0x37a61ddd,0x000001bc, 0x00000000,0x00000000,0x77500000,0x77777777,0x98000000,0x07544fff, 0x2026c000,0x11000008,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x013ffe60,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x7fcc0000,0x0000004f, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x20000000,0x00000009, 0x00d54400,0x54c01998,0xaaaabccc,0x0cccc42a,0x200eed40,0x80009998, 0x99999999,0x26600001,0x5cc01aaa,0x00999882,0x65d4c000,0x533a89ac, 0xabdca855,0x016e6000,0xaccb9880,0xefff9801,0x64c000bc,0x4003defe, 0x01effffb,0x6c41bff2,0xffffffff,0x3f60ffff,0x7fd407ff,0x3ff200ff, 0xfff8003f,0x01ffffff,0x7fff5400,0xff907fff,0x5fffb8df,0xfff50000, 0xdfffffff,0x7f4dfff2,0x400effff,0x0007fff9,0xfffffff7,0x7ffcc03f, 0x800bffff,0xfffffffc,0xfffb801e,0xf980ffff,0xfff880ff,0xffffffff, 0x3ff60fff,0x7ffec07f,0x3fff203f,0xffff8003,0x001fffff,0x3fffff60, 0xff987fff,0x3fee3fff,0x6c40005f,0xffffffff,0xfff96fff,0xfffffff5, 0x7fd403ff,0x7ec4007f,0xffffffff,0xffff303f,0x403fffff,0xfffffffc, 0x7fc00eff,0x83ffeabf,0xffd03ffe,0xfff935bf,0x7ec199bf,0x7fec07ff, 0x3ff203ff,0xfff8003f,0x01ffffff,0xfffff700,0xf50fffdf,0x7dc9ffff, 0x6c0005ff,0xdcdfffff,0xff96ffff,0xffdfffff,0x7d40bfff,0x7f4007ff, 0xffffffff,0xee883fff,0xefffffff,0xbffff980,0x04ffffb9,0xffa9bfe6, 0x9837fdc5,0xff986fff,0xffff906f,0x0ffff980,0x00ffff20,0x0ffffc00, 0x7fffc400,0x7cc0c40d,0x3ee3ffff,0x2a0005ff,0xf984ffff,0xffff96ff, 0x7ffec3bf,0xffff500f,0x7fffdc00,0xfffc98ad,0xffd7007f,0xfff70bff, 0x05fffa87,0xff993fea,0x407ffe66,0xfd02fffa,0xfff901ff,0x0177300d, 0x003fffc8,0x03ffff00,0x1ffff300,0x6fffd800,0x002fffdc,0x20bfffd0, 0xff96fff9,0x3ffe0dff,0xf955553f,0x55555fff,0x7fffc435,0x7ffff504, 0x3fffa200,0x07ffec0f,0xf5037ffc,0xd2ffd4bf,0x7fdc07ff,0x3fff902f, 0x00dfff90,0x3fffc800,0xffff0000,0xfff50003,0x0f2a000b,0x0017ffee, 0x80ffffcc,0xff96fff9,0x3ff601df,0xffffff5f,0xffffffff,0x3fffdcbf, 0x01bfff60,0x41ffffa8,0x7cc1fffd,0x3fe605ff,0x2e9ff90f,0x7fd406ff, 0x0fffd04f,0x551bfff2,0x15555555,0x51fffe40,0x7c0059b9,0xc8001fff, 0x00004fff,0x105fffb8,0x7d455555,0x3fe607ff,0x07fff96f,0xffb7ffdc, 0xffffffff,0x365fffff,0x7d404fff,0xf1000fff,0xffb87fff,0x1fffec4f, 0x3fbfffa0,0x1fff88ff,0x0ffffc40,0x5c1bffee,0x7ffc5fff,0x01ffffff, 0x3a6bfff2,0x00efffff,0x001ffff8,0x004fffc8,0x5fffb800,0x1ffffe88, 0x981bffee,0xfff96fff,0xbfffdc07,0xfffeeeed,0x4eeeeeef,0x100bfffa, 0x2003ffff,0x4c1ffff9,0xfd89ffff,0xff9806ff,0xffb3ffff,0x3fff2009, 0xffffecef,0x8bfff701,0xffffffff,0x3fff201f,0xfffffffc,0xffff806f, 0xfffc8001,0xfb800004,0xfffd85ff,0x2fffe42f,0x32dfff30,0x3ea03fff, 0xfff506ff,0x3fffe00f,0x2ffff801,0x1ffffb00,0xffdfffb0,0x22001dff, 0xff71deed,0x7ffd400d,0x3fffffff,0xb17ffee0,0xffffdddd,0x7fffe403, 0xffffffff,0x7fffc02f,0x77775c01,0xeeefffff,0x70002eee,0xffc8bfff, 0xfffc83ff,0x5bffe605,0x2e03fffc,0xff505fff,0xfff100ff,0xffff001f, 0xfd755307,0x3e209fff,0x0dffffff,0xfff88000,0xdfff1001,0x019fffff, 0x805fffa8,0x3201ffff,0x31dfffff,0xf809fffd,0x7e401fff,0xffffffff, 0x03ffffff,0x3fee02a2,0x3fffea5f,0x0dfff704,0xfcb7ffd4,0x3ff603ff, 0xffff504f,0x1ffff300,0x09fffd00,0xfffffffb,0x7ffec01d,0x200002ff, 0x32004ffd,0x000627ff,0xf009fff5,0x7e403fff,0xffc86fff,0x7fffc05f, 0x7fffe401,0xffffffff,0xff703fff,0x5fffb87f,0x409ffff3,0x880ffffa, 0xff96fffe,0x3ffe207f,0xffff502f,0x1ffff300,0x07fffd00,0xbffffffb, 0x3fffa201,0x66642fff,0x1bfea003,0x00fffd00,0x04fffa80,0x201ffff8, 0xa80efffc,0x7fc06fff,0x554c01ff,0xadfffdaa,0x880aaaaa,0x2e2fffff, 0xfff8dfff,0x7ffc405f,0xffffe83f,0x207fff96,0x500ffffd,0xf300ffff, 0xff003fff,0xfff905ff,0xffd8037d,0x10ffffff,0x2200bfff,0x6c001fff, 0x9aabefff,0xfffa8019,0x1ffff804,0x40ffff20,0x7c06fff9,0xc8001fff, 0x4c004fff,0x2e5fffff,0xfffedfff,0xffffb006,0xfffff737,0x37fff2df, 0x3ffff660,0x1fffea03,0x07fffe20,0x207fffe0,0xb801fffc,0xffe8efff, 0x4fff88ef,0x269ffb00,0xf703effe,0xffffffff,0x3e605dff,0xfff803ff, 0x3fff201f,0x0dfff303,0x001ffff8,0x004fffc8,0x3fffffc4,0xfffffff7, 0x3fe6001f,0xffffffff,0xfff96fff,0xffffffff,0xfffa80bf,0x7ffff007, 0x0ffff880,0x801fffb8,0xff11ffff,0x7fff5bff,0x51fff500,0x09ffffff, 0x3ffffff2,0x85ffffff,0xf803fff9,0x3f201fff,0xfff303ff,0x1ffff80d, 0x4fffc800,0xffffa800,0x3fbffee7,0x2e005fff,0xffffffff,0xff96fffa, 0xffffffff,0xffa8019f,0xfffd007f,0x7fffb80b,0x801fff70,0x7d46fff9, 0x2fffefff,0x457ffc40,0xfffddfff,0x77fff4c1,0xfffffeee,0x1fffcc3f, 0x00ffffc0,0x2607fff9,0x7fc06fff,0xfc8001ff,0xf90004ff,0x7ffdcdff, 0x03ffffad,0x3ffffaa0,0x96fff88d,0xffffffff,0x3e6003bf,0xfb800fff, 0x3fa00fff,0x500004ff,0xff70bfff,0xb00dffff,0x97feabff,0x3fa23ffd, 0xffd302ff,0xff0000df,0x7fe403ff,0xdfff303f,0x01ffff80,0x04fffc80, 0x49fff500,0xff95fffb,0xa88005ff,0x5bffe609,0x999bfffc,0xfff88000, 0xfff8802f,0xfffd80ef,0xf500000f,0x3ff60dff,0x7d403fff,0x47ff70ff, 0x3fee4ffb,0x7ffd405f,0xfff80007,0x3fff201f,0x0dfff303,0x001ffff8, 0x004fffc8,0x5c5fff90,0x3ffa5fff,0x980000ff,0xfff96fff,0x3fe00007, 0x0660aeff,0x79dffff9,0x07ffffd9,0x2006ff54,0xd01ffff8,0x4403ffff, 0x3ff22fff,0xfc93fea3,0x7fdc05ff,0x06f6445f,0x00ffffc0,0x2607fff9, 0x7fc06fff,0xfc8001ff,0x5c4004ff,0x7fdc4fff,0x3fffe65f,0x7cc0000e, 0x7fff96ff,0x3ff60000,0x5fffffff,0x7fffff44,0x0effffff,0x0dffff10, 0x15fffff0,0x3fffff26,0x717ff206,0x1ffe4bff,0x207ffff7,0x6c3ffffa, 0x26626fff,0xaffff999,0x3ff21999,0xdfff303f,0x3e666662,0x1999afff, 0x04fffc80,0xffffee88,0x2fffdc0e,0x017fffee,0x2dfff300,0x0003fffc, 0xffffff10,0xfb10bfff,0xffffffff,0xffffa809,0x7ffd400f,0xffffffff, 0xf984ffff,0x7ffcc0ff,0x220fffbc,0xeeffffff,0x84fffffe,0xf71fffff, 0xffffffff,0x323fffff,0xff303fff,0x3fffeedf,0xffffffff,0x7fe401ff, 0xfff8804f,0xfff703ff,0x7ffffb0b,0x7ffcc000,0x007fff96,0x7ffe4400, 0x2e04ffff,0x2efffffe,0x7ffff980,0xfffff900,0xffbfffff,0x2ffe87ff, 0xffffffb0,0xfffff309,0x9fffffff,0x43ffffa0,0xfffffffb,0x1fffffff, 0x2607fff9,0xfff76fff,0xffffffff,0xfc803fff,0xdf8804ff,0x3fee00bc, 0xfffe885f,0xff30002f,0x0ffff2df,0x54cc0000,0x0d4c001a,0x17ffe400, 0xffffb300,0x3ff219ff,0x0bff92ff,0x03ffffc8,0x3ffff6a2,0x2a00beff, 0x3fee3fff,0xffffffff,0xff91ffff,0x3ffe607f,0xffffff76,0xffffffff, 0x4fffc803,0xffb80000,0xffff305f,0xdd30003f,0x0bbbaebd,0x00000000, 0x054c0000,0x01553000,0x03300000,0x20006200,0x000000a8,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x10000000, 0x35999975,0x3732a601,0x55400abc,0xaaaaaaaa,0x310002aa,0x95300555, 0x00015799,0x2b332ea2,0x00d554c1,0xaa86aaa2,0xaaaaaaaa,0x953000aa, 0x4c003799,0x4c01accb,0x53002aaa,0x55554555,0x55551002,0x002aaa21, 0x5551aaa8,0x55555555,0xffc88155,0x5fffffff,0xfffffff8,0xff00cfff, 0xffffffff,0x32200fff,0x07ffffff,0x3fffff66,0x7000cfff,0xffffffff, 0x3ffee7ff,0x2fffdc05,0xfffffffd,0x4c07ffff,0xfffffffe,0x3fee00ff, 0x00efffff,0x003ffff5,0x7ec9fffd,0xff7007ff,0x0fffd4ff,0x3a9ffd00, 0xffffffff,0x3ea2ffff,0xffffffff,0xffff85ff,0x6fffffff,0xfffffff0, 0x80ffffff,0xffffffd8,0xfff307ff,0xffffffff,0xfffe880b,0xffffffff, 0x80bfff74,0x3fa5fffb,0xffffffff,0xfff703ff,0xffffffff,0x3ffff201, 0x02ffffff,0xa80bfffd,0x3ee0ffff,0xfd801fff,0x3ffea5ff,0x53ffe002, 0xfffffffe,0xf12fffff,0xffffffff,0xfff0bfff,0xfffffddf,0xfffff09f, 0xffffffff,0x7ffff440,0x887fffff,0xdcdfffff,0x503fffff,0xffffffff, 0x2e9fffff,0x7dc05fff,0x3fffa5ff,0xffffffff,0xfffffd83,0x0fffffff, 0xdfffffd8,0x81ffffff,0x200ffffa,0x7c44fffe,0xff804fff,0x3ffe62ff, 0x4fffe002,0xfffffffe,0xf92fffff,0x73019fff,0xa8815909,0xff87ffff, 0xccccccff,0xfff104cc,0x33357dff,0x0dfff703,0x741bfff2,0x89beffff, 0xf74fda98,0xffb80bff,0x2666625f,0x3fffe999,0x67ffffd4,0x0fdb988a, 0x21ffffcc,0xd05ffffa,0x3ea09fff,0xffe80fff,0x7ffd406f,0x0bffe60f, 0xfd3fff80,0x333337ff,0x3ffa1333,0x7000004f,0xff81ffff,0x3f20007f, 0x64002fff,0xff103fff,0xffff70ff,0x7fdc200b,0x7ffdc05f,0x3fffa005, 0x17ffff43,0x3fff6020,0x1ffff704,0x01ffff50,0x2e09fffd,0x3200ffff, 0x7fc45fff,0x3ffe003f,0x005fffd3,0x001ffffc,0xffff8800,0x003fffc0, 0x02ffff88,0x02fffd80,0xf88dfff1,0xb8005fff,0x7dc05fff,0x3fa005ff, 0x3ffee3ff,0xff98002f,0x3ff600ff,0x9fffd04f,0x00ffffa8,0x405ffff3, 0x7c43fffe,0xff1003ff,0x0bfffa5f,0x0effff80,0xff980000,0x07fff85f, 0x0bfff700,0x3bfff200,0x44fffb80,0x001ffffb,0x405fffb8,0x2005fffb, 0x3fa3fffe,0xf70006ff,0x7f4c0bff,0xfff506ff,0x27fff41f,0x413fffe0, 0xf80ffff8,0x066543ff,0x3fa5fff1,0x3f6002ff,0x0002efff,0x41fffec0, 0xb0007fff,0x20007fff,0x21effff9,0x640ffffa,0x70005fff,0xfb80bfff, 0x3fa005ff,0x3fffe3ff,0xfff90003,0x3fffee05,0x3fffa07f,0x01ffff53, 0x707fffc8,0x3fe0dfff,0x117ff43f,0x3ffa3fff,0x3fee002f,0x00bfffff, 0x3ae66660,0xff80dfff,0x1cceeeff,0x557fffc0,0x00bceeec,0x37fffff2, 0xe82ffffd,0x70004fff,0xfb80bfff,0x3fa005ff,0xffff33ff,0x3ff60003, 0x7ffec42f,0x3ea07fff,0x7fffb7ff,0x3ffff500,0x209fffb0,0x3fe64fff, 0x47ffe25f,0x4002fffe,0xfffffffd,0xfff801df,0x203fffff,0xffffffff, 0xff883eff,0xffffffff,0x3f203fff,0xffffffff,0x87ffff02,0xfffffff9, 0x80bfff74,0x2005fffb,0xff53fffe,0x3a0001ff,0x3fea1fff,0x0fffffff, 0x3f3fffa0,0xff000fff,0xffff07ff,0xb93ffa03,0x3fe67fff,0x9bfffd0f, 0x07999999,0xfffffff9,0x7fc01bff,0x2cffffff,0xfffffff0,0x987fffff, 0xffffffff,0x03ffffff,0x3fffffee,0xfff880df,0x7fffcc2f,0xfff74fff, 0x5fffb80b,0x4ffffa00,0x0007fffb,0x7e43fffe,0xffe8efff,0x3ffea01f, 0x2003ffff,0x7cc5fffd,0x3ffa07ff,0x47ffffa4,0xffd0fff9,0xffffffff, 0x3ff660df,0x0effffff,0xfffffff0,0x9990bfff,0xffffb999,0x7ffcc5ff, 0xfeccdfff,0xfa80ffff,0xffffffff,0x7fffc41f,0x7ffffcc2,0xbfff74ff, 0x05fffb80,0x5cffffa0,0x0000ffff,0xffd5ffff,0x7fffc9ff,0x7ffff401, 0x3ea000ff,0x3ff20fff,0x53ff604f,0x34fffff8,0x7fff4fff,0xffffffff, 0x7ff5c406,0x9804ffff,0x4ffffeb9,0x3ffee200,0x3fffe64f,0x7ffff703, 0xbdffffa8,0x41ffffff,0x6443ffff,0x74fffdcc,0xfb80bfff,0x3fa005ff, 0xffff53ff,0x3ffa0001,0x42ffffff,0x5c00ffff,0x003fffff,0xd17fffc4, 0x7ec05fff,0xffdff75f,0xfe9ffead,0xeeeeeeff,0x3aa005ee,0x000fffff, 0x007fffec,0x99bfff20,0x3600ffff,0x3fe65fff,0x3ff623ff,0x7fff46ff, 0xa7ffdc03,0x5c05fffb,0x3a005fff,0xfff33fff,0x3f60003f,0x40dfffff, 0xd007fff8,0x2000ffff,0xff14fffe,0x5ffd80ff,0x3fff5ffb,0x7ff4fff5, 0xd800002f,0x4001ffff,0x001ffff8,0x887fffd4,0x2e01ffff,0x3ff66fff, 0xffff904f,0x02fffec3,0x7dd3ffee,0x7fdc05ff,0x3ffa004f,0x7ffff13f, 0x3fff2000,0xfff303ff,0x3fff200d,0xfff70005,0x017ffead,0xdff1dff9, 0x3feafffa,0x00bfffa6,0x3ffea000,0xfff8002f,0x7fd4002f,0x17fffc7f, 0x7cdfff70,0x3fe00fff,0x3fff22ff,0x3ffee00f,0x80dfff54,0x2003fffc, 0x3fe2ffff,0xf90007ff,0x7e403fff,0xff9005ff,0x3e6000bf,0xfffd9fff, 0x577fe403,0x7dff94ff,0x7fff4dff,0xf9800002,0x4c000fff,0x4000ffff, 0x7f46fffc,0x3ff205ff,0x0ffff34f,0x262fffd8,0x2e04ffff,0xfff34fff, 0x2fffd80f,0x3ffff100,0x01ffffec,0x0ffffcc0,0x005ffff0,0x0017fff2, 0xffbfffe8,0x7fdc00ff,0xff31ffce,0x7f4bff9f,0x153002ff,0x0ffffb00, 0x7fffe880,0x7fffd400,0x0ffffdc4,0x897fffcc,0x3e03ffff,0x7fe41fff, 0xfff705ff,0x0ffffe29,0x707fffcc,0x07fffe40,0x09fffff1,0x3ff605c4, 0xdfff906f,0x2fffe400,0xdfff9000,0xf700dfff,0xff8fffff,0x3fa5ffef, 0xff5002ff,0xf955579d,0x5d49ffff,0xfca9999a,0x3263ffff,0xfda9999a, 0xff80efff,0xfb99bfff,0x3fa0efff,0x3661bfff,0xff887fff,0xbabdefff, 0x3f64fffe,0xb989cfff,0x7fc4ffff,0xfffd999c,0xffffc85f,0xfecbcdff, 0x7fffcc0f,0xfffc98ad,0x3ff2002f,0x3e60005f,0x03ffffff,0x4fffffa8, 0x2fffffe4,0x2005fffd,0xfffffffa,0x46ffffff,0xfffffffc,0x545fffff, 0xffffffff,0xf701ffff,0xffffffff,0xffa83fff,0xffffffff,0xff702fff, 0xffffffff,0x7fc49fff,0xffffffff,0x7ffc0eff,0xffffffff,0xffffe880, 0xffffffff,0xfffffd80,0x05ffffff,0x02fffe40,0x3ffffe00,0xffa801ff, 0x7fd42fff,0x3ffa4fff,0xfff5002f,0xffffffff,0xfffc81df,0xffffffff, 0xfffffa84,0x01dfffff,0x7fffffdc,0xf902ffff,0xffffffff,0xfe9807ff, 0xffffffff,0x7ffd44ff,0xefffffff,0xffffff81,0x5c02ffff,0xffffffff, 0xff900fff,0x7fffffff,0xbfff9000,0xfffd8000,0xff5007ff,0x3ffe0fff, 0x3fffa4ff,0xffdb3002,0x3bffffff,0x3fffff20,0x500befff,0xffffffff, 0x7ecc003b,0x00cfffff,0x7ffffecc,0x32000cff,0xfffffffe,0xffc880ad, 0x203fffff,0xffffffda,0xfd93000c,0x059fffff,0xfffffea8,0xff90002d, 0xfa8000bf,0x3004ffff,0x360bffff,0x3fa3ffff,0x988002ff,0x30009aa9, 0x00135533,0x001aa998,0x00135100,0x0026a660,0x066aa200,0x01353100, 0x00099980,0x00099880,0x00001530,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x88355300,0xaaa882aa,0x5554c01a,0x5555540a,0xaaaaaaaa, 0x555530aa,0x55555555,0x2aa25555,0x555402aa,0x80d55542,0x260aaaa9, 0x54001aaa,0x2aa01aaa,0x2aaaa2aa,0x00019aaa,0x01599751,0x20155544, 0x5531aaa9,0x00135555,0x55555555,0x26355555,0x09aaaaaa,0x4ffd8000, 0xff83ffd4,0x7ff406ff,0xffffe86f,0xffffffff,0xffff92ff,0xffffffff, 0x3feadfff,0x3fe00fff,0x3fffe25f,0x5ffffb06,0x0027ffe4,0x540ffff6, 0x3f64ffff,0xffffffff,0xffea802e,0x80cfffff,0x6406fffa,0xfffb4fff, 0x7dffffff,0x3fffffa0,0x4fffffff,0xfffffff7,0x00019dff,0xffb87ffd, 0x7ffff506,0x0bfffee0,0x3ffffffa,0xffffffff,0xffffff92,0xffffffff, 0x3fffeadf,0x97ffe04f,0x80fffff9,0x323fffff,0x6c004fff,0xff883fff, 0x7ffec6ff,0xffffffff,0xfffc880e,0xefffffff,0x037ffd40,0x7ed3fff2, 0xffffffff,0x7ff42fff,0xffffffff,0xffff74ff,0xffffffff,0x3ffe8007, 0xfd02ffe4,0x3ffa0fff,0xffffd06f,0xffffffff,0x3fff25ff,0xffffffff, 0xff56ffff,0x3e01ffff,0x3ffe65ff,0x7ffd43ff,0x3fff23ff,0x7ffec004, 0x1ffffd83,0x7fffffec,0x86ffffff,0xfffffffc,0x544fffff,0x7e406fff, 0xffffb4ff,0xffffffff,0x7ffff43f,0xffffffff,0xffffff74,0xdfffffff, 0x217ffc00,0x3ea04ffd,0x7fdc3fff,0x555501ff,0xff755555,0x26621fff, 0xefffc999,0xf5099999,0x207fffff,0x3fea5fff,0x7fe45fff,0x3ff23fff, 0x7fec004f,0x7fffd43f,0x9bfffd83,0xfffffdb9,0x567ff442,0xfffffa88, 0x01bffea0,0x3f69fff9,0xea999cff,0xfd0effff,0x333337ff,0x3fee1333, 0xfcba99df,0x8803ffff,0x7ff41fff,0x3fffec03,0x0017fffe,0x05ffffb0, 0x80bfff70,0x7ffffffa,0x7d4bfff0,0x3e0fffff,0x324fffff,0x6c004fff, 0x3fe23fff,0xfffb05ff,0x9ffff505,0x3ea03d30,0x3fea1fff,0x7ffe406f, 0x207fffb4,0xfd2ffffc,0x7dc005ff,0xfff504ff,0xfff501ff,0xffffffff, 0x307fffff,0x3ee7ffff,0x20001fff,0x005ffffa,0xa80bfff7,0x2fffffff, 0x3ea5fff8,0xf32ffeef,0x649ffbdf,0x6c004fff,0x3ff23fff,0xfffb00ff, 0x17fffa05,0x1ffffc00,0xc80dfff5,0xfffb4fff,0xa7fff407,0x2002fffe, 0x2a04fffb,0xfa84ffff,0xffffffff,0x3fffffff,0xf1ffff90,0x40009fff, 0x00fffff8,0x80bfff70,0xfffdfffa,0x2e5fff86,0x95ffcdff,0x4bffb7ff, 0x4004fffc,0xff53fffd,0x7fec05ff,0xbfff902f,0x3fffe000,0x01bffea3, 0x3f69fff9,0x3ff603ff,0x05fffd5f,0x027ffdc0,0x2a1bfffa,0xffffffff, 0xffffffff,0xdffff103,0x0001ffff,0x017fffe4,0x80bfff70,0xffebfffa, 0x72fffc2f,0x2fff3bff,0x5ffd9ffe,0x0013fff2,0xfd17fffb,0xffd80bff, 0x9fffd02f,0xffff1000,0x037ffd45,0x7ed3fff2,0x3ff603ff,0x05fffd5f, 0x027ffdc0,0x221fffee,0x99effc99,0x999fffa9,0x3ffff200,0x20004fff, 0x004ffffa,0x202fffdc,0xffabfffa,0x92fffc5f,0x2bffebff,0x4bff96ff, 0x4004fffc,0xffcbfffd,0x7fec00ef,0xffffc82f,0xfffb8001,0x3bffea0f, 0xdaaaaaaa,0xfffb4fff,0x9ffff407,0x999bfffe,0x3ee19999,0x7fd404ff, 0x2ffe407f,0x8801ffea,0x0fffffff,0xffff1000,0xffb8001d,0x7ffd405f, 0x7c3ffff3,0x57ff25ff,0x94ffeffd,0x7ffe4dff,0x7ffec004,0x801ffffd, 0xdccdfffd,0x003fffff,0x44fffe88,0xfffffffa,0xffffffff,0x207fffb4, 0xfd2ffffa,0xffffffff,0x3fee1fff,0x7ffcc04f,0x13ff601f,0xc800fff5, 0x004fffff,0x07ffff20,0x17ffee00,0x2e7fff50,0x3ffe5fff,0x7d57ff25, 0xff91ffff,0x027ffe4d,0x3fffff60,0xffb006ff,0xffffffff,0x3f60005d, 0x7fd40fff,0xffffffff,0xfb4fffff,0xfff507ff,0x7ffff4df,0xffffffff, 0x809fff70,0x201ffff9,0x7fdc3ffe,0x7fff4006,0xf50006ff,0x20009fff, 0x5405fffb,0xfff13fff,0xd97ffe1f,0xffff14ff,0xf93ffe4d,0xfd8009ff, 0x3ffffdff,0xfffffd80,0x0003ffff,0x20ffffee,0xfffffffa,0xffffffff, 0x99dfffb4,0x3fffffdb,0x7ffffff4,0x70ffffff,0xf9809fff,0x3fa01fff, 0x02ffe43f,0xffffff70,0xff88009f,0x2e0006ff,0x7d405fff,0x3fff23ff, 0x7ecbfff4,0x93fffa4f,0x3ff27ffb,0x7fec004f,0x0ffffdbf,0x777ffec0, 0x003fffff,0x04ffffb8,0x333dfff5,0xfff93333,0x3fffff69,0x3fffffff, 0x4cdffff4,0x2e199999,0x7d404fff,0x7ffcc7ff,0xffffffff,0x204fffff, 0xfffffff8,0x3f2000ff,0x20001fff,0x5405fffb,0x3fe23fff,0x25fff8ff, 0x3fee4ffe,0xc9ffee1f,0x6c004fff,0xfff8bfff,0x7ffec05f,0x3ffffb12, 0x7fffd400,0x1bffea05,0x369fff90,0xffffffff,0xffe80dff,0x3fee002f, 0x7ffdc04f,0x7ffffcc7,0xffffffff,0x3f204fff,0xffff9fff,0xffff5005, 0xffb80009,0x7ffd405f,0x7dfffec3,0x93ffa5ff,0x7fdc7ff9,0x09fff90f, 0x73fffd80,0x6c07ffff,0x3fa22fff,0xff5006ff,0xffa80bff,0x7ffe406f, 0xdddfffb4,0x7f40359b,0x3ee002ff,0x7fec04ff,0x7fffcc5f,0xffffffff, 0xf304ffff,0x3ff29fff,0x7f4401ff,0xb80006ff,0x7d405fff,0x7ffcc3ff, 0x3fa5fffe,0x2e0d543f,0xfff90fff,0xfffd8009,0x03ffffa3,0x2a17ffec, 0x5401ffff,0xa805ffff,0x7e406fff,0x7fffb4ff,0x5fffd000,0x27ffdc00, 0x07ffff30,0x33fff733,0x337fff33,0x3ffff601,0x0dffff10,0x01ffffc8, 0x5fffb800,0x41fffd40,0x5ffffffe,0x5400fffe,0xfff90fff,0xfffd8009, 0x1bfffe63,0x7417ffec,0x3ea05fff,0xf5004fff,0xffc80dff,0x07fffb4f, 0x05fffd00,0x027ffdc0,0x401ffffb,0x7fc46ffa,0x7ffd401f,0x7fffe43f, 0x7ffff503,0x3fee0000,0x7ffd405f,0xfffffa83,0x00fffe5f,0xfc8fffd4, 0x7ec004ff,0x7ffe43ff,0x2fffd83f,0x81ffffb8,0x004ffffa,0x901bffea, 0x3ff69fff,0xffe8003f,0x3fee002f,0xfffe884f,0x37fdc03f,0xd003ffe6, 0xf881ffff,0x7440ffff,0xeeeeffff,0x02eeeeee,0x202fffdc,0xff03fffa, 0x7fcbffff,0xfff5003f,0x33bfff23,0x4ccccccc,0xf10ffff6,0xfd83ffff, 0xfff882ff,0x7fffd45f,0xeeeeeeef,0xdfff51ee,0xb4fffc80,0xd0007fff, 0x9999bfff,0x3ee59999,0xfedcceff,0xc806ffff,0x3ffd45ff,0x0ffffee0, 0x227fffe4,0xfffffff9,0xffffffff,0x2fffdc03,0x40fffea0,0x15fffffb, 0x2a005fff,0xfff92fff,0xffffffff,0x1fffecff,0x237fffd4,0xf902fffd, 0x7fec3fff,0xffffffff,0xff52ffff,0xfffc80df,0x007fffb4,0xffffffd0, 0x29ffffff,0xfffffffb,0x00dfffff,0x7dc4ffd8,0x3ffe206f,0x3ffe207f, 0x3ffe61ff,0xffffffff,0x5c03ffff,0x7d405fff,0xfff103ff,0x3ffe2bff, 0x5fff5002,0x3ffffff2,0x27ffffff,0xfb03fffd,0x7fec9fff,0xffff302f, 0x7ffffec9,0xffffffff,0x0dfff52f,0xfb4fffc8,0xfd0007ff,0xffffffff, 0x3fee9fff,0xffffffff,0x3ffa002f,0x9037fdc3,0xb807ffff,0x3e65ffff, 0xffffffff,0x03ffffff,0x202fffdc,0x3203fffa,0xff35ffff,0x3fe6005f, 0xfffff92f,0xffffffff,0x881fffec,0xfb1fffff,0x7fec05ff,0xffffb0ff, 0xffffffff,0x3ffea5ff,0xa7ffe406,0x8003fffd,0xfffffffe,0xf74fffff, 0x79dfffff,0x00000015,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x55544000,0xaaaaaaaa,0xaa8801aa, 0x2aaaa01a,0x0009aaaa,0x35555510,0x2aa60000,0x555102aa,0x55555555, 0x4c015555,0x000accca,0x00000000,0x4de6dd44,0x32ea2000,0x800abccd, 0x801bccb9,0x5554c2b9,0x05555101,0xabccba88,0x7ffffdc0,0xffffffff, 0x3fff2204,0x3fff604f,0xdfffffff,0x3fff2001,0x880006ff,0x80ffffff, 0xfffffff8,0xffffffff,0xffffe982,0x80004fff,0x0009705a,0xffffff90, 0xfc8805ff,0xffffffff,0x3fffe602,0xf901efff,0x7ffe4dff,0x0dfff303, 0x3fffffa6,0x3fee2fff,0xffffffff,0xfc884fff,0x204fffff,0xfffffffd, 0x003fffff,0x1ffffffd,0xfffd8000,0xff880fff,0xffffffff,0x5c2fffff, 0xffffffff,0x70000eff,0x5ffb8bff,0xfffd3000,0xbfffffff,0x3ffffa20, 0x02ffffff,0xfffffff7,0xff987fff,0xfff93fff,0x1bffe607,0x3ffffff2, 0x3ee2ffff,0xffffffff,0x2e24ffff,0xffffffff,0x3ffff604,0xffffffff, 0x7ffc402f,0x0002ffff,0x3fffffea,0xffff880f,0xffffffff,0x3fe62fff, 0xfffeffff,0xfd8005ff,0xfff54fff,0xfe8001df,0xffffffff,0xffe82fff, 0xdcaabdff,0xffffa82f,0xffffebbe,0x3ffffea1,0x207fff94,0x7e46fff9, 0xffffffff,0x7fdc02ff,0x7fff405f,0x04ffffff,0x930bfff6,0xb80bffff, 0x4fffffff,0x3fffa000,0xc880ffff,0xcccccccc,0x11ffffec,0x443dffff, 0x001ffffd,0x1dffffb1,0x0f7fffe4,0xcffffb80,0x1bfffea0,0x807ffff1, 0x82fffe80,0x3e65fffd,0xff93ffff,0x3ffe607f,0x3ffffe66,0x00b6a60b, 0xb80bfff7,0xffdaefff,0x3fff604f,0x0ffff902,0xffcfffd8,0xff90007f, 0x01fffd9f,0x5fffe800,0x403fffea,0x9805fffe,0x705ffffe,0x805fffff, 0x304ffff8,0x7cc7ffff,0x5c001fff,0xff106fff,0x7ffec1ff,0x40ffff26, 0x3fa6fff9,0x40000fff,0x4405fffb,0x3fff63ff,0x0bfff604,0x203fffd4, 0xfff8ffff,0x7fcc001f,0x01fffd6f,0x7fffd400,0x817ffee1,0x4c07fffb, 0x403fffff,0x03fffffa,0x803fffea,0x3e24fffd,0x2002efff,0x3a02fffd, 0x1e541fff,0x4c0ffff2,0xfff36fff,0xf700007f,0x81500bff,0x3604fffd, 0xff702fff,0x7ffd40df,0x009fffb5,0xfd2fffd8,0x740001ff,0x7fec5fff, 0x3ffe204f,0xffff700f,0x3fa6005f,0xff704fff,0xfffb80bf,0x7fffff45, 0x7ff401ce,0xcccccccf,0x9002fffe,0x3e607fff,0xffff56ff,0x3fee0000, 0xffb0005f,0x7ffec09f,0x07fffd02,0xfb97ffe4,0x3ea006ff,0x3fffa5ff, 0xfff30000,0x6fffc85f,0x07fffe20,0x07bffff2,0xffffb100,0x4fffc81b, 0x237ffd40,0xfffffff9,0xfff80bef,0xffffffff,0x9003ffff,0x3e607fff, 0xdfff76ff,0x3fee0000,0xffb0005f,0x7ffec09f,0x3fffaa62,0x3fffa00e, 0x01ffff30,0x41ffff10,0x0000fffe,0xf70dfffb,0x7fc03fff,0x3ff622ff, 0x20000dff,0x20effffc,0x5404fffd,0xfe887fff,0xefffffff,0x3ffffe61, 0xffffffff,0xff9003ff,0x3ffe607f,0x00bfffb6,0x17ffee00,0x27ffec00, 0xffffffb0,0x01bfffff,0x3e37ffcc,0xfc803fff,0x7fff43ff,0xfff98000, 0xffff982f,0x3ff660ae,0x3fffa2ff,0xf900005f,0x3f23ffff,0x7fdc05ff, 0x3fae606f,0x10ffffff,0x5555ffff,0x15555555,0x0ffff200,0xfcb7ffcc, 0x700007ff,0x2000bfff,0x3604fffd,0xffffffff,0x2e01cfff,0x7fe44fff, 0x7ffcc05f,0x00fffe86,0x06fffd80,0x3ffffffa,0xfffffffe,0x3ffffea2, 0x7fcc0003,0x3fee3fff,0x7ffe406f,0xfff93004,0x7fffc7ff,0xfc800000, 0xfff503ff,0x03fffead,0x3ffee000,0xfffb0005,0x7fffec09,0xffffffff, 0x3fffb02f,0x407fffa8,0xfe81fffe,0x7cc000ff,0x3e202fff,0xffffffff, 0x4c1fffff,0x004ffffe,0x5fffff50,0x01ffffa8,0x000ffffe,0x749ffff3, 0x20002fff,0x3ff20cdb,0xffff884f,0x09ffff36,0xbfff7000,0x3fff6000, 0x2ffff604,0xfffc9999,0x7ffc40ff,0x2ffff887,0x209fff70,0x4000fffe, 0x8806fffd,0xfffffffc,0x880ffffd,0x00dffffe,0x3fffff20,0x5ffff881, 0x01ffff90,0x47ffff00,0x000ffffc,0x70ffffd8,0xfe88dfff,0x3ffe6fff, 0x002203ff,0x000bfff7,0xd813fff6,0xff502fff,0xfffa89ff,0x09fffd05, 0x333ffff1,0x3fffd333,0xff980133,0x2a2003ff,0xff98abcb,0x3ff600ff, 0xfd800eff,0x2e00efff,0xa9beffff,0x543ffffd,0xffc881be,0x3ffe21ff, 0x5d440bff,0x3ffffe62,0x3bffff53,0xdffffff7,0x77ffffd4,0x02fdbaac, 0x002fffdc,0x204fffd8,0x3a02fffd,0x7fe46fff,0xfeeeeeff,0xffa86fff, 0xffffffff,0x3fffffff,0x03fffec0,0xdfff7000,0xfffff700,0x3fffa205, 0xfffd005f,0xffffffff,0xfffff50d,0xdffffffd,0xffffff50,0x49ffffff, 0x24fffffa,0xffffffff,0x6c6ffeff,0xffffffff,0x7dc02fff,0xfb0005ff, 0x7fec09ff,0x3fff202f,0x7fffffc6,0xffffffff,0x7fffd41f,0xffffffff, 0x203fffff,0x003ffff8,0x0ffff600,0x7ffffd40,0x7ffffcc3,0x3ffa6004, 0xdfffffff,0xfffffa80,0x0effffff,0xffffff70,0x449fffff,0x2a2fffff, 0xffffffff,0x6446ffd9,0xffffffff,0x7fdc02ff,0xffb0005f,0x7ffec09f, 0x93fffa02,0xfffffff9,0xffffffff,0x7ffffd43,0xffffffff,0x3203ffff, 0x00007fff,0x003fffee,0x4fffff98,0x05fffff5,0x3fffae00,0x3a602eff, 0xffffffff,0x7ec400be,0xdfffffff,0x42fffdc2,0x0dfffffa,0x3660dffb, 0xcefffffe,0x2fffdc00,0x4fffd800,0x40bfff60,0x2e3ffffc,0xccccdfff, 0x5fffeccc,0x55555544,0xffffaaaa,0xff101aab,0x100007ff,0x009ffff9, 0x23fffd10,0x001fffe8,0x001a9880,0x09aaa998,0x35531000,0x401a8801, 0x800009a9,0x55100999,0x5dfffb55,0x77543555,0xeffffeee,0xffb2eeee, 0xfd97559f,0x7f41ffff,0x7fdc01ff,0xff0000ff,0xff9001ff,0x326001ff, 0xfffeeccc,0x6c0006ff,0x0077441f,0x00000000,0x00000000,0x00000000, 0xffffffb8,0x4fffffff,0x3fffffea,0xffffffff,0xffffffb3,0x3fffffff, 0x403fffc4,0x002ffff8,0x801ffff0,0x004ffff8,0x3fffffee,0x000effff, 0x00110080,0x00000000,0x00000000,0x00000000,0x7fffffdc,0x4fffffff, 0x3fffffea,0xffffffff,0xffffffb3,0x85dfffff,0xd004fffa,0x20009fff, 0x6400ffff,0x2000ffff,0xfffffffb,0x000003ff,0x00000000,0x00000000, 0x00000000,0xfffb8000,0xffffffff,0x3ffea4ff,0xffffffff,0xfffb3fff, 0x39bdffff,0x00bfff60,0x003fffe4,0x200ffff8,0x004ffff8,0x6f7fffdc, 0x0000009b,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x654c0000,0xa80abcdc,0x372e22aa,0x2e2aa82b,0x2f2e20bc,0x2a1554c0, 0xaa982cdc,0x5553002a,0x2ccc8805,0x55555440,0xaaaaaaaa,0x00aaaaa1, 0x2a155551,0x54c002aa,0x0999802a,0x00054c00,0xa9801555,0xaaaaaaaa, 0x2662aaaa,0x26666099,0x06666620,0xfffff900,0xf89fffff,0xffff76ff, 0x8fff89ff,0xe88ffffd,0x3f21ffff,0xffffd37f,0x7ffcc1df,0xfffe802f, 0x27ffcc04,0x3ffffe60,0xffffffff,0x13fffee4,0x365fffe8,0x36001fff, 0x7fc407ff,0x3ff2002f,0xfffc802f,0x7fffec04,0xffffffff,0x5ffff17f, 0x70bfffe2,0x400bffff,0xfffffffd,0x3fe4ffff,0xfffffbff,0x3ffe4fff, 0xdbfffffc,0x325fffff,0xffffafff,0x7f46ffff,0x7fcc05ff,0x7fcc00ff, 0x7ffcc04f,0xffffffff,0x7ffec4ff,0xffffb81f,0x00bfff20,0xf806ffe8, 0xff3001ff,0x7c401fff,0x3601ffff,0xffffffff,0x3e7fffff,0x3ffe1fff, 0xffff981f,0x9bffb005,0xfffff957,0x3fffffe3,0xfffffeff,0xddfffff0, 0xffbfffff,0x7fffe4ff,0xffffffff,0x3fffee2f,0x17fff200,0x013ffe60, 0xfffffff3,0x87ffffff,0x4c6ffff8,0x7dc2ffff,0x3fe003ff,0x3fe24c5f, 0x7dc0ea0f,0x3604ffff,0x206fffff,0xfffffffd,0x27ffffff,0x3fe0ffff, 0xffb101ff,0x403700bf,0xff4fffe8,0x2219ffff,0xfff3ffff,0x3fffe6bf, 0x321fff73,0x31dfffff,0x7c49fffd,0x3fe03fff,0xff9802ff,0x9999804f, 0xffffa999,0x9ffff506,0x542ffff4,0xf1004fff,0x1efd87ff,0xffb11ffd, 0xfffff301,0x27ffea0b,0x00003fff,0xe83fffa0,0x7e400fff,0xb80005ff, 0xffff5fff,0x9fff909f,0x7c47fffe,0x3ffea7ff,0x0dffff91,0xfc8bfff9, 0xfff506ff,0x3ffe600f,0x3fa20004,0x3f200fff,0xfffb9fff,0x5fff880f, 0xff30e664,0x7fffd45f,0xffe9ffdb,0xffff904f,0x5cbffa0d,0x00000fff, 0xfe8fffd0,0x5553007f,0xffa80003,0x0bffff6f,0x7fd3ffee,0x8fffe25f, 0xff91fffa,0xfff501df,0x0ffff98d,0x004fffd8,0x0009fff3,0x00ffffec, 0x7ffffff4,0x3ffe02ff,0x993ffe66,0x3f221fff,0xffffffff,0x3fa01dff, 0x6ffb84ff,0x00027ff4,0x6c7ffd80,0x000007ff,0x6e665544,0xffff6fff, 0x46aaa205,0x3fe24fff,0x47ffea2f,0xf303fffc,0xfffd0dff,0x1ffff887, 0x7fffffe4,0xffffffff,0x7ffdc07f,0xfff3003f,0xe809ffff,0x3fff27ff, 0x203ffea7,0xffffffb8,0xffc800cf,0x0fffc43f,0x9707ffea,0x99999999, 0x7ec99999,0x03ffec7f,0xffd98000,0xffffffff,0x005ffff6,0x3e24fff8, 0x3ffea2ff,0x207fff91,0xfb86fff9,0x7ffd46ff,0xfffffc86,0xffffffff, 0x3fe607ff,0x7dc005ff,0xd806ffff,0xfffd0fff,0x81ffee5f,0xdfffffb8, 0x1fffd000,0xfd05ffd8,0xffffd8df,0xffffffff,0x91bff27f,0x00000dff, 0xfffffff7,0x3edfffff,0x7c002fff,0x3ffe24ff,0x647ffea2,0xff303fff, 0xffff10df,0x41fffec3,0xfffffffc,0xffffffff,0xdffff107,0xfff88001, 0xffc804ff,0xfffff99f,0x910dff95,0xffffffff,0x3f2203bf,0x7ffcc3ff, 0x47fff301,0xfffffffd,0x27ffffff,0x554c2aa9,0x7d400002,0xaaabefff, 0xfff6fffc,0xfff8005f,0xa8bffe24,0xfff91fff,0x1bffe607,0xf8a7ffec, 0xaa980fff,0xdfffcaaa,0xd02aaaaa,0x0003ffff,0x5ffffffd,0xcafffb80, 0xd8ffffff,0x7ffd45ff,0xffdffeef,0xffdd54ff,0x9ffd0bff,0x70fffd80, 0x99999999,0x00999999,0xfb000000,0x3fea0bff,0x05ffff6f,0x224fff80, 0x3fea2fff,0x07fff91f,0x4c1bffe6,0xfff77fff,0xfff98009,0x3fff2004, 0xffc8003f,0x00ffffff,0x3fafffea,0xfeafffbf,0xa7ffc44f,0x5fff77fd, 0x0bbfffea,0x10033326,0x00005999,0x20000cc0,0x3ffe0098,0xdfff502f, 0x000bfffe,0x7fc49fff,0x47ffea2f,0xf303fffc,0x7ff40dff,0x01fffeaf, 0x027ffcc0,0x04ffffa8,0xbffffa80,0x2205ffff,0xd7ffdfff,0x07fffbff, 0x87ff45f7,0x337aa5e9,0x00000002,0x7ffe4000,0x8266604f,0xff04fffb, 0xfff507ff,0x0bfffedf,0x449fff00,0x3fea2fff,0x07fff91f,0xb81bffe6, 0x6fffefff,0x4fff9800,0x6ffff880,0xffff8800,0x07ffff74,0xaffffffc, 0x1ffffffb,0x41fff810,0x00000000,0xffd00000,0x881dffff,0xfff52fff, 0xfffd07ff,0x3ffee23d,0x5ffff6ff,0x24fff800,0x3ea2fff8,0x7fff91ff, 0x81bffe60,0xfffffff8,0xfff98003,0x7fff4404,0xccccccdf,0xefffd82c, 0x07ffffa0,0x97fffff4,0x0ffffff8,0x003fff00,0x00000000,0xffff5000, 0x541dffff,0xfff91fff,0xfff90bff,0xffffffff,0x3fffedff,0x27ffc002, 0x7d45fff1,0x7fff91ff,0x01bffe60,0x1ffffffb,0x9fff3000,0xfffffb80, 0xffffffff,0x17fffe45,0x41bfffe2,0x20fffffd,0x007ffffe,0x00007332, 0x00000000,0x2effffa0,0xd9afffff,0xfff90fff,0xfff10bff,0xd5ffffff, 0x3fffedff,0x27ffc002,0x7d45fff1,0x7fff91ff,0x01bffe60,0x0bfffff5, 0x13ffe600,0xffffff70,0xbfffffff,0x827fffcc,0xc84ffffb,0x7dc5ffff, 0x00006fff,0x00000000,0x3ffe0000,0x3ffffa24,0x3ea5ffff,0xb103ffff, 0x21bfffff,0xffff6ffd,0x4fff8005,0xfa8bffe2,0x7fff91ff,0x01bffe60, 0x007ffffa,0x7fdc0000,0xffffffff,0xfff15fff,0xfffd80df,0x7fffdc2f, 0x2ffffc42,0x00000000,0x80000000,0x7443fff8,0x1fffffff,0x402fffe4, 0x00009a98,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x80999800,0x1fffffc8,0x00001510,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00003751, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000, }; static signed short stb__consolas_bold_35_usascii_x[95]={ 0,6,3,0,1,0,0,7,4,3,2,1,3,4, 6,1,0,1,2,2,0,2,1,1,1,1,6,3,1,2,3,4,0,0,2,1,1,3,3,0,1,2,2,2, 3,0,1,0,2,0,2,1,1,1,0,0,0,0,1,5,2,4,1,0,0,1,2,2,1,1,0,1,2,2, 2,2,2,1,2,1,2,1,3,2,1,2,0,0,0,0,2,2,7,3,0, }; static signed short stb__consolas_bold_35_usascii_y[95]={ 25,0,0,2,-1,0,0,0,-1,-1,0,7,18,13, 18,0,2,2,2,2,2,2,2,2,2,2,7,7,5,10,5,0,0,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,0,2,28,0,7,0,7,0,7,0,7,0,0, 0,0,0,7,7,7,7,7,7,7,2,7,7,7,7,7,7,0,-3,0,11, }; static unsigned short stb__consolas_bold_35_usascii_w[95]={ 0,7,13,19,17,20,20,5,12,12,15,17,10,11, 7,17,19,17,16,16,19,16,17,17,17,17,7,11,15,15,15,13,20,20,16,17,18,14,14,18,17,15,14,17, 15,19,17,19,16,20,17,17,17,17,20,19,20,20,17,10,17,10,17,20,12,16,16,15,16,17,18,18,15,16, 14,17,16,18,15,18,16,16,15,15,16,15,19,20,19,19,15,14,5,14,19, }; static unsigned short stb__consolas_bold_35_usascii_h[95]={ 0,26,10,23,31,26,26,10,34,34,16,18,14,5, 8,29,24,23,23,24,23,24,24,23,24,23,19,25,21,11,21,26,33,23,23,24,23,23,23,24,23,23,24,23, 23,23,23,24,23,30,23,24,23,24,23,23,23,23,23,32,29,32,12,5,8,19,26,19,26,19,25,26,25,25, 33,25,25,18,18,19,25,25,18,19,24,19,18,18,18,26,18,32,36,32,9, }; static unsigned short stb__consolas_bold_35_usascii_s[95]={ 250,76,225,1,121,36,15,250,20,7,164, 89,180,217,245,160,159,17,168,19,73,36,53,93,71,111,214,153,129,209,145, 1,48,52,35,141,235,220,241,89,185,1,126,132,116,96,78,234,203,139,150, 1,60,108,200,221,21,179,42,95,178,84,191,196,239,1,233,238,216,196,134, 57,101,84,33,165,117,34,53,161,200,183,18,180,217,222,69,143,123,196,107, 69,1,106,225, }; static unsigned short stb__consolas_bold_35_usascii_t[95]={ 12,38,138,90,1,38,38,1,1,1,138, 138,138,28,149,1,65,114,90,65,114,65,65,114,65,114,114,38,114,138,114, 38,1,114,114,65,90,90,65,65,90,114,65,90,90,90,90,38,90,1,90, 65,90,65,65,65,90,65,90,1,1,1,138,28,138,138,1,114,1,114,38, 38,38,38,1,38,38,138,138,114,38,38,138,114,38,114,138,138,138,1,138, 1,1,1,149, }; static unsigned short stb__consolas_bold_35_usascii_a[95]={ 308,308,308,308,308,308,308,308, 308,308,308,308,308,308,308,308,308,308,308,308,308,308,308,308, 308,308,308,308,308,308,308,308,308,308,308,308,308,308,308,308, 308,308,308,308,308,308,308,308,308,308,308,308,308,308,308,308, 308,308,308,308,308,308,308,308,308,308,308,308,308,308,308,308, 308,308,308,308,308,308,308,308,308,308,308,308,308,308,308,308, 308,308,308,308,308,308,308, }; // Call this function with // font: NULL or array length // data: NULL or specified size // height: STB_FONT_consolas_bold_35_usascii_BITMAP_HEIGHT or STB_FONT_consolas_bold_35_usascii_BITMAP_HEIGHT_POW2 // return value: spacing between lines static void stb_font_consolas_bold_35_usascii(stb_fontchar font[STB_FONT_consolas_bold_35_usascii_NUM_CHARS], unsigned char data[STB_FONT_consolas_bold_35_usascii_BITMAP_HEIGHT][STB_FONT_consolas_bold_35_usascii_BITMAP_WIDTH], int height) { int i,j; if (data != 0) { unsigned int *bits = stb__consolas_bold_35_usascii_pixels; unsigned int bitpack = *bits++, numbits = 32; for (i=0; i < STB_FONT_consolas_bold_35_usascii_BITMAP_WIDTH*height; ++i) data[0][i] = 0; // zero entire bitmap for (j=1; j < STB_FONT_consolas_bold_35_usascii_BITMAP_HEIGHT-1; ++j) { for (i=1; i < STB_FONT_consolas_bold_35_usascii_BITMAP_WIDTH-1; ++i) { unsigned int value; if (numbits==0) bitpack = *bits++, numbits=32; value = bitpack & 1; bitpack >>= 1, --numbits; if (value) { if (numbits < 3) bitpack = *bits++, numbits = 32; data[j][i] = (bitpack & 7) * 0x20 + 0x1f; bitpack >>= 3, numbits -= 3; } else { data[j][i] = 0; } } } } // build font description if (font != 0) { float recip_width = 1.0f / STB_FONT_consolas_bold_35_usascii_BITMAP_WIDTH; float recip_height = 1.0f / height; for (i=0; i < STB_FONT_consolas_bold_35_usascii_NUM_CHARS; ++i) { // pad characters so they bilerp from empty space around each character font[i].s0 = (stb__consolas_bold_35_usascii_s[i]) * recip_width; font[i].t0 = (stb__consolas_bold_35_usascii_t[i]) * recip_height; font[i].s1 = (stb__consolas_bold_35_usascii_s[i] + stb__consolas_bold_35_usascii_w[i]) * recip_width; font[i].t1 = (stb__consolas_bold_35_usascii_t[i] + stb__consolas_bold_35_usascii_h[i]) * recip_height; font[i].x0 = stb__consolas_bold_35_usascii_x[i]; font[i].y0 = stb__consolas_bold_35_usascii_y[i]; font[i].x1 = stb__consolas_bold_35_usascii_x[i] + stb__consolas_bold_35_usascii_w[i]; font[i].y1 = stb__consolas_bold_35_usascii_y[i] + stb__consolas_bold_35_usascii_h[i]; font[i].advance_int = (stb__consolas_bold_35_usascii_a[i]+8)>>4; font[i].s0f = (stb__consolas_bold_35_usascii_s[i] - 0.5f) * recip_width; font[i].t0f = (stb__consolas_bold_35_usascii_t[i] - 0.5f) * recip_height; font[i].s1f = (stb__consolas_bold_35_usascii_s[i] + stb__consolas_bold_35_usascii_w[i] + 0.5f) * recip_width; font[i].t1f = (stb__consolas_bold_35_usascii_t[i] + stb__consolas_bold_35_usascii_h[i] + 0.5f) * recip_height; font[i].x0f = stb__consolas_bold_35_usascii_x[i] - 0.5f; font[i].y0f = stb__consolas_bold_35_usascii_y[i] - 0.5f; font[i].x1f = stb__consolas_bold_35_usascii_x[i] + stb__consolas_bold_35_usascii_w[i] + 0.5f; font[i].y1f = stb__consolas_bold_35_usascii_y[i] + stb__consolas_bold_35_usascii_h[i] + 0.5f; font[i].advance = stb__consolas_bold_35_usascii_a[i]/16.0f; } } } #ifndef STB_SOMEFONT_CREATE #define STB_SOMEFONT_CREATE stb_font_consolas_bold_35_usascii #define STB_SOMEFONT_BITMAP_WIDTH STB_FONT_consolas_bold_35_usascii_BITMAP_WIDTH #define STB_SOMEFONT_BITMAP_HEIGHT STB_FONT_consolas_bold_35_usascii_BITMAP_HEIGHT #define STB_SOMEFONT_BITMAP_HEIGHT_POW2 STB_FONT_consolas_bold_35_usascii_BITMAP_HEIGHT_POW2 #define STB_SOMEFONT_FIRST_CHAR STB_FONT_consolas_bold_35_usascii_FIRST_CHAR #define STB_SOMEFONT_NUM_CHARS STB_FONT_consolas_bold_35_usascii_NUM_CHARS #define STB_SOMEFONT_LINE_SPACING STB_FONT_consolas_bold_35_usascii_LINE_SPACING #endif
66.660589
133
0.797913
stetre
dc7c7aad5a84b37e159d8e5fcb8c8879c09905b7
13,988
hpp
C++
libs/ml/include/ml/dataloaders/tensor_dataloader.hpp
devjsc/ledger
5681480faf6e2aeee577f149c17745d6ab4d4ab3
[ "Apache-2.0" ]
null
null
null
libs/ml/include/ml/dataloaders/tensor_dataloader.hpp
devjsc/ledger
5681480faf6e2aeee577f149c17745d6ab4d4ab3
[ "Apache-2.0" ]
null
null
null
libs/ml/include/ml/dataloaders/tensor_dataloader.hpp
devjsc/ledger
5681480faf6e2aeee577f149c17745d6ab4d4ab3
[ "Apache-2.0" ]
null
null
null
#pragma once //------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // 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 "core/random.hpp" #include "core/serializers/group_definitions.hpp" #include "ml/dataloaders/dataloader.hpp" #include "ml/exceptions/exceptions.hpp" #include "ml/meta/ml_type_traits.hpp" #include <stdexcept> #include <utility> namespace fetch { namespace ml { namespace dataloaders { template <typename LabelType, typename InputType> class TensorDataLoader : public DataLoader<LabelType, InputType> { using TensorType = InputType; using DataType = typename TensorType::Type; using SizeType = fetch::math::SizeType; using SizeVector = fetch::math::SizeVector; using ReturnType = std::pair<LabelType, std::vector<TensorType>>; using IteratorType = typename TensorType::IteratorType; public: TensorDataLoader() = default; TensorDataLoader(SizeVector label_shape, std::vector<SizeVector> data_shapes); ~TensorDataLoader() override = default; ReturnType GetNext() override; bool AddData(std::vector<InputType> const &data, LabelType const &labels) override; SizeType Size() const override; bool IsDone() const override; void Reset() override; bool IsModeAvailable(DataLoaderMode mode) override; void SetTestRatio(float new_test_ratio) override; void SetValidationRatio(float new_validation_ratio) override; template <typename X, typename D> friend struct fetch::serializers::MapSerializer; LoaderType LoaderCode() override { return LoaderType::TENSOR; } protected: std::shared_ptr<SizeType> train_cursor_ = std::make_shared<SizeType>(0); std::shared_ptr<SizeType> test_cursor_ = std::make_shared<SizeType>(0); std::shared_ptr<SizeType> validation_cursor_ = std::make_shared<SizeType>(0); SizeType test_offset_ = 0; SizeType validation_offset_ = 0; SizeType n_samples_ = 0; // number of all samples SizeType n_test_samples_ = 0; // number of test samples SizeType n_validation_samples_ = 0; // number of validation samples SizeType n_train_samples_ = 0; // number of train samples std::vector<TensorType> data_; TensorType labels_; SizeVector label_shape_; SizeVector one_sample_label_shape_; std::vector<SizeVector> data_shapes_; std::vector<SizeVector> one_sample_data_shapes_; float test_to_train_ratio_ = 0.0; float validation_to_train_ratio_ = 0.0; SizeType batch_label_dim_ = fetch::math::numeric_max<SizeType>(); SizeType batch_data_dim_ = fetch::math::numeric_max<SizeType>(); random::Random rand; SizeType count_ = 0; void UpdateRanges(); void UpdateCursor() override; }; template <typename LabelType, typename InputType> TensorDataLoader<LabelType, InputType>::TensorDataLoader(SizeVector label_shape, std::vector<SizeVector> data_shapes) : DataLoader<LabelType, TensorType>() , label_shape_(std::move(label_shape)) , data_shapes_(std::move(data_shapes)) { UpdateCursor(); } template <typename LabelType, typename InputType> typename TensorDataLoader<LabelType, InputType>::ReturnType TensorDataLoader<LabelType, InputType>::GetNext() { std::vector<InputType> ret_data; LabelType ret_labels = labels_.View(*this->current_cursor_).Copy(one_sample_label_shape_); for (SizeType i{0}; i < data_.size(); i++) { ret_data.emplace_back( data_.at(i).View(*this->current_cursor_).Copy(one_sample_data_shapes_.at(i))); } if (this->random_mode_) { *this->current_cursor_ = this->current_min_ + (static_cast<SizeType>(decltype(rand)::generator()) % this->current_size_); ++count_; } else { (*this->current_cursor_)++; } return ReturnType(ret_labels, ret_data); } template <typename LabelType, typename InputType> bool TensorDataLoader<LabelType, InputType>::AddData(std::vector<InputType> const &data, LabelType const & labels) { one_sample_label_shape_ = labels.shape(); one_sample_label_shape_.at(one_sample_label_shape_.size() - 1) = 1; labels_ = labels.Copy(); // Resize data vector if (data_.size() < data.size()) { data_.resize(data.size()); one_sample_data_shapes_.resize(data.size()); } // Add data to data vector for (SizeType i{0}; i < data.size(); i++) { data_.at(i) = data.at(i).Copy(); one_sample_data_shapes_.at(i) = data.at(i).shape(); one_sample_data_shapes_.at(i).at(one_sample_data_shapes_.at(i).size() - 1) = 1; } n_samples_ = data_.at(0).shape().at(data_.at(0).shape().size() - 1); UpdateRanges(); return true; } template <typename LabelType, typename InputType> typename TensorDataLoader<LabelType, InputType>::SizeType TensorDataLoader<LabelType, InputType>::Size() const { return this->current_size_; } template <typename LabelType, typename InputType> bool TensorDataLoader<LabelType, InputType>::IsDone() const { if (this->random_mode_) { return (count_ > (this->current_max_ - this->current_min_)); } return *(this->current_cursor_) >= this->current_max_; } template <typename LabelType, typename InputType> void TensorDataLoader<LabelType, InputType>::Reset() { count_ = 0; *(this->current_cursor_) = this->current_min_; } template <typename LabelType, typename InputType> void TensorDataLoader<LabelType, InputType>::SetTestRatio(float new_test_ratio) { test_to_train_ratio_ = new_test_ratio; UpdateRanges(); } template <typename LabelType, typename InputType> void TensorDataLoader<LabelType, InputType>::SetValidationRatio(float new_validation_ratio) { validation_to_train_ratio_ = new_validation_ratio; UpdateRanges(); } template <typename LabelType, typename InputType> void TensorDataLoader<LabelType, InputType>::UpdateRanges() { float test_percentage = 1.0f - test_to_train_ratio_ - validation_to_train_ratio_; float validation_percentage = test_percentage + test_to_train_ratio_; // Define where test set starts test_offset_ = static_cast<uint32_t>(test_percentage * static_cast<float>(n_samples_)); if (test_offset_ == static_cast<SizeType>(0)) { test_offset_ = static_cast<SizeType>(1); } // Define where validation set starts validation_offset_ = static_cast<uint32_t>(validation_percentage * static_cast<float>(n_samples_)); if (validation_offset_ <= test_offset_) { validation_offset_ = test_offset_ + 1; } // boundary check and fix if (validation_offset_ > n_samples_) { validation_offset_ = n_samples_; } if (test_offset_ > n_samples_) { test_offset_ = n_samples_; } n_validation_samples_ = n_samples_ - validation_offset_; n_test_samples_ = validation_offset_ - test_offset_; n_train_samples_ = test_offset_; *train_cursor_ = 0; *test_cursor_ = test_offset_; *validation_cursor_ = validation_offset_; UpdateCursor(); } template <typename LabelType, typename InputType> void TensorDataLoader<LabelType, InputType>::UpdateCursor() { switch (this->mode_) { case DataLoaderMode::TRAIN: { this->current_cursor_ = train_cursor_; this->current_min_ = 0; this->current_max_ = test_offset_; this->current_size_ = n_train_samples_; break; } case DataLoaderMode::TEST: { if (test_to_train_ratio_ == 0) { throw exceptions::InvalidMode("Dataloader has no test set."); } this->current_cursor_ = test_cursor_; this->current_min_ = test_offset_; this->current_max_ = validation_offset_; this->current_size_ = n_test_samples_; break; } case DataLoaderMode::VALIDATE: { if (validation_to_train_ratio_ == 0) { throw exceptions::InvalidMode("Dataloader has no validation set."); } this->current_cursor_ = validation_cursor_; this->current_min_ = validation_offset_; this->current_max_ = n_samples_; this->current_size_ = n_validation_samples_; break; } default: { throw exceptions::InvalidMode("Unsupported dataloader mode."); } } } template <typename LabelType, typename InputType> bool TensorDataLoader<LabelType, InputType>::IsModeAvailable(DataLoaderMode mode) { switch (mode) { case DataLoaderMode::TRAIN: { return test_offset_ > 0; } case DataLoaderMode::TEST: { return test_offset_ < validation_offset_; } case DataLoaderMode::VALIDATE: { return validation_offset_ < n_samples_; } default: { throw exceptions::InvalidMode("Unsupported dataloader mode."); } } } } // namespace dataloaders } // namespace ml namespace serializers { /** * serializer for tensor dataloader * @tparam TensorType */ template <typename LabelType, typename InputType, typename D> struct MapSerializer<fetch::ml::dataloaders::TensorDataLoader<LabelType, InputType>, D> { using Type = fetch::ml::dataloaders::TensorDataLoader<LabelType, InputType>; using DriverType = D; static uint8_t const BASE_DATA_LOADER = 1; static uint8_t const TRAIN_CURSOR = 2; static uint8_t const TEST_CURSOR = 3; static uint8_t const VALIDATION_CURSOR = 4; static uint8_t const TEST_OFFSET = 5; static uint8_t const VALIDATION_OFFSET = 6; static uint8_t const TEST_TO_TRAIN_RATIO = 7; static uint8_t const VALIDATION_TO_TRAIN_RATIO = 8; static uint8_t const N_SAMPLES = 9; static uint8_t const N_TRAIN_SAMPLES = 10; static uint8_t const N_TEST_SAMPLES = 11; static uint8_t const N_VALIDATION_SAMPLES = 12; static uint8_t const DATA = 13; static uint8_t const LABELS = 14; static uint8_t const LABEL_SHAPE = 15; static uint8_t const ONE_SAMPLE_LABEL_SHAPE = 16; static uint8_t const DATA_SHAPES = 17; static uint8_t const ONE_SAMPLE_DATA_SHAPES = 18; static uint8_t const BATCH_LABEL_DIM = 19; static uint8_t const BATCH_DATA_DIM = 20; template <typename Constructor> static void Serialize(Constructor &map_constructor, Type const &sp) { auto map = map_constructor(20); // serialize parent class first auto dl_pointer = static_cast<ml::dataloaders::DataLoader<LabelType, InputType> const *>(&sp); map.Append(BASE_DATA_LOADER, *(dl_pointer)); map.Append(TRAIN_CURSOR, *sp.train_cursor_); map.Append(TEST_CURSOR, *sp.test_cursor_); map.Append(VALIDATION_CURSOR, *sp.validation_cursor_); map.Append(TEST_OFFSET, sp.test_offset_); map.Append(VALIDATION_OFFSET, sp.validation_offset_); map.Append(TEST_TO_TRAIN_RATIO, sp.test_to_train_ratio_); map.Append(VALIDATION_TO_TRAIN_RATIO, sp.validation_to_train_ratio_); map.Append(N_SAMPLES, sp.n_samples_); map.Append(N_TRAIN_SAMPLES, sp.n_train_samples_); map.Append(N_TEST_SAMPLES, sp.n_test_samples_); map.Append(N_VALIDATION_SAMPLES, sp.n_validation_samples_); map.Append(DATA, sp.data_); map.Append(LABELS, sp.labels_); map.Append(LABEL_SHAPE, sp.label_shape_); map.Append(ONE_SAMPLE_LABEL_SHAPE, sp.one_sample_label_shape_); map.Append(DATA_SHAPES, sp.data_shapes_); map.Append(ONE_SAMPLE_DATA_SHAPES, sp.one_sample_data_shapes_); map.Append(BATCH_LABEL_DIM, sp.batch_label_dim_); map.Append(BATCH_DATA_DIM, sp.batch_data_dim_); } template <typename MapDeserializer> static void Deserialize(MapDeserializer &map, Type &sp) { auto dl_pointer = static_cast<ml::dataloaders::DataLoader<LabelType, InputType> *>(&sp); map.ExpectKeyGetValue(BASE_DATA_LOADER, (*dl_pointer)); map.ExpectKeyGetValue(TRAIN_CURSOR, *sp.train_cursor_); map.ExpectKeyGetValue(TEST_CURSOR, *sp.test_cursor_); map.ExpectKeyGetValue(VALIDATION_CURSOR, *sp.validation_cursor_); map.ExpectKeyGetValue(TEST_OFFSET, sp.test_offset_); map.ExpectKeyGetValue(VALIDATION_OFFSET, sp.validation_offset_); map.ExpectKeyGetValue(TEST_TO_TRAIN_RATIO, sp.test_to_train_ratio_); map.ExpectKeyGetValue(VALIDATION_TO_TRAIN_RATIO, sp.validation_to_train_ratio_); map.ExpectKeyGetValue(N_SAMPLES, sp.n_samples_); map.ExpectKeyGetValue(N_TRAIN_SAMPLES, sp.n_train_samples_); map.ExpectKeyGetValue(N_TEST_SAMPLES, sp.n_test_samples_); map.ExpectKeyGetValue(N_VALIDATION_SAMPLES, sp.n_validation_samples_); map.ExpectKeyGetValue(DATA, sp.data_); map.ExpectKeyGetValue(LABELS, sp.labels_); map.ExpectKeyGetValue(LABEL_SHAPE, sp.label_shape_); map.ExpectKeyGetValue(ONE_SAMPLE_LABEL_SHAPE, sp.one_sample_label_shape_); map.ExpectKeyGetValue(DATA_SHAPES, sp.data_shapes_); map.ExpectKeyGetValue(ONE_SAMPLE_DATA_SHAPES, sp.one_sample_data_shapes_); map.ExpectKeyGetValue(BATCH_LABEL_DIM, sp.batch_label_dim_); map.ExpectKeyGetValue(BATCH_DATA_DIM, sp.batch_data_dim_); sp.UpdateRanges(); sp.UpdateCursor(); } }; } // namespace serializers } // namespace fetch
32.082569
100
0.696097
devjsc
dc7df497c6f0f6510db247d9385e1e9d2214fe87
7,100
cpp
C++
libraries/chain/gravity_evaluator.cpp
petrkotegov/gravity-core
52c9a96126739c33ee0681946e1d88c5be9a6190
[ "MIT" ]
8
2018-05-25T17:58:46.000Z
2018-06-23T21:13:26.000Z
libraries/chain/gravity_evaluator.cpp
petrkotegov/gravity-core
52c9a96126739c33ee0681946e1d88c5be9a6190
[ "MIT" ]
14
2018-05-25T19:44:30.000Z
2018-08-03T11:35:27.000Z
libraries/chain/gravity_evaluator.cpp
petrkotegov/gravity-core
52c9a96126739c33ee0681946e1d88c5be9a6190
[ "MIT" ]
6
2018-05-30T04:37:46.000Z
2019-03-05T14:47:34.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 <graphene/chain/gravity_evaluator.hpp> #include <graphene/chain/gravity_transfer_object.hpp> #include <graphene/chain/exceptions.hpp> #include <graphene/chain/hardfork.hpp> #include <graphene/chain/is_authorized_asset.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/uuid/string_generator.hpp> namespace graphene { namespace chain { //**********************************************************************************************************************************************// void_result gravity_transfer_evaluator::do_evaluate( const gravity_transfer_operation& op ) { try { const database& d = db(); const account_object& from_account = op.from(d); const account_object& to_account = op.to(d); const account_object& fee_payer = op.fee_payer_account(d); const asset_object& asset_type = op.amount.asset_id(d); try { GRAPHENE_ASSERT( is_authorized_asset( d, from_account, asset_type ), transfer_from_account_not_whitelisted, "'from' account ${from} is not whitelisted for asset ${asset}", ("from",op.from) ("asset",op.amount.asset_id) ); GRAPHENE_ASSERT( is_authorized_asset( d, to_account, asset_type ), transfer_to_account_not_whitelisted, "'to' account ${to} is not whitelisted for asset ${asset}", ("to",op.to) ("asset",op.amount.asset_id) ); if( asset_type.is_transfer_restricted() ) { GRAPHENE_ASSERT( from_account.id == asset_type.issuer || to_account.id == asset_type.issuer, transfer_restricted_transfer_asset, "Asset {asset} has transfer_restricted flag enabled", ("asset", op.amount.asset_id) ); } FC_ASSERT( ( from_account.id != fee_payer.id || to_account.id != fee_payer.id ), "wrong fee_payer account" ); bool insufficient_balance = d.get_balance( from_account, asset_type ).amount >= op.amount.amount; FC_ASSERT( insufficient_balance, "Insufficient Balance: ${balance}, unable to transfer '${total_transfer}' from account '${a}' to '${t}'", ("a",from_account.name)("t",to_account.name)("total_transfer",d.to_pretty_string(op.amount))("balance",d.to_pretty_string(d.get_balance(from_account, asset_type))) ); return void_result(); } FC_RETHROW_EXCEPTIONS( error, "Unable to transfer ${a} from ${f} to ${t}", ("a",d.to_pretty_string(op.amount))("f",op.from(d).name)("t",op.to(d).name) ); } FC_CAPTURE_AND_RETHROW( (op) ) } void_result gravity_transfer_evaluator::do_apply( const gravity_transfer_operation& o ) { try { const auto& gto = db( ).create<gravity_transfer_object>( [&]( gravity_transfer_object& obj ) { std::string time_str = boost::posix_time::to_iso_string( boost::posix_time::from_time_t( db( ).head_block_time( ).sec_since_epoch( ) ) ); std::string id = fc::to_string( obj.id.space( ) ) + "." + fc::to_string( obj.id.type( ) ) + "." + fc::to_string( obj.id.instance( ) ); boost::uuids::string_generator gen; boost::uuids::uuid u1 = gen( id + time_str + time_str ); obj.uuid = to_string( u1 ); obj.fee = o.fee; obj.from = o.from; obj.to = o.to; obj.amount = o.amount; obj.fee_payer = o.fee_payer_account; obj.memo = o.memo; }); return void_result(); } FC_CAPTURE_AND_RETHROW( (o) ) } //**********************************************************************************************************************************************// void_result gravity_transfer_approve_evaluator::do_evaluate( const gravity_transfer_approve_operation& op ) { return void_result(); } void_result gravity_transfer_approve_evaluator::do_apply( const gravity_transfer_approve_operation& o ) { try { bool gravity_transfer_founded = false; auto& e = db( ).get_index_type<gravity_transfer_index>( ).indices( ).get<by_transfer_by_uuid>( ); for( auto itr = e.begin( ); itr != e.end( ); itr++ ) { if( ( *itr ).uuid.compare( o.uuid ) == 0 ) { if( ( *itr ).to != o.approver ) FC_ASSERT( 0, "wrong receiver!" ); db().adjust_balance( ( *itr ).from, -( *itr ).amount ); db().adjust_balance( ( *itr ).to, ( *itr ).amount ); auto c = db().get_core_asset(); const auto& a = ( *itr ).amount.asset_id( (database&)db() ); db( ).remove( *itr ); gravity_transfer_founded = true; break; } } FC_ASSERT( gravity_transfer_founded, "gravity transfer not founed!" ); return void_result(); } FC_CAPTURE_AND_RETHROW( (o) ) } //**********************************************************************************************************************************************// void_result gravity_transfer_reject_evaluator::do_evaluate( const gravity_transfer_reject_operation& op ) { return void_result(); } void_result gravity_transfer_reject_evaluator::do_apply( const gravity_transfer_reject_operation& o ) { try { bool gravity_transfer_founded = false; auto& e = db( ).get_index_type<gravity_transfer_index>( ).indices( ).get<by_transfer_by_uuid>( ); for( auto itr = e.begin( ); itr != e.end( ); itr++ ) { if( ( *itr ).uuid.compare( o.uuid ) == 0 ) { if( ( *itr ).to != o.approver ) FC_ASSERT( 0, "wrong receiver!" ); db( ).remove( *itr ); gravity_transfer_founded = true; break; } } FC_ASSERT( gravity_transfer_founded, "gravity transfer not founed!" ); return void_result(); } FC_CAPTURE_AND_RETHROW( (o) ) } //**********************************************************************************************************************************************// } } // graphene::chain
43.030303
183
0.600282
petrkotegov
dc828fcddb0a659452f04bb7a96fd368e4a1d4d6
4,625
cpp
C++
Official Windows Driver Kit Sample/Windows Driver Kit (WDK) 8.1 Samples/[C++]-windows-driver-kit-81-cpp/WDK 8.1 C++ Samples/Async Notification Sample/C++/server/library/asyncnotify.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
2
2022-01-21T01:40:58.000Z
2022-01-21T01:41:10.000Z
Official Windows Driver Kit Sample/Windows Driver Kit (WDK) 8.1 Samples/[C++]-windows-driver-kit-81-cpp/WDK 8.1 C++ Samples/Async Notification Sample/C++/server/library/asyncnotify.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
1
2022-03-15T04:21:41.000Z
2022-03-15T04:21:41.000Z
Official Windows Driver Kit Sample/Windows Driver Kit (WDK) 8.1 Samples/[C++]-windows-driver-kit-81-cpp/WDK 8.1 C++ Samples/Async Notification Sample/C++/server/library/asyncnotify.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
null
null
null
// // Windows Server (Printing) Driver Development Kit Samples. // // // Copyright (c) 1990 - 2005 Microsoft Corporation. // All Rights Reserved. // // // This source code is intended only as a supplement to Microsoft // Development Tools and/or on-line documentation. See these other // materials for detailed information regarding Microsoft code samples. // // THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // #include "precomp.h" #pragma hdrstop _Analysis_mode_(_Analysis_code_type_user_driver_) #include "acallback.hpp" #include "notifydata.hpp" // // MarshalSchema is used to marshal an EOEMDataSchema enum value into a byte array // in a platform-independent fashion (to avoid endianness and size issues on other platforms). // This allows the client and server to run on independent architectures without issue. // To marshal more complex data structures than a simple enum value, it is recommended that // the RPC Serialization Services be used. See the MSDN documentation at: // http://msdn2.microsoft.com/en-us/library/aa378670.aspx for details on their use. // void MarshalSchema( _In_ EOEMDataSchema const &in, _Out_ BYTE (&out)[4] ) { out[0] = (BYTE)(in); out[1] = (BYTE)(in >> 8); out[2] = (BYTE)(in >> 16); out[3] = (BYTE)(in >> 24); } VOID SendAsyncNotification( _In_ LPWSTR pPrinterName, EOEMDataSchema action ) { IPrintAsyncNotifyChannel *pIAsynchNotification = NULL; CPrintOEMAsyncNotifyCallback *pIAsynchCallback = new CPrintOEMAsyncNotifyCallback; if (pIAsynchCallback) { RouterCreatePrintAsyncNotificationChannel(pPrinterName, const_cast<GUID*>(&SAMPLE_NOTIFICATION_UI), kPerUser, kBiDirectional, pIAsynchCallback, &pIAsynchNotification); pIAsynchCallback->Release(); } if (pIAsynchNotification) { BYTE data[4] = { 0 }; MarshalSchema(action, data); CPrintOEMAsyncNotifyDataObject *pClientNotification = new CPrintOEMAsyncNotifyDataObject(data, sizeof(data), const_cast<GUID*>(&SAMPLE_NOTIFICATION_UI)); if (pClientNotification) { pIAsynchNotification->SendNotification(pClientNotification); pClientNotification->Release(); } pIAsynchNotification->Release(); } } VOID SendAsyncUINotification( _In_ LPWSTR pPrinterName ) { WCHAR pszMsg[] = L"<?xml version=\"1.0\" ?>" \ L"<asyncPrintUIRequest xmlns=\"http://schemas.microsoft.com/2003/print/asyncui/v1/request\">" \ L"<v1><requestOpen><balloonUI><title>AsyncUI sample</title><body>This text is a sample.</body>" \ L"</balloonUI></requestOpen></v1></asyncPrintUIRequest>"; IPrintAsyncNotifyChannel *pIAsynchNotification = NULL; CPrintOEMAsyncNotifyCallback *pIAsynchCallback = new CPrintOEMAsyncNotifyCallback; if (pIAsynchCallback) { RouterCreatePrintAsyncNotificationChannel(pPrinterName, const_cast<GUID*>(&MS_ASYNCNOTIFY_UI), kPerUser, kBiDirectional, pIAsynchCallback, &pIAsynchNotification); pIAsynchCallback->Release(); } if (pIAsynchNotification) { CPrintOEMAsyncNotifyDataObject *pClientNotification = new CPrintOEMAsyncNotifyDataObject(reinterpret_cast<BYTE*>(pszMsg), sizeof(pszMsg), const_cast<GUID*>(&MS_ASYNCNOTIFY_UI)); if (pClientNotification) { pIAsynchNotification->SendNotification(pClientNotification); pClientNotification->Release(); } pIAsynchNotification->Release(); } }
34.774436
141
0.568649
zzgchina888
dc87d18e6b2106b111bb9e13745676a8752e419b
2,268
cpp
C++
SocketWatcher/RegisterServer.cpp
kiranjosek/HAM
26ef64aba7064f2279114213fbad37ab8cdafd7b
[ "Apache-2.0" ]
1
2020-06-14T01:16:20.000Z
2020-06-14T01:16:20.000Z
SocketWatcher/RegisterServer.cpp
kiranjosek/HAM
26ef64aba7064f2279114213fbad37ab8cdafd7b
[ "Apache-2.0" ]
null
null
null
SocketWatcher/RegisterServer.cpp
kiranjosek/HAM
26ef64aba7064f2279114213fbad37ab8cdafd7b
[ "Apache-2.0" ]
1
2020-06-14T01:16:21.000Z
2020-06-14T01:16:21.000Z
#include "RegisterServer.h" RegisterServer::RegisterServer(int port) { int sockFd= CreateServerSocket(port); CreateEpollSocket(sockFd); watchEvent = &SocketWatcher::StartServerWatcher; printf("Register Server\n"); } RegisterServer::RegisterServer(char* ipAddr,int port) { int sockFd = CreateClientSocket(ipAddr,port); // CreateEpollSocket(sockFd,1); CreateEpollSocket(sockFd,DEFAULT_SERVER_EVENTS|EPOLLET,new SocketInfo(sockFd,64)); watchEvent = &SocketWatcher::StartClientWatcher; //MUXER.AddSubscriberSocket(sockFd); printf("Register Client\n"); } void RegisterServer::EventErrorHandler(struct epoll_event &event) { printf("RegisterServer::EventErrorHandler();\n"); SocketInfo* dh = (SocketInfo*)event.data.ptr; //MUXER.RemoveSubscriberSocket(dh->m_socketDescriptor); close (dh->m_socketDescriptor); delete dh; } void RegisterServer::AcceptNewClientConnection(struct epoll_event &event) { printf("RegisterServer()::AcceptNewClientConnection()\n"); struct sockaddr in_addr; socklen_t in_len; int infd; in_len = sizeof in_addr; infd = accept(m_socketDescriptor,&in_addr,&in_len); if (infd == -1) //error or Exception return; if(SetSocketFlags(infd,O_NONBLOCK) < 0) { perror ("Flag Error:"); return;// exit() } event.data.ptr = new SocketInfo(infd,64); #ifdef EDGETRIGGERED event.events = EPOLLIN | EPOLLET | EPOLLERR | EPOLLRDHUP | EPOLLHUP; #else event.events = EPOLLIN | EPOLLERR | EPOLLRDHUP | EPOLLHUP; #endif if(epoll_ctl(m_epollDescriptor,EPOLL_CTL_ADD,infd,&event)) { perror ("epoll_ctl"); return; // exit() } //MUXER.AddSubscriberSocket(infd); } void RegisterServer::ProcessClientEvent(struct epoll_event &event) { printf("RegisterServer::ProcessClientEvent();\n"); int done = 0; SocketInfo* dh = (SocketInfo*)event.data.ptr; #ifdef EDGETRIGGERED while(1) { #endif dh->ReadFromSocket(dh->m_socketDescriptor,done); if(done == 1) // socket read Error { EventErrorHandler(event); return; } #ifdef EDGETRIGGERED else if(done == 2) //EAGAIN { return; } } #endif }
23.873684
86
0.666226
kiranjosek
dc8807302de6a2674509187012e123a28919d462
7,388
cpp
C++
src/LuminoEngine/src/Graphics/RenderPass.cpp
infinnie/Lumino
921caabdbcb91528a2aac290e31d650628bc3bed
[ "MIT" ]
null
null
null
src/LuminoEngine/src/Graphics/RenderPass.cpp
infinnie/Lumino
921caabdbcb91528a2aac290e31d650628bc3bed
[ "MIT" ]
null
null
null
src/LuminoEngine/src/Graphics/RenderPass.cpp
infinnie/Lumino
921caabdbcb91528a2aac290e31d650628bc3bed
[ "MIT" ]
null
null
null
/* 移行 Note: map を各 GraphicsResource から CommandBuffer へ移動する。 ※ ネイティブの map (transfar) は RenderPass の外側でなければ使えないので、順序制御するため CommandBuffer に統合したい CommandBuffer と RenderPass は全て pool からインスタンスを得る。インスタンスを外側で保持し続けてはならない。 */ #include "Internal.hpp" #include <LuminoEngine/Graphics/Texture.hpp> #include <LuminoEngine/Graphics/DepthBuffer.hpp> #include <LuminoEngine/Graphics/RenderPass.hpp> #include "GraphicsManager.hpp" #include "GraphicsProfiler.hpp" #include "RHIs/GraphicsDeviceContext.hpp" namespace ln { //============================================================================== // RenderPass RenderPass::RenderPass() : m_manager(nullptr) , m_rhiObject() , m_renderTargets{} , m_depthBuffer() , m_clearFlags(ClearFlags::None) , m_clearColor(0, 0, 0, 0) , m_clearDepth(1.0f) , m_clearStencil(0x00) , m_dirty(true) , m_active(false) { detail::GraphicsResourceInternal::initializeHelper_GraphicsResource(this, &m_manager); detail::GraphicsResourceInternal::manager(this)->profiler()->addRenderPass(this); } RenderPass::~RenderPass() { detail::GraphicsResourceInternal::manager(this)->profiler()->removeRenderPass(this); detail::GraphicsResourceInternal::finalizeHelper_GraphicsResource(this, &m_manager); } void RenderPass::init() { Object::init(); } void RenderPass::init(RenderTargetTexture* renderTarget, DepthBuffer* depthBuffer) { init(); setRenderTarget(0, renderTarget); setDepthBuffer(depthBuffer); } void RenderPass::onDispose(bool explicitDisposing) { releaseRHI(); Object::onDispose(explicitDisposing); } void RenderPass::setRenderTarget(int index, RenderTargetTexture* value) { if (LN_REQUIRE(!m_active)) return; if (LN_REQUIRE_RANGE(index, 0, GraphicsContext::MaxMultiRenderTargets)) return; if (m_renderTargets[index] != value) { m_renderTargets[index] = value; m_dirty = true; } } RenderTargetTexture* RenderPass::renderTarget(int index) const { if (LN_REQUIRE_RANGE(index, 0, GraphicsContext::MaxMultiRenderTargets)) return nullptr; return m_renderTargets[index]; } void RenderPass::setDepthBuffer(DepthBuffer* value) { if (LN_REQUIRE(!m_active)) return; if (m_depthBuffer != value) { m_depthBuffer = value; m_dirty = true; } } void RenderPass::setClearFlags(ClearFlags value) { if (LN_REQUIRE(!m_active)) return; if (m_clearFlags != value) { m_clearFlags = value; m_dirty = true; } } void RenderPass::setClearColor(const Color& value) { if (LN_REQUIRE(!m_active)) return; if (m_clearColor != value) { m_clearColor = value; m_dirty = true; } } void RenderPass::setClearDepth(float value) { if (LN_REQUIRE(!m_active)) return; if (m_clearDepth != value) { m_clearDepth = value; m_dirty = true; } } void RenderPass::setClearStencil(uint8_t value) { if (LN_REQUIRE(!m_active)) return; if (m_clearStencil != value) { m_clearStencil = value; m_dirty = true; } } void RenderPass::setClearValues(ClearFlags flags, const Color& color, float depth, uint8_t stencil) { if (LN_REQUIRE(!m_active)) return; setClearFlags(flags); setClearColor(color); setClearDepth(depth); setClearStencil(stencil); } DepthBuffer* RenderPass::depthBuffer() const { return m_depthBuffer; } void RenderPass::onChangeDevice(detail::IGraphicsDevice* device) { if (LN_REQUIRE(!m_active)) return; if (!device) { releaseRHI(); } else { m_dirty = true; // create with next resolveRHIObject } } detail::IRenderPass* RenderPass::resolveRHIObject(GraphicsContext* context, bool* outModified) { if (m_dirty) { releaseRHI(); m_dirty = false; const RenderTargetTexture* primaryTarget = m_renderTargets[0]; if (LN_REQUIRE(primaryTarget, "RenderPass: [0] Invalid render target.")) return nullptr; const Size primarySize(primaryTarget->width(), primaryTarget->height()); detail::NativeRenderPassCache::FindKey key; for (auto i = 0; i < m_renderTargets.size(); i++) { RenderTargetTexture* rt = m_renderTargets[i]; if (rt) { if (LN_REQUIRE(rt->width() == primarySize.width && rt->height() == primarySize.height, u"RenderPass: Invalid render target dimensions.")) return nullptr; } key.renderTargets[i] = detail::GraphicsResourceInternal::resolveRHIObject<detail::RHIResource>(context, rt, nullptr); } key.depthBuffer = detail::GraphicsResourceInternal::resolveRHIObject<detail::IDepthBuffer>(context, m_depthBuffer, nullptr); key.clearFlags = m_clearFlags; key.clearColor = m_clearColor; key.clearDepth = m_clearDepth; key.clearStencil = m_clearStencil; if (!m_renderTargets[0]->m_cleared && !testFlag(key.clearFlags, ClearFlags::Color)) { key.clearFlags = Flags<ClearFlags>(key.clearFlags) | ClearFlags::Color; m_dirty = true; } m_renderTargets[0]->m_cleared = true; if (m_depthBuffer) { if (LN_REQUIRE(m_depthBuffer->width() == primarySize.width && m_depthBuffer->height() == primarySize.height, u"RenderPass: Invalid depth buffer dimensions.")) return nullptr; if (!m_depthBuffer->m_cleared && !testFlag(key.clearFlags, Flags<ClearFlags>(ClearFlags::Depth | ClearFlags::Stencil).get())) { key.clearFlags = Flags<ClearFlags>(key.clearFlags) | ClearFlags::Depth | ClearFlags::Stencil; m_dirty = true; } m_depthBuffer->m_cleared = true; } auto device = detail::GraphicsResourceInternal::manager(this)->deviceContext(); m_rhiObject = device->renderPassCache()->findOrCreate(key); key.clearFlags = ClearFlags::None; key.clearColor = Color(0, 0, 0, 0); key.clearDepth = 1.0f; key.clearStencil = 0x00; m_rhiObjectNoClear = device->renderPassCache()->findOrCreate(key); } return m_rhiObject; } // [2019/10/5] // GraphicsContext はデータ転送を遅延実行するため、各種 resolve (vkCmdCopyBuffer()) が呼ばれるタイミングが RenderPass の内側に入ってしまう。 // // 多分グラフィックスAPIとして正しいであろう対策は、GraphicsContext に map, unmap, setData 等を実装して、resolve の遅延実行をやめること。 // ただ、dynamic なリソース更新するところすべてで GraphicsContext が必要になるので、描画に制限が多くなるし、GraphicsContext の取り回しを考えないとならない。 // 制限として厄介なのは DebugRendering. 各 onUpdate() の時点で何か描きたいときは GraphicsContext が確定していないのでいろいろ制約を考える必要がある。 // 特に、onUpdate 1度に対して複数 SwapChain から world を覗きたいときとか。 // // もうひとつ、泥臭いけど今のところあまり時間掛けないで回避できるのが、この方法。 detail::IRenderPass* RenderPass::resolveRHIObjectNoClear(GraphicsContext* context, bool* outModified) { resolveRHIObject(context, outModified); return m_rhiObjectNoClear; } void RenderPass::releaseRHI() { if (m_rhiObject) { //auto device = detail::GraphicsResourceInternal::manager(this)->deviceContext(); //device->renderPassCache()->release(m_rhiObject); m_rhiObject = nullptr; } } ////============================================================================== //// RenderPassPool //namespace detail { // //RenderPassPool::RenderPassPool(GraphicsManager* manager) //{ //} // //RenderPass* RenderPassPool::findOrCreate(const FindKey& key) //{ // uint64_t hash = computeHash(key); // auto itr = m_hashMap.find(hash); // if (itr != m_hashMap.end()) { // return itr->second; // } // else { // // TODO: Pool を使い切ったら、使っていないものを消す // // auto pipeline = m_device->createPipeline(key.renderPass, key.state); // if (!pipeline) { // return nullptr; // } // // m_hashMap.insert({ hash, pipeline }); // return pipeline; // } //} // //uint64_t RenderPassPool::computeHash(const FindKey& key) //{ //} // //} // namespace detail } // namespace ln
28.091255
177
0.70804
infinnie
dc8812275a6a339a60bb8ae06392c6c1fb9d39ae
1,108
cpp
C++
JTS/CF-B/CF6-D2-B/main.cpp
rahulsrma26/ol_codes
dc599f5b70c14229a001c5239c366ba1b990f68b
[ "MIT" ]
2
2019-03-18T16:06:10.000Z
2019-04-07T23:17:06.000Z
JTS/CF-B/CF6-D2-B/main.cpp
rahulsrma26/ol_codes
dc599f5b70c14229a001c5239c366ba1b990f68b
[ "MIT" ]
null
null
null
JTS/CF-B/CF6-D2-B/main.cpp
rahulsrma26/ol_codes
dc599f5b70c14229a001c5239c366ba1b990f68b
[ "MIT" ]
1
2019-03-18T16:06:52.000Z
2019-03-18T16:06:52.000Z
// Date : 2019-03-26 // Author : Rahul Sharma // Problem : http://codeforces.com/contest/6/problem/B #include <iostream> #include <string> int main() { using namespace std; ios_base::sync_with_stdio(false); cin.tie(0); int n, m; cin >> n >> m; char p; cin >> p; char d[128] = {}; auto check = [&](const string& s) { if (m > 1) { if (s[0] == p) d[s[1]] = 1; if (s[m - 1] == p) d[s[m - 2]] = 1; } for (int j = 1; j < m - 1; j++) if (s[j] == p) d[s[j - 1]] = d[s[j + 1]] = 1; }; string s[2]; cin >> s[0]; check(s[0]); for (int i = 1; i < n; i++) { auto& top = s[1 - (i & 1)]; auto& bot = s[i & 1]; cin >> bot; check(bot); for (int j = 0; j < m; j++) if (top[j] == p) d[bot[j]] = 1; else if (bot[j] == p) d[top[j]] = 1; } int c = 0; for (int i = 'A'; i <= 'Z'; i++) if (i != p && d[i]) c++; cout << c; }
20.518519
54
0.351083
rahulsrma26
dc893fd46df1575862244fb3ec44f42cbb74d463
532
cpp
C++
Codeforces/HelpfulMaths.cpp
canis-majoris123/CompetitiveProgramming
be6c208abe6e0bd748c3bb0e715787506d73588d
[ "MIT" ]
null
null
null
Codeforces/HelpfulMaths.cpp
canis-majoris123/CompetitiveProgramming
be6c208abe6e0bd748c3bb0e715787506d73588d
[ "MIT" ]
null
null
null
Codeforces/HelpfulMaths.cpp
canis-majoris123/CompetitiveProgramming
be6c208abe6e0bd748c3bb0e715787506d73588d
[ "MIT" ]
null
null
null
//https://codeforces.com/problemset/problem/339/A #include<bits/stdc++.h> using namespace std ; #define aakriti string int main() { ios_base::sync_with_stdio(false); cin.tie(0); aakriti s ; int a ; cin >> s ; sort(s.begin(), s.end()); vector<char>v; for(int i = 0; i < s.size(); i++) { if(s[i] != '+') { v.push_back(s[i]); } } a = v.size(); for(int i = 0; i < a-1; i++) { cout << v[i] << "+"; } cout << v[a-1]; }
19
50
0.443609
canis-majoris123
dc8ffd8eb171620b43a8b04ac703d218ae42e844
9,300
cpp
C++
Amcl/cpp_armv7l/ecdh_NIST256.cpp
UoS-SCCS/ecc-daa
eebd40d01aed7a3ccb8dc33df8a4b6415f02dda9
[ "BSD-2-Clause" ]
2
2020-02-28T10:40:12.000Z
2021-02-18T03:32:28.000Z
Amcl/cpp_armv7l/ecdh_NIST256.cpp
UoS-SCCS/ecc-daa
eebd40d01aed7a3ccb8dc33df8a4b6415f02dda9
[ "BSD-2-Clause" ]
null
null
null
Amcl/cpp_armv7l/ecdh_NIST256.cpp
UoS-SCCS/ecc-daa
eebd40d01aed7a3ccb8dc33df8a4b6415f02dda9
[ "BSD-2-Clause" ]
null
null
null
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* ECDH/ECIES/ECDSA Functions - see main program below */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #include "ecdh_NIST256.h" using namespace B256_28; using namespace NIST256; /* Calculate a public/private EC GF(p) key pair. W=S.G mod EC(p), * where S is the secret key and W is the public key * and G is fixed generator. * If RNG is NULL then the private key is provided externally in S * otherwise it is generated randomly internally */ int NIST256::ECP_KEY_PAIR_GENERATE(csprng *RNG,octet* S,octet *W) { BIG r,gx,gy,s; ECP G; int res=0; ECP_generator(&G); BIG_rcopy(r,CURVE_Order); if (RNG!=NULL) { BIG_randomnum(s,r,RNG); } else { BIG_fromBytes(s,S->val); BIG_mod(s,r); } #ifdef AES_S BIG_mod2m(s,2*AES_S); // BIG_toBytes(S->val,s); #endif S->len=EGS_NIST256; BIG_toBytes(S->val,s); ECP_mul(&G,s); ECP_toOctet(W,&G,false); // To use point compression on public keys, change to true /* #if CURVETYPE_NIST256!=MONTGOMERY ECP_get(gx,gy,&G); #else ECP_get(gx,&G); #endif #if CURVETYPE_NIST256!=MONTGOMERY W->len=2*EFS_NIST256+1; W->val[0]=4; BIG_toBytes(&(W->val[1]),gx); BIG_toBytes(&(W->val[EFS_NIST256+1]),gy); #else W->len=EFS_NIST256+1; W->val[0]=2; BIG_toBytes(&(W->val[1]),gx); #endif */ return res; } /* Validate public key */ int NIST256::ECP_PUBLIC_KEY_VALIDATE(octet *W) { BIG q,r,wx,k; ECP WP; int valid,nb; int res=0; BIG_rcopy(q,Modulus); BIG_rcopy(r,CURVE_Order); valid=ECP_fromOctet(&WP,W); if (!valid) res=ECDH_INVALID_PUBLIC_KEY; /* BIG_fromBytes(wx,&(W->val[1])); if (BIG_comp(wx,q)>=0) res=ECDH_INVALID_PUBLIC_KEY; #if CURVETYPE_NIST256!=MONTGOMERY BIG wy; BIG_fromBytes(wy,&(W->val[EFS_NIST256+1])); if (BIG_comp(wy,q)>=0) res=ECDH_INVALID_PUBLIC_KEY; #endif */ if (res==0) { //#if CURVETYPE_NIST256!=MONTGOMERY // valid=ECP_set(&WP,wx,wy); //#else // valid=ECP_set(&WP,wx); //#endif // if (!valid || ECP_isinf(&WP)) res=ECDH_INVALID_PUBLIC_KEY; // if (res==0 ) // {/* Check point is not in wrong group */ nb=BIG_nbits(q); BIG_one(k); BIG_shl(k,(nb+4)/2); BIG_add(k,q,k); BIG_sdiv(k,r); /* get co-factor */ while (BIG_parity(k)==0) { ECP_dbl(&WP); BIG_fshr(k,1); } if (!BIG_isunity(k)) ECP_mul(&WP,k); if (ECP_isinf(&WP)) res=ECDH_INVALID_PUBLIC_KEY; // } } return res; } /* IEEE-1363 Diffie-Hellman online calculation Z=S.WD */ int NIST256::ECP_SVDP_DH(octet *S,octet *WD,octet *Z) { BIG r,s,wx; int valid; ECP W; int res=0; BIG_fromBytes(s,S->val); valid=ECP_fromOctet(&W,WD); /* BIG_fromBytes(wx,&(WD->val[1])); #if CURVETYPE_NIST256!=MONTGOMERY BIG wy; BIG_fromBytes(wy,&(WD->val[EFS_NIST256+1])); valid=ECP_set(&W,wx,wy); #else valid=ECP_set(&W,wx); #endif */ if (!valid) res=ECDH_ERROR; if (res==0) { BIG_rcopy(r,CURVE_Order); BIG_mod(s,r); ECP_mul(&W,s); if (ECP_isinf(&W)) res=ECDH_ERROR; else { #if CURVETYPE_NIST256!=MONTGOMERY ECP_get(wx,wx,&W); #else ECP_get(wx,&W); #endif Z->len=MODBYTES_B256_28; BIG_toBytes(Z->val,wx); } } return res; } #if CURVETYPE_NIST256!=MONTGOMERY /* IEEE ECDSA Signature, C and D are signature on F using private key S */ int NIST256::ECP_SP_DSA(int sha,csprng *RNG,octet *K,octet *S,octet *F,octet *C,octet *D) { char h[128]; octet H= {0,sizeof(h),h}; BIG r,s,f,c,d,u,vx,w; ECP G,V; ehashit(sha,F,-1,NULL,&H,sha); ECP_generator(&G); BIG_rcopy(r,CURVE_Order); BIG_fromBytes(s,S->val); int hlen=H.len; if (H.len>MODBYTES_B256_28) hlen=MODBYTES_B256_28; BIG_fromBytesLen(f,H.val,hlen); if (RNG!=NULL) { do { BIG_randomnum(u,r,RNG); BIG_randomnum(w,r,RNG); /* side channel masking */ #ifdef AES_S BIG_mod2m(u,2*AES_S); #endif ECP_copy(&V,&G); ECP_mul(&V,u); ECP_get(vx,vx,&V); BIG_copy(c,vx); BIG_mod(c,r); if (BIG_iszilch(c)) continue; BIG_modmul(u,u,w,r); BIG_invmodp(u,u,r); BIG_modmul(d,s,c,r); BIG_add(d,f,d); BIG_modmul(d,d,w,r); BIG_modmul(d,u,d,r); } while (BIG_iszilch(d)); } else { BIG_fromBytes(u,K->val); BIG_mod(u,r); #ifdef AES_S BIG_mod2m(u,2*AES_S); #endif ECP_copy(&V,&G); ECP_mul(&V,u); ECP_get(vx,vx,&V); BIG_copy(c,vx); BIG_mod(c,r); if (BIG_iszilch(c)) return ECDH_ERROR; BIG_invmodp(u,u,r); BIG_modmul(d,s,c,r); BIG_add(d,f,d); BIG_modmul(d,u,d,r); if (BIG_iszilch(d)) return ECDH_ERROR; } C->len=D->len=EGS_NIST256; BIG_toBytes(C->val,c); BIG_toBytes(D->val,d); return 0; } /* IEEE1363 ECDSA Signature Verification. Signature C and D on F is verified using public key W */ int NIST256::ECP_VP_DSA(int sha,octet *W,octet *F, octet *C,octet *D) { char h[128]; octet H= {0,sizeof(h),h}; BIG r,wx,wy,f,c,d,h2; int res=0; ECP G,WP; int valid; ehashit(sha,F,-1,NULL,&H,sha); ECP_generator(&G); BIG_rcopy(r,CURVE_Order); OCT_shl(C,C->len-MODBYTES_B256_28); OCT_shl(D,D->len-MODBYTES_B256_28); BIG_fromBytes(c,C->val); BIG_fromBytes(d,D->val); int hlen=H.len; if (hlen>MODBYTES_B256_28) hlen=MODBYTES_B256_28; BIG_fromBytesLen(f,H.val,hlen); //BIG_fromBytes(f,H.val); if (BIG_iszilch(c) || BIG_comp(c,r)>=0 || BIG_iszilch(d) || BIG_comp(d,r)>=0) res=ECDH_INVALID; if (res==0) { BIG_invmodp(d,d,r); BIG_modmul(f,f,d,r); BIG_modmul(h2,c,d,r); valid=ECP_fromOctet(&WP,W); /* BIG_fromBytes(wx,&(W->val[1])); BIG_fromBytes(wy,&(W->val[EFS_NIST256+1])); valid=ECP_set(&WP,wx,wy); */ if (!valid) res=ECDH_ERROR; else { ECP_mul2(&WP,&G,h2,f); if (ECP_isinf(&WP)) res=ECDH_INVALID; else { ECP_get(d,d,&WP); BIG_mod(d,r); if (BIG_comp(d,c)!=0) res=ECDH_INVALID; } } } return res; } /* IEEE1363 ECIES encryption. Encryption of plaintext M uses public key W and produces ciphertext V,C,T */ void NIST256::ECP_ECIES_ENCRYPT(int sha,octet *P1,octet *P2,csprng *RNG,octet *W,octet *M,int tlen,octet *V,octet *C,octet *T) { int i,len; char z[EFS_NIST256],vz[3*EFS_NIST256+1],k[2*AESKEY_NIST256],k1[AESKEY_NIST256],k2[AESKEY_NIST256],l2[8],u[EFS_NIST256]; octet Z= {0,sizeof(z),z}; octet VZ= {0,sizeof(vz),vz}; octet K= {0,sizeof(k),k}; octet K1= {0,sizeof(k1),k1}; octet K2= {0,sizeof(k2),k2}; octet L2= {0,sizeof(l2),l2}; octet U= {0,sizeof(u),u}; if (ECP_KEY_PAIR_GENERATE(RNG,&U,V)!=0) return; if (ECP_SVDP_DH(&U,W,&Z)!=0) return; OCT_copy(&VZ,V); OCT_joctet(&VZ,&Z); KDF2(sha,&VZ,P1,2*AESKEY_NIST256,&K); K1.len=K2.len=AESKEY_NIST256; for (i=0; i<AESKEY_NIST256; i++) { K1.val[i]=K.val[i]; K2.val[i]=K.val[AESKEY_NIST256+i]; } AES_CBC_IV0_ENCRYPT(&K1,M,C); OCT_jint(&L2,P2->len,8); len=C->len; OCT_joctet(C,P2); OCT_joctet(C,&L2); HMAC(sha,C,&K2,tlen,T); C->len=len; } /* IEEE1363 ECIES decryption. Decryption of ciphertext V,C,T using private key U outputs plaintext M */ int NIST256::ECP_ECIES_DECRYPT(int sha,octet *P1,octet *P2,octet *V,octet *C,octet *T,octet *U,octet *M) { int i,len; char z[EFS_NIST256],vz[3*EFS_NIST256+1],k[2*AESKEY_NIST256],k1[AESKEY_NIST256],k2[AESKEY_NIST256],l2[8],tag[32]; octet Z= {0,sizeof(z),z}; octet VZ= {0,sizeof(vz),vz}; octet K= {0,sizeof(k),k}; octet K1= {0,sizeof(k1),k1}; octet K2= {0,sizeof(k2),k2}; octet L2= {0,sizeof(l2),l2}; octet TAG= {0,sizeof(tag),tag}; if (ECP_SVDP_DH(U,V,&Z)!=0) return 0; OCT_copy(&VZ,V); OCT_joctet(&VZ,&Z); KDF2(sha,&VZ,P1,2*AESKEY_NIST256,&K); K1.len=K2.len=AESKEY_NIST256; for (i=0; i<AESKEY_NIST256; i++) { K1.val[i]=K.val[i]; K2.val[i]=K.val[AESKEY_NIST256+i]; } if (!AES_CBC_IV0_DECRYPT(&K1,C,M)) return 0; OCT_jint(&L2,P2->len,8); len=C->len; OCT_joctet(C,P2); OCT_joctet(C,&L2); HMAC(sha,C,&K2,T->len,&TAG); C->len=len; if (!OCT_ncomp(T,&TAG,T->len)) return 0; return 1; } #endif
21.330275
126
0.605806
UoS-SCCS
dc942c79cd64ccf6f1695c44efd44629642dc60b
194
hpp
C++
src/icons.hpp
nagalun/guimachi
571ffcb762d12c14e019106d7324232f90b02729
[ "0BSD" ]
null
null
null
src/icons.hpp
nagalun/guimachi
571ffcb762d12c14e019106d7324232f90b02729
[ "0BSD" ]
null
null
null
src/icons.hpp
nagalun/guimachi
571ffcb762d12c14e019106d7324232f90b02729
[ "0BSD" ]
null
null
null
#pragma once #include <QIcon> #include <QColor> QIcon loadSvgIconReplacingColor(const char * file, QColor newColor); QIcon loadSvgIconReplacingColor(const char * file, const char * newColor);
24.25
74
0.783505
nagalun
dc968986514ea0009709d2dae96c4023c687eb2a
1,486
cpp
C++
altitude.cpp
ErofeevAA/taskCats
16fbcba6a0b824a581c7fed9c720b523a65fb2da
[ "MIT" ]
2
2021-05-02T04:44:00.000Z
2021-07-08T09:39:42.000Z
altitude.cpp
ErofeevAA/taskCats
16fbcba6a0b824a581c7fed9c720b523a65fb2da
[ "MIT" ]
null
null
null
altitude.cpp
ErofeevAA/taskCats
16fbcba6a0b824a581c7fed9c720b523a65fb2da
[ "MIT" ]
null
null
null
#include <fstream> #include <stack> #include <vector> int main() { std::ifstream in_file("input.txt"); int N; in_file >> N; std::vector<int> a(N); for(int i = 0; i < N; ++i) { in_file >> a[i]; } in_file.close(); std::stack<int> stack; std::vector<int> nums_global_end(N); std::vector<int> radii(N); for(int i = 0; i < N; ++i) { nums_global_end[i] = -1; radii[i] = 0; } for(int i = 0; i < N; ++i) { while (!stack.empty() && a[stack.top()] < a[i]) { int j = stack.top(); stack.pop(); if (nums_global_end[j] == -1 || i - j < j - nums_global_end[j]) { nums_global_end[j] = i; radii[j] = i - j; } } if (stack.empty()) { nums_global_end[i] = -1; radii[i] = 0; } else { if (a[i] != a[stack.top()]) { nums_global_end[i] = stack.top(); radii[i] = i - stack.top(); } else { nums_global_end[i] = nums_global_end[stack.top()]; if (nums_global_end[i] != -1) { radii[i] = i - nums_global_end[stack.top()]; } else { radii[i] = 0; } } } stack.push(i); } std::ofstream out_file("output.txt"); for(int i = 0; i < N; ++i) { out_file << radii[i] << ' '; } out_file.close(); }
27.018182
77
0.415882
ErofeevAA
dca84e1837382a5d915962c1f8f563619001e9b6
393
hpp
C++
src/RenderSystem.Direct3D/PrerequisitesDirect3D.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
src/RenderSystem.Direct3D/PrerequisitesDirect3D.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
src/RenderSystem.Direct3D/PrerequisitesDirect3D.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
// Copyright (c) 2013-2015 mogemimi. // Distributed under the MIT license. See LICENSE.md file for details. #ifndef POMDOG_PREREQUISITESDIRECT3D_373FDC61_HPP #define POMDOG_PREREQUISITESDIRECT3D_373FDC61_HPP #if defined(_XBOX_ONE) && defined(_TITLE) #include <d3dcompiler_x.h> #else #include <d3dcompiler.h> #include <d3dcommon.h> #endif #endif // POMDOG_PREREQUISITESDIRECT3D_373FDC61_HPP
26.2
70
0.80916
bis83
dcaeb731ec2a112ef61adb5b892de419a3edd2b6
11,227
cpp
C++
vireo/encode/h264.cpp
shahzadlone/vireo
73e7176d0255a9506b009c9ab8cc532ecd86e98c
[ "MIT" ]
890
2017-12-15T17:55:42.000Z
2022-03-27T07:46:49.000Z
vireo/encode/h264.cpp
shahzadlone/vireo
73e7176d0255a9506b009c9ab8cc532ecd86e98c
[ "MIT" ]
29
2017-12-16T21:49:08.000Z
2021-09-08T23:04:10.000Z
vireo/encode/h264.cpp
shahzadlone/vireo
73e7176d0255a9506b009c9ab8cc532ecd86e98c
[ "MIT" ]
88
2017-12-15T19:29:49.000Z
2022-03-21T00:59:29.000Z
/* * MIT License * * Copyright (c) 2017 Twitter * * 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 "vireo/base_cpp.h" #include "vireo/common/security.h" #include "vireo/encode/h264.h" #include "vireo/error/error.h" extern "C" { #include "x264.h" } #define X264_CSP X264_CSP_I420 #define X264_LOG_LEVEL X264_LOG_WARNING #define X264_NALU_LENGTH_SIZE 4 #define X264_PROFILE "main" #define X264_TUNE "ssim" static vireo::encode::VideoProfileType GetDefaultProfile(const int width, const int height) { auto min_dimension = min(width, height); if (min_dimension <= 480) { return vireo::encode::VideoProfileType::Baseline; } else if (min_dimension <= 720) { return vireo::encode::VideoProfileType::Main; } else { return vireo::encode::VideoProfileType::High; } } namespace vireo { using common::Data16; namespace encode { struct _H264 { unique_ptr<x264_t, decltype(&x264_encoder_close)> encoder = { NULL, [](x264_t* encoder) { if (encoder) x264_encoder_close(encoder); } }; functional::Video<frame::Frame> frames; uint32_t num_cached_frames = 0; uint32_t num_threads = 0; uint32_t max_delay = 0; static inline const char* const GetProfile(VideoProfileType profile) { THROW_IF(profile != VideoProfileType::Baseline && profile != VideoProfileType::Main && profile != VideoProfileType::High, Unsupported, "unsupported profile type"); switch (profile) { case VideoProfileType::Baseline: return "baseline"; case VideoProfileType::Main: return "main"; case VideoProfileType::High: return "high"; default: return "baseline"; } } }; H264::H264(const functional::Video<frame::Frame>& frames, float crf, uint32_t optimization, float fps, uint32_t max_bitrate, uint32_t thread_count) : H264(frames, H264Params(H264Params::ComputationalParams(optimization, thread_count), H264Params::RateControlParams(RCMethod::CRF, crf, max_bitrate), H264Params::GopParams(0), GetDefaultProfile(frames.settings().width, frames.settings().height), fps)) {}; H264::H264(const functional::Video<frame::Frame>& frames, const H264Params& params) : functional::DirectVideo<H264, Sample>(frames.a(), frames.b()), _this(new _H264()) { THROW_IF(frames.count() >= security::kMaxSampleCount, Unsafe); THROW_IF(params.computation.optimization < kH264MinOptimization || params.computation.optimization > kH264MaxOptimization, InvalidArguments); THROW_IF(params.fps < 0.0f, InvalidArguments); THROW_IF(params.rc.max_bitrate < 0.0f, InvalidArguments); THROW_IF(params.computation.thread_count < kH264MinThreadCount || params.computation.thread_count > kH264MaxThreadCount, InvalidArguments); THROW_IF(!security::valid_dimensions(frames.settings().width, frames.settings().height), Unsafe); THROW_IF(frames.settings().par_width != frames.settings().par_height, InvalidArguments); x264_param_t param; { // Params x264_param_default_preset(&param, x264_preset_names[params.computation.optimization], X264_TUNE); param.i_threads = params.computation.thread_count ? params.computation.thread_count : 1; param.i_log_level = X264_LOG_LEVEL; param.i_width = (int)((frames.settings().width + 1) / 2) * 2; param.i_height = (int)((frames.settings().height + 1) / 2) * 2; param.i_fps_num = (int)(params.fps * 1000.0f + 0.5f); param.i_fps_den = params.fps > 0.0f ? 1000 : 0.0; param.i_csp = X264_CSP; param.b_annexb = 0; param.b_repeat_headers = 0; param.b_vfr_input = 0; if (params.gop.num_bframes >= 0) { // if num_bframes < 0, use default settings param.i_bframe = params.gop.num_bframes; param.i_bframe_pyramid = params.gop.pyramid_mode; } if (param.i_bframe == 0) { // set these zerolatency settings in case number of b frames is 0, otherwise use default settings param.rc.i_lookahead = 0; param.i_sync_lookahead = 0; param.rc.b_mb_tree = 0; param.b_sliced_threads = 1; } if (!params.rc.stats_log_path.empty()) { if (!params.rc.is_second_pass) { param.rc.b_stat_write = true; param.rc.psz_stat_out = (char*)params.rc.stats_log_path.c_str(); } else { param.rc.b_stat_read = true; param.rc.psz_stat_in = (char*)params.rc.stats_log_path.c_str(); } param.rc.b_mb_tree = params.rc.enable_mb_tree; param.rc.i_lookahead = params.rc.look_ahead; param.rc.i_aq_mode = params.rc.aq_mode; param.rc.i_qp_min = params.rc.qp_min; param.i_frame_reference = params.gop.frame_references; param.analyse.b_mixed_references = params.rc.mixed_refs; param.analyse.i_trellis = params.rc.trellis; param.analyse.i_me_method = params.rc.me_method; param.analyse.i_me_range = 16; param.analyse.i_subpel_refine = params.rc.subpel_refine; param.i_keyint_max = params.gop.keyint_max; param.i_keyint_min = params.gop.keyint_min; param.b_sliced_threads = 0; param.i_lookahead_threads = 1; } switch (params.rc.rc_method) { case RCMethod::CRF: param.rc.i_rc_method = X264_RC_CRF; THROW_IF(params.rc.crf < kH264MinCRF || params.rc.crf > kH264MaxCRF, InvalidArguments); param.rc.f_rf_constant = params.rc.crf; if (params.rc.max_bitrate != 0.0) { param.rc.i_vbv_max_bitrate = params.rc.max_bitrate; param.rc.i_vbv_buffer_size = params.rc.max_bitrate; } break; case RCMethod::CBR: CHECK(params.rc.bitrate == params.rc.max_bitrate); param.rc.i_rc_method = X264_RC_ABR; param.rc.i_bitrate = params.rc.bitrate; param.rc.i_vbv_max_bitrate = params.rc.bitrate; param.rc.i_vbv_buffer_size = params.rc.buffer_size; param.rc.f_vbv_buffer_init = params.rc.buffer_init; break; case RCMethod::ABR: param.rc.i_rc_method = X264_RC_ABR; param.rc.i_bitrate = params.rc.bitrate; break; default: // USE CRF as default mode param.rc.i_rc_method = X264_RC_CRF; param.rc.f_rf_constant = 28.0f; break; } THROW_IF(x264_param_apply_profile(&param, _H264::GetProfile(params.profile)) < 0, InvalidArguments); } _this->frames = frames; _this->num_threads = params.computation.thread_count; _this->max_delay = params.computation.thread_count + params.rc.look_ahead + params.gop.num_bframes; { // Encoder _this->encoder.reset(x264_encoder_open(&param)); CHECK(_this->encoder); } _settings = frames.settings(); _settings.codec = settings::Video::Codec::H264; { x264_nal_t* nals; int count; THROW_IF(x264_encoder_headers(_this->encoder.get(), &nals, &count) < 0, InvalidArguments); CHECK(count >= 3); _settings.sps_pps = (header::SPS_PPS){ Data16(nals[0].p_payload + X264_NALU_LENGTH_SIZE, nals[0].i_payload - X264_NALU_LENGTH_SIZE, NULL), Data16(nals[1].p_payload + X264_NALU_LENGTH_SIZE, nals[1].i_payload - X264_NALU_LENGTH_SIZE, NULL), X264_NALU_LENGTH_SIZE }; } } H264::H264(const H264& h264) : functional::DirectVideo<H264, Sample>(h264.a(), h264.b(), h264.settings()), _this(h264._this) { } auto H264::operator()(uint32_t index) const -> Sample { THROW_IF(index >= count(), OutOfRange); THROW_IF(index >= _this->frames.count(), OutOfRange); x264_nal_t* nals = nullptr; int i_nals; x264_picture_t out_picture; int video_size = 0; auto has_more_frames_to_encode = [_this = _this, &index]() -> bool { return index + _this->num_cached_frames < _this->frames.count(); }; if (has_more_frames_to_encode()) { while (video_size == 0 && has_more_frames_to_encode()) { const frame::Frame frame = _this->frames(index + _this->num_cached_frames); const uint64_t pts = frame.pts; const frame::YUV yuv = frame.yuv(); x264_picture_t in_picture; x264_picture_init(&in_picture); in_picture.i_pts = pts; in_picture.img.i_csp = X264_CSP; in_picture.img.i_plane = 3; in_picture.img.plane[0] = (uint8_t*)yuv.plane(frame::Y).bytes().data(); in_picture.img.plane[1] = (uint8_t*)yuv.plane(frame::U).bytes().data(); in_picture.img.plane[2] = (uint8_t*)yuv.plane(frame::V).bytes().data(); in_picture.img.i_stride[0] = (int)yuv.plane(frame::Y).row(); in_picture.img.i_stride[1] = (int)yuv.plane(frame::U).row(); in_picture.img.i_stride[2] = (int)yuv.plane(frame::V).row(); video_size = x264_encoder_encode(_this->encoder.get(), &nals, &i_nals, &in_picture, &out_picture); _this->num_cached_frames += (video_size == 0); THROW_IF(_this->num_cached_frames > _this->max_delay, Unsupported); } } if (!has_more_frames_to_encode()) { CHECK(_this->num_cached_frames > 0); uint32_t thread = 0; while (video_size == 0 && (_this->num_threads == 0 || thread < _this->num_threads)) { CHECK(thread < kH264MaxThreadCount); video_size = x264_encoder_encode(_this->encoder.get(), &nals, &i_nals, nullptr, &out_picture); // flush out cached frames thread++; } _this->num_cached_frames--; } CHECK(video_size > 0); CHECK(nals); CHECK(i_nals != 0); CHECK(out_picture.i_pts >= 0); const auto video_nal = common::Data32(nals[0].p_payload, video_size, NULL); if (out_picture.b_keyframe) { common::Data16 sps_pps_data = _settings.sps_pps.as_extradata(header::SPS_PPS::ExtraDataType::avcc); uint32_t sps_pps_size = sps_pps_data.count(); uint32_t video_sample_data_size = sps_pps_size + video_size; common::Data32 video_sample_data = common::Data32(new uint8_t[video_sample_data_size], video_sample_data_size, [](uint8_t* p) { delete[] p; }); video_sample_data.copy(common::Data32(sps_pps_data.data(), sps_pps_size, nullptr)); video_sample_data.set_bounds(video_sample_data.a() + sps_pps_size, video_sample_data_size); video_sample_data.copy(video_nal); video_sample_data.set_bounds(0, video_sample_data_size); return Sample(out_picture.i_pts, out_picture.i_dts, (bool)out_picture.b_keyframe, SampleType::Video, video_sample_data); } else { return Sample(out_picture.i_pts, out_picture.i_dts, (bool)out_picture.b_keyframe, SampleType::Video, video_nal); } } }}
43.34749
258
0.703394
shahzadlone
dcaff48a13a08466dd426f5713284ae52db97bd7
62,756
cpp
C++
SOURCES/sim/fcc/fccmain.cpp
IsraelyFlightSimulator/Negev-Storm
86de63e195577339f6e4a94198bedd31833a8be8
[ "Unlicense" ]
1
2021-02-19T06:06:31.000Z
2021-02-19T06:06:31.000Z
src/sim/fcc/fccmain.cpp
markbb1957/FFalconSource
07b12e2c41a93fa3a95b912a2433a8056de5bc4d
[ "BSD-2-Clause" ]
null
null
null
src/sim/fcc/fccmain.cpp
markbb1957/FFalconSource
07b12e2c41a93fa3a95b912a2433a8056de5bc4d
[ "BSD-2-Clause" ]
2
2019-08-20T13:35:13.000Z
2021-04-24T07:32:04.000Z
#include "Graphics\Include\Render2D.h" #include "Graphics\Include\DrawBsp.h" #include "stdhdr.h" #include "entity.h" #include "PilotInputs.h" #include "simveh.h" #include "sms.h" #include "airframe.h" #include "object.h" #include "fsound.h" #include "soundfx.h" #include "simdrive.h" #include "mfd.h" #include "radar.h" #include "classtbl.h" #include "playerop.h" #include "navsystem.h" #include "commands.h" #include "hud.h" #include "fcc.h" #include "fault.h" #include "fack.h" #include "aircrft.h" #include "smsdraw.h" #include "airunit.h" #include "handoff.h" #include "otwdrive.h" //MI #include "radardoppler.h" //MI #include "missile.h" //MI #include "misslist.h" //MLR #include "getsimobjectdata.h" // MLR #include "bomb.h" // MLR #include "bombfunc.h" // MLR #include "profiler.h" #include "harmpod.h" // RV - I-Hawk extern bool g_bUseRC135; extern bool g_bEnableColorMfd; extern bool g_bRealisticAvionics; extern bool g_bEnableFCCSubNavCycle; // ASSOCIATOR 04/12/03: Enables you to cycle the Nav steerpoint modes modes with the FCC submodes key extern bool g_bWeaponStepToGun; // MLR 3/13/2004 - optionally turns off weapon stepping to guns extern bool g_bGreyMFD; extern bool g_bGreyScaleMFD; extern bool bNVGmode; const int FireControlComputer::DATALINK_CYCLE = 20;//JPO = 20 seconds const float FireControlComputer::MAXJSTARRANGESQ = 200*200;//JPO = 200 nm const float FireControlComputer::EMITTERRANGE = 60;//JPO = 40 km const float FireControlComputer::CursorRate = 0.15f; //MI added FireControlComputer::FireControlComputer (SimVehicleClass* vehicle, int numHardpoints) { // sfr: smartpointer //fccWeaponPtr = NULL; // MLR 3/16/2004 - simulated weapon fccWeaponId = 0; //rocketPointer = NULL; // MLR 3/5/2004 - For impact prediction rocketWeaponId = 0; platform = vehicle; airGroundDelayTime = 0.0F; airGroundRange = 10.0F * NM_TO_FT; missileMaxTof = -1.0f; missileActiveTime = -1.0f; lastmissileActiveTime = -1.0f; bombPickle = FALSE; postDrop = FALSE; preDesignate = TRUE; tossAnticipationCue = NoCue; laddAnticipationCue = NoLADDCue; //MI lastMasterMode = Nav; // ASSOCIATOR lastNavMasterMode = Nav; lastAgMasterMode = (FCCMasterMode)-1; // AirGroundBomb; // MLR 2/8/2004 - EnterAGMasterMode() will see this, and determine the default weapon // MLR 3/13/2004 - back to using hp ids lastAirAirHp = -1; lastAirGroundHp = -1; lastDogfightHp = -1; lastMissileOverrideHp = -1; lastAirAirGunSubMode = EEGS; // MLR 2/7/2004 - lastAirGroundGunSubMode = STRAF; // MLR 2/7/2004 - lastAirGroundLaserSubMode = SLAVE; // MLR 4/11/2004 - inAAGunMode = 0; // MLR 3/14/2004 - inAGGunMode = 0; // MLR 3/14/2004 - lastSubMode = ETE; //lastAirGroundSubMode = CCRP;//me123 lastDogfightGunSubMode = EEGS; //MI lastAirAirSubMode = Aim9; // ASSOCIATOR strcpy (subModeString, ""); playerFCC = FALSE; targetList = NULL; releaseConsent = FALSE; designateCmd = FALSE; dropTrackCmd = FALSE; targetPtr = NULL; missileCageCmd = FALSE; missileTDBPCmd = FALSE; missileSpotScanCmd = FALSE; missileSlaveCmd = FALSE; cursorXCmd = 0; cursorYCmd = 0; waypointStepCmd = 127; // Force an intial update (GM radar, at least, needs this) HSDRangeStepCmd = 0; HSDRange = 15.0F; HsdRangeIndex = 0; // JPO groundPipperAz = groundPipperEl = 0.0F; masterMode = Nav; subMode = ETE; dgftSubMode = Aim9; // JPO dogfight specific mrmSubMode = Aim120; // ASSOCIATOR 04/12/03: for remembering MRM mode missiles autoTarget = FALSE; missileWEZDisplayRange = 20.0F * NM_TO_FT; mSavedWayNumber = 0; mpSavedWaypoint = NULL; mStptMode = FCCWaypoint; mNewStptMode = mStptMode; bombReleaseOverride = FALSE; lastMissileShootRng = -1; missileLaunched = 0; lastMissileShootHeight = 0; lastMissileShootEnergy = 0; nextMissileImpactTime = -1.0F; lastMissileImpactTime = -1.0f; Height = 0;//me123 targetspeed = 0;//me123 hsdstates = 0; // JPO MissileImpactTimeFlash = 0; // JPO grndlist = NULL; BuildPrePlanned(); // JPO //MI LaserArm = FALSE; LaserFire = FALSE; ManualFire = FALSE; LaserWasFired = FALSE; CheckForLaserFire = FALSE; InhibitFire = FALSE; Timer = 0.0F; ImpactTime = 0.0F; LaserRange = 0.0F; SafetyDistance = 1 * NM_TO_FT; pitch = 0.0F; roll = 0.0F; yaw = 0.0F; time = 0; //MI SOI and HSD IsSOI = FALSE; CouldBeSOI = FALSE; HSDZoom = 0; HSDXPos = 0; //Wombat778 11-10-2003 HSDYPos = 0; //Wombat778 11-10-2003 HSDCursorXCmd = 0; HSDCursorYCmd = 0; xPos = 0; //position of the curson on the scope yPos = 0; HSDDesignate = 0; curCursorRate = CursorRate; DispX = 0; DispY = 0; missileSeekerAz = missileSeekerEl = 0; } FireControlComputer::~FireControlComputer (void) { ClearCurrentTarget(); ClearPlanned(); // JPO } void FireControlComputer::SetPlayerFCC (int flag) { WayPointClass* tmpWaypoint; playerFCC = flag; Sms->SetPlayerSMS(flag); tmpWaypoint = platform->waypoint; TheHud->waypointNum = 0; while (tmpWaypoint && tmpWaypoint != platform->curWaypoint) { tmpWaypoint = tmpWaypoint->GetNextWP(); TheHud->waypointNum ++; } } // JPO - just note it is launched. void FireControlComputer::MissileLaunch() { if(subMode == Aim120) { missileLaunched = 1; lastMissileShootTime = SimLibElapsedTime; } if(!Sms->GetCurrentWeapon()) { switch(masterMode) // MLR 4/12/2004 - Even though this function only appears to be called in AA modes { case Missile: case MissileOverride: if(!Sms->FindWeaponType (wtAim120)) Sms->FindWeaponType (wtAim9); SetMasterMode(masterMode); break; case Dogfight: if(!Sms->FindWeaponType (wtAim9)) Sms->FindWeaponType (wtAim120); SetMasterMode(masterMode); break; } } UpdateLastData(); // UpdateWeaponPtr(); } SimObjectType* FireControlComputer::Exec (SimObjectType* curTarget, SimObjectType* newList, PilotInputs* theInputs) { #ifdef Prof_ENABLED Prof(FireControlComputer_Exec); #endif //me123 overtake needs to be calgulated the same way in MissileClass::GetTOF static const float MISSILE_ALTITUDE_BONUS = 23.0f; //me123 addet here and in // JB 010215 changed from 24 to 23 static const float MISSILE_SPEED = 1500.0f; // JB 010215 changed from 1300 to 1500 if (playerFCC && ((AircraftClass*)platform)->mFaults->GetFault(FaultClass::fcc_fault)) { SetTarget (NULL); } else { if (SimDriver.MotionOn()) { if (!targetPtr) { MissileImpactTimeFlash = 0; // cancel flashing lastMissileImpactTime = 0; lastmissileActiveTime = 0; } if (targetPtr && missileLaunched) { lastMissileShootRng = targetPtr->localData->range; lastMissileImpactTime = nextMissileImpactTime; lastMissileShootHeight = Height; lastMissileShootEnergy = (platform->GetVt() * FTPSEC_TO_KNOTS - 150.0f)/2 ; // JB 010215 changed from 250 to 150 } missileLaunched = 0; if (lastMissileImpactTime > 0.0F && targetPtr ) { //me123 addet this stuff //this is the missiles approximate overtake //missilespeed + altitude bonus + target closure float overtake = lastMissileShootEnergy + MISSILE_SPEED +(lastMissileShootHeight/1000.0f * MISSILE_ALTITUDE_BONUS) + targetspeed * (float)cos(targetPtr->localData->ataFrom); //this is the predicted range from the missile to the target lastMissileShootRng = lastMissileShootRng - (overtake / SimLibMajorFrameRate); lastMissileImpactTime = max (0.0F, lastMissileShootRng/overtake); // this is TOF. Counting on silent failure of divid by 0.0 here... lastMissileImpactTime += -5.0f * (float) sin(.07f * lastMissileImpactTime); // JB 010215 if (lastMissileImpactTime == 0.0f) { // JPO - trigger flashing X // 8 seconds steady, 5 seconds flash MissileImpactTimeFlash = SimLibElapsedTime + (5+8) * CampaignSeconds; lastMissileShootRng = -1.0f; // reset for next } else MissileImpactTimeFlash = 0; } } SetTarget(curTarget); targetList = newList; NavMode(); switch (masterMode) { case AGGun: //if (GetSubMode() == STRAF) { AirGroundMode(); break; case ILS: case Nav: break; case Dogfight: case MissileOverride: case Missile: AirAirMode(); lastCage = missileCageCmd; break; case AirGroundBomb: AirGroundMode(); break; case AirGroundRocket: AirGroundMode(); break; case AirGroundMissile: case AirGroundHARM: AirGroundMissileMode(); break; case AirGroundLaser: //if(!playerFCC) TargetingPodMode(); break; } // always run targeting pod for player // FRB - always run targeting pod for All //TargetingPodMode(); //if(playerFCC) TargetingPodMode(); // COBRA - RED - CCIP HUD FIX - make the Time To target equal to 0, targeting Pod mode is assigning a time to target // messing up the CCIP pipper in HudClas::DrawCCIP call //if(subMode==CCIP) airGroundDelayTime=0.0F; lastDesignate = designateCmd; } return (targetPtr); } void FireControlComputer::SetSubMode (FCCSubMode newSubMode) { if (newSubMode == CCRP && Sms && Sms->Ownship() && Sms->Ownship()->IsAirplane() && // MLR not always owned by a/c ((AircraftClass *)(Sms->Ownship()))->af && (!((AircraftClass *)Sms->Ownship())->af->IsSet(AirframeClass::IsDigital) || (!(((AircraftClass *)(Sms->Ownship()))->AutopilotType() == AircraftClass::CombatAP))) && platform && RadarDataTable[platform->GetRadarType()].NominalRange == 0.0) // JB 011018 { newSubMode = CCIP; } // It has been stated (by Leon R) that changing modes while releasing weapons is bad, so... if (bombPickle) { return; } if (masterMode != Dogfight && masterMode != MissileOverride) { lastSubMode = subMode; } if (lastSubMode == BSGT || lastSubMode == SLAVE || lastSubMode == HARM || lastSubMode == HTS ) { platform->SOIManager (SimVehicleClass::SOI_RADAR); } subMode = newSubMode; // COBRA - RED - Default to immediate release Pickle Time PICKLE(DEFAULT_PICKLE); switch (subMode) { case SAM: strcpy (subModeString, "SAM"); Sms->SetWeaponType (wtNone); Sms->FindWeaponClass (wcSamWpn); break; case Aim9: strcpy (subModeString, "SRM"); if(Sms && Sms->Ownship() && ((AircraftClass *)Sms->Ownship())->AutopilotType() == AircraftClass::CombatAP ) { if(Sms->GetCoolState() == SMSClass::WARM && Sms->MasterArm() == SMSClass::Arm) { // JPO aim9 cooling Sms->SetCoolState(SMSClass::COOLING); } } platform->SOIManager (SimVehicleClass::SOI_RADAR); break; case Aim120: strcpy (subModeString, "MRM"); platform->SOIManager (SimVehicleClass::SOI_RADAR); // COBRA - RED - 1 Second Pickle for AIM 120 PICKLE(SEC_1_PICKLE); break; case EEGS: strcpy (subModeString, "EEGS"); platform->SOIManager (SimVehicleClass::SOI_RADAR); break; // ASSOCIATOR 03/12/03: Added the combined SnapShot LCOS Gunmode SSLC case SSLC: strcpy (subModeString, "SSLC"); platform->SOIManager (SimVehicleClass::SOI_RADAR); break; case LCOS: strcpy (subModeString, "LCOS"); platform->SOIManager (SimVehicleClass::SOI_RADAR); break; case Snapshot: strcpy (subModeString, "SNAP"); platform->SOIManager (SimVehicleClass::SOI_RADAR); break; case CCIP: // MLR 4/1/2004 - rewrite based on Mirv's info. preDesignate = TRUE; strcpy (subModeString, "CCIP"); platform->SOIManager (SimVehicleClass::SOI_RADAR); break; case CCRP: // MLR 4/1/2004 - rewrite based on Mirv's info. preDesignate = FALSE; strcpy (subModeString, "CCRP");//me123 moved so we don't write this with no bombs platform->SOIManager (SimVehicleClass::SOI_RADAR); // 2001-04-18 ADDED BY S.G. I'LL SET MY RANDOM NUMBER FOR CCRP BOMBING INNACURACY NOW // Since autoTarget is a byte :-( I'm limiting to just use the same value for both x and y offset :-( // autoTarget = (rand() & 0x3f) - 32; // In RP5, I'm limited to the variables I can use xBombAccuracy = (rand() & 0x3f) - 32; yBombAccuracy = (rand() & 0x3f) - 32; // COBRA - RED - 1 Second Pickle for CCRP PICKLE(SEC_1_PICKLE); break; case DTOSS: preDesignate = TRUE; groundPipperAz = 0.0F; groundPipperEl = 0.0F; platform->SOIManager (SimVehicleClass::SOI_HUD); // MLR 4/1/2004 - rewrite based on Mirv's info. strcpy (subModeString, "DTOS"); // COBRA - RED - 1 Second Pickle for DTOSS PICKLE(SEC_1_PICKLE); break; case LADD: preDesignate = FALSE; groundPipperAz = 0.0F; groundPipperEl = 0.0F; platform->SOIManager (SimVehicleClass::SOI_RADAR); // MLR 4/1/2004 - rewrite based on Mirv's info. strcpy (subModeString, "LADD"); break; case MAN: // JPO preDesignate = TRUE; strcpy (subModeString, "MAN"); platform->SOIManager (SimVehicleClass::SOI_RADAR); // COBRA - RED - 1 Second Pickle for MAN PICKLE(SEC_1_PICKLE); break; case OBSOLETERCKT: preDesignate = TRUE; strcpy (subModeString, "RCKT"); platform->SOIManager (SimVehicleClass::SOI_RADAR); break; case STRAF: preDesignate = TRUE; strcpy (subModeString, "STRF"); platform->SOIManager (SimVehicleClass::SOI_RADAR); break; case BSGT: preDesignate = TRUE; groundPipperAz = 0.0F; groundPipperEl = 0.0F; strcpy (subModeString, "BSGT"); platform->SOIManager (SimVehicleClass::SOI_HUD); break; case SLAVE: preDesignate = TRUE; groundPipperAz = 0.0F; groundPipperEl = 0.0F; strcpy (subModeString, "SLAV"); platform->SOIManager (SimVehicleClass::SOI_RADAR); // COBRA - RED - 1 Second Pickle for SLAVE PICKLE(SEC_1_PICKLE); break; case HARM: case HTS: preDesignate = TRUE; groundPipperAz = 0.0F; groundPipperEl = 0.0F; // RV - I-Hawk - on HUD it should read "HTS" for HTS and "HARM" for the HARM WPN mode usage if ( subMode == HTS ) { strcpy (subModeString, "HTS"); } else { strcpy (subModeString, "HARM"); } if (Sms->GetCurrentWeaponHardpoint() >= 0 && // JPO CTD fix Sms->CurHardpoint() >= 0 && // JB 010805 Possible CTD check curhardpoint Sms->hardPoint[Sms->CurHardpoint()] != NULL) // Cobra - Sms->GetCurrentWeaponHardpoint() was causing a CTD (returned with a very large number) { Sms->SetWeaponType(Sms->hardPoint[Sms->CurHardpoint()]->GetWeaponType()); // RV - I-Hawk - Don't auto pass SOI to HARM if we are using the advanced HARM systems HarmTargetingPod* harmPod = (HarmTargetingPod*)FindSensor(platform, SensorClass::HTS); if ( harmPod && (harmPod->GetSubMode() == HarmTargetingPod::HAS || harmPod->GetSubMode() == HarmTargetingPod::HAD) ) { platform->SOIManager (SimVehicleClass::SOI_RADAR); } else { platform->SOIManager (SimVehicleClass::SOI_WEAPON); } } else Sms->SetWeaponType (wtNone); // COBRA - RED - 1 Second Pickle for HTS PICKLE(SEC_1_PICKLE); break; case TargetingPod: preDesignate = TRUE; groundPipperAz = 0.0F; groundPipperEl = 0.0F; strcpy (subModeString, "GBU"); if (Sms->GetCurrentWeaponHardpoint() >= 0 && // JPO CTD fix Sms->CurHardpoint() >= 0 && // JB 010805 Possible CTD check curhardpoint Sms->hardPoint[Sms->GetCurrentWeaponHardpoint()] != NULL && Sms->hardPoint[Sms->GetCurrentWeaponHardpoint()]->weaponPointer) Sms->SetWeaponType(Sms->hardPoint[Sms->CurHardpoint()]->GetWeaponType()); else Sms->SetWeaponType (wtNone); platform->SOIManager (SimVehicleClass::SOI_RADAR); // COBRA - RED - 1 Second Pickle for TGP PICKLE(SEC_1_PICKLE); break; case TimeToGo: case ETE: case ETA: platform->SOIManager (SimVehicleClass::SOI_RADAR); break; } // Make sure string is correct in override modes switch (masterMode) { case Dogfight: //strcpy (subModeString, "DGFT"); //JPG 29 Apr 04 - This is no longer displayed in new software tapes break; case MissileOverride: if (Sms->curWeaponType == Aim9) { strcpy (subModeString, "SRM"); } if (Sms->curWeaponType == Aim120) { strcpy (subModeString, "MRM"); } break; } // MLR 4/1/2004 - Memorize SubMode switch(masterMode) { case ILS: case Nav: break; case Dogfight: lastDogfightGunSubMode = subMode; break; case MissileOverride: lastMissileOverrideSubMode = subMode; break; case AAGun: lastAirAirGunSubMode = subMode; break; case Missile: lastAirAirSubMode = subMode; break; case AGGun: lastAirGroundGunSubMode = subMode; break; case AirGroundBomb: Sms->SetAGBSubMode(subMode); { if (playerFCC && SimDriver.GetPlayerAircraft()->AutopilotType() != AircraftClass::CombatAP) { RadarDopplerClass* pradar = (RadarDopplerClass*) FindSensor (platform, SensorClass::Radar); if(g_bRealisticAvionics && pradar) { if(subMode == CCRP || subMode == MAN) { pradar->SelectLastAGMode(); } else { pradar->DefaultAGMode(); } pradar->SetScanDir(1.0F); } } else { RadarClass* pradar = (RadarClass*) FindSensor (platform, SensorClass::Radar); pradar->DefaultAGMode(); } } break; case AirGroundMissile: //lastAirGroundMissileSubMode = subMode; break; case AirGroundHARM: //lastAirGroundHARMSubMode = subMode; break; case AirGroundLaser: lastAirGroundLaserSubMode = subMode; break; case AirGroundCamera: //lastAirGroundCameraSubMode = subMode; break; } } void FireControlComputer::ClearOverrideMode (void) { if ((GetMasterMode() == Dogfight) || (GetMasterMode() == MissileOverride)) { masterMode = lastMasterMode; // MLR - little kludge so I can get the MM MASTERMODES mmm = GetMainMasterMode(); masterMode = ClearOveride;//me123 to allow leaving an overide mode switch(mmm) { case MM_AA: EnterAAMasterMode(); break; case MM_AG: EnterAGMasterMode(); break; default: SetMasterMode (lastMasterMode); break; } } } void FireControlComputer::NextSubMode (void) { // MLR 4/3/2004 - Added calls to SetSubMode instead of doing 'stuff' for ourselves. //MI RadarDopplerClass* pradar = (RadarDopplerClass*) FindSensor (platform, SensorClass::Radar); switch (masterMode) { // ASSOCIATOR 02/12/03: Now we can use the Cycle FCC Submodes key when in Dogfight Mode // ASSOCIATOR 03/12/03: Added the combined SnapShot LCOS Gunmode SSLC case Dogfight: switch (subMode) { case EEGS: if (PlayerOptions.GetAvionicsType() != ATEasy) { SetSubMode (SSLC); } break; case SSLC: SetSubMode (LCOS); break; case LCOS: SetSubMode (Snapshot); break; case Snapshot: SetSubMode (EEGS); break; } break; // ASSOCIATOR 02/12/03: Now we can use the Cycle FCC Submodes key when in MissileOverride // ASSOCIATOR 03/12/03: Added the combined SnapShot LCOS Gunmode SSLC case AAGun: switch (subMode) { case EEGS: if (PlayerOptions.GetAvionicsType() != ATEasy) { SetSubMode (SSLC); } break; case SSLC: SetSubMode (LCOS); break; case LCOS: SetSubMode (Snapshot); break; case Snapshot: SetSubMode (EEGS); break; } break; case Nav: // MD -- 20031203: removed this since sources seem to indicate that there is no such function in the real jet. // ASSOCIATOR Added g_bEnableFCCSubNavCycle as an option and !g_bRealisticAvionics to not break the other modes if( g_bEnableFCCSubNavCycle | !g_bRealisticAvionics ) { switch (subMode) { case ETE: if (PlayerOptions.GetAvionicsType() != ATEasy) { SetSubMode (TimeToGo); } break; case TimeToGo: SetSubMode (ETA); break; case ETA: SetSubMode (ETE); break; } break; } else break; case AirGroundBomb: switch (subMode) { case CCIP: if (PlayerOptions.GetAvionicsType() != ATEasy) { SetSubMode (DTOSS); } break; case CCRP: SetSubMode (CCIP); break; case DTOSS: SetSubMode (CCRP); break; default: // catch LADD MAN etc SetSubMode(CCRP); break; } break; case AirGroundLaser: if(g_bRealisticAvionics) { SetSubMode(lastAirGroundLaserSubMode); SetSubMode(SLAVE); break; } // intentionally fall thru case AirGroundMissile: switch (subMode) { case SLAVE: if (PlayerOptions.GetAvionicsType() != ATEasy) { SetSubMode (BSGT); } break; case BSGT: SetSubMode (SLAVE); break; } break; } } void FireControlComputer::WeaponStep(void) { RadarDopplerClass* pradar = (RadarDopplerClass*) FindSensor (platform, SensorClass::Radar); BombClass *TheBomb=GetTheBomb(); switch (masterMode) { case Dogfight: case MissileOverride: case Missile: case AirGroundMissile: case AirGroundHARM: Sms->WeaponStep(); if(pradar && (masterMode == AirGroundMissile || masterMode == AirGroundHARM)) //MI fix { pradar->SetScanDir(1.0F); pradar->SelectLastAGMode(); } break; case AGGun: if(lastAgMasterMode==AirGroundBomb) { ToggleAGGunMode(); SetSubMode(CCRP); } break; case AirGroundBomb: // COBRA - RED - FIXING POSSIBLE CTDs // CCIP -> DTOS -> STRAF -> CCRP /*if ((Sms->GetCurrentHardpoint() > 0) && (Sms->hardPoint[Sms->GetCurrentHardpoint()]->GetWeaponType()==wtGPS || // Cobra - no rippling GPS (((BombClass*)Sms->hardPoint[Sms->GetCurrentHardpoint()]->weaponPointer) && ((BombClass*)Sms->hardPoint[Sms->GetCurrentHardpoint()]->weaponPointer)->IsSetBombFlag(BombClass::IsJSOW))))*/ { if( TheBomb && ( TheBomb->IsSetBombFlag(BombClass::IsGPS) || TheBomb->IsSetBombFlag(BombClass::IsJSOW))) Sms->WeaponStep(); break; } switch (subMode) { case CCIP: SetSubMode (DTOSS); break; case DTOSS: //Cobra TJL 11/17/04 Aircraft w/o guns get stuck in DTOSS //with missile step //ToggleAGGunMode(); if( Sms->FindWeaponClass(wcGunWpn, TRUE) ) ToggleAGGunMode(); else SetSubMode(CCRP); break; case CCRP: SetSubMode (CCIP); break; default: // catch LADD MAN etc SetSubMode(CCRP); break; } break; } } SimObjectType* FireControlComputer::TargetStep (SimObjectType* startObject, int checkFeature) { VuEntity* testObject = NULL; VuEntity* groundTarget = NULL; SimObjectType* curObject = NULL; SimObjectType* retObject = NULL; float angOff; // Starting in the object list if (startObject == NULL || startObject != targetPtr){ // Start at next and go on if (startObject){ curObject = startObject->next; while (curObject){ if (curObject->localData->ata < 60.0F * DTR){ retObject = curObject; break; } curObject = curObject->next; } } // Did we go off the End of the objects? if (!retObject && checkFeature){ // Check features { VuListIterator featureWalker(SimDriver.featureList); testObject = featureWalker.GetFirst(); while (testObject) { angOff = (float)atan2 (testObject->YPos() - platform->YPos(), testObject->XPos() - platform->XPos()) - platform->Yaw(); if (fabs(angOff) < 60.0F * DTR) { break; } testObject = featureWalker.GetNext(); } } if (testObject) { groundTarget = testObject; // KCK NOTE: Uh.. why are we doing this? //if (retObject) //{ //Tpoint pos; //targetPtr->BaseData()->drawPointer->GetPosition (&pos); //targetPtr->BaseData()->SetPosition (pos.x, pos.y, pos.z); //} groundDesignateX = testObject->XPos(); groundDesignateY = testObject->YPos(); groundDesignateZ = testObject->ZPos(); } } // Did we go off the end of the Features? if (!retObject && !groundTarget){ // Check the head of the object list curObject = targetList; if (curObject){ if (curObject->localData->ata < 60.0F * DTR){ retObject = curObject; } else { while (curObject != startObject){ curObject = curObject->next; if (curObject && curObject->localData->ata < 60.0F * DTR){ retObject = curObject; break; } } } } } } else if (startObject == targetPtr) { // Find the current object if (checkFeature) { { VuListIterator featureWalker(SimDriver.featureList); testObject = featureWalker.GetFirst(); // Iterate up to our position in the list. while (testObject && testObject != targetPtr->BaseData()) testObject = featureWalker.GetNext(); // And then get the next object if (testObject) testObject = featureWalker.GetNext(); // Is there anything after the current object? while (testObject) { angOff = (float)atan2 (testObject->YPos() - platform->YPos(), testObject->XPos() - platform->XPos()) - platform->Yaw(); if (fabs(angOff) < 60.0F * DTR) { break; } testObject = featureWalker.GetNext(); } } // Found one, so use it if (testObject) { groundTarget = testObject; // KCK: Why are we doing this? // Tpoint pos; // targetPtr->BaseData()->drawPointer->GetPosition (&pos); // targetPtr->BaseData()->SetPosition (pos.x, pos.y, pos.z); groundDesignateX = testObject->XPos(); groundDesignateY = testObject->YPos(); groundDesignateZ = testObject->ZPos(); } } // Off the end of the feature list? if (!retObject && !groundTarget) { // Check the head of the object list curObject = targetList; while (curObject) { if (curObject->localData->ata < 60.0F * DTR) { retObject = curObject; break; } curObject = curObject->next; } } // Of the End of the object list ? if (!retObject && checkFeature && !groundTarget){ // Check features VuListIterator featureWalker(SimDriver.featureList); testObject = featureWalker.GetFirst(); while (testObject && testObject != targetPtr->BaseData()){ angOff = (float)atan2 (testObject->YPos() - platform->YPos(), testObject->XPos() - platform->XPos()) - platform->Yaw(); if (fabs(angOff) < 60.0F * DTR){ break; } testObject = featureWalker.GetNext(); } if (testObject) { groundTarget = testObject; groundDesignateX = testObject->XPos(); groundDesignateY = testObject->YPos(); groundDesignateZ = testObject->ZPos(); } } } if (groundTarget){ // We're targeting a feature thing - make a new SimObjectType #ifdef DEBUG //retObject = new SimObjectType(OBJ_TAG, platform, (SimBaseClass*)groundTarget); #else retObject = new SimObjectType((SimBaseClass*)groundTarget); #endif retObject->localData->ataFrom = 180.0F * DTR; } SetTarget(retObject); return retObject; } void FireControlComputer::ClearCurrentTarget (void) { if (targetPtr) targetPtr->Release( ); targetPtr = NULL; } void FireControlComputer::SetTarget (SimObjectType* newTarget) { if (newTarget == targetPtr) return; /* MLR debugging stuff MonoPrint(" FCC::SetTarget - prev:%08x/%08x, new: %08x/%08x\n", targetPtr,(targetPtr?targetPtr->BaseData():0), newTarget,(newTarget?newTarget->BaseData():0)); if(!newTarget) int stop=0; */ ClearCurrentTarget(); if (newTarget) { ShiAssert( newTarget->BaseData() != (FalconEntity*)0xDDDDDDDD ); newTarget->Reference( ); } targetPtr = newTarget; } void FireControlComputer::DisplayInit (ImageBuffer* image) { DisplayExit(); privateDisplay = new Render2D; ((Render2D*)privateDisplay)->Setup (image); if ((g_bGreyMFD) && (!bNVGmode)) privateDisplay->SetColor(GetMfdColor(MFD_WHITE)); else privateDisplay->SetColor (0xff00ff00); } void FireControlComputer::Display (VirtualDisplay* newDisplay) { display = newDisplay; // JPO intercept for now FCC power... if (!((AircraftClass*)platform)->HasPower(AircraftClass::FCCPower)) { BottomRow(); display->TextCenter(0.0f, 0.2f, "FCC"); int ofont = display->CurFont(); display->SetFont(2); display->TextCenterVertical (0.0f, 0.0f, "OFF"); display->SetFont(3); return; } NavDisplay(); } void FireControlComputer::PushButton(int whichButton, int whichMFD) { AircraftClass *playerAC = SimDriver.GetPlayerAircraft(); ShiAssert(whichButton < 20); ShiAssert(whichMFD < 4); if (IsHsdState(HSDCNTL)) { if (hsdcntlcfg[whichButton].mode != HSDNONE) { ToggleHsdState(hsdcntlcfg[whichButton].mode); return; } } //MI if(g_bRealisticAvionics) { if(playerAC) { if(IsSOI && (whichButton >=11 && whichButton <= 13)) platform->StepSOI(2); } } switch (whichButton) { case 0: // DEP - JPO if (g_bRealisticAvionics) { ToggleHsdState (HSDCEN); } break; case 1: // DCPL - JPO if (g_bRealisticAvionics) { ToggleHsdState (HSDCPL); } break; //MI case 2: if(g_bRealisticAvionics) ToggleHSDZoom(); break; case 4: // CTRL if (g_bRealisticAvionics) { ToggleHsdState (HSDCNTL); } break; case 6: // FRZ - JPO if (g_bRealisticAvionics) { frz_x = platform->XPos(); frz_y = platform->YPos(); frz_dir = platform->Yaw(); ToggleHsdState(HSDFRZ); } break; case 10: if (g_bRealisticAvionics) { MfdDrawable::PushButton(whichButton, whichMFD); } break; case 11: // SMS if (g_bRealisticAvionics) MfdDrawable::PushButton(whichButton, whichMFD); else MfdDisplay[whichMFD]->SetNewMode(MFDClass::SMSMode); break; case 12: // jpo if (g_bRealisticAvionics) MfdDrawable::PushButton(whichButton, whichMFD); break; case 13: // HSD if (g_bRealisticAvionics) MfdDrawable::PushButton(whichButton, whichMFD); else MfdDisplay[whichMFD]->SetNewMode(MFDClass::MfdMenu); break; case 14: // SWAP if (g_bRealisticAvionics) MfdDrawable::PushButton(whichButton, whichMFD); else MFDSwapDisplays(); break; case 18: // Down if(!g_bRealisticAvionics) SimHSDRangeStepDown (0, KEY_DOWN, NULL); else { //MI if(HSDZoom == 0) SimHSDRangeStepDown (0, KEY_DOWN, NULL); } break; case 19: // UP if(!g_bRealisticAvionics) SimHSDRangeStepUp (0, KEY_DOWN, NULL); else { //MI if(HSDZoom == 0) SimHSDRangeStepUp (0, KEY_DOWN, NULL); } break; } } // STUFF Copied from Harm - now merged. JPO // JPO // This routine builds the initial list of preplanned targets. // this will remain unchanged if there is no dlink/jstar access void FireControlComputer::BuildPrePlanned() { FlightClass* theFlight = (FlightClass*)(platform->GetCampaignObject()); FalconPrivateList* knownEmmitters = NULL; GroundListElement* tmpElement; GroundListElement* curElement = NULL; FalconEntity* eHeader; // this is all based around waypoints. if (SimDriver.RunningCampaignOrTactical() && theFlight) knownEmmitters = theFlight->GetKnownEmitters(); if (knownEmmitters) { { VuListIterator elementWalker (knownEmmitters); eHeader = (FalconEntity*)elementWalker.GetFirst(); while (eHeader) { tmpElement = new GroundListElement (eHeader); if (grndlist == NULL) grndlist = tmpElement; else curElement->next = tmpElement; curElement = tmpElement; eHeader = (FalconEntity*)elementWalker.GetNext(); } } knownEmmitters->Unregister(); delete knownEmmitters; } nextDlUpdate = SimLibElapsedTime + CampaignSeconds * DATALINK_CYCLE; } // update - every so often from a JSTAR platform if available. void FireControlComputer::UpdatePlanned() { if (nextDlUpdate > SimLibElapsedTime) return; //Cobra This function was killing SAMs and threat rings on HSD //without it, everything is appearing as normal on the HSD. nextDlUpdate = SimLibElapsedTime + 5000/*CampaignSeconds * DATALINK_CYCLE*/; /*if (((AircraftClass*)platform)->mFaults->GetFault(FaultClass::dlnk_fault) || !((AircraftClass*)platform)->HasPower(AircraftClass::DLPower)) return;*/ // RV version // nextDlUpdate = SimLibElapsedTime + CampaignSeconds * DATALINK_CYCLE; //if (((AircraftClass*)platform)->mFaults->GetFault(FaultClass::dlnk_fault) || !((AircraftClass*)platform)->HasPower(AircraftClass::DLPower)) // return; FlightClass* theFlight = (FlightClass*)(platform->GetCampaignObject()); if (!theFlight) return; CampEntity e; VuListIterator myit(EmitterList); // see if we have a jstar. Flight jstar = theFlight->GetJSTARFlight(); Team us = theFlight->GetTeam(); // If we didn't find JSTAR do other search if (!jstar) { Unit nu, cf; VuListIterator new_myit(AllAirList); nu = (Unit) new_myit.GetFirst(); while (nu && !jstar) { cf = nu; nu = (Unit) new_myit.GetNext(); if (!cf->IsFlight() || cf->IsDead()) continue; if (cf->GetUnitMission() == AMIS_JSTAR && cf->GetTeam() == us && cf->GetUnitTOT()+5*CampaignMinutes < Camp_GetCurrentTime() && cf->GetUnitTOT()+95*CampaignMinutes > Camp_GetCurrentTime()) { // Check if JSTAR is in range for communication if (Distance(platform->XPos(), platform->YPos(), cf->XPos(), cf->YPos()) * FT_TO_NM <= 250.0f) { jstar = (Flight)cf; } } } } if ((!jstar)||(!g_bUseRC135)) { // completely new list please //cobra added here float myx = platform->XPos(); float myy = platform->YPos(); ClearPlanned(); GroundListElement* tmpElement; GroundListElement* curElement = NULL; for (e = (CampEntity) myit.GetFirst(); e; e = (Unit) myit.GetNext()) { if (e->GetTeam() != us /*&& e->GetSpotted(us) && (!e->IsUnit() || !((Unit)e)->Moving()) && e->GetElectronicDetectionRange(Air)*/) { float ex = e -> XPos(); float ey = e -> YPos(); if (Distance(ex,ey,myx,myy) * FT_TO_NM < 150/*EMITTERRANGE*/) { tmpElement = new GroundListElement(e); tmpElement->SetFlag(GroundListElement::DataLink);//Cobra nothing is using this... tmpElement->SetFlag(GroundListElement::RangeRing);//Cobra set the ring??? if (grndlist == NULL){ grndlist = tmpElement; } else { curElement->next = tmpElement; } curElement = tmpElement; } } } return; } //cobra added here int jstarDetectionChance = 0; if (jstar) { // This is a ELINT flight (e.g. RC-135) if (jstar->class_data->Role == ROLE_ELINT) jstarDetectionChance = 75; else // FRB - Give JSTAR SAM finder capabilities if (!g_bUseRC135) jstarDetectionChance = 75; else jstarDetectionChance = 25; } //CampEntity e; // VuListIterator myit(EmitterList); for (e = (CampEntity) myit.GetFirst(); e; e = (CampEntity) myit.GetNext()) { if (e->IsUnit() && e->IsBattalion() && rand()%100 > jstarDetectionChance) continue; if (e->IsGroundVehicle()) { GroundListElement* tmpElement = GetFirstGroundElement(); while (tmpElement) { if (tmpElement->BaseObject() == e) break; tmpElement = tmpElement->GetNext(); } if (!tmpElement) { tmpElement = new GroundListElement(e); AddGroundElement(tmpElement); } } } } // every so often - remove dead targets void FireControlComputer::PruneList() { GroundListElement **gpp; for (gpp = &grndlist; *gpp; ) { if ((*gpp)->BaseObject() == NULL) { // delete this one GroundListElement *gp = *gpp; *gpp = gp -> next; delete gp; } else gpp = &(*gpp)->next; } } GroundListElement::GroundListElement(FalconEntity* newEntity) { F4Assert (newEntity); baseObject = newEntity; VuReferenceEntity(newEntity); symbol = RadarDataTable[newEntity->GetRadarType()].RWRsymbol; if (newEntity->IsCampaign()) range = (float)((CampBaseClass*)newEntity)->GetAproxWeaponRange(Air); else range = 0; flags = RangeRing; next = NULL; lastHit = SimLibElapsedTime; } GroundListElement::~GroundListElement() { VuDeReferenceEntity(baseObject); } void GroundListElement::HandoffBaseObject() { FalconEntity *newBase; if (baseObject == NULL) return; newBase = SimCampHandoff( baseObject, HANDOFF_RADAR); if (newBase != baseObject) { VuDeReferenceEntity(baseObject); baseObject = newBase; if (baseObject) { VuReferenceEntity(baseObject); } } } void FireControlComputer::ClearPlanned() { GroundListElement* tmpElement; while (grndlist) { tmpElement = grndlist; grndlist = tmpElement->next; delete tmpElement; } } MASTERMODES FireControlComputer::GetMainMasterMode() { switch (masterMode) { case AAGun: case Missile: return MM_AA; case ILS: case Nav: default: return MM_NAV; case AirGroundBomb: case AirGroundRocket: case AirGroundMissile: case AirGroundHARM: case AirGroundLaser: case AirGroundCamera: case AGGun: return MM_AG; //case Gun: //if (subMode == STRAF) // return MM_AG; //else return MM_AA; case Dogfight: return MM_DGFT; case MissileOverride: return MM_MSL; } } int FireControlComputer::LastMissileWillMiss(float range) { /* if (lastMissileImpactTime >0 && range > missileRMax ) { return 1; } else return 0; */ //me123 if the predicted total TOF is over xx seconds the missile is considered out of energy if (lastMissileImpactTime >0 && //me123 let's make sure there is a missile in the air lastMissileImpactTime - ((lastMissileShootTime - SimLibElapsedTime) /1000) >= 80) return 1; return 0; } float FireControlComputer::Aim120ASECRadius(float range) { float asecradius = 0.6f; static const float bestmaxrange = 0.8f; // upper bound if (!g_bRealisticAvionics) return asecradius; if (range > bestmaxrange*missileRMax) { // above best range float dr = (range - bestmaxrange*missileRMax) / (0.2f*missileRMax); dr = 1.0f - dr; asecradius *= dr; } else if (range < (missileRneMax - missileRneMin)/2.0f) { float dr = (range - missileRMin); dr /= (missileRneMax - missileRneMin)/2.0f - missileRMin; asecradius *= dr; } //MI make the size dependant on missile mode if(Sms && Sms->curWeapon && ((MissileClass*)Sms->GetCurrentWeapon())->isSlave) asecradius = max(min(0.3f, asecradius), 0.1f); else asecradius = max(min(0.6f, asecradius), 0.1f); return asecradius; } // MLR - SetMasterMode() no longer finds matching weapons if the currently // selected weapon doesn't match the mastermode. // However - SMM() will change HPs when Master Modes change. void FireControlComputer::SetMasterMode (FCCMasterMode newMode) { RadarClass* theRadar = (RadarClass*) FindSensor (platform, SensorClass::Radar); FCCMasterMode oldMode; HarmTargetingPod* harmPod = (HarmTargetingPod*) FindSensor (platform, SensorClass::HTS); /* appears to not be needed anymore if( playerFCC && (masterMode == Dogfight || masterMode == MissileOverride) && newMode != MissileOverride && newMode != Dogfight && (Sms->curWeaponType == wtAim9 || Sms->curWeaponType == wtAim120 )) // MLR 1/19/2004 - put these two in parenthesis { if ( masterMode == MissileOverride ) weaponMisOvrdMode = Sms->curWeaponType; else if ( masterMode == Dogfight ) weaponDogOvrdMode = Sms->curWeaponType; else weaponNoOvrdMode = Sms->curWeaponType; } */ // Nav only if Amux and Bmux failed, no change if FCC fail if(playerFCC && ( ( ((AircraftClass*)platform)->mFaults->GetFault(FaultClass::fcc_fault) ) || ( ((AircraftClass*)platform)->mFaults->GetFault(FaultClass::amux_fault) && ((AircraftClass*)platform)->mFaults->GetFault(FaultClass::bmux_fault) && newMode != Nav ) ) ) return; // It has been stated (by Leon R) that changing modes while releasing weapons is bad, so... if (bombPickle) { return; } switch (masterMode) { case ClearOveride: if (theRadar) theRadar->ClearOverride(); break; // Clear any holdouts from previous modes case AirGroundHARM: ((AircraftClass*)platform)->SetTarget (NULL); break; } oldMode = masterMode; if (masterMode != Dogfight && masterMode != MissileOverride) masterMode = newMode;//me123 int isAI = !playerFCC || ( playerFCC && ((AircraftClass *)Sms->Ownship())->AutopilotType() == AircraftClass::CombatAP) ; switch (masterMode) { case Dogfight: // Clear out any non-air-to-air targets we had locked. if (oldMode != Dogfight && oldMode != Missile && oldMode != MissileOverride) ClearCurrentTarget(); //if (oldMode != Dogfight)// MLR 4/11/2004 - I'ld like to remove these, but the AI still calls SMM() directly //Sms->SetCurrentHpByWeaponId(lastDogfightWId); // Sms->SetCurrentHardPoint(lastDogfightHp); postDrop = FALSE; //MI changed so it remembers last gun submode too if(!g_bRealisticAvionics) SetSubMode (EEGS); else SetSubMode(lastDogfightGunSubMode); if(isAI && !WeaponClassMatchesMaster(Sms->curWeaponClass)) if(!Sms->FindWeaponType (wtAim9)) Sms->FindWeaponType(wtAim120); switch(Sms->curWeaponType) { case wtAim9: SetDgftSubMode(Aim9); break; case wtAim120: SetDgftSubMode(Aim120); break; } if (theRadar && oldMode != Dogfight) { theRadar->SetSRMOverride(); } if (TheHud && playerFCC) { TheHud->headingPos = HudClass::Low; } break; case MissileOverride://me123 multi changes here //strcpy (subModeString, "MSL"); // JPG 20 Jan 04 // Clear out any non-air-to-air targets we had locked. if (oldMode != Dogfight && oldMode != Missile && oldMode != MissileOverride) ClearCurrentTarget(); postDrop = FALSE; //if (oldMode != MissileOverride)// MLR 4/11/2004 - I'ld like to remove these, but the AI still calls SMM() directly // Sms->SetCurrentHardPoint(lastMissileOverrideHp); // Sms->SetCurrentHpByWeaponId(lastMissileOverrideWId); if(isAI && !WeaponClassMatchesMaster(Sms->curWeaponClass)) if(!Sms->FindWeaponType (wtAim120)) Sms->FindWeaponType (wtAim9); switch(Sms->curWeaponType) { case wtAim9: SetSubMode(Aim9); SetMrmSubMode(Aim9); break; case wtAim120: SetSubMode(Aim120); SetMrmSubMode(Aim120); break; } if (theRadar ) { theRadar->SetMRMOverride(); } if (TheHud && playerFCC) TheHud->headingPos = HudClass::Low; break; case Missile: // Clear out any non-air-to-air targets we had locked. if (oldMode != Dogfight && oldMode != MissileOverride) ClearCurrentTarget(); postDrop = FALSE; //if(oldMode != masterMode) // MLR 4/11/2004 - I'ld like to remove these, but the AI still calls SMM() directly // Sms->SetCurrentHardPoint(lastAirAirHp); //MonoPrint("FCC:SetMasterMode - 1. CurrentWeaponType=%d\n",Sms->GetCurrentWeaponType()); // make sure the AI get a proper weapon if(isAI && !WeaponClassMatchesMaster(Sms->curWeaponClass)) if(!Sms->FindWeaponType (wtAim120)) Sms->FindWeaponType (wtAim9); switch(Sms->GetCurrentWeaponType()) { case wtAim120: SetSubMode(Aim120); break; case wtAim9: SetSubMode(Aim9); break; } if (TheHud && playerFCC) TheHud->headingPos = HudClass::Low; break; case ILS: // Clear out any previous targets we had locked. ClearCurrentTarget(); Sms->SetWeaponType (wtNone); Sms->FindWeaponClass (wcNoWpn); if (TheHud && playerFCC) TheHud->headingPos = HudClass::High; platform->SOIManager (SimVehicleClass::SOI_RADAR); break; case Nav: // Clear out any previous targets we had locked. strcpy (subModeString, "NAV"); ClearCurrentTarget(); Sms->SetWeaponType (wtNone); Sms->FindWeaponClass (wcNoWpn); SetSubMode (ETE); releaseConsent = FALSE; postDrop = FALSE; preDesignate = TRUE; postDrop = FALSE; bombPickle = FALSE; // Find currentwaypoint if (TheHud && playerFCC) { TheHud->headingPos = HudClass::Low; } // SOI is RADAR in NAV //Cobra test Double here since ETE above sets SOI_RADAR //platform->SOIManager (SimVehicleClass::SOI_RADAR); break; case AirGroundBomb: // Clear out any previous targets we had locked. ClearCurrentTarget(); preDesignate = TRUE; postDrop = FALSE; inRange = TRUE; if(isAI && !WeaponClassMatchesMaster(Sms->curWeaponClass)) Sms->FindWeaponClass (wcBombWpn); if(g_bRealisticAvionics) { SetSubMode(Sms->GetAGBSubMode()); } else { SetSubMode(CCIP); } //if(playerFCC) //{ // Sms->drawable->SetDisplayMode(SmsDrawable::Wpn); ///} if (TheHud && playerFCC) TheHud->headingPos = HudClass::High; break; case AirGroundRocket: // Clear out any previous targets we had locked. ClearCurrentTarget(); preDesignate = TRUE; postDrop = FALSE; inRange = TRUE; if(isAI && !WeaponClassMatchesMaster(Sms->curWeaponClass)) Sms->FindWeaponClass (wcRocketWpn); SetSubMode (OBSOLETERCKT); /* if(!playerFCC) { SetSubMode (OBSOLETERCKT); } else { if(g_bRealisticAvionics) { SetSubMode (Sms->GetAGBSubMode()); } else { SetSubMode (OBSOLETERCKT); } } */ if (TheHud && playerFCC) TheHud->headingPos = HudClass::High; break; case AirGroundMissile: // Clear out any previous targets we had locked. ClearCurrentTarget(); preDesignate = TRUE; postDrop = FALSE; inRange = TRUE; missileTarget = FALSE; if(isAI && !WeaponClassMatchesMaster(Sms->curWeaponClass)) Sms->FindWeaponType (wtAgm65); if(WeaponClassMatchesMaster(Sms->curWeaponClass)) { if(playerFCC) { this-> Sms->StepMavSubMode(TRUE); // TRUE means initial step } /* if (PlayerOptions.GetAvionicsType() == ATRealistic || PlayerOptions.GetAvionicsType() == ATRealisticAV) SetSubMode (BSGT); else SetSubMode (SLAVE); */ } else { if(playerFCC) { Sms->drawable->SetDisplayMode(SmsDrawable::Wpn); } } /* if (Sms->curWeaponClass != wcAgmWpn) { if (Sms->FindWeaponClass (wcAgmWpn) && Sms->CurHardpoint() >= 0) // JB 010805 Possible CTD check curhardpoint { Sms->SetWeaponType(Sms->hardPoint[Sms->CurHardpoint()]->GetWeaponType()); switch (Sms->curWeaponType) { case wtAgm65: // M.N. added full realism mode if (PlayerOptions.GetAvionicsType() == ATRealistic || PlayerOptions.GetAvionicsType() == ATRealisticAV) SetSubMode (BSGT); else SetSubMode (SLAVE); break; } } else { Sms->SetWeaponType (wtNone); if( playerFCC ) { Sms->GetNextWeapon(wdGround); Sms->drawable->SetDisplayMode(SmsDrawable::Wpn); } } } */ if (TheHud && playerFCC) TheHud->headingPos = HudClass::High; break; case AirGroundHARM: // Clear out any previous targets we had locked. ClearCurrentTarget(); preDesignate = TRUE; postDrop = FALSE; // RV - I-Hawk - Get into the right HARM modes if( isAI && !WeaponClassMatchesMaster(Sms->curWeaponClass) ) { Sms->FindWeaponType (wtAgm88); } if ( isAI ) { harmPod->SetSubMode ( HarmTargetingPod::HAS ); harmPod->SetHandedoff ( true ); // AI doesn't need any target hadnoff delay } else { harmPod->SetSubMode( HarmTargetingPod::HarmModeChooser ); } /* if (Sms->curWeaponClass != wcHARMWpn) { if (Sms->FindWeaponClass (wcHARMWpn, FALSE) && Sms->CurHardpoint() >= 0) // JB 010805 Possible CTD check curhardpoint { Sms->SetWeaponType(Sms->hardPoint[Sms->CurHardpoint()]->GetWeaponType()); switch (Sms->curWeaponType) { case wtAgm88: SetSubMode (HTS); break; } } else { Sms->SetWeaponType (wtNone); if( playerFCC ) { Sms->GetNextWeapon(wdGround); Sms->drawable->SetDisplayMode(SmsDrawable::Wpn); } } } */ if (TheHud && playerFCC) { TheHud->headingPos = HudClass::High; } break; case AirGroundLaser: // Clear out any previous targets we had locked. ClearCurrentTarget(); preDesignate = TRUE; postDrop = FALSE; if(isAI && !WeaponClassMatchesMaster(Sms->curWeaponClass)) Sms->FindWeaponType (wtGBU); if(WeaponClassMatchesMaster(Sms->curWeaponClass)) { if(!g_bRealisticAvionics) { //Mi this isn't true... doc states you start off in SLAVE if (PlayerOptions.GetAvionicsType() == ATRealistic) SetSubMode (BSGT); else SetSubMode (SLAVE); } else { InhibitFire = FALSE; // M.N. added full realism mode if( PlayerOptions.GetAvionicsType() != ATRealistic && PlayerOptions.GetAvionicsType() != ATRealisticAV) SetSubMode (BSGT); else SetSubMode (SLAVE); } } else { if( playerFCC ) { Sms->drawable->SetDisplayMode(SmsDrawable::Wpn); } } /* if (Sms->curWeaponClass != wcGbuWpn) { if (Sms->FindWeaponClass (wcGbuWpn, FALSE) && Sms->CurHardpoint() >= 0) // JB 010805 Possible CTD check curhardpoint { Sms->SetWeaponType(Sms->hardPoint[Sms->CurHardpoint()]->GetWeaponType()); switch (Sms->curWeaponType) { case wtGBU: //Mi this isn't true... doc states you start off in SLAVE if(!g_bRealisticAvionics) { if (PlayerOptions.GetAvionicsType() == ATRealistic) SetSubMode (BSGT); else SetSubMode (SLAVE); } else { InhibitFire = FALSE; // M.N. added full realism mode if(PlayerOptions.GetAvionicsType() != ATRealistic && PlayerOptions.GetAvionicsType() != ATRealisticAV) SetSubMode (BSGT); else SetSubMode (SLAVE); } break; } } else { Sms->SetWeaponType (wtNone); if( playerFCC ) { Sms->GetNextWeapon(wdGround); Sms->drawable->SetDisplayMode(SmsDrawable::Wpn); } } } */ if (TheHud && playerFCC) TheHud->headingPos = HudClass::High; break; case AirGroundCamera: // Clear out any previous targets we had locked. ClearCurrentTarget(); preDesignate = TRUE; postDrop = FALSE; if(isAI && !WeaponClassMatchesMaster(Sms->curWeaponClass)) Sms->FindWeaponClass (wcCamera); if(WeaponClassMatchesMaster(Sms->curWeaponClass)) { SetSubMode(PRE); // MLR 2/14/2004 - who knows if this it correct } else { Sms->drawable->SetDisplayMode(SmsDrawable::Wpn); } /* if (Sms->curWeaponClass != wcCamera) { if (Sms->FindWeaponClass (wcCamera, FALSE) && Sms->CurHardpoint() >= 0) // JB 010805 Possible CTD check curhardpoint { Sms->SetWeaponType(Sms->hardPoint[Sms->CurHardpoint()]->GetWeaponType()); } else { Sms->SetWeaponType (wtNone); if( playerFCC ) { Sms->GetNextWeapon(wdGround); Sms->drawable->SetDisplayMode(SmsDrawable::Wpn); } } } */ if (TheHud && playerFCC) TheHud->headingPos = HudClass::High; strcpy (subModeString, "RPOD"); platform->SOIManager (SimVehicleClass::SOI_RADAR); break; } // MLR 2/1/2004 - we check this last, because sometimes we fall back to gun mode in the switch above if(masterMode==AAGun) { if(g_bRealisticAvionics) SetSubMode(lastAirAirGunSubMode); else SetSubMode(EEGS); if(!WeaponClassMatchesMaster(Sms->curWeaponClass)) Sms->FindWeaponType (wtGuns); // we only want to store this as the previous weapon if g_bWeaponStepToGun is TRUE //if(g_bWeaponStepToGun) // lastAirAirHp = Sms->GetCurrentWeaponHardpoint(); //lastAirAirWId=Sms->GetCurrentWeaponId(); if (TheHud && playerFCC) TheHud->headingPos = HudClass::Low; } if(masterMode==AGGun) { { SetSubMode(STRAF); } if(!WeaponClassMatchesMaster(Sms->curWeaponClass)) Sms->FindWeaponType (wtGuns); // we only want to store this as the previous weapon if g_bWeaponStepToGun is TRUE //if(g_bWeaponStepToGun) // lastAirGroundHp = Sms->GetCurrentWeaponHardpoint(); //lastAirGroundWId=Sms->GetCurrentWeaponId(); //>GetCurrentWeaponHardpoint(); if (TheHud && playerFCC) TheHud->headingPos = HudClass::High; } // store master mode, used when leaving DF or MO. switch(masterMode) { case Dogfight: case MissileOverride: break; default: lastMasterMode = masterMode; } UpdateWeaponPtr(); UpdateLastData(); } void FireControlComputer::UpdateLastData(void) { switch(masterMode) { case ILS: case Nav: lastNavMasterMode = masterMode; break; case Dogfight: lastDogfightHp = Sms->GetCurrentWeaponHardpoint(); break; case MissileOverride: lastMissileOverrideHp = Sms->GetCurrentWeaponHardpoint(); break; case AAGun: break; //if(!g_bWeaponStepToGun) //{ // break; //} // intentionally fall thru case Missile: //lastAaMasterMode = masterMode; lastAirAirHp = Sms->GetCurrentWeaponHardpoint(); break; case AGGun: break; //if(!g_bWeaponStepToGun) //{ // break; //} // intentionally fall thru case AirGroundBomb: case AirGroundRocket: case AirGroundMissile: case AirGroundHARM: case AirGroundLaser: case AirGroundCamera: lastAgMasterMode = masterMode; lastAirGroundHp = Sms->GetCurrentWeaponHardpoint(); break; } } int FireControlComputer::WeaponClassMatchesMaster(WeaponClass wc) { switch(masterMode) { case Missile: if(wc==wcAimWpn || wc==wcGunWpn) return 1; return 0; case Dogfight: case MissileOverride: if(wc==wcAimWpn ) return 1; return 0; case AAGun: case AGGun: if(wc==wcGunWpn) return 1; return 0; case AirGroundMissile: if(wc==wcAgmWpn) return 1; return 0; break; case AirGroundBomb: if(wc==wcBombWpn)// || wc==wcRocketWpn) return 1; return 0; break; case AirGroundRocket: if(wc==wcRocketWpn)// || wc==wcRocketWpn) return 1; return 0; break; case AirGroundHARM: if(wc==wcHARMWpn) return 1; return 0; break; case AirGroundLaser: if(wc==wcGbuWpn) return 1; return 0; break; case AirGroundCamera: if(wc==wcCamera) return 1; return 0; break; /* case ClearOveride: if(wc==) return 1; return 0; break; */ } return 0; } int FireControlComputer::CanStepToWeaponClass(WeaponClass wc) { switch(masterMode) { case AAGun: if( ( wc==wcAimWpn && g_bWeaponStepToGun) || wc==wcGunWpn ) return 1; return 0; case Missile: if( wc==wcAimWpn || (wc==wcGunWpn && g_bWeaponStepToGun) ) return 1; return 0; case MissileOverride: case Dogfight: if(wc==wcAimWpn ) return 1; return 0; case AGGun: if( ( ( wc==wcAgmWpn || wc==wcBombWpn || wc==wcRocketWpn || wc==wcHARMWpn || wc==wcGbuWpn || wc==wcCamera ) && g_bWeaponStepToGun) || wc==wcGunWpn ) return 1; return 0; case AirGroundBomb: case AirGroundRocket: case AirGroundMissile: case AirGroundHARM: case AirGroundLaser: case AirGroundCamera: if( wc==wcAgmWpn || wc==wcBombWpn || wc==wcRocketWpn || wc==wcHARMWpn || wc==wcGbuWpn || wc==wcCamera || ( wc==wcGunWpn && g_bWeaponStepToGun ) ) return 1; return 0; } return 0; /* switch(GetMainMasterMode()) { case MM_AA: if(g_bWeaponStepToGun) { if( wc==wcAimWpn || wc==wcGunWpn ) return 1; } else { } return 0; case MM_DGFT: case MM_MSL: if(wc==wcAimWpn ) return 1; return 0; case MM_AG: if( wc==wcAgmWpn || wc==wcBombWpn || wc==wcRocketWpn || wc==wcHARMWpn || wc==wcGbuWpn || wc==wcCamera || ( wc==wcGunWpn && g_bWeaponStepToGun ) ) return 1; return 0; } return 0; */ } void FireControlComputer::SetAAMasterModeForCurrentWeapon(void) { //UpdateWeaponPtr(); FCCMasterMode newmode = masterMode; if(Sms->GetCurrentWeaponHardpoint() == -1) { // maybe we've jetted the weapons, and the Sms curHardpoint is -1 // anyhow, find what we were using before Sms->SetCurrentHardPoint(lastAirAirHp,1); } inAAGunMode = 0; switch(Sms->curWeaponClass) { case wcAimWpn: newmode = Missile; break; case wcGunWpn: inAAGunMode = 1; newmode = AAGun; break; } SetMasterMode(newmode); } void FireControlComputer::SetAGMasterModeForCurrentWeapon(void) { if(Sms->GetCurrentWeaponHardpoint() == -1) { // maybe we've jetted the weapons, and the Sms curHardpoint is -1 // anyhow, find what we were using before Sms->SetCurrentHardPoint(lastAirGroundHp,1); } //UpdateWeaponPtr(); if( Sms->CurHardpoint()<0 ) { // whoops return; } else if(!Sms->hardPoint[Sms->CurHardpoint()]) return; FCCMasterMode newmode = masterMode; inAGGunMode = 0; switch(Sms->hardPoint[Sms->CurHardpoint()]->GetWeaponClass()) { case wcRocketWpn: newmode = AirGroundRocket; break; case wcBombWpn: newmode = AirGroundBomb; break; case wcGunWpn: inAGGunMode = 1; newmode = AGGun; break; case wcAgmWpn: newmode = AirGroundMissile; break; case wcHARMWpn: newmode = AirGroundHARM; break; case wcGbuWpn: newmode = AirGroundLaser; break; case wcCamera: newmode = AirGroundCamera; break; default: newmode = AirGroundBomb; /* case wcSamWpn: break; case wcNoWpn: break; case wcECM: break; case wcTank: break; */ } SetMasterMode(newmode); } int FireControlComputer::IsInAAMasterMode(void) { return(GetMainMasterMode()==MM_AA); } int FireControlComputer::IsInAGMasterMode(void) { return(GetMainMasterMode()==MM_AG); } void FireControlComputer::EnterAAMasterMode(void) { if(inAAGunMode) { // go to gun mode if( Sms->FindWeaponClass(wcGunWpn, TRUE) ) SetMasterMode(AAGun); } else { Sms->SetCurrentHardPoint(lastAirAirHp); //SetMasterMode(lastAaMasterMode); SetMasterMode(Missile); } } void FireControlComputer::EnterAGMasterMode(void) { if(inAGGunMode) { // go to gun mode if( Sms->FindWeaponClass(wcGunWpn, TRUE) ) SetMasterMode(AGGun); } else { Sms->SetCurrentHardPoint(lastAirGroundHp); SetMasterMode(lastAgMasterMode); } } void FireControlComputer::EnterMissileOverrideMode(void) { Sms->SetCurrentHardPoint(lastMissileOverrideHp); SetMasterMode(MissileOverride); } void FireControlComputer::EnterDogfightMode(void) { Sms->SetCurrentHardPoint(lastDogfightHp); SetMasterMode(Dogfight); } void FireControlComputer::ToggleAAGunMode(void) { inAAGunMode = !inAAGunMode; EnterAAMasterMode(); } void FireControlComputer::ToggleAGGunMode(void) { inAGGunMode = !inAGGunMode; EnterAGMasterMode(); } void FireControlComputer::UpdateWeaponPtr(void) { // the fccWeaponPointer is ONLY used to access weapon data, impact prediction etc, it is NEVER fired. int wid; wid = Sms->GetCurrentWeaponId(); if(wid != fccWeaponId) { fccWeaponPtr.reset(); fccWeaponId = wid; if(fccWeaponId) { Falcon4EntityClassType *classPtr = GetWeaponF4CT(fccWeaponId); if(classPtr) { if ( classPtr->vuClassData.classInfo_[VU_TYPE] == TYPE_MISSILE || classPtr->vuClassData.classInfo_[VU_TYPE] == TYPE_ROCKET ){ fccWeaponPtr.reset(InitAMissile(Sms->Ownship(), fccWeaponId, 0)); } else { if ( classPtr->vuClassData.classInfo_[VU_TYPE] == TYPE_BOMB || ( classPtr->vuClassData.classInfo_[VU_TYPE] == TYPE_ELECTRONICS && classPtr->vuClassData.classInfo_[VU_CLASS] == CLASS_VEHICLE ) || ( classPtr->vuClassData.classInfo_[VU_TYPE] == TYPE_FUEL_TANK && classPtr->vuClassData.classInfo_[VU_STYPE] == STYPE_FUEL_TANK ) || ( classPtr->vuClassData.classInfo_[VU_TYPE] == TYPE_RECON && classPtr->vuClassData.classInfo_[VU_STYPE] == STYPE_CAMERA ) || ( classPtr->vuClassData.classInfo_[VU_TYPE] == TYPE_LAUNCHER && classPtr->vuClassData.classInfo_[VU_STYPE] == STYPE_ROCKET ) ){ fccWeaponPtr.reset(InitABomb(Sms->Ownship(), fccWeaponId, 0)); } } } if (fccWeaponPtr && fccWeaponPtr->IsLauncher()){ wid = ((BombClass *)fccWeaponPtr.get())->LauGetWeaponId(); if(wid != rocketWeaponId){ if(wid){ rocketPointer.reset((MissileClass *)InitAMissile(Sms->Ownship(), wid, 0)); } else{ rocketPointer.reset(0); } rocketWeaponId = wid; } } } } } void FireControlComputer::SetSms(SMSClass *SMS) { Sms = SMS; // setup default HPs for MMs // dogfight if(!Sms->FindWeaponType (wtAim9)) Sms->FindWeaponType(wtAim120); lastDogfightHp = Sms->CurHardpoint(); // missile override & aamm if(!Sms->FindWeaponType (wtAim120)) Sms->FindWeaponType(wtAim9); lastMissileOverrideHp = Sms->CurHardpoint(); lastAirAirHp = Sms->CurHardpoint(); // agmm /*if(!Sms->FindWeaponType (wtAgm88)) if(!Sms->FindWeaponType (wtAgm65)) if(!Sms->FindWeaponType (wtGBU)) if(!Sms->FindWeaponType (wtGPS)) if(!Sms->FindWeaponType (wtMk84)) if(!Sms->FindWeaponType (wtMk82)) Sms->FindWeaponClass (wcRocketWpn); // used to be: Sms->FindWeaponType (wtLAU); but jammers are marks as wtLAU :rolleyes:*/ //Cobra if(!Sms->FindWeaponType (wtAgm88)) if(!Sms->FindWeaponType (wtAgm65)) if(!Sms->FindWeaponType (wtGBU)) if(!Sms->FindWeaponType (wtGPS)) if(!Sms->FindWeaponType (wtMk84)) if(!Sms->FindWeaponType (wtMk82)) if(!Sms->FindWeaponClass (wcRocketWpn)) Sms->FindWeaponClass (wcGunWpn); //end if(Sms->CurHardpoint() > 0) { switch(Sms->hardPoint[Sms->CurHardpoint()]->GetWeaponClass()) { case wcRocketWpn: lastAgMasterMode = AirGroundRocket; break; case wcBombWpn: lastAgMasterMode = AirGroundBomb; break; case wcAgmWpn: lastAgMasterMode = AirGroundMissile; break; case wcHARMWpn: lastAgMasterMode = AirGroundHARM; break; case wcGbuWpn: lastAgMasterMode = AirGroundLaser; break; case wcCamera: lastAgMasterMode = AirGroundCamera; break; default: lastAgMasterMode = AirGroundBomb; } } lastAirGroundHp = Sms->CurHardpoint(); // Set us up in Gun mode if we have no AA or AG stores if(lastAirAirHp == -1) { inAAGunMode = 1; } //Cobra change to HP 0 for Gun from -1 if(lastAirGroundHp == 0) { inAGGunMode = 1; } } // RV - I-Hawk - Added function bool FireControlComputer::AllowMaddog() { if ( Sms && Sms->GetCurrentWeaponType() == wtAim120 ) { MissileClass* currMissile = (MissileClass*)Sms->GetCurrentWeapon(); if ( !targetPtr && currMissile && currMissile->isSlave ) { return false; } } return true; }
24.072114
192
0.656846
IsraelyFlightSimulator
dcb191f58b8f8965632d152292210f1c119e9587
847
cpp
C++
Sid's Levels/Level - 2/Recursion/Subset2.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
14
2021-08-22T18:21:14.000Z
2022-03-08T12:04:23.000Z
Sid's Levels/Level - 2/Recursion/Subset2.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
1
2021-10-17T18:47:17.000Z
2021-10-17T18:47:17.000Z
Sid's Levels/Level - 2/Recursion/Subset2.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
5
2021-09-01T08:21:12.000Z
2022-03-09T12:13:39.000Z
class Solution { public: void subsets(vector<int> nums, set<vector<int>> &s, int i, vector<int> r) { if(i == nums.size()) { sort(r.begin(), r.end()); s.insert(r); return; } else { subsets(nums, s, i+1, r); r.push_back(nums[i]); subsets(nums, s, i+1, r); } } vector<vector<int>> subsetsWithDup(vector<int>& nums) { //OM GAN GANAPATHAYE NAMO NAMAH //JAI SHRI RAM //JAI BAJRANGBALI //AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA set<vector<int>> s; vector<int> r; subsets(nums, s, 0, r); vector<vector<int>> res; for(auto it = s.begin(); it != s.end(); it++) res.push_back(*it); return res; } };
26.46875
77
0.475797
Tiger-Team-01
dcb2dc65f5d0c224f199ea103597941bc05e14bf
11,359
cpp
C++
ARM/Nordic/exemples/BlueIOThingy/BlueIOMPU9250.cpp
tmaltesen/IOsonata
3ada9216305653670fccfca8fd53c6597ace8f12
[ "MIT" ]
94
2015-03-12T14:49:43.000Z
2021-08-05T00:43:50.000Z
ARM/Nordic/exemples/BlueIOThingy/BlueIOMPU9250.cpp
tmaltesen/IOsonata
3ada9216305653670fccfca8fd53c6597ace8f12
[ "MIT" ]
3
2017-06-05T20:36:09.000Z
2021-05-08T21:39:48.000Z
ARM/Nordic/exemples/BlueIOThingy/BlueIOMPU9250.cpp
tmaltesen/IOsonata
3ada9216305653670fccfca8fd53c6597ace8f12
[ "MIT" ]
24
2015-04-22T20:35:28.000Z
2022-01-10T13:08:40.000Z
/* * BLueIOMPU9250.h * * Created on: Jul 25, 2018 * Author: hoan */ #include "app_util_platform.h" #include "app_scheduler.h" #include "istddef.h" #include "ble_app.h" #include "ble_service.h" #include "device_intrf.h" #include "coredev/spi.h" #include "coredev/timer.h" #include "sensors/agm_mpu9250.h" #include "imu/imu_mpu9250.h" #include "idelay.h" #include "board.h" #include "BlueIOThingy.h" #include "BlueIOMPU9250.h" static const ACCELSENSOR_CFG s_AccelCfg = { .DevAddr = 0, .OpMode = SENSOR_OPMODE_CONTINUOUS, .Freq = 50000, .Scale = 2, .FltrFreq = 0, .bInter = true, .IntPol = DEVINTR_POL_LOW, }; static const GYROSENSOR_CFG s_GyroCfg = { .DevAddr = 0, .OpMode = SENSOR_OPMODE_CONTINUOUS, .Freq = 50000, .Sensitivity = 10, .FltrFreq = 200, }; static const MAGSENSOR_CFG s_MagCfg = { .DevAddr = 0, .OpMode = SENSOR_OPMODE_CONTINUOUS,//SENSOR_OPMODE_SINGLE, .Freq = 50000, .Precision = MAGSENSOR_PRECISION_HIGH, }; AgmMpu9250 g_Mpu9250; static void ImuEvtHandler(Device * const pDev, DEV_EVT Evt); static const IMU_CFG s_ImuCfg = { .EvtHandler = ImuEvtHandler }; static ImuMpu9250 s_Imu; static Timer * s_pTimer; static uint32_t s_MotionFeature = 0; int8_t g_AlignMatrix[9] = { 0, 1, 0, -1, 0, 0, 0, 0, -1 }; #if 0 /**@brief Acclerometer rotation matrix. * * @note Accellerometer inverted to get positive readings when axis is aligned with g (down). */ static struct platform_data_s s_accel_pdata = { .orientation = { 0, 1, 0, -1, 0, 0, 0, 0, -1} }; /* The sensors can be mounted onto the board in any orientation. The mounting * matrix seen below tells the MPL how to rotate the raw data from the * driver(s). * TODO: The following matrices refer to the configuration on internal test * boards at Invensense. If needed, please modify the matrices to match the * chip-to-body matrix for your particular set up. */ #if 1 static struct platform_data_s gyro_pdata = { .orientation = { 0, 1, 0, -1, 0, 0, 0, 0, -1} }; #else // BLUEIO-TAG-EVIM static struct platform_data_s gyro_pdata = { .orientation = { 0, 1, 0, 1, 0, 0, 0, 0, 1} }; #endif #if defined MPU9150 || defined MPU9250 static struct platform_data_s compass_pdata = { #if 1 .orientation = { 1, 0, 0, 0, 1, 0, 0, 0, -1} #else .orientation = { 1, 0, 0, 0, -1, 0, 0, 0, -1} #endif }; #define COMPASS_ENABLED 1 #elif defined AK8975_SECONDARY static struct platform_data_s compass_pdata = { .orientation = {-1, 0, 0, 0, 1, 0, 0, 0,-1} }; #define COMPASS_ENABLED 1 #elif defined AK8963_SECONDARY static struct platform_data_s compass_pdata = { .orientation = {-1, 0, 0, 0,-1, 0, 0, 0, 1} }; #define COMPASS_ENABLED 1 #endif #endif void ImuRawDataSend(ACCELSENSOR_DATA &AccData, GYROSENSOR_DATA GyroData, MAGSENSOR_DATA &MagData); void ImuQuatDataSend(long Quat[4]); static void ImuDataChedHandler(void * p_event_data, uint16_t event_size) { ACCELSENSOR_DATA accdata; GYROSENSOR_DATA gyrodata; MAGSENSOR_DATA magdata; IMU_QUAT quat; long q[4]; s_Imu.Read(accdata); s_Imu.Read(gyrodata); s_Imu.Read(magdata); ImuRawDataSend(accdata, gyrodata, magdata); s_Imu.Read(quat); //q[0] = ((float)quat.Q[0] / 32768.0) * (float)(1<<30); //q[1] = ((float)quat.Q[1] / 32768.0) * (float)(1<<30); //q[2] = ((float)quat.Q[2] / 32768.0) * (float)(1<<30); //q[3] = ((float)quat.Q[3] / 32768.0) * (float)(1<<30); //q[0] = quat.Q[0] << 15; //q[1] = quat.Q[1] << 15; //q[2] = quat.Q[2] << 15; //q[3] = quat.Q[3] << 15; q[0] = quat.Q[0] * (1 << 30); q[1] = quat.Q[1] * (1 << 30); q[2] = quat.Q[2] * (1 << 30); q[3] = quat.Q[3] * (1 << 30); //printf("Quat %d: %d %d %d %d\r\n", quat.Timestamp, q[0], q[1], q[2], q[3]); ImuQuatDataSend(q); } static void ImuEvtHandler(Device * const pDev, DEV_EVT Evt) { switch (Evt) { case DEV_EVT_DATA_RDY: app_sched_event_put(NULL, 0, ImuDataChedHandler); //ImuDataChedHandler(NULL, 0); //g_MotSensor.Read(accdata); break; } } void MPU9250IntHandler(int IntNo) { s_Imu.IntHandler(); return; } void mpulib_data_handler_cb() { } void MPU9250EnableFeature(uint32_t Feature) { s_MotionFeature |= Feature; } static void mpulib_tap_cb(unsigned char direction, unsigned char count) { // ble_tms_tap_t tap; // tap.dir = direction; // tap.cnt = count; // BleSrvcCharNotify(GetImuSrvcInstance(), 2, (uint8_t*)&tap, sizeof(ble_tms_tap_t)); /* if (m_motion.features & DRV_MOTION_FEATURE_MASK_TAP) { drv_motion_evt_t evt = DRV_MOTION_EVT_TAP; uint8_t data[2] = {direction, count}; m_motion.evt_handler(&evt, data, sizeof(data)); } */ #ifdef MOTION_DEBUG switch (direction) { case TAP_X_UP: NRF_LOG_DEBUG("drv_motion: tap x+ "); break; case TAP_X_DOWN: NRF_LOG_DEBUG("drv_motion: tap x- "); break; case TAP_Y_UP: NRF_LOG_DEBUG("drv_motion: tap y+ "); break; case TAP_Y_DOWN: NRF_LOG_DEBUG("drv_motion: tap y- "); break; case TAP_Z_UP: NRF_LOG_DEBUG("drv_motion: tap z+ "); break; case TAP_Z_DOWN: NRF_LOG_DEBUG("drv_motion: tap z- "); break; default: return; } NRF_LOG_DEBUG("x%d\r\n", count); #endif } static void mpulib_orient_cb(unsigned char orientation) { BleSrvcCharNotify(GetImuSrvcInstance(), 2, &orientation, 1); /* if (m_motion.features & DRV_MOTION_FEATURE_MASK_ORIENTATION) { drv_motion_evt_t evt = DRV_MOTION_EVT_ORIENTATION; m_motion.evt_handler(&evt, &orientation, 1); } */ #ifdef MOTION_DEBUG switch (orientation) { case ANDROID_ORIENT_PORTRAIT: NRF_LOG_DEBUG("Portrait\r\n"); break; case ANDROID_ORIENT_LANDSCAPE: NRF_LOG_DEBUG("Landscape\r\n"); break; case ANDROID_ORIENT_REVERSE_PORTRAIT: NRF_LOG_DEBUG("Reverse Portrait\r\n"); break; case ANDROID_ORIENT_REVERSE_LANDSCAPE: NRF_LOG_DEBUG("Reverse Landscape\r\n"); break; default: return; } #endif } SPI *g_pSpi = NULL; bool MPU9250Init(DeviceIntrf * const pIntrF, Timer * const pTimer) { g_pSpi = (SPI*)pIntrF; s_pTimer = pTimer; bool res = g_Mpu9250.Init(s_AccelCfg, pIntrF, pTimer); if (res == false) return res; g_Mpu9250.Init(s_GyroCfg, NULL); g_Mpu9250.Init(s_MagCfg, NULL); IOPinConfig(BLUEIO_TAG_EVIM_IMU_INT_PORT, BLUEIO_TAG_EVIM_IMU_INT_PIN, BLUEIO_TAG_EVIM_IMU_INT_PINOP, IOPINDIR_INPUT, IOPINRES_PULLUP, IOPINTYPE_NORMAL); IOPinEnableInterrupt(BLUEIO_TAG_EVIM_IMU_INT_NO, 6, BLUEIO_TAG_EVIM_IMU_INT_PORT, BLUEIO_TAG_EVIM_IMU_INT_PIN, IOPINSENSE_LOW_TRANSITION, MPU9250IntHandler); // g_Mpu9250.Enable(); #if 0 while (1) { long l[3]; g_Mpu9250.UpdateData(); ACCELSENSOR_DATA accdata; g_Mpu9250.Read(accdata); l[0] = accdata.X; l[1] = accdata.Y; l[2] = accdata.Z; inv_build_accel(l, 0, accdata.Timestamp); } #endif s_Imu.Init(s_ImuCfg, &g_Mpu9250, &g_Mpu9250, &g_Mpu9250); s_Imu.SetAxisAlignmentMatrix(g_AlignMatrix); s_Imu.Quaternion(true, 6); //s_Imu.Compass(true); return true; } int Mpu9250AuxRead(uint8_t DevAddr, uint8_t *pCmdAddr, int CmdAddrLen, uint8_t *pBuff, int BuffLen) { int retval = 0; uint8_t regaddr; uint8_t d[8]; d[0] = MPU9250_AG_I2C_SLV0_ADDR; d[1] = DevAddr | MPU9250_AG_I2C_SLV0_ADDR_I2C_SLVO_RD; d[2] = *pCmdAddr; while (BuffLen > 0) { int cnt = min(15, BuffLen); d[3] = MPU9250_AG_I2C_SLV0_CTRL_I2C_SLV0_EN |cnt; g_pSpi->Write(0, d, 4, NULL, 0); // Delay require for transfer to complete usDelay(300 + (cnt << 4)); regaddr = MPU9250_AG_EXT_SENS_DATA_00; cnt = g_pSpi->Read(0, &regaddr, 1, pBuff, cnt); if (cnt <=0) break; pBuff += cnt; BuffLen -= cnt; retval += cnt; } return retval; } int Mpu9250AuxWrite(uint8_t DevAddr, uint8_t *pCmdAddr, int CmdAddrLen, uint8_t *pData, int DataLen) { int retval = 0; uint8_t regaddr; uint8_t d[8]; d[0] = MPU9250_AG_I2C_SLV0_ADDR; d[1] = DevAddr; d[2] = *pCmdAddr; d[3] = MPU9250_AG_I2C_SLV0_CTRL_I2C_SLV0_EN; while (DataLen > 0) { regaddr = MPU9250_AG_I2C_SLV0_DO; g_pSpi->Write(0, &regaddr, 1, pData, 1); g_pSpi->Write(0, d, 4, NULL, 0); d[2]++; pData++; DataLen--; retval++; } return retval; } /**@brief Function for writing to a MPU-9250 register. * * @param[in] slave_addr Slave address on the TWI bus. * @param[in] reg_addr Register address to write. * @param[in] length Length of the data to write. * @param[in] p_data Pointer to the data to write. * * @retval 0 if success. Else -1. */ int drv_mpu9250_write(unsigned char slave_addr, unsigned char reg_addr, unsigned char length, unsigned char const * p_data) { if (slave_addr != MPU9250_I2C_DEV_ADDR0 && slave_addr != MPU9250_I2C_DEV_ADDR1) { return Mpu9250AuxWrite(slave_addr, &reg_addr, 1, (uint8_t*)p_data, length) <= 0; } /* else { reg_addr &= 0x7F; return g_pSpi->Write(0, &reg_addr, 1, (uint8_t*)p_data, length) <= 0; }*/ return g_Mpu9250.Write(&reg_addr, 1, (uint8_t*)p_data, length) <= 0; } /**@brief Function for reading a MPU-9250 register. * * @param[in] slave_addr Slave address on the TWI bus. * @param[in] reg_addr Register address to read. * @param[in] length Length of the data to read. * @param[out] p_data Pointer to where the data should be stored. * * @retval 0 if success. Else -1. */ int drv_mpu9250_read(unsigned char slave_addr, unsigned char reg_addr, unsigned char length, unsigned char * p_data) { if (slave_addr != MPU9250_I2C_DEV_ADDR0 && slave_addr != MPU9250_I2C_DEV_ADDR1) { return Mpu9250AuxRead(slave_addr, &reg_addr, 1, (uint8_t*)p_data, length) <= 0; } /* else { reg_addr |= 0x80; return g_pSpi->Read(0, &reg_addr, 1, p_data, length) <= 0; }*/ return g_Mpu9250.Read(&reg_addr, 1, p_data, length) <= 0; } /**@brief Function for getting a timestamp in milliseconds. * * @param[out] p_count Pointer to the timestamp. * * @retval 0 if success. Else -1. */ int drv_mpu9250_ms_get(unsigned long * p_count) { *p_count = s_pTimer->uSecond() / 1000; return 0; } /**@brief Function for enabling and registering the MPU-9250 interrupt callback. * * @param[in] p_int_param Pointer to the interrupt parameter structure. * * @retval 0 if success. Else -1. */ int drv_mpu9250_int_register(struct int_param_s * p_int_param) { printf("drv_mpu9250_int_register\r\n"); IOPinConfig(BLUEIO_TAG_EVIM_IMU_INT_PORT, BLUEIO_TAG_EVIM_IMU_INT_PIN, BLUEIO_TAG_EVIM_IMU_INT_PINOP, IOPINDIR_INPUT, IOPINRES_PULLDOWN, IOPINTYPE_NORMAL); IOPinEnableInterrupt(BLUEIO_TAG_EVIM_IMU_INT_NO, 6, BLUEIO_TAG_EVIM_IMU_INT_PORT, BLUEIO_TAG_EVIM_IMU_INT_PIN, IOPINSENSE_LOW_TRANSITION, MPU9250IntHandler); return 0; }
24.58658
123
0.640725
tmaltesen
dcb6598eb2eb0d9e87bffeb93e34dd6533eadcf1
3,881
hpp
C++
src/sweepers/mc/fission_bank.hpp
tp-ntouran/mocc
77d386cdf341b1a860599ff7c6e4017d46e0b102
[ "Apache-2.0" ]
11
2016-03-31T17:46:15.000Z
2022-02-14T01:07:56.000Z
src/sweepers/mc/fission_bank.hpp
tp-ntouran/mocc
77d386cdf341b1a860599ff7c6e4017d46e0b102
[ "Apache-2.0" ]
3
2016-04-04T16:40:47.000Z
2019-10-16T22:22:54.000Z
src/sweepers/mc/fission_bank.hpp
tp-ntouran/mocc
77d386cdf341b1a860599ff7c6e4017d46e0b102
[ "Apache-2.0" ]
3
2019-10-16T22:20:15.000Z
2019-11-28T11:59:03.000Z
/* Copyright 2016 Mitchell Young 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. */ #pragma once #include <array> #include <iosfwd> #include <vector> #include "util/global_config.hpp" #include "util/pugifwd.hpp" #include "util/rng_lcg.hpp" #include "core/core_mesh.hpp" #include "core/geometry/geom.hpp" #include "core/xs_mesh.hpp" #include "particle.hpp" namespace mocc { namespace mc { /** * A FissionBank stores a sequence of fission sites. Nothing fancy */ class FissionBank { public: FissionBank(const CoreMesh &mesh); /** * \brief Construct a FissionBank by uniformly sampling fission sites. * * \param input XML node containing bounds of a 3-D box within which to * sample initial fission sites * \param n the number of initial sites to sample * \param mesh the \ref CoreMesh to use for initial sampling * \param xs_mesh the \ref XSMesh to use for initial sampling * \param rng a reference to the random number generator to be used for * sampling initial fission sites. * * This constructor initializes a \ref FissionBank using input specified in * an XML node. */ FissionBank(const pugi::xml_node &input, int n, const CoreMesh &mesh, const XSMesh &xs_mesh, RNG_LCG &rng); auto begin() { return sites_.begin(); } const auto begin() const { return sites_.cbegin(); } auto end() { return sites_.end(); } const auto end() const { return sites_.cend(); } int size() const { return sites_.size(); } /** * \brief Add a new fission site to the \ref FissionBank * * \param p a \ref Point3 for the location of the fission site * * This method adds a new fission site to the fission bank, and makes a * contribution to the total number of neutrons that were generated into * the bank. */ void push_back(Particle &p) { #pragma omp critical { sites_.push_back(p); total_fission_ += p.weight; } return; } /** * \brief Return the Shannon entropy of the fission bank. * * This is used to estimate the change in the spatial distribution of * fission sites from generation to generation. Observing little * variation in this metric throughout the active cycles lends some * confidence that the fission source distribution was well converged * before beginning active cycles. */ real_t shannon_entropy() const; /** * \brief Swap contents with another \ref FissionBank * * \param other the other \ref FissionBank to swap with */ void swap(FissionBank &other); const auto &operator[](unsigned i) const { return sites_[i]; } /** * \brief Clear the \ref FissionBank of all fission sites */ void clear() { #pragma omp single { sites_.clear(); total_fission_ = 0.0; } } void resize(unsigned int n, RNG_LCG &rng); real_t total_fission() const { return total_fission_; } friend std::ostream &operator<<(std::ostream &os, const FissionBank &bank); private: const CoreMesh &mesh_; std::vector<Particle> sites_; real_t total_fission_; }; } // namespace mc } // namespace mocc
25.532895
79
0.644164
tp-ntouran
dcb6a1644cf3c3baa909cf163721d1324f193a37
369
cpp
C++
src/23/zad3_9.cpp
AdamSiekierski/cpp
09b9a46b44ecce5cc1d6e0cb9d1c689b350563d5
[ "WTFPL" ]
2
2020-10-27T11:56:10.000Z
2020-10-27T12:42:32.000Z
src/23/zad3_9.cpp
AdamSiekierski/cpp
09b9a46b44ecce5cc1d6e0cb9d1c689b350563d5
[ "WTFPL" ]
null
null
null
src/23/zad3_9.cpp
AdamSiekierski/cpp
09b9a46b44ecce5cc1d6e0cb9d1c689b350563d5
[ "WTFPL" ]
null
null
null
#include <iostream> int main() { float x; int n; std::cout << "Podaj x i n: "; std::cin >> x >> n; switch (n) { case 1: std::cout << "y = " << sqrt(2 * x); break; case 2: std::cout << "y = " << (x * x) - 5; break; case 3: std::cout << "y = " << cos(x) + 1; break; default: std::cout << "y = " << 1; } return 0; }
13.178571
39
0.414634
AdamSiekierski
dcb7c38bae57b96d1ec8c378f65844df77ba0800
4,355
cc
C++
LibreOJ/2245.cc
DesZou/Eros
f49c9ce1dfe193de8199163286afc28ff8c52eef
[ "MIT" ]
1
2017-10-12T13:49:10.000Z
2017-10-12T13:49:10.000Z
LibreOJ/2245.cc
DesZou/Eros
f49c9ce1dfe193de8199163286afc28ff8c52eef
[ "MIT" ]
null
null
null
LibreOJ/2245.cc
DesZou/Eros
f49c9ce1dfe193de8199163286afc28ff8c52eef
[ "MIT" ]
1
2017-10-12T13:49:38.000Z
2017-10-12T13:49:38.000Z
/* * libreoj2245 * * LCT 维护最大值。 * 首先把边按 a 权值排序,从小到大加入,那么所需的 a 就是当前边的 a 。 * 然后用 LCT 维护从 1 到 n 的路径的 b 权值的最大值。 * 由于维护的是边权,我们要给边特别地开点,然后把本来应该相连的点连到两边。 * 动态维护一棵最小生成树,每次加入一条从 u 到 v 的路径的时候就把原来的 * u, v 之间的路径拉出来查询一下路径上的最大值,如果比当前的边要大, * 就把代表这条边的点从路径里拿出来,再把新边放进去。 * */ #include <cstdio> #include <algorithm> #include <iostream> const size_t Size = 5e4 + 5; const int Inf = -1u >> 1; template<class T> T max(const T &a, const T &b) { return a > b? a : b; } template<class T> T min(const T &a, const T &b) { return a < b? a : b; } template<class T> bool chkmin(T &a, const T &b) { return a > b? a = b, 1 : 0; } template<class T> bool chkmax(T &a, const T &b) { return a <b? a = b, 1 : 0; } struct IM { template<class T> IM& operator>>(T &a) { a = 0; char c = getchar(); bool n = false; for(;!isdigit(c); c = getchar()) if(c == '-') n = 1; for(; isdigit(c); c = getchar()) a = a * 10 - 48 + c; if(n) a = -a; return *this; } } getInt; struct UnionFindSet { int fa[Size * 4]; void init(int x) { for(int i = 1; i <= x; ++i) fa[i] = i; } int find(int x) { return x == fa[x]? x : fa[x] = find(fa[x]); } int& operator[](const int &x) { return fa[x]; } } set; struct Edge { int u, v, a, b; } e[Size * 2]; bool operator<(const Edge &a, const Edge &b) { return a.a < b.a; } struct Node { int val, id; Node *fa, *ch[2], *mx; bool rev; bool isroot() { return fa? (fa->ch[0] != this && fa->ch[1] != this) : true; } void pushup() { mx = this; if(ch[0] && ch[0]->mx->val > mx->val) mx = ch[0]->mx; if(ch[1] && ch[1]->mx->val > mx->val) mx = ch[1]->mx; } void reverse() { rev ^= 1; std::swap(ch[0], ch[1]); } void pushdown() { if(rev) { if(ch[0]) ch[0]->reverse(); if(ch[1]) ch[1]->reverse(); rev = 0; } } bool operator!() { return fa->ch[1] == this; } } nd[Size * 4]; void rotate(Node *x) { Node *y = x->fa; bool d = !*x; // must take care here, !*x IS NOT !x if(!y->isroot()) y->fa->ch[!*y] = x; x->fa = y->fa; y->fa = x; y->ch[d] = x->ch[!d]; x->ch[!d] = y; if(y->ch[d]) y->ch[d]->fa = y; y->pushup(); x->pushup(); } void push(Node *x) { if(!x->isroot()) push(x->fa); x->pushdown(); } void splay(Node *x) { push(x); for(Node *y = x->fa; !x->isroot(); y = x->fa) { if(!y->isroot()) rotate(!*x == !*y? y : x); rotate(x); } } void access(Node *x) { for(Node *y = NULL; x; x = (y = x)->fa) { splay(x); x->ch[1] = y; x->pushup(); } } void makeroot(Node *x) { access(x); splay(x); x->reverse(); } Node* findroot(Node *x) { access(x); splay(x); while(x->ch[0]) x = x->ch[0]; return x; } void link(Node *x, Node *y) { makeroot(x); if(findroot(y) != x) x->fa = y; } void cut(Node *x, Node *y) { makeroot(x); if(findroot(y) == x && x->fa == y && x->ch[1] == NULL) { x->fa = y->ch[0] = NULL; y->pushup(); } } void split(Node *x, Node *y) { makeroot(x); access(y); splay(y); } int query(int x, int y) { split(&nd[x], &nd[y]); return nd[y].mx->val; } int n, m; int ans = Inf; int main() { getInt >> n >> m; set.init(n); for(int i = 1; i <= m; ++i) { getInt >> e[i].u >> e[i].v >> e[i].a >> e[i].b; } std::sort(e + 1, e + 1 + m); for(int i = 1, u, v, a, b; i <= m; ++i) { u = e[i].u, v = e[i].v, a = e[i].a, b = e[i].b; if(set.find(u) == set.find(v)) { split(&nd[u], &nd[v]); Node *x = nd[v].mx; if(x->val > b) { cut(x, &nd[e[x->id].u]); cut(x, &nd[e[x->id].v]); } else { // if(set.find(1) == set.find(n)) chkmin(ans, a + query(1, n)); continue; } } else { set[set[u]] = set[v]; } nd[n + i].val = b; nd[n + i].mx = &nd[n + 1]; nd[n + i].id = i; link(&nd[u], &nd[n + i]); link(&nd[v], &nd[n + i]); if(set.find(1) == set.find(n)) chkmin(ans, a + query(1, n)); } std::printf("%d\n", ans == Inf? -1 : ans); return 0; }
20.162037
79
0.439265
DesZou
dcbd88bbf7b50be1b27c9846ddd29f0b192622d4
15,217
cpp
C++
tests/index/test_index_fm_rank_dictionary.cpp
kneubert/seqan
3c4f01dbe67ead02b1ca957b217309493f1ddccf
[ "BSD-3-Clause" ]
null
null
null
tests/index/test_index_fm_rank_dictionary.cpp
kneubert/seqan
3c4f01dbe67ead02b1ca957b217309493f1ddccf
[ "BSD-3-Clause" ]
null
null
null
tests/index/test_index_fm_rank_dictionary.cpp
kneubert/seqan
3c4f01dbe67ead02b1ca957b217309493f1ddccf
[ "BSD-3-Clause" ]
null
null
null
// ========================================================================== // SeqAn - The Library for Sequence Analysis // ========================================================================== // Copyright (c) 2006-2016, Knut Reinert, FU Berlin // Copyright (c) 2013 NVIDIA Corporation // 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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. // // ========================================================================== // Author: Enrico Siragusa <[email protected]> // ========================================================================== #include <seqan/basic.h> #include <seqan/reduced_aminoacid.h> #include <seqan/index.h> #include "test_index_helpers.h" using namespace seqan; // ========================================================================== // Metafunctions // ========================================================================== // ---------------------------------------------------------------------------- // Metafunction Size // ---------------------------------------------------------------------------- //namespace seqan { //template <typename TValue> //struct Size<RankDictionary<TValue, Levels<unsigned> > > //{ // typedef unsigned Type; //}; //} // ========================================================================== // Types // ========================================================================== // -------------------------------------------------------------------------- // RankDictionary Types // -------------------------------------------------------------------------- typedef SimpleType<unsigned char, ReducedAminoAcid_<Murphy10> > ReducedMurphy10; typedef Levels<void, LevelsPrefixRDConfig<uint32_t, Alloc<>, 1, 1> > Prefix1Level; typedef Levels<void, LevelsPrefixRDConfig<uint32_t, Alloc<>, 2, 2> > Prefix2Level; typedef Levels<void, LevelsPrefixRDConfig<uint32_t, Alloc<>, 3, 3> > Prefix3Level; typedef Levels<void, LevelsRDConfig<uint32_t, Alloc<>, 1, 1> > Default1Level; typedef Levels<void, LevelsRDConfig<uint32_t, Alloc<>, 2, 2> > Default2Level; typedef Levels<void, LevelsRDConfig<uint32_t, Alloc<>, 3, 3> > Default3Level; typedef TagList<RankDictionary<bool, Prefix1Level>, TagList<RankDictionary<Dna, Prefix1Level>, TagList<RankDictionary<Dna5Q, Prefix1Level>, TagList<RankDictionary<ReducedMurphy10, Prefix1Level>, TagList<RankDictionary<AminoAcid, Prefix1Level>, TagList<RankDictionary<bool, Prefix2Level>, TagList<RankDictionary<Dna, Prefix2Level>, TagList<RankDictionary<Dna5Q, Prefix2Level>, TagList<RankDictionary<ReducedMurphy10, Prefix2Level>, TagList<RankDictionary<AminoAcid, Prefix2Level>, TagList<RankDictionary<bool, Prefix3Level>, TagList<RankDictionary<Dna, Prefix3Level>, TagList<RankDictionary<Dna5Q, Prefix3Level>, TagList<RankDictionary<ReducedMurphy10, Prefix3Level>, TagList<RankDictionary<AminoAcid, Prefix3Level>, TagList<RankDictionary<bool, WaveletTree<> >, TagList<RankDictionary<Dna, WaveletTree<> >, TagList<RankDictionary<Dna5Q, WaveletTree<> >, TagList<RankDictionary<AminoAcid, WaveletTree<> > > > > > > > > > > > > > > > > > > > > RankDictionaryPrefixSumTypes; typedef TagList<RankDictionary<bool, Naive<> >, TagList<RankDictionary<bool, Default1Level>, TagList<RankDictionary<Dna, Default1Level>, TagList<RankDictionary<Dna5Q, Default1Level>, TagList<RankDictionary<ReducedMurphy10, Default1Level>, TagList<RankDictionary<AminoAcid, Default1Level>, TagList<RankDictionary<bool, Default2Level>, TagList<RankDictionary<Dna, Default2Level>, TagList<RankDictionary<Dna5Q, Default2Level>, TagList<RankDictionary<ReducedMurphy10, Default2Level>, TagList<RankDictionary<AminoAcid, Default2Level>, TagList<RankDictionary<bool, Default3Level>, TagList<RankDictionary<Dna, Default3Level>, TagList<RankDictionary<Dna5Q, Default3Level>, TagList<RankDictionary<ReducedMurphy10, Default3Level>, TagList<RankDictionary<AminoAcid, Default3Level>, RankDictionaryPrefixSumTypes > > > > > > > > > > > > > > > > RankDictionaryAllTypes; // ========================================================================== // Test Classes // ========================================================================== // -------------------------------------------------------------------------- // Class RankDictionaryTest // -------------------------------------------------------------------------- template <typename TRankDictionary> class RankDictionaryTest : public Test { public: typedef TRankDictionary TRankDict; typedef typename Value<TRankDict>::Type TValue; typedef typename Size<TValue>::Type TValueSize; typedef String<TValue> TText; typedef typename Iterator<TText, Standard>::Type TTextIterator; TValueSize alphabetSize; TText text; TTextIterator textBegin; TTextIterator textEnd; RankDictionaryTest() : alphabetSize(ValueSize<TValue>::VALUE), text(), textBegin(), textEnd() {} void setUp() { generateText(text, 3947); textBegin = begin(text, Standard()); textEnd = end(text, Standard()); } }; template <typename TRankDictionary> class RankDictionaryPrefixTest : public RankDictionaryTest<TRankDictionary> {}; SEQAN_TYPED_TEST_CASE(RankDictionaryTest, RankDictionaryAllTypes); SEQAN_TYPED_TEST_CASE(RankDictionaryPrefixTest, RankDictionaryPrefixSumTypes); // ========================================================================== // Tests // ========================================================================== // ---------------------------------------------------------------------------- // Test RankDictionary() // ---------------------------------------------------------------------------- SEQAN_TYPED_TEST(RankDictionaryTest, Constructor) { typename TestFixture::TRankDict dict(this->text); } // ---------------------------------------------------------------------------- // Test createRankDictionary() // ---------------------------------------------------------------------------- SEQAN_TYPED_TEST(RankDictionaryTest, CreateRankDictionary) { typename TestFixture::TRankDict dict; createRankDictionary(dict, this->text); } // ---------------------------------------------------------------------------- // Test clear() and empty() // ---------------------------------------------------------------------------- SEQAN_TYPED_TEST(RankDictionaryTest, ClearEmpty) { typename TestFixture::TRankDict dict; SEQAN_ASSERT(empty(dict)); createRankDictionary(dict, this->text); SEQAN_ASSERT_NOT(empty(dict)); clear(dict); SEQAN_ASSERT(empty(dict)); } // ---------------------------------------------------------------------------- // Test getValue() // ---------------------------------------------------------------------------- SEQAN_TYPED_TEST(RankDictionaryTest, GetValue) { typedef typename TestFixture::TTextIterator TTextIterator; typename TestFixture::TRankDict dict(this->text); for (TTextIterator textIt = this->textBegin; textIt != this->textEnd; ++textIt) SEQAN_ASSERT_EQ(getValue(dict, (unsigned long)(textIt - this->textBegin)), value(textIt)); } // ---------------------------------------------------------------------------- // Test getRank() // ---------------------------------------------------------------------------- SEQAN_TYPED_TEST(RankDictionaryTest, GetRank) { typedef typename TestFixture::TValueSize TValueSize; typedef typename TestFixture::TText TText; typedef typename TestFixture::TTextIterator TTextIterator; typedef typename Size<TText>::Type TTextSize; typedef String<TTextSize> TPrefixSum; typename TestFixture::TRankDict dict(this->text); // The prefix sum is built while scanning the text. TPrefixSum prefixSum; resize(prefixSum, this->alphabetSize, 0); // Scan the text. for (TTextIterator textIt = this->textBegin; textIt != this->textEnd; ++textIt) { // Update the prefix sum. prefixSum[ordValue(value(textIt))]++; // Check the rank for all alphabet symbols. for (TValueSize c = 0; c < this->alphabetSize; ++c) SEQAN_ASSERT_EQ(getRank(dict, (unsigned long)(textIt - this->textBegin), c), prefixSum[c]); } } SEQAN_TYPED_TEST(RankDictionaryPrefixTest, GetPrefixRank) { typedef typename TestFixture::TValueSize TValueSize; typedef typename TestFixture::TText TText; typedef typename TestFixture::TTextIterator TTextIterator; typedef typename Size<TText>::Type TTextSize; typedef String<TTextSize> TPrefixSum; typename TestFixture::TRankDict dict(this->text); // The prefix sum is built while scanning the text. TPrefixSum prefixSum; resize(prefixSum, this->alphabetSize, 0); // Scan the text. for (TTextIterator textIt = this->textBegin; textIt != this->textEnd; ++textIt) { // Update the prefix sum. prefixSum[ordValue(value(textIt))]++; // Check the rank for all alphabet symbols. unsigned long smallerNaive = 0; for (TValueSize c = 0; c < this->alphabetSize; ++c) { unsigned long smaller; SEQAN_ASSERT_EQ(getRank(dict, (unsigned long)(textIt - this->textBegin), c, smaller), prefixSum[c]); SEQAN_ASSERT_EQ(smaller, smallerNaive); smallerNaive += prefixSum[c]; } } } // ---------------------------------------------------------------------------- // Test setValue() // ---------------------------------------------------------------------------- // NOTE(esiragusa): rename it as assignValue() // ---------------------------------------------------------------------------- // Test length() // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Test resize() // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Test reserve() // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Test open() and save() // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Test Size<> // ---------------------------------------------------------------------------- //SEQAN_DEFINE_TEST(test_rss_sizeof) //{ // typedef Dna TAlphabet; // typedef Alloc<unsigned> TTextSpec; // typedef String<TAlphabet, TTextSpec> TText; // // typedef Levels<TAlphabet, unsigned> TRankDictionarySpec; // typedef RankDictionary<TRankDictionarySpec> TRankDictionary; // // TRankSupport rs; // // std::cout << "sizeof(Block): " << sizeof(rs.block) << std::endl; // // std::cout << "bits(Block): " << BitsPerValue<TRankSupport::TBlock>::VALUE << std::endl; // std::cout << "length(Block): " << length(rs.block) << std::endl; // std::cout << "capacity(Block): " << capacity(rs.block) << std::endl; // std::cout << std::endl; // // std::cout << "sizeof(SuperBlock): " << sizeof(rs.sblock) << std::endl; // std::cout << "bits(SuperBlock): " << BitsPerValue<TRankSupport::TSuperBlock>::VALUE << std::endl; // std::cout << "length(SuperBlock): " << length(rs.sblock) << std::endl; // std::cout << "capacity(SuperBlock): " << capacity(rs.sblock) << std::endl; // std::cout << std::endl; // // std::cout << "sizeof(RankSupport): " << sizeof(rs) << std::endl; // std::cout << "bits(RankSupport): " << BitsPerValue<TRankSupport>::VALUE << std::endl; // std::cout << std::endl; //} //SEQAN_DEFINE_TEST(test_rss_resize) //{ // typedef Dna TAlphabet; // typedef Alloc<unsigned> TTextSpec; // typedef String<TAlphabet, TTextSpec> TText; // // typedef Levels<TAlphabet, unsigned> TRankDictionarySpec; // typedef RankDictionary<TRankDictionarySpec> TRankDictionary; // //// TText text = "ACGTNACGTNACGTNACGTNA"; // TText text = "ACGTACGTACGTACGTACGTACGTACGTACGT"; //// TText text = "ACGTACGTACGTACGTACGTACGTACGTACGTCCCCCCCCCCCCCCC"; // // TRankDictionary dict(text); //// createRankDictionary(dict, text); // // std::cout << "Text: " << text << std::endl; //// std::cout << "Block: " << rs.block << std::endl; // // for (unsigned i = 0; i < 10; i++) // for (unsigned char c = 0; c < 4; c++) // std::cout << "getRank(" << Dna(c) << ", " << i << "): " << getRank(dict, i, Dna(c)) << std::endl; // // std::cout << std::endl; //} // ========================================================================== // Functions // ========================================================================== int main(int argc, char const ** argv) { TestSystem::init(argc, argv); return TestSystem::runAll(); }
41.576503
112
0.51495
kneubert
dcc19d9965d66836aaf2949a938de1a5a15c19ca
215,503
cpp
C++
usdmayautils/AL/usdmaya/utils/DgNodeHelper.cpp
garvitverma/AL_USDMaya
5976020facdafce4783fc59aae73a773579f796b
[ "Apache-2.0" ]
275
2017-07-31T16:42:07.000Z
2022-01-27T09:27:45.000Z
usdmayautils/AL/usdmaya/utils/DgNodeHelper.cpp
garvitverma/AL_USDMaya
5976020facdafce4783fc59aae73a773579f796b
[ "Apache-2.0" ]
114
2017-08-01T07:37:35.000Z
2020-01-12T20:27:56.000Z
usdmayautils/AL/usdmaya/utils/DgNodeHelper.cpp
garvitverma/AL_USDMaya
5976020facdafce4783fc59aae73a773579f796b
[ "Apache-2.0" ]
87
2017-08-02T03:00:43.000Z
2021-09-13T02:09:19.000Z
// // Copyright 2017 Animal Logic // // 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 "AL/usd/utils/ALHalf.h" #include "AL/usd/utils/SIMD.h" #include "AL/usdmaya/utils/DgNodeHelper.h" #include "AL/maya/utils/NodeHelper.h" #include "maya/MDGModifier.h" #include "maya/MFloatArray.h" #include "maya/MFloatMatrix.h" #include "maya/MFnCompoundAttribute.h" #include "maya/MFnDoubleArrayData.h" #include "maya/MFnFloatArrayData.h" #include "maya/MFnMatrixData.h" #include "maya/MFnMatrixArrayData.h" #include "maya/MFnNumericAttribute.h" #include "maya/MFnNumericData.h" #include "maya/MFnTypedAttribute.h" #include "maya/MMatrix.h" #include "maya/MMatrixArray.h" namespace AL { namespace usdmaya { namespace utils { //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setFloat(const MObject node, const MObject attr, float value) { const char* const errorString = "float error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.setValue(value), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setAngle(const MObject node, const MObject attr, MAngle value) { const char* const errorString = "DgNodeHelper::setAngle"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.setValue(value), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setTime(const MObject node, const MObject attr, MTime value) { const char* const errorString = "DgNodeHelper::setTime"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.setValue(value), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setDistance(const MObject node, const MObject attr, MDistance value) { const char* const errorString = "DgNodeHelper::setDistance"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.setValue(value), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setDouble(MObject node, MObject attr, double value) { const char* const errorString = "double error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.setValue(value), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setBool(MObject node, MObject attr, bool value) { const char* const errorString = "int error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.setValue(value), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setInt8(MObject node, MObject attr, int8_t value) { const char* const errorString = "int error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.setChar(value), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setInt16(MObject node, MObject attr, int16_t value) { const char* const errorString = "int error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.setShort(value), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setInt32(MObject node, MObject attr, int32_t value) { const char* const errorString = "int error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.setValue(value), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setInt64(MObject node, MObject attr, int64_t value) { const char* const errorString = "int64 error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.setInt64(value), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec3(MObject node, MObject attr, float x, float y, float z) { const char* const errorString = "vec3f error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(x), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(y), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(z), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec3(MObject node, MObject attr, double x, double y, double z) { const char* const errorString = "vec3d error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(x), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(y), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(z), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec3(MObject node, MObject attr, MAngle x, MAngle y, MAngle z) { const char* const errorString = "vec3d error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(x), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(y), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(z), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setBoolArray(MObject node, MObject attribute, const bool* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0; i != count; ++i) { plug.elementByLogicalIndex(i).setBool(values[i]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setBoolArray(const MObject& node, const MObject& attribute, const std::vector<bool>& values) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(values.size()), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0, n = values.size(); i != n; ++i) { plug.elementByLogicalIndex(i).setBool(values[i]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setInt8Array(MObject node, MObject attribute, const int8_t* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0; i != count; ++i) { plug.elementByLogicalIndex(i).setChar(values[i]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setInt16Array(MObject node, MObject attribute, const int16_t* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0; i != count; ++i) { plug.elementByLogicalIndex(i).setShort(values[i]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setInt32Array(MObject node, MObject attribute, const int32_t* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0; i != count; ++i) { plug.elementByLogicalIndex(i).setValue(values[i]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setInt64Array(MObject node, MObject attribute, const int64_t* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0; i != count; ++i) { plug.elementByLogicalIndex(i).setInt64(values[i]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setHalfArray(MObject node, MObject attribute, const GfHalf* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); size_t count8 = count & ~0x7ULL; for(size_t j = 0; j != count8; j += 8) { float f[8]; AL::usd::utils::half2float_8f(values + j, f); plug.elementByLogicalIndex(j + 0).setFloat(f[0]); plug.elementByLogicalIndex(j + 1).setFloat(f[1]); plug.elementByLogicalIndex(j + 2).setFloat(f[2]); plug.elementByLogicalIndex(j + 3).setFloat(f[3]); plug.elementByLogicalIndex(j + 4).setFloat(f[4]); plug.elementByLogicalIndex(j + 5).setFloat(f[5]); plug.elementByLogicalIndex(j + 6).setFloat(f[6]); plug.elementByLogicalIndex(j + 7).setFloat(f[7]); } if(count & 0x4) { float f[4]; AL::usd::utils::half2float_4f(values + count8, f); plug.elementByLogicalIndex(count8 + 0).setFloat(f[0]); plug.elementByLogicalIndex(count8 + 1).setFloat(f[1]); plug.elementByLogicalIndex(count8 + 2).setFloat(f[2]); plug.elementByLogicalIndex(count8 + 3).setFloat(f[3]); count8 |= 0x4; } switch(count & 0x3) { case 3: plug.elementByLogicalIndex(count8 + 2).setFloat(AL::usd::utils::half2float_1f(values[count8 + 2])); case 2: plug.elementByLogicalIndex(count8 + 1).setFloat(AL::usd::utils::half2float_1f(values[count8 + 1])); case 1: plug.elementByLogicalIndex(count8 + 0).setFloat(AL::usd::utils::half2float_1f(values[count8 + 0])); default: break; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setFloatArray(MObject node, MObject attribute, const float* const values, const size_t count) { MPlug plug(node, attribute); if(!plug) { } else { if(!plug.isArray()) { MStatus status; MFnFloatArrayData fn; MFloatArray temp(values, count); MObject obj = fn.create(temp, &status); if(status) { plug.setValue(obj); return MS::kSuccess; } } else { AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0; i != count; ++i) { plug.elementByLogicalIndex(i).setFloat(values[i]); } } return MS::kSuccess; } return MS::kFailure; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setDoubleArray(MObject node, MObject attribute, const double* const values, const size_t count) { MPlug plug(node, attribute); if(!plug) { } else { if(!plug.isArray()) { MStatus status; MFnDoubleArrayData fn; MDoubleArray temp(values, count); MObject obj = fn.create(temp, &status); if(status) { plug.setValue(obj); return MS::kSuccess; } } else { AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0; i != count; ++i) { plug.elementByLogicalIndex(i).setDouble(values[i]); } } return MS::kSuccess; } return MS::kFailure; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec2Array(MObject node, MObject attribute, const int32_t* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0, j = 0; i != count; ++i, j += 2) { auto v = plug.elementByLogicalIndex(i); v.child(0).setInt(values[j]); v.child(1).setInt(values[j + 1]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec2Array(MObject node, MObject attribute, const GfHalf* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); size_t count4 = count & ~0x3ULL; for(size_t i = 0, j = 0; i != count4; i += 4, j += 8) { float f[8]; AL::usd::utils::half2float_8f(values + j, f); auto v0 = plug.elementByLogicalIndex(i + 0); auto v1 = plug.elementByLogicalIndex(i + 1); auto v2 = plug.elementByLogicalIndex(i + 2); auto v3 = plug.elementByLogicalIndex(i + 3); v0.child(0).setFloat(f[0]); v0.child(1).setFloat(f[1]); v1.child(0).setFloat(f[2]); v1.child(1).setFloat(f[3]); v2.child(0).setFloat(f[4]); v2.child(1).setFloat(f[5]); v3.child(0).setFloat(f[6]); v3.child(1).setFloat(f[7]); } if(count & 0x2) { float f[4]; AL::usd::utils::half2float_4f(values + count4 * 2, f); auto v0 = plug.elementByLogicalIndex(count4 + 0); auto v1 = plug.elementByLogicalIndex(count4 + 1); v0.child(0).setFloat(f[0]); v0.child(1).setFloat(f[1]); v1.child(0).setFloat(f[2]); v1.child(1).setFloat(f[3]); count4 += 2; } if(count & 0x1) { auto v0 = plug.elementByLogicalIndex(count4); v0.child(0).setFloat(AL::usd::utils::half2float_1f(values[count4 * 2])); v0.child(1).setFloat(AL::usd::utils::half2float_1f(values[count4 * 2 + 1])); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec2Array(MObject node, MObject attribute, const float* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0, j = 0; i != count; ++i, j += 2) { auto v = plug.elementByLogicalIndex(i); v.child(0).setFloat(values[j]); v.child(1).setFloat(values[j + 1]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec2Array(MObject node, MObject attribute, const double* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0, j = 0; i != count; ++i, j += 2) { auto v = plug.elementByLogicalIndex(i); v.child(0).setDouble(values[j]); v.child(1).setDouble(values[j + 1]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec3Array(MObject node, MObject attribute, const int32_t* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0, j = 0; i != count; ++i, j += 3) { auto v = plug.elementByLogicalIndex(i); v.child(0).setInt(values[j]); v.child(1).setInt(values[j + 1]); v.child(2).setInt(values[j + 2]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec3Array(MObject node, MObject attribute, const GfHalf* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); size_t count8 = count & ~0x7ULL; for(size_t i = 0, j = 0; i != count8; i += 8, j += 24) { float f[24]; AL::usd::utils::half2float_8f(values + j, f); AL::usd::utils::half2float_8f(values + j + 8, f + 8); AL::usd::utils::half2float_8f(values + j + 16, f + 16); for(int k = 0; k < 8; ++k) { auto v = plug.elementByLogicalIndex(i + k); v.child(0).setFloat(f[k * 3 + 0]); v.child(1).setFloat(f[k * 3 + 1]); v.child(2).setFloat(f[k * 3 + 2]); } } for(size_t i = count8, j = count8 * 3; i != count; ++i, j += 3) { float f[4]; GfHalf h[4]; h[0] = values[j]; h[1] = values[j + 1]; h[2] = values[j + 2]; AL::usd::utils::half2float_4f(h, f); auto v = plug.elementByLogicalIndex(i); v.child(0).setFloat(f[0]); v.child(1).setFloat(f[1]); v.child(2).setFloat(f[2]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec3Array(MObject node, MObject attribute, const float* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0, j = 0; i != count; ++i, j += 3) { auto v = plug.elementByLogicalIndex(i); v.child(0).setFloat(values[j]); v.child(1).setFloat(values[j + 1]); v.child(2).setFloat(values[j + 2]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec3Array(MObject node, MObject attribute, const double* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0, j = 0; i != count; ++i, j += 3) { auto v = plug.elementByLogicalIndex(i); v.child(0).setDouble(values[j]); v.child(1).setDouble(values[j + 1]); v.child(2).setDouble(values[j + 2]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec4Array(MObject node, MObject attribute, const GfHalf* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) { return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); size_t count2 = count & ~0x1ULL; for(size_t i = 0, j = 0; i != count2; i += 2, j += 8) { float f[8]; AL::usd::utils::half2float_8f(values + j, f); auto v0 = plug.elementByLogicalIndex(i); auto v1 = plug.elementByLogicalIndex(i + 1); v0.child(0).setFloat(f[0]); v0.child(1).setFloat(f[1]); v0.child(2).setFloat(f[2]); v0.child(3).setFloat(f[3]); v1.child(0).setFloat(f[4]); v1.child(1).setFloat(f[5]); v1.child(2).setFloat(f[6]); v1.child(3).setFloat(f[7]); } if(count & 0x1) { float f[4]; AL::usd::utils::half2float_4f(values + count2 * 4, f); auto v0 = plug.elementByLogicalIndex(count2); v0.child(0).setFloat(f[0]); v0.child(1).setFloat(f[1]); v0.child(2).setFloat(f[2]); v0.child(3).setFloat(f[3]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec4Array(MObject node, MObject attribute, const int* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0, j = 0; i != count; ++i, j += 4) { auto v = plug.elementByLogicalIndex(i); v.child(0).setInt(values[j]); v.child(1).setInt(values[j + 1]); v.child(2).setInt(values[j + 2]); v.child(3).setInt(values[j + 3]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec4Array(MObject node, MObject attribute, const float* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0, j = 0; i != count; ++i, j += 4) { auto v = plug.elementByLogicalIndex(i); v.child(0).setFloat(values[j]); v.child(1).setFloat(values[j + 1]); v.child(2).setFloat(values[j + 2]); v.child(3).setFloat(values[j + 3]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec4Array(MObject node, MObject attribute, const double* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0, j = 0; i != count; ++i, j += 4) { auto v = plug.elementByLogicalIndex(i); v.child(0).setDouble(values[j]); v.child(1).setDouble(values[j + 1]); v.child(2).setDouble(values[j + 2]); v.child(3).setDouble(values[j + 3]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMatrix4x4Array(MObject node, MObject attribute, const double* const values, const size_t count) { MPlug plug(node, attribute); if(!plug) return MS::kFailure; if(!plug.isArray()) { MStatus status; MMatrixArray arrayData; arrayData.setLength(count); memcpy(&arrayData[0], values, sizeof(MMatrix) * count); MFnMatrixArrayData fn; MObject data = fn.create(arrayData, &status); AL_MAYA_CHECK_ERROR2(status, MString("Count not set array value")); status = plug.setValue(data); AL_MAYA_CHECK_ERROR2(status, MString("Count not set array value")); } else { // Yes this is horrible. It would appear that as of Maya 2017, setting the contents of matrix array attributes doesn't work. // Well, at least for dynamic attributes. Using an array builder inside a compute method would be one way char tempStr[1024] = {0}; for(uint32_t i = 0; i < 16 * count; i += 16) { sprintf(tempStr, "setAttr \"%s[%d]\" -type \"matrix\" %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf;", plug.name().asChar(), (i >> 4), values[i + 0], values[i + 1], values[i + 2], values[i + 3], values[i + 4], values[i + 5], values[i + 6], values[i + 7], values[i + 8], values[i + 9], values[i + 10], values[i + 11], values[i + 12], values[i + 13], values[i + 14], values[i + 15] ); MGlobal::executeCommand(tempStr); } } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMatrix4x4Array(MObject node, MObject attribute, const float* const values, const size_t count) { MPlug plug(node, attribute); if(!plug) return MS::kFailure; if(!plug.isArray()) { MStatus status; MMatrixArray arrayData; arrayData.setLength(count); double* ptr = &arrayData[0].matrix[0][0]; for(size_t i = 0, j = 0; i != count; ++i, j += 16) { double* const dptr = ptr + j; const float* const fptr = values + j; #if AL_UTILS_ENABLE_SIMD # if __AVX__ const f256 d0 = loadu8f(fptr); const f256 d1 = loadu8f(fptr + 8); storeu4d(dptr , cvt4f_to_4d(extract4f(d0, 0))); storeu4d(dptr + 4, cvt4f_to_4d(extract4f(d0, 1))); storeu4d(dptr + 8, cvt4f_to_4d(extract4f(d1, 0))); storeu4d(dptr + 12, cvt4f_to_4d(extract4f(d1, 1))); # else const f128 d0 = loadu4f(fptr); const f128 d1 = loadu4f(fptr + 4); const f128 d2 = loadu4f(fptr + 8); const f128 d3 = loadu4f(fptr + 12); storeu2d(dptr , cvt2f_to_2d(d0)); storeu2d(dptr + 2, cvt2f_to_2d(movehl4f(d0, d0))); storeu2d(dptr + 4, cvt2f_to_2d(d1)); storeu2d(dptr + 6, cvt2f_to_2d(movehl4f(d1, d1))); storeu2d(dptr + 8, cvt2f_to_2d(d2)); storeu2d(dptr + 10, cvt2f_to_2d(movehl4f(d2, d2))); storeu2d(dptr + 12, cvt2f_to_2d(d3)); storeu2d(dptr + 14, cvt2f_to_2d(movehl4f(d3, d3))); # endif #else for(int k = 0; k < 16; ++k) { dptr[k] = fptr[k]; } #endif } MFnMatrixArrayData fn; MObject data = fn.create(arrayData, &status); AL_MAYA_CHECK_ERROR2(status, MString("Count not set array value")); status = plug.setValue(data); AL_MAYA_CHECK_ERROR2(status, MString("Count not set array value")); } else { // I can't seem to create a multi of arrays within the Maya API (without using an array data builder within a compute). char tempStr[2048] = {0}; for(uint32_t i = 0; i < 16 * count; i += 16) { sprintf(tempStr, "setAttr \"%s[%d]\" -type \"matrix\" %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f;", plug.name().asChar(), (i >> 4), values[i + 0], values[i + 1], values[i + 2], values[i + 3], values[i + 4], values[i + 5], values[i + 6], values[i + 7], values[i + 8], values[i + 9], values[i + 10], values[i + 11], values[i + 12], values[i + 13], values[i + 14], values[i + 15] ); MGlobal::executeCommand(tempStr); } } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setTimeArray(MObject node, MObject attribute, const float* const values, const size_t count, MTime::Unit unit) { // determine how much we need to modify the const MTime mod(1.0, unit); const float unitConversion = float(mod.as(MTime::k6000FPS)); MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); #if AL_UTILS_ENABLE_SIMD const f128 unitConversion128 = splat4f(unitConversion); const size_t count4 = count & ~3ULL; size_t i = 0; for(; i < count4; i += 4) { MPlug v0 = plug.elementByLogicalIndex(i); MPlug v1 = plug.elementByLogicalIndex(i + 1); MPlug v2 = plug.elementByLogicalIndex(i + 2); MPlug v3 = plug.elementByLogicalIndex(i + 3); const f128 temp = mul4f(unitConversion128, loadu4f(values + i)); ALIGN16(float tempf[4]); store4f(tempf, temp); v0.setFloat(tempf[0]); v1.setFloat(tempf[1]); v2.setFloat(tempf[2]); v3.setFloat(tempf[3]); } switch(count & 3) { case 3: plug.elementByLogicalIndex(i + 2).setFloat(unitConversion * values[i + 2]); case 2: plug.elementByLogicalIndex(i + 1).setFloat(unitConversion * values[i + 1]); case 1: plug.elementByLogicalIndex(i ).setFloat(unitConversion * values[i ]); default: break; } #else for(size_t i = 0; i < count; ++i) { plug.elementByLogicalIndex(i).setFloat(unitConversion * values[i]); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setAngleArray(MObject node, MObject attribute, const float* const values, const size_t count, MAngle::Unit unit) { // determine how much we need to modify the const MAngle mod(1.0, unit); const float unitConversion = float(mod.as(MAngle::internalUnit())); MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); #if AL_UTILS_ENABLE_SIMD const f128 unitConversion128 = splat4f(unitConversion); const size_t count4 = count & ~3ULL; size_t i = 0; for(; i < count4; i += 4) { MPlug v0 = plug.elementByLogicalIndex(i); MPlug v1 = plug.elementByLogicalIndex(i + 1); MPlug v2 = plug.elementByLogicalIndex(i + 2); MPlug v3 = plug.elementByLogicalIndex(i + 3); const f128 temp = mul4f(unitConversion128, loadu4f(values + i)); ALIGN16(float tempf[4]); store4f(tempf, temp); v0.setFloat(tempf[0]); v1.setFloat(tempf[1]); v2.setFloat(tempf[2]); v3.setFloat(tempf[3]); } switch(count & 3) { case 3: plug.elementByLogicalIndex(i + 2).setFloat(unitConversion * values[i + 2]); case 2: plug.elementByLogicalIndex(i + 1).setFloat(unitConversion * values[i + 1]); case 1: plug.elementByLogicalIndex(i ).setFloat(unitConversion * values[i]); default: break; } #else for(size_t i = 0; i < count; ++i) { plug.elementByLogicalIndex(i).setFloat(unitConversion * values[i]); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setDistanceArray(MObject node, MObject attribute, const float* const values, const size_t count, MDistance::Unit unit) { // determine how much we need to modify the const MDistance mod(1.0, unit); const float unitConversion = float(mod.as(MDistance::internalUnit())); MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); #if AL_UTILS_ENABLE_SIMD const f128 unitConversion128 = splat4f(unitConversion); const size_t count4 = count & ~3ULL; size_t i = 0; for(; i < count4; i += 4) { MPlug v0 = plug.elementByLogicalIndex(i); MPlug v1 = plug.elementByLogicalIndex(i + 1); MPlug v2 = plug.elementByLogicalIndex(i + 2); MPlug v3 = plug.elementByLogicalIndex(i + 3); const f128 temp = mul4f(unitConversion128, loadu4f(values + i)); ALIGN16(float tempf[4]); store4f(tempf, temp); v0.setFloat(tempf[0]); v1.setFloat(tempf[1]); v2.setFloat(tempf[2]); v3.setFloat(tempf[3]); } switch(count & 0x3) { case 3: plug.elementByLogicalIndex(i + 2).setFloat(unitConversion * values[i + 2]); case 2: plug.elementByLogicalIndex(i + 1).setFloat(unitConversion * values[i + 1]); case 1: plug.elementByLogicalIndex(i ).setFloat(unitConversion * values[i]); default: break; } #else for(size_t i = 0; i < count; ++i) { plug.elementByLogicalIndex(i).setFloat(unitConversion * values[i]); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setUsdBoolArray(const MObject& node, const MObject& attribute, const VtArray<bool>& values) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(values.size()), "DgNodeTranslator: attribute array could not be resized"); for(size_t i = 0, n = values.size(); i != n; ++i) { plug.elementByLogicalIndex(i).setBool(values[i]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setAngleAnim(MObject node, MObject attr, const UsdGeomXformOp op) { MStatus status; const char* const errorString = "DgNodeHelper::setAngleAnim"; MPlug plug(node, attr); MFnAnimCurve fnCurve; fnCurve.create(plug, NULL, &status); AL_MAYA_CHECK_ERROR(status, errorString); std::vector<double> times; op.GetTimeSamples(&times); const float conversionFactor = 0.0174533f; float value = 0; for(auto const& timeValue: times) { const bool retValue = op.GetAs<float>(&value, timeValue); if (!retValue) continue; MTime tm(timeValue, MTime::kFilm); switch (fnCurve.animCurveType()) { case MFnAnimCurve::kAnimCurveTL: case MFnAnimCurve::kAnimCurveTA: case MFnAnimCurve::kAnimCurveTU: { fnCurve.addKey(tm, value * conversionFactor, MFnAnimCurve::kTangentGlobal, MFnAnimCurve::kTangentGlobal, NULL, &status); AL_MAYA_CHECK_ERROR(status, errorString); break; } default: { std::cout << "[DgNodeHelper::setAngleAnim] Unexpected anim curve type: " << fnCurve.animCurveType() << std::endl; break; } } } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setFloatAttrAnim(const MObject node, const MObject attr, UsdAttribute usdAttr, double conversionFactor) { if (!usdAttr.GetNumTimeSamples()) { return MS::kFailure; } const char* const errorString = "DgNodeTranslator::setFloatAttrAnim"; MStatus status; MPlug plug(node, attr); MPlug srcPlug; MFnAnimCurve fnCurve; MDGModifier dgmod; srcPlug = plug.source(&status); AL_MAYA_CHECK_ERROR(status, errorString); if(!srcPlug.isNull()) { std::cout << "[DgNodeTranslator::setFloatAttrAnim] disconnecting curve! = " << srcPlug.name().asChar() << std::endl; dgmod.disconnect(srcPlug, plug); dgmod.doIt(); } fnCurve.create(plug, NULL, &status); AL_MAYA_CHECK_ERROR(status, errorString); std::vector<double> times; usdAttr.GetTimeSamples(&times); float value; for(auto const& timeValue: times) { const bool retValue = usdAttr.Get(&value, timeValue); if(!retValue) continue; MTime tm(timeValue, MTime::kFilm); switch(fnCurve.animCurveType()) { case MFnAnimCurve::kAnimCurveTL: case MFnAnimCurve::kAnimCurveTA: case MFnAnimCurve::kAnimCurveTU: { fnCurve.addKey(tm, value * conversionFactor, MFnAnimCurve::kTangentGlobal, MFnAnimCurve::kTangentGlobal, NULL, &status); AL_MAYA_CHECK_ERROR(status, errorString); break; } default: { std::cout << "[DgNodeTranslator::setFloatAttrAnim] OTHER ANIM CURVE TYPE! = " << fnCurve.animCurveType() << std::endl; break; } } } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVisAttrAnim(const MObject node, const MObject attr, const UsdAttribute &usdAttr) { if (!usdAttr.GetNumTimeSamples()) { return MS::kFailure; } const char* const errorString = "DgNodeTranslator::setVisAttrAnim"; MStatus status; MPlug plug(node, attr); MPlug srcPlug; MFnAnimCurve fnCurve; MDGModifier dgmod; srcPlug = plug.source(&status); AL_MAYA_CHECK_ERROR(status, errorString); if(!srcPlug.isNull()) { std::cout << "[DgNodeTranslator::setVisAttrAnim] disconnecting curve! = " << srcPlug.name().asChar() << std::endl; dgmod.disconnect(srcPlug, plug); dgmod.doIt(); } fnCurve.create(plug, NULL, &status); AL_MAYA_CHECK_ERROR(status, errorString); std::vector<double> times; usdAttr.GetTimeSamples(&times); TfToken value; for(auto const& timeValue: times) { const bool retValue = usdAttr.Get<TfToken>(&value, timeValue); if(!retValue) continue; MTime tm(timeValue, MTime::kFilm); fnCurve.addKey(tm, (value == UsdGeomTokens->invisible) ? 0 : 1, MFnAnimCurve::kTangentGlobal, MFnAnimCurve::kTangentGlobal, NULL, &status); AL_MAYA_CHECK_ERROR(status, errorString); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getBoolArray(const MObject& node, const MObject& attr, std::vector<bool>& values) { // // Handle the oddity that is std::vector<bool> // MPlug plug(node, attr); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); values.resize(num); for(uint32_t i = 0; i < num; ++i) { values[i] = plug.elementByLogicalIndex(i).asBool(); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getBoolArray(MObject node, MObject attribute, bool* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD uint32_t count16 = count & ~0xF; for(uint32_t i = 0; i < count16; i += 16) { ALIGN16(bool temp[16]); temp[0] = plug.elementByLogicalIndex(i).asBool(); temp[1] = plug.elementByLogicalIndex(i + 1).asBool(); temp[2] = plug.elementByLogicalIndex(i + 2).asBool(); temp[3] = plug.elementByLogicalIndex(i + 3).asBool(); temp[4] = plug.elementByLogicalIndex(i + 4).asBool(); temp[5] = plug.elementByLogicalIndex(i + 5).asBool(); temp[6] = plug.elementByLogicalIndex(i + 6).asBool(); temp[7] = plug.elementByLogicalIndex(i + 7).asBool(); temp[8] = plug.elementByLogicalIndex(i + 8).asBool(); temp[9] = plug.elementByLogicalIndex(i + 9).asBool(); temp[10] = plug.elementByLogicalIndex(i + 10).asBool(); temp[11] = plug.elementByLogicalIndex(i + 11).asBool(); temp[12] = plug.elementByLogicalIndex(i + 12).asBool(); temp[13] = plug.elementByLogicalIndex(i + 13).asBool(); temp[14] = plug.elementByLogicalIndex(i + 14).asBool(); temp[15] = plug.elementByLogicalIndex(i + 15).asBool(); storeu4i(values + i, load4i(temp)); } for(uint32_t i = count16; i < num; ++i) { values[i] = plug.elementByLogicalIndex(i).asBool(); } #else for(uint32_t i = 0; i < num; ++i) { values[i] = plug.elementByLogicalIndex(i).asBool(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getInt64Array(MObject node, MObject attribute, int64_t* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError(plug.name() + ", error array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD #ifdef __AVX__ uint32_t count4 = count & ~0x3; uint32_t i = 0; for(; i < count4; i += 4) { ALIGN32(int64_t temp[4]); temp[0] = plug.elementByLogicalIndex(i).asInt64(); temp[1] = plug.elementByLogicalIndex(i + 1).asInt64(); temp[2] = plug.elementByLogicalIndex(i + 2).asInt64(); temp[3] = plug.elementByLogicalIndex(i + 3).asInt64(); storeu8i(values + i, load8i(temp)); } if(count & 0x2) { ALIGN16(int64_t temp[2]); temp[0] = plug.elementByLogicalIndex(i).asInt64(); temp[1] = plug.elementByLogicalIndex(i + 1).asInt64(); storeu4i(values + i, load4i(temp)); i += 2; } #else uint32_t count2 = count & ~0x1; uint32_t i = 0; for(; i < count2; i += 2) { ALIGN16(int64_t temp[2]); temp[0] = plug.elementByLogicalIndex(i).asInt64(); temp[1] = plug.elementByLogicalIndex(i + 1).asInt64(); storeu4i(values + i, load4i(temp)); } #endif if(count & 1) { values[i] = plug.elementByLogicalIndex(i).asInt64(); } #else for(uint32_t i = 0; i < num; ++i) { values[i] = plug.elementByLogicalIndex(i).asInt64(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getInt32Array(MObject node, MObject attribute, int32_t* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD #ifdef __AVX__ uint32_t count8 = count & ~0x7; uint32_t i = 0; for(; i < count8; i += 8) { ALIGN32(int32_t temp[8]); temp[0] = plug.elementByLogicalIndex(i).asInt(); temp[1] = plug.elementByLogicalIndex(i + 1).asInt(); temp[2] = plug.elementByLogicalIndex(i + 2).asInt(); temp[3] = plug.elementByLogicalIndex(i + 3).asInt(); temp[4] = plug.elementByLogicalIndex(i + 4).asInt(); temp[5] = plug.elementByLogicalIndex(i + 5).asInt(); temp[6] = plug.elementByLogicalIndex(i + 6).asInt(); temp[7] = plug.elementByLogicalIndex(i + 7).asInt(); storeu8i(values + i, load8i(temp)); } if(count & 0x4) { ALIGN16(int32_t temp[4]); temp[0] = plug.elementByLogicalIndex(i).asInt(); temp[1] = plug.elementByLogicalIndex(i + 1).asInt(); temp[2] = plug.elementByLogicalIndex(i + 2).asInt(); temp[3] = plug.elementByLogicalIndex(i + 3).asInt(); storeu4i(values + i, load4i(temp)); i += 4; } #else uint32_t count4 = count & ~0x3; uint32_t i = 0; for(; i < count4; i += 4) { ALIGN16(int32_t temp[4]); temp[0] = plug.elementByLogicalIndex(i).asInt(); temp[1] = plug.elementByLogicalIndex(i + 1).asInt(); temp[2] = plug.elementByLogicalIndex(i + 2).asInt(); temp[3] = plug.elementByLogicalIndex(i + 3).asInt(); storeu4i(values + i, load4i(temp)); } #endif switch(count & 3) { case 3: values[i + 2] = plug.elementByLogicalIndex(i + 2).asInt(); case 2: values[i + 1] = plug.elementByLogicalIndex(i + 1).asInt(); case 1: values[i] = plug.elementByLogicalIndex(i).asInt(); default: break; } #else for(uint32_t i = 0; i < num; ++i) { values[i] = plug.elementByLogicalIndex(i).asInt(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getInt8Array(MObject node, MObject attribute, int8_t* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } for(uint32_t i = 0; i < num; ++i) { values[i] = plug.elementByLogicalIndex(i).asChar(); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getInt16Array(MObject node, MObject attribute, int16_t* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } for(uint32_t i = 0; i < num; ++i) { values[i] = plug.elementByLogicalIndex(i).asShort(); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getFloatArray(MObject node, MObject attribute, float* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD #ifdef __AVX__ uint32_t count8 = count & ~0x7; uint32_t i = 0; for(; i < count8; i += 8) { ALIGN32(float temp[8]); temp[0] = plug.elementByLogicalIndex(i).asFloat(); temp[1] = plug.elementByLogicalIndex(i + 1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 2).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 3).asFloat(); temp[4] = plug.elementByLogicalIndex(i + 4).asFloat(); temp[5] = plug.elementByLogicalIndex(i + 5).asFloat(); temp[6] = plug.elementByLogicalIndex(i + 6).asFloat(); temp[7] = plug.elementByLogicalIndex(i + 7).asFloat(); storeu8f(values + i, load8f(temp)); } if(count & 0x4) { ALIGN16(float temp[4]); temp[0] = plug.elementByLogicalIndex(i).asFloat(); temp[1] = plug.elementByLogicalIndex(i + 1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 2).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 3).asFloat(); storeu4f(values + i, load4f(temp)); i += 4; } #else uint32_t count4 = count & ~0x3; uint32_t i = 0; for(; i < count4; i += 4) { ALIGN16(float temp[4]); temp[0] = plug.elementByLogicalIndex(i).asFloat(); temp[1] = plug.elementByLogicalIndex(i + 1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 2).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 3).asFloat(); storeu4f(values + i, load4f(temp)); } #endif switch(count & 3) { case 3: values[i + 2] = plug.elementByLogicalIndex(i + 2).asFloat(); case 2: values[i + 1] = plug.elementByLogicalIndex(i + 1).asFloat(); case 1: values[i] = plug.elementByLogicalIndex(i).asFloat(); default: break; } #else for(uint32_t i = 0; i < num; ++i) { values[i] = plug.elementByLogicalIndex(i).asFloat(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getHalfArray(MObject node, MObject attribute, GfHalf* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } size_t count8 = count & ~0x7ULL; for(uint32_t i = 0; i < count8; i += 8) { float f[8]; f[0] = plug.elementByLogicalIndex(i + 0).asFloat(); f[1] = plug.elementByLogicalIndex(i + 1).asFloat(); f[2] = plug.elementByLogicalIndex(i + 2).asFloat(); f[3] = plug.elementByLogicalIndex(i + 3).asFloat(); f[4] = plug.elementByLogicalIndex(i + 4).asFloat(); f[5] = plug.elementByLogicalIndex(i + 5).asFloat(); f[6] = plug.elementByLogicalIndex(i + 6).asFloat(); f[7] = plug.elementByLogicalIndex(i + 7).asFloat(); AL::usd::utils::float2half_8f(f, values + i); } if(count & 0x4) { float f[4]; f[0] = plug.elementByLogicalIndex(count8 + 0).asFloat(); f[1] = plug.elementByLogicalIndex(count8 + 1).asFloat(); f[2] = plug.elementByLogicalIndex(count8 + 2).asFloat(); f[3] = plug.elementByLogicalIndex(count8 + 3).asFloat(); AL::usd::utils::float2half_4f(f, values + count8); count8 += 4; } switch(count & 0x3) { case 3: values[count8 + 2] = AL::usd::utils::float2half_1f(plug.elementByLogicalIndex(count8 + 2).asFloat()); case 2: values[count8 + 1] = AL::usd::utils::float2half_1f(plug.elementByLogicalIndex(count8 + 1).asFloat()); case 1: values[count8 + 0] = AL::usd::utils::float2half_1f(plug.elementByLogicalIndex(count8 + 0).asFloat()); default: break; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getDoubleArray(MObject node, MObject attribute, double* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD #ifdef __AVX__ uint32_t count8 = count & ~0x7; uint32_t i = 0; for(; i < count8; i += 8) { ALIGN32(double temp[8]); temp[0] = plug.elementByLogicalIndex(i).asDouble(); temp[1] = plug.elementByLogicalIndex(i + 1).asDouble(); temp[2] = plug.elementByLogicalIndex(i + 2).asDouble(); temp[3] = plug.elementByLogicalIndex(i + 3).asDouble(); temp[4] = plug.elementByLogicalIndex(i + 4).asDouble(); temp[5] = plug.elementByLogicalIndex(i + 5).asDouble(); temp[6] = plug.elementByLogicalIndex(i + 6).asDouble(); temp[7] = plug.elementByLogicalIndex(i + 7).asDouble(); storeu4d(values + i, load4d(temp)); storeu4d(values + i + 4, load4d(temp + 4)); } if(count & 0x4) { ALIGN16(double temp[4]); temp[0] = plug.elementByLogicalIndex(i).asDouble(); temp[1] = plug.elementByLogicalIndex(i + 1).asDouble(); temp[2] = plug.elementByLogicalIndex(i + 2).asDouble(); temp[3] = plug.elementByLogicalIndex(i + 3).asDouble(); storeu4d(values + i, load4d(temp)); i += 4; } #else uint32_t count4 = count & ~0x3; uint32_t i = 0; for(; i < count4; i += 4) { ALIGN16(double temp[4]); temp[0] = plug.elementByLogicalIndex(i).asDouble(); temp[1] = plug.elementByLogicalIndex(i + 1).asDouble(); temp[2] = plug.elementByLogicalIndex(i + 2).asDouble(); temp[3] = plug.elementByLogicalIndex(i + 3).asDouble(); storeu2d(values + i, load2d(temp)); storeu2d(values + i + 2, load2d(temp + 2)); } #endif switch(count & 3) { case 3: values[i + 2] = plug.elementByLogicalIndex(i + 2).asDouble(); case 2: values[i + 1] = plug.elementByLogicalIndex(i + 1).asDouble(); case 1: values[i] = plug.elementByLogicalIndex(i).asDouble(); default: break; } #else for(uint32_t i = 0; i < num; ++i) { values[i] = plug.elementByLogicalIndex(i).asDouble(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec2Array(MObject node, MObject attribute, double* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD #ifdef __AVX__ uint32_t count2 = count & ~0x1; uint32_t i = 0; for(; i < count2; i += 2) { ALIGN32(double temp[4]); temp[0] = plug.elementByLogicalIndex(i).child(0).asDouble(); temp[1] = plug.elementByLogicalIndex(i).child(1).asDouble(); temp[2] = plug.elementByLogicalIndex(i + 1).child(0).asDouble(); temp[3] = plug.elementByLogicalIndex(i + 1).child(1).asDouble(); storeu4d(values + i * 2, load4d(temp)); } if(count & 1) { ALIGN16(double temp[2]); temp[0] = plug.elementByLogicalIndex(i).child(0).asDouble(); temp[1] = plug.elementByLogicalIndex(i).child(1).asDouble(); storeu2d(values + i * 2, load2d(temp)); } #else uint32_t i = 0; for(; i < count; ++i) { ALIGN16(double temp[2]); temp[0] = plug.elementByLogicalIndex(i).child(0).asDouble(); temp[1] = plug.elementByLogicalIndex(i).child(1).asDouble(); storeu2d(values + i * 2, load2d(temp)); } #endif #else for(uint32_t i = 0, j = 0; i < num; ++i, j += 2) { values[j] = plug.elementByLogicalIndex(i).child(0).asDouble(); values[j + 1] = plug.elementByLogicalIndex(i).child(1).asDouble(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec2Array(MObject node, MObject attribute, float* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD #ifdef __AVX__ uint32_t count4 = count & ~0x3; uint32_t i = 0; for(; i < count4; i += 4) { ALIGN32(float temp[8]); temp[0] = plug.elementByLogicalIndex(i).child(0).asFloat(); temp[1] = plug.elementByLogicalIndex(i).child(1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 1).child(0).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 1).child(1).asFloat(); temp[4] = plug.elementByLogicalIndex(i + 2).child(0).asFloat(); temp[5] = plug.elementByLogicalIndex(i + 2).child(1).asFloat(); temp[6] = plug.elementByLogicalIndex(i + 3).child(0).asFloat(); temp[7] = plug.elementByLogicalIndex(i + 3).child(1).asFloat(); storeu8f(values + i * 2, load8f(temp)); } if(count & 0x2) { ALIGN16(float temp[4]); temp[0] = plug.elementByLogicalIndex(i).child(0).asFloat(); temp[1] = plug.elementByLogicalIndex(i).child(1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 1).child(0).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 1).child(1).asFloat(); storeu4f(values + i * 2, load4f(temp)); i += 2; } #else uint32_t count2 = count & ~0x1; uint32_t i = 0; for(; i < count2; i += 2) { ALIGN16(float temp[4]); temp[0] = plug.elementByLogicalIndex(i).child(0).asFloat(); temp[1] = plug.elementByLogicalIndex(i).child(1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 1).child(0).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 1).child(1).asFloat(); storeu4f(values + i * 2, load4f(temp)); } #endif switch(count & 1) { case 1: values[i * 2] = plug.elementByLogicalIndex(i).child(0).asFloat(); values[i * 2 + 1] = plug.elementByLogicalIndex(i).child(1).asFloat(); default: break; } #else for(uint32_t i = 0, j = 0; i < num; ++i, j += 2) { values[j] = plug.elementByLogicalIndex(i).child(0).asFloat(); values[j + 1] = plug.elementByLogicalIndex(i).child(1).asFloat(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec2Array(MObject node, MObject attribute, GfHalf* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } for(uint32_t i = 0, j = 0; i < num; ++i, j += 2) { values[j] = plug.elementByLogicalIndex(i).child(0).asFloat(); values[j + 1] = plug.elementByLogicalIndex(i).child(1).asFloat(); } size_t count4 = count & ~0x3FULL; for(uint32_t i = 0, j = 0; i < count4; i += 4, j += 8) { float f[8]; auto v0 = plug.elementByLogicalIndex(i + 0); auto v1 = plug.elementByLogicalIndex(i + 1); auto v2 = plug.elementByLogicalIndex(i + 2); auto v3 = plug.elementByLogicalIndex(i + 3); f[0] = v0.child(0).asFloat(); f[1] = v0.child(1).asFloat(); f[2] = v1.child(0).asFloat(); f[3] = v1.child(1).asFloat(); f[4] = v2.child(0).asFloat(); f[5] = v2.child(1).asFloat(); f[6] = v3.child(0).asFloat(); f[7] = v3.child(1).asFloat(); AL::usd::utils::float2half_8f(f, values + j); } if(count & 0x2) { float f[4]; auto v0 = plug.elementByLogicalIndex(count4 + 0); auto v1 = plug.elementByLogicalIndex(count4 + 1); f[0] = v0.child(0).asFloat(); f[1] = v0.child(1).asFloat(); f[2] = v1.child(0).asFloat(); f[3] = v1.child(1).asFloat(); AL::usd::utils::float2half_4f(f, values + count4 * 2); count4 += 2; } if(count & 0x1) { auto v = plug.elementByLogicalIndex(count4); values[count4 * 2 + 0] = AL::usd::utils::float2half_1f(v.child(0).asFloat()); values[count4 * 2 + 1] = AL::usd::utils::float2half_1f(v.child(1).asFloat()); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec2Array(MObject node, MObject attribute, int32_t* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD #ifdef __AVX__ uint32_t count4 = count & ~0x3; uint32_t i = 0; for(; i < count4; i += 4) { ALIGN32(int32_t temp[8]); temp[0] = plug.elementByLogicalIndex(i).child(0).asInt(); temp[1] = plug.elementByLogicalIndex(i).child(1).asInt(); temp[2] = plug.elementByLogicalIndex(i + 1).child(0).asInt(); temp[3] = plug.elementByLogicalIndex(i + 1).child(1).asInt(); temp[4] = plug.elementByLogicalIndex(i + 2).child(0).asInt(); temp[5] = plug.elementByLogicalIndex(i + 2).child(1).asInt(); temp[6] = plug.elementByLogicalIndex(i + 3).child(0).asInt(); temp[7] = plug.elementByLogicalIndex(i + 3).child(1).asInt(); storeu8i(values + i * 2, load8i(temp)); } if(count & 0x2) { ALIGN16(int32_t temp[4]); temp[0] = plug.elementByLogicalIndex(i).child(0).asInt(); temp[1] = plug.elementByLogicalIndex(i).child(1).asInt(); temp[2] = plug.elementByLogicalIndex(i + 1).child(0).asInt(); temp[3] = plug.elementByLogicalIndex(i + 1).child(1).asInt(); storeu4i(values + i * 2, load4i(temp)); i += 2; } #else uint32_t count2 = count & ~0x1; uint32_t i = 0; for(; i < count2; i += 2) { ALIGN16(int32_t temp[4]); temp[0] = plug.elementByLogicalIndex(i).child(0).asInt(); temp[1] = plug.elementByLogicalIndex(i).child(1).asInt(); temp[2] = plug.elementByLogicalIndex(i + 1).child(0).asInt(); temp[3] = plug.elementByLogicalIndex(i + 1).child(1).asInt(); storeu4i(values + i * 2, load4i(temp)); } #endif if(count & 1) { values[i * 2] = plug.elementByLogicalIndex(i).child(0).asInt(); values[i * 2 + 1] = plug.elementByLogicalIndex(i).child(1).asInt(); } #else for(uint32_t i = 0, j = 0; i < num; ++i, j += 2) { values[j] = plug.elementByLogicalIndex(i).child(0).asInt(); values[j + 1] = plug.elementByLogicalIndex(i).child(1).asInt(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec3Array(MObject node, MObject attribute, float* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD #ifdef __AVX__ uint32_t count8 = count & ~0x7; uint32_t i = 0; for(; i < count8; i += 8) { ALIGN32(float temp[24]); const MPlug c0 = plug.elementByLogicalIndex(i ); const MPlug c1 = plug.elementByLogicalIndex(i + 1); const MPlug c2 = plug.elementByLogicalIndex(i + 2); const MPlug c3 = plug.elementByLogicalIndex(i + 3); const MPlug c4 = plug.elementByLogicalIndex(i + 4); const MPlug c5 = plug.elementByLogicalIndex(i + 5); const MPlug c6 = plug.elementByLogicalIndex(i + 6); const MPlug c7 = plug.elementByLogicalIndex(i + 7); temp[ 0] = c0.child(0).asFloat(); temp[ 1] = c0.child(1).asFloat(); temp[ 2] = c0.child(2).asFloat(); temp[ 3] = c1.child(0).asFloat(); temp[ 4] = c1.child(1).asFloat(); temp[ 5] = c1.child(2).asFloat(); temp[ 6] = c2.child(0).asFloat(); temp[ 7] = c2.child(1).asFloat(); temp[ 8] = c2.child(2).asFloat(); temp[ 9] = c3.child(0).asFloat(); temp[10] = c3.child(1).asFloat(); temp[11] = c3.child(2).asFloat(); temp[12] = c4.child(0).asFloat(); temp[13] = c4.child(1).asFloat(); temp[14] = c4.child(2).asFloat(); temp[15] = c5.child(0).asFloat(); temp[16] = c5.child(1).asFloat(); temp[17] = c5.child(2).asFloat(); temp[18] = c6.child(0).asFloat(); temp[19] = c6.child(1).asFloat(); temp[20] = c6.child(2).asFloat(); temp[21] = c7.child(0).asFloat(); temp[22] = c7.child(1).asFloat(); temp[23] = c7.child(2).asFloat(); float* optr = values + (i * 3); storeu8f(optr, load8f(temp)); storeu8f(optr + 8, load8f(temp + 8)); storeu8f(optr + 16, load8f(temp + 16)); } if(count & 0x4) { ALIGN32(float temp[12]); const MPlug c0 = plug.elementByLogicalIndex(i ); const MPlug c1 = plug.elementByLogicalIndex(i + 1); const MPlug c2 = plug.elementByLogicalIndex(i + 2); const MPlug c3 = plug.elementByLogicalIndex(i + 3); temp[ 0] = c0.child(0).asFloat(); temp[ 1] = c0.child(1).asFloat(); temp[ 2] = c0.child(2).asFloat(); temp[ 3] = c1.child(0).asFloat(); temp[ 4] = c1.child(1).asFloat(); temp[ 5] = c1.child(2).asFloat(); temp[ 6] = c2.child(0).asFloat(); temp[ 7] = c2.child(1).asFloat(); temp[ 8] = c2.child(2).asFloat(); temp[ 9] = c3.child(0).asFloat(); temp[10] = c3.child(1).asFloat(); temp[11] = c3.child(2).asFloat(); float* optr = values + (i * 3); storeu8f(optr, load8f(temp)); storeu4f(optr + 8, load4f(temp + 8)); i += 4; } #else uint32_t count4 = count & ~0x3; uint32_t i = 0; for(; i < count4; i += 4) { ALIGN16(float temp[12]); const MPlug c0 = plug.elementByLogicalIndex(i ); const MPlug c1 = plug.elementByLogicalIndex(i + 1); const MPlug c2 = plug.elementByLogicalIndex(i + 2); const MPlug c3 = plug.elementByLogicalIndex(i + 3); temp[ 0] = c0.child(0).asFloat(); temp[ 1] = c0.child(1).asFloat(); temp[ 2] = c0.child(2).asFloat(); temp[ 3] = c1.child(0).asFloat(); temp[ 4] = c1.child(1).asFloat(); temp[ 5] = c1.child(2).asFloat(); temp[ 6] = c2.child(0).asFloat(); temp[ 7] = c2.child(1).asFloat(); temp[ 8] = c2.child(2).asFloat(); temp[ 9] = c3.child(0).asFloat(); temp[10] = c3.child(1).asFloat(); temp[11] = c3.child(2).asFloat(); float* optr = values + (i * 3); storeu4f(optr + 0, load4f(temp + 0)); storeu4f(optr + 4, load4f(temp + 4)); storeu4f(optr + 8, load4f(temp + 8)); } #endif float* optr = values + (i * 3); MPlug elem; switch(count & 3) { case 3: elem = plug.elementByLogicalIndex(i + 2); optr[6] = elem.child(0).asFloat(); optr[7] = elem.child(1).asFloat(); optr[8] = elem.child(2).asFloat(); case 2: elem = plug.elementByLogicalIndex(i + 1); optr[3] = elem.child(0).asFloat(); optr[4] = elem.child(1).asFloat(); optr[5] = elem.child(2).asFloat(); case 1: elem = plug.elementByLogicalIndex(i); optr[0] = elem.child(0).asFloat(); optr[1] = elem.child(1).asFloat(); optr[2] = elem.child(2).asFloat(); default: break; } #else for(uint32_t i = 0, j = 0; i < num; ++i, j += 3) { MPlug elem = plug.elementByLogicalIndex(i); values[j ] = elem.child(0).asFloat(); values[j + 1] = elem.child(1).asFloat(); values[j + 2] = elem.child(2).asFloat(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec3Array(MObject node, MObject attribute, double* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD #ifdef __AVX__ uint32_t count4 = count & ~0x3; uint32_t i = 0; for(; i < count4; i += 4) { ALIGN32(double temp[12]); const MPlug c0 = plug.elementByLogicalIndex(i ); const MPlug c1 = plug.elementByLogicalIndex(i + 1); const MPlug c2 = plug.elementByLogicalIndex(i + 2); const MPlug c3 = plug.elementByLogicalIndex(i + 3); temp[ 0] = c0.child(0).asDouble(); temp[ 1] = c0.child(1).asDouble(); temp[ 2] = c0.child(2).asDouble(); temp[ 3] = c1.child(0).asDouble(); temp[ 4] = c1.child(1).asDouble(); temp[ 5] = c1.child(2).asDouble(); temp[ 6] = c2.child(0).asDouble(); temp[ 7] = c2.child(1).asDouble(); temp[ 8] = c2.child(2).asDouble(); temp[ 9] = c3.child(0).asDouble(); temp[10] = c3.child(1).asDouble(); temp[11] = c3.child(2).asDouble(); double* optr = values + (i * 3); storeu4d(optr, load4d(temp)); storeu4d(optr + 4, load4d(temp + 4)); storeu4d(optr + 8, load4d(temp + 8)); } if(count & 0x2) { ALIGN32(double temp[6]); const MPlug c0 = plug.elementByLogicalIndex(i ); const MPlug c1 = plug.elementByLogicalIndex(i + 1); temp[ 0] = c0.child(0).asDouble(); temp[ 1] = c0.child(1).asDouble(); temp[ 2] = c0.child(2).asDouble(); temp[ 3] = c1.child(0).asDouble(); temp[ 4] = c1.child(1).asDouble(); temp[ 5] = c1.child(2).asDouble(); double* optr = values + (i * 3); storeu4d(optr, load4d(temp)); storeu2d(optr + 4, load2d(temp + 4)); i += 2; } #else uint32_t count2 = count & ~0x1; uint32_t i = 0; for(; i < count2; i += 2) { ALIGN16(double temp[6]); const MPlug c0 = plug.elementByLogicalIndex(i ); const MPlug c1 = plug.elementByLogicalIndex(i + 1); temp[ 0] = c0.child(0).asDouble(); temp[ 1] = c0.child(1).asDouble(); temp[ 2] = c0.child(2).asDouble(); temp[ 3] = c1.child(0).asDouble(); temp[ 4] = c1.child(1).asDouble(); temp[ 5] = c1.child(2).asDouble(); double* optr = values + (i * 3); storeu2d(optr + 0, load2d(temp + 0)); storeu2d(optr + 2, load2d(temp + 2)); storeu2d(optr + 4, load2d(temp + 4)); } #endif if(count & 1) { double* optr = values + (i * 3); MPlug elem = plug.elementByLogicalIndex(i); optr[0] = elem.child(0).asDouble(); optr[1] = elem.child(1).asDouble(); optr[2] = elem.child(2).asDouble(); } #else for(uint32_t i = 0, j = 0; i < num; ++i, j += 3) { MPlug elem = plug.elementByLogicalIndex(i); values[j ] = elem.child(0).asFloat(); values[j + 1] = elem.child(1).asFloat(); values[j + 2] = elem.child(2).asFloat(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec3Array(MObject node, MObject attribute, GfHalf* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } size_t count8 = count & ~0x7ULL; for(uint32_t i = 0, j = 0; i < count8; i += 8, j += 24) { float r[24]; MPlug v0 = plug.elementByLogicalIndex(i + 0); MPlug v1 = plug.elementByLogicalIndex(i + 1); MPlug v2 = plug.elementByLogicalIndex(i + 2); MPlug v3 = plug.elementByLogicalIndex(i + 3); MPlug v4 = plug.elementByLogicalIndex(i + 4); MPlug v5 = plug.elementByLogicalIndex(i + 5); MPlug v6 = plug.elementByLogicalIndex(i + 6); MPlug v7 = plug.elementByLogicalIndex(i + 7); r[ 0] = v0.child(0).asFloat(); r[ 1] = v0.child(1).asFloat(); r[ 2] = v0.child(2).asFloat(); r[ 3] = v1.child(0).asFloat(); r[ 4] = v1.child(1).asFloat(); r[ 5] = v1.child(2).asFloat(); r[ 6] = v2.child(0).asFloat(); r[ 7] = v2.child(1).asFloat(); r[ 8] = v2.child(2).asFloat(); r[ 9] = v3.child(0).asFloat(); r[10] = v3.child(1).asFloat(); r[11] = v3.child(2).asFloat(); r[12] = v4.child(0).asFloat(); r[13] = v4.child(1).asFloat(); r[14] = v4.child(2).asFloat(); r[15] = v5.child(0).asFloat(); r[16] = v5.child(1).asFloat(); r[17] = v5.child(2).asFloat(); r[18] = v6.child(0).asFloat(); r[19] = v6.child(1).asFloat(); r[20] = v6.child(2).asFloat(); r[21] = v7.child(0).asFloat(); r[22] = v7.child(1).asFloat(); r[23] = v7.child(2).asFloat(); AL::usd::utils::float2half_8f(r, values + j); AL::usd::utils::float2half_8f(r + 8, values + j + 8); AL::usd::utils::float2half_8f(r + 16, values + j + 16); } for(uint32_t i = count8, j = count8 * 3; i < count; ++i, j += 3) { float v[4]; GfHalf h[4]; MPlug elem = plug.elementByLogicalIndex(i); v[0] = elem.child(0).asFloat(); v[1] = elem.child(1).asFloat(); v[2] = elem.child(2).asFloat(); AL::usd::utils::float2half_4f(v, h); values[j + 0] = h[0]; values[j + 1] = h[1]; values[j + 2] = h[2]; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec3Array(MObject node, MObject attribute, int32_t* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD #ifdef __AVX__ uint32_t count8 = count & ~0x7; uint32_t i = 0; for(; i < count8; i += 8) { ALIGN32(int32_t temp[24]); const MPlug c0 = plug.elementByLogicalIndex(i ); const MPlug c1 = plug.elementByLogicalIndex(i + 1); const MPlug c2 = plug.elementByLogicalIndex(i + 2); const MPlug c3 = plug.elementByLogicalIndex(i + 3); const MPlug c4 = plug.elementByLogicalIndex(i + 4); const MPlug c5 = plug.elementByLogicalIndex(i + 5); const MPlug c6 = plug.elementByLogicalIndex(i + 6); const MPlug c7 = plug.elementByLogicalIndex(i + 7); temp[ 0] = c0.child(0).asInt(); temp[ 1] = c0.child(1).asInt(); temp[ 2] = c0.child(2).asInt(); temp[ 3] = c1.child(0).asInt(); temp[ 4] = c1.child(1).asInt(); temp[ 5] = c1.child(2).asInt(); temp[ 6] = c2.child(0).asInt(); temp[ 7] = c2.child(1).asInt(); temp[ 8] = c2.child(2).asInt(); temp[ 9] = c3.child(0).asInt(); temp[10] = c3.child(1).asInt(); temp[11] = c3.child(2).asInt(); temp[12] = c4.child(0).asInt(); temp[13] = c4.child(1).asInt(); temp[14] = c4.child(2).asInt(); temp[15] = c5.child(0).asInt(); temp[16] = c5.child(1).asInt(); temp[17] = c5.child(2).asInt(); temp[18] = c6.child(0).asInt(); temp[19] = c6.child(1).asInt(); temp[20] = c6.child(2).asInt(); temp[21] = c7.child(0).asInt(); temp[22] = c7.child(1).asInt(); temp[23] = c7.child(2).asInt(); int32_t* optr = values + (i * 3); storeu8i(optr + 0, load8i(temp + 0)); storeu8i(optr + 8, load8i(temp + 8)); storeu8i(optr + 16, load8i(temp + 16)); } if(count & 0x4) { ALIGN32(int32_t temp[12]); const MPlug c0 = plug.elementByLogicalIndex(i ); const MPlug c1 = plug.elementByLogicalIndex(i + 1); const MPlug c2 = plug.elementByLogicalIndex(i + 2); const MPlug c3 = plug.elementByLogicalIndex(i + 3); temp[ 0] = c0.child(0).asInt(); temp[ 1] = c0.child(1).asInt(); temp[ 2] = c0.child(2).asInt(); temp[ 3] = c1.child(0).asInt(); temp[ 4] = c1.child(1).asInt(); temp[ 5] = c1.child(2).asInt(); temp[ 6] = c2.child(0).asInt(); temp[ 7] = c2.child(1).asInt(); temp[ 8] = c2.child(2).asInt(); temp[ 9] = c3.child(0).asInt(); temp[10] = c3.child(1).asInt(); temp[11] = c3.child(2).asInt(); int32_t* optr = values + (i * 3); storeu8i(optr + 0, load8i(temp + 0)); storeu4i(optr + 8, load4i(temp + 8)); i += 4; } #else uint32_t count4 = count & ~0x3; uint32_t i = 0; for(; i < count4; i += 4) { ALIGN16(int32_t temp[12]); const MPlug c0 = plug.elementByLogicalIndex(i ); const MPlug c1 = plug.elementByLogicalIndex(i + 1); const MPlug c2 = plug.elementByLogicalIndex(i + 2); const MPlug c3 = plug.elementByLogicalIndex(i + 3); temp[ 0] = c0.child(0).asInt(); temp[ 1] = c0.child(1).asInt(); temp[ 2] = c0.child(2).asInt(); temp[ 3] = c1.child(0).asInt(); temp[ 4] = c1.child(1).asInt(); temp[ 5] = c1.child(2).asInt(); temp[ 6] = c2.child(0).asInt(); temp[ 7] = c2.child(1).asInt(); temp[ 8] = c2.child(2).asInt(); temp[ 9] = c3.child(0).asInt(); temp[10] = c3.child(1).asInt(); temp[11] = c3.child(2).asInt(); int32_t* optr = values + (i * 3); storeu4i(optr + 0, load4i(temp + 0)); storeu4i(optr + 4, load4i(temp + 4)); storeu4i(optr + 8, load4i(temp + 8)); } #endif int32_t* optr = values + (i * 3); MPlug elem; switch(count & 3) { case 3: elem = plug.elementByLogicalIndex(i + 2); optr[6] = elem.child(0).asInt(); optr[7] = elem.child(1).asInt(); optr[8] = elem.child(2).asInt(); case 2: elem = plug.elementByLogicalIndex(i + 1); optr[3] = elem.child(0).asInt(); optr[4] = elem.child(1).asInt(); optr[5] = elem.child(2).asInt(); case 1: elem = plug.elementByLogicalIndex(i); optr[0] = elem.child(0).asInt(); optr[1] = elem.child(1).asInt(); optr[2] = elem.child(2).asInt(); default: break; } #else for(uint32_t i = 0, j = 0; i < num; ++i, j += 3) { MPlug elem = plug.elementByLogicalIndex(i); values[j ] = elem.child(0).asInt(); values[j + 1] = elem.child(1).asInt(); values[j + 2] = elem.child(2).asInt(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec4Array(MObject node, MObject attribute, int32_t* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } size_t count2 = count & ~1; size_t i = 0, j = 0; for(; i < count2; i += 2, j += 8) { ALIGN32(int32_t temp[8]); MPlug elem0 = plug.elementByLogicalIndex(i); MPlug elem1 = plug.elementByLogicalIndex(i + 1); temp[0] = elem0.child(0).asInt(); temp[1] = elem0.child(1).asInt(); temp[2] = elem0.child(2).asInt(); temp[3] = elem0.child(3).asInt(); temp[4] = elem1.child(0).asInt(); temp[5] = elem1.child(1).asInt(); temp[6] = elem1.child(2).asInt(); temp[7] = elem1.child(3).asInt(); #if AL_UTILS_ENABLE_SIMD # ifdef __AVX__ storeu8i(values + j, load8i(temp)); # else storeu4i(values + j, load4i(temp)); storeu4i(values + j + 4, load4i(temp + 4)); # endif #else values[j + 0] = temp[0]; values[j + 1] = temp[1]; values[j + 2] = temp[2]; values[j + 3] = temp[3]; values[j + 4] = temp[4]; values[j + 5] = temp[5]; values[j + 6] = temp[6]; values[j + 7] = temp[7]; #endif } if(count & 1) { ALIGN16(int32_t temp[4]); MPlug elem0 = plug.elementByLogicalIndex(i); temp[0] = elem0.child(0).asInt(); temp[1] = elem0.child(1).asInt(); temp[2] = elem0.child(2).asInt(); temp[3] = elem0.child(3).asInt(); #if AL_UTILS_ENABLE_SIMD storeu4i(values + j, load4i(temp)); #else values[j + 0] = temp[0]; values[j + 1] = temp[1]; values[j + 2] = temp[2]; values[j + 3] = temp[3]; #endif } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec4Array(MObject node, MObject attribute, float* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } size_t count2 = count & ~1; size_t i = 0, j = 0; for(; i < count2; i += 2, j += 8) { ALIGN32(float temp[8]); MPlug elem0 = plug.elementByLogicalIndex(i); MPlug elem1 = plug.elementByLogicalIndex(i + 1); temp[0] = elem0.child(0).asFloat(); temp[1] = elem0.child(1).asFloat(); temp[2] = elem0.child(2).asFloat(); temp[3] = elem0.child(3).asFloat(); temp[4] = elem1.child(0).asFloat(); temp[5] = elem1.child(1).asFloat(); temp[6] = elem1.child(2).asFloat(); temp[7] = elem1.child(3).asFloat(); #if AL_UTILS_ENABLE_SIMD # ifdef __AVX__ storeu8f(values + j, load8f(temp)); # else storeu4f(values + j, load4f(temp)); storeu4f(values + j + 4, load4f(temp + 4)); # endif #else values[j + 0] = temp[0]; values[j + 1] = temp[1]; values[j + 2] = temp[2]; values[j + 3] = temp[3]; values[j + 4] = temp[4]; values[j + 5] = temp[5]; values[j + 6] = temp[6]; values[j + 7] = temp[7]; #endif } if(count & 1) { ALIGN16(float temp[4]); MPlug elem0 = plug.elementByLogicalIndex(i); temp[0] = elem0.child(0).asFloat(); temp[1] = elem0.child(1).asFloat(); temp[2] = elem0.child(2).asFloat(); temp[3] = elem0.child(3).asFloat(); #if AL_UTILS_ENABLE_SIMD storeu4f(values + j, load4f(temp)); #else values[j + 0] = temp[0]; values[j + 1] = temp[1]; values[j + 2] = temp[2]; values[j + 3] = temp[3]; #endif } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec4Array(MObject node, MObject attribute, double* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } for(uint32_t i = 0, j = 0; i < num; ++i, j += 4) { ALIGN32(double temp[4]); MPlug elem = plug.elementByLogicalIndex(i); temp[0] = elem.child(0).asDouble(); temp[1] = elem.child(1).asDouble(); temp[2] = elem.child(2).asDouble(); temp[3] = elem.child(3).asDouble(); #if AL_UTILS_ENABLE_SIMD # ifdef __AVX__ storeu4d(values + j, load4d(temp)); # else storeu2d(values + j, load2d(temp)); storeu2d(values + j + 2, load2d(temp + 2)); # endif #else values[j + 0] = temp[0]; values[j + 1] = temp[1]; values[j + 2] = temp[2]; values[j + 3] = temp[3]; #endif } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec4Array(MObject node, MObject attribute, GfHalf* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } size_t count2 = count & ~0x1ULL; for(uint32_t i = 0, j = 0; i < count2; i += 2, j += 8) { MPlug v0 = plug.elementByLogicalIndex(i + 0); MPlug v1 = plug.elementByLogicalIndex(i + 1); float f[8]; f[0] = v0.child(0).asFloat(); f[1] = v0.child(1).asFloat(); f[2] = v0.child(2).asFloat(); f[3] = v0.child(3).asFloat(); f[4] = v1.child(0).asFloat(); f[5] = v1.child(1).asFloat(); f[6] = v1.child(2).asFloat(); f[7] = v1.child(3).asFloat(); AL::usd::utils::float2half_8f(f, values + j); } if(count & 0x1) { MPlug v0 = plug.elementByLogicalIndex(count2); float f[4]; f[0] = v0.child(0).asFloat(); f[1] = v0.child(1).asFloat(); f[2] = v0.child(2).asFloat(); f[3] = v0.child(3).asFloat(); AL::usd::utils::float2half_4f(f, values + count2 * 4); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getQuatArray(MObject node, MObject attr, GfHalf* const values, const size_t count) { return getVec4Array(node, attr, values, count); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getQuatArray(MObject node, MObject attr, float* const values, const size_t count) { return getVec4Array(node, attr, values, count); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getQuatArray(MObject node, MObject attr, double* const values, const size_t count) { return getVec4Array(node, attr, values, count); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getMatrix2x2Array(MObject node, MObject attribute, double* const values, const size_t count) { const char* const errorString = "getMatrix2x2Array error"; MPlug arrayPlug(node, attribute); for(uint32_t i = 0; i < count; ++i) { double* const str = values + i * 4; MPlug plug = arrayPlug.elementByLogicalIndex(i); AL_MAYA_CHECK_ERROR(plug.child(0).child(0).getValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).getValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).getValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).getValue(str[3]), errorString); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getMatrix2x2Array(MObject node, MObject attribute, float* const values, const size_t count) { const char* const errorString = "getMatrix2x2Array error"; MPlug arrayPlug(node, attribute); for(uint32_t i = 0; i < count; ++i) { float* const str = values + i * 4; MPlug plug = arrayPlug.elementByLogicalIndex(i); AL_MAYA_CHECK_ERROR(plug.child(0).child(0).getValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).getValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).getValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).getValue(str[3]), errorString); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getMatrix3x3Array(MObject node, MObject attribute, double* const values, const size_t count) { const char* const errorString = "getMatrix3x3Array error"; MPlug arrayPlug(node, attribute); for(uint32_t i = 0; i < count; ++i) { double* const str = values + i * 9; MPlug plug = arrayPlug.elementByLogicalIndex(i); AL_MAYA_CHECK_ERROR(plug.child(0).child(0).getValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).getValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(2).getValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).getValue(str[3]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).getValue(str[4]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(2).getValue(str[5]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(0).getValue(str[6]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(1).getValue(str[7]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(2).getValue(str[8]), errorString); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getMatrix3x3Array(MObject node, MObject attribute, float* const values, const size_t count) { const char* const errorString = "getMatrix3x3Array error"; MPlug arrayPlug(node, attribute); for(uint32_t i = 0; i < count; ++i) { float* const str = values + i * 9; MPlug plug = arrayPlug.elementByLogicalIndex(i); AL_MAYA_CHECK_ERROR(plug.child(0).child(0).getValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).getValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(2).getValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).getValue(str[3]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).getValue(str[4]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(2).getValue(str[5]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(0).getValue(str[6]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(1).getValue(str[7]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(2).getValue(str[8]), errorString); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getMatrix4x4Array(MObject node, MObject attribute, float* const values, const size_t count) { MPlug plug(node, attribute); if(!plug) return MS::kFailure; if(plug.isArray()) { uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } MFnMatrixData fn; MObject elementValue; for(uint32_t i = 0, j = 0; i < count; ++i, j += 16) { plug.elementByLogicalIndex(i).getValue(elementValue); fn.setObject(elementValue); const MMatrix& m = fn.matrix(); #if AL_UTILS_ENABLE_SIMD # ifdef __AVX__ const f128 m0 = cvt4d_to_4f(loadu4d(&m.matrix[0][0])); const f128 m1 = cvt4d_to_4f(loadu4d(&m.matrix[1][0])); const f128 m2 = cvt4d_to_4f(loadu4d(&m.matrix[2][0])); const f128 m3 = cvt4d_to_4f(loadu4d(&m.matrix[3][0])); # else const f128 m0a = cvt2d_to_2f(loadu2d(&m.matrix[0][0])); const f128 m0b = cvt2d_to_2f(loadu2d(&m.matrix[0][2])); const f128 m1a = cvt2d_to_2f(loadu2d(&m.matrix[1][0])); const f128 m1b = cvt2d_to_2f(loadu2d(&m.matrix[1][2])); const f128 m2a = cvt2d_to_2f(loadu2d(&m.matrix[2][0])); const f128 m2b = cvt2d_to_2f(loadu2d(&m.matrix[2][2])); const f128 m3a = cvt2d_to_2f(loadu2d(&m.matrix[3][0])); const f128 m3b = cvt2d_to_2f(loadu2d(&m.matrix[3][2])); const f128 m0 = movelh4f(m0a, m0b); const f128 m1 = movelh4f(m1a, m1b); const f128 m2 = movelh4f(m2a, m2b); const f128 m3 = movelh4f(m3a, m3b); # endif float* optr = values + j; storeu4f(optr, m0); storeu4f(optr + 4, m1); storeu4f(optr + 8, m2); storeu4f(optr + 12, m3); #else float* optr = values + j; optr[0] = m.matrix[0][0]; optr[1] = m.matrix[0][1]; optr[2] = m.matrix[0][2]; optr[3] = m.matrix[0][3]; optr[4] = m.matrix[1][0]; optr[5] = m.matrix[1][1]; optr[6] = m.matrix[1][2]; optr[7] = m.matrix[1][3]; optr[8] = m.matrix[2][0]; optr[9] = m.matrix[2][1]; optr[10] = m.matrix[2][2]; optr[11] = m.matrix[2][3]; optr[12] = m.matrix[3][0]; optr[13] = m.matrix[3][1]; optr[14] = m.matrix[3][2]; optr[15] = m.matrix[3][3]; #endif } } else { MObject value; plug.getValue(value); MFnMatrixArrayData fn(value); for(uint32_t i = 0, n = fn.length(); i < n; ++i) { float* optr = values + i * 16; double* iptr = &fn[i].matrix[0][0]; #if AL_UTILS_ENABLE_SIMD # ifdef __AVX__ const f128 m0 = cvt4d_to_4f(loadu4d(iptr)); const f128 m1 = cvt4d_to_4f(loadu4d(iptr + 4)); const f128 m2 = cvt4d_to_4f(loadu4d(iptr + 8)); const f128 m3 = cvt4d_to_4f(loadu4d(iptr + 12)); # else const f128 m0a = cvt2d_to_2f(loadu2d(iptr)); const f128 m0b = cvt2d_to_2f(loadu2d(iptr + 2)); const f128 m1a = cvt2d_to_2f(loadu2d(iptr + 4)); const f128 m1b = cvt2d_to_2f(loadu2d(iptr + 6)); const f128 m2a = cvt2d_to_2f(loadu2d(iptr + 8)); const f128 m2b = cvt2d_to_2f(loadu2d(iptr + 10)); const f128 m3a = cvt2d_to_2f(loadu2d(iptr + 12)); const f128 m3b = cvt2d_to_2f(loadu2d(iptr + 14)); const f128 m0 = movelh4f(m0a, m0b); const f128 m1 = movelh4f(m1a, m1b); const f128 m2 = movelh4f(m2a, m2b); const f128 m3 = movelh4f(m3a, m3b); # endif storeu4f(optr, m0); storeu4f(optr + 4, m1); storeu4f(optr + 8, m2); storeu4f(optr + 12, m3); #else for(int k = 0; k < 16; ++k) { optr[k] = iptr[k]; } #endif } } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getMatrix4x4Array(MObject node, MObject attribute, double* const values, const size_t count) { MPlug plug(node, attribute); if(!plug) return MS::kFailure; if(plug.isArray()) { uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } MFnMatrixData fn; MObject elementValue; for(uint32_t i = 0, j = 0; i < count; ++i, j += 16) { plug.elementByLogicalIndex(i).getValue(elementValue); fn.setObject(elementValue); const MMatrix& m = fn.matrix(); #if AL_UTILS_ENABLE_SIMD # ifdef __AVX__ double* optr = values + j; storeu4d(optr + 0, loadu4d(&m.matrix[0][0])); storeu4d(optr + 4, loadu4d(&m.matrix[1][0])); storeu4d(optr + 8, loadu4d(&m.matrix[2][0])); storeu4d(optr + 12, loadu4d(&m.matrix[3][0])); # else double* optr = values + j; storeu2d(optr + 0, loadu2d(&m.matrix[0][0])); storeu2d(optr + 2, loadu2d(&m.matrix[0][2])); storeu2d(optr + 4, loadu2d(&m.matrix[1][0])); storeu2d(optr + 6, loadu2d(&m.matrix[1][2])); storeu2d(optr + 8, loadu2d(&m.matrix[2][0])); storeu2d(optr + 10, loadu2d(&m.matrix[2][2])); storeu2d(optr + 12, loadu2d(&m.matrix[3][0])); storeu2d(optr + 14, loadu2d(&m.matrix[3][2])); # endif #else double* optr = values + j; optr[0] = m.matrix[0][0]; optr[1] = m.matrix[0][1]; optr[2] = m.matrix[0][2]; optr[3] = m.matrix[0][3]; optr[4] = m.matrix[1][0]; optr[5] = m.matrix[1][1]; optr[6] = m.matrix[1][2]; optr[7] = m.matrix[1][3]; optr[8] = m.matrix[2][0]; optr[9] = m.matrix[2][1]; optr[10] = m.matrix[2][2]; optr[11] = m.matrix[2][3]; optr[12] = m.matrix[3][0]; optr[13] = m.matrix[3][1]; optr[14] = m.matrix[3][2]; optr[15] = m.matrix[3][3]; #endif } } else { MObject value; plug.getValue(value); MFnMatrixArrayData fn(value); for(uint32_t i = 0, n = fn.length(); i < n; ++i) { double* optr = values + i * 16; double* iptr = &fn[i].matrix[0][0]; #if AL_UTILS_ENABLE_SIMD # ifdef __AVX__ storeu4d(optr, loadu4d(iptr)); storeu4d(optr + 4, loadu4d(iptr + 4)); storeu4d(optr + 8, loadu4d(iptr + 8)); storeu4d(optr + 12, loadu4d(iptr + 12)); # else storeu2d(optr , loadu2d(iptr)); storeu2d(optr + 2, loadu2d(iptr + 2)); storeu2d(optr + 4, loadu2d(iptr + 4)); storeu2d(optr + 6, loadu2d(iptr + 6)); storeu2d(optr + 8, loadu2d(iptr + 8)); storeu2d(optr + 10, loadu2d(iptr + 10)); storeu2d(optr + 12, loadu2d(iptr + 12)); storeu2d(optr + 14, loadu2d(iptr + 14)); # endif #else for(uint32_t k = 0; k < 16; ++k) { optr[k] = iptr[k]; } #endif } } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getTimeArray(MObject node, MObject attribute, float* const values, const size_t count, MTime::Unit unit) { const MTime mod(1.0, MTime::k6000FPS); const float unitConversion = float(mod.as(unit)); MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD #if defined(__AVX__) && ENABLE_SOME_AVX_ROUTINES const f256 unitConversion256 = splat8f(unitConversion); const f128 unitConversion128 = splat4f(unitConversion); uint32_t count8 = count & ~0x7; uint32_t i = 0; for(; i < count8; i += 8) { ALIGN32(float temp[8]); temp[0] = plug.elementByLogicalIndex(i).asFloat(); temp[1] = plug.elementByLogicalIndex(i + 1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 2).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 3).asFloat(); temp[4] = plug.elementByLogicalIndex(i + 4).asFloat(); temp[5] = plug.elementByLogicalIndex(i + 5).asFloat(); temp[6] = plug.elementByLogicalIndex(i + 6).asFloat(); temp[7] = plug.elementByLogicalIndex(i + 7).asFloat(); storeu8f(values + i, mul8f(unitConversion256, load8f(temp))); } if(count & 0x4) { ALIGN16(float temp[4]); temp[0] = plug.elementByLogicalIndex(i).asFloat(); temp[1] = plug.elementByLogicalIndex(i + 1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 2).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 3).asFloat(); storeu4f(values + i, mul4f(unitConversion128, load4f(temp))); i += 4; } #else const f128 unitConversion128 = splat4f(unitConversion); uint32_t count4 = count & ~0x3; uint32_t i = 0; for(; i < count4; i += 4) { ALIGN16(float temp[4]); temp[0] = plug.elementByLogicalIndex(i).asFloat(); temp[1] = plug.elementByLogicalIndex(i + 1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 2).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 3).asFloat(); storeu4f(values + i, mul4f(unitConversion128, load4f(temp))); } #endif switch(count & 3) { case 3: values[i + 2] = unitConversion * plug.elementByLogicalIndex(i + 2).asFloat(); case 2: values[i + 1] = unitConversion * plug.elementByLogicalIndex(i + 1).asFloat(); case 1: values[i ] = unitConversion * plug.elementByLogicalIndex(i ).asFloat(); default: break; } #else for(uint32_t i = 0; i < num; ++i) { values[i] = unitConversion * plug.elementByLogicalIndex(i).asFloat(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getAngleArray(MObject node, MObject attribute, float* const values, const size_t count, MAngle::Unit unit) { const MAngle mod(1.0, MAngle::internalUnit()); const float unitConversion = float(mod.as(unit)); MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD #if defined(__AVX__) && ENABLE_SOME_AVX_ROUTINES const f256 unitConversion256 = splat8f(unitConversion); const f128 unitConversion128 = splat4f(unitConversion); uint32_t count8 = count & ~0x7; uint32_t i = 0; for(; i < count8; i += 8) { ALIGN32(float temp[8]); temp[0] = plug.elementByLogicalIndex(i).asFloat(); temp[1] = plug.elementByLogicalIndex(i + 1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 2).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 3).asFloat(); temp[4] = plug.elementByLogicalIndex(i + 4).asFloat(); temp[5] = plug.elementByLogicalIndex(i + 5).asFloat(); temp[6] = plug.elementByLogicalIndex(i + 6).asFloat(); temp[7] = plug.elementByLogicalIndex(i + 7).asFloat(); storeu8f(values + i, mul8f(unitConversion256, load8f(temp))); } if(count & 0x4) { ALIGN16(float temp[4]); temp[0] = plug.elementByLogicalIndex(i).asFloat(); temp[1] = plug.elementByLogicalIndex(i + 1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 2).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 3).asFloat(); storeu4f(values + i, mul4f(unitConversion128, load4f(temp))); i += 4; } #else const f128 unitConversion128 = splat4f(unitConversion); uint32_t count4 = count & ~0x3; uint32_t i = 0; for(; i < count4; i += 4) { ALIGN16(float temp[4]); temp[0] = plug.elementByLogicalIndex(i).asFloat(); temp[1] = plug.elementByLogicalIndex(i + 1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 2).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 3).asFloat(); storeu4f(values + i, mul4f(unitConversion128, load4f(temp))); } #endif switch(count & 3) { case 3: values[i + 2] = unitConversion * plug.elementByLogicalIndex(i + 2).asFloat(); case 2: values[i + 1] = unitConversion * plug.elementByLogicalIndex(i + 1).asFloat(); case 1: values[i] = unitConversion * plug.elementByLogicalIndex(i).asFloat(); default: break; } #else for(uint32_t i = 0; i < num; ++i) { values[i] = unitConversion * plug.elementByLogicalIndex(i).asFloat(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getDistanceArray(MObject node, MObject attribute, float* const values, const size_t count, MDistance::Unit unit) { const MDistance mod(1.0, MDistance::internalUnit()); const float unitConversion = float(mod.as(unit)); MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD #if defined(__AVX__) && ENABLE_SOME_AVX_ROUTINES const f256 unitConversion256 = splat8f(unitConversion); const f128 unitConversion128 = splat4f(unitConversion); uint32_t count8 = count & ~0x7; uint32_t i = 0; for(; i < count8; i += 8) { ALIGN32(float temp[8]); temp[0] = plug.elementByLogicalIndex(i).asFloat(); temp[1] = plug.elementByLogicalIndex(i + 1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 2).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 3).asFloat(); temp[4] = plug.elementByLogicalIndex(i + 4).asFloat(); temp[5] = plug.elementByLogicalIndex(i + 5).asFloat(); temp[6] = plug.elementByLogicalIndex(i + 6).asFloat(); temp[7] = plug.elementByLogicalIndex(i + 7).asFloat(); storeu8f(values + i, mul8f(unitConversion256, load8f(temp))); } if(count & 0x4) { ALIGN16(float temp[4]); temp[0] = plug.elementByLogicalIndex(i).asFloat(); temp[1] = plug.elementByLogicalIndex(i + 1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 2).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 3).asFloat(); storeu4f(values + i, mul4f(unitConversion128, load4f(temp))); i += 4; } #else const f128 unitConversion128 = splat4f(unitConversion); uint32_t count4 = count & ~0x3; uint32_t i = 0; for(; i < count4; i += 4) { ALIGN16(float temp[4]); temp[0] = plug.elementByLogicalIndex(i).asFloat(); temp[1] = plug.elementByLogicalIndex(i + 1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 2).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 3).asFloat(); storeu4f(values + i, mul4f(unitConversion128, load4f(temp))); } #endif switch(count & 3) { case 3: values[i + 2] = unitConversion * plug.elementByLogicalIndex(i + 2).asFloat(); case 2: values[i + 1] = unitConversion * plug.elementByLogicalIndex(i + 1).asFloat(); case 1: values[i] = unitConversion * plug.elementByLogicalIndex(i).asFloat(); default: break; } #else for(uint32_t i = 0; i < num; ++i) { values[i] = unitConversion * plug.elementByLogicalIndex(i).asFloat(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setString(MObject node, MObject attr, const std::string& str) { return setString(node, attr, str.c_str()); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec2(MObject node, MObject attr, const int* const xy) { const char* const errorString = "vec2i error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xy[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xy[1]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec2(MObject node, MObject attr, const float* const xy) { const char* const errorString = "vec2f error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xy[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xy[1]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec2(MObject node, MObject attr, const GfHalf* const xy) { const char* const errorString = "vec2h error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(AL::usd::utils::float2half_1f(xy[0])), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(AL::usd::utils::float2half_1f(xy[1])), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec2(MObject node, MObject attr, const double* const xy) { const char* const errorString = "vec2d error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xy[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xy[1]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec3(MObject node, MObject attr, const int* const xyz) { const char* const errorString = "vec3i error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xyz[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xyz[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(xyz[2]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec3(MObject node, MObject attr, const float* const xyz) { const char* const errorString = "vec3f error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xyz[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xyz[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(xyz[2]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec3(MObject node, MObject attr, const GfHalf* const xyz) { const char* const errorString = "vec3h error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(AL::usd::utils::float2half_1f(xyz[0])), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(AL::usd::utils::float2half_1f(xyz[1])), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(AL::usd::utils::float2half_1f(xyz[2])), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec3(MObject node, MObject attr, const double* const xyz) { const char* const errorString = "vec3d error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xyz[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xyz[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(xyz[2]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec4(MObject node, MObject attr, const int* const xyzw) { const char* const errorString = "vec4i error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xyzw[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xyzw[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(xyzw[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(3).setValue(xyzw[3]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec4(MObject node, MObject attr, const float* const xyzw) { const char* const errorString = "vec4f error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xyzw[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xyzw[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(xyzw[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(3).setValue(xyzw[3]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec4(MObject node, MObject attr, const double* const xyzw) { const char* const errorString = "vec4d error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xyzw[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xyzw[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(xyzw[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(3).setValue(xyzw[3]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec4(MObject node, MObject attr, const GfHalf* const xyzw) { const char* const errorString = "vec4h error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(AL::usd::utils::float2half_1f(xyzw[0])), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(AL::usd::utils::float2half_1f(xyzw[1])), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(AL::usd::utils::float2half_1f(xyzw[2])), errorString); AL_MAYA_CHECK_ERROR(plug.child(3).setValue(AL::usd::utils::float2half_1f(xyzw[3])), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setQuat(MObject node, MObject attr, const float* const xyzw) { const char* const errorString = "quatf error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xyzw[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xyzw[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(xyzw[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(3).setValue(xyzw[3]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setQuat(MObject node, MObject attr, const double* const xyzw) { const char* const errorString = "quatd error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xyzw[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xyzw[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(xyzw[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(3).setValue(xyzw[3]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setQuat(MObject node, MObject attr, const GfHalf* const xyzw) { const char* const errorString = "quath error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(AL::usd::utils::float2half_1f(xyzw[0])), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(AL::usd::utils::float2half_1f(xyzw[1])), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(AL::usd::utils::float2half_1f(xyzw[2])), errorString); AL_MAYA_CHECK_ERROR(plug.child(3).setValue(AL::usd::utils::float2half_1f(xyzw[3])), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setString(MObject node, MObject attr, const char* const str) { const char* const errorString = "string error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.setString(str), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMatrix4x4(MObject node, MObject attr, const double* const str) { const char* const errorString = "matrix4x4 error - unimplemented"; MPlug plug(node, attr); MFnMatrixData fn; typedef double hack[4]; MObject data = fn.create(MMatrix((const hack*)str)); AL_MAYA_CHECK_ERROR(plug.setValue(data), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMatrix4x4(MObject node, MObject attr, const float* const ptr) { const char* const errorString = "matrix4x4 error - unimplemented"; MPlug plug(node, attr); MFnMatrixData fn; MMatrix m; #if AL_UTILS_ENABLE_SIMD # if __AVX__ const f256 d0 = loadu8f(ptr); const f256 d1 = loadu8f(ptr + 8); storeu4d(&m.matrix[0][0], cvt4f_to_4d(extract4f(d0, 0))); storeu4d(&m.matrix[1][0], cvt4f_to_4d(extract4f(d0, 1))); storeu4d(&m.matrix[2][0], cvt4f_to_4d(extract4f(d1, 0))); storeu4d(&m.matrix[3][0], cvt4f_to_4d(extract4f(d1, 1))); # else const f128 d0 = loadu4f(ptr); const f128 d1 = loadu4f(ptr + 4); const f128 d2 = loadu4f(ptr + 8); const f128 d3 = loadu4f(ptr + 12); storeu2d(&m.matrix[0][0], cvt2f_to_2d(d0)); storeu2d(&m.matrix[0][2], cvt2f_to_2d(movehl4f(d0, d0))); storeu2d(&m.matrix[1][0], cvt2f_to_2d(d1)); storeu2d(&m.matrix[1][2], cvt2f_to_2d(movehl4f(d1, d1))); storeu2d(&m.matrix[2][0], cvt2f_to_2d(d2)); storeu2d(&m.matrix[2][2], cvt2f_to_2d(movehl4f(d2, d2))); storeu2d(&m.matrix[3][0], cvt2f_to_2d(d3)); storeu2d(&m.matrix[3][2], cvt2f_to_2d(movehl4f(d3, d3))); # endif #else m[0][0] = ptr[0]; m[0][1] = ptr[1]; m[0][2] = ptr[2]; m[0][3] = ptr[3]; m[1][0] = ptr[4]; m[1][1] = ptr[5]; m[1][2] = ptr[6]; m[1][3] = ptr[7]; m[2][0] = ptr[8]; m[2][1] = ptr[9]; m[2][2] = ptr[10]; m[2][3] = ptr[11]; m[3][0] = ptr[12]; m[3][1] = ptr[13]; m[3][2] = ptr[14]; m[3][3] = ptr[15]; #endif MObject data = fn.create(m); AL_MAYA_CHECK_ERROR(plug.setValue(data), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMatrix3x3(MObject node, MObject attr, const double* const str) { const char* const errorString = "matrix3x3 error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).child(0).setValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).setValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(2).setValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).setValue(str[3]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).setValue(str[4]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(2).setValue(str[5]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(0).setValue(str[6]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(1).setValue(str[7]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(2).setValue(str[8]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMatrix3x3(MObject node, MObject attr, const float* const str) { const char* const errorString = "matrix3x3 error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).child(0).setValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).setValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(2).setValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).setValue(str[3]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).setValue(str[4]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(2).setValue(str[5]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(0).setValue(str[6]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(1).setValue(str[7]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(2).setValue(str[8]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMatrix2x2(MObject node, MObject attr, const double* const str) { const char* const errorString = "matrix2x2 error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).child(0).setValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).setValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).setValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).setValue(str[3]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMatrix2x2(MObject node, MObject attr, const float* const str) { const char* const errorString = "matrix2x2 error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).child(0).setValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).setValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).setValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).setValue(str[3]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMatrix2x2Array(MObject node, MObject attribute, const double* const values, const size_t count) { const char* const errorString = "setMatrix2x2Array error"; MPlug arrayPlug(node, attribute); arrayPlug.setNumElements(count); for(uint32_t i = 0; i < count; ++i) { const double* const str = values + i * 4; MPlug plug = arrayPlug.elementByLogicalIndex(i); AL_MAYA_CHECK_ERROR(plug.child(0).child(0).setValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).setValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).setValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).setValue(str[3]), errorString); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMatrix2x2Array(MObject node, MObject attribute, const float* const values, const size_t count) { const char* const errorString = "setMatrix2x2Array error"; MPlug arrayPlug(node, attribute); arrayPlug.setNumElements(count); for(uint32_t i = 0; i < count; ++i) { const float* const str = values + i * 4; MPlug plug = arrayPlug.elementByLogicalIndex(i); AL_MAYA_CHECK_ERROR(plug.child(0).child(0).setValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).setValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).setValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).setValue(str[3]), errorString); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMatrix3x3Array(MObject node, MObject attribute, const double* const values, const size_t count) { const char* const errorString = "setMatrix3x3Array error"; MPlug arrayPlug(node, attribute); arrayPlug.setNumElements(count); for(uint32_t i = 0; i < count; ++i) { const double* const str = values + i * 9; MPlug plug = arrayPlug.elementByLogicalIndex(i); AL_MAYA_CHECK_ERROR(plug.child(0).child(0).setValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).setValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(2).setValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).setValue(str[3]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).setValue(str[4]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(2).setValue(str[5]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(0).setValue(str[6]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(1).setValue(str[7]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(2).setValue(str[8]), errorString); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMatrix3x3Array(MObject node, MObject attribute, const float* const values, const size_t count) { const char* const errorString = "setMatrix3x3Array error"; MPlug arrayPlug(node, attribute); arrayPlug.setNumElements(count); for(uint32_t i = 0; i < count; ++i) { const float* const str = values + i * 9; MPlug plug = arrayPlug.elementByLogicalIndex(i); AL_MAYA_CHECK_ERROR(plug.child(0).child(0).setValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).setValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(2).setValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).setValue(str[3]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).setValue(str[4]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(2).setValue(str[5]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(0).setValue(str[6]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(1).setValue(str[7]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(2).setValue(str[8]), errorString); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setStringArray(MObject node, MObject attribute, const std::string* const values, const size_t count) { const char* const errorString = "DgNodeHelper::setStringArray error"; MPlug plug(node, attribute); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } plug.setNumElements(count); for(uint32_t i = 0; i < count; ++i) { MPlug elem = plug.elementByLogicalIndex(i); elem.setString(MString(values[i].c_str(), values[i].size())); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setQuatArray(MObject node, MObject attr, const GfHalf* const values, const size_t count) { return setVec4Array(node, attr, values, count); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setQuatArray(MObject node, MObject attr, const float* const values, const size_t count) { return setVec4Array(node, attr, values, count); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setQuatArray(MObject node, MObject attr, const double* const values, const size_t count) { return setVec4Array(node, attr, values, count); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getFloat(MObject node, MObject attr, float& value) { const char* const errorString = "DgNodeHelper::getFloat error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } return plug.getValue(value); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getDouble(MObject node, MObject attr, double& value) { const char* const errorString = "DgNodeHelper::getDouble error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } return plug.getValue(value); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getTime(MObject node, MObject attr, MTime& value) { const char* const errorString = "DgNodeHelper::getTime error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } return plug.getValue(value); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getDistance(MObject node, MObject attr, MDistance& value) { const char* const errorString = "DgNodeHelper::getDistance error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } return plug.getValue(value); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getAngle(MObject node, MObject attr, MAngle& value) { const char* const errorString = "DgNodeHelper::getAngle error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } return plug.getValue(value); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getBool(MObject node, MObject attr, bool& value) { const char* const errorString = "DgNodeHelper::getBool error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } return plug.getValue(value); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getInt8(MObject node, MObject attr, int8_t& value) { const char* const errorString = "DgNodeHelper::getInt32 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } char c; MStatus status = plug.getValue(c); value = c; return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getInt16(MObject node, MObject attr, int16_t& value) { const char* const errorString = "DgNodeHelper::getInt32 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } return plug.getValue(value); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getInt32(MObject node, MObject attr, int32_t& value) { const char* const errorString = "DgNodeHelper::getInt32 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } return plug.getValue(value); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getInt64(MObject node, MObject attr, int64_t& value) { const char* const errorString = "DgNodeHelper::getInt32 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } MStatus status; #if MAYA_API_VERSION >= 201800 value = plug.asInt64(&status); #else value = plug.asInt64(MDGContext::fsNormal, &status); #endif return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getMatrix2x2(MObject node, MObject attr, float* const str) { const char* const errorString = "DgNodeHelper::getMatrix2x2 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.child(0).child(0).getValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).getValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).getValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).getValue(str[3]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getMatrix3x3(MObject node, MObject attr, float* const str) { const char* const errorString = "getMatrix3x3 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.child(0).child(0).getValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).getValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(2).getValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).getValue(str[3]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).getValue(str[4]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(2).getValue(str[5]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(0).getValue(str[6]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(1).getValue(str[7]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(2).getValue(str[8]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getMatrix4x4(MObject node, MObject attr, float* const values) { const char* const errorString = "DgNodeHelper::getMatrix4x4 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } MObject data; AL_MAYA_CHECK_ERROR(plug.getValue(data), errorString); MFnMatrixData fn(data); const MMatrix& mat = fn.matrix(); #if AL_UTILS_ENABLE_SIMD # ifdef __AVX__ const f128 r0 = cvt4d_to_4f(loadu4d(&mat.matrix[0][0])); const f128 r1 = cvt4d_to_4f(loadu4d(&mat.matrix[1][0])); const f128 r2 = cvt4d_to_4f(loadu4d(&mat.matrix[2][0])); const f128 r3 = cvt4d_to_4f(loadu4d(&mat.matrix[3][0])); # else const f128 r0 = movelh4f( cvt2d_to_2f(loadu2d(&mat.matrix[0][0])), cvt2d_to_2f(loadu2d(&mat.matrix[0][2]))); const f128 r1 = movelh4f( cvt2d_to_2f(loadu2d(&mat.matrix[1][0])), cvt2d_to_2f(loadu2d(&mat.matrix[1][2]))); const f128 r2 = movelh4f( cvt2d_to_2f(loadu2d(&mat.matrix[2][0])), cvt2d_to_2f(loadu2d(&mat.matrix[2][2]))); const f128 r3 = movelh4f( cvt2d_to_2f(loadu2d(&mat.matrix[3][0])), cvt2d_to_2f(loadu2d(&mat.matrix[3][2]))); # endif storeu4f(values, r0); storeu4f(values + 4, r1); storeu4f(values + 8, r2); storeu4f(values + 12, r3); #else values[0] = mat.matrix[0][0]; values[1] = mat.matrix[0][1]; values[2] = mat.matrix[0][2]; values[3] = mat.matrix[0][3]; values[4] = mat.matrix[1][0]; values[5] = mat.matrix[1][1]; values[6] = mat.matrix[1][2]; values[7] = mat.matrix[1][3]; values[8] = mat.matrix[2][0]; values[9] = mat.matrix[2][1]; values[10] = mat.matrix[2][2]; values[11] = mat.matrix[2][3]; values[12] = mat.matrix[3][0]; values[13] = mat.matrix[3][1]; values[14] = mat.matrix[3][2]; values[15] = mat.matrix[3][3]; #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getMatrix2x2(MObject node, MObject attr, double* const str) { const char* const errorString = "DgNodeHelper::getMatrix2x2 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.child(0).child(0).getValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).getValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).getValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).getValue(str[3]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getMatrix3x3(MObject node, MObject attr, double* const str) { const char* const errorString = "DgNodeHelper::getMatrix3x3 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.child(0).child(0).getValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).getValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(2).getValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).getValue(str[3]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).getValue(str[4]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(2).getValue(str[5]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(0).getValue(str[6]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(1).getValue(str[7]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(2).getValue(str[8]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getMatrix4x4(MObject node, MObject attr, double* const values) { const char* const errorString = "DgNodeHelper::getMatrix4x4 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } MObject data; AL_MAYA_CHECK_ERROR(plug.getValue(data), errorString); MFnMatrixData fn(data); const MMatrix& mat = fn.matrix(); #if AL_UTILS_ENABLE_SIMD # ifdef __AVX__ const d256 r0 = loadu4d(&mat.matrix[0][0]); const d256 r1 = loadu4d(&mat.matrix[1][0]); const d256 r2 = loadu4d(&mat.matrix[2][0]); const d256 r3 = loadu4d(&mat.matrix[3][0]); storeu4d(values, r0); storeu4d(values + 4, r1); storeu4d(values + 8, r2); storeu4d(values + 12, r3); # else const d128 r0a = loadu2d(&mat.matrix[0][0]); const d128 r0b = loadu2d(&mat.matrix[0][2]); const d128 r1a = loadu2d(&mat.matrix[1][0]); const d128 r1b = loadu2d(&mat.matrix[1][2]); const d128 r2a = loadu2d(&mat.matrix[2][0]); const d128 r2b = loadu2d(&mat.matrix[2][2]); const d128 r3a = loadu2d(&mat.matrix[3][0]); const d128 r3b = loadu2d(&mat.matrix[3][2]); storeu2d(values, r0a); storeu2d(values + 2, r0b); storeu2d(values + 4, r1a); storeu2d(values + 6, r1b); storeu2d(values + 8, r2a); storeu2d(values + 10, r2b); storeu2d(values + 12, r3a); storeu2d(values + 14, r3b); # endif #else values[0] = mat.matrix[0][0]; values[1] = mat.matrix[0][1]; values[2] = mat.matrix[0][2]; values[3] = mat.matrix[0][3]; values[4] = mat.matrix[1][0]; values[5] = mat.matrix[1][1]; values[6] = mat.matrix[1][2]; values[7] = mat.matrix[1][3]; values[8] = mat.matrix[2][0]; values[9] = mat.matrix[2][1]; values[10] = mat.matrix[2][2]; values[11] = mat.matrix[2][3]; values[12] = mat.matrix[3][0]; values[13] = mat.matrix[3][1]; values[14] = mat.matrix[3][2]; values[15] = mat.matrix[3][3]; #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getString(MObject node, MObject attr, std::string& str) { const char* const errorString = "DgNodeHelper::getString error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } MString value; AL_MAYA_CHECK_ERROR(plug.getValue(value), errorString); str.assign(value.asChar(), value.asChar() + value.length()); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec2(MObject node, MObject attr, int* xy) { const char* const errorString = "DgNodeHelper::getVec2 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.child(0).getValue(xy[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).getValue(xy[1]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec2(MObject node, MObject attr, float* xy) { const char* const errorString = "DgNodeHelper::getVec2 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.child(0).getValue(xy[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).getValue(xy[1]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec2(MObject node, MObject attr, double* xy) { const char* const errorString = "DgNodeHelper::getVec2 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.child(0).getValue(xy[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).getValue(xy[1]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec2(MObject node, MObject attr, GfHalf* xy) { float fxy[2]; MStatus status = getVec2(node, attr, fxy); xy[0] = AL::usd::utils::float2half_1f(fxy[0]); xy[1] = AL::usd::utils::float2half_1f(fxy[1]); return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec3(MObject node, MObject attr, int* xyz) { const char* const errorString = "DgNodeHelper::getVec3 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.child(0).getValue(xyz[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).getValue(xyz[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).getValue(xyz[2]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec3(MObject node, MObject attr, float* xyz) { const char* const errorString = "DgNodeHelper::getVec3 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.child(0).getValue(xyz[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).getValue(xyz[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).getValue(xyz[2]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec3(MObject node, MObject attr, double* xyz) { const char* const errorString = "DgNodeHelper::getVec3 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.child(0).getValue(xyz[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).getValue(xyz[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).getValue(xyz[2]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec3(MObject node, MObject attr, GfHalf* xyz) { float fxyz[4]; GfHalf xyzw[4]; MStatus status = getVec3(node, attr, fxyz); AL::usd::utils::float2half_4f(fxyz, xyzw); xyz[0] = xyzw[0]; xyz[1] = xyzw[1]; xyz[2] = xyzw[2]; return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec4(MObject node, MObject attr, int* xyzw) { const char* const errorString = "DgNodeHelper::getVec4 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.child(0).getValue(xyzw[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).getValue(xyzw[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).getValue(xyzw[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(3).getValue(xyzw[3]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec4(MObject node, MObject attr, float* xyzw) { const char* const errorString = "DgNodeHelper::getVec4 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.child(0).getValue(xyzw[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).getValue(xyzw[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).getValue(xyzw[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(3).getValue(xyzw[3]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec4(MObject node, MObject attr, double* xyzw) { const char* const errorString = "DgNodeHelper::getVec4 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.child(0).getValue(xyzw[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).getValue(xyzw[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).getValue(xyzw[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(3).getValue(xyzw[3]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec4(MObject node, MObject attr, GfHalf* xyzw) { float fxyzw[4]; MStatus status = getVec4(node, attr, fxyzw); AL::usd::utils::float2half_4f(fxyzw, xyzw); return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getQuat(MObject node, MObject attr, float* xyzw) { return getVec4(node, attr, xyzw); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getQuat(MObject node, MObject attr, double* xyzw) { return getVec4(node, attr, xyzw); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getQuat(MObject node, MObject attr, GfHalf* xyzw) { return getVec4(node, attr, xyzw); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getUsdBoolArray(const MObject& node, const MObject& attr, VtArray<bool>& values) { // // Handle the oddity that is std::vector<bool> // MPlug plug(node, attr); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); values.resize(num); for(uint32_t i = 0; i < num; ++i) { values[i] = plug.elementByLogicalIndex(i).asBool(); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getStringArray(MObject node, MObject attr, std::string* const values, const size_t count) { const char* const errorString = "DgNodeHelper::getStringArray"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } if(count != plug.numElements()) { return MS::kFailure; } for(size_t i = 0; i < count; ++i) { const MString& str = plug.elementByLogicalIndex(i).asString(); values[i].assign(str.asChar(), str.length()); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::addStringValue(MObject node, const char* const attrName, const char* const stringValue) { MFnTypedAttribute fnT; MObject attribute = fnT.create(attrName, attrName, MFnData::kString); fnT.setArray(false); fnT.setReadable(true); fnT.setWritable(true); MFnDependencyNode fn(node); if(fn.addAttribute(attribute)) { MPlug plug(node, attribute); plug.setValue(stringValue); return MS::kSuccess; } return MS::kFailure; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMatrix4x4(MObject node, MObject attr, const MFloatMatrix& value) { return setMatrix4x4(node, attr, &value[0][0]); } MStatus DgNodeHelper::setMatrix4x4(MObject node, MObject attr, const MMatrix& value) { return setMatrix4x4(node, attr, &value[0][0]); } MStatus DgNodeHelper::getMatrix4x4(MObject node, MObject attr, MFloatMatrix& value) { return getMatrix4x4(node, attr, &value[0][0]); } MStatus DgNodeHelper::getMatrix4x4(MObject node, MObject attr, MMatrix& value) { return getMatrix4x4(node, attr, &value[0][0]); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::copyBool(MObject node, MObject attr, const UsdAttribute& value) { if(value.IsAuthored() && value.HasValue()) { bool data; value.Get<bool> (&data); return setBool(node, attr, data); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::copyFloat(MObject node, MObject attr, const UsdAttribute& value) { if(value.IsAuthored() && value.HasValue()) { float data; value.Get<float> (&data); return setFloat(node, attr, data); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::copyDouble(MObject node, MObject attr, const UsdAttribute& value) { if(value.IsAuthored() && value.HasValue()) { double data; value.Get<double> (&data); return setDouble(node, attr, data); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::copyInt(MObject node, MObject attr, const UsdAttribute& value) { if(value.IsAuthored() && value.HasValue()) { int data; value.Get<int> (&data); return setBool(node, attr, data); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::copyVec3(MObject node, MObject attr, const UsdAttribute& value) { if(value.IsAuthored() && value.HasValue()) { int data; value.Get<int> (&data); return setBool(node, attr, data); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::addDynamicAttribute(MObject node, const UsdAttribute& usdAttr) { const SdfValueTypeName typeName = usdAttr.GetTypeName(); const bool isArray = typeName.IsArray(); const UsdDataType dataType = getAttributeType(usdAttr); MObject attribute = MObject::kNullObj; const char* attrName = usdAttr.GetName().GetString().c_str(); const uint32_t flags = (isArray ? AL::maya::utils::NodeHelper::kArray : 0) | AL::maya::utils::NodeHelper::kReadable | AL::maya::utils::NodeHelper::kWritable | AL::maya::utils::NodeHelper::kStorable | AL::maya::utils::NodeHelper::kConnectable; switch(dataType) { case UsdDataType::kAsset: { return MS::kSuccess; } break; case UsdDataType::kBool: { AL::maya::utils::NodeHelper::addBoolAttr(node, attrName, attrName, false, flags, &attribute); } break; case UsdDataType::kUChar: { AL::maya::utils::NodeHelper::addInt8Attr(node, attrName, attrName, 0, flags, &attribute); } break; case UsdDataType::kInt: case UsdDataType::kUInt: { AL::maya::utils::NodeHelper::addInt32Attr(node, attrName, attrName, 0, flags, &attribute); } break; case UsdDataType::kInt64: case UsdDataType::kUInt64: { AL::maya::utils::NodeHelper::addInt64Attr(node, attrName, attrName, 0, flags, &attribute); } break; case UsdDataType::kHalf: case UsdDataType::kFloat: { AL::maya::utils::NodeHelper::addFloatAttr(node, attrName, attrName, 0, flags, &attribute); } break; case UsdDataType::kDouble: { AL::maya::utils::NodeHelper::addDoubleAttr(node, attrName, attrName, 0, flags, &attribute); } break; case UsdDataType::kString: { AL::maya::utils::NodeHelper::addStringAttr(node, attrName, attrName, flags, true, &attribute); } break; case UsdDataType::kMatrix2d: { const float defValue[2][2] = {{0, 0}, {0, 0}}; AL::maya::utils::NodeHelper::addMatrix2x2Attr(node, attrName, attrName, defValue, flags, &attribute); } break; case UsdDataType::kMatrix3d: { const float defValue[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}; AL::maya::utils::NodeHelper::addMatrix3x3Attr(node, attrName, attrName, defValue, flags, &attribute); } break; case UsdDataType::kMatrix4d: { AL::maya::utils::NodeHelper::addMatrixAttr(node, attrName, attrName, MMatrix(), flags, &attribute); } break; case UsdDataType::kQuatd: { AL::maya::utils::NodeHelper::addVec4dAttr(node, attrName, attrName, flags, &attribute); } break; case UsdDataType::kQuatf: case UsdDataType::kQuath: { AL::maya::utils::NodeHelper::addVec4fAttr(node, attrName, attrName, flags, &attribute); } break; case UsdDataType::kVec2d: { AL::maya::utils::NodeHelper::addVec2dAttr(node, attrName, attrName, flags, &attribute); } break; case UsdDataType::kVec2f: case UsdDataType::kVec2h: { AL::maya::utils::NodeHelper::addVec2fAttr(node, attrName, attrName, flags, &attribute); } break; case UsdDataType::kVec2i: { AL::maya::utils::NodeHelper::addVec2iAttr(node, attrName, attrName, flags, &attribute); } break; case UsdDataType::kVec3d: { AL::maya::utils::NodeHelper::addVec3dAttr(node, attrName, attrName, flags, &attribute); } break; case UsdDataType::kVec3f: case UsdDataType::kVec3h: { AL::maya::utils::NodeHelper::addVec3fAttr(node, attrName, attrName, flags, &attribute); } break; case UsdDataType::kVec3i: { AL::maya::utils::NodeHelper::addVec3iAttr(node, attrName, attrName, flags, &attribute); } break; case UsdDataType::kVec4d: { AL::maya::utils::NodeHelper::addVec4dAttr(node, attrName, attrName, flags, &attribute); } break; case UsdDataType::kVec4f: case UsdDataType::kVec4h: { AL::maya::utils::NodeHelper::addVec4fAttr(node, attrName, attrName, flags, &attribute); } break; case UsdDataType::kVec4i: { AL::maya::utils::NodeHelper::addVec4iAttr(node, attrName, attrName, flags, &attribute); } break; default: MGlobal::displayError("DgNodeTranslator::addDynamicAttribute - unsupported USD data type"); return MS::kFailure; } if(isArray) { return setArrayMayaValue(node, attribute, usdAttr, dataType); } return setSingleMayaValue(node, attribute, usdAttr, dataType); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMayaValue(MObject node, MObject attr, const UsdAttribute& usdAttr) { const SdfValueTypeName typeName = usdAttr.GetTypeName(); UsdDataType dataType = getAttributeType(usdAttr); if(typeName.IsArray()) { return setArrayMayaValue(node, attr, usdAttr, dataType); } return setSingleMayaValue(node, attr, usdAttr, dataType); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setArrayMayaValue(MObject node, MObject attr, const UsdAttribute& usdAttr, const UsdDataType type) { switch(type) { case UsdDataType::kBool: { VtArray<bool> value; usdAttr.Get(&value); return setUsdBoolArray(node, attr, value); } case UsdDataType::kUChar: { VtArray<unsigned char> value; usdAttr.Get(&value); return setInt8Array(node, attr, (const int8_t*)value.cdata(), value.size()); } case UsdDataType::kInt: { VtArray<int32_t> value; usdAttr.Get(&value); return setInt32Array(node, attr, (const int32_t*)value.cdata(), value.size()); } case UsdDataType::kUInt: { VtArray<uint32_t> value; usdAttr.Get(&value); return setInt32Array(node, attr, (const int32_t*)value.cdata(), value.size()); } case UsdDataType::kInt64: { VtArray<int64_t> value; usdAttr.Get(&value); return setInt64Array(node, attr, (const int64_t*)value.cdata(), value.size()); } case UsdDataType::kUInt64: { VtArray<uint64_t> value; usdAttr.Get(&value); return setInt64Array(node, attr, (const int64_t*)value.cdata(), value.size()); } case UsdDataType::kHalf: { VtArray<GfHalf> value; usdAttr.Get(&value); return setHalfArray(node, attr, (const GfHalf*)value.cdata(), value.size()); } case UsdDataType::kFloat: { VtArray<float> value; usdAttr.Get(&value); return setFloatArray(node, attr, (const float*)value.cdata(), value.size()); } case UsdDataType::kDouble: { VtArray<double> value; usdAttr.Get(&value); return setDoubleArray(node, attr, (const double*)value.cdata(), value.size()); } case UsdDataType::kString: { VtArray<std::string> value; usdAttr.Get(&value); return setStringArray(node, attr, (const std::string*)value.cdata(), value.size()); } case UsdDataType::kMatrix2d: { VtArray<GfMatrix2d> value; usdAttr.Get(&value); return setMatrix2x2Array(node, attr, (const double*)value.cdata(), value.size()); } case UsdDataType::kMatrix3d: { VtArray<GfMatrix3d> value; usdAttr.Get(&value); return setMatrix3x3Array(node, attr, (const double*)value.cdata(), value.size()); } case UsdDataType::kMatrix4d: { VtArray<GfMatrix4d> value; usdAttr.Get(&value); return setMatrix4x4Array(node, attr, (const double*)value.cdata(), value.size()); } case UsdDataType::kQuatd: { VtArray<GfQuatd> value; usdAttr.Get(&value); return setQuatArray(node, attr, (const double*)value.cdata(), value.size()); } case UsdDataType::kQuatf: { VtArray<GfQuatf> value; usdAttr.Get(&value); return setQuatArray(node, attr, (const float*)value.cdata(), value.size()); } case UsdDataType::kQuath: { VtArray<GfQuath> value; usdAttr.Get(&value); return setQuatArray(node, attr, (const GfHalf*)value.cdata(), value.size()); } case UsdDataType::kVec2d: { VtArray<GfVec2d> value; usdAttr.Get(&value); return setVec2Array(node, attr, (const double*)value.cdata(), value.size()); } case UsdDataType::kVec2f: { VtArray<GfVec2f> value; usdAttr.Get(&value); return setVec2Array(node, attr, (const float*)value.cdata(), value.size()); } case UsdDataType::kVec2h: { VtArray<GfVec2h> value; usdAttr.Get(&value); return setVec2Array(node, attr, (const GfHalf*)value.cdata(), value.size()); } case UsdDataType::kVec2i: { VtArray<GfVec2i> value; usdAttr.Get(&value); return setVec2Array(node, attr, (const int32_t*)value.cdata(), value.size()); } case UsdDataType::kVec3d: { VtArray<GfVec3d> value; usdAttr.Get(&value); return setVec3Array(node, attr, (const double*)value.cdata(), value.size()); } case UsdDataType::kVec3f: { VtArray<GfVec3f> value; usdAttr.Get(&value); return setVec3Array(node, attr, (const float*)value.cdata(), value.size()); } case UsdDataType::kVec3h: { VtArray<GfVec3h> value; usdAttr.Get(&value); return setVec3Array(node, attr, (const GfHalf*)value.cdata(), value.size()); } case UsdDataType::kVec3i: { VtArray<GfVec3i> value; usdAttr.Get(&value); return setVec3Array(node, attr, (const int32_t*)value.cdata(), value.size()); } case UsdDataType::kVec4d: { VtArray<GfVec4d> value; usdAttr.Get(&value); return setVec4Array(node, attr, (const double*)value.cdata(), value.size()); } case UsdDataType::kVec4f: { VtArray<GfVec4f> value; usdAttr.Get(&value); return setVec4Array(node, attr, (const float*)value.cdata(), value.size()); } case UsdDataType::kVec4h: { VtArray<GfVec4h> value; usdAttr.Get(&value); return setVec4Array(node, attr, (const GfHalf*)value.cdata(), value.size()); } case UsdDataType::kVec4i: { VtArray<GfVec4i> value; usdAttr.Get(&value); return setVec4Array(node, attr, (const int32_t*)value.cdata(), value.size()); } default: MGlobal::displayError("DgNodeTranslator::setArrayMayaValue - unsupported USD data type"); break; } return MS::kFailure; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setSingleMayaValue(MObject node, MObject attr, const UsdAttribute& usdAttr, const UsdDataType type) { switch(type) { case UsdDataType::kBool: { bool value; usdAttr.Get<bool>(&value); return setBool(node, attr, value); } case UsdDataType::kUChar: { unsigned char value; usdAttr.Get<unsigned char>(&value); return setInt8(node, attr, value); } case UsdDataType::kInt: { int32_t value; usdAttr.Get<int32_t>(&value); return setInt32(node, attr, value); } case UsdDataType::kUInt: { uint32_t value; usdAttr.Get<uint32_t>(&value); return setInt32(node, attr, value); } case UsdDataType::kInt64: { int64_t value; usdAttr.Get<int64_t>(&value); return setInt64(node, attr, value); } case UsdDataType::kUInt64: { uint64_t value; usdAttr.Get<uint64_t>(&value); return setInt64(node, attr, value); } case UsdDataType::kHalf: { GfHalf value; usdAttr.Get<GfHalf>(&value); return setFloat(node, attr, value); } case UsdDataType::kFloat: { float value; usdAttr.Get<float>(&value); return setFloat(node, attr, value); } case UsdDataType::kDouble: { double value; usdAttr.Get<double>(&value); return setDouble(node, attr, value); } case UsdDataType::kString: { std::string value; usdAttr.Get<std::string>(&value); return setString(node, attr, value.c_str()); } case UsdDataType::kMatrix2d: { GfMatrix2d value; usdAttr.Get<GfMatrix2d>(&value); return setMatrix2x2(node, attr, value.GetArray()); } case UsdDataType::kMatrix3d: { GfMatrix3d value; usdAttr.Get<GfMatrix3d>(&value); return setMatrix3x3(node, attr, value.GetArray()); } case UsdDataType::kMatrix4d: { GfMatrix4d value; usdAttr.Get<GfMatrix4d>(&value); return setMatrix4x4(node, attr, value.GetArray()); } case UsdDataType::kQuatd: { GfQuatd value; usdAttr.Get<GfQuatd>(&value); return setQuat(node, attr, reinterpret_cast<const double*>(&value)); } case UsdDataType::kQuatf: { GfQuatf value; usdAttr.Get<GfQuatf>(&value); return setQuat(node, attr, reinterpret_cast<const float*>(&value)); } case UsdDataType::kQuath: { GfQuath value; usdAttr.Get<GfQuath>(&value); float xyzw[4]; xyzw[0] = value.GetImaginary()[0]; xyzw[1] = value.GetImaginary()[1]; xyzw[2] = value.GetImaginary()[2]; xyzw[3] = value.GetReal(); return setQuat(node, attr, xyzw); } case UsdDataType::kVec2d: { GfVec2d value; usdAttr.Get<GfVec2d>(&value); return setVec2(node, attr, reinterpret_cast<const double*>(&value)); } case UsdDataType::kVec2f: { GfVec2f value; usdAttr.Get<GfVec2f>(&value); return setVec2(node, attr, reinterpret_cast<const float*>(&value)); } case UsdDataType::kVec2h: { GfVec2h value; usdAttr.Get<GfVec2h>(&value); float data[2]; data[0] = value[0]; data[1] = value[1]; return setVec2(node, attr, data); } case UsdDataType::kVec2i: { GfVec2i value; usdAttr.Get<GfVec2i>(&value); return setVec2(node, attr, reinterpret_cast<const int32_t*>(&value)); } case UsdDataType::kVec3d: { GfVec3d value; usdAttr.Get<GfVec3d>(&value); return setVec3(node, attr, reinterpret_cast<const double*>(&value)); } case UsdDataType::kVec3f: { GfVec3f value; usdAttr.Get<GfVec3f>(&value); return setVec3(node, attr, reinterpret_cast<const float*>(&value)); } case UsdDataType::kVec3h: { GfVec3h value; usdAttr.Get<GfVec3h>(&value); return setVec3(node, attr, value[0], value[1], value[2]); } case UsdDataType::kVec3i: { GfVec3i value; usdAttr.Get<GfVec3i>(&value); return setVec3(node, attr, reinterpret_cast<const int32_t*>(&value)); } case UsdDataType::kVec4d: { GfVec4d value; usdAttr.Get<GfVec4d>(&value); return setVec4(node, attr, reinterpret_cast<const double*>(&value)); } case UsdDataType::kVec4f: { GfVec4f value; usdAttr.Get<GfVec4f>(&value); return setVec4(node, attr, reinterpret_cast<const float*>(&value)); } case UsdDataType::kVec4h: { GfVec4h value; usdAttr.Get<GfVec4h>(&value); float xyzw[4]; xyzw[0] = value[0]; xyzw[1] = value[1]; xyzw[2] = value[2]; xyzw[3] = value[3]; return setVec4(node, attr, xyzw); } case UsdDataType::kVec4i: { GfVec4i value; usdAttr.Get<GfVec4i>(&value); return setVec4(node, attr, reinterpret_cast<const int32_t*>(&value)); } default: MGlobal::displayError("DgNodeTranslator::setArrayMayaValue - unsupported USD data type"); break; } return MS::kFailure; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::convertSpecialValueToUSDAttribute(const MPlug& plug, UsdAttribute& usdAttr) { // now we start some hard-coded special attribute value type conversion, no better way found: // interpolateBoundary: This property comes from alembic, in maya it is boolean type: if(usdAttr.GetName() == UsdGeomTokens->interpolateBoundary) { if(plug.asBool()) usdAttr.Set(UsdGeomTokens->edgeAndCorner); else usdAttr.Set(UsdGeomTokens->edgeOnly); return MS::kSuccess; } // more special type conversion rules might come here.. return MS::kFailure; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::copyDynamicAttributes(MObject node, UsdPrim& prim) { MFnDependencyNode fn(node); uint32_t numAttributes = fn.attributeCount(); for(uint32_t i = 0; i < numAttributes; ++i) { MObject attribute = fn.attribute(i); MPlug plug(node, attribute); // skip child attributes (only export from highest level) if(plug.isChild()) continue; bool isDynamic = plug.isDynamic(); if(isDynamic) { TfToken attributeName = TfToken(plug.partialName(false, false, false, false, false, true).asChar()); // first test if the attribute happen to come with the prim by nature and we have a mapping rule for it: if(prim.HasAttribute(attributeName)) { UsdAttribute usdAttr = prim.GetAttribute(attributeName); // if the conversion works, we are done: if(convertSpecialValueToUSDAttribute(plug, usdAttr)) { continue; } // if not, then we count on CreateAttribute codes below since that will return the USDAttribute if // already exists and hopefully the type conversions below will work. } bool isArray = plug.isArray(); switch(attribute.apiType()) { case MFn::kAttribute2Double: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double2); GfVec2d m; getVec2(node, attribute, (double*)&m); usdAttr.Set(m); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double2Array); VtArray<GfVec2d> m; m.resize(plug.numElements()); getVec2Array(node, attribute, (double*)m.data(), m.size()); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; case MFn::kAttribute2Float: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Float2); GfVec2f m; getVec2(node, attribute, (float*)&m); usdAttr.Set(m); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Float2Array); VtArray<GfVec2f> m; m.resize(plug.numElements()); getVec2Array(node, attribute, (float*)m.data(), m.size()); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; case MFn::kAttribute2Int: case MFn::kAttribute2Short: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int2); GfVec2i m; getVec2(node, attribute, (int32_t*)&m); usdAttr.Set(m); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int2Array); VtArray<GfVec2i> m; m.resize(plug.numElements()); getVec2Array(node, attribute, (int32_t*)m.data(), m.size()); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; case MFn::kAttribute3Double: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double3); GfVec3d m; getVec3(node, attribute, (double*)&m); usdAttr.Set(m); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double3Array); VtArray<GfVec3d> m; m.resize(plug.numElements()); getVec3Array(node, attribute, (double*)m.data(), m.size()); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; case MFn::kAttribute3Float: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Float3); GfVec3f m; getVec3(node, attribute, (float*)&m); usdAttr.Set(m); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Float3Array); VtArray<GfVec3f> m; m.resize(plug.numElements()); getVec3Array(node, attribute, (float*)m.data(), m.size()); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; case MFn::kAttribute3Long: case MFn::kAttribute3Short: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int3); GfVec3i m; getVec3(node, attribute, (int32_t*)&m); usdAttr.Set(m); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int3Array); VtArray<GfVec3i> m; m.resize(plug.numElements()); getVec3Array(node, attribute, (int32_t*)m.data(), m.size()); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; case MFn::kAttribute4Double: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double4); GfVec4d m; getVec4(node, attribute, (double*)&m); usdAttr.Set(m); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double4Array); VtArray<GfVec4d> m; m.resize(plug.numElements()); getVec4Array(node, attribute, (double*)m.data(), m.size()); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; case MFn::kNumericAttribute: { MFnNumericAttribute fn(attribute); switch(fn.unitType()) { case MFnNumericData::kBoolean: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Bool); bool value; getBool(node, attribute, value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->BoolArray); VtArray<bool> m; m.resize(plug.numElements()); getUsdBoolArray(node, attribute, m); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; case MFnNumericData::kFloat: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Float); float value; getFloat(node, attribute, value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->FloatArray); VtArray<float> m; m.resize(plug.numElements()); getFloatArray(node, attribute, (float*)m.data(), m.size()); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; case MFnNumericData::kDouble: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double); double value; getDouble(node, attribute, value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->DoubleArray); VtArray<double> m; m.resize(plug.numElements()); getDoubleArray(node, attribute, (double*)m.data(), m.size()); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; case MFnNumericData::kInt: case MFnNumericData::kShort: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int); int32_t value; getInt32(node, attribute, value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->IntArray); VtArray<int> m; m.resize(plug.numElements()); getInt32Array(node, attribute, (int32_t*)m.data(), m.size()); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; case MFnNumericData::kInt64: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int64); int64_t value; getInt64(node, attribute, value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int64Array); VtArray<int64_t> m; m.resize(plug.numElements()); getInt64Array(node, attribute, (int64_t*)m.data(), m.size()); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; case MFnNumericData::kByte: case MFnNumericData::kChar: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->UChar); int16_t value; getInt16(node, attribute, value); usdAttr.Set(uint8_t(value)); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->UCharArray); VtArray<uint8_t> m; m.resize(plug.numElements()); getInt8Array(node, attribute, (int8_t*)m.data(), m.size()); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; default: { std::cout << "Unhandled numeric attribute: " << fn.name().asChar() << " " << fn.unitType() << std::endl; } break; } } break; case MFn::kDoubleAngleAttribute: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double); double value; getDouble(node, attribute, value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->DoubleArray); VtArray<double> value; value.resize(plug.numElements()); getDoubleArray(node, attribute, (double*)value.data(), value.size()); usdAttr.Set(value); usdAttr.SetCustom(true); } } break; case MFn::kFloatAngleAttribute: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Float); float value; getFloat(node, attribute, value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->FloatArray); VtArray<float> value; value.resize(plug.numElements()); getFloatArray(node, attribute, (float*)value.data(), value.size()); usdAttr.Set(value); usdAttr.SetCustom(true); } } break; case MFn::kDoubleLinearAttribute: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double); double value; getDouble(node, attribute, value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->DoubleArray); VtArray<double> value; value.resize(plug.numElements()); getDoubleArray(node, attribute, (double*)value.data(), value.size()); usdAttr.Set(value); usdAttr.SetCustom(true); } } break; case MFn::kFloatLinearAttribute: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Float); float value; getFloat(node, attribute, value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->FloatArray); VtArray<float> value; value.resize(plug.numElements()); getFloatArray(node, attribute, (float*)value.data(), value.size()); usdAttr.Set(value); usdAttr.SetCustom(true); } } break; case MFn::kTimeAttribute: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double); double value; getDouble(node, attribute, value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->DoubleArray); VtArray<double> value; value.resize(plug.numElements()); getDoubleArray(node, attribute, (double*)value.data(), value.size()); usdAttr.Set(value); usdAttr.SetCustom(true); } } break; case MFn::kEnumAttribute: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int); int32_t value; getInt32(node, attribute, value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->IntArray); VtArray<int> m; m.resize(plug.numElements()); getInt32Array(node, attribute, (int32_t*)m.data(), m.size()); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; case MFn::kTypedAttribute: { MFnTypedAttribute fnTyped(plug.attribute()); MFnData::Type type = fnTyped.attrType(); switch(type) { case MFnData::kString: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->String); std::string value; getString(node, attribute, value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->StringArray); VtArray<std::string> value; value.resize(plug.numElements()); getStringArray(node, attribute, (std::string*)value.data(), value.size()); usdAttr.Set(value); usdAttr.SetCustom(true); } } break; case MFnData::kMatrixArray: { MFnMatrixArrayData fnData(plug.asMObject()); UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Matrix4dArray); VtArray<GfMatrix4d> m; m.assign((const GfMatrix4d*)&fnData.array()[0], ((const GfMatrix4d*)&fnData.array()[0]) + fnData.array().length()); usdAttr.Set(m); usdAttr.SetCustom(true); } break; default: { std::cout << "Unhandled typed attribute: " << fn.name().asChar() << " " << fn.typeName().asChar() << std::endl; } break; } } break; case MFn::kCompoundAttribute: { MFnCompoundAttribute fnCompound(plug.attribute()); { if(fnCompound.numChildren() == 2) { MObject x = fnCompound.child(0); MObject y = fnCompound.child(1); if(x.apiType() == MFn::kCompoundAttribute && y.apiType() == MFn::kCompoundAttribute) { MFnCompoundAttribute fnCompoundX(x); MFnCompoundAttribute fnCompoundY(y); if(fnCompoundX.numChildren() == 2 && fnCompoundY.numChildren() == 2) { MObject xx = fnCompoundX.child(0); MObject xy = fnCompoundX.child(1); MObject yx = fnCompoundY.child(0); MObject yy = fnCompoundY.child(1); if(xx.apiType() == MFn::kNumericAttribute && xy.apiType() == MFn::kNumericAttribute && yx.apiType() == MFn::kNumericAttribute && yy.apiType() == MFn::kNumericAttribute) { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Matrix2d); GfMatrix2d value; getMatrix2x2(node, attribute, (double*)&value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Matrix2dArray); VtArray<GfMatrix2d> value; value.resize(plug.numElements()); getMatrix2x2Array(node, attribute, (double*)value.data(), plug.numElements()); usdAttr.Set(value); usdAttr.SetCustom(true); } } } } } else if(fnCompound.numChildren() == 3) { MObject x = fnCompound.child(0); MObject y = fnCompound.child(1); MObject z = fnCompound.child(2); if(x.apiType() == MFn::kCompoundAttribute && y.apiType() == MFn::kCompoundAttribute && z.apiType() == MFn::kCompoundAttribute) { MFnCompoundAttribute fnCompoundX(x); MFnCompoundAttribute fnCompoundY(y); MFnCompoundAttribute fnCompoundZ(z); if(fnCompoundX.numChildren() == 3 && fnCompoundY.numChildren() == 3 && fnCompoundZ.numChildren() == 3) { MObject xx = fnCompoundX.child(0); MObject xy = fnCompoundX.child(1); MObject xz = fnCompoundX.child(2); MObject yx = fnCompoundY.child(0); MObject yy = fnCompoundY.child(1); MObject yz = fnCompoundY.child(2); MObject zx = fnCompoundZ.child(0); MObject zy = fnCompoundZ.child(1); MObject zz = fnCompoundZ.child(2); if(xx.apiType() == MFn::kNumericAttribute && xy.apiType() == MFn::kNumericAttribute && xz.apiType() == MFn::kNumericAttribute && yx.apiType() == MFn::kNumericAttribute && yy.apiType() == MFn::kNumericAttribute && yz.apiType() == MFn::kNumericAttribute && zx.apiType() == MFn::kNumericAttribute && zy.apiType() == MFn::kNumericAttribute && zz.apiType() == MFn::kNumericAttribute) { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Matrix3d); GfMatrix3d value; getMatrix3x3(node, attribute, (double*)&value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Matrix3dArray); VtArray<GfMatrix3d> value; value.resize(plug.numElements()); getMatrix3x3Array(node, attribute, (double*)value.data(), plug.numElements()); usdAttr.Set(value); usdAttr.SetCustom(true); } } } } } else if(fnCompound.numChildren() == 4) { MObject x = fnCompound.child(0); MObject y = fnCompound.child(1); MObject z = fnCompound.child(2); MObject w = fnCompound.child(3); if(x.apiType() == MFn::kNumericAttribute && y.apiType() == MFn::kNumericAttribute && z.apiType() == MFn::kNumericAttribute && w.apiType() == MFn::kNumericAttribute) { MFnNumericAttribute fnx(x); MFnNumericAttribute fny(y); MFnNumericAttribute fnz(z); MFnNumericAttribute fnw(w); MFnNumericData::Type typex = fnx.unitType(); MFnNumericData::Type typey = fny.unitType(); MFnNumericData::Type typez = fnz.unitType(); MFnNumericData::Type typew = fnw.unitType(); if(typex == typey && typex == typez && typex == typew) { switch(typex) { case MFnNumericData::kInt: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int4); GfVec4i value; getVec4(node, attribute, (int32_t*)&value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int4Array); VtArray<GfVec4i> value; value.resize(plug.numElements()); getVec4Array(node, attribute, (int32_t*)value.data(), value.size()); usdAttr.Set(value); usdAttr.SetCustom(true); } } break; case MFnNumericData::kFloat: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Float4); GfVec4f value; getVec4(node, attribute, (float*)&value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Float4Array); VtArray<GfVec4f> value; value.resize(plug.numElements()); getVec4Array(node, attribute, (float*)value.data(), value.size()); usdAttr.Set(value); usdAttr.SetCustom(true); } } break; case MFnNumericData::kDouble: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double4); GfVec4d value; getVec4(node, attribute, (double*)&value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double4Array); VtArray<GfVec4d> value; value.resize(plug.numElements()); getVec4Array(node, attribute, (double*)value.data(), value.size()); usdAttr.Set(value); usdAttr.SetCustom(true); } } break; default: break; } } } } } } break; case MFn::kFloatMatrixAttribute: case MFn::kMatrixAttribute: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Matrix4d); GfMatrix4d m; getMatrix4x4(node, attribute, (double*)&m); usdAttr.Set(m); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Matrix4dArray); VtArray<GfMatrix4d> value; value.resize(plug.numElements()); getMatrix4x4Array(node, attribute, (double*)value.data(), value.size()); usdAttr.Set(value); usdAttr.SetCustom(true); } } break; default: break; } } } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- void DgNodeHelper::copySimpleValue(const MPlug& plug, UsdAttribute& usdAttr, const UsdTimeCode& timeCode) { MObject node = plug.node(); MObject attribute = plug.attribute(); bool isArray = plug.isArray(); switch(getAttributeType(usdAttr)) { case UsdDataType::kUChar: if(!isArray) { int8_t value; getInt8(node, attribute, value); usdAttr.Set(uint8_t(value), timeCode); } else { VtArray<uint8_t> m; m.resize(plug.numElements()); getInt8Array(node, attribute, (int8_t*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kInt: if(!isArray) { int32_t value; getInt32(node, attribute, value); usdAttr.Set(value, timeCode); } else { VtArray<int32_t> m; m.resize(plug.numElements()); getInt32Array(node, attribute, (int32_t*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kUInt: if(!isArray) { int32_t value; getInt32(node, attribute, value); usdAttr.Set(uint32_t(value), timeCode); } else { VtArray<uint32_t> m; m.resize(plug.numElements()); getInt32Array(node, attribute, (int32_t*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kInt64: if(!isArray) { int64_t value; getInt64(node, attribute, value); usdAttr.Set(value, timeCode); } else { VtArray<int64_t> m; m.resize(plug.numElements()); getInt64Array(node, attribute, (int64_t*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kUInt64: if(!isArray) { int64_t value; getInt64(node, attribute, value); usdAttr.Set(value, timeCode); } else { VtArray<int64_t> m; m.resize(plug.numElements()); getInt64Array(node, attribute, (int64_t*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kFloat: if(!isArray) { float value; getFloat(node, attribute, value); usdAttr.Set(value, timeCode); } else { VtArray<float> m; m.resize(plug.numElements()); getFloatArray(node, attribute, (float*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kDouble: if(!isArray) { double value; getDouble(node, attribute, value); usdAttr.Set(value, timeCode); } else { VtArray<double> m; m.resize(plug.numElements()); getDoubleArray(node, attribute, (double*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kHalf: if(!isArray) { GfHalf value; getHalf(node, attribute, value); usdAttr.Set(value, timeCode); } else { VtArray<GfHalf> m; m.resize(plug.numElements()); getHalfArray(node, attribute, (GfHalf*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; default: break; } } //---------------------------------------------------------------------------------------------------------------------- void DgNodeHelper::copyAttributeValue(const MPlug& plug, UsdAttribute& usdAttr, const UsdTimeCode& timeCode) { MObject node = plug.node(); MObject attribute = plug.attribute(); bool isArray = plug.isArray(); switch(attribute.apiType()) { case MFn::kAttribute2Double: case MFn::kAttribute2Float: case MFn::kAttribute2Int: case MFn::kAttribute2Short: { switch(getAttributeType(usdAttr)) { case UsdDataType::kVec2d: if(!isArray) { GfVec2d m; getVec2(node, attribute, (double*)&m); usdAttr.Set(m, timeCode); } else { VtArray<GfVec2d> m; m.resize(plug.numElements()); getVec2Array(node, attribute, (double*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kVec2f: if(!isArray) { GfVec2f m; getVec2(node, attribute, (float*)&m); usdAttr.Set(m, timeCode); } else { VtArray<GfVec2f> m; m.resize(plug.numElements()); getVec2Array(node, attribute, (float*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kVec2i: if(!isArray) { GfVec2i m; getVec2(node, attribute, (int*)&m); usdAttr.Set(m, timeCode); } else { VtArray<GfVec2i> m; m.resize(plug.numElements()); getVec2Array(node, attribute, (int*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kVec2h: if(!isArray) { GfVec2h m; getVec2(node, attribute, (GfHalf*)&m); usdAttr.Set(m, timeCode); } else { VtArray<GfVec2h> m; m.resize(plug.numElements()); getVec2Array(node, attribute, (GfHalf*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; default: break; } } break; case MFn::kAttribute3Double: case MFn::kAttribute3Float: case MFn::kAttribute3Long: case MFn::kAttribute3Short: { switch(getAttributeType(usdAttr)) { case UsdDataType::kVec3d: if(!isArray) { GfVec3d m; getVec3(node, attribute, (double*)&m); usdAttr.Set(m, timeCode); } else { VtArray<GfVec3d> m; m.resize(plug.numElements()); getVec3Array(node, attribute, (double*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kVec3f: if(!isArray) { GfVec3f m; getVec3(node, attribute, (float*)&m); usdAttr.Set(m, timeCode); } else { VtArray<GfVec3f> m; m.resize(plug.numElements()); getVec3Array(node, attribute, (float*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kVec3i: if(!isArray) { GfVec3i m; getVec3(node, attribute, (int*)&m); usdAttr.Set(m, timeCode); } else { VtArray<GfVec3i> m; m.resize(plug.numElements()); getVec3Array(node, attribute, (int*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kVec3h: if(!isArray) { GfVec3h m; getVec3(node, attribute, (GfHalf*)&m); usdAttr.Set(m, timeCode); } else { VtArray<GfVec3h> m; m.resize(plug.numElements()); getVec3Array(node, attribute, (GfHalf*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; default: break; } } break; case MFn::kAttribute4Double: { switch(getAttributeType(usdAttr)) { case UsdDataType::kVec4d: if(!isArray) { GfVec4d m; getVec4(node, attribute, (double*)&m); usdAttr.Set(m, timeCode); } else { VtArray<GfVec4d> m; m.resize(plug.numElements()); getVec4Array(node, attribute, (double*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kVec4f: if(!isArray) { GfVec4f m; getVec4(node, attribute, (float*)&m); usdAttr.Set(m, timeCode); } else { VtArray<GfVec4f> m; m.resize(plug.numElements()); getVec4Array(node, attribute, (float*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kVec4i: if(!isArray) { GfVec4i m; getVec4(node, attribute, (int*)&m); usdAttr.Set(m, timeCode); } else { VtArray<GfVec4i> m; m.resize(plug.numElements()); getVec4Array(node, attribute, (int*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kVec4h: if(!isArray) { GfVec4h m; getVec4(node, attribute, (GfHalf*)&m); usdAttr.Set(m, timeCode); } else { VtArray<GfVec4h> m; m.resize(plug.numElements()); getVec4Array(node, attribute, (GfHalf*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; default: break; } } break; case MFn::kNumericAttribute: { MFnNumericAttribute fn(attribute); switch(fn.unitType()) { case MFnNumericData::kBoolean: { if(!isArray) { bool value; getBool(node, attribute, value); usdAttr.Set(value, timeCode); } else { VtArray<bool> m; m.resize(plug.numElements()); getUsdBoolArray(node, attribute, m); usdAttr.Set(m, timeCode); } } break; case MFnNumericData::kFloat: case MFnNumericData::kDouble: case MFnNumericData::kInt: case MFnNumericData::kShort: case MFnNumericData::kInt64: case MFnNumericData::kByte: case MFnNumericData::kChar: { copySimpleValue(plug, usdAttr, timeCode); } break; default: { } break; } } break; case MFn::kTimeAttribute: case MFn::kFloatAngleAttribute: case MFn::kDoubleAngleAttribute: case MFn::kDoubleLinearAttribute: case MFn::kFloatLinearAttribute: { copySimpleValue(plug, usdAttr, timeCode); } break; case MFn::kEnumAttribute: { switch(getAttributeType(usdAttr)) { case UsdDataType::kInt: { if(!isArray) { int32_t value; getInt32(node, attribute, value); usdAttr.Set(value, timeCode); } else { VtArray<int> m; m.resize(plug.numElements()); getInt32Array(node, attribute, m.data(), m.size()); usdAttr.Set(m, timeCode); } } } } break; case MFn::kTypedAttribute: { MFnTypedAttribute fnTyped(plug.attribute()); MFnData::Type type = fnTyped.attrType(); switch(type) { case MFnData::kString: { std::string value; getString(node, attribute, value); usdAttr.Set(value, timeCode); } break; case MFnData::kMatrixArray: { MFnMatrixArrayData fnData(plug.asMObject()); VtArray<GfMatrix4d> m; m.assign((const GfMatrix4d*)&fnData.array()[0], ((const GfMatrix4d*)&fnData.array()[0]) + fnData.array().length()); usdAttr.Set(m, timeCode); } break; default: { } break; } } break; case MFn::kCompoundAttribute: { MFnCompoundAttribute fnCompound(plug.attribute()); { if(fnCompound.numChildren() == 2) { MObject x = fnCompound.child(0); MObject y = fnCompound.child(1); if(x.apiType() == MFn::kCompoundAttribute && y.apiType() == MFn::kCompoundAttribute) { MFnCompoundAttribute fnCompoundX(x); MFnCompoundAttribute fnCompoundY(y); if(fnCompoundX.numChildren() == 2 && fnCompoundY.numChildren() == 2) { MObject xx = fnCompoundX.child(0); MObject xy = fnCompoundX.child(1); MObject yx = fnCompoundY.child(0); MObject yy = fnCompoundY.child(1); if(xx.apiType() == MFn::kNumericAttribute && xy.apiType() == MFn::kNumericAttribute && yx.apiType() == MFn::kNumericAttribute && yy.apiType() == MFn::kNumericAttribute) { if(!isArray) { GfMatrix2d value; getMatrix2x2(node, attribute, (double*)&value); usdAttr.Set(value, timeCode); } else { VtArray<GfMatrix2d> value; value.resize(plug.numElements()); getMatrix2x2Array(node, attribute, (double*)value.data(), plug.numElements()); usdAttr.Set(value, timeCode); } } } } } else if(fnCompound.numChildren() == 3) { MObject x = fnCompound.child(0); MObject y = fnCompound.child(1); MObject z = fnCompound.child(2); if(x.apiType() == MFn::kCompoundAttribute && y.apiType() == MFn::kCompoundAttribute && z.apiType() == MFn::kCompoundAttribute) { MFnCompoundAttribute fnCompoundX(x); MFnCompoundAttribute fnCompoundY(y); MFnCompoundAttribute fnCompoundZ(z); if(fnCompoundX.numChildren() == 3 && fnCompoundY.numChildren() == 3 && fnCompoundZ.numChildren() == 3) { MObject xx = fnCompoundX.child(0); MObject xy = fnCompoundX.child(1); MObject xz = fnCompoundX.child(2); MObject yx = fnCompoundY.child(0); MObject yy = fnCompoundY.child(1); MObject yz = fnCompoundY.child(2); MObject zx = fnCompoundZ.child(0); MObject zy = fnCompoundZ.child(1); MObject zz = fnCompoundZ.child(2); if(xx.apiType() == MFn::kNumericAttribute && xy.apiType() == MFn::kNumericAttribute && xz.apiType() == MFn::kNumericAttribute && yx.apiType() == MFn::kNumericAttribute && yy.apiType() == MFn::kNumericAttribute && yz.apiType() == MFn::kNumericAttribute && zx.apiType() == MFn::kNumericAttribute && zy.apiType() == MFn::kNumericAttribute && zz.apiType() == MFn::kNumericAttribute) { if(!isArray) { GfMatrix3d value; getMatrix3x3(node, attribute, (double*)&value); usdAttr.Set(value, timeCode); } else { VtArray<GfMatrix3d> value; value.resize(plug.numElements()); getMatrix3x3Array(node, attribute, (double*)value.data(), plug.numElements()); usdAttr.Set(value, timeCode); } } } } } else if(fnCompound.numChildren() == 4) { MObject x = fnCompound.child(0); MObject y = fnCompound.child(1); MObject z = fnCompound.child(2); MObject w = fnCompound.child(3); if(x.apiType() == MFn::kNumericAttribute && y.apiType() == MFn::kNumericAttribute && z.apiType() == MFn::kNumericAttribute && w.apiType() == MFn::kNumericAttribute) { MFnNumericAttribute fnx(x); MFnNumericAttribute fny(y); MFnNumericAttribute fnz(z); MFnNumericAttribute fnw(w); MFnNumericData::Type typex = fnx.unitType(); MFnNumericData::Type typey = fny.unitType(); MFnNumericData::Type typez = fnz.unitType(); MFnNumericData::Type typew = fnw.unitType(); if(typex == typey && typex == typez && typex == typew) { switch(typex) { case MFnNumericData::kInt: { if(!isArray) { GfVec4i value; getVec4(node, attribute, (int32_t*)&value); usdAttr.Set(value, timeCode); } else { VtArray<GfVec4i> value; value.resize(plug.numElements()); getVec4Array(node, attribute, (int32_t*)value.data(), value.size()); usdAttr.Set(value, timeCode); } } break; case MFnNumericData::kFloat: { if(!isArray) { GfVec4f value; getVec4(node, attribute, (float*)&value); usdAttr.Set(value, timeCode); } else { VtArray<GfVec4f> value; value.resize(plug.numElements()); getVec4Array(node, attribute, (float*)value.data(), value.size()); usdAttr.Set(value, timeCode); } } break; case MFnNumericData::kDouble: { if(!isArray) { GfVec4d value; getVec4(node, attribute, (double*)&value); usdAttr.Set(value, timeCode); } else { VtArray<GfVec4d> value; value.resize(plug.numElements()); getVec4Array(node, attribute, (double*)value.data(), value.size()); usdAttr.Set(value, timeCode); } } break; default: break; } } } } } } break; case MFn::kFloatMatrixAttribute: case MFn::kMatrixAttribute: { if(!isArray) { GfMatrix4d m; getMatrix4x4(node, attribute, (double*)&m); usdAttr.Set(m, timeCode); } else { VtArray<GfMatrix4d> value; value.resize(plug.numElements()); getMatrix4x4Array(node, attribute, (double*)value.data(), value.size()); usdAttr.Set(value, timeCode); } } break; default: break; } } //---------------------------------------------------------------------------------------------------------------------- void DgNodeHelper::copySimpleValue(const MPlug& plug, UsdAttribute& usdAttr, const float scale, const UsdTimeCode& timeCode) { MObject node = plug.node(); MObject attribute = plug.attribute(); bool isArray = plug.isArray(); switch(getAttributeType(usdAttr)) { case UsdDataType::kFloat: if(!isArray) { float value; getFloat(node, attribute, value); usdAttr.Set(value * scale, timeCode); } else { VtArray<float> m; m.resize(plug.numElements()); getFloatArray(node, attribute, (float*)m.data(), m.size()); for(auto it = m.begin(), e = m.end(); it != e; ++it) { *it *= scale; } usdAttr.Set(m, timeCode); } break; case UsdDataType::kDouble: if(!isArray) { double value; getDouble(node, attribute, value); usdAttr.Set(value * scale, timeCode); } else { VtArray<double> m; m.resize(plug.numElements()); getDoubleArray(node, attribute, (double*)m.data(), m.size()); double temp = scale; for(auto it = m.begin(), e = m.end(); it != e; ++it) { *it *= temp; } usdAttr.Set(m, timeCode); } break; default: break; } } //---------------------------------------------------------------------------------------------------------------------- void DgNodeHelper::copyAttributeValue(const MPlug& plug, UsdAttribute& usdAttr, const float scale, const UsdTimeCode& timeCode) { MObject node = plug.node(); MObject attribute = plug.attribute(); bool isArray = plug.isArray(); switch(attribute.apiType()) { case MFn::kAttribute2Double: case MFn::kAttribute2Float: case MFn::kAttribute2Int: case MFn::kAttribute2Short: { switch(getAttributeType(usdAttr)) { case UsdDataType::kVec2d: if(!isArray) { GfVec2d m; getVec2(node, attribute, (double*)&m); m *= scale; usdAttr.Set(m, timeCode); } else { VtArray<GfVec2d> m; m.resize(plug.numElements()); getVec2Array(node, attribute, (double*)m.data(), m.size()); double temp = scale; for(auto it = m.begin(), e = m.end(); it != e; ++it) { *it *= temp; } usdAttr.Set(m, timeCode); } break; case UsdDataType::kVec2f: if(!isArray) { GfVec2f m; getVec2(node, attribute, (float*)&m); m *= scale; usdAttr.Set(m, timeCode); } else { VtArray<GfVec2f> m; m.resize(plug.numElements()); getVec2Array(node, attribute, (float*)m.data(), m.size()); for(auto it = m.begin(), e = m.end(); it != e; ++it) { *it *= scale; } usdAttr.Set(m, timeCode); } break; default: break; } } break; case MFn::kAttribute3Double: case MFn::kAttribute3Float: case MFn::kAttribute3Long: case MFn::kAttribute3Short: { switch(getAttributeType(usdAttr)) { case UsdDataType::kVec3d: if(!isArray) { GfVec3d m; getVec3(node, attribute, (double*)&m); m *= scale; usdAttr.Set(m, timeCode); } else { VtArray<GfVec3d> m; m.resize(plug.numElements()); getVec3Array(node, attribute, (double*)m.data(), m.size()); double temp = scale; for(auto it = m.begin(), e = m.end(); it != e; ++it) { *it *= temp; } usdAttr.Set(m, timeCode); } break; case UsdDataType::kVec3f: if(!isArray) { GfVec3f m; getVec3(node, attribute, (float*)&m); m *= scale; usdAttr.Set(m, timeCode); } else { VtArray<GfVec3f> m; m.resize(plug.numElements()); getVec3Array(node, attribute, (float*)m.data(), m.size()); for(auto it = m.begin(), e = m.end(); it != e; ++it) { *it *= scale; } usdAttr.Set(m, timeCode); } break; default: break; } } break; case MFn::kAttribute4Double: { switch(getAttributeType(usdAttr)) { case UsdDataType::kVec4d: if(!isArray) { GfVec4d m; getVec4(node, attribute, (double*)&m); m *= scale; usdAttr.Set(m, timeCode); } else { VtArray<GfVec4d> m; m.resize(plug.numElements()); getVec4Array(node, attribute, (double*)m.data(), m.size()); double temp = scale; for(auto it = m.begin(), e = m.end(); it != e; ++it) { *it *= temp; } usdAttr.Set(m, timeCode); } break; case UsdDataType::kVec4f: if(!isArray) { GfVec4f m; getVec4(node, attribute, (float*)&m); m *= scale; usdAttr.Set(m, timeCode); } else { VtArray<GfVec4f> m; m.resize(plug.numElements()); getVec4Array(node, attribute, (float*)m.data(), m.size()); for(auto it = m.begin(), e = m.end(); it != e; ++it) { *it *= scale; } usdAttr.Set(m, timeCode); } break; default: break; } } break; case MFn::kNumericAttribute: { MFnNumericAttribute fn(attribute); switch(fn.unitType()) { case MFnNumericData::kFloat: case MFnNumericData::kDouble: case MFnNumericData::kInt: case MFnNumericData::kShort: case MFnNumericData::kInt64: case MFnNumericData::kByte: case MFnNumericData::kChar: { copySimpleValue(plug, usdAttr, scale, timeCode); } break; default: { } break; } } break; case MFn::kTimeAttribute: case MFn::kFloatAngleAttribute: case MFn::kDoubleAngleAttribute: case MFn::kDoubleLinearAttribute: case MFn::kFloatLinearAttribute: { copySimpleValue(plug, usdAttr, scale, timeCode); } break; default: break; } } //---------------------------------------------------------------------------------------------------------------------- } // utils } // usdmaya } // AL //----------------------------------------------------------------------------------------------------------------------
32.766155
151
0.55667
garvitverma