hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
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
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
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
5afa112bf2c5007dde353b142e2a1c3d5389df56
12,284
cpp
C++
src/render/Mesh/Mesh.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
src/render/Mesh/Mesh.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
src/render/Mesh/Mesh.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
#include <algorithm> #include <mtt/render/DrawPlan/DrawPlanBuildInfo.h> #include <mtt/render/Mesh/Mesh.h> #include <mtt/utilities/Abort.h> using namespace mtt; Mesh::Mesh(LogicalDevice& device) noexcept: _device(device), _verticesNumber(0), _extraData(*this, device) { } void Mesh::setVerticesNumber(uint32_t newValue) noexcept { if(_verticesNumber == newValue) return; try { _techniquesList.pass( [&](AbstractMeshTechnique& technique) { technique.setVerticesNumber(newValue); }); } catch (...) { Abort("Mesh::setVerticesNumber: unable to set vertices number to technique."); } _verticesNumber = newValue; } void Mesh::addVerticesBuffer( std::shared_ptr<Buffer> buffer, const std::string& name) { Buffers::iterator iBuffer = std::find_if( _vertexBuffers.begin(), _vertexBuffers.end(), [&](const BufferRecord& record) -> bool { return record.name == name; }); if(iBuffer != _vertexBuffers.end()) Abort("Mesh::addVerticesBuffer: buffer with this name is already registered."); try { _techniquesList.pass( [&](AbstractMeshTechnique& technique) { technique.registerVertexBuffer(*buffer, name); }); } catch(...) { Abort("Mesh::addVerticesBuffer: unable to register vertex buffer in technique."); } BufferRecord newRecord; newRecord.name = name; newRecord.buffer = buffer; _vertexBuffers.push_back(newRecord); } void Mesh::removeVerticesBuffer(size_t index) noexcept { BufferRecord& record = _vertexBuffers[index]; try { _techniquesList.pass( [&](AbstractMeshTechnique& technique) { technique.unregisterVertexBuffer(*record.buffer, record.name); }); } catch(...) { Abort("Mesh::removeVerticesBuffer: unable to unregister vertex buffer in technique."); } _vertexBuffers.erase(_vertexBuffers.begin() + index); } void Mesh::removeVerticesBuffer(const std::string& name) noexcept { for(size_t iBuffer = 0; iBuffer < _vertexBuffers.size(); iBuffer++) { if(_vertexBuffers[iBuffer].name == name) { removeVerticesBuffer(iBuffer); break; } } } void Mesh::setIndices(VkPrimitiveTopology topology, std::shared_ptr<Buffer> buffer, VkIndexType indexType, size_t indicesNumber) { if(buffer == nullptr) Abort("Mesh::setIndices: buffer is null"); if (indicesNumber == 0) Abort("Mesh::setIndices: indicesNumber is null"); removeIndices(topology); try { _techniquesList.pass( [&](AbstractMeshTechnique& technique) { technique.registerIndicesBuffer(topology, *buffer, indexType, indicesNumber); }); } catch (...) { Abort("Mesh::addVerticesBuffer: unable to register indices in technique."); } _indicesTable[topology].buffer = buffer; _indicesTable[topology].indexType = indexType; _indicesTable[topology].indicesNumber = indicesNumber; } void Mesh::removeIndices(VkPrimitiveTopology topology) noexcept { if (_indicesTable[topology].buffer == nullptr) return; try { _techniquesList.pass( [&](AbstractMeshTechnique& technique) { technique.unregisterIndicesBuffer(topology); }); } catch(...) { Abort("Mesh::removeIndices: unable to unregister indices from technique."); } _indicesTable[topology].buffer.reset(); _indicesTable[topology].indicesNumber = 0; } void Mesh::registerAreaModificators(AreaModificatorSet& set) { Drawable::registerAreaModificators(set); _areaModificators.push_back(&set); try { _techniquesList.pass( [&](AbstractMeshTechnique& technique) { technique.registerAreaModificators(set); }); } catch (...) { Abort("Mesh::registerAreaModificators: unable to register modificator in techniques."); } } void Mesh::unregisterAreaModificators(AreaModificatorSet& set) noexcept { Drawable::unregisterAreaModificators(set); AreaModificators::iterator iModificators = std::find( _areaModificators.begin(), _areaModificators.end(), &set); if (iModificators == _areaModificators.end()) return; _areaModificators.erase(iModificators); _techniquesList.pass( [&](AbstractMeshTechnique& technique) { technique.unregisterAreaModificators(set); }); } void Mesh::setGeometry(const CommonMeshGeometry& meshData) { if(!meshData.positions.empty()) { std::shared_ptr<Buffer> positionsBuffer(new Buffer( _device, Buffer::VERTEX_BUFFER)); positionsBuffer->setData( meshData.positions.data(), meshData.positions.size() * sizeof(glm::vec3)); setPositionBuffer(positionsBuffer); } else removePositionBuffer(); if(!meshData.normals.empty()) { std::shared_ptr<Buffer> normalsBuffer(new Buffer( _device, Buffer::VERTEX_BUFFER)); normalsBuffer->setData( meshData.normals.data(), meshData.normals.size() * sizeof(glm::vec3)); setNormalBuffer(normalsBuffer); } else removeNormalBuffer(); if(!meshData.tangents.empty()) { std::shared_ptr<Buffer> tangentBuffer(new Buffer( _device, Buffer::VERTEX_BUFFER)); tangentBuffer->setData( meshData.tangents.data(), meshData.tangents.size() * sizeof(glm::vec3)); setTangentBuffer(tangentBuffer); } else removeTangentBuffer(); if(!meshData.binormals.empty()) { std::shared_ptr<Buffer> binormalBuffer( new Buffer( _device, Buffer::VERTEX_BUFFER)); binormalBuffer->setData(meshData.binormals.data(), meshData.binormals.size() * sizeof(glm::vec3)); setBinormalBuffer(binormalBuffer); } else removeBinormalBuffer(); if(!meshData.texCoords.empty()) { std::shared_ptr<Buffer> texCoordBuffer( new Buffer( _device, Buffer::VERTEX_BUFFER)); texCoordBuffer->setData(meshData.texCoords.data(), meshData.texCoords.size() * sizeof(glm::vec2)); setTexCoordBuffer(texCoordBuffer); } else removeTexCoordBuffer(); if(!meshData.skeletonRefs.empty()) { std::vector<uint32_t> indices; indices.reserve(meshData.skeletonRefs.size() * CommonMeshGeometry::MAX_BONES_PER_VERTEX); std::vector<float> weights; weights.reserve(meshData.skeletonRefs.size() * CommonMeshGeometry::MAX_BONES_PER_VERTEX); for(const CommonMeshGeometry::SkeletonRef& ref : meshData.skeletonRefs) { uint16_t iBone = 0; for(; iBone < ref.bonesNumber; iBone++) { indices.push_back(ref.bones[iBone].boneIndex); weights.push_back(ref.bones[iBone].weight); } for (; iBone < CommonMeshGeometry::MAX_BONES_PER_VERTEX; iBone++) { indices.push_back(0); weights.push_back(0); } } std::shared_ptr<Buffer> boneIndicesBuffer( new Buffer(_device, Buffer::VERTEX_BUFFER)); boneIndicesBuffer->setData( indices.data(), indices.size() * sizeof(uint32_t)); setBoneIndecesBuffer(boneIndicesBuffer); std::shared_ptr<Buffer> boneWeightsBuffer( new Buffer(_device, Buffer::VERTEX_BUFFER)); boneWeightsBuffer->setData( weights.data(), weights.size() * sizeof(float)); setBoneWeightsBuffer(boneWeightsBuffer); } else { removeBoneIndicesBuffer(); removeBoneWeightsBuffer(); } setVerticesNumber(uint32_t(meshData.positions.size())); if(!meshData.triangleIndices.empty()) { std::shared_ptr<Buffer> indicesBuffer( new Buffer(_device, Buffer::INDICES_BUFFER)); indicesBuffer->setData( meshData.triangleIndices.data(), meshData.triangleIndices.size() * sizeof(uint16_t)); setIndices( VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, indicesBuffer, VK_INDEX_TYPE_UINT16, meshData.triangleIndices.size()); } else removeIndices(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST); if(!meshData.lineIndices.empty()) { std::shared_ptr<Buffer> indicesBuffer( new Buffer(_device, Buffer::INDICES_BUFFER)); indicesBuffer->setData( meshData.lineIndices.data(), meshData.lineIndices.size() * sizeof(uint16_t)); setIndices( VK_PRIMITIVE_TOPOLOGY_LINE_LIST, indicesBuffer, VK_INDEX_TYPE_UINT16, meshData.lineIndices.size()); } else removeIndices(VK_PRIMITIVE_TOPOLOGY_LINE_LIST); } void Mesh::bindTechnique(AbstractMeshTechnique& technique) { try { technique.setVerticesNumber(_verticesNumber); for (BufferRecord& bufferRecord : _vertexBuffers) { technique.registerVertexBuffer( *bufferRecord.buffer, bufferRecord.name); } for (size_t topology = 0; topology < topologiesNumber; topology++) { if (_indicesTable[topology].buffer != nullptr) { technique.registerIndicesBuffer(VkPrimitiveTopology(topology), *_indicesTable[topology].buffer, _indicesTable[topology].indexType, _indicesTable[topology].indicesNumber); } } for (AreaModificatorSet* modificator : _areaModificators) { technique.registerAreaModificators(*modificator); } _extraData.onTechniqueAdded(technique); } catch (std::exception& error) { Log() << error.what(); Abort("Mesh::bindTechnique: unable to bind technique."); } catch (...) { Abort("Mesh::bindTechnique: unable to bind technique."); } } void Mesh::releaseTechnique(AbstractMeshTechnique& technique) noexcept { _extraData.onTechniqueRemoved(technique); for(BufferRecord& bufferRecord : _vertexBuffers) { technique.unregisterVertexBuffer(*bufferRecord.buffer, bufferRecord.name); } for(size_t topology = 0; topology < topologiesNumber; topology++) { if(_indicesTable[topology].buffer != nullptr) { technique.unregisterIndicesBuffer(VkPrimitiveTopology(topology)); } } for (AreaModificatorSet* modificator : _areaModificators) { technique.unregisterAreaModificators(*modificator); } } void Mesh::setTechnique(FrameType frameType, std::unique_ptr<AbstractMeshTechnique> newTechnique) { try { AbstractMeshTechnique* oldTechnique = _techniquesList.get(frameType); if (oldTechnique != nullptr) oldTechnique->setMesh(nullptr); newTechnique->setMesh(this); } catch(...) { Abort("Mesh::setTechnique: Unable to update technique"); } _techniquesList.set(std::move(newTechnique), frameType); } std::unique_ptr<AbstractMeshTechnique> Mesh::removeTechnique( FrameType frameType) noexcept { std::unique_ptr<AbstractMeshTechnique> removedTechnique = _techniquesList.remove(frameType); if(removedTechnique != nullptr) removedTechnique->setMesh(nullptr); return removedTechnique; } void Mesh::buildDrawActions(DrawPlanBuildInfo& buildInfo) { AbstractMeshTechnique* technique = _techniquesList.get(buildInfo.frameType); if(technique != nullptr) technique->addToDrawPlan(buildInfo); }
31.020202
117
0.611771
AluminiumRat
5afb05a4fe9a26d58f4c401f15e1e3d4984342a0
8,347
cc
C++
hackt_docker/hackt/src/main/flatten.cc
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/main/flatten.cc
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/main/flatten.cc
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
/** \file "main/flatten.cc" Converts HAC source code to an object file (pre-unrolled). This file was born from "art++2obj.cc" in earlier revision history. $Id: flatten.cc,v 1.13 2010/03/11 18:39:26 fang Exp $ */ #include <iostream> #include <list> #include <string> #include <map> #include <cstdio> #include "common/config.hh" #include "main/program_registry.hh" #include "main/flatten.hh" #include "main/main_funcs.hh" #include "main/compile_options.hh" #include "main/global_options.hh" #include "lexer/file_manager.hh" #include "util/getopt_portable.h" #include "util/getopt_mapped.hh" // #include "util/dirent.hh" // configured wrapper around <dirent.h> #include "util/attributes.h" extern HAC::lexer::file_manager hackt_parse_file_manager; namespace HAC { #include "util/using_ostream.hh" using std::list; using std::string; using lexer::file_manager; using util::good_bool; namespace lexer { // from "lexer/hacflat-lex.ll" (and .cc derivatives, of course) extern void flatten_with_wrappers(const bool); } //============================================================================= /** Entry for options. */ struct flatten::options_modifier_info { options_modifier op; string brief; options_modifier_info() : op(NULL), brief() { } options_modifier_info(const options_modifier o, const char* b) : op(o), brief(b) { } operator bool () const { return op; } good_bool operator () (options& o) const { NEVER_NULL(op); return (*op)(o); } }; // end struct options_modifier_info //============================================================================= // class flatten static initializers const char flatten::name[] = "flatten"; const char flatten::brief_str[] = "Flattens HAC source to single file (stdout)."; #ifndef WITH_MAIN const size_t flatten::program_id = register_hackt_program_class<flatten>(); #endif /** Options modifier map must be initialized before any registrations. */ const flatten::options_modifier_map_type flatten::options_modifier_map; //============================================================================= static const char default_options_brief[] = "Needs description."; /** Options modification registration interface. */ class flatten::register_options_modifier { public: register_options_modifier(const string& optname, const options_modifier om, const char* b = default_options_brief) { options_modifier_map_type& omm(const_cast<options_modifier_map_type&>( options_modifier_map)); NEVER_NULL(om); options_modifier_info& i(omm[optname]); INVARIANT(!i); i.op = om; i.brief = b; } } __ATTRIBUTE_UNUSED__; // end class register_options_modifier //============================================================================= // flatten::options_modifier declarations and definitions // TODO: texinfo documentation! static good_bool __flatten_dump_include_paths(flatten::options& o) { o.dump_include_paths = true; return good_bool(true); } static const flatten::register_options_modifier __flatten_om_dump_include_paths("dump-include-paths", &__flatten_dump_include_paths, "dumps -I include paths as they are processed"); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - static good_bool __flatten_no_dump_include_paths(flatten::options& o) { o.dump_include_paths = false; return good_bool(true); } static const flatten::register_options_modifier __flatten_om_no_dump_include_paths("no-dump-include-paths", &__flatten_no_dump_include_paths, "suppress feedback of -I include paths"); //----------------------------------------------------------------------------- #if 0 static good_bool __flatten_dump_object_header(flatten::options& o) { o.dump_object_header = true; return good_bool(true); } static const flatten::register_options_modifier __flatten_om_dump_object_header("dump-object-header", &__flatten_dump_object_header, "dumps persistent object header before saving"); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - static good_bool __flatten_no_dump_object_header(flatten::options& o) { o.dump_object_header = false; return good_bool(true); } static const flatten::register_options_modifier __flatten_om_no_dump_object_header("no-dump-object-header", &__flatten_no_dump_object_header, "suppress persistent object header dump"); #endif //============================================================================= // class flatten method definitions flatten::flatten() { } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** The main program for compiling source to object. TODO: clean up file manager after done? */ int flatten::main(const int _argc, char* argv[], const global_options&) { int argc = _argc; options opt; if (parse_command_options(argc, argv, opt)) { usage(); return 1; } argc -= optind; // shift argv += optind; // shift /*** Now would be a good time to add include paths to the parser's file manager. Don't use a global file_manager, use local variables and pass as arguments, to allow these main subprograms to be re-entrant. Q: Should file_manager be a member of module? ***/ opt.export_include_paths(hackt_parse_file_manager); // TODO: support multi-file flattening, or just defer to cat? if (argc > 1 || argc < 0) { usage(); return 1; } if (argc == 1) { // check file readability FILE* f = open_source_file(argv[0]); if (!f) return 1; fclose(f); // or use util::memory::excl_ptr<FILE, fclose_tag> // dependency generation setup opt.source_file = argv[0]; } else { opt.use_stdin = true; } // flatten it return flatten_source( (argc == 0) ? NULL : opt.source_file.c_str(), opt).good ? 0 : 1; } //----------------------------------------------------------------------------- /** \return 0 if is ok to continue, anything else will signal early termination, an error will cause exit(1). NOTE: the getopt option string begins with '+' to enforce POSIXLY correct termination at the first non-option argument. */ int flatten::parse_command_options(const int argc, char* argv[], options& opt) { static const char* optstring = "+hi:I:M:Pv"; int c; while ((c = getopt(argc, argv, optstring)) != -1) { switch (c) { case 'h': return 1; case 'I': // no need to check validity of paths yet opt.include_paths.push_back(optarg); break; case 'i': opt.prepend_files.push_back(optarg); break; case 'M': opt.make_depend = true; opt.make_depend_target = optarg; break; case 'P': // doesn't have complement or undo... lexer::flatten_with_wrappers(false); break; case 'v': config::dump_all(cout); exit(0); break; case ':': cerr << "Expected but missing non-option argument." << endl; return 1; case '?': util::unknown_option(cerr, optopt); return 1; default: abort(); } // end switch } // end while return 0; } //----------------------------------------------------------------------------- /** Prints summary of options and arguments. */ void flatten::usage(void) { cerr << "hacpp: flattens input file (import directives) to single file, print to stdout" << endl; cerr << "usage: hacpp [options] [hac-source-file]" << endl; cerr << "\tIf no input file is named, then read from stdin (pipe)" << endl; cerr << "options:" << endl; #if 0 { typedef options_modifier_map_type::const_iterator const_iterator; const_iterator i(options_modifier_map.begin()); const const_iterator e(options_modifier_map.end()); for ( ; i!=e; ++i) { cerr << "\t " << i->first << ": " << i->second.brief << endl; } } #endif cerr << "\t-h : gives this usage message" << endl << "\t-I <path> : adds include path (repeatable)" << endl << "\t-i <file> : prepends import file (repeatable)" << endl; cerr << "\t-M <dependfile> : produces make dependency to file" << endl; // cerr << "\t-p : pipe in source from stdin" << endl; cerr << "\t-P : suppress #FILE hierarchical wrappers in output" << endl; cerr << "\t-v : print version and exit" << endl; } //============================================================================= } // end namespace HAC #ifdef WITH_MAIN /** Assumes no global hackt options. */ int main(const int argc, char* argv[]) { const HAC::global_options g; return HAC::flatten::main(argc, argv, g); } #endif // WITH_MAIN
26.925806
80
0.631604
broken-wheel
8500ccba47ab05b65a53675e3628afe36e76b0a7
516
hpp
C++
src/dto/DTOs.hpp
bhorn/example-yuv-websocket-stream
5c77d2eb5387096bbbd37035dcb9818d762c9206
[ "Apache-2.0" ]
6
2020-05-25T20:14:24.000Z
2021-11-22T10:04:44.000Z
src/dto/DTOs.hpp
bhorn/example-yuv-websocket-stream
5c77d2eb5387096bbbd37035dcb9818d762c9206
[ "Apache-2.0" ]
2
2020-05-26T00:12:37.000Z
2021-12-04T01:34:24.000Z
src/dto/DTOs.hpp
bhorn/example-yuv-websocket-stream
5c77d2eb5387096bbbd37035dcb9818d762c9206
[ "Apache-2.0" ]
2
2020-08-28T08:54:46.000Z
2021-08-11T00:14:26.000Z
#ifndef DTOs_hpp #define DTOs_hpp #include "oatpp/core/macro/codegen.hpp" #include "oatpp/core/Types.hpp" #include OATPP_CODEGEN_BEGIN(DTO) namespace dtov0 { class MessageDto : public oatpp::DTO { DTO_INIT(MessageDto, DTO); DTO_FIELD(Int32, statusCode); DTO_FIELD(String, message); }; class ErrorDto : public oatpp::DTO{ DTO_INIT(ErrorDto, DTO) DTO_FIELD(Int32, code); DTO_FIELD(String, message); DTO_FIELD(String, description); }; } #include OATPP_CODEGEN_END(DTO) #endif /* DTOs_hpp */
14.742857
39
0.724806
bhorn
850f95b7364694ea316bd346ba56db0dde99441c
542
cpp
C++
Codeforces/242B.cpp
Benson1198/CPP
b12494becadc9431303cfdb51c5134dc68c679c3
[ "MIT" ]
null
null
null
Codeforces/242B.cpp
Benson1198/CPP
b12494becadc9431303cfdb51c5134dc68c679c3
[ "MIT" ]
null
null
null
Codeforces/242B.cpp
Benson1198/CPP
b12494becadc9431303cfdb51c5134dc68c679c3
[ "MIT" ]
1
2020-10-06T09:17:33.000Z
2020-10-06T09:17:33.000Z
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; long int l[n]; long int r[n]; long int pos[2]; long diff = -1; int position,ans; long int t1,t2; for(int i=0;i<n;i++){ cin >> t1 >> t2; l[i] = t1; r[i] = t2; } for(int i=0;i<n;i++){ if(r[i] - l[i] > diff){ diff = (r[i] - l[i]); pos[0] = l[i]; pos[1] = r[i]; position = i; } } ans = position + 1; for(int i=0;i<n;i++){ if(pos[0] > l[i] || pos[1] < r[i]){ ans = -1; break; } } cout << ans << endl; }
11.291667
37
0.450185
Benson1198
85180c6429c58df77f31b7a75be1f87b9721304f
2,544
cc
C++
gcs/constraints/element.cc
ciaranm/glasgow-constraint-solver
39d925c776474743a51a80492585db3a07801908
[ "MIT" ]
5
2021-08-13T11:36:49.000Z
2022-02-09T11:13:04.000Z
gcs/constraints/element.cc
ciaranm/glasgow-constraint-solver
39d925c776474743a51a80492585db3a07801908
[ "MIT" ]
null
null
null
gcs/constraints/element.cc
ciaranm/glasgow-constraint-solver
39d925c776474743a51a80492585db3a07801908
[ "MIT" ]
null
null
null
/* vim: set sw=4 sts=4 et foldmethod=syntax : */ #include <gcs/constraints/element.hh> #include <gcs/constraints/comparison.hh> #include <gcs/state.hh> #include <gcs/propagators.hh> #include <gcs/integer.hh> #include <util/for_each.hh> #include <algorithm> using namespace gcs; using std::max; using std::min; using std::vector; Element::Element(IntegerVariableID var, IntegerVariableID idx_var, const vector<IntegerVariableID> & vars) : _var(var), _idx_var(idx_var), _vars(vars) { } auto Element::install(Propagators & propagators, const State & initial_state) && -> void { if (_vars.empty()) { propagators.cnf(initial_state, { }, true); return; } // _idx_var >= 0, _idx_var < _vars.size() propagators.trim_lower_bound(initial_state, _idx_var, 0_i); propagators.trim_upper_bound(initial_state, _idx_var, Integer(_vars.size()) - 1_i); // _var <= max(upper(_vars)), _var >= min(lower(_vars)) // ...and this should really be just over _vars that _idx_var might cover auto max_upper = initial_state.upper_bound(*max_element(_vars.begin(), _vars.end(), [&] (const IntegerVariableID & v, const IntegerVariableID & w) { return initial_state.upper_bound(v) < initial_state.upper_bound(w); })); auto min_lower = initial_state.lower_bound(*min_element(_vars.begin(), _vars.end(), [&] (const IntegerVariableID & v, const IntegerVariableID & w) { return initial_state.lower_bound(v) < initial_state.lower_bound(w); })); propagators.trim_lower_bound(initial_state, _var, min_lower); propagators.trim_upper_bound(initial_state, _var, max_upper); for_each_with_index(_vars, [&] (auto & v, auto idx) { // _idx_var == i -> _var == _vars[idx] if (initial_state.in_domain(_idx_var, Integer(idx))) EqualsIf{ _var, v, _idx_var == Integer(idx) }.install(propagators, initial_state); }); initial_state.for_each_value(_var, [&] (Integer val) { // _var == val -> exists i . _vars[idx] == val Literals options; options.emplace_back(_var != val); for_each_with_index(_vars, [&] (auto & v, auto idx) { if (initial_state.in_domain(_idx_var, Integer(idx)) && initial_state.in_domain(v, val)) options.emplace_back(v == val); }); propagators.cnf(initial_state, move(options), true); }); } auto Element::describe_for_proof() -> std::string { return "element"; }
35.333333
152
0.646226
ciaranm
851988557ba3f490b8de173c1b200dd20e5ec525
350
hpp
C++
src/OutputResult.hpp
oleksandrkozlov/touch-typing
e38f315fa979ab66539c0a6a47796b5e6cabe0a2
[ "MIT" ]
1
2020-10-10T14:04:15.000Z
2020-10-10T14:04:15.000Z
src/OutputResult.hpp
oleksandrkozlov/touch-typing
e38f315fa979ab66539c0a6a47796b5e6cabe0a2
[ "MIT" ]
37
2020-04-19T12:37:03.000Z
2021-06-06T09:33:37.000Z
src/OutputResult.hpp
oleksandrkozlov/touch-typing
e38f315fa979ab66539c0a6a47796b5e6cabe0a2
[ "MIT" ]
null
null
null
#ifndef TOUCH_TYPING_OUTPUT_RESULT_HPP #define TOUCH_TYPING_OUTPUT_RESULT_HPP namespace touch_typing { struct OutputResult { enum class Answer { Wrong, Correct, Backspace, }; int expectedSymbol; int enteredSymbol; Answer answer; }; } // namespace touch_typing #endif // TOUCH_TYPING_OUTPUT_RESULT_HPP
16.666667
40
0.708571
oleksandrkozlov
85249aaee3eec536883222f4cb24cdf87abaf217
3,602
cpp
C++
src/objects/joystick.cpp
soulik/LuaSDL-2.0
092684f042de7671a6ee21aaa417e1190b986762
[ "Unlicense", "MIT" ]
10
2016-06-16T12:35:21.000Z
2021-11-14T18:32:41.000Z
src/objects/joystick.cpp
soulik/LuaSDL-2.0
092684f042de7671a6ee21aaa417e1190b986762
[ "Unlicense", "MIT" ]
null
null
null
src/objects/joystick.cpp
soulik/LuaSDL-2.0
092684f042de7671a6ee21aaa417e1190b986762
[ "Unlicense", "MIT" ]
null
null
null
#include "objects/joystick.hpp" #include "objects/haptic.hpp" #include <lua.hpp> namespace LuaSDL { int Joystick::getAxis(State & state, SDL_Joystick * joystick) { Stack * stack = state.stack; stack->push<int>( SDL_JoystickGetAxis( joystick, stack->to<int>(1))); return 1; } int Joystick::getBall(State & state, SDL_Joystick * joystick) { Stack * stack = state.stack; int dx, dy; int retval = SDL_JoystickGetBall( joystick, stack->to<int>(1), &dx, &dy ); if (retval == 0){ stack->push<int>(dx); stack->push<int>(dy); return 2; } else{ return 0; } } int Joystick::getButton(State & state, SDL_Joystick * joystick) { Stack * stack = state.stack; stack->push<bool>( SDL_JoystickGetButton( joystick, stack->to<int>(1)) == 1); return 1; } int Joystick::getHat(State & state, SDL_Joystick * joystick) { Stack * stack = state.stack; stack->push<int>( SDL_JoystickGetHat( joystick, stack->to<int>(1))); return 1; } int Joystick::getIndex(State & state, SDL_Joystick * joystick) { Stack * stack = state.stack; stack->push<int>(SDL_JoystickInstanceID(joystick)); return 1; } int Joystick::getName(State & state, SDL_Joystick * joystick) { Stack * stack = state.stack; const char * name = SDL_JoystickName(joystick); if (name){ stack->push<const std::string &>(name); return 1; } else{ return 0; } } int Joystick::getNumAxes(State & state, SDL_Joystick * joystick) { Stack * stack = state.stack; stack->push<int>(SDL_JoystickNumAxes(joystick)); return 1; } int Joystick::getNumBalls(State & state, SDL_Joystick * joystick) { Stack * stack = state.stack; stack->push<int>(SDL_JoystickNumBalls(joystick)); return 1; } int Joystick::getNumButtons(State & state, SDL_Joystick * joystick) { Stack * stack = state.stack; stack->push<int>(SDL_JoystickNumButtons(joystick)); return 1; } int Joystick::getNumHats(State & state, SDL_Joystick * joystick) { Stack * stack = state.stack; stack->push<int>(SDL_JoystickNumHats(joystick)); return 1; } int Joystick::getHaptic(State & state, SDL_Joystick * joystick){ Stack * stack = state.stack; Haptic * interfaceHaptic = state.getInterface<Haptic>("LuaSDL_Haptic"); SDL_Haptic * haptic = SDL_HapticOpenFromJoystick(joystick); if (haptic){ interfaceHaptic->push(haptic, true); return 1; } else{ return 0; } } int Joystick::isHaptic(State & state, SDL_Joystick * joystick) { Stack * stack = state.stack; stack->push<bool>(SDL_JoystickIsHaptic(joystick) == 1); return 1; } SDL_Joystick * Joystick::constructor(State & state, bool & managed){ Stack * stack = state.stack; Joystick * interfaceJoystick = state.getInterface<Joystick>("LuaSDL_Joystick"); SDL_Joystick * joystick = SDL_JoystickOpen(stack->to<int>(1)); return joystick; } static int lua_SDL_NumJoysticks(State & state){ Stack * stack = state.stack; stack->push<int>(SDL_NumJoysticks()); return 1; } static int lua_SDL_JoystickUpdate(State & state){ Stack * stack = state.stack; SDL_JoystickUpdate(); return 0; } static int lua_SDL_JoystickNameForIndex(State & state){ Stack * stack = state.stack; stack->push<const std::string &>(SDL_JoystickNameForIndex(stack->to<int>(1))); return 1; } void initJoystick(State * state, Module & module){ INIT_OBJECT(Joystick); //module["Joystick"] = lua_SDL_JoystickOpen; module["numJoysticks"] = lua_SDL_NumJoysticks; module["joystickUpdate"] = lua_SDL_JoystickUpdate; module["joystickNameForIndex"] = lua_SDL_JoystickNameForIndex; } };
25.546099
81
0.686008
soulik
8524eb85cb862a64b5e5d48f45f69be8b7d5288c
5,169
cpp
C++
src/relabel_to_front.cpp
FamousCake/flow
77f134f74996225f679a1b9d796b7328ad6e1867
[ "MIT" ]
null
null
null
src/relabel_to_front.cpp
FamousCake/flow
77f134f74996225f679a1b9d796b7328ad6e1867
[ "MIT" ]
null
null
null
src/relabel_to_front.cpp
FamousCake/flow
77f134f74996225f679a1b9d796b7328ad6e1867
[ "MIT" ]
null
null
null
#include "inc/relabel_to_front.h" using namespace std; RelabelToFront::RelabelToFront(const ResidualNetwork &A) : E(ResidualNetwork(A)) { this->Source = E.getSource(); this->Sink = E.getSink(); this->VertexCount = E.getCount(); this->PushCount = 0; this->RelabelCount = 0; this->DischargeCount = 0; // Инициализация на списъка от върховете this->V = vector<Vertex>(VertexCount); for (int i = 0; i < VertexCount; ++i) { // Инициализация на указател към текущо ребро V[i].NCurrent = E.getOutgoingEdges(i).begin(); } // Масив, в които се запазва броя на върховете на всяка от височините this->HeightCount = vector<int>(2 * VertexCount, 0); // Източника и шахтата имат статична височина this->HeightCount[VertexCount] = 1; this->HeightCount[0] = VertexCount - 1; V[Source].Height = VertexCount; } RelabelToFront::~RelabelToFront() { } void RelabelToFront::Run() { // Изпълнението на евристиката Global Relabeling Heuristic SetInitialLabels(); // Избутване на поток равен на разреза ({s}, V\{s}) for (auto &edge : E.getOutgoingEdges(Source)) { if (edge.weight > 0) { V[Source].ExcessFlow += edge.weight; Push(edge); } } // Основно действие на алгоритъма do { int i = ActiveQueue.front(); ActiveQueue.pop(); Discharge(i); } while (!ActiveQueue.empty()); } void RelabelToFront::Discharge(const int i) { this->DischargeCount++; auto begin = E.getOutgoingEdges(i).begin(); auto end = E.getOutgoingEdges(i).end(); auto current = V[i].NCurrent; while (V[i].ExcessFlow > 0) { if (current == end) { int oldHeight = V[i].Height; Relabel(i); // Изпълнение на евристиката Gap Heuristic, ако е намерена празна височина if (HeightCount[oldHeight] == 0) { Gap(oldHeight); } current = begin; continue; } else if (CanPush(*current)) { Push(*current); } current++; } V[i].NCurrent = current; } void RelabelToFront::Push(ResidualEdge &edge) { this->PushCount++; // Ако избутваме поток към неактивен връх, се добавя към опашката if (V[edge.to].ExcessFlow == 0 && edge.to != Source && edge.to != Sink) { ActiveQueue.push(edge.to); } int min = std::min(V[edge.from].ExcessFlow, edge.weight); edge.weight -= min; E.E[edge.to][edge.index].weight += min; V[edge.from].ExcessFlow -= min; V[edge.to].ExcessFlow += min; } void RelabelToFront::Relabel(const int i) { this->RelabelCount++; this->V[i].RelabelCount++; auto minHeight = 2 * VertexCount; for (const auto &edge : E.getOutgoingEdges(i)) { if (edge.weight > 0) { minHeight = min(minHeight, V[edge.to].Height); } } HeightCount[V[i].Height]--; V[i].Height = minHeight + 1; HeightCount[V[i].Height]++; } void RelabelToFront::Gap(const int k) { // Промяна на височините на всички върхове ако е намерена дупка във височините for (int i = 0; i < VertexCount; i++) { if (i != Source && i != Sink && V[i].Height >= k) { HeightCount[V[i].Height]--; V[i].Height = std::max(V[i].Height, VertexCount + 1); HeightCount[V[i].Height]++; } } } bool RelabelToFront::CanPush(const ResidualEdge &edge) { // 1) Must be overflowing if (!IsOverflowing(edge.from)) { return false; } // 2) There must exist an edge in the residual network if (edge.weight == 0) { return false; } // 4) i.h = j.h +1 if (V[edge.from].Height != V[edge.to].Height + 1) { return false; } return true; } bool RelabelToFront::CanRelabel(const int i) { // 1) Must be overflowing if (!IsOverflowing(i)) { return false; } // 2) All neigbors must be highter for (auto edge : E.getOutgoingEdges(i)) { if (edge.weight > 0) { if (V[edge.from].Height > V[edge.to].Height) { return false; } } } return true; } bool RelabelToFront::IsOverflowing(const int i) { return V[i].ExcessFlow > 0 && i != Source && i != Sink; } // Изпълнява обратно търсене в дълбочина void RelabelToFront::SetInitialLabels() { queue<int> q; vector<bool> A = vector<bool>(VertexCount, false); q.push(Sink); A[Sink] = true; A[Source] = true; while (!q.empty()) { const int u = q.front(); q.pop(); const int dist = V[u].Height + 1; for (const auto &edge : E.getOutgoingEdges(u)) { if (E.E[edge.to][edge.index].weight > 0 && A[edge.to] == false) { q.push(edge.to); A[edge.to] = true; HeightCount[V[edge.to].Height]--; V[edge.to].Height = dist; HeightCount[V[edge.to].Height]++; } } } }
22.184549
86
0.549236
FamousCake
85261618b4f7eb39d943d1c8063ae6e1e79b3b8d
3,085
hpp
C++
FFG_EXT/include/FFG_XML.hpp
GarrettGutierrez1/FFG_Engine
ba61887f6db2bdc947118b50beb3388d49eeaad4
[ "Apache-2.0" ]
null
null
null
FFG_EXT/include/FFG_XML.hpp
GarrettGutierrez1/FFG_Engine
ba61887f6db2bdc947118b50beb3388d49eeaad4
[ "Apache-2.0" ]
null
null
null
FFG_EXT/include/FFG_XML.hpp
GarrettGutierrez1/FFG_Engine
ba61887f6db2bdc947118b50beb3388d49eeaad4
[ "Apache-2.0" ]
null
null
null
#ifndef FFG_EXT_XML_H_INCLUDED #define FFG_EXT_XML_H_INCLUDED #include <boost/property_tree/xml_parser.hpp> #include <boost/property_tree/ptree.hpp> #include <string> #include <vector> /***************************************************************************//** * A class that represents an XML tag. * * Example usage: * ----------------------------------------------------------------------------- * TODO: Add example usage. * ----------------------------------------------------------------------------- ******************************************************************************/ class FFG_XML_Tag { public: /***************************************************************************//** * The index of this tag's parent. ******************************************************************************/ int parent; /***************************************************************************//** * The index of this tag's first child. ******************************************************************************/ int first_child; /***************************************************************************//** * The number of children this tag has. ******************************************************************************/ int num_children; /***************************************************************************//** * The name of this tag. ******************************************************************************/ std::string name; /***************************************************************************//** * The inner text of this tag. ******************************************************************************/ std::string inner_text; /***************************************************************************//** * The attributes of this tag. ******************************************************************************/ std::vector<std::pair<std::string, std::string>> attributes; public: FFG_XML_Tag(); std::string get_attribute(const std::string& attribute_name, const std::string& default_value); }; /***************************************************************************//** * A class for parsing XML documents. A thin wrapper over boost's property_tree. * * Example usage: * ----------------------------------------------------------------------------- * TODO: Add example usage. * ----------------------------------------------------------------------------- ******************************************************************************/ class FFG_XML { public: /***************************************************************************//** * The tags of the parsed XML document. ******************************************************************************/ std::vector<FFG_XML_Tag> tags; private: bool is_tag(const std::string& name); void parse_tree(const boost::property_tree::ptree& tree, int parent_index); public: void parse(const std::string filepath); }; #endif // FFG_EXT_XML_H_INCLUDED
44.071429
99
0.294003
GarrettGutierrez1
852cb9a8406af1f1e3ae63037f10878bcdba303a
2,029
cpp
C++
src/SaveGame/SaveGameHandler.cpp
Perchindroid/DigimonVPet
75ae638fb19a5b5d7073589734aa43f8a20813a4
[ "MIT" ]
23
2021-02-17T06:37:42.000Z
2022-03-31T23:16:39.000Z
src/SaveGame/SaveGameHandler.cpp
Perchindroid/DigimonVPet
75ae638fb19a5b5d7073589734aa43f8a20813a4
[ "MIT" ]
3
2021-03-09T14:39:48.000Z
2022-03-22T12:27:52.000Z
src/SaveGame/SaveGameHandler.cpp
Perchindroid/DigimonVPet
75ae638fb19a5b5d7073589734aa43f8a20813a4
[ "MIT" ]
13
2021-03-23T05:35:32.000Z
2022-03-21T12:01:38.000Z
#include "SaveGameHandler.h" void SaveGameHandler::loadDigimon(Digimon* digimon) { digimon->setDigimonIndex(EEPROM.readUShort(ADRESS_DIGIMONINDEX)); digimon->setState(EEPROM.readByte(ADDRESS_STATE)); digimon->setAge(EEPROM.readUShort(ADDRESS_AGE)); digimon->setWeight(EEPROM.readUShort(ADDRESS_WEIGHT)); digimon->setFeedCounter(EEPROM.readUShort(ADDRESS_FEEDCOUNTER)); digimon->setCareMistakes(EEPROM.readUShort(ADDRESS_CAREMISTAKES)); digimon->setTrainingCounter(EEPROM.readUShort(ADDRESS_TRAININGCOUNTER)); digimon->setPoopTimer(EEPROM.readULong(ADDRESS_POOPTIMER)); digimon->setAgeTimer(EEPROM.readULong(ADDRESS_AGETIMER)); digimon->setEvolutionTimer(EEPROM.readULong(ADDRESS_EVOLUTIONETIMER)); digimon->setNumberOfPoops(EEPROM.readByte(ADDRESS_NUMBEROFPOOPS)); digimon->setHunger(EEPROM.readByte(ADDRESS_HUNGER)); digimon->setStrength(EEPROM.readByte(ADDRESS_STRENGTH)); digimon->setEffort(EEPROM.readByte(ADDRESS_EFFORT)); digimon->setDigimonPower(EEPROM.readByte(ADDRESS_DIGIMONPOWER)); } void SaveGameHandler::saveDigimon(Digimon* digimon) { EEPROM.put(ADRESS_DIGIMONINDEX,digimon->getDigimonIndex()); EEPROM.put(ADDRESS_STATE,digimon->getState()); EEPROM.put(ADDRESS_AGE,digimon->getAge()); EEPROM.put(ADDRESS_WEIGHT,digimon->getWeight()); EEPROM.put(ADDRESS_FEEDCOUNTER,digimon->getFeedCounter()); EEPROM.put(ADDRESS_CAREMISTAKES,digimon->getCareMistakes()); EEPROM.put(ADDRESS_TRAININGCOUNTER,digimon->getTrainingCounter()); EEPROM.put(ADDRESS_POOPTIMER,digimon->getPoopTimer()); EEPROM.put(ADDRESS_AGETIMER,digimon->getAgeTimer()); EEPROM.put(ADDRESS_EVOLUTIONETIMER,digimon->getEvolutionTimer()); EEPROM.put(ADDRESS_NUMBEROFPOOPS,digimon->getNumberOfPoops()); EEPROM.put(ADDRESS_HUNGER,digimon->getHunger()); EEPROM.put(ADDRESS_STRENGTH,digimon->getStrength()); EEPROM.put(ADDRESS_EFFORT,digimon->getEffort()); EEPROM.put(ADDRESS_DIGIMONPOWER,digimon->getDigimonPower()); EEPROM.commit(); }
52.025641
76
0.780187
Perchindroid
852ced3651dbabe577a0de3dd6fbbfe85a4259ea
4,185
cpp
C++
src/libs/test/main.cpp
jdmclark/gorc
a03d6a38ab7684860c418dd3d2e77cbe6a6d9fc8
[ "Apache-2.0" ]
97
2015-02-24T05:09:24.000Z
2022-01-23T12:08:22.000Z
src/libs/test/main.cpp
annnoo/gorc
1889b4de6380c30af6c58a8af60ecd9c816db91d
[ "Apache-2.0" ]
8
2015-03-27T23:03:23.000Z
2020-12-21T02:34:33.000Z
src/libs/test/main.cpp
annnoo/gorc
1889b4de6380c30af6c58a8af60ecd9c816db91d
[ "Apache-2.0" ]
10
2016-03-24T14:32:50.000Z
2021-11-13T02:38:53.000Z
#include <string> #include "test.hpp" #include "strings.hpp" #include "stream_reporter.hpp" namespace test { std::shared_ptr<test::reporter> test_reporter; std::string test_suite_name; std::string test_case_name; bool test_passing; void run_case(int &failures, std::string const &suite_name, std::string const &case_name, std::shared_ptr<case_factory> factory) { test_suite_name = suite_name; test_case_name = case_name; std::unique_ptr<case_object> test_case; // Setup case try { test_case = factory->create_case(); test_case->setup(); } catch(...) { test_reporter->fixture_setup_fail(suite_name, case_name, factory->filename, factory->line_number); ++failures; return; } // Run test case try { test_passing = true; test_case->run(); if(test_passing) { test_reporter->case_pass(suite_name, case_name); } else { ++failures; } } catch(test::exception const &e) { test_reporter->case_assertion_fail(suite_name, case_name, e.reason, e.filename, e.line_number); ++failures; } catch(std::exception const &e) { test_reporter->case_std_exception_fail(suite_name, case_name, e.what(), factory->filename, factory->line_number); ++failures; } catch(...) { test_reporter->case_unhandled_exception_fail(suite_name, case_name, factory->filename, factory->line_number); ++failures; } // Teardown case try { test_case->teardown(); test_case.reset(); } catch(...) { test_reporter->fixture_teardown_fail(suite_name, case_name, factory->filename, factory->line_number); ++failures; return; } } void run_suite(int &failures, std::string const &suite_name, std::shared_ptr<suite_factory> factory) { std::shared_ptr<suite> suite = factory->create_suite(); case_vector& caseFactories = suite->get_case_factories(); for(auto jt = caseFactories.begin(); jt != caseFactories.end(); ++jt) { test_reporter->case_begin(suite_name, jt->first); run_case(failures, suite_name, jt->first, jt->second); test_reporter->case_end(suite_name, jt->first); } } void run_cases(std::string const &bin_name, int &failures) { test_reporter->report_begin(bin_name); auto &factories = ::gorc::get_global<suite_registry>()->factories; for(auto it = factories.begin(); it != factories.end(); ++it) { test_reporter->suite_begin(it->first); run_suite(failures, it->first, it->second); test_reporter->suite_end(it->first); } test_reporter->report_end(); } } int main(int, char** argv) { // Build reporter test::test_reporter = std::make_shared<test::stream_reporter>(std::cout); int failures = 0; test::run_cases(argv[0], failures); return (failures == 0) ? EXIT_SUCCESS : EXIT_FAILURE; }
32.695313
79
0.455675
jdmclark
852f79e1d35f914d3475d46eb01873679266c680
1,138
cpp
C++
src/game/shared/neotokyo/neo_bloomcontroller.cpp
L-Leite/neotokyo-re
a45cdcb9027ffe8af72cf1f8e22976375e6b1e0a
[ "Unlicense" ]
4
2017-08-29T15:39:53.000Z
2019-06-04T07:37:48.000Z
src/game/shared/neotokyo/neo_bloomcontroller.cpp
Ochii/neotokyo
a45cdcb9027ffe8af72cf1f8e22976375e6b1e0a
[ "Unlicense" ]
null
null
null
src/game/shared/neotokyo/neo_bloomcontroller.cpp
Ochii/neotokyo
a45cdcb9027ffe8af72cf1f8e22976375e6b1e0a
[ "Unlicense" ]
1
2021-08-10T20:01:00.000Z
2021-08-10T20:01:00.000Z
#include "cbase.h" #include "neo_bloomcontroller.h" CNeoBloomController* g_pMapBloomController = nullptr; IMPLEMENT_NETWORKCLASS_ALIASED( NeoBloomController, DT_NeoBloomController ) BEGIN_NETWORK_TABLE( CNeoBloomController, DT_NeoBloomController ) #ifdef CLIENT_DLL RecvPropFloat( RECVINFO( m_BloomAmount ) ), #else SendPropFloat( SENDINFO( m_BloomAmount ) ), #endif END_NETWORK_TABLE() LINK_ENTITY_TO_CLASS( neo_bloom_controller, CNeoBloomController ); inline CNeoBloomController* GetMapBloomController() { return g_pMapBloomController; } CNeoBloomController::CNeoBloomController() { g_pMapBloomController = this; } CNeoBloomController::~CNeoBloomController() { if ( g_pMapBloomController == this ) g_pMapBloomController = nullptr; } #ifdef GAME_DLL int CNeoBloomController::UpdateTransmitState() { return SetTransmitState( FL_EDICT_ALWAYS ); } bool CNeoBloomController::KeyValue( const char *szKeyName, const char *szValue ) { if ( FStrEq( szKeyName, "bloomamount" ) ) m_BloomAmount = atof( szValue ); else return BaseClass::KeyValue( szKeyName, szValue ); return true; } #endif
21.884615
80
0.771529
L-Leite
85307d422933be16fb72ca1365745675bb2ae260
3,422
cpp
C++
tech/Script/integration/Lua/ScriptHelper.cpp
nbtdev/teardrop
fa9cc8faba03a901d1d14f655a04167e14cd08ee
[ "MIT" ]
null
null
null
tech/Script/integration/Lua/ScriptHelper.cpp
nbtdev/teardrop
fa9cc8faba03a901d1d14f655a04167e14cd08ee
[ "MIT" ]
null
null
null
tech/Script/integration/Lua/ScriptHelper.cpp
nbtdev/teardrop
fa9cc8faba03a901d1d14f655a04167e14cd08ee
[ "MIT" ]
null
null
null
/****************************************************************************** Copyright (c) 2015 Teardrop Games 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 "stdafx.h" extern "C" { #include "lua.h" #include "lualib.h" #include "lauxlib.h" } #include "ScriptHelper.h" #include "Variant.h" using namespace Teardrop; //--------------------------------------------------------------------------- ScriptHelper::ScriptHelper(lua_State& L) : m_l(L) { } //--------------------------------------------------------------------------- bool ScriptHelper::getParam(int idx, Variant& param) { if (idx < 1 || idx > lua_gettop(&m_l)) { param.type = Variant::VT_NONE; return false; } if (lua_isboolean(&m_l, idx)) { param.type = Variant::VT_BOOL; param.v.b = (lua_toboolean(&m_l, idx) == 1); return true; } if (lua_isnumber(&m_l, idx)) { if (param.type == Variant::VT_INT) { param.v.i = (int)lua_tointeger(&m_l, idx); } else { param.v.f = (float)lua_tonumber(&m_l, idx); } return true; } if (lua_isstring(&m_l, idx)) { param.type = Variant::VT_STRING; param.v.s = lua_tostring(&m_l, idx); return true; } if (lua_islightuserdata(&m_l, idx)) { param.type = Variant::VT_USER; param.v.p = const_cast<void*>(lua_topointer(&m_l, idx)); return true; } if (lua_isuserdata(&m_l, idx)) { param.type = Variant::VT_USER; param.v.p = const_cast<void*>(lua_topointer(&m_l, idx)); return true; } param.type = Variant::VT_NONE; return false; } //--------------------------------------------------------------------------- bool ScriptHelper::setParam(int idx, Variant& param) { switch(param.type) { case Variant::VT_BOOL: lua_pushboolean(&m_l, param.v.b ? 1 : 0); break; case Variant::VT_INT: lua_pushinteger(&m_l, param.v.i); break; case Variant::VT_FLOAT: lua_pushnumber(&m_l, (lua_Number)param.v.f); break; case Variant::VT_STRING: lua_pushstring(&m_l, param.v.s); break; case Variant::VT_USER: lua_pushlightuserdata(&m_l, param.v.p); break; default: lua_pushnil(&m_l); break; } return true; } //--------------------------------------------------------------------------- LuaScriptVM* ScriptHelper::getCurrentVM() { // this is stored in the globals lua_getglobal(&m_l, "CURRENTVM"); return (LuaScriptVM*)lua_topointer(&m_l, lua_gettop(&m_l)); }
26.122137
79
0.612215
nbtdev
853cb0c82c9d3eb4a1b694ad305b755b203c3619
12,324
cpp
C++
source/main.cpp
HaikuArchives/WheresMyMouse
4baac8a8fe313f4251ec40f7235ca033a8be0b19
[ "BSD-3-Clause" ]
1
2017-09-09T17:47:16.000Z
2017-09-09T17:47:16.000Z
source/main.cpp
HaikuArchives/WheresMyMouse
4baac8a8fe313f4251ec40f7235ca033a8be0b19
[ "BSD-3-Clause" ]
10
2016-06-26T12:42:25.000Z
2017-02-19T10:02:58.000Z
source/main.cpp
HaikuArchives/WheresMyMouse
4baac8a8fe313f4251ec40f7235ca033a8be0b19
[ "BSD-3-Clause" ]
6
2016-06-26T08:11:12.000Z
2020-10-26T06:17:56.000Z
/* Copyright (c) 2002, Marcin 'Shard' Konicki 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. * Name "Marcin Konicki", "Shard" or any combination of them, must not be used to endorse or promote products derived from this software without specific prior written permission from Marcin Konicki. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------------- // // Include // //---------------------------------------------------------------------------- #include <Catalog.h> #include <LayoutBuilder.h> #include "main.h" //---------------------------------------------------------------------------- // // Main Functions // //---------------------------------------------------------------------------- //--------------------------------------------------- // Load settings to given settings struct //--------------------------------------------------- void LoadSettings( WMM_SETTINGS *settings) { BPath settings_file_path; if( find_directory( B_USER_SETTINGS_DIRECTORY, &settings_file_path) != B_OK) settings_file_path.SetTo( WMM_SETTINGS_FILE); else settings_file_path.Append( WMM_SETTINGS_FILE); FILE *file; if( (file = fopen( settings_file_path.Path(), "rb+"))) { if( !fread( settings, sizeof( WMM_SETTINGS), 1, file)) { // settings file was smaller, make default settings first and then load again // this prevents from older settings lost, when some new will be added SettingsToDefault( settings); fseek( file, 0, SEEK_SET); fread( settings, sizeof( WMM_SETTINGS), 1, file); fclose( file); // save modified settings SaveSettings( settings); // return since file is closed now return; } fclose( file); } else { SettingsToDefault( settings); SaveSettings( settings); } } //--------------------------------------------------- // Set given settings struct to defaults //--------------------------------------------------- void SettingsToDefault( WMM_SETTINGS *settings) { settings->radius = WMM_RADIUS_MIN; settings->circles = WMM_CIRCLES_COUNT; settings->lwidth = WMM_LINE_WIDTH; settings->lspace = WMM_LINE_SPACE; settings->pulse = WMM_PULSE_RATE; settings->color = WMM_COLOR; } //--------------------------------------------------- // Save settings from given settings struct //--------------------------------------------------- void SaveSettings( WMM_SETTINGS *settings) { BPath settings_file_path; if( find_directory( B_USER_SETTINGS_DIRECTORY, &settings_file_path) != B_OK) settings_file_path.SetTo( WMM_SETTINGS_FILE); else settings_file_path.Append( WMM_SETTINGS_FILE); FILE *file; if( (file = fopen( settings_file_path.Path(), "wb+"))) { fwrite( settings, sizeof( WMM_SETTINGS), 1, file); fclose( file); } } //--------------------------------------------------- // WMM main function //--------------------------------------------------- void usage() { printf("'Where is my Mouse' shows a short animation to easily locate the " "mouse pointer.\n" "Use the Shortcuts preferences to assign your preferred key combo.\n" "usage:\tWhereIsMyMouse [s|-s|--set]\n" "\ts, -s, --set\tShow the settings panel\n\n"); } int main(int argc, char** argv) { bool showSettingsPanel = false; if( argc > 1) { if (!strcmp(argv[1], "s") || !strcmp(argv[1], "-s") || !strcmp(argv[1], "--set")) showSettingsPanel = true; else { usage(); return B_ERROR; } } WMMApp* App = new WMMApp( showSettingsPanel); App->Run(); delete App; return B_NO_ERROR; } //---------------------------------------------------------------------------- // // Functions :: WMMApp // //---------------------------------------------------------------------------- //--------------------------------------------------- // Constructor //--------------------------------------------------- WMMApp::WMMApp(bool showSettingsPanel) : BApplication(WMM_SIGNATURE) { BWindow *window; if (showSettingsPanel) { window = new BWindow(BRect(200, 200, 200, 200), B_TRANSLATE_SYSTEM_NAME("Where's my Mouse settings?"), B_TITLED_WINDOW_LOOK, B_NORMAL_WINDOW_FEEL, B_AUTO_UPDATE_SIZE_LIMITS | B_NOT_ZOOMABLE | B_NOT_RESIZABLE | B_NOT_MINIMIZABLE | B_WILL_ACCEPT_FIRST_CLICK | B_QUIT_ON_WINDOW_CLOSE, B_ALL_WORKSPACES); window->SetLayout(new BGroupLayout(B_VERTICAL)); window->AddChild(new WMMSettingsView()); } else { window = new BWindow(BRect(0, 0, 0, 0), "Here it is!", B_NO_BORDER_WINDOW_LOOK, B_FLOATING_ALL_WINDOW_FEEL, B_NOT_MOVABLE | B_NOT_ZOOMABLE | B_NOT_RESIZABLE | B_NOT_MINIMIZABLE | B_WILL_ACCEPT_FIRST_CLICK | B_QUIT_ON_WINDOW_CLOSE, B_ALL_WORKSPACES); window->AddChild(new WMMView()); } window->Show(); } //--------------------------------------------------- // Destructor //--------------------------------------------------- WMMApp::~WMMApp() { } //---------------------------------------------------------------------------- // // Functions :: WMMView // //---------------------------------------------------------------------------- //--------------------------------------------------- // Constructor //--------------------------------------------------- WMMView::WMMView() : BView( BRect( 0, 0, 0, 0), "Circles, circles...", B_FOLLOW_ALL_SIDES, B_WILL_DRAW | B_PULSE_NEEDED | B_FULL_UPDATE_ON_RESIZE) { LoadSettings( &Settings); SetBlendingMode( B_PIXEL_ALPHA, B_ALPHA_OVERLAY); SetDrawingMode( B_OP_ALPHA); SetViewColor( B_TRANSPARENT_32_BIT); SetPenSize( Settings.lwidth); Settings.color.alpha = WMM_ALPHA_MIN; alphaMod = ( 255 - WMM_ALPHA_MIN) / Settings.circles; radiusMod = ( Settings.lwidth / 2) + Settings.lspace; } //--------------------------------------------------- // Destructor //--------------------------------------------------- WMMView::~WMMView() { } //--------------------------------------------------- // Draw gets mouse point //--------------------------------------------------- void WMMView::AttachedToWindow() { int32 size = (Settings.radius + ( Settings.circles * ( (Settings.lwidth / 2) + Settings.lspace))) * 2; Window()->ResizeTo( size, size); ResizeTo( size, size); uint32 buttons; GetMouse( &mousePoint, &buttons); size /= 2; Window()->MoveTo( mousePoint.x-size, mousePoint.y-size); ConvertFromScreen( &mousePoint); Window()->SetPulseRate( Settings.pulse * WMM_PULSE_MULTIPLIER); } //--------------------------------------------------- // On mouse down quit //--------------------------------------------------- void WMMView::MouseDown( BPoint where) { Window()->PostMessage( B_QUIT_REQUESTED); } //--------------------------------------------------- // Pulse - draw circles around mouse cursor //--------------------------------------------------- void WMMView::Pulse() { if( Settings.circles-- < 1) Window()->PostMessage( B_QUIT_REQUESTED); else { SetHighColor( Settings.color); StrokeEllipse( mousePoint, Settings.radius, Settings.radius); Settings.radius += radiusMod; Settings.color.alpha += alphaMod; } } //---------------------------------------------------------------------------- // // Functions :: WMMSettingsView // //---------------------------------------------------------------------------- #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "WMMSettingsView" //--------------------------------------------------- // Constructor //--------------------------------------------------- WMMSettingsView::WMMSettingsView() : BView("Maybe this, or that, or...", B_WILL_DRAW | B_FULL_UPDATE_ON_RESIZE) { SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR)); Icon = new BBitmap(BRect(0, 0, 31, 31), B_RGBA32); memcpy(Icon->Bits(), WMM_ICON_DATA, 32*32*4); fIconView = new StripeView(Icon); fAuthorView = new BStringView(NULL, "by Shard"); BFont font; fAuthorView->GetFont(&font); int size = (int) font.Size(); // round down font size fAuthorView->SetFontSize(size > 12 ? size * 2/3 : 8); fAuthorView->SetAlignment(B_ALIGN_RIGHT); fDemoView = new DemoView(size > 16 ? size * 25/8 : 50); // expand view height to maintain aspect ratio rgb_color color = ui_color(B_MENU_SELECTION_BACKGROUND_COLOR); // slidRadius = new SSlider("slidRadius", B_TRANSLATE("Radius at start"), new BMessage(WMM_MSG_SET_RADIUS), 16, 64); slidRadius->SetHashMarks(B_HASH_MARKS_BOTTOM); slidRadius->SetHashMarkCount(16); //slidRadius->SetLimitLabels("16", "64"); slidRadius->UseFillColor(true, &color); slidRadius->SetValue(fDemoView->radius()); // slidCircles = new SSlider("slidRadius", B_TRANSLATE("Number of circles"), new BMessage(WMM_MSG_SET_CIRCLES), 1, 15); slidCircles->SetHashMarks(B_HASH_MARKS_BOTTOM); slidCircles->SetHashMarkCount(15); slidCircles->UseFillColor(true, &color); slidCircles->SetValue(fDemoView->circles()); // slidLineWidth = new SSlider("slidRadius", B_TRANSLATE("Circle width"), new BMessage(WMM_MSG_SET_LWIDTH), 1, 32); slidLineWidth->SetHashMarks(B_HASH_MARKS_BOTTOM); slidLineWidth->SetHashMarkCount(16); slidLineWidth->UseFillColor(true, &color); slidLineWidth->SetValue(fDemoView->lwidth()); // slidLineSpace = new SSlider("slidRadius", B_TRANSLATE("Space between circles"), new BMessage(WMM_MSG_SET_LSPACE), 1, 32); slidLineSpace->SetHashMarks(B_HASH_MARKS_BOTTOM); slidLineSpace->SetHashMarkCount(16); slidLineSpace->UseFillColor(true, &color); slidLineSpace->SetValue(fDemoView->lspace()); // slidPulseRate = new SSlider("slidRadius", B_TRANSLATE("Animation speed"), new BMessage(WMM_MSG_SET_PULSE), 1, 5); slidPulseRate->SetHashMarks(B_HASH_MARKS_BOTTOM); slidPulseRate->SetHashMarkCount(5); slidPulseRate->UseFillColor(true, &color); slidPulseRate->SetValue(fDemoView->pulse()); BLayoutBuilder::Group<>(this, B_HORIZONTAL, 0) .Add(fIconView, 0) .AddGroup(B_VERTICAL, 0) .AddStrut(10) .Add(slidRadius) .Add(slidCircles) .Add(slidLineWidth) .Add(slidLineSpace) .Add(slidPulseRate) .AddStrut(10) .Add(fDemoView) .Add(fAuthorView) .AddStrut(10) .End() .AddStrut(10) .End(); } //--------------------------------------------------- // Destructor //--------------------------------------------------- WMMSettingsView::~WMMSettingsView() { fIconView->RemoveSelf(); delete fIconView; slidRadius->RemoveSelf(); delete slidRadius; slidCircles->RemoveSelf(); delete slidCircles; slidLineWidth->RemoveSelf(); delete slidLineWidth; slidLineSpace->RemoveSelf(); delete slidLineSpace; slidPulseRate->RemoveSelf(); delete slidPulseRate; fDemoView->RemoveSelf(); delete fDemoView; fAuthorView->RemoveSelf(); delete fAuthorView; delete Icon; } //--------------------------------------------------- // Attached to window - set siblings target //--------------------------------------------------- void WMMSettingsView::AttachedToWindow() { slidRadius->SetTarget(fDemoView); slidCircles->SetTarget(fDemoView); slidLineWidth->SetTarget(fDemoView); slidLineSpace->SetTarget(fDemoView); slidPulseRate->SetTarget(fDemoView); } //--------------------------------------------------- // Message handler //--------------------------------------------------- void WMMSettingsView::MessageReceived(BMessage *msg) { if (msg->what == 'PSTE') return; BView::MessageReceived(msg); }
31.6
754
0.596478
HaikuArchives
854d372ba261499e8dfb45ef9e3435b2e89056a9
529
hpp
C++
src/checkbox_delegate.hpp
degarashi/sprinkler
afc6301ae2c7185f514148100da63dcef94d7f00
[ "MIT" ]
null
null
null
src/checkbox_delegate.hpp
degarashi/sprinkler
afc6301ae2c7185f514148100da63dcef94d7f00
[ "MIT" ]
null
null
null
src/checkbox_delegate.hpp
degarashi/sprinkler
afc6301ae2c7185f514148100da63dcef94d7f00
[ "MIT" ]
null
null
null
#pragma once #include <QStyledItemDelegate> namespace dg { class ColumnTarget; class CheckBoxDelegate : public QStyledItemDelegate { Q_OBJECT private: const ColumnTarget* _column; public: CheckBoxDelegate(const ColumnTarget* column, QObject* parent=nullptr); void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) override; }; }
29.388889
133
0.778828
degarashi
85504cb2689ac2c38a99ac1d4797e591e1966394
353
cpp
C++
Uni/c++/programamzione-1/Esempi/Tutorato/Lezione2/Esercizio17.cpp
VenomBigBozz/Esercizi
44bcf62df162cfb5b924b291f9839fbe1b04dcba
[ "Unlicense" ]
null
null
null
Uni/c++/programamzione-1/Esempi/Tutorato/Lezione2/Esercizio17.cpp
VenomBigBozz/Esercizi
44bcf62df162cfb5b924b291f9839fbe1b04dcba
[ "Unlicense" ]
null
null
null
Uni/c++/programamzione-1/Esempi/Tutorato/Lezione2/Esercizio17.cpp
VenomBigBozz/Esercizi
44bcf62df162cfb5b924b291f9839fbe1b04dcba
[ "Unlicense" ]
null
null
null
#include <iostream> using namespace std; bool esercizio17(int **A, int n, int m, double w, double v) { for(int j = 0; j < m; j++) { double somma = 0; for(int i = 0; i < n; i++) { somma += A[i][j]; } somma /= n; if(somma >= w && somma <= v) return true; } return false; } int main() { }
18.578947
61
0.461756
VenomBigBozz
85505596d6838934b2f3760746179725a92a5abc
2,680
cpp
C++
SnapshotPrim.cpp
ScottyPotty1/Dolphin-7-VM-Releases
696039e4192d662ed81af034ab47fe4324422477
[ "MIT" ]
null
null
null
SnapshotPrim.cpp
ScottyPotty1/Dolphin-7-VM-Releases
696039e4192d662ed81af034ab47fe4324422477
[ "MIT" ]
null
null
null
SnapshotPrim.cpp
ScottyPotty1/Dolphin-7-VM-Releases
696039e4192d662ed81af034ab47fe4324422477
[ "MIT" ]
null
null
null
/****************************************************************************** File: SnapshotPrim.cpp Description: Implementation of the Interpreter class' snapshot/quit primitive methods ******************************************************************************/ #include "Ist.h" #ifndef _DEBUG #pragma optimize("s", on) #pragma auto_inline(off) #endif #if defined(TO_GO) #error To Go VMs should not be able to snapshot the image #endif #include "ObjMem.h" #include "Interprt.h" #include "InterprtPrim.inl" #include "InterprtProc.inl" // Smalltalk classes #include "STString.h" #pragma auto_inline(off) BOOL __fastcall Interpreter::primitiveSnapshot(CompiledMethod&, unsigned argCount) { Oop arg = stackValue(argCount - 1); char* szFileName; if (arg == Oop(Pointers.Nil)) szFileName = 0; else if (ObjectMemory::fetchClassOf(arg) == Pointers.ClassString) { StringOTE* oteString = reinterpret_cast<StringOTE*>(arg); String* fileName = oteString->m_location; szFileName = fileName->m_characters; } else return primitiveFailure(0); bool bBackup; if (argCount >= 2) bBackup = reinterpret_cast<OTE*>(stackValue(argCount - 2)) == Pointers.True; else bBackup = false; SMALLINTEGER nCompressionLevel; if (argCount >= 3) { Oop oopCompressionLevel = stackValue(argCount - 3); nCompressionLevel = ObjectMemoryIsIntegerObject(oopCompressionLevel) ? ObjectMemoryIntegerValueOf(oopCompressionLevel) : 0; } else nCompressionLevel = 0; SMALLUNSIGNED nMaxObjects = 0; if (argCount >= 4) { Oop oopMaxObjects = stackValue(argCount - 4); if (ObjectMemoryIsIntegerObject(oopMaxObjects)) { nMaxObjects = ObjectMemoryIntegerValueOf(oopMaxObjects); } } // N.B. It is not necessary to clear down the memory pools as the free list is rebuild on every image // load and the pool members, though not on the free list at present, are marked as free entries // in the object table // ZCT is reconciled, so objects may be deleted flushAtCaches(); // Store the active frame of the active process before saving so available on image reload // We're not actually suspending the process now, but it appears like that to the snapshotted // image on restarting m_registers.PrepareToSuspendProcess(); #ifdef OAD DWORD timeStart = timeGetTime(); #endif int saveResult = ObjectMemory::SaveImageFile(szFileName, bBackup, nCompressionLevel, nMaxObjects); #ifdef OAD DWORD timeEnd = timeGetTime(); TRACESTREAM << "Time to save image: " << (timeEnd - timeStart) << " mS" << endl; #endif if (!saveResult) { // Success popStack(); return primitiveSuccess(); } else { // Failure return primitiveFailure(saveResult); } }
25.283019
125
0.693284
ScottyPotty1
855a687422bf20eb254af6af8229182fd8e67566
803
cpp
C++
zhangjunyan2580-c++/day2/P2.cpp
joelfak/advent_of_code_2019
d5031078c53c181835b4bf86458b360542f0122e
[ "Apache-2.0" ]
9
2019-12-01T14:52:40.000Z
2020-12-16T14:24:19.000Z
zhangjunyan2580-c++/day2/P2.cpp
joelfak/advent_of_code_2019
d5031078c53c181835b4bf86458b360542f0122e
[ "Apache-2.0" ]
null
null
null
zhangjunyan2580-c++/day2/P2.cpp
joelfak/advent_of_code_2019
d5031078c53c181835b4bf86458b360542f0122e
[ "Apache-2.0" ]
51
2019-11-26T14:49:05.000Z
2021-12-01T20:53:41.000Z
#include <stdio.h> int read(){ int n=0; static char ch; while(ch!=EOF&&(ch<'0'||ch>'9'))ch=getchar(); if(ch==EOF)return -1; while(ch>='0'&&ch<='9')n=n*10+ch-'0',ch=getchar(); return n; } int values[10005],real[10005]; int main(){ freopen("Input.txt","r",stdin); int i=0; while((real[i++]=read())!=-1); for(int n=0;n<100;n++) for(int v=0;v<100;v++){ for(int k=0;k<i;k++) values[k]=real[k]; values[1]=n; values[2]=v; int j=0; while(values[j]!=99){ if(values[j]==1)values[values[j+3]]=values[values[j+2]]+values[values[j+1]]; else if(values[j]==2)values[values[j+3]]=values[values[j+2]]*values[values[j+1]]; else return -1; j+=4; } if(values[0]==19690720){ printf("%d%2d",n,v); return 0; } } return -1; }
22.942857
86
0.533001
joelfak
855a79605de8eba1cec296ee974f23e1c03859e5
1,135
cpp
C++
test/tprocess.cpp
drypot/san-2.x
44e626793b1dc50826ba0f276d5cc69b7c9ca923
[ "MIT" ]
5
2019-12-27T07:30:03.000Z
2020-10-13T01:08:55.000Z
test/tprocess.cpp
drypot/san-2.x
44e626793b1dc50826ba0f276d5cc69b7c9ca923
[ "MIT" ]
null
null
null
test/tprocess.cpp
drypot/san-2.x
44e626793b1dc50826ba0f276d5cc69b7c9ca923
[ "MIT" ]
1
2020-07-27T22:36:40.000Z
2020-07-27T22:36:40.000Z
/* 1994.05.05 12.17 1995.08.23 10.07 */ #include <pub\config.hpp> #include <pub\init.hpp> #include <pub\process.hpp> #include <stdio.h> void TestExit() { Exit(); } void TestAbort() { Abort(); } void TestLogMessageOverflow() { forever LogMessage ("Hello!\n"); } void IniterCallBack0() { puts ("Initer Test : priority 0"); } void IniterCallBackM10() { puts ("Initer Test : priority -10"); } void IniterCallBackP10() { puts ("Initer Test : priority +10"); } Initer initer1(IniterCallBack0); Initer initer2(IniterCallBackM10,-10); Initer initer3(IniterCallBackP10,+10); void Main() { int n; ErrorMessage ("\nErrorMessage Test : %d %s\n", 123, "Two"); LogMessage ("\nLogMessage Test :%d %s in Main\n", 123, "STRING"); puts ("1. Exit"); puts ("2. Abort"); puts ("3. Test LogMessage Overflow"); scanf ("%d",&n); switch (n) { case 1 : TestExit(); break; case 2 : TestAbort(); break; case 3: TestLogMessageOverflow(); break; } }
15.337838
69
0.548018
drypot
855c50ff92e60dc79cab3ac4530912887a0a552d
416
cpp
C++
src/assets/image_asset.cpp
e-bondarev/AstrumEngine
cd4ceb702a4148d765d729267d695940a9d8c0bc
[ "MIT" ]
1
2021-04-27T10:34:46.000Z
2021-04-27T10:34:46.000Z
src/assets/image_asset.cpp
e-bondarev/AstrumEngine
cd4ceb702a4148d765d729267d695940a9d8c0bc
[ "MIT" ]
null
null
null
src/assets/image_asset.cpp
e-bondarev/AstrumEngine
cd4ceb702a4148d765d729267d695940a9d8c0bc
[ "MIT" ]
null
null
null
#include "pch.h" #include "image_asset.h" #include "stb_image/stb_image.h" void ImageAsset::Load(const std::string& path) { int width, height; Data = stbi_load((ASTRUM_ROOT + path).c_str(), &width, &height, &Channels, 0); Size = { static_cast<float>(width), static_cast<float>(height) }; } ImageAsset::ImageAsset(const std::string& path) { Load(path); } ImageAsset::~ImageAsset() { stbi_image_free(Data); }
18.909091
79
0.699519
e-bondarev
855e5da4e85972b06f419622c5f282afc05b80b7
2,738
cpp
C++
src/system/core/libcutils/socket_local_server_unix.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
5
2020-12-19T06:56:06.000Z
2022-01-09T01:28:42.000Z
src/system/core/libcutils/socket_local_server_unix.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
1
2021-09-27T06:00:40.000Z
2021-09-27T06:00:40.000Z
src/system/core/libcutils/socket_local_server_unix.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
3
2020-12-19T06:56:27.000Z
2021-09-26T18:50:44.000Z
/* libs/cutils/socket_local_server.c ** ** Copyright 2006, The Android Open Source Project ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ #include <cutils/sockets.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <stddef.h> #if defined(_WIN32) int socket_local_server(const char *name, int namespaceId, int type) { errno = ENOSYS; return -1; } #else /* !_WIN32 */ #include <sys/socket.h> #include <sys/un.h> #include <sys/select.h> #include <sys/types.h> #include <netinet/in.h> #include "socket_local_unix.h" #define LISTEN_BACKLOG 4 /* Only the bottom bits are really the socket type; there are flags too. */ #define SOCK_TYPE_MASK 0xf /** * Binds a pre-created socket(AF_LOCAL) 's' to 'name' * returns 's' on success, -1 on fail * * Does not call listen() */ int socket_local_server_bind(int s, const char *name, int namespaceId) { struct sockaddr_un addr; socklen_t alen; int n; int err; err = socket_make_sockaddr_un(name, namespaceId, &addr, &alen); if (err < 0) { return -1; } /* basically: if this is a filesystem path, unlink first */ #if !defined(__linux__) if (1) { #else if (namespaceId == ANDROID_SOCKET_NAMESPACE_RESERVED || namespaceId == ANDROID_SOCKET_NAMESPACE_FILESYSTEM) { #endif /*ignore ENOENT*/ unlink(addr.sun_path); } n = 1; setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)); if(bind(s, (struct sockaddr *) &addr, alen) < 0) { return -1; } return s; } /** Open a server-side UNIX domain datagram socket in the Linux non-filesystem * namespace * * Returns fd on success, -1 on fail */ int socket_local_server(const char *name, int namespaceId, int type) { int err; int s; s = socket(AF_LOCAL, type, 0); if (s < 0) return -1; err = socket_local_server_bind(s, name, namespaceId); if (err < 0) { close(s); return -1; } if ((type & SOCK_TYPE_MASK) == SOCK_STREAM) { int ret; ret = listen(s, LISTEN_BACKLOG); if (ret < 0) { close(s); return -1; } } return s; } #endif /* !_WIN32 */
21.559055
79
0.641344
dAck2cC2
855fbf0008119e14180c8828f5067996a63853d5
2,654
cpp
C++
engine-base/GameManager.cpp
geoffwhitehead/snooker-game
54c607bbfc31cfe2f6adbec488f408a6d49f1d8d
[ "MIT" ]
null
null
null
engine-base/GameManager.cpp
geoffwhitehead/snooker-game
54c607bbfc31cfe2f6adbec488f408a6d49f1d8d
[ "MIT" ]
null
null
null
engine-base/GameManager.cpp
geoffwhitehead/snooker-game
54c607bbfc31cfe2f6adbec488f408a6d49f1d8d
[ "MIT" ]
null
null
null
#include "GameManager.h" GameManager::GameManager(float w_x, float w_y) : window(Window(w_x, w_y)), renderer(Renderer(window)){ } GameManager::~GameManager(){ } //for (vector<GLuint>::iterator tex = textures.begin(); tex != textures.end(); ++tex) //delete (*tex); void GameManager::addEntity(Entity* e){ entities.push_back(e); } void GameManager::addSystemManager(SystemManager* sm) { system_managers.push_back(sm); } Window* GameManager::getWindow() { return &window; } vector<Entity*>* GameManager::getEntities() { return &entities; } Entity* GameManager::getEntityByName(string name_to_find, string parent_name) { if (parent_name == "") { for (int i = 0; i < entities.size(); i++) { if (entities[i]->name == name_to_find) { return entities[i]; } } } else { for (int i = 0; i < entities.size(); i++) { if (entities[i]->name == parent_name) { for (int j = 0; j < entities[i]->getChildren().size(); j++) { if (entities[i]->getChildren()[j]->name == name_to_find) { return entities[i]->getChildren()[j]; } } } } } return nullptr; } void GameManager::run(){ for (vector<SystemManager*>::iterator system = system_managers.begin(); system != system_managers.end(); ++system) (*system)->init(); while (window.UpdateWindow()){ float msec = window.GetTimer()->GetTimedMS(); msec *= 2.0f; for (vector<SystemManager*>::iterator system = system_managers.begin(); system != system_managers.end(); ++system) (*system)->update(msec); for (vector<Entity*>::iterator entity = entities.begin(); entity != entities.end(); ++entity) { (*entity)->update(msec); } renderer.ClearBuffers(); for (vector<Entity*>::iterator entity = entities.begin(); entity != entities.end(); ++entity) { (*entity)->render(&renderer); } renderer.SwapBuffers(); } for (vector<SystemManager*>::iterator system = system_managers.begin(); system != system_managers.end(); ++system) (*system)->destroy(); } GLuint GameManager::LoadTexture(const char* filename, bool textureRepeating){ GLuint texture = SOIL_load_OGL_texture(filename, SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_NTSC_SAFE_RGB | SOIL_FLAG_MULTIPLY_ALPHA ); if (texture == NULL){ printf("[Texture loader] \"%s\" failed to load!\n", filename); return 0; } else { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, textureRepeating ? GL_REPEAT : GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, textureRepeating ? GL_REPEAT : GL_CLAMP); glActiveTexture(0); textures.push_back(texture); return texture; } }
25.519231
116
0.678975
geoffwhitehead
8564b9423df92e244a2dfc57a5da94e76024fcae
638
cpp
C++
TrackerGrupo02/src/Events/LogoutZone.cpp
Sounagix/UsabilidadTelemetria
7f88ac2ed9912bb69fa3bda27620e6c2271c61fd
[ "MIT" ]
null
null
null
TrackerGrupo02/src/Events/LogoutZone.cpp
Sounagix/UsabilidadTelemetria
7f88ac2ed9912bb69fa3bda27620e6c2271c61fd
[ "MIT" ]
null
null
null
TrackerGrupo02/src/Events/LogoutZone.cpp
Sounagix/UsabilidadTelemetria
7f88ac2ed9912bb69fa3bda27620e6c2271c61fd
[ "MIT" ]
null
null
null
#include "LogoutZone.h" #include "jute.h" std::string LogoutZone::toJson() { TrackerEvent::commonJson(); jute::jValue num(jute::jType::JNUMBER); num.set_string(std::to_string((int)_zone)); mainJson.add_property("zone", num); jute::jValue aux(jute::jType::JNUMBER); aux.set_string(std::to_string((int)_next)); mainJson.add_property("next", aux); return mainJson.to_string(); } LogoutZone::LogoutZone() : TrackerEvent() { } void LogoutZone::setZone(int zone) { _zone = zone; } void LogoutZone::setNext(int next) { _next = next; } int LogoutZone::getZone() { return _zone; } int LogoutZone::getNext() { return _next; }
15.190476
44
0.69906
Sounagix
85727d3f738acd1ea5fe1d3cfe515e0ef4fd1898
977
cpp
C++
Algorithms_Badge/Birthday Cake Candles/BirthdayCakeCandles/BirthdayCakeCandles/main.cpp
Muhand/HackerRank
c93dc19f4339440f0f23d8d6a0e3fafd15e34a8f
[ "MIT" ]
null
null
null
Algorithms_Badge/Birthday Cake Candles/BirthdayCakeCandles/BirthdayCakeCandles/main.cpp
Muhand/HackerRank
c93dc19f4339440f0f23d8d6a0e3fafd15e34a8f
[ "MIT" ]
null
null
null
Algorithms_Badge/Birthday Cake Candles/BirthdayCakeCandles/BirthdayCakeCandles/main.cpp
Muhand/HackerRank
c93dc19f4339440f0f23d8d6a0e3fafd15e34a8f
[ "MIT" ]
null
null
null
#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <string> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <climits> #include <cstring> #include <cstdlib> #include <fstream> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> #include <unordered_map> using namespace std; int main() { int n; map<int, int> largest; cin >> n; vector<int> height(n); for (int height_i = 0; height_i < n; height_i++) { int t; cin >> t; height[height_i] = t; if (largest[t] == false) { largest[t] = 1; //cout << "notfound" << endl; } else { int inc = largest[t]; inc++; largest[t] = inc; } } int lar = -1; for (auto const &ent1 : largest) { //cout << "Key: " << ent1.first << "\t\tValue: " << ent1.second << endl; if (ent1.second > lar) lar = ent1.second; } cout << lar << endl; return 0; }
16.283333
74
0.609007
Muhand
85738b621da825b6ae9ffd9eb6782780a7447534
698
cpp
C++
dev/overcutted_2.0/Source.cpp
DrAntoine/over-cutted
d14ed1aea3ca6cd3a36ecc6e2dc96e44afccab25
[ "MIT" ]
1
2021-05-18T09:26:35.000Z
2021-05-18T09:26:35.000Z
dev/overcutted_2.0/Source.cpp
DrAntoine/over-cutted
d14ed1aea3ca6cd3a36ecc6e2dc96e44afccab25
[ "MIT" ]
16
2021-04-16T12:20:04.000Z
2021-05-17T18:35:00.000Z
dev/overcutted_2.0/Source.cpp
DrAntoine/over-cutted
d14ed1aea3ca6cd3a36ecc6e2dc96e44afccab25
[ "MIT" ]
null
null
null
#include <SFML/Graphics.hpp> #include"Perso.h" #include"Map.h" #include "Event.h" int main() { sf::RenderWindow window(sf::VideoMode(800, 800), "SFML works!"); Perso player("textures/sprite_player_1.png"); Map carte; Event test; window.setFramerateLimit(60); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } player.move(); test.poisson(); window.clear(sf::Color::White); carte.dessinMap(&window), window.draw(player.GetSprite()); window.display(); } return 0; }
20.529412
68
0.557307
DrAntoine
8576be24f3b23e3513fbf7c4b872d337956605d5
919
hpp
C++
src/libs/level0/guishell/cppinclude/guishell/guishell.hpp
DeanoC/wyrd
50508dbe2427f1bd72a0ed03d7c7963cb74b37a7
[ "MIT" ]
null
null
null
src/libs/level0/guishell/cppinclude/guishell/guishell.hpp
DeanoC/wyrd
50508dbe2427f1bd72a0ed03d7c7963cb74b37a7
[ "MIT" ]
null
null
null
src/libs/level0/guishell/cppinclude/guishell/guishell.hpp
DeanoC/wyrd
50508dbe2427f1bd72a0ed03d7c7963cb74b37a7
[ "MIT" ]
null
null
null
#pragma once #ifndef WYRD_GUISHELL_GUISHELL_HPP #define WYRD_GUISHELL_GUISHELL_HPP #include "core/core.h" #include "guishell/guishell.h" #include "guishell/window.hpp" // Init, Load, Unload, Update, Draw and Exit and InitialWindow must be defined // as static function in the users app class #define DECLARE_APP(type) static type theApp; \ DEFINE_APPLICATION_MAIN \ EXTERN_C void GuiShell_AppConfig(GuiShell_Functions* functions, GuiShell_WindowDesc* initialWindow) { \ functions->init = &theApp.Init; \ functions->load = &theApp.Load; \ functions->unload = &theApp.Unload; \ functions->update = &theApp.Update; \ functions->draw = &theApp.Draw; \ functions->exit = &theApp.Exit; \ memcpy(initialWindow, theApp.InitialWindow(), sizeof(GuiShell_WindowDesc)); \ } namespace GuiShell { inline void Terminate() { GuiShell_Terminate(); } } // end namespace GuiShell #endif //WYRD_GUISHELL_GUISHELL_HPP
28.71875
103
0.756257
DeanoC
857ce3e0e533e1eaeee220888edf7450d4a2fa27
4,198
cpp
C++
practica4/menu.cpp
MrcRjs/OpenGl101
52dc2fdb28a3551bd4a789d63eaad31be99ae2c2
[ "MIT" ]
1
2021-11-17T07:26:30.000Z
2021-11-17T07:26:30.000Z
practica4/menu.cpp
MrcRjs/OpenGl101
52dc2fdb28a3551bd4a789d63eaad31be99ae2c2
[ "MIT" ]
null
null
null
practica4/menu.cpp
MrcRjs/OpenGl101
52dc2fdb28a3551bd4a789d63eaad31be99ae2c2
[ "MIT" ]
null
null
null
// Marco Antonio Rojas Arriaga #ifdef __APPLE__ #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/glut.h> #else #include <GL/glut.h> #endif int sky = 0; int fig1 = 2; int fig2 = 4; int fig3 = 6; typedef enum { FONDO0, FONDO1, COLOR2, COLOR3, COLOR4, COLOR5, COLOR6, COLOR7 } opcionesMenu; float colores[8][3] = { {1.00f, 1.00f, 1.00f}, // 0 - blanco {0.00f, 0.00f, 0.00f}, // 1 - negro {1.00f, 0.00f, 0.00f}, // 2 - rojo {0.50f, 0.26f, 0.12f}, // 3 - rojo claro {0.00f, 1.00f, 0.00f}, // 4 - verde {0.06f, 0.25f, 0.13f}, // 5 - verde oscuro {0.00f, 0.00f, 1.00f}, // 6 - azul {0.85f, 0.95f, 1.00f}, // 7 - azul claro }; void init(void) { glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0f, 640.0f, 0.0f, 480.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void miCuadrado(); void display(void) { glClearColor(colores[sky][0], colores[sky][1], colores[sky][2], 0.0); glClear(GL_COLOR_BUFFER_BIT); // Limpia la pantalla glPushMatrix(); glTranslatef(100.0f, 100.0f, 0.0f); glColor3f(1.0f, 1.0f, 0.0f); miCuadrado(); glPopMatrix(); glPushMatrix(); glTranslatef(100.0f, 400.0f, 0.0f); glColor3f(colores[fig1][0], colores[fig1][1], colores[fig1][2]); miCuadrado(); glPopMatrix(); glPushMatrix(); glTranslatef(400.0f, 400.0f, 0.0f); glScalef(1.5f, 1.5f, 1.0f); glColor3f(colores[fig2][0], colores[fig2][1], colores[fig2][2]); miCuadrado(); glPopMatrix(); glPushMatrix(); glTranslatef(400.0f, 100.0f, 0.0f); glRotatef(45.0f, 0.0f, 0.0f, 1.0f); glColor3f(colores[fig3][0], colores[fig3][1], colores[fig3][2]); miCuadrado(); glPopMatrix(); glFlush(); // Envía toda la salida a la pantalla } void miCuadrado() { glBegin(GL_POLYGON); glVertex2f(-50.0f, -50.0f); glVertex2f(50.0f, -50.0f); glVertex2f(50.0f, 50.f); glVertex2f(-50.0f, 50.0f); glEnd(); } // posición de matriz de color void onMenu(int opcion) { switch (opcion) { case FONDO0: sky = 0; break; case FONDO1: sky = 1; break; case COLOR2: fig1 = 2; break; case COLOR3: fig1 = 3; break; case COLOR4: fig2 = 4; break; case COLOR5: fig2 = 5; break; case COLOR6: fig3 = 7; break; case COLOR7: fig3 = 6; break; break; } glutPostRedisplay(); } // creacion de menu y submenus void creacionMenu(void) { int menuSky, menuFig, menuMain; menuFig = glutCreateMenu(onMenu); glutAddMenuEntry("ROJO -> claro", COLOR2); glutAddMenuEntry("ROJO -> oscuro", COLOR3); glutAddMenuEntry("VERDE -> claro", COLOR4); glutAddMenuEntry("VERDE -> oscuro", COLOR5); glutAddMenuEntry("AZUL -> claro", COLOR6); glutAddMenuEntry("AZUL -> oscuro", COLOR7); menuSky = glutCreateMenu(onMenu); glutAddMenuEntry("Blanco", FONDO0); glutAddMenuEntry("Negro", FONDO1); menuMain = glutCreateMenu(onMenu); glutAddSubMenu("Color de Fondo", menuSky); glutAddSubMenu("Color de Figuras", menuFig); glutAttachMenu(GLUT_RIGHT_BUTTON); } void reshape(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0f, 640.0f, 0.0f, 480.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } int main(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 150); glutCreateWindow("Manejo de Menús y Sub-menús GLUT"); init(); creacionMenu(); glutDisplayFunc(display); glutReshapeFunc(reshape); glutMainLoop(); }
23.717514
74
0.54526
MrcRjs
3ff294ac10314e9e94a5d8282c8c765b307b9f78
42,327
cp
C++
gpcp/CPascalErrors.cp
imt-ag/gpcp
1c3de23993e0979d672f1c8fe7f193d0de22991a
[ "BSD-3-Clause" ]
32
2017-08-15T11:49:34.000Z
2021-12-24T13:10:29.000Z
gpcp/CPascalErrors.cp
imt-ag/gpcp
1c3de23993e0979d672f1c8fe7f193d0de22991a
[ "BSD-3-Clause" ]
14
2017-10-14T16:44:02.000Z
2022-03-09T08:17:56.000Z
gpcp/CPascalErrors.cp
imt-ag/gpcp
1c3de23993e0979d672f1c8fe7f193d0de22991a
[ "BSD-3-Clause" ]
7
2017-11-10T14:55:30.000Z
2022-02-07T01:23:22.000Z
(* ==================================================================== *) (* *) (* Error Module for the Gardens Point Component Pascal Compiler. *) (* Copyright (c) John Gough 1999, 2000. *) (* *) (* ==================================================================== *) MODULE CPascalErrors; IMPORT RTS, GPCPcopyright, GPTextFiles, Console, FileNames, Scnr := CPascalS, LitValue, GPText; (* ============================================================ *) CONST consoleWidth = 80; listingWidth = 128; listingMax = listingWidth-1; TYPE ParseHandler* = POINTER TO RECORD (Scnr.ErrorHandler) END; SemanticHdlr* = POINTER TO RECORD (Scnr.ErrorHandler) END; TYPE Message = LitValue.CharOpen; Err = POINTER TO ErrDesc; ErrDesc = RECORD num, lin, col: INTEGER; msg: Message; END; ErrBuff = POINTER TO ARRAY OF Err; VAR parsHdlr : ParseHandler; semaHdlr : SemanticHdlr; eBuffer : ErrBuff; (* Invariant: eBuffer[eTide] = NIL *) eLimit : INTEGER; (* High index of dynamic array. *) eTide : INTEGER; (* Next index for insertion in buf *) prompt* : BOOLEAN; (* Emit error message immediately *) nowarn* : BOOLEAN; (* Don't store warning messages *) no239Err*: BOOLEAN; (* Don't emit 239 while TRUE *) srcNam : FileNames.NameString; forVisualStudio* : BOOLEAN; xmlErrors* : BOOLEAN; (* ============================================================ *) PROCEDURE StoreError (eNum, linN, colN : INTEGER; mesg: Message); (* Store an error message for later printing *) VAR nextErr: Err; (* -------------------------------------- *) PROCEDURE append(b : ErrBuff; n : Err) : ErrBuff; VAR s : ErrBuff; i : INTEGER; BEGIN IF eTide = eLimit THEN (* must expand *) s := b; eLimit := eLimit * 2 + 1; NEW(b, eLimit+1); FOR i := 0 TO eTide DO b[i] := s[i] END; END; b[eTide] := n; INC(eTide); b[eTide] := NIL; RETURN b; END append; (* -------------------------------------- *) BEGIN NEW(nextErr); nextErr.num := eNum; nextErr.msg := mesg; nextErr.col := colN; nextErr.lin := linN; eBuffer := append(eBuffer, nextErr); END StoreError; (* ============================================================ *) PROCEDURE QuickSort(min, max : INTEGER); VAR i,j : INTEGER; key : INTEGER; tmp : Err; (* ------------------------------------------------- *) PROCEDURE keyVal(i : INTEGER) : INTEGER; BEGIN IF (eBuffer[i].col <= 0) OR (eBuffer[i].col >= listingWidth) THEN eBuffer[i].col := listingMax; END; RETURN eBuffer[i].lin * 256 + eBuffer[i].col; END keyVal; (* ------------------------------------------------- *) BEGIN i := min; j := max; key := keyVal((min+max) DIV 2); REPEAT WHILE keyVal(i) < key DO INC(i) END; WHILE keyVal(j) > key DO DEC(j) END; IF i <= j THEN tmp := eBuffer[i]; eBuffer[i] := eBuffer[j]; eBuffer[j] := tmp; INC(i); DEC(j); END; UNTIL i > j; IF min < j THEN QuickSort(min,j) END; IF i < max THEN QuickSort(i,max) END; END QuickSort; (* ============================================================ *) PROCEDURE (h : ParseHandler)Report*(num,lin,col : INTEGER); VAR str : ARRAY 128 OF CHAR; msg : Message; idx : INTEGER; len : INTEGER; BEGIN CASE num OF | 0: str := "EOF expected"; | 1: str := "ident expected"; | 2: str := "integer expected"; | 3: str := "real expected"; | 4: str := "CharConstant expected"; | 5: str := "string expected"; | 6: str := "'*' expected"; | 7: str := "'-' expected"; | 8: str := "'!' expected"; | 9: str := "'.' expected"; | 10: str := "'=' expected"; | 11: str := "'ARRAY' expected"; | 12: str := "',' expected"; | 13: str := "'OF' expected"; | 14: str := "'ABSTRACT' expected"; | 15: str := "'EXTENSIBLE' expected"; | 16: str := "'LIMITED' expected"; | 17: str := "'RECORD' expected"; | 18: str := "'(' expected"; | 19: str := "'+' expected"; | 20: str := "')' expected"; | 21: str := "'END' expected"; | 22: str := "';' expected"; | 23: str := "':' expected"; | 24: str := "'POINTER' expected"; | 25: str := "'TO' expected"; | 26: str := "'PROCEDURE' expected"; | 27: str := "'[' expected"; | 28: str := "']' expected"; | 29: str := "'^' expected"; | 30: str := "'$' expected"; | 31: str := "'#' expected"; | 32: str := "'<' expected"; | 33: str := "'<=' expected"; | 34: str := "'>' expected"; | 35: str := "'>=' expected"; | 36: str := "'IN' expected"; | 37: str := "'IS' expected"; | 38: str := "'OR' expected"; | 39: str := "'/' expected"; | 40: str := "'DIV' expected"; | 41: str := "'MOD' expected"; | 42: str := "'&' expected"; | 43: str := "'NIL' expected"; | 44: str := "'~' expected"; | 45: str := "'{' expected"; | 46: str := "'}' expected"; | 47: str := "'..' expected"; | 48: str := "'EXIT' expected"; | 49: str := "'RETURN' expected"; | 50: str := "'NEW' expected"; | 51: str := "':=' expected"; | 52: str := "'IF' expected"; | 53: str := "'THEN' expected"; | 54: str := "'ELSIF' expected"; | 55: str := "'ELSE' expected"; | 56: str := "'CASE' expected"; | 57: str := "'|' expected"; | 58: str := "'WHILE' expected"; | 59: str := "'DO' expected"; | 60: str := "'REPEAT' expected"; | 61: str := "'UNTIL' expected"; | 62: str := "'FOR' expected"; | 63: str := "'BY' expected"; | 64: str := "'LOOP' expected"; | 65: str := "'WITH' expected"; | 66: str := "'EMPTY' expected"; | 67: str := "'BEGIN' expected"; | 68: str := "'CONST' expected"; | 69: str := "'TYPE' expected"; | 70: str := "'VAR' expected"; | 71: str := "'OUT' expected"; | 72: str := "'IMPORT' expected"; | 73: str := "'MODULE' expected"; | 74: str := "'CLOSE' expected"; | 75: str := "'JAVACLASS' expected"; | 76: str := "not expected"; | 77: str := "error in OtherAtts"; | 78: str := "error in MethAttributes"; | 79: str := "error in ProcedureStuff"; | 80: str := "this symbol not expected in StatementSequence"; | 81: str := "this symbol not expected in StatementSequence"; | 82: str := "error in IdentStatement"; | 83: str := "error in MulOperator"; | 84: str := "error in Factor"; | 85: str := "error in AddOperator"; | 86: str := "error in Relation"; | 87: str := "error in OptAttr"; | 88: str := "error in ProcedureType"; | 89: str := "error in Type"; | 90: str := "error in Module"; | 91: str := "invalid lexical token"; END; len := LEN(str$); NEW(msg, len+1); FOR idx := 0 TO len-1 DO msg[idx] := str[idx]; END; msg[len] := 0X; StoreError(num,lin,col,msg); INC(Scnr.errors); END Report; (* ============================================================ *) PROCEDURE (h : ParseHandler)RepSt1*(num : INTEGER; IN s1 : ARRAY OF CHAR; lin,col : INTEGER),EMPTY; PROCEDURE (h : ParseHandler)RepSt2*(num : INTEGER; IN s1,s2 : ARRAY OF CHAR; lin,col : INTEGER),EMPTY; (* ============================================================ *) PROCEDURE (h : SemanticHdlr)Report*(num,lin,col : INTEGER); VAR str : ARRAY 128 OF CHAR; msg : Message; idx : INTEGER; len : INTEGER; BEGIN CASE num OF (* ======================= ERRORS ========================= *) | -1: str := "invalid character"; | 0: RETURN; (* just a placeholder *) | 1: str := "Name after 'END' does not match"; | 2: str := "Identifier not known in this scope"; | 3: str := "Identifier not known in qualified scope"; | 4: str := "This name already known in this scope"; | 5: str := "This identifier is not a type name"; | 6: str := "This fieldname clashes with previous fieldname"; | 7: str := "Qualified identifier is not a type name"; | 8: str := "Not a record type, so you cannot select a field"; | 9: str := "Identifier is not a fieldname of the current type"; | 10: str := "Not an array type, so you cannot index into it"; | 11: str := "Too many indices for the dimension of the array"; | 12: str := "Not a pointer type, so you cannot dereference it"; | 13: str := "Not a procedure call or type guard"; | 14: str := "Basetype is not record or pointer type"; | 15: str := "Typename not a subtype of the current type"; | 16: str := "Basetype was not declared ABSTRACT or EXTENSIBLE"; | 17: str := "Not dynamically typed, so you cannot have type-guard"; | 18: str := "The type-guard must be a record type here"; | 19: str := "This constant token not known"; | 20: str := "Name of formal is not unique"; | 21: str := "Actual parameter is not compatible with formal type"; | 22: str := "Too few actual parameters"; | 23: str := "Too many actual parameters"; | 24: str := "Attempt to use a proper procedure when function needed"; | 25: str := "Expression is not constant"; | 26: str := "Range of the numerical type exceeded"; | 27: str := "String literal too long for destination type"; | 28: str := "Low value of range not in SET base-type range"; | 29: str := "High value of range not in SET base-type range"; | 30: str := "Low value of range cannot be greater than high value"; | 31: str := "Array index not of an integer type"; | 32: str := "Literal array index is outside array bounds"; | 33: str := "Literal value is not in SET base-type range"; | 34: str := "Typename is not a subtype of the type of destination"; | 35: str := "Expression is not of SET type"; | 36: str := "Expression is not of BOOLEAN type"; | 37: str := "Expression is not of an integer type"; | 38: str := "Expression is not of a numeric type"; | 39: str := "Overflow of negation of literal value"; | 40: str := "Expression is not of ARRAY type"; | 41: str := "Expression is not of character array type"; | 42: str := "Expression is not a standard function"; | 43: str := "Expression is not of character type"; | 44: str := "Literal expression is not in CHAR range"; | 45: str := "Expression is not of REAL type"; | 46: str := "Optional param of LEN must be a positive integer constant"; | 47: str := "LONG cannot be applied to this type"; | 48: str := "Name is not the name of a basic type"; | 49: str := "MAX and MIN not applicable to this type"; | 50: str := "ORD only applies to SET and CHAR types"; | 51: str := "SHORT cannot be applied to this type"; | 52: str := "Both operands must be numeric, SET or CHAR types"; | 53: str := "Character constant outside CHAR range"; | 54: str := "Bad conversion type"; | 55: str := "Numeric overflow in constant evaluation"; | 56: str := "BITS only applies to expressions of type INTEGER"; | 57: str := "Operands in '=' or '#' test are not type compatible"; | 58: str := "EXIT is only permitted inside a LOOP"; | 59: str := "BY expression must be a constant expression"; | 60: str := "Case label is not an integer or character constant"; | 61: str := "Method attributes don't apply to ordinary procedure"; | 62: str := "Forward type-bound method elaborated as static procedure"; | 63: str := "Forward static procedure elaborated as type-bound method"; | 64: str := "Forward method had different receiver mode"; | 65: str := "Forward procedure had non-matching formal types"; | 66: str := "Forward method had different attributes"; | 67: str := "Variable cannot have open array type"; | 68: str := "Arrays must have at least one element"; | 69: str := "Fixed array cannot have open array element type"; | 70: str := "Forward procedure had different names for formals"; | 71: str := "This imported type is LIMITED, and cannot be instantiated"; | 72: str := "Forward procedure was not elaborated by end of block"; | 73: str := "RETURN is not legal in a module body"; | 74: str := "This is a proper procedure, it cannot return a value"; | 75: str := "This is a function, it must return a value"; | 76: str := "RETURN value not assign-compatible with function type"; | 77: str := "Actual for VAR formal must be a writeable variable"; | 78: str := "Functions cannot return record types"; | 79: str := "Functions cannot return array types"; | 80: str := "This designator is not the name of a proper procedure"; | 81: str := "FOR loops cannot have zero step size"; | 82: str := "This fieldname clashes with an inherited fieldname"; | 83: str := "Expression not assign-compatible with destination"; | 84: str := "FOR loop control variable must be of integer type"; | 85: str := "Identifier is not the name of a variable"; | 86: str := "Typename is not an extension of the variable type"; | 87: str := "The selected identifier is not of dynamic type"; | 88: str := "Case select expression is not of integer or CHAR type"; | 89: str := "Case select value is duplicated for this statement"; | 90: str := "Variables of ABSTRACT type cannot be instantiated"; | 91: str := "Optional param of ASSERT must be an integer constant"; | 92: str := "This is not a standard procedure"; | 93: str := "The param of HALT must be a constant integer"; | 94: str := "This variable is not of pointer or vector type"; | 95: str := "NEW requires a length param for open arrays and vectors"; | 96: str := "NEW only applies to pointers to records and arrays"; | 97: str := "This call of NEW has too many lengths specified"; | 98: str := "Length for an open array NEW must be an integer type"; | 99: str := "Length only applies to open arrays and vectors"; | 100: str := "This call of NEW needs more length params"; | 101: str := "Numeric literal is too large, even for long type"; | 102: str := "Only ABSTRACT basetypes can have abstract extensions"; | 103: str := "This expression is read-only"; | 104: str := "Receiver type must be a record, or pointer to record"; | 105: str := "This method is not a redefinition, you must use NEW"; | 106: str := "This method is a redefinition, you must not use NEW"; | 107: str := "Receivers of record type must be VAR or IN mode"; | 108: str := "Final method cannot be redefined"; | 109: str := "Only ABSTRACT method can have ABSTRACT redefinition"; | 110: str := "This type has ABSTRACT method, must be ABSTRACT"; | 111: str := "Type has NEW,EMPTY method, must be ABSTRACT or EXTENSIBLE"; | 112: str := "Only EMPTY or ABSTRACT method can be redefined EMPTY"; | 113: str := "This redefinition of exported method must be exported"; | 114: str := "This is an EMPTY method, and cannot have OUT parameters"; | 115: str := "This is an EMPTY method, and cannot return a value"; | 116: str := "Redefined method must have consistent return type"; | 117: str := "Type has EXTENSIBLE method, must be ABSTRACT or EXTENSIBLE"; | 118: str := "Empty or abstract methods cannot be called by super-call"; | 119: str := "Super-call is invalid here"; | 120: str := "There is no overridden method with this name"; | 121: str := "Not all abstract methods were implemented"; | 122: str := "This procedure is not at module scope, cannot be a method"; | 123: str := "There is a cycle in the base-type declarations"; | 124: str := "There is a cycle in the field-type declarations"; | 125: str := "Cycle in typename equivalence declarations"; | 126: str := "There is a cycle in the array element type declarations"; | 127: str := "This is an implement-only method, and cannot be called"; | 128: str := "Only declarations at module level can be exported"; | 129: str := "Cannot open symbol file"; | 130: str := "Bad magic number in symbol file"; | 131: str := "This type is an INTERFACE, and cannot be instantiated"; | 132: str := "Corrupted symbol file"; | 133: str := "Inconsistent module keys"; | 134: str := "Types can only be public or fully private"; | 135: str := "This variable may be uninitialized"; | 136: str := "Not all paths to END contain a RETURN statement"; | 137: str := "This type tries to directly include itself"; | 138: str := "Not all paths to END in RESCUE contain a RETURN statement"; | 139: str := "Not all OUT parameters have been assigned to"; | 140: str := "Pointer bound type can only be RECORD or ARRAY"; | 141: str := "GPCP restriction: select expression cannot be LONGINT"; | 142: str := "Cannot assign entire open array"; | 143: str := "Cannot assign entire extensible or abstract record"; | 144: str := "Foreign modules must be compiled with '-special'"; | 145: str := "This type tries to indirectly include itself"; | 146: str := "Constructors are declared without receiver"; | 147: str := "Multiple supertype constructors match these parameters"; | 148: str := "This type has another constructor with equal signature"; | 149: str := "This procedure needs parameters"; | 150: str := "Parameter types of exported procedures must be exported"; | 151: str := "Return types of exported procedures must be exported"; | 152: str := "Bound type of foreign reference type cannot be assigned"; | 153: str := "Bound type of foreign reference type cannot be value param"; | 154: str := "It is not possible to extend an interface type"; | 155: str := "NEW illegal unless foreign supertype has no-arg constructor"; | 156: str := "Interfaces can only extend ANYREC or the target Object type"; | 157: str := "Only extensions of Foreign classes can implement interfaces"; | 158: str := "Additional base types must be interface types"; | 159: str := "Not all interface methods were implemented"; | 160: str := "Inherited procedure had non-matching formal types"; | 161: str := "Only foreign procs and fields can have protected mode"; | 162: str := "This name only accessible in extensions of defining type"; | 163: str := "Interface implementation has wrong export mode"; (**)| 164: str := "Non-locally accessed variable may be uninitialized"; | 165: str := "This procedure cannot be used as a procedure value"; | 166: str := "Super calls are only valid on the current receiver"; | 167: str := "SIZE is not meaningful in this implementation"; | 168: str := "Character literal outside SHORTCHAR range"; | 169: str := "Module exporting this type is not imported"; | 170: str := "This module has already been directly imported"; | 171: str := "Invalid binary operation on these types"; | 172: str := "Name clash in imported scope"; | 173: str := "This module indirectly imported with different key"; | 174: str := "Actual for IN formal must be record, array or string"; | 175: str := "The module exporting this name has not been imported"; | 176: str := "The current type is opaque and cannot be selected further"; | 177: str := "File creation error"; | 178: str := "This record field is read-only"; | 179: str := "This IN parameter is read-only"; | 180: str := "This variable is read-only"; | 181: str := "This identifier is read-only"; | 182: str := "Attempt to use a function when a proper procedure needed"; | 183: str := "This record is private, you cannot export this field"; | 184: str := "This record is readonly, this field cannot be public"; | 185: str := "Static members can only be defined with -special"; | 186: str := 'Ids with "$", "@" or "`" can only be defined with -special'; | 187: str := "Idents escaped with ` must have length >= 2"; | 188: str := "Methods of INTERFACE types must be ABSTRACT"; | 189: str := "Non-local access to byref param of value type"; | 190: str := "Temporary restriction: non-locals not allowed"; | 191: str := "Temporary restriction: only name equivalence here"; | 192: str := "Only '=' or ':' can go here"; | 193: str := "THROW needs a string or native exception object"; | 194: str := 'Only "UNCHECKED_ARITHMETIC" can go here'; | 195: str := "NEW method cannot be exported if receiver type is private"; | 196: str := "Only static fields can select on a type-name"; | 197: str := "Only static methods can select on a type-name"; | 198: str := "Static fields can only select on a type-name"; | 199: str := "Static methods can only select on a type-name"; | 200: str := "Constructors cannot be declared for imported types"; | 201: str := "Constructors must return POINTER TO RECORD type"; | 202: str := "Base type does not have a matching constructor"; | 203: str := "Base type does not allow a no-arg constructor"; | 204: str := "Constructors only allowed for extensions of foreign types"; | 205: str := "Methods can only be declared for local record types"; | 206: str := "Receivers of pointer type must have value mode"; | 207: str := "Feature with this name already known in binding scope"; | 208: str := "EVENT types only valid for .NET target"; | 209: str := "Events must have a valid formal parameter list"; | 210: str := "REGISTER expects an EVENT type here"; | 211: str := "Only procedure literals allowed here"; | 212: str := "Event types cannot be local to procedures"; | 213: str := "Temporary restriction: no proc. variables with JVM"; | 214: str := "Interface types cannot be anonymous"; | 215: str := "Interface types must be exported"; | 216: str := "Interface methods must be exported"; | 217: str := "Covariant OUT parameters unsafe removed from language"; | 218: str := "No procedure of this name with matching parameters"; | 219: str := "Multiple overloaded procedure signatures match this call"; | 220: RETURN; (* BEWARE PREMATURE EXIT *) | 221: str := "Non-standard construct, not allowed with /strict"; | 222: str := "This is not a value: thus cannot end with a type guard"; | 223: str := "Override of imp-only in exported type must be imp-only"; | 224: str := "This designator is not a procedure or a function call"; | 225: str := "Non-empty constructors can only return SELF"; | 226: str := "USHORT cannot be applied to this type"; | 227: str := "Cannot import SYSTEM without /unsafe option"; | 228: str := "Cannot import SYSTEM unless target=net"; | 229: str := "Designator is not of VECTOR type"; | 230: str := "Type is incompatible with element type"; | 231: str := "Vectors are always one-dimensional only"; | 232: str := 'Hex constant too big, use suffix "L" instead'; | 233: str := "Literal constant too big, even for LONGINT"; | 234: str := "Extension of LIMITED type must be limited"; | 235: str := "LIMITED types can only be extended in the same module"; | 236: str := "Cannot resolve CLR name of this type"; | 237: str := "Invalid hex escape sequence in this string"; | 238: str := "STA is illegal unless target is NET"; | 239: str := "This module can only be accessed via an alias"; | 240: str := "This module already has an alias"; | 298: str := "ILASM failed to assemble IL file"; | 299: str := "Compiler raised an internal exception"; (* ===================== END ERRORS ======================= *) (* ====================== WARNINGS ======================== *) | 300: str := "Warning: Super calls are deprecated"; | 301: str := "Warning: Procedure variables are deprecated"; | 302: str := "Warning: Non-local variable access here"; | 303: str := "Warning: Numeric literal is not in the SET range [0 .. 31]"; | 304: str := "Warning: This procedure is not exported, called or assigned"; | 305: str := "Warning: Another constructor has an equal signature"; | 306: str := "Warning: Covariant OUT parameters unsafe when aliassed"; | 307: str := "Warning: Multiple overloaded procedure signatures match this call"; | 308: str := "Warning: Default static class has name clash"; | 309: str := "Warning: Looking for an automatically renamed module"; | 310, 311: str := "Warning: This variable is accessed from nested procedure"; | 312, 313: RETURN; (* BEWARE PREMATURE EXIT *) | 314: str := "The anonymous record type is incomptible with all values"; | 315: str := "The anonymous array type is incomptible with all values"; | 316: str := "This pointer type may still have its default NIL value"; | 317: str := "Empty CASE statement will trap if control reaches here"; | 318: str := "Empty WITH statement will trap if control reaches here"; | 319: str := "STA has no effect without CPmain or WinMain"; | 320: str := "Procedure variables with JVM target are experimental"; (* ==================== END WARNINGS ====================== *) ELSE str := "Semantic error: " + LitValue.intToCharOpen(num)^; END; len := LEN(str$); NEW(msg, len+1); FOR idx := 0 TO len-1 DO msg[idx] := str[idx]; END; msg[len] := 0X; IF num < 300 THEN INC(Scnr.errors); StoreError(num,lin,col,msg); ELSIF ~nowarn THEN INC(Scnr.warnings); StoreError(num,lin,col,msg); END; IF prompt THEN IF num < 300 THEN Console.WriteString("Error"); ELSE Console.WriteString("Warning"); END; Console.WriteInt(num,0); Console.WriteString("@ line:"); Console.WriteInt(lin,0); Console.WriteString(", col:"); Console.WriteInt(col,0); Console.WriteLn; Console.WriteString(str); Console.WriteLn; END; END Report; (* ============================================================ *) PROCEDURE (h : SemanticHdlr)RepSt1*(num : INTEGER; IN s1 : ARRAY OF CHAR; lin,col : INTEGER); VAR msg : Message; BEGIN CASE num OF | 0: msg := LitValue.strToCharOpen("Expected: END " + s1); | 1: msg := LitValue.strToCharOpen("Expected: " + s1); | 89: msg := LitValue.strToCharOpen("Duplicated selector values <" + s1 + ">"); | 9, 169: msg := LitValue.strToCharOpen("Current type was <" + s1 + '>'); | 117: msg := LitValue.strToCharOpen("Type <" + s1 + "> must be extensible"); | 121: msg := LitValue.strToCharOpen("Missing methods <" + s1 + '>'); | 145: msg := LitValue.strToCharOpen("Types on cycle <" + s1 + '>'); | 129: msg := LitValue.strToCharOpen ( "Cannot open symbol file <" + s1 + ">" ); StoreError(num,lin,0,msg); INC(Scnr.errors); RETURN; | 130: msg := LitValue.strToCharOpen( "Bad magic number in symbol file <" + s1 + ">" ); StoreError(num,lin,0,msg); INC(Scnr.errors); RETURN; | 132: msg := LitValue.strToCharOpen( "Corrupted symbol file <" + s1 + ">" ); StoreError(num,lin,0,msg); INC(Scnr.errors); RETURN; | 133: msg := LitValue.strToCharOpen("Module <" + s1 + "> already imported with different key"); | 138: msg := LitValue.strToCharOpen('<' + s1 + '> not assigned before "RETURN"'); | 139: msg := LitValue.strToCharOpen('<' + s1 + '> not assigned before end of procedure'); | 154: msg := LitValue.strToCharOpen('<' + s1 + "> is a Foreign interface type"); | 157: msg := LitValue.strToCharOpen('<' + s1 + "> is not a Foreign type"); | 158: msg := LitValue.strToCharOpen('<' + s1 + "> is not a foreign language interface type"); | 159: msg := LitValue.strToCharOpen("Missing interface methods <" + s1 + '>'); | 162: msg := LitValue.strToCharOpen('<' + s1 + "> is a protected, foreign-language feature"); | 164: msg := LitValue.strToCharOpen('<' + s1 + "> not assigned before this call"); | 172: msg := LitValue.strToCharOpen('Name <' + s1 + '> clashes in imported scope'); | 175, 176: msg := LitValue.strToCharOpen("Module " + '<' + s1 + "> is not imported"); | 189: msg := LitValue.strToCharOpen('Non-local access to <' + s1 + '> cannot be verified on .NET'); | 205, 207: msg := LitValue.strToCharOpen( "Binding scope of feature is record type <" + s1 + ">"); | 236: msg := LitValue.strToCharOpen( "Cannot resolve CLR name of type : " + s1); | 239, 240: msg := LitValue.strToCharOpen( 'This module has alias name "' + s1 + '"'); | 299: msg := LitValue.strToCharOpen("Exception: " + s1); | 308: msg := LitValue.strToCharOpen( "Renaming static class to <" + s1 + ">"); | 310: msg := LitValue.strToCharOpen('Access to <' + s1 + '> has copying not reference semantics'); | 311: msg := LitValue.strToCharOpen('Access to variable <' + s1 + '> will be inefficient'); | 220, 312: msg := LitValue.strToCharOpen("Matches with - " + s1); | 313: msg := LitValue.strToCharOpen("Bound to - " + s1); END; IF ~nowarn OR (* If warnings are on OR *) (num < 300) THEN (* this is an error then *) StoreError(num,lin,0,msg); (* (1) Store THIS message *) h.Report(num,lin,col); (* (2) Generate other msg *) END; END RepSt1; (* ============================================================ *) PROCEDURE (h : SemanticHdlr)RepSt2*(num : INTEGER; IN s1,s2 : ARRAY OF CHAR; lin,col : INTEGER); VAR msg : Message; BEGIN CASE num OF | 21, 217, 306: msg := LitValue.strToCharOpen( "Actual par-type was " + s1 + ", Formal type was " + s2); | 76: msg := LitValue.strToCharOpen( "Expr-type was " + s2 + ", should be " + s1); | 57, 83: msg := LitValue.strToCharOpen( "LHS type was " + s1 + ", RHS type was " + s2); | 116: msg := LitValue.strToCharOpen( "Inherited retType is " + s1 + ", this retType " + s2); | 131: msg := LitValue.strToCharOpen( "Module name in file <" + s1 + ".cps> was <" + s2 + '>'); | 156: msg := LitValue.strToCharOpen( "Interfaces can only extend ANYREC or the target Object type" + RTS.eol^ + " Interface <" + s1 + "> has invalid base type" + RTS.eol^ + " Basetype <" + s2 + "> is not the target Object type"); StoreError(156, lin, col, msg); INC(Scnr.errors); RETURN; | 172: msg := LitValue.strToCharOpen( 'Name <' + s1 + '> clashes in scope <' + s2 + '>'); | 230: msg := LitValue.strToCharOpen( "Expression type is " + s2 + ", element type is " + s1); | 309: msg := LitValue.strToCharOpen( 'Looking for module "' + s1 + '" in file <' + s2 + '>'); END; StoreError(num,lin,col,msg); h.Report(num,lin,col); END RepSt2; (* ============================================================ *) PROCEDURE GetLine (VAR pos : INTEGER; OUT line : ARRAY OF CHAR; OUT eof : BOOLEAN); (** Read a source line. Return empty line if eof *) CONST cr = 0DX; lf = 0AX; tab = 09X; VAR ch: CHAR; i: INTEGER; BEGIN ch := Scnr.charAt(pos); INC(pos); i := 0; eof := FALSE; WHILE (ch # lf) & (ch # 0X) DO IF ch = cr THEN (* skip *) ELSIF ch = tab THEN REPEAT line[MIN(i,listingMax)] := ' '; INC(i) UNTIL i MOD 8 = 0; ELSE line[MIN(i,listingMax)] := ch; INC(i); END; ch := Scnr.charAt(pos); INC(pos); END; eof := (i = 0) & (ch = 0X); line[MIN(i,listingMax)] := 0X; END GetLine; (* ============================================================ *) PROCEDURE PrintErr(IN desc : ErrDesc); (** Print an error message *) VAR mLen : INTEGER; indx : INTEGER; BEGIN GPText.WriteString(Scnr.lst, "**** "); mLen := LEN(desc.msg$); IF desc.col = listingMax THEN (* write field of width (col-2) *) GPText.WriteString(Scnr.lst, desc.msg); ELSIF mLen < desc.col-1 THEN (* write field of width (col-2) *) GPText.WriteFiller(Scnr.lst, desc.msg, "-", desc.col-1); GPText.Write(Scnr.lst, "^"); ELSIF mLen + desc.col + 5 < consoleWidth THEN GPText.WriteFiller(Scnr.lst, "", "-", desc.col-1); GPText.WriteString(Scnr.lst, "^ "); GPText.WriteString(Scnr.lst, desc.msg); ELSE GPText.WriteFiller(Scnr.lst, "", "-", desc.col-1); GPText.Write(Scnr.lst, "^"); GPText.WriteLn(Scnr.lst); GPText.WriteString(Scnr.lst, "**** "); GPText.WriteString(Scnr.lst, desc.msg); END; GPText.WriteLn(Scnr.lst); END PrintErr; (* ============================================================ *) PROCEDURE Display (IN desc : ErrDesc); (** Display an error message *) VAR mLen : INTEGER; indx : INTEGER; BEGIN Console.WriteString("**** "); mLen := LEN(desc.msg$); IF desc.col = listingMax THEN Console.WriteString(desc.msg); ELSIF mLen < desc.col-1 THEN Console.WriteString(desc.msg); FOR indx := mLen TO desc.col-2 DO Console.Write("-") END; Console.Write("^"); ELSIF mLen + desc.col + 5 < consoleWidth THEN FOR indx := 2 TO desc.col DO Console.Write("-") END; Console.WriteString("^ "); Console.WriteString(desc.msg); ELSE FOR indx := 2 TO desc.col DO Console.Write("-") END; Console.Write("^"); Console.WriteLn; Console.WriteString("**** "); Console.WriteString(desc.msg); END; Console.WriteLn; END Display; (* ============================================================ *) PROCEDURE DisplayVS (IN desc : ErrDesc); (** Display an error message for Visual Studio *) VAR mLen : INTEGER; indx : INTEGER; BEGIN Console.WriteString(srcNam); Console.Write("("); Console.WriteInt(desc.lin,1); Console.Write(","); Console.WriteInt(desc.col,1); Console.WriteString(") : "); IF desc.num < 300 THEN Console.WriteString("error : "); ELSE Console.WriteString("warning : "); END; Console.WriteString(desc.msg); Console.WriteLn; END DisplayVS; (* ============================================================ *) PROCEDURE DisplayXMLHeader (); BEGIN Console.WriteString('<?xml version="1.0"?>'); Console.WriteLn; Console.WriteString('<compilererrors errorsContained="yes">'); Console.WriteLn; END DisplayXMLHeader; PROCEDURE DisplayXMLEnd (); BEGIN Console.WriteString('</compilererrors>'); Console.WriteLn; END DisplayXMLEnd; PROCEDURE DisplayXML (IN desc : ErrDesc); (** Display an error message in xml format (for eclipse) *) (* <?xml version="1.0"?> * <compilererrors errorsContained="yes"> * <error> * <line> 1 </line> * <position> 34 </position> * <description> ; expected </description> * </error> * ... * </compilererrors> *) VAR mLen : INTEGER; indx : INTEGER; isWarn : BOOLEAN; BEGIN isWarn := desc.num >= 300; IF isWarn THEN Console.WriteString(" <warning> "); ELSE Console.WriteString(" <error> "); END; Console.WriteLn; Console.WriteString(" <line> "); Console.WriteInt(desc.lin,1); Console.WriteString(" </line>"); Console.WriteLn; Console.WriteString(" <position> "); Console.WriteInt(desc.col,1); Console.WriteString(" </position>"); Console.WriteLn; Console.WriteString(" <description> "); IF isWarn THEN Console.WriteString("warning : "); ELSE Console.WriteString("error : "); END; Console.WriteString(desc.msg); Console.WriteString(" </description> "); Console.WriteLn; IF isWarn THEN Console.WriteString(" </warning> "); ELSE Console.WriteString(" </error> "); END; Console.WriteLn; END DisplayXML; (* ============================================================ *) PROCEDURE PrintLine(n : INTEGER; IN l : ARRAY OF CHAR); BEGIN GPText.WriteInt(Scnr.lst, n, 4); GPText.Write(Scnr.lst, " "); GPText.WriteString(Scnr.lst, l); GPText.WriteLn(Scnr.lst); END PrintLine; (* ============================================================ *) PROCEDURE DisplayLn(n : INTEGER; IN l : ARRAY OF CHAR); BEGIN Console.WriteInt(n, 4); Console.Write(" "); Console.WriteString(l); Console.WriteLn; END DisplayLn; (* ============================================================ *) PROCEDURE PrintListing*(list : BOOLEAN); (** Print a source listing with error messages *) VAR nextErr : Err; (* next error descriptor *) nextLin : INTEGER; (* line num of nextErr *) eof : BOOLEAN; (* end of file found *) lnr : INTEGER; (* current line number *) errC : INTEGER; (* current error index *) srcPos : INTEGER; (* postion in sourceFile *) line : ARRAY listingWidth OF CHAR; BEGIN IF xmlErrors THEN DisplayXMLHeader(); END; nextLin := 0; IF eTide > 0 THEN QuickSort(0, eTide-1) END; IF list THEN GPText.WriteString(Scnr.lst, "Listing:"); GPText.WriteLn(Scnr.lst); GPText.WriteLn(Scnr.lst); END; srcPos := 0; nextErr := eBuffer[0]; GetLine(srcPos, line, eof); lnr := 1; errC := 0; WHILE ~ eof DO IF nextErr # NIL THEN nextLin := nextErr.lin END; IF list THEN PrintLine(lnr, line) END; IF ~forVisualStudio & ~xmlErrors & (~list OR (lnr = nextLin)) THEN DisplayLn(lnr, line) END; WHILE (nextErr # NIL) & (nextErr.lin = lnr) DO IF list THEN PrintErr(nextErr) END; IF forVisualStudio THEN DisplayVS(nextErr); ELSIF xmlErrors THEN DisplayXML(nextErr); ELSE Display(nextErr); END; INC(errC); nextErr := eBuffer[errC]; END; GetLine(srcPos, line, eof); INC(lnr); END; WHILE nextErr # NIL DO IF list THEN PrintErr(nextErr) END; IF forVisualStudio THEN DisplayVS(nextErr); ELSE Display(nextErr); END; INC(errC); nextErr := eBuffer[errC]; END; (* * IF list THEN * GPText.WriteLn(Scnr.lst); * GPText.WriteInt(Scnr.lst, errC, 5); * GPText.WriteString(Scnr.lst, " error"); * IF errC # 1 THEN GPText.Write(Scnr.lst, "s") END; * GPText.WriteLn(Scnr.lst); * GPText.WriteLn(Scnr.lst); * GPText.WriteLn(Scnr.lst); * END; *) IF list THEN GPText.WriteLn(Scnr.lst); GPText.WriteString(Scnr.lst, "There were: "); IF Scnr.errors = 0 THEN GPText.WriteString(Scnr.lst, "No errors"); ELSE GPText.WriteInt(Scnr.lst, Scnr.errors, 0); GPText.WriteString(Scnr.lst, " error"); IF Scnr.errors # 1 THEN GPText.Write(Scnr.lst, "s") END; END; GPText.WriteString(Scnr.lst, ", and "); IF Scnr.warnings = 0 THEN GPText.WriteString(Scnr.lst, "No warnings"); ELSE GPText.WriteInt(Scnr.lst, Scnr.warnings, 0); GPText.WriteString(Scnr.lst, " warning"); IF Scnr.warnings # 1 THEN GPText.Write(Scnr.lst, "s") END; END; GPText.WriteLn(Scnr.lst); GPText.WriteLn(Scnr.lst); GPText.WriteLn(Scnr.lst); END; IF xmlErrors THEN DisplayXMLEnd(); END; END PrintListing; PROCEDURE ResetErrorList*(); BEGIN eTide := 0; eBuffer[0] := NIL; END ResetErrorList; (* ============================================================ *) PROCEDURE Init*; BEGIN NEW(parsHdlr); Scnr.ParseErr := parsHdlr; NEW(semaHdlr); Scnr.SemError := semaHdlr; END Init; (* ============================================================ *) PROCEDURE SetSrcNam* (IN nam : ARRAY OF CHAR); BEGIN GPText.Assign(nam,srcNam); END SetSrcNam; (* ============================================================ *) BEGIN NEW(eBuffer, 8); eBuffer[0] := NIL; eLimit := 7; eTide := 0; prompt := FALSE; nowarn := FALSE; no239Err := FALSE; forVisualStudio := FALSE; END CPascalErrors. (* ============================================================ *)
41.825099
87
0.546483
imt-ag
3ff301844814536c79081067323f3296411d078a
3,241
cpp
C++
src/StateMove.cpp
Pnaop/interface_opdracht
891d619ee00610241eba44bfef51b11d3235c687
[ "MIT" ]
null
null
null
src/StateMove.cpp
Pnaop/interface_opdracht
891d619ee00610241eba44bfef51b11d3235c687
[ "MIT" ]
null
null
null
src/StateMove.cpp
Pnaop/interface_opdracht
891d619ee00610241eba44bfef51b11d3235c687
[ "MIT" ]
null
null
null
#include "../include/StateMove.h" #include "../include/StateEmergency.h" #include "../include/StateIdle.h" #include <interface_opdracht/moveAction.h> StateMove::StateMove(HighLevelDriver& context):context(context) { } StateMove::~StateMove() { } void StateMove::handleEvent(Event& event) { switch (event.getEventType()) { case EVENT_NEW_GOAL: case EVENT_GOAL_DONE: { std::shared_ptr<State> ptr = std::make_shared<StateIdle>(context); context.setCurrentState(ptr); } break; case EVENT_EMERGENCY: default: { std::shared_ptr<StateEmergency> ptr = std::make_shared<StateEmergency>(context); context.setCurrentState(ptr); } break; } } void StateMove::entry() { ROS_INFO("STATE: MOVE"); start = std::chrono::high_resolution_clock::now(); RobotLD& arm = context.getArm(); saveStartPositions(arm.getAxis()); arm.sendCommand(this->context.getCurrentGoal()); } bool StateMove::doActivity() { actionlib::SimpleActionServer<interface_opdracht::moveAction>& as_ = this->context.getActionServer(); interface_opdracht::moveFeedback& feedback_ = context.getFeedback(); if(as_.isPreemptRequested() || !ros::ok()) { RobotLD& arm = context.getArm(); arm.sendStopCommand(); setcurrentPositionsAsGoal(arm.getAxis(),std::chrono::duration<double,std::milli>(std::chrono::high_resolution_clock::now() - start).count(),context.getCurrentGoal().time); feedback_.sequence.clear(); as_.setPreempted(); Event e(EVENT_NEW_GOAL); context.addEvent(e); } else { if(std::chrono::duration<double,std::milli>(std::chrono::high_resolution_clock::now() - start).count() >= this->context.getCurrentGoal().time) { interface_opdracht::moveResult& result_ = context.getResult(); result_.sequence = feedback_.sequence; feedback_.sequence.clear(); as_.setSucceeded(result_); Event e(EVENT_GOAL_DONE); context.addEvent(e); } else { feedback_.sequence.push_back(std::chrono::duration<double,std::milli>(std::chrono::high_resolution_clock::now() - start).count()); as_.publishFeedback(feedback_); } } return true; } void StateMove::setcurrentPositionsAsGoal(std::vector<Axis>& axis,double currentTime,double endTime) { for(uint8_t i = 0; i < axis.size(); ++i) { axis[i].setGoal(calculatePosition(startPositions[i],axis[i].getGoal(),currentTime,endTime)); } } void StateMove::saveStartPositions(std::vector<Axis>& axis) { startPositions.clear(); for(uint8_t i = 0; i < axis.size(); ++i) { startPositions.push_back(axis[i].getGoal()); } } float StateMove::calculatePosition(float startPosition,float goal,double currentTime,double endTime) { float ratioProgress = currentTime/endTime; float distance = goal - startPosition; float returnValue = startPosition + (distance * ratioProgress); return returnValue; } void StateMove::exit() { std::cout << "exit Move" << std::endl; }
28.9375
179
0.636532
Pnaop
3ff65485b02000023e180d497d85c53716f4a0c9
651
hpp
C++
options.hpp
a12n/rematrix
e539a5573a99665ba7b21e1c2114508060dcd163
[ "MIT" ]
2
2022-01-15T16:27:05.000Z
2022-01-15T16:48:03.000Z
options.hpp
a12n/rematrix
e539a5573a99665ba7b21e1c2114508060dcd163
[ "MIT" ]
null
null
null
options.hpp
a12n/rematrix
e539a5573a99665ba7b21e1c2114508060dcd163
[ "MIT" ]
null
null
null
#ifndef REMATRIX_OPTIONS_HPP #define REMATRIX_OPTIONS_HPP #include "matrix.hpp" namespace rematrix { struct options { enum mode { binary, decimal, dna, hexadecimal, matrix, }; bool enable_fog{false}; bool enable_waves{true}; mode mode{matrix}; unsigned int frame_rate{10}; vec3 char_color{0x45 / 255.0f, 0x85 / 255.0f, 0x88 / 255.0f}; vec3 clear_color{0x28 / 255.0f, 0x28 / 255.0f, 0x28 / 255.0f}; vec3 feeder_color{0x83 / 255.0f, 0xa5 / 255.0f, 0x98 / 255.0f}; }; options parse_options(int argc, char* argv[]); } // namespace rematrix #endif // REMATRIX_OPTIONS_HPP
19.727273
67
0.642089
a12n
3ffeb94e53ae830e4e101654ea0c7ae3c93820a9
2,307
hpp
C++
particle_render.vs.hpp
demotomohiro/The-Job-changing-knight-Ganglion
40382990b58f6e643b39ea108aa45e7c7173ce1c
[ "MIT" ]
1
2015-03-21T23:00:01.000Z
2015-03-21T23:00:01.000Z
particle_render.vs.hpp
demotomohiro/The-Job-changing-knight-Ganglion
40382990b58f6e643b39ea108aa45e7c7173ce1c
[ "MIT" ]
null
null
null
particle_render.vs.hpp
demotomohiro/The-Job-changing-knight-Ganglion
40382990b58f6e643b39ea108aa45e7c7173ce1c
[ "MIT" ]
null
null
null
/* File generated with Shader Minifier 1.1.4 * http://www.ctrl-alt-test.fr */ #ifndef PARTICLE_RENDER_VS_HPP_ # define PARTICLE_RENDER_VS_HPP_ const char *particle_render_vs = "#version 420\n" "float s(float f,float v)" "{" "float s=v/4.*60.,D=15.,g=.8;" "return smoothstep(-D/2.,-D*(1.-g)/2.,-abs(f-s-D*.5));" "}" "vec3 s(float v)" "{" "float f=v+2.;" "vec3 s=vec3(f,f*f,f*f*f),g=fract(s*222.)+vec3(2.);" "return fract(s*g.yzx*g.zxy);" "}" "float v(float v)" "{" "return v/44100;" "}" "float e(float v)" "{" "return 1.-smoothstep(0.,4.,v);" "}" "float t(float v)" "{" "float f=60.-v;" "return 1.-smoothstep(0.,4.,f);" "}" "mat3 e(vec3 f,vec3 v)" "{" "vec3 s=normalize(f-v),g=normalize(cross(vec3(0.,1.,0.),s)),t=normalize(cross(s,g));" "mat3 m=mat3(g,t,s);" "return m;" "}" "uniform bool is_shadowmap;" "const mat4 m=mat4(1./1.5,0.,0.,0.,0.,1./1.5,0.,0.,0.,0.,-.4,0.,0.,0.,-1.4,1.);" "vec3 e()" "{" "return vec3(1.5,3.,2.);" "}" "mat3 s()" "{" "return e(e(),vec3(0.));" "}" "vec3 n(float v)" "{" "return is_shadowmap?e():vec3(.3,2.+cos(v),3.+sin(v)*.8);" "}" "mat3 n(float v,vec3 f)" "{" "return is_shadowmap?s():e(f,vec3(0.));" "}" "const mat4 i=mat4(2.,0.,0.,0.,0.,3.55556,0.,0.,0.,0.,-1.0339,-1.,0.,0.,-.20339,0.);" "uniform float sample_count;" "layout(binding=0)uniform samplerBuffer positions;" "out vec3 vary_tangent,vary_view_dir;" "out vec4 vary_shadow_pos;" "out float vary_t,vary_nrm_insid;" "void main()" "{" "vec3 f=texelFetch(positions,gl_VertexID/2+gl_InstanceID*16+2).xyz,g=gl_VertexID/2==15?texelFetch(positions,gl_VertexID/2-1+gl_InstanceID*16+2).xyz:texelFetch(positions,gl_VertexID/2+1+gl_InstanceID*16+2).xyz,t=normalize(gl_VertexID/2==15?f-g:g-f);" "float p=v(sample_count);" "vec3 D=n(p);" "mat3 x=transpose(n(p,D));" "vec3 r=x*(f-D),c=x*t;" "r+=vec3(c.yx*vec2(1.,-1.)*float(gl_VertexID%2)*.001,0.);" "gl_Position=(is_shadowmap?m:i)*vec4(r,1.);" "vary_tangent=t;" "vary_view_dir=D-f;" "mat3 b=s(),d=transpose(b);" "vary_shadow_pos=m*vec4(d*(f-e()),1.);" "vary_shadow_pos.xyz*=.5;" "vary_shadow_pos.xyz+=.5;" "vary_shadow_pos.z-=.001;" "vary_t=gl_VertexID/2/16.;" "vary_nrm_insid=gl_InstanceID/20000.;" "}"; #endif // PARTICLE_RENDER_VS_HPP_
27.464286
252
0.596879
demotomohiro
b203c159f1a83d4b0d53df12b2d2deaa2f8827a3
2,582
hpp
C++
lib/drivers/include/drivers/BasicDout.hpp
amsobr/iotool
233ec320ee25c96d34332fe847663682c4aa0a91
[ "MIT" ]
null
null
null
lib/drivers/include/drivers/BasicDout.hpp
amsobr/iotool
233ec320ee25c96d34332fe847663682c4aa0a91
[ "MIT" ]
4
2022-03-13T23:07:12.000Z
2022-03-13T23:10:09.000Z
lib/drivers/include/drivers/BasicDout.hpp
amsobr/iotool
233ec320ee25c96d34332fe847663682c4aa0a91
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <list> #include <vector> #include <memory> #include <tuple> #include <gpiod.hpp> #include <common/Peripheral.hpp> #include <common/PeripheralType.hpp> #include <common/DigitalOut.hpp> class BasicDout : public DigitalOut { public: /** * @brief Digital Output configuration * @li first element: the name of the PIN * @li second element: the name of the GPIO that handles PIN with libgpiod * @li third element: initial state of the pin */ using Config = std::vector< std::tuple<std::string,std::string,bool> >; // using Output = DigitalOut::Output; /** * @brief Create a simple digital output * @param id ID of the DigitalOut peripheral. Should be sequential within * a board. * @param outs Vector of tuples with the configuration of the outputs. * For each tuple: * * the first element is the symbolic to assign the output * * the second element is the name of the gpio that controls * the output through libgpiod * * the third element is the initial state of the output */ BasicDout(int id , Config const& outs ); ~BasicDout() override = default; [[nodiscard]] std::string getVendor() const override { return "TBD"; } [[nodiscard]] std::string getModel() const override { return "BASIC Digital Out"; } [[nodiscard]] std::string getRevision() const override { return "1.0.0"; } [[nodiscard]] std::string getDriverVersion() const override { return "1.0.0"; } [[nodiscard]] std::string getAuthor() const override { return "amsobr@github"; } [[nodiscard]] std::vector<Output> getOutputs() const override; int setOut( std::string name , bool value ) override; private: struct DoutHolder { std::string name; bool state; gpiod::line io; DoutHolder( BasicDout const& self, std::string oName, std::string const& ioName , bool ini ) : name{ std::move(oName) } , state{ini} , io{ gpiod::find_line(ioName) } { gpiod::line_request req; req.request_type = gpiod::line_request::DIRECTION_OUTPUT; req.consumer = Poco::format("basic-dout/%d/%s",self.getId(),name); io.request(req,0); io.set_value(ini); } }; std::vector<DoutHolder> myOutputs; }; /* class Agp01Indicators */ typedef std::shared_ptr<BasicDout> BasicDoutPtr;
31.876543
102
0.606507
amsobr
b204cbd87f2025ddaad07a2bfd4fcc98fd04e43a
9,264
hpp
C++
pennylane_lightning/src/tests/TestHelpers.hpp
AmintorDusko/pennylane-lightning
9554a95842de9d7759ce96bfa75857e0c9ca756b
[ "Apache-2.0" ]
null
null
null
pennylane_lightning/src/tests/TestHelpers.hpp
AmintorDusko/pennylane-lightning
9554a95842de9d7759ce96bfa75857e0c9ca756b
[ "Apache-2.0" ]
null
null
null
pennylane_lightning/src/tests/TestHelpers.hpp
AmintorDusko/pennylane-lightning
9554a95842de9d7759ce96bfa75857e0c9ca756b
[ "Apache-2.0" ]
null
null
null
#include <algorithm> #include <complex> #include <memory> #include <random> #include <string> #include <type_traits> #include <vector> #include "Constant.hpp" #include "ConstantUtil.hpp" #include "Error.hpp" #include "GateOperation.hpp" #include "LinearAlgebra.hpp" #include "Util.hpp" #include <catch2/catch.hpp> namespace Pennylane { template <class T, class Alloc = std::allocator<T>> struct PLApprox { const std::vector<T, Alloc> &comp_; explicit PLApprox(const std::vector<T, Alloc> &comp) : comp_{comp} {} Util::remove_complex_t<T> margin_{}; Util::remove_complex_t<T> epsilon_ = std::numeric_limits<float>::epsilon() * 100; template <class AllocA> [[nodiscard]] bool compare(const std::vector<T, AllocA> &lhs) const { if (lhs.size() != comp_.size()) { return false; } for (size_t i = 0; i < lhs.size(); i++) { if constexpr (Util::is_complex_v<T>) { if (lhs[i].real() != Approx(comp_[i].real()) .epsilon(epsilon_) .margin(margin_) || lhs[i].imag() != Approx(comp_[i].imag()) .epsilon(epsilon_) .margin(margin_)) { return false; } } else { if (lhs[i] != Approx(comp_[i]).epsilon(epsilon_).margin(margin_)) { return false; } } } return true; } [[nodiscard]] std::string describe() const { std::ostringstream ss; ss << "is Approx to {"; for (const auto &elt : comp_) { ss << elt << ", "; } ss << "}" << std::endl; return ss.str(); } PLApprox &epsilon(Util::remove_complex_t<T> eps) { epsilon_ = eps; return *this; } PLApprox &margin(Util::remove_complex_t<T> m) { margin_ = m; return *this; } }; /** * @brief Simple helper for PLApprox for the cases when the class template * deduction does not work well. */ template <typename T, class Alloc> PLApprox<T, Alloc> approx(const std::vector<T, Alloc> &vec) { return PLApprox<T, Alloc>(vec); } template <typename T, class Alloc> std::ostream &operator<<(std::ostream &os, const PLApprox<T, Alloc> &approx) { os << approx.describe(); return os; } template <class T, class AllocA, class AllocB> bool operator==(const std::vector<T, AllocA> &lhs, const PLApprox<T, AllocB> &rhs) { return rhs.compare(lhs); } template <class T, class AllocA, class AllocB> bool operator!=(const std::vector<T, AllocA> &lhs, const PLApprox<T, AllocB> &rhs) { return !rhs.compare(lhs); } /** * @brief Utility function to compare complex statevector data. * * @tparam Data_t Floating point data-type. * @param data1 StateVector data 1. * @param data2 StateVector data 2. * @return true Data are approximately equal. * @return false Data are not approximately equal. */ template <class Data_t, class AllocA, class AllocB> inline bool isApproxEqual(const std::vector<Data_t, AllocA> &data1, const std::vector<Data_t, AllocB> &data2, const typename Data_t::value_type eps = std::numeric_limits<typename Data_t::value_type>::epsilon() * 100) { return data1 == PLApprox<Data_t, AllocB>(data2).epsilon(eps); } /** * @brief Utility function to compare complex statevector data. * * @tparam Data_t Floating point data-type. * @param data1 StateVector data 1. * @param data2 StateVector data 2. * @return true Data are approximately equal. * @return false Data are not approximately equal. */ template <class Data_t> inline bool isApproxEqual(const Data_t &data1, const Data_t &data2, typename Data_t::value_type eps = std::numeric_limits<typename Data_t::value_type>::epsilon() * 100) { return !(data1.real() != Approx(data2.real()).epsilon(eps) || data1.imag() != Approx(data2.imag()).epsilon(eps)); } /** * @brief Multiplies every value in a dataset by a given complex scalar value. * * @tparam Data_t Precision of complex data type. Supports float and double * data. * @param data Data to be scaled. * @param scalar Scalar value. */ template <class Data_t> void scaleVector(std::vector<std::complex<Data_t>> &data, std::complex<Data_t> scalar) { std::transform( data.begin(), data.end(), data.begin(), [scalar](const std::complex<Data_t> &c) { return c * scalar; }); } /** * @brief Multiplies every value in a dataset by a given complex scalar value. * * @tparam Data_t Precision of complex data type. Supports float and double * data. * @param data Data to be scaled. * @param scalar Scalar value. */ template <class Data_t> void scaleVector(std::vector<std::complex<Data_t>> &data, Data_t scalar) { std::transform( data.begin(), data.end(), data.begin(), [scalar](const std::complex<Data_t> &c) { return c * scalar; }); } /** * @brief create |0>^N */ template <typename PrecisionT> auto createZeroState(size_t num_qubits) -> std::vector<std::complex<PrecisionT>> { std::vector<std::complex<PrecisionT>> res(size_t{1U} << num_qubits, {0.0, 0.0}); res[0] = std::complex<PrecisionT>{1.0, 0.0}; return res; } /** * @brief create |+>^N */ template <typename PrecisionT> auto createPlusState(size_t num_qubits) -> std::vector<std::complex<PrecisionT>> { std::vector<std::complex<PrecisionT>> res(size_t{1U} << num_qubits, {1.0, 0.0}); for (auto &elt : res) { elt /= std::sqrt(1U << num_qubits); } return res; } /** * @brief create a random state */ template <typename PrecisionT, class RandomEngine> auto createRandomState(RandomEngine &re, size_t num_qubits) -> std::vector<std::complex<PrecisionT>> { std::vector<std::complex<PrecisionT>> res(size_t{1U} << num_qubits, {0.0, 0.0}); std::uniform_real_distribution<PrecisionT> dist; for (size_t idx = 0; idx < (size_t{1U} << num_qubits); idx++) { res[idx] = {dist(re), dist(re)}; } scaleVector(res, std::complex<PrecisionT>{1.0, 0.0} / std::sqrt(Util::squaredNorm(res.data(), res.size()))); return res; } /** * @brief Create an arbitrary product state in X- or Z-basis. * * Example: createProductState("+01") will produce |+01> state. */ template <typename PrecisionT> auto createProductState(std::string_view str) { using Pennylane::Util::INVSQRT2; std::vector<std::complex<PrecisionT>> st; st.resize(size_t{1U} << str.length()); std::vector<PrecisionT> zero{1.0, 0.0}; std::vector<PrecisionT> one{0.0, 1.0}; std::vector<PrecisionT> plus{INVSQRT2<PrecisionT>(), INVSQRT2<PrecisionT>()}; std::vector<PrecisionT> minus{INVSQRT2<PrecisionT>(), -INVSQRT2<PrecisionT>()}; for (size_t k = 0; k < (size_t{1U} << str.length()); k++) { PrecisionT elt = 1.0; for (size_t n = 0; n < str.length(); n++) { char c = str[n]; const size_t wire = str.length() - 1 - n; switch (c) { case '0': elt *= zero[(k >> wire) & 1U]; break; case '1': elt *= one[(k >> wire) & 1U]; break; case '+': elt *= plus[(k >> wire) & 1U]; break; case '-': elt *= minus[(k >> wire) & 1U]; break; default: PL_ABORT("Unknown character in the argument."); } } st[k] = elt; } return st; } inline auto createWires(Gates::GateOperation op) -> std::vector<size_t> { if (Pennylane::Util::array_has_elt(Gates::Constant::multi_qubit_gates, op)) { // if multi-qubit gates return {0, 1, 2}; } switch (Pennylane::Util::lookup(Gates::Constant::gate_wires, op)) { case 1: return {0}; case 2: return {0, 1}; case 3: return {0, 1, 2}; default: PL_ABORT("The number of wires for a given gate is unknown."); } return {}; } template <class PrecisionT> auto createParams(Gates::GateOperation op) -> std::vector<PrecisionT> { switch (Pennylane::Util::lookup(Gates::Constant::gate_num_params, op)) { case 0: return {}; case 1: return {PrecisionT{0.312}}; case 3: return {PrecisionT{0.128}, PrecisionT{-0.563}, PrecisionT{1.414}}; default: PL_ABORT("The number of parameters for a given gate is unknown."); } return {}; } template <class PrecisionT> struct PrecisionToName; template <> struct PrecisionToName<float> { constexpr static auto value = "float"; }; template <> struct PrecisionToName<double> { constexpr static auto value = "double"; }; } // namespace Pennylane
30.88
79
0.571891
AmintorDusko
b20c3cc46f2c6e8c7de2a0cd723dce901e1c39db
18,045
cpp
C++
src/common.cpp
iamyoukou/sdf3d
3a7353156e800bccd58adeddcd110efe24b11f88
[ "Unlicense", "MIT" ]
18
2020-05-21T16:05:40.000Z
2022-02-26T00:41:39.000Z
src/common.cpp
iamyoukou/sdf3d
3a7353156e800bccd58adeddcd110efe24b11f88
[ "Unlicense", "MIT" ]
null
null
null
src/common.cpp
iamyoukou/sdf3d
3a7353156e800bccd58adeddcd110efe24b11f88
[ "Unlicense", "MIT" ]
8
2019-11-26T09:18:14.000Z
2022-03-01T20:10:47.000Z
#include "common.h" std::string readFile(const std::string filename) { std::ifstream in; in.open(filename.c_str()); std::stringstream ss; ss << in.rdbuf(); std::string sOut = ss.str(); in.close(); return sOut; } Mesh loadObj(std::string filename) { Mesh outMesh; std::ifstream fin; fin.open(filename.c_str()); if (!(fin.good())) { std::cout << "failed to open file : " << filename << std::endl; } while (fin.peek() != EOF) { // read obj loop std::string s; fin >> s; // vertex coordinate if ("v" == s) { float x, y, z; fin >> x; fin >> y; fin >> z; outMesh.vertices.push_back(glm::vec3(x, y, z)); } // texture coordinate else if ("vt" == s) { float u, v; fin >> u; fin >> v; outMesh.uvs.push_back(glm::vec2(u, v)); } // face normal (recorded as vn in obj file) else if ("vn" == s) { float x, y, z; fin >> x; fin >> y; fin >> z; outMesh.faceNormals.push_back(glm::vec3(x, y, z)); } // vertices contained in face, and face normal else if ("f" == s) { Face f; // v1/vt1/vn1 fin >> f.v1; fin.ignore(1); fin >> f.vt1; fin.ignore(1); fin >> f.vn1; // v2/vt2/vn2 fin >> f.v2; fin.ignore(1); fin >> f.vt2; fin.ignore(1); fin >> f.vn2; // v3/vt3/vn3 fin >> f.v3; fin.ignore(1); fin >> f.vt3; fin.ignore(1); fin >> f.vn3; // Note: // v, vt, vn in "v/vt/vn" start from 1, // but indices of std::vector start from 0, // so we need minus 1 for all elements f.v1 -= 1; f.vt1 -= 1; f.vn1 -= 1; f.v2 -= 1; f.vt2 -= 1; f.vn2 -= 1; f.v3 -= 1; f.vt3 -= 1; f.vn3 -= 1; outMesh.faces.push_back(f); } else { continue; } } // end read obj loop fin.close(); return outMesh; } // return a shader executable GLuint buildShader(string vsDir, string fsDir) { GLuint vs, fs; GLint linkOk; GLuint exeShader; // compile vs = compileShader(vsDir, GL_VERTEX_SHADER); fs = compileShader(fsDir, GL_FRAGMENT_SHADER); // link exeShader = linkShader(vs, fs); return exeShader; } GLuint compileShader(string filename, GLenum type) { /* read source code */ string sTemp = readFile(filename); string info; const GLchar *source = sTemp.c_str(); switch (type) { case GL_VERTEX_SHADER: info = "Vertex"; break; case GL_FRAGMENT_SHADER: info = "Fragment"; break; } if (source == NULL) { std::cout << info << " Shader : Can't read shader source file." << std::endl; return 0; } const GLchar *sources[] = {source}; GLuint objShader = glCreateShader(type); glShaderSource(objShader, 1, sources, NULL); glCompileShader(objShader); GLint compile_ok; glGetShaderiv(objShader, GL_COMPILE_STATUS, &compile_ok); if (compile_ok == GL_FALSE) { std::cout << info << " Shader : Fail to compile." << std::endl; printLog(objShader); glDeleteShader(objShader); return 0; } return objShader; } GLuint linkShader(GLuint vsObj, GLuint fsObj) { GLuint exe; GLint linkOk; exe = glCreateProgram(); glAttachShader(exe, vsObj); glAttachShader(exe, fsObj); glLinkProgram(exe); // check result glGetProgramiv(exe, GL_LINK_STATUS, &linkOk); if (linkOk == GL_FALSE) { std::cout << "Failed to link shader program." << std::endl; printLog(exe); glDeleteProgram(exe); return 0; } return exe; } void printLog(GLuint &object) { GLint log_length = 0; if (glIsShader(object)) { glGetShaderiv(object, GL_INFO_LOG_LENGTH, &log_length); } else if (glIsProgram(object)) { glGetProgramiv(object, GL_INFO_LOG_LENGTH, &log_length); } else { std::cout << "printlog: Not a shader or a program" << std::endl; return; } char *log = (char *)malloc(log_length); if (glIsShader(object)) glGetShaderInfoLog(object, log_length, NULL, log); else if (glIsProgram(object)) glGetProgramInfoLog(object, log_length, NULL, log); std::cout << log << '\n'; free(log); } GLint myGetUniformLocation(GLuint &prog, std::string name) { GLint location; location = glGetUniformLocation(prog, name.c_str()); if (location == -1) { std::cout << "Could not bind uniform : " << name << ". " << "Did you set the right name? " << "Or is " << name << " not used?" << std::endl; } return location; } /* Mesh class */ void Mesh::translate(glm::vec3 xyz) { // move each vertex with xyz for (size_t i = 0; i < vertices.size(); i++) { vertices[i] += xyz; } // update aabb min += xyz; max += xyz; } void Mesh::scale(glm::vec3 xyz) { // scale each vertex with xyz for (size_t i = 0; i < vertices.size(); i++) { vertices[i].x *= xyz.x; vertices[i].y *= xyz.y; vertices[i].z *= xyz.z; } // update aabb min.x *= xyz.x; min.y *= xyz.y; min.z *= xyz.z; max.x *= xyz.x; max.y *= xyz.y; max.z *= xyz.z; } void findAABB(Mesh &mesh) { int nOfVtxs = mesh.vertices.size(); glm::vec3 min(0, 0, 0), max(0, 0, 0); for (size_t i = 0; i < nOfVtxs; i++) { glm::vec3 vtx = mesh.vertices[i]; // x if (vtx.x > max.x) { max.x = vtx.x; } if (vtx.x < min.x) { min.x = vtx.x; } // y if (vtx.y > max.y) { max.y = vtx.y; } if (vtx.y < min.y) { min.y = vtx.y; } // z if (vtx.z > max.z) { max.z = vtx.z; } if (vtx.z < min.z) { min.z = vtx.z; } } mesh.min = min; mesh.max = max; } void drawBox(glm::vec3 min, glm::vec3 max) { // 8 corners GLfloat aVtxs[] = { min.x, max.y, min.z, // 0 min.x, min.y, min.z, // 1 max.x, min.y, min.z, // 2 max.x, max.y, min.z, // 3 min.x, max.y, max.z, // 4 min.x, min.y, max.z, // 5 max.x, min.y, max.z, // 6 max.x, max.y, max.z // 7 }; // vertex color // GLfloat colorArray[] = {color.x, color.y, color.z, color.x, color.y, // color.z, // color.x, color.y, color.z, color.x, color.y, // color.z, color.x, color.y, color.z, color.x, // color.y, color.z, color.x, color.y, color.z, // color.x, color.y, color.z}; // vertex index GLushort aIdxs[] = { 0, 1, 2, 3, // front face 4, 7, 6, 5, // back 4, 0, 3, 7, // up 5, 6, 2, 1, // down 0, 4, 5, 1, // left 3, 2, 6, 7 // right }; // prepare buffers to draw GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); GLuint vboVtx; glGenBuffers(1, &vboVtx); glBindBuffer(GL_ARRAY_BUFFER, vboVtx); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 8 * 3, aVtxs, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(0); // GLuint vboColor; // glGenBuffers(1, &vboColor); // glBindBuffer(GL_ARRAY_BUFFER, vboColor); // glBufferData(GL_ARRAY_BUFFER, sizeof(colorArray), colorArray, // GL_STATIC_DRAW); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0); // glEnableVertexAttribArray(1); GLuint ibo; glGenBuffers(1, &ibo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(aIdxs), aIdxs, GL_STATIC_DRAW); // draw box glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); for (size_t i = 0; i < 6; i++) { glDrawElements(GL_LINE_LOOP, 4, GL_UNSIGNED_SHORT, (GLvoid *)(sizeof(GLushort) * 4 * i)); } glDeleteBuffers(1, &vboVtx); // glDeleteBuffers(1, &vboColor); glDeleteBuffers(1, &ibo); glDeleteVertexArrays(1, &vao); } void createMesh(Mesh &mesh) { // write vertex coordinate to array int nOfFaces = mesh.faces.size(); // 3 vertices per face, 3 float per vertex coord, 2 float per tex coord GLfloat *aVtxCoords = new GLfloat[nOfFaces * 3 * 3]; // GLfloat *aUvs = new GLfloat[nOfFaces * 3 * 2]; GLfloat *aNormals = new GLfloat[nOfFaces * 3 * 3]; for (size_t i = 0; i < nOfFaces; i++) { // vertex 1 int vtxIdx = mesh.faces[i].v1; aVtxCoords[i * 9 + 0] = mesh.vertices[vtxIdx].x; aVtxCoords[i * 9 + 1] = mesh.vertices[vtxIdx].y; aVtxCoords[i * 9 + 2] = mesh.vertices[vtxIdx].z; // normal for vertex 1 int nmlIdx = mesh.faces[i].vn1; aNormals[i * 9 + 0] = mesh.faceNormals[nmlIdx].x; aNormals[i * 9 + 1] = mesh.faceNormals[nmlIdx].y; aNormals[i * 9 + 2] = mesh.faceNormals[nmlIdx].z; // uv for vertex 1 // int uvIdx = mesh.faces[i].vt1; // aUvs[i * 6 + 0] = mesh.uvs[uvIdx].x; // aUvs[i * 6 + 1] = mesh.uvs[uvIdx].y; // vertex 2 vtxIdx = mesh.faces[i].v2; aVtxCoords[i * 9 + 3] = mesh.vertices[vtxIdx].x; aVtxCoords[i * 9 + 4] = mesh.vertices[vtxIdx].y; aVtxCoords[i * 9 + 5] = mesh.vertices[vtxIdx].z; // normal for vertex 2 nmlIdx = mesh.faces[i].vn2; aNormals[i * 9 + 3] = mesh.faceNormals[nmlIdx].x; aNormals[i * 9 + 4] = mesh.faceNormals[nmlIdx].y; aNormals[i * 9 + 5] = mesh.faceNormals[nmlIdx].z; // uv for vertex 2 // uvIdx = mesh.faces[i].vt2; // aUvs[i * 6 + 2] = mesh.uvs[uvIdx].x; // aUvs[i * 6 + 3] = mesh.uvs[uvIdx].y; // vertex 3 vtxIdx = mesh.faces[i].v3; aVtxCoords[i * 9 + 6] = mesh.vertices[vtxIdx].x; aVtxCoords[i * 9 + 7] = mesh.vertices[vtxIdx].y; aVtxCoords[i * 9 + 8] = mesh.vertices[vtxIdx].z; // normal for vertex 3 nmlIdx = mesh.faces[i].vn3; aNormals[i * 9 + 6] = mesh.faceNormals[nmlIdx].x; aNormals[i * 9 + 7] = mesh.faceNormals[nmlIdx].y; aNormals[i * 9 + 8] = mesh.faceNormals[nmlIdx].z; // uv for vertex 3 // uvIdx = mesh.faces[i].vt3; // aUvs[i * 6 + 4] = mesh.uvs[uvIdx].x; // aUvs[i * 6 + 5] = mesh.uvs[uvIdx].y; } // vao glGenVertexArrays(1, &mesh.vao); glBindVertexArray(mesh.vao); // vbo for vertex glGenBuffers(1, &mesh.vboVtxs); glBindBuffer(GL_ARRAY_BUFFER, mesh.vboVtxs); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * nOfFaces * 3 * 3, aVtxCoords, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(0); // vbo for texture // glGenBuffers(1, &mesh.vboUvs); // glBindBuffer(GL_ARRAY_BUFFER, mesh.vboUvs); // glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * nOfFaces * 3 * 2, aUvs, // GL_STATIC_DRAW); // glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0); // glEnableVertexAttribArray(1); // vbo for normal glGenBuffers(1, &mesh.vboNormals); glBindBuffer(GL_ARRAY_BUFFER, mesh.vboNormals); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * nOfFaces * 3 * 3, aNormals, GL_STATIC_DRAW); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(2); // delete client data delete[] aVtxCoords; // delete[] aUvs; delete[] aNormals; } // Whenever the vertex attributes have been changed, call this function // Otherwise, the vertex data on the server side will not be updated void updateMesh(Mesh &mesh) { // write vertex coordinate to array int nOfFaces = mesh.faces.size(); // 3 vertices per face, 3 float per vertex coord, 2 float per tex coord GLfloat *aVtxCoords = new GLfloat[nOfFaces * 3 * 3]; // GLfloat *aUvs = new GLfloat[nOfFaces * 3 * 2]; // GLfloat *aNormals = new GLfloat[nOfFaces * 3 * 3]; for (size_t i = 0; i < nOfFaces; i++) { // vertex 1 int vtxIdx = mesh.faces[i].v1; aVtxCoords[i * 9 + 0] = mesh.vertices[vtxIdx].x; aVtxCoords[i * 9 + 1] = mesh.vertices[vtxIdx].y; aVtxCoords[i * 9 + 2] = mesh.vertices[vtxIdx].z; // normal for vertex 1 // int nmlIdx = mesh.faces[i].vn1; // aNormals[i * 9 + 0] = mesh.faceNormals[nmlIdx].x; // aNormals[i * 9 + 1] = mesh.faceNormals[nmlIdx].y; // aNormals[i * 9 + 2] = mesh.faceNormals[nmlIdx].z; // uv for vertex 1 // int uvIdx = mesh.faces[i].vt1; // aUvs[i * 6 + 0] = mesh.uvs[uvIdx].x; // aUvs[i * 6 + 1] = mesh.uvs[uvIdx].y; // vertex 2 vtxIdx = mesh.faces[i].v2; aVtxCoords[i * 9 + 3] = mesh.vertices[vtxIdx].x; aVtxCoords[i * 9 + 4] = mesh.vertices[vtxIdx].y; aVtxCoords[i * 9 + 5] = mesh.vertices[vtxIdx].z; // normal for vertex 2 // nmlIdx = mesh.faces[i].vn2; // aNormals[i * 9 + 3] = mesh.faceNormals[nmlIdx].x; // aNormals[i * 9 + 4] = mesh.faceNormals[nmlIdx].y; // aNormals[i * 9 + 5] = mesh.faceNormals[nmlIdx].z; // uv for vertex 2 // uvIdx = mesh.faces[i].vt2; // aUvs[i * 6 + 2] = mesh.uvs[uvIdx].x; // aUvs[i * 6 + 3] = mesh.uvs[uvIdx].y; // vertex 3 vtxIdx = mesh.faces[i].v3; aVtxCoords[i * 9 + 6] = mesh.vertices[vtxIdx].x; aVtxCoords[i * 9 + 7] = mesh.vertices[vtxIdx].y; aVtxCoords[i * 9 + 8] = mesh.vertices[vtxIdx].z; // normal for vertex 3 // nmlIdx = mesh.faces[i].vn3; // aNormals[i * 9 + 6] = mesh.faceNormals[nmlIdx].x; // aNormals[i * 9 + 7] = mesh.faceNormals[nmlIdx].y; // aNormals[i * 9 + 8] = mesh.faceNormals[nmlIdx].z; // uv for vertex 3 // uvIdx = mesh.faces[i].vt3; // aUvs[i * 6 + 4] = mesh.uvs[uvIdx].x; // aUvs[i * 6 + 5] = mesh.uvs[uvIdx].y; } // vao glBindVertexArray(mesh.vao); // vbo for vertex glBindBuffer(GL_ARRAY_BUFFER, mesh.vboVtxs); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * nOfFaces * 3 * 3, aVtxCoords, GL_STATIC_DRAW); // vbo for texture // glBindBuffer(GL_ARRAY_BUFFER, mesh.vboUvs); // glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * nOfFaces * 3 * 2, aUvs, // GL_STATIC_DRAW); // vbo for normal // glBindBuffer(GL_ARRAY_BUFFER, mesh.vboNormals); // glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * nOfFaces * 3 * 3, aNormals, // GL_STATIC_DRAW); // delete client data delete[] aVtxCoords; // delete[] aUvs; // delete[] aNormals; } void drawPoints(std::vector<Point> &pts) { // array data int nOfPs = pts.size(); GLfloat *aPos = new GLfloat[nOfPs * 3]; GLfloat *aColor = new GLfloat[nOfPs * 3]; // implant data for (size_t i = 0; i < nOfPs; i++) { // positions Point &p = pts[i]; aPos[i * 3 + 0] = p.pos.x; aPos[i * 3 + 1] = p.pos.y; aPos[i * 3 + 2] = p.pos.z; // colors aColor[i * 3 + 0] = p.color.r; aColor[i * 3 + 1] = p.color.g; aColor[i * 3 + 2] = p.color.b; } // selete vao GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); // position GLuint vboPos; glGenBuffers(1, &vboPos); glBindBuffer(GL_ARRAY_BUFFER, vboPos); glBufferData(GL_ARRAY_BUFFER, nOfPs * 3 * sizeof(GLfloat), aPos, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(0); // color GLuint vboColor; glGenBuffers(1, &vboColor); glBindBuffer(GL_ARRAY_BUFFER, vboColor); glBufferData(GL_ARRAY_BUFFER, nOfPs * 3 * sizeof(GLfloat), aColor, GL_STREAM_DRAW); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(1); glDrawArrays(GL_POINTS, 0, nOfPs); // release delete[] aPos; delete[] aColor; glDeleteBuffers(1, &vboPos); glDeleteBuffers(1, &vboColor); glDeleteVertexArrays(1, &vao); } void drawLine(vec3 start, vec3 end) { GLfloat aPos[] = {start.x, start.y, start.z, end.x, end.y, end.z}; GLfloat aColor[] = {0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5}; // selete vao GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); // position GLuint vboPos; glGenBuffers(1, &vboPos); glBindBuffer(GL_ARRAY_BUFFER, vboPos); glBufferData(GL_ARRAY_BUFFER, 2 * 3 * sizeof(GLfloat), aPos, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(0); GLuint vboColor; glGenBuffers(1, &vboColor); glBindBuffer(GL_ARRAY_BUFFER, vboColor); glBufferData(GL_ARRAY_BUFFER, 2 * 3 * sizeof(GLfloat), aColor, GL_STATIC_DRAW); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(1); glDrawArrays(GL_LINES, 0, 2); glDeleteBuffers(1, &vboPos); glDeleteVertexArrays(1, &vao); } void drawTriangle(Triangle &tri) { GLfloat aPos[] = { tri.v1.x, tri.v1.y, tri.v1.z, // 0 tri.v2.x, tri.v2.y, tri.v2.z, // 1 tri.v3.x, tri.v3.y, tri.v3.z // 2 }; // selete vao GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); // position GLuint vboPos; glGenBuffers(1, &vboPos); glBindBuffer(GL_ARRAY_BUFFER, vboPos); glBufferData(GL_ARRAY_BUFFER, 3 * 3 * sizeof(GLfloat), aPos, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(0); glDrawArrays(GL_TRIANGLES, 0, 9); glDeleteBuffers(1, &vboPos); glDeleteVertexArrays(1, &vao); } void drawPoints(Particles &ps) { int nOfPs = ps.Ps.size(); // select vao glBindVertexArray(ps.vao); // position glBindBuffer(GL_ARRAY_BUFFER, ps.vboPos); // buffer orphaning glBufferData(GL_ARRAY_BUFFER, nOfPs * 3 * sizeof(GLfloat), NULL, GL_STREAM_DRAW); for (size_t i = 0; i < nOfPs; i++) { Point &p = ps.Ps[i]; glBufferSubData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 3 * i, sizeof(GLfloat) * 3, &p.pos); // if vec3 does not save data continuously in memory // use the following code // GLfloat temp[] = {p.pos.x, p.pos.y, p.pos.z}; // glBufferSubData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 3 * i, // sizeof(GLfloat) * 3, &temp); } // color // glBindBuffer(GL_ARRAY_BUFFER, ps.vboColor); // // buffer orphaning // glBufferData(GL_ARRAY_BUFFER, nOfPs * 3 * sizeof(GLfloat), NULL, // GL_STREAM_DRAW); // for (size_t i = 0; i < nOfPs; i++) { // glBufferSubData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 3 * i, // sizeof(GLfloat) * 3, &aColor[i * 3]); // } glDrawArrays(GL_POINTS, 0, nOfPs); }
26.575847
80
0.593295
iamyoukou
b20d90cdfb15815c85b5e07851adebf0889f1cd8
3,601
cc
C++
control/src/sl_sb03md.cc
SamThomas/Face_and_Voice_Recognition
ec405803c8ec9bc82370926d0b6ba97fa70fa31c
[ "MIT" ]
2
2016-08-25T19:09:41.000Z
2021-09-07T04:04:52.000Z
control/src/sl_sb03md.cc
SamThomas/Face_and_Voice_Recognition
ec405803c8ec9bc82370926d0b6ba97fa70fa31c
[ "MIT" ]
null
null
null
control/src/sl_sb03md.cc
SamThomas/Face_and_Voice_Recognition
ec405803c8ec9bc82370926d0b6ba97fa70fa31c
[ "MIT" ]
1
2022-03-05T16:17:16.000Z
2022-03-05T16:17:16.000Z
/* Copyright (C) 2009-2014 Lukas F. Reichlin This file is part of LTI Syncope. LTI Syncope is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. LTI Syncope is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with LTI Syncope. If not, see <http://www.gnu.org/licenses/>. Solution of Lyapunov equations. Uses SLICOT SB03MD by courtesy of NICONET e.V. <http://www.slicot.org> Author: Lukas Reichlin <lukas.reichlin@gmail.com> Created: December 2009 Version: 0.3 */ #include <octave/oct.h> #include <f77-fcn.h> #include "common.h" extern "C" { int F77_FUNC (sb03md, SB03MD) (char& DICO, char& JOB, char& FACT, char& TRANA, int& N, double* A, int& LDA, double* U, int& LDU, double* C, int& LDC, double& SCALE, double& SEP, double& FERR, double* WR, double* WI, int* IWORK, double* DWORK, int& LDWORK, int& INFO); } // PKG_ADD: autoload ("__sl_sb03md__", "__control_slicot_functions__.oct"); DEFUN_DLD (__sl_sb03md__, args, nargout, "-*- texinfo -*-\n\ Slicot SB03MD Release 5.0\n\ No argument checking.\n\ For internal use only.") { int nargin = args.length (); octave_value_list retval; if (nargin != 3) { print_usage (); } else { // arguments in char dico; char job = 'X'; char fact = 'N'; char trana = 'T'; Matrix a = args(0).matrix_value (); Matrix c = args(1).matrix_value (); int discrete = args(2).int_value (); if (discrete == 0) dico = 'C'; else dico = 'D'; int n = a.rows (); // n: number of states int lda = max (1, n); int ldu = max (1, n); int ldc = max (1, n); // arguments out double scale; double sep = 0; double ferr = 0; Matrix u (ldu, n); ColumnVector wr (n); ColumnVector wi (n); // workspace int* iwork = 0; // not referenced because job = X int ldwork = max (n*n, 3*n); OCTAVE_LOCAL_BUFFER (double, dwork, ldwork); // error indicator int info; // SLICOT routine SB03MD F77_XFCN (sb03md, SB03MD, (dico, job, fact, trana, n, a.fortran_vec (), lda, u.fortran_vec (), ldu, c.fortran_vec (), ldc, scale, sep, ferr, wr.fortran_vec (), wi.fortran_vec (), iwork, dwork, ldwork, info)); if (f77_exception_encountered) error ("lyap: __sl_sb03md__: exception in SLICOT subroutine SB03MD"); if (info != 0) error ("lyap: __sl_sb03md__: SB03MD returned info = %d", info); // return values retval(0) = c; retval(1) = octave_value (scale); } return retval; }
26.674074
81
0.526243
SamThomas
b213fa398b1f3e4bbbac24b630fd39bac9a8435f
1,741
cpp
C++
example/example2_opt.cpp
carlcc/JsonMapper
23adfe75482181d1f5b7eec052eb0626d441a2bf
[ "MIT" ]
3
2020-08-15T03:47:20.000Z
2021-06-29T10:49:38.000Z
example/example2_opt.cpp
carlcc/JsonMapper
23adfe75482181d1f5b7eec052eb0626d441a2bf
[ "MIT" ]
null
null
null
example/example2_opt.cpp
carlcc/JsonMapper
23adfe75482181d1f5b7eec052eb0626d441a2bf
[ "MIT" ]
1
2021-06-29T10:49:45.000Z
2021-06-29T10:49:45.000Z
#include <cstdint> #include <iostream> #include <jsonmapper/JsonMapper.h> #include <jsonmapper/types/deserialize/shared_ptr.h> #include <jsonmapper/types/deserialize/string.h> #include <jsonmapper/types/deserialize/unordered_map.h> #include <jsonmapper/types/deserialize/vector.h> #include <sstream> #include <string> #include <unordered_map> #include <vector> struct Address { std::vector<std::string> street; // NOTE: Deserialize from raw pointer is not supported for memory issue std::shared_ptr<std::string> nullable_string { nullptr }; template <class Archiver> bool DeserializeFromJson(Archiver& ar) { return ar(JMKVP(street), JMKVP(nullable_string)); } }; struct Student { std::unordered_map<std::string, Address> address; std::string name; int age; template <class Archiver> bool DeserializeFromJson(Archiver& ar) { // NOTE: // The difference between this example and example2 is that the 'address` field is optional, // thus, the deserializer just ignores 'address' field when it cannot find 'address' field. // NOTE2: // The 'address' field is just optional, if there is 'address' field, but it's wrong data, // this function will return false then. return ar(JMOPTKVP(address), JMKVP(name), JMKVP(age)); } }; const std::string kJsonString = R"({ "name": "Bill", "age": 44 })"; int main(int argc, char** argv) { Student stu; bool succeed = jsonmapper::DeserializeFromJsonString(stu, kJsonString); if (succeed) { // Here, the struct `stu` is filled std::cout << "Succeed" << std::endl; } else { std::cout << "Failed" << std::endl; } return 0; }
28.080645
100
0.659391
carlcc
b2151ff7da996110d20f2cb42e5fa64456c87e0e
4,383
cpp
C++
QuickGUI/src/QuickGUILabel.cpp
VisualEntertainmentAndTechnologies/VENT-QuickGUI
7c687193001bcf914bd4a9947644915091ea8723
[ "Unlicense" ]
3
2017-01-12T19:22:01.000Z
2017-05-06T09:55:39.000Z
QuickGUI/src/QuickGUILabel.cpp
VisualEntertainmentAndTechnologies/VENT-QuickGUI
7c687193001bcf914bd4a9947644915091ea8723
[ "Unlicense" ]
null
null
null
QuickGUI/src/QuickGUILabel.cpp
VisualEntertainmentAndTechnologies/VENT-QuickGUI
7c687193001bcf914bd4a9947644915091ea8723
[ "Unlicense" ]
null
null
null
#include "QuickGUILabel.h" #include "QuickGUISkinDefinitionManager.h" #include "QuickGUISkinDefinition.h" namespace QuickGUI { const Ogre::String Label::BACKGROUND = "background"; void Label::registerSkinDefinition() { SkinDefinition* d = OGRE_NEW_T(SkinDefinition,Ogre::MEMCATEGORY_GENERAL)("Label"); d->defineSkinElement(BACKGROUND); d->definitionComplete(); SkinDefinitionManager::getSingleton().registerSkinDefinition("Label",d); } LabelDesc::LabelDesc() : WidgetDesc(), TextUserDesc() { resetToDefault(); } void LabelDesc::resetToDefault() { WidgetDesc::resetToDefault(); TextUserDesc::resetToDefault(); widget_dimensions.size = Size::ZERO; widget_minSize = Size::ZERO; label_verticalTextAlignment = TEXT_ALIGNMENT_VERTICAL_CENTER; } void LabelDesc::serialize(SerialBase* b) { WidgetDesc::serialize(b); b->IO("VerticalTextAlignment",&label_verticalTextAlignment); TextUserDesc::serialize(b); } Label::Label(const Ogre::String& name) : Widget(name), TextUser() { } Label::~Label() { } void Label::_initialize(WidgetDesc* d) { Widget::_initialize(d); mDesc = dynamic_cast<LabelDesc*>(mWidgetDesc); LabelDesc* ld = dynamic_cast<LabelDesc*>(d); setSkinType(d->widget_skinTypeName); // Make a copy of the Text Desc. The Text object will // modify it directly, which is umSkinElementd for mSkinElementrialization. mDesc->textDesc = ld->textDesc; if(mDesc->widget_dimensions.size.width == 1) { if(mDesc->textDesc.segments.empty()) mDesc->widget_dimensions.size.width = 50; else mDesc->widget_dimensions.size.width = mSkinElement->getBorderThickness(BORDER_LEFT) + mDesc->textDesc.getTextWidth() + mSkinElement->getBorderThickness(BORDER_RIGHT); } if(mDesc->widget_dimensions.size.height == 1) { if(mDesc->textDesc.segments.empty()) mDesc->widget_dimensions.size.height = 20; else mDesc->widget_dimensions.size.height = mSkinElement->getBorderThickness(BORDER_TOP) + mDesc->textDesc.getTextHeight() + mSkinElement->getBorderThickness(BORDER_BOTTOM); } // Now that dimensions may have changed, update client dimensions updateClientDimensions(); mDesc->label_verticalTextAlignment = ld->label_verticalTextAlignment; mDesc->textDesc.allottedWidth = mDesc->widget_dimensions.size.width - (mSkinElement->getBorderThickness(BORDER_LEFT) + mSkinElement->getBorderThickness(BORDER_RIGHT)); TextUser::_initialize(this,mDesc); } Ogre::String Label::getClass() { return "Label"; } VerticalTextAlignment Label::getVerticalTextAlignment() { return mDesc->label_verticalTextAlignment; } void Label::onDraw() { Brush* brush = Brush::getSingletonPtr(); brush->setFilterMode(mDesc->widget_brushFilterMode); brush->drawSkinElement(Rect(mTexturePosition,mWidgetDesc->widget_dimensions.size),mSkinElement); ColourValue prevColor = brush->getColour(); Rect prevClipRegion = brush->getClipRegion(); // Center Text Vertically float textHeight = mText->getTextHeight(); float yPos = 0; switch(mDesc->label_verticalTextAlignment) { case TEXT_ALIGNMENT_VERTICAL_BOTTOM: yPos = mDesc->widget_dimensions.size.height - mSkinElement->getBorderThickness(BORDER_BOTTOM) - textHeight; break; case TEXT_ALIGNMENT_VERTICAL_CENTER: yPos = (mDesc->widget_dimensions.size.height / 2.0) - (textHeight / 2.0); break; case TEXT_ALIGNMENT_VERTICAL_TOP: yPos = mSkinElement->getBorderThickness(BORDER_TOP); break; } // Clip to client dimensions Rect clipRegion(mClientDimensions); clipRegion.translate(mTexturePosition); brush->setClipRegion(prevClipRegion.getIntersection(clipRegion)); // Adjust Rect to Text drawing region clipRegion = mClientDimensions; clipRegion.position.y = yPos; clipRegion.translate(mTexturePosition); mText->draw(clipRegion.position); brush->setClipRegion(prevClipRegion); brush->setColor(prevColor); } void Label::setVerticalTextAlignment(VerticalTextAlignment a) { mDesc->label_verticalTextAlignment = a; redraw(); } void Label::updateClientDimensions() { Widget::updateClientDimensions(); if(mText != NULL) mText->setAllottedWidth(mClientDimensions.size.width); redraw(); } }
26.72561
173
0.71937
VisualEntertainmentAndTechnologies
b2160e725a2c271f3b1639a4c68c3d3c7a03e9c7
129
cpp
C++
dependencies/physx-4.1/source/lowlevel/common/src/pipeline/PxcMaterialMesh.cpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
dependencies/physx-4.1/source/lowlevel/common/src/pipeline/PxcMaterialMesh.cpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
dependencies/physx-4.1/source/lowlevel/common/src/pipeline/PxcMaterialMesh.cpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
version https://git-lfs.github.com/spec/v1 oid sha256:cec3dd4f00e26ea2aebec0b1e380637c61b78ff4a46e1690b39b52adb5f0b3fb size 4431
32.25
75
0.883721
realtehcman
b21a444cb7f8bc13be4bba8bfd44d3e80de669cf
501
hpp
C++
include/mgcpp/type_traits/shape_type.hpp
MGfoundation/mgcpp
66c072191e58871637bcb3b76701a79a4ae89779
[ "BSL-1.0" ]
48
2018-01-02T03:47:18.000Z
2021-09-09T05:55:45.000Z
include/mgcpp/type_traits/shape_type.hpp
MGfoundation/mgcpp
66c072191e58871637bcb3b76701a79a4ae89779
[ "BSL-1.0" ]
24
2017-12-27T18:03:13.000Z
2018-07-02T09:00:30.000Z
include/mgcpp/type_traits/shape_type.hpp
MGfoundation/mgcpp
66c072191e58871637bcb3b76701a79a4ae89779
[ "BSL-1.0" ]
6
2018-01-14T14:06:10.000Z
2018-10-16T08:43:01.000Z
#ifndef SHAPE_TYPE_HPP #define SHAPE_TYPE_HPP #include <mgcpp/global/shape.hpp> #include <tuple> #include <type_traits> namespace mgcpp { template <typename T> struct has_shape { private: typedef char one; typedef struct { char array[2]; } two; template <typename C> static one test(typename C::shape_type*); template <typename C> static two test(...); public: static const bool value = sizeof(test<T>(0)) == sizeof(one); }; } // namespace mgcpp #endif // SHAPE_TYPE_HPP
17.275862
62
0.694611
MGfoundation
b220f6bdb7a564b32df4d09a4d864b9cde5a25a5
1,975
cpp
C++
src/commandparameters.cpp
tapir-dream/berserkJS
6c2820ead3a3319b910b8bad9f1c0d9cb02f450d
[ "BSD-3-Clause" ]
409
2015-01-10T15:20:39.000Z
2022-03-17T04:44:22.000Z
src/commandparameters.cpp
mba811/berserkJS
7effebd3aa9b8918fcbe41f7a073075bc531b726
[ "BSD-3-Clause" ]
7
2015-01-16T03:43:03.000Z
2018-07-12T13:06:27.000Z
src/commandparameters.cpp
mba811/berserkJS
7effebd3aa9b8918fcbe41f7a073075bc531b726
[ "BSD-3-Clause" ]
82
2015-01-04T15:49:37.000Z
2022-03-17T04:44:24.000Z
#include "commandparameters.h" CommandParameters::CommandParameters() { params = getParams(); } QMap<QString, QString> CommandParameters::getParams() { int argc = qApp->argc(); char **argv = qApp->argv(); QMap<QString, QString> params; // Parse command line parameters for (int ax = 1; ax < argc; ++ax) { size_t nlen; const char* s = argv[ax]; const char* value; value = strchr(s, '='); if (value == NULL) { if (strncmp("--help", s, 6) == 0) { params["help"] = "1"; } else if (strncmp("--start", s, 7) == 0) { params["start"] = "1"; } else if (strncmp("--command", s, 9) == 0) { params["command"] = "1"; } else if (strncmp("--version", s, 9) == 0) { params["version"] = "1"; } else if (strncmp("--cache", s, 7) == 0) { params["cache"] = "1"; } continue; } nlen = value++ - s; // --name=value options if (strncmp("--start", s, nlen) == 0) { params["start"] = value; } else if (strncmp("--script", s, nlen) == 0) { params["script"] = value; } else if (strncmp("--command", s, nlen) == 0) { params["command"] = value; } else if (strncmp("--help", s, nlen) == 0) { params["help"] = value; } else { //error continue; } } return params; } bool CommandParameters::isCommandMode() { return params.contains("command"); } bool CommandParameters::hasStart() { return params.contains("start"); } bool CommandParameters::hasScript() { return params.contains("script") && params["script"] != ""; } bool CommandParameters::hasHelp() { return params.contains("help"); } bool CommandParameters::hasVersion() { return params.contains("version") && params["version"] != ""; } bool CommandParameters::hasCache() { return params.contains("cache"); }
21.944444
65
0.521013
tapir-dream
b221cb8585edd6d49d99efb122d853221d748675
426
cpp
C++
Examples/Example3/main.cpp
naddu77/CubbyMenu
8889873d377e62589e10e89ebe01ec739cf86752
[ "MIT" ]
16
2020-12-20T18:24:06.000Z
2021-04-04T12:07:31.000Z
Examples/Example3/main.cpp
naddu77/CubbyMenu
8889873d377e62589e10e89ebe01ec739cf86752
[ "MIT" ]
2
2020-12-23T04:15:42.000Z
2020-12-23T14:46:47.000Z
Examples/Example3/main.cpp
naddu77/CubbyMenu
8889873d377e62589e10e89ebe01ec739cf86752
[ "MIT" ]
4
2020-12-22T14:40:18.000Z
2020-12-26T00:19:50.000Z
#include <CubbyMenu/CubbyMenu.hpp> #include <iostream> void option0() { std::cout << "Option 0 is called!\n"; } void option1() { std::cout << "Option 1 is called!\n"; } void option2() { std::cout << "Option 2 is called!\n"; } int main() { CubbyMenu::Menu menu; menu.add_item("Option 0", &option0); menu.add_item("Option 1", &option1); menu.add_item("Option 2", &option2); menu.print(); }
14.689655
41
0.600939
naddu77
b223d6629ab0b4063c57f2ef792f69dd445b9f74
20,221
cpp
C++
src/calc_wave_func_bilayer.cpp
suwamaro/rpa
fc9d37f03705334ee17b77de6ad2b8feab3cc7b0
[ "Apache-2.0" ]
null
null
null
src/calc_wave_func_bilayer.cpp
suwamaro/rpa
fc9d37f03705334ee17b77de6ad2b8feab3cc7b0
[ "Apache-2.0" ]
null
null
null
src/calc_wave_func_bilayer.cpp
suwamaro/rpa
fc9d37f03705334ee17b77de6ad2b8feab3cc7b0
[ "Apache-2.0" ]
null
null
null
/***************************************************************************** * * Functions for calculating the wave function * * Copyright (C) 2018 by Hidemaro Suwa * e-mail:suwamaro@phys.s.u-tokyo.ac.jp * *****************************************************************************/ #include <complex> #ifdef WITH_OpenMP #include <omp.h> #endif #include "calc_intensity.h" #include "calc_spectrum.h" #include "self_consistent_eq.h" #include "calc_gap.h" #include "calc_chemical_potential.h" #include "calc_wave_func.h" #include "BinarySearch.h" /* Creating an instance */ PhiDerIntegrandBilayer pdib; WaveFuncIntegrandBilayer wfib; /* Member functions of PhiDerIntegrand */ double PhiDerIntegrand::integrand(double omega, double delta, double zk, cx_double bk){ if ( delta == 0 ) { /* For U <= Uc */ double b = std::abs(bk); double g2 = std::pow(omega / (2.*b), 2); return 1. / ( std::pow(b,3) * std::pow( 1. - g2, 2) ); } else { /* For U > Uc */ return std::pow(zk,3) * (1. - zk*zk) / std::pow(1 - std::pow(omega*zk/(2.*delta), 2), 2); } } /* Member functions of PhiDerIntegrandBilayer */ void PhiDerIntegrandBilayer::set_parameters(hoppings_bilayer2 const& h, double omega, double delta){ hb_ = h; omega_ = omega; delta_ = delta; } int PhiDerIntegrandBilayer::calc(const int *ndim, const cubareal xx[], const int *ncomp, cubareal ff[], void *userdata) const { /* Reset */ ff[0] = 0; /* Wavenumbers */ double k1 = xx[0] * 2 * M_PI; double k2 = xx[1] * 2 * M_PI; double kx = 0.5 * (k2 + k1); double ky = 0.5 * (k2 - k1); /* Sum over kz */ for(int z=0; z < 2; z++){ double kz = M_PI * z; cx_double ek1 = ts()->ek1(kx, ky, kz); double zki = zk(ek1, ts()->tz, kz, delta()); cx_double bki = bk(up_spin, ek1, ts()->tz, kz); // spin does not matter. ff[0] += integrand(omega(), delta(), zki, bki); } return 0; } /* Member functions of WaveFuncIntegrandBilayer */ cx_double WaveFuncIntegrandBilayer::integrand(cx_double xk, double zk, cx_double bk, double ek_plus, double ek_minus, cx_double phase) const { if ( sublattice() == 0 ) { if ( largeUlimit() ) { return 0; } else { double ek_diff = ek_plus - ek_minus; return (double)spin() * (1. - zk*zk) / (2.*sqrt(psider())) * ek_diff / (omega()*omega() - ek_diff*ek_diff) * phase; } } else if ( sublattice() == 1 ) { if ( largeUlimit() ) { return 2. * std::conj(bk) / sqrt(psider()) / ( scaling_prefactor() + 2. * (std::norm(bk) - min_bk_sq()) ) * phase; } else { double ek_diff = ek_plus - ek_minus; return (double)spin() * std::conj(xk) * sqrt(1. - zk*zk) / (2.* sqrt(psider())) * ( (1.-spin()*zk) / (omega() - ek_diff) + (1.+spin()*zk) / (omega() + ek_diff) ) * phase; } } else { std::cerr << "\"sublattice_\" has to be 0 or 1." << std::endl; std::exit(EXIT_FAILURE); } } void WaveFuncIntegrandBilayer::set_parameters(hoppings_bilayer2 const& h, bool largeUlimit, double scaling_prefactor, int spin, double omega, double psider, double delta, int *diff_r, int sublattice, double min_bk_sq){ hb_ = h; largeUlimit_ = largeUlimit; scaling_prefactor_ = scaling_prefactor; spin_ = spin; omega_ = omega; psider_ = psider; delta_ = delta; for(int d=0; d < 3; d++){ diff_r_[d] = diff_r[d]; } sublattice_ = sublattice; min_bk_sq_ = min_bk_sq; } int WaveFuncIntegrandBilayer::calc(const int *ndim, const cubareal xx[], const int *ncomp, cubareal ff[], void *userdata) const { cx_double sum = 0; /* Wavenumbers */ double k1 = xx[0] * 2 * M_PI; double k2 = xx[1] * 2 * M_PI; double kx = 0.5 * (k2 + k1); double ky = 0.5 * (k2 - k1); /* Sum over kz */ for(int z=0; z < 2; z++){ double kz = M_PI * z; cx_double ek1 = ts()->ek1(kx, ky, kz); cx_double ek23 = ts()->ek23(kx, ky, kz); cx_double ekz = ts()->ekz(kx, ky, kz); cx_double xki = xk(spin(), ek1, ts()->tz, kz, delta()); double zki = zk(ek1, ts()->tz, kz, delta()); cx_double bki = bk(spin(), ek1, ts()->tz, kz); double ek_plus = eigenenergy_HF(1., ek1, ek23, ekz, ts()->tz, kz, delta()); double ek_minus = eigenenergy_HF(-1., ek1, ek23, ekz, ts()->tz, kz, delta()); cx_double pure_i(0,1); double inner_prod = kx * diff_r(0) + ky * diff_r(1) + kz * diff_r(2); cx_double phase = exp(pure_i*inner_prod); sum += integrand(xki, zki, bki, ek_plus, ek_minus, phase); } ff[0] = std::real(sum); ff[1] = std::imag(sum); return 0; } int pd_integrand_bilayer(const int *ndim, const cubareal xx[], const int *ncomp, cubareal ff[], void *userdata){ return pdib.calc(ndim, xx, ncomp, ff, userdata); } int wf_integrand_bilayer(const int *ndim, const cubareal xx[], const int *ncomp, cubareal ff[], void *userdata){ return wfib.calc(ndim, xx, ncomp, ff, userdata); } double pole_eq_bilayer(int L, hoppings_bilayer2 const& ts, double omega, double mu, double U, double T, double delta, CubaParam const& cbp, Polarization const& Pz, bool continuous_k, std::string const& mode){ arma::cx_mat chi0_pm(NSUBL,NSUBL,arma::fill::zeros); arma::cx_mat chi0_zz(NSUBL,NSUBL,arma::fill::zeros); /* Calculating the bare response functions */ std::tie(chi0_pm, chi0_zz) = calc_bare_response_bilayer(L, ts, mu, U, T, delta, cbp, Pz, omega, continuous_k); cx_double det = 0; if ( mode == "transverse" ) { det = arma::det(arma::eye<arma::cx_mat>(NSUBL,NSUBL) - U * chi0_pm); } else if ( mode == "longitudinal" ) { det = arma::det(arma::eye<arma::cx_mat>(NSUBL,NSUBL) - 0.5 * U * chi0_zz); } else { std::cerr << "\"mode\" has to be \"transverse\" or \"longitudinal\"." << std::endl; std::exit(EXIT_FAILURE); } return std::real(det); /* Assume that the imaginary part is 0. */ } double calc_band_gap_bilayer(int L, hoppings_bilayer2 const& ts, double delta, double qx, double qy, double qz){ double k1 = 2. * M_PI / (double)L; double E_diff_min = std::numeric_limits<double>::max(); cx_double tz = ts.tz; for(int z=0; z < 2; z++){ double kz = M_PI * z; for(int x=-L/2; x < L/2; x++){ double kx = k1 * x; for(int y=-L/2; y < L/2; y++){ double ky = k1 * y; cx_double ek1 = ts.ek1(kx, ky, kz); cx_double ek23 = ts.ek23(kx, ky, kz); cx_double ekz = ts.ekz(kx, ky, kz); double kx2 = kx + qx; double ky2 = ky + qy; double kz2 = kz + qz; cx_double ek_q1 = ts.ek1( kx2, ky2, kz2 ); cx_double ek_q23 = ts.ek23( kx2, ky2, kz2 ); cx_double ek_qz = ts.ekz( kx2, ky2, kz2 ); double Ek_plus = eigenenergy_HF(1., ek_q1, ek_q23, ek_qz, tz, kz2, delta); double Ek_minus = eigenenergy_HF(-1., ek1, ek23, ekz, tz, kz, delta); double E_diff = std::max( 0., Ek_plus - Ek_minus ); E_diff_min = std::min( E_diff_min, E_diff ); } /* end for y */ } /* end for x */ } /* end for z */ return E_diff_min; } double solve_pole_eq_bilayer(int L, hoppings_bilayer2 const& ts, double mu, double U, double T, double delta, CubaParam const& cbp, Polarization const& Pz, bool continuous_k, std::string const& mode, double upper){ std::cout << "Solving the pole equation for U=" << U << std::endl; double target = 0; double omega = 0.5 * upper; using std::placeholders::_1; auto pe = std::bind( pole_eq_bilayer, L, std::ref(ts), _1, mu, U, T, delta, std::ref(cbp), std::ref(Pz), continuous_k, mode ); BinarySearch bs(continuous_k); bs.set_x_MIN(0); double omega_eps = 1e-5; // double omega_eps = 1e-7; bs.set_x_MAX(upper - omega_eps); bool sol_found = bs.find_solution( omega, target, pe, false, 0, true ); if ( sol_found ) { return omega; } else { return 0; } } std::tuple<double, double, double> calc_gap_bilayer(int L, hoppings_bilayer2 const& ts, double mu, double U, double T, double delta, CubaParam const& cbp, Polarization const& Pz, bool continuous_k){ double upper = calc_band_gap_bilayer(L, ts, delta, Pz.qx(), Pz.qy(), Pz.qz()); double omega_T = solve_pole_eq_bilayer(L, ts, mu, U, T, delta, cbp, Pz, continuous_k, "transverse", upper); double omega_L = solve_pole_eq_bilayer(L, ts, mu, U, T, delta, cbp, Pz, continuous_k, "longitudinal", upper); return std::make_tuple(omega_T, omega_L, upper); } double calc_Psider(int L, hoppings_bilayer2 const& ts, double mu, double omega, double delta, CubaParam const& cbp, bool continuous_k){ double Psider = 0; if ( continuous_k ) { /* Changing the parameters */ pdib.set_parameters(ts, omega, delta); /* For Cuba */ double epsrel = 1e-10; double epsabs = 1e-10; int ncomp = 1; int nregions, neval, fail; cubareal integral[ncomp], error[ncomp], prob[ncomp]; /* Cuhre */ Cuhre(cbp.NDIM, ncomp, pd_integrand_bilayer, cbp.userdata, cbp.nvec, epsrel, epsabs, cbp.flags, cbp.mineval, cbp.maxeval, cbp.key, cbp.statefile, cbp.spin, &nregions, &neval, &fail, integral, error, prob); // for check printf("CUHRE RESULT:\tnregions %d\tneval %d\tfail %d\n", nregions, neval, fail); // for(int comp = 0; comp < ncomp; comp++ ) // printf("CUHRE RESULT:\t%.8f +- %.8f\tp = %.3f\n", // (double)integral[comp], (double)error[comp], (double)prob[comp]); if ( delta == 0 ) { Psider = integral[0] * omega / std::pow(2, 3); } else { Psider = integral[0] * omega / std::pow(2*delta, 3); } } else { double eps = 1e-12; double k1 = 2. * M_PI / (double)L; for(int z=0; z < 2; z++){ double kz = M_PI * z; for(int x=-L/2; x < L/2; x++){ double kx = k1 * x; for(int y=-L/2; y < L/2; y++){ double ky = k1 * y; /* Checking if k is inside/outside the BZ. */ double mu_free = 0; /* Assume at half filling */ double e_free = energy_free_electron( 1., mu_free, kx, ky ); /* ad-hoc */ if ( e_free > mu_free + eps ) continue; /* Prefactor */ double factor = 1.; /* On the zone boundary */ if ( std::abs(e_free - mu_free) < eps ) { factor = 0.5; } /* Sum of the Fourier transformed hoppings */ cx_double ek1 = ts.ek1(kx, ky, kz); double zki = zk(ek1, ts.tz, kz, delta); cx_double bki = bk(up_spin, ek1, ts.tz, kz); // spin does not matter. Psider += factor * PhiDerIntegrand::integrand(omega, delta, zki, bki); } /* end for y */ } /* end for x */ } /* end for z */ int n_sites = L * L * 2; int n_unit_cell = n_sites / 2; if ( delta == 0 ) { Psider *= 2. * omega / std::pow(2., 3) / (double)n_unit_cell; } else { Psider *= 2. * omega / std::pow(2*delta, 3) / (double)n_unit_cell; } } return Psider; } double calc_min_bk_sq_bilayer(int L, hoppings2 const& ts){ /* Finite size */ double k1 = 2. * M_PI / (double)L; double min_bk_sq = std::numeric_limits<double>::max(); for(int z=0; z < 2; z++){ double kz = M_PI * z; for(int x=-L/2; x < L/2; x++){ double kx = k1 * x; for(int y=-L/2; y < L/2; y++){ double ky = k1 * y; cx_double ek1 = ts.ek1(kx, ky, kz); cx_double bki = bk(up_spin, ek1, ts.tz, kz); // spin does not matter. min_bk_sq = std::min( min_bk_sq, std::norm(bki) ); } /* end for y */ } /* end for x */ } /* end for z */ return min_bk_sq; } double calc_weight_distribution_bilayer(int L, hoppings_bilayer2 const& ts, CubaParam const& cbp, Polarization const& Pz, bool continuous_k, int *diff_r){ cx_double wavefunc = 0; if ( continuous_k ) { /* For Cuba */ double epsrel = 1e-10; double epsabs = 1e-10; int ncomp = 2; int nregions, neval, fail; cubareal integral[ncomp], error[ncomp], prob[ncomp]; /* Cuhre */ Cuhre(cbp.NDIM, ncomp, wf_integrand_bilayer, cbp.userdata, cbp.nvec, epsrel, epsabs, cbp.flags, cbp.mineval, cbp.maxeval, cbp.key, cbp.statefile, cbp.spin, &nregions, &neval, &fail, integral, error, prob); // for check printf("CUHRE RESULT:\tnregions %d\tneval %d\tfail %d\n", nregions, neval, fail); // for(int comp = 0; comp < ncomp; comp++ ) // printf("CUHRE RESULT:\t%.8f +- %.8f\tp = %.3f\n", // (double)integral[comp], (double)error[comp], (double)prob[comp]); wavefunc = { integral[0] / 2., integral[1] / 2. }; } else { double eps = 1e-12; double k1 = 2. * M_PI / (double)L; for(int z=0; z < 2; z++){ double kz = M_PI * z; for(int x=-L/2; x < L/2; x++){ double kx = k1 * x; for(int y=-L/2; y < L/2; y++){ double ky = k1 * y; /* Checking if k is inside/outside the BZ. */ double mu_free = 0; /* Assume at half filling */ double e_free = energy_free_electron( 1., mu_free, kx, ky ); /* ad-hoc */ if ( e_free > mu_free + eps ) continue; /* Prefactor */ double factor = 1.; /* On the zone boundary */ if ( std::abs(e_free - mu_free) < eps ) { factor = 0.5; } cx_double ek1 = ts.ek1(kx, ky, kz); cx_double ek23 = ts.ek23(kx, ky, kz); cx_double ekz = ts.ekz(kx, ky, kz); cx_double xki = xk(wfib.spin(), ek1, ts.tz, kz, wfib.delta()); double zki = zk(ek1, ts.tz, kz, wfib.delta()); cx_double bki = bk(wfib.spin(), ek1, ts.tz, kz); double ek_plus = eigenenergy_HF(1., ek1, ek23, ekz, ts.tz, kz, wfib.delta()); double ek_minus = eigenenergy_HF(-1., ek1, ek23, ekz, ts.tz, kz, wfib.delta()); cx_double pure_i(0,1); double inner_prod = kx * diff_r[0] + ky * diff_r[1] + kz * diff_r[2]; cx_double phase = exp(pure_i*inner_prod); wavefunc += factor * wfib.integrand(xki, zki, bki, ek_plus, ek_minus, phase); } /* end for y */ } /* end for x */ } /* end for z */ int n_sites = L * L * 2; int n_unit_cell = n_sites / 2; wavefunc /= (double)n_unit_cell; } cx_double pure_i(0,1); double inner_prod2 = Pz.qx() * diff_r[0] + Pz.qy() * diff_r[1] + Pz.qz() * diff_r[2]; // Assume that the origin is (0,0,0). cx_double phase2 = exp(0.5*pure_i*inner_prod2); wavefunc *= phase2; return std::norm(wavefunc); } void calc_wave_func_bilayer(path& base_dir, rpa::parameters const& pr){ /* Getting parameters */ int L = pr.L; int Lk = pr.Lk; double U = pr.U; double filling = pr.filling; double T = pr.T; bool continuous_k = pr.continuous_k; /* Hopping parameters */ std::unique_ptr<hoppings_bilayer2> ts = hoppings_bilayer2::mk_bilayer3(pr); /* Parameters for Cuba */ CubaParam cbp(pr); /* Calculate the chemical potential and the charge gap. */ double delta = solve_self_consistent_eq_bilayer2( L, *ts, U, filling, T, cbp, continuous_k ); std::cout << "delta = " << delta << std::endl; /* Assume that mu does not depend on L for integral over continuous k. */ double ch_gap, mu; std::tie(ch_gap, mu) = calc_charge_gap_bilayer( L, *ts, delta ); /* Finite size */ // double mu = calc_chemical_potential_bilayer2( base_dir, L, *ts, delta ); /* Finite size */ /* Output */ ofstream out_gap; out_gap.open(base_dir / "gap.text"); out_gap << "Charge gap = " << ch_gap << std::endl; out_gap << "mu = " << mu << std::endl; /* Precision */ int prec = 15; /* Polarization */ Polarization Pz( L, L, 2, NSUBL ); /* Setting the ordering vector */ Pz.set_q( M_PI, M_PI, M_PI ); if ( !continuous_k ) { /* The polarizations are calculated in advance. */ Pz.set_table( *ts, delta ); } /* Calculating gaps */ double omega_T = 0, omega_L = 0, omega_ph = 0; std::tie(omega_T, omega_L, omega_ph) = calc_gap_bilayer(L, *ts, mu, U, T, delta, cbp, Pz, continuous_k); /* Output */ out_gap << "omega_T = " << omega_T << std::endl; out_gap << "omega_L = " << omega_L << std::endl; out_gap << "omega_ph = " << omega_ph << std::endl; /* Calculating Psi'*/ double Psider = calc_Psider(L, *ts, mu, omega_L, delta, cbp, continuous_k); /* Output */ out_gap << "Psider = " << Psider << std::endl; /* Output */ ofstream out_prob; out_prob.open(base_dir / "weight-distribution.text"); out_prob << "# x y z P(r)" << std::endl; /* Calculating the minimum bk square */ double min_bk_sq = calc_min_bk_sq_bilayer(L, *ts); /* Calculating the weight distribution of the exciton eigenstate */ int spin = -1; // down electron and down hole int dL = 10; for(int dx=-dL; dx <= dL; dx++){ for(int dy=-dL; dy <= dL; dy++){ for(int dz=0; dz <= 1; dz++){ int diff_r[] = {dx, dy, dz}; int sublattice = (dx+dy+dz) & 1; /* Setting the parameters */ wfib.set_parameters(*ts, pr.largeUlimit, pr.largeU_scaling_prefactor, spin, omega_L, Psider, delta, diff_r, sublattice, min_bk_sq); /* Calculating the weight distribution */ double prob = calc_weight_distribution_bilayer(L, *ts, cbp, Pz, continuous_k, diff_r); /* Output */ out_prob << dx << std::setw(10) << dy << std::setw(10) << dz << std::setw(20) << prob << std::endl; } } } out_gap.close(); out_prob.close(); } void check_wave_func_bilayer(path& base_dir, rpa::parameters const& pr){ /* Getting parameters */ int L = pr.L; int Lk = pr.Lk; double U = pr.U; double filling = pr.filling; double T = pr.T; bool continuous_k = pr.continuous_k; /* Hopping parameters */ std::unique_ptr<hoppings_bilayer2> ts = hoppings_bilayer2::mk_bilayer3(pr); /* Parameters for Cuba */ CubaParam cbp(pr); /* Calculate the chemical potential and the charge gap. */ double delta = solve_self_consistent_eq_bilayer2( L, *ts, U, filling, T, cbp, continuous_k ); std::cout << "delta = " << delta << std::endl; /* Assume that mu does not depend on L for integral over continuous k. */ double ch_gap, mu; std::tie(ch_gap, mu) = calc_charge_gap_bilayer( L, *ts, delta ); /* Finite size */ // double mu = calc_chemical_potential_bilayer2( base_dir, L, *ts, delta ); /* Finite size */ /* Output */ ofstream out_gap; out_gap.open(base_dir / "gap.text"); out_gap << "Charge gap = " << ch_gap << std::endl; out_gap << "mu = " << mu << std::endl; /* Polarization */ Polarization Pz( L, L, 2, NSUBL ); /* Setting the ordering vector */ Pz.set_q( M_PI, M_PI, M_PI ); if ( !continuous_k ) { /* The polarizations are calculated in advance. */ Pz.set_table( *ts, delta ); } /* Calculating gaps */ double omega_T = 0, omega_L = 0, omega_ph = 0; std::tie(omega_T, omega_L, omega_ph) = calc_gap_bilayer(L, *ts, mu, U, T, delta, cbp, Pz, continuous_k); /* Output */ out_gap << "omega_T = " << omega_T << std::endl; out_gap << "omega_L = " << omega_L << std::endl; out_gap << "omega_ph = " << omega_ph << std::endl; /* Calculating Psi'*/ double Psider = 1.0; // double Psider = calc_Psider(L, *ts, mu, omega_L, delta, cbp, continuous_k); /* Output */ out_gap << "Psider = " << Psider << std::endl; /* Output */ ofstream out_wf; out_wf.open(base_dir / "exciton_wave_function-k.text"); out_wf << "# x y z P(r)" << std::endl; /* Calculating the minimum bk square */ double min_bk_sq = calc_min_bk_sq_bilayer(L, *ts); /* Calculating the wave function */ int spin = -1; // down electron and down hole int sublattice = 0; int diff_r[] = {0,0,0}; /* Setting the parameters */ wfib.set_parameters(*ts, pr.largeUlimit, pr.largeU_scaling_prefactor, spin, omega_L, Psider, delta, diff_r, sublattice, min_bk_sq); double k1 = 2. * M_PI / (double)L; for(int z=0; z < 2; z++){ double kz = M_PI * z; for(int x=-L/2; x < L/2; x++){ double kx = k1 * x; for(int y=-L/2; y < L/2; y++){ double ky = k1 * y; cx_double ek1 = ts->ek1(kx, ky, kz); cx_double ek23 = ts->ek23(kx, ky, kz); cx_double ekz = ts->ekz(kx, ky, kz); cx_double xki = xk(wfib.spin(), ek1, ts->tz, kz, wfib.delta()); double zki = zk(ek1, ts->tz, kz, wfib.delta()); cx_double bki = bk(wfib.spin(), ek1, ts->tz, kz); double ek_plus = eigenenergy_HF(1., ek1, ek23, ekz, ts->tz, kz, wfib.delta()); double ek_minus = eigenenergy_HF(-1., ek1, ek23, ekz, ts->tz, kz, wfib.delta()); double wavefunc = std::real(wfib.integrand(xki, zki, bki, ek_plus, ek_minus, 1.)); out_wf << kx << std::setw(15) << ky << std::setw(15) << kz << std::setw(15) << wavefunc << std::endl; } /* end for y */ } /* end for x */ } /* end for z */ out_gap.close(); out_wf.close(); }
34.565812
218
0.604916
suwamaro
b2257d98dd0c5114f0a653847b2d5c0e449038b8
1,285
cpp
C++
tapSynth-main/Source/Data/MeterData.cpp
34Audiovisual/Progetti_JUCE
d22d91d342939a8463823d7a7ec528bd2228e5f7
[ "MIT" ]
null
null
null
tapSynth-main/Source/Data/MeterData.cpp
34Audiovisual/Progetti_JUCE
d22d91d342939a8463823d7a7ec528bd2228e5f7
[ "MIT" ]
null
null
null
tapSynth-main/Source/Data/MeterData.cpp
34Audiovisual/Progetti_JUCE
d22d91d342939a8463823d7a7ec528bd2228e5f7
[ "MIT" ]
null
null
null
/* ============================================================================== MeterData.cpp Created: 27 Feb 2021 9:37:46pm Author: Joshua Hodge ============================================================================== */ #include "MeterData.h" void MeterData::processRMS (juce::AudioBuffer<float>& buffer) { // Running total of all samples in the callback float sum = 0; for (int ch = 0; ch < buffer.getNumChannels(); ++ch) { auto output = buffer.getReadPointer (ch); for (int s = 0; s < buffer.getNumSamples(); ++s) { auto squaredSample = output[s] * output[s]; sum+=squaredSample; } auto avg = sum / buffer.getNumSamples(); rms.store (std::sqrt (avg)); } } void MeterData::processPeak (juce::AudioBuffer<float>& buffer) { auto max = 0.0f; for (int ch = 0; ch < buffer.getNumChannels(); ++ch) { auto output = buffer.getReadPointer (ch); for (int s = 0; s < buffer.getNumSamples(); ++s) { auto abs = std::abs (output[s]); if (abs > max) max = abs; } peak.store (max); } }
22.946429
81
0.429572
34Audiovisual
b22933af4b43eb0e41f2621433e4363e8a3d800f
755
cpp
C++
src/prod/src/Transport/ClientAuthHeader.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/Transport/ClientAuthHeader.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/Transport/ClientAuthHeader.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" namespace Transport { ClientAuthHeader::ClientAuthHeader() { } ClientAuthHeader::ClientAuthHeader(SecurityProvider::Enum providerType) : providerType_(providerType) { } SecurityProvider::Enum ClientAuthHeader::ProviderType() { return providerType_; } void ClientAuthHeader::WriteTo(Common::TextWriter & w, Common::FormatOptions const &) const { w << providerType_; } }
26.034483
98
0.569536
vishnuk007
b230c55292dabf3db6e64ff2593c66aadc8aefe2
533
cpp
C++
Trem/src/trem/renderer/vertex_buffer.cpp
Tremah/TremEngine
29e04e69da84e4c60709854010376edc1b96dc0a
[ "MIT" ]
10
2021-01-17T01:48:31.000Z
2021-12-31T19:31:22.000Z
Trem/src/trem/renderer/vertex_buffer.cpp
Tremah/TremEngine
29e04e69da84e4c60709854010376edc1b96dc0a
[ "MIT" ]
null
null
null
Trem/src/trem/renderer/vertex_buffer.cpp
Tremah/TremEngine
29e04e69da84e4c60709854010376edc1b96dc0a
[ "MIT" ]
null
null
null
#include <trpch.h> #include "vertex_buffer.h" namespace Trem { VertexBuffer::VertexBuffer(uint32_t size) { glCreateBuffers(1, &vertexBufferID_); glBindBuffer(GL_ARRAY_BUFFER, vertexBufferID_); glBufferData(GL_ARRAY_BUFFER, size, nullptr, GL_STATIC_DRAW); } VertexBuffer::~VertexBuffer() { glDeleteBuffers(1, &vertexBufferID_); } void VertexBuffer::bind() const { glBindBuffer(GL_ARRAY_BUFFER, vertexBufferID_); } void VertexBuffer::unbind() { glBindBuffer(GL_ARRAY_BUFFER, 0); } }
19.035714
65
0.712946
Tremah
b233a79cbe979750371161c79e6a22fc44803493
601
cpp
C++
leetcode.com/0925 Long Pressed Name/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2020-08-20T11:02:49.000Z
2020-08-20T11:02:49.000Z
leetcode.com/0925 Long Pressed Name/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
null
null
null
leetcode.com/0925 Long Pressed Name/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2022-01-01T23:23:13.000Z
2022-01-01T23:23:13.000Z
#include <iostream> #include <vector> using namespace std; class Solution { public: bool isLongPressedName(string name, string typed) { int n1 = name.size(), n2 = typed.size(); if (n1 > n2) return false; else if (n1 == n2) return name == typed; int i = 0, j = 0; while (i < n1 && j < n2) { if (name[i] != typed[j]) return false; int ii = i + 1, jj = j + 1; while (name[ii] == name[i]) ++ii; while (typed[jj] == typed[j]) ++jj; if (jj - j < ii - i) return false; i = ii; j = jj; } return i == n1 && j == n2; } };
22.259259
53
0.499168
sky-bro
b239fc5220a9fb1a8b01248897a020b48fcfc0a1
1,008
cpp
C++
ShenShengYi/UT/UT/School_Test.cpp
shenshengyi/ShenShengYi
0b16b555d498c0bd17dd16f830343a5f2a1fd4e1
[ "MIT" ]
null
null
null
ShenShengYi/UT/UT/School_Test.cpp
shenshengyi/ShenShengYi
0b16b555d498c0bd17dd16f830343a5f2a1fd4e1
[ "MIT" ]
null
null
null
ShenShengYi/UT/UT/School_Test.cpp
shenshengyi/ShenShengYi
0b16b555d498c0bd17dd16f830343a5f2a1fd4e1
[ "MIT" ]
null
null
null
#include "pch.h" #include "School_Test.h" #include <Student.h> #include <iostream> using namespace std; void School_Test::SetUpTestCase(void) { } void School_Test::TearDownTestCase(void) { } void School_Test::SetUp() { _shool = STU::School::GetInstance(); } void School_Test::TearDown() { STU::School::Release(); } int add1(int a, int b) { return a + b; } TEST_F(School_Test, GetStudentNum) { _shool->AddStudent(); int num = _shool->GetStudentNum(); auto result = _shool->FindStudentByClassNum(5); for (auto student : result) { cout << student->GetStudentInformation().GetClassNum() << endl; } //STU::Student** studentBegin = _shool->StudentIteratorBegin(); //STU::Student** studentEnd = _shool->StudentIteratorEnd(); //int i = 0; //while (studentBegin != studentEnd) { // if (nullptr != studentBegin) { // cout << (*studentBegin)->GetStudentInformation().GetName() << " " << (*studentBegin)->GetStudentInformation().GetClassNum() << endl; // } // studentBegin++; // i++; //} }
22.909091
138
0.672619
shenshengyi
b24710c2e9df42d01256f3184b3eb3f987734dbf
3,975
cpp
C++
src/MultiLayerOptics/src/AbsorptancesMultiPane.cpp
bakonyidani/Windows-CalcEngine
afa4c4a9f88199c6206af8bc994a073931fc8b91
[ "BSD-3-Clause-LBNL" ]
null
null
null
src/MultiLayerOptics/src/AbsorptancesMultiPane.cpp
bakonyidani/Windows-CalcEngine
afa4c4a9f88199c6206af8bc994a073931fc8b91
[ "BSD-3-Clause-LBNL" ]
null
null
null
src/MultiLayerOptics/src/AbsorptancesMultiPane.cpp
bakonyidani/Windows-CalcEngine
afa4c4a9f88199c6206af8bc994a073931fc8b91
[ "BSD-3-Clause-LBNL" ]
null
null
null
#include "AbsorptancesMultiPane.hpp" #include "WCECommon.hpp" using namespace FenestrationCommon; namespace MultiLayerOptics { CAbsorptancesMultiPane::CAbsorptancesMultiPane( const std::shared_ptr< const CSeries >& t_T, const std::shared_ptr< const CSeries >& t_Rf, const std::shared_ptr< const CSeries >& t_Rb ) : m_StateCalculated( false ) { m_T.push_back( t_T ); m_Rf.push_back( t_Rf ); m_Rb.push_back( t_Rb ); } void CAbsorptancesMultiPane::addLayer( const std::shared_ptr< const CSeries >& t_T, const std::shared_ptr< const CSeries >& t_Rf, const std::shared_ptr< const CSeries >& t_Rb ) { m_T.push_back( t_T ); m_Rf.push_back( t_Rf ); m_Rb.push_back( t_Rb ); m_StateCalculated = false; } std::shared_ptr< CSeries > CAbsorptancesMultiPane::Abs( size_t const Index ) { calculateState(); std::shared_ptr< CSeries > aAbs = nullptr; if ( Index < m_Abs.size() ) { aAbs = m_Abs[ Index ]; } return aAbs; } size_t CAbsorptancesMultiPane::numOfLayers() { calculateState(); return m_Abs.size(); } void CAbsorptancesMultiPane::calculateState() { if ( !m_StateCalculated ) { size_t size = m_T.size(); // Calculate r and t coefficients std::shared_ptr< CSeries > r = std::make_shared< CSeries >(); std::shared_ptr< CSeries > t = std::make_shared< CSeries >(); std::vector< double > wv = m_T[ size - 1 ]->getXArray(); r->setConstantValues( wv, 0 ); t->setConstantValues( wv, 0 ); m_rCoeffs.clear(); m_tCoeffs.clear(); // layers loop for ( int i = int( size ) - 1; i >= 0; --i ) { t = tCoeffs( *m_T[ i ], *m_Rb[ i ], *r ); r = rCoeffs( *m_T[ i ], *m_Rf[ i ], *m_Rb[ i ], *r ); m_rCoeffs.insert( m_rCoeffs.begin(), r ); m_tCoeffs.insert( m_tCoeffs.begin(), t ); } // Calculate normalized radiances size = m_rCoeffs.size(); std::vector< std::shared_ptr< CSeries > > Iplus; std::vector< std::shared_ptr< CSeries > > Iminus; std::shared_ptr< CSeries > Im = std::make_shared< CSeries >(); std::shared_ptr< CSeries > Ip = nullptr; Im->setConstantValues( wv, 1 ); Iminus.push_back( Im ); for ( size_t i = 0; i < size; ++i ) { Ip = m_rCoeffs[ i ]->mMult( *Im ); Im = m_tCoeffs[ i ]->mMult( *Im ); Iplus.push_back( Ip ); Iminus.push_back( Im ); } Ip = std::make_shared< CSeries >(); Ip->setConstantValues( wv, 0 ); Iplus.push_back( Ip ); // Calculate absorptances m_Abs.clear(); size = Iminus.size(); for ( size_t i = 0; i < size - 1; ++i ) { std::shared_ptr< CSeries > Iincoming = Iminus[ i ]->mSub( *Iplus[ i ] ); std::shared_ptr< CSeries > Ioutgoing = Iminus[ i + 1 ]->mSub( *Iplus[ i + 1 ] ); std::shared_ptr< CSeries > layerAbs = Iincoming->mSub( *Ioutgoing ); m_Abs.push_back( layerAbs ); } } } std::shared_ptr< CSeries > CAbsorptancesMultiPane::rCoeffs( const CSeries& t_T, const CSeries& t_Rf, const CSeries& t_Rb, const CSeries& t_RCoeffs ) { std::shared_ptr< CSeries > rCoeffs = std::make_shared< CSeries >(); size_t size = t_T.size(); for ( size_t i = 0; i < size; ++i ) { double wl = t_T[ i ].x(); double rValue = t_Rf[ i ].value() + t_T[ i ].value() * t_T[ i ].value() * t_RCoeffs[ i ].value() / ( 1 - t_Rb[ i ].value() * t_RCoeffs[ i ].value() ); rCoeffs->addProperty( wl, rValue ); } return rCoeffs; } std::shared_ptr< CSeries > CAbsorptancesMultiPane::tCoeffs( const CSeries& t_T, const CSeries& t_Rb, const CSeries& t_RCoeffs ) { std::shared_ptr< CSeries > tCoeffs = std::make_shared< CSeries >(); size_t size = t_T.size(); for ( size_t i = 0; i < size; ++i ) { double wl = t_T[ i ].x(); double tValue = t_T[ i ].value() / ( 1 - t_Rb[ i ].value() * t_RCoeffs[ i ].value() ); tCoeffs->addProperty( wl, tValue ); } return tCoeffs; } }
30.576923
126
0.598491
bakonyidani
b24b45c453a0f8325feff47a9040a4a8d6e53588
1,029
hpp
C++
DemoProject/FarmGame/BaseFarmState.hpp
spywhere/Legacy-ParticlePlay
0c1ec6e4706f72b64e0408cc79cdeffce535b484
[ "BSD-3-Clause" ]
null
null
null
DemoProject/FarmGame/BaseFarmState.hpp
spywhere/Legacy-ParticlePlay
0c1ec6e4706f72b64e0408cc79cdeffce535b484
[ "BSD-3-Clause" ]
null
null
null
DemoProject/FarmGame/BaseFarmState.hpp
spywhere/Legacy-ParticlePlay
0c1ec6e4706f72b64e0408cc79cdeffce535b484
[ "BSD-3-Clause" ]
null
null
null
#ifndef BASEFARMSTATE_HEADER #define BASEFARMSTATE_HEADER #include <string> #include <ParticlePlay/ParticlePlay.hpp> #include "Spritesheet.hpp" #include "Tile.hpp" #include "Entity.hpp" class BaseFarmState : public ppState { protected: ppGUI* gui; ppIMS* ims; Spritesheet* spritesheet; Tile* grassTile, *dirtTile, *waterTile; int gameTime, timeSec, timeSpeed; void RenderNumber(ppGraphics* graphics, int x, int y, int number); void RenderText(ppGraphics* graphics, int x, int y, const char *time); std::string FormatTime(int time); std::string FormatNumber(int number); public: virtual void InitEntities()=0; virtual void RenderEntities(ppGraphics* graphics, int delta)=0; virtual void Render(ppGraphics* graphics, int delta); virtual void UpdateEntities(ppInput* input, int delta)=0; virtual void Update(ppInput* input, int delta)=0; virtual void InitSounds()=0; virtual void InitMusic()=0; void OnInit(); void OnRender(ppGraphics* graphics, int delta); void OnUpdate(ppInput* input, int delta); }; #endif
29.4
71
0.759961
spywhere
b24dae266c1704cf575597ba7625ab5c08cb0da0
22,520
cpp
C++
SimSpark/rcssserver3d/plugin/soccer/soccerbase/soccerbase.cpp
IllyasvielEin/Robocup3dInstaller
12e91d9372dd08a92feebf98e916c98bc2242ff4
[ "MIT" ]
null
null
null
SimSpark/rcssserver3d/plugin/soccer/soccerbase/soccerbase.cpp
IllyasvielEin/Robocup3dInstaller
12e91d9372dd08a92feebf98e916c98bc2242ff4
[ "MIT" ]
null
null
null
SimSpark/rcssserver3d/plugin/soccer/soccerbase/soccerbase.cpp
IllyasvielEin/Robocup3dInstaller
12e91d9372dd08a92feebf98e916c98bc2242ff4
[ "MIT" ]
null
null
null
/* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*- this file is part of rcssserver3D Fri May 9 2003 Copyright (C) 2002,2003 Koblenz University Copyright (C) 2003 RoboCup Soccer Server 3D Maintenance Group $Id$ 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 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "soccerbase.h" #include <oxygen/physicsserver/rigidbody.h> #include <oxygen/physicsserver/spherecollider.h> #include <oxygen/agentaspect/perceptor.h> #include <oxygen/agentaspect/agentaspect.h> #include <oxygen/sceneserver/sceneserver.h> #include <oxygen/sceneserver/scene.h> #include <oxygen/sceneserver/transform.h> #include <oxygen/controlaspect/controlaspect.h> #include <oxygen/gamecontrolserver/gamecontrolserver.h> #include <gamestateaspect/gamestateaspect.h> #include <soccerruleaspect/soccerruleaspect.h> #include <agentstate/agentstate.h> #include <ball/ball.h> #include <oxygen/physicsserver/space.h> #include <zeitgeist/leaf.h> using namespace boost; using namespace zeitgeist; using namespace oxygen; using namespace std; using namespace salt; bool SoccerBase::GetSceneServer(const Leaf& base, boost::shared_ptr<SceneServer>& scene_server) { scene_server = static_pointer_cast<SceneServer> (base.GetCore()->Get("/sys/server/scene")); if (scene_server.get() == 0) { base.GetLog()->Error() << "Error: (SoccerBase: " << base.GetName() << ") scene server not found.\n"; return false; } return true; } bool SoccerBase::GetTransformParent(const Leaf& base, boost::shared_ptr<Transform>& transform_parent) { transform_parent = dynamic_pointer_cast<Transform> ((base.FindParentSupportingClass<Transform>()).lock()); if (transform_parent.get() == 0) { base.GetLog()->Error() << "Error: (SoccerBase: " << base.GetName() << ") parent node is not derived from TransformNode\n"; return false; } return true; } bool SoccerBase::GetAgentState(const boost::shared_ptr<Transform> transform, boost::shared_ptr<AgentState>& agent_state) { agent_state = dynamic_pointer_cast<AgentState>(transform->GetChild("AgentState", true)); if (agent_state.get() == 0) { return false; } return true; } bool SoccerBase::GetAgentBody(const boost::shared_ptr<Transform> transform, boost::shared_ptr<RigidBody>& agent_body) { agent_body = transform->FindChildSupportingClass<RigidBody>(true); if (agent_body.get() == 0) { transform->GetLog()->Error() << "(SoccerBase) ERROR: " << transform->GetName() << " node has no Body child\n"; return false; } return true; } bool SoccerBase::GetAgentBody(const Leaf& base, TTeamIndex idx, int unum, boost::shared_ptr<RigidBody>& agent_body) { boost::shared_ptr<AgentState> agentState; boost::shared_ptr<Transform> parent; // get matching AgentState if (!GetAgentState(base, idx, unum, agentState)) return false; // get AgentAspect if (!GetTransformParent(*agentState, parent)) return false; // call GetAgentBody with matching AgentAspect return GetAgentBody(parent, agent_body); } bool SoccerBase::GetAgentState(const Leaf& base, boost::shared_ptr<AgentState>& agent_state) { boost::shared_ptr<Transform> parent; if (! GetTransformParent(base,parent)) { return false; } return GetAgentState(parent,agent_state); } bool SoccerBase::GetAgentState(const Leaf& base, TTeamIndex idx, int unum, boost::shared_ptr<AgentState>& agentState) { static TAgentStateMap mAgentStateMapLeft; static TAgentStateMap mAgentStateMapRight; if (idx == TI_NONE) return false; // do we have a cached reference? if ( idx == TI_LEFT && !mAgentStateMapLeft.empty() ) { TAgentStateMap::iterator iter = mAgentStateMapLeft.find(unum); if (iter != mAgentStateMapLeft.end()) { // is the pointer to the parent (AgentAspect) still valid // (maybe the agent disconnected)? if (!(iter->second)->GetParent().lock().get()) { base.GetLog()->Error() << "(SoccerBase) WARNING: " << "AgentState has invalid parent! " << "The agent probably disconnected, removing from map." << "\n"; mAgentStateMapLeft.erase(iter); } else { agentState = (*iter).second; return true; } } } else if ( idx == TI_RIGHT && !mAgentStateMapRight.empty() ) { TAgentStateMap::iterator iter = mAgentStateMapRight.find(unum); if (iter != mAgentStateMapRight.end()) { // is the pointer to the parent (AgentAspect) still valid // (maybe the agent disconnected)? if ((iter->second)->GetParent().lock().get() == 0) { base.GetLog()->Error() << "(SoccerBase) WARNING: " << "AgentState has invalid parent! " << "The agent probably disconnected, removing from map." << "\n"; mAgentStateMapRight.erase(iter); } else { agentState = (*iter).second; return true; } } } // we have to get all agent states for this team TAgentStateList agentStates; GetAgentStates(base, agentStates, idx); for (TAgentStateList::iterator iter = agentStates.begin(); iter != agentStates.end(); ++iter) { if ((*iter)->GetUniformNumber() == unum) { agentState = *iter; if (idx == TI_LEFT) { mAgentStateMapLeft[unum] = agentState; } else { mAgentStateMapRight[unum] = agentState; } return true; } } return false; } bool SoccerBase::GetAgentStates(const zeitgeist::Leaf& base, TAgentStateList& agentStates, TTeamIndex idx) { static boost::shared_ptr<GameControlServer> gameCtrl; if (gameCtrl.get() == 0) { GetGameControlServer(base, gameCtrl); if (gameCtrl.get() == 0) { base.GetLog()->Error() << "(SoccerBase) ERROR: can't get " << "GameControlServer\n"; return false; } } GameControlServer::TAgentAspectList aspectList; gameCtrl->GetAgentAspectList(aspectList); GameControlServer::TAgentAspectList::iterator iter; boost::shared_ptr<AgentState> agentState; for ( iter = aspectList.begin(); iter != aspectList.end(); ++iter ) { agentState = dynamic_pointer_cast<AgentState>((*iter)->GetChild("AgentState", true)); if ( agentState.get() != 0 && ( agentState->GetTeamIndex() == idx || idx == TI_NONE ) ) { agentStates.push_back(agentState); } } return true; } bool SoccerBase::GetGameState(const Leaf& base, boost::shared_ptr<GameStateAspect>& game_state) { game_state = dynamic_pointer_cast<GameStateAspect> (base.GetCore()->Get("/sys/server/gamecontrol/GameStateAspect")); if (game_state.get() == 0) { base.GetLog()->Error() << "Error: (SoccerBase: " << base.GetName() << ") found no GameStateAspect\n"; return false; } return true; } bool SoccerBase::GetSoccerRuleAspect(const Leaf& base, boost::shared_ptr<SoccerRuleAspect> & soccer_rule_aspect) { soccer_rule_aspect = dynamic_pointer_cast<SoccerRuleAspect> (base.GetCore()->Get("/sys/server/gamecontrol/SoccerRuleAspect")); if (soccer_rule_aspect.get() == 0) { base.GetLog()->Error() << "Error: (SoccerBase: " << base.GetName() << " found no SoccerRuleAspect\n"; return false; } return true; } bool SoccerBase::GetGameControlServer(const Leaf& base, boost::shared_ptr<GameControlServer> & game_control_server) { static boost::shared_ptr<GameControlServer> gameControlServer; if (gameControlServer.get() == 0) { gameControlServer = dynamic_pointer_cast<GameControlServer> (base.GetCore()->Get("/sys/server/gamecontrol")); if (gameControlServer.get() == 0) { base.GetLog()->Error() << "Error: (SoccerBase: " << base.GetName() << " found no GameControlServer\n"; return false; } } game_control_server = gameControlServer; return true; } bool SoccerBase::GetActiveScene(const Leaf& base, boost::shared_ptr<Scene>& active_scene) { static boost::shared_ptr<SceneServer> sceneServer; if (sceneServer.get() == 0) { if (! GetSceneServer(base,sceneServer)) { base.GetLog()->Error() << "(SoccerBase) ERROR: " << base.GetName() << ", could not get SceneServer\n"; return false; } } active_scene = sceneServer->GetActiveScene(); if (active_scene.get() == 0) { base.GetLog()->Error() << "ERROR: (SoccerBase: " << base.GetName() << ", SceneServer reports no active scene\n"; return false; } return true; } bool SoccerBase::GetBody(const Leaf& base, boost::shared_ptr<RigidBody>& body) { boost::shared_ptr<Transform> parent; if (! GetTransformParent(base,parent)) { base.GetLog()->Error() << "(SoccerBase) ERROR: no transform parent " << "found in GetBody()\n"; return false; } body = dynamic_pointer_cast<RigidBody>(parent->FindChildSupportingClass<RigidBody>()); if (body.get() == 0) { base.GetLog()->Error() << "ERROR: (SoccerBase: " << base.GetName() << ") parent node has no Body child."; return false; } return true; } bool SoccerBase::GetBall(const Leaf& base, boost::shared_ptr<Ball>& ball) { static boost::shared_ptr<Scene> scene; static boost::shared_ptr<Ball> ballRef; if (scene.get() == 0) { if (! GetActiveScene(base,scene)) { base.GetLog()->Error() << "(SoccerBase) ERROR: " << base.GetName() << ", could not get active scene.\n"; return false; } } if (ballRef.get() == 0) { ballRef = dynamic_pointer_cast<Ball> (base.GetCore()->Get(scene->GetFullPath() + "Ball")); if (ballRef.get() == 0) { base.GetLog()->Error() << "(SoccerBase) ERROR: " << base.GetName() << ", found no ball node\n"; return false; } } ball = ballRef; return true; } bool SoccerBase::GetBallBody(const Leaf& base, boost::shared_ptr<RigidBody>& body) { static boost::shared_ptr<Scene> scene; static boost::shared_ptr<RigidBody> bodyRef; if (scene.get() == 0) { if (! GetActiveScene(base,scene)) { base.GetLog()->Error() << "(SoccerBase) ERROR: " << base.GetName() << ", could not get active scene.\n"; return false; } } if (bodyRef.get() == 0) { bodyRef = dynamic_pointer_cast<RigidBody> (base.GetCore()->Get(scene->GetFullPath() + "Ball/physics")); if (bodyRef.get() == 0) { base.GetLog()->Error() << "(SoccerBase) ERROR: " << base.GetName() << ", found no ball body node\n"; return false; } } body = bodyRef; return true; } bool SoccerBase::GetBallCollider(const zeitgeist::Leaf& base, boost::shared_ptr<oxygen::SphereCollider>& sphere) { static boost::shared_ptr<Scene> scene; static boost::shared_ptr<SphereCollider> sphereRef; if (scene.get() == 0) { if (! GetActiveScene(base,scene)) { base.GetLog()->Error() << "(SoccerBase) ERROR: " << base.GetName() << ", could not get active scene.\n"; return false; } } if (sphereRef.get() == 0) { sphereRef = dynamic_pointer_cast<SphereCollider> (base.GetCore()->Get(scene->GetFullPath() + "Ball/geometry")); if (sphereRef.get() == 0) { base.GetLog()->Error() << "(SoccerBase) ERROR:" << base.GetName() << ", Ball got no SphereCollider node\n"; return false; } } sphere = sphereRef; return true; } salt::Vector3f SoccerBase::FlipView(const salt::Vector3f& pos, TTeamIndex ti) { salt::Vector3f newPos; switch (ti) { case TI_RIGHT: newPos[0] = -pos[0]; newPos[1] = -pos[1]; newPos[2] = pos[2]; break; case TI_NONE: case TI_LEFT: newPos = pos; break; } return newPos; } TTeamIndex SoccerBase::OpponentTeam(TTeamIndex ti) { switch (ti) { case TI_RIGHT: return TI_LEFT; case TI_LEFT: return TI_RIGHT; default: return TI_NONE; } } string SoccerBase::PlayMode2Str(const TPlayMode mode) { switch (mode) { case PM_BeforeKickOff: return STR_PM_BeforeKickOff; case PM_KickOff_Left: return STR_PM_KickOff_Left; case PM_KickOff_Right: return STR_PM_KickOff_Right; case PM_PlayOn: return STR_PM_PlayOn; case PM_KickIn_Left: return STR_PM_KickIn_Left; case PM_KickIn_Right: return STR_PM_KickIn_Right; case PM_CORNER_KICK_LEFT: return STR_PM_CORNER_KICK_LEFT; case PM_CORNER_KICK_RIGHT: return STR_PM_CORNER_KICK_RIGHT; case PM_GOAL_KICK_LEFT: return STR_PM_GOAL_KICK_LEFT; case PM_GOAL_KICK_RIGHT: return STR_PM_GOAL_KICK_RIGHT; case PM_OFFSIDE_LEFT: return STR_PM_OFFSIDE_LEFT; case PM_OFFSIDE_RIGHT: return STR_PM_OFFSIDE_RIGHT; case PM_GameOver: return STR_PM_GameOver; case PM_Goal_Left: return STR_PM_Goal_Left; case PM_Goal_Right: return STR_PM_Goal_Right; case PM_FREE_KICK_LEFT: return STR_PM_FREE_KICK_LEFT; case PM_FREE_KICK_RIGHT: return STR_PM_FREE_KICK_RIGHT; case PM_DIRECT_FREE_KICK_LEFT: return STR_PM_DIRECT_FREE_KICK_LEFT; case PM_DIRECT_FREE_KICK_RIGHT: return STR_PM_DIRECT_FREE_KICK_RIGHT; case PM_PASS_LEFT: return STR_PM_PASS_LEFT; case PM_PASS_RIGHT: return STR_PM_PASS_RIGHT; default: return STR_PM_Unknown; }; } boost::shared_ptr<ControlAspect> SoccerBase::GetControlAspect(const zeitgeist::Leaf& base,const string& name) { static const string gcsPath = "/sys/server/gamecontrol/"; boost::shared_ptr<ControlAspect> aspect = dynamic_pointer_cast<ControlAspect> (base.GetCore()->Get(gcsPath + name)); if (aspect.get() == 0) { base.GetLog()->Error() << "ERROR: (SoccerBase: " << base.GetName() << ") found no ControlAspect " << name << "\n"; } return aspect; } bool SoccerBase::MoveAgent(boost::shared_ptr<Transform> agent_aspect, const Vector3f& pos) { Vector3f agentPos = agent_aspect->GetWorldTransform().Pos(); boost::shared_ptr<Transform> parent = dynamic_pointer_cast<Transform> (agent_aspect->FindParentSupportingClass<Transform>().lock()); if (parent.get() == 0) { agent_aspect->GetLog()->Error() << "(MoveAgent) ERROR: can't get parent node.\n"; return false; } Leaf::TLeafList leafList; parent->ListChildrenSupportingClass<RigidBody>(leafList, true); if (leafList.size() == 0) { agent_aspect->GetLog()->Error() << "(MoveAgent) ERROR: agent aspect doesn't have " << "children of type Body\n"; return false; } Leaf::TLeafList::iterator iter = leafList.begin(); // move all child bodies for (; iter != leafList.end(); ++iter) { boost::shared_ptr<RigidBody> childBody = dynamic_pointer_cast<RigidBody>(*iter); Vector3f childPos = childBody->GetPosition(); childBody->SetPosition(pos + (childPos-agentPos)); childBody->SetVelocity(Vector3f(0,0,0)); childBody->SetAngularVelocity(Vector3f(0,0,0)); } return true; } bool SoccerBase::MoveAndRotateAgent(boost::shared_ptr<Transform> agent_aspect, const Vector3f& pos, float angle) { boost::shared_ptr<Transform> parent = dynamic_pointer_cast<Transform> (agent_aspect->FindParentSupportingClass<Transform>().lock()); if (parent.get() == 0) { agent_aspect->GetLog()->Error() << "(MoveAndRotateAgent) ERROR: can't get parent node.\n"; return false; } Leaf::TLeafList leafList; parent->ListChildrenSupportingClass<RigidBody>(leafList, true); if (leafList.size() == 0) { agent_aspect->GetLog()->Error() << "(MoveAndRotateAgent) ERROR: agent aspect doesn't have " << "children of type Body\n"; return false; } boost::shared_ptr<RigidBody> body; GetAgentBody(agent_aspect, body); const Vector3f& agentPos = body->GetPosition(); Matrix bodyR = body->GetRotation(); bodyR.InvertRotationMatrix(); Matrix mat; mat.RotationZ(gDegToRad(angle)); mat *= bodyR; Leaf::TLeafList::iterator iter = leafList.begin(); // move all child bodies for (; iter != leafList.end(); ++iter ) { boost::shared_ptr<RigidBody> childBody = dynamic_pointer_cast<RigidBody>(*iter); Vector3f childPos = childBody->GetPosition(); Matrix childR = childBody->GetRotation(); childR = mat*childR; childBody->SetPosition(pos + mat.Rotate(childPos-agentPos)); childBody->SetVelocity(Vector3f(0,0,0)); childBody->SetAngularVelocity(Vector3f(0,0,0)); childBody->SetRotation(childR); } return true; } AABB3 SoccerBase::GetAgentBoundingBox(const Leaf& base) { AABB3 boundingBox; boost::shared_ptr<Space> parent = base.FindParentSupportingClass<Space>().lock(); if (!parent) { base.GetLog()->Error() << "(GetAgentBoundingBox) ERROR: can't get parent node.\n"; return boundingBox; } /* We can't simply use the GetWorldBoundingBox of the space node, becuase * (at least currently) it'll return a wrong answer. Currently, the space * object is always at (0,0,0) which is encapsulated in the result of it's * GetWorldBoundingBox method call. */ Leaf::TLeafList baseNodes; parent->ListChildrenSupportingClass<BaseNode>(baseNodes); if (baseNodes.empty()) { base.GetLog()->Error() << "(GetAgentBoundingBox) ERROR: space object doesn't have any" << " children of type BaseNode.\n"; } for (Leaf::TLeafList::iterator i = baseNodes.begin(); i!= baseNodes.end(); ++i) { boost::shared_ptr<BaseNode> node = static_pointer_cast<BaseNode>(*i); boundingBox.Encapsulate(node->GetWorldBoundingBox()); } return boundingBox; } AABB2 SoccerBase::GetAgentBoundingRect(const Leaf& base) { AABB2 boundingRect; boost::shared_ptr<Space> parent = base.FindParentSupportingClass<Space>().lock(); if (!parent) { base.GetLog()->Error() << "(GetAgentBoundingBox) ERROR: can't get parent node.\n"; return boundingRect; } /* We can't simply use the GetWorldBoundingBox of the space node, becuase * (at least currently) it'll return a wrong answer. Currently, the space * object is always at (0,0,0) which is encapsulated in the result of it's * GetWorldBoundingBox method call. */ Leaf::TLeafList baseNodes; parent->ListChildrenSupportingClass<Collider>(baseNodes,true); if (baseNodes.empty()) { base.GetLog()->Error() << "(GetAgentBoundingBox) ERROR: space object doesn't have any" << " children of type BaseNode.\n"; } for (Leaf::TLeafList::iterator i = baseNodes.begin(); i!= baseNodes.end(); ++i) { boost::shared_ptr<BaseNode> node = static_pointer_cast<BaseNode>(*i); const AABB3 &box = node->GetWorldBoundingBox(); boundingRect.Encapsulate(box.minVec.x(), box.minVec.y()); boundingRect.Encapsulate(box.maxVec.x(), box.maxVec.y()); } return boundingRect; }
27.29697
107
0.573579
IllyasvielEin
b2514262d5bdd97030d6b23b95b266bf0ff1c1ed
149
cpp
C++
abc176/a.cpp
magurotuna/atcoder-submissions-cpp
afbf5df2f22bcd17d8ad580d3c143602d9af7398
[ "CC0-1.0" ]
null
null
null
abc176/a.cpp
magurotuna/atcoder-submissions-cpp
afbf5df2f22bcd17d8ad580d3c143602d9af7398
[ "CC0-1.0" ]
null
null
null
abc176/a.cpp
magurotuna/atcoder-submissions-cpp
afbf5df2f22bcd17d8ad580d3c143602d9af7398
[ "CC0-1.0" ]
null
null
null
#include <bits/stdc++.h> int main() { int n, x, t; std::cin >> n >> x >> t; int cnt = (n + x - 1) / x; std::cout << t * cnt << std::endl; }
16.555556
36
0.442953
magurotuna
b255cfd2e71168d3bac1075a744ccf1b7540b7ea
199
cpp
C++
src/pocketdb/services/WsNotifier.cpp
pocketnetapp/pocketnet.core
2bdcd58bd8a4210d1117c06d52295c0b62c4061d
[ "Apache-2.0" ]
1
2022-02-07T14:19:54.000Z
2022-02-07T14:19:54.000Z
src/pocketdb/services/WsNotifier.cpp
pocketnetapp/pocketnet.core
2bdcd58bd8a4210d1117c06d52295c0b62c4061d
[ "Apache-2.0" ]
null
null
null
src/pocketdb/services/WsNotifier.cpp
pocketnetapp/pocketnet.core
2bdcd58bd8a4210d1117c06d52295c0b62c4061d
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2018-2022 The Pocketnet developers // Distributed under the Apache 2.0 software license, see the accompanying // https://www.apache.org/licenses/LICENSE-2.0 #include "WsNotifier.h"
33.166667
74
0.763819
pocketnetapp
b25b56b2e42ec0e8935f537feeebfdc154f1324b
30
cpp
C++
Engine/Helper/valuedatavariant.cpp
hefsoftware/Stem
0903032db9ba6f843c01d06aea5a31f2b519ec56
[ "BSD-3-Clause" ]
null
null
null
Engine/Helper/valuedatavariant.cpp
hefsoftware/Stem
0903032db9ba6f843c01d06aea5a31f2b519ec56
[ "BSD-3-Clause" ]
null
null
null
Engine/Helper/valuedatavariant.cpp
hefsoftware/Stem
0903032db9ba6f843c01d06aea5a31f2b519ec56
[ "BSD-3-Clause" ]
null
null
null
#include "valuedatavariant.h"
15
29
0.8
hefsoftware
b267864e88d6a620439efa9d5166c494ef677871
3,312
hpp
C++
hash_table.hpp
wheatman/ConcurrentHashMap
7af9030e084d8c2c5eec2ca3e4a51e3a8bb80dda
[ "MIT" ]
null
null
null
hash_table.hpp
wheatman/ConcurrentHashMap
7af9030e084d8c2c5eec2ca3e4a51e3a8bb80dda
[ "MIT" ]
null
null
null
hash_table.hpp
wheatman/ConcurrentHashMap
7af9030e084d8c2c5eec2ca3e4a51e3a8bb80dda
[ "MIT" ]
null
null
null
#pragma once #include "parallel.h" #include "reducer.h" #include <algorithm> #include <functional> #include <memory> #include <mutex> #include <unordered_map> #include <unordered_set> #include <vector> template <class Key, class T, class Hash = std::hash<Key>> class ConcurrentHashMap { private: using Map = std::pair<std::unordered_map<Key, T>, std::mutex>; struct aligned_map { alignas(hardware_destructive_interference_size) Map m; }; std::vector<aligned_map> maps; public: ConcurrentHashMap(int num_workers, int blow_up_factor = 10) : maps(num_workers * blow_up_factor) {} void insert(Key k, T value) { size_t bucket = Hash{}(k) % maps.size(); maps[bucket].m.second.lock(); maps[bucket].m.first.insert({k, value}); maps[bucket].m.second.unlock(); } void remove(Key k) { size_t bucket = Hash{}(k) % maps.size(); maps[bucket].m.second.lock(); maps[bucket].m.first.erase(k); maps[bucket].m.second.unlock(); } T value(Key k, T null_value) { size_t bucket = Hash{}(k) % maps.size(); maps[bucket].m.second.lock(); auto it = maps[bucket].m.first.find(k); T value; if (it == maps[bucket].m.first.end()) { value = null_value; } else { value = *it; } maps[bucket].m.second.unlock(); return value; } bool contains(Key k) { size_t bucket = Hash{}(k) % maps.size(); maps[bucket].m.second.lock(); bool has = maps[bucket].m.first.contains(k); maps[bucket].m.second.unlock(); return has; } }; template <class Key, class Hash = std::hash<Key>> class ConcurrentHashSet { private: using Set = std::pair<std::unordered_set<Key>, std::mutex>; struct aligned_set { alignas(hardware_destructive_interference_size) Set s; }; std::vector<aligned_set> sets; public: ConcurrentHashSet(int num_workers, int blow_up_factor = 10) : sets(num_workers * blow_up_factor) {} void insert(Key k) { size_t bucket = Hash{}(k) % sets.size(); sets[bucket].s.second.lock(); sets[bucket].s.first.insert(k); sets[bucket].s.second.unlock(); } void insert_batch(Key *k, uint64_t num_keys) { std::sort(k, k + num_keys, [](Key a, Key b) { return Hash{}(a) > Hash{}(b); }); parallel_for(uint64_t i = 0; i < num_keys; i++) { insert(k[i]); } } void remove(Key k) { size_t bucket = Hash{}(k) % sets.size(); sets[bucket].s.second.lock(); sets[bucket].s.first.erase(k); sets[bucket].s.second.unlock(); } bool contains(Key k) { size_t bucket = Hash{}(k) % sets.size(); sets[bucket].s.second.lock(); bool has = sets[bucket].s.first.contains(k); sets[bucket].s.second.unlock(); return has; } Key sum() { Reducer_sum<Key> s(getWorkers()); parallel_for(size_t i = 0; i < sets.size(); i++) { Key local_sum = 0; sets[i].s.second.lock(); for (const auto &item : sets[i].s.first) { local_sum += item; } sets[i].s.second.unlock(); s.add(local_sum); } return s.get(); } Key sum_no_lock() { Reducer_sum<Key> s(getWorkers()); parallel_for(size_t i = 0; i < sets.size(); i++) { Key local_sum = 0; for (const auto &item : sets[i].s.first) { local_sum += item; } s.add(local_sum); } return s.get(); } };
26.285714
75
0.610507
wheatman
b26875abce8e9890cbb8cfb1b03663110905b511
12,391
cpp
C++
data/954.cpp
TianyiChen/rdcpp-data
75c6868c876511e3ce143fdc3c08ddd74c7aa4ea
[ "MIT" ]
null
null
null
data/954.cpp
TianyiChen/rdcpp-data
75c6868c876511e3ce143fdc3c08ddd74c7aa4ea
[ "MIT" ]
null
null
null
data/954.cpp
TianyiChen/rdcpp-data
75c6868c876511e3ce143fdc3c08ddd74c7aa4ea
[ "MIT" ]
null
null
null
int b9MhF//6oKqb , th6sZ, pQ , wzc , sJ0u , J , B5 , qet, Y, M , JIk, dRbLB , JI , HVm ,V6i , ApWJ, QLr, kr, yaXv , LrB ,vms, ZpPk/**/, qrW ,/*n*/ QBDYi, jH , E ,Qp,qlMm ,i,/*KnSK*/ ZW,K1E , AXo , N4 , gI4I,/*X*/PhCO ,awv , zP7C , NJ , C ,G , rKp3S9, DCW ,xNvW,c6, im , OXaT,ll9V,JSBw; void f_f0//kmq //r () { //7 {for(int i=1;i<1 ;++i/*HFQR*/) {{ { return ; /*eTOii*/{}{} } { return //S ; }}{ { }; { } } }/*O*/ { volatile int F, E8tFH , Bs ; {//k {/*Pk*/} }{for(int i=1 ; i< 2;++i );} JSBw=Bs + F +E8tFH; } if(true ) { ; {return ;}{ for//Mb (int i=1 ; i< 3 ;++i ) {}{/*P9F*/ return ;/*ry*/} //d1 { } }} else return ; {{; /*Dx*//*G*/return ;//l } for (int i=1;//fy i< 4 ;++i){for(int i=1 ; i< 5;++i//EAIZ );{ return//Gp ; {{//GtM } { {} { } } }}} }/*W*/} {{ { { {} {}} /*E33Cgxe*/}if(true) { return ;} else return /*fCd*///U7 ; return ; }{ { return ; for(int /**/ i=1; i<6// //zU02 ;++i) return ;{ {} } } { ; }}if( true) ; else { { { } } { volatile int tYFMrLQ//CQD ,KEux , san ; {return ;{ }/*b*/;{ } }return ; b9MhF= san + tYFMrLQ //OHW6 +//z1B KEux ; } } { ;for(int i=1//Plsg1 ; i</*iCv*/7 ;++i ) {return /**/ ; return ; { { }}} }{ { {}}{ volatile int V4 , rYV8H; if ( true ) {{} return ;{} {int sw ; volatile int ymBF;{/*kM*/} if ( true)return ; else sw =ymBF; //XAcg } } else ; for(int i=1 ; i< 8;++i)for (int i=1; i< //M 9 ;++i) if ( true)if( true) {//CP } else th6sZ = rYV8H//0rOrA /*8jE*/+V4;/*u*//*rM*/else {} } if (true ){ return ;{ } } else//Yz7 { int w ; volatile int H7m ,d, hjV ;{ { } }if ( true ) for(int i=1 ; i<10 ;++i) if( true ){ ; return ; /*HfM*/return ; } else w = hjV /*VBZ*/ +H7m //2l +d ;else {return ; } } } } { volatile int nRJc ,fDNr , sinwWT//YD , fi, q3 ;{{ //VCQ volatile int oXu ,Hdk/*pOc*/ , lsI1q, y4 , S ;{ }pQ = S+ oXu+Hdk+lsI1q + y4; }for(int i=1; i<11 ;++i )return ; }{ { ; {} }return ; for (int i=1 ; i< 12 ;++i) {;} { return ; } }{{volatile int wfK ,Gxe ; wzc =/*8l*/Gxe +wfK; } {{} } { { return ;return ;{/*2cOo*/} } } } sJ0u =q3 + nRJc+ fDNr + sinwWT +fi; { if (true){ { { { } return ; } } { //Kn } } else for(int i=1 ;//bq i< 13;++i ) ; { if( true) {volatile int U, yCT;{ } J = yCT+ U//9 ; } else/*ak3eA*/{ {}}return ; }return ;{{ {} }} return //8v ; { if( true){ if( true ) {}else { } /*vWn*/}else{{ volatile int eM ;{} {} //q B5= eM ; }for(int i=1 ;i<//X 14;++i ) { volatile int LD,qEqK// ;qet//lJI0L = qEqK+LD ; }} }}{ volatile int p11hGD,/*74*/i4 ,//1 hrp ,FDGYY, Zyf ,nOzZWj , HSp , mY ;//0 return ; if (true) for(int i=1; i< 15;++i ) Y = mY+//8 p11hGD + i4 + hrp ; else {int b/*D*/;volatile int XJ/*6*/,KmB; b=KmB+ XJ ;} M= FDGYY +Zyf+nOzZWj +HSp ;}} {{volatile int Qr,AwZ ,qX ;return ;/*s*/JIk= qX + Qr+AwZ ;/*R*/}for (int i=1 ;i<//RLu 16 ;++i ) return ; { int V; volatile int RVI0V , zo5,zMR ,Lfo ,pul ; { ; {{ }//1tSS ;/*RulKW*/ } ; }if ( true)// {{ } { }} else for (int i=1 ;i<17 ;++i )return ;V=pul + RVI0V + zo5 +/**/ zMR+/*ZBe*/Lfo ;} } return ;} void f_f1(){for(int i=1//W ; i<18;++i ) { volatile int NWZ , jlt, rBKVJ , sn2 , oEm //J , QthW,rukJt , azL , //Iye Ke;dRbLB =Ke+NWZ +jlt+rBKVJ + sn2; { volatile int//j rG ,XTaV,s5wyn7, f;if( true )/*RN*/ { volatile int PVL ,/*v*/h ;JI= h + PVL ; ; } /*5U*/else{ {return ;}{ if (true ){} else for (int //aX //3 i=1;i< 19 ;++i) {{ } { } for (int i=1 ; i< 20 ;++i) { } {}}}//G } return ; if( true ) {volatile int XI92, Zs , /*N4M*/E5,LsV4F ;return ; { { {} return//r3i ;} }HVm //n = LsV4F +XI92+ Zs + E5; {{} {} }}else//f9n V6i = f+ rG + XTaV+s5wyn7 ;if( true ) {//WE1 { { } }} else { return ;{{}{ /*6B*/{ }} }return ; }}if( true )/*YAc*/ if (// true /*zD*/ )return ; else/*h65*/ return ; else for (int i=1 ; i<21;++i) return ; ApWJ=oEm +QthW +rukJt //oXNkl +//Y azL;{ volatile int I3Z, gf,cA ;;{ /*Qc*/for (int i=1 ;/*KQzb*/ i<// 22;++i) ; { ; }{ { } }} QLr= cA/*O0J*/ +/*3*/ I3Z +gf ; }{volatile int//eV7CY CrAg/*YAww*/, s8kDY,YK, DX; for (int //Q i=1; i<23;++i)kr =DX +//GI CrAg + s8kDY+YK; { int X ; volatile int AkDJk , VW , Brv16 //A3Q ;{ for (int i=1 ; i<24 ;++i ) {return ;}}X= Brv16/*C*/+ AkDJk+ VW ;/*xrq*/ }}}{ {if (true )//Oe { { {}return ; } { {}} for (int //UA i=1; i<25 ;++i//J7 ) ;} else if( true) { //J { }if (// true ) if(true ) return ; else ;else return //c5q ; }else {;return ;{/*F*/ { return ;} if ( true ) { }//MPO else return ;}//ZE }//FF if( true){volatile int Xq ,OVM //g ,XI7; for (int i=1 ;i< 26;++i){ {/**/} {}//a5 }yaXv=XI7 //P7yS +Xq +OVM ; } else{ { int z ; volatile int dA4jYi, /*Wf*/WM5, vI ;/*r6*/ ; z= vI + dA4jYi+ WM5; }{ }} } { { ; } { {for//f (int i=1;i< 27 ;++i ) {}/*FZ*/ }//jdB { { }} }{ { } //eN }}{ ;{ volatile int//C4sh O0,U0sSs ,//I5 sb, NEUB; LrB =NEUB +//B O0 + U0sSs +sb ; ;}/**/ } return ; {{ ;return ; } {; for(int i=1/*5D*/;i<28;++i) {} }}}/*M*/ for(int i=1 ;i<29 ;++i ){ volatile int DTKb, V6xW,R , PT , kB , T ; if( true ) for(int i=1 ; i<30 //oIV ;++i/*0T*/ ) ;else { volatile int Dar , w1p , QA , SKa;return ; if (/*6*/true) ; else vms /**/= SKa +Dar + w1p + QA ;/*OW*/} /*m9*/ZpPk =T+DTKb + V6xW/*y*///6 + R + PT +kB; ; {{ ; }return ; }} for(int i=1 ;i< 31;++i );return ; } void f_f2 () { int xE ; volatile int SD6, EaMN2,UMSBa ,MKobU ,rzZjyb ,A7d, YcSK,/*Z*/KR , tu/**/,H2 , oR ,m9Ro ;{{ { if( true ) { { if ( true /*r*/ ) return ; else { } } { } } else {if (true ){ } else{ ; }for (int i=1 ; i< 32 ;++i /*kn*/){ /**/{ }}}{//4 { }} }{volatile int K ,Q56W ; if (true) { /**/ { { } }}else for(int i=1 ;i< 33 ;++i) qrW//s //q =Q56W + K//1t ; ;} if ( true ){ {/*w40*/ { }//Bc } if// ( true ) return ;/*vN4*/else {volatile int cQnn , WUUX ;// QBDYi= WUUX+cQnn ;} {volatile int j7 ;jH//e = j7 ; }}else return ; { if(/*Et*/true ); else { //S90m } } }{{ volatile int LuO , d5y /*df*/;E = d5y+/*G2R*/LuO; {}{} } ; {{} { }}} {/*R6e8*/{{} };}} if (true/*1*/ )for (int //Y /*3RP*/i=1 ; i<34;++i ) if (/*3*/true) { for(int i=1 ; i<35;++i ) { //9 {/*ZG*/ {return ; return ;} } { volatile int oUF9u//WP ,o //W ;{return ; {//QgL } }if(true ) return ; else {} { }Qp =o//FLlN +oUF9u ;} }{ {return ;} for (int i=1 ; i< 36;++i) { for (int i=1 ; i<37 //i ;++i ) {int QV ;volatile int larZBD ,//d RHiwl ; /*rTCH*/QV =RHiwl + larZBD; } }}return ;{volatile int JHdG2 , CFU , ow3,AF ;return ; { { if ( true ) {} // else for(int i=1; i< 38 ;++i){} }for (int i=1;i< 39 ;++i ) ;}if ( true)qlMm = AF+ JHdG2+/*sX*/ CFU+ ow3 ;//ZV8 else{/*xv*/ return ; {return ;} } } }else for(int i=1 ; i<40;++i ) { volatile int LutM, yR , C2CY/*49x*/, jc ;; i = //K jc+ LutM +yR+ C2CY ;{for(int i=1 ; i<41/**/;++i )return ; { { { } } } {{ } }}}else xE = m9Ro //x4 + SD6+EaMN2 + UMSBa + MKobU+ rzZjyb ;ZW = A7d +YcSK+ KR+ tu + H2 + oR;/*31*/for (int i=1; i< 42;++i) {{//Iu for (int i=1; i< 43/*tLa*/ ;++i );return ; if (true ){ { }}/*3o83*/else{ volatile int Rlysi ,axHk,hlUvES ;for(int i=1 //5D ; i<44 ;++i/*K*/) K1E =hlUvES+ Rlysi //MR5VH + axHk ;}} {volatile int jPl, Uz0 , nr ,Fe51 ,dLRL ; {int //Q MxHn; volatile int X33S,Pj ,/**/ uj,/*b*/Em , N3Bxsh ;return ;AXo =N3Bxsh +X33S ;for//r (int i=1 ; i<45//qX ;++i ){ for(int i=1; i< 46 ;++i)//eB {}//bSq } MxHn = Pj+ uj+Em /*tOr7*/;}N4=dLRL+ jPl + Uz0 + nr +Fe51 ; { {} ; { volatile int xBZD , JnL; if ( true ) gI4I = JnL+xBZD;//m else { { }}} }//NrPM {{ } } } {// return ; { { /*kX*/{ } ;}{ } }/*n4mn*//*wm*/{ if ( true){if (true ){ }/*EEnU*/else for (int i=1;i<47;++i ) for (int i=1; i< 48 ;++i ){ {}} { } { int GUj ; volatile int sy , PDmhpXK //Wvpw ;return ; //ufr GUj = PDmhpXK+ sy ; }}else //sq { {} } for (int i=1/*G9Nb*/; i<49 ;++i ) ;for (int i=1 ; i<50 ;++i ){}; } ; ; } {volatile int qOY ,idtw ,USa ;{ { //8L for(int i=1 ; i<51 //H ;++i) {} } { return ; /*M*//*QVp*/ }//N }{ ;} PhCO =USa+qOY +idtw;/**/ //cG }{for (int i=1 ;i< 52/*lTce*/;++i ) if( true /*hL*//*qU*/) return ;else{ volatile int Wa ,c5SK , vxGG ; //DTdM awv = vxGG+Wa +c5SK;};;} { { for(int i=1 ;i< 53/**/;++i )return ;} ;} } { volatile int A, DC8/*3*/ ,kZ , Kr6Ad, bw7 ; zP7C =/*O*/ bw7+A + DC8 //C + kZ+ Kr6Ad ;{ { {}; // return ; //2 {}}for (int i=1; i< 54 ;++i )if(true/*7*/) ; else//Ct {{ int duvDQ; volatile int W3JjA ,nQQW, zs; if ( true/*VwqT*/); //l9 else duvDQ//U =zs ;NJ // = W3JjA +nQQW ;}{}}if/*l*/ ( true ) {int m;volatile int Re , WpJLuBp/*9*/ , Ek// ; m = Ek + Re + WpJLuBp ; }else/*PWg*/ ; } for (int i=1; i<55 ;++i //bwqvD ) { ; {;{ /*Q*/volatile int kPykv2/*O9*/,Ob ;if ( true ) C =// Ob + kPykv2;else {/*Q*/ } } } return ;}{ volatile int Earb , G5i2,D,//cnvd ByJM ,UA, mLh; /*Lsu*/ ; G =mLh +Earb+ G5i2+ D+ByJM+/*5*/ UA ;}//B }//d return ;}int main () { volatile int c56o , v2vOO, IuM ,Gt , qV , lo; ; rKp3S9= /*RH*/lo+c56o/*Nqi*/// +//Ee v2vOO + IuM+Gt + qV ; {for (int i=1 ;i<56 ;++i) for(int i=1;i< 57;++i )return 1554571940; for (int i=1 ; //y5 i< 58 ;++i )for (int i=1 ; i< 59 ;++i){{int mQR ;volatile int tn, dPt ; { {} }if (// true)for /*i*/(int i=1 ;i<60/*Cy*/// ;++i) mQR//JW /*8I*/ = dPt+tn;else { } for(int i=1 ; i< 61;++i ) {{} }{ } }{//0X2Z volatile int /*8XDq*/ ttLhG , Zq /*9*/ , fU8 ; { { } return 1515121173 ; ; }DCW= fU8+ttLhG/*C9TH*/ + Zq ;{}}}//zqp for (int i=1 ; i< 62 ;++i ) { {int GYV ;/*7*/volatile int bkzL ,vG ,/*qAvp*/ by ,vmy , t,/*VB*///Gfv Lmy ; xNvW=Lmy +//jJ bkzL + vG;GYV = by //p /*7k*/+ vmy+ t;} {{ {} } for /*1TW*/(int i=1 ; i< 63 ;++i ) for (int i=1 ;i<//Tat 64 ;++i ){ volatile int qPzI ; //Ah c6 = qPzI ;} ; }} { ; return 342298984 ; ; }// {volatile int fuaXI ,tp , lsa , iPv; { ; } { for(int i=1 ; i< 65 ;++i ); for(int i=1; i<66;++i) { } }if ( true ) return 1447531146; else for(int //Z i=1 ;i<67;++i )if (true) { for (int i=1 ;i<68;++i ) {} {volatile int kQ,mbL;im= mbL +kQ ;} } else if ( true )if (true) if ( true ){{ { return 979977644; } { //0UH }} {}{}} else{/*W*/volatile int pmR, DCUk ; {} OXaT = /*dk*/DCUk+ pmR ; }else if( true) for (int i=1 ; i< 69 ;++i)/*s*/ if ( //p true ) { int fTSt , I6 ; volatile int NO //pMX , EK , GU , yftnK ;I6=yftnK/*1h*/+/*zM*/NO ;fTSt= EK + GU;} else if( true ) { return //V5Q 537655346;}else//WqF ll9V=iPv +fuaXI + tp//3 +lsa ;else { { { }} //QSg return 1949675337 ;{ return 823386512 ; { } } ; } /*fbny*/ else{ /*k5*/;; }}}/*57r*/{int iHW ,k ; volatile int cYucnb,//ZsQpN kYD ,jk ,MigTxQ, tU, DD/*3E*//*H*/, Ha ,sWM /*Ycp*/,p , TgI ; k =TgI +cYucnb + kYD +jk+ MigTxQ +tU; for(int i=1 ; i< 70;++i ) for//jV (int i=1 ;i<71;++i/*BK*/) { int QQIm ;volatile int Zh,g37 , nzL ;QQIm =/*PC5*/nzL + //Bh Zh+g37 ; for(int i=1 ; i< 72 ;++i ) if ( true){return 273918517 ;{ for /*f1w*/(int i=1 ;i<73 ;++i/*e*/){}for(int i=1 ;i<74 ;++i ){return 701179560;}}if (true)return 947020880;else {{return 1418285300;} { if ( /*x*/true) { }else { }if ( true ) { } else { } } }} else { for(int i=1/*SZZ*/ ;/*H*/ i<75 ;++i ) { int qSi ;volatile int UkRK ,WHu ; qSi=WHu+ //y UkRK ;/*bN*/ } } {return 731672588 ;if ( true ) { }else { } } }{ /*p*/ ;{/*9s*/{//v }}{ return 685353140 ; {int g0g; volatile int mlt3 ;/*7GI*/for (int i=1 ; i</*iK1hGWP*/76 ;++i )g0g=mlt3 ; if( true ) return//8Mknj 1866251558; else return 459065220 ;} { }} } for(int i=1/*WRUY*/; i< 77 ;++i ) if( true)for (int i=1 ; i< 78;++i)for (int i=1 ; i<79 ;++i ){ if ( true ) {{ {} /*BJ*/{} }} else return 1759302931 ; { { } ;{ {for (int i=1 ; i< 80;++i ) /*E*/{ }/*9*/}; } ;{{ } }} }else /*m*/ iHW= DD//Vr +Ha //JJ + sWM +p ;/*x2*/if( true )return 901312828 ; //k else ;} }
10.343072
61
0.450488
TianyiChen
b26af8c0fa87c0a6ce64a4b200a5a1d80aefdff5
53,298
cpp
C++
surfgradDemo/main.cpp
mmikk/surfgrad-bump-standalone-demo
82f5f9979cf1f295ee73747db0bcdd906c99c752
[ "MIT" ]
55
2020-10-21T19:03:55.000Z
2022-03-24T19:33:16.000Z
surfgradDemo/main.cpp
mmikk/surfgrad-bump-standalone-demo
82f5f9979cf1f295ee73747db0bcdd906c99c752
[ "MIT" ]
null
null
null
surfgradDemo/main.cpp
mmikk/surfgrad-bump-standalone-demo
82f5f9979cf1f295ee73747db0bcdd906c99c752
[ "MIT" ]
3
2020-10-22T06:20:06.000Z
2020-11-23T07:18:32.000Z
// This sample was made by Morten S. Mikkelsen // It illustrates how to do compositing of bump maps in complex scenarios using the surface gradient based framework. #define SHOW_DEMO_SCENE #include "DXUT.h" #include "DXUTcamera.h" #include "DXUTgui.h" //#include "DXUTsettingsDlg.h" #include "SDKmisc.h" //#include "SDKMesh.h" #include <d3d11_2.h> #include "strsafe.h" #include <stdlib.h> #include <math.h> #include "scenegraph.h" #ifdef SHOW_DEMO_SCENE #include "shadows.h" #include "canvas.h" #endif #include "debug_volume_base.h" #define RECOMPILE_SCRBOUND_CS_SHADER #define DISABLE_QUAT #include <geommath/geommath.h> #include "shader.h" #include "shaderpipeline.h" #include "std_cbuffer.h" #include "shaderutils.h" #include "texture_rt.h" #include "buffer.h" #include <wchar.h> CDXUTDialogResourceManager g_DialogResourceManager; CDXUTTextHelper * g_pTxtHelper = NULL; CFirstPersonCamera g_Camera; CShader scrbound_shader; CShader volumelist_coarse_shader; CShader volumelist_exact_shader; static CShader debug_vol_vert_shader, debug_vol_pix_shader; static CShaderPipeline debug_volume_shader_pipeline; #ifndef SHOW_DEMO_SCENE static CShader vert_shader, pix_shader; static CShader vert_shader_basic; static ID3D11InputLayout * g_pVertexLayout = NULL; static ID3D11InputLayout * g_pVertexSimpleLayout = NULL; CShaderPipeline shader_dpthfill_pipeline; CShaderPipeline shader_pipeline; ID3D11Buffer * g_pMeshInstanceCB = NULL; #define MODEL_NAME "ground2_reduced.fil" #define MODEL_PATH ".\\" #define MODEL_PATH_W WIDEN(MODEL_PATH) #include "mesh_fil.h" #endif ID3D11Buffer * g_pGlobalsCB = NULL; CBufferObject g_VolumeDataBuffer; CBufferObject g_ScrSpaceAABounds; ID3D11Buffer * g_pVolumeClipInfo = NULL; CBufferObject g_volumeListBuffer; CBufferObject g_OrientedBounds; #define WIDEN2(x) L ## x #define WIDEN(x) WIDEN2(x) #ifndef SHOW_DEMO_SCENE #define MAX_LEN 64 #define NR_TEXTURES 1 const WCHAR tex_names[NR_TEXTURES][MAX_LEN] = {L"normals.png"}; const char stex_names[NR_TEXTURES][MAX_LEN] = {"g_norm_tex"}; static ID3D11ShaderResourceView * g_pTexturesHandler[NR_TEXTURES]; #else #include "meshimport/meshdraw.h" #endif #ifndef M_PI #define M_PI 3.1415926535897932384626433832795 #endif bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ); void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext ); bool CALLBACK IsD3D11DeviceAcceptable( const CD3D11EnumAdapterInfo *AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo *DeviceInfo, DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext ); HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); void CALLBACK OnD3D11DestroyDevice( void* pUserContext ); void CALLBACK OnKeyboard( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ); HRESULT CALLBACK OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, IDXGISwapChain* pSwapChain, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); void CALLBACK OnD3D11ReleasingSwapChain( void* pUserContext ); LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ); void myFrustum(float * pMat, const float fLeft, const float fRight, const float fBottom, const float fTop, const float fNear, const float fFar); #ifndef SHOW_DEMO_SCENE CMeshFil g_cMesh; #endif static int g_iCullMethod = 1; #ifdef SHOW_DEMO_SCENE static int g_iVisualMode = 1; #else static int g_iVisualMode = 0; #endif static int g_iMenuVisib = 1; static int g_iDecalBlendingMethod = 0; // additive, masked, decal dir static bool g_bUseSecondaryUVsetOnPirate = true; static int g_iBumpFromHeightMapMethod = 0; static bool g_bEnableDecalMipMapping = true; static bool g_bEnableDecals = true; static bool g_bShowNormalsWS = false; static bool g_bIndirectSpecular = true; static bool g_bShowDebugVolumes = false; static bool g_bEnableShadows = true; #include "volume_definitions.h" #include "VolumeTiling.h" int g_iSqrtNrVolumes = 0; int g_iNrVolumes = MAX_NR_VOLUMES_PER_CAMERA; SFiniteVolumeData g_sLgtData[MAX_NR_VOLUMES_PER_CAMERA]; SFiniteVolumeBound g_sLgtColiData[MAX_NR_VOLUMES_PER_CAMERA]; CVolumeTiler g_cVolumeTiler; static float frnd() { return (float) (((double) (rand() % (RAND_MAX+1))) / RAND_MAX); } CTextureObject g_tex_depth; #ifdef SHOW_DEMO_SCENE CShadowMap g_shadowMap; CCanvas g_canvas; #endif void InitApp() { g_Camera.SetRotateButtons( true, false, false ); g_Camera.SetEnablePositionMovement( true ); #ifdef SHOW_DEMO_SCENE const float scale = 0.04f; #else const float scale = 1.0f; // 0.1f #endif g_Camera.SetScalers( 0.2f*0.005f, 3*100.0f * scale ); DirectX::XMVECTOR vEyePt, vEyeTo; Vec3 cam_pos = 75.68f*Normalize(Vec3(16,0,40)); // normal vEyePt = DirectX::XMVectorSet(cam_pos.x, cam_pos.y, -cam_pos.z, 1.0f); //vEyeTo = DirectX::XMVectorSet(0.0f, 2.0f, 0.0f, 1.0f); vEyeTo = DirectX::XMVectorSet(10.0f, 2.0f, 0.0f, 1.0f); // surfgrad demo #ifdef SHOW_DEMO_SCENE const float g_O = 2*2.59f; const float g_S = -1.0f; // convert unity scene to right hand frame. vEyeTo = DirectX::XMVectorSet(g_S*3.39f+g_O, 1.28f+0.3, -0.003f+1.5, 1.0f); vEyePt = DirectX::XMVectorSet(g_S*3.39f+g_O-10, 1.28f+2.5, -0.003f, 1.0f); #endif g_Camera.SetViewParams( vEyePt, vEyeTo ); g_iSqrtNrVolumes = (int) sqrt((double) g_iNrVolumes); assert((g_iSqrtNrVolumes*g_iSqrtNrVolumes)<=g_iNrVolumes); g_iNrVolumes = g_iSqrtNrVolumes*g_iSqrtNrVolumes; } void RenderText() { g_pTxtHelper->Begin(); g_pTxtHelper->SetInsertionPos( 2, 0 ); g_pTxtHelper->SetForegroundColor(DirectX::XMFLOAT4(1.0f, 1.0f, 0.0f, 1.0f)); g_pTxtHelper->DrawTextLine( DXUTGetFrameStats(true) ); if(g_iMenuVisib!=0) { #ifndef SHOW_DEMO_SCENE g_pTxtHelper->DrawTextLine(L"This scene is forward lit by 1024 lights of different shapes. High performance is achieved using FPTL.\n"); #else g_pTxtHelper->DrawTextLine(L"This scene illustrates advanced bump map compositing using the surface gradient based framework.\n"); #endif g_pTxtHelper->DrawTextLine(L"Rotate the camera by using the mouse while pressing and holding the left mouse button.\n"); g_pTxtHelper->DrawTextLine(L"Move the camera by using the arrow keys or: w, a, s, d\n"); g_pTxtHelper->DrawTextLine(L"Hide menu using the x key.\n"); #ifdef SHOW_DEMO_SCENE // U if(g_bUseSecondaryUVsetOnPirate) g_pTxtHelper->DrawTextLine(L"Secondary UV set on the pirate On (toggle using u)\n"); else g_pTxtHelper->DrawTextLine(L"Secondary UV set on the pirate Off (toggle using u)\n"); // H if(g_iBumpFromHeightMapMethod==2) g_pTxtHelper->DrawTextLine(L"Bump from Height - 1 tap (toggle using h)\n"); else if(g_iBumpFromHeightMapMethod==1) g_pTxtHelper->DrawTextLine(L"Bump from Height - 3 taps (toggle using h)\n"); else g_pTxtHelper->DrawTextLine(L"Bump from Height - HQ upscale (toggle using h)\n"); // B if(g_iDecalBlendingMethod==2) g_pTxtHelper->DrawTextLine(L"Decals blending - todays approach uses decal direction (toggle using b)\n"); else if(g_iDecalBlendingMethod==1) g_pTxtHelper->DrawTextLine(L"Decals blending - surfgrad masked (toggle using b)\n"); else g_pTxtHelper->DrawTextLine(L"Decal blending - surfgrad additive (toggle using b)\n"); // M if(g_bEnableDecalMipMapping) g_pTxtHelper->DrawTextLine(L"Decals mip mapping enabled (toggle using m)\n"); else g_pTxtHelper->DrawTextLine(L"Decals mip mapping disabled (toggle using m)\n"); // P if(g_bEnableDecals) g_pTxtHelper->DrawTextLine(L"Projected Decals enabled (toggle using p)\n"); else g_pTxtHelper->DrawTextLine(L"Projected Decals disabled (toggle using p)\n"); // N if(g_bShowNormalsWS) g_pTxtHelper->DrawTextLine(L"Show Normals in world space enabled (toggle using n)\n"); else g_pTxtHelper->DrawTextLine(L"Show Normals in world space disabled (toggle using n)\n"); // R if(g_bIndirectSpecular) g_pTxtHelper->DrawTextLine(L"Indirect Specular Reflection enabled (toggle using r)\n"); else g_pTxtHelper->DrawTextLine(L"Indirect Specular Reflection disabled (toggle using r)\n"); // V if(g_bShowDebugVolumes) g_pTxtHelper->DrawTextLine(L"Show decal volumes in wireframe enabled (toggle using v)\n"); else g_pTxtHelper->DrawTextLine(L"Show decal volumes in wireframe disabled (toggle using v)\n"); // I if(g_bEnableShadows) g_pTxtHelper->DrawTextLine(L"Shadows enabled (toggle using i)\n"); else g_pTxtHelper->DrawTextLine(L"Shadows disabled (toggle using i)\n"); #endif #ifdef SHOW_DEMO_SCENE #else if (g_iCullMethod == 0) g_pTxtHelper->DrawTextLine(L"Fine pruning disabled (toggle using m)\n"); else g_pTxtHelper->DrawTextLine(L"Fine pruning enabled (toggle using m)\n"); #endif // O if (g_iVisualMode == 0) g_pTxtHelper->DrawTextLine(L"Show Decal Overlaps enabled (toggle using o)\n"); else g_pTxtHelper->DrawTextLine(L"Show Decal Overlaps disabled (toggle using o)\n"); } g_pTxtHelper->End(); } float Lerp(const float fA, const float fB, const float fT) { return fA*(1-fT) + fB*fT; } // full fov from left to right void InitVolumeEntry(SFiniteVolumeData &lgtData, SFiniteVolumeBound &lgtColiData, const Mat44 &mat, const Vec3 vSize, const float range, const float fov, unsigned int uFlag) { Mat33 rot; for(int c=0; c<3; c++) { const Vec4 col = GetColumn(mat, c); SetColumn(&rot, c, Vec3(col.x, col.y, col.z)); } const Vec4 lastCol = GetColumn(mat, 3); const Vec3 vCen = Vec3(lastCol.x, lastCol.y, lastCol.z); float fFar = range; float fNear = 0.80*range; lgtData.vLpos = vCen; lgtData.fInvRange = -1/(fFar-fNear); lgtData.fNearRadiusOverRange_LP0 = fFar/(fFar-fNear); lgtData.fSphRadiusSq = fFar*fFar; float fFov = fov; // full fov from left to right float fSeg = Lerp(2*range, 3*range, frnd()); lgtData.fSegLength = (uFlag==WEDGE_VOLUME || uFlag==CAPSULE_VOLUME) ? fSeg : 0.0f; lgtData.uVolumeType = uFlag; Vec3 vX = GetColumn(rot, 0); Vec3 vY = GetColumn(rot, 1); Vec3 vZ = GetColumn(rot, 2); // default coli settings lgtColiData.vBoxAxisX = vX; lgtColiData.vBoxAxisY = vY; lgtColiData.vBoxAxisZ = vZ; lgtColiData.vScaleXZ = Vec2(1.0f, 1.0f); lgtData.vAxisX = vX; lgtData.vAxisY = vY; lgtData.vAxisZ = vZ; // build colision info for each volume type if(uFlag==CAPSULE_VOLUME) { lgtColiData.fRadius = range + 0.5*fSeg; lgtColiData.vCen = vCen + (0.5*fSeg)*lgtColiData.vBoxAxisX; lgtColiData.vBoxAxisX *= (range+0.5*fSeg); lgtColiData.vBoxAxisY *= range; lgtColiData.vBoxAxisZ *= range; lgtData.vCol = Vec3(1.0, 0.1, 1.0); } else if(uFlag==SPHERE_VOLUME) { lgtColiData.vBoxAxisX *= range; lgtColiData.vBoxAxisY *= range; lgtColiData.vBoxAxisZ *= range; lgtColiData.fRadius = range; lgtColiData.vCen = vCen; lgtData.vCol = Vec3(1,1,1); } else if(uFlag==SPOT_CIRCULAR_VOLUME || uFlag==WEDGE_VOLUME) { if(uFlag==SPOT_CIRCULAR_VOLUME) lgtData.vCol = Vec3(0*0.7,0.6,1); else lgtData.vCol = Vec3(1,0.6,0*0.7); float fQ = uFlag==WEDGE_VOLUME ? 0.1 : 1; //Vec3 vDir = Normalize( Vec3(fQ*0.5*(2*frnd()-1), -1, fQ*0.5*(2*frnd()-1)) ); lgtData.fPenumbra = cosf(fFov*0.5); lgtData.fInvUmbraDelta = 1/( lgtData.fPenumbra - cosf(0.02*(fFov*0.5)) ); Vec3 vDir = -vY; //Vec3 vY = lgtColiData.vBoxAxisY; //Vec3 vTmpAxis = (fabsf(vY.x)<=fabsf(vY.y) && fabsf(vY.x)<=fabsf(vY.z)) ? Vec3(1,0,0) : ( fabsf(vY.y)<=fabsf(vY.z) ? Vec3(0,1,0) : Vec3(0,0,1) ); //Vec3 vX = Normalize( Cross(vY,vTmpAxis ) ); //lgtColiData.vBoxAxisZ = Cross(vX, vY); //lgtColiData.vBoxAxisX = vX; // this is silly but nevertheless where this is passed in engine (note the coliData is setup with vBoxAxisY==-vDir). // apply nonuniform scale to OBB of spot volume bool bSqueeze = true;//uFlag==SPOT_CIRCULAR_VOLUME && fFov<0.7*(M_PI*0.5f); float fS = bSqueeze ? tan(0.5*fFov) : sin(0.5*fFov); lgtColiData.vCen += (vCen + ((0.5f*range)*vDir) + ((0.5f*lgtData.fSegLength)*vX)); lgtColiData.vBoxAxisX *= (fS*range + 0.5*lgtData.fSegLength); lgtColiData.vBoxAxisY *= (0.5f*range); lgtColiData.vBoxAxisZ *= (fS*range); float fAltDx = sin(0.5*fFov); float fAltDy = cos(0.5*fFov); fAltDy = fAltDy-0.5; if(fAltDy<0) fAltDy=-fAltDy; fAltDx *= range; fAltDy *= range; fAltDx += (0.5f*lgtData.fSegLength); float fAltDist = sqrt(fAltDy*fAltDy+fAltDx*fAltDx); lgtColiData.fRadius = fAltDist>(0.5*range) ? fAltDist : (0.5*range); if(bSqueeze) lgtColiData.vScaleXZ = Vec2(0.01f, 0.01f); } else if(uFlag==BOX_VOLUME) { //Mat33 rot; LoadRotation(&rot, 2*M_PI*frnd(), 2*M_PI*frnd(), 2*M_PI*frnd()); float fSx = vSize.x;//5*2*(10*frnd()+4); float fSy = vSize.y;//5*2*(10*frnd()+4); float fSz = vSize.z;//5*2*(10*frnd()+4); //float fSx2 = 0.1f*fSx; //float fSy2 = 0.1f*fSy; //float fSz2 = 0.1f*fSz; float fSx2 = 0.85f*fSx; float fSy2 = 0.85f*fSy; float fSz2 = 0.85f*fSz; lgtColiData.vBoxAxisX = fSx*lgtData.vAxisX; lgtColiData.vBoxAxisY = fSy*lgtData.vAxisY; lgtColiData.vBoxAxisZ = fSz*lgtData.vAxisZ; lgtColiData.vCen = vCen; lgtColiData.fRadius = sqrtf(fSx*fSx+fSy*fSy+fSz*fSz); lgtData.vCol = Vec3(0.1,1,0.16); lgtData.fSphRadiusSq = lgtColiData.fRadius*lgtColiData.fRadius; lgtData.vBoxInnerDist = Vec3(fSx2, fSy2, fSz2); lgtData.vBoxInvRange = Vec3( 1/(fSx-fSx2), 1/(fSy-fSy2), 1/(fSz-fSz2) ); } } #ifdef SHOW_DEMO_SCENE void BuildVolumesBuffer() { static bool bBufferMade = false; const float g_O = 2*2.59f; const float g_S = -1.0f; // convert unity scene to right hand frame. if(!bBufferMade) { bBufferMade = true; int iNrLgts = 0; const float deg2rad = M_PI/180.0f; // full fov from left to right float totfov = 70.0f*deg2rad; // insert spot decal { SFiniteVolumeData &lgtData = g_sLgtData[iNrLgts]; SFiniteVolumeBound &lgtColiData = g_sLgtColiData[iNrLgts]; float totfov = 60.0f*deg2rad; const float range = 8.0f; Mat44 mat; LoadIdentity(&mat); LoadRotation(&mat, 55.0f*deg2rad, (180+105.0f)*deg2rad, 0.0f*deg2rad); SetColumn(&mat, 3, Vec3(g_S*3.39f+g_O-4, 1.28f+2.0f, -0.003f-2*0-1)); InitVolumeEntry(g_sLgtData[iNrLgts], lgtColiData, mat, Vec3(0.0f, 0.0f, 0.0f), range, totfov, SPOT_CIRCULAR_VOLUME); //InitVolumeEntry(g_sLgtData[iNrLgts], lgtColiData, mat, Vec3(0.0f, 0.0f, 0.0f), range, totfov, WEDGE_VOLUME); ++iNrLgts; } // insert sphere decal { SFiniteVolumeData &lgtData = g_sLgtData[iNrLgts]; SFiniteVolumeBound &lgtColiData = g_sLgtColiData[iNrLgts]; const float range = 1.6f; Mat44 mat; LoadIdentity(&mat); //LoadRotation(&mat, -30.0f*deg2rad, (180+105.0f)*deg2rad, 0.0f*deg2rad); #if 1 SetColumn(&mat, 3, Vec3(g_S*3.39f+g_O-2-0.7, 1.28f+0.5+0.2, -0.003f-2*0-0.3)); InitVolumeEntry(g_sLgtData[iNrLgts], lgtColiData, mat, Vec3(0.0f, 0.0f, 0.0f), range, totfov, SPHERE_VOLUME); #else SetColumn(&mat, 3, Vec3(g_S*3.39f+g_O-2-0.7-7, 1.28f+0.5+0.2, -0.003f-2*0-0.3)); InitVolumeEntry(g_sLgtData[iNrLgts], lgtColiData, mat, Vec3(0.0f, 0.0f, 0.0f), 0.3*range, totfov, CAPSULE_VOLUME); #endif ++iNrLgts; } // insert box decal { SFiniteVolumeData &lgtData = g_sLgtData[iNrLgts]; SFiniteVolumeBound &lgtColiData = g_sLgtColiData[iNrLgts]; const Vec3 vSize = Vec3(0.5*1.2f,0.5*1.2f,1.7); const float range = Length(vSize); Mat44 mat; LoadIdentity(&mat); LoadRotation(&mat, -30.0f*deg2rad, (180+105.0f)*deg2rad, 0.0f*deg2rad); SetColumn(&mat, 3, Vec3(g_S*3.39f+g_O-1, 1.28f, -0.003f-2-1)); //const Vec4 nose = -GetColumn(mat, 2); InitVolumeEntry(g_sLgtData[iNrLgts], lgtColiData, mat, vSize, range, totfov, BOX_VOLUME); ++iNrLgts; } g_cVolumeTiler.InitTiler(); g_iNrVolumes = iNrLgts; } } #else void BuildVolumesBuffer() { static bool bBufferMade = false; if(!bBufferMade) { bBufferMade = true; // build volume lists int iNrLgts = 0; int iRealCounter = 0; while(iNrLgts<g_iNrVolumes) { // 5 volume types define in unsigned int uFlag = rand()%MAX_TYPES; const int iX = iNrLgts % g_iSqrtNrVolumes; const int iZ = iNrLgts / g_iSqrtNrVolumes; const float fX = 4000*(2*((iX+0.5f)/g_iSqrtNrVolumes)-1); const float fZ = 4000*(2*((iZ+0.5f)/g_iSqrtNrVolumes)-1); const float fY = g_cMesh.QueryTopY(fX, fZ)+12*5 + (uFlag==WEDGE_VOLUME || uFlag==CAPSULE_VOLUME ? 2*50 : 0); const Vec3 vCen = Vec3(fX, fY, fZ); const float fT = frnd(); const float fRad = (uFlag==SPOT_CIRCULAR_VOLUME ? 3.0 : 2.0)*(100*fT + 80*(1-fT)+1); { SFiniteVolumeData &lgtData = g_sLgtData[iNrLgts]; SFiniteVolumeBound &lgtColiData = g_sLgtColiData[iNrLgts]; float fFar = fRad; float fNear = 0.80*fRad; lgtData.vLpos = vCen; lgtData.fInvRange = -1/(fFar-fNear); lgtData.fNearRadiusOverRange_LP0 = fFar/(fFar-fNear); lgtData.fSphRadiusSq = fFar*fFar; float fFov = 1.0*frnd()+0.2; // full fov from left to right float fSeg = Lerp(fRad, 0.5*fRad, frnd()); lgtData.fSegLength = (uFlag==WEDGE_VOLUME || uFlag==CAPSULE_VOLUME) ? fSeg : 0.0f; lgtData.uVolumeType = uFlag; lgtData.vAxisX = Vec3(1,0,0); lgtData.vAxisY = Vec3(0,1,0); lgtData.vAxisZ = Vec3(0,0,1); // default coli settings lgtColiData.vBoxAxisX = Vec3(1,0,0); lgtColiData.vBoxAxisY = Vec3(0,1,0); lgtColiData.vBoxAxisZ = Vec3(0,0,1); lgtColiData.vScaleXZ = Vec2(1.0f, 1.0f); // build colision info for each volume type if(uFlag==CAPSULE_VOLUME) { //lgtData.vLdir = lgtColiData.vBoxAxisX; lgtColiData.fRadius = fRad + 0.5*fSeg; lgtColiData.vCen = vCen + (0.5*fSeg)*lgtColiData.vBoxAxisX; lgtColiData.vBoxAxisX *= (fRad+0.5*fSeg); lgtColiData.vBoxAxisY *= fRad; lgtColiData.vBoxAxisZ *= fRad; lgtData.vCol = Vec3(1.0, 0.1, 1.0); } else if(uFlag==SPHERE_VOLUME) { lgtColiData.vBoxAxisX *= fRad; lgtColiData.vBoxAxisY *= fRad; lgtColiData.vBoxAxisZ *= fRad; lgtColiData.fRadius = fRad; lgtColiData.vCen = vCen; lgtData.vCol = Vec3(1,1,1); } else if(uFlag==SPOT_CIRCULAR_VOLUME || uFlag==WEDGE_VOLUME) { if(uFlag==SPOT_CIRCULAR_VOLUME) lgtData.vCol = Vec3(0*0.7,0.6,1); else lgtData.vCol = Vec3(1,0.6,0*0.7); fFov *= 2; float fQ = uFlag==WEDGE_VOLUME ? 0.1 : 1; Vec3 vDir = Normalize( Vec3(fQ*0.5*(2*frnd()-1), -1, fQ*0.5*(2*frnd()-1)) ); //lgtData.vBoxAxisX = vDir; // Spot Dir lgtData.fPenumbra = cosf(fFov*0.5); lgtData.fInvUmbraDelta = 1/( lgtData.fPenumbra - cosf(0.02*(fFov*0.5)) ); lgtColiData.vBoxAxisY = -vDir; Vec3 vY = lgtColiData.vBoxAxisY; Vec3 vTmpAxis = (fabsf(vY.x)<=fabsf(vY.y) && fabsf(vY.x)<=fabsf(vY.z)) ? Vec3(1,0,0) : ( fabsf(vY.y)<=fabsf(vY.z) ? Vec3(0,1,0) : Vec3(0,0,1) ); Vec3 vX = Normalize( Cross(vY,vTmpAxis ) ); lgtColiData.vBoxAxisZ = Cross(vX, vY); lgtColiData.vBoxAxisX = vX; // this is silly but nevertheless where this is passed in engine (note the coliData is setup with vBoxAxisY==-vDir). lgtData.vAxisX = vX; lgtData.vAxisY = vY; lgtData.vAxisZ = Cross(vX, vY); // apply nonuniform scale to OBB of spot volume bool bSqueeze = true;//uFlag==SPOT_CIRCULAR_VOLUME && fFov<0.7*(M_PI*0.5f); float fS = bSqueeze ? tan(0.5*fFov) : sin(0.5*fFov); lgtColiData.vCen += (vCen + ((0.5f*fRad)*vDir) + ((0.5f*lgtData.fSegLength)*vX)); lgtColiData.vBoxAxisX *= (fS*fRad + 0.5*lgtData.fSegLength); lgtColiData.vBoxAxisY *= (0.5f*fRad); lgtColiData.vBoxAxisZ *= (fS*fRad); float fAltDx = sin(0.5*fFov); float fAltDy = cos(0.5*fFov); fAltDy = fAltDy-0.5; if(fAltDy<0) fAltDy=-fAltDy; fAltDx *= fRad; fAltDy *= fRad; fAltDx += (0.5f*lgtData.fSegLength); float fAltDist = sqrt(fAltDy*fAltDy+fAltDx*fAltDx); lgtColiData.fRadius = fAltDist>(0.5*fRad) ? fAltDist : (0.5*fRad); if(bSqueeze) lgtColiData.vScaleXZ = Vec2(0.01f, 0.01f); } else if(uFlag==BOX_VOLUME) { Mat33 rot; LoadRotation(&rot, 2*M_PI*frnd(), 2*M_PI*frnd(), 2*M_PI*frnd()); float fSx = 5*2*(10*frnd()+4); float fSy = 5*2*(10*frnd()+4); float fSz = 5*2*(10*frnd()+4); float fSx2 = 0.1f*fSx; float fSy2 = 0.1f*fSy; float fSz2 = 0.1f*fSz; lgtData.vAxisX = GetColumn(rot, 0); lgtData.vAxisY = GetColumn(rot, 1); lgtData.vAxisZ = GetColumn(rot, 2); lgtColiData.vBoxAxisX = fSx*lgtData.vAxisX; lgtColiData.vBoxAxisY = fSy*lgtData.vAxisY; lgtColiData.vBoxAxisZ = fSz*lgtData.vAxisZ; lgtColiData.vCen = vCen; lgtColiData.fRadius = sqrtf(fSx*fSx+fSy*fSy+fSz*fSz); lgtData.vCol = Vec3(0.1,1,0.16); lgtData.fSphRadiusSq = lgtColiData.fRadius*lgtColiData.fRadius; lgtData.vBoxInnerDist = Vec3(fSx2, fSy2, fSz2); lgtData.vBoxInvRange = Vec3( 1/(fSx-fSx2), 1/(fSy-fSy2), 1/(fSz-fSz2) ); } ++iNrLgts; } } g_cVolumeTiler.InitTiler(); } } #endif void RenderDebugVolumes(ID3D11DeviceContext* pd3dImmediateContext) { if(g_iNrVolumes>0) { CShaderPipeline &pipe = debug_volume_shader_pipeline; pipe.PrepPipelineForRendering(pd3dImmediateContext); // set streams and layout pd3dImmediateContext->IASetVertexBuffers( 0, 0, NULL, NULL, NULL ); pd3dImmediateContext->IASetIndexBuffer( NULL, DXGI_FORMAT_UNKNOWN, 0 ); pd3dImmediateContext->IASetInputLayout( NULL ); // Set primitive topology pd3dImmediateContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_LINELIST ); pd3dImmediateContext->DrawInstanced( 2*MAX_NR_SEGMENTS_ON_ANY_VOLUME, g_iNrVolumes, 0, 0); //pd3dImmediateContext->Draw( 2*12, 0); pipe.FlushResources(pd3dImmediateContext); } } void render_surface(ID3D11DeviceContext* pd3dImmediateContext, bool bSimpleLayout) { #ifdef SHOW_DEMO_SCENE RenderSceneGraph(pd3dImmediateContext, bSimpleLayout, g_bEnableDecals, g_bEnableDecalMipMapping, false); #else CShaderPipeline &shader_pipe = bSimpleLayout ? shader_dpthfill_pipeline : shader_pipeline; shader_pipe.PrepPipelineForRendering(pd3dImmediateContext); // set streams and layout UINT stride = sizeof(SFilVert), offset = 0; pd3dImmediateContext->IASetVertexBuffers( 0, 1, g_cMesh.GetVertexBuffer(), &stride, &offset ); pd3dImmediateContext->IASetIndexBuffer( g_cMesh.GetIndexBuffer(), DXGI_FORMAT_R32_UINT, 0 ); pd3dImmediateContext->IASetInputLayout( bSimpleLayout ? g_pVertexSimpleLayout : g_pVertexLayout ); // Set primitive topology pd3dImmediateContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); pd3dImmediateContext->DrawIndexed( 3*g_cMesh.GetNrTriangles(), 0, 0 ); shader_pipe.FlushResources(pd3dImmediateContext); #endif if(!bSimpleLayout && g_bShowDebugVolumes) RenderDebugVolumes(pd3dImmediateContext); } Mat44 g_m44Proj, g_m44InvProj, g_mViewToScr, g_mScrToView; Vec3 XMVToVec3(const DirectX::XMVECTOR vec) { return Vec3(DirectX::XMVectorGetX(vec), DirectX::XMVectorGetY(vec), DirectX::XMVectorGetZ(vec)); } Vec4 XMVToVec4(const DirectX::XMVECTOR vec) { return Vec4(DirectX::XMVectorGetX(vec), DirectX::XMVectorGetY(vec), DirectX::XMVectorGetZ(vec), DirectX::XMVectorGetW(vec)); } Mat44 ToMat44(const DirectX::XMMATRIX &dxmat) { Mat44 res; for (int c = 0; c < 4; c++) SetColumn(&res, c, XMVToVec4(dxmat.r[c])); return res; } void CALLBACK OnD3D11FrameRender( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, double fTime, float fElapsedTime, void* pUserContext ) { HRESULT hr; //const float fTimeDiff = DXUTGetElapsedTime(); // clear screen ID3D11RenderTargetView* pRTV = DXUTGetD3D11RenderTargetView(); ID3D11DepthStencilView* pDSV = g_tex_depth.GetDSV();//DXUTGetD3D11DepthStencilView(); //DXUTGetD3D11DepthStencil(); Vec3 vToPoint = XMVToVec3(g_Camera.GetLookAtPt()); Vec3 cam_pos = XMVToVec3(g_Camera.GetEyePt()); Mat44 world_to_view = ToMat44(g_Camera.GetViewMatrix() ); // get world to view projection Mat44 mZflip; LoadIdentity(&mZflip); SetColumn(&mZflip, 2, Vec4(0,0,-1,0)); #ifndef LEFT_HAND_COORDINATES world_to_view = mZflip * world_to_view * mZflip; #else world_to_view = world_to_view * mZflip; #endif Mat44 m44LocalToWorld; LoadIdentity(&m44LocalToWorld); Mat44 m44LocalToView = world_to_view * m44LocalToWorld; Mat44 Trans = g_m44Proj * world_to_view; // fill constant buffers D3D11_MAPPED_SUBRESOURCE MappedSubResource; #ifndef SHOW_DEMO_SCENE V( pd3dImmediateContext->Map( g_pMeshInstanceCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedSubResource ) ); ((cbMeshInstance *)MappedSubResource.pData)->g_mLocToWorld = Transpose(m44LocalToWorld); ((cbMeshInstance *)MappedSubResource.pData)->g_mWorldToLocal = Transpose(~m44LocalToWorld); pd3dImmediateContext->Unmap( g_pMeshInstanceCB, 0 ); #endif // prefill shadow map #ifdef SHOW_DEMO_SCENE if(g_bEnableShadows) g_shadowMap.RenderShadowMap(pd3dImmediateContext, g_pGlobalsCB, GetSunDir()); #endif // fill constant buffers const Mat44 view_to_world = ~world_to_view; V( pd3dImmediateContext->Map( g_pGlobalsCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedSubResource ) ); ((cbGlobals *)MappedSubResource.pData)->g_mWorldToView = Transpose(world_to_view); ((cbGlobals *)MappedSubResource.pData)->g_mViewToWorld = Transpose(view_to_world); ((cbGlobals *)MappedSubResource.pData)->g_mScrToView = Transpose(g_mScrToView); ((cbGlobals *)MappedSubResource.pData)->g_mProj = Transpose(g_m44Proj); ((cbGlobals *)MappedSubResource.pData)->g_mViewProjection = Transpose(Trans); ((cbGlobals *)MappedSubResource.pData)->g_vCamPos = view_to_world * Vec3(0,0,0); ((cbGlobals *)MappedSubResource.pData)->g_iWidth = DXUTGetDXGIBackBufferSurfaceDesc()->Width; ((cbGlobals *)MappedSubResource.pData)->g_iHeight = DXUTGetDXGIBackBufferSurfaceDesc()->Height; ((cbGlobals *)MappedSubResource.pData)->g_iMode = g_iVisualMode; ((cbGlobals *)MappedSubResource.pData)->g_iDecalBlendingMethod = g_iDecalBlendingMethod; ((cbGlobals *)MappedSubResource.pData)->g_bShowNormalsWS = g_bShowNormalsWS; ((cbGlobals *)MappedSubResource.pData)->g_bIndirectSpecular = g_bIndirectSpecular; ((cbGlobals *)MappedSubResource.pData)->g_vSunDir = GetSunDir(); ((cbGlobals *)MappedSubResource.pData)->g_bEnableShadows = g_bEnableShadows; ((cbGlobals *)MappedSubResource.pData)->g_iBumpFromHeightMapMethod = g_iBumpFromHeightMapMethod; ((cbGlobals *)MappedSubResource.pData)->g_bUseSecondaryUVsetOnPirate = g_bUseSecondaryUVsetOnPirate; pd3dImmediateContext->Unmap( g_pGlobalsCB, 0 ); V( pd3dImmediateContext->Map( g_pVolumeClipInfo, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedSubResource ) ); ((cbBoundsInfo *) MappedSubResource.pData)->g_mProjection = Transpose(g_m44Proj); ((cbBoundsInfo *) MappedSubResource.pData)->g_mInvProjection = Transpose(g_m44InvProj); ((cbBoundsInfo *) MappedSubResource.pData)->g_mScrProjection = Transpose(g_mViewToScr); ((cbBoundsInfo *) MappedSubResource.pData)->g_mInvScrProjection = Transpose(g_mScrToView); ((cbBoundsInfo *) MappedSubResource.pData)->g_iNrVisibVolumes = g_iNrVolumes; ((cbBoundsInfo *) MappedSubResource.pData)->g_vStuff = Vec3(0,0,0); pd3dImmediateContext->Unmap( g_pVolumeClipInfo, 0 ); // build volume list g_cVolumeTiler.InitFrame(world_to_view, g_m44Proj); for(int l=0; l<g_iNrVolumes; l++) { g_cVolumeTiler.AddVolume(g_sLgtData[l], g_sLgtColiData[l]); } g_cVolumeTiler.CompileVolumeList(); // transfer volume bounds V( pd3dImmediateContext->Map( g_OrientedBounds.GetStagedBuffer(), 0, D3D11_MAP_WRITE, 0, &MappedSubResource ) ); for(int l=0; l<g_iNrVolumes; l++) { ((SFiniteVolumeBound *) MappedSubResource.pData)[l] = g_cVolumeTiler.GetOrderedBoundsList()[l]; } pd3dImmediateContext->Unmap( g_OrientedBounds.GetStagedBuffer(), 0 ); V( pd3dImmediateContext->Map( g_VolumeDataBuffer.GetStagedBuffer(), 0, D3D11_MAP_WRITE, 0, &MappedSubResource ) ); for(int l=0; l<g_iNrVolumes; l++) { ((SFiniteVolumeData *) MappedSubResource.pData)[l] = g_cVolumeTiler.GetVolumesDataList()[l]; if(g_iVisualMode==0) ((SFiniteVolumeData *) MappedSubResource.pData)[l].vCol = Vec3(1,1,1); } pd3dImmediateContext->Unmap( g_VolumeDataBuffer.GetStagedBuffer(), 0 ); pd3dImmediateContext->CopyResource(g_VolumeDataBuffer.GetBuffer(), g_VolumeDataBuffer.GetStagedBuffer()); // Convert OBBs of volumes into screen space AABBs (incl. depth) const int nrGroups = (g_iNrVolumes*8 + 63)/64; ID3D11UnorderedAccessView* g_ppNullUAV[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}; ID3D11Buffer * pDatas[] = {g_pVolumeClipInfo}; pd3dImmediateContext->CSSetConstantBuffers(0, 1, pDatas); // pd3dImmediateContext->CopyResource(g_OrientedBounds.GetBuffer(), g_OrientedBounds.GetStagedBuffer()); ID3D11ShaderResourceView * pSRVbounds[] = {g_OrientedBounds.GetSRV()}; pd3dImmediateContext->CSSetShaderResources(0, 1, pSRVbounds); ID3D11UnorderedAccessView * ppAABB_UAV[] = { g_ScrSpaceAABounds.GetUAV() }; pd3dImmediateContext->CSSetUnorderedAccessViews(0, 1, ppAABB_UAV, 0); ID3D11ComputeShader * pShaderCS = (ID3D11ComputeShader *) scrbound_shader.GetDeviceChild(); pd3dImmediateContext->CSSetShader( pShaderCS, NULL, 0 ); pd3dImmediateContext->Dispatch(nrGroups, 1, 1); pd3dImmediateContext->CSSetUnorderedAccessViews(0, 1, g_ppNullUAV, 0); ID3D11ShaderResourceView * pNullSRV_bound[] = {NULL}; pd3dImmediateContext->CSSetShaderResources(0, 1, pNullSRV_bound); // debugging code... /* pd3dImmediateContext->CopyResource(g_pScrSpaceAABounds_staged, g_pScrSpaceAABounds); V( pd3dImmediateContext->Map( g_pScrSpaceAABounds_staged, 0, D3D11_MAP_READ, 0, &MappedSubResource ) ); const Vec3 * pData0 = ((Vec3 *) MappedSubResource.pData); const Vec3 * pData1 = g_cVolumeTiler.GetScrBoundsList(); pd3dImmediateContext->Unmap( g_pScrSpaceAABounds_staged, 0 );*/ // prefill depth const bool bRenderFront = true; float ClearColor[4] = { 0.03f, 0.05f, 0.1f, 0.0f }; DXUTSetupD3D11Views(pd3dImmediateContext); pd3dImmediateContext->OMSetRenderTargets( 0, NULL, pDSV ); pd3dImmediateContext->ClearDepthStencilView( pDSV, D3D11_CLEAR_DEPTH, 1.0f, 0 ); pd3dImmediateContext->RSSetState( GetDefaultRasterSolidCullBack() ); pd3dImmediateContext->OMSetDepthStencilState( GetDefaultDepthStencilState(), 0 ); render_surface(pd3dImmediateContext, true); // resolve shadow map #ifdef SHOW_DEMO_SCENE if(g_bEnableShadows) g_shadowMap.ResolveToScreen(pd3dImmediateContext, g_tex_depth.GetReadOnlyDSV(), g_pGlobalsCB); #endif // restore depth state pd3dImmediateContext->OMSetDepthStencilState( GetDefaultDepthStencilState_NoDepthWrite(), 0 ); // switch to back-buffer pd3dImmediateContext->OMSetRenderTargets( 1, &pRTV, g_tex_depth.GetReadOnlyDSV() ); pd3dImmediateContext->ClearRenderTargetView( pRTV, ClearColor ); const int iNrTilesX = (DXUTGetDXGIBackBufferSurfaceDesc()->Width+15)/16; const int iNrTilesY = (DXUTGetDXGIBackBufferSurfaceDesc()->Height+15)/16; ID3D11ShaderResourceView * pNullSRV[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}; // build a volume list per 16x16 tile ID3D11UnorderedAccessView * ppVolumeList_UAV[] = { g_volumeListBuffer.GetUAV() }; ID3D11ShaderResourceView * pSRV[] = {g_tex_depth.GetSRV(), g_ScrSpaceAABounds.GetSRV(), g_VolumeDataBuffer.GetSRV(), g_OrientedBounds.GetSRV()}; pShaderCS = (ID3D11ComputeShader *) (g_iCullMethod==0 ? volumelist_coarse_shader.GetDeviceChild() : volumelist_exact_shader.GetDeviceChild()); pd3dImmediateContext->CSSetUnorderedAccessViews(0, 1, ppVolumeList_UAV, 0); pd3dImmediateContext->CSSetShaderResources(0, 4, pSRV); pd3dImmediateContext->CSSetShader( pShaderCS, NULL, 0 ); pd3dImmediateContext->Dispatch(iNrTilesX, iNrTilesY, 1); pd3dImmediateContext->CSSetUnorderedAccessViews(0, 1, g_ppNullUAV, 0); pd3dImmediateContext->CSSetShaderResources(0, 4, pNullSRV); // debugging code... /* pd3dImmediateContext->CopyResource(g_pVolumeListBuffer_staged, g_pVolumeListBuffer); V( pd3dImmediateContext->Map( g_pVolumeListBuffer_staged, 0, D3D11_MAP_READ, 0, &MappedSubResource ) ); const unsigned int * pData2 = ((const unsigned int *) MappedSubResource.pData); pd3dImmediateContext->Unmap( g_pVolumeListBuffer_staged, 0 ); */ #ifdef SHOW_DEMO_SCENE // g_canvas.DrawCanvas(pd3dImmediateContext, g_pGlobalsCB); // restore depth state pd3dImmediateContext->OMSetDepthStencilState( GetDefaultDepthStencilState_NoDepthWrite(), 0 ); #endif // Do tiled forward rendering render_surface(pd3dImmediateContext, false); // fire off menu text RenderText(); } int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow ) { // Enable run-time memory check for debug builds. #if defined(DEBUG) | defined(_DEBUG) _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif // Set DXUT callbacks DXUTSetCallbackDeviceChanging( ModifyDeviceSettings ); DXUTSetCallbackMsgProc( MsgProc ); DXUTSetCallbackFrameMove( OnFrameMove ); DXUTSetCallbackD3D11DeviceAcceptable( IsD3D11DeviceAcceptable ); DXUTSetCallbackD3D11DeviceCreated( OnD3D11CreateDevice ); DXUTSetCallbackD3D11SwapChainResized( OnD3D11ResizedSwapChain ); DXUTSetCallbackD3D11FrameRender( OnD3D11FrameRender ); DXUTSetCallbackD3D11SwapChainReleasing( OnD3D11ReleasingSwapChain ); DXUTSetCallbackD3D11DeviceDestroyed( OnD3D11DestroyDevice ); DXUTSetCallbackKeyboard( OnKeyboard ); InitApp(); DXUTInit( true, true ); DXUTSetCursorSettings( true, true ); // Show the cursor and clip it when in full screen DXUTCreateWindow( L"Surface Gradient Based Bump Mapping Demo." ); int dimX = 1280, dimY = 960; DXUTCreateDevice( D3D_FEATURE_LEVEL_11_0, true, dimX, dimY); //DXUTCreateDevice( D3D_FEATURE_LEVEL_11_0, true, 1024, 768); DXUTMainLoop(); // Enter into the DXUT render loop return DXUTGetExitCode(); } //-------------------------------------------------------------------------------------- // Create any D3D11 resources that depend on the back buffer //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, IDXGISwapChain* pSwapChain, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { HRESULT hr; // Setup the camera's projection parameters int w = pBackBufferSurfaceDesc->Width; int h = pBackBufferSurfaceDesc->Height; #ifdef SHOW_DEMO_SCENE const float scale = 0.01f; #else const float scale = 1.0f; // 0.1f #endif //const float fFov = 30; const float fNear = 10 * scale; const float fFar = 10000 * scale; //const float fNear = 45;//275; //const float fFar = 65;//500; //const float fHalfWidthAtMinusNear = fNear * tanf((fFov*((float) M_PI))/360); //const float fHalfHeightAtMinusNear = fHalfWidthAtMinusNear * (((float) 3)/4.0); const float fFov = 2*23; const float fHalfHeightAtMinusNear = fNear * tanf((fFov*((float) M_PI))/360); const float fHalfWidthAtMinusNear = fHalfHeightAtMinusNear * (((float) w)/h); const float fS = 1.0;// 1280.0f / 960.0f; myFrustum(g_m44Proj.m_fMat, -fS*fHalfWidthAtMinusNear, fS*fHalfWidthAtMinusNear, -fHalfHeightAtMinusNear, fHalfHeightAtMinusNear, fNear, fFar); { float fAspectRatio = fS; g_Camera.SetProjParams( (fFov*M_PI)/360, fAspectRatio, fNear, fFar ); } Mat44 mToScr; SetRow(&mToScr, 0, Vec4(0.5*w, 0, 0, 0.5*w)); SetRow(&mToScr, 1, Vec4(0, -0.5*h, 0, 0.5*h)); SetRow(&mToScr, 2, Vec4(0, 0, 1, 0)); SetRow(&mToScr, 3, Vec4(0, 0, 0, 1)); g_mViewToScr = mToScr * g_m44Proj; g_mScrToView = ~g_mViewToScr; g_m44InvProj = ~g_m44Proj; // Set GUI size and locations /*g_HUD.SetLocation( pBackBufferSurfaceDesc->Width - 170, 0 ); g_HUD.SetSize( 170, 170 ); g_SampleUI.SetLocation( pBackBufferSurfaceDesc->Width - 245, pBackBufferSurfaceDesc->Height - 520 ); g_SampleUI.SetSize( 245, 520 );*/ // create render targets const bool bEnableReadBySampling = true; const bool bEnableWriteTo = true; const bool bAllocateMipMaps = false; const bool bAllowStandardMipMapGeneration = false; const void * pInitData = NULL; g_tex_depth.CleanUp(); g_tex_depth.CreateTexture(pd3dDevice,w,h, DXGI_FORMAT_R24G8_TYPELESS, bAllocateMipMaps, false, NULL, bEnableReadBySampling, DXGI_FORMAT_R24_UNORM_X8_TYPELESS, bEnableWriteTo, DXGI_FORMAT_D24_UNORM_S8_UINT, true); //////////////////////////////////////////////// g_volumeListBuffer.CleanUp(); const int nrTiles = ((w+15)/16)*((h+15)/16); g_volumeListBuffer.CreateBuffer(pd3dDevice, NR_USHORTS_PER_TILE*sizeof( unsigned short ) * nrTiles, 0, NULL, CBufferObject::DefaultBuf, true, true, CBufferObject::StagingCpuReadOnly); g_volumeListBuffer.AddTypedSRV(pd3dDevice, DXGI_FORMAT_R16_UINT); g_volumeListBuffer.AddTypedUAV(pd3dDevice, DXGI_FORMAT_R16_UINT); #ifndef SHOW_DEMO_SCENE shader_pipeline.RegisterResourceView("g_vVolumeList", g_volumeListBuffer.GetSRV()); #endif #ifdef SHOW_DEMO_SCENE g_shadowMap.OnResize(pd3dDevice, g_tex_depth.GetSRV()); PassVolumeIndicesPerTileBuffer(g_volumeListBuffer.GetSRV(), g_shadowMap.GetShadowResolveSRV()); #endif //////////////////////////////////////////////// V_RETURN( g_DialogResourceManager.OnD3D11ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) ); //V_RETURN( g_D3DSettingsDlg.OnD3D11ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) ); return S_OK; } //-------------------------------------------------------------------------------------- // Release D3D11 resources created in OnD3D11ResizedSwapChain //-------------------------------------------------------------------------------------- void CALLBACK OnD3D11ReleasingSwapChain( void* pUserContext ) { g_DialogResourceManager.OnD3D11ReleasingSwapChain(); } //-------------------------------------------------------------------------------------- // Handle key presses //-------------------------------------------------------------------------------------- LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ) { #if 0 switch( uMsg ) { case WM_KEYDOWN: // Prevent the camera class to use some prefefined keys that we're already using { switch( (UINT)wParam ) { case VK_CONTROL: case VK_LEFT: { g_fL0ay -= 0.05f; return 0; } break; case VK_RIGHT: { g_fL0ay += 0.05f; return 0; } case VK_UP: { g_fL0ax += 0.05f; if(g_fL0ax>(M_PI/2.5)) g_fL0ax=(M_PI/2.5); return 0; } break; case VK_DOWN: { g_fL0ax -= 0.05f; if(g_fL0ax<-(M_PI/2.5)) g_fL0ax=-(M_PI/2.5); return 0; } break; case 'F': { int iTing; iTing = 0; } default: ; } } break; } #endif // Pass all remaining windows messages to camera so it can respond to user input g_Camera.HandleMessages( hWnd, uMsg, wParam, lParam ); return 0; } void CALLBACK OnKeyboard( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ) { if(bKeyDown) { if(nChar=='M') { #ifndef SHOW_DEMO_SCENE g_iCullMethod = 1-g_iCullMethod; #else g_bEnableDecalMipMapping = !g_bEnableDecalMipMapping; #endif } if(nChar=='O') { g_iVisualMode = 1-g_iVisualMode; } if (nChar == 'X') { g_iMenuVisib = 1 - g_iMenuVisib; } if (nChar == 'B') { g_iDecalBlendingMethod = g_iDecalBlendingMethod+1; if(g_iDecalBlendingMethod>=3) g_iDecalBlendingMethod -= 3; } if (nChar == 'H') { g_iBumpFromHeightMapMethod = g_iBumpFromHeightMapMethod+1; if(g_iBumpFromHeightMapMethod>=3) g_iBumpFromHeightMapMethod -= 3; } if (nChar == 'P') { g_bEnableDecals = !g_bEnableDecals; } if (nChar == 'N') { g_bShowNormalsWS = !g_bShowNormalsWS; } if (nChar == 'R') { g_bIndirectSpecular = !g_bIndirectSpecular; } if (nChar == 'V') { g_bShowDebugVolumes = !g_bShowDebugVolumes; } if (nChar == 'I') { g_bEnableShadows = !g_bEnableShadows; } if (nChar == 'U') { g_bUseSecondaryUVsetOnPirate = !g_bUseSecondaryUVsetOnPirate; } } } //-------------------------------------------------------------------------------------- // Called right before creating a D3D9 or D3D10 device, allowing the app to modify the device settings as needed //-------------------------------------------------------------------------------------- bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ) { // For the first device created if its a REF device, optionally display a warning dialog box static bool s_bFirstTime = true; if( s_bFirstTime ) { s_bFirstTime = false; pDeviceSettings->d3d11.AutoCreateDepthStencil = false; /* s_bFirstTime = false; if( ( DXUT_D3D11_DEVICE == pDeviceSettings->ver && pDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE ) ) { DXUTDisplaySwitchingToREFWarning( pDeviceSettings->ver ); } // Enable 4xMSAA by default DXGI_SAMPLE_DESC MSAA4xSampleDesc = { 4, 0 }; pDeviceSettings->d3d11.sd.SampleDesc = MSAA4xSampleDesc;*/ } return true; } //-------------------------------------------------------------------------------------- // Handle updates to the scene //-------------------------------------------------------------------------------------- void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext ) { // Update the camera's position based on user input g_Camera.FrameMove( fElapsedTime ); } //-------------------------------------------------------------------------------------- // Reject any D3D11 devices that aren't acceptable by returning false //-------------------------------------------------------------------------------------- bool CALLBACK IsD3D11DeviceAcceptable( const CD3D11EnumAdapterInfo *AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo *DeviceInfo, DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext ) { return true; } //-------------------------------------------------------------------------------------- // Create any D3D11 resources that aren't dependant on the back buffer //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { HRESULT hr; // Get device context ID3D11DeviceContext* pd3dImmediateContext = DXUTGetD3D11DeviceContext(); // create text helper V_RETURN( g_DialogResourceManager.OnD3D11CreateDevice(pd3dDevice, pd3dImmediateContext) ); g_pTxtHelper = new CDXUTTextHelper( pd3dDevice, pd3dImmediateContext, &g_DialogResourceManager, 15 ); InitUtils(pd3dDevice); // set compiler flag DWORD dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS; #if defined( DEBUG ) || defined( _DEBUG ) // Set the D3D10_SHADER_DEBUG flag to embed debug information in the shaders. // Setting this flag improves the shader debugging experience, but still allows // the shaders to be optimized and to run exactly the way they will run in // the release configuration of this program. dwShaderFlags |= D3D10_SHADER_DEBUG; #endif //dwShaderFlags |= D3DCOMPILE_OPTIMIZATION_LEVEL0; // create constant buffers D3D11_BUFFER_DESC bd; #ifndef SHOW_DEMO_SCENE memset(&bd, 0, sizeof(bd)); bd.Usage = D3D11_USAGE_DYNAMIC; bd.ByteWidth = (sizeof( cbMeshInstance )+0xf)&(~0xf); bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; bd.MiscFlags = 0; V_RETURN( pd3dDevice->CreateBuffer( &bd, NULL, &g_pMeshInstanceCB ) ); #endif memset(&bd, 0, sizeof(bd)); bd.Usage = D3D11_USAGE_DYNAMIC; bd.ByteWidth = (sizeof( cbGlobals )+0xf)&(~0xf); bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; bd.MiscFlags = 0; V_RETURN( pd3dDevice->CreateBuffer( &bd, NULL, &g_pGlobalsCB ) ); CONST D3D10_SHADER_MACRO* pDefines = NULL; // compile per tile volume list generation compute shader (with and without fine pruning) CONST D3D10_SHADER_MACRO sDefineExact[] = {{"FINE_PRUNING_ENABLED", NULL}, {NULL, NULL}}; volumelist_exact_shader.CompileShaderFunction(pd3dDevice, L"volumelist_cs.hlsl", sDefineExact, "main", "cs_5_0", dwShaderFlags ); volumelist_coarse_shader.CompileShaderFunction(pd3dDevice, L"volumelist_cs.hlsl", pDefines, "main", "cs_5_0", dwShaderFlags ); // compile compute shader for screen-space AABB generation #ifdef RECOMPILE_SCRBOUND_CS_SHADER scrbound_shader.CompileShaderFunction(pd3dDevice, L"scrbound_cs.hlsl", pDefines, "main", "cs_5_0", dwShaderFlags ); FILE * fptr_out = fopen("scrbound_cs.bsh", "wb"); fwrite(scrbound_shader.GetBufferPointer(), 1, scrbound_shader.GetBufferSize(), fptr_out); fclose(fptr_out); #else scrbound_shader.CreateComputeShaderFromBinary(pd3dDevice, "scrbound_cs.bsh"); #endif #ifndef SHOW_DEMO_SCENE // compile tiled forward lighting shader vert_shader.CompileShaderFunction(pd3dDevice, L"shader_lighting_old_fptl_demo.hlsl", pDefines, "RenderSceneVS", "vs_5_0", dwShaderFlags ); pix_shader.CompileShaderFunction(pd3dDevice, L"shader_lighting_old_fptl_demo.hlsl", pDefines, "RenderScenePS", "ps_5_0", dwShaderFlags ); // prepare shader pipeline shader_pipeline.SetVertexShader(&vert_shader); shader_pipeline.SetPixelShader(&pix_shader); // register constant buffers shader_pipeline.RegisterConstBuffer("cbMeshInstance", g_pMeshInstanceCB); shader_pipeline.RegisterConstBuffer("cbGlobals", g_pGlobalsCB); // register samplers shader_pipeline.RegisterSampler("g_samWrap", GetDefaultSamplerWrap() ); shader_pipeline.RegisterSampler("g_samClamp", GetDefaultSamplerClamp() ); shader_pipeline.RegisterSampler("g_samShadow", GetDefaultShadowSampler() ); // depth only pre-pass vert_shader_basic.CompileShaderFunction(pd3dDevice, L"shader_basic.hlsl", pDefines, "RenderSceneVS", "vs_5_0", dwShaderFlags ); shader_dpthfill_pipeline.SetVertexShader(&vert_shader_basic); shader_dpthfill_pipeline.RegisterConstBuffer("cbMeshInstance", g_pMeshInstanceCB); shader_dpthfill_pipeline.RegisterConstBuffer("cbGlobals", g_pGlobalsCB); #endif { debug_vol_vert_shader.CompileShaderFunction(pd3dDevice, L"shader_debug_volumes.hlsl", pDefines, "RenderDebugVolumeVS", "vs_5_0", dwShaderFlags ); debug_vol_pix_shader.CompileShaderFunction(pd3dDevice, L"shader_debug_volumes.hlsl", pDefines, "YellowPS", "ps_5_0", dwShaderFlags ); // prepare shader pipeline debug_volume_shader_pipeline.SetVertexShader(&debug_vol_vert_shader); debug_volume_shader_pipeline.SetPixelShader(&debug_vol_pix_shader); // register constant buffers debug_volume_shader_pipeline.RegisterConstBuffer("cbGlobals", g_pGlobalsCB); // register samplers debug_volume_shader_pipeline.RegisterSampler("g_samWrap", GetDefaultSamplerWrap() ); debug_volume_shader_pipeline.RegisterSampler("g_samClamp", GetDefaultSamplerClamp() ); debug_volume_shader_pipeline.RegisterSampler("g_samShadow", GetDefaultShadowSampler() ); } #ifndef SHOW_DEMO_SCENE // create all textures WCHAR dest_str[256]; for(int t=0; t<NR_TEXTURES; t++) { wcscpy(dest_str, MODEL_PATH_W); wcscat(dest_str, tex_names[t]); V_RETURN(DXUTCreateShaderResourceViewFromFile(pd3dDevice, dest_str, &g_pTexturesHandler[t])); shader_pipeline.RegisterResourceView(stex_names[t], g_pTexturesHandler[t]); if(t==1) shader_dpthfill_pipeline.RegisterResourceView(stex_names[t], g_pTexturesHandler[t]); } #endif #ifndef SHOW_DEMO_SCENE g_cMesh.ReadMeshFil(pd3dDevice, MODEL_PATH MODEL_NAME, 4000.0f, true, true); #endif bd.ByteWidth = (sizeof( cbBoundsInfo )+0xf)&(~0xf); V_RETURN( pd3dDevice->CreateBuffer( &bd, NULL, &g_pVolumeClipInfo ) ); D3D11_SHADER_RESOURCE_VIEW_DESC srvbuffer_desc; // attribute data for volumes such as attenuation, color, etc. g_VolumeDataBuffer.CreateBuffer(pd3dDevice, sizeof( SFiniteVolumeData ) * MAX_NR_VOLUMES_PER_CAMERA, sizeof( SFiniteVolumeData ), NULL, CBufferObject::StructuredBuf, true, false, CBufferObject::StagingCpuWriteOnly); g_VolumeDataBuffer.AddStructuredSRV(pd3dDevice); #ifndef SHOW_DEMO_SCENE shader_pipeline.RegisterResourceView("g_vVolumeData", g_VolumeDataBuffer.GetSRV()); #endif debug_volume_shader_pipeline.RegisterResourceView("g_vVolumeData", g_VolumeDataBuffer.GetSRV()); // buffer for GPU generated screen-space AABB per volume g_ScrSpaceAABounds.CreateBuffer(pd3dDevice, 2 * sizeof(Vec3) * MAX_NR_VOLUMES_PER_CAMERA, sizeof(Vec3), NULL, CBufferObject::StructuredBuf, true, true, CBufferObject::StagingCpuReadOnly); g_ScrSpaceAABounds.AddStructuredSRV(pd3dDevice); g_ScrSpaceAABounds.AddStructuredUAV(pd3dDevice); // a nonuniformly scaled OBB per volume g_OrientedBounds.CreateBuffer(pd3dDevice, sizeof(SFiniteVolumeBound) * MAX_NR_VOLUMES_PER_CAMERA, sizeof(SFiniteVolumeBound), NULL, CBufferObject::StructuredBuf, true, false, CBufferObject::StagingCpuWriteOnly); g_OrientedBounds.AddStructuredSRV(pd3dDevice); InitializeSceneGraph(pd3dDevice, pd3dImmediateContext, g_pGlobalsCB, g_VolumeDataBuffer.GetSRV()); BuildVolumesBuffer(); // create vertex decleration #ifndef SHOW_DEMO_SCENE const D3D11_INPUT_ELEMENT_DESC vertexlayout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, ATTR_OFFS(SFilVert, pos), D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, ATTR_OFFS(SFilVert, s), D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 1, DXGI_FORMAT_R32G32_FLOAT, 0, ATTR_OFFS(SFilVert, s2), D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, ATTR_OFFS(SFilVert, norm), D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 2, DXGI_FORMAT_R32G32B32A32_FLOAT,0, ATTR_OFFS(SFilVert, tang), D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; V_RETURN( pd3dDevice->CreateInputLayout( vertexlayout, ARRAYSIZE( vertexlayout ), vert_shader.GetBufferPointer(), vert_shader.GetBufferSize(), &g_pVertexLayout ) ); const D3D11_INPUT_ELEMENT_DESC simplevertexlayout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, ATTR_OFFS(SFilVert, pos), D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; V_RETURN( pd3dDevice->CreateInputLayout( simplevertexlayout, ARRAYSIZE( simplevertexlayout ), vert_shader_basic.GetBufferPointer(), vert_shader_basic.GetBufferSize(), &g_pVertexSimpleLayout ) ); #endif #ifdef SHOW_DEMO_SCENE g_shadowMap.InitShadowMap(pd3dDevice, g_pGlobalsCB, 4096, 4096); g_canvas.InitCanvas(pd3dDevice, g_pGlobalsCB); #endif return S_OK; } //-------------------------------------------------------------------------------------- // Release D3D11 resources created in OnD3D11CreateDevice //-------------------------------------------------------------------------------------- void CALLBACK OnD3D11DestroyDevice( void* pUserContext ) { g_DialogResourceManager.OnD3D11DestroyDevice(); SAFE_DELETE( g_pTxtHelper ); g_tex_depth.CleanUp(); g_VolumeDataBuffer.CleanUp(); g_ScrSpaceAABounds.CleanUp(); g_OrientedBounds.CleanUp(); g_volumeListBuffer.CleanUp(); #ifndef SHOW_DEMO_SCENE SAFE_RELEASE( g_pMeshInstanceCB ); #endif SAFE_RELEASE( g_pGlobalsCB ); SAFE_RELEASE( g_pVolumeClipInfo ); #ifndef SHOW_DEMO_SCENE for(int t=0; t<NR_TEXTURES; t++) SAFE_RELEASE( g_pTexturesHandler[t] ); #endif ReleaseSceneGraph(); #ifndef SHOW_DEMO_SCENE g_cMesh.CleanUp(); #endif #ifndef SHOW_DEMO_SCENE vert_shader.CleanUp(); pix_shader.CleanUp(); vert_shader_basic.CleanUp(); #endif debug_vol_vert_shader.CleanUp(); debug_vol_pix_shader.CleanUp(); scrbound_shader.CleanUp(); volumelist_coarse_shader.CleanUp(); volumelist_exact_shader.CleanUp(); #ifndef SHOW_DEMO_SCENE SAFE_RELEASE( g_pVertexLayout ); SAFE_RELEASE( g_pVertexSimpleLayout ); #endif #ifdef SHOW_DEMO_SCENE g_shadowMap.CleanUp(); g_canvas.CleanUp(); #endif DeinitUtils(); } // [0;1] but right hand coordinate system void myFrustum(float * pMat, const float fLeft, const float fRight, const float fBottom, const float fTop, const float fNear, const float fFar) { // first column pMat[0*4 + 0] = (2 * fNear) / (fRight - fLeft); pMat[0*4 + 1] = 0; pMat[0*4 + 2] = 0; pMat[0*4 + 3] = 0; // second column pMat[1*4 + 0] = 0; pMat[1*4 + 1] = (2 * fNear) / (fTop - fBottom); pMat[1*4 + 2] = 0; pMat[1*4 + 3] = 0; // fourth column pMat[3*4 + 0] = 0; pMat[3*4 + 1] = 0; pMat[3*4 + 2] = -(fFar * fNear) / (fFar - fNear); pMat[3*4 + 3] = 0; // third column pMat[2*4 + 0] = (fRight + fLeft) / (fRight - fLeft); pMat[2*4 + 1] = (fTop + fBottom) / (fTop - fBottom); pMat[2*4 + 2] = -fFar / (fFar - fNear); pMat[2*4 + 3] = -1; #ifdef LEFT_HAND_COORDINATES for(int r=0; r<4; r++) pMat[2*4 + r] = -pMat[2*4 + r]; #endif }
33.478643
216
0.707569
mmikk
05cf6f58b90b4b7ed4ec36a1aaed0cac03615d00
9,164
cpp
C++
src/vision_opencv/opencv_apps/src/nodelet/segment_objects_nodelet.cpp
mwimble/kaimiPi
92ea97f7d761ed38fb490dab10bfdf09c2ba352f
[ "FSFAP" ]
1
2022-03-29T07:26:29.000Z
2022-03-29T07:26:29.000Z
src/vision_opencv/opencv_apps/src/nodelet/segment_objects_nodelet.cpp
mwimble/kaimiPi
92ea97f7d761ed38fb490dab10bfdf09c2ba352f
[ "FSFAP" ]
null
null
null
src/vision_opencv/opencv_apps/src/nodelet/segment_objects_nodelet.cpp
mwimble/kaimiPi
92ea97f7d761ed38fb490dab10bfdf09c2ba352f
[ "FSFAP" ]
null
null
null
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2014, Kei Okada. * 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 Kei Okada nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ // https://github.com/Itseez/opencv/blob/2.4/samples/cpp/segment_objects.cpp /** * This program demonstrated a simple method of connected components clean up of background subtraction */ #include <ros/ros.h> #include "opencv_apps/nodelet.h" #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/video/background_segm.hpp> #include <dynamic_reconfigure/server.h> #include "opencv_apps/SegmentObjectsConfig.h" #include "std_srvs/Empty.h" #include "std_msgs/Float64.h" #include "opencv_apps/Contour.h" #include "opencv_apps/ContourArray.h" #include "opencv_apps/ContourArrayStamped.h" namespace segment_objects { class SegmentObjectsNodelet : public opencv_apps::Nodelet { image_transport::Publisher img_pub_; image_transport::Subscriber img_sub_; image_transport::CameraSubscriber cam_sub_; ros::Publisher msg_pub_, area_pub_; ros::ServiceServer update_bg_model_service_; boost::shared_ptr<image_transport::ImageTransport> it_; segment_objects::SegmentObjectsConfig config_; dynamic_reconfigure::Server<segment_objects::SegmentObjectsConfig> srv; bool debug_view_; ros::Time prev_stamp_; std::string window_name_; static bool need_config_update_; #ifndef CV_VERSION_EPOCH cv::Ptr<cv::BackgroundSubtractorMOG2> bgsubtractor; #else cv::BackgroundSubtractorMOG bgsubtractor; #endif bool update_bg_model; void reconfigureCallback(segment_objects::SegmentObjectsConfig &new_config, uint32_t level) { config_ = new_config; } const std::string &frameWithDefault(const std::string &frame, const std::string &image_frame) { if (frame.empty()) return image_frame; return frame; } void imageCallbackWithInfo(const sensor_msgs::ImageConstPtr& msg, const sensor_msgs::CameraInfoConstPtr& cam_info) { do_work(msg, cam_info->header.frame_id); } void imageCallback(const sensor_msgs::ImageConstPtr& msg) { do_work(msg, msg->header.frame_id); } static void trackbarCallback( int, void* ) { need_config_update_ = true; } void do_work(const sensor_msgs::ImageConstPtr& msg, const std::string input_frame_from_msg) { // Work on the image. try { // Convert the image into something opencv can handle. cv::Mat frame = cv_bridge::toCvShare(msg, msg->encoding)->image; // Messages opencv_apps::ContourArrayStamped contours_msg; contours_msg.header = msg->header; // Do the work cv::Mat bgmask, out_frame; if( debug_view_) { /// Create Trackbars for Thresholds cv::namedWindow( window_name_, cv::WINDOW_AUTOSIZE ); if (need_config_update_) { srv.updateConfig(config_); need_config_update_ = false; } } #ifndef CV_VERSION_EPOCH bgsubtractor->apply(frame, bgmask, update_bg_model ? -1 : 0); #else bgsubtractor(frame, bgmask, update_bg_model ? -1 : 0); #endif //refineSegments(tmp_frame, bgmask, out_frame); int niters = 3; std::vector<std::vector<cv::Point> > contours; std::vector<cv::Vec4i> hierarchy; cv::Mat temp; cv::dilate(bgmask, temp, cv::Mat(), cv::Point(-1,-1), niters); cv::erode(temp, temp, cv::Mat(), cv::Point(-1,-1), niters*2); cv::dilate(temp, temp, cv::Mat(), cv::Point(-1,-1), niters); cv::findContours( temp, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE ); out_frame = cv::Mat::zeros(frame.size(), CV_8UC3); if( contours.size() == 0 ) return; // iterate through all the top-level contours, // draw each connected component with its own random color int idx = 0, largestComp = 0; double maxArea = 0; for( ; idx >= 0; idx = hierarchy[idx][0] ) { const std::vector<cv::Point>& c = contours[idx]; double area = fabs(cv::contourArea(cv::Mat(c))); if( area > maxArea ) { maxArea = area; largestComp = idx; } } cv::Scalar color( 0, 0, 255 ); cv::drawContours( out_frame, contours, largestComp, color, CV_FILLED, 8, hierarchy ); std_msgs::Float64 area_msg; area_msg.data = maxArea; for( size_t i = 0; i< contours.size(); i++ ) { opencv_apps::Contour contour_msg; for ( size_t j = 0; j < contours[i].size(); j++ ) { opencv_apps::Point2D point_msg; point_msg.x = contours[i][j].x; point_msg.y = contours[i][j].y; contour_msg.points.push_back(point_msg); } contours_msg.contours.push_back(contour_msg); } //-- Show what you got if( debug_view_) { cv::imshow( window_name_, out_frame ); int keycode = cv::waitKey(1); //if( keycode == 27 ) // break; if( keycode == ' ' ) { update_bg_model = !update_bg_model; NODELET_INFO("Learn background is in state = %d",update_bg_model); } } // Publish the image. sensor_msgs::Image::Ptr out_img = cv_bridge::CvImage(msg->header, "bgr8", out_frame).toImageMsg(); img_pub_.publish(out_img); msg_pub_.publish(contours_msg); area_pub_.publish(area_msg); } catch (cv::Exception &e) { NODELET_ERROR("Image processing error: %s %s %s %i", e.err.c_str(), e.func.c_str(), e.file.c_str(), e.line); } prev_stamp_ = msg->header.stamp; } bool update_bg_model_cb(std_srvs::Empty::Request& request, std_srvs::Empty::Response& response) { update_bg_model = !update_bg_model; NODELET_INFO("Learn background is in state = %d",update_bg_model); return true; } void subscribe() { NODELET_DEBUG("Subscribing to image topic."); if (config_.use_camera_info) cam_sub_ = it_->subscribeCamera("image", 3, &SegmentObjectsNodelet::imageCallbackWithInfo, this); else img_sub_ = it_->subscribe("image", 3, &SegmentObjectsNodelet::imageCallback, this); } void unsubscribe() { NODELET_DEBUG("Unsubscribing from image topic."); img_sub_.shutdown(); cam_sub_.shutdown(); } public: virtual void onInit() { Nodelet::onInit(); it_ = boost::shared_ptr<image_transport::ImageTransport>(new image_transport::ImageTransport(*nh_)); pnh_->param("debug_view", debug_view_, false); if (debug_view_) { always_subscribe_ = true; } prev_stamp_ = ros::Time(0, 0); window_name_ = "segmented"; update_bg_model = true; #ifndef CV_VERSION_EPOCH bgsubtractor = cv::createBackgroundSubtractorMOG2(); #else bgsubtractor.set("noiseSigma", 10); #endif dynamic_reconfigure::Server<segment_objects::SegmentObjectsConfig>::CallbackType f = boost::bind(&SegmentObjectsNodelet::reconfigureCallback, this, _1, _2); srv.setCallback(f); img_pub_ = advertiseImage(*pnh_, "image", 1); msg_pub_ = advertise<opencv_apps::ContourArrayStamped>(*pnh_, "contours", 1); area_pub_ = advertise<std_msgs::Float64>(*pnh_, "area", 1); update_bg_model_service_ = pnh_->advertiseService("update_bg_model", &SegmentObjectsNodelet::update_bg_model_cb, this); onInitPostProcess(); } }; bool SegmentObjectsNodelet::need_config_update_ = false; } #include <pluginlib/class_list_macros.h> PLUGINLIB_EXPORT_CLASS(segment_objects::SegmentObjectsNodelet, nodelet::Nodelet);
33.083032
123
0.678306
mwimble
05d09fa85f4ff909e6ed03acc4552dc3c95ad691
8,559
cpp
C++
SpelJongEmu/src/AluFunctions.cpp
fallahn/speljongen
57cb5e09eec7db8c21ee7b3e7943fa0a76738c51
[ "Unlicense" ]
17
2018-06-23T14:40:56.000Z
2019-07-02T11:58:55.000Z
SpelJongEmu/src/AluFunctions.cpp
fallahn/speljongen
57cb5e09eec7db8c21ee7b3e7943fa0a76738c51
[ "Unlicense" ]
3
2018-06-23T12:35:12.000Z
2018-06-23T12:38:54.000Z
SpelJongEmu/src/AluFunctions.cpp
fallahn/speljongen
57cb5e09eec7db8c21ee7b3e7943fa0a76738c51
[ "Unlicense" ]
null
null
null
#include "AluFunctions.hpp" #include "CpuRegisters.hpp" #include <cassert> std::uint8_t AluFunction::inc(Flags& flags, std::uint8_t arg) { std::uint8_t result = arg + 1; flags.set(Flags::Z, result == 0); flags.set(Flags::N, false); flags.set(Flags::H, ((arg & 0x0f) == 0x0f)); return result; } std::uint16_t AluFunction::inc16(Flags&, std::uint16_t arg) { return arg + 1; } std::uint8_t AluFunction::dec(Flags& flags, std::uint8_t arg) { std::uint8_t result = arg - 1; flags.set(Flags::Z, result == 0); flags.set(Flags::N, true); flags.set(Flags::H, ((arg & 0x0f) == 0)); return result; } std::uint16_t AluFunction::dec16(Flags&, std::uint16_t arg) { return arg - 1; } std::uint16_t AluFunction::add(Flags& flags, std::uint16_t arg1, std::uint16_t arg2) { flags.set(Flags::N, false); flags.set(Flags::H, ((arg1 & 0x0fff) + (arg2 & 0x0fff) > 0x0fff)); flags.set(Flags::C, arg1 + arg2 > 0xffff); return arg1 + arg2; } std::uint16_t AluFunction::add(Flags&, std::uint16_t arg1, std::int8_t arg2) { return arg1 + arg2; } std::uint16_t AluFunction::add_sp(Flags& flags, std::uint16_t arg1, std::int8_t arg2) { flags.set(Flags::Z, false); flags.set(Flags::N, false); uint16_t result = arg1 + arg2; flags.set(Flags::C, (((arg1 & 0xff) + (arg2 & 0xff)) & 0x100) != 0); flags.set(Flags::H, (((arg1 & 0x0f) + (arg2 & 0x0f)) & 0x10) != 0); return result; } std::uint8_t AluFunction::daa(Flags& flags, std::uint8_t arg) { std::int32_t result = arg; if (flags.isSet(Flags::N)) { if (flags.isSet(Flags::H)) { result = (result - 6) & 0xff; } if (flags.isSet(Flags::C)) { result = (result - 0x60) & 0xff; } } else { if (flags.isSet(Flags::H) || (result & 0xf) > 9) { result += 0x06; } if (flags.isSet(Flags::C) || result > 0x9f) { result += 0x60; } } flags.set(Flags::H, false); if (result > 0xff) { flags.set(Flags::C, true); } result &= 0xff; flags.set(Flags::Z, result == 0); return static_cast<std::uint8_t>(result); } std::uint8_t AluFunction::cpl(Flags& flags, std::uint8_t arg) { flags.set(Flags::N, true); flags.set(Flags::H, true); return ~arg; } std::uint8_t AluFunction::scf(Flags& flags, std::uint8_t arg) { flags.set(Flags::N, false); flags.set(Flags::H, false); flags.set(Flags::C, true); return arg; } std::uint8_t AluFunction::ccf(Flags& flags, std::uint8_t arg) { flags.set(Flags::N, false); flags.set(Flags::H, false); flags.set(Flags::C, !flags.isSet(Flags::C)); return arg; } std::uint8_t AluFunction::add(Flags& flags, std::uint8_t arg1, std::uint8_t arg2) { std::int32_t sum = arg1 + arg2; flags.set(Flags::Z, (sum & 0xff) == 0); flags.set(Flags::N, false); flags.set(Flags::H, (arg1 & 0x0f) + (arg2 & 0x0f) > 0x0f); flags.set(Flags::C, sum > 0xff); return static_cast<std::uint8_t>(sum & 0xff); } std::uint8_t AluFunction::adc(Flags& flags, std::uint8_t arg1, std::uint8_t arg2) { std::uint8_t carry = flags.isSet(Flags::C) ? 1 : 0; std::int32_t sum = arg1 + arg2 + carry; flags.set(Flags::Z, (sum & 0xff) == 0); flags.set(Flags::N, false); flags.set(Flags::H, (arg1 & 0x0f) + (arg2 & 0x0f) + carry > 0x0f); flags.set(Flags::C, sum > 0xff); return static_cast<std::uint8_t>(sum & 0xff); } std::uint8_t AluFunction::sub(Flags& flags, std::uint8_t arg1, std::uint8_t arg2) { std::int32_t sum = arg1 - arg2; flags.set(Flags::Z, (sum & 0xff) == 0); flags.set(Flags::N, true); flags.set(Flags::H, (arg2 & 0x0f) > (arg1 & 0x0f)); flags.set(Flags::C, (arg2 > arg1)); return static_cast<std::uint8_t>(sum & 0xff); } std::uint8_t AluFunction::sbc(Flags& flags, std::uint8_t arg1, std::uint8_t arg2) { std::uint8_t carry = flags.isSet(Flags::C) ? 1 : 0; std::int32_t sum = arg1 - arg2 - carry; flags.set(Flags::Z, (sum & 0xff) == 0); flags.set(Flags::N, true); flags.set(Flags::H, ((arg1 ^ arg2 ^ (sum & 0xff)) & (1 << 4)) != 0); flags.set(Flags::C, sum < 0); return static_cast<std::uint8_t>(sum & 0xff); } std::uint8_t AluFunction::AND(Flags& flags, std::uint8_t arg1, std::uint8_t arg2) { std::uint8_t result = arg1 & arg2; flags.set(Flags::Z, result == 0); flags.set(Flags::N, false); flags.set(Flags::H, true); flags.set(Flags::C, false); return result; } std::uint8_t AluFunction::OR(Flags& flags, std::uint8_t arg1, std::uint8_t arg2) { std::uint8_t result = arg1 | arg2; flags.set(Flags::Z, result == 0); flags.set(Flags::N, false); flags.set(Flags::H, false); flags.set(Flags::C, false); return result; } std::uint8_t AluFunction::XOR(Flags& flags, std::uint8_t arg1, std::uint8_t arg2) { std::uint8_t result = arg1 ^ arg2; flags.set(Flags::Z, result == 0); flags.set(Flags::N, false); flags.set(Flags::H, false); flags.set(Flags::C, false); return result; } std::uint8_t AluFunction::cp(Flags& flags, std::uint8_t arg1, std::uint8_t arg2) { std::int32_t cp = (arg1 - arg2) & 0xff; flags.set(Flags::Z, cp == 0); flags.set(Flags::N, true); flags.set(Flags::H, (arg2 & 0x0f) > (arg1 & 0x0f)); flags.set(Flags::C, arg2 > arg1); return arg1; } std::uint8_t AluFunction::rlc(Flags& flags, std::uint8_t arg) { std::int32_t result = (arg << 1) & 0xff; if ((arg & (1 << 7)) != 0) { result |= 1; flags.set(Flags::C, true); } else { flags.set(Flags::C, false); } flags.set(Flags::Z, result == 0); flags.set(Flags::N, false); flags.set(Flags::H, false); return static_cast<std::uint8_t>(result); } std::uint8_t AluFunction::rrc(Flags& flags, std::uint8_t arg) { std::int32_t result = arg >> 1; if ((arg & 1) == 1) { result |= (1 << 7); flags.set(Flags::C, true); } else { flags.set(Flags::C, false); } flags.set(Flags::Z, result == 0); flags.set(Flags::N, false); flags.set(Flags::H, false); return static_cast<std::uint8_t>(result); } std::uint8_t AluFunction::rl(Flags& flags, std::uint8_t arg) { std::int32_t result = (arg << 1) & 0xff; result |= flags.isSet(Flags::C) ? 1 : 0; flags.set(Flags::C, (arg & (1 << 7)) != 0); flags.set(Flags::Z, result == 0); flags.set(Flags::N, false); flags.set(Flags::H, false); return static_cast<std::uint8_t>(result); } std::uint8_t AluFunction::rr(Flags& flags, std::uint8_t arg) { std::int32_t result = arg >> 1; result |= flags.isSet(Flags::C) ? (1 << 7) : 0; flags.set(Flags::C, (arg & 1) != 0); flags.set(Flags::Z, result == 0); flags.set(Flags::N, false); flags.set(Flags::H, false); return static_cast<std::uint8_t>(result); } std::uint8_t AluFunction::sla(Flags& flags, std::uint8_t arg) { std::uint8_t result = arg << 1; flags.set(Flags::C, (arg & (1 << 7)) != 0); flags.set(Flags::Z, result == 0); flags.set(Flags::N, false); flags.set(Flags::H, false); return result; } std::uint8_t AluFunction::sra(Flags& flags, std::uint8_t arg) { std::uint8_t result = (arg >> 1) | (arg & (1 << 7)); flags.set(Flags::C, (arg & 1) != 0); flags.set(Flags::Z, result == 0); flags.set(Flags::N, false); flags.set(Flags::H, false); return result; } std::uint8_t AluFunction::swap(Flags& flags, std::uint8_t arg) { std::uint8_t upper = arg & 0xf0; std::uint8_t lower = arg & 0x0f; std::uint8_t result = (upper >> 4) | (lower << 4); flags.set(Flags::Z, result == 0); flags.set(Flags::N, false); flags.set(Flags::H, false); flags.set(Flags::C, false); return result; } std::uint8_t AluFunction::srl(Flags& flags, std::uint8_t arg) { std::uint8_t result = arg >> 1; flags.set(Flags::C, (arg & 1) != 0); flags.set(Flags::Z, result == 0); flags.set(Flags::N, false); flags.set(Flags::H, false); return result; } std::uint8_t AluFunction::bit(Flags& flags, std::uint8_t arg1, std::uint8_t arg2) { flags.set(Flags::N, false); flags.set(Flags::H, true); if (arg2 < 8) { flags.set(Flags::Z, !BitUtil::getBit(arg1, arg2)); } return arg1; } std::uint8_t AluFunction::res(std::uint8_t arg1, std::uint8_t arg2) { return arg1 & ~(1 << arg2); } std::uint8_t AluFunction::set(std::uint8_t arg1, std::uint8_t arg2) { return arg1 |= (1 << arg2); }
26.663551
85
0.586984
fallahn
05d27ef62eb5a58839ad4a04691af8355f3911b0
3,783
cpp
C++
source/math/regression.cpp
ramenhut/final-stage-path-tracer-2-0
77c3a706f6521d88245b95b6310344b202be0e37
[ "BSD-2-Clause" ]
5
2019-07-26T06:24:16.000Z
2019-11-10T09:41:20.000Z
source/jmath/regression.cpp
ramenhut/global-illumination-lightmaps
e2099e1dca2ba181b18c248958b6f3cec96f14f2
[ "BSD-2-Clause" ]
null
null
null
source/jmath/regression.cpp
ramenhut/global-illumination-lightmaps
e2099e1dca2ba181b18c248958b6f3cec96f14f2
[ "BSD-2-Clause" ]
2
2019-09-18T13:01:45.000Z
2021-10-17T00:04:04.000Z
#include "statistics.h" namespace base { void compute_linear_squares(vector2* point_list, uint32 count, vector2* out_start, vector2* out_end) { if (BASE_PARAM_CHECK) { if (!point_list || !out_start || !out_end) { return; } } float32 m = 0; float32 b = 0; float32 xiyi = 0; float32 xi2 = 0; float32 yi = 0; float32 xi = 0; for (uint32 j = 0; j < count; j++) { xiyi += point_list[j].x * point_list[j].y; xi2 += point_list[j].x * point_list[j].x; yi += point_list[j].y; xi += point_list[j].x; } // Solve our linear system of equations matrix2 A; vector2 B; vector2 C; A.set(xi2, xi, xi, 1); B.set(xiyi, yi); if (!A.is_invertible()) { return; } C = A.inverse() * B; m = C.x; b = C.y; // Direct method (provided for example purposes only) // // b = ( xiyi / xi2 - yi / xi ) / ( i / xi - xi / xi2 ); // m = ( 2 * xiyi + 2 * b * xi ) / ( 2 * xi2 ); // // Now we must determine an origin and vector for the line. We // search for the coordinate with the minimum x, and then plug this // into our line equation to determine the closest origin. // // We will also search for the coordinate with the maximum x, and // plug this into our equation to derive the line segment end point. float32 min_x_value = 9999999.0f; float32 max_x_value = 0; for (uint32 j = 0; j < count; j++) { if (point_list[j].x <= min_x_value) min_x_value = point_list[j].x; if (point_list[j].x >= max_x_value) max_x_value = point_list[j].x; } out_start->x = min_x_value; out_start->y = m * min_x_value + b; out_end->x = max_x_value; out_end->y = m * max_x_value + b; } void compute_linear_squares(vector3* point_list, uint32 count, vector3* out_start, vector3* out_end) { if (BASE_PARAM_CHECK) { if (!point_list || !out_start || !out_end) { return; } } std::vector<vector2> a_list; std::vector<vector2> b_list; a_list.resize(count); b_list.resize(count); for (uint32 i = 0; i < count; i++) { a_list[i].x = point_list[i].x; a_list[i].y = point_list[i].y; b_list[i].x = point_list[i].y; b_list[i].y = point_list[i].z; } vector2 a_list_origin, a_list_vector; vector2 b_list_origin, b_list_vector; compute_linear_squares(&a_list[0], count, &a_list_origin, &a_list_vector); compute_linear_squares(&b_list[0], count, &b_list_origin, &b_list_vector); out_start->x = a_list_origin.x; out_start->y = a_list_origin.y; out_start->z = b_list_origin.y; out_end->x = a_list_vector.x; out_end->y = a_list_vector.y; out_end->z = b_list_vector.y; } void compute_linear_squares(vector4* point_list, uint32 count, vector4* out_start, vector4* out_end) { if (BASE_PARAM_CHECK) { if (!point_list || !out_start || !out_end) { return; } } std::vector<vector3> a_list; std::vector<vector3> b_list; a_list.resize(count); b_list.resize(count); for (uint32 i = 0; i < count; i++) { a_list[i].x = point_list[i].x; a_list[i].y = point_list[i].y; a_list[i].z = point_list[i].z; b_list[i].x = point_list[i].y; b_list[i].y = point_list[i].z; b_list[i].z = point_list[i].w; } vector3 a_list_origin, a_list_vector; vector3 b_list_origin, b_list_vector; compute_linear_squares(&a_list[0], count, &a_list_origin, &a_list_vector); compute_linear_squares(&b_list[0], count, &b_list_origin, &b_list_vector); out_start->x = a_list_origin.x; out_start->y = a_list_origin.y; out_start->z = a_list_origin.z; out_start->w = b_list_origin.z; out_end->x = a_list_vector.x; out_end->y = a_list_vector.y; out_end->z = a_list_vector.z; out_end->w = b_list_vector.z; } } // namespace base
25.560811
76
0.629923
ramenhut
05d91c22665eeb990044f7d7d45da481140a2924
3,577
hh
C++
dune/gdt/spaces/mapper/finite-volume.hh
pymor/dune-gdt
fabc279a79e7362181701866ce26133ec40a05e0
[ "BSD-2-Clause" ]
4
2018-10-12T21:46:08.000Z
2020-08-01T18:54:02.000Z
dune/gdt/spaces/mapper/finite-volume.hh
dune-community/dune-gdt
fabc279a79e7362181701866ce26133ec40a05e0
[ "BSD-2-Clause" ]
154
2016-02-16T13:50:54.000Z
2021-12-13T11:04:29.000Z
dune/gdt/spaces/mapper/finite-volume.hh
dune-community/dune-gdt
fabc279a79e7362181701866ce26133ec40a05e0
[ "BSD-2-Clause" ]
5
2016-03-02T10:11:20.000Z
2020-02-08T03:56:24.000Z
// This file is part of the dune-gdt project: // https://github.com/dune-community/dune-gdt // Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2018) // René Fritze (2018) #ifndef DUNE_GDT_SPACES_MAPPER_FINITE_VOLUME_HH #define DUNE_GDT_SPACES_MAPPER_FINITE_VOLUME_HH #include <dune/geometry/type.hh> #include <dune/grid/common/mcmgmapper.hh> #include <dune/grid/common/rangegenerators.hh> #include <dune/xt/common/numeric_cast.hh> #include <dune/xt/grid/type_traits.hh> #include <dune/gdt/exceptions.hh> #include <dune/gdt/local/finite-elements/interfaces.hh> #include <dune/gdt/local/finite-elements/lagrange.hh> #include "interfaces.hh" namespace Dune { namespace GDT { template <class GV, size_t r = 1, size_t rC = 1> class FiniteVolumeMapper : public MapperInterface<GV> { static_assert(rC == 1, "The FiniteVolumeMapper is not yet available for rC > 1!"); using ThisType = FiniteVolumeMapper; using BaseType = MapperInterface<GV>; public: using BaseType::d; using typename BaseType::D; private: using Implementation = MultipleCodimMultipleGeomTypeMapper<GV>; using LocalFiniteElementFamily = LocalLagrangeFiniteElementFamily<D, d, double, r>; public: using typename BaseType::ElementType; using typename BaseType::GridViewType; FiniteVolumeMapper(const GridViewType& grd_vw) : grid_view_(grd_vw) , local_finite_elements_() , mapper_(grid_view_, mcmgElementLayout()) { this->update_after_adapt(); } FiniteVolumeMapper(const ThisType&) = default; FiniteVolumeMapper(ThisType&&) = default; FiniteVolumeMapper& operator=(const ThisType&) = delete; FiniteVolumeMapper& operator=(ThisType&&) = delete; const GridViewType& grid_view() const override final { return grid_view_; } const LocalFiniteElementCoefficientsInterface<D, d>& local_coefficients(const GeometryType& geometry_type) const override final { return local_finite_elements_.get(geometry_type, 0).coefficients(); } size_t size() const override final { return mapper_.size() * r * rC; } size_t max_local_size() const override final { return r * rC; } size_t local_size(const ElementType& /*element*/) const override final { return r * rC; } size_t global_index(const ElementType& element, const size_t local_index) const override final { if (local_index >= r * rC) DUNE_THROW(Exceptions::mapper_error, "local_size(element) = " << r * rC << "\n local_index = " << local_index); return mapper_.index(element) * r * rC + local_index; } using BaseType::global_indices; void global_indices(const ElementType& element, DynamicVector<size_t>& indices) const override final { constexpr size_t local_sz = r * rC; if (indices.size() < local_sz) indices.resize(local_sz); size_t* indices_ptr = &indices[0]; std::iota(indices_ptr, indices_ptr + local_sz, mapper_.index(element) * local_sz); } // ... global_indices(...) void update_after_adapt() override final { mapper_.update(); } private: const GridViewType& grid_view_; LocalFiniteElementFamily local_finite_elements_; Implementation mapper_; }; // class FiniteVolumeMapper } // namespace GDT } // namespace Dune #endif // DUNE_GDT_SPACES_MAPPER_FINITE_VOLUME_HH
28.388889
119
0.728823
pymor
05dcffcae4da3aa57b64116b37688eba011f35ec
484
cpp
C++
C/202009011649.cpp
zawa-ch/code-fragments
4cc4fab495e633f48cadfdaa753f2fb604093caf
[ "Unlicense" ]
null
null
null
C/202009011649.cpp
zawa-ch/code-fragments
4cc4fab495e633f48cadfdaa753f2fb604093caf
[ "Unlicense" ]
null
null
null
C/202009011649.cpp
zawa-ch/code-fragments
4cc4fab495e633f48cadfdaa753f2fb604093caf
[ "Unlicense" ]
null
null
null
#include <iostream> #include <limits> int main(int argc, char const *argv[]) { // 明らかにオーバーフローを起こす値キャストの確認 // 3E113をint型(max:2147483647)に変換 const double value1 = 3.0e+113; int castvalue1 = int(value1); std::cout << value1 << " --int cast-> " << castvalue1 << std::endl; // Quiet NaN (無効な値)をint型に変換 const double value2 = std::numeric_limits<double>::quiet_NaN(); int castvalue2 = int(value2); std::cout << value2 << " --int cast-> " << castvalue2 << std::endl; return 0; }
25.473684
68
0.663223
zawa-ch
05e40631f92f1ae84df484863908744364615275
1,545
cpp
C++
test/route_test.cpp
LeonineKing1199/foxy-old
bc2d127dc3be48aea7007e4a7262d0a2bf0931d0
[ "BSL-1.0" ]
1
2020-09-30T08:58:35.000Z
2020-09-30T08:58:35.000Z
test/route_test.cpp
LeonineKing1199/foxy-old
bc2d127dc3be48aea7007e4a7262d0a2bf0931d0
[ "BSL-1.0" ]
null
null
null
test/route_test.cpp
LeonineKing1199/foxy-old
bc2d127dc3be48aea7007e4a7262d0a2bf0931d0
[ "BSL-1.0" ]
null
null
null
#include "foxy/route.hpp" #include "foxy/match_route.hpp" #include <boost/asio/executor.hpp> #include <boost/spirit/include/qi_int.hpp> #include <boost/spirit/include/qi_lit.hpp> #include <boost/spirit/include/qi_rule.hpp> #include <boost/spirit/include/qi_sequence.hpp> #include <catch.hpp> namespace qi = boost::spirit::qi; namespace asio = boost::asio; TEST_CASE("Our router") { SECTION("should invoke a handler upon a succesful route match") { using iterator_type = boost::string_view::iterator; auto was_called = false; auto const int_rule = qi::rule<iterator_type, int()>("/" >> qi::int_); auto const int_rule_handler = [&was_called](int const x) -> void { was_called = true; REQUIRE(x == 1337); }; auto const routes = foxy::make_routes( foxy::make_route(int_rule, int_rule_handler)); auto const* target = "/1337"; auto executor = asio::executor(); REQUIRE(foxy::match_route(target, routes, executor)); REQUIRE(was_called); } SECTION("should _not_ invoke a handler upon a failed route match") { using iterator_type = boost::string_view::iterator; auto was_called = false; auto const routes = foxy::make_routes( foxy::make_route( qi::rule<iterator_type>("/" >> qi::int_), [&was_called](void) -> void { was_called = true; })); auto const* target = "/rawr"; auto executor = asio::executor(); REQUIRE(!foxy::match_route(target, routes, executor)); REQUIRE(!was_called); } }
24.140625
74
0.653722
LeonineKing1199
05e4ea8c83712ab12abe3ea97ed01f4dc38a7163
1,204
cpp
C++
source/xyo-pixel32-process-wrapbox.cpp
g-stefan/xyo-pixel32
2f0e7500473f38ccffdff19e864f262b9f36056d
[ "MIT", "Unlicense" ]
null
null
null
source/xyo-pixel32-process-wrapbox.cpp
g-stefan/xyo-pixel32
2f0e7500473f38ccffdff19e864f262b9f36056d
[ "MIT", "Unlicense" ]
null
null
null
source/xyo-pixel32-process-wrapbox.cpp
g-stefan/xyo-pixel32
2f0e7500473f38ccffdff19e864f262b9f36056d
[ "MIT", "Unlicense" ]
null
null
null
// // XYO Pixel32 // // Copyright (c) 2020-2021 Grigore Stefan <g_stefan@yahoo.com> // Created by Grigore Stefan <g_stefan@yahoo.com> // // MIT License (MIT) <http://opensource.org/licenses/MIT> // #include "xyo-pixel32-process.hpp" namespace XYO { namespace Pixel32 { namespace Process { using namespace XYO; TPointer<Image> wrapBox(Image *imgThis, long int dx, long int dy) { uint32_t lx = imgThis->width; uint32_t ly = imgThis->height; TPointer<Image> retV; retV = create(lx + 2 * dx, ly + 2 * dy); if(retV) { // center copy(retV, imgThis, dx, dy, 0, 0, lx, ly); // top copy(retV, imgThis, 0, 0, lx - dx, ly - dy, dx, dy); copy(retV, imgThis, dx, 0, 0, ly - dy, lx, dy); copy(retV, imgThis, lx + dx, 0, 0, ly - dy, dx, dy); // bottom copy(retV, imgThis, 0, ly + dy, lx - dx, 0, dx, dy); copy(retV, imgThis, dx, ly + dy, 0, 0, lx, dy); copy(retV, imgThis, lx + dx, ly + dy, 0, 0, dx, dy); //right copy(retV, imgThis, lx + dx, dy, 0, 0, dx, ly); //left copy(retV, imgThis, 0, dy, lx - dx, 0, dx, ly); }; return retV; }; }; }; };
24.08
73
0.535714
g-stefan
05e8b91c6da8173c0d75ef85ebf78627958ff339
388
cpp
C++
Codeforces/ProblemSet/144A.cpp
Binary-bug/CP
f9f356d36bd252c71ee3ed2d0585cc372f2baf5e
[ "MIT" ]
null
null
null
Codeforces/ProblemSet/144A.cpp
Binary-bug/CP
f9f356d36bd252c71ee3ed2d0585cc372f2baf5e
[ "MIT" ]
null
null
null
Codeforces/ProblemSet/144A.cpp
Binary-bug/CP
f9f356d36bd252c71ee3ed2d0585cc372f2baf5e
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int main(){ int n,x,max_i,min_i,max,min; scanf("%d",&n); scanf("%d",&x); max = min = x; max_i = min_i = 0; for(int i=1; i < n; ++i){ scanf("%d",&x); if(x > max) max = x, max_i = i; if(x <= min) min = x, min_i = i; } (max_i > min_i)?(cout << (n + max_i - min_i - 2)):(cout << (max_i + n - min_i - 1)); cout << endl; return 0; }
18.47619
85
0.512887
Binary-bug
05e9370c686fafe079834bdcc34f3a492a7fb13a
4,079
cpp
C++
common/utils.cpp
olafurw/server2
28cfc7c07ef5e87951af8f5326b54e3434391765
[ "MIT" ]
null
null
null
common/utils.cpp
olafurw/server2
28cfc7c07ef5e87951af8f5326b54e3434391765
[ "MIT" ]
null
null
null
common/utils.cpp
olafurw/server2
28cfc7c07ef5e87951af8f5326b54e3434391765
[ "MIT" ]
null
null
null
#include "utils.hpp" #include "sha256.hpp" #include <dlfcn.h> #include <execinfo.h> #include <cxxabi.h> namespace utils { std::string sha256(const std::string& data) { static char const hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; unsigned char result[32]; sha256_state md; sha_init(md); sha_process(md, data.c_str(), data.size()); sha_done(md, result); std::string sha_string; for(int i = 0; i < 32; ++i) { sha_string.append(&hex[(result[i] & 0xF0) >> 4], 1); sha_string.append(&hex[result[i] & 0xF], 1); } return sha_string; } // This function produces a stack backtrace with demangled function & method names. std::string stacktrace(int skip) { void *callstack[128]; const int nMaxFrames = sizeof(callstack) / sizeof(callstack[0]); char buf[1024]; int nFrames = backtrace(callstack, nMaxFrames); char **symbols = backtrace_symbols(callstack, nFrames); std::ostringstream trace_buf; for (int i = skip; i < nFrames; i++) { Dl_info info; if(dladdr(callstack[i], &info) && info.dli_sname) { char *demangled = NULL; int status = -1; if (info.dli_sname[0] == '_') { demangled = abi::__cxa_demangle(info.dli_sname, NULL, 0, &status); } snprintf(buf, sizeof(buf), "%-3d %*p %s + %zd\n", i, int(2 + sizeof(void*) * 2), callstack[i], status == 0 ? demangled : info.dli_sname == 0 ? symbols[i] : info.dli_sname, (char *)callstack[i] - (char *)info.dli_saddr); free(demangled); } else { snprintf(buf, sizeof(buf), "%-3d %*p %s\n", i, int(2 + sizeof(void*) * 2), callstack[i], symbols[i]); } trace_buf << buf; } free(symbols); if (nFrames == nMaxFrames) { trace_buf << "[truncated]\n"; } return trace_buf.str(); } std::string& ltrim(std::string& s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); return s; } std::string& rtrim(std::string& s) { s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } std::string& trim(std::string& s) { return ltrim(rtrim(s)); } std::string ltrim(const std::string& s) { std::string tmp_str = s; tmp_str.erase(tmp_str.begin(), std::find_if(tmp_str.begin(), tmp_str.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); return tmp_str; } std::string rtrim(const std::string& s) { std::string tmp_str = s; tmp_str.erase(std::find_if(tmp_str.rbegin(), tmp_str.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), tmp_str.end()); return tmp_str; } std::string trim(const std::string& s) { std::string tmp_str = s; return ltrim(rtrim(tmp_str)); } std::vector<std::string> split_string(const std::string& str, const char token, const bool skip_empty) { std::vector<std::string> segments; std::stringstream ss(str); std::string segment; while(std::getline(ss, segment, token)) { if(skip_empty && trim(segment) == "") { continue; } segments.emplace_back(std::move(segment)); } return segments; } std::string file_to_string(const std::string& filename) { std::ifstream in(filename, std::ios::in | std::ios::binary); std::string content; in.seekg(0, std::ios::end); content.resize(in.tellg()); in.seekg(0, std::ios::beg); in.read(&content[0], content.size()); in.close(); return content; } std::vector<std::string> file_to_array(const std::string& filename, char token) { return split_string(file_to_string(filename), token); } void write_to_file(const std::string& filename, const std::string& content) { std::ofstream out(filename, std::ios::out | std::ios::app); out << content; out.close(); } }
25.179012
183
0.579063
olafurw
05e94c4ac2a7c68f01d18d3c017ce05a3aa2a02e
28,002
cpp
C++
src/XPTools/DDSTool.cpp
den-rain/xptools
4c39da8d44a4a92e9efb2538844d433496b38f07
[ "X11", "MIT" ]
null
null
null
src/XPTools/DDSTool.cpp
den-rain/xptools
4c39da8d44a4a92e9efb2538844d433496b38f07
[ "X11", "MIT" ]
null
null
null
src/XPTools/DDSTool.cpp
den-rain/xptools
4c39da8d44a4a92e9efb2538844d433496b38f07
[ "X11", "MIT" ]
null
null
null
/* * Copyright (c) 2007, Laminar Research. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #include "version.h" #include "BitmapUtils.h" #include "QuiltUtils.h" #include "FileUtils.h" #include "MathUtils.h" #if PHONE #define WANT_PVR 1 #define WANT_ATI IBM #else #define WANT_PVR 0 #define WANT_ATI 0 #endif #if PHONE #if WANT_ATI #include "ATI_Compress.h" #endif #include "MathUtils.h" #endif /* WHAT IS ALL OF THIS PHONE STUFF??? DDSTool is mainly used by the X-Plane community to convert PNGs to DDS/DXT files so that the texture compression they get is high quality/produced offline. But...LR also uses DDSTool and XGrinder to prepare content for the iphone apps. The iphone uses "pvr" files, an image container for use with PowerVR's PVRTC compressed format. In other words, the iphone has its own file formats and its own compression. When PHONE is defined to 1, the tools compile with iphone options enabled...that's what most of this junk is. Normally we ship the tools with phone features off because they are (1) completely useless to desktop users and (2) likely to create confusion. */ enum { raw_16 = 0, raw_24 = 1, pvr_2 = 2, pvr_4 = 3 }; static int exp_mode = pvr_2; typedef struct PVR_Header_Texture_TAG { unsigned int dwHeaderSize; /*!< size of the structure */ unsigned int dwHeight; /*!< height of surface to be created */ unsigned int dwWidth; /*!< width of input surface */ unsigned int dwMipMapCount; /*!< number of mip-map levels requested */ unsigned int dwpfFlags; /*!< pixel format flags */ unsigned int dwTextureDataSize; /*!< Total size in bytes */ unsigned int dwBitCount; /*!< number of bits per pixel */ unsigned int dwRBitMask; /*!< mask for red bit */ unsigned int dwGBitMask; /*!< mask for green bits */ unsigned int dwBBitMask; /*!< mask for blue bits */ unsigned int dwAlphaBitMask; /*!< mask for alpha channel */ unsigned int dwPVR; /*!< magic number identifying pvr file */ unsigned int dwNumSurfs; /*!< the number of surfaces present in the pvr */ } PVR_Texture_Header; #if PHONE typedef struct ATC_Header_Texture_TAG { unsigned int signature; unsigned int width; unsigned int height; unsigned int flags; unsigned int dataOffset; // From start of header/file unsigned int reserved1; unsigned int reserved2; unsigned int reserved3; } ATC_Texture_Header; #endif enum { OGL_RGBA_4444= 0x10, OGL_RGBA_5551, OGL_RGBA_8888, OGL_RGB_565, OGL_RGB_555, OGL_RGB_888, OGL_I_8, OGL_AI_88, OGL_PVRTC2, OGL_PVRTC4, OGL_PVRTC2_2, OGL_PVRTC2_4, }; #if PHONE enum { ATC_RGB = 0x01, ATC_RGBA = 0x02, ATC_TILED = 0x04, ATC_INTERP_RGBA = 0x12, ATC_RAW_RGBA_4444 = 0x20, // From here down, these are formats that WE made up ATC_RAW_RGBA_8888, // They are NOT part of the ATITC spec. ATC_RAW_RGB_565, ATC_RAW_RGB_888, ATC_RAW_I_8 }; #endif static int size_for_image(int x, int y, int bpp, int min_bytes) { return max(x * y * bpp / 8, min_bytes); } static int size_for_mipmap(int x, int y, int bpp, int min_bytes) { int total = 0; while (1) { total += size_for_image(x,y,bpp, min_bytes); if (x == 1 && y == 1) break; if (x > 1) x >>= 1; if (y > 1) y >>= 1; } return total; } #if PHONE static int WriteToRaw(const ImageInfo& info, const char * outf, int s_raw_16_bit, bool isPvr, int mip_count) { PVR_Texture_Header h = { 0 }; ATC_Texture_Header atcHdr = { 0 }; unsigned int totalSize = 0; unsigned int hdrSize = 0; void* hdr = NULL; int bpp = 8; ImageInfo img(info); /// copy so we can advance the mip stack. switch(info.channels) { case 1: bpp = 8; break; case 3: bpp = s_raw_16_bit ? 16 : 24; break; case 4: bpp = s_raw_16_bit ? 16 : 32; break; } totalSize = (mip_count > 1) ? size_for_mipmap(info.width, info.height, bpp, 1) : size_for_image(info.width,info.height,bpp,1); if(isPvr) { h.dwHeaderSize = sizeof(h); h.dwHeight = info.height; h.dwWidth = info.width; h.dwMipMapCount = mip_count; h.dwTextureDataSize = totalSize; h.dwPVR = 0x21525650; if(s_raw_16_bit) switch(info.channels) { case 1: h.dwpfFlags = OGL_I_8; break; case 3: h.dwpfFlags = OGL_RGB_565; break; case 4: h.dwpfFlags = OGL_RGBA_4444; break; } else switch(info.channels) { case 1: h.dwpfFlags = OGL_I_8; break; case 3: h.dwpfFlags = OGL_RGB_888; break; case 4: h.dwpfFlags = OGL_RGBA_8888; break; } hdrSize = h.dwHeaderSize; hdr = &h; } // We must be ATC then if we're not PVR else { atcHdr.signature = 0xCCC40002; atcHdr.width = info.width; atcHdr.height = info.height; atcHdr.dataOffset = sizeof(atcHdr); if(s_raw_16_bit) switch(info.channels) { case 1: atcHdr.flags = ATC_RAW_I_8; break; case 3: atcHdr.flags = ATC_RAW_RGB_565; break; case 4: atcHdr.flags = ATC_RAW_RGBA_4444; break; } else switch(info.channels) { case 1: atcHdr.flags = ATC_RAW_I_8; break; case 3: atcHdr.flags = ATC_RAW_RGB_888; break; case 4: atcHdr.flags = ATC_RAW_RGBA_8888; break; } hdrSize = sizeof(atcHdr); hdr = &atcHdr; } int sbp = info.channels; int dbp = bpp / 8; unsigned char * storage = (unsigned char *) malloc(totalSize); unsigned char * base_ptr = storage; while(mip_count--) { for(int y = 0; y < img.height; ++y) for(int x = 0; x < img.width; ++x) { unsigned char * srcb = (unsigned char*)img.data + img.width * sbp * y + x * sbp; unsigned char * dstb = base_ptr + img.width * dbp * y + dbp * x; if(img.channels == 1) { *dstb = *srcb; } else if (img.channels == 3) { if(s_raw_16_bit) *((unsigned short *) dstb) = ((srcb[2] & 0xF8) << 8) | ((srcb[1] & 0xFC) << 3) | ((srcb[0] & 0xF8) >> 3); else dstb[0]=srcb[2], dstb[1]=srcb[1], dstb[2]=srcb[0]; } else if (img.channels == 4) { if(s_raw_16_bit) *((unsigned short *) dstb) = ((srcb[2] & 0xF0) << 8) | ((srcb[1] & 0xF0) << 4) | ((srcb[0] & 0xF0) << 0) | ((srcb[3] & 0xF0) >> 4); else dstb[0]=srcb[2], dstb[1]=srcb[1], dstb[2]=srcb[0], dstb[3]=srcb[3]; } } base_ptr += size_for_image(img.width,img.height,bpp,1); AdvanceMipmapStack(&img); } FILE * fi = fopen(outf,"wb"); if(fi) { fwrite(hdr,1,hdrSize,fi); fwrite(storage,1,totalSize,fi); fclose(fi); } free(storage); return 0; } #endif int pow2_up(int n) { int o = 1; while(o < n) o *= 2; return o; } int pow2_down(int n) { int o = 65536; while(o > n) o /= 2; return o; } // Resizes the image to meet our constraints. // up - resize bigger to hit power of 2 // down - resize smaller to hit power of 2 // if neither: do nothing // square: require image to be square // returns true if the image ALREADY meets these criteria, false if it must // be resized. if up & down are both false, a "false" return leaves the image in its // original (unusable) form. static bool HandleScale(ImageInfo& info, bool up, bool down, bool half, bool square) { int nx = down ? pow2_down(info.width) : pow2_up(info.width); int ny = down ? pow2_down(info.height) : pow2_up(info.height); if(half) nx /= 2.0; if(half) ny /= 2.0; if(square && up ) nx = ny = max(nx,ny); if(square && down) nx = ny = min(nx, ny); if(nx == info.width && ny == info.height) return true; if(!up && !down && !half) return false; ImageInfo n; CreateNewBitmap(nx,ny,info.channels, &n); CopyBitmapSection(&info, &n, 0, 0, info.width, info.height, 0, 0, nx, ny); swap(n, info); DestroyBitmap(&n); return false; } inline float to_srgb(float p) { if(p <= 0.0031308f) return 12.92f * p; return 1.055f * pow(p,0.41666f) - 0.055f; } inline float from_srgb(float p) { if(p <= 0.04045f) return p / 12.92f; else return powf(p * (1.0/1.055f) + (0.055f/1.055f),2.4f); } unsigned char srgb_filter(unsigned char src[], int count, int channel, int level) { if(channel == 3) // alpha is not corrected { int total = 0; for(int i = 0; i < count; ++i) total += (int) src[i]; return min(255,total / count); } float total = 0.f; for(int i = 0; i < count; ++i) { float p = src[i]; p /= 255.0f; p = from_srgb(p); total += p; } total /= ((float) count); total = to_srgb(total); total *= 255.0f; if(total <= 0.0f) return 0; if (total >= 255.0f) return 255; return roundf(total); } unsigned char night_filter(unsigned char src[], int count, int channel, int level) { int total = 0; for(int i = 0; i < count; ++i) total += (int) src[i]; total *= 2; return min(255,total / count); } unsigned char fade_filter(unsigned char src[], int count, int channel, int level) { int total = 0; for(int i = 0; i < count; ++i) total += (int) src[i]; total /= count; if (channel == 3) { float alpha = interp(3,1.0,6,0.0,level); total = (float) total * alpha; } return total; } unsigned char fade_2_black_filter(unsigned char src[], int count, int channel, int level) { int total = 0; for(int i = 0; i < count; ++i) total += (int) src[i]; total /= count; { float alpha = interp(3,1.0,6,0.0,level); total = (float) total * alpha; } return total; } int main(int argc, char * argv[]) { char my_dir[2048]; strcpy(my_dir,argv[0]); char * last_slash = my_dir; char * p = my_dir; while(*p) { if(*p=='/') last_slash = p; ++p; } last_slash[1] = 0; // DDSTool --png2dds <infile> <outfile> if (argc == 2 && strcmp(argv[1],"--version")==0) { print_product_version("DDSTool", DDSTOOL_VER, DDSTOOL_EXTRAVER); return 0; } if (argc == 2 && strcmp(argv[1],"--auto_config")==0) { printf("CMD .png .dds \"%s\" DDS_MODE HAS_MIPS GAMMA_MODE PVR_SCALE \"INFILE\" \"OUTFILE\"\n",argv[0]); printf("OPTIONS DDSTool\n"); printf("RADIO DDS_MODE 1 --png2dxt Auto-pick compression\n"); printf("RADIO DDS_MODE 0 --png2dxt1 Use DXT1 Compression (1-bit alpha)\n"); printf("RADIO DDS_MODE 0 --png2dxt3 Use DXT3 Compression (high-freq alpha)\n"); printf("RADIO DDS_MODE 0 --png2dxt5 Use DXT5 Compression (smooth alpha)\n"); printf("RADIO DDS_MODE 0 --png2rgb No Compression\n"); printf("DIV\n"); printf("RADIO HAS_MIPS 1 --std_mips Generate Mip-Maps\n"); printf("RADIO HAS_MIPS 0 --pre_mips Image Is a Mip-Map Tree\n"); printf("RADIO HAS_MIPS 0 --night_mips Generate Night-Style Mip-Map\n"); printf("RADIO HAS_MIPS 0 --fade_mips Generate Fading Mip-Map\n"); printf("RADIO HAS_MIPS 0 --ctl_mips Generate Fading CTL Mip-Map\n"); printf("DIV\n"); printf("RADIO GAMMA_MODE 1 --gamma_22 Use X-Plane 10 Gamma\n"); printf("RADIO GAMMA_MODE 0 --gamma_18 Use X-Plane 9 Gamma\n"); #if WANT_ATI printf("CMD .png .atc \"%s\" ATC_MODE MIPS PVR_SCALE \"INFILE\" \"OUTFILE\"\n",argv[0]); printf("DIV\n"); printf("RADIO ATC_MODE 1 --png2atc4 4-bit ATC compression\n"); printf("RADIO ATC_MODE 0 --png2atc_raw16 ATC uses 16-bit color\n"); printf("RADIO ATC_MODE 0 --png2atc_raw24 ATC uses 24-bit color\n"); #endif #if PHONE printf("CMD .png .txt \"%s\" --info ONEFILE \"INFILE\" \"OUTFILE\"\n", argv[0]); printf("DIV\n"); printf("RADIO PVR_MODE 1 --png2pvrtc2 2-bit PVR compression\n"); printf("RADIO PVR_MODE 0 --png2pvrtc4 4-bit PVR compression\n"); printf("RADIO PVR_MODE 0 --png2pvr_raw16 PVR uses 16-bit color\n"); printf("RADIO PVR_MODE 0 --png2pvr_raw24 PVR uses 24-bit color\n"); #endif printf("DIV\n"); printf("RADIO PVR_SCALE 1 --scale_none Do not resize images\n"); printf("RADIO PVR_SCALE 0 --scale_up Scale up to nearest power of 2\n"); printf("RADIO PVR_SCALE 0 --scale_down Scale down to nearest power of 2\n"); printf("RADIO PVR_SCALE 0 --scale_half Scale down by a factor of two\n"); #if PHONE printf("DIV\n"); printf("CHECK PREVIEW 0 --make_preview Output preview of compressed PVR image\n"); printf("CHECK MIPS 1 --make_mips Create mipmap for PVR image\n"); printf("CHECK ONEFILE 1 --one_file All text info goes into one file\n"); printf("CMD .png .pvr \"%s\" PVR_MODE PVR_SCALE PREVIEW MIPS \"INFILE\" \"OUTFILE\"\n",argv[0]); #endif return 0; } if (argc < 4) { printf("Usage: %s <convert mode> <options> <input_file> <output_file>|-\n",argv[0]); printf("Usage: %s --quilt <input_file> <width> <height> <patch size> <overlap> <trials> <output_files>n",argv[0]); printf(" %s --version\n",argv[0]); exit(1); } if(strcmp(argv[1],"--info")==0) { ImageInfo info; int n = 2; bool one_file = false; if(strcmp(argv[n],"--one_file")==0) { ++n; one_file = true; } if(CreateBitmapFromPNG(argv[n], &info, true, GAMMA_SRGB)) { printf("Unable to open png file %s\n", argv[n]); return 1; } string target = argv[n+1]; if(one_file) { string::size_type p = target.find_last_of("\\/:"); if(p != target.npos) target.erase(p+1); target += "info.txt"; } FILE * fi = fopen(target.c_str(), one_file ? "a" : "w"); if(fi) { const char * name = argv[n]; const char * p = name; while(*p) { if(*p == '\\' || *p == ':' || *p == '/') name = p+1; ++p; } fprintf(fi,"\"%s\", %ld, %ld, %hd\n", name, info.width, info.height, info.channels); fclose(fi); } } else if(strcmp(argv[1],"--png2pvrtc2")==0 || strcmp(argv[1],"--png2pvrtc4")==0) { char cmd_buf[2048]; const char * pvr_mode = "--bits-per-pixel-2"; if(strcmp(argv[1],"--png2pvrtc4")==0) pvr_mode = "--bits-per-pixel-4"; // PowerVR does not provide open src for PVRTC. So...we have to convert our png using Apple's texture tool. bool want_preview = false; bool want_mips = false; bool scale_up = strcmp(argv[2], "--scale_up") == 0; bool scale_down = strcmp(argv[2], "--scale_down") == 0; bool scale_half = strcmp(argv[2], "--scale_half") == 0; int n = 3; if(strcmp(argv[n],"--make_preview")==0) { want_preview = true; ++n; } if(strcmp(argv[n],"--make_mips")==0) { want_mips = true; ++n; } ImageInfo info; if(CreateBitmapFromPNG(argv[n], &info, true, 2.2f)) { printf("Unable to open png file %s\n", argv[n]); return 1; } if (!HandleScale(info, scale_up, scale_down, scale_half, true)) { // Image does NOT meet our power of 2 needs. if(!scale_up && !scale_down && !scale_half) { printf("The image is not a square power of 2. It is: %ld by %ld\n", info.width, info.height); return 1; } else if(want_preview) { string preview_path = string(argv[n]) + ".scl.png"; WriteBitmapToPNG(&info, preview_path.c_str(), NULL, 0, 2.2f); } } FlipImageY(info); string temp_path = argv[n]; temp_path += "_temp"; if(WriteBitmapToPNG(&info, temp_path.c_str(), NULL, 0, 2.2f)) { printf("Unable to write temp file %s\n", temp_path.c_str()); return 1; } DestroyBitmap(&info); string preview = string(argv[n+1]) + ".png"; string flags; if(want_mips) flags += "-m "; if(want_preview){ flags += "-p \""; flags += preview; flags += "\" "; } sprintf(cmd_buf,"\"%stexturetool\" -e PVRTC %s %s -c PVR -o \"%s\" \"%s\"", my_dir, pvr_mode, flags.c_str(), argv[n+1], temp_path.c_str()); printf("Cmd: %s\n", cmd_buf); system(cmd_buf); FILE_delete_file(temp_path.c_str(), 0); if(want_preview) { if(!CreateBitmapFromPNG(preview.c_str(), &info, true, 2.2f)) { FlipImageY(info); WriteBitmapToPNG(&info, preview.c_str(),0,false, 2.2f); DestroyBitmap(&info); } } return 1; } #if PHONE else if(strcmp(argv[1],"--png2pvr_raw16")==0 || strcmp(argv[1],"--png2pvr_raw24")==0) { bool want_preview = false; bool want_mips = false; bool scale_up = strcmp(argv[2], "--scale_up") == 0; bool scale_down = strcmp(argv[2], "--scale_down") == 0; bool scale_half = strcmp(argv[2], "--scale_half") == 0; int n = 3; if(strcmp(argv[n],"--make_preview")==0) { want_preview = true; ++n; } if(strcmp(argv[n],"--make_mips")==0) { want_mips = true; ++n; } ImageInfo info; if (CreateBitmapFromPNG(argv[n], &info, true,2.2f)!=0) { printf("Unable to open png file %s\n", argv[n]); return 1; } if (!HandleScale(info, scale_up, scale_down, scale_half, false)) { // Image does NOT meet our power of 2 needs. if(!scale_up && !scale_down && !scale_half) { printf("The imager is not a power of 2. It is: %d by %d\n", info.width, info.height); return 1; } else if(want_preview) { string preview_path = string(argv[n]) + ".scl.png"; WriteBitmapToPNG(&info, preview_path.c_str(), NULL, 0, 2.2f); } } char buf[1024]; const char * outf = argv[n+1]; if(strcmp(outf,"-")==0) { strcpy(buf,argv[n]); buf[strlen(buf)-4]=0; strcat(buf,".raw"); outf=buf; } int mc = 1; if(want_mips) mc = MakeMipmapStack(&info); if (WriteToRaw(info, outf, strcmp(argv[1],"--png2pvr_raw16")==0, true, mc)!=0) { printf("Unable to write raw PVR file %s\n", argv[n+1]); return 1; } return 0; } #endif else if(strcmp(argv[1],"--png2dxt")==0 || strcmp(argv[1],"--png2dxt1")==0 || strcmp(argv[1],"--png2dxt3")==0 || strcmp(argv[1],"--png2dxt5")==0) { int arg_base = 2; int has_mips = 0; if(strcmp(argv[arg_base], "--std_mips") == 0) { has_mips = 0; ++arg_base; } else if(strcmp(argv[arg_base], "--pre_mips") == 0) { has_mips = 1; ++arg_base; } else if(strcmp(argv[arg_base], "--night_mips") == 0) { has_mips = 2; ++arg_base; } else if(strcmp(argv[arg_base], "--fade_mips") == 0) { has_mips = 3; ++arg_base; } else if(strcmp(argv[arg_base], "--ctl_mips") == 0) { has_mips = 4; ++arg_base; } float gamma = (strcmp(argv[arg_base], "--gamma_22") == 0) ? 2.2f : 1.8f; arg_base +=1; bool scale_up = strcmp(argv[arg_base], "--scale_up") == 0; bool scale_down = strcmp(argv[arg_base], "--scale_down") == 0; bool scale_half = strcmp(argv[arg_base], "--scale_half") == 0; arg_base +=1; ImageInfo info; if (CreateBitmapFromPNG(argv[arg_base], &info, false, gamma)!=0) { printf("Unable to open png file %s\n", argv[arg_base]); return 1; } if (!HandleScale(info, scale_up, scale_down, scale_half, false)) { // Image does NOT meet our power of 2 needs. if(!scale_up && !scale_down && !scale_half) { printf("The imager is not a power of 2. It is: %ld by %ld\n", info.width, info.height); return 1; } } char buf[1024]; const char * outf = argv[arg_base+1]; if(strcmp(outf,"-")==0) { strcpy(buf,argv[arg_base]); buf[strlen(buf)-4]=0; strcat(buf,".dds"); outf=buf; } if(info.channels == 1) { printf("Unable to write DDS file from alpha-only PNG %s\n", argv[arg_base+1]); } int dxt_type = argv[1][9]-'0'; if(argv[1][9]==0) { if(info.channels == 3) dxt_type=1; else dxt_type=5; } ConvertBitmapToAlpha(&info,false); switch(has_mips) { // case 0: MakeMipmapStack(&info); break; case 0: MakeMipmapStackWithFilter(&info,srgb_filter); break; case 1: MakeMipmapStackFromImage(&info); break; case 2: MakeMipmapStackWithFilter(&info,night_filter); break; case 3: MakeMipmapStackWithFilter(&info,fade_filter); break; case 4: MakeMipmapStackWithFilter(&info,fade_2_black_filter); break; } if (WriteBitmapToDDS(info, dxt_type, outf, gamma == GAMMA_SRGB)!=0) { printf("Unable to write DDS file %s\n", argv[arg_base+1]); return 1; } return 0; } else if(strcmp(argv[1],"--png2rgb")==0) { int arg_base = 2; int has_mips = 0; if(strcmp(argv[2], "--std_mips") == 0) { has_mips = 0; ++arg_base; } else if(strcmp(argv[2], "--pre_mips") == 0) { has_mips = 1; ++arg_base; } else if(strcmp(argv[2], "--night_mips") == 0) { has_mips = 2; ++arg_base; } else if(strcmp(argv[2], "--fade_mips") == 0) { has_mips = 3; ++arg_base; } else if(strcmp(argv[2], "--ctl_mips") == 0) { has_mips = 4; ++arg_base; } float gamma = (strcmp(argv[arg_base], "--gamma_22") == 0) ? 2.2f : 1.8f; arg_base +=1; bool scale_up = strcmp(argv[arg_base], "--scale_up") == 0; bool scale_down = strcmp(argv[arg_base], "--scale_down") == 0; bool scale_half = strcmp(argv[arg_base], "--scale_half") == 0; arg_base +=1; ImageInfo info; if (CreateBitmapFromPNG(argv[arg_base], &info, true, gamma)!=0) { printf("Unable to open png file %s\n", argv[arg_base]); return 1; } if (!HandleScale(info, scale_up, scale_down, scale_half, false)) { // Image does NOT meet our power of 2 needs. if(!scale_up && !scale_down && !scale_half) { printf("The imager is not a power of 2. It is: %ld by %ld\n", info.width, info.height); return 1; } } char buf[1024]; const char * outf = argv[arg_base+1]; if(strcmp(outf,"-")==0) { strcpy(buf,argv[arg_base]); buf[strlen(buf)-4]=0; strcat(buf,".raw"); outf=buf; } switch(has_mips) { case 0: MakeMipmapStack(&info); break; case 1: MakeMipmapStackFromImage(&info); break; case 2: MakeMipmapStackWithFilter(&info,night_filter); break; case 3: MakeMipmapStackWithFilter(&info,fade_filter); break; case 4: MakeMipmapStackWithFilter(&info,fade_2_black_filter); break; } if (WriteUncompressedToDDS(info, outf, gamma == GAMMA_SRGB)!=0) { printf("Unable to write DDS file %s\n", argv[arg_base+1]); return 1; } return 0; // Quilt src w h splat over trials dest } else if (strcmp(argv[1],"--quilt")==0) { ImageInfo src, dst; if(CreateBitmapFromPNG(argv[2], &src, false, 2.2f) != 0) return 1; int dst_w = atoi(argv[3]); int dst_h = atoi(argv[4]); int splat = atoi(argv[5]); int overlap = atoi(argv[6]); int trials = atoi(argv[7]); printf("Will make %d x %d tex, with %d splats (%d overlap, %d trials.)\n", dst_w,dst_h, splat,overlap,trials); CreateNewBitmap(dst_w,dst_h, 4, &dst); if(src.channels == 3) ConvertBitmapToAlpha(&src,false); make_texture(src, dst, splat, overlap, trials); WriteBitmapToPNG(&dst, argv[8], NULL, 0, 2.2f); } #if PHONE && WANT_ATI else if(strcmp(argv[1],"--png2atc4")==0) { bool scale_up = strcmp(argv[2], "--scale_up") == 0; bool scale_down = strcmp(argv[2], "--scale_down") == 0; bool scale_half = strcmp(argv[2], "--scale_half") == 0; int n = 3; ImageInfo info; if(CreateBitmapFromPNG(argv[n], &info, true, 2.2f)) { printf("Unable to open png file %s\n", argv[n]); return 1; } if (!HandleScale(info, scale_up, scale_down, scale_half, false)) { // Image does NOT meet our power of 2 needs. if(!scale_up && !scale_down && !scale_half) { printf("The imager is not a power of 2. It is: %d by %d\n", info.width, info.height); return 1; } } // We need to save our channel count because MakeMipmapStack is going to // manually force everything to have an alpha channel. int channels = info.channels; // Ben says: WTF? Well, in the old days, MakeMipmapStack "upgraded" the image to RGBA. Chris's // code goes through some hoops to avoid that. The new MakeMipmapStack works in any color format. // So to keep Chris's code working, I do the upgrade by hand. // Chris, you could someday rip out the convert bitmap to alpha call here as well as the special // handling of RGB images. ConvertBitmapToAlpha(&info,false); MakeMipmapStack(&info); struct ImageInfo img(info); ATC_Texture_Header h; h.signature = 0xCCC40002; h.dataOffset = sizeof(h); h.height = info.height; h.width = info.width; h.flags = (channels == 3) ? ATC_RGB : ATC_RGBA; h.reserved1 = h.reserved2 = h.reserved3 = 0; FILE * fi = fopen(argv[++n],"wb"); if(!fi) { printf("Unable to open destination file %s\n", argv[n]); return 1; } // Write the file header fwrite(&h,1,sizeof(h),fi); // Initialize our source texture ATI_TC_Texture srcTex; srcTex.dwSize = sizeof(srcTex); srcTex.format = (channels == 3) ? ATI_TC_FORMAT_RGB_888 : ATI_TC_FORMAT_ARGB_8888; // Initialize our destination texture ATI_TC_Texture destTex; destTex.dwSize = sizeof(destTex); destTex.format = (channels == 3) ? ATI_TC_FORMAT_ATC_RGB : ATI_TC_FORMAT_ATC_RGBA_Explicit; do { ImageInfo tempImg; CreateNewBitmap(img.width, img.height, img.channels, &tempImg); CopyBitmapSectionDirect(img, tempImg, 0, 0, 0, 0, img.width, img.height); if(channels == 3) ConvertAlphaToBitmap(&tempImg, false, false); srcTex.dwWidth = tempImg.width; srcTex.dwHeight = tempImg.height; // This is true because we shut padding off in ConvertAlphaToBitmap srcTex.dwPitch = tempImg.width * tempImg.channels; srcTex.dwDataSize = (tempImg.width * tempImg.height * (tempImg.channels * 8)) / 8; srcTex.pData = tempImg.data; destTex.dwWidth = srcTex.dwWidth; destTex.dwHeight = srcTex.dwHeight; destTex.dwPitch = 0; destTex.dwDataSize = intmax2((destTex.dwHeight * destTex.dwWidth * (tempImg.channels == 3 ? 4 : 8)) / 8, (tempImg.channels == 3) ? 8 : 16); destTex.pData = (ATI_TC_BYTE*) malloc(destTex.dwDataSize); // Convert it! ATI_TC_ConvertTexture(&srcTex, &destTex, NULL, NULL, NULL, NULL); fwrite(destTex.pData,1,destTex.dwDataSize,fi); free(destTex.pData); DestroyBitmap(&tempImg); if(!AdvanceMipmapStack(&img)) break; } while (1); fclose(fi); DestroyBitmap(&info); } else if(strcmp(argv[1],"--png2atc_raw16")==0 || strcmp(argv[1],"--png2atc_raw24")==0) { bool want_mips = false; bool scale_up = false; bool scale_down = false; bool scale_half = false; int n = 2; if(strcmp(argv[n], "--make_mips") ==0) { want_mips = true;++n; } if(strcmp(argv[n], "--scale_none") ==0) { ++n; } else if(strcmp(argv[n], "--scale_up") ==0) { scale_up = true;++n; } else if(strcmp(argv[n], "--scale_down") ==0) { scale_down = true;++n; } else if(strcmp(argv[n], "--scale_half") ==0) { scale_half = true;++n; } ImageInfo info; if(CreateBitmapFromPNG(argv[n], &info, true, 2.2f)) { printf("Unable to open png file %s\n", argv[n]); return 1; } if (!HandleScale(info, scale_up, scale_down, scale_half, false)) { // Image does NOT meet our power of 2 needs. if(!scale_up && !scale_down && !scale_half) { printf("The imager is not a power of 2. It is: %d by %d\n", info.width, info.height); return 1; } } const char * outf = argv[++n]; int mc = 1; if(want_mips) mc = MakeMipmapStack(&info); if (WriteToRaw(info, outf, strcmp(argv[1],"--png2atc_raw16")==0, false, mc)!=0) { printf("Unable to write raw ARC file %s\n", argv[n]); return 1; } return 0; } #endif else { printf("Unknown conversion flag %s\n", argv[1]); return 1; } return 0; }
27.426053
156
0.628669
den-rain
05fc2ce0994eaa85e79762f4941bd7224eb15a66
346
cpp
C++
graphics/shaders/FloatConstNode.cpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
26
2015-04-22T05:25:25.000Z
2020-11-15T11:07:56.000Z
graphics/shaders/FloatConstNode.cpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
2
2015-01-05T10:41:27.000Z
2015-01-06T20:46:11.000Z
graphics/shaders/FloatConstNode.cpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
5
2016-08-02T11:13:57.000Z
2018-10-26T11:19:27.000Z
#include "FloatConstNode.hpp" BEGIN_INANITY_SHADERS FloatConstNode::FloatConstNode(float value) : value(value) {} Node::Type FloatConstNode::GetType() const { return typeFloatConst; } DataType FloatConstNode::GetValueType() const { return DataTypes::_float; } float FloatConstNode::GetValue() const { return value; } END_INANITY_SHADERS
14.416667
45
0.777457
quyse
af00a0eeb24fbf4aecfd507708a2fcbd01680a40
682
hpp
C++
src/gametransition.hpp
cpusam/dangerous_tux
e5f099f3e3665d62f1c484458125f003c1d5eece
[ "Zlib" ]
1
2020-09-18T07:43:07.000Z
2020-09-18T07:43:07.000Z
src/gametransition.hpp
cpusam/dangerous_tux
e5f099f3e3665d62f1c484458125f003c1d5eece
[ "Zlib" ]
null
null
null
src/gametransition.hpp
cpusam/dangerous_tux
e5f099f3e3665d62f1c484458125f003c1d5eece
[ "Zlib" ]
null
null
null
#ifndef GAMETRANSITION_HPP #define GAMETRANSITION_HPP #include "player.hpp" #include "background.hpp" #include "camera.hpp" #include "platform/tilemap.hpp" #include "gui/label.hpp" class CGameTransition: public StateMachine { protected: Background bg; Camera * cam; TileMapView * map; CPlayer * player; GuiLabel * phrase; SDL_Renderer * renderer; public: CGameTransition ( SDL_Renderer * r ); virtual ~CGameTransition ( ); void set_cam ( Camera * c, SDL_Renderer * renderer ); void set_bg ( string path ); void set_player ( CPlayer * p ); void reset ( int curr_level, int num_levels ); void draw ( ); int update ( ); }; #endif
16.634146
55
0.681818
cpusam
af05ec2b0ab770eb898c56a7214eb607d39e067a
365
cpp
C++
day5/Line.cpp
fardragon/AdventOfCode2021
16f31bcf2e7ff3a1c943e6dfb8b9e791f029dbea
[ "MIT" ]
1
2021-12-02T14:11:37.000Z
2021-12-02T14:11:37.000Z
day5/Line.cpp
fardragon/AdventOfCode2021
16f31bcf2e7ff3a1c943e6dfb8b9e791f029dbea
[ "MIT" ]
null
null
null
day5/Line.cpp
fardragon/AdventOfCode2021
16f31bcf2e7ff3a1c943e6dfb8b9e791f029dbea
[ "MIT" ]
null
null
null
#include "Line.hpp" Line::Line(const Point &p1, const Point &p2) : _points({p1, p2}) { } bool Line::IsHorizontal() const { return _points[0].second == _points[1].second; } bool Line::IsVertical() const { return _points[0].first == _points[1].first; } const std::array<std::pair<std::uint16_t, std::uint16_t>, 2> &Line::GetPoints() const { return _points; }
16.590909
85
0.671233
fardragon
af06f41b2069f25d29a4aa86c04ec4919c50d8c0
1,986
cpp
C++
tests/atexit/host/host.cpp
jbdelcuv/openenclave
c2e9cfabd788597f283c8dd39edda5837b1b1339
[ "MIT" ]
617
2019-06-19T22:08:04.000Z
2022-03-25T09:21:03.000Z
tests/atexit/host/host.cpp
jbdelcuv/openenclave
c2e9cfabd788597f283c8dd39edda5837b1b1339
[ "MIT" ]
2,545
2019-06-18T21:46:10.000Z
2022-03-31T23:26:51.000Z
tests/atexit/host/host.cpp
jbdelcuv/openenclave
c2e9cfabd788597f283c8dd39edda5837b1b1339
[ "MIT" ]
292
2019-07-02T15:40:35.000Z
2022-03-27T13:27:10.000Z
// Copyright (c) Open Enclave SDK contributors. // Licensed under the MIT License. #include <openenclave/host.h> #include <openenclave/internal/calls.h> #include <openenclave/internal/error.h> #include <openenclave/internal/tests.h> #include <cstdio> #include <cstdlib> #include <thread> #include "atexit_u.h" #define OCALL_WITH_INCREASE_SINGLE 0 #define OCALL_WITH_INCREASE_MULTIPLE 1 #define OCALL_WITH_AN_ECALL 2 oe_enclave_t* enclave = NULL; int global_var = 0; void global_variable_increase_ocall(void) { global_var++; } void with_an_ecall_ocall(void) { global_var += 3; uint32_t magic = 2; oe_result_t result = get_magic_ecall(enclave, &magic); // should fail since reentrant ecalls not allowed OE_TEST(result == OE_REENTRANT_ECALL); OE_TEST(2 == magic); global_var += 2; return; } int main(int argc, const char* argv[]) { if (argc != 3) { fprintf(stderr, "Usage: %s ENCLAVE_PATH TEST_NUMBER\n", argv[0]); exit(1); } int expected_value = -1; const uint32_t flags = oe_get_create_flags(); oe_result_t result = oe_create_atexit_enclave( argv[1], OE_ENCLAVE_TYPE_SGX, flags, NULL, 0, &enclave); OE_TEST(result == OE_OK); switch (atoi(argv[2])) { case OCALL_WITH_INCREASE_SINGLE: expected_value = 1; result = atexit_1_call_ecall(enclave); break; case OCALL_WITH_INCREASE_MULTIPLE: expected_value = 32; result = atexit_32_call_ecall(enclave); break; case OCALL_WITH_AN_ECALL: expected_value = 5; result = atexit_with_ecall_ecall(enclave); break; default: break; } // value should not change when enclave is valid OE_TEST(global_var == 0); OE_TEST(result == OE_OK); // Clean up the enclave if (enclave) oe_terminate_enclave(enclave); OE_TEST(global_var == expected_value); return 0; }
24.219512
73
0.651561
jbdelcuv
af0a67c64339e2f7d426d813043cf5fede83d3d6
5,569
cpp
C++
QmlVlcVideoOutput.cpp
xsmart/QmlVlc
284a3731924690ef3b1a2291857f69ce2d271a20
[ "BSD-2-Clause" ]
1
2019-05-13T09:27:29.000Z
2019-05-13T09:27:29.000Z
QmlVlcVideoOutput.cpp
xsmart/QmlVlc
284a3731924690ef3b1a2291857f69ce2d271a20
[ "BSD-2-Clause" ]
1
2021-11-02T17:20:00.000Z
2021-11-02T17:20:00.000Z
deps/QmlVlc/QmlVlcVideoOutput.cpp
litovko/giko_rig
fbc9d336a149f5e072a66245eb94260696a81e1d
[ "Apache-2.0" ]
1
2021-05-25T04:31:11.000Z
2021-05-25T04:31:11.000Z
/******************************************************************************* * Copyright © 2014-2015, Sergey Radionov <rsatom_gmail.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ #include "QmlVlcVideoOutput.h" #include <functional> #include "QmlVlcGenericVideoSurface.h" QmlVlcVideoOutput::QmlVlcVideoOutput( const std::shared_ptr<vlc::player>& player, QObject* parent /*= 0*/ ) : QObject( parent ), m_player( player ) { } void QmlVlcVideoOutput::init() { assert( m_player && m_player->is_open() ); vlc::basic_vmem_wrapper::open( &( m_player->basic_player() ) ); } QmlVlcVideoOutput::~QmlVlcVideoOutput() { //we should force closing vmem here, //to avoid pure virtual member call in vlc::basic_vmem_wrapper vlc::basic_vmem_wrapper::close(); } QSharedPointer<QmlVlcI420Frame> cloneFrame( const QSharedPointer<QmlVlcI420Frame>& from ) { QSharedPointer<QmlVlcI420Frame> newFrame( new QmlVlcI420Frame ); newFrame->frameBuf.resize( from->frameBuf.size() ); newFrame->width = from->width; newFrame->height = from->height; char* fb = newFrame->frameBuf.data(); newFrame->yPlane = fb; newFrame->yPlaneSize = from->yPlaneSize; newFrame->uPlane = fb + newFrame->yPlaneSize; newFrame->uPlaneSize = from->uPlaneSize; newFrame->vPlane = fb + newFrame->yPlaneSize + newFrame->uPlaneSize; newFrame->vPlaneSize = from->vPlaneSize; return newFrame; } unsigned QmlVlcVideoOutput::video_format_cb( char *chroma, unsigned *width, unsigned *height, unsigned *pitches, unsigned *lines ) { memcpy( chroma, "I420", 4 ); uint16_t evenWidth = *width + ( *width & 1 ? 1 : 0 ); uint16_t evenHeight = *height + ( *height & 1 ? 1 : 0 ); pitches[0] = evenWidth; if( pitches[0] % 4 ) pitches[0] += 4 - pitches[0] % 4; pitches[1] = evenWidth / 2; if( pitches[1] % 4 ) pitches[1] += 4 - pitches[1] % 4; pitches[2] = pitches[1]; lines[0] = evenHeight; lines[1] = evenHeight / 2; lines[2] = lines[1]; m_decodeFrame.reset( new QmlVlcI420Frame ); m_decodeFrame->frameBuf.resize( pitches[0] * lines[0] + pitches[1] * lines[1] + pitches[2] * lines[2] ); m_decodeFrame->width = evenWidth; m_decodeFrame->height = evenHeight; char* fb = m_decodeFrame->frameBuf.data(); m_decodeFrame->yPlane = fb; m_decodeFrame->yPlaneSize = pitches[0] * lines[0]; m_decodeFrame->uPlane = fb + m_decodeFrame->yPlaneSize; m_decodeFrame->uPlaneSize = pitches[1] * lines[1]; m_decodeFrame->vPlane = fb + m_decodeFrame->yPlaneSize + m_decodeFrame->uPlaneSize; m_decodeFrame->vPlaneSize = pitches[2] * lines[2]; m_renderFrame = cloneFrame( m_decodeFrame ); return 3; } void QmlVlcVideoOutput::video_cleanup_cb() { m_decodeFrame.clear(); m_renderFrame.clear(); QMetaObject::invokeMethod( this, "frameUpdated" ); } void* QmlVlcVideoOutput::video_lock_cb( void **planes ) { Q_ASSERT( m_decodeFrame ); planes[0] = m_decodeFrame->yPlane; planes[1] = m_decodeFrame->uPlane; planes[2] = m_decodeFrame->vPlane; return 0; } void QmlVlcVideoOutput::video_unlock_cb( void* /*picture*/, void *const * /*planes*/ ) { } void QmlVlcVideoOutput::video_display_cb( void* /*picture*/ ) { m_renderFrame.swap( m_decodeFrame ); QMetaObject::invokeMethod( this, "frameUpdated" ); } void QmlVlcVideoOutput::frameUpdated() { //convert to shared pointer to const frame to avoid crash QSharedPointer<const QmlVlcI420Frame> frame = m_renderFrame; std::for_each( m_attachedSurfaces.begin(), m_attachedSurfaces.end(), std::bind2nd( std::mem_fun( &QmlVlcGenericVideoSurface::presentFrame ), frame ) ); } void QmlVlcVideoOutput::registerVideoSurface( QmlVlcGenericVideoSurface* s ) { Q_ASSERT( m_attachedSurfaces.count( s ) <= 1 ); if( m_attachedSurfaces.contains( s ) ) return; m_attachedSurfaces.append( s ); } void QmlVlcVideoOutput::unregisterVideoSurface( QmlVlcGenericVideoSurface* s ) { Q_ASSERT( m_attachedSurfaces.count( s ) <= 1 ); m_attachedSurfaces.removeOne( s ); }
33.14881
108
0.672652
xsmart
af0b7b989e4709dbe9eed9fb2ca2f9e8b1a079c6
3,906
hh
C++
src/lisp/symbol.hh
kuriboshi/lips
f9f4838a95ff574fb7a627a3eb966b38b6f430f7
[ "Apache-2.0" ]
1
2020-11-10T11:02:21.000Z
2020-11-10T11:02:21.000Z
src/lisp/symbol.hh
kuriboshi/lips
f9f4838a95ff574fb7a627a3eb966b38b6f430f7
[ "Apache-2.0" ]
null
null
null
src/lisp/symbol.hh
kuriboshi/lips
f9f4838a95ff574fb7a627a3eb966b38b6f430f7
[ "Apache-2.0" ]
null
null
null
// // Lips, lisp shell. // Copyright 2021 Krister Joas // #ifndef LISP_SYMBOL_HH #define LISP_SYMBOL_HH #include <cstdint> #include <string> #include <unordered_map> #include <vector> #include "lisp.hh" namespace lisp { class lisp_t; using LISPT = std::shared_ptr<lisp_t>; extern LISPT C_UNBOUND; namespace symbol { struct symbol_t; using store_t = std::vector<symbol_t>; using symbol_index_t = store_t::size_type; using symbol_collection_id = std::uint32_t; struct symbol_index { symbol_index_t index; }; // The print_name class contains the symbol store identifier and the name of // the symbol. struct print_name { symbol_collection_id ident = 0; symbol_index_t index = 0; std::string name; }; struct symbol_t { print_name pname; // The printname of the atom LISPT self; // The LISPT object for this symbol LISPT value; // Value LISPT plist; // The property list LISPT topval; // Holds top value (not used yet) bool constant = false; // If true this is a constant which can't be set }; class symbol_store_t { public: symbol_store_t(symbol_collection_id id): _id(id) {} symbol_store_t(symbol_store_t&& other) noexcept : _id(other._id), _map(std::move(other._map)), _store(std::move(other._store)) {} ~symbol_store_t() {} symbol_store_t& operator=(const symbol_store_t&) = delete; symbol_store_t& operator=(symbol_store_t&& other) noexcept { std::swap(other._map, _map); std::swap(other._store, _store); _id = other._id; return *this; } bool exists(const std::string& name) { return _map.find(name) != _map.end(); } symbol_t& get(const std::string& name) { auto p = _map.find(name); if(p != _map.end()) return _store[p->second]; symbol_t symbol; symbol.pname = {_id, _store.size(), name}; symbol.value = C_UNBOUND; _store.push_back(symbol); _map.emplace(name, symbol.pname.index); return _store[symbol.pname.index]; } symbol_t& get(symbol_index_t index) { return _store.at(index); } store_t::iterator begin() { return _store.begin(); } store_t::iterator end() { return _store.end(); } private: symbol_collection_id _id; using map_type = std::unordered_map<std::string, symbol_index_t>; map_type _map; store_t _store; }; class symbol_collection { public: static const constexpr symbol_collection_id global_id = 0; symbol_collection() { // Create the global symbol store create(); } ~symbol_collection() {} std::unordered_map<symbol_collection_id, symbol_store_t> collection; symbol_store_t& create() { auto [p, inserted] = collection.try_emplace(_free, _free); ++_free; return p->second; } symbol_store_t& symbol_store(symbol_collection_id id) { auto p = collection.find(id); if(p == collection.end()) throw std::runtime_error("no such symbol store"); return p->second; } bool exists(symbol_collection_id id, const std::string& name) { auto p = collection.find(id); if(p == collection.end()) throw std::runtime_error("no such symbol store"); return p->second.exists(name); } symbol_t& get(const print_name& pname) { auto p = collection.find(pname.ident); if(p == collection.end()) throw std::runtime_error("no such symbol store"); return p->second.get(pname.name); } symbol_t& get(symbol_collection_id id, const std::string& name) { auto p = collection.find(id); if(p == collection.end()) throw std::runtime_error("no such symbol store"); return p->second.get(name); } symbol_t& get(symbol_collection_id id, symbol_index_t index) { auto p = collection.find(id); if(p == collection.end()) throw std::runtime_error("no such symbol store"); return p->second.get(index); } private: symbol_collection_id _free = 0; }; } // namespace symbol } // namespace lisp #endif
23.96319
82
0.678187
kuriboshi
af0ca9d1a06932b25d39ef87acd36f59c0b2db6b
404
cpp
C++
src/wire/core/ssl_certificate.cpp
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
5
2016-04-07T19:49:39.000Z
2021-08-03T05:24:11.000Z
src/wire/core/ssl_certificate.cpp
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
null
null
null
src/wire/core/ssl_certificate.cpp
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
1
2020-12-27T11:47:31.000Z
2020-12-27T11:47:31.000Z
/* * ssl_certificate.cpp * * Created on: May 24, 2017 * Author: zmij */ #include <wire/core/ssl_certificate.hpp> #include <openssl/x509.h> namespace wire { namespace core { ::std::string ssl_certificate::subject_name() const { char sn[256]; X509_NAME_oneline(X509_get_subject_name(native_), sn, 256); return ::std::string{sn}; } } /* namespace core */ } /* namespace wire */
15.538462
63
0.660891
zmij
af0d8d4c3ea38246bb2aba7d7c7e2bf2dfd18905
1,998
cpp
C++
Engine/Src/Common/GfInput/GfMouse.cpp
alapontgr/Engine
6be363d79b9fdaee813b196db12ae296a6ca8089
[ "MIT" ]
null
null
null
Engine/Src/Common/GfInput/GfMouse.cpp
alapontgr/Engine
6be363d79b9fdaee813b196db12ae296a6ca8089
[ "MIT" ]
null
null
null
Engine/Src/Common/GfInput/GfMouse.cpp
alapontgr/Engine
6be363d79b9fdaee813b196db12ae296a6ca8089
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // // Author: Sergio Alapont Granero (seralgrainf@gmail.com) // Date: 2019/04/16 // File: GfMouse.cpp // // Copyright (c) 2018 (See README.md) // //////////////////////////////////////////////////////////////////////////////// // Includes #include "Common/GfInput/GfMouse.h" //////////////////////////////////////////////////////////////////////////////// GfMouse::GfMouse() : m_vMousePosition(0.0f) , m_uiButtonsDown(0) , m_uiButtonsPressed(0) { m_pWheelDelta[0] = m_pWheelDelta[1] = 0.0f; } //////////////////////////////////////////////////////////////////////////////// void GfMouse::Update() { m_uiButtonsPressed = (m_uiButtonsPressed ^ m_uiButtonsDown); // Every button down becomes pressed m_uiButtonsDown = 0; // delay the delta for one frame just in case m_pWheelDelta[0] = m_pWheelDelta[1]; m_pWheelDelta[1] = 0.0f; } //////////////////////////////////////////////////////////////////////////////// bool GfMouse::IsButtonDown(MouseButtons eButton) const { return (m_uiButtonsDown & (1<<eButton)) != 0; } //////////////////////////////////////////////////////////////////////////////// bool GfMouse::IsButtonPressed(MouseButtons eButton) const { return (m_uiButtonsPressed & (1 << eButton)) != 0; } //////////////////////////////////////////////////////////////////////////////// f32 GfMouse::GetWheelDelta() const { return m_pWheelDelta[0]; } //////////////////////////////////////////////////////////////////////////////// v2 GfMouse::GetMousePos() const { return m_vMousePosition; } //////////////////////////////////////////////////////////////////////////////// void GfMouse::SetMousePos(const v2& vPos) { m_vMousePosition = vPos; } //////////////////////////////////////////////////////////////////////////////// void GfMouse::SetWheelDelta(f32 fVal) { m_pWheelDelta[1] = fVal; } //////////////////////////////////////////////////////////////////////////////// // EOF
25.615385
98
0.391892
alapontgr
af0e1fe2eabf992658b72ca9358b8017b715aab4
406
cpp
C++
C++/homeworksC++/countString.cpp
faber222/Aulas-Prog
989843c5e0ede5b7a5e8fffbd4c2da80e924ffdb
[ "MIT" ]
null
null
null
C++/homeworksC++/countString.cpp
faber222/Aulas-Prog
989843c5e0ede5b7a5e8fffbd4c2da80e924ffdb
[ "MIT" ]
null
null
null
C++/homeworksC++/countString.cpp
faber222/Aulas-Prog
989843c5e0ede5b7a5e8fffbd4c2da80e924ffdb
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; int main() { cout << "\x1b[2J"; cout << "\x1b[H"; string frase; getline(cin, frase); int x = 0; int y = 0; while (x != string::npos) { int z = frase.find_first_not_of(" \n\t.?:!;,", x); if (z == string::npos) break; y++; x = frase.find_first_of(" \n\t.?:!;,", z); } cout << y << ' ' << frase.size() << endl; }
18.454545
54
0.514778
faber222
af239c5ad9557a5e132c1eb0bffd0d0ea19a32e8
10,984
cpp
C++
fast_dc.cpp
Borges3D/fast_dual_contouring
2dbe5c22900bf69e4ae3f4dcfb54e126e8a0f22f
[ "Unlicense" ]
136
2017-05-30T21:48:39.000Z
2022-03-11T20:47:54.000Z
fast_dc.cpp
Borges3D/fast_dual_contouring
2dbe5c22900bf69e4ae3f4dcfb54e126e8a0f22f
[ "Unlicense" ]
1
2019-09-17T09:12:32.000Z
2019-09-19T23:47:11.000Z
fast_dc.cpp
Borges3D/fast_dual_contouring
2dbe5c22900bf69e4ae3f4dcfb54e126e8a0f22f
[ "Unlicense" ]
19
2017-06-01T00:59:59.000Z
2021-01-25T22:45:53.000Z
// // Written by Nick Gildea (2017) // Public Domain // #include "fast_dc.h" #include "ng_mesh_simplify.h" #include "qef_simd.h" #include <glm/glm.hpp> #include <stdint.h> // ---------------------------------------------------------------------------- // TODO the winding field could be packed into the normal vec as the unused w component struct EdgeInfo { vec4 pos; vec4 normal; bool winding = false; }; // Ideally we'd use https://github.com/greg7mdp/sparsepp but fall back to STL #ifdef HAVE_SPARSEPP #include <sparsepp/spp.h> using EdgeInfoMap = spp::sparese_hash_map<uint32_t, EdgeInfo>; using VoxelIDSet = spp::sparse_hash_set<uint32_t>; using VoxelIndexMap = spp::sparese_hash_map<uint32_t, int>; #else #include <unordered_map> #include <unordered_set> using EdgeInfoMap = std::unordered_map<uint32_t, EdgeInfo>; using VoxelIDSet = std::unordered_set<uint32_t>; using VoxelIndexMap = std::unordered_map<uint32_t, int>; #endif // ---------------------------------------------------------------------------- using glm::ivec4; using glm::vec4; using glm::vec3; using glm::vec2; #ifdef _MSC_VER #define ALIGN16 __declspec(align(16)) #else #define ALIGN16 __attribute__((aligned(16)) #endif // ---------------------------------------------------------------------------- const int VOXEL_GRID_SIZE = 128; const float VOXEL_GRID_OFFSET = (float)VOXEL_GRID_SIZE / 2.f; // ---------------------------------------------------------------------------- static const vec4 AXIS_OFFSET[3] = { vec4(1.f, 0.f, 0.f, 0.f), vec4(0.f, 1.f, 0.f, 0.f), vec4(0.f, 0.f, 1.f, 0.f) }; // ---------------------------------------------------------------------------- static const ivec4 EDGE_NODE_OFFSETS[3][4] = { { ivec4(0), ivec4(0, 0, 1, 0), ivec4(0, 1, 0, 0), ivec4(0, 1, 1, 0) }, { ivec4(0), ivec4(1, 0, 0, 0), ivec4(0, 0, 1, 0), ivec4(1, 0, 1, 0) }, { ivec4(0), ivec4(0, 1, 0, 0), ivec4(1, 0, 0, 0), ivec4(1, 1, 0, 0) }, }; // ---------------------------------------------------------------------------- // The two lookup tables below were calculated by expanding the IDs into 3d coordinates // performing the calcuations in 3d space and then converting back into the compact form // and subtracting the base voxel ID. Use of this lookup table means those calculations // can be avoided at run-time. const uint32_t ENCODED_EDGE_NODE_OFFSETS[12] = { 0x00000000, 0x00100000, 0x00000400, 0x00100400, 0x00000000, 0x00000001, 0x00100000, 0x00100001, 0x00000000, 0x00000400, 0x00000001, 0x00000401, }; const uint32_t ENCODED_EDGE_OFFSETS[12] = { 0x00000000, 0x00100000, 0x00000400, 0x00100400, 0x40000000, 0x40100000, 0x40000001, 0x40100001, 0x80000000, 0x80000400, 0x80000001, 0x80000401, }; // ---------------------------------------------------------------------------- // The "super primitve" -- use the parameters to configure different shapes from a single function // see https://www.shadertoy.com/view/MsVGWG float sdSuperprim(vec3 p, vec4 s, vec2 r) { const vec3 d = glm::abs(p) - vec3(s); float q = glm::length(vec2(glm::max(d.x + r.x, 0.f), glm::max(d.y + r.x, 0.f))); q += glm::min(-r.x, glm::max(d.x,d.y)); q = (glm::abs((q + s.w)) - s.w); return glm::length(vec2(glm::max(q + r.y,0.f), glm::max(d.z + r.y, 0.f))) + glm::min(-r.y, glm::max(q, d.z)); } // ---------------------------------------------------------------------------- float Density(const SuperPrimitiveConfig& config, const vec4& p) { const float scale = 32.f; return sdSuperprim(vec3(p) / scale, vec4(config.s), vec2(config.r)) * scale; } // ---------------------------------------------------------------------------- uint32_t EncodeVoxelUniqueID(const ivec4& idxPos) { return idxPos.x | (idxPos.y << 10) | (idxPos.z << 20); } // ---------------------------------------------------------------------------- ivec4 DecodeVoxelUniqueID(const uint32_t id) { return ivec4( id & 0x3ff, (id >> 10) & 0x3ff, (id >> 20) & 0x3ff, 0); } // ---------------------------------------------------------------------------- uint32_t EncodeAxisUniqueID(const int axis, const int x, const int y, const int z) { return (x << 0) | (y << 10) | (z << 20) | (axis << 30); } // ---------------------------------------------------------------------------- float FindIntersection(const SuperPrimitiveConfig& config, const vec4& p0, const vec4& p1) { const int FIND_EDGE_INFO_STEPS = 16; const float FIND_EDGE_INFO_INCREMENT = 1.f / FIND_EDGE_INFO_STEPS; float minValue = FLT_MAX; float currentT = 0.f; float t = 0.f; for (int i = 0; i < FIND_EDGE_INFO_STEPS; i++) { const vec4 p = glm::mix(p0, p1, currentT); const float d = glm::abs(Density(config, p)); if (d < minValue) { t = currentT; minValue = d; } currentT += FIND_EDGE_INFO_INCREMENT; } return t; } // ---------------------------------------------------------------------------- static void FindActiveVoxels( const SuperPrimitiveConfig& config, VoxelIDSet& activeVoxels, EdgeInfoMap& activeEdges) { for (int x = 0; x < VOXEL_GRID_SIZE; x++) for (int y = 0; y < VOXEL_GRID_SIZE; y++) for (int z = 0; z < VOXEL_GRID_SIZE; z++) { const ivec4 idxPos(x, y, z, 0); const vec4 p = vec4(x - VOXEL_GRID_OFFSET, y - VOXEL_GRID_OFFSET, z - VOXEL_GRID_OFFSET, 1.f); for (int axis = 0; axis < 3; axis++) { const vec4 q = p + AXIS_OFFSET[axis]; const float pDensity = Density(config, p); const float qDensity = Density(config, q); const bool zeroCrossing = pDensity >= 0.f && qDensity < 0.f || pDensity < 0.f && qDensity >= 0.f; if (!zeroCrossing) { continue; } const float t = FindIntersection(config, p, q); const vec4 pos = vec4(glm::mix(glm::vec3(p), glm::vec3(q), t), 1.f); const float H = 0.001f; const auto normal = glm::normalize(vec4( Density(config, pos + vec4(H, 0.f, 0.f, 0.f)) - Density(config, pos - vec4(H, 0.f, 0.f, 0.f)), Density(config, pos + vec4(0.f, H, 0.f, 0.f)) - Density(config, pos - vec4(0.f, H, 0.f, 0.f)), Density(config, pos + vec4(0.f, 0.f, H, 0.f)) - Density(config, pos - vec4(0.f, 0.f, H, 0.f)), 0.f)); EdgeInfo info; info.pos = pos; info.normal = normal; info.winding = pDensity >= 0.f; const auto code = EncodeAxisUniqueID(axis, x, y, z); activeEdges[code] = info; const auto edgeNodes = EDGE_NODE_OFFSETS[axis]; for (int i = 0; i < 4; i++) { const auto nodeIdxPos = idxPos - edgeNodes[i]; const auto nodeID = EncodeVoxelUniqueID(nodeIdxPos); activeVoxels.insert(nodeID); } } } } // ---------------------------------------------------------------------------- static void GenerateVertexData( const VoxelIDSet& voxels, const EdgeInfoMap& edges, VoxelIndexMap& vertexIndices, MeshBuffer* buffer) { MeshVertex* vert = &buffer->vertices[0]; int idxCounter = 0; for (const auto& voxelID: voxels) { ALIGN16 vec4 p[12]; ALIGN16 vec4 n[12]; int idx = 0; for (int i = 0; i < 12; i++) { const auto edgeID = voxelID + ENCODED_EDGE_OFFSETS[i]; const auto iter = edges.find(edgeID); if (iter != end(edges)) { const auto& info = iter->second; const vec4 pos = info.pos; const vec4 normal = info.normal; p[idx] = pos; n[idx] = normal; idx++; } } ALIGN16 vec4 nodePos; qef_solve_from_points_4d(&p[0].x, &n[0].x, idx, &nodePos.x); vec4 nodeNormal; for (int i = 0; i < idx; i++) { nodeNormal += n[i]; } nodeNormal *= (1.f / (float)idx); vertexIndices[voxelID] = idxCounter++; buffer->numVertices++; vert->xyz = nodePos; vert->normal = nodeNormal; vert++; } } // ---------------------------------------------------------------------------- static void GenerateTriangles( const EdgeInfoMap& edges, const VoxelIndexMap& vertexIndices, MeshBuffer* buffer) { MeshTriangle* tri = &buffer->triangles[0]; for (const auto& pair: edges) { const auto& edge = pair.first; const auto& info = pair.second; const ivec4 basePos = DecodeVoxelUniqueID(edge); const int axis = (edge >> 30) & 0xff; const int nodeID = edge & ~0xc0000000; const uint32_t voxelIDs[4] = { nodeID - ENCODED_EDGE_NODE_OFFSETS[axis * 4 + 0], nodeID - ENCODED_EDGE_NODE_OFFSETS[axis * 4 + 1], nodeID - ENCODED_EDGE_NODE_OFFSETS[axis * 4 + 2], nodeID - ENCODED_EDGE_NODE_OFFSETS[axis * 4 + 3], }; // attempt to find the 4 voxels which share this edge int edgeVoxels[4]; int numFoundVoxels = 0; for (int i = 0; i < 4; i++) { const auto iter = vertexIndices.find(voxelIDs[i]); if (iter != end(vertexIndices)) { edgeVoxels[numFoundVoxels++] = iter->second; } } // we can only generate a quad (or two triangles) if all 4 are found if (numFoundVoxels < 4) { continue; } if (info.winding) { tri->indices_[0] = edgeVoxels[0]; tri->indices_[1] = edgeVoxels[1]; tri->indices_[2] = edgeVoxels[3]; tri++; tri->indices_[0] = edgeVoxels[0]; tri->indices_[1] = edgeVoxels[3]; tri->indices_[2] = edgeVoxels[2]; tri++; } else { tri->indices_[0] = edgeVoxels[0]; tri->indices_[1] = edgeVoxels[3]; tri->indices_[2] = edgeVoxels[1]; tri++; tri->indices_[0] = edgeVoxels[0]; tri->indices_[1] = edgeVoxels[2]; tri->indices_[2] = edgeVoxels[3]; tri++; } buffer->numTriangles += 2; } } // ---------------------------------------------------------------------------- MeshBuffer* GenerateMesh(const SuperPrimitiveConfig& config) { VoxelIDSet activeVoxels; EdgeInfoMap activeEdges; FindActiveVoxels(config, activeVoxels, activeEdges); MeshBuffer* buffer = new MeshBuffer; buffer->vertices = (MeshVertex*)malloc(activeVoxels.size() * sizeof(MeshVertex)); buffer->numVertices = 0; VoxelIndexMap vertexIndices; GenerateVertexData(activeVoxels, activeEdges, vertexIndices, buffer); buffer->triangles = (MeshTriangle*)malloc(2 * activeEdges.size() * sizeof(MeshTriangle)); buffer->numTriangles = 0; GenerateTriangles(activeEdges, vertexIndices, buffer); printf("mesh: %d %d\n", buffer->numVertices, buffer->numTriangles); return buffer; } // ---------------------------------------------------------------------------- SuperPrimitiveConfig ConfigForShape(const SuperPrimitiveConfig::Type& type) { SuperPrimitiveConfig config; switch (type) { default: case SuperPrimitiveConfig::Cube: config.s = vec4(1.f); config.r = vec2(0.f); break; case SuperPrimitiveConfig::Cylinder: config.s = vec4(1.f); config.r = vec2(1.f, 0.f); break; case SuperPrimitiveConfig::Pill: config.s = vec4(1.f, 1.f, 2.f, 1.); config.r = vec2(1.f); break; case SuperPrimitiveConfig::Corridor: config.s = vec4(1.f, 1.f, 1.f, 0.25f); config.r = vec2(0.1f); break; case SuperPrimitiveConfig::Torus: config.s = vec4(1.f, 1.f, 0.25f, 0.25f); config.r = vec2(1.f, 0.25f); break; } return config; } // ----------------------------------------------------------------------------
24.794582
99
0.569829
Borges3D
af2ab6fd45d426f4a39cbcd17dd10fe5baecc967
4,985
cpp
C++
12/passage_pathing.t.cpp
ComicSansMS/AdventOfCode2021
60902d14c356c3375266703e85aca991241afc84
[ "Unlicense" ]
null
null
null
12/passage_pathing.t.cpp
ComicSansMS/AdventOfCode2021
60902d14c356c3375266703e85aca991241afc84
[ "Unlicense" ]
null
null
null
12/passage_pathing.t.cpp
ComicSansMS/AdventOfCode2021
60902d14c356c3375266703e85aca991241afc84
[ "Unlicense" ]
null
null
null
#include <passage_pathing.hpp> #include <catch.hpp> #include <sstream> TEST_CASE("Passage Pathing") { char const sample_input1[] = "start-A" "\n" "start-b" "\n" "A-c" "\n" "A-b" "\n" "b-d" "\n" "A-end" "\n" "b-end" "\n"; char const sample_input2[] = "dc-end" "\n" "HN-start" "\n" "start-kj" "\n" "dc-start" "\n" "dc-HN" "\n" "LN-dc" "\n" "HN-end" "\n" "kj-sa" "\n" "kj-HN" "\n" "kj-dc" "\n"; char const sample_input3[] = "fs-end" "\n" "he-DX" "\n" "fs-he" "\n" "start-DX" "\n" "pj-DX" "\n" "end-zg" "\n" "zg-sl" "\n" "zg-pj" "\n" "pj-he" "\n" "RW-he" "\n" "fs-DX" "\n" "pj-RW" "\n" "zg-RW" "\n" "start-pj" "\n" "he-WI" "\n" "zg-he" "\n" "pj-fs" "\n" "start-RW" "\n"; SECTION("Parse Input") { auto const graph = parseInput(sample_input1); REQUIRE(graph.caves.size() == 6); CHECK(graph.caves[0] == Cave{ .name = "start", .isBig = false, .neighbours = { 1, 2 } }); CHECK(graph.caves[1] == Cave{ .name = "A", .isBig = true, .neighbours = { 0, 3, 2, 5 } }); CHECK(graph.caves[2] == Cave{ .name = "b", .isBig = false, .neighbours = { 0, 1, 4, 5 } }); CHECK(graph.caves[3] == Cave{ .name = "c", .isBig = false, .neighbours = { 1 } }); CHECK(graph.caves[4] == Cave{ .name = "d", .isBig = false, .neighbours = { 2 } }); CHECK(graph.caves[5] == Cave{ .name = "end", .isBig = false, .neighbours = { 1, 2 } }); REQUIRE(graph.edges.size() == 7); CHECK(graph.edges[0] == Edge{ .start_index = 0, .destination_index = 1 }); CHECK(graph.edges[1] == Edge{ .start_index = 0, .destination_index = 2 }); CHECK(graph.edges[2] == Edge{ .start_index = 1, .destination_index = 3 }); CHECK(graph.edges[3] == Edge{ .start_index = 1, .destination_index = 2 }); CHECK(graph.edges[4] == Edge{ .start_index = 2, .destination_index = 4 }); CHECK(graph.edges[5] == Edge{ .start_index = 1, .destination_index = 5 }); CHECK(graph.edges[6] == Edge{ .start_index = 2, .destination_index = 5 }); CHECK(graph.startCaveIndex == 0); CHECK(graph.endCaveIndex == 5); } SECTION("All Paths") { auto const graph = parseInput(sample_input1); auto const ap = allPaths(graph); REQUIRE(ap.size() == 10); // start,A,b,A,c,A,end CHECK(ap[3].nodes == std::vector<std::size_t>{ 0, 1, 2, 1, 3, 1, 5 }); // start,A,b,A,end CHECK(ap[4].nodes == std::vector<std::size_t>{ 0, 1, 2, 1, 5 }); // start,A,b,end CHECK(ap[5].nodes == std::vector<std::size_t>{ 0, 1, 2, 5 }); // start,A,c,A,b,A,end CHECK(ap[0].nodes == std::vector<std::size_t>{ 0, 1, 3, 1, 2, 1, 5 }); // start,A,c,A,b,end CHECK(ap[1].nodes == std::vector<std::size_t>{ 0, 1, 3, 1, 2, 5 }); // start,A,c,A,end CHECK(ap[2].nodes == std::vector<std::size_t>{ 0, 1, 3, 1, 5 }); // start,A,end CHECK(ap[6].nodes == std::vector<std::size_t>{ 0, 1, 5 }); // start,b,A,c,A,end CHECK(ap[7].nodes == std::vector<std::size_t>{ 0, 2, 1, 3, 1, 5 }); // start,b,A,end CHECK(ap[8].nodes == std::vector<std::size_t>{ 0, 2, 1, 5 }); // start,b,end CHECK(ap[9].nodes == std::vector<std::size_t>{ 0, 2, 5 }); auto const graph2 = parseInput(sample_input2); CHECK(allPaths(graph2).size() == 19); auto const graph3 = parseInput(sample_input3); CHECK(allPaths(graph3).size() == 226); } SECTION("All Paths 2") { auto const graph = parseInput(sample_input1); auto const ap = allPaths2(graph); REQUIRE(ap.size() == 36); auto const graph2 = parseInput(sample_input2); CHECK(allPaths2(graph2).size() == 103); auto const graph3 = parseInput(sample_input3); CHECK(allPaths2(graph3).size() == 3509); } }
44.115044
99
0.408225
ComicSansMS
af2ed4b1e1c502fe3ec94638e47e5a5fb24c372b
975
cpp
C++
Framework/PathUtils.cpp
jerryrox/RenkoSDLFramework
0db6948c067b101a3702128e61d601dfe879aba1
[ "MIT" ]
null
null
null
Framework/PathUtils.cpp
jerryrox/RenkoSDLFramework
0db6948c067b101a3702128e61d601dfe879aba1
[ "MIT" ]
null
null
null
Framework/PathUtils.cpp
jerryrox/RenkoSDLFramework
0db6948c067b101a3702128e61d601dfe879aba1
[ "MIT" ]
null
null
null
#include "PathUtils.h" std::string PathUtils::Combine(std::string* x, std::string* y) { if (x == 0 || y == 0) return ""; if (x->size() == 0) return std::string(*y); if (y->size() == 0) return std::string(*x); for (int i = (int)x->size() - 1; i >= 0; i--) { if (x->at(i) != '\\') break; x->erase(x->begin() + i); } for (int i=0; i<(int)y->size(); i++) { if (y->at(i) != '\\') break; y->erase(y->begin() + i); } return std::string(*x) + '\\' + std::string(*y); } std::wstring PathUtils::Combine(std::wstring* x, std::wstring* y) { if (x == 0 || y == 0) return L""; if (x->size() == 0) return std::wstring(*y); if (y->size() == 0) return std::wstring(*x); for (int i = (int)x->size() - 1; i >= 0; i--) { if (x->at(i) != L'\\') break; x->erase(x->begin() + i); } for (int i = 0; i < (int)y->size(); i++) { if (y->at(i) != L'\\') break; y->erase(y->begin() + i); } return std::wstring(*x) + L'\\' + std::wstring(*y); }
20.744681
65
0.471795
jerryrox
af2f1ff3777e823efa7240711d1032d064055d49
48,883
cpp
C++
src/QtTasks/Items/VcfScheduler.cpp
Vladimir-Lin/QtTasks
2150f149509678f012afa05cd7fb7d4acbfdbc9d
[ "MIT" ]
null
null
null
src/QtTasks/Items/VcfScheduler.cpp
Vladimir-Lin/QtTasks
2150f149509678f012afa05cd7fb7d4acbfdbc9d
[ "MIT" ]
null
null
null
src/QtTasks/Items/VcfScheduler.cpp
Vladimir-Lin/QtTasks
2150f149509678f012afa05cd7fb7d4acbfdbc9d
[ "MIT" ]
null
null
null
#include <qttasks.h> N::VcfScheduler:: VcfScheduler ( VcfHeadParaments ) : VcfCanvas ( parent , item , p ) , Thread ( ) , TimeBar ( NULL ) , Section ( NULL ) , TimeBlock ( NULL ) { Configure ( ) ; } N::VcfScheduler::~VcfScheduler(void) { Timer . stop ( ) ; } void N::VcfScheduler::contextMenuEvent(QGraphicsSceneContextMenuEvent * event) { ScheduleMenu ( event -> pos ( ) ) ; event -> accept ( ) ; } void N::VcfScheduler::Paint(QPainter * painter,QRectF Region,bool clip,bool color) { VcfCanvas::Paint(painter,Region,clip,color) ; } void N::VcfScheduler::Configure(void) { Printable = true ; Scaling = false ; Editable = true ; setFlag ( ItemIsMovable , false ) ; setFlag ( ItemIsSelectable , true ) ; setFlag ( ItemIsFocusable , true ) ; setFlag ( ItemClipsToShape , false ) ; setFlag ( ItemClipsChildrenToShape , false ) ; Painter . addMap ( "Default" , 0 ) ; Painter . addPen ( 0 , QColor ( 192 , 192 , 192 ) ) ; Painter . addPen ( 1 , QColor ( 0 , 0 , 0 ) ) ; Painter . addBrush ( 0 , QColor ( 252 , 252 , 252 ) ) ; nConnect ( &Timer , SIGNAL ( timeout() ) , this , SLOT ( Refresh() ) ) ; setDropFlag ( DropText , true ) ; setDropFlag ( DropUrls , true ) ; setDropFlag ( DropImage , false ) ; setDropFlag ( DropHtml , true ) ; setDropFlag ( DropColor , true ) ; setDropFlag ( DropTag , true ) ; setDropFlag ( DropPicture , true ) ; setDropFlag ( DropPeople , true ) ; setDropFlag ( DropVideo , true ) ; setDropFlag ( DropAlbum , true ) ; setDropFlag ( DropGender , false ) ; setDropFlag ( DropDivision , false ) ; setDropFlag ( DropURIs , true ) ; setDropFlag ( DropBookmark , true ) ; setDropFlag ( DropFont , true ) ; setDropFlag ( DropPen , true ) ; setDropFlag ( DropBrush , true ) ; setDropFlag ( DropGradient , true ) ; setDropFlag ( DropShape , false ) ; setDropFlag ( DropMember , false ) ; setDropFlag ( DropSet , false ) ; } void N::VcfScheduler::Initialize(void) { Mutex . lock ( ) ; QTime T(12,0,0,0) ; //////////////////////////////////////////////////////////// QDateTime CC = QDateTime::currentDateTime() ; QTime TT = CC . time ( ) ; if (TT.hour()< 6) T . setHMS ( 6,0,0) ; else if (TT.hour()>18) T . setHMS (18,0,0) ; MidDay = CC ; MidDay . setTime ( T ) ; //////////////////////////////////////////////////////////// QGraphicsView * gv = GraphicsView() ; TimeBar = new VcfTimeBar ( gv , this , plan ) ; TimeBar -> Options = Options ; TimeBar -> setZValue ( 0.75f ) ; TimeBar -> setOpacity ( 0.90f ) ; TimeBar -> setPos (QPointF(0,0) ) ; TimeBar -> setRect (QRectF(0,0,1.0,0.75) ) ; TimeBar -> setToday ( ) ; nConnect ( TimeBar , SIGNAL ( TimeUpdated() ) , this , SLOT ( TimeUpdated() ) ) ; //////////////////////////////////////////////////////////// QPen Pxn ( QColor(128,128, 32) ) ; QBrush Bxn ( QColor(248,248, 0) ) ; Pxn . setStyle ( Qt::DashLine ) ; Bxn . setStyle ( Qt::Dense6Pattern ) ; TimeBlock = new QGraphicsRectItem ( this ) ; TimeBlock -> setZValue ( 0.60f ) ; TimeBlock -> setOpacity ( 0.20f ) ; TimeBlock -> setPen ( Pxn ) ; TimeBlock -> setBrush ( Bxn ) ; //////////////////////////////////////////////////////////// Section = new VcfTimeSection ( gv , this , plan ) ; Section -> Options = Options ; Section -> Start = TimeBar->Start ; Section -> Final = TimeBar->Final ; Section -> setZValue ( 0.50f ) ; Section -> setOpacity ( 0.80f ) ; Section -> setPos (QPointF(0.0,0.75) ) ; Section -> setRect (QRectF(0,0,1.0,1.0) ) ; Section -> FetchFont (0,"Default" ) ; Section -> FetchFont (1,"ToolTip" ) ; nConnect ( Section , SIGNAL(Append(QDateTime,QDateTime)) , this , SLOT (Append(QDateTime,QDateTime)) ) ; //////////////////////////////////////////////////////////// Mutex . unlock ( ) ; //////////////////////////////////////////////////////////// emit Append ( TimeBar , this ) ; emit Append ( Section , this ) ; //////////////////////////////////////////////////////////// Timer . start ( 1000 ) ; } bool N::VcfScheduler::contains(QDateTime start,QDateTime final) { if (IsNull(TimeBar) ) return false ; if (final< TimeBar->Start ) return false ; if (start> TimeBar->Final ) return false ; if (start>=TimeBar->Start && start<=TimeBar->Final) return true ; if (final>=TimeBar->Start && final<=TimeBar->Final) return true ; if (start<=TimeBar->Start && final>=TimeBar->Final) return true ; return false ; } int N::VcfScheduler::PaperX(void) { if (IsNull(TimeBar)) return 0 ; int x = 1 ; QDateTime S = TimeBar->Start ; QDateTime F = TimeBar->Final ; QDateTime E ; QTime T(23,59,59,0) ; QTime Z( 0, 0, 0,0) ; do { E = S ; E.setTime(T) ; if (E<F) { x++ ; S = S.addSecs(86400) ; S . setTime (Z ) ; } ; } while (E<F) ; return x ; } int N::VcfScheduler::PaperY(void) { if (IsNull(TimeBar)) return 0 ; QRectF P = PaperDPI() ; double dh = ScreenRect.height() ; P = Options->Region(P) ; int DH = (int)dh ; int DP = (int)P.height() ; int Y = DH / DP ; int M = DH % DP ; if (M>0) Y++ ; return Y ; } QRectF N::VcfScheduler::PaperDPI(void) { return plan->paper["A4"].rect(Qt::Horizontal) ; } double N::VcfScheduler::LeftBase(QRectF View) { if (IsNull(TimeBar)) return 0 ; QRectF Z = Options->Standard(View) ; QDateTime S = TimeBar->Start ; QDateTime F = TimeBar->Final ; QDateTime L = S ; QTime T (0,0,0,0) ; double x ; L.setTime(T) ; int dt = S.secsTo(F) ; int ds = L.secsTo(S) ; if (dt<=0) return Z . left () ; x = ScreenRect.width() ; x *= ds ; x /= dt ; QPointF v(x,x) ; v = Options->Standard(v) ; x = v.x() ; return Z . left ( ) - x ; } void N::VcfScheduler::setRegion(QRectF Region) { Mutex . lock () ; //////////////////////////////////////// QRectF P = PaperDPI() ; VcfRectangle::setRect ( Region ) ; double dw = ScreenRect.width() ; P = Options->Region(P) ; dw /= P.width() ; dw *= 43200 ; //////////////////////////////////////// QRectF R = Region ; R.setHeight(0.75f) ; if (NotNull(TimeBar)) { TimeBar->Start = MidDay.addSecs(-dw) ; TimeBar->Final = MidDay.addSecs( dw) ; TimeBar->setRect(R) ; } ; //////////////////////////////////////// if (NotNull(Section)) { R.setTop (0.00f) ; R.setHeight (1.00f) ; Section->Start = TimeBar->Start ; Section->Final = TimeBar->Final ; Section->setRect ( R ) ; Section->update ( ) ; } ; Mutex . unlock () ; emit RegionUpdated() ; QTimer::singleShot(200,this,SLOT(UpdateItems())) ; } void N::VcfScheduler::Refresh(void) { if (IsNull(TimeBar )) return ; if (IsNull(TimeBlock)) return ; QDateTime S = TimeBar->Start ; QDateTime F = TimeBar->Final ; QDateTime C = nTimeNow ; QRectF R = ScreenRect ; if (C<S) { TimeBlock -> setVisible ( false ) ; return ; } ; if (C<F) { int dt = S.secsTo(F) ; int ds = S.secsTo(C) ; double dw = ScreenRect.width() ; if (dt>0) { dw *= ds ; dw /= dt ; R . setWidth ( dw ) ; } ; } ; TimeBlock -> setVisible ( true ) ; TimeBlock -> setRect ( R ) ; } void N::VcfScheduler::TimeUpdated(void) { if (IsNull(TimeBar)) return ; if (IsNull(Section)) return ; Mutex . lock ( ) ; int dt = TimeBar->Start.secsTo(TimeBar->Final) ; dt /= 2 ; MidDay = TimeBar -> Start ; MidDay = MidDay . addSecs ( dt ) ; if (NotNull(Section)) { Section->Start = TimeBar->Start ; Section->Final = TimeBar->Final ; Section->update ( ) ; } ; Mutex . unlock ( ) ; UpdateItems() ; emit RegionUpdated ( ) ; } void N::VcfScheduler::Append(QDateTime start,QDateTime final) { int ds = start.secsTo(final) ; if (ds<60) return ; Font F1 = Section -> Painter . fonts [ 0 ] ; Font F2 = Section -> Painter . fonts [ 1 ] ; VcfGantt * Gantt ; Gantt = new VcfGantt(GraphicsView(),this,plan) ; Gantt -> Uuid = 0 ; Gantt -> Task = 0 ; Gantt -> Owner = 0 ; Gantt -> EventType = Period ; Gantt -> Status = 0 ; Gantt -> Adjust = 0 ; Gantt -> Painter.fonts[0] = F1 ; Gantt -> Painter.fonts[1] = F2 ; Gantt -> plan = plan ; Gantt -> Options = Options ; Gantt -> Start = start ; Gantt -> Final = final ; Gantt -> TabletStart = TimeBar->Start ; Gantt -> TabletFinal = TimeBar->Final ; Gantt -> Content = "" ; Gantt -> Note = "" ; Gantt -> setZValue ( 0.50f ) ; Gantt -> setOpacity ( 1.00f ) ; Gantt -> setPos ( QPointF(0,2.00) ) ; Gantt -> setRect ( QRectF(0,0,0.01,0.75) ) ; Gantt -> DropChanged ( ) ; UpdateGantt ( Gantt ) ; Gantts << Gantt ; nConnect ( Gantt,SIGNAL(Changed (VcfGantt*)) , this ,SLOT (GanttChanged(VcfGantt*))) ; nConnect ( Gantt,SIGNAL(Updated (VcfGantt*)) , this ,SLOT (GanttUpdated(VcfGantt*))) ; nConnect ( Gantt,SIGNAL(Edit (VcfGantt*,int)) , this ,SLOT (GanttEdit(VcfGantt*,int)) ) ; emit Append ( Gantt , this ) ; ArrangeItems ( ) ; DoProcessEvents ; Gantt -> MountEditor ( ) ; } void N::VcfScheduler::DateTimeFinished(void) { QDateTimeEdit * dte = NULL ; dte = qobject_cast<QDateTimeEdit *>(Widgets[99]) ; if (NotNull(dte)) { MidDay = dte->dateTime() ; } ; DeleteGadgets ( ) ; int dt = TimeBar->Start.secsTo(TimeBar->Final) ; dt /= 2 ; TimeBar->Start = MidDay ; TimeBar->Start = TimeBar->Start.addSecs(-dt) ; TimeBar->Final = MidDay ; TimeBar->Final = TimeBar->Final.addSecs( dt) ; if (NotNull(Section)) { Section->Start = TimeBar->Start ; Section->Final = TimeBar->Final ; Section->update ( ) ; } ; UpdateItems() ; emit RegionUpdated ( ) ; Alert ( Done ) ; } void N::VcfScheduler::UpdateItems(void) { if (IsNull(TimeBar)) return ; if (IsNull(Section)) return ; if (!Mutex.tryLock(100)) return ; setCursor ( Qt::WaitCursor ) ; ///////////////////////////////////////////////////////// QList<VcfGantt *> OldGantts = Gantts ; Gantts . clear ( ) ; for (int i=0;i<OldGantts.count();i++) { emit RemoveItem(OldGantts[i]) ; } ; ///////////////////////////////////////////////////////// EventManager EM ( plan ) ; SqlConnection SC ( plan->sql ) ; if (SC.open("VcfScheduler","UpdateItems")) { QString Q ; UUIDs Uuids ; SUID uuid ; Uuids = EM.Events(SC,TimeBar->Start,TimeBar->Final) ; Font F1 = Section -> Painter . fonts [ 0 ] ; Font F2 = Section -> Painter . fonts [ 1 ] ; foreach (uuid,Uuids) { Q = SC.sql.SelectFrom ( "owner,type,status,adjust,start,final" , PlanTable(EventHistory) , SC.WhereUuid(uuid) ) ; if (SC.Fetch(Q)) { QDateTime S = EM.toDateTime(SC.Tuid(4) ) ; QDateTime F = EM.toDateTime(SC.Tuid(5) ) ; if (contains(S,F)) { VcfGantt * Gantt ; Gantt = new VcfGantt(GraphicsView(),this,plan) ; Gantt -> Uuid = uuid ; Gantt -> Task = 0 ; Gantt -> Owner = SC.Uuid(0) ; Gantt -> EventType = SC.Int (1) ; Gantt -> Status = SC.Int (2) ; Gantt -> Adjust = SC.Int (3) ; Gantt -> Painter.fonts [0] = F1 ; Gantt -> Painter.fonts [1] = F2 ; Gantt -> plan = plan ; Gantt -> Options = Options ; Gantt -> Start = EM.toDateTime(SC.Tuid(4)) ; Gantt -> Final = EM.toDateTime(SC.Tuid(5)) ; Gantt -> TabletStart = TimeBar->Start ; Gantt -> TabletFinal = TimeBar->Final ; Gantt -> Note = SC.getName ( PlanTable(EventNotes) , "uuid",vLanguageId,uuid ) ; Gantt -> setZValue ( 0.50f ) ; Gantt -> setOpacity ( 1.00f ) ; Gantt -> setPos (QPointF(0,2.00) ) ; Gantt -> setRect (QRectF(0,0,0.01,0.75) ) ; Gantt -> Content = EM . Name ( SC , uuid ) ; Gantt -> DropChanged( ) ; Gantts << Gantt ; connect(Gantt,SIGNAL(Changed (VcfGantt*)) , this ,SLOT (GanttChanged(VcfGantt*))) ; connect(Gantt,SIGNAL(Updated (VcfGantt*)) , this ,SLOT (GanttUpdated(VcfGantt*))) ; connect(Gantt,SIGNAL(Edit (VcfGantt*,int)) , this ,SLOT (GanttEdit(VcfGantt*,int))) ; } ; } ; } ; SC.close ( ) ; } ; SC.remove ( ) ; setCursor ( Qt::ArrowCursor ) ; Mutex . unlock ( ) ; for (int i=0;i<Gantts.count();i++) { VcfGantt * Gantt = Gantts [ i ] ; emit Append ( Gantt , this ) ; } ; ///////////////////////////////////////////////////////// DoProcessEvents ; ArrangeItems ( ) ; } void N::VcfScheduler::ArrangeItems(void) { if (IsNull(TimeBar) ) return ; if (IsNull(Section) ) return ; if (Gantts.count()<=0 ) return ; if (!Mutex.tryLock(500)) return ; QPainterPath Path ; for (int i=0;i<Gantts.count();i++) { VcfGantt * Gantt = Gantts[i] ; QDateTime S = Gantt->Start ; QDateTime F = Gantt->Final ; if (TimeBar->Start>S) { S = TimeBar->Start ; } ; if (TimeBar->Final<F) { F = TimeBar->Final ; } ; double x1 = Section->X(S) ; double x2 = Section->X(F) ; double dx = x2 - x1 ; double dy = 2.00 ; QPointF dw ( dx , 0 ) ; QPointF dp ( x1 , 0 ) ; QPointF yh ( 0 , dy ) ; QRectF ss = ScreenRect ; dw = Options->Standard(dw) ; dp = Options->Standard(dp) ; yh = Options->Standard(yh) ; ss.setTop (yh.y() ) ; ss.setBottom(ScreenRect.bottom()) ; QPainterPath B ; do { QPainterPath path ; QPointF ds(dp.x(),dy ) ; QRectF dr(0,0,dw.x(),0.75 ) ; Gantt -> setPos ( ds ) ; Gantt -> setRect ( dr ) ; Gantt -> Available = mapToItem(Gantt,ss).boundingRect() ; Gantt -> update ( ) ; DoProcessEvents ; path = Gantt->shape() ; B = mapFromItem(Gantt,path) ; dy += 1.0 ; } while (Path.intersects(B)) ; Path . addPath ( B ) ; } ; for (int i=0;i<Gantts.count();i++) { Gantts [ i ] -> GanttUpdated ( ) ; Gantts [ i ] -> DropChanged ( ) ; } ; Mutex . unlock ( ) ; update ( ) ; } void N::VcfScheduler::GoToNow(void) { QTime T(12,0,0,0) ; //////////////////////////////////////////////// QDateTime CC = QDateTime::currentDateTime() ; QTime TT = CC . time ( ) ; if (TT.hour()< 6) T . setHMS ( 6,0,0) ; else if (TT.hour()>18) T . setHMS (18,0,0) ; MidDay = CC ; MidDay . setTime ( T ) ; DeleteGadgets ( ) ; int dt = TimeBar->Start.secsTo(TimeBar->Final) ; dt /= 2 ; TimeBar->Start = MidDay ; TimeBar->Start = TimeBar->Start.addSecs(-dt) ; TimeBar->Final = MidDay ; TimeBar->Final = TimeBar->Final.addSecs( dt) ; if (NotNull(Section)) { Section->Start = TimeBar->Start ; Section->Final = TimeBar->Final ; Section->update ( ) ; } ; UpdateItems() ; emit RegionUpdated ( ) ; Alert ( Done ) ; } void N::VcfScheduler::GoToTime(void) { QDateTimeEdit * dte = new QDateTimeEdit ( ) ; QGraphicsProxyWidget * proxy = new QGraphicsProxyWidget (this) ; proxy -> setFlag ( ItemAcceptsInputMethod , true ) ; proxy -> setWidget ( dte ) ; Proxys [ 99 ] = proxy ; Widgets [ 99 ] = dte ; dte -> setDateTime ( MidDay ) ; Font F1 = Section -> Painter.fonts[0] ; F1 . setDPI ( Options->DPI ) ; dte -> setFont ( F1 ) ; QRectF SR = Section -> ScreenRect ; QPointF CR = SR . center ( ) ; QPointF GR ( 5.60 , 0.60 ) ; CR = mapFromItem ( Section , CR ) ; GR = Options -> position( GR ) ; QRectF DR(CR.x()-(GR.x()/2),CR.y()-(GR.y()/2),GR.x(),GR.y()) ; proxy -> setGeometry ( DR ) ; proxy -> setZValue ( 1.00 ) ; proxy -> setOpacity ( 1.00 ) ; connect(dte ,SIGNAL(editingFinished ()) , this,SLOT (DateTimeFinished()) ) ; dte -> setFocus ( Qt::TabFocusReason ) ; } void N::VcfScheduler::GanttChanged(VcfGantt * gantt) { UpdateGantt ( gantt ) ; ArrangeItems ( ) ; } void N::VcfScheduler::GanttUpdated(VcfGantt * gantt) { update ( ) ; } bool N::VcfScheduler::UpdateGantt(VcfGantt * gantt) { EventManager EM ( plan ) ; EnterSQL ( SC , plan->sql ) ; //////////////////////////////////////////////// QString Q ; QDateTime CC = QDateTime::currentDateTime() ; StarDate ST ; StarDate FT ; if (gantt->Uuid<=0) { gantt->Uuid = EM . AssureUuid ( SC ) ; } ; EM.UpdateType ( SC , PlanTable(EventHistory) , gantt->Uuid,gantt->EventType ) ; //////////////////////////////////////////////// if (CC>gantt->Final) { EM.Delete(SC,gantt->Uuid) ; } else { EM.AssureEvent ( SC , gantt->Uuid , gantt->EventType ) ; EM.UpdateType ( SC , PlanTable(Events) , gantt->Uuid,gantt->EventType ) ; } ; //////////////////////////////////////////////// EM . assureName ( SC , gantt -> Uuid , plan -> LanguageId , gantt -> Content ) ; ST = gantt->Start ; FT = gantt->Final ; EM.UpdateEvent ( SC,gantt->Uuid , Calendars::Duration , ST.Stardate,FT.Stardate ) ; EM.attachSpot ( SC,gantt->Uuid , History::WorkingPeriod , ST.Stardate,FT.Stardate ) ; //////////////////////////////////////////////// if (CC>gantt->Final) { EM . DeleteScheduling ( SC , gantt->Uuid ) ; } else { EM . AddScheduling ( SC , gantt->Uuid ) ; } ; //////////////////////////////////////////////// LeaveSQL ( SC , plan->sql ) ; gantt -> DropChanged ( ) ; emit ItemUpdate ( gantt->Uuid ) ; Alert ( Done ) ; update ( ) ; return true ; } void N::VcfScheduler::DeleteGantt(VcfGantt * gantt) { } void N::VcfScheduler::ItemFinished(VcfItem * item) { emit RemoveItem ( item ) ; } void N::VcfScheduler::AttachNote(VcfGantt * gantt) { QPointF GC = gantt->ScreenRect.topLeft() ; VcfInterface * vine = NULL ; GanttNote * note = NULL ; vine = new VcfInterface ( GraphicsView() , this , plan ) ; note = new GanttNote ( NULL , plan ) ; QRect RN = note->geometry() ; QRect RF( 0, 0,RN.width()+8,RN.height()+36) ; QRect RC( 4,32,RN.width() ,RN.height() ) ; QRect RH( 4, 4,RN.width() , 24) ; GC = mapFromItem(gantt,GC) ; GC = Options->Standard(GC) ; QPointF GP (GC.x(),GC.y()+3.0) ; vine -> plan = plan ; vine -> Scaling = false ; vine -> showHeader = true ; vine -> Title = note->windowTitle() ; vine -> setOptions ( *Options , true ) ; vine -> setZValue ( 1.00f ) ; vine -> setWidget ( note , GP , RF , RC ) ; vine -> HeaderRect = RH ; emit Append ( vine , this ) ; note -> setGantt ( gantt->Uuid , gantt->Content ) ; nConnect ( vine , SIGNAL(Finish (VcfItem*)) , this , SLOT (ItemFinished(VcfItem*)) ) ; nConnect ( note , SIGNAL(Finish()) , vine , SLOT (Finish()) ) ; } void N::VcfScheduler::EditGantt(VcfGantt * gantt) { switch ( gantt->EventType ) { case N::Notify : break ; case N::Period : break ; case N::Record : break ; case N::Meeting : break ; case N::Automation : break ; case N::Operation : break ; case N::Sync : break ; case N::Download : break ; case N::Upload : break ; case N::Audio : break ; case N::Video : break ; case N::TV : break ; case N::Programming : break ; case N::Backup : break ; case N::FileUpdate : break ; case N::Cooking : break ; case N::Sleep : break ; case N::Housework : break ; case N::Shopping : break ; case N::Communication : break ; default : break ; } ; } void N::VcfScheduler::GanttTime(VcfGantt * gantt) { QPointF GC = gantt->ScreenRect.topLeft() ; VcfInterface * vine = NULL ; GanttDuration * Dura = NULL ; vine = new VcfInterface ( GraphicsView() , this , plan ) ; Dura = new GanttDuration ( NULL , plan ) ; QRect RN = Dura->geometry() ; QRect RF( 0, 0,RN.width()+8,RN.height()+36) ; QRect RC( 4,32,RN.width() ,RN.height() ) ; QRectF RH( 4, 4,RN.width() , 24) ; GC = mapFromItem(gantt,GC) ; GC = Options->Standard(GC) ; QPointF GP (GC.x(),GC.y()+3.0) ; vine -> Scaling = false ; vine -> showHeader = true ; vine -> Title = Dura->windowTitle() ; vine -> setOptions ( *Options , true ) ; vine -> setZValue ( 1.00f ) ; vine -> setWidget ( Dura , GP , RF , RC ) ; vine -> HeaderRect = RH ; emit Append ( vine , this ) ; Dura -> Gantt = gantt ; connect(vine,SIGNAL(Finish (VcfItem*)) , this,SLOT (ItemFinished(VcfItem*)) ) ; connect(Dura,SIGNAL(Finish()) , vine,SLOT (Finish()) ) ; connect(Dura ,SIGNAL(GanttChanged(VcfGantt*)) , this ,SLOT (GanttChanged(VcfGantt*)) ) ; Dura -> Prepare ( ) ; } void N::VcfScheduler::GanttTriggers(VcfGantt * gantt) { QPointF GC = gantt->ScreenRect.topLeft() ; VcfInterface * vine = NULL ; N::GanttTriggers * Trig = NULL ; vine = new VcfInterface (GraphicsView(),this,plan) ; Trig = new N::GanttTriggers ( NULL , plan ) ; QRect RN = Trig->geometry() ; QRect RF( 0, 0,RN.width()+8,RN.height()+36) ; QRect RC( 4,32,RN.width() ,RN.height() ) ; QRect RH( 4, 4,RN.width() , 24) ; GC = mapFromItem(gantt,GC) ; GC = Options->Standard(GC) ; QPointF GP (GC.x(),GC.y()+3.0) ; vine -> Scaling = false ; vine -> showHeader = true ; vine -> Title = Trig->windowTitle() ; vine -> setOptions ( *Options , true ) ; vine -> setZValue ( 1.00f ) ; vine -> setWidget ( Trig , GP , RF , RC ) ; vine -> HeaderRect = RH ; emit Append ( vine , this ) ; Trig -> Gantt = gantt ; connect(vine,SIGNAL(Finish (VcfItem*)) , this,SLOT (ItemFinished(VcfItem*)) ) ; connect(Trig,SIGNAL(Finish()) , vine,SLOT (Finish()) ) ; connect(Trig ,SIGNAL(GanttChanged(VcfGantt*)) , this ,SLOT (GanttChanged(VcfGantt*)) ) ; Trig -> Prepare ( ) ; } void N::VcfScheduler::GanttEdit(VcfGantt * gantt,int Id) { switch (Id) { case 101 : // Edit EditGantt ( gantt ) ; break ; case 102 : // Set start time case 103 : // Set finish time GanttTime ( gantt ) ; break ; case 104 : // Delete DeleteGantt ( gantt ) ; break ; case 105 : // Job start now gantt->Start = QDateTime::currentDateTime() ; if (gantt->Final<gantt->Start) { QDateTime GS = gantt->Start ; GS = GS.addSecs(60*30) ; gantt->Final = GS ; } ; UpdateGantt ( gantt ) ; ArrangeItems ( ) ; break ; case 106 : // Job finished gantt->Final = QDateTime::currentDateTime() ; UpdateGantt ( gantt ) ; ArrangeItems ( ) ; break ; case 901 : // Owner break ; case 902 : // Task break ; case 903 : // Note AttachNote ( gantt ) ; break ; case 904 : // Set start trigger case 905 : // Set finish trigger GanttTriggers ( gantt ) ; break ; } ; } void N::VcfScheduler::MountAudios(void) { /////////////////////////////////////////////////// // Start position // /////////////////////////////////////////////////// QPointF PS(8.5,4.0) ; QPointF RX = ScreenRect.topRight() ; QPointF SS ; PS = Options->position(PS) ; PS . setX ( RX . x ( ) - PS . x ( ) ) ; PS . setY ( RX . y ( ) + PS . y ( ) ) ; SS = PS ; PS = Options->Standard(PS) ; /////////////////////////////////////////////////// // Regions // /////////////////////////////////////////////////// QRect RF ( 0 , 0 , 1 , 1 ) ; QRect RC ( 4 , 32 , 1 , 1 ) ; QRect RH ( 4 , 4 , 1 , 24 ) ; QRect RR ; QRectF MS ( SS.x() , SS.y() , 0 , 0 ) ; QPolygon PR ; MS . setRight ( ScreenRect . right ( ) - 40 ) ; MS . setBottom ( ScreenRect . bottom ( ) - 40 ) ; MS = mapToScene ( MS ) . boundingRect ( ) ; PR = GraphicsView() -> mapFromScene ( MS ) ; RR = PR . boundingRect ( ) ; RF . setWidth ( RR . width ( ) ) ; RF . setHeight ( RR . height ( ) ) ; RC . setWidth ( RR . width ( ) - 8 ) ; RC . setHeight ( RR . height ( ) - 36 ) ; RH . setWidth ( RR . width ( ) - 8 ) ; /////////////////////////////////////////////////// VcfInterface * vine = NULL ; N::AudioLists * alsw = NULL ; vine = new VcfInterface(GraphicsView(),this,plan) ; alsw = new N::AudioLists ( NULL , plan ) ; /////////////////////////////////////////////////// vine -> showHeader = true ; vine -> Title = alsw -> windowTitle () ; vine -> setOptions ( *Options , true ) ; vine -> setZValue ( 1.00f ) ; vine -> setOpacity ( 1.00f ) ; vine -> setWidget ( alsw , PS , RF , RC ) ; vine -> HeaderRect = RH ; emit Append ( vine , this ) ; alsw -> List ( ) ; connect(vine,SIGNAL(Finish (VcfItem*)) , this,SLOT (ItemFinished(VcfItem*)) ) ; connect(alsw,SIGNAL(Finish()) , vine,SLOT (Finish()) ) ; } void N::VcfScheduler::MountTriggers(void) { /////////////////////////////////////////////////// // Start position // /////////////////////////////////////////////////// QPointF PS(8.5,4.0) ; QPointF RX = ScreenRect.topRight() ; QPointF SS ; PS = Options->position(PS) ; PS . setX ( RX . x ( ) - PS . x ( ) ) ; PS . setY ( RX . y ( ) + PS . y ( ) ) ; SS = PS ; PS = Options->Standard(PS) ; /////////////////////////////////////////////////// // Regions // /////////////////////////////////////////////////// QRect RF ( 0 , 0 , 1 , 1 ) ; QRect RC ( 4 , 32 , 1 , 1 ) ; QRect RH ( 4 , 4 , 1 , 24 ) ; QRect RR ; QRectF MS ( SS.x() , SS.y() , 0 , 0 ) ; QPolygon PR ; MS . setRight ( ScreenRect . right ( ) - 40 ) ; MS . setBottom ( ScreenRect . bottom ( ) - 40 ) ; MS = mapToScene ( MS ) . boundingRect ( ) ; PR = GraphicsView() -> mapFromScene ( MS ) ; RR = PR . boundingRect ( ) ; RF . setWidth ( RR . width ( ) ) ; RF . setHeight ( RR . height ( ) ) ; RC . setWidth ( RR . width ( ) - 8 ) ; RC . setHeight ( RR . height ( ) - 36 ) ; RH . setWidth ( RR . width ( ) - 8 ) ; /////////////////////////////////////////////////// VcfInterface * vine = NULL ; N::TriggerEditor * nte = NULL ; vine = new VcfInterface(GraphicsView(),this,plan) ; nte = new N::TriggerEditor ( NULL , plan ) ; /////////////////////////////////////////////////// vine -> showHeader = true ; vine -> Title = nte -> windowTitle () ; vine -> setOptions ( *Options , true ) ; vine -> setZValue ( 1.00f ) ; vine -> setOpacity ( 1.00f ) ; vine -> setWidget ( nte , PS , RF , RC ) ; vine -> HeaderRect = RH ; emit Append ( vine , this ) ; connect(nte ,SIGNAL(Clicked (SUID)) , this ,SLOT (Trigger (SUID))) ; nte -> List ( ) ; nConnect ( vine , SIGNAL(Finish (VcfItem*)) , this , SLOT (ItemFinished(VcfItem*))) ; } void N::VcfScheduler::Trigger(SUID uuid) { /////////////////////////////////////////////////// // Start position // /////////////////////////////////////////////////// QPointF PS(12.0,12.0) ; QPointF PW ; QPointF RX = ScreenRect.center() ; QPointF SS ; PS = Options->position(PS) ; PW = PS ; PS . setX ( RX . x ( ) - (PS . x ( ) / 2) ) ; PS . setY ( RX . y ( ) - (PS . y ( ) / 2) ) ; SS = PS ; PS = Options->Standard(PS) ; /////////////////////////////////////////////////// // Regions // /////////////////////////////////////////////////// QRect RF ( 0 , 0 , 1 , 1 ) ; QRect RC ( 4 , 32 , 1 , 1 ) ; QRect RH ( 4 , 4 , 1 , 24 ) ; QRect RR ; QRectF MS ( PS.x() , PS.y() , 0 , 0 ) ; QPolygon PR ; MS . setWidth ( PW.x() ) ; MS . setHeight ( PW.y() ) ; MS = mapToScene ( MS ) . boundingRect ( ) ; PR = GraphicsView() -> mapFromScene ( MS ) ; RR = PR . boundingRect ( ) ; RF . setWidth ( RR . width ( ) ) ; RF . setHeight ( RR . height ( ) ) ; RC . setWidth ( RR . width ( ) - 8 ) ; RC . setHeight ( RR . height ( ) - 36 ) ; RH . setWidth ( RR . width ( ) - 8 ) ; /////////////////////////////////////////////////// VcfInterface * vine = NULL ; N::TriggerProperty * ntp = NULL ; vine = new VcfInterface(GraphicsView(),this,plan) ; ntp = new N::TriggerProperty ( NULL , plan ) ; /////////////////////////////////////////////////// vine -> showHeader = true ; vine -> Title = ntp -> windowTitle () ; vine -> setOptions ( *Options , true ) ; vine -> setZValue ( 1.00f ) ; vine -> setOpacity ( 1.00f ) ; vine -> setWidget ( ntp , PS , RF , RC ) ; vine -> HeaderRect = RH ; emit Append ( vine , this ) ; ntp -> load (uuid) ; nConnect ( vine , SIGNAL(Finish (VcfItem*)) , this , SLOT (ItemFinished(VcfItem*))) ; nConnect ( ntp , SIGNAL(Closed()) , vine , SLOT (Finish()) ) ; } bool N::VcfScheduler::dropText(QWidget * source,QPointF pos,const QString & text) { return false ; } bool N::VcfScheduler::dropUrls(QWidget * source,QPointF pos,const QList<QUrl> & urls) { return false ; } bool N::VcfScheduler::dropHtml(QWidget * source,QPointF pos,const QString & html) { return false ; } bool N::VcfScheduler::dropColor(QWidget * source,QPointF pos,const QColor & color) { return false ; } bool N::VcfScheduler::dropTags(QWidget * source,QPointF pos,const UUIDs & Uuids) { return false ; } bool N::VcfScheduler::dropPictures(QWidget * source,QPointF pos,const UUIDs & Uuids) { return false ; } bool N::VcfScheduler::dropPeople(QWidget * source,QPointF pos,const UUIDs & Uuids) { return false ; } bool N::VcfScheduler::dropVideos(QWidget * source,QPointF pos,const UUIDs & Uuids) { return false ; } bool N::VcfScheduler::dropAlbums(QWidget * source,QPointF pos,const UUIDs & Uuids) { return false ; } bool N::VcfScheduler::dropURIs(QWidget * source,QPointF pos,const UUIDs & Uuids) { return false ; } bool N::VcfScheduler::dropBookmarks(QWidget * source,QPointF pos,const UUIDs & Uuids) { return false ; } bool N::VcfScheduler::dropFont(QWidget * source,QPointF pos,const SUID font) { return false ; } bool N::VcfScheduler::dropPen(QWidget * source,QPointF pos,const SUID pen) { return false ; } bool N::VcfScheduler::dropBrush(QWidget * source,QPointF pos,const SUID brush) { return false ; } bool N::VcfScheduler::dropGradient(QWidget * source,QPointF pos,const SUID gradient) { return false ; } bool N::VcfScheduler::ScheduleMenu(QPointF) { VcfScopedMenu ( mm ) ; QMenu * ma ; QMenu * mt ; QAction * aa ; ma = mm.addMenu(tr("Adjustments")) ; mt = mm.addMenu(tr("Tools" )) ; mm.add(ma,101,tr("Show current duration")) ; mm.add(ma,102,tr("Go to specific time" )) ; mm.add(ma,103,tr("Refresh" )) ; mm.add(mt,201,tr("Trigger lists" )) ; mm.add(mt,202,tr("Audio lists" )) ; mm.setFont(plan) ; aa = mm.exec(QCursor::pos()) ; if (IsNull(aa)) return false ; switch (mm[aa]) { case 101 : GoToNow ( ) ; break ; case 102 : GoToTime ( ) ; break ; case 103 : emit Zoom ( ) ; break ; case 201 : MountTriggers ( ) ; break ; case 202 : MountAudios ( ) ; break ; } ; return true ; } void N::VcfScheduler::run(int Type,ThreadData * data) { Q_UNUSED ( Type ) ; Q_UNUSED ( data ) ; }
45.856473
85
0.336804
Vladimir-Lin
af443f51991c44be47cd78d86d492fb86c26470a
1,698
cpp
C++
test/posix/start.cpp
malachi-iot/ATCommander
a261ca2f62e3ae2a224b43127cb846413555a01b
[ "MIT" ]
6
2017-07-08T07:50:16.000Z
2021-01-24T00:08:57.000Z
test/posix/start.cpp
malachi-iot/ATCommander
a261ca2f62e3ae2a224b43127cb846413555a01b
[ "MIT" ]
null
null
null
test/posix/start.cpp
malachi-iot/ATCommander
a261ca2f62e3ae2a224b43127cb846413555a01b
[ "MIT" ]
5
2017-04-05T06:15:14.000Z
2021-01-24T22:45:26.000Z
#include "catch.hpp" #include <atcommander.h> //int fakeStream = 0; //ATCommander<int> atc(fakeStream, fakeStream); /* template <class ...TRef> ATCommander::command_helper2(TRef...dummy) -> ATCommander::command_helper2<dummy...>; */ struct FakeCommand { static constexpr char CMD = 'V'; }; static void fake_request_suffix(ATCommander& atc, int value) { } template <class ...TArgs> void _deducer(void (*_func)(ATCommander&, TArgs...)) { } /* template <class ...TArgs> //auto typename ATCommander::command_helper2<FakeCommand, TArgs...> deducer(void (*_func)(ATCommander&, TArgs...)) //-> //decltype(ATCommander::command_helper2<FakeCommand, TArgs...>::template helper3<_func>) //decltype(declval(ATCommander::command_helper2<FakeCommand, TArgs...>)) { typedef typename ATCommander::command_helper2<FakeCommand, TArgs...> temp1; //typedef typename temp1::template helper3<_func> temp2; //::helper3<_func> temp; temp1 temp2; //return (temp1*) nullptr; //return declval(ATCommander::command_helper2<FakeCommand, TArgs...>); } */ TEST_CASE( "Make sure catch.hpp is running", "[meta]" ) { REQUIRE(1 == 1); ATCommander atc(fstd::cin, fstd::cout); /* //_deducer(fake_request_suffix); auto value = deducer(fake_request_suffix); //value->helper3<fake_request_suffix>::request(atc, 5); typedef decltype(value) test2; decltype(value)::helper3<fake_request_suffix>::request(atc, 5); //test2::request(atc, 5); //decltype(deducer(fake_request_suffix)) deduced; ATCommander::command_helper2<FakeCommand, int>::helper3<fake_request_suffix>::request(atc, 3); */ //ATCommander::command_helper2 val(1, 2, 3); }
26.952381
101
0.690224
malachi-iot
af4a847f640ad035e2c633531416c6660b1e3902
470
hpp
C++
esp32m/include/esp32m/log/uart.hpp
esp32m/core
94181c07634c09981e1775886dc49fa6fb703357
[ "MIT" ]
2
2021-08-04T15:40:13.000Z
2021-09-27T08:13:33.000Z
esp32m/include/esp32m/log/uart.hpp
esp32m/core
94181c07634c09981e1775886dc49fa6fb703357
[ "MIT" ]
null
null
null
esp32m/include/esp32m/log/uart.hpp
esp32m/core
94181c07634c09981e1775886dc49fa6fb703357
[ "MIT" ]
null
null
null
#ifdef ARDUINO # pragma once # include "esp32m/logging.hpp" namespace esp32m { namespace log { /** * Sends output to the specified UART */ class Uart : public FormattingAppender { public: Uart(const Uart &) = delete; Uart(uint8_t num = 0); private: uint32_t _portBase; protected: virtual bool append(const char *message); }; } // namespace log } // namespace esp32m #endif
18.8
48
0.578723
esp32m
af4b4147177aa78bb3b3323ee5223607970b5a7b
1,775
cpp
C++
lib/Parser/DefaultParser.cpp
scross99/locic
a24bb380e17f8af69e7389acf8ce354c91a2abf3
[ "MIT" ]
80
2015-02-19T21:38:57.000Z
2016-05-25T06:53:12.000Z
lib/Parser/DefaultParser.cpp
scross99/locic
a24bb380e17f8af69e7389acf8ce354c91a2abf3
[ "MIT" ]
8
2015-02-20T09:47:20.000Z
2015-11-13T07:49:17.000Z
lib/Parser/DefaultParser.cpp
scross99/locic
a24bb380e17f8af69e7389acf8ce354c91a2abf3
[ "MIT" ]
6
2015-02-20T11:26:19.000Z
2016-04-13T14:30:39.000Z
#include <cassert> #include <cstdio> #include <cstdlib> #include <string> #include <locic/Frontend/DiagnosticReceiver.hpp> #include <locic/Parser/DefaultParser.hpp> #include <locic/Parser/NamespaceParser.hpp> #include <locic/Parser/TokenReader.hpp> #include <locic/Support/ErrorHandling.hpp> #include <locic/Support/StringHost.hpp> #include "LexLexer.hpp" namespace locic { namespace Parser { class DefaultParserImpl { public: DefaultParserImpl(const StringHost& stringHost, AST::NamespaceList& argRootNamespaceList, FILE * file, const std::string& fileName, DiagnosticReceiver& argDiagReceiver) : rootNamespaceList_(argRootNamespaceList), lexer_(file, String(stringHost, fileName), argDiagReceiver), diagReceiver_(argDiagReceiver) { } AST::NamespaceList& rootNamespaceList() { return rootNamespaceList_; } LexLexer& lexer() { return lexer_; } DiagnosticReceiver& diagReceiver() { return diagReceiver_; } private: AST::NamespaceList& rootNamespaceList_; LexLexer lexer_; DiagnosticReceiver& diagReceiver_; }; DefaultParser::DefaultParser(const StringHost& stringHost, AST::NamespaceList& rootNamespaceList, FILE * file, const std::string& fileName, DiagnosticReceiver& diagReceiver) : impl_(new DefaultParserImpl(stringHost, rootNamespaceList, file, fileName, diagReceiver)) { } DefaultParser::~DefaultParser() { } void DefaultParser::parseFile() { TokenReader reader(impl_->lexer().getLexer(), impl_->diagReceiver()); auto namespaceDecl = NamespaceParser(reader).parseGlobalNamespace(); impl_->rootNamespaceList().push_back(std::move(namespaceDecl)); } } }
27.734375
106
0.701408
scross99
af4cfd01136e6e5f14abf06614bbf5cee9453eaf
5,331
cc
C++
oss-internship-2020/libtiff/wrapper/func.cc
oshogbo/sandboxed-api
8e82b900f4d873219b3abfa2fd06ecbd416edefd
[ "Apache-2.0" ]
1
2022-02-10T10:38:30.000Z
2022-02-10T10:38:30.000Z
oss-internship-2020/libtiff/wrapper/func.cc
oshogbo/sandboxed-api
8e82b900f4d873219b3abfa2fd06ecbd416edefd
[ "Apache-2.0" ]
null
null
null
oss-internship-2020/libtiff/wrapper/func.cc
oshogbo/sandboxed-api
8e82b900f4d873219b3abfa2fd06ecbd416edefd
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 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. #include "func.h" // NOLINT(build/include) int TIFFGetField1(TIFF* tif, uint32_t tag, void* param) { return TIFFGetField(tif, tag, param); } int TIFFGetField2(TIFF* tif, uint32_t tag, void* param1, void* param2) { return TIFFGetField(tif, tag, param1, param2); } int TIFFGetField3(TIFF* tif, uint32_t tag, void* param1, void* param2, void* param3) { return TIFFGetField(tif, tag, param1, param2, param3); } int TIFFSetFieldUChar1(TIFF* tif, uint32_t tag, uint8_t param) { return TIFFSetField(tif, tag, param); } int TIFFSetFieldUChar2(TIFF* tif, uint32_t tag, uint8_t param1, uint8_t param2) { return TIFFSetField(tif, tag, param1, param2); } int TIFFSetFieldUChar3(TIFF* tif, uint32_t tag, uint8_t param1, uint8_t param2, uint8_t param3) { return TIFFSetField(tif, tag, param1, param2, param3); } int TIFFSetFieldSChar1(TIFF* tif, uint32_t tag, int8_t param) { return TIFFSetField(tif, tag, param); } int TIFFSetFieldSChar2(TIFF* tif, uint32_t tag, int8_t param1, int8_t param2) { return TIFFSetField(tif, tag, param1, param2); } int TIFFSetFieldSChar3(TIFF* tif, uint32_t tag, int8_t param1, int8_t param2, int8_t param3) { return TIFFSetField(tif, tag, param1, param2, param3); } int TIFFSetFieldU1(TIFF* tif, uint32_t tag, uint32_t param) { return TIFFSetField(tif, tag, param); } int TIFFSetFieldU2(TIFF* tif, uint32_t tag, uint32_t param1, uint32_t param2) { return TIFFSetField(tif, tag, param1, param2); } int TIFFSetFieldU3(TIFF* tif, uint32_t tag, uint32_t param1, uint32_t param2, uint32_t param3) { return TIFFSetField(tif, tag, param1, param2, param3); } int TIFFSetFieldS1(TIFF* tif, uint32_t tag, int param) { return TIFFSetField(tif, tag, param); } int TIFFSetFieldS2(TIFF* tif, uint32_t tag, int param1, int param2) { return TIFFSetField(tif, tag, param1, param2); } int TIFFSetFieldS3(TIFF* tif, uint32_t tag, int param1, int param2, int param3) { return TIFFSetField(tif, tag, param1, param2, param3); } int TIFFSetFieldUShort1(TIFF* tif, uint32_t tag, uint16_t param) { return TIFFSetField(tif, tag, param); } int TIFFSetFieldUShort2(TIFF* tif, uint32_t tag, uint16_t param1, uint16_t param2) { return TIFFSetField(tif, tag, param1, param2); } int TIFFSetFieldUShort3(TIFF* tif, uint32_t tag, uint16_t param1, uint16_t param2, uint16_t param3) { return TIFFSetField(tif, tag, param1, param2, param3); } int TIFFSetFieldSShort1(TIFF* tif, uint32_t tag, int16_t param) { return TIFFSetField(tif, tag, param); } int TIFFSetFieldSShort2(TIFF* tif, uint32_t tag, int16_t param1, int16_t param2) { return TIFFSetField(tif, tag, param1, param2); } int TIFFSetFieldSShort3(TIFF* tif, uint32_t tag, int16_t param1, int16_t param2, int16_t param3) { return TIFFSetField(tif, tag, param1, param2, param3); } int TIFFSetFieldULLong1(TIFF* tif, uint32_t tag, uint64_t param) { return TIFFSetField(tif, tag, param); } int TIFFSetFieldULLong2(TIFF* tif, uint32_t tag, uint64_t param1, uint64_t param2) { return TIFFSetField(tif, tag, param1, param2); } int TIFFSetFieldULLong3(TIFF* tif, uint32_t tag, uint64_t param1, uint64_t param2, uint64_t param3) { return TIFFSetField(tif, tag, param1, param2, param3); } int TIFFSetFieldSLLong1(TIFF* tif, uint32_t tag, int64_t param) { return TIFFSetField(tif, tag, param); } int TIFFSetFieldSLLong2(TIFF* tif, uint32_t tag, int64_t param1, int64_t param2) { return TIFFSetField(tif, tag, param1, param2); } int TIFFSetFieldSLLong3(TIFF* tif, uint32_t tag, int64_t param1, int64_t param2, int64_t param3) { return TIFFSetField(tif, tag, param1, param2, param3); } int TIFFSetFieldFloat1(TIFF* tif, uint32_t tag, float param) { return TIFFSetField(tif, tag, param); } int TIFFSetFieldFloat2(TIFF* tif, uint32_t tag, float param1, float param2) { return TIFFSetField(tif, tag, param1, param2); } int TIFFSetFieldFloat3(TIFF* tif, uint32_t tag, float param1, float param2, float param3) { return TIFFSetField(tif, tag, param1, param2, param3); } int TIFFSetFieldDouble1(TIFF* tif, uint32_t tag, double param) { return TIFFSetField(tif, tag, param); } int TIFFSetFieldDouble2(TIFF* tif, uint32_t tag, double param1, double param2) { return TIFFSetField(tif, tag, param1, param2); } int TIFFSetFieldDouble3(TIFF* tif, uint32_t tag, double param1, double param2, double param3) { return TIFFSetField(tif, tag, param1, param2, param3); }
32.506098
80
0.695554
oshogbo
af4e3e483ceb39b807fb4bf217016e31b47750b0
294
cpp
C++
Practice/rodion.cpp
ashishjayamohan/competitive-programming
05c5c560c2c2eb36121c52693b8c7d084f435f9e
[ "MIT" ]
null
null
null
Practice/rodion.cpp
ashishjayamohan/competitive-programming
05c5c560c2c2eb36121c52693b8c7d084f435f9e
[ "MIT" ]
null
null
null
Practice/rodion.cpp
ashishjayamohan/competitive-programming
05c5c560c2c2eb36121c52693b8c7d084f435f9e
[ "MIT" ]
null
null
null
#include <iostream> #include<string> using namespace std; int main() { int n,d; string s; cin>>n>>d; if(d==10&&n<2)cout<<"-1"; else if(d==10&&n>=2){ for(int i=0;i<n-1;i++){ s+=1+'0'; } s+=0+'0'; cout<<s; } else{ for(int i=0;i<n;i++){ s+= d+'0'; } cout<<s;} return 0; }
12.25
26
0.493197
ashishjayamohan
af578f63f432c682abcfdf89222a303ad70bb6c8
4,394
cpp
C++
SuperRes.cpp
pl2526/PSCAcoustic
eaf127f0bd6aa9bdf4a051b4390966e86fdf6751
[ "MIT" ]
null
null
null
SuperRes.cpp
pl2526/PSCAcoustic
eaf127f0bd6aa9bdf4a051b4390966e86fdf6751
[ "MIT" ]
null
null
null
SuperRes.cpp
pl2526/PSCAcoustic
eaf127f0bd6aa9bdf4a051b4390966e86fdf6751
[ "MIT" ]
null
null
null
#ifndef SR_CPP #define SR_CPP /* * MAIN.h * PSC * * Created by Pierre-David Letourneau on 3/6/11. * Copyright 2011 Stanford University. All rights reserved. * * Overstructure. * * Copyright 2014 Pierre-David Letourneau * * 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 <vector> #include <complex> #include <iostream> #include "Coordinates.h" #include "IncWave.h" #include "Scatterer.h" #include "Distributions.h" #include "PSCEnv.h" #include "Solver.h" #include "Imaging.h" #include "Finalize.h" Indexing temp_index(LMAX); int main(int argc,char **args) { int Proc_Idx = 0; // Properties of source std::string src_type("PtW"); //double amplitude = 1; Pvec src_location(25., 30., 40.,Pvec::Cartesian); complex src_amplitude = 1.; // Properties of images double L = 1.5; // Size of window [-L,L]x[-L,L] int M = 65; // Number of samples per dimension (2*M+1) // Display relevant information concerning the problem cout << endl << endl; cout << "LMAX : " << LMAX << endl; cout << "RTOL : " << RTOL << endl; cout << "MAXITS : " << MAXITS << endl; cout << "OMEGA : " << OMEGA << endl; cout << "C_OUT : " << C_OUT << endl; cout << "C : " << C << endl; cout << "K_OUT : " << K_OUT << endl; cout << "K : " << K << endl; cout << "NScat : " << NScat << endl; cout << "RADIUS : " << RADIUS << endl; cout << "nLevels : " << nLevels << endl; cout << "EPS : " << EPS << endl; cout << endl; // PSC environment for fast algorithm PSC_Env PSC_env(nLevels, EPS); // Linear solver Solver solver; // TODO: Should not have different instances of Index Indexing Index(LMAX); // Construct scatterers cout << "***Building scatterers..." << endl; std::vector<Scatterer> ScL = ScatInit(NScat, K, K_OUT ); cout << "***Building scatterers: done" << endl << endl; // Construct PSC environment cout << "***Constructing environment..." << endl; PSC_env.Construct(K_OUT, ScL); cout << "***Constructing environment: done" << endl << endl; // *** Solve forward problem // Initialization of source // R.h.s. SphericalWave* IW = new SphericalWave(K_OUT, src_amplitude, src_location); std::vector< std::vector<complex > > RHS(NScat, std::vector<complex >(Index.size())); solver.RHSInit(IW, ScL, RHS); // Solve linear system cout << " ***Solving linear system..." << endl; std::vector< std::vector<complex> > u(NScat, std::vector<complex>(Index.size())); double res = 1e10, rel_res = 1e10, cond; solver.Solve(PSC_env, ScL, RHS, u, res, rel_res, cond); cout << " ***Solving linear system: done" << endl; // Compute solution inside scatterers std::vector<std::vector<complex> > *u_in = new std::vector<std::vector<complex> >(NScat, std::vector<complex>((LMAX+1)*(LMAX+1))); // Produce image std::string im_filename("SuperRes_Im"); Imaging(ScL, IW, im_filename, u, Proc_Idx, M, L, u_in); // Write information about problem to file cout << " ***Writing to file..." << endl; std::string filename("Super_Res_A"); Write_Info(Proc_Idx, src_type, res, rel_res, cond, filename); Write_Source(Proc_Idx, IW, IncWave::Pt, filename); Write_Location(Proc_Idx, ScL, filename); Write_Solution( Proc_Idx, Index, u, filename); cout << " ***Writing to file: done" << endl << endl; return 0; } #endif
27.810127
130
0.662039
pl2526
af67601c27ba318738849ff3e59339187e1ec42d
2,708
cpp
C++
src/ComDemo.17/MfcCli/MfcCli.cpp
jimbeveridge/multithreading
b092dde13968f91dfb9b86e3d7e760a50f799a96
[ "MIT" ]
2
2021-11-23T10:43:45.000Z
2022-01-03T14:51:32.000Z
src/ComDemo.17/MfcCli/MfcCli.cpp
jimbeveridge/multithreading
b092dde13968f91dfb9b86e3d7e760a50f799a96
[ "MIT" ]
null
null
null
src/ComDemo.17/MfcCli/MfcCli.cpp
jimbeveridge/multithreading
b092dde13968f91dfb9b86e3d7e760a50f799a96
[ "MIT" ]
1
2020-10-28T15:11:55.000Z
2020-10-28T15:11:55.000Z
/* * MfcCli.cpp * * Sample code for "Multithreading Applications in Win32" * This is from Chapter 17 * * Communicates to a FreeThreaded COM Object */ #include "stdafx.h" #include "MfcCli.h" #include "CliDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif ///////////////////////////////////////////////////////////////////////////// // CMfcCliApp BEGIN_MESSAGE_MAP(CMfcCliApp, CWinApp) //{{AFX_MSG_MAP(CMfcCliApp) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG ON_COMMAND(ID_HELP, CWinApp::OnHelp) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CMfcCliApp construction CMfcCliApp::CMfcCliApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } ///////////////////////////////////////////////////////////////////////////// // The one and only CMfcCliApp object CMfcCliApp theApp; ///////////////////////////////////////////////////////////////////////////// // CMfcCliApp initialization BOOL CMfcCliApp::InitInstance() { // Initialize OLE libraries if (!AfxOleInit()) { AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. #ifdef _AFXDLL Enable3dControls(); // Call this when using MFC in a shared DLL #else Enable3dControlsStatic(); // Call this when linking to MFC statically #endif // Parse the command line to see if launched as OLE server if (RunEmbedded() || RunAutomated()) { // Register all OLE server (factories) as running. This enables the // OLE libraries to create objects from other applications. COleTemplateServer::RegisterAll(); // Application was run with /Embedding or /Automation. Don't show the // main window in this case. return TRUE; } // When a server application is launched stand-alone, it is a good idea // to update the system registry in case it has been damaged. COleObjectFactory::UpdateRegistryAll(); CMfcCliDlg dlg; m_pMainWnd = &dlg; int nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK } else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; }
26.54902
77
0.643648
jimbeveridge
af690478fc75b49643d34dc44ef8c1196005e1d8
1,418
cpp
C++
Variables/Variables/Main.cpp
matt360/ModernCpp
42ab42447d22c9e92f3da12dcb8ac16794668879
[ "MIT" ]
null
null
null
Variables/Variables/Main.cpp
matt360/ModernCpp
42ab42447d22c9e92f3da12dcb8ac16794668879
[ "MIT" ]
16
2018-03-01T11:18:55.000Z
2018-07-01T17:17:32.000Z
Variables/Variables/Main.cpp
matzar/ModernCpp
42ab42447d22c9e92f3da12dcb8ac16794668879
[ "MIT" ]
null
null
null
// Variables // Int - integer - 4 bytes (Ultimatelly it's the compilers choice to tell you how big an integer is going to be) // 1 byte - 8 bits of data // 4 bytes - 32 bits of data // int (signed) - 1 bit is for the sign, to know if the varaible is positive or negative. That leaves 31 bits for the number. // Each bit can be eitehr 0 or 1. 2^31 = 2,147,483,648. // The maximum number we can store is 2,147,483,647 (minumum being -2,147,483,647) becasue we need to be able to store 0. // unsigned int - now we have 32 bits to store the number which gives us - 2^32 = 4,294,967,296, // so the maximum number we can store is 4,294,967,295 (we need to be able to store 0) // char - 1 byte of data (8 bits) // short - 2 bytes of data (16 bits) // int - 4 bytes of data (32 bits) // long - 4 bytes of data (usually, depending on the compiler) (32 bits) // long long - 8 bytes of data (64 bits) // float - 4 bytes (32 bits) // double - 8 bytes (64 bits) // bool - 1 byte of memory (8 bits) - true or false - 0 means false, any other number means true. It does take up only 1 bit of memory but when we are addressing memory // (we need to retrieve our bool from memory) we can only address bytes; we can't address a single bit. //CODE #include <iostream> int main() { int variable = 8; // -2b -> 2b float a = 5.5f; float b = 5.5; // that's a double std::cout << sizeof(bool) << std::endl; std::cin.get(); }
37.315789
168
0.670663
matt360
af6dc6769a5505f80d0328fdf81b5efe349da6e5
2,623
cpp
C++
tomasulo_simulator/simulator/instructions.cpp
Billijk/Tomasulo-simulator
dc2993d8129d4d01e1459671423273f9b68b4de9
[ "MIT" ]
null
null
null
tomasulo_simulator/simulator/instructions.cpp
Billijk/Tomasulo-simulator
dc2993d8129d4d01e1459671423273f9b68b4de9
[ "MIT" ]
null
null
null
tomasulo_simulator/simulator/instructions.cpp
Billijk/Tomasulo-simulator
dc2993d8129d4d01e1459671423273f9b68b4de9
[ "MIT" ]
null
null
null
#include "instructions.h" #include <vector> #include <iostream> using namespace std; int Instruction::needed_cycle(InstrType type) { switch (type) { case ADDD: case SUBD: case LD: case ST: return 2; case MULD: return 10; case DIVD: return 40; default: return -1; } } Instruction* Instruction::parse(string instr, const set<string>& valid_reg_names, int valid_memory_size) { // split size_t split_pos = instr.find(" "); if (split_pos == string::npos) return new ErrorInstruction(); string op = instr.substr(0, split_pos); vector<string> tokens; size_t new_pos; do { // ignore possible spaces while (instr[split_pos] == ' ' && split_pos < instr.size()) split_pos ++; new_pos = instr.find(",", split_pos); int len = new_pos - split_pos; while (instr[split_pos + len - 1] == ' ' && len > 0) len --; tokens.push_back(instr.substr(split_pos, len)); split_pos = new_pos + 1; } while (new_pos != string::npos); // check instrucion format if (tokens.size() == 3) { for (int i = 0; i < 3; ++ i) if (valid_reg_names.find(tokens[i]) == valid_reg_names.end()) return new ErrorInstruction(); // operands valid, check op if (op == string("ADDD")) { return new ADDDi(tokens[0], tokens[1], tokens[2]); } else if (op == string("SUBD")) { return new SUBDi(tokens[0], tokens[1], tokens[2]); } else if (op == string("MULD")) { return new MULDi(tokens[0], tokens[1], tokens[2]); } else if (op == string("DIVD")) { return new DIVDi(tokens[0], tokens[1], tokens[2]); } else return new ErrorInstruction(); } else if (tokens.size() == 2) { // first operand as register name if (valid_reg_names.find(tokens[0]) == valid_reg_names.end()) return new ErrorInstruction(); // second operand as int addr for (size_t i = 0; i < tokens[1].size(); ++ i) if (tokens[1][i] < '0' || tokens[1][i] > '9') return new ErrorInstruction(); int addr = stoi(tokens[1]); if (addr >= valid_memory_size) return new ErrorInstruction(); // operands valid, check op if (op == string("LD")) { return new LDi(tokens[0], addr); } else if (op == string("ST")) { return new STi(tokens[0], addr); } else return new ErrorInstruction(); } else return new ErrorInstruction(); }
35.445946
106
0.547083
Billijk
af6eec3ba000438cfe6cec109031e7be13e6eed1
1,242
cxx
C++
617_Merge_Two_Binary_Trees.cxx
KerouichaReda/leetcode_submission
f4a1c668fcb962e5ff92285d6bfc41b7573b9dc0
[ "MIT" ]
1
2020-12-05T06:06:28.000Z
2020-12-05T06:06:28.000Z
617_Merge_Two_Binary_Trees.cxx
KerouichaReda/leetcode_submission
f4a1c668fcb962e5ff92285d6bfc41b7573b9dc0
[ "MIT" ]
null
null
null
617_Merge_Two_Binary_Trees.cxx
KerouichaReda/leetcode_submission
f4a1c668fcb962e5ff92285d6bfc41b7573b9dc0
[ "MIT" ]
null
null
null
/* * 617_Merge_Two_Binary_Trees.cxx * * Copyright 2020 RedaKerouicha <redakerouicha@localhost> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * */ #include <iostream> TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) { if(t1 == nullptr && t2 == nullptr) return nullptr; if(t1 == nullptr || t2 == nullptr) return t1 == nullptr ? t2 : t1; TreeNode* newNode = new TreeNode( ( t1->val + t2->val), mergeTrees( t1->left, t2->left), mergeTrees( t1->right, t2->right) ); return newNode; } int main(int argc, char **argv) { return 0; }
27.6
71
0.699678
KerouichaReda
af71273c470fb287c6107f0ffa5996eb0314e441
6,365
cpp
C++
Source/RenderAPIs/VulkanAPI/VulkanCommandPoolManager.cpp
Cube219/CubeEngine
b54a7373be96333aa38fdf49ea32272c28c42a4b
[ "MIT" ]
2
2017-09-25T12:43:02.000Z
2018-04-07T06:50:13.000Z
Source/RenderAPIs/VulkanAPI/VulkanCommandPoolManager.cpp
Cube219/CubeEngine
b54a7373be96333aa38fdf49ea32272c28c42a4b
[ "MIT" ]
null
null
null
Source/RenderAPIs/VulkanAPI/VulkanCommandPoolManager.cpp
Cube219/CubeEngine
b54a7373be96333aa38fdf49ea32272c28c42a4b
[ "MIT" ]
null
null
null
#include "VulkanCommandPoolManager.h" #include "Interface/CommandListVk.h" #include "VulkanDebug.h" #include "VulkanDevice.h" #include "VulkanQueueManager.h" #include "Core/Allocator/FrameAllocator.h" #include "Core/Assertion.h" namespace cube { namespace rapi { void VulkanCommandPoolManager::Initialize(Uint32 numGraphicsPools, Uint32 numTransferPools, Uint32 numComputePools) { VkResult res; VkCommandPoolCreateInfo info; info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; info.pNext = nullptr; info.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT | VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; VulkanQueueManager& queueManager = mDevice.GetQueueManager(); VkCommandPool pool; // Graphics pool { info.queueFamilyIndex = queueManager.GetGraphicsQueueFamilyIndex(); mGraphicsPools.resize(numGraphicsPools); for(Uint32 i = 0; i < numGraphicsPools; ++i) { res = vkCreateCommandPool(mDevice.GetHandle(), &info, nullptr, &pool); CHECK_VK(res, "Failed to create a graphics command pool."); VULKAN_SET_OBJ_NAME(mDevice.GetHandle(), pool, FrameFormat("VkCommandPool for graphics[{}]", i).c_str()); mGraphicsPools[i] = pool; } } // Transfer pool { info.queueFamilyIndex = queueManager.GetTransferQueueFamilyIndex(); mTransferPools.resize(numTransferPools); for(Uint32 i = 0; i < numTransferPools; ++i) { res = vkCreateCommandPool(mDevice.GetHandle(), &info, nullptr, &pool); CHECK_VK(res, "Failed to create a transfer command pool."); VULKAN_SET_OBJ_NAME(mDevice.GetHandle(), pool, FrameFormat("VkCommandPool for transfer[{}]", i).c_str()); mTransferPools[i] = pool; } } // Compute pool { info.queueFamilyIndex = queueManager.GetComputeQueueFamilyIndex(); mComputePools.resize(numComputePools); for(Uint32 i = 0; i < numComputePools; ++i) { res = vkCreateCommandPool(mDevice.GetHandle(), &info, nullptr, &pool); CHECK_VK(res, "Failed to create a compute command pool."); VULKAN_SET_OBJ_NAME(mDevice.GetHandle(), pool, FrameFormat("VkCommandPool for compute[{}]", i).c_str()); mComputePools[i] = pool; } } } void VulkanCommandPoolManager::Shutdown() { for(auto pool : mGraphicsPools) { vkDestroyCommandPool(mDevice.GetHandle(), pool, nullptr); } for(auto pool : mTransferPools) { vkDestroyCommandPool(mDevice.GetHandle(), pool, nullptr); } for(auto pool : mComputePools) { vkDestroyCommandPool(mDevice.GetHandle(), pool, nullptr); } } SPtr<CommandListVk> VulkanCommandPoolManager::AllocateCommandList(const CommandListAllocateInfo& allocateInfo) { VulkanCommandBuffer commandBuffer = AllocateCommandBuffer(allocateInfo); return std::make_shared<CommandListVk>(mDevice, *this, allocateInfo, commandBuffer); } VulkanCommandBuffer VulkanCommandPoolManager::AllocateCommandBuffer(const CommandListAllocateInfo& allocateInfo) { VkResult res; VkCommandBufferAllocateInfo info; info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; info.pNext = nullptr; if(allocateInfo.isSub == false) { info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; } else { info.level = VK_COMMAND_BUFFER_LEVEL_SECONDARY; } info.commandBufferCount = 1; SPtr<CommandListVk> cmd; VkCommandBuffer vkCmdBuf; switch(allocateInfo.type) { case CommandListType::Graphics: info.commandPool = mGraphicsPools[allocateInfo.poolIndex]; break; case CommandListType::Transfer: info.commandPool = mTransferPools[allocateInfo.poolIndex]; break; case CommandListType::Compute: info.commandPool = mComputePools[allocateInfo.poolIndex]; break; default: ASSERTION_FAILED("Unknown CommandListType ({})", allocateInfo.type); } res = vkAllocateCommandBuffers(mDevice.GetHandle(), &info, &vkCmdBuf); CHECK_VK(res, "Failed to allocate VkCommandBuffer"); VULKAN_SET_OBJ_NAME(mDevice.GetHandle(), vkCmdBuf, allocateInfo.debugName); VulkanCommandBuffer cmdBuf; cmdBuf.handle = vkCmdBuf; cmdBuf.type = allocateInfo.type; cmdBuf.poolIndex = allocateInfo.poolIndex; return cmdBuf; } void VulkanCommandPoolManager::FreeCommandList(SPtr<CommandListVk>& commandList) { VulkanCommandBuffer commandBuffer = commandList->GetCommandBuffer(); FreeCommandBuffer(commandBuffer); } void VulkanCommandPoolManager::FreeCommandBuffer(VulkanCommandBuffer& commandBuffer) { CommandListType type = commandBuffer.type; Uint32 poolIndex = commandBuffer.poolIndex; VkCommandBuffer vkCmdBuf = commandBuffer.handle; switch(commandBuffer.type) { case CommandListType::Graphics: vkFreeCommandBuffers(mDevice.GetHandle(), mGraphicsPools[poolIndex], 1, &vkCmdBuf); break; case CommandListType::Transfer: vkFreeCommandBuffers(mDevice.GetHandle(), mTransferPools[poolIndex], 1, &vkCmdBuf); break; case CommandListType::Compute: vkFreeCommandBuffers(mDevice.GetHandle(), mComputePools[poolIndex], 1, &vkCmdBuf); break; default: ASSERTION_FAILED("Unknown CommandListType ({})", type); } commandBuffer.handle = VK_NULL_HANDLE; } } // namespace rapi } // namespace cube
40.541401
129
0.602514
Cube219
af736021af26254326b305752302bf492cb9d5a0
1,161
hpp
C++
include/mizuiro/image/access/data.hpp
cpreh/mizuiro
5ab15bde4e72e3a4978c034b8ff5700352932485
[ "BSL-1.0" ]
1
2015-08-22T04:19:39.000Z
2015-08-22T04:19:39.000Z
include/mizuiro/image/access/data.hpp
freundlich/mizuiro
5ab15bde4e72e3a4978c034b8ff5700352932485
[ "BSL-1.0" ]
null
null
null
include/mizuiro/image/access/data.hpp
freundlich/mizuiro
5ab15bde4e72e3a4978c034b8ff5700352932485
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2016. // 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 MIZUIRO_IMAGE_ACCESS_DATA_HPP_INCLUDED #define MIZUIRO_IMAGE_ACCESS_DATA_HPP_INCLUDED #include <mizuiro/image/access/data_ns/tag.hpp> #include <mizuiro/image/format/make_tag_of.hpp> #include <mizuiro/image/format/store_fwd.hpp> #include <mizuiro/image/types/pointer.hpp> #include <mizuiro/image/types/reference.hpp> namespace mizuiro::image::access { // TODO(philipp): This is only used for prepare_store and that doesn't work for planar images template <typename Access, typename Constness, typename ImageFormat> mizuiro::image::types::pointer<Access, ImageFormat, Constness> data( mizuiro::image::format::store<ImageFormat> const &_format, mizuiro::image::types::reference<Access, ImageFormat, Constness> const &_ref) { return data_adl( mizuiro::image::access::data_ns::tag(), Access(), mizuiro::image::format::make_tag_of<ImageFormat>(), Constness(), _format, _ref); } } #endif
32.25
93
0.734711
cpreh
af7b48cf46176a892f303fbcb2392c48faefb026
4,679
hpp
C++
three/core/math.hpp
Lecrapouille/three_cpp
5c3b4f4ca02bda6af232898c17e62caf8f887aa0
[ "MIT" ]
null
null
null
three/core/math.hpp
Lecrapouille/three_cpp
5c3b4f4ca02bda6af232898c17e62caf8f887aa0
[ "MIT" ]
null
null
null
three/core/math.hpp
Lecrapouille/three_cpp
5c3b4f4ca02bda6af232898c17e62caf8f887aa0
[ "MIT" ]
null
null
null
#ifndef THREE_MATH_HPP #define THREE_MATH_HPP #include <three/common.hpp> #include <cmath> #include <random> namespace three { namespace Math { inline const float PI() { return 3.1415926535897932384f; } //std::atan(1.f)/4; inline const float LN2() { return 0.6931471805599453094f; } inline const float INF() { return std::numeric_limits<float>::max(); } //std::numeric_limits<float>::infinity(); template <typename T> inline T sqrt(T t) { return std::sqrt(t); } template <typename T> inline T abs(T t) { return std::abs(t); } template <typename T> inline T acos(T t) { return std::acos(t); } template <typename T> inline T asin(T t) { return std::asin(t); } template <typename T> inline T atan2(T y, T x) { return std::atan2(y, x); } template <typename T> inline T atan(T t) { return std::atan(t); } template <typename T> inline T cos(T t) { return std::cos(t); } template <typename T> inline T sin(T t) { return std::sin(t); } template <typename T> inline T tan(T t) { return std::tan(t); } template <typename T> inline T log(T t) { return std::log(t); } template <typename T, typename U> inline T pow(T a, U b) { return std::pow(a, b); } #if defined(_MSC_VER) template <typename T> inline T round(T n) { return (n > (T)0) ? std::floor(n + (T)0.5) : std::ceil(n - (T)0.5); } #else template <typename T> inline T round(T t) { return std::round(t); } #endif template <typename T> inline T ceil(T t) { return std::ceil(t); } template <typename T> inline T floor(T t) { return std::floor(t); } template <typename T> inline T fmod(T a, T b) { return std::fmod(a, b); } template <typename T> inline T min(T a, T b) { return std::min(a, b); } template <typename T> inline T max(T a, T b) { return std::max(a, b); } template <typename T> inline T clamp(T x, T a, T b) { return x < a ? a : ((x > b) ? b : x); } template <typename T> inline T clampBottom(T x, T a) { return x < a ? a : x; } // Linear mapping from range <a1, a2> to range <b1, b2> template <typename T> inline T mapLinear(T x, T a1, T a2, T b1, T b2) { return b1 + (x - a1) * (b2 - b1) / (a2 - a1); } // MinGW crashes on std::random_device initialization #if !defined(__MINGW32__) template <typename T> inline typename std::enable_if<std::is_floating_point<T>::value, T>::type randomT(T low, T high) { static std::random_device rd; static std::mt19937 rng(rd()); std::uniform_real_distribution<T> dis(low, high); return dis(rng); } template <typename T> inline typename std::enable_if<!std::is_floating_point<T>::value, T>::type randomT(T low, T high) { static std::random_device rd; static std::mt19937 rng(rd()); std::uniform_int_distribution<T> dis(low, high); return dis(rng); } #else template <typename T> inline T randomT(T low, T high) { return (low + static_cast<double>(rand()) / ((unsigned long long)RAND_MAX + 1) * (high - low)); } #endif // !defined(__MINGW32__) inline float random(float low = 0, float high = 1) { return randomT(low, high); } // Random float from <0, 1> with 16 bits of randomness // (standard Math.random() creates repetitive patterns when applied over larger space) inline float random16() { return (65280 * random() + 255 * random()) / 65535; } // Random integer from <low, high> interval inline int randInt(int low, int high) { return low + (int)floor(random() * (high - low + 1)); } // Random float from <low, high> interval inline float randFloat(float low, float high) { return random(low, high); } // Random float from <-range/2, range/2> interval inline float randFloatSpread(float range) { return range * (0.5f - random()); } template <typename T> inline int sign(T x) { return (x < 0) ? -1 : ((x > 0) ? 1 : 0); } inline bool isPowerOfTwo(int value) { return (value != 0) && ((value & (value - 1)) == 0); } inline int upperPowerOfTwo(int value) { return (int)pow(2.f, ceil(log((float)value) / LN2())); } inline int lowerPowerOfTwo(int value) { return (int)pow(2.f, floor(log((float)value) / LN2())); } inline int nearestPowerOfTwo(int value) { return (int)pow(2.f, round(log((float)value) / LN2())); } } } // namespace three #endif // THREE_MATH_HPP
26.585227
116
0.582603
Lecrapouille
5030ffd09598fddb1847be4043abf398d4fdba1f
164
cpp
C++
RTHeightfield/TessellationEvaluationShader.cpp
AndreSilvs/RTMasterThesis
9eb6c34dbe5acb10ab818c2d34b16d786db11030
[ "MIT" ]
1
2020-06-18T19:21:01.000Z
2020-06-18T19:21:01.000Z
RTHeightfieldScalable/TessellationEvaluationShader.cpp
AndreSilvs/RTMasterThesis
9eb6c34dbe5acb10ab818c2d34b16d786db11030
[ "MIT" ]
null
null
null
RTHeightfieldScalable/TessellationEvaluationShader.cpp
AndreSilvs/RTMasterThesis
9eb6c34dbe5acb10ab818c2d34b16d786db11030
[ "MIT" ]
null
null
null
#include "TessellationEvaluationShader.h" GLuint TessellationEvaluationShader::generateShaderId() { return glCreateShader( GL_TESS_EVALUATION_SHADER ); }
27.333333
58
0.79878
AndreSilvs
5033b261bfe7bb409e99900de7c841f9af9ef73a
2,286
cpp
C++
WordPattern.cpp
ShreyaPrasad1209/Hash-Map-LeetCode-Questions
25e360079582db6a7f5fcdeaf889632f5e550e3b
[ "MIT" ]
2
2020-09-23T11:27:14.000Z
2021-10-30T06:46:08.000Z
WordPattern.cpp
ShreyaPrasad1209/Hash-Map-LeetCode-Questions
25e360079582db6a7f5fcdeaf889632f5e550e3b
[ "MIT" ]
null
null
null
WordPattern.cpp
ShreyaPrasad1209/Hash-Map-LeetCode-Questions
25e360079582db6a7f5fcdeaf889632f5e550e3b
[ "MIT" ]
1
2021-07-08T15:45:25.000Z
2021-07-08T15:45:25.000Z
class Solution { public: bool wordPattern(string pattern, string str) { int i = 0, j = 0, len = pattern.size(), n = str.size(); unordered_map<char, string> map1; unordered_map<string, char> map2; string word = ""; while(j < len) { if (i > n) return false;//there are letters in pattern but str has no word while(str[i] != ' ' && str[i] != '\0')//get the word word += str[i++]; if (map1.find(pattern[j]) != map1.end() && map1[pattern[j]] != word) return false; if (map2.find(word) != map2.end() && map2[word] != pattern[j]) return false; map1[pattern[j]] = word; map2[word] = pattern[j]; ++j, ++i; word = ""; } if (i <= n)//there are no letters in pattern, but str still has word return false; return true; } }; //Simpler Implementation class Solution { public: bool wordPattern(string pattern, string str) { int j=-1; //map for checking char to string unordered_map<char,string> mm; //map for checking string to char unordered_map<string,char> mn; for(int i=0;i<pattern.length();i++) { char pp=pattern[i]; string s=""; j++; while(str[j]!=' '&&j<str.length()) { s.push_back(str[j]); j++; } //only valid when not found in both if(mm.find(pp)==mm.end()&&mn.find(s)==mn.end()) { mm[pp]=s; mn[s]=pp; } //if not found in only one that means word or char is being used repeatedly for another char/string combination hence reject else if(mm.find(pp)==mm.end()||mn.find(s)==mn.end()) return false; //if found but doesnt match then reject else if(mm.find(pp)->second!=s||mn.find(s)->second!=pp) return false; } //make sure j has traveled complete length of str return j==str.length()?true:false; } }; //LeetCode Link: https://leetcode.com/problems/word-pattern/
31.75
127
0.485564
ShreyaPrasad1209
50365d5af40e1dba322fb42d558f792c15cd2687
4,007
hh
C++
dune/ax1/common/ax1_parallelhelper.hh
pederpansen/dune-ax1
152153824d95755a55bdd4fba80686863e928196
[ "BSD-3-Clause" ]
null
null
null
dune/ax1/common/ax1_parallelhelper.hh
pederpansen/dune-ax1
152153824d95755a55bdd4fba80686863e928196
[ "BSD-3-Clause" ]
null
null
null
dune/ax1/common/ax1_parallelhelper.hh
pederpansen/dune-ax1
152153824d95755a55bdd4fba80686863e928196
[ "BSD-3-Clause" ]
null
null
null
/* * ax1_parallelhelper.hh * * Created on: May 5, 2013 * Author: jpods */ #ifndef DUNE_AX1_PARALLELHELPER_HH #define DUNE_AX1_PARALLELHELPER_HH #include <dune/common/forloop.hh> #if HAVE_MPI namespace Dune { template<typename... Elements> struct MPITraits<std::tuple<Elements...> > { typedef std::tuple<Elements...> TupleType; static MPI_Datatype datatype; static inline MPI_Datatype getType() { if(datatype==MPI_DATATYPE_NULL) { const int n = sizeof...(Elements); MPI_Datatype oldtypes[n]; int blockcounts[n]; MPI_Aint offsets[n], extent; // Initialize data types for elements i=1,...,n-1 Dune::ForLoop<create_tuple_type, 0, n-1>::apply(offsets, blockcounts, oldtypes); // std::cout << std::endl; // std::cout << "--------------" << std::endl; // for(int i=0; i<n; i++) // { // std::cout << "offsets[" << i << "] = " << offsets[i] << std::endl; // std::cout << "blockcounts[" << i << "] = " << blockcounts[i] << std::endl; // } // std::cout << "--------------" << std::endl; // std::cout << std::endl; MPI_Type_struct(n, blockcounts, offsets, oldtypes, &datatype); MPI_Type_commit(&datatype); } return datatype; } template<int i> struct create_tuple_type { static void apply(MPI_Aint* offsets, int* blockcounts, MPI_Datatype* oldtypes) { TupleType tuple; MPI_Aint base; MPI_Aint displ; MPI_Address(&tuple, &base); MPI_Address(&(std::get<i>(tuple)), &displ); displ -= base; offsets[i] = displ; //offsets[i] = offsets[i-1] + blockcounts[i-1] * previous_extent; oldtypes[i] = MPITraits<typename std::tuple_element<i,TupleType>::type>::getType(); blockcounts[i] = 1; // std::cout << "offsets[" << i << "] = " << offsets[i] << std::endl; // std::cout << "oldtypes[" << i << "] = " << oldtypes[i] << std::endl; // std::cout << "blockcounts[" << i << "] = " << blockcounts[i] << std::endl; } }; }; template<typename... Elements> MPI_Datatype MPITraits<std::tuple<Elements...> >::datatype = MPI_DATATYPE_NULL; } #endif class Ax1LogTag { public: Ax1LogTag(const int rank_) : rank(rank_) {} std::ostream& operator() (std::ostream &s) const { return s << "[p" << rank << "]"; } private: const int rank; }; template<typename DebugStream> class Ax1ParallelDebugStream : public DebugStream { public: typedef Ax1ParallelDebugStream<DebugStream> This; Ax1ParallelDebugStream(std::ostream& out = std::cerr) : DebugStream(out), logtag(""), insertTag(true) {} Ax1ParallelDebugStream(Dune::DebugStreamState& master, std::ostream& fallback = std::cerr, std::string logtag_ = "") : DebugStream(master, fallback), logtag(logtag_), insertTag(true) {} //! \brief Generic types are passed on to current output stream template <class T> This& operator<<(const T data) { if(insertTag) { insertTag = false; return (This&) DebugStream::operator<<(logtag) << data; } else return (This&) DebugStream::operator<<(data); //return DebugStream::operator<<(Dune::PDELab::logtag) << data; } This& operator<<(const int data) { if(insertTag) { insertTag = false; return (This&) DebugStream::operator<<(logtag) << data; } else return (This&) DebugStream::operator<<(data); insertTag = false; } This& operator<<(std::ostream& (*f)(std::ostream&)) { typedef std::ostream& (*manip_t)(std::ostream&); //if(f == std::endl) if(f == static_cast<manip_t>(std::endl)) { //std::cerr << "std::endl detected!" << std::endl; insertTag = true; } return (This&) DebugStream::operator<<(f); } void setLogTag(std::string tag) { logtag = tag; } private: std::string logtag; bool insertTag; }; #endif /* AX1_PARALLELHELPER_HH_ */
22.511236
91
0.585475
pederpansen
50370ce07dbd901d2c7a167f7d68df222fff078f
8,514
cxx
C++
Legolas/BlockMatrix/tst/Poisson2D/Poisson2D.cxx
LaurentPlagne/Legolas
fdf533528baf7ab5fcb1db15d95d2387b3e3723c
[ "MIT" ]
null
null
null
Legolas/BlockMatrix/tst/Poisson2D/Poisson2D.cxx
LaurentPlagne/Legolas
fdf533528baf7ab5fcb1db15d95d2387b3e3723c
[ "MIT" ]
null
null
null
Legolas/BlockMatrix/tst/Poisson2D/Poisson2D.cxx
LaurentPlagne/Legolas
fdf533528baf7ab5fcb1db15d95d2387b3e3723c
[ "MIT" ]
1
2021-02-11T14:43:25.000Z
2021-02-11T14:43:25.000Z
# include <cstdlib> # include <cmath> # include <iostream> # include "UTILITES.hxx" # include "Legolas/Vector/Vector.hxx" # include "XYLightBandedBlockMatrix.hxx" # include "XYBandedBlockMatrix.hxx" # include "XYBandedPolyBlockMatrix.hxx" # include "XYDiagonalBlockMatrix.hxx" #include "X86Timer.hxx" #include "SourceFunctor.hxx" #include "Legolas/BlockMatrix/tst/LegolasTestSolver.hxx" #include "Legolas/BlockMatrix/ConjugateGradientSolver.hxx" #include "Legolas/BlockMatrix/PreconditionedConjugateGradientSolver.hxx" #include "Legolas/BlockMatrix/BiCGStabSolver.hxx" #include "Legolas/BlockMatrix/Structures/Sparse/SparseParallelMultOperator.hxx" #include "Legolas/BlockMatrix/SteepestDescentSolver.hxx" #include "Legolas/BlockMatrix/SteepestDescentMinResSolver.hxx" using namespace std; using namespace Legolas; int main( SizeType argc, char *argv[] ) { // typedef Legolas::Vector<double> Vector1D; typedef Legolas::MultiVector<double,1> Vector1D; const int maxIteration=10000; // ************* Physical data *********************** // Mesh : the 1D mesh is a regular partition of [0,1]; const SizeType meshSize=128; // const SizeType meshSize=1024; // const SizeType meshSize=512; Vector1D mesh; mesh.resize(meshSize); double stepSize=1.0/double(meshSize-1); for (SizeType i = 0 ; i < mesh.size() ; i++) mesh[i]=double(i)*stepSize; double pi=2.0*acos(0.0); const double omega=4.0*pi; SourceFunctor<double> myFunction(omega); // ********* Vector construction : U,S,R *********** // size of the unknown solution = meshSize - 2 degrees of freedom for the boundary conditions const SizeType size=meshSize-2; typedef Legolas::MultiVector<double,2> Vector2D; Vector2D::Shape shape(size,size); Vector2D U(shape); U=0.0; Vector2D S(U); for (SizeType i=0 ; i < size ; i++){ for (SizeType j=0 ; j < size ; j++){ const double x=mesh[i+1]; const double y=mesh[j+1]; S[i][j]=myFunction(x,y)*stepSize*stepSize; } } // Boundary conditions // j=0 et j=N for (SizeType i=0 ; i < size ; i++){ const double x=mesh[i+1]; const double ui0=myFunction.exact(x,mesh[0]); const double uin=myFunction.exact(x,mesh[mesh.size()-1]); S[i][0]-=ui0; S[i][size-1]-=uin; } for (SizeType j=0 ; j < size ; j++){ const double y=mesh[j+1]; const double u0j=myFunction.exact(mesh[0],y); const double unj=myFunction.exact(mesh[mesh.size()-1],y); S[0][j]-=u0j; S[size-1][j]-=unj; } // ***************** Matrix Construction *********************** // Legolas::MultiVector<double,2>::Shape shape(size,size); Legolas::MatrixShape<2> ms2(shape,shape); if (1==0) { XYLightBandedBlockMatrix LXY(ms2); LXY.maxIteration()=maxIteration; LXY.displayLatex("LXY.tex"); LXY.solve(S,U); LXY.displayProfile(); INFOS("U[0]="<<U[0]); Vector2D R(S); LXY.addMult(-1.0,U,R); INFOS("R[0]="<<R[0]); cout << "Residual="<< (Legolas::dot(R,R)) << endl ; } if (1==0) { U=0.0; XYBandedBlockMatrix HXY(ms2); HXY.maxIteration()=maxIteration; HXY.solve(S,U); HXY.displayProfile(); INFOS("U[0]="<<U[0]); Vector2D R(S); HXY.addMult(-1.0,U,R); INFOS("R[0]="<<R[0]); cout << "Residual="<< (Legolas::dot(R,R)) << endl ; } if (1==1) { U=0.0; XYBandedPolyBlockMatrix PXY(ms2); PXY.maxIteration()=maxIteration; PXY.epsilon()=1.e-5; PXY.solve(S,U); INFOS("PXY.iterationNumber()="<<PXY.iterationNumber()); INFOS("PXY.relativeDifference()="<<PXY.relativeDifference()); PXY.displayProfile(); INFOS("U[0]="<<U[0]); Vector2D R(S); PXY.addMult(-1.0,U,R); INFOS("R[0]="<<R[0]); cout << "Residual="<< (Legolas::dot(R,R)) << endl ; } { U=0.0; XYBandedPolyBlockMatrix PXY(ms2); PXY.setSolverPtr(new Legolas::ConjugateGradientSolver() ); PXY.setMultOperatorPtr(new Legolas::SparseParallelMultOperator() ); PXY.maxIteration()=maxIteration; PXY.fixedIterationNumber()=false; PXY.epsilon()=1.e-5; INFOS("PXY.maxIteration()="<<PXY.maxIteration()); PXY.solve(S,U); INFOS("PXY.iterationNumber()="<<PXY.iterationNumber()); INFOS("PXY.relativeDifference()="<<PXY.relativeDifference()); PXY.displayProfile(); INFOS("U[0]="<<U[0]); Vector2D R(S); PXY.addMult(-1.0,U,R); INFOS("R[0]="<<R[0]); cout << "Residual="<< (Legolas::dot(R,R)) << endl ; } { U=0.0; XYBandedPolyBlockMatrix PXY(ms2); PXY.setSolverPtr(new Legolas::BiCGStabSolver() ); PXY.setMultOperatorPtr(new Legolas::SparseParallelMultOperator() ); PXY.maxIteration()=maxIteration; PXY.fixedIterationNumber()=false; PXY.epsilon()=1.e-5; INFOS("PXY.maxIteration()="<<PXY.maxIteration()); PXY.solve(S,U); INFOS("PXY.iterationNumber()="<<PXY.iterationNumber()); INFOS("PXY.relativeDifference()="<<PXY.relativeDifference()); PXY.displayProfile(); INFOS("U[0]="<<U[0]); Vector2D R(S); PXY.addMult(-1.0,U,R); INFOS("R[0]="<<R[0]); cout << "Residual="<< (Legolas::dot(R,R)) << endl ; } { U=0.0; XYBandedPolyBlockMatrix PXY(ms2); // XYDiagonalBlockMatrix * Preconditioner = new XYDiagonalBlockMatrix(ms2); Legolas::Matrix * Preconditioner = new XYDiagonalBlockMatrix(ms2); INFOS("Preconditioner="<<Preconditioner); auto pcg=new Legolas::PreconditionedConjugateGradientSolver(Preconditioner); INFOS("pcg->name()="<<pcg->name()); PXY.setSolverPtr(pcg ); PXY.setMultOperatorPtr(new Legolas::SparseParallelMultOperator() ); PXY.maxIteration()=maxIteration; PXY.fixedIterationNumber()=false; PXY.epsilon()=1.e-5; INFOS("PXY.maxIteration()="<<PXY.maxIteration()); PXY.solve(S,U); INFOS("PXY.iterationNumber()="<<PXY.iterationNumber()); INFOS("PXY.relativeDifference()="<<PXY.relativeDifference()); PXY.displayProfile(); INFOS("U[0]="<<U[0]); Vector2D R(S); PXY.addMult(-1.0,U,R); INFOS("R[0]="<<R[0]); cout << "Residual="<< (Legolas::dot(R,R)) << endl ; } { U=0.0; XYBandedPolyBlockMatrix PXY(ms2); auto solver=new Legolas::SteepestDescentSolver(); INFOS("solver->name()="<<solver->name()); PXY.setSolverPtr(solver ); PXY.setMultOperatorPtr(new Legolas::SparseParallelMultOperator() ); PXY.maxIteration()=maxIteration; PXY.fixedIterationNumber()=false; PXY.epsilon()=1.e-5; INFOS("PXY.maxIteration()="<<PXY.maxIteration()); PXY.solve(S,U); INFOS("PXY.iterationNumber()="<<PXY.iterationNumber()); INFOS("PXY.relativeDifference()="<<PXY.relativeDifference()); PXY.displayProfile(); INFOS("U[0]="<<U[0]); Vector2D R(S); PXY.addMult(-1.0,U,R); INFOS("R[0]="<<R[0]); cout << "Residual="<< (Legolas::dot(R,R)) << endl ; } { U=0.0; XYBandedPolyBlockMatrix PXY(ms2); auto solver=new Legolas::SteepestDescentMinResSolver(); INFOS("solver->name()="<<solver->name()); PXY.setSolverPtr(solver); PXY.setMultOperatorPtr(new Legolas::SparseParallelMultOperator() ); PXY.maxIteration()=maxIteration; PXY.fixedIterationNumber()=false; PXY.epsilon()=1.e-5; INFOS("PXY.maxIteration()="<<PXY.maxIteration()); PXY.solve(S,U); INFOS("PXY.iterationNumber()="<<PXY.iterationNumber()); INFOS("PXY.relativeDifference()="<<PXY.relativeDifference()); PXY.displayProfile(); INFOS("U[0]="<<U[0]); Vector2D R(S); PXY.addMult(-1.0,U,R); INFOS("R[0]="<<R[0]); cout << "Residual="<< (Legolas::dot(R,R)) << endl ; } if (1==0) { ofstream outfile ("result.dat",ios::out) ; for (SizeType i=1 ; i < mesh.size()-1 ; i++){ for (SizeType j=1 ; j < mesh.size()-1 ; j++){ double xi= mesh[i]; double yj= mesh[j]; double uij=U[i-1][j-1]; double eij=myFunction.exact(xi,yj); outfile << xi << " " << yj << " " << uij << " " << eij << " " << uij-eij<< " " << endl; } outfile << endl; } outfile.close(); } if (1==0) { ofstream outfile ("u.dat",ios::out) ; for (SizeType i=1 ; i < mesh.size()-1 ; i++){ for (SizeType j=1 ; j < mesh.size()-1 ; j++){ // double xi= mesh[i]; // double yj= mesh[j]; double uij=U[i-1][j-1]; // double eij=myFunction.exact(xi,yj); outfile << uij << " " ; } outfile << endl; } outfile.close(); } #ifndef UU #endif }
24.11898
95
0.608997
LaurentPlagne
5044f0f18d3575e444997a51ed30e643be858970
4,653
cpp
C++
Src/Game.cpp
joshua-barnett/SnakeGame
d9fb55c869d7f301a681aaa9ec51686311ee858b
[ "MIT" ]
13
2019-08-08T08:47:36.000Z
2021-12-24T17:11:51.000Z
Src/Game.cpp
joshua-barnett/SnakeGame
d9fb55c869d7f301a681aaa9ec51686311ee858b
[ "MIT" ]
null
null
null
Src/Game.cpp
joshua-barnett/SnakeGame
d9fb55c869d7f301a681aaa9ec51686311ee858b
[ "MIT" ]
3
2019-08-09T10:44:45.000Z
2021-07-23T13:18:12.000Z
#include "Game.h" #include "Engine/Logger.h" #include "Components/Components.h" #include "Factories.h" #include "Constants.h" #include "PlayerSnake.h" #include "Engine/Color.h" #include "CollisionHandler.h" #include "CustomEvents.h" #include "PlayerPickups.h" #include "GameText.h" SDL_Renderer* Game::renderer = nullptr; void Game::initSDL(const char * title, int xpos, int ypos, int width, int height, bool fullscreen) { int flags = 0; if (fullscreen) flags += SDL_WINDOW_FULLSCREEN; isRunning = SDL_Init(SDL_INIT_EVERYTHING) == 0; if (isRunning) { LOG("SDL Subsystems Initialized"); window = SDL_CreateWindow(title, xpos, ypos, width, height, flags); if (window) { LOG("Window Created"); } renderer = SDL_CreateRenderer(window, -1, 0); if (renderer) { LOG("Renderer Created"); //SDL_SetRenderDrawColor(renderer, bgColor.r, bgColor.g, bgColor.b, bgColor.a); } //initialize font TTF_Init(); //initialize our custom event initEvent(); } } void Game::initEntt(entt::registry& registry) { //Generate the boundaries - form a boundary around the visible play area const int SIZE = SNAKE_CELL_SIZE; const int WID = SNAKE_SCREEN_WIDTH; const int HGT = SNAKE_SCREEN_HEIGHT; makeBoundary(registry, -SIZE, -SIZE, WID + 2*SIZE, SIZE); //top left to top right makeBoundary(registry, -SIZE, HGT, WID + 2*SIZE, SIZE); //bottom left to bottom right makeBoundary(registry, -SIZE, 0, SIZE, HGT); //top left to bottom left makeBoundary(registry, WID, 0, SIZE, HGT); //top right to bottom right //Generate the snake float centerX = WID / 2 - SIZE / 2; float centerY = HGT / 2; float scl = 1; makeSnakeHead(registry, centerX, centerY, scl, scl); makeSnakeTail(registry, centerX, centerY + SIZE, scl, scl); //Generate the pickup makePickup(registry); movePickup(registry); //Generate text makeGameOverText(registry, 40, { 200, 0, 0, 255 }); makeScoreText(registry, 25, { 240, 210, 0, 255 }); updateScoreText(registry); } void Game::handleEvents(entt::registry& registry) { while (SDL_PollEvent(NULL)) { SDL_PollEvent(&event); switch (event.type) { case SDL_QUIT: isRunning = false; break; case SDL_KEYDOWN: if (event.key.keysym.sym == SDLK_ESCAPE) isRunning = false; if (isAwaitingRestart) { if (event.key.keysym.sym == SDLK_RETURN) { isAwaitingRestart = false; cleanEntt(registry); initEntt(registry); } } else { processInput(registry, event); } default: break; } if (!isAwaitingRestart && event.type == SNAKE_EVENT_TYPE) { switch (event.user.code) { case SnakeEvent::EV_endGame: setGameOverText(registry); destroySnake(registry); isAwaitingRestart = true; break; case SnakeEvent::EV_pickup: makeSnakeBody(registry, -SNAKE_CELL_SIZE, -SNAKE_CELL_SIZE, 1., 1.); movePickup(registry); updateScoreText(registry); break; default: break; } } } } void Game::update(entt::registry& registry) { if (isAwaitingRestart) return; //update and move the snake bool movePending = updateSnake(registry); if (movePending) { moveSnake(registry); } //update colliders updateColliders(registry); checkPlayerCollision(registry); //update sprites auto view = registry.view<Sprite, Transform>(); for (auto entity : view) { view.get<Sprite>(entity).update(view.get<Transform>(entity)); } frameCounter++; } void Game::render(entt::registry& registry) { TextureManager::SetDrawColor(Color::grey()); SDL_RenderClear(renderer); //render border TextureManager::SetDrawColor(Color::black()); int w = SNAKE_SCREEN_WIDTH - 1; int h = SNAKE_SCREEN_HEIGHT - 1; SDL_RenderDrawLine(renderer, 0, 0, w, 0); //top left to top right SDL_RenderDrawLine(renderer, 0, 0, 0, h); //top left to bottom left SDL_RenderDrawLine(renderer, w, h, w, 0); // bottom right to top right SDL_RenderDrawLine(renderer, w, h, 0, h); // bottom right to bottom left //render sprites auto sprView = registry.view<Sprite>(); for (auto entity : sprView) { sprView.get(entity).render(); } //render text auto txtView = registry.view<Text>(); for (auto entity : txtView) { txtView.get(entity).render(); } SDL_RenderPresent(renderer); } void Game::cleanEntt(entt::registry& registry) { auto sprView = registry.view<Sprite>(); for (auto e : sprView) { sprView.get(e).clean(); } auto txtView = registry.view<Text>(); for (auto e : txtView) { txtView.get(e).clean(); } registry.reset(); LOG("EnTT Cleaned"); } void Game::cleanSDL() { SDL_DestroyWindow(window); SDL_DestroyRenderer(renderer); TTF_Quit(); SDL_Quit(); LOG("SDL Cleaned"); }
21.541667
98
0.688803
joshua-barnett
504904ec6fd92c850c467163b0354ab7c39897e9
5,164
inl
C++
src/bookkeeping.define.inl
cristiarg/fmi2AllocGuard
6b7f55783f5b42620c097a6e7f8b23585a515d24
[ "BSD-2-Clause" ]
3
2019-01-18T10:37:59.000Z
2019-09-06T21:52:58.000Z
src/bookkeeping.define.inl
cristiarg/fmi2AllocGuard
6b7f55783f5b42620c097a6e7f8b23585a515d24
[ "BSD-2-Clause" ]
null
null
null
src/bookkeeping.define.inl
cristiarg/fmi2AllocGuard
6b7f55783f5b42620c097a6e7f8b23585a515d24
[ "BSD-2-Clause" ]
null
null
null
void* fmi2_calloc1 ( size_t _num , size_t _size ) { void* const p = calloc( _num , _size ); const bool add_res = avl_add(&fmi2_guarded_bookkeeping[ 1 ].pointer_keeper, p, func_avl_data_comp_lt); if( add_res ) { return p; } else { free( p ); return NULL; } } void* fmi2_calloc2 ( size_t _num , size_t _size ) { void* const p = calloc( _num , _size ); const bool add_res = avl_add(&fmi2_guarded_bookkeeping[ 2 ].pointer_keeper, p, func_avl_data_comp_lt); if( add_res ) { return p; } else { free( p ); return NULL; } } void* fmi2_calloc3 ( size_t _num , size_t _size ) { void* const p = calloc( _num , _size ); const bool add_res = avl_add(&fmi2_guarded_bookkeeping[ 3 ].pointer_keeper, p, func_avl_data_comp_lt); if( add_res ) { return p; } else { free( p ); return NULL; } } void* fmi2_calloc4 ( size_t _num , size_t _size ) { void* const p = calloc( _num , _size ); const bool add_res = avl_add(&fmi2_guarded_bookkeeping[ 4 ].pointer_keeper, p, func_avl_data_comp_lt); if( add_res ) { return p; } else { free( p ); return NULL; } } void* fmi2_calloc5 ( size_t _num , size_t _size ) { void* const p = calloc( _num , _size ); const bool add_res = avl_add(&fmi2_guarded_bookkeeping[ 5 ].pointer_keeper, p, func_avl_data_comp_lt); if( add_res ) { return p; } else { free( p ); return NULL; } } void* fmi2_calloc6 ( size_t _num , size_t _size ) { void* const p = calloc( _num , _size ); const bool add_res = avl_add(&fmi2_guarded_bookkeeping[ 6 ].pointer_keeper, p, func_avl_data_comp_lt); if( add_res ) { return p; } else { free( p ); return NULL; } } void* fmi2_calloc7 ( size_t _num , size_t _size ) { void* const p = calloc( _num , _size ); const bool add_res = avl_add(&fmi2_guarded_bookkeeping[ 7 ].pointer_keeper, p, func_avl_data_comp_lt); if( add_res ) { return p; } else { free( p ); return NULL; } } void* fmi2_calloc8 ( size_t _num , size_t _size ) { void* const p = calloc( _num , _size ); const bool add_res = avl_add(&fmi2_guarded_bookkeeping[ 8 ].pointer_keeper, p, func_avl_data_comp_lt); if( add_res ) { return p; } else { free( p ); return NULL; } } void* fmi2_calloc9 ( size_t _num , size_t _size ) { void* const p = calloc( _num , _size ); const bool add_res = avl_add(&fmi2_guarded_bookkeeping[ 9 ].pointer_keeper, p, func_avl_data_comp_lt); if( add_res ) { return p; } else { free( p ); return NULL; } } void* fmi2_calloc10 ( size_t _num , size_t _size ) { void* const p = calloc( _num , _size ); const bool add_res = avl_add(&fmi2_guarded_bookkeeping[ 10 ].pointer_keeper, p, func_avl_data_comp_lt); if( add_res ) { return p; } else { free( p ); return NULL; } } void fmi2_free1 ( void* _ptr ) { const bool rem_res = avl_rem(&fmi2_guarded_bookkeeping[ 1 ].pointer_keeper, _ptr, func_avl_data_comp_lt, func_avl_data_clear_nop); if( !rem_res ) { //TODO: assert? error? } free( _ptr ); } void fmi2_free2 ( void* _ptr ) { const bool rem_res = avl_rem(&fmi2_guarded_bookkeeping[ 2 ].pointer_keeper, _ptr, func_avl_data_comp_lt, func_avl_data_clear_nop); if( !rem_res ) { //TODO: assert? error? } free( _ptr ); } void fmi2_free3 ( void* _ptr ) { const bool rem_res = avl_rem(&fmi2_guarded_bookkeeping[ 3 ].pointer_keeper, _ptr, func_avl_data_comp_lt, func_avl_data_clear_nop); if( !rem_res ) { //TODO: assert? error? } free( _ptr ); } void fmi2_free4 ( void* _ptr ) { const bool rem_res = avl_rem(&fmi2_guarded_bookkeeping[ 4 ].pointer_keeper, _ptr, func_avl_data_comp_lt, func_avl_data_clear_nop); if( !rem_res ) { //TODO: assert? error? } free( _ptr ); } void fmi2_free5 ( void* _ptr ) { const bool rem_res = avl_rem(&fmi2_guarded_bookkeeping[ 5 ].pointer_keeper, _ptr, func_avl_data_comp_lt, func_avl_data_clear_nop); if( !rem_res ) { //TODO: assert? error? } free( _ptr ); } void fmi2_free6 ( void* _ptr ) { const bool rem_res = avl_rem(&fmi2_guarded_bookkeeping[ 6 ].pointer_keeper, _ptr, func_avl_data_comp_lt, func_avl_data_clear_nop); if( !rem_res ) { //TODO: assert? error? } free( _ptr ); } void fmi2_free7 ( void* _ptr ) { const bool rem_res = avl_rem(&fmi2_guarded_bookkeeping[ 7 ].pointer_keeper, _ptr, func_avl_data_comp_lt, func_avl_data_clear_nop); if( !rem_res ) { //TODO: assert? error? } free( _ptr ); } void fmi2_free8 ( void* _ptr ) { const bool rem_res = avl_rem(&fmi2_guarded_bookkeeping[ 8 ].pointer_keeper, _ptr, func_avl_data_comp_lt, func_avl_data_clear_nop); if( !rem_res ) { //TODO: assert? error? } free( _ptr ); } void fmi2_free9 ( void* _ptr ) { const bool rem_res = avl_rem(&fmi2_guarded_bookkeeping[ 9 ].pointer_keeper, _ptr, func_avl_data_comp_lt, func_avl_data_clear_nop); if( !rem_res ) { //TODO: assert? error? } free( _ptr ); } void fmi2_free10 ( void* _ptr ) { const bool rem_res = avl_rem(&fmi2_guarded_bookkeeping[ 10 ].pointer_keeper, _ptr, func_avl_data_comp_lt, func_avl_data_clear_nop); if( !rem_res ) { //TODO: assert? error? } free( _ptr ); }
24.473934
133
0.668861
cristiarg
504e6433bd3dcdea0c7676ff371b3d879386485f
2,194
cpp
C++
mordor/examples/echoserver.cpp
cmpxchg16/mordor
58e62ab71d98af165fadd361bd5607c87ce34f46
[ "BSD-3-Clause" ]
1
2017-07-22T09:34:18.000Z
2017-07-22T09:34:18.000Z
mordor/examples/echoserver.cpp
cmpxchg16/mordor
58e62ab71d98af165fadd361bd5607c87ce34f46
[ "BSD-3-Clause" ]
null
null
null
mordor/examples/echoserver.cpp
cmpxchg16/mordor
58e62ab71d98af165fadd361bd5607c87ce34f46
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2009 - Mozy, Inc. #include "mordor/predef.h" #include <boost/bind.hpp> #include <boost/thread.hpp> #include "mordor/config.h" #include "mordor/daemon.h" #include "mordor/iomanager.h" #include "mordor/main.h" #include "mordor/socket.h" #include "mordor/streams/socket.h" #include "mordor/streams/transfer.h" #include "mordor/streams/ssl.h" using namespace Mordor; void streamConnection(Stream::ptr stream) { try { transferStream(stream, stream); } catch (UnexpectedEofException &) {} stream->close(); } void socketServer(Socket::ptr listen) { IOManager ioManager; while (true) { Socket::ptr socket = listen->accept(&ioManager); Stream::ptr stream(new SocketStream(socket)); Scheduler::getThis()->schedule(boost::bind(&streamConnection, stream)); } } void startSocketServer(IOManager &ioManager) { std::vector<Address::ptr> addresses = Address::lookup("localhost:8000"); for (std::vector<Address::ptr>::const_iterator it(addresses.begin()); it != addresses.end(); ++it) { Socket::ptr s = (*it)->createSocket(ioManager, SOCK_STREAM); s->bind(*it); Scheduler::getThis()->schedule(boost::bind(&socketServer, s)); } UnixAddress echoaddress("/tmp/echo"); Socket::ptr s = echoaddress.createSocket(ioManager, SOCK_STREAM); s->bind(echoaddress); Scheduler::getThis()->schedule(boost::bind(&socketServer, s)); } int main(int argc, char *argv[]) { try { IOManager ioManager; std::vector<Address::ptr> addresses = Address::lookup("localhost:8080"); Socket::ptr socket = addresses[0]->createSocket(ioManager, SOCK_STREAM); socket->bind(addresses[0]); socket->listen(); boost::thread serveThread1(socketServer, socket); boost::thread serveThread2(socketServer, socket); boost::thread serveThread3(socketServer, socket); boost::thread serveThread4(socketServer, socket); serveThread1.join(); serveThread2.join(); serveThread3.join(); serveThread4.join(); } catch (...) { std::cerr << boost::current_exception_diagnostic_information() << std::endl; return 1; } return 0; }
25.811765
84
0.666819
cmpxchg16
50509f0c34a2453dc6fea5a13cffcc2af8318054
1,112
cpp
C++
GameOfChess/src/view/BoardView.cpp
My-Cpp-projects/GameOfChess
58ea06fc30ef9a9b7ddc33293a392908a24e55ac
[ "MIT" ]
1
2021-09-13T15:57:01.000Z
2021-09-13T15:57:01.000Z
GameOfChess/src/view/BoardView.cpp
My-Cpp-projects/GameOfChess
58ea06fc30ef9a9b7ddc33293a392908a24e55ac
[ "MIT" ]
null
null
null
GameOfChess/src/view/BoardView.cpp
My-Cpp-projects/GameOfChess
58ea06fc30ef9a9b7ddc33293a392908a24e55ac
[ "MIT" ]
null
null
null
#include "view/BoardView.h" #include "util/Texture.h" BoardView::BoardView(BoardData& boardData, SDL_Renderer& renderer) : m_boardData(boardData) , m_renderer(renderer) { m_boardTexture = std::make_unique<Texture>(common::ImageType::PNG, "Assets/Chessboard.png", renderer); m_chessPieceView = std::make_unique<ChessPieceView>(renderer); for(int boardHeight = 0; boardHeight < m_boardData.m_board.size(); ++boardHeight) { for(int boardWidth = 0; boardWidth < m_boardData.m_board[boardHeight].size(); ++boardWidth) { m_tileViewMatrix[boardWidth][boardHeight] = std::make_unique<TileView>(m_boardData.m_board[boardWidth][boardHeight]->getData(), renderer, *m_chessPieceView); } } } BoardView::~BoardView() { printf("Destructor called for BoardView\n"); } void BoardView::render(const SDL_Point& renderStartLocation) const { SDL_RenderClear(&m_renderer); m_boardTexture->render({ 0, 0 }); for(auto& tileViewRow : m_tileViewMatrix) { for(auto& tileView : tileViewRow) { tileView->render(); } } SDL_RenderPresent(&m_renderer); }
26.47619
130
0.705935
My-Cpp-projects