hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
641235d287332ab2df405fc2c6b41803a0fa4fb2
600
cpp
C++
lib-src/sgcc/project/cpptesthelper.cpp
xiaomailong/prestudy
f4c53a5d568def175fbe1dc75283ed05b46d1238
[ "MIT" ]
2
2019-03-20T01:30:24.000Z
2020-05-25T09:56:31.000Z
lib-src/sgcc/project/cpptesthelper.cpp
xiaomailong/prestudy
f4c53a5d568def175fbe1dc75283ed05b46d1238
[ "MIT" ]
null
null
null
lib-src/sgcc/project/cpptesthelper.cpp
xiaomailong/prestudy
f4c53a5d568def175fbe1dc75283ed05b46d1238
[ "MIT" ]
1
2022-01-21T01:02:36.000Z
2022-01-21T01:02:36.000Z
// Copyright 2012 sgcc Bolik #include <gtest/gtest.h> #include "cpptesthelper.h" std::ostream& operator<<(std::ostream& os, const ObjectTestHelper& objHelper) { objHelper.writeTo(os); return os; } //TEST(Other, DefineTest) { // int a[10]; // for (int i = 0; i < 10; i++) // a[i] = i; // int *ip = a; // PrintExpression(*ip); // PrintExpression(*++ip); // PrintExpression(*(ip+5)); // int *ip2 = ip + 5; // PrintExpression(*ip2); // PrintExpression(*(ip2 - 4)); // PrintExpression(*--ip2); // PrintExpression(ip2-ip); //}
22.222222
80
0.548333
xiaomailong
64159169c4f39ed755abc04c639bfdef54164353
8,465
hpp
C++
Source/System/ResourceManager.hpp
gunstarpl/Perim-Game-07-2015
58efdee1857f5cccad909d5c2a76f2d6871657e6
[ "Unlicense", "MIT" ]
null
null
null
Source/System/ResourceManager.hpp
gunstarpl/Perim-Game-07-2015
58efdee1857f5cccad909d5c2a76f2d6871657e6
[ "Unlicense", "MIT" ]
null
null
null
Source/System/ResourceManager.hpp
gunstarpl/Perim-Game-07-2015
58efdee1857f5cccad909d5c2a76f2d6871657e6
[ "Unlicense", "MIT" ]
null
null
null
#pragma once #include "Precompiled.hpp" #include "Resource.hpp" // // Resource Manager // namespace System { // Resource pool interface. class ResourcePoolInterface { protected: ResourcePoolInterface() { } public: virtual ~ResourcePoolInterface() { } virtual void ReleaseUnused() = 0; }; // Resource pool class. template<typename Type> class ResourcePool : public ResourcePoolInterface { public: // Validate resource type. static_assert(std::is_base_of<Resource, Type>::value, "Not a resource type."); // Type declarations. typedef std::shared_ptr<Type> ResourcePtr; typedef std::unordered_map<std::string, ResourcePtr> ResourceList; typedef typename ResourceList::value_type ResourceListPair; public: ResourcePool(ResourceManager& resourceManager); ~ResourcePool(); // Sets the default resource. void SetDefault(std::shared_ptr<const Type> resource); // Gets the default resource. std::shared_ptr<const Type> GetDefault() const; // Loads a resource. std::shared_ptr<const Type> Load(std::string filename); // Releases unused resources. void ReleaseUnused(); // Releases all resources. void ReleaseAll(); private: // Resource manager reference. ResourceManager& m_resourceManager; // List of resources. ResourceList m_resources; // Default resource. std::shared_ptr<const Type> m_default; }; template<typename Type> ResourcePool<Type>::ResourcePool(ResourceManager& resourceManager) : m_resourceManager(resourceManager), m_default(std::make_shared<Type>(&m_resourceManager)) { } template<typename Type> ResourcePool<Type>::~ResourcePool() { // Release all resources. this->ReleaseAll(); } template<typename Type> void ResourcePool<Type>::SetDefault(std::shared_ptr<const Type> resource) { m_default = resource; } template<typename Type> std::shared_ptr<const Type> ResourcePool<Type>::GetDefault() const { return m_default; } template<typename Type> std::shared_ptr<const Type> ResourcePool<Type>::Load(std::string filename) { // Find the resource. auto it = m_resources.find(filename); if(it != m_resources.end()) return it->second; // Create and load the new resource instance. std::shared_ptr<Type> resource = std::make_shared<Type>(&m_resourceManager); if(!resource->Load(filename)) return m_default; // Add resource to the list. auto result = m_resources.emplace(filename, std::move(resource)); assert(result.second == true); // Return resource pointer. return result.first->second; } template<typename Type> void ResourcePool<Type>::ReleaseUnused() { // Release unused resources. auto it = m_resources.begin(); while(it != m_resources.end()) { if(it->second.unique()) { // Take out filename string to print it later. std::string filename = std::move(it->first); // Release the resource. it = m_resources.erase(it); // Print log message. Log() << "Released a resource loaded from \"" << filename << "\" file."; } else { ++it; } } } template<typename Type> void ResourcePool<Type>::ReleaseAll() { // Release all resources. auto it = m_resources.begin(); while(it != m_resources.end()) { // Take out filename string to print it later. std::string filename = std::move(it->first); // Release the resource. it = m_resources.erase(it); // Print log message. Log() << "Released a resource loaded from \"" << filename << "\" file."; } assert(m_resources.empty()); } // Resource manager class. class ResourceManager { public: // Type declarations. typedef std::unique_ptr<ResourcePoolInterface> ResourcePoolPtr; typedef std::unordered_map<std::type_index, ResourcePoolPtr> ResourcePoolList; typedef ResourcePoolList::value_type ResourcePoolPair; public: ResourceManager(); ~ResourceManager(); // Restores instance to it's original state. void Cleanup(); // Initializes the component system. bool Initialize(Context& context); // Releases unused resources. void ReleaseUnused(); // Loads a resource. template<typename Type> std::shared_ptr<const Type> Load(std::string filename); // Sets the default resource. template<typename Type> void SetDefault(std::shared_ptr<const Type> default); // Gets the default resource. template<typename Type> std::shared_ptr<const Type> GetDefault() const; // Gets a resource pool. template<typename Type> ResourcePool<Type>* GetPool(); private: // Creates a resource pool. template<typename Type> ResourcePool<Type>* CreatePool(); private: // Resource pools. ResourcePoolList m_pools; // Initialization state. bool m_initialized; }; template<typename Type> std::shared_ptr<const Type> ResourceManager::Load(std::string filename) { if(!m_initialized) return nullptr; // Validate resource type. static_assert(std::is_base_of<Resource, Type>::value, "Not a resource type."); // Get the resource pool. ResourcePool<Type>* pool = this->GetPool<Type>(); assert(pool != nullptr); // Delegate to the resource pool. return pool->Load(filename); } template<typename Type> void ResourceManager::SetDefault(std::shared_ptr<const Type> default) { if(!m_initialized) return; // Validate resource type. static_assert(std::is_base_of<Resource, Type>::value, "Not a resource type."); // Get the resource pool. ResourcePool<Type>* pool = this->GetPool<Type>(); assert(pool != nullptr); // Set the default resource. pool->SetDefault(default); } template<typename Type> std::shared_ptr<const Type> ResourceManager::GetDefault() const { if(!m_initialized) return nullptr; // Validate resource type. static_assert(std::is_base_of<Resource, Type>::value, "Not a resource type."); // Get the resource pool. ResourcePool<Type>* pool = this->GetPool<Type>(); assert(pool != nullptr); // Return the default resource. return pool->GetDefault(); } template<typename Type> ResourcePool<Type>* ResourceManager::CreatePool() { assert(m_initialized); // Validate resource type. static_assert(std::is_base_of<Resource, Type>::value, "Not a resource type."); // Create and add a pool to the collection. auto pool = std::make_unique<ResourcePool<Type>>(*this); auto pair = ResourcePoolPair(typeid(Type), std::move(pool)); auto result = m_pools.insert(std::move(pair)); assert(result.second == true); // Return created pool. return reinterpret_cast<ResourcePool<Type>*>(result.first->second.get()); } template<typename Type> ResourcePool<Type>* ResourceManager::GetPool() { if(!m_initialized) return nullptr; // Validate resource type. static_assert(std::is_base_of<Resource, Type>::value, "Not a resource type."); // Find pool by resource type. auto it = m_pools.find(typeid(Type)); if(it == m_pools.end()) { // Create a new resource pool. return this->CreatePool<Type>(); } // Cast and return the pointer that we already know is a resource pool. return reinterpret_cast<ResourcePool<Type>*>(it->second.get()); } };
27.21865
88
0.588305
gunstarpl
6416a341f41a586e5ddd2a1d022eb53d11351671
7,409
cpp
C++
src/mongo/db/pipeline/document.cpp
spencerjackson/mongo
51c46e71c9f310fc91168c0945ffa6cfc00d380b
[ "Apache-2.0" ]
null
null
null
src/mongo/db/pipeline/document.cpp
spencerjackson/mongo
51c46e71c9f310fc91168c0945ffa6cfc00d380b
[ "Apache-2.0" ]
null
null
null
src/mongo/db/pipeline/document.cpp
spencerjackson/mongo
51c46e71c9f310fc91168c0945ffa6cfc00d380b
[ "Apache-2.0" ]
null
null
null
/** * Copyright (c) 2011 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "pch.h" #include <boost/functional/hash.hpp> #undef assert #define assert MONGO_assert #include "db/jsobj.h" #include "db/pipeline/document.h" #include "db/pipeline/value.h" #include "util/mongoutils/str.h" namespace mongo { using namespace mongoutils; string Document::idName("_id"); intrusive_ptr<Document> Document::createFromBsonObj(BSONObj *pBsonObj) { intrusive_ptr<Document> pDocument(new Document(pBsonObj)); return pDocument; } Document::Document(BSONObj *pBsonObj): vFieldName(), vpValue() { BSONObjIterator bsonIterator(pBsonObj->begin()); while(bsonIterator.more()) { BSONElement bsonElement(bsonIterator.next()); string fieldName(bsonElement.fieldName()); intrusive_ptr<const Value> pValue( Value::createFromBsonElement(&bsonElement)); vFieldName.push_back(fieldName); vpValue.push_back(pValue); } } void Document::toBson(BSONObjBuilder *pBuilder) { const size_t n = vFieldName.size(); for(size_t i = 0; i < n; ++i) vpValue[i]->addToBsonObj(pBuilder, vFieldName[i]); } intrusive_ptr<Document> Document::create(size_t sizeHint) { intrusive_ptr<Document> pDocument(new Document(sizeHint)); return pDocument; } Document::Document(size_t sizeHint): vFieldName(), vpValue() { if (sizeHint) { vFieldName.reserve(sizeHint); vpValue.reserve(sizeHint); } } intrusive_ptr<Document> Document::clone() { const size_t n = vFieldName.size(); intrusive_ptr<Document> pNew(Document::create(n)); for(size_t i = 0; i < n; ++i) pNew->addField(vFieldName[i], vpValue[i]); return pNew; } Document::~Document() { } FieldIterator *Document::createFieldIterator() { return new FieldIterator(intrusive_ptr<Document>(this)); } intrusive_ptr<const Value> Document::getValue(const string &fieldName) { /* For now, assume the number of fields is small enough that iteration is ok. Later, if this gets large, we can create a map into the vector for these lookups. Note that because of the schema-less nature of this data, we always have to look, and can't assume that the requested field is always in a particular place as we would with a statically compilable reference. */ const size_t n = vFieldName.size(); for(size_t i = 0; i < n; ++i) { if (fieldName.compare(vFieldName[i]) == 0) return vpValue[i]; } return(intrusive_ptr<const Value>()); } void Document::addField(const string &fieldName, const intrusive_ptr<const Value> &pValue) { uassert(15945, str::stream() << "cannot add undefined field " << fieldName << " to document", pValue->getType() != Undefined); vFieldName.push_back(fieldName); vpValue.push_back(pValue); } void Document::setField(size_t index, const string &fieldName, const intrusive_ptr<const Value> &pValue) { /* special case: should this field be removed? */ if (!pValue.get()) { vFieldName.erase(vFieldName.begin() + index); vpValue.erase(vpValue.begin() + index); return; } /* make sure we have a valid value */ uassert(15968, str::stream() << "cannot set undefined field " << fieldName << " to document", pValue->getType() != Undefined); /* set the indicated field */ vFieldName[index] = fieldName; vpValue[index] = pValue; } intrusive_ptr<const Value> Document::getField(const string &fieldName) const { const size_t n = vFieldName.size(); for(size_t i = 0; i < n; ++i) { if (fieldName.compare(vFieldName[i]) == 0) return vpValue[i]; } /* if we got here, there's no such field */ return intrusive_ptr<const Value>(); } size_t Document::getApproximateSize() const { size_t size = sizeof(Document); const size_t n = vpValue.size(); for(size_t i = 0; i < n; ++i) size += vpValue[i]->getApproximateSize(); return size; } size_t Document::getFieldIndex(const string &fieldName) const { const size_t n = vFieldName.size(); size_t i = 0; for(; i < n; ++i) { if (fieldName.compare(vFieldName[i]) == 0) break; } return i; } void Document::hash_combine(size_t &seed) const { const size_t n = vFieldName.size(); for(size_t i = 0; i < n; ++i) { boost::hash_combine(seed, vFieldName[i]); vpValue[i]->hash_combine(seed); } } int Document::compare(const intrusive_ptr<Document> &rL, const intrusive_ptr<Document> &rR) { const size_t lSize = rL->vFieldName.size(); const size_t rSize = rR->vFieldName.size(); for(size_t i = 0; true; ++i) { if (i >= lSize) { if (i >= rSize) return 0; // documents are the same length return -1; // left document is shorter } if (i >= rSize) return 1; // right document is shorter const int nameCmp = rL->vFieldName[i].compare(rR->vFieldName[i]); if (nameCmp) return nameCmp; // field names are unequal const int valueCmp = Value::compare(rL->vpValue[i], rR->vpValue[i]); if (valueCmp) return valueCmp; // fields are unequal } /* NOTREACHED */ assert(false); return 0; } /* ----------------------- FieldIterator ------------------------------- */ FieldIterator::FieldIterator(const intrusive_ptr<Document> &pTheDocument): pDocument(pTheDocument), index(0) { } bool FieldIterator::more() const { return (index < pDocument->vFieldName.size()); } pair<string, intrusive_ptr<const Value> > FieldIterator::next() { assert(more()); pair<string, intrusive_ptr<const Value> > result( pDocument->vFieldName[index], pDocument->vpValue[index]); ++index; return result; } }
33.224215
83
0.563369
spencerjackson
64171fc4727f307a00e40a612cc01bc22fc6d847
2,088
hpp
C++
renderer/msd_renderer.hpp
msdmazarei/cpp-msd-freetype
ae4c79512ea6c9fba686235e9dd2dd03bd791a6f
[ "BSD-2-Clause" ]
null
null
null
renderer/msd_renderer.hpp
msdmazarei/cpp-msd-freetype
ae4c79512ea6c9fba686235e9dd2dd03bd791a6f
[ "BSD-2-Clause" ]
null
null
null
renderer/msd_renderer.hpp
msdmazarei/cpp-msd-freetype
ae4c79512ea6c9fba686235e9dd2dd03bd791a6f
[ "BSD-2-Clause" ]
null
null
null
#ifndef _MSD_RENDERER_H_ #define _MSD_RENDERER_H_ #include <hb-ft.h> #include <mupdf/fitz.h> #include <png++/png.hpp> #include <vector> typedef unsigned char BYTE; typedef unsigned int uint; // typedef struct ImagePixel_ { // BYTE C; // R, G, B; // } ImagePixel; typedef struct glyph_position_ { hb_codepoint_t gid; double x, y; int bitmap_width; int bitmap_height; int metrics_height; int metrics_width; int metrics_horiBearingY; int bitmap_left; float x_advancing; } glyph_position; typedef struct TextBitmap_ { png::image<png::gray_pixel> bitmap; uint base_line; } TextBitmap; typedef png::image<png::rgba_pixel> RGBAImage; typedef struct TextImage_ { RGBAImage image; uint base_line; } TextImage; class TextRenderer { private: BYTE *font_buffer; unsigned long font_buffer_len; unsigned int font_size; FT_Library ft_library; FT_Face ft_face; FT_Error ft_error; fz_context *ctx; hb_font_t *hb_font; std::vector<glyph_position> get_glyphs(char *text, unsigned int len); // template <typename pixel> // void TextRenderer::copy_to_target_image(png::image<pixel> &target_image, // BYTE *graybitmap, uint x_offset, // uint y_offset, uint gwidth, // uint gheight); // void copy_to_target_image(ImagePixel *target, ImagePixel *glyph_bitmap, // uint16_t x_offset, uint16_t y_offset, // uint16_t gwidth, uint16_t gheight, // uint16_t image_width, uint16_t image_height); public: TextRenderer(BYTE *buffer, unsigned long len); ~TextRenderer() { if (ctx) fz_drop_context(ctx); } void set_font_size(unsigned int font_size); TextBitmap render(char *text, unsigned int text_len, bool ltr); static RGBAImage colorizeBitmap(png::image<png::gray_pixel> &src, png::rgba_pixel &foreground_color, png::rgba_pixel &background_color); }; #endif
27.473684
77
0.645115
msdmazarei
641a3c3bce9823d835bca8504751b151b026a358
219
hpp
C++
el/types/void.hpp
Xikeb/elSandbox
f0d2474672016a87aae9720b6ee9346904f21cd2
[ "MIT" ]
null
null
null
el/types/void.hpp
Xikeb/elSandbox
f0d2474672016a87aae9720b6ee9346904f21cd2
[ "MIT" ]
null
null
null
el/types/void.hpp
Xikeb/elSandbox
f0d2474672016a87aae9720b6ee9346904f21cd2
[ "MIT" ]
null
null
null
#pragma once namespace el { namespace impl { template<typename ...Ts> struct void_t { using type = void; }; } // impl template<typename ...Ts> using void_t = typename el::impl::void_t<Ts...>::type; } // el
18.25
55
0.630137
Xikeb
641a940d040f30d58b48dd743252e18c4dde82fd
682
cc
C++
ui/events/x/keyboard_hook_x11.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
ui/events/x/keyboard_hook_x11.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
ui/events/x/keyboard_hook_x11.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/events/x/keyboard_hook_x11.h" namespace ui { KeyboardHookX11::KeyboardHookX11( absl::optional<base::flat_set<DomCode>> dom_codes, gfx::AcceleratedWidget accelerated_widget, KeyboardHookBase::KeyEventCallback callback) : KeyboardHookBase(std::move(dom_codes), std::move(callback)), XKeyboardHook(accelerated_widget) {} KeyboardHookX11::~KeyboardHookX11() = default; bool KeyboardHookX11::RegisterHook() { return XKeyboardHook::RegisterHook(dom_codes()); } } // namespace ui
29.652174
73
0.755132
zealoussnow
6421ef93fa801a45627238d076c5a706c03210d8
794
cc
C++
lib/sk/io/win32/AnonymousPipe.cc
stemkit-collection/stemkit-cpp
dfa77d831f49916ba6d134f407a4dcd0983328f6
[ "MIT" ]
4
2019-02-19T16:48:41.000Z
2022-01-31T07:57:54.000Z
lib/sk/io/win32/AnonymousPipe.cc
stemkit-collection/stemkit-cpp
dfa77d831f49916ba6d134f407a4dcd0983328f6
[ "MIT" ]
1
2019-01-30T04:48:35.000Z
2019-01-30T04:48:35.000Z
lib/sk/io/win32/AnonymousPipe.cc
stemkit-collection/stemkit-cpp
dfa77d831f49916ba6d134f407a4dcd0983328f6
[ "MIT" ]
null
null
null
/* vi: sw=2: * Copyright (c) 2006, Gennady Bystritsky <bystr@mac.com> * * Distributed under the MIT Licence. * This is free software. See 'LICENSE' for details. * You must read and accept the license prior to use. */ #include <sk/util/Class.h> #include <sk/util/String.h> #include <sk/util/SystemException.h> #include <sk/util/UnsupportedOperationException.h> #include <sk/io/AnonymousPipe.h> sk::io::AnonymousPipe:: AnonymousPipe() : _scope(*this) { throw sk::util::UnsupportedOperationException(SK_METHOD); } sk::io::AnonymousPipe:: ~AnonymousPipe() { } const sk::util::Class sk::io::AnonymousPipe:: getClass() const { return sk::util::Class("sk::io::AnonymousPipe"); } void sk::io::AnonymousPipe:: resetSignals() { } void sk::io::AnonymousPipe:: ignoreSignals() { }
17.26087
59
0.700252
stemkit-collection
6426306a3b5cbb8437d7b249319a250084f0de32
17,941
cxx
C++
Programs/ThirionRegistration/mimxThirionRegistrationPrimary.cxx
Piyusha23/IAFEMesh
e91b34c9eaa9c8ecc4ebb5d16f4c13f330d75c9f
[ "BSD-4-Clause-UC" ]
null
null
null
Programs/ThirionRegistration/mimxThirionRegistrationPrimary.cxx
Piyusha23/IAFEMesh
e91b34c9eaa9c8ecc4ebb5d16f4c13f330d75c9f
[ "BSD-4-Clause-UC" ]
null
null
null
Programs/ThirionRegistration/mimxThirionRegistrationPrimary.cxx
Piyusha23/IAFEMesh
e91b34c9eaa9c8ecc4ebb5d16f4c13f330d75c9f
[ "BSD-4-Clause-UC" ]
null
null
null
#include <iostream> #include <string> #include <fstream> #include <stdio.h> #include "itkImage.h" #include "itkExceptionObject.h" #include "itkBrains2MaskImageIOFactory.h" #include "ThirionRegistration.h" #include <metaCommand.h> //This function prints the valid pixel types. void PrintDataTypeStrings(void) { //Prints the Input and output data type strings. std::cout << "UCHAR" << std::endl; std::cout << "SHORT" << std::endl; std::cout << "USHORT" << std::endl; std::cout << "INT" << std::endl; std::cout << "FLOAT" << std::endl; } //This function compares strings. int CompareNoCase( const std::string &s, const std::string& s2 ) { //Compare strings. std::string::const_iterator p = s.begin(); std::string::const_iterator p2 = s2.begin(); while ( p != s.end() && p2 != s2.end() ) { if ( toupper(*p) != toupper(*p2) ) return (toupper(*p) < toupper(*p2)) ? -1 : 1; p++; p2++; } return ( s2.size() == s.size() ) ? 0 : (s.size() < s2.size()) ? -1 : 1; } // This function calls the Thirion registration filter setting all the parameters. template < class InPixelType, class OutPixelType > void ThirionFunction (MetaCommand command) { const std::string InputFilename(command.GetValueAsString("InputFilename", "filename")); const std::string OutputFilename(command.GetValueAsString("OutputFilename", "filename")); const std::string TargetFilename(command.GetValueAsString("TargetFilename", "filename")); const std::string ParameterFilename(command. GetValueAsString("ParameterFilename","filename")); const std::string OutputDeformationFilename(command. GetValueAsString("OutputDeformationFieldname","filename")); const std::string CheckerboardFilename(command. GetValueAsString("CheckerboardFilename","filename")); const std::string CheckerboardPattern(command. GetValueAsString("CheckerPattern","PatternArray")); const std::string DisplacementPrefix(command. GetValueAsString("DisplacementField","filename")); int MedianFilterRadius(command.GetValueAsInt("Median","radius")); std::cerr << "InputFilename " << InputFilename << std::endl << "OutputFilename " << OutputFilename << std::endl << "TargetFilename " << TargetFilename << std::endl << "ParameterFilename " << ParameterFilename << std::endl << "OutputDeformationFilename " << OutputDeformationFilename << std::endl << "CheckerboardFilename " << CheckerboardFilename << std::endl << "CheckerboardPattern " << CheckerboardPattern << std::endl << "DisplacementPrefix " << DisplacementPrefix << std::endl << "MedianFilterRadius" << MedianFilterRadius << std::endl; const int dims =3; typedef itk::Image<InPixelType, dims> ImageType; typedef itk::Image<float, dims> RealImageType; typedef itk::Image<OutPixelType, dims> OutputImageType; typedef itk::Image< itk::Vector<float, 3>, 3> DeformationFieldType; typename DeformationFieldType::Pointer initialDeformationField; // // If optional initial transform is given, will use this transform to generate // a deformation field to prime the thirion demons registration. std::string initialTransformFilename(command.GetValueAsString("InitialTransform","filename")); //Need to explicity register the B2MaskIOFactory itk::Brains2MaskImageIOFactory::RegisterOneFactory (); //Thirion Registration application filter. typedef itk::ThirionRegistration < ImageType, RealImageType, OutputImageType > AppType; //Set the parameters for the filter. typename AppType::Pointer app = AppType::New (); if(initialTransformFilename != "" ) { app->SetInitialTransformFileName(initialTransformFilename); } app->SetParameterFileName (ParameterFilename.c_str ()); app->SetTheMovingImageFileName (InputFilename.c_str ()); app->SetTheFixedImageFileName (TargetFilename.c_str ()); app->SetWarpedImageName (OutputFilename.c_str ()); app->SetMedianFilterRadius(MedianFilterRadius); //Set the other optional arguments if specified by the user. if (DisplacementPrefix != "") { app->SetDisplacementBaseName (DisplacementPrefix.c_str ()); } if (OutputDeformationFilename != "") { app->SetDeformationFieldOutputName (OutputDeformationFilename.c_str ()); } if (CheckerboardFilename != "") { app->SetCheckerBoardFileName (CheckerboardFilename.c_str ()); if (CheckerboardPattern != "") { unsigned int array[3] = { command.GetValueAsInt ("CheckerPattern", "XPattern"), command.GetValueAsInt ("CheckerPattern", "YPattern"), command.GetValueAsInt ("CheckerPattern", "ZPattern") }; app->SetCheckerBoardPattern (array); } } if (command.GetValueAsBool ("Normalize", "norm")) { std::string normalize = "ON"; app->SetOutNormalized (normalize.c_str ()); } if (command.GetValueAsBool ("DEBUG", "debug")) { std::string debug = "ON"; app->SetOutDebug (debug.c_str ()); } //If Making BOBF option is specified Initialize its parameters if (command.GetValueAsBool ("BOBF", "bobf")) { if ((command.GetValueAsString ("BOBFTargetMaskname", "tgmask") == "") || (command. GetValueAsString ("BOBFTemplateMaskname", "tmpgmask") == "")) { std::cout << "Error: If BOBF option is set then the target mask name and template mask file name should be specified. \n"; exit(-1); } app->SetBOBFTargetMask (command. GetValueAsString ("BOBFTargetMaskname", "tgmask").c_str ()); app->SetBOBFTemplateMask (command. GetValueAsString ("BOBFTemplateMaskname", "tmpgmask").c_str ()); app->SetLower (command.GetValueAsInt ("BOBFLtshd", "ltshd")); app->SetUpper (command.GetValueAsInt ("BOBFUtshd", "utshd")); typename ImageType::SizeType radius; radius[0] = command.GetValueAsInt ("BOBFNeighX", "nbdx"); // Radius along X radius[1] = command.GetValueAsInt ("BOBFNeighY", "nbdy"); // Radius along Y radius[2] = command.GetValueAsInt ("BOBFNeighZ", "nbdz"); // Radius along Z app->SetRadius (radius); typename ImageType::IndexType seed; seed[0] = command.GetValueAsInt ("BOBFSeedX", "seedx"); // Seed in X dimension; seed[1] = command.GetValueAsInt ("BOBFSeedY", "seedy"); // Seed in Y dimension; seed[2] = command.GetValueAsInt ("BOBFSeedZ", "seedz"); // Seed in Z dimension; app->SetSeed (seed); } std::cout << "Setting Default PixelValue: " << command.GetValueAsInt ("BOBFBgnd", "bgnd") << "."<<std::endl; app->SetDefaultPixelValue (command.GetValueAsInt ("BOBFBgnd", "bgnd")); std::cout << "Running Thirion Registration" << std::endl; try { app->Execute (); } catch (itk::ExceptionObject & err) { std::cout << "Caught an ITK exception: " << std::endl; std::cout << err << " " << __FILE__ << " " << __LINE__ << std::endl; throw err; } catch (...) { std:: cout << "Caught a non-ITK exception " << __FILE__ << " " << __LINE__ << std::endl; } return ; } //This function processes the output data type. template < class PixelType > void ProcessOutputType (MetaCommand command) { const std::string OutType (command. GetValueAsString ("OutputPixelType", "PixelType")); if (command.GetValueAsString ("OutputPixelType", "PixelType") != "") { // process the string for the data type if (CompareNoCase (OutType.c_str (), std::string ("UCHAR")) == 0) { ThirionFunction < PixelType, unsigned char > (command); } else if (CompareNoCase (OutType.c_str (), std::string ("SHORT")) == 0) { ThirionFunction < PixelType, short > (command); } else if (CompareNoCase (OutType.c_str (), std::string ("USHORT")) == 0) { ThirionFunction < PixelType, unsigned short > (command); } else if (CompareNoCase (OutType.c_str (), std::string ("INT")) == 0) { ThirionFunction < PixelType, int > (command); } else if (CompareNoCase (OutType.c_str (), std::string ("FLOAT")) == 0) { ThirionFunction < PixelType, float > (command); } else { std::cout << "Error. Invalid data type for -outtype! Use one of these:" << std::endl; PrintDataTypeStrings (); exit (-1); } } else { ThirionFunction < PixelType, float > (command); } } int ThrionRegistrationPrimary(int argc, char *argv[]) { MetaCommand command; //Moving image filename. command.SetOption("InputFilename","input",true,"InputFile name"); command.AddOptionField("InputFilename","filename",MetaCommand::STRING,true); //Output image filename. command.SetOption("OutputFilename","output",true,"OutputFile name"); command.AddOptionField("OutputFilename","filename",MetaCommand::STRING,true); //Target image filename. command.SetOption("TargetFilename","target",true,"TargetFile name"); command.AddOptionField("TargetFilename","filename",MetaCommand::STRING,true); //Parameter filename containing histogram parameters and number of resolution levels. command.SetOption("ParameterFilename","p",true,"ParameterFile name"); command.AddOptionField("ParameterFilename","filename",MetaCommand::STRING,true); command.SetOption("InputPixelType","intype",true,"InputPixel Type UCHAR|SHORT|USHORT|INT|FLOAT"); command.AddOptionField("InputPixelType","PixelType",MetaCommand::STRING,true); //The images will be written in this type. The default is input pixel type. command.SetOption("OutputPixelType","outtype",false,"OutputPixel Type UCHAR|SHORT|USHORT|INT|FLOAT"); command.AddOptionField("OutputPixelType","PixelType",MetaCommand::STRING,false); //The prefix of the displacementfield to be written. X,Y,Z displacement fields will be written with the prefix added to them. command.SetOption("DisplacementField","dispfields",false,"DisplacementField Prefix"); command.AddOptionField("DisplacementField","Prefix",MetaCommand::STRING,false); //Checkerboard option gives the checker image of the fixed image and the output image. command.SetOption("CheckerboardFilename","checkerbd",false,"CheckerFile name"); command.AddOptionField("CheckerboardFilename","filename",MetaCommand::STRING,false); //Checker patterns for the checker board image. command.SetOption("CheckerPattern","cbpattern",false,"CheckerBoard Pattern"); command.AddOptionField("CheckerPattern","XPattern",MetaCommand::INT,false,"4"); command.AddOptionField("CheckerPattern","YPattern",MetaCommand::INT,false,"4"); command.AddOptionField("CheckerPattern","ZPattern",MetaCommand::INT,false,"4"); //Writes the deformation field to the filename specified by this option. command.SetOption("OutputDeformationFieldname","defwrite",false,"Deformation Field Output."); command.AddOptionField("OutputDeformationFieldname","filename",MetaCommand::STRING,false); //This option allows to warp and write the normalized images to output. In normalized images the image values are shfit-scaled to be between 0 and 1 command.SetOption("Normalize","norm",false,"Warp Normalized Images."); command.AddOptionField("Normalize","norm",MetaCommand::FLAG,false); //This Option helps you to write the images after each step command.SetOption("DEBUG","debug",false,"Write intermediate Images."); command.AddOptionField("DEBUG","debug",MetaCommand::FLAG,false); //Make BOBF images. command.SetOption("BOBF","bobf",false,"Make BOBF Images (use -debug flag to view results)"); command.AddOptionField("BOBF","bobf",MetaCommand::FLAG,false); //BOBF Fixed Mask filename. command.SetOption("BOBFTargetMaskname","tgmask",false,"Target Mask name to perform BOBF"); command.AddOptionField("BOBFTargetMaskname","tgmask",MetaCommand::STRING, false); //BOBF Moving Mask filename. command.SetOption("BOBFTemplateMaskname","tmpmask",false,"Template Mask name to perform BOBF"); command.AddOptionField("BOBFTemplateMaskname","tmpgmask",MetaCommand::STRING, false); //Lower Threshold for the BOBF command.SetOption("BOBFLtshd","ltshd",false,"Lower Threshold for performing BOBF. Default 0"); command.AddOptionField("BOBFLtshd","ltshd",MetaCommand::INT,false,"0"); //Backgrnd Replace Value for the BOBF command.SetOption("BOBFBgnd","bgnd",false,"Background fill with this value Default 0"); command.AddOptionField("BOBFBgnd","bgnd",MetaCommand::INT,false,"0"); //Upper Threshold for the BOBF command.SetOption("BOBFUtshd","utshd",false,"Upper Threshold for performing BOBF. Default 70"); command.AddOptionField("BOBFUtshd","utshd",MetaCommand::INT,false,"70"); //Seed X for BOBF command.SetOption("BOBFSeedX","seedx",false,"Seed X for BOBF. Default 0"); command.AddOptionField("BOBFSeedX","seedx",MetaCommand::INT,false,"0"); //Seed Y for BOBF command.SetOption("BOBFSeedY","seedy",false,"Seed Y for BOBF. Default 0"); command.AddOptionField("BOBFSeedY","seedy",MetaCommand::INT,false,"0"); //Seed Z for BOBF command.SetOption("BOBFSeedZ","seedz",false,"Seed Z for BOBF. Default 0"); command.AddOptionField("BOBFSeedZ","seedz",MetaCommand::INT,false,"0"); //X Neighborhood to be included for BOBF command.SetOption("BOBFNeighX","nbdx",false,"X Neighborhood to be included for BOBF. Default 1"); command.AddOptionField("BOBFNeighX","nbdx",MetaCommand::INT,false,"1"); //Y Neighborhood to be included for BOBF command.SetOption("BOBFNeighY","nbdy",false,"Y Neighborhood to be included for BOBF. Default 1"); command.AddOptionField("BOBFNeighY","nbdy",MetaCommand::INT,false,"1"); //Z Neighborhood to be included for BOBF command.SetOption("BOBFNeighZ","nbdz",false,"Z Neighborhood to be included for BOBF. Default 1"); command.AddOptionField("BOBFNeighZ","nbdz",MetaCommand::INT,false,"1"); command.SetOption("Median","median",false,"Apply median filter to input images"); command.AddOptionField("Median","radius",MetaCommand::INT,false,"0"); command.SetOption("InitialTransform","InitialTransform",false,"Initial Transform for registration"); command.AddOptionField("InitialTransform","filename",MetaCommand::STRING,false,""); if (!command.Parse(argc,argv)) { return 1; } std::cout << "Running as: \n"; for(int i=0; i<argc; i++) { std::cout << " " << argv[i]; } std::cout << std::endl; //Test if the input data type is valid const std::string PixelType(command.GetValueAsString("InputPixelType","PixelType")); if ( command.GetValueAsString("InputPixelType","PixelType") != "") { // check to see if valid type if (( CompareNoCase( PixelType.c_str(), std::string("UCHAR" ) ) ) && ( CompareNoCase( PixelType.c_str(), std::string("SHORT" ) ) ) && ( CompareNoCase( PixelType.c_str(), std::string("USHORT") ) ) && ( CompareNoCase( PixelType.c_str(), std::string("INT" ) ) ) && ( CompareNoCase( PixelType.c_str(), std::string("FLOAT" ) ) ) ) { std::cout << "Error. Invalid data type string specified with -intype!" << std::endl; std::cout << "Use one of the following:" << std::endl; PrintDataTypeStrings(); exit(-1); } } const std::string OutPixelType(command.GetValueAsString("OutputPixelType", "PixelType" )); if ( command.GetValueAsString("OutputPixelType","PixelType" ) != "") { // check to see if valid type if( ( CompareNoCase( OutPixelType.c_str(), std::string("UCHAR" ) ) ) && ( CompareNoCase( OutPixelType.c_str(), std::string("SHORT") ) ) && ( CompareNoCase( OutPixelType.c_str(), std::string("USHORT") ) ) && ( CompareNoCase( OutPixelType.c_str(), std::string("INT" ) ) ) && ( CompareNoCase( OutPixelType.c_str(), std::string("FLOAT" ) ) ) ) { std::cout << "Error. Invalid data type string specified with -intype!" << std::endl; std::cout << "Use one of the following:" << std::endl; PrintDataTypeStrings(); exit(-1); } } //Call the process output data type function based on the input data type. const std::string InType(command.GetValueAsString("InputPixelType", "PixelType")); if (CompareNoCase (InType, std::string ("UCHAR")) == 0) { ProcessOutputType < unsigned char > (command); } else if (CompareNoCase (InType, std::string ("SHORT")) == 0) { ProcessOutputType < short > (command); } else if (CompareNoCase (InType, std::string ("USHORT")) == 0) { ProcessOutputType < unsigned short > (command); } else if (CompareNoCase (InType, std::string ("INT")) == 0) { ProcessOutputType < int > (command); } else if (CompareNoCase (InType, std::string ("FLOAT")) == 0) { ProcessOutputType < float > (command); } else { std::cout << "Error. Invalid data type for -intype! Use one of these:" << std::endl; PrintDataTypeStrings (); exit (-1); } return 0; }
41.530093
157
0.643777
Piyusha23
6426db6d2a533df9a3b75ea5d593d82079b85a8a
11,704
cpp
C++
src/graphics/scene/BoardRenderable.cpp
petuzk/Warcaby
2102493199c7edf9ea752dfcb374435d5b9049fd
[ "MIT" ]
null
null
null
src/graphics/scene/BoardRenderable.cpp
petuzk/Warcaby
2102493199c7edf9ea752dfcb374435d5b9049fd
[ "MIT" ]
null
null
null
src/graphics/scene/BoardRenderable.cpp
petuzk/Warcaby
2102493199c7edf9ea752dfcb374435d5b9049fd
[ "MIT" ]
null
null
null
#include "inc/graphics/scene/BoardRenderable.hpp" #include "src/game/board/Board_template.cpp" #include "src/graphics/scene/CheckerRenderable_template.cpp" rl::Model BoardRenderable::rlModel = { 0 }; int BoardRenderable::shaderHlFromLoc[SHADER_MAX_HIGHLIGHTS]; int BoardRenderable::shaderHlToLoc[SHADER_MAX_HIGHLIGHTS]; int BoardRenderable::shaderHlColorLoc[SHADER_MAX_HIGHLIGHTS]; const rl::Vector3 BoardRenderable::CAMERA_TARGET = { 0.0f, 0.5f, 0.0f }; BoardRenderable::BoardRenderable(): Renderable(Renderable::T3D), Updatable(Priority::PBoardRenderable) { if (rlModel.meshCount == 0) { // Generacja modeli planszy static constexpr float width = 9.0f; static constexpr float height = 1.0f; static constexpr float length = 9.0f; rl::Mesh topMesh = rl::GenMeshPlane(width, length, 5, 5); rl::Mesh sideMesh = { 0 }; sideMesh.vboId = new unsigned int[7]; sideMesh.vertexCount = 16; sideMesh.triangleCount = 8; float vertices[] = { -width/2, -height, length/2, width/2, -height, length/2, width/2, 0, length/2, -width/2, 0, length/2, -width/2, -height, -length/2, -width/2, 0, -length/2, width/2, 0, -length/2, width/2, -height, -length/2, width/2, -height, -length/2, width/2, 0, -length/2, width/2, 0, length/2, width/2, -height, length/2, -width/2, -height, -length/2, -width/2, -height, length/2, -width/2, 0, length/2, -width/2, 0, -length/2 }; float texcoords[] = { 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, }; float normals[] = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,-1.0f, 0.0f, 0.0f,-1.0f, 0.0f, 0.0f,-1.0f, 0.0f, 0.0f,-1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f }; sideMesh.vertices = new float[sideMesh.vertexCount * 3]; std::memcpy(sideMesh.vertices, vertices, sideMesh.vertexCount*3*sizeof(float)); sideMesh.texcoords = new float[sideMesh.vertexCount * 2]; std::memcpy(sideMesh.texcoords, texcoords, sideMesh.vertexCount*2*sizeof(float)); sideMesh.normals = new float[sideMesh.vertexCount * 3]; std::memcpy(sideMesh.normals, normals, sideMesh.vertexCount*3*sizeof(float)); sideMesh.indices = new unsigned short[sideMesh.triangleCount * 3]; for (int i = 0, k = 0; i < sideMesh.triangleCount*3; i+=6, k+=4) { sideMesh.indices[i+0] = k; sideMesh.indices[i+1] = k+1; sideMesh.indices[i+2] = k+2; sideMesh.indices[i+3] = k; sideMesh.indices[i+4] = k+2; sideMesh.indices[i+5] = k+3; } rl::rlLoadMesh(&sideMesh, false); // kolejny "bezpiecznik" -- obraz się nie załaduje gdy zmienimy rozmiar planszy a nie dodamy odpowiedniego obrazu rl::Texture2D topAlbedoTex = rl::LoadTexture(rl::TextFormat("resources/images/board/%dx%d_top_albedo.png", BoardConst::SIZE, BoardConst::SIZE)); rl::Texture2D topNormalTex = rl::LoadTexture(rl::TextFormat("resources/images/board/%dx%d_top_normal.png", BoardConst::SIZE, BoardConst::SIZE)); rl::Texture2D sideAlbedoTex = rl::LoadTexture("resources/images/board/side_albedo.png"); rl::Texture2D sideNormalTex = rl::LoadTexture("resources/images/board/side_normal.png"); rl::Shader shader = ShaderProvider::getInstance()->loadShader("resources/shaders/base.vs", "resources/shaders/board.fs"); shader.locs[rl::LOC_MAP_ALBEDO] = rl::GetShaderLocation(shader, "albedoSampler"); shader.locs[rl::LOC_MAP_NORMAL] = rl::GetShaderLocation(shader, "normalsSampler"); for (int i = 0; i < SHADER_MAX_HIGHLIGHTS; i++) { shaderHlFromLoc[i] = rl::GetShaderLocation(shader, rl::TextFormat("hlSquares[%d].from", i)); shaderHlToLoc[i] = rl::GetShaderLocation(shader, rl::TextFormat("hlSquares[%d].to", i)); shaderHlColorLoc[i] = rl::GetShaderLocation(shader, rl::TextFormat("hlSquares[%d].color", i)); } rlModel.transform = rl::MatrixIdentity(); rlModel.meshCount = 2; rlModel.meshes = new rl::Mesh[rlModel.meshCount]; rlModel.meshes[0] = topMesh; rlModel.meshes[1] = sideMesh; rlModel.materialCount = 2; rlModel.materials = new rl::Material[rlModel.materialCount]; rlModel.materials[0] = rl::LoadMaterialDefault(); rlModel.materials[0].shader = shader; rlModel.materials[0].maps[rl::MAP_ALBEDO].texture = topAlbedoTex; rlModel.materials[0].maps[rl::MAP_NORMAL].texture = topNormalTex; rlModel.materials[1] = rl::LoadMaterialDefault(); rlModel.materials[1].shader = shader; rlModel.materials[1].maps[rl::MAP_ALBEDO].texture = sideAlbedoTex; rlModel.materials[1].maps[rl::MAP_NORMAL].texture = sideNormalTex; rlModel.meshMaterial = new int[rlModel.meshCount]; rlModel.meshMaterial[0] = 0; rlModel.meshMaterial[1] = 1; } reset(); } void BoardRenderable::reset() { ifState = NONE; inputEnabled = true; delayedShaderUpdate = false; Board::reset<CheckerRenderable<CheckerMan>>(); } void BoardRenderable::setInputEnabled(bool en) { inputEnabled = en; if (!inputEnabled) { prevPointed = Square(); updateShaderColor(0); } else { delayedShaderUpdate = true; } } void BoardRenderable::draw() { rl::DrawModel(rlModel, (rl::Vector3){ 0.0f, 0.0f, 0.0f }, 1.0f, rl::WHITE); } void BoardRenderable::requestMoveFor(HumanPlayer* player, std::shared_ptr<PlayerMoveSequence> sequence) { updateShaderColor(0); delayedShaderUpdate = true; moveForPlayer = player; moveSequence = sequence; prevPointed = selectedMoveSquare = reSelectedCheckerSquare = Square(); if (sequence->getOriginsForNextMove().size() > 1) { ifState = SELECT_CHECKER; possibleMoves.clear(); selectedCheckerSquare = Square(); } else { Square start = sequence->getOriginsForNextMove().at(0); std::shared_ptr<Checker> c = at(start); if (c == nullptr || c->getSide() != player->getSide()) throw std::logic_error("bad move selection origin"); ifState = SELECT_MOVE; possibleMoves = c->getPossibleMoves(this, moveSequence); selectedCheckerSquare = start; } Camera::getInstance()->moveToSide(player->getSide()); } void BoardRenderable::update() { if (ifState == NONE || !inputEnabled) { return; } bool updateShader = delayedShaderUpdate; delayedShaderUpdate = false; Square pointed = getPointedSquare(); if (pointed != prevPointed) { prevPointed = pointed; std::shared_ptr<Checker> c = at(pointed); if (ifState == SELECT_CHECKER) { if ((c == nullptr || c->getSide() != moveForPlayer->getSide())) { if (selectedCheckerSquare) { selectedCheckerSquare = Square(); possibleMoves.clear(); updateShader = true; } } else { selectedCheckerSquare = pointed; if (moveSequence->isOriginForNextMove(selectedCheckerSquare)) { possibleMoves = c->getPossibleMoves(this, moveSequence); } else { possibleMoves.clear(); } updateShader = true; } } else if (ifState == SELECT_MOVE) { if (c == nullptr) { Square newSelectedMoveSquare = Square(); for (PlayerMove& move: possibleMoves) { Square dest = move.getDestination(); if (pointed == dest) { newSelectedMoveSquare = dest; break; } } if (selectedMoveSquare != newSelectedMoveSquare || reSelectedCheckerSquare) { reSelectedCheckerSquare = Square(); selectedMoveSquare = newSelectedMoveSquare; updateShader = true; } } else { if (c->getSide() != moveForPlayer->getSide()) { if (reSelectedCheckerSquare) { reSelectedCheckerSquare = Square(); updateShader = true; } } else if (moveSequence->isOriginForNextMove(pointed)) { reSelectedCheckerSquare = pointed; updateShader = true; } } } } if (rl::IsMouseButtonPressed(rl::MOUSE_LEFT_BUTTON)) { if (ifState == SELECT_CHECKER) { if (selectedCheckerSquare && moveSequence->isOriginForNextMove(selectedCheckerSquare)) { ifState = SELECT_MOVE; } } else if (ifState == SELECT_MOVE) { if (reSelectedCheckerSquare) { selectedCheckerSquare = reSelectedCheckerSquare; possibleMoves = at(selectedCheckerSquare)->getPossibleMoves(this, moveSequence); updateShader = true; } else { for (PlayerMove& move: possibleMoves) { if (selectedMoveSquare == move.getDestination()) { ifState = NONE; /* Jeżeli zastąpić to `updateShader = true;` i `break;`, to w efekcie końcowym wywołanie * Player::respond() doprowadzi do kolejnego wywołania BoardRenderable::requestMoveFor(), * które zmieni ifState oraz inne zmienne stanu, i wtedy wywołanie updateShaderData() niżej * narysuje te zmiany przed rozpoczęciem animacji. */ updateShaderData(); moveForPlayer->respond(move); return; } } } } } if (updateShader) { updateShaderData(); } } void BoardRenderable::updateShaderPos(int i, Square sq) { float xpos = sq.col() / 9.0f + 1.0f / 18.0f; float zpos = (BoardConst::SIZE - sq.row() - 1) / 9.0f + 1.0f / 18.0f; rl::SetShaderValue(rlModel.materials[0].shader, shaderHlFromLoc[i], (float[2]){ xpos, zpos }, rl::UNIFORM_VEC2); rl::SetShaderValue(rlModel.materials[0].shader, shaderHlToLoc[i], (float[2]){ xpos + 1.0f/9.0f, zpos + 1.0f/9.0f }, rl::UNIFORM_VEC2); } void BoardRenderable::updateShaderColor(int i, rl::Color c) { float color[4] = { c.r / 255.0f, c.g / 255.0f, c.b / 255.0f, c.a / 255.0f }; rl::SetShaderValue(rlModel.materials[0].shader, shaderHlColorLoc[i], &color, rl::UNIFORM_VEC4); } void BoardRenderable::updateShaderData() { int i = 0, size = possibleMoves.size(); if (SHADER_MAX_HIGHLIGHTS < size) // sytuacja (prawdopodobnie) niemożliwa size = SHADER_MAX_HIGHLIGHTS; rl::Shader shader = rlModel.materials[0].shader; if (ifState == NONE) { updateShaderColor(0); } else if (ifState == SELECT_CHECKER) { if (!selectedCheckerSquare) { updateShaderColor(0); } else { updateShaderPos(0, selectedCheckerSquare); if (size == 0) { updateShaderColor(0, rl::RED); // maroon, orange } else { updateShaderColor(0, rl::GREEN); //lime, darkgreen for ( ; i < size; i++) { updateShaderPos(i + 1, possibleMoves[i].getDestination()); updateShaderColor(i + 1, rl::BROWN); } } if (i + 1 < SHADER_MAX_HIGHLIGHTS) { updateShaderColor(i + 1); } } } else if (ifState == SELECT_MOVE) { updateShaderPos(0, selectedCheckerSquare); updateShaderColor(0, rl::GREEN); for ( ; i < size; i++) { Square dest = possibleMoves[i].getDestination(); updateShaderPos(i + 1, dest); updateShaderColor(i + 1, dest == selectedMoveSquare ? rl::BEIGE : rl::BROWN); } if (i + 1 < SHADER_MAX_HIGHLIGHTS && reSelectedCheckerSquare) { updateShaderPos(i + 1, reSelectedCheckerSquare); updateShaderColor(i + 1, rl::GREEN); i++; } if (i + 1 < SHADER_MAX_HIGHLIGHTS) { updateShaderColor(i + 1); } } } Square BoardRenderable::getPointedSquare() { static const rl::Vector3 triangles[] = { { -4.0f, 0.0f, -4.0f }, { 4.0f, 0.0f, 4.0f }, { 4.0f, 0.0f, -4.0f }, { -4.0f, 0.0f, -4.0f }, { -4.0f, 0.0f, 4.0f }, { 4.0f, 0.0f, 4.0f }, }; rl::Ray ray = Camera::getInstance()->getMouseRay(); rl::RayHitInfo hitInfo; for (int i = 0; i < 6; i += 3) { hitInfo = rl::GetCollisionRayTriangle(ray, triangles[i], triangles[i+1], triangles[i+2]); if (hitInfo.hit) { int xsq = hitInfo.position.x + 4.0f; int zsq = hitInfo.position.z + 4.0f; return Square(xsq, BoardConst::SIZE - zsq - 1); } } return Square(); }
30.558747
146
0.66285
petuzk
6428afc1bf1c0257688956df9929ef74b371df01
936
cpp
C++
libs/options/src/options/option_name_comparison.cpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/options/src/options/option_name_comparison.cpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/options/src/options/option_name_comparison.cpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <fcppt/strong_typedef_comparison.hpp> #include <fcppt/options/option_name.hpp> #include <fcppt/options/option_name_comparison.hpp> #include <fcppt/config/external_begin.hpp> #include <utility> #include <fcppt/config/external_end.hpp> bool fcppt::options::operator==( fcppt::options::option_name const &_left, fcppt::options::option_name const &_right ) { return _left.name_ == _right.name_ && _left.is_short_ == _right.is_short_; } bool fcppt::options::operator<( fcppt::options::option_name const &_left, fcppt::options::option_name const &_right ) { return std::make_pair( _left.name_, _left.is_short_ ) < std::make_pair( _right.name_, _right.is_short_ ); }
19.5
61
0.711538
pmiddend
642b4cbccd243e294bc48caca7b79bb1dd960dc3
33,871
cpp
C++
src/Graphics/Isosurface.cpp
llGuy/Ondine
325c2d3ea5bd5ef5456b0181c53ad227571fada3
[ "MIT" ]
1
2022-01-24T18:15:56.000Z
2022-01-24T18:15:56.000Z
src/Graphics/Isosurface.cpp
llGuy/Ondine
325c2d3ea5bd5ef5456b0181c53ad227571fada3
[ "MIT" ]
null
null
null
src/Graphics/Isosurface.cpp
llGuy/Ondine
325c2d3ea5bd5ef5456b0181c53ad227571fada3
[ "MIT" ]
null
null
null
#include "Math.hpp" #include "Terrain.hpp" #include "Isosurface.hpp" namespace Ondine::Graphics { const glm::vec3 Isosurface::NORMALIZED_CUBE_VERTICES[8] = { glm::vec3(-0.5f, -0.5f, -0.5f), glm::vec3(+0.5f, -0.5f, -0.5f), glm::vec3(-0.5f, +0.5f, -0.5f), glm::vec3(+0.5f, +0.5f, -0.5f), glm::vec3(-0.5f, -0.5f, +0.5f), glm::vec3(+0.5f, -0.5f, +0.5f), glm::vec3(-0.5f, +0.5f, +0.5f), glm::vec3(+0.5f, +0.5f, +0.5f), }; const glm::ivec3 Isosurface::NORMALIZED_CUBE_VERTEX_INDICES[8] = { glm::ivec3(0, 0, 0), glm::ivec3(1, 0, 0), glm::ivec3(0, 1, 0), glm::ivec3(1, 1, 0), glm::ivec3(0, 0, 1), glm::ivec3(1, 0, 1), glm::ivec3(0, 1, 1), glm::ivec3(1, 1, 1), }; void Isosurface::init(const QuadTree &quadTree, VulkanContext &graphicsContext) { mGPUVerticesAllocator.init( 10000, (VulkanBufferFlagBits)VulkanBufferFlag::VertexBuffer, graphicsContext); mIsoGroups.init(1000); mIsoGroupIndices.init(); mVertexPool = (IsoVertex *)malloc( sizeof(IsoVertex) * 10000 * 4096); auto maxUpdateCount = quadTree.mDimensions * quadTree.mDimensions * 2; mFullUpdates = new IsoGroup *[maxUpdateCount]; mTransitionUpdates = new IsoGroup *[maxUpdateCount]; mFullUpdateCount = 0; mTransitionUpdateCount = 0; } void Isosurface::bindToTerrain(const Terrain &terrain) { mScale = terrain.mTerrainScale; mSurfaceDensity = {30000}; } void Isosurface::prepareForUpdate(QuadTree &quadTree, Terrain &terrain) { mScale = terrain.mTerrainScale; // Generates normals for updated chunks only terrain.generateVoxelNormals(); /* Step #1: Figure out which chunk groups to delete and to create Step #2: Figure out which chunk groups to update the meshes for Step #3: Figure out which chunk groups contained modified chunks Step #4: Update those damn chunk groups (BONUS) Make step #2 distinguish between chunk groups which require just mesh transitions or everything to be updated */ // Step #1 for (auto deletion : quadTree.mDiffDelete) { QuadTree::Node *node = deletion.node; glm::ivec2 offset = {node->offsetx, node->offsety}; // How many chunks does this node encompass int width = pow(2, quadTree.mMaxLOD - node->level); for (int z = offset.y; z < offset.y + width; ++z) { for (int x = offset.x; x < offset.x + width; ++x) { glm::ivec2 offset = quadTreeCoordsToChunk(quadTree, {x, z}); IsoGroup *lowest = getFirstFlatIsoGroup(offset); if (lowest) { mFlatIsoGroupIndices.remove(hashFlatChunkCoord(offset)); while (lowest) { // Delete the chunk group auto nextKey = lowest->next; freeIsoGroup(lowest); if (nextKey == INVALID_CHUNK_INDEX) { break; } else { lowest = mIsoGroups[nextKey]; } } } } } } // Step #2 for (auto addition : quadTree.mDiffAdd) { QuadTree::Node *node = addition.node; auto deepestNodes = quadTree.getDeepestNodesUnder(node); for (auto nodeInfo : deepestNodes) { glm::ivec2 offset = quadTreeCoordsToChunk(quadTree, nodeInfo.offset); int width = pow(2, quadTree.mMaxLOD - nodeInfo.level); // Generate chunk groups for (int z = offset.y; z < offset.y + width; ++z) { for (int x = offset.x; x < offset.x + width; ++x) { // For now we assume that the terrain doesn't get modified Chunk *current = terrain.getFirstFlatChunk(glm::ivec2(x, z)); while (current) { glm::ivec3 groupCoord = getIsoGroupCoord( quadTree, current->chunkCoord); IsoGroup *group = getIsoGroup(groupCoord); group->level = nodeInfo.level; current->chunkGroupKey = group->key; int stride = (int)pow(2, quadTree.mMaxLOD - nodeInfo.level); float width = stride; glm::vec3 chunkCoordOffset = (glm::vec3)( current->chunkCoord - groupCoord); glm::vec3 start = (float)CHUNK_DIM * (chunkCoordOffset / width); for (int z = 0 ; z < CHUNK_DIM / stride; ++z) { for (int y = 0 ; y < CHUNK_DIM / stride; ++y) { for (int x = 0 ; x < CHUNK_DIM / stride; ++x) { glm::ivec3 coord = glm::ivec3(x, y, z); uint32_t dstVIndex = getVoxelIndex(coord + (glm::ivec3)start); uint32_t srcVIndex = getVoxelIndex(coord * stride); group->voxels[dstVIndex] = current->voxels[srcVIndex]; } } } // Need to add transition updates for neighbouring chunk groups if (!group->pushedToFullUpdates) { mFullUpdates[mFullUpdateCount++] = group; group->pushedToFullUpdates = 1; } if (current->next == INVALID_CHUNK_INDEX) { current = nullptr; } else { current = terrain.mLoadedChunks[current->next]; } } } } } } for (auto addition : quadTree.mDiffAdd) { QuadTree::Node *node = addition.node; int width = pow(2, quadTree.mMaxLOD - node->level); glm::ivec2 qtCoord = {node->offsetx, node->offsety}; glm::ivec2 chunkCoord = quadTreeCoordsToChunk(quadTree, qtCoord); int components[] = { // Z, Z, X, X 2, 2, 0, 0 }; glm::ivec2 offsets[] = { {-1, 0}, {width, 0}, {0, -1}, {0, width} }; glm::ivec2 nav[] = { {0, 1}, {0, 1}, {1, 0}, {1, 0} }; // Check neighbouring chunk groups for (int i = 0; i < 4; ++i) { glm::ivec2 adjNodeCoord = qtCoord + offsets[i]; auto adjNodeInfo = quadTree.getNodeInfo((glm::vec2)adjNodeCoord); if (adjNodeInfo.exists && !adjNodeInfo.wasDiffed) { // (hmmm?) Transitions only need to be done for nodes with lower LOD glm::ivec2 adjChunkCoord = quadTreeCoordsToChunk( quadTree, adjNodeInfo.offset); int comp3D = components[i]; int comp2D = comp3D / 2; while ( adjChunkCoord[comp2D] < chunkCoord[comp2D] + width && adjNodeInfo.exists) { int adjWidth = pow(2, quadTree.mMaxLOD - adjNodeInfo.level); // Do something IsoGroup *lowest = getFirstFlatIsoGroup(adjChunkCoord); while (lowest) { if (!lowest->pushedToFullUpdates && !lowest->pushedToTransitionUpdates) { lowest->pushedToTransitionUpdates = 1; mTransitionUpdates[mTransitionUpdateCount++] = lowest; } auto nextKey = lowest->next; if (nextKey == INVALID_CHUNK_INDEX) { break; } else { lowest = mIsoGroups[nextKey]; } } adjChunkCoord[comp2D] += adjWidth; adjNodeCoord[comp2D] += adjWidth; adjNodeInfo = quadTree.getNodeInfo((glm::vec2)adjNodeCoord); } } } } // For isogroups containing updated chunks, make sure to update voxel values for (int i = 0; i < terrain.mUpdatedChunks.size; ++i) { Chunk *chunk = terrain.mLoadedChunks[terrain.mUpdatedChunks[i]]; glm::ivec3 groupCoord = getIsoGroupCoord( quadTree, chunk->chunkCoord); IsoGroup *group = getIsoGroup(groupCoord); if (!group->pushedToFullUpdates) { mFullUpdates[mFullUpdateCount++] = group; group->pushedToFullUpdates = 1; glm::vec2 quadTreeCoord = glm::vec2(groupCoord.x, groupCoord.z) + glm::vec2(glm::pow(2.0f, quadTree.mMaxLOD - 1)); auto nodeInfo = quadTree.getNodeInfo(quadTreeCoord); group->level = nodeInfo.level; chunk->chunkGroupKey = group->key; int stride = (int)pow(2, quadTree.mMaxLOD - nodeInfo.level); float width = stride; glm::vec3 chunkCoordOffset = (glm::vec3)( chunk->chunkCoord - groupCoord); glm::vec3 start = (float)CHUNK_DIM * (chunkCoordOffset / width); for (int z = 0 ; z < CHUNK_DIM / stride; ++z) { for (int y = 0 ; y < CHUNK_DIM / stride; ++y) { for (int x = 0 ; x < CHUNK_DIM / stride; ++x) { glm::ivec3 coord = glm::ivec3(x, y, z); uint32_t dstVIndex = getVoxelIndex(coord + (glm::ivec3)start); uint32_t srcVIndex = getVoxelIndex(coord * stride); group->voxels[dstVIndex] = chunk->voxels[srcVIndex]; } } } } } terrain.clearUpdatedChunks(); quadTree.clearDiff(); Voxel surfaceDensity = {(uint16_t)30000}; uint32_t vertexCounter = 0; for (int i = 0; i < mFullUpdateCount; ++i) { IsoGroup *group = mFullUpdates[i]; uint32_t groupVertexCount = generateVertices( {terrain, quadTree, *group}, mVertexPool + vertexCounter); group->vertexCount = groupVertexCount; group->verticesMem = mVertexPool + vertexCounter; vertexCounter += groupVertexCount; groupVertexCount = generateTransVoxelVertices( {terrain, quadTree, *group}, mVertexPool + vertexCounter); group->transVoxelVertexCount = groupVertexCount; group->transVerticesMem = mVertexPool + vertexCounter; vertexCounter += groupVertexCount; } for (int i = 0; i < mTransitionUpdateCount; ++i) { IsoGroup *group = mTransitionUpdates[i]; uint32_t groupVertexCount = generateTransVoxelVertices( {terrain, quadTree, *group}, mVertexPool + vertexCounter); group->transVoxelVertexCount = groupVertexCount; group->transVerticesMem = mVertexPool + vertexCounter; vertexCounter += groupVertexCount; } } void Isosurface::syncWithGPU(const VulkanCommandBuffer &commandBuffer) { if (mFullUpdateCount) { for (int i = 0; i < mFullUpdateCount; ++i) { IsoGroup *group = mFullUpdates[i]; group->pushedToFullUpdates = 0; group->pushedToTransitionUpdates = 0; if (group->vertices.size()) { // This chunk already has allocated memory mGPUVerticesAllocator.free(group->vertices); } if (group->transVoxelVertices.size()) { // This chunk already has allocated memory mGPUVerticesAllocator.free(group->transVoxelVertices); } if (group->vertexCount) { auto slot = mGPUVerticesAllocator.allocate( sizeof(IsoVertex) * group->vertexCount); slot.write( commandBuffer, group->verticesMem, sizeof(IsoVertex) * group->vertexCount); group->vertices = slot; } else { group->vertices = {}; } if (group->transVoxelVertexCount) { auto slot = mGPUVerticesAllocator.allocate( sizeof(IsoVertex) * group->transVoxelVertexCount); slot.write( commandBuffer, group->transVerticesMem, sizeof(IsoVertex) * group->transVoxelVertexCount); group->transVoxelVertices = slot; } else { group->transVoxelVertices = {}; } } mFullUpdateCount = 0; mGPUVerticesAllocator.debugLogState(); } if (mTransitionUpdateCount) { for (int i = 0; i < mTransitionUpdateCount; ++i) { IsoGroup *group = mTransitionUpdates[i]; group->pushedToFullUpdates = 0; group->pushedToTransitionUpdates = 0; if (group->transVoxelVertices.size()) { // This chunk already has allocated memory mGPUVerticesAllocator.free(group->transVoxelVertices); } if (group->transVoxelVertexCount) { auto slot = mGPUVerticesAllocator.allocate( sizeof(IsoVertex) * group->transVoxelVertexCount); slot.write( commandBuffer, group->transVerticesMem, sizeof(IsoVertex) * group->transVoxelVertexCount); group->transVoxelVertices = slot; } else { group->transVoxelVertices = {}; } } mTransitionUpdateCount = 0; mGPUVerticesAllocator.debugLogState(); } } uint32_t Isosurface::hashIsoGroupCoord(const glm::ivec3 &coord) const { struct { union { struct { uint32_t padding: 2; uint32_t x: 10; uint32_t y: 10; uint32_t z: 10; }; uint32_t value; }; } hasher; hasher.value = 0; hasher.x = *(uint32_t *)(&coord.x); hasher.y = *(uint32_t *)(&coord.y); hasher.z = *(uint32_t *)(&coord.z); return (uint32_t)hasher.value; } glm::ivec3 Isosurface::getIsoGroupCoord( const QuadTree &quadTree, const glm::ivec3 &chunkCoord) const { glm::ivec2 quadTreeCoord = glm::ivec2(chunkCoord.x, chunkCoord.z) + glm::ivec2(glm::pow(2, quadTree.maxLOD() - 1)); QuadTree::NodeInfo node = quadTree.getNodeInfo(quadTreeCoord); node.offset -= glm::vec2(glm::pow(2.0f, quadTree.maxLOD() - 1)); glm::ivec3 coord = glm::ivec3(node.offset.x, chunkCoord.y, node.offset.y); // Round down the nearest 2^node.level int width = pow(2, quadTree.maxLOD() - node.level); coord.y = (int)(glm::floor( (float)coord.y / (float)width)) * width; return coord; } IsoGroup *Isosurface::getIsoGroup(const glm::ivec3 &coord) { uint32_t hash = hashIsoGroupCoord(coord); uint32_t *index = mIsoGroupIndices.get(hash); if (index) { // Chunk was already added return mIsoGroups[*index]; } else { IsoGroup *group = flAlloc<IsoGroup>(); auto key = mIsoGroups.add(group); zeroMemory(group); group->coord = coord; group->key = key; mIsoGroupIndices.insert(hash, key); addToFlatIsoGroupIndices(group); return group; } } void Isosurface::freeIsoGroup(IsoGroup *group) { uint32_t hash = hashIsoGroupCoord(group->coord); mIsoGroupIndices.remove(hash); if (group->vertices.size()) { mGPUVerticesAllocator.free(group->vertices); } if (group->transVoxelVertices.size()) { mGPUVerticesAllocator.free(group->transVoxelVertices); } mIsoGroups.remove(group->key); // This is temporary - TODO: Add pre-allocated space for chunk groups flFree(group); } glm::ivec2 Isosurface::quadTreeCoordsToChunk( const QuadTree &quadTree, glm::ivec2 offset) const { return offset - glm::ivec2(pow(2, quadTree.maxLOD() - 1)); } // One unit in offset = chunk coord. The origin of the quadtree is at 0,0 glm::ivec2 Isosurface::quadTreeCoordsToWorld( const QuadTree &quadTree, glm::ivec2 offset) const { offset -= glm::ivec2(pow(2, quadTree.maxLOD() - 1)); offset *= CHUNK_DIM * mScale; return offset; } glm::vec2 Isosurface::worldToQuadTreeCoords( const QuadTree &quadTree, glm::vec2 offset) const { offset /= (CHUNK_DIM * mScale); offset += glm::vec2(glm::pow(2.0f, quadTree.maxLOD() - 1)); return offset; } void Isosurface::addToFlatIsoGroupIndices(IsoGroup *group) { int x = group->coord.x, z = group->coord.z; uint32_t hash = hashFlatChunkCoord(glm::ivec2(x, z)); uint32_t *index = mFlatIsoGroupIndices.get(hash); if (index) { IsoGroup *head = mIsoGroups[*index]; group->next = head->key; *index = group->key; } else { mFlatIsoGroupIndices.insert(hash, group->key); group->next = INVALID_CHUNK_INDEX; } } IsoGroup *Isosurface::getFirstFlatIsoGroup(glm::ivec2 flatCoord) { uint32_t hash = hashFlatChunkCoord(flatCoord); uint32_t *index = mFlatIsoGroupIndices.get(hash); if (index) { return mIsoGroups[*index]; } else { return nullptr; } } uint32_t Isosurface::generateVertices( GenIsoGroupVerticesParams params, IsoVertex *meshVertices) { const auto &terrain = params.terrain; const auto &quadTree = params.quadTree; const auto &group = params.group; int groupSize = pow(2, quadTree.mMaxLOD - group.level); int stride = groupSize; // glm::ivec3 groupCoord = group.coord + glm::ivec3( // pow(2, mQuadTree.mMaxLOD - 1)); glm::ivec3 groupStart = group.coord * (int)CHUNK_DIM; // TODO: Optimise the getVoxel operation auto getVoxel = [&terrain, &groupSize, &groupStart]( uint32_t x, uint32_t y, uint32_t z) { return terrain.getVoxel(groupStart + glm::ivec3(x, y, z) * groupSize); }; auto getVoxelLOD = [&terrain, &groupSize, &groupStart, &stride]( uint32_t x, uint32_t y, uint32_t z, // Offset uint32_t ox, uint32_t oy, uint32_t oz) { return terrain.getVoxel( groupStart + glm::ivec3(x, y, z) * groupSize + glm::ivec3(ox, oy, oz) * stride / 2); }; uint32_t vertexCount = 0; for (uint32_t z = 1; z < CHUNK_DIM - 1; ++z) { for (uint32_t y = 1; y < CHUNK_DIM - 1; ++y) { for (uint32_t x = 1; x < CHUNK_DIM - 1; ++x) { Voxel voxelValues[8] = { group.voxels[getVoxelIndex(x, y, z)], group.voxels[getVoxelIndex(x + 1, y, z)], group.voxels[getVoxelIndex(x, y + 1, z)], group.voxels[getVoxelIndex(x + 1, y + 1, z)], group.voxels[getVoxelIndex(x, y, z + 1)], group.voxels[getVoxelIndex(x + 1, y, z + 1)], group.voxels[getVoxelIndex(x, y + 1, z + 1)], group.voxels[getVoxelIndex(x + 1, y + 1, z + 1)], }; updateVoxelCell( voxelValues, glm::ivec3(x, y, z), meshVertices, vertexCount); } } } return vertexCount; } uint32_t Isosurface::generateTransVoxelVertices( GenIsoGroupVerticesParams params, IsoVertex *meshVertices) { const auto &terrain = params.terrain; const auto &quadTree = params.quadTree; const auto &group = params.group; uint32_t vertexCount = 0; glm::ivec3 groupCoord = group.coord + glm::ivec3( pow(2, quadTree.mMaxLOD - 1)); updateIsoGroupFace( params, 0, 1, // Inner axis is X, outer axis is Y 2, 1, // We are updating the positive Z face meshVertices, vertexCount); updateIsoGroupFace( params, 0, 1, // Inner axis is X, outer axis is Y 2, 0, // We are updating the negative Z face meshVertices, vertexCount); updateIsoGroupFace( params, 1, 2, // Inner axis is Y, outer axis is Z 0, 1, // We are updating the positive X face meshVertices, vertexCount); updateIsoGroupFace( params, 1, 2, // Inner axis is Y, outer axis is Z 0, 0, // We are updating the negative X face meshVertices, vertexCount); updateIsoGroupFace( params, 0, 2, // Inner axis is x, outer axis is Z 1, 1, // We are updating the positive Y face meshVertices, vertexCount); updateIsoGroupFace( params, 0, 2, // Inner axis is X, outer axis is Z 1, 0, // We are updating the negative Y face meshVertices, vertexCount); return vertexCount; } void Isosurface::updateIsoGroupFace( GenIsoGroupVerticesParams params, uint32_t primaryAxis, uint32_t secondAxis, uint32_t faceAxis, uint32_t side, IsoVertex *meshVertices, uint32_t &vertexCount) { const auto &terrain = params.terrain; const auto &quadTree = params.quadTree; const auto &group = params.group; int groupSize = pow(2, quadTree.mMaxLOD - group.level); glm::ivec3 groupStart = group.coord * (int)CHUNK_DIM; int stride = groupSize; glm::ivec3 groupCoordOffset = glm::ivec3(0); groupCoordOffset[faceAxis] = (int)side * 2 - 1; glm::ivec3 adjacentCoord = group.coord + glm::ivec3( pow(2, quadTree.mMaxLOD - 1)); if (side == 1) { adjacentCoord += groupCoordOffset * groupSize; } else { adjacentCoord += groupCoordOffset; } QuadTree::NodeInfo adjacentNode = quadTree.getNodeInfo( glm::vec2(adjacentCoord.x, adjacentCoord.z)); if (adjacentNode.exists) { static const glm::ivec3 offsets[8] = { {0, 0, 0}, {1, 0, 0}, {0, 1, 0}, {1, 1, 0}, {0, 0, 1}, {1, 0, 1}, {0, 1, 1}, {1, 1, 1}, }; auto getVoxel = [&terrain, &groupSize, &groupStart]( uint32_t x, uint32_t y, uint32_t z) { return terrain.getVoxel(groupStart + glm::ivec3(x, y, z) * groupSize); }; auto getVoxelLOD = [&terrain, &groupSize, &groupStart, &stride]( uint32_t x, uint32_t y, uint32_t z, // Offset uint32_t ox, uint32_t oy, uint32_t oz) { return terrain.getVoxel( groupStart + glm::ivec3(x, y, z) * groupSize + glm::ivec3(ox, oy, oz) * stride / 2); }; if (adjacentNode.level <= group.level) { uint32_t d2 = (CHUNK_DIM - 1) * side; for (uint32_t d1 = 0; d1 < CHUNK_DIM; ++d1) { for (uint32_t d0 = 0; d0 < CHUNK_DIM; ++d0) { Voxel voxelValues[8] = {}; for (int i = 0; i < 8; ++i) { glm::ivec3 voxelCoord = {}; voxelCoord[primaryAxis] = d0 + offsets[i][primaryAxis]; voxelCoord[secondAxis] = d1 + offsets[i][secondAxis]; voxelCoord[faceAxis] = d2 + offsets[i][faceAxis]; voxelValues[i] = getVoxel(voxelCoord.x, voxelCoord.y, voxelCoord.z); } glm::ivec3 coord = {}; coord[primaryAxis] = d0; coord[secondAxis] = d1; coord[faceAxis] = d2; updateVoxelCell(voxelValues, coord, meshVertices, vertexCount); } } } else { static const glm::ivec4 transOffsets[9] = { {0,0,0,0}, {0,0,1,0}, {1,0,0,0}, {0,0,0,1}, {0,0,1,1}, {1,0,0,1}, {0,1,0,0}, {0,1,1,0}, {1,1,0,0} }; uint32_t d2 = (CHUNK_DIM - 1) * side; for (uint32_t d1 = 0; d1 < CHUNK_DIM; ++d1) { for (uint32_t d0 = 0; d0 < CHUNK_DIM; ++d0) { Voxel voxelValues[8] = {}; for (int i = 0; i < 8; ++i) { glm::ivec3 voxelCoord = {}; voxelCoord[primaryAxis] = d0 + offsets[i][primaryAxis]; voxelCoord[secondAxis] = d1 + offsets[i][secondAxis]; voxelCoord[faceAxis] = d2 + offsets[i][faceAxis]; voxelValues[i] = getVoxel(voxelCoord.x, voxelCoord.y, voxelCoord.z); } Voxel transVoxels[13] = {}; for (int i = 0; i < 9; ++i) { glm::ivec3 voxelCoord = {}; voxelCoord[primaryAxis] = d0 + transOffsets[i][0]; voxelCoord[secondAxis] = d1 + transOffsets[i][1]; voxelCoord[faceAxis] = d2 + side; glm::ivec3 halfCoord = {}; halfCoord[primaryAxis] = transOffsets[i][2]; halfCoord[secondAxis] = transOffsets[i][3]; transVoxels[i] = getVoxelLOD( voxelCoord.x, voxelCoord.y, voxelCoord.z, halfCoord.x, halfCoord.y, halfCoord.z); } for (int i = 0; i < 4; ++i) { glm::ivec3 voxelCoord = {}; voxelCoord[primaryAxis] = d0 + offsets[i][0]; voxelCoord[secondAxis] = d1 + offsets[i][1]; voxelCoord[faceAxis] = d2 + side; transVoxels[i + 9] = getVoxel(voxelCoord.x, voxelCoord.y, voxelCoord.z); } static const int CUBE_AXIS_BITS[3][2][4] = { {{0, 2, 4, 6}, {1, 3, 5, 7}}, {{0, 1, 4, 5}, {2, 3, 6, 7}}, {{0, 1, 2, 3}, {4, 5, 6, 7}} }; for (int i = 0; i < 4; ++i) { transVoxels[i + 9].normalX = transVoxels[i + 9].normalX * 0.875 + voxelValues[CUBE_AXIS_BITS[faceAxis][(1 - side)][i]].normalX * 0.125; transVoxels[i + 9].normalY = transVoxels[i + 9].normalY * 0.875 + voxelValues[CUBE_AXIS_BITS[faceAxis][(1 - side)][i]].normalY * 0.125; transVoxels[i + 9].normalZ = transVoxels[i + 9].normalZ * 0.875 + voxelValues[CUBE_AXIS_BITS[faceAxis][(1 - side)][i]].normalZ * 0.125; voxelValues[CUBE_AXIS_BITS[faceAxis][side][i]].normalX = transVoxels[i + 9].normalX; voxelValues[CUBE_AXIS_BITS[faceAxis][side][i]].normalY = transVoxels[i + 9].normalY; voxelValues[CUBE_AXIS_BITS[faceAxis][side][i]].normalZ = transVoxels[i + 9].normalZ; } glm::ivec3 coord = {}; coord[primaryAxis] = d0; coord[secondAxis] = d1; coord[faceAxis] = d2; glm::ivec3 axis = {}; axis[faceAxis] = side * 2 - 1; updateTransVoxelCell( voxelValues, transVoxels, axis, coord, meshVertices, vertexCount); } } } } } #include "Transvoxel.inc" void Isosurface::updateVoxelCell( Voxel *voxels, const glm::ivec3 &coord, IsoVertex *meshVertices, uint32_t &vertexCount) { uint8_t bitCombination = 0; for (uint32_t i = 0; i < 8; ++i) { bool isOverSurface = (voxels[i].density > mSurfaceDensity.density); bitCombination |= isOverSurface << i; } if (bitCombination == 0 || bitCombination == 0xFF) { return; } uint8_t cellClassIdx = regularCellClass[bitCombination]; const RegularCellData &cellData = regularCellData[cellClassIdx]; glm::vec3 vertices[8] = {}; for (uint32_t i = 0; i < 8; ++i) { vertices[i] = NORMALIZED_CUBE_VERTICES[i] + glm::vec3(0.5f) + glm::vec3(coord); } IsoVertex *verts = STACK_ALLOC(IsoVertex, cellData.GetVertexCount()); for (int i = 0; i < cellData.GetVertexCount(); ++i) { uint16_t nibbles = regularVertexData[bitCombination][i]; if (nibbles == 0x0) { // Finished break; } uint8_t v0 = (nibbles >> 4) & 0xF; uint8_t v1 = nibbles & 0xF; float surfaceLevelF = (float)mSurfaceDensity.density; float voxelValue0 = (float)voxels[v0].density; float voxelValue1 = (float)voxels[v1].density; if (voxelValue0 > voxelValue1) { float tmp = voxelValue0; voxelValue0 = voxelValue1; voxelValue1 = tmp; uint8_t tmpV = v0; v0 = v1; v1 = tmpV; } float interpolatedVoxelValues = lerp(voxelValue0, voxelValue1, surfaceLevelF); glm::vec3 vertex = interpolate( vertices[v0], vertices[v1], interpolatedVoxelValues); glm::vec3 normal0 = glm::vec3( voxels[v0].normalX, voxels[v0].normalY, voxels[v0].normalZ) / 1000.0f; glm::vec3 normal1 = glm::vec3( voxels[v1].normalX, voxels[v1].normalY, voxels[v1].normalZ) / 1000.0f; glm::vec3 normal = interpolate( normal0, normal1, interpolatedVoxelValues); if (glm::dot(normal, normal) != 0.0f) { normal = glm::normalize(normal); } verts[i] = {vertex, normal}; } for (int i = 0; i < cellData.GetTriangleCount() * 3; ++i) { int vertexIndex = cellData.vertexIndex[i]; meshVertices[vertexCount++] = verts[vertexIndex]; } } void Isosurface::updateTransVoxelCell( Voxel *voxels, Voxel *transVoxels, const glm::ivec3 &axis, const glm::ivec3 &coord, IsoVertex *meshVertices, uint32_t &vertexCount) { const float percentTrans = 0.125f; { // Normal mesh creation uint8_t bitCombination = 0; for (uint32_t i = 0; i < 8; ++i) { bool isOverSurface = (voxels[i].density > mSurfaceDensity.density); bitCombination |= isOverSurface << i; } if (bitCombination == 0 || bitCombination == 0xFF) { return; } uint8_t cellClassIdx = regularCellClass[bitCombination]; const RegularCellData &cellData = regularCellData[cellClassIdx]; glm::vec3 vertices[8] = {}; for (uint32_t i = 0; i < 8; ++i) { vertices[i] = NORMALIZED_CUBE_VERTICES[i] + glm::vec3(0.5f) + glm::vec3(coord); } if (axis.x == -1) { vertices[0].x += percentTrans; vertices[2].x += percentTrans; vertices[4].x += percentTrans; vertices[6].x += percentTrans; } else if (axis.x == 1) { vertices[1].x -= percentTrans; vertices[3].x -= percentTrans; vertices[5].x -= percentTrans; vertices[7].x -= percentTrans; } else if (axis.z == -1) { vertices[0].z += percentTrans; vertices[1].z += percentTrans; vertices[2].z += percentTrans; vertices[3].z += percentTrans; } else if (axis.z == 1) { vertices[4].z -= percentTrans; vertices[5].z -= percentTrans; vertices[6].z -= percentTrans; vertices[7].z -= percentTrans; } IsoVertex *verts = STACK_ALLOC(IsoVertex, cellData.GetVertexCount()); for (int i = 0; i < cellData.GetVertexCount(); ++i) { uint16_t nibbles = regularVertexData[bitCombination][i]; if (nibbles == 0x0) { // Finished break; } uint8_t v0 = (nibbles >> 4) & 0xF; uint8_t v1 = nibbles & 0xF; float surfaceLevelF = (float)mSurfaceDensity.density; float voxelValue0 = (float)voxels[v0].density; float voxelValue1 = (float)voxels[v1].density; if (voxelValue0 > voxelValue1) { float tmp = voxelValue0; voxelValue0 = voxelValue1; voxelValue1 = tmp; uint8_t tmpV = v0; v0 = v1; v1 = tmpV; } float interpolatedVoxelValues = lerp(voxelValue0, voxelValue1, surfaceLevelF); glm::vec3 vertex = interpolate( vertices[v0], vertices[v1], interpolatedVoxelValues); glm::vec3 normal0 = glm::vec3( voxels[v0].normalX, voxels[v0].normalY, voxels[v0].normalZ) / 1000.0f; glm::vec3 normal1 = glm::vec3( voxels[v1].normalX, voxels[v1].normalY, voxels[v1].normalZ) / 1000.0f; glm::vec3 normal = interpolate( normal0, normal1, interpolatedVoxelValues); verts[i] = {vertex, normal}; } for (int i = 0; i < cellData.GetTriangleCount() * 3; ++i) { int vertexIndex = cellData.vertexIndex[i]; meshVertices[vertexCount++] = verts[vertexIndex]; } } { // Transvoxel mesh creation uint32_t bitCombination = 0; bitCombination |= (transVoxels[0].density > mSurfaceDensity.density) << 0; bitCombination |= (transVoxels[1].density > mSurfaceDensity.density) << 1; bitCombination |= (transVoxels[2].density > mSurfaceDensity.density) << 2; bitCombination |= (transVoxels[3].density > mSurfaceDensity.density) << 7; bitCombination |= (transVoxels[4].density > mSurfaceDensity.density) << 8; bitCombination |= (transVoxels[5].density > mSurfaceDensity.density) << 3; bitCombination |= (transVoxels[6].density > mSurfaceDensity.density) << 6; bitCombination |= (transVoxels[7].density > mSurfaceDensity.density) << 5; bitCombination |= (transVoxels[8].density > mSurfaceDensity.density) << 4; if (bitCombination == 0 || bitCombination == 511) { return; } int detailed0, detailed1, nonDetailed, nonDetailedBit; if (axis.x == -1) { detailed0 = 1, detailed1 = 2, nonDetailed = 0, nonDetailedBit = 0; } else if (axis.x == 1) { detailed0 = 1, detailed1 = 2, nonDetailed = 0, nonDetailedBit = 1; } else if (axis.z == -1) { detailed0 = 0, detailed1 = 1, nonDetailed = 2, nonDetailedBit = 0; } else if (axis.z == 1) { detailed0 = 0, detailed1 = 1, nonDetailed = 2, nonDetailedBit = 1; } glm::vec3 vertices[13] = {}; uint32_t counter = 0; for (int d1 = 0; d1 < 3; ++d1) { for (int d0 = 0; d0 < 3; ++d0) { vertices[counter][detailed0] = (float)d0 * 0.5f; vertices[counter][detailed1] = (float)d1 * 0.5f; vertices[counter][nonDetailed] = (float)nonDetailedBit; vertices[counter] += glm::vec3(coord); ++counter; } } for (int d1 = 0; d1 < 2; ++d1) { for (int d0 = 0; d0 < 2; ++d0) { vertices[counter][detailed0] = (float)d0; vertices[counter][detailed1] = (float)d1; vertices[counter][nonDetailed] = (float)(nonDetailedBit ^ 1); vertices[counter] += glm::vec3(coord); ++counter; } } if (nonDetailedBit) { if (axis[nonDetailed] == 1) { for (int i = 9; i < 13; ++i) { vertices[i][nonDetailed] += (1.0f - percentTrans); } } } else { if (axis[nonDetailed] == -1) { for (int i = 9; i < 13; ++i) { vertices[i][nonDetailed] -= (1.0f - percentTrans); } } } uint8_t cellClassIdx = transitionCellClass[bitCombination]; const TransitionCellData &cellData = transitionCellData[cellClassIdx & 0x7F]; IsoVertex *verts = STACK_ALLOC(IsoVertex, cellData.GetVertexCount()); for (int i = 0; i < cellData.GetVertexCount(); ++i) { uint16_t nibbles = transitionVertexData[bitCombination][i]; if (nibbles == 0x0) { break; } uint8_t v0 = (nibbles >> 4) & 0xF; uint8_t v1 = nibbles & 0xF; float surfaceLevelF = (float)mSurfaceDensity.density; float voxelValue0 = (float)transVoxels[v0].density; float voxelValue1 = (float)transVoxels[v1].density; if (voxelValue0 > voxelValue1) { float tmp = voxelValue0; voxelValue0 = voxelValue1; voxelValue1 = tmp; uint8_t tmpV = v0; v0 = v1; v1 = tmpV; } float interpolatedVoxelValues = lerp(voxelValue0, voxelValue1, surfaceLevelF); glm::vec3 vertex = interpolate( vertices[v0], vertices[v1], interpolatedVoxelValues); glm::vec3 normal0 = glm::vec3( transVoxels[v0].normalX, transVoxels[v0].normalY, transVoxels[v0].normalZ) / 1000.0f; glm::vec3 normal1 = glm::vec3( transVoxels[v1].normalX, transVoxels[v1].normalY, transVoxels[v1].normalZ) / 1000.0f; glm::vec3 normal = interpolate( normal0, normal1, interpolatedVoxelValues); if (glm::dot(normal, normal) != 0.0f) { normal = glm::normalize(normal); } verts[i] = {vertex, normal}; } if (cellClassIdx & 0x80) { for (int i = cellData.GetTriangleCount() * 3 - 1; i >= 0; --i) { int vertexIndex = cellData.vertexIndex[i]; glm::vec3 diff = verts[vertexIndex].position - (glm::vec3)coord; meshVertices[vertexCount++] = verts[vertexIndex]; } } else { for (int i = 0; i < cellData.GetTriangleCount() * 3; ++i) { int vertexIndex = cellData.vertexIndex[i]; glm::vec3 diff = verts[vertexIndex].position - (glm::vec3)coord; meshVertices[vertexCount++] = verts[vertexIndex]; } } } } NumericMap<IsoGroup *> &Isosurface::isoGroups() { return mIsoGroups; } }
30.107556
147
0.602994
llGuy
642dbd4ffe7bccee18b43176e13a58ae8311e6e0
44,623
cc
C++
test/f32-vsub.cc
khadas/android_external_XNNPACK
5fa0858b57c36722f0ab2606c606e927b5a40448
[ "BSD-3-Clause" ]
40
2021-06-01T07:37:59.000Z
2022-03-25T01:42:09.000Z
test/f32-vsub.cc
khadas/android_external_XNNPACK
5fa0858b57c36722f0ab2606c606e927b5a40448
[ "BSD-3-Clause" ]
14
2021-06-01T11:52:46.000Z
2022-03-25T02:13:08.000Z
test/f32-vsub.cc
khadas/android_external_XNNPACK
5fa0858b57c36722f0ab2606c606e927b5a40448
[ "BSD-3-Clause" ]
7
2021-07-20T19:34:26.000Z
2022-03-13T21:07:36.000Z
// Copyright 2019 Google LLC // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. // // Auto-generated file. Do not edit! // Specification: test/f32-vsub.yaml // Generator: tools/generate-vbinary-test.py #include <gtest/gtest.h> #include <xnnpack/common.h> #include <xnnpack/isa-checks.h> #include <xnnpack/vbinary.h> #include "vbinary-microkernel-tester.h" #if XNN_ARCH_ARM || XNN_ARCH_ARM64 TEST(F32_VSUB__NEON_X4, batch_eq_4) { TEST_REQUIRES_ARM_NEON; VBinOpMicrokernelTester() .batch_size(4) .Test(xnn_f32_vsub_ukernel__neon_x4, VBinOpMicrokernelTester::OpType::Sub); } TEST(F32_VSUB__NEON_X4, batch_div_4) { TEST_REQUIRES_ARM_NEON; for (size_t batch_size = 8; batch_size < 40; batch_size += 4) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__neon_x4, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__NEON_X4, batch_lt_4) { TEST_REQUIRES_ARM_NEON; for (size_t batch_size = 1; batch_size < 4; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__neon_x4, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__NEON_X4, batch_gt_4) { TEST_REQUIRES_ARM_NEON; for (size_t batch_size = 5; batch_size < 8; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__neon_x4, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__NEON_X4, inplace_a) { TEST_REQUIRES_ARM_NEON; for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .Test(xnn_f32_vsub_ukernel__neon_x4, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__NEON_X4, inplace_b) { TEST_REQUIRES_ARM_NEON; for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__neon_x4, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__NEON_X4, inplace_a_and_b) { TEST_REQUIRES_ARM_NEON; for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__neon_x4, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__NEON_X4, qmin) { TEST_REQUIRES_ARM_NEON; for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmin(128) .Test(xnn_f32_vsub_ukernel__neon_x4, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__NEON_X4, qmax) { TEST_REQUIRES_ARM_NEON; for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmax(128) .Test(xnn_f32_vsub_ukernel__neon_x4, VBinOpMicrokernelTester::OpType::Sub); } } #endif // XNN_ARCH_ARM || XNN_ARCH_ARM64 #if XNN_ARCH_ARM || XNN_ARCH_ARM64 TEST(F32_VSUB__NEON_X8, batch_eq_8) { TEST_REQUIRES_ARM_NEON; VBinOpMicrokernelTester() .batch_size(8) .Test(xnn_f32_vsub_ukernel__neon_x8, VBinOpMicrokernelTester::OpType::Sub); } TEST(F32_VSUB__NEON_X8, batch_div_8) { TEST_REQUIRES_ARM_NEON; for (size_t batch_size = 16; batch_size < 80; batch_size += 8) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__neon_x8, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__NEON_X8, batch_lt_8) { TEST_REQUIRES_ARM_NEON; for (size_t batch_size = 1; batch_size < 8; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__neon_x8, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__NEON_X8, batch_gt_8) { TEST_REQUIRES_ARM_NEON; for (size_t batch_size = 9; batch_size < 16; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__neon_x8, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__NEON_X8, inplace_a) { TEST_REQUIRES_ARM_NEON; for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .Test(xnn_f32_vsub_ukernel__neon_x8, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__NEON_X8, inplace_b) { TEST_REQUIRES_ARM_NEON; for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__neon_x8, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__NEON_X8, inplace_a_and_b) { TEST_REQUIRES_ARM_NEON; for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__neon_x8, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__NEON_X8, qmin) { TEST_REQUIRES_ARM_NEON; for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmin(128) .Test(xnn_f32_vsub_ukernel__neon_x8, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__NEON_X8, qmax) { TEST_REQUIRES_ARM_NEON; for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmax(128) .Test(xnn_f32_vsub_ukernel__neon_x8, VBinOpMicrokernelTester::OpType::Sub); } } #endif // XNN_ARCH_ARM || XNN_ARCH_ARM64 #if XNN_ARCH_X86 || XNN_ARCH_X86_64 TEST(F32_VSUB__SSE_X4, batch_eq_4) { TEST_REQUIRES_X86_SSE; VBinOpMicrokernelTester() .batch_size(4) .Test(xnn_f32_vsub_ukernel__sse_x4, VBinOpMicrokernelTester::OpType::Sub); } TEST(F32_VSUB__SSE_X4, batch_div_4) { TEST_REQUIRES_X86_SSE; for (size_t batch_size = 8; batch_size < 40; batch_size += 4) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__sse_x4, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__SSE_X4, batch_lt_4) { TEST_REQUIRES_X86_SSE; for (size_t batch_size = 1; batch_size < 4; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__sse_x4, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__SSE_X4, batch_gt_4) { TEST_REQUIRES_X86_SSE; for (size_t batch_size = 5; batch_size < 8; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__sse_x4, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__SSE_X4, inplace_a) { TEST_REQUIRES_X86_SSE; for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .Test(xnn_f32_vsub_ukernel__sse_x4, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__SSE_X4, inplace_b) { TEST_REQUIRES_X86_SSE; for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__sse_x4, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__SSE_X4, inplace_a_and_b) { TEST_REQUIRES_X86_SSE; for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__sse_x4, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__SSE_X4, qmin) { TEST_REQUIRES_X86_SSE; for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmin(128) .Test(xnn_f32_vsub_ukernel__sse_x4, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__SSE_X4, qmax) { TEST_REQUIRES_X86_SSE; for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmax(128) .Test(xnn_f32_vsub_ukernel__sse_x4, VBinOpMicrokernelTester::OpType::Sub); } } #endif // XNN_ARCH_X86 || XNN_ARCH_X86_64 #if XNN_ARCH_X86 || XNN_ARCH_X86_64 TEST(F32_VSUB__SSE_X8, batch_eq_8) { TEST_REQUIRES_X86_SSE; VBinOpMicrokernelTester() .batch_size(8) .Test(xnn_f32_vsub_ukernel__sse_x8, VBinOpMicrokernelTester::OpType::Sub); } TEST(F32_VSUB__SSE_X8, batch_div_8) { TEST_REQUIRES_X86_SSE; for (size_t batch_size = 16; batch_size < 80; batch_size += 8) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__sse_x8, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__SSE_X8, batch_lt_8) { TEST_REQUIRES_X86_SSE; for (size_t batch_size = 1; batch_size < 8; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__sse_x8, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__SSE_X8, batch_gt_8) { TEST_REQUIRES_X86_SSE; for (size_t batch_size = 9; batch_size < 16; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__sse_x8, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__SSE_X8, inplace_a) { TEST_REQUIRES_X86_SSE; for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .Test(xnn_f32_vsub_ukernel__sse_x8, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__SSE_X8, inplace_b) { TEST_REQUIRES_X86_SSE; for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__sse_x8, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__SSE_X8, inplace_a_and_b) { TEST_REQUIRES_X86_SSE; for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__sse_x8, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__SSE_X8, qmin) { TEST_REQUIRES_X86_SSE; for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmin(128) .Test(xnn_f32_vsub_ukernel__sse_x8, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__SSE_X8, qmax) { TEST_REQUIRES_X86_SSE; for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmax(128) .Test(xnn_f32_vsub_ukernel__sse_x8, VBinOpMicrokernelTester::OpType::Sub); } } #endif // XNN_ARCH_X86 || XNN_ARCH_X86_64 #if XNN_ARCH_X86 || XNN_ARCH_X86_64 TEST(F32_VSUB__AVX_X8, batch_eq_8) { TEST_REQUIRES_X86_AVX; VBinOpMicrokernelTester() .batch_size(8) .Test(xnn_f32_vsub_ukernel__avx_x8, VBinOpMicrokernelTester::OpType::Sub); } TEST(F32_VSUB__AVX_X8, batch_div_8) { TEST_REQUIRES_X86_AVX; for (size_t batch_size = 16; batch_size < 80; batch_size += 8) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__avx_x8, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX_X8, batch_lt_8) { TEST_REQUIRES_X86_AVX; for (size_t batch_size = 1; batch_size < 8; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__avx_x8, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX_X8, batch_gt_8) { TEST_REQUIRES_X86_AVX; for (size_t batch_size = 9; batch_size < 16; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__avx_x8, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX_X8, inplace_a) { TEST_REQUIRES_X86_AVX; for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .Test(xnn_f32_vsub_ukernel__avx_x8, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX_X8, inplace_b) { TEST_REQUIRES_X86_AVX; for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__avx_x8, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX_X8, inplace_a_and_b) { TEST_REQUIRES_X86_AVX; for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__avx_x8, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX_X8, qmin) { TEST_REQUIRES_X86_AVX; for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmin(128) .Test(xnn_f32_vsub_ukernel__avx_x8, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX_X8, qmax) { TEST_REQUIRES_X86_AVX; for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmax(128) .Test(xnn_f32_vsub_ukernel__avx_x8, VBinOpMicrokernelTester::OpType::Sub); } } #endif // XNN_ARCH_X86 || XNN_ARCH_X86_64 #if XNN_ARCH_X86 || XNN_ARCH_X86_64 TEST(F32_VSUB__AVX_X16, batch_eq_16) { TEST_REQUIRES_X86_AVX; VBinOpMicrokernelTester() .batch_size(16) .Test(xnn_f32_vsub_ukernel__avx_x16, VBinOpMicrokernelTester::OpType::Sub); } TEST(F32_VSUB__AVX_X16, batch_div_16) { TEST_REQUIRES_X86_AVX; for (size_t batch_size = 32; batch_size < 160; batch_size += 16) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__avx_x16, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX_X16, batch_lt_16) { TEST_REQUIRES_X86_AVX; for (size_t batch_size = 1; batch_size < 16; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__avx_x16, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX_X16, batch_gt_16) { TEST_REQUIRES_X86_AVX; for (size_t batch_size = 17; batch_size < 32; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__avx_x16, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX_X16, inplace_a) { TEST_REQUIRES_X86_AVX; for (size_t batch_size = 1; batch_size <= 80; batch_size += 15) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .Test(xnn_f32_vsub_ukernel__avx_x16, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX_X16, inplace_b) { TEST_REQUIRES_X86_AVX; for (size_t batch_size = 1; batch_size <= 80; batch_size += 15) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__avx_x16, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX_X16, inplace_a_and_b) { TEST_REQUIRES_X86_AVX; for (size_t batch_size = 1; batch_size <= 80; batch_size += 15) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__avx_x16, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX_X16, qmin) { TEST_REQUIRES_X86_AVX; for (size_t batch_size = 1; batch_size <= 80; batch_size += 15) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmin(128) .Test(xnn_f32_vsub_ukernel__avx_x16, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX_X16, qmax) { TEST_REQUIRES_X86_AVX; for (size_t batch_size = 1; batch_size <= 80; batch_size += 15) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmax(128) .Test(xnn_f32_vsub_ukernel__avx_x16, VBinOpMicrokernelTester::OpType::Sub); } } #endif // XNN_ARCH_X86 || XNN_ARCH_X86_64 #if XNN_ARCH_X86 || XNN_ARCH_X86_64 TEST(F32_VSUB__AVX512F_X16, batch_eq_16) { TEST_REQUIRES_X86_AVX512F; VBinOpMicrokernelTester() .batch_size(16) .Test(xnn_f32_vsub_ukernel__avx512f_x16, VBinOpMicrokernelTester::OpType::Sub); } TEST(F32_VSUB__AVX512F_X16, batch_div_16) { TEST_REQUIRES_X86_AVX512F; for (size_t batch_size = 32; batch_size < 160; batch_size += 16) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__avx512f_x16, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX512F_X16, batch_lt_16) { TEST_REQUIRES_X86_AVX512F; for (size_t batch_size = 1; batch_size < 16; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__avx512f_x16, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX512F_X16, batch_gt_16) { TEST_REQUIRES_X86_AVX512F; for (size_t batch_size = 17; batch_size < 32; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__avx512f_x16, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX512F_X16, inplace_a) { TEST_REQUIRES_X86_AVX512F; for (size_t batch_size = 1; batch_size <= 80; batch_size += 15) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .Test(xnn_f32_vsub_ukernel__avx512f_x16, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX512F_X16, inplace_b) { TEST_REQUIRES_X86_AVX512F; for (size_t batch_size = 1; batch_size <= 80; batch_size += 15) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__avx512f_x16, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX512F_X16, inplace_a_and_b) { TEST_REQUIRES_X86_AVX512F; for (size_t batch_size = 1; batch_size <= 80; batch_size += 15) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__avx512f_x16, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX512F_X16, qmin) { TEST_REQUIRES_X86_AVX512F; for (size_t batch_size = 1; batch_size <= 80; batch_size += 15) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmin(128) .Test(xnn_f32_vsub_ukernel__avx512f_x16, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX512F_X16, qmax) { TEST_REQUIRES_X86_AVX512F; for (size_t batch_size = 1; batch_size <= 80; batch_size += 15) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmax(128) .Test(xnn_f32_vsub_ukernel__avx512f_x16, VBinOpMicrokernelTester::OpType::Sub); } } #endif // XNN_ARCH_X86 || XNN_ARCH_X86_64 #if XNN_ARCH_X86 || XNN_ARCH_X86_64 TEST(F32_VSUB__AVX512F_X32, batch_eq_32) { TEST_REQUIRES_X86_AVX512F; VBinOpMicrokernelTester() .batch_size(32) .Test(xnn_f32_vsub_ukernel__avx512f_x32, VBinOpMicrokernelTester::OpType::Sub); } TEST(F32_VSUB__AVX512F_X32, batch_div_32) { TEST_REQUIRES_X86_AVX512F; for (size_t batch_size = 64; batch_size < 320; batch_size += 32) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__avx512f_x32, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX512F_X32, batch_lt_32) { TEST_REQUIRES_X86_AVX512F; for (size_t batch_size = 1; batch_size < 32; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__avx512f_x32, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX512F_X32, batch_gt_32) { TEST_REQUIRES_X86_AVX512F; for (size_t batch_size = 33; batch_size < 64; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__avx512f_x32, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX512F_X32, inplace_a) { TEST_REQUIRES_X86_AVX512F; for (size_t batch_size = 1; batch_size <= 160; batch_size += 31) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .Test(xnn_f32_vsub_ukernel__avx512f_x32, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX512F_X32, inplace_b) { TEST_REQUIRES_X86_AVX512F; for (size_t batch_size = 1; batch_size <= 160; batch_size += 31) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__avx512f_x32, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX512F_X32, inplace_a_and_b) { TEST_REQUIRES_X86_AVX512F; for (size_t batch_size = 1; batch_size <= 160; batch_size += 31) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__avx512f_x32, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX512F_X32, qmin) { TEST_REQUIRES_X86_AVX512F; for (size_t batch_size = 1; batch_size <= 160; batch_size += 31) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmin(128) .Test(xnn_f32_vsub_ukernel__avx512f_x32, VBinOpMicrokernelTester::OpType::Sub); } } TEST(F32_VSUB__AVX512F_X32, qmax) { TEST_REQUIRES_X86_AVX512F; for (size_t batch_size = 1; batch_size <= 160; batch_size += 31) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmax(128) .Test(xnn_f32_vsub_ukernel__avx512f_x32, VBinOpMicrokernelTester::OpType::Sub); } } #endif // XNN_ARCH_X86 || XNN_ARCH_X86_64 #if !XNN_ARCH_ASMJS && !XNN_ARCH_WASM TEST(F32_VSUB__PSIMD_X4, batch_eq_4) { TEST_REQUIRES_PSIMD; VBinOpMicrokernelTester() .batch_size(4) .Test(xnn_f32_vsub_ukernel__psimd_x4, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } TEST(F32_VSUB__PSIMD_X4, batch_div_4) { TEST_REQUIRES_PSIMD; for (size_t batch_size = 8; batch_size < 40; batch_size += 4) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__psimd_x4, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__PSIMD_X4, batch_lt_4) { TEST_REQUIRES_PSIMD; for (size_t batch_size = 1; batch_size < 4; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__psimd_x4, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__PSIMD_X4, batch_gt_4) { TEST_REQUIRES_PSIMD; for (size_t batch_size = 5; batch_size < 8; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__psimd_x4, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__PSIMD_X4, inplace_a) { TEST_REQUIRES_PSIMD; for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .Test(xnn_f32_vsub_ukernel__psimd_x4, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__PSIMD_X4, inplace_b) { TEST_REQUIRES_PSIMD; for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__psimd_x4, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__PSIMD_X4, inplace_a_and_b) { TEST_REQUIRES_PSIMD; for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__psimd_x4, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__PSIMD_X4, qmin) { TEST_REQUIRES_PSIMD; for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmin(128) .Test(xnn_f32_vsub_ukernel__psimd_x4, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__PSIMD_X4, qmax) { TEST_REQUIRES_PSIMD; for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmax(128) .Test(xnn_f32_vsub_ukernel__psimd_x4, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } #endif // !XNN_ARCH_ASMJS && !XNN_ARCH_WASM #if !XNN_ARCH_ASMJS && !XNN_ARCH_WASM TEST(F32_VSUB__PSIMD_X8, batch_eq_8) { TEST_REQUIRES_PSIMD; VBinOpMicrokernelTester() .batch_size(8) .Test(xnn_f32_vsub_ukernel__psimd_x8, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } TEST(F32_VSUB__PSIMD_X8, batch_div_8) { TEST_REQUIRES_PSIMD; for (size_t batch_size = 16; batch_size < 80; batch_size += 8) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__psimd_x8, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__PSIMD_X8, batch_lt_8) { TEST_REQUIRES_PSIMD; for (size_t batch_size = 1; batch_size < 8; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__psimd_x8, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__PSIMD_X8, batch_gt_8) { TEST_REQUIRES_PSIMD; for (size_t batch_size = 9; batch_size < 16; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__psimd_x8, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__PSIMD_X8, inplace_a) { TEST_REQUIRES_PSIMD; for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .Test(xnn_f32_vsub_ukernel__psimd_x8, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__PSIMD_X8, inplace_b) { TEST_REQUIRES_PSIMD; for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__psimd_x8, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__PSIMD_X8, inplace_a_and_b) { TEST_REQUIRES_PSIMD; for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__psimd_x8, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__PSIMD_X8, qmin) { TEST_REQUIRES_PSIMD; for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmin(128) .Test(xnn_f32_vsub_ukernel__psimd_x8, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__PSIMD_X8, qmax) { TEST_REQUIRES_PSIMD; for (size_t batch_size = 1; batch_size <= 40; batch_size += 7) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmax(128) .Test(xnn_f32_vsub_ukernel__psimd_x8, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } #endif // !XNN_ARCH_ASMJS && !XNN_ARCH_WASM #if XNN_ARCH_WASM TEST(F32_VSUB__WASM_X1, batch_eq_1) { VBinOpMicrokernelTester() .batch_size(1) .Test(xnn_f32_vsub_ukernel__wasm_x1, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } TEST(F32_VSUB__WASM_X1, batch_gt_1) { for (size_t batch_size = 2; batch_size < 10; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__wasm_x1, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__WASM_X1, inplace_a) { for (size_t batch_size = 1; batch_size <= 5; batch_size += 1) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .Test(xnn_f32_vsub_ukernel__wasm_x1, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__WASM_X1, inplace_b) { for (size_t batch_size = 1; batch_size <= 5; batch_size += 1) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__wasm_x1, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__WASM_X1, inplace_a_and_b) { for (size_t batch_size = 1; batch_size <= 5; batch_size += 1) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__wasm_x1, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__WASM_X1, qmin) { for (size_t batch_size = 1; batch_size <= 5; batch_size += 1) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmin(128) .Test(xnn_f32_vsub_ukernel__wasm_x1, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__WASM_X1, qmax) { for (size_t batch_size = 1; batch_size <= 5; batch_size += 1) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmax(128) .Test(xnn_f32_vsub_ukernel__wasm_x1, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } #endif // XNN_ARCH_WASM #if XNN_ARCH_WASM TEST(F32_VSUB__WASM_X2, batch_eq_2) { VBinOpMicrokernelTester() .batch_size(2) .Test(xnn_f32_vsub_ukernel__wasm_x2, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } TEST(F32_VSUB__WASM_X2, batch_div_2) { for (size_t batch_size = 4; batch_size < 20; batch_size += 2) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__wasm_x2, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__WASM_X2, batch_lt_2) { for (size_t batch_size = 1; batch_size < 2; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__wasm_x2, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__WASM_X2, batch_gt_2) { for (size_t batch_size = 3; batch_size < 4; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__wasm_x2, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__WASM_X2, inplace_a) { for (size_t batch_size = 1; batch_size <= 10; batch_size += 1) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .Test(xnn_f32_vsub_ukernel__wasm_x2, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__WASM_X2, inplace_b) { for (size_t batch_size = 1; batch_size <= 10; batch_size += 1) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__wasm_x2, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__WASM_X2, inplace_a_and_b) { for (size_t batch_size = 1; batch_size <= 10; batch_size += 1) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__wasm_x2, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__WASM_X2, qmin) { for (size_t batch_size = 1; batch_size <= 10; batch_size += 1) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmin(128) .Test(xnn_f32_vsub_ukernel__wasm_x2, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__WASM_X2, qmax) { for (size_t batch_size = 1; batch_size <= 10; batch_size += 1) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmax(128) .Test(xnn_f32_vsub_ukernel__wasm_x2, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } #endif // XNN_ARCH_WASM #if XNN_ARCH_WASM TEST(F32_VSUB__WASM_X4, batch_eq_4) { VBinOpMicrokernelTester() .batch_size(4) .Test(xnn_f32_vsub_ukernel__wasm_x4, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } TEST(F32_VSUB__WASM_X4, batch_div_4) { for (size_t batch_size = 8; batch_size < 40; batch_size += 4) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__wasm_x4, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__WASM_X4, batch_lt_4) { for (size_t batch_size = 1; batch_size < 4; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__wasm_x4, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__WASM_X4, batch_gt_4) { for (size_t batch_size = 5; batch_size < 8; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__wasm_x4, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__WASM_X4, inplace_a) { for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .Test(xnn_f32_vsub_ukernel__wasm_x4, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__WASM_X4, inplace_b) { for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__wasm_x4, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__WASM_X4, inplace_a_and_b) { for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__wasm_x4, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__WASM_X4, qmin) { for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmin(128) .Test(xnn_f32_vsub_ukernel__wasm_x4, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__WASM_X4, qmax) { for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmax(128) .Test(xnn_f32_vsub_ukernel__wasm_x4, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } #endif // XNN_ARCH_WASM TEST(F32_VSUB__SCALAR_X1, batch_eq_1) { VBinOpMicrokernelTester() .batch_size(1) .Test(xnn_f32_vsub_ukernel__scalar_x1, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } TEST(F32_VSUB__SCALAR_X1, batch_gt_1) { for (size_t batch_size = 2; batch_size < 10; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__scalar_x1, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__SCALAR_X1, inplace_a) { for (size_t batch_size = 1; batch_size <= 5; batch_size += 1) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .Test(xnn_f32_vsub_ukernel__scalar_x1, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__SCALAR_X1, inplace_b) { for (size_t batch_size = 1; batch_size <= 5; batch_size += 1) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__scalar_x1, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__SCALAR_X1, inplace_a_and_b) { for (size_t batch_size = 1; batch_size <= 5; batch_size += 1) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__scalar_x1, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__SCALAR_X1, qmin) { for (size_t batch_size = 1; batch_size <= 5; batch_size += 1) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmin(128) .Test(xnn_f32_vsub_ukernel__scalar_x1, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__SCALAR_X1, qmax) { for (size_t batch_size = 1; batch_size <= 5; batch_size += 1) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmax(128) .Test(xnn_f32_vsub_ukernel__scalar_x1, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__SCALAR_X2, batch_eq_2) { VBinOpMicrokernelTester() .batch_size(2) .Test(xnn_f32_vsub_ukernel__scalar_x2, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } TEST(F32_VSUB__SCALAR_X2, batch_div_2) { for (size_t batch_size = 4; batch_size < 20; batch_size += 2) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__scalar_x2, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__SCALAR_X2, batch_lt_2) { for (size_t batch_size = 1; batch_size < 2; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__scalar_x2, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__SCALAR_X2, batch_gt_2) { for (size_t batch_size = 3; batch_size < 4; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__scalar_x2, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__SCALAR_X2, inplace_a) { for (size_t batch_size = 1; batch_size <= 10; batch_size += 1) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .Test(xnn_f32_vsub_ukernel__scalar_x2, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__SCALAR_X2, inplace_b) { for (size_t batch_size = 1; batch_size <= 10; batch_size += 1) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__scalar_x2, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__SCALAR_X2, inplace_a_and_b) { for (size_t batch_size = 1; batch_size <= 10; batch_size += 1) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__scalar_x2, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__SCALAR_X2, qmin) { for (size_t batch_size = 1; batch_size <= 10; batch_size += 1) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmin(128) .Test(xnn_f32_vsub_ukernel__scalar_x2, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__SCALAR_X2, qmax) { for (size_t batch_size = 1; batch_size <= 10; batch_size += 1) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmax(128) .Test(xnn_f32_vsub_ukernel__scalar_x2, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__SCALAR_X4, batch_eq_4) { VBinOpMicrokernelTester() .batch_size(4) .Test(xnn_f32_vsub_ukernel__scalar_x4, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } TEST(F32_VSUB__SCALAR_X4, batch_div_4) { for (size_t batch_size = 8; batch_size < 40; batch_size += 4) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__scalar_x4, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__SCALAR_X4, batch_lt_4) { for (size_t batch_size = 1; batch_size < 4; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__scalar_x4, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__SCALAR_X4, batch_gt_4) { for (size_t batch_size = 5; batch_size < 8; batch_size++) { VBinOpMicrokernelTester() .batch_size(batch_size) .Test(xnn_f32_vsub_ukernel__scalar_x4, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__SCALAR_X4, inplace_a) { for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .Test(xnn_f32_vsub_ukernel__scalar_x4, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__SCALAR_X4, inplace_b) { for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__scalar_x4, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__SCALAR_X4, inplace_a_and_b) { for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinOpMicrokernelTester() .batch_size(batch_size) .inplace_a(true) .inplace_b(true) .Test(xnn_f32_vsub_ukernel__scalar_x4, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__SCALAR_X4, qmin) { for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmin(128) .Test(xnn_f32_vsub_ukernel__scalar_x4, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } } TEST(F32_VSUB__SCALAR_X4, qmax) { for (size_t batch_size = 1; batch_size <= 20; batch_size += 3) { VBinOpMicrokernelTester() .batch_size(batch_size) .qmax(128) .Test(xnn_f32_vsub_ukernel__scalar_x4, VBinOpMicrokernelTester::OpType::Sub, VBinOpMicrokernelTester::Variant::Scalar); } }
33.52592
126
0.699639
khadas
642f552caf8360f1efc2230731e1409502dc5304
2,383
hh
C++
preprocessor/preprocessor-src/src/preprocessor/cxx_ast.hh
fabianmcg/wavedag
e975792aef4423de6cf43af6bfde44ef89a5db0d
[ "MIT" ]
1
2021-01-10T09:04:38.000Z
2021-01-10T09:04:38.000Z
preprocessor/preprocessor-src/src/preprocessor/cxx_ast.hh
fabianmcg/wavedag
e975792aef4423de6cf43af6bfde44ef89a5db0d
[ "MIT" ]
null
null
null
preprocessor/preprocessor-src/src/preprocessor/cxx_ast.hh
fabianmcg/wavedag
e975792aef4423de6cf43af6bfde44ef89a5db0d
[ "MIT" ]
null
null
null
#ifndef __PREPROCESSOR_CXX_AST_HH__ #define __PREPROCESSOR_CXX_AST_HH__ #include <pragma-parser.hh> #include "../clang/clang-wrapper.hh" #include "../util.hh" #include "util.hh" #include "types.hh" #include "pragma.hh" namespace __preprocessor__ { namespace __cxx__ { enum class variable_list_mode_e { NAMES, NAMES_TYPES }; using variable_list_mode_t=variable_list_mode_e; std::vector<for_statement_t> for_statements(const clang_ast_t& ast,clang_ast_node_t* root=nullptr); std::vector<for_statement_t> for_statements(const std::vector<std::string>& src,const clang_ast_t& ast,clang_ast_node_t* root=nullptr); void remove_unexposed(clang_ast_t &ast,clang_ast_node_t *root=nullptr); variable_t variable_type(const clang_ast_node_t& node); template <variable_list_mode_t mode=variable_list_mode_t::NAMES_TYPES,std::enable_if_t<mode==variable_list_mode_t::NAMES_TYPES,int> = 0> std::set<std::pair<std::string,variable_t>> variable_list(const clang_ast_t& ast,clang_ast_node_t* root=nullptr) { std::set<std::pair<std::string,variable_t>> variables; auto visitor=[&variables](const clang_ast_node_t& node,size_t depth) { variable_t type=variable_type(node); if(type!=NOT_VAR) variables.insert(std::make_pair(std::get<std::string>(node.value),type)); }; ast.traverse(visitor,root); return variables; } template <variable_list_mode_t mode=variable_list_mode_t::NAMES_TYPES,std::enable_if_t<mode==variable_list_mode_t::NAMES,int> = 0> std::set<std::string> variable_list(const clang_ast_t& ast,clang_ast_node_t* root=nullptr) { std::set<std::string> variables; auto visitor=[&variables](const clang_ast_node_t& node,size_t depth) { variable_t type=variable_type(node); if(type!=NOT_VAR) variables.insert(std::get<std::string>(node.value)); }; ast.traverse(visitor,root); return variables; } std::pair<std::map<clang_ast_node_t*,size_t>,std::vector<clang_ast_node_t*>> pragma_code_blocks(const std::vector<pragma_ast_node_t*>& pragma_translation,const clang_ast_t& ast,clang_ast_node_t* root=nullptr); std::vector<std::string> pragma_identifier_list(const clang_ast_t& ast,clang_ast_node_t* root=nullptr); std::string remove_tasks(const std::vector<std::string>& src,const std::vector<pragma_ast_node_t*>& pragma_translation,const std::vector<clang_ast_node_t*>& cxx_translation,const clang_ast_t& ast,clang_ast_node_t* root=nullptr,bool leave=false); } } #endif
45.826923
245
0.793538
fabianmcg
642f9f56efd39702aaeb2e9844c3c9b8cbafc274
839
cc
C++
src/ops/softmax.cc
Parkchanjun/CTranslate2
62e3af774e0ba23e052e242c263dcbc00cd6c0c6
[ "MIT" ]
null
null
null
src/ops/softmax.cc
Parkchanjun/CTranslate2
62e3af774e0ba23e052e242c263dcbc00cd6c0c6
[ "MIT" ]
null
null
null
src/ops/softmax.cc
Parkchanjun/CTranslate2
62e3af774e0ba23e052e242c263dcbc00cd6c0c6
[ "MIT" ]
null
null
null
#include "ctranslate2/ops/softmax.h" #include "../device_dispatch.h" namespace ctranslate2 { namespace ops { LogSoftMax::LogSoftMax() : SoftMax(/*log=*/true) { } SoftMax::SoftMax(bool log) : _log(log) { } void SoftMax::operator()(const StorageView& x, StorageView& y) const { operator()(x, nullptr, y); } void SoftMax::operator()(const StorageView& x, const StorageView& lengths, StorageView& y) const { operator()(x, &lengths, y); } void SoftMax::operator()(const StorageView& x, const StorageView* lengths, StorageView& y) const { PROFILE_FUN; if (lengths && lengths->dim(0) == 1) // Disable masking when batch size is 1. lengths = nullptr; y.resize_as(x); DEVICE_DISPATCH(x.device(), (compute<D, float>(x, lengths, y))); } } }
24.676471
102
0.615018
Parkchanjun
6431948ead17245979c8032bcb8a3317bc86acfc
13,539
cpp
C++
lib/CubeSolver/TableManager.cpp
C-minus-minus/Cubebert
bef38d5ba9baa884b32710c058ca4d18d6734ecf
[ "MIT" ]
null
null
null
lib/CubeSolver/TableManager.cpp
C-minus-minus/Cubebert
bef38d5ba9baa884b32710c058ca4d18d6734ecf
[ "MIT" ]
null
null
null
lib/CubeSolver/TableManager.cpp
C-minus-minus/Cubebert
bef38d5ba9baa884b32710c058ca4d18d6734ecf
[ "MIT" ]
null
null
null
#include "TableManager.h" TableManager* TableManager::instance = NULL; TableManager::TableManager() { this->generatePhase1MoveTables(); this->generatePhase1PruningTables(); this->generatePhase2MoveTables(); this->generatePhase2PruningTables(); } TableManager* TableManager::getInstance() { if (TableManager::instance == NULL) { TableManager::instance = new TableManager(); } return TableManager::instance; } void TableManager::generatePhase1EdgeMoveTable(StickerCube* cube, int coord, int depth) { if (this->phase1EdgeMoveTable[coord][0] == -1) { for (int move = 0; move < CubeConstants::PHASE_1_MOVE_COUNT; move++) { cube->applyMove(CubeConstants::PHASE_1_MOVES[move]); int newCoord = cube->getPhase1EdgeCoordinate(); phase1EdgeMoveTable[coord][move] = newCoord; generatePhase1EdgeMoveTable(cube, newCoord, depth + 1); cube->applyMove(CubeConstants::PHASE_1_ANTIMOVES[move]); } } } void TableManager::generatePhase1CornerMoveTable(StickerCube* cube, int coord, int depth) { if (this->phase1CornerMoveTable[coord][0] == -1) { for (int move = 0; move < CubeConstants::PHASE_1_MOVE_COUNT; move++) { cube->applyMove(CubeConstants::PHASE_1_MOVES[move]); int newCoord = cube->getPhase1CornerCoordinate(); this->phase1CornerMoveTable[coord][move] = newCoord; this->generatePhase1CornerMoveTable(cube, newCoord, depth + 1); cube->applyMove(CubeConstants::PHASE_1_ANTIMOVES[move]); } } } void TableManager::generatePhase1UdsliceMoveTable(StickerCube* cube, int coord, int depth) { if (this->phase1UdsliceMoveTable[coord][0] == -1) { for (int move = 0; move < CubeConstants::PHASE_1_MOVE_COUNT; move++) { cube->applyMove(CubeConstants::PHASE_1_MOVES[move]); int newCoord = cube->getPhase1UdsliceCoordinate(); this->phase1UdsliceMoveTable[coord][move] = newCoord; this->generatePhase1UdsliceMoveTable(cube, newCoord, depth + 1); cube->applyMove(CubeConstants::PHASE_1_ANTIMOVES[move]); } } } void TableManager::generatePhase2EdgeMoveTable() { for (int coord = 0; coord < CubeConstants::PHASE_2_MAX_EDGE_COORDINATE; coord++) { StickerCube* stickerCube = StickerCube::fromEdgePermutation(coord); for (int move = 0; move < CubeConstants::PHASE_2_MOVE_COUNT; move++) { stickerCube->applyMove(CubeConstants::PHASE_2_MOVES[move]); this->phase2EdgeMoveTable[coord][move] = stickerCube->getPhase2EdgeCoordinate(); stickerCube->applyMove(CubeConstants::PHASE_2_ANTIMOVES[move]); } delete stickerCube; } } void TableManager::generatePhase2CornerMoveTable() { for (int coord = 0; coord < CubeConstants::PHASE_2_MAX_CORNER_COORDINATE; coord++) { StickerCube* stickerCube = StickerCube::fromCornerPermutation(coord); for (int move = 0; move < CubeConstants::PHASE_2_MOVE_COUNT; move++) { stickerCube->applyMove(CubeConstants::PHASE_2_MOVES[move]); this->phase2CornerMoveTable[coord][move] = stickerCube->getPhase2CornerCoordinate(); stickerCube->applyMove(CubeConstants::PHASE_2_ANTIMOVES[move]); } } } void TableManager::generatePhase2UdsliceMoveTable() { for (int coord = 0; coord < CubeConstants::PHASE_2_MAX_UDSLICE_COORDINATE; coord++) { StickerCube* stickerCube = StickerCube::fromUDSlice(coord); for (int move = 0; move < CubeConstants::PHASE_2_MOVE_COUNT; move++) { stickerCube->applyMove(CubeConstants::PHASE_2_MOVES[move]); this->phase2UdsliceMoveTable[coord][move] = stickerCube->getPhase2UdsliceCoordinate(); stickerCube->applyMove(CubeConstants::PHASE_2_ANTIMOVES[move]); } } } void TableManager::generatePhase1MoveTables() { // Allocate memory for tables this->phase1EdgeMoveTable = new int*[CubeConstants::PHASE_1_MAX_EDGE_COORDINATE]; for (int i = 0; i < CubeConstants::PHASE_1_MAX_EDGE_COORDINATE; i++) { this->phase1EdgeMoveTable[i] = new int[CubeConstants::PHASE_1_MOVE_COUNT]; for (int a = 0; a < CubeConstants::PHASE_1_MOVE_COUNT; a++) { this->phase1EdgeMoveTable[i][a] = -1; } } this->phase1CornerMoveTable = new int*[CubeConstants::PHASE_1_MAX_CORNER_COORDINATE]; for (int i = 0; i < CubeConstants::PHASE_1_MAX_CORNER_COORDINATE; i++) { this->phase1CornerMoveTable[i] = new int[CubeConstants::PHASE_1_MOVE_COUNT]; for (int a = 0; a < CubeConstants::PHASE_1_MOVE_COUNT; a++) { this->phase1CornerMoveTable[i][a] = -1; } } this->phase1UdsliceMoveTable = new int*[CubeConstants::PHASE_1_MAX_UDSLICE_COORDINATE]; for (int i = 0; i < CubeConstants::PHASE_1_MAX_UDSLICE_COORDINATE; i++) { this->phase1UdsliceMoveTable[i] = new int[CubeConstants::PHASE_1_MOVE_COUNT]; for (int a = 0; a < CubeConstants::PHASE_1_MOVE_COUNT; a++) { this->phase1UdsliceMoveTable[i][a] = -1; } } //// populate tables with -1 to start //int** tables[] = {this->phase1EdgeMoveTable, this->phase1CornerMoveTable, this->phase1UdsliceMoveTable}; //const int maxCoordinateLength = 3; //const int maxCoordinate[] = { // CubeConstants::PHASE_1_MAX_EDGE_COORDINATE, // CubeConstants::PHASE_1_MAX_CORNER_COORDINATE, // CubeConstants::PHASE_1_MAX_UDSLICE_COORDINATE //}; //for (int move = 0; move < CubeConstants::PHASE_1_MOVE_COUNT; move++) { // for (int table = 0; table < maxCoordinateLength; table++) { // for (int coord = 0; coord < maxCoordinate[table]; coord++) { // tables[table][coord][move] = -1; // } // } //} // Generate move tables using DFS StickerCube* solvedCube = new StickerCube(); this->generatePhase1UdsliceMoveTable(solvedCube, 0, 0); this->generatePhase1EdgeMoveTable(solvedCube, 0, 0); this->generatePhase1CornerMoveTable(solvedCube, 0, 0); } void TableManager::generatePhase2MoveTables() { this->phase2EdgeMoveTable = new int*[CubeConstants::PHASE_2_MAX_EDGE_COORDINATE]; for (int i = 0; i < CubeConstants::PHASE_2_MAX_EDGE_COORDINATE; i++) { this->phase2EdgeMoveTable[i] = new int[CubeConstants::PHASE_2_MOVE_COUNT]; for (int a = 0; a < CubeConstants::PHASE_2_MOVE_COUNT; a++) { this->phase2EdgeMoveTable[i][a] = -1; } } this->phase2CornerMoveTable = new int*[CubeConstants::PHASE_2_MAX_CORNER_COORDINATE]; for (int i = 0; i < CubeConstants::PHASE_2_MAX_CORNER_COORDINATE; i++) { this->phase2CornerMoveTable[i] = new int[CubeConstants::PHASE_2_MOVE_COUNT]; for (int a = 0; a < CubeConstants::PHASE_2_MOVE_COUNT; a++) { this->phase2CornerMoveTable[i][a] = -1; } } this->phase2UdsliceMoveTable = new int*[CubeConstants::PHASE_2_MAX_UDSLICE_COORDINATE]; for (int i = 0; i < CubeConstants::PHASE_2_MAX_UDSLICE_COORDINATE; i++) { this->phase2UdsliceMoveTable[i] = new int[CubeConstants::PHASE_2_MOVE_COUNT] ; for (int a = 0; a < CubeConstants::PHASE_2_MOVE_COUNT; a++) { this->phase2UdsliceMoveTable[i][a] = -1; } } /* for (int move = 0; move < CubeConstants::PHASE_2_MOVE_COUNT; move++) { int** tables[] = {this->phase2EdgeMoveTable, this->phase2CornerMoveTable, this->phase2UdsliceMoveTable}; const int maxCoordinateSize = 3; int maxCoordinate[] = { CubeConstants::PHASE_2_MAX_EDGE_COORDINATE, CubeConstants::PHASE_2_MAX_CORNER_COORDINATE, CubeConstants::PHASE_2_MAX_UDSLICE_COORDINATE }; for (int table = 0; table < maxCoordinateSize; table++) { for (int coord = 0; coord < maxCoordinate[table]; coord++) { tables[table][coord][move] = -1; } } }*/ this->generatePhase2EdgeMoveTable(); this->generatePhase2CornerMoveTable(); this->generatePhase2UdsliceMoveTable(); } void TableManager::generatePhase1EdgePruningTable() { this->phase1EdgePruningTable = new int[CubeConstants::PHASE_1_MAX_EDGE_COORDINATE]; for (int i = 0; i < CubeConstants::PHASE_1_MAX_EDGE_COORDINATE; i++) { this->phase1EdgePruningTable[i] = -1; } std::queue<SearchNode*> que; que.emplace(new SearchNode(0, 0)); while (!que.empty()) { SearchNode* curr = que.front(); que.pop(); if (this->phase1EdgePruningTable[curr->value] == -1) { this->phase1EdgePruningTable[curr->value] = curr->depth; for (int move = 0; move < CubeConstants::PHASE_1_MOVE_COUNT; move++) { int coord = this->phase1EdgeMoveTable[curr->value][move]; que.emplace(new SearchNode(curr->depth + 1, coord)); } } } } void TableManager::generatePhase1CornerPruningTable() { this->phase1CornerPruningTable = new int[CubeConstants::PHASE_1_MAX_CORNER_COORDINATE]; for (int i = 0; i < CubeConstants::PHASE_1_MAX_CORNER_COORDINATE; i++) { this->phase1CornerPruningTable[i] = -1; } std::queue<SearchNode*> que; que.emplace(new SearchNode(0, 0)); while (!que.empty()) { SearchNode* curr = que.front(); que.pop(); if (this->phase1CornerPruningTable[curr->value] == -1) { this->phase1CornerPruningTable[curr->value] = curr->depth; for (int move = 0; move < CubeConstants::PHASE_1_MOVE_COUNT; move++) { int coord = this->phase1CornerMoveTable[curr->value][move]; que.emplace(new SearchNode(curr->depth + 1, coord)); } } } } void TableManager::generatePhase1UDSlicePruningTable() { this->phase1UdslicePruningTable = new int[CubeConstants::PHASE_1_MAX_UDSLICE_COORDINATE]; for (int i = 0; i < CubeConstants::PHASE_1_MAX_UDSLICE_COORDINATE; i++) { this->phase1UdslicePruningTable[i] = -1; } std::queue<SearchNode*> que; que.emplace(new SearchNode(0, 0)); while (!que.empty()) { SearchNode* curr = que.front(); que.pop(); if (this->phase1UdslicePruningTable[curr->value] == -1) { this->phase1UdslicePruningTable[curr->value] = curr->depth; for (int move = 0; move < CubeConstants::PHASE_1_MOVE_COUNT; move++) { int coord = this->phase1UdsliceMoveTable[curr->value][move]; que.emplace(new SearchNode(curr->depth + 1, coord)); } } } } void TableManager::generatePhase2EdgePruningTable() { this->phase2EdgePruningTable = new int[CubeConstants::PHASE_2_MAX_EDGE_COORDINATE]; for (int i = 0; i < CubeConstants::PHASE_2_MAX_EDGE_COORDINATE; i++) { this->phase2EdgePruningTable[i] = -1; } std::queue<SearchNode*> que; que.emplace(new SearchNode(0, 0)); while (!que.empty()) { SearchNode* curr = que.front(); que.pop(); if (this->phase2EdgePruningTable[curr->value] == -1) { this->phase2EdgePruningTable[curr->value] = curr->depth; for (int move = 0; move < CubeConstants::PHASE_2_MOVE_COUNT; move++) { int coord = this->phase2EdgeMoveTable[curr->value][move]; que.emplace(new SearchNode(curr->depth + 1, coord)); } } } } void TableManager::generatePhase2CornerPruningTable() { this->phase2CornerPruningTable = new int[CubeConstants::PHASE_2_MAX_CORNER_COORDINATE]; for (int i = 0; i < CubeConstants::PHASE_2_MAX_CORNER_COORDINATE; i++) { this->phase2CornerPruningTable[i] = -1; } std::queue<SearchNode*> que; que.emplace(new SearchNode(0, 0)); while (!que.empty()) { SearchNode* curr = que.front(); que.pop(); if (this->phase2CornerPruningTable[curr->value] == -1) { this->phase2CornerPruningTable[curr->value] = curr->depth; for (int move = 0; move < CubeConstants::PHASE_2_MOVE_COUNT; move++) { int coord = this->phase2CornerMoveTable[curr->value][move]; que.emplace(new SearchNode(curr->depth + 1, coord)); } } } } void TableManager::generatePhase2UDSlicePruningTable() { this->phase2UdslicePruningTable = new int[CubeConstants::PHASE_2_MAX_UDSLICE_COORDINATE]; for (int i = 0; i < CubeConstants::PHASE_2_MAX_UDSLICE_COORDINATE; i++) { this->phase2UdslicePruningTable[i] = -1; } std::queue<SearchNode*> que; que.emplace(new SearchNode(0, 0)); while (!que.empty()) { SearchNode* curr = que.front(); que.pop(); if (this->phase2UdslicePruningTable[curr->value] == -1) { this->phase2UdslicePruningTable[curr->value] = curr->depth; for (int move = 0; move < CubeConstants::PHASE_2_MOVE_COUNT; move++) { int coord = this->phase2UdsliceMoveTable[curr->value][move]; que.emplace(new SearchNode(curr->depth + 1, coord)); } } } } void TableManager::generatePhase1PruningTables() { this->generatePhase1EdgePruningTable(); this->generatePhase1CornerPruningTable(); this->generatePhase1UDSlicePruningTable(); } void TableManager::generatePhase2PruningTables() { this->generatePhase2EdgePruningTable(); this->generatePhase2CornerPruningTable(); this->generatePhase2UDSlicePruningTable(); }
41.658462
112
0.646872
C-minus-minus
6431c915f87e30410ac8db28838277e7ea7a2804
5,341
cpp
C++
tools/bpp-phyl/src/Bpp/Phyl/Distance/NeighborJoining.cpp
danydoerr/spp_dcj
1ab9dacb1f0dc34a3ebbeed9e74226a9a53c297a
[ "MIT" ]
2
2021-08-24T16:03:30.000Z
2022-03-18T14:52:43.000Z
tools/bpp-phyl/src/Bpp/Phyl/Distance/NeighborJoining.cpp
danydoerr/spp_dcj
1ab9dacb1f0dc34a3ebbeed9e74226a9a53c297a
[ "MIT" ]
null
null
null
tools/bpp-phyl/src/Bpp/Phyl/Distance/NeighborJoining.cpp
danydoerr/spp_dcj
1ab9dacb1f0dc34a3ebbeed9e74226a9a53c297a
[ "MIT" ]
null
null
null
// // File: NeighborJoining.cpp // Created by: Julien Dutheil // Vincent Ranwez // Created on: Thu jun 23 10:39 2005 // /* Copyright or © or Copr. CNRS, (November 16, 2004) This software is a computer program whose purpose is to provide classes for phylogenetic data analysis. This software is governed by the CeCILL license under French law and abiding by the rules of distribution of free software. You can use, modify and/ or redistribute the software under the terms of the CeCILL license as circulated by CEA, CNRS and INRIA at the following URL "http://www.cecill.info". As a counterpart to the access to the source code and rights to copy, modify and redistribute granted by the license, users are provided only with a limited warranty and the software's author, the holder of the economic rights, and the successive licensors have only limited liability. In this respect, the user's attention is drawn to the risks associated with loading, using, modifying and/or developing or reproducing the software by the user in light of its specific status of free software, that may mean that it is complicated to manipulate, and that also therefore means that it is reserved for developers and experienced professionals having in-depth computer knowledge. Users are therefore encouraged to load and test the software's suitability as regards their requirements in conditions enabling the security of their systems and/or data to be ensured and, more generally, to use and operate it in the same conditions as regards security. The fact that you are presently reading this means that you have had knowledge of the CeCILL license and that you accept its terms. */ #include "NeighborJoining.h" #include "../Tree.h" using namespace bpp; #include <cmath> #include <iostream> using namespace std; std::vector<size_t> NeighborJoining::getBestPair() { for (std::map<size_t, Node*>::iterator i = currentNodes_.begin(); i != currentNodes_.end(); i++) { size_t id = i->first; sumDist_[id] = 0; for (map<size_t, Node*>::iterator j = currentNodes_.begin(); j != currentNodes_.end(); j++) { size_t jd = j->first; sumDist_[id] += matrix_(id, jd); } } vector<size_t> bestPair(2); double critMax = std::log(0.); for (map<size_t, Node*>::iterator i = currentNodes_.begin(); i != currentNodes_.end(); i++) { size_t id = i->first; map<size_t, Node*>::iterator j = i; j++; for ( ; j != currentNodes_.end(); j++) { size_t jd = j->first; double crit = sumDist_[id] + sumDist_[jd] - static_cast<double>(currentNodes_.size() - 2) * matrix_(id, jd); // cout << "\t" << id << "\t" << jd << "\t" << crit << endl; if (crit > critMax) { critMax = crit; bestPair[0] = id; bestPair[1] = jd; } } } if (critMax == std::log(0.)) { throw Exception("Unexpected error: no maximum criterium found."); } return bestPair; } std::vector<double> NeighborJoining::computeBranchLengthsForPair(const std::vector<size_t>& pair) { double ratio = (sumDist_[pair[0]] - sumDist_[pair[1]]) / static_cast<double>(currentNodes_.size() - 2); vector<double> d(2); if (positiveLengths_) { d[0] = std::max(.5 * (matrix_(pair[0], pair[1]) + ratio), 0.); d[1] = std::max(.5 * (matrix_(pair[0], pair[1]) - ratio), 0.); } else { d[0] = .5 * (matrix_(pair[0], pair[1]) + ratio); d[1] = .5 * (matrix_(pair[0], pair[1]) - ratio); } return d; } double NeighborJoining::computeDistancesFromPair(const std::vector<size_t>& pair, const std::vector<double>& branchLengths, size_t pos) { return positiveLengths_ ? std::max(.5 * (matrix_(pair[0], pos) - branchLengths[0] + matrix_(pair[1], pos) - branchLengths[1]), 0.) : .5 * (matrix_(pair[0], pos) - branchLengths[0] + matrix_(pair[1], pos) - branchLengths[1]); } void NeighborJoining::finalStep(int idRoot) { Node* root = new Node(idRoot); map<size_t, Node* >::iterator it = currentNodes_.begin(); size_t i1 = it->first; Node* n1 = it->second; it++; size_t i2 = it->first; Node* n2 = it->second; if (currentNodes_.size() == 2) { // Rooted double d = matrix_(i1, i2) / 2; root->addSon(n1); root->addSon(n2); n1->setDistanceToFather(d); n2->setDistanceToFather(d); } else { // Unrooted it++; size_t i3 = it->first; Node* n3 = it->second; double d1 = positiveLengths_ ? std::max(matrix_(i1, i2) + matrix_(i1, i3) - matrix_(i2, i3), 0.) : matrix_(i1, i2) + matrix_(i1, i3) - matrix_(i2, i3); double d2 = positiveLengths_ ? std::max(matrix_(i2, i1) + matrix_(i2, i3) - matrix_(i1, i3), 0.) : matrix_(i2, i1) + matrix_(i2, i3) - matrix_(i1, i3); double d3 = positiveLengths_ ? std::max(matrix_(i3, i1) + matrix_(i3, i2) - matrix_(i1, i2), 0.) : matrix_(i3, i1) + matrix_(i3, i2) - matrix_(i1, i2); root->addSon(n1); root->addSon(n2); root->addSon(n3); n1->setDistanceToFather(d1 / 2.); n2->setDistanceToFather(d2 / 2.); n3->setDistanceToFather(d3 / 2.); } tree_ = new TreeTemplate<Node>(root); }
33.38125
135
0.628908
danydoerr
6432871bdc57b9574fd2a55cd84adf8e68b56258
317
cpp
C++
LeetCode/Problems/Algorithms/#96_UniqueBinarySearchTrees_sol4_catalan_numbers_O(N)_time_O(1)_extra_space.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#96_UniqueBinarySearchTrees_sol4_catalan_numbers_O(N)_time_O(1)_extra_space.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#96_UniqueBinarySearchTrees_sol4_catalan_numbers_O(N)_time_O(1)_extra_space.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { private: long long comb(int n, int k){ long long res = 1; for(int i = 1; i <= k; ++i){ res *= (n - k + i); res /= i; } return res; } public: int numTrees(int n) { return comb(2 * n, n) / (n + 1); } };
19.8125
41
0.37224
Tudor67
643327a34be9fdcd3335fe2b06e0f66cb2b32bb2
1,027
cpp
C++
Commom/BaseFrame.cpp
chungmin99/Medial-IPC
e5c7a2ed81f28bab6ad96eab61eb61213cb3089d
[ "MIT" ]
7
2021-10-30T16:48:31.000Z
2022-02-14T04:47:56.000Z
Commom/BaseFrame.cpp
chungmin99/Medial-IPC
e5c7a2ed81f28bab6ad96eab61eb61213cb3089d
[ "MIT" ]
null
null
null
Commom/BaseFrame.cpp
chungmin99/Medial-IPC
e5c7a2ed81f28bab6ad96eab61eb61213cb3089d
[ "MIT" ]
4
2021-08-31T00:24:49.000Z
2022-02-06T09:10:48.000Z
#include "BaseFrame.h" void BaseFrameConstraint::freeFrame() { select_frame.clear(); } void BaseFrameConstraint::setFrame(BaseFrame * f) { select_frame.append(f); } void BaseFrameConstraint::constrainTranslation(qglviewer::Vec& translation, qglviewer::Frame* const frame) { for (QList<localFrame*>::iterator it = select_frame.begin(), end = select_frame.end(); it != end; ++it) { (*it)->translate(translation); } } void BaseFrameConstraint::constrainRotation(qglviewer::Quaternion& rotation, qglviewer::Frame* const frame) { const qglviewer::Vec worldAxis = frame->inverseTransformOf(rotation.axis()); const qglviewer::Vec pos = frame->position(); const float angle = rotation.angle(); for (QList<localFrame*>::iterator it = select_frame.begin(), end = select_frame.end(); it != end; ++it) { qglviewer::Quaternion qVertex((*it)->transformOf(worldAxis), angle); (*it)->rotate(qVertex); qglviewer::Quaternion qWorld(worldAxis, angle); (*it)->setPosition(pos + qWorld.rotate((*it)->position() - pos)); } }
31.121212
107
0.719572
chungmin99
64333d1253de18a6251fbf26d6f9ce4649e87df2
9,548
cc
C++
src/xpath.cc
CodeCat-maker/cxml
e5912f997a050ffd26e40faaea14558456f6e119
[ "MIT" ]
115
2022-02-16T14:27:04.000Z
2022-03-29T23:05:24.000Z
src/xpath.cc
CodeCat-maker/cxml
e5912f997a050ffd26e40faaea14558456f6e119
[ "MIT" ]
null
null
null
src/xpath.cc
CodeCat-maker/cxml
e5912f997a050ffd26e40faaea14558456f6e119
[ "MIT" ]
1
2022-03-12T01:36:51.000Z
2022-03-12T01:36:51.000Z
#include "xpath.hpp" using std::cout; using std::endl; using std::__1::pair; using std::__1::queue; typedef queue<pair<string, string> > qpss; qpss queue_option; //储存操作类型和名称 int XPATH_PARSE_STATUE = XPATH_PARSE_SUCCESS; //child 子 //genera 后 const string options[] = { "get_parent_node", // /.. 选择父元素 ✅ "get_this_node", // /. 选择当前元素 ✅ "get_all_nodes", // /* 匹配任意元素 "get_node_from_genera_by_name", // //name 选择当前元素后代元素中的name元素 ✅ "get_node_from_child_by_name", // /name 选择当前元素子代元素中的name元素 ✅ "get_node_by_array_and_name", // /name[n] 选择当前元素下第n个name元素 ✅ "get_node_by_attr_and_name", // /name[@attr] 属性筛选,选择有attr属性的元素 ✅ "get_node_by_attrValue_and_name", // /name[@attr=value] 属性筛选,选择attr属性的值为value的name元素(属性值不加分号) ✅ "get_text_from_this", // /text() 返回当前元素中的文本 ✅ "get_texts_from_genera", // //text() 返回当前元素以及它所有后代元素中的文本 ✅ "get_attr_from_this", // /@attr 返回当前元素attr属性的值 ✅ "get_all_attr" // @* 匹配任意属性}; }; // string转int constexpr unsigned int str2int(const char *str, int h = 0) { return !str[h] ? 5381 : (str2int(str, h + 1) * 33) ^ str[h]; } pair<string, string> parse_option(const string op) { pair<string, string> ret; //取后代 if (op.find("//") < maxLength) { if (op.find("text()") < maxLength) { ret = {options[9], op.substr(2)}; } else { ret = {options[3], op.substr(2)}; } } else { //取子代 if (op.find("..") < maxLength) { ret = {options[0], ""}; } else if (op.find(".") < maxLength) { ret = {options[1], ""}; } else if (op.find("[") < maxLength) { if (op.find("@") < maxLength) { if (op.find("=") < maxLength) { ret = {options[7], op.substr(1)}; } else { ret = {options[6], op.substr(1)}; } } else { ret = {options[5], op.substr(1)}; } } else if (op.find("@") < maxLength) { ret = {options[10], op.substr(1)}; } else if (op.find("text()") < maxLength) { ret = {options[8], op.substr(1)}; } else { ret = {options[4], op.substr(1)}; } } //cout << ret.first << " " << ret.second << endl; return ret; } //返回父节点 CXMLNode *xpath_get_parent_node(CXMLNode *root) { return root->parent; } //返回当前节点 CXMLNode *xpath_get_this_node(CXMLNode *root) { return root; } //获取当前节点文本 string xpath_get_text_from_this(CXMLNode *root) { return root->text->content; } //获取当前节点后节点的所有文本 string xpath_get_texts_from_genera(CXMLNode *root) { pair<CXMLNode *, bool> d; queue<CXMLNode *> q; q.push(root); string ret; while (!q.empty()) { auto p = q.front(); q.pop(); for (auto m : p->children) { auto t = m->text; ret += t->content + " "; q.push(m); } } return ret; } //根据属性 值 名称 来选择节点 CXMLNode *xpath_get_node_by_attrValue_and_name(const string name, CXMLNode *root) { string attr_name = name.substr(name.find("@") + 1, name.find("=") - name.find("@") - 1); string value_name = name.substr(name.find("=") + 1, name.find("]") - name.find("=") - 1); string node_name = name.substr(0, name.find("[")); //cout << attr_name << " " << node_name << " " << value_name << endl; for (auto child : root->children) { CXMLNode_attr *att = child->attr; if (child->name == node_name) { for (auto item : att->attributes) { if (item.first == attr_name && item.second == value_name) { return child; } } } } return nullptr; } //根据属性 in过程 选择节点 CXMLNode *xpath_get_node_by_attr_and_name(const string name, CXMLNode *root) { string attr_name = name.substr(name.find("@") + 1, name.find("]") - name.find("@") - 1); string node_name = name.substr(0, name.find("[")); for (auto child : root->children) { CXMLNode_attr *att = child->attr; if (child->name == node_name) { for (auto item : att->attributes) { if (item.first == attr_name) return child; } } } return nullptr; } // 通过数组选择与名字相同的节点 CXMLNode *xpath_get_node_by_array_and_name(const string name, CXMLNode *root) { int j = *(name.substr(name.find("[") + 1, name.find("]") - name.find("[")).c_str()) - '0'; string tmp_name = name.substr(0, name.find("[")); cout << tmp_name << " " << j << " " << endl; int i = 0; for (auto child : root->children) { //cout << child->name << endl; if (child->name == tmp_name) { i++; if (i == j) return child; } } return nullptr; } //选择当前元素子代元素中的name元素 CXMLNode *xpath_get_node_from_child_by_name(const string name, CXMLNode *root) { if (root->children.size() == 0) return nullptr; for (auto child : root->children) { if (child->name == name) return child; } return nullptr; } map<CXMLNode *, bool> used; //选择当前元素后代元素中的name元素 CXMLNode *xpath_get_node_from_genera_by_name(const string name, CXMLNode *root) { if (root->name == name) { return root; } for (auto m : root->children) { if (used.count(m) == 0) { used.insert({m, true}); CXMLNode *result = xpath_get_node_from_genera_by_name(name, m); if (result != nullptr) return result; used.erase(m); } } return nullptr; } string xpath_get_attr_from_this(const string name, CXMLNode *root) { string attr_name = name.substr(name.find("@") + 1); string ret; CXMLNode_attr *a = root->attr; for (auto m : a->attributes) { if (m.first == attr_name) return m.second; } return ret; } //将操作入队 双指针算法入队 bool get_xpath_option(const string exp) { int l(0), r(0); int len = 0; while (len <= exp.length()) { if ((exp[len] == '/')) { if (exp[len + 1] == '/') r = l + 2; else r = l + 1; while (r <= exp.length()) { if (exp[r] == '/') break; r++; } string tmp_option = exp.substr(l, r - l); //cout << tmp_option << " "; queue_option.push(parse_option(tmp_option)); } len = r; l = r; } //string name = exp.substr(0, len); return true; } //处理xpath操作 bool do_xpath_option(CXMLNode *root, CXMLNode_result *result) { CXMLNode *node = root; string ret_text; while (queue_option.empty() == false) { pair<string, string> op = queue_option.front(); queue_option.pop(); string option = op.first; string name = op.second; //cout << option << " " << name << endl; switch (str2int(option.c_str())) { case str2int("get_node_from_genera_by_name"): node = xpath_get_node_from_genera_by_name(name, node); result->element = node; break; case str2int("get_node_from_child_by_name"): node = xpath_get_node_from_child_by_name(name, node); result->element = node; break; case str2int("get_node_by_array_and_name"): node = xpath_get_node_by_array_and_name(name, node); result->element = node; break; case str2int("get_node_by_attr_and_name"): node = xpath_get_node_by_attr_and_name(name, node); result->element = node; break; case str2int("get_node_by_attrValue_and_name"): node = xpath_get_node_by_attrValue_and_name(name, node); result->element = node; break; case str2int("get_text_from_this"): ret_text = xpath_get_text_from_this(node); result->text = ret_text; return true; case str2int("get_texts_from_genera"): ret_text = xpath_get_texts_from_genera(node); result->text = ret_text; return true; case str2int("get_this_node"): node = xpath_get_this_node(node); result->element = node; break; case str2int("get_parent_node"): node = xpath_get_parent_node(node); result->element = node; break; case str2int("get_attr_from_this"): ret_text = xpath_get_attr_from_this(name, node); result->text = ret_text; return true; default: return false; } } return true; } //返回xpath解析内容 const CXMLNode_result *xpath(const string exp, CXMLNode *root) { const char *ptr = exp.c_str(); CXMLNode_result *ret = new CXMLNode_result(); try { get_xpath_option(exp); do_xpath_option(root, ret); } catch (const std::exception &e) { XPATH_PARSE_STATUE = XPATH_SYNTAX_ERROR; return nullptr; } return ret; }
27.436782
99
0.519271
CodeCat-maker
6435e4fa88db25508361bbafe31959161ade016c
3,229
cpp
C++
src/uint64comp.cpp
whuang022nccu/IndriLab
24d13dca14c7c447a4acedb45d7d1ef83551f6ac
[ "Apache-2.0" ]
2
2020-02-16T07:46:47.000Z
2020-11-23T06:50:19.000Z
src/uint64comp.cpp
whuang022nccu/IndriLab
24d13dca14c7c447a4acedb45d7d1ef83551f6ac
[ "Apache-2.0" ]
null
null
null
src/uint64comp.cpp
whuang022nccu/IndriLab
24d13dca14c7c447a4acedb45d7d1ef83551f6ac
[ "Apache-2.0" ]
null
null
null
/*========================================================================== * Copyright (c) 2012 University of Massachusetts. All Rights Reserved. * * Use of the Lemur Toolkit for Language Modeling and Information Retrieval * is subject to the terms of the software license set forth in the LICENSE * file included with this software, and also available at * http://www.lemurproject.org/license.html * *========================================================================== */ #include "indri/uint64comp.hpp" #include <cstdlib> // All "string" functions adapted from: // http://en.wikibooks.org/wiki/C_Programming/Strings namespace indri { namespace parse { Uint64Comp::Uint64Comp() { } /* u_strlen */ size_t Uint64Comp::u_strlen(const UINT64 *s) { const UINT64 *p = s; /* Loop over the data in s. */ while (*p != '\0') p++; return (size_t)(p - s); } /* u_strcpy */ UINT64 *Uint64Comp::u_strcpy(UINT64 *s1, const UINT64 *s2) { UINT64 *dst = s1; const UINT64 *src = s2; /* Do the copying in a loop. */ while ((*dst++ = *src++) != '\0') ; /* The body of this loop is left empty. */ /* Return the destination string. */ return s1; } UINT64 *Uint64Comp::u_strdup(UINT64 *s) { int length = u_strlen(s) + 1; UINT64 *result = (UINT64*)malloc(length*sizeof(UINT64)); if (result == (UINT64*)0){return (UINT64*)0;} u_strcpy(result, s); return result; } /* u_strcmp */ // Note the unsigned conversion doesn't actually do anything here - UINT64 is unsigned already int Uint64Comp::u_strcmp(const UINT64 *s1, const UINT64 *s2) { UINT64 uc1, uc2; /* Move s1 and s2 to the first differing characters in each string, or the ends of the strings if they are identical. */ while (*s1 != '\0' && *s1 == *s2) { s1++; s2++; } /* Compare the characters as unsigned char and return the difference. */ uc1 = (*s1); uc2 = (*s2); return ((uc1 < uc2) ? -1 : (uc1 > uc2)); } /* u_strncmp */ // Note the unsigned conversion doesn't actually do anything here - UINT64 is unsigned already int Uint64Comp::u_strncmp(const UINT64 *s1, const UINT64 *s2, size_t n) { UINT64 uc1, uc2; /* Nothing to compare? Return zero. */ if (n == 0) return 0; /* Loop, comparing bytes. */ while (n-- > 0 && *s1 == *s2) { /* If we've run out of bytes or hit a null, return zero since we already know *s1 == *s2. */ if (n == 0 || *s1 == '\0') return 0; s1++; s2++; } uc1 = (*s1); uc2 = (*s2); return ((uc1 < uc2) ? -1 : (uc1 > uc2)); } } }
33.28866
120
0.462063
whuang022nccu
643a20e7e28a53e113a98419609f9a9f7bd635d5
456
cpp
C++
dbms/src/Functions/log.cpp
anrodigina/ClickHouse
7a4dc5a212ccbf8d0730db2d3fb25fc23574d803
[ "Apache-2.0" ]
4
2020-04-27T13:03:31.000Z
2020-10-15T09:51:13.000Z
dbms/src/Functions/log.cpp
anrodigina/ClickHouse
7a4dc5a212ccbf8d0730db2d3fb25fc23574d803
[ "Apache-2.0" ]
6
2020-01-28T22:09:09.000Z
2021-11-10T19:39:24.000Z
dbms/src/Functions/log.cpp
anrodigina/ClickHouse
7a4dc5a212ccbf8d0730db2d3fb25fc23574d803
[ "Apache-2.0" ]
2
2019-12-09T10:36:46.000Z
2022-01-13T17:14:08.000Z
#include <Functions/FunctionMathUnaryFloat64.h> #include <Functions/FunctionFactory.h> namespace DB { struct LogName { static constexpr auto name = "log"; }; using FunctionLog = FunctionMathUnaryFloat64<UnaryFunctionVectorized<LogName, log>>; void registerFunctionLog(FunctionFactory & factory) { factory.registerFunction<FunctionLog>(FunctionFactory::CaseInsensitive); factory.registerAlias("ln", "log", FunctionFactory::CaseInsensitive); } }
26.823529
84
0.789474
anrodigina
643b7784377b8f0ae60b4559ec236685c8aa8cb7
4,700
cc
C++
src/compiler/cpp_cb_plugin.cc
jinq0123/grpc_cb
1b3058528d66dd6777a3248550a3d87f6b9e1b7f
[ "Apache-2.0" ]
43
2016-11-02T15:19:00.000Z
2021-08-19T08:46:24.000Z
src/compiler/cpp_cb_plugin.cc
jinq0123/grpc_cb
1b3058528d66dd6777a3248550a3d87f6b9e1b7f
[ "Apache-2.0" ]
2
2018-02-09T09:06:37.000Z
2018-08-18T01:26:13.000Z
src/compiler/cpp_cb_plugin.cc
jinq0123/grpc_cb
1b3058528d66dd6777a3248550a3d87f6b9e1b7f
[ "Apache-2.0" ]
19
2016-12-04T08:49:27.000Z
2022-03-29T07:30:59.000Z
/* * * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. 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. * */ // Generates cpp_cb gRPC service interface out of Protobuf IDL. // #include <memory> #include "config.h" #include "cpp_generator_helpers.h" #include "cpp_cb_generator.h" class CppcbGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator { public: CppcbGrpcGenerator() {} virtual ~CppcbGrpcGenerator() {} virtual bool Generate(const grpc::protobuf::FileDescriptor *file, const grpc::string &parameter, grpc::protobuf::compiler::GeneratorContext *context, grpc::string *error) const { if (file->options().cc_generic_services()) { *error = "cpp grpc proto compiler plugin does not work with generic " "services. To generate cpp grpc APIs, please set \"" "cc_generic_service = false\"."; return false; } grpc_cpp_cb_generator::Parameters generator_parameters; if (!parameter.empty()) { std::vector<grpc::string> parameters_list = grpc_generator::tokenize(parameter, ","); for (auto parameter_string = parameters_list.begin(); parameter_string != parameters_list.end(); parameter_string++) { std::vector<grpc::string> param = grpc_generator::tokenize(*parameter_string, "="); if (param[0] == "services_namespace") { generator_parameters.services_namespace = param[1]; } else { *error = grpc::string("Unknown parameter: ") + *parameter_string; return false; } } } grpc::string file_name = grpc_generator::StripProto(file->name()); grpc::string header_code = grpc_cpp_cb_generator::GetHeaderPrologue(file, generator_parameters) + grpc_cpp_cb_generator::GetHeaderIncludes(file, generator_parameters) + grpc_cpp_cb_generator::GetHeaderServices(file, generator_parameters) + grpc_cpp_cb_generator::GetHeaderEpilogue(file, generator_parameters); std::unique_ptr<grpc::protobuf::io::ZeroCopyOutputStream> header_output( context->Open(file_name + ".grpc_cb.pb.h")); grpc::protobuf::io::CodedOutputStream header_coded_out( header_output.get()); header_coded_out.WriteRaw(header_code.data(), header_code.size()); grpc::string source_code = grpc_cpp_cb_generator::GetSourcePrologue(file, generator_parameters) + grpc_cpp_cb_generator::GetSourceIncludes(file, generator_parameters) + grpc_cpp_cb_generator::GetSourceDescriptors(file, generator_parameters) + grpc_cpp_cb_generator::GetSourceServices(file, generator_parameters) + grpc_cpp_cb_generator::GetSourceEpilogue(file, generator_parameters); std::unique_ptr<grpc::protobuf::io::ZeroCopyOutputStream> source_output( context->Open(file_name + ".grpc_cb.pb.cc")); grpc::protobuf::io::CodedOutputStream source_coded_out( source_output.get()); source_coded_out.WriteRaw(source_code.data(), source_code.size()); return true; } }; int main(int argc, char *argv[]) { CppcbGrpcGenerator generator; return grpc::protobuf::compiler::PluginMain(argc, argv, &generator); }
41.59292
81
0.709787
jinq0123
6440fc2cf30396e4f846a722df41dcc453dff4bf
5,963
hpp
C++
runtime/cpp/src/core/Engine.hpp
DaMSL/K3
51749157844e76ae79dba619116fc5ad9d685643
[ "Apache-2.0" ]
17
2015-05-27T17:36:33.000Z
2020-06-07T07:21:29.000Z
runtime/cpp/src/core/Engine.hpp
DaMSL/K3
51749157844e76ae79dba619116fc5ad9d685643
[ "Apache-2.0" ]
3
2015-10-02T19:37:58.000Z
2016-01-05T18:26:48.000Z
runtime/cpp/src/core/Engine.hpp
DaMSL/K3
51749157844e76ae79dba619116fc5ad9d685643
[ "Apache-2.0" ]
6
2015-03-18T20:05:24.000Z
2020-02-06T21:35:09.000Z
#ifndef K3_ENGINE #define K3_ENGINE #include <atomic> #include <vector> #include <unordered_map> #ifdef _WIN32 #include <winsock2.h> #endif //_WIN32 #include <spdlog/spdlog.h> #include <boost/date_time/posix_time/posix_time.hpp> #include "Common.hpp" #include "Hash.hpp" #include "Options.hpp" #include "network/NetworkManager.hpp" #include "storage/StorageManager.hpp" #include "serialization/Yaml.hpp" #include "serialization/Codec.hpp" #include "Peer.hpp" #include "builtins/ProfilingBuiltins.hpp" namespace K3 { class ProgramContext; class Engine { public: // Core Interface Engine(const Options& opts); ~Engine(); template <class Context> void run(); void stop(); void join(); template <class T> void send(const Address& src, const Address& dst, TriggerID trig, const T& value); template <class T> void send(const Address& src, const Address& dst, TriggerID trig, T&& value); // Delayed sends, in microseconds from now. template <class T> void delayedSend(const Address& src, const Address& dst, TriggerID trig, const T& value, const TimerType& tmty, int delay); template <class T> void delayedSend(const Address& src, const Address& dst, TriggerID trig, T&& value, const TimerType& tmty, int delay); // Accessors ProgramContext& getContext(const Address& addr); NetworkManager& getNetworkManager(); StorageManager& getStorageManager(); protected: // Components shared_ptr<spdlog::logger> logger_; NetworkManager network_manager_; StorageManager storage_manager_; std::unordered_map<Address, shared_ptr<Peer>> peers_; // Configuration Options options_; // State std::atomic<bool> running_; std::atomic<int> ready_peers_; int total_peers_; }; template <class Context> void Engine::run() { if (running_) { throw std::runtime_error("Engine run(): already running"); } logger_->info("The Engine has started."); // Create peers from their command line arguments auto ctxt_fac = make_shared<ContextFactory>( [this]() { return make_shared<Context>(*this); }); auto rdy_callback = [this]() { ready_peers_++; }; vector<YAML::Node> nodes = serialization::yaml::parsePeers(options_.peer_strs_); for (auto node : nodes) { Address addr = serialization::yaml::meFromYAML(node); if (peers_.find(addr) != end(peers_)) { throw std::runtime_error("Engine createPeers(): Duplicate address: " + addr.toString()); } auto p = make_shared<Peer>(ctxt_fac, node, rdy_callback, options_); peers_[addr] = p; } total_peers_ = peers_.size(); // Wait for peers to check in while (total_peers_ > ready_peers_) continue; logger_->info("All peers are ready."); // Accept network connections and send initial messages for (auto& it : peers_) { network_manager_.listenInternal(it.second); it.second->processRole(); } // All roles are processed: signal peers to start message loop for (auto& it : peers_) { it.second->start(); } running_ = true; return; } unique_ptr<Dispatcher> getDispatcher(Peer& p, unique_ptr<NativeValue>, TriggerID trig); string getTriggerName(int); template <class T> void Engine::send(const Address& src, const Address& dst, TriggerID trig, T&& value) { if (peers_.empty()) { throw std::runtime_error( "Engine send(): Can't send before peers_ is initialized"); } if (logger_->level() <= spdlog::level::debug) { logger_->debug() << "Message: " << src.toString() << " --> " << dst.toString() << " @" << getTriggerName(trig); } auto it = peers_.find(dst); if (options_.local_sends_enabled_ && it != end(peers_)) { // Direct enqueue for local messages auto nv = std::make_unique<TNativeValue<T>>(std::move(value)); auto d = getDispatcher(*it->second, std::move(nv), trig); #ifdef K3MESSAGETRACE d->source_ = src; d->destination_ = dst; #endif #if defined(K3MESSAGETRACE) || defined(K3TRIGGERTIMES) d->trigger_ = trig; #endif it->second->getQueue().enqueue(std::move(d)); } else { // Serialize and send over the network, otherwise unique_ptr<PackedValue> pv = pack<T>(value, K3_INTERNAL_FORMAT); auto m = make_unique<OutNetworkMessage>(trig, std::move(pv)); #ifdef K3MESSAGETRACE m->source_ = src; m->destination_ = dst; #endif network_manager_.sendInternal(dst, std::move(m)); } } template <class T> void Engine::send(const Address& src, const Address& dst, TriggerID trig, const T& value) { send(src, dst, trig, T(value)); } // Delayed sends, based on timers. template <class T> void Engine::delayedSend(const Address& src, const Address& dst, TriggerID trig, T&& value, const TimerType& tmty, int delay) { if (peers_.empty()) { throw std::runtime_error( "Engine send(): Can't send before peers_ is initialized"); } if (logger_->level() <= spdlog::level::debug) { logger_->debug() << "Delayed Message: " << src.toString() << " --> " << dst.toString() << " @" << getTriggerName(trig); } auto timer_key = network_manager_.timerKey(tmty, src, dst, trig); network_manager_.addTimer(timer_key, boost::posix_time::microseconds(delay)); auto cb = [this, timer_key, src, dst, trig, value = std::move(value)] (const boost::system::error_code& error) mutable { if ( !error ) { this->network_manager_.removeTimer(timer_key); this->send(src, dst, trig, std::move(value)); } }; network_manager_.asyncWaitTimer(timer_key, cb); } template <class T> void Engine::delayedSend(const Address& src, const Address& dst, TriggerID trig, const T& value, const TimerType& tmty, int delay) { delayedSend(src, dst, trig, T(value), tmty, delay); } } // namespace K3 #endif
30.116162
87
0.654704
DaMSL
6443612b8ba3bf6d37f5479b2f9fb701af73de00
12,834
inl
C++
Library/Sources/Stroika/Foundation/Containers/Concrete/Mapping_LinkedList.inl
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
28
2015-09-22T21:43:32.000Z
2022-02-28T01:35:01.000Z
Library/Sources/Stroika/Foundation/Containers/Concrete/Mapping_LinkedList.inl
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
98
2015-01-22T03:21:27.000Z
2022-03-02T01:47:00.000Z
Library/Sources/Stroika/Foundation/Containers/Concrete/Mapping_LinkedList.inl
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
4
2019-02-21T16:45:25.000Z
2022-02-18T13:40:04.000Z
/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #ifndef _Stroika_Foundation_Containers_Concrete_Mapping_LinkedList_inl_ #define _Stroika_Foundation_Containers_Concrete_Mapping_LinkedList_inl_ /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../../Memory/BlockAllocated.h" #include "../Private/IteratorImplHelper.h" #include "../Private/PatchingDataStructures/LinkedList.h" namespace Stroika::Foundation::Containers::Concrete { using Traversal::IteratorOwnerID; /* ******************************************************************************** ******** Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::IImplRepBase_ ******** ******************************************************************************** */ template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> class Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::IImplRepBase_ : public Mapping<KEY_TYPE, MAPPED_VALUE_TYPE>::_IRep { private: using inherited = typename Mapping<KEY_TYPE, MAPPED_VALUE_TYPE>::_IRep; #if qCompilerAndStdLib_TemplateTypenameReferenceToBaseOfBaseClassMemberNotFound_Buggy protected: using _APPLY_ARGTYPE = typename inherited::_APPLY_ARGTYPE; using _APPLYUNTIL_ARGTYPE = typename inherited::_APPLYUNTIL_ARGTYPE; #endif }; /* ******************************************************************************** *********** Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::Rep_*************** ******************************************************************************** */ template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> template <typename KEY_EQUALS_COMPARER> class Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::Rep_ : public IImplRepBase_, public Memory::UseBlockAllocationIfAppropriate<Rep_<KEY_EQUALS_COMPARER>> { private: using inherited = IImplRepBase_; public: using _IterableRepSharedPtr = typename Iterable<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::_IterableRepSharedPtr; using _MappingRepSharedPtr = typename inherited::_MappingRepSharedPtr; using _APPLY_ARGTYPE = typename inherited::_APPLY_ARGTYPE; using _APPLYUNTIL_ARGTYPE = typename inherited::_APPLYUNTIL_ARGTYPE; using KeyEqualsCompareFunctionType = typename Mapping<KEY_TYPE, MAPPED_VALUE_TYPE>::KeyEqualsCompareFunctionType; public: Rep_ (const KEY_EQUALS_COMPARER& keyEqualsComparer) : fKeyEqualsComparer_{keyEqualsComparer} { } Rep_ (const Rep_& from) = delete; Rep_ (Rep_* from, IteratorOwnerID forIterableEnvelope) : inherited () , fKeyEqualsComparer_{from->fKeyEqualsComparer_} , fData_{&from->fData_, forIterableEnvelope} { RequireNotNull (from); } public: nonvirtual Rep_& operator= (const Rep_&) = delete; private: KEY_EQUALS_COMPARER fKeyEqualsComparer_; // Iterable<T>::_IRep overrides public: virtual _IterableRepSharedPtr Clone (IteratorOwnerID forIterableEnvelope) const override { // const cast because though cloning LOGICALLY makes no changes in reality we have to patch iterator lists return Iterable<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::template MakeSmartPtr<Rep_> (const_cast<Rep_*> (this), forIterableEnvelope); } virtual Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>> MakeIterator (IteratorOwnerID suggestedOwner) const override { Rep_* NON_CONST_THIS = const_cast<Rep_*> (this); // logically const, but non-const cast cuz re-using iterator API return Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>> (Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::template MakeSmartPtr<IteratorRep_> (suggestedOwner, &NON_CONST_THIS->fData_)); } virtual size_t GetLength () const override { return fData_.GetLength (); } virtual bool IsEmpty () const override { return fData_.IsEmpty (); } virtual void Apply (_APPLY_ARGTYPE doToElement) const override { // empirically faster (vs2k13) to lock once and apply (even calling stdfunc) than to // use iterator (which currently implies lots of locks) with this->_Apply () fData_.Apply (doToElement); } virtual Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>> FindFirstThat (_APPLYUNTIL_ARGTYPE doToElement, IteratorOwnerID suggestedOwner) const override { shared_lock<const Debug::AssertExternallySynchronizedLock> critSec{fData_}; using RESULT_TYPE = Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>; using SHARED_REP_TYPE = Traversal::IteratorBase::PtrImplementationTemplate<IteratorRep_>; auto iLink = fData_.FindFirstThat (doToElement); if (iLink == nullptr) { return RESULT_TYPE::GetEmptyIterator (); } Rep_* NON_CONST_THIS = const_cast<Rep_*> (this); // logically const, but non-const cast cuz re-using iterator API SHARED_REP_TYPE resultRep = Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::template MakeSmartPtr<IteratorRep_> (suggestedOwner, &NON_CONST_THIS->fData_); resultRep->fIterator.SetCurrentLink (iLink); // because Iterator<T> locks rep (non recursive mutex) - this CTOR needs to happen outside CONTAINER_LOCK_HELPER_START() return RESULT_TYPE (move (resultRep)); } // Mapping<KEY_TYPE, MAPPED_VALUE_TYPE>::_IRep overrides public: virtual KeyEqualsCompareFunctionType GetKeyEqualsComparer () const override { return KeyEqualsCompareFunctionType{fKeyEqualsComparer_}; } virtual _MappingRepSharedPtr CloneEmpty (IteratorOwnerID forIterableEnvelope) const override { if (fData_.HasActiveIterators ()) { // const cast because though cloning LOGICALLY makes no changes in reality we have to patch iterator lists auto r = Iterable<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::template MakeSmartPtr<Rep_> (const_cast<Rep_*> (this), forIterableEnvelope); r->fData_.RemoveAll (); return r; } else { return Iterable<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::template MakeSmartPtr<Rep_> (fKeyEqualsComparer_); } } virtual Iterable<KEY_TYPE> Keys () const override { return this->_Keys_Reference_Implementation (); } virtual Iterable<MAPPED_VALUE_TYPE> MappedValues () const override { return this->_Values_Reference_Implementation (); } virtual bool Lookup (ArgByValueType<KEY_TYPE> key, optional<MAPPED_VALUE_TYPE>* item) const override { shared_lock<const Debug::AssertExternallySynchronizedLock> critSec{fData_}; for (typename DataStructures::LinkedList<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::ForwardIterator it (&fData_); it.More (nullptr, true);) { if (fKeyEqualsComparer_ (it.Current ().fKey, key)) { if (item != nullptr) { *item = it.Current ().fValue; } return true; } } if (item != nullptr) { *item = nullopt; } return false; } virtual bool Add (ArgByValueType<KEY_TYPE> key, ArgByValueType<MAPPED_VALUE_TYPE> newElt, AddReplaceMode addReplaceMode) override { using Traversal::kUnknownIteratorOwnerID; lock_guard<const Debug::AssertExternallySynchronizedLock> critSec{fData_}; for (typename DataStructureImplType_::ForwardIterator it (kUnknownIteratorOwnerID, &fData_); it.More (nullptr, true);) { if (fKeyEqualsComparer_ (it.Current ().fKey, key)) { switch (addReplaceMode) { case AddReplaceMode::eAddReplaces: fData_.SetAt (it, KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>{key, newElt}); break; case AddReplaceMode::eAddIfMissing: break; default: AssertNotReached (); } return false; } } fData_.Append (KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>{key, newElt}); return true; } virtual void Remove (ArgByValueType<KEY_TYPE> key) override { using Traversal::kUnknownIteratorOwnerID; lock_guard<const Debug::AssertExternallySynchronizedLock> critSec{fData_}; for (typename DataStructureImplType_::ForwardIterator it (kUnknownIteratorOwnerID, &fData_); it.More (nullptr, true);) { if (fKeyEqualsComparer_ (it.Current ().fKey, key)) { fData_.RemoveAt (it); return; } } } virtual void Remove (const Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>& i) override { lock_guard<const Debug::AssertExternallySynchronizedLock> critSec{fData_}; const typename Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::IRep& ir = i.ConstGetRep (); AssertMember (&ir, IteratorRep_); auto& mir = dynamic_cast<const IteratorRep_&> (ir); fData_.RemoveAt (mir.fIterator); } #if qDebug virtual void AssertNoIteratorsReferenceOwner (IteratorOwnerID oBeingDeleted) const override { shared_lock<const Debug::AssertExternallySynchronizedLock> critSec{fData_}; fData_.AssertNoIteratorsReferenceOwner (oBeingDeleted); } #endif private: using DataStructureImplType_ = Private::PatchingDataStructures::LinkedList<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>; using IteratorRep_ = Private::IteratorImplHelper_<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>, DataStructureImplType_>; private: DataStructureImplType_ fData_; }; /* ******************************************************************************** *************** Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE> **************** ******************************************************************************** */ template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> inline Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::Mapping_LinkedList () : Mapping_LinkedList{equal_to<KEY_TYPE>{}} { AssertRepValidType_ (); } template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> template <typename KEY_EQUALS_COMPARER, enable_if_t<Common::IsPotentiallyComparerRelation<KEY_TYPE, KEY_EQUALS_COMPARER> ()>*> Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::Mapping_LinkedList (const KEY_EQUALS_COMPARER& keyEqualsComparer) : inherited (inherited::template MakeSmartPtr<Rep_<KEY_EQUALS_COMPARER>> (keyEqualsComparer)) { AssertRepValidType_ (); } template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> template <typename CONTAINER_OF_ADDABLE, enable_if_t<Configuration::IsIterable_v<CONTAINER_OF_ADDABLE> and not is_convertible_v<const CONTAINER_OF_ADDABLE*, const Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>*>>*> inline Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::Mapping_LinkedList (const CONTAINER_OF_ADDABLE& src) : Mapping_LinkedList{} { this->AddAll (src); AssertRepValidType_ (); } template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> template <typename COPY_FROM_ITERATOR_KEYVALUE> Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::Mapping_LinkedList (COPY_FROM_ITERATOR_KEYVALUE start, COPY_FROM_ITERATOR_KEYVALUE end) : Mapping_LinkedList{} { this->AddAll (start, end); AssertRepValidType_ (); } template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> inline void Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::AssertRepValidType_ () const { #if qDebug typename inherited::template _SafeReadRepAccessor<IImplRepBase_> tmp{this}; // for side-effect of AssertMemeber #endif } } #endif /* _Stroika_Foundation_Containers_Concrete_Mapping_LinkedList_inl_ */
49.361538
219
0.62576
SophistSolutions
64454fd1135bdb44d4768d9b00c52a088fc94d15
1,192
cpp
C++
codeSpace/Leetcode_684.cpp
chen810/study-code
79cac459595aee422fecbe281705b0ec7a7a08d2
[ "MIT" ]
1
2020-10-18T14:08:21.000Z
2020-10-18T14:08:21.000Z
codeSpace/Leetcode_684.cpp
chen810/study-code
79cac459595aee422fecbe281705b0ec7a7a08d2
[ "MIT" ]
null
null
null
codeSpace/Leetcode_684.cpp
chen810/study-code
79cac459595aee422fecbe281705b0ec7a7a08d2
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; class Solution { public: int Find(vector<int>& parent, int index) { // 返回parent[index]的值,顺便更新最新节点的分组 if (parent[index] != index) { // 如果被分组过则进行再次分组 parent[index] = Find(parent, parent[index]); // } return parent[index]; } void Union(vector<int>&parent, int index1, int index2){ // 两个分组合一 parent[Find(parent, index1)] = Find(parent, index2); } vector<int> findRedundantConnection(vector<vector<int>>& edges) { int n = edges.size(); // n条边 vector<int> parent(n + 1); // n个节点 for (int i = 1; i <= n; ++i) { // 初始单独分组 parent[i] = i; } for (auto& i : edges) { // 寻找冲突 int node1 = i[0], node2 = i[1]; if (Find(parent, node1) != Find(parent, node2)) { Union(parent, node1, node2); } else { return i; // 返回冲突 } } return vector<int>{}; } }; int main() { vector<vector<int>> p{ {1,2},{1,3},{2,3} }; Solution t; auto q = t.findRedundantConnection(p); cout << q[0] << "," << q[1] << endl; }
31.368421
80
0.500839
chen810
64464fa0b3a914b63f3f8afdbb01377de8561fbb
5,852
cpp
C++
tests/test_nsg_multi_merge_index.cpp
liql2007/nsg
e47c8228aaeaa0ad83fb195150f742bd7e43e712
[ "MIT" ]
null
null
null
tests/test_nsg_multi_merge_index.cpp
liql2007/nsg
e47c8228aaeaa0ad83fb195150f742bd7e43e712
[ "MIT" ]
null
null
null
tests/test_nsg_multi_merge_index.cpp
liql2007/nsg
e47c8228aaeaa0ad83fb195150f742bd7e43e712
[ "MIT" ]
null
null
null
// // Created by liql2007 on 2020/12/23. // #include <cassert> #include <memory> #include <efanna2e/index_nsg.h> #include <faiss/Clustering.h> #include <efanna2e/test_helper.h> namespace { void loadDocIds(const PartInfo& part, std::vector<unsigned>& docIds) { std::ifstream in(part.idPath.c_str(), std::ios::binary); docIds.resize(part.vecNum); in.read((char*)docIds.data(), docIds.size() * sizeof(unsigned)); if (in.bad()) { std::cerr << "read doc id failed" << std::endl; in.close(); exit(-1); } in.close(); } void mergeNsgEdge(const PartInfo& part, const efanna2e::IndexNSG& partIndex, efanna2e::IndexNSG& index) { std::vector<unsigned> docIds; loadDocIds(part, docIds); auto& graph = index.graph(); const auto& partGraph = partIndex.graph(); auto dim = index.GetDimension(); auto isExist = [](const std::vector<unsigned> vec, unsigned v) { for (auto vi : vec) { if (vi == v) { return true; } } return false; }; #pragma omp parallel for for (size_t i = 0; i < partGraph.size(); ++i) { auto gid = docIds[i]; auto& neighbors = graph[gid]; if (neighbors.empty()) { // first add auto partVecPtr = partIndex.getData() + i * dim; auto vecPtr = const_cast<float*>(index.getData() + gid * dim); std::memcpy(vecPtr, partVecPtr, dim * sizeof(float)); } neighbors.reserve(neighbors.size() + partGraph[i].size()); for (auto partVecId : partGraph[i]) { auto partGid = docIds[partVecId]; if (!isExist(neighbors, partGid)) { neighbors.push_back(partGid); } } } auto& eps = index.getEps(); auto& partEps = partIndex.getEps(); for (auto partDocId : partEps) { auto partGid = docIds[partDocId]; if (!isExist(eps, partGid)) { eps.push_back(partGid); } } } void pruneEdge(unsigned R, efanna2e::IndexNSG& index) { std::cout << "prune edge" << std::endl; efanna2e::DistanceL2 distance; auto& graph = index.graph(); auto data = index.getData(); auto dim = index.GetDimension(); #pragma omp parallel for for (size_t id = 0; id < graph.size(); ++id) { auto& neighbors = graph[id]; if (neighbors.size() < R) { continue; } auto vec = data + id * dim; std::vector<efanna2e::Neighbor> pool(neighbors.size()); for (unsigned i = 0; i < neighbors.size(); ++i) { auto nid = neighbors[i]; assert(nid != id); auto nVec = data + nid * dim; pool[i].id = nid; pool[i].distance = distance.compare(vec, nVec, dim); } std::sort(pool.begin(), pool.end()); unsigned resultSize = 1; unsigned checkIndex = 1; while(++checkIndex < pool.size() && resultSize < R) { auto &p = pool[checkIndex]; bool occlude = false; for (unsigned t = 0; t < resultSize; t++) { if (p.id == pool[t].id) { occlude = true; break; } float djk = distance.compare(data + dim * (size_t)pool[t].id, data + dim * (size_t)p.id, (unsigned)dim); #ifdef SSG float cos_ij = (p.distance + pool[t].distance - djk) / 2 / sqrt(p.distance * pool[t].distance); if (cos_ij > efanna2e::cosinThreshold) { occlude = true; break; } #else if (djk < p.distance /* dik */) { occlude = true; break; } #endif } if (!occlude) pool[resultSize++] = p; } neighbors.resize(resultSize); for (unsigned i = 0; i < resultSize; ++i) { neighbors[i] = pool[i].id; } } } void statisticAndSet(efanna2e::IndexNSG& index) { unsigned max = 0, min = 1e6; double avg = 0; auto& graph = index.graph(); for (size_t i = 0; i < graph.size(); i++) { auto size = graph[i].size(); max = max < size ? size : max; min = min > size ? size : min; avg += size; } index.setWidth(max); avg /= index.getVecNum(); printf("Degree Statistics: Max = %d, Min = %d, Avg = %.3lf\n", max, min, avg); } } int main(int argc, char** argv) { if (argc != 3) { std::cout << argv[0] << " multi_index_dir R" << std::endl; exit(-1); } auto multi_index_path = argv[1]; unsigned R = (unsigned)atoi(argv[2]); Partitions parts; parts.deserialize(multi_index_path); efanna2e::IndexNSG index(parts.dim, parts.totalVecNum, efanna2e::L2, nullptr); float* vecData = new float[parts.totalVecNum * parts.dim]; index.graph().resize(parts.totalVecNum); index.setData(vecData); auto bb = std::chrono::high_resolution_clock::now(); auto partCount = parts.partInfos.size(); double avgDegree = 0; for (unsigned i = 0; i < partCount; ++i) { std::cout << "** Merge NSG: " << i + 1 << std::endl; const auto& part = parts.partInfos[i]; float* partVecData = NULL; unsigned pointNum, dim; load_data(part.docPath.c_str(), partVecData, pointNum, dim); assert(pointNum == part.vecNum); assert(dim == parts.dim); std::unique_ptr<float[]>holder(partVecData); efanna2e::IndexNSG partIndex(dim, pointNum, efanna2e::L2, nullptr); partIndex.Load(part.nsgPath.c_str()); partIndex.setData(partVecData); avgDegree += partIndex.getAvgDegree(); mergeNsgEdge(part, partIndex, index); } std::cout << "part index avg degree: " << avgDegree / partCount << "\n"; statisticAndSet(index); pruneEdge(R, index); // efanna2e::Parameters paras; // paras.Set<unsigned>("L", R); // index.tree_grow(paras); statisticAndSet(index); auto ee = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> diff = ee - bb; std::cout << "merge time: " << diff.count() << "\n"; index.Save(parts.getMergedNsgPath().c_str()); // save_data(parts.getMergedVecPath().c_str(), vecData, parts.totalVecNum, parts.dim); return 0; }
30.010256
88
0.596206
liql2007
644ac7f0f8b1fa90a8d6437f8f2a24c85481dce2
12,424
cpp
C++
check_fever_app/Palettes.cpp
Myzhar/Lepton3_Jetson
f6ecce258484b47e102da7239c942662520dd2bc
[ "MIT" ]
45
2020-06-08T00:23:55.000Z
2021-12-23T08:38:17.000Z
check_fever_app/Palettes.cpp
Myzhar/Lepton3_Jetson
f6ecce258484b47e102da7239c942662520dd2bc
[ "MIT" ]
12
2020-07-11T13:46:06.000Z
2022-03-23T11:38:56.000Z
check_fever_app/Palettes.cpp
Myzhar/Lepton3_Jetson
f6ecce258484b47e102da7239c942662520dd2bc
[ "MIT" ]
12
2020-06-08T02:27:54.000Z
2022-01-12T09:52:45.000Z
#include "Palettes.h" #include <math.h> #include <iostream> using namespace std; uint8_t colormap_byr[LUT_SIZE_8*3]; uint8_t colormap_bry[LUT_SIZE_8*3]; uint8_t colormap_bgyr[LUT_SIZE_8*3]; uint8_t colormap_whitehot[LUT_SIZE_8*3]; uint8_t colormap_blackhot[LUT_SIZE_8*3]; uint8_t colormap_whitehotBYR[LUT_SIZE_8*3]; uint8_t colormap_whitehotBRY[LUT_SIZE_8*3]; const uint8_t* palettes[PALETTES_COUNT] = { colormap_byr, colormap_bry, colormap_bgyr, colormap_whitehot, colormap_blackhot, colormap_whitehotBYR, colormap_whitehotBRY }; // From http://www.andrewnoske.com/wiki/Code_-_heatmaps_and_color_gradients void getHeatMapColorBYR(double value, double& red, double& green, double& blue) { const int NUM_COLORS = 3; static double color[NUM_COLORS][3] = { {0,0,1}, {1,1,0}, {1,0,0} }; // A static array of 3 colors: (blue, yellow, red) using {r,g,b} for each. int idx1; // |-- Our desired color will be between these two indexes in "color". int idx2; // | double fractBetween = 0; // Fraction between "idx1" and "idx2" where our value is. if(value <= 0) // accounts for an input <=0 { idx1 = idx2 = 0; } else if(value >= 1) // accounts for an input >=0 { idx1 = idx2 = NUM_COLORS-1; } else { value = value * (NUM_COLORS-1); // Will multiply value by NUM_COLORS (-1). idx1 = floor(value); // Our desired color will be after this index. idx2 = idx1+1; // ... and before this index (inclusive). fractBetween = value - static_cast<double>(idx1); // Distance between the two indexes (0-1). } red = (color[idx2][0] - color[idx1][0])*fractBetween + color[idx1][0]; green = (color[idx2][1] - color[idx1][1])*fractBetween + color[idx1][1]; blue = (color[idx2][2] - color[idx1][2])*fractBetween + color[idx1][2]; } void getHeatMapColorBRY(double value, double& red, double& green, double& blue) { const int NUM_COLORS = 3; static double color[NUM_COLORS][3] = { {0,0,1}, {1,0,0}, {1,1,0} }; // A static array of 3 colors: (blue, red, yellow ) using {r,g,b} for each. int idx1; // |-- Our desired color will be between these two indexes in "color". int idx2; // | double fractBetween = 0; // Fraction between "idx1" and "idx2" where our value is. if(value <= 0) // accounts for an input <=0 { idx1 = idx2 = 0; } else if(value >= 1) // accounts for an input >=0 { idx1 = idx2 = NUM_COLORS-1; } else { value = value * (NUM_COLORS-1); // Will multiply value by NUM_COLORS (-1). idx1 = floor(value); // Our desired color will be after this index. idx2 = idx1+1; // ... and before this index (inclusive). fractBetween = value - static_cast<double>(idx1); // Distance between the two indexes (0-1). } red = (color[idx2][0] - color[idx1][0])*fractBetween + color[idx1][0]; green = (color[idx2][1] - color[idx1][1])*fractBetween + color[idx1][1]; blue = (color[idx2][2] - color[idx1][2])*fractBetween + color[idx1][2]; } void getHeatMapColorBGYR(double value, double& red, double& green, double& blue) { const int NUM_COLORS = 4; static double color[NUM_COLORS][3] = { {0,0,1}, {0,1,0}, {1,1,0}, {1,0,0} }; // A static array of 4 colors: (blue, green, yellow, red) using {r,g,b} for each. int idx1; // |-- Our desired color will be between these two indexes in "color". int idx2; // | double fractBetween = 0; // Fraction between "idx1" and "idx2" where our value is. if(value <= 0) // accounts for an input <=0 { idx1 = idx2 = 0; } else if(value >= 1) // accounts for an input >=0 { idx1 = idx2 = NUM_COLORS-1; } else { value = value * (NUM_COLORS-1); // Will multiply value by NUM_COLORS (-1). idx1 = floor(value); // Our desired color will be after this index. idx2 = idx1+1; // ... and before this index (inclusive). fractBetween = value - static_cast<double>(idx1); // Distance between the two indexes (0-1). } red = (color[idx2][0] - color[idx1][0])*fractBetween + color[idx1][0]; green = (color[idx2][1] - color[idx1][1])*fractBetween + color[idx1][1]; blue = (color[idx2][2] - color[idx1][2])*fractBetween + color[idx1][2]; } void getHeatMapColorWhiteHot(double value, double& red, double& green, double& blue) { const int NUM_COLORS = 2; static double color[NUM_COLORS][3] = { {0,0,0}, {1,1,1} }; // A static array of 2 colors: (black, white) using {r,g,b} for each. int idx1; // |-- Our desired color will be between these two indexes in "color". int idx2; // | double fractBetween = 0; // Fraction between "idx1" and "idx2" where our value is. if(value <= 0) // accounts for an input <=0 { idx1 = idx2 = 0; } else if(value >= 1) // accounts for an input >=0 { idx1 = idx2 = NUM_COLORS-1; } else { value = value * (NUM_COLORS-1); // Will multiply value by NUM_COLORS (-1). idx1 = floor(value); // Our desired color will be after this index. idx2 = idx1+1; // ... and before this index (inclusive). fractBetween = value - static_cast<double>(idx1); // Distance between the two indexes (0-1). } red = (color[idx2][0] - color[idx1][0])*fractBetween + color[idx1][0]; green = (color[idx2][1] - color[idx1][1])*fractBetween + color[idx1][1]; blue = (color[idx2][2] - color[idx1][2])*fractBetween + color[idx1][2]; } void getHeatMapColorBlackHot(double value, double& red, double& green, double& blue) { const int NUM_COLORS = 2; static double color[NUM_COLORS][3] = { {1,1,1}, {0,0,0} }; // A static array of 2 colors: (black, white) using {r,g,b} for each. int idx1; // |-- Our desired color will be between these two indexes in "color". int idx2; // | double fractBetween = 0; // Fraction between "idx1" and "idx2" where our value is. if(value <= 0) // accounts for an input <=0 { idx1 = idx2 = 0; } else if(value >= 1) // accounts for an input >=0 { idx1 = idx2 = NUM_COLORS-1; } else { value = value * (NUM_COLORS-1); // Will multiply value by NUM_COLORS (-1). idx1 = floor(value); // Our desired color will be after this index. idx2 = idx1+1; // ... and before this index (inclusive). fractBetween = value - static_cast<double>(idx1); // Distance between the two indexes (0-1). } red = (color[idx2][0] - color[idx1][0])*fractBetween + color[idx1][0]; green = (color[idx2][1] - color[idx1][1])*fractBetween + color[idx1][1]; blue = (color[idx2][2] - color[idx1][2])*fractBetween + color[idx1][2]; } void getHeatMapColorWhiteHotBYR(double value, double& red, double& green, double& blue) { const int NUM_COLORS = 5; static double color[NUM_COLORS][3] = { {0,0,0}, {0,0,1}, {1,1,0}, {1,0,0}, {1,1,1} }; // A static array of 5 colors: (black, blue, yellow, red, white) using {r,g,b} for each. int idx1; // |-- Our desired color will be between these two indexes in "color". int idx2; // | double fractBetween = 0; // Fraction between "idx1" and "idx2" where our value is. if(value <= 0) // accounts for an input <=0 { idx1 = idx2 = 0; } else if(value >= 1) // accounts for an input >=0 { idx1 = idx2 = NUM_COLORS-1; } else { value = value * (NUM_COLORS-1); // Will multiply value by NUM_COLORS (-1). idx1 = floor(value); // Our desired color will be after this index. idx2 = idx1+1; // ... and before this index (inclusive). fractBetween = value - static_cast<double>(idx1); // Distance between the two indexes (0-1). } red = (color[idx2][0] - color[idx1][0])*fractBetween + color[idx1][0]; green = (color[idx2][1] - color[idx1][1])*fractBetween + color[idx1][1]; blue = (color[idx2][2] - color[idx1][2])*fractBetween + color[idx1][2]; } void getHeatMapColorWhiteHotBRY(double value, double& red, double& green, double& blue) { const int NUM_COLORS = 5; static double color[NUM_COLORS][3] = { {0,0,0}, {0,0,1}, {1,0,0}, {1,1,0}, {1,1,1} }; // A static array of 5 colors: (black, blue, red, yellow, white) using {r,g,b} for each. int idx1; // |-- Our desired color will be between these two indexes in "color". int idx2; // | double fractBetween = 0; // Fraction between "idx1" and "idx2" where our value is. if(value <= 0) // accounts for an input <=0 { idx1 = idx2 = 0; } else if(value >= 1) // accounts for an input >=0 { idx1 = idx2 = NUM_COLORS-1; } else { value = value * (NUM_COLORS-1); // Will multiply value by NUM_COLORS (-1). idx1 = floor(value); // Our desired color will be after this index. idx2 = idx1+1; // ... and before this index (inclusive). fractBetween = value - static_cast<double>(idx1); // Distance between the two indexes (0-1). } red = (color[idx2][0] - color[idx1][0])*fractBetween + color[idx1][0]; green = (color[idx2][1] - color[idx1][1])*fractBetween + color[idx1][1]; blue = (color[idx2][2] - color[idx1][2])*fractBetween + color[idx1][2]; } void createColorMaps() { double r,g,b; uint8_t r8,g8,b8; for( int i=0; i<LUT_SIZE_8; i++ ) { double val = static_cast<double>(i)/LUT_SIZE_8; // >>>>> BLU YELLOW RED getHeatMapColorBYR( val, r,g,b ); r8=static_cast<uint8_t>(r*255+0.5); g8=static_cast<uint8_t>(g*255+0.5); b8=static_cast<uint8_t>(b*255+0.5); colormap_byr[i*3+0] = r8; colormap_byr[i*3+1] = g8; colormap_byr[i*3+2] = b8; // <<<<< BLU YELLOW RED // >>>>> BLU RED YELLOW getHeatMapColorBRY( val, r,g,b ); r8=static_cast<uint8_t>(r*255+0.5); g8=static_cast<uint8_t>(g*255+0.5); b8=static_cast<uint8_t>(b*255+0.5); colormap_bry[i*3+0] = r8; colormap_bry[i*3+1] = g8; colormap_bry[i*3+2] = b8; // <<<<< BLU RED YELLOW // >>>>> BLU GREEN YELLOW RED getHeatMapColorBGYR( val, r,g,b ); r8=static_cast<uint8_t>(r*255+0.5); g8=static_cast<uint8_t>(g*255+0.5); b8=static_cast<uint8_t>(b*255+0.5); colormap_bgyr[i*3+0] = r8; colormap_bgyr[i*3+1] = g8; colormap_bgyr[i*3+2] = b8; // <<<<< BLU GREEN YELLOW RED // >>>>> WhiteHot getHeatMapColorWhiteHot( val, r,g,b ); r8=static_cast<uint8_t>(r*255+0.5); g8=static_cast<uint8_t>(g*255+0.5); b8=static_cast<uint8_t>(b*255+0.5); colormap_whitehot[i*3+0] = r8; colormap_whitehot[i*3+1] = g8; colormap_whitehot[i*3+2] = b8; // <<<<< WhiteHot // >>>>> BlackHot getHeatMapColorBlackHot( val, r,g,b ); r8=static_cast<uint8_t>(r*255+0.5); g8=static_cast<uint8_t>(g*255+0.5); b8=static_cast<uint8_t>(b*255+0.5); colormap_blackhot[i*3+0] = r8; colormap_blackhot[i*3+1] = g8; colormap_blackhot[i*3+2] = b8; // <<<<< BlackHot // >>>>> WhiteHot BYR getHeatMapColorWhiteHotBYR( val, r,g,b ); r8=static_cast<uint8_t>(r*255+0.5); g8=static_cast<uint8_t>(g*255+0.5); b8=static_cast<uint8_t>(b*255+0.5); colormap_whitehotBYR[i*3+0] = r8; colormap_whitehotBYR[i*3+1] = g8; colormap_whitehotBYR[i*3+2] = b8; // <<<<< WhiteHot BYR // >>>>> WhiteHot BRY getHeatMapColorWhiteHotBRY( val, r,g,b ); r8=static_cast<uint8_t>(r*255+0.5); g8=static_cast<uint8_t>(g*255+0.5); b8=static_cast<uint8_t>(b*255+0.5); colormap_whitehotBRY[i*3+0] = r8; colormap_whitehotBRY[i*3+1] = g8; colormap_whitehotBRY[i*3+2] = b8; // <<<<< WhiteHot BRY } }
36.327485
103
0.568496
Myzhar
644ae703913c3522fd31d9f5e3e487a917a3daa9
317
hpp
C++
sdk/FusionAPI.hpp
LB--/hSDK
2775c5aa7150c9c09162920070aa4363b99512cb
[ "Unlicense" ]
1
2021-09-18T22:50:59.000Z
2021-09-18T22:50:59.000Z
sdk/FusionAPI.hpp
LB--/hSDK
2775c5aa7150c9c09162920070aa4363b99512cb
[ "Unlicense" ]
null
null
null
sdk/FusionAPI.hpp
LB--/hSDK
2775c5aa7150c9c09162920070aa4363b99512cb
[ "Unlicense" ]
null
null
null
#ifndef hSDK_FusionAPI_HeaderPlusPlus #define hSDK_FusionAPI_HeaderPlusPlus #include "FusionAPI/Ccxhdr.h" #include "FusionAPI/CfcFile.h" #include "FusionAPI/ImageFlt.h" #include "FusionAPI/ImgFlt.h" #include "FusionAPI/Surface.h" #include "FusionAPI/Cncf.h" #include "FusionAPI/Mvt.h" #undef min #undef max #endif
19.8125
37
0.791798
LB--
64531ec75fc0932a0b58d98458c71676e618c134
1,196
hpp
C++
Libraries/Zilch/Delegate.hpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
3
2022-02-11T10:34:33.000Z
2022-02-24T17:44:17.000Z
Libraries/Zilch/Delegate.hpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
null
null
null
Libraries/Zilch/Delegate.hpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
null
null
null
// MIT Licensed (see LICENSE.md). #pragma once #ifndef ZILCH_DELEGATE_HPP # define ZILCH_DELEGATE_HPP namespace Zilch { // Invalid constants const size_t InvalidOpcodeLocation = (size_t)-1; // A delegate is a simple type that consists of an index for a function, as well // as the this pointer object class ZeroShared Delegate { public: // Constructor Delegate(); // Are two handles the exact same? bool operator==(const Delegate& rhs) const; bool operator==(Zero::NullPointerType) const; // Are two handles different? bool operator!=(const Delegate& rhs) const; bool operator!=(Zero::NullPointerType) const; // Hashes a handle (generally used by hashable containers) size_t Hash() const; // Checks if the value stored within the delegate is null (no function // pointer) bool IsNull() const; bool IsNotNull() const; // Invokes a delegate, automatically passing in the 'this' handle Any Invoke(const Array<Any>& arguments = Array<Any>()); public: // The function we run when invoking this delegate Function* BoundFunction; // The handle for the delegate Handle ThisHandle; }; typedef const Delegate& DelegateParam; } // namespace Zilch #endif
23.45098
80
0.727425
RyanTylerRae
6453a16d758ec757b3e1189d39f2c331d592f321
950
cpp
C++
31.05/run.cpp
NoizuHika/SOP
2ecfde6fba607f161a8e03ae353e36ea39c847e5
[ "MIT" ]
null
null
null
31.05/run.cpp
NoizuHika/SOP
2ecfde6fba607f161a8e03ae353e36ea39c847e5
[ "MIT" ]
null
null
null
31.05/run.cpp
NoizuHika/SOP
2ecfde6fba607f161a8e03ae353e36ea39c847e5
[ "MIT" ]
null
null
null
#include <iostream> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <string.h> pid_t cpid; void handler(int i){ kill(cpid, i); } auto main(int argc, char *argv[]) -> int { cpid = fork(); if (cpid == -1) { perror("fork"); exit(EXIT_FAILURE); } if (cpid == 0) { execvp(argv[1], argv+1); perror("execve"); exit(EXIT_FAILURE); } struct sigaction act{}; act.sa_handler = handler; sigaction(SIGTERM, &act, nullptr); signal(SIGINT, SIG_IGN); int status = 0; waitpid(cpid, &status, 0); if (WIFEXITED(status)) { std::cout << "Child PID is " << cpid << " proccess, status: " << WEXITSTATUS(status) << "\n"; } if (WIFSIGNALED(status)) { std::cout << "Procces: " << cpid << " killed by signal: " << WTERMSIG(status) << "\n" << strsignal(WTERMSIG(status)) << "\n"; } return 0; }
19.387755
97
0.572632
NoizuHika
645595c7fcdb1c67cbdbc185f43afe6d3c3092d2
8,859
cpp
C++
src/tests/ClassPath/src/Posix.cpp
TakuKitamura/verimqtt-c
30109f66df126e5860f2329ce2ad3cfb7f12d9da
[ "MIT" ]
null
null
null
src/tests/ClassPath/src/Posix.cpp
TakuKitamura/verimqtt-c
30109f66df126e5860f2329ce2ad3cfb7f12d9da
[ "MIT" ]
null
null
null
src/tests/ClassPath/src/Posix.cpp
TakuKitamura/verimqtt-c
30109f66df126e5860f2329ce2ad3cfb7f12d9da
[ "MIT" ]
null
null
null
// We need our declaration #include "../include/Platform/Platform.hpp" // We need locks too #include "../include/Threading/Lock.hpp" // We need Logger too #include "../include/Logger/Logger.hpp" #ifdef _POSIX #include <termios.h> #include <dlfcn.h> #include <fcntl.h> #include <syslog.h> #include <errno.h> #include <pwd.h> #include <signal.h> #include <unistd.h> #include <sys/stat.h> #ifdef _LINUX #include <grp.h> #endif namespace Platform { void * malloc(size_t size, const bool) { return ::malloc(size); } void * calloc(size_t elementNumber, size_t size, const bool) { return ::calloc(elementNumber, size); } void free(void * p, const bool) { ::free(p); } void * realloc(void * p, size_t size) { return ::realloc(p, size); } bool queryHiddenInput(const char * prompt, char * buffer, size_t & size) { struct termios oflags, nflags; // Don't allow multiple thread from running here static Threading::Lock lock; Threading::ScopedLock scope(lock); // Disabling echo FILE *in = fopen("/dev/tty", "r+"), *out = in; if (in == NULL) { in = stdin; out = stderr; } tcgetattr(fileno(in), &oflags); nflags = oflags; nflags.c_lflag &= ~ECHO; nflags.c_lflag |= ECHONL; if (tcsetattr(fileno(in), TCSANOW, &nflags) != 0 || fputs(prompt, out) < 0 || fflush(out) != 0 || fgets(buffer, size, stdin) == NULL || tcsetattr(fileno(stdin), TCSANOW, &oflags) != 0) { if (in != stdin) fclose(in); return false; } if (in != stdin) fclose(in); size = strlen(buffer); if (size && buffer[size - 1] == '\n') buffer[--size] = 0; return true; } const char * getProcessName() { static Strings::FastString processName; if (!processName) { #ifdef _LINUX FILE * f = fopen("/proc/self/cmdline", "r"); if (f) { char buffer[256]; processName = fgets(buffer, 256, f); fclose(f); } #else processName = getprogname(); #endif } return processName; } DynamicLibrary::DynamicLibrary(const char * pathToLibrary) : handle(dlopen(pathToLibrary, RTLD_LAZY)) { } DynamicLibrary::~DynamicLibrary() { if (handle) dlclose(handle); handle = 0; } // Load the given symbol out of this library void * DynamicLibrary::loadSymbol(const char * nameInUTF8) const { if (handle && nameInUTF8) return dlsym(handle, nameInUTF8); return 0; } // Get the platform expected file name for the given library name void DynamicLibrary::getPlatformName(const char * libraryName, char * outputName) { if (!libraryName || !outputName) return; strcpy(outputName, libraryName); strcat(outputName, ".so"); // On Mac OSX both .bundle and .so are valid, so let's use .so } /** The output sink to the error console */ struct SyslogSink : public Logger::OutputSink { // Members private: Threading::Lock lock; public: virtual void gotMessage(const char * message, const unsigned int flags) { if (logMask & flags) { Threading::ScopedLock scope(lock); int level = LOG_INFO; if ((flags & Logger::Dump) > 0) level = LOG_DEBUG; if ((flags & Logger::Warning) > 0) level = LOG_WARNING; if ((flags & Logger::Error) > 0) level = LOG_ERR; syslog(level, "%s", (const char*)message); } } SyslogSink(unsigned int logMask, const char * daemonName) : OutputSink(logMask) { openlog(daemonName, LOG_PID, LOG_DAEMON); } ~SyslogSink() { closelog(); } }; #define EXIT_SUCCESS 0 #define EXIT_FAILURE 1 #ifdef DEBUG #define OUTLOG(X, Y, ...) printf(Y "\n", ##__VA_ARGS__) // , __VA_ARGS) #else #define OUTLOG(X, Y, ...) syslog(X, Y, ##__VA_ARGS__) #endif static volatile bool childReady = false; // The child signal handler static void childSigHandler(int signum) { switch(signum) { case SIGALRM: childReady = false; break; case SIGUSR1: childReady = true; break; case SIGCHLD: childReady = false; break; default: break; } } struct RemovePIDFile { const char * pidFile; RemovePIDFile(const char * pidFile) : pidFile(pidFile) {} ~RemovePIDFile() { unlink(pidFile); } }; static RemovePIDFile & autoRemovePIDFile(const char * pidFile) { static RemovePIDFile i(pidFile); return i; } static bool isDaemonInstalled = false; bool daemonize(const char * pidFile, const char * syslogName, bool & isParent) { // Set up the logger to use Logger::setDefaultSink(new SyslogSink(Logger::getDefaultSink().logMask, syslogName)); Logger::log(Logger::Content, "Starting %s", syslogName); isParent = true; // Check if already a daemon if (isDaemonInstalled && getppid() == 1) { const char * ttyName = ctermid(NULL); int devtty = open(ttyName, O_RDWR); if (devtty < 0) { Logger::log(Logger::Content, "Seems like %s is already a daemon, the tty name is %s", syslogName, ttyName); return true; } close(devtty); } // Trap signals that we expect to recieve signal(SIGCHLD, childSigHandler); signal(SIGUSR1, childSigHandler); signal(SIGALRM, childSigHandler); // Fork off the parent process childReady = false; pid_t pid = fork(); if (pid < 0) { Logger::log(Logger::Error, "Unable to fork daemon, code=%d (%s)", errno, strerror(errno)); return false; } // If we got a good PID, then we can exit the parent process. if (pid > 0) { // Wait for confirmation from the child via SIGUSR1 or SIGCHLD uint32 sleepTime = 0; while (sleepTime < 2000 && !childReady) { usleep(100000); sleepTime += 100; } return childReady; } // At this point we are executing as the child process isParent = false; if (pidFile && pidFile[0]) { FILE * f = fopen(pidFile, "w"); fprintf(f, "%d", getpid()); fclose(f); (void)autoRemovePIDFile(pidFile); } // Cancel certain signals signal(SIGCHLD, SIG_DFL); // A child process dies // Various TTY signals signal(SIGTSTP, SIG_IGN); signal(SIGTTOU, SIG_IGN); signal(SIGTTIN, SIG_IGN); // Ignore hangup signal(SIGHUP, SIG_IGN); // Change the file mode mask, create new session for child, and change to root folder to avoid holding references umask(0); if (setsid() < 0) { Logger::log(Logger::Error, "Unable to create new session, code=%d (%s)", errno, strerror(errno)); return false; } if ((chdir("/")) < 0) { Logger::log(Logger::Error, "Unable to reset current directory, code=%d (%s)", errno, strerror(errno)); return false; } // Redirect standard files to /dev/null freopen( "/dev/null", "r", stdin); freopen( "/dev/null", "w", stdout); freopen( "/dev/null", "w", stderr); // Tell the parent process that we have started kill(getppid(), SIGUSR1); isDaemonInstalled = true; return true; } bool dropPrivileges(const bool userID, const bool groupID) { gid_t newgid = getgid(), oldgid = getegid(); uid_t newuid = getuid(), olduid = geteuid(); // We need to drop ancillary groups while we are root as they can be used back to regain root if (!olduid && groupID) setgroups(1, &newgid); if (groupID && newgid != oldgid) { if (setgid(newgid) == -1) return false; } if (userID && newuid != olduid) { if (setuid(newuid) == -1) return false; } // Verify we can get back to full privileges if (groupID && newgid != oldgid && (setegid(oldgid) != -1 || getegid() != newgid)) return false; if (userID && newuid != olduid && (seteuid(olduid) != -1 || geteuid() != newuid)) return false; return true; } } #endif
29.53
123
0.545998
TakuKitamura
6455ce89933bc8b63399ceed4c1c0619cd9cbc2e
917
hpp
C++
android-28/android/media/MediaCodecList.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/media/MediaCodecList.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-30/android/media/MediaCodecList.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once #include "../../JObject.hpp" class JArray; namespace android::media { class MediaCodecInfo; } namespace android::media { class MediaFormat; } class JString; namespace android::media { class MediaCodecList : public JObject { public: // Fields static jint ALL_CODECS(); static jint REGULAR_CODECS(); // QJniObject forward template<typename ...Ts> explicit MediaCodecList(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} MediaCodecList(QJniObject obj); // Constructors MediaCodecList(jint arg0); // Methods static jint getCodecCount(); static android::media::MediaCodecInfo getCodecInfoAt(jint arg0); JString findDecoderForFormat(android::media::MediaFormat arg0) const; JString findEncoderForFormat(android::media::MediaFormat arg0) const; JArray getCodecInfos() const; }; } // namespace android::media
22.365854
155
0.730643
YJBeetle
645a0446be72dd25ca73ee0770a8182841ad3bf2
6,938
cpp
C++
qtmultimedia/src/imports/audioengine/qdeclarative_audiolistener_p.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
1
2020-04-30T15:47:35.000Z
2020-04-30T15:47:35.000Z
qtmultimedia/src/imports/audioengine/qdeclarative_audiolistener_p.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
qtmultimedia/src/imports/audioengine/qdeclarative_audiolistener_p.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qdeclarative_audiolistener_p.h" #include "qdeclarative_audioengine_p.h" #include "qdebug.h" #define DEBUG_AUDIOENGINE QT_USE_NAMESPACE /*! \qmltype AudioListener \instantiates QDeclarativeAudioListener \since 5.0 \brief Control global listener parameters. \inqmlmodule QtAudioEngine \ingroup multimedia_audioengine \inherits Item \preliminary AudioListener will have only one global instance and you can either access it through the listener property of AudioEngine: \qml Rectangle { color:"white" width: 300 height: 500 AudioEngine { id:audioengine listener.up:"0,0,1" listener.velocity:"0,0,0" listener.direction:"0,1,0" listener.position:Qt.vector3d(observer.x, observer.y, 0); } Item { id: observer x: 10 + observer.percent * 100 y: 20 + observer.percent * 80 property real percent: 0 SequentialAnimation on percent { loops: Animation.Infinite running: true NumberAnimation { duration: 8000 from: 0 to: 1 } } } } \endqml or alternatively, by defining an AudioListener outside AudioEngine: \qml Rectangle { color:"white" width: 300 height: 500 AudioEngine { id:audioengine listener.up:"0,0,1" listener.velocity:"0,0,0" listener.direction:"0,1,0" } AudioListener { engine:audioengine position: Qt.vector3d(observer.x, observer.y, 0); } Item { id: observer x: 10 + observer.percent * 100 y: 20 + observer.percent * 80 property real percent: 0 SequentialAnimation on percent { loops: Animation.Infinite running: true NumberAnimation { duration: 8000 from: 0 to: 1 } } } } \endqml This separate AudioListener definition is allowed to make QML bindings easier in some cases. */ QDeclarativeAudioListener::QDeclarativeAudioListener(QObject *parent) : QObject(parent) , m_engine(0) { m_engine = qobject_cast<QDeclarativeAudioEngine*>(parent); } QDeclarativeAudioListener::~QDeclarativeAudioListener() { } /*! \qmlproperty QtAudioEngine::AudioEngine QtAudioEngine::AudioListener::engine This property holds the reference to AudioEngine, and must only be set once. */ QDeclarativeAudioEngine* QDeclarativeAudioListener::engine() const { return m_engine; } void QDeclarativeAudioListener::setEngine(QDeclarativeAudioEngine *engine) { setParent(engine); m_engine = engine; } /*! \qmlproperty vector3d QtAudioEngine::AudioListener::position This property holds the 3D position of the listener. */ QVector3D QDeclarativeAudioListener::position() const { return m_engine->engine()->listenerPosition(); } void QDeclarativeAudioListener::setPosition(const QVector3D &position) { #ifdef DEBUG_AUDIOENGINE qDebug() << "QDeclarativeAudioListener::setPosition"; #endif m_engine->engine()->setListenerPosition(position); emit positionChanged(); } /*! \qmlproperty vector3d QtAudioEngine::AudioListener::direction This property holds the normalized 3D direction vector of the listener. */ QVector3D QDeclarativeAudioListener::direction() const { return m_engine->engine()->listenerDirection(); } void QDeclarativeAudioListener::setDirection(const QVector3D &direction) { #ifdef DEBUG_AUDIOENGINE qDebug() << "QDeclarativeAudioListener::setDirection"; #endif m_engine->engine()->setListenerDirection(direction); emit directionChanged(); } /*! \qmlproperty vector3d QtAudioEngine::AudioListener::velocity This property holds the 3D velocity vector of the listener. */ QVector3D QDeclarativeAudioListener::velocity() const { return m_engine->engine()->listenerVelocity(); } void QDeclarativeAudioListener::setVelocity(const QVector3D &velocity) { #ifdef DEBUG_AUDIOENGINE qDebug() << "QDeclarativeAudioListener::setVelocity"; #endif m_engine->engine()->setListenerVelocity(velocity); emit velocityChanged(); } /*! \qmlproperty vector3d QtAudioEngine::AudioListener::up This property holds the normalized 3D up vector of the listener. */ QVector3D QDeclarativeAudioListener::up() const { return m_engine->engine()->listenerUp(); } void QDeclarativeAudioListener::setUp(const QVector3D &up) { #ifdef DEBUG_AUDIOENGINE qDebug() << "QDeclarativeAudioListener::setUp"; #endif m_engine->engine()->setListenerUp(up); emit upChanged(); } /*! \qmlproperty real QtAudioEngine::AudioListener::gain This property will modulate all audio output from audio engine instances. */ qreal QDeclarativeAudioListener::gain() const { return m_engine->engine()->listenerGain(); } void QDeclarativeAudioListener::setGain(qreal gain) { #ifdef DEBUG_AUDIOENGINE qDebug() << "QDeclarativeAudioListener::setGain"; #endif m_engine->engine()->setListenerGain(gain); emit gainChanged(); }
27.863454
96
0.662871
wgnet
645f0d1be2c6c4cf36ba6c144b211fc7a7f912cb
231
cpp
C++
variant/variant.cpp
danielkrupinski/cpp-playground
0b02de70bfdbbc7ebb073180972b382231a198d4
[ "MIT" ]
1
2018-07-23T21:15:11.000Z
2018-07-23T21:15:11.000Z
variant/variant.cpp
danielkrupinski/cpp-playground
0b02de70bfdbbc7ebb073180972b382231a198d4
[ "MIT" ]
null
null
null
variant/variant.cpp
danielkrupinski/cpp-playground
0b02de70bfdbbc7ebb073180972b382231a198d4
[ "MIT" ]
3
2018-11-10T05:39:00.000Z
2019-12-08T12:14:19.000Z
#include <iostream> #include <variant> int main() { std::variant<int, double> v = 20; std::cout << "v = " << std::get<int>(v) << '\n'; v = 33.33; std::cout << "v = " << std::get<double>(v) << '\n'; return 0; }
19.25
55
0.480519
danielkrupinski
64601ce7b4662e1beb8705ca8f670deef7141456
1,248
cpp
C++
nets/analyses/largestComponent.cpp
CxAalto/lcelib
dceea76e3f18696a2fa7c8287e1a537fbf493474
[ "0BSD" ]
1
2017-01-24T01:35:43.000Z
2017-01-24T01:35:43.000Z
nets/analyses/largestComponent.cpp
CxAalto/lcelib
dceea76e3f18696a2fa7c8287e1a537fbf493474
[ "0BSD" ]
null
null
null
nets/analyses/largestComponent.cpp
CxAalto/lcelib
dceea76e3f18696a2fa7c8287e1a537fbf493474
[ "0BSD" ]
null
null
null
/* largestComponent.cpp 2006 Jun 14 Author: Lauri Kovanen Reads a network from standard input and writes out largest component. The nodes will be re-indexed from 0 to N, where N is the size of the largest component. To compile: g++ -O -Wall largestComponent.cpp -o largestComponent To run: cat net.edg | ./largestComponent > net_largest.edg (net.edg is a file where each row contains the values EDGE TAIL EDGECHARACTERISTIC (EDGECHARACTERISTIC for example edge weight) */ //#define DEBUG // for debugging code to be run #define NDEBUG // to turn assertions off #include "../../Containers.H" #include "../../Nets.H" #include "../NetExtras.H" typedef float EdgeData; typedef SymmNet<EdgeData> NetType; int main(int argc, char* argv[]) { std::auto_ptr<NetType> netPointer(readNet2<NetType>(1,0)); NetType& net = *netPointer; // Create a reference for easier handling of net. std::auto_ptr<NetType> netPointer2(findLargestComponent<NetType>(net)); NetType& net2 = *netPointer2; // Create a reference for easier handling of net. outputEdgesAndWeights(net2); }
28.363636
82
0.642628
CxAalto
6462566d2243de74364fc34516a1934d95a5552e
627
cpp
C++
src/macro/macro39.cpp
chennachaos/stabfem
b3d1f44c45e354dc930203bda22efc800c377c6f
[ "MIT" ]
null
null
null
src/macro/macro39.cpp
chennachaos/stabfem
b3d1f44c45e354dc930203bda22efc800c377c6f
[ "MIT" ]
null
null
null
src/macro/macro39.cpp
chennachaos/stabfem
b3d1f44c45e354dc930203bda22efc800c377c6f
[ "MIT" ]
null
null
null
#include "Macro.h" #include "MacroQueue.h" extern MacroQueue macroQueue; int macro39(Macro &macro) { if (!macro) { macro.name = "stop"; macro.type = "ctrl"; macro.what = "stop macro queue execution"; macro.sensitivity[INTER] = true; macro.sensitivity[BATCH] = true; macro.sensitivity[PRE] = true; return 0; } //-------------------------------------------------------------------------------------------------- return macroQueue.macCmd.n + 1; //-------------------------------------------------------------------------------------------------- }
20.9
101
0.392344
chennachaos
6462ae75f72b596a29bd92f2f9898cf60c57628a
2,244
cpp
C++
src/osd/modules/render/bgfx/effectmanager.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
emulator/src/osd/modules/render/bgfx/effectmanager.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
emulator/src/osd/modules/render/bgfx/effectmanager.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:Ryan Holtz //============================================================ // // effectmanager.cpp - BGFX shader effect manager // // Maintains a string-to-entry lookup of BGFX shader // effects, defined by effect.h and read by effectreader.h // //============================================================ #include <rapidjson/document.h> #include <rapidjson/error/en.h> #include <bx/readerwriter.h> #include <bx/file.h> #include "emu.h" #include <bgfx/bgfx.h> #include "effectmanager.h" #include "effectreader.h" #include "effect.h" using namespace rapidjson; effect_manager::~effect_manager() { for (std::pair<std::string, bgfx_effect*> effect : m_effects) { delete effect.second; } m_effects.clear(); } bgfx_effect* effect_manager::effect(std::string name) { std::map<std::string, bgfx_effect*>::iterator iter = m_effects.find(name); if (iter != m_effects.end()) { return iter->second; } return load_effect(name); } bgfx_effect* effect_manager::load_effect(std::string name) { std::string full_name = name; if (full_name.length() < 5 || (full_name.compare(full_name.length() - 5, 5, ".json") != 0)) { full_name = full_name + ".json"; } std::string path; osd_subst_env(path, util::string_format("%s" PATH_SEPARATOR "effects" PATH_SEPARATOR, m_options.bgfx_path())); path += full_name; bx::FileReader reader; if (!bx::open(&reader, path.c_str())) { printf("Unable to open effect file %s\n", path.c_str()); return nullptr; } int32_t size (bx::getSize(&reader)); char* data = new char[size + 1]; bx::read(&reader, reinterpret_cast<void*>(data), size); bx::close(&reader); data[size] = 0; Document document; document.Parse<kParseCommentsFlag>(data); delete [] data; if (document.HasParseError()) { std::string error(GetParseError_En(document.GetParseError())); printf("Unable to parse effect %s. Errors returned:\n", path.c_str()); printf("%s\n", error.c_str()); return nullptr; } bgfx_effect* effect = effect_reader::read_from_value(document, "Effect '" + name + "': ", m_shaders); if (effect == nullptr) { printf("Unable to load effect %s\n", path.c_str()); return nullptr; } m_effects[name] = effect; return effect; }
23.621053
111
0.651515
Robbbert
6463d3a33ec0f14890570283641e453098957267
4,546
cpp
C++
Program/DefragIPv4.cpp
CapBuran/PCAPFilter_Faster
94058c53f3ce861d017580c853543893e9b88096
[ "Unlicense" ]
1
2020-07-16T09:03:43.000Z
2020-07-16T09:03:43.000Z
Program/DefragIPv4.cpp
CapBuran/PCAPFilter_Faster
94058c53f3ce861d017580c853543893e9b88096
[ "Unlicense" ]
1
2021-07-02T09:00:05.000Z
2021-07-02T09:00:05.000Z
Program/DefragIPv4.cpp
CapBuran/PCAPFilter_Faster
94058c53f3ce861d017580c853543893e9b88096
[ "Unlicense" ]
1
2019-10-25T14:42:50.000Z
2019-10-25T14:42:50.000Z
#include <cstring> #include "UInts.h" #include "DefragIPv4.h" #include "FilterTCPHeader.h" #include "FilterUDPHeader.h" #include "FilterSCTPHeader.h" struct HashForDefragRowsIVv4 { uint32_t src_addr; /**< source address */ uint32_t dst_addr; /**< destination address */ uint32_t network_id; uint16_t packet_id; HashForDefragRowsIVv4(uint16_t NetworkID, const FilterTraffic::ip4_header* IPv4) : network_id(NetworkID) , packet_id(IPv4->packet_id) , src_addr(IPv4->src_addr.ip_32) , dst_addr(IPv4->dst_addr.ip_32) { } bool operator<(const HashForDefragRowsIVv4& other) const { uint64_t S1 = packet_id + (static_cast<uint64_t>(network_id) << 32); uint64_t S2 = other.packet_id + (static_cast<uint64_t>(other.network_id) << 32); uint64_t S3 = src_addr + (static_cast<uint64_t>(dst_addr) << 32); uint64_t S4 = other.src_addr + (static_cast<uint64_t>(other.dst_addr) << 32); if (S1 == S2) return S1 < S2; else return S3 < S4; } }; struct DefragRowIPv4 { struct BeginEndFragment { uint16_t Begin; uint16_t Size; BeginEndFragment() : Begin(0) , Size(0) { } }; uint16_t MaxFragment; uint16_t CounterFragment; uint16_t StartIPv4; char summData[64 * 1024 - 64]; BeginEndFragment Fragments[256]; DefragRowIPv4() { MaxFragment = 0; CounterFragment = 0; StartIPv4 = 0; } bool IsContainsFragment(uint16_t Begin) const { for (uint16_t i = 0; i < CounterFragment; i++) { const BeginEndFragment& fragments = Fragments[i]; if (fragments.Begin == Begin) { return fragments.Size > 0; } } return false; } void AddFragment(uint16_t Begin, uint16_t Size, const char* Data) { if (IsContainsFragment(Begin)) return; BeginEndFragment& fragments = Fragments[CounterFragment++]; fragments.Begin = Begin; fragments.Size = Size; memcpy(&summData[StartIPv4 + (fragments.Begin << 3)], Data, Size << 3); } bool IsBuild() const { if (CounterFragment < 2) return false; uint16_t FindNextBegin = 0; for (uint16_t i = 0; i < CounterFragment; i++) { bool IsFind = false; for (uint16_t j = 0; j < CounterFragment; j++) { const BeginEndFragment& fragments = Fragments[j]; if (fragments.Begin == FindNextBegin) { IsFind = true; FindNextBegin = fragments.Begin + fragments.Size; break; } } if (!IsFind) return false; } return true; } DefragData Build(const char *Frame, uint32_t LengthFrame, const FilterTraffic::ip4_header* IPv4) { const uint16_t lenIP((IPv4->version_ihl & 0x0f) << 2); const uint16_t LengthIPData(Swap16(IPv4->total_length) - lenIP); StartIPv4 = static_cast<uint16_t>(reinterpret_cast<const char*>(IPv4) - Frame) + lenIP; if(CounterFragment == 0) memcpy(&summData[0], Frame, StartIPv4); const uint16_t fragment_offset = Swap16(IPv4->fragment_offset); if (IPv4->packet_id != 0) { uint16_t fragment_offset_begin = fragment_offset & 0x1FFF; if (!(fragment_offset & 0x2000)) { MaxFragment = fragment_offset_begin + (LengthIPData >> 3); } AddFragment(fragment_offset_begin, LengthIPData >> 3, reinterpret_cast<const char*>(IPv4) + lenIP); if (IsBuild()) { FilterTraffic::ip4_header* IPv4Build = reinterpret_cast<FilterTraffic::ip4_header*>(&summData[StartIPv4 - lenIP]); IPv4Build->total_length = Swap16(MaxFragment << 3); IPv4Build->fragment_offset = 0; IPv4Build->packet_id = 0; return DefragData( &summData[0], &summData[StartIPv4], (MaxFragment << 3) + StartIPv4, (MaxFragment << 3)); } } else { return DefragData(Frame, reinterpret_cast<const char*>(IPv4) + lenIP, LengthFrame, LengthIPData); } return DefragData(); } }; typedef std::map<HashForDefragRowsIVv4, DefragRowIPv4> typeDefragDataIPv4; static typeDefragDataIPv4 DefragDataIPv4; DefragData DefragIP::AddIPv4(uint32_t NetworkID, const char *Frame, uint32_t LengthFrame, const FilterTraffic::ip4_header* IPv4) { HashForDefragRowsIVv4 Packet(NetworkID, IPv4); return DefragDataIPv4[Packet].Build(Frame, LengthFrame, IPv4); } void DefragIP::EraseIPv4(uint32_t NetworkID, const FilterTraffic::ip4_header * IPv4) { HashForDefragRowsIVv4 Packet(NetworkID, IPv4); auto it_find = DefragDataIPv4.find(Packet); if (it_find != DefragDataIPv4.end()) { DefragDataIPv4.erase(it_find); } }
27.551515
128
0.66498
CapBuran
6464adb75fb222dc90ec6bfe9ea78ef820615f78
537
hpp
C++
Jagerts.Felcp.Xml/XmlFile.hpp
Jagreaper/Project-Felcp
195d5de4230fe98e53d862c5c69b986344bc2cf5
[ "MIT" ]
null
null
null
Jagerts.Felcp.Xml/XmlFile.hpp
Jagreaper/Project-Felcp
195d5de4230fe98e53d862c5c69b986344bc2cf5
[ "MIT" ]
null
null
null
Jagerts.Felcp.Xml/XmlFile.hpp
Jagreaper/Project-Felcp
195d5de4230fe98e53d862c5c69b986344bc2cf5
[ "MIT" ]
null
null
null
#pragma once #include "Jagerts.Felcp.Xml/XmlAttribute.hpp" #include "Jagerts.Felcp.Xml/XmlElement.hpp" namespace Jagerts::Felcp::Xml { class JAGERTS_FELCP_XML_API XmlFile { public: const std::vector<XmlElement>* GetElements() const; const std::vector<XmlElement> GetElements(const std::string name) const; void AddElement(const XmlElement& element); static void FromString(const std::string& string, XmlFile* file); void ToString(std::string* string); void Clear(); private: std::vector<XmlElement> _elements; }; }
24.409091
74
0.746741
Jagreaper
6466c2ba3ef7685dfcb8c2baaf3b8f52262d5218
1,681
cpp
C++
src/main.cpp
astojanov/Clover
80d6cb248737ab786300623a4678b4ab91e78fc2
[ "Apache-2.0" ]
63
2018-05-29T13:20:21.000Z
2022-01-01T23:41:04.000Z
src/main.cpp
astojanov/Clover
80d6cb248737ab786300623a4678b4ab91e78fc2
[ "Apache-2.0" ]
1
2018-10-23T11:49:33.000Z
2018-10-24T09:11:55.000Z
src/main.cpp
astojanov/Clover
80d6cb248737ab786300623a4678b4ab91e78fc2
[ "Apache-2.0" ]
5
2018-07-02T11:06:51.000Z
2021-02-27T09:18:05.000Z
#include <CloverBase.h> #include "../lib/cxxopts.h" #include "../lib/sysinfo.h" #include "../test/search/00_search.h" #include "../test/performance/00_test.h" #include "../test/validate/00_validate.h" #include "../test/accuracy/00_accuracy.h" int main (int argc, const char* argv[]) { // // Parse the option and perform different tests // try { cxxopts::Options options(argv[0], " - example command line options"); options.positional_help("[optional args]").show_positional_help(); options.add_options() ("a,accuracy", "Start the tests for accuracy") ("g,grid", "Start the grid search for hyperparameter optimization") ("v,validate", "Start the tests for validation") ("p,performance", "Start the tests for performance") ("h,help", "Print help") ; options.parse_positional({"input", "output", "positional"}); auto result = options.parse(argc, argv); if (result.count("help")) { std::cout << options.help({"", "Group"}) << std::endl; exit(0); } print_compiler_and_system_info(); CloverBase::initializeLibraries(); if (result.count("a")) { test_accuracy(); } if (result.count("g")) { search(argc, argv); } if (result.count("v")) { validate(argc, argv); } if (result.count("p")) { test(argc, argv); } } catch (const cxxopts::OptionException& e) { std::cout << "error parsing options: " << e.what() << std::endl; exit(1); } return 0; }
29.491228
83
0.544914
astojanov
646901913c75ef2579be714d0486d519d3421045
4,844
hpp
C++
projects/merge_sort_multithreading/merge_sort.hpp
ItsKarlito/OperatingSystems
258e884a8484d3b5e5b7ead2507234db6de50cc1
[ "MIT" ]
4
2021-02-03T22:53:24.000Z
2021-02-10T02:01:24.000Z
projects/merge_sort_multithreading/merge_sort.hpp
ItsKarlito/OperatingSystems
258e884a8484d3b5e5b7ead2507234db6de50cc1
[ "MIT" ]
3
2021-04-03T23:08:14.000Z
2021-04-06T04:09:16.000Z
projects/merge_sort_multithreading/merge_sort.hpp
ItsKarlito/OperatingSystems
258e884a8484d3b5e5b7ead2507234db6de50cc1
[ "MIT" ]
4
2021-02-03T22:59:33.000Z
2021-04-29T21:52:11.000Z
#ifndef MERGE_SORT_H_ #define MERGE_SORT_H_ #include <iostream> #include <fstream> #include <sstream> #include <utility> #include <thread> #include <cstring> #include <functional> template <typename Type> class MergeSort { private: typedef std::function<void(const std::string)> report_callback_t; report_callback_t report_callback; //Send message to output file regarding thread status inline void report_thread_start_(std::thread &t, const std::thread::id i) { std::ostringstream ss; ss << "Thread " << i << " started\n"; this->report(ss.str()); ss.clear(); } inline void report_thread_finish_(std::thread &t, const std::thread::id i) { std::ostringstream ss; ss << "Thread " << i << " finished "; this->report(ss.str()); ss.clear(); } public: //Initialize the output text file MergeSort(report_callback_t report_callback = nullptr) : report_callback(report_callback) {} void sort_main(Type *arr, size_t size) { //Start the parent thread of merge sort if (size > 0) { std::thread parent(&MergeSort::sort, this, arr, 0, size - 1); std::thread::id parent_id = parent.get_id(); report_thread_start_(parent, parent_id); parent.join(); report_thread_finish_(parent, parent_id); print_array(arr, 0, size - 1); } else throw std::runtime_error("ERROR: Sorting size cannot be lower than 1"); } private: //Sort for specific segment of array void sort(Type *arr, int start, int end) { //Check if arr is divisible if (start >= end) return; //Divide arr into two segments, and sort each int m = start + (end - start) / 2; //Start the first thread which will deal with 1st half of given array //wait for first thread to finish before moving on std::thread first(&MergeSort::sort, this, arr, start, m); std::thread::id first_id = first.get_id(); report_thread_start_(first, first_id); first.join(); report_thread_finish_(first, first_id); print_array(arr, start, m); //Start the second thread which will deal with 2nd half of given array //wait for second thread to finish before moving on std::thread second(&MergeSort::sort, this, arr, m + 1, end); std::thread::id second_id = second.get_id(); report_thread_start_(second, second_id); second.join(); report_thread_finish_(second, second_id); print_array(arr, m + 1, end); //Merge both segments into one. The end result will //be on the same location as arr merge(arr, start, m, m + 1, end); } //Merge two segments into arr void merge( Type *arr, int start_l, int end_l, int start_r, int end_r) { //left segment right segment //[start_l ... end_l][start_r ... end_r] //Represents current index on arr int i = start_l; //Represent current index on the left //segment (i_l) and right segment (r_l) int i_l = 0; int i_r = 0; //Left and right segment sizes int size_l = end_l - start_l + 1; int size_r = end_r - start_r + 1; //Copy the contents of the left and right segments //into arr_l and arr_r respectively int arr_l[size_l] = {0}; int arr_r[size_r] = {0}; memcpy(arr_l, &arr[start_l], size_l * sizeof(Type)); memcpy(arr_r, &arr[start_r], size_r * sizeof(Type)); while (i_l < size_l && i_r < size_r) { //If current element on the left array //is bigger than the current element on //the right one, copy it on arr and increment i_l if (arr_l[i_l] <= arr_r[i_r]) arr[i] = arr_l[i_l++]; //Otherwise, do the same but with arr_r and i_r else arr[i] = arr_r[i_r++]; //Increment i i++; } //Make sure there are no data left to be added while (i_l < size_l) arr[i++] = arr_l[i_l++]; while (i_r < size_r) arr[i++] = arr_r[i_r++]; } //print contents of an array between indeces start and end void print_array(Type *arr, int start, int end) { //Iterate between indeces start and end std::ostringstream ss; for (int i = start; i <= end; i++) { ss << arr[i] << ", "; } ss << "\n"; this->report(ss.str()); } void report(const std::string msg) { if (this->report_callback == nullptr) return; this->report_callback(msg); } }; #endif
29.005988
96
0.568538
ItsKarlito
64699087791dd1465eeccdb7a35c098fab238824
9,233
cpp
C++
src/QtPhonemes/Phonemes/nVoiceFeature.cpp
Vladimir-Lin/QtPhonemes
1c1b4f4aa99bbadab5ca25dce1fc64c8ee70202d
[ "MIT" ]
null
null
null
src/QtPhonemes/Phonemes/nVoiceFeature.cpp
Vladimir-Lin/QtPhonemes
1c1b4f4aa99bbadab5ca25dce1fc64c8ee70202d
[ "MIT" ]
null
null
null
src/QtPhonemes/Phonemes/nVoiceFeature.cpp
Vladimir-Lin/QtPhonemes
1c1b4f4aa99bbadab5ca25dce1fc64c8ee70202d
[ "MIT" ]
null
null
null
#include <qtphonemes.h> enum { V_NAME = 1 , V_LANGUAGE , V_GENDER , V_TRANSLATOR , V_PHONEMES , V_DICTIONARY , V_FORMANT , V_PITCH , V_ECHO , V_FLUTTER , V_ROUGHNESS , V_CLARITY , V_TONE , V_VOICING , V_BREATH , V_BREATHW , V_WORDGAP , V_INTONATION , V_TUNES , V_STRESSLENGTH , V_STRESSAMP , V_STRESSADD , V_DICTRULES , V_STRESSRULE , V_STRESSOPT , V_CHARSET , V_NUMBERS , V_OPTION , V_MBROLA , V_KLATT , V_FAST , V_SPEED , V_DICTMIN , V_ALPHABET2 , V_REPLACE , V_CONSONANTS } ; N::VoiceFeature:: VoiceFeature (void) : Name ("" ) , Appear ("" ) , Language ("" ) , Priority (0 ) , Gender (1 ) , Age (20 ) , Variant (0 ) , XX1 (0 ) , Score (0 ) , Spare (NULL) { } N::VoiceFeature::~VoiceFeature (void) { } QString N::VoiceFeature::Strip(QString Line) { if (Line.length()<=0) return "" ; int length = Line.toUtf8().size() ; char * p = new char[length+1] ; memset(p,0,length+1) ; p <= Line ; ////////////////////////////////////////////////////// if (p[0]=='#') { delete [] p ; return "" ; } ; ////////////////////////////////////////////////////// length = strlen(p) ; while ( (--length > 0) && isspace ( p [ length ] ) ) { p[length] = 0 ; } ; ////////////////////////////////////////////////////// char * cm = NULL ; if ( ( cm = strstr(p,"//")) != NULL) *cm = 0 ; QString X(p) ; delete [] p ; return X ; } bool N::VoiceFeature::Parse(int control) { if (Data.size()<=0) return false ; QString S = QString::fromUtf8(Data) ; QStringList L = S.split('\n') ; bool T = ( ( control & 2 ) == 2 ) ; L = File::PurifyLines(L) ; foreach (S,L) { S = Strip(S) ; if (S.length()>0) Assign ( S , T ) ; } ; return true ; } bool N::VoiceFeature::Assign(QString Line,bool toneOnly) { QStringList P = Line.split(' ') ; if (P.count()<1) return false ; int key ; key = Acoustics::Lookup(Speak::KeywordTable,P[0]) ; if (key<=0) return false ; /////////////////////////////////////////////////////////////////////// switch ( key ) { case V_NAME : setName ( Line , toneOnly ) ; break ; case V_LANGUAGE : setLanguage ( Line ) ; break ; case V_GENDER : setGender ( Line ) ; break ; case V_TRANSLATOR : setTranslator ( Line ) ; break ; case V_PHONEMES : setPhoneme ( Line ) ; break ; case V_DICTIONARY : setDictionary ( Line ) ; break ; case V_FORMANT : break ; case V_PITCH : break ; case V_ECHO : break ; case V_FLUTTER : break ; case V_ROUGHNESS : break ; case V_CLARITY : break ; case V_TONE : break ; case V_VOICING : break ; case V_BREATH : break ; case V_BREATHW : break ; case V_WORDGAP : break ; case V_INTONATION : break ; case V_TUNES : break ; case V_STRESSLENGTH : break ; case V_STRESSAMP : break ; case V_STRESSADD : break ; case V_DICTRULES : break ; case V_STRESSRULE : break ; case V_STRESSOPT : break ; case V_CHARSET : break ; case V_NUMBERS : break ; case V_OPTION : break ; case V_MBROLA : break ; case V_KLATT : break ; case V_FAST : break ; case V_SPEED : break ; case V_DICTMIN : break ; case V_ALPHABET2 : break ; case V_REPLACE : break ; case V_CONSONANTS : break ; default : break ; } ; return true ; } void N::VoiceFeature::setName(QString Line,bool toneOnly) { QString N = Line.simplified() ; QStringList L = N .split(' ') ; if (toneOnly ) return ; if (L.count()<2) return ; Name = L[1] ; } void N::VoiceFeature::setLanguage(QString Line) { QString N = Line.simplified() ; QStringList L = N .split(' ') ; if (L.count()<2) return ; if (Language.length()<=0) { Language = L[1] ; Phoneme = L[1] ; Translator = L[1] ; Dictionary = L[1] ; } ; if (!Languages.contains(L[1])) { Languages << L[1] ; } ; if (L.count()<3) return ; Priority = L[2].toInt() ; } void N::VoiceFeature::setTranslator(QString Line) { QString N = Line.simplified() ; QStringList L = N .split(' ') ; if (L.count()<2) return ; Translator = L[1] ; } void N::VoiceFeature::setPhoneme(QString Line) { QString N = Line.simplified() ; QStringList L = N .split(' ') ; if (L.count()<2) return ; Phoneme = L[1] ; } void N::VoiceFeature::setDictionary(QString Line) { QString N = Line.simplified() ; QStringList L = N .split(' ') ; if (L.count()<2) return ; Dictionary = L[1] ; } void N::VoiceFeature::setGender(QString Line) { QString N = Line.simplified() ; QStringList L = N .split(' ') ; if (L.count()<3) return ; Gender = Acoustics::Lookup(Speak::MnemonicGender,L[1]) ; Age = L[2].toInt() ; } bool N::VoiceFeature::is(QString name) { return ( Name.toLower() == name.toLower() ) ; } QStringList N::VoiceFeature::PossiblePhonemes (void) { QStringList phonemes ; QString S ; if (Phoneme.length()>0) { phonemes << Phoneme ; } ; foreach (S,Languages) { if (!phonemes.contains(S)) { phonemes << S ; } ; } ; return phonemes ; } QStringList N::VoiceFeature::PossibleDictionary (void) { QStringList dictionary ; QString S ; if (Dictionary.length()>0) { dictionary << Phoneme ; } ; foreach (S,Languages) { if (!dictionary.contains(S)) { dictionary << S ; } ; } ; return dictionary ; }
38.152893
78
0.326654
Vladimir-Lin
646bfbef46c795868be2925c38363bf8a1d8eb6d
12,440
cpp
C++
Source/Components/ttn-esp32-dev/src/hal/hal_esp32.cpp
ContextQuickie/TTGO-T-Beam
0428cd2b12914f3c59da58e113c08b7a19d72f6c
[ "Apache-2.0" ]
6
2020-01-12T01:15:22.000Z
2020-09-16T11:11:49.000Z
Source/Components/ttn-esp32-dev/src/hal/hal_esp32.cpp
ContextQuickie/TTGO-T-Beam
0428cd2b12914f3c59da58e113c08b7a19d72f6c
[ "Apache-2.0" ]
null
null
null
Source/Components/ttn-esp32-dev/src/hal/hal_esp32.cpp
ContextQuickie/TTGO-T-Beam
0428cd2b12914f3c59da58e113c08b7a19d72f6c
[ "Apache-2.0" ]
2
2020-01-12T01:15:26.000Z
2020-06-04T22:26:54.000Z
/******************************************************************************* * * ttn-esp32 - The Things Network device library for ESP-IDF / SX127x * * Copyright (c) 2018-2019 Manuel Bleichenbacher * * Licensed under MIT License * https://opensource.org/licenses/MIT * * Hardware abstraction layer to run LMIC on a ESP32 using ESP-IDF. *******************************************************************************/ #include "../lmic/lmic.h" #include "../hal/hal_esp32.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "driver/gpio.h" #include "driver/spi_master.h" #include "driver/timer.h" #include "esp_log.h" #define LMIC_UNUSED_PIN 0xff #define NOTIFY_BIT_DIO 1 #define NOTIFY_BIT_TIMER 2 #define NOTIFY_BIT_WAKEUP 4 static const char* const TAG = "ttn_hal"; HAL_ESP32 ttn_hal; TaskHandle_t HAL_ESP32::lmicTask = nullptr; uint32_t HAL_ESP32::dioInterruptTime = 0; uint8_t HAL_ESP32::dioNum = 0; // ----------------------------------------------------------------------------- // Constructor HAL_ESP32::HAL_ESP32() : rssiCal(10), nextAlarm(0) { } // ----------------------------------------------------------------------------- // I/O void HAL_ESP32::configurePins(spi_host_device_t spi_host, uint8_t nss, uint8_t rxtx, uint8_t rst, uint8_t dio0, uint8_t dio1) { spiHost = spi_host; pinNSS = (gpio_num_t)nss; pinRxTx = (gpio_num_t)rxtx; pinRst = (gpio_num_t)rst; pinDIO0 = (gpio_num_t)dio0; pinDIO1 = (gpio_num_t)dio1; // Until the background process has been started, use the current task // for supporting calls like `hal_waitUntil()`. lmicTask = xTaskGetCurrentTaskHandle(); } void IRAM_ATTR HAL_ESP32::dioIrqHandler(void *arg) { dioInterruptTime = hal_ticks(); dioNum = (u1_t)(long)arg; BaseType_t higherPrioTaskWoken = pdFALSE; xTaskNotifyFromISR(lmicTask, NOTIFY_BIT_DIO, eSetBits, &higherPrioTaskWoken); if (higherPrioTaskWoken) portYIELD_FROM_ISR(); } void HAL_ESP32::ioInit() { // pinNSS and pinDIO0 and pinDIO1 are required ASSERT(pinNSS != LMIC_UNUSED_PIN); ASSERT(pinDIO0 != LMIC_UNUSED_PIN); ASSERT(pinDIO1 != LMIC_UNUSED_PIN); gpio_pad_select_gpio(pinNSS); gpio_set_level(pinNSS, 0); gpio_set_direction(pinNSS, GPIO_MODE_OUTPUT); if (pinRxTx != LMIC_UNUSED_PIN) { gpio_pad_select_gpio(pinRxTx); gpio_set_level(pinRxTx, 0); gpio_set_direction(pinRxTx, GPIO_MODE_OUTPUT); } if (pinRst != LMIC_UNUSED_PIN) { gpio_pad_select_gpio(pinRst); gpio_set_level(pinRst, 0); gpio_set_direction(pinRst, GPIO_MODE_OUTPUT); } // DIO pins with interrupt handlers gpio_pad_select_gpio(pinDIO0); gpio_set_direction(pinDIO0, GPIO_MODE_INPUT); gpio_set_intr_type(pinDIO0, GPIO_INTR_POSEDGE); gpio_pad_select_gpio(pinDIO1); gpio_set_direction(pinDIO1, GPIO_MODE_INPUT); gpio_set_intr_type(pinDIO1, GPIO_INTR_POSEDGE); ESP_LOGI(TAG, "IO initialized"); } void hal_pin_rxtx(u1_t val) { if (ttn_hal.pinRxTx == LMIC_UNUSED_PIN) return; gpio_set_level(ttn_hal.pinRxTx, val); } void hal_pin_rst(u1_t val) { if (ttn_hal.pinRst == LMIC_UNUSED_PIN) return; if (val == 0 || val == 1) { // drive pin gpio_set_level(ttn_hal.pinRst, val); gpio_set_direction(ttn_hal.pinRst, GPIO_MODE_OUTPUT); } else { // keep pin floating gpio_set_level(ttn_hal.pinRst, val); gpio_set_direction(ttn_hal.pinRst, GPIO_MODE_INPUT); } } s1_t hal_getRssiCal (void) { return ttn_hal.rssiCal; } ostime_t hal_setModuleActive (bit_t val) { return 0; } bit_t hal_queryUsingTcxo(void) { return false; } uint8_t hal_getTxPowerPolicy(u1_t inputPolicy, s1_t requestedPower, u4_t frequency) { return LMICHAL_radio_tx_power_policy_paboost; } // ----------------------------------------------------------------------------- // SPI void HAL_ESP32::spiInit() { // init device spi_device_interface_config_t spiConfig; memset(&spiConfig, 0, sizeof(spiConfig)); spiConfig.mode = 1; spiConfig.clock_speed_hz = CONFIG_TTN_SPI_FREQ; spiConfig.command_bits = 0; spiConfig.address_bits = 8; spiConfig.spics_io_num = pinNSS; spiConfig.queue_size = 1; spiConfig.cs_ena_posttrans = 2; esp_err_t ret = spi_bus_add_device(spiHost, &spiConfig, &spiHandle); ESP_ERROR_CHECK(ret); ESP_LOGI(TAG, "SPI initialized"); } void hal_spi_write(u1_t cmd, const u1_t *buf, size_t len) { ttn_hal.spiWrite(cmd, buf, len); } void HAL_ESP32::spiWrite(uint8_t cmd, const uint8_t *buf, size_t len) { memset(&spiTransaction, 0, sizeof(spiTransaction)); spiTransaction.addr = cmd; spiTransaction.length = 8 * len; spiTransaction.tx_buffer = buf; esp_err_t err = spi_device_transmit(spiHandle, &spiTransaction); ESP_ERROR_CHECK(err); } void hal_spi_read(u1_t cmd, u1_t *buf, size_t len) { ttn_hal.spiRead(cmd, buf, len); } void HAL_ESP32::spiRead(uint8_t cmd, uint8_t *buf, size_t len) { memset(buf, 0, len); memset(&spiTransaction, 0, sizeof(spiTransaction)); spiTransaction.addr = cmd; spiTransaction.length = 8 * len; spiTransaction.rxlength = 8 * len; spiTransaction.tx_buffer = buf; spiTransaction.rx_buffer = buf; esp_err_t err = spi_device_transmit(spiHandle, &spiTransaction); ESP_ERROR_CHECK(err); } // ----------------------------------------------------------------------------- // TIME /* * LIMIC uses a 32 bit time system (ostime_t) counting ticks. In this * implementation each tick is 16µs. It will wrap arounnd every 19 hours. * * The ESP32 has a 64 bit timer counting microseconds. It will wrap around * every 584,000 years. So we don't need to bother. * * Based on this timer, future callbacks can be scheduled. This is used to * schedule the next LMIC job. */ // Convert LMIC tick time (ostime_t) to ESP absolute time. // `osTime` is assumed to be somewhere between one hour in the past and // 18 hours into the future. int64_t HAL_ESP32::osTimeToEspTime(int64_t espNow, uint32_t osTime) { int64_t espTime; uint32_t osNow = (uint32_t)(espNow >> 4); // unsigned difference: // 0x00000000 - 0xefffffff: future (0 to about 18 hours) // 0xf0000000 - 0xffffffff: past (about 1 to 0 hours) uint32_t osDiff = osTime - osNow; if (osDiff < 0xf0000000) { espTime = espNow + (((int64_t)osDiff) << 4); } else { // one's complement instead of two's complement: // off by 1 µs and ignored osDiff = ~osDiff; espTime = espNow - (((int64_t)osDiff) << 4); } return espTime; } void HAL_ESP32::timerInit() { esp_timer_create_args_t timerConfig = { .callback = &timerCallback, .arg = nullptr, .dispatch_method = ESP_TIMER_TASK, .name = "lmic_job" }; esp_err_t err = esp_timer_create(&timerConfig, &timer); ESP_ERROR_CHECK(err); ESP_LOGI(TAG, "Timer initialized"); } void HAL_ESP32::setNextAlarm(int64_t time) { nextAlarm = time; } void HAL_ESP32::armTimer(int64_t espNow) { if (nextAlarm == 0) return; int64_t timeout = nextAlarm - esp_timer_get_time(); if (timeout < 0) timeout = 10; esp_timer_start_once(timer, timeout); } void HAL_ESP32::disarmTimer() { esp_timer_stop(timer); } void HAL_ESP32::timerCallback(void *arg) { xTaskNotify(lmicTask, NOTIFY_BIT_TIMER, eSetBits); } // Wait for the next external event. Either: // - scheduled timer due to scheduled job or waiting for a given time // - wake up event from the client code // - I/O interrupt (DIO0 or DIO1 pin) bool HAL_ESP32::wait(WaitKind waitKind) { TickType_t ticksToWait = waitKind == CHECK_IO ? 0 : portMAX_DELAY; while (true) { uint32_t bits = ulTaskNotifyTake(pdTRUE, ticksToWait); if (bits == 0) return false; if ((bits & NOTIFY_BIT_WAKEUP) != 0) { if (waitKind != WAIT_FOR_TIMER) { disarmTimer(); return true; } } else if ((bits & NOTIFY_BIT_TIMER) != 0) { disarmTimer(); setNextAlarm(0); if (waitKind != CHECK_IO) return true; } else // IO interrupt { if (waitKind != WAIT_FOR_TIMER) disarmTimer(); enterCriticalSection(); radio_irq_handler_v2(dioNum, dioInterruptTime); leaveCriticalSection(); if (waitKind != WAIT_FOR_TIMER) return true; } } } // Gets current time in LMIC ticks u4_t hal_ticks() { // LMIC tick unit: 16µs // esp_timer unit: 1µs return (u4_t)(esp_timer_get_time() >> 4); } // Wait until the specified time. // Called if the LMIC code needs to wait for a precise time. // All other events are ignored and will be served later. void hal_waitUntil(u4_t time) { ttn_hal.waitUntil(time); } void HAL_ESP32::waitUntil(uint32_t osTime) { int64_t espNow = esp_timer_get_time(); int64_t espTime = osTimeToEspTime(espNow, osTime); setNextAlarm(espTime); armTimer(espNow); wait(WAIT_FOR_TIMER); } // Called by client code to wake up LMIC to do something, // e.g. send a submitted messages. void HAL_ESP32::wakeUp() { xTaskNotify(lmicTask, NOTIFY_BIT_WAKEUP, eSetBits); } // Check if the specified time has been reached or almost reached. // Otherwise, save it as alarm time. // LMIC calls this function with the scheduled time of the next job // in the queue. If the job is not due yet, LMIC will go to sleep. u1_t hal_checkTimer(uint32_t time) { return ttn_hal.checkTimer(time); } uint8_t HAL_ESP32::checkTimer(u4_t osTime) { int64_t espNow = esp_timer_get_time(); int64_t espTime = osTimeToEspTime(espNow, osTime); int64_t diff = espTime - espNow; if (diff < 100) return 1; // timer has expired or will expire very soon setNextAlarm(espTime); return 0; } // Go to sleep until next event. // Called when LMIC is not busy and not job is due to be executed. void hal_sleep() { ttn_hal.sleep(); } void HAL_ESP32::sleep() { if (wait(CHECK_IO)) return; armTimer(esp_timer_get_time()); wait(WAIT_FOR_ANY_EVENT); } // ----------------------------------------------------------------------------- // IRQ void hal_disableIRQs() { // nothing to do as interrupt handlers post message to queue // and don't access any shared data structures } void hal_enableIRQs() { // nothing to do as interrupt handlers post message to queue // and don't access any shared data structures } // ----------------------------------------------------------------------------- // Synchronization between application code and background task void HAL_ESP32::initCriticalSection() { mutex = xSemaphoreCreateRecursiveMutex(); } void HAL_ESP32::enterCriticalSection() { xSemaphoreTakeRecursive(mutex, portMAX_DELAY); } void HAL_ESP32::leaveCriticalSection() { xSemaphoreGiveRecursive(mutex); } // ----------------------------------------------------------------------------- void HAL_ESP32::lmicBackgroundTask(void* pvParameter) { os_runloop(); } void hal_init_ex(const void *pContext) { ttn_hal.init(); } void HAL_ESP32::init() { // configure radio I/O and interrupt handler ioInit(); // configure radio SPI spiInit(); // configure timer and alarm callback timerInit(); } void HAL_ESP32::startLMICTask() { xTaskCreate(lmicBackgroundTask, "ttn_lmic", 1024 * 4, nullptr, CONFIG_TTN_BG_TASK_PRIO, &lmicTask); // enable interrupts gpio_isr_handler_add(pinDIO0, dioIrqHandler, (void *)0); gpio_isr_handler_add(pinDIO1, dioIrqHandler, (void *)1); } // ----------------------------------------------------------------------------- // Fatal failure static hal_failure_handler_t* custom_hal_failure_handler = nullptr; void hal_set_failure_handler(const hal_failure_handler_t* const handler) { custom_hal_failure_handler = handler; } void hal_failed(const char *file, u2_t line) { if (custom_hal_failure_handler != nullptr) (*custom_hal_failure_handler)(file, line); ESP_LOGE(TAG, "LMIC failed and stopped: %s:%d", file, line); // go to sleep forever while (true) { vTaskDelay(portMAX_DELAY); } }
25.336049
125
0.634405
ContextQuickie
646d04406fc159189be354eb08f5239cef0d8e9a
919
cpp
C++
CodeForces/747/Servers.cpp
seeva92/Competitive-Programming
69061c5409bb806148616fe7d86543e94bf76edd
[ "Apache-2.0" ]
null
null
null
CodeForces/747/Servers.cpp
seeva92/Competitive-Programming
69061c5409bb806148616fe7d86543e94bf76edd
[ "Apache-2.0" ]
null
null
null
CodeForces/747/Servers.cpp
seeva92/Competitive-Programming
69061c5409bb806148616fe7d86543e94bf76edd
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> typedef long long ll; const int mod = 1e9 + 7; const int MAX = 1e5 + 7; using namespace std; typedef vector<int> vi; int server[107]; class Servers { int n, q, t, k, d; public: void solve() { memset(server, 0, sizeof server); cin >> n >> q; for (int i = 0; i < q; i++) { cin >> t >> k >> d; int cnt = 0; for (int j = 1; j <= n && cnt < k; j++) { if (server[j] < t) cnt++; } if (cnt == k) { int sum = 0; for (int j = 1; j <= n && cnt > 0; j++) { if (server[j] < t) { server[j] = t + d - 1; cnt--; sum += j; } } cout << sum << '\n'; } else { cout << -1 << '\n'; } } } }; int main() { #ifndef ONLINE_JUDGE freopen("/Users/seeva92/Workspace/Contests/1.txt", "r", stdin); freopen("/Users/seeva92/Workspace/Contests/2.txt", "w", stdout); #endif ios::sync_with_stdio(false); cin.tie(0); Servers s; s.solve(); }
19.553191
65
0.508161
seeva92
646d2e1498ddee8460f419b5cd6cd15be5a62592
2,461
cpp
C++
Problem Solving Paradigm/Greedy/Classical, Usually Easier/10037.cpp
joe-stifler/uHunt
02465ea9868403691e4f0aaa6ddde730afa11f47
[ "MIT" ]
3
2019-05-22T00:36:23.000Z
2021-03-22T12:23:18.000Z
Problem Solving Paradigm/Greedy/Classical, Usually Easier/10037.cpp
joe-stifler/uHunt
02465ea9868403691e4f0aaa6ddde730afa11f47
[ "MIT" ]
null
null
null
Problem Solving Paradigm/Greedy/Classical, Usually Easier/10037.cpp
joe-stifler/uHunt
02465ea9868403691e4f0aaa6ddde730afa11f47
[ "MIT" ]
null
null
null
/*------------------------------------------------*/ // Uva Problem No: 10037 // Problem Name: Bridge // Type: Classical, Usually Easier (Greedy) // Autor: Joe Stifler // Data: 2018-06-10 02:10:56 // Runtime: 0.000s // Universidade: Unicamp /*------------------------------------------------*/ #include <bits/stdc++.h> using namespace std; int main() { int t; scanf("%d", &t); int caso = 0; while(t--) { int n; scanf("%d", &n); vector<int> vals; while(n--) { int v; scanf("%d", &v); vals.push_back(v); } sort(vals.begin(), vals.end()); int i; int cont = 0; int total = 0; int count = 0; vector<int> res; int a, b; int A = vals[0], B = vals[1]; for (i = vals.size() - 1; i > 2; i -= 2) { a = vals[i]; b = vals[i-1]; int t1 = a + b + 2 * A; int t2 = a + A + 2 * B; if (t1 < t2) { total += t1; res.push_back(A); res.push_back(b); res.push_back(A); res.push_back(A); res.push_back(a); res.push_back(A); } else { total += t2; res.push_back(A); res.push_back(B); res.push_back(A); res.push_back(b); res.push_back(a); res.push_back(B); } } if (caso != 0) printf("\n"); if (vals.size() == 1) printf("%d\n%d\n", vals[0], vals[0]); else { if (vals.size() % 2 == 0) { total += vals[1]; res.push_back(vals[0]); res.push_back(vals[1]); } else { total += vals[2] + vals[0] + vals[1]; res.push_back(vals[0]); res.push_back(vals[1]); res.push_back(vals[0]); res.push_back(vals[0]); res.push_back(vals[2]); } printf("%d\n", total); for (int i = 0; i < res.size(); i++) { if (i % 3 == 2) printf("\n"); else if (i % 3 == 1) printf(" "); printf("%d", res[i]); if (i % 3 == 2) printf("\n"); } printf("\n"); } caso++; } return 0; }
23.663462
53
0.354328
joe-stifler
646d6ac6da554b57f9fbf52f495fd49a166fc805
2,053
cpp
C++
user/tests/unit/tools/string.cpp
zsoltmazlo/indoor-controller2
5fde9f40b30d087af03f6cccdb97821719941955
[ "MIT" ]
1
2019-02-24T07:13:51.000Z
2019-02-24T07:13:51.000Z
user/tests/unit/tools/string.cpp
zsoltmazlo/indoor-controller2
5fde9f40b30d087af03f6cccdb97821719941955
[ "MIT" ]
1
2018-05-29T19:27:53.000Z
2018-05-29T19:27:53.000Z
user/tests/unit/tools/string.cpp
zsoltmazlo/indoor-controller2
5fde9f40b30d087af03f6cccdb97821719941955
[ "MIT" ]
null
null
null
#include "string.h" #include "catch.h" #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/trim_all.hpp> #include <boost/algorithm/hex.hpp> // test::RegExpMatcher test::RegExpMatcher::RegExpMatcher(const std::string &expr) { try { r_.assign(expr); } catch (const boost::regex_error&) { CATCH_WARN("test::RegExpMatcher: Invalid expression: " << expr); } } test::RegExpMatcher::RegExpMatcher(const std::string &str, const std::string &expr) : RegExpMatcher(expr) { if (!match(str)) { r_ = boost::regex(); // Invalidate matcher } } bool test::RegExpMatcher::match(const std::string &str) { try { if (r_.empty()) { return false; } boost::smatch m; if (!boost::regex_match(str, m, r_)) { return false; } s_ = str; m_ = m; return true; } catch (boost::regex_error&) { return false; } } std::string test::RegExpMatcher::at(size_t i) const { i += 1; // Skip string matching whole expression if (i >= m_.size()) { return std::string(); } return m_.str(i); } size_t test::RegExpMatcher::size() const { if (m_.empty()) { return 0; } return m_.size() - 1; } // test:: std::string test::trim(const std::string &str) { return boost::algorithm::trim_all_copy(str, std::locale::classic()); } std::string test::toLowerCase(const std::string &str) { return boost::algorithm::to_lower_copy(str, std::locale::classic()); } std::string test::toUpperCase(const std::string &str) { return boost::algorithm::to_upper_copy(str, std::locale::classic()); } std::string test::toHex(const std::string &str) { std::string s = boost::algorithm::hex(str); boost::algorithm::to_lower(s, std::locale::classic()); return s; } std::string test::fromHex(const std::string &str) { try { return boost::algorithm::unhex(str); } catch (const boost::algorithm::hex_decode_error&) { return std::string(); } }
24.73494
85
0.604968
zsoltmazlo
6472fd2a607b3c66c457bb2292a0d8923da40d8e
1,313
hpp
C++
spec/dummy/vendor/bundle/ruby/2.7.0/gems/sassc-2.4.0/ext/libsass/src/source_map.hpp
puzzle/nochmal
3299efb56b77f9b0293b6ffec39b7507621888f8
[ "MIT" ]
2,975
2015-01-01T01:34:50.000Z
2022-03-29T06:58:51.000Z
spec/dummy/vendor/bundle/ruby/2.7.0/gems/sassc-2.4.0/ext/libsass/src/source_map.hpp
puzzle/nochmal
3299efb56b77f9b0293b6ffec39b7507621888f8
[ "MIT" ]
2,096
2015-01-01T01:48:47.000Z
2022-02-25T08:20:47.000Z
spec/dummy/vendor/bundle/ruby/2.7.0/gems/sassc-2.4.0/ext/libsass/src/source_map.hpp
puzzle/nochmal
3299efb56b77f9b0293b6ffec39b7507621888f8
[ "MIT" ]
458
2015-01-09T22:02:21.000Z
2022-02-25T06:40:53.000Z
#ifndef SASS_SOURCE_MAP_H #define SASS_SOURCE_MAP_H #include <string> #include <vector> #include "ast_fwd_decl.hpp" #include "base64vlq.hpp" #include "position.hpp" #include "mapping.hpp" #include "backtrace.hpp" #include "memory.hpp" #define VECTOR_PUSH(vec, ins) vec.insert(vec.end(), ins.begin(), ins.end()) #define VECTOR_UNSHIFT(vec, ins) vec.insert(vec.begin(), ins.begin(), ins.end()) namespace Sass { class Context; class OutputBuffer; class SourceMap { public: sass::vector<size_t> source_index; SourceMap(); SourceMap(const sass::string& file); void append(const Offset& offset); void prepend(const Offset& offset); void append(const OutputBuffer& out); void prepend(const OutputBuffer& out); void add_open_mapping(const AST_Node* node); void add_close_mapping(const AST_Node* node); sass::string render_srcmap(Context &ctx); SourceSpan remap(const SourceSpan& pstate); private: sass::string serialize_mappings(); sass::vector<Mapping> mappings; Position current_position; public: sass::string file; private: Base64VLQ base64vlq; }; class OutputBuffer { public: OutputBuffer(void) : buffer(), smap() { } public: sass::string buffer; SourceMap smap; }; } #endif
19.893939
80
0.683168
puzzle
64742ec8c450462c42a94dfbadbfb9c7325aebc5
785
cpp
C++
minStack.cpp
anishmo99/DailyInterviewPro
d8724e8feec558ab1882d22c9ca63b850b767753
[ "MIT" ]
2
2020-08-09T02:09:50.000Z
2020-08-09T07:07:47.000Z
minStack.cpp
anishmo99/DailyInterviewPro
d8724e8feec558ab1882d22c9ca63b850b767753
[ "MIT" ]
null
null
null
minStack.cpp
anishmo99/DailyInterviewPro
d8724e8feec558ab1882d22c9ca63b850b767753
[ "MIT" ]
5
2020-09-21T12:49:07.000Z
2020-09-29T16:13:09.000Z
class MinStack { public: /** initialize your data structure here. */ stack<pair<int, int>> stack; int min = INT_MAX; MinStack() { } void push(int x) { if (stack.empty()) { stack.push(make_pair(x, x)); return; } int min = stack.top().second < x ? stack.top().second : x; stack.push(make_pair(x, min)); } void pop() { stack.pop(); } int top() { return stack.top().first; } int getMin() { return stack.top().second; } }; /** * Your MinStack object will be instantiated and called as such: * MinStack* obj = new MinStack(); * obj->push(x); * obj->pop(); * int param_3 = obj->top(); * int param_4 = obj->getMin(); */
16.702128
66
0.496815
anishmo99
647a663db5311d4c52dc6ef7d7ebe192729c73b7
1,707
cpp
C++
Codeforces/Gym/Helvetic_Coding_Contest_2017/pA.cpp
calee0219/CP
911ac3671881f6b80ca5a06b7d4f97a3ccc96e50
[ "MIT" ]
null
null
null
Codeforces/Gym/Helvetic_Coding_Contest_2017/pA.cpp
calee0219/CP
911ac3671881f6b80ca5a06b7d4f97a3ccc96e50
[ "MIT" ]
null
null
null
Codeforces/Gym/Helvetic_Coding_Contest_2017/pA.cpp
calee0219/CP
911ac3671881f6b80ca5a06b7d4f97a3ccc96e50
[ "MIT" ]
null
null
null
#include <iostream> #include <map> #include <vector> using namespace std; int main() { int n, K; cin >> n >> K; int a[88]; map<int,int> m; set<int> v; // index set<pair<int,int> > last; // index, end pointer map<int,int> before; // index -> before index map<int,int> index; for(int i = 0; i < n; ++i) { cin >> a[i]; m[a[i]]++; before[i] = index[a[i]]; last.insert(make_pair(i,a[i])); index[a[i]] = i; } int cost = 0; for(int i = 0; i < n; ++i) { m[a[i]]--; bool chk = 1; //for(int j = 0; j < v.size(); ++j) { //if(v[j] == a[i]) { //chk = 0; //break; //} //} if(v.find(make_pair(i,a[i])) == v.end()) { if(v.size() == K) { //bool chk2 = 1; //for(int j = 0; j < v.size(); ++j) { //if(m[v[j]] == 0) { //v.erase(v.begin() + j); //chk2 = 0; //break; //} //} //if(chk2) { //int far_d = 0; //int far_i = 0; //for(int j = 0; j < v.size(); ++j) { //for(int k = i+1; k < n; ++k) { //if(a[k] == v[j]) { //if(far_d < k-i) { //far_d = k-i; //far_i = j; //} //break; //} //} //} //v.erase(v.begin() + far_i); //} v.erase(last.end()) } v.insert(a[i]); cost++; } } cout << cost << endl; return 0; }
25.477612
53
0.310486
calee0219
647a97d00c436bf7284b0feb179637e7a10c7714
8,111
cpp
C++
src/physics/bumper.cpp
ArneDJ/terranova
533e9e5687d464153418f73a1d811f57e7c572b9
[ "CC0-1.0" ]
null
null
null
src/physics/bumper.cpp
ArneDJ/terranova
533e9e5687d464153418f73a1d811f57e7c572b9
[ "CC0-1.0" ]
null
null
null
src/physics/bumper.cpp
ArneDJ/terranova
533e9e5687d464153418f73a1d811f57e7c572b9
[ "CC0-1.0" ]
null
null
null
#include <iostream> #include <memory> #include <vector> #include <glm/glm.hpp> #include <glm/vec3.hpp> #include <glm/vec4.hpp> #include <glm/mat4x4.hpp> #include <glm/gtc/type_ptr.hpp> #include "../geometry/transform.h" #include "../geometry/geometry.h" #include "physical.h" #include "bumper.h" namespace fysx { class ClosestNotMe : public btCollisionWorld::ClosestRayResultCallback { public: ClosestNotMe(btCollisionObject *body) : btCollisionWorld::ClosestRayResultCallback(btVector3(0.0, 0.0, 0.0), btVector3(0.0, 0.0, 0.0)) { me = body; } virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult &rayResult, bool normalInWorldSpace) { if (rayResult.m_collisionObject == me) { return 1.0; } return ClosestRayResultCallback::addSingleResult(rayResult, normalInWorldSpace); } protected: btCollisionObject *me; }; class BumperConvexCallback : public btCollisionWorld::ClosestConvexResultCallback { public: BumperConvexCallback(btCollisionObject* me, const btVector3& up, btScalar minSlopeDot) : btCollisionWorld::ClosestConvexResultCallback(btVector3(0.0, 0.0, 0.0), btVector3(0.0, 0.0, 0.0)), m_me(me), m_up(up), m_minSlopeDot(minSlopeDot) { } virtual btScalar addSingleResult(btCollisionWorld::LocalConvexResult& convexResult, bool normalInWorldSpace) { if (convexResult.m_hitCollisionObject == m_me) return btScalar(1.0); if (!convexResult.m_hitCollisionObject->hasContactResponse()) return btScalar(1.0); btVector3 hitNormalWorld; if (normalInWorldSpace) { hitNormalWorld = convexResult.m_hitNormalLocal; } else { ///need to transform normal into worldspace hitNormalWorld = convexResult.m_hitCollisionObject->getWorldTransform().getBasis() * convexResult.m_hitNormalLocal; } /* btScalar dotUp = m_up.dot(hitNormalWorld); if (dotUp < m_minSlopeDot) { return btScalar(1.0); } */ return ClosestConvexResultCallback::addSingleResult(convexResult, normalInWorldSpace); } protected: btCollisionObject *m_me; const btVector3 m_up = btVector3(0, 1, 0); btScalar m_minSlopeDot; }; struct Trace { float fraction = 1.f; // time completed, 1.0 = didn't hit anything glm::vec3 endpos; // final position glm::vec3 normal; // surface normal at impact }; static const float V_GRAVITY = 9.81F; static const float TERMINAL_VELOCITY = 55.F; Trace trace_movement(btPairCachingGhostObject *object, const btConvexShape *shape, const btDynamicsWorld *world, const glm::vec3 &origin, const glm::vec3 &destination) { Trace trace = {}; trace.fraction = 1.f; trace.endpos = origin; glm::vec3 sweep_direction = origin - destination; btTransform start = object->getWorldTransform(); btTransform end = start; end.setOrigin(vec3_to_bt(destination)); BumperConvexCallback callback(object, vec3_to_bt(sweep_direction), 0.45); callback.m_collisionFilterGroup = object->getBroadphaseHandle()->m_collisionFilterGroup; callback.m_collisionFilterMask = object->getBroadphaseHandle()->m_collisionFilterMask; object->convexSweepTest(shape, start, end, callback, world->getDispatchInfo().m_allowedCcdPenetration); glm::vec3 direction = destination - origin; if (callback.hasHit() && object->hasContactResponse()) { glm::vec3 hitpoint = bt_to_vec3(callback.m_hitPointWorld); trace.fraction = callback.m_closestHitFraction; trace.normal = bt_to_vec3(callback.m_hitNormalWorld); trace.endpos = origin + (trace.fraction * direction); } return trace; } glm::vec3 hit_to_velocity(const glm::vec3 &velocity, const glm::vec3 &normal) { glm::vec3 velocity_normalized = glm::normalize(velocity); glm::vec3 undesired_motion = normal * glm::dot(velocity_normalized, normal); glm::vec3 desired_motion = velocity_normalized - undesired_motion; return desired_motion * glm::length(velocity); } Bumper::Bumper(const glm::vec3 &origin, float radius, float length) { float height = length - (2.f * radius); if (height < 0.f) { height = 0.f; } shape = std::make_unique<btCapsuleShape>(radius, height); btTransform t; t.setIdentity(); t.setOrigin(vec3_to_bt(origin)); ghost_object = std::make_unique<btPairCachingGhostObject>(); ghost_object->setWorldTransform(t); ghost_object->setCollisionShape(shape.get()); ghost_object->setCollisionFlags(btCollisionObject::CF_CHARACTER_OBJECT); transform = std::make_unique<geom::Transform>(); transform->position = origin; } void Bumper::update(const btDynamicsWorld *world, float delta) { const glm::vec3 start_position = bt_to_vec3(ghost_object->getWorldTransform().getOrigin()); glm::vec3 displacement = speed * delta * walk_direction; collide_and_slide(world, displacement); apply_gravity(world, delta); const glm::vec3 end_position = bt_to_vec3(ghost_object->getWorldTransform().getOrigin()); update_fallen_distance(start_position, end_position); } void Bumper::sync_transform() { btTransform t = ghost_object->getWorldTransform(); transform->position = fysx::bt_to_vec3(t.getOrigin()); } void Bumper::teleport(const glm::vec3 &position) { btTransform t; t.setIdentity (); t.setOrigin(fysx::vec3_to_bt(position)); ghost_object->setWorldTransform(t); } void Bumper::apply_gravity(const btDynamicsWorld *world, float delta) { glm::vec3 gravity = { 0.f, -V_GRAVITY, 0.f }; if (!on_ground) { gravity.y = -sqrtf(6.f * V_GRAVITY * fallen_distance); if (fabs(gravity.y) > TERMINAL_VELOCITY) { gravity.y = -TERMINAL_VELOCITY; } // in case fallen distance was 0 (start of fall) if (!gravity.y) { gravity.y = -V_GRAVITY; } } gravity.y *= delta; // find closest ground collision const glm::vec3 origin = bt_to_vec3(ghost_object->getWorldTransform().getOrigin()); glm::vec3 destination = origin + gravity; Trace trace = trace_movement(ghost_object.get(), shape.get(), world, origin, destination); on_ground = (trace.fraction < 1.f); if (on_ground) { // stick on ground if not in air glm::vec3 moved = glm::normalize(gravity) * (trace.fraction * glm::length(gravity - 0.1f)); destination = origin + moved; on_ground = true; } teleport(destination); } void Bumper::apply_velocity(const glm::vec3 &velocity) { glm::vec3 current_position = bt_to_vec3(ghost_object->getWorldTransform().getOrigin()); teleport(current_position + velocity); } void Bumper::collide_and_slide(const btDynamicsWorld *world, const glm::vec3 &displacement) { // no motion early exit if (glm::length(displacement) < 1e-6f) { return; } static const float CLIP_OFFSET = 0.01F; const glm::vec3 origin = bt_to_vec3(ghost_object->getWorldTransform().getOrigin()); glm::vec3 position = origin; glm::vec3 start = origin; glm::vec3 end = origin + displacement; glm::vec3 motion = displacement; for (int i = 0; i < 4; i++) { if (glm::length(motion) < 1e-6f) { return; } // find collision with convex sweep Trace trace = trace_movement(ghost_object.get(), shape.get(), world, start, end); // hit nothing early exit if (trace.fraction >= 1.f) { position = end; break; } // we must have hit something // find the position right before the collision occurs glm::vec3 moved = glm::normalize(motion) * (trace.fraction * glm::length(motion) - CLIP_OFFSET); start += moved; // update last visited position position = start; // remaining motion glm::vec3 remainder = end - start; // slide remaining motion along hit normal glm::vec3 direction = glm::normalize(remainder); float d = glm::dot(direction, trace.normal); glm::vec3 slide = direction - (d * trace.normal); motion = glm::length(remainder) * slide; end = start + motion; } motion = position - origin; // to avoid occilations somewhat lerp with original position if (glm::dot(glm::normalize(motion), glm::normalize(displacement)) <= 0.f) { position = glm::mix(origin, position, 0.25f); } teleport(position); } void Bumper::update_fallen_distance(const glm::vec3 &start, const glm::vec3 &end) { if (on_ground) { fallen_distance = 0.f; } else { fallen_distance += glm::distance(start.y, end.y); } } void Bumper::set_scale(float scale) { shape->setLocalScaling(btVector3(scale, scale, scale)); } };
28.36014
167
0.730983
ArneDJ
647d7f80f6dc2b07d4806f34a1e1eb3b1bd9375c
10,374
cpp
C++
modules/attention_segmentation/src/SVMTrainModel.cpp
v4r-tuwien/v4r
ff3fbd6d2b298b83268ba4737868bab258262a40
[ "BSD-1-Clause", "BSD-2-Clause" ]
2
2021-02-22T11:36:33.000Z
2021-07-20T11:31:08.000Z
modules/attention_segmentation/src/SVMTrainModel.cpp
v4r-tuwien/v4r
ff3fbd6d2b298b83268ba4737868bab258262a40
[ "BSD-1-Clause", "BSD-2-Clause" ]
null
null
null
modules/attention_segmentation/src/SVMTrainModel.cpp
v4r-tuwien/v4r
ff3fbd6d2b298b83268ba4737868bab258262a40
[ "BSD-1-Clause", "BSD-2-Clause" ]
3
2018-10-19T10:39:23.000Z
2021-04-07T13:39:03.000Z
/**************************************************************************** ** ** Copyright (C) 2017 TU Wien, ACIN, Vision 4 Robotics (V4R) group ** Contact: v4r.acin.tuwien.ac.at ** ** This file is part of V4R ** ** V4R is distributed under dual licenses - GPLv3 or closed source. ** ** GNU General Public License Usage ** V4R 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. ** ** V4R 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. ** ** Please review the following information to ensure the GNU General Public ** License requirements will be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ** ** Commercial License Usage ** If GPL is not suitable for your project, you must purchase a commercial ** license to use V4R. Licensees holding valid commercial V4R licenses may ** use this file in accordance with the commercial license agreement ** provided with the Software or, alternatively, in accordance with the ** terms contained in a written agreement between you and TU Wien, ACIN, V4R. ** For licensing terms and conditions please contact office<at>acin.tuwien.ac.at. ** ** ** The copyright holder additionally grants the author(s) of the file the right ** to use, copy, modify, merge, publish, distribute, sublicense, and/or ** sell copies of their contributions without any restrictions. ** ****************************************************************************/ /** * @file SVMTrainModel.cpp * @author Andreas Richtsfeld * @date August 2011 * @version 0.1 * @brief Trains svm. */ #include "v4r/attention_segmentation/SVMTrainModel.h" #define Malloc(type, n) (type *)malloc((n) * sizeof(type)) namespace svm { void SVMTrainModel::print_null(const char *s) { (void)s; } void SVMTrainModel::exit_input_error(int line_num) { fprintf(stderr, "Wrong input format at line %d\n", line_num); exit(1); } char *SVMTrainModel::readline(FILE *input) { int len; if (fgets(line, max_line_len, input) == NULL) return nullptr; while (strrchr(line, '\n') == NULL) { max_line_len *= 2; line = (char *)realloc(line, max_line_len); len = (int)strlen(line); if (fgets(line + len, max_line_len - len, input) == NULL) break; } return line; } SVMTrainModel::SVMTrainModel() { // default values param.svm_type = C_SVC; param.kernel_type = RBF; param.degree = 3; param.gamma = 0; // 1/num_features param.coef0 = 0; param.nu = 0.5; param.cache_size = 100; param.C = 1; param.eps = 1e-3; param.p = 0.1; param.shrinking = 1; param.probability = 0; param.nr_weight = 0; param.weight_label = nullptr; param.weight = nullptr; cross_validation = 0; line = nullptr; void (*print_func)(const char *) = nullptr; // default printing to stdout svm_set_print_string_function(print_func); have_input_file_name = false; have_model_file_name = false; } void SVMTrainModel::setSVMType(int _svm_type) { param.svm_type = _svm_type; } void SVMTrainModel::setKernelType(int _kernel_type) { param.kernel_type = _kernel_type; } void SVMTrainModel::setDegree(int _degree) { param.degree = _degree; } void SVMTrainModel::setGamma(double _gamma) { param.gamma = _gamma; } void SVMTrainModel::setCoef0(double _coef0) { param.coef0 = _coef0; } void SVMTrainModel::setNu(double _nu) { param.nu = _nu; } void SVMTrainModel::setCacheSize(double _cache_size) { param.cache_size = _cache_size; } void SVMTrainModel::setC(double _C) { param.C = _C; } void SVMTrainModel::setEps(double _eps) { param.eps = _eps; } void SVMTrainModel::setP(double _p) { param.p = _p; } void SVMTrainModel::setShrinking(int _shrinking) { param.shrinking = _shrinking; } void SVMTrainModel::setProbability(int _probability) { param.probability = _probability; } void SVMTrainModel::setCrossValidation(int _nr_fold) { cross_validation = 0; if (_nr_fold > 0) { cross_validation = 1; nr_fold = _nr_fold; } } // for class i weight _weight void SVMTrainModel::setWeight(int _i, float _weight) { ++param.nr_weight; param.weight_label = (int *)realloc(param.weight_label, sizeof(int) * param.nr_weight); param.weight = (double *)realloc(param.weight, sizeof(double) * param.nr_weight); param.weight_label[param.nr_weight - 1] = _i; param.weight[param.nr_weight - 1] = _weight; } void SVMTrainModel::setInputFileName(std::string _input_file_name) { have_input_file_name = true; std::strcpy(input_file_name, _input_file_name.c_str()); // input_file_name = _input_file_name.c_str(); } void SVMTrainModel::setModelFileName(std::string _model_file_name) { have_model_file_name = true; std::strcpy(model_file_name, _model_file_name.c_str()); // model_file_name = _model_file_name.c_str(); } void SVMTrainModel::setNoPrint(bool _no_print) { if (_no_print) { void (*print_func)(const char *) = &SVMTrainModel::print_null; svm_set_print_string_function(print_func); } else { void (*print_func)(const char *) = nullptr; // default printing to stdout svm_set_print_string_function(print_func); } } int SVMTrainModel::train(double &RecRate, std::vector<int> &ConfusionTable) { if ((!have_input_file_name) || (!have_model_file_name)) { fprintf(stderr, "ERROR: Set Input and Model files first!\n"); exit(1); } const char *error_msg; readProblem(input_file_name); error_msg = svm_check_parameter(&prob, &param); if (error_msg) { fprintf(stderr, "ERROR: %s\n", error_msg); exit(1); } if (cross_validation) { do_cross_validation(RecRate, ConfusionTable); } else { model = svm_train(&prob, &param); if (svm_save_model(model_file_name, model)) { fprintf(stderr, "can't save model to file %s\n", model_file_name); exit(1); } svm_free_and_destroy_model(&model); } svm_destroy_param(&param); free(prob.y); free(prob.x); free(x_space); free(line); return 0; } void SVMTrainModel::do_cross_validation(double &RecRate, std::vector<int> &ConfusionTable) { int i; int total_correct = 0; double total_error = 0; double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0; double *target = Malloc(double, prob.l); svm_cross_validation(&prob, &param, nr_fold, target); if (param.svm_type == EPSILON_SVR || param.svm_type == NU_SVR) { for (i = 0; i < prob.l; i++) { double y = prob.y[i]; double v = target[i]; total_error += (v - y) * (v - y); sumv += v; sumy += y; sumvv += v * v; sumyy += y * y; sumvy += v * y; } printf("Cross Validation Mean squared error = %g\n", total_error / prob.l); printf("Cross Validation Squared correlation coefficient = %g\n", ((prob.l * sumvy - sumv * sumy) * (prob.l * sumvy - sumv * sumy)) / ((prob.l * sumvv - sumv * sumv) * (prob.l * sumyy - sumy * sumy))); } else { ConfusionTable.at(0) = 0; ConfusionTable.at(1) = 0; ConfusionTable.at(2) = 0; ConfusionTable.at(3) = 0; for (i = 0; i < prob.l; i++) { if (target[i] == prob.y[i]) { ++total_correct; if (target[i] == 0) { ConfusionTable.at(0) += 1; } else { ConfusionTable.at(3) += 1; } } else { if (target[i] == 0) { ConfusionTable.at(2) += 1; } else { ConfusionTable.at(1) += 1; } } } // printf("Cross Validation Accuracy = %g%%\n",100.0*total_correct/prob.l); RecRate = 100.0 * total_correct / prob.l; } free(target); } // read in a problem (in svmlight format) void SVMTrainModel::readProblem(const char *filename) { int elements, max_index, inst_max_index, i, j; FILE *fp = fopen(filename, "r"); char *endptr; char *idx, *val, *label; if (fp == nullptr) { fprintf(stderr, "can't open input file %s\n", filename); exit(1); } prob.l = 0; elements = 0; max_line_len = 1024; line = Malloc(char, max_line_len); while (readline(fp) != nullptr) { char *p = strtok(line, " \t"); // label // features while (1) { p = strtok(nullptr, " \t"); if (p == nullptr || *p == '\n') // check '\n' as ' ' may be after the last feature break; ++elements; } ++elements; ++prob.l; } rewind(fp); prob.y = Malloc(double, prob.l); prob.x = Malloc(struct svm_node *, prob.l); x_space = Malloc(struct svm_node, elements); max_index = 0; j = 0; for (i = 0; i < prob.l; i++) { inst_max_index = -1; // strtol gives 0 if wrong format, and precomputed kernel has <index> start from 0 readline(fp); prob.x[i] = &x_space[j]; label = strtok(line, " \t\n"); if (label == nullptr) // empty line exit_input_error(i + 1); prob.y[i] = strtod(label, &endptr); if (endptr == label || *endptr != '\0') exit_input_error(i + 1); while (true) { idx = strtok(nullptr, ":"); val = strtok(nullptr, " \t"); if (val == nullptr) break; errno = 0; x_space[j].index = (int)strtol(idx, &endptr, 10); if (endptr == idx || errno != 0 || *endptr != '\0' || x_space[j].index <= inst_max_index) exit_input_error(i + 1); else inst_max_index = x_space[j].index; errno = 0; x_space[j].value = strtod(val, &endptr); if (endptr == val || errno != 0 || (*endptr != '\0' && !isspace(*endptr))) exit_input_error(i + 1); ++j; } if (inst_max_index > max_index) max_index = inst_max_index; x_space[j++].index = -1; } if (param.gamma == 0 && max_index > 0) param.gamma = 1.0 / max_index; if (param.kernel_type == PRECOMPUTED) for (i = 0; i < prob.l; i++) { if (prob.x[i][0].index != 0) { fprintf(stderr, "Wrong input format: first column must be 0:sample_serial_number\n"); exit(1); } if ((int)prob.x[i][0].value <= 0 || (int)prob.x[i][0].value > max_index) { fprintf(stderr, "Wrong input format: sample_serial_number out of range\n"); exit(1); } } fclose(fp); } } // namespace svm
27.737968
108
0.632639
v4r-tuwien
647f6feab95a24cb98315ef067c6de194d0bc65d
1,400
cpp
C++
PocketNN/Main.cpp
jaewoosong/pocketnn
68f95401e8681483f764b063a6b886967d228a7f
[ "MIT" ]
9
2022-02-16T19:15:55.000Z
2022-03-21T10:44:51.000Z
PocketNN/Main.cpp
jaewoosong/pocketnn
68f95401e8681483f764b063a6b886967d228a7f
[ "MIT" ]
null
null
null
PocketNN/Main.cpp
jaewoosong/pocketnn
68f95401e8681483f764b063a6b886967d228a7f
[ "MIT" ]
1
2022-03-09T12:24:25.000Z
2022-03-09T12:24:25.000Z
#include "pktnn_examples.h" int main() { // There are 3 examples // 1) very simple integer BP: example_fc_int_bp_very_simple(); // 2) fc mnist integer DFA: example_fc_int_dfa_mnist(); // 3) fc fashion mnist integer DFA: example_fc_int_dfa_fashion_mnist(); // CAUTION: // MNIST and Fashion-MNIST datasets should be downloaded in advance // and put into ./dataset/ directory with following filenames. // (1) MNIST (http://yann.lecun.com/exdb/mnist/) // Already downloaded in advance because MNIST website allows making copies. // ("Please refrain from accessing these files from automated scripts with high frequency. Make copies!") // ./dataset/mnist/train-labels.idx1-ubyte // ./dataset/mnist/train-images.idx3-ubyte // ./dataset/mnist/t10k-labels.idx1-ubyte // ./dataset/mnist/t10k-images.idx3-ubyte // (2) Fashion-MNIST (https://github.com/zalandoresearch/fashion-mnist) // Already downloaded in advance because Fashion-MNIST uses MIT License which allows distribution. // ./dataset/fashion_mnist/train-labels-idx1-ubyte // ./dataset/fashion_mnist/train-images-idx3-ubyte // ./dataset/fashion_mnist/t10k-labels-idx1-ubyte // ./dataset/fashion_mnist/t10k-images-idx3-ubyte // (Please download the files from the link.) example_fc_int_dfa_mnist(); return 0; }
43.75
110
0.689286
jaewoosong
647fa93ac7caedbb6b8d09ff15b5c2def11e1613
446
cpp
C++
d1eq.cpp
fluier/math
626ab4f0cd92e1c0ac9f7172d80cc202100e3673
[ "MIT" ]
null
null
null
d1eq.cpp
fluier/math
626ab4f0cd92e1c0ac9f7172d80cc202100e3673
[ "MIT" ]
null
null
null
d1eq.cpp
fluier/math
626ab4f0cd92e1c0ac9f7172d80cc202100e3673
[ "MIT" ]
null
null
null
/* * d1eq.cpp * * Created on: Apr 4, 2017 * Author: constantin */ #include "d1eq.h" d1eq::d1eq(float a, float b, float c):_a(a),_b(b),_c(c) { } d1eq::~d1eq() { // TODO Auto-generated destructor stub } bool d1eq::belong(float x, float y) { const float thresh = 0.000001; float aux = _a*x + _b*y - _c; if(-thresh < aux || aux < thresh){ return true; } return false; } float d1eq::fdx(float x) { return (_c - _a * x)/_b; }
14.866667
57
0.589686
fluier
647fc9fe57682629ccb9a0068775f5d779d8d585
4,648
cpp
C++
2term/Programming/3.1/31.cpp
nik-sergeson/bsuir-informatics-labs
14805fb83b8e2324580b6253158565068595e804
[ "Apache-2.0" ]
null
null
null
2term/Programming/3.1/31.cpp
nik-sergeson/bsuir-informatics-labs
14805fb83b8e2324580b6253158565068595e804
[ "Apache-2.0" ]
null
null
null
2term/Programming/3.1/31.cpp
nik-sergeson/bsuir-informatics-labs
14805fb83b8e2324580b6253158565068595e804
[ "Apache-2.0" ]
null
null
null
#include <malloc.h> #include <stdio.h> #include <conio.h> #include <Windows.h> #include <string.h> #include <stdlib.h> const int SLength=17; void Menu(void); double * AddElem(double Val,double* Mas,int *Smas); double CurrVal(int Index,double* Mas); double * EditMas(int ElemIndex,double Val,double* Mas); double * MasMenu(double* Mas,int *Smas); void Calculations(double *VoiceTime,double *MoveSp,double *MoveTime,int SVoiceTime,double VVelos); int Count(double Val); void main(void){ Menu(); } void Menu(void){ int Choice=0,SVoiceTime=0,SMoveSp=0,SMoveTime=0; double *VoiceTime=NULL,*MoveSp=NULL,*MoveTime=NULL,VVelos; char str1[SLength]; while (Choice!=5){ system("cls"); printf("1)Vrem'a golosovani'a pered i'm ychastkom\n2)Skorost na i'm ychastke\n3)Vrem'a dvizheni'a na i'm ychastke\n4)Calculate\n5)Exit\n"); Choice=getch(); switch (Choice){ case '1': VoiceTime=MasMenu(VoiceTime,&SVoiceTime); break; case '2': MoveSp=MasMenu(MoveSp,&SMoveSp); break; case '3': MoveTime=MasMenu(MoveTime,&SMoveTime); break; case '4': system("cls"); printf("Enter speed of bycecle\n"); scanf("%s",&str1); if (((VVelos=atof(str1))==0)||(Count(VVelos)<strlen(str1))) printf("Wrong value"); else Calculations(VoiceTime,MoveSp,MoveTime,SVoiceTime,VVelos); getch(); break; case '5': Choice=5; free(VoiceTime); free(MoveSp); free(MoveTime); break; } } } double * MasMenu(double* Mas,int *Smas){ int Choice=0,ElemIndex; double Val; char str1[SLength],str2[SLength]; while (Choice!=4){ system("cls"); printf("1)Add Element\n2)Edit element\n3)Value(index)\n4)Back\n"); Choice=getch(); switch (Choice){ case '1': system("cls"); printf("Enter value\n"); scanf("%s",str1); if (((Val=atof(str1))==0)||(Count(Val)<strlen(str1))) printf("Wrong value"); else{ Mas=AddElem(Val,Mas,Smas); printf("Element entered,press any button to continue\n"); } getch(); break; case '2': system("cls"); printf("Enter value and index \n"); scanf("%s",str1); Val=atof(str1); scanf("%s",str2); ElemIndex=atoi(str2); if ((Val==0) || (ElemIndex==0) ||(Count(ElemIndex)<strlen(str2))||(Count(Val)<strlen(str1))|| (ElemIndex>*Smas)){ printf("Wrong value"); } else{ Mas=EditMas(ElemIndex,Val,Mas); printf("Element edited,press any button to continue\n"); } getch(); break; case '3': system("cls"); printf("Enter index\n"); scanf("%s",str2); if (((ElemIndex=atoi(str2))==0)||(Count(ElemIndex)<strlen(str2))||(ElemIndex>*Smas)) printf("Wrong value"); else{ printf("Value=%.2lf\n",CurrVal(ElemIndex,Mas)); printf("Press any button to continue\n"); } getch(); break; case '4': Choice=4; break; } } return Mas; } double * EditMas(int ElemIndex,double Val,double* Mas){ Mas[ElemIndex-1]=Val; return Mas; } double * AddElem(double Val,double* Mas,int *Smas){ double* CMas=NULL; int i; if (*Smas==0){ Mas = (double *) malloc( sizeof(double)); *Smas=1; Mas[0]=Val; return Mas; } else{ ++*Smas; CMas=(double *) malloc((*Smas)*sizeof(double)); for(i=0;i<*Smas-1;++i){ CMas[i]=Mas[i]; } free(Mas); CMas[*Smas-1]=Val; return CMas; } } double CurrVal(int Index,double* Mas){ return Mas[Index-1]; } void Calculations(double *VoiceTime,double *MoveSp,double *MoveTime,int SVoiceTime,double VVelos){ int i=0; double SVelos=0,SStop=0,ds=0,Nds=0,Tmeet=0,CTime=0,SMeet=0; bool VLead=true; for(i;i<=SVoiceTime-1;++i){ ds=(SStop-SVelos); Nds=ds-(VoiceTime[i]/60)*VVelos; if ((ds*Nds)<0){ Tmeet=ds/VVelos; SMeet=SStop; Tmeet=CTime+Tmeet; printf("Time=%3.1lf\n",Tmeet); printf("Length=%3.1lf\n",SMeet); } ds=Nds; SVelos=SVelos+(VoiceTime[i]/60)*VVelos; CTime=CTime+VoiceTime[i]/60; Nds=(SStop+MoveSp[i]*MoveTime[i]-(SVelos+VVelos*MoveTime[i])); if ((ds*Nds)<0){ Tmeet=ds/(VVelos-MoveSp[i]); SMeet=SVelos+Tmeet*VVelos; Tmeet=CTime+Tmeet; printf("Time=%3.1lf\n",Tmeet); printf("Length=%3.1lf\n",SMeet); } SVelos=SVelos+VVelos*MoveTime[i]; SStop=SStop+MoveTime[i]*MoveSp[i]; CTime=CTime+MoveTime[i]; } if (Tmeet==0) printf("Won't meet\n"); } int Count(double Val){ int i=0; if ((Val-(int)Val)!=0) ++i; while ((int)Val!=0) Val/=10; while ((Val-(int)Val)!=0){ Val*=10; ++i; } return i; }
23.356784
142
0.597461
nik-sergeson
6482ac1f37f2f984af16d4dc08d678ce8b1ae9f2
107
hpp
C++
native/copy.hpp
G07cha/node-libpng
e89f4ef762e255b2c839185341e61af138956b04
[ "MIT" ]
20
2018-03-22T08:37:33.000Z
2021-12-14T13:17:19.000Z
native/copy.hpp
G07cha/node-libpng
e89f4ef762e255b2c839185341e61af138956b04
[ "MIT" ]
43
2018-03-21T09:46:04.000Z
2021-12-14T13:13:54.000Z
native/copy.hpp
G07cha/node-libpng
e89f4ef762e255b2c839185341e61af138956b04
[ "MIT" ]
8
2018-07-05T06:56:47.000Z
2021-01-16T11:25:36.000Z
#ifndef COPY_HPP #define COPY_HPP #include <nan.h> NAN_METHOD(copy); NAN_MODULE_INIT(InitCopy); #endif
9.727273
26
0.757009
G07cha
64842b87ba3bd11e3ac3f897a099165bed6567b5
1,322
hpp
C++
kernel/include/io/io.hpp
Eospp/Eospp
bc231908aaf34dfc2f790a259487253a4151be16
[ "MIT" ]
18
2022-01-21T18:19:37.000Z
2022-03-15T05:26:32.000Z
kernel/include/io/io.hpp
Eospp/Eospp
bc231908aaf34dfc2f790a259487253a4151be16
[ "MIT" ]
null
null
null
kernel/include/io/io.hpp
Eospp/Eospp
bc231908aaf34dfc2f790a259487253a4151be16
[ "MIT" ]
3
2022-01-22T14:24:04.000Z
2022-02-23T10:19:11.000Z
#pragma once #include <type.hpp> namespace eospp::io { inline estd::uint8_t in_byte(estd::uint16_t port) { estd::uint8_t v; asm volatile("inb %[v] %[port]" : [v] "=a"(v) : [port] "dN"(port) : "memory"); return v; } inline void out_byte(estd::uint16_t _port, estd::uint8_t _data) { asm volatile("outb %[data],%[port]" : : [port] "dN"(_port), [data] "a"(_data):); } inline estd::uint16_t in_word(estd::uint16_t port) { estd::uint16_t v; asm volatile("inb %[v] %[port]" : [v] "=a"(v) : [port] "dN"(port) : "memory"); return v; } inline void out_word(estd::uint16_t port, estd::uint16_t data) { asm volatile("outw %[data] %[port]" : : [port] "dN"(port), [data] "a"(data)); } inline estd::uint32_t in_dword(estd::uint16_t port) { estd::uint32_t v; asm volatile("inl %[v] %[port]" : [v] "=a"(v) : [port] "dN"(port) : "memory"); return v; } inline void out_dword(estd::uint16_t port, estd::uint32_t data) { __asm__ __volatile__("outl %[data] %[port]" : : [port] "dN"(port), [data] "a"(data)); } } // namespace eospp::io
26.44
65
0.484115
Eospp
6485801304be1490f9b980ae1ef03f2fe9151097
18,463
cpp
C++
NavimeshExporter/src/interface.cpp
noodle1983/recastnavigation
f4804a183bb3ab3387e78d11696591651b0e6bd8
[ "Zlib" ]
null
null
null
NavimeshExporter/src/interface.cpp
noodle1983/recastnavigation
f4804a183bb3ab3387e78d11696591651b0e6bd8
[ "Zlib" ]
null
null
null
NavimeshExporter/src/interface.cpp
noodle1983/recastnavigation
f4804a183bb3ab3387e78d11696591651b0e6bd8
[ "Zlib" ]
1
2022-02-09T11:50:25.000Z
2022-02-09T11:50:25.000Z
#include "interface.h" #include "MeshParser.hpp" using namespace nd; #include "nd_header.h" namespace nd{ #include "Detour/DetourCommon.h" #include "Detour/DetourNavMesh.h" #include "Detour/DetourNavMeshBuilder.cpp" template<class T> inline T rcMin(T a, T b) { return a < b ? a : b; } inline unsigned int nextPow2(unsigned int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } inline unsigned int ilog2(unsigned int v) { unsigned int r; unsigned int shift; r = (v > 0xffff) << 4; v >>= r; shift = (v > 0xff) << 3; v >>= shift; r |= shift; shift = (v > 0xf) << 2; v >>= shift; r |= shift; shift = (v > 0x3) << 1; v >>= shift; r |= shift; r |= (v >> 1); return r; } } #include <cstring> #include <memory> using namespace std; //[StructLayout(LayoutKind.Sequential)] //class MyClass { // ... //} struct NavimeshTileData{ float* verts; int vertCount; // per vertice/edge data unsigned short* triangles; unsigned short* neis; int triangleIndexCount; // per triangle data short* polyFlags; char* polyAreaTypes; // portal count short portalCount; bool buildBvTree; int tileX; int tileY; int tileLayer; unsigned int userId; float walkableHeight; float walkableRadius; float walkableClimb; float bmin[3]; float bmax[3]; }; const float BvQuantFactor = 1; static int createBVTree(NavimeshTileData* tileData, dtBVNode* nodes, int /*nnodes*/) { // Build tree const int polyCount = tileData->triangleIndexCount/3; BVItem* items = (BVItem*)dtAlloc(sizeof(BVItem)*polyCount, DT_ALLOC_TEMP); float* tbmin = tileData->bmin; for (int i = 0; i < polyCount; i++) { BVItem& it = items[i]; it.i = i; float bmin[3]; float bmax[3]; const unsigned short* p = &tileData->triangles[i*3]; dtVcopy(bmin, &tileData->verts[p[0] * 3]); dtVcopy(bmax, &tileData->verts[p[0] * 3]); for (int j = 1; j < 3; ++j) { dtVmin(bmin, &tileData->verts[p[j] * 3]); dtVmax(bmax, &tileData->verts[p[j] * 3]); } it.bmin[0] = (unsigned short)dtMathFloorf((bmin[0]-tbmin[0])*BvQuantFactor); it.bmin[1] = (unsigned short)dtMathFloorf((bmin[1]-tbmin[1])*BvQuantFactor); it.bmin[2] = (unsigned short)dtMathFloorf((bmin[2]-tbmin[2])*BvQuantFactor); it.bmax[0] = (unsigned short)dtMathCeilf((bmax[0]-tbmin[0])*BvQuantFactor); it.bmax[1] = (unsigned short)dtMathCeilf((bmax[1]-tbmin[1])*BvQuantFactor); it.bmax[2] = (unsigned short)dtMathCeilf((bmax[2]-tbmin[2])*BvQuantFactor); } int curNode = 0; subdivide(items, polyCount, 0, polyCount, curNode, nodes); dtFree(items); return curNode; } bool dumpSoloTileData(NavimeshTileData* tileData, unsigned char** outData, int* outDataSize) { if (tileData->vertCount >= 0xffff) return false; if (!tileData->vertCount || !tileData->verts) return false; if (!tileData->triangleIndexCount || !tileData->triangles) return false; int storedOffMeshConCount = 0; int offMeshConLinkCount = 0; // Off-mesh connectionss are stored as polygons, adjust values. const int polyCount = tileData->triangleIndexCount/3; const int totPolyCount = tileData->triangleIndexCount/3 + storedOffMeshConCount; const int totVertCount = tileData->vertCount + storedOffMeshConCount*2; const int portalCount = tileData->portalCount; //const int edgeCount = tileData->triangleIndexCount; const int maxLinkCount = tileData->triangleIndexCount + tileData->portalCount*2 + offMeshConLinkCount*2; int uniqueDetailVertCount = 0; int detailTriCount = tileData->triangleIndexCount/3; // Calculate data size const int headerSize = dtAlign4(sizeof(dtMeshHeader)); const int vertsSize = dtAlign4(sizeof(float)*3*totVertCount); const int polysSize = dtAlign4(sizeof(dtPoly)*totPolyCount); const int linksSize = dtAlign4(sizeof(dtLink)*maxLinkCount); const int detailMeshesSize = dtAlign4(sizeof(dtPolyDetail)*polyCount); const int detailVertsSize = dtAlign4(sizeof(float)*3*uniqueDetailVertCount); const int detailTrisSize = dtAlign4(sizeof(unsigned char)*4*detailTriCount); const int bvTreeSize = tileData->buildBvTree ? dtAlign4(sizeof(dtBVNode)*polyCount*2) : 0; const int offMeshConsSize = dtAlign4(sizeof(dtOffMeshConnection)*storedOffMeshConCount); const int dataSize = headerSize + vertsSize + polysSize + linksSize + detailMeshesSize + detailVertsSize + detailTrisSize + bvTreeSize + offMeshConsSize; unsigned char* data = (unsigned char*)dtAlloc(sizeof(unsigned char)*dataSize, DT_ALLOC_PERM); if (!data) { return false; } memset(data, 0, dataSize); unsigned char* d = data; dtMeshHeader* header = dtGetThenAdvanceBufferPointer<dtMeshHeader>(d, headerSize); float* navVerts = dtGetThenAdvanceBufferPointer<float>(d, vertsSize); dtPoly* navPolys = dtGetThenAdvanceBufferPointer<dtPoly>(d, polysSize); d += linksSize; // Ignore links; just leave enough space for them. They'll be created on load. dtPolyDetail* navDMeshes = dtGetThenAdvanceBufferPointer<dtPolyDetail>(d, detailMeshesSize); float* navDVerts = dtGetThenAdvanceBufferPointer<float>(d, detailVertsSize); unsigned char* navDTris = dtGetThenAdvanceBufferPointer<unsigned char>(d, detailTrisSize); dtBVNode* navBvtree = dtGetThenAdvanceBufferPointer<dtBVNode>(d, bvTreeSize); dtOffMeshConnection* offMeshCons = dtGetThenAdvanceBufferPointer<dtOffMeshConnection>(d, offMeshConsSize); // Store header header->magic = DT_NAVMESH_MAGIC; header->version = DT_NAVMESH_VERSION; header->x = tileData->tileX; header->y = tileData->tileY; header->layer = tileData->tileLayer; header->userId = tileData->userId; header->polyCount = totPolyCount; header->vertCount = totVertCount; header->maxLinkCount = maxLinkCount; dtVcopy(header->bmin, tileData->bmin); dtVcopy(header->bmax, tileData->bmax); header->detailMeshCount = polyCount; header->detailVertCount = uniqueDetailVertCount; header->detailTriCount = detailTriCount; header->bvQuantFactor = BvQuantFactor; // limited scene max length to 0xffff header->offMeshBase = polyCount; header->walkableHeight = tileData->walkableHeight; header->walkableRadius = tileData->walkableRadius; header->walkableClimb = tileData->walkableClimb; header->offMeshConCount = storedOffMeshConCount; header->bvNodeCount = tileData->buildBvTree ? polyCount*2 : 0; const int offMeshVertsBase = tileData->vertCount; const int offMeshPolyBase = polyCount; // Store vertices // Mesh vertices memcpy(navVerts, tileData->verts, sizeof(tileData->verts[0]) * tileData->vertCount); // Store polygons // Mesh polys for (int i = 0; i < polyCount; ++i) { dtPoly* p = &navPolys[i]; p->vertCount = 3; p->flags = tileData->polyFlags[i]; p->areaAndtype = tileData->polyAreaTypes[i]; for(int j = 0; j < p->vertCount; j++){ p->verts[j] = tileData->triangles[i*3 + j]; p->neis[j] = tileData->neis[i*3 + j]; } } // Store detail meshes and vertices. // The nav polygon vertices are stored as the first vertices on each mesh. // We compress the mesh data by skipping them and using the navmesh coordinates. // Create dummy detail mesh by triangulating polys. int tbase = 0; for (int i = 0; i < polyCount; ++i) { dtPolyDetail& dtl = navDMeshes[i]; const int nv = navPolys[i].vertCount; dtl.vertBase = 0; dtl.vertCount = 0; dtl.triBase = (unsigned int)tbase; dtl.triCount = (unsigned char)(nv-2); // Triangulate polygon (local indices). for (int j = 2; j < nv; ++j) { unsigned char* t = &navDTris[tbase*4]; t[0] = 0; t[1] = (unsigned char)(j-1); t[2] = (unsigned char)j; // Bit for each edge that belongs to poly boundary. t[3] = (1<<2); if (j == 2) t[3] |= (1<<0); if (j == nv-1) t[3] |= (1<<4); tbase++; } } // Store and create BVtree. if (tileData->buildBvTree) { createBVTree(tileData, navBvtree, 2*polyCount); } *outData = data; *outDataSize = dataSize; return true; } static const int NAVMESHSET_MAGIC = 'M'<<24 | 'S'<<16 | 'E'<<8 | 'T'; //'MSET'; static const int NAVMESHSET_VERSION = 1; struct NavMeshSetHeader { int magic; int version; int numTiles; dtNavMeshParams params; }; struct NavMeshTileHeader { dtTileRef tileRef; int dataSize; }; void saveAll(const char* path, const dtNavMesh* mesh) { if (!mesh) return; FILE* fp = fopen(path, "wb"); if (!fp) return; // Store header. NavMeshSetHeader header; header.magic = NAVMESHSET_MAGIC; header.version = NAVMESHSET_VERSION; header.numTiles = 0; for (int i = 0; i < mesh->getMaxTiles(); ++i) { const dtMeshTile* tile = mesh->getTile(i); if (!tile || !tile->header || !tile->dataSize) continue; header.numTiles++; } memcpy(&header.params, mesh->getParams(), sizeof(dtNavMeshParams)); fwrite(&header, sizeof(NavMeshSetHeader), 1, fp); // Store tiles. for (int i = 0; i < mesh->getMaxTiles(); ++i) { const dtMeshTile* tile = mesh->getTile(i); if (!tile || !tile->header || !tile->dataSize) continue; NavMeshTileHeader tileHeader; tileHeader.tileRef = mesh->getTileRef(tile); tileHeader.dataSize = tile->dataSize; fwrite(&tileHeader, sizeof(tileHeader), 1, fp); fwrite(tile->data, tile->dataSize, 1, fp); } fclose(fp); } static char* dupstr(const char* str) { if (str == nullptr) { return nullptr; } int len = (int)strlen(str) + 1; char* ret = new char[len]; if (len > 1) { memcpy(ret, str, len - 1); } ret[len - 1] = 0; return ret; } char* exportDetourFormatFile(const char* detourMeshPath, const char* detourBinPath){ auto mesh = parseMesh(detourMeshPath); if (mesh == nullptr) { return dupstr("failed to parse the detour mesh file!"); } shared_ptr<Mesh> meshDeletor(mesh); auto& vertices = mesh->vertices; auto& vi = mesh->triangles; auto& trianglesFlag = mesh->trianglesFlag; auto& trianglesAreaType = mesh->trianglesAreaType; auto& lineNeis = mesh->lineNeis; if (vertices.size() == 0 || vi.size() == 0) { return dupstr("empty mesh!"); } struct NavimeshTileData tileData; memset(&tileData, 0, sizeof(NavimeshTileData)); tileData.verts = vertices.data(); tileData.vertCount = (int)vertices.size(); float* bmin = tileData.bmin; float* bmax = tileData.bmax; dtVcopy(bmin, tileData.verts); dtVcopy(bmax, tileData.verts); for(int i = 0; i < tileData.vertCount/3; i++){ float* base = &tileData.verts[i*3]; dtVmin(bmin, base); dtVmax(bmax, base); } // per vertice/edge data tileData.triangles = vi.data(); tileData.triangleIndexCount = (int)vi.size(); using Edge2Triangle = map<uint64_t, vector<unsigned short>>; Edge2Triangle edge2triangle; auto make_line = [](uint64_t a, uint64_t b){ return a > b ? ((b<<32) | a) : ((a<<32) | b); }; for(unsigned short i = 0; i < vi.size()/3; i++){ unsigned short* base = &vi[i * 3]; uint64_t line1 = make_line(base[0], base[1]); edge2triangle[line1].push_back(i); uint64_t line2 = make_line(base[1], base[2]); edge2triangle[line2].push_back(i); uint64_t line3 = make_line(base[2], base[0]); edge2triangle[line3].push_back(i); } VerticeIndexes edgeInfo; VerticeIndexes flagsInfo; using CharVector = vector<char>; CharVector areaTypesInfo; for(unsigned short i = 0; i < vi.size()/3; i++){ flagsInfo.push_back(trianglesFlag[i]); areaTypesInfo.push_back(trianglesAreaType[i]); unsigned short* base = &vi[i * 3]; for(int j = 0; j < 3; j++){ uint64_t line = make_line(base[j], base[(j+1)%3]); if(edge2triangle[line].size() == 1){ edgeInfo.push_back(0); }else{ unsigned short otherPolyRef = edge2triangle[line][0] == i ? edge2triangle[line][1] : edge2triangle[line][0]; edgeInfo.push_back(otherPolyRef + 1); } } } tileData.neis = edgeInfo.data(); // per triangle data tileData.polyFlags = (short*)flagsInfo.data(); tileData.polyAreaTypes = areaTypesInfo.data(); // portal count tileData.portalCount = 0; tileData.buildBvTree = true; tileData.tileX = 0; tileData.tileY = 0; tileData.tileLayer = 0; tileData.userId = 0; tileData.walkableHeight = 0; tileData.walkableRadius = 0; tileData.walkableClimb = 0; unsigned char* outData = NULL; int outDataSize = 0; bool ret = dumpSoloTileData(&tileData, &outData, &outDataSize); if(ret){ dtNavMesh* navMesh = dtAllocNavMesh(); if (!navMesh) { dtFree(outData); return dupstr("Could not create Detour navmesh"); } shared_ptr<dtNavMesh> navMeshDeletor(navMesh, [](auto p) {dtFreeNavMesh(p); }); dtStatus status = navMesh->init(outData, outDataSize, DT_TILE_FREE_DATA); if (dtStatusFailed(status)) { dtFree(outData); return dupstr("Could not init Detour navmesh"); } saveAll(detourBinPath, navMesh); } return nullptr; } unsigned char* buildTileMesh(TiledMesh* mesh, int& dataSize){ auto& vertices = mesh->vertices; auto& vi = mesh->triangles; auto& trianglesFlag = mesh->trianglesFlag; auto& trianglesAreaType = mesh->trianglesAreaType; auto& lineNeis = mesh->lineNeis; auto tx = mesh->tx; auto ty = mesh->ty; struct NavimeshTileData tileData; memset(&tileData, 0, sizeof(NavimeshTileData)); tileData.verts = vertices.data(); tileData.vertCount = (int)vertices.size(); float* bmin = tileData.bmin; float* bmax = tileData.bmax; dtVcopy(bmin, tileData.verts); dtVcopy(bmax, tileData.verts); for(int i = 0; i < tileData.vertCount/3; i++){ float* base = &tileData.verts[i*3]; dtVmin(bmin, base); dtVmax(bmax, base); } // per vertice/edge data tileData.triangles = vi.data(); tileData.triangleIndexCount = (int)vi.size(); using Edge2Triangle = map<uint64_t, vector<unsigned short>>; Edge2Triangle edge2triangle; auto make_line = [](uint64_t a, uint64_t b){ return a > b ? ((b<<32) | a) : ((a<<32) | b); }; for(unsigned short i = 0; i < vi.size()/3; i++){ unsigned short* base = &vi[i * 3]; uint64_t line1 = make_line(base[0], base[1]); edge2triangle[line1].push_back(i); uint64_t line2 = make_line(base[1], base[2]); edge2triangle[line2].push_back(i); uint64_t line3 = make_line(base[2], base[0]); edge2triangle[line3].push_back(i); } VerticeIndexes edgeInfo; VerticeIndexes flagsInfo; using CharVector = vector<char>; CharVector areaTypesInfo; CharVector typeInfo; short portalCount = 0; for(unsigned short i = 0; i < vi.size()/3; i++){ flagsInfo.push_back(trianglesFlag[i]); areaTypesInfo.push_back(trianglesAreaType[i]); unsigned short* base = &vi[i * 3]; unsigned short* lineNeisBase = &lineNeis[i * 3]; for(int j = 0; j < 3; j++){ uint64_t line = make_line(base[j], base[(j+1)%3]); if (lineNeisBase[j] & DT_EXT_LINK) { edgeInfo.push_back(lineNeisBase[j]); portalCount++; } else if(edge2triangle[line].size() == 1){ edgeInfo.push_back(0); }else{ unsigned short otherPolyRef = edge2triangle[line][0] == i ? edge2triangle[line][1] : edge2triangle[line][0]; edgeInfo.push_back(otherPolyRef + 1); } } } tileData.neis = edgeInfo.data(); // per triangle data tileData.polyFlags = (short*)flagsInfo.data(); tileData.polyAreaTypes = areaTypesInfo.data(); // portal count tileData.portalCount = portalCount; tileData.buildBvTree = true; tileData.tileX = tx; tileData.tileY = ty; tileData.tileLayer = 0; tileData.userId = 0; tileData.walkableHeight = 0; tileData.walkableRadius = 0; tileData.walkableClimb = 0; unsigned char* outData = NULL; bool ret = dumpSoloTileData(&tileData, &outData, &dataSize); return outData; } char* exportTiledDetourFormatFile(const char* detourMeshPath, const char* detourBinPath) { auto mesh = parseMesh(detourMeshPath); if (mesh == nullptr) { return dupstr("failed to parse the detour mesh file!"); } shared_ptr<Mesh> meshDeletor(mesh); if (mesh->tiledMeshList.size() <= 1) { return exportDetourFormatFile(detourMeshPath, detourBinPath); } dtNavMesh* navMesh = dtAllocNavMesh(); if (!navMesh) { return dupstr("Could not create Detour navmesh"); } shared_ptr<dtNavMesh> navMeshDeletor(navMesh, [](auto p) {dtFreeNavMesh(p); }); dtNavMeshParams params; dtVcopy(params.orig, mesh->bmin.data()); params.tileWidth = mesh->tileWidth; params.tileHeight = mesh->tileHeight; int tileBits = ilog2(nextPow2(mesh->tw* mesh->th)); if (tileBits > 14) { return dupstr("too many tiles!"); } int polyBits = 22 - tileBits; params.maxTiles = 1 << tileBits; params.maxPolys = 1 << polyBits; dtStatus status = navMesh->init(&params); if (dtStatusFailed(status)) { return dupstr("Could not init Detour navmesh"); } for (auto & tiledMesh : mesh->tiledMeshList) { int polyCount = (int)tiledMesh.triangles.size() / 3; if (polyCount > params.maxPolys) { return dupstr("too many polys in a tile!"); } if (tiledMesh.vertices.size() == 0 || tiledMesh.triangles.size() == 0) { continue; } int dataSize = 0; unsigned char* data = buildTileMesh(&tiledMesh, dataSize); if (data) { // Remove any previous data (navmesh owns and deletes the data). navMesh->removeTile(navMesh->getTileRefAt(tiledMesh.tx, tiledMesh.ty, 0), 0, 0); // Let the navmesh own the data. dtStatus status = navMesh->addTile(data, dataSize, DT_TILE_FREE_DATA, 0, 0); if (dtStatusFailed(status)) { dtFree(data); } } } saveAll(detourBinPath, navMesh); return nullptr; }
32.22164
125
0.642203
noodle1983
6487238a009c9c402ee97317f3263003af34ff8b
1,603
cpp
C++
PGRIsland/source/CSplineSceneNode.cpp
ngohongs/pgr-island
48aa8e688ff1204cca51976c255ba378840b0565
[ "CC-BY-4.0" ]
null
null
null
PGRIsland/source/CSplineSceneNode.cpp
ngohongs/pgr-island
48aa8e688ff1204cca51976c255ba378840b0565
[ "CC-BY-4.0" ]
null
null
null
PGRIsland/source/CSplineSceneNode.cpp
ngohongs/pgr-island
48aa8e688ff1204cca51976c255ba378840b0565
[ "CC-BY-4.0" ]
null
null
null
//---------------------------------------------------------------------------------------- /** * \file CSplineSceneNode.cpp * \author Hong Son Ngo * \date 2021/05/05 * \brief Scene node of an object that moves along a Catmull-Rom spline * * Modification of a scene node for drawing a moving object * */ //---------------------------------------------------------------------------------------- #include "../include/CSplineSceneNode.h" #include "../include/CGameState.h" CSplineSceneNode::CSplineSceneNode(const CShaderProgram& program, const CCatmulRomSpline& spline, const float& slow) :CSceneNode(program), MSpline(spline), MSlow(slow) { // initial position glm::vec3 point = MSpline.GetSplineLoopPoint(MTime); glm::vec3 gradient = MSpline.GetSplineLoopGradient(MTime); SetPosition(point); SetDirection(glm::normalize(gradient)); } void CSplineSceneNode::Update(const float& deltaTime) { if (MTimeSet && MTime > MTimeToLive) { MTimeSet = false; MTimeToLive = 0.0f; SetOn(false); } MTime += deltaTime / MSlow; for (const auto& node : MSceneNodes) node->Update(deltaTime); // Move and rotate the object if (MTime >= (float) MSpline.GetControlPointSize()) MTime -= MSpline.GetControlPointSize(); glm::vec3 point = MSpline.GetSplineLoopPoint(MTime); glm::vec3 gradient = MSpline.GetSplineLoopGradient(MTime); SetPosition(glm::vec3(point.x, point.y, point.z)); SetDirection(glm::normalize(glm::vec3(gradient.x, 0.0f, gradient.z))); }
34.106383
117
0.587648
ngohongs
52c3ef9484a6c8ff8b5ad0b8fb7ce52aa659cfb6
386
cpp
C++
Lecture-6/Code/OpenHashing_Lookup.cpp
TobiOnline/AlgoDat
565a9f03a9ed7ef354cb4f143959df77df89b726
[ "MIT" ]
17
2016-12-16T17:42:34.000Z
2020-08-26T11:07:16.000Z
Lecture-6/Code/OpenHashing_Lookup.cpp
TobiOnline/AlgoDat
565a9f03a9ed7ef354cb4f143959df77df89b726
[ "MIT" ]
23
2016-10-08T09:27:41.000Z
2019-10-20T15:40:10.000Z
Lecture-6/Code/OpenHashing_Lookup.cpp
TobiOnline/AlgoDat
565a9f03a9ed7ef354cb4f143959df77df89b726
[ "MIT" ]
8
2016-10-07T11:55:23.000Z
2021-04-05T08:36:38.000Z
T lookup(int s) { int j = 0; while (@{\color{cpp_static}t}@[(h(s) - g(s,j)) % @{\color{cpp_static}m}@]) { if (@{\color{cpp_static}t}@[(h(s) - g(s,j)) % @{\color{cpp_static}m}@].@{\color{cpp_static}key}@ == s) return @{\color{cpp_static}t}@[(h(s) - g(s,j)) % @{\color{cpp_static}m}@].@{\color{cpp_static}value}@ j++; } // end while return nullptr; }
29.692308
108
0.520725
TobiOnline
52cb71b4d2caeba832866b83be18279db8df6a62
8,170
cc
C++
test/libponyc/codegen_identity.cc
EvanHahn/ponyc
e081a64b2aa506964d32841bb646c1ca3f8f1e84
[ "BSD-2-Clause" ]
1
2021-04-19T22:56:20.000Z
2021-04-19T22:56:20.000Z
test/libponyc/codegen_identity.cc
EvanHahn/ponyc
e081a64b2aa506964d32841bb646c1ca3f8f1e84
[ "BSD-2-Clause" ]
null
null
null
test/libponyc/codegen_identity.cc
EvanHahn/ponyc
e081a64b2aa506964d32841bb646c1ca3f8f1e84
[ "BSD-2-Clause" ]
null
null
null
#include <gtest/gtest.h> #include <platform.h> #include "util.h" #define TEST_COMPILE(src) DO(test_compile(src, "ir")) class CodegenIdentityTest : public PassTest {}; extern "C" { EXPORT_SYMBOL uintptr_t ptr_to_int(void* p) { return (uintptr_t)p; } } TEST_F(CodegenIdentityTest, ObjectIsObject) { const char* src = "use @pony_exitcode[None](code: I32)\n" "class C1\n" "class C2\n" "actor Main\n" " new create(env: Env) =>\n" " let c1: Any = C1\n" " let c2: Any = C2\n" " if (c1 is c1) and (c1 isnt c2) then\n" " @pony_exitcode(I32(1))\n" " end"; TEST_COMPILE(src); int exit_code = 0; ASSERT_TRUE(run_program(&exit_code)); ASSERT_EQ(exit_code, 1); } TEST_F(CodegenIdentityTest, NumericIsNumeric) { const char* src = "use @pony_exitcode[None](code: I32)\n" "actor Main\n" " new create(env: Env) =>\n" " if (U32(0) is U32(0)) and (U32(0) isnt U32(1)) and\n" " (U32(0) isnt U64(0))\n" " then\n" " @pony_exitcode(I32(1))\n" " end"; TEST_COMPILE(src); int exit_code = 0; ASSERT_TRUE(run_program(&exit_code)); ASSERT_EQ(exit_code, 1); } TEST_F(CodegenIdentityTest, TupleIsTuple) { const char* src = "use @pony_exitcode[None](code: I32)\n" "actor Main\n" " new create(env: Env) =>\n" " let a: (Any, Any) = (U32(0), env)\n" " let b: (Any, Any) = (U32(1), this)\n" " if (a is a) and (a isnt b) then\n" " @pony_exitcode(I32(1))\n" " end"; TEST_COMPILE(src); int exit_code = 0; ASSERT_TRUE(run_program(&exit_code)); ASSERT_EQ(exit_code, 1); } TEST_F(CodegenIdentityTest, NumericIsBoxedNumeric) { const char* src = "use @pony_exitcode[None](code: I32)\n" "actor Main\n" " new create(env: Env) =>\n" " let boxed: (Any | (U32, U32)) = U32(0)\n" " if (U32(0) is boxed) and (U32(1) isnt boxed) and\n" " (U64(0) isnt boxed)\n" " then\n" " @pony_exitcode(I32(1))\n" " end"; TEST_COMPILE(src); int exit_code = 0; ASSERT_TRUE(run_program(&exit_code)); ASSERT_EQ(exit_code, 1); } TEST_F(CodegenIdentityTest, BoxedNumericIsBoxedNumeric) { const char* src = "use @pony_exitcode[None](code: I32)\n" "actor Main\n" " new create(env: Env) =>\n" " let u32_0_a: (Any | (U32, U32)) = U32(0)\n" " let u32_0_b: (Any | (U32, U32)) = U32(0)\n" " let u32_1: (Any | (U32, U32)) = U32(1)\n" " let u64_0: (Any | (U32, U32)) = U64(0)\n" " if (u32_0_a is u32_0_a) and (u32_0_a is u32_0_b) and\n" " (u32_0_a isnt u32_1) and (u32_0_a isnt u64_0)\n" " then\n" " @pony_exitcode(I32(1))\n" " end"; TEST_COMPILE(src); int exit_code = 0; ASSERT_TRUE(run_program(&exit_code)); ASSERT_EQ(exit_code, 1); } TEST_F(CodegenIdentityTest, TupleIsBoxedTuple) { const char* src = "use @pony_exitcode[None](code: I32)\n" "actor Main\n" " new create(env: Env) =>\n" " let boxed: (Any | (U32, U32) | (U64, U64)) = (U32(0), U32(0))\n" " if ((U32(0), U32(0)) is boxed) and ((U32(1), U32(0)) isnt boxed) and\n" " ((U64(0), U64(0)) isnt boxed)\n" " then\n" " @pony_exitcode(I32(1))\n" " end"; TEST_COMPILE(src); int exit_code = 0; ASSERT_TRUE(run_program(&exit_code)); ASSERT_EQ(exit_code, 1); } TEST_F(CodegenIdentityTest, BoxedTupleIsBoxedTuple) { const char* src = "use @pony_exitcode[None](code: I32)\n" "actor Main\n" " new create(env: Env) =>\n" " let t1_a: (Any | (U32, U32) | (U64, U64)) = (U32(0), U32(0))\n" " let t1_b: (Any | (U32, U32) | (U64, U64)) = (U32(0), U32(0))\n" " let t2: (Any | (U32, U32) | (U64, U64)) = (U32(1), U32(0))\n" " let t3: (Any | (U32, U32) | (U64, U64)) = (U64(0), U64(0))\n" " if (t1_a is t1_a) and (t1_a is t1_b) and (t1_a isnt t2) and\n" " (t1_a isnt t3)\n" " then\n" " @pony_exitcode(I32(1))\n" " end"; TEST_COMPILE(src); int exit_code = 0; ASSERT_TRUE(run_program(&exit_code)); ASSERT_EQ(exit_code, 1); } TEST_F(CodegenIdentityTest, TupleCardinality) { const char* src = "use @pony_exitcode[None](code: I32)\n" "actor Main\n" " new create(env: Env) =>\n" " if (env, this, this) isnt (env, this) then\n" " @pony_exitcode(I32(1))\n" " end"; TEST_COMPILE(src); int exit_code = 0; ASSERT_TRUE(run_program(&exit_code)); ASSERT_EQ(exit_code, 1); } TEST_F(CodegenIdentityTest, AbstractTypeNoSubtyping) { const char* src = "use @pony_exitcode[None](code: I32)\n" "actor Main\n" " new create(env: Env) =>\n" " let a: (Env | None) = None\n" " let b: (Main | None) = None\n" " if a is b then\n" " @pony_exitcode(I32(1))\n" " end"; TEST_COMPILE(src); int exit_code = 0; ASSERT_TRUE(run_program(&exit_code)); ASSERT_EQ(exit_code, 1); } TEST_F(CodegenIdentityTest, NestedTuple) { const char* src = "use @pony_exitcode[None](code: I32)\n" "actor Main\n" " new create(env: Env) =>\n" " let a: (((U8, U16) | None, U8) | None) = None\n" " let b: (((U8, U16) | None, U8) | None) = None\n" " if a is b then\n" " @pony_exitcode(I32(1))\n" " end"; TEST_COMPILE(src); int exit_code = 0; ASSERT_TRUE(run_program(&exit_code)); ASSERT_EQ(exit_code, 1); } TEST_F(CodegenIdentityTest, TupleDifferentTypes) { const char* src = "use @pony_exitcode[None](code: I32)\n" "actor Main\n" " new create(env: Env) =>\n" " let a: ((Any, U8) | None) = (U8(0), 0)\n" " let b: ((U8, U8) | None) = (0, 0)\n" " if a is b then \n" " @pony_exitcode(I32(1))\n" " end"; TEST_COMPILE(src); int exit_code = 0; ASSERT_TRUE(run_program(&exit_code)); ASSERT_EQ(exit_code, 1); } TEST_F(CodegenIdentityTest, DigestofObject) { const char* src = "use @ptr_to_int[USize](env: Env)\n" "use @pony_exitcode[None](code: I32)\n" "actor Main\n" " new create(env: Env) =>\n" " let dg = digestof env\n" " if dg == @ptr_to_int(env) then\n" " @pony_exitcode(I32(1))\n" " end"; TEST_COMPILE(src); int exit_code = 0; ASSERT_TRUE(run_program(&exit_code)); ASSERT_EQ(exit_code, 1); } TEST_F(CodegenIdentityTest, DigestofNumeric) { const char* src = "use @pony_exitcode[None](code: I32)\n" "actor Main\n" " new create(env: Env) =>\n" " let value = U32(5)\n" " let dg = digestof value\n" " if dg == 5 then\n" " @pony_exitcode(I32(1))\n" " end"; TEST_COMPILE(src); int exit_code = 0; ASSERT_TRUE(run_program(&exit_code)); ASSERT_EQ(exit_code, 1); } TEST_F(CodegenIdentityTest, DigestofTuple) { const char* src = "use @pony_exitcode[None](code: I32)\n" "actor Main\n" " new create(env: Env) =>\n" " let value = (this, env)\n" " let dg = digestof value\n" " if dg == ((digestof this) xor (digestof env)) then\n" " @pony_exitcode(I32(1))\n" " end"; TEST_COMPILE(src); int exit_code = 0; ASSERT_TRUE(run_program(&exit_code)); ASSERT_EQ(exit_code, 1); } TEST_F(CodegenIdentityTest, DigestofBoxedNumeric) { const char* src = "use @pony_exitcode[None](code: I32)\n" "actor Main\n" " new create(env: Env) =>\n" " let boxed: (Any | (U32, U32)) = U32(5)\n" " let dg = digestof boxed\n" " if dg == 5 then\n" " @pony_exitcode(I32(1))\n" " end"; TEST_COMPILE(src); int exit_code = 0; ASSERT_TRUE(run_program(&exit_code)); ASSERT_EQ(exit_code, 1); } TEST_F(CodegenIdentityTest, DigestofBoxedTuple) { const char* src = "use @pony_exitcode[None](code: I32)\n" "actor Main\n" " new create(env: Env) =>\n" " let boxed: (Any | (Main, Env)) = (this, env)\n" " let dg = digestof boxed\n" " if dg == ((digestof this) xor (digestof env)) then\n" " @pony_exitcode(I32(1))\n" " end"; TEST_COMPILE(src); int exit_code = 0; ASSERT_TRUE(run_program(&exit_code)); ASSERT_EQ(exit_code, 1); }
23.144476
80
0.572093
EvanHahn
52cd664783f2002408f0b8d6caea2520c03a1f1c
13,299
cpp
C++
source/common/application.cpp
Abdelrahman-Shahda/Graphics-Project
3d86a24d34c871a20ae2d09ad3a41a6d3621a073
[ "MIT" ]
null
null
null
source/common/application.cpp
Abdelrahman-Shahda/Graphics-Project
3d86a24d34c871a20ae2d09ad3a41a6d3621a073
[ "MIT" ]
null
null
null
source/common/application.cpp
Abdelrahman-Shahda/Graphics-Project
3d86a24d34c871a20ae2d09ad3a41a6d3621a073
[ "MIT" ]
null
null
null
#include "application.hpp" #include <sstream> #include <iostream> #include <string> #include <iomanip> #include <ctime> // Include the Dear ImGui implementation headers #define IMGUI_IMPL_OPENGL_LOADER_GLAD2 #include <imgui_impl/imgui_impl_glfw.h> #include <imgui_impl/imgui_impl_opengl3.h> #if !defined(NDEBUG) // If NDEBUG (no debug) is not defined, enable OpenGL debug messages #define ENABLE_OPENGL_DEBUG_MESSAGES #endif #include "texture/screenshot.h" // This function will be used to log errors thrown by GLFW void glfw_error_callback(int error, const char* description){ std::cerr << "GLFW Error: " << error << ": " << description << std::endl; } // This function will be used to log OpenGL debug messages void GLAPIENTRY opengl_callback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam) { std::string _source; std::string _type; std::string _severity; // What is the source of the message switch (source) { case GL_DEBUG_SOURCE_API: _source = "API"; break; case GL_DEBUG_SOURCE_WINDOW_SYSTEM: _source = "WINDOW SYSTEM"; break; case GL_DEBUG_SOURCE_SHADER_COMPILER: _source = "SHADER COMPILER"; break; case GL_DEBUG_SOURCE_THIRD_PARTY: _source = "THIRD PARTY"; break; case GL_DEBUG_SOURCE_APPLICATION: _source = "APPLICATION"; break; case GL_DEBUG_SOURCE_OTHER: default: _source = "UNKNOWN"; break; } // What is the type of the message (error, warning, etc). switch (type) { case GL_DEBUG_TYPE_ERROR: _type = "ERROR"; break; case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: _type = "DEPRECATED BEHAVIOR"; break; case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: _type = "UDEFINED BEHAVIOR"; break; case GL_DEBUG_TYPE_PORTABILITY: _type = "PORTABILITY"; break; case GL_DEBUG_TYPE_PERFORMANCE: _type = "PERFORMANCE"; break; case GL_DEBUG_TYPE_OTHER: _type = "OTHER"; break; case GL_DEBUG_TYPE_MARKER: _type = "MARKER"; break; default: _type = "UNKNOWN"; break; } // How severe is the message switch (severity) { case GL_DEBUG_SEVERITY_HIGH: _severity = "HIGH"; break; case GL_DEBUG_SEVERITY_MEDIUM: _severity = "MEDIUM"; break; case GL_DEBUG_SEVERITY_LOW: _severity = "LOW"; break; case GL_DEBUG_SEVERITY_NOTIFICATION: _severity = "NOTIFICATION"; break; default: _severity = "UNKNOWN"; break; } std::cout << "OpenGL Debug Message " << id << " (type: " << _type << ") of " << _severity << " raised from " << _source << ": " << message << std::endl; } void GraphicsProject::Application::configureOpenGL() { // Request that OpenGL is 3.3 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // Only enable core functionalities (disable features from older OpenGL versions that were removed in 3.3) glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Enable forward compatibility with newer OpenGL versions by removing deprecated functionalities // This is necessary for some platforms glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); //Make window size fixed (User can't resize it) glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); //Set Number of sample used in MSAA (0 = Disabled) glfwWindowHint(GLFW_SAMPLES, 0); //Enable Double Buffering glfwWindowHint(GLFW_DOUBLEBUFFER, GLFW_TRUE); //Set the bit-depths of the frame buffer glfwWindowHint(GLFW_RED_BITS, 8); glfwWindowHint(GLFW_GREEN_BITS, 8); glfwWindowHint(GLFW_BLUE_BITS, 8); glfwWindowHint(GLFW_ALPHA_BITS, 8); //Set Bits for Depth Buffer glfwWindowHint(GLFW_DEPTH_BITS, 24); //Set Bits for Stencil Buffer glfwWindowHint(GLFW_STENCIL_BITS, 8); //Set the refresh rate of the window (GLFW_DONT_CARE = Run as fast as possible) glfwWindowHint(GLFW_REFRESH_RATE, GLFW_DONT_CARE); } GraphicsProject::WindowConfiguration GraphicsProject::Application::getWindowConfiguration() { return {"OpenGL Application", {1280, 720}, false }; } // This is the main class function that run the whole application (Initialize, Game loop, House cleaning). int GraphicsProject::Application::run() { // Set the function to call when an error occurs. glfwSetErrorCallback(glfw_error_callback); // Initialize GLFW and exit if it failed if(!glfwInit()){ std::cerr << "Failed to Initialize GLFW" << std::endl; return -1; } configureOpenGL(); // This function sets OpenGL window hints. auto win_config = getWindowConfiguration(); // Returns the WindowConfiguration current struct instance. // Create a window with the given "WindowConfiguration" attributes. // If it should be fullscreen, monitor should point to one of the monitors (e.g. primary monitor), otherwise it should be null GLFWmonitor* monitor = win_config.isFullscreen ? glfwGetPrimaryMonitor() : nullptr; // The last parameter "share" can be used to share the resources (OpenGL objects) between multiple windows. window = glfwCreateWindow(win_config.size.x, win_config.size.y, win_config.title, monitor, nullptr); if(!window) { std::cerr << "Failed to Create Window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); // Tell GLFW to make the context of our window the main context on the current thread. gladLoadGL(glfwGetProcAddress); // Load the OpenGL functions from the driver // Print information about the OpenGL context std::cout << "VENDOR : " << glGetString(GL_VENDOR) << std::endl; std::cout << "RENDERER : " << glGetString(GL_RENDERER) << std::endl; std::cout << "VERSION : " << glGetString(GL_VERSION) << std::endl; std::cout << "GLSL VERSION : " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl; #if defined(ENABLE_OPENGL_DEBUG_MESSAGES) // if we have OpenGL debug messages enabled, set the message callback glDebugMessageCallback(opengl_callback, nullptr); // Then enable debug output glEnable(GL_DEBUG_OUTPUT); // Then make the output synchronized to the OpenGL commands. // This will make sure that OpenGL and the main thread are synchronized such that message callback is called as soon // as the command causing it is called. This is useful for debugging but slows down the code execution. glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); #endif setupCallbacks(); keyboard.enable(window); mouse.enable(window); // Start the ImGui context and set dark style (just my preference :D) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); ImGui::StyleColorsDark(); // Initialize ImGui for GLFW and OpenGL ImGui_ImplGlfw_InitForOpenGL(window, true); ImGui_ImplOpenGL3_Init("#version 330 core"); // Call onInitialize if the application needs to do some custom initialization (such as file loading, object creation, etc). onInitialize(); // The time at which the last frame started. But there was no frames yet, so we'll just pick the current time. double last_frame_time = glfwGetTime(); while(!glfwWindowShouldClose(window)){ glfwPollEvents(); // Read all the user events and call relevant callbacks. // Start a new ImGui frame ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); onImmediateGui(io); // Call to run any required Immediate GUI. // If ImGui is using the mouse or keyboard, then we don't want the captured events to affect our keyboard and mouse objects. // For example, if you're focusing on an input and writing "W", the keyboard object shouldn't record this event. keyboard.setEnabled(!io.WantCaptureKeyboard, window); mouse.setEnabled(!io.WantCaptureMouse, window); // Render the ImGui commands we called (this doesn't actually draw to the screen yet. ImGui::Render(); // Just in case ImGui changed the OpenGL viewport (the portion of the window to which we render the geometry), // we set it back to cover the whole window auto frame_buffer_size = getFrameBufferSize(); glViewport(0, 0, frame_buffer_size.x, frame_buffer_size.y); // Get the current time (the time at which we are starting the current frame). double current_frame_time = glfwGetTime(); // Call onDraw, in which we will draw the current frame, and send to it the time difference between the last and current frame onDraw(current_frame_time - last_frame_time); last_frame_time = current_frame_time; // Then update the last frame start time (this frame is now the last frame) #if defined(ENABLE_OPENGL_DEBUG_MESSAGES) // Since ImGui causes many messages to be thrown, we are temporarily disabling the debug messages till we render the ImGui glDisable(GL_DEBUG_OUTPUT); glDisable(GL_DEBUG_OUTPUT_SYNCHRONOUS); #endif ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); // Render the ImGui to the framebuffer #if defined(ENABLE_OPENGL_DEBUG_MESSAGES) // Re-enable the debug messages glEnable(GL_DEBUG_OUTPUT); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); #endif // If F12 is pressed, take a screenshot if(keyboard.justPressed(GLFW_KEY_F12)){ glViewport(0, 0, frame_buffer_size.x, frame_buffer_size.y); std::stringstream stream; auto time = std::time(nullptr); auto localtime = std::localtime(&time); stream << "screenshots/screenshot-" << std::put_time(localtime, "%Y-%m-%d-%H-%M-%S") << ".png"; if(GraphicsProject::screenshot_png(stream.str())){ std::cout << "Screenshot saved to: " << stream.str() << std::endl; } else { std::cerr << "Failed to save a Screenshot" << std::endl; } } //Close program if escape key is pressed if (keyboard.justPressed(GLFW_KEY_ESCAPE)) break; // Swap the frame buffers glfwSwapBuffers(window); // Update the keyboard and mouse data keyboard.update(); mouse.update(); } // Call for cleaning up onDestroy(); // Shutdown ImGui & destroy the context ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); // Destroy the window glfwDestroyWindow(window); // And finally terminate GLFW glfwTerminate(); return 0; // Good bye } // Sets-up the window callback functions from GLFW to our (Mouse/Keyboard) classes. void GraphicsProject::Application::setupCallbacks() { // We use GLFW to store a pointer to "this" window instance. glfwSetWindowUserPointer(window, this); // The pointer is then retrieved in the callback function. // The second parameter to "glfwSet---Callback" is a function pointer. // It is replaced by an inline function -lambda expression- as it is not needed to create // a seperate function for it. // In the inline function we retrieve the window instance and use it to set our (Mouse/Keyboard) classes values. // Keyboard callbacks glfwSetKeyCallback(window, [](GLFWwindow* window, int key, int scancode, int action, int mods){ auto* app = static_cast<Application*>(glfwGetWindowUserPointer(window)); if(app){ app->getKeyboard().keyEvent(key, scancode, action, mods); app->onKeyEvent(key, scancode, action, mods); } }); // mouse position callbacks glfwSetCursorPosCallback(window, [](GLFWwindow* window, double x_position, double y_position){ auto* app = static_cast<Application*>(glfwGetWindowUserPointer(window)); if(app){ app->getMouse().CursorMoveEvent(x_position, y_position); app->onCursorMoveEvent(x_position, y_position); } }); // mouse position callbacks glfwSetCursorEnterCallback(window, [](GLFWwindow* window, int entered){ auto* app = static_cast<Application*>(glfwGetWindowUserPointer(window)); if(app){ app->onCursorEnterEvent(entered); } }); // mouse button position callbacks glfwSetMouseButtonCallback(window, [](GLFWwindow* window, int button, int action, int mods){ auto* app = static_cast<Application*>(glfwGetWindowUserPointer(window)); if(app){ app->getMouse().MouseButtonEvent(button, action, mods); app->onMouseButtonEvent(button, action, mods); } }); // mouse scroll callbacks glfwSetScrollCallback(window, [](GLFWwindow* window, double x_offset, double y_offset){ auto* app = static_cast<Application*>(glfwGetWindowUserPointer(window)); if(app){ app->getMouse().ScrollEvent(x_offset, y_offset); app->onScrollEvent(x_offset, y_offset); } }); }
39.936937
149
0.67366
Abdelrahman-Shahda
52d0f8f31cae4ba2e77ea436a36c49f554fb99ba
12,665
cpp
C++
src/kirby.cpp
sarietta/kdceditor
52069434e7945bf5651bdd497b78aa08ab168778
[ "MIT" ]
47
2015-03-08T02:34:24.000Z
2022-02-15T00:02:25.000Z
src/kirby.cpp
sarietta/kdceditor
52069434e7945bf5651bdd497b78aa08ab168778
[ "MIT" ]
7
2015-03-11T20:12:31.000Z
2020-05-11T11:58:07.000Z
src/kirby.cpp
sarietta/kdceditor
52069434e7945bf5651bdd497b78aa08ab168778
[ "MIT" ]
8
2015-03-08T13:12:08.000Z
2022-01-10T01:38:25.000Z
/* This code is released under the terms of the MIT license. See COPYING.txt for details. */ #include "kirby.h" #include <QString> const int fgPaletteBase[] = {0xD4A9, 0xD8ED, 0xD8ED}; const int waterBase[][3] = {{0xA444, 0xE030, 0xE030}, {0xA46E, 0xE05A, 0xE05A}}; const int paletteTable[] = {0x80D425, 0x80D869, 0x80D869}; const int waterTable[][3] = {{0x8484AF, 0x8484AF, 0x8484AF}, {0x8484F1, 0x8484F1, 0x8484F1}}; const int backgroundTable[][3] = {{0x80D0AF, 0x80D517, 0x80D517}, {0x80D304, 0x80D748, 0x80D748}, {0x80D324, 0x80D768, 0x80D768}, {0x84CD23, 0x84CD42, 0x84CD42}}; const int musicTable[] = {0x80C533, 0x80C99D, 0x80C99D}; const int newMusicAddr[] = {0x80F440, 0x80F950, 0x80F950}; // first dimension is indexed by game number (0 = kirby, 1 = sts) const char* courseNames[][224 / 8] = { // KDC / Kirby Bowl courses { "1P Course 1", "1P Course 2", "1P Course 3", "1P Course 4", "1P Course 5", "1P Course 6", "1P Course 7", "1P Course 8", "1P Extra Course 1", "1P Extra Course 2", "1P Extra Course 3", "1P Extra Course 4", "1P Extra Course 5", "1P Extra Course 6", "1P Extra Course 7", "1P Extra Course 8", "2P Course 1", "2P Course 2", "2P Course 3", "2P Course 4", "Demo Course 1", "Demo Course 2", "Demo Course 3 / Test Course", "Test Course", "2P Extra Course 1", "2P Extra Course 2", "2P Extra Course 3", "2P Extra Course 4" }, // Special Tee Shot courses { "Beginner Course", "Amateur Course", "Professional Course", "Master Course", "Extra Course 1", "Extra Course 2", "Extra Course 3", "Extra Course 4", "Gold Course" } }; const bg_t bgNames[] = { {"Background 1 (clouds)", {0x8290, 0xC290, 0xC290}, {0x92BEB1, 0x90A836, 0x90A836}, {0x94AC83, 0x928000, 0x92855B}, {0xCD33, 0xCD52, 0xCD52}}, {"Background 2 (stars & moon)", {0x83D0, 0xC3D0, 0xC3D0}, {0x92D18C, 0x90B1B2, 0x90B1B2}, {0x94EDAB, 0x8EFB5F, 0x8EFB5F}, {0xCECA, 0xCEE9, 0xCEE9}}, {"Background 3 (waterfalls)", {0x8330, 0xC330, 0xC330}, {0x93A043, 0x90ED83, 0x90ED83}, {0x94967D, 0x91E7A2, 0x91EE62}, {0xCE79, 0xCE98, 0xCE98}}, {"Background 4 (jigsaw)", {0x82E0, 0xC2E0, 0xC2E0}, {0x93E286, 0x91AD5B, 0x91B41B}, {0x93D5F8, 0x91A0CD, 0x91A78D}, {0xCE64, 0xCE83, 0xCE83}}, {"Background 5 (candy)", {0x8380, 0xC380, 0xC380}, {0x92AB0F, 0x909494, 0x909494}, {0x93FA68, 0x91E20F, 0x91E8CF}, {0xCFAE, 0xCFCD, 0xCFCD}}, {"Background 6 (ocean)", {0x85E0, 0xC5E0, 0xC5E0}, {0x9398A1, 0x90E5E1, 0x90E5E1}, {0x94DA7C, 0x92B347, 0x92B8A2}, {0xCFF3, 0xD012, 0xD012}} /* something here (the GFX?) gets loaded to a different address than normal so it's not usable with the rest of the course BGs {"Background 7 (diamonds)", {0xD368, 0}, {0x93EEC0, 0}, {0x9798EF, 0}, {0xD12D, 0}}, */ }; const char* paletteNames[] = { "Course 1 (blue)", "Course 2 (green)", "Course 3 (purple)", "Course 4 (pink)", "Course 5 (tan)", "Course 6 (beige)", "Course 7 (grey)", "Course 8 (red)", "Extra course 7/8 (dark grey)", "Demo course (teal)" }; const StringMap musicNames ({ {0x7e, "7E: (none)"}, {0x80, "80: Epilogue"}, {0x82, "82: Title"}, {0x83, "83: Opening demo (JP only)"}, {0x84, "84: High scores"}, {0x85, "85: Space Valley (course 2/7b)"}, {0x86, "86: Over Water (course 1b)"}, {0x87, "87: The Tricky Stuff (course 5b)"}, {0x88, "88: Castles of Cake (course 6)"}, {0x89, "89: Green Fields (course 5a/7a)"}, {0x8a, "8A: The First Hole (course 1a/3)"}, {0x8b, "8B: Iceberg Ocean (course 8)"}, {0x8c, "8C: Last Hole"}, {0x8d, "8D: Jigsaw Plains (course 4)"}, {0x8f, "8F: Continue?"}, {0x92, "92: Final score"}, {0x93, "93: 2P course select"}, {0x94, "94: Eyecatch"}, {0x95, "95: Main menu"}, {0x96, "96: 1P course select"}, {0x97, "97: Scorecard"}, {0x9a, "9A: Demo play"}, {0x9b, "9B: Dedede 1"}, {0x9c, "9C: Dedede 2"}, {0x9f, "9F: Game over"} }); const StringMap kirbyGeometry ({ {0, "00: None"}, {1, "01: Flat"}, {2, "02: Four slopes up towards center"}, // this type is unusable // {3, "03: Four slopes down into ground"}, {4, "04: Slope down towards south"}, {5, "05: Slope down towards east"}, {6, "06: Slope down towards north"}, {7, "07: Slope down towards west"}, {8, "08: Slopes down towards south and east (inner)"}, {9, "09: Slopes down towards north and east (inner)"}, {10, "0A: Slopes down towards north and west (inner)"}, {11, "0B: Slopes down towards south and west (inner)"}, {12, "0C: Slopes down towards south and east (outer)"}, {13, "0D: Slopes down towards north and east (outer)"}, {14, "0E: Slopes down towards north and west (outer)"}, {15, "0F: Slopes down towards south and west (outer)"}, {16, "10: Slope down towards southeast (top)"}, {17, "11: Slope down towards northeast (top)"}, {18, "12: Slope down towards northwest (top)"}, {19, "13: Slope down towards southwest (top)"}, {20, "14: Slope down towards southeast (bottom)"}, {21, "15: Slope down towards northeast (bottom)"}, {22, "16: Slope down towards northwest (bottom)"}, {23, "17: Slope down towards southwest (bottom)"}, {24, "18: Slope down towards southeast (middle)"}, {25, "19: Slope down towards northeast (middle)"}, {26, "1A: Slope down towards northwest (middle)"}, {27, "1B: Slope down towards southwest (middle)"} }); const StringMap kirbyObstacles ({ {0x00, "00: None"}, {0x02, "02: Whispy Woods"}, {0x04, "04: Sand trap"}, {0x05, "05: Spike pit"}, /* hole can't be placed independently in KDC (unless it can be placed on obstacle layer w/ correct palette somehow) {0x08, "08: Hole"}, */ {0x0c, "0C: Kirby"}, {0x0d, "0D: King Dedede (course 24-1 only)"}, {0x10, "10: Current (south)"}, {0x11, "11: Current (east)"}, {0x12, "12: Current (north)"}, {0x13, "13: Current (west)"}, {0x14, "14: Arrow (south)"}, {0x15, "15: Arrow (east)"}, {0x16, "16: Arrow (north)"}, {0x17, "17: Arrow (west)"}, {0x18, "18: Booster (south)"}, {0x19, "19: Booster (east)"}, {0x1a, "1A: Booster (north)"}, {0x1b, "1B: Booster (west)"}, {0x1c, "1C: Air vent (north-south)"}, {0x1d, "1D: Air vent (east-west)"}, {0x20, "20: Bounce (use with tile 04)"}, {0x21, "21: Bounce (use with tile 05)"}, {0x22, "22: Bounce (use with tile 06)"}, {0x23, "23: Bounce (use with tile 07)"}, {0x24, "24: Bounce"}, {0x28, "28: Bumper (north to south)"}, {0x29, "29: Bumper (east to west)"}, {0x2a, "2A: Bumper (south to west)"}, {0x2b, "2B: Bumper (north to west)"}, {0x2c, "2C: Bumper (north to east)"}, {0x2d, "2D: Bumper (south to east)"}, {0x30, "30: Conveyor belt (south)"}, {0x31, "31: Conveyor belt (east)"}, {0x32, "32: Conveyor belt (north)"}, {0x33, "33: Conveyor belt (west)"}, {0x34, "34: Conveyor belt (north, use with tile 04)"}, {0x35, "35: Conveyor belt (south, use with tile 04)"}, {0x36, "36: Conveyor belt (west, use with tile 05)"}, {0x37, "37: Conveyor belt (east, use with tile 05)"}, {0x38, "38: Conveyor belt (south, use with tile 06)"}, {0x39, "39: Conveyor belt (north, use with tile 06)"}, {0x3a, "3A: Conveyor belt (east, use with tile 07)"}, {0x3b, "3B: Conveyor belt (west, use with tile 07)"}, {0x40, "40: Waddle Dee"}, {0x41, "41: Rocky"}, {0x42, "42: Waddle Doo"}, {0x43, "43: Flamer"}, {0x44, "44: Spiney"}, {0x45, "45: Twister"}, {0x46, "46: Wheelie"}, {0x47, "47: Sparky"}, {0x48, "48: Starman"}, {0x49, "49: Chilly"}, {0x4a, "4A: Broom Hatter"}, {0x4b, "4B: Squishy"}, {0x4c, "4C: Kabu"}, {0x4d, "4D: Gaspar"}, {0x4e, "4E: Pumpkin"}, {0x4f, "4F: UFO"}, {0x50, "50: Gaspar (higher)"}, {0x51, "51: Pumpkin (higher)"}, {0x52, "52: UFO (higher)"}, {0x57, "57: Transformer"}, {0x58, "58: Mr. Bright switch"}, {0x59, "59: Mr. Shine switch"}, {0x5a, "5A: Rotating space switch (off)"}, {0x5b, "5B: Rotating space switch (on)"}, {0x5c, "5C: Water switch (on)"}, {0x5d, "5D: Water switch (off)"}, {0x61, "61: Water hazard"}, {0x64, "64: Water hazard (use with tile 04)"}, {0x65, "65: Water hazard (use with tile 05)"}, {0x66, "66: Water hazard (use with tile 06)"}, {0x67, "67: Water hazard (use with tile 07)"}, {0x68, "68: Water hazard (use with tile 08)"}, {0x69, "69: Water hazard (use with tile 09)"}, {0x6a, "6A: Water hazard (use with tile 0A)"}, {0x6b, "6B: Water hazard (use with tile 0B)"}, {0x6c, "6C: Water hazard (use with tile 0C)"}, {0x6d, "6D: Water hazard (use with tile 0D)"}, {0x6e, "6E: Water hazard (use with tile 0E)"}, {0x6f, "6F: Water hazard (use with tile 0F)"}, /* Most of these are not used in KDC. */ {0x70, "70: Rotating space (clockwise, always on)"}, {0x71, "71: Rotating space (counterclockwise, always on)"}, {0x72, "72: Rotating space (clockwise, always on, slow)"}, {0x73, "73: Rotating space (counterclockwise, always on, slow)"}, {0x74, "74: Rotating space (clockwise, switch)"}, {0x75, "75: Rotating space (counterclockwise, switch)"}, {0x76, "76: Rotating space (clockwise, switch, slow)"}, {0x77, "77: Rotating space (counterclockwise, switch, slow)"}, {0x78, "78: Rotating space (clockwise, switch-opposite)"}, {0x79, "79: Rotating space (counterclockwise, switch-opposite)"}, {0x7a, "7A: Rotating space (clockwise, switch-opposite, slow)"}, {0x7b, "7B: Rotating space (counterclockwise, switch-opposite, slow)"}, {0x80, "80: Gordo (moves south, faces south)"}, {0x81, "81: Gordo (moves east, faces south)"}, {0x82, "82: Gordo (moves north, faces south)"}, {0x83, "83: Gordo (moves west, faces south)"}, {0x84, "84: Gordo (moves south, faces east)"}, {0x85, "85: Gordo (moves east, faces east)"}, {0x86, "86: Gordo (moves north, faces east)"}, {0x87, "87: Gordo (moves west, faces east)"}, {0x88, "88: Gordo (moves south, faces north)"}, {0x89, "89: Gordo (moves east, faces north)"}, {0x8a, "8A: Gordo (moves north, faces north)"}, {0x8b, "8B: Gordo (moves west, faces north)"}, {0x8c, "8C: Gordo (moves south, faces west)"}, {0x8d, "8D: Gordo (moves east, faces west)"}, {0x8e, "8E: Gordo (moves north, faces west)"}, {0x8f, "8F: Gordo (moves west, faces west)"}, {0x90, "90: Gordo (moves up/down, faces south)"}, {0x91, "91: Gordo (moves up/down, faces east)"}, {0x92, "92: Gordo (moves up/down, faces north)"}, {0x93, "93: Gordo (moves up/down, faces west)"}, {0x94, "94: Gordo (moves down/up, faces south)"}, {0x95, "95: Gordo (moves down/up, faces east)"}, {0x96, "96: Gordo (moves down/up, faces north)"}, {0x97, "97: Gordo (moves down/up, faces west)"}, {0x98, "98: Gordo path (north-south)"}, {0x99, "99: Gordo path (east-west)"}, {0x9a, "9A: Gordo path (northwest corner)"}, {0x9b, "9B: Gordo path (southwest corner)"}, {0x9c, "9C: Gordo path (southeast corner)"}, {0x9d, "9D: Gordo path (northeast corner)"}, {0x9e, "9E: Gordo endpoint (south)"}, {0x9f, "9F: Gordo endpoint (east)"}, {0xa0, "A0: Gordo endpoint (north)"}, {0xa1, "A1: Gordo endpoint (west)"}, {0xac, "AC: Kracko (no lightning)"}, {0xad, "AD: Kracko (lightning 1)"}, {0xae, "AE: Kracko (lightning 2)"}, {0xb0, "B0: Blue warp 1 (south)"}, {0xb1, "B1: Blue warp 1 (east)"}, {0xb2, "B2: Blue warp 1 (north)"}, {0xb3, "B3: Blue warp 1 (west)"}, {0xb4, "B4: Blue warp 2 (south)"}, {0xb5, "B5: Blue warp 2 (east)"}, {0xb6, "B6: Blue warp 2 (north)"}, {0xb7, "B7: Blue warp 2 (west)"}, {0xb8, "B8: Red warp 1"}, {0xb9, "B9: Red warp 2"}, {0xc0, "C0: Starting line (west end)"}, {0xc1, "C1: Starting line"}, {0xc2, "C2: Starting line (east end)"}, {0xc3, "C3: Kirby (course 24-1 only)"}, });
33.773333
78
0.563364
sarietta
52d14d9fa182e34f6014bd6ec6196a7f1acf16f4
10,301
cpp
C++
src/dev/btietz/multiTerrain_OC/OctahedralComplex.cpp
wvat/NTRTsim
0443cbd542e12e23c04adf79ea0d8d003c428baa
[ "Apache-2.0" ]
148
2015-01-08T22:44:00.000Z
2022-03-19T18:42:48.000Z
src/dev/btietz/multiTerrain_OC/OctahedralComplex.cpp
wvat/NTRTsim
0443cbd542e12e23c04adf79ea0d8d003c428baa
[ "Apache-2.0" ]
107
2015-01-02T16:41:42.000Z
2021-06-14T22:09:19.000Z
src/dev/btietz/multiTerrain_OC/OctahedralComplex.cpp
wvat/NTRTsim
0443cbd542e12e23c04adf79ea0d8d003c428baa
[ "Apache-2.0" ]
86
2015-01-06T07:02:36.000Z
2022-02-28T17:36:14.000Z
/* * Copyright © 2012, United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * All rights reserved. * * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is licensed * under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ /** * @file OctahedralComplex.cpp * @brief Implementing the cross-linked octahedral complex spine inspired by Tom Flemons * @author Brian Tietz * @date May 2014 * @version 1.0.0 * $Id$ */ #include "OctahedralComplex.h" // This library #include "core/tgCast.h" #include "core/tgSpringCableActuator.h" #include "core/tgString.h" #include "core/tgBox.h" #include "tgcreator/tgBoxInfo.h" #include "tgcreator/tgBuildSpec.h" #include "tgcreator/tgBasicActuatorInfo.h" #include "tgcreator/tgBasicContactCableInfo.h" #include "tgcreator/tgKinematicContactCableInfo.h" #include "tgcreator/tgRodInfo.h" #include "tgcreator/tgStructure.h" #include "tgcreator/tgStructureInfo.h" #include "tgcreator/tgUtil.h" #include "LinearMath/btVector3.h" #include <iostream> #include <algorithm> // std::fill #include <map> #include <set> OctahedralComplex::OctahedralComplex(int segments, double goalAngle, double startAngle) : BaseSpineModelGoal(segments, goalAngle), m_startAngle(startAngle) { } OctahedralComplex::~OctahedralComplex() { } void OctahedralComplex::setup(tgWorld& world) { // This is basically a manual setup of a model. There are things that do this for us (@todo: reference the things that do this for us) // Rod and Muscle configuration const double density = 4.2/300.0; // Note: This needs to be high enough or things fly apart... const double radius = 0.5; const double friction = 0.5; const double rollFriction = 0.0; const double restitution = 0.0; const tgRod::Config rodConfig(radius, density, friction, rollFriction, restitution); const double elasticity = 1000.0; const double damping = 10.0; const double pretension = 0.0; const bool history = false; const double maxTens = 7000.0; const double maxSpeed = 24.0; const double mRad = 1.0; const double motorFriction = 10.0; const double motorInertia = 1.0; const bool backDrivable = false; tgKinematicActuator::Config motorConfig(elasticity, damping, pretension, mRad, motorFriction, motorInertia, backDrivable, history, maxTens, maxSpeed); /// @todo acceleration constraint was removed on 12/10/14 Replace with tgKinematicActuator as appropreate #if (0) const tgSpringCableActuator::Config stringConfig(stiffness, damping, pretension, false, 7000, 24); #endif const double passivePretension = 700; // 5 N tgKinematicActuator::Config muscleConfig(2000, 20, passivePretension, mRad, motorFriction, motorInertia, backDrivable, history, maxTens, maxSpeed); // Calculations for the flemons spine model double v_size = 10.0; // Create the tetrahedra tgStructure tetra; tetra.addNode(0,0,0); // center tetra.addNode(0.0, v_size, 0.0); // Top tetra.addNode(0.0, -v_size, 0.0); // Bottom tetra.addNode(0.0, 0.0, v_size); // front tetra.addNode(0.0, 0.0, -v_size); // back tetra.addNode(v_size, 0.0, 0.0); // right tetra.addNode(-v_size, 0.0, 0.0); // left tetra.addPair(0,1, "top rod"); tetra.addPair(0,2, "bottom rod"); tetra.addPair(0,3, "front rod"); tetra.addPair(0,4, "back rod"); tetra.addPair(0,5, "right rod"); tetra.addPair(0,6, "left rod"); // Create our snake segments tgStructure snake; const double offsetDist = -v_size *1.25; btVector3 offset(0,0,offsetDist); // @todo: there seems to be an issue with Muscle2P connections if the front of a tetra is inside the next one. for(std::size_t i = 0; i < m_segments; i++) { // @todo: the snake is a temporary variable -- will its destructor be called? If not, where do we delete its children? tgStructure* t = new tgStructure(tetra); t->addTags(tgString("segment num", i + 1)); t->move((i + 1)*offset); if (i % 2 == 1) { t->addRotation(btVector3(0.0, 0.0, (i + 1) * offsetDist), btVector3(1, 0, 0), M_PI/4.0); } else { t->addRotation(btVector3(0.0, 0.0, (i + 1) * offsetDist), btVector3(0, 1, 0), -M_PI/4.0); } //t->addRotation(btVector3(0.0, 0.0, (i + 1) * offsetDist), btVector3(0, 0, 1), M_PI/4.0); snake.addChild(t); // Add a child to the snake } // Move the snake at the end, up to you. snake.addRotation(btVector3(0.0, 0.0, 0.0), btVector3(0, 0, 1), M_PI/4.0); snake.move(btVector3(0.0,15.0,100.0)); //conditionally compile for debugging #if (1) // Add muscles that connect the segments // Tag the muscles with their segment numbers so CPGs can find // them. std::vector<tgStructure*> children = snake.getChildren(); for(std::size_t i = 1; i < children.size(); i++) { tgNodes n0 = children[i-1]->getNodes(); tgNodes n1 = children[i]->getNodes(); if (i % 2 == 0 ) { snake.addPair(n0[2], n1[3], tgString("inner front muscle seg", i-1) + tgString(" seg", i)); snake.addPair(n0[4], n1[3], tgString("inner right muscle seg", i-1) + tgString(" seg", i)); snake.addPair(n0[2], n1[5], tgString("inner left muscle seg", i-1) + tgString(" seg", i)); snake.addPair(n0[4], n1[5], tgString("inner back muscle seg", i-1) + tgString(" seg", i)); #if (1) // Traditional interior crosslink snake.addPair(n0[5], n1[3], tgString("inner left muscle2 seg", i-1) + tgString(" seg", i)); snake.addPair(n0[6], n1[5], tgString("inner back muscle2 seg", i-1) + tgString(" seg", i)); snake.addPair(n0[2], n1[1], tgString("inner left muscle2 seg", i-1) + tgString(" seg", i)); snake.addPair(n0[4], n1[2], tgString("inner back muscle2 seg", i-1) + tgString(" seg", i)); #else snake.addPair(n0[5], n1[5], tgString("inner left muscle2 seg", i-1) + tgString(" seg", i)); snake.addPair(n0[6], n1[3], tgString("inner back muscle2 seg", i-1) + tgString(" seg", i)); snake.addPair(n0[4], n1[1], tgString("inner left muscle2 seg", i-1) + tgString(" seg", i)); snake.addPair(n0[2], n1[2], tgString("inner back muscle2 seg", i-1) + tgString(" seg", i)); #endif } else { snake.addPair(n0[6], n1[1], tgString("inner front muscle seg", i-1) + tgString(" seg", i)); snake.addPair(n0[4], n1[1], tgString("inner right muscle seg", i-1) + tgString(" seg", i)); snake.addPair(n0[6], n1[3], tgString("inner left muscle seg", i-1) + tgString(" seg", i)); snake.addPair(n0[4], n1[3], tgString("inner back muscle seg", i-1) + tgString(" seg", i)); #if (1) snake.addPair(n0[1], n1[3], tgString("inner left muscle2 seg", i-1) + tgString(" seg", i)); snake.addPair(n0[2], n1[1], tgString("inner back muscle2 seg", i-1) + tgString(" seg", i)); snake.addPair(n0[6], n1[5], tgString("inner left muscle2 seg", i-1) + tgString(" seg", i)); snake.addPair(n0[4], n1[6], tgString("inner back muscle2 seg", i-1) + tgString(" seg", i)); #else snake.addPair(n0[4], n1[5], tgString("inner left muscle2 seg", i-1) + tgString(" seg", i)); snake.addPair(n0[2], n1[3], tgString("inner back muscle2 seg", i-1) + tgString(" seg", i)); snake.addPair(n0[1], n1[1], tgString("inner left muscle2 seg", i-1) + tgString(" seg", i)); snake.addPair(n0[6], n1[6], tgString("inner back muscle2 seg", i-1) + tgString(" seg", i)); #endif } } #endif btVector3 fixedPoint(0.0, 0.0, 0.0); btVector3 axis(0.0, 1.0, 0.0); snake.addRotation(fixedPoint, axis, m_startAngle); // Create the build spec that uses tags to turn the structure into a real model tgBuildSpec spec; spec.addBuilder("rod", new tgRodInfo(rodConfig)); #if (1) spec.addBuilder("muscle", new tgKinematicContactCableInfo(muscleConfig)); spec.addBuilder("muscle2", new tgKinematicContactCableInfo(motorConfig)); #else spec.addBuilder("muscle", new tgBasicActuatorInfo(muscleConfig)); spec.addBuilder("muscle2", new tgBasicActuatorInfo(stringConfig)); #endif // Create your structureInfo tgStructureInfo structureInfo(snake, spec); // Use the structureInfo to build ourselves structureInfo.buildInto(*this, world); // Setup vectors for control m_allMuscles = find<tgSpringCableActuator> ("muscle2"); m_saddleMuscles = find<tgSpringCableActuator> ("muscle"); m_allSegments = this->find<tgModel> ("segment"); #if (0) // Debug printing std::cout << "StructureInfo:" << std::endl; std::cout << structureInfo << std::endl; std::cout << "Model: " << std::endl; std::cout << *this << std::endl; #endif children.clear(); // Actually setup the children BaseSpineModelGoal::setup(world); } void OctahedralComplex::teardown() { BaseSpineModelGoal::teardown(); } void OctahedralComplex::step(double dt) { /* CPG update occurs in the controller so that we can decouple it * from the physics update */ BaseSpineModelGoal::step(dt); // Step any children }
38.580524
148
0.616639
wvat
52d51c076b115f9530be3973503725334d1f2e78
428
cpp
C++
Dev Skill/vector.cpp
Sohelr360/my_codes
9bdd28f62d3850aad8f8af2a253ba66138a7057c
[ "MIT" ]
null
null
null
Dev Skill/vector.cpp
Sohelr360/my_codes
9bdd28f62d3850aad8f8af2a253ba66138a7057c
[ "MIT" ]
null
null
null
Dev Skill/vector.cpp
Sohelr360/my_codes
9bdd28f62d3850aad8f8af2a253ba66138a7057c
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> #include <iterator> using namespace std; int main() { vector <int> v; vector <int>:: iterator it; v.push_back(20); v.push_back(2); v.push_back(50); cout<<v.size()<<endl; for(auto x: v) cout<<x<<endl; sort(v.begin(), v.end()); it = v.begin(); for(; it != v.end();it++) cout<<*it<<'\t'; }
17.833333
32
0.509346
Sohelr360
52d52d4e16c888fb5d98300d177d956e25587bfb
3,091
cpp
C++
apps/shared/interval.cpp
VersiraSec/epsilon-cfw
d12b44c6c6668ecc14b60d8dd098ba5c230b1291
[ "FSFAP" ]
1,442
2017-08-28T19:39:45.000Z
2022-03-30T00:56:14.000Z
apps/shared/interval.cpp
VersiraSec/epsilon-cfw
d12b44c6c6668ecc14b60d8dd098ba5c230b1291
[ "FSFAP" ]
1,321
2017-08-28T23:03:10.000Z
2022-03-31T19:32:17.000Z
apps/shared/interval.cpp
VersiraSec/epsilon-cfw
d12b44c6c6668ecc14b60d8dd098ba5c230b1291
[ "FSFAP" ]
421
2017-08-28T22:02:39.000Z
2022-03-28T20:52:21.000Z
#include <assert.h> #include <cmath> #include <poincare/print_float.h> #include "interval.h" #include "poincare_helpers.h" namespace Shared { Interval::Interval() : m_numberOfElements(0) { reset(); } int Interval::numberOfElements() { computeElements(); return m_numberOfElements; } void Interval::deleteElementAtIndex(int index) { assert(!m_needCompute); assert(m_numberOfElements > 0); for (int k = index; k < m_numberOfElements-1; k++) { m_intervalBuffer[k] = m_intervalBuffer[k+1]; } m_numberOfElements--; } bool Interval::hasSameParameters(IntervalParameters parameters) { return (m_parameters.start() == parameters.start() && m_parameters.end() == parameters.end() && m_parameters.step() == parameters.step()); } double Interval::element(int i) { assert(i >= 0 && i < numberOfElements()); computeElements(); return m_intervalBuffer[i]; } void Interval::setElement(int i, double f) { assert(i <= numberOfElements() && i < k_maxNumberOfElements); computeElements(); m_intervalBuffer[i] = f; if (i == numberOfElements()) { m_numberOfElements++; } } void Interval::reset() { m_parameters.setStart(0.0); m_parameters.setEnd(10.0); m_parameters.setStep(1.0); m_needCompute = true; } void Interval::clear() { m_parameters.setStart(1.0); m_parameters.setEnd(0.0); m_parameters.setStep(1.0); m_needCompute = true; } void Interval::computeElements() { if (!m_needCompute) { return; } if (m_parameters.start() > m_parameters.end()) { m_numberOfElements = 0; } else { m_numberOfElements = m_parameters.step() > 0 ? 1 + (m_parameters.end() - m_parameters.start())/m_parameters.step() : k_maxNumberOfElements; m_numberOfElements = m_numberOfElements > k_maxNumberOfElements || m_numberOfElements < 0 ? k_maxNumberOfElements : m_numberOfElements; } /* Even though elements are displayed with 7 significant digits, we round the * element to 14 significant digits to prevent unexpected imprecisions due to * doubles. For example, with start=-0.2 and step=0.2, 6th element is * 1.0000000000000002 although 1.0 was expected. */ constexpr int precision = Poincare::PrintFloat::k_numberOfStoredSignificantDigits; static_assert(precision == 14, "ratioThreshold value should be updated"); // Save some calls to std::pow(10.0, -precision) constexpr double ratioThreshold = 10e-14; bool checkForElementZero = (m_parameters.start() < 0.0); for (int i = 0; i < m_numberOfElements; i += 1) { if (checkForElementZero && i > 0 && std::abs(1.0 + m_parameters.start() / (i * m_parameters.step())) < ratioThreshold) { /* We also round to 0 if start/(i*step) would have been rounded to -1. * For example, with start=-1.2, and step=0.2, 6th element should be 0 * instead of 2.22e-16. */ m_intervalBuffer[i] = 0.0; } else { m_intervalBuffer[i] = PoincareHelpers::ValueOfFloatAsDisplayed<double>(m_parameters.start() + i * m_parameters.step(), precision, nullptr); checkForElementZero &= (m_intervalBuffer[i] < 0.0); } } m_needCompute = false; } }
32.197917
145
0.697509
VersiraSec
52d6d4152980983d93ae0d34dd7adc7b0f081d3e
5,728
cpp
C++
include/eigenvec_centrality.cpp
masatoshihanai/HyInfluenceMin
40b01947e1e1785806582eb6791310aeeee3d7c5
[ "MIT" ]
null
null
null
include/eigenvec_centrality.cpp
masatoshihanai/HyInfluenceMin
40b01947e1e1785806582eb6791310aeeee3d7c5
[ "MIT" ]
null
null
null
include/eigenvec_centrality.cpp
masatoshihanai/HyInfluenceMin
40b01947e1e1785806582eb6791310aeeee3d7c5
[ "MIT" ]
null
null
null
/* * Copyright (c) 2020 Masatoshi Hanai * * This software is released under MIT License. * See LICENSE. * */ #include "hygraph.hpp" #include "external/Eigen/Core" #include "external/Eigen/Dense" #include "external/Eigen/Eigenvalues" #include "wtime.hpp" class EigenVectorCentrality { public: void getTopK(HyGraph& hygraph, HyIDSet& topK, uint64_t k) { #ifdef HAS_OMP Eigen::initParallel(); #endif if (hygraph.numHyEdges() > 500000) { std::cout << "!!! Too big data for Eigen !!! Skip computation " << std::endl; return; } // todo fix to include repeat interval std::string bFileName = hygraph.fName_ + std::to_string(TIME_UNIT_HOUR) + "-eigenvec.bin"; std::vector<std::pair<HyEdgeID, double>> idValuePairs(hygraph.numHyEdges()); std::ifstream ifs(bFileName); if (ifs.is_open()) { std::cout << "Eigen vector exists. Read from file " << std::endl; ifs.read((char*)&idValuePairs[0], (sizeof(HyEdgeID) + sizeof(double) * idValuePairs.size())); ifs.close(); } else { ifs.close(); std::cout << "Build Matrix" << std::endl; Eigen::MatrixXd mmT(hygraph.numHyEdges(), hygraph.numHyEdges()); { Eigen::MatrixXd m(hygraph.numHyEdges(), hygraph.numVert()); for (uint64_t i = 0; i < hygraph.numHyEdges(); ++i) { for (auto v: hygraph.getHyEdge(i).vertices_) { m(i, v) = 1.0; } } auto mT = m.transpose(); mmT = m * mT; } double start = getTime(); uint64_t numItr = 100; Eigen::Vector<double, Eigen::Dynamic> v_prev = Eigen::Vector<double, Eigen::Dynamic>::Random( mmT.cols()).cwiseAbs(); Eigen::Vector<double, Eigen::Dynamic> v = Eigen::Vector<double, Eigen::Dynamic>(mmT.cols()); std::cout << "Start Power Method" << std::endl; for (uint64_t i = 0; i < numItr; ++i) { v.swap(mmT * v_prev); v.normalize(); v_prev.swap(v); std::cout << "\r Iteration " << i << " : " << (getTime() - start) << std::flush; } std::cout << std::endl; for (uint i = 0; i < idValuePairs.size(); ++i) { idValuePairs.at(i).first = i; idValuePairs.at(i).second = v(i); } std::sort(idValuePairs.begin(), idValuePairs.end(), [](std::pair<HyEdgeID, double> &l, std::pair<HyEdgeID, double> &r) { return l.second > r.second; }); double end = getTime(); std::cout << "Execution Time for Eigen Centrality: " << end - start << std::endl; std::cout << "Write result to " << bFileName << std::endl; std::ofstream file; file.open(bFileName, std::ios::out | std::ios::binary); file.write((char*) &idValuePairs[0], (sizeof(HyEdgeID) + sizeof(double))*idValuePairs.size()); file.close(); } for (uint i = 0; i < k; ++i) { // std::cout << "i: " << i << " " << idValuePairs.at(i).first << " " << idValuePairs.at(i).second << std::endl; topK.insert(idValuePairs.at(i).first); } } }; //int main(int argc, char** argv) { // int size = std::atol(argv[1]); // std::cout << "test EigenVector size " << size << std::endl; // //// Eigen::MatrixXd mmt = Eigen::MatrixXd::Random(size,size); // //// /* (12*7) vector */ // Eigen::MatrixXd m = Eigen::MatrixXd(12,7); // m << // 1,1,0,0,1,0,0, // 1,0,0,1,1,0,0, // 0,1,1,0,1,0,0, // 0,0,1,1,1,0,0, // 1,1,0,0,0,1,0, // 1,0,1,0,0,1,0, // 1,0,0,1,0,1,0, // 0,1,0,1,0,1,0, // 1,0,0,1,0,0,1, // 1,0,1,0,0,0,1, // 0,1,0,1,0,0,1, // 0,1,1,0,0,0,1; // // auto mt = m.transpose(); // std::cout << "m is" << std::endl; // std::cout << m << std::endl; // std::cout << std::endl; // // std::cout << "transpose(m) is " << std::endl; // std::cout << mt << std::endl; // std::cout << std::endl; // // std::cout << "m * transpose(m) is " << std::endl; // std::cout << (m*mt) << std::endl; // std::cout << std::endl; // auto mmt = m*mt; // // // Exact method // Eigen::EigenSolver<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>> s(mmt); // auto eval = s.eigenvalues(); // std::cout << "eigen value \n" << eval << std::endl; // std::cout << eval(0) << std::endl; //// for (auto x: eval) { //// std::cout << x << std::endl; //// } // // auto evec = s.eigenvectors(); // std::cout << "eigen vector \n";// << evec << std::endl; // // for (int i = 0; i < 12; ++i) { // std::cout << evec(i,0).real() / evec(0,0).real() << std::endl; // } // // // Power method // clock_t start = clock(); // uint64_t numItr = 100; // // std::cout << "mmt size" << mmt.cols() << std::endl; // Eigen::Vector<double, Eigen::Dynamic> v_prev = Eigen::Vector<double, Eigen::Dynamic>::Random(mmt.cols()).cwiseAbs(); // Eigen::Vector<double, Eigen::Dynamic> v = Eigen::Vector<double, Eigen::Dynamic>(mmt.cols()); // // for (uint64_t i = 0; i < numItr; ++i) { // v.swap(mmt*v_prev); // v.normalize(); // v_prev.swap(v); // } // clock_t end = clock(); // std::cout << "power method's eigen vector \n" << std::endl; // std::cout << v << std::endl; // // std::vector<std::pair<HyEdgeID, double>> idValuePairs(mmt.cols()); // for (uint i = 0; i < idValuePairs.size(); ++i) { // idValuePairs.at(i).first = i; // idValuePairs.at(i).second = v(i); // } // // std::sort(idValuePairs.begin(), idValuePairs.end(), [](std::pair<HyEdgeID, double>& l, std::pair<HyEdgeID, double>& r) { // return l.second > r.second; // }); // // for (auto x: idValuePairs) { // std::cout << "id " << x.first << " val " << x.second << std::endl; // } // // // std::cout << "time to compute for " << size*size << " " << (double) (end - start)/CLOCKS_PER_SEC << std::endl; //}
31.822222
124
0.54574
masatoshihanai
52d75adeb5daa16d9dc557cdd2dbbb63e45668c3
1,089
cpp
C++
codeforces/A - Vasya and Petya's Game/Wrong answer on test 4.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/A - Vasya and Petya's Game/Wrong answer on test 4.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/A - Vasya and Petya's Game/Wrong answer on test 4.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Sep/02/2018 12:39 * solution_verdict: Wrong answer on test 4 language: GNU C++14 * run_time: 15 ms memory_used: 0 KB * problem: https://codeforces.com/contest/576/problem/A ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e6; bool is_prime(int x) { for(int i=2;i<x;i++) if(x%i==0)return false; return true; } int main() { ios_base::sync_with_stdio(0);cin.tie(0); int n,cnt=0;cin>>n; for(int i=2;i<=n;i++) { if(is_prime(i)) { cnt++; if(i*i<=n)cnt++; } } cout<<cnt<<endl; for(int i=2;i<=n;i++) { if(is_prime(i)) { cout<<i<<" "; if(i*i<=n)cout<<i*i<<" "; } } cout<<endl; return 0; }
27.225
111
0.380165
kzvd4729
52d7c710466ec69daf41255227b15079e72792b6
4,108
cpp
C++
src/LittleCrusaderAsi/modcore/modLoader.cpp
TheRedDaemon/LittleCrusaderAsi
da98790f68422d359dc93c198e2a79ec60719007
[ "MIT" ]
4
2020-11-30T21:53:57.000Z
2022-03-18T05:14:48.000Z
src/LittleCrusaderAsi/modcore/modLoader.cpp
TheRedDaemon/LittleCrusaderAsi
da98790f68422d359dc93c198e2a79ec60719007
[ "MIT" ]
3
2020-10-22T20:40:04.000Z
2021-10-05T14:24:22.000Z
src/LittleCrusaderAsi/modcore/modLoader.cpp
TheRedDaemon/LittleCrusaderAsi
da98790f68422d359dc93c198e2a79ec60719007
[ "MIT" ]
null
null
null
#include "modLoader.h" namespace modcore { ModLoader::ModLoader(HMODULE ownModule) { // set own Module handle ModMan::handle = ownModule; // will load config and what ever is required at the start std::unordered_map<ModID, Json> modConfigs{}; try { std::ifstream configStream("modConfig.json"); // reading config from file if (!configStream.good()) { throw std::exception("Unable to load config file. Does it exist?"); } Json modConfig = Json::parse(configStream); for (auto& pair : modConfig.items()) { ModID key{ ModManager::GetEnumByName(pair.key()) }; if (!key) { LOG(WARNING) << "No mod registration for name '" << pair.key() << "' found."; continue; // ignore } modConfigs[key] = pair.value(); } } catch (const Json::parse_error& o_O) { LOG(ERROR) << "Config parse error: " << o_O.what(); throw; } catch (const std::exception& o_O) { LOG(ERROR) << "Error during config load: " << o_O.what(); throw; } LOG(INFO) << "Configuration loaded."; fillAndOrderModVector(modConfigs); LOG(INFO) << "Mods loaded."; // end by calling initialze on every mod: int initializedMods{ 0 }; for (Mod* modPtr : ModMan::orderedMods) { if (modPtr->callInitialize()) { ++initializedMods; } } LOG(INFO) << initializedMods << " of " << ModMan::orderedMods.size() << " mods initialized."; } void ModLoader::dllThreadAttachEvent() { // at the first attach event, fire this event to the mods for (Mod* modPtr : ModMan::orderedMods) { modPtr->threadAttachAfterModAttachEvent(); } } // will run backwards over mods and call cleanUp // destruction will be handled by smart pointers ModLoader::~ModLoader() { // call cleanUp in reverse dependency order (is this reverse order?) for (int i = ModMan::orderedMods.size() - 1; i >= 0; i--) { ModMan::orderedMods.at(i)->cleanUp(); } LOG(INFO) << "Cleaned up mods."; } void ModLoader::fillAndOrderModVector(const std::unordered_map<ModID, Json> &modConfigs) { // normaly, the mod will run over all configs and add them for (const auto& config : modConfigs) { fulfillDependencies(modConfigs, config.first, config.second); } } void ModLoader::fulfillDependencies( const std::unordered_map<ModID, Json> &modConfigs, ModID neededMod, const Json &config) { if (auto it{ ModMan::loadedMods.find(neededMod) }; it != ModMan::loadedMods.end()) { if (!(it->second.mod)) { throw std::exception(("Cylic dependency reference encountered! Dependency with id '" + neededMod->getName() + "' was already requested.").c_str()); } // no else, if mod inside, everything is okay } else { // create mod entry: ModMan::loadedMods[neededMod]; // create mod only if needed, otherwise unused creates auto nextMod{ (neededMod->getValue())(config) }; std::vector<ModID> deps{ nextMod->getDependencies() }; if (!deps.empty()) { for (ModID dep : deps) { if (modConfigs.find(dep) != modConfigs.end()) { fulfillDependencies(modConfigs, dep, modConfigs.at(dep)); } else { // trying to call build in stuff (without external config?) fulfillDependencies(modConfigs, dep, nullptr); } // add, that this mod wanted this dependency ModMan::loadedMods[dep].modsThatNeedThis.push_back(neededMod); } } // if no dependency, it can be added // at this point, either everything is fulfilled or it broke anyway ModMan::loadedMods[neededMod].mod = nextMod; ModMan::orderedMods.push_back(&(*nextMod)); } } }
29.553957
98
0.570837
TheRedDaemon
52d7c7ca54a0eea33deb1efc16581a75f216be5d
907
hpp
C++
telnetpp/include/telnetpp/detail/negotiation_router.hpp
CalielOfSeptem/septem
fe7a615eb6c279d3746ee78de8864b5e07bf7e3e
[ "MIT" ]
1
2017-03-30T14:31:33.000Z
2017-03-30T14:31:33.000Z
telnetpp/include/telnetpp/detail/negotiation_router.hpp
HoraceWeebler/septem
fe7a615eb6c279d3746ee78de8864b5e07bf7e3e
[ "MIT" ]
null
null
null
telnetpp/include/telnetpp/detail/negotiation_router.hpp
HoraceWeebler/septem
fe7a615eb6c279d3746ee78de8864b5e07bf7e3e
[ "MIT" ]
null
null
null
#pragma once #include "telnetpp/detail/router.hpp" #include "telnetpp/negotiation.hpp" #include "telnetpp/element.hpp" #include <vector> namespace telnetpp { namespace detail { struct negotiation_router_key_from_message_policy { static negotiation key_from_message(negotiation const &neg) { return neg; } }; //* ========================================================================= /// \brief A structure that can route incoming negotiations to their /// associated options. /// /// This can be used as a multiplexer between incoming /// negotiations and the set of supported client and server options. /// ========================================================================= class negotiation_router : public router< negotiation, negotiation, std::vector<telnetpp::token>, detail::negotiation_router_key_from_message_policy > { }; }}
25.194444
77
0.597574
CalielOfSeptem
52d83c9b2ec6636a204b2cefb02ac76c8129cd33
544
cpp
C++
src/lib/lib_ruben/ruben.cpp
rpasquay/scratch
6c8076f9ab208cbd60e60ceaf0223c3170312c0d
[ "MIT" ]
5
2018-12-04T09:30:00.000Z
2021-08-21T08:50:09.000Z
src/lib/lib_ruben/ruben.cpp
rpasquay/scratch
6c8076f9ab208cbd60e60ceaf0223c3170312c0d
[ "MIT" ]
null
null
null
src/lib/lib_ruben/ruben.cpp
rpasquay/scratch
6c8076f9ab208cbd60e60ceaf0223c3170312c0d
[ "MIT" ]
3
2018-12-05T10:36:01.000Z
2020-07-10T13:48:46.000Z
#include <sstream> #include "scratch/lib_ruben/ruben.hpp" #include "scratch/lib_ruben/exceptions.hpp" scratch::ruben::Ruben::Ruben() : rubens_secret(42) {} unsigned int scratch::ruben::Ruben::get_secrect() const { return rubens_secret; } void scratch::ruben::Ruben::set_secrect(const unsigned int secret) { rubens_secret = secret; } void scratch::ruben::Ruben::throw_secrect() const { std::stringstream msg; msg << "My secret number is " << rubens_secret << "." << std::endl; throw SecretException(msg.str().c_str()); }
27.2
71
0.700368
rpasquay
52d89693da7154c6e0a7248b94cd96063e8dd01b
9,099
cxx
C++
bpkg/cfg-unlink.cxx
build2/bpkg
bd939839b44d90d027517e447537dd52539269ff
[ "MIT" ]
19
2018-05-30T12:01:25.000Z
2022-01-29T21:37:23.000Z
bpkg/cfg-unlink.cxx
build2/bpkg
bd939839b44d90d027517e447537dd52539269ff
[ "MIT" ]
2
2019-03-18T22:31:45.000Z
2020-07-28T06:44:03.000Z
bpkg/cfg-unlink.cxx
build2/bpkg
bd939839b44d90d027517e447537dd52539269ff
[ "MIT" ]
1
2019-02-04T02:58:14.000Z
2019-02-04T02:58:14.000Z
// file : bpkg/cfg-unlink.cxx -*- C++ -*- // license : MIT; see accompanying LICENSE file #include <bpkg/cfg-unlink.hxx> #include <bpkg/package.hxx> #include <bpkg/package-odb.hxx> #include <bpkg/database.hxx> #include <bpkg/diagnostics.hxx> using namespace std; namespace bpkg { static int cfg_unlink_config (const cfg_unlink_options& o, cli::scanner& args) try { tracer trace ("cfg_unlink_config"); dir_path c (o.directory ()); l4 ([&]{trace << "configuration: " << c;}); database mdb (c, trace, true /* pre_attach */); transaction t (mdb); // Find the configuration to be unlinked. // // Note that we exclude the current configuration from the search. // database& udb (o.name_specified () ? mdb.find_attached (o.name (), false) : o.id_specified () ? mdb.find_attached (o.id (), false) : o.uuid_specified () ? mdb.find_attached (o.uuid (), false) : mdb.find_attached ( normalize (dir_path (args.next ()), "specified linked configuration"), false)); l4 ([&]{trace << "unlink configuration: " << udb.config;}); bool priv (udb.private_ ()); // If the configuration being unlinked contains any prerequisites of // packages in other configurations, make sure that they will stay // resolvable for their dependents after the configuration is unlinked // (see _selected_package_ref::to_ptr() for the resolution details). // // Specifically, if the configuration being unlinked is private, make sure // it doesn't contain any prerequisites of any dependents in any other // configurations (since we will remove it). Otherwise, do not consider // those dependent configurations which will still be linked with the // unlinked configuration (directly or indirectly through some different // path). // // So, for example, for the following link chain where cfg1 contains a // dependent of a prerequisite in cfg3, unlinking cfg3 from cfg2 will // result with the "cfg3 still depends on cfg1" error. // // cfg1 (target) -> cfg2 (target) -> cfg3 (host) // { // Note: needs to come before the subsequent unlinking. // // Also note that this call also verifies integrity of the implicit // links of the configuration being unlinked, which we rely upon below. // linked_databases dcs (udb.dependent_configs ()); // Unlink the configuration in the in-memory model, so we can evaluate // if the dependent configurations are still linked with it. // // Note that we don't remove the backlink here, since this is not // required for the check. // if (!priv) { linked_configs& ls (mdb.explicit_links ()); auto i (find_if (ls.begin (), ls.end (), [&udb] (const linked_config& lc) { return lc.db == udb; })); assert (i != ls.end ()); // By definition. ls.erase (i); } // Now go through the packages configured in the unlinked configuration // and check it they have some dependents in other configurations which // now unable to resolve them as prerequisites. Issue diagnostics and // fail if that's the case. // using query = query<selected_package>; for (shared_ptr<selected_package> sp: pointer_result ( udb.query<selected_package> (query::state == "configured"))) { for (auto i (dcs.begin_linked ()); i != dcs.end (); ++i) { database& db (*i); odb::result<package_dependent> ds ( query_dependents (db, sp->name, udb)); // Skip the dependent configuration if it doesn't contain any // dependents of the package. // if (ds.empty ()) continue; // Skip the dependent configuration if it is still (potentially // indirectly) linked with the unlinked configuration. // if (!priv) { linked_databases cs (db.dependency_configs ()); if (find_if (cs.begin (), cs.end (), [&udb] (const database& db) { return db == udb; }) != cs.end ()) continue; } diag_record dr (fail); dr << "configuration " << db.config_orig << " still depends on " << (priv ? "private " : "") << "configuration " << udb.config_orig << info << "package " << sp->name << udb << " has dependents:"; for (const package_dependent& pd: ds) { dr << info << "package " << pd.name << db; if (pd.constraint) dr << " on " << sp->name << " " << *pd.constraint; } } } } // Now unlink the configuration for real, in the database. // // Specifically, load the current and the being unlinked configurations // and remove their respective explicit and implicit links. // { using query = query<configuration>; // Explicit link. // shared_ptr<configuration> uc ( mdb.query_one<configuration> (query::uuid == udb.uuid.string ())); // The integrity of the current configuration explicit links is verified // by the database constructor. // assert (uc != nullptr); // Implicit backlink. // shared_ptr<configuration> cc ( udb.query_one<configuration> (query::uuid == mdb.uuid.string ())); // The integrity of the implicit links of the configuration being // unlinked is verified by the above dependent_configs() call. // assert (cc != nullptr); // If the backlink turns out to be explicit, then, unless the // configuration being unlinked is private, we just turn the explicit // link into an implicit one rather then remove the direct and back // links. // if (cc->expl && !priv) { info << "configurations " << udb.config_orig << " and " << mdb.config_orig << " are mutually linked, turning the link " << "to " << udb.config_orig << " into implicit backlink"; uc->expl = false; mdb.update (uc); } else { mdb.erase (uc); udb.erase (cc); } } t.commit (); // If the unlinked configuration is private, then detach its database and // remove its directory. But first, stash the directory path for the // subsequent removal and diagnostics. // dir_path ud (udb.config); if (priv) { mdb.detach_all (); rm_r (ud); } if (verb && !o.no_result ()) text << "unlinked " << (priv ? "and removed " : "") << "configuration " << ud; return 0; } catch (const invalid_path& e) { fail << "invalid path: '" << e.path << "'" << endf; } static int cfg_unlink_dangling (const cfg_unlink_options& o, cli::scanner&) { tracer trace ("cfg_unlink_dangling"); dir_path c (o.directory ()); l4 ([&]{trace << "configuration: " << c;}); database db (c, trace, false /* pre_attach */); transaction t (db); using query = query<configuration>; size_t count (0); for (auto& c: db.query<configuration> (query::id != 0 && !query::expl)) { if (!exists (c.effective_path (db.config))) { if (verb > 1) text << "removing dangling implicit backlink " << c.path; db.erase (c); ++count; } } t.commit (); if (verb && !o.no_result ()) text << "removed " << count << " dangling implicit backlink(s)"; return 0; } int cfg_unlink (const cfg_unlink_options& o, cli::scanner& args) { // Verify that the unlink mode is specified unambiguously. // // Points to the mode, if any is specified and NULL otherwise. // const char* mode (nullptr); // If the mode is specified, then check that it hasn't been specified yet // and set it, if that's the case, or fail otherwise. // auto verify = [&mode] (const char* m, bool specified) { if (specified) { if (mode == nullptr) mode = m; else fail << "both " << mode << " and " << m << " specified"; } }; verify ("--dangling", o.dangling ()); verify ("--name", o.name_specified ()); verify ("--id", o.id_specified ()); verify ("--uuid", o.uuid_specified ()); verify ("directory argument", args.more ()); if (mode == nullptr) fail << "expected configuration to unlink or --dangling option" << info << "run 'bpkg help cfg-unlink' for more information"; return o.dangling () ? cfg_unlink_dangling (o, args) : cfg_unlink_config (o, args); } }
31.054608
79
0.560611
build2
52d94feb5eca1106ba8a092a4391590ca1a176a8
2,490
cpp
C++
Solutions/Count Complete Tree Nodes/main.cpp
Crayzero/LeetCodeProgramming
b10ebe22c0de1501722f0f5c934c0c1902a26789
[ "MIT" ]
1
2015-04-13T10:58:30.000Z
2015-04-13T10:58:30.000Z
Solutions/Count Complete Tree Nodes/main.cpp
Crayzero/LeetCodeProgramming
b10ebe22c0de1501722f0f5c934c0c1902a26789
[ "MIT" ]
null
null
null
Solutions/Count Complete Tree Nodes/main.cpp
Crayzero/LeetCodeProgramming
b10ebe22c0de1501722f0f5c934c0c1902a26789
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x): val(x), left(NULL), right(NULL) {} }; class Solution { public: int countNodes(TreeNode* root) { int level = 0; for(TreeNode *p = root; p; level++, p = p->left); if (level <= 1) return pow(2, level-1); int cnt = 0; int cur_level = 1; cnt = pow(2, level - cur_level - 1); int tot = 0; while(1) { if (cnt == 1) { return pow(2, level-1) -1 + tot + (root->left ? 1 : 0) + (root->right ? 1 : 0); } TreeNode *left = root->left; TreeNode *tmp = left; cur_level++; if (cur_level == level) tmp = root; for(int i = cur_level; i < level-1 && tmp; ++i) { tmp = tmp->right; } cout<<tmp->val<<endl; if (tmp == NULL) return pow(2, level - 1) + tot -1; if (tmp->left == NULL && tmp->right == NULL) { cnt /= 2; root = root->left; } else if (tmp->right == NULL) { tot += cnt - 1; return pow(2, level - 1) -1 + tot; } else { tot += cnt; cnt /= 2; root = root->right; } cout<<" "<<tot<<endl; } cout<<cnt<<endl; return pow(2, level-1) - 1 + cnt; } }; int main() { TreeNode *a1 = new TreeNode(1); TreeNode *a2 = new TreeNode(2); TreeNode *a3 = new TreeNode(3); TreeNode *a4 = new TreeNode(4); TreeNode *a5 = new TreeNode(5); TreeNode *a6 = new TreeNode(6); TreeNode *a7 = new TreeNode(7); TreeNode *a8 = new TreeNode(8); TreeNode *a9 = new TreeNode(9); TreeNode *a10 = new TreeNode(10); TreeNode *a11 = new TreeNode(11); TreeNode *a12 = new TreeNode(12); TreeNode *a13 = new TreeNode(13); TreeNode *a14 = new TreeNode(14); TreeNode *a15 = new TreeNode(15); a1->left = a2; a1->right = a3; a2->left = a4; a2->right = a5; a3->left = a6; a3->right = a7; a4->left = a8; //a4->right = a9; //a5->left = a10; //a5->right = a11; //a6->left = a12; //a6->right = a13; //a7->left = a14; //a7->right = a15; Solution s; cout<<s.countNodes(a1); return 0; }
26.489362
95
0.45743
Crayzero
52daa4e79485287f41e303cec8808154406be5cf
4,235
cpp
C++
wled00/Effect/snowflake/Solid.cpp
mdraper81/WLED
408696ef02f7b2dd66300a6a2ddb67a74d037b88
[ "MIT" ]
null
null
null
wled00/Effect/snowflake/Solid.cpp
mdraper81/WLED
408696ef02f7b2dd66300a6a2ddb67a74d037b88
[ "MIT" ]
null
null
null
wled00/Effect/snowflake/Solid.cpp
mdraper81/WLED
408696ef02f7b2dd66300a6a2ddb67a74d037b88
[ "MIT" ]
null
null
null
#include "Solid.h" namespace Effect { namespace Snowflake { /* ** ============================================================================ ** Constructor ** ============================================================================ */ Solid::Solid(NeoPixelWrapper* pixelWrapper, Data* effectData) : BaseSnowFlake(pixelWrapper, effectData) { } /* ** ============================================================================ ** Destructor ** ============================================================================ */ Solid::~Solid() { } /* ** ============================================================================ ** Run the current effect ** ============================================================================ */ bool Solid::runEffect(uint32_t delta) { incrementRunningTime(delta); updateEffectData(); // Process the effect to shift the colors of the LEDs for (int armIndex = 0; armIndex < mNumberOfArms; ++armIndex) { processArm(armIndex); } } /* ** ============================================================================ ** Process the LEDs in the arm with the given index. This will set the correct ** colors for the LEDs for this arm ** ============================================================================ */ void Solid::processArm(int armIndex) { // Turn on the correct number of LEDs in the arm for where we are in the // effect (what tick we are on). const uint16_t armStartingAddress = getStartingAddressForArmIndex(armIndex); for (int armAddressIndex = 0; armAddressIndex < mArmLength; ++armAddressIndex) { uint16_t address = armStartingAddress + armAddressIndex; const int effectOffset = armAddressIndex; setPixelColorFromPalette(address, effectOffset); } processSmallChevron(armIndex); processLargeChevron(armIndex); } /* ** ============================================================================ ** Process the LEDs in the small chevron for the arm with the given index. ** This will set the correct colors for the LEDs in this chevron. ** ============================================================================ */ void Solid::processSmallChevron(int armIndex) { const uint8_t numTicksToProcess = getNumberOfTicksForSmallChevron(); const uint16_t smallChevronStartingAddress_Left = getStartingAddressForSmallChevron(armIndex, true); const uint16_t smallChevronStartingAddress_Right = getStartingAddressForSmallChevron(armIndex, false); for (uint8_t chevronAddressIndex = 0; chevronAddressIndex < numTicksToProcess; ++chevronAddressIndex) { const uint16_t leftAddress = smallChevronStartingAddress_Left + chevronAddressIndex; const uint16_t rightAddress = smallChevronStartingAddress_Right + chevronAddressIndex; const int effectOffset = mSmallChevronPosition + chevronAddressIndex; setPixelColorFromPalette(leftAddress, effectOffset); setPixelColorFromPalette(rightAddress, effectOffset); } } /* ** ============================================================================ ** Process the LEDs in the large chevron for the arm with the given index. ** This will set the correct colors for the LEDs in this chevron. ** ============================================================================ */ void Solid::processLargeChevron(int armIndex) { const uint8_t numTicksToProcess = getNumberOfTicksForLargeChevron(); const uint16_t largeChevronStartingAddress_Left = getStartingAddressForLargeChevron(armIndex, true); const uint16_t largeChevronStartingAddress_Right = getStartingAddressForLargeChevron(armIndex, false); for (uint8_t chevronAddressIndex = 0; chevronAddressIndex < numTicksToProcess; ++chevronAddressIndex) { const uint16_t leftAddress = largeChevronStartingAddress_Left + chevronAddressIndex; const uint16_t rightAddress = largeChevronStartingAddress_Right + chevronAddressIndex; const int effectOffset = mArmLength + chevronAddressIndex; setPixelColorFromPalette(leftAddress, effectOffset); setPixelColorFromPalette(rightAddress, effectOffset); } } } // namespace Effect::Snowflake } // namespace Effect
37.477876
106
0.577568
mdraper81
52dba18fa461cee3687767207b5b9b83251f7800
25,585
hpp
C++
include/System/Collections/ArrayList.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/System/Collections/ArrayList.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/System/Collections/ArrayList.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.ICloneable #include "System/ICloneable.hpp" // Including type: System.Collections.IList #include "System/Collections/IList.hpp" // Including type: System.Int32 #include "System/Int32.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/typedefs-array.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Collections namespace System::Collections { // Skipping declaration: ICollection because it is already included! // Forward declaring type: IEnumerator class IEnumerator; } // Forward declaring namespace: System namespace System { // Forward declaring type: Array class Array; // Forward declaring type: Type class Type; } // Completed forward declares // Type namespace: System.Collections namespace System::Collections { // Forward declaring type: ArrayList class ArrayList; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::System::Collections::ArrayList); DEFINE_IL2CPP_ARG_TYPE(::System::Collections::ArrayList*, "System.Collections", "ArrayList"); // Type namespace: System.Collections namespace System::Collections { // Size: 0x28 #pragma pack(push, 1) // Autogenerated type: System.Collections.ArrayList // [TokenAttribute] Offset: FFFFFFFF // [DebuggerTypeProxyAttribute] Offset: 57D850 // [DebuggerDisplayAttribute] Offset: 57D850 // [DefaultMemberAttribute] Offset: 57D850 // [ComVisibleAttribute] Offset: 57D850 class ArrayList : public ::Il2CppObject/*, public ::System::ICloneable, public ::System::Collections::IList*/ { public: // Nested type: ::System::Collections::ArrayList::ReadOnlyArrayList class ReadOnlyArrayList; // Nested type: ::System::Collections::ArrayList::ArrayListEnumeratorSimple class ArrayListEnumeratorSimple; // Nested type: ::System::Collections::ArrayList::ArrayListDebugView class ArrayListDebugView; #ifdef USE_CODEGEN_FIELDS public: #else #ifdef CODEGEN_FIELD_ACCESSIBILITY CODEGEN_FIELD_ACCESSIBILITY: #else protected: #endif #endif // private System.Object[] _items // Size: 0x8 // Offset: 0x10 ::ArrayW<::Il2CppObject*> items; // Field size check static_assert(sizeof(::ArrayW<::Il2CppObject*>) == 0x8); // private System.Int32 _size // Size: 0x4 // Offset: 0x18 int size; // Field size check static_assert(sizeof(int) == 0x4); // private System.Int32 _version // Size: 0x4 // Offset: 0x1C int version; // Field size check static_assert(sizeof(int) == 0x4); // private System.Object _syncRoot // Size: 0x8 // Offset: 0x20 ::Il2CppObject* syncRoot; // Field size check static_assert(sizeof(::Il2CppObject*) == 0x8); public: // Creating interface conversion operator: operator ::System::ICloneable operator ::System::ICloneable() noexcept { return *reinterpret_cast<::System::ICloneable*>(this); } // Creating interface conversion operator: operator ::System::Collections::IList operator ::System::Collections::IList() noexcept { return *reinterpret_cast<::System::Collections::IList*>(this); } // static field const value: static private System.Int32 _defaultCapacity static constexpr const int _defaultCapacity = 4; // Get static field: static private System.Int32 _defaultCapacity static int _get__defaultCapacity(); // Set static field: static private System.Int32 _defaultCapacity static void _set__defaultCapacity(int value); // Get static field: static private readonly System.Object[] emptyArray static ::ArrayW<::Il2CppObject*> _get_emptyArray(); // Set static field: static private readonly System.Object[] emptyArray static void _set_emptyArray(::ArrayW<::Il2CppObject*> value); // Get instance field reference: private System.Object[] _items ::ArrayW<::Il2CppObject*>& dyn__items(); // Get instance field reference: private System.Int32 _size int& dyn__size(); // Get instance field reference: private System.Int32 _version int& dyn__version(); // Get instance field reference: private System.Object _syncRoot ::Il2CppObject*& dyn__syncRoot(); // public System.Void set_Capacity(System.Int32 value) // Offset: 0xDEA178 void set_Capacity(int value); // public System.Int32 get_Count() // Offset: 0xDEA298 int get_Count(); // public System.Boolean get_IsReadOnly() // Offset: 0xDEA2A0 bool get_IsReadOnly(); // public System.Object get_SyncRoot() // Offset: 0xDEA2A8 ::Il2CppObject* get_SyncRoot(); // public System.Object get_Item(System.Int32 index) // Offset: 0xDEA31C ::Il2CppObject* get_Item(int index); // public System.Void set_Item(System.Int32 index, System.Object value) // Offset: 0xDEA3D0 void set_Item(int index, ::Il2CppObject* value); // public System.Void .ctor(System.Int32 capacity) // Offset: 0xDE9E68 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static ArrayList* New_ctor(int capacity) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<ArrayList*, creationType>(capacity))); } // public System.Void .ctor(System.Collections.ICollection c) // Offset: 0xDE9FCC template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static ArrayList* New_ctor(::System::Collections::ICollection* c) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<ArrayList*, creationType>(c))); } // static private System.Void .cctor() // Offset: 0xDEB24C static void _cctor(); // public System.Int32 Add(System.Object value) // Offset: 0xDEA4C8 int Add(::Il2CppObject* value); // public System.Void AddRange(System.Collections.ICollection c) // Offset: 0xDEA5D4 void AddRange(::System::Collections::ICollection* c); // public System.Void Clear() // Offset: 0xDEA5F0 void Clear(); // public System.Object Clone() // Offset: 0xDEA634 ::Il2CppObject* Clone(); // public System.Boolean Contains(System.Object item) // Offset: 0xDEA6CC bool Contains(::Il2CppObject* item); // public System.Void CopyTo(System.Array array) // Offset: 0xDEA7A0 void CopyTo(::System::Array* array); // public System.Void CopyTo(System.Array array, System.Int32 arrayIndex) // Offset: 0xDEA7B4 void CopyTo(::System::Array* array, int arrayIndex); // public System.Void CopyTo(System.Int32 index, System.Array array, System.Int32 arrayIndex, System.Int32 count) // Offset: 0xDEA854 void CopyTo(int index, ::System::Array* array, int arrayIndex, int count); // private System.Void EnsureCapacity(System.Int32 min) // Offset: 0xDEA57C void EnsureCapacity(int min); // public System.Collections.IEnumerator GetEnumerator() // Offset: 0xDEA920 ::System::Collections::IEnumerator* GetEnumerator(); // public System.Int32 IndexOf(System.Object value) // Offset: 0xDEA980 int IndexOf(::Il2CppObject* value); // public System.Void Insert(System.Int32 index, System.Object value) // Offset: 0xDEA994 void Insert(int index, ::Il2CppObject* value); // public System.Void InsertRange(System.Int32 index, System.Collections.ICollection c) // Offset: 0xDEAAD0 void InsertRange(int index, ::System::Collections::ICollection* c); // static public System.Collections.ArrayList ReadOnly(System.Collections.ArrayList list) // Offset: 0xDEAD40 static ::System::Collections::ArrayList* ReadOnly(::System::Collections::ArrayList* list); // public System.Void Remove(System.Object obj) // Offset: 0xDEADE8 void Remove(::Il2CppObject* obj); // public System.Void RemoveAt(System.Int32 index) // Offset: 0xDEAE38 void RemoveAt(int index); // public System.Void RemoveRange(System.Int32 index, System.Int32 count) // Offset: 0xDEAF24 void RemoveRange(int index, int count); // public System.Object[] ToArray() // Offset: 0xDEB0A4 ::ArrayW<::Il2CppObject*> ToArray(); // public System.Array ToArray(System.Type type) // Offset: 0xDEB118 ::System::Array* ToArray(::System::Type* type); // public System.Void .ctor() // Offset: 0xDDE338 // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static ArrayList* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<ArrayList*, creationType>())); } }; // System.Collections.ArrayList #pragma pack(pop) static check_size<sizeof(ArrayList), 32 + sizeof(::Il2CppObject*)> __System_Collections_ArrayListSizeCheck; static_assert(sizeof(ArrayList) == 0x28); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::Collections::ArrayList::set_Capacity // Il2CppName: set_Capacity template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::ArrayList::*)(int)>(&System::Collections::ArrayList::set_Capacity)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "set_Capacity", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::get_Count // Il2CppName: get_Count template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Collections::ArrayList::*)()>(&System::Collections::ArrayList::get_Count)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "get_Count", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::get_IsReadOnly // Il2CppName: get_IsReadOnly template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Collections::ArrayList::*)()>(&System::Collections::ArrayList::get_IsReadOnly)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "get_IsReadOnly", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::get_SyncRoot // Il2CppName: get_SyncRoot template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (System::Collections::ArrayList::*)()>(&System::Collections::ArrayList::get_SyncRoot)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "get_SyncRoot", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::get_Item // Il2CppName: get_Item template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (System::Collections::ArrayList::*)(int)>(&System::Collections::ArrayList::get_Item)> { static const MethodInfo* get() { static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "get_Item", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::set_Item // Il2CppName: set_Item template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::ArrayList::*)(int, ::Il2CppObject*)>(&System::Collections::ArrayList::set_Item)> { static const MethodInfo* get() { static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "set_Item", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index, value}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: System::Collections::ArrayList::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: System::Collections::ArrayList::_cctor // Il2CppName: .cctor template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&System::Collections::ArrayList::_cctor)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::Add // Il2CppName: Add template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Collections::ArrayList::*)(::Il2CppObject*)>(&System::Collections::ArrayList::Add)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "Add", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::AddRange // Il2CppName: AddRange template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::ArrayList::*)(::System::Collections::ICollection*)>(&System::Collections::ArrayList::AddRange)> { static const MethodInfo* get() { static auto* c = &::il2cpp_utils::GetClassFromName("System.Collections", "ICollection")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "AddRange", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{c}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::Clear // Il2CppName: Clear template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::ArrayList::*)()>(&System::Collections::ArrayList::Clear)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "Clear", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::Clone // Il2CppName: Clone template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (System::Collections::ArrayList::*)()>(&System::Collections::ArrayList::Clone)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "Clone", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::Contains // Il2CppName: Contains template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Collections::ArrayList::*)(::Il2CppObject*)>(&System::Collections::ArrayList::Contains)> { static const MethodInfo* get() { static auto* item = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "Contains", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{item}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::CopyTo // Il2CppName: CopyTo template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::ArrayList::*)(::System::Array*)>(&System::Collections::ArrayList::CopyTo)> { static const MethodInfo* get() { static auto* array = &::il2cpp_utils::GetClassFromName("System", "Array")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "CopyTo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{array}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::CopyTo // Il2CppName: CopyTo template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::ArrayList::*)(::System::Array*, int)>(&System::Collections::ArrayList::CopyTo)> { static const MethodInfo* get() { static auto* array = &::il2cpp_utils::GetClassFromName("System", "Array")->byval_arg; static auto* arrayIndex = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "CopyTo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{array, arrayIndex}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::CopyTo // Il2CppName: CopyTo template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::ArrayList::*)(int, ::System::Array*, int, int)>(&System::Collections::ArrayList::CopyTo)> { static const MethodInfo* get() { static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* array = &::il2cpp_utils::GetClassFromName("System", "Array")->byval_arg; static auto* arrayIndex = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* count = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "CopyTo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index, array, arrayIndex, count}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::EnsureCapacity // Il2CppName: EnsureCapacity template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::ArrayList::*)(int)>(&System::Collections::ArrayList::EnsureCapacity)> { static const MethodInfo* get() { static auto* min = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "EnsureCapacity", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{min}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::GetEnumerator // Il2CppName: GetEnumerator template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::IEnumerator* (System::Collections::ArrayList::*)()>(&System::Collections::ArrayList::GetEnumerator)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "GetEnumerator", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::IndexOf // Il2CppName: IndexOf template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Collections::ArrayList::*)(::Il2CppObject*)>(&System::Collections::ArrayList::IndexOf)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "IndexOf", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::Insert // Il2CppName: Insert template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::ArrayList::*)(int, ::Il2CppObject*)>(&System::Collections::ArrayList::Insert)> { static const MethodInfo* get() { static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "Insert", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index, value}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::InsertRange // Il2CppName: InsertRange template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::ArrayList::*)(int, ::System::Collections::ICollection*)>(&System::Collections::ArrayList::InsertRange)> { static const MethodInfo* get() { static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* c = &::il2cpp_utils::GetClassFromName("System.Collections", "ICollection")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "InsertRange", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index, c}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::ReadOnly // Il2CppName: ReadOnly template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::ArrayList* (*)(::System::Collections::ArrayList*)>(&System::Collections::ArrayList::ReadOnly)> { static const MethodInfo* get() { static auto* list = &::il2cpp_utils::GetClassFromName("System.Collections", "ArrayList")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "ReadOnly", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{list}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::Remove // Il2CppName: Remove template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::ArrayList::*)(::Il2CppObject*)>(&System::Collections::ArrayList::Remove)> { static const MethodInfo* get() { static auto* obj = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "Remove", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{obj}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::RemoveAt // Il2CppName: RemoveAt template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::ArrayList::*)(int)>(&System::Collections::ArrayList::RemoveAt)> { static const MethodInfo* get() { static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "RemoveAt", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::RemoveRange // Il2CppName: RemoveRange template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::ArrayList::*)(int, int)>(&System::Collections::ArrayList::RemoveRange)> { static const MethodInfo* get() { static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* count = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "RemoveRange", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index, count}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::ToArray // Il2CppName: ToArray template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::ArrayW<::Il2CppObject*> (System::Collections::ArrayList::*)()>(&System::Collections::ArrayList::ToArray)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "ToArray", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::ToArray // Il2CppName: ToArray template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Array* (System::Collections::ArrayList::*)(::System::Type*)>(&System::Collections::ArrayList::ToArray)> { static const MethodInfo* get() { static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "ToArray", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
53.976793
201
0.726715
RedBrumbler
52dc71d923f378f329c13d74be120a145ce2082a
2,882
cpp
C++
GA_lapagos/SRC/tsp/tsp_ga_threaded.cpp
drpaj12/GA_lapagos
119a4a486e0bfe681ac640ef18b25de5f2a6076a
[ "MIT" ]
null
null
null
GA_lapagos/SRC/tsp/tsp_ga_threaded.cpp
drpaj12/GA_lapagos
119a4a486e0bfe681ac640ef18b25de5f2a6076a
[ "MIT" ]
null
null
null
GA_lapagos/SRC/tsp/tsp_ga_threaded.cpp
drpaj12/GA_lapagos
119a4a486e0bfe681ac640ef18b25de5f2a6076a
[ "MIT" ]
null
null
null
/* Copyright (c) 2019 Peter Andrew Jamieson (jamieson.peter@gmail.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <math.h> #include "globals.h" #include "types.h" #include "utils.h" #include "genetic_algorithm.h" #include "genetic_algorithm_threaded.h" #include "genetic_algorithm_combinational_crossovers.h" #include "genetic_algorithm_selectors.h" #include "tsp_globals.h" #include "tsp_types.h" #include "tsp_ga_genome_combinatorial_tupple.h" #include "tsp_ga_genome_combinatorial_tupple_threaded.h" #include "tsp_adjacency.h" #include "tsp_cartesian.h" /* Prototypes */ /*------------------------------------------------------------------------- * (function: tsp_run_ga) *-----------------------------------------------------------------------*/ void *tsp_run_ga_threaded(void *thread_structure) { double (*fptr_cost_function)(void *); thread_t *thread_struct = (thread_t*)thread_structure; switch(tsp_problem.problem_type) { case ADJACENCY_PERMUTATION: fptr_cost_function = tsp_cost_function_from_adjacency_permutation; break; case CARTESIAN: fptr_cost_function = tsp_cost_function_from_cartesian; break; default: printf("Not recognized tsp problem type!!!\n"); return NULL; } run_base_ga_threaded( thread_struct, (int (*)())setup_selector_function(), (void (*)(int))setup_selector_init_function(), tsp_cost_function_and_order_threaded, fptr_cost_function, tsp_copy_old_genomes_threaded, tsp_cross_breed_threaded, tsp_mutate_threaded, tsp_breed_and_mutate_threaded, tsp_random_new_threaded, tsp_cost_report_best, (void (*)(void*,void*,void*,void*,int))setup_crossover_function(), tsp_exit_condition); /* TEST OUT REPORT */ output_test_details((*fptr_cost_function)(genomes.population[global_index][0]->genome)); return NULL; }
30.989247
89
0.74254
drpaj12
52de456b0a33cf85a396d5029c3b997356632176
2,343
cpp
C++
Sources/Core/Input/InputEventHandler.cpp
VladimirBalun/RacingWorld
c7e600c5899e3ea78f50bd2f8cd915437bad7789
[ "Apache-2.0" ]
70
2019-02-02T15:43:38.000Z
2022-03-09T13:58:27.000Z
Sources/Core/Input/InputEventHandler.cpp
VladimirBalun/RacingWorld
c7e600c5899e3ea78f50bd2f8cd915437bad7789
[ "Apache-2.0" ]
19
2019-03-27T05:57:30.000Z
2019-07-07T16:07:05.000Z
Sources/Core/Input/InputEventHandler.cpp
VladimirBalun/RacingWorld
c7e600c5899e3ea78f50bd2f8cd915437bad7789
[ "Apache-2.0" ]
32
2019-03-07T12:22:40.000Z
2022-03-18T01:12:56.000Z
/* * Copyright 2018 Vladimir Balun * * 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 "PrecompiledHeader.hpp" #include "InputEventHandler.hpp" #include "MouseState.hpp" #include "KeyboardState.hpp" #include "../Helpers/Debug.hpp" #include "../Helpers/Macroses.hpp" void Core::Input::onInputError(const int error, const char* description) noexcept { LOG_WARNING(STR("Input error:" + STR(description))); } void Core::Input::onMouseMoveEvent(GLFWwindow* window, double x_pos, double y_pos) noexcept { g_mouse_state.setPosition(static_cast<int>(x_pos), static_cast<int>(y_pos)); } void Core::Input::onMouseClickEvent(GLFWwindow* window, int button, int action, int mods) noexcept { } void Core::Input::onKeyboardEvent(GLFWwindow* window, const int key, const int scan_code, const int action, const int mods) noexcept { KeyboardState& keyboard_state = KeyboardState::getInstance(); if (key == GLFW_KEY_W && action == GLFW_PRESS) { keyboard_state.pressKeyW(); return; } if (key == GLFW_KEY_S && action == GLFW_PRESS) { keyboard_state.pressKeyS(); return; } if (key == GLFW_KEY_A && action == GLFW_PRESS) { keyboard_state.pressKeyA(); return; } if (key == GLFW_KEY_D && action == GLFW_PRESS) { keyboard_state.pressKeyD(); return; } if (key == GLFW_KEY_W && action == GLFW_RELEASE) { keyboard_state.releaseKeyW(); return; } if (key == GLFW_KEY_S && action == GLFW_RELEASE) { keyboard_state.releaseKeyS(); return; } if (key == GLFW_KEY_A && action == GLFW_RELEASE) { keyboard_state.releaseKeyA(); return; } if (key == GLFW_KEY_D && action == GLFW_RELEASE) { keyboard_state.releaseKeyD(); } }
28.228916
132
0.662825
VladimirBalun
52e27ab59559a2c1d72582938a321ad0209f744e
539
hpp
C++
src/util/timer.hpp
StuffByDavid/Base
d37713fcf48655cb49032c576a1586c135e2e83d
[ "MIT" ]
null
null
null
src/util/timer.hpp
StuffByDavid/Base
d37713fcf48655cb49032c576a1586c135e2e83d
[ "MIT" ]
null
null
null
src/util/timer.hpp
StuffByDavid/Base
d37713fcf48655cb49032c576a1586c135e2e83d
[ "MIT" ]
null
null
null
#pragma once #include <chrono> // high_resolution_clock namespace Base { class Timer { public: EXPORT Timer(const string& name); /* Timer functionality */ EXPORT void stop(); EXPORT void print() const; EXPORT void stopAndPrint(); /* Get the time elapsed in milliseconds. */ double getDuration() const { return time; } private: std::chrono::_V2::high_resolution_clock::time_point startTime, endTime; double time; string name; }; }
20.730769
79
0.597403
StuffByDavid
52e7f7d832b6d461e41b65a35617a71006f98794
4,799
cpp
C++
source/blender/compositor/nodes/COM_TrackPositionNode.cpp
gunslingster/CSC581-assignement1
39012146e142bf400c7140d90ecfd27c45b589ca
[ "Naumen", "Condor-1.1", "MS-PL" ]
365
2015-02-10T15:10:55.000Z
2022-03-03T15:50:51.000Z
source/blender/compositor/nodes/COM_TrackPositionNode.cpp
mmtt1998819/blender
c9c3bf983321990a6960c422e002a372c35a6f76
[ "Naumen", "Condor-1.1", "MS-PL" ]
45
2015-01-09T15:34:20.000Z
2021-10-05T14:44:23.000Z
source/blender/compositor/nodes/COM_TrackPositionNode.cpp
mmtt1998819/blender
c9c3bf983321990a6960c422e002a372c35a6f76
[ "Naumen", "Condor-1.1", "MS-PL" ]
172
2015-01-25T15:16:53.000Z
2022-01-31T08:25:36.000Z
/* * 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. * * Copyright 2012, Blender Foundation. */ #include "COM_TrackPositionNode.h" #include "COM_ConvertOperation.h" #include "COM_ExecutionSystem.h" #include "COM_TrackPositionOperation.h" #include "DNA_movieclip_types.h" #include "BKE_node.h" TrackPositionNode::TrackPositionNode(bNode *editorNode) : Node(editorNode) { /* pass */ } static TrackPositionOperation *create_motion_operation(NodeConverter &converter, MovieClip *clip, NodeTrackPosData *trackpos_data, int axis, int frame_number, int delta) { TrackPositionOperation *operation = new TrackPositionOperation(); operation->setMovieClip(clip); operation->setTrackingObject(trackpos_data->tracking_object); operation->setTrackName(trackpos_data->track_name); operation->setFramenumber(frame_number); operation->setAxis(axis); operation->setPosition(CMP_TRACKPOS_ABSOLUTE); operation->setRelativeFrame(frame_number + delta); operation->setSpeedOutput(true); converter.addOperation(operation); return operation; } void TrackPositionNode::convertToOperations(NodeConverter &converter, const CompositorContext &context) const { bNode *editorNode = this->getbNode(); MovieClip *clip = (MovieClip *)editorNode->id; NodeTrackPosData *trackpos_data = (NodeTrackPosData *)editorNode->storage; NodeOutput *outputX = this->getOutputSocket(0); NodeOutput *outputY = this->getOutputSocket(1); NodeOutput *outputSpeed = this->getOutputSocket(2); int frame_number; if (editorNode->custom1 == CMP_TRACKPOS_ABSOLUTE_FRAME) { frame_number = editorNode->custom2; } else { frame_number = context.getFramenumber(); } TrackPositionOperation *operationX = new TrackPositionOperation(); operationX->setMovieClip(clip); operationX->setTrackingObject(trackpos_data->tracking_object); operationX->setTrackName(trackpos_data->track_name); operationX->setFramenumber(frame_number); operationX->setAxis(0); operationX->setPosition(editorNode->custom1); operationX->setRelativeFrame(editorNode->custom2); converter.addOperation(operationX); converter.mapOutputSocket(outputX, operationX->getOutputSocket()); TrackPositionOperation *operationY = new TrackPositionOperation(); operationY->setMovieClip(clip); operationY->setTrackingObject(trackpos_data->tracking_object); operationY->setTrackName(trackpos_data->track_name); operationY->setFramenumber(frame_number); operationY->setAxis(1); operationY->setPosition(editorNode->custom1); operationY->setRelativeFrame(editorNode->custom2); converter.addOperation(operationY); converter.mapOutputSocket(outputY, operationY->getOutputSocket()); TrackPositionOperation *operationMotionPreX = create_motion_operation( converter, clip, trackpos_data, 0, frame_number, -1); TrackPositionOperation *operationMotionPreY = create_motion_operation( converter, clip, trackpos_data, 1, frame_number, -1); TrackPositionOperation *operationMotionPostX = create_motion_operation( converter, clip, trackpos_data, 0, frame_number, 1); TrackPositionOperation *operationMotionPostY = create_motion_operation( converter, clip, trackpos_data, 1, frame_number, 1); CombineChannelsOperation *combine_operation = new CombineChannelsOperation(); converter.addOperation(combine_operation); converter.addLink(operationMotionPreX->getOutputSocket(), combine_operation->getInputSocket(0)); converter.addLink(operationMotionPreY->getOutputSocket(), combine_operation->getInputSocket(1)); converter.addLink(operationMotionPostX->getOutputSocket(), combine_operation->getInputSocket(2)); converter.addLink(operationMotionPostY->getOutputSocket(), combine_operation->getInputSocket(3)); converter.mapOutputSocket(outputSpeed, combine_operation->getOutputSocket()); }
42.848214
99
0.734945
gunslingster
52f1532e5ccc10b6720fefee80f58a572fe672a9
109
cc
C++
main.cc
DingXuefeng/sample-pybind11
e356877e83f2e183070ba16a303cdc84b420fc1c
[ "MIT" ]
null
null
null
main.cc
DingXuefeng/sample-pybind11
e356877e83f2e183070ba16a303cdc84b420fc1c
[ "MIT" ]
null
null
null
main.cc
DingXuefeng/sample-pybind11
e356877e83f2e183070ba16a303cdc84b420fc1c
[ "MIT" ]
null
null
null
#include "add.h" #include <iostream> int main(int,char*[]) { std::cout<<add(1,2)<<std::endl; return 0; }
15.571429
33
0.605505
DingXuefeng
52f180aa199856bbd1daa3cd50a319a79072faef
2,043
cpp
C++
src/Interpreters/MarkTableIdentifiersVisitor.cpp
mga-chka/ClickHouse
4fe722d1a460aea63de883299790ae8671424fae
[ "Apache-2.0" ]
3
2019-06-27T08:59:08.000Z
2021-09-03T02:38:02.000Z
src/Interpreters/MarkTableIdentifiersVisitor.cpp
mga-chka/ClickHouse
4fe722d1a460aea63de883299790ae8671424fae
[ "Apache-2.0" ]
1
2020-10-30T15:17:16.000Z
2020-10-30T15:17:16.000Z
src/Interpreters/MarkTableIdentifiersVisitor.cpp
mga-chka/ClickHouse
4fe722d1a460aea63de883299790ae8671424fae
[ "Apache-2.0" ]
1
2021-07-19T12:07:14.000Z
2021-07-19T12:07:14.000Z
#include <Interpreters/MarkTableIdentifiersVisitor.h> #include <IO/WriteBufferFromOStream.h> #include <Interpreters/IdentifierSemantic.h> #include <Interpreters/misc.h> #include <Parsers/ASTFunction.h> #include <Parsers/ASTSelectQuery.h> #include <Parsers/ASTTablesInSelectQuery.h> namespace DB { bool MarkTableIdentifiersMatcher::needChildVisit(ASTPtr & node, const ASTPtr & child) { if (child->as<ASTSelectQuery>()) return false; if (node->as<ASTTableExpression>()) return false; return true; } void MarkTableIdentifiersMatcher::visit(ASTPtr & ast, Data & data) { if (auto * node_func = ast->as<ASTFunction>()) visit(*node_func, ast, data); } void MarkTableIdentifiersMatcher::visit(const ASTFunction & func, ASTPtr & ptr, Data & data) { /// `IN t` can be specified, where t is a table, which is equivalent to `IN (SELECT * FROM t)`. if (checkFunctionIsInOrGlobalInOperator(func)) { auto ast = func.arguments->children.at(1); auto opt_name = tryGetIdentifierName(ast); if (opt_name && !data.aliases.count(*opt_name) && ast->as<ASTIdentifier>()) { ptr->as<ASTFunction>()->arguments->children[1] = ast->as<ASTIdentifier>()->createTable(); assert(ptr->as<ASTFunction>()->arguments->children[1]); } } // First argument of joinGet can be a table name, perhaps with a database. // First argument of dictGet can be a dictionary name, perhaps with a database. else if (functionIsJoinGet(func.name) || functionIsDictGet(func.name)) { if (!func.arguments || func.arguments->children.empty()) return; auto ast = func.arguments->children.at(0); auto opt_name = tryGetIdentifierName(ast); if (opt_name && !data.aliases.count(*opt_name) && ast->as<ASTIdentifier>()) { ptr->as<ASTFunction>()->arguments->children[0] = ast->as<ASTIdentifier>()->createTable(); assert(ptr->as<ASTFunction>()->arguments->children[0]); } } } }
33.491803
101
0.656877
mga-chka
52f5a999da6a1babaef52a0761237478be0f30e9
578
cpp
C++
lectures/week2/vector.cpp
garyCC227/cs6771
9a632b29743848fbba22c08caf760bd0f0463a0a
[ "MIT" ]
3
2020-06-30T11:06:27.000Z
2021-12-16T05:59:45.000Z
lectures/week2/vector.cpp
garyCC227/cs6771
9a632b29743848fbba22c08caf760bd0f0463a0a
[ "MIT" ]
null
null
null
lectures/week2/vector.cpp
garyCC227/cs6771
9a632b29743848fbba22c08caf760bd0f0463a0a
[ "MIT" ]
3
2020-08-02T00:21:15.000Z
2021-08-01T10:41:07.000Z
#include <iostream> #include <vector> // Begin with numbers 1, 2, 3 in the list already int main() { // In C++17 we can omit the int if the compiler can determine the type. std::vector<int> numbers{1, 2, 3}; int input; while (std::cin >> input) { numbers.push_back(input); } std::cout << "1st element: " << numbers.at(0) << "\n"; // slower, safer std::cout << "2nd element: " << numbers[1] << "\n"; // faster, less safe std::cout << "Max size before realloc: " << numbers.capacity() << "\n"; for (int n : numbers) { std::cout << n << "\n"; } }
30.421053
78
0.577855
garyCC227
52f655c89606cb8b53d542d8aec1dc7d4d87826a
13,682
cpp
C++
src/chromecast_finder.cpp
p2004a/pulseaudio-chromecast-sink
c62d2a8defb6a5819369624351441f4c972b1b98
[ "BSD-3-Clause" ]
1
2016-06-15T15:13:43.000Z
2016-06-15T15:13:43.000Z
src/chromecast_finder.cpp
p2004a/pulseaudio-chromecast-sink
c62d2a8defb6a5819369624351441f4c972b1b98
[ "BSD-3-Clause" ]
null
null
null
src/chromecast_finder.cpp
p2004a/pulseaudio-chromecast-sink
c62d2a8defb6a5819369624351441f4c972b1b98
[ "BSD-3-Clause" ]
1
2019-12-24T02:43:37.000Z
2019-12-24T02:43:37.000Z
/* chromecast_finder.cpp -- This file is part of pulseaudio-chromecast-sink * Copyright (C) 2016 Marek Rusinowski * * 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 3 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, see <http://www.gnu.org/licenses/>. */ #include <functional> #include <map> #include <memory> #include <string> #include <unordered_map> #include <asio/io_service.hpp> #include <asio/ip/tcp.hpp> #include <spdlog/spdlog.h> #include <avahi-client/client.h> #include <avahi-client/lookup.h> #include <avahi-common/error.h> #include <avahi-common/malloc.h> #include <avahi-common/simple-watch.h> #include "chromecast_finder.h" #include "defer.h" ChromecastFinder::ChromecastFinder(asio::io_service& io_service_, const char* logger_name) : io_service(io_service_), poll(io_service) { logger = spdlog::get(logger_name); } ChromecastFinder::~ChromecastFinder() { assert(avahi_client == nullptr && "Tried to destruct running instance of ChromecastFinder"); } void ChromecastFinder::start() { assert(update_handler != nullptr); poll.get_strand().post([this] { start_discovery(); }); } void ChromecastFinder::stop() { poll.get_strand().dispatch([this]() { logger->trace("(ChromecastFinder) Stopping"); if (stopped) { logger->trace("(ChromecastFinder) Already stopped!"); return; } stopped = true; while (!resolvers.empty()) { auto resolverId = resolvers.begin()->first; remove_resolver(resolverId); } if (avahi_browser != nullptr) { logger->trace("(ChromecastFinder) Freeing avahi_browser"); avahi_service_browser_free(avahi_browser); avahi_browser = nullptr; } if (avahi_client != nullptr) { logger->trace("(ChromecastFinder) Freeing avahi_client"); avahi_client_free(avahi_client); avahi_client = nullptr; } logger->debug("(ChromecastFinder) Stopped running"); }); } void ChromecastFinder::start_discovery() { stopped = false; int error; avahi_client = avahi_client_new(poll.get_pool(), AVAHI_CLIENT_NO_FAIL, ChromecastFinder::client_callback, this, &error); if (stopped) { avahi_client = nullptr; return; } if (!avahi_client) { report_error("Couldn't create avahi client: " + std::string(avahi_strerror(error))); } } void ChromecastFinder::client_callback(AvahiClient* c, AvahiClientState state, void* data) { ChromecastFinder* cf = static_cast<ChromecastFinder*>(data); if (cf->avahi_client != c) { cf->avahi_client = c; } assert(c); switch (state) { case AVAHI_CLIENT_S_RUNNING: cf->logger->info("(ChromecastFinder) Connected to Avahi server"); cf->avahi_browser = avahi_service_browser_new(cf->avahi_client, AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, "_googlecast._tcp", "local", static_cast<AvahiLookupFlags>(0), ChromecastFinder::browse_callback, cf); if (!cf->avahi_browser) { cf->report_error("Failed to create service browser: " + cf->get_avahi_error()); } break; case AVAHI_CLIENT_S_REGISTERING: case AVAHI_CLIENT_S_COLLISION: break; case AVAHI_CLIENT_CONNECTING: cf->logger->info("(ChromecastFinder) Connecting to Avahi server..."); break; case AVAHI_CLIENT_FAILURE: if (avahi_client_errno(cf->avahi_client) == AVAHI_ERR_DISCONNECTED) { cf->logger->info("(ChromecastFinder) Avahi server disconnected"); cf->stop(); cf->start_discovery(); } else { cf->report_error("Server connection failure: " + cf->get_avahi_error()); } break; } } void ChromecastFinder::browse_callback(AvahiServiceBrowser* b, AvahiIfIndex interface, AvahiProtocol protocol, AvahiBrowserEvent event, const char* name, const char* type, const char* domain, AvahiLookupResultFlags, void* data) { ChromecastFinder* cf = static_cast<ChromecastFinder*>(data); assert(b); /* Called whenever a new services becomes available on the LAN or is removed from the LAN */ switch (event) { case AVAHI_BROWSER_FAILURE: cf->report_error("Browser failure: " + cf->get_avahi_error()); break; case AVAHI_BROWSER_NEW: { cf->logger->debug( "(ChromecastFinder) (Browser) New service discovered name: {} interface: {}, " "protocol: {}", name, interface, protocol); AvahiServiceResolver* resolver = avahi_service_resolver_new( cf->avahi_client, interface, protocol, name, type, domain, AVAHI_PROTO_UNSPEC, static_cast<AvahiLookupFlags>(0), ChromecastFinder::resolve_callback, cf); if (!resolver) { cf->report_error("Failed to create service resolver: " + cf->get_avahi_error()); } else { cf->add_resolver(ResolverId(interface, protocol, name), resolver); } break; } case AVAHI_BROWSER_REMOVE: { cf->logger->debug( "(ChromecastFinder) (Browser) Service dissapeared name: '{}' interface: {}, " "protocol: {}", name, interface, protocol); cf->remove_resolver(ResolverId(interface, protocol, name)); break; } case AVAHI_BROWSER_ALL_FOR_NOW: case AVAHI_BROWSER_CACHE_EXHAUSTED: break; } } asio::ip::tcp::endpoint ChromecastFinder::avahiAddresToAsioEndpoint(const AvahiAddress* address, uint16_t port) { char addr_str[AVAHI_ADDRESS_STR_MAX]; avahi_address_snprint(addr_str, sizeof(addr_str), address); return asio::ip::tcp::endpoint(asio::ip::address::from_string(addr_str), port); } std::map<std::string, std::string> ChromecastFinder::avahiDNSStringListToMap( AvahiStringList* node) { std::map<std::string, std::string> result; for (; node; node = node->next) { size_t eq_pos; for (eq_pos = 0; eq_pos < node->size; ++eq_pos) { if (node->text[eq_pos] == '=') { break; } } if (eq_pos == node->size) { logger->warn( "(ChromecastFinder) Avahi DNS string element didn't contain equal sign, " "ignoring"); continue; } result.insert({std::string((char*)node->text, eq_pos), std::string((char*)node->text + eq_pos + 1, node->size - eq_pos - 1)}); } return result; }; void ChromecastFinder::resolve_callback(AvahiServiceResolver* r, AvahiIfIndex interface, AvahiProtocol protocol, AvahiResolverEvent event, const char* name, const char* /*type*/, const char* /*domain*/, const char* /*host_name*/, const AvahiAddress* address, uint16_t port, AvahiStringList* txt, AvahiLookupResultFlags, void* data) { assert(r); ChromecastFinder* cf = static_cast<ChromecastFinder*>(data); switch (event) { case AVAHI_RESOLVER_FAILURE: cf->logger->error( "(ChromecastFinder) (Resolver) Failed to resolve service name: '{}' interface: " "{} protocol: " "{}: {}", name, interface, protocol, cf->get_avahi_error()); break; case AVAHI_RESOLVER_FOUND: { cf->logger->debug( "(ChromecastFinder) (Resolver) Resolved service name: '{}' interface: {} " "protocol: {}", name, interface, protocol); auto endpoint = cf->avahiAddresToAsioEndpoint(address, port); auto dns = cf->avahiDNSStringListToMap(txt); std::string chromecast_name(name); cf->chromecasts_update(r, name, endpoint, dns); break; } } } void ChromecastFinder::report_error(const std::string& message) { if (error_handler) { error_handler(message); } else { throw ChromecastFinderException(message); } } std::string ChromecastFinder::get_avahi_error() const { return avahi_strerror(avahi_client_errno(avahi_client)); } void ChromecastFinder::remove_resolver(ResolverId id) { logger->trace("(ChromecastFinder) Remove resolver: {} {} {}", id.name, id.interface, id.protocol); auto resolver_it = resolvers.find(id); assert(resolver_it != resolvers.end()); AvahiServiceResolver* resolver = resolver_it->second; avahi_service_resolver_free(resolver); resolvers.erase(resolver_it); chromecasts_remove(resolver); } void ChromecastFinder::add_resolver(ResolverId id, AvahiServiceResolver* resolver) { logger->trace("(ChromecastFinder) Add resolver: {} {} {}", id.name, id.interface, id.protocol); bool inserted = resolvers.insert({id, resolver}).second; assert(inserted); } void ChromecastFinder::chromecasts_update(AvahiServiceResolver* resolver, const std::string& name, const asio::ip::tcp::endpoint& endpoint, const std::map<std::string, std::string>& dns) { bool added = false, updated = false; InternalChromecastInfo* chromecast; auto chromecast_it = chromecasts.find(name); if (chromecast_it == chromecasts.end()) { chromecast = new InternalChromecastInfo(); chromecast->name = name; chromecasts.emplace(name, std::unique_ptr<InternalChromecastInfo>(chromecast)); added = true; } else { chromecast = chromecast_it->second.get(); } if (dns != chromecast->dns) { chromecast->dns = dns; updated = true; } bool set_endpoint = false; if (resolver_to_chromecast.find(resolver) == resolver_to_chromecast.end()) { resolver_to_chromecast[resolver] = chromecast; set_endpoint = true; } else { auto curr_endpoint = chromecast->endpoints[resolver]; if (curr_endpoint != endpoint) { auto endpoint_count_it = chromecast->endpoint_count.find(curr_endpoint); if (--endpoint_count_it->second == 0) { chromecast->endpoint_count.erase(endpoint_count_it); updated = true; } set_endpoint = true; } } if (set_endpoint) { chromecast->endpoints[resolver] = endpoint; auto endpoint_count_it = chromecast->endpoint_count.find(endpoint); if (endpoint_count_it == chromecast->endpoint_count.end()) { chromecast->endpoint_count[endpoint] = 1; updated = true; } else { endpoint_count_it->second += 1; } } if (added || updated) { send_update(added ? UpdateType::NEW : UpdateType::UPDATE, chromecast); } } void ChromecastFinder::chromecasts_remove(AvahiServiceResolver* resolver) { auto resolver_to_chromecast_it = resolver_to_chromecast.find(resolver); if (resolver_to_chromecast_it == resolver_to_chromecast.end()) { // This is possible when someone calls ChromecastFinder::stop after resolver was registered // but before it resolved service. return; } bool updated = false; auto chromecast = resolver_to_chromecast_it->second; resolver_to_chromecast.erase(resolver_to_chromecast_it); auto endpoints_it = chromecast->endpoints.find(resolver); auto endpoint_count_it = chromecast->endpoint_count.find(endpoints_it->second); if (--endpoint_count_it->second == 0) { chromecast->endpoint_count.erase(endpoint_count_it); updated = true; } chromecast->endpoints.erase(endpoints_it); if (chromecast->endpoints.empty()) { send_update(UpdateType::REMOVE, chromecast); chromecasts.erase(chromecast->name); } else if (updated) { send_update(UpdateType::UPDATE, chromecast); } } void ChromecastFinder::send_update(UpdateType type, InternalChromecastInfo* chromecast) const { static const char* update_name[] = {"NEW", "UPDATE", "REMOVE"}; logger->trace("(ChromecastFinder) Sending update {} {}", chromecast->name, update_name[static_cast<int>(type)]); ChromecastInfo info; info.name = chromecast->name; info.dns = chromecast->dns; for (const auto& elem : chromecast->endpoint_count) { info.endpoints.insert(elem.first); } update_handler(type, info); }
38.111421
100
0.606783
p2004a
52fc19fd562a3f56481bd6de6ebb572def1d146e
6,759
cpp
C++
cpp/bmpshow.cpp
jerrythomas/cui-toolkit
5b9970e3c01ec17de6a2e9922ad211b7e3ac6a94
[ "MIT" ]
null
null
null
cpp/bmpshow.cpp
jerrythomas/cui-toolkit
5b9970e3c01ec17de6a2e9922ad211b7e3ac6a94
[ "MIT" ]
null
null
null
cpp/bmpshow.cpp
jerrythomas/cui-toolkit
5b9970e3c01ec17de6a2e9922ad211b7e3ac6a94
[ "MIT" ]
null
null
null
#include <string.h> #include <stdio.h> #include <pixel.h> #include <kbd.h> struct ColorMap { byte blu; byte grn; byte red; byte gry; }; struct BmpHeader { char Type[2]; //type of file ; must be ascii "BM" dword Size; // Size of file word Reserved1; //reserved fiels must be 0 word Reserved2; // ----------do------------ dword OffBits; //specifies offset in bytes fo start of bitmap data }; struct BmpInfo { dword Size; //Size of bitmapinfostructure 40 bytes dword Width; //Width of bitmap in pixels dword Height; //Height of Bitmap in pixels word Planes; //image planes( 1) word BitCount; //BitsPerPixel (1,4,8 or 24) dword Compression; //Compression used dword SizeImage; // Size of image in bytes dword XPelsPerMeter; // Horizontal resolution in pixels per meter dword YPelsPerMeter; // Vertical resolution in pixels per meter dword ClrUsed; // Number of color indexes in the color table dword ClrImportant; // Number of color indexes considered important for displaying bitmap }; class Bmp { private : BmpHeader bf; BmpInfo bi; ColorMap *co; char *BmpFile; word swImage; int ColMapSize; byte xScl,yScl; word X,Y; dword Width,Height; byte TotPix; byte BitMask; public : Bmp(char *FileName); Bmp(); ~Bmp(); private : void ShowBW(); void Show16(); void Show256(); public : void Capture(int x,int y,int w,int h); void SaveAs(char *F); void Show(int x,int y); void Scale(byte x,byte y); void Spec(); }; Bmp::Bmp() { bf.Type[0] = 'B'; bf.Type[1] = 'M'; bf.Size = 56; bf.Reserved1 = 0; bf.Reserved2 = 0; bf.OffBits = 56; swImage = 0; bi.Size = 40; BmpFile = (char*)NULL; xScl =yScl = 1; } Bmp::Bmp(char *FileName) { FILE *f; swImage = 0x00; xScl = yScl = 1; f = fopen(FileName,"r"); if (f != (FILE*)NULL) { fread((char*)&bf,sizeof(bf),1,f); if (bf.Type[0] == 'B' && bf.Type[1] == 'M') { fread((char*)&bi,sizeof(bi),1,f); BmpFile = new char[strlen(FileName)+1]; strcpy(BmpFile,FileName); swImage = 0x10; BitMask = 0; for(TotPix=0;TotPix<bi.BitCount;TotPix++) BitMask |= (1<<TotPix); TotPix = 8/bi.BitCount; Width = bi.Width; Width += (bi.BitCount==1) ? (32-bi.Width%32)%32:(8-bi.Width%8)%8; ColMapSize=(bf.OffBits-54)/4; co = new ColorMap[ColMapSize]; fread((char*)co,sizeof(ColorMap),ColMapSize,f); } } fclose(f); } Bmp::~Bmp() { if (BmpFile != (char*)NULL) delete BmpFile; if (co != (ColorMap*)NULL) delete co; } void Bmp::Show16() { int x,y,Pix; char dummy; FILE *f=fopen(BmpFile,"rb"); for (x=0;x<bf.OffBits;x++) fread(&dummy,sizeof(char),1,f); x=y=0; byte scl=1; if (bi.BitCount==1) { scl=15; //loadcolormap } if (swImage==0x10) do { fread(&dummy,sizeof(char),1,f); for (int k=0;k<TotPix;k++) { Pix = scl*((dummy>>((TotPix-1-k)*bi.BitCount))&BitMask); if (x<bi.Width) for(int i=0;i<xScl;i++) for (int j=0;j<yScl;j++) SetPixel(X+x*xScl+i,Y+(bi.Height-y)*yScl+j,Pix); x++; if (x==Width) { x=0;y++;} } } while((y<bi.Height) && !feof(f)); fclose(f); } void Bmp::Show(int x,int y) { X = x; Y = y; for (int i=0 ; i< ColMapSize;i++) { RGBHue[i].red = co[i].red>>2; RGBHue[i].blu = co[i].blu>>2; RGBHue[i].grn = co[i].grn>>2; } SetPalette(RGBHue); Show16(); } void Bmp::Capture(int x,int y,int w,int h) { bf.Type[0] = 'B'; bf.Type[1] = 'M'; bf.Size = 56; bf.Reserved1 = 0; bf.Reserved2 = 0; bf.OffBits = 56; swImage = 0; bi.Size = 40; bi.Width = w; bi.Height = h; bi.BitCount = 8; bi.Planes = 1; bi.Compression = 0; bi.SizeImage = w*h; ColMapSize = 256; if (co) delete co; co = new ColorMap[256]; for (int i=0 ; i< ColMapSize;i++) { co[i].red = RGBHue[i].red<<2; co[i].blu = RGBHue[i].blu<<2; co[i].grn = RGBHue[i].grn<<2; } xScl =yScl = 1; X = x; Y = y; } void Bmp::SaveAs(char *F) { byte Pix; int x,y; char dummy; if (BmpFile != (char*)NULL) delete BmpFile; BmpFile = new char [strlen(F)+1]; strcpy(BmpFile,F); FILE *f=fopen(BmpFile,"wb"); fwrite(&bf,sizeof(bf),1,f); fwrite((char*)&bi,sizeof(bi),1,f); fwrite((char*)co,sizeof(ColorMap),ColMapSize,f); BitMask = 0; for(TotPix=0;TotPix<bi.BitCount;TotPix++) BitMask |= (1<<TotPix); TotPix = 8/bi.BitCount; Width = bi.Width; Width += (bi.BitCount==1) ? (32-bi.Width%32)%32:(8-bi.Width%8)%8; y=0; byte buffer[1024]; do { for (x=0;x<bi.Width;x++) buffer[x] = GetPixel(X+x,Y+bi.Height-y); fwrite(buffer,sizeof(char),bi.Width,f); y++; } while(y<bi.Height); fclose(f); } void Bmp::Scale(byte x,byte y) { xScl = (x>0) ? x:1; yScl = (y>0) ? y:1; } void Bmp::Spec() { gPrintf(600,510,"\n File Name %s",BmpFile); gPrintf(600,520,"\nbfType %c%c ",bf.Type[0],bf.Type[1]); gPrintf(600,530,"\nbfSize %u ",bf.Size); gPrintf(600,540,"\nbfReserved1 %d ",bf.Reserved1); gPrintf(600,550,"\nbfReserved2 %d ",bf.Reserved2); gPrintf(600,560,"\nbfOffBits %u ",bf.OffBits); gPrintf(600,570,"\n head Size %u %u %u",sizeof(bf),sizeof(bi),sizeof(BmpHeader)); gPrintf(600,580,"\nColMapSize %d ",ColMapSize); gPrintf(600,590,"\n\nBMP InfoStructure\n"); gPrintf(600,600,"\nbiSize %u",bi.Size); gPrintf(600,610,"\nbiWidth %u",bi.Width); gPrintf(600,620,"\nbiHeight %u",bi.Height); gPrintf(600,630,"\nbiPlanes %u",bi.Planes); gPrintf(600,640,"\nbiBitCount %u",bi.BitCount); gPrintf(600,650,"\nbiCompression %u",bi.Compression); gPrintf(600,660,"\nbiSizeImage %u",bi.SizeImage); gPrintf(600,670,"\nbiXPelsPerMeter %u",bi.XPelsPerMeter); gPrintf(600,680,"\nbiYPelsPerMeter %u",bi.YPelsPerMeter); gPrintf(600,690,"\nbiClrUsed %u",bi.ClrUsed); gPrintf(600,700,"\nbiClrImportant %u\n",bi.ClrImportant); } /*main()//int argc,char **argv) { Bmp A("C:\\windows\\setup.bmp"); Bmp B; ModeSearch(VgaCo1024x768x256); A.Spec(); A.Show(10,10); GetKey(); CloseGraph(); return 0; }*/
24.578182
96
0.536322
jerrythomas
52fedf855cee29964159c06128a9cbbb260055d4
4,121
hpp
C++
src/fft_plan.hpp
MartinK84/riesling
3deb01ef6ec4a03ecbd5cf694d37f20de063dbae
[ "MIT" ]
null
null
null
src/fft_plan.hpp
MartinK84/riesling
3deb01ef6ec4a03ecbd5cf694d37f20de063dbae
[ "MIT" ]
null
null
null
src/fft_plan.hpp
MartinK84/riesling
3deb01ef6ec4a03ecbd5cf694d37f20de063dbae
[ "MIT" ]
null
null
null
#pragma once #include "fft_plan.h" #include "tensorOps.h" namespace FFT { template <int TRank, int FRank> Plan<TRank, FRank>::Plan(Tensor &workspace, Log &log, long const nThreads) : dims_{workspace.dimensions()} , log_{log} , threaded_{nThreads > 1} { plan(workspace, nThreads); } template <int TRank, int FRank> Plan<TRank, FRank>::Plan(TensorDims const &dims, Log &log, long const nThreads) : dims_{dims} , log_{log} , threaded_{nThreads > 1} { Tensor ws(dims); plan(ws, nThreads); } template <int TRank, int FRank> void Plan<TRank, FRank>::plan(Tensor &ws, long const nThreads) { std::array<int, FRank> sizes; int N = 1; int Nvox = 1; // Process the two different kinds of dimensions - howmany / FFT { constexpr int FStart = TRank - FRank; int ii = 0; for (; ii < FStart; ii++) { N *= ws.dimension(ii); } for (; ii < TRank; ii++) { int const sz = ws.dimension(ii); Nvox *= sz; sizes[ii - FStart] = sz; phase_[ii - FStart] = FFT::Phase(sz); // Prep FFT phase factors } } scale_ = 1. / sqrt(Nvox); auto ptr = reinterpret_cast<fftwf_complex *>(ws.data()); log_.info(FMT_STRING("Planning {} {} FFTs with {} threads"), N, fmt::join(sizes, "x"), nThreads); // FFTW is row-major. Reverse dims as per // http://www.fftw.org/fftw3_doc/Column_002dmajor-Format.html#Column_002dmajor-Format std::reverse(sizes.begin(), sizes.end()); auto const start = log_.now(); fftwf_plan_with_nthreads(nThreads); forward_plan_ = fftwf_plan_many_dft( FRank, sizes.data(), N, ptr, nullptr, N, 1, ptr, nullptr, N, 1, FFTW_FORWARD, FFTW_MEASURE); reverse_plan_ = fftwf_plan_many_dft( FRank, sizes.data(), N, ptr, nullptr, N, 1, ptr, nullptr, N, 1, FFTW_BACKWARD, FFTW_MEASURE); if (forward_plan_ == NULL) { log_.fail("Could not create forward FFT plan"); } if (reverse_plan_ == NULL) { log_.fail("Could not create reverse FFT plan"); } log_.debug("FFT planning took {}", log_.toNow(start)); } template <int TRank, int FRank> Plan<TRank, FRank>::~Plan() { fftwf_destroy_plan(forward_plan_); fftwf_destroy_plan(reverse_plan_); } template <int TRank, int FRank> float Plan<TRank, FRank>::scale() const { return scale_; } template <int TRank, int FRank> void Plan<TRank, FRank>::applyPhase(Tensor &x, float const scale, bool const forward) const { constexpr int FStart = TRank - FRank; for (long ii = 0; ii < FRank; ii++) { Eigen::array<long, TRank> rsh, brd; for (long in = 0; in < TRank; in++) { rsh[in] = 1; brd[in] = x.dimension(in); } rsh[FStart + ii] = phase_[ii].dimension(0); brd[FStart + ii] = 1; if (threaded_) { if (forward) { x.device(Threads::GlobalDevice()) = x * phase_[ii].reshape(rsh).broadcast(brd); } else { x.device(Threads::GlobalDevice()) = x / phase_[ii].reshape(rsh).broadcast(brd); } } else { if (forward) { x = x * phase_[ii].reshape(rsh).broadcast(brd); } else { x = x / phase_[ii].reshape(rsh).broadcast(brd); } } } if (scale != 1.f) { if (threaded_) { x.device(Threads::GlobalDevice()) = x * x.constant(scale); } else { x = x * x.constant(scale); } } } template <int TRank, int FRank> void Plan<TRank, FRank>::forward(Tensor &x) const { for (long ii = 0; ii < TRank; ii++) { assert(x.dimension(ii) == dims_[ii]); } auto const start = log_.now(); applyPhase(x, 1.f, true); auto ptr = reinterpret_cast<fftwf_complex *>(x.data()); fftwf_execute_dft(forward_plan_, ptr, ptr); applyPhase(x, scale_, true); log_.debug("Forward FFT: {}", log_.toNow(start)); } template <int TRank, int FRank> void Plan<TRank, FRank>::reverse(Tensor &x) const { for (long ii = 0; ii < TRank; ii++) { assert(x.dimension(ii) == dims_[ii]); } auto start = log_.now(); applyPhase(x, scale_, false); auto ptr = reinterpret_cast<fftwf_complex *>(x.data()); fftwf_execute_dft(reverse_plan_, ptr, ptr); applyPhase(x, 1.f, false); log_.debug("Reverse FFT: {}", log_.toNow(start)); } } // namespace FFT
27.657718
99
0.626062
MartinK84
52ff3b850aa6f5584cbb5655594d55cdc14475a1
546
cpp
C++
Source/ActorPool/Private/PoolActor.cpp
Othereum/ActorPool
b5a8a874120017ddb09503fb3eafdb49e5b98363
[ "MIT" ]
6
2020-03-10T02:17:43.000Z
2022-03-25T10:27:29.000Z
Source/ActorPool/Private/PoolActor.cpp
Othereum/ActorPool
b5a8a874120017ddb09503fb3eafdb49e5b98363
[ "MIT" ]
null
null
null
Source/ActorPool/Private/PoolActor.cpp
Othereum/ActorPool
b5a8a874120017ddb09503fb3eafdb49e5b98363
[ "MIT" ]
null
null
null
// Copyright 2019 Seokjin Lee. All Rights Reserved. #include "PoolActor.h" #include "ActorPool.h" void APoolActor::Release(const bool bForce) { if (!bActivated && !bForce) return; SetActorTickEnabled(false); SetActorEnableCollision(false); SetActorHiddenInGame(true); bActivated = false; Pool->Release(this); OnReleased(); } void APoolActor::Activate(const bool bForce) { if (bActivated && !bForce) return; SetActorTickEnabled(true); SetActorEnableCollision(true); SetActorHiddenInGame(false); bActivated = true; OnActivated(); }
21
51
0.752747
Othereum
5e0021af34be737bd4984952bd703be4b0ab83d1
13,879
cpp
C++
cpp-cgdk/tests/optimal_target.cpp
elsid/CodeWizards
6c7b5df632ec3d0a26fbf9b7f5fa8a3d5e0316ca
[ "MIT" ]
null
null
null
cpp-cgdk/tests/optimal_target.cpp
elsid/CodeWizards
6c7b5df632ec3d0a26fbf9b7f5fa8a3d5e0316ca
[ "MIT" ]
null
null
null
cpp-cgdk/tests/optimal_target.cpp
elsid/CodeWizards
6c7b5df632ec3d0a26fbf9b7f5fa8a3d5e0316ca
[ "MIT" ]
null
null
null
#include "common.hpp" #include <debug/output.hpp> #include <optimal_target.hpp> #include <gtest/gtest.h> namespace strategy { namespace tests { using namespace testing; TEST(GetTargetScore, for_me_and_enemy_wizard) { const model::Wizard enemy( 2, // Id 1300, // X 1300, // Y 0, // SpeedX 0, // SpeedY 0, // Angle model::FACTION_RENEGADES, // Faction 35, // Radius 100, // Life 100, // MaxLife {}, // Statuses 1, // OwnerPlayerId false, // Me 100, // Mana 100, // MaxMana 600, // VisionRange 500, // CastRange 0, // Xp 0, // Level {}, // Skills 0, // RemainingActionCooldownTicks {0, 0, 0, 0, 0, 0, 0}, // RemainingCooldownTicksByAction true, // Master {} // Messages ); const model::World world( 0, // TickIndex 20000, // TickCount 4000, // Width 4000, // Height {}, // Players {enemy, SELF}, // Wizards {}, // Minions {}, // Projectiles {}, // Bonuses {}, // Buildings {} // Trees ); model::Move move; const Profiler profiler; FullCache cache; update_cache(cache, world); const Context context(SELF, world, GAME, move, cache, cache, profiler, Duration::max()); const GetTargetScore get_target_score {context}; EXPECT_DOUBLE_EQ(get_target_score(enemy), 0.99247322403195037); EXPECT_DOUBLE_EQ(get_target_score.get_base(enemy), 2.625); EXPECT_DOUBLE_EQ(get_target_score.get_angle_probability(enemy), 1); EXPECT_DOUBLE_EQ(get_target_score.get_hit_probability(enemy), 0.5); EXPECT_DOUBLE_EQ(get_target_score.get_distance_probability(enemy), 0.75617007545291459); } TEST(GetTargetScore, for_me_and_enemy_minion) { const model::Minion enemy( 2, // Id 1300, // X 1300, // Y 0, // SpeedX 0, // SpeedY M_PI, // Angle model::FACTION_RENEGADES, // Faction 25, // Radius 100, // Life 100, // MaxLife {}, // Statuses model::MINION_ORC_WOODCUTTER, // Type 400, // VisionRange 12, // Damage 60, // CooldownTicks 0 // RemainingActionCooldownTicks ); const model::World world( 0, // TickIndex 20000, // TickCount 4000, // Width 4000, // Height {}, // Players {SELF}, // Wizards {enemy}, // Minions {}, // Projectiles {}, // Bonuses {}, // Buildings {} // Trees ); model::Move move; const Profiler profiler; FullCache cache; update_cache(cache, world); const Context context(SELF, world, GAME, move, cache, cache, profiler, Duration::max()); const GetTargetScore get_target_score {context}; EXPECT_DOUBLE_EQ(get_target_score(enemy), 3.0246803018116584); EXPECT_DOUBLE_EQ(get_target_score.get_base(enemy), 4); EXPECT_DOUBLE_EQ(get_target_score.get_angle_probability(enemy), 1); EXPECT_DOUBLE_EQ(get_target_score.get_hit_probability(enemy), 1); EXPECT_DOUBLE_EQ(get_target_score.get_distance_probability(enemy), 0.75617007545291459); } TEST(GetTargetScore, for_me_and_enemy_building) { const model::Wizard self( 1, // Id 4000 - 1929.29 - 300, // X 4000 - 2400 - 300, // Y 0, // SpeedX 0, // SpeedY M_PI_4, // Angle model::FACTION_ACADEMY, // Faction 35, // Radius 100, // Life 100, // MaxLife {}, // Statuses 1, // OwnerPlayerId true, // Me 100, // Mana 100, // MaxMana 600, // VisionRange 500, // CastRange 0, // Xp 0, // Level {}, // Skills 0, // RemainingActionCooldownTicks {0, 0, 0, 0, 0, 0, 0}, // RemainingCooldownTicksByAction true, // Master {} // Messages ); const model::Building enemy( 2, // Id 4000 - 1929.29, // X 4000 - 2400, // Y 0, // SpeedX 0, // SpeedY 0, // Angle model::FACTION_RENEGADES, // Faction 50, // Radius 500, // Life 500, // MaxLife {}, // Statuses model::BUILDING_GUARDIAN_TOWER, // Type 600, // VisionRange 600, // AttackRange 36, // Damage 240, // CooldownTicks 0 // RemainingActionCooldownTicks ); const model::World world( 0, // TickIndex 20000, // TickCount 4000, // Width 4000, // Height {}, // Players {self}, // Wizards {}, // Minions {}, // Projectiles {}, // Bonuses {enemy}, // Buildings {} // Trees ); model::Move move; const Profiler profiler; FullCache cache; update_cache(cache, world); const Context context(self, world, GAME, move, cache, cache, profiler, Duration::max()); const GetTargetScore get_target_score {context}; EXPECT_DOUBLE_EQ(get_target_score(enemy), 4.5370204527174876); EXPECT_DOUBLE_EQ(get_target_score.get_base(enemy), 6); EXPECT_DOUBLE_EQ(get_target_score.get_angle_probability(enemy), 1); EXPECT_DOUBLE_EQ(get_target_score.get_hit_probability(enemy), 1); EXPECT_DOUBLE_EQ(get_target_score.get_distance_probability(enemy), 0.75617007545291459); } TEST(get_optimal_target, for_me_and_enemy_wizard) { const model::Wizard enemy( 2, // Id 1100, // X 1100, // Y 0, // SpeedX 0, // SpeedY 0, // Angle model::FACTION_RENEGADES, // Faction 35, // Radius 100, // Life 100, // MaxLife {}, // Statuses 1, // OwnerPlayerId false, // Me 100, // Mana 100, // MaxMana 600, // VisionRange 500, // CastRange 0, // Xp 0, // Level {}, // Skills 0, // RemainingActionCooldownTicks {0, 0, 0, 0, 0, 0, 0}, // RemainingCooldownTicksByAction true, // Master {} // Messages ); const model::World world( 0, // TickIndex 20000, // TickCount 4000, // Width 4000, // Height {}, // Players {enemy, SELF}, // Wizards {}, // Minions {}, // Projectiles {}, // Bonuses {}, // Buildings {} // Trees ); model::Move move; const Profiler profiler; FullCache cache; update_cache(cache, world); const Context context(SELF, world, GAME, move, cache, cache, profiler, Duration::max()); const auto result = get_optimal_target(context, 1000); ASSERT_TRUE(result.is<model::Wizard>()); EXPECT_EQ(result.unit<model::Wizard>(cache)->getId(), world.getWizards().front().getId()); } TEST(get_optimal_target, for_me_and_friend_wizard) { const model::Wizard friend_wizard( 2, // Id 1100, // X 1100, // Y 0, // SpeedX 0, // SpeedY 0, // Angle model::FACTION_ACADEMY, // Faction 35, // Radius 100, // Life 100, // MaxLife {}, // Statuses 1, // OwnerPlayerId false, // Me 100, // Mana 100, // MaxMana 600, // VisionRange 500, // CastRange 0, // Xp 0, // Level {}, // Skills 0, // RemainingActionCooldownTicks {0, 0, 0, 0, 0, 0, 0}, // RemainingCooldownTicksByAction false, // Master {} // Messages ); const model::World world( 0, // TickIndex 20000, // TickCount 4000, // Width 4000, // Height {}, // Players {friend_wizard, SELF}, // Wizards {}, // Minions {}, // Projectiles {}, // Bonuses {}, // Buildings {} // Trees ); model::Move move; const Profiler profiler; FullCache cache; update_cache(cache, world); const Context context(SELF, world, GAME, move, cache, cache, profiler, Duration::max()); const auto result = get_optimal_target(context, 1000); EXPECT_FALSE(result.is_some()); } TEST(get_optimal_target, for_me_enemy_wizard_and_enemy_building) { static const model::Wizard self( 1, // Id 2500, // X 1000, // Y 0, // SpeedX 0, // SpeedY M_PI / 4, // Angle model::FACTION_ACADEMY, // Faction 35, // Radius 100, // Life 100, // MaxLife {}, // Statuses 1, // OwnerPlayerId true, // Me 100, // Mana 100, // MaxMana 600, // VisionRange 500, // CastRange 0, // Xp 0, // Level {}, // Skills 0, // RemainingActionCooldownTicks {0, 0, 0, 0, 0, 0, 0}, // RemainingCooldownTicksByAction true, // Master {} // Messages ); const model::Wizard enemy_wizard( 2, // Id 3097.3869999999997, // X 1231.9, // Y 0, // SpeedX 0, // SpeedY 0, // Angle model::FACTION_RENEGADES, // Faction 35, // Radius 100, // Life 100, // MaxLife {}, // Statuses 1, // OwnerPlayerId false, // Me 100, // Mana 100, // MaxMana 600, // VisionRange 500, // CastRange 0, // Xp 0, // Level {}, // Skills 0, // RemainingActionCooldownTicks {0, 0, 0, 0, 0, 0, 0}, // RemainingCooldownTicksByAction true, // Master {} // Messages ); const model::Building enemy_building( 3, // Id 3097.3869999999997, // X 1231.9, // Y 0, // SpeedX 0, // SpeedY 0, // Angle model::FACTION_RENEGADES, // Faction 100, // Radius 1000, // Life 1000, // MaxLife {}, // Statuses model::BUILDING_GUARDIAN_TOWER, // Type 800, // VisionRange 800, // AttackRange 48, // Damage 240, // CooldownTicks 0 // RemainingActionCooldownTicks ); const model::World world( 0, // TickIndex 20000, // TickCount 4000, // Width 4000, // Height {}, // Players {enemy_wizard, self}, // Wizards {}, // Minions {}, // Projectiles {}, // Bonuses {enemy_building}, // Buildings {} // Trees ); model::Move move; const Profiler profiler; FullCache cache; update_cache(cache, world); const Context context(self, world, GAME, move, cache, cache, profiler, Duration::max()); const auto result = get_optimal_target(context, 1000); ASSERT_TRUE(result.is<model::Building>()); EXPECT_EQ(result.unit<model::Building>(cache)->getId(), enemy_building.getId()); } TEST(get_optimal_target, for_me_and_enemy_wizards_with_different_skills) { const model::Wizard enemy_with_fireball( 2, // Id 1600, // X 1000, // Y 0, // SpeedX 0, // SpeedY 0, // Angle model::FACTION_RENEGADES, // Faction 35, // Radius 100, // Life 100, // MaxLife {}, // Statuses 1, // OwnerPlayerId false, // Me 100, // Mana 100, // MaxMana 600, // VisionRange 500, // CastRange 0, // Xp 0, // Level {model::SKILL_STAFF_DAMAGE_BONUS_AURA_2, model::SKILL_FIREBALL}, // Skills 0, // RemainingActionCooldownTicks {0, 0, 0, 0, 0, 0, 0}, // RemainingCooldownTicksByAction true, // Master {} // Messages ); const model::Wizard enemy_with_frostbolt( 3, // Id 1600, // X 1000, // Y 0, // SpeedX 0, // SpeedY 0, // Angle model::FACTION_RENEGADES, // Faction 35, // Radius 100, // Life 100, // MaxLife {}, // Statuses 1, // OwnerPlayerId false, // Me 100, // Mana 100, // MaxMana 600, // VisionRange 500 + 4 * 25, // CastRange 0, // Xp 0, // Level {model::SKILL_MAGICAL_DAMAGE_BONUS_AURA_2, model::SKILL_FROST_BOLT}, // Skills 0, // RemainingActionCooldownTicks {0, 0, 0, 0, 0, 0, 0}, // RemainingCooldownTicksByAction true, // Master {} // Messages ); const model::Wizard enemy_with_advanced_magic_missile( 4, // Id 1600, // X 1000, // Y 0, // SpeedX 0, // SpeedY 0, // Angle model::FACTION_RENEGADES, // Faction 35, // Radius 100, // Life 100, // MaxLife {}, // Statuses 1, // OwnerPlayerId false, // Me 100, // Mana 100, // MaxMana 600, // VisionRange 500, // CastRange 0, // Xp 0, // Level {model::SKILL_RANGE_BONUS_AURA_2, model::SKILL_ADVANCED_MAGIC_MISSILE}, // Skills 0, // RemainingActionCooldownTicks {0, 0, 0, 0, 0, 0, 0}, // RemainingCooldownTicksByAction true, // Master {} // Messages ); const model::World world( 0, // TickIndex 20000, // TickCount 4000, // Width 4000, // Height {}, // Players {enemy_with_fireball, enemy_with_frostbolt, enemy_with_advanced_magic_missile, SELF}, // Wizards {}, // Minions {}, // Projectiles {}, // Bonuses {}, // Buildings {} // Trees ); model::Move move; const Profiler profiler; FullCache cache; update_cache(cache, world); const Context context(SELF, world, GAME, move, cache, cache, profiler, Duration::max()); const auto result = get_optimal_target(context, 1000); ASSERT_TRUE(result.is<model::Wizard>()); EXPECT_EQ(result.unit<model::Wizard>(cache)->getId(), enemy_with_advanced_magic_missile.getId()); } } }
28.85447
104
0.53426
elsid
5e03f7f5683221fdaf0da88c1063cbb1fe849053
3,898
cpp
C++
src/protocol/http/uri.cpp
cysme/pump
d91cfdf3e09ebca1e90f0c1395a3b3fba1158a0c
[ "Apache-2.0" ]
2
2020-07-16T04:57:40.000Z
2020-11-24T10:33:48.000Z
src/protocol/http/uri.cpp
jimi36/pump
d91cfdf3e09ebca1e90f0c1395a3b3fba1158a0c
[ "Apache-2.0" ]
2
2020-12-23T09:40:16.000Z
2021-03-03T09:49:36.000Z
src/protocol/http/uri.cpp
cysme/pump
d91cfdf3e09ebca1e90f0c1395a3b3fba1158a0c
[ "Apache-2.0" ]
3
2020-11-24T10:33:35.000Z
2021-04-19T01:53:24.000Z
/* * Copyright (C) 2015-2018 ZhengHaiTao <ming8ren@163.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "pump/utils.h" #include "pump/protocol/http/uri.h" namespace pump { namespace protocol { namespace http { const std::string ut_strings[] = { "", "http", "https", "ws", "wss" }; std::string get_ut_string(int32_t ut) { return ut_strings[ut]; } bool parse_url(const std::string &url, int32_t &ut, std::string &host, std::string &path, std::map<std::string, std::string> &params) { std::string sut; { auto result = split_string(url, "[:]"); if (result.size() >= 2) { sut = result[0]; } else { sut = "https"; } } const block_t *p = url.c_str(); for (ut = URI_HTTP; ut < URI_END; ut++) { if (pump_strncasecmp(ut_strings[ut].c_str(), sut.c_str(), sut.size()) == 0) { p += ut_strings[ut].size(); break; } } if (ut == URI_END) { return false; } if (memcmp(p, "://", 3) != 0) { return false; } p += 3; const block_t *end = strstr(p, "/"); if (!end) { host.assign(p); path.assign("/"); return true; } host.assign(p, end); p = end; end = strstr(p, "?"); if (!end) { path.assign(p); return true; } path.assign(p, end); p = end + 1; std::string new_params; std::string raw_params(p); if (!url_decode(raw_params, new_params)) { return false; } auto kvs = split_string(new_params, "[=&]"); uint32_t cnt = (uint32_t)kvs.size(); if (cnt % 2 != 0) { return false; } for (uint32_t i = 0; i < cnt; i += 2) { params[kvs[i]] = kvs[i + 1]; } return true; } uri::uri() noexcept : ut_(UIR_NONE) { } uri::uri(const std::string &url) noexcept { parse(url); } void uri::reset() { ut_ = UIR_NONE; host_ = ""; path_ = ""; params_.clear(); } bool uri::parse(const std::string &url) { return parse_url(url, ut_, host_, path_, params_); } bool uri::get_param(const std::string &key, std::string &value) const { auto it = params_.find(key); if (it == params_.end()) { return false; } value = it->second; return true; } std::string uri::to_url() const { if (ut_ == UIR_NONE || ut_ == URI_END) { return std::string(); } std::string url; url = get_ut_string(ut_) + "://" + host_ + path_; std::vector<std::string> tmps; for (auto p : params_) { tmps.push_back(p.first + "=" + p.second); } if (!tmps.empty()) { url += "?" + join_strings(tmps, "&"); } std::string en_url; if (!url_encode(url, en_url)) { return std::string(); } return en_url; } } // namespace http } // namespace protocol } // namespace pump
24.670886
89
0.485121
cysme
5e0515da923a93bda2aa216137c981d4fb85206b
319
cpp
C++
Iniciante/URI 1013.cpp
wellmoot/UriOnlineJuge
8b367207f4544daae81f954f53b797b8a82d2133
[ "MIT" ]
null
null
null
Iniciante/URI 1013.cpp
wellmoot/UriOnlineJuge
8b367207f4544daae81f954f53b797b8a82d2133
[ "MIT" ]
null
null
null
Iniciante/URI 1013.cpp
wellmoot/UriOnlineJuge
8b367207f4544daae81f954f53b797b8a82d2133
[ "MIT" ]
null
null
null
#include <iostream> #include <stdlib.h> using namespace std; int main() { int a, b, c, maiorab, maiobc, maior; cin >> a >> b >> c; maiorab = (a + b + abs(a - b))/2; maiobc = (b + c + abs(b - c))/2; maior = (maiorab + maiobc + abs(maiorab - maiobc))/2; cout << maior << " eh o maior" << endl; }
24.538462
57
0.526646
wellmoot
5e060af528ae5dc70e1960cc003e7edfade4e194
5,779
cc
C++
src/vt/elm/elm_id_bits.cc
rbuch/vt
74c2e0cae3201dfbcbfda7644c354703ddaed6bb
[ "BSD-3-Clause" ]
26
2019-11-26T08:36:15.000Z
2022-02-15T17:13:21.000Z
src/vt/elm/elm_id_bits.cc
rbuch/vt
74c2e0cae3201dfbcbfda7644c354703ddaed6bb
[ "BSD-3-Clause" ]
1,215
2019-09-09T14:31:33.000Z
2022-03-30T20:20:14.000Z
src/vt/elm/elm_id_bits.cc
rbuch/vt
74c2e0cae3201dfbcbfda7644c354703ddaed6bb
[ "BSD-3-Clause" ]
12
2019-09-08T00:03:05.000Z
2022-02-23T21:28:35.000Z
/* //@HEADER // ***************************************************************************** // // elm_id_bits.cc // DARMA/vt => Virtual Transport // // Copyright 2019-2021 National Technology & Engineering Solutions of Sandia, LLC // (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. // // Questions? Contact darma@sandia.gov // // ***************************************************************************** //@HEADER */ #include "vt/elm/elm_id_bits.h" #include "vt/utils/bits/bits_common.h" #include "vt/objgroup/common.h" #include "vt/objgroup/proxy/proxy_bits.h" #include "vt/vrt/collection/balance/node_stats.h" namespace vt { namespace elm { /*static*/ ElementIDStruct ElmIDBits::createCollection( bool migratable, NodeType curr_node ) { auto const seq_id = theNodeStats()->getNextElm(); auto const home_node = theContext()->getNode(); return createCollectionImpl(migratable, seq_id, home_node, curr_node); } /*static*/ ElementIDStruct ElmIDBits::createCollectionImpl( bool migratable, ElementIDType seq_id, NodeType home_node, NodeType curr_node ) { ElementIDType ret = 0; setCollectionID(ret, migratable, seq_id, home_node); return ElementIDStruct{ret, curr_node}; } /*static*/ ElementIDStruct ElmIDBits::createObjGroup( ObjGroupProxyType proxy, NodeType node ) { ElementIDType ret = 0; setObjGroup(ret, proxy, node); auto const this_node = theContext()->getNode(); return ElementIDStruct{ret, this_node}; } /*static*/ ElementIDStruct ElmIDBits::createBareHandler(NodeType node) { ElementIDType ret = 0; BitPackerType::setField<eElmIDProxyBitsObjGroup::Control, num_control_bits>( ret, BareHandler ); constexpr auto num_node_bits = BitCounterType<NodeType>::value; BitPackerType::setField<eElmIDProxyBitsNonObjGroup::Node, num_node_bits>( ret, node ); return ElementIDStruct{ret, node}; } /*static*/ void ElmIDBits::setObjGroup( ElementIDType& id, ObjGroupProxyType proxy, NodeType node ) { BitPackerType::setField<eElmIDProxyBitsObjGroup::Control, num_control_bits>( id, ObjGroup ); objgroup::proxy::ObjGroupProxy::setNode(proxy, node); constexpr auto proxy_bits = BitCounterType<ObjGroupProxyType>::value - 2; BitPackerType::setField<eElmIDProxyBitsObjGroup::ObjGroupID, proxy_bits>( id, proxy ); } /*static*/ void ElmIDBits::setCollectionID( ElementIDType& id, bool migratable, ElementIDType seq_id, NodeType node ) { BitPackerType::setField<eElmIDProxyBitsNonObjGroup::Control2, num_control_bits>( id, migratable ? CollectionMigratable : CollectionNonMigratable ); constexpr auto num_node_bits = BitCounterType<NodeType>::value; BitPackerType::setField<eElmIDProxyBitsNonObjGroup::Node, num_node_bits>( id, node ); BitPackerType::setField<eElmIDProxyBitsNonObjGroup::ID, elm_id_num_bits>( id, seq_id ); } /*static*/ eElmIDControlBits ElmIDBits::getControlBits(ElementIDType id) { auto const n = num_control_bits; auto r = BitPackerType::getField<eElmIDProxyBitsObjGroup::Control, n, int>(id); return static_cast<eElmIDControlBits>(r); } /*static*/ bool ElmIDBits::isMigratable(ElementIDType id) { auto const ctrl = getControlBits(id); return not ( ctrl == BareHandler or ctrl == ObjGroup or ctrl == CollectionNonMigratable ); } /*static*/ NodeType ElmIDBits::getNode(ElementIDType id) { auto const ctrl = getControlBits(id); if (ctrl == ObjGroup) { auto const proxy = ElmIDBits::getObjGroupProxy(id, true); return objgroup::proxy::ObjGroupProxy::getNode(proxy); } else { constexpr auto num_node_bits = BitCounterType<NodeType>::value; return BitPackerType::getField< eElmIDProxyBitsNonObjGroup::Node, num_node_bits, NodeType >(id); } } /*static*/ ObjGroupProxyType ElmIDBits::getObjGroupProxy( ElementIDType id, bool include_node ) { constexpr auto proxy_bits = BitCounterType<ObjGroupProxyType>::value - 2; auto proxy = BitPackerType::getField< eElmIDProxyBitsObjGroup::ObjGroupID, proxy_bits, ObjGroupProxyType >(id); if (not include_node) { objgroup::proxy::ObjGroupProxy::setNode(proxy, 0); } return proxy; } }} /* end namespace vt::elm */
36.808917
82
0.725731
rbuch
5e06b9b826daed5b9762f2d3de78e595b74df6a1
1,313
hpp
C++
osm2pgsql/src/pgsql-helper.hpp
traitor6789/osm-tile-server
bddcfabee825c0e176d2037cad9c6cf06895beb8
[ "Apache-2.0" ]
null
null
null
osm2pgsql/src/pgsql-helper.hpp
traitor6789/osm-tile-server
bddcfabee825c0e176d2037cad9c6cf06895beb8
[ "Apache-2.0" ]
null
null
null
osm2pgsql/src/pgsql-helper.hpp
traitor6789/osm-tile-server
bddcfabee825c0e176d2037cad9c6cf06895beb8
[ "Apache-2.0" ]
null
null
null
#ifndef OSM2PGSQL_PGSQL_HELPER_HPP #define OSM2PGSQL_PGSQL_HELPER_HPP /** * SPDX-License-Identifier: GPL-2.0-or-later * * This file is part of osm2pgsql (https://osm2pgsql.org/). * * Copyright (C) 2006-2022 by the osm2pgsql developer community. * For a full list of authors see the git log. */ #include "osmtypes.hpp" #include <string> class pg_conn_t; class pg_result_t; /** * Iterate over the result from a pgsql query and generate a list of all the * ids from the first column. * * \param result The result to iterate over. * \returns A list of ids. */ idlist_t get_ids_from_result(pg_result_t const &result); idlist_t get_ids_from_db(pg_conn_t const *db_connection, char const *stmt, osmid_t id); void create_geom_check_trigger(pg_conn_t *db_connection, std::string const &schema, std::string const &table, std::string const &geom_column); void drop_geom_check_trigger(pg_conn_t *db_connection, std::string const &schema, std::string const &table); void analyze_table(pg_conn_t const &db_connection, std::string const &schema, std::string const &name); #endif // OSM2PGSQL_PGSQL_HELPER_HPP
28.543478
77
0.647372
traitor6789
5e0739249f2e15624ab33e99eb886148fb7ebede
224
hpp
C++
glm_mat_1/glm/mat1x1.hpp
xaedes/glm_mat_1
e80e788a0704eeb62a89c399faedb770f76ea635
[ "MIT" ]
null
null
null
glm_mat_1/glm/mat1x1.hpp
xaedes/glm_mat_1
e80e788a0704eeb62a89c399faedb770f76ea635
[ "MIT" ]
null
null
null
glm_mat_1/glm/mat1x1.hpp
xaedes/glm_mat_1
e80e788a0704eeb62a89c399faedb770f76ea635
[ "MIT" ]
null
null
null
/// @ref core /// @file glm/mat1x1.hpp #pragma once #include "./ext/matrix_double1x1.hpp" #include "./ext/matrix_double1x1_precision.hpp" #include "./ext/matrix_float1x1.hpp" #include "./ext/matrix_float1x1_precision.hpp"
22.4
47
0.745536
xaedes
5e0844ba5c835c32c4abf54e673058268ab71c9e
2,989
cpp
C++
modules/juce_gui_basics/application/juce_Application.cpp
luzpaz/JUCE
2b16c1b94c90d0db3072f6dc9da481a9484d0435
[ "ISC" ]
null
null
null
modules/juce_gui_basics/application/juce_Application.cpp
luzpaz/JUCE
2b16c1b94c90d0db3072f6dc9da481a9484d0435
[ "ISC" ]
null
null
null
modules/juce_gui_basics/application/juce_Application.cpp
luzpaz/JUCE
2b16c1b94c90d0db3072f6dc9da481a9484d0435
[ "ISC" ]
null
null
null
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2022 - Raw Material Software Limited JUCE is an open source library subject to commercial or open-source licensing. By using JUCE, you agree to the terms of both the JUCE 7 End-User License Agreement and JUCE Privacy Policy. End User License Agreement: www.juce.com/juce-7-licence Privacy Policy: www.juce.com/juce-privacy-policy Or: You may also use this code under the terms of the GPL v3 (see www.gnu.org/licenses). JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ namespace juce { JUCEApplication::JUCEApplication() {} JUCEApplication::~JUCEApplication() {} //============================================================================== JUCEApplication* JUCE_CALLTYPE JUCEApplication::getInstance() noexcept { return dynamic_cast<JUCEApplication*> (JUCEApplicationBase::getInstance()); } bool JUCEApplication::moreThanOneInstanceAllowed() { return true; } void JUCEApplication::anotherInstanceStarted (const String&) {} void JUCEApplication::suspended() {} void JUCEApplication::resumed() {} void JUCEApplication::systemRequestedQuit() { quit(); } void JUCEApplication::unhandledException (const std::exception*, const String&, int) { jassertfalse; } //============================================================================== ApplicationCommandTarget* JUCEApplication::getNextCommandTarget() { return nullptr; } void JUCEApplication::getAllCommands (Array<CommandID>& commands) { commands.add (StandardApplicationCommandIDs::quit); } void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result) { if (commandID == StandardApplicationCommandIDs::quit) { result.setInfo (TRANS("Quit"), TRANS("Quits the application"), "Application", 0); result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0)); } } bool JUCEApplication::perform (const InvocationInfo& info) { if (info.commandID == StandardApplicationCommandIDs::quit) { systemRequestedQuit(); return true; } return false; } //============================================================================== #if JUCE_MAC extern void juce_initialiseMacMainMenu(); #endif bool JUCEApplication::initialiseApp() { if (JUCEApplicationBase::initialiseApp()) { #if JUCE_MAC juce_initialiseMacMainMenu(); // (needs to get the app's name) #endif return true; } return false; } } // namespace juce
28.466667
97
0.587822
luzpaz
5e09b2450d47e1d64e3ffd18f678a7a25bab70cf
707
cpp
C++
Code/Score/Score.cpp
4rlenrey/JumpHigh
af5f24c8b8fd2c46bb80f3b3e9755b419964d3da
[ "MIT" ]
8
2020-09-23T19:32:48.000Z
2022-01-18T16:43:47.000Z
Code/Score/Score.cpp
Haranoi17/JumpHigh
3cd5e47fb991d828e0843cf3bfb05511d2da7f9e
[ "MIT" ]
null
null
null
Code/Score/Score.cpp
Haranoi17/JumpHigh
3cd5e47fb991d828e0843cf3bfb05511d2da7f9e
[ "MIT" ]
5
2020-09-23T19:32:51.000Z
2022-03-11T06:18:07.000Z
#include "Score/Score.h" #include "GameObject/GameObject.hpp" #include <string> #include <SFML/Graphics.hpp> sf::Font Score::font; Score::Score(GameObject& player, sf::View& viev) : _playerS{player}, _viewS{viev} { _score = 0; text.setString("0"); text.setFont(font); text.setPosition(100, 500); text.setCharacterSize(35); text.setStyle(sf::Text::Bold); text.setFillColor(sf::Color::White); } void Score::update() { s = "Score: "; s.append(std::to_string(_score)); if (_score < -(_playerS.getPosition().y)) _score = -(_playerS.getPosition().y); text.setString(s); text.setPosition(10, _viewS.getCenter().y - 350); }
22.806452
56
0.618105
4rlenrey
5e09d6c8f8c2da4ef076eff09e009e1844532213
4,965
cpp
C++
lang_service/java/com/intel/daal/data_management/data_source/data_source.cpp
h2oai/daal
d49815df3040f3872a1fdb9dc99ee86148e4494e
[ "Apache-2.0" ]
2
2020-05-16T00:57:44.000Z
2020-05-17T15:56:38.000Z
lang_service/java/com/intel/daal/data_management/data_source/data_source.cpp
afcarl/daal
d49815df3040f3872a1fdb9dc99ee86148e4494e
[ "Apache-2.0" ]
null
null
null
lang_service/java/com/intel/daal/data_management/data_source/data_source.cpp
afcarl/daal
d49815df3040f3872a1fdb9dc99ee86148e4494e
[ "Apache-2.0" ]
3
2017-09-29T19:51:42.000Z
2020-12-03T09:09:48.000Z
/* file: data_source.cpp */ /******************************************************************************* * Copyright 2014-2017 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "JDataSource.h" #include "numeric_table.h" #include "data_source.h" using namespace daal; using namespace daal::data_management; #define NO_PARAMS_FUNCTION_MAP_0ARG(jType,jFunc,cFunc) \ JNIEXPORT jType JNICALL Java_com_intel_daal_data_1management_data_1source_DataSource_##jFunc \ (JNIEnv *env, jobject obj, jlong ptr) \ { \ return(jType)((DataSource *)ptr)->cFunc(); \ } \ #define NO_PARAMS_FUNCTION_MAP_1ARG(jType,jFunc,cFunc,arg1,jArg1type,cArg1type) \ JNIEXPORT jType JNICALL Java_com_intel_daal_data_1management_data_1source_DataSource_##jFunc \ (JNIEnv *env, jobject obj, jlong ptr, jArg1type arg1) \ { \ return(jType)((DataSource *)ptr)->cFunc((cArg1type)arg1); \ } \ #define NO_PARAMS_FUNCTION_MAP_2ARG(jType,jFunc,cFunc,arg1,jArg1type,cArg1type,arg2,jArg2type,cArg2type) \ JNIEXPORT jType JNICALL Java_com_intel_daal_data_1management_data_1source_DataSource_##jFunc \ (JNIEnv *env, jobject obj, jlong ptr, jArg1type arg1, jArg2type arg2) \ { \ return(jType)((DataSource *)ptr)->cFunc((cArg1type)arg1, (cArg2type)arg2); \ } \ NO_PARAMS_FUNCTION_MAP_0ARG(void, cCreateDictionaryFromContext, createDictionaryFromContext); NO_PARAMS_FUNCTION_MAP_0ARG(jlong, cGetNumberOfColumns, getNumberOfColumns ); NO_PARAMS_FUNCTION_MAP_0ARG(jlong, cGetNumberOfAvailableRows, getNumberOfAvailableRows ); NO_PARAMS_FUNCTION_MAP_0ARG(void, cAllocateNumericTable, allocateNumericTable ); //NO_PARAMS_FUNCTION_MAP_0ARG(jlong,cGetNumericTable, getNumericTable ); NO_PARAMS_FUNCTION_MAP_0ARG(void, cFreeNumericTable, freeNumericTable ); NO_PARAMS_FUNCTION_MAP_0ARG(jlong, cLoadDataBlock0Inputs, loadDataBlock); NO_PARAMS_FUNCTION_MAP_1ARG(jlong, cLoadDataBlock, loadDataBlock, maxRows, jlong, size_t); /* * Class: com_intel_daal_data_1management_data_1source_DataSource * Method: cDispose * Signature:(J)V */ JNIEXPORT void JNICALL Java_com_intel_daal_data_1management_data_1source_DataSource_cDispose (JNIEnv *env, jobject obj, jlong ptr) { delete(DataSource *)ptr; } JNIEXPORT jlong JNICALL Java_com_intel_daal_data_1management_data_1source_DataSource_cGetNumericTable(JNIEnv *env, jobject obj, jlong ptr) { NumericTablePtr *spnt = new NumericTablePtr(); *spnt = ((DataSource *)ptr)->getNumericTable(); return (jlong)((SerializationIfacePtr *)spnt); } JNIEXPORT jlong JNICALL Java_com_intel_daal_data_1management_data_1source_DataSource_cLoadDataBlock3Inputs (JNIEnv *env, jobject obj, jlong ptr, jlong maxRows, jlong offset, jlong fullRows) { return(jlong)((DataSource *)ptr)->loadDataBlock((size_t)maxRows, (size_t)offset, (size_t)fullRows); } JNIEXPORT jlong JNICALL Java_com_intel_daal_data_1management_data_1source_DataSource_cLoadDataBlockNt (JNIEnv *env, jobject obj, jlong ptr, jlong maxRows, jlong ntAddr) { NumericTable *tbl = ((NumericTablePtr *)ntAddr)->get(); return(jlong)((DataSource *)ptr)->loadDataBlock((size_t)maxRows, tbl); } JNIEXPORT jlong JNICALL Java_com_intel_daal_data_1management_data_1source_DataSource_cLoadDataBlockNt1Input (JNIEnv *env, jobject obj, jlong ptr, jlong ntAddr) { NumericTable *tbl = ((NumericTablePtr *)ntAddr)->get(); return(jlong)((DataSource *)ptr)->loadDataBlock(tbl); }
52.263158
138
0.609265
h2oai
5e0ab6796a85c1e80e991c232a4bdef1807a280e
1,353
cpp
C++
codeforces/C - Fly/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/C - Fly/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/C - Fly/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Jul/27/2018 15:45 * solution_verdict: Accepted language: GNU C++14 * run_time: 31 ms memory_used: 200 KB * problem: https://codeforces.com/contest/1011/problem/C ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e3; int n; double pay,a[N+2],b[N+2]; bool ok(double xx) { xx-=((pay+xx)/a[1]); if(xx<0.0)return false; for(int i=2;i<=n;i++) { xx-=((pay+xx)/b[i]); if(xx<0.0)return false; xx-=((pay+xx)/a[i]); if(xx<0.0)return false; } xx-=((pay+xx)/b[1]); if(xx<0.0)return false; return true; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin>>n>>pay; for(int i=1;i<=n;i++) cin>>a[i]; for(int i=1;i<=n;i++) cin>>b[i]; double lo=0.0,hi=1000000000.0+100.0,md; for(int i=1;i<=100;i++) { md=(lo+hi)/2.0; if(ok(md))hi=md; else lo=md; } if(md>1000000000.0)cout<<-1<<endl; else cout<<setprecision(10)<<fixed<<md<<endl; return 0; }
28.787234
111
0.424242
kzvd4729
5e0b663a20e9d6da64d139f638dac59a3d3933af
1,483
cpp
C++
src/rewrite_pooling.cpp
pruthvistony/AMDMIGraphX
cf85b4c65d89b634fc50d586385c73839bb59bd0
[ "MIT" ]
null
null
null
src/rewrite_pooling.cpp
pruthvistony/AMDMIGraphX
cf85b4c65d89b634fc50d586385c73839bb59bd0
[ "MIT" ]
null
null
null
src/rewrite_pooling.cpp
pruthvistony/AMDMIGraphX
cf85b4c65d89b634fc50d586385c73839bb59bd0
[ "MIT" ]
null
null
null
#include <migraphx/rewrite_pooling.hpp> #include <migraphx/instruction.hpp> #include <migraphx/iterator_for.hpp> #include <migraphx/op/pooling.hpp> #include <migraphx/op/reshape.hpp> #include <migraphx/op/reduce_mean.hpp> #include <migraphx/program.hpp> namespace migraphx { inline namespace MIGRAPHX_INLINE_NS { void rewrite_pooling::apply(program& prog) const { for(auto ins : iterator_for(prog)) { if(ins->name() != "pooling") continue; if(ins->get_shape().lens().size() != 4) continue; if(ins->inputs().empty()) continue; auto&& s = ins->inputs().front()->get_shape(); if(not s.standard()) continue; auto&& op = any_cast<op::pooling>(ins->get_operator()); if(op.mode != "average") continue; if(op.padding[0] != 0 and op.padding[1] != 0) continue; if(op.stride[0] != 1 and op.stride[1] != 1) continue; if(s.lens()[2] != op.lengths[0] and s.lens()[3] != op.lengths[1]) continue; std::int64_t n = s.lens()[0]; std::int64_t c = s.lens()[1]; auto reshape = prog.insert_instruction(ins, op::reshape{{n * c, -1}}, ins->inputs().front()); auto pooling = prog.insert_instruction(ins, op::reduce_mean{{1}}, reshape); prog.replace_instruction(ins, op::reshape{{n, c, 1, 1}}, pooling); } } } // namespace MIGRAPHX_INLINE_NS } // namespace migraphx
32.955556
90
0.582603
pruthvistony
5e0bbd8b606f5f0fefed96f290e420d702ea993e
470
cpp
C++
sk4d/src/c/sk4d_svgcanvas.cpp
skia4delphi/skia
64806a3b12c226fb57d6befc4c0df5443533d220
[ "BSD-3-Clause" ]
5
2022-02-12T07:52:56.000Z
2022-03-10T23:55:51.000Z
sk4d/src/c/sk4d_svgcanvas.cpp
skia4delphi/skia
64806a3b12c226fb57d6befc4c0df5443533d220
[ "BSD-3-Clause" ]
null
null
null
sk4d/src/c/sk4d_svgcanvas.cpp
skia4delphi/skia
64806a3b12c226fb57d6befc4c0df5443533d220
[ "BSD-3-Clause" ]
2
2022-02-12T07:52:59.000Z
2022-03-03T03:06:23.000Z
/* * Copyright (c) 2011-2022 Google LLC. * Copyright (c) 2021-2022 Skia4Delphi Project. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/c/sk4d_svgcanvas.h" #include "src/c/sk4d_mapping.h" sk_canvas_t* sk4d_svgcanvas_make(const sk_rect_t* bounds, sk_wstream_t* w_stream, uint32_t flags) { return ToCanvas(SkSVGCanvas::Make(AsRect(*bounds), AsWStream(w_stream), flags).release()); }
31.333333
99
0.738298
skia4delphi
5e158800f0164ed23a9b6094b72b761bd164f377
1,710
cpp
C++
examples/example3.cpp
mambaru/wjson
48de30f1247564ab16c93fc824a14b182145ff90
[ "MIT" ]
21
2016-09-29T10:25:12.000Z
2020-07-07T23:19:51.000Z
examples/example3.cpp
mambaru/wjson
48de30f1247564ab16c93fc824a14b182145ff90
[ "MIT" ]
10
2016-11-17T09:09:35.000Z
2021-10-03T11:47:18.000Z
examples/example3.cpp
mambaru/wjson
48de30f1247564ab16c93fc824a14b182145ff90
[ "MIT" ]
6
2016-09-29T12:05:06.000Z
2022-02-17T13:05:18.000Z
#include <wjson/json.hpp> #include <iostream> #include <cstring> int main() { const char* english = "\"hello world!\""; const char* russian = "\"\\u041F\\u0440\\u0438\\u0432\\u0435\\u0442\\u0020\\u043C\\u0438\\u0440\\u0021\""; const char* chinese = "\"\\u4E16\\u754C\\u4F60\\u597D!\""; typedef char str_t[128]; typedef ::wjson::value< std::string, 128 >::serializer sser_t; typedef ::wjson::value< std::vector<char> >::serializer vser_t; typedef ::wjson::value< str_t >::serializer aser_t; std::string sstr; std::vector<char> vstr; str_t astr={'\0'}; // Десериализация sser_t()( sstr, english, english + std::strlen(english), fas_nullptr); vser_t()( vstr, russian, russian + std::strlen(russian), fas_nullptr); aser_t()( astr, chinese, chinese + std::strlen(chinese), fas_nullptr); // Результат std::cout << "English: " << sstr << "\tfrom JSON: " << english << std::endl; std::cout << "Russian: " << std::string(vstr.begin(), vstr.end() ) << "\tfrom JSON: " << russian << std::endl; std::cout << "Chinese: " << astr << "\tfrom JSON: " << chinese << std::endl; // Сериализация english в stdout std::cout << std::endl << "English JSON: "; sser_t()( sstr, std::ostream_iterator<char>( std::cout) ); std::cout << "\tfrom: " << sstr; // Сериализация russian в stdout std::cout << std::endl << "Russian JSON: "; vser_t()( vstr, std::ostream_iterator<char>( std::cout) ); std::cout << "\tfrom: " << std::string(vstr.begin(), vstr.end() ); // Сериализация chinese в stdout std::cout << std::endl << "Chinese JSON: "; aser_t()( astr, std::ostream_iterator<char>( std::cout) ); std::cout << "\tfrom: " << astr; std::cout << std::endl; }
37.173913
112
0.615205
mambaru
5e15f4b108695d25722984aff32f1d1168600923
4,833
cpp
C++
src/hardware/encoders/quadraturecounter.cpp
Bormachine-Learning/embedded
165daf847fe9c2a7bcc17c7aee4c5e28b3cf4055
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/hardware/encoders/quadraturecounter.cpp
Bormachine-Learning/embedded
165daf847fe9c2a7bcc17c7aee4c5e28b3cf4055
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/hardware/encoders/quadraturecounter.cpp
Bormachine-Learning/embedded
165daf847fe9c2a7bcc17c7aee4c5e28b3cf4055
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/** Copyright 2019 Bosch Engineering Center Cluj and BFMC organizers Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. * @file quadratureencoder.cpp * @author RBRO/PJ-IU * @brief * @version 0.1 * @date 2018-10-23 * * @copyright Copyright (c) 2018 * */ #include <hardware/encoders/quadraturecounter.hpp> namespace hardware::drivers{ CQuadratureCounter_TIM4 *CQuadratureCounter_TIM4::m_instance = 0; CQuadratureCounter_TIM4::CQuadratureCounter_TIM4_Destroyer CQuadratureCounter_TIM4::m_destroyer; /** * @brief Setter function for the singelton object. * * @param pSingObj - singleton object address */ void CQuadratureCounter_TIM4::CQuadratureCounter_TIM4_Destroyer::SetSingleton(CQuadratureCounter_TIM4* pSingObj){ m_singleton = pSingObj; } /** * @brief Destroy the singelton object. * */ CQuadratureCounter_TIM4::CQuadratureCounter_TIM4_Destroyer::~CQuadratureCounter_TIM4_Destroyer(){ delete m_singleton; } /** * @brief * It verifies the existence of the singleton object. It creates a new instance when it's necessary and return the address of instance. * It initializes all parameter by appling method 'initialize'. * * @return The address of the singleton object */ CQuadratureCounter_TIM4* CQuadratureCounter_TIM4::Instance(){ if(!CQuadratureCounter_TIM4::m_instance){ CQuadratureCounter_TIM4::m_instance = new CQuadratureCounter_TIM4; m_instance->initialize(); CQuadratureCounter_TIM4::m_destroyer.SetSingleton(m_instance); } return CQuadratureCounter_TIM4::m_instance; } /** * @brief Initialize the parameter of the object. * * It configures all register, for timer TIM4 decodes the quadrature encoder signal. */ void CQuadratureCounter_TIM4::initialize(){ //PB6 PB7 aka D10 MORPHO_PB7 // Enable clock for GPIOA RCC->AHB1ENR |= RCC_AHB1ENR_GPIOBEN; //stm32f4xx.h GPIOB->MODER |= GPIO_MODER_MODER6_1 | GPIO_MODER_MODER7_1; //PB6 & PB7 as Alternate Function /*!< GPIO port mode register, Address offset: 0x00 */ GPIOB->OTYPER |= GPIO_OTYPER_OT_6 | GPIO_OTYPER_OT_7; //PB6 & PB7 as Inputs /*!< GPIO port output type register, Address offset: 0x04 */ GPIOB->OSPEEDR |= GPIO_OSPEEDER_OSPEEDR6 | GPIO_OSPEEDER_OSPEEDR7; //Low speed /*!< GPIO port output speed register, Address offset: 0x08 */ GPIOB->PUPDR |= GPIO_PUPDR_PUPDR6_1 | GPIO_PUPDR_PUPDR7_1; //Pull Down /*!< GPIO port pull-up/pull-down register, Address offset: 0x0C */ GPIOB->AFR[0] |= 0x22000000; //AF02 for PB6 & PB7 /*!< GPIO alternate function registers, Address offset: 0x20-0x24 */ GPIOB->AFR[1] |= 0x00000000; //nibbles here refer to gpio8..15 /*!< GPIO alternate function registers, Address offset: 0x20-0x24 */ // configure TIM4 as Encoder input // Enable clock for TIM4 // __TIM4_CLK_ENABLE(); RCC->APB1ENR |= RCC_APB1ENR_TIM4EN; TIM4->CR1 = 0x0001; // CEN(Counter ENable)='1' < TIM control register 1 TIM4->SMCR = TIM_ENCODERMODE_TI12; // < TIM slave mode control register //TIM_ENCODERMODE_TI1 input 1 edges trigger count //TIM_ENCODERMODE_TI2 input 2 edges trigger count //TIM_ENCODERMODE_TI12 all edges trigger count TIM4->CCMR1 = 0xF1F1; // CC1S='01' CC2S='01' < TIM capture/compare mode register 1 //0xF nibble sets up filter TIM4->CCMR2 = 0x0000; // < TIM capture/compare mode register 2 TIM4->CCER = TIM_CCER_CC1E | TIM_CCER_CC2E; // < TIM capture/compare enable register TIM4->PSC = 0x0000; // Prescaler = (0+1) < TIM prescaler TIM4->ARR = 0xffff; // reload at 0xfffffff < TIM auto-reload register TIM4->CNT = 0x0000; //reset the counter before we use it } /** * @brief Get the position of encoder. * * It returns the last counted value by the timer. * */ int16_t CQuadratureCounter_TIM4::getCount(){ return TIM4->CNT; } /** * @brief Reset the value of the counter to zero value. */ void CQuadratureCounter_TIM4::reset(){ TIM4->CNT = 0; } }; // namespace hardware::drivers
38.357143
178
0.671633
Bormachine-Learning
5e18d4c6e941dd29af5ab99b246c9dfd9e63beb2
12,511
cpp
C++
src/ompl/base/spaces/src/ClothoidStateSpace.cpp
tigerk0430/DesiredOrientationRRT
c62a9cf2c472380937d0a0ab379b5f9140767f51
[ "BSD-3-Clause" ]
2
2018-07-08T11:56:04.000Z
2019-02-14T12:14:35.000Z
src/ompl/base/spaces/src/ClothoidStateSpace.cpp
edward0im/DesiredOrientationRRT
c62a9cf2c472380937d0a0ab379b5f9140767f51
[ "BSD-3-Clause" ]
1
2019-08-03T03:42:55.000Z
2019-08-03T03:42:55.000Z
src/ompl/base/spaces/src/ClothoidStateSpace.cpp
edward0im/DesiredOrientationRRT
c62a9cf2c472380937d0a0ab379b5f9140767f51
[ "BSD-3-Clause" ]
2
2018-06-11T00:49:39.000Z
2018-10-03T07:09:30.000Z
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2010, Rice University * 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 Rice University 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. *********************************************************************/ /* Author: Seho Shin */ #include "ompl/base/spaces/ClothoidStateSpace.h" #include "ompl/base/SpaceInformation.h" #include "ompl/util/Exception.h" #include <queue> #include <boost/math/constants/constants.hpp> #include "ompl/tools/config/MagicConstants.h" #include <cstring> using namespace std; using namespace ompl::base; namespace { const double twopi = 2. * boost::math::constants::pi<double>(); const double pi = boost::math::constants::pi<double>(); const double CLOTHOID_ZERO = -1e-9; //[0~2pi] double conv2pi(double x){ x = fmod(x,twopi); if (x < 0) x += twopi; return x; } //[-pi,pi] double convpi(double x){ x = fmod(x + pi,twopi); if (x < 0) x += twopi; return x - pi; } inline double mod2pi(double x) { if (x<0 && x>CLOTHOID_ZERO) return 0; return x - twopi * floor(x / twopi); } }; ompl::base::State* ompl::base::ClothoidStateSpace::allocState() const { StateType *state = new StateType(); allocStateComponents(state); return state; } void ompl::base::ClothoidStateSpace::freeState(State *state) const { CompoundStateSpace::freeState(state); } void ompl::base::ClothoidStateSpace::registerProjections() { class ClothoidDefaultProjection : public ProjectionEvaluator { public: ClothoidDefaultProjection(const StateSpace *space) : ProjectionEvaluator(space) { } virtual unsigned int getDimension() const { return 2; } virtual void defaultCellSizes() { cellSizes_.resize(2); bounds_ = space_->as<ClothoidStateSpace>()->getBounds(); cellSizes_[0] = (bounds_.high[0] - bounds_.low[0]) / magic::PROJECTION_DIMENSION_SPLITS; cellSizes_[1] = (bounds_.high[1] - bounds_.low[1]) / magic::PROJECTION_DIMENSION_SPLITS; //cellSizes_[2] = (bounds_.high[2] - bounds_.low[2]) / magic::PROJECTION_DIMENSION_SPLITS; } virtual void project(const State *state, EuclideanProjection &projection) const { memcpy(&projection(0), state->as<ClothoidStateSpace::StateType>()->as<RealVectorStateSpace::StateType>(0)->values, 2* sizeof(double)); } }; registerDefaultProjection(ProjectionEvaluatorPtr(dynamic_cast<ProjectionEvaluator*>(new ClothoidDefaultProjection(this)))); } double ompl::base::ClothoidStateSpace::distance(const State *state1, const State *state2) const { double W0 = weight_[0]; double W1 = weight_[1]; double W2 = weight_[2]; const StateType *s1 = static_cast<const StateType*>(state1); const StateType *s2 = static_cast<const StateType*>(state2); double x1 = s1->getX(), y1 = s1->getY(), th1 = s1->getYaw(); double x2 = s2->getX(), y2 = s2->getY(), th2 = s2->getYaw(); if( x1 == x2 && y1 == y2 && th1 == th2 ) return 0.; if( !CheckRange(s1, s2) ) return 99999.0; if (isReversable_) { ClothoidPath pathForward = clothoid(state1, state2); ClothoidPath pathReverse = clothoid(state2, state1); //When searching in the forward direction, it should be compared with the // curvature of the first node of the candidate clothoid. double clothoid_k = pathForward.k_; double clothoid_l = pathForward.length(); double costF = W0*clothoid_l + W1*fabs(s1->getK()-clothoid_k); //When searching in the reverse direction, it should be compared with //the curvature of the last node of the candidate clothoid. clothoid_k = pathReverse.k_+pathReverse.dk_*pathReverse.l_; clothoid_l = pathReverse.length(); double costR = W2*(W0*clothoid_l + W1*fabs(s1->getK()-clothoid_k)); return std::min(costF, costR); } else { ClothoidPath path = clothoid(state1, state2); return W0*path.length()+W1*fabs(s1->getK()-path.k_); } } void ompl::base::ClothoidStateSpace::interpolate(const State *from, const State *to, const double t, State *state) const { bool firstTime = true; Clothoid::ClothoidCurve cc; ClothoidPath path(cc); interpolate(from, to, t, firstTime, path, state); } void ompl::base::ClothoidStateSpace::interpolate(const State *from, const State *to, const double t, bool &firstTime, ClothoidPath &path, State *state) const { if (firstTime) { if (t>=1.) { if (to != state) copyState(state, to); return; } if (t<=0.) { if (from != state) copyState(state, from); return; } path = clothoid(from, to); if (isReversable_) // should be true in vehicle case - commented by shinsh { double W0 = weight_[0]; double W1 = weight_[1]; double W2 = weight_[2]; ClothoidPath path2(clothoid(to, from)); const StateType *s1 = static_cast<const StateType*>(from); double costF = W0*path.length()+W1*fabs(s1->getK()-path.k_); double rev_k = path2.k_+path2.dk_*path2.l_; double costR = (W0*path2.length()+W1*fabs(s1->getK()-rev_k))*W2; if (costR < costF) { path2.reverse_ = true; path = path2; } } firstTime = false; } //const StateType *s1 = static_cast<const StateType*>(from); //const StateType *s2 = static_cast<const StateType*>(to); //cout << s1->getX() << " " << s1->getY() << " " <<s1->getYaw()<< endl; //cout << s2->getX() << " " << s2->getY() << " " <<s2->getYaw()<< endl; interpolate(from, path, t, state); } void ompl::base::ClothoidStateSpace::interpolate(const State *from, const ClothoidPath &path, double t, State *state) const { StateType *s = allocState()->as<StateType>(); double seg = t * path.length(); Clothoid::valueType theta; Clothoid::valueType kappa; Clothoid::valueType x; Clothoid::valueType y; if (path.reverse_) { seg = path.length()-seg; path.cc_.eval(seg, theta, kappa, x, y); // state->as<StateType>()->setYaw(conv2pi(conv2pi(theta)-pi)); } else { path.cc_.eval(seg, theta, kappa, x, y); } state->as<StateType>()->setX(x); state->as<StateType>()->setY(y); getSubspace(1)->enforceBounds(s->as<SO2StateSpace::StateType>(1)); state->as<StateType>()->setYaw(theta); state->as<StateType>()->setK(kappa); freeState(s); //cout << x << " " << y << " " <<theta << endl; //getchar(); } ompl::base::ClothoidStateSpace::ClothoidPath ompl::base::ClothoidStateSpace::clothoid(const State *state1, const State *state2) const { Clothoid::ClothoidCurve cc; const StateType *s1 = static_cast<const StateType*>(state1); const StateType *s2 = static_cast<const StateType*>(state2); double x1 = s1->getX(), y1 = s1->getY(), th1 = convpi(s1->getYaw()); double x2 = s2->getX(), y2 = s2->getY(), th2 = convpi(s2->getYaw()); // cout << x1 << " " << y1 << " " << th1 << " " << x2 <<" " << y2 << " " << // th2 << endl; cc.setup_G1(x1, y1, th1, x2, y2, th2); ompl::base::ClothoidStateSpace::ClothoidPath path(cc); return path; } bool ompl::base::ClothoidStateSpace::CheckRange(const State *state1, const State *state2) const { const StateType *s1 = static_cast<const StateType*>(state1); const StateType *s2 = static_cast<const StateType*>(state2); double x1 = s1->getX(), y1 = s1->getY(); double x2 = s2->getX(), y2 = s2->getY(); if( sqrt( (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)) < 1.0 ) { return false; } else { return true; } } void ompl::base::ClothoidMotionValidator::defaultSettings() { stateSpace_ = dynamic_cast<ClothoidStateSpace*>(si_->getStateSpace().get()); if (!stateSpace_) throw Exception("No state space for motion validator"); } bool ompl::base::ClothoidMotionValidator::checkMotion(const State *s1, const State *s2, std::pair<State*, double> &lastValid) const { /* assume motion starts in a valid configuration so s1 is valid */ if( !stateSpace_->CheckRange(s1, s2) ) return false; bool result = true, firstTime = true; Clothoid::ClothoidCurve cc; ClothoidStateSpace::ClothoidPath path(cc); int nd = stateSpace_->validSegmentCount(s1, s2); nd = 30; if (nd > 1) { /* temporary storage for the checked state */ State *test = si_->allocState(); for (int j = 1 ; j < nd ; ++j) { stateSpace_->interpolate(s1, s2, (double)j / (double)nd, firstTime, path, test); if (!si_->isValid(test)) { lastValid.second = (double)(j - 1) / (double)nd; if (lastValid.first) stateSpace_->interpolate(s1, s2, lastValid.second, firstTime, path, lastValid.first); result = false; break; } } si_->freeState(test); } if (result) if (!si_->isValid(s2)) { lastValid.second = (double)(nd - 1) / (double)nd; if (lastValid.first) stateSpace_->interpolate(s1, s2, lastValid.second, firstTime, path, lastValid.first); result = false; } if (result) valid_++; else invalid_++; return result; } bool ompl::base::ClothoidMotionValidator::checkMotion(const State *s1, const State *s2) const { /* assume motion starts in a valid configuration so s1 is valid */ if( !stateSpace_->CheckRange(s1, s2) ) return false; // if (!si_->isValid(s2)) // return false; bool result = true, firstTime = true; Clothoid::ClothoidCurve cc; ClothoidStateSpace::ClothoidPath path(cc); int nd = stateSpace_->validSegmentCount(s1, s2); nd = 30; /* initialize the queue of test positions */ std::queue< std::pair<int, int> > pos; if (nd >= 2) { pos.push(std::make_pair(1, nd - 1)); /* temporary storage for the checked state */ State *test = si_->allocState(); /* repeatedly subdivide the path segment in the middle (and check the middle) */ while (!pos.empty()) { std::pair<int, int> x = pos.front(); int mid = (x.first + x.second) / 2; stateSpace_->interpolate(s1, s2, (double)mid / (double)nd, firstTime, path, test); if (!si_->isValid(test)) { result = false; break; } pos.pop(); if (x.first < mid) pos.push(std::make_pair(x.first, mid - 1)); if (x.second > mid) pos.push(std::make_pair(mid + 1, x.second)); } si_->freeState(test); } if (result) valid_++; else invalid_++; return result; }
30.002398
131
0.612101
tigerk0430