hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
03c4fb374fbe7afe1df793d90a2084510230f943
10,306
cxx
C++
vtr/toro/TO_Output/TO_Output.cxx
haojunliu/OpenFPGA
b0c4f27077f698aae59bbcbd3ca002f22ba2a5a1
[ "BSD-2-Clause" ]
31
2016-02-15T02:57:28.000Z
2021-06-02T10:40:25.000Z
vtr/toro/TO_Output/TO_Output.cxx
haojunliu/OpenFPGA
b0c4f27077f698aae59bbcbd3ca002f22ba2a5a1
[ "BSD-2-Clause" ]
null
null
null
vtr/toro/TO_Output/TO_Output.cxx
haojunliu/OpenFPGA
b0c4f27077f698aae59bbcbd3ca002f22ba2a5a1
[ "BSD-2-Clause" ]
6
2017-02-08T21:51:51.000Z
2021-06-02T10:40:40.000Z
//===========================================================================// // Purpose : Method definitions for the TO_Output post-processor class. // // Public methods include: // - TO_Output_c, ~TO_Output_c // - Init // - Apply // - IsValid // // Private methods include: // - WriteFileHeader_ // - WriteFileFooter_ // //===========================================================================// //---------------------------------------------------------------------------// // Copyright (C) 2012 Jeff Rudolph, Texas Instruments (jrudolph@ti.com) // // // // This program is free software; you can redistribute it and/or modify it // // under the terms of the GNU General Public License as published by the // // Free Software Foundation; version 3 of the License, or any later version. // // // // This program is distributed in the hope that it will be useful, but // // WITHOUT ANY WARRANTY; without even an implied warranty of MERCHANTABILITY // // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // // for more details. // // // // You should have received a copy of the GNU General Public License along // // with this program; if not, see <http://www.gnu.org/licenses>. // //---------------------------------------------------------------------------// #include "TC_StringUtils.h" #include "TIO_StringText.h" #include "TIO_SkinHandler.h" #include "TIO_PrintHandler.h" #include "TO_Output.h" //===========================================================================// // Method : TO_Output_c // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 05/01/12 jeffr : Original //===========================================================================// TO_Output_c::TO_Output_c( void ) : pcommandLine_( 0 ), poptionsStore_( 0 ), pcontrolSwitches_( 0 ), prulesSwitches_( 0 ), pfloorplanStore_( 0 ), parchitectureSpec_( 0 ), pfabricModel_( 0 ), pcircuitDesign_( 0 ) { } //===========================================================================// // Method : TO_Output_c // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 05/01/12 jeffr : Original //===========================================================================// TO_Output_c::~TO_Output_c( void ) { } //===========================================================================// // Method : Init // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 05/01/12 jeffr : Original //===========================================================================// bool TO_Output_c::Init( const TCL_CommandLine_c& commandLine, const TOS_OptionsStore_c& optionsStore, const TFS_FloorplanStore_c& floorplanStore ) { this->pcommandLine_ = &commandLine; this->poptionsStore_ = &optionsStore; this->pcontrolSwitches_ = &optionsStore.controlSwitches; this->prulesSwitches_ = &optionsStore.rulesSwitches; this->pfloorplanStore_ = &floorplanStore; this->parchitectureSpec_ = &floorplanStore.architectureSpec; this->pfabricModel_ = &floorplanStore.fabricModel; this->pcircuitDesign_ = &floorplanStore.circuitDesign; return( this->IsValid( )); } //===========================================================================// // Method : Apply // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 05/01/12 jeffr : Original //===========================================================================// bool TO_Output_c::Apply( const TCL_CommandLine_c& commandLine, const TOS_OptionsStore_c& optionsStore, const TFS_FloorplanStore_c& floorplanStore ) { bool ok = this->Init( commandLine, optionsStore, floorplanStore ); if( ok ) { ok = this->Apply( ); } return( ok ); } //===========================================================================// bool TO_Output_c::Apply( void ) { bool ok = true; if( this->IsValid( )) { TIO_PrintHandler_c& printHandler = TIO_PrintHandler_c::GetInstance( ); printHandler.Info( "Post-processing...\n" ); const TAS_ArchitectureSpec_c& architectureSpec = *this->parchitectureSpec_; const TFM_FabricModel_c& fabricModel = *this->pfabricModel_; const TFV_FabricView_c& fabricView = *this->pfabricModel_->GetFabricView( ); const TCD_CircuitDesign_c& circuitDesign = *this->pcircuitDesign_; const TOS_OptionsStore_c& optionsStore = *this->poptionsStore_; const TOS_InputOptions_c& inputOptions = this->pcontrolSwitches_->inputOptions; const TOS_OutputOptions_c& outputOptions = this->pcontrolSwitches_->outputOptions; if( ok && outputOptions.optionsFileEnable ) { ok = this->WriteOptionsFile_( optionsStore, outputOptions ); } if( ok && outputOptions.xmlFileEnable ) { ok = this->WriteXmlFile_( architectureSpec, outputOptions ); } if( ok && outputOptions.blifFileEnable ) { ok = this->WriteBlifFile_( circuitDesign, outputOptions ); } if( ok && outputOptions.architectureFileEnable ) { ok = this->WriteArchitectureFile_( architectureSpec, outputOptions ); } if( ok && outputOptions.fabricFileEnable ) { ok = this->WriteFabricFile_( fabricModel, outputOptions ); } if( ok && outputOptions.circuitFileEnable ) { ok = this->WriteCircuitFile_( circuitDesign, outputOptions ); } if( ok && outputOptions.laffFileEnable ) { ok = this->WriteLaffFile_( fabricView, outputOptions ); } if( ok && outputOptions.metricsEmailEnable ) { ok = this->SendMetricsEmail_( inputOptions, outputOptions ); } } return( ok ); } //===========================================================================// // Method : IsValid // Author : Jon Sykes //---------------------------------------------------------------------------// // Version history // 11/19/02 jsykes: Original //===========================================================================// bool TO_Output_c::IsValid( void ) const { return( this->pcommandLine_ && this->poptionsStore_ && this->pfloorplanStore_ ? true : false ); } //===========================================================================// // Method : WriteFileHeader_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 05/01/12 jeffr : Original //===========================================================================// void TO_Output_c::WriteFileHeader_( FILE* pfile, const char* pszFileType, const char* pszPrefix, const char* pszPostfix, const char* pszMessage ) const { TIO_SkinHandler_c& skinHandler = TIO_SkinHandler_c::GetInstance( ); const char* pszProgramTitle = skinHandler.GetProgramTitle( ); const char* pszProgramCopyright = skinHandler.GetCopyright( ); TIO_PrintHandler_c& printHandler = TIO_PrintHandler_c::GetInstance( ); size_t spaceLen = 0; size_t separatorLen = TIO_FORMAT_BANNER_LEN_DEF; char szSeparator[TIO_FORMAT_STRING_LEN_HEAD_FOOT]; char szDateTimeStamp[TIO_FORMAT_STRING_LEN_DATE_TIME]; TC_FormatStringFilled( '_', szSeparator, separatorLen ); TC_AddStringPrefix( szSeparator, pszPrefix ); TC_AddStringPostfix( szSeparator, pszPostfix ); TC_FormatStringDateTimeStamp( szDateTimeStamp, TIO_FORMAT_BANNER_LEN_DEF ); printHandler.WriteCenter( pfile, spaceLen, szSeparator, separatorLen ); printHandler.WriteCenter( pfile, spaceLen, pszProgramTitle, separatorLen, pszPrefix, pszPostfix ); printHandler.WriteCenter( pfile, spaceLen, TIO_SZ_BUILD_VERSION, separatorLen, pszPrefix, pszPostfix ); printHandler.WriteCenter( pfile, spaceLen, pszProgramCopyright, separatorLen, pszPrefix, pszPostfix ); printHandler.WriteCenter( pfile, spaceLen, szSeparator, separatorLen ); printHandler.WriteCenter( pfile, spaceLen, szDateTimeStamp, separatorLen, pszPrefix, pszPostfix ); printHandler.WriteCenter( pfile, spaceLen, pszFileType, separatorLen, pszPrefix, pszPostfix ); printHandler.WriteCenter( pfile, spaceLen, szSeparator, separatorLen ); if( pszMessage ) { printHandler.WriteCenter( pfile, spaceLen, pszMessage, separatorLen, pszPrefix, pszPostfix ); printHandler.WriteCenter( pfile, spaceLen, szSeparator, separatorLen ); } } //===========================================================================// // Method : WriteFileFooter_ // Author : Jeff Rudolph //---------------------------------------------------------------------------// // Version history // 05/01/12 jeffr : Original //===========================================================================// void TO_Output_c::WriteFileFooter_( FILE* pfile, const char* pszPrefix, const char* pszPostfix ) const { TIO_PrintHandler_c& printHandler = TIO_PrintHandler_c::GetInstance( ); size_t spaceLen = 0; size_t separatorLen = TIO_FORMAT_BANNER_LEN_DEF; char szSeparator[TIO_FORMAT_STRING_LEN_HEAD_FOOT]; TC_FormatStringFilled( '_', szSeparator, separatorLen ); TC_AddStringPrefix( szSeparator, pszPrefix ); TC_AddStringPostfix( szSeparator, pszPostfix ); printHandler.WriteCenter( pfile, spaceLen, szSeparator, separatorLen ); }
38.312268
88
0.512032
haojunliu
03c5856a4c58265a9d869eef64c01440ee330048
342
cpp
C++
Task1/Task1/Load.cpp
RostyslavMV/OOP_Module1
33f0701660262e7d8fefc3a3dd92145e239fb3d1
[ "MIT" ]
null
null
null
Task1/Task1/Load.cpp
RostyslavMV/OOP_Module1
33f0701660262e7d8fefc3a3dd92145e239fb3d1
[ "MIT" ]
null
null
null
Task1/Task1/Load.cpp
RostyslavMV/OOP_Module1
33f0701660262e7d8fefc3a3dd92145e239fb3d1
[ "MIT" ]
null
null
null
#include "Load.h" Load::Load(int type, double volume, double weight) { this->type = type; this->volume = volume; this->weight = weight; } PeriodicalLoad::PeriodicalLoad(Load* load, int period, int increase) { this->load = load; this->period = period; this->increase = increase; this->nextTime = period; this->quantity = increase; }
19
68
0.692982
RostyslavMV
03ca2f4b23485e1581ee2af9b7527c2e2b8a9c4b
78
cpp
C++
source/code/utilities/image/stb_image.cpp
luxe/CodeLang-compiler
78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a
[ "MIT" ]
33
2019-05-30T07:43:32.000Z
2021-12-30T13:12:32.000Z
source/code/utilities/image/stb_image.cpp
luxe/CodeLang-compiler
78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a
[ "MIT" ]
371
2019-05-16T15:23:50.000Z
2021-09-04T15:45:27.000Z
source/code/utilities/image/stb_image.cpp
UniLang/compiler
c338ee92994600af801033a37dfb2f1a0c9ca897
[ "MIT" ]
6
2019-08-22T17:37:36.000Z
2020-11-07T07:15:32.000Z
#define STB_IMAGE_IMPLEMENTATION #include "code/utilities/image/stb_image.hpp"
39
45
0.858974
luxe
03ca32200d1d172d5830a06267ec957700848233
3,513
cc
C++
benchmark/benchnum.cc
MengRao/str
80389e30ff07bfd5d71f2bdcfad23db6c1353c2c
[ "MIT" ]
90
2019-01-27T09:02:14.000Z
2022-03-19T16:53:08.000Z
benchmark/benchnum.cc
MengRao/str
80389e30ff07bfd5d71f2bdcfad23db6c1353c2c
[ "MIT" ]
4
2019-01-28T03:42:53.000Z
2021-07-04T13:46:15.000Z
benchmark/benchnum.cc
MengRao/str
80389e30ff07bfd5d71f2bdcfad23db6c1353c2c
[ "MIT" ]
25
2019-02-15T08:18:42.000Z
2022-03-19T16:53:10.000Z
#include <bits/stdc++.h> #include "../Str.h" using namespace std; inline uint64_t getns() { return std::chrono::high_resolution_clock::now().time_since_epoch().count(); } uint32_t getRand() { uint32_t num = rand() & 0xffff; num <<= 16; num |= rand() & 0xffff; return num; } string dest; char buf[1024]; template<uint32_t Size> void bench() { using NumStr = Str<Size>; uint64_t mod = 1; for (int i = 0; i < Size; i++) mod *= 10; const int datasize = 1000; const int loop = 1000; vector<uint64_t> nums(datasize); vector<NumStr> strs(datasize); vector<string> strings(datasize); for (int i = 0; i < datasize; i++) { uint64_t num = getRand(); num <<= 32; num += getRand(); num %= mod; string str = to_string(num); while (str.size() < Size) str = string("0") + str; NumStr numstr = str.data(); assert(numstr.toi64() == num); assert(stoll(str) == num); assert(strtoll(str.data(), NULL, 10) == num); NumStr teststr; teststr.fromi(num); assert(teststr == numstr); sprintf(buf, "%0*lld", Size, num); assert(str == buf); nums[i] = num; strs[i] = numstr; strings[i] = str; } { uint64_t sum = 0; auto before = getns(); for (int l = 0; l < loop; l++) { for (auto& str : strs) { sum += str.toi64(); } } auto after = getns(); cout << "bench " << Size << " toi64: " << (double)(after - before) / (loop * datasize) << " res: " << sum << endl; } { uint64_t sum = 0; auto before = getns(); for (int l = 0; l < loop; l++) { for (auto& str : strings) { sum += stoll(str); } } auto after = getns(); cout << "bench " << Size << " stoll: " << (double)(after - before) / (loop * datasize) << " res: " << sum << endl; } { uint64_t sum = 0; auto before = getns(); for (int l = 0; l < loop; l++) { for (auto& str : strings) { sum += strtoll(str.data(), NULL, 10); } } auto after = getns(); cout << "bench " << Size << " strtoll: " << (double)(after - before) / (loop * datasize) << " res: " << sum << endl; } { union { uint64_t num; char str[Size]; } res; res.num = 0; uint64_t sum = 0; auto before = getns(); for (int l = 0; l < loop; l++) { for (auto num : nums) { (*(NumStr*)res.str).fromi(num); sum += res.num; } } auto after = getns(); cout << "bench " << Size << " fromi: " << (double)(after - before) / (loop * datasize) << " res: " << sum << endl; } { auto before = getns(); for (int l = 0; l < loop; l++) { for (auto num : nums) { dest = to_string(num); } } auto after = getns(); cout << "bench " << Size << " to_string: " << (double)(after - before) / (loop * datasize) << " res: " << dest << endl; } { auto before = getns(); for (int l = 0; l < loop; l++) { for (auto num : nums) { sprintf(buf, "%0*lld", Size, num); } } auto after = getns(); cout << "bench " << Size << " sprintf: " << (double)(after - before) / (loop * datasize) << " res: " << dest << endl; } cout << endl; } int main() { srand(time(NULL)); bench<1>(); bench<2>(); bench<3>(); bench<4>(); bench<5>(); bench<6>(); bench<7>(); bench<8>(); bench<9>(); bench<10>(); bench<11>(); bench<12>(); bench<13>(); bench<14>(); bench<15>(); bench<16>(); bench<17>(); bench<18>(); }
22.375796
120
0.495588
MengRao
03cd22aa09817f0ae0627c5e5a92c9391559911f
7,328
hpp
C++
src/isochunk.hpp
sweetkristas/anura
5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd
[ "CC0-1.0" ]
null
null
null
src/isochunk.hpp
sweetkristas/anura
5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd
[ "CC0-1.0" ]
null
null
null
src/isochunk.hpp
sweetkristas/anura
5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd
[ "CC0-1.0" ]
null
null
null
#pragma once #if defined(USE_ISOMAP) #if !defined(USE_SHADERS) #error in order to build with Iso tiles you need to be building with shaders (USE_SHADERS) #endif #include <boost/intrusive_ptr.hpp> #include <boost/unordered_map.hpp> #include <vector> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include "geometry.hpp" #include "graphics.hpp" #include "formula_callable.hpp" #include "formula_callable_definition.hpp" #include "lighting.hpp" #include "pathfinding.hpp" #include "raster.hpp" #include "shaders.hpp" #include "variant.hpp" namespace voxel { struct position { position(int xx, int yy, int zz) : x(xx), y(yy), z(zz) {} int x, y, z; }; bool operator==(position const& p1, position const& p2); std::size_t hash_value(position const& p); struct textured_tile_editor_info { std::string name; std::string group; variant id; graphics::texture tex; rect area; }; struct colored_tile_editor_info { std::string name; std::string group; variant id; graphics::color color; }; class logical_world; typedef boost::intrusive_ptr<logical_world> logical_world_ptr; class chunk : public game_logic::formula_callable { public: enum { FRONT = 1, RIGHT = 2, TOP = 4, BACK = 8, LEFT = 16, BOTTOM = 32, }; chunk(); explicit chunk(gles2::program_ptr shader, logical_world_ptr logic, const variant& node); virtual ~chunk(); void init(); void build(); void draw(const graphics::lighting_ptr lighting, const camera_callable_ptr& camera) const; variant write(); virtual bool is_solid(int x, int y, int z) const = 0; virtual variant get_tile_type(int x, int y, int z) const = 0; static variant get_tile_info(const std::string& type); void set_tile(int x, int y, int z, const variant& type); void del_tile(int x, int y, int z); bool textured() const { return textured_; } int size_x() const { return size_x_; } int size_y() const { return size_y_; } int size_z() const { return size_z_; } void set_size(int mx, int my, int mz); size_t scale_x() const { return scale_x_; } size_t scale_y() const { return scale_y_; } size_t scale_z() const { return scale_z_; } static const std::vector<textured_tile_editor_info>& get_textured_editor_tiles(); static const std::vector<colored_tile_editor_info>& get_colored_editor_tiles(); protected: enum { FRONT_FACE, RIGHT_FACE, TOP_FACE, BACK_FACE, LEFT_FACE, BOTTOM_FACE, MAX_FACES, }; virtual void handle_build() = 0; virtual void handle_draw(const graphics::lighting_ptr lighting, const camera_callable_ptr& camera) const = 0; virtual void handle_set_tile(int x, int y, int z, const variant& type) = 0; virtual void handle_del_tile(int x, int y, int z) = 0; virtual variant handle_write() = 0; void add_vertex_data(int face, GLfloat x, GLfloat y, GLfloat z, GLfloat size, std::vector<GLfloat>& varray); std::vector<std::vector<GLfloat> >& get_vertex_data() { return varray_; } void add_vertex_vbo_data(); void clear_vertex_data() { varray_.clear(); } const graphics::vbo_array& vbo() const { return vbos_; } const std::vector<size_t>& get_vertex_attribute_offsets() const { return vattrib_offsets_; } const std::vector<size_t>& get_num_vertices() const { return num_vertices_; } const std::vector<glm::vec3>& normals() const { return normals_; } GLuint mvp_uniform() const { return u_mvp_matrix_; } GLuint normal_uniform() const { return u_normal_; } GLuint position_uniform() const { return a_position_; } const glm::vec3& worldspace_position() const {return worldspace_position_; } private: DECLARE_CALLABLE(chunk); // Is this a coloured or textured chunk bool textured_; // VBO's to draw the chunk. graphics::vbo_array vbos_; // Vertex array data for the chunk std::vector<std::vector<GLfloat> > varray_; // Vertex attribute offsets std::vector<size_t> vattrib_offsets_; // Number of vertices to be drawn. std::vector<size_t> num_vertices_; int size_x_; int size_y_; int size_z_; size_t scale_x_; size_t scale_y_; size_t scale_z_; void get_uniforms_and_attributes(gles2::program_ptr shader); GLuint u_mvp_matrix_; GLuint u_normal_; GLuint a_position_; std::vector<glm::vec3> normals_; glm::vec3 worldspace_position_; }; class chunk_colored : public chunk { public: chunk_colored(); explicit chunk_colored(gles2::program_ptr shader, logical_world_ptr logic, const variant& node); virtual ~chunk_colored(); bool is_solid(int x, int y, int z) const; variant get_tile_type(int x, int y, int z) const; protected: void handle_build(); void handle_draw(const graphics::lighting_ptr lighting, const camera_callable_ptr& camera) const; variant handle_write(); void handle_set_tile(int x, int y, int z, const variant& type); void handle_del_tile(int x, int y, int z); private: void add_face_left(GLfloat x, GLfloat y, GLfloat z, GLfloat size, const variant& col); void add_face_right(GLfloat x, GLfloat y, GLfloat z, GLfloat size, const variant& col); void add_face_front(GLfloat x, GLfloat y, GLfloat z, GLfloat size, const variant& col); void add_face_back(GLfloat x, GLfloat y, GLfloat z, GLfloat size, const variant& col); void add_face_top(GLfloat x, GLfloat y, GLfloat z, GLfloat size, const variant& col); void add_face_bottom(GLfloat x, GLfloat y, GLfloat z, GLfloat size, const variant& col); void add_carray_data(int face, const graphics::color& color, std::vector<uint8_t>& carray); std::vector<std::vector<uint8_t> > carray_; std::vector<size_t> cattrib_offsets_; boost::unordered_map<position, variant> tiles_; GLuint a_color_; }; class chunk_textured : public chunk { public: chunk_textured(); explicit chunk_textured(gles2::program_ptr shader, logical_world_ptr logic, const variant& node); virtual ~chunk_textured(); bool is_solid(int x, int y, int z) const; variant get_tile_type(int x, int y, int z) const; protected: void handle_build(); void handle_draw(const graphics::lighting_ptr lighting, const camera_callable_ptr& camera) const; variant handle_write(); void handle_set_tile(int x, int y, int z, const variant& type); void handle_del_tile(int x, int y, int z); private: void add_face_left(GLfloat x, GLfloat y, GLfloat z, GLfloat size, const std::string& bid); void add_face_right(GLfloat x, GLfloat y, GLfloat z, GLfloat size, const std::string& bid); void add_face_front(GLfloat x, GLfloat y, GLfloat z, GLfloat size, const std::string& bid); void add_face_back(GLfloat x, GLfloat y, GLfloat z, GLfloat size, const std::string& bid); void add_face_top(GLfloat x, GLfloat y, GLfloat z, GLfloat size, const std::string& bid); void add_face_bottom(GLfloat x, GLfloat y, GLfloat z, GLfloat size, const std::string& bid); void add_tarray_data(int face, const rectf& area, std::vector<GLfloat>& tarray); std::vector<std::vector<GLfloat> > tarray_; std::vector<size_t> tattrib_offsets_; boost::unordered_map<position, std::string> tiles_; GLuint u_texture_; GLuint a_texcoord_; }; typedef boost::intrusive_ptr<chunk> chunk_ptr; typedef boost::intrusive_ptr<const chunk> const_chunk_ptr; namespace chunk_factory { chunk_ptr create(gles2::program_ptr shader, logical_world_ptr logic, const variant& v); } } #endif // USE_ISOMAP
32
111
0.729121
sweetkristas
03ce66746d11ffe092777d7123bc94bd6832c953
4,520
cpp
C++
2SST/7LW/functions.cpp
AVAtarMod/University
3c784a1e109b7a6f6ea495278ec3dc126258625a
[ "BSD-3-Clause" ]
1
2021-07-31T06:55:08.000Z
2021-07-31T06:55:08.000Z
2SST/7LW/functions.cpp
AVAtarMod/University-C
e516aac99eabbcbe14d897239f08acf6c8e146af
[ "BSD-3-Clause" ]
1
2020-11-25T12:00:11.000Z
2021-01-13T08:51:52.000Z
2SST/7LW/functions.cpp
AVAtarMod/University-C
e516aac99eabbcbe14d897239f08acf6c8e146af
[ "BSD-3-Clause" ]
null
null
null
#include "functions.hpp" #include <vector> #include <iostream> #include <string> #include <algorithm> bool isMagickSquareSolved(unsigned **square, unsigned size) { const unsigned numberRows = size, numberCols = size, numberDiagonals = 2; const unsigned numberObjects = numberRows + numberCols + numberDiagonals; unsigned *sum = new unsigned[numberObjects]{0}; for (unsigned i = 0; i < numberCols; ++i) for (unsigned ii = 0; ii < numberRows; ++ii) sum[i] += square[ii][i]; for (unsigned i = 0; i < numberRows; ++i) for (unsigned ii = 0; ii < numberCols; ++ii) sum[i + numberCols] += square[i][ii]; for (unsigned i = 0; i < numberCols; ++i) sum[numberCols + numberRows] += square[i][i]; for (unsigned i = size - 1, ii; i < 0 - 1; --i, ++ii) sum[numberCols + numberCols + 1] += square[i][ii]; bool solved = true; for (unsigned i = 0; i < numberObjects && solved; ++i) if (sum[i] != sum[0]) solved = false; delete[] sum; return solved; } bool checkNumber(unsigned number) { int tnum = number, c = 0; while (tnum != 0) { int temp = tnum % 10; if (temp == 0) return false; tnum /= 10; c++; } int p = 0; tnum = number; for (int i = 0; i < c; ++i) { int temp1 = tnum % 10; int tnum2 = number; int p2 = 0; while (tnum2 != 0) { int temp = tnum2 % 10; if (temp == temp1 && p != p2) return false; tnum2 /= 10; p2++; } p++; tnum /= 10; } return true; } unsigned **magickSquare(unsigned size) { try { if (size < 2) throw "magickSquare: too little size (" + std::to_string(size) + ")"; } catch (const std::exception &e) { std::cerr << e.what() << '\n'; } unsigned **square = array2d::init<unsigned>(size, size, 0); unsigned counter = 1; for (unsigned row = 0; row < size; ++row) for (unsigned col = 0; col < size; ++col, ++counter) square[row][col] = counter; unsigned start = 123456789; while (start < 987654321) { unsigned ts = start; for (unsigned row = size - 1; row < 0 - 1; --row) for (unsigned col = size - 1; col < 0 - 1; --col) { square[row][col] = ts % 10; ts /= 10; } if (isMagickSquareSolved(square, size)) { for (int i = 0; i < 3; ++i) { for (int ii = 0; ii < 3; ++ii) { std::cout << square[i][ii] << " "; } std::cout << "\n"; } std::cout << "\n"; } start++; while (!checkNumber(start)) { start++; } } return square; } struct setNumbers { int a, b; bool used = false; setNumbers(int a = 0, int b = 0, bool used = false) { this->a = a; this->b = b; this->used = used; } bool operator==(setNumbers &b) { return (this->a == b.a && this->b == b.b); } }; bool compareNumbers(int a, int b, int operatorChar) { if (operatorChar == '<') return a < b; else return a > b; } void solveBoxesProblem(int *array, unsigned length) { const unsigned amountNumbers = length / 2 + 1; const unsigned amountOperators = amountNumbers - 1; int *numbers = new int[amountNumbers]; int *operators = new int[amountOperators]; for (unsigned i = 0; i < amountNumbers; ++i) numbers[i] = array[i]; for (unsigned i = 0; i < amountOperators; ++i) operators[i] = array[i + amountNumbers]; std::vector<std::vector<setNumbers>> sets; sets.resize(amountOperators); for (unsigned i = 0; i < amountOperators; ++i) { for (unsigned a = 0; a < amountNumbers; ++a) for (unsigned b = 0; b < amountNumbers; ++b) { setNumbers current = {numbers[a], numbers[b]}; bool uniqueSet = (std::find_if(sets[i].begin(), sets[i].end(), [&current](setNumbers &a) { return (current.a == a.a && current.b == a.b); }) == sets[i].end()); if (compareNumbers(numbers[a], numbers[b], operators[i]) && uniqueSet) { sets.at(i).push_back(current); } } } }
25.828571
175
0.488496
AVAtarMod
03d02a1af870d8d0b6c13a55dac2d2be5cf4e884
3,680
hh
C++
src/drivers/Execute.hh
RLReed/libdetran
77637c788823e0a14aae7e40e476a291f6f3184b
[ "MIT" ]
4
2015-03-07T16:20:23.000Z
2020-02-10T13:40:16.000Z
src/drivers/Execute.hh
RLReed/libdetran
77637c788823e0a14aae7e40e476a291f6f3184b
[ "MIT" ]
3
2018-02-27T21:24:22.000Z
2020-12-16T00:56:44.000Z
src/drivers/Execute.hh
RLReed/libdetran
77637c788823e0a14aae7e40e476a291f6f3184b
[ "MIT" ]
9
2015-03-07T16:20:26.000Z
2022-01-29T00:14:23.000Z
//----------------------------------*-C++-*----------------------------------// /** * @file Execute.hh * @brief Execute class definition. * @note Copyright (C) 2013 Jeremy Roberts. */ //---------------------------------------------------------------------------// //---------------------------------------------------------------------------// /** @mainpage detran: A DEterministic TRANsport package * * @section sec_introduction Introduction * * This is the introduction. * * @section install_sec Installation * * @subsection step1 Step 1: Opening the box * * etc... */ //---------------------------------------------------------------------------// #ifndef detran_EXECUTE_HH_ #define detran_EXECUTE_HH_ #include "detran_config.hh" #include "StupidParser.hh" #include "external_source/ExternalSource.hh" #include "external_source/ConstantSource.hh" #include "external_source/DiscreteSource.hh" #include "external_source/IsotropicSource.hh" #include "geometry/Mesh.hh" #include "material/Material.hh" #include "solvers/FixedSourceManager.hh" #include "solvers/EigenvalueManager.hh" #include "transport/DimensionTraits.hh" #include "transport/State.hh" #include "utilities/DBC.hh" #include "utilities/InputDB.hh" #include <iostream> #include <string> namespace detran { //---------------------------------------------------------------------------// /** * @class Execute * @brief Setup and execute the problem. */ //---------------------------------------------------------------------------// class Execute { public: //-------------------------------------------------------------------------// // TYPEDEFS //-------------------------------------------------------------------------// typedef detran_utilities::InputDB::SP_input SP_input; typedef detran_geometry::Mesh::SP_mesh SP_mesh; typedef detran_material::Material::SP_material SP_material; typedef detran_external_source:: ExternalSource::SP_externalsource SP_externalsource; typedef detran_external_source:: ExternalSource::vec_externalsource vec_externalsource; typedef detran::State::SP_state SP_state; //-------------------------------------------------------------------------// // CONSTRUCTOR & DESTRUCTOR //-------------------------------------------------------------------------// /* * \brief Constructor * \param parser Input parser */ Execute(StupidParser &parser); //-------------------------------------------------------------------------// // PUBLIC FUNCTIONS //-------------------------------------------------------------------------// /// Solve the problem. template <class D> void solve(); /// Write output to file. void output(); // Return dimension of problem. int dimension() { return d_dimension; } private: //-------------------------------------------------------------------------// // DATA //-------------------------------------------------------------------------// // Input SP_input d_input; // Material SP_material d_material; // Mesh SP_mesh d_mesh; // State vector SP_state d_state; // Number of groups int d_number_groups; // External source SP_externalsource d_externalsource; // Problem dimensions int d_dimension; // Problem type std::string d_problem_type; }; } // end namespace detran #endif /* detran_EXECUTE_HH_ */ //---------------------------------------------------------------------------// // end of Execute.hh //---------------------------------------------------------------------------//
28.091603
79
0.449728
RLReed
03d2376c614a415939118a4844cddfdd847d9384
7,138
cpp
C++
api/depth2depth/gaps/pkgs/R2Shapes/R2Box.cpp
AriaPs/cleargrasp
3c5fd901970cab2bb5da38ca0b3eff32d8f9dc12
[ "Apache-2.0" ]
708
2017-09-20T15:05:44.000Z
2022-03-29T15:08:01.000Z
gaps/pkgs/R2Shapes/R2Box.cpp
OTTFFIVE/3dmatch-toolbox
69af229d3dab924c20dc940ae71a48394322dea2
[ "BSD-2-Clause" ]
51
2017-09-20T17:26:52.000Z
2022-03-20T13:23:11.000Z
gaps/pkgs/R2Shapes/R2Box.cpp
OTTFFIVE/3dmatch-toolbox
69af229d3dab924c20dc940ae71a48394322dea2
[ "BSD-2-Clause" ]
203
2016-12-16T02:49:10.000Z
2022-03-21T06:38:12.000Z
/* Source file for the R2 Box class */ /* Include files */ #include "R2Shapes/R2Shapes.h" /* Public variables */ const R2Box R2zero_box(0.0, 0.0, 0.0, 0.0); const R2Box R2unit_box(-1.0, -1.0, 1.0, 1.0); const R2Box R2infinite_box(-RN_INFINITY, -RN_INFINITY, RN_INFINITY, RN_INFINITY); const R2Box R2null_box( RN_INFINITY, RN_INFINITY, -RN_INFINITY, -RN_INFINITY); /* Public functions */ int R2InitBox() { /* Return success */ return TRUE; } void R2StopBox() { } R2Box:: R2Box(void) { } R2Box:: R2Box(const R2Box& box) : minpt(box.minpt), maxpt(box.maxpt) { } R2Box:: R2Box(const R2Point& minpt, const R2Point& maxpt) : minpt(minpt), maxpt(maxpt) { } R2Box:: R2Box(const R2Point& center, RNLength xradius, RNLength yradius) : minpt(center.X() - xradius, center.Y() - yradius), maxpt(center.X() + xradius, center.Y() + yradius) { } R2Box:: R2Box(RNCoord xmin, RNCoord ymin, RNCoord xmax, RNCoord ymax) : minpt(xmin, ymin), maxpt(xmax, ymax) { } const RNBoolean R2Box:: IsPoint (void) const { // Return whether bounding box contains just one point return ((minpt.X() == maxpt.X()) && (minpt.Y() == maxpt.Y())); } const RNBoolean R2Box:: IsLinear (void) const { // Return whether bounding box contains just one line segment return (this->NDimensions() <= 1); } const RNBoolean R2Box:: IsConvex (void) const { // All boxes are convex return TRUE; } const RNBoolean R2Box:: IsFinite (void) const { // Return whether bounding box contains a finite amount of space if (IsEmpty()) return TRUE; if (!RNIsFinite(minpt.X())) return FALSE; if (!RNIsFinite(minpt.Y())) return FALSE; if (!RNIsFinite(maxpt.X())) return FALSE; if (!RNIsFinite(maxpt.Y())) return FALSE; return TRUE; } const R2Point R2Box:: Corner (RNQuadrant quadrant) const { // Return corner point switch (quadrant) { case RN_NN_QUADRANT: return minpt; case RN_NP_QUADRANT: return R2Point(minpt.X(), maxpt.Y()); case RN_PN_QUADRANT: return R2Point(maxpt.X(), minpt.Y()); case RN_PP_QUADRANT: return maxpt; default: RNAbort("Invalid quadrant for box corner"); return R2null_point; } } const R2Point R2Box:: Corner (RNDirection xdir, RNDirection ydir) const { // Return corner point return R2Point(Coord(xdir, RN_X), Coord(ydir, RN_Y)); } const R2Box R2Box:: Quadrant (RNDirection xdir, RNDirection ydir) const { // Return box in quadrant (xdir, ydir) R2Box result; R2Point centroid = Centroid(); if (xdir == RN_HI) { result[RN_LO][RN_X] = centroid[RN_X]; result[RN_HI][RN_X] = maxpt[RN_X]; } else { result[RN_LO][RN_X] = minpt[RN_X]; result[RN_HI][RN_X] = centroid[RN_X]; } if (ydir == RN_HI) { result[RN_LO][RN_Y] = centroid[RN_Y]; result[RN_HI][RN_Y] = maxpt[RN_Y]; } else { result[RN_LO][RN_Y] = minpt[RN_Y]; result[RN_HI][RN_Y] = centroid[RN_Y]; } return result; } const int R2Box:: NDimensions (void) const { // Return number of non-zero dimensions in box int ndimensions = 0; if (minpt.X() > maxpt.X()) return -1; if (minpt.X() < maxpt.X()) ndimensions++; if (minpt.Y() > maxpt.Y()) return -1; if (minpt.Y() < maxpt.Y()) ndimensions++; return ndimensions; } const RNAxis R2Box:: ShortestAxis (void) const { // Return shortest axis RNLength dx = this->XLength(); RNLength dy = this->YLength(); return (dx < dy) ? RN_XAXIS : RN_YAXIS; } const RNAxis R2Box:: LongestAxis (void) const { // Return longest axis RNLength dx = this->XLength(); RNLength dy = this->YLength(); return (dx > dy) ? RN_XAXIS : RN_YAXIS; } const RNLength R2Box:: ShortestAxisLength (void) const { // Return shortest axis length RNLength dx = this->XLength(); RNLength dy = this->YLength(); return (dx < dy) ? dx : dy; } const RNLength R2Box:: LongestAxisLength (void) const { // Return longest axis length RNLength dx = this->XLength(); RNLength dy = this->YLength(); return (dx > dy) ? dx : dy; } const RNLength R2Box:: DiagonalLength (void) const { // Return length of box along diagonal return R2Distance(minpt, maxpt); } const R2Point R2Box:: ClosestPoint(const R2Point& point) const { // Return closest point in box R2Point closest(point); if (closest.X() < XMin()) closest[RN_X] = XMin(); else if (closest.X() > XMax()) closest[RN_X] = XMax(); if (closest.Y() < YMin()) closest[RN_Y] = YMin(); else if (closest.Y() > YMax()) closest[RN_Y] = YMax(); return closest; } const RNArea R2Box:: Area (void) const { // Return area of bounding box return (XLength() * YLength()); } const R2Point R2Box:: Centroid (void) const { // Return center point return R2Point(XCenter(), YCenter()); } const R2Shape& R2Box:: BShape (void) const { // Return self return *this; } const R2Box R2Box:: BBox (void) const { // Return self - shape virtual function return *this; } const R2Circle R2Box:: BCircle (void) const { // Return bounding circle return R2Circle(Centroid(), DiagonalRadius()); } void R2Box:: Empty (void) { // Copy empty box *this = R2null_box; } void R2Box:: Inflate (RNScalar fraction) { // Scale box around centroid by fraction if (IsEmpty()) return; R2Point centroid = Centroid(); R2Vector diagonal = Max() - centroid; Reset(centroid - fraction * diagonal, centroid + fraction * diagonal); } void R2Box:: Translate(const R2Vector& vector) { // Move box by vector minpt += vector; maxpt += vector; } void R2Box:: Union (const R2Point& point) { // Expand this to include point if (minpt.X() > point.X()) minpt[0] = point.X(); if (minpt.Y() > point.Y()) minpt[1] = point.Y(); if (maxpt.X() < point.X()) maxpt[0] = point.X(); if (maxpt.Y() < point.Y()) maxpt[1] = point.Y(); } void R2Box:: Union (const R2Box& box) { // Expand this to include box if (minpt.X() > box.XMin()) minpt[0] = box.XMin(); if (minpt.Y() > box.YMin()) minpt[1] = box.YMin(); if (maxpt.X() < box.XMax()) maxpt[0] = box.XMax(); if (maxpt.Y() < box.YMax()) maxpt[1] = box.YMax(); } void R2Box:: Union (const R2Circle& circle) { // Expand this to include circle Union(circle.BBox()); } void R2Box:: Intersect (const R2Box& box) { // Intersect with box if (minpt.X() < box.XMin()) minpt[0] = box.XMin(); if (minpt.Y() < box.YMin()) minpt[1] = box.YMin(); if (maxpt.X() > box.XMax()) maxpt[0] = box.XMax(); if (maxpt.Y() > box.YMax()) maxpt[1] = box.YMax(); } void R2Box:: Transform (const R2Transformation& transformation) { // Do not transform empty box if (IsEmpty()) return; // Transform box ??? R2Box tmp = R2null_box; for (RNQuadrant quadrant = 0; quadrant < RN_NUM_QUADRANTS; quadrant++) { R2Point corner(Corner(quadrant)); corner.Transform(transformation); tmp.Union(corner); } *this = tmp; } void R2Box:: Reset(const R2Point& min, const R2Point& max) { // Move box by vector minpt = min; maxpt = max; }
17.756219
99
0.627767
AriaPs
03d512f3c99f4efb5d0abba6b0e49210b9da1d2f
20,534
cpp
C++
Sorting/Michelsen_Sorting/Michelsen_Sorting/main.cpp
bgmichelsen/CSC382-Data-Structures-
f38f8bc04c0191fb93178616797c67062c485814
[ "MIT" ]
null
null
null
Sorting/Michelsen_Sorting/Michelsen_Sorting/main.cpp
bgmichelsen/CSC382-Data-Structures-
f38f8bc04c0191fb93178616797c67062c485814
[ "MIT" ]
null
null
null
Sorting/Michelsen_Sorting/Michelsen_Sorting/main.cpp
bgmichelsen/CSC382-Data-Structures-
f38f8bc04c0191fb93178616797c67062c485814
[ "MIT" ]
1
2021-11-22T19:31:59.000Z
2021-11-22T19:31:59.000Z
// This is the main file for the sorting program. It is where the // sorting functions are defined and tested. The Linked List project // from the beginning of the semester is included as part of this // project. // // Author: Brandon Michelsen #include <iostream> #include <string> #include <limits> #include <time.h> #include <chrono> #include <fstream> #include "linked-list.h" #include "node.h" using namespace std; // Function prototypes template<typename T> void insertionSort(LinkedList<T>& list); // Insertion sort algorithm template<typename T> void quickSort(LinkedList<T>& list, Node<T>* low, Node<T>* high); // Quick sort algorithm template<typename T> Node<T>* quickSortPartition(LinkedList<T>& list, Node<T>* low, Node<T>* high); // Partitioning function for quick sort void displayList(LinkedList<int>& list); // Function for displaying the list string checkStrInput(); // Function for checking user string input int checkInput(); // Function for testing user input bool testSuite(); // Function for the whole test suite bool testInsertionSort(); // Function for testing insertion sort bool testQuickSort(); // Fucntion for testing quick sort int main() { // Declare local variables LinkedList<int> list; // List to add data to and sort ifstream inFile; // File for reading in data to the linked list ofstream outFile; // File for writing data from the linked list int menuInput = -1; // Variable for the menu input chrono::high_resolution_clock::time_point runTimeStart; // Variables for tracking the runtime of sorting functions chrono::high_resolution_clock::time_point runTimeEnd; // Seed the random number srand(static_cast<unsigned int>(time(0))); do { cout << "\tWelcome to the Sorting Algorithm Program\n\n"; cout << "Please select an option from the menu below:\n"; cout << "1) Enter data from a file into the linked list.\n"; cout << "2) Sort the list using Insertion Sort.\n"; cout << "3) Sort the list using Quicksort.\n"; cout << "4) Display the linked list.\n"; cout << "5) Clear the linked list.\n"; cout << "6) Write the linked list data to a file.\n"; cout << "7) Run the automated test suite.\n"; cout << "0) Exit the program.\n"; cout << "\nPlease enter an option from the menu: "; menuInput = checkInput(); system("cls"); switch (menuInput) { // Exit the program case 0: { continue; break; } // Create data to populate the linked list case 1: { // Declare local variables string fileName; // Variable for the name of the file to open string inDataStr; // Variable for reading in the data from the file int inDataInt = 0; // Variable for converting to the integer // Get the file to open cout << "Please enter the location of the file you want to sort:\n"; fileName = checkStrInput(); // Open the file cout << "Opening the file...\n"; inFile.open(fileName); cout << "Done.\n"; cout << "\nWriting the file data to the linked list...\n"; // Make sure the file opened before proceeding if (inFile.is_open()) { // Read in the data from the file while there is data to read while (!(inFile.eof())) { inFile >> inDataStr; inDataInt = stoi(inDataStr); // Convert to integer list.insertNode(inDataInt); // Insert the data into the linked list } cout << "Done.\n"; } else // Otherwise, the file could not be opened cout << "Error. Cannot open the file.\n"; // Close the file inFile.close(); break; } // Sort the list using insertion sort case 2: { cout << "****** Insertion Sort ******\n"; cout << "\nSorting the list...\n"; runTimeStart = chrono::high_resolution_clock::now(); // Get the start time insertionSort<int>(list); runTimeEnd = chrono::high_resolution_clock::now(); // Get the end time cout << "Finished.\n"; cout << "\nTime it took to sort: "; cout << chrono::duration_cast<chrono::microseconds>(runTimeEnd - runTimeStart).count(); cout << " microseconds" << endl; break; } // Sort the list using quicksort case 3: { cout << "****** Quick Sort ******\n"; cout << "\nSorting the list...\n"; runTimeStart = chrono::high_resolution_clock::now(); // Get the start time quickSort<int>(list, list.getHeadPtr(), list.getTailPtr()); runTimeEnd = chrono::high_resolution_clock::now(); // Get the end time cout << "Finished.\n"; cout << "\nTime it took to sort: "; cout << chrono::duration_cast<chrono::microseconds>(runTimeEnd - runTimeStart).count(); cout << " microseconds" << endl; break; } // Display the list case 4: { displayList(list); break; } // Clear the linked list case 5: { cout << "Clearing the linked list...\n"; list.clear(); cout << "Finished.\n"; break; } // Write sorted data to an output file case 6: { // Declare local variables string fileName; // Variable for the file name Node<int>* current; // Variable for cycling through the list // Get the name of the output file cout << "Please enter the name of the file to write to:\n"; fileName = checkStrInput(); // Open the file cout << "Opening the file...\n"; outFile.open(fileName); cout << "Done.\n"; cout << "Writing to the file...\n"; // Make sure the file is opened before continuing if (outFile.is_open()) { // Start at the beginning of the linked list current = list.getHeadPtr(); // Cycle through the list while (current->getNextNode() != nullptr) { // Write the data of the node out to the file outFile << current->getData() << '\n'; // Get the next node current = current->getNextNode(); } cout << "Done.\n"; } else // Otherwise, the file cannot be opened cout << "Error. The file could not be opened.\n"; // Close the file outFile.close(); break; } // Run the automated test suite case 7: { if (testSuite() == true) cout << "****** All tests were successful ******\n"; else cout << "****** Some or all tests failed ******\n"; break; } // Default - invalid input default: { cout << "That is not a valid input.\n"; break; } } system("pause"); system("cls"); } while (menuInput != 0); cout << "Thank you for using our program.\n"; system("pause"); return 0; } /* Function definitions */ // Check user input function // Takes no parameters, returns the integer value entered by the user int checkInput() { // Declare local variables int x = 0; // While the user has not entered a valid integer, have them try again while (!(cin >> x)) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "Invalid input. You must enter an integer.\n"; cout << "Try again: "; } // Return the value they entered return x; } // Function to check user string input // Takes no parameters, returns the user-entered string string checkStrInput() { string x; cin.ignore(); getline(cin, x); return x; } // Insertion sort function // Takes a reference for the linked list to sort, returns void template<typename T> void insertionSort(LinkedList<T>& list) { // Declare local variables T key, temp; // Variables for swapping Node<T>* current = list.getHeadPtr(); // Get the first element to check Node<T>* swap = list.getHeadPtr(); // Get the element before the first element to check // Make sure we are not sorting an empty list if (list.getHeadPtr() == nullptr) return; else { // Loop through the list while (current->getNextNode() != nullptr) { // Ensure we are checking the proper nodes current = current->getNextNode(); swap = current->getPrevNode(); // Get the key to check key = current->getData(); // Check for data that is greater than the key while (swap != nullptr && swap->getData() > key) { // Swap the data that is greater than the key temp = swap->getData(); swap->getNextNode()->setData(temp); swap->setData(key); swap = swap->getPrevNode(); } } } } // Quick sort function // Takes a reference for the linked list to sort, returns void template<typename T> void quickSort(LinkedList<T>& list, Node<T>* low, Node<T>* high) { // Declare local variables Node<T>* p; // Variable for the partition // Ensure we are not sorting an empty list if (list.getHeadPtr() == nullptr) return; else { // Ensure we don't give a stack overflow error if (high != nullptr && low != high && low != high->getNextNode()) { p = quickSortPartition<T>(list, low, high); // Get the proper partition // Recursive calls for proper sorting quickSort<T>(list, low, p->getPrevNode()); quickSort<T>(list, p->getNextNode(), high); } } } // Quick sort partition function // Takes a reference for the linked list to sort, returns an int template<typename T> Node<T>* quickSortPartition(LinkedList<T>& list, Node<T>* low, Node<T>* high) { // Declare local variables T pivot = high->getData(); // Select the pivot value Node<T>* swap = low; // Node variable for swapping values Node<T>* next = low; // Node variable for running through the partition T temp = 0; // Temporary variable for swapping values // Cycle through the partition while (next != high) { // If the data in the current node is less than or equal to the pivot, swap if (next->getData() <= pivot) { // Swap the data temp = next->getData(); next->setData(swap->getData()); swap->setData(temp); // Get the next swap node swap = swap->getNextNode(); } // Continue cycling through the partition next = next->getNextNode(); } // Final swap temp = high->getData(); high->setData(swap->getData()); swap->setData(temp); // Return the swp node as the next partition return swap; } // Function to display the list // Takes a reference for the linked list to display, returns void void displayList(LinkedList<int>& list) { // Get the head node auto current = list.getHeadPtr(); // Only print the data if it contains less than or equal to 100 elements if (list.getSize() > 100) cout << "The data set is too large to print.\n"; else { cout << "****** Displaying the List *****\n"; // Run through the list until there are no more elements while (current != nullptr) { cout << current->getData() << endl; current = current->getNextNode(); } cout << "****** Done Displaying ******\n"; } } // Whole test suite function // Takes no parameters, returns a boolean value indicating the success of the tests bool testSuite() { return (testInsertionSort() && testQuickSort()); } // Test insertion sort function // Takes no parameters, returns a boolean value indicating the success of the tests bool testInsertionSort() { // Declare local variables bool testSort = true; // Variable for tracking test success and failure LinkedList<int> testList; // List for testing sorting on cout << "****** Insertion Sort Test Function ******\n"; // Add data to the list cout << "Adding elements to the list...\n"; testList.insertNode(10); testList.insertNode(1); testList.insertNode(5); cout << "Elements currently in the list:\n"; cout << testList.getHeadPtr()->getData() << endl; cout << testList.getHeadPtr()->getNextNode()->getData() << endl; cout << testList.getTailPtr()->getData() << endl; /* Test insertion sort With 3 unsorted elements */ cout << "Testing insertion sort on unsorted data...\n"; insertionSort<int>(testList); // Test if the value of 1 was sorted to the correct spot if (testList.getHeadPtr()->getData() == 1) cout << "SUCCESS - Element containing value of 1 successfully sorted to first element.\n"; else { cout << "FAIL - Element containing value of 1 failed to be sorted to first element.\n"; testSort = false; } // Test if the value of 5 was sorted to the correct spot if (testList.getHeadPtr()->getNextNode()->getData() == 5) cout << "SUCCESS - Element containing value of 5 successfully sorted to second element.\n"; else { cout << "FAIL - Element containing value of 5 failed to be sorted to second element.\n"; testSort = false; } // Test if the value of ten was sorted to the correct spot if (testList.getTailPtr()->getData() == 10) cout << "SUCCESS - Element containing value of 10 successfully sorted to third element.\n"; else { cout << "FAIL - Element containing value of 10 failed to be sorted to third element.\n"; testSort = false; } cout << "Clearing the list...\n"; testList.clear(); cout << "Done.\n"; /* End test on unsorted data */ /* Test insertion sort with duplicate data*/ cout << "Adding new data to the list...\n"; testList.insertNode(5); testList.insertNode(10); testList.insertNode(5); cout << "Elements currently in the list:\n"; cout << testList.getHeadPtr()->getData() << endl; cout << testList.getHeadPtr()->getNextNode()->getData() << endl; cout << testList.getTailPtr()->getData() << endl; cout << "Testing insertion sort with duplicate data...\n"; insertionSort<int>(testList); // Test if the first element was sorted correctly if (testList.getHeadPtr()->getData() == 5) cout << "SUCCESS - Element containing value 5 successfully sorted to the correct location.\n"; else { cout << "FAIL - Element containing value 5 failed to be sorted to the correct location.\n"; testSort = false; } // Test if the duplicate data was sorted correctly if (testList.getHeadPtr()->getNextNode()->getData() == testList.getHeadPtr()->getData()) cout << "SUCCESS - Duplicate data successfully sorted to the correct location.\n"; else { cout << "FAIL - Duplicate data failed to be sorted to the correct location.\n"; testSort = false; } // Test if the last element was sorted correctly if (testList.getTailPtr()->getData() == 10) cout << "SUCCESS - Element containing value 10 successfully sorted to the correct location.\n"; else { cout << "FAIL - Element containing value 10 failed to be sorted to the correct location.\n"; testSort = false; } cout << "Clearing the list...\n"; testList.clear(); cout << "Done.\n"; /* End test on duplicate data */ /* Test insertion sort on sorted data */ cout << "Adding new data to the list...\n"; testList.insertNode(1); testList.insertNode(5); testList.insertNode(10); cout << "Elements currently in the list:\n"; cout << testList.getHeadPtr()->getData() << endl; cout << testList.getHeadPtr()->getNextNode()->getData() << endl; cout << testList.getTailPtr()->getData() << endl; cout << "Testing insertion sort on sorted data...\n"; insertionSort<int>(testList); // Test if the first element has not changed if (testList.getHeadPtr()->getData() == 1) cout << "SUCCESS - Element containing value 1 is still in the correct location.\n"; else { cout << "FAIL - Element containing value 1 changed its location.\n"; testSort = false; } // Test if the second element has not changed if (testList.getHeadPtr()->getNextNode()->getData() == 5) cout << "SUCCESS - Element containing value 5 is still in the correct location.\n"; else { cout << "FAIL - Element containing value 5 changed its location.\n"; testSort = false; } // Test if final element has not changed if (testList.getTailPtr()->getData() == 10) cout << "SUCCESS - Element containing value 10 is still in the correct location.\n"; else { cout << "FAIL - Element containing value 10 changed its location.\n"; testSort = false; } /* End test on sorted data */ cout << "****** End Insertion Sort Test ******\n\n"; return testSort; } // Test quick sort function // Takes no parameters, returns a boolean value indicating the success of the tests bool testQuickSort() { // Declare local variables bool testSort = true; // Variable for tracking test success and failure LinkedList<int> testList; // List for testing on cout << "****** Quicksort Test Function ******\n"; // Add data to the list cout << "Adding elements to the list...\n"; testList.insertNode(10); testList.insertNode(1); testList.insertNode(5); cout << "Elements currently in the list:\n"; cout << testList.getHeadPtr()->getData() << endl; cout << testList.getHeadPtr()->getNextNode()->getData() << endl; cout << testList.getTailPtr()->getData() << endl; /* Test quicksort With 3 unsorted elements */ cout << "Testing quick sort on unsorted data...\n"; quickSort<int>(testList, testList.getHeadPtr(), testList.getTailPtr()); // Test if the value of 1 was sorted to the correct spot if (testList.getHeadPtr()->getData() == 1) cout << "SUCCESS - Element containing value of 1 successfully sorted to first element.\n"; else { cout << "FAIL - Element containing value of 1 failed to be sorted to first element.\n"; testSort = false; } // Test if the value of 5 was sorted to the correct spot if (testList.getHeadPtr()->getNextNode()->getData() == 5) cout << "SUCCESS - Element containing value of 5 successfully sorted to second element.\n"; else { cout << "FAIL - Element containing value of 5 failed to be sorted to second element.\n"; testSort = false; } // Test if the value of ten was sorted to the correct spot if (testList.getTailPtr()->getData() == 10) cout << "SUCCESS - Element containing value of 10 successfully sorted to third element.\n"; else { cout << "FAIL - Element containing value of 10 failed to be sorted to third element.\n"; testSort = false; } cout << "Clearing the list...\n"; testList.clear(); cout << "Done.\n"; /* End test on unsorted data */ /* Test quicksort with duplicate data*/ cout << "Adding new data to the list...\n"; testList.insertNode(5); testList.insertNode(10); testList.insertNode(5); cout << "Elements currently in the list:\n"; cout << testList.getHeadPtr()->getData() << endl; cout << testList.getHeadPtr()->getNextNode()->getData() << endl; cout << testList.getTailPtr()->getData() << endl; cout << "Testing quick sort with duplicate data...\n"; quickSort<int>(testList, testList.getHeadPtr(), testList.getTailPtr()); // Test if the first element was sorted correctly if (testList.getHeadPtr()->getData() == 5) cout << "SUCCESS - Element containing value 5 successfully sorted to the correct location.\n"; else { cout << "FAIL - Element containing value 5 failed to be sorted to the correct location.\n"; testSort = false; } // Test if the duplicate data was sorted correctly if (testList.getHeadPtr()->getNextNode()->getData() == testList.getHeadPtr()->getData()) cout << "SUCCESS - Duplicate data successfully sorted to the correct location.\n"; else { cout << "FAIL - Duplicate data failed to be sorted to the correct location.\n"; testSort = false; } // Test if the last element was sorted correctly if (testList.getTailPtr()->getData() == 10) cout << "SUCCESS - Element containing value 10 successfully sorted to the correct location.\n"; else { cout << "FAIL - Element containing value 10 failed to be sorted to the correct location.\n"; testSort = false; } cout << "Clearing the list...\n"; testList.clear(); cout << "Done.\n"; /* End test on duplicate data */ /* Test quicksort on sorted data */ cout << "Adding new data to the list...\n"; testList.insertNode(1); testList.insertNode(5); testList.insertNode(10); cout << "Elements currently in the list:\n"; cout << testList.getHeadPtr()->getData() << endl; cout << testList.getHeadPtr()->getNextNode()->getData() << endl; cout << testList.getTailPtr()->getData() << endl; cout << "Testing quick sort on sorted data...\n"; quickSort<int>(testList, testList.getHeadPtr(), testList.getTailPtr()); // Test if the first element has not changed if (testList.getHeadPtr()->getData() == 1) cout << "SUCCESS - Element containing value 1 is still in the correct location.\n"; else { cout << "FAIL - Element containing value 1 changed its location.\n"; testSort = false; } // Test if the second element has not changed if (testList.getHeadPtr()->getNextNode()->getData() == 5) cout << "SUCCESS - Element containing value 5 is still in the correct location.\n"; else { cout << "FAIL - Element containing value 5 changed its location.\n"; testSort = false; } // Test if final element has not changed if (testList.getTailPtr()->getData() == 10) cout << "SUCCESS - Element containing value 10 is still in the correct location.\n"; else { cout << "FAIL - Element containing value 10 changed its location.\n"; testSort = false; } /* End test on sorted data */ cout << "****** End Quicksort Test ******\n\n"; return testSort; }
30.511144
118
0.67118
bgmichelsen
03d756a651baef8b69f602d1bacd3c614a2083a0
1,004
hpp
C++
include/_app_state_recognition.hpp
zborffs/Delta
b2efa9fe1cc2138656f4d7964ccdbbbfcebba639
[ "MIT" ]
1
2022-03-03T09:34:54.000Z
2022-03-03T09:34:54.000Z
include/_app_state_recognition.hpp
zborffs/Delta
b2efa9fe1cc2138656f4d7964ccdbbbfcebba639
[ "MIT" ]
null
null
null
include/_app_state_recognition.hpp
zborffs/Delta
b2efa9fe1cc2138656f4d7964ccdbbbfcebba639
[ "MIT" ]
null
null
null
#ifndef DELTA__APP_STATE_RECOGNITION_HPP #define DELTA__APP_STATE_RECOGNITION_HPP /// Third-Party Includes #include <spdlog/spdlog.h> /// Project Includes #include "app.hpp" #include "_app_state_eng.hpp" #include "_app_state_shutdown.hpp" /** * The AppStateRecognition class is responsible for coloring the Application's functionality when in the "Recognition" * state. * - it transforms a null input into a (legal) chess position * - it is reached from either the Initialization state, or the Waiting state * - it makes use of the Recognition component and the Engine component * - if successful, it transitions to the Engine state */ class AppStateRecognition : public AppState { public: explicit AppStateRecognition() { spdlog::get("delta_logger")->info("Created AppStateRecognition"); } ~AppStateRecognition() { spdlog::get("delta_logger")->info("Destroyed AppStateRecognition"); } bool handle() override; }; #endif // DELTA__APP_STATE_RECOGNITION_HPP
30.424242
118
0.747012
zborffs
03d84fff4764df02d25c380969ade60037598442
14,202
hpp
C++
plugins/EstimationPlugin/src/base/estimator/BatchEstimator.hpp
Randl/GMAT
d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5
[ "Apache-2.0" ]
2
2020-01-01T13:14:57.000Z
2020-12-09T07:05:07.000Z
plugins/EstimationPlugin/src/base/estimator/BatchEstimator.hpp
rdadan/GMAT-R2016a
d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5
[ "Apache-2.0" ]
1
2018-03-15T08:58:37.000Z
2018-03-20T20:11:26.000Z
plugins/EstimationPlugin/src/base/estimator/BatchEstimator.hpp
rdadan/GMAT-R2016a
d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5
[ "Apache-2.0" ]
3
2019-10-13T10:26:49.000Z
2020-12-09T07:06:55.000Z
//$Id: BatchEstimator.hpp 1398 2011-04-21 20:39:37Z $ //------------------------------------------------------------------------------ // BatchEstimator //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002 - 2015 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 NNG06CA54C // // Author: Darrel J. Conway, Thinking Systems, Inc. // Created: 2009/08/04 // /** * Definition of the BatchEstimator class */ //------------------------------------------------------------------------------ #ifndef BatchEstimator_hpp #define BatchEstimator_hpp #include "Estimator.hpp" #include "PropSetup.hpp" #include "MeasurementManager.hpp" #include "OwnedPlot.hpp" #include "DataWriter.hpp" #include "WriterData.hpp" #include "DataBucket.hpp" /** * Implementation of a standard batch estimation state machine * * This class provides a batch estimation state machine that follows a typical * batch estimation process. Derived classes override specific methods to * implement the math required for their algorithm. Every derived estimator * must implement the Accumulate and Estimate methods. The other methods called * in the finite state machine provide default implementation that can be * overridden as needed. * * BatchEstimator is an abstract class; a derived class is needed to instantiate * a BatchEstimator */ class ESTIMATION_API BatchEstimator : public Estimator { public: BatchEstimator(const std::string &type, const std::string &name); virtual ~BatchEstimator(); BatchEstimator(const BatchEstimator& est); BatchEstimator& operator=(const BatchEstimator& est); virtual bool Initialize(); virtual SolverState AdvanceState(); virtual bool Finalize(); // methods overridden from GmatBase virtual std::string GetParameterText(const Integer id) const; virtual std::string GetParameterUnit(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 Integer GetIntegerParameter(const Integer id) const; virtual Integer SetIntegerParameter(const Integer id, const Integer value); virtual Integer GetIntegerParameter(const std::string &label) const; virtual Integer SetIntegerParameter(const std::string &label, const Integer value); virtual std::string GetStringParameter(const Integer id) const; virtual bool SetStringParameter(const Integer id, const std::string &value); virtual std::string GetStringParameter(const Integer id, const Integer index) const; virtual bool SetStringParameter(const Integer id, const std::string &value, const Integer index); virtual std::string GetStringParameter(const std::string &label) const; virtual bool SetStringParameter(const std::string &label, const std::string &value); virtual std::string GetStringParameter(const std::string &label, const Integer index) const; virtual bool SetStringParameter(const std::string &label, const std::string &value, const Integer index); virtual bool GetBooleanParameter(const Integer id) const; virtual bool SetBooleanParameter(const Integer id, const bool value); virtual bool GetBooleanParameter(const std::string &label) const; virtual bool SetBooleanParameter(const std::string &label, const bool value); virtual const StringArray& GetPropertyEnumStrings(const Integer id) const; virtual bool TakeAction(const std::string &action, const std::string &actionData = ""); protected: /// Time system used to specify the estimation epoch std::string estEpochFormat; /// The estimation epoch. "FromParticipants" means use the spacecraft epoch. std::string estEpoch; /// RMS residual value from the previous pass through the data Real oldResidualRMS; /// RMS residual value from the current pass through the data Real newResidualRMS; /// The best RMS residual Real bestResidualRMS; Real resetBestResidualRMS; /// Predicted RMS residual Real predictedRMS; /// Number consecutive iterations diverging Integer numDivIterations; /// Flag to indicate weightedRMS or predictedRMS bool chooseRMSP; /// Flag set when an a priori estimate is available bool useApriori; /// The most recently computed state vector changes RealArray dx; /// The weighting matrix used when accumulating data Rmatrix weights; /// Flag used to indicate propagation to estimation epoch is executing bool advanceToEstimationEpoch; /// The .mat DataWriter object used to write data for MATLAB DataWriter *matWriter; /// Flag indicating is the .mat file should be written bool writeMatFile; /// .mat data file name std::string matFileName; /// Data container used during accumulation DataBucket matData; // Indexing for the .mat data elements /// Iteration number index Integer matIterationIndex; /// Index of the participants list in the .mat data Integer matPartIndex; /// Index of the participants list in the .mat data Integer matTypeIndex; /// Index of the TAI Mod Julian epoch data in the .mat data Integer matEpochIndex; /// Index of the observation data list in the .mat data Integer matObsIndex; /// Index of the calculated data in the .mat data Integer matCalcIndex; /// Index of the O-C data in the .mat data Integer matOmcIndex; /// Index of the elevation for the obs Integer matElevationIndex; /// TAI Gregorian epoch index Integer matGregorianIndex; /// Observation edit flag index Integer matObsEditFlagIndex; // Extra entries Integer matFrequencyIndex; Integer matFreqBandIndex; Integer matDoppCountIndex; // /// Estimation status // Integer estimationStatus; // This variable is moved to Estimator class // String to show reason of convergence std::string convergenceReason; /// Buffer of the participants for the outer batch loop ObjectArray outerLoopBuffer; /// Inversion algorithm used std::string inversionType; /// Maximum consecutive divergences Integer maxConsDivergences; /// particicpants column lenght. It is used for writing report file Integer pcolumnLen; /// Variables used for statistics calculation std::map<std::string, std::map<std::string, Real> > statisticsTable; // this table is for groundstation and measurement type std::map<std::string, std::map<std::string, Real> > statisticsTable1; // this table is for measurement type only // Statistics information for all combination of station and measurement type StringArray stationAndType; // combination of station and type StringArray stationsList; // station StringArray measTypesList; // measurement type IntegerArray sumAllRecords; // total number of records IntegerArray sumAcceptRecords; // total all accepted records RealArray sumResidual; // sum of all O-C of accepted records RealArray sumResidualSquare; // sum of all (O-C)^2 of accepted records RealArray sumWeightResidualSquare; // sum of all [W*(O-C)]^2 of accepted records // Statistics information for sigma edited records IntegerArray sumSERecords; // total all sigma edited records RealArray sumSEResidual; // sum of all O-C of all sigma edited records RealArray sumSEResidualSquare; // sum of all (O-C)^2 of all sigma edited records RealArray sumSEWeightResidualSquare; // sum of all [W*(O-C)]^2 of all sigma edited records std::stringstream textFile0; std::stringstream textFile1; std::stringstream textFile1_1; std::stringstream textFile2; std::stringstream textFile3; std::stringstream textFile4; /// Parameter IDs for the BatchEstimators enum { ESTIMATION_EPOCH_FORMAT = EstimatorParamCount, ESTIMATION_EPOCH, // USE_PRIORI_ESTIMATE, USE_INITIAL_COVARIANCE, INVERSION_ALGORITHM, MAX_CONSECUTIVE_DIVERGENCES, MATLAB_OUTPUT_FILENAME, BatchEstimatorParamCount, }; /// Strings describing the BatchEstimator parameters static const std::string PARAMETER_TEXT[BatchEstimatorParamCount - EstimatorParamCount]; /// Types of the BatchEstimator parameters static const Gmat::ParameterType PARAMETER_TYPE[BatchEstimatorParamCount - EstimatorParamCount]; virtual void CompleteInitialization(); virtual void FindTimeStep(); virtual void CalculateData(); virtual void ProcessEvent(); virtual void CheckCompletion(); virtual void RunComplete(); // Abstract methods defined in derived classes /// Abstract method that implements accumulation in derived classes virtual void Accumulate() = 0; /// Abstract method that performs the estimation in derived classes virtual void Estimate() = 0; virtual Integer TestForConvergence(std::string &reason); virtual void WriteToTextFile(Solver::SolverState state = Solver::UNDEFINED_STATE); // progress string for reporting virtual std::string GetProgressString(); Integer SchurInvert(Real *SUM1, Integer array_size); Integer CholeskyInvert(Real *SUM1, Integer array_size); virtual bool DataFilter(); bool WriteMatData(); private: void WriteReportFileHeaderPart1(); void WriteReportFileHeaderPart2(); void WriteReportFileHeaderPart2b(); void WriteReportFileHeaderPart3(); void WriteReportFileHeaderPart4_1(); void WriteReportFileHeaderPart4_2(); void WriteReportFileHeaderPart4_3(); void WriteReportFileHeaderPart4(); void WriteReportFileHeaderPart5(); void WriteReportFileHeaderPart6(); void WriteReportFileHeader(); void WriteIterationHeader(); void WritePageHeader(); void WriteIterationSummaryPart1(Solver::SolverState sState); void WriteIterationSummaryPart2(Solver::SolverState sState); void WriteIterationSummaryPart3(Solver::SolverState sState); void WriteIterationSummaryPart4(Solver::SolverState sState); void WriteReportFileSummary(Solver::SolverState sState); std::string GetElementFullName(ListItem* infor, bool isInternalCS) const; std::string GetElementUnit(ListItem* infor) const; std::string GetUnit(std::string type); Integer GetElementPrecision(std::string unit) const; Rmatrix CovarianceConvertionMatrix(std::map<GmatBase*, Rvector6> stateMap); std::map<GmatBase*, Rvector6> CalculateCartesianStateMap(const std::vector<ListItem*> *map, GmatState state); std::map<GmatBase*, Rvector6> CalculateKeplerianStateMap(const std::vector<ListItem*> *map, GmatState state); Rmatrix66 CartesianToKeplerianCoverianceConvertionMatrix(GmatBase* obj, const Rvector6 state); std::map<GmatBase*, RealArray> CalculateAncillaryElements(const std::vector<ListItem*> *map, GmatState state); std::string GetFileCreateTime(std::string fileName); std::string CTime(const time_t* time); std::string GetGMATBuildDate(); std::string GetDayOfWeek(Integer day, Integer month, Integer year); std::string GetOperatingSystemName(); std::string GetOperatingSystemVersion(); std::string GetHostName(); std::string GetUserID(); }; #endif /* BatchEstimator_hpp */
44.38125
133
0.62118
Randl
03dc3947e926b39dd0bbca213cde97f12bd14735
2,743
cpp
C++
IOI/ioi14p2.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
IOI/ioi14p2.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
IOI/ioi14p2.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() #define gc getchar() #define pc(x) putchar(x) template<typename T> void scan(T &x){x = 0;bool _=0;T c=gc;_=c==45;c=_?gc:c;while(c<48||c>57)c=gc;for(;c<48||c>57;c=gc);for(;c>47&&c<58;c=gc)x=(x<<3)+(x<<1)+(c&15);x=_?-x:x;} template<typename T> void printn(T n){bool _=0;_=n<0;n=_?-n:n;char snum[65];int i=0;do{snum[i++]=char(n%10+48);n/= 10;}while(n);--i;if (_)pc(45);while(i>=0)pc(snum[i--]);} template<typename First, typename ... Ints> void scan(First &arg, Ints&... rest){scan(arg);scan(rest...);} template<typename T> void print(T n){printn(n);pc(10);} template<typename First, typename ... Ints> void print(First arg, Ints... rest){printn(arg);pc(32);print(rest...);} #define lc (rt<<1) #define rc (rt<<1|1) #define nm ((nl+nr)>>1) using namespace std; const int MM = 2e6+5; struct L{ int mn, mx; }; struct node{ L lp; inline void apply(L v){ lp.mn = max(lp.mn, v.mx); lp.mn = min(lp.mn, v.mn); lp.mx = max(lp.mx, v.mx); lp.mx = min(lp.mx, v.mn); } }; struct segtree{ node tree[MM*4]; int LS, RS; const L DEFL = {INT_MAX, 0}; inline void push(int rt, int nl, int nr){ // node with lazy val means yet to push to children (but updated itself) if(nl == nr) return; L &val = tree[rt].lp; tree[lc].apply(val); tree[rc].apply(val); val = DEFL; } void build(int _LS, int _RS){ build(LS = _LS, RS = _RS, 1); } void build(int nl, int nr, int rt){ tree[rt].lp = DEFL; if(nl == nr) return; build(nl, nm, lc); build(nm+1, nr, rc); } void update(int l, int r, L val){ update(l, r, val, LS, RS, 1); } void update(int l, int r, L val, int nl, int nr, int rt){ if(r < nl || l > nr) return; if(l <= nl && r >= nr){ tree[rt].apply(val); return; } push(rt, nl, nr); update(l, r, val, nl, nm, lc); update(l, r, val, nm+1, nr, rc); } void out(int nl, int nr, int rt, int *&ptr){ if(nl == nr){ *ptr++ = tree[rt].lp.mx; } else{ push(rt, nl, nr); out(nl, nm, lc, ptr); out(nm+1, nr, rc, ptr); } } } ST; void buildWall(int n, int q, int op[], int l[], int r[], int h[], int ans[]){ ST.build(0, n-1); for(int i = 0; i < q; i++){ if(op[i] == 1) //add operation ST.update(l[i], r[i], {INT_MAX, h[i]}); else ST.update(l[i], r[i], {h[i], 0}); } for(int i = 0; i < n; i++) ans[i] = i; ST.out(0, n-1, 1, ans); } #ifdef LOCAL int main(){ int n, q; scan(n, q); int op[n], l[n], r[n], h[n], ans[n]; for(int i = 0; i < q; i++) scan(op[i], l[i], r[i], h[i]); buildWall(n, q, op, l, r, h, ans); for(int i = 0; i < n; i++) print(ans[i]); } #endif /* 10 6 1 1 8 4 2 4 9 1 2 3 6 5 1 0 5 3 1 2 2 5 2 6 7 0 */
26.631068
175
0.53518
crackersamdjam
03dc7baec0e3dae5f2d6b09cddf7f275c16b5b29
1,382
hxx
C++
private/inet/xml/xql/query/orexpr.hxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/inet/xml/xql/query/orexpr.hxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/inet/xml/xql/query/orexpr.hxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
/* * @(#)OrExpr.hxx 1.0 3/20/98 * * Copyright (C) 1998,1999 Microsoft Corporation. All rights reserved. * * definition of XQL OrExpr object * */ #ifndef _XQL_QUERY_OREXPR #define _XQL_QUERY_OREXPR #ifndef _XQL_QUERY_BASEOPERAND #include "xql/query/baseoperand.hxx" #endif DEFINE_CLASS(Element); DEFINE_CLASS(OrExpr); /** * An object for performing boolean and on two operands. * * Hungarian: bexpr * */ class OrExpr : public BaseOperand { public: DECLARE_CLASS_MEMBERS(OrExpr, BaseOperand); public: static OrExpr * newOrExpr(Operand * opnd1, Operand * opnd2); virtual TriState isTrue(QueryContext *inContext, Query * qyContext, Element * eContext); #if DBG == 1 virtual String * toString(); #endif protected: OrExpr(Operand * opnd1, Operand * opnd2); void finalize() { _opnd1 = null; _opnd2 = null; } private: OrExpr(){} /** * this OrExpr's l-value */ ROperand _opnd1; /** * this OrExpr's r-value */ ROperand _opnd2; }; #endif _XQL_QUERY_OREXPR /// End of file /////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
19.194444
97
0.509407
King0987654
03dd00fecd4b06afe13ccabbe97fb6ca471bac05
6,019
cpp
C++
renderers/SSAORenderer.cpp
sarahayu/Fibonacci-Spring-Tree
bf6809d5d8b7f9d13e1acf6af29edb14cec0805a
[ "MIT" ]
null
null
null
renderers/SSAORenderer.cpp
sarahayu/Fibonacci-Spring-Tree
bf6809d5d8b7f9d13e1acf6af29edb14cec0805a
[ "MIT" ]
null
null
null
renderers/SSAORenderer.cpp
sarahayu/Fibonacci-Spring-Tree
bf6809d5d8b7f9d13e1acf6af29edb14cec0805a
[ "MIT" ]
null
null
null
#include "SSAORenderer.h" #include "..\utils\ShaderUtil.h" #include "..\utils\MathUtil.h" #include "..\utils\GlobalClock.h" #include "..\RenderSettings.h" #include "..\Camera.h" #include "Model.h" #include "ScreenQuad.h" #include <random> #include <glm\glm.hpp> namespace { const std::vector<glm::vec3> getSamples() { std::uniform_real_distribution<float> random(0.f, 1.f); std::default_random_engine gen; std::vector<glm::vec3> ssaoKernel; for (int i = 0; i < 36; i++) { glm::vec3 sample(random(gen) * 2 - 1, random(gen) * 2 - 1, random(gen)); sample = glm::normalize(sample); float scale = (float)i / 36; scale = MathUtil::lerp(0.1f, 1.f, scale * scale); sample *= scale; ssaoKernel.push_back(sample); } return ssaoKernel; } const std::vector<glm::vec3> getNoise() { std::uniform_real_distribution<float> random(0.f, 1.f); std::default_random_engine gen; std::vector<glm::vec3> noise; for (int i = 0; i < 16; i++) { noise.push_back({ random(gen) * 2 - 1, random(gen) * 2 - 1, 0.f }); } return noise; } } void SSAORenderer::loadResources() { m_ssaoKernel = getSamples(); const auto noise = getNoise(); TexParams params; params.filter = GL_NEAREST; params.type = GL_FLOAT; params.internalFormat = GL_RGBA16F; params.format = GL_RGB; ShaderUtil::createTexture(m_noiseTex, { 4, 4 }, params, noise.data()); m_solidGeomShader.loadFromFile("solid-geometry-shader", "geometry-shader"); m_solidGeomShader.use(); m_solidUniforms.projection = m_solidGeomShader.getLocation("projection"); m_solidUniforms.view = m_solidGeomShader.getLocation("view"); m_solidUniforms.invView = m_solidGeomShader.getLocation("invView"); m_leavesGeomShader.loadFromFile("leaves-geometry-shader", "geometry-shader"); m_leavesGeomShader.use(); m_leavesUniforms.projection = m_leavesGeomShader.getLocation("projection"); m_leavesUniforms.view = m_leavesGeomShader.getLocation("view"); m_leavesUniforms.time = m_leavesGeomShader.getLocation("time"); m_leavesUniforms.invView = m_leavesGeomShader.getLocation("invView"); m_ssaoShader.loadFromFile("quad-shader", "ssao-shader"); m_ssaoShader.use(); m_ssaoShader.setInt(m_ssaoShader.getLocation("posTex"), 0); m_ssaoShader.setInt(m_ssaoShader.getLocation("normalTex"), 1); m_ssaoShader.setInt(m_ssaoShader.getLocation("noiseTex"), 2); for (int i = 0; i < m_ssaoKernel.size(); i++) m_ssaoShader.setVec3(m_ssaoShader.getLocation("samples[" + std::to_string(i) + "]"), m_ssaoKernel[i]); //m_ssaoUniforms.samples = m_ssaoShader.getLocation("samples"); m_ssaoUniforms.projection = m_ssaoShader.getLocation("projection"); m_ssaoUniforms.windowSize = m_ssaoShader.getLocation("windowSize"); m_ssaoUniforms.radius = m_ssaoShader.getLocation("radius"); m_blurShader.loadFromFile("quad-shader", "blur-shader"); } void SSAORenderer::reloadFramebuffers(const sf::Vector2i & screenDimensions) { m_screenDimensions = screenDimensions; TexParams params; params.filter = GL_NEAREST; params.type = GL_FLOAT; params.wrap = GL_CLAMP_TO_EDGE; params.internalFormat = GL_RGB16F; params.format = GL_RGB; m_geometryFBO.rebuild(screenDimensions); m_geometryFBO.attachColorTexture(params); m_geometryFBO.attachColorTexture(params); unsigned int attachments[2] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 }; glDrawBuffers(2, attachments); m_geometryFBO.attachDepthBuffer(); params.internalFormat = GL_RED; params.format = GL_RGB; m_ssaoFBO.rebuild(screenDimensions); m_ssaoFBO.attachColorTexture(params); m_blurFBO.rebuild(screenDimensions); m_blurFBO.attachColorTexture(params); } void SSAORenderer::clear() { m_blurFBO.bindAndClear(); glBindFramebuffer(GL_FRAMEBUFFER, 0); } void SSAORenderer::bindSSAOTexture() const { m_blurFBO.bindTexture(GL_COLOR_ATTACHMENT0); } void SSAORenderer::draw(Model & scene, const Camera & camera, const RenderSettings & settings) { m_geometryFBO.bindAndClear(); m_solidGeomShader.use(); m_solidGeomShader.setMat4(m_solidUniforms.view, camera.getView()); m_solidGeomShader.setMat3(m_solidUniforms.invView, camera.getInvView()); m_solidGeomShader.setMat4(m_solidUniforms.projection, camera.getProjection()); glEnable(GL_CULL_FACE); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, 0); if (scene.onReflectionPass()) { glEnable(GL_CLIP_DISTANCE0); glCullFace(GL_FRONT); } scene.renderBasic(Model::SOLID_MESH); // disable clipping to avoid z-fighting? glDisable(GL_CLIP_DISTANCE0); scene.renderBasic(Model::WATER_MESH); m_leavesGeomShader.use(); m_leavesGeomShader.setMat4(m_leavesUniforms.view, camera.getView()); m_leavesGeomShader.setMat3(m_leavesUniforms.invView, camera.getInvView()); m_leavesGeomShader.setMat4(m_leavesUniforms.projection, camera.getProjection()); m_leavesGeomShader.setFloat(m_leavesUniforms.time, GlobalClock::getClock() .getElapsedTime().asSeconds()); glDisable(GL_CULL_FACE); if (scene.onReflectionPass()) glEnable(GL_CLIP_DISTANCE0); scene.renderBasic(Model::LEAVES_MESH); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glDisable(GL_CLIP_DISTANCE0); m_ssaoFBO.bindAndClear(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glActiveTexture(GL_TEXTURE0); m_geometryFBO.bindTexture(GL_COLOR_ATTACHMENT0); glActiveTexture(GL_TEXTURE1); m_geometryFBO.bindTexture(GL_COLOR_ATTACHMENT1); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, m_noiseTex); m_ssaoShader.use(); m_ssaoShader.setMat4(m_ssaoUniforms.projection, camera.getProjection()); m_ssaoShader.setFloat(m_ssaoUniforms.radius, settings.ssaoRadius); m_ssaoShader.setVec2(m_ssaoUniforms.windowSize, MathUtil::toGLM2(m_screenDimensions)); ScreenQuad::getQuad().draw(false); m_blurFBO.bindAndClear(); glActiveTexture(GL_TEXTURE0); m_ssaoFBO.bindTexture(GL_COLOR_ATTACHMENT0); m_blurShader.use(); ScreenQuad::getQuad().draw(false); scene.setSSAOInfo(m_blurFBO.getTextureID(GL_COLOR_ATTACHMENT0)); glBindFramebuffer(GL_FRAMEBUFFER, 0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, 0); }
31.025773
107
0.7684
sarahayu
03dd78b44c732d23cd134fdf790cbca208806a4e
8,195
cpp
C++
Source/gday/CoordinateSystemDlg.cpp
mattdocherty314/GDAy3.0
81b13012765e6f4efe3f98c0a4e2c117841f909a
[ "BSD-3-Clause" ]
5
2018-10-30T08:39:02.000Z
2022-02-18T06:34:18.000Z
Source/gday/CoordinateSystemDlg.cpp
mattdocherty314/GDAy3.0
81b13012765e6f4efe3f98c0a4e2c117841f909a
[ "BSD-3-Clause" ]
1
2022-02-18T05:02:24.000Z
2022-02-18T05:02:24.000Z
Source/gday/CoordinateSystemDlg.cpp
mattdocherty314/GDAy3.0
81b13012765e6f4efe3f98c0a4e2c117841f909a
[ "BSD-3-Clause" ]
4
2019-07-30T09:31:05.000Z
2022-01-31T05:51:18.000Z
// CoordinateSystemDlg.cpp : implementation file // #include "stdafx.h" #include "GDAy.h" #include "CoordinateSystemDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CCoordinateSystemDlg dialog CCoordinateSystemDlg::CCoordinateSystemDlg(CWnd* pParent /*=NULL*/) : CDialog(CCoordinateSystemDlg::IDD, pParent) { //{{AFX_DATA_INIT(CCoordinateSystemDlg) //}}AFX_DATA_INIT } void CCoordinateSystemDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CCoordinateSystemDlg) DDX_CBIndex(pDX, IDC_INPUT_DATUM, (m_coordinate_t.InputisGDA20)); DDX_LBIndex(pDX, IDC_INPUT_PROJ, (m_coordinate_t.InputisProjected)); DDX_Radio(pDX, IDC_IN_DMS, (m_coordinate_t.InputDMS)); DDX_CBIndex(pDX, IDC_OUTPUT_DATUM, (m_coordinate_t.OutputisGDA)); DDX_LBIndex(pDX, IDC_OUTPUT_PROJ, (m_coordinate_t.OutputisProjected)); DDX_Check(pDX, IDC_OUTZONE_PROMPT, (m_coordinate_t.PromptforOutputZone)); DDX_Radio(pDX, IDC_OUT_DMS, (m_coordinate_t.OutputDMS)); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CCoordinateSystemDlg, CDialog) //{{AFX_MSG_MAP(CCoordinateSystemDlg) ON_CBN_SELCHANGE(IDC_INPUT_DATUM, OnSelchangeInputDatum) ON_LBN_SELCHANGE(IDC_INPUT_PROJ, OnSelchangeInputProj) ON_CBN_SELCHANGE(IDC_OUTPUT_DATUM, OnSelchangeOutputDatum) ON_LBN_SELCHANGE(IDC_OUTPUT_PROJ, OnSelchangeOutputProj) ON_BN_CLICKED(ID_HELP, OnHelp) ON_WM_HELPINFO() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CCoordinateSystemDlg message handlers void CCoordinateSystemDlg::OnSelchangeInputDatum() { int selection; UpdateData(TRUE); selection = ((CListBox*)GetDlgItem(IDC_INPUT_PROJ))->GetCurSel(); // delete all contents of the input projection list box ((CListBox*)GetDlgItem(IDC_INPUT_PROJ))->ResetContent(); ((CListBox*)GetDlgItem(IDC_INPUT_PROJ))->AddString(GEO); switch ( ((CComboBox*)GetDlgItem(IDC_INPUT_DATUM))->GetCurSel() ) { case 0: ((CListBox*)GetDlgItem(IDC_INPUT_PROJ))->AddString(MGA94_STR); break; case 1: ((CListBox*)GetDlgItem(IDC_INPUT_PROJ))->AddString(MGA20_STR); break; default: MessageBox(SEL_ERR, "Error", MB_OK | MB_ICONEXCLAMATION); break; } ((CListBox*)GetDlgItem(IDC_INPUT_PROJ))->SetCurSel(selection); OnSelchangeInputProj(); } void CCoordinateSystemDlg::OnSelchangeInputProj() { switch ( ((CListBox*)GetDlgItem(IDC_INPUT_PROJ))->GetCurSel() ) { case 0: // The user selected "None" GetDlgItem(IDC_IN_DDEG)->EnableWindow(TRUE); GetDlgItem(IDC_IN_DMIN)->EnableWindow(TRUE); GetDlgItem(IDC_IN_DMS)->EnableWindow(TRUE); GetDlgItem(IDC_IN_FORMAT)->EnableWindow(TRUE); break; case 1: // The user selected a projection type...no choice for D.ms/D.Deg GetDlgItem(IDC_IN_DDEG)->EnableWindow(FALSE); GetDlgItem(IDC_IN_DMIN)->EnableWindow(FALSE); GetDlgItem(IDC_IN_DMS)->EnableWindow(FALSE); GetDlgItem(IDC_IN_FORMAT)->EnableWindow(FALSE); break; default: MessageBox(SEL_ERR, "Error", MB_OK | MB_ICONEXCLAMATION); break; } } void CCoordinateSystemDlg::OnSelchangeOutputDatum() { int selection; selection = ((CListBox*)GetDlgItem(IDC_OUTPUT_PROJ))->GetCurSel(); // delete all contents of the output projection list box ((CListBox*)GetDlgItem(IDC_OUTPUT_PROJ))->ResetContent(); ((CListBox*)GetDlgItem(IDC_OUTPUT_PROJ))->AddString(GEO); switch ( ((CComboBox*)GetDlgItem(IDC_OUTPUT_DATUM))->GetCurSel() ) { case 0: ((CListBox*)GetDlgItem(IDC_OUTPUT_PROJ))->AddString(MGA94_STR); break; case 1: ((CListBox*)GetDlgItem(IDC_OUTPUT_PROJ))->AddString(MGA20_STR); break; default: MessageBox(SEL_ERR, "Error", MB_OK | MB_ICONEXCLAMATION); break; } ((CListBox*)GetDlgItem(IDC_OUTPUT_PROJ))->SetCurSel(selection); OnSelchangeOutputProj(); } void CCoordinateSystemDlg::OnSelchangeOutputProj() { switch ( ((CListBox*)GetDlgItem(IDC_OUTPUT_PROJ))->GetCurSel() ) { case 0: // The user selected "None" GetDlgItem(IDC_OUT_DDEG)->EnableWindow(TRUE); GetDlgItem(IDC_OUT_DMIN)->EnableWindow(TRUE); GetDlgItem(IDC_OUT_DMS)->EnableWindow(TRUE); GetDlgItem(IDC_OUT_FORMAT)->EnableWindow(TRUE); GetDlgItem(IDC_OUTZONE_PROMPT)->EnableWindow(FALSE); break; case 1: // The user selected a projection type...no choice for D.ms/D.Deg GetDlgItem(IDC_OUT_DDEG)->EnableWindow(FALSE); GetDlgItem(IDC_OUT_DMIN)->EnableWindow(FALSE); GetDlgItem(IDC_OUT_DMS)->EnableWindow(FALSE); GetDlgItem(IDC_OUT_FORMAT)->EnableWindow(FALSE); GetDlgItem(IDC_OUTZONE_PROMPT)->EnableWindow(TRUE); break; default: MessageBox(SEL_ERR, "Error", MB_OK | MB_ICONEXCLAMATION); break; } } BOOL CCoordinateSystemDlg::OnInitDialog() { CDialog::OnInitDialog(); // Create tooltip control if (m_ToolTip.Create(this)) { // add the dialog's controls to the Tooltip m_ToolTip.AddTool(GetDlgItem(IDC_IN_DMS), IDC_DMS); m_ToolTip.AddTool(GetDlgItem(IDC_IN_DMIN), IDC_DMIN); m_ToolTip.AddTool(GetDlgItem(IDC_IN_DDEG), IDC_DDEG); m_ToolTip.AddTool(GetDlgItem(IDC_OUT_DMS), IDC_DMS); m_ToolTip.AddTool(GetDlgItem(IDC_OUT_DMIN), IDC_DMIN); m_ToolTip.AddTool(GetDlgItem(IDC_OUT_DDEG), IDC_DDEG); m_ToolTip.AddTool(GetDlgItem(IDC_OUTPUT_DATUM), IDC_OUTPUT_DATUM); m_ToolTip.AddTool(GetDlgItem(IDC_INPUT_DATUM), IDC_INPUT_DATUM); m_ToolTip.AddTool(GetDlgItem(IDC_OUTPUT_PROJ), IDC_OUTPUT_PROJ); m_ToolTip.AddTool(GetDlgItem(IDC_INPUT_PROJ), IDC_INPUT_PROJ); // activate ToolTip control m_ToolTip.Activate(TRUE); } // clear projection list boxes ((CListBox*)GetDlgItem(IDC_INPUT_PROJ))->ResetContent(); ((CListBox*)GetDlgItem(IDC_INPUT_PROJ))->AddString(GEO); ((CListBox*)GetDlgItem(IDC_OUTPUT_PROJ))->ResetContent(); ((CListBox*)GetDlgItem(IDC_OUTPUT_PROJ))->AddString(GEO); // Input Datum switch (m_coordinate_t.InputisGDA20) { case 0: ((CListBox*)GetDlgItem(IDC_INPUT_PROJ))->AddString(MGA94_STR); break; case 1: ((CListBox*)GetDlgItem(IDC_INPUT_PROJ))->AddString(MGA20_STR); break; default: return FALSE; } ((CComboBox*)GetDlgItem(IDC_INPUT_DATUM))->SetCurSel(m_coordinate_t.InputisGDA20); // Input Coordinates projected? GetDlgItem(IDC_IN_DDEG)->EnableWindow(!m_coordinate_t.InputisProjected); GetDlgItem(IDC_IN_DMIN)->EnableWindow(!m_coordinate_t.InputisProjected); GetDlgItem(IDC_IN_DMS)->EnableWindow(!m_coordinate_t.InputisProjected); GetDlgItem(IDC_IN_FORMAT)->EnableWindow(!m_coordinate_t.InputisProjected); ((CListBox*)GetDlgItem(IDC_INPUT_PROJ))->SetCurSel(m_coordinate_t.InputisProjected); // Output Datum switch (m_coordinate_t.OutputisGDA) { case 0: ((CListBox*)GetDlgItem(IDC_OUTPUT_PROJ))->AddString(MGA94_STR); break; case 1: ((CListBox*)GetDlgItem(IDC_OUTPUT_PROJ))->AddString(MGA20_STR); break; default: return FALSE; } ((CComboBox*)GetDlgItem(IDC_OUTPUT_DATUM))->SetCurSel(m_coordinate_t.OutputisGDA); // Output Coordinates projected? GetDlgItem(IDC_OUT_DDEG)->EnableWindow(!m_coordinate_t.OutputisProjected); GetDlgItem(IDC_OUT_DMIN)->EnableWindow(!m_coordinate_t.OutputisProjected); GetDlgItem(IDC_OUT_DMS)->EnableWindow(!m_coordinate_t.OutputisProjected); GetDlgItem(IDC_OUT_FORMAT)->EnableWindow(!m_coordinate_t.OutputisProjected); GetDlgItem(IDC_OUTZONE_PROMPT)->EnableWindow(m_coordinate_t.OutputisProjected); ((CListBox*)GetDlgItem(IDC_OUTPUT_PROJ))->SetCurSel(m_coordinate_t.OutputisProjected); UpdateData(FALSE); return TRUE; } void CCoordinateSystemDlg::OnOK() { UpdateData(TRUE); CDialog::OnOK(); } void CCoordinateSystemDlg::OnCancel() { UpdateData(FALSE); CDialog::OnCancel(); } void CCoordinateSystemDlg::OnHelp() { ::HtmlHelp(NULL, "gday.chm::/html/TC_choose_coord_sys.htm", HH_DISPLAY_TOC, 0); } BOOL CCoordinateSystemDlg::PreTranslateMessage(MSG* pMsg) { // Relay events to the tooltip control m_ToolTip.RelayEvent(pMsg); return CDialog::PreTranslateMessage(pMsg); } BOOL CCoordinateSystemDlg::OnHelpInfo(HELPINFO* pHelpInfo) { if (pHelpInfo->iContextType == HELPINFO_WINDOW) return ::HtmlHelp((HWND)pHelpInfo->hItemHandle, "gday.chm::/html/TC_choose_coord_sys.htm", HH_DISPLAY_TOC, 0)!=NULL; return true; }
29.584838
118
0.755461
mattdocherty314
03de7a8db815a632b1e77fcadbe38e30359aad75
3,238
cpp
C++
scrimmage/test/test_quaternion.cpp
ddfan/swarm_evolve
cd2d972c021e9af5946673363fbfd39cff18f13f
[ "MIT" ]
10
2019-04-29T03:01:19.000Z
2022-03-22T03:11:30.000Z
scrimmage/test/test_quaternion.cpp
lyers179/swarm_evolve
cd2d972c021e9af5946673363fbfd39cff18f13f
[ "MIT" ]
3
2018-10-29T02:14:10.000Z
2020-11-23T02:36:14.000Z
scrimmage/test/test_quaternion.cpp
lyers179/swarm_evolve
cd2d972c021e9af5946673363fbfd39cff18f13f
[ "MIT" ]
8
2018-10-29T02:07:56.000Z
2022-01-04T06:37:53.000Z
/// --------------------------------------------------------------------------- /// @section LICENSE /// /// Copyright (c) 2016 Georgia Tech Research Institute (GTRI) /// All Rights Reserved /// /// 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. /// --------------------------------------------------------------------------- /// @file filename.ext /// @author Kevin DeMarco <kevin.demarco@gtri.gatech.edu> /// @author Eric Squires <eric.squires@gtri.gatech.edu> /// @version 1.0 /// --------------------------------------------------------------------------- /// @brief A brief description. /// /// @section DESCRIPTION /// A long description. /// --------------------------------------------------------------------------- #include <gtest/gtest.h> #include <gmock/gmock.h> #include <scrimmage/math/Quaternion.h> #include <scrimmage/math/Angles.h> #include <Eigen/Dense> #define _USE_MATH_DEFINES #include <cmath> using Eigen::Vector3d; namespace sc = scrimmage; TEST(test_quaternion, rotation) { Vector3d vector = Vector3d(1, 0, 0); sc::Quaternion quaternion(Vector3d(1, 1, 1), 2 * M_PI / 3); Vector3d rotated_vector = quaternion.rotate(vector); EXPECT_NEAR(rotated_vector(0), 0, 1e-10); EXPECT_NEAR(rotated_vector(1), 1, 1e-10); EXPECT_NEAR(rotated_vector(2), 0, 1e-10); } TEST(test_quaternion, reverse_rotation) { Vector3d vector = Vector3d(1, 0, 0); sc::Quaternion quaternion(Vector3d(1, 1, 1), -2 * M_PI / 3); Vector3d rotated_vector = quaternion.rotate_reverse(vector); EXPECT_NEAR(rotated_vector(0), 0, 1e-10); EXPECT_NEAR(rotated_vector(1), 1, 1e-10); EXPECT_NEAR(rotated_vector(2), 0, 1e-10); } TEST(test_quaternion, euler_convert) { double roll = 0.3; double pitch = 0.2; double yaw = 0.1; sc::Quaternion quaternion(roll, pitch, yaw); EXPECT_NEAR(roll, quaternion.roll(), 1e-10); EXPECT_NEAR(pitch, quaternion.pitch(), 1e-10); EXPECT_NEAR(yaw, quaternion.yaw(), 1e-10); } TEST(test_quaternion, frames) { Vector3d vec1(0, 0, 0); Vector3d vec2(1, 0, 1); Vector3d vec_diff = vec2 - vec1; // pointing upward with negative pitch sc::Quaternion q1(0, -sc::Angles::deg2rad(45), 0); Vector3d vec_diff_local1 = q1.rotate_reverse(vec_diff); EXPECT_NEAR(sqrt(2), vec_diff_local1(0), 1e-10); EXPECT_NEAR(0, vec_diff_local1(1), 1e-10); EXPECT_NEAR(0, vec_diff_local1(2), 1e-10); Vector3d vec_diff_global = q1.rotate(vec_diff_local1); EXPECT_NEAR(vec_diff(0), vec_diff_global(0), 1e-10); EXPECT_NEAR(vec_diff(1), vec_diff_global(1), 1e-10); EXPECT_NEAR(vec_diff(2), vec_diff_global(2), 1e-10); }
37.651163
79
0.627548
ddfan
03deff61049e0ab79ea5e1e5fd849c974f217e2a
1,241
cpp
C++
sort/cpu/quickSort.cpp
jitMatrix/xiuxian
ba52d11f39957dd14ca34b51ccb5fadb422e6833
[ "Apache-2.0" ]
3
2021-03-08T06:17:55.000Z
2021-04-09T12:50:21.000Z
sort/cpu/quickSort.cpp
jitMatrix/xiuxian
ba52d11f39957dd14ca34b51ccb5fadb422e6833
[ "Apache-2.0" ]
null
null
null
sort/cpu/quickSort.cpp
jitMatrix/xiuxian
ba52d11f39957dd14ca34b51ccb5fadb422e6833
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <iterator> #include <vector> #include "utils.hpp" template <typename T> std::int64_t partition( std::vector<T> &arr, std::int64_t low, std::int64_t high) { T pivot = arr[low]; while (low < high) { while (low < high && arr[high] >= pivot) { --high; } arr[low] = arr[high]; while (low < high && arr[low] <= pivot) { ++low; } arr[high] = arr[low]; } arr[low] = pivot; return low; } template <typename T> void quickSort(std::vector<T> &arr, std::int64_t low, std::int64_t high) { if (low < high) { std::int64_t pivot = partition(arr, low, high); quickSort(arr, low, pivot - 1); quickSort(arr, pivot + 1, high); } } int main() { std::int64_t count = 10; std::vector<std::int64_t> arr; generator::init(arr, std::make_pair(std::pow(10, generator::minval_radix), std::pow(10, generator::maxval_radix)), count); std::cout << "before sort" << arr << std::endl; quickSort<std::int64_t>(arr, 0, arr.size() - 1); std::cout << "after sort" << arr << std::endl; utils::check_ascend<std::int64_t>(arr); return 0; }
25.854167
74
0.541499
jitMatrix
03df26affc1a5eeb7c79ba5b2b54f5f493990d25
1,582
cpp
C++
src/cpp/rtps/resources/ResourceSend.cpp
zhangzhimin/Fast-RTPS
3032f11d0c62d226eea39ea4f8428afef4558693
[ "Apache-2.0" ]
null
null
null
src/cpp/rtps/resources/ResourceSend.cpp
zhangzhimin/Fast-RTPS
3032f11d0c62d226eea39ea4f8428afef4558693
[ "Apache-2.0" ]
null
null
null
src/cpp/rtps/resources/ResourceSend.cpp
zhangzhimin/Fast-RTPS
3032f11d0c62d226eea39ea4f8428afef4558693
[ "Apache-2.0" ]
1
2021-08-23T01:09:51.000Z
2021-08-23T01:09:51.000Z
// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @file ResourceSend.cpp * */ #include <fastrtps/rtps/resources/ResourceSend.h> #include "ResourceSendImpl.h" #include "../participant/RTPSParticipantImpl.h" namespace eprosima { namespace fastrtps{ namespace rtps { ResourceSend::ResourceSend() { // TODO Auto-generated constructor stub mp_impl = new ResourceSendImpl(); } ResourceSend::~ResourceSend() { // TODO Auto-generated destructor stub delete(mp_impl); } bool ResourceSend::initSend(RTPSParticipantImpl* pimpl, const Locator_t& loc, uint32_t sendsockBuffer,bool useIP4, bool useIP6) { return mp_impl->initSend(pimpl,loc,sendsockBuffer,useIP4,useIP6); } void ResourceSend::sendSync(CDRMessage_t* msg, const Locator_t& loc) { return mp_impl->sendSync(msg,loc); } boost::recursive_mutex* ResourceSend::getMutex() { return mp_impl->getMutex(); } void ResourceSend::loose_next_change() { return mp_impl->loose_next(); } } } /* namespace rtps */ } /* namespace eprosima */
24.71875
77
0.747788
zhangzhimin
03e12365b2cc583b2428393857ecc55ab3bd134b
421
cpp
C++
src/edible.cpp
Md7tz/Running-Lizard
9a3109cfb7e253dadd75655631bbdefa46a7ee28
[ "MIT" ]
7
2022-02-03T15:57:50.000Z
2022-02-22T12:42:06.000Z
src/edible.cpp
Md7tz/Running-Lizard
9a3109cfb7e253dadd75655631bbdefa46a7ee28
[ "MIT" ]
null
null
null
src/edible.cpp
Md7tz/Running-Lizard
9a3109cfb7e253dadd75655631bbdefa46a7ee28
[ "MIT" ]
null
null
null
#include "GameObjects/edible.h" const uint8_t Edible::count = 2; Edible::Edible() {} Edible::Edible(uint8_t _randInt) { randInt = _randInt; foodColor = RED; } Edible::~Edible() {} bool Edible::update(int16_t lizardHeadx, int16_t lizardHeady) { if (foodPos.x == lizardHeadx && foodPos.y == lizardHeady) return true; else return false; } uint8_t Edible::getCount() { return count; }
16.84
61
0.655582
Md7tz
03e125306563f84c43c946ad1d084821fd267889
17,485
cpp
C++
examples/parallaxmapping/parallaxmapping.cpp
jaebaek/VulkanSample
5f327f8d66b17fdaf9d38328b71f40382cb87b50
[ "MIT" ]
3
2019-10-06T20:07:11.000Z
2022-03-24T06:17:08.000Z
examples/parallaxmapping/parallaxmapping.cpp
jaebaek/VulkanSample
5f327f8d66b17fdaf9d38328b71f40382cb87b50
[ "MIT" ]
null
null
null
examples/parallaxmapping/parallaxmapping.cpp
jaebaek/VulkanSample
5f327f8d66b17fdaf9d38328b71f40382cb87b50
[ "MIT" ]
1
2022-03-24T06:17:11.000Z
2022-03-24T06:17:11.000Z
/* * Vulkan Example - Parallax Mapping * * Copyright (C) 2016 by Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) * (http://opensource.org/licenses/MIT) */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <vector> #define GLM_FORCE_RADIANS #define GLM_FORCE_DEPTH_ZERO_TO_ONE #include <glm/glm.hpp> #include <glm/gtc/matrix_inverse.hpp> #include <glm/gtc/matrix_transform.hpp> #include "VulkanBuffer.hpp" #include "VulkanModel.hpp" #include "VulkanTexture.hpp" #include "vulkanexamplebase.h" #include <vulkan/vulkan.h> #define VERTEX_BUFFER_BIND_ID 0 #define ENABLE_VALIDATION false class VulkanExample : public VulkanExampleBase { public: struct { vks::Texture2D colorMap; // Normals and height are combined into one texture (height = alpha channel) vks::Texture2D normalHeightMap; } textures; // Vertex layout for the models vks::VertexLayout vertexLayout = vks::VertexLayout({ vks::VERTEX_COMPONENT_POSITION, vks::VERTEX_COMPONENT_UV, vks::VERTEX_COMPONENT_NORMAL, vks::VERTEX_COMPONENT_TANGENT, vks::VERTEX_COMPONENT_BITANGENT, }); struct { vks::Model quad; } models; struct { vks::Buffer vertexShader; vks::Buffer fragmentShader; } uniformBuffers; struct { struct { glm::mat4 projection; glm::mat4 view; glm::mat4 model; glm::vec4 lightPos = glm::vec4(0.0f, -2.0f, 0.0f, 1.0f); glm::vec4 cameraPos; } vertexShader; struct { float heightScale = 0.1f; // Basic parallax mapping needs a bias to look any good (and is hard to // tweak) float parallaxBias = -0.02f; // Number of layers for steep parallax and parallax occlusion (more layer // = better result for less performance) float numLayers = 48.0f; // (Parallax) mapping mode to use int32_t mappingMode = 4; } fragmentShader; } ubos; VkPipelineLayout pipelineLayout; VkPipeline pipeline; VkDescriptorSetLayout descriptorSetLayout; VkDescriptorSet descriptorSet; const std::vector<std::string> mappingModes = { "Color only", "Normal mapping", "Parallax mapping", "Steep parallax mapping", "Parallax occlusion mapping", }; VulkanExample() : VulkanExampleBase(ENABLE_VALIDATION) { title = "Parallax Mapping"; timerSpeed *= 0.5f; camera.type = Camera::CameraType::firstperson; camera.setPosition(glm::vec3(0.0f, 1.25f, 1.5f)); camera.setRotation(glm::vec3(-45.0f, 180.0f, 0.0f)); camera.setPerspective(60.0f, (float)width / (float)height, 0.1f, 256.0f); settings.overlay = true; } ~VulkanExample() { vkDestroyPipeline(device, pipeline, nullptr); vkDestroyPipelineLayout(device, pipelineLayout, nullptr); vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr); models.quad.destroy(); uniformBuffers.vertexShader.destroy(); uniformBuffers.fragmentShader.destroy(); textures.colorMap.destroy(); textures.normalHeightMap.destroy(); } void loadAssets() { models.quad.loadFromFile(getAssetPath() + "models/plane_z.obj", vertexLayout, 0.1f, vulkanDevice, queue); // Textures textures.normalHeightMap.loadFromFile( getAssetPath() + "textures/rocks_normal_height_rgba.dds", VK_FORMAT_R8G8B8A8_UNORM, vulkanDevice, queue); if (vulkanDevice->features.textureCompressionBC) { textures.colorMap.loadFromFile( getAssetPath() + "textures/rocks_color_bc3_unorm.dds", VK_FORMAT_BC3_UNORM_BLOCK, vulkanDevice, queue); } else if (vulkanDevice->features.textureCompressionASTC_LDR) { textures.colorMap.loadFromFile( getAssetPath() + "textures/rocks_color_astc_8x8_unorm.ktx", VK_FORMAT_ASTC_8x8_UNORM_BLOCK, vulkanDevice, queue); } else if (vulkanDevice->features.textureCompressionETC2) { textures.colorMap.loadFromFile( getAssetPath() + "textures/rocks_color_etc2_unorm.ktx", VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK, vulkanDevice, queue); } else { vks::tools::exitFatal( "Device does not support any compressed texture format!", VK_ERROR_FEATURE_NOT_PRESENT); } } void buildCommandBuffers() { VkCommandBufferBeginInfo cmdBufInfo = vks::initializers::commandBufferBeginInfo(); VkClearValue clearValues[2]; clearValues[0].color = defaultClearColor; clearValues[1].depthStencil = {1.0f, 0}; VkRenderPassBeginInfo renderPassBeginInfo = vks::initializers::renderPassBeginInfo(); renderPassBeginInfo.renderPass = renderPass; renderPassBeginInfo.renderArea.offset.x = 0; renderPassBeginInfo.renderArea.offset.y = 0; renderPassBeginInfo.renderArea.extent.width = width; renderPassBeginInfo.renderArea.extent.height = height; renderPassBeginInfo.clearValueCount = 2; renderPassBeginInfo.pClearValues = clearValues; for (int32_t i = 0; i < drawCmdBuffers.size(); ++i) { // Set target frame buffer renderPassBeginInfo.framebuffer = frameBuffers[i]; VK_CHECK_RESULT(vkBeginCommandBuffer(drawCmdBuffers[i], &cmdBufInfo)); vkCmdBeginRenderPass(drawCmdBuffers[i], &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); VkViewport viewport = vks::initializers::viewport((float)width, (float)height, 0.0f, 1.0f); vkCmdSetViewport(drawCmdBuffers[i], 0, 1, &viewport); VkRect2D scissor = vks::initializers::rect2D(width, height, 0, 0); vkCmdSetScissor(drawCmdBuffers[i], 0, 1, &scissor); vkCmdBindDescriptorSets(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSet, 0, NULL); VkDeviceSize offsets[1] = {0}; vkCmdBindVertexBuffers(drawCmdBuffers[i], VERTEX_BUFFER_BIND_ID, 1, &models.quad.vertices.buffer, offsets); vkCmdBindIndexBuffer(drawCmdBuffers[i], models.quad.indices.buffer, 0, VK_INDEX_TYPE_UINT32); vkCmdSetViewport(drawCmdBuffers[i], 0, 1, &viewport); vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); vkCmdDrawIndexed(drawCmdBuffers[i], models.quad.indexCount, 1, 0, 0, 1); vkCmdEndRenderPass(drawCmdBuffers[i]); VK_CHECK_RESULT(vkEndCommandBuffer(drawCmdBuffers[i])); } } void setupDescriptorPool() { // Example uses two ubos and two image sampler std::vector<VkDescriptorPoolSize> poolSizes = { vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2), vks::initializers::descriptorPoolSize( VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2)}; VkDescriptorPoolCreateInfo descriptorPoolInfo = vks::initializers::descriptorPoolCreateInfo(poolSizes, 2); VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool)); } void setupDescriptorSetLayout() { std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings = { vks::initializers::descriptorSetLayoutBinding( VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), // Binding 0: Vertex shader uniform buffer vks::initializers::descriptorSetLayoutBinding( VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), // Binding 1: Fragment shader color map image sampler vks::initializers::descriptorSetLayoutBinding( VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 2), // Binding 2: Fragment combined normal and heightmap vks::initializers::descriptorSetLayoutBinding( VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_FRAGMENT_BIT, 3), // Binding 3: Fragment shader uniform buffer }; VkDescriptorSetLayoutCreateInfo descriptorLayout = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings); VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayout)); VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = vks::initializers::pipelineLayoutCreateInfo(&descriptorSetLayout, 1); VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pPipelineLayoutCreateInfo, nullptr, &pipelineLayout)); } void setupDescriptorSet() { VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayout, 1); VK_CHECK_RESULT( vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet)); std::vector<VkWriteDescriptorSet> writeDescriptorSets = { vks::initializers::writeDescriptorSet( descriptorSet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformBuffers.vertexShader .descriptor), // Binding 0: Vertex shader uniform buffer vks::initializers::writeDescriptorSet( descriptorSet, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &textures.colorMap .descriptor), // Binding 1: Fragment shader image sampler vks::initializers::writeDescriptorSet( descriptorSet, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2, &textures.normalHeightMap .descriptor), // Binding 2: Combined normal and heightmap vks::initializers::writeDescriptorSet( descriptorSet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 3, &uniformBuffers.fragmentShader .descriptor), // Binding 3: Fragment shader uniform buffer }; vkUpdateDescriptorSets(device, static_cast<uint32_t>(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, NULL); } void preparePipelines() { VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vks::initializers::pipelineInputAssemblyStateCreateInfo( VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterizationState = vks::initializers::pipelineRasterizationStateCreateInfo( VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE); VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE); VkPipelineColorBlendStateCreateInfo colorBlendState = vks::initializers::pipelineColorBlendStateCreateInfo( 1, &blendAttachmentState); VkPipelineDepthStencilStateCreateInfo depthStencilState = vks::initializers::pipelineDepthStencilStateCreateInfo( VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL); VkPipelineViewportStateCreateInfo viewportState = vks::initializers::pipelineViewportStateCreateInfo(1, 1, 0); VkPipelineMultisampleStateCreateInfo multisampleState = vks::initializers::pipelineMultisampleStateCreateInfo( VK_SAMPLE_COUNT_1_BIT); std::vector<VkDynamicState> dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamicState = vks::initializers::pipelineDynamicStateCreateInfo(dynamicStateEnables); // Load shaders std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages; VkGraphicsPipelineCreateInfo pipelineCreateInfo = vks::initializers::pipelineCreateInfo(pipelineLayout, renderPass); pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState; pipelineCreateInfo.pRasterizationState = &rasterizationState; pipelineCreateInfo.pColorBlendState = &colorBlendState; pipelineCreateInfo.pMultisampleState = &multisampleState; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pDepthStencilState = &depthStencilState; pipelineCreateInfo.pDynamicState = &dynamicState; pipelineCreateInfo.stageCount = static_cast<uint32_t>(shaderStages.size()); pipelineCreateInfo.pStages = shaderStages.data(); // Vertex bindings an attributes std::vector<VkVertexInputBindingDescription> vertexInputBindings = { vks::initializers::vertexInputBindingDescription( 0, vertexLayout.stride(), VK_VERTEX_INPUT_RATE_VERTEX), }; std::vector<VkVertexInputAttributeDescription> vertexInputAttributes = { vks::initializers::vertexInputAttributeDescription( VERTEX_BUFFER_BIND_ID, 0, VK_FORMAT_R32G32B32_SFLOAT, 0), // Location 0: Position vks::initializers::vertexInputAttributeDescription( VERTEX_BUFFER_BIND_ID, 1, VK_FORMAT_R32G32_SFLOAT, sizeof(float) * 3), // Location 1: Texture coordinates vks::initializers::vertexInputAttributeDescription( VERTEX_BUFFER_BIND_ID, 2, VK_FORMAT_R32G32B32_SFLOAT, sizeof(float) * 5), // Location 2: Normal vks::initializers::vertexInputAttributeDescription( VERTEX_BUFFER_BIND_ID, 3, VK_FORMAT_R32G32B32_SFLOAT, sizeof(float) * 8), // Location 3: Tangent vks::initializers::vertexInputAttributeDescription( VERTEX_BUFFER_BIND_ID, 4, VK_FORMAT_R32G32B32_SFLOAT, sizeof(float) * 11), // Location 4: Bitangent }; VkPipelineVertexInputStateCreateInfo vertexInputState = vks::initializers::pipelineVertexInputStateCreateInfo(); vertexInputState.vertexBindingDescriptionCount = static_cast<uint32_t>(vertexInputBindings.size()); vertexInputState.pVertexBindingDescriptions = vertexInputBindings.data(); vertexInputState.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertexInputAttributes.size()); vertexInputState.pVertexAttributeDescriptions = vertexInputAttributes.data(); pipelineCreateInfo.pVertexInputState = &vertexInputState; // Parallax mapping modes pipeline shaderStages[0] = loadShader(getAssetPath() + "shaders/parallaxmapping/parallax.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader(getAssetPath() + "shaders/parallaxmapping/parallax.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); VK_CHECK_RESULT(vkCreateGraphicsPipelines( device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipeline)); } void prepareUniformBuffers() { // Vertex shader uniform buffer VK_CHECK_RESULT(vulkanDevice->createBuffer( VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &uniformBuffers.vertexShader, sizeof(ubos.vertexShader))); // Fragment shader uniform buffer VK_CHECK_RESULT(vulkanDevice->createBuffer( VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &uniformBuffers.fragmentShader, sizeof(ubos.fragmentShader))); // Map persistent VK_CHECK_RESULT(uniformBuffers.vertexShader.map()); VK_CHECK_RESULT(uniformBuffers.fragmentShader.map()); updateUniformBuffers(); } void updateUniformBuffers() { // Vertex shader ubos.vertexShader.projection = camera.matrices.perspective; ubos.vertexShader.view = camera.matrices.view; ubos.vertexShader.model = glm::rotate(glm::mat4(1.0f), glm::radians(90.0f), glm::vec3(1.0f, 0.0f, 0.0f)); ; ubos.vertexShader.model = glm::rotate(ubos.vertexShader.model, glm::radians(180.0f), glm::vec3(0.0f, 0.0f, 1.0f)); ; if (!paused) { ubos.vertexShader.lightPos.x = sin(glm::radians(timer * 360.0f)) * 1.5f; ubos.vertexShader.lightPos.z = cos(glm::radians(timer * 360.0f)) * 1.5f; } ubos.vertexShader.cameraPos = glm::vec4(camera.position, -1.0f) * -1.0f; memcpy(uniformBuffers.vertexShader.mapped, &ubos.vertexShader, sizeof(ubos.vertexShader)); // Fragment shader memcpy(uniformBuffers.fragmentShader.mapped, &ubos.fragmentShader, sizeof(ubos.fragmentShader)); } void draw() { VulkanExampleBase::prepareFrame(); submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer]; VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE)); VulkanExampleBase::submitFrame(); } void prepare() { VulkanExampleBase::prepare(); loadAssets(); prepareUniformBuffers(); setupDescriptorSetLayout(); preparePipelines(); setupDescriptorPool(); setupDescriptorSet(); buildCommandBuffers(); prepared = true; } virtual void render() { if (!prepared) return; draw(); if (!paused) { updateUniformBuffers(); } } virtual void viewChanged() { updateUniformBuffers(); } virtual void OnUpdateUIOverlay(vks::UIOverlay *overlay) { if (overlay->header("Settings")) { if (overlay->comboBox("Mode", &ubos.fragmentShader.mappingMode, mappingModes)) { updateUniformBuffers(); } } } }; VULKAN_EXAMPLE_MAIN()
37.928416
80
0.694481
jaebaek
03e136b4a44a2c80b6aa24e40c73c346a590b9c6
19,606
hpp
C++
gearoenix/math/gx-math-matrix-4d.hpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
35
2018-01-07T02:34:38.000Z
2022-02-09T05:19:03.000Z
gearoenix/math/gx-math-matrix-4d.hpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
111
2017-09-20T09:12:36.000Z
2020-12-27T12:52:03.000Z
gearoenix/math/gx-math-matrix-4d.hpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
5
2020-02-11T11:17:37.000Z
2021-01-08T17:55:43.000Z
#ifndef GEAROENIX_MATH_MATRIX_4D_HPP #define GEAROENIX_MATH_MATRIX_4D_HPP #include "gx-math-vector-4d.hpp" namespace gearoenix::math { /// It is a column major matrix template <typename Element> struct Mat4x4 { Element data[4][4]; constexpr Mat4x4() noexcept : data { { static_cast<Element>(1), static_cast<Element>(0), static_cast<Element>(0), static_cast<Element>(0) }, { static_cast<Element>(0), static_cast<Element>(1), static_cast<Element>(0), static_cast<Element>(0) }, { static_cast<Element>(0), static_cast<Element>(0), static_cast<Element>(1), static_cast<Element>(0) }, { static_cast<Element>(0), static_cast<Element>(0), static_cast<Element>(0), static_cast<Element>(1) } } { } constexpr explicit Mat4x4(const Element diameter) noexcept : data { { diameter, static_cast<Element>(0), static_cast<Element>(0), static_cast<Element>(0) }, { static_cast<Element>(0), diameter, static_cast<Element>(0), static_cast<Element>(0) }, { static_cast<Element>(0), static_cast<Element>(0), diameter, static_cast<Element>(0) }, { static_cast<Element>(0), static_cast<Element>(0), static_cast<Element>(0), static_cast<Element>(1) } } { } constexpr Mat4x4( const Element e0, const Element e1, const Element e2, const Element e3, const Element e4, const Element e5, const Element e6, const Element e7, const Element e8, const Element e9, const Element e10, const Element e11, const Element e12, const Element e13, const Element e14, const Element e15) noexcept : data { { e0, e1, e2, e3 }, { e4, e5, e6, e7 }, { e8, e9, e10, e11 }, { e12, e13, e14, e15 }, } { } explicit Mat4x4(system::stream::Stream* const f) noexcept { read(f); } constexpr Mat4x4(const Mat4x4<Element>& m) noexcept : data { { m.data[0][0], m.data[0][1], m.data[0][2], m.data[0][3] }, { m.data[1][0], m.data[1][1], m.data[1][2], m.data[1][3] }, { m.data[2][0], m.data[2][1], m.data[2][2], m.data[2][3] }, { m.data[3][0], m.data[3][1], m.data[3][2], m.data[3][3] }, } { } template <typename T> constexpr explicit Mat4x4(const Mat4x4<T>& m) noexcept : data { { static_cast<Element>(m.data[0][0]), static_cast<Element>(m.data[0][1]), static_cast<Element>(m.data[0][2]), static_cast<Element>(m.data[0][3]) }, { static_cast<Element>(m.data[1][0]), static_cast<Element>(m.data[1][1]), static_cast<Element>(m.data[1][2]), static_cast<Element>(m.data[1][3]) }, { static_cast<Element>(m.data[2][0]), static_cast<Element>(m.data[2][1]), static_cast<Element>(m.data[2][2]), static_cast<Element>(m.data[2][3]) }, { static_cast<Element>(m.data[3][0]), static_cast<Element>(m.data[3][1]), static_cast<Element>(m.data[3][2]), static_cast<Element>(m.data[3][3]) }, } { } [[nodiscard]] constexpr Vec4<Element> operator*(const Vec4<Element>& v) const noexcept { return Vec4<Element>( data[0][0] * v.x + data[1][0] * v.y + data[2][0] * v.z + data[3][0] * v.w, data[0][1] * v.x + data[1][1] * v.y + data[2][1] * v.z + data[3][1] * v.w, data[0][2] * v.x + data[1][2] * v.y + data[2][2] * v.z + data[3][2] * v.w, data[0][3] * v.x + data[1][3] * v.y + data[2][3] * v.z + data[3][3] * v.w); } [[nodiscard]] constexpr Mat4x4<Element> operator*(const Mat4x4<Element>& m) const noexcept { Mat4x4<Element> r; for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { r.data[i][j] = m.data[i][0] * data[0][j] + m.data[i][1] * data[1][j] + m.data[i][2] * data[2][j] + m.data[i][3] * data[3][j]; } } return r; } constexpr Mat4x4<Element>& operator=(const Mat4x4<Element>& m) noexcept { for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { data[i][j] = m.data[i][j]; } } return *this; } constexpr void operator*=(const Mat4x4<Element>& m) noexcept { const auto o = *this * m; *this = o; } template <typename T> constexpr Element operator[](const T i) const noexcept { return data[i >> 2][i & 3]; } template <typename T> constexpr Element& operator[](const T i) noexcept { return data[i >> 2][i & 3]; } /// It does not change location constexpr void local_scale(const Element s) noexcept { local_scale(s, s, s); } /// It does not change location constexpr void local_x_scale(const Element s) noexcept { data[0][0] *= s; data[0][1] *= s; data[0][2] *= s; data[0][3] *= s; } /// It does not change location constexpr void local_y_scale(const Element s) noexcept { data[1][0] *= s; data[1][1] *= s; data[1][2] *= s; data[1][3] *= s; } /// It does not change location constexpr void local_z_scale(const Element s) noexcept { data[2][0] *= s; data[2][1] *= s; data[2][2] *= s; data[2][3] *= s; } /// It does not change location constexpr void local_w_scale(const Element s) noexcept { data[3][0] *= s; data[3][1] *= s; data[3][2] *= s; data[3][3] *= s; } /// It does not change location constexpr void local_scale(const Element a, const Element b, const Element c) noexcept { local_x_scale(a); local_y_scale(b); local_z_scale(c); } /// It changes location constexpr void local_scale(const Element a, const Element b, const Element c, const Element d) noexcept { local_scale(a, b, c); local_w_scale(d); } /// It does not change location constexpr void local_scale(const Vec3<Element>& s) noexcept { local_scale(s.x, s.y, s.z); } /// It changes location constexpr void local_scale(const Vec4<Element>& s) noexcept { local_scale(s.x, s.y, s.z, s.w); } /// It changes location constexpr void global_scale(const Element s) noexcept { global_scale(s, s, s); } /// It changes location constexpr void global_scale(const Element a, const Element b, const Element c) noexcept { data[0][0] *= a; data[1][0] *= a; data[2][0] *= a; data[3][0] *= a; data[0][1] *= b; data[1][1] *= b; data[2][1] *= b; data[3][1] *= b; data[0][2] *= c; data[1][2] *= c; data[2][2] *= c; data[3][2] *= c; } /// It changes location constexpr void global_scale(const Element a, const Element b, const Element c, const Element d) noexcept { global_scale(a, b, c); data[0][3] *= d; data[1][3] *= d; data[2][3] *= d; data[3][3] *= d; } /// It changes location constexpr void global_scale(const Vec3<Element>& s) noexcept { global_scale(s.x, s.y, s.z); } /// It changes location constexpr void global_scale(const Vec4<Element>& s) noexcept { global_scale(s.x, s.y, s.z, s.w); } constexpr void translate(const Vec3<Element>& v) noexcept { data[3][0] += v.x; data[3][1] += v.y; data[3][2] += v.z; } constexpr void set_location(const Vec3<Element>& location = Vec3<Element>(0)) noexcept { data[3][0] = location.x; data[3][1] = location.y; data[3][2] = location.z; } constexpr void get_location(Vec3<Element>& location) const noexcept { location.x = data[3][0]; location.y = data[3][1]; location.z = data[3][2]; } [[nodiscard]] constexpr Vec3<Element> get_location() const noexcept { Vec3<Element> v; get_location(v); return v; } constexpr void inverse() noexcept { *this = inverted(); } constexpr void transpose() noexcept { for (auto i = 0; i < 4; ++i) { for (auto j = i + 1; j < 4; ++j) { std::swap(data[i][j], data[j][i]); } } } void read(system::stream::Stream* const f) noexcept { for (auto& r : data) for (auto& c : r) c = static_cast<Element>(f->read<float>()); } [[nodiscard]] constexpr Element determinant() const noexcept { return (+data[0][0] * (+data[1][1] * (data[2][2] * data[3][3] - data[2][3] * data[3][2]) - data[2][1] * (data[1][2] * data[3][3] - data[1][3] * data[3][2]) + data[3][1] * (data[1][2] * data[2][3] - data[1][3] * data[2][2])) - data[1][0] * (+data[0][1] * (data[2][2] * data[3][3] - data[2][3] * data[3][2]) - data[2][1] * (data[0][2] * data[3][3] - data[0][3] * data[3][2]) + data[3][1] * (data[0][2] * data[2][3] - data[0][3] * data[2][2])) + data[2][0] * (+data[0][1] * (data[1][2] * data[3][3] - data[1][3] * data[3][2]) - data[1][1] * (data[0][2] * data[3][3] - data[0][3] * data[3][2]) + data[3][1] * (data[0][2] * data[1][3] - data[0][3] * data[1][2])) - data[3][0] * (+data[0][1] * (data[1][2] * data[2][3] - data[1][3] * data[2][2]) - data[1][1] * (data[0][2] * data[2][3] - data[0][3] * data[2][2]) + data[2][1] * (data[0][2] * data[1][3] - data[0][3] * data[1][2]))); } [[nodiscard]] constexpr Mat4x4<Element> inverted() const noexcept { const auto id = static_cast<Element>(1) / determinant(); Mat4x4<Element> result; result.data[0][0] = id * (+data[1][1] * (data[2][2] * data[3][3] - data[2][3] * data[3][2]) - data[2][1] * (data[1][2] * data[3][3] - data[1][3] * data[3][2]) + data[3][1] * (data[1][2] * data[2][3] - data[1][3] * data[2][2])); result.data[0][1] = id * -(+data[0][1] * (data[2][2] * data[3][3] - data[2][3] * data[3][2]) - data[2][1] * (data[0][2] * data[3][3] - data[0][3] * data[3][2]) + data[3][1] * (data[0][2] * data[2][3] - data[0][3] * data[2][2])); result.data[0][2] = id * (+data[0][1] * (data[1][2] * data[3][3] - data[1][3] * data[3][2]) - data[1][1] * (data[0][2] * data[3][3] - data[0][3] * data[3][2]) + data[3][1] * (data[0][2] * data[1][3] - data[0][3] * data[1][2])); result.data[0][3] = id * -(+data[0][1] * (data[1][2] * data[2][3] - data[1][3] * data[2][2]) - data[1][1] * (data[0][2] * data[2][3] - data[0][3] * data[2][2]) + data[2][1] * (data[0][2] * data[1][3] - data[0][3] * data[1][2])); result.data[1][0] = id * -(+data[1][0] * (data[2][2] * data[3][3] - data[2][3] * data[3][2]) - data[2][0] * (data[1][2] * data[3][3] - data[1][3] * data[3][2]) + data[3][0] * (data[1][2] * data[2][3] - data[1][3] * data[2][2])); result.data[1][1] = id * (+data[0][0] * (data[2][2] * data[3][3] - data[2][3] * data[3][2]) - data[2][0] * (data[0][2] * data[3][3] - data[0][3] * data[3][2]) + data[3][0] * (data[0][2] * data[2][3] - data[0][3] * data[2][2])); result.data[1][2] = id * -(+data[0][0] * (data[1][2] * data[3][3] - data[1][3] * data[3][2]) - data[1][0] * (data[0][2] * data[3][3] - data[0][3] * data[3][2]) + data[3][0] * (data[0][2] * data[1][3] - data[0][3] * data[1][2])); result.data[1][3] = id * (+data[0][0] * (data[1][2] * data[2][3] - data[1][3] * data[2][2]) - data[1][0] * (data[0][2] * data[2][3] - data[0][3] * data[2][2]) + data[2][0] * (data[0][2] * data[1][3] - data[0][3] * data[1][2])); result.data[2][0] = id * (+data[1][0] * (data[2][1] * data[3][3] - data[2][3] * data[3][1]) - data[2][0] * (data[1][1] * data[3][3] - data[1][3] * data[3][1]) + data[3][0] * (data[1][1] * data[2][3] - data[1][3] * data[2][1])); result.data[2][1] = id * -(+data[0][0] * (data[2][1] * data[3][3] - data[2][3] * data[3][1]) - data[2][0] * (data[0][1] * data[3][3] - data[0][3] * data[3][1]) + data[3][0] * (data[0][1] * data[2][3] - data[0][3] * data[2][1])); result.data[2][2] = id * (+data[0][0] * (data[1][1] * data[3][3] - data[1][3] * data[3][1]) - data[1][0] * (data[0][1] * data[3][3] - data[0][3] * data[3][1]) + data[3][0] * (data[0][1] * data[1][3] - data[0][3] * data[1][1])); result.data[2][3] = id * -(+data[0][0] * (data[1][1] * data[2][3] - data[1][3] * data[2][1]) - data[1][0] * (data[0][1] * data[2][3] - data[0][3] * data[2][1]) + data[2][0] * (data[0][1] * data[1][3] - data[0][3] * data[1][1])); result.data[3][0] = id * -(+data[1][0] * (data[2][1] * data[3][2] - data[2][2] * data[3][1]) - data[2][0] * (data[1][1] * data[3][2] - data[1][2] * data[3][1]) + data[3][0] * (data[1][1] * data[2][2] - data[1][2] * data[2][1])); result.data[3][1] = id * (+data[0][0] * (data[2][1] * data[3][2] - data[2][2] * data[3][1]) - data[2][0] * (data[0][1] * data[3][2] - data[0][2] * data[3][1]) + data[3][0] * (data[0][1] * data[2][2] - data[0][2] * data[2][1])); result.data[3][2] = id * -(+data[0][0] * (data[1][1] * data[3][2] - data[1][2] * data[3][1]) - data[1][0] * (data[0][1] * data[3][2] - data[0][2] * data[3][1]) + data[3][0] * (data[0][1] * data[1][2] - data[0][2] * data[1][1])); result.data[3][3] = id * (+data[0][0] * (data[1][1] * data[2][2] - data[1][2] * data[2][1]) - data[1][0] * (data[0][1] * data[2][2] - data[0][2] * data[2][1]) + data[2][0] * (data[0][1] * data[1][2] - data[0][2] * data[1][1])); return result; } [[nodiscard]] constexpr Mat4x4<Element> transposed() const noexcept { Mat4x4<Element> r; for (auto i = 0; i < 4; ++i) { for (auto j = 0; j < 4; ++j) { r.data[i][j] = data[j][i]; } } return r; } [[nodiscard]] constexpr Vec3<Element> project(const Vec3<Element>& v) const noexcept { Vec4<Element> v4(v, static_cast<Element>(1)); v4 = *this * v4; return v4.xyz() / v4.w; } [[nodiscard]] constexpr static Mat4x4<Element> look_at(const Vec3<Element>& position, const Vec3<Element>& target, const Vec3<Element>& up) noexcept { const auto z = (target - position).normalized(); const auto x = up.cross(z).normalized(); const auto y = z.cross(x); Mat4x4<Element> m; m.data[0][0] = -x.x; m.data[0][1] = y.x; m.data[0][2] = -z.x; m.data[0][3] = static_cast<Element>(0); m.data[1][0] = -x.y; m.data[1][1] = y.y; m.data[1][2] = -z.y; m.data[1][3] = static_cast<Element>(0); m.data[2][0] = -x.z; m.data[2][1] = y.z; m.data[2][2] = -z.z; m.data[2][3] = static_cast<Element>(0); m.data[3][0] = x.dot(position); m.data[3][1] = -y.dot(position); m.data[3][2] = z.dot(position); m.data[3][3] = static_cast<Element>(1); return m; } [[nodiscard]] constexpr static Mat4x4<Element> rotation(const Vec3<Element>& v, const Element degree) noexcept { const auto sinus = static_cast<Element>(sin(static_cast<double>(degree))); const auto cosinus = static_cast<Element>(cos(static_cast<double>(degree))); const Element oneminuscos = 1.0f - cosinus; const Vec3 w = v.normalized(); const Element wx2 = w[0] * w[0]; const Element wxy = w[0] * w[1]; const Element wxz = w[0] * w[2]; const Element wy2 = w[1] * w[1]; const Element wyz = w[1] * w[2]; const Element wz2 = w[2] * w[2]; const Element wxyonemincos = wxy * oneminuscos; const Element wxzonemincos = wxz * oneminuscos; const Element wyzonemincos = wyz * oneminuscos; const Element wxsin = w[0] * sinus; const Element wysin = w[1] * sinus; const Element wzsin = w[2] * sinus; Mat4x4 m; m.data[0][0] = cosinus + (wx2 * oneminuscos); m.data[0][1] = wzsin + wxyonemincos; m.data[0][2] = wxzonemincos - wysin; m.data[0][3] = static_cast<Element>(0); m.data[1][0] = wxyonemincos - wzsin; m.data[1][1] = cosinus + (wy2 * oneminuscos); m.data[1][2] = wxsin + wyzonemincos; m.data[1][3] = static_cast<Element>(0); m.data[2][0] = wysin + wxzonemincos; m.data[2][1] = wyzonemincos - wxsin; m.data[2][2] = cosinus + (wz2 * oneminuscos); m.data[2][3] = static_cast<Element>(0); m.data[3][0] = static_cast<Element>(0); m.data[3][1] = static_cast<Element>(0); m.data[3][2] = static_cast<Element>(0); m.data[3][3] = static_cast<Element>(1); return m; } [[nodiscard]] constexpr static Mat4x4<Element> translator(const Vec3<Element>& v) noexcept { Mat4x4<Element> r; r.data[0][0] = static_cast<Element>(1); r.data[0][1] = static_cast<Element>(0); r.data[0][2] = static_cast<Element>(0); r.data[0][3] = static_cast<Element>(0); r.data[1][0] = static_cast<Element>(0); r.data[1][1] = static_cast<Element>(1); r.data[1][2] = static_cast<Element>(0); r.data[1][3] = static_cast<Element>(0); r.data[2][0] = static_cast<Element>(0); r.data[2][1] = static_cast<Element>(0); r.data[2][2] = static_cast<Element>(1); r.data[2][3] = static_cast<Element>(0); r.data[3][0] = v.x; r.data[3][1] = v.y; r.data[3][2] = v.z; r.data[3][3] = static_cast<Element>(1); return r; } [[nodiscard]] constexpr static Mat4x4<Element> orthographic(const Element width, const Element height, const Element near, const Element far) noexcept { Mat4x4 r; r.data[0][0] = Element(2.0f / width); r.data[0][1] = static_cast<Element>(0); r.data[0][2] = static_cast<Element>(0); r.data[0][3] = static_cast<Element>(0); r.data[1][0] = static_cast<Element>(0); r.data[1][1] = Element(2.0f / height); r.data[1][2] = static_cast<Element>(0); r.data[1][3] = static_cast<Element>(0); r.data[2][0] = static_cast<Element>(0); r.data[2][1] = static_cast<Element>(0); r.data[2][2] = Element(2.0f / (near - far)); r.data[2][3] = static_cast<Element>(0); r.data[3][0] = static_cast<Element>(0); r.data[3][1] = static_cast<Element>(0); r.data[3][2] = Element((far + near) / (near - far)); r.data[3][3] = static_cast<Element>(1); return r; } [[nodiscard]] constexpr static Mat4x4<Element> perspective(const Element width, const Element height, const Element near, const Element far) noexcept { Mat4x4 r; r.data[0][0] = Element((2.0f * near) / width); r.data[0][1] = static_cast<Element>(0); r.data[0][2] = static_cast<Element>(0); r.data[0][3] = static_cast<Element>(0); r.data[1][0] = static_cast<Element>(0); r.data[1][1] = Element((2.0f * near) / height); r.data[1][2] = static_cast<Element>(0); r.data[1][3] = static_cast<Element>(0); r.data[2][0] = static_cast<Element>(0); r.data[2][1] = static_cast<Element>(0); r.data[2][2] = Element((far + near) / (near - far)); r.data[2][3] = Element(-1.0); r.data[3][0] = static_cast<Element>(0); r.data[3][1] = static_cast<Element>(0); r.data[3][2] = Element((2.0f * far * near) / (near - far)); r.data[3][3] = static_cast<Element>(0); return r; } }; } #endif
42.163441
236
0.511527
Hossein-Noroozpour
03e1ff81de734ba25e35f11c2c9a5d2de140ded4
10,929
cpp
C++
src/core/TChem_IgnitionZeroD.cpp
mschmidt271/TChem
01adfcbef0ac107cbc7b9df9d03d783ef5eac83b
[ "BSD-2-Clause" ]
null
null
null
src/core/TChem_IgnitionZeroD.cpp
mschmidt271/TChem
01adfcbef0ac107cbc7b9df9d03d783ef5eac83b
[ "BSD-2-Clause" ]
null
null
null
src/core/TChem_IgnitionZeroD.cpp
mschmidt271/TChem
01adfcbef0ac107cbc7b9df9d03d783ef5eac83b
[ "BSD-2-Clause" ]
null
null
null
#include "TChem_Util.hpp" #include "TChem_IgnitionZeroD.hpp" /// tadv - an input structure for time marching /// state (nSpec+3) - initial condition of the state vector /// qidx (lt nSpec+1) - QoI indices to store in qoi output /// work - work space sized by getWorkSpaceSize /// tcnt - time counter /// qoi (time + qidx.extent(0)) - QoI output /// kmcd - const data for kinetic model namespace TChem { template<typename PolicyType, typename TimeAdvance1DViewType, typename RealType0DViewType, typename RealType1DViewType, typename RealType2DViewType, typename KineticModelConstViewType> void IgnitionZeroD_TemplateRunModelVariation( /// required template arguments const std::string& profile_name, const RealType0DViewType& dummy_0d, /// team size setting const PolicyType& policy, /// input const RealType1DViewType& tol_newton, const RealType2DViewType& tol_time, const RealType2DViewType& fac, const TimeAdvance1DViewType& tadv, const RealType2DViewType& state, /// output const RealType1DViewType& t_out, const RealType1DViewType& dt_out, const RealType2DViewType& state_out, /// const data from kinetic model const KineticModelConstViewType& kmcds) { Kokkos::Profiling::pushRegion(profile_name); using policy_type = PolicyType; auto kmcd_host = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), Kokkos::subview(kmcds, 0)); const ordinal_type level = 1; const ordinal_type per_team_extent = IgnitionZeroD::getWorkSpaceSize(kmcd_host()); Kokkos::parallel_for( profile_name, policy, KOKKOS_LAMBDA(const typename policy_type::member_type& member) { const ordinal_type i = member.league_rank(); const auto kmcd_at_i = (kmcds.extent(0) == 1 ? kmcds(0) : kmcds(i)); const RealType1DViewType fac_at_i = Kokkos::subview(fac, i, Kokkos::ALL()); const auto tadv_at_i = tadv(i); const real_type t_end = tadv_at_i._tend; const RealType0DViewType t_out_at_i = Kokkos::subview(t_out, i); if (t_out_at_i() < t_end) { const RealType1DViewType state_at_i = Kokkos::subview(state, i, Kokkos::ALL()); const RealType1DViewType state_out_at_i = Kokkos::subview(state_out, i, Kokkos::ALL()); const RealType0DViewType dt_out_at_i = Kokkos::subview(dt_out, i); Scratch<RealType1DViewType> work(member.team_scratch(level), per_team_extent); Impl::StateVector<RealType1DViewType> sv_at_i(kmcd_at_i.nSpec, state_at_i); Impl::StateVector<RealType1DViewType> sv_out_at_i(kmcd_at_i.nSpec, state_out_at_i); TCHEM_CHECK_ERROR(!sv_at_i.isValid(), "Error: input state vector is not valid"); TCHEM_CHECK_ERROR(!sv_out_at_i.isValid(), "Error: input state vector is not valid"); { const ordinal_type max_num_newton_iterations = tadv_at_i._max_num_newton_iterations; const ordinal_type max_num_time_iterations = tadv_at_i._num_time_iterations_per_interval; const real_type dt_in = tadv_at_i._dt, dt_min = tadv_at_i._dtmin, dt_max = tadv_at_i._dtmax; const real_type t_beg = tadv_at_i._tbeg; const auto temperature = sv_at_i.Temperature(); const auto pressure = sv_at_i.Pressure(); const auto Ys = sv_at_i.MassFractions(); const RealType0DViewType temperature_out(sv_out_at_i.TemperaturePtr()); const RealType0DViewType pressure_out(sv_out_at_i.PressurePtr()); const RealType1DViewType Ys_out = sv_out_at_i.MassFractions(); const ordinal_type m = Impl::IgnitionZeroD_Problem< typename KineticModelConstViewType::non_const_value_type >::getNumberOfEquations(kmcd_at_i); auto wptr = work.data(); const RealType1DViewType vals(wptr, m); wptr += m; const RealType1DViewType ww(wptr, work.extent(0) - (wptr - work.data())); /// we can only guarantee vals is contiguous array. we basically assume /// that a state vector can be arbitrary ordered. /// m is nSpec + 1 Kokkos::parallel_for(Kokkos::TeamVectorRange(member, m), [&](const ordinal_type& i) { vals(i) = i == 0 ? temperature : Ys(i - 1); }); member.team_barrier(); Impl::IgnitionZeroD ::team_invoke(member, max_num_newton_iterations, max_num_time_iterations, tol_newton, tol_time, fac_at_i, dt_in, dt_min, dt_max, t_beg, t_end, pressure, vals, t_out_at_i, dt_out_at_i, pressure_out, vals, ww, kmcd_at_i); member.team_barrier(); Kokkos::parallel_for(Kokkos::TeamVectorRange(member, m), [&](const ordinal_type& i) { if (i == 0) { temperature_out() = vals(0); } else { Ys_out(i - 1) = vals(i); } }); member.team_barrier(); } } }); Kokkos::Profiling::popRegion(); } template<typename PolicyType, typename TimeAdvance1DViewType, typename RealType0DViewType, typename RealType1DViewType, typename RealType2DViewType, typename KineticModelConstType> void IgnitionZeroD_TemplateRun( /// required template arguments const std::string& profile_name, const RealType0DViewType& dummy_0d, /// team size setting const PolicyType& policy, /// input const RealType1DViewType& tol_newton, const RealType2DViewType& tol_time, const RealType2DViewType& fac, const TimeAdvance1DViewType& tadv, const RealType2DViewType& state, /// output const RealType1DViewType& t_out, const RealType1DViewType& dt_out, const RealType2DViewType& state_out, /// const data from kinetic model const KineticModelConstType& kmcd) { Kokkos::Profiling::pushRegion(profile_name); using policy_type = PolicyType; using space_type = typename policy_type::execution_space; Kokkos::View<KineticModelConstType*,space_type> kmcds(do_not_init_tag("IgnitionaZeroD::kmcds"), 1); Kokkos::deep_copy(kmcds, kmcd); IgnitionZeroD_TemplateRunModelVariation (profile_name, dummy_0d, policy, tol_newton, tol_time, fac, tadv, state, t_out, dt_out, state_out, kmcds); Kokkos::Profiling::popRegion(); } void IgnitionZeroD::runHostBatch( /// input typename UseThisTeamPolicy<host_exec_space>::type& policy, const real_type_1d_view_host& tol_newton, const real_type_2d_view_host& tol_time, const real_type_2d_view_host& fac, const time_advance_type_1d_view_host& tadv, const real_type_2d_view_host& state, /// output const real_type_1d_view_host& t_out, const real_type_1d_view_host& dt_out, const real_type_2d_view_host& state_out, /// const data from kinetic model const KineticModelConstDataHost& kmcd) { IgnitionZeroD_TemplateRun( /// template arguments deduction "TChem::IgnitionZeroD::runHostBatch::kmcd", real_type_0d_view_host(), /// team policy policy, /// input tol_newton, tol_time, fac, tadv, state, /// output t_out, dt_out, state_out, /// const data of kinetic model kmcd); } void IgnitionZeroD::runDeviceBatch( /// thread block size typename UseThisTeamPolicy<exec_space>::type& policy, /// input const real_type_1d_view& tol_newton, const real_type_2d_view& tol_time, const real_type_2d_view& fac, const time_advance_type_1d_view& tadv, const real_type_2d_view& state, /// output const real_type_1d_view& t_out, const real_type_1d_view& dt_out, const real_type_2d_view& state_out, /// const data from kinetic model const KineticModelConstDataDevice& kmcd) { IgnitionZeroD_TemplateRun( /// template arguments deduction "TChem::IgnitionZeroD::runHostBatch::kmcd", real_type_0d_view(), /// team policy policy, /// input tol_newton, tol_time, fac, tadv, state, /// output t_out, dt_out, state_out, /// const data of kinetic model kmcd); } void IgnitionZeroD::runHostBatch( /// input typename UseThisTeamPolicy<host_exec_space>::type& policy, const real_type_1d_view_host& tol_newton, const real_type_2d_view_host& tol_time, const real_type_2d_view_host& fac, const time_advance_type_1d_view_host& tadv, const real_type_2d_view_host& state, /// output const real_type_1d_view_host& t_out, const real_type_1d_view_host& dt_out, const real_type_2d_view_host& state_out, /// const data from kinetic model const Kokkos::View<KineticModelConstDataHost*,host_exec_space>& kmcds) { IgnitionZeroD_TemplateRunModelVariation( /// template arguments deduction "TChem::IgnitionZeroD::runHostBatch::kmcd array", real_type_0d_view_host(), /// team policy policy, /// input tol_newton, tol_time, fac, tadv, state, /// output t_out, dt_out, state_out, /// const data of kinetic model kmcds); } void IgnitionZeroD::runDeviceBatch( /// thread block size typename UseThisTeamPolicy<exec_space>::type& policy, /// input const real_type_1d_view& tol_newton, const real_type_2d_view& tol_time, const real_type_2d_view& fac, const time_advance_type_1d_view& tadv, const real_type_2d_view& state, /// output const real_type_1d_view& t_out, const real_type_1d_view& dt_out, const real_type_2d_view& state_out, /// const data from kinetic model const Kokkos::View<KineticModelConstDataDevice*,exec_space>& kmcds) { IgnitionZeroD_TemplateRunModelVariation( /// template arguments deduction "TChem::IgnitionZeroD::runHostBatch::kmcd array", real_type_0d_view(), /// team policy policy, /// input tol_newton, tol_time, fac, tadv, state, /// output t_out, dt_out, state_out, /// const data of kinetic model kmcds); } } // namespace TChem
32.526786
84
0.631897
mschmidt271
03e4abf480bb30d6785b80fa1d0f6423786d80bd
90,496
cpp
C++
Source/WebCore/animation/KeyframeEffect.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
Source/WebCore/animation/KeyframeEffect.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
Source/WebCore/animation/KeyframeEffect.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2017-2019 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 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 APPLE INC. ``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 APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "KeyframeEffect.h" #include "Animation.h" #include "CSSAnimation.h" #include "CSSComputedStyleDeclaration.h" #include "CSSKeyframeRule.h" #include "CSSPropertyAnimation.h" #include "CSSPropertyNames.h" #include "CSSSelector.h" #include "CSSStyleDeclaration.h" #include "CSSTimingFunctionValue.h" #include "CSSTransition.h" #include "Element.h" #include "FontCascade.h" #include "FrameView.h" #include "GeometryUtilities.h" #include "InspectorInstrumentation.h" #include "JSCompositeOperation.h" #include "JSCompositeOperationOrAuto.h" #include "JSDOMConvert.h" #include "JSKeyframeEffect.h" #include "KeyframeEffectStack.h" #include "Logging.h" #include "PseudoElement.h" #include "RenderBox.h" #include "RenderBoxModelObject.h" #include "RenderElement.h" #include "RenderStyle.h" #include "RuntimeEnabledFeatures.h" #include "StyleAdjuster.h" #include "StylePendingResources.h" #include "StyleResolver.h" #include "TimingFunction.h" #include "TranslateTransformOperation.h" #include "WillChangeData.h" #include <JavaScriptCore/Exception.h> #include <wtf/UUID.h> #include <wtf/text/TextStream.h> namespace WebCore { using namespace JSC; static inline void invalidateElement(Element* element) { if (element) element->invalidateStyle(); } static inline String CSSPropertyIDToIDLAttributeName(CSSPropertyID cssPropertyId) { // https://drafts.csswg.org/web-animations-1/#animation-property-name-to-idl-attribute-name // 1. If property follows the <custom-property-name> production, return property. // FIXME: We don't handle custom properties yet. // 2. If property refers to the CSS float property, return the string "cssFloat". if (cssPropertyId == CSSPropertyFloat) return "cssFloat"; // 3. If property refers to the CSS offset property, return the string "cssOffset". // FIXME: we don't support the CSS "offset" property // 4. Otherwise, return the result of applying the CSS property to IDL attribute algorithm [CSSOM] to property. return getJSPropertyName(cssPropertyId); } static inline CSSPropertyID IDLAttributeNameToAnimationPropertyName(const String& idlAttributeName) { // https://drafts.csswg.org/web-animations-1/#idl-attribute-name-to-animation-property-name // 1. If attribute conforms to the <custom-property-name> production, return attribute. // FIXME: We don't handle custom properties yet. // 2. If attribute is the string "cssFloat", then return an animation property representing the CSS float property. if (idlAttributeName == "cssFloat") return CSSPropertyFloat; // 3. If attribute is the string "cssOffset", then return an animation property representing the CSS offset property. // FIXME: We don't support the CSS "offset" property. // 4. Otherwise, return the result of applying the IDL attribute to CSS property algorithm [CSSOM] to attribute. auto cssPropertyId = CSSStyleDeclaration::getCSSPropertyIDFromJavaScriptPropertyName(idlAttributeName); // We need to check that converting the property back to IDL form yields the same result such that a property passed // in non-IDL form is rejected, for instance "font-size". if (idlAttributeName != CSSPropertyIDToIDLAttributeName(cssPropertyId)) return CSSPropertyInvalid; return cssPropertyId; } static inline void computeMissingKeyframeOffsets(Vector<KeyframeEffect::ParsedKeyframe>& keyframes) { // https://drafts.csswg.org/web-animations-1/#compute-missing-keyframe-offsets if (keyframes.isEmpty()) return; // 1. For each keyframe, in keyframes, let the computed keyframe offset of the keyframe be equal to its keyframe offset value. // In our implementation, we only set non-null values to avoid making computedOffset Optional<double>. Instead, we'll know // that a keyframe hasn't had a computed offset by checking if it has a null offset and a 0 computedOffset, since the first // keyframe will already have a 0 computedOffset. for (auto& keyframe : keyframes) { auto computedOffset = keyframe.offset; keyframe.computedOffset = computedOffset ? *computedOffset : 0; } // 2. If keyframes contains more than one keyframe and the computed keyframe offset of the first keyframe in keyframes is null, // set the computed keyframe offset of the first keyframe to 0. if (keyframes.size() > 1 && !keyframes[0].offset) keyframes[0].computedOffset = 0; // 3. If the computed keyframe offset of the last keyframe in keyframes is null, set its computed keyframe offset to 1. if (!keyframes.last().offset) keyframes.last().computedOffset = 1; // 4. For each pair of keyframes A and B where: // - A appears before B in keyframes, and // - A and B have a computed keyframe offset that is not null, and // - all keyframes between A and B have a null computed keyframe offset, // calculate the computed keyframe offset of each keyframe between A and B as follows: // 1. Let offsetk be the computed keyframe offset of a keyframe k. // 2. Let n be the number of keyframes between and including A and B minus 1. // 3. Let index refer to the position of keyframe in the sequence of keyframes between A and B such that the first keyframe after A has an index of 1. // 4. Set the computed keyframe offset of keyframe to offsetA + (offsetB − offsetA) × index / n. size_t indexOfLastKeyframeWithNonNullOffset = 0; for (size_t i = 1; i < keyframes.size(); ++i) { auto& keyframe = keyframes[i]; // Keyframes with a null offset that don't yet have a non-zero computed offset are keyframes // with an offset that needs to be computed. if (!keyframe.offset && !keyframe.computedOffset) continue; if (indexOfLastKeyframeWithNonNullOffset != i - 1) { double lastNonNullOffset = keyframes[indexOfLastKeyframeWithNonNullOffset].computedOffset; double offsetDelta = keyframe.computedOffset - lastNonNullOffset; double offsetIncrement = offsetDelta / (i - indexOfLastKeyframeWithNonNullOffset); size_t indexOfFirstKeyframeWithNullOffset = indexOfLastKeyframeWithNonNullOffset + 1; for (size_t j = indexOfFirstKeyframeWithNullOffset; j < i; ++j) keyframes[j].computedOffset = lastNonNullOffset + (j - indexOfLastKeyframeWithNonNullOffset) * offsetIncrement; } indexOfLastKeyframeWithNonNullOffset = i; } } static inline ExceptionOr<KeyframeEffect::KeyframeLikeObject> processKeyframeLikeObject(JSGlobalObject& lexicalGlobalObject, Strong<JSObject>&& keyframesInput, bool allowLists) { // https://drafts.csswg.org/web-animations-1/#process-a-keyframe-like-object VM& vm = lexicalGlobalObject.vm(); auto scope = DECLARE_THROW_SCOPE(vm); // 1. Run the procedure to convert an ECMAScript value to a dictionary type [WEBIDL] with keyframe input as the ECMAScript value as follows: // // If allow lists is true, use the following dictionary type: // // dictionary BasePropertyIndexedKeyframe { // (double? or sequence<double?>) offset = []; // (DOMString or sequence<DOMString>) easing = []; // (CompositeOperationOrAuto or sequence<CompositeOperationOrAuto>) composite = []; // }; // // Otherwise, use the following dictionary type: // // dictionary BaseKeyframe { // double? offset = null; // DOMString easing = "linear"; // CompositeOperationOrAuto composite = "auto"; // }; // // Store the result of this procedure as keyframe output. KeyframeEffect::BasePropertyIndexedKeyframe baseProperties; if (allowLists) baseProperties = convert<IDLDictionary<KeyframeEffect::BasePropertyIndexedKeyframe>>(lexicalGlobalObject, keyframesInput.get()); else { auto baseKeyframe = convert<IDLDictionary<KeyframeEffect::BaseKeyframe>>(lexicalGlobalObject, keyframesInput.get()); if (baseKeyframe.offset) baseProperties.offset = baseKeyframe.offset.value(); else baseProperties.offset = nullptr; baseProperties.easing = baseKeyframe.easing; if (RuntimeEnabledFeatures::sharedFeatures().webAnimationsCompositeOperationsEnabled()) baseProperties.composite = baseKeyframe.composite; } RETURN_IF_EXCEPTION(scope, Exception { TypeError }); KeyframeEffect::KeyframeLikeObject keyframeOuput; keyframeOuput.baseProperties = baseProperties; // 2. Build up a list of animatable properties as follows: // // 1. Let animatable properties be a list of property names (including shorthand properties that have longhand sub-properties // that are animatable) that can be animated by the implementation. // 2. Convert each property name in animatable properties to the equivalent IDL attribute by applying the animation property // name to IDL attribute name algorithm. // 3. Let input properties be the result of calling the EnumerableOwnNames operation with keyframe input as the object. PropertyNameArray inputProperties(vm, PropertyNameMode::Strings, PrivateSymbolMode::Exclude); JSObject::getOwnPropertyNames(keyframesInput.get(), &lexicalGlobalObject, inputProperties, EnumerationMode()); // 4. Make up a new list animation properties that consists of all of the properties that are in both input properties and animatable // properties, or which are in input properties and conform to the <custom-property-name> production. Vector<JSC::Identifier> animationProperties; size_t numberOfProperties = inputProperties.size(); for (size_t i = 0; i < numberOfProperties; ++i) { if (CSSPropertyAnimation::isPropertyAnimatable(IDLAttributeNameToAnimationPropertyName(inputProperties[i].string()))) animationProperties.append(inputProperties[i]); } // 5. Sort animation properties in ascending order by the Unicode codepoints that define each property name. std::sort(animationProperties.begin(), animationProperties.end(), [](auto& lhs, auto& rhs) { return lhs.string().utf8() < rhs.string().utf8(); }); // 6. For each property name in animation properties, size_t numberOfAnimationProperties = animationProperties.size(); for (size_t i = 0; i < numberOfAnimationProperties; ++i) { // 1. Let raw value be the result of calling the [[Get]] internal method on keyframe input, with property name as the property // key and keyframe input as the receiver. auto rawValue = keyframesInput->get(&lexicalGlobalObject, animationProperties[i]); // 2. Check the completion record of raw value. RETURN_IF_EXCEPTION(scope, Exception { TypeError }); // 3. Convert raw value to a DOMString or sequence of DOMStrings property values as follows: Vector<String> propertyValues; if (allowLists) { // If allow lists is true, // Let property values be the result of converting raw value to IDL type (DOMString or sequence<DOMString>) // using the procedures defined for converting an ECMAScript value to an IDL value [WEBIDL]. // If property values is a single DOMString, replace property values with a sequence of DOMStrings with the original value of property // Values as the only element. if (rawValue.isObject()) propertyValues = convert<IDLSequence<IDLDOMString>>(lexicalGlobalObject, rawValue); else propertyValues = { rawValue.toWTFString(&lexicalGlobalObject) }; } else { // Otherwise, // Let property values be the result of converting raw value to a DOMString using the procedure for converting an ECMAScript value to a DOMString. propertyValues = { convert<IDLDOMString>(lexicalGlobalObject, rawValue) }; } RETURN_IF_EXCEPTION(scope, Exception { TypeError }); // 4. Calculate the normalized property name as the result of applying the IDL attribute name to animation property name algorithm to property name. auto cssPropertyID = IDLAttributeNameToAnimationPropertyName(animationProperties[i].string()); // 5. Add a property to to keyframe output with normalized property name as the property name, and property values as the property value. keyframeOuput.propertiesAndValues.append({ cssPropertyID, propertyValues }); } // 7. Return keyframe output. return { WTFMove(keyframeOuput) }; } static inline ExceptionOr<void> processIterableKeyframes(JSGlobalObject& lexicalGlobalObject, Strong<JSObject>&& keyframesInput, JSValue method, Vector<KeyframeEffect::ParsedKeyframe>& parsedKeyframes) { // 1. Let iter be GetIterator(object, method). forEachInIterable(lexicalGlobalObject, keyframesInput.get(), method, [&parsedKeyframes](VM& vm, JSGlobalObject& lexicalGlobalObject, JSValue nextValue) -> ExceptionOr<void> { // Steps 2 through 6 are already implemented by forEachInIterable(). auto scope = DECLARE_THROW_SCOPE(vm); if (!nextValue || !nextValue.isObject()) { throwException(&lexicalGlobalObject, scope, JSC::Exception::create(vm, createTypeError(&lexicalGlobalObject))); return { }; } // 7. Append to processed keyframes the result of running the procedure to process a keyframe-like object passing nextItem // as the keyframe input and with the allow lists flag set to false. auto processKeyframeLikeObjectResult = processKeyframeLikeObject(lexicalGlobalObject, Strong<JSObject>(vm, nextValue.toObject(&lexicalGlobalObject)), false); if (processKeyframeLikeObjectResult.hasException()) return processKeyframeLikeObjectResult.releaseException(); auto keyframeLikeObject = processKeyframeLikeObjectResult.returnValue(); KeyframeEffect::ParsedKeyframe keyframeOutput; // When calling processKeyframeLikeObject() with the "allow lists" flag set to false, the only offset // alternatives we should expect are double and nullptr. if (WTF::holds_alternative<double>(keyframeLikeObject.baseProperties.offset)) keyframeOutput.offset = WTF::get<double>(keyframeLikeObject.baseProperties.offset); else ASSERT(WTF::holds_alternative<std::nullptr_t>(keyframeLikeObject.baseProperties.offset)); // When calling processKeyframeLikeObject() with the "allow lists" flag set to false, the only easing // alternative we should expect is String. ASSERT(WTF::holds_alternative<String>(keyframeLikeObject.baseProperties.easing)); keyframeOutput.easing = WTF::get<String>(keyframeLikeObject.baseProperties.easing); // When calling processKeyframeLikeObject() with the "allow lists" flag set to false, the only composite // alternatives we should expect is CompositeOperationAuto. if (RuntimeEnabledFeatures::sharedFeatures().webAnimationsCompositeOperationsEnabled()) { ASSERT(WTF::holds_alternative<CompositeOperationOrAuto>(keyframeLikeObject.baseProperties.composite)); keyframeOutput.composite = WTF::get<CompositeOperationOrAuto>(keyframeLikeObject.baseProperties.composite); } for (auto& propertyAndValue : keyframeLikeObject.propertiesAndValues) { auto cssPropertyId = propertyAndValue.property; // When calling processKeyframeLikeObject() with the "allow lists" flag set to false, // there should only ever be a single value for a given property. ASSERT(propertyAndValue.values.size() == 1); auto stringValue = propertyAndValue.values[0]; if (keyframeOutput.style->setProperty(cssPropertyId, stringValue)) keyframeOutput.unparsedStyle.set(cssPropertyId, stringValue); } parsedKeyframes.append(WTFMove(keyframeOutput)); return { }; }); return { }; } static inline ExceptionOr<void> processPropertyIndexedKeyframes(JSGlobalObject& lexicalGlobalObject, Strong<JSObject>&& keyframesInput, Vector<KeyframeEffect::ParsedKeyframe>& parsedKeyframes, Vector<String>& unusedEasings) { // 1. Let property-indexed keyframe be the result of running the procedure to process a keyframe-like object passing object as the keyframe input. auto processKeyframeLikeObjectResult = processKeyframeLikeObject(lexicalGlobalObject, WTFMove(keyframesInput), true); if (processKeyframeLikeObjectResult.hasException()) return processKeyframeLikeObjectResult.releaseException(); auto propertyIndexedKeyframe = processKeyframeLikeObjectResult.returnValue(); // 2. For each member, m, in property-indexed keyframe, perform the following steps: for (auto& m : propertyIndexedKeyframe.propertiesAndValues) { // 1. Let property name be the key for m. auto propertyName = m.property; // 2. If property name is “composite”, or “easing”, or “offset”, skip the remaining steps in this loop and continue from the next member in property-indexed // keyframe after m. // We skip this test since we split those properties and the actual CSS properties that we're currently iterating over. // 3. Let property values be the value for m. auto propertyValues = m.values; // 4. Let property keyframes be an empty sequence of keyframes. Vector<KeyframeEffect::ParsedKeyframe> propertyKeyframes; // 5. For each value, v, in property values perform the following steps: for (auto& v : propertyValues) { // 1. Let k be a new keyframe with a null keyframe offset. KeyframeEffect::ParsedKeyframe k; // 2. Add the property-value pair, property name → v, to k. if (k.style->setProperty(propertyName, v)) k.unparsedStyle.set(propertyName, v); // 3. Append k to property keyframes. propertyKeyframes.append(WTFMove(k)); } // 6. Apply the procedure to compute missing keyframe offsets to property keyframes. computeMissingKeyframeOffsets(propertyKeyframes); // 7. Add keyframes in property keyframes to processed keyframes. for (auto& keyframe : propertyKeyframes) parsedKeyframes.append(WTFMove(keyframe)); } // 3. Sort processed keyframes by the computed keyframe offset of each keyframe in increasing order. std::sort(parsedKeyframes.begin(), parsedKeyframes.end(), [](auto& lhs, auto& rhs) { return lhs.computedOffset < rhs.computedOffset; }); // 4. Merge adjacent keyframes in processed keyframes when they have equal computed keyframe offsets. size_t i = 1; while (i < parsedKeyframes.size()) { auto& keyframe = parsedKeyframes[i]; auto& previousKeyframe = parsedKeyframes[i - 1]; // If the offsets of this keyframe and the previous keyframe are different, // this means that the two keyframes should not be merged and we can move // on to the next keyframe. if (keyframe.computedOffset != previousKeyframe.computedOffset) { i++; continue; } // Otherwise, both this keyframe and the previous keyframe should be merged. // Unprocessed keyframes in parsedKeyframes at this stage have at most a single // property in cssPropertiesAndValues, so just set this on the previous keyframe. // In case an invalid or null value was originally provided, then the property // was not set and the property count is 0, in which case there is nothing to merge. if (keyframe.style->propertyCount()) { auto property = keyframe.style->propertyAt(0); previousKeyframe.style->setProperty(property.id(), property.value()); previousKeyframe.unparsedStyle.set(property.id(), keyframe.unparsedStyle.get(property.id())); } // Since we've processed this keyframe, we can remove it and keep i the same // so that we process the next keyframe in the next loop iteration. parsedKeyframes.remove(i); } // 5. Let offsets be a sequence of nullable double values assigned based on the type of the “offset” member of the property-indexed keyframe as follows: // - sequence<double?>, the value of “offset” as-is. // - double?, a sequence of length one with the value of “offset” as its single item, i.e. « offset », Vector<Optional<double>> offsets; if (WTF::holds_alternative<Vector<Optional<double>>>(propertyIndexedKeyframe.baseProperties.offset)) offsets = WTF::get<Vector<Optional<double>>>(propertyIndexedKeyframe.baseProperties.offset); else if (WTF::holds_alternative<double>(propertyIndexedKeyframe.baseProperties.offset)) offsets.append(WTF::get<double>(propertyIndexedKeyframe.baseProperties.offset)); else if (WTF::holds_alternative<std::nullptr_t>(propertyIndexedKeyframe.baseProperties.offset)) offsets.append(WTF::nullopt); // 6. Assign each value in offsets to the keyframe offset of the keyframe with corresponding position in property keyframes until the end of either sequence is reached. for (size_t i = 0; i < offsets.size() && i < parsedKeyframes.size(); ++i) parsedKeyframes[i].offset = offsets[i]; // 7. Let easings be a sequence of DOMString values assigned based on the type of the “easing” member of the property-indexed keyframe as follows: // - sequence<DOMString>, the value of “easing” as-is. // - DOMString, a sequence of length one with the value of “easing” as its single item, i.e. « easing », Vector<String> easings; if (WTF::holds_alternative<Vector<String>>(propertyIndexedKeyframe.baseProperties.easing)) easings = WTF::get<Vector<String>>(propertyIndexedKeyframe.baseProperties.easing); else if (WTF::holds_alternative<String>(propertyIndexedKeyframe.baseProperties.easing)) easings.append(WTF::get<String>(propertyIndexedKeyframe.baseProperties.easing)); // 8. If easings is an empty sequence, let it be a sequence of length one containing the single value “linear”, i.e. « "linear" ». if (easings.isEmpty()) easings.append("linear"); // 9. If easings has fewer items than property keyframes, repeat the elements in easings successively starting from the beginning of the list until easings has as many // items as property keyframes. if (easings.size() < parsedKeyframes.size()) { size_t initialNumberOfEasings = easings.size(); for (i = initialNumberOfEasings; i < parsedKeyframes.size(); ++i) easings.append(easings[i % initialNumberOfEasings]); } // 10. If easings has more items than property keyframes, store the excess items as unused easings. while (easings.size() > parsedKeyframes.size()) unusedEasings.append(easings.takeLast()); // 11. Assign each value in easings to a property named “easing” on the keyframe with the corresponding position in property keyframes until the end of property keyframes // is reached. for (size_t i = 0; i < parsedKeyframes.size(); ++i) parsedKeyframes[i].easing = easings[i]; // 12. If the “composite” member of the property-indexed keyframe is not an empty sequence: if (RuntimeEnabledFeatures::sharedFeatures().webAnimationsCompositeOperationsEnabled()) { Vector<CompositeOperationOrAuto> compositeModes; if (WTF::holds_alternative<Vector<CompositeOperationOrAuto>>(propertyIndexedKeyframe.baseProperties.composite)) compositeModes = WTF::get<Vector<CompositeOperationOrAuto>>(propertyIndexedKeyframe.baseProperties.composite); else if (WTF::holds_alternative<CompositeOperationOrAuto>(propertyIndexedKeyframe.baseProperties.composite)) compositeModes.append(WTF::get<CompositeOperationOrAuto>(propertyIndexedKeyframe.baseProperties.composite)); if (!compositeModes.isEmpty()) { // 1. Let composite modes be a sequence of CompositeOperationOrAuto values assigned from the “composite” member of property-indexed keyframe. If that member is a single // CompositeOperationOrAuto value operation, let composite modes be a sequence of length one, with the value of the “composite” as its single item. // 2. As with easings, if composite modes has fewer items than processed keyframes, repeat the elements in composite modes successively starting from the beginning of // the list until composite modes has as many items as processed keyframes. if (compositeModes.size() < parsedKeyframes.size()) { size_t initialNumberOfCompositeModes = compositeModes.size(); for (i = initialNumberOfCompositeModes; i < parsedKeyframes.size(); ++i) compositeModes.append(compositeModes[i % initialNumberOfCompositeModes]); } // 3. Assign each value in composite modes that is not auto to the keyframe-specific composite operation on the keyframe with the corresponding position in processed // keyframes until the end of processed keyframes is reached. for (size_t i = 0; i < compositeModes.size() && i < parsedKeyframes.size(); ++i) { if (compositeModes[i] != CompositeOperationOrAuto::Auto) parsedKeyframes[i].composite = compositeModes[i]; } } } return { }; } ExceptionOr<Ref<KeyframeEffect>> KeyframeEffect::create(JSGlobalObject& lexicalGlobalObject, Element* target, Strong<JSObject>&& keyframes, Optional<Variant<double, KeyframeEffectOptions>>&& options) { auto keyframeEffect = adoptRef(*new KeyframeEffect(target, PseudoId::None)); if (options) { OptionalEffectTiming timing; auto optionsValue = options.value(); if (WTF::holds_alternative<double>(optionsValue)) { Variant<double, String> duration = WTF::get<double>(optionsValue); timing.duration = duration; } else { auto keyframeEffectOptions = WTF::get<KeyframeEffectOptions>(optionsValue); auto setPseudoElementResult = keyframeEffect->setPseudoElement(keyframeEffectOptions.pseudoElement); if (setPseudoElementResult.hasException()) return setPseudoElementResult.releaseException(); timing = { keyframeEffectOptions.duration, keyframeEffectOptions.iterations, keyframeEffectOptions.delay, keyframeEffectOptions.endDelay, keyframeEffectOptions.iterationStart, keyframeEffectOptions.easing, keyframeEffectOptions.fill, keyframeEffectOptions.direction }; } auto updateTimingResult = keyframeEffect->updateTiming(timing); if (updateTimingResult.hasException()) return updateTimingResult.releaseException(); } auto processKeyframesResult = keyframeEffect->processKeyframes(lexicalGlobalObject, WTFMove(keyframes)); if (processKeyframesResult.hasException()) return processKeyframesResult.releaseException(); return keyframeEffect; } ExceptionOr<Ref<KeyframeEffect>> KeyframeEffect::create(JSC::JSGlobalObject&, Ref<KeyframeEffect>&& source) { auto keyframeEffect = adoptRef(*new KeyframeEffect(nullptr, PseudoId::None)); keyframeEffect->copyPropertiesFromSource(WTFMove(source)); return keyframeEffect; } Ref<KeyframeEffect> KeyframeEffect::create(const Element& target, PseudoId pseudoId) { return adoptRef(*new KeyframeEffect(const_cast<Element*>(&target), pseudoId)); } KeyframeEffect::KeyframeEffect(Element* target, PseudoId pseudoId) : m_target(target) , m_pseudoId(pseudoId) { } void KeyframeEffect::copyPropertiesFromSource(Ref<KeyframeEffect>&& source) { m_target = source->m_target; m_pseudoId = source->m_pseudoId; m_compositeOperation = source->m_compositeOperation; m_iterationCompositeOperation = source->m_iterationCompositeOperation; Vector<ParsedKeyframe> parsedKeyframes; for (auto& sourceParsedKeyframe : source->m_parsedKeyframes) { ParsedKeyframe parsedKeyframe; parsedKeyframe.easing = sourceParsedKeyframe.easing; parsedKeyframe.offset = sourceParsedKeyframe.offset; parsedKeyframe.composite = sourceParsedKeyframe.composite; parsedKeyframe.unparsedStyle = sourceParsedKeyframe.unparsedStyle; parsedKeyframe.computedOffset = sourceParsedKeyframe.computedOffset; parsedKeyframe.timingFunction = sourceParsedKeyframe.timingFunction; parsedKeyframe.style = sourceParsedKeyframe.style->mutableCopy(); parsedKeyframes.append(WTFMove(parsedKeyframe)); } m_parsedKeyframes = WTFMove(parsedKeyframes); setFill(source->fill()); setDelay(source->delay()); setEndDelay(source->endDelay()); setDirection(source->direction()); setIterations(source->iterations()); setTimingFunction(source->timingFunction()); setIterationStart(source->iterationStart()); setIterationDuration(source->iterationDuration()); updateStaticTimingProperties(); KeyframeList keyframeList("keyframe-effect-" + createCanonicalUUIDString()); keyframeList.copyKeyframes(source->m_blendingKeyframes); setBlendingKeyframes(keyframeList); } Vector<Strong<JSObject>> KeyframeEffect::getBindingsKeyframes(JSGlobalObject& lexicalGlobalObject) { if (is<DeclarativeAnimation>(animation())) downcast<DeclarativeAnimation>(*animation()).flushPendingStyleChanges(); return getKeyframes(lexicalGlobalObject); } Vector<Strong<JSObject>> KeyframeEffect::getKeyframes(JSGlobalObject& lexicalGlobalObject) { // https://drafts.csswg.org/web-animations-1/#dom-keyframeeffectreadonly-getkeyframes auto lock = JSLockHolder { &lexicalGlobalObject }; // Since keyframes are represented by a partially open-ended dictionary type that is not currently able to be expressed with WebIDL, // the procedure used to prepare the result of this method is defined in prose below: // // 1. Let result be an empty sequence of objects. Vector<Strong<JSObject>> result; // 2. Let keyframes be the result of applying the procedure to compute missing keyframe offsets to the keyframes for this keyframe effect. // 3. For each keyframe in keyframes perform the following steps: if (m_parsedKeyframes.isEmpty() && m_blendingKeyframesSource != BlendingKeyframesSource::WebAnimation) { auto* target = m_target.get(); auto* renderer = this->renderer(); auto computedStyleExtractor = ComputedStyleExtractor(target, false, m_pseudoId); for (size_t i = 0; i < m_blendingKeyframes.size(); ++i) { // 1. Initialize a dictionary object, output keyframe, using the following definition: // // dictionary BaseComputedKeyframe { // double? offset = null; // double computedOffset; // DOMString easing = "linear"; // CompositeOperationOrAuto composite = "auto"; // }; auto& keyframe = m_blendingKeyframes[i]; // 2. Set offset, computedOffset, easing members of output keyframe to the respective values keyframe offset, computed keyframe offset, // and keyframe-specific timing function of keyframe. BaseComputedKeyframe computedKeyframe; computedKeyframe.offset = keyframe.key(); computedKeyframe.computedOffset = keyframe.key(); // For CSS transitions, all keyframes should return "linear" since the effect's global timing function applies. computedKeyframe.easing = is<CSSTransition>(animation()) ? "linear" : timingFunctionForKeyframeAtIndex(i)->cssText(); auto outputKeyframe = convertDictionaryToJS(lexicalGlobalObject, *jsCast<JSDOMGlobalObject*>(&lexicalGlobalObject), computedKeyframe); // 3. For each animation property-value pair specified on keyframe, declaration, perform the following steps: auto& style = *keyframe.style(); for (auto cssPropertyId : keyframe.properties()) { if (cssPropertyId == CSSPropertyCustom) continue; // 1. Let property name be the result of applying the animation property name to IDL attribute name algorithm to the property name of declaration. auto propertyName = CSSPropertyIDToIDLAttributeName(cssPropertyId); // 2. Let IDL value be the result of serializing the property value of declaration by passing declaration to the algorithm to serialize a CSS value. String idlValue = ""; if (auto cssValue = computedStyleExtractor.valueForPropertyInStyle(style, cssPropertyId, renderer)) idlValue = cssValue->cssText(); // 3. Let value be the result of converting IDL value to an ECMAScript String value. auto value = toJS<IDLDOMString>(lexicalGlobalObject, idlValue); // 4. Call the [[DefineOwnProperty]] internal method on output keyframe with property name property name, // Property Descriptor { [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true, [[Value]]: value } and Boolean flag false. JSObject::defineOwnProperty(outputKeyframe, &lexicalGlobalObject, AtomString(propertyName).impl(), PropertyDescriptor(value, 0), false); } // 5. Append output keyframe to result. result.append(JSC::Strong<JSC::JSObject> { lexicalGlobalObject.vm(), outputKeyframe }); } } else { for (size_t i = 0; i < m_parsedKeyframes.size(); ++i) { // 1. Initialize a dictionary object, output keyframe, using the following definition: // // dictionary BaseComputedKeyframe { // double? offset = null; // double computedOffset; // DOMString easing = "linear"; // CompositeOperationOrAuto composite = "auto"; // }; auto& parsedKeyframe = m_parsedKeyframes[i]; // 2. Set offset, computedOffset, easing, composite members of output keyframe to the respective values keyframe offset, computed keyframe // offset, keyframe-specific timing function and keyframe-specific composite operation of keyframe. BaseComputedKeyframe computedKeyframe; computedKeyframe.offset = parsedKeyframe.offset; computedKeyframe.computedOffset = parsedKeyframe.computedOffset; computedKeyframe.easing = timingFunctionForKeyframeAtIndex(i)->cssText(); if (RuntimeEnabledFeatures::sharedFeatures().webAnimationsCompositeOperationsEnabled()) computedKeyframe.composite = parsedKeyframe.composite; auto outputKeyframe = convertDictionaryToJS(lexicalGlobalObject, *jsCast<JSDOMGlobalObject*>(&lexicalGlobalObject), computedKeyframe); // 3. For each animation property-value pair specified on keyframe, declaration, perform the following steps: for (auto it = parsedKeyframe.unparsedStyle.begin(), end = parsedKeyframe.unparsedStyle.end(); it != end; ++it) { // 1. Let property name be the result of applying the animation property name to IDL attribute name algorithm to the property name of declaration. auto propertyName = CSSPropertyIDToIDLAttributeName(it->key); // 2. Let IDL value be the result of serializing the property value of declaration by passing declaration to the algorithm to serialize a CSS value. // 3. Let value be the result of converting IDL value to an ECMAScript String value. auto value = toJS<IDLDOMString>(lexicalGlobalObject, it->value); // 4. Call the [[DefineOwnProperty]] internal method on output keyframe with property name property name, // Property Descriptor { [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true, [[Value]]: value } and Boolean flag false. JSObject::defineOwnProperty(outputKeyframe, &lexicalGlobalObject, AtomString(propertyName).impl(), PropertyDescriptor(value, 0), false); } // 4. Append output keyframe to result. result.append(JSC::Strong<JSC::JSObject> { lexicalGlobalObject.vm(), outputKeyframe }); } } // 4. Return result. return result; } ExceptionOr<void> KeyframeEffect::setBindingsKeyframes(JSGlobalObject& lexicalGlobalObject, Strong<JSObject>&& keyframesInput) { auto retVal = setKeyframes(lexicalGlobalObject, WTFMove(keyframesInput)); if (!retVal.hasException() && is<CSSAnimation>(animation())) downcast<CSSAnimation>(*animation()).effectKeyframesWereSetUsingBindings(); return retVal; } ExceptionOr<void> KeyframeEffect::setKeyframes(JSGlobalObject& lexicalGlobalObject, Strong<JSObject>&& keyframesInput) { auto processKeyframesResult = processKeyframes(lexicalGlobalObject, WTFMove(keyframesInput)); if (!processKeyframesResult.hasException() && animation()) animation()->effectTimingDidChange(); return processKeyframesResult; } ExceptionOr<void> KeyframeEffect::processKeyframes(JSGlobalObject& lexicalGlobalObject, Strong<JSObject>&& keyframesInput) { // 1. If object is null, return an empty sequence of keyframes. if (!keyframesInput.get()) return { }; VM& vm = lexicalGlobalObject.vm(); auto scope = DECLARE_THROW_SCOPE(vm); // 2. Let processed keyframes be an empty sequence of keyframes. Vector<ParsedKeyframe> parsedKeyframes; // 3. Let method be the result of GetMethod(object, @@iterator). auto method = keyframesInput.get()->get(&lexicalGlobalObject, vm.propertyNames->iteratorSymbol); // 4. Check the completion record of method. RETURN_IF_EXCEPTION(scope, Exception { TypeError }); // 5. Perform the steps corresponding to the first matching condition from below, Vector<String> unusedEasings; if (!method.isUndefined()) { auto retVal = processIterableKeyframes(lexicalGlobalObject, WTFMove(keyframesInput), WTFMove(method), parsedKeyframes); if (retVal.hasException()) return retVal.releaseException(); } else { auto retVal = processPropertyIndexedKeyframes(lexicalGlobalObject, WTFMove(keyframesInput), parsedKeyframes, unusedEasings); if (retVal.hasException()) return retVal.releaseException(); } // 6. If processed keyframes is not loosely sorted by offset, throw a TypeError and abort these steps. // 7. If there exist any keyframe in processed keyframes whose keyframe offset is non-null and less than // zero or greater than one, throw a TypeError and abort these steps. double lastNonNullOffset = -1; for (auto& keyframe : parsedKeyframes) { if (!keyframe.offset) continue; auto offset = keyframe.offset.value(); if (offset < lastNonNullOffset || offset < 0 || offset > 1) return Exception { TypeError }; lastNonNullOffset = offset; } // We take a slight detour from the spec text and compute the missing keyframe offsets right away // since they can be computed up-front. computeMissingKeyframeOffsets(parsedKeyframes); // 8. For each frame in processed keyframes, perform the following steps: for (auto& keyframe : parsedKeyframes) { // Let the timing function of frame be the result of parsing the “easing” property on frame using the CSS syntax // defined for the easing property of the AnimationEffectTiming interface. // If parsing the “easing” property fails, throw a TypeError and abort this procedure. auto timingFunctionResult = TimingFunction::createFromCSSText(keyframe.easing); if (timingFunctionResult.hasException()) return timingFunctionResult.releaseException(); keyframe.timingFunction = timingFunctionResult.returnValue(); } // 9. Parse each of the values in unused easings using the CSS syntax defined for easing property of the // AnimationEffectTiming interface, and if any of the values fail to parse, throw a TypeError // and abort this procedure. for (auto& easing : unusedEasings) { auto timingFunctionResult = TimingFunction::createFromCSSText(easing); if (timingFunctionResult.hasException()) return timingFunctionResult.releaseException(); } m_parsedKeyframes = WTFMove(parsedKeyframes); clearBlendingKeyframes(); return { }; } void KeyframeEffect::updateBlendingKeyframes(RenderStyle& elementStyle) { if (!m_blendingKeyframes.isEmpty() || !m_target) return; KeyframeList keyframeList("keyframe-effect-" + createCanonicalUUIDString()); auto& styleResolver = m_target->styleResolver(); for (auto& keyframe : m_parsedKeyframes) { KeyframeValue keyframeValue(keyframe.computedOffset, nullptr); keyframeValue.setTimingFunction(keyframe.timingFunction->clone()); auto styleProperties = keyframe.style->immutableCopyIfNeeded(); for (unsigned i = 0; i < styleProperties->propertyCount(); ++i) keyframeList.addProperty(styleProperties->propertyAt(i).id()); auto keyframeRule = StyleRuleKeyframe::create(WTFMove(styleProperties)); keyframeValue.setStyle(styleResolver.styleForKeyframe(*m_target, &elementStyle, keyframeRule.ptr(), keyframeValue)); keyframeList.insert(WTFMove(keyframeValue)); } setBlendingKeyframes(keyframeList); } bool KeyframeEffect::animatesProperty(CSSPropertyID property) const { if (!m_blendingKeyframes.isEmpty()) return m_blendingKeyframes.properties().contains(property); for (auto& keyframe : m_parsedKeyframes) { for (auto keyframeProperty : keyframe.unparsedStyle.keys()) { if (keyframeProperty == property) return true; } } return false; } bool KeyframeEffect::forceLayoutIfNeeded() { if (!m_needsForcedLayout || !m_target) return false; auto* renderer = this->renderer(); if (!renderer || !renderer->parent()) return false; ASSERT(document()); auto* frameView = document()->view(); if (!frameView) return false; frameView->forceLayout(); return true; } void KeyframeEffect::clearBlendingKeyframes() { m_blendingKeyframesSource = BlendingKeyframesSource::WebAnimation; m_blendingKeyframes.clear(); } void KeyframeEffect::setBlendingKeyframes(KeyframeList& blendingKeyframes) { m_blendingKeyframes = WTFMove(blendingKeyframes); computedNeedsForcedLayout(); computeStackingContextImpact(); computeAcceleratedPropertiesState(); computeSomeKeyframesUseStepsTimingFunction(); checkForMatchingTransformFunctionLists(); checkForMatchingFilterFunctionLists(); #if ENABLE(FILTERS_LEVEL_2) checkForMatchingBackdropFilterFunctionLists(); #endif checkForMatchingColorFilterFunctionLists(); } void KeyframeEffect::checkForMatchingTransformFunctionLists() { m_transformFunctionListsMatch = false; if (m_blendingKeyframes.size() < 2 || !m_blendingKeyframes.containsProperty(CSSPropertyTransform)) return; // Empty transforms match anything, so find the first non-empty entry as the reference. size_t numKeyframes = m_blendingKeyframes.size(); size_t firstNonEmptyTransformKeyframeIndex = numKeyframes; for (size_t i = 0; i < numKeyframes; ++i) { const KeyframeValue& currentKeyframe = m_blendingKeyframes[i]; if (currentKeyframe.style()->transform().operations().size()) { firstNonEmptyTransformKeyframeIndex = i; break; } } if (firstNonEmptyTransformKeyframeIndex == numKeyframes) return; const TransformOperations* firstVal = &m_blendingKeyframes[firstNonEmptyTransformKeyframeIndex].style()->transform(); for (size_t i = firstNonEmptyTransformKeyframeIndex + 1; i < numKeyframes; ++i) { const KeyframeValue& currentKeyframe = m_blendingKeyframes[i]; const TransformOperations* val = &currentKeyframe.style()->transform(); // An empty transform list matches anything. if (val->operations().isEmpty()) continue; if (!firstVal->operationsMatch(*val)) return; } m_transformFunctionListsMatch = true; } bool KeyframeEffect::checkForMatchingFilterFunctionLists(CSSPropertyID propertyID, const std::function<const FilterOperations& (const RenderStyle&)>& filtersGetter) const { if (m_blendingKeyframes.size() < 2 || !m_blendingKeyframes.containsProperty(propertyID)) return false; // Empty filters match anything, so find the first non-empty entry as the reference. size_t numKeyframes = m_blendingKeyframes.size(); size_t firstNonEmptyKeyframeIndex = numKeyframes; for (size_t i = 0; i < numKeyframes; ++i) { if (filtersGetter(*m_blendingKeyframes[i].style()).operations().size()) { firstNonEmptyKeyframeIndex = i; break; } } if (firstNonEmptyKeyframeIndex == numKeyframes) return false; auto& firstVal = filtersGetter(*m_blendingKeyframes[firstNonEmptyKeyframeIndex].style()); for (size_t i = firstNonEmptyKeyframeIndex + 1; i < numKeyframes; ++i) { auto& value = filtersGetter(*m_blendingKeyframes[i].style()); // An empty filter list matches anything. if (value.operations().isEmpty()) continue; if (!firstVal.operationsMatch(value)) return false; } return true; } void KeyframeEffect::checkForMatchingFilterFunctionLists() { m_filterFunctionListsMatch = checkForMatchingFilterFunctionLists(CSSPropertyFilter, [] (const RenderStyle& style) -> const FilterOperations& { return style.filter(); }); } #if ENABLE(FILTERS_LEVEL_2) void KeyframeEffect::checkForMatchingBackdropFilterFunctionLists() { m_backdropFilterFunctionListsMatch = checkForMatchingFilterFunctionLists(CSSPropertyWebkitBackdropFilter, [] (const RenderStyle& style) -> const FilterOperations& { return style.backdropFilter(); }); } #endif void KeyframeEffect::checkForMatchingColorFilterFunctionLists() { m_colorFilterFunctionListsMatch = checkForMatchingFilterFunctionLists(CSSPropertyAppleColorFilter, [] (const RenderStyle& style) -> const FilterOperations& { return style.appleColorFilter(); }); } void KeyframeEffect::computeDeclarativeAnimationBlendingKeyframes(const RenderStyle* oldStyle, const RenderStyle& newStyle) { ASSERT(is<DeclarativeAnimation>(animation())); if (is<CSSAnimation>(animation())) computeCSSAnimationBlendingKeyframes(newStyle); else if (is<CSSTransition>(animation())) computeCSSTransitionBlendingKeyframes(oldStyle, newStyle); } void KeyframeEffect::computeCSSAnimationBlendingKeyframes(const RenderStyle& unanimatedStyle) { ASSERT(is<CSSAnimation>(animation())); ASSERT(document()); auto cssAnimation = downcast<CSSAnimation>(animation()); auto& backingAnimation = cssAnimation->backingAnimation(); KeyframeList keyframeList(backingAnimation.name()); if (auto* styleScope = Style::Scope::forOrdinal(*m_target, backingAnimation.nameStyleScopeOrdinal())) styleScope->resolver().keyframeStylesForAnimation(*m_target, &unanimatedStyle, keyframeList); // Ensure resource loads for all the frames. for (auto& keyframe : keyframeList.keyframes()) { if (auto* style = const_cast<RenderStyle*>(keyframe.style())) Style::loadPendingResources(*style, *document(), m_target.get()); } m_blendingKeyframesSource = BlendingKeyframesSource::CSSAnimation; setBlendingKeyframes(keyframeList); } void KeyframeEffect::computeCSSTransitionBlendingKeyframes(const RenderStyle* oldStyle, const RenderStyle& newStyle) { ASSERT(is<CSSTransition>(animation())); ASSERT(document()); if (!oldStyle || m_blendingKeyframes.size()) return; auto property = downcast<CSSTransition>(animation())->property(); auto toStyle = RenderStyle::clonePtr(newStyle); if (m_target) Style::loadPendingResources(*toStyle, *document(), m_target.get()); KeyframeList keyframeList("keyframe-effect-" + createCanonicalUUIDString()); keyframeList.addProperty(property); KeyframeValue fromKeyframeValue(0, RenderStyle::clonePtr(*oldStyle)); fromKeyframeValue.addProperty(property); keyframeList.insert(WTFMove(fromKeyframeValue)); KeyframeValue toKeyframeValue(1, WTFMove(toStyle)); toKeyframeValue.addProperty(property); keyframeList.insert(WTFMove(toKeyframeValue)); m_blendingKeyframesSource = BlendingKeyframesSource::CSSTransition; setBlendingKeyframes(keyframeList); } void KeyframeEffect::computedNeedsForcedLayout() { m_needsForcedLayout = false; if (is<CSSTransition>(animation()) || !m_blendingKeyframes.containsProperty(CSSPropertyTransform)) return; size_t numberOfKeyframes = m_blendingKeyframes.size(); for (size_t i = 0; i < numberOfKeyframes; i++) { auto* keyframeStyle = m_blendingKeyframes[i].style(); if (!keyframeStyle) { ASSERT_NOT_REACHED(); continue; } if (keyframeStyle->hasTransform()) { auto& transformOperations = keyframeStyle->transform(); for (const auto& operation : transformOperations.operations()) { if (operation->isTranslateTransformOperationType()) { auto translation = downcast<TranslateTransformOperation>(operation.get()); if (translation->x().isPercent() || translation->y().isPercent()) { m_needsForcedLayout = true; return; } } } } } } void KeyframeEffect::computeStackingContextImpact() { m_triggersStackingContext = false; for (auto cssPropertyId : m_blendingKeyframes.properties()) { if (WillChangeData::propertyCreatesStackingContext(cssPropertyId)) { m_triggersStackingContext = true; break; } } } void KeyframeEffect::animationTimelineDidChange(AnimationTimeline* timeline) { if (!targetElementOrPseudoElement()) return; if (timeline) m_inTargetEffectStack = targetElementOrPseudoElement()->ensureKeyframeEffectStack().addEffect(*this); else { targetElementOrPseudoElement()->ensureKeyframeEffectStack().removeEffect(*this); m_inTargetEffectStack = false; } } void KeyframeEffect::animationTimingDidChange() { updateEffectStackMembership(); } void KeyframeEffect::updateEffectStackMembership() { if (!targetElementOrPseudoElement()) return; bool isRelevant = animation() && animation()->isRelevant(); if (isRelevant && !m_inTargetEffectStack) m_inTargetEffectStack = targetElementOrPseudoElement()->ensureKeyframeEffectStack().addEffect(*this); else if (!isRelevant && m_inTargetEffectStack) { targetElementOrPseudoElement()->ensureKeyframeEffectStack().removeEffect(*this); m_inTargetEffectStack = false; } } void KeyframeEffect::setAnimation(WebAnimation* animation) { bool animationChanged = animation != this->animation(); AnimationEffect::setAnimation(animation); if (!animationChanged) return; if (animation) animation->updateRelevance(); updateEffectStackMembership(); } bool KeyframeEffect::targetsPseudoElement() const { return m_target.get() && m_pseudoId != PseudoId::None; } Element* KeyframeEffect::targetElementOrPseudoElement() const { if (!targetsPseudoElement()) return m_target.get(); if (m_pseudoId == PseudoId::Before) return m_target->beforePseudoElement(); if (m_pseudoId == PseudoId::After) return m_target->afterPseudoElement(); // We only support targeting ::before and ::after pseudo-elements at the moment. return nullptr; } void KeyframeEffect::setTarget(RefPtr<Element>&& newTarget) { if (m_target == newTarget) return; auto* previousTargetElementOrPseudoElement = targetElementOrPseudoElement(); m_target = WTFMove(newTarget); didChangeTargetElementOrPseudoElement(previousTargetElementOrPseudoElement); } const String KeyframeEffect::pseudoElement() const { // https://drafts.csswg.org/web-animations/#dom-keyframeeffect-pseudoelement // The target pseudo-selector. null if this effect has no effect target or if the effect target is an element (i.e. not a pseudo-element). // When the effect target is a pseudo-element, this specifies the pseudo-element selector (e.g. ::before). if (targetsPseudoElement()) return PseudoElement::pseudoElementNameForEvents(m_pseudoId); return { }; } ExceptionOr<void> KeyframeEffect::setPseudoElement(const String& pseudoElement) { // https://drafts.csswg.org/web-animations/#dom-keyframeeffect-pseudoelement // On setting, sets the target pseudo-selector of the animation effect to the provided value after applying the following exceptions: // // - If the provided value is not null and is an invalid <pseudo-element-selector>, the user agent must throw a DOMException with error // name SyntaxError and leave the target pseudo-selector of this animation effect unchanged. Note, that invalid in this context follows // the definition of an invalid selector defined in [SELECTORS-4] such that syntactically invalid pseudo-elements as well as pseudo-elements // for which the user agent has no usable level of support are both deemed invalid. // - If one of the legacy Selectors Level 2 single-colon selectors (':before', ':after', ':first-letter', or ':first-line') is specified, // the target pseudo-selector must be set to the equivalent two-colon selector (e.g. '::before'). auto pseudoId = PseudoId::None; if (!pseudoElement.isNull()) { auto isLegacy = pseudoElement == ":before" || pseudoElement == ":after" || pseudoElement == ":first-letter" || pseudoElement == ":first-line"; if (!isLegacy && !pseudoElement.startsWith("::")) return Exception { SyntaxError }; auto pseudoType = CSSSelector::parsePseudoElementType(pseudoElement.substring(isLegacy ? 1 : 2)); if (pseudoType == CSSSelector::PseudoElementUnknown) return Exception { SyntaxError }; pseudoId = CSSSelector::pseudoId(pseudoType); } if (pseudoId == m_pseudoId) return { }; auto* previousTargetElementOrPseudoElement = targetElementOrPseudoElement(); m_pseudoId = pseudoId; didChangeTargetElementOrPseudoElement(previousTargetElementOrPseudoElement); return { }; } void KeyframeEffect::didChangeTargetElementOrPseudoElement(Element* previousTargetElementOrPseudoElement) { auto* newTargetElementOrPseudoElement = targetElementOrPseudoElement(); // We must ensure a PseudoElement exists for this m_target / m_pseudoId pair if both are specified. if (!newTargetElementOrPseudoElement && m_target.get() && m_pseudoId != PseudoId::None) { // We only support targeting ::before and ::after pseudo-elements at the moment. if (m_pseudoId == PseudoId::Before || m_pseudoId == PseudoId::After) newTargetElementOrPseudoElement = &m_target->ensurePseudoElement(m_pseudoId); } if (auto* effectAnimation = animation()) effectAnimation->effectTargetDidChange(previousTargetElementOrPseudoElement, newTargetElementOrPseudoElement); clearBlendingKeyframes(); // We need to invalidate the effect now that the target has changed // to ensure the effect's styles are applied to the new target right away. invalidate(); // Likewise, we need to invalidate styles on the previous target so that // any animated styles are removed immediately. invalidateElement(previousTargetElementOrPseudoElement); if (previousTargetElementOrPseudoElement) { previousTargetElementOrPseudoElement->ensureKeyframeEffectStack().removeEffect(*this); m_inTargetEffectStack = false; } if (newTargetElementOrPseudoElement) m_inTargetEffectStack = newTargetElementOrPseudoElement->ensureKeyframeEffectStack().addEffect(*this); } void KeyframeEffect::apply(RenderStyle& targetStyle, Optional<Seconds> startTime) { if (!m_target) return; updateBlendingKeyframes(targetStyle); auto computedTiming = getComputedTiming(startTime); if (!startTime) { m_phaseAtLastApplication = computedTiming.phase; InspectorInstrumentation::willApplyKeyframeEffect(*targetElementOrPseudoElement(), *this, computedTiming); } if (!computedTiming.progress) return; setAnimatedPropertiesInStyle(targetStyle, computedTiming.progress.value()); } bool KeyframeEffect::isCurrentlyAffectingProperty(CSSPropertyID property, Accelerated accelerated) const { if (accelerated == Accelerated::Yes && !isRunningAccelerated() && !isAboutToRunAccelerated()) return false; if (!m_blendingKeyframes.properties().contains(property)) return false; return m_phaseAtLastApplication == AnimationEffectPhase::Active; } bool KeyframeEffect::isRunningAcceleratedAnimationForProperty(CSSPropertyID property) const { return isRunningAccelerated() && CSSPropertyAnimation::animationOfPropertyIsAccelerated(property) && m_blendingKeyframes.properties().contains(property); } void KeyframeEffect::invalidate() { LOG_WITH_STREAM(Animations, stream << "KeyframeEffect::invalidate on element " << ValueOrNull(targetElementOrPseudoElement())); invalidateElement(targetElementOrPseudoElement()); } void KeyframeEffect::computeAcceleratedPropertiesState() { bool hasSomeAcceleratedProperties = false; bool hasSomeUnacceleratedProperties = false; for (auto cssPropertyId : m_blendingKeyframes.properties()) { // If any animated property can be accelerated, then the animation should run accelerated. if (CSSPropertyAnimation::animationOfPropertyIsAccelerated(cssPropertyId)) hasSomeAcceleratedProperties = true; else hasSomeUnacceleratedProperties = true; if (hasSomeAcceleratedProperties && hasSomeUnacceleratedProperties) break; } if (!hasSomeAcceleratedProperties) m_acceleratedPropertiesState = AcceleratedProperties::None; else if (hasSomeUnacceleratedProperties) m_acceleratedPropertiesState = AcceleratedProperties::Some; else m_acceleratedPropertiesState = AcceleratedProperties::All; } void KeyframeEffect::computeSomeKeyframesUseStepsTimingFunction() { m_someKeyframesUseStepsTimingFunction = false; size_t numberOfKeyframes = m_blendingKeyframes.size(); // If we're dealing with a CSS Animation and it specifies a default steps() timing function, // we need to check that any of the specified keyframes either does not have an explicit timing // function or specifies an explicit steps() timing function. if (is<CSSAnimation>(animation()) && is<StepsTimingFunction>(downcast<DeclarativeAnimation>(*animation()).backingAnimation().timingFunction())) { for (size_t i = 0; i < numberOfKeyframes; i++) { auto* timingFunction = m_blendingKeyframes[i].timingFunction(); if (!timingFunction || is<StepsTimingFunction>(timingFunction)) { m_someKeyframesUseStepsTimingFunction = true; return; } } return; } // For any other type of animation, we just need to check whether any of the keyframes specify // an explicit steps() timing function. for (size_t i = 0; i < numberOfKeyframes; i++) { if (is<StepsTimingFunction>(m_blendingKeyframes[i].timingFunction())) { m_someKeyframesUseStepsTimingFunction = true; return; } } } void KeyframeEffect::getAnimatedStyle(std::unique_ptr<RenderStyle>& animatedStyle) { if (!renderer() || !animation()) return; auto progress = getComputedTiming().progress; LOG_WITH_STREAM(Animations, stream << "KeyframeEffect " << this << " getAnimatedStyle - progress " << progress); if (!progress) return; if (!animatedStyle) animatedStyle = RenderStyle::clonePtr(renderer()->style()); setAnimatedPropertiesInStyle(*animatedStyle.get(), progress.value()); } void KeyframeEffect::setAnimatedPropertiesInStyle(RenderStyle& targetStyle, double iterationProgress) { auto& properties = m_blendingKeyframes.properties(); // In the case of CSS Transitions we already know that there are only two keyframes, one where offset=0 and one where offset=1, // and only a single CSS property so we can simply blend based on the style available on those keyframes with the provided iteration // progress which already accounts for the transition's timing function. if (m_blendingKeyframesSource == BlendingKeyframesSource::CSSTransition) { ASSERT(properties.size() == 1); CSSPropertyAnimation::blendProperties(this, *properties.begin(), &targetStyle, m_blendingKeyframes[0].style(), m_blendingKeyframes[1].style(), iterationProgress); return; } // 4.4.3. The effect value of a keyframe effect // https://drafts.csswg.org/web-animations-1/#the-effect-value-of-a-keyframe-animation-effect // // The effect value of a single property referenced by a keyframe effect as one of its target properties, // for a given iteration progress, current iteration and underlying value is calculated as follows. updateBlendingKeyframes(targetStyle); if (m_blendingKeyframes.isEmpty()) return; for (auto cssPropertyId : properties) { // 1. If iteration progress is unresolved abort this procedure. // 2. Let target property be the longhand property for which the effect value is to be calculated. // 3. If animation type of the target property is not animatable abort this procedure since the effect cannot be applied. // 4. Define the neutral value for composition as a value which, when combined with an underlying value using the add composite operation, // produces the underlying value. // 5. Let property-specific keyframes be the result of getting the set of computed keyframes for this keyframe effect. // 6. Remove any keyframes from property-specific keyframes that do not have a property value for target property. unsigned numberOfKeyframesWithZeroOffset = 0; unsigned numberOfKeyframesWithOneOffset = 0; Vector<Optional<size_t>> propertySpecificKeyframes; for (size_t i = 0; i < m_blendingKeyframes.size(); ++i) { auto& keyframe = m_blendingKeyframes[i]; auto offset = keyframe.key(); if (!keyframe.containsProperty(cssPropertyId)) { // If we're dealing with a CSS animation, we consider the first and last keyframes to always have the property listed // since the underlying style was provided and should be captured. if (m_blendingKeyframesSource == BlendingKeyframesSource::WebAnimation || (offset && offset < 1)) continue; } if (!offset) numberOfKeyframesWithZeroOffset++; if (offset == 1) numberOfKeyframesWithOneOffset++; propertySpecificKeyframes.append(i); } // 7. If property-specific keyframes is empty, return underlying value. if (propertySpecificKeyframes.isEmpty()) continue; // 8. If there is no keyframe in property-specific keyframes with a computed keyframe offset of 0, create a new keyframe with a computed keyframe // offset of 0, a property value set to the neutral value for composition, and a composite operation of add, and prepend it to the beginning of // property-specific keyframes. if (!numberOfKeyframesWithZeroOffset) { propertySpecificKeyframes.insert(0, WTF::nullopt); numberOfKeyframesWithZeroOffset = 1; } // 9. Similarly, if there is no keyframe in property-specific keyframes with a computed keyframe offset of 1, create a new keyframe with a computed // keyframe offset of 1, a property value set to the neutral value for composition, and a composite operation of add, and append it to the end of // property-specific keyframes. if (!numberOfKeyframesWithOneOffset) { propertySpecificKeyframes.append(WTF::nullopt); numberOfKeyframesWithOneOffset = 1; } // 10. Let interval endpoints be an empty sequence of keyframes. Vector<Optional<size_t>> intervalEndpoints; // 11. Populate interval endpoints by following the steps from the first matching condition from below: if (iterationProgress < 0 && numberOfKeyframesWithZeroOffset > 1) { // If iteration progress < 0 and there is more than one keyframe in property-specific keyframes with a computed keyframe offset of 0, // Add the first keyframe in property-specific keyframes to interval endpoints. intervalEndpoints.append(propertySpecificKeyframes.first()); } else if (iterationProgress >= 1 && numberOfKeyframesWithOneOffset > 1) { // If iteration progress ≥ 1 and there is more than one keyframe in property-specific keyframes with a computed keyframe offset of 1, // Add the last keyframe in property-specific keyframes to interval endpoints. intervalEndpoints.append(propertySpecificKeyframes.last()); } else { // Otherwise, // 1. Append to interval endpoints the last keyframe in property-specific keyframes whose computed keyframe offset is less than or equal // to iteration progress and less than 1. If there is no such keyframe (because, for example, the iteration progress is negative), // add the last keyframe whose computed keyframe offset is 0. // 2. Append to interval endpoints the next keyframe in property-specific keyframes after the one added in the previous step. size_t indexOfLastKeyframeWithZeroOffset = 0; int indexOfFirstKeyframeToAddToIntervalEndpoints = -1; for (size_t i = 0; i < propertySpecificKeyframes.size(); ++i) { auto keyframeIndex = propertySpecificKeyframes[i]; auto offset = [&] () -> double { if (!keyframeIndex) return i ? 1 : 0; return m_blendingKeyframes[keyframeIndex.value()].key(); }(); if (!offset) indexOfLastKeyframeWithZeroOffset = i; if (offset <= iterationProgress && offset < 1) indexOfFirstKeyframeToAddToIntervalEndpoints = i; else break; } if (indexOfFirstKeyframeToAddToIntervalEndpoints >= 0) { intervalEndpoints.append(propertySpecificKeyframes[indexOfFirstKeyframeToAddToIntervalEndpoints]); intervalEndpoints.append(propertySpecificKeyframes[indexOfFirstKeyframeToAddToIntervalEndpoints + 1]); } else { ASSERT(indexOfLastKeyframeWithZeroOffset < propertySpecificKeyframes.size() - 1); intervalEndpoints.append(propertySpecificKeyframes[indexOfLastKeyframeWithZeroOffset]); intervalEndpoints.append(propertySpecificKeyframes[indexOfLastKeyframeWithZeroOffset + 1]); } } // 12. For each keyframe in interval endpoints… // FIXME: we don't support this step yet since we don't deal with any composite operation other than "replace". // 13. If there is only one keyframe in interval endpoints return the property value of target property on that keyframe. if (intervalEndpoints.size() == 1) { auto keyframeIndex = intervalEndpoints[0]; auto keyframeStyle = !keyframeIndex ? &targetStyle : m_blendingKeyframes[keyframeIndex.value()].style(); CSSPropertyAnimation::blendProperties(this, cssPropertyId, &targetStyle, keyframeStyle, keyframeStyle, 0); continue; } // 14. Let start offset be the computed keyframe offset of the first keyframe in interval endpoints. auto startKeyframeIndex = intervalEndpoints.first(); auto startOffset = !startKeyframeIndex ? 0 : m_blendingKeyframes[startKeyframeIndex.value()].key(); // 15. Let end offset be the computed keyframe offset of last keyframe in interval endpoints. auto endKeyframeIndex = intervalEndpoints.last(); auto endOffset = !endKeyframeIndex ? 1 : m_blendingKeyframes[endKeyframeIndex.value()].key(); // 16. Let interval distance be the result of evaluating (iteration progress - start offset) / (end offset - start offset). auto intervalDistance = (iterationProgress - startOffset) / (endOffset - startOffset); // 17. Let transformed distance be the result of evaluating the timing function associated with the first keyframe in interval endpoints // passing interval distance as the input progress. auto transformedDistance = intervalDistance; if (startKeyframeIndex) { if (auto duration = iterationDuration()) { auto rangeDuration = (endOffset - startOffset) * duration.seconds(); if (auto* timingFunction = timingFunctionForKeyframeAtIndex(startKeyframeIndex.value())) transformedDistance = timingFunction->transformTime(intervalDistance, rangeDuration); } } // 18. Return the result of applying the interpolation procedure defined by the animation type of the target property, to the values of the target // property specified on the two keyframes in interval endpoints taking the first such value as Vstart and the second as Vend and using transformed // distance as the interpolation parameter p. auto startStyle = !startKeyframeIndex ? &targetStyle : m_blendingKeyframes[startKeyframeIndex.value()].style(); auto endStyle = !endKeyframeIndex ? &targetStyle : m_blendingKeyframes[endKeyframeIndex.value()].style(); CSSPropertyAnimation::blendProperties(this, cssPropertyId, &targetStyle, startStyle, endStyle, transformedDistance); } } TimingFunction* KeyframeEffect::timingFunctionForKeyframeAtIndex(size_t index) const { if (!m_parsedKeyframes.isEmpty()) { if (index >= m_parsedKeyframes.size()) return nullptr; return m_parsedKeyframes[index].timingFunction.get(); } auto effectAnimation = animation(); if (is<DeclarativeAnimation>(effectAnimation)) { // If we're dealing with a CSS Animation, the timing function is specified either on the keyframe itself. if (is<CSSAnimation>(effectAnimation)) { if (index >= m_blendingKeyframes.size()) return nullptr; if (auto* timingFunction = m_blendingKeyframes[index].timingFunction()) return timingFunction; } // Failing that, or for a CSS Transition, the timing function is inherited from the backing Animation object. return downcast<DeclarativeAnimation>(effectAnimation)->backingAnimation().timingFunction(); } return nullptr; } void KeyframeEffect::updateAcceleratedActions() { if (m_acceleratedPropertiesState == AcceleratedProperties::None) return; auto computedTiming = getComputedTiming(); // If we're not already running accelerated, the only thing we're interested in is whether we need to start the animation // which we need to do once we're in the active phase. Otherwise, there's no change in accelerated state to consider. bool isActive = computedTiming.phase == AnimationEffectPhase::Active; if (m_runningAccelerated == RunningAccelerated::NotStarted) { if (isActive && animation()->playState() == WebAnimation::PlayState::Running) addPendingAcceleratedAction(AcceleratedAction::Play); return; } // If we're no longer active, we need to remove the accelerated animation. if (!isActive) { addPendingAcceleratedAction(AcceleratedAction::Stop); return; } auto playState = animation()->playState(); // The only thing left to consider is whether we need to pause or resume the animation following a change of play-state. if (playState == WebAnimation::PlayState::Paused) { if (m_lastRecordedAcceleratedAction != AcceleratedAction::Pause) { if (m_lastRecordedAcceleratedAction == AcceleratedAction::Stop) addPendingAcceleratedAction(AcceleratedAction::Play); addPendingAcceleratedAction(AcceleratedAction::Pause); } } else if (playState == WebAnimation::PlayState::Running && isActive) { if (m_lastRecordedAcceleratedAction != AcceleratedAction::Play) addPendingAcceleratedAction(AcceleratedAction::Play); } } void KeyframeEffect::addPendingAcceleratedAction(AcceleratedAction action) { if (action == m_lastRecordedAcceleratedAction) return; if (action == AcceleratedAction::Stop) m_pendingAcceleratedActions.clear(); m_pendingAcceleratedActions.append(action); if (action != AcceleratedAction::UpdateTiming) m_lastRecordedAcceleratedAction = action; animation()->acceleratedStateDidChange(); } void KeyframeEffect::animationDidTick() { invalidate(); updateAcceleratedActions(); } void KeyframeEffect::animationDidPlay() { if (m_acceleratedPropertiesState != AcceleratedProperties::None) addPendingAcceleratedAction(AcceleratedAction::Play); } void KeyframeEffect::animationDidChangeTimingProperties() { computeSomeKeyframesUseStepsTimingFunction(); // The timing function can affect whether the platform can run this as an accelerated animation. m_runningAccelerated = RunningAccelerated::NotStarted; // There is no need to update the animation if we're not playing already. If updating timing // means we're moving into an active lexicalGlobalObject, we'll pick this up in apply(). if (isAboutToRunAccelerated()) addPendingAcceleratedAction(AcceleratedAction::UpdateTiming); } void KeyframeEffect::animationWasCanceled() { if (isRunningAccelerated() || isAboutToRunAccelerated()) addPendingAcceleratedAction(AcceleratedAction::Stop); } void KeyframeEffect::willChangeRenderer() { if (isRunningAccelerated() || isAboutToRunAccelerated()) addPendingAcceleratedAction(AcceleratedAction::Stop); } void KeyframeEffect::animationSuspensionStateDidChange(bool animationIsSuspended) { if (isRunningAccelerated() || isAboutToRunAccelerated()) addPendingAcceleratedAction(animationIsSuspended ? AcceleratedAction::Pause : AcceleratedAction::Play); } void KeyframeEffect::applyPendingAcceleratedActions() { // Once an accelerated animation has been committed, we no longer want to force a layout. // This should have been performed by a call to forceLayoutIfNeeded() prior to applying // pending accelerated actions. m_needsForcedLayout = false; if (m_pendingAcceleratedActions.isEmpty()) return; auto* renderer = this->renderer(); if (!renderer || !renderer->isComposited()) { // The renderer may no longer be composited because the accelerated animation ended before we had a chance to update it, // in which case if we asked for the animation to stop, we can discard the current set of accelerated actions. if (m_lastRecordedAcceleratedAction == AcceleratedAction::Stop) { m_pendingAcceleratedActions.clear(); m_runningAccelerated = RunningAccelerated::NotStarted; } return; } auto pendingAcceleratedActions = m_pendingAcceleratedActions; m_pendingAcceleratedActions.clear(); // To simplify the code we use a default of 0s for an unresolved current time since for a Stop action that is acceptable. auto timeOffset = animation()->currentTime().valueOr(0_s).seconds() - delay().seconds(); auto startAnimation = [&]() -> RunningAccelerated { if (m_runningAccelerated == RunningAccelerated::Yes) renderer->animationFinished(m_blendingKeyframes.animationName()); if (!m_blendingKeyframes.hasImplicitKeyframes()) return renderer->startAnimation(timeOffset, backingAnimationForCompositedRenderer(), m_blendingKeyframes) ? RunningAccelerated::Yes : RunningAccelerated::No; ASSERT(m_target); auto* lastStyleChangeEventStyle = m_target->lastStyleChangeEventStyle(); ASSERT(lastStyleChangeEventStyle); KeyframeList explicitKeyframes(m_blendingKeyframes.animationName()); explicitKeyframes.copyKeyframes(m_blendingKeyframes); explicitKeyframes.fillImplicitKeyframes(*m_target, m_target->styleResolver(), lastStyleChangeEventStyle); return renderer->startAnimation(timeOffset, backingAnimationForCompositedRenderer(), explicitKeyframes) ? RunningAccelerated::Yes : RunningAccelerated::No; }; for (const auto& action : pendingAcceleratedActions) { switch (action) { case AcceleratedAction::Play: m_runningAccelerated = startAnimation(); LOG_WITH_STREAM(Animations, stream << "KeyframeEffect " << this << " applyPendingAcceleratedActions " << m_blendingKeyframes.animationName() << " Play, started accelerated: " << (m_runningAccelerated == RunningAccelerated::Yes)); if (m_runningAccelerated == RunningAccelerated::No) { m_lastRecordedAcceleratedAction = AcceleratedAction::Stop; return; } break; case AcceleratedAction::Pause: renderer->animationPaused(timeOffset, m_blendingKeyframes.animationName()); break; case AcceleratedAction::UpdateTiming: m_runningAccelerated = startAnimation(); LOG_WITH_STREAM(Animations, stream << "KeyframeEffect " << this << " applyPendingAcceleratedActions " << m_blendingKeyframes.animationName() << " UpdateTiming, started accelerated: " << (m_runningAccelerated == RunningAccelerated::Yes)); if (animation()->playState() == WebAnimation::PlayState::Paused) renderer->animationPaused(timeOffset, m_blendingKeyframes.animationName()); break; case AcceleratedAction::Stop: ASSERT(document()); renderer->animationFinished(m_blendingKeyframes.animationName()); if (!document()->renderTreeBeingDestroyed()) m_target->invalidateStyleAndLayerComposition(); m_runningAccelerated = RunningAccelerated::NotStarted; break; } } } Ref<const Animation> KeyframeEffect::backingAnimationForCompositedRenderer() const { auto effectAnimation = animation(); if (is<DeclarativeAnimation>(effectAnimation)) return downcast<DeclarativeAnimation>(effectAnimation)->backingAnimation(); // FIXME: The iterationStart and endDelay AnimationEffectTiming properties do not have // corresponding Animation properties. auto animation = Animation::create(); animation->setDuration(iterationDuration().seconds()); animation->setDelay(delay().seconds()); animation->setIterationCount(iterations()); animation->setTimingFunction(timingFunction()->clone()); animation->setPlaybackRate(effectAnimation->playbackRate()); switch (fill()) { case FillMode::None: case FillMode::Auto: animation->setFillMode(AnimationFillMode::None); break; case FillMode::Backwards: animation->setFillMode(AnimationFillMode::Backwards); break; case FillMode::Forwards: animation->setFillMode(AnimationFillMode::Forwards); break; case FillMode::Both: animation->setFillMode(AnimationFillMode::Both); break; } switch (direction()) { case PlaybackDirection::Normal: animation->setDirection(Animation::AnimationDirectionNormal); break; case PlaybackDirection::Alternate: animation->setDirection(Animation::AnimationDirectionAlternate); break; case PlaybackDirection::Reverse: animation->setDirection(Animation::AnimationDirectionReverse); break; case PlaybackDirection::AlternateReverse: animation->setDirection(Animation::AnimationDirectionAlternateReverse); break; } return animation; } Document* KeyframeEffect::document() const { return m_target ? &m_target->document() : nullptr; } RenderElement* KeyframeEffect::renderer() const { return targetElementOrPseudoElement() ? targetElementOrPseudoElement()->renderer() : nullptr; } const RenderStyle& KeyframeEffect::currentStyle() const { if (auto* renderer = this->renderer()) return renderer->style(); return RenderStyle::defaultStyle(); } bool KeyframeEffect::computeExtentOfTransformAnimation(LayoutRect& bounds) const { ASSERT(m_blendingKeyframes.containsProperty(CSSPropertyTransform)); if (!is<RenderBox>(renderer())) return true; // Non-boxes don't get transformed; auto& box = downcast<RenderBox>(*renderer()); auto rendererBox = snapRectToDevicePixels(box.borderBoxRect(), box.document().deviceScaleFactor()); LayoutRect cumulativeBounds; for (const auto& keyframe : m_blendingKeyframes.keyframes()) { const auto* keyframeStyle = keyframe.style(); // FIXME: maybe for declarative animations we always say it's true for the first and last keyframe. if (!keyframe.containsProperty(CSSPropertyTransform)) { // If the first keyframe is missing transform style, use the current style. if (!keyframe.key()) keyframeStyle = &box.style(); else continue; } auto keyframeBounds = bounds; bool canCompute; if (transformFunctionListsMatch()) canCompute = computeTransformedExtentViaTransformList(rendererBox, *keyframeStyle, keyframeBounds); else canCompute = computeTransformedExtentViaMatrix(rendererBox, *keyframeStyle, keyframeBounds); if (!canCompute) return false; cumulativeBounds.unite(keyframeBounds); } bounds = cumulativeBounds; return true; } static bool containsRotation(const Vector<RefPtr<TransformOperation>>& operations) { for (const auto& operation : operations) { if (operation->type() == TransformOperation::ROTATE) return true; } return false; } bool KeyframeEffect::computeTransformedExtentViaTransformList(const FloatRect& rendererBox, const RenderStyle& style, LayoutRect& bounds) const { FloatRect floatBounds = bounds; FloatPoint transformOrigin; bool applyTransformOrigin = containsRotation(style.transform().operations()) || style.transform().affectedByTransformOrigin(); if (applyTransformOrigin) { transformOrigin = rendererBox.location() + floatPointForLengthPoint(style.transformOriginXY(), rendererBox.size()); // Ignore transformOriginZ because we'll bail if we encounter any 3D transforms. floatBounds.moveBy(-transformOrigin); } for (const auto& operation : style.transform().operations()) { if (operation->type() == TransformOperation::ROTATE) { // For now, just treat this as a full rotation. This could take angle into account to reduce inflation. floatBounds = boundsOfRotatingRect(floatBounds); } else { TransformationMatrix transform; operation->apply(transform, rendererBox.size()); if (!transform.isAffine()) return false; if (operation->type() == TransformOperation::MATRIX || operation->type() == TransformOperation::MATRIX_3D) { TransformationMatrix::Decomposed2Type toDecomp; transform.decompose2(toDecomp); // Any rotation prevents us from using a simple start/end rect union. if (toDecomp.angle) return false; } floatBounds = transform.mapRect(floatBounds); } } if (applyTransformOrigin) floatBounds.moveBy(transformOrigin); bounds = LayoutRect(floatBounds); return true; } bool KeyframeEffect::computeTransformedExtentViaMatrix(const FloatRect& rendererBox, const RenderStyle& style, LayoutRect& bounds) const { TransformationMatrix transform; style.applyTransform(transform, rendererBox, RenderStyle::IncludeTransformOrigin); if (!transform.isAffine()) return false; TransformationMatrix::Decomposed2Type fromDecomp; transform.decompose2(fromDecomp); // Any rotation prevents us from using a simple start/end rect union. if (fromDecomp.angle) return false; bounds = LayoutRect(transform.mapRect(bounds)); return true; } bool KeyframeEffect::requiresPseudoElement() const { return m_blendingKeyframesSource == BlendingKeyframesSource::WebAnimation && targetsPseudoElement(); } Optional<double> KeyframeEffect::progressUntilNextStep(double iterationProgress) const { ASSERT(iterationProgress >= 0 && iterationProgress <= 1); if (auto progress = AnimationEffect::progressUntilNextStep(iterationProgress)) return progress; if (!is<LinearTimingFunction>(timingFunction()) || !m_someKeyframesUseStepsTimingFunction) return WTF::nullopt; if (m_blendingKeyframes.isEmpty()) return WTF::nullopt; auto progressUntilNextStepInInterval = [iterationProgress](double intervalStartProgress, double intervalEndProgress, TimingFunction* timingFunction) -> Optional<double> { if (!is<StepsTimingFunction>(timingFunction)) return WTF::nullopt; auto numberOfSteps = downcast<StepsTimingFunction>(*timingFunction).numberOfSteps(); auto intervalProgress = intervalEndProgress - intervalStartProgress; auto iterationProgressMappedToCurrentInterval = (iterationProgress - intervalStartProgress) / intervalProgress; auto nextStepProgress = ceil(iterationProgressMappedToCurrentInterval * numberOfSteps) / numberOfSteps; return (nextStepProgress - iterationProgressMappedToCurrentInterval) * intervalProgress; }; for (size_t i = 0; i < m_blendingKeyframes.size(); ++i) { auto intervalEndProgress = m_blendingKeyframes[i].key(); // We can stop once we find a keyframe for which the progress is more than the provided iteration progress. if (intervalEndProgress <= iterationProgress) continue; // In case we're on the first keyframe, then this means we are dealing with an implicit 0% keyframe. // This will be a linear timing function unless we're dealing with a CSS Animation which might have // the default timing function for its keyframes defined on its backing Animation object. if (!i) { if (is<CSSAnimation>(animation())) return progressUntilNextStepInInterval(0, intervalEndProgress, downcast<DeclarativeAnimation>(*animation()).backingAnimation().timingFunction()); return WTF::nullopt; } return progressUntilNextStepInInterval(m_blendingKeyframes[i - 1].key(), intervalEndProgress, timingFunctionForKeyframeAtIndex(i - 1)); } // If we end up here, then this means we are dealing with an implicit 100% keyframe. // This will be a linear timing function unless we're dealing with a CSS Animation which might have // the default timing function for its keyframes defined on its backing Animation object. auto& lastExplicitKeyframe = m_blendingKeyframes[m_blendingKeyframes.size() - 1]; if (is<CSSAnimation>(animation())) return progressUntilNextStepInInterval(lastExplicitKeyframe.key(), 1, downcast<DeclarativeAnimation>(*animation()).backingAnimation().timingFunction()); // In any other case, we are not dealing with an interval with a steps() timing function. return WTF::nullopt; } } // namespace WebCore
47.729958
249
0.704142
jacadcaps
03e5b62ad865ba44024dd644fc012af939d2db94
14,267
cpp
C++
Tools/AssetBuilder/src/AssetPacking.cpp
palikar/DirectXer
c21b87eed220fc54d97d5363e8a33bd0944a2596
[ "MIT" ]
null
null
null
Tools/AssetBuilder/src/AssetPacking.cpp
palikar/DirectXer
c21b87eed220fc54d97d5363e8a33bd0944a2596
[ "MIT" ]
null
null
null
Tools/AssetBuilder/src/AssetPacking.cpp
palikar/DirectXer
c21b87eed220fc54d97d5363e8a33bd0944a2596
[ "MIT" ]
null
null
null
#include "AssetBuilder.hpp" static size_t CalculateBaseOffset(AssetBundlerContext& context) { size_t offset{0}; offset += sizeof(AssetColletionHeader); offset += sizeof(TextureLoadEntry) * context.TexturesToCreate.size(); offset += sizeof(IBLoadEntry) * context.IBsToCreate.size(); offset += sizeof(VBLoadEntry) * context.VBsToCreate.size(); offset += sizeof(ImageEntry) * context.Images.size(); offset += sizeof(ImageAtlas) * context.Atlases.size(); offset += sizeof(MaterialLoadEntry) * context.Materials.size(); offset += sizeof(SkyboxLoadEntry) * context.Skyboxes.size(); offset += sizeof(ImageLoadEntry) * context.LoadImages.size(); offset += sizeof(WavLoadEntry) * context.LoadWavs.size(); offset += sizeof(FontLoadEntry) * context.LoadFonts.size(); offset += sizeof(MeshLoadEntry) * context.LoadMeshes.size(); return offset; } static void ApplyBaseOffset(AssetBundlerContext& context, size_t offset) { for (auto& entry : context.TexturesToCreate) { entry.DataOffset += offset; } for (auto& entry : context.VBsToCreate) { entry.DataOffset += offset; } for (auto& entry : context.IBsToCreate) { entry.DataOffset += offset; } for (auto& entry : context.LoadImages) { entry.DataOffset += offset; } for (auto& entry : context.LoadWavs) { entry.DataOffset += offset; } for (auto& entry : context.LoadFonts) { entry.DataOffset += offset; } for (auto& entry : context.Skyboxes) { entry.DataOffset[0] += offset; entry.DataOffset[1] += offset; entry.DataOffset[2] += offset; entry.DataOffset[3] += offset; entry.DataOffset[4] += offset; entry.DataOffset[5] += offset; } } static void GenerateHeaderArrays(std::ofstream& headerFile, AssetBundlerContext& context, AssetType type, std::string_view arrayName) { // Some defines can be emptry which will generate array with 0 elements which is not a thing in C++ if (std::count_if(context.Defines.begin(), context.Defines.end(), [type](auto& def) { return def.Type == type; }) == 0) return; headerFile << fmt::format("static inline const char* {}Names[] = {{\n", arrayName); for(auto& define : context.Defines) if(define.Type == type) headerFile << fmt::format("\t\"{}\",\n", define.Name); headerFile << "};\n\n"; headerFile << fmt::format("static inline uint32 {}Ids[] = {{\n", arrayName); for(auto& define : context.Defines) if(define.Type == type) headerFile << fmt::format("\t{},\n", define.Id); headerFile << "};\n\n"; headerFile << "/* ------------------------------ */\n\n"; } static void GenerateHeaderDefines(std::ofstream& headerFile, AssetBundlerContext& context) { auto maxLength = std::max_element(context.Defines.begin(), context.Defines.end(), [](auto& d1, auto d2) { return d1.Name.size() < d2.Name.size(); })->Name.size(); for(auto& define : context.Defines) { headerFile << fmt::format("#define {} {:>{}}", define.Name, define.Id, maxLength + 4 - define.Name.size()) << "\n"; } headerFile << "\n\n"; } void PackAssets(AssetBuilder::CommandLineArguments arguments, AssetToLoad* assets, size_t assetsCount, ImageToPack* imagesToPack, size_t imagesToPackCount) { AssetBundlerContext context; context.Header.VersionSpec = 1; AssetDataBlob dataBlob; dataBlob.Data.reserve(1024u*1024u*256u); std::chrono::steady_clock::time_point beginBuilding = std::chrono::steady_clock::now(); fmt::print("----------Running the texture packer----------\n"); { TexturePacker::CommandLineArguments texturePackingArguments; texturePackingArguments.Root = arguments.Root; TexturePackerOutput packedImages = PackTextures(texturePackingArguments, imagesToPack, imagesToPackCount); assert(packedImages.Success); fmt::print("----------Done with image packing----------\n"); // @Note: Create atlas entry and texture load entry for each atlas for (size_t i = 0; i < packedImages.Atlases.size(); ++i) { auto& atlas = packedImages.Atlases[i]; TextureLoadEntry texEntry; texEntry.Id = NextTextureAssetId(); texEntry.Desc.Width = atlas.Width; texEntry.Desc.Height = atlas.Height; texEntry.Desc.Format = atlas.Format; texEntry.DataOffset = dataBlob.PutData(packedImages.AtlasesBytes[i]); context.TexturesToCreate.push_back(texEntry); auto texName = fmt::format("T_ATLAS_{}", context.Atlases.size()); NewAssetName(context, Type_Texture, texName.c_str(), texEntry.Id); std::cout << fmt::format("{} \t->\t Bundling Texture [{:.3} MB]\n", texName, dataBlob.lastSize / (1024.0f*1024.0f)); ImageAtlas atlEntry; atlEntry.TexHandle = texEntry.Id; context.Atlases.push_back(atlEntry); } // @Note: Create image entry for each atlas image by using the tex handles generated // in the previous loop for (size_t i = 0; i < packedImages.Images.size(); ++i) { auto atlasImage = packedImages.Images[i]; ImageEntry imgEntry; imgEntry.Image.AtlasSize = { atlasImage.AtlasWidth, atlasImage.AtlasHeight}; imgEntry.Image.ScreenPos = { atlasImage.X, atlasImage.Y}; imgEntry.Image.ScreenSize = { atlasImage.Width, atlasImage.Height}; imgEntry.Image.TexHandle = context.TexturesToCreate[atlasImage.Atlas].Id; imgEntry.Id = NewAssetName(context, Type_Image, atlasImage.Name); context.Images.push_back(imgEntry); } } for (size_t i = 0; i < assetsCount; ++i) { auto& asset = assets[i]; asset.Path = fmt::format("{}/{}", arguments.Root, asset.Path); switch (asset.Type) { case Type_Font: { LoadFont(asset, context, dataBlob); std::cout << fmt::format("{} \t->\t Bundling Font [{:.3} KB] [{}]\n", asset.Id, dataBlob.lastSize/1024.0f, asset.Path); break; } case Type_Wav: { LoadWav(asset, context, dataBlob); std::cout << fmt::format("{} \t->\t Bundling WAV [{:.3} KB] [{}]\n", asset.Id, dataBlob.lastSize/1024.0f, asset.Path); break; } case Type_Image: { LoadImage(asset, context, dataBlob); std::cout << fmt::format("{} \t->\t Bundling Image [{:.3} MB] [{}]\n", asset.Id, dataBlob.lastSize/(1024.0f*1024.0f), asset.Path); break; } case Type_Texture: { LoadTexture(asset, context, dataBlob); std::cout << fmt::format("{} \t->\t Bundling Texture [{:.3} MB] [{}]\n", asset.Id, dataBlob.lastSize/(1024.0f*1024.0f), asset.Path); break; } case Type_Skybox: { LoadSkybox(asset, context, dataBlob); std::cout << fmt::format("{} \t->\t Bundling Skybox [{:.3} MB] [{}]\n", asset.Id, (6*dataBlob.lastSize)/(1024.0f*1024.0f), asset.Path); break; } case Type_Material: { LoadMaterial(asset, context, dataBlob); std::cout << fmt::format("{} \t->\t Bundling Material [{:.3} B] [{}]\n", asset.Id, (float)sizeof(MaterialDesc), asset.Path); break; } case Type_Mesh: { LoadMesh(asset, context, dataBlob); const float mem = dataBlob.lastSize > 1024*1024 ? dataBlob.lastSize / (1024.0f*1024.0f) : dataBlob.lastSize / 1024.0f; const char* unit = dataBlob.lastSize > 1024*1024 ? "MBs" : "KBs"; std::cout << fmt::format("{} \t->\t Bundling Mesh [{:.3} {}] [{}]\n", asset.Id, mem, unit, asset.Path); break; } } } context.Header.TexturesCount = (uint32)context.TexturesToCreate.size(); context.Header.VBsCount = (uint32)context.VBsToCreate.size(); context.Header.IBsCount = (uint32)context.IBsToCreate.size(); context.Header.ImagesCount = (uint32)context.Images.size(); context.Header.AtlasesCount = (uint32)context.Atlases.size(); context.Header.LoadImagesCount = (uint32)context.LoadImages.size(); context.Header.LoadWavsCount = (uint32)context.LoadWavs.size(); context.Header.LoadFontsCount = (uint32)context.LoadFonts.size(); context.Header.SkyboxesCount = (uint32)context.Skyboxes.size(); context.Header.LoadMeshesCount = (uint32)context.LoadMeshes.size(); context.Header.MaterialsCount = (uint32)context.Materials.size(); // @Note: The offsets in the context are relative to the beginning of the DataBlob; // when we put them on disk, some of the data in the context will be in front of the // pure data; hence we have to add this base offset to the offsets in the context size_t baseOffset = CalculateBaseOffset(context); ApplyBaseOffset(context, baseOffset); fmt::print("----------Done building assets----------\n"); fmt::print("Textures: \t[{}]\n", context.Header.TexturesCount); fmt::print("Images: \t[{}]\n", context.Header.ImagesCount); fmt::print("Atlases: \t[{}]\n", context.Header.AtlasesCount); fmt::print("LoadImages: \t[{}]\n", context.Header.LoadImagesCount); fmt::print("LoadWavs: \t[{}]\n", context.Header.LoadWavsCount); fmt::print("LoadFonts: \t[{}]\n", context.Header.LoadFontsCount); fmt::print("Skyboxes: \t[{}]\n", context.Header.SkyboxesCount); fmt::print("Meshes: \t[{}]\n", context.Header.LoadMeshesCount); fmt::print("Materials: \t[{}]\n", context.Header.MaterialsCount); std::chrono::steady_clock::time_point endBuilding = std::chrono::steady_clock::now(); fmt::print("Total time for building: [{:.2} s]\n", std::chrono::duration_cast<std::chrono::milliseconds>(endBuilding - beginBuilding).count() / 1000.0f); // @Note: From here forward, we are only writing the results of the packing to the files; // one header file and one asset bundle file /* @Note: The output file will have the following format |---------------Header-------------------| -- struct AssetColletionHeader |----------------------------------------| |---------------Texture_i----------------| -- struct TextureLoadEntry |----------------------------------------| |------------------VB_i------------------| -- struct VBLoadEntry |----------------------------------------| |------------------IB_i------------------| -- struct IBLoadEntry |----------------------------------------| |---------------Image_1------------------| -- struct ImageEntry |---------------Image_2------------------| |---------------.......------------------| |---------------Image_i------------------| |----------------------------------------| |---------------Atlas_1------------------| -- struct AtlasEntry |---------------Atlas_2------------------| |---------------.......------------------| |---------------Atlas_i------------------| |----------------------------------------| |---------------Images-------------------| -- struct ImageLoadEntry |----------------------------------------| |----------------Wavs--------------------| -- struct WavLoadEntry |----------------------------------------| |---------------Fonts--------------------| -- struct FontsLoadEntry |----------------------------------------| |---------------Skyboxes-----------------| -- struct SkyboxLoadEntry |----------------------------------------| -----------------Meshes------------------| -- struct MeshLoadEntry |----------------------------------------| |---------------Material-----------------| -- struct MaterialLoadEntrym |----------------------------------------| |----------------DATA--------------------| -- unsigned char[] */ std::string assetFileName = fmt::format("{}.dbundle", arguments.Output); fmt::print("Saving [{} Bytes] of meta data in [{}]\n", baseOffset, assetFileName); fmt::print("Saving [{:.3} MBs] of pure data in [{}]\n", dataBlob.Data.size() / (1024.0f* 1024.0f), assetFileName); std::ofstream outfile(assetFileName, std::ios::out | std::ios::binary); outfile.write((char*)&context.Header, sizeof(AssetColletionHeader)); outfile.write((char*)context.TexturesToCreate.data(), sizeof(TextureLoadEntry)*context.TexturesToCreate.size()); outfile.write((char*)context.VBsToCreate.data(), sizeof(VBLoadEntry)*context.VBsToCreate.size()); outfile.write((char*)context.IBsToCreate.data(), sizeof(IBLoadEntry)*context.IBsToCreate.size()); outfile.write((char*)context.Images.data(), sizeof(ImageEntry)*context.Images.size()); outfile.write((char*)context.Atlases.data(), sizeof(ImageAtlas)*context.Atlases.size()); outfile.write((char*)context.LoadImages.data(), sizeof(ImageLoadEntry)*context.LoadImages.size()); outfile.write((char*)context.LoadWavs.data(), sizeof(WavLoadEntry)*context.LoadWavs.size()); outfile.write((char*)context.LoadFonts.data(), sizeof(FontLoadEntry)*context.LoadFonts.size()); outfile.write((char*)context.Skyboxes.data(), sizeof(SkyboxLoadEntry)*context.Skyboxes.size()); outfile.write((char*)context.LoadMeshes.data(), sizeof(MeshLoadEntry)*context.LoadMeshes.size()); outfile.write((char*)context.Materials.data(), sizeof(MaterialLoadEntry)*context.Materials.size()); outfile.write((char*)dataBlob.Data.data(), sizeof(char) * dataBlob.Data.size()); outfile.close(); std::ofstream headerFile(fmt::format("{}", arguments.Header), std::ios::out); headerFile << "#pragma once\n"; headerFile << "\n\n"; // @Note: Generate #define with the id of every asset GenerateHeaderDefines(headerFile, context); // @Note: Generaet arrays with the names and ids of each asset GenerateHeaderArrays(headerFile, context, Type_Image, "Images"); GenerateHeaderArrays(headerFile, context, Type_Wav, "Wavs"); GenerateHeaderArrays(headerFile, context, Type_Font, "Fonts"); GenerateHeaderArrays(headerFile, context, Type_Mesh, "Meshes"); // Generate an array which can tell us how big (what font size) given font is headerFile << fmt::format("static inline size_t FontsSizes[] = {{\n"); for (auto& font : context.LoadFonts) { headerFile << fmt::format("\t{},\n", font.Desc.FontSize); } headerFile << "};\n\n"; headerFile << "/* ------------------------------ */\n\n"; headerFile << "inline GPUResource GPUResources[] = {\n"; for(auto& define : context.Defines) { if (define.Type >= GP_Count) continue; headerFile << fmt::format("\t{{ GPUResourceType({}), {}, \"{}\" }},\n", define.Type, define.Id, define.Name); } headerFile << "};\n\n"; headerFile << fmt::format("static inline AssetFile AssetFiles[] = {{\n"); headerFile << fmt::format("\t{{ \"{}\", {} }},\n", assetFileName, baseOffset + dataBlob.Data.size()); headerFile << fmt::format("}};\n\n"); // @Note: This teslls the loading code which file from the AssetFiles collection to load headerFile << fmt::format("static inline size_t {} = {};\n", arguments.Id , 0); }
40.997126
163
0.624658
palikar
03e68c0fdd51c9a3e227755939abfa568dd29f5f
648
cpp
C++
dmoj/uncategorized/16_bit_sw_only.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-07-16T01:46:38.000Z
2020-07-16T01:46:38.000Z
dmoj/uncategorized/16_bit_sw_only.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
null
null
null
dmoj/uncategorized/16_bit_sw_only.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-05-27T14:30:43.000Z
2020-05-27T14:30:43.000Z
#include <iostream> using namespace std; inline void use_io_optimizations() { ios_base::sync_with_stdio(false); cin.tie(nullptr); } int main() { use_io_optimizations(); unsigned int multiplications; cin >> multiplications; for (unsigned int i {0}; i < multiplications; ++i) { long long left; long long right; long long product; cin >> left >> right >> product; if (left * right == product) { cout << "POSSIBLE DOUBLE SIGMA"; } else { cout << "16 BIT S/W ONLY"; } cout << '\n'; } return 0; }
15.804878
54
0.521605
Rkhoiwal
03e71a3be1508cfe9132a6a65b3a9f9b2ede5228
1,031
cpp
C++
proZPRd/ScriptParser.cpp
peku33/proZPRd
632097bc8221116c57b9ae5e76dafd0a63d57fe6
[ "MIT" ]
null
null
null
proZPRd/ScriptParser.cpp
peku33/proZPRd
632097bc8221116c57b9ae5e76dafd0a63d57fe6
[ "MIT" ]
null
null
null
proZPRd/ScriptParser.cpp
peku33/proZPRd
632097bc8221116c57b9ae5e76dafd0a63d57fe6
[ "MIT" ]
null
null
null
#include "ScriptParser.hpp" #include "File.hpp" #include "Tools/Exception.hpp" #ifdef _WIN32 #define popen _popen #define pclose _pclose #endif proZPRd::ScriptParser::ScriptParser(const std::string & ParserExecutable): ParserExecutable(ParserExecutable) { } std::string proZPRd::ScriptParser::Parse(const std::string & ScriptName) const { if(!proZPRd::File::Exists(ScriptName)) throw Tools::Exception(EXCEPTION_PARAMS, "file: " + ScriptName + " not found!"); std::string Command = ParserExecutable + " " + ScriptName.c_str(); FILE* ParserProcess = popen(Command.c_str(), "r"); if (!ParserProcess) throw Tools::Exception(EXCEPTION_PARAMS, "popen() failed!"); char Buffer[128]; std::string Result; while(!feof(ParserProcess)) { auto Length = fread(Buffer, 1, sizeof(Buffer), ParserProcess); if(Length > 0) Result.append(Buffer, Length); } if(pclose(ParserProcess) != 0) throw Tools::Exception(EXCEPTION_PARAMS, Command + " process returned an error!"); return Result; }
27.131579
109
0.702231
peku33
03e7e0fb3bd5648ac5f66e0f418e07bb932947ff
7,226
cc
C++
src/sgmmbin/sgmm-acc-tree-stats.cc
hihihippp/Kaldi
861f838a2aea264a9e4ffa4df253df00a8b1247f
[ "Apache-2.0" ]
19
2015-03-19T10:53:38.000Z
2020-12-17T06:12:32.000Z
src/sgmmbin/sgmm-acc-tree-stats.cc
UdyanSachdev/kaldi
861f838a2aea264a9e4ffa4df253df00a8b1247f
[ "Apache-2.0" ]
1
2018-12-18T17:43:44.000Z
2018-12-18T17:43:44.000Z
src/sgmmbin/sgmm-acc-tree-stats.cc
UdyanSachdev/kaldi
861f838a2aea264a9e4ffa4df253df00a8b1247f
[ "Apache-2.0" ]
47
2015-01-27T06:22:57.000Z
2021-11-11T20:59:04.000Z
// sgmmbin/sgmm-acc-tree-stats.cc // Copyright 2012 Johns Hopkins University (Author: Daniel Povey) // 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 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include "base/kaldi-common.h" #include "util/common-utils.h" #include "tree/context-dep.h" #include "tree/build-tree-utils.h" #include "sgmm/sgmm-clusterable.h" #include "hmm/transition-model.h" int main(int argc, char *argv[]) { using namespace kaldi; typedef kaldi::int32 int32; try { const char *usage = "Accumulate statistics for decision tree training.\n" "This version accumulates statistics in the form of state-specific " "SGMM stats; you need to use the program sgmm-build-tree to build " "the tree (and sgmm-sum-tree-accs to sum the stats).\n" "Usage: sgmm-acc-tree-stats [options] sgmm-model-in features-rspecifier " "alignments-rspecifier [tree-accs-out]\n" "e.g.: sgmm-acc-tree-stats --ci-phones=48:49 1.mdl scp:train.scp ark:1.ali 1.tacc\n"; ParseOptions po(usage); bool binary = true; std::string gselect_rspecifier, spkvecs_rspecifier, utt2spk_rspecifier; string ci_phones_str; int N = 3, P = 1; SgmmGselectConfig sgmm_opts; po.Register("binary", &binary, "Write output in binary mode"); po.Register("gselect", &gselect_rspecifier, "Precomputed Gaussian indices (rspecifier)"); po.Register("spk-vecs", &spkvecs_rspecifier, "Speaker vectors (rspecifier)"); po.Register("utt2spk", &utt2spk_rspecifier, "rspecifier for utterance to speaker map"); po.Register("ci-phones", &ci_phones_str, "Colon-separated list of integer " "indices of context-independent phones."); po.Register("context-width", &N, "Context window size."); po.Register("central-position", &P, "Central context-window position (zero-based)"); sgmm_opts.Register(&po); po.Read(argc, argv); if (po.NumArgs() < 3 || po.NumArgs() > 4) { po.PrintUsage(); exit(1); } std::string sgmm_filename = po.GetArg(1), feature_rspecifier = po.GetArg(2), alignment_rspecifier = po.GetArg(3), accs_wxfilename = po.GetOptArg(4); std::vector<int32> ci_phones; if (ci_phones_str != "") { SplitStringToIntegers(ci_phones_str, ":", false, &ci_phones); std::sort(ci_phones.begin(), ci_phones.end()); if (!IsSortedAndUniq(ci_phones) || ci_phones[0] == 0) { KALDI_ERR << "Invalid set of ci_phones: " << ci_phones_str; } } TransitionModel trans_model; AmSgmm am_sgmm; std::vector<SpMatrix<double> > H; // Not initialized in this program-- not needed // as we don't call Objf() from stats. { bool binary; Input ki(sgmm_filename, &binary); trans_model.Read(ki.Stream(), binary); am_sgmm.Read(ki.Stream(), binary); } if (gselect_rspecifier.empty()) KALDI_ERR << "--gselect option is required."; SequentialBaseFloatMatrixReader feature_reader(feature_rspecifier); RandomAccessInt32VectorReader alignment_reader(alignment_rspecifier); RandomAccessInt32VectorVectorReader gselect_reader(gselect_rspecifier); RandomAccessBaseFloatVectorReader spkvecs_reader(spkvecs_rspecifier); RandomAccessTokenReader utt2spk_reader(utt2spk_rspecifier); std::map<EventType, SgmmClusterable*> tree_stats; int num_done = 0, num_err = 0; for (; !feature_reader.Done(); feature_reader.Next()) { std::string utt = feature_reader.Key(); if (!alignment_reader.HasKey(utt)) { num_err++; } else { const Matrix<BaseFloat> &mat = feature_reader.Value(); const std::vector<int32> &alignment = alignment_reader.Value(utt); if (!gselect_reader.HasKey(utt) || gselect_reader.Value(utt).size() != mat.NumRows()) { KALDI_WARN << "No gselect information for utterance " << utt << " (or wrong size)"; num_err++; continue; } const std::vector<std::vector<int32> > &gselect = gselect_reader.Value(utt); if (alignment.size() != mat.NumRows()) { KALDI_WARN << "Alignments has wrong size "<< (alignment.size())<<" vs. "<< (mat.NumRows()); num_err++; continue; } string utt_or_spk; if (utt2spk_rspecifier.empty()) utt_or_spk = utt; else { if (!utt2spk_reader.HasKey(utt)) { KALDI_WARN << "Utterance " << utt << " not present in utt2spk map; " << "skipping this utterance."; num_err++; continue; } else { utt_or_spk = utt2spk_reader.Value(utt); } } SgmmPerSpkDerivedVars spk_vars; if (spkvecs_reader.IsOpen()) { if (spkvecs_reader.HasKey(utt_or_spk)) { spk_vars.v_s = spkvecs_reader.Value(utt_or_spk); am_sgmm.ComputePerSpkDerivedVars(&spk_vars); } else { KALDI_WARN << "Cannot find speaker vector for " << utt_or_spk; } } // else spk_vars is "empty" // The work gets done here. if (!AccumulateSgmmTreeStats(trans_model, am_sgmm, H, N, P, ci_phones, alignment, gselect, spk_vars, mat, &tree_stats)) { num_err++; } else { num_done++; if (num_done % 1000 == 0) KALDI_LOG << "Processed " << num_done << " utterances."; } } } BuildTreeStatsType stats; // Converting from a map to a vector of pairs. for (std::map<EventType, SgmmClusterable*>::const_iterator iter = tree_stats.begin(); iter != tree_stats.end(); iter++ ) { stats.push_back(std::make_pair<EventType, Clusterable*>(iter->first, iter->second)); } tree_stats.clear(); { Output ko(accs_wxfilename, binary); WriteBuildTreeStats(ko.Stream(), binary, stats); } KALDI_LOG << "Accumulated stats for " << num_done << " files, " << num_err << " failed."; KALDI_LOG << "Number of separate stats (context-dependent states) is " << stats.size(); DeleteBuildTreeStats(&stats); return (num_done != 0 ? 0 : 1); } catch(const std::exception &e) { std::cerr << e.what(); return -1; } }
36.680203
101
0.596872
hihihippp
03e7eedbb9a40e47d88ba5db11d7f0db5d1e653c
1,634
cpp
C++
src/Common_Controls/Button/Button.cpp
gammasoft71/Examples_FLTK
7d8f11d5da25f7279834d3730732d07e91591f7c
[ "MIT" ]
21
2020-03-04T17:38:14.000Z
2022-03-07T02:46:39.000Z
src/Common_Controls/Button/Button.cpp
gammasoft71/Examples_FLTK
7d8f11d5da25f7279834d3730732d07e91591f7c
[ "MIT" ]
null
null
null
src/Common_Controls/Button/Button.cpp
gammasoft71/Examples_FLTK
7d8f11d5da25f7279834d3730732d07e91591f7c
[ "MIT" ]
6
2021-03-12T20:57:00.000Z
2022-03-31T23:19:03.000Z
#include <string> #include <FL/Fl.H> #include <FL/Fl_Box.H> #include <FL/Fl_Button.H> #include <FL/Fl_Repeat_Button.H> #include <FL/Fl_Window.H> using namespace std; namespace Examples { class Main_Window : public Fl_Window { public: Main_Window() : Fl_Window(200, 100, 300, 300, "Button example") { button1.align(FL_ALIGN_INSIDE | FL_ALIGN_CLIP | FL_ALIGN_WRAP); button1.callback([](Fl_Widget* sender, void* window) { auto result = "button1 clicked " + to_string(++reinterpret_cast<Main_Window*>(window)->button1_clicked) + " times"; reinterpret_cast<Main_Window*>(window)->box1.copy_label(result.c_str()); }, this); button2.align(FL_ALIGN_INSIDE | FL_ALIGN_CLIP | FL_ALIGN_WRAP); button2.callback([](Fl_Widget* sender, void* window) { auto result = "button2 clicked " + to_string(++reinterpret_cast<Main_Window*>(window)->button2_clicked) + " times"; reinterpret_cast<Main_Window*>(window)->box2.copy_label(result.c_str()); }, this); box1.align(FL_ALIGN_LEFT | FL_ALIGN_TOP | FL_ALIGN_INSIDE | FL_ALIGN_CLIP); box2.align(FL_ALIGN_LEFT | FL_ALIGN_TOP | FL_ALIGN_INSIDE | FL_ALIGN_CLIP); } private: Fl_Button button1 {50, 50, 75, 25, "button1"}; Fl_Repeat_Button button2 {50, 100, 200, 75, "button 2"}; Fl_Box box1 {50, 200, 200, 20, "button1 clicked 0 times"}; Fl_Box box2 {50, 230, 200, 25, "button2 clicked 0 times"}; int button1_clicked = 0; int button2_clicked = 0; }; } int main(int argc, char *argv[]) { Examples::Main_Window window; window.show(argc, argv); return Fl::run(); }
36.311111
123
0.672583
gammasoft71
03ec5b5f51d937311a211b54c17fb4910be5ee95
2,286
hh
C++
notification/inc/com/centreon/broker/notification/builders/composed_timeperiod_builder.hh
sdelafond/centreon-broker
21178d98ed8a061ca71317d23c2026dbc4edaca2
[ "Apache-2.0" ]
null
null
null
notification/inc/com/centreon/broker/notification/builders/composed_timeperiod_builder.hh
sdelafond/centreon-broker
21178d98ed8a061ca71317d23c2026dbc4edaca2
[ "Apache-2.0" ]
null
null
null
notification/inc/com/centreon/broker/notification/builders/composed_timeperiod_builder.hh
sdelafond/centreon-broker
21178d98ed8a061ca71317d23c2026dbc4edaca2
[ "Apache-2.0" ]
null
null
null
/* ** Copyright 2011-2014 Centreon ** ** 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. ** ** For more information : contact@centreon.com */ #ifndef CCB_NOTIFICATION_BUILDERS_COMPOSED_TIMEPERIOD_BUILDER_HH # define CCB_NOTIFICATION_BUILDERS_COMPOSED_TIMEPERIOD_BUILDER_HH # include <vector> # include "com/centreon/broker/namespace.hh" # include "com/centreon/broker/time/timeperiod.hh" # include "com/centreon/broker/notification/builders/timeperiod_builder.hh" # include "com/centreon/broker/notification/builders/composed_builder.hh" CCB_BEGIN() namespace notification { /** * @class composed_timeperiod_builder composed_timeperiod_builder.hh "com/centreon/broker/notification/builders/composed_timeperiod_builder.hh" * @brief Composed timeperiod builder. * * This class forward its method call to several other builders. */ class composed_timeperiod_builder : public composed_builder<timeperiod_builder> { public: composed_timeperiod_builder(); virtual ~composed_timeperiod_builder() {} virtual void add_timeperiod( unsigned int id, time::timeperiod::ptr tperiod); virtual void add_timeperiod_exception( unsigned int timeperiod_id, std::string const& days, std::string const& timerange); virtual void add_timeperiod_exclude_relation( unsigned int timeperiod_id, unsigned int exclude_id); virtual void add_timeperiod_include_relation( unsigned int timeperiod_id, unsigned int include_id); }; } CCB_END() #endif // !CCB_NOTIFICATION_BUILDERS_COMPOSED_TIMEPERIOD_BUILDER_HH
36.285714
146
0.698163
sdelafond
03edcec7dd078dd995694fd563f26e980748dcfa
2,271
hpp
C++
include/codegen/include/OVR/OpenVR/IVROverlay__FindOverlay.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/OVR/OpenVR/IVROverlay__FindOverlay.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/OVR/OpenVR/IVROverlay__FindOverlay.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:02 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.MulticastDelegate #include "System/MulticastDelegate.hpp" // Including type: OVR.OpenVR.IVROverlay #include "OVR/OpenVR/IVROverlay.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Skipping declaration: IntPtr because it is already included! // Forward declaring type: IAsyncResult class IAsyncResult; // Forward declaring type: AsyncCallback class AsyncCallback; } // Forward declaring namespace: OVR::OpenVR namespace OVR::OpenVR { // Forward declaring type: EVROverlayError struct EVROverlayError; } // Completed forward declares // Type namespace: OVR.OpenVR namespace OVR::OpenVR { // Autogenerated type: OVR.OpenVR.IVROverlay/_FindOverlay class IVROverlay::_FindOverlay : public System::MulticastDelegate { public: // public System.Void .ctor(System.Object object, System.IntPtr method) // Offset: 0x1508B08 static IVROverlay::_FindOverlay* New_ctor(::Il2CppObject* object, System::IntPtr method); // public OVR.OpenVR.EVROverlayError Invoke(System.String pchOverlayKey, System.UInt64 pOverlayHandle) // Offset: 0x1508B1C OVR::OpenVR::EVROverlayError Invoke(::Il2CppString* pchOverlayKey, uint64_t& pOverlayHandle); // public System.IAsyncResult BeginInvoke(System.String pchOverlayKey, System.UInt64 pOverlayHandle, System.AsyncCallback callback, System.Object object) // Offset: 0x1508F28 System::IAsyncResult* BeginInvoke(::Il2CppString* pchOverlayKey, uint64_t& pOverlayHandle, System::AsyncCallback* callback, ::Il2CppObject* object); // public OVR.OpenVR.EVROverlayError EndInvoke(System.UInt64 pOverlayHandle, System.IAsyncResult result) // Offset: 0x1508FC4 OVR::OpenVR::EVROverlayError EndInvoke(uint64_t& pOverlayHandle, System::IAsyncResult* result); }; // OVR.OpenVR.IVROverlay/_FindOverlay } DEFINE_IL2CPP_ARG_TYPE(OVR::OpenVR::IVROverlay::_FindOverlay*, "OVR.OpenVR", "IVROverlay/_FindOverlay"); #pragma pack(pop)
45.42
157
0.745927
Futuremappermydud
03f2d5de87a128dbbf8ea8b365b65dd3c6282c1b
2,590
cpp
C++
Source/engine/render/automap_render.cpp
pionere/devilutionX
63f8deb298a00b040010fc299c0568eae19522e1
[ "Unlicense" ]
2
2021-02-02T19:27:20.000Z
2022-03-07T16:50:55.000Z
Source/engine/render/automap_render.cpp
pionere/devilutionX
63f8deb298a00b040010fc299c0568eae19522e1
[ "Unlicense" ]
null
null
null
Source/engine/render/automap_render.cpp
pionere/devilutionX
63f8deb298a00b040010fc299c0568eae19522e1
[ "Unlicense" ]
1
2022-03-07T16:51:16.000Z
2022-03-07T16:51:16.000Z
/** * @file automap_render.cpp * * Line drawing routines for the automap. */ #include "automap_render.hpp" #include "all.h" DEVILUTION_BEGIN_NAMESPACE #ifdef _DEBUG /** automap pixel color 8-bit (palette entry) */ char gbPixelCol; /** flip - if y < x */ bool _gbRotateMap; /** valid - if x/y are in bounds */ bool _gbNotInView; /** Number of times the current seed has been fetched */ #endif /** * @brief Set the value of a single pixel in the back buffer, DOES NOT checks bounds * @param sx Back buffer coordinate * @param sy Back buffer coordinate * @param col Color index from current palette */ void AutomapDrawPixel(int sx, int sy, BYTE col) { BYTE *dst; //assert(gpBuffer != NULL); //if (sy < SCREEN_Y || sy >= SCREEN_HEIGHT + SCREEN_Y || sx < SCREEN_X || sx >= SCREEN_WIDTH + SCREEN_X) // return; dst = &gpBuffer[sx + BUFFER_WIDTH * sy]; //if (dst < gpBufEnd && dst > gpBufStart) *dst = col; } #ifdef _DEBUG /** * @brief Set the value of a single pixel in the back buffer to that of gbPixelCol, checks bounds * @param sx Back buffer coordinate * @param sy Back buffer coordinate */ void engine_draw_pixel(int sx, int sy) { BYTE *dst; assert(gpBuffer != NULL); if (_gbRotateMap) { if (_gbNotInView && (sx < 0 || sx >= SCREEN_HEIGHT + SCREEN_Y || sy < SCREEN_X || sy >= SCREEN_WIDTH + SCREEN_X)) return; dst = &gpBuffer[sy + BUFFER_WIDTH * sx]; } else { if (_gbNotInView && (sy < 0 || sy >= SCREEN_HEIGHT + SCREEN_Y || sx < SCREEN_X || sx >= SCREEN_WIDTH + SCREEN_X)) return; dst = &gpBuffer[sx + BUFFER_WIDTH * sy]; } if (dst < gpBufEnd && dst > gpBufStart) *dst = gbPixelCol; } #endif /** * @brief Draw a line on the back buffer * @param x0 Back buffer coordinate * @param y0 Back buffer coordinate * @param x1 Back buffer coordinate * @param y1 Back buffer coordinate * @param col Color index from current palette */ void AutomapDrawLine(int x0, int y0, int x1, int y1, BYTE col) { int di, ip, dx, dy, ax, ay, steps; float df, fp; dx = x1 - x0; dy = y1 - y0; ax = abs(dx); ay = abs(dy); if (ax > ay) { steps = ax; di = dx / ax; df = dy / (float)steps; ip = x0; fp = (float)y0; for ( ; steps >= 0; steps--, ip += di, fp += df) { AutomapDrawPixel(ip, (int)fp, col); } } else { steps = ay; di = dy / ay; df = dx / float(steps); fp = (float)x0; ip = y0; for ( ; steps >= 0; steps--, fp += df, ip += di) { AutomapDrawPixel((int)fp, ip, col); } } } DEVILUTION_END_NAMESPACE
23.981481
116
0.609266
pionere
03f35212d5fddcc9822f56c56bdf275f527fde93
244
cpp
C++
primer/ch06/exercise6.25.cpp
zhangrxiang/learn-cpp
6043009096315cab75c92115d8ecb65fb345aade
[ "Apache-2.0" ]
null
null
null
primer/ch06/exercise6.25.cpp
zhangrxiang/learn-cpp
6043009096315cab75c92115d8ecb65fb345aade
[ "Apache-2.0" ]
null
null
null
primer/ch06/exercise6.25.cpp
zhangrxiang/learn-cpp
6043009096315cab75c92115d8ecb65fb345aade
[ "Apache-2.0" ]
null
null
null
// // Created by zing on 5/21/2020. // #include <iostream> using namespace std; int main(int argc, char *argv[]) { string str; for (int i = 0; i != argc; i++) { str += argv[i]; } cout << str << endl; return 0; }
13.555556
37
0.512295
zhangrxiang
03f6af84193b21e7db5661a2f272d288bb969f3c
964
cpp
C++
codeforces/A - Parity/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/A - Parity/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/A - Parity/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Feb/15/2019 00:51 * solution_verdict: Accepted language: GNU C++14 * run_time: 46 ms memory_used: 3900 KB * problem: https://codeforces.com/contest/1110/problem/A ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e6; int aa[N+2]; int main() { ios_base::sync_with_stdio(0);cin.tie(0); int b,k;cin>>b>>k; for(int i=1;i<=k;i++) cin>>aa[i],aa[i]%=2; int bs=1;int sum=0; for(int i=k;i>=1;i--) { sum=(sum+aa[i]*bs)%2; bs=(bs*b)%2; } if(sum)cout<<"odd"<<endl; else cout<<"even"<<endl; return 0; }
35.703704
111
0.378631
kzvd4729
03f9f14214d1ec694b02fbe34284f24699273f55
1,203
cpp
C++
src/common/low_precision_transformations/src/variadic_split.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
1
2022-02-26T17:33:44.000Z
2022-02-26T17:33:44.000Z
src/common/low_precision_transformations/src/variadic_split.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
18
2022-01-21T08:42:58.000Z
2022-03-28T13:21:31.000Z
src/common/low_precision_transformations/src/variadic_split.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
1
2020-12-13T22:16:54.000Z
2020-12-13T22:16:54.000Z
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "low_precision/variadic_split.hpp" #include "ngraph/node.hpp" #include <ngraph/pattern/op/wrap_type.hpp> #include "low_precision/network_helper.hpp" namespace ngraph { namespace pass { namespace low_precision { NGRAPH_RTTI_DEFINITION(ngraph::pass::low_precision::VariadicSplitTransformation, "VariadicSplitTransformation", 0); VariadicSplitTransformation::VariadicSplitTransformation(const Params& params) : SplitTransformation(params) { auto matcher = pattern::wrap_type<opset1::VariadicSplit>({ pattern::wrap_type<opset1::Multiply>(), pattern::wrap_type<opset1::Constant>(), pattern::wrap_type<opset1::Constant>() }); ngraph::graph_rewrite_callback callback = [this](pattern::Matcher& m) { auto op = m.get_match_root(); if (transformation_callback(op)) { return false; } return transform(*context, m); }; auto m = std::make_shared<ngraph::pattern::Matcher>(matcher, "VariadicSplitTransformation"); this->register_matcher(m, callback); } } // namespace low_precision } // namespace pass } // namespace ngraph
30.846154
115
0.716542
ryanloney
03fed44f9750c22e983dccbafcbdc592396eee76
784
hpp
C++
cppsrc/js-wrappers/wrapColour.hpp
sjoerd108/jimp-native
d489a68923e377d5a7f4fd0f9583382fc3773906
[ "MIT" ]
11
2021-06-05T19:32:08.000Z
2022-03-24T02:01:10.000Z
cppsrc/js-wrappers/wrapColour.hpp
sjoerd108/jimp-native
d489a68923e377d5a7f4fd0f9583382fc3773906
[ "MIT" ]
1
2021-11-13T13:12:48.000Z
2022-02-07T23:46:17.000Z
cppsrc/js-wrappers/wrapColour.hpp
sjoerd108/jimp-native
d489a68923e377d5a7f4fd0f9583382fc3773906
[ "MIT" ]
null
null
null
#pragma once #include <napi.h> #include "../util/referenceFactory.hpp" void wrapBrightness (const Napi::CallbackInfo& info, ReferenceFactory& referenceFactory); void wrapOpacity (const Napi::CallbackInfo& info, ReferenceFactory& referenceFactory); void wrapOpaque (const Napi::CallbackInfo& info, ReferenceFactory& referenceFactory); void wrapContrast (const Napi::CallbackInfo& info, ReferenceFactory& referenceFactory); void wrapPosterize (const Napi::CallbackInfo& info, ReferenceFactory& referenceFactory); void wrapSepia (const Napi::CallbackInfo& info, ReferenceFactory& referenceFactory); void wrapConvolution (const Napi::CallbackInfo& info, ReferenceFactory& referenceFactory); void wrapGreyscale (const Napi::CallbackInfo& info, ReferenceFactory& referenceFactory);
39.2
90
0.8125
sjoerd108
ff001b84a7f0daa0657944aca81ec5320060dfd9
2,452
cc
C++
third_party/openscreen/src/streaming/cast/clock_drift_smoother.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
third_party/openscreen/src/streaming/cast/clock_drift_smoother.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
third_party/openscreen/src/streaming/cast/clock_drift_smoother.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "streaming/cast/clock_drift_smoother.h" #include <cmath> #include "platform/api/logging.h" namespace openscreen { namespace cast_streaming { namespace { constexpr ClockDriftSmoother::Clock::time_point kNullTime = ClockDriftSmoother::Clock::time_point::min(); } ClockDriftSmoother::ClockDriftSmoother(Clock::duration time_constant) : time_constant_(time_constant), last_update_time_(kNullTime), estimated_tick_offset_(0.0) { OSP_DCHECK(time_constant_ > decltype(time_constant_)::zero()); } ClockDriftSmoother::~ClockDriftSmoother() = default; ClockDriftSmoother::Clock::duration ClockDriftSmoother::Current() const { OSP_DCHECK(last_update_time_ != kNullTime); const double rounded_estimate = std::round(estimated_tick_offset_); if (rounded_estimate < Clock::duration::min().count()) { return Clock::duration::min(); } else if (rounded_estimate > Clock::duration::max().count()) { return Clock::duration::max(); } return Clock::duration(static_cast<Clock::duration::rep>(rounded_estimate)); } void ClockDriftSmoother::Reset(Clock::time_point now, Clock::duration measured_offset) { OSP_DCHECK(now != kNullTime); last_update_time_ = now; estimated_tick_offset_ = static_cast<double>(measured_offset.count()); } void ClockDriftSmoother::Update(Clock::time_point now, Clock::duration measured_offset) { OSP_DCHECK(now != kNullTime); if (last_update_time_ == kNullTime) { Reset(now, measured_offset); } else if (now < last_update_time_) { // |now| is not monotonically non-decreasing. OSP_NOTREACHED(); } else { const double elapsed_ticks = static_cast<double>((now - last_update_time_).count()); last_update_time_ = now; // Compute a weighted-average between the last estimate and // |measured_offset|. The more time that has elasped since the last call to // Update(), the more-heavily |measured_offset| will be weighed. const double weight = elapsed_ticks / (elapsed_ticks + time_constant_.count()); estimated_tick_offset_ = weight * measured_offset.count() + (1.0 - weight) * estimated_tick_offset_; } } } // namespace cast_streaming } // namespace openscreen
35.028571
79
0.708401
zipated
ff026199929a25bfa9158d1fd9e13f01eace5d05
16,590
cpp
C++
181041025_main.cpp
perihanmirkelam/FitTheShapes
3f1efb6fb049951c75bb93fcdd81cb760efc0e89
[ "Apache-2.0" ]
1
2020-01-18T12:59:33.000Z
2020-01-18T12:59:33.000Z
181041025_main.cpp
perihanmirkelam/FitTheShapes
3f1efb6fb049951c75bb93fcdd81cb760efc0e89
[ "Apache-2.0" ]
7
2018-12-22T15:49:35.000Z
2018-12-22T16:07:01.000Z
181041025_main.cpp
perihanmirkelam/FitTheShapes
3f1efb6fb049951c75bb93fcdd81cb760efc0e89
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <fstream> #include <string> #include <cmath> #include <math.h> using namespace std; //area double bigRectangleArea=0.0; double bigCircleArea=0.0; double bigTriangleArea=0.0; double rectangleArea=0.0; double circleArea=0.0; double triangleArea=0.0; double bigShapeArea=0.0; double smallShapeArea=0.0; //whole file size int svg_w=0; int svg_h=0; //rectangle sizes int bigRectangle_x=0; int bigRectangle_y=0; int bigRectangle_w=0; int bigRectangle_h=0; int rectangle_x=0; int rectangle_y=0; int rectangle_w=0; int rectangle_h=0; //circle sizes int bigCircle_x=0; int bigCircle_y=0; int bigCircle_r=0; int circle_x=0; int circle_y=0; int circle_r=0; //triangle sizes int bigTriangle_x1=0; int bigTriangle_y1=0; int bigTriangle_x2=0; int bigTriangle_y2=0; int bigTriangle_x3=0; int bigTriangle_y3=0; int bigTriangle_e=0; int triangle_x1=0; int triangle_y1=0; int triangle_x2=0; int triangle_y2=0; int triangle_x3=0; int triangle_y3=0; int triangle_e=0; //shape types enum class ShapeEnum { R, C, T }; //desired shape types ShapeEnum bigShapeType; ShapeEnum smallShapesType; string bigShapeSvg; int quantityOfSmallShapes; void askSmallShapes(); void askBigShape(); void drawSvg(string smallShapes){ string svg; ofstream myfile; myfile.open ("output.svg"); myfile << "<svg version=\"1.1\"\n" "baseProfile=\"full\"\n" "width= \"" << svg_w << "\" height=\"" << svg_h << "\"\n" "xmlns=\"http://www.w3.org/2000/svg\">\n" << bigShapeSvg << smallShapes << // "<rect width=\"70%\" height=\"50%\" fill=\"red\" />\n" // "<rect x=\"0\" y=\"105\" width=\"80\" height=\"80\" fill=\"blue\"/>\n" // "<polygon points=\"10,10 20,80 80,80\" class=\"triangle\" />" // "<circle cx=\"100\" cy=\"100\" r=\"80\" fill=\"green\" />\n" "</svg>" << endl; myfile.close(); } string circlesInTriangle(){ string svgPart; int diameter = 2*circle_r; int innerVertical= ((circle_r * sqrt(3)) / 2) + 1; int row = (svg_h - (circle_r * sqrt(3))) / (diameter -(circle_r*sqrt(3) - circle_r)/4); quantityOfSmallShapes += (row * (row + 1)) / 2; //svg_w+=1; //int tempWidth = svg_w - triangle_e; int minusX = -circle_r; for (int i=0; i<row; i++){ for(int j=0; j<i+1; j++){ svgPart += "<circle cx=\"" + to_string(int((svg_w/2) - (i*circle_r) + (j* diameter))) + "\" cy=\"" + to_string((int)((i+1)*diameter) - (i * (circle_r*sqrt(3) - circle_r)/4)) + "\" r=\" " + to_string(circle_r) + "\" fill=\"green\" style=\"stroke-width:1;stroke:rgb(10,10,10)\" />\n"; // addMinusX =-addMinusX; } } return svgPart; } string rectanglesInTriangle(){ string svgPart; int row = svg_h / rectangle_h; int column = svg_w / rectangle_w; int leapLength = (rectangle_h / sqrt(3)) + 1; int bigTriangle_w = svg_w; int bigTriangle_h = svg_h; if(row == 0 && column == 0 && (svg_w / rectangle_h) > 0 && (svg_w / rectangle_w)> 0){ //if only one and rotated rectangle fit in triangle svgPart += "<rect x=\"" + to_string(svg_w - rectangle_h) + "\" y=\"" + to_string(svg_h - rectangle_w) + "\" width=\"" + to_string(rectangle_h) + "\" height=\"" + to_string(rectangle_w) + "\" fill=\"yellow\" style=\"stroke-width:1;stroke:rgb(10,10,10)\" />\n"; return svgPart; } int upperWidth = bigTriangle_w - (2 * leapLength); for (int i=0; i<row; i++){ for(int j=0; j<column; j++){ if((j+1)*rectangle_w <= upperWidth){ svgPart += "<rect x=\"" + to_string((i+1)*leapLength + j*rectangle_w) + "\" y=\"" + to_string(bigTriangle_h - rectangle_h) + "\" width=\"" + to_string(rectangle_w) + "\" height=\"" + to_string(rectangle_h) + "\" fill=\"yellow\" style=\"stroke-width:1;stroke:rgb(10,10,10)\" />\n"; quantityOfSmallShapes++; } } bigTriangle_w = upperWidth; upperWidth = bigTriangle_w - (2 * (leapLength)); bigTriangle_h -= rectangle_h; } return svgPart; } string trianglesInCircle(){ string svgPart; return svgPart; } string circlesInCircle(){ string svgPart; int diameter = 2*circle_r; //int row = (2 * bigCircle_r) / (diameter - (circle_r * sqrt(3) - circle_r) / 4); int row = (2 * bigCircle_r) / (diameter); quantityOfSmallShapes += (row * (row + 1)) / 2; int sCircle_r = ((circle_r * sqrt(3)) - circle_r); int sDiameter = (diameter - sCircle_r); row = row/2; row = row%2==1 ? row : row+1; for (int i=0; i<row; i++){ for(int j=0; j<i*2+1; j++){ svgPart += "<circle cx=\"" + to_string((int)( (svg_w / 2) - ((i * 2* circle_r)) + (j * diameter))) + "\" cy=\"" + to_string((int)(((i+1)*circle_r) + (i * (circle_r)))) + "\" r=\" " + to_string(circle_r) + "\" fill=\"green\" style=\"stroke-width:1;stroke:rgb(10,10,10)\" />\n"; svgPart += "<circle cx=\"" + to_string((int)( (svg_w / 2) - ((i *2* circle_r)) + (j * diameter))) + "\" cy=\"" + to_string((svg_h - (int)(((i+1)*circle_r)) - (i * (circle_r)))) + "\" r=\" " + to_string(circle_r) + "\" fill=\"green\" style=\"stroke-width:1;stroke:rgb(10,10,10)\" />\n"; } } return svgPart; } string rectanglesInCircle(){ string svgPart; return svgPart; } //calculate and draw how many triangle fit in rectangle string trianglesInRectangle(){ string svgPart; int height = (triangle_e * sqrt(3)) / 2; int halfEdge = triangle_e/2; cout << "triangle height: " << height << endl; int column = bigRectangle_w / triangle_e; int row = bigRectangle_h / height; quantityOfSmallShapes = (column) * (row); for (int i=0; i<row; i++){ for(int j=0; j<column; j++){ svgPart += "<polygon points=\"" + to_string(j*triangle_e) + "," + to_string(height + i*height) + " " //x1 y1 + to_string(triangle_e + (j*triangle_e)) + "," + to_string(height + i*height) + " " //x2 y2 + to_string(halfEdge + (j*triangle_e)) + "," + to_string(i*height) //x3 y3 +"\" class=\"triangle\" fill=\"green\" style=\"stroke-width:1;stroke:rgb(10,10,10)\" />\n"; if((halfEdge + ((j+1)*triangle_e)) <= svg_w){ svgPart += "<polygon points=\"" + to_string(halfEdge + ((j+1)*triangle_e)) + "," + to_string(i*height) + " " //x1 y1 + to_string(triangle_e + (j*triangle_e)) + "," + to_string(height + i*height) + " " //x2 y2 + to_string(halfEdge + (j*triangle_e)) + "," + to_string(i*height) //x3 y3 +"\" class=\"triangle\" fill=\"green\" style=\"stroke-width:1;stroke:rgb(10,10,10)\" />\n"; quantityOfSmallShapes++; } } } return svgPart; } //calculate and draw how many circle fit in rectangle string circlesInRectangle(){ string svgPart; int diameter = circle_r*2; int column = bigRectangle_w / diameter; int row = bigRectangle_h / diameter; quantityOfSmallShapes = (column) * (row); for (int i=0; i<row; i++){ for(int j=0; j<column; j++){ svgPart += "<circle cx=\"" + to_string(circle_r + (j*diameter)) + "\" cy=\"" + to_string(circle_r + (i*diameter)) + "\" r=\"" + to_string(circle_r) + "\" fill=\"green\" style=\"stroke-width:1;stroke:rgb(10,10,10)\" />\n"; } } return svgPart; } //calculate and draw how many rectangle fit in rectangle string rectanglesInRectangle(){ string svgPart; int quantityStraight = (bigRectangle_h / rectangle_h) * (bigRectangle_w / rectangle_w); int quantityRotated = (bigRectangle_h / rectangle_w) * (bigRectangle_w / rectangle_h); int row=0, column = 0; if(quantityStraight >= quantityRotated){ quantityOfSmallShapes = quantityStraight; row = bigRectangle_h / rectangle_h; column = bigRectangle_w / rectangle_w; } else { quantityOfSmallShapes = quantityRotated; row = bigRectangle_h / rectangle_w; column = bigRectangle_w / rectangle_h; int temp = rectangle_w; rectangle_w = rectangle_h; rectangle_h = temp; } for (int i=0; i<row; i++){ for(int j=0; j<column; j++){ svgPart += "<rect x=\"" + to_string(rectangle_w * j) + "\" y=\"" + to_string(i * rectangle_h) + "\" width=\"" + to_string(rectangle_w) + "\" height=\"" + to_string(rectangle_h) + "\" fill=\"yellow\" style=\"stroke-width:1;stroke:rgb(10,10,10)\" />\n"; } } return svgPart; } void drawSmallShapes(ShapeEnum bigShapeType, ShapeEnum smallShapeType){ string smallShapes =""; switch(bigShapeType){ case ShapeEnum::R: switch(smallShapeType){ case ShapeEnum::R: smallShapes = rectanglesInRectangle(); break; case ShapeEnum::C: smallShapes = circlesInRectangle(); break; case ShapeEnum::T: smallShapes = trianglesInRectangle(); break; } break; case ShapeEnum::C: switch(smallShapeType){ case ShapeEnum::R: smallShapes = rectanglesInCircle(); break; case ShapeEnum::C: smallShapes = circlesInCircle(); break; case ShapeEnum::T: smallShapes = trianglesInCircle(); break; } break; case ShapeEnum::T: switch(smallShapeType){ case ShapeEnum::R: smallShapes = rectanglesInTriangle(); break; case ShapeEnum::C: smallShapes = circlesInTriangle(); break; case ShapeEnum::T: smallShapes = trianglesInTriangle(); break; } break; } cout << "smallShapes: " << smallShapes << endl; drawSvg(smallShapes); } double calculateRectangleArea(bool isBigShape){ double area=0.0; if(isBigShape){ bigRectangleArea = bigRectangle_w * bigRectangle_h; area = bigRectangleArea; } else { rectangleArea = rectangle_w * rectangle_h; area = rectangleArea; } return area; } double calculateCircleArea(bool isBigShape){ double area=0.0; if(isBigShape){ bigCircleArea = M_PI * pow(bigCircle_r, 2); area = bigCircleArea; } else { circleArea = M_PI * pow(circle_r, 2); area = circleArea; } return area; } double calculateTriangleArea(bool isBigShape){ double area=0.0; if(isBigShape){ bigTriangleArea = (pow(bigTriangle_e, 2) * sqrt(3)) / 2; area = bigTriangleArea; } else { triangleArea = (pow(triangle_e, 2) * sqrt(3)) / 2; area = triangleArea; } return area; } void drawBigShape(){ switch(bigShapeType){ case ShapeEnum::R : bigShapeSvg = "<rect x=\"0\" y=\"0\" width=\"" + to_string(svg_w) + "\" height=\"" + to_string(svg_h) + "\" fill=\"blue\"/>\n"; break; case ShapeEnum::C : bigCircle_x = svg_w/2; bigCircle_y = svg_h/2; bigShapeSvg = "<circle cx=\"" + to_string(bigCircle_x) + "\" cy=\"" + to_string(bigCircle_y) + "\" r=\"" + to_string(bigCircle_r) + "\" fill=\"blue\" />\n"; break; case ShapeEnum::T : bigTriangle_x1=0; bigTriangle_y1=svg_h; bigTriangle_x2=svg_w; bigTriangle_y2=svg_h; bigTriangle_x3=svg_w/2; bigTriangle_y3=0; bigShapeSvg = "<polygon points=\"" + to_string(bigTriangle_x1) + "," + to_string(bigTriangle_y1) + " " + to_string(bigTriangle_x2) + "," + to_string(bigTriangle_y2) + " " + to_string(bigTriangle_x3) + "," + to_string(bigTriangle_y3) + "\" class=\"triangle\" fill=\"blue\" /> \n"; break; } } void calculateSvgSize(){ switch(bigShapeType){ case ShapeEnum::R : svg_w = bigRectangle_w; svg_h = bigRectangle_h; break; case ShapeEnum::C : svg_w = bigCircle_r * 2; svg_h = bigCircle_r * 2; break; case ShapeEnum::T : svg_w = bigTriangle_e; svg_h = (int) (bigTriangle_e/2)*(sqrt(3)); break; } drawBigShape(); } //ask for width and height of rectangle void askRectangleSize(bool isBigShape){ int width; int height; cout << "Enter width of rectangle:\n"; cin >> width; while(cin.fail() || width < 1){ cin.clear(); cin.ignore(1000,'\n'); cout<<"Bad value! Please enter a positive integer value for width of rectangle: " << endl; cin >> width; } cout << "Enter height of rectangle:\n"; cin >> height; while(cin.fail() || height < 1){ cin.clear(); cin.ignore(1000,'\n'); cout<<"Bad value! Please enter a positive integer value for height of rectangle: " << endl; cin >> height; } if(isBigShape){ bigRectangle_w = width; bigRectangle_h = height; } else { rectangle_w = width; rectangle_h = height; } } //ask for radius length of circle void askCircleSize(bool isBigShape){ int radius; cout << "Enter radius of circle:\n"; cin >> radius; while(cin.fail() || radius < 1){ cin.clear(); cin.ignore(1000,'\n'); cout<<"Bad value! Please enter a positive integer value for radius of circle: " << endl; cin >> radius; } if(isBigShape){ bigCircle_r = radius; } else { circle_r = radius; } } //ask for edge length of equilateral triangle void askTriangleSize(bool isBigShape){ int edge; cout << "Enter edge length of triangle:\n"; cin >> edge; while(cin.fail() || edge < 1){ cin.clear(); cin.ignore(1000,'\n'); cout<<"Bad value! Please enter a positive integer value for edge length of triangle: " << endl; cin >> edge; } if(isBigShape){ bigTriangle_e = edge; } else { triangle_e = edge; } } void assignShapeType(bool isBigShape, string input){ ShapeEnum shape; if(input == "R" || input == "r"){ shape = ShapeEnum::R; } else if(input == "C" || input == "c"){ shape = ShapeEnum::C; } else if(input == "T" || input == "t"){ shape = ShapeEnum::T; } else { cout << "Incorrect input! Try again..." << endl; isBigShape ? askBigShape() : askSmallShapes(); return; } if(isBigShape){ bigShapeType = shape; } else { smallShapesType = shape; } } // ask what is the type of small shapes and their sizes void askSmallShapes(){ string smallShape = ""; cout << "Please enter the type of shape include your container shape (R, C, T):\n"; cin >> smallShape; assignShapeType(false, smallShape); switch(smallShapesType){ case ShapeEnum::R : askRectangleSize(false); if(calculateRectangleArea(false) > bigShapeArea){ cout << "This area must be smaller than first one!" << endl; cout << "calculateRectangleArea(false): " << calculateRectangleArea(false) << " bigShapeArea: " << bigShapeArea <<endl; rectangle_w=0; rectangle_h=0; rectangleArea = 0.0; askSmallShapes(); } break; case ShapeEnum::C : askCircleSize(false); if(calculateCircleArea(false) > bigShapeArea){ cout << "This area must be smaller than first one!" << endl; circle_r=0; circleArea = 0.0; askSmallShapes(); } break; case ShapeEnum::T : askTriangleSize(false); calculateTriangleArea(false); if(calculateTriangleArea(false) > bigShapeArea){ cout << "This area must be smaller than first one!" << endl; triangle_e=0; triangleArea = 0.0; askSmallShapes(); } break; } drawSmallShapes(bigShapeType, smallShapesType); } // ask what is the type of the big shape and its sizes void askBigShape(){ string mainShape; cout << "Please enter the main container shape (R, C, T):\n"; cin >> mainShape; assignShapeType(true, mainShape); double area = 0.0; switch(bigShapeType){ case ShapeEnum::R : askRectangleSize(true); area = calculateRectangleArea(true); break; case ShapeEnum::C : askCircleSize(true); area = calculateCircleArea(true); break; case ShapeEnum::T : askTriangleSize(true); area = calculateTriangleArea(true); break; } bigShapeArea = area; calculateSvgSize(); askSmallShapes(); } int main() { askBigShape(); cout<< "Drawing svg to canvas width: "<< svg_w << " svg height: " << svg_h <<endl; cout<<"big rectangle: " << bigRectangle_x << ", " << bigRectangle_y << ", " << bigRectangle_w <<", " << bigRectangle_h << "\n" << "big circle: " << bigCircle_x << ", " << bigCircle_y << ", " << bigCircle_r << "\n" << "big triangle: (" << bigTriangle_x1 << ", " << bigTriangle_y1 << "), (" << bigTriangle_x2 <<", " << bigTriangle_y2 << "), (" << bigTriangle_x3 <<", " << bigTriangle_y3 << ")\n \n" << "rectangle: " << rectangle_x << ", " << rectangle_y << ", " << rectangle_w <<", " << rectangle_h << "\n" << "circle: " << circle_x << ", " << circle_y << ", " << circle_r << "\n" << "triangle: (" << triangle_x1 << ", " << triangle_y1 << "), (" << triangle_x2 <<", " << triangle_y2 << "), (" << triangle_x3 <<", " << triangle_y3 << ")\n \n" << "rectangle area: " << rectangleArea << " - big rectangle area: " << bigRectangleArea << "\n" << "circle area: " << circleArea << " - big circle area: " << bigCircleArea << "\n" << "triangle area: " << triangleArea << " - big triangle area: " << bigTriangleArea << "\n" << "svg height: " << svg_h << " - svg width: " << bigTriangleArea << "\n" << endl; double remainedArea = bigShapeArea - (quantityOfSmallShapes*smallShapeArea); cout << "I can fit at most " << quantityOfSmallShapes << " small shapes into the main container. " << "The empty area (blue) in container is " << remainedArea << endl; return 0; }
29.731183
127
0.629717
perihanmirkelam
ff03540b571d45c24718bbf7fdbb31d23409c3ea
7,690
cpp
C++
Tools/ExtractStrain/DataExtractor.cpp
danielfrascarelli/esys-particle
e56638000fd9c4af77e21c75aa35a4f8922fd9f0
[ "Apache-2.0" ]
null
null
null
Tools/ExtractStrain/DataExtractor.cpp
danielfrascarelli/esys-particle
e56638000fd9c4af77e21c75aa35a4f8922fd9f0
[ "Apache-2.0" ]
null
null
null
Tools/ExtractStrain/DataExtractor.cpp
danielfrascarelli/esys-particle
e56638000fd9c4af77e21c75aa35a4f8922fd9f0
[ "Apache-2.0" ]
null
null
null
///////////////////////////////////////////////////////////// // // // Copyright (c) 2003-2017 by The University of Queensland // // Centre for Geoscience Computing // // http://earth.uq.edu.au/centre-geoscience-computing // // // // Primary Business: Brisbane, Queensland, Australia // // Licensed under the Open Software License version 3.0 // // http://www.apache.org/licenses/LICENSE-2.0 // // // ///////////////////////////////////////////////////////////// #include "DataExtractor.h" #include "SnapFileHelp.h" // --- Project includes --- #include "ntable/src/handle.h" // --- std. includes --- #include <cmath> using std::atan; using std::sqrt; // --- IO includes --- #include <fstream> using std::ifstream; using std::ofstream; /*! constructor \param x nr. of grid points in x-direction \param y nr. of grid points in y-direction \param z nr. of grid points in z-direction \param range grid spacing \param p0_global minimal corner (origin) of the global search space */ DataExtractor::DataExtractor(int x,int y,int z,double range,const Vec3& p0_global,const Vec3& pmax_global)://modified (fluid contents) m_data(x,y,z,range,0.0,p0_global,pmax_global,0,0,0) //modified (fluid contents) { } /*! read snapshot \param filename the name of the "metadata" file, usually *_0.txt */ void DataExtractor::read(const string& infilename) { ifstream headerfile(infilename.c_str()); int version=get_version(infilename); vector<string> filenames=get_filenames(infilename,version); // get main files for(vector<string>::iterator iter=filenames.begin(); iter!=filenames.end(); iter++){ cout << *iter << endl; ifstream datafile(iter->c_str()); // get particles int npart; Vec3 pos; Vec3 oldpos; Vec3 initpos; Vec3 force; Vec3 vel; Vec3 angvel; Vec3 circ_shift; double rad; double mass; double q1,q2,q3,q4; int id; int tag; datafile >> npart; if(version<2){ for(int i=0;i<npart;i++){ // read data datafile >> pos >> rad >> id >> tag >> mass >> initpos >> oldpos >> vel >> force >> q1 >> q2 >> q3 >> q4 >> angvel; DataParticle dp=DataParticle(pos,initpos,rad,id); m_data.insert(dp); } } else { for(int i=0;i<npart;i++){ // read data datafile >> pos >> rad >> id >> tag >> mass >> initpos >> oldpos >> vel >> force >> circ_shift >> q1 >> q2 >> q3 >> q4 >> angvel; DataParticle dp=DataParticle(pos,initpos,rad,id); m_data.insert(dp); } } datafile.close(); } std::cout << "inserted " << m_data.size() << " particles " << std::endl; // m_data.build(); } /*! write tensor data as unstructured grid VTK-XML file \param filename the name of the output file \param dataname the name of the data in the VTK file */ void DataExtractor::writeTensorDataVtk(const string& filename,const string& dataname) { } /*! write scalar data as unstructured grid VTK-XML file \param filename the name of the output file \param dataname the name of the data in the VTK file */ void DataExtractor::writeScalarDataVtk(const string& filename,const string& dataname) { ofstream vtkfile(filename.c_str()); // write the file // write header vtkfile << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\">\n"; vtkfile << "<UnstructuredGrid>\n"; vtkfile << "<Piece NumberOfPoints=\"" << m_data.size() << "\" NumberOfCells=\"0\">\n"; // write particle pos vtkfile << "<Points>\n"; vtkfile << "<DataArray NumberOfComponents=\"3\" type=\"Float64\" format=\"ascii\">\n"; for(NeighborTable<DataParticle>::iterator iter=m_data.begin(); iter!=m_data.end(); iter++){ vtkfile << iter->getPos() << " "; } vtkfile << "</DataArray>\n"; vtkfile << "</Points>\n"; // --- write particle data --- // radius vtkfile << "<PointData Scalars=\"radius\">\n"; vtkfile << "<DataArray type=\"Float64\" Name=\"radius\" NumberOfComponents=\"1\" format=\"ascii\">\n"; for(NeighborTable<DataParticle>::iterator iter=m_data.begin(); iter!=m_data.end(); iter++){ vtkfile << iter->getRad() << " "; } vtkfile << "</DataArray>\n"; vtkfile << "</PointData>\n"; // data vtkfile << "<PointData Scalars=\"" << dataname << "\">\n"; vtkfile << "<DataArray type=\"Float64\" Name=\"radius\" NumberOfComponents=\"1\" format=\"ascii\">\n"; for(NeighborTable<DataParticle>::iterator iter=m_data.begin(); iter!=m_data.end(); iter++){ vtkfile << iter->getScalarData() << " "; } vtkfile << "</DataArray>\n"; vtkfile << "</PointData>\n"; // write empty cell block vtkfile << "<Cells>\n"; vtkfile << "<DataArray type=\"Int32\" NumberOfComponents=\"1\" Name=\"connectivity\" format=\"ascii\">\n"; vtkfile << "</DataArray>\n"; vtkfile << "<DataArray type=\"UInt8\" NumberOfComponents=\"1\" Name=\"types\" format=\"ascii\">\n"; vtkfile << "</DataArray>\n"; vtkfile << "</Cells>\n"; // write footer vtkfile << "</Piece>\n"; vtkfile << "</UnstructuredGrid>\n"; vtkfile << "</VTKFile>\n"; // close file vtkfile.close(); } /*! extract best fit strain tensors from the data and write the result into the tensor data member of the particles \param rad the search radius for the neighbour particles */ void DataExtractor::StrainToTensorData(double rad) { // for each particle for(NeighborTable<DataParticle>::iterator iter=m_data.begin(); iter!=m_data.end(); iter++){ // get list of neighbours T_Handle<NeighborTable<DataParticle>::particlelist> plist=m_data.getParticlesNearPoint(iter->getPos()); std::cout << "pos: " << iter->getPos() << " list size : " << plist->size() << std::endl; if(plist->size()>3){ // init sums Matrix3 M; Vec3 Su,Sv,Sw; // for each neighbour for(NeighborTable<DataParticle>::particlelist::iterator n_iter=plist->begin(); n_iter!=plist->end(); n_iter++){ // get relative position & displacement Vec3 disp=(*n_iter)->getDisplacement()-iter->getDisplacement(); Vec3 rpos=(*n_iter)->getPos()-iter->getPos(); // --- udate sums // M M(0,0)+=rpos.X()*rpos.X(); M(0,1)+=rpos.X()*rpos.Y(); M(0,2)+=rpos.X()*rpos.Z(); M(1,1)+=rpos.Y()*rpos.Y(); M(1,2)+=rpos.Y()*rpos.Z(); M(2,2)+=rpos.Z()*rpos.Z(); // Su,v,w Su+=disp.X()*rpos; Sv+=disp.Y()*rpos; Sw+=disp.Z()*rpos; } // make M symmetric M(1,0)=M(0,1); M(2,0)=M(0,2); M(2,1)=M(1,2); // solve equations to get displacement gradient tensor components Vec3 Du=M.solve(Su); Vec3 Dv=M.solve(Sv); Vec3 Dw=M.solve(Sw); // make deformation gradient tensor Matrix3 A; A(0,0)=Du.X()+1; A(0,1)=Du.Y(); A(0,2)=Du.Z(); A(1,0)=Dv.X(); A(1,1)=Dv.Y()+1; A(1,2)=Dv.Z(); A(2,0)=Dw.X(); A(2,1)=Dw.Y(); A(2,2)=Dw.Z()+1; // right Cauchy-Green deformation tensor Matrix3 C=A.trans()*A; // write to tensor data member of the particle iter->setTensorData(C); } } } /*! write maximum shear strain to scalar data member. Needs strain tensor calculation done before */ void DataExtractor::MaxShearToScalarData() { for(NeighborTable<DataParticle>::iterator iter=m_data.begin(); iter!=m_data.end(); iter++){ // get eigenvalues of tensor data Vec3 D1,D2,D3; double e1,e2,e3; (iter->getTensorData()).eigen(D1,D2,D3,e1,e2,e3); // set scalar data to max shear strain iter->setScalarData(atan(sqrt(e3/e1))); } }
30.275591
134
0.593628
danielfrascarelli
ff05932e8e55201de1611d969f06a644cc0a651f
2,062
cpp
C++
src/UI/Core/TextArea.cpp
Goof-fr/OPHD
ab3414181b04ab2757b124d81fd5592f930c5370
[ "BSD-3-Clause" ]
2
2020-01-27T19:44:45.000Z
2020-01-27T19:44:49.000Z
src/UI/Core/TextArea.cpp
Goof-fr/OPHD
ab3414181b04ab2757b124d81fd5592f930c5370
[ "BSD-3-Clause" ]
null
null
null
src/UI/Core/TextArea.cpp
Goof-fr/OPHD
ab3414181b04ab2757b124d81fd5592f930c5370
[ "BSD-3-Clause" ]
null
null
null
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com #include "TextArea.h" #include "../../Common.h" #include "../../Constants.h" #include "../../FontManager.h" #include "NAS2D/Utility.h" #include "NAS2D/Renderer/Renderer.h" using namespace NAS2D; void TextArea::font(const std::string& font, size_t size) { mFont = Utility<FontManager>::get().font(font, size); } void TextArea::processString() { mFormattedList.clear(); if (width() < 10 || !mFont || text().empty()) { return; } StringList tokenList = split_string(text().c_str(), ' '); size_t w = 0, i = 0; while (i < tokenList.size()) { std::string line; while (w < width() && i < tokenList.size()) { int tokenWidth = mFont->width(tokenList[i] + " "); w += tokenWidth; if (w >= width()) { /** * \todo In some edge cases where the width of the TextArea is too * narrow for a single word/token, this will result in an infinite * loop. This edge case will need to be resolved either by splitting * the token that's too wide or by simply rendering it as is. */ //++i; break; } if (tokenList[i] == "\n") { ++i; break; } line += (tokenList[i] + " "); ++i; } w = 0; mFormattedList.push_back(line); } mNumLines = static_cast<size_t>(height() / mFont->height()); } void TextArea::onSizeChanged() { Control::onSizeChanged(); processString(); } void TextArea::onTextChanged() { processString(); } void TextArea::onFontChanged() { processString(); } void TextArea::update() { draw(); } void TextArea::draw() { Renderer& r = Utility<Renderer>::get(); if (highlight()) { r.drawBox(rect(), 255, 255, 255); } if (!mFont) { return; } for (size_t i = 0; i < mFormattedList.size() && i < mNumLines; ++i) { r.drawText(*mFont, mFormattedList[i], positionX(), positionY() + (mFont->height() * i), mTextColor.red(), mTextColor.green(), mTextColor.blue(), mTextColor.alpha()); } }
19.826923
167
0.618817
Goof-fr
ff07abe555f00304ab1ffa0cd453e90331af827c
629
cc
C++
CommonTools/RecoAlgos/plugins/EtMinCaloJetRefSelector.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
CommonTools/RecoAlgos/plugins/EtMinCaloJetRefSelector.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
CommonTools/RecoAlgos/plugins/EtMinCaloJetRefSelector.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
/* \class EtMinCaloJetRefSelector * * selects calo-jet above a minumum Et cut * and saves a collection of references (RefVector) to selctedobjects * * \author: Luca Lista, INFN * */ #include "FWCore/Framework/interface/MakerMacros.h" #include "CommonTools/UtilAlgos/interface/EtMinSelector.h" #include "CommonTools/UtilAlgos/interface/SingleObjectSelector.h" #include "DataFormats/JetReco/interface/CaloJet.h" typedef SingleObjectSelector< reco::CaloJetCollection, EtMinSelector, reco::CaloJetRefVector > EtMinCaloJetRefSelector; DEFINE_FWK_MODULE( EtMinCaloJetRefSelector );
29.952381
69
0.748808
nistefan
ff095491d08d633f594690163bef526fdbc7d828
234
cc
C++
kythe/cxx/indexer/cxx/testdata/docs/tvar_docs_template_partial_spec_var.cc
BearerPipelineTest/kythe
c496c5c00177e437e28bb3a75a5ef811d5d55ff7
[ "Apache-2.0" ]
1,168
2015-01-27T10:19:25.000Z
2018-10-30T15:07:11.000Z
kythe/cxx/indexer/cxx/testdata/docs/tvar_docs_template_partial_spec_var.cc
BearerPipelineTest/kythe
c496c5c00177e437e28bb3a75a5ef811d5d55ff7
[ "Apache-2.0" ]
2,811
2015-01-29T16:19:04.000Z
2018-11-01T19:48:06.000Z
kythe/cxx/indexer/cxx/testdata/docs/tvar_docs_template_partial_spec_var.cc
BearerPipelineTest/kythe
c496c5c00177e437e28bb3a75a5ef811d5d55ff7
[ "Apache-2.0" ]
165
2015-01-27T19:06:27.000Z
2018-10-30T17:31:10.000Z
// We associate template partial specialization documentation correctly. /// Empty. template <typename T> int S = 1; //- @+2"/// Special." documents Var /// Special. template <typename T> int S<T*> = 2; //- Var.node/kind variable
19.5
72
0.675214
BearerPipelineTest
ff0c0878f1d9530eb4881b6dcc9c9e167a1b09fc
1,031
cpp
C++
C++/0320-Generalized-Abbreviation/soln-1.cpp
wyaadarsh/LeetCode-Solutions
3719f5cb059eefd66b83eb8ae990652f4b7fd124
[ "MIT" ]
5
2020-07-24T17:48:59.000Z
2020-12-21T05:56:00.000Z
C++/0320-Generalized-Abbreviation/soln-1.cpp
zhangyaqi1989/LeetCode-Solutions
2655a1ffc8678ad1de6c24295071308a18c5dc6e
[ "MIT" ]
null
null
null
C++/0320-Generalized-Abbreviation/soln-1.cpp
zhangyaqi1989/LeetCode-Solutions
2655a1ffc8678ad1de6c24295071308a18c5dc6e
[ "MIT" ]
2
2020-07-24T17:49:01.000Z
2020-08-31T19:57:35.000Z
class Solution { public: vector<string> generateAbbreviations(string word) { vector<char> cand; vector<string> ans; Dfs(0, word, &cand, &ans); return ans; } private: void Dfs(int i, const string & word, vector<char> * cand, vector<string> * ans) { if (i == word.length()) { ans->push_back(ToString(*cand)); } else { cand->push_back(word[i]); Dfs(i + 1, word, cand, ans); cand->pop_back(); cand->push_back('#'); Dfs(i + 1, word, cand, ans); cand->pop_back(); } } string ToString(const vector<char> & cand) { string ans; int cnt = 0; for(char ch : cand) { if (ch == '#') { ++cnt; } else { if(cnt) ans += to_string(cnt); cnt = 0; ans += ch; } } if (cnt) ans += to_string(cnt); return ans; } };
24.547619
85
0.42289
wyaadarsh
ff0c29dd2b90603aa1a1ea9fb2018edc6d93b707
3,607
cpp
C++
LeetCode/C++/1567. Maximum Length of Subarray With Positive Product.cpp
shreejitverma/GeeksforGeeks
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-18T05:14:28.000Z
2022-03-08T07:00:08.000Z
LeetCode/C++/1567. Maximum Length of Subarray With Positive Product.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
6
2022-01-13T04:31:04.000Z
2022-03-12T01:06:16.000Z
LeetCode/C++/1567. Maximum Length of Subarray With Positive Product.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-14T19:53:53.000Z
2022-02-18T05:14:30.000Z
//Runtime: 252 ms, faster than 40.00% of C++ online submissions for Maximum Length of Subarray With Positive Product. //Memory Usage: 58.7 MB, less than 20.00% of C++ online submissions for Maximum Length of Subarray With Positive Product. //time: O(N) class Solution { public: int getMaxLen(vector<int>& nums) { int n = nums.size(); int neg = 0; int len = 0; int ans = 0; vector<int> negs; int i = 0; while(i < n){ /* for a specific start point "i", records the position of negative numbers until a "0" */ int j; for(j = i; j < n && nums[j] != 0; ++j){ if(nums[j] < 0){ negs.push_back(j); } } // cout << "negs: " << negs.size() << endl; if(negs.size() % 2 == 0){ /* if we have even number of negative numbers, then the subarray nums[i...j-1] is valid */ len = j-i; }else if(negs.size() == 1){ // cout << negs[0]-i << " or " << j-1-(negs[0]+1)+1 << endl; /* if there is a negative number in nums[i...j-1], then we may choose [i...negs[0]-1] or [negs[0]+1...j-1] */ len = max(negs[0]-i, j-1-(negs[0]+1)+1); }else{ /* there are multiple negative numbers, we may exclude the first one or the last one, so [i...last-1] or [first+1...j-1] */ int first = negs[0], last = negs.back(); // cout << last-i << " or " << j-1-(first+1)+1 << endl; len = max(last-i, j-1-(first+1)+1); } ans = max(ans, len); negs.clear(); //next start from the position behind "0" i = j+1; } ans = max(ans, len); return ans; } }; //Greedy //https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/819278/Java-O(n)-time-O(1)-space //Runtime: 260 ms, faster than 20.00% of C++ online submissions for Maximum Length of Subarray With Positive Product. //Memory Usage: 57.9 MB, less than 20.00% of C++ online submissions for Maximum Length of Subarray With Positive Product. class Solution { public: int getMaxLen(vector<int>& nums) { int firstNeg = -1, lastZero = -1; int negCount = 0; int ans = 0; int n = nums.size(); for(int i = 0; i < n; ++i){ int e = nums[i]; if(e < 0){ ++negCount; if(firstNeg == -1) firstNeg = i; } if(e == 0){ lastZero = i; negCount = 0; //this also need to be reset! firstNeg = -1; }else{ //e > 0 or e < 0!! if(!(negCount&1)){ //negCount is even //[lastZero+1...i] // cout << i << " : " << i-lastZero << endl; ans = max(ans, i-lastZero); }else{ //[firstNeg+1...i] // cout << i << " : " << i-firstNeg << endl; ans = max(ans, i-firstNeg); } } } return ans; } };
32.790909
121
0.411145
shreejitverma
ff0dbeaaa207b26349a0dd1cccc12db72b12809c
317
hpp
C++
include/RED4ext/Scripting/Natives/Generated/game/PSMZones.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
42
2020-12-25T08:33:00.000Z
2022-03-22T14:47:07.000Z
include/RED4ext/Scripting/Natives/Generated/game/PSMZones.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
38
2020-12-28T22:36:06.000Z
2022-02-16T11:25:47.000Z
include/RED4ext/Scripting/Natives/Generated/game/PSMZones.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
20
2020-12-28T22:17:38.000Z
2022-03-22T17:19:01.000Z
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> namespace RED4ext { namespace game { enum class PSMZones : uint32_t { Default = 0, Public = 1, Safe = 2, Restricted = 3, Dangerous = 4, Any = 4294967295, }; } // namespace game } // namespace RED4ext
15.85
57
0.649842
jackhumbert
ff0f7991b88f8f3ef53d6c678d7fb436aefc0644
8,721
cpp
C++
camera/hal/intel/ipu3/common/platformdata/CameraMetadataHelper.cpp
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
4
2020-07-24T06:54:16.000Z
2021-06-16T17:13:53.000Z
camera/hal/intel/ipu3/common/platformdata/CameraMetadataHelper.cpp
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2021-04-02T17:35:07.000Z
2021-04-02T17:35:07.000Z
camera/hal/intel/ipu3/common/platformdata/CameraMetadataHelper.cpp
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2020-11-04T22:31:45.000Z
2020-11-04T22:31:45.000Z
/* * Copyright (C) 2014-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. */ #define LOG_TAG "MetadataHelper" #include "CameraMetadataHelper.h" #include "LogHelper.h" #include <string> #include <sstream> namespace cros { namespace intel { namespace MetadataHelper { #define CHECK_AND_GET(TYPE, UNION_FIELD) \ camera_metadata_ro_entry entry = metadata.find(tag); \ if (entry.count == 0) { \ LOG2("tag %s.%s is not set.", \ get_camera_metadata_section_name(tag), \ get_camera_metadata_tag_name(tag)); \ return false; \ } else if (count > 0 && entry.count != (size_t)count) { \ LOGE("Bad count %d for tag %s.%s! Should be %zu", \ count, \ get_camera_metadata_section_name(tag), \ get_camera_metadata_tag_name(tag), \ entry.count); \ return false; \ } else if (entry.type != (TYPE)) { \ LOGE("Bad type %d for tag %s.%s! Should be %d", \ TYPE, \ get_camera_metadata_section_name(tag), \ get_camera_metadata_tag_name(tag), \ entry.type); \ return false; \ }\ value = *entry.data.UNION_FIELD; \ return true; bool getMetadataValue(const android::CameraMetadata &metadata, uint32_t tag, uint8_t & value, int count) { CHECK_AND_GET(TYPE_BYTE, u8); } bool getMetadataValue(const android::CameraMetadata &metadata, uint32_t tag, int32_t & value, int count) { CHECK_AND_GET(TYPE_INT32, i32); } bool getMetadataValue(const android::CameraMetadata &metadata, uint32_t tag, int64_t & value, int count) { CHECK_AND_GET(TYPE_INT64, i64); } bool getMetadataValue(const android::CameraMetadata &metadata, uint32_t tag, float & value, int count) { CHECK_AND_GET(TYPE_FLOAT, f); } bool getMetadataValue(const android::CameraMetadata &metadata, uint32_t tag, double & value, int count) { CHECK_AND_GET(TYPE_DOUBLE, d); } const void * getMetadataValues(const android::CameraMetadata &metadata, uint32_t tag, int type, int * count) { camera_metadata_ro_entry entry = metadata.find(tag); if (count) *count = entry.count; if (entry.count == 0) { LOG2("Tag %s.%s is not set.", get_camera_metadata_section_name(tag), get_camera_metadata_tag_name(tag)); return nullptr; } if (entry.type != type) { LOGE("Bad type %d for tag %s.%s! Should be %d", type, get_camera_metadata_section_name(tag), get_camera_metadata_tag_name(tag), entry.type); return nullptr; } return entry.data.u8; } /** * Convenience getter for an entry. Difference to the framework version is that * the tag is always written to the entry, even if no entry is found. * * \param[in] metadata The camera metadata to get tag info for * \param[in] tag Tag of the queried metadata * \param[in] printError If set to \e true, Prints an error if no metadata * for given tag found. Default: true. * * \return The metadata entry corresponding to \e tag. */ camera_metadata_ro_entry_t getMetadataEntry(const camera_metadata_t *metadata, uint32_t tag, bool printError) { camera_metadata_ro_entry entry; CLEAR(entry); entry.tag = tag; find_camera_metadata_ro_entry(metadata, tag, &entry); if (printError && entry.count <= 0) LOGW("Metadata error, check camera3_profile. Tag %s", get_camera_metadata_tag_name(tag)); return entry; } void getValueByType(const camera_metadata_ro_entry_t& setting, int idx, uint8_t* value) { *value = setting.data.u8[idx]; } void getValueByType(const camera_metadata_ro_entry_t& setting, int idx, int32_t* value) { *value = setting.data.i32[idx]; } void getValueByType(const camera_metadata_ro_entry_t& setting, int idx, float* value) { *value = setting.data.f[idx]; } void getValueByType(const camera_metadata_ro_entry_t& setting, int idx, int64_t* value) { *value = setting.data.i64[idx]; } void getValueByType(const camera_metadata_ro_entry_t& setting, int idx, double* value) { *value = setting.data.d[idx]; } const void * getMetadataValues(const camera_metadata_t * metadata, uint32_t tag, int type, int * count) { status_t res = NO_ERROR; camera_metadata_ro_entry entry; res = find_camera_metadata_ro_entry(metadata, tag, &entry); if (res != OK) { LOGE("Failed to find %s.%s", get_camera_metadata_section_name(tag), get_camera_metadata_tag_name(tag)); return nullptr; } if (entry.type != type) { LOGE("Bad type %d for tag %s.%s! Should be %d", type, get_camera_metadata_section_name(tag), get_camera_metadata_tag_name(tag), entry.type); return nullptr; } if (count) * count = entry.count; return entry.count ? entry.data.u8 : nullptr; } status_t updateMetadata(camera_metadata_t * metadata, uint32_t tag, const void* data, size_t data_count) { status_t res = NO_ERROR; camera_metadata_entry_t entry; res = find_camera_metadata_entry(metadata, tag, &entry); if (res == NAME_NOT_FOUND) { res = add_camera_metadata_entry(metadata, tag, data, data_count); } else if (res == OK) { res = update_camera_metadata_entry(metadata, entry.index, data, data_count, nullptr); } return res; } void dumpMetadata(const camera_metadata_t * meta) { if (!meta) return; if ((gLogLevel & CAMERA_DEBUG_LOG_LEVEL2) != CAMERA_DEBUG_LOG_LEVEL2) return; int entryCount = get_camera_metadata_entry_count(meta); for (int i = 0; i < entryCount; i++) { camera_metadata_entry_t entry; if (get_camera_metadata_entry((camera_metadata_t *)meta, i, &entry)) { continue; } // Print tag & type const char *tagName, *tagSection; tagSection = get_camera_metadata_section_name(entry.tag); if (tagSection == nullptr) { tagSection = "unknownSection"; } tagName = get_camera_metadata_tag_name(entry.tag); if (tagName == nullptr) { tagName = "unknownTag"; } const char *typeName; if (entry.type >= NUM_TYPES) { typeName = "unknown"; } else { typeName = camera_metadata_type_names[entry.type]; } LOG2("(%d)%s.%s (%05x): %s[%zu], type: %d", i, tagSection, tagName, entry.tag, typeName, entry.count, entry.type); // Print data size_t j; const uint8_t *u8; const int32_t *i32; const float *f; const int64_t *i64; const double *d; const camera_metadata_rational_t *r; std::ostringstream stringStream; stringStream << "["; switch (entry.type) { case TYPE_BYTE: u8 = entry.data.u8; for (j = 0; j < entry.count; j++) stringStream << (int32_t)u8[j] << " "; break; case TYPE_INT32: i32 = entry.data.i32; for (j = 0; j < entry.count; j++) stringStream << " " << i32[j] << " "; break; case TYPE_FLOAT: f = entry.data.f; for (j = 0; j < entry.count; j++) stringStream << " " << f[j] << " "; break; case TYPE_INT64: i64 = entry.data.i64; for (j = 0; j < entry.count; j++) stringStream << " " << i64[j] << " "; break; case TYPE_DOUBLE: d = entry.data.d; for (j = 0; j < entry.count; j++) stringStream << " " << d[j] << " "; break; case TYPE_RATIONAL: r = entry.data.r; for (j = 0; j < entry.count; j++) stringStream << " (" << r[j].numerator << ", " << r[j].denominator << ") "; break; } stringStream << "]"; std::string str = stringStream.str(); LOG2("%s", str.c_str()); } } } } /* namespace intel */ } /* namespace cros */
31.035587
109
0.606582
strassek
ff11146ddacd3980ca02e2ec5d3b514224b1520a
1,325
hpp
C++
cpp-source/shell.hpp
bwackwat/event-spiral
177331035a23f68a0294a0f3e9af948779eef794
[ "MIT" ]
3
2016-12-08T02:28:27.000Z
2019-05-15T23:16:11.000Z
cpp-source/shell.hpp
bwackwat/event-spiral
177331035a23f68a0294a0f3e9af948779eef794
[ "MIT" ]
3
2017-02-10T18:21:28.000Z
2017-09-21T00:06:44.000Z
cpp-source/shell.hpp
bwackwat/event-spiral
177331035a23f68a0294a0f3e9af948779eef794
[ "MIT" ]
3
2017-02-04T01:37:24.000Z
2019-05-15T23:17:43.000Z
#pragma once #include <atomic> #include "util.hpp" class Shell{ private: int pid; public: std::atomic<bool> opened; int input; int output; Shell():opened(false){} bool sopen(){ if(this->opened){ return false; } int shell_pipe[2][2]; if(pipe(shell_pipe[0]) < 0){ ERROR("pipe 0") return true; } if(pipe(shell_pipe[1]) < 0){ ERROR("pipe 1") return true; } if((this->pid = fork()) < 0){ ERROR("fork") return true; }else if(this->pid == 0){ dup2(shell_pipe[0][0], STDIN_FILENO); dup2(shell_pipe[1][1], STDOUT_FILENO); dup2(shell_pipe[1][1], STDERR_FILENO); close(shell_pipe[0][0]); close(shell_pipe[1][1]); close(shell_pipe[1][0]); close(shell_pipe[0][1]); if(execl("/bin/bash", "/bin/bash", static_cast<char*>(0)) < 0){ perror("execl"); } PRINT("execl done!") return true; }else{ close(shell_pipe[0][0]); close(shell_pipe[1][1]); this->output = shell_pipe[1][0]; this->input = shell_pipe[0][1]; } this->opened = true; return false; } void sclose(){ if(!this->opened){ return; } if(kill(this->pid, SIGTERM) < 0){ ERROR("kill shell") } if(close(this->input) < 0){ ERROR("close shell input") } if(close(this->output) < 0){ ERROR("close shell output") } this->opened = false; } };
16.358025
66
0.584906
bwackwat
ff128ff1e530f9ee6cdd776d8fa6bbbbf3ae03f4
2,135
hxx
C++
main/chart2/source/inc/chartview/servicenames_charttypes.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/chart2/source/inc/chartview/servicenames_charttypes.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/chart2/source/inc/chartview/servicenames_charttypes.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef _CHART2_SERVICENAMES_CHARTTYPES_HXX #define _CHART2_SERVICENAMES_CHARTTYPES_HXX //............................................................................. namespace chart { //............................................................................. #define CHART2_VIEW_BARCHART_SERVICE_IMPLEMENTATION_NAME ::rtl::OUString::createFromAscii("com.sun.star.chart2.view.BarChart_Impl") #define CHART2_VIEW_BARCHART_SERVICE_NAME ::rtl::OUString::createFromAscii("com.sun.star.chart2.view.BarChart") #define CHART2_VIEW_PIECHART_SERVICE_IMPLEMENTATION_NAME ::rtl::OUString::createFromAscii("com.sun.star.chart2.view.PieChart_Impl") #define CHART2_VIEW_PIECHART_SERVICE_NAME ::rtl::OUString::createFromAscii("com.sun.star.chart2.view.PieChart") #define CHART2_VIEW_AREACHART_SERVICE_IMPLEMENTATION_NAME ::rtl::OUString::createFromAscii("com.sun.star.chart2.view.AreaChart_Impl") #define CHART2_VIEW_AREACHART_SERVICE_NAME ::rtl::OUString::createFromAscii("com.sun.star.chart2.view.AreaChart") //............................................................................. } //namespace chart //............................................................................. #endif
48.522727
133
0.629508
Grosskopf
ff14623c4a3e531d648f00c5d95c6fcc02d58690
2,679
cc
C++
thirdparty/aria2/test/array_funTest.cc
deltegic/deltegic
9b4f3a505a6842db52efbe850150afbab3af5e2f
[ "BSD-3-Clause" ]
null
null
null
thirdparty/aria2/test/array_funTest.cc
deltegic/deltegic
9b4f3a505a6842db52efbe850150afbab3af5e2f
[ "BSD-3-Clause" ]
2
2021-04-08T08:46:23.000Z
2021-04-08T08:57:58.000Z
thirdparty/aria2/test/array_funTest.cc
deltegic/deltegic
9b4f3a505a6842db52efbe850150afbab3af5e2f
[ "BSD-3-Clause" ]
null
null
null
#include "array_fun.h" #include <cppunit/extensions/HelperMacros.h> using namespace aria2::expr; namespace aria2 { class array_funTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(array_funTest); CPPUNIT_TEST(testArray_negate); CPPUNIT_TEST(testArray_and); CPPUNIT_TEST(testArrayLength); CPPUNIT_TEST(testArrayWrapper); CPPUNIT_TEST_SUITE_END(); public: void testBit_negate(); void testBit_and(); void testArray_negate(); void testArray_and(); void testArrayLength(); void testArrayWrapper(); struct X { int m; }; }; CPPUNIT_TEST_SUITE_REGISTRATION(array_funTest); void array_funTest::testArray_negate() { unsigned char a[] = {0xaa, 0x55}; CPPUNIT_ASSERT_EQUAL((unsigned char)0x55, (~array(a))[0]); CPPUNIT_ASSERT_EQUAL((unsigned char)0xaa, (~array((unsigned char*)a))[1]); CPPUNIT_ASSERT_EQUAL((unsigned char)0xaa, (~~array(a))[0]); CPPUNIT_ASSERT_EQUAL((unsigned char)0x55, (~~array(a))[1]); } void array_funTest::testArray_and() { unsigned char a1[] = {0xaa, 0x55}; unsigned char a2[] = {0x1a, 0x25}; CPPUNIT_ASSERT_EQUAL((unsigned char)0x0a, (array(a1) & array(a2))[0]); CPPUNIT_ASSERT_EQUAL((unsigned char)0x05, (array(a1) & array(a2))[1]); CPPUNIT_ASSERT_EQUAL((unsigned char)0xa0, (array(a1) & ~array(a2))[0]); CPPUNIT_ASSERT_EQUAL((unsigned char)0x50, (array(a1) & ~array(a2))[1]); CPPUNIT_ASSERT_EQUAL((unsigned char)0xa0, (~array(a2) & array(a1))[0]); CPPUNIT_ASSERT_EQUAL((unsigned char)0x50, (~array(a2) & array(a1))[1]); CPPUNIT_ASSERT_EQUAL((unsigned char)0x45, (~array(a1) & ~array(a2))[0]); CPPUNIT_ASSERT_EQUAL((unsigned char)0x8a, (~array(a1) & ~array(a2))[1]); } void array_funTest::testArrayLength() { int64_t ia[] = {1, 2, 3, 4, 5}; CPPUNIT_ASSERT_EQUAL((size_t)5, arraySize(ia)); // This causes compile error under clang and gcc v3.4.3 opensolaris // 5.11 // int64_t zeroLengthArray[] = {}; // CPPUNIT_ASSERT_EQUAL((size_t)0, arraySize(zeroLengthArray)); } namespace { void arrayPtrCast(struct array_funTest::X* x) {} } // namespace namespace { void arrayPtrConstCast(const struct array_funTest::X* x) {} } // namespace namespace { void arrayWrapperConst(const array_wrapper<int, 10>& array) { CPPUNIT_ASSERT_EQUAL(9, array[9]); } } // namespace void array_funTest::testArrayWrapper() { array_wrapper<int, 10> a1; CPPUNIT_ASSERT_EQUAL((size_t)10, a1.size()); for (size_t i = 0; i < a1.size(); ++i) { a1[i] = i; } CPPUNIT_ASSERT_EQUAL(9, a1[9]); array_wrapper<int, 10> a2 = a1; CPPUNIT_ASSERT_EQUAL(9, a2[9]); arrayWrapperConst(a2); array_wrapper<struct X, 10> x1; arrayPtrCast(x1); arrayPtrConstCast(x1); } } // namespace aria2
26.009709
76
0.702128
deltegic
d4300685e603399b0d95c4a51883fd6965c34a02
147
cc
C++
CondFormats/CSCObjects/src/T_EventSetup_CSCBadStrips.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
CondFormats/CSCObjects/src/T_EventSetup_CSCBadStrips.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
CondFormats/CSCObjects/src/T_EventSetup_CSCBadStrips.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include "CondFormats/CSCObjects/interface/CSCBadStrips.h" #include "FWCore/Utilities/interface/typelookup.h" TYPELOOKUP_DATA_REG(CSCBadStrips);
24.5
58
0.836735
nistefan
d4332047cfa3d0a3a68ad938fae594992542c332
1,032
hpp
C++
libvvhd/headers/XIsoline.hpp
rosik/vvflow
87caadf3973b31058a16a1372365ae8a7a157cdb
[ "MIT" ]
29
2020-08-05T16:08:35.000Z
2022-02-21T06:43:01.000Z
libvvhd/headers/XIsoline.hpp
rosik/vvflow
87caadf3973b31058a16a1372365ae8a7a157cdb
[ "MIT" ]
6
2021-01-07T21:29:57.000Z
2021-06-28T20:54:04.000Z
libvvhd/headers/XIsoline.hpp
rosik/vvflow
87caadf3973b31058a16a1372365ae8a7a157cdb
[ "MIT" ]
6
2020-07-24T06:53:54.000Z
2022-01-06T06:12:45.000Z
#pragma once #include "XField.hpp" #include <list> #include <deque> #include <sstream> class XIsoline { public: XIsoline() = delete; XIsoline(const XIsoline&) = delete; XIsoline(XIsoline&&) = delete; XIsoline& operator=(const XIsoline&) = delete; XIsoline& operator=(XIsoline&&) = delete; XIsoline( const XField &field, double vmin, double vmax, double dv ); // ~XIsoline(); friend std::ostream& operator<< (std::ostream& os, const XIsoline&); private: struct TPoint { float x, y; TPoint(): x(0),y(0) {} TPoint(float x, float y): x(x), y(y) {} inline bool operator==(const TPoint &v) const { return (v.x == x) && (v.y == y); } }; typedef std::deque<TPoint> TLine; std::list<TLine> isolines; float xmin, ymin, dxdy; private: void merge_lines(TLine* dst, bool dst_side); void commit_segment(TPoint p1, TPoint p2); void process_rect(float x, float y, float z[5], float C); };
22.933333
72
0.585271
rosik
d4349502e93874e1ef20b7e3d21836fec0a38e0d
6,400
cpp
C++
mysql-server/libbinlogevents/src/compression/iterator.cpp
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/libbinlogevents/src/compression/iterator.cpp
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/libbinlogevents/src/compression/iterator.cpp
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
/* Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <byteorder.h> #include <compression/factory.h> #include <compression/iterator.h> namespace binary_log { namespace transaction { namespace compression { /* purecov: begin inspected */ Iterable_buffer::Iterable_buffer(const char *input_buffer, size_t input_buffer_size) : Iterable_buffer(input_buffer, input_buffer_size, input_buffer_size, CompType::NONE) {} /* purecov: end */ Iterable_buffer::Iterable_buffer( const char *input_buffer, size_t input_buffer_size, size_t decompressed_buffer_size, binary_log::transaction::compression::type comp_algo) : m_compressed_buffer(input_buffer), m_compressed_buffer_size(input_buffer_size), m_decompressed_buffer_size(decompressed_buffer_size) { if (comp_algo != CompType::NONE) { auto res{false}; auto left{0}; m_decoder = Factory::build_decompressor(comp_algo); auto ptr = (unsigned char *)malloc(m_decompressed_buffer_size); m_decoder->set_buffer((unsigned char *)ptr, m_decompressed_buffer_size); // We decompress everything in one go. m_decoder->open(); std::tie(left, res) = m_decoder->decompress( (const unsigned char *)m_compressed_buffer, m_compressed_buffer_size); m_decoder->close(); // Some error happened. Was not able to successfully decompress everything if (res || left > 0) { /* purecov: begin inspected */ free(const_cast<char *>(m_decompressed_buffer)); m_decompressed_buffer = nullptr; m_decompressed_buffer_size = 0; /* purecov: end */ } else { // may have been realloc'ed in the decompressor std::tie(ptr, m_decompressed_buffer_size, std::ignore) = m_decoder->get_buffer(); m_decompressed_buffer = (const char *)ptr; } } else { /* purecov: begin inspected */ m_decompressed_buffer = m_compressed_buffer; m_decompressed_buffer_size = m_compressed_buffer_size; /* purecov: end */ } } Iterable_buffer::~Iterable_buffer() { if (m_decompressed_buffer != m_compressed_buffer) { auto ptr{const_cast<char *>(m_decompressed_buffer)}; free(ptr); m_decompressed_buffer = nullptr; } } Iterable_buffer::iterator::iterator(Iterable_buffer &parent) : m_target{&parent} { m_reader = std::make_unique<binary_log::Event_reader>( m_target->m_decompressed_buffer, m_target->m_decompressed_buffer_size); m_reader->go_to(0); } Iterable_buffer::iterator::iterator(const iterator &rhs) { (*this) = rhs; } Iterable_buffer::iterator::iterator(iterator &&rhs) { (*this) = rhs; } Iterable_buffer::iterator::~iterator() {} Iterable_buffer::iterator &Iterable_buffer::iterator::operator=( const Iterable_buffer::iterator &rhs) { m_target = rhs.m_target; if (rhs.m_target != nullptr) { m_reader = std::make_unique<binary_log::Event_reader>( m_target->m_decompressed_buffer, m_target->m_decompressed_buffer_size); m_reader->go_to(rhs.m_reader->position()); } return (*this); } /* purecov: begin inspected */ Iterable_buffer::iterator &Iterable_buffer::iterator::operator=( Iterable_buffer::iterator &&rhs) { m_target = rhs.m_target; m_reader.swap(rhs.m_reader); rhs.m_target = nullptr; return (*this); } /* purecov: end */ Iterable_buffer::iterator &Iterable_buffer::iterator::operator++() { // advance the previous buffer length if (has_next_buffer()) { auto ptr = m_reader->ptr(); m_reader->forward(EVENT_LEN_OFFSET); uint32_t event_len = m_reader->read_and_letoh<uint32_t>(); m_reader->go_to((ptr - m_reader->buffer()) + event_len); } // now check again if we have reached the end if (!has_next_buffer()) m_reader.reset(nullptr); return (*this); } Iterable_buffer::iterator::reference Iterable_buffer::iterator::operator*() const { if (has_next_buffer()) return m_reader->ptr(); return nullptr; /* purecov: inspected */ } /* purecov: begin inspected */ Iterable_buffer::iterator Iterable_buffer::iterator::operator++(int) { Iterable_buffer::iterator to_return = (*this); ++(*this); return to_return; } /* purecov: end */ /* purecov: begin inspected */ Iterable_buffer::iterator::pointer Iterable_buffer::iterator::operator->() const { return this->operator*(); } /* purecov: end */ bool Iterable_buffer::iterator::operator==( Iterable_buffer::iterator rhs) const { return m_reader == rhs.m_reader || (m_reader != nullptr && rhs.m_reader != nullptr && m_reader->position() == rhs.m_reader->position()); } bool Iterable_buffer::iterator::operator!=( Iterable_buffer::iterator rhs) const { return !((*this) == rhs); } bool Iterable_buffer::iterator::has_next_buffer() const { if (m_reader->has_error() || !m_reader->can_read(LOG_EVENT_MINIMAL_HEADER_LEN)) return false; return true; } Iterable_buffer::iterator Iterable_buffer::begin() { Iterable_buffer::iterator begin{*this}; if (begin.has_next_buffer()) return begin; else return Iterable_buffer::iterator{}; /* purecov: inspected */ } Iterable_buffer::iterator Iterable_buffer::end() { return Iterable_buffer::iterator{}; } } // namespace compression } // namespace transaction } // namespace binary_log
33.333333
79
0.712969
silenc3502
d4361a192dfa105e98ff3b883a7529d0d1b4cdae
1,442
cc
C++
chrome/profiling/profiling_process.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/profiling/profiling_process.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/profiling/profiling_process.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/profiling/profiling_process.h" #include "base/bind.h" #include "base/files/platform_file.h" #include "chrome/common/profiling/profiling_constants.h" #include "chrome/profiling/profiling_globals.h" #include "mojo/public/cpp/system/platform_handle.h" namespace profiling { ProfilingProcess::ProfilingProcess() : binding_(this) {} ProfilingProcess::~ProfilingProcess() {} void ProfilingProcess::EnsureMojoStarted() { if (started_mojo_) return; started_mojo_ = true; control_invitation_ = mojo::edk::IncomingBrokerClientInvitation::AcceptFromCommandLine( mojo::edk::TransportProtocol::kLegacy); binding_.Bind(mojom::ProfilingControlRequest( control_invitation_->ExtractMessagePipe(kProfilingControlPipeName))); } void ProfilingProcess::AttachPipeServer( scoped_refptr<MemlogReceiverPipeServer> server) { server_ = server; } void ProfilingProcess::AddNewSender(mojo::ScopedHandle sender_pipe, int32_t sender_pid) { base::PlatformFile sender_file; MojoResult result = mojo::UnwrapPlatformFile(std::move(sender_pipe), &sender_file); CHECK_EQ(result, MOJO_RESULT_OK); server_->OnNewPipe(base::ScopedPlatformFile(sender_file), sender_pid); } } // namespace profiling
30.680851
75
0.753814
metux
d43ce46ed6cf430880372955c8ab51fc2c09aca2
1,184
cpp
C++
tests/regression/GoToLoops1/test.cpp
SusanTan/noelle
33c9e10a20bc59590c13bf29fb661fc406a9e687
[ "MIT" ]
43
2020-09-04T15:21:40.000Z
2022-03-23T03:53:02.000Z
tests/regression/GoToLoops1/test.cpp
SusanTan/noelle
33c9e10a20bc59590c13bf29fb661fc406a9e687
[ "MIT" ]
15
2020-09-17T18:06:15.000Z
2022-01-24T17:14:36.000Z
tests/regression/GoToLoops1/test.cpp
SusanTan/noelle
33c9e10a20bc59590c13bf29fb661fc406a9e687
[ "MIT" ]
23
2020-09-04T15:50:09.000Z
2022-03-25T13:38:25.000Z
#include <stdio.h> #include <stdlib.h> #include <math.h> void func1(); void func2(); int sccCausing1 = 0; void func1() { if (sccCausing1++ > 2) { sccCausing1 = 0; func2(); } } int sccCausing2 = 1; void func2() { if (sccCausing2++ > 2) { sccCausing2 = 0; func1(); } } int main (int argc, char *argv[]){ if (argc < 2){ fprintf(stderr, "USAGE: %s LOOP_ITERATIONS\n", argv[0]); return -1; } auto iterations = atoll(argv[1]); if (iterations == 0) return 0; LOOP0: auto maxIters2 = iterations; int i = 0, j = 0, k = 0; for (i = 0; i < iterations; ++i) { // Introduce a control flow path from loop 0 to loop 2 if (maxIters2 == 0) { maxIters2 = iterations; } else { j = 0; goto LOOP2; } LOOP1: for (j = 0; j < argc; ++j) { func1(); // LLVM doesn't even identify this as a loop... LOOP2: for (k = 0; k < argc; ++k) { func2(); // Introduce a control flow path from loop 2 to loop 0 if (maxIters2-- == 0) goto LOOP0_NEXT_ITER; } } LOOP0_NEXT_ITER: continue; } printf("%d, %d\n", sccCausing1, sccCausing2); return 0; }
17.411765
62
0.537162
SusanTan
d43dfc6df505945434b5bd67c2e7305fe96bcf7f
7,757
hpp
C++
src/AFQMC/Numerics/ma_small_mat_ops.hpp
djstaros/qmcpack
280f67e638bae280448b47fa618f05b848c530d2
[ "NCSA" ]
null
null
null
src/AFQMC/Numerics/ma_small_mat_ops.hpp
djstaros/qmcpack
280f67e638bae280448b47fa618f05b848c530d2
[ "NCSA" ]
11
2020-05-09T20:57:21.000Z
2020-06-10T00:00:17.000Z
src/AFQMC/Numerics/ma_small_mat_ops.hpp
djstaros/qmcpack
280f67e638bae280448b47fa618f05b848c530d2
[ "NCSA" ]
null
null
null
////////////////////////////////////////////////////////////////////// // This file is distributed under the University of Illinois/NCSA Open Source // License. See LICENSE file in top directory for details. // // Copyright (c) 2016 Jeongnim Kim and QMCPACK developers. // // File developed by: // // File created by: // Miguel A. Morales, moralessilva2@llnl.gov // Lawrence Livermore National Laboratory //////////////////////////////////////////////////////////////////////////////// #ifndef MA_SMALL_MAT_OPS_HPP #define MA_SMALL_MAT_OPS_HPP namespace ma { template<typename T> inline static T D2x2(T const a11, T const a12, T const a21, T const a22) { return a11 * a22 - a21 * a12; } template<typename T> inline static T I2x2(T const a11, T const a12, T const a21, T const a22, T* M) { T det = a11 * a22 - a21 * a12; M[0] = a22 / det; M[1] = -a12 / det; M[2] = -a21 / det; M[3] = a11 / det; return det; } template<typename T, class Mat> inline static T I2x2(T const a11, T const a12, T const a21, T const a22, Mat& M) { T det = a11 * a22 - a21 * a12; M[0][0] = a22 / det; M[0][1] = -a12 / det; M[1][0] = -a21 / det; M[1][1] = a11 / det; return det; } template<typename T> inline static T D3x3(T const a11, T const a12, T const a13, T const a21, T const a22, T const a23, T const a31, T const a32, T const a33) { return (a11 * (a22 * a33 - a32 * a23) - a21 * (a12 * a33 - a32 * a13) + a31 * (a12 * a23 - a22 * a13)); } template<typename T> inline static T I3x3(T const a11, T const a12, T const a13, T const a21, T const a22, T const a23, T const a31, T const a32, T const a33, T* M) { T det = (a11 * (a22 * a33 - a32 * a23) - a21 * (a12 * a33 - a32 * a13) + a31 * (a12 * a23 - a22 * a13)); M[0] = (a22 * a33 - a32 * a23) / det; M[1] = (a13 * a32 - a12 * a33) / det; M[2] = (a12 * a23 - a13 * a22) / det; M[3] = (a23 * a31 - a21 * a33) / det; M[4] = (a11 * a33 - a13 * a31) / det; M[5] = (a13 * a21 - a11 * a23) / det; M[6] = (a21 * a32 - a22 * a31) / det; M[7] = (a12 * a31 - a11 * a32) / det; M[8] = (a11 * a22 - a12 * a21) / det; return det; } template<typename T, class Mat> inline static T I3x3(T const a11, T const a12, T const a13, T const a21, T const a22, T const a23, T const a31, T const a32, T const a33, Mat& M) { T det = (a11 * (a22 * a33 - a32 * a23) - a21 * (a12 * a33 - a32 * a13) + a31 * (a12 * a23 - a22 * a13)); M[0][0] = (a22 * a33 - a32 * a23) / det; M[0][1] = (a13 * a32 - a12 * a33) / det; M[0][2] = (a12 * a23 - a13 * a22) / det; M[1][0] = (a23 * a31 - a21 * a33) / det; M[1][1] = (a11 * a33 - a13 * a31) / det; M[1][2] = (a13 * a21 - a11 * a23) / det; M[2][0] = (a21 * a32 - a22 * a31) / det; M[2][1] = (a12 * a31 - a11 * a32) / det; M[2][2] = (a11 * a22 - a12 * a21) / det; return det; } template<typename T> inline static T D4x4(T const a11, T const a12, T const a13, T const a14, T const a21, T const a22, T const a23, T const a24, T const a31, T const a32, T const a33, T const a34, T const a41, T const a42, T const a43, T const a44) { return (a11 * (a22 * (a33 * a44 - a43 * a34) - a32 * (a23 * a44 - a43 * a24) + a42 * (a23 * a34 - a33 * a24)) - a21 * (a12 * (a33 * a44 - a43 * a34) - a32 * (a13 * a44 - a43 * a14) + a42 * (a13 * a34 - a33 * a14)) + a31 * (a12 * (a23 * a44 - a43 * a24) - a22 * (a13 * a44 - a43 * a14) + a42 * (a13 * a24 - a23 * a14)) - a41 * (a12 * (a23 * a34 - a33 * a24) - a22 * (a13 * a34 - a33 * a14) + a32 * (a13 * a24 - a23 * a14))); } template<typename T> inline static T D5x5(T const a11, T const a12, T const a13, T const a14, T const a15, T const a21, T const a22, T const a23, T const a24, T const a25, T const a31, T const a32, T const a33, T const a34, T const a35, T const a41, T const a42, T const a43, T const a44, T const a45, T const a51, T const a52, T const a53, T const a54, T const a55) { return (a11 * (a22 * (a33 * (a44 * a55 - a54 * a45) - a43 * (a34 * a55 - a54 * a35) + a53 * (a34 * a45 - a44 * a35)) - a32 * (a23 * (a44 * a55 - a54 * a45) - a43 * (a24 * a55 - a54 * a25) + a53 * (a24 * a45 - a44 * a25)) + a42 * (a23 * (a34 * a55 - a54 * a35) - a33 * (a24 * a55 - a54 * a25) + a53 * (a24 * a35 - a34 * a25)) - a52 * (a23 * (a34 * a45 - a44 * a35) - a33 * (a24 * a45 - a44 * a25) + a43 * (a24 * a35 - a34 * a25))) - a21 * (a12 * (a33 * (a44 * a55 - a54 * a45) - a43 * (a34 * a55 - a54 * a35) + a53 * (a34 * a45 - a44 * a35)) - a32 * (a13 * (a44 * a55 - a54 * a45) - a43 * (a14 * a55 - a54 * a15) + a53 * (a14 * a45 - a44 * a15)) + a42 * (a13 * (a34 * a55 - a54 * a35) - a33 * (a14 * a55 - a54 * a15) + a53 * (a14 * a35 - a34 * a15)) - a52 * (a13 * (a34 * a45 - a44 * a35) - a33 * (a14 * a45 - a44 * a15) + a43 * (a14 * a35 - a34 * a15))) + a31 * (a12 * (a23 * (a44 * a55 - a54 * a45) - a43 * (a24 * a55 - a54 * a25) + a53 * (a24 * a45 - a44 * a25)) - a22 * (a13 * (a44 * a55 - a54 * a45) - a43 * (a14 * a55 - a54 * a15) + a53 * (a14 * a45 - a44 * a15)) + a42 * (a13 * (a24 * a55 - a54 * a25) - a23 * (a14 * a55 - a54 * a15) + a53 * (a14 * a25 - a24 * a15)) - a52 * (a13 * (a24 * a45 - a44 * a25) - a23 * (a14 * a45 - a44 * a15) + a43 * (a14 * a25 - a24 * a15))) - a41 * (a12 * (a23 * (a34 * a55 - a54 * a35) - a33 * (a24 * a55 - a54 * a25) + a53 * (a24 * a35 - a34 * a25)) - a22 * (a13 * (a34 * a55 - a54 * a35) - a33 * (a14 * a55 - a54 * a15) + a53 * (a14 * a35 - a34 * a15)) + a32 * (a13 * (a24 * a55 - a54 * a25) - a23 * (a14 * a55 - a54 * a15) + a53 * (a14 * a25 - a24 * a15)) - a52 * (a13 * (a24 * a35 - a34 * a25) - a23 * (a14 * a35 - a34 * a15) + a33 * (a14 * a25 - a24 * a15))) + a51 * (a12 * (a23 * (a34 * a45 - a44 * a35) - a33 * (a24 * a45 - a44 * a25) + a43 * (a24 * a35 - a34 * a25)) - a22 * (a13 * (a34 * a45 - a44 * a35) - a33 * (a14 * a45 - a44 * a15) + a43 * (a14 * a35 - a34 * a15)) + a32 * (a13 * (a24 * a45 - a44 * a25) - a23 * (a14 * a45 - a44 * a15) + a43 * (a14 * a25 - a24 * a15)) - a42 * (a13 * (a24 * a35 - a34 * a25) - a23 * (a14 * a35 - a34 * a15) + a33 * (a14 * a25 - a24 * a15)))); } } // namespace ma #endif
40.401042
119
0.405569
djstaros
d43f88f0da65efa13a81277c2e8a34f637314dfe
3,186
cpp
C++
JAERO/tests/fftwrapper_tests.cpp
Roethenbach/JAERO
753a4409507a356489f3635b93dc16955c8cf01a
[ "MIT" ]
152
2015-12-02T01:38:42.000Z
2022-03-29T10:41:37.000Z
JAERO/tests/fftwrapper_tests.cpp
Roethenbach/JAERO
753a4409507a356489f3635b93dc16955c8cf01a
[ "MIT" ]
59
2015-12-02T02:11:24.000Z
2022-03-21T02:48:11.000Z
JAERO/tests/fftwrapper_tests.cpp
Roethenbach/JAERO
753a4409507a356489f3635b93dc16955c8cf01a
[ "MIT" ]
38
2015-12-07T16:24:03.000Z
2021-12-25T15:44:27.000Z
#include "../fftwrapper.h" #include "../util/RuntimeError.h" #include "../DSP.h" //important for Qt include cpputest last as it mucks up new and causes compiling to fail #include "CppUTest/TestHarness.h" TEST_GROUP(Test_FFTWrapper) { const double doubles_equal_threshold=0.00001; void setup() { srand(1); } void teardown() { // This gets run after every test } }; TEST(Test_FFTWrapper, fftwrapper_matches_unusual_kissfft_scalling_as_expected_by_old_jaero_code_by_default) { //this was obtained from v1.0.4.11 of JAERO QVector<cpx_type> input={cpx_type(-0.997497,0.127171),cpx_type(-0.613392,0.617481),cpx_type(0.170019,-0.040254),cpx_type(-0.299417,0.791925),cpx_type(0.645680,0.493210),cpx_type(-0.651784,0.717887),cpx_type(0.421003,0.027070),cpx_type(-0.392010,-0.970031),cpx_type(-0.817194,-0.271096),cpx_type(-0.705374,-0.668203),cpx_type(0.977050,-0.108615),cpx_type(-0.761834,-0.990661),cpx_type(-0.982177,-0.244240),cpx_type(0.063326,0.142369),cpx_type(0.203528,0.214331),cpx_type(-0.667531,0.326090)}; QVector<cpx_type> expected_forward={cpx_type(-4.407605,0.164434),cpx_type(2.204298,2.308064),cpx_type(-2.713014,-1.356784),cpx_type(-2.347572,1.698848),cpx_type(-2.270577,-0.201056),cpx_type(1.611736,-2.136282),cpx_type(-0.902078,1.606222),cpx_type(0.335445,-0.964384),cpx_type(3.648427,0.230720),cpx_type(-2.707027,-3.571981),cpx_type(-1.023916,-0.474082),cpx_type(1.792787,2.825653),cpx_type(-5.574999,0.226081),cpx_type(1.119577,-1.518164),cpx_type(-1.273769,-1.346937),cpx_type(-3.451670,4.544378)}; QVector<cpx_type> expected_forward_backwards={cpx_type(-15.959960,2.034730),cpx_type(-9.814264,9.879696),cpx_type(2.720298,-0.644063),cpx_type(-4.790674,12.670797),cpx_type(10.330882,7.891354),cpx_type(-10.428541,11.486190),cpx_type(6.736045,0.433119),cpx_type(-6.272164,-15.520493),cpx_type(-13.075106,-4.337535),cpx_type(-11.285989,-10.691244),cpx_type(15.632801,-1.737846),cpx_type(-12.189337,-15.850581),cpx_type(-15.714835,-3.907834),cpx_type(1.013215,2.277902),cpx_type(3.256447,3.429304),cpx_type(-10.680502,5.217444)}; int nfft=input.size(); CHECK(input.size()==nfft); CHECK(expected_forward.size()==nfft); CHECK(expected_forward_backwards.size()==nfft); FFTWrapper<double> fft=FFTWrapper<double>(nfft,false); FFTWrapper<double> ifft=FFTWrapper<double>(nfft,true); QVector<cpx_type> actual_forward,actual_forward_backwards; actual_forward.resize(nfft); actual_forward_backwards.resize(nfft); CHECK(actual_forward.size()==nfft); CHECK(actual_forward_backwards.size()==nfft); fft.transform(input,actual_forward); ifft.transform(actual_forward,actual_forward_backwards); for(int k=0;k<nfft;k++) { DOUBLES_EQUAL(actual_forward[k].real(),expected_forward[k].real(),doubles_equal_threshold); DOUBLES_EQUAL(actual_forward[k].imag(),expected_forward[k].imag(),doubles_equal_threshold); DOUBLES_EQUAL(actual_forward_backwards[k].real(),expected_forward_backwards[k].real(),doubles_equal_threshold); DOUBLES_EQUAL(actual_forward_backwards[k].imag(),expected_forward_backwards[k].imag(),doubles_equal_threshold); } }
57.927273
527
0.743879
Roethenbach
d4403a2e169d36eeb27f9f6322e78bee72d75748
7,420
cpp
C++
examples/pxScene2d/external/WinSparkle/3rdparty/wxWidgets/src/motif/bmpbuttn.cpp
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
471
2019-06-26T09:59:09.000Z
2022-03-30T04:59:42.000Z
examples/pxScene2d/external/WinSparkle/3rdparty/wxWidgets/src/motif/bmpbuttn.cpp
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
1,432
2017-06-21T04:08:48.000Z
2020-08-25T16:21:15.000Z
examples/pxScene2d/external/WinSparkle/3rdparty/wxWidgets/src/motif/bmpbuttn.cpp
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
317
2017-06-20T19:57:17.000Z
2020-09-16T10:28:30.000Z
///////////////////////////////////////////////////////////////////////////// // Name: src/motif/bmpbuttn.cpp // Purpose: wxBitmapButton // Author: Julian Smart // Modified by: // Created: 17/09/98 // Copyright: (c) Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #include "wx/bmpbuttn.h" #ifdef __VMS__ #pragma message disable nosimpint #endif #include <Xm/PushBG.h> #include <Xm/PushB.h> #ifdef __VMS__ #pragma message enable nosimpint #endif #include "wx/motif/private.h" // Implemented in button.cpp void wxButtonCallback (Widget w, XtPointer clientData, XtPointer ptr); // Pixmap XCreateInsensitivePixmap( Display *display, Pixmap pixmap ); wxBitmapButton::wxBitmapButton() { m_marginX = m_marginY = wxDEFAULT_BUTTON_MARGIN; m_insensPixmap = (WXPixmap) 0; } bool wxBitmapButton::Create(wxWindow *parent, wxWindowID id, const wxBitmap& bitmap, const wxPoint& pos, const wxSize& size, long style, const wxValidator& validator, const wxString& name) { if( !CreateControl( parent, id, pos, size, style, validator, name ) ) return false; PreCreation(); m_bitmaps[State_Normal] = m_bitmapsOriginal[State_Normal] = bitmap; m_bitmaps[State_Pressed] = m_bitmapsOriginal[State_Pressed] = bitmap; Widget parentWidget = (Widget) parent->GetClientWidget(); /* * Patch Note (important) * There is no major reason to put a defaultButtonThickness here. * Not requesting it give the ability to put wxButton with a spacing * as small as requested. However, if some button become a DefaultButton, * other buttons are no more aligned -- This is why we set * defaultButtonThickness of ALL buttons belonging to the same wxPanel, * in the ::SetDefaultButton method. */ Widget buttonWidget = XtVaCreateManagedWidget ("button", // Gadget causes problems for default button operation. #if wxUSE_GADGETS xmPushButtonGadgetClass, parentWidget, #else xmPushButtonWidgetClass, parentWidget, #endif // See comment for wxButton::SetDefault // XmNdefaultButtonShadowThickness, 1, XmNrecomputeSize, False, NULL); m_mainWidget = (WXWidget) buttonWidget; XtAddCallback (buttonWidget, XmNactivateCallback, (XtCallbackProc) wxButtonCallback, (XtPointer) this); wxSize best = GetBitmapLabel().IsOk() ? GetBestSize() : wxSize(30, 30); if( size.x != -1 ) best.x = size.x; if( size.y != -1 ) best.y = size.y; PostCreation(); OnSetBitmap(); AttachWidget (parent, m_mainWidget, (WXWidget) NULL, pos.x, pos.y, best.x, best.y); return true; } wxBitmapButton::~wxBitmapButton() { SetBitmapLabel(wxNullBitmap); if (m_insensPixmap) XmDestroyPixmap (DefaultScreenOfDisplay ((Display*) GetXDisplay()), (Pixmap) m_insensPixmap); } void wxBitmapButton::DoSetBitmap(const wxBitmap& bitmap, State which) { m_bitmapsOriginal[which] = bitmap; wxBitmapButtonBase::DoSetBitmap(bitmap, which); } void wxBitmapButton::OnSetBitmap() { wxBitmapButtonBase::OnSetBitmap(); if ( m_bitmapsOriginal[State_Normal].IsOk() ) { Pixmap pixmap = 0; Pixmap insensPixmap = 0; Pixmap armPixmap = 0; // Must re-make the bitmap to have its transparent areas drawn // in the current widget background colour. if ( m_bitmapsOriginal[State_Normal].GetMask() ) { WXPixel backgroundPixel; XtVaGetValues((Widget) m_mainWidget, XmNbackground, &backgroundPixel, NULL); wxColour col; col.SetPixel(backgroundPixel); wxBitmap newBitmap = wxCreateMaskedBitmap(m_bitmapsOriginal[State_Normal], col); m_bitmaps[State_Normal] = newBitmap; m_bitmapCache.SetBitmap( m_bitmaps[State_Normal] ); pixmap = (Pixmap) m_bitmaps[State_Normal].GetDrawable(); } else { m_bitmapCache.SetBitmap( m_bitmaps[State_Normal] ); pixmap = (Pixmap) m_bitmapCache.GetLabelPixmap(m_mainWidget); } if (m_bitmapsOriginal[State_Disabled].IsOk()) { if (m_bitmapsOriginal[State_Disabled].GetMask()) { WXPixel backgroundPixel; XtVaGetValues((Widget) m_mainWidget, XmNbackground, &backgroundPixel, NULL); wxColour col; col.SetPixel(backgroundPixel); wxBitmap newBitmap = wxCreateMaskedBitmap(m_bitmapsOriginal[State_Disabled], col); m_bitmaps[State_Disabled] = newBitmap; insensPixmap = (Pixmap) m_bitmaps[State_Disabled].GetDrawable(); } else insensPixmap = (Pixmap) m_bitmapCache.GetInsensPixmap(m_mainWidget); } else insensPixmap = (Pixmap) m_bitmapCache.GetInsensPixmap(m_mainWidget); // Now make the bitmap representing the armed state if (m_bitmapsOriginal[State_Pressed].IsOk()) { if (m_bitmapsOriginal[State_Pressed].GetMask()) { WXPixel backgroundPixel; XtVaGetValues((Widget) m_mainWidget, XmNarmColor, &backgroundPixel, NULL); wxColour col; col.SetPixel(backgroundPixel); wxBitmap newBitmap = wxCreateMaskedBitmap(m_bitmapsOriginal[State_Pressed], col); m_bitmaps[State_Pressed] = newBitmap; armPixmap = (Pixmap) m_bitmaps[State_Pressed].GetDrawable(); } else armPixmap = (Pixmap) m_bitmapCache.GetArmPixmap(m_mainWidget); } else armPixmap = (Pixmap) m_bitmapCache.GetArmPixmap(m_mainWidget); XtVaSetValues ((Widget) m_mainWidget, XmNlabelPixmap, pixmap, XmNlabelInsensitivePixmap, insensPixmap, XmNarmPixmap, armPixmap, XmNlabelType, XmPIXMAP, NULL); } else { // Null bitmap: must not use current pixmap // since it is no longer valid. XtVaSetValues ((Widget) m_mainWidget, XmNlabelType, XmSTRING, XmNlabelPixmap, XmUNSPECIFIED_PIXMAP, XmNlabelInsensitivePixmap, XmUNSPECIFIED_PIXMAP, XmNarmPixmap, XmUNSPECIFIED_PIXMAP, NULL); } } void wxBitmapButton::ChangeBackgroundColour() { wxDoChangeBackgroundColour(m_mainWidget, m_backgroundColour, true); // Must reset the bitmaps since the colours have changed. OnSetBitmap(); } wxSize wxBitmapButton::DoGetBestSize() const { wxSize ret( 30,30 ); if (GetBitmapLabel().IsOk()) { int border = HasFlag(wxNO_BORDER) ? 4 : 10; ret.x += border; ret.y += border; ret += GetBitmapLabel().GetSize(); } return ret; }
30.916667
84
0.596092
madanagopaltcomcast
d440558273128ecf7d241e3e2ec8c2f1d4cd6ebf
11,989
cpp
C++
src/prog_util.cpp
RabbitBio/RabbitBM
c5cc9e6b23cf1046675a07f2d3eb3a4578f1e96b
[ "MIT" ]
108
2019-05-03T12:36:50.000Z
2022-03-29T04:54:08.000Z
src/prog_util.cpp
RabbitBio/RabbitBM
c5cc9e6b23cf1046675a07f2d3eb3a4578f1e96b
[ "MIT" ]
10
2019-02-12T10:18:38.000Z
2021-07-02T12:21:25.000Z
src/prog_util.cpp
RabbitBio/RabbitBM
c5cc9e6b23cf1046675a07f2d3eb3a4578f1e96b
[ "MIT" ]
13
2019-05-20T15:50:44.000Z
2022-01-07T17:06:13.000Z
/* * prog_util.c - utility functions for programs * * Copyright 2016 Eric Biggers * * 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 "lib/memory.hpp" #include "prog_util.h" #include <errno.h> #include <fcntl.h> #include <stdarg.h> #include <time.h> #ifdef _WIN32 # include <windows.h> #else # include <unistd.h> # include <sys/mman.h> # include <sys/time.h> #endif #ifndef O_BINARY # define O_BINARY 0 #endif #ifndef O_SEQUENTIAL # define O_SEQUENTIAL 0 #endif #ifndef O_NOFOLLOW # define O_NOFOLLOW 0 #endif #ifndef O_NONBLOCK # define O_NONBLOCK 0 #endif #ifndef O_NOCTTY # define O_NOCTTY 0 #endif /* The invocation name of the program (filename component only) */ const tchar* _program_invocation_name; static void do_msg(const char* format, bool with_errno, va_list va) { int saved_errno = errno; fprintf(stderr, "%" TS ": ", program_invocation_name); vfprintf(stderr, format, va); if (with_errno) fprintf(stderr, ": %s\n", strerror(saved_errno)); else fprintf(stderr, "\n"); errno = saved_errno; } /* Print a message to standard error */ void msg(const char* format, ...) { va_list va; va_start(va, format); do_msg(format, false, va); va_end(va); } /* Print a message to standard error, including a description of errno */ void msg_errno(const char* format, ...) { va_list va; va_start(va, format); do_msg(format, true, va); va_end(va); } /* * Return the number of timer ticks that have elapsed since some unspecified * point fixed at the start of program execution */ uint64_t timer_ticks(void) { #ifdef _WIN32 LARGE_INTEGER count; QueryPerformanceCounter(&count); return count.QuadPart; #elif defined(HAVE_CLOCK_GETTIME) struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (1000000000 * (uint64_t)ts.tv_sec) + ts.tv_nsec; #else struct timeval tv; gettimeofday(&tv, nullptr); return (1000000 * uint64_t(tv.tv_sec)) + uint64_t(tv.tv_usec); #endif } /* * Return the number of timer ticks per second */ static uint64_t timer_frequency(void) { #ifdef _WIN32 LARGE_INTEGER freq; QueryPerformanceFrequency(&freq); return freq.QuadPart; #elif defined(HAVE_CLOCK_GETTIME) return 1000000000; #else return 1000000; #endif } /* * Convert a number of elapsed timer ticks to milliseconds */ uint64_t timer_ticks_to_ms(uint64_t ticks) { return ticks * 1000 / timer_frequency(); } /* * Convert a byte count and a number of elapsed timer ticks to MB/s */ uint64_t timer_MB_per_s(uint64_t bytes, uint64_t ticks) { return bytes * timer_frequency() / ticks / 1000000; } /* * Retrieve a pointer to the filename component of the specified path. * * Note: this does not modify the path. Therefore, it is not guaranteed to work * properly for directories, since a path to a directory might have trailing * slashes. */ const tchar* get_filename(const tchar* path) { const tchar* slash = tstrrchr(path, '/'); #ifdef _WIN32 const tchar* backslash = tstrrchr(path, '\\'); if (backslash != nullptr && (slash == nullptr || backslash > slash)) slash = backslash; #endif if (slash != nullptr) return slash + 1; return path; } /* Create a copy of 'path' surrounded by double quotes */ static tchar* quote_path(const tchar* path) { size_t len = tstrlen(path); tchar* result = new tchar[1 + len + 1 + 1]; if (result == nullptr) return nullptr; result[0] = '"'; tmemcpy(&result[1], path, len); result[1 + len] = '"'; result[1 + len + 1] = '\0'; return result; } /* Open a file for reading, or set up standard input for reading */ int xopen_for_read(const tchar* path, bool symlink_ok, struct file_stream* strm) { strm->mmap_token = nullptr; strm->mmap_mem = nullptr; if (path == nullptr) { strm->is_standard_stream = true; strm->name = T("standard input"); strm->fd = STDIN_FILENO; #ifdef _WIN32 _setmode(strm->fd, O_BINARY); #endif return 0; } strm->is_standard_stream = false; strm->name = quote_path(path); if (strm->name == nullptr) return -1; strm->fd = topen(path, O_RDONLY | O_BINARY | O_NONBLOCK | O_NOCTTY | (symlink_ok ? 0 : O_NOFOLLOW) | O_SEQUENTIAL); if (strm->fd < 0) { msg_errno("Can't open %" TS " for reading", strm->name); delete strm->name; return -1; } #if defined(HAVE_POSIX_FADVISE) && (O_SEQUENTIAL == 0) // posix_fadvise(strm->fd, 0, 0, POSIX_FADV_SEQUENTIAL); #endif return 0; } /* Open a file for writing, or set up standard output for writing */ int xopen_for_write(const tchar* path, bool overwrite, struct file_stream* strm) { int ret = -1; strm->mmap_token = nullptr; strm->mmap_mem = nullptr; if (path == nullptr) { strm->is_standard_stream = true; strm->name = T("standard output"); strm->fd = STDOUT_FILENO; #ifdef _WIN32 _setmode(strm->fd, O_BINARY); #endif return 0; } strm->is_standard_stream = false; strm->name = quote_path(path); if (strm->name == nullptr) goto err; retry: strm->fd = topen(path, O_WRONLY | O_BINARY | O_NOFOLLOW | O_CREAT | O_EXCL, 0644); if (strm->fd < 0) { if (errno != EEXIST) { msg_errno("Can't open %" TS " for writing", strm->name); goto err; } if (!overwrite) { if (!isatty(STDERR_FILENO) || !isatty(STDIN_FILENO)) { msg("%" TS " already exists; use -f to overwrite", strm->name); ret = -2; /* warning only */ goto err; } fprintf(stderr, "%" TS ": %" TS " already exists; " "overwrite? (y/n) ", program_invocation_name, strm->name); if (getchar() != 'y') { msg("Not overwriting."); goto err; } } if (tunlink(path) != 0) { msg_errno("Unable to delete %" TS, strm->name); goto err; } goto retry; } return 0; err: delete strm->name; return ret; } #include <vector> /* Read the full contents of a file into memory */ static int read_full_contents(struct file_stream* strm) { size_t filled = 0; size_t capacity = 4096; std::vector<char> buf; ssize_t ret; buf.resize(capacity); do { if (filled == capacity) { if (capacity == SIZE_MAX) goto oom; capacity += std::min(SIZE_MAX - capacity, capacity); buf.resize(capacity); } ret = xread(strm, &buf[filled], capacity - filled); if (ret < 0) goto err; filled += size_t(ret); } while (ret != 0); strm->mmap_mem = &buf[0]; strm->mmap_size = filled; return 0; err: return int(ret); oom: msg("Out of memory! %" TS " is too large to be processed by " "this program as currently implemented.", strm->name); ret = -1; goto err; } /* Map the contents of a file into memory */ int map_file_contents(struct file_stream* strm, uint64_t size) { if (size == 0) /* mmap isn't supported on empty files */ return read_full_contents(strm); if (size > SIZE_MAX) { msg("%" TS " is too large to be processed by this program", strm->name); return -1; } #ifdef _WIN32 strm->mmap_token = CreateFileMapping((HANDLE)(intptr_t)_get_osfhandle(strm->fd), nullptr, PAGE_READONLY, 0, 0, nullptr); if (strm->mmap_token == nullptr) { DWORD err = GetLastError(); if (err == ERROR_BAD_EXE_FORMAT) /* mmap unsupported */ return read_full_contents(strm); msg("Unable create file mapping for %" TS ": Windows error %u", strm->name, (unsigned int)err); return -1; } strm->mmap_mem = MapViewOfFile((HANDLE)strm->mmap_token, FILE_MAP_READ, 0, 0, size); if (strm->mmap_mem == nullptr) { msg("Unable to map %" TS " into memory: Windows error %u", strm->name, (unsigned int)GetLastError()); CloseHandle((HANDLE)strm->mmap_token); return -1; } #else /* _WIN32 */ strm->mmap_mem = mmap(nullptr, size, PROT_READ, MAP_SHARED, strm->fd, 0); if (strm->mmap_mem == MAP_FAILED) { strm->mmap_mem = nullptr; if (errno == ENODEV) /* mmap isn't supported on this file */ return read_full_contents(strm); if (errno == ENOMEM) { msg("%" TS " is too large to be processed by this " "program", strm->name); } else { msg_errno("Unable to map %" TS " into memory", strm->name); } return -1; } madvise_huge(strm->mmap_mem, size); strm->mmap_token = strm; /* anything that's not nullptr */ #endif /* !_WIN32 */ strm->mmap_size = size; return 0; } /* * Read from a file, returning the full count to indicate all bytes were read, a * short count (possibly 0) to indicate EOF, or -1 to indicate error. */ ssize_t xread(struct file_stream* strm, void* buf, size_t count) { char* p = static_cast<char*>(buf); size_t orig_count = count; while (count != 0) { ssize_t res = read(strm->fd, p, std::min(count, size_t(INT_MAX))); if (res == 0) break; if (res < 0) { if (errno == EAGAIN || errno == EINTR) continue; msg_errno("Error reading from %" TS, strm->name); return -1; } p += size_t(res); count -= size_t(res); } return ssize_t(orig_count) - ssize_t(count); } /* Write to a file, returning 0 if all bytes were written or -1 on error */ int full_write(struct file_stream* strm, const void* buf, size_t count) { const char* p = static_cast<const char*>(buf); while (count != 0) { ssize_t res = write(strm->fd, p, std::min(count, size_t(INT_MAX))); if (res <= 0) { msg_errno("Error writing to %" TS, strm->name); return -1; } p += size_t(res); count -= size_t(res); } return 0; } /* Close a file, returning 0 on success or -1 on error */ int xclose(struct file_stream* strm) { int ret = 0; if (!strm->is_standard_stream) { if (close(strm->fd) != 0) { msg_errno("Error closing %" TS, strm->name); ret = -1; } delete[] strm->name; } if (strm->mmap_token != nullptr) { #ifdef _WIN32 UnmapViewOfFile(strm->mmap_mem); CloseHandle((HANDLE)strm->mmap_token); #else munmap(strm->mmap_mem, strm->mmap_size); #endif strm->mmap_token = nullptr; } else { free(strm->mmap_mem); } strm->mmap_mem = nullptr; strm->fd = -1; strm->name = nullptr; return ret; }
26.881166
119
0.609058
RabbitBio
d440af2356c934fd13611eaccc185007e848b38f
2,411
cpp
C++
inorder_traversal.cpp
akhilesh59/Programming-Helpers
c4af814f99fc8288e28fb6fb8fee61acf9549f2c
[ "MIT" ]
null
null
null
inorder_traversal.cpp
akhilesh59/Programming-Helpers
c4af814f99fc8288e28fb6fb8fee61acf9549f2c
[ "MIT" ]
null
null
null
inorder_traversal.cpp
akhilesh59/Programming-Helpers
c4af814f99fc8288e28fb6fb8fee61acf9549f2c
[ "MIT" ]
6
2021-10-21T13:01:30.000Z
2021-10-31T08:29:34.000Z
// RECURSION METHOD // #include <iostream> // using namespace std; // struct Node { // int data; // Node *left, *right; // Node (int data) { // this->data = data; // this->left = this->right = nullptr; // } // }; // // recursion function // void inorder(Node* root) { // if (root == nullptr) // return; // inorder(root->left); // cout << root -> data << " "; // inorder(root->right); // } // int main() { // /* Construct the following tree // 1 // / \ // / \ // 2 3 // / / \ // / / \ // 4 5 6 // / \ // / \ // 7 8 // */ // Node* root = new Node(1); // root->left = new Node(2); // root->right = new Node(3); // root->left->left = new Node(4); // root->right->left = new Node(4); // root->right->right = new Node(4); // root->right->left->left = new Node(4); // root->right->left->right = new Node(4); // inorder(root); // return 0; // } //************************************************************** // Iterative method #include <iostream> #include <stack> using namespace std; struct Node { int data; Node *left, *right; Node(int data) { this->data = data; this->left = this->right = nullptr; } }; void inorderIterative (Node* root) { stack<Node*> stack; Node* curr = root; while (!stack.empty() || curr != nullptr) { if (curr != nullptr) { stack.push(curr) ; curr = curr->left; } else { curr = stack.top(); stack.pop(); cout << curr->data << " "; curr = curr-> right; } } } int main() { /* Construct the following tree 1 / \ / \ 2 3 / / \ / / \ 4 5 6 / \ / \ 7 8 */ Node *root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->right->left = new Node(5); root->right->right = new Node(6); root->right->left->left = new Node(7); root->right->left->right = new Node(8); inorderIterative(root); return 0; }
19.601626
64
0.404811
akhilesh59
d440b79d4eeeecba139bcead65783a7cf67fb3c2
5,961
cpp
C++
kcalg/sec/zk/ffs/ffsa.cpp
kn1ghtc/kctsb
ee0e5b31dbe293dad0fb6ea5acf5da1652e4e733
[ "Apache-2.0" ]
1
2021-03-16T00:10:51.000Z
2021-03-16T00:10:51.000Z
kcalg/sec/zk/ffs/ffsa.cpp
kn1ghtc/kctsb
ee0e5b31dbe293dad0fb6ea5acf5da1652e4e733
[ "Apache-2.0" ]
null
null
null
kcalg/sec/zk/ffs/ffsa.cpp
kn1ghtc/kctsb
ee0e5b31dbe293dad0fb6ea5acf5da1652e4e733
[ "Apache-2.0" ]
null
null
null
#include "ffsa.h" #include "opentsb/kc_sec.h" #include <iostream> /*check GMP number for primality*/ bool ffsa_check_prime(mpz_class p) { int8_t reps = 25; int prob = mpz_probab_prime_p(p.get_mpz_t(), reps); if(prob == 2) return true; else if(prob == 0) return false; else if(prob == 1) { /*REMARK: Instead of increasing the reps(maybe even n number of times) one may run some deterministic prime verification algorithm like AKS to provide a level of certainty. But, since Miller-Rabin is likely or almost definitely destined to return "probably prime", one may also consider going with a deterministic version all along as the speedup may not be achieved through double checking.*/ reps = 50; prob = mpz_probab_prime_p(p.get_mpz_t(), reps); if(prob == 2) return true; else if(prob == 0) return false; else if(prob == 1) return true; } return false; } /*generate random prime couple p,q and derive the modulus n=pq*/ mpz_class ffsa_get_modulus(void) { mpz_class p, q; gmp_randclass r (gmp_randinit_mt); srand(time(NULL)); unsigned long int seed = (unsigned long int) rand(); r.seed(seed); p = r.get_z_bits(1024); q = r.get_z_bits(1024); while(p % 2 == 0 || p % 4 != 3) p = r.get_z_bits(1024); while(q % 2 == 0 || q % 4 != 3) q = r.get_z_bits(1024); while(ffsa_check_prime(p) == false || p % 4 != 3) p = p + 2; while(ffsa_check_prime(q) == false || p == q || q % 4 != 3) q = q + 2; return p * q; } /*get random bool vector of length k*/ bool_vec_t ffsa_get_bool_vector(int8_t k) { bool_vec_t a; a.reserve(k); srand(time(NULL)); for(int8_t i = 0; i < k; i++) a.push_back((bool)rand() % 2); return a; } /*get random coprime vector of length k derived from n*/ mpz_vec_t ffsa_get_secrets(int8_t k, mpz_class n) { mpz_vec_t s; s.reserve(k); gmp_randclass r (gmp_randinit_mt); srand(time(NULL)); unsigned long int seed = (unsigned long int) rand(); r.seed(seed); mpz_class intermediate; for(int8_t i = 0; i < k; i++) { begin: do { intermediate = r.get_z_range(n-1) + 1; } while(gcd(intermediate, n) != 1); for(int8_t j = 0; j < i; j++) if(s[i] == intermediate) goto begin; s.push_back(intermediate); } return s; } /*derive verifier vector from secret vector and modulus*/ mpz_vec_t ffsa_get_verifiers(mpz_vec_t s, mpz_class n) { srand(time(NULL)); mpz_vec_t v; v.reserve(s.size()); mpz_class inter; int8_t sig; for(int8_t i = 0; i < s.size(); i++) { sig = (rand() % 2) ? -1 : 1; inter = s[i] * s[i]; inter = inter % n; inter = sig * inter; v.push_back(inter); } return v; } /*compute verifier constant*/ mpz_class ffsa_compute_x(mpz_class r, int8_t sig, mpz_class n) { mpz_class x = r * r; x = x % n; x = sig * x; return x; } /*compute share number*/ mpz_class ffsa_compute_y(mpz_vec_t s, const bool_vec_t a, mpz_class r, mpz_class n) { if(s.size() != a.size()) return 0; mpz_class y = r; for(int8_t i = 0; i < s.size(); i++) if(a[i]) y = y * s[i]; return y % n; } /*verify share number and verify-vector*/ bool ffsa_verify_values(mpz_class y, mpz_vec_t v, const bool_vec_t a, mpz_class n, mpz_class x) { if(v.size() != a.size() || x == 0) return false; mpz_class verifier = y * y, check = x; verifier = verifier % n; for(int8_t i = 0; i < v.size(); i++) if(a[i]) check = check * v[i]; check = check % n; if(verifier == check || verifier == -1 * check) return true; else return false; } int test_ffsa_main() { /*Example run*/ /*-------- * Setup - *-------- */ /*set number of streams and rounds*/ int8_t k = 6, t = 5; /*derive private primes and modulus*/ mpz_class n = ffsa_get_modulus(); /*derive secrets vector*/ mpz_vec_t s = ffsa_get_secrets(k, n); /*derive derive verifier vector*/ mpz_vec_t v = ffsa_get_verifiers(s, n); /*initialize random generator*/ srand(time(NULL)); gmp_randclass rand_c (gmp_randinit_mt); /*----------------------------- * Prover and verifier dialog - *----------------------------- */ mpz_class r, x, y; int8_t sig; /*round based iteration*/ for(int8_t i = 1; i <= t; i++) { /*-------- * Round - *-------- */ /*REMARK: Round iteration may be too fast for providing sufficient distinct rand seeds generated over the time parameter. Fast computers may require a wait command.*/ /*seed GMP random generator*/ unsigned long int seed = (unsigned long int) rand(); rand_c.seed(seed); /*derive random round constant and sign*/ r = rand_c.get_z_range(n-1) + 1; sig = (rand() % 2) ? -1 : 1; /*derive verifier constant*/ x = ffsa_compute_x(r, sig, n); /*get random bool vector of length k*/ const bool_vec_t a = ffsa_get_bool_vector(k); /*derive share number*/ y = ffsa_compute_y(s, a, r, n); /*single round verification of derived values*/ if(ffsa_verify_values(y, v, a, n, x)) std::cout << "Round " << (int)i << ": Correct\n"; else { std::cout << "####Uncorrect -- Aborted####\n"; return 0; } } /*Complete verification after t successful rounds*/ std::cout << "####Verified####\n"; return 0; }
23.104651
95
0.539171
kn1ghtc
d4436d170cadeeccca596ad6c3768959e9e8d390
3,405
cpp
C++
src/syphon/utils/UUID.cpp
asmodehn/syphon
4d73873547278c5cec353e444cb439ef3c4c28a1
[ "MIT" ]
null
null
null
src/syphon/utils/UUID.cpp
asmodehn/syphon
4d73873547278c5cec353e444cb439ef3c4c28a1
[ "MIT" ]
null
null
null
src/syphon/utils/UUID.cpp
asmodehn/syphon
4d73873547278c5cec353e444cb439ef3c4c28a1
[ "MIT" ]
null
null
null
#include "WkCocos/Utils/UUID.h" #include "cocos/cocos2d.h" //cocos style platform detection #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) //works with MSYS2 MINGW GCC as well #include <locale> #elif (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) #include <uuid/uuid.h> #elif (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) //UUID generation on Android device ( Java calls ) #include <jni.h> #include "platform/android/jni/JniHelper.h" #include <android/log.h> #define LOG_TAG "main" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) #endif namespace WkCocos { std::string UUID::create() { std::string uuid = ""; //platform detection based on cocos #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) //generating UUID ( from Android code ) cocos2d::JniMethodInfo j_randomUUIDMI; CCLOG("Calling java/util/UUID/randomUUID()Ljava/util/UUID;"); if (cocos2d::JniHelper::getStaticMethodInfo(j_randomUUIDMI, "java/util/UUID", "randomUUID", "()Ljava/util/UUID;")) { cocos2d::JniMethodInfo j_UUIDtoStringMI; jobject juuid = j_randomUUIDMI.env->CallStaticObjectMethod(j_randomUUIDMI.classID, j_randomUUIDMI.methodID); CCLOG("Calling java/util/UUID/toString()Ljava/lang/String;"); if (juuid && cocos2d::JniHelper::getMethodInfo(j_UUIDtoStringMI, "java/util/UUID", "toString", "()Ljava/lang/String;")) { jstring uuidjstr = (jstring)j_UUIDtoStringMI.env->CallObjectMethod(juuid, j_UUIDtoStringMI.methodID); const char* uuidcstr = j_UUIDtoStringMI.env->GetStringUTFChars((jstring)uuidjstr, NULL); uuid.assign(uuidcstr); j_UUIDtoStringMI.env->ReleaseStringUTFChars(uuidjstr, uuidcstr); //Here uuid variable is setup with a UUID string. j_UUIDtoStringMI.env->DeleteLocalRef(j_UUIDtoStringMI.classID); j_UUIDtoStringMI.env->DeleteLocalRef(uuidjstr); } j_randomUUIDMI.env->DeleteLocalRef(j_randomUUIDMI.classID); j_randomUUIDMI.env->DeleteLocalRef(juuid); } #elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) ///WIN32 only code !!! from http://src.chromium.org/svn/trunk/src/net/base/keygen_handler_win.cc //generating UUID ::UUID win32_uuid = { 0 }; //std::wstring wuuid; RPC_CSTR rpc_string = NULL; if (RPC_S_OK == UuidCreate(&win32_uuid) && RPC_S_OK == UuidToString(&win32_uuid, &rpc_string)) { //VS2013 implementation uuid.assign(reinterpret_cast<char*>(rpc_string)); //VS2010 implementation // RPC_WSTR is unsigned short*. wchar_t is a built-in type of Visual C++, // so the type cast is necessary. //wuuid.assign(reinterpret_cast<wchar_t*>(rpc_string)); //RpcStringFree(&rpc_string); //uuid = std::wstring_convert<std::codecvt_utf8<wchar_t> >().to_bytes(wuuid); } #elif (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) //TEST CODE !!! uuid_t uuid_impl; int result = uuid_generate_time_safe(uuid_impl); CCLOG("sizeof uuid = %d\n", (int)sizeof uuid_impl); // or: printf("sizeof uuid = %zu\n", sizeof uuid_impl); if (result == 0) { CCLOG("uuid generated safely"); } else { CCLOG("uuid not generated safely"); } for (size_t i = 0; i < sizeof uuid_impl; i ++) { CCLOG("%02x ", uuid_impl[i]); } char strbuf[37]; uuid_unparse_lower(uuid_impl,strbuf); uuid.replace(0,strlen(strbuf),strbuf,strlen(strbuf)); #endif return uuid; } }
31.82243
122
0.698678
asmodehn
d446a9568df176437c55638ff603caf95c5e8191
5,671
hpp
C++
include/uxr/agent/transport/util/InterfaceLinux.hpp
vibnwis/Micro-XRCE-DDS-Agent
57ff677855b75d79657b7c20110241e6c1eec351
[ "Apache-2.0" ]
null
null
null
include/uxr/agent/transport/util/InterfaceLinux.hpp
vibnwis/Micro-XRCE-DDS-Agent
57ff677855b75d79657b7c20110241e6c1eec351
[ "Apache-2.0" ]
null
null
null
include/uxr/agent/transport/util/InterfaceLinux.hpp
vibnwis/Micro-XRCE-DDS-Agent
57ff677855b75d79657b7c20110241e6c1eec351
[ "Apache-2.0" ]
null
null
null
// Copyright 2017-present Proyectos y Sistemas de Mantenimiento SL (eProsima). // // 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 UXR_AGENT_TRANSPORT_UTIL_INTERFACELINUX_HPP_ #define UXR_AGENT_TRANSPORT_UTIL_INTERFACELINUX_HPP_ #include <uxr/agent/transport/util/Interface.hpp> #include <uxr/agent/transport/endpoint/CAN2EndPoint.hpp> #include <uxr/agent/transport/endpoint/IPv4EndPoint.hpp> #include <uxr/agent/transport/endpoint/IPv6EndPoint.hpp> #include <uxr/agent/logger/Logger.hpp> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <ifaddrs.h> namespace eprosima { namespace uxr { namespace util { template<typename E> void get_transport_interfaces( uint16_t agent_port, std::vector<dds::xrce::TransportAddress>& transport_addresses); template<> inline void get_transport_interfaces<CAN2EndPoint>( uint16_t agent_port, std::vector<dds::xrce::TransportAddress>& transport_addresses) { struct ifaddrs* ifaddr; struct ifaddrs* ptr; transport_addresses.clear(); if (-1 != getifaddrs(&ifaddr)) { for (ptr = ifaddr; ptr != nullptr; ptr = ptr->ifa_next) { if (AF_INET == ptr->ifa_addr->sa_family) { dds::xrce::TransportAddressMedium medium_locator; medium_locator.port(agent_port); medium_locator.address( {uint8_t(ptr->ifa_addr->sa_data[2]), uint8_t(ptr->ifa_addr->sa_data[3]), uint8_t(ptr->ifa_addr->sa_data[4]), uint8_t(ptr->ifa_addr->sa_data[5])}); transport_addresses.emplace_back(); transport_addresses.back().medium_locator(medium_locator); UXR_AGENT_LOG_TRACE( UXR_DECORATE_WHITE("interface found"), "address: {}", transport_addresses.back() ); } } } freeifaddrs(ifaddr); } template<> inline void get_transport_interfaces<IPv4EndPoint>( uint16_t agent_port, std::vector<dds::xrce::TransportAddress>& transport_addresses) { struct ifaddrs* ifaddr; struct ifaddrs* ptr; transport_addresses.clear(); if (-1 != getifaddrs(&ifaddr)) { for (ptr = ifaddr; ptr != nullptr; ptr = ptr->ifa_next) { if (AF_INET == ptr->ifa_addr->sa_family) { dds::xrce::TransportAddressMedium medium_locator; medium_locator.port(agent_port); medium_locator.address( {uint8_t(ptr->ifa_addr->sa_data[2]), uint8_t(ptr->ifa_addr->sa_data[3]), uint8_t(ptr->ifa_addr->sa_data[4]), uint8_t(ptr->ifa_addr->sa_data[5])}); transport_addresses.emplace_back(); transport_addresses.back().medium_locator(medium_locator); UXR_AGENT_LOG_TRACE( UXR_DECORATE_WHITE("interface found"), "address: {}", transport_addresses.back() ); } } } freeifaddrs(ifaddr); } template<> inline void get_transport_interfaces<IPv6EndPoint>( uint16_t agent_port, std::vector<dds::xrce::TransportAddress>& transport_addresses) { struct ifaddrs* ifaddr; struct ifaddrs* ptr; transport_addresses.clear(); if (-1 != getifaddrs(&ifaddr)) { for (ptr = ifaddr; ptr != nullptr; ptr = ptr->ifa_next) { if (AF_INET6 == ptr->ifa_addr->sa_family) { dds::xrce::TransportAddressLarge large_locator; large_locator.port(agent_port); struct sockaddr_in6* addr = reinterpret_cast<sockaddr_in6*>(ptr->ifa_addr); large_locator.address( {addr->sin6_addr.s6_addr[0], addr->sin6_addr.s6_addr[1], addr->sin6_addr.s6_addr[2], addr->sin6_addr.s6_addr[3], addr->sin6_addr.s6_addr[4], addr->sin6_addr.s6_addr[5], addr->sin6_addr.s6_addr[6], addr->sin6_addr.s6_addr[7], addr->sin6_addr.s6_addr[8], addr->sin6_addr.s6_addr[9], addr->sin6_addr.s6_addr[10], addr->sin6_addr.s6_addr[11], addr->sin6_addr.s6_addr[12], addr->sin6_addr.s6_addr[13], addr->sin6_addr.s6_addr[14], addr->sin6_addr.s6_addr[15]}); transport_addresses.emplace_back(); transport_addresses.back().large_locator(large_locator); UXR_AGENT_LOG_TRACE( UXR_DECORATE_WHITE("interface found"), "address: {}", transport_addresses.back() ); } } } freeifaddrs(ifaddr); } } // namespace util } // namespace uxr } // namespace eprosima #endif // UXR_AGENT_TRANSPORT_UTIL_INTERFACELINUX_HPP_
33.556213
91
0.588256
vibnwis
d44779df4b7f12d2d13716f781dc7b0b95588ce3
42,472
cpp
C++
lib/AudioGroupPool.cpp
AxioDL/amuse
89986bdd650685261311a87b37f504baee342eff
[ "MIT" ]
36
2016-05-05T21:49:16.000Z
2022-03-20T02:28:41.000Z
lib/AudioGroupPool.cpp
AxioDL/amuse
89986bdd650685261311a87b37f504baee342eff
[ "MIT" ]
10
2016-06-26T21:05:22.000Z
2021-08-14T11:46:55.000Z
lib/AudioGroupPool.cpp
AxioDL/amuse
89986bdd650685261311a87b37f504baee342eff
[ "MIT" ]
5
2016-09-16T08:38:16.000Z
2021-01-08T22:37:52.000Z
#include "amuse/AudioGroupPool.hpp" #include "amuse/AudioGroupData.hpp" #include "amuse/Common.hpp" #include "amuse/Entity.hpp" #include <athena/FileReader.hpp> #include <athena/FileWriter.hpp> #include <athena/MemoryWriter.hpp> #include <athena/VectorWriter.hpp> #include <logvisor/logvisor.hpp> using namespace std::literals; namespace amuse { static logvisor::Module Log("amuse::AudioGroupPool"); struct MakeCmdOp { template <class Tp, class R> static std::unique_ptr<SoundMacro::ICmd> Do(R& r) { std::unique_ptr<SoundMacro::ICmd> ret = std::make_unique<Tp>(); static_cast<Tp&>(*ret).read(r); return ret; } }; struct MakeCopyCmdOp { template <class Tp, class R> static std::unique_ptr<SoundMacro::ICmd> Do(R& r) { return std::make_unique<Tp>(static_cast<const Tp&>(r)); } }; struct MakeDefaultCmdOp { template <class Tp, class R> static std::unique_ptr<SoundMacro::ICmd> Do(R& r) { std::unique_ptr<SoundMacro::ICmd> ret = std::make_unique<Tp>(); if (const SoundMacro::CmdIntrospection* introspection = SoundMacro::GetCmdIntrospection(r)) { for (const auto& field : introspection->m_fields) { if (field.m_name.empty()) { continue; } switch (field.m_tp) { case amuse::SoundMacro::CmdIntrospection::Field::Type::Bool: AccessField<bool>(ret.get(), field) = bool(field.m_default); break; case amuse::SoundMacro::CmdIntrospection::Field::Type::Int8: case amuse::SoundMacro::CmdIntrospection::Field::Type::Choice: AccessField<int8_t>(ret.get(), field) = int8_t(field.m_default); break; case amuse::SoundMacro::CmdIntrospection::Field::Type::UInt8: AccessField<uint8_t>(ret.get(), field) = uint8_t(field.m_default); break; case amuse::SoundMacro::CmdIntrospection::Field::Type::Int16: AccessField<int16_t>(ret.get(), field) = int16_t(field.m_default); break; case amuse::SoundMacro::CmdIntrospection::Field::Type::UInt16: AccessField<uint16_t>(ret.get(), field) = uint16_t(field.m_default); break; case amuse::SoundMacro::CmdIntrospection::Field::Type::Int32: AccessField<int32_t>(ret.get(), field) = int32_t(field.m_default); break; case amuse::SoundMacro::CmdIntrospection::Field::Type::UInt32: AccessField<uint32_t>(ret.get(), field) = uint32_t(field.m_default); break; case amuse::SoundMacro::CmdIntrospection::Field::Type::SoundMacroId: case amuse::SoundMacro::CmdIntrospection::Field::Type::SoundMacroStep: case amuse::SoundMacro::CmdIntrospection::Field::Type::TableId: case amuse::SoundMacro::CmdIntrospection::Field::Type::SampleId: AccessField<SoundMacroIdDNA<athena::Endian::Little>>(ret.get(), field).id = uint16_t(field.m_default); break; default: break; } } } return ret; } }; struct IntrospectCmdOp { template <class Tp> static const SoundMacro::CmdIntrospection* Do(SoundMacro::CmdOp) { return &Tp::Introspective; } }; static bool AtEnd(athena::io::IStreamReader& r) { uint32_t v = r.readUint32Big(); r.seek(-4, athena::SeekOrigin::Current); return v == 0xffffffff; } template <athena::Endian DNAE> AudioGroupPool AudioGroupPool::_AudioGroupPool(athena::io::IStreamReader& r) { AudioGroupPool ret; PoolHeader<DNAE> head; head.read(r); if (head.soundMacrosOffset) { r.seek(head.soundMacrosOffset, athena::SeekOrigin::Begin); while (!AtEnd(r)) { ObjectHeader<DNAE> objHead; atInt64 startPos = r.position(); objHead.read(r); if (SoundMacroId::CurNameDB) SoundMacroId::CurNameDB->registerPair(NameDB::generateName(objHead.objectId, NameDB::Type::SoundMacro), objHead.objectId); auto& macro = ret.m_soundMacros[objHead.objectId.id]; macro = MakeObj<SoundMacro>(); macro->template readCmds<DNAE>(r, objHead.size - 8); r.seek(startPos + objHead.size, athena::SeekOrigin::Begin); } } if (head.tablesOffset) { r.seek(head.tablesOffset, athena::SeekOrigin::Begin); while (!AtEnd(r)) { ObjectHeader<DNAE> objHead; atInt64 startPos = r.position(); objHead.read(r); if (TableId::CurNameDB) TableId::CurNameDB->registerPair(NameDB::generateName(objHead.objectId, NameDB::Type::Table), objHead.objectId); auto& ptr = ret.m_tables[objHead.objectId.id]; switch (objHead.size) { case 0x10: ptr = MakeObj<std::unique_ptr<ITable>>(std::make_unique<ADSR>()); static_cast<ADSR&>(**ptr).read(r); break; case 0x1c: ptr = MakeObj<std::unique_ptr<ITable>>(std::make_unique<ADSRDLS>()); static_cast<ADSRDLS&>(**ptr).read(r); break; default: ptr = MakeObj<std::unique_ptr<ITable>>(std::make_unique<Curve>()); static_cast<Curve&>(**ptr).data.resize(objHead.size - 8); r.readUBytesToBuf(&static_cast<Curve&>(**ptr).data[0], objHead.size - 8); break; } r.seek(startPos + objHead.size, athena::SeekOrigin::Begin); } } if (head.keymapsOffset) { r.seek(head.keymapsOffset, athena::SeekOrigin::Begin); while (!AtEnd(r)) { ObjectHeader<DNAE> objHead; atInt64 startPos = r.position(); objHead.read(r); if (KeymapId::CurNameDB) KeymapId::CurNameDB->registerPair(NameDB::generateName(objHead.objectId, NameDB::Type::Keymap), objHead.objectId); auto& km = ret.m_keymaps[objHead.objectId.id]; km = MakeObj<std::array<Keymap, 128>>(); for (int i = 0; i < 128; ++i) { KeymapDNA<DNAE> kmData; kmData.read(r); (*km)[i] = kmData; } r.seek(startPos + objHead.size, athena::SeekOrigin::Begin); } } if (head.layersOffset) { r.seek(head.layersOffset, athena::SeekOrigin::Begin); while (!AtEnd(r)) { ObjectHeader<DNAE> objHead; atInt64 startPos = r.position(); objHead.read(r); if (LayersId::CurNameDB) LayersId::CurNameDB->registerPair(NameDB::generateName(objHead.objectId, NameDB::Type::Layer), objHead.objectId); auto& lm = ret.m_layers[objHead.objectId.id]; lm = MakeObj<std::vector<LayerMapping>>(); uint32_t count; athena::io::Read<athena::io::PropType::None>::Do<decltype(count), DNAE>({}, count, r); lm->reserve(count); for (uint32_t i = 0; i < count; ++i) { LayerMappingDNA<DNAE> lmData; lmData.read(r); lm->push_back(lmData); } r.seek(startPos + objHead.size, athena::SeekOrigin::Begin); } } return ret; } template AudioGroupPool AudioGroupPool::_AudioGroupPool<athena::Endian::Big>(athena::io::IStreamReader& r); template AudioGroupPool AudioGroupPool::_AudioGroupPool<athena::Endian::Little>(athena::io::IStreamReader& r); AudioGroupPool AudioGroupPool::CreateAudioGroupPool(const AudioGroupData& data) { if (data.getPoolSize() < 16) return {}; athena::io::MemoryReader r(data.getPool(), data.getPoolSize()); switch (data.getDataFormat()) { case DataFormat::PC: return _AudioGroupPool<athena::Endian::Little>(r); default: return _AudioGroupPool<athena::Endian::Big>(r); } } AudioGroupPool AudioGroupPool::CreateAudioGroupPool(std::string_view groupPath) { AudioGroupPool ret; std::string poolPath(groupPath); poolPath += "/!pool.yaml"; athena::io::FileReader fi(poolPath, 32 * 1024, false); if (!fi.hasError()) { athena::io::YAMLDocReader r; if (r.parse(&fi) && r.readString("DNAType") == "amuse::Pool") { if (auto __r = r.enterSubRecord("soundMacros")) { for (const auto& sm : r.getCurNode()->m_mapChildren) { ObjectId macroId = SoundMacroId::CurNameDB->generateId(NameDB::Type::SoundMacro); SoundMacroId::CurNameDB->registerPair(sm.first, macroId); } } if (auto __r = r.enterSubRecord("tables")) { for (const auto& t : r.getCurNode()->m_mapChildren) { if (auto __v = r.enterSubRecord(t.first.c_str())) { ObjectId tableId = TableId::CurNameDB->generateId(NameDB::Type::Table); TableId::CurNameDB->registerPair(t.first, tableId); } } } if (auto __r = r.enterSubRecord("keymaps")) { for (const auto& k : r.getCurNode()->m_mapChildren) if (auto __v = r.enterSubRecord(k.first.c_str())) { ObjectId keymapId = KeymapId::CurNameDB->generateId(NameDB::Type::Keymap); KeymapId::CurNameDB->registerPair(k.first, keymapId); } } if (auto __r = r.enterSubRecord("layers")) { for (const auto& l : r.getCurNode()->m_mapChildren) { size_t mappingCount; if (auto __v = r.enterSubVector(l.first.c_str(), mappingCount)) { ObjectId layersId = LayersId::CurNameDB->generateId(NameDB::Type::Layer); LayersId::CurNameDB->registerPair(l.first, layersId); } } } if (auto __r = r.enterSubRecord("soundMacros")) { ret.m_soundMacros.reserve(r.getCurNode()->m_mapChildren.size()); for (const auto& sm : r.getCurNode()->m_mapChildren) { auto& smOut = ret.m_soundMacros[SoundMacroId::CurNameDB->resolveIdFromName(sm.first)]; smOut = MakeObj<SoundMacro>(); size_t cmdCount; if (auto __v = r.enterSubVector(sm.first.c_str(), cmdCount)) smOut->fromYAML(r, cmdCount); } } if (auto __r = r.enterSubRecord("tables")) { ret.m_tables.reserve(r.getCurNode()->m_mapChildren.size()); for (const auto& t : r.getCurNode()->m_mapChildren) { if (auto __v = r.enterSubRecord(t.first.c_str())) { auto& tableOut = ret.m_tables[TableId::CurNameDB->resolveIdFromName(t.first)]; if (auto __att = r.enterSubRecord("attack")) { __att.leave(); if (auto __vta = r.enterSubRecord("velToAttack")) { __vta.leave(); tableOut = MakeObj<std::unique_ptr<ITable>>(std::make_unique<ADSRDLS>()); static_cast<ADSRDLS&>(**tableOut).read(r); } else { tableOut = MakeObj<std::unique_ptr<ITable>>(std::make_unique<ADSR>()); static_cast<ADSR&>(**tableOut).read(r); } } else if (auto __dat = r.enterSubRecord("data")) { __dat.leave(); tableOut = MakeObj<std::unique_ptr<ITable>>(std::make_unique<Curve>()); static_cast<Curve&>(**tableOut).read(r); } } } } if (auto __r = r.enterSubRecord("keymaps")) { ret.m_keymaps.reserve(r.getCurNode()->m_mapChildren.size()); for (const auto& k : r.getCurNode()->m_mapChildren) { size_t mappingCount; if (auto __v = r.enterSubVector(k.first.c_str(), mappingCount)) { auto& kmOut = ret.m_keymaps[KeymapId::CurNameDB->resolveIdFromName(k.first)]; kmOut = MakeObj<std::array<Keymap, 128>>(); for (size_t i = 0; i < mappingCount && i < 128; ++i) if (auto __r2 = r.enterSubRecord()) (*kmOut)[i].read(r); } } } if (auto __r = r.enterSubRecord("layers")) { ret.m_layers.reserve(r.getCurNode()->m_mapChildren.size()); for (const auto& l : r.getCurNode()->m_mapChildren) { size_t mappingCount; if (auto __v = r.enterSubVector(l.first.c_str(), mappingCount)) { auto& layOut = ret.m_layers[LayersId::CurNameDB->resolveIdFromName(l.first)]; layOut = MakeObj<std::vector<LayerMapping>>(); layOut->reserve(mappingCount); for (size_t lm = 0; lm < mappingCount; ++lm) { if (auto __r2 = r.enterSubRecord()) { layOut->emplace_back(); layOut->back().read(r); } } } } } } } return ret; } int SoundMacro::assertPC(int pc) const { if (pc < 0) return -1; if (size_t(pc) >= m_cmds.size()) { fmt::print(stderr, FMT_STRING("SoundMacro PC bounds exceeded [{}/{}]\n"), pc, int(m_cmds.size())); abort(); } return pc; } template <athena::Endian DNAE> void SoundMacro::readCmds(athena::io::IStreamReader& r, uint32_t size) { uint32_t numCmds = size / 8; m_cmds.reserve(numCmds); for (uint32_t i = 0; i < numCmds; ++i) { uint32_t data[2]; athena::io::Read<athena::io::PropType::None>::Do<decltype(data), DNAE>({}, data, r); athena::io::MemoryReader mr(data, sizeof(data)); m_cmds.push_back(CmdDo<MakeCmdOp, std::unique_ptr<ICmd>>(mr)); } } template void SoundMacro::readCmds<athena::Endian::Big>(athena::io::IStreamReader& r, uint32_t size); template void SoundMacro::readCmds<athena::Endian::Little>(athena::io::IStreamReader& r, uint32_t size); template <athena::Endian DNAE> void SoundMacro::writeCmds(athena::io::IStreamWriter& w) const { for (const auto& cmd : m_cmds) { uint32_t data[2]; athena::io::MemoryWriter mw(reinterpret_cast<uint8_t*>(data), sizeof(data)); mw.writeUByte(uint8_t(cmd->Isa())); cmd->write(mw); athena::io::Write<athena::io::PropType::None>::Do<decltype(data), DNAE>({}, data, w); } } template void SoundMacro::writeCmds<athena::Endian::Big>(athena::io::IStreamWriter& w) const; template void SoundMacro::writeCmds<athena::Endian::Little>(athena::io::IStreamWriter& w) const; void SoundMacro::buildFromPrototype(const SoundMacro& other) { m_cmds.reserve(other.m_cmds.size()); for (auto& cmd : other.m_cmds) m_cmds.push_back(CmdDo<MakeCopyCmdOp, std::unique_ptr<SoundMacro::ICmd>>(*cmd)); } void SoundMacro::toYAML(athena::io::YAMLDocWriter& w) const { for (const auto& c : m_cmds) { if (auto __r2 = w.enterSubRecord()) { w.setStyle(athena::io::YAMLNodeStyle::Flow); w.writeString("cmdOp", SoundMacro::CmdOpToStr(c->Isa())); c->write(w); } } } void SoundMacro::fromYAML(athena::io::YAMLDocReader& r, size_t cmdCount) { m_cmds.reserve(cmdCount); for (size_t c = 0; c < cmdCount; ++c) if (auto __r2 = r.enterSubRecord()) m_cmds.push_back(SoundMacro::CmdDo<MakeCmdOp, std::unique_ptr<SoundMacro::ICmd>>(r)); } const SoundMacro* AudioGroupPool::soundMacro(ObjectId id) const { auto search = m_soundMacros.find(id); if (search == m_soundMacros.cend()) return nullptr; return search->second.get(); } const Keymap* AudioGroupPool::keymap(ObjectId id) const { auto search = m_keymaps.find(id); if (search == m_keymaps.cend()) return nullptr; return search->second.get()->data(); } const std::vector<LayerMapping>* AudioGroupPool::layer(ObjectId id) const { auto search = m_layers.find(id); if (search == m_layers.cend()) return nullptr; return search->second.get(); } const ADSR* AudioGroupPool::tableAsAdsr(ObjectId id) const { auto search = m_tables.find(id); if (search == m_tables.cend() || (*search->second)->Isa() != ITable::Type::ADSR) return nullptr; return static_cast<const ADSR*>((*search->second).get()); } const ADSRDLS* AudioGroupPool::tableAsAdsrDLS(ObjectId id) const { auto search = m_tables.find(id); if (search == m_tables.cend() || (*search->second)->Isa() != ITable::Type::ADSRDLS) return nullptr; return static_cast<const ADSRDLS*>((*search->second).get()); } const Curve* AudioGroupPool::tableAsCurves(ObjectId id) const { auto search = m_tables.find(id); if (search == m_tables.cend() || (*search->second)->Isa() != ITable::Type::Curve) return nullptr; return static_cast<const Curve*>((*search->second).get()); } static SoundMacro::CmdOp _ReadCmdOp(athena::io::MemoryReader& r) { return SoundMacro::CmdOp(r.readUByte()); } static SoundMacro::CmdOp _ReadCmdOp(athena::io::YAMLDocReader& r) { return SoundMacro::CmdStrToOp(r.readString("cmdOp")); } static SoundMacro::CmdOp _ReadCmdOp(SoundMacro::CmdOp& op) { return op; } static SoundMacro::CmdOp _ReadCmdOp(const SoundMacro::ICmd& op) { return op.Isa(); } template <class Op, class O, class... _Args> O SoundMacro::CmdDo(_Args&&... args) { SoundMacro::CmdOp op = _ReadCmdOp(std::forward<_Args>(args)...); switch (op) { case CmdOp::End: return Op::template Do<CmdEnd>(std::forward<_Args>(args)...); case CmdOp::Stop: return Op::template Do<CmdStop>(std::forward<_Args>(args)...); case CmdOp::SplitKey: return Op::template Do<CmdSplitKey>(std::forward<_Args>(args)...); case CmdOp::SplitVel: return Op::template Do<CmdSplitVel>(std::forward<_Args>(args)...); case CmdOp::WaitTicks: return Op::template Do<CmdWaitTicks>(std::forward<_Args>(args)...); case CmdOp::Loop: return Op::template Do<CmdLoop>(std::forward<_Args>(args)...); case CmdOp::Goto: return Op::template Do<CmdGoto>(std::forward<_Args>(args)...); case CmdOp::WaitMs: return Op::template Do<CmdWaitMs>(std::forward<_Args>(args)...); case CmdOp::PlayMacro: return Op::template Do<CmdPlayMacro>(std::forward<_Args>(args)...); case CmdOp::SendKeyOff: return Op::template Do<CmdSendKeyOff>(std::forward<_Args>(args)...); case CmdOp::SplitMod: return Op::template Do<CmdSplitMod>(std::forward<_Args>(args)...); case CmdOp::PianoPan: return Op::template Do<CmdPianoPan>(std::forward<_Args>(args)...); case CmdOp::SetAdsr: return Op::template Do<CmdSetAdsr>(std::forward<_Args>(args)...); case CmdOp::ScaleVolume: return Op::template Do<CmdScaleVolume>(std::forward<_Args>(args)...); case CmdOp::Panning: return Op::template Do<CmdPanning>(std::forward<_Args>(args)...); case CmdOp::Envelope: return Op::template Do<CmdEnvelope>(std::forward<_Args>(args)...); case CmdOp::StartSample: return Op::template Do<CmdStartSample>(std::forward<_Args>(args)...); case CmdOp::StopSample: return Op::template Do<CmdStopSample>(std::forward<_Args>(args)...); case CmdOp::KeyOff: return Op::template Do<CmdKeyOff>(std::forward<_Args>(args)...); case CmdOp::SplitRnd: return Op::template Do<CmdSplitRnd>(std::forward<_Args>(args)...); case CmdOp::FadeIn: return Op::template Do<CmdFadeIn>(std::forward<_Args>(args)...); case CmdOp::Spanning: return Op::template Do<CmdSpanning>(std::forward<_Args>(args)...); case CmdOp::SetAdsrCtrl: return Op::template Do<CmdSetAdsrCtrl>(std::forward<_Args>(args)...); case CmdOp::RndNote: return Op::template Do<CmdRndNote>(std::forward<_Args>(args)...); case CmdOp::AddNote: return Op::template Do<CmdAddNote>(std::forward<_Args>(args)...); case CmdOp::SetNote: return Op::template Do<CmdSetNote>(std::forward<_Args>(args)...); case CmdOp::LastNote: return Op::template Do<CmdLastNote>(std::forward<_Args>(args)...); case CmdOp::Portamento: return Op::template Do<CmdPortamento>(std::forward<_Args>(args)...); case CmdOp::Vibrato: return Op::template Do<CmdVibrato>(std::forward<_Args>(args)...); case CmdOp::PitchSweep1: return Op::template Do<CmdPitchSweep1>(std::forward<_Args>(args)...); case CmdOp::PitchSweep2: return Op::template Do<CmdPitchSweep2>(std::forward<_Args>(args)...); case CmdOp::SetPitch: return Op::template Do<CmdSetPitch>(std::forward<_Args>(args)...); case CmdOp::SetPitchAdsr: return Op::template Do<CmdSetPitchAdsr>(std::forward<_Args>(args)...); case CmdOp::ScaleVolumeDLS: return Op::template Do<CmdScaleVolumeDLS>(std::forward<_Args>(args)...); case CmdOp::Mod2Vibrange: return Op::template Do<CmdMod2Vibrange>(std::forward<_Args>(args)...); case CmdOp::SetupTremolo: return Op::template Do<CmdSetupTremolo>(std::forward<_Args>(args)...); case CmdOp::Return: return Op::template Do<CmdReturn>(std::forward<_Args>(args)...); case CmdOp::GoSub: return Op::template Do<CmdGoSub>(std::forward<_Args>(args)...); case CmdOp::TrapEvent: return Op::template Do<CmdTrapEvent>(std::forward<_Args>(args)...); case CmdOp::UntrapEvent: return Op::template Do<CmdUntrapEvent>(std::forward<_Args>(args)...); case CmdOp::SendMessage: return Op::template Do<CmdSendMessage>(std::forward<_Args>(args)...); case CmdOp::GetMessage: return Op::template Do<CmdGetMessage>(std::forward<_Args>(args)...); case CmdOp::GetVid: return Op::template Do<CmdGetVid>(std::forward<_Args>(args)...); case CmdOp::AddAgeCount: return Op::template Do<CmdAddAgeCount>(std::forward<_Args>(args)...); case CmdOp::SetAgeCount: return Op::template Do<CmdSetAgeCount>(std::forward<_Args>(args)...); case CmdOp::SendFlag: return Op::template Do<CmdSendFlag>(std::forward<_Args>(args)...); case CmdOp::PitchWheelR: return Op::template Do<CmdPitchWheelR>(std::forward<_Args>(args)...); case CmdOp::SetPriority: return Op::template Do<CmdSetPriority>(std::forward<_Args>(args)...); case CmdOp::AddPriority: return Op::template Do<CmdAddPriority>(std::forward<_Args>(args)...); case CmdOp::AgeCntSpeed: return Op::template Do<CmdAgeCntSpeed>(std::forward<_Args>(args)...); case CmdOp::AgeCntVel: return Op::template Do<CmdAgeCntVel>(std::forward<_Args>(args)...); case CmdOp::VolSelect: return Op::template Do<CmdVolSelect>(std::forward<_Args>(args)...); case CmdOp::PanSelect: return Op::template Do<CmdPanSelect>(std::forward<_Args>(args)...); case CmdOp::PitchWheelSelect: return Op::template Do<CmdPitchWheelSelect>(std::forward<_Args>(args)...); case CmdOp::ModWheelSelect: return Op::template Do<CmdModWheelSelect>(std::forward<_Args>(args)...); case CmdOp::PedalSelect: return Op::template Do<CmdPedalSelect>(std::forward<_Args>(args)...); case CmdOp::PortamentoSelect: return Op::template Do<CmdPortamentoSelect>(std::forward<_Args>(args)...); case CmdOp::ReverbSelect: return Op::template Do<CmdReverbSelect>(std::forward<_Args>(args)...); case CmdOp::SpanSelect: return Op::template Do<CmdSpanSelect>(std::forward<_Args>(args)...); case CmdOp::DopplerSelect: return Op::template Do<CmdDopplerSelect>(std::forward<_Args>(args)...); case CmdOp::TremoloSelect: return Op::template Do<CmdTremoloSelect>(std::forward<_Args>(args)...); case CmdOp::PreASelect: return Op::template Do<CmdPreASelect>(std::forward<_Args>(args)...); case CmdOp::PreBSelect: return Op::template Do<CmdPreBSelect>(std::forward<_Args>(args)...); case CmdOp::PostBSelect: return Op::template Do<CmdPostBSelect>(std::forward<_Args>(args)...); case CmdOp::AuxAFXSelect: return Op::template Do<CmdAuxAFXSelect>(std::forward<_Args>(args)...); case CmdOp::AuxBFXSelect: return Op::template Do<CmdAuxBFXSelect>(std::forward<_Args>(args)...); case CmdOp::SetupLFO: return Op::template Do<CmdSetupLFO>(std::forward<_Args>(args)...); case CmdOp::ModeSelect: return Op::template Do<CmdModeSelect>(std::forward<_Args>(args)...); case CmdOp::SetKeygroup: return Op::template Do<CmdSetKeygroup>(std::forward<_Args>(args)...); case CmdOp::SRCmodeSelect: return Op::template Do<CmdSRCmodeSelect>(std::forward<_Args>(args)...); case CmdOp::WiiUnknown: return Op::template Do<CmdWiiUnknown>(std::forward<_Args>(args)...); case CmdOp::WiiUnknown2: return Op::template Do<CmdWiiUnknown2>(std::forward<_Args>(args)...); case CmdOp::AddVars: return Op::template Do<CmdAddVars>(std::forward<_Args>(args)...); case CmdOp::SubVars: return Op::template Do<CmdSubVars>(std::forward<_Args>(args)...); case CmdOp::MulVars: return Op::template Do<CmdMulVars>(std::forward<_Args>(args)...); case CmdOp::DivVars: return Op::template Do<CmdDivVars>(std::forward<_Args>(args)...); case CmdOp::AddIVars: return Op::template Do<CmdAddIVars>(std::forward<_Args>(args)...); case CmdOp::SetVar: return Op::template Do<CmdSetVar>(std::forward<_Args>(args)...); case CmdOp::IfEqual: return Op::template Do<CmdIfEqual>(std::forward<_Args>(args)...); case CmdOp::IfLess: return Op::template Do<CmdIfLess>(std::forward<_Args>(args)...); default: return {}; } } template std::unique_ptr<SoundMacro::ICmd> SoundMacro::CmdDo<MakeCmdOp>(athena::io::MemoryReader& r); template std::unique_ptr<SoundMacro::ICmd> SoundMacro::CmdDo<MakeCmdOp>(athena::io::YAMLDocReader& r); template std::unique_ptr<SoundMacro::ICmd> SoundMacro::CmdDo<MakeDefaultCmdOp>(SoundMacro::CmdOp& r); template const SoundMacro::CmdIntrospection* SoundMacro::CmdDo<IntrospectCmdOp>(SoundMacro::CmdOp& op); std::unique_ptr<SoundMacro::ICmd> SoundMacro::MakeCmd(CmdOp op) { return CmdDo<MakeDefaultCmdOp, std::unique_ptr<SoundMacro::ICmd>>(op); } const SoundMacro::CmdIntrospection* SoundMacro::GetCmdIntrospection(CmdOp op) { return CmdDo<IntrospectCmdOp, const SoundMacro::CmdIntrospection*>(op); } std::string_view SoundMacro::CmdOpToStr(CmdOp op) { switch (op) { case CmdOp::End: return "End"sv; case CmdOp::Stop: return "Stop"sv; case CmdOp::SplitKey: return "SplitKey"sv; case CmdOp::SplitVel: return "SplitVel"sv; case CmdOp::WaitTicks: return "WaitTicks"sv; case CmdOp::Loop: return "Loop"sv; case CmdOp::Goto: return "Goto"sv; case CmdOp::WaitMs: return "WaitMs"sv; case CmdOp::PlayMacro: return "PlayMacro"sv; case CmdOp::SendKeyOff: return "SendKeyOff"sv; case CmdOp::SplitMod: return "SplitMod"sv; case CmdOp::PianoPan: return "PianoPan"sv; case CmdOp::SetAdsr: return "SetAdsr"sv; case CmdOp::ScaleVolume: return "ScaleVolume"sv; case CmdOp::Panning: return "Panning"sv; case CmdOp::Envelope: return "Envelope"sv; case CmdOp::StartSample: return "StartSample"sv; case CmdOp::StopSample: return "StopSample"sv; case CmdOp::KeyOff: return "KeyOff"sv; case CmdOp::SplitRnd: return "SplitRnd"sv; case CmdOp::FadeIn: return "FadeIn"sv; case CmdOp::Spanning: return "Spanning"sv; case CmdOp::SetAdsrCtrl: return "SetAdsrCtrl"sv; case CmdOp::RndNote: return "RndNote"sv; case CmdOp::AddNote: return "AddNote"sv; case CmdOp::SetNote: return "SetNote"sv; case CmdOp::LastNote: return "LastNote"sv; case CmdOp::Portamento: return "Portamento"sv; case CmdOp::Vibrato: return "Vibrato"sv; case CmdOp::PitchSweep1: return "PitchSweep1"sv; case CmdOp::PitchSweep2: return "PitchSweep2"sv; case CmdOp::SetPitch: return "SetPitch"sv; case CmdOp::SetPitchAdsr: return "SetPitchAdsr"sv; case CmdOp::ScaleVolumeDLS: return "ScaleVolumeDLS"sv; case CmdOp::Mod2Vibrange: return "Mod2Vibrange"sv; case CmdOp::SetupTremolo: return "SetupTremolo"sv; case CmdOp::Return: return "Return"sv; case CmdOp::GoSub: return "GoSub"sv; case CmdOp::TrapEvent: return "TrapEvent"sv; case CmdOp::UntrapEvent: return "UntrapEvent"sv; case CmdOp::SendMessage: return "SendMessage"sv; case CmdOp::GetMessage: return "GetMessage"sv; case CmdOp::GetVid: return "GetVid"sv; case CmdOp::AddAgeCount: return "AddAgeCount"sv; case CmdOp::SetAgeCount: return "SetAgeCount"sv; case CmdOp::SendFlag: return "SendFlag"sv; case CmdOp::PitchWheelR: return "PitchWheelR"sv; case CmdOp::SetPriority: return "SetPriority"sv; case CmdOp::AddPriority: return "AddPriority"sv; case CmdOp::AgeCntSpeed: return "AgeCntSpeed"sv; case CmdOp::AgeCntVel: return "AgeCntVel"sv; case CmdOp::VolSelect: return "VolSelect"sv; case CmdOp::PanSelect: return "PanSelect"sv; case CmdOp::PitchWheelSelect: return "PitchWheelSelect"sv; case CmdOp::ModWheelSelect: return "ModWheelSelect"sv; case CmdOp::PedalSelect: return "PedalSelect"sv; case CmdOp::PortamentoSelect: return "PortamentoSelect"sv; case CmdOp::ReverbSelect: return "ReverbSelect"sv; case CmdOp::SpanSelect: return "SpanSelect"sv; case CmdOp::DopplerSelect: return "DopplerSelect"sv; case CmdOp::TremoloSelect: return "TremoloSelect"sv; case CmdOp::PreASelect: return "PreASelect"sv; case CmdOp::PreBSelect: return "PreBSelect"sv; case CmdOp::PostBSelect: return "PostBSelect"sv; case CmdOp::AuxAFXSelect: return "AuxAFXSelect"sv; case CmdOp::AuxBFXSelect: return "AuxBFXSelect"sv; case CmdOp::SetupLFO: return "SetupLFO"sv; case CmdOp::ModeSelect: return "ModeSelect"sv; case CmdOp::SetKeygroup: return "SetKeygroup"sv; case CmdOp::SRCmodeSelect: return "SRCmodeSelect"sv; case CmdOp::WiiUnknown: return "WiiUnknown"sv; case CmdOp::WiiUnknown2: return "WiiUnknown2"sv; case CmdOp::AddVars: return "AddVars"sv; case CmdOp::SubVars: return "SubVars"sv; case CmdOp::MulVars: return "MulVars"sv; case CmdOp::DivVars: return "DivVars"sv; case CmdOp::AddIVars: return "AddIVars"sv; case CmdOp::SetVar: return "SetVar"sv; case CmdOp::IfEqual: return "IfEqual"sv; case CmdOp::IfLess: return "IfLess"sv; default: return ""sv; } } SoundMacro::CmdOp SoundMacro::CmdStrToOp(std::string_view op) { if (!CompareCaseInsensitive(op.data(), "End")) return CmdOp::End; else if (!CompareCaseInsensitive(op.data(), "Stop")) return CmdOp::Stop; else if (!CompareCaseInsensitive(op.data(), "SplitKey")) return CmdOp::SplitKey; else if (!CompareCaseInsensitive(op.data(), "SplitVel")) return CmdOp::SplitVel; else if (!CompareCaseInsensitive(op.data(), "WaitTicks")) return CmdOp::WaitTicks; else if (!CompareCaseInsensitive(op.data(), "Loop")) return CmdOp::Loop; else if (!CompareCaseInsensitive(op.data(), "Goto")) return CmdOp::Goto; else if (!CompareCaseInsensitive(op.data(), "WaitMs")) return CmdOp::WaitMs; else if (!CompareCaseInsensitive(op.data(), "PlayMacro")) return CmdOp::PlayMacro; else if (!CompareCaseInsensitive(op.data(), "SendKeyOff")) return CmdOp::SendKeyOff; else if (!CompareCaseInsensitive(op.data(), "SplitMod")) return CmdOp::SplitMod; else if (!CompareCaseInsensitive(op.data(), "PianoPan")) return CmdOp::PianoPan; else if (!CompareCaseInsensitive(op.data(), "SetAdsr")) return CmdOp::SetAdsr; else if (!CompareCaseInsensitive(op.data(), "ScaleVolume")) return CmdOp::ScaleVolume; else if (!CompareCaseInsensitive(op.data(), "Panning")) return CmdOp::Panning; else if (!CompareCaseInsensitive(op.data(), "Envelope")) return CmdOp::Envelope; else if (!CompareCaseInsensitive(op.data(), "StartSample")) return CmdOp::StartSample; else if (!CompareCaseInsensitive(op.data(), "StopSample")) return CmdOp::StopSample; else if (!CompareCaseInsensitive(op.data(), "KeyOff")) return CmdOp::KeyOff; else if (!CompareCaseInsensitive(op.data(), "SplitRnd")) return CmdOp::SplitRnd; else if (!CompareCaseInsensitive(op.data(), "FadeIn")) return CmdOp::FadeIn; else if (!CompareCaseInsensitive(op.data(), "Spanning")) return CmdOp::Spanning; else if (!CompareCaseInsensitive(op.data(), "SetAdsrCtrl")) return CmdOp::SetAdsrCtrl; else if (!CompareCaseInsensitive(op.data(), "RndNote")) return CmdOp::RndNote; else if (!CompareCaseInsensitive(op.data(), "AddNote")) return CmdOp::AddNote; else if (!CompareCaseInsensitive(op.data(), "SetNote")) return CmdOp::SetNote; else if (!CompareCaseInsensitive(op.data(), "LastNote")) return CmdOp::LastNote; else if (!CompareCaseInsensitive(op.data(), "Portamento")) return CmdOp::Portamento; else if (!CompareCaseInsensitive(op.data(), "Vibrato")) return CmdOp::Vibrato; else if (!CompareCaseInsensitive(op.data(), "PitchSweep1")) return CmdOp::PitchSweep1; else if (!CompareCaseInsensitive(op.data(), "PitchSweep2")) return CmdOp::PitchSweep2; else if (!CompareCaseInsensitive(op.data(), "SetPitch")) return CmdOp::SetPitch; else if (!CompareCaseInsensitive(op.data(), "SetPitchAdsr")) return CmdOp::SetPitchAdsr; else if (!CompareCaseInsensitive(op.data(), "ScaleVolumeDLS")) return CmdOp::ScaleVolumeDLS; else if (!CompareCaseInsensitive(op.data(), "Mod2Vibrange")) return CmdOp::Mod2Vibrange; else if (!CompareCaseInsensitive(op.data(), "SetupTremolo")) return CmdOp::SetupTremolo; else if (!CompareCaseInsensitive(op.data(), "Return")) return CmdOp::Return; else if (!CompareCaseInsensitive(op.data(), "GoSub")) return CmdOp::GoSub; else if (!CompareCaseInsensitive(op.data(), "TrapEvent")) return CmdOp::TrapEvent; else if (!CompareCaseInsensitive(op.data(), "UntrapEvent")) return CmdOp::UntrapEvent; else if (!CompareCaseInsensitive(op.data(), "SendMessage")) return CmdOp::SendMessage; else if (!CompareCaseInsensitive(op.data(), "GetMessage")) return CmdOp::GetMessage; else if (!CompareCaseInsensitive(op.data(), "GetVid")) return CmdOp::GetVid; else if (!CompareCaseInsensitive(op.data(), "AddAgeCount")) return CmdOp::AddAgeCount; else if (!CompareCaseInsensitive(op.data(), "SetAgeCount")) return CmdOp::SetAgeCount; else if (!CompareCaseInsensitive(op.data(), "SendFlag")) return CmdOp::SendFlag; else if (!CompareCaseInsensitive(op.data(), "PitchWheelR")) return CmdOp::PitchWheelR; else if (!CompareCaseInsensitive(op.data(), "SetPriority")) return CmdOp::SetPriority; else if (!CompareCaseInsensitive(op.data(), "AddPriority")) return CmdOp::AddPriority; else if (!CompareCaseInsensitive(op.data(), "AgeCntSpeed")) return CmdOp::AgeCntSpeed; else if (!CompareCaseInsensitive(op.data(), "AgeCntVel")) return CmdOp::AgeCntVel; else if (!CompareCaseInsensitive(op.data(), "VolSelect")) return CmdOp::VolSelect; else if (!CompareCaseInsensitive(op.data(), "PanSelect")) return CmdOp::PanSelect; else if (!CompareCaseInsensitive(op.data(), "PitchWheelSelect")) return CmdOp::PitchWheelSelect; else if (!CompareCaseInsensitive(op.data(), "ModWheelSelect")) return CmdOp::ModWheelSelect; else if (!CompareCaseInsensitive(op.data(), "PedalSelect")) return CmdOp::PedalSelect; else if (!CompareCaseInsensitive(op.data(), "PortamentoSelect")) return CmdOp::PortamentoSelect; else if (!CompareCaseInsensitive(op.data(), "ReverbSelect")) return CmdOp::ReverbSelect; else if (!CompareCaseInsensitive(op.data(), "SpanSelect")) return CmdOp::SpanSelect; else if (!CompareCaseInsensitive(op.data(), "DopplerSelect")) return CmdOp::DopplerSelect; else if (!CompareCaseInsensitive(op.data(), "TremoloSelect")) return CmdOp::TremoloSelect; else if (!CompareCaseInsensitive(op.data(), "PreASelect")) return CmdOp::PreASelect; else if (!CompareCaseInsensitive(op.data(), "PreBSelect")) return CmdOp::PreBSelect; else if (!CompareCaseInsensitive(op.data(), "PostBSelect")) return CmdOp::PostBSelect; else if (!CompareCaseInsensitive(op.data(), "AuxAFXSelect")) return CmdOp::AuxAFXSelect; else if (!CompareCaseInsensitive(op.data(), "AuxBFXSelect")) return CmdOp::AuxBFXSelect; else if (!CompareCaseInsensitive(op.data(), "SetupLFO")) return CmdOp::SetupLFO; else if (!CompareCaseInsensitive(op.data(), "ModeSelect")) return CmdOp::ModeSelect; else if (!CompareCaseInsensitive(op.data(), "SetKeygroup")) return CmdOp::SetKeygroup; else if (!CompareCaseInsensitive(op.data(), "SRCmodeSelect")) return CmdOp::SRCmodeSelect; else if (!CompareCaseInsensitive(op.data(), "WiiUnknown")) return CmdOp::WiiUnknown; else if (!CompareCaseInsensitive(op.data(), "WiiUnknown2")) return CmdOp::WiiUnknown2; else if (!CompareCaseInsensitive(op.data(), "AddVars")) return CmdOp::AddVars; else if (!CompareCaseInsensitive(op.data(), "SubVars")) return CmdOp::SubVars; else if (!CompareCaseInsensitive(op.data(), "MulVars")) return CmdOp::MulVars; else if (!CompareCaseInsensitive(op.data(), "DivVars")) return CmdOp::DivVars; else if (!CompareCaseInsensitive(op.data(), "AddIVars")) return CmdOp::AddIVars; else if (!CompareCaseInsensitive(op.data(), "SetVar")) return CmdOp::SetVar; else if (!CompareCaseInsensitive(op.data(), "IfEqual")) return CmdOp::IfEqual; else if (!CompareCaseInsensitive(op.data(), "IfLess")) return CmdOp::IfLess; return CmdOp::Invalid; } std::vector<uint8_t> AudioGroupPool::toYAML() const { athena::io::YAMLDocWriter w("amuse::Pool"); if (!m_soundMacros.empty()) { if (auto __r = w.enterSubRecord("soundMacros")) { for (const auto& p : SortUnorderedMap(m_soundMacros)) { if (auto __v = w.enterSubVector(SoundMacroId::CurNameDB->resolveNameFromId(p.first))) { p.second.get()->toYAML(w); } } } } if (!m_tables.empty()) { if (auto __r = w.enterSubRecord("tables")) { for (const auto& p : SortUnorderedMap(m_tables)) { if (auto __v = w.enterSubRecord(TableId::CurNameDB->resolveNameFromId(p.first))) { w.setStyle(athena::io::YAMLNodeStyle::Flow); (*p.second.get())->write(w); } } } } if (!m_keymaps.empty()) { if (auto __r = w.enterSubRecord("keymaps")) { for (const auto& p : SortUnorderedMap(m_keymaps)) { if (auto __v = w.enterSubVector(KeymapId::CurNameDB->resolveNameFromId(p.first))) { for (const auto& km : *p.second.get()) { if (auto __r2 = w.enterSubRecord()) { w.setStyle(athena::io::YAMLNodeStyle::Flow); km.write(w); } } } } } } if (!m_layers.empty()) { if (auto __r = w.enterSubRecord("layers")) { for (const auto& p : SortUnorderedMap(m_layers)) { if (auto __v = w.enterSubVector(LayersId::CurNameDB->resolveNameFromId(p.first))) { for (const auto& lm : *p.second.get()) { if (auto __r2 = w.enterSubRecord()) { w.setStyle(athena::io::YAMLNodeStyle::Flow); lm.write(w); } } } } } } athena::io::VectorWriter fo; w.finish(&fo); return fo.data(); } template <athena::Endian DNAE> std::vector<uint8_t> AudioGroupPool::toData() const { athena::io::VectorWriter fo; PoolHeader<DNAE> head = {}; head.write(fo); const uint32_t term = 0xffffffff; if (!m_soundMacros.empty()) { head.soundMacrosOffset = fo.position(); for (const auto& p : m_soundMacros) { auto startPos = fo.position(); ObjectHeader<DNAE> objHead = {}; objHead.write(fo); p.second->template writeCmds<DNAE>(fo); objHead.size = fo.position() - startPos; objHead.objectId = p.first; fo.seek(startPos, athena::SeekOrigin::Begin); objHead.write(fo); fo.seek(startPos + objHead.size, athena::SeekOrigin::Begin); } athena::io::Write<athena::io::PropType::None>::Do<decltype(term), DNAE>({}, term, fo); } if (!m_tables.empty()) { head.tablesOffset = fo.position(); for (const auto& p : m_tables) { auto startPos = fo.position(); ObjectHeader<DNAE> objHead = {}; objHead.write(fo); switch ((*p.second)->Isa()) { case ITable::Type::ADSR: static_cast<ADSR*>(p.second->get())->write(fo); break; case ITable::Type::ADSRDLS: static_cast<ADSRDLS*>(p.second->get())->write(fo); break; case ITable::Type::Curve: { const auto& data = static_cast<Curve*>(p.second->get())->data; fo.writeUBytes(data.data(), data.size()); break; } default: break; } objHead.size = fo.position() - startPos; objHead.objectId = p.first; fo.seek(startPos, athena::SeekOrigin::Begin); objHead.write(fo); fo.seek(startPos + objHead.size, athena::SeekOrigin::Begin); } athena::io::Write<athena::io::PropType::None>::Do<decltype(term), DNAE>({}, term, fo); } if (!m_keymaps.empty()) { head.keymapsOffset = fo.position(); for (const auto& p : m_keymaps) { auto startPos = fo.position(); ObjectHeader<DNAE> objHead = {}; objHead.write(fo); for (const auto& km : *p.second) { KeymapDNA<DNAE> kmData = km.toDNA<DNAE>(); kmData.write(fo); } objHead.size = fo.position() - startPos; objHead.objectId = p.first; fo.seek(startPos, athena::SeekOrigin::Begin); objHead.write(fo); fo.seek(startPos + objHead.size, athena::SeekOrigin::Begin); } athena::io::Write<athena::io::PropType::None>::Do<decltype(term), DNAE>({}, term, fo); } if (!m_layers.empty()) { head.layersOffset = fo.position(); for (const auto& p : m_layers) { auto startPos = fo.position(); ObjectHeader<DNAE> objHead = {}; objHead.write(fo); uint32_t count = p.second->size(); athena::io::Write<athena::io::PropType::None>::Do<decltype(count), DNAE>({}, count, fo); for (const auto& lm : *p.second) { LayerMappingDNA<DNAE> lmData = lm.toDNA<DNAE>(); lmData.write(fo); } objHead.size = fo.position() - startPos; objHead.objectId = p.first; fo.seek(startPos, athena::SeekOrigin::Begin); objHead.write(fo); fo.seek(startPos + objHead.size, athena::SeekOrigin::Begin); } athena::io::Write<athena::io::PropType::None>::Do<decltype(term), DNAE>({}, term, fo); } fo.seek(0, athena::SeekOrigin::Begin); head.write(fo); return fo.data(); } template std::vector<uint8_t> AudioGroupPool::toData<athena::Endian::Big>() const; template std::vector<uint8_t> AudioGroupPool::toData<athena::Endian::Little>() const; template <> void amuse::Curve::Enumerate<LittleDNA::Read>(athena::io::IStreamReader& r) { Log.report(logvisor::Fatal, FMT_STRING("Curve binary DNA read not supported")); } template <> void amuse::Curve::Enumerate<LittleDNA::Write>(athena::io::IStreamWriter& w) { Log.report(logvisor::Fatal, FMT_STRING("Curve binary DNA write not supported")); } template <> void amuse::Curve::Enumerate<LittleDNA::BinarySize>(size_t& sz) { Log.report(logvisor::Fatal, FMT_STRING("Curve binary DNA size not supported")); } template <> void amuse::Curve::Enumerate<LittleDNA::ReadYaml>(athena::io::YAMLDocReader& r) { r.enumerate("data", data); } template <> void amuse::Curve::Enumerate<LittleDNA::WriteYaml>(athena::io::YAMLDocWriter& w) { w.enumerate("data", data); } std::string_view amuse::Curve::DNAType() { return "amuse::Curve"sv; } } // namespace amuse
37.387324
120
0.660105
AxioDL
d44786db6d3a7651fa40eaa0835a5e6f06a3fbd4
2,243
cpp
C++
libs/intrusive/example/doc_function_hooks.cpp
jmuskaan72/Boost
047e36c01841a8cd6a5c74d4e3034da46e327bc1
[ "BSL-1.0" ]
198
2015-01-13T05:47:18.000Z
2022-03-09T04:46:46.000Z
libs/intrusive/example/doc_function_hooks.cpp
xiaoliang2121/Boost
fc90c3fde129c62565c023f091eddc4a7ed9902b
[ "BSL-1.0" ]
4
2015-03-19T08:23:23.000Z
2019-06-24T07:48:47.000Z
libs/intrusive/example/doc_function_hooks.cpp
xiaoliang2121/Boost
fc90c3fde129c62565c023f091eddc4a7ed9902b
[ "BSL-1.0" ]
139
2015-01-15T20:09:31.000Z
2022-01-31T15:21:16.000Z
///////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2010-2012 // // 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) // // See http://www.boost.org/libs/intrusive for documentation. // ///////////////////////////////////////////////////////////////////////////// #include <boost/intrusive/detail/config_begin.hpp> //[doc_function_hooks #include <boost/intrusive/list.hpp> #include <boost/intrusive/parent_from_member.hpp> using namespace boost::intrusive; struct MyClass { int dummy; //This internal type has a member hook struct InnerNode { int dummy; list_member_hook<> hook; } inner; }; //This functor converts between MyClass and InnerNode's member hook struct Functor { //Required types typedef list_member_hook<> hook_type; typedef hook_type* hook_ptr; typedef const hook_type* const_hook_ptr; typedef MyClass value_type; typedef value_type* pointer; typedef const value_type* const_pointer; //Required static functions static hook_ptr to_hook_ptr (value_type &value) { return &value.inner.hook; } static const_hook_ptr to_hook_ptr(const value_type &value) { return &value.inner.hook; } static pointer to_value_ptr(hook_ptr n) { return get_parent_from_member<MyClass> (get_parent_from_member<MyClass::InnerNode>(n, &MyClass::InnerNode::hook) ,&MyClass::inner ); } static const_pointer to_value_ptr(const_hook_ptr n) { return get_parent_from_member<MyClass> (get_parent_from_member<MyClass::InnerNode>(n, &MyClass::InnerNode::hook) ,&MyClass::inner ); } }; //Define a list that will use the hook accessed through the function object typedef list< MyClass, function_hook< Functor> > List; int main() { MyClass n; List l; //Insert the node in both lists l.insert(l.begin(), n); assert(l.size() == 1); return 0; } //] #include <boost/intrusive/detail/config_end.hpp>
29.12987
83
0.612572
jmuskaan72
d4496a1f863a7e06e2727f8ec8ec8dcc773f8e61
2,757
hpp
C++
src/mlpack/core/metrics/iou_metric_impl.hpp
gaurav-singh1998/mlpack
c104a2dcf0b51a98d9d6fcfc01d4e7047cc83872
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-12-09T17:58:29.000Z
2021-12-09T17:58:29.000Z
src/mlpack/core/metrics/iou_metric_impl.hpp
R-Aravind/mlpack
99d11a9b4d379885cf7f8160d8c71fb792fa1bbc
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
src/mlpack/core/metrics/iou_metric_impl.hpp
R-Aravind/mlpack
99d11a9b4d379885cf7f8160d8c71fb792fa1bbc
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-09-17T21:33:59.000Z
2019-09-17T21:33:59.000Z
/** * @file core/metrics/iou_metric_impl.hpp * @author Kartik Dutt * * Implementation of Intersection Over Union metric. * * mlpack is free software; you may redistribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #ifndef MLPACK_CORE_METRICS_IOU_IMPL_HPP #define MLPACK_CORE_METRICS_IOU_IMPL_HPP // In case it hasn't been included. #include "iou_metric.hpp" namespace mlpack { namespace metric { template<bool UseCoordinates> template <typename VecTypeA, typename VecTypeB> typename VecTypeA::elem_type IoU<UseCoordinates>::Evaluate( const VecTypeA& a, const VecTypeB& b) { Log::Assert(a.n_elem == b.n_elem && a.n_elem == 4, "Incorrect \ shape for bounding boxes. They must contain 4 elements either be \ {x0, y0, x1, y1} or {x0, y0, h, w}. Refer to the documentation \ for more information."); // Bounding boxes represented as {x0, y0, x1, y1}. if (UseCoordinates) { // Check the correctness of bounding box. if (a(0) >= a(2) || a(1) >= a(3) || b(0) >= b(2) || b(1) >= b(3)) { Log::Fatal << "Check the correctness of bounding boxes i.e. " << "{x0, y0} must represent lower left coordinates and " << "{x1, y1} must represent upper right coordinates of bounding" << "box." << std::endl; } typename VecTypeA::elem_type interSectionArea = std::max(0.0, std::min(a(2), b(2)) - std::max(a(0), b(0)) + 1) * std::max(0.0, std::min(a(3), b(3)) - std::max(a(1), b(1)) + 1); // Union of Area can be calculated using the following equation // A union B = A + B - A intersection B. return interSectionArea / (1.0 * ((a(2) - a(0) + 1) * (a(3) - a(1) + 1) + (b(2) - b(0) + 1) * (b(3) - b(1) + 1) - interSectionArea)); } // Bounding boxes represented as {x0, y0, h, w}. // Check correctness of bounding box. Log::Assert(a(2) > 0 && b(2) > 0 && a(3) > 0 && b(3) > 0, "Height and width \ of bounding boxes must be greater than zero."); typename VecTypeA::elem_type interSectionArea = std::max(0.0, std::min(a(0) + a(2), b(0) + b(2)) - std::max(a(0), b(0)) + 1) * std::max(0.0, std::min(a(1) + a(3), b(1) + b(3)) - std::max(a(1), b(1)) + 1); return interSectionArea / (1.0 * ((a(2) + 1) * (a(3) + 1) + (b(2) + 1) * (b(3) + 1) - interSectionArea)); } template<bool UseCoordinates> template<typename Archive> void IoU<UseCoordinates>::serialize( Archive& /* ar */, const unsigned int /* version */) { // Nothing to do here. } } // namespace metric } // namespace mlpack #endif
34.898734
79
0.608995
gaurav-singh1998
d44ed9ea3d1c11e444823cbd28a6c503669cd4a2
10,283
cpp
C++
src/test/unit/lang/parser/math_functions_test.cpp
drezap/stan
9b319ed125e2a7d14d0c9c246d2f462dad668537
[ "BSD-3-Clause" ]
1
2019-07-05T01:40:40.000Z
2019-07-05T01:40:40.000Z
src/test/unit/lang/parser/math_functions_test.cpp
drezap/stan
9b319ed125e2a7d14d0c9c246d2f462dad668537
[ "BSD-3-Clause" ]
null
null
null
src/test/unit/lang/parser/math_functions_test.cpp
drezap/stan
9b319ed125e2a7d14d0c9c246d2f462dad668537
[ "BSD-3-Clause" ]
1
2018-08-28T12:09:08.000Z
2018-08-28T12:09:08.000Z
#include <gtest/gtest.h> #include <test/unit/lang/utility.hpp> TEST(lang_parser, abs_math_function_signatures) { test_parsable("function-signatures/math/functions/abs"); } TEST(lang_parser, asin_math_function_signatures) { test_parsable("function-signatures/math/functions/asin"); } TEST(lang_parser, asinh_math_function_signatures) { test_parsable("function-signatures/math/functions/asinh"); } TEST(lang_parser, acos_math_function_signatures) { test_parsable("function-signatures/math/functions/acos"); } TEST(lang_parser, acosh_math_function_signatures) { test_parsable("function-signatures/math/functions/acosh"); } TEST(lang_parser, atan_math_function_signatures) { test_parsable("function-signatures/math/functions/atan"); } TEST(lang_parser, atan2_math_function_signatures) { test_parsable("function-signatures/math/functions/atan2"); } TEST(lang_parser, atanh_math_function_signatures) { test_parsable("function-signatures/math/functions/atanh"); } TEST(lang_parser, bessel_first_kind_math_function_signatures) { test_parsable("function-signatures/math/functions/bessel_first_kind"); } TEST(lang_parser, bessel_second_kind_math_function_signatures) { test_parsable("function-signatures/math/functions/bessel_second_kind"); } TEST(lang_parser, binary_log_loss_math_function_signatures) { test_parsable("function-signatures/math/functions/binary_log_loss"); } TEST(lang_parser, binomial_coefficient_log_math_function_signatures) { test_parsable("function-signatures/math/functions/binomial_coefficient_log"); } TEST(lang_parser, cbrt_math_function_signatures) { test_parsable("function-signatures/math/functions/cbrt"); } TEST(lang_parser, ceil_math_function_signatures) { test_parsable("function-signatures/math/functions/ceil"); } TEST(lang_parser, constants_math_function_signatures) { test_parsable("function-signatures/math/functions/constants"); } TEST(lang_parser, cos_math_function_signatures) { test_parsable("function-signatures/math/functions/cos"); } TEST(lang_parser, cosh_math_function_signatures) { test_parsable("function-signatures/math/functions/cosh"); } TEST(lang_parser, digamma_math_function_signatures) { test_parsable("function-signatures/math/functions/digamma"); } TEST(lang_parser, erf_math_function_signatures) { test_parsable("function-signatures/math/functions/erf"); } TEST(lang_parser, erfc_math_function_signatures) { test_parsable("function-signatures/math/functions/erfc"); } TEST(lang_parser, exp_math_function_signatures) { test_parsable("function-signatures/math/functions/exp"); } TEST(lang_parser, exp2_math_function_signatures) { test_parsable("function-signatures/math/functions/exp2"); } TEST(lang_parser, expm1_math_function_signatures) { test_parsable("function-signatures/math/functions/expm1"); } TEST(lang_parser, fabs_math_function_signatures) { test_parsable("function-signatures/math/functions/fabs"); } TEST(lang_parser, falling_factorial_math_function_signatures) { test_parsable("function-signatures/math/functions/falling_factorial"); } TEST(lang_parser, fdim_math_function_signatures) { test_parsable("function-signatures/math/functions/fdim"); } TEST(lang_parser, floor_math_function_signatures) { test_parsable("function-signatures/math/functions/floor"); } TEST(lang_parser, fma_math_function_signatures) { test_parsable("function-signatures/math/functions/fma"); } TEST(lang_parser, fmax_math_function_signatures) { test_parsable("function-signatures/math/functions/fmax"); } TEST(lang_parser, fmin_math_function_signatures) { test_parsable("function-signatures/math/functions/fmin"); } TEST(lang_parser, fmod_math_function_signatures) { test_parsable("function-signatures/math/functions/fmod"); } TEST(lang_parser, gamma_p_math_function_signatures) { test_parsable("function-signatures/math/functions/gamma_p"); } TEST(lang_parser, gamma_q_math_function_signatures) { test_parsable("function-signatures/math/functions/gamma_q"); } TEST(lang_parser, hypot_math_function_signatures) { test_parsable("function-signatures/math/functions/hypot"); } TEST(lang_parser, if_else_math_function_signatures) { test_parsable("function-signatures/math/functions/if_else"); } TEST(lang_parser, inc_beta_math_function_signatures) { test_parsable("function-signatures/math/functions/inc_beta"); } TEST(lang_parser, int_step_math_function_signatures) { test_parsable("function-signatures/math/functions/int_step"); } TEST(lang_parser, inv_math_function_signatures) { test_parsable("function-signatures/math/functions/inv"); } TEST(lang_parser, inv_logit_math_function_signatures) { test_parsable("function-signatures/math/functions/inv_logit"); } TEST(lang_parser, inv_cloglog_math_function_signatures) { test_parsable("function-signatures/math/functions/inv_cloglog"); } TEST(lang_parser, inv_square_math_function_signatures) { test_parsable("function-signatures/math/functions/inv_square"); } TEST(lang_parser, inv_sqrt_math_function_signatures) { test_parsable("function-signatures/math/functions/inv_sqrt"); } TEST(lang_parser, lbeta_math_function_signatures) { test_parsable("function-signatures/math/functions/lbeta"); } TEST(lang_parser, lgamma_math_function_signatures) { test_parsable("function-signatures/math/functions/lgamma"); } TEST(lang_parser, lmgamma_math_function_signatures) { test_parsable("function-signatures/math/functions/lmgamma"); } TEST(lang_parser, log1m_math_function_signatures) { test_parsable("function-signatures/math/functions/log1m"); } TEST(lang_parser, log1m_exp_math_function_signatures) { test_parsable("function-signatures/math/functions/log1m_exp"); } TEST(lang_parser, log1m_inv_logit_math_function_signatures) { test_parsable("function-signatures/math/functions/log1m_inv_logit"); } TEST(lang_parser, log1p_math_function_signatures) { test_parsable("function-signatures/math/functions/log1p"); } TEST(lang_parser, log1p_exp_math_function_signatures) { test_parsable("function-signatures/math/functions/log1p_exp"); } TEST(lang_parser, log_math_function_signatures) { test_parsable("function-signatures/math/functions/log"); } TEST(lang_parser, log10_math_function_signatures) { test_parsable("function-signatures/math/functions/log10"); } TEST(lang_parser, log2_math_function_signatures) { test_parsable("function-signatures/math/functions/log2"); } TEST(lang_parser, log_diff_exp_math_function_signatures) { test_parsable("function-signatures/math/functions/log_diff_exp"); } TEST(lang_parser, log_inv_logit_math_function_signatures) { test_parsable("function-signatures/math/functions/log_inv_logit"); } TEST(lang_parser, logit_math_function_signatures) { test_parsable("function-signatures/math/functions/logit"); } TEST(lang_parser, log_falling_factorial_math_function_signatures) { test_parsable("function-signatures/math/functions/log_falling_factorial"); } TEST(lang_parser, log_mix_math_function_signatures) { test_parsable("function-signatures/math/functions/log_mix"); } TEST(lang_parser, log_rising_factorial_math_function_signatures) { test_parsable("function-signatures/math/functions/log_rising_factorial"); } TEST(lang_parser, log_sum_exp_math_function_signatures) { test_parsable("function-signatures/math/functions/log_sum_exp"); } TEST(lang_parser, max_math_function_signatures) { test_parsable("function-signatures/math/functions/max"); } TEST(lang_parser, min_math_function_signatures) { test_parsable("function-signatures/math/functions/min"); } TEST(lang_parser, modified_bessel_first_kind_math_function_signatures) { test_parsable("function-signatures/math/functions/modified_bessel_first_kind"); } TEST(lang_parser, modified_bessel_second_kind_math_function_signatures) { test_parsable("function-signatures/math/functions/modified_bessel_second_kind"); } TEST(lang_parser, multiply_log_math_function_signatures) { test_parsable("function-signatures/math/functions/multiply_log"); } TEST(lang_parser, operators_int_math_function_signatures) { test_parsable("function-signatures/math/functions/operators_int"); } TEST(lang_parser, operators_real_math_function_signatures) { test_parsable("function-signatures/math/functions/operators_real"); } TEST(lang_parser, owens_t_math_function_signatures) { test_parsable("function-signatures/math/functions/owens_t"); } TEST(lang_parser, phi_math_function_signatures) { test_parsable("function-signatures/math/functions/phi"); } TEST(lang_parser, phi_approx_math_function_signatures) { test_parsable("function-signatures/math/functions/phi_approx"); } TEST(lang_parser, pow_math_function_signatures) { test_parsable("function-signatures/math/functions/pow"); } TEST(lang_parser, sin_math_function_signatures) { test_parsable("function-signatures/math/functions/sin"); } TEST(lang_parser, sinh_math_function_signatures) { test_parsable("function-signatures/math/functions/sinh"); } TEST(lang_parser, step_math_function_signatures) { test_parsable("function-signatures/math/functions/step"); } TEST(lang_parser, special_values_math_function_signatures) { test_parsable("function-signatures/math/functions/special_values"); } TEST(lang_parser, sqrt_math_function_signatures) { test_parsable("function-signatures/math/functions/sqrt"); } TEST(lang_parser, square_math_function_signatures) { test_parsable("function-signatures/math/functions/square"); } TEST(lang_parser, rising_factorial_math_function_signatures) { test_parsable("function-signatures/math/functions/rising_factorial"); } TEST(lang_parser, round_math_function_signatures) { test_parsable("function-signatures/math/functions/round"); } TEST(lang_parser, tan_math_function_signatures) { test_parsable("function-signatures/math/functions/tan"); } TEST(lang_parser, tanh_math_function_signatures) { test_parsable("function-signatures/math/functions/tanh"); } TEST(lang_parser, tgamma_math_function_signatures) { test_parsable("function-signatures/math/functions/tgamma"); } TEST(lang_parser, trigamma_math_function_signatures) { test_parsable("function-signatures/math/functions/trigamma"); } TEST(lang_parser, trunc_math_function_signatures) { test_parsable("function-signatures/math/functions/trunc"); }
30.333333
82
0.817563
drezap
d44ee6da08df8deb1bbffdb1f585e6f160fcd33d
30,796
cpp
C++
csie/jpeg/nj.cpp
dk00/old-stuff
e1184684c85fe9bbd1ceba58b94d4da84c67784e
[ "Unlicense" ]
null
null
null
csie/jpeg/nj.cpp
dk00/old-stuff
e1184684c85fe9bbd1ceba58b94d4da84c67784e
[ "Unlicense" ]
null
null
null
csie/jpeg/nj.cpp
dk00/old-stuff
e1184684c85fe9bbd1ceba58b94d4da84c67784e
[ "Unlicense" ]
null
null
null
// NanoJPEG -- KeyJ's Tiny Baseline JPEG Decoder // version 1.3 (2012-03-05) // by Martin J. Fiedler <martin.fiedler@gmx.net> // // This software is published under the terms of KeyJ's Research License, // version 0.2. Usage of this software is subject to the following conditions: // 0. There's no warranty whatsoever. The author(s) of this software can not // be held liable for any damages that occur when using this software. // 1. This software may be used freely for both non-commercial and commercial // purposes. // 2. This software may be redistributed freely as long as no fees are charged // for the distribution and this license information is included. // 3. This software may be modified freely except for this license information, // which must not be changed in any way. // 4. If anything other than configuration, indentation or comments have been // altered in the code, the original author(s) must receive a copy of the // modified code. /////////////////////////////////////////////////////////////////////////////// // DOCUMENTATION SECTION // // read this if you want to know what this is all about // /////////////////////////////////////////////////////////////////////////////// // INTRODUCTION // ============ // // This is a minimal decoder for baseline JPEG images. It accepts memory dumps // of JPEG files as input and generates either 8-bit grayscale or packed 24-bit // RGB images as output. It does not parse JFIF or Exif headers; all JPEG files // are assumed to be either grayscale or YCbCr. CMYK or other color spaces are // not supported. All YCbCr subsampling schemes with power-of-two ratios are // supported, as are restart intervals. Progressive or lossless JPEG is not // supported. // Summed up, NanoJPEG should be able to decode all images from digital cameras // and most common forms of other non-progressive JPEG images. // The decoder is not optimized for speed, it's optimized for simplicity and // small code. Image quality should be at a reasonable level. A bicubic chroma // upsampling filter ensures that subsampled YCbCr images are rendered in // decent quality. The decoder is not meant to deal with broken JPEG files in // a graceful manner; if anything is wrong with the bitstream, decoding will // simply fail. // The code should work with every modern C compiler without problems and // should not emit any warnings. It uses only (at least) 32-bit integer // arithmetic and is supposed to be endianness independent and 64-bit clean. // However, it is not thread-safe. // COMPILE-TIME CONFIGURATION // ========================== // // The following aspects of NanoJPEG can be controlled with preprocessor // defines: // // _NJ_EXAMPLE_PROGRAM = Compile a main() function with an example // program. // _NJ_INCLUDE_HEADER_ONLY = Don't compile anything, just act as a header // file for NanoJPEG. Example: // #define _NJ_INCLUDE_HEADER_ONLY // #include "nanojpeg.c" // int main(void) { // njInit(); // // your code here // njDone(); // } // NJ_USE_LIBC=1 = Use the malloc(), free(), memset() and memcpy() // functions from the standard C library (default). // NJ_USE_LIBC=0 = Don't use the standard C library. In this mode, // external functions njAlloc(), njFreeMem(), // njFillMem() and njCopyMem() need to be defined // and implemented somewhere. // NJ_USE_WIN32=0 = Normal mode (default). // NJ_USE_WIN32=1 = If compiling with MSVC for Win32 and // NJ_USE_LIBC=0, NanoJPEG will use its own // implementations of the required C library // functions (default if compiling with MSVC and // NJ_USE_LIBC=0). // NJ_CHROMA_FILTER=1 = Use the bicubic chroma upsampling filter // (default). // NJ_CHROMA_FILTER=0 = Use simple pixel repetition for chroma upsampling // (bad quality, but faster and less code). // API // === // // For API documentation, read the "header section" below. // EXAMPLE // ======= // // A few pages below, you can find an example program that uses NanoJPEG to // convert JPEG files into PGM or PPM. To compile it, use something like // gcc -O3 -D_NJ_EXAMPLE_PROGRAM -o nanojpeg nanojpeg.c // You may also add -std=c99 -Wall -Wextra -pedantic -Werror, if you want :) /////////////////////////////////////////////////////////////////////////////// // HEADER SECTION // // copy and pase this into nanojpeg.h if you want // /////////////////////////////////////////////////////////////////////////////// #ifndef _NANOJPEG_H #define _NANOJPEG_H // nj_result_t: Result codes for njDecode(). typedef enum _nj_result { NJ_OK = 0, // no error, decoding successful NJ_NO_JPEG, // not a JPEG file NJ_UNSUPPORTED, // unsupported format NJ_OUT_OF_MEM, // out of memory NJ_INTERNAL_ERR, // internal error NJ_SYNTAX_ERROR, // syntax error __NJ_FINISHED, // used internally, will never be reported } nj_result_t; // njInit: Initialize NanoJPEG. // For safety reasons, this should be called at least one time before using // using any of the other NanoJPEG functions. void njInit(void); // njDecode: Decode a JPEG image. // Decodes a memory dump of a JPEG file into internal buffers. // Parameters: // jpeg = The pointer to the memory dump. // size = The size of the JPEG file. // Return value: The error code in case of failure, or NJ_OK (zero) on success. nj_result_t njDecode(const void* jpeg, const int size); // njGetWidth: Return the width (in pixels) of the most recently decoded // image. If njDecode() failed, the result of njGetWidth() is undefined. int njGetWidth(void); // njGetHeight: Return the height (in pixels) of the most recently decoded // image. If njDecode() failed, the result of njGetHeight() is undefined. int njGetHeight(void); // njIsColor: Return 1 if the most recently decoded image is a color image // (RGB) or 0 if it is a grayscale image. If njDecode() failed, the result // of njGetWidth() is undefined. int njIsColor(void); // njGetImage: Returns the decoded image data. // Returns a pointer to the most recently image. The memory layout it byte- // oriented, top-down, without any padding between lines. Pixels of color // images will be stored as three consecutive bytes for the red, green and // blue channels. This data format is thus compatible with the PGM or PPM // file formats and the OpenGL texture formats GL_LUMINANCE8 or GL_RGB8. // If njDecode() failed, the result of njGetImage() is undefined. unsigned char* njGetImage(void); // njGetImageSize: Returns the size (in bytes) of the image data returned // by njGetImage(). If njDecode() failed, the result of njGetImageSize() is // undefined. int njGetImageSize(void); // njDone: Uninitialize NanoJPEG. // Resets NanoJPEG's internal state and frees all memory that has been // allocated at run-time by NanoJPEG. It is still possible to decode another // image after a njDone() call. void njDone(void); #endif//_NANOJPEG_H /////////////////////////////////////////////////////////////////////////////// // CONFIGURATION SECTION // // adjust the default settings for the NJ_ defines here // /////////////////////////////////////////////////////////////////////////////// #ifndef NJ_USE_LIBC #define NJ_USE_LIBC 1 #endif #ifndef NJ_USE_WIN32 #ifdef _MSC_VER #define NJ_USE_WIN32 (!NJ_USE_LIBC) #else #define NJ_USE_WIN32 0 #endif #endif #ifndef NJ_CHROMA_FILTER #define NJ_CHROMA_FILTER 1 #endif /////////////////////////////////////////////////////////////////////////////// // EXAMPLE PROGRAM // // just define _NJ_EXAMPLE_PROGRAM to compile this (requires NJ_USE_LIBC) // /////////////////////////////////////////////////////////////////////////////// #ifdef _NJ_EXAMPLE_PROGRAM #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char* argv[]) { int size; char *buf; FILE *f; if (argc < 2) { printf("Usage: %s <input.jpg> [<output.ppm>]\n", argv[0]); return 2; } f = fopen(argv[1], "rb"); if (!f) { printf("Error opening the input file.\n"); return 1; } fseek(f, 0, SEEK_END); size = (int) ftell(f); buf = malloc(size); fseek(f, 0, SEEK_SET); size = (int) fread(buf, 1, size, f); fclose(f); njInit(); if (njDecode(buf, size)) { printf("Error decoding the input file.\n"); return 1; } f = fopen((argc > 2) ? argv[2] : (njIsColor() ? "nanojpeg_out.ppm" : "nanojpeg_out.pgm"), "wb"); if (!f) { printf("Error opening the output file.\n"); return 1; } fprintf(f, "P%d\n%d %d\n255\n", njIsColor() ? 6 : 5, njGetWidth(), njGetHeight()); fwrite(njGetImage(), 1, njGetImageSize(), f); fclose(f); njDone(); return 0; } #endif /////////////////////////////////////////////////////////////////////////////// // IMPLEMENTATION SECTION // // you may stop reading here // /////////////////////////////////////////////////////////////////////////////// #ifndef _NJ_INCLUDE_HEADER_ONLY #ifdef _MSC_VER #define NJ_INLINE static __inline #define NJ_FORCE_INLINE static __forceinline #else #define NJ_INLINE static inline #define NJ_FORCE_INLINE static inline #endif #if NJ_USE_LIBC #include <stdlib.h> #include <string.h> #define njAllocMem malloc #define njFreeMem free #define njFillMem memset #define njCopyMem memcpy #elif NJ_USE_WIN32 #include <windows.h> #define njAllocMem(size) ((void*) LocalAlloc(LMEM_FIXED, (SIZE_T)(size))) #define njFreeMem(block) ((void) LocalFree((HLOCAL) block)) NJ_INLINE void njFillMem(void* block, unsigned char value, int count) { __asm { mov edi, block mov al, value mov ecx, count rep stosb } } NJ_INLINE void njCopyMem(void* dest, const void* src, int count) { __asm { mov edi, dest mov esi, src mov ecx, count rep movsb } } #else extern void* njAllocMem(int size); extern void njFreeMem(void* block); extern void njFillMem(void* block, unsigned char byte, int size); extern void njCopyMem(void* dest, const void* src, int size); #endif typedef struct _nj_code { unsigned char bits, code; } nj_vlc_code_t; typedef struct _nj_cmp { int cid; int ssx, ssy; int width, height; int stride; int qtsel; int actabsel, dctabsel; int dcpred; unsigned char *pixels; } nj_component_t; typedef struct _nj_ctx { nj_result_t error; const unsigned char *pos; int size; int length; int width, height; int mbwidth, mbheight; int mbsizex, mbsizey; int ncomp; nj_component_t comp[3]; int qtused, qtavail; unsigned char qtab[4][64]; nj_vlc_code_t vlctab[4][65536]; int buf, bufbits; int block[64]; int rstinterval; unsigned char *rgb; } nj_context_t; static nj_context_t nj; static const char njZZ[64] = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63 }; NJ_FORCE_INLINE unsigned char njClip(const int x) { return (x < 0) ? 0 : ((x > 0xFF) ? 0xFF : (unsigned char) x); } #define W1 2841 #define W2 2676 #define W3 2408 #define W5 1609 #define W6 1108 #define W7 565 NJ_INLINE void njRowIDCT(int* blk) { int x0, x1, x2, x3, x4, x5, x6, x7, x8; if (!((x1 = blk[4] << 11) | (x2 = blk[6]) | (x3 = blk[2]) | (x4 = blk[1]) | (x5 = blk[7]) | (x6 = blk[5]) | (x7 = blk[3]))) { blk[0] = blk[1] = blk[2] = blk[3] = blk[4] = blk[5] = blk[6] = blk[7] = blk[0] << 3; return; } x0 = (blk[0] << 11) + 128; x8 = W7 * (x4 + x5); x4 = x8 + (W1 - W7) * x4; x5 = x8 - (W1 + W7) * x5; x8 = W3 * (x6 + x7); x6 = x8 - (W3 - W5) * x6; x7 = x8 - (W3 + W5) * x7; x8 = x0 + x1; x0 -= x1; x1 = W6 * (x3 + x2); x2 = x1 - (W2 + W6) * x2; x3 = x1 + (W2 - W6) * x3; x1 = x4 + x6; x4 -= x6; x6 = x5 + x7; x5 -= x7; x7 = x8 + x3; x8 -= x3; x3 = x0 + x2; x0 -= x2; x2 = (181 * (x4 + x5) + 128) >> 8; x4 = (181 * (x4 - x5) + 128) >> 8; blk[0] = (x7 + x1) >> 8; blk[1] = (x3 + x2) >> 8; blk[2] = (x0 + x4) >> 8; blk[3] = (x8 + x6) >> 8; blk[4] = (x8 - x6) >> 8; blk[5] = (x0 - x4) >> 8; blk[6] = (x3 - x2) >> 8; blk[7] = (x7 - x1) >> 8; } NJ_INLINE void njColIDCT(const int* blk, unsigned char *out, int stride) { int x0, x1, x2, x3, x4, x5, x6, x7, x8; if (!((x1 = blk[8*4] << 8) | (x2 = blk[8*6]) | (x3 = blk[8*2]) | (x4 = blk[8*1]) | (x5 = blk[8*7]) | (x6 = blk[8*5]) | (x7 = blk[8*3]))) { x1 = njClip(((blk[0] + 32) >> 6) + 128); for (x0 = 8; x0; --x0) { *out = (unsigned char) x1; out += stride; } return; } x0 = (blk[0] << 8) + 8192; x8 = W7 * (x4 + x5) + 4; x4 = (x8 + (W1 - W7) * x4) >> 3; x5 = (x8 - (W1 + W7) * x5) >> 3; x8 = W3 * (x6 + x7) + 4; x6 = (x8 - (W3 - W5) * x6) >> 3; x7 = (x8 - (W3 + W5) * x7) >> 3; x8 = x0 + x1; x0 -= x1; x1 = W6 * (x3 + x2) + 4; x2 = (x1 - (W2 + W6) * x2) >> 3; x3 = (x1 + (W2 - W6) * x3) >> 3; x1 = x4 + x6; x4 -= x6; x6 = x5 + x7; x5 -= x7; x7 = x8 + x3; x8 -= x3; x3 = x0 + x2; x0 -= x2; x2 = (181 * (x4 + x5) + 128) >> 8; x4 = (181 * (x4 - x5) + 128) >> 8; *out = njClip(((x7 + x1) >> 14) + 128); out += stride; *out = njClip(((x3 + x2) >> 14) + 128); out += stride; *out = njClip(((x0 + x4) >> 14) + 128); out += stride; *out = njClip(((x8 + x6) >> 14) + 128); out += stride; *out = njClip(((x8 - x6) >> 14) + 128); out += stride; *out = njClip(((x0 - x4) >> 14) + 128); out += stride; *out = njClip(((x3 - x2) >> 14) + 128); out += stride; *out = njClip(((x7 - x1) >> 14) + 128); } #define njThrow(e) do { nj.error = e; return; } while (0) #define njCheckError() do { if (nj.error) return; } while (0) static int njShowBits(int bits) { unsigned char newbyte; if (!bits) return 0; while (nj.bufbits < bits) { if (nj.size <= 0) { nj.buf = (nj.buf << 8) | 0xFF; nj.bufbits += 8; continue; } newbyte = *nj.pos++; nj.size--; nj.bufbits += 8; nj.buf = (nj.buf << 8) | newbyte; if (newbyte == 0xFF) { if (nj.size) { unsigned char marker = *nj.pos++; nj.size--; switch (marker) { case 0x00: case 0xFF: break; case 0xD9: nj.size = 0; break; default: if ((marker & 0xF8) != 0xD0) nj.error = NJ_SYNTAX_ERROR; else { nj.buf = (nj.buf << 8) | marker; nj.bufbits += 8; } } } else nj.error = NJ_SYNTAX_ERROR; } } return (nj.buf >> (nj.bufbits - bits)) & ((1 << bits) - 1); } NJ_INLINE void njSkipBits(int bits) { if (nj.bufbits < bits) (void) njShowBits(bits); nj.bufbits -= bits; } NJ_INLINE int njGetBits(int bits) { int res = njShowBits(bits); njSkipBits(bits); return res; } NJ_INLINE void njByteAlign(void) { nj.bufbits &= 0xF8; } static void njSkip(int count) { nj.pos += count; nj.size -= count; nj.length -= count; if (nj.size < 0) nj.error = NJ_SYNTAX_ERROR; } NJ_INLINE unsigned short njDecode16(const unsigned char *pos) { return (pos[0] << 8) | pos[1]; } static void njDecodeLength(void) { if (nj.size < 2) njThrow(NJ_SYNTAX_ERROR); nj.length = njDecode16(nj.pos); if (nj.length > nj.size) njThrow(NJ_SYNTAX_ERROR); njSkip(2); } NJ_INLINE void njSkipMarker(void) { njDecodeLength(); njSkip(nj.length); } NJ_INLINE void njDecodeSOF(void) { int i, ssxmax = 0, ssymax = 0; nj_component_t* c; njDecodeLength(); if (nj.length < 9) njThrow(NJ_SYNTAX_ERROR); if (nj.pos[0] != 8) njThrow(NJ_UNSUPPORTED); nj.height = njDecode16(nj.pos+1); nj.width = njDecode16(nj.pos+3); nj.ncomp = nj.pos[5]; njSkip(6); switch (nj.ncomp) { case 1: case 3: break; default: njThrow(NJ_UNSUPPORTED); } if (nj.length < (nj.ncomp * 3)) njThrow(NJ_SYNTAX_ERROR); for (i = 0, c = nj.comp; i < nj.ncomp; ++i, ++c) { c->cid = nj.pos[0]; if (!(c->ssx = nj.pos[1] >> 4)) njThrow(NJ_SYNTAX_ERROR); if (c->ssx & (c->ssx - 1)) njThrow(NJ_UNSUPPORTED); // non-power of two if (!(c->ssy = nj.pos[1] & 15)) njThrow(NJ_SYNTAX_ERROR); if (c->ssy & (c->ssy - 1)) njThrow(NJ_UNSUPPORTED); // non-power of two if ((c->qtsel = nj.pos[2]) & 0xFC) njThrow(NJ_SYNTAX_ERROR); njSkip(3); nj.qtused |= 1 << c->qtsel; if (c->ssx > ssxmax) ssxmax = c->ssx; if (c->ssy > ssymax) ssymax = c->ssy; } if (nj.ncomp == 1) { c = nj.comp; c->ssx = c->ssy = ssxmax = ssymax = 1; } nj.mbsizex = ssxmax << 3; nj.mbsizey = ssymax << 3; nj.mbwidth = (nj.width + nj.mbsizex - 1) / nj.mbsizex; nj.mbheight = (nj.height + nj.mbsizey - 1) / nj.mbsizey; for (i = 0, c = nj.comp; i < nj.ncomp; ++i, ++c) { c->width = (nj.width * c->ssx + ssxmax - 1) / ssxmax; c->stride = (c->width + 7) & 0x7FFFFFF8; c->height = (nj.height * c->ssy + ssymax - 1) / ssymax; c->stride = nj.mbwidth * nj.mbsizex * c->ssx / ssxmax; if (((c->width < 3) && (c->ssx != ssxmax)) || ((c->height < 3) && (c->ssy != ssymax))) njThrow(NJ_UNSUPPORTED); if (!(c->pixels = njAllocMem(c->stride * (nj.mbheight * nj.mbsizey * c->ssy / ssymax)))) njThrow(NJ_OUT_OF_MEM); } if (nj.ncomp == 3) { nj.rgb = njAllocMem(nj.width * nj.height * nj.ncomp); if (!nj.rgb) njThrow(NJ_OUT_OF_MEM); } njSkip(nj.length); } NJ_INLINE void njDecodeDHT(void) { int codelen, currcnt, remain, spread, i, j; nj_vlc_code_t *vlc; static unsigned char counts[16]; njDecodeLength(); while (nj.length >= 17) { i = nj.pos[0]; if (i & 0xEC) njThrow(NJ_SYNTAX_ERROR); if (i & 0x02) njThrow(NJ_UNSUPPORTED); i = (i | (i >> 3)) & 3; // combined DC/AC + tableid value for (codelen = 1; codelen <= 16; ++codelen) counts[codelen - 1] = nj.pos[codelen]; njSkip(17); vlc = &nj.vlctab[i][0]; remain = spread = 65536; for (codelen = 1; codelen <= 16; ++codelen) { spread >>= 1; currcnt = counts[codelen - 1]; if (!currcnt) continue; if (nj.length < currcnt) njThrow(NJ_SYNTAX_ERROR); remain -= currcnt << (16 - codelen); if (remain < 0) njThrow(NJ_SYNTAX_ERROR); for (i = 0; i < currcnt; ++i) { register unsigned char code = nj.pos[i]; for (j = spread; j; --j) { vlc->bits = (unsigned char) codelen; vlc->code = code; ++vlc; } } njSkip(currcnt); } while (remain--) { vlc->bits = 0; ++vlc; } } if (nj.length) njThrow(NJ_SYNTAX_ERROR); } NJ_INLINE void njDecodeDQT(void) { int i; unsigned char *t; njDecodeLength(); while (nj.length >= 65) { i = nj.pos[0]; if (i & 0xFC) njThrow(NJ_SYNTAX_ERROR); nj.qtavail |= 1 << i; t = &nj.qtab[i][0]; for (i = 0; i < 64; ++i) t[i] = nj.pos[i + 1]; njSkip(65); } if (nj.length) njThrow(NJ_SYNTAX_ERROR); } NJ_INLINE void njDecodeDRI(void) { njDecodeLength(); if (nj.length < 2) njThrow(NJ_SYNTAX_ERROR); nj.rstinterval = njDecode16(nj.pos); njSkip(nj.length); } static int njGetVLC(nj_vlc_code_t* vlc, unsigned char* code) { int value = njShowBits(16); int bits = vlc[value].bits; if (!bits) { nj.error = NJ_SYNTAX_ERROR; return 0; } njSkipBits(bits); value = vlc[value].code; if (code) *code = (unsigned char) value; bits = value & 15; if (!bits) return 0; value = njGetBits(bits); if (value < (1 << (bits - 1))) value += ((-1) << bits) + 1; return value; } NJ_INLINE void njDecodeBlock(nj_component_t* c, unsigned char* out) { unsigned char code = 0; int value, coef = 0; njFillMem(nj.block, 0, sizeof(nj.block)); c->dcpred += njGetVLC(&nj.vlctab[c->dctabsel][0], NULL); nj.block[0] = (c->dcpred) * nj.qtab[c->qtsel][0]; do { value = njGetVLC(&nj.vlctab[c->actabsel][0], &code); if (!code) break; // EOB if (!(code & 0x0F) && (code != 0xF0)) njThrow(NJ_SYNTAX_ERROR); coef += (code >> 4) + 1; if (coef > 63) njThrow(NJ_SYNTAX_ERROR); nj.block[(int) njZZ[coef]] = value * nj.qtab[c->qtsel][coef]; } while (coef < 63); for (coef = 0; coef < 64; coef += 8) njRowIDCT(&nj.block[coef]); for (coef = 0; coef < 8; ++coef) njColIDCT(&nj.block[coef], &out[coef], c->stride); } NJ_INLINE void njDecodeScan(void) { int i, mbx, mby, sbx, sby; int rstcount = nj.rstinterval, nextrst = 0; nj_component_t* c; njDecodeLength(); if (nj.length < (4 + 2 * nj.ncomp)) njThrow(NJ_SYNTAX_ERROR); if (nj.pos[0] != nj.ncomp) njThrow(NJ_UNSUPPORTED); njSkip(1); for (i = 0, c = nj.comp; i < nj.ncomp; ++i, ++c) { if (nj.pos[0] != c->cid) njThrow(NJ_SYNTAX_ERROR); if (nj.pos[1] & 0xEE) njThrow(NJ_SYNTAX_ERROR); c->dctabsel = nj.pos[1] >> 4; c->actabsel = (nj.pos[1] & 1) | 2; njSkip(2); } if (nj.pos[0] || (nj.pos[1] != 63) || nj.pos[2]) njThrow(NJ_UNSUPPORTED); njSkip(nj.length); for (mbx = mby = 0;;) { for (i = 0, c = nj.comp; i < nj.ncomp; ++i, ++c) for (sby = 0; sby < c->ssy; ++sby) for (sbx = 0; sbx < c->ssx; ++sbx) { njDecodeBlock(c, &c->pixels[((mby * c->ssy + sby) * c->stride + mbx * c->ssx + sbx) << 3]); njCheckError(); } if (++mbx >= nj.mbwidth) { mbx = 0; if (++mby >= nj.mbheight) break; } if (nj.rstinterval && !(--rstcount)) { njByteAlign(); i = njGetBits(16); if (((i & 0xFFF8) != 0xFFD0) || ((i & 7) != nextrst)) njThrow(NJ_SYNTAX_ERROR); nextrst = (nextrst + 1) & 7; rstcount = nj.rstinterval; for (i = 0; i < 3; ++i) nj.comp[i].dcpred = 0; } } nj.error = __NJ_FINISHED; } #if NJ_CHROMA_FILTER #define CF4A (-9) #define CF4B (111) #define CF4C (29) #define CF4D (-3) #define CF3A (28) #define CF3B (109) #define CF3C (-9) #define CF3X (104) #define CF3Y (27) #define CF3Z (-3) #define CF2A (139) #define CF2B (-11) #define CF(x) njClip(((x) + 64) >> 7) NJ_INLINE void njUpsampleH(nj_component_t* c) { const int xmax = c->width - 3; unsigned char *out, *lin, *lout; int x, y; out = njAllocMem((c->width * c->height) << 1); if (!out) njThrow(NJ_OUT_OF_MEM); lin = c->pixels; lout = out; for (y = c->height; y; --y) { lout[0] = CF(CF2A * lin[0] + CF2B * lin[1]); lout[1] = CF(CF3X * lin[0] + CF3Y * lin[1] + CF3Z * lin[2]); lout[2] = CF(CF3A * lin[0] + CF3B * lin[1] + CF3C * lin[2]); for (x = 0; x < xmax; ++x) { lout[(x << 1) + 3] = CF(CF4A * lin[x] + CF4B * lin[x + 1] + CF4C * lin[x + 2] + CF4D * lin[x + 3]); lout[(x << 1) + 4] = CF(CF4D * lin[x] + CF4C * lin[x + 1] + CF4B * lin[x + 2] + CF4A * lin[x + 3]); } lin += c->stride; lout += c->width << 1; lout[-3] = CF(CF3A * lin[-1] + CF3B * lin[-2] + CF3C * lin[-3]); lout[-2] = CF(CF3X * lin[-1] + CF3Y * lin[-2] + CF3Z * lin[-3]); lout[-1] = CF(CF2A * lin[-1] + CF2B * lin[-2]); } c->width <<= 1; c->stride = c->width; njFreeMem(c->pixels); c->pixels = out; } NJ_INLINE void njUpsampleV(nj_component_t* c) { const int w = c->width, s1 = c->stride, s2 = s1 + s1; unsigned char *out, *cin, *cout; int x, y; out = njAllocMem((c->width * c->height) << 1); if (!out) njThrow(NJ_OUT_OF_MEM); for (x = 0; x < w; ++x) { cin = &c->pixels[x]; cout = &out[x]; *cout = CF(CF2A * cin[0] + CF2B * cin[s1]); cout += w; *cout = CF(CF3X * cin[0] + CF3Y * cin[s1] + CF3Z * cin[s2]); cout += w; *cout = CF(CF3A * cin[0] + CF3B * cin[s1] + CF3C * cin[s2]); cout += w; cin += s1; for (y = c->height - 3; y; --y) { *cout = CF(CF4A * cin[-s1] + CF4B * cin[0] + CF4C * cin[s1] + CF4D * cin[s2]); cout += w; *cout = CF(CF4D * cin[-s1] + CF4C * cin[0] + CF4B * cin[s1] + CF4A * cin[s2]); cout += w; cin += s1; } cin += s1; *cout = CF(CF3A * cin[0] + CF3B * cin[-s1] + CF3C * cin[-s2]); cout += w; *cout = CF(CF3X * cin[0] + CF3Y * cin[-s1] + CF3Z * cin[-s2]); cout += w; *cout = CF(CF2A * cin[0] + CF2B * cin[-s1]); } c->height <<= 1; c->stride = c->width; njFreeMem(c->pixels); c->pixels = out; } #else NJ_INLINE void njUpsample(nj_component_t* c) { int x, y, xshift = 0, yshift = 0; unsigned char *out, *lin, *lout; while (c->width < nj.width) { c->width <<= 1; ++xshift; } while (c->height < nj.height) { c->height <<= 1; ++yshift; } out = njAllocMem(c->width * c->height); if (!out) njThrow(NJ_OUT_OF_MEM); lin = c->pixels; lout = out; for (y = 0; y < c->height; ++y) { lin = &c->pixels[(y >> yshift) * c->stride]; for (x = 0; x < c->width; ++x) lout[x] = lin[x >> xshift]; lout += c->width; } c->stride = c->width; njFreeMem(c->pixels); c->pixels = out; } #endif NJ_INLINE void njConvert() { int i; nj_component_t* c; for (i = 0, c = nj.comp; i < nj.ncomp; ++i, ++c) { #if NJ_CHROMA_FILTER while ((c->width < nj.width) || (c->height < nj.height)) { if (c->width < nj.width) njUpsampleH(c); njCheckError(); if (c->height < nj.height) njUpsampleV(c); njCheckError(); } #else if ((c->width < nj.width) || (c->height < nj.height)) njUpsample(c); #endif if ((c->width < nj.width) || (c->height < nj.height)) njThrow(NJ_INTERNAL_ERR); } if (nj.ncomp == 3) { // convert to RGB int x, yy; unsigned char *prgb = nj.rgb; const unsigned char *py = nj.comp[0].pixels; const unsigned char *pcb = nj.comp[1].pixels; const unsigned char *pcr = nj.comp[2].pixels; for (yy = nj.height; yy; --yy) { for (x = 0; x < nj.width; ++x) { register int y = py[x] << 8; register int cb = pcb[x] - 128; register int cr = pcr[x] - 128; *prgb++ = njClip((y + 359 * cr + 128) >> 8); *prgb++ = njClip((y - 88 * cb - 183 * cr + 128) >> 8); *prgb++ = njClip((y + 454 * cb + 128) >> 8); } py += nj.comp[0].stride; pcb += nj.comp[1].stride; pcr += nj.comp[2].stride; } } else if (nj.comp[0].width != nj.comp[0].stride) { // grayscale -> only remove stride unsigned char *pin = &nj.comp[0].pixels[nj.comp[0].stride]; unsigned char *pout = &nj.comp[0].pixels[nj.comp[0].width]; int y; for (y = nj.comp[0].height - 1; y; --y) { njCopyMem(pout, pin, nj.comp[0].width); pin += nj.comp[0].stride; pout += nj.comp[0].width; } nj.comp[0].stride = nj.comp[0].width; } } void njInit(void) { njFillMem(&nj, 0, sizeof(nj_context_t)); } void njDone(void) { int i; for (i = 0; i < 3; ++i) if (nj.comp[i].pixels) njFreeMem((void*) nj.comp[i].pixels); if (nj.rgb) njFreeMem((void*) nj.rgb); njInit(); } nj_result_t njDecode(const void* jpeg, const int size) { njDone(); nj.pos = (const unsigned char*) jpeg; nj.size = size & 0x7FFFFFFF; if (nj.size < 2) return NJ_NO_JPEG; if ((nj.pos[0] ^ 0xFF) | (nj.pos[1] ^ 0xD8)) return NJ_NO_JPEG; njSkip(2); while (!nj.error) { if ((nj.size < 2) || (nj.pos[0] != 0xFF)) return NJ_SYNTAX_ERROR; njSkip(2); switch (nj.pos[-1]) { case 0xC0: njDecodeSOF(); break; case 0xC4: njDecodeDHT(); break; case 0xDB: njDecodeDQT(); break; case 0xDD: njDecodeDRI(); break; case 0xDA: njDecodeScan(); break; case 0xFE: njSkipMarker(); break; default: if ((nj.pos[-1] & 0xF0) == 0xE0) njSkipMarker(); else return NJ_UNSUPPORTED; } } if (nj.error != __NJ_FINISHED) return nj.error; nj.error = NJ_OK; njConvert(); return nj.error; } int njGetWidth(void) { return nj.width; } int njGetHeight(void) { return nj.height; } int njIsColor(void) { return (nj.ncomp != 1); } unsigned char* njGetImage(void) { return (nj.ncomp == 1) ? nj.comp[0].pixels : nj.rgb; } int njGetImageSize(void) { return nj.width * nj.height * nj.ncomp; } #endif // _NJ_INCLUDE_HEADER_ONLY
34.141907
120
0.520425
dk00
d45284ba5583709a12d74e1d5b741b1777075e51
683
cxx
C++
NeosegPipeline/AntsJointFusionParameters.cxx
KevinPhamCPE/Neosegpipeline
91b4c4f3e56dd5f3203d240a5aca932c28287bd3
[ "Apache-2.0" ]
null
null
null
NeosegPipeline/AntsJointFusionParameters.cxx
KevinPhamCPE/Neosegpipeline
91b4c4f3e56dd5f3203d240a5aca932c28287bd3
[ "Apache-2.0" ]
null
null
null
NeosegPipeline/AntsJointFusionParameters.cxx
KevinPhamCPE/Neosegpipeline
91b4c4f3e56dd5f3203d240a5aca932c28287bd3
[ "Apache-2.0" ]
null
null
null
#include "AntsJointFusionParameters.h" AntsJointFusionParameters::AntsJointFusionParameters() { m_output_dir_default=""; m_output_dir=m_output_dir_default; m_compute_rois_parc_fusion_default= false ; m_compute_rois_parc_fusion=m_compute_rois_parc_fusion_default; } void AntsJointFusionParameters::setOutputDir(QString output_dir) { m_output_dir=output_dir; } QString AntsJointFusionParameters::getOutputDir() { return m_output_dir; } void AntsJointFusionParameters::setRoicParcFusion(bool rois_parc_fusion) { m_compute_rois_parc_fusion=rois_parc_fusion; } bool AntsJointFusionParameters::getRoicParcFusion() { return m_compute_rois_parc_fusion; }
20.088235
72
0.82284
KevinPhamCPE
d453fbb44894c49055ea505f25e6961ee52c79f2
456
hpp
C++
library/ATF/DLGTEMPLATE.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/DLGTEMPLATE.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/DLGTEMPLATE.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> START_ATF_NAMESPACE #pragma pack(push, 2) const struct DLGTEMPLATE { unsigned int style; unsigned int dwExtendedStyle; unsigned __int16 cdit; __int16 x; __int16 y; __int16 cx; __int16 cy; }; #pragma pack(pop) END_ATF_NAMESPACE
21.714286
108
0.649123
lemkova
d454b0536ea3bd6a168d8daac1a5c6451443e237
4,488
cpp
C++
UnitTest/Primitive.cpp
garlyon/onion2
b20d966de6a9ddeee0b66478d50725d1eaaad4c8
[ "MIT" ]
null
null
null
UnitTest/Primitive.cpp
garlyon/onion2
b20d966de6a9ddeee0b66478d50725d1eaaad4c8
[ "MIT" ]
null
null
null
UnitTest/Primitive.cpp
garlyon/onion2
b20d966de6a9ddeee0b66478d50725d1eaaad4c8
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "CppUnitTest.h" #include "../Collision/Primitive.h" #include "Tetrahedron.h" #include <set> #include <algorithm> using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace UnitTest { TEST_CLASS( Neighborhood ) { template <typename A, typename B> void check( A a, B b ) { std::set<std::pair<size_t, size_t>> ids; a.forEachNb( [&ids, b]( auto, auto pa ) { b.forEachNb( [&ids, pa]( auto, auto pb ) { Assert::IsTrue( ids.insert( { id( pa ), id( pb ) } ).second ); } ); } ); } public: TEST_METHOD( UniqueNbId ) { Test_NS::Tetrahedron x, y; using V = Collision_NS::Vert; using E = Collision_NS::Edge; using F = Collision_NS::Face; check<V, V>( x.a, y.a ); check<V, E>( x.a, y.a ); check<V, F>( x.a, y.a ); check<E, V>( x.a, y.a ); check<E, E>( x.a, y.a ); check<E, F>( x.a, y.a ); check<F, V>( x.a, y.a ); check<F, E>( x.a, y.a ); } }; TEST_CLASS( PrimitiveId ) { public: TEST_METHOD( FaceId ) { QEdge_NS::Shape s; auto a = s.makeEdge(); auto b = s.makeEdge(); auto c = s.makeEdge(); a.splice0( b.sym() ); b.splice0( c.sym() ); c.splice0( a.sym() ); Assert::AreEqual( a.l().id(), b.l().id() ); Assert::AreEqual( c.l().id(), c.l().id() ); Assert::AreEqual<size_t>( a.l().id(), id( Collision_NS::Face( a ) ) ); Assert::AreEqual<size_t>( b.l().id(), id( Collision_NS::Face( b ) ) ); Assert::AreEqual<size_t>( c.l().id(), id( Collision_NS::Face( c ) ) ); Assert::AreEqual<size_t>( a.r().id(), id( Collision_NS::Face( a.sym() ) ) ); Assert::AreEqual<size_t>( b.r().id(), id( Collision_NS::Face( b.sym() ) ) ); Assert::AreEqual<size_t>( c.r().id(), id( Collision_NS::Face( c.sym() ) ) ); } TEST_METHOD( EdgeId ) { QEdge_NS::Shape s; auto a = s.makeEdge(); auto b = s.makeEdge(); auto c = s.makeEdge(); a.splice0( b.sym() ); b.splice0( c.sym() ); c.splice0( a.sym() ); Assert::AreEqual<size_t>( a.id(), id( Collision_NS::Edge( a ) ) ); Assert::AreEqual<size_t>( b.id(), id( Collision_NS::Edge( b ) ) ); Assert::AreEqual<size_t>( c.id(), id( Collision_NS::Edge( c ) ) ); Assert::AreEqual<size_t>( a.id(), id( Collision_NS::Edge( a.sym() ) ) ); Assert::AreEqual<size_t>( b.id(), id( Collision_NS::Edge( b.sym() ) ) ); Assert::AreEqual<size_t>( c.id(), id( Collision_NS::Edge( c.sym() ) ) ); } TEST_METHOD( VertId ) { QEdge_NS::Shape s; auto a = s.makeEdge(); auto b = s.makeEdge(); auto c = s.makeEdge(); a.splice0( b.sym() ); b.splice0( c.sym() ); c.splice0( a.sym() ); Assert::AreEqual<size_t>( a.o().id(), id( Collision_NS::Vert( a ) ) ); Assert::AreEqual<size_t>( b.o().id(), id( Collision_NS::Vert( b ) ) ); Assert::AreEqual<size_t>( c.o().id(), id( Collision_NS::Vert( c ) ) ); Assert::AreEqual<size_t>( a.d().id(), id( Collision_NS::Vert( a.sym() ) ) ); Assert::AreEqual<size_t>( b.d().id(), id( Collision_NS::Vert( b.sym() ) ) ); Assert::AreEqual<size_t>( c.d().id(), id( Collision_NS::Vert( c.sym() ) ) ); } }; TEST_CLASS( Major ) { public: TEST_METHOD( Vert ) { Test_NS::Tetrahedron t; Assert::AreEqual( id( major( Collision_NS::Vert( t.A ) ) ), id( major( Collision_NS::Vert( t.B ) ) ) ); Assert::AreEqual( id( major( Collision_NS::Vert( t.B ) ) ), id( major( Collision_NS::Vert( t.C ) ) ) ); Assert::AreNotEqual( id( major( Collision_NS::Vert( t.a ) ) ), id( major( Collision_NS::Vert( t.A ) ) ) ); } TEST_METHOD( Edge ) { Test_NS::Tetrahedron t; Assert::AreEqual( id( major( Collision_NS::Edge( t.a ) ) ), id( major( Collision_NS::Edge( t.a.sym() ) ) ) ); Assert::AreNotEqual( id( major( Collision_NS::Edge( t.a ) ) ), id( major( Collision_NS::Edge( t.b ) ) ) ); } TEST_METHOD( Face ) { Test_NS::Tetrahedron t; Assert::AreEqual( id( major( Collision_NS::Face( t.a ) ) ), id( major( Collision_NS::Face( t.b ) ) ) ); Assert::AreEqual( id( major( Collision_NS::Face( t.a ) ) ), id( major( Collision_NS::Face( t.c ) ) ) ); Assert::AreNotEqual( id( major( Collision_NS::Face( t.a ) ) ), id( major( Collision_NS::Face( t.A ) ) ) ); } }; }
28.769231
115
0.532531
garlyon
d4556d997b55c84d1489226659aa8bd4165e704f
5,888
cpp
C++
Phase #3/Items.cpp
Squshy/sqa-baller-squad-v2
a63cac6d24f282137864453727fa1c35371997fd
[ "MIT" ]
null
null
null
Phase #3/Items.cpp
Squshy/sqa-baller-squad-v2
a63cac6d24f282137864453727fa1c35371997fd
[ "MIT" ]
null
null
null
Phase #3/Items.cpp
Squshy/sqa-baller-squad-v2
a63cac6d24f282137864453727fa1c35371997fd
[ "MIT" ]
1
2020-02-27T13:18:06.000Z
2020-02-27T13:18:06.000Z
/** * Items Function Definition file for Our Auction Sales Service Project * * @author Paul Kerrigan, Henry Zheng, Calvin Lapp * @date January 24, 2020 * @version 1.0 * @name Items.cpp */ #include "Items.h" #include <string> #include "Users.h" #include "AuctionLib.h" string** bidList; int bidListCount = 0; bool itemMatch = false; bool itemCheck = false; int itemLength = 0; string itemNameListCut = ""; const string EXIT = "exit"; int j = 0; string usernameplusspaces = ""; Items::Items(){ } void Items::CheckItems(string** items, int itemCount, Users user){ //Item stores the username + spaces for a total of 16 characters //So we need to add spaces at the end of user's username until it's 16 characters long to compare properly usernameplusspaces = user.getUserName(); for (int i = user.getUserName().length(); i < 16; i++){ usernameplusspaces += " "; } for (int i = 0; i < itemCount; i++){ //Compares username but right now item stores the username + spaces //Either trim the spaces at the end or add spaces at the end of user input until it's 15 characters long if(usernameplusspaces.compare(items[i][2]) == 0){ bidListCount++; } } bidList = new string*[bidListCount]; for (int i = 0; i < bidListCount; i++){ bidList[i] = new string[5]; } if (bidListCount <= 0){ cout << "\nYou have no items in auction."; }else if(bidListCount >= 1){ for (int i = 0; i < itemCount; i++){ //Get Item name, seller's name, remaining days and current bid when it matches //TODO: Check if seller's name is same as current user and don't add it in bidList if(usernameplusspaces.compare(items[i][2]) == 0){ //We need i on the items array but we want to increment bidList[j][0] = items[i][1]; //Item ID bidList[j][1] = items[i][1]; //Item Name bidList[j][2] = items[i][3]; //Current bidder's name bidList[j][3] = items[i][4]; //Remaining days bidList[j][4] = items[i][5]; //Current Bid j++; } } } for (int i = 0; i < bidListCount; i++){ std::cout << "\n" << i << ". " << bidList[i][0] << " " << bidList[i][1] << " " << bidList[i][2] << " " << bidList[i][3] << " " << bidList[i][4]; } } void Items::FindItems(string** items, int itemCount){ // Resets string** bidList; int bidListCount = 0; bool itemMatch = false; bool itemCheck = false; int itemLength = 0; string itemNameListCut = ""; int j = 0; while (itemMatch == false){ itemName = ""; itemCheck = false; while (itemCheck == false){ std::cout << "\nEnter an Item name: "; getline(cin, itemName); if (exitCmd(itemName)){ std::cout << "Hi " << exitCmd(itemName); break; } //Item name has to be 19 characters or fewer if (itemName.length() > MAX_ITEM_NAME_LENGTH){ std::cout << "\nItem Name must be 19 characters or fewer"; } else{ itemCheck = true; } } //Get the first number of characters based on the length of input of itemName and see if they match //So if someone types Ham //Ham, Hammer, Hamster gets sent into bidList and is counted, while han,hanmster,chammer doesn't //TODO: This needs to ignore case sensitivity //Compare input to the item file in a loop and add it into an array if matches itemLength = itemName.length(); //Gets the total number of matching items, which will be used for the array for (int i = 0; i < itemCount; i++){ itemNameListCut = items[i][1].substr(0,itemLength); if(itemName.compare(itemNameListCut) == 0){ bidListCount++; } } //If itemCount is 0 then that means there are no matches and will prompt user to start over if (bidListCount == 0){ std::cout << "\nThere are no matching results. Please enter a new item name."; itemCheck = false; //reset itemNameCheck }else{ itemMatch = true; } // 2D array for the bidlist to contain item name and current bid on it bidList = new string*[bidListCount]; for (int i = 0; i < bidListCount; i++){ bidList[i] = new string[4]; } //Now we can put the item name, seller's name, remaining days and current bid inside with this defined array for (int i = 0; i < itemCount; i++){ itemNameListCut = items[i][1].substr(0,itemLength); //Get Item name, seller's name, remaining days and current bid when it matches //TODO: Check if seller's name is same as current user and don't add it in bidList if(itemName.compare(itemNameListCut) == 0){ //We need i on the items array but we want to increment bidList[j][0] = items[i][1]; //Item Name bidList[j][1] = items[i][2]; //Seller's name bidList[j][2] = items[i][4]; //Remaining days bidList[j][3] = items[i][5]; //Current Bid j++; } } //Do another for loop and print out each item with a cooresponding number for user to input, the name and the current bid per line // Calculates the number of elements inside an array for (int i = 0; i < bidListCount; i++){ std::cout << "\n" << i << ". " << bidList[i][0] << " " << bidList[i][1] << " " << bidList[i][2] << " " << bidList[i][3]; } } } bool Items::exitCmd(string buffer){ if (ToLower(buffer).compare(EXIT) == 0){ return true; }else { return false; } }
37.503185
152
0.563179
Squshy
d4560b83baff7d59f3efc50a387b12ff9f04e9f8
217
cpp
C++
source/Node.cpp
xzrunner/sop
80f84765548fde33d990663d4a4b8054bb6714d1
[ "MIT" ]
null
null
null
source/Node.cpp
xzrunner/sop
80f84765548fde33d990663d4a4b8054bb6714d1
[ "MIT" ]
null
null
null
source/Node.cpp
xzrunner/sop
80f84765548fde33d990663d4a4b8054bb6714d1
[ "MIT" ]
null
null
null
#include "sop/Node.h" #include <assert.h> namespace sop { Node::Node() : m_parms(*this) { } void Node::SetParent(const std::shared_ptr<Node>& node) { m_parent = node; m_level = node->m_level + 1; } }
10.85
55
0.617512
xzrunner
d456a7da80592d3581cbfa914084f3334757c7a2
7,927
cpp
C++
libhpx/scheduler/Scheduler.cpp
luglio/hpx5
6cbeebb8e730ee9faa4487dba31a38e3139e1ce7
[ "BSD-3-Clause" ]
1
2019-11-05T21:11:32.000Z
2019-11-05T21:11:32.000Z
libhpx/scheduler/Scheduler.cpp
ldalessa/hpx
c8888c38f5c12c27bfd80026d175ceb3839f0b40
[ "BSD-3-Clause" ]
null
null
null
libhpx/scheduler/Scheduler.cpp
ldalessa/hpx
c8888c38f5c12c27bfd80026d175ceb3839f0b40
[ "BSD-3-Clause" ]
3
2019-06-21T07:05:43.000Z
2020-11-21T15:24:04.000Z
// ============================================================================= // High Performance ParalleX Library (libhpx) // // Copyright (c) 2013-2017, Trustees of Indiana University, // All rights reserved. // // This software may be modified and distributed under the terms of the BSD // license. See the COPYING file for details. // // This software was created at the Indiana University Center for Research in // Extreme Scale Technologies (CREST). // ============================================================================= #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "libhpx/Scheduler.h" #include "Thread.h" #include "libhpx/debug.h" #include "libhpx/memory.h" #include "libhpx/Network.h" #include <cstring> #ifdef HAVE_APEX #include <sys/time.h> #endif namespace { using libhpx::Scheduler; using libhpx::Worker; using libhpx::scheduler::Thread; LIBHPX_ACTION(HPX_DEFAULT, HPX_MARSHALLED, SetOutput, Scheduler::SetOutputHandler, HPX_POINTER, HPX_SIZE_T); LIBHPX_ACTION(HPX_DEFAULT, 0, Stop, Scheduler::StopHandler); LIBHPX_ACTION(HPX_DEFAULT, 0, TerminateSPMD, Scheduler::TerminateSPMDHandler); } Scheduler::Scheduler(const config_t* cfg) : lock_(), stopped_(), state_(STOP), nextTlsId_(0), code_(HPX_SUCCESS), nActive_(cfg->threads), spmdCount_(0), nWorkers_(cfg->threads), nTarget_(cfg->threads), epoch_(0), spmd_(0), nsWait_(cfg->progress_period), output_(nullptr), workers_(nWorkers_) { Thread::SetStackSize(cfg->stacksize); // This thread can allocate even though it's not a scheduler thread. as_join(AS_REGISTERED); as_join(AS_GLOBAL); as_join(AS_CYCLIC); } Scheduler::~Scheduler() { for (auto&& w : workers_) { if (w) { w->shutdown(); delete w; } } as_leave(); } int Scheduler::start(int spmd, hpx_action_t act, void *out, int n, va_list *args) { log_dflt("hpx started running %d\n", epoch_); // Create the worker threads for the first epoch. if (epoch_ == 0) { for (int i = 0, e = nWorkers_; i < e; ++i) { workers_[i] = new Worker(i); } } // remember the output slot spmd_ = spmd; output_ = out; if (spmd_ || here->rank == 0) { hpx_parcel_t *p = action_new_parcel_va(act, HPX_HERE, 0, 0, n, args); parcel_prepare(p); workers_[0]->pushMail(p); } // switch the state and then start all the workers setCode(HPX_SUCCESS); setState(RUN); for (auto&& w : workers_) { w->start(); } // wait for someone to stop the scheduler { std::unique_lock<std::mutex> _(lock_); while (getState() == RUN) { wait(std::move(_)); } } // stop all of the worker threads for (auto&& w : workers_) { w->stop(); } // Use sched crude barrier to wait for the worker threads to stop. while (nActive_.load(std::memory_order_acquire)) { } // return the exit code DEBUG_IF (getCode() != HPX_SUCCESS && here->rank == 0) { log_error("hpx_run epoch exited with exit code (%d).\n", getCode()); } log_dflt("hpx stopped running %d\n", epoch_); // clear the output slot spmd_ = 0; output_ = NULL; // bump the epoch epoch_++; return getCode(); } void Scheduler::wait(std::unique_lock<std::mutex>&& lock) { #ifdef HAVE_APEX using std::min; using std::max; int prev = nTarget_; nTarget_ = min(apex_get_thread_cap(), nWorkers_); if (prev != nTarget_) { log_sched("apex adjusting from %d to %d workers\n", prev, nTarget_); } for (int i = min(prev, nTarget_), e = max(prev, nTarget_); i < e; ++i) { dbg_assert(workers_[i]); if (nTarget_ < prev) { workers_[i]->stop(); } else { workers_[i]->start(); } } #endif stopped_.wait_for(lock, nsWait_); } void Scheduler::setOutput(size_t bytes, const void* value) { if (!bytes) return; if (!output_) return; std::lock_guard<std::mutex> _(lock_); memcpy(output_, value, bytes); } void Scheduler::stop(uint64_t code) { std::lock_guard<std::mutex> _(lock_); dbg_assert(code < UINT64_MAX); setCode(int(code)); setState(Scheduler::STOP); stopped_.notify_all(); } void Scheduler::terminateSPMD() { if (++spmdCount_ != here->ranks) return; spmdCount_ = 0; hpx_addr_t sync = hpx_lco_and_new(here->ranks - 1); for (auto i = 0u, e = here->ranks; i < e; ++i) { if (i == here->rank) continue; hpx_parcel_t *p = action_new_parcel(Stop, // action HPX_THERE(i), // target 0, // continuation target 0, // continuation action 0); // number of args hpx_parcel_t *q = action_new_parcel(hpx_lco_set_action, // action sync, // target 0, // continuation target 0, // continuation action 0); // number of args parcel_prepare(p); parcel_prepare(q); dbg_check( here->net->send(p, q) ); } dbg_check( hpx_lco_wait(sync) ); hpx_lco_delete_sync(sync); stop(HPX_SUCCESS); } /// This is deceptively complex when we have synchronous network progress (i.e., /// when the scheduler is responsible for calling network progress from the /// schedule loop) because we can't stop the scheduler until we are sure that /// the signal has made it out. We use the network_send operation manually here /// because it allows us to wait for the `ssync` event (this event means that /// we're guaranteed that we don't need to keep progressing locally for the send /// to be seen remotely). /// /// Don't perform the local shutdown until we're sure all the remote shutdowns /// have gotten out, otherwise we might not progress the network enough. void Scheduler::exitDiffuse(size_t size, const void *out) { hpx_addr_t sync = hpx_lco_and_new(here->ranks - 1); for (auto i = 0u, e = here->ranks; i < e; ++i) { if (i == here->rank) continue; hpx_parcel_t *p = action_new_parcel(SetOutput, // action HPX_THERE(i), // target HPX_THERE(i), // continuation target Stop, // continuation action 2, // number of args out, // arg 0 size); // the 1 hpx_parcel_t *q = action_new_parcel(hpx_lco_set_action, // action sync, // target 0, // continuation target 0, // continuation action 0); // number of args parcel_prepare(p); parcel_prepare(q); dbg_check( here->net->send(p, q) ); } dbg_check( hpx_lco_wait(sync) ); hpx_lco_delete_sync(sync); setOutput(size, out); stop(HPX_SUCCESS); } void Scheduler::exitSPMD(size_t size, const void *out) { setOutput(size, out); hpx_call(HPX_THERE(0), TerminateSPMD, HPX_NULL); } void Scheduler::exit(size_t size, const void *out) { if (spmd_) { exitSPMD(size, out); } else { exitDiffuse(size, out); } hpx_thread_exit(HPX_SUCCESS); } int Scheduler::SetOutputHandler(const void *out, size_t bytes) { here->sched->setOutput(bytes, out); return HPX_SUCCESS; } int Scheduler::StopHandler(void) { here->sched->stop(HPX_SUCCESS); return HPX_SUCCESS; } int Scheduler::TerminateSPMDHandler() { here->sched->terminateSPMD(); return HPX_SUCCESS; } CallbackType Scheduler::begin_callback = nullptr; CallbackType Scheduler::before_transfer_callback = nullptr; CallbackType Scheduler::after_transfer_callback = nullptr;
27.054608
80
0.588369
luglio
d457e79f2a5d43b52250b34878bd5ed5d996e0d4
1,462
cpp
C++
ch16/ex16.53.54.55/main.cpp
zhang1990215/Cpp-Primer
81e51869c02f2ba75e4fe491dee07eaedce2bbc9
[ "CC0-1.0" ]
null
null
null
ch16/ex16.53.54.55/main.cpp
zhang1990215/Cpp-Primer
81e51869c02f2ba75e4fe491dee07eaedce2bbc9
[ "CC0-1.0" ]
null
null
null
ch16/ex16.53.54.55/main.cpp
zhang1990215/Cpp-Primer
81e51869c02f2ba75e4fe491dee07eaedce2bbc9
[ "CC0-1.0" ]
null
null
null
/*************************************************************************** * @file main.cpp * @author Yue Wang * @date 16 Feb 2014 Aug, 2015 * @remark This code is for the exercises from C++ Primer 5th Edition * @note ***************************************************************************/ // // Exercise 16.53: // Write your own version of the print functions and test them by printing // one, two, and five arguments, each of which should have different types. // // Exercise 16.54: // What happens if we call print on a type that doesn’t have an << operator? // It didn't compile. // // Exercise 16.55: // Explain how the variadic version of print would execute if we declared // the nonvariadic version of print after the definition of the variadic // version. // error: no matching function for call to 'print(std::ostream&)' // #include <iostream> // trivial case template<typename Printable> std::ostream& print(std::ostream& os, Printable const& printable) { return os << printable; } // recursion template<typename Printable, typename... Args> std::ostream& print(std::ostream& os, Printable const& printable, Args const&... rest) { return print(os << printable << ", ", rest...); } int main(int argc, char const *argv[]) { print(std::cout, 1) << std::endl; print(std::cout, 1, 2) << std::endl; print(std::cout, 1, 2, 3, 4, "sss", 42.4242) << std::endl; return 0; }
30.458333
86
0.583447
zhang1990215
d4581f440f129559d780b917380b8f7c797c9d36
2,548
cpp
C++
Algorithms/KMPAlgorithm/Algo.cpp
TeacherManoj0131/HacktoberFest2020-Contributions
c7119202fdf211b8a6fc1eadd0760dbb706a679b
[ "MIT" ]
256
2020-09-30T19:31:34.000Z
2021-11-20T18:09:15.000Z
Algorithms/KMPAlgorithm/Algo.cpp
TeacherManoj0131/HacktoberFest2020-Contributions
c7119202fdf211b8a6fc1eadd0760dbb706a679b
[ "MIT" ]
293
2020-09-30T19:14:54.000Z
2021-06-06T02:34:47.000Z
Algorithms/KMPAlgorithm/Algo.cpp
TeacherManoj0131/HacktoberFest2020-Contributions
c7119202fdf211b8a6fc1eadd0760dbb706a679b
[ "MIT" ]
1,620
2020-09-30T18:37:44.000Z
2022-03-03T20:54:22.000Z
#include<bits/stdc++.h> #include<algorithm> using namespace std; /*standard declarations*/ typedef long long ll; typedef long double ld; typedef vector<ll> vll; typedef vector<pair<ll,ll> > vllp; #define fr(i,a,b) for(ll i=a;i<b;i++) #define frr(i,a,b) for(ll i=a;i>=b;i--) #define forn(i, n) for (ll i = 0; i < ll(n); i++) #define err() cout<<"=================================="<<endl; #define errA(A) for(auto i:A) cout<<i<<" ";cout<<endl; #define all(A) A.begin(),A.end() #define allr(A) A.rbegin(),A.rend() #define ft first #define sd second #define pb push_back /*global variables here*/ ll TESTTEST; #define mxn 2000001 #define PI 3.14159265 #define mod 1000000007 ll dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}}; ll n,k; /*global functions here*/ void KMPsearch(string pat,string txt){ ll n=txt.length(); // the data-string we have ll m=pat.length(); // the pattern-string we want to search ll lps[m]; ll len=0; ll i=1; lps[0]=0; while(i<m){ // creating prefix functio for pattern we want to search if(pat[i]==pat[len]){ lps[i]=len+1; len++; i++; } else{ if(len!=0){ // optimisation consider this case abcabx-----abcabc here abcabc!=abcabx so we should not make len=0 len=lps[len-1]; // instead we can still see for abc and abc can still make len=3; rest u can think ! } else{ lps[i]=0; i++; } } } //for(ll x:lps)cout<<x<<" "; //cout<<"\n"; ll j=0; i=0; while(i<n){ // we are here matching the pattern and strings if(txt[i]==pat[j]){ // if both the corresponding indexes match , move forward i++,j++; } else{ if(j!=0){ // corner case where lps[-1] cant be used hence as the first letter also dont match j=lps[j-1]; } else{ i++; } } if(j==m){ // strings matched process answer here cout<<i<<" "; j=lps[j-1]; // still looking for optimised matching } } } /*main function here*/ void solve(){ string pat,txt; cin>>pat>>txt; cout<<"beforefunctioncalled:\n"; KMPsearch(pat,txt); cout<<"afterfunctioncalled:\n"; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll zzz=1; //cin>>zzz; for(TESTTEST=1;TESTTEST<(zzz+1);TESTTEST++){ solve(); } return 0; }
27.106383
129
0.525118
TeacherManoj0131
d45d7682898972cc69119762cca36a6c940746be
1,299
hpp
C++
import/include/asio_OIR/detail/reactor_fwd.hpp
goodspeed24e/2014iOT
139f6e2131f8a94cb876328b5f733e3feef77707
[ "MIT" ]
1
2019-04-15T14:10:58.000Z
2019-04-15T14:10:58.000Z
import/include/asio_OIR/detail/reactor_fwd.hpp
goodspeed24e/2014iOT
139f6e2131f8a94cb876328b5f733e3feef77707
[ "MIT" ]
null
null
null
import/include/asio_OIR/detail/reactor_fwd.hpp
goodspeed24e/2014iOT
139f6e2131f8a94cb876328b5f733e3feef77707
[ "MIT" ]
2
2019-10-31T09:11:09.000Z
2021-09-17T01:00:49.000Z
// // detail/reactor_fwd.hpp // ~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2011 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef ASIO_DETAIL_REACTOR_FWD_HPP #define ASIO_DETAIL_REACTOR_FWD_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_IOCP) # include "asio/detail/select_reactor_fwd.hpp" #elif defined(ASIO_HAS_EPOLL) # include "asio/detail/epoll_reactor_fwd.hpp" #elif defined(ASIO_HAS_KQUEUE) # include "asio/detail/kqueue_reactor_fwd.hpp" #elif defined(ASIO_HAS_DEV_POLL) # include "asio/detail/dev_poll_reactor_fwd.hpp" #else # include "asio/detail/select_reactor_fwd.hpp" #endif namespace asio { namespace detail { #if defined(ASIO_HAS_IOCP) typedef select_reactor reactor; #elif defined(ASIO_HAS_EPOLL) typedef epoll_reactor reactor; #elif defined(ASIO_HAS_KQUEUE) typedef kqueue_reactor reactor; #elif defined(ASIO_HAS_DEV_POLL) typedef dev_poll_reactor reactor; #else typedef select_reactor reactor; #endif } // namespace detail } // namespace asio #endif // ASIO_DETAIL_REACTOR_FWD_HPP
25.470588
79
0.769823
goodspeed24e
d45f75408662bdc0d88b55bd1b2bc4cb45817322
2,864
cpp
C++
modules/task_2/ivina_a_fox_alg_omp/main.cpp
allnes/pp_2022_spring
159191f9c2f218f8b8487f92853cc928a7652462
[ "BSD-3-Clause" ]
null
null
null
modules/task_2/ivina_a_fox_alg_omp/main.cpp
allnes/pp_2022_spring
159191f9c2f218f8b8487f92853cc928a7652462
[ "BSD-3-Clause" ]
null
null
null
modules/task_2/ivina_a_fox_alg_omp/main.cpp
allnes/pp_2022_spring
159191f9c2f218f8b8487f92853cc928a7652462
[ "BSD-3-Clause" ]
2
2022-03-31T17:48:22.000Z
2022-03-31T18:06:07.000Z
// Copyright 2022 Ivina Anastasiya #include <gtest/gtest.h> #include <omp.h> #include <vector> #include "./Fox_alg_omp.h" constexpr int NumThreads = 4; TEST(MatrixMultPar, RandNumCorrectSize) { const int size = 3; std::vector<std::vector<double>> MatrixA(size, std::vector<double>(size, 0)); MatrixA = FillMatrixRandom(MatrixA); std::vector<std::vector<double>> MatrixB(size, std::vector<double>(size, 0)); MatrixB = FillMatrixRandom(MatrixB); ASSERT_NO_THROW(Fox(MatrixA, MatrixB, NumThreads)); } TEST(MatrixMultPar, RandNumWrongSize) { const int row1 = 3; const int col1 = 5; std::vector<std::vector<double>> MatrixA(row1, std::vector<double>(col1, 0)); MatrixA = FillMatrixRandom(MatrixA); const int row2 = 1; const int col2 = 4; std::vector<std::vector<double>> MatrixB(row2, std::vector<double>(col2, 0)); MatrixB = FillMatrixRandom(MatrixB); ASSERT_ANY_THROW(Fox(MatrixA, MatrixB, NumThreads)); } TEST(MatrixMultPar, ConstNumFox) { std::vector<std::vector<double>> MatrixA{ {1.2, 3.1, 2.7}, {3.5, 2.5, 1.9}, {2.1, 5, 5.1}, }; std::vector<std::vector<double>> MatrixB{ {2.6, 5.1, 2.4}, {1.7, 4.5, 3.2}, {6.1, 3.5, 1.2}, }; std::vector<std::vector<double>> MatrixC{ {24.86, 29.52, 16.04}, {24.94, 35.75, 18.68}, {45.07, 51.06, 27.16}, }; std::vector<std::vector<double>> MatrixD = Fox(MatrixA, MatrixB, NumThreads); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { ASSERT_DOUBLE_EQ(MatrixC[i][j], MatrixD[i][j]); } } } TEST(MatrixMultPar, RandNumCompareToBlock) { const int n = 3; std::vector<std::vector<double>> MatrixA(n, std::vector<double>(n, 0)); MatrixA = FillMatrixRandom(MatrixA); std::vector<std::vector<double>> MatrixB(n, std::vector<double>(n, 0)); MatrixB = FillMatrixRandom(MatrixB); std::vector<std::vector<double>> MatrixC = BlockMatrixMultiplication(MatrixA, MatrixB); std::vector<std::vector<double>> MatrixD = Fox(MatrixA, MatrixB, NumThreads); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { ASSERT_DOUBLE_EQ(MatrixC[i][j], MatrixD[i][j]); } } } TEST(MatrixMultPar, RandNumCompareToDence) { const int n = 3; std::vector<std::vector<double>> MatrixA(n, std::vector<double>(n, 0)); MatrixA = FillMatrixRandom(MatrixA); std::vector<std::vector<double>> MatrixB(n, std::vector<double>(n, 0)); MatrixB = FillMatrixRandom(MatrixB); std::vector<std::vector<double>> MatrixC = DenseMatrixMultiplication(MatrixA, MatrixB); std::vector<std::vector<double>> MatrixD = Fox(MatrixA, MatrixB, NumThreads); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { ASSERT_DOUBLE_EQ(MatrixC[i][j], MatrixD[i][j]); } } } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
29.525773
79
0.63757
allnes
d461774f952bed1c0d629aa1a558f1dc90ec3f9e
10,453
cpp
C++
src/MapDrawer.cpp
sarthou/semantic_map_drawer
2e1bce2fdefb25d87194a5ee888b03c2807b0bca
[ "Apache-2.0" ]
null
null
null
src/MapDrawer.cpp
sarthou/semantic_map_drawer
2e1bce2fdefb25d87194a5ee888b03c2807b0bca
[ "Apache-2.0" ]
null
null
null
src/MapDrawer.cpp
sarthou/semantic_map_drawer
2e1bce2fdefb25d87194a5ee888b03c2807b0bca
[ "Apache-2.0" ]
null
null
null
#include "route_drawer/MapDrawer.h" #include <opencv2/imgproc/imgproc.hpp> void MapDrawer::draw(std::vector<corridor_t> corridors) { for(size_t i = 0; i < corridors.size(); i++) drawOneCorridor(corridors[i]); } void MapDrawer::draw(std::vector<openspace_t> openspaces) { for(size_t i = 0; i < openspaces.size(); i++) drawOneCorridor(openspace2corridor(openspaces[i])); } corridor_t MapDrawer::openspace2corridor(openspace_t openspace) { corridor_t res; size_t half = openspace.around_.size() / 2; std::vector<std::string> side_I, side_II; for(size_t i = 0; i < half; i++) side_I.push_back(openspace.around_[i]); for(size_t i = half; i < openspace.around_.size(); i++) side_II.push_back(openspace.around_[i]); std::vector<std::string> side_1, side_2, side_3, side_4; half = side_I.size() / 2; for(size_t i = 0; i < half; i++) side_1.push_back(side_I[i]); for(size_t i = half; i < side_I.size(); i++) side_2.push_back(side_I[i]); half = side_II.size() / 2; for(size_t i = 0; i < half; i++) side_3.push_back(side_II[i]); for(size_t i = half; i < side_II.size(); i++) side_4.push_back(side_II[i]); res.name_ = openspace.name_; res.in_front_of_ = openspace.in_front_of_; res.at_end_edge_ = side_1; std::reverse(side_2.begin(),side_2.end()); res.at_right_ = side_2; std::reverse(side_3.begin(),side_3.end()); res.at_begin_edge_ = side_3; res.at_left_ = side_4; return res; } void MapDrawer::drawOneCorridor(corridor_t corridor) { size_t nb_places = 0; image = cvCreateImage(cvSize(1000, 400), IPL_DEPTH_8U, 3); cvSet(image, cvScalar(255,255,255)); drawCorridor_t to_draw; size_t height_offset = 50; size_t width_offset = 50; for(size_t begin_i = 0; begin_i < corridor.at_begin_edge_.size(); begin_i++) { rect_t rect(width_offset, height_offset + rect_t::HEIGHT * (begin_i + 1), rect_t::WIDTH, rect_t::HEIGHT); to_draw.at_begin_edge_rects_.push_back(rect); to_draw.at_begin_edge_names_.push_back(corridor.at_begin_edge_[begin_i]); nb_places++; } for(size_t left_i = 0; left_i < corridor.at_left_.size(); left_i++) { rect_t rect(width_offset + rect_t::WIDTH * (left_i + 1), height_offset, rect_t::WIDTH, rect_t::HEIGHT); to_draw.at_left_rects_.push_back(rect); to_draw.at_left_names_.push_back(corridor.at_left_[left_i]); nb_places++; } height_offset = height_offset + (corridor.at_begin_edge_.size() + 1) * rect_t::HEIGHT; for(size_t right_i = 0; right_i < corridor.at_right_.size(); right_i++) { rect_t rect(width_offset + rect_t::WIDTH * (right_i + 1), height_offset, rect_t::WIDTH, rect_t::HEIGHT); to_draw.at_right_rects_.push_back(rect); to_draw.at_right_names_.push_back(corridor.at_right_[right_i]); nb_places++; } int right_trig_pose = -1; int left_trig_pose = -1; findRightLeftTrigger(corridor, right_trig_pose, left_trig_pose); if((right_trig_pose != -1) && (left_trig_pose != -1)) { while((right_trig_pose != -1) && (left_trig_pose != -1)) { to_draw.at_right_rects_[right_trig_pose].fix_ = true; to_draw.at_left_rects_[left_trig_pose].fix_ = true; if(right_trig_pose > left_trig_pose) { int move_of = to_draw.at_right_rects_[right_trig_pose].x - to_draw.at_left_rects_[left_trig_pose].x; for(size_t left_i = left_trig_pose; left_i < to_draw.at_left_rects_.size(); left_i++) to_draw.at_left_rects_[left_i].x += move_of; int fix = getPreviousFix(to_draw.at_left_rects_, left_trig_pose); if(fix != -1) { int delta = to_draw.at_left_rects_[left_trig_pose].x_top() - to_draw.at_left_rects_[fix].x_bot(); size_t nb = left_trig_pose - fix + 1; int add = delta /nb; to_draw.at_left_rects_[fix].x += add/2; to_draw.at_left_rects_[fix].width += add; for(size_t move_i = 1; move_i < nb - 1; move_i++) { to_draw.at_left_rects_[fix + move_i].x += add/2 + add*move_i; to_draw.at_left_rects_[fix + move_i].width += add; } to_draw.at_left_rects_[left_trig_pose].x -= add/2; to_draw.at_left_rects_[left_trig_pose].width += add; } } else if(right_trig_pose < left_trig_pose) { int move_of = to_draw.at_left_rects_[left_trig_pose].x - to_draw.at_right_rects_[right_trig_pose].x; for(size_t right_i = right_trig_pose; right_i < to_draw.at_right_rects_.size(); right_i++) to_draw.at_right_rects_[right_i].x += move_of; int fix = getPreviousFix(to_draw.at_right_rects_, right_trig_pose); if(fix != -1) { int delta = to_draw.at_right_rects_[right_trig_pose].x_top() - to_draw.at_right_rects_[fix].x_bot(); size_t nb = right_trig_pose - fix + 1; int add = delta /nb; to_draw.at_right_rects_[fix].x += add/2; to_draw.at_right_rects_[fix].width += add; for(size_t move_i = 1; move_i < nb - 1; move_i++) { to_draw.at_right_rects_[fix + move_i].x += add/2 + add*move_i; to_draw.at_right_rects_[fix + move_i].width += add; } to_draw.at_right_rects_[right_trig_pose].x -= add/2; to_draw.at_right_rects_[right_trig_pose].width += add; } } else { std::cout << "ALIGNED" << std::endl; } findRightLeftTrigger(corridor, right_trig_pose, left_trig_pose); } } if((to_draw.at_right_rects_.size() > 0) && (to_draw.at_left_rects_.size() > 0)) if(to_draw.at_right_rects_[to_draw.at_right_rects_.size() - 1].x_bot() > to_draw.at_left_rects_[to_draw.at_left_rects_.size() - 1].x_bot()) width_offset = to_draw.at_right_rects_[to_draw.at_right_rects_.size() - 1].x_bot() + rect_t::WIDTH/2; else width_offset = to_draw.at_left_rects_[to_draw.at_left_rects_.size() - 1].x_bot() + rect_t::WIDTH/2; else if(to_draw.at_right_rects_.size() > 0) width_offset = to_draw.at_right_rects_[to_draw.at_right_rects_.size() - 1].x_bot() + rect_t::WIDTH/2; else if(to_draw.at_left_rects_.size() > 0) width_offset = to_draw.at_left_rects_[to_draw.at_left_rects_.size() - 1].x_bot() + rect_t::WIDTH/2; for(size_t end_i = 0; end_i < corridor.at_end_edge_.size(); end_i++) { rect_t rect(width_offset, 50 + rect_t::HEIGHT * (end_i + 1), rect_t::WIDTH, rect_t::HEIGHT); to_draw.at_end_edge_rects_.push_back(rect); to_draw.at_end_edge_names_.push_back(corridor.at_end_edge_[end_i]); nb_places++; } if((to_draw.at_end_edge_rects_.size() > 0) && (to_draw.at_begin_edge_rects_.size() > 0)) if(to_draw.at_end_edge_rects_[to_draw.at_end_edge_rects_.size() - 1].y_bot() > to_draw.at_begin_edge_rects_[to_draw.at_begin_edge_rects_.size() - 1].y_bot()) height_offset = to_draw.at_end_edge_rects_[to_draw.at_end_edge_rects_.size() - 1].y_bot() + rect_t::HEIGHT/2; else height_offset = to_draw.at_begin_edge_rects_[to_draw.at_begin_edge_rects_.size() - 1].y_bot() + rect_t::HEIGHT/2; else if(to_draw.at_end_edge_rects_.size() > 0) height_offset = to_draw.at_end_edge_rects_[to_draw.at_end_edge_rects_.size() - 1].y_bot() + rect_t::HEIGHT/2; else if(to_draw.at_begin_edge_rects_.size() > 0) height_offset = to_draw.at_begin_edge_rects_[to_draw.at_begin_edge_rects_.size() - 1].y_bot() + rect_t::HEIGHT/2; for(size_t right_i = 0; right_i < corridor.at_right_.size(); right_i++) { to_draw.at_right_rects_[right_i].y = height_offset; } for(size_t begin_i = 0; begin_i < to_draw.at_begin_edge_rects_.size(); begin_i++) set_rect(to_draw.at_begin_edge_rects_[begin_i], to_draw.at_begin_edge_names_[begin_i]); for(size_t left_i = 0; left_i < to_draw.at_left_rects_.size(); left_i++) set_rect(to_draw.at_left_rects_[left_i], to_draw.at_left_names_[left_i]); for(size_t right_i = 0; right_i < to_draw.at_right_rects_.size(); right_i++) set_rect(to_draw.at_right_rects_[right_i], to_draw.at_right_names_[right_i]); for(size_t end_i = 0; end_i < to_draw.at_end_edge_rects_.size(); end_i++) set_rect(to_draw.at_end_edge_rects_[end_i], to_draw.at_end_edge_names_[end_i]); if(nb_places != 0) cvSaveImage(std::string(corridor.name_ + ".png").c_str(), image); } void MapDrawer::set_rect(rect_t rect, std::string name) { cv::Scalar color = getColor(name); cvRectangle(image, cvPoint(rect.x_top(), rect.y_top()), cvPoint(rect.x_bot(), rect.y_bot()), color, -1, 8, 0); cvRectangle(image, cvPoint(rect.x_top(), rect.y_top()), cvPoint(rect.x_bot(), rect.y_bot()), color - cv::Scalar(50, 50, 50), 1, 8, 0); CvFont font; cvInitFont(&font, CV_FONT_HERSHEY_COMPLEX, 0.4, 0.6, 0, 1); cvPutText(image, name.c_str(), cvPoint(rect.x_top() + 3, rect.y_top() + 20), &font, cv::Scalar(0, 0, 0)); } void MapDrawer::findRightLeftTrigger(corridor_t corridor, int& right_trig, int& left_trig) { int right_trig_pose; right_trig >= 0 ? right_trig_pose = right_trig + 1 : right_trig_pose = 0; int left_trig_pose = -1; left_trig >= 0 ? left_trig_pose = left_trig + 1 : left_trig_pose = 0; right_trig = -1; left_trig = -1; for(size_t right_i = right_trig_pose; right_i < corridor.at_right_.size(); right_i++) { if(corridor.in_front_of_.find(corridor.at_right_[right_i]) != corridor.in_front_of_.end()) { right_trig = right_i; for(size_t left_i = left_trig_pose; left_i < corridor.at_left_.size(); left_i++) if(corridor.at_left_[left_i] == corridor.in_front_of_[corridor.at_right_[right_i]]) { left_trig = left_i; break; } break; } } } int MapDrawer::getPreviousFix(std::vector<rect_t> rects, size_t pose) { for(int i = pose - 1; i >= 0; i--) if(rects[i].fix_ == true) return i; return -1; } cv::Scalar MapDrawer::getColor(std::string name) { std::vector<std::string> up = onto_.individuals.getUp(name); if(std::find(up.begin(), up.end(), "interface") != up.end()) return cv::Scalar(255, 100, 0); else if(std::find(up.begin(), up.end(), "restaurant") != up.end()) return cv::Scalar(0, 160, 255); else if(std::find(up.begin(), up.end(), "clothes_shop") != up.end()) return cv::Scalar(0, 0, 255); else if(std::find(up.begin(), up.end(), "pathIntersection") != up.end()) return cv::Scalar(60, 170, 60); else return cv::Scalar(255, 150, 150); }
38.430147
161
0.667368
sarthou
d46183b40d51fcbd5a500612199530cef146f42f
6,795
cpp
C++
Cartwheel/cartwheel-3d/Core/TurnController.cpp
MontyThibault/centre-of-mass-awareness
58778f148e65749e1dfc443043e9fc054ca3ff4d
[ "MIT" ]
null
null
null
Cartwheel/cartwheel-3d/Core/TurnController.cpp
MontyThibault/centre-of-mass-awareness
58778f148e65749e1dfc443043e9fc054ca3ff4d
[ "MIT" ]
null
null
null
Cartwheel/cartwheel-3d/Core/TurnController.cpp
MontyThibault/centre-of-mass-awareness
58778f148e65749e1dfc443043e9fc054ca3ff4d
[ "MIT" ]
null
null
null
#include "TurnController.h" TurnController::TurnController(Character* b, IKVMCController* llc, WorldOracle* w) : BehaviourController(b, llc, w){ headingRequested = false; stillTurning = false; requestedHeadingValue = 0; turningBodyTwist = 0; initialTiming = 0; } /** ask for a heading... */ void TurnController::requestHeading(double v){ stillTurning = false; headingRequested = true; requestedHeadingValue = v; //if the turn angle is pretty small, then just turn right away (or the old way... who knows). currentHeadingQ = bip->getHeading(); finalHeadingQ.setToRotationQuaternion(v, PhysicsGlobals::up); tmpQ.setToProductOf(finalHeadingQ, currentHeadingQ, false, true); turnAngle = tmpQ.getRotationAngle(PhysicsGlobals::up); tprintf("turnAngle: %lf\n", turnAngle); initialTiming = stepTime; if (fabs(turnAngle) < 1.0) initiateTurn(v); } TurnController::~TurnController(void){ } /** this method gets called at every simulation time step */ void TurnController::simStepPlan(double dt){ BehaviourController::simStepPlan(dt); if (stillTurning == false) return; //this is this guy's equivalent of panic management... double vLength = lowLCon->v.length(); if (vLength > 1.5*initialVelocity.length() && vLength > 1.5*desiredVelocity.length() && vLength > 0.5){ lowLCon->states[lowLCon->FSMStateIndex]->stateTime *= 0.99; // tprintf("velocity is too large... changing transition time to: %lf\n", lowLCon->states[lowLCon->FSMStateIndex]->stateTime); }else lowLCon->states[lowLCon->FSMStateIndex]->stateTime = initialTiming; //2 rads per second... double turnRate = dt * 2; //TODO: get all those limits on the twisting deltas to be related to dt, so that we get uniform turning despite the //having different dts currentHeadingQ = bip->getHeading(); currentDesiredHeadingQ.setToRotationQuaternion(turningDesiredHeading, PhysicsGlobals::up); finalHeadingQ.setToRotationQuaternion(finalHeading, PhysicsGlobals::up); //the *3 below is because the head rotates thrice more than the body, and we don't want it to go past the target... upperBodyTwistQ.setToRotationQuaternion(turningBodyTwist * 3, PhysicsGlobals::up); //this is the angle between the current heading and the final desired heading... tmpQ.setToProductOf(currentHeadingQ, finalHeadingQ, false, true); double curToFinal = tmpQ.getRotationAngle(PhysicsGlobals::up); //this is the difference between the current and final orientation, offset by the current turningBodyTwist - to know how much more we //should twist into the rotation... tmpQ2.setToProductOf(tmpQ, upperBodyTwistQ, false, true); double deltaTwist = tmpQ2.getRotationAngle(PhysicsGlobals::up); //this is the angle between the set desired heading and the final heading - adding this to the current desired heading would reach finalHeading in one go... tmpQ.setToProductOf(finalHeadingQ, currentDesiredHeadingQ, false, true); double desToFinal = tmpQ.getRotationAngle(PhysicsGlobals::up); //do we still need to increase the desired heading? if (fabs(desToFinal) > 0.01){ boundToRange(&desToFinal, -turnRate, turnRate); turningDesiredHeading += desToFinal; } boundToRange(&deltaTwist, -turnRate*4, turnRate*4); turningBodyTwist += deltaTwist; boundToRange(&turningBodyTwist, -0.5, 0.5); double footAngleRelToBody = (lowLCon->stance == LEFT_STANCE)?(-duckWalk):(duckWalk); double t = (lowLCon->phi) - 0.2; boundToRange(&t, 0, 1); double twistCoef = 2*(desiredVelocity.length() + 0.5); boundToRange(&twistCoef, 0, 2.5); footAngleRelToBody = (1-t) * footAngleRelToBody + t * -turningBodyTwist*twistCoef; setDuckWalkDegree(footAngleRelToBody); setUpperBodyPose(ubSagittalLean + 0.01, ubCoronalLean - turningBodyTwist/10, turningBodyTwist); //are we there yet (or close enough)? if (fabs(curToFinal) < 0.2){ tprintf("done turning!\n"); turningBodyTwist = 0; desiredHeading = turningDesiredHeading = finalHeading; //reset everything... setUpperBodyPose(ubSagittalLean, ubCoronalLean, ubTwist); setDesiredHeading(desiredHeading); setDuckWalkDegree(duckWalk); setVelocities(velDSagittal, velDCoronal); lowLCon->states[lowLCon->FSMStateIndex]->stateTime = initialTiming; stillTurning = false; }else{ //still turning... so we need to still specify the desired velocity, in character frame... t = fabs(curToFinal/turnAngle) - 0.3; boundToRange(&t, 0, 1); Vector3d vD = initialVelocity*t + desiredVelocity*(1-t); //Vector3d vD = desiredVelocity; vD = lowLCon->characterFrame.inverseRotate(vD); lowLCon->velDSagittal = vD.z; lowLCon->velDCoronal = vD.x; } setDesiredHeading(turningDesiredHeading); } /** this method gets called every time the controller transitions to a new state */ void TurnController::conTransitionPlan(){ BehaviourController::conTransitionPlan(); if (headingRequested) initiateTurn(requestedHeadingValue); } /** sets a bunch of parameters to some default initial value */ void TurnController::initializeDefaultParameters(){ BehaviourController::initializeDefaultParameters(); } /** commence turning... */ void TurnController::initiateTurn(double finalDHeading){ if (stillTurning == false){ turningBodyTwist = 0; turningDesiredHeading = bip->getHeadingAngle();; } headingRequested = false; stillTurning = true; currentHeadingQ = bip->getHeading(); finalHeadingQ.setToRotationQuaternion(finalDHeading, PhysicsGlobals::up); tmpQ.setToProductOf(finalHeadingQ, currentHeadingQ, false, true); turnAngle = tmpQ.getRotationAngle(PhysicsGlobals::up); finalHeading = finalHeadingQ.getRotationAngle(PhysicsGlobals::up); initialHeading = currentHeadingQ.getRotationAngle(PhysicsGlobals::up); tprintf("turnAngle: %lf. InitialHeading: %lf. Final Heading: %lf\n", turnAngle, initialHeading, finalHeading); initialVelocity = bip->getCOMVelocity(); double finalVDSagittal = velDSagittal; boundToRange(&finalVDSagittal, -0.5, 0.6); if (fabs(turnAngle) > 2.5) boundToRange(&finalVDSagittal, -0.2, 0.3); desiredVelocity = Vector3d(0,0,finalVDSagittal).rotate(finalHeading, Vector3d(0,1,0)); if (((lowLCon->stance == LEFT_STANCE && turnAngle < -1.5) || (lowLCon->stance == RIGHT_STANCE && turnAngle > 1.5)) && finalVDSagittal >=0){ tprintf("this is the bad side... try a smaller heading first...\n"); if (lowLCon->stance == LEFT_STANCE) initiateTurn(initialHeading - 1.4); else initiateTurn(initialHeading + 1.4); desiredVelocity /= 0.5; headingRequested = true; requestedHeadingValue = finalDHeading; } } /** this method determines the degree to which the character should be panicking */ double TurnController::getPanicLevel(){ //don't panic during turning, if the vel's are not there yet... or at least, panic in a different way. if (stillTurning) return 0; return BehaviourController::getPanicLevel(); }
36.532258
157
0.753054
MontyThibault
d4622904c62f26a74067e522b4c5f303b223aaff
11,086
cpp
C++
test/new_lexer_test.cpp
Nicholas-Baron/little-lang
dc7cca0ad4d06987f12edbe990ae6f27ec02d182
[ "MIT" ]
1
2019-08-09T13:59:32.000Z
2019-08-09T13:59:32.000Z
test/new_lexer_test.cpp
Nicholas-Baron/little-lang
dc7cca0ad4d06987f12edbe990ae6f27ec02d182
[ "MIT" ]
3
2019-08-08T04:39:49.000Z
2019-12-11T20:57:47.000Z
test/new_lexer_test.cpp
Nicholas-Baron/little-lang
dc7cca0ad4d06987f12edbe990ae6f27ec02d182
[ "MIT" ]
null
null
null
#include "new_lexer.hpp" #include <catch2/catch.hpp> TEST_CASE("the lexer will not accept empty inputs") { std::string buffer; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); CHECK(lexer->peek_token() == lexer::token_type::eof); } TEST_CASE("the lexer will report locations for tokens") { std::string buffer = "foo\n bar"; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); CHECK(lexer->next_token().location == Location{1, 0}); CHECK(lexer->next_token().location == Location{2, 2}); CHECK(lexer->next_token().location == Location{2, 5}); } TEST_CASE("the lexer can look ahead for whole text fragments") { std::string buffer = "foo bar baz"; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); CHECK(lexer->next_chars("foo")); CHECK(lexer->next_chars("oo", 1)); CHECK(lexer->next_chars("bar", 4)); CHECK(lexer->next_chars("baz", 8)); } TEST_CASE("the lexer will ignore comments") { std::string buffer = R"(// this is a comment # this is another comment comment I am from the 1960s Comment I am also from the 1960s foo bar baz)"; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); CHECK(lexer->next_token() == "foo"); CHECK(lexer->next_token() == "bar"); CHECK(lexer->next_token() == "baz"); CHECK(lexer->next_token() == lexer::token_type::eof); } TEST_CASE("the lexer will parse an identifier") { std::string buffer = "main"; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); auto tok = lexer->next_token(); CHECK(tok == lexer::token_type::identifier); CHECK(tok == "main"); CHECK(lexer->next_token() == lexer::token_type::eof); } TEST_CASE("the lexer will parse primitive types") { std::string buffer = "int unit string char bool float"; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); CHECK(lexer->next_token() == lexer::token_type::prim_type); CHECK(lexer->next_token() == lexer::token_type::prim_type); CHECK(lexer->next_token() == lexer::token_type::prim_type); CHECK(lexer->next_token() == lexer::token_type::prim_type); CHECK(lexer->next_token() == lexer::token_type::prim_type); CHECK(lexer->next_token() == lexer::token_type::prim_type); CHECK(lexer->next_token() == lexer::token_type::eof); } TEST_CASE("the lexer will parse an identifier containing underscores") { std::string buffer = "my_value"; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); auto tok = lexer->next_token(); CHECK(tok == lexer::token_type::identifier); CHECK(tok == "my_value"); CHECK(lexer->next_token() == lexer::token_type::eof); } TEST_CASE("the lexer will parse an identifier starting with underscores") { std::string buffer = "_value"; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); auto tok = lexer->next_token(); CHECK(tok == lexer::token_type::identifier); CHECK(tok == "_value"); CHECK(lexer->next_token() == lexer::token_type::eof); } TEST_CASE("the lexer will parse a plain string") { std::string buffer = "\"raw\""; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); auto tok = lexer->next_token(); CHECK(tok == lexer::token_type::string); CHECK(tok == "\"raw\""); CHECK(lexer->next_token() == lexer::token_type::eof); } TEST_CASE("the lexer will parse a string with escaped character") { std::string buffer = R"("raw\n")"; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); auto tok = lexer->next_token(); CHECK(tok == lexer::token_type::string); CHECK(tok == "\"raw\n\""); CHECK(lexer->next_token() == lexer::token_type::eof); } TEST_CASE("the lexer will parse a character literal") { std::string buffer = "\'w\'"; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); auto tok = lexer->next_token(); CHECK(tok == lexer::token_type::character); CHECK(tok == "\'w\'"); CHECK(lexer->next_token() == lexer::token_type::eof); } TEST_CASE("the lexer will parse an integer") { std::string buffer = "1234"; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); auto tok = lexer->next_token(); CHECK(tok == lexer::token_type::integer); CHECK(tok == "1234"); CHECK(lexer->next_token() == lexer::token_type::eof); } TEST_CASE("the lexer will parse a hexadecimal integer") { std::string buffer = "0x123456789aBcDeF"; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); auto tok = lexer->next_token(); CHECK(tok == lexer::token_type::integer); CHECK(tok == buffer); CHECK(lexer->next_token() == lexer::token_type::eof); } TEST_CASE("the lexer will parse a colon and the word 'is' as the same token") { std::string buffer = "is:"; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); CHECK(lexer->next_token() == lexer::token_type::colon); CHECK(lexer->next_token() == lexer::token_type::colon); CHECK(lexer->next_token() == lexer::token_type::eof); } TEST_CASE("the lexer will parse parentheses") { std::string buffer = "()"; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); CHECK(lexer->next_token() == lexer::token_type::lparen); CHECK(lexer->next_token() == lexer::token_type::rparen); CHECK(lexer->next_token() == lexer::token_type::eof); } TEST_CASE("the lexer will parse braces") { std::string buffer = "{}"; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); CHECK(lexer->next_token() == lexer::token_type::lbrace); CHECK(lexer->next_token() == lexer::token_type::rbrace); CHECK(lexer->next_token() == lexer::token_type::eof); } TEST_CASE("the lexer will parse a 'skinny' arrow") { std::string buffer = "->"; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); CHECK(lexer->next_token() == lexer::token_type::arrow); CHECK(lexer->next_token() == lexer::token_type::eof); } TEST_CASE("the lexer will parse a comma") { std::string buffer = ","; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); CHECK(lexer->next_token() == lexer::token_type::comma); CHECK(lexer->next_token() == lexer::token_type::eof); } TEST_CASE("the lexer will parse a semicolon") { std::string buffer = ";"; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); CHECK(lexer->next_token() == lexer::token_type::semi); CHECK(lexer->next_token() == lexer::token_type::eof); } TEST_CASE("the lexer will parse 'from', 'import', and 'export'") { std::string buffer = "from import export"; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); CHECK(lexer->next_token() == lexer::token_type::from); CHECK(lexer->next_token() == lexer::token_type::import_); CHECK(lexer->next_token() == lexer::token_type::export_); CHECK(lexer->next_token() == lexer::token_type::eof); } TEST_CASE("the lexer will parse 'if', 'then', and 'else'") { std::string buffer = "if else then"; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); CHECK(lexer->next_token() == lexer::token_type::if_); CHECK(lexer->next_token() == lexer::token_type::else_); CHECK(lexer->next_token() == lexer::token_type::then); CHECK(lexer->next_token() == lexer::token_type::eof); } TEST_CASE("the lexer will parse 'return' and 'ret' the same") { std::string buffer = "return ret"; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); CHECK(lexer->next_token() == lexer::token_type::return_); CHECK(lexer->next_token() == lexer::token_type::return_); CHECK(lexer->next_token() == lexer::token_type::eof); } TEST_CASE("the lexer will parse '<' and '>'") { std::string buffer = "< >"; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); CHECK(lexer->next_token() == lexer::token_type::lt); CHECK(lexer->next_token() == lexer::token_type::gt); CHECK(lexer->next_token() == lexer::token_type::eof); } TEST_CASE("the lexer will parse '<=' and '>=' as 1 token each") { std::string buffer = "<= >="; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); CHECK(lexer->next_token() == lexer::token_type::le); CHECK(lexer->next_token() == lexer::token_type::ge); CHECK(lexer->next_token() == lexer::token_type::eof); } TEST_CASE("the lexer will parse 'let' and 'const'") { std::string buffer = "let const"; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); CHECK(lexer->next_token() == lexer::token_type::let); CHECK(lexer->next_token() == lexer::token_type::const_); CHECK(lexer->next_token() == lexer::token_type::eof); } TEST_CASE("the lexer will parse 'and' as '&&'") { std::string buffer = "and &&"; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); CHECK(lexer->next_token() == lexer::token_type::double_and); CHECK(lexer->next_token() == lexer::token_type::double_and); CHECK(lexer->next_token() == lexer::token_type::eof); } TEST_CASE("the lexer will parse 'or' as '||'") { std::string buffer = "or ||"; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); CHECK(lexer->next_token() == lexer::token_type::double_or); CHECK(lexer->next_token() == lexer::token_type::double_or); CHECK(lexer->next_token() == lexer::token_type::eof); } TEST_CASE("the lexer will parse 'equals' as '=='") { std::string buffer = "equals =="; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); CHECK(lexer->next_token() == lexer::token_type::eq); CHECK(lexer->next_token() == lexer::token_type::eq); CHECK(lexer->next_token() == lexer::token_type::eof); } TEST_CASE("the lexer will parse basic mathematical symbols") { std::string buffer = "= + - / * %"; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); CHECK(lexer->next_token() == lexer::token_type::equal); CHECK(lexer->next_token() == lexer::token_type::plus); CHECK(lexer->next_token() == lexer::token_type::minus); CHECK(lexer->next_token() == lexer::token_type::slash); CHECK(lexer->next_token() == lexer::token_type::asterik); CHECK(lexer->next_token() == lexer::token_type::percent); CHECK(lexer->next_token() == lexer::token_type::eof); } TEST_CASE("the lexer will parse pointer-related tokens") { std::string buffer = " & ? null"; auto lexer = lexer::from_buffer(buffer); CHECK(lexer != nullptr); CHECK(lexer->next_token() == lexer::token_type::amp); CHECK(lexer->next_token() == lexer::token_type::question); CHECK(lexer->next_token() == lexer::token_type::null); CHECK(lexer->next_token() == lexer::token_type::eof); }
30.539945
79
0.638102
Nicholas-Baron
d466d3fc9ad349b40da93af5b1f5ae6e4d78ec36
5,442
cc
C++
msf_distort/src/msf_distort.cc
tdnet12434/multi_sensor_fusion
fea64a56ecab2bd65f96675c207cd0d776c4a969
[ "Apache-2.0" ]
1
2018-07-11T11:32:26.000Z
2018-07-11T11:32:26.000Z
msf_distort/src/msf_distort.cc
tdnet12434/multi_sensor_fusion
fea64a56ecab2bd65f96675c207cd0d776c4a969
[ "Apache-2.0" ]
null
null
null
msf_distort/src/msf_distort.cc
tdnet12434/multi_sensor_fusion
fea64a56ecab2bd65f96675c207cd0d776c4a969
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2012-2013 Simon Lynen, ASL, ETH Zurich, Switzerland * You can contact the author at <slynen at ethz dot ch> * * 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 <ros/ros.h> #include <sensor_msgs/NavSatFix.h> #include <geometry_msgs/PoseWithCovariance.h> #include <geometry_msgs/PoseWithCovarianceStamped.h> #include <tf/transform_broadcaster.h> #include <geometry_msgs/TransformStamped.h> #include <msf_distort/MSF_DistortConfig.h> #include <dynamic_reconfigure/Reconfigure.h> #include <dynamic_reconfigure/server.h> #include <msf_core/msf_macros.h> struct CallbackHandler { typedef msf_distort::MSF_DistortConfig Config_T; Config_T config_; ros::Publisher pubPoseWithCovarianceStamped_; ros::Publisher pubTransformStamped_; ros::Publisher pubPoseStamped_; ros::Publisher pubNavSatFix_; ros::Publisher pubPoint_; ros::Publisher pubPoseWithCovarianceStampedGPS_; CallbackHandler(ros::NodeHandle& nh) { pubPoseWithCovarianceStamped_ = nh.advertise<geometry_msgs::PoseWithCovarianceStamped> ("pose_with_covariance_output", 100); pubTransformStamped_ = nh.advertise<geometry_msgs::TransformStamped>("transform_output", 100); pubPoseStamped_ = nh.advertise<geometry_msgs::PoseStamped>("pose_output", 100); pubNavSatFix_ = nh.advertise<sensor_msgs::NavSatFix>("navsatfix_output", 100); pubPoint_ = nh.advertise<geometry_msgs::PointStamped>("point_output", 100); pubPoseWithCovarianceStampedGPS_ = nh.advertise<geometry_msgs::PoseWithCovarianceStamped>("pose_with_covariance_gps_output", 100); } void config(Config_T &config, uint32_t /*level*/) { config_ = config; } void MeasurementCallback( const geometry_msgs::PoseWithCovarianceStampedConstPtr & msg) { if (config_.publish_pose) { pubPoseWithCovarianceStamped_.publish(msg); } } void MeasurementCallback( const geometry_msgs::TransformStampedConstPtr & msg) { if (config_.publish_pose) { pubTransformStamped_.publish(msg); } } void MeasurementCallback(const geometry_msgs::PoseStampedConstPtr & msg) { if (config_.publish_pose) { pubPoseStamped_.publish(msg); } } void MeasurementCallback(const sensor_msgs::NavSatFixConstPtr & msg) { if (config_.publish_position) { pubNavSatFix_.publish(msg); } } void MeasurementCallback(const geometry_msgs::PointStampedConstPtr & msg) { if (config_.publish_position) { pubPoint_.publish(msg); } } void MeasurementCallback2( const geometry_msgs::PoseWithCovarianceStampedConstPtr & msg) { if (config_.publish_position) { pubPoseWithCovarianceStampedGPS_.publish(msg); } } }; int main(int argc, char** argv) { ros::init(argc, argv, "msf_distort"); typedef msf_distort::MSF_DistortConfig Config_T; typedef dynamic_reconfigure::Server<Config_T> ReconfigureServer; typedef boost::shared_ptr<ReconfigureServer> ReconfigureServerPtr; ros::NodeHandle nh("msf_distort"); CallbackHandler handler(nh); ReconfigureServerPtr reconf_server_; ///< dynamic reconfigure server reconf_server_.reset(new ReconfigureServer(nh)); ReconfigureServer::CallbackType f = boost::bind(&CallbackHandler::config, &handler, _1, _2); reconf_server_->setCallback(f); ros::Subscriber subPoseWithCovarianceStamped_ = nh.subscribe < geometry_msgs::PoseWithCovarianceStamped > ("pose_with_covariance_input", 20, &CallbackHandler::MeasurementCallback, &handler); ros::Subscriber subTransformStamped_ = nh.subscribe < geometry_msgs::TransformStamped > ("transform_input", 20, &CallbackHandler::MeasurementCallback, &handler); ros::Subscriber subPoseStamped_ = nh.subscribe < geometry_msgs::PoseStamped > ("pose_input", 20, &CallbackHandler::MeasurementCallback, &handler); ros::Subscriber subNavSatFix_ = nh.subscribe < sensor_msgs::NavSatFix > ("navsatfix_input", 20, &CallbackHandler::MeasurementCallback, &handler); ros::Subscriber subPoint_ = nh.subscribe < geometry_msgs::PointStamped > ("point_input", 20, &CallbackHandler::MeasurementCallback, &handler); ros::Subscriber subPoseGPS_ = nh.subscribe < geometry_msgs::PoseWithCovarianceStamped > ("posegps_input", 20, &CallbackHandler::MeasurementCallback2, &handler); ros::V_string topics; ros::this_node::getSubscribedTopics(topics); std::string nodeName = ros::this_node::getName(); std::string topicsStr = nodeName + ":\n\tsubscribed to topics:\n"; for (unsigned int i = 0; i < topics.size(); i++) topicsStr += ("\t\t" + topics.at(i) + "\n"); topicsStr += "\tadvertised topics:\n"; ros::this_node::getAdvertisedTopics(topics); for (unsigned int i = 0; i < topics.size(); i++) topicsStr += ("\t\t" + topics.at(i) + "\n"); MSF_INFO_STREAM("" << topicsStr); ros::spin(); }
37.020408
103
0.725101
tdnet12434
d46748c94583e2896eab7e3d1025198b606c7612
7,205
cpp
C++
hw.cpp
microsoft/pxt-jacdac
5c2b7f928b003d9a089dc00d77bb411db3dbed2e
[ "MIT" ]
6
2020-12-31T03:26:47.000Z
2022-03-20T03:38:05.000Z
hw.cpp
microsoft/pxt-jacdac
5c2b7f928b003d9a089dc00d77bb411db3dbed2e
[ "MIT" ]
21
2020-12-14T17:52:35.000Z
2022-03-22T00:03:00.000Z
hw.cpp
microsoft/pxt-jacdac
5c2b7f928b003d9a089dc00d77bb411db3dbed2e
[ "MIT" ]
8
2021-02-11T08:47:56.000Z
2021-11-10T08:36:35.000Z
#include "pxt.h" #include "jdlow.h" #include "ZSingleWireSerial.h" //#define ENABLE_PIN_LOG 1 #define DEVICE_ID DEVICE_ID_JACDAC_PHYS #define LOG(msg, ...) DMESG("JD: " msg, ##__VA_ARGS__) //#define LOG(...) ((void)0) static ZSingleWireSerial *sws; static cb_t tim_cb; static volatile uint8_t status; static uint16_t currEvent; #define STATUS_IN_RX 0x01 #define STATUS_IN_TX 0x02 #ifdef ENABLE_PIN_LOG #define NUM_LOG_PINS 5 static DevicePin **logPins; static uint32_t *logPinMasks; #ifdef PICO_BOARD #include "hardware/gpio.h" #endif static void init_log_pins() { logPins = new DevicePin *[NUM_LOG_PINS]; #ifdef PICO_BOARD logPins[0] = pxt::lookupPin(2); logPins[1] = pxt::lookupPin(3); logPins[2] = pxt::lookupPin(4); logPins[3] = pxt::lookupPin(5); logPins[4] = pxt::lookupPin(6); #else logPins[0] = LOOKUP_PIN(P0); logPins[1] = LOOKUP_PIN(P1); logPins[2] = LOOKUP_PIN(P2); logPins[3] = LOOKUP_PIN(P8); logPins[4] = LOOKUP_PIN(P16); #endif logPinMasks = new uint32_t[NUM_LOG_PINS]; for (int i = 0; i < NUM_LOG_PINS; ++i) { logPins[i]->setDigitalValue(0); logPinMasks[i] = 1 << (uint32_t)logPins[i]->name; } } REAL_TIME_FUNC static inline void log_pin_set_core(unsigned line, int v) { if (line >= NUM_LOG_PINS) return; #ifdef NRF52_SERIES if (v) NRF_P0->OUTSET = logPinMasks[line]; else NRF_P0->OUTCLR = logPinMasks[line]; #elif defined(PICO_BOARD) if (v) sio_hw->gpio_set = logPinMasks[line]; else sio_hw->gpio_clr = logPinMasks[line]; #else logPins[line]->setDigitalValue(v); #endif } #else REAL_TIME_FUNC static void log_pin_set_core(unsigned, int) {} REAL_TIME_FUNC static void init_log_pins() {} #endif extern "C" void timer_log(int line, int v) { // log_pin_set_core(line, v); } REAL_TIME_FUNC void log_pin_set(int line, int v) { // if (line == 1) log_pin_set_core(line, v); } REAL_TIME_FUNC static void pin_log(int v) { log_pin_set(3, v); } REAL_TIME_FUNC static void pin_pulse() { log_pin_set(4, 1); log_pin_set(4, 0); } void jd_panic(void) { target_panic(PANIC_JACDAC); } REAL_TIME_FUNC static void tim_callback(Event e) { cb_t f = tim_cb; if (f && e.value == currEvent) { tim_cb = NULL; f(); } } void tim_init() { init_log_pins(); EventModel::defaultEventBus->listen(DEVICE_ID, 0, tim_callback, MESSAGE_BUS_LISTENER_IMMEDIATE); } REAL_TIME_FUNC uint64_t tim_get_micros(void) { return current_time_us(); } // timer overhead measurements (without any delta compensation) // STM32F030 - +5.5us +7.8us (not this code - just raw) // ATSAMD51 - +13us +10.8us // ATSAMD21 - +29us +20us REAL_TIME_FUNC void tim_set_timer(int delta, cb_t cb) { // compensate for overheads delta -= JD_TIM_OVERHEAD; if (delta < 20) delta = 20; target_disable_irq(); uint16_t prev = currEvent; currEvent++; if (currEvent == 0) currEvent = 1; tim_cb = cb; system_timer_event_after_us(delta, DEVICE_ID, currEvent); system_timer_cancel_event(DEVICE_ID, prev); // make sure we don't get the same slot target_enable_irq(); } REAL_TIME_FUNC static void setup_exti() { // LOG("setup exti; %d", sws->p.name); sws->setMode(SingleWireDisconnected); // force transition to output so that the pin is reconfigured. // also drive the bus high for a little bit. // TODO this is problematic as it may drive the line high, while another device is transmitting, // in case we're called by rx_timeout() sws->p.setDigitalValue(1); sws->p.getDigitalValue(PullMode::Up); sws->p.eventOn(DEVICE_PIN_INTERRUPT_ON_EDGE); } REAL_TIME_FUNC static void line_falling(int lineV) { pin_log(1); if (lineV) return; // rising if (sws->p.isOutput()) { // LOG("in send already"); return; } sws->p.eventOn(DEVICE_PIN_EVENT_NONE); jd_line_falling(); } REAL_TIME_FUNC static void sws_done(uint16_t errCode) { // pin_pulse(); // pin_pulse(); // LOG("sws_done %d @%d", errCode, (int)tim_get_micros()); switch (errCode) { case SWS_EVT_DATA_SENT: if (status & STATUS_IN_TX) { status &= ~STATUS_IN_TX; sws->setMode(SingleWireDisconnected); // force reconfigure sws->p.getDigitalValue(); // send break signal sws->p.setDigitalValue(0); target_wait_us(11); sws->p.setDigitalValue(1); jd_tx_completed(0); } break; case SWS_EVT_ERROR: // brk condition if (!(status & STATUS_IN_RX)) { LOG("SWS error"); target_panic(122); } else { return; } break; case SWS_EVT_DATA_RECEIVED: // LOG("DMA overrun"); // sws->getBytesReceived() always returns 1 on NRF if (status & STATUS_IN_RX) { status &= ~STATUS_IN_RX; sws->setMode(SingleWireDisconnected); jd_rx_completed(0); } else { LOG("double complete"); // target_panic(122); } sws->abortDMA(); break; } setup_exti(); pin_pulse(); } void uart_init_() { #ifdef MICROBIT_CODAL sws = new ZSingleWireSerial(uBit.io.P12); #else sws = new ZSingleWireSerial(*LOOKUP_PIN(JACK_TX)); #endif sws->setBaud(1000000); sws->p.setIRQ(line_falling); sws->setIRQ(sws_done); setup_exti(); pin_log(0); } REAL_TIME_FUNC int uart_start_tx(const void *data, uint32_t numbytes) { if (status & STATUS_IN_TX) jd_panic(); target_disable_irq(); if (status & STATUS_IN_RX) { target_enable_irq(); return -1; } sws->p.eventOn(DEVICE_PIN_EVENT_NONE); int val = sws->p.getDigitalValue(); target_enable_irq(); // try to pull the line low, provided it currently reads as high if (val == 0 || sws->p.getAndSetDigitalValue(0)) { // we failed - the line was low - start reception // jd_line_falling() would normally execute from EXTI, which has high // priority - we simulate this by completely disabling IRQs target_disable_irq(); jd_line_falling(); target_enable_irq(); return -1; } target_wait_us(11); status |= STATUS_IN_TX; sws->p.setDigitalValue(1); // LOG("start tx @%d", (int)tim_get_micros()); target_wait_us(50); pin_pulse(); sws->sendDMA((uint8_t *)data, numbytes); return 0; } void uart_flush_rx(void) { // nothing to do } REAL_TIME_FUNC void uart_start_rx(void *data, uint32_t maxbytes) { // LOG("start rx @%d", (int)tim_get_micros()); if (status & STATUS_IN_RX) jd_panic(); status |= STATUS_IN_RX; sws->receiveDMA((uint8_t *)data, maxbytes); pin_log(0); } void uart_disable() { pin_pulse(); sws->abortDMA(); status = 0; setup_exti(); pin_pulse(); } REAL_TIME_FUNC int uart_wait_high() { int timeout = 1000; // should be around 100-1000us while (timeout-- > 0 && sws->p.getDigitalValue() == 0) ; if (timeout <= 0) return -1; return 0; }
23.545752
100
0.629146
microsoft
d46764d908176863484f6f12857d802e55eeba10
7,601
cpp
C++
libs/gui/src/font.cpp
blagodarin/yttrium
534289c3082355e5537a03c0b5855b60f0c344ad
[ "Apache-2.0" ]
null
null
null
libs/gui/src/font.cpp
blagodarin/yttrium
534289c3082355e5537a03c0b5855b60f0c344ad
[ "Apache-2.0" ]
null
null
null
libs/gui/src/font.cpp
blagodarin/yttrium
534289c3082355e5537a03c0b5855b60f0c344ad
[ "Apache-2.0" ]
null
null
null
// This file is part of the Yttrium toolkit. // Copyright (C) Sergei Blagodarin. // SPDX-License-Identifier: Apache-2.0 #include <yttrium/gui/font.h> #include <yttrium/base/exceptions.h> #include <yttrium/geometry/rect.h> #include <yttrium/image/image.h> #include <yttrium/renderer/2d.h> #include <yttrium/renderer/manager.h> #include <yttrium/renderer/texture.h> #include <yttrium/storage/reader.h> #include <yttrium/storage/source.h> #include <seir_base/utf8.hpp> #include <cassert> #include <cstring> #include <optional> #include <unordered_map> #include <ft2build.h> #include FT_FREETYPE_H namespace { constexpr size_t builtinWidth = 4; constexpr size_t builtinHeight = 4; constexpr uint8_t builtinData[builtinHeight][builtinWidth]{ { 0xff, 0xff, 0x00, 0x00 }, { 0xff, 0xff, 0x00, 0x00 }, { 0x00, 0x00, 0x00, 0x00 }, { 0x00, 0x00, 0x00, 0x00 }, }; constexpr Yt::RectF builtinWhiteRect{ {}, Yt::SizeF{ 1, 1 } }; } namespace Yt { struct FreeTypeWrapper { FT_Library _library = nullptr; Buffer _faceBuffer; FT_Face _face = nullptr; FreeTypeWrapper() { if (FT_Init_FreeType(&_library)) throw InitializationError{ "Failed to initialize FreeType library" }; } ~FreeTypeWrapper() noexcept { if (_face) FT_Done_Face(_face); // TODO: Handle error code. FT_Done_FreeType(_library); // TODO: Handle error code. } void load(Buffer&& buffer) { assert(!_face); if (buffer.size() > static_cast<size_t>(std::numeric_limits<FT_Long>::max()) || FT_New_Memory_Face(_library, static_cast<const FT_Byte*>(buffer.data()), static_cast<FT_Long>(buffer.size()), 0, &_face)) throw DataError{ "Failed to load font" }; _faceBuffer = std::move(buffer); } }; class FontImpl final : public Font { public: FontImpl(const Source& source, RenderManager& renderManager, size_t size) : _size{ static_cast<int>(size) } { _freetype.load(source.to_buffer()); _hasKerning = FT_HAS_KERNING(_freetype._face); FT_Set_Pixel_Sizes(_freetype._face, 0, static_cast<FT_UInt>(size)); Image image{ { size * 32, size * 32, PixelFormat::Intensity8 } }; size_t x_offset = 0; size_t y_offset = 0; size_t row_height = 0; const auto copy_rect = [&](const uint8_t* src, size_t width, size_t height, ptrdiff_t stride) { if (height > 0) { if (stride < 0) src += (height - 1) * static_cast<size_t>(-stride); auto dst = static_cast<uint8_t*>(image.data()) + image.info().stride() * y_offset + x_offset; for (size_t y = 0; y < height; ++y) { std::memcpy(dst, src, width); src += stride; dst += image.info().stride(); } if (row_height < height) row_height = height; } x_offset += width + 1; }; copy_rect(::builtinData[0], ::builtinWidth, ::builtinHeight, ::builtinWidth); const auto baseline = static_cast<FT_Int>(size) * _freetype._face->ascender / _freetype._face->height; for (FT_UInt codepoint = 0; codepoint < 65536; ++codepoint) { const auto id = FT_Get_Char_Index(_freetype._face, codepoint); if (!id) continue; if (FT_Load_Glyph(_freetype._face, id, FT_LOAD_RENDER)) continue; // TODO: Report error. const auto glyph = _freetype._face->glyph; if (x_offset + glyph->bitmap.width > image.info().width()) { x_offset = 0; y_offset += row_height + 1; row_height = 0; } if (y_offset + glyph->bitmap.rows > image.info().height()) break; // TODO: Report error. auto& glyphInfo = _glyph[codepoint]; glyphInfo._id = id; glyphInfo._rect = { { static_cast<int>(x_offset), static_cast<int>(y_offset) }, Size{ static_cast<int>(glyph->bitmap.width), static_cast<int>(glyph->bitmap.rows) } }; glyphInfo._offset = { glyph->bitmap_left, baseline - glyph->bitmap_top }; glyphInfo._advance = static_cast<int>(glyph->advance.x >> 6); copy_rect(glyph->bitmap.buffer, glyph->bitmap.width, glyph->bitmap.rows, glyph->bitmap.pitch); } _texture = renderManager.create_texture_2d(image); } void render(Renderer2D& renderer, const RectF& rect, std::string_view text) const override { const auto scale = rect.height() / static_cast<float>(_size); int x = 0; auto previous = _glyph.end(); renderer.setTexture(_texture); for (size_t i = 0; i < text.size();) { const auto current = _glyph.find(seir::readUtf8(text, i)); if (current == _glyph.end()) continue; if (_hasKerning && previous != _glyph.end()) { FT_Vector kerning; if (!FT_Get_Kerning(_freetype._face, previous->second._id, current->second._id, FT_KERNING_DEFAULT, &kerning)) x += static_cast<int>(kerning.x >> 6); } const auto left = rect.left() + static_cast<float>(x + current->second._offset._x) * scale; if (left >= rect.right()) break; RectF positionRect{ { left, rect.top() + static_cast<float>(current->second._offset._y) * scale }, SizeF{ current->second._rect.size() } * scale }; RectF glyphRect{ current->second._rect }; bool clipped = false; if (positionRect.right() > rect.right()) { const auto originalWidth = positionRect.width(); positionRect._right = rect._right; glyphRect.setWidth(glyphRect.width() * positionRect.width() / originalWidth); clipped = true; } renderer.setTextureRect(glyphRect); renderer.addBorderlessRect(positionRect); if (clipped) return; x += current->second._advance; previous = current; } } float textWidth(std::string_view text, float fontSize, TextCapture* capture) const override { const auto scale = fontSize / static_cast<float>(_size); int x = 0; std::optional<float> selectionX; const auto updateCapture = [&](size_t offset) { if (!capture) return; if (capture->_cursorOffset == offset) capture->_cursorPosition.emplace(static_cast<float>(x) * scale); if (capture->_selectionBegin < capture->_selectionEnd) { if (selectionX) { if (offset == capture->_selectionEnd) { capture->_selectionRange.emplace(*selectionX, static_cast<float>(x) * scale); selectionX.reset(); } } else if (offset == capture->_selectionBegin) selectionX = static_cast<float>(x) * scale; } }; auto previous = _glyph.end(); for (size_t i = 0; i < text.size();) { const auto offset = i; const auto current = _glyph.find(seir::readUtf8(text, i)); if (current == _glyph.end()) continue; if (_hasKerning && previous != _glyph.end()) { FT_Vector kerning; if (!FT_Get_Kerning(_freetype._face, previous->second._id, current->second._id, FT_KERNING_DEFAULT, &kerning)) x += static_cast<int>(kerning.x >> 6); } updateCapture(offset); x += current->second._advance; previous = current; } updateCapture(text.size()); return static_cast<float>(x) * scale; } std::shared_ptr<const Texture2D> texture() const noexcept override { return _texture; } RectF textureRect(Graphics graphics) const noexcept override { switch (graphics) { case Graphics::WhiteRect: return ::builtinWhiteRect; } return {}; } private: struct Glyph { FT_UInt _id = 0; Rect _rect; Point _offset; int _advance = 0; }; FreeTypeWrapper _freetype; const int _size; bool _hasKerning = false; std::unordered_map<char32_t, Glyph> _glyph; std::shared_ptr<const Texture2D> _texture; }; std::shared_ptr<const Font> Font::load(const Source& source, RenderManager& renderManager) { return std::make_shared<FontImpl>(source, renderManager, 64); } }
30.526104
170
0.662281
blagodarin
d46b0a1df8de235cce48be3d860b5b19cd2a3019
784
cc
C++
solutions/kattis/soundex.cc
zwliew/ctci
871f4fc957be96c6d0749d205549b7b35dc53d9e
[ "MIT" ]
4
2020-11-07T14:38:02.000Z
2022-01-03T19:02:36.000Z
solutions/kattis/soundex.cc
zwliew/ctci
871f4fc957be96c6d0749d205549b7b35dc53d9e
[ "MIT" ]
1
2019-04-17T06:55:14.000Z
2019-04-17T06:55:14.000Z
solutions/kattis/soundex.cc
zwliew/ctci
871f4fc957be96c6d0749d205549b7b35dc53d9e
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define debug(...) 0 #ifdef LOCAL #include "../../_library/cc/debug.h" #endif int main() { cin.tie(nullptr)->sync_with_stdio(false); #if defined(FILE) && !defined(LOCAL) freopen(FILE ".in", "r", stdin), freopen(FILE ".out", "w", stdout); #endif const vector<string> reps = { "AEIOUHWY", "BFPV", "CGJKQSXZ", "DT", "L", "MN", "R", }; unordered_map<char, int> mp; for (char c = 'A'; c <= 'Z'; ++c) { int idx; for (idx = 0; idx < reps.size() && reps[idx].find(c) == string::npos; ++idx) ; mp[c] = idx; } string s; while (cin >> s) { for (int i = 0; i < s.size(); ++i) { int rep = mp[s[i]]; if ((!i || rep != mp[s[i - 1]]) && rep) cout << rep; } cout << "\n"; } }
22.4
80
0.505102
zwliew
d46ce08bf913569243d9781d5b9258de977cbe7c
1,335
cpp
C++
app/jni/Box2D/GearJoint.cpp
walkingice/nobunagapuke
bb1ab970192f818dad31bdf09184fa12a509c59a
[ "BSD-3-Clause" ]
null
null
null
app/jni/Box2D/GearJoint.cpp
walkingice/nobunagapuke
bb1ab970192f818dad31bdf09184fa12a509c59a
[ "BSD-3-Clause" ]
null
null
null
app/jni/Box2D/GearJoint.cpp
walkingice/nobunagapuke
bb1ab970192f818dad31bdf09184fa12a509c59a
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright 2010 Mario Zechner (contact@badlogicgames.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Box2D.h" #include "GearJoint.h" /* * Class: com_badlogic_gdx_physics_box2d_joints_GearJoint * Method: jniSetRatio * Signature: (JF)V */ JNIEXPORT void JNICALL Java_com_badlogic_gdx_physics_box2d_joints_GearJoint_jniSetRatio (JNIEnv *, jobject, jlong addr, jfloat ratio) { b2GearJoint* joint = (b2GearJoint*)addr; joint->SetRatio( ratio ); } /* * Class: com_badlogic_gdx_physics_box2d_joints_GearJoint * Method: jniGetRatio * Signature: (J)F */ JNIEXPORT jfloat JNICALL Java_com_badlogic_gdx_physics_box2d_joints_GearJoint_jniGetRatio (JNIEnv *, jobject, jlong addr) { b2GearJoint* joint = (b2GearJoint*)addr; return joint->GetRatio(); }
31.785714
90
0.733333
walkingice
d46f2d4882e48f3e55477fc22a159829c7d2ca77
7,282
cpp
C++
dp/gl/src/Shader.cpp
asuessenbach/pipeline
2e49968cc3b9948a57f7ee6c4cc3258925c92ab2
[ "BSD-3-Clause" ]
217
2015-01-06T09:26:53.000Z
2022-03-23T14:03:18.000Z
dp/gl/src/Shader.cpp
asuessenbach/pipeline
2e49968cc3b9948a57f7ee6c4cc3258925c92ab2
[ "BSD-3-Clause" ]
10
2015-01-25T12:42:05.000Z
2017-11-28T16:10:16.000Z
dp/gl/src/Shader.cpp
asuessenbach/pipeline
2e49968cc3b9948a57f7ee6c4cc3258925c92ab2
[ "BSD-3-Clause" ]
44
2015-01-13T01:19:41.000Z
2022-02-21T21:35:08.000Z
// Copyright (c) 2010-2016, 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 NVIDIA CORPORATION 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 ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <dp/gl/Shader.h> namespace dp { namespace gl { std::string shaderTypeToName( GLenum type ) { switch( type ) { case GL_COMPUTE_SHADER : return( "ComputeShader" ); case GL_VERTEX_SHADER : return( "VertexShader" ); case GL_TESS_CONTROL_SHADER : return( "TessControlShader" ); case GL_TESS_EVALUATION_SHADER : return( "TessEvaluationShader" ); case GL_GEOMETRY_SHADER : return( "GeometryShader" ); case GL_FRAGMENT_SHADER : return( "FragmentShader" ); default : DP_ASSERT( false ); return( "" ); } } ShaderSharedPtr Shader::create( GLenum type, std::string const& source ) { switch( type ) { case GL_COMPUTE_SHADER : return( ComputeShader::create( source ) ); case GL_VERTEX_SHADER : return( VertexShader::create( source ) ); case GL_TESS_CONTROL_SHADER : return( TessControlShader::create( source ) ); case GL_TESS_EVALUATION_SHADER : return( TessEvaluationShader::create( source ) ); case GL_GEOMETRY_SHADER : return( GeometryShader::create( source ) ); case GL_FRAGMENT_SHADER : return( FragmentShader::create( source ) ); default : DP_ASSERT( false ); return( ShaderSharedPtr() ); } } Shader::Shader( GLenum type, std::string const& source ) { GLuint id = glCreateShader( type ); setGLId( id ); GLint length = dp::checked_cast<GLint>(source.length()); GLchar const* src = source.c_str(); glShaderSource( id, 1, &src, &length ); glCompileShader( id ); #if !defined( NDEBUG ) GLint result; glGetShaderiv( id, GL_COMPILE_STATUS, &result ); if ( ! result ) { GLint errorLen; glGetShaderiv( id, GL_INFO_LOG_LENGTH, &errorLen ); std::string buffer; buffer.resize( errorLen, 0 ); glGetShaderInfoLog( id, errorLen, NULL, &buffer[0] ); DP_ASSERT( false ); } #endif } Shader::~Shader( ) { if ( getGLId() ) { if ( getShareGroup() ) { DEFINE_PTR_TYPES( CleanupTask ); class CleanupTask : public ShareGroupTask { public: static CleanupTaskSharedPtr create( GLuint id ) { return( std::shared_ptr<CleanupTask>( new CleanupTask( id ) ) ); } virtual void execute() { glDeleteShader( m_id ); } protected: CleanupTask( GLuint id ) : m_id( id ) {} private: GLuint m_id; }; // make destructor exception safe try { getShareGroup()->executeTask( CleanupTask::create( getGLId() ) ); } catch (...) {} } else { glDeleteShader( getGLId() ); } } } std::string Shader::getSource() const { GLint sourceLength; glGetShaderiv( getGLId(), GL_SHADER_SOURCE_LENGTH, &sourceLength ); std::vector<char> source( sourceLength ); glGetShaderSource( getGLId(), sourceLength, nullptr, source.data() ); return( source.data() ); } VertexShaderSharedPtr VertexShader::create( std::string const& source ) { return( std::shared_ptr<VertexShader>( new VertexShader( source ) ) ); } VertexShader::VertexShader( std::string const& source ) : Shader( GL_VERTEX_SHADER, source ) { } GLenum VertexShader::getType() const { return( GL_VERTEX_SHADER ); } TessControlShaderSharedPtr TessControlShader::create( std::string const& source ) { return( std::shared_ptr<TessControlShader>( new TessControlShader( source ) ) ); } TessControlShader::TessControlShader( std::string const& source ) : Shader( GL_TESS_CONTROL_SHADER, source ) { } GLenum TessControlShader::getType() const { return( GL_TESS_CONTROL_SHADER ); } TessEvaluationShaderSharedPtr TessEvaluationShader::create( std::string const& source ) { return( std::shared_ptr<TessEvaluationShader>( new TessEvaluationShader( source ) ) ); } TessEvaluationShader::TessEvaluationShader( std::string const& source ) : Shader( GL_TESS_EVALUATION_SHADER, source ) { } GLenum TessEvaluationShader::getType() const { return( GL_TESS_EVALUATION_SHADER ); } GeometryShaderSharedPtr GeometryShader::create( std::string const& source ) { return( std::shared_ptr<GeometryShader>( new GeometryShader( source ) ) ); } GeometryShader::GeometryShader( std::string const& source ) : Shader( GL_GEOMETRY_SHADER, source ) { } GLenum GeometryShader::getType() const { return( GL_GEOMETRY_SHADER ); } FragmentShaderSharedPtr FragmentShader::create( std::string const& source ) { return( std::shared_ptr<FragmentShader>( new FragmentShader( source ) ) ); } FragmentShader::FragmentShader( std::string const& source ) : Shader( GL_FRAGMENT_SHADER, source ) { } GLenum FragmentShader::getType() const { return( GL_FRAGMENT_SHADER ); } ComputeShaderSharedPtr ComputeShader::create( std::string const& source ) { return( std::shared_ptr<ComputeShader>( new ComputeShader( source ) ) ); } ComputeShader::ComputeShader( std::string const& source ) : Shader( GL_COMPUTE_SHADER, source ) { } GLenum ComputeShader::getType() const { return( GL_COMPUTE_SHADER ); } } // namespace gl } // namespace dp
30.855932
92
0.634304
asuessenbach
d46f9faa425e0f5c23fb0c5f229aa7cc9b820409
1,153
cpp
C++
OperatorsAndConditions/06.PointDistance/Startup.cpp
Tanya-Zheleva/FMI-Intro-Programming
c326d331ac72bc41e4664b23fc56a4da7d2d6729
[ "MIT" ]
2
2020-10-27T09:27:14.000Z
2021-10-09T14:57:15.000Z
OperatorsAndConditions/06.PointDistance/Startup.cpp
Tanya-Zheleva/FMI-Intro-Programming
c326d331ac72bc41e4664b23fc56a4da7d2d6729
[ "MIT" ]
null
null
null
OperatorsAndConditions/06.PointDistance/Startup.cpp
Tanya-Zheleva/FMI-Intro-Programming
c326d331ac72bc41e4664b23fc56a4da7d2d6729
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> using namespace std; int main() { double x1 = 0, y1 = 0, x2 = 0, y2 = 0, x = 0, y = 0; cin >> x1 >> y1 >> x2 >> y2 >> x >> y; double distance = 0; if (x >= x1 && x <= x2 && y >= y1 && y <= y2) { cout << "distance=" << distance << endl; } else { if (x > x1 && x < x2 && y < y1) //Bottom { distance = abs(y1 - y); } else if (x > x1 && x < x2 && y > y2) //Top { distance = abs(y - y2); } else if (y > y1 && y < y2 && x < x1) //Left { distance = abs(x1 - x); } else if (y > y1 && y < y2 && x > x2) //Right { distance = abs(x - x2); } else if (x < x1 && y > y2) //Top left { distance = abs(x1 - x) * abs(x1 - x) + abs(y - y2) * abs(y - y2); } else if (x > x2 && y > y2) //Top right { distance = abs(x - x2) * abs(x - x2) + abs(y - y2) * abs(y - y2); } else if (x < x1 && y < y1) //Bottom left { distance = abs(x1 - x) * abs(x1 - x) + abs(y1 - y) * abs(y1 - y); } else if (x > x2 && y < y1) //Bottom right { distance = abs(x - x2) * abs(x - x2) + abs(y1 - y) * abs(y1 - y); } cout << "distance=" << distance << endl; } return 0; }
20.589286
68
0.447528
Tanya-Zheleva
d471b6e9e858654e1c9ae2a9bdaa02e9dbc17322
22,747
cpp
C++
src/EditorRuntime/GUI/PreferencesGenerated.cpp
akumetsuv/flood
e0d6647df9b7fac72443a0f65c0003b0ead7ed3a
[ "BSD-2-Clause" ]
null
null
null
src/EditorRuntime/GUI/PreferencesGenerated.cpp
akumetsuv/flood
e0d6647df9b7fac72443a0f65c0003b0ead7ed3a
[ "BSD-2-Clause" ]
null
null
null
src/EditorRuntime/GUI/PreferencesGenerated.cpp
akumetsuv/flood
e0d6647df9b7fac72443a0f65c0003b0ead7ed3a
[ "BSD-2-Clause" ]
null
null
null
/////////////////////////////////////////////////////////////////////////// // C++ code generated with wxFormBuilder (version Jun 30 2011) // http://www.wxformbuilder.org/ // // PLEASE DO "NOT" EDIT THIS FILE! /////////////////////////////////////////////////////////////////////////// #include "Editor/API.h" #include "PreferencesGenerated.h" /////////////////////////////////////////////////////////////////////////// Bindings::Bindings( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : wxPanel( parent, id, pos, size, style ) { wxBoxSizer* bSizer15; bSizer15 = new wxBoxSizer( wxVERTICAL ); m_panelBindings = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); wxBoxSizer* bSizer4; bSizer4 = new wxBoxSizer( wxVERTICAL ); wxBoxSizer* bSizer5; bSizer5 = new wxBoxSizer( wxHORIZONTAL ); wxBoxSizer* bSizer7; bSizer7 = new wxBoxSizer( wxVERTICAL ); m_staticText2 = new wxStaticText( m_panelBindings, wxID_ANY, wxT("Commands"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText2->Wrap( -1 ); bSizer7->Add( m_staticText2, 0, wxALL|wxEXPAND, 5 ); m_treeCtrl1 = new wxTreeCtrl( m_panelBindings, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTR_DEFAULT_STYLE ); bSizer7->Add( m_treeCtrl1, 1, wxALL|wxEXPAND, 5 ); bSizer5->Add( bSizer7, 1, wxEXPAND, 5 ); wxBoxSizer* bSizer8; bSizer8 = new wxBoxSizer( wxVERTICAL ); bSizer8->SetMinSize( wxSize( 160,-1 ) ); m_staticText3 = new wxStaticText( m_panelBindings, wxID_ANY, wxT("Current Shortcuts"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText3->Wrap( -1 ); bSizer8->Add( m_staticText3, 0, wxALL|wxEXPAND, 5 ); m_listBox1 = new wxListBox( m_panelBindings, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0, NULL, 0 ); bSizer8->Add( m_listBox1, 1, wxALL|wxEXPAND, 5 ); wxBoxSizer* bSizer9; bSizer9 = new wxBoxSizer( wxHORIZONTAL ); m_button1 = new wxButton( m_panelBindings, wxID_ANY, wxT("Remove"), wxDefaultPosition, wxDefaultSize, 0 ); m_button1->Enable( false ); bSizer9->Add( m_button1, 0, wxALL, 5 ); m_button2 = new wxButton( m_panelBindings, wxID_ANY, wxT("Remove All"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer9->Add( m_button2, 0, wxALL, 5 ); bSizer8->Add( bSizer9, 0, wxEXPAND, 5 ); m_staticText4 = new wxStaticText( m_panelBindings, wxID_ANY, wxT("New"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText4->Wrap( -1 ); bSizer8->Add( m_staticText4, 0, wxALL|wxEXPAND, 5 ); m_textCtrl2 = new wxTextCtrl( m_panelBindings, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_READONLY ); bSizer8->Add( m_textCtrl2, 0, wxALL|wxEXPAND, 5 ); m_staticText5 = new wxStaticText( m_panelBindings, wxID_ANY, wxT("Currently Assigned"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText5->Wrap( -1 ); bSizer8->Add( m_staticText5, 0, wxALL|wxEXPAND, 5 ); m_textCtrl3 = new wxTextCtrl( m_panelBindings, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_READONLY ); m_textCtrl3->Enable( false ); bSizer8->Add( m_textCtrl3, 0, wxALL|wxEXPAND, 5 ); m_button3 = new wxButton( m_panelBindings, wxID_ANY, wxT("Add"), wxDefaultPosition, wxDefaultSize, 0 ); m_button3->Enable( false ); bSizer8->Add( m_button3, 0, wxALL|wxEXPAND, 5 ); bSizer5->Add( bSizer8, 0, wxEXPAND, 5 ); bSizer4->Add( bSizer5, 1, wxEXPAND, 5 ); wxBoxSizer* bSizer6; bSizer6 = new wxBoxSizer( wxVERTICAL ); m_staticText1 = new wxStaticText( m_panelBindings, wxID_ANY, wxT("Description"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText1->Wrap( -1 ); bSizer6->Add( m_staticText1, 0, wxALL, 5 ); m_textCtrl1 = new wxTextCtrl( m_panelBindings, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize( -1,48 ), wxTE_MULTILINE|wxTE_NO_VSCROLL|wxTE_READONLY ); m_textCtrl1->Enable( false ); bSizer6->Add( m_textCtrl1, 1, wxALL|wxEXPAND, 5 ); bSizer4->Add( bSizer6, 0, wxEXPAND, 5 ); m_panelBindings->SetSizer( bSizer4 ); m_panelBindings->Layout(); bSizer4->Fit( m_panelBindings ); bSizer15->Add( m_panelBindings, 1, wxEXPAND | wxALL, 5 ); this->SetSizer( bSizer15 ); this->Layout(); } Bindings::~Bindings() { } Plugins::Plugins( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : wxPanel( parent, id, pos, size, style ) { wxBoxSizer* bSizer1; bSizer1 = new wxBoxSizer( wxVERTICAL ); wxBoxSizer* bSizer11; bSizer11 = new wxBoxSizer( wxVERTICAL ); m_listPlugins = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_REPORT|wxLC_SINGLE_SEL ); bSizer11->Add( m_listPlugins, 1, wxALL|wxEXPAND, 5 ); wxBoxSizer* bSizer19; bSizer19 = new wxBoxSizer( wxHORIZONTAL ); m_buttonPluginEnable = new wxButton( this, wxID_ANY, wxT("Disable"), wxDefaultPosition, wxDefaultSize, 0 ); m_buttonPluginEnable->Enable( false ); bSizer19->Add( m_buttonPluginEnable, 0, wxALL, 5 ); m_buttonPluginUninstall = new wxButton( this, wxID_ANY, wxT("Uninstall"), wxDefaultPosition, wxDefaultSize, 0 ); m_buttonPluginUninstall->Enable( false ); bSizer19->Add( m_buttonPluginUninstall, 1, wxALL, 5 ); m_staticline1 = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_VERTICAL ); bSizer19->Add( m_staticline1, 0, wxEXPAND | wxALL, 5 ); m_buttonPluginCheckUpdates = new wxButton( this, wxID_ANY, wxT("Check Updates"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer19->Add( m_buttonPluginCheckUpdates, 1, wxALL, 5 ); m_buttonPluginInstall = new wxButton( this, wxID_ANY, wxT("Install..."), wxDefaultPosition, wxDefaultSize, 0 ); bSizer19->Add( m_buttonPluginInstall, 1, wxALL, 5 ); bSizer11->Add( bSizer19, 0, wxEXPAND, 5 ); bSizer1->Add( bSizer11, 1, wxEXPAND, 5 ); wxBoxSizer* bSizer18; bSizer18 = new wxBoxSizer( wxVERTICAL ); wxBoxSizer* bSizer61; bSizer61 = new wxBoxSizer( wxVERTICAL ); m_staticText11 = new wxStaticText( this, wxID_ANY, wxT("Description:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText11->Wrap( -1 ); bSizer61->Add( m_staticText11, 0, wxEXPAND|wxRIGHT|wxLEFT, 5 ); m_textPluginDescription = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize( -1,48 ), wxTE_MULTILINE|wxTE_NO_VSCROLL|wxTE_READONLY ); bSizer61->Add( m_textPluginDescription, 1, wxALL|wxEXPAND, 5 ); bSizer18->Add( bSizer61, 0, wxEXPAND, 5 ); bSizer1->Add( bSizer18, 0, wxEXPAND, 5 ); this->SetSizer( bSizer1 ); this->Layout(); // Connect Events this->Connect( wxEVT_INIT_DIALOG, wxInitDialogEventHandler( Plugins::OnPluginInit ) ); m_listPlugins->Connect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( Plugins::OnPluginSelected ), NULL, this ); m_buttonPluginEnable->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( Plugins::OnPluginEnable ), NULL, this ); m_buttonPluginCheckUpdates->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( Plugins::OnPluginCheckUpdates ), NULL, this ); m_buttonPluginInstall->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( Plugins::OnPluginInstall ), NULL, this ); } Plugins::~Plugins() { // Disconnect Events this->Disconnect( wxEVT_INIT_DIALOG, wxInitDialogEventHandler( Plugins::OnPluginInit ) ); m_listPlugins->Disconnect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( Plugins::OnPluginSelected ), NULL, this ); m_buttonPluginEnable->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( Plugins::OnPluginEnable ), NULL, this ); m_buttonPluginCheckUpdates->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( Plugins::OnPluginCheckUpdates ), NULL, this ); m_buttonPluginInstall->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( Plugins::OnPluginInstall ), NULL, this ); } Resources::Resources( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : wxPanel( parent, id, pos, size, style ) { wxBoxSizer* bSizer22; bSizer22 = new wxBoxSizer( wxVERTICAL ); wxBoxSizer* bSizer30; bSizer30 = new wxBoxSizer( wxVERTICAL ); m_staticText21 = new wxStaticText( this, wxID_ANY, wxT("Lookup Paths"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText21->Wrap( -1 ); bSizer30->Add( m_staticText21, 0, wxALL, 5 ); m_listResourcePaths = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_REPORT|wxLC_SINGLE_SEL ); bSizer30->Add( m_listResourcePaths, 1, wxALL|wxEXPAND, 5 ); wxBoxSizer* bSizer28; bSizer28 = new wxBoxSizer( wxHORIZONTAL ); bSizer28->Add( 0, 0, 1, wxEXPAND, 5 ); m_button10 = new wxButton( this, wxID_ANY, wxT("Add..."), wxDefaultPosition, wxDefaultSize, 0 ); bSizer28->Add( m_button10, 0, wxALL, 5 ); m_button11 = new wxButton( this, wxID_ANY, wxT("Remove"), wxDefaultPosition, wxDefaultSize, 0 ); m_button11->Enable( false ); bSizer28->Add( m_button11, 0, wxALL, 5 ); bSizer30->Add( bSizer28, 0, wxEXPAND, 5 ); bSizer22->Add( bSizer30, 1, wxEXPAND, 5 ); wxStaticBoxSizer* sbSizer1; sbSizer1 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, wxT("Indexing") ), wxVERTICAL ); m_checkBox1 = new wxCheckBox( this, wxID_ANY, wxT("Generate thumbnails"), wxDefaultPosition, wxDefaultSize, 0 ); m_checkBox1->SetValue(true); sbSizer1->Add( m_checkBox1, 0, wxALL, 5 ); wxBoxSizer* bSizer23; bSizer23 = new wxBoxSizer( wxHORIZONTAL ); m_staticText8 = new wxStaticText( this, wxID_ANY, wxT("Thumbnails Cache"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText8->Wrap( -1 ); bSizer23->Add( m_staticText8, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); m_dirPicker1 = new wxDirPickerCtrl( this, wxID_ANY, wxEmptyString, wxT("Select a folder"), wxDefaultPosition, wxDefaultSize, wxDIRP_DEFAULT_STYLE|wxDIRP_DIR_MUST_EXIST ); bSizer23->Add( m_dirPicker1, 1, wxALL, 5 ); sbSizer1->Add( bSizer23, 0, wxEXPAND, 5 ); m_button14 = new wxButton( this, wxID_ANY, wxT("Cleanup cache"), wxDefaultPosition, wxDefaultSize, 0 ); sbSizer1->Add( m_button14, 0, wxALL, 5 ); bSizer22->Add( sbSizer1, 0, wxEXPAND, 5 ); this->SetSizer( bSizer22 ); this->Layout(); // Connect Events this->Connect( wxEVT_INIT_DIALOG, wxInitDialogEventHandler( Resources::OnResourcesInit ) ); m_button10->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( Resources::OnResourcesPathAdd ), NULL, this ); } Resources::~Resources() { // Disconnect Events this->Disconnect( wxEVT_INIT_DIALOG, wxInitDialogEventHandler( Resources::OnResourcesInit ) ); m_button10->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( Resources::OnResourcesPathAdd ), NULL, this ); } Renderers::Renderers( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : wxPanel( parent, id, pos, size, style ) { wxBoxSizer* bSizer19; bSizer19 = new wxBoxSizer( wxVERTICAL ); wxBoxSizer* bSizer20; bSizer20 = new wxBoxSizer( wxVERTICAL ); m_staticText8 = new wxStaticText( this, wxID_ANY, wxT("Default Renderer:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText8->Wrap( -1 ); bSizer20->Add( m_staticText8, 0, wxALL, 5 ); wxArrayString m_choice1Choices; m_choice1 = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, m_choice1Choices, 0 ); m_choice1->SetSelection( -1 ); bSizer20->Add( m_choice1, 0, wxALL|wxEXPAND, 5 ); m_staticText10 = new wxStaticText( this, wxID_ANY, wxT("Renderers:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText10->Wrap( -1 ); bSizer20->Add( m_staticText10, 0, wxALL, 5 ); m_listCtrl2 = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_NO_HEADER|wxLC_REPORT|wxLC_SINGLE_SEL ); bSizer20->Add( m_listCtrl2, 0, wxALL|wxEXPAND, 5 ); m_staticText9 = new wxStaticText( this, wxID_ANY, wxT("Extensions:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText9->Wrap( -1 ); bSizer20->Add( m_staticText9, 0, wxALL, 5 ); m_listBox3 = new wxListBox( this, wxID_ANY, wxDefaultPosition, wxSize( -1,120 ), 0, NULL, 0 ); bSizer20->Add( m_listBox3, 1, wxALL|wxEXPAND, 5 ); bSizer19->Add( bSizer20, 1, wxEXPAND, 5 ); this->SetSizer( bSizer19 ); this->Layout(); } Renderers::~Renderers() { } ResourcesFrame::ResourcesFrame( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) { this->SetSizeHints( wxDefaultSize, wxDefaultSize ); wxBoxSizer* bSizer16; bSizer16 = new wxBoxSizer( wxVERTICAL ); m_splitter2 = new wxSplitterWindow( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSP_3D ); m_splitter2->Connect( wxEVT_IDLE, wxIdleEventHandler( ResourcesFrame::m_splitter2OnIdle ), NULL, this ); m_panel2 = new wxPanel( m_splitter2, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); wxBoxSizer* bSizer20; bSizer20 = new wxBoxSizer( wxVERTICAL ); m_resourceGroups = new wxTreeCtrl( m_panel2, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTR_DEFAULT_STYLE|wxTR_HIDE_ROOT|wxTR_ROW_LINES ); bSizer20->Add( m_resourceGroups, 1, wxEXPAND|wxTOP|wxBOTTOM|wxLEFT, 5 ); m_panel2->SetSizer( bSizer20 ); m_panel2->Layout(); bSizer20->Fit( m_panel2 ); m_panel3 = new wxPanel( m_splitter2, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); wxBoxSizer* bSizer18; bSizer18 = new wxBoxSizer( wxVERTICAL ); wxBoxSizer* bSizer21; bSizer21 = new wxBoxSizer( wxHORIZONTAL ); m_searchCtrl = new wxSearchCtrl( m_panel3, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); #ifndef __WXMAC__ m_searchCtrl->ShowSearchButton( true ); #endif m_searchCtrl->ShowCancelButton( false ); bSizer21->Add( m_searchCtrl, 1, wxEXPAND|wxRIGHT, 5 ); m_staticText17 = new wxStaticText( m_panel3, wxID_ANY, wxT("Detail"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText17->Wrap( -1 ); bSizer21->Add( m_staticText17, 0, wxALL, 5 ); m_detailSlider = new wxSlider( m_panel3, wxID_ANY, 0, 0, 256, wxDefaultPosition, wxSize( 60,-1 ), wxSL_HORIZONTAL ); bSizer21->Add( m_detailSlider, 0, 0, 5 ); bSizer18->Add( bSizer21, 0, wxEXPAND|wxTOP, 5 ); m_resourceList = new wxListCtrl( m_panel3, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_ICON ); bSizer18->Add( m_resourceList, 1, wxEXPAND|wxTOP|wxBOTTOM|wxRIGHT, 5 ); m_gauge1 = new wxGauge( m_panel3, wxID_ANY, 100, wxDefaultPosition, wxSize( -1,8 ), wxGA_HORIZONTAL ); bSizer18->Add( m_gauge1, 0, wxEXPAND|wxBOTTOM|wxRIGHT, 5 ); m_panel3->SetSizer( bSizer18 ); m_panel3->Layout(); bSizer18->Fit( m_panel3 ); m_splitter2->SplitVertically( m_panel2, m_panel3, 121 ); bSizer16->Add( m_splitter2, 1, wxEXPAND, 5 ); this->SetSizer( bSizer16 ); this->Layout(); this->Centre( wxBOTH ); // Connect Events this->Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( ResourcesFrame::OnClose ) ); m_resourceGroups->Connect( wxEVT_COMMAND_TREE_SEL_CHANGED, wxTreeEventHandler( ResourcesFrame::onResourceGroupChanged ), NULL, this ); m_detailSlider->Connect( wxEVT_SCROLL_THUMBTRACK, wxScrollEventHandler( ResourcesFrame::onResourceSliderScroll ), NULL, this ); m_resourceList->Connect( wxEVT_COMMAND_LIST_BEGIN_DRAG, wxListEventHandler( ResourcesFrame::OnListBeginDrag ), NULL, this ); m_resourceList->Connect( wxEVT_COMMAND_LIST_ITEM_ACTIVATED, wxListEventHandler( ResourcesFrame::onResourceListActivated ), NULL, this ); m_resourceList->Connect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( ResourcesFrame::onResourceListSelection ), NULL, this ); } ResourcesFrame::~ResourcesFrame() { // Disconnect Events this->Disconnect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( ResourcesFrame::OnClose ) ); m_resourceGroups->Disconnect( wxEVT_COMMAND_TREE_SEL_CHANGED, wxTreeEventHandler( ResourcesFrame::onResourceGroupChanged ), NULL, this ); m_detailSlider->Disconnect( wxEVT_SCROLL_THUMBTRACK, wxScrollEventHandler( ResourcesFrame::onResourceSliderScroll ), NULL, this ); m_resourceList->Disconnect( wxEVT_COMMAND_LIST_BEGIN_DRAG, wxListEventHandler( ResourcesFrame::OnListBeginDrag ), NULL, this ); m_resourceList->Disconnect( wxEVT_COMMAND_LIST_ITEM_ACTIVATED, wxListEventHandler( ResourcesFrame::onResourceListActivated ), NULL, this ); m_resourceList->Disconnect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( ResourcesFrame::onResourceListSelection ), NULL, this ); } ServerFrame::ServerFrame( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxFrame( parent, id, title, pos, size, style ) { this->SetSizeHints( wxDefaultSize, wxDefaultSize ); wxBoxSizer* bSizer22; bSizer22 = new wxBoxSizer( wxVERTICAL ); m_notebookServer = new wxNotebook( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0 ); m_panelStatus = new wxPanel( m_notebookServer, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); wxBoxSizer* bSizer251; bSizer251 = new wxBoxSizer( wxVERTICAL ); wxStaticBoxSizer* sbSizer2; sbSizer2 = new wxStaticBoxSizer( new wxStaticBox( m_panelStatus, wxID_ANY, wxEmptyString ), wxVERTICAL ); wxFlexGridSizer* fgSizer1; fgSizer1 = new wxFlexGridSizer( 0, 2, 0, 0 ); fgSizer1->AddGrowableCol( 1 ); fgSizer1->SetFlexibleDirection( wxVERTICAL ); fgSizer1->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); m_staticText11 = new wxStaticText( m_panelStatus, wxID_ANY, wxT("Host:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText11->Wrap( -1 ); fgSizer1->Add( m_staticText11, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); m_textHost = new wxTextCtrl( m_panelStatus, wxID_ANY, wxT("localhost"), wxDefaultPosition, wxDefaultSize, 0 ); fgSizer1->Add( m_textHost, 1, wxALL|wxEXPAND|wxALIGN_CENTER_VERTICAL, 5 ); m_staticText12 = new wxStaticText( m_panelStatus, wxID_ANY, wxT("Port:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText12->Wrap( -1 ); fgSizer1->Add( m_staticText12, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); m_textPort = new wxTextCtrl( m_panelStatus, wxID_ANY, wxT("9999"), wxDefaultPosition, wxDefaultSize, 0 ); m_textPort->SetValidator( wxTextValidator( wxFILTER_NUMERIC, &port ) ); fgSizer1->Add( m_textPort, 0, wxALL|wxEXPAND|wxALIGN_CENTER_VERTICAL, 5 ); m_staticText16 = new wxStaticText( m_panelStatus, wxID_ANY, wxT("Name:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText16->Wrap( -1 ); fgSizer1->Add( m_staticText16, 0, wxALL, 5 ); m_textName = new wxTextCtrl( m_panelStatus, wxID_ANY, wxT("triton"), wxDefaultPosition, wxDefaultSize, 0 ); fgSizer1->Add( m_textName, 0, wxALL|wxEXPAND, 5 ); m_staticText15 = new wxStaticText( m_panelStatus, wxID_ANY, wxT("Authentication:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText15->Wrap( -1 ); fgSizer1->Add( m_staticText15, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); wxString m_choiceAuthChoices[] = { wxT("None"), wxT("Password"), wxT("Certificate") }; int m_choiceAuthNChoices = sizeof( m_choiceAuthChoices ) / sizeof( wxString ); m_choiceAuth = new wxChoice( m_panelStatus, wxID_ANY, wxDefaultPosition, wxDefaultSize, m_choiceAuthNChoices, m_choiceAuthChoices, 0 ); m_choiceAuth->SetSelection( 0 ); fgSizer1->Add( m_choiceAuth, 1, wxALL|wxEXPAND|wxALIGN_CENTER_VERTICAL, 5 ); sbSizer2->Add( fgSizer1, 1, wxEXPAND, 5 ); bSizer251->Add( sbSizer2, 1, wxEXPAND, 5 ); wxBoxSizer* bSizer26; bSizer26 = new wxBoxSizer( wxHORIZONTAL ); m_staticText13 = new wxStaticText( m_panelStatus, wxID_ANY, wxT("Status:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText13->Wrap( -1 ); bSizer26->Add( m_staticText13, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); m_textStatus = new wxStaticText( m_panelStatus, wxID_ANY, wxT("Disconnected"), wxDefaultPosition, wxDefaultSize, 0 ); m_textStatus->Wrap( -1 ); bSizer26->Add( m_textStatus, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); bSizer26->Add( 0, 0, 1, wxEXPAND|wxALIGN_CENTER_VERTICAL, 5 ); m_buttonConnect = new wxButton( m_panelStatus, wxID_ANY, wxT("Connect"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer26->Add( m_buttonConnect, 0, wxALL|wxEXPAND, 5 ); bSizer251->Add( bSizer26, 0, wxEXPAND, 5 ); m_panelStatus->SetSizer( bSizer251 ); m_panelStatus->Layout(); bSizer251->Fit( m_panelStatus ); m_notebookServer->AddPage( m_panelStatus, wxT("Status"), true ); m_panelChat = new wxPanel( m_notebookServer, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); wxBoxSizer* bSizer25; bSizer25 = new wxBoxSizer( wxVERTICAL ); wxBoxSizer* bSizer24; bSizer24 = new wxBoxSizer( wxHORIZONTAL ); m_textChat = new wxTextCtrl( m_panelChat, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE|wxTE_READONLY ); bSizer24->Add( m_textChat, 1, wxALL|wxEXPAND, 5 ); m_listBox3 = new wxListBox( m_panelChat, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0, NULL, 0 ); bSizer24->Add( m_listBox3, 0, wxALL|wxEXPAND, 5 ); bSizer25->Add( bSizer24, 1, wxEXPAND, 5 ); wxBoxSizer* bSizer23; bSizer23 = new wxBoxSizer( wxHORIZONTAL ); m_textMessage = new wxTextCtrl( m_panelChat, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_NO_VSCROLL|wxTE_PROCESS_ENTER ); bSizer23->Add( m_textMessage, 1, wxALL, 5 ); m_button10 = new wxButton( m_panelChat, wxID_ANY, wxT("Send"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer23->Add( m_button10, 0, wxALL, 5 ); bSizer25->Add( bSizer23, 0, wxEXPAND, 5 ); m_panelChat->SetSizer( bSizer25 ); m_panelChat->Layout(); bSizer25->Fit( m_panelChat ); m_notebookServer->AddPage( m_panelChat, wxT("Chat"), false ); bSizer22->Add( m_notebookServer, 1, wxEXPAND, 5 ); this->SetSizer( bSizer22 ); this->Layout(); this->Centre( wxBOTH ); // Connect Events m_buttonConnect->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( ServerFrame::onConnectButtonClick ), NULL, this ); m_textMessage->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( ServerFrame::onChatSendButtonClick ), NULL, this ); m_button10->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( ServerFrame::onChatSendButtonClick ), NULL, this ); } ServerFrame::~ServerFrame() { // Disconnect Events m_buttonConnect->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( ServerFrame::onConnectButtonClick ), NULL, this ); m_textMessage->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( ServerFrame::onChatSendButtonClick ), NULL, this ); m_button10->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( ServerFrame::onChatSendButtonClick ), NULL, this ); }
43.913127
191
0.728624
akumetsuv
d473e5a5fe110eaa5bd15dc20f09f6a3f1d96622
8,211
cpp
C++
deltaNote/utils/inter_var.cpp
delta1037/deltaNote_repo
f2626412b4f6d178789ed77bf4835bf54e97919c
[ "MIT" ]
null
null
null
deltaNote/utils/inter_var.cpp
delta1037/deltaNote_repo
f2626412b4f6d178789ed77bf4835bf54e97919c
[ "MIT" ]
null
null
null
deltaNote/utils/inter_var.cpp
delta1037/deltaNote_repo
f2626412b4f6d178789ed77bf4835bf54e97919c
[ "MIT" ]
null
null
null
/** * @author: delta1037 * @mail:geniusrabbit@qq.com * @brief: */ #ifdef WINDOW_BUILD #include <Windows.h> #include <sphelper.h> #endif #ifdef LINUX_BUILD #include <dir.h> #endif #include "inter_var.h" #include "log.h" #include "aes_encryption.hpp" std::string is_check_str(IsCheck is_check){ if(is_check == Check_true){ return "true"; } else if(is_check == Check_false){ return "false"; } return "null"; } IsCheck is_check_enum(const std::string &is_check){ if(is_check == "true"){ return Check_true; }else if(is_check == "false"){ return Check_false; } return Check_null; } std::string op_type_str(OpType op_type){ if(op_type == OpType_add){ return "add"; }else if(op_type == OpType_del){ return "del"; }else if(op_type == OpType_alt){ return "alt"; } return "nul"; } OpType op_type_enum(const std::string &op_type){ if(op_type == "add"){ return OpType_add; }else if(op_type == "del"){ return OpType_del; }else if(op_type == "alt"){ return OpType_alt; } return OpType_nul; } std::string tag_type_str(TagType tag_type){ if(tag_type == TagType_low){ return "3-low"; }else if(tag_type == TagType_mid){ return "2-mid"; }else if(tag_type == TagType_high){ return "1-high"; } return "4-nul"; } TagType tag_type_enum(const std::string &tag_type){ if(tag_type == "3-low"){ return TagType_low; }else if(tag_type == "2-mid"){ return TagType_mid; }else if(tag_type == "1-high"){ return TagType_high; } return TagType_nul; } TodoItem::TodoItem(){ this->create_key = ""; this->edit_key = ""; this->op_type = OpType_nul; this->is_check = Check_false; this->tag_type = TagType_low; this->reminder = ""; this->data = ""; } TodoItem::TodoItem( const std::string &create_key, const std::string &edit_key, OpType op_type, IsCheck is_check, TagType tag_type, const std::string &reminder, const std::string &data ){ this->create_key = create_key; this->edit_key = edit_key; this->op_type = op_type; this->is_check = is_check; this->tag_type = tag_type; this->reminder = reminder; this->data = data; } bool check_item_valid(const TodoItem &item){ if(item.create_key.empty()){ return false; } if(item.edit_key.empty()){ return false; } if(item.is_check == Check_null){ return false; } if(item.op_type == OpType_nul){ return false; } return true; } int time_int_s(const std::string &s_time){ tm tm_{}; int year, month, day, hour, minute,second; sscanf(s_time.c_str(),"%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &second); tm_.tm_year = year-1900; tm_.tm_mon = month-1; tm_.tm_mday = day; tm_.tm_hour = hour; tm_.tm_min = minute; tm_.tm_sec = second; tm_.tm_isdst = 0; time_t t_ = mktime(&tm_); //已经减了8个时区 return t_; //秒时间 } /* 获取MS时间 -3 */ uint64_t get_time_of_ms(){ struct timeval tv{}; gettimeofday(&tv, nullptr); return tv.tv_sec * (uint64_t)1000 + tv.tv_usec / 1000; } uint64_t get_time_of_s(){ struct timeval tv{}; gettimeofday(&tv, nullptr); return tv.tv_sec; } std::string get_time_key(){ return std::to_string(get_time_of_ms()); } std::string form_group_data(IsCheck is_check, TagType tag_type, const std::string &reminder, const std::string &data) { Json::Value t_group_data; t_group_data[TODO_ITEM_IS_CHECK] = is_check_str(is_check); t_group_data[TODO_ITEM_TAG_TYPE] = tag_type_str(tag_type); t_group_data[TODO_ITEM_REMINDER] = reminder; t_group_data[TODO_ITEM_DATA] = data; return t_group_data.toStyledString(); } void group_data_parser(const std::string &group_data, IsCheck &is_check, TagType &tag_type, std::string &reminder, std::string &data) { Json::Value t_json_res; Json::Reader t_reader; t_reader.parse(group_data, t_json_res); is_check = is_check_enum(t_json_res.get(TODO_ITEM_IS_CHECK, "").asString()); tag_type = tag_type_enum(t_json_res.get(TODO_ITEM_TAG_TYPE, "").asString()); reminder = t_json_res.get(TODO_ITEM_REMINDER, "").asString(); data = t_json_res.get(TODO_ITEM_DATA, "").asString(); } bool todo_is_valid(const TodoItem &item){ if(item.is_check == Check_null){ return false; } if(item.op_type == OpType_nul){ return false; } if(item.data.empty()){ return false; } return true; } std::string get_abs_path(){ // window 获取存放路径 char path_buffer[1024]; #ifdef WINDOW_BUILD ::GetModuleFileNameA(NULL, path_buffer, 1024); (strrchr(path_buffer, '\\'))[1] = 0; #endif #ifdef LINUX_BUILD getcwd(path_buffer, 1024); #endif return std::string(path_buffer); } std::string encrypt_data(const std::string &src_data, const std::string &key) { if(src_data == ""){ return ""; } AesEncryption aes("cbc", 256); CryptoPP::SecByteBlock enc = aes.encrypt(src_data, key); return std::string(enc.begin(), enc.end()); } std::string decrypt_data(const std::string &src_data, const std::string &key) { if(src_data == ""){ return ""; } AesEncryption aes("cbc", 256); CryptoPP::SecByteBlock enc = aes.decrypt(src_data, key); return std::string(enc.begin(), enc.end()); } Json::Value json_list(const TodoList &todo_list) { // 将列表封装为json的格式[{},{},{}] Json::Value ret_json; for(const auto &it : todo_list){ Json::Value one_todo; one_todo[TODO_ITEM_CREATE_KEY] = it.create_key; one_todo[TODO_ITEM_EDIT_KEY] = it.edit_key; one_todo[TODO_ITEM_OP_TYPE] = op_type_str(it.op_type); one_todo[TODO_ITEM_IS_CHECK] = is_check_str(it.is_check); one_todo[TODO_ITEM_TAG_TYPE] = tag_type_str(it.tag_type); one_todo[TODO_ITEM_REMINDER] = it.reminder; one_todo[TODO_ITEM_DATA] = it.data; ret_json.append(one_todo); } d_logic_debug("list to json, size:%d", ret_json.size()) // 格式:[{},{},{}] return ret_json; } void json_list(TodoList &todo_list, const Json::Value &json_list) { // 将json解析为list的格式 for(const auto& one_todo : json_list){ TodoItem one_item; one_item.create_key = one_todo.get(TODO_ITEM_CREATE_KEY, "").asString(); one_item.edit_key = one_todo.get(TODO_ITEM_EDIT_KEY, "").asString(); one_item.op_type = op_type_enum(one_todo.get(TODO_ITEM_OP_TYPE, "").asString()); one_item.is_check = is_check_enum(one_todo.get(TODO_ITEM_IS_CHECK, "").asString()); one_item.tag_type = tag_type_enum(one_todo.get(TODO_ITEM_TAG_TYPE, "").asString()); one_item.reminder = one_todo.get(TODO_ITEM_REMINDER, "").asString(); one_item.data = one_todo.get(TODO_ITEM_DATA, "").asString(); if(check_item_valid(one_item)){ todo_list.emplace_back(one_item); d_logic_debug("todo valid, create_key:%s, edit_key:%s, op_type:%s, check_type:%s, tag_type:%s, reminder:%s, data:%s", one_item.create_key.c_str(), one_item.edit_key.c_str(), op_type_str(one_item.op_type).c_str(), is_check_str(one_item.is_check).c_str(), tag_type_str(one_item.tag_type).c_str(), one_item.reminder.c_str(), one_item.data.c_str()) }else{ d_logic_warn("todo is invalid, create_key:%s, edit_key:%s, op_type:%s, check_type:%s, tag_type:%s, reminder:%s, data:%s", one_item.create_key.c_str(), one_item.edit_key.c_str(), op_type_str(one_item.op_type).c_str(), is_check_str(one_item.is_check).c_str(), tag_type_str(one_item.tag_type).c_str(), one_item.reminder.c_str(), one_item.data.c_str()) } } d_logic_debug("json to list, size:%d", todo_list.size()) }
29.858182
135
0.617221
delta1037
d476ece0486eabdca89e214205e8e0cbd745c27d
2,812
hpp
C++
src/main/cpp/RLBotInterface/src/RLBotMessages/TCP/SocketReaderWithTimeout.hpp
VirxEC/RLBot
b2d06110b0c8541a85605b6c00dcb898e7f35946
[ "MIT" ]
408
2018-02-16T17:55:53.000Z
2022-03-09T20:50:23.000Z
src/main/cpp/RLBotInterface/src/RLBotMessages/TCP/SocketReaderWithTimeout.hpp
VirxEC/RLBot
b2d06110b0c8541a85605b6c00dcb898e7f35946
[ "MIT" ]
280
2018-02-27T22:11:14.000Z
2022-03-28T21:39:05.000Z
src/main/cpp/RLBotInterface/src/RLBotMessages/TCP/SocketReaderWithTimeout.hpp
VirxEC/RLBot
b2d06110b0c8541a85605b6c00dcb898e7f35946
[ "MIT" ]
125
2018-02-19T19:26:33.000Z
2022-03-23T20:48:09.000Z
#pragma once // blocking_reader.h - a class that provides basic support for // blocking & time-outable single character reads from // boost::asio::serial_port. // // use like this: // // blocking_reader reader(port, 500); // // char c; // // if (!reader.read_char(c)) // return false; // // Kevin Godden, www.ridgesolutions.ie // https://www.ridgesolutions.ie/index.php/2012/12/13/boost-c-read-from-serial-port-with-timeout-example/ // #include <boost/asio.hpp> #include <boost/bind.hpp> class SocketReaderWithTimeout { boost::asio::ip::tcp::socket& socket; boost::asio::deadline_timer timer; bool read_error; // Called when an async read completes or has been cancelled void read_complete(const boost::system::error_code& error, size_t bytes_transferred) { read_error = (error || bytes_transferred == 0); // Read has finished, so cancel the // timer. timer.cancel(); } // Called when the timer's deadline expires. void time_out(const boost::system::error_code& error) { // Was the timeout was cancelled? if (error) { // yes return; } // no, we have timed out, so kill // the read operation // The read callback will be called // with an error socket.cancel(); } public: // Constructs a blocking reader, pass in an open serial_port and // a timeout in milliseconds. SocketReaderWithTimeout(boost::asio::ip::tcp::socket & socket) : socket(socket), timer(socket.get_io_service()), read_error(true) { } // Reads a character or times out // returns false if the read times out bool read_data(int num_bytes, int timeout_millis, boost::asio::streambuf* buffer) { // After a timeout & cancel it seems we need // to do a reset for subsequent reads to work. socket.get_io_service().reset(); boost::asio::async_read( socket, *buffer, boost::asio::transfer_exactly(num_bytes), boost::bind(&SocketReaderWithTimeout::read_complete, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); // Setup a deadline time to implement our timeout. timer.expires_from_now(boost::posix_time::milliseconds(timeout_millis)); timer.async_wait(boost::bind(&SocketReaderWithTimeout::time_out, this, boost::asio::placeholders::error)); // This will block until a character is read // or until the it is cancelled. socket.get_io_service().run(); return !read_error; } };
29.291667
105
0.601351
VirxEC
d478c34c9e275be45836a40c4ceb1088c1206cf9
1,728
cpp
C++
third-party/Empirical/examples/math/math.cpp
koellingh/empirical-p53-simulator
aa6232f661e8fc65852ab6d3e809339557af521b
[ "MIT" ]
null
null
null
third-party/Empirical/examples/math/math.cpp
koellingh/empirical-p53-simulator
aa6232f661e8fc65852ab6d3e809339557af521b
[ "MIT" ]
null
null
null
third-party/Empirical/examples/math/math.cpp
koellingh/empirical-p53-simulator
aa6232f661e8fc65852ab6d3e809339557af521b
[ "MIT" ]
null
null
null
// This file is part of Empirical, https://github.com/devosoft/Empirical // Copyright (C) Michigan State University, 2016-2017. // Released under the MIT Software license; see doc/LICENSE // // // Some examples code for using math functions. #include <iostream> #include "emp/math/math.hpp" int main() { std::cout.setf( std::ios::fixed, std::ios::floatfield ); for (double i = 1; i <= 20; i += 1.0) { std::cout << "Log2(" << i << ") = " << emp::Log2(i) << " Log(10, " << i << ") = " << emp::Log(10, i) << " Pow(" << i << ", 3.0) = " << emp::Pow(i, 3.0) << std::endl; } constexpr double x = emp::Log(10, emp::E); std::cout << "x = " << x << std::endl; std::cout << "emp::Mod(10, 7) = " << emp::Mod(10, 7) << " (expected 3)" << std::endl; std::cout << "emp::Mod(3, 7) = " << emp::Mod(3, 7) << " (expected 3)" << std::endl; std::cout << "emp::Mod(-4, 7) = " << emp::Mod(-4, 7) << " (expected 3)" << std::endl; std::cout << "emp::Mod(-11, 7) = " << emp::Mod(-11, 7) << " (expected 3)" << std::endl; std::cout << "emp::Mod(3.0, 2.5) = " << emp::Mod(3.0, 2.5) << " (expected 0.5)" << std::endl; std::cout << "emp::Mod(-1.1, 2.5) = " << emp::Mod(-1.1, 2.5) << " (expected 1.4)" << std::endl; std::cout << "emp::Mod(12.34, 2.5) = " << emp::Mod(12.34, 2.5) << " (expected 2.34)" << std::endl; std::cout << "emp::Mod(-12.34, 2.5) = " << emp::Mod(-12.34, 2.5) << " (expected 0.16)" << std::endl; std::cout << "emp::Pow(2,3) = " << emp::Pow(2,3) << " (expected 8)" << std::endl; std::cout << "emp::Pow(-2,2) = " << emp::Pow(-2,2) << " (expected 4)" << std::endl; std::cout << "emp::Pow(3,4) = " << emp::Pow(3,4) << " (expected 81)" << std::endl; }
45.473684
102
0.488426
koellingh
d47a5cf69d13c7bea9bca793f3911943798bc2d2
2,915
cpp
C++
miditool/miditool.cpp
DannyHavenith/miditool
f3a371912ef5d2d5f23fce30c06a378575debb36
[ "BSL-1.0" ]
null
null
null
miditool/miditool.cpp
DannyHavenith/miditool
f3a371912ef5d2d5f23fce30c06a378575debb36
[ "BSL-1.0" ]
null
null
null
miditool/miditool.cpp
DannyHavenith/miditool
f3a371912ef5d2d5f23fce30c06a378575debb36
[ "BSL-1.0" ]
null
null
null
// // Copyright (C) 2012 Danny Havenith // // 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) // #include <iostream> #include <fstream> #include <exception> #include <iomanip> // for setiosflags, setw #include "midilib/include/midi_parser.hpp" #include "midilib/include/midi_multiplexer.hpp" #include "midilib/include/timed_midi_visitor.hpp" /// /// This class only reacts on meta events. If the meta event is of type "text" (0x01) /// then it will print the data of the event to the given output stream. /// backward- and forward slashes will be converted to newlines. /// texts that start with @ will be ignored. /// struct print_text_visitor: public events::timed_visitor<print_text_visitor> { typedef events::timed_visitor< print_text_visitor> parent; using parent::operator(); print_text_visitor( std::ostream &output, midi_header &header) : output(output), parent( header) { } void operator()( const events::meta &event) { using namespace std; // is it a text event? // we're ignoring lyrics (0x05) events, because text events have more // information (like 'start of new line') if (event.type == 0x01) { string event_text( event.bytes.begin(), event.bytes.end()); if (event_text.size() > 0 && event_text[0] != '@') { if (event_text[0] == '/' || event_text[0] == '\\') { output << "\n" << setiosflags( ios::right) << setprecision(2) << fixed << setw( 6) << get_current_time() << '\t'; output << event_text.substr( 1); } else { output << event_text; } } } } private: std::ostream &output; }; int main( int argc, char *argv[]) { using namespace std; if (argc != 2) { cerr << "usage: miditool <midi file name>\n"; exit( -1); } try { string filename( argv[1]); ifstream inputfile( filename.c_str(), ios::binary); if (!inputfile) { throw runtime_error( "could not open " + filename + " for reading"); } midi_file midi; if (!parse_midifile( inputfile, midi)) { throw runtime_error( "I can't parse " + filename + " as a valid midi file"); } // combine all midi tracks into one virtual track. midi_multiplexer multiplexer( midi.tracks); // now print all lyrics in the midi file by sending a print_text_visitor into the data structure. multiplexer.accept( print_text_visitor( cout, midi.header)); } catch (const exception &e) { cerr << "something went wrong: " << e.what() << '\n'; } return 0; }
29.15
133
0.578731
DannyHavenith
d47aa88f80d1f5ab83c66a3f017671032818feff
16,604
cpp
C++
extras/ses_apps/sleeve/sleeve_simple_app.cpp
MalcolmSlaney/audio-to-tactile
8c1fa37509aa53307f24dc7d54e99f730a8bcc1f
[ "Apache-2.0" ]
64
2019-05-03T17:33:07.000Z
2022-03-30T17:19:05.000Z
extras/ses_apps/sleeve/sleeve_simple_app.cpp
MalcolmSlaney/audio-to-tactile
8c1fa37509aa53307f24dc7d54e99f730a8bcc1f
[ "Apache-2.0" ]
null
null
null
extras/ses_apps/sleeve/sleeve_simple_app.cpp
MalcolmSlaney/audio-to-tactile
8c1fa37509aa53307f24dc7d54e99f730a8bcc1f
[ "Apache-2.0" ]
10
2019-05-17T15:03:34.000Z
2022-01-29T08:52:03.000Z
// Copyright 2020-2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // // App for running the tactors on the sleeve. // // This app was compiled using Segger studio (SES). The code takes the input // from the puck through the serial port. Upon startup, the sleeve will start // listening to the serial port analog mic data. The analog mic data is // processed by sleeve's tactile processor and outputs pwm to the tactors. The // audio data is downsampled by 8x for the tactile processor, and after // processing it is upsampled back (8x) by the pwm module. // // The sleeve implements a state machine, controlled by the puck commands. // Either raw data from the analog microphone or tactor pwm values could be // sent. Also, the puck can send a command to disable/enable the audio // amplifiers. // // On the puck: // Pressing button 1 on the puck silences the amplifiers. Pressing button 2 will // change the mode to test mode, where tactors are turned on one by one. // Pressing 2 again goes back to analog mic mode. // // The timing is as follows: // Analog mic data is sent every 4 ms, corresponding to 64 samples at 15kHz. // Data transmission over serial takes 1.3 ms at 1Mbit/sec; this happens while // mic data is collected. With optimization level 0 it takes 8 ms to do the // processing (mostly tactor_processor) on the sleeve. With optimization level 2 // for speed (in SES), time is shortened to 3.2 ms. // // On occasion, the startup sequence fails, so the sleeve will automatically // restart. This could take a couple of restart cycles. // // The tactors on the flex pcb is ordered as follows below. The op codes allows // control of the specific channel from the puck. Op code: (PWM module, PWM // channel). The graphic below has op codes in (x). // // 1: (0, 0) 6: (1, 1) (4)-(1) // 2: (0, 1) 7: (1, 2) / \ (2) // 3: (0, 2) 8: (1, 3) (3) (8) (6) (5) // 4: (0, 3) 9: (2, 0) \ / (9) // 5: (1, 0) 10:(2, 1) (7)-(10) // // The tactile processor output is ordered as following: // // 0: baseband 5: eh (6)-(5) sh fricative // 1: aa 6: ae / \ (8) // 2: uw 7: uh (0) (1) (7) (4) // 3: ih 8: sh fricative baseband \ / (9) // 4: iy 9: fricative (2)-(3) fricative // vowel cluster // NOLINTBEGIN(build/include) #include <math.h> #include <stdio.h> #include <string.h> // Hardware drivers. #include "analog_external_mic.h" #include "board_defs.h" #include "lp5012.h" #include "pwm_sleeve.h" #include "serial_com.h" // TODO: There is build error for temperature_monitor and // battery_monitor, as they use the same LPCOMP_COMP_IRQHandler. // Should find a way to resolve it. #include "look_up.h" #include "post_processor_cpp.h" #include "dsp/channel_map.h" #include "tactile/tactile_pattern.h" #include "tactile_processor_cpp.h" #include "two_wire.h" // FreeRTOS libraries. #include "FreeRTOS.h" #include "timers.h" // nRF libraries. #include "app_error.h" #include "nrf.h" #include "nrf_delay.h" #include "nrf_log.h" #include "nrf_log_ctrl.h" #include "nrf_log_default_backends.h" #include "nrf_uarte.h" // NOLINTEND using namespace audio_tactile; // NOLINT(build/namespaces) const int kPwmSamplesAllChannels = kNumPwmValues * kNumTotalPwm; // Audio samples per CARL block. Must be no more than kSaadcFramesPerPeriod. const int kCarlBlockSize = 64; // Decimation factor in audio-to-tactile processing. Tactile signals are // bandlimited below 500 Hz, so e.g. 8x decimation is reasonable. const int kTactileDecimationFactor = 8; // Number of tactile frames per CARL block. const int kTactileFramesPerCarlBlock = kCarlBlockSize / kTactileDecimationFactor; static TaskHandle_t g_tactile_processor_task_handle; // Buffer of received mic audio as int16 samples. static int16_t g_mic_audio_int16[kAdcDataSize]; // Buffer of mic audio converted to floats in [-1, 1]. static float g_mic_audio_float[kAdcDataSize]; static uint16_t pwm_rx[kNumPwmValues]; // True when serial is streaming tactile playback. static bool g_streaming_tactile_playback = true; // True when serial is receiving mic audio (kLoadMicDataOpCode). static bool g_receiving_audio = false; static bool g_led_initialized = false; // TactileProcessor, turns audio into tactile signals. TactileProcessorWrapper g_tactile_processor; // Tuning knobs for configuring tactile processing. TuningKnobs g_tuning_knobs; // TactilePostprocessor, does equalization and limiting on tactile signals. PostProcessorWrapper g_post_processor; // Channel to tactor mapping and final output gains. ChannelMap g_channel_map; // Tactile pattern synthesizer. TactilePattern g_tactile_pattern; // Buffer for holding the tactile pattern string to play. char g_tactile_pattern_buffer[16]; // Pointer to the tactile output buffer of g_tactile_processor. static float* g_tactile_output; // Buffer for streaming tactile playback. uint8_t g_all_tactor_streaming_buffer[kPwmSamplesAllChannels]; static void OnSerialEvent(); static void LogInit(); void OnPwmSequenceEnd(); void OnOverheating(); static void TactileProcessorTaskFun(void* pvParameter); void OnPwmSequenceEnd() { const int which_pwm_module_triggered = SleeveTactors.GetEvent(); // All modules are used together, so only take action on the module 0 trigger. if (which_pwm_module_triggered != 0) { return; } if (g_streaming_tactile_playback) { SleeveTactors.UpdatePwmAllChannelsByte(g_all_tactor_streaming_buffer); // Transmit one byte to synchronize. uint8_t tx_byte[1]; tx_byte[0] = static_cast<uint8_t>(MessageType::kRequestMoreData); SerialCom.SendRaw(Slice<uint8_t, 1>(tx_byte)); } else { constexpr int kNumChannels = 10; // Hardware channel `c` plays logical channel kHwToLogical[c]. constexpr static int kHwToLogical[kNumChannels] = {5, 8, 0, 6, 4, 7, 2, 1, 9, 3}; // There are two levels of mapping: // 1. Hardware channel `c` plays logical channel kHwToLogical[c], // hw[c] = logical[kHwToLogical[c]]. // 2. g_channel_map maps tactile channels to logical channels, // logical[c] = channel_map.gains[c] * tactile[channel_map.sources[c]]. // // We compose this into a single step of copying as // hw[c] = channel_map.gains[logical_c] // * tactile[channel_map.sources[logical_c]]. // with logical_c = kHwToLogical[c]. for (int c = 0; c < kNumChannels; ++c) { const int logical_c = kHwToLogical[c]; const float gain = g_channel_map.gains[logical_c]; const float* src = g_tactile_output + g_channel_map.sources[logical_c]; SleeveTactors.UpdateChannelWithGain(c, gain, src, kTactileProcessorNumTactors); } } } void HandleMessage(const Message& message) { switch (message.type()) { case MessageType::kAudioSamples: { g_receiving_audio = true; g_streaming_tactile_playback = false; message.ReadAudioSamples( Slice<int16_t, kAdcDataSize>(g_mic_audio_int16)); // Unblock the audio processing task. BaseType_t xHigherPriorityTaskWoken; xHigherPriorityTaskWoken = pdFALSE; vTaskNotifyGiveFromISR(g_tactile_processor_task_handle, &xHigherPriorityTaskWoken); portEND_SWITCHING_ISR(xHigherPriorityTaskWoken); } break; case MessageType::kTactor1Samples: case MessageType::kTactor2Samples: case MessageType::kTactor3Samples: case MessageType::kTactor4Samples: case MessageType::kTactor5Samples: case MessageType::kTactor6Samples: case MessageType::kTactor7Samples: case MessageType::kTactor8Samples: case MessageType::kTactor9Samples: case MessageType::kTactor10Samples: case MessageType::kTactor11Samples: case MessageType::kTactor12Samples: { int channel; if (message.ReadSingleTactorSamples( &channel, Slice<uint16_t, kNumPwmValues>(pwm_rx))) { SleeveTactors.UpdateChannel(channel - 1, pwm_rx); } } break; case MessageType::kDisableAmplifiers: SleeveTactors.DisableAmplifiers(); break; case MessageType::kEnableAmplifiers: SleeveTactors.EnableAmplifiers(); break; case MessageType::kTuning: { if (message.ReadTuning(&g_tuning_knobs)) { g_tactile_processor.ApplyTuning(g_tuning_knobs); if (!g_led_initialized) { LedArray.Initialize(); g_led_initialized = true; } LedArray.Clear(); LedArray.LedBar(g_tuning_knobs.values[kKnobOutputGain], 20); // Play "confirm" pattern as UI feedback when new settings are applied. TactilePatternStart(&g_tactile_pattern, kTactilePatternConfirm); } } break; case MessageType::kTactilePattern: if (message.ReadTactilePattern(g_tactile_pattern_buffer)) { TactilePatternStart(&g_tactile_pattern, g_tactile_pattern_buffer); } break; case MessageType::kChannelMap: message.ReadChannelMap(&g_channel_map, kTactileProcessorNumTactors, kTactileProcessorNumTactors); break; case MessageType::kChannelGainUpdate: { int test_channels[2]; if (message.ReadChannelGainUpdate(&g_channel_map, test_channels, kTactileProcessorNumTactors, kTactileProcessorNumTactors)) { TactilePatternStartCalibrationTones(&g_tactile_pattern, test_channels[0], test_channels[1]); } } break; case MessageType::kStreamDataStart: SleeveTactors.DisableAmplifiers(); // Should this be Enable? g_streaming_tactile_playback = true; break; case MessageType::kStreamDataStop: SleeveTactors.EnableAmplifiers(); // Should this be Disable? g_streaming_tactile_playback = false; break; case MessageType::kAllTactorsSamples: if (message.ReadAllTactorsSamples( Slice<uint8_t, kNumTotalPwm * kNumPwmValues>( g_all_tactor_streaming_buffer))) { g_streaming_tactile_playback = true; } break; default: // Handle an unknown op code event. NRF_LOG_RAW_INFO("== UNKNOWN MESSAGE TYPE ==\n"); NRF_LOG_FLUSH(); break; } } static void OnSerialEvent() { g_receiving_audio = false; switch (SerialCom.event()) { case SerialEvent::kMessageReceived: HandleMessage(SerialCom.rx_message()); break; case SerialEvent::kCommError: // Maybe reset if there are errors. Serial coms are not always reliable. break; case SerialEvent::kTimeOutError: // Disable task auto-restarting. nrf_uarte_shorts_disable(NRF_UARTE0, NRF_UARTE_SHORT_ENDRX_STARTRX); // Stop UARTE Rx task. nrf_uarte_task_trigger(NRF_UARTE0, NRF_UARTE_TASK_STOPRX); nrf_delay_ms(8); // Wait a couple frames. // Re-enable auto-restarting. nrf_uarte_shorts_enable(NRF_UARTE0, NRF_UARTE_SHORT_ENDRX_STARTRX); // Start UARTE Rx task. nrf_uarte_task_trigger(NRF_UARTE0, NRF_UARTE_TASK_STARTRX); break; default: NRF_LOG_RAW_INFO("== UNKNOWN SERIAL EVENT ==\n"); NRF_LOG_FLUSH(); break; } } // This interrupt is triggered on overheating. void OnOverheating() { nrf_gpio_pin_toggle(kLedPinBlue); } static void TactileProcessorTaskFun(void*) { for (;;) { // Block the task until interrupt is triggered, when new data is collected. // https://www.freertos.org/xTaskNotifyGive.html ulTaskNotifyTake(pdTRUE, portMAX_DELAY); nrf_gpio_pin_write(kLedPinBlue, 1); // Play synthesized tactile pattern if either a pattern is active or if the // sleeve is not receiving audio, for instance because of a timeout error. // If the pattern isn't active, the pattern synthesizer produces silence. if (!g_receiving_audio || TactilePatternIsActive(&g_tactile_pattern)) { TactilePatternSynthesize( &g_tactile_pattern, g_tactile_processor.GetOutputBlockSize(), g_tactile_processor.GetOutputNumberTactileChannels(), g_tactile_output); } else { // Convert ADC values to floats. The raw ADC values can swing from -2048 // to 2048, so we scale by that value. const float scale = TuningGetInputGain(&g_tuning_knobs) / 2048.0f; for (int i = 0; i < kAdcDataSize; ++i) { g_mic_audio_float[i] = scale * g_mic_audio_int16[i]; } // Process samples. g_tactile_output = g_tactile_processor.ProcessSamples(g_mic_audio_float); } g_post_processor.PostProcessSamples(g_tactile_output); nrf_gpio_pin_write(kLedPinBlue, 0); } } static void LogInit(void) { ret_code_t err_code = NRF_LOG_INIT(nullptr); APP_ERROR_CHECK(err_code); NRF_LOG_DEFAULT_BACKENDS_INIT(); } int main() { // Initialize log, allows to print to the console with seggers j-link. LogInit(); NRF_LOG_RAW_INFO("== SLEEVE START ==\n"); const int kPwmFramesPerPeriod = 64; // SAADC sample rate in Hz. const int kSaadcSampleRateHz = 15625; // To simplify buffering logic, we determine kSaadcFramesPerPeriod so that the // SAADC update period is equal to the PWM update period. const float kSaadcFramesPerPeriod = ((2 * kSaadcSampleRateHz * 512 * kPwmFramesPerPeriod) / 16000000L); // Print important constants. const float update_period_s = (float)kSaadcFramesPerPeriod / kSaadcSampleRateHz; NRF_LOG_RAW_INFO( "%d us period \n %d mic samples \n %d tactile samples \n %d PWM samples " "\n", (int)(1e6f * update_period_s + 0.5f), kAdcDataSize, kNumPwmValues * kTactileDecimationFactor, kNumPwmValues); NRF_LOG_FLUSH(); // Set the indicator led pin to output. nrf_gpio_cfg_output(kLedPinBlue); // Initialize LED driver. // For unknown reason LED driver need to be initialized again in the loop. LedArray.Initialize(); LedArray.CycleAllLeds(1); LedArray.SetOneLed(1, 10); // Initialize tactor driver. SleeveTactors.OnSequenceEnd(OnPwmSequenceEnd); SleeveTactors.Initialize(); SleeveTactors.SetUpsamplingFactor(kTactileDecimationFactor); SleeveTactors.StartPlayback(); // Initialize temperature monitor. // SleeveTemperatureMonitor.StartMonitoringTemperature(); // SleeveTemperatureMonitor.OnOverheatingEventListener(OnOverheating); // Initialize the tactile processor. g_tactile_processor.Init(kSaadcSampleRateHz, kCarlBlockSize, kTactileDecimationFactor); const float kDefaultGain = 4.0f; g_post_processor.Init(g_tactile_processor.GetOutputSampleRate(), g_tactile_processor.GetOutputBlockSize(), g_tactile_processor.GetOutputNumberTactileChannels(), kDefaultGain); ChannelMapInit(&g_channel_map, kTactileProcessorNumTactors); TactilePatternInit(&g_tactile_pattern, g_tactile_processor.GetOutputSampleRate()); TactilePatternStart(&g_tactile_pattern, kTactilePatternSilence); NRF_LOG_RAW_INFO("== TACTILE PROCESSOR SETUP DONE ==\n"); NRF_LOG_FLUSH(); // Initialize serial port. SerialCom.InitSleeve(OnSerialEvent); // Start freeRTOS. xTaskCreate(TactileProcessorTaskFun, "audio", configMINIMAL_STACK_SIZE + 500, nullptr, 2, &g_tactile_processor_task_handle); vTaskStartScheduler(); // App should go into tasks naw, and not reach the code below. Reset the // system if it does. NVIC_SystemReset(); } void HardFault_Handler(void) { uint32_t* sp = (uint32_t*)__get_MSP(); // Get stack pointer. uint32_t ia = sp[12]; // Get instruction address from stack. NRF_LOG_RAW_INFO("Hard Fault at address: 0x%08x\r\n", (unsigned int)ia); NRF_LOG_FLUSH(); while (true) { } }
37.822323
80
0.692122
MalcolmSlaney
d47f901d5644fd16a972e82ad4b2cfe6670851c4
512
hxx
C++
util-lib/include/util/VectorComparator.hxx
andrey-nakin/caen-v1720e-frontend
00d713df62cf3abe330b08411e1f3732e56b4895
[ "MIT" ]
null
null
null
util-lib/include/util/VectorComparator.hxx
andrey-nakin/caen-v1720e-frontend
00d713df62cf3abe330b08411e1f3732e56b4895
[ "MIT" ]
8
2019-03-06T08:43:29.000Z
2019-05-07T11:28:08.000Z
util-lib/include/util/VectorComparator.hxx
andrey-nakin/gneis-daq
00d713df62cf3abe330b08411e1f3732e56b4895
[ "MIT" ]
null
null
null
#pragma once #include <cstring> #include <vector> namespace util { class VectorComparator { VectorComparator() = delete; public: template<typename ValueT> static bool equal(std::vector<ValueT> const& a, std::vector<ValueT> const& b) { if (a.size() != b.size()) { return false; } if (a.empty()) { return true; } return 0 == memcmp(&a[0], &b[0], a.size() * sizeof(a[0])); } static bool equal(std::vector<bool> const& a, std::vector<bool> const& b) { return a == b; } }; }
13.128205
76
0.605469
andrey-nakin
d47fc7db2de430e7d6e0e628f1eee74e63d7ffeb
2,394
cpp
C++
w2/decomposition/correct.cpp
alekseik1/cpp_yellow
8c7e50ffa06a2633f7279ec9b9dae64922860400
[ "MIT" ]
null
null
null
w2/decomposition/correct.cpp
alekseik1/cpp_yellow
8c7e50ffa06a2633f7279ec9b9dae64922860400
[ "MIT" ]
null
null
null
w2/decomposition/correct.cpp
alekseik1/cpp_yellow
8c7e50ffa06a2633f7279ec9b9dae64922860400
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <map> #include <vector> using namespace std; int main() { int q; cin >> q; map<string, vector<string>> buses_to_stops, stops_to_buses; for (int i = 0; i < q; ++i) { string operation_code; cin >> operation_code; if (operation_code == "NEW_BUS") { string bus; cin >> bus; int stop_count; cin >> stop_count; vector<string>& stops = buses_to_stops[bus]; stops.resize(stop_count); for (string& stop : stops) { cin >> stop; stops_to_buses[stop].push_back(bus); } } else if (operation_code == "BUSES_FOR_STOP") { string stop; cin >> stop; if (stops_to_buses.count(stop) == 0) { cout << "No stop" << endl; } else { for (const string& bus : stops_to_buses[stop]) { cout << bus << " "; } cout << endl; } } else if (operation_code == "STOPS_FOR_BUS") { string bus; cin >> bus; if (buses_to_stops.count(bus) == 0) { cout << "No bus" << endl; } else { for (const string& stop : buses_to_stops[bus]) { cout << "Stop " << stop << ": "; if (stops_to_buses[stop].size() == 1) { cout << "no interchange"; } else { for (const string& other_bus : stops_to_buses[stop]) { if (bus != other_bus) { cout << other_bus << " "; } } } cout << endl; } } } else if (operation_code == "ALL_BUSES") { if (buses_to_stops.empty()) { cout << "No buses" << endl; } else { for (const auto& bus_item : buses_to_stops) { cout << "Bus " << bus_item.first << ": "; for (const string& stop : bus_item.second) { cout << stop << " "; } cout << endl; } } } } return 0; }
28.5
78
0.390977
alekseik1
d481bf312f155e5eedaad5a503d3e60689a8e52e
6,271
cc
C++
src/SymmetryAxisNormal.cc
maruinen/FullereneViewer
da1554af2de21e90bfa0380a5b635f8bab8e2d8c
[ "Apache-2.0" ]
null
null
null
src/SymmetryAxisNormal.cc
maruinen/FullereneViewer
da1554af2de21e90bfa0380a5b635f8bab8e2d8c
[ "Apache-2.0" ]
null
null
null
src/SymmetryAxisNormal.cc
maruinen/FullereneViewer
da1554af2de21e90bfa0380a5b635f8bab8e2d8c
[ "Apache-2.0" ]
null
null
null
/* * Project: FullereneViewer * Version: 1.0 * Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext) */ #include <assert.h> #include "SymmetryAxisNormal.h" #include "CarbonAllotrope.h" #include "OpenGLUtil.h" #include "ShutUp.h" SymmetryAxisNormal::SymmetryAxisNormal(CarbonAllotrope* ca, SymmetryAxis* axis) : InteractiveRegularPolygon(ca, 0, 1.0, 2), p_ca(ca), p_axis(axis) { } SymmetryAxisNormal::~SymmetryAxisNormal() { } void SymmetryAxisNormal::reset_interaction() { InteractiveRegularPolygon::reset_interaction(); } void SymmetryAxisNormal::interaction_original(OriginalForceType UNUSED(force_type), Interactives* UNUSED(interactives), double UNUSED(delta)) { Vector3 north_location; Vector3 south_location; int north = p_axis->get_north_sequence_no(); int south = p_axis->get_south_sequence_no(); switch (p_axis->get_type()) { case AXIS_TYPE_CENTER_OF_TWO_CARBONS: { Carbon* north_carbon = p_ca->get_carbon_by_sequence_no(north); Carbon* south_carbon = p_ca->get_carbon_by_sequence_no(south); north_location = north_carbon->get_center_location(); south_location = south_carbon->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_CARBON_AND_BOND: { Carbon* north_carbon = p_ca->get_carbon_by_sequence_no(north); Bond* south_bond = p_ca->get_bond_by_sequence_no(south); north_location = north_carbon->get_center_location(); south_location = south_bond->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_CARBON_AND_RING: { Carbon* north_carbon = p_ca->get_carbon_by_sequence_no(north); Ring* south_ring = p_ca->get_ring_by_sequence_no(south); north_location = north_carbon->get_center_location(); south_location = south_ring->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_CARBON_AND_BOUNDARY: { Carbon* north_carbon = p_ca->get_carbon_by_sequence_no(north); ConnectedBoundary* south_boundary = p_ca->get_boundary_by_sequence_no(south); north_location = north_carbon->get_center_location(); south_location = south_boundary->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_TWO_BONDS: { Bond* north_bond = p_ca->get_bond_by_sequence_no(north); Bond* south_bond = p_ca->get_bond_by_sequence_no(south); north_location = north_bond->get_center_location(); south_location = south_bond->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_BOND_AND_RING: { Bond* north_bond = p_ca->get_bond_by_sequence_no(north); Ring* south_ring = p_ca->get_ring_by_sequence_no(south); north_location = north_bond->get_center_location(); south_location = south_ring->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_BOND_AND_BOUNDARY: { Bond* north_bond = p_ca->get_bond_by_sequence_no(north); ConnectedBoundary* south_boundary = p_ca->get_boundary_by_sequence_no(south); north_location = north_bond->get_center_location(); south_location = south_boundary->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_TWO_RINGS: { Ring* north_ring = p_ca->get_ring_by_sequence_no(north); Ring* south_ring = p_ca->get_ring_by_sequence_no(south); north_location = north_ring->get_center_location(); south_location = south_ring->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_RING_AND_BOUNDARY: { Ring* north_ring = p_ca->get_ring_by_sequence_no(north); ConnectedBoundary* south_boundary = p_ca->get_boundary_by_sequence_no(south); north_location = north_ring->get_center_location(); south_location = south_boundary->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_TWO_BOUNDARIES: { ConnectedBoundary* north_boundary = p_ca->get_boundary_by_sequence_no(north); ConnectedBoundary* south_boundary = p_ca->get_boundary_by_sequence_no(south); north_location = north_boundary->get_center_location(); south_location = south_boundary->get_center_location(); } break; case AXIS_TYPE_CENTER_OF_ONLY_ONE_CARBON: { Carbon* north_carbon = p_ca->get_carbon_by_sequence_no(north); Vector3 center_location = p_ca->get_center_location(); north_location = north_carbon->get_center_location(); south_location = Vector3() - north_location; } break; case AXIS_TYPE_CENTER_OF_ONLY_ONE_BOND: { Bond* north_bond = p_ca->get_bond_by_sequence_no(north); Vector3 center_location = p_ca->get_center_location(); north_location = north_bond->get_center_location(); south_location = Vector3() - north_location; } break; case AXIS_TYPE_CENTER_OF_ONLY_ONE_RING: { Ring* north_ring = p_ca->get_ring_by_sequence_no(north); Vector3 center_location = p_ca->get_center_location(); north_location = north_ring->get_center_location(); south_location = Vector3() - north_location; } break; case AXIS_TYPE_CENTER_OF_ONLY_ONE_BOUNDARY: { ConnectedBoundary* north_boundary = p_ca->get_boundary_by_sequence_no(north); Vector3 center_location = p_ca->get_center_location(); north_location = north_boundary->get_center_location(); south_location = Vector3() - north_location; } break; default: assert(0); } Vector3 center = (north_location + south_location) * 0.5; Vector3 normal = north_location - south_location; p_normal.clockwise = 1; fix_center_location(center); fix_radius_length(normal.abs() * 0.6); fix_posture(Matrix3(Quaternion(Vector3(0.0, 0.0, 1.0), normal))); } void SymmetryAxisNormal::draw_opaque_by_OpenGL(bool UNUSED(selection)) const { Vector3 norm = get_normal(); norm *= p_radius.length; OpenGLUtil::set_color(0x001810); OpenGLUtil::draw_cylinder(0.1, get_center_location() - norm, get_center_location() + norm); } /* Local Variables: */ /* mode: c++ */ /* End: */
36.672515
103
0.69351
maruinen
d481ed8e9cfc1e5f8c9a8c56f91d115871d25666
4,164
cpp
C++
dbi_clients_src/pin/pin-3.6-97554-g31f0a167d-gcc-linux/source/tools/Tests/test_ebx_in_exceptions_xed_interface.cpp
DigitalAlchemist/fuzzwatch
32517e7b80b680dd658e833ed2dfdd88744e6694
[ "Apache-2.0" ]
326
2019-08-10T21:17:22.000Z
2022-03-22T08:40:47.000Z
dbi_clients_src/pin/pin-3.6-97554-g31f0a167d-gcc-linux/source/tools/Tests/test_ebx_in_exceptions_xed_interface.cpp
DigitalAlchemist/fuzzwatch
32517e7b80b680dd658e833ed2dfdd88744e6694
[ "Apache-2.0" ]
42
2019-08-13T12:48:19.000Z
2021-11-03T12:57:59.000Z
dbi_clients_src/pin/pin-3.6-97554-g31f0a167d-gcc-linux/source/tools/Tests/test_ebx_in_exceptions_xed_interface.cpp
DigitalAlchemist/fuzzwatch
32517e7b80b680dd658e833ed2dfdd88744e6694
[ "Apache-2.0" ]
66
2019-08-10T21:41:38.000Z
2022-03-17T13:03:42.000Z
/*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2017 Intel 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 the Intel Corporation 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 INTEL OR ITS 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. END_LEGAL */ #include <iostream> #include <sstream> #include <iomanip> #include <fstream> #include <cstdlib> #include "pin.H" #include "instlib.H" using namespace std; extern "C" void InitXed () { xed_tables_init(); } static char nibble_to_ascii_hex(UINT8 i) { if (i<10) return i+'0'; if (i<16) return i-10+'A'; return '?'; } static void print_hex_line(char* buf, const UINT8* array, const int length) { int n = length; int i=0; if (length == 0) n = XED_MAX_INSTRUCTION_BYTES; for( i=0 ; i< n; i++) { buf[2*i+0] = nibble_to_ascii_hex(array[i]>>4); buf[2*i+1] = nibble_to_ascii_hex(array[i]&0xF); } buf[2*i]=0; } extern "C" UINT32 GetInstructionLenAndDisasm (UINT8 *ip, string *str) { xed_state_t dstate; xed_decoded_inst_t xedd; xed_state_zero(&dstate); if (sizeof(ADDRINT) == 4) xed_state_init(&dstate, XED_MACHINE_MODE_LEGACY_32, XED_ADDRESS_WIDTH_32b, XED_ADDRESS_WIDTH_32b); else xed_state_init(&dstate, XED_MACHINE_MODE_LONG_64, XED_ADDRESS_WIDTH_64b, XED_ADDRESS_WIDTH_64b); xed_decoded_inst_zero_set_mode(&xedd, &dstate); xed_error_enum_t xed_error = xed_decode(&xedd, reinterpret_cast<const UINT8*>(ip), 15); if (XED_ERROR_NONE != xed_error) { fprintf (stderr, "***Error in decoding exception causing instruction at %p\n", ip); return (0); } UINT32 decLen = xed_decoded_inst_get_length(&xedd); ostringstream os; iostream::fmtflags fmt = os.flags(); { char buffer[200]; unsigned int dec_len = 0; unsigned int sp = 0; os << std::setfill('0') << std::hex << std::setw(sizeof(ADDRINT)*2) << reinterpret_cast<UINT64>(ip) << std::dec << ": " << std::setfill(' ') << std::setw(4); os << xed_extension_enum_t2str(xed_decoded_inst_get_extension(&xedd)); print_hex_line(buffer, reinterpret_cast<UINT8*>(ip), decLen); os << " " << buffer; for ( sp=dec_len; sp < 12; sp++) // pad out the instruction bytes os << " "; os << " "; memset(buffer,0,200); int dis_okay = xed_format_context(XED_SYNTAX_INTEL, &xedd, buffer, 200, (ADDRINT)ip, 0, 0); if (dis_okay) os << buffer << endl; else os << "Error disasassembling ip 0x" << std::hex << ip << std::dec << endl; } os.flags(fmt); *str = os.str(); return (decLen); }
31.78626
99
0.657301
DigitalAlchemist
d482493f22cee7d1d51fd9516f9bc6a9e3f4c973
2,222
cpp
C++
Visual Studio 2010/Projects/bjarneStroustrupC++PartIII/bjarneStroustrupC++PartIII/Chapter20TryThis1.cpp
Ziezi/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup-
6fd64801863e883508f15d16398744405f4f9e34
[ "Unlicense" ]
9
2018-10-24T15:16:47.000Z
2021-12-14T13:53:50.000Z
Visual Studio 2010/Projects/bjarneStroustrupC++PartIII/bjarneStroustrupC++PartIII/Chapter20TryThis1.cpp
ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup-
6fd64801863e883508f15d16398744405f4f9e34
[ "Unlicense" ]
null
null
null
Visual Studio 2010/Projects/bjarneStroustrupC++PartIII/bjarneStroustrupC++PartIII/Chapter20TryThis1.cpp
ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup-
6fd64801863e883508f15d16398744405f4f9e34
[ "Unlicense" ]
7
2018-10-29T15:30:37.000Z
2021-01-18T15:15:09.000Z
/* TITLE Improving "ugly" code Chapter20TryThis1.cpp "Bjarne Stroustrup "C++ Programming: Principles and Practice."" COMMENT Objective: If you were able how would you change Jill's code to get rid of the ugliness? Input: - Output: - Author: Chris B. Kirov Date: 17. 02. 2017 */ #include <iostream> #include <vector> double* get_from_jack(int* count); // read from array std::vector<double>* get_from_jill(); // read from vector // First attempt void fct() { int jack_count = 0; double* jack_data = get_from_jack(&jack_count); std::vector<double>* jill_data = get_from_jill(); std::vector<double>& v = *jill_data; // introduce a reference to eliminate ptr dereference in the code // process double h = -1; double* jack_high; double* jill_high; for (int i = 0; i < jack_count; ++i) { if (h < jack_data[i]) { jack_high = &jack_data[i]; } } h = -1; for (int i = 0; i < v.size(); ++i) { if (h < v[i]) { jill_high = &v[i]; } } std::cout <<"Jill's max: " << *jill_high <<" Jack's max: "<< *jack_high; delete[] jack_data; delete jill_data; } //--------------------------------------------------------------------------------------------------------------------------- // Second attempt double* high (double* first, double* last) { double h = -1; double* high; for (double* p = first; p != last; ++p) { if (h < *p) { high = p; } } return high; } //--------------------------------------------------------------------------------------------------------------------------- void fct2() { int jack_count = 0; double* jack_data = get_from_jack(&jack_count); std::vector<double>* jill_data = get_from_jill(); std::vector<double>& v = *jill_data; double* jack_high = high(jack_data, jack_data + jack_count); double* jill_high = high(&v[0], &v[0] + v.size()); std::cout <<"Jill's max: " << *jill_high <<" Jack's max: "<< *jack_high; delete[] jack_data; delete jill_data; } //--------------------------------------------------------------------------------------------------------------------------- int main() { try { } catch (std::exception& e) { std::cerr << e.what(); } getchar (); }
21.572816
125
0.5045
Ziezi
d4839516c3e8b8be4f0bab362e61cfb67d92d376
1,125
hpp
C++
include/Frame.hpp
AgostonSzepessy/oxshans-battle
15d4cd5eb6375cca5e8e426fc9b8f70e74ca28b0
[ "MIT" ]
null
null
null
include/Frame.hpp
AgostonSzepessy/oxshans-battle
15d4cd5eb6375cca5e8e426fc9b8f70e74ca28b0
[ "MIT" ]
null
null
null
include/Frame.hpp
AgostonSzepessy/oxshans-battle
15d4cd5eb6375cca5e8e426fc9b8f70e74ca28b0
[ "MIT" ]
null
null
null
#pragma once #include <SFML/Graphics.hpp> #include <SFML/System.hpp> #include <vector> /** * A class that . */ /** * @brief The Frame class Contains the frames in a vector that are needed for an AnimatedSprite * and the delay between each frame. A frame is an sf::IntRect and the * AnimatedSprite uses that to find the subimage */ class Frame { public: /** * @brief Frame Creates a new Frame */ Frame(); /** * @brief setDelay Sets the delay between the frames * @param d The delay between frames */ void setDelay(double d); /** * @brief addFrame Adds a frame to the back of the vector * @param rect The Frame to add */ void addFrame(const sf::IntRect rect); /** * @brief getFrames Returns a vector that contains all the frames * that have been added. * @return A vector with all the frames */ std::vector<sf::IntRect> getFrames() const; /** * @brief getDelay Gets the delay between frames. * @return Delay between frames */ int getDelay() const; protected: private: std::vector<sf::IntRect> frames; int delay; int height; int width; };
21.226415
95
0.661333
AgostonSzepessy
d48969fb33f306f43abfda229e1d7d202a16f9b3
2,261
cc
C++
kernel/rendering/font_factory.cc
NeilKleistGao/NginD
f36024035a9fa21b893190d6a398778b150e624f
[ "MIT" ]
13
2020-08-02T12:46:21.000Z
2021-09-17T17:44:48.000Z
kernel/rendering/font_factory.cc
NeilKleistGao/NginD
f36024035a9fa21b893190d6a398778b150e624f
[ "MIT" ]
null
null
null
kernel/rendering/font_factory.cc
NeilKleistGao/NginD
f36024035a9fa21b893190d6a398778b150e624f
[ "MIT" ]
1
2020-09-17T04:50:40.000Z
2020-09-17T04:50:40.000Z
/** * @copybrief * MIT License * Copyright (c) 2020 NeilKleistGao * 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. */ /// @file font_factory.h #include "font_factory.h" #include "log/logger_factory.h" namespace ngind::rendering { FontFactory* FontFactory::_instance = nullptr; FontFactory::FontFactory() : _library(nullptr) { auto error = FT_Init_FreeType(&_library); if (error) { auto logger = log::LoggerFactory::getInstance()->getLogger("crash.log", log::LogLevel::LOG_LEVEL_ERROR); logger->log("Can't load Free Type Library"); logger->flush(); } } FontFactory::~FontFactory() { FT_Done_FreeType(_library); } FontFactory* FontFactory::getInstance() { if (_instance == nullptr) { _instance = new(std::nothrow) FontFactory(); } return _instance; } void FontFactory::destroyInstance() { if (_instance != nullptr) { delete _instance; _instance = nullptr; } } FT_Face FontFactory::loadFontFace(const std::string& filename, const long& index) { FT_Face face = nullptr; auto error = FT_New_Face(_library, filename.c_str(), index, &face); if (error) { face = nullptr; } return face; } } // namespace ngind::rendering
32.3
112
0.709421
NeilKleistGao
d489814f335adad50b94a8e3ceb8c95932ba22d2
310
cpp
C++
src/window_helpers/window_manager.cpp
LesleyLai/unnamed-voxel-game
fd2dda6efddd39af969701e17aa0193f7a7df7db
[ "MIT" ]
10
2021-03-07T04:18:01.000Z
2021-07-19T16:55:30.000Z
src/window_helpers/window_manager.cpp
LesleyLai/unnamed-voxel-game
fd2dda6efddd39af969701e17aa0193f7a7df7db
[ "MIT" ]
null
null
null
src/window_helpers/window_manager.cpp
LesleyLai/unnamed-voxel-game
fd2dda6efddd39af969701e17aa0193f7a7df7db
[ "MIT" ]
1
2021-03-24T12:43:53.000Z
2021-03-24T12:43:53.000Z
#include "window_manager.hpp" #include <GLFW/glfw3.h> #include <beyond/utils/panic.hpp> WindowManager::WindowManager() { if (!glfwInit()) { beyond::panic("Failed to initialize GLFW\n"); } } WindowManager::~WindowManager() { glfwTerminate(); } void WindowManager::pull_events() { glfwPollEvents(); }
14.761905
68
0.703226
LesleyLai