hexsha
stringlengths
40
40
size
int64
22
2.4M
ext
stringclasses
5 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
260
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
260
max_issues_repo_name
stringlengths
5
109
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
260
max_forks_repo_name
stringlengths
5
109
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
22
2.4M
avg_line_length
float64
5
169k
max_line_length
int64
5
786k
alphanum_fraction
float64
0.06
0.95
matches
listlengths
1
11
57368af2169e93ee4c6f3f5ba73dfebb3cd60d2a
746
h
C
extern/firebreath/sources/ActiveXPlugin/axutil.h
untgames/funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
7
2016-03-30T17:00:39.000Z
2017-03-27T16:04:04.000Z
extern/firebreath/sources/ActiveXPlugin/axutil.h
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2017-11-21T11:25:49.000Z
2018-09-20T17:59:27.000Z
extern/firebreath/sources/ActiveXPlugin/axutil.h
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2016-11-29T15:18:40.000Z
2017-03-27T16:04:08.000Z
/**********************************************************\ Original Author: Georg Fritzsche Created: Sept 17, 2009 License: Dual license model; choose one of two: New BSD License http://www.opensource.org/licenses/bsd-license.php - or - GNU Lesser General Public License, version 2.1 http://www.gnu.org/licenses/lgpl-2.1.html Copyright 2009 Richard Bateman, Firebreath development team \**********************************************************/ #include "Win/win_common.h" class FbPerUserRegistration { public: FbPerUserRegistration(bool perUser = true); ~FbPerUserRegistration(); private: #if _MSC_VER < 1500 HKEY m_hkey; #endif };
27.62963
63
0.542895
[ "model" ]
5737e0834f9253a3ced7fdf3fd34a5513165685f
2,018
h
C
include/mylibrary/engine.h
CS126SP20/final-project-jananir2
74e0799403fbd904ed99979b18407e654a0725e4
[ "MIT" ]
null
null
null
include/mylibrary/engine.h
CS126SP20/final-project-jananir2
74e0799403fbd904ed99979b18407e654a0725e4
[ "MIT" ]
null
null
null
include/mylibrary/engine.h
CS126SP20/final-project-jananir2
74e0799403fbd904ed99979b18407e654a0725e4
[ "MIT" ]
null
null
null
// // Created by janan on 5/2/2020. // #ifndef FINALPROJECT_ENGINE_H #define FINALPROJECT_ENGINE_H #include <vector> #include <csv2/reader.hpp> #include <mylibrary/setup.h> namespace mylibrary { class Engine { public: /** Creates an engine with 4 options for trivia quizzes the user can take */ Engine(std::string file1, std::string file2, std::string file3, std::string file4); /** Takes in the user's answer choice for the current question and stores it * in the user_answers vector */ void SetAnswerChoice(int choice); /** Returns the correct answer for the question specified by the number * passed in */ std::string RetrieveAnswer(int num); /** Returns the question and answer choices specified by the number * passed in */ std::vector<std::string> RetrieveQuestion(int num); /** Gets the index of the current question */ int GetCurrQuestionIndex(); /** Decreases the index of the current question by 1 */ void DecCurrQuestion(); /** Increases the index of the current question by 1 */ void IncCurrQuestion(); /** Returns whether the current question is the last question */ bool CheckIsLastQuestion (); /** Returns whether the choice passed in is the one the user selected */ bool CheckIsSelected(int choice); /** Returns the score the user got on the quiz */ double GetScore(); /** Takes in the quiz the user chose to take and passes it to the * setup class */ void HandleQuizChoice(int choice); /** Checks whether the quiz the user chose is valid */ bool CheckIsValid(); /** Resets the engine */ void ResetEngine(); private: /** Checks and returns how many answers the user got correct */ double CheckAnswers(); private: Setup setup_; int curr_question; std::vector<std::string> user_answer; std::string filename1; std::string filename2; std::string filename3; std::string filename4; }; } #endif // FINALPROJECT_ENGINE_H
33.081967
80
0.679386
[ "vector" ]
5748b0af9057d0e486c43426a510087526cfd16b
1,022
h
C
src/cd_engine.h
ARandomOWL/verimap
0da478f7289d5b64e74b2821cf1c941acfcc8d7f
[ "MIT" ]
3
2018-02-23T13:13:22.000Z
2019-02-02T06:05:14.000Z
src/cd_engine.h
ARandomOWL/verimap
0da478f7289d5b64e74b2821cf1c941acfcc8d7f
[ "MIT" ]
6
2018-03-08T16:09:35.000Z
2018-04-04T10:36:20.000Z
src/cd_engine.h
ARandomOWL/verimap
0da478f7289d5b64e74b2821cf1c941acfcc8d7f
[ "MIT" ]
1
2018-02-23T17:04:55.000Z
2018-02-23T17:04:55.000Z
// Andrey Mokhov // // School of EECE // University of Newcastle upon Tyne // // April 2006 // // Email: Andrey.Mokhov@ncl.ac.uk, Andrey.Mokhov@gmail.com #ifndef _CD_ENIGNE_H_ #define _CD_ENIGNE_H_ #include "sv_net.h" #include "sv_module.h" #include "sv_circuit.h" #include <string> #include <cstdio> #include <string> #include <queue> #include <vector> #include <map> using namespace std; #ifdef LINUX #include <ext/algorithm> #include <ext/hash_map> #include <ext/hash_set> namespace __gnu_cxx { template<class T> struct hash<T*> { size_t operator()(T* const & x) const { return (size_t)x; } }; } using namespace __gnu_cxx; #else //if WIN32 #include <algorithm> #include <hash_map> #include <hash_set> using namespace stdext; #endif //--------------------------------------------------------------------------- void setTimings(Circuit *circuit, float shrink = 1.0); bool optimiseCD(Module *module, float celement2_min_delay, float tree2_min_delay, float tree3_min_delay); #endif
20.039216
105
0.657534
[ "vector" ]
5749dce2b1b77d3cede01eb0ec86f5344cb79abf
1,712
h
C
includes/basic/basic.h
alexandrerodrigopinheiro/gorilla2d
b5c71214fb7a0b9e9e729675c37cbd30ffb13e57
[ "Unlicense" ]
null
null
null
includes/basic/basic.h
alexandrerodrigopinheiro/gorilla2d
b5c71214fb7a0b9e9e729675c37cbd30ffb13e57
[ "Unlicense" ]
null
null
null
includes/basic/basic.h
alexandrerodrigopinheiro/gorilla2d
b5c71214fb7a0b9e9e729675c37cbd30ffb13e57
[ "Unlicense" ]
null
null
null
#ifndef G2D_BASIC_BASIC_H_ #define G2D_BASIC_BASIC_H_ #pragma once #include <algorithm> #include <string> #include <iostream> #include <cassert> #include <cstring> #include <iosfwd> #include <iomanip> #include <vector> #include <sstream> #include <memory> #include <vector> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> namespace g2d { namespace basic { template<class... T> void unused(T&&...); template<typename T, typename M> T to(M src); template<typename T> std::vector<T> explode(const std::string& src, const char delimeter); template<typename T> std::vector<T> slice(const std::vector<T>& org, std::size_t begin, std::size_t end); template <typename T, typename N> std::vector<T> slice(const std::vector<N>& src, std::size_t begin, std::size_t end); template<typename T> void swap(const std::vector<T>& org, std::vector<T>& dst, std::size_t begin); template<typename T> bool repeated(const std::vector<T>& org, T element); template<typename T, typename N> bool repeated(const std::vector<T>& org, N element); template<typename T> bool repeated(const std::vector<T>& org); template <typename T, std::size_t N> constexpr std::size_t array_size(T (&)[N]); template <typename T, std::size_t N> T* array_begin(T (&array)[N]); template <typename T, std::size_t N> T* array_end(T (&array)[N]); template <typename T> std::string to_monetary(T org); std::string to_hex_string(int value, std::size_t length = 2); std::vector<std::string> explode(const std::string& src, const char delimeter); std::string replace(const std::string& src, const char org, const char dst); } } #include "basic.inl" #endif /* G2D_BASIC_BASIC_H_ */
22.526316
86
0.692173
[ "vector" ]
574de976a0df87b1618d40a32e96d0226f8f308f
1,942
h
C
include/core/shaderprogram.h
GuyTristram/grt
4329ed58f22248ed4924246e148fb6b5f3f7e1bc
[ "MIT" ]
1
2015-10-08T19:11:18.000Z
2015-10-08T19:11:18.000Z
include/core/shaderprogram.h
GuyTristram/grt
4329ed58f22248ed4924246e148fb6b5f3f7e1bc
[ "MIT" ]
null
null
null
include/core/shaderprogram.h
GuyTristram/grt
4329ed58f22248ed4924246e148fb6b5f3f7e1bc
[ "MIT" ]
null
null
null
#ifndef SHADERPROGRAM_H #define SHADERPROGRAM_H #include "common/shared.h" #include "core/uniform.h" #include <vector> class Texture; class ShaderProgram : public Shared { public: typedef SharedPtr< ShaderProgram > Ptr; ShaderProgram(); ShaderProgram( char const *vertex_source, char const *fragment_source, char const *geometry_source = 0, char const *control_source = 0, char const *evaluation_source = 0 ); ~ShaderProgram(); void bind(); void unbind() const; void bind_textures(); void set( UniformBase const &uniform ); void set( UniformGroup const &group ); template< typename T > void set( UniformId<T> const &id, T const &value ); template< typename T > void set( char const *name, T const &value ); static Ptr const &stock_unlit(); // Only for use by Uniform class static void bind_texture_to_current_program( int unit, SharedPtr< Texture > texture ); void swap( ShaderProgram &other ); private: void get_vertex_attribute_info(); void get_uniform_info(); int m_program; struct AttributeLocation { int location; int *shared_location; }; std::vector< AttributeLocation > m_att_locations; struct UniformLocation { int location; int count; UniformInfo const *info; }; std::vector< UniformLocation > m_uniform_locations; std::vector< SharedPtr< Texture > > m_bound_textures; }; //////////////////////////////////////////////////////////////////////////////// // Implementation //////////////////////////////////////////////////////////////////////////////// template< typename T > void ShaderProgram::set( char const *name, T const &value ) { bind( ); UniformId<T>( name ).bind( value ); } template< typename T > void ShaderProgram::set( UniformId<T> const &id, T const &value ) { bind( ); id.bind( value ); } #endif //SHADERPROGRAM_H
23.119048
88
0.611226
[ "vector" ]
57521f13cdf2b03b1d2cc5fb6c78435a82308476
1,053
h
C
leetcodeInXcode/Solution/Partition Array by Odd and Even.h
thats2ez/leetcode-in-Xcode
6a9cd577276908d1186002d8c365ad2fe84347f0
[ "MIT" ]
1
2019-08-11T08:47:53.000Z
2019-08-11T08:47:53.000Z
leetcodeInXcode/Solution/Partition Array by Odd and Even.h
thats2ez/leetcode-in-Xcode
6a9cd577276908d1186002d8c365ad2fe84347f0
[ "MIT" ]
null
null
null
leetcodeInXcode/Solution/Partition Array by Odd and Even.h
thats2ez/leetcode-in-Xcode
6a9cd577276908d1186002d8c365ad2fe84347f0
[ "MIT" ]
1
2021-07-21T09:03:43.000Z
2021-07-21T09:03:43.000Z
// // Partition Array by Odd and Even.h // leetcodeInXcode // // Created by Kaiqi on 5/30/15. // Copyright (c) 2015 edu.self. All rights reserved. // class Solution { public: /** * @param nums: a vector of integers * @return: nothing */ // this is WRONG, this is stable partition void partitionArray(vector<int> &nums) { // write your code here int i = 0; while (i < nums.size() && (nums[i] % 2)) { i++; } int j = i + 1; while (j < nums.size()) { if (nums[j] % 2) { swap(nums[i++], nums[j++]); } else { j++; } } } void partitionArray(vector<int> &nums) { // write your code here int i = 0, j = nums.size() - 1; while (i < j) { if (nums[i] % 2) { i++; } else if (!(nums[j] % 2)) { j--; } else { swap(nums[i++], nums[j--]); } } } };
22.404255
53
0.40076
[ "vector" ]
575ffee73d60e9bd5d4f5af7538d01789268cc9a
3,422
h
C
paddle/fluid/framework/ir/fuse_gemm_epilogue_pass.h
Li-fAngyU/Paddle
e548f65f96697830035a28f9070b40829408ccdb
[ "Apache-2.0" ]
11
2016-08-29T07:43:26.000Z
2016-08-29T07:51:24.000Z
paddle/fluid/framework/ir/fuse_gemm_epilogue_pass.h
Li-fAngyU/Paddle
e548f65f96697830035a28f9070b40829408ccdb
[ "Apache-2.0" ]
1
2022-01-28T07:23:22.000Z
2022-01-28T07:23:22.000Z
paddle/fluid/framework/ir/fuse_gemm_epilogue_pass.h
Li-fAngyU/Paddle
e548f65f96697830035a28f9070b40829408ccdb
[ "Apache-2.0" ]
1
2021-12-09T08:59:17.000Z
2021-12-09T08:59:17.000Z
// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. // Copyright (c) 2022 NVIDIA Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <mutex> #include <string> #include <unordered_set> #include "paddle/fluid/framework/ir/fuse_pass_base.h" #include "paddle/fluid/framework/ir/graph.h" #include "paddle/fluid/framework/ir/graph_pattern_detector.h" #include "paddle/fluid/framework/ir/pass.h" namespace paddle { namespace framework { namespace ir { /* * Fuse the ElewiseAdd and activation */ class Graph; class Node; class EpiloguePassActivationCache { public: EpiloguePassActivationCache() {} EpiloguePassActivationCache(const EpiloguePassActivationCache &) = delete; void operator=(const EpiloguePassActivationCache &) = delete; bool HasFusedActivation(const std::string &key) const { return fused_activation_space_map_.count(key); } ir::Node *GetFusedActivationSpace(const std::string &key) { if (HasFusedActivation(key)) { return fused_activation_space_map_.find(key)->second; } PADDLE_THROW(platform::errors::InvalidArgument( "The key (%d) of EpiloguePassActivationCache does not exist.", key)); } void InsertFusedActivation(const std::string &key, ir::Node *const value) { if (!HasFusedActivation(key)) { mtx.lock(); fused_activation_space_map_.insert({key, value}); mtx.unlock(); } else { PADDLE_THROW(platform::errors::AlreadyExists( "The key (%d) of EpiloguePassActivationCache already exist.", key)); } } private: std::unordered_map<std::string, ir::Node *> fused_activation_space_map_; std::mutex mtx; }; class FuseGemmEpiloguePass : public FusePassBase { public: virtual ~FuseGemmEpiloguePass() {} protected: void ApplyImpl(ir::Graph *graph) const override; ir::Graph *FuseLinearFwd(ir::Graph *graph, bool is_training) const; ir::Graph *FuseLinearActFwd(ir::Graph *graph, const std::unordered_set<std::string> &act_types, bool is_training, bool is_act_grad_x_from_act, EpiloguePassActivationCache *cache) const; ir::Graph *FuseLinearBwd(ir::Graph *graph, bool without_x_gradient) const; ir::Graph *FuseLinearActBwd( ir::Graph *graph, const std::unordered_set<std::string> &act_grad_types, bool is_act_grad_x_from_act, EpiloguePassActivationCache *cache) const; private: bool IsGemmFromLinear_(const std::vector<int64_t> &x_shape, const std::vector<int64_t> &w_shape, OpDesc *matmul_v2_op) const; const std::string GetReserveSpaceCacheKey(const std::string var_name, int block_id) const { return std::to_string(block_id) + var_name; } }; } // namespace ir } // namespace framework } // namespace paddle
33.881188
79
0.698714
[ "vector" ]
5766fb8bbef797a6fa55834eea26ac8c89e0f249
3,990
h
C
LacqJS/LQJSBridgeObject.h
pojala/lacqjs
f2bd44b7bf04b96c23b4c32f0abb3810bb372c65
[ "MIT" ]
1
2021-09-05T20:45:16.000Z
2021-09-05T20:45:16.000Z
LacqJS/LQJSBridgeObject.h
pojala/lacqjs
f2bd44b7bf04b96c23b4c32f0abb3810bb372c65
[ "MIT" ]
null
null
null
LacqJS/LQJSBridgeObject.h
pojala/lacqjs
f2bd44b7bf04b96c23b4c32f0abb3810bb372c65
[ "MIT" ]
null
null
null
// // LQJSBridgeObject.h // LacqJS // // Created by Pauli Ojala on 8.10.2008. // Copyright 2008 Lacquer oy/ltd. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // #import <Foundation/Foundation.h> #import "JSKitTypes.h" #import "JSKitInterpreter.h" #import "LQScriptBridging.h" @interface LQJSBridgeObject : NSObject <LQScriptBridging> { JSObjectRef _jsObject; JSContextRef _jsContext; id _owner; } - (id)initInJSContext:(JSContextRef)context withOwner:(id)owner; - (void)setOwner:(id)newOwner; - (id)owner; - (id)objcOwnerOfJSObject; + (JSClassRef)jsClassRef; - (JSContextRef)jsContextRef; - (JSObjectRef)jsObjectRef; - (id)propertyForKey:(NSString *)key; - (void)setProperty:(id)value forKey:(NSString *)key options:(LQJSKitPropertyAttributes)propAttrs; // method call interface to match JSKitObject - (id)callMethod:(NSString *)name withParameters:(NSArray *)param error:(NSError **)error; // utilities for bridge implementations - (BOOL)parseByteFromArg:(id)arg outValue:(uint8_t *)b; - (BOOL)parseLongFromArg:(id)arg outValue:(long *)l; // creates an empty Object in the same JS context as this bridge; // useful for returning dictionaries - (LQJSKitObject *)emptyProtectedJSObject; // the "contextObj" passed to js function implementations is an opaque Obj-C object; // this should be called to get the context from it. - (JSContextRef)jsContextRefFromJSCallContextObj:(id)contextObj; @end @interface LQJSKitInterpreter(BridgeObjects) /*! @method loadBridge: @abstract Adds a bridge class to the interpreter context @param bridgeClassObject A class object that represents the bridge class (a subclass of LQJSKitBridgeObject) @discussion Adds a constructor to the curernt context that will create a new instance of the bridgeObjectClass when called. */ //- (void) loadBridge: (id) bridgeObjectClass; // ^^^ 2009.04.24 / Pauli -- method renamed to: - (void)loadBridgeClass:(Class)bridgeObjectClass; /*! @method bridgeObject:withConstructorArguments: @abstract Creates (from Objective-C) a new bridge object of a given class, with specified arguments @discussion Creating a new bridge object involves some lower level manipulation to be able to expose the result properly to the appropriate JavaScript interpreter context. This routine will make an object of a given class in the same context as the receiver, and then awaken the object, and finally return the bridge object. @param cls The class to create. Should be a subclass of LQJSKitBridgeObject @param arguments The parameter list to pass to awakeFromConstructor @result The newly created, auto-released object. */ - (id)bridgeObject:(id)cls withConstructorArguments:(NSArray *)arguments; // these constructor access methods added 2009.06.29 by Pauli - (id)constructorNamed:(NSString *)name; - (Class)bridgeClassForJSConstructor:(JSObjectRef)constr; @end
37.641509
124
0.751629
[ "object" ]
5768aa5ead9910d50c507c062bc47ad469817786
605
h
C
src/xr_3da/xrGame/ai/Biting/biting_state_attack.h
ixray-team/ixray-b2945
ad5ef375994ee9cd790c4144891e9f00e7efe565
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:19.000Z
2022-03-26T17:00:19.000Z
src/xr_3da/xrGame/ai/Biting/biting_state_attack.h
ixray-team/ixray-b2945
ad5ef375994ee9cd790c4144891e9f00e7efe565
[ "Linux-OpenIB" ]
null
null
null
src/xr_3da/xrGame/ai/Biting/biting_state_attack.h
ixray-team/ixray-b2945
ad5ef375994ee9cd790c4144891e9f00e7efe565
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:21.000Z
2022-03-26T17:00:21.000Z
#pragma once #include "../../state_manager_state.h" class CAI_Biting; class CStateBitingAttack : public CStateManagerState<CAI_Biting> { protected: typedef CStateManagerState<CAI_Biting> inherited; enum EAttackStates { eAS_Run = u32(0), eAS_Melee, eALifeStateDummy = u32(-1), }; public: CStateBitingAttack (LPCSTR state_name); virtual ~CStateBitingAttack (); virtual void Load (LPCSTR section); virtual void reinit (CAI_Biting *object); virtual void initialize (); virtual void execute (); virtual void finalize (); };
21.607143
67
0.666116
[ "object" ]
57702542e2357848de2eaeeba8dde33a9595974d
1,098
h
C
src/libgeodecomp/misc/patternoptimizer.h
aproeme/libgeodecomp
f78899c67ad62540fd153cba132a0a363a7b3fa9
[ "BSL-1.0" ]
40
2015-03-18T16:36:25.000Z
2020-08-19T07:35:19.000Z
src/libgeodecomp/misc/patternoptimizer.h
aproeme/libgeodecomp
f78899c67ad62540fd153cba132a0a363a7b3fa9
[ "BSL-1.0" ]
72
2015-02-05T10:41:30.000Z
2022-03-03T12:02:47.000Z
src/libgeodecomp/misc/patternoptimizer.h
aproeme/libgeodecomp
f78899c67ad62540fd153cba132a0a363a7b3fa9
[ "BSL-1.0" ]
17
2015-11-22T14:49:16.000Z
2020-01-15T19:05:04.000Z
#ifndef LIBGEODECOMP_MISC_PATTERNOPTIMIZER_H #define LIBGEODECOMP_MISC_PATTERNOPTIMIZER_H #include <libgeodecomp/misc/optimizer.h> #include <libgeodecomp/misc/simulationparameters.h> namespace LibGeoDecomp { /** * This class implements a direct search (pattern search) which * searches a given neighborhood to find better parameters. */ class PatternOptimizer : public Optimizer { public: explicit PatternOptimizer( SimulationParameters params, std::vector<double> stepwidth = std::vector<double>(), std::vector<double> minStepwidth = std::vector<double>()); virtual SimulationParameters operator()(int steps, Evaluator& eval); private: std::vector<double> stepwidth; std::vector<double> minStepwidth; bool reduceStepwidth(); std::vector<SimulationParameters> genPattern(SimulationParameters middle); std::size_t getMaxPos( const std::vector<SimulationParameters>& pattern, Evaluator& eval, std::size_t oldMiddle); std::string patternToString(std::vector<SimulationParameters> pattern); }; } #endif
24.954545
78
0.734062
[ "vector" ]
577124bd2a6a59b34fe2bcba4267042163eaba7e
5,562
h
C
linear_equations/equation.h
hassanelshazly/linear_equations_solver
48bc7c64e33533acc958995dc29f280531331de7
[ "MIT" ]
null
null
null
linear_equations/equation.h
hassanelshazly/linear_equations_solver
48bc7c64e33533acc958995dc29f280531331de7
[ "MIT" ]
null
null
null
linear_equations/equation.h
hassanelshazly/linear_equations_solver
48bc7c64e33533acc958995dc29f280531331de7
[ "MIT" ]
null
null
null
/****************************************************************************** * Copyright (C) 2020 by Hassan El-shazly * * Redistribution, modification or use of this software in source or binary * forms is permitted as long as the files maintain this copyright. * *****************************************************************************/ /** * * @author Hassan El-shazly * @date Last Edit Aug-2020 * */ #ifndef _EQUATION_H_ #define _EQUATION_H_ #include <iostream> #include <string> #include <vector> #include <set> #include "term.h" using std::set; using std::string; using std::vector; template <typename value_t> class equation { public: /** * Default constructor */ equation(); /** * Copy constructor */ equation(const equation &equ); /** * Move constructor */ equation(const equation &&equ); /** * Construct equation from string */ equation(const string &equ_str); /** * @return number of terms */ uint32_t size(); /** * @return the coff of specifec variable */ value_t get(const string &var); /** * @return the constant term */ value_t get_const(); /** * @return set with varible names */ set<string> get_vars(); /** * @return terms of the equation */ set<term<value_t>> get_terms(); /** * change the value of specifec term * @return reference to the calling object */ equation &set_term(const string &var, value_t val); /** * change the value of the constant * @return reference to the calling object */ equation &set_const(value_t val); /** * add value to the const term * @return reference to the calling object */ equation &add_const(value_t val); /** * subtract value from the const term * @return reference to the calling object */ equation &subtract_const(value_t val); /** * add term to the equation * @return reference to the calling object */ equation &add_term(term<value_t> tm); /** * add term to the equation * @return reference to the calling object */ equation &add_term(const string &var, value_t val); /** * subtract term from the equation * @return reference to the calling object */ equation &subtract_term(term<value_t> tm); /** * subtract term from the equation * @return reference to the calling object */ equation &subtract_term(const string &var, value_t val); /** * remove term from the equation * @return reference to the calling object */ equation &remove_term(const string &var); /** * subsutuite varible with specfic value * @return reference to the calling object */ equation &sub_term(const string &var, value_t val); /** * add two equations * @return reference to the calling object */ equation &add(const equation &equ); /** * subtract two equations * @return reference to the calling object */ equation &subtract(const equation &equ); /** * multiply all the terms of the equation with val * @return reference to the calling object */ equation &multiply(value_t val); /** * divide all the terms of the equation on val * @return reference to the calling object */ equation &divide(value_t val); /** * add two equations * @return reference to the calling object */ equation &operator+=(const equation &equ); /** * subtract two equations * @return reference to the calling object */ equation &operator-=(const equation &equ); /** * multiply all the terms of the equation with val * @return reference to the calling object */ equation &operator*=(value_t val); /** * divide all the terms of the equation on val * @return reference to the calling object */ equation &operator/=(value_t val); /** * add two equations * @return new equation object */ template <typename T> friend equation<T> &operator+(const equation<T> &equ1, const equation<T> &equ2); /** * subtract two equations * @return new equation object */ template <typename T> friend equation<T> &operator-(const equation<T> &equ1, const equation<T> &equ2); /** * multiply all the terms of the equation with val * @return new equation object */ template <typename T> friend equation<T> &operator*(const equation<T> &equ, value_t val); /** * divide all the terms of the equation on val * @return new equation object */ template <typename T> friend equation<T> &operator/(const equation<T> &equ, value_t val); /** * Overloads << operator to print equation as a native type. */ template <typename T> friend std::ostream &operator<<(std::ostream &os, const equation<T> &equ); private: /** * convert string to an equation */ equation convert(const string &equ_str); /** * convert string to an equation */ equation evaluate(const string &equ_str, int sign); /** * @return vector of matched strings with regex */ vector<string> get_tokens(string to_match, const string &pattern); set<term<value_t>> terms; value_t constant; }; // include implemention #include "equation_impl.h" #endif // End of the file
22.795082
84
0.591334
[ "object", "vector" ]
5776ac564a35b63288383a2f0763ec87956cc3c7
455
h
C
besspin/cwesEvaluation/informationLeakage/sources/include/interpreter.h
mikkowus/BESSPIN-Tool-Suite
e87e9abb1156a8627aacc3272f1925b034129146
[ "Apache-2.0" ]
null
null
null
besspin/cwesEvaluation/informationLeakage/sources/include/interpreter.h
mikkowus/BESSPIN-Tool-Suite
e87e9abb1156a8627aacc3272f1925b034129146
[ "Apache-2.0" ]
null
null
null
besspin/cwesEvaluation/informationLeakage/sources/include/interpreter.h
mikkowus/BESSPIN-Tool-Suite
e87e9abb1156a8627aacc3272f1925b034129146
[ "Apache-2.0" ]
null
null
null
#ifndef __INTERPRETER_H__ #define __INTERPRETER_H__ #include "types.h" #include "control.h" // Return a representation, for a given interpreter, // of the address of object 'addr' and offset 'offset'. // This function exists to make the exploits modular. uaddr_t build_uaddr(char addr, char offset); // Allocate & return a poitner // to a 'system' message constructed from the user message. struct smessage* interpret_cmd(struct umessage *umsg); #endif
26.764706
59
0.767033
[ "object" ]
579e9e2a58b07141727508e8ff732a9e61e8af84
1,887
c
C
src/variable_vector.c
Adda0/ifj20-go-compiler
477407734e5f87d26aaa7a07f2947a3ee9da4c9d
[ "MIT" ]
null
null
null
src/variable_vector.c
Adda0/ifj20-go-compiler
477407734e5f87d26aaa7a07f2947a3ee9da4c9d
[ "MIT" ]
null
null
null
src/variable_vector.c
Adda0/ifj20-go-compiler
477407734e5f87d26aaa7a07f2947a3ee9da4c9d
[ "MIT" ]
null
null
null
/** @file variable_vector.c * * IFJ20 compiler * * @brief Contains definitions of variable vector functions. * * @author František Nečas (xnecas27), FIT BUT */ #include <stdlib.h> #include "variable_vector.h" #include "symtable.h" #include "stderr_message.h" /** @brief Initializes the vector. */ void vv_init(VariableVector *vector) { vector->first = NULL; } /** @brief Adds a variable to the variable vector. */ bool vv_append(VariableVector *vector, VariableData var) { Variable *new = calloc(sizeof(Variable), 1); if (new == NULL) { stderr_message("variable_vector", ERROR, COMPILER_RESULT_ERROR_INTERNAL, "Out of memory\n"); return false; } new->data = var; new->next = vector->first; vector->first = new; return true; } /** @brief Checks whether the vector contains the given symbol. */ Variable *vv_find(VariableVector *vector, STSymbol *symbol) { Variable *curr = vector->first; while (curr != NULL) { if (curr->data.symbol == symbol) { return curr; } curr = curr->next; } return NULL; } /** @brief Removes the given symbol from the vector. */ void vv_remove_symbol(VariableVector *vector, STSymbol *symbol) { Variable *prev = NULL; Variable *curr = vector->first; while (curr != NULL) { if (curr->data.symbol == symbol) { break; } prev = curr; curr = curr->next; } if (curr == NULL) { return; } if (prev == NULL) { // Curr was head vector->first = curr->next; } else { prev->next = curr->next; } free(curr); } /** @brief Destroys the variable vector. */ void vv_free(VariableVector *vector) { Variable *curr = vector->first; Variable *tmp; while (curr != NULL) { tmp = curr->next; free(curr); curr = tmp; } }
24.192308
100
0.596184
[ "vector" ]
57a1524331833196d90b43bb2ddcafdcea3c6645
11,358
h
C
src/commlib/zcelib/zce_server_status.h
sailzeng/zcelib
88e14ab436f1b40e8071e15ef6d9fae396efc3b4
[ "Apache-2.0" ]
72
2015-01-08T05:01:48.000Z
2021-12-28T06:13:03.000Z
src/commlib/zcelib/zce_server_status.h
sailzeng/zcelib
88e14ab436f1b40e8071e15ef6d9fae396efc3b4
[ "Apache-2.0" ]
4
2016-01-18T12:24:59.000Z
2019-10-12T07:19:15.000Z
src/commlib/zcelib/zce_server_status.h
sailzeng/zcelib
88e14ab436f1b40e8071e15ef6d9fae396efc3b4
[ "Apache-2.0" ]
40
2015-01-26T06:49:18.000Z
2021-07-20T08:11:48.000Z
/*! * @copyright 2004-2013 Apache License, Version 2.0 FULLSAIL * @filename zce_server_status.h * @author Sailzeng <sailerzeng@gmail.com> * @version * @date 2006年3月7日 * @brief * * * @details 服务器的统计类, * 这个想法来自rong,sonicmao的C4A的服务器,向rong,sonicmao致敬. * * * @note 修改记录,很简单的一个类,但改动很多 * 1.Date :2011年10月30日 * Author :根据ZCELIB的代码对现有的代码进行优化 * Modification : * 2.Date :2012年1月15日 * Author :Sailzeng * Modification :在N次反复,以及吐血的改了2次后,我开始倾向用一个最简单的方式解决问题, * 3.Date :2012年5月10日 * Author :Sailzeng * Modification :很多啊同事还是吐槽需要设置classify,我想还是改了把。部分告别sandy和mandy * 4.Date :2013年10月1日 * Author :Sailzeng * Modification :有一个防止统计ID重复的需求,将原来的ARRAY改造成了一个MAP映射, * */ #ifndef ZCE_LIB_SERVER_STATUS_H_ #define ZCE_LIB_SERVER_STATUS_H_ #include "zce_share_mem_posix.h" #include "zce_shm_array.h" #include "zce_lock_null_lock.h" #include "zce_os_adapt_time.h" //=========================================================================================== /*! * @brief 状态统计的方式,比如5分钟记录一次的方式,一个小时记录的方式等 * * @note */ enum ZCE_STATUS_STATICS_TYPE { //标识范围 STATICS_INVALID_TYPE = 0, //每5分钟进行一次统计,尽量用5分钟的统计方式 STATICS_PER_FIVE_MINTUES = 1, //每小时进行一次统计,:0会清空,这种统计方式主要用于1个小时变化数据,用于对比等, STATICS_PER_HOUR = 2, //每天进行一次统计,0:0会清空,,这种统计方式主要用于1天变化数据 STATICS_PER_DAYS = 3, //绝对值 STATICS_ABSOLUTE_VALUE = 11, //原来还有一种每次启动时,数值是否清空的选项,算了,没必要保留了 }; //保证数据文件的一致性 #pragma pack(8) //=========================================================================================== /*! * @brief 统计项目ID, * * @note */ struct ZCE_STATUS_ITEM_ID { public: ZCE_STATUS_ITEM_ID(uint32_t statics_id, uint32_t classify_id, uint32_t subclassing_id); ZCE_STATUS_ITEM_ID(); ~ZCE_STATUS_ITEM_ID(); bool operator == (const ZCE_STATUS_ITEM_ID& others) const; public: ///统计ID uint32_t statics_id_=0; ///分类ID,目前好像主要是业务ID,这个是可以变化的 uint32_t classify_id_=0; ///子分类ID,这个也是可以变化的, uint32_t subclassing_id_=0; }; //=========================================================================================== /*! * @brief ZCE_STATUS_ITEM_ID得到HASH因子的函数, * */ struct HASH_ZCE_STATUS_ITEM_ID { public: //就把3个数值相+,这样冲突感觉还小一点,(左移反而感觉不好) size_t operator()(const ZCE_STATUS_ITEM_ID &stat_item) const { return static_cast<size_t>(stat_item.statics_id_) + static_cast<size_t>(stat_item.classify_id_) + static_cast<size_t>(stat_item.subclassing_id_); } }; //=========================================================================================== /*! * @brief 状态计数器项,包括ID,统计方式,以及数值 * */ class ZCE_STATUS_ITEM { public: //构造函数和析构函数 ZCE_STATUS_ITEM(); ZCE_STATUS_ITEM(unsigned int statics_id, ZCE_STATUS_STATICS_TYPE statics_type); ~ZCE_STATUS_ITEM(); public: ///ID标识 ZCE_STATUS_ITEM_ID item_id_; ///可以重新计数 ZCE_STATUS_STATICS_TYPE statics_type_ =STATICS_INVALID_TYPE; ///计数器 uint64_t counter_=0; }; //=========================================================================================== /*! * @brief 状态计数器+名字,用于配置,DUMP输出等 * */ class ZCE_STATUS_ITEM_WITHNAME { public: // ZCE_STATUS_ITEM_WITHNAME(unsigned int, ZCE_STATUS_STATICS_TYPE, const char *); ZCE_STATUS_ITEM_WITHNAME(); ~ZCE_STATUS_ITEM_WITHNAME(); public: //统计项目名称的长度 static const size_t MAX_COUNTER_NAME_LEN = 64; public: ZCE_STATUS_ITEM statics_item_; //计数器名称 char item_name_[MAX_COUNTER_NAME_LEN + 1]; }; //用于帮助你定义 ZCE_STATUS_ITEM_WITHNAME数组 #ifndef DEF_ZCE_STATUS_ITEM #define DEF_ZCE_STATUS_ITEM(_statics_id,_statics_type) ZCE_STATUS_ITEM_WITHNAME(_statics_id,_statics_type,(#_statics_id)) #endif //=========================================================================================== /*! * @brief 存放统计信息的状态文件的头部。记录监控时间等时间戳 * */ struct ZCE_STATUS_HEAD { //监控开始时间 uint64_t monitor_start_time_; //监控数据复制的时间戳 uint64_t copy_time_; //向monitor上报的时间 uint64_t report_monitor_time_; //激活时间长度,目前没有记录 uint64_t active_time_; }; #pragma pack() //=========================================================================================== /*! * @brief 使用Posix MMAP,记录保存服务器的一些计数器,状态, * * @note 本来使用的是锁模式,但发现使用这个东西会导致满世界的问题扩大化, */ class ZCE_Server_Status : public ZCE_NON_Copyable { protected: ///存放统计数据的共享内存数组, typedef zce::shm_array<ZCE_STATUS_ITEM> ARRYA_OF_SHM_STATUS; ///统计ID到数组的下标的hash map typedef unordered_map<ZCE_STATUS_ITEM_ID, size_t, HASH_ZCE_STATUS_ITEM_ID> STATID_TO_INDEX_MAP; ///statics_id_做key的ZCE_STATUS_ITEM_WITHNAME的结构 typedef unordered_map<uint32_t, ZCE_STATUS_ITEM_WITHNAME> STATUS_WITHNAME_MAP; public: ///统计数据的数组,用于dump输出的数据结构 typedef std::vector<ZCE_STATUS_ITEM_WITHNAME> ARRAY_OF_STATUS_WITHNAME; public: ///构造函数,也给你单独使用的机会,所以不用protected ZCE_Server_Status(); ///析构函数 virtual ~ZCE_Server_Status(); protected: /*! * @brief 初始化的方法,通用的底层, * @return int * @param[in] stat_filename MMAP影射的状态文件名称 * @param[in] restore_mmap 是否用于恢复MMAP,如果是恢复,文件必须是存在的, * @param[in] multi_thread 是否是多线程环境使用 */ int initialize(const char *stat_filename, bool restore_mmap, bool multi_thread); /*! * @brief 在数据区里面,找数据项目 * @return int 如果成功找到返回0 * @param[in] statics_id 统计ID * @param[in] classify_id 分类ID * @param[in] subclassing_id 子分类ID * @param[out] idx 查询到数据项目存放索引 */ int find_insert_idx(uint32_t statics_id, uint32_t classify_id, uint32_t subclassing_id, size_t *idx); public: /*! * @brief 根据一个已经存在的文件进行初始化,用于恢复数据区,文件必须已经存在, * 一般查询状态工具使用这个函数。 * @return int * @param[in] stat_filename MMAP影射的状态文件名称 * @param[in] multi_thread 是否多线程 */ int initialize(const char *stat_filename, bool multi_thread); /*! * @brief 创建一个已经存在的文件进行初始化,用于恢复数据区,如果文件必须已经存在,会重新创建 * 需要记录状态的服务器使用这个函数 * @return int * @param[in] stat_filename MMAP影射的状态文件名称 * @param[in] num_stat_item item_ary的数量, * @param[in] item_ary 统计项目, * @param[in] multi_thread 是否多线程 * @note 注意统计项目数量不是监控ID的数量,监控ID数量默认是固定的 @ref MAX_MONITOR_STAT_ITEM */ int initialize(const char *stat_filename, size_t num_stat_item, const ZCE_STATUS_ITEM_WITHNAME item_ary[], bool multi_thread); /*! * @brief 增加一些监控项目,如果有2段的初始化(比如框架一次,业务一次)时使用 * @return void * @param num_stat_item item_ary的数量 * @param item_ary 增加的统计项目 */ void add_status_item(size_t num_stat_item, const ZCE_STATUS_ITEM_WITHNAME item_ary[]); ///监控项是否已经存在 bool is_exist_stat_id(unsigned int stat_id, ZCE_STATUS_ITEM_WITHNAME *status_item_withname) const; ///初始化以后,修改是否需要多线程保护 void multi_thread_guard(bool multi_thread); /*! * @brief 使用统计ID和分类ID作为key,对统计值增加1 * @return int * @param[in] statics_id 统计ID * @param[in] classify_id 分类ID * @param[in] subclassing_id 子分类ID */ inline int increase_once(uint32_t statics_id, uint32_t classify_id, uint32_t subclassing_id) { return increase_by_statid(statics_id, classify_id, subclassing_id, 1); } /*! * @brief 使用统计ID和分类ID作为key,绝对值修改监控统计项目 * @return int * @param[in] statics_id 统计ID * @param[in] classify_id 分类ID * @param[in] subclassing_id 子分类ID * @param[in] set_value 修改的统计值 */ int set_by_statid(uint32_t statics_id, uint32_t classify_id, uint32_t subclassing_id, uint64_t set_value); /*! * @brief 使用统计ID和分类ID作为key,相对值修改监控统计值 * @return int * @param[in] statics_id 统计ID * @param[in] classify_id 分类ID * @param[in] subclassing_id 子分类ID * @param[in] incre_value 修改的相对值,符号整数,可加可减 */ int increase_by_statid(uint32_t statics_id, uint32_t classify_id, uint32_t subclassing_id, int64_t incre_value); /*! * @brief 根据统计ID和分类ID作为key,得到统计数值 * @return uint64_t 返回的统计值 * @param[in] statics_id 统计ID * @param[in] classify_id 分类ID * @param[in] subclassing_id 子分类ID */ uint64_t get_counter(uint32_t statics_id, uint32_t classify_id, uint32_t subclassing_id); //取得计数器的个数 size_t num_of_counter(); //获取copy_time uint64_t get_copy_time(); //清理过期的数据,在你的定时器触发时调用(当然前面最好应该上报),用于将一些数据清0, //理论上每5分钟调用一次就OK void check_overtime(time_t now_time); ///备份计数器信息 void copy_stat_counter(); ///由于将内部数据全部取出,用于你外部打包之类 void dump_all(ARRAY_OF_STATUS_WITHNAME &array_status, bool dump_copy = false); ///Dump所有的数据 void dump_status_info(std::ostringstream &strstream, bool dump_copy = false); ///Dump所有的数据 void dump_status_info(ZCE_LOG_PRIORITY log_priority, bool dump_copy = false); ///得到文件的头部信息 void get_stat_head(ZCE_STATUS_HEAD *stat_head ); ///记录监控的上报时间 void report_monitor_time(uint64_t report_time = static_cast<uint64_t>(time(NULL))); //单子的函数群,不是我不知道可以用BOOST的模板使用单子,是这样更加直接清爽,容易扩张修改一些 //我不会为了单子考虑所谓的保护问题,你自己保证你的初始化函数不会重入 public: //得到单子实例 static ZCE_Server_Status *instance(); //单子实例赋值 static void instance(ZCE_Server_Status *); //清理单子实例 static void clean_instance(); protected: //最多的监控项目ID, static const size_t MAX_MONITOR_STAT_ITEM = 64 * 1024; //五分钟的描述 static const time_t FIVE_MINTUE_SECONDS = 300; //一小时的秒数 static const time_t ONE_HOURS_SECONDS = 3600; //一天的时间 static const time_t ONE_DAY_SECONDS = 86400; //统计项目数值增加1 static const uint64_t INCREASE_VALUE_ONCE = 1; protected: //多态的锁, ZCE_Lock_Base *stat_lock_; //MMAP内存影射的数据文件 ZCE_ShareMem_Posix stat_file_; //内存文件头 ZCE_STATUS_HEAD *stat_file_head_; //mandy和sandy是原来代码中间为了区分用数组定位,hash定位两个数据区的东东, //后来代码全部改为了用hansh定位,不好意思,两个小MM,怪蜀黍就是步放过你们, //http://t.qq.com/angelbaby22 // 存放状态计数器的数组 ARRYA_OF_SHM_STATUS *status_stat_sandy_; //状态计数器的一份拷贝(备份),数据放在共享内存中,我们可以用考虑用mandy读取数据,所以可以讲每个 ARRYA_OF_SHM_STATUS *status_copy_mandy_; //记录配置的的统计数据SET,用于记录配置的统计项目,也用于防止重复插入和dump 输出时有名称信息 STATUS_WITHNAME_MAP conf_stat_map_; //STAT_ID to idx索引的MAP STATID_TO_INDEX_MAP statid_to_index_; //是否进行多线程保护 bool multi_thread_guard_; // 是否已经初始化 bool initialized_; protected: //单子实例 static ZCE_Server_Status *instance_; }; #endif //_ZCE_LIB_SERVER_STATUS_H_
24.373391
121
0.596408
[ "vector" ]
707103ad0e4b24d9cfe091be67f15bf5f75f888b
42,649
c
C
src/encoder_state-bitstream.c
fador/kvazaar
55bb8ee17f96a9625b8c10bce7c82fa91e7eec09
[ "BSD-3-Clause" ]
512
2015-01-13T21:42:48.000Z
2022-03-31T17:57:28.000Z
src/encoder_state-bitstream.c
fador/kvazaar
55bb8ee17f96a9625b8c10bce7c82fa91e7eec09
[ "BSD-3-Clause" ]
217
2015-01-04T16:06:49.000Z
2022-03-30T12:54:29.000Z
src/encoder_state-bitstream.c
fador/kvazaar
55bb8ee17f96a9625b8c10bce7c82fa91e7eec09
[ "BSD-3-Clause" ]
179
2015-01-05T08:58:40.000Z
2022-03-29T07:08:24.000Z
/***************************************************************************** * This file is part of Kvazaar HEVC encoder. * * Copyright (c) 2021, Tampere University, ITU/ISO/IEC, project contributors * 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 Tampere University or ITU/ISO/IEC nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS ****************************************************************************/ #include "encoder_state-bitstream.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "bitstream.h" #include "cabac.h" #include "checkpoint.h" #include "cu.h" #include "encoder.h" #include "encoder_state-geometry.h" #include "encoderstate.h" #include "imagelist.h" #include "kvazaar.h" #include "kvz_math.h" #include "nal.h" #include "scalinglist.h" #include "tables.h" #include "threadqueue.h" #include "videoframe.h" #include "rate_control.h" static void encoder_state_write_bitstream_aud(encoder_state_t *const state) { bitstream_t *const stream = &state->stream; kvz_nal_write(stream, KVZ_NAL_AUD_NUT, 0, 1); uint8_t pic_type = state->frame->slicetype == KVZ_SLICE_I ? 0 : state->frame->slicetype == KVZ_SLICE_P ? 1 : 2; WRITE_U(stream, pic_type, 3, "pic_type"); kvz_bitstream_add_rbsp_trailing_bits(stream); } static void encoder_state_write_bitstream_PTL(bitstream_t *stream, encoder_state_t *const state) { // PTL // Profile Tier WRITE_U(stream, 0, 2, "general_profile_space"); WRITE_U(stream, state->encoder_control->cfg.high_tier, 1, "general_tier_flag"); // Main Profile == 1, Main 10 profile == 2 WRITE_U(stream, (state->encoder_control->bitdepth == 8) ? 1 : 2, 5, "general_profile_idc"); /* Compatibility flags should be set at general_profile_idc * (so with general_profile_idc = 1, compatibility_flag[1] should be 1) * According to specification, when compatibility_flag[1] is set, * compatibility_flag[2] should be set too. */ WRITE_U(stream, 3 << 29, 32, "general_profile_compatibility_flag[]"); WRITE_U(stream, 1, 1, "general_progressive_source_flag"); WRITE_U(stream, state->encoder_control->in.source_scan_type != 0, 1, "general_interlaced_source_flag"); WRITE_U(stream, 0, 1, "general_non_packed_constraint_flag"); WRITE_U(stream, 0, 1, "general_frame_only_constraint_flag"); WRITE_U(stream, 0, 32, "XXX_reserved_zero_44bits[0..31]"); WRITE_U(stream, 0, 12, "XXX_reserved_zero_44bits[32..43]"); // end Profile Tier uint8_t level = state->encoder_control->cfg.level; WRITE_U(stream, level * 3, 8, "general_level_idc"); WRITE_U(stream, 0, 1, "sub_layer_profile_present_flag"); WRITE_U(stream, 0, 1, "sub_layer_level_present_flag"); for (int i = 1; i < 8; i++) { WRITE_U(stream, 0, 2, "reserved_zero_2bits"); } // end PTL } static uint8_t max_required_dpb_size(const encoder_control_t * const encoder) { int max_buffer = 1; for (int g = 0; g < encoder->cfg.gop_len; ++g) { int neg_refs = encoder->cfg.gop[g].ref_neg_count; int pos_refs = encoder->cfg.gop[g].ref_pos_count; if (neg_refs + pos_refs + 1 > max_buffer) max_buffer = neg_refs + pos_refs + 1; } if (encoder->cfg.gop_len == 0) max_buffer = encoder->cfg.ref_frames + 1; return max_buffer; } static uint8_t max_num_reorder_pics(const encoder_control_t * const encoder) { return encoder->cfg.gop_lowdelay ? 0 : MAX(encoder->cfg.gop_len - 1, 0); } static void encoder_state_write_bitstream_vid_parameter_set(bitstream_t* stream, encoder_state_t * const state) { #ifdef KVZ_DEBUG printf("=========== Video Parameter Set ID: 0 ===========\n"); #endif const encoder_control_t* encoder = state->encoder_control; WRITE_U(stream, 0, 4, "vps_video_parameter_set_id"); WRITE_U(stream, 3, 2, "vps_reserved_three_2bits" ); WRITE_U(stream, 0, 6, "vps_reserved_zero_6bits" ); WRITE_U(stream, 1, 3, "vps_max_sub_layers_minus1"); WRITE_U(stream, 0, 1, "vps_temporal_id_nesting_flag"); WRITE_U(stream, 0xffff, 16, "vps_reserved_ffff_16bits"); encoder_state_write_bitstream_PTL(stream, state); WRITE_U(stream, 0, 1, "vps_sub_layer_ordering_info_present_flag"); int max_buffer = max_required_dpb_size(encoder); int max_reorder = max_num_reorder_pics(encoder); if (max_buffer - 1 < max_reorder) max_buffer = max_reorder + 1; WRITE_UE(stream, max_buffer - 1, "vps_max_dec_pic_buffering_minus1"); WRITE_UE(stream, max_reorder, "vps_max_num_reorder_pics"); WRITE_UE(stream, 0, "vps_max_latency_increase"); WRITE_U(stream, 0, 6, "vps_max_nuh_reserved_zero_layer_id"); WRITE_UE(stream, 0, "vps_max_op_sets_minus1"); WRITE_U(stream, 0, 1, "vps_timing_info_present_flag"); //IF timing info //END IF WRITE_U(stream, 0, 1, "vps_extension_flag"); kvz_bitstream_add_rbsp_trailing_bits(stream); } static void encoder_state_write_bitstream_scaling_list(bitstream_t *stream, encoder_state_t * const state) { const encoder_control_t * const encoder = state->encoder_control; uint32_t size_id; for (size_id = 0; size_id < SCALING_LIST_SIZE_NUM; size_id++) { int32_t list_id; for (list_id = 0; list_id < kvz_g_scaling_list_num[size_id]; list_id++) { uint8_t scaling_list_pred_mode_flag = 1; int32_t pred_list_idx; int32_t i; uint32_t ref_matrix_id = UINT32_MAX; for (pred_list_idx = list_id; pred_list_idx >= 0; pred_list_idx--) { const int32_t * const pred_list = (list_id == pred_list_idx) ? kvz_scalinglist_get_default(size_id, pred_list_idx) : encoder->scaling_list.scaling_list_coeff[size_id][pred_list_idx]; if (!memcmp(encoder->scaling_list.scaling_list_coeff[size_id][list_id], pred_list, sizeof(int32_t) * MIN(8, kvz_g_scaling_list_size[size_id])) && ((size_id < SCALING_LIST_16x16) || (encoder->scaling_list.scaling_list_dc[size_id][list_id] == encoder->scaling_list.scaling_list_dc[size_id][pred_list_idx]))) { ref_matrix_id = pred_list_idx; scaling_list_pred_mode_flag = 0; break; } } WRITE_U(stream, scaling_list_pred_mode_flag, 1, "scaling_list_pred_mode_flag" ); if (!scaling_list_pred_mode_flag) { WRITE_UE(stream, list_id - ref_matrix_id, "scaling_list_pred_matrix_id_delta"); } else { int32_t delta; const int32_t coef_num = MIN(MAX_MATRIX_COEF_NUM, kvz_g_scaling_list_size[size_id]); const uint32_t * const scan_cg = (size_id == 0) ? g_sig_last_scan_16x16 : g_sig_last_scan_32x32; int32_t next_coef = 8; const int32_t * const coef_list = encoder->scaling_list.scaling_list_coeff[size_id][list_id]; if (size_id >= SCALING_LIST_16x16) { WRITE_SE(stream, encoder->scaling_list.scaling_list_dc[size_id][list_id] - 8, "scaling_list_dc_coef_minus8"); next_coef = encoder->scaling_list.scaling_list_dc[size_id][list_id]; } for (i = 0; i < coef_num; i++) { delta = coef_list[scan_cg[i]] - next_coef; next_coef = coef_list[scan_cg[i]]; if (delta > 127) delta -= 256; if (delta < -128) delta += 256; WRITE_SE(stream, delta, "scaling_list_delta_coef"); } } } } } static void encoder_state_write_bitstream_VUI(bitstream_t *stream, encoder_state_t * const state) { const encoder_control_t * const encoder = state->encoder_control; #ifdef KVZ_DEBUG printf("=========== VUI Set ID: 0 ===========\n"); #endif if (encoder->cfg.vui.sar_width > 0 && encoder->cfg.vui.sar_height > 0) { int i; static const struct { uint8_t width; uint8_t height; uint8_t idc; } sar[] = { // aspect_ratio_idc = 0 -> unspecified { 1, 1, 1 }, { 12, 11, 2 }, { 10, 11, 3 }, { 16, 11, 4 }, { 40, 33, 5 }, { 24, 11, 6 }, { 20, 11, 7 }, { 32, 11, 8 }, { 80, 33, 9 }, { 18, 11, 10}, { 15, 11, 11}, { 64, 33, 12}, {160, 99, 13}, { 4, 3, 14}, { 3, 2, 15}, { 2, 1, 16}, // aspect_ratio_idc = [17..254] -> reserved { 0, 0, 255 } }; for (i = 0; sar[i].idc != 255; i++) if (sar[i].width == encoder->cfg.vui.sar_width && sar[i].height == encoder->cfg.vui.sar_height) break; WRITE_U(stream, 1, 1, "aspect_ratio_info_present_flag"); WRITE_U(stream, sar[i].idc, 8, "aspect_ratio_idc"); if (sar[i].idc == 255) { // EXTENDED_SAR WRITE_U(stream, encoder->cfg.vui.sar_width, 16, "sar_width"); WRITE_U(stream, encoder->cfg.vui.sar_height, 16, "sar_height"); } } else WRITE_U(stream, 0, 1, "aspect_ratio_info_present_flag"); //IF aspect ratio info //ENDIF if (encoder->cfg.vui.overscan > 0) { WRITE_U(stream, 1, 1, "overscan_info_present_flag"); WRITE_U(stream, encoder->cfg.vui.overscan - 1, 1, "overscan_appropriate_flag"); } else WRITE_U(stream, 0, 1, "overscan_info_present_flag"); //IF overscan info //ENDIF if (encoder->cfg.vui.videoformat != 5 || encoder->cfg.vui.fullrange != 0 || encoder->cfg.vui.colorprim != 2 || encoder->cfg.vui.transfer != 2 || encoder->cfg.vui.colormatrix != 2) { WRITE_U(stream, 1, 1, "video_signal_type_present_flag"); WRITE_U(stream, encoder->cfg.vui.videoformat, 3, "chroma_format"); WRITE_U(stream, encoder->cfg.vui.fullrange, 1, "video_full_range_flag"); if (encoder->cfg.vui.colorprim != 2 || encoder->cfg.vui.transfer != 2 || encoder->cfg.vui.colormatrix != 2) { WRITE_U(stream, 1, 1, "colour_description_present_flag"); WRITE_U(stream, encoder->cfg.vui.colorprim, 8, "colour_primaries"); WRITE_U(stream, encoder->cfg.vui.transfer, 8, "transfer_characteristics"); WRITE_U(stream, encoder->cfg.vui.colormatrix, 8, "matrix_coeffs"); } else WRITE_U(stream, 0, 1, "colour_description_present_flag"); } else WRITE_U(stream, 0, 1, "video_signal_type_present_flag"); //IF video type //ENDIF if (encoder->cfg.vui.chroma_loc > 0) { WRITE_U(stream, 1, 1, "chroma_loc_info_present_flag"); WRITE_UE(stream, encoder->cfg.vui.chroma_loc, "chroma_sample_loc_type_top_field"); WRITE_UE(stream, encoder->cfg.vui.chroma_loc, "chroma_sample_loc_type_bottom_field"); } else WRITE_U(stream, 0, 1, "chroma_loc_info_present_flag"); //IF chroma loc info //ENDIF WRITE_U(stream, 0, 1, "neutral_chroma_indication_flag"); WRITE_U(stream, encoder->vui.field_seq_flag, 1, "field_seq_flag"); // 0: frames, 1: fields WRITE_U(stream, encoder->vui.frame_field_info_present_flag, 1, "frame_field_info_present_flag"); WRITE_U(stream, 0, 1, "default_display_window_flag"); //IF default display window //ENDIF WRITE_U(stream, encoder->vui.timing_info_present_flag, 1, "vui_timing_info_present_flag"); if (encoder->vui.timing_info_present_flag) { WRITE_U(stream, encoder->vui.num_units_in_tick, 32, "vui_num_units_in_tick"); WRITE_U(stream, encoder->vui.time_scale, 32, "vui_time_scale"); WRITE_U(stream, 0, 1, "vui_poc_proportional_to_timing_flag"); WRITE_U(stream, 0, 1, "vui_hrd_parameters_present_flag"); } WRITE_U(stream, 0, 1, "bitstream_restriction_flag"); //IF bitstream restriction //ENDIF } static void encoder_state_write_bitstream_SPS_extension(bitstream_t *stream, encoder_state_t * const state) { const kvz_config *cfg = &state->encoder_control->cfg; if (cfg->implicit_rdpcm && cfg->lossless) { WRITE_U(stream, 1, 1, "sps_extension_present_flag"); WRITE_U(stream, 1, 1, "sps_range_extension_flag"); WRITE_U(stream, 0, 1, "sps_multilayer_extension_flag"); WRITE_U(stream, 0, 1, "sps_3d_extension_flag"); WRITE_U(stream, 0, 5, "sps_extension_5bits"); WRITE_U(stream, 0, 1, "transform_skip_rotation_enabled_flag"); WRITE_U(stream, 0, 1, "transform_skip_context_enabled_flag"); WRITE_U(stream, 1, 1, "implicit_rdpcm_enabled_flag"); WRITE_U(stream, 0, 1, "explicit_rdpcm_enabled_flag"); WRITE_U(stream, 0, 1, "extended_precision_processing_flag"); WRITE_U(stream, 0, 1, "intra_smoothing_disabled_flag"); WRITE_U(stream, 0, 1, "high_precision_offsets_enabled_flag"); WRITE_U(stream, 0, 1, "persistent_rice_adaptation_enabled_flag"); WRITE_U(stream, 0, 1, "cabac_bypass_alignment_enabled_flag"); } else { WRITE_U(stream, 0, 1, "sps_extension_present_flag"); } } static void encoder_state_write_bitstream_seq_parameter_set(bitstream_t* stream, encoder_state_t * const state) { const encoder_control_t * encoder = state->encoder_control; #ifdef KVZ_DEBUG printf("=========== Sequence Parameter Set ID: 0 ===========\n"); #endif // TODO: profile IDC and level IDC should be defined later on WRITE_U(stream, 0, 4, "sps_video_parameter_set_id"); WRITE_U(stream, 1, 3, "sps_max_sub_layers_minus1"); WRITE_U(stream, 0, 1, "sps_temporal_id_nesting_flag"); encoder_state_write_bitstream_PTL(stream, state); WRITE_UE(stream, 0, "sps_seq_parameter_set_id"); WRITE_UE(stream, encoder->chroma_format, "chroma_format_idc"); if (encoder->chroma_format == KVZ_CSP_444) { WRITE_U(stream, 0, 1, "separate_colour_plane_flag"); } if (encoder->cfg.partial_coding.fullWidth != 0) { WRITE_UE(stream, encoder->cfg.partial_coding.fullWidth, "pic_width_in_luma_samples"); WRITE_UE(stream, encoder->cfg.partial_coding.fullHeight, "pic_height_in_luma_samples"); } else { WRITE_UE(stream, encoder->in.width, "pic_width_in_luma_samples"); WRITE_UE(stream, encoder->in.height, "pic_height_in_luma_samples"); } if (encoder->in.width != encoder->in.real_width || encoder->in.height != encoder->in.real_height) { // The standard does not seem to allow setting conf_win values such that // the number of luma samples is not a multiple of 2. Options are to either // hide one line or show an extra line of non-video. Neither seems like a // very good option, so let's not even try. assert(!(encoder->in.width % 2)); WRITE_U(stream, 1, 1, "conformance_window_flag"); WRITE_UE(stream, 0, "conf_win_left_offset"); WRITE_UE(stream, (encoder->in.width - encoder->in.real_width) >> 1, "conf_win_right_offset"); WRITE_UE(stream, 0, "conf_win_top_offset"); WRITE_UE(stream, (encoder->in.height - encoder->in.real_height) >> 1, "conf_win_bottom_offset"); } else { WRITE_U(stream, 0, 1, "conformance_window_flag"); } //IF window flag //END IF WRITE_UE(stream, encoder->bitdepth-8, "bit_depth_luma_minus8"); WRITE_UE(stream, encoder->bitdepth-8, "bit_depth_chroma_minus8"); WRITE_UE(stream, encoder->poc_lsb_bits - 4, "log2_max_pic_order_cnt_lsb_minus4"); WRITE_U(stream, 0, 1, "sps_sub_layer_ordering_info_present_flag"); //for each layer int max_buffer = max_required_dpb_size(encoder); int max_reorder = max_num_reorder_pics(encoder); if (max_buffer - 1 < max_reorder) max_buffer = max_reorder + 1; WRITE_UE(stream, max_buffer - 1, "sps_max_dec_pic_buffering_minus1"); WRITE_UE(stream, max_reorder, "sps_max_num_reorder_pics"); WRITE_UE(stream, 0, "sps_max_latency_increase_plus1"); //end for WRITE_UE(stream, MIN_SIZE-3, "log2_min_coding_block_size_minus3"); WRITE_UE(stream, MAX_DEPTH, "log2_diff_max_min_coding_block_size"); WRITE_UE(stream, 0, "log2_min_transform_block_size_minus2"); // 4x4 WRITE_UE(stream, 3, "log2_diff_max_min_transform_block_size"); // 4x4...32x32 WRITE_UE(stream, encoder->tr_depth_inter, "max_transform_hierarchy_depth_inter"); WRITE_UE(stream, encoder->cfg.tr_depth_intra, "max_transform_hierarchy_depth_intra"); // scaling list WRITE_U(stream, encoder->scaling_list.enable, 1, "scaling_list_enable_flag"); if (encoder->scaling_list.enable) { // Signal scaling list data for custom lists WRITE_U(stream, (encoder->cfg.scaling_list == KVZ_SCALING_LIST_CUSTOM) ? 1 : 0, 1, "sps_scaling_list_data_present_flag"); if (encoder->cfg.scaling_list == KVZ_SCALING_LIST_CUSTOM) { encoder_state_write_bitstream_scaling_list(stream, state); } } WRITE_U(stream, (encoder->cfg.amp_enable ? 1 : 0), 1, "amp_enabled_flag"); WRITE_U(stream, encoder->cfg.sao_type ? 1 : 0, 1, "sample_adaptive_offset_enabled_flag"); WRITE_U(stream, ENABLE_PCM, 1, "pcm_enabled_flag"); #if ENABLE_PCM == 1 WRITE_U(stream, 7, 4, "pcm_sample_bit_depth_luma_minus1"); WRITE_U(stream, 7, 4, "pcm_sample_bit_depth_chroma_minus1"); WRITE_UE(stream, 0, "log2_min_pcm_coding_block_size_minus3"); WRITE_UE(stream, 2, "log2_diff_max_min_pcm_coding_block_size"); WRITE_U(stream, 1, 1, "pcm_loop_filter_disable_flag"); #endif WRITE_UE(stream, 0, "num_short_term_ref_pic_sets"); //IF num short term ref pic sets //ENDIF WRITE_U(stream, 0, 1, "long_term_ref_pics_present_flag"); //IF long_term_ref_pics_present //ENDIF WRITE_U(stream, state->encoder_control->cfg.tmvp_enable, 1, "sps_temporal_mvp_enable_flag"); WRITE_U(stream, 0, 1, "sps_strong_intra_smoothing_enable_flag"); WRITE_U(stream, 1, 1, "vui_parameters_present_flag"); encoder_state_write_bitstream_VUI(stream, state); encoder_state_write_bitstream_SPS_extension(stream, state); kvz_bitstream_add_rbsp_trailing_bits(stream); } static void encoder_state_write_bitstream_pic_parameter_set(bitstream_t* stream, encoder_state_t * const state) { const encoder_control_t * const encoder = state->encoder_control; #ifdef KVZ_DEBUG printf("=========== Picture Parameter Set ID: 0 ===========\n"); #endif WRITE_UE(stream, 0, "pic_parameter_set_id"); WRITE_UE(stream, 0, "seq_parameter_set_id"); WRITE_U(stream, encoder->pps.dependent_slice_segments_enabled_flag, 1, "dependent_slice_segments_enabled_flag"); WRITE_U(stream, 0, 1, "output_flag_present_flag"); WRITE_U(stream, 0, 3, "num_extra_slice_header_bits"); WRITE_U(stream, encoder->cfg.signhide_enable, 1, "sign_data_hiding_flag"); WRITE_U(stream, 0, 1, "cabac_init_present_flag"); WRITE_UE(stream, 0, "num_ref_idx_l0_default_active_minus1"); WRITE_UE(stream, 0, "num_ref_idx_l1_default_active_minus1"); // If tiles and slices = tiles is enabled, signal QP in the slice header. Keeping the PPS constant for OMAF etc // Keep QP constant here also if it will be only set at CU level. bool constant_qp_in_pps = ((encoder->cfg.slices & KVZ_SLICES_TILES) && encoder->tiles_enable) || encoder->cfg.set_qp_in_cu; WRITE_SE(stream, constant_qp_in_pps ? 0 : (((int8_t)encoder->cfg.qp) - 26), "pic_init_qp_minus26"); WRITE_U(stream, 0, 1, "constrained_intra_pred_flag"); WRITE_U(stream, encoder->cfg.trskip_enable, 1, "transform_skip_enabled_flag"); if (encoder->max_qp_delta_depth >= 0) { // Use separate QP for each LCU when rate control is enabled. WRITE_U(stream, 1, 1, "cu_qp_delta_enabled_flag"); WRITE_UE(stream, encoder->max_qp_delta_depth, "diff_cu_qp_delta_depth"); } else { WRITE_U(stream, 0, 1, "cu_qp_delta_enabled_flag"); } //TODO: add QP offsets WRITE_SE(stream, 0, "pps_cb_qp_offset"); WRITE_SE(stream, 0, "pps_cr_qp_offset"); WRITE_U(stream, 0, 1, "pps_slice_chroma_qp_offsets_present_flag"); WRITE_U(stream, 0, 1, "weighted_pred_flag"); WRITE_U(stream, 0, 1, "weighted_bipred_idc"); //WRITE_U(stream, 0, 1, "dependent_slices_enabled_flag"); WRITE_U(stream, encoder->cfg.lossless, 1, "transquant_bypass_enable_flag"); WRITE_U(stream, encoder->tiles_enable, 1, "tiles_enabled_flag"); //wavefronts WRITE_U(stream, encoder->cfg.wpp, 1, "entropy_coding_sync_enabled_flag"); if (encoder->tiles_enable) { WRITE_UE(stream, encoder->cfg.tiles_width_count - 1, "num_tile_columns_minus1"); WRITE_UE(stream, encoder->cfg.tiles_height_count - 1, "num_tile_rows_minus1"); WRITE_U(stream, encoder->tiles_uniform_spacing_flag, 1, "uniform_spacing_flag"); if (!encoder->tiles_uniform_spacing_flag) { int i; for (i = 0; i < encoder->cfg.tiles_width_count - 1; ++i) { WRITE_UE(stream, encoder->tiles_col_width[i] - 1, "column_width_minus1[...]"); } for (i = 0; i < encoder->cfg.tiles_height_count - 1; ++i) { WRITE_UE(stream, encoder->tiles_row_height[i] - 1, "row_height_minus1[...]"); } } WRITE_U(stream, 0, 1, "loop_filter_across_tiles_enabled_flag"); } WRITE_U(stream, 0, 1, "loop_filter_across_slice_flag"); WRITE_U(stream, 1, 1, "deblocking_filter_control_present_flag"); //IF deblocking_filter WRITE_U(stream, 0, 1, "deblocking_filter_override_enabled_flag"); WRITE_U(stream, encoder->cfg.deblock_enable ? 0 : 1, 1, "pps_disable_deblocking_filter_flag"); //IF !disabled if (encoder->cfg.deblock_enable) { WRITE_SE(stream, encoder->cfg.deblock_beta, "beta_offset_div2"); WRITE_SE(stream, encoder->cfg.deblock_tc, "tc_offset_div2"); } //ENDIF //ENDIF WRITE_U(stream, 0, 1, "pps_scaling_list_data_present_flag"); //IF scaling_list //ENDIF WRITE_U(stream, 0, 1, "lists_modification_present_flag"); WRITE_UE(stream, 0, "log2_parallel_merge_level_minus2"); WRITE_U(stream, 0, 1, "slice_segment_header_extension_present_flag"); WRITE_U(stream, 0, 1, "pps_extension_flag"); kvz_bitstream_add_rbsp_trailing_bits(stream); } static void encoder_state_write_bitstream_prefix_sei_version(encoder_state_t * const state) { #define STR_BUF_LEN 1000 bitstream_t * const stream = &state->stream; int i, length; char buf[STR_BUF_LEN] = { 0 }; char *s = buf + 16; const kvz_config * const cfg = &state->encoder_control->cfg; // random uuid_iso_iec_11578 generated with www.famkruithof.net/uuid/uuidgen static const uint8_t uuid[16] = { 0x32, 0xfe, 0x46, 0x6c, 0x98, 0x41, 0x42, 0x69, 0xae, 0x35, 0x6a, 0x91, 0x54, 0x9e, 0xf3, 0xf1 }; memcpy(buf, uuid, 16); // user_data_payload_byte s += sprintf(s, "Kvazaar HEVC Encoder v. " VERSION_STRING " - " "Copyleft 2012-2015 - http://ultravideo.cs.tut.fi/ - options:"); s += sprintf(s, " %dx%d", cfg->width, cfg->height); s += sprintf(s, " deblock=%d:%d:%d", cfg->deblock_enable, cfg->deblock_beta, cfg->deblock_tc); s += sprintf(s, " sao=%d", cfg->sao_type); s += sprintf(s, " intra_period=%d", cfg->intra_period); s += sprintf(s, " qp=%d", cfg->qp); s += sprintf(s, " ref=%d", cfg->ref_frames); length = (int)(s - buf + 1); // length, +1 for \0 // Assert this so that in the future if the message gets longer, we remember // to increase the buf len. Divide by 2 for margin. assert(length < STR_BUF_LEN / 2); // payloadType = 5 -> user_data_unregistered WRITE_U(stream, 5, 8, "last_payload_type_byte"); // payloadSize for (i = 0; i <= length - 255; i += 255) WRITE_U(stream, 255, 8, "ff_byte"); WRITE_U(stream, length - i, 8, "last_payload_size_byte"); for (i = 0; i < length; i++) WRITE_U(stream, ((uint8_t *)buf)[i], 8, "sei_payload"); // The bitstream is already aligned, but align it anyway. kvz_bitstream_align(stream); #undef STR_BUF_LEN } /* static void encoder_state_write_active_parameter_sets_sei_message(encoder_state_t * const state) { const encoder_control_t * const encoder = state->encoder_control; bitstream_t * const stream = &state->stream; int i = 0; int active_vps_id = 0; int self_contained_cvs_flag = 0; int no_parameter_set_update_flag = 0; int num_sps_ids_minus1 = 0; int layer_sps_idx = 0; int active_seq_parameter_set_id = 0; int vps_base_layer_internal_flag = 0; int max_layers_minus1 = 0; WRITE_U(stream, 129, 8, "last_payload_type_byte"); //active_parameter_sets WRITE_U(stream, 2, 8, "last_payload_size_byte"); WRITE_U(stream, active_vps_id, 4, "active_video_parameter_set_id"); WRITE_U(stream, self_contained_cvs_flag, 1, "self_contained_cvs_flag"); WRITE_U(stream, no_parameter_set_update_flag, 1, "no_parameter_set_update_flag"); WRITE_UE(stream, num_sps_ids_minus1, "num_sps_ids_minus1"); //for (i = 0; i <= num_sps_ids_minus1; ++i) { WRITE_UE(stream, active_seq_parameter_set_id, "active_seq_parameter_set_id"); //} // for (i = vps_base_layer_internal_flag; i <= max_layers_minus1; ++i){ WRITE_UE(stream, layer_sps_idx, "layer_sps_idx"); //} kvz_bitstream_rbsp_trailing_bits(stream); //rbsp_trailing_bits } */ static void encoder_state_write_picture_timing_sei_message(encoder_state_t * const state) { bitstream_t * const stream = &state->stream; if (state->encoder_control->vui.frame_field_info_present_flag){ int8_t odd_picture = state->frame->num % 2; int8_t pic_struct = 0; //0: progressive picture, 1: top field, 2: bottom field, 3... int8_t source_scan_type = 1; //0: interlaced, 1: progressive switch (state->tile->frame->source->interlacing){ case 0: //Progressive frame pic_struct = 0; source_scan_type = 1; break; case 1: //Top field first pic_struct = odd_picture ? 2 : 1; source_scan_type = 0; break; case 2: //Bottom field first pic_struct = odd_picture ? 1 : 2; source_scan_type = 0; break; default: assert(0); //Should never execute break; } WRITE_U(stream, 1, 8, "last_payload_type_byte"); //pic_timing WRITE_U(stream, 1, 8, "last_payload_size_byte"); WRITE_U(stream, pic_struct, 4, "pic_struct"); WRITE_U(stream, source_scan_type, 2, "source_scan_type"); WRITE_U(stream, 0, 1, "duplicate_flag"); kvz_bitstream_align(stream); } } static void encoder_state_entry_points_explore(const encoder_state_t * const state, int * const r_count, int * const r_max_length) { int i; for (i = 0; state->children[i].encoder_control; ++i) { if (state->children[i].is_leaf) { const int my_length = kvz_bitstream_tell(&state->children[i].stream)/8; ++(*r_count); if (my_length > *r_max_length) { *r_max_length = my_length; } } else { encoder_state_entry_points_explore(&state->children[i], r_count, r_max_length); } } } static void encoder_state_write_bitstream_entry_points_write(bitstream_t * const stream, const encoder_state_t * const state, const int num_entry_points, const int write_length, int * const r_count) { int i; for (i = 0; state->children[i].encoder_control; ++i) { if (state->children[i].is_leaf) { const int my_length = kvz_bitstream_tell(&state->children[i].stream)/8; ++(*r_count); //Don't write the last one if (*r_count < num_entry_points) { WRITE_U(stream, my_length - 1, write_length, "entry_point_offset-minus1") } } else { encoder_state_write_bitstream_entry_points_write(stream, &state->children[i], num_entry_points, write_length, r_count); } } } static void kvz_encoder_state_write_bitstream_slice_header_independent( struct bitstream_t * const stream, struct encoder_state_t * const state) { const encoder_control_t * const encoder = state->encoder_control; int j; int ref_negative = 0; int ref_positive = 0; if (encoder->cfg.gop_len) { for (j = 0; j < state->frame->ref->used_size; j++) { if (state->frame->ref->pocs[j] < state->frame->poc) { ref_negative++; } else { ref_positive++; } } } else ref_negative = state->frame->ref->used_size; WRITE_UE(stream, state->frame->slicetype, "slice_type"); if (state->frame->pictype != KVZ_NAL_IDR_W_RADL && state->frame->pictype != KVZ_NAL_IDR_N_LP) { const int poc_lsb = state->frame->poc & ((1 << encoder->poc_lsb_bits) - 1); WRITE_U(stream, poc_lsb, encoder->poc_lsb_bits, "pic_order_cnt_lsb"); int last_poc = 0; int poc_shift = 0; WRITE_U(stream, 0, 1, "short_term_ref_pic_set_sps_flag"); WRITE_UE(stream, ref_negative, "num_negative_pics"); WRITE_UE(stream, ref_positive, "num_positive_pics"); for (j = 0; j < ref_negative; j++) { int8_t delta_poc = 0; if (encoder->cfg.gop_len) { int8_t found = 0; do { delta_poc = encoder->cfg.gop[state->frame->gop_offset].ref_neg[j + poc_shift]; for (int i = 0; i < state->frame->ref->used_size; i++) { if (state->frame->ref->pocs[i] == state->frame->poc - delta_poc) { found = 1; break; } } if (!found) poc_shift++; if (j + poc_shift == ref_negative) { fprintf(stderr, "Failure, reference not found!"); exit(EXIT_FAILURE); } } while (!found); } WRITE_UE(stream, encoder->cfg.gop_len?delta_poc - last_poc - 1:0, "delta_poc_s0_minus1"); last_poc = delta_poc; WRITE_U(stream, !state->frame->is_irap, 1, "used_by_curr_pic_s0_flag"); } last_poc = 0; poc_shift = 0; for (j = 0; j < ref_positive; j++) { int8_t delta_poc = 0; if (encoder->cfg.gop_len) { int8_t found = 0; do { delta_poc = encoder->cfg.gop[state->frame->gop_offset].ref_pos[j + poc_shift]; for (int i = 0; i < state->frame->ref->used_size; i++) { if (state->frame->ref->pocs[i] == state->frame->poc + delta_poc) { found = 1; break; } } if (!found) poc_shift++; if (j + poc_shift == ref_positive) { fprintf(stderr, "Failure, reference not found!"); exit(EXIT_FAILURE); } } while (!found); } WRITE_UE(stream, encoder->cfg.gop_len ? delta_poc - last_poc - 1 : 0, "delta_poc_s1_minus1"); last_poc = delta_poc; WRITE_U(stream, !state->frame->is_irap, 1, "used_by_curr_pic_s1_flag"); } //WRITE_UE(stream, 0, "short_term_ref_pic_set_idx"); if (state->encoder_control->cfg.tmvp_enable) { WRITE_U(stream, ref_negative ? 1 : 0, 1, "slice_temporal_mvp_enabled_flag"); } } //end if //end if if (encoder->cfg.sao_type) { WRITE_U(stream, 1, 1, "slice_sao_luma_flag"); if (encoder->chroma_format != KVZ_CSP_400) { WRITE_U(stream, 1, 1, "slice_sao_chroma_flag"); } } if (state->frame->slicetype != KVZ_SLICE_I) { WRITE_U(stream, 1, 1, "num_ref_idx_active_override_flag"); WRITE_UE(stream, MAX(0, ((int)state->frame->ref_LX_size[0]) - 1), "num_ref_idx_l0_active_minus1"); if (state->frame->slicetype == KVZ_SLICE_B) { WRITE_UE(stream, MAX(0, ((int)state->frame->ref_LX_size[1]) - 1), "num_ref_idx_l1_active_minus1"); WRITE_U(stream, 0, 1, "mvd_l1_zero_flag"); } // Temporal Motion Vector Prediction flags if (state->encoder_control->cfg.tmvp_enable && ref_negative > 0) { if (state->frame->slicetype == KVZ_SLICE_B) { // Always use L0 for prediction WRITE_U(stream, 1, 1, "collocated_from_l0_flag"); } if (ref_negative > 1) { // Use first reference from L0 // ToDo: use better reference WRITE_UE(stream, 0, "collocated_ref_idx"); } } const uint8_t max_merge_cands = state->encoder_control->cfg.max_merge; WRITE_UE(stream, 5- max_merge_cands, "five_minus_max_num_merge_cand"); } { // If tiles are enabled, signal the full QP here (relative to the base value of 26) // If QP is to be set only at CU level, force slice_qp_delta zero bool signal_qp_in_slice_header = (encoder->cfg.slices & KVZ_SLICES_TILES) && encoder->tiles_enable; int slice_qp_delta = state->frame->QP - (signal_qp_in_slice_header ? 26 : encoder->cfg.qp); if(encoder->cfg.set_qp_in_cu) slice_qp_delta = 0; WRITE_SE(stream, slice_qp_delta, "slice_qp_delta"); } } void kvz_encoder_state_write_bitstream_slice_header( struct bitstream_t * const stream, struct encoder_state_t * const state, bool independent) { const encoder_control_t * const encoder = state->encoder_control; #ifdef KVZ_DEBUG printf("=========== Slice ===========\n"); #endif if (encoder->cfg.partial_coding.fullWidth != 0) { state->slice->start_in_rs = encoder->cfg.partial_coding.startCTU_x + CEILDIV(encoder->cfg.partial_coding.fullWidth, 64) * encoder->cfg.partial_coding.startCTU_y; } bool first_slice_segment_in_pic = (state->slice->start_in_rs == 0); if ((state->encoder_control->cfg.slices & KVZ_SLICES_WPP) && state->wfrow->lcu_offset_y > 0) { first_slice_segment_in_pic = false; } WRITE_U(stream, first_slice_segment_in_pic, 1, "first_slice_segment_in_pic_flag"); if (state->frame->pictype >= KVZ_NAL_BLA_W_LP && state->frame->pictype <= KVZ_NAL_RSV_IRAP_VCL23) { WRITE_U(stream, 0, 1, "no_output_of_prior_pics_flag"); } WRITE_UE(stream, 0, "slice_pic_parameter_set_id"); if (!first_slice_segment_in_pic) { if (encoder->pps.dependent_slice_segments_enabled_flag) { WRITE_U(stream, !independent, 1, "dependent_slice_segment_flag"); } int lcu_cnt = encoder->in.width_in_lcu * encoder->in.height_in_lcu; if (encoder->cfg.partial_coding.fullWidth != 0) { lcu_cnt = CEILDIV(encoder->cfg.partial_coding.fullWidth, 64) * CEILDIV(encoder->cfg.partial_coding.fullHeight, 64); } int num_bits = kvz_math_ceil_log2(lcu_cnt); int slice_start_rs = state->slice->start_in_rs; if (state->encoder_control->cfg.slices & KVZ_SLICES_WPP) { slice_start_rs += state->wfrow->lcu_offset_y * state->tile->frame->width_in_lcu; } WRITE_U(stream, slice_start_rs, num_bits, "slice_segment_address"); } if (independent) { kvz_encoder_state_write_bitstream_slice_header_independent(stream, state); } if (encoder->tiles_enable || encoder->cfg.wpp) { int num_entry_points = 0; int max_length_seen = 0; if (state->is_leaf) { num_entry_points = 1; } else { encoder_state_entry_points_explore(state, &num_entry_points, &max_length_seen); } int num_offsets = num_entry_points - 1; WRITE_UE(stream, num_offsets, "num_entry_point_offsets"); if (num_offsets > 0) { int entry_points_written = 0; int offset_len = kvz_math_floor_log2(max_length_seen) + 1; WRITE_UE(stream, offset_len - 1, "offset_len_minus1"); encoder_state_write_bitstream_entry_points_write(stream, state, num_entry_points, offset_len, &entry_points_written); } } } /** * \brief Add a checksum SEI message to the bitstream. * \param encoder The encoder. * \returns Void */ static void add_checksum(encoder_state_t * const state) { bitstream_t * const stream = &state->stream; const videoframe_t * const frame = state->tile->frame; unsigned char checksum[3][SEI_HASH_MAX_LENGTH]; kvz_nal_write(stream, KVZ_NAL_SUFFIX_SEI_NUT, 0, 0); WRITE_U(stream, 132, 8, "sei_type"); int num_colors = (state->encoder_control->chroma_format == KVZ_CSP_400 ? 1 : 3); switch (state->encoder_control->cfg.hash) { case KVZ_HASH_CHECKSUM: kvz_image_checksum(frame->rec, checksum, state->encoder_control->bitdepth); WRITE_U(stream, 1 + num_colors * 4, 8, "size"); WRITE_U(stream, 2, 8, "hash_type"); // 2 = checksum for (int i = 0; i < num_colors; ++i) { uint32_t checksum_val = ( (checksum[i][0] << 24) + (checksum[i][1] << 16) + (checksum[i][2] << 8) + (checksum[i][3])); WRITE_U(stream, checksum_val, 32, "picture_checksum"); CHECKPOINT("checksum[%d] = %u", i, checksum_val); } break; case KVZ_HASH_MD5: kvz_image_md5(frame->rec, checksum, state->encoder_control->bitdepth); WRITE_U(stream, 1 + num_colors * 16, 8, "size"); WRITE_U(stream, 0, 8, "hash_type"); // 0 = md5 for (int i = 0; i < num_colors; ++i) { for (int b = 0; b < 16; ++b) { WRITE_U(stream, checksum[i][b], 8, "picture_md5"); } } break; case KVZ_HASH_NONE: // Means we shouldn't be writing this SEI. assert(0); } kvz_bitstream_align(stream); // spec:sei_rbsp() rbsp_trailing_bits kvz_bitstream_add_rbsp_trailing_bits(stream); } static void encoder_state_write_slice_header( bitstream_t * stream, encoder_state_t * state, bool independent) { kvz_nal_write(stream, state->frame->pictype, 0, state->frame->first_nal); state->frame->first_nal = false; kvz_encoder_state_write_bitstream_slice_header(stream, state, independent); kvz_bitstream_add_rbsp_trailing_bits(stream); } /** * \brief Move child state bitstreams to the parent stream. */ static void encoder_state_write_bitstream_children(encoder_state_t * const state) { // Write Slice headers to the parent stream instead of the child stream // in case the child stream is a leaf with something in it already. for (int i = 0; state->children[i].encoder_control; ++i) { if (state->children[i].type == ENCODER_STATE_TYPE_SLICE) { encoder_state_write_slice_header(&state->stream, &state->children[i], true); } else if (state->children[i].type == ENCODER_STATE_TYPE_WAVEFRONT_ROW) { if ((state->encoder_control->cfg.slices & KVZ_SLICES_WPP) && i != 0) { // Add header for dependent WPP row slice. encoder_state_write_slice_header(&state->stream, &state->children[i], false); } } kvz_encoder_state_write_bitstream(&state->children[i]); kvz_bitstream_move(&state->stream, &state->children[i].stream); } } static void encoder_state_write_bitstream_main(encoder_state_t * const state) { const encoder_control_t * const encoder = state->encoder_control; bitstream_t * const stream = &state->stream; uint64_t curpos = kvz_bitstream_tell(stream); // The first NAL unit of the access unit must use a long start code. state->frame->first_nal = true; // Access Unit Delimiter (AUD) if (encoder->cfg.aud_enable) { state->frame->first_nal = false; encoder_state_write_bitstream_aud(state); } if (encoder_state_must_write_vps(state)) { state->frame->first_nal = false; kvz_encoder_state_write_parameter_sets(&state->stream, state); } // Send Kvazaar version information only in the first frame. if (state->frame->num == 0 && encoder->cfg.add_encoder_info) { kvz_nal_write(stream, KVZ_NAL_PREFIX_SEI_NUT, 0, state->frame->first_nal); state->frame->first_nal = false; encoder_state_write_bitstream_prefix_sei_version(state); // spec:sei_rbsp() rbsp_trailing_bits kvz_bitstream_add_rbsp_trailing_bits(stream); } //SEI messages for interlacing if (encoder->vui.frame_field_info_present_flag) { // These should be optional, needed for earlier versions // of HM decoder to accept bitstream //kvz_nal_write(stream, KVZ_NAL_PREFIX_SEI_NUT, 0, 0); //encoder_state_write_active_parameter_sets_sei_message(state); //kvz_bitstream_rbsp_trailing_bits(stream); kvz_nal_write(stream, KVZ_NAL_PREFIX_SEI_NUT, 0, state->frame->first_nal); state->frame->first_nal = false; encoder_state_write_picture_timing_sei_message(state); // spec:sei_rbsp() rbsp_trailing_bits kvz_bitstream_add_rbsp_trailing_bits(stream); } encoder_state_write_bitstream_children(state); if (state->encoder_control->cfg.hash != KVZ_HASH_NONE) { // Calculate checksum add_checksum(state); } //Get bitstream length for stats uint64_t newpos = kvz_bitstream_tell(stream); state->stats_bitstream_length = (newpos >> 3) - (curpos >> 3); if (state->frame->num > 0) { state->frame->total_bits_coded = state->previous_encoder_state->frame->total_bits_coded; } state->frame->total_bits_coded += newpos - curpos; if(state->encoder_control->cfg.rc_algorithm == KVZ_OBA || state->encoder_control->cfg.stats_file_prefix) { kvz_update_after_picture(state); } if(state->frame->gop_offset) state->frame->cur_gop_bits_coded = state->previous_encoder_state->frame->cur_gop_bits_coded; state->frame->cur_gop_bits_coded += newpos - curpos; } void kvz_encoder_state_write_bitstream(encoder_state_t * const state) { if (!state->is_leaf) { switch (state->type) { case ENCODER_STATE_TYPE_MAIN: encoder_state_write_bitstream_main(state); break; case ENCODER_STATE_TYPE_TILE: case ENCODER_STATE_TYPE_SLICE: encoder_state_write_bitstream_children(state); break; default: fprintf(stderr, "Unsupported node type %c!\n", state->type); assert(0); } } } void kvz_encoder_state_worker_write_bitstream(void * opaque) { kvz_encoder_state_write_bitstream((encoder_state_t *) opaque); } void kvz_encoder_state_write_parameter_sets(bitstream_t *stream, encoder_state_t * const state) { // Video Parameter Set (VPS) kvz_nal_write(stream, KVZ_NAL_VPS_NUT, 0, 1); encoder_state_write_bitstream_vid_parameter_set(stream, state); // Sequence Parameter Set (SPS) kvz_nal_write(stream, KVZ_NAL_SPS_NUT, 0, 1); encoder_state_write_bitstream_seq_parameter_set(stream, state); // Picture Parameter Set (PPS) kvz_nal_write(stream, KVZ_NAL_PPS_NUT, 0, 1); encoder_state_write_bitstream_pic_parameter_set(stream, state); }
37.313211
200
0.685338
[ "geometry", "vector" ]
707e2f4798b396abafdcc4d8a6e70faf99323735
25,508
c
C
csrc/org/trifort/rootbeer/runtime/CUDAContext.c
mxmlnkn/rootbeer1
e48b9aefd1d4dbf949c308d3208a4d036662e5bf
[ "MIT" ]
19
2016-04-06T00:26:02.000Z
2022-01-17T14:02:35.000Z
csrc/org/trifort/rootbeer/runtime/CUDAContext.c
mxmlnkn/rootbeer1
e48b9aefd1d4dbf949c308d3208a4d036662e5bf
[ "MIT" ]
null
null
null
csrc/org/trifort/rootbeer/runtime/CUDAContext.c
mxmlnkn/rootbeer1
e48b9aefd1d4dbf949c308d3208a4d036662e5bf
[ "MIT" ]
4
2017-05-01T11:18:19.000Z
2020-05-15T08:49:04.000Z
#include "CUDAContext.h" #include <cuda.h> #include <stdio.h> // printf, sprintf #include <stdlib.h> // malloc, free #include <string.h> // strlen #include <assert.h> #include "PointerCasting.h" #include "CUDARuntime.h" #include "Stopwatch.h" #define DEBUG_CUDA_CONTEXT 0 /* e.g. because of alignment to 16 the last 4 bits will always be 0 * and can be cut off for compression! */ #define N_ALIGNED_ZERO_BITS 4 #define CE( STATUS ) \ { \ const CUresult status = STATUS; \ const char *errorName, *errorString; \ cuGetErrorName ( status, &errorName ); \ cuGetErrorString( status, &errorString ); \ if ( status != CUDA_SUCCESS ) \ { \ char msg[8*1024]; \ sprintf( msg, \ "Line %i, command: "#STATUS"\n failed with " \ "error code %i (%.1000s) : %.4000s\n", \ __LINE__, status, errorString, errorString ); \ throw_cuda_error_exception( env, msg, status, s->device ); \ return; \ } \ } #define __PRINTOUT(...) sprintf( &output[ strlen( output ) ], __VA_ARGS__ ); //#define __PRINTOUT(...) printf( __VA_ARGS__ ); /* One reason for using the CUDA driver api is that nvcc isn't needed, * instead this can be compiled with gcc! */ struct ContextState { CUdevice device ; CUcontext context ; CUmodule module ; CUfunction function ; CUdeviceptr gpu_info_space ; CUdeviceptr gpu_object_mem ; CUdeviceptr gpu_handles_mem ; CUdeviceptr gpu_exceptions_mem ; CUdeviceptr gpu_class_mem ; CUdeviceptr gpu_heap_end ; void * cpu_object_mem ; void * cpu_handles_mem ; void * cpu_exceptions_mem ; void * cpu_class_mem ; jlong cpu_object_mem_size ; jlong cpu_handles_mem_size ; jlong cpu_exceptions_mem_size ; jlong cpu_class_mem_size ; jint * info_space ; jint block_count_x ; jint block_count_y ; jint using_kernel_templates_offset; jint using_exceptions ; jint context_built ; struct stopwatch execMemcopyToDevice ; struct stopwatch execGpuRun ; struct stopwatch execMemcopyFromDevice ; }; /* interfaced java classes and methods which we want to access / call */ jclass cuda_memory_class ; jmethodID get_address_method ; jmethodID get_size_method ; jmethodID get_heap_end_method; jmethodID set_heap_end_method; jclass stats_row_class ; jmethodID set_driver_times ; /** * Throws a runtimeexception called CudaMemoryException * allocd - number of bytes tried to allocate * id - variable the memory assignment was for */ void throw_cuda_error_exception ( JNIEnv * env , const char * message, int error , CUdevice device ) { char msg[4*1024]; jclass exp; jfieldID fid; int a = 0; int b = 0; char name[1024]; exp = (*env)->FindClass(env,"org/trifort/rootbeer/runtime/CudaErrorException"); // we truncate the message to 900 characters to stop any buffer overflow switch ( error ) { case CUDA_ERROR_OUT_OF_MEMORY: { sprintf( msg, "CUDA_ERROR_OUT_OF_MEMORY: %.900s",message ); break; } case CUDA_ERROR_NO_BINARY_FOR_GPU: { cuDeviceGetName(name,1024,device); cuDeviceComputeCapability(&a, &b, device); sprintf( msg, "No binary for gpu. %.900s Selected %s (%d.%d). 2.0 compatibility required.", message, name, a, b ); break; } default: sprintf( msg, "ERROR STATUS:%i : %.900s", error, message ); } fid = (*env)->GetFieldID(env,exp, "cudaError_enum", "I"); (*env)->SetLongField(env,exp,fid, (jint)error); (*env)->ThrowNew(env,exp,msg); return; } /** * Cache function pointers to Java class methods */ JNIEXPORT void JNICALL Java_org_trifort_rootbeer_runtime_CUDAContext_initializeDriver ( JNIEnv *env, jobject this_ref ) { cuda_memory_class = (*env)->FindClass ( env, "org/trifort/rootbeer/runtime/FixedMemory" ); get_address_method = (*env)->GetMethodID( env, cuda_memory_class, "getAddress" , "()J" ); get_size_method = (*env)->GetMethodID( env, cuda_memory_class, "getSize" , "()J" ); get_heap_end_method = (*env)->GetMethodID( env, cuda_memory_class, "getHeapEndPtr", "()J" ); set_heap_end_method = (*env)->GetMethodID( env, cuda_memory_class, "setHeapEndPtr", "(J)V" ); stats_row_class = (*env)->FindClass ( env, "org/trifort/rootbeer/runtime/StatsRow" ); set_driver_times = (*env)->GetMethodID( env, stats_row_class, "setDriverTimes" , "(JJJ)V" ); } JNIEXPORT jlong JNICALL Java_org_trifort_rootbeer_runtime_CUDAContext_allocateNativeContext (JNIEnv *env, jobject this_ref) { struct ContextState * ret = (struct ContextState *) malloc(sizeof(struct ContextState)); ret->context_built = 0; return pointerToJlong( ret ); } JNIEXPORT void JNICALL Java_org_trifort_rootbeer_runtime_CUDAContext_freeNativeContext ( JNIEnv *env, jobject this_ref, jlong reference ) { struct ContextState * s /* stateObject */ = (struct ContextState *) jlongToPointer( reference ); if ( s->context_built ) { free ( s->info_space ); cuMemFree ( s->gpu_info_space ); cuMemFree ( s->gpu_object_mem ); cuMemFree ( s->gpu_handles_mem ); cuMemFree ( s->gpu_exceptions_mem ); cuMemFree ( s->gpu_class_mem ); cuMemFree ( s->gpu_heap_end ); cuCtxDestroy( s->context ); } free( s ); } /** * Sets the state as specified by the multitude of parameters * * Sets specified GPU device, creates CUDA context, sets shared memory, * configuration, kernel parameters and kernel configuration. * * @todo Can on thread have multiple CUDA contexts and work on multiple * GPU devices in parallel? Or do I need to call cuDeviceSet before each * command? **/ JNIEXPORT void JNICALL Java_org_trifort_rootbeer_runtime_CUDAContext_nativeBuildState ( JNIEnv * env , jobject rThisRef , jlong rNativeContext , jint rDeviceIndex , jbyteArray rCubinFile , jint rCubinLength , jint rThreadCountX , jint rThreadCountY , jint rThreadCountZ , jint rBlockCountX , jint rBlockCountY , jint rNumThreads , jobject rObjectMem , /* instances of Memory.java */ jobject rHandlesMem , /* either: */ jobject rExceptionsMem , /* FixedMemory.java */ jobject rClassMem , /* or: CheckedMemody.java */ jint rUsingExceptions, jint rCacheConfig ) { /* just basically an alias + pointer conversion */ struct ContextState * const s /* stateObject */ = (struct ContextState *) jlongToPointer( rNativeContext ); s->block_count_x = rBlockCountX ; s->block_count_y = rBlockCountY ; s->using_exceptions = rUsingExceptions; CE( cuDeviceGet( &(s->device) , rDeviceIndex ) ) CE( cuCtxCreate( &(s->context), CU_CTX_MAP_HOST, s->device ) ) #if ( ! defined( NDEBUG ) ) && ( DEBUG_CUDA_CONTEXT >= 9 ) printf( "Created CUDA Context for device number %i (cuDevice: %i)\n", rDeviceIndex, s->device ); #endif /* Loads fatCubin (device code for multiple architectures) into a module */ void * fatcubin = malloc( rCubinLength ); // holds cubin in memory /* http://docs.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html#wp1716 * >copies< C javaByteArray rCubinFile into raw C data fatcubin */ (*env)->GetByteArrayRegion( env, rCubinFile, 0, rCubinLength, fatcubin ); /* http://docs.nvidia.com/cuda/cuda-c-programming-guide/#module */ CE( cuModuleLoadFatBinary( &(s->module), fatcubin) ) free( fatcubin ); /* get kernel which to start from loaded module (i.e. ptx library) */ CE( cuModuleGetFunction( &(s->function), s->module, "_Z5entryPiS_ii" ) ) /* c++filt '_Z5entryPiS_ii' -> entry(int*, int*, int, int) * As can be seen in generated_unix.xu the meaning of those kernel * parameters is: * __global__ void entry * ( * int * handles, * int * exceptions, * int numThreads, * int usingKernelTemplates * ) */ CUfunc_cache cache_config_enum; // prefer shared, L1, ... if ( rCacheConfig != 0 ) { switch ( rCacheConfig ) { case 1: cache_config_enum = CU_FUNC_CACHE_PREFER_SHARED; break; case 2: cache_config_enum = CU_FUNC_CACHE_PREFER_L1 ; break; case 3: cache_config_enum = CU_FUNC_CACHE_PREFER_EQUAL ; break; } CE( cuFuncSetCacheConfig( s->function, cache_config_enum ) ) } s->cpu_object_mem = jlongToPointer( (*env)->CallLongMethod( env, rObjectMem , get_address_method ) ); s->cpu_handles_mem = jlongToPointer( (*env)->CallLongMethod( env, rHandlesMem , get_address_method ) ); s->cpu_exceptions_mem = jlongToPointer( (*env)->CallLongMethod( env, rExceptionsMem, get_address_method ) ); s->cpu_class_mem = jlongToPointer( (*env)->CallLongMethod( env, rClassMem , get_address_method ) ); s->cpu_object_mem_size = (*env)->CallLongMethod( env, rObjectMem , get_size_method ); s->cpu_handles_mem_size = (*env)->CallLongMethod( env, rHandlesMem , get_size_method ); s->cpu_exceptions_mem_size = (*env)->CallLongMethod( env, rExceptionsMem, get_size_method ); s->cpu_class_mem_size = (*env)->CallLongMethod( env, rClassMem , get_size_method ); s->info_space = (jint *) malloc( sizeof( *(s->info_space) ) ); /** allocate corresponding memory on gpu **/ CE( cuMemAlloc( &( s->gpu_info_space ), sizeof( *(s->info_space) ) ) ) CE( cuMemAlloc( &( s->gpu_object_mem ), s->cpu_object_mem_size ) ) CE( cuMemAlloc( &( s->gpu_handles_mem ), s->cpu_handles_mem_size ) ) CE( cuMemAlloc( &( s->gpu_class_mem ), s->cpu_class_mem_size ) ) CE( cuMemAlloc( &( s->gpu_heap_end ), sizeof( jint ) ) ) if ( s->using_exceptions ) CE( cuMemAlloc( &( s->gpu_exceptions_mem ), s->cpu_exceptions_mem_size ) ) else s->gpu_exceptions_mem = (CUdeviceptr) 0; /******** set function parameters ********/ /* cuParamSet is officially deprecated ... * http://horacio9573.no-ip.org/cuda/group__CUDA__EXEC__DEPRECATED_gdf689dac0db8f6c1232c339d3f923554.html * Since CUDA Driver 4.0 i.e. NVCC/CUDA 4.0 there is cuLaunchKernel instead * http://stackoverflow.com/questions/19240658/cuda-kernel-launch-parameters-explained-right * It seems like Rootbeer wants to support even 3.0 and 3.2, see * src/org/trifort/rootbeer/generate/opencl/tweaks/GencodeOptions.java */ /* Sets the total size in bytes needed by the function parameters of the kernel */ int const nBytesTotalParameters = 2 * sizeof(CUdeviceptr) + 2 * sizeof(int); CE( cuParamSetSize(s->function, nBytesTotalParameters ) ) int offset = 0; // parameter list offset for cuParamSet{i,v} #define setNextParam( SRC, NBYTES ) \ CE( cuParamSetv( s->function, offset, (void *) SRC, NBYTES ) ) \ offset += NBYTES; setNextParam( &(s->gpu_handles_mem ), sizeof(CUdeviceptr) ) setNextParam( &(s->gpu_exceptions_mem), sizeof(CUdeviceptr) ) CE( cuParamSeti( s->function, offset, rNumThreads) ); offset += sizeof(int); /* The last kernel parameter is set by cudaRun, remember only the offset! */ assert( offset >= 0 ); assert( (unsigned int) offset == nBytesTotalParameters - sizeof(int) ); s->using_kernel_templates_offset = offset; CE( cuFuncSetBlockShape( s->function, rThreadCountX, rThreadCountY, rThreadCountZ ) ) s->context_built = 1; /* debug output, trying to understand rootbeer */ #if ( ! defined( NDEBUG ) ) && ( DEBUG_CUDA_CONTEXT >= 10 ) char * output = malloc( 1024*1024 ); output[0] = '\0'; __PRINTOUT( "+-------------- [nativeBuildState] --------------\n" ); #define __PRINTI( NAME ) __PRINTOUT( "| %32s = %10i\n", #NAME, NAME ); __PRINTI( rCubinLength ) __PRINTI( rThreadCountX ) __PRINTI( rThreadCountY ) __PRINTI( rThreadCountZ ) __PRINTI( rBlockCountX ) __PRINTI( rBlockCountY ) __PRINTI( rNumThreads ) __PRINTI( rCacheConfig ) __PRINTI( rDeviceIndex ) __PRINTI( s->using_kernel_templates_offset ) __PRINTOUT( "|\n" ); #define __PRINTP( PTR, SIZE ) \ __PRINTOUT( "| %32s = %p (size: %10lu B = %10lu KiB)\n", \ #PTR, PTR, SIZE, SIZE / 1024 ); __PRINTP( (void*) s->cpu_object_mem , (unsigned long) s->cpu_object_mem_size ) __PRINTP( (void*) s->cpu_handles_mem , (unsigned long) s->cpu_handles_mem_size ) __PRINTP( (void*) s->cpu_exceptions_mem, (unsigned long) s->cpu_exceptions_mem_size ) __PRINTP( (void*) s->cpu_class_mem , (unsigned long) s->cpu_class_mem_size ) __PRINTOUT( "|\n" ); __PRINTP( (void*) s->gpu_info_space , sizeof( *(s->info_space) ) ) __PRINTP( (void*) s->gpu_object_mem , (unsigned long) s->cpu_object_mem_size ) __PRINTP( (void*) s->gpu_handles_mem , (unsigned long) s->cpu_handles_mem_size ) __PRINTP( (void*) s->gpu_class_mem , (unsigned long) s->cpu_class_mem_size ) __PRINTP( (void*) s->gpu_heap_end , sizeof( jint ) ) __PRINTP( (void*) s->gpu_exceptions_mem, sizeof( jint ) ) __PRINTOUT( "|\n" ); printf( "%s", output ); free( output ); #undef __PRINTI #undef __PRINTP #endif } JNIEXPORT void JNICALL Java_org_trifort_rootbeer_runtime_CUDAContext_cudaRun ( JNIEnv * env, jobject this_ref, jlong nativeContext, jobject object_mem, /**< maybe better to save object in member on native build state, not just address? -> wouldn't update member variables -> address to object then? */ jint using_kernel_templates, jobject stats_row ) { struct ContextState * const s = (struct ContextState *) jlongToPointer( nativeContext ); stopwatchStart(&(s->execMemcopyToDevice)); jlong heap_end_long; heap_end_long = (*env)->CallLongMethod( env, object_mem, get_heap_end_method ); #if ( ! defined( NDEBUG ) ) && ( DEBUG_CUDA_CONTEXT >= 10 ) unsigned int nMaxBytesOutput = 16*1024*1024; char * output = malloc( nMaxBytesOutput ); output[0] = '\0'; __PRINTOUT( "[cudaRun] heap_end_long = %lu\n", heap_end_long ); #endif assert( heap_end_long >= 0 ); /* it also may not be -1 which is sometimes used for null ! */ jint heap_end_int = (jint)( heap_end_long >> N_ALIGNED_ZERO_BITS ); /* check that compression is reversible (includes check for numbers not fitting into jint) */ assert( ( (jlong) heap_end_int ) << N_ALIGNED_ZERO_BITS == heap_end_long ); s->info_space[0] = heap_end_int; unsigned long long hostMLocal[3]; hostMLocal[0] = s->gpu_object_mem; assert( s->cpu_object_mem_size >= 0 ); hostMLocal[1] = s->cpu_object_mem_size >> N_ALIGNED_ZERO_BITS; assert( s->cpu_object_mem_size >= 0 ); assert( sizeof(jint) == 4 && "If this assert fails the assert after this may need to be rewritten!" ); assert( hostMLocal[1] < 2147483647 ); /* equality would be more clean programming, but it just isn't, and if * the hostMLocal version is smaller no harm is done, as that size is used * for the rootbeer garbage collector. (Currently the size is set manually * by the user in createContext arguments or with */ assert( hostMLocal[1] << N_ALIGNED_ZERO_BITS <= (unsigned long long) s->cpu_object_mem_size ); hostMLocal[2] = s->gpu_class_mem; /* Get address and size of global_free_pointer which is defined in * src/org/trifort/rootbeer/generate/opencl/CudaKernel.c * from the loaded module i.e. ptx library-like binary. */ size_t nBytesDeviceGlobalFreePointer = 0; CUdeviceptr deviceGlobalFreePointer; CE( cuModuleGetGlobal( &deviceGlobalFreePointer, &nBytesDeviceGlobalFreePointer, s->module, "global_free_pointer" ) ) assert( nBytesDeviceGlobalFreePointer == sizeof( *(s->info_space) ) ); CUdeviceptr deviceMLocal; size_t nBytesDeviceMLocal = 0; CE( cuModuleGetGlobal( &deviceMLocal, &nBytesDeviceMLocal, s->module, "m_Local" ) ) assert( nBytesDeviceMLocal == sizeof( hostMLocal ) ); /* debug output, trying to understand rootbeer */ #if ( ! defined( NDEBUG ) ) && ( DEBUG_CUDA_CONTEXT >= 10 ) #define __PRINTI( NAME ) \ __PRINTOUT( "| %32s = % 10i\n", #NAME, NAME ); __PRINTOUT( "+-------------- [nativeBuildState] --------------\n" ); __PRINTI( heap_end_int ) #define __PRINTP( PTR, SIZE ) \ __PRINTOUT( "| %32s = %p (size: %10lu B = %10lu KiB)\n", \ #PTR, PTR, SIZE, SIZE / 1024 ); __PRINTP( (void*) deviceGlobalFreePointer, nBytesDeviceGlobalFreePointer ) __PRINTP( (void*) deviceMLocal , nBytesDeviceMLocal ) __PRINTOUT( "|\n" ); //__PRINTOUT( "+-------- Handles to send to GPU:\n" ): //int i = 0; //while ( (i+1) * sizeof(long) <= s->cpu_handles_mem_size ) //{ // if ( i % 8 == 0 ) // __PRINTOUT( "\n" ); // // __PRINTOUT( "% 8d ", ((long*)s->cpu_handles_mem)[i] ); // ++i; //} /* make backup of handle memory */ void * handlesSentToGpu = malloc( s->cpu_handles_mem_size ); memcpy( handlesSentToGpu, s->cpu_handles_mem, s->cpu_handles_mem_size ); void * objectsSentToGpu = malloc( s->cpu_object_mem_size ); memcpy( objectsSentToGpu, s->cpu_object_mem, s->cpu_object_mem_size ); #undef __PRINTI #undef __PRINTP #endif /** copy data **/ /* why not gpu_info_space used here ??? gpu_info_space is unused else. * also info_space holds gpu_heap_end >> 4. Why this duplication? */ CE( cuMemcpyHtoD( deviceGlobalFreePointer, s->info_space , sizeof( *(s->info_space) ) ) ) CE( cuMemcpyHtoD( deviceMLocal , hostMLocal , sizeof( hostMLocal ) ) ) CE( cuMemcpyHtoD( s->gpu_object_mem , s->cpu_object_mem , s->cpu_object_mem_size ) ) CE( cuMemcpyHtoD( s->gpu_handles_mem , s->cpu_handles_mem, s->cpu_handles_mem_size ) ) CE( cuMemcpyHtoD( s->gpu_class_mem , s->cpu_class_mem , s->cpu_class_mem_size ) ) CE( cuMemcpyHtoD( s->gpu_heap_end , &(heap_end_int) , sizeof( heap_end_int ) ) ) if ( s->using_exceptions ) CE( cuMemcpyHtoD( s->gpu_exceptions_mem, s->cpu_exceptions_mem, s->cpu_exceptions_mem_size ) ) stopwatchStop( &s->execMemcopyToDevice ); /** launch **/ stopwatchStart( &s->execGpuRun ); #if ( ! defined( NDEBUG ) ) && ( DEBUG_CUDA_CONTEXT >= 9 ) CUdevice deviceWhereLaunched = 0; CE( cuCtxGetDevice( &deviceWhereLaunched ) ) printf( "Launching kernel on CUdevice: %i\n", deviceWhereLaunched ); #endif CE( cuParamSeti ( s->function, s->using_kernel_templates_offset, using_kernel_templates ) ) CE( cuLaunchGrid( s->function, s->block_count_x, s->block_count_y) ) CE( cuCtxSynchronize() ) stopwatchStop(&(s->execGpuRun)); /** copy data back **/ stopwatchStart(&(s->execMemcopyFromDevice)); CE( cuMemcpyDtoH( s->info_space, deviceGlobalFreePointer, sizeof( *(s->info_space) ) ) ) heap_end_long = s->info_space[0]; /** * An old bug was using * 16 instead of *= 16 (I think some compiler * warning might have had noticed this...) resulting in: * 1324514 inside 0 outside * => Something is wrong! Don't add up to 1684701 * 1323744 inside 0 outside * => Something is wrong! Don't add up to 1684701 * 1323263 inside 0 outside * => Something is wrong! Don't add up to 1684701 * 1322902 inside 0 outside * => Something is wrong! Don't add up to 1684701 * [...] * 0 inside 0 outside * => Something is wrong! Don't add up to 1684701 * 0 inside 0 outside * => Something is wrong! Don't add up to 1684701 * 0 inside 0 outside * => Something is wrong! Don't add up to 1684701 * 0 inside 0 outside * => Something is wrong! Don't add up to 1684701 * This means the nHitsB array and more than half of nHitsA array were * not copied back to host from gpu resulting in those values being 0. * This means that nHitsB lies after nHistA in the the rootbeer managed * heap. */ heap_end_long <<= N_ALIGNED_ZERO_BITS; CE( cuMemcpyDtoH( s->cpu_object_mem, s->gpu_object_mem, heap_end_long ) ) if ( s->using_exceptions ) CE( cuMemcpyDtoH(s->cpu_exceptions_mem, s->gpu_exceptions_mem, s->cpu_exceptions_mem_size) ) (*env)->CallVoidMethod( env, object_mem, set_heap_end_method, heap_end_long ); stopwatchStop(&(s->execMemcopyFromDevice)); /* save performance statistics to Java readable class */ (*env)->CallVoidMethod( env, stats_row, set_driver_times, stopwatchTimeMS( &(s->execMemcopyToDevice ) ), stopwatchTimeMS( &(s->execGpuRun ) ), stopwatchTimeMS( &(s->execMemcopyFromDevice ) ) ); #if ( ! defined( NDEBUG ) ) && ( DEBUG_CUDA_CONTEXT >= 10 ) { __PRINTOUT( "+-------- Handles after GPU call ('!' means they changed !):" ); int i = 0; while ( (i+1) * sizeof(jint) <= (unsigned long) s->cpu_handles_mem_size ) { if ( i % 8 == 0 ) __PRINTOUT( "\n%6i : ", i ); if ( ((jint*)s->cpu_handles_mem)[i] == ((jint*)handlesSentToGpu)[i] ) { __PRINTOUT( "%6i ", ((jint*)s->cpu_handles_mem)[i] ); } else { __PRINTOUT( "!%i(%i) ", ((jint*)s->cpu_handles_mem)[i], ((jint*)handlesSentToGpu )[i] ); } ++i; } __PRINTOUT( "\n\n" ); } for ( long i = 0; i < s->cpu_handles_mem_size; ++i ) { assert( ( (char*) s->cpu_handles_mem )[i] == ( (char*) handlesSentToGpu )[i] && "[CUDAContext.c] handles memory changed indicating a problem!" ); } free( handlesSentToGpu ); { __PRINTOUT( "+-------- Object Memory after GPU call ('!' means they changed):" ); int i = 0; while ( (i+1) * sizeof(jint) <= (unsigned long) s->cpu_object_mem_size ) { /* also print the last 1024 jints */ if ( i == 1024 && s->cpu_object_mem_size / sizeof(jint) > 2048 ) { i = s->cpu_object_mem_size / sizeof(jint) - 1024; __PRINTOUT( "\n ... \n" ); continue; } if ( i % 8 == 0 ) __PRINTOUT( "\n%5i : ", i ); if ( ((jint*)s->cpu_object_mem)[i] == ((jint*)objectsSentToGpu)[i] ) { __PRINTOUT( "%6i ", ((jint*)s->cpu_object_mem)[i] ); } else { __PRINTOUT( "!%i(%i) ", ((jint*)s->cpu_object_mem)[i], ((jint*)objectsSentToGpu )[i] ); } ++i; } __PRINTOUT( "\n\n" ); } free( objectsSentToGpu ); printf( "%s", output ); free( output ); #endif } #undef CE
42.870588
177
0.573271
[ "object" ]
7081979b2ef9061116d58bdd3ac42e6464bd1c95
1,190
h
C
src/json.h
ReanGD/rofi-proxy
f2790f3f0e386865956078ae69e15d29e271639e
[ "Apache-2.0" ]
2
2020-09-03T09:09:56.000Z
2021-02-13T21:54:04.000Z
src/json.h
ReanGD/rofi-proxy
f2790f3f0e386865956078ae69e15d29e271639e
[ "Apache-2.0" ]
null
null
null
src/json.h
ReanGD/rofi-proxy
f2790f3f0e386865956078ae69e15d29e271639e
[ "Apache-2.0" ]
null
null
null
#pragma once #include <string_view> enum class TokenType : uint8_t { Undefined = 0, Object = 1, Array = 2, String = 3, Primitive = 4 // Other primitive: number, boolean (true/false) or null }; struct Token { TokenType type; char* start; char* end; uint32_t size; std::string_view AsString(); }; class Json { public: Json(); ~Json(); void Parse(const char* text); [[maybe_unused]] Token* Next(); [[maybe_unused]] Token* Next(TokenType expectedType); [[maybe_unused]] Token* NextOrNull(TokenType expectedType, bool& isValue); void NextNull(); std::string_view NextString(); std::string_view NextStringOrNull(bool& isString); bool NextBool(); bool NextBoolOrNull(bool& isBool); std::string EscapeString(const char* str); protected: Token* NewToken(TokenType type, char* start, char* end); void ParsePrimitive(); void ParseString(); void ParseImpl(); private: char* m_text = nullptr; char* m_textIt = nullptr; Token* m_tokens = nullptr; Token* m_parent = nullptr; uint32_t m_tokensIt = 0; uint32_t m_tokensCount = 0; uint32_t m_tokensCapacity = 0; };
21.25
78
0.64958
[ "object" ]
708d3f01759ce647efae0357c619fe78e651b1fe
2,190
h
C
temperature/temperature.h
buelowp/aquarium
6d379469fbfe2a8c12631bc5571c76d3c0d9d84a
[ "MIT" ]
3
2017-05-04T08:14:46.000Z
2020-04-21T12:17:08.000Z
temperature/temperature.h
buelowp/aquarium
6d379469fbfe2a8c12631bc5571c76d3c0d9d84a
[ "MIT" ]
12
2019-08-17T20:49:35.000Z
2020-04-22T00:46:17.000Z
temperature/temperature.h
buelowp/aquarium
6d379469fbfe2a8c12631bc5571c76d3c0d9d84a
[ "MIT" ]
null
null
null
/* * Copyright (c) 2019 <copyright holder> <email> * * 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. */ #ifndef TEMPERATURE_H #define TEMPERATURE_H #include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> #include <map> #include <syslog.h> #include <sys/types.h> #include <dirent.h> class Temperature { public: Temperature(); Temperature(std::string, std::string); ~Temperature(); double convertToFarenheit(double c) { return ((c * 1.8) + 32); } double getTemperatureByDevice(std::string device); double getTemperatureByName(std::string name); void getAllTemperatures(std::map<std::string, double> &devices); bool enabled() { return m_enabled; } std::string name(std::string device) { return m_devices[device]; } std::map<std::string, std::string> devices() { return m_devices; } bool setNameForDevice(std::string name, std::string device); std::string deviceName(std::string); private: double getTemperature(std::string device); std::map<std::string, std::string> m_devices; bool m_enabled; }; #endif // TEMPERATURE_H
32.686567
70
0.717352
[ "vector" ]
7093677dad377597000f36602021e42be018d54f
6,083
h
C
src/plugins/monocle/util/monocle/textdocumentadapter.h
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
1
2017-01-12T07:05:45.000Z
2017-01-12T07:05:45.000Z
src/plugins/monocle/util/monocle/textdocumentadapter.h
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
src/plugins/monocle/util/monocle/textdocumentadapter.h
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. **********************************************************************/ #pragma once #include <memory> #include <QPainter> #include <interfaces/monocle/idocument.h> #include <interfaces/monocle/isupportpainting.h> #include <interfaces/monocle/isearchabledocument.h> class QTextDocument; namespace LeechCraft { namespace Monocle { /** @brief Provides an adapter of QTextDocument to Monocle's IDocument. * * This class provides implementations for most of the IDocument's * methods, as well as methods of ISupportPainting and * ISearchableDocument, working over a QTextDocument. * * The document for this class to work on is passed either via the * constructor or by calling the SetDocument() method. The adapter * owns the document. */ class TextDocumentAdapter : public IDocument , public ISupportPainting , public ISearchableDocument { protected: /** @brief The adapted QTextDocument. */ std::shared_ptr<QTextDocument> Doc_; /** @brief The hints used during rendering operations. * * These hints are set via SetRenderHint() calls and are used in * RenderPage() and PaintPage() implementations. */ QPainter::RenderHints Hints_; public: /** @brief Constructs the TextDocumentAdapter over the \em document. * * The ownership of the \em document is passed to the adapter. */ TextDocumentAdapter (QTextDocument *document = nullptr); /** @brief Checks if a document is set. */ bool IsValid () const; /** @brief Returns the pages count in the underlying document. * * @note If IsValid() returns false, the behavior is undefined. * * @return Pages count. */ int GetNumPages () const; /** @brief Returns the size of the \em page. * * @note If IsValid() returns false, the behavior is undefined. * * @param[in] page The index of the page to query. * @return The size of the given \em page in pixels. */ QSize GetPageSize (int page) const; /** @brief Renders the given \em page. * * The hints set via SetRenderHint() are used during rendering. * * @note If IsValid() returns false, the behavior is undefined. * * @param[in] page The index of the page to render. * @param[in] xScale The scale in the X dimension. * @param[in] yScale The scale in the Y dimension. * * @return The rendered image of the given page. * * @sa SetRenderHint() */ QImage RenderPage (int page, double xScale, double yScale); /** @brief Returns the links found on the given \em page. * * The implementation currently always returns an empty list. * * @note If IsValid() returns false, the behavior is undefined. * * @param[in] page The index of the page to query. * * @return The list of links found on the \em page. */ QList<ILink_ptr> GetPageLinks (int page); /** @brief Paints the given \em page using the \em painter. * * The hints set via SetRenderHint() are used during rendering. * * @note If IsValid() returns false, the behavior is undefined. * * @param[in] painter The painter to use. * @param[in] page The index of the page to paint. * @param[in] xScale The X-axis scale which should be used during * painting. * @param[in] yScale The Y-axis scale which should be used during * painting. * * @sa SetRenderHint() */ void PaintPage (QPainter *painter, int page, double xScale, double yScale); /** @brief Searches for the given \em text and returns its positions. * * @note If IsValid() returns false, the behavior is undefined. * * @param[in] text The text to search for. * @param[in] cs The case sensitivity of the search. * * @return The list of positions of the given \em text string for * each page. */ QMap<int, QList<QRectF>> GetTextPositions (const QString& text, Qt::CaseSensitivity cs); /** @brief Toggles the render \em hint used during painting. * * Sets the \em hint state to \em enable. * * The hints are used during RenderPage() and PaintPage() calls. * * @param[in] hint The hint to toggle. * @param[in] enable Whether the hint should be enabled. * * @sa RenderPage(), PaintPage() */ void SetRenderHint (QPainter::RenderHint hint, bool enable = true); protected: /** @brief Sets the underlying document to \em doc. * * Ownership is passed to the TextDocumentAdapter object. * * @param[in] doc The document to use. */ void SetDocument (QTextDocument *doc); }; } }
34.367232
90
0.684531
[ "render", "object" ]
7097e20d231ca1b2822c51a86a5d723165234574
2,220
h
C
src/io/server_manager.h
biswajit-mandal/contrail-controller
80c4a7e8515f7296b18ba4c21a439bd3daefcc4a
[ "Apache-2.0" ]
5
2015-01-08T17:34:41.000Z
2017-09-28T16:00:25.000Z
src/io/server_manager.h
biswajit-mandal/contrail-controller
80c4a7e8515f7296b18ba4c21a439bd3daefcc4a
[ "Apache-2.0" ]
null
null
null
src/io/server_manager.h
biswajit-mandal/contrail-controller
80c4a7e8515f7296b18ba4c21a439bd3daefcc4a
[ "Apache-2.0" ]
18
2017-01-12T09:28:44.000Z
2019-04-18T20:47:42.000Z
/* * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved. */ #ifndef IO_SERVER_MANAGER_H_ #define IO_SERVER_MANAGER_H_ #include <set> #include <tbb/mutex.h> // // ServerManager is the place holder for all the TcpServer and UdpServer // objects instantiated in the life time of a process // // TcpServer and UdpServer objects are help in ServerSet until all the cleanup // is complete and only then should they be deleted via DeleteServer() API // // Since TcpServer and UdpServer bjects are also held by boost::asio routines, // they are protected using intrusive pointers // // This is similar to how TcpSession objects are managed via TcpSessionPtr // template <typename ServerType, typename ServerPtrType> class ServerManager { public: // // Add a server object to the data base, by creating an intrusive reference // static void AddServer(ServerType *server) { tbb::mutex::scoped_lock lock(mutex_); server_ref_.insert(ServerPtrType(server)); } // // Delete a server object from the data base, by removing the intrusive // reference. If any other objects has a reference to this server such as // boost::asio, the server object deletion is automatically deferred // static void DeleteServer(ServerType *server) { tbb::mutex::scoped_lock lock(mutex_); server_ref_.erase(ServerPtrType(server)); } // // Return number of Servers. // Used in tests to ensure there are no leaks. // size_t GetServerCount() { return server_ref_.size(); } private: struct ServerPtrCmp { bool operator()(const ServerPtrType &lhs, const ServerPtrType &rhs) const { return lhs.get() < rhs.get(); } }; typedef std::set<ServerPtrType, ServerPtrCmp> ServerSet; static tbb::mutex mutex_; static ServerSet server_ref_; }; template <typename ServerType, typename ServerPtrType> typename ServerManager<ServerType, ServerPtrType>::ServerSet ServerManager<ServerType, ServerPtrType>::server_ref_; template <typename ServerType, typename ServerPtrType> tbb::mutex ServerManager<ServerType, ServerPtrType>::mutex_; #endif // IO_SERVER_MANAGER_H_
31.267606
79
0.707658
[ "object" ]
70b4a4a53885a2a6c003c4e3292e0772a58bce4a
1,097
h
C
snake.h
Literal-Eval/SFML_snake
2440a44781f3d83f05f68dfaa62c8242a420b796
[ "MIT" ]
null
null
null
snake.h
Literal-Eval/SFML_snake
2440a44781f3d83f05f68dfaa62c8242a420b796
[ "MIT" ]
null
null
null
snake.h
Literal-Eval/SFML_snake
2440a44781f3d83f05f68dfaa62c8242a420b796
[ "MIT" ]
null
null
null
#ifndef _SNAKE_H_ #define _SNAKE_H_ #include <SFML/Audio.hpp> #include <SFML/Graphics.hpp> #include <iostream> #include <vector> #include "constants.h" class Snake { private: std::vector<sf::Vector2f> bodyArray{sf::Vector2f{330, 240}, sf::Vector2f{330 - blockWidth, 240}}; std::vector<sf::Vector2f> bodyArrayTemp{sf::Vector2f{330, 240}}; sf::Vector2f movement{0, 0}; std::vector<sf::Vector2f> movements{{5, 0}, {5, 0}}; sf::Sound moveSound; sf::Sprite head; sf::Sprite tail; sf::Sprite headRight; sf::Sprite headLeft; sf::Sprite headUp; sf::Sprite headDown; sf::Sprite tailRight; sf::Sprite tailLeft; sf::Sprite tailUp; sf::Sprite tailDown; sf::Sprite bodyHorizontal; sf::Sprite bodyVertical; public: Snake(); void eat(); void move(); void setMovement(sf::Vector2f newMovement); bool checkEat(sf::Vector2f foodPos); std::vector<sf::Vector2f>& getSnakeBody(); sf::Vector2f& getHeadPos(); sf::Sprite& getHeadSprite(); sf::Sprite& getTailSprite(); sf::Sprite& getBodySprite(int index); }; #endif
21.509804
75
0.66454
[ "vector" ]
70b679bd1d4632bad0404bdc5250569182fb19eb
549
h
C
src/digg/sentry.h
erikalds/mt
802652157cf9c26970a69acbbeb48800d2983a23
[ "Unlicense" ]
null
null
null
src/digg/sentry.h
erikalds/mt
802652157cf9c26970a69acbbeb48800d2983a23
[ "Unlicense" ]
null
null
null
src/digg/sentry.h
erikalds/mt
802652157cf9c26970a69acbbeb48800d2983a23
[ "Unlicense" ]
null
null
null
#ifndef SENTRY_H #define SENTRY_H #include <functional> namespace digg { /// Simple sentry class that calls the given function object in destructor. class Sentry { public: explicit Sentry(std::function<void()> call_in_dtor) : fun(std::move(call_in_dtor)) {} Sentry(const Sentry&) = delete; Sentry& operator=(const Sentry&) = delete; Sentry(Sentry&&) = default; Sentry& operator=(Sentry&&) = default; ~Sentry() { fun(); } private: std::function<void()> fun; }; } // namespace digg #endif /* SENTRY_H */
20.333333
89
0.652095
[ "object" ]
70f2e7ab020a24b3f984e1470168c4e7cdfd45e0
14,025
c
C
sdk/mesh_inc/src/models/src/gen/gens/mm_gens.c
Yulong007/bk3435_BLEMesh_DesignKit
ee1069fba8a137ccea16c3a1c247ec8972248e24
[ "Apache-2.0" ]
4
2020-02-29T08:45:14.000Z
2021-01-13T12:31:58.000Z
sdk/mesh_inc/src/models/src/gen/gens/mm_gens.c
Yulong007/bk3435_BLEMesh_DesignKit
ee1069fba8a137ccea16c3a1c247ec8972248e24
[ "Apache-2.0" ]
null
null
null
sdk/mesh_inc/src/models/src/gen/gens/mm_gens.c
Yulong007/bk3435_BLEMesh_DesignKit
ee1069fba8a137ccea16c3a1c247ec8972248e24
[ "Apache-2.0" ]
8
2020-02-29T08:45:31.000Z
2021-06-01T06:18:45.000Z
/** **************************************************************************************** * @file mm_gens.c * * @brief Mesh Model Generic Server Module * * Copyright (C) RivieraWaves 2017-2019 * **************************************************************************************** */ /** **************************************************************************************** * @addtogroup MM_GENS * @{ **************************************************************************************** */ /* * INCLUDE FILES **************************************************************************************** */ #include "mm_gens_int.h" // Mesh Model Generic Server Module Internal Definitions #if (BLE_MESH_MDL_GENS) /* * LOCAL FUNCTIONS **************************************************************************************** */ /** **************************************************************************************** * @brief Register Generic OnOff Server model needed for management of Generic OnOff state. * * @param[in] elmt_idx Index of element on which model must be registered * @param[in] main True if model is a main model, else false * * @return An error status **************************************************************************************** */ __STATIC uint16_t mm_gens_register_oo(uint8_t elmt_idx, bool main) { // Status uint16_t status = MESH_ERR_MDL_ALREADY_REGISTERED; if (mm_tb_state_get_lid(elmt_idx, MM_ID_GENS_OO) == MESH_INVALID_LID) { // Model local index m_lid_t mdl_lid; // Register the Generic OnOff Server model status = mm_gens_oo_register(elmt_idx, &mdl_lid); if (status != MESH_ERR_NO_ERROR) { MESH_MODEL_PRINT_WARN("%s, Register the Generic OnOff Server model fail, status = 0x%x\n", __func__, status); } if (main && (status == MESH_ERR_NO_ERROR)) { // Group local index m_lid_t grp_lid; // Create group mm_tb_bind_add_group(0, elmt_idx, &grp_lid, mdl_lid, mm_gens_oo_cb_grp_event, NULL); } } return (status); } /** **************************************************************************************** * @brief Register Generic Power OnOff Server and Generic Power OnOff Setup Server models * needed for management of Generic OnPowerUp state. Also register the Generic OnOff models * which is extended by the Generic Power OnOff Server model * * @param[in] elmt_idx Index of element on which models must be registered * @param[in] main True if Generic OnOff model is a main model, else false * * @return An error status **************************************************************************************** */ #if (BLE_MESH_MDL_GENS_POO) __STATIC uint16_t mm_gens_register_poo(uint8_t elmt_idx, bool main) { // Status uint16_t status; do { // Add Generic OnOff Server model if not already present status = mm_gens_register_oo(elmt_idx, main); if (status != MESH_ERR_NO_ERROR) { MESH_MODEL_PRINT_WARN("%s, Register the Generic OnOff Server model fail, status = 0x%x\n", __func__, status); break; } // Add Generic Power OnOff Server and Generic Power OnOff Setup Server models if not // already present if ((mm_tb_state_get_lid(elmt_idx, MM_ID_GENS_POO) == MESH_INVALID_LID) && (mm_tb_state_get_lid(elmt_idx, MM_ID_GENS_POOS) == MESH_INVALID_LID)) { status = mm_gens_poo_register(elmt_idx); if (status != MESH_ERR_NO_ERROR) { MESH_MODEL_PRINT_WARN("%s, Register the Generic OnOff Server model fail, status = 0x%x\n", __func__, status); } } } while (0); return (status); } #endif /** **************************************************************************************** * @brief Register Generic Power Level Server and Generic Power Level Setup Server models * needed for management of Generic Power Level state. Also register the Generic Power * OnOff Server and the Generic Level Server models extended by the Generic Power Level * Server model, and the Generic OnOff Server model extended by the Generic Power OnOff * Server model. * * @param[in] elmt_idx Index of element on which required models must be registered * @param[in] main True if Generic Power Level model is a main model, else false * * @return An error status **************************************************************************************** */ #if (BLE_MESH_MDL_GENS_PLVL) __STATIC uint16_t mm_gens_register_plvl(uint8_t elmt_idx, bool main) { // Status uint16_t status = MESH_ERR_MDL_ALREADY_REGISTERED; if ((mm_tb_state_get_lid(elmt_idx, MM_ID_GENS_PLVL) == MESH_INVALID_LID) && (mm_tb_state_get_lid(elmt_idx, MM_ID_GENS_PLVLS) == MESH_INVALID_LID) && (mm_tb_state_get_lid(elmt_idx, MM_ID_GENS_LVL) == MESH_INVALID_LID)) { do { // Model local index Generic Level Server and Generic Power Level Server models m_lid_t lvl_mdl_lid, plvl_mdl_lid; // Register the Generic OnOff Server, the Generic Power OnOff Server and the Generic Power // OnOff Setup Server models status = mm_gens_register_poo(elmt_idx, false); if (status != MESH_ERR_NO_ERROR) { MESH_MODEL_PRINT_WARN("%s, Register the Generic OnOff Server model fail, status = 0x%x\n", __func__, status); break; } // Register the Generic Level Server model status = mm_gens_lvl_register(elmt_idx, &lvl_mdl_lid); if (status != MESH_ERR_NO_ERROR) { MESH_MODEL_PRINT_WARN("%s, Register the Generic Level Server model fail, status = 0x%x\n", __func__, status); break; } // Register the Generic Power Level Server and the Generic Power Level Setup Server // models status = mm_gens_plvl_register(elmt_idx, &plvl_mdl_lid); if (status == MESH_ERR_NO_ERROR) { if (main) { // Retrieve model local index allocated for Generic OnOff Server model m_lid_t oo_mdl_lid = mm_tb_state_get_lid(elmt_idx, MM_ID_GENS_OO); // Group local index m_lid_t grp_lid; // Create group and set Generic Power Level Server model as main model mm_tb_bind_add_group(2, elmt_idx, &grp_lid, plvl_mdl_lid, mm_gens_plvl_cb_grp_event, mm_gens_plvl_cb_trans_req); // Add Generic Level Server model to the group mm_tb_bind_group_add_mdl(grp_lid, lvl_mdl_lid, MM_ID_GENS_LVL, mm_gens_lvl_cb_grp_event, mm_gens_lvl_cb_set_state); // Add Generic OnOff Server model to the group mm_tb_bind_group_add_mdl(grp_lid, oo_mdl_lid, MM_ID_GENS_OO, mm_gens_oo_cb_grp_event, mm_gens_oo_cb_set_state); } } else { MESH_MODEL_PRINT_WARN("%s, Register the Generic Power Level Server and the Generic Power Level fail, status = 0x%x\n", __func__, status); } } while (0); } return (status); } #endif /* * GLOBAL FUNCTIONS **************************************************************************************** */ uint16_t mm_gens_init(bool reset, void *p_env, const mm_cfg_t *p_cfg) { // Return size of environment return (0); } uint16_t mm_gens_get_env_size(const mm_cfg_t *p_cfg) { // Return size of environment return (0); } uint16_t mm_gens_register(uint8_t elmt_idx, uint8_t mdl_cfg_idx, bool main) { // Status uint16_t status = MESH_ERR_NO_ERROR; switch (mdl_cfg_idx) { case (MM_CFG_IDX_GENS_ONOFF): { // Add Generic OnOff Server model if not already present status = mm_gens_register_oo(elmt_idx, main); } break; #if (BLE_MESH_MDL_GENS_LVL) case (MM_CFG_IDX_GENS_LEVEL): { // Add Generic Level Server model if not already present if (mm_tb_state_get_lid(elmt_idx, MM_ID_GENS_LVL) == MESH_INVALID_LID) { // Model local index m_lid_t mdl_lid; status = mm_gens_lvl_register(elmt_idx, &mdl_lid); if ((status == MESH_ERR_NO_ERROR) && main) { // Group local index m_lid_t grp_lid; // Create group mm_tb_bind_add_group(0, elmt_idx, &grp_lid, mdl_lid, mm_gens_lvl_cb_grp_event, NULL); } } } break; #endif #if (BLE_MESH_MDL_GENS_DTT) case (MM_CFG_IDX_GENS_DFT_TRANS_TIME): { // Add Generic Default Transition Time Server model if not already present if (mm_tb_state_get_lid(elmt_idx, MM_ID_GENS_DTT) == MESH_INVALID_LID) { status = mm_gens_dtt_register(elmt_idx); } } break; #endif #if (BLE_MESH_MDL_GENS_POO) case (MM_CFG_IDX_GENS_POWER_ONOFF): { // Add models needed for use of Generic Power OnOff Server model status = mm_gens_register_poo(elmt_idx, main); } break; #endif #if (BLE_MESH_MDL_GENS_PLVL) case (MM_CFG_IDX_GENS_POWER_LEVEL): { // Add models needed for use of Generic Power Level Server model status = mm_gens_register_plvl(elmt_idx, main); } break; #endif #if (BLE_MESH_MDL_GENS_BAT) case (MM_CFG_IDX_GENS_BATTERY): { // Add Generic Battery Server model if not already present if (mm_tb_state_get_lid(elmt_idx, MM_ID_GENS_BAT) == MESH_INVALID_LID) { status = mm_gens_bat_register(elmt_idx); } } break; #endif #if (BLE_MESH_MDL_GENS_LOC) case (MM_CFG_IDX_GENS_LOCATION): { // Add Generic Location Server and Generic Location Setup Server models // if not already present if ((mm_tb_state_get_lid(elmt_idx, MM_ID_GENS_LOC) == MESH_INVALID_LID) && (mm_tb_state_get_lid(elmt_idx, MM_ID_GENS_LOCS) == MESH_INVALID_LID)) { status = mm_gens_loc_register(elmt_idx); } } break; #endif default: { // Configuration is unknown ASSERT_INFO(0, mdl_cfg_idx, 0); status = MESH_ERR_COMMAND_DISALLOWED; } } return (status); } void mm_gens_add_to_grp(uint8_t elmt_idx, uint32_t model_id, uint8_t grp_lid) { // Retrieve model local index m_lid_t mdl_lid = mm_tb_state_get_lid(elmt_idx, model_id); if (mdl_lid != MESH_INVALID_LID) { mm_tb_bind_grp_event_cb cb_grp_event = NULL; mm_tb_bind_set_state_cb cb_set_state = NULL; switch (model_id) { case (MM_ID_GENS_OO): { cb_grp_event = mm_gens_oo_cb_grp_event; cb_set_state = mm_gens_oo_cb_set_state; } break; #if (BLE_MESH_MDL_GENS_LVL) case (MM_ID_GENS_LVL): { cb_grp_event = mm_gens_lvl_cb_grp_event; cb_set_state = mm_gens_lvl_cb_set_state; } break; #endif default: { } break; } mm_tb_bind_group_add_mdl(grp_lid, mdl_lid, model_id, cb_grp_event, cb_set_state); } } #if (BLE_MESH_MDL_GENS_BAT) void mm_gens_cfm_bat(uint16_t status, uint8_t elmt_idx, uint8_t bat_lvl, uint32_t time_charge, uint32_t time_discharge, uint8_t flags) { // Look for Generic Battery Server model in the list of models m_lid_t mdl_lid = mm_tb_state_get_lid(elmt_idx, MM_ID_GENS_BAT); if (mdl_lid != MESH_INVALID_LID) { // Get environment mm_tb_state_mdl_env_t *p_mdl_env = mm_tb_state_get_env(mdl_lid); // Inform the model about reception of the confirmation mm_gens_bat_cfm(p_mdl_env, status, bat_lvl, time_discharge, time_charge, flags); } } #endif //(BLE_MESH_MDL_GENS_POO) #if (BLE_MESH_MDL_GENS_LOC) void mm_gens_cfm_locg(uint16_t status, uint8_t elmt_idx, int32_t latitude, int32_t longitude, int16_t altitude) { // Look for Generic Location Server model in the list of models m_lid_t mdl_lid = mm_tb_state_get_lid(elmt_idx, MM_ID_GENS_LOC); if (mdl_lid != MESH_INVALID_LID) { // Get environment mm_tb_state_mdl_env_t *p_mdl_env = mm_tb_state_get_env(mdl_lid); // Inform the model about reception of the confirmation mm_gens_loc_global_cfm(p_mdl_env, status, latitude, longitude, altitude); } } void mm_gens_cfm_locl(uint16_t status, uint8_t elmt_idx, int16_t north, int16_t east, int16_t altitude, uint8_t floor, uint16_t uncertainty) { // Look for Generic Location Server model in the list of models m_lid_t mdl_lid = mm_tb_state_get_lid(elmt_idx, MM_ID_GENS_LOC); if (mdl_lid != MESH_INVALID_LID) { // Get environment mm_tb_state_mdl_env_t *p_mdl_env = mm_tb_state_get_env(mdl_lid); // Inform the model about reception of the confirmation mm_gens_loc_local_cfm(p_mdl_env, status, north, east, altitude, floor, uncertainty); } } #endif //(BLE_MESH_MDL_GENS_POO) #endif //(BLE_MESH_MDL_GENS) //(BLE_MESH_MDL_GENS) /// @} end of group
34.459459
153
0.565062
[ "mesh", "model" ]
70f857a40dc132fd3d2e70e6a4357001917e4b6c
2,190
h
C
Dev/asd_cpp/core/Graphics/3D/Object/asd.RenderedTerrainObject3D.h
GCLemon/Altseed
b525740d64001aaed673552eb4ba3e98a321fcdf
[ "FTL" ]
37
2015-07-12T14:21:03.000Z
2020-10-17T03:08:17.000Z
Dev/asd_cpp/core/Graphics/3D/Object/asd.RenderedTerrainObject3D.h
GCLemon/Altseed
b525740d64001aaed673552eb4ba3e98a321fcdf
[ "FTL" ]
91
2015-06-14T10:47:22.000Z
2020-06-29T18:05:21.000Z
Dev/asd_cpp/core/Graphics/3D/Object/asd.RenderedTerrainObject3D.h
GCLemon/Altseed
b525740d64001aaed673552eb4ba3e98a321fcdf
[ "FTL" ]
14
2015-07-13T04:15:20.000Z
2021-09-30T01:34:51.000Z
 #pragma once #include "asd.RenderedObject3D.h" namespace asd { #if !defined(_CONSOLE_GAME) class RenderedTerrainObject3DProxy : public RenderedObject3DProxy { private: std::shared_ptr<asd::NativeShader_Imp> m_shaderDF; std::shared_ptr<asd::NativeShader_Imp> m_shaderDF_ND; std::shared_ptr<asd::NativeShader_Imp> m_shaderLightweight; std::vector<ShaderConstantValue> shaderConstants; std::vector<RenderedObject3DCullingProxy> cullingProxies; std::vector<Culling3D::Object*> cullingObjects; bool isCullingRegistered = false; Renderer3DProxy* renderer = nullptr; public: RenderedTerrainObject3DProxy(Graphics* graphics); virtual ~RenderedTerrainObject3DProxy(); Terrain3D* TerrainPtr = nullptr; std::shared_ptr<MaterialPropertyBlock> materialPropertyBlock; void RegisterCulling(); void UnregisterCulling(); void UpdateCullingMatrix(const Matrix44& mat); void OnAdded(Renderer3DProxy* renderer) override; void OnRemoving(Renderer3DProxy* renderer) override; void Rendering(RenderingCommandHelper* helper, RenderingProperty& prop) override; void Rendering(int32_t index, RenderingCommandHelper* helper, RenderingProperty& prop); RenderedObject3DType GetObjectType() const override { return RenderedObject3DType::Terrain; } }; #endif /** @brief 地形のクラス */ class RenderedTerrainObject3D : public RenderedObject3D { friend class RenderedTerrainObject3DProxy; private: #if defined(_CONSOLE_GAME) #else RenderedTerrainObject3DProxy* proxy = nullptr; #endif Terrain3D* terrain = nullptr; std::shared_ptr<MaterialPropertyBlock> materialPropertyBlock; public: RenderedTerrainObject3D(Graphics* graphics); virtual ~RenderedTerrainObject3D(); void SetMaterialPropertyBlock(MaterialPropertyBlock* block); void SetTerrain(Terrain3D* terrain); void OnApplyingNextSRT() override; void Flip(float deltaTime) override; #if defined(_CONSOLE_GAME) RenderedObject3DProxy* GetProxy() const override { return nullptr; } #else RenderedObject3DProxy* GetProxy() const override { return proxy; } #endif RenderedObject3DType GetObjectType() const override { return RenderedObject3DType::Terrain; } }; }
24.333333
95
0.784475
[ "object", "vector" ]
cb23112f36c011f78c3982760174b6dfd1e99ab0
945
h
C
Neon/src/Platform/OpenGL/OpenGLShader.h
gdvaud/cpp-game-engine
90d79a5cd480de84ca65e7069d41554480f25778
[ "MIT" ]
null
null
null
Neon/src/Platform/OpenGL/OpenGLShader.h
gdvaud/cpp-game-engine
90d79a5cd480de84ca65e7069d41554480f25778
[ "MIT" ]
null
null
null
Neon/src/Platform/OpenGL/OpenGLShader.h
gdvaud/cpp-game-engine
90d79a5cd480de84ca65e7069d41554480f25778
[ "MIT" ]
null
null
null
#pragma once #include "Neon/Graphic/Shader.h" namespace Neon { class OpenGLShader : public Shader { public: OpenGLShader(const std::string& name, const std::string& filepath); OpenGLShader(const std::string& name, const std::string& vertexStr, const std::string& fragmentStr); ~OpenGLShader() override; void Bind() const override; void Unbind() const override; void SetFloat4(const std::string& name, const glm::vec4& value) override; void SetMat4(const std::string& name, const glm::mat4& matrix) override; void SetInt(const std::string& name, int value) override; const std::string& GetName() const override; private: GLuint CompileShader(GLenum type, const std::string& source); void LinkShaders(const std::vector<GLuint>& shaderIDs); private: uint32_t m_RendererId; std::string m_Name; }; } // namespace Neon
31.5
108
0.657143
[ "vector" ]
cb23d1032bdece5e1760a120220b1b5cf2b481e4
2,469
h
C
src/Cpp/Data_Structures/Vectors/Approach_II/Header/Database.h
Ahmopasa/TheCodes
560ed94190fd0da8cc12285e9b4b5e27b19010a5
[ "MIT" ]
null
null
null
src/Cpp/Data_Structures/Vectors/Approach_II/Header/Database.h
Ahmopasa/TheCodes
560ed94190fd0da8cc12285e9b4b5e27b19010a5
[ "MIT" ]
null
null
null
src/Cpp/Data_Structures/Vectors/Approach_II/Header/Database.h
Ahmopasa/TheCodes
560ed94190fd0da8cc12285e9b4b5e27b19010a5
[ "MIT" ]
null
null
null
#ifndef LEARNINGCPP_H #define LEARNINGCPP_H //#define DebugMessages // Used to activa debugging messages. ( Make it non-comment ) /******************************* A Place To Define Related Macros ******************************/ #ifdef DebugMessages #define DebugMessage_CallingConstructor std::cout << "Constructor was Called!" << std::endl #define DebugMessage_CallingDeconstructor std::cout << "Deconstructor was Called!" << std::endl #else #define DebugMessage_CallingConstructor #define DebugMessage_CallingDeconstructor #endif /******************************* A Place To Define Related Libraries ***************************/ #include <iostream> #include <time.h> #include <string> #include <vector> #include <algorithm> /******************************* A Place To Define Global Variables *****************************/ class NotLearning { public: NotLearning(); // Constructor int getID()const; // Function to get the private variable "ID" of the class. int getDay()const; // Function to get the private variable "day" of the class. int getYear()const; // Function to get the private variable "year" of the class. double getAverage()const; // Function to get the private variable "average" of the class. std::string getName()const; // Function to get the private variable "name" of the class. std::string getSurname()const; // Function to get the private variable "surname" of the class. std::string getCity()const; // Function to get the private variable "city" of the class. std::string getMonth()const; // Function to get the private variable "month" of the class. private: int ID; int day; int year; double average; std::string name; std::string surname; std::string city; std::string month; }; /******************************* A Place To Define Global Functions *******************************/ void fillVector(std::vector<NotLearning>&); void showVector(const std::vector<NotLearning>&); void sortVectorByID(std::vector<NotLearning>&); void sortVectorByAverage(std::vector<NotLearning>&); void sortVectorByName(std::vector<NotLearning>&); void sortVectorBySurname(std::vector<NotLearning>&); void sortVectorByCity(std::vector<NotLearning>&); void sortVectorByDay(std::vector<NotLearning>&); void sortVectorByMonth(std::vector<NotLearning>&); void sortVectorByYear(std::vector<NotLearning>&); void sortVectorByDetail(std::vector<NotLearning>&); #endif // !LEARNINGCPP_H
39.190476
100
0.666262
[ "vector" ]
cb25af700d4a305fa1250f21295680c8eaccd6ec
1,012
h
C
common/inc/Config.h
liyandong1/WebServer
65ce01b36edf4c307b19dec6572955f06871687c
[ "MIT" ]
null
null
null
common/inc/Config.h
liyandong1/WebServer
65ce01b36edf4c307b19dec6572955f06871687c
[ "MIT" ]
null
null
null
common/inc/Config.h
liyandong1/WebServer
65ce01b36edf4c307b19dec6572955f06871687c
[ "MIT" ]
null
null
null
//@Athor LiYanDong //@Email 416620418@qq.com #ifndef _CONFIG_H_ #define _CONFIG_H_ #include <mutex> #include <vector> #include <string> //配置文件条目 struct ConfigItem { std::string ItemName; std::string ItemContent; ConfigItem(const std::string& str1, const std::string& str2) { this->ItemName = str1; this->ItemContent = str2; } }; //以单例类读取配置文件 class Config { private: static std::mutex m_mutex; static Config* m_instance; Config(); //用于单例类资源回收 class Recovery { public: ~Recovery() { if(m_instance != nullptr) { delete m_instance; } } }; public: //配置文件 std::vector<ConfigItem*> configs; static Config* getInstance(); //装载配置文件 bool load(const std::string& file_path); //获取数字类型的配置信息 int getNum(const std::string& item_name); //获取字符串类型配置信息 const std::string getStr(const std::string& item_name); ~Config(); }; #endif
15.8125
64
0.587945
[ "vector" ]
cb37e1863a3c0c57eddc24f77f27f637ea3153b3
15,708
h
C
_cffi_build/secp256k1_rangeproof.h
SlurmDiver/secp256k1-zkp-py
f922d14b9604349c5b2edfc4b0792bde2367688b
[ "MIT" ]
1
2021-11-20T21:10:52.000Z
2021-11-20T21:10:52.000Z
_cffi_build/secp256k1_rangeproof.h
SlurmDiver/secp256k1-zkp-py
f922d14b9604349c5b2edfc4b0792bde2367688b
[ "MIT" ]
4
2018-11-27T17:49:48.000Z
2018-12-15T14:47:39.000Z
_cffi_build/secp256k1_rangeproof.h
WTRMQDev/secp256k1-zkp-py
10e398e88cfca4c1606e60a6d758dd4ad5584008
[ "MIT" ]
null
null
null
/** Opaque data structure that stores a base point * * The exact representation of data inside is implementation defined and not * guaranteed to be portable between different platforms or versions. It is * however guaranteed to be 33 bytes in size, and can be safely copied/moved. * If you need to convert to a format suitable for storage or transmission, use * the secp256k1_generator_serialize_*. * * Furthermore, it is guaranteed to identical points will have identical * representation, so they can be memcmp'ed. */ typedef struct { unsigned char data[64]; } secp256k1_generator; extern const secp256k1_generator secp256k1_generator_const_g; extern const secp256k1_generator secp256k1_generator_const_h; /** Parse a 33-byte generator byte sequence into a generator object. * * Returns: 1 if input contains a valid generator. * Args: ctx: a secp256k1 context object. * Out: commit: pointer to the output generator object * In: input: pointer to a 33-byte serialized generator */ int secp256k1_generator_parse( const secp256k1_context* ctx, secp256k1_generator* commit, const unsigned char *input ); /** Serialize a 33-byte generator into a serialized byte sequence. * * Returns: 1 always. * Args: ctx: a secp256k1 context object. * Out: output: a pointer to a 33-byte byte array * In: commit: a pointer to a generator */ int secp256k1_generator_serialize( const secp256k1_context* ctx, unsigned char *output, const secp256k1_generator* commit ); /** Generate a generator for the curve. * * Returns: 0 in the highly unlikely case the seed is not acceptable, * 1 otherwise. * Args: ctx: a secp256k1 context object * Out: gen: a generator object * In: seed32: a 32-byte seed * * If succesful, a valid generator will be placed in gen. The produced * generators are distributed uniformly over the curve, and will not have a * known dicrete logarithm with respect to any other generator produced, * or to the base generator G. */ int secp256k1_generator_generate( const secp256k1_context* ctx, secp256k1_generator* gen, const unsigned char *seed32 ); /** Generate a blinded generator for the curve. * * Returns: 0 in the highly unlikely case the seed is not acceptable or when * blind is out of range. 1 otherwise. * Args: ctx: a secp256k1 context object, initialized for signing * Out: gen: a generator object * In: seed32: a 32-byte seed * blind32: a 32-byte secret value to blind the generator with. * * The result is equivalent to first calling secp256k1_generator_generate, * converting the result to a public key, calling secp256k1_ec_pubkey_tweak_add, * and then converting back to generator form. */ int secp256k1_generator_generate_blinded( const secp256k1_context* ctx, secp256k1_generator* gen, const unsigned char *key32, const unsigned char *blind32 ); typedef struct { unsigned char data[64]; } secp256k1_pedersen_commitment; /** Parse a 33-byte commitment into a commitment object. * * Returns: 1 if input contains a valid commitment. * Args: ctx: a secp256k1 context object. * Out: commit: pointer to the output commitment object * In: input: pointer to a 33-byte serialized commitment key */ int secp256k1_pedersen_commitment_parse( const secp256k1_context* ctx, secp256k1_pedersen_commitment* commit, const unsigned char *input ); /** Serialize a commitment object into a serialized byte sequence. * * Returns: 1 always. * Args: ctx: a secp256k1 context object. * Out: output: a pointer to a 33-byte byte array * In: commit: a pointer to a secp256k1_pedersen_commitment containing an * initialized commitment */ int secp256k1_pedersen_commitment_serialize( const secp256k1_context* ctx, unsigned char *output, const secp256k1_pedersen_commitment* commit ); /** Generate a pedersen commitment. * Returns 1: Commitment successfully created. * 0: Error. The blinding factor is larger than the group order * (probability for random 32 byte number < 2^-127) or results in the * point at infinity. Retry with a different factor. * In: ctx: pointer to a context object, initialized for signing and Pedersen commitment (cannot be NULL) * blind: pointer to a 32-byte blinding factor (cannot be NULL) * value: unsigned 64-bit integer value to commit to. * gen: additional generator 'h' * Out: commit: pointer to the commitment (cannot be NULL) * * Blinding factors can be generated and verified in the same way as secp256k1 private keys for ECDSA. */ int secp256k1_pedersen_commit( const secp256k1_context* ctx, secp256k1_pedersen_commitment *commit, const unsigned char *blind, uint64_t value, const secp256k1_generator *value_gen, const secp256k1_generator *blind_gen ); /** Computes the sum of multiple positive and negative blinding factors. * Returns 1: Sum successfully computed. * 0: Error. A blinding factor is larger than the group order * (probability for random 32 byte number < 2^-127). Retry with * different factors. * In: ctx: pointer to a context object (cannot be NULL) * blinds: pointer to pointers to 32-byte character arrays for blinding factors. (cannot be NULL) * n: number of factors pointed to by blinds. * npositive: how many of the initial factors should be treated with a positive sign. * Out: blind_out: pointer to a 32-byte array for the sum (cannot be NULL) */ int secp256k1_pedersen_blind_sum( const secp256k1_context* ctx, unsigned char *blind_out, const unsigned char * const *blinds, size_t n, size_t npositive ); /** Verify a tally of pedersen commitments * Returns 1: commitments successfully sum to zero. * 0: Commitments do not sum to zero or other error. * In: ctx: pointer to a context object (cannot be NULL) * commits: pointer to array of pointers to the commitments. (cannot be NULL if pcnt is non-zero) * pcnt: number of commitments pointed to by commits. * ncommits: pointer to array of pointers to the negative commitments. (cannot be NULL if ncnt is non-zero) * ncnt: number of commitments pointed to by ncommits. * * This computes sum(commit[0..pcnt)) - sum(ncommit[0..ncnt)) == 0. * * A pedersen commitment is xG + vA where G and A are generators for the secp256k1 group and x is a blinding factor, * while v is the committed value. For a collection of commitments to sum to zero, for each distinct generator * A all blinding factors and all values must sum to zero. * */ int secp256k1_pedersen_verify_tally( const secp256k1_context* ctx, const secp256k1_pedersen_commitment * const* commits, size_t pcnt, const secp256k1_pedersen_commitment * const* ncommits, size_t ncnt ); /** Sets the final Pedersen blinding factor correctly when the generators themselves * have blinding factors. * * Consider a generator of the form A' = A + rG, where A is the "real" generator * but A' is the generator provided to verifiers. Then a Pedersen commitment * P = vA' + r'G really has the form vA + (vr + r')G. To get all these (vr + r') * to sum to zero for multiple commitments, we take three arrays consisting of * the `v`s, `r`s, and `r'`s, respectively called `value`s, `generator_blind`s * and `blinding_factor`s, and sum them. * * The function then subtracts the sum of all (vr + r') from the last element * of the `blinding_factor` array, setting the total sum to zero. * * Returns 1: Blinding factor successfully computed. * 0: Error. A blinding_factor or generator_blind are larger than the group * order (probability for random 32 byte number < 2^-127). Retry with * different values. * * In: ctx: pointer to a context object * value: array of asset values, `v` in the above paragraph. * May not be NULL unless `n_total` is 0. * generator_blind: array of asset blinding factors, `r` in the above paragraph * May not be NULL unless `n_total` is 0. * n_total: Total size of the above arrays * n_inputs: How many of the initial array elements represent commitments that * will be negated in the final sum * In/Out: blinding_factor: array of commitment blinding factors, `r'` in the above paragraph * May not be NULL unless `n_total` is 0. * the last value will be modified to get the total sum to zero. */ int secp256k1_pedersen_blind_generator_blind_sum( const secp256k1_context* ctx, const uint64_t *value, const unsigned char* const* generator_blind, unsigned char* const* blinding_factor, size_t n_total, size_t n_inputs ); /** Verify a proof that a committed value is within a range. * Returns 1: Value is within the range [0..2^64), the specifically proven range is in the min/max value outputs. * 0: Proof failed or other error. * In: ctx: pointer to a context object, initialized for range-proof and commitment (cannot be NULL) * commit: the commitment being proved. (cannot be NULL) * proof: pointer to character array with the proof. (cannot be NULL) * plen: length of proof in bytes. * extra_commit: additional data covered in rangeproof signature * extra_commit_len: length of extra_commit byte array (0 if NULL) * gen: additional generator 'h' * Out: min_value: pointer to a unsigned int64 which will be updated with the minimum value that commit could have. (cannot be NULL) * max_value: pointer to a unsigned int64 which will be updated with the maximum value that commit could have. (cannot be NULL) */ int secp256k1_rangeproof_verify( const secp256k1_context* ctx, uint64_t *min_value, uint64_t *max_value, const secp256k1_pedersen_commitment *commit, const unsigned char *proof, size_t plen, const unsigned char *extra_commit, size_t extra_commit_len, const secp256k1_generator* gen ); /** Verify a range proof proof and rewind the proof to recover information sent by its author. * Returns 1: Value is within the range [0..2^64), the specifically proven range is in the min/max value outputs, and the value and blinding were recovered. * 0: Proof failed, rewind failed, or other error. * In: ctx: pointer to a context object, initialized for range-proof and Pedersen commitment (cannot be NULL) * commit: the commitment being proved. (cannot be NULL) * proof: pointer to character array with the proof. (cannot be NULL) * plen: length of proof in bytes. * nonce: 32-byte secret nonce used by the prover (cannot be NULL) * extra_commit: additional data covered in rangeproof signature * extra_commit_len: length of extra_commit byte array (0 if NULL) * gen: additional generator 'h' * In/Out: blind_out: storage for the 32-byte blinding factor used for the commitment * value_out: pointer to an unsigned int64 which has the exact value of the commitment. * message_out: pointer to a 4096 byte character array to receive message data from the proof author. * outlen: length of message data written to message_out. * min_value: pointer to an unsigned int64 which will be updated with the minimum value that commit could have. (cannot be NULL) * max_value: pointer to an unsigned int64 which will be updated with the maximum value that commit could have. (cannot be NULL) */ int secp256k1_rangeproof_rewind( const secp256k1_context* ctx, unsigned char *blind_out, uint64_t *value_out, unsigned char *message_out, size_t *outlen, const unsigned char *nonce, uint64_t *min_value, uint64_t *max_value, const secp256k1_pedersen_commitment *commit, const unsigned char *proof, size_t plen, const unsigned char *extra_commit, size_t extra_commit_len, const secp256k1_generator *gen ); /** Author a proof that a committed value is within a range. * Returns 1: Proof successfully created. * 0: Error * In: ctx: pointer to a context object, initialized for range-proof, signing, and Pedersen commitment (cannot be NULL) * proof: pointer to array to receive the proof, can be up to 5134 bytes. (cannot be NULL) * min_value: constructs a proof where the verifer can tell the minimum value is at least the specified amount. * commit: the commitment being proved. * blind: 32-byte blinding factor used by commit. * nonce: 32-byte secret nonce used to initialize the proof (value can be reverse-engineered out of the proof if this secret is known.) * exp: Base-10 exponent. Digits below above will be made public, but the proof will be made smaller. Allowed range is -1 to 18. * (-1 is a special case that makes the value public. 0 is the most private.) * min_bits: Number of bits of the value to keep private. (0 = auto/minimal, - 64). * value: Actual value of the commitment. * message: pointer to a byte array of data to be embedded in the rangeproof that can be recovered by rewinding the proof * msg_len: size of the message to be embedded in the rangeproof * extra_commit: additional data to be covered in rangeproof signature * extra_commit_len: length of extra_commit byte array (0 if NULL) * gen: additional generator 'h' * In/out: plen: point to an integer with the size of the proof buffer and the size of the constructed proof. * * If min_value or exp is non-zero then the value must be on the range [0, 2^63) to prevent the proof range from spanning past 2^64. * * If exp is -1 the value is revealed by the proof (e.g. it proves that the proof is a blinding of a specific value, without revealing the blinding key.) * * This can randomly fail with probability around one in 2^100. If this happens, buy a lottery ticket and retry with a different nonce or blinding. * */ int secp256k1_rangeproof_sign( const secp256k1_context* ctx, unsigned char *proof, size_t *plen, uint64_t min_value, const secp256k1_pedersen_commitment *commit, const unsigned char *blind, const unsigned char *nonce, int exp, int min_bits, uint64_t value, const unsigned char *message, size_t msg_len, const unsigned char *extra_commit, size_t extra_commit_len, const secp256k1_generator *gen ); /** Extract some basic information from a range-proof. * Returns 1: Information successfully extracted. * 0: Decode failed. * In: ctx: pointer to a context object * proof: pointer to character array with the proof. * plen: length of proof in bytes. * Out: exp: Exponent used in the proof (-1 means the value isn't private). * mantissa: Number of bits covered by the proof. * min_value: pointer to an unsigned int64 which will be updated with the minimum value that commit could have. (cannot be NULL) * max_value: pointer to an unsigned int64 which will be updated with the maximum value that commit could have. (cannot be NULL) */ int secp256k1_rangeproof_info( const secp256k1_context* ctx, int *exp, int *mantissa, uint64_t *min_value, uint64_t *max_value, const unsigned char *proof, size_t plen );
44.625
157
0.701044
[ "object" ]
cb3934de73386997fedf63dca65d257d678b863a
2,217
h
C
OVP/D3D9Client/MaterialMgr.h
Ybalrid/orbiter
7bed82f845ea8347f238011367e07007b0a24099
[ "MIT" ]
null
null
null
OVP/D3D9Client/MaterialMgr.h
Ybalrid/orbiter
7bed82f845ea8347f238011367e07007b0a24099
[ "MIT" ]
null
null
null
OVP/D3D9Client/MaterialMgr.h
Ybalrid/orbiter
7bed82f845ea8347f238011367e07007b0a24099
[ "MIT" ]
null
null
null
// ============================================================== // MaterialMgr.h // Part of the ORBITER VISUALISATION PROJECT (OVP) // Dual licensed under GPL v3 and LGPL v3 // Copyright (C) 2012 - 2016 Jarmo Nikkanen // ============================================================== #ifndef __MATERIALMGR_H #define __MATERIALMGR_H #include <d3d9.h> #include <d3dx9.h> #include "Mesh.h" #include "D3D9Client.h" #include "D3D9Util.h" #include "vObject.h" #define ENVCAM_OMIT_ATTC 0x0001 #define ENVCAM_OMIT_DOCKS 0x0002 #define ENVCAM_FOCUS 0x0004 /** * \brief Storage structure to keep environmental camera information. */ struct ENVCAMREC { D3DXVECTOR3 lPos; ///< Camera local position float near_clip; ///< Near clip-plane distance DWORD flags; ///< Camera flags WORD nAttc; ///< Number of attachments points in a list WORD nDock; ///< Number of docking ports in a list BYTE * pOmitAttc; ///< Omit attachments BYTE * pOmitDock; ///< Omit cessels in docking ports }; /** * \brief Management of custom configurations for vessel materials */ class MatMgr { public: // Disable copy construct & copy assign MatMgr (MatMgr const&) = delete; MatMgr & operator= (MatMgr const&) = delete; MatMgr(class vObject *vObj, class D3D9Client *_gc); ~MatMgr(); //DWORD NewRecord(const char *name, DWORD midx); //void ClearRecord(DWORD iRec); void RegisterMaterialChange(D3D9Mesh *pMesh, DWORD midx, const D3D9MatExt *pM); void RegisterShaderChange(D3D9Mesh *pMesh, WORD id); void ApplyConfiguration(D3D9Mesh *pMesh); bool SaveConfiguration(); bool LoadConfiguration(bool bAppend=false); bool LoadCameraConfig(); bool HasMesh(const char *name); void ResetCamera(DWORD idx); ENVCAMREC * GetCamera(DWORD idx); DWORD CameraCount(); private: vObject *vObj; D3D9Client *gc; //DWORD nRec; ///< Number of records //DWORD mRec; ///< Allocated records struct SHADER { SHADER(string x, WORD i) { name = x; id = i; } string name; WORD id; }; struct MESHREC { WORD shader; map<int, D3D9MatExt> material; }; std::map<string, MESHREC> MeshConfig; std::list<SHADER> Shaders; ENVCAMREC *pCamera; }; #endif
24.633333
82
0.653586
[ "mesh" ]
cb62fc1c85c4b1efd5f59ffebae158614bdbd762
7,379
h
C
dali/devel-api/adaptor-framework/native-image-source-queue.h
dalihub/dali-adaptor
b7943ae5aeb7ddd069be7496a1c1cee186b740c5
[ "Apache-2.0", "BSD-3-Clause" ]
6
2016-11-18T10:26:46.000Z
2021-11-01T12:29:05.000Z
dali/devel-api/adaptor-framework/native-image-source-queue.h
dalihub/dali-adaptor
b7943ae5aeb7ddd069be7496a1c1cee186b740c5
[ "Apache-2.0", "BSD-3-Clause" ]
5
2020-07-15T11:30:49.000Z
2020-12-11T19:13:46.000Z
dali/devel-api/adaptor-framework/native-image-source-queue.h
dalihub/dali-adaptor
b7943ae5aeb7ddd069be7496a1c1cee186b740c5
[ "Apache-2.0", "BSD-3-Clause" ]
7
2019-05-17T07:14:40.000Z
2021-05-24T07:25:26.000Z
#ifndef DALI_NATIVE_IMAGE_SOURCE_QUEUE_H #define DALI_NATIVE_IMAGE_SOURCE_QUEUE_H /* * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // EXTERNAL INCLUDES #include <dali/public-api/images/native-image-interface.h> #include <dali/public-api/object/any.h> #include <memory> // INTERNAL INCLUDES #include <dali/public-api/dali-adaptor-common.h> namespace Dali { /** * @addtogroup dali_adaptor_framework * @{ */ namespace Internal DALI_INTERNAL { namespace Adaptor { class NativeImageSourceQueue; } } // namespace DALI_INTERNAL class NativeImageSourceQueue; /** * @brief Pointer to Dali::NativeImageSourceQueue. */ typedef Dali::IntrusivePtr<Dali::NativeImageSourceQueue> NativeImageSourceQueuePtr; /** * @brief Used for displaying native images. * * NativeImage is a platform specific way of providing pixel data to the GPU for rendering,for example via an EGL image. * NativeImageSourceQueue can be created internally or externally by native image source. * It has a queue which handles some image buffers. * Someone should fill the buffers and enqueue them, then DALi will show them. */ class DALI_ADAPTOR_API NativeImageSourceQueue : public NativeImageInterface { public: /** * @brief Enumeration for the instance when creating a native image, the color depth has to be specified. */ enum class ColorFormat { RGB888, /// 8 red bits, 8 green bits, 8 blue bits RGBA8888, /// 8 red bits, 8 green bits, 8 blue bits, alpha 8 bits RGBX8888 /// 8 red bits, 8 green bits, 8 blue bits, and 8 ignored bits }; /** * @brief Creates a new NativeImageSourceQueue. * Depending on hardware, the width and height may have to be a power of two. * @param[in] width The width of the image * @param[in] height The height of the image * @param[in] colorFormat The color format of the image * @return A smart-pointer to a newly allocated image */ static NativeImageSourceQueuePtr New(uint32_t width, uint32_t height, ColorFormat colorFormat); /** * @brief Creates a new NativeImageSourceQueue from an existing native image source. * * @param[in] nativeImageSourceQueue NativeImageSourceQueue must be a any handle with native image source * @return A smart-pointer to a newly allocated image * @see NativeImageInterface */ static NativeImageSourceQueuePtr New(Any nativeImageSourceQueue); /** * @brief Retrieves the internal native image. * * @return Any object containing the internal native image source queue */ Any GetNativeImageSourceQueue(); /** * @brief Sets the size of the image. * * @param[in] width The width of the image * @param[in] height The height of the image */ void SetSize(uint32_t width, uint32_t height); /** * @brief Ignores a source image which is inserted to the queue. * * @note This can be called from worker threads. */ void IgnoreSourceImage(); /** * @brief Checks if the buffer can be got from the queue. * * Check the available buffer using this API before call DequeueBuffer() * @return True if the buffer can be got from the queue. */ bool CanDequeueBuffer(); /** * @brief Dequeue buffer from the queue. * * Acquire buffer and information of the queue. * it returns the information of the buffer. * @param[out] width The width of buffer * @param[out] height The height of buffer * @param[out] stride The stride of buffer * @return A pointer of buffer */ uint8_t* DequeueBuffer(uint32_t& width, uint32_t& height, uint32_t& stride); /** * @brief Enqueue buffer to the queue. * * Enqueue buffer to the queue * this requests the release of the buffer internally. * @param[in] buffer A pointer of buffer * @return True if success */ bool EnqueueBuffer(uint8_t* buffer); /** * @copydoc Dali::NativeImageInterface::GetTextureTarget() */ int GetTextureTarget() const override; /** * @copydoc Dali::NativeImageInterface::ApplyNativeFragmentShader() */ bool ApplyNativeFragmentShader(std::string& shader) override; /** * @copydoc Dali::NativeImageInterface::GetCustomSamplerTypename() */ const char* GetCustomSamplerTypename() const override; private: // native image /** * @copydoc Dali::NativeImageInterface::CreateResource() */ bool CreateResource() override; /** * @copydoc Dali::NativeImageInterface::DestroyResource() */ void DestroyResource() override; /** * @copydoc Dali::NativeImageInterface::TargetTexture() */ uint32_t TargetTexture() override; /** * @copydoc Dali::NativeImageInterface::PrepareTexture() */ void PrepareTexture() override; /** * @copydoc Dali::NativeImageInterface::GetWidth() */ uint32_t GetWidth() const override; /** * @copydoc Dali::NativeImageInterface::GetHeight() */ uint32_t GetHeight() const override; /** * @copydoc Dali::NativeImageInterface::RequiresBlending() */ bool RequiresBlending() const override; /** * @copydoc Dali::NativeImageInterface::GetNativeImageHandle() */ Any GetNativeImageHandle() const override; /** * @copydoc Dali::NativeImageInterface::SourceChanged() */ bool SourceChanged() const override; /** * @copydoc Dali::NativeImageInterface::GetExtension() */ NativeImageInterface::Extension* GetExtension() override; private: /// @cond internal /** * @brief Private constructor. * @param[in] width The width of the image * @param[in] height The height of the image * @param[in] colorFormat The color format of the image * @param[in] nativeImageSourceQueue contains either: native image source or is empty */ DALI_INTERNAL NativeImageSourceQueue(uint32_t width, uint32_t height, ColorFormat colorFormat, Any nativeImageSourceQueue); /** * @brief A reference counted object may only be deleted by calling Unreference(). * * The implementation should destroy the NativeImage resources. */ DALI_INTERNAL ~NativeImageSourceQueue() override; /** * @brief Undefined copy constructor. * * This avoids accidental calls to a default copy constructor. * @param[in] nativeImageSourceQueue A reference to the object to copy */ DALI_INTERNAL NativeImageSourceQueue(const NativeImageSourceQueue& nativeImageSourceQueue); /** * @brief Undefined assignment operator. * * This avoids accidental calls to a default assignment operator. * @param[in] rhs A reference to the object to copy */ DALI_INTERNAL NativeImageSourceQueue& operator=(const NativeImageSourceQueue& rhs); /// @endcond private: /// @cond internal std::unique_ptr<Internal::Adaptor::NativeImageSourceQueue> mImpl; ///< Implementation pointer /// @endcond }; /** * @} */ } // namespace Dali #endif // DALI_NATIVE_IMAGE_SOURCE_QUEUE_H
28.824219
125
0.714053
[ "object" ]
3b105f07e44a09e30311bd6f3fe50bb143fe514d
11,246
h
C
sacapidll.h
jaschweder/sqlanywhere-php-extension
42aa6f38cc209ff610bdec43eeeb57b823f4f780
[ "Apache-2.0" ]
null
null
null
sacapidll.h
jaschweder/sqlanywhere-php-extension
42aa6f38cc209ff610bdec43eeeb57b823f4f780
[ "Apache-2.0" ]
null
null
null
sacapidll.h
jaschweder/sqlanywhere-php-extension
42aa6f38cc209ff610bdec43eeeb57b823f4f780
[ "Apache-2.0" ]
null
null
null
/* ==================================================== * * Copyright 2013 SAP AG or an SAP affiliate company. * * 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. * * While not a requirement of the license, if you do modify this file, we * would appreciate hearing about it. Please email * sqlany_interfaces@sybase.com * * ==================================================== */ #ifndef SACAPIDLL_H #define SACAPIDLL_H #include "sacapi.h" /** \file sacapidll.h * \brief Header file for stub that can dynamically load the main API DLL. * The user will need to include sacapidll.h in their source files and compile in sacapidll.c */ #if defined( __cplusplus ) extern "C" { #endif typedef sacapi_bool (*sqlany_init_func)( const char * app_name, sacapi_u32 api_version, sacapi_u32 * max_version ); typedef void (*sqlany_fini_func)(); typedef a_sqlany_connection * (*sqlany_new_connection_func)( ); typedef void (*sqlany_free_connection_func)( a_sqlany_connection *sqlany_conn ); typedef a_sqlany_connection * (*sqlany_make_connection_func)( void * arg ); typedef sacapi_bool (*sqlany_connect_func)( a_sqlany_connection * sqlany_conn, const char * str ); typedef sacapi_bool (*sqlany_disconnect_func)( a_sqlany_connection * sqlany_conn ); typedef sacapi_bool (*sqlany_execute_immediate_func)( a_sqlany_connection * sqlany_conn, const char * sql ); typedef a_sqlany_stmt * (*sqlany_prepare_func)( a_sqlany_connection * sqlany_conn, const char * sql_str ); typedef void (*sqlany_free_stmt_func)( a_sqlany_stmt * sqlany_stmt ); typedef sacapi_i32 (*sqlany_num_params_func)( a_sqlany_stmt * sqlany_stmt ); typedef sacapi_bool (*sqlany_describe_bind_param_func)( a_sqlany_stmt * sqlany_stmt, sacapi_u32 index, a_sqlany_bind_param * params ); typedef sacapi_bool (*sqlany_bind_param_func)( a_sqlany_stmt * sqlany_stmt, sacapi_u32 index, a_sqlany_bind_param * params ); typedef sacapi_bool (*sqlany_send_param_data_func)( a_sqlany_stmt * sqlany_stmt, sacapi_u32 index, char * buffer, size_t size ); typedef sacapi_bool (*sqlany_reset_func)( a_sqlany_stmt * sqlany_stmt ); typedef sacapi_bool (*sqlany_get_bind_param_info_func)( a_sqlany_stmt * sqlany_stmt, sacapi_u32 index, a_sqlany_bind_param_info * info ); typedef sacapi_bool (*sqlany_execute_func)( a_sqlany_stmt * sqlany_stmt ); typedef a_sqlany_stmt * (*sqlany_execute_direct_func)( a_sqlany_connection * sqlany_conn, const char * sql_str ); typedef sacapi_bool (*sqlany_fetch_absolute_func)( a_sqlany_stmt * sqlany_result, sacapi_i32 row_num ); typedef sacapi_bool (*sqlany_fetch_next_func)( a_sqlany_stmt * sqlany_stmt ); typedef sacapi_bool (*sqlany_get_next_result_func)( a_sqlany_stmt * sqlany_stmt ); typedef sacapi_i32 (*sqlany_affected_rows_func)( a_sqlany_stmt * sqlany_stmt ); typedef sacapi_i32 (*sqlany_num_cols_func)( a_sqlany_stmt * sqlany_stmt ); typedef sacapi_i32 (*sqlany_num_rows_func)( a_sqlany_stmt * sqlany_stmt ); typedef sacapi_bool (*sqlany_get_column_func)( a_sqlany_stmt * sqlany_stmt, sacapi_u32 col_index, a_sqlany_data_value * buffer ); typedef sacapi_i32 (*sqlany_get_data_func)( a_sqlany_stmt * sqlany_stmt, sacapi_u32 col_index, size_t offset, void * buffer, size_t size ); typedef sacapi_bool (*sqlany_get_data_info_func)( a_sqlany_stmt * sqlany_stmt, sacapi_u32 col_index, a_sqlany_data_info * buffer ); typedef sacapi_bool (*sqlany_get_column_info_func)( a_sqlany_stmt * sqlany_stmt, sacapi_u32 col_index, a_sqlany_column_info * buffer ); typedef sacapi_bool (*sqlany_commit_func)( a_sqlany_connection * sqlany_conn ); typedef sacapi_bool (*sqlany_rollback_func)( a_sqlany_connection * sqlany_conn ); typedef sacapi_bool (*sqlany_client_version_func)( char * buffer, size_t len ); typedef sacapi_i32 (*sqlany_error_func)( a_sqlany_connection * sqlany_conn, char * buffer, size_t size ); typedef size_t (*sqlany_sqlstate_func)( a_sqlany_connection * sqlany_conn, char * buffer, size_t size ); typedef void (*sqlany_clear_error_func)( a_sqlany_connection * sqlany_conn ); #if _SACAPI_VERSION+0 >= 2 typedef a_sqlany_interface_context *(*sqlany_init_ex_func)( const char *app_name, sacapi_u32 api_version, sacapi_u32 *max_version ); typedef void (*sqlany_fini_ex_func)( a_sqlany_interface_context *context ); typedef a_sqlany_connection *(*sqlany_new_connection_ex_func)( a_sqlany_interface_context *context ); typedef a_sqlany_connection *(*sqlany_make_connection_ex_func)( a_sqlany_interface_context *context, void *arg ); typedef sacapi_bool (*sqlany_client_version_ex_func)( a_sqlany_interface_context *context, char *buffer, size_t len ); typedef void (*sqlany_cancel_func)( a_sqlany_connection * sqlany_conn ); #endif #if defined( __cplusplus ) } #endif #define function( x ) x ## _func x /** An API interface structure. * The user would need only one instance of this in their environment. When the * instance is initialized, the DLL will be loaded and all the entry points will be looked up. */ typedef struct SQLAnywhereInterface { /** DLL handle. */ void * dll_handle; /** Flag to know if initialized or not. */ int initialized; /** Pointer to ::sqlany_init() function. */ function( sqlany_init ); /** Pointer to ::sqlany_fini() function. */ function( sqlany_fini ); /** Pointer to ::sqlany_new_connection() function. */ function( sqlany_new_connection ); /** Pointer to ::sqlany_free_connection() function. */ function( sqlany_free_connection ); /** Pointer to ::sqlany_make_connection() function. */ function( sqlany_make_connection ); /** Pointer to ::sqlany_connect() function. */ function( sqlany_connect ); /** Pointer to ::sqlany_disconnect() function. */ function( sqlany_disconnect ); /** Pointer to ::sqlany_execute_immediate() function. */ function( sqlany_execute_immediate ); /** Pointer to ::sqlany_prepare() function. */ function( sqlany_prepare ); /** Pointer to ::sqlany_free_stmt() function. */ function( sqlany_free_stmt ); /** Pointer to ::sqlany_num_params() function. */ function( sqlany_num_params ); /** Pointer to ::sqlany_describe_bind_param() function. */ function( sqlany_describe_bind_param ); /** Pointer to ::sqlany_bind_param() function. */ function( sqlany_bind_param ); /** Pointer to ::sqlany_send_param_data() function. */ function( sqlany_send_param_data ); /** Pointer to ::sqlany_reset() function. */ function( sqlany_reset ); /** Pointer to ::sqlany_get_bind_param_info() function. */ function( sqlany_get_bind_param_info ); /** Pointer to ::sqlany_execute() function. */ function( sqlany_execute ); /** Pointer to ::sqlany_execute_direct() function. */ function( sqlany_execute_direct ); /** Pointer to ::sqlany_fetch_absolute() function. */ function( sqlany_fetch_absolute ); /** Pointer to ::sqlany_fetch_next() function. */ function( sqlany_fetch_next ); /** Pointer to ::sqlany_get_next_result() function. */ function( sqlany_get_next_result ); /** Pointer to ::sqlany_affected_rows() function. */ function( sqlany_affected_rows ); /** Pointer to ::sqlany_num_cols() function. */ function( sqlany_num_cols ); /** Pointer to ::sqlany_num_rows() function. */ function( sqlany_num_rows ); /** Pointer to ::sqlany_get_column() function. */ function( sqlany_get_column ); /** Pointer to ::sqlany_get_data() function. */ function( sqlany_get_data ); /** Pointer to ::sqlany_get_data_info() function. */ function( sqlany_get_data_info ); /** Pointer to ::sqlany_get_column_info() function. */ function( sqlany_get_column_info ); /** Pointer to ::sqlany_commit() function. */ function( sqlany_commit ); /** Pointer to ::sqlany_rollback() function. */ function( sqlany_rollback ); /** Pointer to ::sqlany_client_version() function. */ function( sqlany_client_version ); /** Pointer to ::sqlany_error() function. */ function( sqlany_error ); /** Pointer to ::sqlany_sqlstate() function. */ function( sqlany_sqlstate ); /** Pointer to ::sqlany_clear_error() function. */ function( sqlany_clear_error ); #if _SACAPI_VERSION+0 >= 2 /** Pointer to ::sqlany_init_ex() function. */ function( sqlany_init_ex ); /** Pointer to ::sqlany_fini_ex() function. */ function( sqlany_fini_ex ); /** Pointer to ::sqlany_new_connection_ex() function. */ function( sqlany_new_connection_ex ); /** Pointer to ::sqlany_make_connection_ex() function. */ function( sqlany_make_connection_ex ); /** Pointer to ::sqlany_client_version_ex() function. */ function( sqlany_client_version_ex ); /** Pointer to ::sqlany_cancel() function. */ function( sqlany_cancel ); #endif } SQLAnywhereInterface; #undef function /** Initializes the SQLAnywhereInterface object and loads the DLL dynamically. * This function attempts to load the SQL Anywhere C API DLL dynamically and looks up all * the entry points of the DLL. The fields in the SQLAnywhereInterface structure will be * populated to point to the corresponding functions in the DLL. If the optional path argument * is NULL, the environment variable SQLANY_DLL_PATH will be checked. If the variable is set, * the library will attempt to load the DLL specified by the environment variable. If that fails, * the interface will attempt to load the DLL directly (this relies on the environment being * setup correctly). * \param api An API structure to initialize. * \param optional_path_to_dll An optional argument that specifies a path to the DLL API to load. * \return 1 on successful initialization, and 0 on failure. */ int sqlany_initialize_interface( SQLAnywhereInterface * api, const char * optional_path_to_dll ); /** Finalize and free resources associated with the SQL Anywhere C API DLL. * This function will unload the library and uninitialize the supplied SQLAnywhereInterface * structure. * \param api An initialized structure to finalize. */ void sqlany_finalize_interface( SQLAnywhereInterface * api ); #endif
39.048611
140
0.695092
[ "object" ]
3b13f27f9277df06777c11c27ada815a223c9ddb
9,597
h
C
rack/drain/imageops/ImageOp.h
fmidev/rack
95c39ef610637e8068253efc36aab40177caff03
[ "MIT" ]
20
2018-03-21T10:58:00.000Z
2022-02-11T14:43:03.000Z
rack/drain/imageops/ImageOp.h
fmidev/rack
95c39ef610637e8068253efc36aab40177caff03
[ "MIT" ]
null
null
null
rack/drain/imageops/ImageOp.h
fmidev/rack
95c39ef610637e8068253efc36aab40177caff03
[ "MIT" ]
6
2018-07-04T04:55:56.000Z
2021-04-15T19:25:13.000Z
/* MIT License Copyright (c) 2017 FMI Open Development / Markus Peura, first.last@fmi.fi 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. */ /* Part of Rack development has been done in the BALTRAD projects part-financed by the European Union (European Regional Development Fund and European Neighbourhood Partnership Instrument, Baltic Sea Region Programme 2007-2013) */ #ifndef DRAIN_IMAGE_OP_H_ #define DRAIN_IMAGE_OP_H_ #include "drain/util/BeanLike.h" #include "drain/image/CoordinateHandler.h" #include "ImageMod.h" namespace drain { namespace image { /// Base class for image processing functions. /** * * TODO: */ class ImageOp : public ImageMod { public: inline virtual ~ImageOp(){}; // const std::string & getName(); /// Main interface. Typically splits processing to each channel. /** * The default implementation calls makeCompatible() and * * \see processWithTemp() */ virtual void process(const ImageFrame & src, Image & dst) const; virtual void process(const ImageFrame & src, const ImageFrame & srcWeight, Image & dst, Image & dstWeight) const; /* virtual inline void process(const ImageTray<const Channel> & src, ImageTray<Image> & dst) const { processConditional(src, dst, true); } */ /// Run the operator on a series of images. Geometry and type may be changed. UNDER CONSTR /** * Checks that images in dst are not overlapping with those of src. If yes, create tmp images. */ virtual void process(const ImageTray<const Channel> & src, ImageTray<Image> & dst, bool checkOverlap = true) const; // could be Tray<ModifiableChannel> ? // Note: only a default implementation. virtual inline void traverseChannels(const ImageTray<const Channel> & src, ImageTray<Channel> & dst) const { drain::Logger mout(getImgLog(), __FUNCTION__, __FILE__); //REPL this->name+"(ImageOp::)[const ChannelTray &, ChannelTray &]", __FUNCTION__); mout.error() << "not implemented; consider processChannels[Equally|Repeated|Separately]" << mout.endl; // traverseChannelsEqually(src, dst); // traverseChannelsRepeated(src, dst); // traverseChannelsSeparately(src, dst); // traverseMultiChannel(src, dst); } /// Apply to single channel. virtual inline void traverseChannel(const Channel & src, Channel &dst) const { throw std::runtime_error(name+"(ImageOp)::"+__FUNCTION__+"(src,dst) unimplemented."); }; /// Apply to single channel with alpha. virtual inline void traverseChannel(const Channel &src, const Channel &srcAlpha, Channel &dst, Channel &dstAlpha) const { //throw std::runtime_error(name+"(ImageOp)::"+__FUNCTION__+"(src,srcAlpha,dst,dstAlpha) unimplemented."); Logger mout(getImgLog(), __FUNCTION__, __FILE__); mout.note() << "using image channels only (discarding alpha channels)" << mout.endl; traverseChannel(src, dst); }; /// Given source image, determine respective dest image configuration. /** * This default implementations * - changes type and scaling only if either is undefined in dst. * - copies geometry and coordinate policy of src. */ virtual void getDstConf(const ImageConf & src, ImageConf & dst) const; /// Depending on the operator, modifies the geometry and type of dst. /* The old policy was to have this default implementation * -# returns immediately, if dst==src. * -# sets dst type, if unset, to that of src * -# sets dst geometry to that of src */ virtual // TODO: non-virtual, ie, final! void makeCompatible(const ImageConf & src, Image & dst) const; /// Modifies the geometry and type of dst to fit the computation result. /* * This default implementation * - returns immediately, if dst has overlap with src1 or src2. * - else, calls makeCompatible(src1, dst); src2 has no effect. */ virtual void makeCompatible2(const ImageFrame & src1, const ImageFrame & src2, Image & dst) const; /// Prints name, description and parameters using BeanLike::toOStr(). Virtual, so derived classes may extend output. virtual inline void help(std::ostream & ostr = std::cout) const { toStream(ostr); } protected: /** * \param weight_supported - not supported (0), flexibly supported (1) or required (2) * \param tmp_required - temporary image needed, if src and dst are same or overlapping. */ inline // = std::string(__FUNCTION__).substr(0, ::strlen(__FUNCTION__)-2 ImageOp(const std::string &name = __FUNCTION__, const std::string &description="") : ImageMod(name, description){ }; /** * This is needed, otherwise parameters(parameters) is called through BeanLike(BeanLike). */ inline ImageOp(const ImageOp & op) : ImageMod(op.name, op.description){ }; virtual bool processOverlappingWithTemp(const ImageFrame & src, Image & dst) const; virtual bool processOverlappingWithTemp(const ImageTray<const Channel> & src, ImageTray<Image> & dst) const; // Final ? bool traverseOverlappingWithTemp(const Channel & src, Channel & dst) const; // Final ? bool traverseOverlappingWithTemp(const Channel & src, const Channel & srcWeight, Channel & dst, Channel & dstWeight) const; /// Calls processWithTemp() if the frames overlap // Final /// Creates a copy of dstImage, runs the operator and copies the result to dstImage. //bool processOverlappingWithTemp(const ImageFrame & srcFrame, Image & dstImage) const; // needed? /// Calls processWithTemp() if the frames overlap // Final //bool processOverlappingWithTemp(const ImageFrame & src, const ImageFrame & srcWeight, Image & dst, Image & dstWeight) const; // needed? /// Apply to a frame. Target dst must be compatible.. //virtual void traverse rame(const ImageFrame & src, ImageFrame & dst) const; // USE /// Process image channel and alpha channels equally. Eg. resizing operations may use this. /** * Neutral */ void traverseChannelsEqually(const ImageTray<const Channel> & src, ImageTray<Channel> & dst) const; /// Recycle channels until all dst channels completed. void traverseChannelsRepeated(const ImageTray<const Channel> & src, ImageTray<Channel> & dst) const; /// Process each (src,dst) channel pair independently. Raise error if their counts differ. /** */ void traverseChannelsSeparately(const ImageTray<const Channel> & src, ImageTray<Channel> & dst) const; /// Redirect to processing as trays. This is the opposite of processChannels...() functions. inline void traverseAsChannelTrays(const ImageFrame &src, ImageFrame &dst) const { Logger mout(getImgLog(), __FUNCTION__, __FILE__); mout.debug() << "restoring to trays" << mout.endl; ImageTray<const Channel> s; // s.setChannels(src); ImageTray<Channel> d; d.setChannels(dst); traverseChannels(s, d); } /// Redirect to processing as trays. This is the opposite of processChannels...() functions. inline void traverseAsChannelTrays(const ImageFrame &src, const ImageFrame & srcWeight, ImageFrame &dst, ImageFrame &dstWeight) const { Logger mout(getImgLog(), __FUNCTION__, __FILE__); mout.debug() << "restoring to trays" << mout.endl; ImageTray<const Channel> s; s.setChannels(src, srcWeight); ImageTray<Channel> d; d.setChannels(dst, dstWeight); traverseChannels(s, d); } static inline void adaptCoordinateHandler(const Channel & src, CoordinateHandler2D & handler){ handler.set(src.getGeometry(), src.getCoordinatePolicy()); // handler.setLimits(src.getWidth(), src.getHeight()); // handler.setPolicy(src.getCoordinatePolicy()); } protected: /// Set applicable internal parameters before calling traverse(). virtual inline void initializeParameters(const ImageFrame &src, const ImageFrame &dst) const { drain::Logger mout(getImgLog(), __FUNCTION__, __FILE__); // name+"(ImageOp) src,dst" mout.debug() << "nothing defined (ok)" << mout.endl; } /// Set applicable internal parameters before calling traverse(). inline virtual void initializeParameters(const ImageFrame &src, const ImageFrame &src2, const ImageFrame &dst) const { //drain::Logger mout(getImgLog(), __FUNCTION__, __FILE__); //REPL getImgLog(), name+"(ImageOp) src,src2,dst", __FUNCTION__); drain::Logger mout(getImgLog(), __FUNCTION__, __FILE__); mout.debug() << "nothing defined (ok)" << mout.endl; } }; inline std::ostream & operator<<(std::ostream & ostr, const ImageOp &op){ //op.help(ostr); // todo: name & params only ostr << op.getName() << '(' << op.getParameters() << ')'; return ostr; } } // namespace image } // namespace drain #endif /* IMAGE_OP_H_ */ // Drain
33.207612
147
0.718454
[ "geometry" ]
3b1836cd4852e47da92abcb6edb9cdbc850d854b
784
h
C
CodePath-TwitterClient/View/TWTweetTableViewCell.h
jhurray/CodePath-TwitterClient
4bd7c7e6a241aa6b24aa261b84e3d407250c58bd
[ "MIT" ]
1
2017-02-06T21:05:37.000Z
2017-02-06T21:05:37.000Z
CodePath-TwitterClient/View/TWTweetTableViewCell.h
jhurray/CodePath-TwitterClient
4bd7c7e6a241aa6b24aa261b84e3d407250c58bd
[ "MIT" ]
null
null
null
CodePath-TwitterClient/View/TWTweetTableViewCell.h
jhurray/CodePath-TwitterClient
4bd7c7e6a241aa6b24aa261b84e3d407250c58bd
[ "MIT" ]
null
null
null
// // TWTweetTableViewCell.h // CodePath-TwitterClient // // Created by Jeffrey Hurray on 1/29/17. // Copyright © 2017 Jeffrey Hurray. All rights reserved. // #import <UIKit/UIKit.h> #import "TWTweet.h" @class TWTweetTableViewCell; @protocol TWTweetTableViewCellDelegate <NSObject> - (void)tweetTableViewCellProfileImageSelected:(TWTweetTableViewCell *)cell; - (void)tweetTableViewCellReplySelected:(TWTweetTableViewCell *)cell; - (void)tweetTableViewCellRetweetSelected:(TWTweetTableViewCell *)cell; - (void)tweetTableViewCellFavoriteSelected:(TWTweetTableViewCell *)cell; @end @interface TWTweetTableViewCell : UITableViewCell @property (nonatomic, strong) TWTweet *model; @property (nonatomic, weak) id<TWTweetTableViewCellDelegate> delegate; - (void)reloadData; @end
26.133333
76
0.790816
[ "model" ]
3b24b4b2e6a5bd8d3290d38a585df379ed79945b
3,593
h
C
Source/BenchTable/Skeleton/SkeletonCommon.h
Dwarfius/VulkanRTSEngine
b26d49114aea07566ac60ea8ccf9afc3c21d615a
[ "Apache-2.0" ]
17
2017-10-29T15:47:41.000Z
2022-03-05T16:53:03.000Z
Source/BenchTable/Skeleton/SkeletonCommon.h
Dwarfius/VulkanRTSEngine
b26d49114aea07566ac60ea8ccf9afc3c21d615a
[ "Apache-2.0" ]
null
null
null
Source/BenchTable/Skeleton/SkeletonCommon.h
Dwarfius/VulkanRTSEngine
b26d49114aea07566ac60ea8ccf9afc3c21d615a
[ "Apache-2.0" ]
4
2020-08-16T16:05:12.000Z
2021-09-24T22:30:41.000Z
#pragma once #include <random> #include <Core/Transform.h> #include <Engine/Animation/Skeleton.h> struct BoneInput { Transform myLocalTransf{}; Skeleton::BoneIndex myParentInd = Skeleton::kInvalidIndex; }; constexpr static size_t kMaxSize = 1024; const static std::vector<BoneInput> kBoneInputs = [] { std::random_device realRandSeed; std::mt19937 engine(realRandSeed()); std::uniform_int_distribution<Skeleton::BoneIndex> distrib; std::vector<BoneInput> inputs; inputs.resize(kMaxSize); for (size_t i = 1; i < kMaxSize; i++) { std::uniform_int_distribution<Skeleton::BoneIndex>::param_type newParams(0, i - 1); distrib.param(newParams); inputs[i].myParentInd = distrib(engine); } return inputs; } (); const static std::vector<Skeleton::BoneIndex> kIndices = [] { std::random_device realRandSeed; std::mt19937 engine(realRandSeed()); std::uniform_int_distribution<Skeleton::BoneIndex> distrib; std::vector<Skeleton::BoneIndex> indices; indices.resize(kMaxSize); indices[0] = 0; for (Skeleton::BoneIndex i = 1; i < kMaxSize; i++) { std::uniform_int_distribution<Skeleton::BoneIndex>::param_type newParams(1, i); distrib.param(newParams); indices[i] = distrib(engine); } return indices; }(); struct GroupedBone { Transform myLocalTransf{}; Transform myWorldTransf{}; // unused, padding Transform myInverseBindTransf{}; // ==== Skeleton::BoneIndex myParentInd = Skeleton::kInvalidIndex; // unused, padding Skeleton::BoneIndex myFirstChildInd = Skeleton::kInvalidIndex; Skeleton::BoneIndex myChildCount = 0; // ==== static std::vector<GroupedBone> ProcessBones(const std::vector<BoneInput>& aInputs, size_t aCount) { std::vector<GroupedBone> bones; bones.resize(aCount); // copying all the info for (size_t i = 0; i < aCount; i++) { bones[i].myLocalTransf = aInputs[i].myLocalTransf; bones[i].myParentInd = aInputs[i].myParentInd; } // grouping by parent auto sortStart = bones.begin(); std::advance(bones.begin(), 1); std::sort(sortStart, bones.end(), [](const GroupedBone& left, const GroupedBone& right) { if (left.myParentInd == Skeleton::kInvalidIndex) { return true; } else if (right.myParentInd == Skeleton::kInvalidIndex) { return false; } return left.myParentInd < right.myParentInd; }); // find grouping indices Skeleton::BoneIndex currStart = 0; Skeleton::BoneIndex currCount = 0; Skeleton::BoneIndex currParent = Skeleton::kInvalidIndex; for (Skeleton::BoneIndex i = 0; i < bones.size(); i++) { GroupedBone& bone = bones[i]; if (bone.myParentInd != currParent) { for (Skeleton::BoneIndex j = currStart; j < currStart + currCount; j++) { bones[j].myFirstChildInd = currStart; bones[j].myChildCount = currCount; } currStart = i; currCount = 0; currParent = bone.myParentInd; } else { currCount++; } } for (Skeleton::BoneIndex j = currStart; j < currStart + currCount; j++) { bones[j].myFirstChildInd = currStart; bones[j].myChildCount = currCount + 1; } return bones; } }; struct Bone { Transform myLocalTransf{}; Transform myWorldTransf{}; // unused, padding Transform myInverseBindTransf{}; // ==== Skeleton::BoneIndex myParentInd = Skeleton::kInvalidIndex; static std::vector<Bone> ProcessBones(const std::vector<BoneInput>& aInputs, size_t aCount) { std::vector<Bone> bones; bones.resize(aCount); for (size_t i = 0; i < aCount; i++) { bones[i].myLocalTransf = aInputs[i].myLocalTransf; bones[i].myParentInd = aInputs[i].myParentInd; } return bones; } };
25.848921
99
0.693571
[ "vector", "transform" ]
3b374ccc88f789e4d5bbd724c6f367845ce4b42e
9,051
h
C
HopsanGUI/MainWindow.h
mjfwest/hopsan
77a0a1e69fd9588335b7e932f348972186cbdf6f
[ "Apache-2.0" ]
null
null
null
HopsanGUI/MainWindow.h
mjfwest/hopsan
77a0a1e69fd9588335b7e932f348972186cbdf6f
[ "Apache-2.0" ]
null
null
null
HopsanGUI/MainWindow.h
mjfwest/hopsan
77a0a1e69fd9588335b7e932f348972186cbdf6f
[ "Apache-2.0" ]
null
null
null
/*----------------------------------------------------------------------------- Copyright 2017 Hopsan Group 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/>. The full license is available in the file GPLv3. For details about the 'Hopsan Group' or information about Authors and Contributors see the HOPSANGROUP and AUTHORS files that are located in the Hopsan source code root directory. -----------------------------------------------------------------------------*/ //! //! @file MainWindow.h //! @author Flumes <flumes@lists.iei.liu.se> //! @date 2010-01-01 //! //! @brief Contains the HopsanGUI MainWindow class //! //$Id$ #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QLineEdit> #include <QGridLayout> #include <QFileInfo> #include <QDir> #include <QLabel> #include <QToolButton> class CentralTabWidget; class GraphicsView; class QGraphicsScene; class LibraryWidget; class OptionsDialog; class MessageWidget; class TerminalConsole; class PlotWidget2; class PyDockWidget; class SystemParametersWidget; class WelcomeWidget; class Configuration; class CopyStack; class AboutDialog; class HelpDialog; class OptimizationDialog; class SensitivityAnalysisDialog; class TerminalWidget; class UndoWidget; class HVCWidget; class ModelHandler; class MainWindowLineEdit; class DataExplorer; class FindWidget; class HelpPopUpWidget; class SimulationTimeEdit : public QWidget { Q_OBJECT public: SimulationTimeEdit(QWidget *pParent); void getSimulationTime(QString &rStartTime, QString &rTimeStep, QString &rStopTime) const; QString getStartTime() const; QString getTimeStep() const; QString getStopTime() const; void displayStartTime(const QString startTime); void displayTimeStep(const QString timeStep); void dispalyStopTime(const QString stopTime); void clearFocus(); public slots: void displaySimulationTime(const QString startTime, const QString timeStep, const QString stopTime); signals: void simulationTimeChanged(QString start, QString ts, QString stop); void mouseEnterEvent(); protected: bool eventFilter(QObject *object, QEvent *event); private slots: void emitSimTime(); private: QLineEdit *mpStartTimeLineEdit; QLineEdit *mpTimeStepLineEdit; QLineEdit *mpStopTimeLineEdit; }; class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = 0); ~MainWindow(); void createContents(); OptionsDialog *getOptionsDialog(); // Get methods for simulation parameters in toolbar double getStartTimeFromToolBar(); double getTimeStepFromToolBar(); double getFinishTimeFromToolBar(); void closeEvent(QCloseEvent *event); void showHelpPopupMessage(const QString &rMessage); void hideHelpPopupMessage(); //Widgets //! @todo These should probably not be public UndoWidget *mpUndoWidget; CentralTabWidget *mpCentralTabs; ModelHandler *mpModelHandler; WelcomeWidget *mpWelcomeWidget; LibraryWidget *mpLibraryWidget; SystemParametersWidget *mpSystemParametersWidget; QStatusBar *mpStatusBar; //Not used, but gives some nice extra space at bottom :) QGridLayout *mpCentralGridLayout; HVCWidget *mpHVCWidget; DataExplorer *mpDataExplorer; OptimizationDialog *mpOptimizationDialog; SimulationTimeEdit *mpSimulationTimeEdit; //Actions (public because other widgets connect to them) QAction *mpNewAction; QAction *mpOpenAction; QAction *mpSaveAction; QAction *mpSaveAsAction; QAction *mpExportSimulationStateAction; QAction *mpExportModelParametersAction; QAction *mpImportFMUAction; QAction *mpImportDataFileAction; QAction *mpExportToSimulinkAction; QAction *mpExportToFMU1_32Action; QAction *mpExportToFMU1_64Action; QAction *mpExportToFMU2_32Action; QAction *mpExportToFMU2_64Action; QAction *mpExportToLabviewAction; QAction *mpLoadModelParametersAction; QAction *mpCloseAction; QAction *mpUndoAction; QAction *mpRedoAction; QAction *mpOpenUndoAction; QAction *mpOpenSystemParametersAction; QAction *mpOpenHvcWidgetAction; QAction *mpOpenDataExplorerAction; QAction *mpOpenFindWidgetAction; QAction *mpRevertModelAction; QAction *mpNumHopAction; QAction *mpDisableUndoAction; QAction *mpCutAction; QAction *mpCopyAction; QAction *mpPasteAction; QAction *mpOpenDebuggerAction; QAction *mpCoSimulationAction; QAction *mpToggleRemoteCoreSimAction; QAction *mpOptimizeAction; QAction *mpSensitivityAnalysisAction; QAction *mpPlotAction; QAction *mpLoadLibsAction; QAction *mpPropertiesAction; QAction *mpOptionsAction; QAction *mpAnimateAction; QAction *mpResetZoomAction; QAction *mpZoomInAction; QAction *mpZoomOutAction; QAction *mpCenterViewAction; QAction *mpToggleNamesAction; QAction *mpTogglePortsAction; QAction *mpToggleSignalsAction; QAction *mpExportGfxAction; QAction *mpPrintAction; QAction *mpExportPDFAction; QAction *mpExportPNGAction; QAction *mpAlignXAction; QAction *mpAlignYAction; QAction *mpDistributeXAction; QAction *mpDistributeYAction; QAction *mpRotateLeftAction; QAction *mpRotateRightAction; QAction *mpFlipHorizontalAction; QAction *mpFlipVerticalAction; QAction *mpIssueTrackerAction; QAction *mpAboutAction; QAction *mpLicenseAction; QAction *mpHelpAction; QAction *mpReleaseNotesAction; QAction *mpWebsiteAction; QAction *mpNewVersionsAction; QAction *mpShowLossesAction; QAction *mpMeasureSimulationTimeAction; QAction *mpToggleHideAllDockAreasAction; QAction *mpDebug1Action; QAction *mpDebug2Action; QDockWidget *mpTerminalDock; public slots: // void show(); void initializeWorkspace(); void updateToolBarsToNewTab(); void refreshUndoWidgetList(); void updateRecentList(); signals: void simulateKeyPressed(); protected: virtual void mouseMoveEvent(QMouseEvent *); virtual void keyPressEvent(QKeyEvent *); private slots: void simulateKeyWasPressed(); void openHVCWidget(); void openDataExplorerWidget(); void openFindWidget(); void revertModel(); void openNumHopDialog(); void toggleVisiblePlotWidget(); void openUndoWidget(); void openSystemParametersWidget(); void openRecentModel(); void openHopsanURL(); void openArchiveURL(); void openIssueTrackerDialog(); void updatePlotActionButton(bool); void updateSystemParametersActionButton(bool); void showToolBarHelpPopup(); void openModelByAction(); void showReleaseNotes(); void toggleHideShowDockAreas(bool show); void openLicenseDialog(); private: void createActions(); void createMenus(); void createToolbars(); void buildModelActionsMenu(QMenu *pParentMenu, QDir dir); // Private Actions QAction *mpSimulateAction; QToolButton *mpExportToFMUMenuButton; // Dialogs OptionsDialog *mpOptionsDialog; AboutDialog *mpAboutDialog; SensitivityAnalysisDialog *mpSensitivityAnalysisDialog; // Dock area widgets QDockWidget *mpMessageDock; QDockWidget *mpLibDock; QDockWidget *mpPlotWidgetDock; QDockWidget *mpUndoWidgetDock; QDockWidget *mpSystemParametersDock; QDockWidget *mpPyDockWidget; QWidget *mpCentralWidget; QGridLayout *mpTabgrid; // Widgets MessageWidget *mpMessageWidget; HelpDialog *mpHelpDialog; // Menubar items QMenuBar *mpMenuBar; QMenu *mpFileMenu; QMenu *mpNewMenu; QMenu *mpLibsMenu; QMenu *mpSimulationMenu; QMenu *mpEditMenu; QMenu *mpViewMenu; QMenu *mpToolsMenu; QMenu *mpImportMenu; QMenu *mpExportMenu; QMenu *mpExportToFMUMenu; QMenu *mpPlotMenu; QMenu *mpRecentMenu; QMenu *mpHelpMenu; QMenu *mpExamplesMenu; QMenu *mpTestModelsMenu; // Buttons QToolButton *mpImportButton; QToolButton *mpExportButton; // Toolbar items QToolBar *mpFileToolBar; QToolBar *mpConnectivityToolBar; QToolBar *mpEditToolBar; QToolBar *mpToolsToolBar; QToolBar *mpSimToolBar; QToolBar *mpViewToolBar; QLabel *mpTimeLabelDeliminator1; QLabel *mpTimeLabelDeliminator2; // Help popup HelpPopUpWidget *mpHelpPopup; QMap<QAction*, QString> mHelpPopupTextMap; }; #endif // MAINWINDOW_H
27.678899
104
0.733068
[ "object" ]
3b4b14f3df789f9cea5297c4aa39c64fc2341788
3,521
h
C
libaqmd3/include/libaqmd3/acquireddata.h
PNNL-Comp-Mass-Spec/AqMD3-Acquisition-Console
59eca8ec256218ec3f2117a55198a2d6d2406813
[ "BSD-2-Clause" ]
1
2021-07-26T21:13:03.000Z
2021-07-26T21:13:03.000Z
libaqmd3/include/libaqmd3/acquireddata.h
PNNL-Comp-Mass-Spec/AqMD3-Acquisition-Console
59eca8ec256218ec3f2117a55198a2d6d2406813
[ "BSD-2-Clause" ]
null
null
null
libaqmd3/include/libaqmd3/acquireddata.h
PNNL-Comp-Mass-Spec/AqMD3-Acquisition-Console
59eca8ec256218ec3f2117a55198a2d6d2406813
[ "BSD-2-Clause" ]
null
null
null
#ifndef ACQUIRED_DATA_H #define ACQUIRED_DATA_H #include "acquisitionbuffer.h" #include <UIMFWriter/encodedresult.h> #include <tuple> #include <vector> #include <list> // Contains raw sample data, timestamp data, and gated-record data for both CST and CST-ZS acquisition. // For CST acquision, this class simply holds the raw sample data and cannot be used to extract samples // from elements. class AcquiredData { public: // Gated record descriptor class used to calculate the first and last valid sample index, and the number of elements to process in the // flat array of elements. class GateData { private: // This is the minimum size of a gated record on the SA220P and is used to calculate the sample index of the // first valid sample in a gated record and the position of the gated record in the the area after a trigger // event when a sample can be recorded (also known as the "record"). int const processing_block_size = 8; public: // *_block_index member variables are the index in units of processing_block_size blocks of int32 elements within the record. uint64_t const gate_start_block_index; uint64_t const gate_stop_block_index; // *_sample_pos member variables are the index of the first valid sample or one after the last valid sample within the processing_block_size // sized block at index gate_*_block index. uint32_t const gate_start_sample_pos; uint32_t const gate_stop_sample_pos; // The total number of elements in the gated record. uint32_t const element_count; GateData(uint64_t gate_start_block_index, uint32_t gate_start_sample_pos, uint64_t gate_stop_block_index, uint32_t gate_stop_sample_pos, uint32_t element_count) : gate_start_block_index(gate_start_block_index) , gate_start_sample_pos(gate_start_sample_pos) , gate_stop_block_index(gate_stop_block_index) , gate_stop_sample_pos(gate_stop_sample_pos) , element_count(element_count) {} inline uint64_t get_start_sample_index() const { return (gate_start_block_index - 1) * processing_block_size + gate_start_sample_pos; } inline uint64_t get_stop_sample_index() const { return (gate_stop_block_index - 1) * processing_block_size - (processing_block_size - gate_stop_sample_pos); } }; // Couples trigger timestamps data with gated record information. class TriggerData { public: uint64_t const timestamp; double const subsample_pos; uint32_t const index; std::vector<GateData> gate_data; TriggerData(uint64_t timestamp, uint32_t index, double subsample_pos) : timestamp(timestamp) , index(index) , subsample_pos(subsample_pos) , gate_data() {} }; private: std::shared_ptr<AcquisitionBuffer> samples_buffer; // Used to bring data into the unsigned int16 range. [-2^15, 2^15 - 1] + 2^15 -> [0, 2^16 - 1] int32_t const range_shift_constant = 32768; public: std::vector<TriggerData> const stamps; uint64_t const samples_count; public: AcquiredData(std::vector<TriggerData> stamps, std::shared_ptr<AcquisitionBuffer> samples_buffer, uint64_t samples_count) : samples_buffer(samples_buffer) , stamps(stamps) , samples_count(samples_count) {} // Processes the raw sample data and returns a vector of processed results equivalent to a row of scan data in a .uimf file. // Should not be called if the data was acquired without data-reduction enabled. std::shared_ptr<std::vector<EncodedResult>> process(int processing_scan_start_number, uint32_t post_trigger_samples) const; }; #endif // !ACQUIRED_DATA_H
35.928571
143
0.774212
[ "vector" ]
3b4bc6e99d7ca888c7ac6b44df8b02029c1020d6
831
h
C
vmicore/src/io/IEventStream.h
GDATASoftwareAG/smartvmi
68c9d9791c3b291ec2b49ffd8191c9cdf335baf3
[ "MIT" ]
5
2022-02-17T23:35:08.000Z
2022-02-21T12:36:45.000Z
vmicore/src/io/IEventStream.h
GDATASoftwareAG/smartvmi
68c9d9791c3b291ec2b49ffd8191c9cdf335baf3
[ "MIT" ]
null
null
null
vmicore/src/io/IEventStream.h
GDATASoftwareAG/smartvmi
68c9d9791c3b291ec2b49ffd8191c9cdf335baf3
[ "MIT" ]
null
null
null
#ifndef VMICORE_IEVENTSTREAM_H #define VMICORE_IEVENTSTREAM_H #include "cxxbridge/rust_grpc_server/src/bridge.rs.h" #include <memory> #include <vector> class IEventStream { public: virtual ~IEventStream() = default; virtual void sendProcessEvent(::grpc::ProcessState processState, const std::string& processName, uint32_t processID, const std::string& cr3) = 0; virtual void sendBSODEvent(int64_t code) = 0; virtual void sendReadyEvent() = 0; virtual void sendTerminationEvent() = 0; virtual void sendErrorEvent(const std::string& message) = 0; virtual void sendInMemDetectionEvent(const std::string& message) = 0; protected: IEventStream() = default; }; #endif // VMICORE_IEVENTSTREAM_H
29.678571
73
0.652226
[ "vector" ]
3b4f5564a0cea2abf23a3dc4ae19ed97f95ff824
548
h
C
Board.h
spakai/tictactoe
f1c45523db6b768004d617bb2c6970907bb0566d
[ "Apache-2.0" ]
3
2015-11-19T06:53:01.000Z
2015-12-18T18:05:54.000Z
Board.h
spakai/tictactoe
f1c45523db6b768004d617bb2c6970907bb0566d
[ "Apache-2.0" ]
null
null
null
Board.h
spakai/tictactoe
f1c45523db6b768004d617bb2c6970907bb0566d
[ "Apache-2.0" ]
null
null
null
#pragma once #include <vector> #include <algorithm> #include <iostream> #include "GenericPlayer.h" #include "PlayerOptions.h" #include "GameResults.h" class GenericPlayer; class Board { public: Board(); std::vector<PlayerOptions>& getBoard(); bool makeMove(const GenericPlayer & player, const int move); void clearMove(const int move); GameResults Winner() const; void displayBoard() const ; private: std::vector<PlayerOptions> m_Board; bool isValidMove(const int move) const; };
21.076923
68
0.671533
[ "vector" ]
3b566e33c5bef6fa3b286f3696cc949cdec6a232
806
c
C
1/13.c
harrisi/bookish-eureka
218122b37042a0ba7a856f4d220badd2643c9644
[ "MIT" ]
null
null
null
1/13.c
harrisi/bookish-eureka
218122b37042a0ba7a856f4d220badd2643c9644
[ "MIT" ]
null
null
null
1/13.c
harrisi/bookish-eureka
218122b37042a0ba7a856f4d220badd2643c9644
[ "MIT" ]
null
null
null
#include <stdio.h> #define IN 1 #define OUT 0 #define MAX_WORD 1000 main() { int c, nw, lw, state; // curChar, numWords, lenWord, state; int nword[MAX_WORD + 1]; state = OUT; nw = lw = 0; for (int i = 0; i <= MAX_WORD + 1; i++) { nword[i] = 0; } while ((c = getchar()) != EOF) { if (c == ' ' || c == '\n' || c == '\t') { state = OUT; nword[lw]++; lw = 0; } else { state = IN; ++lw; } } printf("output:\n"); for (int i = 1; i <= MAX_WORD; i++) { if (nword[i] > 0) { printf("length %3d: ", i); for (int j = 1; j <= nword[i]; j++) { putchar('*'); } putchar('\n'); } } return 0; }
19.658537
49
0.368486
[ "3d" ]
3b5df757a30f9a52901d66f9596f7ce13aac9d34
3,686
h
C
indra/newview/llfloaterimnearbychat.h
humbletim/archived-casviewer
3b51b1baae7e7cebf1c7dca62d9c02751709ee57
[ "Unlicense" ]
1
2022-01-29T07:10:03.000Z
2022-01-29T07:10:03.000Z
indra/newview/llfloaterimnearbychat.h
bloomsirenix/Firestorm-manikineko
67e1bb03b2d05ab16ab98097870094a8cc9de2e7
[ "Unlicense" ]
null
null
null
indra/newview/llfloaterimnearbychat.h
bloomsirenix/Firestorm-manikineko
67e1bb03b2d05ab16ab98097870094a8cc9de2e7
[ "Unlicense" ]
1
2021-10-01T22:22:27.000Z
2021-10-01T22:22:27.000Z
/** * @file llfloaterimnearbychat.h * @brief LLFloaterIMNearbyChat class definition * * $LicenseInfo:firstyear=2002&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #if 0 #ifndef LL_LLFLOATERIMNEARBYCHAT_H #define LL_LLFLOATERIMNEARBYCHAT_H #include "llfloaterimsessiontab.h" #include "llcombobox.h" #include "llgesturemgr.h" #include "llchat.h" #include "llvoiceclient.h" #include "lloutputmonitorctrl.h" #include "llspeakers.h" #include "llscrollbar.h" #include "llviewerchat.h" #include "llpanel.h" class LLResizeBar; class LLFloaterIMNearbyChat : public LLFloaterIMSessionTab { public: // constructor for inline chat-bars (e.g. hosted in chat history window) LLFloaterIMNearbyChat(const LLSD& key = LLSD(LLUUID())); ~LLFloaterIMNearbyChat() {} static LLFloaterIMNearbyChat* buildFloater(const LLSD& key); /*virtual*/ BOOL postBuild(); /*virtual*/ void onOpen(const LLSD& key); /*virtual*/ void onClose(bool app_quitting); /*virtual*/ void setVisible(BOOL visible); /*virtual*/ void setVisibleAndFrontmost(BOOL take_focus=TRUE, const LLSD& key = LLSD()); /*virtual*/ void closeHostedFloater(); void loadHistory(); void reloadMessages(bool clean_messages = false); void removeScreenChat(); void show(); bool isChatVisible() const; /** @param archive true - to save a message to the chat history log */ void addMessage (const LLChat& message,bool archive = true, const LLSD &args = LLSD()); LLChatEntry* getChatBox() { return mInputEditor; } std::string getCurrentChat(); S32 getMessageArchiveLength() {return mMessageArchive.size();} virtual BOOL handleKeyHere( KEY key, MASK mask ); static void startChat(const char* line); static void stopChat(); static void sendChatFromViewer(const std::string &utf8text, EChatType type, BOOL animate); static void sendChatFromViewer(const LLWString &wtext, EChatType type, BOOL animate); static bool isWordsName(const std::string& name); void showHistory(); protected: static BOOL matchChatTypeTrigger(const std::string& in_str, std::string* out_str); void onChatBoxKeystroke(); void onChatBoxFocusLost(); void onChatBoxFocusReceived(); void sendChat( EChatType type ); void onChatBoxCommit(); void onChatFontChange(LLFontGL* fontp); /*virtual*/ void onTearOffClicked(); /*virtual*/ void onClickCloseBtn(bool app_qutting = false); static LLWString stripChannelNumber(const LLWString &mesg, S32* channel); EChatType processChatTypeTriggers(EChatType type, std::string &str); void displaySpeakingIndicator(); // Which non-zero channel did we last chat on? static S32 sLastSpecialChatChannel; LLOutputMonitorCtrl* mOutputMonitor; LLLocalSpeakerMgr* mSpeakerMgr; S32 mExpandedHeight; private: /*virtual*/ void refresh(); std::vector<LLChat> mMessageArchive; }; #endif // LL_LLFLOATERIMNEARBYCHAT_H #endif
29.725806
91
0.754748
[ "vector" ]
3b66fc48b970063fcd846a480b71e1acd67a67bc
632
h
C
cavs/frontend/cxx/graphsupport.h
xsz/HPops
35bcc0316fe313529b67472ad6702ceacf771d01
[ "Apache-2.0" ]
9
2020-09-19T06:29:48.000Z
2022-01-31T09:24:25.000Z
cavs/frontend/cxx/graphsupport.h
xsz/HPops
35bcc0316fe313529b67472ad6702ceacf771d01
[ "Apache-2.0" ]
1
2021-02-15T05:56:57.000Z
2021-02-17T21:15:27.000Z
cavs/frontend/cxx/graphsupport.h
xsz/HPops
35bcc0316fe313529b67472ad6702ceacf771d01
[ "Apache-2.0" ]
3
2020-09-19T16:22:47.000Z
2021-02-16T07:34:47.000Z
#ifndef CAVS_FRONTEND_CXX_VERTEX_H_ #define CAVS_FRONTEND_CXX_VERTEX_H_ #include "cavs/frontend/cxx/sym.h" #include <vector> #include <string> class GraphSupport { public: GraphSupport(const Sym& graph_ph, const Sym& vertex_ph) : raw_graph_(graph_ph), raw_vertex_(vertex_ph) {} //virtual void Inode() = 0; //virtual void Leaf() = 0; virtual void Node() = 0; Sym Output(); protected: Sym Gather(int child, const std::vector<int>& shape); Sym Pull(int offset, const std::vector<int>& shape); void Push(const Sym& s); void Scatter(const Sym& s); private: Sym raw_graph_; Sym raw_vertex_; }; #endif
21.066667
60
0.702532
[ "shape", "vector" ]
3b904c346316a4200027e54a0e08b92425acd16e
1,748
h
C
aplcore/include/apl/graphic/graphicelementcontainer.h
DamianMehers/apl-core-library
9c003dbfc8bc90709396c07179c523473d380db1
[ "Apache-2.0" ]
28
2019-11-05T12:23:01.000Z
2022-03-22T10:01:53.000Z
aplcore/include/apl/graphic/graphicelementcontainer.h
DamianMehers/apl-core-library
9c003dbfc8bc90709396c07179c523473d380db1
[ "Apache-2.0" ]
7
2020-03-28T12:44:08.000Z
2022-01-23T17:02:27.000Z
aplcore/include/apl/graphic/graphicelementcontainer.h
DamianMehers/apl-core-library
9c003dbfc8bc90709396c07179c523473d380db1
[ "Apache-2.0" ]
15
2019-12-25T10:15:52.000Z
2021-12-30T03:50:00.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #ifndef _APL_GRAPHIC_ELEMENT_CONTAINER_H #define _APL_GRAPHIC_ELEMENT_CONTAINER_H #include "apl/graphic/graphicelement.h" namespace apl { class GraphicElementContainer : public GraphicElement, public Counter<GraphicElementContainer> { public: static GraphicElementPtr create(const GraphicPtr& graphic, const ContextPtr& context, const Object& json); GraphicElementContainer(const GraphicPtr& graphic, const ContextPtr& context) : GraphicElement(graphic, context) {} GraphicElementType getType() const override { return kGraphicElementTypeContainer; } bool hasChildren() const override { return true; } std::string toDebugString() const override { std::string result = "GraphicElementContainer<children=["; for (auto& child : mChildren) { result += " "; result += child->toDebugString(); } result += ">"; return result; } protected: const GraphicPropDefSet& propDefSet() const override; bool initialize(const GraphicPtr& graphic, const Object& json) override; }; } // namespace apl #endif // _APL_GRAPHIC_ELEMENT_CONTAINER_H
32.981132
119
0.707094
[ "object" ]
3b95634049c20dbe8ae48d17cc4a2b68de3eafa6
8,593
h
C
B2G/gecko/media/webrtc/signaling/src/sipcc/core/includes/phone_platform_constants.h
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/gecko/media/webrtc/signaling/src/sipcc/core/includes/phone_platform_constants.h
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/gecko/media/webrtc/signaling/src/sipcc/core/includes/phone_platform_constants.h
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the Cisco Systems SIP Stack. * * The Initial Developer of the Original Code is * Cisco Systems (CSCO). * Portions created by the Initial Developer are Copyright (C) 2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Enda Mannion <emannion@cisco.com> * Suhas Nandakumar <snandaku@cisco.com> * Ethan Hugg <ehugg@cisco.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef _PHONE_PLATFORM_CONSTANTS_H_ #define _PHONE_PLATFORM_CONSTANTS_H_ // Defines for the various phone models. Note that the device numbers // appearing after the model name are pre-determined when new phone models // are added and must correspond to the ones programmed into CCM #define SIP_FIRMWARE_VERSION "9.1.1" // Legacy #define PHONE_MODEL_NUMBER_7940 "8" #define PHONE_MODEL_NUMBER_7960 "7" #define LEGACY_MODEL_7940 "CP-7940G" #define LEGACY_MODEL_7960 "CP-7960G" #define CCSIP_SIP_7940_USER_AGENT "CP7940G" #define CCSIP_SIP_7960_USER_AGENT "CP7960G" // Communicator // Note: The Communicator will send its native device number of 30016 // so that the CCM will recognize it as a CIPC. If talking to an older CCM // that expects the Communicator to register as a 7970, please define // _CIPC_7970_ in SIP project file #ifdef _CIPC_7970_ #define PHONE_MODEL_NUMBER_COMMUNICATOR "30006" #else #define PHONE_MODEL_NUMBER_COMMUNICATOR "30016" #endif #define CCSIP_SIP_COMMUNICATOR_USER_AGENT "SIPIPCommunicator" // UC core #define PHONE_MODEL_NUMBER_UCCORE "358" #define CCSIP_SIP_UCCORE_USER_AGENT "SIPUCCore" // 8961 #define PHONE_MODEL_NUMBER_8961 "540" #define RT_MODEL_8961 "CP-8961" #define CCSIP_SIP_8961_USER_AGENT "CP8961" // 9951 #define PHONE_MODEL_NUMBER_9951 "537" #define RT_MODEL_9951 "CP-9951" #define CCSIP_SIP_9951_USER_AGENT "CP9951" // 9971 #define PHONE_MODEL_NUMBER_9971 "493" #define RT_MODEL_9971 "CP-9971" #define CCSIP_SIP_9971_USER_AGENT "CP9971" // 7970 #define PHONE_MODEL_NUMBER_7970 "30006" #define TNP_MODEL_7970 "CP-7970G" #define CCSIP_SIP_7970_USER_AGENT "CP7970G" // 7971 #define PHONE_MODEL_NUMBER_7971 "119" #define TNP_MODEL_7971 "CP-7971G-GE" #define CCSIP_SIP_7971_USER_AGENT "CP7971G-GE" // 7911 #define PHONE_MODEL_NUMBER_7911 "307" #define TNP_MODEL_7911 "CP-7911G" #define CCSIP_SIP_7911_USER_AGENT "CP7911G" // 7906 #define PHONE_MODEL_NUMBER_7906 "369" #define TNP_MODEL_7906 "CP-7906G" #define CCSIP_SIP_7906_USER_AGENT "CP7906G" // 7931 #define PHONE_MODEL_NUMBER_7931 "348" #define TNP_MODEL_7931 "CP-7931G" #define CCSIP_SIP_7931_USER_AGENT "CP7931G" // Maximum Lines on 794X models #define MAX_REG_LINES_794X 2 // 7941 #define PHONE_MODEL_NUMBER_7941 "115" #define TNP_MODEL_7941 "CP-7941G" #define CCSIP_SIP_7941_USER_AGENT "CP7941G" // 7941 GE #define PHONE_MODEL_NUMBER_7941GE "309" #define TNP_MODEL_7941GE "CP-7941G-GE" #define CCSIP_SIP_7941_GE_USER_AGENT "CP7941G-GE" // 7961 #define PHONE_MODEL_NUMBER_7961 "30018" #define TNP_MODEL_7961 "CP-7961G" #define CCSIP_SIP_7961_USER_AGENT "CP7961G" // 7961 GE #define PHONE_MODEL_NUMBER_7961GE "308" #define TNP_MODEL_7961GE "CP-7961G-GE" #define CCSIP_SIP_7961_GE_USER_AGENT "CP7961G-GE" // 7942 #define PHONE_MODEL_NUMBER_7942 "434" #define TNP_MODEL_7942 "CP-7942G" #define CCSIP_SIP_7942_USER_AGENT "CP7942G" // 7945 #define PHONE_MODEL_NUMBER_7945 "435" #define TNP_MODEL_7945 "CP-7945G" #define CCSIP_SIP_7945_USER_AGENT "CP7945G" // 7962 #define PHONE_MODEL_NUMBER_7962 "404" #define TNP_MODEL_7962 "CP-7962G" #define CCSIP_SIP_7962_USER_AGENT "CP7962G" // 7965 #define PHONE_MODEL_NUMBER_7965 "436" #define TNP_MODEL_7965 "CP-7965G" #define CCSIP_SIP_7965_USER_AGENT "CP7965G" // 7975 #define PHONE_MODEL_NUMBER_7975 "437" #define TNP_MODEL_7975 "CP-7975G" #define CCSIP_SIP_7975_USER_AGENT "CP7975G" // CSF #define PHONE_MODEL_NUMBER_CSF "503" #define CSF_MODEL "CSF" #define CCSIP_SIP_CSF_USER_AGENT "IKRAN" // CIUS #define PHONE_MODEL_NUMBER_CIUS "593" #define CIUS_MODEL "CP-CIUS" #define CCSIP_SIP_CIUS_USER_AGENT "CPCIUS" // SOUNDWAVE #define PHONE_MODEL_NUMBER_SOUNDWAVE "575" #define SOUNDWAVE_MODEL "SOUNDWAVE" #define CCSIP_SIP_SOUNDWAVE_USER_AGENT "SOUNDWAVE" #define MAX_SIDECAR_LINES 28 // Max number of lines supported on sidecars #define MAX_BKEM_LINES 48 // Max number of lines supported on BKEMs /**************************************************** * Start: definitions for vendor's phones */ //Definition for 6901 #define PHONE_MODEL_NUMBER_6901 "547" #define RTLITE_MODEL_6901 "CP-6901" #define CCSIP_SIP_6901_USER_AGENT "CP6901" //Definitions for 6911 #define PHONE_MODEL_NUMBER_6911 "548" #define RTLITE_MODEL_6911 "CP-6911" #define CCSIP_SIP_6911_USER_AGENT "CP6911" //Definition for 6921 #define PHONE_MODEL_NUMBER_6921 "495" #define RTLITE_MODEL_6921 "CP-6921" #define CCSIP_SIP_6921_USER_AGENT "CP6921" //Definition for 6941 #define PHONE_MODEL_NUMBER_6941 "496" #define RTLITE_MODEL_6941 "CP-6941" #define CCSIP_SIP_6941_USER_AGENT "CP6941" //Definition for 6945 #define PHONE_MODEL_NUMBER_6945 "564" #define RTLITE_MODEL_6945 "CP-6945" #define CCSIP_SIP_6945_USER_AGENT "CP6945" //Definition for 6961 #define PHONE_MODEL_NUMBER_6961 "497" #define RTLITE_MODEL_6961 "CP-6961" #define CCSIP_SIP_6961_USER_AGENT "CP6961" //Definition for 7937 #define PHONE_MODEL_NUMBER_7937 "431" #define RTLITE_MODEL_7937 "7937G" #define CCSIP_SIP_7937_USER_AGENT "7937G" /** * End of vendor's definition ******************************************************/ //Default set #define PHONE_MODEL_NUMBER "493" #define PHONE_MODEL "CP-9971" #define CCSIP_SIP_USER_AGENT "CP9971" #define MAX_PHONE_LINES 8 #define MAX_REG_LINES 51 #define MAX_CALLS 51 #define MAX_CALLS_PER_LINE 51 /* * MAX_INSTANCES (call_instances) should equal to maximum number of calls * allowed by the phone but MAX_CALLS is defined to be 1 more than the * actual maximum capacity. Therefore define MAX_INSTANCES to MAX_CALLS -1 */ #define MAX_INSTANCES (MAX_CALLS - 1) /* max number of instance ID */ /* MAX_CONFIG_LINES - java side defined fixed number to 36 for non-Buckfast TNP * models so use 36 in call cases. Changing this needs java side change */ #define MAX_CONFIG_LINES 51 #endif
34.930894
80
0.680438
[ "model" ]
3b9cb27a33a05c8606571e16e941ddeec47c580c
3,127
h
C
src/models/expressions/assignitem/PlnAssignWorkValsItem.h
tosyama/palan
ed809a26511366825cd0d7848b4444dcf8f09b1a
[ "MIT" ]
32
2017-10-25T21:02:45.000Z
2022-02-07T05:53:37.000Z
src/models/expressions/assignitem/PlnAssignWorkValsItem.h
tosyama/palan
ed809a26511366825cd0d7848b4444dcf8f09b1a
[ "MIT" ]
39
2018-07-29T00:55:36.000Z
2021-12-22T05:10:48.000Z
src/models/expressions/assignitem/PlnAssignWorkValsItem.h
tosyama/palan
ed809a26511366825cd0d7848b4444dcf8f09b1a
[ "MIT" ]
1
2019-07-10T05:44:50.000Z
2019-07-10T05:44:50.000Z
/// Assignment Item class definition. /// /// Src item returns multiple work values expression. /// The work valuses don't need to be cleared. /// Exist two cases need to free. /// 1) After object was copied. /// 2) Didn't assign any variable. (freed by src_ex) /// /// @file PlnAssignWorkValsItem.h /// @copyright 2018-2019 YAMAGUCHI Toshinobu class PlnAssignWorkValsItem : public PlnAssignItem { PlnExpression* src_ex; struct DstInf { PlnDstItem* item; PlnVariable* save_src_var; PlnExpression* copy_src_ex, *free_ex; }; vector<DstInf> dsts; vector<PlnExpression*> free_exs; public: PlnAssignWorkValsItem(PlnExpression* ex) : src_ex(ex) { auto v = src_ex->values[0]; BOOST_ASSERT(v.type == VL_WORK); } ~PlnAssignWorkValsItem() { for (auto di: dsts) { delete di.item; delete di.save_src_var; delete di.copy_src_ex; delete di.free_ex; } } void addDstEx(PlnExpression* ex, bool need_save) override { BOOST_ASSERT(ex->values.size() == 1); BOOST_ASSERT(src_ex->values.size() > dsts.size()); auto& dstv = ex->values[0]; BOOST_ASSERT(dstv.type == VL_VAR); auto& srcv = src_ex->values[dsts.size()]; if (srcv.getVarType()->mode[IDENTITY_MD] != 'm' && dstv.asgn_type == ASGN_MOVE) { // For the case that return value is readonly ref but move ownership value. // e.g.) struct_tm t <<= localtime(); // ccall localtime->struct_tm@ BOOST_ASSERT(srcv.type == VL_WORK); PlnCompileError err(E_CantUseMoveOwnershipFrom, "source value"); throw err; } dsts.push_back( {PlnDstItem::createDstItem(ex, need_save), NULL, NULL, NULL} ); } int addDataPlace(vector<PlnDataPlace*> &data_places, int start_ind) override { for (auto &di: dsts) { di.item->place = data_places[start_ind]; start_ind++; if (start_ind >= data_places.size()) break; } return start_ind; } void finishS(PlnDataAllocator& da, PlnScopeInfo& si) override { int i=0; for (auto &di: dsts) { auto& v = src_ex->values[i]; if (v.getVarType()->mode[ALLOC_MD] == 'h' && di.item->getAssginType() == ASGN_COPY) { di.save_src_var = PlnVariable::createTempVar(da, v.inf.wk_type, "save src"); di.free_ex = PlnFreer::getFreeEx(di.save_src_var); src_ex->data_places.push_back(di.save_src_var->place); di.copy_src_ex = new PlnExpression(di.save_src_var); di.item->setSrcEx(da, si, di.copy_src_ex); } else { di.item->setSrcEx(da, si, src_ex); } i++; } src_ex->finish(da, si); } void finishD(PlnDataAllocator& da, PlnScopeInfo& si) override { for (auto &di: dsts) { if (di.save_src_var) { // ASGN_COPY da.popSrc(di.save_src_var->place); di.copy_src_ex->finish(da, si); di.item->finish(da, si); di.free_ex->finish(da, si); da.releaseDp(di.save_src_var->place); } else { di.item->finish(da, si); } } } void genS(PlnGenerator& g) override { src_ex->gen(g); } void genD(PlnGenerator& g) override { for (auto di: dsts) { if (di.save_src_var) { // ASGN_COPY g.genLoadDp(di.save_src_var->place); di.item->gen(g); di.free_ex->gen(g); } else { di.item->gen(g); } } } };
25.422764
83
0.662616
[ "object", "vector" ]
3b9dc410ac30a29f839de12ffd27c766b42aa29f
788
h
C
NewRelicVideoCore/NewRelicVideoCore/Model/NREventAttributes.h
newrelic/video-agent-iOS
143cb5e34b3967e7edad83d3a3ea9981220254d6
[ "Apache-2.0" ]
null
null
null
NewRelicVideoCore/NewRelicVideoCore/Model/NREventAttributes.h
newrelic/video-agent-iOS
143cb5e34b3967e7edad83d3a3ea9981220254d6
[ "Apache-2.0" ]
2
2021-04-27T15:04:16.000Z
2021-07-19T18:05:59.000Z
NewRelicVideoCore/NewRelicVideoCore/Model/NREventAttributes.h
newrelic/video-agent-iOS
143cb5e34b3967e7edad83d3a3ea9981220254d6
[ "Apache-2.0" ]
null
null
null
// // NREventAttributes.h // NextVideoAgent // // Created by Andreu Santaren on 11/12/2020. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN /** Event attributes model. */ @interface NREventAttributes : NSObject /** Set attribute for a given action filter. @param key Attribute name. @param value Attribute value. @param regexp Action filter, a regular expression. */ - (void)setAttribute:(NSString *)key value:(id<NSCopying>)value filter:(nullable NSString *)regexp; /** Generate list of attributes for a given action. @param action Action. @param attributes Append attributes. @return Dictionary of attributes. */ - (NSMutableDictionary *)generateAttributes:(NSString *)action append:(nullable NSDictionary *)attributes; @end NS_ASSUME_NONNULL_END
20.736842
106
0.748731
[ "model" ]
3bac0631e290183d21c4c03d8965c6636bb4b017
593
h
C
CrossWars2/ObjFormatLoader.h
GigaNova/CrossWars-2
390bda94a9a446ad35fb1ea0399332f668325875
[ "MIT" ]
null
null
null
CrossWars2/ObjFormatLoader.h
GigaNova/CrossWars-2
390bda94a9a446ad35fb1ea0399332f668325875
[ "MIT" ]
null
null
null
CrossWars2/ObjFormatLoader.h
GigaNova/CrossWars-2
390bda94a9a446ad35fb1ea0399332f668325875
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <GLM/glm.hpp> #include "ModelData.h" #include "Vertex.h" #include <string>- class ObjFormatLoader { public: ObjFormatLoader(); ~ObjFormatLoader(); ModelData* loadModel(std::string t_filename); std::vector<std::string> splitStringDel(std::string const& t_original, char t_separator, std::vector<std::string>& t_result); void vertexElimination(Vertex* t_previous_index, int t_texture_index, int t_normal_index, std::vector<GLuint>* t_indices, std::vector<Vertex*>* t_vertices); void removeUnusedVertices(const std::vector<Vertex*>& vertices); };
29.65
157
0.762226
[ "vector" ]
3bb013705696dd3b68ca4412c5add7f40e7698ac
4,006
h
C
lib/KeyRange.h
jojochuang/eventwave
6cb3a8569f12a9127bf326be3231123428cd754d
[ "BSD-3-Clause" ]
null
null
null
lib/KeyRange.h
jojochuang/eventwave
6cb3a8569f12a9127bf326be3231123428cd754d
[ "BSD-3-Clause" ]
null
null
null
lib/KeyRange.h
jojochuang/eventwave
6cb3a8569f12a9127bf326be3231123428cd754d
[ "BSD-3-Clause" ]
null
null
null
/* * KeyRange.h : part of the Mace toolkit for building distributed systems * * Copyright (c) 2011, Charles Killian, Dejan Kostic, Ryan Braud, James W. Anderson, John Fisher-Ogden, Calvin Hubble, Duy Nguyen, Justin Burke, David Oppenheimer, Amin Vahdat, Adolfo Rodriguez, Sooraj Bhat * 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 names of the contributors, nor their associated universities * or organizations 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. * * ----END-OF-LEGAL-STUFF---- */ #ifndef KEY_RANGE_H #define KEY_RANGE_H /** * \file KeyRange.h * \brief defines the mace::KeyRange class */ #include "mpair.h" #include "MaceKey.h" namespace mace { /// A pair of MaceKey which represent an inclusive start, exclusive end circulur key range for hash addresses. class KeyRange : public mace::pair<MaceKey, MaceKey> { public: KeyRange() : mace::pair<MaceKey, MaceKey>() { } KeyRange(const KeyRange& copy) : mace::pair<MaceKey, MaceKey>(copy) { } KeyRange(const MaceKey& f, const MaceKey& s) : mace::pair<MaceKey, MaceKey>(f, s) { } /// returns true if the range includes the key \c k bool containsKey(const MaceKey& k) const { return KeyRange::containsKey(k, first, second); } // containsKey /// determines if id is between start and end /** * If either address is null, the return is false. If the address families don't match, an exception is thrown. * \f$ start = end \Rightarrow id \in range \f$ * @param id the key to test * @param start inclusive start to the key range * @param end exclusive end to the key range */ inline static bool containsKey(const MaceKey& id, const MaceKey& start, const MaceKey& end) { if (id.isNullAddress() || start.isNullAddress() || end.isNullAddress()) { return false; } if (id.addressFamily() != start.addressFamily() || start.addressFamily() != end.addressFamily()) { throw(InvalidMaceKeyException("Cannot perform KeyRange::containsKey on keys of different families")); } if (start == end) { return true; } else if (start < end) { return ((start <= id) && (id < end)); } else { return ((start <= id) || (id < end)); } } void print(std::ostream& out) const { out << "KeyRange["<<first<<","<<second<<")"; } void printState(std::ostream& out) const { out << "KeyRange["; mace::printState(out, &first, first); out << ","; mace::printState(out, &second, second); out <<")"; } static const KeyRange null; ///< convenience object for the null KeyRange }; // KeyRange } // namespace mace #endif // KEY_RANGE_H
40.06
206
0.696955
[ "object" ]
3bb37d9198bc3bbaef83999edaf30234fb31c058
28,445
h
C
MasteryAssignments/Turn in Folder M1/renderer.h
Neteroh/FinalLevelRenderer
6a60475893242fb52d0b0786b047b2a5001fa90e
[ "MIT" ]
null
null
null
MasteryAssignments/Turn in Folder M1/renderer.h
Neteroh/FinalLevelRenderer
6a60475893242fb52d0b0786b047b2a5001fa90e
[ "MIT" ]
null
null
null
MasteryAssignments/Turn in Folder M1/renderer.h
Neteroh/FinalLevelRenderer
6a60475893242fb52d0b0786b047b2a5001fa90e
[ "MIT" ]
null
null
null
// minimalistic code to draw a single triangle, this is not part of the API. #include "shaderc/shaderc.h" // needed for compiling shaders at runtime #include <vector> #include <cstdlib> #include <ctime> #ifdef _WIN32 // must use MT platform DLL libraries on windows #pragma comment(lib, "shaderc_combined.lib") #endif // TODO: Part 2b // Simple Vertex Shader const char* vertexShaderSource = R"( // an ultra simple hlsl vertex shader float4 main(float2 inputVertex : POSITION) : SV_POSITION { return float4(inputVertex, 0, 1); } )"; // Simple Pixel Shader const char* pixelShaderSource = R"( // an ultra simple hlsl pixel shader float4 main() : SV_TARGET { return float4(1.0f ,1.0f, 1.0f, 0); // TODO: Part 1a } )"; const char* vertexShaderSource2 = R"( // an ultra simple hlsl vertex shader struct vecColor { float2 pos : POSITION; float4 clr : COLOR; }; struct vecColor_out { float4 pos : SV_POSITION; float4 clr : COLOR; }; vecColor_out main(vecColor inputVertex : POSITION) : SV_POSITION { vecColor_out output; output.pos = float4(inputVertex.pos, 0, 1); output.clr = inputVertex.clr; /*return vecColor_out(inputVertex, 0, 1);*/ return output; } )"; // Simple Pixel Shader const char* pixelShaderSource2 = R"( // an ultra simple hlsl pixel shader struct vecColor_out { float4 pos : SV_POSITION; float4 clr : COLOR; }; float4 main(vecColor_out output) : SV_TARGET { return output.clr; // TODO: Part 1a } )"; struct vecPosition { float x, y, z, w; }; struct vecColor { float pos[2]; float color[4]; }; // TODO: Part 4b // TODO: Part 4c (in new shader) // TODO: Part 4d (in new shader) // TODO: Part 4e // Creation, Rendering & Cleanup class Renderer { // proxy handles GW::SYSTEM::GWindow win; GW::GRAPHICS::GVulkanSurface vlk; GW::CORE::GEventReceiver shutdown; // what we need at a minimum to draw a triangle VkDevice device = nullptr; VkBuffer vertexHandle = nullptr; VkDeviceMemory vertexData = nullptr; VkBuffer vertexHandle2 = nullptr; VkDeviceMemory vertexData2 = nullptr; // TODO: Part 3a VkShaderModule vertexShader = nullptr; VkShaderModule pixelShader = nullptr; VkShaderModule vertexShader2 = nullptr; VkShaderModule pixelShader2 = nullptr; // TODO: Part 4b // pipeline settings for drawing (also required) VkPipeline pipeline = nullptr; VkPipelineLayout pipelineLayout = nullptr; VkPipeline pipeline2 = nullptr; public: // TODO: Part 4a Renderer(GW::SYSTEM::GWindow _win, GW::GRAPHICS::GVulkanSurface _vlk) { win = _win; vlk = _vlk; unsigned int width, height; win.GetClientWidth(width); win.GetClientHeight(height); /***************** GEOMETRY INTIALIZATION ******************/ // Grab the device & physical device so we can allocate some stuff VkPhysicalDevice physicalDevice = nullptr; vlk.GetDevice((void**)&device); vlk.GetPhysicalDevice((void**)&physicalDevice); // TODO: Part 2b // Create Vertex Buffer srand(static_cast <unsigned> (time(0))); /*std::vector<vec> stars;*/ vecPosition stars[20000]; srand(static_cast <unsigned> (time(0))); for (size_t i = 0; i < 20000; i++) { float Rx = -1 + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (1 - -1))); float Ry = -1 + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (1 - -1))); stars[i].x = Rx; stars[i].y = Ry; } float R = rand() / static_cast<float>(RAND_MAX); float G = rand() / static_cast<float>(RAND_MAX); float B = rand() / static_cast<float>(RAND_MAX); float A = rand() / static_cast<float>(RAND_MAX); vecColor star2D[22] = { star2D[0].pos[0] = 0.0f, star2D[0].pos[1] = 0.9f, star2D[0].color[0] = rand() / static_cast<float>(RAND_MAX), star2D[0].color[1] = rand() / static_cast<float>(RAND_MAX),star2D[0].color[2] = rand() / static_cast<float>(RAND_MAX),star2D[0].color[3] = rand() / static_cast<float>(RAND_MAX), star2D[1].pos[0] = 0.25f, star2D[1].pos[1] = 0.25f, star2D[1].color[0] = rand() / static_cast<float>(RAND_MAX), star2D[1].color[1] = rand() / static_cast<float>(RAND_MAX),star2D[1].color[2] = rand() / static_cast<float>(RAND_MAX),star2D[1].color[3] = rand() / static_cast<float>(RAND_MAX), star2D[2].pos[0] = 0.95f, star2D[2].pos[1] = 0.125f, star2D[2].color[0] = rand() / static_cast<float>(RAND_MAX), star2D[2].color[1] = rand() / static_cast<float>(RAND_MAX),star2D[2].color[2] = rand() / static_cast<float>(RAND_MAX),star2D[2].color[3] = rand() / static_cast<float>(RAND_MAX), star2D[3].pos[0] = 0.35f, star2D[3].pos[1] = -0.15, star2D[3].color[0] = rand() / static_cast<float>(RAND_MAX), star2D[3].color[1] = rand() / static_cast<float>(RAND_MAX),star2D[3].color[2] = rand() / static_cast<float>(RAND_MAX),star2D[3].color[3] = rand() / static_cast<float>(RAND_MAX), star2D[4].pos[0] = 0.5f, star2D[4].pos[1] = -0.9f, star2D[4].color[0] = rand() / static_cast<float>(RAND_MAX), star2D[4].color[1] = rand() / static_cast<float>(RAND_MAX),star2D[4].color[2] = rand() / static_cast<float>(RAND_MAX),star2D[4].color[3] = rand() / static_cast<float>(RAND_MAX), star2D[5].pos[0] = 0.0f, star2D[5].pos[1] = -0.3f, star2D[5].color[0] = rand() / static_cast<float>(RAND_MAX), star2D[5].color[1] = rand() / static_cast<float>(RAND_MAX),star2D[5].color[2] = rand() / static_cast<float>(RAND_MAX),star2D[5].color[3] = rand() / static_cast<float>(RAND_MAX), star2D[6].pos[0] = -0.5f, star2D[6].pos[1] = -0.9f, star2D[6].color[0] = rand() / static_cast<float>(RAND_MAX), star2D[6].color[1] = rand() / static_cast<float>(RAND_MAX),star2D[6].color[2] = rand() / static_cast<float>(RAND_MAX),star2D[6].color[3] = rand() / static_cast<float>(RAND_MAX), star2D[7].pos[0] = -0.35f, star2D[7].pos[1] = -0.15, star2D[7].color[0] = rand() / static_cast<float>(RAND_MAX), star2D[7].color[1] = rand() / static_cast<float>(RAND_MAX),star2D[7].color[2] = rand() / static_cast<float>(RAND_MAX),star2D[7].color[3] = rand() / static_cast<float>(RAND_MAX), star2D[8].pos[0] = -0.95f, star2D[8].pos[1] = 0.125f, star2D[8].color[0] = rand() / static_cast<float>(RAND_MAX), star2D[8].color[1] = rand() / static_cast<float>(RAND_MAX),star2D[8].color[2] = rand() / static_cast<float>(RAND_MAX),star2D[8].color[3] = rand() / static_cast<float>(RAND_MAX), star2D[9].pos[0] = -0.25f, star2D[9].pos[1] = 0.25f, star2D[9].color[0] = rand() / static_cast<float>(RAND_MAX), star2D[9].color[1] = rand() / static_cast<float>(RAND_MAX),star2D[9].color[2] = rand() / static_cast<float>(RAND_MAX),star2D[9].color[3] = rand() / static_cast<float>(RAND_MAX), star2D[10].pos[0] = 0.0f, star2D[10].pos[1] = 0.9f, star2D[10].color[0] = rand() / static_cast<float>(RAND_MAX), star2D[10].color[1] = rand() / static_cast<float>(RAND_MAX),star2D[10].color[2] = rand() / static_cast<float>(RAND_MAX),star2D[10].color[3] = rand() / static_cast<float>(RAND_MAX) }; // Transfer triangle data to the vertex buffer. (staging would be prefered here) GvkHelper::create_buffer(physicalDevice, device, sizeof(star2D), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &vertexHandle, &vertexData); GvkHelper::write_to_buffer(device, vertexData, star2D, sizeof(star2D)); // TODO: Part 3a GvkHelper::create_buffer(physicalDevice, device, sizeof(stars), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &vertexHandle2, &vertexData2); GvkHelper::write_to_buffer(device, vertexData2, stars, sizeof(stars)); // TODO: Part 4a /***************** SHADER INTIALIZATION ******************/ // Intialize runtime shader compiler HLSL -> SPIRV shaderc_compiler_t compiler = shaderc_compiler_initialize(); shaderc_compile_options_t options = shaderc_compile_options_initialize(); shaderc_compile_options_set_source_language(options, shaderc_source_language_hlsl); shaderc_compile_options_set_invert_y(options, true); #ifndef NDEBUG shaderc_compile_options_set_generate_debug_info(options); #endif // Create Vertex Shader shaderc_compilation_result_t result = shaderc_compile_into_spv( // compile compiler, vertexShaderSource, strlen(vertexShaderSource), shaderc_vertex_shader, "main.vert", "main", options); if (shaderc_result_get_compilation_status(result) != shaderc_compilation_status_success) // errors? std::cout << "Vertex Shader Errors: " << shaderc_result_get_error_message(result) << std::endl; GvkHelper::create_shader_module(device, shaderc_result_get_length(result), // load into Vulkan (char*)shaderc_result_get_bytes(result), &vertexShader); shaderc_result_release(result); // done // Create Pixel Shader result = shaderc_compile_into_spv( // compile compiler, pixelShaderSource, strlen(pixelShaderSource), shaderc_fragment_shader, "main.frag", "main", options); if (shaderc_result_get_compilation_status(result) != shaderc_compilation_status_success) // errors? std::cout << "Pixel Shader Errors: " << shaderc_result_get_error_message(result) << std::endl; GvkHelper::create_shader_module(device, shaderc_result_get_length(result), // load into Vulkan (char*)shaderc_result_get_bytes(result), &pixelShader); shaderc_result_release(result); // done // TODO: Part 4b // Create Vertex Shader shaderc_compilation_result_t result2 = shaderc_compile_into_spv( // compile compiler, vertexShaderSource2, strlen(vertexShaderSource2), shaderc_vertex_shader, "main.vert", "main", options); if (shaderc_result_get_compilation_status(result2) != shaderc_compilation_status_success) // errors? std::cout << "Vertex Shader Errors: " << shaderc_result_get_error_message(result2) << std::endl; GvkHelper::create_shader_module(device, shaderc_result_get_length(result2), // load into Vulkan (char*)shaderc_result_get_bytes(result2), &vertexShader2); shaderc_result_release(result2); // done // Create Pixel Shader result2 = shaderc_compile_into_spv( // compile compiler, pixelShaderSource2, strlen(pixelShaderSource2), shaderc_fragment_shader, "main.frag", "main", options); if (shaderc_result_get_compilation_status(result2) != shaderc_compilation_status_success) // errors? std::cout << "Pixel Shader Errors: " << shaderc_result_get_error_message(result2) << std::endl; GvkHelper::create_shader_module(device, shaderc_result_get_length(result2), // load into Vulkan (char*)shaderc_result_get_bytes(result2), &pixelShader2); shaderc_result_release(result2); // done // Free runtime shader compiler resources shaderc_compile_options_release(options); shaderc_compiler_release(compiler); /***************** PIPELINE INTIALIZATION ******************/ // Create Pipeline & Layout (Thanks Tiny!) VkRenderPass renderPass; vlk.GetRenderPass((void**)&renderPass); VkPipelineShaderStageCreateInfo stage_create_info[2] = {}; // Create Stage Info for Vertex Shader stage_create_info[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; stage_create_info[0].stage = VK_SHADER_STAGE_VERTEX_BIT; stage_create_info[0].module = vertexShader2; stage_create_info[0].pName = "main"; // Create Stage Info for Fragment Shader stage_create_info[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; stage_create_info[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; stage_create_info[1].module = pixelShader2; stage_create_info[1].pName = "main"; // Assembly State VkPipelineInputAssemblyStateCreateInfo assembly_create_info = {}; assembly_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; assembly_create_info.topology = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP; assembly_create_info.primitiveRestartEnable = false; // Vertex Input State VkVertexInputBindingDescription vertex_binding_description = {}; vertex_binding_description.binding = 0; vertex_binding_description.stride = sizeof(vecColor); vertex_binding_description.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; VkVertexInputAttributeDescription vertex_attribute_description[2] = { { 0, 0, VK_FORMAT_R32G32_SFLOAT, 0 },{1,0, VK_FORMAT_R32G32B32A32_SFLOAT, offsetof(vecColor,color)} //uv, normal, etc.... }; VkPipelineVertexInputStateCreateInfo input_vertex_info = {}; input_vertex_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; input_vertex_info.vertexBindingDescriptionCount = 1; input_vertex_info.pVertexBindingDescriptions = &vertex_binding_description; input_vertex_info.vertexAttributeDescriptionCount = 2; input_vertex_info.pVertexAttributeDescriptions = vertex_attribute_description; // Viewport State (we still need to set this up even though we will overwrite the values) VkViewport viewport = { 0, 0, static_cast<float>(width), static_cast<float>(height), 0, 1 }; VkRect2D scissor = { {0, 0}, {width, height} }; VkPipelineViewportStateCreateInfo viewport_create_info = {}; viewport_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; viewport_create_info.viewportCount = 1; viewport_create_info.pViewports = &viewport; viewport_create_info.scissorCount = 1; viewport_create_info.pScissors = &scissor; // Rasterizer State VkPipelineRasterizationStateCreateInfo rasterization_create_info = {}; rasterization_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; rasterization_create_info.rasterizerDiscardEnable = VK_FALSE; rasterization_create_info.polygonMode = VK_POLYGON_MODE_LINE; // TODO: Part 2a rasterization_create_info.lineWidth = 1.0f; rasterization_create_info.cullMode = VK_CULL_MODE_BACK_BIT; rasterization_create_info.frontFace = VK_FRONT_FACE_CLOCKWISE; rasterization_create_info.depthClampEnable = VK_FALSE; rasterization_create_info.depthBiasEnable = VK_FALSE; rasterization_create_info.depthBiasClamp = 0.0f; rasterization_create_info.depthBiasConstantFactor = 0.0f; rasterization_create_info.depthBiasSlopeFactor = 0.0f; // Multisampling State VkPipelineMultisampleStateCreateInfo multisample_create_info = {}; multisample_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; multisample_create_info.sampleShadingEnable = VK_FALSE; multisample_create_info.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; multisample_create_info.minSampleShading = 1.0f; multisample_create_info.pSampleMask = VK_NULL_HANDLE; multisample_create_info.alphaToCoverageEnable = VK_FALSE; multisample_create_info.alphaToOneEnable = VK_FALSE; // Depth-Stencil State VkPipelineDepthStencilStateCreateInfo depth_stencil_create_info = {}; depth_stencil_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; depth_stencil_create_info.depthTestEnable = VK_FALSE; depth_stencil_create_info.depthWriteEnable = VK_FALSE; depth_stencil_create_info.depthCompareOp = VK_COMPARE_OP_LESS; depth_stencil_create_info.depthBoundsTestEnable = VK_FALSE; depth_stencil_create_info.minDepthBounds = 0.0f; depth_stencil_create_info.maxDepthBounds = 1.0f; depth_stencil_create_info.stencilTestEnable = VK_FALSE; // Color Blending Attachment & State VkPipelineColorBlendAttachmentState color_blend_attachment_state = {}; color_blend_attachment_state.colorWriteMask = 0xF; color_blend_attachment_state.blendEnable = VK_FALSE; color_blend_attachment_state.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_COLOR; color_blend_attachment_state.dstColorBlendFactor = VK_BLEND_FACTOR_DST_COLOR; color_blend_attachment_state.colorBlendOp = VK_BLEND_OP_ADD; color_blend_attachment_state.srcAlphaBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; color_blend_attachment_state.dstAlphaBlendFactor = VK_BLEND_FACTOR_DST_ALPHA; color_blend_attachment_state.alphaBlendOp = VK_BLEND_OP_ADD; VkPipelineColorBlendStateCreateInfo color_blend_create_info = {}; color_blend_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; color_blend_create_info.logicOpEnable = VK_FALSE; color_blend_create_info.logicOp = VK_LOGIC_OP_COPY; color_blend_create_info.attachmentCount = 1; color_blend_create_info.pAttachments = &color_blend_attachment_state; color_blend_create_info.blendConstants[0] = 0.0f; color_blend_create_info.blendConstants[1] = 0.0f; color_blend_create_info.blendConstants[2] = 0.0f; color_blend_create_info.blendConstants[3] = 0.0f; // Dynamic State VkDynamicState dynamic_state[2] = { // By setting these we do not need to re-create the pipeline on Resize VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; VkPipelineDynamicStateCreateInfo dynamic_create_info = {}; dynamic_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; dynamic_create_info.dynamicStateCount = 2; dynamic_create_info.pDynamicStates = dynamic_state; // Descriptor pipeline layout VkPipelineLayoutCreateInfo pipeline_layout_create_info = {}; pipeline_layout_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipeline_layout_create_info.setLayoutCount = 0; pipeline_layout_create_info.pSetLayouts = VK_NULL_HANDLE; pipeline_layout_create_info.pushConstantRangeCount = 0; pipeline_layout_create_info.pPushConstantRanges = nullptr; vkCreatePipelineLayout(device, &pipeline_layout_create_info, nullptr, &pipelineLayout); // Pipeline State... (FINALLY) VkGraphicsPipelineCreateInfo pipeline_create_info = {}; pipeline_create_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; pipeline_create_info.stageCount = 2; pipeline_create_info.pStages = stage_create_info; pipeline_create_info.pInputAssemblyState = &assembly_create_info; pipeline_create_info.pVertexInputState = &input_vertex_info; pipeline_create_info.pViewportState = &viewport_create_info; pipeline_create_info.pRasterizationState = &rasterization_create_info; pipeline_create_info.pMultisampleState = &multisample_create_info; pipeline_create_info.pDepthStencilState = &depth_stencil_create_info; pipeline_create_info.pColorBlendState = &color_blend_create_info; pipeline_create_info.pDynamicState = &dynamic_create_info; pipeline_create_info.layout = pipelineLayout; pipeline_create_info.renderPass = renderPass; pipeline_create_info.subpass = 0; pipeline_create_info.basePipelineHandle = VK_NULL_HANDLE; vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipeline_create_info, nullptr, &pipeline); // TODO: Part 3b /***************** PIPELINE INTIALIZATION ******************/ // Create Pipeline & Layout (Thanks Tiny!) VkRenderPass renderPass2; vlk.GetRenderPass((void**)&renderPass2); VkPipelineShaderStageCreateInfo stage_create_info2[2] = {}; // Create Stage Info for Vertex Shader stage_create_info2[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; stage_create_info2[0].stage = VK_SHADER_STAGE_VERTEX_BIT; stage_create_info2[0].module = vertexShader; stage_create_info2[0].pName = "main"; // Create Stage Info for Fragment Shader stage_create_info2[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; stage_create_info2[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; stage_create_info2[1].module = pixelShader; stage_create_info2[1].pName = "main"; // Assembly State VkPipelineInputAssemblyStateCreateInfo assembly_create_info2 = {}; assembly_create_info2.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; assembly_create_info2.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; assembly_create_info2.primitiveRestartEnable = false; // Vertex Input State VkVertexInputBindingDescription vertex_binding_description2 = {}; vertex_binding_description2.binding = 0; vertex_binding_description2.stride = sizeof(float) * 2; vertex_binding_description2.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; VkVertexInputAttributeDescription vertex_attribute_description2[1] = { { 0, 0, VK_FORMAT_R32G32_SFLOAT, 0 } //uv, normal, etc.... }; VkPipelineVertexInputStateCreateInfo input_vertex_info2 = {}; input_vertex_info2.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; input_vertex_info2.vertexBindingDescriptionCount = 1; input_vertex_info2.pVertexBindingDescriptions = &vertex_binding_description2; input_vertex_info2.vertexAttributeDescriptionCount = 1; input_vertex_info2.pVertexAttributeDescriptions = vertex_attribute_description2; // Viewport State (we still need to set this up even though we will overwrite the values) VkViewport viewport2 = { 0, 0, static_cast<float>(width), static_cast<float>(height), 0, 1 }; VkRect2D scissor2 = { {0, 0}, {width, height} }; VkPipelineViewportStateCreateInfo viewport_create_info2 = {}; viewport_create_info2.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; viewport_create_info2.viewportCount = 1; viewport_create_info2.pViewports = &viewport2; viewport_create_info2.scissorCount = 1; viewport_create_info2.pScissors = &scissor2; // Rasterizer State VkPipelineRasterizationStateCreateInfo rasterization_create_info2 = {}; rasterization_create_info2.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; rasterization_create_info2.rasterizerDiscardEnable = VK_FALSE; rasterization_create_info2.polygonMode = VK_POLYGON_MODE_POINT; // TODO: Part 2a rasterization_create_info2.lineWidth = 1.0f; rasterization_create_info2.cullMode = VK_CULL_MODE_BACK_BIT; rasterization_create_info2.frontFace = VK_FRONT_FACE_CLOCKWISE; rasterization_create_info2.depthClampEnable = VK_FALSE; rasterization_create_info2.depthBiasEnable = VK_FALSE; rasterization_create_info2.depthBiasClamp = 0.0f; rasterization_create_info2.depthBiasConstantFactor = 0.0f; rasterization_create_info2.depthBiasSlopeFactor = 0.0f; // Multisampling State VkPipelineMultisampleStateCreateInfo multisample_create_info2 = {}; multisample_create_info2.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; multisample_create_info2.sampleShadingEnable = VK_FALSE; multisample_create_info2.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; multisample_create_info2.minSampleShading = 1.0f; multisample_create_info2.pSampleMask = VK_NULL_HANDLE; multisample_create_info2.alphaToCoverageEnable = VK_FALSE; multisample_create_info2.alphaToOneEnable = VK_FALSE; // Depth-Stencil State VkPipelineDepthStencilStateCreateInfo depth_stencil_create_info2 = {}; depth_stencil_create_info2.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; depth_stencil_create_info2.depthTestEnable = VK_FALSE; depth_stencil_create_info2.depthWriteEnable = VK_FALSE; depth_stencil_create_info2.depthCompareOp = VK_COMPARE_OP_LESS; depth_stencil_create_info2.depthBoundsTestEnable = VK_FALSE; depth_stencil_create_info2.minDepthBounds = 0.0f; depth_stencil_create_info2.maxDepthBounds = 1.0f; depth_stencil_create_info2.stencilTestEnable = VK_FALSE; // Color Blending Attachment & State VkPipelineColorBlendAttachmentState color_blend_attachment_state2 = {}; color_blend_attachment_state2.colorWriteMask = 0xF; color_blend_attachment_state2.blendEnable = VK_FALSE; color_blend_attachment_state2.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_COLOR; color_blend_attachment_state2.dstColorBlendFactor = VK_BLEND_FACTOR_DST_COLOR; color_blend_attachment_state2.colorBlendOp = VK_BLEND_OP_ADD; color_blend_attachment_state2.srcAlphaBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; color_blend_attachment_state2.dstAlphaBlendFactor = VK_BLEND_FACTOR_DST_ALPHA; color_blend_attachment_state2.alphaBlendOp = VK_BLEND_OP_ADD; VkPipelineColorBlendStateCreateInfo color_blend_create_info2 = {}; color_blend_create_info2.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; color_blend_create_info2.logicOpEnable = VK_FALSE; color_blend_create_info2.logicOp = VK_LOGIC_OP_COPY; color_blend_create_info2.attachmentCount = 1; color_blend_create_info2.pAttachments = &color_blend_attachment_state2; color_blend_create_info2.blendConstants[0] = 0.0f; color_blend_create_info2.blendConstants[1] = 0.0f; color_blend_create_info2.blendConstants[2] = 0.0f; color_blend_create_info2.blendConstants[3] = 0.0f; // Dynamic State VkDynamicState dynamic_state2[2] = { // By setting these we do not need to re-create the pipeline on Resize VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; VkPipelineDynamicStateCreateInfo dynamic_create_info2 = {}; dynamic_create_info2.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; dynamic_create_info2.dynamicStateCount = 2; dynamic_create_info2.pDynamicStates = dynamic_state2; // Descriptor pipeline layout VkPipelineLayoutCreateInfo pipeline_layout_create_info2 = {}; pipeline_layout_create_info2.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipeline_layout_create_info2.setLayoutCount = 0; pipeline_layout_create_info2.pSetLayouts = VK_NULL_HANDLE; pipeline_layout_create_info2.pushConstantRangeCount = 0; pipeline_layout_create_info2.pPushConstantRanges = nullptr; vkCreatePipelineLayout(device, &pipeline_layout_create_info2, nullptr, &pipelineLayout); // Pipeline State... (FINALLY) VkGraphicsPipelineCreateInfo pipeline_create_info2 = {}; pipeline_create_info2.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; pipeline_create_info2.stageCount = 2; pipeline_create_info2.pStages = stage_create_info2; pipeline_create_info2.pInputAssemblyState = &assembly_create_info2; pipeline_create_info2.pVertexInputState = &input_vertex_info2; pipeline_create_info2.pViewportState = &viewport_create_info2; pipeline_create_info2.pRasterizationState = &rasterization_create_info2; pipeline_create_info2.pMultisampleState = &multisample_create_info2; pipeline_create_info2.pDepthStencilState = &depth_stencil_create_info2; pipeline_create_info2.pColorBlendState = &color_blend_create_info2; pipeline_create_info2.pDynamicState = &dynamic_create_info2; pipeline_create_info2.layout = pipelineLayout; pipeline_create_info2.renderPass = renderPass2; pipeline_create_info2.subpass = 0; pipeline_create_info2.basePipelineHandle = VK_NULL_HANDLE; vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipeline_create_info2, nullptr, &pipeline2); // TODO: Part 4f /***************** CLEANUP / SHUTDOWN ******************/ // GVulkanSurface will inform us when to release any allocated resources shutdown.Create(vlk, [&]() { if (+shutdown.Find(GW::GRAPHICS::GVulkanSurface::Events::RELEASE_RESOURCES, true)) { CleanUp(); // unlike D3D we must be careful about destroy timing } }); } void Render() { // grab the current Vulkan commandBuffer unsigned int currentBuffer; vlk.GetSwapchainCurrentImage(currentBuffer); VkCommandBuffer commandBuffer; vlk.GetCommandBuffer(currentBuffer, (void**)&commandBuffer); // what is the current client area dimensions? unsigned int width, height; win.GetClientWidth(width); win.GetClientHeight(height); // setup the pipeline's dynamic settings VkViewport viewport = { 0, 0, static_cast<float>(width), static_cast<float>(height), 0, 1 }; VkRect2D scissor = { {0, 0}, {width, height} }; vkCmdSetViewport(commandBuffer, 0, 1, &viewport); vkCmdSetScissor(commandBuffer, 0, 1, &scissor); vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); // now we can draw VkDeviceSize offsets[] = { 0 }; vkCmdBindVertexBuffers(commandBuffer, 0, 1, &vertexHandle, offsets); vkCmdDraw(commandBuffer, 11, 1, 0, 0); // TODO: Part 2b // TODO: Part 3b vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline2); vkCmdBindVertexBuffers(commandBuffer, 0, 1, &vertexHandle2, offsets); vkCmdDraw(commandBuffer, 20000, 1, 0, 0); } private: void CleanUp() { // wait till everything has completed vkDeviceWaitIdle(device); // Release allocated buffers, shaders & pipeline vkDestroyBuffer(device, vertexHandle, nullptr); vkFreeMemory(device, vertexData, nullptr); vkDestroyBuffer(device, vertexHandle2, nullptr); vkFreeMemory(device, vertexData2, nullptr); // TODO: Part 3a vkDestroyShaderModule(device, vertexShader, nullptr); vkDestroyShaderModule(device, pixelShader, nullptr); vkDestroyShaderModule(device, vertexShader2, nullptr); vkDestroyShaderModule(device, pixelShader2, nullptr); // TODO: Part 4b vkDestroyPipelineLayout(device, pipelineLayout, nullptr); vkDestroyPipeline(device, pipeline, nullptr); vkDestroyPipeline(device, pipeline2, nullptr); } };
51.068223
297
0.779926
[ "geometry", "render", "vector" ]
3bb4264f393e80e614e14fd48e15a6f939a585ba
5,872
h
C
sgf/3.0/headers/ExternalLibs/smf/Gamecore/geometry/SMF_2DCircleSegment.h
rasputtim/SGPacMan
b0fd33f0951a42625a391383b4d1bd378391493c
[ "BSD-2-Clause" ]
null
null
null
sgf/3.0/headers/ExternalLibs/smf/Gamecore/geometry/SMF_2DCircleSegment.h
rasputtim/SGPacMan
b0fd33f0951a42625a391383b4d1bd378391493c
[ "BSD-2-Clause" ]
null
null
null
sgf/3.0/headers/ExternalLibs/smf/Gamecore/geometry/SMF_2DCircleSegment.h
rasputtim/SGPacMan
b0fd33f0951a42625a391383b4d1bd378391493c
[ "BSD-2-Clause" ]
null
null
null
#ifndef __SMF_CIRCLE_SEGMENT_2D_ #define __SMF_CIRCLE_SEGMENT_2D_ #include "../SMF_Config.h" #include "../math/all.h" #include "SMF_2DPoint.h" #include "SMF_2DCircleSector.h" #include "SMF_GeoDefs.h" namespace SMF { using namespace MATH; using namespace Util; namespace GEO{ /** * \class CCircleSegment2D * * \ingroup SMF_Geometric * \image html pics/circle.png * \if pt_br * \brief Um Setor Circular em duas dimensões num espaço cartesiano * \note Esta classe representa tanto um setor sólido, quanto somente a borda do setor * \elseif us_en * \brief A two-dimensional segment in 2D space. \note This class represents both a hollow segment (only edge) and a solid segment. * * \endif * * \author (last to touch it) $Autor: Salvathor $ * * \version 1.0 $Revision: 1.0 $ * * Contact: carygrant@ig.com.br * */ class SMF_API CCircleSegment2D: public CCircle2D { public: /// The begin of this segment from left to right, or CW. CPoint2D startPoint; /// The end of this segment from left to right, or CW. CPoint2D endPoint; /** \brief sagitta at the central point of the arc \n \image html pics/sagitta.png \n Calculating the sagitta \n \f$ s = r - \sqrt[2]{r^2 - l^2} \f$ \n s = sagitta \n r = radius \n l = half length of the chord (span) connecting the two ends of the segment **/ float _sag; /** \brief The default constructor does not initialize any members of this class. This means that the values of the members startPoint, endPoint and supCircle are all undefined after creating a new Arc using this default constructor. Remember to assign to them before use. \see supCircle, endPoint, startPoint. */ CCircleSegment2D(); /** \brief Constructs a new segment by explicitly specifying the member variables. \param start The start point of the segment. \param end The endPoint of the segment \param circ The supporting segment of the segment. \warning the start and endPoint must be on the circle edge */ CCircleSegment2D(CPoint2D &start, CPoint2D &end, CCircle2D &circ); /** \brief Constructs a new segment by explicitly specifying the member variables. \param start The start point of the segment. \param end The endPoint of the segment \param radius of the circle. */ CCircleSegment2D(CPoint2D &start, CPoint2D &end, float radius, int orientation = RightHandSide); /** \brief set the circleSegment // This method must be called by all constructors (except the default // constructor) and all methods that change the coefficients. */ void set(CPoint2D &start, CPoint2D &end, CCircle2D &circ); /** \brief get the sagitta at specified distance from origin (ponto méio entre o start point e o end point do segmento) \note s = r - (dist+square(r^2-l^2)) \note distance between [0,_sag]. if dist > _sag will return _sag. if dist < 0 will return 0; where: r= radius of the suporting circle l= half lenght of the segment (startPoint - endPoint) **/ float sagitta(float dist) const; /** \brief return the area of the segment The formula to find the area of the segment is given below. It can also be found by calculating the area of the whole pie-shaped sector and subtracting the area of the isosceles triangle △ACB. A=R^2/2 *(((π /180)-C)-sin C) where: C is the central angle in DEGREES R is the radius of the circle of which the segment is a part. π is Pi, approximately 3.142 sin is the trigonometry Sine function. See Trigonometry Overview Area of a Circular Segment given its height Definition: The number of square units it takes to fill a segment of a circle Try this Drag one of the orange dot that defines an endpoint of the segment. Adjust the segment height. Note the number of square units it takes to fill it and the calculation. If you know the radius of the circle and the height of the segment, you can find the segment area from the formula below. The result will vary from zero when the height is zero, to the full area of the circle when the height is equal to the diameter. A= r* Arccos((r-h)/r)-(r-h)*sqrt(2rh-h^2) r is the radius of the circle of which the segment is a part. h is the height of the segment (sagitta). **/ float area()const; /** \brief Calculating Height of an Arc at Any Point \note h = s + sqrt(r^2-x^2)-r where: h = the height of the arc; s = the sagitta of the arc; r = the radius of the arc; x = the horizontal offset from the center to the point where you want the height; **/ float height(CPoint2D &point)const; /** \brief Returns the start point at the edge of this segment. */ SMF_INLINE CPoint2D getStartPoint() const{return startPoint;}; /** \brief Returns the end point at the edge of this segment. */ SMF_INLINE CPoint2D getEndPoint() const{return endPoint;}; /** \brief Returns the supporting segment of this segment. */ CCircle2D getSupCircle() const; /** \return the central angle of the arc in radians */ float centralAngle()const; /** \return the lenght of the arc \param angle in radians \note ArcLen= RC where: C is the central angle of the arc in radians. R is the radius of the arc */ float getLenght()const; /** \brief Returns a human-readable representation of this segment. Most useful for debugging purposes. The returned string specifies the center position, normal direction and the radius of this segment. */ std::string toString() const; #ifdef MATH_QT_INTEROP operator QString() const { return toString(); } QString toString() const { return QString::fromStdString(toString()); } #endif }; //CCircleSegment2D operator *(const CMat2D &transform, const CCircleSegment2D &segment); #ifdef MATH_QT_INTEROP Q_DECLARE_METATYPE(CCircleSegment2D) Q_DECLARE_METATYPE(CCircleSegment2D*) #endif std::ostream &operator <<(std::ostream &o, const CCircleSegment2D &segment); } //end GEO } //end SMF #endif // __SMF_CIRCLE_2D_
31.40107
193
0.729905
[ "transform", "solid" ]
3bb7ff84aebbdb74a281f5cf894006469def4622
4,255
h
C
CPP/Modules/include/GpsParser.h
wayfinder/Wayfinder-S60-Navigator
14d1b729b2cea52f726874687e78f17492949585
[ "BSD-3-Clause" ]
6
2015-12-01T01:12:33.000Z
2021-07-24T09:02:34.000Z
CPP/Modules/include/GpsParser.h
wayfinder/Wayfinder-S60-Navigator
14d1b729b2cea52f726874687e78f17492949585
[ "BSD-3-Clause" ]
null
null
null
CPP/Modules/include/GpsParser.h
wayfinder/Wayfinder-S60-Navigator
14d1b729b2cea52f726874687e78f17492949585
[ "BSD-3-Clause" ]
2
2017-02-02T19:31:29.000Z
2018-12-17T21:00:45.000Z
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd 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 Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** This is a helper class for gps receivers with * nmea output. */ #ifndef MODULES_GpsParser_H #define MODULES_GpsParser_H namespace isab { /** This class stores the state of * the NMEA packet reassembly state machine. In addition it maintains * some information on the current state of the receiver such as * health and the current constellation of satellites etc. */ class GpsParser { protected: /** The serial port that connects us to the Trimble receiver */ class SerialProviderPublic * m_serial; /** Where to send the calculated data */ class GpsConsumerPublic * m_consumer; /** The logging facility */ class Log * m_log; /** Read out a fixed point number from a string. * * @param s a pointer to the start of the string holding the digits. * * @param N the maximum number of digits to read */ int32 readNDigitsInt(char *s, int N); /** * Read out an integer. */ int32 readInt32(char *s); /** Read out a floating point number from a string. * At most a given number of digits are converted. * No error checking is done. * * @param s a pointer to the start of the string holding the digits. */ float readFloat(char *s); /** Time support routine */ static isabTime time_from_gps(int weekno, float tow); public: /** * Called by the owner (a GpsTrimble object) once the connection * to the hardware or a simulator is in place. */ virtual void connection_ready() = 0; /** * Set a new consumer. Called from highlevelConnectTo(). */ virtual void setConsumer(class GpsConsumerPublic *c) = 0; /** * Receive data from the serial port. * * Returns the number of handled packets and -1 on failure. * 0 means no end of packet was found for a valid packet. * This is normal. * * If there is an unfinsihed packet when the input buffer ends the * current state of the packet reassembly state machine is stored. */ virtual int receiveData(const uint8 *indata, int len) = 0; /** Unconditionally send the current status to the cosnumer, * if one exists. */ virtual void sendStatus() = 0; GpsParser(class SerialProviderPublic *p, class Log * log); /** * Virtual destructor for proper deletion. */ virtual ~GpsParser(); }; } /* namespace isab */ #endif /* MODULES_GpsParser_H */
40.141509
758
0.664865
[ "object" ]
3bbe6dda8d34cc14f9d3bdd48c5ec1799d624e3b
675
h
C
src/hpgl.pyd/extract_indicator_values.h
hpgl/hpgl
72d8c4113c242295de740513093f5779c94ba84a
[ "BSD-3-Clause" ]
70
2015-01-21T12:24:50.000Z
2022-03-16T02:10:45.000Z
src/hpgl.pyd/extract_indicator_values.h
hpgl/hpgl
72d8c4113c242295de740513093f5779c94ba84a
[ "BSD-3-Clause" ]
8
2015-04-22T13:14:30.000Z
2021-11-23T12:16:32.000Z
src/hpgl.pyd/extract_indicator_values.h
hpgl/hpgl
72d8c4113c242295de740513093f5779c94ba84a
[ "BSD-3-Clause" ]
18
2015-02-15T18:04:31.000Z
2021-01-16T08:54:32.000Z
/* Copyright 2009 HPGL Team This file is part of HPGL (High Perfomance Geostatistics Library). HPGL is free software: you can redistribute it and/or modify it under the terms of the BSD License. You should have received a copy of the BSD License along with HPGL. */ #ifndef __EXTRACT_INDICATOR_VALUES_H__983CBD36_7A03_465D_8962_748DD91A6187 #define __EXTRACT_INDICATOR_VALUES_H__983CBD36_7A03_465D_8962_748DD91A6187 namespace hpgl { void extract_indicator_values( boost::python::list values, int expected_count, std::vector<indicator_value_t> & result); } #endif //__EXTRACT_INDICATOR_VALUES_H__983CBD36_7A03_465D_8962_748DD91A6187
32.142857
103
0.791111
[ "vector" ]
3bd9def1a2a4d71d91eba96664a878eedbbdb72c
715
h
C
client/h/gapi/vao.h
egslava/arena_shooter
c93245441ed72c63a7f628d99b766ff005b8a3dc
[ "MIT" ]
1
2021-05-11T09:06:05.000Z
2021-05-11T09:06:05.000Z
client/h/gapi/vao.h
egslava/arena_shooter
c93245441ed72c63a7f628d99b766ff005b8a3dc
[ "MIT" ]
null
null
null
client/h/gapi/vao.h
egslava/arena_shooter
c93245441ed72c63a7f628d99b766ff005b8a3dc
[ "MIT" ]
null
null
null
#pragma once class VAO { friend class Particles; GLuint _vao = 0; std::vector<VBO> _vbos; void _gen(); void delete_(); /** Safe VAO removal. Should be used only internally. A class user should just use destructor. */ void _delete(){ if(_vao != 0) delete_(); } public: VAO(){} VAO(const VAO &that)=delete; VAO(VAO &&that){ _vao = that._vao; _vbos = std::move(that._vbos); that._vao = 0; } VAO&& operator = (VAO &&that){ _vao = that._vao; _vbos = std::move(that._vbos); that._vao = 0; return static_cast<VAO&&>(*this); } VAO&& data(std::vector<VBO> &&vbos); void bind(); ~VAO(); };
18.333333
101
0.535664
[ "vector" ]
3bdb6ddc091a428d8e343c60a01b17c3f7ebaa51
6,663
h
C
src/hssh/global_topological/mapping/lazy_evaluation_mapper.h
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
3
2020-03-05T23:56:14.000Z
2021-02-17T19:06:50.000Z
src/hssh/global_topological/mapping/lazy_evaluation_mapper.h
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
1
2021-03-07T01:23:47.000Z
2021-03-07T01:23:47.000Z
src/hssh/global_topological/mapping/lazy_evaluation_mapper.h
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
1
2021-03-03T07:54:16.000Z
2021-03-03T07:54:16.000Z
/* Copyright (C) 2010-2019, The Regents of The University of Michigan. All rights reserved. This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an MIT-style License that can be found at "https://github.com/h2ssh/Vulcan". */ /** * \file lazy_evaluation_mapper.h * \author Collin Johnson * * Declaration of LazyEvaluationMapper. */ #ifndef HSSH_GLOBAL_TOPOLOGICAL_MAPPING_LAZY_EVALUATION_MAPPER_H #define HSSH_GLOBAL_TOPOLOGICAL_MAPPING_LAZY_EVALUATION_MAPPER_H #include "hssh/global_topological/actions.h" #include "hssh/global_topological/mapping/probability_evaluator.h" #include "hssh/global_topological/mapping/topological_mapper.h" #include "hssh/global_topological/measurements.h" #include "hssh/global_topological/params.h" #include <deque> #include <fstream> #include <queue> namespace vulcan { namespace hssh { class MapOptimizer; class TopologicalLocalizer; const std::string LAZY_EVALUATION_MAPPER_TYPE("lazy-evaluation"); /** * LazyEvaluationMapper is a topological mapping algorithm the uses map likelihoods as a heuristic * for searching the space of potential map hypotheses. The algorithm focuses the expansion of map * hypotheses on the most likely map hypotheses based on current measurements or a heuristic for * older hypotheses. * * Each hypothesis has both a calculated and estimated likelihood. The calculated likelihood * incorporates all measurements up through the last topology event included in the map hypothesis. * The estimated likelihood guesses how the likelihood of a hypothesis will evolve as new measurements * are incorporated by considering how the likelihood of already expanded maps changes. * * The configuration parameters for LazyEvaluationMapper are: * * [LazyEvaluationMapperParameters] * min_hypotheses_to_expand = minimum number of hypotheses to expand for a given event, even if they are less likely * than the current best * */ class LazyEvaluationMapper : public TopologicalMapper { public: /** * Constructor for LazyEvaluationMapper. * * \param params Parameters for the mapper * \param manager Place manager that maintains the LPMs for the topological places */ LazyEvaluationMapper(const topological_mapper_params_t& params, MetricMapCache& manager); // TopologicalMapper interface void setCorrectMap(uint32_t id); void setCorrectMap(TopoMapPtr map); void updateMap(const topology_action_t& action, const topology_measurements_t& measurements); TopoMapPtr getUsableHypothesis(void) const { return mostLikelyHypothesis; } private: typedef std::vector<topology_action_t> reverse_actions_t; // topology_event_t stores all data associated with a given place struct topology_event_t { topology_action_t enteredAction; topology_action_t exitedAction; topology_measurements_t measurements; topology_event_t(void) { } topology_event_t(const topology_action_t& entered, const topology_measurements_t& measurements) : enteredAction(entered) , measurements(measurements) { } }; class TopoMapPriority { public: bool operator()(const TopoMapPtr& lhs, const TopoMapPtr& rhs) { return (lhs->getEstimatedLogPosterior() < rhs->getEstimatedLogPosterior()) || ((lhs->getEstimatedLogPosterior() == rhs->getEstimatedLogPosterior()) && (lhs.get() < rhs.get())); } }; void addEventToQueue(const topology_action_t& action, const topology_measurements_t& measurements); void handleExitedEvent(const topology_action_t& action, const topology_measurements_t& measurements); void handleEnteredEvent(const topology_action_t& action, const topology_measurements_t& measurements); void handleReverseEvent(const topology_action_t& action, const topology_measurements_t& measurements); bool initializeIfNeeded(const topology_action_t& action, const topology_measurements_t& measurements); void constructHypothesisQueue(void); void expandHypothesis(TopoMapPtr& hypothesis); void localizeHypothesis(TopoMapPtr& hypothesis); void movedToKnownPlace(TopoMapPtr& hypothesis, const LargeScaleStar& placeStar, const topology_event_t& event); void addNewPlace(TopoMapPtr& hypothesis, const LargeScaleStar& placeStar, const topology_measurements_t& measurements); void closeLoops(TopoMapPtr& hypothesis, const LargeScaleStar& placeStar, const topology_measurements_t& measurements); void processNewMapHypothesis(TopoMapPtr& child, TopoMapPtr& parent, const topology_measurements_t& measurements); void calculateHypothesisLikelihood(TopoMapPtr& child, TopoMapPtr& parent, const topology_measurements_t& measurements); void calculateEstimatedProbabilities(uint32_t depth, hypothesis_probability_t& probability); void updateHeuristic(TopoMapPtr& child, TopoMapPtr& parent); double likelihoodHeurstic(uint32_t hypothesisDepth); // calc from depth+1 to height double priorHeuristic(uint32_t depth, double calculatedPrior); bool isValidHypothesis(TopoMapPtr& hypothesis, const LargeScaleStar& placeStar); bool haveFinishedUpdate(void); bool hypothesisContainsAllEvents(uint32_t depth) { return depth + 1 == events.size(); } topology_event_t& enteredPlaceEvent(const TopoMapPtr& hyp) { return events[hyp->getDepth() + 1]; } topology_event_t& exitedPlaceEvent(const TopoMapPtr& hyp) { return events[hyp->getDepth()]; } reverse_actions_t& reverseActions(const TopoMapPtr& hyp) { return pathEvents[hyp->getDepth() + 1]; } TopoMapPtr mostLikelyHypothesis; uint32_t numHypothesesExpanded; uint32_t numHypothesesEvaluated; std::priority_queue<TopoMapPtr, std::vector<TopoMapPtr>, TopoMapPriority> mapQueue; std::vector<double> heuristicLikelihood; std::vector<double> heuristicPrior; std::deque<topology_event_t> events; std::deque<reverse_actions_t> pathEvents; // INVARIANT: pathEvents.size() == events.size()+1 // pathEvents[n] is all path events that occurred between events[n-1] and events[n] std::unique_ptr<TopologicalLocalizer> localizer; std::unique_ptr<MapOptimizer> optimizer; HypothesisProbabilityEvaluator probabilityEvaluator; lazy_evaluation_mapper_params_t params; std::ofstream evaluationLog; std::ofstream leafDepthLog; }; } // namespace hssh } // namespace vulcan #endif // HSSH_GLOBAL_TOPOLOGICAL_MAPPING_LAZY_EVALUATION_MAPPER_H
40.628049
120
0.765121
[ "vector" ]
3bde05bb9dab2217856b6528feda562db0a110a9
448
h
C
dataray-p1/include/Metall.h
leRoderic/Graphics_20
12e9f43b40a50faa61bc15cfd3db4ad94b9ef8de
[ "MIT" ]
null
null
null
dataray-p1/include/Metall.h
leRoderic/Graphics_20
12e9f43b40a50faa61bc15cfd3db4ad94b9ef8de
[ "MIT" ]
null
null
null
dataray-p1/include/Metall.h
leRoderic/Graphics_20
12e9f43b40a50faa61bc15cfd3db4ad94b9ef8de
[ "MIT" ]
1
2021-04-11T13:32:32.000Z
2021-04-11T13:32:32.000Z
// // Created by Qijun Jin on 28/03/2020. // #ifndef RAYDATA_METALL_H #define RAYDATA_METALL_H #include "Material.h" class Metall : public Material { public: Metall(const vec3 &ambient, const vec3 &diffuse, const vec3 &specular, const int &beta, const float &alpha); virtual ~Metall(); virtual bool scatter(const Ray &r_in, const IntersectionInfo &rec, vec3 &color, std::vector<Ray> &r_out) const; }; #endif //RAYDATA_METALL_H
19.478261
115
0.712054
[ "vector" ]
3be581f371fe380539be2b3b0c3cc8230b29087a
2,375
h
C
vulkan/src/main/cpp/Graphics/Kernel.h
ktprograms/HaishinKit.kt
6c26e007de1c1e3d23e0709527c2c39e1cb13e7a
[ "BSD-3-Clause" ]
null
null
null
vulkan/src/main/cpp/Graphics/Kernel.h
ktprograms/HaishinKit.kt
6c26e007de1c1e3d23e0709527c2c39e1cb13e7a
[ "BSD-3-Clause" ]
null
null
null
vulkan/src/main/cpp/Graphics/Kernel.h
ktprograms/HaishinKit.kt
6c26e007de1c1e3d23e0709527c2c39e1cb13e7a
[ "BSD-3-Clause" ]
null
null
null
#ifndef HAISHINKIT_KT_KERNEL_H #define HAISHINKIT_KT_KERNEL_H #define VK_USE_PLATFORM_ANDROID_KHR 1 #include "../haishinkit.hpp" #include <vulkan/vulkan.h> #include <vulkan/vulkan_core.h> #include <vulkan/vulkan_android.h> #include <vulkan/vulkan.hpp> #include <android/asset_manager.h> #include "CommandBuffer.h" #include "SwapChain.h" #include "Pipeline.h" #include "Texture.h" #include "Queue.h" #include "Feature/FeatureManager.h" #include "SurfaceRotation.hpp" namespace Graphics { class Kernel { public: vk::UniqueInstance instance; vk::UniqueSurfaceKHR surface; vk::UniqueDevice device; vk::PhysicalDevice physicalDevice; int32_t selectedPhysicalDevice = -1; bool invalidateSurfaceRotation = true; SwapChain swapChain; Pipeline pipeline; Queue queue; CommandBuffer commandBuffer; Kernel(); ~Kernel(); SurfaceRotation GetSurfaceRotation(); void SetSurfaceRotation(SurfaceRotation surfaceRotation); void SetAssetManager(AAssetManager *newAssetManager); void SetUp(ANativeWindow *window); void TearDown(); vk::Result DrawFrame(const std::function<void(uint32_t)> &lambda); void Submit(const std::function<void(vk::CommandBuffer)> &transaction); bool IsAvailable() const; std::string InspectDevices(); vk::ShaderModule LoadShader(const std::string &fileName); void SelectPhysicalDevice(); vk::UniqueImageView CreateImageView(vk::Image image, vk::Format); uint32_t FindMemoryType(uint32_t typeFilter, vk::MemoryPropertyFlags properties) const; void ReadPixels(void *buffer); void OnOutOfDate(); bool HasFeatures(); private: const std::string applicationName = "HaishinKit"; const std::string engineName = "Vulkan::Kernel"; const std::vector<const char *> validationLayers = { "VK_LAYER_KHRONOS_validation" }; SurfaceRotation surfaceRotation = ROTATION_0; bool isValidationLayersEnabled; bool isAvailable = false; AAssetManager *assetManager; FeatureManager *featureManager; std::vector<char> ReadFile(const std::string &fileName); bool IsValidationLayersSupported(); }; } #endif //HAISHINKIT_KT_KERNEL_H
26.685393
95
0.678737
[ "vector" ]
3be597b8ff6ada06019699e5a2b83230e0e23678
1,539
h
C
Source/Texture/Texture2D/TextureManager.h
frobro98/Musa
6e7dcd5d828ca123ce8f43d531948a6486428a3d
[ "MIT" ]
null
null
null
Source/Texture/Texture2D/TextureManager.h
frobro98/Musa
6e7dcd5d828ca123ce8f43d531948a6486428a3d
[ "MIT" ]
null
null
null
Source/Texture/Texture2D/TextureManager.h
frobro98/Musa
6e7dcd5d828ca123ce8f43d531948a6486428a3d
[ "MIT" ]
null
null
null
// Copyright 2020, Nathan Blane #pragma once #include "Containers/DynamicArray.hpp" // TODO - Move String up a directory level....or make Core required for every lib #include "String/String.h" #include "Path/Path.hpp" #include "Texture/TextureChunk.h" #include "Texture/ImageFormats.h" #include "Texture/TextureAPI.hpp" class Texture; class MemoryBuffer; class TEX_API TextureManager { public: static constexpr const char* DefaultFileName = "default.tex"; // TODO - Might not be the best place. Could be in Texture scope static constexpr const char* DefaultTexture = "_default-texture"; // Only exists because it's a static object and it needs to destroyed before the vulkan instance void Deinitialize(); Texture* LoadTextureFromFile(const Path& textureFilePath, const String& textureName); Texture* LoadTexture(MemoryBuffer& textureData, const char* textureName); void UnloadTexture(const char* textureName); Texture* FindTexture(const char* textureName); //Texture* CompressTextureData(const TextureChunk& chunkData, uint8* textureData, const char* textureName, ImageFormat format); //Texture* CompressTextureData(MemoryBuffer& textureData, const char* textureName); // TODO - This is to get around the problem of global texture not having gpu resources...need to fix this issue somehow void AddTexture(Texture& tex); private: //Texture* Compress(const TextureChunk& chunk, uint8* textureData, ImageFormat format); private: DynamicArray<Texture*> texturesLoaded; }; TEX_API TextureManager& GetTextureManager();
34.2
128
0.780377
[ "object" ]
ce017abd9c9bfea5de99ea68a6687c377bce133f
1,359
h
C
vegastrike/src/gfx/vec.h
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
vegastrike/src/gfx/vec.h
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
vegastrike/src/gfx/vec.h
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
#ifndef _3DMANIP_H_ #define _3DMANIP_H_ #include "config.h" //for Solaris #include "macosx_math.h" #include <math.h> #ifdef SOLARIS extern float __sqrtf( float ); extern float __cosf( float ); extern float __sinf( float ); extern float __tanf( float ); #define sqrtf __sqrtf #define cosf __cosf #define sinf __sinf #define tanf __tanf #endif #include "endianness.h" #define QFLOAT float #define NetSwap VSSwapHostFloatToLittle #define XSQRT sqrtf #define XVector Vector #define YVector QVector #include "xvector.h" #undef NetSwap #undef QFLOAT #undef XVector #undef YVector #undef XSQRT #define QFLOAT double #define NetSwap VSSwapHostDoubleToLittle #define XSQRT sqrt #define XVector QVector #define YVector Vector #include "xvector.h" #undef XSQRT #undef NetSwap #undef QFLOAT #undef XVector #undef YVector inline Vector QVector::operator=( const Vector &a ) { i = a.i; j = a.j; k = a.k; return a; } inline QVector::QVector( const Vector &a ) { i = a.i; j = a.j; k = a.k; } inline QVector Vector::operator=( const QVector &a ) { i = a.i; j = a.j; k = a.k; return a; } inline Vector::Vector( const QVector &a ) { i = a.i; j = a.j; k = a.k; } inline QVector Vector::Cast() const { return QVector( i, j, k ); } inline Vector QVector::Cast() const { return Vector( i, j, k ); } #endif
15.802326
52
0.679912
[ "vector" ]
ce019eb3d40feea9df668cd62ea2fc488291ac7f
3,665
h
C
Tests/DefaultPipelineTest/SimpleSample.h
HermanLederer/gtaRenderHook
2ce53ce954c2d298717119dd6d02a2e58fff3aed
[ "MIT" ]
null
null
null
Tests/DefaultPipelineTest/SimpleSample.h
HermanLederer/gtaRenderHook
2ce53ce954c2d298717119dd6d02a2e58fff3aed
[ "MIT" ]
null
null
null
Tests/DefaultPipelineTest/SimpleSample.h
HermanLederer/gtaRenderHook
2ce53ce954c2d298717119dd6d02a2e58fff3aed
[ "MIT" ]
null
null
null
#pragma once #include <TestUtils\TestSample.h> #include <dinput.h> #include <unordered_map> #include <atomic> #include <condition_variable> #include <array> #include "forward_pbr_pipeline.h" namespace RHEngine { class IRenderingContext; class D3D11ConstantBuffer; class D3D11PrimitiveBatch; }; class ForwardPBRPipeline; struct ModelData { RpClump* object; float drawDist; float boundSphereRad; bool hasAlpha; std::string dffname; std::string txdname; }; struct ModelInfo { uint32_t modelId; DirectX::XMMATRIX transform; bool selected = false; }; struct RenderingData { ModelData data; ModelInfo info; }; extern std::unordered_map<std::string, RwTexture*> g_ideTextureList; extern std::vector<std::string> g_ideLoadedTextureList; extern std::unordered_map<std::string, MaterialCB> g_materialBuffer; class MaterialBufferProvider : public IMaterialBufferProvider { MaterialCB* GetBuffer( std::string name ) { if( g_materialBuffer.find( name ) != g_materialBuffer.end() ) return &g_materialBuffer[name]; else return nullptr; } }; struct RenderBatch { uint32_t start = 0, end = 0; }; extern MaterialBufferProvider g_materialBufferProvider; /** * @brief Simple test sample for RenderHook, write your own code as you wish * */ class SimpleSample : public RHTests::TestSample { public: SimpleSample( RHEngine::RHRenderingAPI api, HINSTANCE inst ) : RHTests::TestSample( api, inst ) { } virtual ~SimpleSample() {}; void CustomRender() override; bool CustomInitialize() override; void CustomUpdate( float dt ) override; void CustomShutdown() override; private: void RenderUI(); void LoadIDE( const RHEngine::String& path ); void LoadIPL( const RHEngine::String& path, int32_t version ); void LoadIPLBinary( const RHEngine::String& path ); void LoadDFFForIPL( const RHEngine::String& models_path ); void DrawClump( RHEngine::IRenderingContext* context, RpClump* clump, bool selected, DirectX::XMMATRIX transf_mult ); void RenderWorker( std::uint32_t id ); private: std::unordered_map<uint32_t, ModelData> m_ideModelList{}; std::vector<ModelInfo> m_iplModelInfoMap{}; std::vector<RenderingData> m_vCurrentFrameRenderList{}; std::vector<RenderingData> m_vCurrentFrameAlphaRenderList{}; uint32_t m_nVisibleObjects =0; bool button_toggled[4] = { false, false, false, false }; bool mouse_aq = false; bool m_bThreadShouldStaph = false; bool m_bUseConstDrawDist = false; float m_fMaxDrawDist = 300; float m_fCamSpeed = 1; char m_sTexFilter[32] = {}; char m_sModelFilter[32] = {}; float m_fFPS = 0; float m_fCullingTime = 0; float m_fRenderingTime = 0; int32_t m_nMinMeshPerThread = 100; std::vector<float> m_fRenderingThreadTime; const uint32_t m_nMaxThreadCount = 64; std::vector<void*> m_aCommandListBuffer{}; std::atomic<uint32_t> m_nCmdListCount; std::vector<HANDLE> m_nBeginRenderingEvents; std::vector<HANDLE> m_nEndRenderingEvents; std::vector<std::thread> m_tWorkers; std::condition_variable m_main_thread_cond; std::mutex m_main_thread_mutex; std::mutex m_io_mtx; std::vector<RenderBatch> m_batches; int32_t m_nWorkerThreadCount = 0; ForwardPBRPipeline* m_pForwardPBRPipeline = nullptr; RHEngine::D3D11ConstantBuffer* mBaseConstantBuffer = nullptr; RHEngine::D3D11ConstantBuffer* mPerModelConstantBuffer = nullptr; std::vector<RHEngine::IRenderingContext*> mDeferredContextList; DirectX::XMMATRIX mObjTransformMatrix{}; DirectX::XMMATRIX mCurrentTransformMultiplier{}; };
30.289256
121
0.727694
[ "object", "vector", "transform" ]
22d55460f1de912edb6ddbe29b33ad990e5148f4
17,765
c
C
copasi/shinyExport/uiShiny.c
SzVarga/COPASI
00451b1a67eeec8272c73791ca861da754a7c4c4
[ "Artistic-2.0" ]
64
2015-03-14T14:06:18.000Z
2022-02-04T23:19:08.000Z
copasi/shinyExport/uiShiny.c
SzVarga/COPASI
00451b1a67eeec8272c73791ca861da754a7c4c4
[ "Artistic-2.0" ]
4
2017-08-16T10:26:46.000Z
2020-01-08T12:05:54.000Z
copasi/shinyExport/uiShiny.c
SzVarga/COPASI
00451b1a67eeec8272c73791ca861da754a7c4c4
[ "Artistic-2.0" ]
28
2015-04-16T14:14:59.000Z
2022-03-28T12:04:14.000Z
// Copyright (C) 2019 by Pedro Mendes, Rector and Visitors of the // University of Virginia, University of Heidelberg, and University // of Connecticut School of Medicine. // All rights reserved. static const char* shinyUIString = "\n" "check.packages <- function(pkg){\n" " new.pkg <- pkg[!(pkg %in% installed.packages()[, 'Package'])]\n" " if (length(new.pkg)) \n" " install.packages(new.pkg, dependencies = TRUE)\n" " sapply(pkg, require, character.only = TRUE)\n" "}\n" "packages<-c('shiny','devtools', 'reshape2', 'ggplot2', 'shinyTree', 'markdown', 'formattable','XML','zip')\n" "check.packages(packages)\n" "if(!('CoRC' %in% installed.packages()[, 'Package'])){\n" " install_github('jpahle/CoRC')\n" " CoRC::getCopasi()\n" "}\n" "\n" "ui <- fluidPage(list(tags$head(HTML('<link rel=\"icon\", href=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEYAAAA8CAMAAADsSTwRAAAC/VBMVEUAAAD///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////8uMZLl5fF8frv8/P7Y2OpHSp8wMpP+/v739/s3OpcxNJT5+fz7+/2wsdbu7vbi4/BwcrRVV6Y+QJu1ttl0drc1N5Xw8PfPz+ZrbbJeYKtaXKkzNpWqq9N+f7tFSJ45PJj6+v3z8/nn5/PS0+e9vt1MT6JIS6Dx8fibnMqUlceEhr9iZK1QU6RCRJzd3e24udqur9Wjpc+XmMmJi8KCg7729vrCw9+mp9Ds7PXr6/Tg4O/f3+7V1unMzOTKyuO6u9udnsza2+zHyOK8vdyZmsqPkMVNUKM7PpnU1OjFxeHAwd6HiMB5e7l2eLhnaa9XWadKTKFDRp7//v3//PqnqdKhoc2Agr2IOWfyYCz09Pno6fSys9errdSRk8aMjsSHicH937x7fbpqbLFlZ69ZW6hAQ5s8P5k0NJFlNXiPOWPX1+q/wN7+792Gh8D81KVSVaVBO5A3Mo5JN4dJNIVVNH+oQFe5PE/wSjXzazH0bCn/+fLk5PH+9+3w4uP96dCUlsf82rH8161PUaROSpn7yo9CM4l8S3N6N26iOlytO1X5rlT5p0nLPUfcPz/eQj3yXC/xWC/3lif0dSf1fiX+8+X80rpeTpdWPYX6unL5s3KBN2qYOV+1R07APEzFRUjVP0LqQDjvQDb1eTLsajDzZCv2iCH38vTFwNPgzc764cbgyMaknca4nryWkLfgxbKzmrJ5eLJ/da+bgKvBp6Odi590bJ9GSJ+vhJ77zpiEbJNMPI34pYXWkIX4p4NuQHmNUHX6tmaNRGL5s174p175sFmwWk33k0n4mkf2iEP3lUDMVkD4oz74oz3cUzrfYDbgYTXpVjT2jS2rs0N4AAAALHRSTlMAcMWADcqf/PWX6dGtVQLv3MKJdmpRODIU9+bh1L2RjXtaWEYrBvm0paSMYhcEx6wAAAeLSURBVFjD7ZZVdJNBEIVxd3d37sBPXGnSCBqgUCHBQnEo7u7u7u7u7u7u7u7uHGZ/CBTLAV544b7sOd3my9jeSZR/oDSps2XJFCtBgryZ/xoRI2WmDPAp8V8ysiVICyC8bueqbQe3d/8dJlWsOIBkr+LUEkvjKYL0fx5ICs5FVcbrYUK7sF4je4AV/0+LGj0eYKzfnqhkm4pGCMVJly5ORj+hR/9B+WLGBuxWLWnNo3SisvFzx0r29TrVzzBR8ROpqjmJylY24meK+nOMVCCygiWogtxEg6pJgMtWusB3cv0KU4C+ymECGhYhMtcB1JXa0Y8q9GuMUqEMUAQoFc4WQINBDGkA1KhfOFCj6EAdFBqNYggpFEVLKjyk9IdR1FQWQlUzgFJeJTk5EjS/qpdKVELFAD3clREyGOqSLVG9bGG/mC5u6AobAcsQKteII9HB0Q/1AkvBMQZ1lDWwsLIMLFLFP6ZwfdRRo4aZiobqgKDWMGqbo7iVjzLwDkRzJjGwFpn8YrTUE0CvoeSsDUDH4Vdu+jkLSB4Lk2TgPCf8YmgAEF6QAitLMI36FH7jz1mgmiZcGmIRQFW5Yv4xg1yo4KZxFYDSGhscYahNs+BoJbJAmwFMUgugvagNbj+Y4hIiNFRVBzW3Sw6/j1M+Qp0I17RAm4ICKO5K+5mbYCCEAnsBFaFrFvQ5fN9h8Eg9AhsKoG5oI4T4wUAKI08ZoE8IgprpRPh1iwZzdeQsBvWFoYPEQPnO/UtMAkitqf0swESlYa4qh9/V7MuiJn9sYGfU5AemBiRjIUvPn2ISQjWAePL06FMetqJ27ip3PIizkDPs0hUuPYDZc/vPHzt2Qf/RnYB4yWN8T0kdB14aZ0QdiNEvVk4lwm80VCdnwR0PB0Yv2PF8evc3e3dPmTJl98tDTxePRrys31llEhSj9jXRIkIefWeoXA9zmHxElEKn/jsOrlu7YufkCeTT5BFvH41G3ESRMbHQXNusNhoGqMXom6iWqIdNa0fVMABztx9cv7rbZCJSLnL0q9/Z0DnkwlYlDet2aAGSRaJkh7o9tUQhTXF59KsUEV0Vqbksqo7zn3Vfu2sSkbZ8SF01vii4y3ga/r4/cnyhJIqPvtSKq0L15NEvW13uqrMKpI7zX3Tft2wYaR2WHhCq2wBlvCpE1AZsbWnZ9E6xInXJpO0QjhoUIIkXUEZrFB03dVBj7qrDa5YRlahfAyxLL/mubV+MJGKOuiyt3vJ1ZyVFVzJAGIU8+mMcCOaOVwrutHjTtF0TqL3BBfSsKJeslQPC2rxi/GLCQN3uxP6yjFAqsIQUW2DE6OsDKoqyQDd75Yx9k6lkdT0klU5TDY2LyHdsbZJHYKLDSMNvxfFhUsJCocxmjHgBLUuqRcelza8OT51AZk6nYRW2Q0mUrBrfsbW10JSVMcE0fMuXDZqFc6qDuAIjRt9aHLP4mP26+wqlsjoAm7I5BnpFWcRdAyqN1q0Ly0mdo24d4/owceFU6mMnF5hQJydYT4TfceWMPcMCW8BVB5UXooayDpdFvmsySJiGwODoRLqNlD5MHjQNQDzZi3n0K5Xg8Efh+pG1S5TVoCuvxuAQJomyiDupg0GYRmGOqeNSWookOb+O8DgNcgkM8eiXb8IT7Zq5YV03mgf0K44KVADtQkTJxF3DwB6i4wNHodM9mjQH2aP4lBkOtvJkAiN8rQJatcHYI/sneNQI5yz4xTOJyyLfFWzDHa8AF+bcpSUnwcPnUwqEUG8kFRj2tcIcfl3c37iHxkBkoVL0ZpJclvqFoebGWxoBqmtLaOJxxIwRySRgIrc8NyV1vBq5q3qsmr6CKoOzEA4oMYmBcHeBpa0EQDq9jWjbnEgUVqIkaEPFPk3xSGVNET5jplIY9O0qoKsVddk7GDiycCnYANS8OJGIbuiQ8Vvbyo8CGo0J6qIKeNvK4WP7xv3jAxsAkFrZUT8EwY1LQQdWgVNsEUTjjwFJRZMihxMTvampEfXaidVo4PBd/TdMm0Ka+sGILJOl6iISGnZGDelHL86RFmE0riaMDTThIvw6vfF404HlwyiwbaihYV17i0aVqrQu0ow+SXm+NGBp8BNLzwppAHkacszoyV31WjFz5aZpa0bcpEiaNHy4cK/iJkA34OcLJjlUjZVUkL9G3xCSwgJ1p8UbZkw7sGbq8hHddo4YsXzq6r0PuLJDQvlfbI1/ucNTAPam/FV2FcDGgArAzLEPP2yc0X39+nXd3z1ZOp5n3NxID6hQtvMvMfxAoS9Wgp2uuKGWhM/quPnE2UuXr4jCaqy9RMHtnWHX2tD018u3hwQpyKoRRSxX3tymYEGro4hCSwJRvkpdl2iVbBphZtT29xPSHQFAX6aLdXCArymedtZQS215ciG1CxI/m1wBEQj1hyEFapeBLLWxQAVTgWAVZOmBfpURMdQlTCOoJO9S/xj2Ndh4YH37SIXwIDXC+grPE0u0tnjqXXmXKvxhAgyaMEPxZgaDppWlSZGIiPbFDY6mhmLKJgZrCUMlrddg7WCoVLQf/7GEP8wf6NcYY8E/UelfYf5QP8ckjPanShjlv35DHwGk0flWntRGUwAAAABJRU5ErkJggg==\"/>'))),\n" " div(style='padding: 1px 0px;',\n" " titlePanel(title='', windowTitle = 'ShinyCOPASI')\n" " ),\n" " div(style='text-align: center',\n" " img (src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAp8AAACZBAMAAACbAEwPAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAnUExURQAAAAAAchMPYwAAcQAAcQQDbwAAcgAAcgAAcb4LAtZqAFIFQdRxAVamC64AAAANdFJOUwDWCUu9I86Wc8/S0WL/3whaAAAc9klEQVR42u2du28bSZ7He5vqJXGYYHtINXnQBW1SHAmDCURRr9CUScnAJdSDloINttd6AZeYsl6hKMmS0pnM42yBC9aYxMEFhi44GLhk4D/qqn6/ele1JNuSzx53BbQpUiL54a/q+3tVtedlIxvZyEY2svFHGX5vZaXZzTjcDcx682KvTcZkxuIucK5ctNtbUUhGBvQOcM7ttbdCNjKgn26de+0kDDOgdzTIZOc4o/bh4WEmSp806rMc58ZRs9erVqtxBuVTzHNvAW1z8bQHLP2Myaesntw8F6eXqxmOTx61s4UM551OdzDP0mmG846mO5jn4+kM512MYBam+8aL5UzV78RbOmtl5nmXcgTLZ/Q8M8+7lKPSi8w872ast9FZynjeEU+Qo8fZdL9LnmT5zEjcKc9sut8lzxvkyK9Wq/VsQfgUnpRgr7fSbDYvLy8ODw+z0tKH8UTrqzOCl4QglOfa7YWFhS0ywiRL3N8UuQPDceA5Df/31xlCSjCJlBoIjpMMmrUSslk8R22QGlxN5Tm7EIWuEW20k9LhQQbUGrNtxQTpLM/tRWK+s9wIK36EJTLrz8KjZnM22e/1WsXqagbUGjOKBVIvKaDxJuNZnz0kRnh02mwmRWLGSYeo0mo4Wa2OkrUz1+p4GVB7NCTPR5TnmeRZe04AzkTLcbWWzHteIdmlX0CJPDZV6sLdDKg9BuHh0WU/ajandkhU5E8RntE+2ufeJrk9L5M7+YSAGwJJP6jE+ENqpRlQF9DlanVQrlbXaJS5RvOfz9FfAov0W0Vyb5WyXI267D7crBIrzYA6gBJMBBDx2mPmMD1i/jxYZC7Z5PMcbDWXdDxYPuFuBtQefQI0AGoE1AHkl4RcdbmZ9sk8hxuc/PSHaKUZUBsoMb5CuAtO0h7huQ086aQ/oBZJV0ovaD2NyQ2lDpOf/hDuZkDdQIfCCY8JUhliyRpQpKvnDFkpyTyfpzco8l0p8hlQx2gRoE/KXSZI6DDV2pwimmmechsDeELkx0CnMqBOoGci4kSH6YxSBIABE/muLfIRWRtmMqDWSAg8apawgD5ChwkpRhPcTEHfQelx8lORn6E/y2J5OzdCgVbZArqDAo+if17ikx313RB5Ovf9VgbUCZSMcbqAsuQmin6rwic7CHrQGvaY6AuRz2VArREkFfiHeqAso8xcJenRg6Dj5AeRpzc5jO4zoBbQsAMeE1tA/a7t0aM8wWSXIg93R7MEsw10h4fwZfgPBTqQHj2YKej7ash9UxYjkadPZUBtoJNswsMCut6OeT4EJjdm7FSR77AbjO4zoLYoxWzCgwcKMxpXy74wUwR8IEQ+TykzkU8BWm82e/G3C5Uq/A6d65B1Iq7Srgg8Iy7ySHUUw6NJfDiXAjSYpenq7Rfqj+ZefEOznk94Zpujoe7RM5HvcNEHkae+fSFZcAEN+ryiIo10QKbANzPpVxMecoIbj9TQo5dmCfMc5/2BFPlzF9BzUVPpiNf4lirOdOJWuswBpVkncJWehF1pll2RxuMiD3enSlMOSmuOqn1A75S/kVX1LAwjFiKBbeLqiaWkME3kaQKPPODINgUtBShnWId7E9+GIiXg0sPWuH6Zi7xSSvIVwELk6V3ygAPoqtYPsatYaPjsm1hBD9Clbyoif6JpEPxXAUxnu48i33EAbWlAmYki0ONvAehaAvo73hEiD/kQnOywmmoi39VEfneUm6AYeaNlZ+IbA0pdpp2Y/LMrskxgljLQRP0pKCJPbuAuecAGyvsmFvfw32EF6Lewhq6iIuWTYy7ymA+R2WRF5GGiA+WxNtbpLaABtufRylQNJn9ZAWptsa/3/nAGSj70U+4kcZHf5JOdVZHoOgj5EQAcXFLbpYHlSjO2gOKML4EtjkuKADSKbQfrcfyHM1CIkRoUJYo8zOYgGearqSryG9TZF0cP+FUSURqitKQ69AOxcAbSWA0Hq/OHM9AOoKwIkQezLIQi8EQ5Aqo1O+FhHuwAUWeJze1R4SsB0IpLv0rdP5qBLnu8vIHonkSwZIrAE9xOXAfYMQ5+/T0b70zAuFZu8hiM3vle/LxoPPnBpzqndNdE1bWvonoPR3hUb/FHwUC9gHhBYJAFJS6CLFMiWkUKi7yXnsB8rYz3/6u9RkFTcz/hGAMp+Oby8P1H0+zRxv/TZs/Yx1+trpAHTs3TEpA+H3EaMvdD8sWUL9B+/lpEZ9xalyVFUOTBLAdiNWVKhfvp/Pe/U4r/fInjn/TOb++UFx7S18o+n+iBC91S6MJ8W4NZ2QMvIgmjtra5tz6HByaEG9qP/dlFOQ4vp21u/iE+OOHAyf4mfbGjSY70Ap+/rwVJHS+3GHs/SJGHbjtcTcFVQr330TgpQAbz7RUZ5F9qpbHOqKg5pWUB9KHxPoc+AWh9Vo0eSkIa/dqe/PH2tHxnfkMPOLZPzbUip0fLCk/1b9LdcKpeqB9gLCEG6k9VGEpmlqGMizC7zPgE7znNV1dXI+QPvSE3IyNXBOlv/6O59Q81vqVUoPgJHn4UzzN9B4WAUOtroF/EaUCVLkOe1DBzjvw31/VoWsxA9lKbat6yE49TBwmtUEl+Sgc0x1ZPjvMVwFTGyNtfJdGBHmFS2YkEO0t+Gh8bPhk8w4j/6Xpff2BjMh1oYvjAPKtjOiM1g6d4gmmhuYQGSTNEj3CGK+H6E/oxMfDE1fOn3zlOxw4bYqS/xcprSER/4p69GygVxeLH6NGU8Q5KxykPRDtxKlDe+W4+oaRzNr8j+ZZNC12FIGlADEoV+b7exoSr53sUIidOaqSCaF+PMP/M+ebckzt3cfQxbui6uf2sNCFTkSa0dKDhhvriPgcXTej1DOvXht0WykqWg7DLUktc5Hk4n+epue/QPDWc9PS7w8O2JPrOBXToBqAfGY5YNsOiA3/AmWxtcbTb3XSg2nKZS0KXKtVb1m/93W2hY5ispECx8iFbaxUHlIy/onleveHvdvGIumMwesyfuPoVTbTlAHrMgEZ3BVTWWLa22m3Kjs1SLisbR83mxYKuVxxoqd1e4Ed2RmpRZlz81U1nvhxfa0tZugwLncGvgrbYKyKfx8ATHFB4Of+9bp4bR8SFq2LPOBlxdZ12RYVvf33nsNAHfOm8SwuVBrrxfLrX6xF228hshhklNmEf4D22inKgO9QKFhyzW07tHXXGD0Jx6B+81t7W1rHTQokgwEShHeGAEpVplRorOqB79MbH6f7zG+69LceGR+yD5I68BBM1RGmJc7wBqP8hJzpzU4oQXEz8xFN1dnKnlC2oGxM6UE24511+qppeYOlI6mOxL2blYsJpoWTGF2MEykVedNvB5PcnY+AJ051ZhPO0NiSKJmq4TQ0eIAHQv3l6csWfO53kpkV70msXi5pGrVy69o5zO1RcIrmIwWfnTzxX57wGVKwaT21N0u123GasJ4KEhc5gjdcnQHPJ36XIQ2stTHbJE82z9Dzt8Lv6ATXR/+QE5dcOfP/CgW6eh9HRpB74Qy/EGHw0Ws4WLapkkFgocrSbcJWI9t2koxMD8FMHUF6a3TbSOvgX5s1oTgFvAx0WMx6WyFYpLkiRh7gIHVCP83z1JtSPGwqaJMZYv1TCurWEzXkj9GxpUx7f7Qs9fddh3MtstSpNqO8" "34tbu9wxMQr7NtVUaE0OPyqMDFRIV25qk4XtiLg1pFjrGfs1vlS2RRwdU51limYY6bWzcok0O27EXXC7L2fX21y77QuW7DDVRYmNfAxrFmJSq8OpeJVa/jWcionzc1Wa8ZaBeLTEkhX1FOIN1oJiqVemr7ua2mcBxL/+ahbIZTzvCMQOKyjQm9894HugR8txm5lnYO0H04KrmFvZOY54WGKGLaEGrbvqh5oea7SRD7GF4WmVgOoct+afAk69oGl+yQtYx07dkDHERNYCOGUDx4e2WuWIu3dJCyRKMdkSBKiIPbKF+BP4n5wmnYfncN6UxftAajgnG861dPrtGXr7jK1FRm/JdE2i5qwLt4tPKlsgqPm1D5iSYHWq+jRbSzFueUMcBdNzQH9SkR8goOjaB3riG5vinDsKKGslDdhluvJ8ETzwNq3bBYlJscqDLwmq4ysMKYvEv/8FfJOoqolT2TKDciP6kAlUGQwLkYvmxKtfmhIQ9PrNs9tEtgGKv0G7D/FKW9JaiVAsd4wEWAYpxESgTxpwt+g4CGh+hfeJpWHvUQ4aJTtGPJTD3RdWTGMPbf/BFPOoon6hjA2VvD9z+knxn5KOv9GV6jD+qp1lX9XSI5YIr1sWplW8BdBx/d9Q0SPaD6OQGC23Ilo6KKvKUbY5un0VBAvvcr6JbADX5YY9v8pyk+AXQQhK+/UWQ47OWrixdBWhleU2pkSzxTzuQoMfEw76Senwg3riQ564rdWWsrTVFyt1rqAC6in903DTIUf7Wlq+1UPJB2e/kwiITedj5QfkUTvgC+obluPxY1X+Io+jcD1qbo3x2ECcSgLJX2RQe1qSSS6Yv0ZfpBTGRBzIrQVM2KO2+knp8IH6Jh4L2HGQxjQo0p8C/QeVxlY7ZHxFrlvSmHIcqKhZKfq/IX7OITQ5s5wd5OzXyn+8oT4iPiH0GF111/+wUfbkDmPvzQxwosY9//UV5pxOu5HyRP16RH6Io23fAkhrcFtVC6QNZj+7r4ZBtjorp1hXGBtAl3Q9FTXrK4yW5bsi1ats6Z02x0ILIURGgUuR9EHkfPCaygIIekcfOtnkmH/T/vMz6cQhjGyibeeVuSrUjJ5dGEZg2lNX9B62upwI9VmPrR7cByu3t2HbsB7rHiejnhbLN67EJN9JqmoWOChMiQKHJASP5AZtJP/EJ/yiWu2wcIt8VQH0OlKuG7mjI8jJ48egNiQLUQLHqPLcbtfL8QDxcSxN5V9SdDpQ7X091TRIT7KmrcpKU9MKeYqENYeuFsAhdNyjyrCAHikQnPGwKQy/ggO+fhZ4H6LydKccSaD8cead53vu2hcZ62anBJ/JAqX3lOLvrgVqlSctVZzl0/hoaUFEq6aiaRBWqwCw3NiNdx0qqWOhAVO4KxKNWdn7gC/xIDPSVkDZsdnKKfKxN+Xe6gJ6YFlr2NIzyf32z8fFYazthQLuqu/Pso4HSvDivofC1Eh+EBgRTlQLdSd6edFkoeaGi+KQb8PZh9cRSiOezCU+Q9DxxOA4X+TEU+S6Y6pCq8ppi6hWbgpQikSM1gR7LRUuE/38xqqcC6HFaHl+b8i0ZiXOg281m8yIxgjLUoh2ZxVP+vlFT2l52WCj5GjaVBIUu8tRAUZEexevQ0QysobueivwqF3lqqgIoCeb/LTY+RyXWgRZlwPm9DZQbRV9NoT6UQMs3AF1Nt9D5tJrSI22x7ShPk6oUHBjl/Ni20Jysi+TR0nH1xFIIrKBv6ITPLYhmJzwJK1RFnvpQAihZlP47Tm8ZKMg5nVejCwWo2j4wnAp0/UOABjcAFX9lXK7LVqzkjxuR8b5toQWZEMrjTEThwcTyd2wFPWFty7KjGapMGH3Oo6lyoP5BOPKL/CRT5uGiBbkgSrYDDeiwEv8XjVL+AzOUL92JhQpjW5VRkxUref6sXpwWHqG00Lx0vIfw3RfY9k6P+aBvoGYPKVLsZDzgJ2FBmgkWAGqqHChZQkfUprFzI8dWwBKIPvt1oA+VFbjiAFr88Cl/g4WKGgrTpK7qaqnfi3rmpzLxpIXmZWVyKAyN7Z3MQGktgm1bkiK/ye6C6VK8UwyoNuMV36kcK0AfSr+oaE/5Y6PBrKAAXboF0NEPtdCNfb2etKPVllQ3wiBajk0LHdWAnkiRP2GShAaqbVviJ2HBXRT5YWqJu/xdaECxQCSXfYVOGlAuuEspQIe9D3abAofbJHnKrb1olVrtKdIjB3ZNKW2rkGKhozzPCJHeBBd56GiiM/4Vbg1h25bo+UwpIu/3sahGE/bv3MXeExNo4AYqdjTwjj030NpH+KGRDXRrY3HafK/zmqUbKWXtqN+ObaGRBGqIPJvxT2Ntb7IUeRF9UpEPWnjQ01kY/nvsTqDj/LgZaNlsgcwrQBsmUEcT5zWhpwo0oucjLx5Nd83VIjrBZphxZ8uY568vmO130kJ/kECfwCdhIk/lnM34E9704EmRB//pgKeYqanmNjCWIpbwX9YnPFe+TgWo7wZauR3Q4JNjebsvnz10dAnj0NUyBt+lIFqK7TVUApUiD0E91XhmV2zb0jCjykSeppn49tkxaAik6P7jnZeS8YWA6WagRa19xwA6UMvf8HFvlW1i6bvIkb7zXH132rAXFeGQMhdAW0O7wh7mQZpoXgCWTJzxMJP74gASVeRZihnwrsdsBTUkSVvVdj8CaKwD7Uug/bT0XT1Jzdh3rwcaJOENnXmGe81UyemHNuA9Q44Zssd0Cf2ZmH/M3VIp8pAVwTQTRvJsTziNzUacF1xoiBVHVRgBdEkFOnwd0EQ8QSQy408rgdi5RXO4yHMTPbYjJQlUijy1ZAr0Deb4+N7kCTVdL+rIuEWEp8KeuqqCPN3d1encEqipY8Pe9TUlO63Bl9Vt73qgo06gpTjNQgygeiyPQOVWmh9hCYV1wBL5iO3tZiLPjJLuD4/4Cjp3OGm/gWe6hYrNSw9uC1TJBPCAyNYMRxl5TfGA0oE60yauV5Doj+1s07wKNJBbaVCTmMh3eWJZEfkyF3m2DIP2PZUBkdbRkeNbu/IuoH92Al1iQJXkSF4BOp7qN1ltSPwnnRuA9t2N7nYOWxwGcJyeD6UNzFzkNwEo1aRIbFvCA1ixXF9hHmiBizxPbomWuYaetGPvtZgCdOhaoMpesSUFaD1J6+UYs+RqkN6KY2lStCVG4mhk1oFOmBn7vvCjByhHE7ydEUW+7BJ56lWBcYLIH0AkHJxF8hhX9hK75pznQB8aa+iQU+U5ULmvEcEM61kCexGtmXKlyVQ6ULT5naYYMzeuthN2TYlnUwAo2y87IYDCfhpwS/PipEuwS7ihJ+IEEAnDdS6UJoDE/Kga0L8ZQPOpjn0Yqz/Fut6wd0P3XWB2etXC1HZGO021awexlir5Syl+KCV9zG2KyxF0OvjoNUGpmZ0yNilEnh3gginmquAZyu0+LXM2DmR+SxSI3EDLFtAGj/Dz2t6AcbsW4Wi2U4LfR961QPEB1TmoqapUje3V1oqUqHiwFaJP3zLIEZbn0UJ3Pd7UCClRcJ1Q5CMm8p7kqSyaDeOItgLfhqLKigBacAH1BVCxhaShARUdzPIChNWeKup8rxfbseVsCbc0yZGkgl/0j2QxnqcL7Fie/gpL6tE9CzC5UeQZ0BPu7CuHYInGvFwLv4wau0z6pDVZwtJRs9frrcy1uCbmla4FHehDM9vU4EBz7L3njP1VPF4p7YP1VKv12UW12B7hBk9/TUtypwJFTSo7ZH8THqWXgScv5FerYh/ppt19N+BuVotfZwFLyIqFnpdFkwNG8kVV5Pl1VNUJn+KBRDzsqRihpygUa5txBFDk/Jh9K9INkNvljuiumpWLBd7rytIx5WkoFbe0" "pp1UoAXbaWhIQ6zhtifYUSNqS8d2990o89doiz2KPJaQGVB68hUFiJhlJA+u1Ri1AHFptUrXlQVVx6Zel5dARSJvoHZDSaDMjUwMoP65sqGvvaVY4VoiJoj4+ObGrx23cs+7kv+x/EDEl4rMjmDVQnNcQFvEDhWR94kf+hKWRdY16hB5uj2kdsbf+6SzOm5uGwxcQIWOL7mB5pw7LMlSZiUzGND6gf11ci8qDaitSSK4p5N47Jris2qhdG5OsD0LKEd4Lg6r0JE/heykyMP/xrCu5YutaNqEl+3wdtW17wL6hP0w7wbqzTiBev6Ztao88zQTvWbz7I5bkyZc6addZ5xfmnDtAlnFiCxIyrEP3WL9igD6M/0SCq1J0XNPPyxoVG3ZKLA8sjMI+hEA4XPp7BVNoLkWexctxetrSIUSmxAT/eSH2kJKmBgcpFaK04CipG/EnluVlmxJeOTcBZLDuUhPsYfJzQ9u+BfsGolOfLhIrxT5syO2d6l2sSVWkx3Xpaj9uZa9Kynoiy3DiuDXDhe7bKHYVwumT/VS335fB6qWI/TkpYnaPoBgxx0nOdMlZe2KfXzTZ9e5T4ne24WOcCbydFnmnbZvRFPUHN02M0tvYnDH/JUL5S2XUy7tHcwxS1H2zQVzk8r7MI8dqCt/KbiQ7zmY3WsvTnsGUIuosBrjgY0X3k1AR13Z5FXRnTW1YPKcdO9Ton+IBjwEKCyReeoLvGCNYq9gZxI8DXKzYtqs7KmXTS1dcxnfXnPutKny9lWbcJTVrx0mUAJub0u5Zqs8PsRfb4v1KGorOxv9Gcx8GEDZj416xxhLk0wQO2gvJM5X8rwDfJLcjUw8ihyxFVgd6Y2/GOMiCr22W8al5evEOLfso2g+4nrp60cfekHlvn16Tn0Wtq+T0V48VVfA2kV7AX+uvYy/BkcmHD43gM7CT80OdnzuIf3e63OHbfiLG+320bT6Shf4pH1p1uVu0C9Kkc+RbwTn/M9YuyYOLez4qhN7O5Q0R97IE2dqn+XsbwdQ8q6a9PLXl6fTZsG3N0c+6tGpea5c/LGv7tdXms3L0+b08rVPo4Fax6s/5yLP3KMqnN9wxY+agMv8bmxtJdLu8WgHDPCCg87/F9Avb0zBKliFSB5usA7/I5w4IM8XUVnSg5peKjy9fJIBlSbagsyMP7XLssusPfS1doaDfvzNFd+czE6Y+kxAW18FUHAOiL9R5YEn8+2/SzlT6M3VW7DcRDmxa/WznP/ph18HUOpCs9DsCVwtlb3n3/lxgVf8FLGRETjnjkMu09MzvBXaa++qvNz9G/2UUxw/5xgXzk/tUlwtFYnyMwO1wc522Aae4wu0De+zWGhOKaB80aM6pbqTYwn121bIqhr8rpxpKceIdggf7va8Pwtdl+dO5u/yGK17n/QiPvPBcZuCfMf71wbS16+vWO8Qr29gG969WajfkrWVpa/nMg1wgFHEGOEhoVCf8X/6/bU2rt5EypGcvsfbR+7NQgsywvb7X9FVBSBZGz12xAA/vVdxbrHCGDyx9ly0j9ybheZl+/OY+xD8L3RgQrh0ar9f3/8rHl19lUTaibHBQocl78/v10Ix+4fHgJW+Ep6ej0SjxVNnpFqf22uxIL70fJlM9bq8bgX0sN+XhbKs+eLhnn5o59dgo5jFTTaOmtqpBX51ZW5vgdfIosfgLK0/5henoh3hre37i5QaNzUUf7kjx89sjkqLR6fNaTKazbkLCZPiZLOd1j5nSmyHYiE5vD+gOdcJoV/JqOqb75IEaqZKUkTkAaEAChen6sN11GaT+4uU1m5o0P4iB88Z1i6SMG3w8+D9aczw+aJMP1Vav0eg3qxjf+WXPmae8w1sKxctJ82j6WWsXgR7m9hmCw4T6xEdv0+gsiRd+mquxNRQtn/XmxdG6WtRvSABIKTxJvxnDE31foH6NazAL056Xw9Q5dT2OPZ7zUuslBzRy15I58lTNsyK83GIqRaSe842rcxdnk5/RXLUoGnGnFLkwsDSj/XFjFbvKELocmIXpoP9X/cOVITEX8kY0HJ8Pkq/JqxfVS9RJUQeUiOr4eRnAep9VUCPsYScO3Ku+8Fhh1/os49HX7FtDGiqcQbUBEp7lwZwiB/N5uSU0itcHQ1YyktU0f1K7Oqz82ClGVBj9KHFu8K6wsg6Se0ULonIdiKKxjsh8nne10gPy8iAWkBpO84mP6QN654Idwi3yE+wUBPQHnCRHwVTnfcyoCZQ1hGOuoMbvNiericRE3N2Hcqwy1fOLu6soa5oBtQYrVKzORU+b86FRbrlKanQ21aZ3h6Qh5p9+t8W/ek5uTuXPGU/pzcz4WlzNgNqAE2N4MP04N7dqZ2NG4DecgzHGUXFbU8yoHc7mp88pjOI2bjr8X/3bXrEBe1HvAAAAABJRU5ErkJggg==')\n" " ),\n" " tags$hr(),\n" " sidebarLayout(\n" " sidebarPanel(\n" " div(style='height: 70px;',downloadButton('downloadModel', 'Download Model')),\n" " #h6('Model files (.cps or SBML) that are less than 30 MB can only be loaded. For larger models, please use stand-alone program of COPASI.'),\n" " #h6('If the model has a data file, load it along with your model file using multiple selection.'),\n" " #tags$hr(),\n" " tags$strong(style = 'font-size: 15px;','COPASI:'),\n" " shinyTree('taskSelection'),\n" " tags$hr()\n" " ),\n" " mainPanel(tags$style(type='text/css', '#errorOut {background-color: rgba(255,255,0,0.40); color: red;}'),\n" " verbatimTextOutput('errorOut'),\n" " htmlOutput('modelInfo'),\n" " uiOutput('choose_options',inline = T),\n" " tags$hr(),\n" " uiOutput('choose_columns',inline = T),\n" " uiOutput('show_output',inline = T)\n" " )\n" " ),\n" " tags$hr(),\n" " tagList('This web-based interface uses Shiny package in R and CoRC, which a high-level R API for COPASI. The CoRC package can be downloaded from:', a('https://jpahle.github.io/CoRC', href= 'https://jpahle.github.io/CoRC'))\n" ")\n" "";
328.981481
3,898
0.826344
[ "model" ]
22d7b94748161586ec32471d0a830d35f41860f7
4,018
c
C
blinky/blinky/asf-3.21.0/avr32/services/dsp/dsplib/generic/basic/vectors/vect_dsp16_complex_abs.c
femtoio/femtousb-blink-example
5e166bdee500f67142d0ee83a1a169bab57fe142
[ "MIT" ]
null
null
null
blinky/blinky/asf-3.21.0/avr32/services/dsp/dsplib/generic/basic/vectors/vect_dsp16_complex_abs.c
femtoio/femtousb-blink-example
5e166bdee500f67142d0ee83a1a169bab57fe142
[ "MIT" ]
null
null
null
blinky/blinky/asf-3.21.0/avr32/services/dsp/dsplib/generic/basic/vectors/vect_dsp16_complex_abs.c
femtoio/femtousb-blink-example
5e166bdee500f67142d0ee83a1a169bab57fe142
[ "MIT" ]
null
null
null
/***************************************************************************** * * \file * * \brief generic 16-bit complex vector absolute function * * Copyright (c) 2014 Atmel Corporation. All rights reserved. * * \asf_license_start * * \page License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name of Atmel may not be used to endorse or promote products derived * from this software without specific prior written permission. * * 4. This software may only be redistributed and used in connection with an * Atmel microcontroller product. * * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. * * \asf_license_stop * ******************************************************************************/ /** * Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a> */ #include "dsp.h" #include "preprocessor.h" #if defined(FORCE_ALL_GENERICS) || \ defined(FORCE_GENERIC_VECT16_COMPLEX_ABS) || \ !defined(TARGET_SPECIFIC_VECT16_COMPLEX_ABS) #define DSP16_COMPLEX_ABS(x_num, data) \ temp1 = vect2[x_num].real; \ temp1 = (temp1*temp1) >> DSP16_QB; \ temp2 = vect2[x_num].imag; \ temp2 = (temp2*temp2) >> DSP16_QB; \ vect1[x_num] = dsp16_op_sqrt(temp1 + temp2); /********************************************************************************************* * This function is the ending function of the complex absolute. It is used to absolute the last items of a complex vector. *********************************************************************************************/ #define DSP16_COMPLEX_ABS_KERNEL_X_FCT(x_num, data) \ static void TPASTE2(dsp16_vect_complex_abs_kernel_x, x_num)(dsp16_t *vect1, dsp16_complex_t *vect2) \ { \ S32 temp1, temp2; \ MREPEAT(x_num, DSP16_COMPLEX_ABS, ""); \ } /*********************************************************************************************/ static void dsp16_vect_complex_abs_kernel_x0(dsp16_t *vect1, dsp16_complex_t *vect2) { } DSP16_COMPLEX_ABS_KERNEL_X_FCT(1, "") DSP16_COMPLEX_ABS_KERNEL_X_FCT(2, "") DSP16_COMPLEX_ABS_KERNEL_X_FCT(3, "") void dsp16_vect_complex_abs(dsp16_t *vect1, dsp16_complex_t *vect2, int size) { typedef void (*complex_abs_kernel_opti_t)(dsp16_t *, dsp16_complex_t *); static const complex_abs_kernel_opti_t complex_abs_end_kernel_opti[4] = { dsp16_vect_complex_abs_kernel_x0, dsp16_vect_complex_abs_kernel_x1, dsp16_vect_complex_abs_kernel_x2, dsp16_vect_complex_abs_kernel_x3 }; int n; S32 temp1, temp2; for(n=0; n<size-3; n+=4) { DSP16_COMPLEX_ABS(n, ""); DSP16_COMPLEX_ABS(n+1, ""); DSP16_COMPLEX_ABS(n+2, ""); DSP16_COMPLEX_ABS(n+3, ""); } // Jump on different functions depending on the length of the vectors to compute complex_abs_end_kernel_opti[size&0x3](&vect1[n], &vect2[n]); } #endif
37.551402
123
0.661772
[ "vector" ]
22e1e78c3a9f9a16cf38eff97c8cf206d823482d
1,465
h
C
ppapi/utility/private/network_list_observer_private.h
Scopetta197/chromium
b7bf8e39baadfd9089de2ebdc0c5d982de4a9820
[ "BSD-3-Clause" ]
212
2015-01-31T11:55:58.000Z
2022-02-22T06:35:11.000Z
ppapi/utility/private/network_list_observer_private.h
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
5
2015-03-27T14:29:23.000Z
2019-09-25T13:23:12.000Z
ppapi/utility/private/network_list_observer_private.h
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
221
2015-01-07T06:21:24.000Z
2022-02-11T02:51:12.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef PPAPI_UTILITY_PRIVATE_NETWORK_LIST_OBSERVER_H_ #define PPAPI_UTILITY_PRIVATE_NETWORK_LIST_OBSERVER_H_ #include "ppapi/cpp/private/network_monitor_private.h" namespace pp { class NetworkListPrivate; /// <code>NetworkListObserver</code> is a wrapper for /// <code>pp::NetworkMonitorPrivate</code> that makes it easier to /// handle network list update notifications. A child class must /// implement the <code>OnNetworkListChanged()</code> method. That /// method will be called once after the object is created and then /// every time network configuration changes. class NetworkListObserverPrivate { public: explicit NetworkListObserverPrivate(const InstanceHandle& instance); virtual ~NetworkListObserverPrivate(); protected: /// Called once after this object is created and later every time /// network configuration changes. Child classes must implement this /// method. /// /// @param[in] list The current list of network interfaces. virtual void OnNetworkListChanged(const NetworkListPrivate& list) = 0; private: static void NetworkListCallbackHandler(void* user_data, PP_Resource list_resource); NetworkMonitorPrivate monitor_; }; } // namespace pp #endif // PPAPI_UTILITY_PRIVATE_NETWORK_LIST_OBSERVER_H_
34.069767
73
0.761775
[ "object" ]
22eac9ac2c2daf96055986c1168b1650d760059e
762
c
C
src/reproBLAS/rssum.c
nikolovjovan/ReproBLAS
418db4320660d519c3831598de306f8c3bbefee5
[ "BSD-3-Clause" ]
6
2018-10-02T18:51:26.000Z
2021-03-13T02:23:24.000Z
src/reproBLAS/rssum.c
nikolovjovan/ReproBLAS
418db4320660d519c3831598de306f8c3bbefee5
[ "BSD-3-Clause" ]
6
2017-08-01T22:27:28.000Z
2019-12-20T08:34:48.000Z
src/reproBLAS/rssum.c
nikolovjovan/ReproBLAS
418db4320660d519c3831598de306f8c3bbefee5
[ "BSD-3-Clause" ]
8
2017-07-01T22:19:09.000Z
2022-02-01T21:02:31.000Z
#include <reproBLAS.h> #include <binnedBLAS.h> /** * @brief Compute the reproducible sum of single precision vector X * * Return the sum of X. * * The reproducible sum is computed with binned types using #binnedBLAS_sbssum() * * @param fold the fold of the binned types * @param N vector length * @param X single precision vector * @param incX X vector stride (use every incX'th element) * @return sum of X * * @author Peter Ahrens * @date 15 Jan 2016 */ float reproBLAS_rssum(const int fold, const int N, const float* X, const int incX) { float_binned *sumi = binned_sballoc(fold); float sum; binned_sbsetzero(fold, sumi); binnedBLAS_sbssum(fold, N, X, incX, sumi); sum = binned_ssbconv(fold, sumi); free(sumi); return sum; }
23.8125
84
0.700787
[ "vector" ]
22edad431b2fd3063366cd41d9cf4f04e39afc80
20,624
c
C
PQC/cl1.c
APeche/OGS-HYSTEM-EXTRAN
467feebe8dd8cc584c1c49e45b8008495efe8fc5
[ "Apache-2.0" ]
30
2015-09-26T00:26:28.000Z
2022-01-20T10:13:13.000Z
PQC/cl1.c
APeche/OGS-HYSTEM-EXTRAN
467feebe8dd8cc584c1c49e45b8008495efe8fc5
[ "Apache-2.0" ]
129
2016-01-25T12:54:40.000Z
2021-04-10T18:57:37.000Z
PQC/cl1.c
APeche/OGS-HYSTEM-EXTRAN
467feebe8dd8cc584c1c49e45b8008495efe8fc5
[ "Apache-2.0" ]
100
2015-08-01T12:04:34.000Z
2022-03-16T16:22:39.000Z
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include "phqalloc.h" #include "output.h" #include "phrqtype.h" void cl1_space (int check, int n2d, int klm, int nklmd); extern void zero_double(LDBLE *target, int n); LDBLE *x_arg = NULL, *res_arg = NULL, *scratch = NULL; int x_arg_max = 0, res_arg_max = 0, scratch_max = 0; int cl1 (int k, int l, int m, int n, int nklmd, int n2d, LDBLE * q, int *kode, LDBLE toler, int *iter, LDBLE * x, LDBLE * res, LDBLE * error, LDBLE * cu, int *iu, int *s, int check); static char const svnid[] = "$Id: cl1.c 4 2009-04-21 17:29:29Z delucia $"; extern void *free_check_null (void *ptr); extern void malloc_error (void); /* debug #define DEBUG_CL1 #define CHECK_ERRORS */ int cl1 (int k, int l, int m, int n, int nklmd, int n2d, LDBLE * q, int *kode, LDBLE toler, int *iter, LDBLE * x, LDBLE * res, LDBLE * error, LDBLE * cu, int *iu, int *s, int check) { /* System generated locals */ union double_or_int { int ival; LDBLE dval; } *q2; /* Local variables */ static int nklm; static LDBLE xmin, xmax; static int iout, i, j; static LDBLE z; static int maxit, n1, n2; static LDBLE pivot; static int ia, ii, kk, in, nk, js; static LDBLE sn; static int iphase, kforce; static LDBLE zu, zv; static LDBLE tpivot; static int klm, jmn, nkl, jpn; static LDBLE cuv, sum; static int klm1; int q_dim, cu_dim; int kode_arg; LDBLE check_toler; #ifdef CHECK_ERRORS extern char **col_name, **row_name; extern int *row_back, *col_back; #endif /* THIS SUBROUTINE USES A MODIFICATION OF THE SIMPLEX */ /* METHOD OF LINEAR PROGRAMMING TO CALCULATE AN L1 SOLUTION */ /* TO A K BY N SYSTEM OF LINEAR EQUATIONS */ /* AX=B */ /* SUBJECT TO L LINEAR EQUALITY CONSTRAINTS */ /* CX=D */ /* AND M LINEAR INEQUALITY CONSTRAINTS */ /* EX.LE.F. */ /* DESCRIPTION OF PARAMETERS */ /* K NUMBER OF ROWS OF THE MATRIX A (K.GE.1). */ /* L NUMBER OF ROWS OF THE MATRIX C (L.GE.0). */ /* M NUMBER OF ROWS OF THE MATRIX E (M.GE.0). */ /* N NUMBER OF COLUMNS OF THE MATRICES A,C,E (N.GE.1). */ /* KLMD SET TO AT LEAST K+L+M FOR ADJUSTABLE DIMENSIONS. */ /* KLM2D SET TO AT LEAST K+L+M+2 FOR ADJUSTABLE DIMENSIONS. */ /* NKLMD SET TO AT LEAST N+K+L+M FOR ADJUSTABLE DIMENSIONS. */ /* N2D SET TO AT LEAST N+2 FOR ADJUSTABLE DIMENSIONS */ /* Q TWO DIMENSIONAL REAL ARRAY WITH KLM2D ROWS AND */ /* AT LEAST N2D COLUMNS. */ /* ON ENTRY THE MATRICES A,C AND E, AND THE VECTORS */ /* B,D AND F MUST BE STORED IN THE FIRST K+L+M ROWS */ /* AND N+1 COLUMNS OF Q AS FOLLOWS */ /* A B */ /* Q = C D */ /* E F */ /* THESE VALUES ARE DESTROYED BY THE SUBROUTINE. */ /* KODE A CODE USED ON ENTRY TO, AND EXIT */ /* FROM, THE SUBROUTINE. */ /* ON ENTRY, THIS SHOULD NORMALLY BE SET TO 0. */ /* HOWEVER, IF CERTAIN NONNEGATIVITY CONSTRAINTS */ /* ARE TO BE INCLUDED IMPLICITLY, RATHER THAN */ /* EXPLICITLY IN THE CONSTRAINTS EX.LE.F, THEN KODE */ /* SHOULD BE SET TO 1, AND THE NONNEGATIVITY */ /* CONSTRAINTS INCLUDED IN THE ARRAYS X AND */ /* RES (SEE BELOW). */ /* ON EXIT, KODE HAS ONE OF THE */ /* FOLLOWING VALUES */ /* 0- OPTIMAL SOLUTION FOUND, */ /* 1- NO FEASIBLE SOLUTION TO THE */ /* CONSTRAINTS, */ /* 2- CALCULATIONS TERMINATED */ /* PREMATURELY DUE TO ROUNDING ERRORS, */ /* 3- MAXIMUM NUMBER OF ITERATIONS REACHED. */ /* TOLER A SMALL POSITIVE TOLERANCE. EMPIRICAL */ /* EVIDENCE SUGGESTS TOLER = 10**(-D*2/3), */ /* WHERE D REPRESENTS THE NUMBER OF DECIMAL */ /* DIGITS OF ACCURACY AVAILABLE. ESSENTIALLY, */ /* THE SUBROUTINE CANNOT DISTINGUISH BETWEEN ZERO */ /* AND ANY QUANTITY WHOSE MAGNITUDE DOES NOT EXCEED */ /* TOLER. IN PARTICULAR, IT WILL NOT PIVOT ON ANY */ /* NUMBER WHOSE MAGNITUDE DOES NOT EXCEED TOLER. */ /* ITER ON ENTRY ITER MUST CONTAIN AN UPPER BOUND ON */ /* THE MAXIMUM NUMBER OF ITERATIONS ALLOWED. */ /* A SUGGESTED VALUE IS 10*(K+L+M). ON EXIT ITER */ /* GIVES THE NUMBER OF SIMPLEX ITERATIONS. */ /* X ONE DIMENSIONAL REAL ARRAY OF SIZE AT LEAST N2D. */ /* ON EXIT THIS ARRAY CONTAINS A */ /* SOLUTION TO THE L1 PROBLEM. IF KODE=1 */ /* ON ENTRY, THIS ARRAY IS ALSO USED TO INCLUDE */ /* SIMPLE NONNEGATIVITY CONSTRAINTS ON THE */ /* VARIABLES. THE VALUES -1, 0, OR 1 */ /* FOR X(J) INDICATE THAT THE J-TH VARIABLE */ /* IS RESTRICTED TO BE .LE.0, UNRESTRICTED, */ /* OR .GE.0 RESPECTIVELY. */ /* RES ONE DIMENSIONAL REAL ARRAY OF SIZE AT LEAST KLMD. */ /* ON EXIT THIS CONTAINS THE RESIDUALS B-AX */ /* IN THE FIRST K COMPONENTS, D-CX IN THE */ /* NEXT L COMPONENTS (THESE WILL BE =0),AND */ /* F-EX IN THE NEXT M COMPONENTS. IF KODE=1 ON */ /* ENTRY, THIS ARRAY IS ALSO USED TO INCLUDE SIMPLE */ /* NONNEGATIVITY CONSTRAINTS ON THE RESIDUALS */ /* B-AX. THE VALUES -1, 0, OR 1 FOR RES(I) */ /* INDICATE THAT THE I-TH RESIDUAL (1.LE.I.LE.K) IS */ /* RESTRICTED TO BE .LE.0, UNRESTRICTED, OR .GE.0 */ /* RESPECTIVELY. */ /* ERROR ON EXIT, THIS GIVES THE MINIMUM SUM OF */ /* ABSOLUTE VALUES OF THE RESIDUALS. */ /* CU A TWO DIMENSIONAL REAL ARRAY WITH TWO ROWS AND */ /* AT LEAST NKLMD COLUMNS USED FOR WORKSPACE. */ /* IU A TWO DIMENSIONAL INTEGER ARRAY WITH TWO ROWS AND */ /* AT LEAST NKLMD COLUMNS USED FOR WORKSPACE. */ /* S INTEGER ARRAY OF SIZE AT LEAST KLMD, USED FOR */ /* WORKSPACE. */ /* DOUBLE PRECISION DBLE */ /* REAL */ /* INITIALIZATION. */ if (svnid == NULL) fprintf (stderr, " "); zv = 0; kode_arg = *kode; cl1_space(check, n2d, k+l+m, nklmd); /* Parameter adjustments */ q_dim = n2d; q2 = (union double_or_int *) q; cu_dim = nklmd; /* Function Body */ maxit = *iter; n1 = n + 1; n2 = n + 2; nk = n + k; nkl = nk + l; klm = k + l + m; klm1 = klm + 1; nklm = n + klm; kforce = 1; *iter = 0; js = 0; ia = -1; /* SET UP LABELS IN Q. */ for (j = 0; j < n; ++j) { q2[klm1 * q_dim + j].ival = j + 1; } /* L10: */ for (i = 0; i < klm; ++i) { q2[i * q_dim + n1].ival = n + i + 1; if (q2[i * q_dim + n].dval < 0.) { for (j = 0; j < n1; ++j) { q2[i * q_dim + j].dval = -q2[i * q_dim + j].dval; } q2[i * q_dim + n1].ival = -q2[i * q_dim + n1].ival; /* L20: */ } } /* L30: */ /* SET UP PHASE 1 COSTS. */ iphase = 2; #ifdef DEBUG_CL1 output_msg (OUTPUT_MESSAGE, "Set up phase 1 costs\n"); #endif /* Zero first row of cu and iu */ memcpy ((void *) &(cu[0]), (void *) &(scratch[0]), (size_t) nklm * sizeof (LDBLE)); for (j = 0; j < nklm; ++j) { iu[j] = 0; } /* L40: */ #ifdef DEBUG_CL1 output_msg (OUTPUT_MESSAGE, "L40\n"); #endif if (l != 0) { for (j = nk; j < nkl; ++j) { cu[j] = 1.; iu[j] = 1; } /* L50: */ iphase = 1; } /* Copy first row of cu and iu to second row */ memcpy ((void *) &(cu[cu_dim]), (void *) &(cu[0]), (size_t) nklm * sizeof (LDBLE)); memcpy ((void *) &(iu[cu_dim]), (void *) &(iu[0]), (size_t) nklm * sizeof (int)); /* L60: */ #ifdef DEBUG_CL1 output_msg (OUTPUT_MESSAGE, "L60\n"); #endif if (m != 0) { for (j = nkl; j < nklm; ++j) { cu[cu_dim + j] = 1.; iu[cu_dim + j] = 1; jmn = j - n; if (q2[jmn * q_dim + n1].ival < 0) { iphase = 1; } } /* L70: */ } /* L80: */ #ifdef DEBUG_CL1 output_msg (OUTPUT_MESSAGE, "L80\n"); #endif if (*kode != 0) { for (j = 0; j < n; ++j) { if (x[j] < 0.) { /* L90: */ cu[j] = 1.; iu[j] = 1; } else if (x[j] > 0.) { cu[cu_dim + j] = 1.; iu[cu_dim + j] = 1; } } /* L110: */ #ifdef DEBUG_CL1 output_msg (OUTPUT_MESSAGE, "L110\n"); #endif for (j = 0; j < k; ++j) { jpn = j + n; if (res[j] < 0.) { /* L120: */ cu[jpn] = 1.; iu[jpn] = 1; if (q2[j * q_dim + n1].ival > 0) { iphase = 1; } } else if (res[j] > 0.) { /* L130: */ cu[cu_dim + jpn] = 1.; iu[cu_dim + jpn] = 1; if (q2[j * q_dim + n1].ival < 0) { iphase = 1; } } } /* L140: */ } /* L150: */ #ifdef DEBUG_CL1 output_msg (OUTPUT_MESSAGE, "L150\n"); #endif if (iphase == 2) { goto L500; } /* COMPUTE THE MARGINAL COSTS. */ L160: #ifdef DEBUG_CL1 output_msg (OUTPUT_MESSAGE, "L160\n"); #endif for (j = js; j < n1; ++j) { sum = 0.; for (i = 0; i < klm; ++i) { ii = q2[i * q_dim + n1].ival; if (ii < 0) { z = cu[cu_dim - ii - 1]; } else { z = cu[ii - 1]; } sum += q2[i * q_dim + j].dval * z; } q2[klm * q_dim + j].dval = sum; } for (j = js; j < n; ++j) { ii = q2[klm1 * q_dim + j].ival; if (ii < 0) { z = cu[cu_dim - ii - 1]; } else { z = cu[ii - 1]; } q2[klm * q_dim + j].dval -= z; } /* DETERMINE THE VECTOR TO ENTER THE BASIS. */ L240: #ifdef DEBUG_CL1 output_msg (OUTPUT_MESSAGE, "L240, xmax %e\n", xmax); #endif xmax = 0.; if (js >= n) { goto L490; /* test for optimality */ } for (j = js; j < n; ++j) { zu = q2[klm * q_dim + j].dval; ii = q2[klm1 * q_dim + j].ival; if (ii > 0) { zv = -zu - cu[ii - 1] - cu[cu_dim + ii - 1]; } else { ii = -ii; zv = zu; zu = -zu - cu[ii - 1] - cu[cu_dim + ii - 1]; } /* L260 */ if (kforce == 1 && ii > n) { continue; } if (iu[ii - 1] != 1 && zu > xmax) { xmax = zu; in = j; } /* L270 */ if (iu[cu_dim + ii - 1] != 1 && zv > xmax) { xmax = zv; in = j; } } /* L280 */ #ifdef DEBUG_CL1 output_msg (OUTPUT_MESSAGE, "L280 xmax %e, toler %e\n", xmax, toler); #endif if (xmax <= toler) { #ifdef DEBUG_CL1 output_msg (OUTPUT_MESSAGE, "xmax before optimality test %e\n", xmax); #endif goto L490; /* test for optimality */ } if (q2[klm * q_dim + in].dval != xmax) { for (i = 0; i < klm1; ++i) { q2[i * q_dim + in].dval = -q2[i * q_dim + in].dval; } q2[klm1 * q_dim + in].ival = -q2[klm1 * q_dim + in].ival; /* L290: */ q2[klm * q_dim + in].dval = xmax; } /* DETERMINE THE VECTOR TO LEAVE THE BASIS. */ if (iphase != 1 && ia != -1) { xmax = 0.; /* find maximum absolute value in column "in" */ for (i = 0; i <= ia; ++i) { z = fabs (q2[i * q_dim + in].dval); if (z > xmax) { xmax = z; iout = i; } } /* L310: */ #ifdef DEBUG_CL1 output_msg (OUTPUT_MESSAGE, "L310, xmax %e\n", xmax); #endif /* switch row ia with row iout, use memcpy */ if (xmax > toler) { memcpy ((void *) &(scratch[0]), (void *) &(q2[ia * q_dim]), (size_t) n2 * sizeof (LDBLE)); memcpy ((void *) &(q2[ia * q_dim]), (void *) &(q2[iout * q_dim]), (size_t) n2 * sizeof (LDBLE)); memcpy ((void *) &(q2[iout * q_dim]), (void *) &(scratch[0]), (size_t) n2 * sizeof (LDBLE)); /* L320: */ /* set pivot to row ia, column in */ iout = ia; --ia; pivot = q2[iout * q_dim + in].dval; goto L420; /* Gauss Jordan */ } } /* L330: */ #ifdef DEBUG_CL1 output_msg (OUTPUT_MESSAGE, "L330, xmax %e\n", xmax); #endif kk = -1; /* divide column n1 by positive value in column "in" greater than toler */ for (i = 0; i < klm; ++i) { z = q2[i * q_dim + in].dval; if (z > toler) { ++kk; res[kk] = q2[i * q_dim + n].dval / z; s[kk] = i; } } /* L340: */ #ifdef DEBUG_CL1 if (kk < 0) { output_msg (OUTPUT_MESSAGE, "kode = 2 in loop 340.\n"); } #endif L350: #ifdef DEBUG_CL1 output_msg (OUTPUT_MESSAGE, "L350, xmax %e\n", xmax); #endif if (kk < 0) { /* no positive value found in L340 or bypass intermediate verticies */ *kode = 2; goto L590; } /* L360: */ #ifdef DEBUG_CL1 output_msg (OUTPUT_MESSAGE, "L360, xmax %e\n", xmax); #endif /* find minimum residual */ xmin = res[0]; iout = s[0]; j = 0; if (kk != 0) { for (i = 1; i <= kk; ++i) { if (res[i] < xmin) { j = i; xmin = res[i]; iout = s[i]; } } /* L370: */ /* put kk in position j */ res[j] = res[kk]; s[j] = s[kk]; } /* L380: */ #ifdef DEBUG_CL1 output_msg (OUTPUT_MESSAGE, "L380 iout %d, xmin %e, xmax %e\n", iout, xmin, xmax); #endif --kk; pivot = q2[iout * q_dim + in].dval; ii = q2[iout * q_dim + n1].ival; if (iphase != 1) { if (ii < 0) { /* L390: */ if (iu[-ii - 1] == 1) { goto L420; } } else { if (iu[cu_dim + ii - 1] == 1) { goto L420; } } } /* L400: */ #ifdef DEBUG_CL1 output_msg (OUTPUT_MESSAGE, "L400\n"); #endif ii = abs (ii); cuv = cu[ii - 1] + cu[cu_dim + ii - 1]; if (q2[klm * q_dim + in].dval - pivot * cuv > toler) { /* BYPASS INTERMEDIATE VERTICES. */ for (j = js; j < n1; ++j) { z = q2[iout * q_dim + j].dval; q2[klm * q_dim + j].dval -= z * cuv; q2[iout * q_dim + j].dval = -z; } /* L410: */ q2[iout * q_dim + n1].ival = -q2[iout * q_dim + n1].ival; goto L350; } /* GAUSS-JORDAN ELIMINATION. */ L420: #ifdef DEBUG_CL1 output_msg (OUTPUT_MESSAGE, "Gauss Jordon %d\n", *iter); #endif if (*iter >= maxit) { *kode = 3; goto L590; } /* L430: */ #ifdef DEBUG_CL1 output_msg (OUTPUT_MESSAGE, "L430\n"); #endif ++(*iter); for (j = js; j < n1; ++j) { if (j != in) { q2[iout * q_dim + j].dval /= pivot; } } /* L440: */ for (j = js; j < n1; ++j) { if (j != in) { z = -q2[iout * q_dim + j].dval; for (i = 0; i < klm1; ++i) { if (i != iout) { q2[i * q_dim + j].dval += z * q2[i * q_dim + in].dval; } } /* L450: */ } } /* L460: */ #ifdef DEBUG_CL1 output_msg (OUTPUT_MESSAGE, "L460\n"); #endif tpivot = -pivot; for (i = 0; i < klm1; ++i) { if (i != iout) { q2[i * q_dim + in].dval /= tpivot; } } /* L470: */ q2[iout * q_dim + in].dval = 1. / pivot; ii = q2[iout * q_dim + n1].ival; q2[iout * q_dim + n1].ival = q2[klm1 * q_dim + in].ival; q2[klm1 * q_dim + in].ival = ii; ii = abs (ii); if (iu[ii - 1] == 0 || iu[cu_dim + ii - 1] == 0) { goto L240; } /* switch column */ for (i = 0; i < klm1; ++i) { z = q2[i * q_dim + in].dval; q2[i * q_dim + in].dval = q2[i * q_dim + js].dval; q2[i * q_dim + js].dval = z; } i = q2[klm1 * q_dim + in].ival; q2[klm1 * q_dim + in].ival = q2[klm1 * q_dim + js].ival; q2[klm1 * q_dim + js].ival = i; /* L480: */ ++js; goto L240; /* TEST FOR OPTIMALITY. */ L490: #ifdef DEBUG_CL1 output_msg (OUTPUT_MESSAGE, "L490\n"); #endif if (kforce == 0) { if (iphase == 1) { if (q2[klm * q_dim + n].dval <= toler) { goto L500; } #ifdef DEBUG_CL1 output_msg (OUTPUT_MESSAGE, "q2[klm1-1, n1-1] > *toler. %e\n", q2[(klm1 - 1) * q_dim + n1 - 1].dval); #endif *kode = 1; goto L590; } *kode = 0; goto L590; } if (iphase != 1 || q2[klm * q_dim + n].dval > toler) { kforce = 0; goto L240; } /* SET UP PHASE 2 COSTS. */ L500: #ifdef DEBUG_CL1 output_msg (OUTPUT_MESSAGE, "Set up phase 2 costs %d\n", *iter); #endif iphase = 2; for (j = 0; j < nklm; ++j) { cu[j] = 0.; } /* L510: */ for (j = n; j < nk; ++j) { cu[j] = 1.; } memcpy ((void *) &(cu[cu_dim]), (void *) &(cu[0]), (size_t) nklm * sizeof (LDBLE)); /* L520: */ for (i = 0; i < klm; ++i) { ii = q2[i * q_dim + n1].ival; if (ii <= 0) { if (iu[cu_dim - ii - 1] == 0) { continue; } cu[cu_dim - ii - 1] = 0.; } else { /* L530: */ if (iu[ii - 1] == 0) { continue; } cu[ii - 1] = 0.; } /* L540: */ ++ia; /* switch row */ memcpy ((void *) &(scratch[0]), (void *) &(q2[ia * q_dim]), (size_t) n2 * sizeof (LDBLE)); memcpy ((void *) &(q2[ia * q_dim]), (void *) &(q2[i * q_dim]), (size_t) n2 * sizeof (LDBLE)); memcpy ((void *) &(q2[i * q_dim]), (void *) &(scratch[0]), (size_t) n2 * sizeof (LDBLE)); /* L550: */ } /* L560: */ goto L160; /* PREPARE OUTPUT. */ L590: #ifdef DEBUG_CL1 output_msg (OUTPUT_MESSAGE, "L590\n"); #endif sum = 0.; for (j = 0; j < n; ++j) { x[j] = 0.; } /* L600: */ for (i = 0; i < klm; ++i) { res[i] = 0.; } /* L610: */ for (i = 0; i < klm; ++i) { ii = q2[i * q_dim + n1].ival; sn = 1.; if (ii < 0) { ii = -ii; sn = -1.; } if (ii <= n) { /* L620: */ x[ii - 1] = sn * q2[i * q_dim + n].dval; } else { /* L630: */ res[ii - n - 1] = sn * q2[i * q_dim + n].dval; if (ii >= n1 && ii <= nk) { /* * DBLE(Q(I,N1)) */ sum += q2[i * q_dim + n].dval; } } } /* L640: */ #ifdef DEBUG_CL1 output_msg (OUTPUT_MESSAGE, "L640\n"); #endif *error = sum; /* * Check calculation */ if ((check == 1) && (*kode == 0)) { check_toler = 10. * toler; /* * Check optimization constraints */ if (kode_arg == 1) { for (i = 0; i < k; i++) { if (res_arg[i] < 0.0) { if (res[i] > check_toler) { #ifdef CHECK_ERRORS output_msg (OUTPUT_MESSAGE, "\tCL1: optimization constraint not satisfied row %d, res %s, constraint %f.\n", row_name[row_back[i]], res[i], res_arg[i]); #endif *kode = 1; } } else if (res_arg[i] > 0.0) { if (res[i] < -check_toler) { #ifdef CHECK_ERRORS output_msg (OUTPUT_MESSAGE, "\tCL1: optimization constraint not satisfied row %s, res %e, constraint %f.\n", row_name[row_back[i]], res[i], res_arg[i]); #endif *kode = 1; } } } } /* * Check equalities */ for (i = k; i < k + l; i++) { if (fabs (res[i]) > check_toler) { #ifdef CHECK_ERRORS output_msg (OUTPUT_MESSAGE, "\tCL1: equality constraint not satisfied row %s, res %e, tolerance %e.\n", row_name[row_back[i]], res[i], check_toler); #endif *kode = 1; } } /* * Check inequalities */ for (i = k + l; i < k + l + m; i++) { if (res[i] < -check_toler) { #ifdef CHECK_ERRORS output_msg (OUTPUT_MESSAGE, "\tCL1: inequality constraint not satisfied row %s, res %e, tolerance %e.\n", row_name[row_back[i]], res[i], check_toler); #endif *kode = 1; } } /* * Check dissolution/precipitation constraints */ if (kode_arg == 1) { for (i = 0; i < n; i++) { if (x_arg[i] < 0.0) { if (x[i] > check_toler) { #ifdef CHECK_ERRORS output_msg (OUTPUT_MESSAGE, "\tCL1: dis/pre constraint not satisfied column %s, x %e, constraint %f.\n", col_name[col_back[i]], x[i], x_arg[i]); #endif *kode = 1; } } else if (x_arg[i] > 0.0) { if (x[i] < -check_toler) { #ifdef CHECK_ERRORS output_msg (OUTPUT_MESSAGE, "\tCL1: dis/pre constraint not satisfied column %s, x %e, constraint %f.\n", col_name[col_back[i]], x[i], x_arg[i]); #endif *kode = 1; } } } } if (*kode == 1) { output_msg (OUTPUT_MESSAGE, "\n\tCL1: Roundoff errors in optimization.\n\t Try using -multiple_precision in INVERSE_MODELING\n"); } } return 0; } void cl1_space (int check, int n2d, int klm, int nklmd) { if (check == 1) { if (x_arg == NULL) { x_arg = (LDBLE *) PHRQ_malloc ((size_t) (n2d * sizeof (LDBLE))); } else if (n2d > x_arg_max) { x_arg = (LDBLE *) PHRQ_realloc (x_arg, (size_t) (n2d * sizeof (LDBLE))); x_arg_max = n2d; } if (x_arg == NULL) malloc_error (); zero_double(x_arg, n2d); if (res_arg == NULL) { res_arg = (LDBLE *) PHRQ_malloc ((size_t) ((klm) * sizeof (LDBLE))); } else if (klm > res_arg_max) { res_arg = (LDBLE *) PHRQ_realloc (res_arg, (size_t) ((klm) * sizeof (LDBLE))); res_arg_max = klm; } if (res_arg == NULL) malloc_error (); zero_double(res_arg, klm); } /* Make scratch space */ if (scratch == NULL) { scratch = (LDBLE *) PHRQ_malloc ((size_t) nklmd * sizeof (LDBLE)); } else if (nklmd > scratch_max) { scratch = (LDBLE *) PHRQ_realloc (scratch, (size_t) nklmd * sizeof (LDBLE)); scratch_max = nklmd; } if (scratch == NULL) malloc_error (); zero_double(scratch, nklmd); }
22.814159
109
0.516195
[ "vector" ]
22f0219844e05a3cc881b8ba3c45f08b8feb90ce
649
h
C
src/Rectangle.h
luqyluqe/Math
3d658eaf0191ef841c9d3ae0f120865cb383993a
[ "MIT" ]
null
null
null
src/Rectangle.h
luqyluqe/Math
3d658eaf0191ef841c9d3ae0f120865cb383993a
[ "MIT" ]
null
null
null
src/Rectangle.h
luqyluqe/Math
3d658eaf0191ef841c9d3ae0f120865cb383993a
[ "MIT" ]
null
null
null
#ifndef MATH_RECTANGLE_H #define MATH_RECTANGLE_H #include "MathDefines.h" #include "Vector.h" #include "Circle.h" BEGIN_NAMESPACE_MATH class Rectangle { public: //Constructor Rectangle(double x,double y,double width,double height); //Accessor double x()const; double y()const; double width()const; double height()const; //Judgement bool contain(const Vector& point)const; bool overlap(const Circle& circle)const; //Arithmetic double overlapArea(const Circle& cirle)const; private: double _x; double _y; double _width; double _height; }; END_NAMESPACE_MATH #endif
16.641026
60
0.687211
[ "vector" ]
fe00dcd35e01251650f8ec6b5538bbd2fc8c7012
4,319
h
C
2004/samples/database/ARXDBG/Inc/ArxDbgEventReactor.h
kevinzhwl/ObjectARXMod
ef4c87db803a451c16213a7197470a3e9b40b1c6
[ "MIT" ]
1
2021-06-25T02:58:47.000Z
2021-06-25T02:58:47.000Z
2004/samples/database/ARXDBG/Inc/ArxDbgEventReactor.h
kevinzhwl/ObjectARXMod
ef4c87db803a451c16213a7197470a3e9b40b1c6
[ "MIT" ]
null
null
null
2004/samples/database/ARXDBG/Inc/ArxDbgEventReactor.h
kevinzhwl/ObjectARXMod
ef4c87db803a451c16213a7197470a3e9b40b1c6
[ "MIT" ]
3
2020-05-23T02:47:44.000Z
2020-10-27T01:26:53.000Z
// // (C) Copyright 1998-1999 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // // #ifndef ARXDBGEVENTREACTOR_H #define ARXDBGEVENTREACTOR_H /**************************************************************************** ** ** CLASS ArxDbgEventReactor: ** ** **jma ** *************************************/ class ArxDbgEventReactor : public AcRxEventReactor { public: ACRX_DECLARE_MEMBERS(ArxDbgEventReactor); ArxDbgEventReactor(); virtual ~ArxDbgEventReactor(); // messages that are sent by notification virtual void dwgFileOpened(AcDbDatabase* pDwg, char* fileName); virtual void initialDwgFileOpenComplete(AcDbDatabase* pDwg); virtual void databaseConstructed(AcDbDatabase*); virtual void databaseToBeDestroyed(AcDbDatabase* pDwg); virtual void beginSave(AcDbDatabase* pDwg, const char* pIntendedName); virtual void saveComplete(AcDbDatabase* pDwg, const char* pActualName); virtual void abortSave(AcDbDatabase* pDwg); virtual void beginDxfIn(AcDbDatabase* db); virtual void abortDxfIn(AcDbDatabase* db); virtual void dxfInComplete(AcDbDatabase* db); virtual void beginDxfOut(AcDbDatabase* pDwg); virtual void abortDxfOut(AcDbDatabase* pDwg); virtual void dxfOutComplete(AcDbDatabase* pDwg); virtual void beginInsert(AcDbDatabase* pTo, const char* pBlockName, AcDbDatabase* pFrom); virtual void beginInsert(AcDbDatabase* pTo, const AcGeMatrix3d& xform, AcDbDatabase* pFrom); virtual void otherInsert(AcDbDatabase* pTo, AcDbIdMapping& idMap, AcDbDatabase* pFrom); virtual void abortInsert(AcDbDatabase* pTo); virtual void endInsert(AcDbDatabase* pTo); virtual void wblockNotice(AcDbDatabase* pDb); virtual void beginWblock(AcDbDatabase* pTo, AcDbDatabase* pFrom, const AcGePoint3d*& insertionPoint); virtual void beginWblock(AcDbDatabase* pTo, AcDbDatabase* pFrom, AcDbObjectId blockId); virtual void beginWblock(AcDbDatabase* pTo, AcDbDatabase* pFrom); virtual void otherWblock(AcDbDatabase* pTo, AcDbIdMapping& pIdMap, AcDbDatabase* pFrom); virtual void abortWblock(AcDbDatabase* pTo); virtual void endWblock(AcDbDatabase* pTo); virtual void beginWblockObjects(AcDbDatabase* db, AcDbIdMapping& map); virtual void beginDeepClone(AcDbDatabase* pTo, AcDbIdMapping& pIdMap); virtual void beginDeepCloneXlation(AcDbIdMapping& pIdMap, Acad::ErrorStatus* pRetStatus); virtual void abortDeepClone(AcDbIdMapping& pIdMap); virtual void endDeepClone(AcDbIdMapping& pIdMap); virtual void partialOpenNotice(AcDbDatabase* pDb); bool showDetails() const; void setShowDetails(bool showThem); private: // data members bool m_showDetails; // helper functions void printReactorMessage(LPCTSTR event) const; void printReactorMessage(LPCTSTR event, AcDbDatabase* pDb) const; void printReactorMessage(LPCTSTR event, AcDbDatabase* pTo, AcDbDatabase* pFrom) const; void printReactorMessage(LPCTSTR event, const AcDbObjectId& objId) const; // outlawed functions ArxDbgEventReactor(const& ArxDbgEventReactor); ArxDbgEventReactor& operator=(const& ArxDbgEventReactor); }; #endif // ARXDBGEVENTREACTOR_H
41.133333
109
0.697847
[ "object" ]
fe11ef4f68ea1b825ec21a7c13247b969adef466
307
h
C
GettersSetters-OBJC/GettersSetters-OBJC/Vehicle.h
hummatli/objective-c-sample-apps
376efe5afe177c06c16fb7bf5a4114377c410887
[ "MIT" ]
1
2017-07-27T12:34:03.000Z
2017-07-27T12:34:03.000Z
GettersSetters-OBJC/GettersSetters-OBJC/Vehicle.h
hummatli/objective-c-sample-apps
376efe5afe177c06c16fb7bf5a4114377c410887
[ "MIT" ]
null
null
null
GettersSetters-OBJC/GettersSetters-OBJC/Vehicle.h
hummatli/objective-c-sample-apps
376efe5afe177c06c16fb7bf5a4114377c410887
[ "MIT" ]
null
null
null
// // Vehicle.h // GettersSetters-OBJC // // Created by Settar Hummetli on 7/28/17. // Copyright © 2017 Settar Hummetli. All rights reserved. // #import <Foundation/Foundation.h> @interface Vehicle : NSObject @property (nonatomic) long odometer; @property (nonatomic, strong) NSString *model; @end
17.055556
58
0.713355
[ "model" ]
fe13ec99587de100dde730da2dc0e0868d1ab95e
1,143
h
C
include/dg/SystemDependenceGraph/DGBBlock.h
bloodycoder/dg
4d261fc688013bcc6d35284315b7d0e861f00b4b
[ "MIT" ]
null
null
null
include/dg/SystemDependenceGraph/DGBBlock.h
bloodycoder/dg
4d261fc688013bcc6d35284315b7d0e861f00b4b
[ "MIT" ]
null
null
null
include/dg/SystemDependenceGraph/DGBBlock.h
bloodycoder/dg
4d261fc688013bcc6d35284315b7d0e861f00b4b
[ "MIT" ]
null
null
null
#ifndef DG_DGBBLOCK_H_ #define DG_DGBBLOCK_H_ #include <assert.h> #include "DGNode.h" namespace dg { namespace sdg { class DependenceGraph; /// // A basic block of a dependence graph. // Basic blocks are useful even in dependence graph in order // to cluster nodes with the same control dependence. class DGBBlock { friend class DependenceGraph; using NodesTy = std::vector<DGNode *>; unsigned _id{0}; // SDG to which this dependence graph belongs DependenceGraph *_dg{nullptr}; NodesTy _nodes; DGBBlock(unsigned id, DependenceGraph *g) : _id(id), _dg(g) { assert(id > 0); } public: unsigned getID() const { return _id; } DependenceGraph *getDG() { return _dg; } const DependenceGraph *getDG() const { return _dg; } NodesTy& getNodes() { return _nodes; } const NodesTy& getNodes() const { return _nodes; } void append(DGNode *n) { assert(n && "nullptr passed as node"); assert(n->getBBlock() == nullptr && "BBlock already set"); _nodes.push_back(n); n->setBBlock(this); } }; } // namespace sdg } // namespace dg #endif // DG_DGBBLOCK_H_
22.411765
66
0.658793
[ "vector" ]
fe2673a39555aedfb8f964897641d1981f2d353e
5,447
h
C
Utils.h
CheckersGuy/Network
24e78c14ab7df6ae87d1aea0fbd749232d88ccfc
[ "MIT" ]
null
null
null
Utils.h
CheckersGuy/Network
24e78c14ab7df6ae87d1aea0fbd749232d88ccfc
[ "MIT" ]
null
null
null
Utils.h
CheckersGuy/Network
24e78c14ab7df6ae87d1aea0fbd749232d88ccfc
[ "MIT" ]
null
null
null
// // Created by root on 14.03.20. // #ifndef NETWORK_UTILS_H #define NETWORK_UTILS_H #include <algorithm> #include <cmath> namespace Utils { struct HyperBolic { template<typename Iter, typename Out> static void apply(Iter begin, Iter end, Out out) { using Type = typename std::iterator_traits<Iter>::value_type; static_assert(std::is_same<float, Type>::value); std::transform(begin, end, out, [](float value) { return std::tanh(value); }); } template<typename Iter, typename Out> static void apply_deriv(Iter begin, Iter end, Out out) { using Type = typename std::iterator_traits<Iter>::value_type; static_assert(std::is_same<float, Type>::value); std::transform(begin, end, out, [](float value) { float sig = std::tanh(value); return 1.0f - sig * sig; }); } }; struct Sigmoid { template<typename Iter, typename Out> static void apply(Iter begin, Iter end, Out out) { using Type = typename std::iterator_traits<Iter>::value_type; static_assert(std::is_same<float, Type>::value); std::transform(begin, end, out, [](float value) { float ret = 1.0f / (1.0f + std::exp(-value)); return ret; }); } template<typename Iter, typename Out> static void apply_deriv(Iter begin, Iter end, Out out) { using Type = typename std::iterator_traits<Iter>::value_type; static_assert(std::is_same<float, Type>::value); std::transform(begin, end, out, [](float value) { float sig = 1.0f / (1.0f + std::exp(-value)); return sig * (1.0f - sig); }); } }; struct SoftMax { template<typename Iter, typename Out> static void apply(Iter begin, Iter end, Out out) { using Type = typename std::iterator_traits<Iter>::value_type; static_assert(std::is_same<float, Type>::value); auto distance = end - begin; float max_value = *std::max_element(begin, end); float summe = 0.0f; std::transform(begin, end, out, [&summe, max_value](float value) { float ex = std::exp(value - max_value); summe += ex; return ex; }); std::transform(out, out + distance, out, [summe](float value) { return value / summe; }); } template<typename Iter, typename Out> static void apply_deriv(Iter begin, Iter end, Out out) { } }; struct Relu { template<typename Iter, typename Out> static void apply(Iter begin, Iter end, Out out) { using Type = typename std::iterator_traits<Iter>::value_type; static_assert(std::is_same<float, Type>::value); std::transform(begin, end, out, [](float value) { return std::max(0.0f, value); }); } template<typename Iter, typename Out> static void apply_deriv(Iter begin, Iter end, Out out) { using Type = typename std::iterator_traits<Iter>::value_type; static_assert(std::is_same<float, Type>::value); std::transform(begin, end, out, [](float value) { return (value > 0.0f) ? 1.0f : 0.0f; }); } }; struct SquareLoss { template<typename Iter, typename Iter2> static float apply(Iter net_output, Iter net_end, Iter2 act_output) { float summe = 0; auto out_iter = act_output; for (auto it = net_output; it != net_end; ++it) { float net = *it; float out = *out_iter; summe += (net - out) * (net - out); out_iter++; } return summe / 2.0f; } template<typename Iter, typename Iter2, typename OutIter> static void apply_deriv(Iter net_output, Iter net_end, Iter2 act_output, OutIter out) { auto a_out = act_output; for (auto it = net_output; it != net_end; ++it) { float p = *a_out; float y = *it; *out = y - p; out++; a_out++; } } }; struct CrossLoss { template<typename Iter, typename Iter2> static float apply(Iter net_output, Iter net_end, Iter2 act_output) { float summe = 0; auto out_iter = act_output; for (auto it = net_output; it != net_end; ++it) { float net = *it; float out = *out_iter; summe += (net - out) * (net - out); out_iter++; } return summe / 2.0f; } template<typename Iter, typename Iter2, typename OutIter> static void apply_deriv(Iter net_output, Iter net_end, Iter2 act_output, OutIter out) { auto a_out = act_output; for (auto it = net_output; it != net_end; ++it) { float p = *a_out; float y = *it; *out = y - p; out++; a_out++; } } }; } #endif //NETWORK_UTILS_H
31.304598
95
0.513126
[ "transform" ]
fe283876dbdf258f420e0d8cbb3b15371bf40dbd
1,070
h
C
util/SimpleTestServer.h
erikleitch/cpputil
6dbd4bdbaaa60d911d166b68fdad6af6afd04963
[ "MIT" ]
null
null
null
util/SimpleTestServer.h
erikleitch/cpputil
6dbd4bdbaaa60d911d166b68fdad6af6afd04963
[ "MIT" ]
null
null
null
util/SimpleTestServer.h
erikleitch/cpputil
6dbd4bdbaaa60d911d166b68fdad6af6afd04963
[ "MIT" ]
null
null
null
// $Id: $ #ifndef GCP_UTIL_SIMPLETESTSERVER_H #define GCP_UTIL_SIMPLETESTSERVER_H /** * @file SimpleTestServer.h * * Tagged: Fri May 26 12:13:05 PDT 2017 * * @version: $Revision: $, $Date: $ * * @author /bin/bash: username: command not found */ #include "gcp/util/Server.h" #include "gcp/util/SimpleTestData.h" namespace gcp { namespace util { class SimpleTestServer : public Server { public: /** * Constructor. */ SimpleTestServer(bool spawn, unsigned listenPort); /** * Destructor. */ virtual ~SimpleTestServer(); void acceptClientAction(); private: SimpleTestData data_; std::vector<unsigned char> bytes_; void readClientData(NetHandler& handler); virtual void processClientData(); }; // End class SimpleTestServer } // End namespace util } // End namespace gcp #endif // End #ifndef GCP_UTIL_SIMPLETESTSERVER_H
20.188679
53
0.566355
[ "vector" ]
fe2e8752edd79f181b36e266600fc926347ab48f
1,965
h
C
src/gadgets/subspace.h
imdea-software/legosnark
3f4a137c050371cf4dd51c3fe2d46a8eee60f8ee
[ "Apache-2.0", "MIT" ]
23
2019-09-09T15:11:48.000Z
2022-02-11T06:11:10.000Z
src/gadgets/subspace.h
imdea-software/legosnark
3f4a137c050371cf4dd51c3fe2d46a8eee60f8ee
[ "Apache-2.0", "MIT" ]
1
2020-10-08T04:19:50.000Z
2020-10-08T20:37:13.000Z
src/gadgets/subspace.h
imdea-software/legosnark
3f4a137c050371cf4dd51c3fe2d46a8eee60f8ee
[ "Apache-2.0", "MIT" ]
2
2021-05-29T09:13:29.000Z
2021-11-11T06:50:11.000Z
#ifndef GADGETS_SUBSPACE_H #define GADGETS_SUBSPACE_H #include "matrix.h" #include "snark.h" #include "commit.h" #include "interp.h" struct SubspaceRel { vector<ColG1> M; vector<ColFr> sM; int l; // # of rows int t; // # of cols size_t C_precomp_sz = 0; Interpolator *interp; bool scalarsAvailable = true; // for efficient keygen when possible SubspaceRel() {} SubspaceRel &withNRows(int _l) { l = _l; return *this; } SubspaceRel &withNCols(int _t) { t = _t; return *this; } SubspaceRel &withMatrix(const vector<ColG1> &_M) { M = _M; return *this; } SubspaceRel &withoutScalars() { scalarsAvailable = false; return *this; } SubspaceRel(int _l, int _t, vector<ColFr> _sM, const vector<ColG1> &_M, size_t _C_precomp_sz, Interpolator *_interp) : l(_l), t(_t), sM(_sM), M(_M), interp(_interp), C_precomp_sz(_C_precomp_sz) { } }; struct SubspaceKey { const SubspaceRel *rel; vector<LG1> P; vector<LG2> C; vector<G2_precomp<def_ec>> C_precomp; LG2 a; G2_precomp<def_ec> a_precomp; void print_size() { fmt::print("Size of subspace's PK: {} G1 \n", P.size() ); fmt::print("Size of subspace's VK: {} G2 \n", 4+1 ); // XXX } }; typedef LG1 SubspacePf; // This class proves "x = Mw" for witness w class SubspaceSnark : public Snark<SubspaceRel, SubspaceKey, SubspacePf, vector<LFr>, vector<LG1>> { public: SubspaceSnark() : Snark<SubspaceRel, SubspaceKey, SubspacePf, vector<LFr>, vector<LG1>>() { } virtual SubspaceKey* keygen(const SubspaceRel *rel) override; // NB: In method prove the ScalarVec is a col vector virtual SubspacePf* prove(const SubspaceKey *crs, const vector<LFr> &) override; virtual bool verify(const SubspaceKey *crs, const vector<LG1> &x, const SubspacePf *pf) override; bool verifyLin3or4(const SubspaceKey *crs, const vector<LG1> &cs, const Fqk<def_ec> *aux_precomp, const SubspacePf *pf); }; #endif
21.358696
122
0.671756
[ "vector" ]
fe339800ea765c248bb4f1d7af6beef79fdc315e
896
h
C
minimal-examples/embedded/esp32/esp-c3dev/main/i2c.h
horchi/libwebsockets
e1a73c42096a9f94617a25440501d7adc4abbd9f
[ "Apache-2.0" ]
3,539
2015-01-02T18:31:36.000Z
2022-03-30T09:56:47.000Z
minimal-examples/embedded/esp32/esp-c3dev/main/i2c.h
horchi/libwebsockets
e1a73c42096a9f94617a25440501d7adc4abbd9f
[ "Apache-2.0" ]
2,393
2015-01-06T08:43:52.000Z
2022-03-31T14:09:09.000Z
minimal-examples/embedded/esp32/esp-c3dev/main/i2c.h
horchi/libwebsockets
e1a73c42096a9f94617a25440501d7adc4abbd9f
[ "Apache-2.0" ]
1,483
2015-01-04T11:33:23.000Z
2022-03-30T17:45:00.000Z
/* * Generic i2c ops * * These ops always appear first in an implementation-specific * object, so the generic ops can be cast to the implementation- * specific object in the handlers. * * Written in 2010-2020 by Andy Green <andy@warmcat.com> * * This file is made available under the Creative Commons CC0 1.0 * Universal Public Domain Dedication. */ #if !defined(__LWS_I2C_H__) #define __LWS_I2C_H__ #include <stdint.h> #include <stddef.h> typedef struct lws_i2c_ops { int (*start)(struct lws_i2c_ops *ctx); void (*stop)(struct lws_i2c_ops *ctx); int (*write)(struct lws_i2c_ops *ctx, uint8_t data); int (*read)(struct lws_i2c_ops *ctx); void (*set_ack)(struct lws_i2c_ops *octx, int ack); } lws_i2c_ops_t; int lws_i2c_command(lws_i2c_ops_t *ctx, uint8_t ads, uint8_t c); int lws_i2c_command_list(lws_i2c_ops_t *ctx, uint8_t ads, const uint8_t *buf, size_t len); #endif
24.888889
86
0.736607
[ "object" ]
fe414508de695ebe356cf6cebc1ad99abee0c46d
1,922
h
C
Cgeom/geom_shapeset.h
victorliu/CAD2D
102f96e959f7ed8a1cc7b940b1f74d72c985c5d3
[ "BSD-3-Clause" ]
null
null
null
Cgeom/geom_shapeset.h
victorliu/CAD2D
102f96e959f7ed8a1cc7b940b1f74d72c985c5d3
[ "BSD-3-Clause" ]
null
null
null
Cgeom/geom_shapeset.h
victorliu/CAD2D
102f96e959f7ed8a1cc7b940b1f74d72c985c5d3
[ "BSD-3-Clause" ]
null
null
null
#ifndef GEOM_SHAPESET_H_INCLUDED #define GEOM_SHAPESET_H_INCLUDED #include <Cgeom/geom_shapes.h> // A shapeset is a collection of shapes. This object only stores pointers // to shapes without managing memory. typedef struct geom_shapeset2d_struct* geom_shapeset2d; typedef struct geom_shapeset3d_struct* geom_shapeset3d; #define GEOM_SHAPESET2D_FLAG_UNBOUNDED 1 #define GEOM_SHAPESET3D_FLAG_UNBOUNDED 1 geom_shapeset2d geom_shapeset2d_new(); geom_shapeset3d geom_shapeset3d_new(); void geom_shapeset2d_destroy(geom_shapeset2d ss); void geom_shapeset3d_destroy(geom_shapeset3d ss); int geom_shapeset2d_set_lattice(geom_shapeset2d ss, const double lattice[4]); int geom_shapeset3d_set_lattice(geom_shapeset3d ss, const double lattice[9]); // returns index of shape int geom_shapeset2d_add(geom_shapeset2d ss, geom_shape2d *s); int geom_shapeset3d_add(geom_shapeset3d ss, geom_shape3d *s); void geom_shapeset2d_finalize(geom_shapeset2d ss); void geom_shapeset3d_finalize(geom_shapeset3d ss); unsigned int geom_shapeset2d_size(geom_shapeset2d ss); unsigned int geom_shapeset3d_size(geom_shapeset3d ss); geom_shape2d* geom_shapeset2d_index(geom_shapeset2d ss, int index); geom_shape3d* geom_shapeset3d_index(geom_shapeset3d ss, int index); int geom_shapeset2d_index_aabb(geom_shapeset2d ss, int index, geom_aabb2d *box); int geom_shapeset3d_index_aabb(geom_shapeset3d ss, int index, geom_aabb3d *box); // Returns item of largest index int geom_shapeset2d_query_pt(geom_shapeset2d ss, const double p[2]); int geom_shapeset3d_query_pt(geom_shapeset3d ss, const double p[3]); int geom_shapeset2d_foreach( geom_shapeset2d ss, int (*func)(geom_shape2d *s, const geom_aabb2d *box, unsigned int flags, void *data), void *data ); int geom_shapeset3d_foreach( geom_shapeset3d ss, int (*func)(geom_shape3d *s, const geom_aabb3d *box, unsigned int flags, void *data), void *data ); #endif // GEOM_SHAPESET_H_INCLUDED
34.321429
86
0.827263
[ "object", "shape" ]
fe4b9bfae1537709af8382045155a6a64a8c5b28
45,085
c
C
src/kilo.c
akkartik/teliva
1316940f2583c6a6da1951de14074d2c9cabf9f5
[ "MIT" ]
142
2021-11-06T09:52:47.000Z
2022-03-15T21:50:08.000Z
src/kilo.c
akkartik/teliva
1316940f2583c6a6da1951de14074d2c9cabf9f5
[ "MIT" ]
1
2021-12-02T15:24:32.000Z
2021-12-06T21:35:39.000Z
src/kilo.c
akkartik/teliva
1316940f2583c6a6da1951de14074d2c9cabf9f5
[ "MIT" ]
1
2022-03-29T21:46:36.000Z
2022-03-29T21:46:36.000Z
/* Based on https://github.com/antirez/kilo * * ----------------------------------------------------------------------- * * Copyright (C) 2016 Salvatore Sanfilippo <antirez at gmail dot com> * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #define KILO_VERSION "0.0.1" #include <assert.h> #ifdef __NetBSD__ #include <curses.h> #else #include <ncurses.h> #endif #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <errno.h> #include <string.h> #include <ctype.h> #include <time.h> #include <sys/types.h> #include <sys/time.h> #include <unistd.h> #include <fcntl.h> #include "lua.h" #include "teliva.h" /* Syntax highlight types */ #define HL_NORMAL 0 #define HL_NONPRINT 1 #define HL_COMMENT 2 /* Single line comment. */ #define HL_MLCOMMENT 3 /* Multi-line comment. */ #define HL_KEYWORD1 4 #define HL_KEYWORD2 5 #define HL_STRING 6 #define HL_NUMBER 7 #define HL_MATCH 8 /* Search match. */ #define HL_SELECTABLE 9 #define HL_SELECTABLE_BORDER 10 struct editorSyntax { char **keywords; char *singleline_comment_start; char *multiline_comment_start; char *multiline_comment_end; char *selectable_start; char *selectable_end; }; /* This structure represents a single line of the file we are editing. */ typedef struct erow { int idx; /* Row index in the file, zero-based. */ int size; /* Size of the row, excluding the null term. */ int rsize; /* Size of the rendered row. */ char *chars; /* Row content. */ char *render; /* Row content "rendered" for screen (for TABs). */ unsigned char *hl; /* Syntax highlight type for each character in render.*/ int hl_oc; /* Row had open comment at end in last syntax highlight check. */ } erow; typedef struct hlcolor { int r,g,b; } hlcolor; #define LINE_NUMBER_SPACE 4 #define MENU_SPACE 1 #define CALLERS_SPACE 2 struct editorConfig { int cx,cy; /* Cursor x and y position in characters relative to top-left of viewport */ int startcol, cols; /* viewport column bounds */ int startrow, endrow; /* viewport row bounds */ int rowoff; /* Offset of row displayed. */ int coloff; /* Offset of column displayed. */ int numrows; /* Number of rows */ erow *row; /* Rows */ int dirty; /* File modified but not saved. */ char *filename; /* Currently open filename */ struct editorSyntax *syntax; /* Current syntax highlight, or NULL. */ }; static struct editorConfig E; /* =========================== Syntax highlights DB ========================= * * In order to add a new syntax, define two arrays with a list of file name * matches and keywords. The file name matches are used in order to match * a given syntax with a given file name: if a match pattern starts with a * dot, it is matched as the last past of the filename, for example ".c". * Otherwise the pattern is just searched inside the filenme, like "Makefile"). * * The list of keywords to highlight is just a list of words, however if they * a trailing '|' character is added at the end, they are highlighted in * a different color, so that you can have two different sets of keywords. * * Finally add a stanza in the HLDB global variable with two two arrays * of strings. * * The characters for single and multi line comments must be exactly two * and must be provided as well (see the C language example). * * There is no support to highlight patterns currently. */ /* Lua */ char *Lua_HL_keywords[] = { /* keywords */ "do", "end", "function", "return", "require", "local", "if", "then", "else", "elseif", "while", "for", "repeat", "until", "break", "and", "or", "not", "in", /* types */ "nil|", "false|", "true|", NULL }; struct editorSyntax LuaSyntax = { Lua_HL_keywords, "--", /* line comment */ "--[[", "--]]", /* multiline comment */ NULL, NULL /* no selectables */ }; /* Prose */ struct editorSyntax ProseSyntax = { NULL, /* no keywords */ NULL, /* no line comment */ NULL, NULL, /* no multiline comment */ "[[", "]]" /* "selectables" */ }; #define HLDB_ENTRIES (sizeof(HLDB)/sizeof(HLDB[0])) /* ====================== Syntax highlight color scheme ==================== */ static int is_separator(int c) { return c == '\0' || isspace(c) || strchr(",.()+-/*=~%[];",c) != NULL; } /* Return true if the specified row last char is part of a multi line comment * that starts at this row or at one before, and does not end at the end * of the row but spawns to the next row. */ static int editorRowHasOpenComment(erow *row, char *mce) { if (row->hl && row->rsize && row->hl[row->rsize-1] == HL_MLCOMMENT && (row->rsize < strlen(mce) || strcmp(&row->render[row->rsize-strlen(mce)], mce) != 0)) return 1; return 0; } /* Set every byte of row->hl (that corresponds to every character in the line) * to the right syntax highlight type (HL_* defines). */ static void editorUpdateSyntax(erow *row) { row->hl = realloc(row->hl,row->rsize); memset(row->hl,HL_NORMAL,row->rsize); if (E.syntax == NULL) return; /* No syntax, everything is HL_NORMAL. */ int i, prev_sep, in_string, in_comment, in_selectable; char *p; char **keywords = E.syntax->keywords; char *scs = E.syntax->singleline_comment_start; char *mcs = E.syntax->multiline_comment_start; char *mce = E.syntax->multiline_comment_end; char *ss = E.syntax->selectable_start; char *se = E.syntax->selectable_end; /* Point to the first non-space char. */ p = row->render; i = 0; /* Current char offset */ while(*p && isspace(*p)) { p++; i++; } prev_sep = 1; /* Tell the parser if 'i' points to start of word. */ in_string = 0; /* Are we inside "" or '' ? */ in_comment = 0; /* Are we inside multi-line comment? */ in_selectable = 0; /* Are we inside [[]] in prose? */ /* If the previous line has an open comment, this line starts * with an open comment state. */ if (row->idx > 0 && editorRowHasOpenComment(&E.row[row->idx-1], mce)) in_comment = 1; while(*p) { /* Handle multi line comments. */ if (mcs && mce) { if (in_comment) { row->hl[i] = HL_MLCOMMENT; if (starts_with(p, mce)) { memset(&row->hl[i],HL_MLCOMMENT, strlen(mce)); p += strlen(mce); i += strlen(mce); in_comment = 0; prev_sep = 1; continue; } else { prev_sep = 0; p++; i++; continue; } } else if (starts_with(p, mcs)) { memset(&row->hl[i],HL_MLCOMMENT, strlen(mcs)); p += strlen(mcs); i += strlen(mcs); in_comment = 1; prev_sep = 0; continue; } } /* Handle single-line comments. */ if (scs && prev_sep && starts_with(p, scs)) { /* From here to end is a comment */ memset(row->hl+i,HL_COMMENT,row->rsize-i); return; } /* Handle selectable widgets */ if (ss && se) { if (in_selectable) { if (starts_with(p, se)) { memset(&row->hl[i],HL_SELECTABLE_BORDER, strlen(se)); p += strlen(se); i += strlen(se); in_selectable = 0; prev_sep = 1; continue; } else { row->hl[i] = HL_SELECTABLE; prev_sep = 0; p++; i++; continue; } } else if (starts_with(p, ss)) { memset(&row->hl[i],HL_SELECTABLE_BORDER, strlen(ss)); p += strlen(ss); i += strlen(ss); in_selectable = 1; prev_sep = 0; continue; } } /* Handle "" and '' */ if (E.syntax == &LuaSyntax) { // obscene hack if (in_string) { row->hl[i] = HL_STRING; if (*p == '\\' && *(p+1)) { row->hl[i+1] = HL_STRING; p += 2; i += 2; prev_sep = 0; continue; } if (*p == in_string) in_string = 0; p++; i++; continue; } else { if (*p == '"' || *p == '\'') { in_string = *p; row->hl[i] = HL_STRING; p++; i++; prev_sep = 0; continue; } } } /* Handle non printable chars. */ if (!isprint(*p)) { row->hl[i] = HL_NONPRINT; p++; i++; prev_sep = 0; continue; } /* Handle numbers */ if ((isdigit(*p) && (prev_sep || row->hl[i-1] == HL_NUMBER)) || (*p == '.' && i > 0 && row->hl[i-1] == HL_NUMBER)) { row->hl[i] = HL_NUMBER; p++; i++; prev_sep = 0; continue; } /* Handle keywords and lib calls */ if (keywords && prev_sep) { int j; int ileft = row->rsize-i; for (j = 0; keywords[j]; j++) { int klen = strlen(keywords[j]); int kw2 = keywords[j][klen-1] == '|'; if (kw2) klen--; if (klen <= ileft && !memcmp(p,keywords[j],klen) && is_separator(*(p+klen))) { /* Keyword */ memset(row->hl+i,kw2 ? HL_KEYWORD2 : HL_KEYWORD1,klen); p += klen; i += klen; break; } } if (keywords[j] != NULL) { prev_sep = 0; continue; /* We had a keyword match */ } } /* Not special chars */ prev_sep = is_separator(*p); p++; i++; } /* Propagate syntax change to the next row if the open comment * state changed. This may recursively affect all the following rows * in the file. */ int oc = editorRowHasOpenComment(row, mce); if (row->hl_oc != oc && row->idx+1 < E.numrows) editorUpdateSyntax(&E.row[row->idx+1]); row->hl_oc = oc; } /* Maps syntax highlight token types to terminal colors. */ static int editorSyntaxToColorPair(int hl) { switch(hl) { case HL_COMMENT: case HL_MLCOMMENT: return COLOR_PAIR_LUA_COMMENT; case HL_KEYWORD1: return COLOR_PAIR_LUA_KEYWORD; case HL_KEYWORD2: return COLOR_PAIR_LUA_CONSTANT; case HL_STRING: return COLOR_PAIR_LUA_CONSTANT; case HL_NUMBER: return COLOR_PAIR_LUA_CONSTANT; case HL_MATCH: return COLOR_PAIR_MATCH; case HL_SELECTABLE: return COLOR_PAIR_SELECTABLE; case HL_SELECTABLE_BORDER: return COLOR_PAIR_FADE; default: return COLOR_PAIR_NORMAL; } } /* ======================= Editor rows implementation ======================= */ /* Update the rendered version and the syntax highlight of a row. */ static void editorUpdateRow(erow *row) { unsigned int tabs = 0, nonprint = 0; int j, idx; /* Create a version of the row we can directly print on the screen, * respecting tabs, substituting non printable characters with '?'. */ free(row->render); for (j = 0; j < row->size; j++) if (row->chars[j] == TAB) tabs++; unsigned long long allocsize = (unsigned long long) row->size + tabs*8 + nonprint*9 + 1; if (allocsize > UINT32_MAX) { printf("Some line of the edited file is too long for kilo\n"); exit(1); } row->render = malloc(row->size + tabs*8 + nonprint*9 + 1); idx = 0; for (j = 0; j < row->size; j++) { if (row->chars[j] == TAB) { row->render[idx++] = ' '; while((idx+1) % 8 != 0) row->render[idx++] = ' '; } else { row->render[idx++] = row->chars[j]; } } row->rsize = idx; row->render[idx] = '\0'; /* Update the syntax highlighting attributes of the row. */ editorUpdateSyntax(row); } /* Insert a row at the specified position, shifting the other rows on the bottom * if required. */ static void editorInsertRow(int at, char *s, size_t len) { if (at > E.numrows) return; E.row = realloc(E.row,sizeof(erow)*(E.numrows+1)); if (at != E.numrows) { memmove(E.row+at+1,E.row+at,sizeof(E.row[0])*(E.numrows-at)); for (int j = at+1; j <= E.numrows; j++) E.row[j].idx++; } E.row[at].size = len; E.row[at].chars = malloc(len+1); memcpy(E.row[at].chars,s,len+1); E.row[at].hl = NULL; E.row[at].hl_oc = 0; E.row[at].render = NULL; E.row[at].rsize = 0; E.row[at].idx = at; editorUpdateRow(E.row+at); E.numrows++; E.dirty++; } /* Free row's heap allocated stuff. */ static void editorFreeRow(erow *row) { free(row->render); free(row->chars); free(row->hl); } /* Remove the row at the specified position, shifting the remaining up. */ static void editorDelRow(int at) { erow *row; if (at >= E.numrows) return; row = E.row+at; editorFreeRow(row); memmove(E.row+at,E.row+at+1,sizeof(E.row[0])*(E.numrows-at-1)); for (int j = at; j < E.numrows-1; j++) E.row[j].idx--; E.numrows--; E.dirty++; } void clearEditor(void) { E.cx = E.cy = 0; E.rowoff = E.coloff = 0; for (int j = E.numrows-1; j >= 0; j--) editorDelRow(j); } /* Turn the editor rows into a single heap-allocated string. * Returns the pointer to the heap-allocated string and populate the * integer pointed by 'buflen' with the size of the string, excluding * the final null term. */ static char *editorRowsToString(int *buflen) { char *buf = NULL, *p; int totlen = 0; int j; /* Compute count of bytes */ for (j = 0; j < E.numrows; j++) totlen += E.row[j].size+1; /* +1 is for "\n" at end of every row */ *buflen = totlen; totlen++; /* Also make space for null term */ p = buf = malloc(totlen); for (j = 0; j < E.numrows; j++) { memcpy(p,E.row[j].chars,E.row[j].size); p += E.row[j].size; *p = '\n'; p++; } *p = '\0'; return buf; } /* Insert a character at the specified position in a row, moving the remaining * chars on the right if needed. */ static void editorRowInsertChar(erow *row, int at, int c) { if (at > row->size) { /* Pad the string with spaces if the insert location is outside the * current length by more than a single character. */ int padlen = at-row->size; /* In the next line +2 means: new char and null term. */ row->chars = realloc(row->chars,row->size+padlen+2); memset(row->chars+row->size,' ',padlen); row->chars[row->size+padlen+1] = '\0'; row->size += padlen+1; } else { /* If we are in the middle of the string just make space for 1 new * char plus the (already existing) null term. */ row->chars = realloc(row->chars,row->size+2); memmove(row->chars+at+1,row->chars+at,row->size-at+1); row->size++; } row->chars[at] = c; editorUpdateRow(row); E.dirty++; } /* Append the string 's' at the end of a row */ static void editorRowAppendString(erow *row, char *s, size_t len) { row->chars = realloc(row->chars,row->size+len+1); memcpy(row->chars+row->size,s,len); row->size += len; row->chars[row->size] = '\0'; editorUpdateRow(row); E.dirty++; } /* Delete the character at offset 'at' from the specified row. */ static void editorRowDelChar(erow *row, int at) { if (row->size <= at) return; memmove(row->chars+at,row->chars+at+1,row->size-at); editorUpdateRow(row); row->size--; E.dirty++; } /* Insert the specified char at the current prompt position. */ static void editorInsertChar(int c) { int filerow = E.rowoff+E.cy; int filecol = E.coloff+E.cx; erow *row = (filerow >= E.numrows) ? NULL : &E.row[filerow]; /* If the row where the cursor is currently located does not exist in our * logical representaion of the file, add enough empty rows as needed. */ if (!row) { while(E.numrows <= filerow) editorInsertRow(E.numrows,"",0); } row = &E.row[filerow]; editorRowInsertChar(row,filecol,c); if (E.cx == E.cols-1) E.coloff++; else E.cx++; E.dirty++; } /* Inserting a newline is slightly complex as we have to handle inserting a * newline in the middle of a line, splitting the line as needed. */ static void editorInsertNewline(void) { int filerow = E.rowoff+E.cy; int filecol = E.coloff+E.cx; erow *row = (filerow >= E.numrows) ? NULL : &E.row[filerow]; if (!row) { if (filerow == E.numrows) { editorInsertRow(filerow,"",0); goto fixcursor; } return; } /* If the cursor is over the current line size, we want to conceptually * think it's just over the last character. */ if (filecol >= row->size) filecol = row->size; if (filecol == 0) { editorInsertRow(filerow,"",0); } else { /* We are in the middle of a line. Split it between two rows. */ editorInsertRow(filerow+1,row->chars+filecol,row->size-filecol); row = &E.row[filerow]; row->chars[filecol] = '\0'; row->size = filecol; editorUpdateRow(row); } fixcursor: if (E.startrow + E.cy == E.endrow-1) { E.rowoff++; } else { E.cy++; } E.cx = 0; E.coloff = 0; } /* Delete the char at the current prompt position. */ static void editorDelChar() { int filerow = E.rowoff+E.cy; int filecol = E.coloff+E.cx; erow *row = (filerow >= E.numrows) ? NULL : &E.row[filerow]; if (!row || (filecol == 0 && filerow == 0)) return; if (filecol == 0) { /* Handle the case of column 0, we need to move the current line * on the right of the previous one. */ filecol = E.row[filerow-1].size; editorRowAppendString(&E.row[filerow-1],row->chars,row->size); editorDelRow(filerow); row = NULL; if (E.cy == 0) E.rowoff--; else E.cy--; E.cx = filecol; if (E.cx >= E.cols) { int shift = (E.cols-E.cx)+1; E.cx -= shift; E.coloff += shift; } } else { editorRowDelChar(row,filecol-1); if (E.cx == 0 && E.coloff) E.coloff--; else E.cx--; } if (row) editorUpdateRow(row); E.dirty++; } static void editorUncommentCursorRow() { erow *row = &E.row[E.rowoff+E.cy]; E.coloff = 0; E.cx = 4; editorUpdateRow(row); editorDelChar(); editorDelChar(); editorDelChar(); editorDelChar(); } static void editorCommentCursorRow() { erow *row = &E.row[E.rowoff+E.cy]; editorRowInsertChar(row, 0, ' '); editorRowInsertChar(row, 0, '?'); editorRowInsertChar(row, 0, '-'); editorRowInsertChar(row, 0, '-'); E.coloff = 0; E.cx = 0; } /* Load the specified program in the editor memory and returns 0 on success * or 1 on error. */ int editorOpen(char *filename) { FILE *fp; E.dirty = 0; free(E.filename); size_t fnlen = strlen(filename)+1; E.filename = malloc(fnlen); memcpy(E.filename,filename,fnlen); fp = fopen(filename,"r"); if (!fp) { if (errno != ENOENT) { perror("Opening file"); exit(1); } return 1; } char *line = NULL; size_t linecap = 0; ssize_t linelen; while((linelen = getline(&line,&linecap,fp)) != -1) { if (linelen && (line[linelen-1] == '\n' || line[linelen-1] == '\r')) line[--linelen] = '\0'; editorInsertRow(E.numrows,line,linelen); } free(line); fclose(fp); E.dirty = 0; return 0; } /* Save the current file on disk. Return 0 on success, 1 on error. */ static int editorSaveToDisk(void) { int len; char *buf = editorRowsToString(&len); int fd = open(E.filename,O_RDWR|O_CREAT,0644); if (fd == -1) goto writeerr; /* Use truncate + a single write(2) call in order to make saving * a bit safer, under the limits of what we can do in a small editor. */ if (ftruncate(fd,len) == -1) goto writeerr; if (write(fd,buf,len) != len) goto writeerr; close(fd); free(buf); E.dirty = 0; return 0; writeerr: free(buf); if (fd != -1) close(fd); /* TODO: better error handling. */ /* I haven't gotten to this yet since we have version control. */ endwin(); printf("Can't save! I/O error: %s",strerror(errno)); exit(1); return 1; } /* ============================= Terminal update ============================ */ static void editorMenu(void) { attrset(A_REVERSE); for (int x = 0; x < COLS; ++x) mvaddch(LINES-1, x, ' '); attrset(A_NORMAL); menu_column = 2; draw_menu_item("^x", "run"); if (Previous_error != NULL) { attron(A_BOLD); draw_menu_item("^c", "abort"); attroff(A_BOLD); } draw_menu_item("^g", "go"); draw_menu_item("^b", "big picture"); draw_menu_item("^f", "find"); draw_menu_item("^h", "backspace"); draw_menu_item("^l", "end of line"); /* draw_menu_item("^/|^-|^_", "(un)comment line"); */ attroff(A_REVERSE); mvaddstr(LINES-1, menu_column, " ^/"); attron(COLOR_PAIR(COLOR_PAIR_MENU_ALTERNATE)); addstr("|"); attroff(COLOR_PAIR(COLOR_PAIR_MENU_ALTERNATE)); addstr("^-"); attron(COLOR_PAIR(COLOR_PAIR_MENU_ALTERNATE)); addstr("|"); attroff(COLOR_PAIR(COLOR_PAIR_MENU_ALTERNATE)); addstr("^_ "); menu_column += 10; attron(A_REVERSE); mvaddstr(LINES-1, menu_column, " (un)comment line "); menu_column += 18; attrset(A_NORMAL); } static void editorFindMenu(void) { attrset(A_REVERSE); for (int x = 0; x < COLS; ++x) mvaddch(LINES-1, x, ' '); attrset(A_NORMAL); menu_column = 2; draw_menu_item("^x", "cancel"); draw_menu_item("Enter", "submit"); draw_menu_item("^h", "backspace"); draw_menu_item("^u", "clear"); /* draw_menu_item("←|↑", "previous"); */ attroff(A_REVERSE); mvaddstr(LINES-1, menu_column, " ←|↑ "); menu_column += 5; /* strlen isn't sufficient */ attron(A_REVERSE); draw_string_on_menu("previous"); /* draw_menu_item("↓|→", "next"); */ attroff(A_REVERSE); mvaddstr(LINES-1, menu_column, " ↓|→ "); menu_column += 5; /* strlen isn't sufficient */ attron(A_REVERSE); draw_string_on_menu("next"); attrset(A_NORMAL); } static void editorGoMenu(void) { attrset(A_REVERSE); for (int x = 0; x < COLS; ++x) mvaddch(LINES-1, x, ' '); attrset(A_NORMAL); menu_column = 2; draw_menu_item("^x", "cancel"); draw_menu_item("Enter", "submit"); draw_menu_item("^h", "backspace"); draw_menu_item("^u", "clear"); attrset(A_NORMAL); } static void editorRefreshScreen(void (*menu_func)(void)) { int y; erow *r; int current_color = -1; curs_set(0); mvaddstr(E.startrow, 0, ""); clrtobot(); attrset(A_NORMAL); /* Draw all line numbers first so they don't mess up curses state later * when rendering lines. */ for (y = E.startrow; y < E.endrow; y++) { int filerow = E.rowoff+y-E.startrow; if (filerow >= E.numrows) { continue; } mvaddstr(y, 0, ""); attron(COLOR_PAIR(COLOR_PAIR_FADE)); printw("%3d ", filerow+1); // %3d = LINE_NUMBER_SPACE-1 attroff(COLOR_PAIR(COLOR_PAIR_FADE)); } for (y = E.startrow; y < E.endrow; y++) { int filerow = E.rowoff+y-E.startrow; if (filerow >= E.numrows) { continue; } r = &E.row[filerow]; int len = r->rsize - E.coloff; mvaddstr(y, E.startcol, ""); if (len > 0) { if (len > E.cols) len = E.cols; char *c = r->render+E.coloff; unsigned char *hl = r->hl+E.coloff; int j; for (j = 0; j < len; j++) { if (hl[j] == HL_NONPRINT) { char sym; attron(A_REVERSE); if (c[j] <= 26) sym = '@'+c[j]; else sym = '?'; addch(sym); attroff(A_REVERSE); } else if (hl[j] == HL_NORMAL) { if (current_color != -1) { attrset(A_NORMAL); current_color = -1; } addch(c[j]); } else { int color = editorSyntaxToColorPair(hl[j]); if (color != current_color) { attrset(COLOR_PAIR(color)); current_color = color; } addch(c[j]); } } } } render_previous_error(); (*menu_func)(); /* Put cursor at its current position. Note that the horizontal position * at which the cursor is displayed may be different compared to 'E.cx' * because of TABs. */ int j; int cx = 0; int filerow = E.rowoff+E.cy; erow *row = (filerow >= E.numrows) ? NULL : &E.row[filerow]; if (row) { for (j = E.coloff; j < (E.cx+E.coloff); j++) { if (j < row->size && row->chars[j] == TAB) cx += 7-((cx)%8); cx++; } } mvaddstr(E.cy+E.startrow, cx+LINE_NUMBER_SPACE, ""); curs_set(1); } /* =============================== Find mode ================================ */ #define KILO_QUERY_LEN 256 static void editorFind() { char query[KILO_QUERY_LEN+1] = {0}; int qlen = 0; int last_match = -1; /* Last line where a match was found. -1 for none. */ int find_next = 0; /* if 1 search next, if -1 search prev. */ int saved_hl_line = -1; /* No saved HL */ char *saved_hl = NULL; #define FIND_RESTORE_HL do { \ if (saved_hl) { \ memcpy(E.row[saved_hl_line].hl,saved_hl, E.row[saved_hl_line].rsize); \ free(saved_hl); \ saved_hl = NULL; \ } \ } while (0) /* Save the cursor position in order to restore it later. */ int saved_cx = E.cx, saved_cy = E.cy; int saved_coloff = E.coloff, saved_rowoff = E.rowoff; while(1) { editorRefreshScreen(editorFindMenu); mvprintw(LINES-2, 0, "Find: %s", query); int c = getch(); if (c == KEY_BACKSPACE || c == DELETE || c == CTRL_H) { if (qlen != 0) query[--qlen] = '\0'; last_match = -1; } else if (c == CTRL_X || c == ENTER) { if (c == CTRL_X) { E.cx = saved_cx; E.cy = saved_cy; E.coloff = saved_coloff; E.rowoff = saved_rowoff; } FIND_RESTORE_HL; return; } else if (c == CTRL_U) { qlen = 0; query[qlen] = '\0'; } else if (c == KEY_RIGHT || c == KEY_DOWN) { find_next = 1; } else if (c == KEY_LEFT || c == KEY_UP) { find_next = -1; } else if (isprint(c)) { if (qlen < KILO_QUERY_LEN) { query[qlen++] = c; query[qlen] = '\0'; last_match = -1; } } /* Search occurrence. */ if (last_match == -1) find_next = 1; if (find_next) { char *match = NULL; int match_offset = 0; int i, current = last_match; for (i = 0; i < E.numrows; i++) { current += find_next; if (current == -1) current = E.numrows-1; else if (current == E.numrows) current = 0; match = strstr(E.row[current].render,query); if (match) { match_offset = match-E.row[current].render; break; } } find_next = 0; /* Highlight */ FIND_RESTORE_HL; if (match) { erow *row = &E.row[current]; last_match = current; if (row->hl) { saved_hl_line = current; saved_hl = malloc(row->rsize); memcpy(saved_hl,row->hl,row->rsize); memset(row->hl+match_offset,HL_MATCH,qlen); } E.cy = 0; E.cx = match_offset; E.rowoff = current; E.coloff = 0; /* Scroll horizontally as needed. */ if (E.cx > E.cols) { int diff = E.cx - E.cols; E.cx -= diff; E.coloff += diff; } } } } } /* ========================= Editor events handling ======================== */ static int editorAtStartOfLine() { return E.coloff == 0 && E.cx == 0; } /* Handle cursor position change because arrow keys were pressed. */ static void editorMoveCursor(int key) { int filerow = E.rowoff+E.cy; int filecol = E.coloff+E.cx; int rowlen; erow *row = (filerow >= E.numrows) ? NULL : &E.row[filerow]; switch(key) { case KEY_LEFT: if (E.cx == 0) { if (E.coloff) { E.coloff--; } else { if (filerow > 0) { E.cy--; E.cx = E.row[filerow-1].size; if (E.cx > E.cols-1) { E.coloff = E.cx-E.cols+1; E.cx = E.cols-1; } } } } else { E.cx -= 1; } break; case KEY_RIGHT: if (row && filecol < row->size) { if (E.cx == E.cols-1) { E.coloff++; } else { E.cx += 1; } } else if (row && filecol == row->size) { E.cx = 0; E.coloff = 0; if (E.startrow + E.cy == E.endrow-1) { E.rowoff++; } else { E.cy += 1; } } break; case KEY_UP: if (E.cy == 0) { if (E.rowoff) E.rowoff--; } else { E.cy -= 1; } break; case KEY_DOWN: if (filerow < E.numrows-1) { if (E.startrow + E.cy == E.endrow-1) { E.rowoff++; } else { E.cy += 1; } } break; } /* Fix cx if the current line has not enough chars. */ filerow = E.rowoff+E.cy; filecol = E.coloff+E.cx; row = (filerow >= E.numrows) ? NULL : &E.row[filerow]; rowlen = row ? row->size : 0; if (filecol > rowlen) { E.cx -= filecol-rowlen; if (E.cx < 0) { E.coloff += E.cx; E.cx = 0; } } } static int identifier_char(char c) { /* keep sync'd with llex, with one exception for prose */ return isalnum(c) || c == '_' || c == ':'; } static void word_at_cursor(char* out, int capacity) { erow* row = &E.row[E.rowoff + E.cy]; int cidx = E.coloff + E.cx; int len = 0; memset(out, 0, capacity); if (row == NULL) return; /* scan back to first identifier char */ while (cidx > 0) { --cidx; if (!identifier_char(row->chars[cidx])) { ++cidx; break; } } /* now scan forward */ for (len = 0; cidx+len < row->size; ++len) { if (!identifier_char(row->chars[cidx+len])) break; } if (len < capacity) strncpy(out, &row->chars[cidx], len); } /* Jump to some definition. */ extern char Current_definition[]; #define CURRENT_DEFINITION_LEN 256 static void editorGo(lua_State* L) { char query[CURRENT_DEFINITION_LEN+1] = {0}; int qlen = 0; if (strlen(Current_definition) > 0) { /* We're currently editing a definition. Save it. */ editorSaveToDisk(); load_editor_buffer_to_current_definition_in_image_and_reload(L); } word_at_cursor(query, CURRENT_DEFINITION_LEN); qlen = strlen(query); while(1) { editorRefreshScreen(editorGoMenu); mvaddstr(E.endrow-1, 0, ""); clrtoeol(); mvprintw(E.endrow-1, 0, "Go to: %s", query); int c = getch(); if (c == KEY_BACKSPACE || c == DELETE || c == CTRL_H) { if (qlen != 0) query[--qlen] = '\0'; } else if (c == CTRL_X || c == ENTER) { if (c == ENTER) { save_to_current_definition_and_editor_buffer(L, query); clearEditor(); if (starts_with(query, "doc:")) E.syntax = &ProseSyntax; else E.syntax = &LuaSyntax; editorOpen("teliva_editor_buffer"); attrset(A_NORMAL); clear(); draw_current_definition_name_and_callers(L); } return; } else if (c == CTRL_U) { qlen = 0; query[qlen] = '\0'; } else if (isprint(c)) { if (qlen < CURRENT_DEFINITION_LEN) { query[qlen++] = c; query[qlen] = '\0'; } } } } /* Process events arriving from the standard input, which is, the user * is typing stuff on the terminal. */ static int Quit = 0; static int Back_to_big_picture = 0; static void editorProcessKeypress2(int c) { switch(c) { case ENTER: { editorInsertNewline(); /* auto-indent */ erow* prevrow = &E.row[E.rowoff + E.cy - 1]; for (int x = 0; x < prevrow->size && prevrow->chars[x] == ' '; ++x) editorInsertChar(' '); } break; case CTRL_C: if (Previous_error != NULL) exit(1); break; case CTRL_X: /* Save and quit. */ editorSaveToDisk(); save_editor_state(E.rowoff, E.coloff, E.cy, E.cx); Quit = 1; break; case CTRL_F: editorFind(); break; case KEY_BACKSPACE: case DELETE: case CTRL_H: editorDelChar(); break; case KEY_NPAGE: case KEY_PPAGE: if (c == KEY_PPAGE && E.cy != 0) E.cy = 0; else if (c == KEY_NPAGE && E.startrow + E.cy != E.endrow-1) E.cy = E.endrow-1-E.startrow; { int times = E.endrow-E.startrow; while(times--) editorMoveCursor(c == KEY_PPAGE ? KEY_UP : KEY_DOWN); } break; case CTRL_A: while (!editorAtStartOfLine()) editorMoveCursor(KEY_LEFT); break; case CTRL_L: while (1) { editorMoveCursor(KEY_RIGHT); if (editorAtStartOfLine()) { editorMoveCursor(KEY_LEFT); break; } } break; case CTRL_U: while (!editorAtStartOfLine()) editorDelChar(); break; case CTRL_K: while (1) { editorMoveCursor(KEY_RIGHT); if (editorAtStartOfLine()) { editorMoveCursor(KEY_LEFT); break; } editorDelChar(); } break; case CTRL_SLASH: /* same as CTRL_UNDERSCORE */ if (starts_with(E.row[E.rowoff+E.cy].chars, "--? ")) editorUncommentCursorRow(); else editorCommentCursorRow(); break; case KEY_UP: case KEY_DOWN: case KEY_LEFT: case KEY_RIGHT: editorMoveCursor(c); break; case TAB: /* insert 2 spaces */ editorInsertChar(' '); editorInsertChar(' '); break; default: if (c >= ' ') editorInsertChar(c); break; } } static void editorProcessKeypress(lua_State* L) { int c = getch(); //? mvprintw(LINES-3, 60, "key: %d\n", c); //? getch(); switch(c) { case CTRL_G: /* Go to a different definition. */ editorGo(L); break; case CTRL_B: /* Go to big-picture view. */ editorSaveToDisk(); Quit = 1; Back_to_big_picture = 1; break; default: editorProcessKeypress2(c); } } static void initEditor(void) { E.cx = 0; E.cy = 0; E.rowoff = 0; E.coloff = 0; E.numrows = 0; E.row = NULL; E.dirty = 0; E.filename = NULL; } /* return true if user chose to back into the big picture view */ int edit(lua_State* L, char* filename, char* definition_name) { Quit = 0; Back_to_big_picture = 0; initEditor(); if (starts_with(definition_name, "doc:")) E.syntax = &ProseSyntax; else E.syntax = &LuaSyntax; editorOpen(filename); attrset(A_NORMAL); clear(); draw_current_definition_name_and_callers(L); while(!Quit) { /* update on resize */ E.startcol = LINE_NUMBER_SPACE; E.cols = COLS-LINE_NUMBER_SPACE; E.startrow = CALLERS_SPACE; E.endrow = LINES-MENU_SPACE; editorRefreshScreen(editorMenu); editorProcessKeypress(L); } return Back_to_big_picture; } /* Like editFrom(), but no highlighting, no callers. */ int editProse(lua_State* L, char* filename) { Quit = 0; Back_to_big_picture = 0; initEditor(); E.syntax = &ProseSyntax; editorOpen(filename); attrset(A_NORMAL); clear(); while(!Quit) { /* update on resize */ E.startcol = LINE_NUMBER_SPACE; E.cols = COLS-LINE_NUMBER_SPACE; E.startrow = CALLERS_SPACE; E.endrow = LINES-MENU_SPACE; editorRefreshScreen(editorMenu); editorProcessKeypress(L); } return Back_to_big_picture; } static void editorNonCodeMenu(void) { attrset(A_REVERSE); for (int x = 0; x < COLS; ++x) mvaddch(LINES-1, x, ' '); attrset(A_NORMAL); menu_column = 2; draw_menu_item("^x", "back"); if (Previous_error != NULL) { attron(A_BOLD); draw_menu_item("^c", "abort"); attroff(A_BOLD); } draw_menu_item("^f", "find"); draw_menu_item("^h", "backspace"); draw_menu_item("^l", "end of line"); /* draw_menu_item("^/|^-|^_", "(un)comment line"); */ attroff(A_REVERSE); mvaddstr(LINES-1, menu_column, " ^/"); attron(COLOR_PAIR(COLOR_PAIR_MENU_ALTERNATE)); addstr("|"); attroff(COLOR_PAIR(COLOR_PAIR_MENU_ALTERNATE)); addstr("^-"); attron(COLOR_PAIR(COLOR_PAIR_MENU_ALTERNATE)); addstr("|"); attroff(COLOR_PAIR(COLOR_PAIR_MENU_ALTERNATE)); addstr("^_ "); menu_column += 10; attron(A_REVERSE); mvaddstr(LINES-1, menu_column, " (un)comment line "); menu_column += 18; attrset(A_NORMAL); } void editNonCode(char* filename) { Quit = 0; Back_to_big_picture = 0; initEditor(); editorOpen(filename); while(!Quit) { /* update on resize */ E.startcol = LINE_NUMBER_SPACE; E.cols = COLS-LINE_NUMBER_SPACE; E.startrow = CALLERS_SPACE; E.endrow = LINES-MENU_SPACE; editorRefreshScreen(editorNonCodeMenu); int c = getch(); editorProcessKeypress2(c); } } #define MIN(x, y) ((x) < (y) ? (x) : (y)) void print_file_permission_suggestions(int row); void editFilePermissions(char* filename) { Quit = 0; Back_to_big_picture = 0; initEditor(); E.syntax = &LuaSyntax; E.startcol = LINE_NUMBER_SPACE; E.startrow = 1; /* space for function header */ E.endrow = 10; /* nudge people to keep function short */ editorOpen(filename); while(!Quit) { /* update on resize */ E.cols = COLS-LINE_NUMBER_SPACE; editorRefreshScreen(editorNonCodeMenu); int y, x; getyx(stdscr, y, x); mvaddstr(0, 0, "function file_operation_permitted(filename, is_write)"); int past_end_row = MIN(E.startrow + E.numrows, E.endrow); mvaddstr(past_end_row, 0, "end"); attrset(COLOR_PAIR(COLOR_PAIR_LUA_COMMENT)); print_file_permission_suggestions(past_end_row+2); attrset(A_NORMAL); mvaddstr(y, x, ""); int c = getch(); editorProcessKeypress2(c); } } /* return true if user chose to back into the big picture view */ int editFrom(lua_State* L, char* filename, char* definition_name, int rowoff, int coloff, int cy, int cx) { Quit = 0; Back_to_big_picture = 0; initEditor(); if (starts_with(definition_name, "doc:")) E.syntax = &ProseSyntax; else E.syntax = &LuaSyntax; E.rowoff = rowoff; E.coloff = coloff; E.cy = cy; E.cx = cx; editorOpen(filename); attrset(A_NORMAL); clear(); draw_current_definition_name_and_callers(L); while(!Quit) { /* update on resize */ E.startcol = LINE_NUMBER_SPACE; E.cols = COLS-LINE_NUMBER_SPACE; E.startrow = CALLERS_SPACE; E.endrow = LINES-MENU_SPACE; editorRefreshScreen(editorMenu); editorProcessKeypress(L); } return Back_to_big_picture; } /* Like editFrom(), but no highlighting, no callers. */ int editProseFrom(lua_State* L, char* filename, int rowoff, int coloff, int cy, int cx) { Quit = 0; Back_to_big_picture = 0; initEditor(); E.syntax = &ProseSyntax; E.rowoff = rowoff; E.coloff = coloff; E.cy = cy; E.cx = cx; editorOpen(filename); attrset(A_NORMAL); clear(); while(!Quit) { /* update on resize */ E.startcol = LINE_NUMBER_SPACE; E.cols = COLS-LINE_NUMBER_SPACE; E.startrow = CALLERS_SPACE; E.endrow = LINES-MENU_SPACE; editorRefreshScreen(editorMenu); editorProcessKeypress(L); } return Back_to_big_picture; } int resumeEdit(lua_State* L) { Quit = 0; Back_to_big_picture = 0; attrset(A_NORMAL); clear(); draw_current_definition_name_and_callers(L); while(!Quit) { /* update on resize */ E.startcol = LINE_NUMBER_SPACE; E.cols = COLS-LINE_NUMBER_SPACE; E.startrow = CALLERS_SPACE; E.endrow = LINES-MENU_SPACE; editorRefreshScreen(editorMenu); editorProcessKeypress(L); } return Back_to_big_picture; } void resumeNonCodeEdit() { Quit = 0; Back_to_big_picture = 0; while(!Quit) { /* update on resize */ E.startcol = LINE_NUMBER_SPACE; E.cols = COLS-LINE_NUMBER_SPACE; E.startrow = CALLERS_SPACE; E.endrow = LINES-MENU_SPACE; editorRefreshScreen(editorNonCodeMenu); int c = getch(); editorProcessKeypress2(c); } } void resumeFilePermissionsEdit() { Quit = 0; Back_to_big_picture = 0; E.startcol = LINE_NUMBER_SPACE; E.startrow = 1; /* space for function header */ E.endrow = 10; /* nudge people to keep function short */ while(!Quit) { /* update on resize */ E.cols = COLS-LINE_NUMBER_SPACE; editorRefreshScreen(editorNonCodeMenu); int y, x; getyx(stdscr, y, x); mvaddstr(0, 0, "function file_operation_permitted(filename, is_write)"); mvaddstr(MIN(E.startrow + E.numrows, E.endrow), 0, "end"); mvaddstr(y, x, ""); int c = getch(); editorProcessKeypress2(c); } } /* vim:tabstop=4:shiftwidth=0:expandtab:softtabstop=-1 */
30.50406
107
0.53876
[ "render", "3d" ]
fe5fd1f639c23ee8ea872022d0603f46c9eaeeed
1,321
h
C
src/src/KCounterMark.h
jcleng/nix-kangle-3.5.13.2
cc7bbaa429ada9a7eb7a023a152b6e2fc5defe3f
[ "MIT" ]
null
null
null
src/src/KCounterMark.h
jcleng/nix-kangle-3.5.13.2
cc7bbaa429ada9a7eb7a023a152b6e2fc5defe3f
[ "MIT" ]
null
null
null
src/src/KCounterMark.h
jcleng/nix-kangle-3.5.13.2
cc7bbaa429ada9a7eb7a023a152b6e2fc5defe3f
[ "MIT" ]
null
null
null
#ifndef KCOUNTER_MARK_H #define KCOUNTER_MARK_H class KCounterMark : public KMark { public: KCounterMark() { counter = 0; } ~KCounterMark() { } bool supportRuntime() { return true; } bool mark(KHttpRequest *rq, KHttpObject *obj,const int chainJumpType, int &jumpType) { lock.Lock(); counter++; lock.Unlock(); return true; } KMark *newInstance() { return new KCounterMark(); } const char *getName() { return "counter"; } std::string getHtml(KModel *model) { std::stringstream s; s << "<input type=checkbox name='reset' value='1'>reset"; return s.str(); } std::string getDisplay() { std::stringstream s; s << counter; return s.str(); } void editHtml(std::map<std::string, std::string> &attribute) throw (KHtmlSupportException) { } int whmCall(WhmContext *ctx) { const char *op = ctx->getUrlValue()->getx("op"); if (op==NULL) { ctx->setStatus("op is missing"); return 404; } if (strcmp(op,"get")==0) { lock.Lock(); ctx->add("counter",counter); lock.Unlock(); return 200; } if (strcmp(op,"get_reset")==0) { lock.Lock(); ctx->add("counter",counter); counter = 0; lock.Unlock(); return 200; } return 400; } void buildXML(std::stringstream &s,int flag) { s << ">"; } private: KMutex lock; INT64 counter; }; #endif
16.935897
91
0.627555
[ "model" ]
fe5fe43a58fad71d8ddcb5b6251516043d2d3218
47,458
h
C
rtmp/srs_librtmp.h
Snowem/snowem
353ce1b8f8559a3d75bea4b364af9e97bf4fc6a7
[ "MIT" ]
176
2018-01-09T03:36:16.000Z
2022-03-24T01:29:42.000Z
rtmp/srs_librtmp.h
Snowem/snowem
353ce1b8f8559a3d75bea4b364af9e97bf4fc6a7
[ "MIT" ]
8
2018-07-06T09:17:26.000Z
2021-06-08T12:48:50.000Z
rtmp/srs_librtmp.h
Snowem/snowem
353ce1b8f8559a3d75bea4b364af9e97bf4fc6a7
[ "MIT" ]
50
2018-01-09T03:36:24.000Z
2022-01-22T07:14:23.000Z
/* The MIT License (MIT) Copyright (c) 2013-2017 SRS(ossrs) 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. */ #ifndef SRS_LIB_RTMP_HPP #define SRS_LIB_RTMP_HPP /* #include <srs_librtmp.h> */ /** * srs-librtmp is a librtmp like library, * used to play/publish rtmp stream from/to rtmp server. * socket: use sync and block socket to connect/recv/send data with server. * depends: no need other libraries; depends on ssl if use srs_complex_handshake. * thread-safe: no */ /************************************************************* ************************************************************** * Windows SRS-LIBRTMP pre-declare ************************************************************** *************************************************************/ // for srs-librtmp, @see https://github.com/ossrs/srs/issues/213 #ifdef _WIN32 // include windows first. #include <windows.h> // the type used by this header for windows. typedef unsigned long long u_int64_t; typedef u_int64_t uint64_t; typedef long long int64_t; typedef unsigned int u_int32_t; typedef u_int32_t uint32_t; typedef int int32_t; typedef unsigned char u_int8_t; typedef u_int8_t uint8_t; typedef char int8_t; typedef unsigned short u_int16_t; typedef u_int16_t uint16_t; typedef short int16_t; typedef int64_t ssize_t; struct iovec { void *iov_base; /* Starting address */ size_t iov_len; /* Number of bytes to transfer */ }; // for pid. typedef int pid_t; pid_t getpid(void); #endif #include <stdint.h> #include <sys/types.h> #ifdef __cplusplus extern "C"{ #endif /** * The schema of RTMP url, the following are legal urls: * srs_url_schema_normal: rtmp://vhost:port/app/stream * srs_url_schema_via : rtmp://ip:port/vhost/app/stream * srs_url_schema_vis : rtmp://ip:port/app/stream?vhost=xxx * srs_url_schema_vis2 : rtmp://ip:port/app/stream?domain=xxx */ enum srs_url_schema { // Forbidden. srs_url_schema_forbidden = 0, // Normal RTMP URL, the vhost put in host field, using DNS to resolve the server ip. // For example, rtmp://vhost:port/app/stream srs_url_schema_normal, // VIA(vhost in app), the vhost put in app field. // For example, rtmp://ip:port/vhost/app/stream srs_url_schema_via, // VIS(vhost in stream), the vhost put in query string, keyword use vhost=xxx. // For example, rtmp://ip:port/app/stream?vhost=xxx srs_url_schema_vis, // VIS, keyword use domain=xxx. // For example, rtmp://ip:port/app/stream?domain=xxx srs_url_schema_vis2 }; // typedefs typedef int srs_bool; /************************************************************* ************************************************************** * srs-librtmp version ************************************************************** *************************************************************/ extern int srs_version_major(); extern int srs_version_minor(); extern int srs_version_revision(); /************************************************************* ************************************************************** * RTMP protocol context ************************************************************** *************************************************************/ // the RTMP handler. typedef void* srs_rtmp_t; typedef void* srs_amf0_t; /** * Create a RTMP handler. * @param url The RTMP url, for example, rtmp://localhost/live/livestream * @remark default timeout to 30s if not set by srs_rtmp_set_timeout. * @remark default schema to srs_url_schema_normal, use srs_rtmp_set_schema to change it. * * @return a rtmp handler, or NULL if error occured. */ extern srs_rtmp_t srs_rtmp_create(const char* url); /** * set socket timeout * @param recv_timeout_ms the timeout for receiving messages in ms. * @param send_timeout_ms the timeout for sending message in ms. * @remark user can set timeout once srs_rtmp_create/srs_rtmp_create2, * or before srs_rtmp_handshake or srs_rtmp_dns_resolve to connect to server. * @remark default timeout to 30s if not set by srs_rtmp_set_timeout. * * @return 0, success; otherswise, failed. */ extern int srs_rtmp_set_timeout(srs_rtmp_t rtmp, int recv_timeout_ms, int send_timeout_ms); /** * close and destroy the rtmp stack. * @remark, user should never use the rtmp again. */ extern void srs_rtmp_destroy(srs_rtmp_t rtmp); /************************************************************* ************************************************************** * RTMP protocol stack ************************************************************** *************************************************************/ /** * connect and handshake with server * category: publish/play * previous: rtmp-create * next: connect-app * * @return 0, success; otherswise, failed. */ /** * simple handshake specifies in rtmp 1.0, * not depends on ssl. */ /** * srs_rtmp_handshake equals to invoke: * srs_rtmp_dns_resolve() * srs_rtmp_connect_server() * srs_rtmp_do_simple_handshake() * user can use these functions if needed. */ extern int srs_rtmp_handshake(srs_rtmp_t rtmp); // parse uri, create socket, resolve host extern int srs_rtmp_dns_resolve(srs_rtmp_t rtmp); // connect socket to server extern int srs_rtmp_connect_server(srs_rtmp_t rtmp); // do simple handshake over socket. extern int srs_rtmp_do_simple_handshake(srs_rtmp_t rtmp); // do complex handshake over socket. extern int srs_rtmp_do_complex_handshake(srs_rtmp_t rtmp); /** * set the args of connect packet for rtmp. * @param args, the extra amf0 object args. * @remark, all params can be NULL to ignore. * @remark, user should never free the args for we directly use it. */ extern int srs_rtmp_set_connect_args(srs_rtmp_t rtmp, const char* tcUrl, const char* swfUrl, const char* pageUrl, srs_amf0_t args ); /** * Set the schema of URL when connect to tcUrl by srs_rtmp_connect_app. * @param schema, The schema of URL, @see srs_url_schema. * @return 0, success; otherswise, failed. */ extern int srs_rtmp_set_schema(srs_rtmp_t rtmp, enum srs_url_schema schema); /** * Connect to RTMP tcUrl(Vhost/App), similar to flash AS3 NetConnection.connect(tcUrl). * @remark When connected to server, user can retrieve informations from RTMP handler, * for example, use srs_rtmp_get_server_id to get server ip/pid/cid. * @return 0, success; otherswise, failed. */ extern int srs_rtmp_connect_app(srs_rtmp_t rtmp); /** * Retrieve server ip from RTMP handler. * @Param ip A NULL terminated string specifies the server ip. * @Param pid An int specifies the PID of server. -1 is no PID information. * @Param cid An int specifies the CID of connection. -1 is no CID information. * @remark For SRS, ip/pid/cid is the UUID of a client. For other server, these values maybe unknown. * @remark When connected to server by srs_rtmp_connect_app, the information is ready to be retrieved. * @return 0, success; otherswise, failed. */ extern int srs_rtmp_get_server_id(srs_rtmp_t rtmp, char** ip, int* pid, int* cid); /** * Retrieve server signature from RTMP handler. * @Param sig A NULL terminated string specifies the server signature. * @remark When connected to server by srs_rtmp_connect_app, the information is ready to be retrieved. * @return 0, success; otherswise, failed. */ extern int srs_rtmp_get_server_sig(srs_rtmp_t rtmp, char** sig); /** * Retrieve server version from RTMP handler, which in major.minor.revision.build format. * @remark When connected to server by srs_rtmp_connect_app, the information is ready to be retrieved. * @return 0, success; otherswise, failed. */ extern int srs_rtmp_get_server_version(srs_rtmp_t rtmp, int* major, int* minor, int* revision, int* build); /** * play a live/vod stream. * category: play * previous: connect-app * next: destroy * @return 0, success; otherwise, failed. */ extern int srs_rtmp_play_stream(srs_rtmp_t rtmp); /** * publish a live stream. * category: publish * previous: connect-app * next: destroy * @return 0, success; otherwise, failed. */ extern int srs_rtmp_publish_stream(srs_rtmp_t rtmp); /** * do bandwidth check with srs server. * * bandwidth info: * @param start_time, output the start time, in ms. * @param end_time, output the end time, in ms. * @param play_kbps, output the play/download kbps. * @param publish_kbps, output the publish/upload kbps. * @param play_bytes, output the play/download bytes. * @param publish_bytes, output the publish/upload bytes. * @param play_duration, output the play/download test duration, in ms. * @param publish_duration, output the publish/upload test duration, in ms. * * @return 0, success; otherswise, failed. */ extern int srs_rtmp_bandwidth_check(srs_rtmp_t rtmp, int64_t* start_time, int64_t* end_time, int* play_kbps, int* publish_kbps, int* play_bytes, int* publish_bytes, int* play_duration, int* publish_duration ); /** * E.4.1 FLV Tag, page 75 */ // 8 = audio #define SRS_RTMP_TYPE_AUDIO 8 // 9 = video #define SRS_RTMP_TYPE_VIDEO 9 // 18 = script data #define SRS_RTMP_TYPE_SCRIPT 18 /** * read a audio/video/script-data packet from rtmp stream. * @param type, output the packet type, macros: * SRS_RTMP_TYPE_AUDIO, FlvTagAudio * SRS_RTMP_TYPE_VIDEO, FlvTagVideo * SRS_RTMP_TYPE_SCRIPT, FlvTagScript * otherswise, invalid type. * @param timestamp, in ms, overflow in 50days * @param data, the packet data, according to type: * FlvTagAudio, @see "E.4.2.1 AUDIODATA" * FlvTagVideo, @see "E.4.3.1 VIDEODATA" * FlvTagScript, @see "E.4.4.1 SCRIPTDATA" * User can free the packet by srs_rtmp_free_packet. * @param size, size of packet. * @return the error code. 0 for success; otherwise, error. * * @remark: for read, user must free the data. * @remark: for write, user should never free the data, even if error. * @example /trunk/research/librtmp/srs_play.c * @example /trunk/research/librtmp/srs_publish.c * * @return 0, success; otherswise, failed. */ extern int srs_rtmp_read_packet(srs_rtmp_t rtmp, char* type, uint32_t* timestamp, char** data, int* size ); // @Param data User should never free it anymore. extern int srs_rtmp_write_packet(srs_rtmp_t rtmp, char type, uint32_t timestamp, char* data, int size ); /** * Free the packet allocated by srs_rtmp_read_packet. */ extern void srs_rtmp_free_packet(char* data); /** * whether type is script data and the data is onMetaData. */ extern srs_bool srs_rtmp_is_onMetaData(char type, char* data, int size); /************************************************************* ************************************************************** * audio raw codec ************************************************************** *************************************************************/ /** * write an audio raw frame to srs. * not similar to h.264 video, the audio never aggregated, always * encoded one frame by one, so this api is used to write a frame. * * @param sound_format Format of SoundData. The following values are defined: * 0 = Linear PCM, platform endian * 1 = ADPCM * 2 = MP3 * 3 = Linear PCM, little endian * 4 = Nellymoser 16 kHz mono * 5 = Nellymoser 8 kHz mono * 6 = Nellymoser * 7 = G.711 A-law logarithmic PCM * 8 = G.711 mu-law logarithmic PCM * 9 = reserved * 10 = AAC * 11 = Speex * 14 = MP3 8 kHz * 15 = Device-specific sound * Formats 7, 8, 14, and 15 are reserved. * AAC is supported in Flash Player 9,0,115,0 and higher. * Speex is supported in Flash Player 10 and higher. * @param sound_rate Sampling rate. The following values are defined: * 0 = 5.5 kHz * 1 = 11 kHz * 2 = 22 kHz * 3 = 44 kHz * @param sound_size Size of each audio sample. This parameter only pertains to * uncompressed formats. Compressed formats always decode * to 16 bits internally. * 0 = 8-bit samples * 1 = 16-bit samples * @param sound_type Mono or stereo sound * 0 = Mono sound * 1 = Stereo sound * @param timestamp The timestamp of audio. * * @example /trunk/research/librtmp/srs_aac_raw_publish.c * @example /trunk/research/librtmp/srs_audio_raw_publish.c * * @remark for aac, the frame must be in ADTS format. * @see ISO_IEC_14496-3-AAC-2001.pdf, page 75, 1.A.2.2 ADTS * @remark for aac, only support profile 1-4, AAC main/LC/SSR/LTP, * @see ISO_IEC_14496-3-AAC-2001.pdf, page 23, 1.5.1.1 Audio object type * * @see https://github.com/ossrs/srs/issues/212 * @see E.4.2.1 AUDIODATA of video_file_format_spec_v10_1.pdf * * @return 0, success; otherswise, failed. */ extern int srs_audio_write_raw_frame(srs_rtmp_t rtmp, char sound_format, char sound_rate, char sound_size, char sound_type, char* frame, int frame_size, uint32_t timestamp ); /** * whether aac raw data is in adts format, * which bytes sequence matches '1111 1111 1111'B, that is 0xFFF. * @param aac_raw_data the input aac raw data, a encoded aac frame data. * @param ac_raw_size the size of aac raw data. * * @reamrk used to check whether current frame is in adts format. * @see ISO_IEC_14496-3-AAC-2001.pdf, page 75, 1.A.2.2 ADTS * @example /trunk/research/librtmp/srs_aac_raw_publish.c * * @return 0 false; otherwise, true. */ extern srs_bool srs_aac_is_adts(char* aac_raw_data, int ac_raw_size); /** * parse the adts header to get the frame size, * which bytes sequence matches '1111 1111 1111'B, that is 0xFFF. * @param aac_raw_data the input aac raw data, a encoded aac frame data. * @param ac_raw_size the size of aac raw data. * * @return failed when <=0 failed; otherwise, ok. */ extern int srs_aac_adts_frame_size(char* aac_raw_data, int ac_raw_size); /************************************************************* ************************************************************** * h264 raw codec ************************************************************** *************************************************************/ /** * write h.264 raw frame over RTMP to rtmp server. * @param frames the input h264 raw data, encoded h.264 I/P/B frames data. * frames can be one or more than one frame, * each frame prefixed h.264 annexb header, by N[00] 00 00 01, where N>=0, * for instance, frame = header(00 00 00 01) + payload(67 42 80 29 95 A0 14 01 6E 40) * about annexb, @see ISO_IEC_14496-10-AVC-2003.pdf, page 211. * @param frames_size the size of h264 raw data. * assert frames_size > 0, at least has 1 bytes header. * @param dts the dts of h.264 raw data. * @param pts the pts of h.264 raw data. * * @remark, user should free the frames. * @remark, the tbn of dts/pts is 1/1000 for RTMP, that is, in ms. * @remark, cts = pts - dts * @remark, use srs_h264_startswith_annexb to check whether frame is annexb format. * @example /trunk/research/librtmp/srs_h264_raw_publish.c * @see https://github.com/ossrs/srs/issues/66 * * @return 0, success; otherswise, failed. * for dvbsp error, @see srs_h264_is_dvbsp_error(). * for duplictated sps error, @see srs_h264_is_duplicated_sps_error(). * for duplictated pps error, @see srs_h264_is_duplicated_pps_error(). */ /** For the example file: http://winlinvip.github.io/srs.release/3rdparty/720p.h264.raw The data sequence is: // SPS 000000016742802995A014016E40 // PPS 0000000168CE3880 // IFrame 0000000165B8041014C038008B0D0D3A071..... // PFrame 0000000141E02041F8CDDC562BBDEFAD2F..... User can send the SPS+PPS, then each frame: // SPS+PPS srs_h264_write_raw_frames('000000016742802995A014016E400000000168CE3880', size, dts, pts) // IFrame srs_h264_write_raw_frames('0000000165B8041014C038008B0D0D3A071......', size, dts, pts) // PFrame srs_h264_write_raw_frames('0000000141E02041F8CDDC562BBDEFAD2F......', size, dts, pts) User also can send one by one: // SPS srs_h264_write_raw_frames('000000016742802995A014016E4', size, dts, pts) // PPS srs_h264_write_raw_frames('00000000168CE3880', size, dts, pts) // IFrame srs_h264_write_raw_frames('0000000165B8041014C038008B0D0D3A071......', size, dts, pts) // PFrame srs_h264_write_raw_frames('0000000141E02041F8CDDC562BBDEFAD2F......', size, dts, pts) */ extern int srs_h264_write_raw_frames(srs_rtmp_t rtmp, char* frames, int frames_size, uint32_t dts, uint32_t pts ); /** * whether error_code is dvbsp(drop video before sps/pps/sequence-header) error. * * @see https://github.com/ossrs/srs/issues/203 * @example /trunk/research/librtmp/srs_h264_raw_publish.c * @remark why drop video? * some encoder, for example, ipcamera, will send sps/pps before each IFrame, * so, when error and reconnect the rtmp, the first video is not sps/pps(sequence header), * this will cause SRS server to disable HLS. */ extern srs_bool srs_h264_is_dvbsp_error(int error_code); /** * whether error_code is duplicated sps error. * * @see https://github.com/ossrs/srs/issues/204 * @example /trunk/research/librtmp/srs_h264_raw_publish.c */ extern srs_bool srs_h264_is_duplicated_sps_error(int error_code); /** * whether error_code is duplicated pps error. * * @see https://github.com/ossrs/srs/issues/204 * @example /trunk/research/librtmp/srs_h264_raw_publish.c */ extern srs_bool srs_h264_is_duplicated_pps_error(int error_code); /** * whether h264 raw data starts with the annexb, * which bytes sequence matches N[00] 00 00 01, where N>=0. * @param h264_raw_data the input h264 raw data, a encoded h.264 I/P/B frame data. * @paam h264_raw_size the size of h264 raw data. * @param pnb_start_code output the size of start code, must >=3. * NULL to ignore. * * @reamrk used to check whether current frame is in annexb format. * @example /trunk/research/librtmp/srs_h264_raw_publish.c * * @return 0 false; otherwise, true. */ extern srs_bool srs_h264_startswith_annexb( char* h264_raw_data, int h264_raw_size, int* pnb_start_code ); /************************************************************* ************************************************************* * MP4 muxer and demuxer. * @example /trunk/research/librtmp/srs_ingest_mp4.c ************************************************************* *************************************************************/ typedef void* srs_mp4_t; // The sample struct of mp4. typedef struct { // The handler type, it's SrsMp4HandlerType. uint32_t handler_type; // The dts in milliseconds. uint32_t dts; // The codec id. // video: SrsVideoCodecId. // audio: SrsAudioCodecId. uint16_t codec; // The frame trait, some characteristic: // video: SrsVideoAvcFrameTrait. // audio: SrsAudioAacFrameTrait. uint16_t frame_trait; // The video pts in milliseconds. Ignore for audio. uint32_t pts; // The video frame type, it's SrsVideoAvcFrameType. uint16_t frame_type; // The audio sample rate, it's SrsAudioSampleRate. uint8_t sample_rate; // The audio sound bits, it's SrsAudioSampleBits. uint8_t sound_bits; // The audio sound type, it's SrsAudioChannels. uint8_t channels; // The size of sample payload in bytes. uint32_t nb_sample; // The output sample data, user must free it by srs_mp4_free_sample. uint8_t* sample; } srs_mp4_sample_t; /** * Open mp4 file for muxer(write) or demuxer(read). * @return A MP4 demuxer, NULL if failed. */ extern srs_mp4_t srs_mp4_open_read(const char* file); /** * Close the MP4 demuxer. */ extern void srs_mp4_close(srs_mp4_t mp4); /** * Initialize mp4 demuxer in non-seek mode. * @remark Only support non-seek mode, that is fmp4 or moov before mdata. * For the live streaming, we must feed stream frame by frame. */ extern int srs_mp4_init_demuxer(srs_mp4_t mp4); /** * Read a sample form mp4. * @remark User can use srs_mp4_sample_to_flv_tag to convert mp4 sampel to flv tag. * Use the srs_mp4_to_flv_tag_size to calc the flv tag data size to alloc. */ extern int srs_mp4_read_sample(srs_mp4_t mp4, srs_mp4_sample_t* sample); /** * Free the allocated mp4 sample. */ extern void srs_mp4_free_sample(srs_mp4_sample_t* sample); /** * Calc the size of flv tag, for the mp4 sample to convert to. */ extern int32_t srs_mp4_sizeof(srs_mp4_t mp4, srs_mp4_sample_t* sample); /** * Covert mp4 sample to flv tag. */ extern int srs_mp4_to_flv_tag(srs_mp4_t mp4, srs_mp4_sample_t* sample, char* type, uint32_t* time, char* data, int32_t size); /* error code */ /* whether the error code indicates EOF */ extern srs_bool srs_mp4_is_eof(int error_code); /************************************************************* ************************************************************** * flv codec * @example /trunk/research/librtmp/srs_flv_injecter.c * @example /trunk/research/librtmp/srs_flv_parser.c * @example /trunk/research/librtmp/srs_ingest_flv.c * @example /trunk/research/librtmp/srs_ingest_rtmp.c ************************************************************** *************************************************************/ typedef void* srs_flv_t; /** * Open FLV file in demux mode. * @return A FLV demuxer, NULL if failed. */ extern srs_flv_t srs_flv_open_read(const char* file); /** * Open FlV file in mux mode. * @return A FLV muxer, NULL if failed. */ extern srs_flv_t srs_flv_open_write(const char* file); /** * Close the FLV demuxer or muxer. */ extern void srs_flv_close(srs_flv_t flv); /** * read the flv header. 9bytes header. * @param header, @see E.2 The FLV header, flv_v10_1.pdf in SRS doc. * 3bytes, signature, "FLV", * 1bytes, version, 0x01, * 1bytes, flags, UB[5] 0, UB[1] audio present, UB[1] 0, UB[1] video present. * 4bytes, dataoffset, 0x09, The length of this header in bytes * * @return 0, success; otherswise, failed. * @remark, drop the 4bytes zero previous tag size. */ extern int srs_flv_read_header(srs_flv_t flv, char header[9]); /** * read the flv tag header, 1bytes tag, 3bytes data_size, * 4bytes time, 3bytes stream id. * @param ptype, output the type of tag, macros: * SRS_RTMP_TYPE_AUDIO, FlvTagAudio * SRS_RTMP_TYPE_VIDEO, FlvTagVideo * SRS_RTMP_TYPE_SCRIPT, FlvTagScript * @param pdata_size, output the size of tag data. * @param ptime, output the time of tag, the dts in ms. * * @return 0, success; otherswise, failed. * @remark, user must ensure the next is a tag, srs never check it. */ extern int srs_flv_read_tag_header(srs_flv_t flv, char* ptype, int32_t* pdata_size, uint32_t* ptime ); /** * read the tag data. drop the 4bytes previous tag size * @param data, the data to read, user alloc and free it. * @param size, the size of data to read, get by srs_flv_read_tag_header(). * @remark, srs will ignore and drop the 4bytes previous tag size. */ extern int srs_flv_read_tag_data(srs_flv_t flv, char* data, int32_t size); /** * write the flv header. 9bytes header. * @param header, @see E.2 The FLV header, flv_v10_1.pdf in SRS doc. * 3bytes, signature, "FLV", * 1bytes, version, 0x01, * 1bytes, flags, UB[5] 0, UB[1] audio present, UB[1] 0, UB[1] video present. * 4bytes, dataoffset, 0x09, The length of this header in bytes * * @return 0, success; otherswise, failed. * @remark, auto write the 4bytes zero previous tag size. */ extern int srs_flv_write_header(srs_flv_t flv, char header[9]); /** * write the flv tag to file. * * @return 0, success; otherswise, failed. * @remark, auto write the 4bytes zero previous tag size. */ /* write flv tag to file, auto write the 4bytes previous tag size */ extern int srs_flv_write_tag(srs_flv_t flv, char type, int32_t time, char* data, int size ); /** * get the tag size, for flv injecter to adjust offset, * size = tag_header(11B) + data_size + previous_tag(4B) * @return the size of tag. */ extern int srs_flv_size_tag(int data_size); /* file stream */ /* file stream tellg to get offset */ extern int64_t srs_flv_tellg(srs_flv_t flv); /* seek file stream, offset is form the start of file */ extern void srs_flv_lseek(srs_flv_t flv, int64_t offset); /* error code */ /* whether the error code indicates EOF */ extern srs_bool srs_flv_is_eof(int error_code); /* media codec */ /** * whether the video body is sequence header * @param data, the data of tag, read by srs_flv_read_tag_data(). * @param size, the size of tag, read by srs_flv_read_tag_data(). */ extern srs_bool srs_flv_is_sequence_header(char* data, int32_t size); /** * whether the video body is keyframe * @param data, the data of tag, read by srs_flv_read_tag_data(). * @param size, the size of tag, read by srs_flv_read_tag_data(). */ extern srs_bool srs_flv_is_keyframe(char* data, int32_t size); /************************************************************* ************************************************************** * amf0 codec * @example /trunk/research/librtmp/srs_ingest_flv.c * @example /trunk/research/librtmp/srs_ingest_rtmp.c ************************************************************** *************************************************************/ /* the output handler. */ typedef double srs_amf0_number; /** * parse amf0 from data. * @param nparsed, the parsed size, NULL to ignore. * @return the parsed amf0 object. NULL for error. * @remark user must free the parsed or created object by srs_amf0_free. */ extern srs_amf0_t srs_amf0_parse(char* data, int size, int* nparsed); extern srs_amf0_t srs_amf0_create_string(const char* value); extern srs_amf0_t srs_amf0_create_number(srs_amf0_number value); extern srs_amf0_t srs_amf0_create_ecma_array(); extern srs_amf0_t srs_amf0_create_strict_array(); extern srs_amf0_t srs_amf0_create_object(); extern srs_amf0_t srs_amf0_ecma_array_to_object(srs_amf0_t ecma_arr); extern void srs_amf0_free(srs_amf0_t amf0); /* size and to bytes */ extern int srs_amf0_size(srs_amf0_t amf0); extern int srs_amf0_serialize(srs_amf0_t amf0, char* data, int size); /* type detecter */ extern srs_bool srs_amf0_is_string(srs_amf0_t amf0); extern srs_bool srs_amf0_is_boolean(srs_amf0_t amf0); extern srs_bool srs_amf0_is_number(srs_amf0_t amf0); extern srs_bool srs_amf0_is_null(srs_amf0_t amf0); extern srs_bool srs_amf0_is_object(srs_amf0_t amf0); extern srs_bool srs_amf0_is_ecma_array(srs_amf0_t amf0); extern srs_bool srs_amf0_is_strict_array(srs_amf0_t amf0); /* value converter */ extern const char* srs_amf0_to_string(srs_amf0_t amf0); extern srs_bool srs_amf0_to_boolean(srs_amf0_t amf0); extern srs_amf0_number srs_amf0_to_number(srs_amf0_t amf0); /* value setter */ extern void srs_amf0_set_number(srs_amf0_t amf0, srs_amf0_number value); /* object value converter */ extern int srs_amf0_object_property_count(srs_amf0_t amf0); extern const char* srs_amf0_object_property_name_at(srs_amf0_t amf0, int index); extern srs_amf0_t srs_amf0_object_property_value_at(srs_amf0_t amf0, int index); extern srs_amf0_t srs_amf0_object_property(srs_amf0_t amf0, const char* name); extern void srs_amf0_object_property_set(srs_amf0_t amf0, const char* name, srs_amf0_t value); extern void srs_amf0_object_clear(srs_amf0_t amf0); /* ecma array value converter */ extern int srs_amf0_ecma_array_property_count(srs_amf0_t amf0); extern const char* srs_amf0_ecma_array_property_name_at(srs_amf0_t amf0, int index); extern srs_amf0_t srs_amf0_ecma_array_property_value_at(srs_amf0_t amf0, int index); extern srs_amf0_t srs_amf0_ecma_array_property(srs_amf0_t amf0, const char* name); extern void srs_amf0_ecma_array_property_set(srs_amf0_t amf0, const char* name, srs_amf0_t value); /* strict array value converter */ extern int srs_amf0_strict_array_property_count(srs_amf0_t amf0); extern srs_amf0_t srs_amf0_strict_array_property_at(srs_amf0_t amf0, int index); extern void srs_amf0_strict_array_append(srs_amf0_t amf0, srs_amf0_t value); /************************************************************* ************************************************************** * utilities ************************************************************** *************************************************************/ /** * get the current system time in ms. * use gettimeofday() to get system time. */ extern int64_t srs_utils_time_ms(); /** * get the send bytes. */ extern int64_t srs_utils_send_bytes(srs_rtmp_t rtmp); /** * get the recv bytes. */ extern int64_t srs_utils_recv_bytes(srs_rtmp_t rtmp); /** * parse the dts and pts by time in header and data in tag, * or to parse the RTMP packet by srs_rtmp_read_packet(). * * @param time, the timestamp of tag, read by srs_flv_read_tag_header(). * @param type, the type of tag, read by srs_flv_read_tag_header(). * @param data, the data of tag, read by srs_flv_read_tag_data(). * @param size, the size of tag, read by srs_flv_read_tag_header(). * @param ppts, output the pts in ms, * * @return 0, success; otherswise, failed. * @remark, the dts always equals to @param time. * @remark, the pts=dts for audio or data. * @remark, video only support h.264. */ extern int srs_utils_parse_timestamp( uint32_t time, char type, char* data, int size, uint32_t* ppts ); /** * whether the flv tag specified by param type is ok. * @return true when tag is video/audio/script-data; otherwise, false. */ extern srs_bool srs_utils_flv_tag_is_ok(char type); extern srs_bool srs_utils_flv_tag_is_audio(char type); extern srs_bool srs_utils_flv_tag_is_video(char type); extern srs_bool srs_utils_flv_tag_is_av(char type); /** * get the CodecID of video tag. * Codec Identifier. The following values are defined: * 2 = Sorenson H.263 * 3 = Screen video * 4 = On2 VP6 * 5 = On2 VP6 with alpha channel * 6 = Screen video version 2 * 7 = AVC * @return the code id. 0 for error. */ extern char srs_utils_flv_video_codec_id(char* data, int size); /** * get the AVCPacketType of video tag. * The following values are defined: * 0 = AVC sequence header * 1 = AVC NALU * 2 = AVC end of sequence (lower level NALU sequence ender is * not required or supported) * @return the avc packet type. -1(0xff) for error. */ extern char srs_utils_flv_video_avc_packet_type(char* data, int size); /** * get the FrameType of video tag. * Type of video frame. The following values are defined: * 1 = key frame (for AVC, a seekable frame) * 2 = inter frame (for AVC, a non-seekable frame) * 3 = disposable inter frame (H.263 only) * 4 = generated key frame (reserved for server use only) * 5 = video info/command frame * @return the frame type. 0 for error. */ extern char srs_utils_flv_video_frame_type(char* data, int size); /** * get the SoundFormat of audio tag. * Format of SoundData. The following values are defined: * 0 = Linear PCM, platform endian * 1 = ADPCM * 2 = MP3 * 3 = Linear PCM, little endian * 4 = Nellymoser 16 kHz mono * 5 = Nellymoser 8 kHz mono * 6 = Nellymoser * 7 = G.711 A-law logarithmic PCM * 8 = G.711 mu-law logarithmic PCM * 9 = reserved * 10 = AAC * 11 = Speex * 14 = MP3 8 kHz * 15 = Device-specific sound * Formats 7, 8, 14, and 15 are reserved. * AAC is supported in Flash Player 9,0,115,0 and higher. * Speex is supported in Flash Player 10 and higher. * @return the sound format. -1(0xff) for error. */ extern char srs_utils_flv_audio_sound_format(char* data, int size); /** * get the SoundRate of audio tag. * Sampling rate. The following values are defined: * 0 = 5.5 kHz * 1 = 11 kHz * 2 = 22 kHz * 3 = 44 kHz * @return the sound rate. -1(0xff) for error. */ extern char srs_utils_flv_audio_sound_rate(char* data, int size); /** * get the SoundSize of audio tag. * Size of each audio sample. This parameter only pertains to * uncompressed formats. Compressed formats always decode * to 16 bits internally. * 0 = 8-bit samples * 1 = 16-bit samples * @return the sound size. -1(0xff) for error. */ extern char srs_utils_flv_audio_sound_size(char* data, int size); /** * get the SoundType of audio tag. * Mono or stereo sound * 0 = Mono sound * 1 = Stereo sound * @return the sound type. -1(0xff) for error. */ extern char srs_utils_flv_audio_sound_type(char* data, int size); /** * get the AACPacketType of audio tag. * The following values are defined: * 0 = AAC sequence header * 1 = AAC raw * @return the aac packet type. -1(0xff) for error. */ extern char srs_utils_flv_audio_aac_packet_type(char* data, int size); /************************************************************* ************************************************************** * human readable print. ************************************************************** *************************************************************/ /** * human readable print * @param pdata, output the heap data, NULL to ignore. * user must use srs_amf0_free_bytes to free it. * @return return the *pdata for print. NULL to ignore. */ extern char* srs_human_amf0_print(srs_amf0_t amf0, char** pdata, int* psize); /** * convert the flv tag type to string. * SRS_RTMP_TYPE_AUDIO to "Audio" * SRS_RTMP_TYPE_VIDEO to "Video" * SRS_RTMP_TYPE_SCRIPT to "Data" * otherwise, "Unknown" * @remark user never free the return char*, * it's static shared const string. */ extern const char* srs_human_flv_tag_type2string(char type); /** * get the codec id string. * H.263 = Sorenson H.263 * Screen = Screen video * VP6 = On2 VP6 * VP6Alpha = On2 VP6 with alpha channel * Screen2 = Screen video version 2 * H.264 = AVC * otherwise, "Unknown" * @remark user never free the return char*, * it's static shared const string. */ extern const char* srs_human_flv_video_codec_id2string(char codec_id); /** * get the avc packet type string. * SH = AVC sequence header * Nalu = AVC NALU * SpsPpsEnd = AVC end of sequence * otherwise, "Unknown" * @remark user never free the return char*, * it's static shared const string. */ extern const char* srs_human_flv_video_avc_packet_type2string(char avc_packet_type); /** * get the frame type string. * I = key frame (for AVC, a seekable frame) * P/B = inter frame (for AVC, a non-seekable frame) * DI = disposable inter frame (H.263 only) * GI = generated key frame (reserved for server use only) * VI = video info/command frame * otherwise, "Unknown" * @remark user never free the return char*, * it's static shared const string. */ extern const char* srs_human_flv_video_frame_type2string(char frame_type); /** * get the SoundFormat string. * Format of SoundData. The following values are defined: * LinearPCM = Linear PCM, platform endian * ADPCM = ADPCM * MP3 = MP3 * LinearPCMLe = Linear PCM, little endian * NellymoserKHz16 = Nellymoser 16 kHz mono * NellymoserKHz8 = Nellymoser 8 kHz mono * Nellymoser = Nellymoser * G711APCM = G.711 A-law logarithmic PCM * G711MuPCM = G.711 mu-law logarithmic PCM * Reserved = reserved * AAC = AAC * Speex = Speex * MP3KHz8 = MP3 8 kHz * DeviceSpecific = Device-specific sound * otherwise, "Unknown" * @remark user never free the return char*, * it's static shared const string. */ extern const char* srs_human_flv_audio_sound_format2string(char sound_format); /** * get the SoundRate of audio tag. * Sampling rate. The following values are defined: * 5.5KHz = 5.5 kHz * 11KHz = 11 kHz * 22KHz = 22 kHz * 44KHz = 44 kHz * otherwise, "Unknown" * @remark user never free the return char*, * it's static shared const string. */ extern const char* srs_human_flv_audio_sound_rate2string(char sound_rate); /** * get the SoundSize of audio tag. * Size of each audio sample. This parameter only pertains to * uncompressed formats. Compressed formats always decode * to 16 bits internally. * 8bit = 8-bit samples * 16bit = 16-bit samples * otherwise, "Unknown" * @remark user never free the return char*, * it's static shared const string. */ extern const char* srs_human_flv_audio_sound_size2string(char sound_size); /** * get the SoundType of audio tag. * Mono or stereo sound * Mono = Mono sound * Stereo = Stereo sound * otherwise, "Unknown" * @remark user never free the return char*, * it's static shared const string. */ extern const char* srs_human_flv_audio_sound_type2string(char sound_type); /** * get the AACPacketType of audio tag. * The following values are defined: * SH = AAC sequence header * Raw = AAC raw * otherwise, "Unknown" * @remark user never free the return char*, * it's static shared const string. */ extern const char* srs_human_flv_audio_aac_packet_type2string(char aac_packet_type); /** * Format the RTMP packet to human readable buffer. * @return Whether parse RTMP packet ok. 0, success; otherwise, failed. */ extern int srs_human_format_rtmp_packet(char* buffer, int nb_buffer, char type, uint32_t timestamp, char* data, int size); extern int srs_human_format_rtmp_packet2(char* buffer, int nb_buffer, char type, uint32_t timestamp, char* data, int size, uint32_t pre_timestamp, int64_t pre_now, int64_t starttime, int64_t nb_packets); /** * Format current time to human readable string. * @return A NULL terminated string. */ extern const char* srs_human_format_time(); #ifndef _WIN32 // for getpid. #include <unistd.h> #endif // The log function for librtmp. // User can disable it by define macro SRS_DISABLE_LOG. // Or user can directly use them, or define the alias by: // #define trace(msg, ...) srs_human_trace(msg, ##__VA_ARGS__) // #define warn(msg, ...) srs_human_warn(msg, ##__VA_ARGS__) // #define error(msg, ...) srs_human_error(msg, ##__VA_ARGS__) #ifdef SRS_DISABLE_LOG #define srs_human_trace(msg, ...) (void)0 #define srs_human_warn(msg, ...) (void)0 #define srs_human_error(msg, ...) (void)0 #define srs_human_verbose(msg, ...) (void)0 #define srs_human_raw(msg, ...) (void)0 #else #include <string.h> #include <errno.h> #define srs_human_trace(msg, ...) \ fprintf(stdout, "[T][%d][%s] ", getpid(), srs_human_format_time());\ fprintf(stdout, msg, ##__VA_ARGS__); fprintf(stdout, "\n") #define srs_human_warn(msg, ...) \ fprintf(stdout, "[W][%d][%s][%d] ", getpid(), srs_human_format_time(), errno); \ fprintf(stdout, msg, ##__VA_ARGS__); \ fprintf(stdout, "\n") #define srs_human_error(msg, ...) \ fprintf(stderr, "[E][%d][%s][%d] ", getpid(), srs_human_format_time(), errno);\ fprintf(stderr, msg, ##__VA_ARGS__); \ fprintf(stderr, " (%s)\n", strerror(errno)) #define srs_human_verbose(msg, ...) (void)0 #define srs_human_raw(msg, ...) printf(msg, ##__VA_ARGS__) #endif /************************************************************* ************************************************************** * IO hijack, use your specified io functions. ************************************************************** *************************************************************/ // the void* will convert to your handler for io hijack. typedef void* srs_hijack_io_t; #ifdef SRS_HIJACK_IO #ifndef _WIN32 // for iovec. #include <sys/uio.h> #endif /** * get the hijack io object in rtmp protocol sdk. * @remark, user should never provides this method, srs-librtmp provides it. */ extern srs_hijack_io_t srs_hijack_io_get(srs_rtmp_t rtmp); #endif // define the following macro and functions in your module to hijack the io. // the example @see https://github.com/ossrs/srs-bench // which use librtmp but use its own io(use st also). #ifdef SRS_HIJACK_IO /** * create hijack. * @return NULL for error; otherwise, ok. */ extern srs_hijack_io_t srs_hijack_io_create(); /** * destroy the context, user must close the socket. */ extern void srs_hijack_io_destroy(srs_hijack_io_t ctx); /** * create socket, not connect yet. * @param owner, the rtmp context which create this socket. * @return 0, success; otherswise, failed. */ extern int srs_hijack_io_create_socket(srs_hijack_io_t ctx, srs_rtmp_t owner); /** * connect socket at server_ip:port. * @return 0, success; otherswise, failed. */ extern int srs_hijack_io_connect(srs_hijack_io_t ctx, const char* server_ip, int port); /** * read from socket. * @return 0, success; otherswise, failed. */ extern int srs_hijack_io_read(srs_hijack_io_t ctx, void* buf, size_t size, ssize_t* nread); /** * set the socket recv timeout in ms. * @return 0, success; otherswise, failed. */ extern int srs_hijack_io_set_recv_timeout(srs_hijack_io_t ctx, int64_t tm); /** * get the socket recv timeout. * @return 0, success; otherswise, failed. */ extern int64_t srs_hijack_io_get_recv_timeout(srs_hijack_io_t ctx); /** * get the socket recv bytes. * @return 0, success; otherswise, failed. */ extern int64_t srs_hijack_io_get_recv_bytes(srs_hijack_io_t ctx); /** * set the socket send timeout in ms. * @return 0, success; otherswise, failed. */ extern int srs_hijack_io_set_send_timeout(srs_hijack_io_t ctx, int64_t tm); /** * get the socket send timeout. * @return 0, success; otherswise, failed. */ extern int64_t srs_hijack_io_get_send_timeout(srs_hijack_io_t ctx); /** * get the socket send bytes. * @return 0, success; otherswise, failed. */ extern int64_t srs_hijack_io_get_send_bytes(srs_hijack_io_t ctx); /** * writev of socket. * @return 0, success; otherswise, failed. * @remark We assume that the writev always write all data to peer, like what ST or block-socket done. */ extern int srs_hijack_io_writev(srs_hijack_io_t ctx, const iovec *iov, int iov_size, ssize_t* nwrite); /** * whether the timeout is never timeout in ms. * @return 0, with timeout specified; otherwise, never timeout. */ extern int srs_hijack_io_is_never_timeout(srs_hijack_io_t ctx, int64_t tm); /** * read fully, fill the buf exactly size bytes. * @return 0, success; otherswise, failed. */ extern int srs_hijack_io_read_fully(srs_hijack_io_t ctx, void* buf, size_t size, ssize_t* nread); /** * write bytes to socket. * @return 0, success; otherswise, failed. * @remark We assume that the write always write all data to peer, like what ST or block-socket done. */ extern int srs_hijack_io_write(srs_hijack_io_t ctx, void* buf, size_t size, ssize_t* nwrite); #endif /************************************************************* ************************************************************** * Windows SRS-LIBRTMP solution ************************************************************** *************************************************************/ // for srs-librtmp, @see https://github.com/ossrs/srs/issues/213 #ifdef _WIN32 // for time. #define _CRT_SECURE_NO_WARNINGS #include <time.h> int gettimeofday(struct timeval* tv, struct timezone* tz); #define PRId64 "lld" // for inet helpers. typedef int socklen_t; const char *inet_ntop(int af, const void *src, char *dst, socklen_t size); // for mkdir(). #include<direct.h> // for open(). typedef int mode_t; #define S_IRUSR 0 #define S_IWUSR 0 #define S_IXUSR 0 #define S_IRGRP 0 #define S_IWGRP 0 #define S_IXGRP 0 #define S_IROTH 0 #define S_IXOTH 0 // for file seek. #include <io.h> #include <fcntl.h> #define open _open #define close _close #define lseek _lseek #define write _write #define read _read // for socket. ssize_t writev(int fd, const struct iovec *iov, int iovcnt); typedef int64_t useconds_t; int usleep(useconds_t usec); int socket_setup(); int socket_cleanup(); // others. #define snprintf _snprintf #endif /************************************************************* ************************************************************* * Deprecated APIs, maybe removed in future versions. ************************************************************* *************************************************************/ /** * Deprecated, for bandwidth test check only. */ extern srs_rtmp_t srs_rtmp_create2(const char* url); /** * Deprecated, use seperate function to retrieve information from rtmp, * for example, use srs_rtmp_get_server_ip to get server ip. */ extern int srs_rtmp_connect_app2(srs_rtmp_t rtmp, char srs_server_ip[128], char srs_server[128], char srs_primary[128], char srs_authors[128], char srs_version[32], int* srs_id, int* srs_pid ); /** * Deprecated, use srs_human_format_rtmp_packet instead. */ extern int srs_human_print_rtmp_packet(char type, uint32_t timestamp, char* data, int size); extern int srs_human_print_rtmp_packet2(char type, uint32_t timestamp, char* data, int size, uint32_t pre_timestamp); extern int srs_human_print_rtmp_packet3(char type, uint32_t timestamp, char* data, int size, uint32_t pre_timestamp, int64_t pre_now); extern int srs_human_print_rtmp_packet4(char type, uint32_t timestamp, char* data, int size, uint32_t pre_timestamp, int64_t pre_now, int64_t starttime, int64_t nb_packets); #ifdef __cplusplus } #endif #endif
37.19279
134
0.647541
[ "object" ]
fe66e86a702318c8e6d2400facb2bd4e0cf56c94
8,108
h
C
vconverter.h
lisu188/vstd
0024620dd11507123aa1d7e1f693d0d4691b29bf
[ "MIT" ]
null
null
null
vconverter.h
lisu188/vstd
0024620dd11507123aa1d7e1f693d0d4691b29bf
[ "MIT" ]
null
null
null
vconverter.h
lisu188/vstd
0024620dd11507123aa1d7e1f693d0d4691b29bf
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2019 Andrzej Lis * * 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. */ #pragma once #include <boost/python.hpp> #include "vcast.h" namespace vstd { namespace detail { template<typename Ret, typename... Args> struct builder { static void build(PyObject *obj_ptr, boost::python::converter::rvalue_from_python_stage1_data *data) { help(obj_ptr, data); } template<typename R=Ret> static void help(PyObject *obj_ptr, boost::python::converter::rvalue_from_python_stage1_data *data, typename vstd::disable_if<vstd::is_shared_ptr<R>::value>::type * = 0) { void *storage = ((boost::python::converter::rvalue_from_python_storage <std::function<R(Args...) >> *) data)->storage.bytes; boost::python::object func = boost::python::object(boost::python::handle<>( boost::python::borrowed( boost::python::incref(obj_ptr)))); new(storage) std::function<R(Args...)>([func](Args... args) { return boost::python::extract<R>( boost::python::incref(func(args...).ptr())); }); data->convertible = storage; } template<typename R=Ret> static void help(PyObject *obj_ptr, boost::python::converter::rvalue_from_python_stage1_data *data, typename vstd::enable_if<vstd::is_shared_ptr<R>::value>::type * = 0) { typedef typename R::element_type *ptr_type; void *storage = ((boost::python::converter::rvalue_from_python_storage <std::function<R(Args...) >> *) data)->storage.bytes; boost::python::object func = boost::python::object( boost::python::handle<>(boost::python::borrowed( boost::python::incref(obj_ptr)))); new(storage) std::function<R(Args...)>([func](Args... args) { return R(vstd::functional::call( boost::python::extract<ptr_type>( boost::python::incref(func(args...).ptr())))); }); data->convertible = storage; } }; template<typename... Args> struct builder<void, Args...> { static void build(PyObject *obj_ptr, boost::python::converter::rvalue_from_python_stage1_data *data) { void *storage = ((boost::python::converter::rvalue_from_python_storage <std::function<void(Args...) >> *) data)->storage.bytes; boost::python::object func = boost::python::object( boost::python::handle<>( boost::python::borrowed( boost::python::incref(obj_ptr)))); new(storage) std::function<void(Args...)>([func](Args... args) { func(args...); }); data->convertible = storage; } }; template<typename... Args> struct builder<bool, Args...> { static void build(PyObject *obj_ptr, boost::python::converter::rvalue_from_python_stage1_data *data) { void *storage = ((boost::python::converter::rvalue_from_python_storage <std::function<bool(Args...) >> *) data)->storage.bytes; boost::python::object func = boost::python::object( boost::python::handle<>( boost::python::borrowed( boost::python::incref(obj_ptr)))); new(storage) std::function<bool(Args...)>([func](Args... args) { return func(args...).ptr() == Py_True; }); data->convertible = storage; } }; template<class Source, class Target> struct implicit_cast { static void *convertible(PyObject *obj) { return boost::python::converter::implicit_rvalue_convertible_from_python(obj, boost::python::converter::registered<Source>::converters) ? obj : 0; } static void construct(PyObject *obj, boost::python::converter::rvalue_from_python_stage1_data *data) { void *storage = ((boost::python::converter::rvalue_from_python_storage<Target> *) data)->storage.bytes; boost::python::arg_from_python<Source> get_source(obj); bool convertible = get_source.convertible(); BOOST_VERIFY (convertible); new(storage) Target(vstd::cast<Target>(get_source())); data->convertible = storage; } }; } namespace detail { template<typename Ret, typename... Args> struct function_converter { function_converter() { boost::python::converter::registry::push_back( [](PyObject *obj_ptr) -> void * { if (PyCallable_Check(obj_ptr)) { return obj_ptr; } return nullptr; }, detail::builder<Ret, Args...>::build, boost::python::type_id<std::function<Ret(Args...) >>()); } }; template<typename T> struct register_pointer { register_pointer() { boost::python::register_ptr_to_python<std::shared_ptr<T> >(); } }; } template<typename Ret, typename... Args> struct function_converter { function_converter() { static detail::function_converter<Ret, Args...> _dummy; } }; template<typename T> void register_pointer() { static detail::register_pointer<T> _dummy; } namespace detail { template<class Source, class Target> struct implicitly_convertible_cast { implicitly_convertible_cast(boost::type<Source> * = 0, boost::type<Target> * = 0) { boost::python::converter::registry::push_back( &detail::implicit_cast<Source, Target>::convertible, &detail::implicit_cast<Source, Target>::construct, boost::python::type_id<Target>(), &boost::python::converter::expected_from_python_type_direct<Source>::get_pytype); } }; } template<class Source, class Target> void implicitly_convertible_cast() { static detail::implicitly_convertible_cast<Source, Target> _dummy; } }
47.139535
463
0.538974
[ "object" ]
b980de3842cbc6ac6e7c0f5284a2c6ac55448fcd
4,433
h
C
aws-cpp-sdk-kendra/include/aws/kendra/model/AdditionalResultAttribute.h
grujicbr/aws-sdk-cpp
bdd43c178042f09c6739645e3f6cd17822a7c35c
[ "Apache-2.0" ]
1
2020-03-11T05:36:20.000Z
2020-03-11T05:36:20.000Z
aws-cpp-sdk-kendra/include/aws/kendra/model/AdditionalResultAttribute.h
grujicbr/aws-sdk-cpp
bdd43c178042f09c6739645e3f6cd17822a7c35c
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-kendra/include/aws/kendra/model/AdditionalResultAttribute.h
grujicbr/aws-sdk-cpp
bdd43c178042f09c6739645e3f6cd17822a7c35c
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/kendra/Kendra_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/kendra/model/AdditionalResultAttributeValueType.h> #include <aws/kendra/model/AdditionalResultAttributeValue.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace kendra { namespace Model { /** * <p/><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/kendra-2019-02-03/AdditionalResultAttribute">AWS * API Reference</a></p> */ class AWS_KENDRA_API AdditionalResultAttribute { public: AdditionalResultAttribute(); AdditionalResultAttribute(Aws::Utils::Json::JsonView jsonValue); AdditionalResultAttribute& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p/> */ inline const Aws::String& GetKey() const{ return m_key; } /** * <p/> */ inline bool KeyHasBeenSet() const { return m_keyHasBeenSet; } /** * <p/> */ inline void SetKey(const Aws::String& value) { m_keyHasBeenSet = true; m_key = value; } /** * <p/> */ inline void SetKey(Aws::String&& value) { m_keyHasBeenSet = true; m_key = std::move(value); } /** * <p/> */ inline void SetKey(const char* value) { m_keyHasBeenSet = true; m_key.assign(value); } /** * <p/> */ inline AdditionalResultAttribute& WithKey(const Aws::String& value) { SetKey(value); return *this;} /** * <p/> */ inline AdditionalResultAttribute& WithKey(Aws::String&& value) { SetKey(std::move(value)); return *this;} /** * <p/> */ inline AdditionalResultAttribute& WithKey(const char* value) { SetKey(value); return *this;} /** * <p/> */ inline const AdditionalResultAttributeValueType& GetValueType() const{ return m_valueType; } /** * <p/> */ inline bool ValueTypeHasBeenSet() const { return m_valueTypeHasBeenSet; } /** * <p/> */ inline void SetValueType(const AdditionalResultAttributeValueType& value) { m_valueTypeHasBeenSet = true; m_valueType = value; } /** * <p/> */ inline void SetValueType(AdditionalResultAttributeValueType&& value) { m_valueTypeHasBeenSet = true; m_valueType = std::move(value); } /** * <p/> */ inline AdditionalResultAttribute& WithValueType(const AdditionalResultAttributeValueType& value) { SetValueType(value); return *this;} /** * <p/> */ inline AdditionalResultAttribute& WithValueType(AdditionalResultAttributeValueType&& value) { SetValueType(std::move(value)); return *this;} /** * <p/> */ inline const AdditionalResultAttributeValue& GetValue() const{ return m_value; } /** * <p/> */ inline bool ValueHasBeenSet() const { return m_valueHasBeenSet; } /** * <p/> */ inline void SetValue(const AdditionalResultAttributeValue& value) { m_valueHasBeenSet = true; m_value = value; } /** * <p/> */ inline void SetValue(AdditionalResultAttributeValue&& value) { m_valueHasBeenSet = true; m_value = std::move(value); } /** * <p/> */ inline AdditionalResultAttribute& WithValue(const AdditionalResultAttributeValue& value) { SetValue(value); return *this;} /** * <p/> */ inline AdditionalResultAttribute& WithValue(AdditionalResultAttributeValue&& value) { SetValue(std::move(value)); return *this;} private: Aws::String m_key; bool m_keyHasBeenSet; AdditionalResultAttributeValueType m_valueType; bool m_valueTypeHasBeenSet; AdditionalResultAttributeValue m_value; bool m_valueHasBeenSet; }; } // namespace Model } // namespace kendra } // namespace Aws
26.230769
144
0.66005
[ "model" ]
b981025a01a2d80af41b37a6957b278d2681076e
6,978
h
C
src/GlobalSocketLogger.h
nQuantums/JunkCpp
1b0b9657520cc2c30a78c5b68915db872358146e
[ "MIT" ]
1
2018-12-11T14:51:43.000Z
2018-12-11T14:51:43.000Z
windows/cpp/Junk/GlobalSocketLogger.h
nQuantums/tips
cdea2a0e778d2de14cd69882f6273c872c366f03
[ "MIT" ]
null
null
null
windows/cpp/Junk/GlobalSocketLogger.h
nQuantums/tips
cdea2a0e778d2de14cd69882f6273c872c366f03
[ "MIT" ]
null
null
null
#pragma once #ifndef __JUNK_GLOBALSOCKETLOGGER_H__ #define __JUNK_GLOBALSOCKETLOGGER_H__ #include "JunkConfig.h" #include "JunkDef.h" #include "Socket.h" #include "Thread.h" #include "File.h" #include <vector> #include <sstream> #include <string.h> _JUNK_BEGIN //! GlobalSocketLogger からのログを処理するサーバー処理クラス class JUNKAPICLASS LogServer { public: //! サーバーへのコマンドID #if (defined _MSC_VER) && (_MSC_VER <= 1500) enum CommandEnum { #else enum class CommandEnum : uint32_t { #endif Unknown = 0, WriteLog, Flush, FileClose, BinaryLog, }; //! サーバーからの応答ID #if (defined _MSC_VER) && (_MSC_VER <= 1500) enum ResultEnum { #else enum class ResultEnum : uint32_t { #endif Ok = 0, Error, }; //! ログの種類 #if (defined _MSC_VER) && (_MSC_VER <= 1500) enum LogTypeEnum { #else enum class LogTypeEnum : uint16_t { #endif Enter = 1, Leave = 2, }; #pragma pack(push, 1) //! コマンド作成時の new 抑止用一時バッファ情報 struct TempBuf { void* Ptr; size_t Size; TempBuf(void* p, size_t size) { this->Ptr = p; this->Size = size; } }; //! サーバーへのコマンド、応答パケット基本クラス struct Pkt { int32_t Size; // 以降に続くパケットバイト数 union { uint32_t Command; //!< コマンドID uint32_t Result; //!< 応答コードID }; //! パケット全体のサイズ(bytes) _FINLINE size_t PacketSize() const { return sizeof(this->Size) + this->Size; } static inline Pkt* Allocate(TempBuf tempBuf, size_t size) { Pkt* pPkt = (Pkt*)(sizeof(pPkt->Size) + size <= tempBuf.Size ? tempBuf.Ptr : new uint8_t[sizeof(pPkt->Size) + size]); pPkt->Size = (int32_t)size; return pPkt; } static inline Pkt* Allocate(TempBuf tempBuf, CommandEnum command, size_t dataSize) { Pkt* pPkt = Allocate(tempBuf, sizeof(pPkt->Command) + dataSize); pPkt->Command = (uint32_t)command; return pPkt; } static inline Pkt* Allocate(TempBuf tempBuf, CommandEnum command, const void* pData, size_t dataSize) { Pkt* pPkt = Allocate(tempBuf, sizeof(pPkt->Command) + dataSize); pPkt->Command = (uint32_t)command; memcpy(&pPkt[1], pData, dataSize); return pPkt; } static inline void Deallocate(TempBuf tempBuf, Pkt* pPkt) { if (pPkt != tempBuf.Ptr && pPkt != NULL) delete pPkt; } }; //! ログ出力コマンドパケット struct PktCommandLogWrite : public Pkt { uint32_t Pid; //!< プロセスID uint32_t Tid; //!< スレッドID uint16_t Depth; //!< 呼び出し階層深度 uint16_t LogType; //!< ログ種類 char Text[1]; //!< UTF-8エンコードされた文字列データ //! テキストサイズ(bytes) _FINLINE size_t TextSize() const { return this->Size - sizeof(this->Command) - sizeof(this->Pid) - sizeof(this->Tid) - sizeof(this->Depth) - sizeof(this->LogType); } static PktCommandLogWrite* Allocate(TempBuf tempBuf, uint32_t pid, uint32_t tid, uint16_t depth, LogTypeEnum logType, const char* pszText, size_t size) { PktCommandLogWrite* pPkt = (PktCommandLogWrite*)Pkt::Allocate(tempBuf, CommandEnum::WriteLog, sizeof(pPkt->Pid) + sizeof(pPkt->Tid) + sizeof(pPkt->Depth) + sizeof(pPkt->LogType) + size); pPkt->Pid = pid; pPkt->Tid = tid; pPkt->Depth = depth; pPkt->LogType = (uint16_t)logType; memcpy(pPkt->Text, pszText, size); return pPkt; } }; //! バイナリ形式ログ出力設定コマンドパケット struct PktCommandBinaryLog : public Pkt { int32_t Binary; //!< 0以外ならバイナリ static PktCommandBinaryLog* Allocate(TempBuf tempBuf, bool binary) { int32_t binaryValue = binary; PktCommandBinaryLog* pPkt = (PktCommandBinaryLog*)Pkt::Allocate(tempBuf, CommandEnum::BinaryLog, &binaryValue, sizeof(binaryValue)); return pPkt; } }; #pragma pack(pop) //! CommandWriteLog 内から呼び出されるハンドラ typedef void (*CommandWriteLogHandler)(SocketRef sock, PktCommandLogWrite* pCmd, const char* pszRemoteName); static void Startup(); //!< ログ出力先など初期化、プログラム起動時一回だけ呼び出す、スレッドアンセーフ static void Cleanup(); //!< 終了処理、プログラム終了時一回だけ呼び出す、スレッドアンセーフ LogServer(); ibool Start(const wchar_t* pszLogFolder, int port); //!< 別スレッドでサーバー処理を開始する、スレッドアンセーフ void Stop(); //!< サーバー処理スレッドを停止する、スレッドアンセーフ void Write(const char* bytes, size_t size); //!< ログファイルへ書き込む void CommandBinaryLog(SocketRef sock, PktCommandBinaryLog* pCmd); //!< バイナリ形式でログ出力するかどうか設定する void CommandWriteLog(std::vector<uint8_t>& buf, SocketRef sock, PktCommandLogWrite* pCmd, const std::string& remoteName); //!< ログ出力コマンド処理 void CommandFlush(SocketRef sock, Pkt* pCmd); //!< フラッシュコマンド処理 void CommandFileClose(SocketRef sock, Pkt* pCmd); //!< 現在のログファイルを閉じる void SetCommandWriteLogHandler(CommandWriteLogHandler handler); //!< CommandWriteLog 内から呼び出されるハンドラを設定する CommandWriteLogHandler GetCommandWriteLogHandler(); //!< CommandWriteLog 内から呼び出されるハンドラを取得する private: //! クライアント毎の処理 class Client { public: Client(LogServer* pOwner, Socket::Handle hClient, const char* pszRemoteName); //!< コンストラクタ、クライアント通信スレッドが開始される void Stop(bool wait = false); //!< クライアント通信スレッドを停止する private: static intptr_t ThreadStart(void* pObj); void ThreadProc(); LogServer* m_pOwner; Socket m_Socket; std::string m_RemoteName; Thread m_Thread; }; static intptr_t ThreadStart(void* pObj); //!< 接続受付スレッド開始アドレス void ThreadProc(); //!< 接続受付スレッド処理 void AddClient(Client* pClient); //!< 指定クライアントを管理下へ追加する bool RemoveClient(Client* pClient, bool wait = false); //!< 指定クライアントを管理下から除外する std::wstring m_LogFolder; //!< ログの置き場フォルダ File m_LogFile; //!< ログファイル CriticalSection m_LogFileCs; //!< m_LogFile アクセス排他処理用 volatile ibool m_RequestStop; //!< サーバー停止要求フラグ Event m_RequestStopEvent; //!< サーバー停止要求イベント Socket m_AcceptanceSocket; //!< 接続受付ソケット Thread m_AcceptanceThread; //!< 接続受付処理スレッド std::vector<Client*> m_Clients; //!< クライアント処理配列 CriticalSection m_ClientsCs; //!< m_Clients アクセス排他処理用 bool m_BinaryLog; //!< バイナリ形式でログを出力するかどうか CommandWriteLogHandler m_CommandWriteLogHandler; //!< CommandWriteLog 内から呼び出されるハンドラ }; #define JUNKLOG_DELIMITER (L',') //! ソケットを使いサーバーへログを送るシングルトンクラス class JUNKAPICLASS GlobalSocketLogger { public: //! インスタンス struct Instance; static Instance* GetInstance(); //!< 通信用ソケットなどの情報を保持するインスタンスを取得する static void Startup(const wchar_t* pszHost, int port); //!< ログ出力先など初期化、プログラム起動時一回だけ呼び出す、スレッドセーフ static void Startup(const char* pszHost, int port); //!< ログ出力先など初期化、プログラム起動時一回だけ呼び出す、スレッドセーフ static void Startup(wchar_t* pszIniFile = L"GlobalSocketLogger.ini"); //!< ログ出力先など初期化、プログラム起動時一回だけ呼び出す、スレッドセーフ static void Startup(Instance* pInstance); //!< 他DLLのインスタンスを指定して初期化する static void Cleanup(); //!< 終了処理、プログラム終了時一回だけ呼び出す、スレッドアンセーフ static LogServer::Pkt* Command(LogServer::TempBuf tempBuf, LogServer::Pkt* pCmd); //!< サーバーへコマンドパケットを送り応答を取得する、スレッドセーフ static void BinaryLog(bool binary); //!< サーバーのログ出力形式をバイナリかどうか設定する、スレッドセーフ static void WriteLog(uint32_t depth, LogServer::LogTypeEnum logType, const wchar_t* pszText); //!< サーバーへログを送る、スレッドセーフ static void Flush(); //!< サーバーへログをファイルへフラッシュ要求、スレッドセーフ static void FileClose(); //!< サーバーへ現在のログファイルを閉じる要求、スレッドセーフ static intptr_t GetDepth(); //!< 現在のスレッドの呼び出し深度の取得 static intptr_t IncrementDepth(); //!< 現在のスレッドの呼び出し深度をインクリメント static intptr_t DecrementDepth(); //!< 現在のスレッドの呼び出し深度をデクリメント }; _JUNK_END #endif
31.151786
189
0.725853
[ "vector" ]
b9893b6c62f50cc1206e84bc55e458614d39b2d8
2,623
h
C
music/abcmidi-m4-64/abc.h
marshallmidden/m4
8ff1cb050efdefe6963c6d7f459fd6f3d25eea94
[ "BSD-2-Clause" ]
null
null
null
music/abcmidi-m4-64/abc.h
marshallmidden/m4
8ff1cb050efdefe6963c6d7f459fd6f3d25eea94
[ "BSD-2-Clause" ]
null
null
null
music/abcmidi-m4-64/abc.h
marshallmidden/m4
8ff1cb050efdefe6963c6d7f459fd6f3d25eea94
[ "BSD-2-Clause" ]
null
null
null
/* abc.h - header file shared by abc2midi, abc2abc and yaps */ /* Copyright James Allwright 2000 */ /* may be copied under the terms of the GNU public license */ typedef enum { ABC2MIDI, ABC2ABC, YAPS, ABCMATCH} programname; typedef enum { TIMESIG_NORMAL, TIMESIG_FREE_METER, TIMESIG_COMMON, TIMESIG_CUT, TIMESIG_COMPLEX } timesig_type_t; typedef struct timesig_details { timesig_type_t type; int num; int denom; int complex_values[8]; int num_values; } timesig_details_t; /* define types of abc object */ typedef enum { /* types of bar sign */ SINGLE_BAR, DOUBLE_BAR, DOTTED_BAR, BAR_REP, REP_BAR, PLAY_ON_REP, REP1, REP2, /* BAR1 = SINGLE_BAR + REP1 */ /* REP_BAR2 = REP_BAR + REP2 */ BAR1, REP_BAR2, DOUBLE_REP, THICK_THIN, THIN_THICK, /* other things */ PART, TEMPO, TIME, KEY, REST, TUPLE, /* CHORD replaced by CHORDON and CHORDOFF */ NOTE, NONOTE, OLDTIE, TEXT, SLUR_ON, SLUR_OFF, TIE, CLOSE_TIE, TITLE, CHANNEL, TRANSPOSE, RTRANSPOSE, GTRANSPOSE, GRACEON, GRACEOFF, SETGRACE, SETC, SETTRIM, EXPAND, GCHORD, GCHORDON, GCHORDOFF, VOICE, CHORDON, CHORDOFF, CHORDOFFEX, DRUMON, DRUMOFF, DRONEON, DRONEOFF, SLUR_TIE, TNOTE, /* broken rhythm */ LT, GT, DYNAMIC, LINENUM, MUSICLINE, MUSICSTOP, WORDLINE, WORDSTOP, INSTRUCTION, NOBEAM, CHORDNOTE, CLEF, PRINTLINE, NEWPAGE, LEFT_TEXT, CENTRE_TEXT, VSKIP, COPYRIGHT, COMPOSER, ARPEGGIO, SPLITVOICE, META, PEDAL_ON, PEDAL_OFF, EFFECT } featuretype; /* note decorations */ #define DECSIZE 13 extern char decorations[]; #define STACCATO 0 #define TENUTO 1 #define LOUD 2 #define ROLL 3 #define FERMATA 4 #define ORNAMENT 5 #define TRILL 6 #define BOWUP 7 #define BOWDOWN 8 #define BREATH 9 #define CODA 10 #define UPPERMORDENT 11 #define SEGNO 12 /* The vstring routines provide a simple way to handle */ /* arbitrary length strings */ struct vstring { int len; int limit; char* st; }; #ifndef KANDR /* vstring routines */ extern void initvstring(struct vstring* s); extern void extendvstring(struct vstring* s); extern void addch(char ch, struct vstring* s); extern void addtext(char* text, struct vstring* s); extern void clearvstring(struct vstring* s); extern void freevstring(struct vstring* s); /* error-handling routines */ extern void event_error(char *s); extern void event_fatal_error(char *s); extern void event_warning(char *s); #else /* vstring routines */ extern void initvstring(); extern void extendvstring(); extern void addch(); extern void addtext(); extern void clearvstring(); extern void freevstring(); /* error-handling routines */ extern void event_error(); extern void event_fatal_error(); extern void event_warning(); #endif
16.092025
62
0.749905
[ "object" ]
b993e1ae53fa37a4c2771eefaef1896a30a22729
560
h
C
docs/parallel/concrt/codesnippet/CPP/creating-asynchronous-operations-in-cpp-for-windows-store-apps_8.h
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
965
2017-06-25T23:57:11.000Z
2022-03-31T14:17:32.000Z
docs/parallel/concrt/codesnippet/CPP/creating-asynchronous-operations-in-cpp-for-windows-store-apps_8.h
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
3,272
2017-06-24T00:26:34.000Z
2022-03-31T22:14:07.000Z
docs/parallel/concrt/codesnippet/CPP/creating-asynchronous-operations-in-cpp-for-windows-store-apps_8.h
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
951
2017-06-25T12:36:14.000Z
2022-03-26T22:49:06.000Z
private: // Splits the provided text string into individual words. concurrency::task<std::vector<std::wstring>> MakeWordList(Platform::String^ text); // Finds the most common words that are at least the provided minimum length. concurrency::task<std::vector<std::pair<std::wstring, size_t>>> FindCommonWords(const std::vector<std::wstring>& words, size_t min_length, size_t count); // Shows the most common words on the UI. void ShowResults(const std::vector<std::pair<std::wstring, size_t>>& commonWords);
62.222222
161
0.694643
[ "vector" ]
b9a69e635505c5e739f834caea9f719de2f748f5
798
h
C
PagoPaSDK.framework/Headers/WALCore.h
teamdigitale/pagopa-ios-example
e4b1c4fa13a12328e733bfc40c1b1b721fb201b3
[ "BSD-3-Clause" ]
2
2017-12-21T14:49:11.000Z
2019-09-17T07:54:34.000Z
PagoPaSDK.framework/Headers/WALCore.h
teamdigitale/pagopa-ios-example
e4b1c4fa13a12328e733bfc40c1b1b721fb201b3
[ "BSD-3-Clause" ]
1
2018-03-28T13:50:44.000Z
2019-11-20T11:57:07.000Z
PagoPaSDK.framework/Headers/WALCore.h
teamdigitale/pagopa-ios-example
e4b1c4fa13a12328e733bfc40c1b1b721fb201b3
[ "BSD-3-Clause" ]
2
2019-05-28T16:22:39.000Z
2019-09-22T11:43:12.000Z
// AUTOGENERATED FILE - DO NOT MODIFY! // This file generated by Djinni from core.djinni #import "WALRouterType.h" #import <Foundation/Foundation.h> @class WALCore; @class WALUiRouter; @protocol WALCoreParamsInterface; @protocol WALUiNativeRouter; @interface WALCore : NSObject + (nullable WALCore *)createCore:(nullable id<WALCoreParamsInterface>)coreParamsInterface; /** important: call this method after the ppa_core object creation! */ - (void)setupCore; - (nullable WALUiRouter *)getUiRouter; - (void)configurePerypheralRouter:(WALRouterType)routerType nativeRouter:(nullable id<WALUiNativeRouter>)nativeRouter; - (nullable WALUiRouter *)getPerypheralRouter:(WALRouterType)routerType; - (void)setNativeRouter:(nullable id<WALUiNativeRouter>)uiNativeRouter; @end
27.517241
90
0.776942
[ "object" ]
b9ac3e121627eeb39d45ca6559c18eb0a6954b65
57,921
h
C
source/blender/editors/include/UI_icons.h
naetherm/Bforartists
4d78856b76544b9eeb49e7dd388b4cf41d58d7e4
[ "Naumen", "Condor-1.1", "MS-PL" ]
3
2019-09-16T10:29:19.000Z
2022-02-11T14:43:18.000Z
source/blender/editors/include/UI_icons.h
naetherm/Bforartists
4d78856b76544b9eeb49e7dd388b4cf41d58d7e4
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
source/blender/editors/include/UI_icons.h
naetherm/Bforartists
4d78856b76544b9eeb49e7dd388b4cf41d58d7e4
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
/* * 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. * * The Original Code is Copyright (C) 2009 Blender Foundation. * All rights reserved. */ /** \file * \ingroup editorui */ /* Note: this is included multiple times with different #defines for DEF_ICON. */ /* Auto define more specific types for places that do not need the distinction. */ #ifndef DEF_ICON_SCENE # define DEF_ICON_SCENE DEF_ICON #endif #ifndef DEF_ICON_COLLECTION # define DEF_ICON_COLLECTION DEF_ICON #endif #ifndef DEF_ICON_OBJECT # define DEF_ICON_OBJECT DEF_ICON #endif #ifndef DEF_ICON_OBJECT_DATA # define DEF_ICON_OBJECT_DATA DEF_ICON #endif #ifndef DEF_ICON_MODIFIER # define DEF_ICON_MODIFIER DEF_ICON #endif #ifndef DEF_ICON_SHADING # define DEF_ICON_SHADING DEF_ICON #endif #ifndef DEF_ICON_COLOR # define DEF_ICON_COLOR DEF_ICON #endif /* ICON_ prefix added */ /* ------------------------- Row 1 ---------------------------*/ DEF_ICON_COLOR(NONE) /* never change! */ DEF_ICON_COLOR(QUESTION) DEF_ICON_COLOR(ERROR) DEF_ICON_COLOR(CANCEL) DEF_ICON_COLOR(TRIA_RIGHT) DEF_ICON_COLOR(TRIA_DOWN) DEF_ICON_COLOR(TRIA_LEFT) DEF_ICON_COLOR(TRIA_UP) DEF_ICON_COLOR(ARROW_LEFTRIGHT) DEF_ICON_COLOR(PLUS) DEF_ICON_COLOR(DISCLOSURE_TRI_RIGHT) DEF_ICON_COLOR(DISCLOSURE_TRI_DOWN) DEF_ICON_COLOR(RADIOBUT_OFF) DEF_ICON_COLOR(RADIOBUT_ON) DEF_ICON_COLOR(MENU_PANEL) DEF_ICON_COLOR(BLENDER) DEF_ICON_COLOR(GRIP) DEF_ICON_COLOR(DOT) DEF_ICON_COLOR(COLLAPSEMENU) DEF_ICON_COLOR(X) DEF_ICON_COLOR(TEMPLATE) DEF_ICON_COLOR(LASTOPERATOR) DEF_ICON_COLOR(ALTERNATED) DEF_ICON_COLOR(UI) DEF_ICON_COLOR(NODE) DEF_ICON_COLOR(NODE_SEL) DEF_ICON_COLOR(BLEND_TEX) DEF_ICON_COLOR(CLOUD_TEX) DEF_ICON_COLOR(DISTORTED_NOISE_TEX) DEF_ICON_COLOR(ASSIGN) DEF_ICON_COLOR(CONNECTED) DEF_ICON_COLOR(PREFIX) DEF_ICON_COLOR(SUFFIX) DEF_ICON_COLOR(FLIP) DEF_ICON_COLOR(STRING) DEF_ICON_COLOR(SET_ROLL) DEF_ICON_COLOR(CLEAR_ROLL) DEF_ICON_COLOR(ROLL_X_NEG) DEF_ICON_COLOR(ROLL_X_POS) DEF_ICON_COLOR(ROLL_X_TANG_NEG) DEF_ICON_COLOR(MARKER_TO_MESH) DEF_ICON_COLOR(ORIGIN) DEF_ICON_COLOR(FLOOR) DEF_ICON_COLOR(WALL) DEF_ICON_COLOR(SETUP) DEF_ICON_COLOR(BACKGROUND) DEF_ICON_COLOR(SELECT_ROOT) DEF_ICON_COLOR(SELECT_TIP) DEF_ICON_COLOR(IMAGE_ASPECT) DEF_ICON_COLOR(BRUSHSIZE) /* ------------------------- Row 2 --------------------------*/ DEF_ICON_COLOR(FULLSCREEN) DEF_ICON_COLOR(SPLITSCREEN) DEF_ICON_COLOR(RIGHTARROW_THIN) DEF_ICON_COLOR(BORDERMOVE) DEF_ICON_COLOR(VIEWZOOM) DEF_ICON_COLOR(ZOOMIN)/* bfa - new iconsheet*/ DEF_ICON_COLOR(ZOOMOUT)/* bfa - new iconsheet*/ DEF_ICON_COLOR(PANEL_CLOSE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(COPY_ID) DEF_ICON_COLOR(EYEDROPPER) DEF_ICON_COLOR(LINK_AREA) DEF_ICON_COLOR(AUTO) DEF_ICON_COLOR(CHECKBOX_DEHLT) DEF_ICON_COLOR(CHECKBOX_HLT) DEF_ICON_COLOR(UNLOCKED) DEF_ICON_COLOR(LOCKED) DEF_ICON_COLOR(UNPINNED) DEF_ICON_COLOR(PINNED) DEF_ICON_COLOR(SCREEN_BACK) DEF_ICON_COLOR(RIGHTARROW) DEF_ICON_COLOR(DOWNARROW_HLT) DEF_ICON_COLOR(SPOT_BLEND) DEF_ICON_COLOR(LENS_SCALE) DEF_ICON_COLOR(MAKE_INTERNAL) DEF_ICON_COLOR(NORMAL_SETSTRENGTH) DEF_ICON_COLOR(PLUGIN) DEF_ICON_COLOR(MAGIC_TEX) DEF_ICON_COLOR(MARBLE_TEX) DEF_ICON_COLOR(MUSGRAVE_TEX) DEF_ICON_COLOR(NOISE_TEX) DEF_ICON_COLOR(ROLL_X_TANG_POS) DEF_ICON_COLOR(ROLL_Y_NEG) DEF_ICON_COLOR(ROLL_Y_POS) DEF_ICON_COLOR(ROLL_Z_NEG) DEF_ICON_COLOR(ROLL_Z_POS) DEF_ICON_COLOR(ROLL_Z_TANG_NEG) DEF_ICON_COLOR(ROLL_Z_TANG_POS) DEF_ICON_COLOR(CLEAR_CONSTRAINT) DEF_ICON_COLOR(ADD_IK) DEF_ICON_COLOR(CLEAR_IK) DEF_ICON_COLOR(FLOODFILL) DEF_ICON_COLOR(OPTIMIZE) DEF_ICON_COLOR(PROPAGATE) DEF_ICON_COLOR(BRUSHSTRENGTH) DEF_ICON_COLOR(INTERPOLATE) DEF_ICON_COLOR(REPROJECT) DEF_ICON_COLOR(BRUSHANGLE) DEF_ICON_COLOR(VERTCOLFROMWEIGHT) DEF_ICON_COLOR(HUECORRECT) DEF_ICON_COLOR(PARTICLEBRUSH_NONE) /* ------------------------- Row 3 --------------------------*/ DEF_ICON_COLOR(HELP) DEF_ICON_COLOR(GHOST_ENABLED) DEF_ICON_COLOR(COLOR) /* see COLOR_RED/GREEN/BLUE */ DEF_ICON_COLOR(LINKED) DEF_ICON_COLOR(UNLINKED) DEF_ICON_COLOR(HAND) DEF_ICON_COLOR(ZOOM_ALL) DEF_ICON_COLOR(ZOOM_SELECTED) DEF_ICON_COLOR(ZOOM_PREVIOUS) DEF_ICON_COLOR(ZOOM_IN) DEF_ICON_COLOR(ZOOM_OUT) DEF_ICON_COLOR(RENDER_REGION) DEF_ICON_COLOR(BORDER_RECT) DEF_ICON_COLOR(BORDER_LASSO) DEF_ICON_COLOR(FREEZE) DEF_ICON_COLOR(STYLUS_PRESSURE) DEF_ICON_COLOR(GHOST_DISABLED) DEF_ICON_COLOR(NEW) DEF_ICON_COLOR(FILE_TICK) DEF_ICON_COLOR(QUIT) DEF_ICON_COLOR(URL) DEF_ICON_COLOR(RECOVER_LAST) DEF_ICON_COLOR(DUPLICATE) DEF_ICON_COLOR(FULLSCREEN_ENTER) DEF_ICON_COLOR(FULLSCREEN_EXIT) DEF_ICON_COLOR(BLANK1) // Not actually blank - this is used all over the place DEF_ICON_COLOR(LOAD_GITF) DEF_ICON_COLOR(SAVE_GITF) DEF_ICON_COLOR(STUCCI_TEX) DEF_ICON_COLOR(VORONI_TEX) DEF_ICON_COLOR(CLEAR) DEF_ICON_COLOR(FLIP_X) DEF_ICON_COLOR(RESET) DEF_ICON_COLOR(FLIP_Y) DEF_ICON_COLOR(FLIP_Z) DEF_ICON_COLOR(ZOOM_SET) DEF_ICON_COLOR(VIEW_FIT) DEF_ICON_COLOR(GP_SELECT_BETWEEN_STROKES)/* bfa - new iconsheet*/ DEF_ICON_COLOR(INVERSESQUARECURVE) /* bfa - new iconsheet*/ DEF_ICON_COLOR(PROP_PROJECTED) /* bfa - new iconsheet*/ DEF_ICON_COLOR(PARTICLEBRUSH_ADD) DEF_ICON_COLOR(PARTICLEBRUSH_COMB) DEF_ICON_COLOR(PARTICLEBRUSH_PUFF) DEF_ICON_COLOR(PARTICLEBRUSH_SMOOTH) DEF_ICON_COLOR(PARTICLEBRUSH_WEIGHT) DEF_ICON_COLOR(PARTICLEBRUSH_LENGTH) DEF_ICON_COLOR(MOD_MESH_CACHE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(ADD)/* bfa - new iconsheet*/ DEF_ICON_COLOR(FILE_3D) DEF_ICON_COLOR(ALIGN_CENTER) /* bfa - new iconsheet*/ /* ------------------------- Row 4 --------------------------*/ DEF_ICON_COLOR(LAMP)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MATERIAL)/* bfa - new iconsheet*/ DEF_ICON_COLOR(TEXTURE) DEF_ICON_COLOR(NORMAL_MULTIPLY) DEF_ICON_COLOR(WORLD) DEF_ICON_COLOR(SCENE) DEF_ICON_COLOR(EDIT) DEF_ICON_COLOR(GAME) DEF_ICON_COLOR(RADIO) DEF_ICON_COLOR(SCRIPT) DEF_ICON_COLOR(PARTICLES) DEF_ICON_COLOR(PHYSICS) DEF_ICON_COLOR(SPEAKER) DEF_ICON_COLOR(TEXTURE_SHADED) DEF_ICON_COLOR(VIEW_FRONT) DEF_ICON_COLOR(VIEW_BACK) DEF_ICON_COLOR(VIEW_LEFT) DEF_ICON_COLOR(VIEW_RIGHT) DEF_ICON_COLOR(VIEW_TOP) DEF_ICON_COLOR(VIEW_BOTTOM) DEF_ICON_COLOR(VIEW_RESET) DEF_ICON_COLOR(VIEW_SWITCHTOCAM) DEF_ICON_COLOR(VIEW_SWITCHACTIVECAM) DEF_ICON_COLOR(DELETE) DEF_ICON_COLOR(PERSP_ORTHO) DEF_ICON_COLOR(WIREFRAME) DEF_ICON_COLOR(WOOD_TEX) DEF_ICON_COLOR(RENDERBORDER_CLEAR) DEF_ICON_COLOR(RENDERBORDER) DEF_ICON_COLOR(CLIPPINGBORDER) DEF_ICON_COLOR(EDIT_EXTERNAL) DEF_ICON_COLOR(SAVE_ALL) DEF_ICON_COLOR(STITCH) DEF_ICON_COLOR(MARKER_BIND) DEF_ICON_COLOR(SPLIT_HORIZONTAL) DEF_ICON_COLOR(SPLIT_VERTICAL) DEF_ICON_COLOR(VIEW_FRAME) DEF_ICON_COLOR(AFTER_CURRENT_FRAME) DEF_ICON_COLOR(BEFORE_CURRENT_FRAME) DEF_ICON_COLOR(BETWEEN_MARKERS) DEF_ICON_COLOR(ALIGN_FLUSH)/* bfa - new iconsheet*/ DEF_ICON_COLOR(ALIGN_JUSTIFY)/* bfa - new iconsheet*/ DEF_ICON_COLOR(ALIGN_LEFT)/* bfa - new iconsheet*/ DEF_ICON_COLOR(ALIGN_MIDDLE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(ALIGN_RIGHT)/* bfa - new iconsheet*/ DEF_ICON_COLOR(ALIGN_BOTTOM)/* bfa - new iconsheet*/ DEF_ICON_COLOR(ALIGN_TOP)/* bfa - new iconsheet*/ DEF_ICON_COLOR(DECORATE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(DECORATE_ANIMATE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(DECORATE_DRIVER)/* bfa - new iconsheet*/ /* ------------------------- Row 5 --------------------------*/ DEF_ICON_COLOR(VIEW3D) DEF_ICON_COLOR(IPO) // Graph Editor DEF_ICON_COLOR(OOPS) // Outliner DEF_ICON_COLOR(BUTS) // Properties DEF_ICON_COLOR(DISSOLVE_BETWEEN) DEF_ICON_COLOR(DISSOLVE_UNSELECTED) DEF_ICON_COLOR(INFO) // Info Editor DEF_ICON_COLOR(SEQUENCE) // Sequencer DEF_ICON_COLOR(TEXT) // Text DEF_ICON_COLOR(IMASEL) // Image Selector? Not an editor! DEF_ICON_COLOR(SOUND) // Sound? Deprecated? DEF_ICON_COLOR(ACTION) // Dope Sheet DEF_ICON_COLOR(NLA) // NLA Editor DEF_ICON_COLOR(SCRIPTWIN) DEF_ICON_COLOR(TIME) DEF_ICON_COLOR(NODETREE) DEF_ICON_COLOR(RENAME) DEF_ICON_COLOR(CONSOLE) DEF_ICON_COLOR(PREFERENCES) DEF_ICON_COLOR(CLIP) DEF_ICON_COLOR(ASSET_MANAGER) DEF_ICON_COLOR(TOOLBAR) // The toolbar editor DEF_ICON_COLOR(CIRCLE_SELECT) DEF_ICON_COLOR(INVERSE) DEF_ICON_COLOR(SELECT_ALL) DEF_ICON_COLOR(SELECT_NONE) DEF_ICON_COLOR(APPTEMPLATE) DEF_ICON_COLOR(MAXIMIZE_AREA) DEF_ICON_COLOR(NEW_WINDOW) DEF_ICON_COLOR(QUADVIEW) DEF_ICON_COLOR(COLUMN_CURRENT_FRAME) DEF_ICON_COLOR(COLUMNS_KEYS) DEF_ICON_COLOR(COLUMNS_MARKERS) DEF_ICON_COLOR(EXPANDMENU) DEF_ICON_COLOR(BAKE_CURVE) DEF_ICON_COLOR(BAKE_SOUND) DEF_ICON_COLOR(CLEAN_CHANNELS) DEF_ICON_COLOR(CLEAN_KEYS) DEF_ICON_COLOR(DISCONTINUE_EULER) DEF_ICON_COLOR(JUMP_TO_KEYFRAMES) DEF_ICON_COLOR(DECORATE_KEYFRAME)/* bfa - new iconsheet*/ DEF_ICON_COLOR(ORIENTATION_CURSOR)/* bfa - new iconsheet*/ DEF_ICON_COLOR(DECORATE_OVERRIDE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(DECORATE_UNLOCKED)/* bfa - new iconsheet*/ DEF_ICON_COLOR(DECORATE_LOCKED)/* bfa - new iconsheet*/ DEF_ICON_COLOR(FACE_MAPS)/* bfa - new iconsheet*/ DEF_ICON_BLANK(330) DEF_ICON_COLOR(FILE_NEW)/* bfa - new iconsheet*/ DEF_ICON_COLOR(FILEBROWSER) /* bfa - new iconsheet*/ DEF_ICON_COLOR(SMOOTH_LAPLACIAN) /* ------------------------- Row 6 --------------------------*/ DEF_ICON_COLOR(OBJECT_DATAMODE) DEF_ICON_COLOR(EDITMODE_HLT) DEF_ICON_COLOR(FACESEL_HLT) DEF_ICON_COLOR(VPAINT_HLT) DEF_ICON_COLOR(TPAINT_HLT) DEF_ICON_COLOR(WPAINT_HLT) DEF_ICON_COLOR(SCULPTMODE_HLT) /* bfa - new iconsheet*/ DEF_ICON_COLOR(POSE_HLT) DEF_ICON_COLOR(PARTICLEMODE) DEF_ICON_COLOR(KNIFE) DEF_ICON_COLOR(SELECTLESS) DEF_ICON_COLOR(SELECTMORE) DEF_ICON_COLOR(BEND) DEF_ICON_COLOR(SHEAR) DEF_ICON_COLOR(TOSPHERE) DEF_ICON_COLOR(JOINCOPY) DEF_ICON_COLOR(SPLITEDGE) DEF_ICON_COLOR(VERTEXCONNECTPATH) DEF_ICON_COLOR(VERTEXCONNECT) DEF_ICON_COLOR(MARKSHARPEDGES) DEF_ICON_COLOR(BUTS_ACTIVE) // Properties DEF_ICON_COLOR(OOPS_ACTIVE) // Outliner DEF_ICON_COLOR(NLA_ACTIVE) DEF_ICON_COLOR(DOPESHEET_ACTIVE) DEF_ICON_COLOR(GRAPH_ACTIVE) DEF_ICON_COLOR(OFFSET_EDGE_SLIDE) DEF_ICON_COLOR(VIEWALL) DEF_ICON_COLOR(VIEWALL_RESETCURSOR) DEF_ICON_COLOR(VIEW_GLOBAL_LOCAL) DEF_ICON_COLOR(VIEW_SELECTED) DEF_ICON_COLOR(SAMPLE_KEYFRAMES) DEF_ICON_COLOR(SMOOTH_KEYFRAMES) DEF_ICON_COLOR(FLATTEN_HANDLER) DEF_ICON_COLOR(SNAP_CURRENTFRAME) DEF_ICON_COLOR(SNAP_CURSORVALUE) DEF_ICON_COLOR(SNAP_NEARESTFRAME) DEF_ICON_COLOR(SNAP_NEARESTMARKER) DEF_ICON_COLOR(SNAP_NEARESTSECOND) DEF_ICON_COLOR(MIRROR_CURSORVALUE) DEF_ICON_COLOR(MIRROR_MARKER) DEF_ICON_COLOR(GRAPH)/* bfa - new iconsheet*/ DEF_ICON_COLOR(LOOP_CUT_AND_SLIDE) DEF_ICON_COLOR(HIDE_ON)/* bfa - new iconsheet*/ DEF_ICON_COLOR(HIDE_OFF)/* bfa - new iconsheet*/ DEF_ICON_COLOR(IMAGE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(KEYFRAME_HLT)/* bfa - new iconsheet*/ DEF_ICON_COLOR(KEYFRAME)/* bfa - new iconsheet*/ DEF_ICON_COLOR(LIBRARY_DATA_OVERRIDE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(LIGHT)/* bfa - new iconsheet*/ DEF_ICON_COLOR(LIGHT_AREA)/* bfa - new iconsheet*/ /* ------------------------- Row 7 --------------------------*/ DEF_ICON_COLOR(SCENE_DATA) DEF_ICON_COLOR(RENDERLAYERS) DEF_ICON_COLOR(FILE_BLANK) DEF_ICON_COLOR(OBJECT_DATA) DEF_ICON_COLOR(MESH_DATA) DEF_ICON_COLOR(CURVE_DATA) DEF_ICON_COLOR(META_DATA) DEF_ICON_COLOR(LATTICE_DATA) DEF_ICON_COLOR(APPLY_ROTSCALE) DEF_ICON_COLOR(MATERIAL_DATA)/* bfa - new iconsheet*/ DEF_ICON_COLOR(OUTLINER_DATA_CAMERA) /*bfa - don't remove this version, it is required by an addon*/ DEF_ICON_COLOR(ANIM_DATA) DEF_ICON_COLOR(CAMERA_DATA) DEF_ICON_COLOR(PARTICLE_DATA) DEF_ICON_COLOR(LIBRARY_DATA_DIRECT) DEF_ICON_COLOR(GROUP) DEF_ICON_COLOR(ARMATURE_DATA) DEF_ICON_COLOR(POSE_DATA) DEF_ICON_COLOR(BONE_DATA) DEF_ICON_COLOR(CONSTRAINT) DEF_ICON_COLOR(SHAPEKEY_DATA) DEF_ICON_COLOR(CONSTRAINT_BONE) DEF_ICON_COLOR(CAMERA_STEREO) DEF_ICON_COLOR(PACKAGE) DEF_ICON_COLOR(UGLYPACKAGE) DEF_ICON_COLOR(SOLIDIFY) DEF_ICON_COLOR(VIEWCAMERACENTER) DEF_ICON_COLOR(VIEW_ACTIVE_BACK) DEF_ICON_COLOR(VIEW_ACTIVE_BOTTOM) DEF_ICON_COLOR(VIEW_ACTIVE_FRONT) DEF_ICON_COLOR(MIRROR_TIME) DEF_ICON_COLOR(HANDLE_AUTO_CLAMPED) DEF_ICON_COLOR(MOVE_DOWN) DEF_ICON_COLOR(MOVE_TO_BOTTOM) DEF_ICON_COLOR(MOVE_TO_TOP) DEF_ICON_COLOR(MOVE_UP) DEF_ICON_COLOR(EXTRAPOLATION_CONSTANT) DEF_ICON_COLOR(EXTRAPOLATION_CYCLIC) DEF_ICON_COLOR(EXTRAPOLATION_CYCLIC_CLEAR) DEF_ICON_COLOR(EXTRAPOLATION_LINEAR) DEF_ICON_COLOR(LIGHT_DATA)/* bfa - new iconsheet*/ DEF_ICON_COLOR(LIGHT_HEMI)/* bfa - new iconsheet*/ DEF_ICON_COLOR(LIGHT_POINT)/* bfa - new iconsheet*/ DEF_ICON_COLOR(LIGHT_SPOT)/* bfa - new iconsheet*/ DEF_ICON_COLOR(LIGHT_SUN)/* bfa - new iconsheet*/ DEF_ICON_COLOR(LIGHTPROBE_CUBEMAP)/* bfa - new iconsheet*/ DEF_ICON_COLOR(LIGHTPROBE_GRID)/* bfa - new iconsheet*/ DEF_ICON_COLOR(LIGHTPROBE_PLANAR)/* bfa - new iconsheet*/ DEF_ICON_COLOR(VIEW_REMOVE_LOCAL) DEF_ICON_COLOR(SHAPE) /* ------------------------- Row 8 --------------------------*/ DEF_ICON_COLOR(BRUSH_DATA) DEF_ICON_COLOR(IMAGE_DATA) DEF_ICON_COLOR(FILE) DEF_ICON_COLOR(FCURVE) DEF_ICON_COLOR(FONT_DATA) DEF_ICON_COLOR(RENDER_RESULT) DEF_ICON_COLOR(SURFACE_DATA) DEF_ICON_COLOR(EMPTY_DATA) DEF_ICON_COLOR(SETTINGS) DEF_ICON_COLOR(RENDER_ANIMATION) DEF_ICON_COLOR(RENDER_STILL) DEF_ICON_COLOR(LIBRARY_DATA_BROKEN) DEF_ICON_COLOR(BOIDS) DEF_ICON_COLOR(GIZMO) DEF_ICON_COLOR(LIBRARY_DATA_INDIRECT) DEF_ICON_COLOR(GREASEPENCIL)/* bfa - new iconsheet*/ DEF_ICON_COLOR(LINE_DATA) DEF_ICON_COLOR(HIDE_RENDERVIEW) DEF_ICON_COLOR(GROUP_BONE) DEF_ICON_COLOR(GROUP_VERTEX) DEF_ICON_COLOR(GROUP_VCOL) DEF_ICON_COLOR(GROUP_UVS) DEF_ICON_COLOR(RENDER_STILL_VIEW) DEF_ICON_COLOR(RENDER_ANI_VIEW) DEF_ICON_COLOR(RNA) DEF_ICON_COLOR(OUTLINER_DATA_LIGHTPROBE) DEF_ICON_COLOR(VIEW_ACTIVE_LEFT) DEF_ICON_COLOR(VIEW_ACTIVE_RIGHT) DEF_ICON_COLOR(VIEW_ACTIVE_TOP) DEF_ICON_COLOR(CENTERTOMOUSE) DEF_ICON_COLOR(BUILTIN_MODIFIER) DEF_ICON_COLOR(CYCLES_MODIFIER) DEF_ICON_COLOR(ENVELOPE_MODIFIER) DEF_ICON_COLOR(GENERATOR_MODIFIER) DEF_ICON_COLOR(LIMIT_MODIFIER) DEF_ICON_COLOR(NOISE_MODIFIER) DEF_ICON_COLOR(STEPPED_MODIFIER) DEF_ICON_COLOR(SWAP) DEF_ICON_COLOR(SYNC) DEF_ICON_COLOR(TRANSITION) DEF_ICON_COLOR(MATCLOTH)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MATFLUID)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MATSHADERBALL)/* bfa - new iconsheet*/ DEF_ICON_COLOR(NODE_COMPOSITING)/* bfa - new iconsheet*/ DEF_ICON_COLOR(NODE_CORNER)/* bfa - new iconsheet*/ DEF_ICON_COLOR(NODE_MATERIAL)/* bfa - new iconsheet*/ DEF_ICON_COLOR(NODE_SIDE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(NODE_TOP)/* bfa - new iconsheet*/ DEF_ICON_COLOR(NORMALS_FACE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(NORMALS_VERTEX)/* bfa - new iconsheet*/ /* ------------------------- Row 9 --------------------------*/ DEF_ICON_COLOR(CLEARSHARPEDGES) DEF_ICON_COLOR(CONVEXHULL) DEF_ICON_COLOR(BLENDFROMSHAPE) DEF_ICON_COLOR(SHAPEPROPAGATE) DEF_ICON_COLOR(BRIDGE_EDGELOOPS) DEF_ICON_COLOR(CLEAR_FS_EDGE) DEF_ICON_COLOR(MARK_FS_EDGE) DEF_ICON_COLOR(MAKEDUPLIFACE) DEF_ICON_COLOR(ROTATECW) DEF_ICON_COLOR(SPLIT) DEF_ICON_COLOR(SUBDIVEDGELOOP) DEF_ICON_COLOR(UNSUBDIVIDE) DEF_ICON_COLOR(SUBDIV_EDGERING) DEF_ICON_COLOR(REVERSE_COLORS) DEF_ICON_COLOR(ROTATE_COLORS) DEF_ICON_COLOR(REVERSE_UVS) DEF_ICON_COLOR(ROTATE_UVS) DEF_ICON_COLOR(ALIGNAUTO) DEF_ICON_COLOR(ALIGNHORIZONTAL) DEF_ICON_COLOR(ALIGNVERTICAL) DEF_ICON_COLOR(STRAIGHTEN) DEF_ICON_COLOR(STRAIGHTEN_X) DEF_ICON_COLOR(STRAIGHTEN_Y) DEF_ICON_COLOR(UNWRAP_ABF) DEF_ICON_COLOR(UNWRAP_LSCM) DEF_ICON_COLOR(WELD) DEF_ICON_COLOR(DOLLY) DEF_ICON_COLOR(FLY_NAVIGATION) DEF_ICON_COLOR(VIEW_NAVIGATION) DEF_ICON_COLOR(WALK_NAVIGATION) DEF_ICON_COLOR(ADD_STRIP) DEF_ICON_COLOR(ADD_TRACK) DEF_ICON_COLOR(ADD_TRACK_ABOVE) DEF_ICON_COLOR(ADD_METASTRIP) DEF_ICON_COLOR(REMOVE_METASTRIP) DEF_ICON_COLOR(SEQ_MULTIPLY) DEF_ICON_COLOR(ADD_SELECTED) DEF_ICON_COLOR(CENTER) DEF_ICON_COLOR(HIERARCHY) DEF_ICON_COLOR(HIERARCHY_DOWN) DEF_ICON_COLOR(NORMALS_VERTEX_FACE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(OBJECT_ORIGIN)/* bfa - new iconsheet*/ DEF_ICON_COLOR(ONIONSKIN_OFF)/* bfa - new iconsheet*/ DEF_ICON_COLOR(ONIONSKIN_ON)/* bfa - new iconsheet*/ DEF_ICON_COLOR(ORIENTATION_GIMBAL)/* bfa - new iconsheet*/ DEF_ICON_COLOR(ORIENTATION_LOCAL)/* bfa - new iconsheet*/ DEF_ICON_COLOR(ORIENTATION_NORMAL)/* bfa - new iconsheet*/ DEF_ICON_COLOR(ORIENTATION_VIEW)/* bfa - new iconsheet*/ DEF_ICON_COLOR(ORPHAN_DATA)/* bfa - new iconsheet*/ DEF_ICON_COLOR(OUTLINER)/* bfa - new iconsheet*/ /* ------------------------- Row 10 --------------------------*/ DEF_ICON_COLOR(OUTLINER_OB_EMPTY) DEF_ICON_COLOR(OUTLINER_OB_MESH) DEF_ICON_COLOR(OUTLINER_OB_CURVE) DEF_ICON_COLOR(OUTLINER_OB_LATTICE) DEF_ICON_COLOR(OUTLINER_OB_META) DEF_ICON_COLOR(OUTLINER_OB_LAMP) DEF_ICON_COLOR(OUTLINER_OB_CAMERA) DEF_ICON_COLOR(OUTLINER_OB_ARMATURE) DEF_ICON_COLOR(OUTLINER_OB_FONT) DEF_ICON_COLOR(OUTLINER_OB_SURFACE) DEF_ICON_COLOR(OUTLINER_OB_SPEAKER) DEF_ICON_COLOR(EMPTY_ARROWS) DEF_ICON_COLOR(EMPTY_CIRCLE) DEF_ICON_COLOR(EMPTY_CONE) DEF_ICON_COLOR(EMPTY_CUBE) DEF_ICON_COLOR(EMPTY_IMAGE) DEF_ICON_COLOR(EMPTY_SINGLEARROW) DEF_ICON_COLOR(EMPTY_SPHERE) DEF_ICON_COLOR(RESTRICT_COLOR_OFF) DEF_ICON_COLOR(RESTRICT_COLOR_ON) DEF_ICON_COLOR(RESTRICT_VIEW_ON) DEF_ICON_COLOR(RESTRICT_VIEW_OFF) DEF_ICON_COLOR(RESTRICT_SELECT_ON) DEF_ICON_COLOR(RESTRICT_SELECT_OFF) DEF_ICON_COLOR(RESTRICT_RENDER_ON) DEF_ICON_COLOR(RESTRICT_RENDER_OFF) DEF_ICON_COLOR(OUTLINER_OB_FORCE_FIELD) DEF_ICON_COLOR(OUTLINER_OB_GROUP_INSTANCE) DEF_ICON_COLOR(ZOOM_CAMERA) DEF_ICON_COLOR(ZOOM_BORDER) DEF_ICON_COLOR(HIERARCHY_UP) DEF_ICON_COLOR(CUT_LINKS) DEF_ICON_COLOR(DETACH_LINKS) DEF_ICON_COLOR(TOGGLE_NODE_MUTE) DEF_ICON_COLOR(TOGGLE_NODE_OPTIONS) DEF_ICON_COLOR(TOGGLE_NODE_PREVIEW) DEF_ICON_BLANK(602) DEF_ICON_BLANK(603) DEF_ICON_COLOR(CARET_LINE_BEGIN) DEF_ICON_COLOR(CARET_LINE_END) DEF_ICON_COLOR(OUTLINER_DATA_GREASEPENCIL)/* bfa - new iconsheet*/ DEF_ICON_COLOR(OUTLINER_DATA_LIGHT)/* bfa - new iconsheet*/ DEF_ICON_COLOR(OUTLINER_OB_GREASEPENCIL)/* bfa - new iconsheet*/ DEF_ICON_COLOR(OUTLINER_OB_IMAGE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(OUTLINER_OB_LIGHT)/* bfa - new iconsheet*/ DEF_ICON_COLOR(OUTLINER_OB_LIGHTPROBE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(OVERLAY)/* bfa - new iconsheet*/ DEF_ICON_COLOR(PIVOT_ACTIVE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(PIVOT_BOUNDBOX)/* bfa - new iconsheet*/ DEF_ICON_COLOR(PIVOT_CURSOR)/* bfa - new iconsheet*/ /* ------------------------- Row 11 --------------------------*/ DEF_ICON_COLOR(OUTLINER_DATA_EMPTY) DEF_ICON_COLOR(OUTLINER_DATA_MESH) DEF_ICON_COLOR(OUTLINER_DATA_CURVE) DEF_ICON_COLOR(OUTLINER_DATA_LATTICE) DEF_ICON_COLOR(OUTLINER_DATA_META) DEF_ICON_COLOR(OUTLINER_DATA_LAMP)/* bfa - new iconsheet*/ DEF_ICON_BLANK(628) DEF_ICON_COLOR(OUTLINER_DATA_ARMATURE) DEF_ICON_COLOR(OUTLINER_DATA_FONT) DEF_ICON_COLOR(OUTLINER_DATA_SURFACE) DEF_ICON_COLOR(OUTLINER_DATA_SPEAKER) DEF_ICON_COLOR(OUTLINER_DATA_POSE) DEF_ICON_COLOR(APPLYALL) DEF_ICON_COLOR(APPLYMOVE) DEF_ICON_COLOR(APPLYROTATE) DEF_ICON_COLOR(APPLYSCALE) DEF_ICON_COLOR(CLEARMOVE) DEF_ICON_COLOR(CLEARORIGIN) DEF_ICON_COLOR(CLEARROTATE) DEF_ICON_COLOR(CLEARSCALE) DEF_ICON_COLOR(MAKEDUPLIREAL) DEF_ICON_COLOR(VISUALTRANSFORM) DEF_ICON_COLOR(POKEFACES) DEF_ICON_COLOR(SPLITBYEDGES) DEF_ICON_COLOR(TRIANGULATE) DEF_ICON_COLOR(TRISTOQUADS) DEF_ICON_COLOR(PAN_DOWN) DEF_ICON_COLOR(PAN_LEFT) DEF_ICON_COLOR(PAN_RIGHT) DEF_ICON_COLOR(PAN_UP) DEF_ICON_COLOR(CARET_NEXT_CHAR) DEF_ICON_COLOR(CARET_NEXT_WORD) DEF_ICON_COLOR(CARET_PREV_WORD) DEF_ICON_COLOR(CARET_PREV_CHAR) DEF_ICON_COLOR(HISTORY_CYCLE_BACK) DEF_ICON_COLOR(HISTORY_CYCLE_FORWARD) DEF_ICON_COLOR(INDENT) DEF_ICON_COLOR(UNINDENT) DEF_ICON_COLOR(AUTOCOMPLETE) DEF_ICON_COLOR(GOTO) DEF_ICON_COLOR(PIVOT_INDIVIDUAL)/* bfa - new iconsheet*/ DEF_ICON_COLOR(PIVOT_MEDIAN)/* bfa - new iconsheet*/ DEF_ICON_COLOR(PRESET)/* bfa - new iconsheet*/ DEF_ICON_COLOR(PROPERTIES)/* bfa - new iconsheet*/ DEF_ICON_COLOR(REMOVE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(SCULPT_DYNTOPO)/* bfa - new iconsheet*/ DEF_ICON_COLOR(SHADERFX)/* bfa - new iconsheet*/ DEF_ICON_COLOR(SHADING_BBOX)/* bfa - new iconsheet*/ DEF_ICON_COLOR(SHADING_RENDERED)/* bfa - new iconsheet*/ DEF_ICON_COLOR(SHADING_SOLID)/* bfa - new iconsheet*/ /* ------------------------- Row 12 --------------------------*/ /* PRIMITIVES */ DEF_ICON_COLOR(MESH_PLANE) DEF_ICON_COLOR(MESH_CUBE) DEF_ICON_COLOR(MESH_CIRCLE) DEF_ICON_COLOR(MESH_UVSPHERE) DEF_ICON_COLOR(MESH_ICOSPHERE) DEF_ICON_COLOR(MESH_GRID) DEF_ICON_COLOR(MESH_MONKEY) DEF_ICON_COLOR(MESH_CYLINDER) DEF_ICON_COLOR(MESH_TORUS) DEF_ICON_COLOR(MESH_CONE) DEF_ICON_COLOR(MESH_CAPSULE) DEF_ICON_COLOR(INTERSECT) DEF_ICON_COLOR(LAMP_POINT) DEF_ICON_COLOR(LAMP_SUN) DEF_ICON_COLOR(LAMP_SPOT) DEF_ICON_BLANK(695) DEF_ICON_COLOR(LAMP_AREA) DEF_ICON_COLOR(MARKFSFACE) DEF_ICON_COLOR(CLEARFSFACE) DEF_ICON_COLOR(META_EMPTY) DEF_ICON_COLOR(META_PLANE) DEF_ICON_COLOR(META_CUBE) DEF_ICON_COLOR(META_BALL) DEF_ICON_COLOR(META_ELLIPSOID) DEF_ICON_COLOR(META_CAPSULE) DEF_ICON_COLOR(BOOLEAN_INTERSECT) DEF_ICON_COLOR(ORBIT_DOWN) DEF_ICON_COLOR(ORBIT_LEFT) DEF_ICON_COLOR(ORBIT_RIGHT) DEF_ICON_COLOR(ORBIT_UP) DEF_ICON_COLOR(SELECT_LINE) DEF_ICON_COLOR(COMMENT) DEF_ICON_COLOR(UNCOMMENT) DEF_ICON_COLOR(WHITESPACE_SPACES) DEF_ICON_COLOR(WHITESPACE_TABS) DEF_ICON_COLOR(DEBUG) DEF_ICON_COLOR(SEQ_MULTICAM) DEF_ICON_COLOR(MAKE_SCREENSHOT) DEF_ICON_COLOR(SEQ_ALPHA_OVER) DEF_ICON_COLOR(PREFETCH) DEF_ICON_COLOR(SHADING_TEXTURE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(SHADING_WIRE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(SORT_DESC)/* bfa - new iconsheet*/ DEF_ICON_COLOR(SORT_ASC)/* bfa - new iconsheet*/ DEF_ICON_COLOR(SYSTEM)/* bfa - new iconsheet*/ DEF_ICON_COLOR(COLLECTION_NEW)/* bfa - new iconsheet*/ DEF_ICON_COLOR(TOOL_SETTINGS)/* bfa - new iconsheet*/ DEF_ICON_COLOR(TRACKING)/* bfa - new iconsheet*/ DEF_ICON_COLOR(TRACKING_BACKWARDS)/* bfa - new iconsheet*/ DEF_ICON_COLOR(TRACKING_BACKWARDS_SINGLE)/* bfa - new iconsheet*/ /* ------------------------- Row 13 --------------------------*/ /* PRIMITIVES */ DEF_ICON_COLOR(SURFACE_NCURVE) DEF_ICON_COLOR(SURFACE_NCIRCLE) DEF_ICON_COLOR(SURFACE_NSURFACE) DEF_ICON_COLOR(SURFACE_NCYLINDER) DEF_ICON_COLOR(SURFACE_NSPHERE) DEF_ICON_COLOR(SURFACE_NTORUS) DEF_ICON_COLOR(BEAUTIFY) DEF_ICON_COLOR(FILL) DEF_ICON_COLOR(GRIDFILL) DEF_ICON_COLOR(CURVE_BEZCURVE) DEF_ICON_COLOR(CURVE_BEZCIRCLE) DEF_ICON_COLOR(CURVE_NCURVE) DEF_ICON_COLOR(CURVE_NCIRCLE) DEF_ICON_COLOR(CURVE_PATH) DEF_ICON_COLOR(AVERAGEISLANDSCALE) DEF_ICON_COLOR(COPYMIRRORED) DEF_ICON_COLOR(MINIMIZESTRETCH) DEF_ICON_COLOR(PACKISLAND) DEF_ICON_COLOR(SEAMSFROMISLAND) DEF_ICON_COLOR(COLOR_RED) DEF_ICON_COLOR(COLOR_GREEN) DEF_ICON_COLOR(COLOR_BLUE) DEF_ICON_COLOR(TRIA_RIGHT_BAR) DEF_ICON_COLOR(TRIA_DOWN_BAR) DEF_ICON_COLOR(TRIA_LEFT_BAR) DEF_ICON_COLOR(TRIA_UP_BAR) DEF_ICON_COLOR(ORBIT_OPPOSITE) DEF_ICON_COLOR(ROLL_LEFT) DEF_ICON_COLOR(ROLL_RIGHT) DEF_ICON_COLOR(LAYER) DEF_ICON_COLOR(NODE_ADD_SHADER) DEF_ICON_BLANK(772) DEF_ICON_COLOR(NODE_ALPHACONVERT) DEF_ICON_COLOR(NODE_AMBIENT_OCCLUSION) DEF_ICON_COLOR(NODE_ANISOTOPIC) DEF_ICON_COLOR(NODE_AT) DEF_ICON_COLOR(NODE_ATTRIBUTE) DEF_ICON_COLOR(NODE_BACKGROUNDSHADER) DEF_ICON_COLOR(NODE_BILATERAL_BLUR) DEF_ICON_COLOR(NODE_BLACKBODY) DEF_ICON_COLOR(TRACKING_CLEAR_BACKWARDS)/* bfa - new iconsheet*/ DEF_ICON_COLOR(TRACKING_CLEAR_FORWARDS)/* bfa - new iconsheet*/ DEF_ICON_COLOR(TRACKING_FORWARDS)/* bfa - new iconsheet*/ DEF_ICON_COLOR(TRACKING_FORWARDS_SINGLE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(TRACKING_REFINE_BACKWARDS)/* bfa - new iconsheet*/ DEF_ICON_COLOR(TRACKING_REFINE_FORWARDS)/* bfa - new iconsheet*/ DEF_ICON_COLOR(UNDERLINE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(USER)/* bfa - new iconsheet*/ DEF_ICON_COLOR(VIEW_CAMERA)/* bfa - new iconsheet*/ DEF_ICON_COLOR(VIEW_ORTHO)/* bfa - new iconsheet*/ /* ------------------------- Row 14 --------------------------*/ /* EMPTY */ DEF_ICON_COLOR(FORCE_FORCE) DEF_ICON_COLOR(FORCE_WIND) DEF_ICON_COLOR(FORCE_VORTEX) DEF_ICON_COLOR(FORCE_MAGNETIC) DEF_ICON_COLOR(FORCE_HARMONIC) DEF_ICON_COLOR(FORCE_CHARGE) DEF_ICON_COLOR(FORCE_LENNARDJONES) DEF_ICON_COLOR(FORCE_TEXTURE) DEF_ICON_COLOR(FORCE_CURVE) DEF_ICON_COLOR(FORCE_BOID) DEF_ICON_COLOR(FORCE_TURBULENCE) DEF_ICON_COLOR(FORCE_DRAG) DEF_ICON_COLOR(FORCE_SMOKEFLOW) DEF_ICON_COLOR(RECALC_NORMALS) DEF_ICON_COLOR(RECALC_NORMALS_INSIDE) DEF_ICON_COLOR(FLIP_NORMALS) DEF_ICON_COLOR(MARK_SEAM) DEF_ICON_COLOR(CLEAR_SEAM) DEF_ICON_BLANK(814) DEF_ICON_COLOR(PUSH_POSE) DEF_ICON_COLOR(RELAX_POSE) DEF_ICON_COLOR(BREAKDOWNER_POSE) DEF_ICON_COLOR(KEYFRAMES_CLEAR) DEF_ICON_COLOR(REMOVE_FROM_ALL_GROUPS) DEF_ICON_COLOR(REMOVE_SELECTED_FROM_ACTIVE_GROUP) DEF_ICON_COLOR(FILLBETWEEN) DEF_ICON_COLOR(PARENT) DEF_ICON_COLOR(CHILD) DEF_ICON_COLOR(CHILD_RECURSIVE) DEF_ICON_COLOR(SIBLINGS) DEF_ICON_BLANK(829) DEF_ICON_COLOR(NODE_BLUR) DEF_ICON_COLOR(NODE_BOKEH_BLUR) DEF_ICON_COLOR(NODE_BOKEH_IMAGE) DEF_ICON_COLOR(NODE_BOXMASK) DEF_ICON_COLOR(NODE_BRICK) DEF_ICON_COLOR(NODE_BRIGHT_CONTRAST) DEF_ICON_COLOR(NODE_BUMP) DEF_ICON_COLOR(NODE_CAMERADATA) DEF_ICON_COLOR(NODE_CHANNEL) DEF_ICON_COLOR(VIEW_PAN)/* bfa - new iconsheet*/ DEF_ICON_COLOR(VIEW_PERSPECTIVE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(VIEW_ZOOM)/* bfa - new iconsheet*/ DEF_ICON_COLOR(VIS_SEL_11)/* bfa - new iconsheet*/ DEF_ICON_COLOR(VIS_SEL_10)/* bfa - new iconsheet*/ DEF_ICON_COLOR(VIS_SEL_01)/* bfa - new iconsheet*/ DEF_ICON_COLOR(VIS_SEL_00)/* bfa - new iconsheet*/ DEF_ICON_COLOR(OUTLINER_DATA_GP_LAYER)/* bfa - new iconsheet*/ DEF_ICON_COLOR(WORKSPACE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(XRAY)/* bfa - new iconsheet*/ /* ------------------------- Row 15 --------------------------*/ DEF_ICON_COLOR(SNAPTOPIXEL_CENTER) DEF_ICON_COLOR(SNAPTOPIXEL_CORNER) DEF_ICON_COLOR(SNAPTOPIXEL_OFF) DEF_ICON_COLOR(NODE_INSERT_ON) DEF_ICON_COLOR(NODE_INSERT_OFF) DEF_ICON_COLOR(RIGID_ADD_ACTIVE) DEF_ICON_COLOR(RIGID_ADD_PASSIVE) DEF_ICON_COLOR(RIGID_REMOVE) DEF_ICON_COLOR(RIGID_CHANGE_SHAPE) DEF_ICON_COLOR(RIGID_CALCULATE_MASS) DEF_ICON_COLOR(RIGID_COPY_FROM_ACTIVE) DEF_ICON_COLOR(RIGID_APPLY_TRANS) DEF_ICON_COLOR(RIGID_BAKE_TO_KEYFRAME) DEF_ICON_COLOR(RIGID_CONSTRAINTS_CONNECT) DEF_ICON_COLOR(KEYFRAMES_INSERT) DEF_ICON_COLOR(KEYFRAMES_REMOVE) DEF_ICON_COLOR(MOTIONPATHS_CALCULATE) DEF_ICON_COLOR(MOTIONPATHS_CLEAR) DEF_ICON_COLOR(BAKE_ACTION) DEF_ICON_COLOR(TOGGLE_CYCLIC) DEF_ICON_COLOR(SWITCH_DIRECTION) DEF_ICON_COLOR(HANDLE_AUTO) DEF_ICON_COLOR(HANDLE_VECTOR) DEF_ICON_COLOR(HANDLE_ALIGN) DEF_ICON_COLOR(HANDLE_FREE) DEF_ICON_COLOR(RADIUS) DEF_ICON_COLOR(TYPE) DEF_ICON_COLOR(PASS) DEF_ICON_COLOR(SELECT_FACES_BY_SIDE) DEF_ICON_COLOR(CHECKER_DESELECT) DEF_ICON_COLOR(NODE_CHECKER) DEF_ICON_COLOR(NODE_CHROMA) DEF_ICON_COLOR(NODE_CLOUDS) DEF_ICON_BLANK(889) DEF_ICON_COLOR(NODE_COLORBALANCE) DEF_ICON_COLOR(NODE_COLORCORRECTION) DEF_ICON_COLOR(NODE_COLORRAMP) DEF_ICON_COLOR(NODE_COMBINEHSV) DEF_ICON_COLOR(NODE_COMBINERGB) DEF_ICON_COLOR(NODE_COMBINEXYZ) DEF_ICON_COLOR(CENTER_ONLY)/* bfa - new iconsheet*/ DEF_ICON_COLOR(HOLDOUT_OFF)/* bfa - new iconsheet*/ DEF_ICON_COLOR(HOLDOUT_ON)/* bfa - new iconsheet*/ DEF_ICON_COLOR(COMMUNITY)/* bfa - new iconsheet*/ DEF_ICON_COLOR(CONE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(CUBE)/* bfa - new iconsheet*/ DEF_ICON_BLANK(902) DEF_ICON_COLOR(DRIVER_DISTANCE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(DRIVER_ROTATIONAL_DIFFERENCE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(DRIVER_TRANSFORM)/* bfa - new iconsheet*/ /* ------------------------- Row 16 --------------------------*/ DEF_ICON_COLOR(ORIGIN_TO_VOLUME) DEF_ICON_COLOR(WEIGHT_TRANSFER_WEIGHTS) DEF_ICON_COLOR(JOIN) DEF_ICON_COLOR(GEOMETRY_TO_ORIGIN) DEF_ICON_COLOR(ORIGIN_TO_GEOMETRY) DEF_ICON_COLOR(ORIGIN_TO_CURSOR) DEF_ICON_COLOR(ORIGIN_TO_CENTEROFMASS) DEF_ICON_COLOR(SHADING_SMOOTH) DEF_ICON_COLOR(SHADING_FLAT) DEF_ICON_COLOR(TRANSFER_DATA) DEF_ICON_COLOR(TRANSFER_DATA_LAYOUT) DEF_ICON_COLOR(NEW_GROUP) DEF_ICON_COLOR(ADD_TO_ACTIVE) DEF_ICON_BLANK(923) DEF_ICON_COLOR(PARENT_SET) DEF_ICON_COLOR(PARENT_CLEAR) DEF_ICON_COLOR(LINK_DATA) DEF_ICON_COLOR(MAKE_SINGLE_USER) DEF_ICON_COLOR(MAKE_LOCAL) DEF_ICON_COLOR(MAKE_PROXY) DEF_ICON_COLOR(ERASE) DEF_ICON_COLOR(EXTRUDESIZE) DEF_ICON_COLOR(WIDTH_SIZE) DEF_ICON_BLANK(934) DEF_ICON_COLOR(RULER) DEF_ICON_COLOR(VERTEX_PARENT) DEF_ICON_COLOR(SELECT_NONMANIFOLD) DEF_ICON_COLOR(SELECT_BOUNDARY) DEF_ICON_COLOR(SELECT_EDGELOOP) DEF_ICON_COLOR(SELECT_EDGERING) DEF_ICON_COLOR(NODE_COMBINEYCBCRA) DEF_ICON_COLOR(NODE_COMBINEYUVA) DEF_ICON_COLOR(NODE_COMPOSITE_OUTPUT) DEF_ICON_COLOR(NODE_CORNERPIN) DEF_ICON_COLOR(NODE_CROP) DEF_ICON_COLOR(NODE_CURVE_TIME) DEF_ICON_COLOR(NODE_DEFOCUS) DEF_ICON_COLOR(NODE_DESPECKLE) DEF_ICON_BLANK(951) DEF_ICON_COLOR(NODE_DIFFUSESHADER) DEF_ICON_COLOR(EMPTY_AXIS)/* bfa - new iconsheet*/ DEF_ICON_COLOR(EMPTY_SINGLE_ARROW)/* bfa - new iconsheet*/ DEF_ICON_COLOR(EXPERIMENTAL)/* bfa - new iconsheet*/ DEF_ICON_COLOR(FAKE_USER_OFF)/* bfa - new iconsheet*/ DEF_ICON_COLOR(FAKE_USER_ON)/* bfa - new iconsheet*/ DEF_ICON_BLANK(958) DEF_ICON_COLOR(GP_MULTIFRAME_EDITING)/* bfa - new iconsheet*/ DEF_ICON_COLOR(GP_ONLY_SELECTED)/* bfa - new iconsheet*/ DEF_ICON_COLOR(GP_SELECT_POINTS)/* bfa - new iconsheet*/ DEF_ICON_COLOR(GP_SELECT_STROKES)/* bfa - new iconsheet*/ /* ------------------------- Row 17 --------------------------*/ DEF_ICON_COLOR(INSET_FACES) DEF_ICON_COLOR(MAKE_EDGEFACE) DEF_ICON_COLOR(SUBDIVIDE_EDGES) DEF_ICON_COLOR(NORMAL_ROTATE) DEF_ICON_COLOR(NORMAL_AVERAGE) DEF_ICON_COLOR(NORMAL_SMOOTH) DEF_ICON_COLOR(NORMAL_TARGET) DEF_ICON_COLOR(KNIFE_PROJECT) DEF_ICON_COLOR(BISECT) DEF_ICON_COLOR(DISSOLVE_VERTS) DEF_ICON_COLOR(DISSOLVE_EDGES) DEF_ICON_COLOR(DISSOLVE_FACES) DEF_ICON_COLOR(DISSOLVE_LIMITED) DEF_ICON_COLOR(DISSOLVE_SELECTION) DEF_ICON_COLOR(EDGE_COLLAPSE) DEF_ICON_COLOR(REMOVE_DOUBLES) DEF_ICON_COLOR(WEIGHT_NORMALIZE_ALL) DEF_ICON_COLOR(WEIGHT_NORMALIZE) DEF_ICON_COLOR(WEIGHT_MIRROR) DEF_ICON_COLOR(WEIGHT_INVERT) DEF_ICON_COLOR(WEIGHT_CLEAN) DEF_ICON_COLOR(WEIGHT_QUANTIZE) DEF_ICON_COLOR(WEIGHT_LEVELS) DEF_ICON_COLOR(WEIGHT_SMOOTH) DEF_ICON_COLOR(WEIGHT_LIMIT_TOTAL) DEF_ICON_COLOR(WEIGHT_FIX_DEFORMS) DEF_ICON_COLOR(SELECT_INTERIOR) DEF_ICON_COLOR(SELECT_LOOPINNER) DEF_ICON_COLOR(SELECT_LOOSE) DEF_ICON_COLOR(SELECT_SHARPEDGES) DEF_ICON_COLOR(NODE_DIRECITONALBLUR) DEF_ICON_BLANK(1001) DEF_ICON_COLOR(SEQ_STRIP_DUPLICATE) DEF_ICON_COLOR(SEQ_STRIP_META) DEF_ICON_COLOR(NODE_DOUBLEEDGEMASK) DEF_ICON_COLOR(NODE_EDITGROUP) DEF_ICON_COLOR(NODE_ELLIPSEMASK) DEF_ICON_COLOR(NODE_EMISSION) DEF_ICON_COLOR(NODE_ENVIRONMENT) DEF_ICON_COLOR(NODE_ERODE) DEF_ICON_COLOR(RIGID_BODY)/* bfa - new iconsheet*/ DEF_ICON_COLOR(IMAGE_BACKGROUND)/* bfa - new iconsheet*/ DEF_ICON_COLOR(RIGID_BODY_CONSTRAINT)/* bfa - new iconsheet*/ DEF_ICON_COLOR(IMAGE_REFERENCE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(INDIRECT_ONLY_OFF)/* bfa - new iconsheet*/ DEF_ICON_COLOR(INDIRECT_ONLY_ON)/* bfa - new iconsheet*/ DEF_ICON_BLANK(1016) DEF_ICON_COLOR(MOD_HUE_SATURATION)/* bfa - new iconsheet*/ DEF_ICON_BLANK(1018) DEF_ICON_COLOR(MOD_NOISE) /* ------------------------- Row 18 --------------------------*/ DEF_ICON_COLOR(MODIFIER)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_WAVE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_BUILD)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_DECIM)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_MIRROR)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_SOFT)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_SUBSURF)/* bfa - new iconsheet*/ DEF_ICON_COLOR(HOOK)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_PHYSICS)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_PARTICLES)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_BOOLEAN)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_EDGESPLIT)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_ARRAY)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_UVPROJECT)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_DISPLACE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_CURVE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_LATTICE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(CONSTRAINT_DATA)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_ARMATURE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_SHRINKWRAP)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_CAST)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_MESHDEFORM)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_BEVEL)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_SMOOTH)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_SIMPLEDEFORM)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_MASK)/* bfa - new iconsheet*/ DEF_ICON_COLOR(SELECT_SHORTESTPATH) DEF_ICON_COLOR(SELECT_SIDEOFACTIVE) DEF_ICON_COLOR(SELECT_UNGROUPED_VERTS) DEF_ICON_COLOR(ANGLE) DEF_ICON_COLOR(NODE_EXITEDITGROUP) DEF_ICON_COLOR(NODE_FILEOUTPUT) DEF_ICON_COLOR(SNAP_MIDPOINT) DEF_ICON_COLOR(SNAP_PERPENDICULAR) DEF_ICON_COLOR(NODE_FRAME) DEF_ICON_COLOR(NODE_FRESNEL) DEF_ICON_COLOR(NODE_GAMMA) DEF_ICON_COLOR(NODE_GEOMETRY) DEF_ICON_COLOR(NODE_GLARE) DEF_ICON_COLOR(NODE_GLASSHADER) DEF_ICON_COLOR(MOD_OFFSET)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_OPACITY)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_PARTICLE_INSTANCE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_SIMPLIFY)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_THICKNESS)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_TIME)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_TINT)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MODIFIER_OFF)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MODIFIER_ON)/* bfa - new iconsheet*/ DEF_ICON_COLOR(ORIENTATION_GLOBAL)/* bfa - new iconsheet*/ /* ------------------------- Row 19 --------------------------*/ /* MODIFIERS */ DEF_ICON_COLOR(MOD_CLOTH)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_EXPLODE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_FLUIDSIM)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_MULTIRES)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_SMOKE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_SOLIDIFY)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_SCREW)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_VERTEX_WEIGHT)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_DYNAMICPAINT)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_REMESH)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_OCEAN)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_WARP)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_SKIN)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_TRIANGULATE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_WIREFRAME)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_DATA_TRANSFER)/* bfa - new iconsheet*/ DEF_ICON_COLOR(MOD_NORMALEDIT)/* bfa - new iconsheet*/ DEF_ICON_COLOR(DECIMATE) DEF_ICON_COLOR(DEGENERATE_DISSOLVE) DEF_ICON_COLOR(DELETE_LOOSE) DEF_ICON_COLOR(FILL_HOLE) DEF_ICON_COLOR(MAKE_PLANAR) DEF_ICON_COLOR(SPLIT_CONCAVE) DEF_ICON_COLOR(SPLIT_NONPLANAR) DEF_ICON_COLOR(MERGE) DEF_ICON_COLOR(SEPARATE) DEF_ICON_COLOR(CREASE) DEF_ICON_COLOR(FACEREGIONS) DEF_ICON_COLOR(PERIMETER) DEF_ICON_COLOR(POLYGONSIDES) DEF_ICON_COLOR(NODE_GLOSSYSHADER) DEF_ICON_COLOR(NODE_GRADIENT) DEF_ICON_COLOR(NODE_GROUPINSERT) DEF_ICON_COLOR(NODE_HAIRINFO) DEF_ICON_BLANK(1119) DEF_ICON_COLOR(NODE_HOLDOUTSHADER) DEF_ICON_COLOR(NODE_HUESATURATION) DEF_ICON_BLANK(1122) DEF_ICON_COLOR(NODE_IMPAINT) DEF_ICON_COLOR(NODE_INVERT) DEF_ICON_BLANK(1125) DEF_ICON_COLOR(OUTPUT)/* bfa - new iconsheet*/ DEF_ICON_BLANK(1127) DEF_ICON_BLANK(1128) DEF_ICON_COLOR(SPHERE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(STROKE)/* bfa - new iconsheet*/ DEF_ICON_BLANK(1131) DEF_ICON_COLOR(UV) DEF_ICON_COLOR(WINDOW)/* bfa - new iconsheet*/ DEF_ICON_BLANK(1134) /* ------------------------- Row 20 --------------------------*/ DEF_ICON_COLOR(REC) DEF_ICON_COLOR(PLAY) DEF_ICON_COLOR(FF) DEF_ICON_COLOR(REW) DEF_ICON_COLOR(PAUSE) DEF_ICON_COLOR(PREV_KEYFRAME) DEF_ICON_COLOR(NEXT_KEYFRAME) DEF_ICON_COLOR(PLAY_AUDIO) DEF_ICON_COLOR(PLAY_REVERSE) DEF_ICON_COLOR(PREVIEW_RANGE) DEF_ICON_COLOR(ACTION_TWEAK) DEF_ICON_COLOR(PMARKER_ACT) DEF_ICON_COLOR(PMARKER_SEL) DEF_ICON_COLOR(PMARKER) DEF_ICON_COLOR(MARKER_HLT) DEF_ICON_COLOR(MARKER) DEF_ICON_COLOR(SPACE2) DEF_ICON_COLOR(SPACE3) DEF_ICON_COLOR(KEYINGSET) DEF_ICON_COLOR(KEY_DEHLT) DEF_ICON_COLOR(KEY_HLT) DEF_ICON_COLOR(MUTE_IPO_OFF) DEF_ICON_COLOR(MUTE_IPO_ON) DEF_ICON_BLANK(1164) DEF_ICON_BLANK(1165) DEF_ICON_COLOR(DRIVER) DEF_ICON_COLOR(AREA) DEF_ICON_COLOR(MIRROR_VERTEXGROUP) DEF_ICON_COLOR(SNAP_SYMMETRY) DEF_ICON_COLOR(SYMMETRIZE) DEF_ICON_COLOR(NODE_KEYINGSCREEN) DEF_ICON_COLOR(NODE_LAYERWEIGHT) DEF_ICON_COLOR(NODE_LENSDISTORT) DEF_ICON_BLANK(1175) DEF_ICON_COLOR(NODE_LIGHTFALLOFF) DEF_ICON_COLOR(NODE_LIGHTPATH) DEF_ICON_COLOR(NODE_LINESTYLE_OUTPUT) DEF_ICON_COLOR(NODE_LUMINANCE) DEF_ICON_BLANK(1180) DEF_ICON_COLOR(NODE_MAKEGROUP) DEF_ICON_COLOR(MODIFIER_DATA)/* bfa - new iconsheet*/ DEF_ICON_COLOR(TRACKER)/* bfa - new iconsheet*/ DEF_ICON_COLOR(TRACKER_DATA)/* bfa - new iconsheet*/ DEF_ICON_COLOR(UV_DATA)/* bfa - new iconsheet*/ DEF_ICON_COLOR(CUBEPROJECT) DEF_ICON_COLOR(CYLINDERPROJECT) DEF_ICON_COLOR(FOLLOWQUADS) DEF_ICON_COLOR(LIGHTMAPPACK) DEF_ICON_COLOR(PROJECTFROMVIEW) DEF_ICON_COLOR(SPHEREPROJECT) /* ------------------------- Row 21 --------------------------*/ DEF_ICON_COLOR(SOLO_OFF) DEF_ICON_COLOR(SOLO_ON) DEF_ICON_COLOR(FRAME_PREV) DEF_ICON_COLOR(FRAME_NEXT) DEF_ICON_COLOR(NLA_PUSHDOWN) DEF_ICON_COLOR(IPO_CONSTANT) DEF_ICON_COLOR(IPO_LINEAR) DEF_ICON_COLOR(IPO_BEZIER) DEF_ICON_COLOR(IPO_SINE) DEF_ICON_COLOR(IPO_QUAD) DEF_ICON_COLOR(IPO_CUBIC) DEF_ICON_COLOR(IPO_QUART) DEF_ICON_COLOR(IPO_QUINT) DEF_ICON_COLOR(IPO_EXPO) DEF_ICON_COLOR(IPO_CIRC) DEF_ICON_COLOR(IPO_BOUNCE) DEF_ICON_COLOR(IPO_ELASTIC) DEF_ICON_COLOR(IPO_BACK) DEF_ICON_COLOR(IPO_EASE_IN) DEF_ICON_COLOR(IPO_EASE_OUT) DEF_ICON_COLOR(IPO_EASE_IN_OUT) DEF_ICON_COLOR(NORMALIZE_FCURVES) DEF_ICON_COLOR(LIGHT_SIZE) DEF_ICON_COLOR(LIGHT_STRENGTH) DEF_ICON_COLOR(DOF) DEF_ICON_COLOR(LENS_ANGLE) DEF_ICON_COLOR(X_ICON) DEF_ICON_COLOR(Y_ICON) DEF_ICON_COLOR(Z_ICON) DEF_ICON_COLOR(EXTEND_VERTICES) DEF_ICON_COLOR(NODE_MAPPING) DEF_ICON_BLANK(1230) DEF_ICON_COLOR(NODE_MATERIALOUTPUT) DEF_ICON_COLOR(NODE_MATH) DEF_ICON_COLOR(NODE_MIXRGB) DEF_ICON_COLOR(NODE_MIXSHADER) DEF_ICON_BLANK(1235) DEF_ICON_BLANK(1236) DEF_ICON_COLOR(NODE_MOVIEDISTORT) DEF_ICON_BLANK(1238) DEF_ICON_COLOR(MOUSE_LMB) /*bfa- don't change the order of the mouse icons*//* bfa - new iconsheet*/ DEF_ICON_COLOR(MOUSE_MMB) /*bfa- don't change the order of the mouse icons*//* bfa - new iconsheet*/ DEF_ICON_COLOR(MOUSE_RMB) /*bfa- don't change the order of the mouse icons*//* bfa - new iconsheet*/ DEF_ICON_COLOR(MOUSE_MOVE) /*bfa- don't change the order of the mouse icons*//* bfa - new iconsheet*/ DEF_ICON_COLOR(MOUSE_LMB_DRAG) /*bfa- don't change the order of the mouse icons*//* bfa - new iconsheet*/ DEF_ICON_COLOR(MOUSE_MMB_DRAG) /*bfa- don't change the order of the mouse icons*//* bfa - new iconsheet*/ DEF_ICON_COLOR(MOUSE_RMB_DRAG) /*bfa- don't change the order of the mouse icons*//* bfa - new iconsheet*/ DEF_ICON_COLOR(AUTOMERGE_OFF) /*bfa- don't change the order of the automerge icons*//* bfa - new iconsheet*/ DEF_ICON_COLOR(AUTOMERGE_ON) /*bfa- don't change the order of the automerge icons*//* bfa - new iconsheet*/ DEF_ICON_BLANK(1249) /* ------------------------- Row 22 --------------------------*/ DEF_ICON_COLOR(VERTEXSEL) DEF_ICON_COLOR(EDGESEL) DEF_ICON_COLOR(FACESEL) DEF_ICON_COLOR(LOOPSEL) DEF_ICON_COLOR(DRAWSIZE) DEF_ICON_COLOR(ROTATE) DEF_ICON_COLOR(CURSOR) DEF_ICON_COLOR(ROTATECOLLECTION) DEF_ICON_COLOR(ROTATECENTER) DEF_ICON_COLOR(ROTACTIVE) DEF_ICON_COLOR(ALIGN) DEF_ICON_COLOR(HIDE_UNSELECTED) DEF_ICON_COLOR(SMOOTHCURVE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(SPHERECURVE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(ROOTCURVE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(SHARPCURVE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(LINCURVE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(NOCURVE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(RNDCURVE)/* bfa - new iconsheet*/ DEF_ICON_COLOR(PROP_OFF) /*bfa- don't change the order of the prop icons*//*bfa - new iconset*/ DEF_ICON_COLOR(PROP_ON)/*bfa- don't change the order of the prop icons*//*bfa - new iconset*/ DEF_ICON_COLOR(PROP_CON)/*bfa- don't change the order of the prop icons*//*bfa - new iconset*/ DEF_ICON_COLOR(CLEAR_TRACK) DEF_ICON_COLOR(PARTICLE_POINT) DEF_ICON_COLOR(PARTICLE_TIP) DEF_ICON_COLOR(PARTICLE_PATH) DEF_ICON_COLOR(RIP) DEF_ICON_COLOR(RIP_FILL) DEF_ICON_COLOR(HOOK_NEW) DEF_ICON_COLOR(HOOK_SELECTED) DEF_ICON_BLANK(1286) DEF_ICON_BLANK(1287) DEF_ICON_COLOR(NODE_NORMALIZE) DEF_ICON_COLOR(NODE_NORMALMAP) DEF_ICON_COLOR(NODE_OBJECTINFO) DEF_ICON_COLOR(NODE_OUTPUT) DEF_ICON_COLOR(NODE_PARTICLEINFO) DEF_ICON_COLOR(NODE_PIXELATED) DEF_ICON_COLOR(NODE_PLANETRACKDEFORM) DEF_ICON_COLOR(NODE_POINTCLOUD) DEF_ICON_COLOR(PARENT_BONE) DEF_ICON_COLOR(PARENT_CURVE) DEF_ICON_COLOR(PARENT_LATTICE) DEF_ICON_COLOR(PARENT_OBJECT) DEF_ICON_COLOR(TOGGLECAPS_BOTH) DEF_ICON_COLOR(TOGGLECAPS_DEFAULT) DEF_ICON_COLOR(TOGGLECAPS_END) DEF_ICON_COLOR(TOGGLECAPS_START) DEF_ICON_BLANK(1305) DEF_ICON_BLANK(1306) /* ------------------------- Row 23 --------------------------*/ DEF_ICON_COLOR(MAN_TRANS) DEF_ICON_COLOR(MAN_ROT) DEF_ICON_COLOR(MAN_SCALE) DEF_ICON_COLOR(MANIPUL) DEF_ICON_COLOR(SNAP_OFF) DEF_ICON_COLOR(SNAP_ON) DEF_ICON_COLOR(SNAP_NORMAL) DEF_ICON_COLOR(SNAP_GRID) DEF_ICON_COLOR(SNAP_VERTEX) DEF_ICON_COLOR(SNAP_EDGE) DEF_ICON_COLOR(SNAP_FACE) DEF_ICON_COLOR(SNAP_VOLUME) DEF_ICON_COLOR(SNAP_INCREMENT) DEF_ICON_COLOR(STICKY_UVS_LOC) DEF_ICON_COLOR(STICKY_UVS_DISABLE) DEF_ICON_COLOR(STICKY_UVS_VERT) DEF_ICON_COLOR(CLIPUV_DEHLT) DEF_ICON_COLOR(CLIPUV_HLT) DEF_ICON_COLOR(SNAP_PEEL_OBJECT) DEF_ICON_COLOR(GRID) DEF_ICON_COLOR(UNDO) DEF_ICON_COLOR(REDO) DEF_ICON_COLOR(REPEAT) DEF_ICON_COLOR(UNDO_HISTORY) DEF_ICON_COLOR(REDO_HISTORY) DEF_ICON_COLOR(BEVEL) DEF_ICON_COLOR(HOOK_BONE) DEF_ICON_COLOR(HOOK_ASSIGN) DEF_ICON_COLOR(HOOK_RESET) DEF_ICON_COLOR(HOOK_RECENTER) DEF_ICON_COLOR(NODE_PRINCIPLED) DEF_ICON_COLOR(NODE_RANGE) DEF_ICON_COLOR(NODE_REFRACTIONSHADER) DEF_ICON_BLANK(1346) DEF_ICON_COLOR(NODE_REROUTE) DEF_ICON_COLOR(NODE_RGB) DEF_ICON_COLOR(NODE_RGBCURVE) DEF_ICON_COLOR(NODE_RGBTOBW) DEF_ICON_BLANK(1351) DEF_ICON_BLANK(1352) DEF_ICON_COLOR(SELECT_DIFFERENCE)/*bfa - new iconset*/ DEF_ICON_COLOR(SELECT_EXTEND)/*bfa - new iconset*/ DEF_ICON_COLOR(SELECT_INTERSECT)/*bfa - new iconset*/ DEF_ICON_COLOR(SELECT_SET)/*bfa - new iconset*/ DEF_ICON_COLOR(SELECT_SUBTRACT)/*bfa - new iconset*/ DEF_ICON_COLOR(FCURVE_SNAPSHOT)/*bfa - new iconset*/ DEF_ICON_BLANK(1360) DEF_ICON_BLANK(1361) DEF_ICON_COLOR(OBJECT_HIDDEN)/*bfa - new iconset*/ DEF_ICON_BLANK(1363) /* ------------------------- Row 24 --------------------------*/ DEF_ICON_COLOR(PASTEDOWN) DEF_ICON_COLOR(COPYDOWN) DEF_ICON_COLOR(PASTEFLIPUP) DEF_ICON_COLOR(PASTEFLIPDOWN) DEF_ICON_COLOR(SLIDE_EDGE) DEF_ICON_COLOR(SLIDE_VERTEX) DEF_ICON_COLOR(SMOOTH_VERTEX) DEF_ICON_BLANK(1374) DEF_ICON_COLOR(SNAP_SURFACE) DEF_ICON_BLANK(1376) DEF_ICON_BLANK(1378) DEF_ICON_COLOR(RETOPO) DEF_ICON_COLOR(UV_VERTEXSEL) DEF_ICON_COLOR(UV_EDGESEL) DEF_ICON_COLOR(UV_FACESEL) DEF_ICON_COLOR(UV_ISLANDSEL) DEF_ICON_COLOR(UV_SYNC_SELECT) DEF_ICON_COLOR(NOISE) DEF_ICON_COLOR(RANDOMIZE) DEF_ICON_COLOR(EXTRUDE_REGION) DEF_ICON_COLOR(SHOW_UNSELECTED) DEF_ICON_COLOR(DUPLI_EXTRUDE) DEF_ICON_COLOR(DUPLI_EXTRUDE_ROTATE) DEF_ICON_COLOR(SPIN) DEF_ICON_COLOR(SCREW) DEF_ICON_COLOR(MAKE_REGULAR) DEF_ICON_COLOR(HOOK_REMOVE) DEF_ICON_COLOR(HOOK_SELECT) DEF_ICON_COLOR(BOX_MASK) DEF_ICON_COLOR(CLEAR_MASK) DEF_ICON_BLANK(1400) DEF_ICON_COLOR(NODE_SEPARATE_YCBCRA) DEF_ICON_COLOR(NODE_SEPARATE_YUVA) DEF_ICON_COLOR(NODE_SEPARATEHSV) DEF_ICON_COLOR(NODE_SEPARATERGB) DEF_ICON_COLOR(NODE_SEPARATEXYZ) DEF_ICON_COLOR(NODE_SKY) DEF_ICON_COLOR(NODE_SSS) DEF_ICON_COLOR(NODE_STABILIZE2D) DEF_ICON_BLANK(1409) DEF_ICON_COLOR(CON_CAMERASOLVER) /*bfa - new iconset*/ DEF_ICON_COLOR(CON_FOLLOWTRACK) /*bfa - new iconset*/ DEF_ICON_COLOR(CON_OBJECTSOLVER) /*bfa - new iconset*/ DEF_ICON_COLOR(CON_LOCLIKE) /*bfa - new iconset*/ DEF_ICON_COLOR(CON_ROTLIKE) /*bfa - new iconset*/ DEF_ICON_COLOR(CON_SIZELIKE) /*bfa - new iconset*/ DEF_ICON_COLOR(CON_TRANSLIKE) /*bfa - new iconset*/ DEF_ICON_COLOR(CON_DISTLIMIT) /*bfa - new iconset*/ DEF_ICON_COLOR(CON_LOCLIMIT) /*bfa - new iconset*/ DEF_ICON_COLOR(CON_ROTLIMIT) /*bfa - new iconset*/ /* ------------------------- Row 25 --------------------------*/ DEF_ICON_COLOR(CHECKMARK) DEF_ICON_COLOR(FILE_ARCHIVE) DEF_ICON_COLOR(SNAP_FACE_CENTER) DEF_ICON_COLOR(TRANSFORM_ORIGINS) DEF_ICON_BLANK(1428) DEF_ICON_COLOR(TRANSFER_UV) DEF_ICON_COLOR(ORTHO) DEF_ICON_COLOR(PUSH_PULL) DEF_ICON_COLOR(SHRINK_FATTEN) DEF_ICON_BLANK(1434) DEF_ICON_COLOR(VIEW) /*bfa - new iconset*/ DEF_ICON_COLOR(TILT) DEF_ICON_COLOR(AXIS_SIDE) /*bfa - new iconset*/ DEF_ICON_COLOR(AXIS_FRONT) /*bfa - new iconset*/ DEF_ICON_COLOR(AXIS_TOP) /*bfa - new iconset*/ DEF_ICON_COLOR(NDOF_DOM) DEF_ICON_COLOR(NDOF_TURN) DEF_ICON_COLOR(NDOF_FLY) DEF_ICON_COLOR(NDOF_TRANS) DEF_ICON_COLOR(LAYER_USED) DEF_ICON_COLOR(LAYER_ACTIVE) DEF_ICON_COLOR(TRANSFORM_MIRROR) DEF_ICON_COLOR(TRANSFORM_MOVE) DEF_ICON_COLOR(TRANSFORM_ROTATE) DEF_ICON_COLOR(TRANSFORM_SCALE) DEF_ICON_COLOR(SEQ_ADD) DEF_ICON_COLOR(FILL_MASK) DEF_ICON_COLOR(INVERT_MASK) DEF_ICON_COLOR(LASSO_MASK) DEF_ICON_COLOR(BRIGHTNESS_CONTRAST) DEF_ICON_COLOR(NODE_SUNBEAMS) DEF_ICON_BLANK(1458) DEF_ICON_BLANK(1459) DEF_ICON_COLOR(NODE_TANGENT) DEF_ICON_COLOR(NODE_TEXCOORDINATE) DEF_ICON_BLANK(1462) DEF_ICON_BLANK(1436) DEF_ICON_COLOR(NODE_TONEMAP) DEF_ICON_COLOR(NODE_TOONSHADER) DEF_ICON_COLOR(NODE_TRACKPOSITION) DEF_ICON_COLOR(CON_SIZELIMIT) /*bfa - new iconset*/ DEF_ICON_COLOR(CON_SAMEVOL) /*bfa - new iconset*/ DEF_ICON_COLOR(CON_TRANSFORM) /*bfa - new iconset*/ DEF_ICON_COLOR(CON_TRANSFORM_CACHE) /*bfa - new iconset*/ DEF_ICON_COLOR(CON_CLAMPTO) /*bfa - new iconset*/ DEF_ICON_COLOR(CON_KINEMATIC) /*bfa - new iconset*/ DEF_ICON_COLOR(CON_LOCKTRACK) /*bfa - new iconset*/ DEF_ICON_COLOR(CON_SPLINEIK) /*bfa - new iconset*/ DEF_ICON_COLOR(CON_STRETCHTO) /*bfa - new iconset*/ DEF_ICON_COLOR(CON_TRACKTO) /*bfa - new iconset*/ /* ------------------------- Row 26 --------------------------*/ DEF_ICON_COLOR(LOAD_3DS) DEF_ICON_COLOR(LOAD_BVH) DEF_ICON_COLOR(LOAD_DAE) DEF_ICON_COLOR(LOAD_FBX) DEF_ICON_COLOR(LOAD_OBJ) DEF_ICON_COLOR(LOAD_PLY) DEF_ICON_COLOR(LOAD_STL) DEF_ICON_COLOR(LOAD_SVG) DEF_ICON_COLOR(LOAD_WRL) DEF_ICON_COLOR(SAVE_3DS) DEF_ICON_COLOR(SAVE_BVH) DEF_ICON_COLOR(SAVE_DAE) DEF_ICON_COLOR(SAVE_FBX) DEF_ICON_COLOR(SAVE_OBJ) DEF_ICON_COLOR(SAVE_PLY) DEF_ICON_COLOR(SAVE_STL) DEF_ICON_COLOR(SAVE_WRL) DEF_ICON_COLOR(LOAD_ABC) DEF_ICON_COLOR(SAVE_ABC) DEF_ICON_COLOR(ROTATE_MINUS_90) DEF_ICON_COLOR(ROTATE_PLUS_90) DEF_ICON_COLOR(MIRROR_X) DEF_ICON_COLOR(MIRROR_Y) DEF_ICON_COLOR(MIRROR_Z) DEF_ICON_COLOR(LIBRARY) DEF_ICON_COLOR(LIBRARY_OBJECT) DEF_ICON_COLOR(DIRTY_VERTEX) DEF_ICON_COLOR(HUESATVAL) DEF_ICON_COLOR(LEVELS) DEF_ICON_COLOR(SEQ_TEXT) DEF_ICON_COLOR(NODE_TRANSFORM) DEF_ICON_COLOR(NODE_TRANSLUCENT) DEF_ICON_COLOR(NODE_TRANSPARENT) DEF_ICON_COLOR(NODE_UNGROUP) DEF_ICON_COLOR(NODE_UVALONGSTROKE) DEF_ICON_BLANK(1519) DEF_ICON_COLOR(NODE_VALUE) DEF_ICON_COLOR(NODE_VECTOR) DEF_ICON_COLOR(NODE_VECTOR_BLUR) DEF_ICON_COLOR(NODE_VECTOR_TRANSFORM) DEF_ICON_COLOR(CON_ARMATURE) /*bfa - new iconset*/ DEF_ICON_COLOR(CON_CHILDOF) /*bfa - new iconset*/ DEF_ICON_COLOR(CON_FLOOR) /*bfa - new iconset*/ DEF_ICON_COLOR(CON_FOLLOWPATH) /*bfa - new iconset*/ DEF_ICON_COLOR(CON_PIVOT) /*bfa - new iconset*/ DEF_ICON_COLOR(CON_SHRINKWRAP) /*bfa - new iconset*/ DEF_ICON_COLOR(CON_ACTION) /*bfa - new iconset*/ DEF_ICON_BLANK(1532) DEF_ICON_BLANK(1533) DEF_ICON_BLANK(1534) /* ------------------------- Row 27 --------------------------*/ DEF_ICON_COLOR(SORTALPHA) DEF_ICON_COLOR(SORTBYEXT) DEF_ICON_COLOR(SORTTIME) DEF_ICON_COLOR(SORTSIZE) DEF_ICON_COLOR(LONGDISPLAY) DEF_ICON_COLOR(SHORTDISPLAY) DEF_ICON_COLOR(GHOST) DEF_ICON_COLOR(IMGDISPLAY) DEF_ICON_COLOR(SAVE_AS) DEF_ICON_COLOR(SAVE_COPY) DEF_ICON_COLOR(BOOKMARKS) DEF_ICON_COLOR(FONTPREVIEW) DEF_ICON_COLOR(FILTER) DEF_ICON_COLOR(NEWFOLDER) DEF_ICON_COLOR(OPEN_RECENT) DEF_ICON_COLOR(FILE_PARENT) DEF_ICON_COLOR(FILE_REFRESH) DEF_ICON_COLOR(FILE_FOLDER) DEF_ICON_BLANK(1557) DEF_ICON_COLOR(FILE_BLEND) DEF_ICON_COLOR(FILE_IMAGE) DEF_ICON_COLOR(FILE_MOVIE) DEF_ICON_COLOR(FILE_SCRIPT) DEF_ICON_COLOR(FILE_SOUND) DEF_ICON_COLOR(FILE_FONT) DEF_ICON_COLOR(FILE_TEXT) DEF_ICON_COLOR(SELECT_FIRST) DEF_ICON_COLOR(SELECT_LAST) DEF_ICON_COLOR(CONTROLPOINTROW) DEF_ICON_COLOR(MAKE_CURVESEGMENT) DEF_ICON_COLOR(NODE_VECTORMATH) DEF_ICON_COLOR(NODE_VELVET) DEF_ICON_COLOR(NODE_VIEWER) DEF_ICON_COLOR(NODE_VIWERSPLIT) DEF_ICON_COLOR(NODE_VOLUMEABSORPTION) DEF_ICON_COLOR(NODE_VOLUMESCATTER) DEF_ICON_BLANK(1577) DEF_ICON_COLOR(NODE_WAVELENGTH) DEF_ICON_COLOR(NODE_WAVES) DEF_ICON_COLOR(NODE_WIREFRAME) DEF_ICON_BLANK(1582) DEF_ICON_BLANK(1583) DEF_ICON_BLANK(1584) DEF_ICON_BLANK(1585) DEF_ICON_BLANK(1586) DEF_ICON_BLANK(1587) DEF_ICON_BLANK(1588) DEF_ICON_BLANK(1589) DEF_ICON_BLANK(1590) DEF_ICON_BLANK(1591) /* ------------------------- Row 28 --------------------------*/ DEF_ICON_COLOR(RECOVER_AUTO) DEF_ICON_COLOR(SAVE_PREFS) DEF_ICON_COLOR(LINK_BLEND) DEF_ICON_COLOR(APPEND_BLEND) DEF_ICON_COLOR(IMPORT) DEF_ICON_COLOR(EXPORT) DEF_ICON_COLOR(EXTERNAL_DATA) DEF_ICON_COLOR(LOAD_FACTORY) DEF_ICON_COLOR(APPLYMOVEDELTA) DEF_ICON_COLOR(APPLYROTATEDELTA) DEF_ICON_COLOR(APPLYSCALEDELTA) DEF_ICON_COLOR(APPLYALLDELTA) DEF_ICON_COLOR(APPLYANIDELTA) DEF_ICON_COLOR(LOOP_BACK) DEF_ICON_COLOR(LOOP_FORWARDS) DEF_ICON_COLOR(BACK) DEF_ICON_COLOR(FORWARD) DEF_ICON_COLOR(ALIGNCAMERA_ACTIVE) DEF_ICON_COLOR(ALIGNCAMERA_VIEW) DEF_ICON_COLOR(CENTERTOCURSOR) DEF_ICON_COLOR(LOCK_CLEAR) DEF_ICON_COLOR(LOCKTOACTIVE) DEF_ICON_COLOR(LOCKTOCENTER) DEF_ICON_COLOR(FILE_HIDDEN) DEF_ICON_COLOR(FILE_BACKUP) DEF_ICON_COLOR(DISK_DRIVE) DEF_ICON_COLOR(SMOOTH_RADIUS) DEF_ICON_COLOR(SMOOTH_TILT) DEF_ICON_COLOR(SMOOTH_WEIGHT) DEF_ICON_COLOR(CLEAR_TILT) DEF_ICON_BLANK(1628) DEF_ICON_BLANK(1629) DEF_ICON_COLOR(NODE_ZCOMBINE) DEF_ICON_COLOR(NODE_KEYING) DEF_ICON_BLANK(1632) DEF_ICON_BLANK(1633) DEF_ICON_COLOR(NODE_SPILL) DEF_ICON_COLOR(REMOVE_ACTIVE_GROUP) DEF_ICON_COLOR(REMOVE_ALL_GROUPS) DEF_ICON_COLOR(SET_FRAMES) DEF_ICON_BLANK(1639) DEF_ICON_BLANK(1640) DEF_ICON_BLANK(1641) DEF_ICON_BLANK(1642) DEF_ICON_BLANK(1643) DEF_ICON_BLANK(1644) DEF_ICON_BLANK(1645) DEF_ICON_BLANK(1646) DEF_ICON_BLANK(1647) DEF_ICON_BLANK(1648) /* ------------------------- Row 29 --------------------------*/ DEF_ICON_COLOR(MATPLANE) DEF_ICON_COLOR(MATSPHERE) DEF_ICON_COLOR(MATCUBE) DEF_ICON_COLOR(MONKEY) DEF_ICON_COLOR(HAIR) DEF_ICON_COLOR(ALIASED) DEF_ICON_COLOR(ANTIALIASED) DEF_ICON_COLOR(MAT_SPHERE_SKY) DEF_ICON_COLOR(MOVE_TEXTURESPACE) DEF_ICON_COLOR(SCALE_TEXTURESPACE) DEF_ICON_COLOR(RANDOMIZE_TRANSFORM) DEF_ICON_COLOR(ALIGN_TRANSFORM) DEF_ICON_COLOR(WORDWRAP_OFF) DEF_ICON_COLOR(WORDWRAP_ON) DEF_ICON_COLOR(SYNTAX_OFF) DEF_ICON_COLOR(SYNTAX_ON) DEF_ICON_COLOR(LINENUMBERS_OFF) DEF_ICON_COLOR(LINENUMBERS_ON) DEF_ICON_COLOR(SCRIPTPLUGINS) DEF_ICON_COLOR(BOLD) DEF_ICON_COLOR(ITALIC) DEF_ICON_COLOR(UNDERLINED) DEF_ICON_COLOR(SET_LOWERCASE) DEF_ICON_COLOR(SET_UPPERCASE) DEF_ICON_COLOR(SMALL_CAPS) DEF_ICON_COLOR(SET_FROM_FACES) DEF_ICON_COLOR(CUT) DEF_ICON_COLOR(PASTEFILE) DEF_ICON_COLOR(CIRCLE) DEF_ICON_COLOR(COPYRIGHT) DEF_ICON_COLOR(YEN) DEF_ICON_COLOR(ABSOLUTEPATH) DEF_ICON_COLOR(RELATIVEPATH) DEF_ICON_COLOR(BATCH_GENERATE) DEF_ICON_COLOR(BATCH_GENERATE_CLEAR) DEF_ICON_COLOR(DATABLOCK_CLEAR) DEF_ICON_COLOR(DETECT) DEF_ICON_COLOR(DISABLE) DEF_ICON_COLOR(ENABLE) DEF_ICON_COLOR(PLANETRACK) DEF_ICON_COLOR(SEQ_SWAP_LEFT) DEF_ICON_COLOR(SEQ_SWAP_RIGHT) DEF_ICON_COLOR(SEQ_RELOAD_STRIPS) DEF_ICON_COLOR(SEQ_RELOAD_ADJUST_LENGTH) DEF_ICON_COLOR(TOGGLE_META) DEF_ICON_COLOR(SEQ_SNAP_STRIP) DEF_ICON_BLANK(1702) DEF_ICON_BLANK(1703) DEF_ICON_BLANK(1704) DEF_ICON_BLANK(1705) /* ------------------------- Row 30 --------------------------*/ DEF_ICON_COLOR(SEQ_SEQUENCER) DEF_ICON_COLOR(SEQ_PREVIEW) DEF_ICON_COLOR(SEQ_LUMA_WAVEFORM) DEF_ICON_COLOR(SEQ_CHROMA_SCOPE) DEF_ICON_COLOR(SEQ_HISTOGRAM) DEF_ICON_COLOR(SEQ_SPLITVIEW) DEF_ICON_COLOR(NEXTACTIVE) DEF_ICON_COLOR(PREVIOUSACTIVE) DEF_ICON_COLOR(BRUSH_RESET) DEF_ICON_COLOR(IMAGE_RGB) DEF_ICON_COLOR(IMAGE_RGB_ALPHA) DEF_ICON_COLOR(IMAGE_ALPHA) DEF_ICON_COLOR(IMAGE_ZDEPTH) DEF_ICON_BLANK(1723) DEF_ICON_COLOR(CURSORTOACTIVE) DEF_ICON_COLOR(CURSORTOCENTER) DEF_ICON_COLOR(CURSORTOGRID) DEF_ICON_COLOR(CURSORTOSELECTION) DEF_ICON_COLOR(SELECTIONTOCURSOROFFSET) DEF_ICON_COLOR(SELECTIONTOACTIVE) DEF_ICON_COLOR(SELECTIONTOCURSOR) DEF_ICON_COLOR(SELECTIONTOGRID) DEF_ICON_COLOR(CURSOR_TO_PIXELS) DEF_ICON_COLOR(SNAP_TO_ADJACENT) DEF_ICON_COLOR(SNAP_TO_PIXELS) DEF_ICON_COLOR(PATTERN) DEF_ICON_COLOR(DEGREE) DEF_ICON_COLOR(DOUBLE_LEFT) DEF_ICON_COLOR(DOUBLE_RIGHT) DEF_ICON_COLOR(DUTCH_FLORIN) DEF_ICON_COLOR(GERMAN_S) DEF_ICON_COLOR(MULTIPLICATION) DEF_ICON_COLOR(POUND) DEF_ICON_COLOR(PROMILLE) DEF_ICON_COLOR(SPANISH_EXCLAMATION) DEF_ICON_COLOR(SPANISH_QUESTION) DEF_ICON_COLOR(SUPER_ONE) DEF_ICON_COLOR(SUPER_TWO) DEF_ICON_COLOR(SUPER_THREE) DEF_ICON_COLOR(TRADEMARK) DEF_ICON_COLOR(SEQ_SNAP_TO_FRAME) DEF_ICON_COLOR(SEQ_CLEAR_OFFSET) DEF_ICON_COLOR(SEQ_CUT_HARD_AT_FRAME) DEF_ICON_COLOR(SEQ_CUT_SOFT_AT_FRAME) DEF_ICON_COLOR(SEQ_DEINTERLACE) DEF_ICON_COLOR(SEQ_MOVE_EXTEND) DEF_ICON_COLOR(SEQ_SLIP_CONTENTS) DEF_ICON_COLOR(SEQ_REMOVE_GAPS) DEF_ICON_COLOR(SEQ_INSERT_GAPS) DEF_ICON_COLOR(SEQ_SWAP_DATA) /*----------------- newline END OF ICONSHEET -------------------------------------*/ /* brush icons */ DEF_ICON_COLOR(BRUSH_BLOB) DEF_ICON_COLOR(BRUSH_BLUR) DEF_ICON_COLOR(BRUSH_CLAY) DEF_ICON_COLOR(BRUSH_CLAY_STRIPS) DEF_ICON_COLOR(BRUSH_CLONE) DEF_ICON_COLOR(BRUSH_CREASE) DEF_ICON_COLOR(BRUSH_FILL) DEF_ICON_COLOR(BRUSH_FLATTEN) DEF_ICON_COLOR(BRUSH_GRAB) DEF_ICON_COLOR(BRUSH_INFLATE) DEF_ICON_COLOR(BRUSH_LAYER) DEF_ICON_COLOR(BRUSH_MASK) DEF_ICON_COLOR(BRUSH_MIX) DEF_ICON_COLOR(BRUSH_NUDGE) DEF_ICON_COLOR(BRUSH_PINCH) DEF_ICON_COLOR(BRUSH_SCRAPE) DEF_ICON_COLOR(BRUSH_SCULPT_DRAW) DEF_ICON_COLOR(BRUSH_SMEAR) DEF_ICON_COLOR(BRUSH_SMOOTH) DEF_ICON_COLOR(BRUSH_SNAKE_HOOK) DEF_ICON_COLOR(BRUSH_SOFTEN) DEF_ICON_COLOR(BRUSH_TEXDRAW) DEF_ICON_COLOR(BRUSH_TEXFILL) DEF_ICON_COLOR(BRUSH_TEXMASK) DEF_ICON_COLOR(BRUSH_THUMB) DEF_ICON_COLOR(BRUSH_ROTATE) /* grease pencil sculpt */ DEF_ICON_COLOR(GPBRUSH_SMOOTH) DEF_ICON_COLOR(GPBRUSH_THICKNESS) DEF_ICON_COLOR(GPBRUSH_STRENGTH) DEF_ICON_COLOR(GPBRUSH_GRAB) DEF_ICON_COLOR(GPBRUSH_PUSH) DEF_ICON_COLOR(GPBRUSH_TWIST) DEF_ICON_COLOR(GPBRUSH_PINCH) DEF_ICON_COLOR(GPBRUSH_RANDOMIZE) DEF_ICON_COLOR(GPBRUSH_CLONE) DEF_ICON_COLOR(GPBRUSH_WEIGHT) DEF_ICON_COLOR(GPBRUSH_PENCIL) DEF_ICON_COLOR(GPBRUSH_PEN) DEF_ICON_COLOR(GPBRUSH_INK) DEF_ICON_COLOR(GPBRUSH_INKNOISE) DEF_ICON_COLOR(GPBRUSH_BLOCK) DEF_ICON_COLOR(GPBRUSH_MARKER) DEF_ICON_COLOR(GPBRUSH_FILL) DEF_ICON_COLOR(GPBRUSH_ERASE_SOFT) DEF_ICON_COLOR(GPBRUSH_ERASE_HARD) DEF_ICON_COLOR(GPBRUSH_ERASE_STROKE) /* Vector Icons */ DEF_ICON_VECTOR(SMALL_TRI_RIGHT_VEC) DEF_ICON_VECTOR(KEYTYPE_KEYFRAME_VEC) DEF_ICON_VECTOR(KEYTYPE_BREAKDOWN_VEC) DEF_ICON_VECTOR(KEYTYPE_EXTREME_VEC) DEF_ICON_VECTOR(KEYTYPE_JITTER_VEC) DEF_ICON_VECTOR(KEYTYPE_MOVING_HOLD_VEC) DEF_ICON_VECTOR(HANDLETYPE_FREE_VEC) DEF_ICON_VECTOR(HANDLETYPE_ALIGNED_VEC) DEF_ICON_VECTOR(HANDLETYPE_VECTOR_VEC) DEF_ICON_VECTOR(HANDLETYPE_AUTO_VEC) DEF_ICON_VECTOR(HANDLETYPE_AUTO_CLAMP_VEC) DEF_ICON_VECTOR(COLORSET_01_VEC) DEF_ICON_VECTOR(COLORSET_02_VEC) DEF_ICON_VECTOR(COLORSET_03_VEC) DEF_ICON_VECTOR(COLORSET_04_VEC) DEF_ICON_VECTOR(COLORSET_05_VEC) DEF_ICON_VECTOR(COLORSET_06_VEC) DEF_ICON_VECTOR(COLORSET_07_VEC) DEF_ICON_VECTOR(COLORSET_08_VEC) DEF_ICON_VECTOR(COLORSET_09_VEC) DEF_ICON_VECTOR(COLORSET_10_VEC) DEF_ICON_VECTOR(COLORSET_11_VEC) DEF_ICON_VECTOR(COLORSET_12_VEC) DEF_ICON_VECTOR(COLORSET_13_VEC) DEF_ICON_VECTOR(COLORSET_14_VEC) DEF_ICON_VECTOR(COLORSET_15_VEC) DEF_ICON_VECTOR(COLORSET_16_VEC) DEF_ICON_VECTOR(COLORSET_17_VEC) DEF_ICON_VECTOR(COLORSET_18_VEC) DEF_ICON_VECTOR(COLORSET_19_VEC) DEF_ICON_VECTOR(COLORSET_20_VEC) /* Events */ DEF_ICON_COLOR(EVENT_A) DEF_ICON_COLOR(EVENT_B) DEF_ICON_COLOR(EVENT_C) DEF_ICON_COLOR(EVENT_D) DEF_ICON_COLOR(EVENT_E) DEF_ICON_COLOR(EVENT_F) DEF_ICON_COLOR(EVENT_G) DEF_ICON_COLOR(EVENT_H) DEF_ICON_COLOR(EVENT_I) DEF_ICON_COLOR(EVENT_J) DEF_ICON_COLOR(EVENT_K) DEF_ICON_COLOR(EVENT_L) DEF_ICON_COLOR(EVENT_M) DEF_ICON_COLOR(EVENT_N) DEF_ICON_COLOR(EVENT_O) DEF_ICON_COLOR(EVENT_P) DEF_ICON_COLOR(EVENT_Q) DEF_ICON_COLOR(EVENT_R) DEF_ICON_COLOR(EVENT_S) DEF_ICON_COLOR(EVENT_T) DEF_ICON_COLOR(EVENT_U) DEF_ICON_COLOR(EVENT_V) DEF_ICON_COLOR(EVENT_W) DEF_ICON_COLOR(EVENT_X) DEF_ICON_COLOR(EVENT_Y) DEF_ICON_COLOR(EVENT_Z) DEF_ICON_COLOR(EVENT_SHIFT) DEF_ICON_COLOR(EVENT_CTRL) DEF_ICON_COLOR(EVENT_ALT) DEF_ICON_COLOR(EVENT_OS) DEF_ICON_COLOR(EVENT_F1) DEF_ICON_COLOR(EVENT_F2) DEF_ICON_COLOR(EVENT_F3) DEF_ICON_COLOR(EVENT_F4) DEF_ICON_COLOR(EVENT_F5) DEF_ICON_COLOR(EVENT_F6) DEF_ICON_COLOR(EVENT_F7) DEF_ICON_COLOR(EVENT_F8) DEF_ICON_COLOR(EVENT_F9) DEF_ICON_COLOR(EVENT_F10) DEF_ICON_COLOR(EVENT_F11) DEF_ICON_COLOR(EVENT_F12) DEF_ICON_COLOR(EVENT_ESC) DEF_ICON_COLOR(EVENT_TAB) DEF_ICON_COLOR(EVENT_PAGEUP) DEF_ICON_COLOR(EVENT_PAGEDOWN) DEF_ICON_COLOR(EVENT_RETURN) /* add as needed. */ /* Undefine all types. */ #undef DEF_ICON #undef DEF_ICON_ERROR #undef DEF_ICON_SCENE #undef DEF_ICON_COLLECTION #undef DEF_ICON_OBJECT #undef DEF_ICON_OBJECT_DATA #undef DEF_ICON_MODIFIER #undef DEF_ICON_SHADING #undef DEF_ICON_VECTOR #undef DEF_ICON_COLOR #undef DEF_ICON_BLANK
30.230167
109
0.823035
[ "shape", "vector" ]
b9b4c64930d4c6d85e86ebaa4877fd37f70a1d8b
17,053
h
C
src/libSBML/src/sbml/packages/distrib/extension/DistribExtension.h
copasi/copasi-dependencies
c01dd455c843522375c32c2989aa8675f59bb810
[ "Unlicense" ]
5
2015-04-16T14:27:38.000Z
2021-11-30T14:54:39.000Z
src/libSBML/src/sbml/packages/distrib/extension/DistribExtension.h
copasi/copasi-dependencies
c01dd455c843522375c32c2989aa8675f59bb810
[ "Unlicense" ]
8
2017-05-30T16:58:39.000Z
2022-02-22T16:51:34.000Z
src/libSBML/src/sbml/packages/distrib/extension/DistribExtension.h
copasi/copasi-dependencies
c01dd455c843522375c32c2989aa8675f59bb810
[ "Unlicense" ]
7
2016-05-29T08:12:59.000Z
2019-05-02T13:39:25.000Z
/** * @file DistribExtension.h * @brief Definition of DistribExtension. * @author SBMLTeam * * <!-------------------------------------------------------------------------- * This file is part of libSBML. Please visit http://sbml.org for more * information about SBML, and the latest version of libSBML. * * Copyright (C) 2020 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. University of Heidelberg, Heidelberg, Germany * 3. University College London, London, UK * * Copyright (C) 2019 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. University of Heidelberg, Heidelberg, Germany * * Copyright (C) 2013-2018 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK * 3. University of Heidelberg, Heidelberg, Germany * * Copyright (C) 2009-2013 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK * * Copyright (C) 2006-2008 by the California Institute of Technology, * Pasadena, CA, USA * * Copyright (C) 2002-2005 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. Japan Science and Technology Agency, Japan * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation. A copy of the license agreement is provided in the * file named "LICENSE.txt" included with this software distribution and also * available online as http://sbml.org/software/libsbml/license.html * ------------------------------------------------------------------------ --> * * @class DistribExtension * @sbmlbrief{distrib} Base extension class for the package. * * @htmlinclude not-sbml-warning.html * * This is the Distrib package extension of the SBMLExtension class that is * used to facilitate libSBML plug-ins in the implementation of an * SBMLLevel&nbsp;3 package. * * @class DistribPkgNamespaces * @sbmlbrief{distrib} SBMLNamespaces extension. * * @htmlinclude not-sbml-warning.html */ #ifndef DistribExtension_H__ #define DistribExtension_H__ #include <sbml/common/extern.h> #include <sbml/SBMLTypeCodes.h> #ifdef __cplusplus #include <sbml/extension/SBMLExtension.h> #include <sbml/extension/SBMLExtensionNamespaces.h> #include <sbml/extension/SBMLExtensionRegister.h> #ifndef DISTRIB_CREATE_NS #define DISTRIB_CREATE_NS(variable, sbmlns)\ EXTENSION_CREATE_NS(DistribPkgNamespaces, variable, sbmlns); #endif #include <vector> LIBSBML_CPP_NAMESPACE_BEGIN class LIBSBML_EXTERN DistribExtension : public SBMLExtension { public: /** * Returns the nickname of the SBML Level&nbsp;3 package implemented by this * libSBML extension. * * @return the package nickname, as a string. * * @copydetails doc_note_static_methods */ static const std::string& getPackageName(); /** * Returns the default SBML Level implemented by this libSBML extension. * * @return the SBML Level, as an unsigned integer. * * @copydetails doc_note_static_methods */ static unsigned int getDefaultLevel(); /** * Returns the default SBML Version implemented by this libSBML extension. * * @return the Version within the default SBML Level, as an unsigned integer. * * @copydetails doc_note_static_methods */ static unsigned int getDefaultVersion(); /** * Returns the default version of the SBML Level&nbsp;3 package implemented * by this libSBML extension. * * @return the default version number of the SBML Level&nbsp;3 package * definition, as an unsigned integer. * * @copydetails doc_note_static_methods */ static unsigned int getDefaultPackageVersion(); /** * Returns the XML namespace URI of the SBML Level&nbsp;3 package implemented * by this libSBML extension. * * @return the XML namespace, as a string. * * @copydetails doc_note_static_methods */ static const std::string& getXmlnsL3V1V1(); /** * Creates a new DistribExtension instance. */ DistribExtension(); /** * Copy constructor for DistribExtension. * * @param orig the DistribExtension instance to copy. */ DistribExtension(const DistribExtension& orig); /** * Assignment operator for DistribExtension. * * @param rhs the DistribExtension object whose values are to be used as the * basis of the assignment. */ DistribExtension& operator=(const DistribExtension& rhs); /** * Creates and returns a deep copy of this DistribExtension object. * * @return a (deep) copy of this DistribExtension object. */ virtual DistribExtension* clone() const; /** * Destructor for DistribExtension. */ virtual ~DistribExtension(); /** * Returns the name of this SBML Level&nbsp;3 package ("distrib"). * * @return a string representing the name of this package ("distrib"). */ virtual const std::string& getName() const; /** * Returns a string representing the SBML XML namespace of this SBML * Level&nbsp;3 package. * * @param sbmlLevel the level of SBML. * * @param sbmlVersion the version of SBML. * * @param pkgVersion the version of this package. * * @return a string representing the name of this package ("distrib"). * * The namespace URI constructed by this method corresponds to the * combination of the Level and Version of SBML, and the Version of the SBML * Level&nbsp;3 package. (At the time of this writing, the only SBML Level * that supports packages is Level&nbsp;3, so the value of @p sbmlLevel is * necessarily always <code>3</code>.) */ virtual const std::string& getURI(unsigned int sbmlLevel, unsigned int sbmlVersion, unsigned int pkgVersion) const; /** * Returns the SBML Level for the given URI of this package. * * @param uri the string of the URI that represents one of the versions of * the "distrib" package. * * @return the SBML Level for the given URI of this package, or @c 0 if the * given URI is invalid, or for a different package. */ virtual unsigned int getLevel(const std::string& uri) const; /** * Returns the Version within the SBML Level for the given URI of this * package. * * @param uri the string of the URI that represents one of the versions of * the "distrib" package. * * @return the SBML Version within the SBML Level for the given URI of this * package, or @c 0 if the given URI is invalid, or for a different package. */ virtual unsigned int getVersion(const std::string& uri) const; /** * Returns the SBML Level&nbsp;3 package version for the given URI of this * package. * * @param uri the string of the URI that represents one of the versions of * the "distrib" package. * * @return the version of the SBML Level&nbsp;3 package for the given URI of * this package, or @c 0 if the given URI is invalid, or for a different * package. */ virtual unsigned int getPackageVersion(const std::string& uri) const; /** * Returns a DistribPkgNamespaces object. * * @param uri the string of the URI that represents one of the versions of * the "distrib" package. * * @return DistribPkgNamespaces object corresponding to the given URI of this * package, or @c NULL if the given URI is not defined in the "distrib" * package. */ virtual SBMLNamespaces* getSBMLExtensionNamespaces(const std::string& uri) const; /** * Takes a type code of the &ldquo;distrib&rdquo; package and returns a * string describing the code. * * @param typeCode a libSBML type code defined by the libSBML extension * implementing support for the SBML Level&nbsp;3 &ldquo;distrib&rdquo; * package. * * @return a text string representing the type code given by @p typeCode. If * the type code is unrecognized for this implementation of the libSBML * &ldquo;distrib&rdquo; package, the string returned will be <code>"(Unknown * SBML Distrib Type)"</code>. */ virtual const char* getStringFromTypeCode(int typeCode) const; /** @cond doxygenLibsbmlInternal */ /** * Returns the entry in the error table at this index. * * @param index an unsigned integer representing the index of the error. * * @return packageErrorTableEntry object in the DistribSBMLErrorTable. */ virtual packageErrorTableEntry getErrorTable(unsigned int index) const; /** @endcond */ /** @cond doxygenLibsbmlInternal */ /** * Return the index in the error table with the given errorId. * * @param errorId an unsigned integer representing the errorId of the error. * * @return unsigned int representing the index in the DistribSBMLErrorTable * corresponding to the errorId given. */ virtual unsigned int getErrorTableIndex(unsigned int errorId) const; /** @endcond */ /** @cond doxygenLibsbmlInternal */ /** * Returns the offset for the errorId range for the "distrib" package. * * @return unsigned int representing the offset for errors in the * DistribSBMLErrorTable. */ virtual unsigned int getErrorIdOffset() const; /** @endcond */ /** @cond doxygenLibsbmlInternal */ /** * Initializes distrib extension by creating an object of this class with the * required SBasePlugin derived objects and registering the object to the * SBMLExtensionRegistry class * * This function is automatically invoked when creatingthe following global * object in DistribExtension.cpp * * static SBMLExtensionRegister<DistribExtension> distribExtensionRegistry; */ static void init(); /** @endcond */ }; /** * * Required typedef definitions * * DistribPkgNamespace is derived from SBMLNamespaces class and used when * creating an object of SBase derived classes defined in the distrib package * * SBMLExtensionNamespaces<DistribExtension> must be instantiated in * DistribExtension.cpp for DLL * */ typedef SBMLExtensionNamespaces<DistribExtension> DistribPkgNamespaces; LIBSBML_CPP_NAMESPACE_END #endif /* __cplusplus */ LIBSBML_CPP_NAMESPACE_BEGIN /** * @enum SBMLDistribTypeCode_t * @brief SBMLDistribTypeCode_t Enumeration of possible types in the libSBML * &ldquo;distrib&rdquo; package implementation. * * @copydetails doc_what_are_typecodes * * @copydetails doc_additional_typecode_details */ typedef enum { SBML_DISTRIB_UNCERTPARAMETER = 1500 /*!<UncertParameter */ , SBML_DISTRIB_UNCERTAINTY = 1501 /*!<Uncertainty */ , SBML_DISTRIB_UNCERTSTATISTICSPAN = 1502 /*!<UncertSpan */ , SBML_DISTRIB_DISTRIBBASE = 1503 /*!<DistribBase */ } SBMLDistribTypeCode_t; /** * @enum UncertType_t * @brief Enumeration of values permitted as the value of the "uncerttype" * attribute on Distrib objects. * * @if conly * @see Distrib_getUncerttype() * @see Distrib_setUncerttype() * @elseif java * @see Distrib::getUncerttype() * @see Distrib::setUncerttype(long) * @else * @see Distrib::getUncerttype() * @see Distrib::setUncerttype() * @endif */ typedef enum { DISTRIB_UNCERTTYPE_DISTRIBUTION /*!< The distrib uncerttype is @c "distribution". */ , DISTRIB_UNCERTTYPE_EXTERNALPARAMETER /*!< The distrib uncerttype is @c "externalParameter". */ , DISTRIB_UNCERTTYPE_COEFFIENTOFVARIATION /*!< The distrib uncerttype is @c "coeffientOfVariation". */ , DISTRIB_UNCERTTYPE_KURTOSIS /*!< The distrib uncerttype is @c "kurtosis". */ , DISTRIB_UNCERTTYPE_MEAN /*!< The distrib uncerttype is @c "mean". */ , DISTRIB_UNCERTTYPE_MEDIAN /*!< The distrib uncerttype is @c "median". */ , DISTRIB_UNCERTTYPE_MODE /*!< The distrib uncerttype is @c "mode". */ , DISTRIB_UNCERTTYPE_SAMPLESIZE /*!< The distrib uncerttype is @c "sampleSize". */ , DISTRIB_UNCERTTYPE_SKEWNESS /*!< The distrib uncerttype is @c "skewness". */ , DISTRIB_UNCERTTYPE_STANDARDDEVIATION /*!< The distrib uncerttype is @c "standardDeviation". */ , DISTRIB_UNCERTTYPE_STANDARDERROR /*!< The distrib uncerttype is @c "standardError". */ , DISTRIB_UNCERTTYPE_VARIANCE /*!< The distrib uncerttype is @c "variance". */ , DISTRIB_UNCERTTYPE_CONFIDENCEINTERVAL /*!< The distrib uncerttype is @c "confidenceInterval". */ , DISTRIB_UNCERTTYPE_CREDIBLEINTERVAL /*!< The distrib uncerttype is @c "credibleInterval". */ , DISTRIB_UNCERTTYPE_INTERQUARTILERANGE /*!< The distrib uncerttype is @c "interquartileRange". */ , DISTRIB_UNCERTTYPE_RANGE /*!< The distrib uncerttype is @c "range". */ , DISTRIB_UNCERTTYPE_INVALID /*!< Invalid UncertType value. */ } UncertType_t; /** * Returns the string version of the provided #UncertType_t enumeration. * * @param ut the #UncertType_t enumeration value to convert. * * @return A string corresponding to the given type: * "distribution", * "externalParameter", * "coeffientOfVariation", * "kurtosis", * "mean", * "median", * "mode", * "sampleSize", * "skewness", * "standardDeviation", * "standardError", * "variance", * "confidenceInterval", * "credibleInterval", * "interquartileRange", * "range", * "invalid UncertType value", * or @c NULL if the value is @sbmlconstant{DISTRIB_UNCERTTYPE_INVALID, * UncertType_t} or another invalid enumeration value. * * @copydetails doc_returned_unowned_char * * @if conly * @memberof Distrib_t * @endif */ LIBSBML_EXTERN const char* UncertType_toString(UncertType_t ut); /** * Returns the #UncertType_t enumeration corresponding to the given string or * @sbmlconstant{DISTRIB_UNCERTTYPE_INVALID, UncertType_t} if there is no such * match. * * @param code the string to convert to a #UncertType_t. * * @return the corresponding #UncertType_t or * @sbmlconstant{DISTRIB_UNCERTTYPE_INVALID, UncertType_t} if no match is * found. * * @note The matching is case-sensitive: "distribution" will return * @sbmlconstant{DISTRIB_UNCERTTYPE_DISTRIBUTION, UncertType_t}, but * "Distribution" will return @sbmlconstant{DISTRIB_UNCERTTYPE_INVALID, * UncertType_t}. * * @if conly * @memberof Distrib_t * @endif */ LIBSBML_EXTERN UncertType_t UncertType_fromString(const char* code); /** * Predicate returning @c 1 (true) or @c 0 (false) depending on whether the * given #UncertType_t is valid. * * @param ut the #UncertType_t enumeration to query. * * @return @c 1 (true) if the #UncertType_t is * @sbmlconstant{DISTRIB_UNCERTTYPE_DISTRIBUTION, UncertType_t}, * @sbmlconstant{DISTRIB_UNCERTTYPE_EXTERNALPARAMETER, UncertType_t}, * @sbmlconstant{DISTRIB_UNCERTTYPE_COEFFIENTOFVARIATION, UncertType_t}, * @sbmlconstant{DISTRIB_UNCERTTYPE_KURTOSIS, UncertType_t}, * @sbmlconstant{DISTRIB_UNCERTTYPE_MEAN, UncertType_t}, * @sbmlconstant{DISTRIB_UNCERTTYPE_MEDIAN, UncertType_t}, * @sbmlconstant{DISTRIB_UNCERTTYPE_MODE, UncertType_t}, * @sbmlconstant{DISTRIB_UNCERTTYPE_SAMPLESIZE, UncertType_t}, * @sbmlconstant{DISTRIB_UNCERTTYPE_SKEWNESS, UncertType_t}, * @sbmlconstant{DISTRIB_UNCERTTYPE_STANDARDDEVIATION, UncertType_t}, * @sbmlconstant{DISTRIB_UNCERTTYPE_STANDARDERROR, UncertType_t}, * @sbmlconstant{DISTRIB_UNCERTTYPE_VARIANCE, UncertType_t}, * @sbmlconstant{DISTRIB_UNCERTTYPE_CONFIDENCEINTERVAL, UncertType_t}, * @sbmlconstant{DISTRIB_UNCERTTYPE_CREDIBLEINTERVAL, UncertType_t}, * @sbmlconstant{DISTRIB_UNCERTTYPE_INTERQUARTILERANGE, UncertType_t}, or * @sbmlconstant{DISTRIB_UNCERTTYPE_RANGE, UncertType_t}; * @c 0 (false) otherwise (including @sbmlconstant{DISTRIB_UNCERTTYPE_INVALID, * UncertType_t}). * * @if conly * @memberof Distrib_t * @endif */ LIBSBML_EXTERN int UncertType_isValid(UncertType_t ut); /** * Predicate returning @c 1 (true) or @c 0 (false) depending on whether the * given string is a valid #UncertType_t. * * @param code the string to query. * * @return @c 1 (true) if the string is * "distribution", * "externalParameter", * "coeffientOfVariation", * "kurtosis", * "mean", * "median", * "mode", * "sampleSize", * "skewness", * "standardDeviation", * "standardError", * "variance", * "confidenceInterval", * "credibleInterval", * "interquartileRange", * "range", or * "invalid UncertType value"; * @c 0 (false) otherwise. * * @note The matching is case-sensitive: "distribution" will return @c 1 * (true), but "Distribution" will return @c 0 (false). * * @if conly * @memberof Distrib_t * @endif */ LIBSBML_EXTERN int UncertType_isValidString(const char* code); LIBSBML_CPP_NAMESPACE_END #endif /* !DistribExtension_H__ */
29.812937
108
0.703982
[ "object", "vector" ]
b9ba6a95fe52f0fa505225dfca780a43d5a6728d
8,275
h
C
cpp/runtimes/include/joynr/JoynrClusterControllerRuntime.h
naeramarth7/joynr
3c378d3447cf83678d26ef0def44a29fe1270193
[ "Apache-2.0" ]
null
null
null
cpp/runtimes/include/joynr/JoynrClusterControllerRuntime.h
naeramarth7/joynr
3c378d3447cf83678d26ef0def44a29fe1270193
[ "Apache-2.0" ]
null
null
null
cpp/runtimes/include/joynr/JoynrClusterControllerRuntime.h
naeramarth7/joynr
3c378d3447cf83678d26ef0def44a29fe1270193
[ "Apache-2.0" ]
null
null
null
/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * 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. * #L% */ #ifndef JOYNRCLUSTERCONTROLLERRUNTIME_H #define JOYNRCLUSTERCONTROLLERRUNTIME_H #include <memory> #include <string> #include <vector> #include "joynr/IClusterControllerSignalHandler.h" #include "joynr/ClusterControllerSettings.h" #include "joynr/IKeychain.h" #include "joynr/JoynrClusterControllerRuntimeExport.h" #include "joynr/JoynrRuntime.h" #include "joynr/LibjoynrSettings.h" #include "joynr/Logger.h" #include "joynr/PrivateCopyAssign.h" #include "joynr/Semaphore.h" #include "joynr/WebSocketSettings.h" class JoynrClusterControllerRuntimeTest; namespace joynr { class AccessController; class AccessControlListEditor; class LocalCapabilitiesDirectory; class ILocalChannelUrlDirectory; class ITransportMessageReceiver; class ITransportMessageSender; class SubscriptionManager; class JoynrMessagingConnectorFactory; class IDispatcher; class InProcessMessagingSkeleton; class HttpMessagingSkeleton; class IMqttMessagingSkeleton; class MqttReceiver; class MulticastMessagingSkeletonDirectory; class IPlatformSecurityManager; class Settings; class IMessageRouter; class IMessageSender; class IWebsocketCcMessagingSkeleton; class CcMessageRouter; class WebSocketMessagingStubFactory; class MosquittoConnection; class LocalDomainAccessController; namespace infrastructure { class ChannelUrlDirectoryProxy; class GlobalDomainAccessControllerProxy; } // namespace infrastructure class JOYNRCLUSTERCONTROLLERRUNTIME_EXPORT JoynrClusterControllerRuntime : public JoynrRuntimeImpl, public IClusterControllerSignalHandler { public: using MqttMessagingSkeletonFactory = std::function< std::shared_ptr<IMqttMessagingSkeleton>(std::weak_ptr<IMessageRouter> messageRouter, std::shared_ptr<MqttReceiver> mqttReceiver, const std::string& multicastTopicPrefix, std::uint64_t ttlUplift)>; JoynrClusterControllerRuntime( std::unique_ptr<Settings> settings, std::shared_ptr<IKeychain> keyChain = nullptr, MqttMessagingSkeletonFactory mqttMessagingSkeletonFactory = nullptr, std::shared_ptr<ITransportMessageReceiver> httpMessageReceiver = nullptr, std::shared_ptr<ITransportMessageSender> httpMessageSender = nullptr, std::shared_ptr<ITransportMessageReceiver> mqttMessageReceiver = nullptr, std::shared_ptr<ITransportMessageSender> mqttMessageSender = nullptr); static std::shared_ptr<JoynrClusterControllerRuntime> create( std::size_t argc, char* argv[], std::shared_ptr<IKeychain> keyChain = nullptr, MqttMessagingSkeletonFactory mqttMessagingSkeletonFactory = nullptr); static std::shared_ptr<JoynrClusterControllerRuntime> create( std::unique_ptr<Settings> settings, const std::string& discoveryEntriesFile = "", std::shared_ptr<IKeychain> keyChain = nullptr, MqttMessagingSkeletonFactory mqttMessagingSkeletonFactory = nullptr); ~JoynrClusterControllerRuntime() override; void start(); void stop(bool deleteChannel = false); void shutdown() final; void runForever(); // Implement IClusterControllerSignalHandler void startExternalCommunication() final; void stopExternalCommunication() final; void shutdownClusterController() final; // Functions used by integration tests void deleteChannel(); void init(); /* * Inject predefined capabilities stored in a JSON file. */ void injectGlobalCapabilitiesFromFile(const std::string& fileName); protected: void importMessageRouterFromFile(); void importPersistedLocalCapabilitiesDirectory(); std::map<std::string, joynr::types::DiscoveryEntryWithMetaInfo> getProvisionedEntries() const final; std::shared_ptr<IMessageRouter> getMessageRouter() final; std::shared_ptr<IDispatcher> joynrDispatcher; std::shared_ptr<SubscriptionManager> subscriptionManager; std::shared_ptr<IMessageSender> messageSender; std::shared_ptr<LocalCapabilitiesDirectory> localCapabilitiesDirectory; std::shared_ptr<InProcessMessagingSkeleton> libJoynrMessagingSkeleton; std::shared_ptr<ITransportMessageReceiver> httpMessageReceiver; std::shared_ptr<ITransportMessageSender> httpMessageSender; std::shared_ptr<HttpMessagingSkeleton> httpMessagingSkeleton; std::shared_ptr<MosquittoConnection> mosquittoConnection; std::shared_ptr<ITransportMessageReceiver> mqttMessageReceiver; std::shared_ptr<ITransportMessageSender> mqttMessageSender; MqttMessagingSkeletonFactory mqttMessagingSkeletonFactory; std::shared_ptr<IMqttMessagingSkeleton> mqttMessagingSkeleton; std::vector<std::shared_ptr<IDispatcher>> dispatcherList; std::unique_ptr<Settings> settings; LibjoynrSettings libjoynrSettings; std::shared_ptr<LocalDomainAccessController> localDomainAccessController; ClusterControllerSettings clusterControllerSettings; WebSocketSettings wsSettings; std::shared_ptr<IWebsocketCcMessagingSkeleton> wsCcMessagingSkeleton; std::shared_ptr<IWebsocketCcMessagingSkeleton> wsTLSCcMessagingSkeleton; bool httpMessagingIsRunning; bool mqttMessagingIsRunning; bool doMqttMessaging; bool doHttpMessaging; std::shared_ptr<WebSocketMessagingStubFactory> wsMessagingStubFactory; ADD_LOGGER(JoynrClusterControllerRuntime) private: template <typename T> std::string registerInternalSystemServiceProvider(std::shared_ptr<T> provider, const std::string& participantId) { const std::string domain(systemServicesSettings.getDomain()); const std::string interfaceName(T::INTERFACE_NAME()); participantIdStorage->setProviderParticipantId(domain, interfaceName, participantId); joynr::types::ProviderQos systemProviderQos; systemProviderQos.setCustomParameters(std::vector<joynr::types::CustomParameter>()); systemProviderQos.setPriority(1); systemProviderQos.setScope(joynr::types::ProviderScope::LOCAL); systemProviderQos.setSupportsOnChangeSubscriptions(false); return registerProvider(domain, provider, systemProviderQos); } void registerInternalSystemServiceProviders(); void unregisterInternalSystemServiceProviders(); void unregisterInternalSystemServiceProvider(const std::string& participantId); void startLocalCommunication(); std::shared_ptr<joynr::infrastructure::GlobalDomainAccessControllerProxy> createGlobalDomainAccessControllerProxy(); DISALLOW_COPY_AND_ASSIGN(JoynrClusterControllerRuntime); std::shared_ptr<MulticastMessagingSkeletonDirectory> multicastMessagingSkeletonDirectory; std::shared_ptr<CcMessageRouter> ccMessageRouter; std::shared_ptr<AccessControlListEditor> aclEditor; void enableAccessController( const std::map<std::string, types::DiscoveryEntryWithMetaInfo>& provisionedEntries); friend class ::JoynrClusterControllerRuntimeTest; Semaphore lifetimeSemaphore; std::shared_ptr<joynr::AccessController> accessController; std::string routingProviderParticipantId; std::string discoveryProviderParticipantId; std::string providerReregistrationControllerParticipantId; std::string messageNotificationProviderParticipantId; std::string accessControlListEditorProviderParticipantId; bool isShuttingDown; }; } // namespace joynr #endif // JOYNRCLUSTERCONTROLLERRUNTIME_H
37.274775
96
0.759879
[ "vector" ]
b9c56a609e1ad724b01bebbca43f134d7fded031
5,931
c
C
src/sys/kernel/cpu.c
brunexgeek/machina-x86
5894ba0bd2815ea873ca2be170bc98cf4b0d0bf5
[ "Spencer-94" ]
2
2016-10-29T12:11:38.000Z
2017-09-26T07:26:49.000Z
src/sys/kernel/cpu.c
brunexgeek/machina-x86
5894ba0bd2815ea873ca2be170bc98cf4b0d0bf5
[ "Spencer-94" ]
null
null
null
src/sys/kernel/cpu.c
brunexgeek/machina-x86
5894ba0bd2815ea873ca2be170bc98cf4b0d0bf5
[ "Spencer-94" ]
null
null
null
// // cpu.c // // CPU detection and information. // // Copyright (C) 2013-2014 Bruno Ribeiro. // Copyright (C) 2002 Michael Ringgaard. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the project 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. // #include <os/krnl.h> #include <os/cpu.h> #include <string.h> /** * Global CPU information. */ struct cpu_info cpuInfo; struct cpu_vendor { const char *vendorId; int vendor; const char *name; }; static const struct cpu_vendor CPU_VENDORS[] = { { "GenuineIntel", CPU_VENDOR_INTEL, "Intel" }, { "AuthenticAMD", CPU_VENDOR_AMD, "AMD" }, { "CyrixInstead", CPU_VENDOR_CYRIX, "Cyrix" }, { "VIA VIA VIA ", CPU_VENDOR_VIA, "Via" }, { "CentaurHauls", CPU_VENDOR_CENTAUR, "Centaur" }, { "KVMKVMKVMKVM", CPU_VENDOR_KVM, "KVM" }, { "Microsoft Hv", CPU_VENDOR_MS, "MS Hyper-V" }, { "VMwareVMware", CPU_VENDOR_VMWARE, "VMware" }, { "NexGenDriven", CPU_VENDOR_NEXGEN, "NexGen" }, { "GenuineTMx86", CPU_VENDOR_TRANSMETA, "Transmeta" }, { "TransmetaCPU", CPU_VENDOR_TRANSMETA, "Transmeta" }, { NULL, CPU_VENDOR_UNKNOWN, "Generic" } }; // TODO: became "naked" function unsigned long kcpu_get_eflags() { __asm__ ( "pushfd;" "pop eax;" ); } void kcpu_initialize() { unsigned long val[4]; const struct cpu_vendor *current; // check if CPUID is not supported if (!cpuid_is_supported()) { // Note: we can not call 'panic' here because 'stop' try to stop threads! kprintf("panic: CPU too old! This OS needs a CPU with support for CUPID instruction."); kmach_cli(); kmach_halt(); } // get vendor ID kmach_cpuid(0x00000000, val); cpuInfo.level = val[0]; memcpy(cpuInfo.vendorId + 0, val + 1, 4); memcpy(cpuInfo.vendorId + 4, val + 3, 4); memcpy(cpuInfo.vendorId + 8, val + 2, 4); // retrieve the vendor name and code current = CPU_VENDORS; while (1) { if (current->vendorId != NULL || strcmp(cpuInfo.vendorId, current->vendorId) == 0) { cpuInfo.vendor = current->vendor; memset(cpuInfo.vendorName, 0, CPU_VENDOR_NAME_SIZE); strncpy(cpuInfo.vendorName, current->name, CPU_VENDOR_NAME_SIZE-1); } if (current->vendorId != NULL) break; current = current + 1; } // get family, model, stepping and features if (cpuInfo.level >= 0x00000001) { kmach_cpuid(0x00000001, val); cpuInfo.family = (val[0] >> 8) & 0x0F; cpuInfo.model = (val[0] >> 4) & 0x0F; cpuInfo.stepping = val[0] & 0x0F; cpuInfo.features = val[3]; } // get brand string kmach_cpuid(0x80000000, val); if (val[0] >= 0x80000004) { char model[64]; char *p, *q; int space; memset(model, 0, 64); kmach_cpuid(0x80000002, (unsigned long *) model); kmach_cpuid(0x80000003, (unsigned long *) (model + 16)); kmach_cpuid(0x80000004, (unsigned long *) (model + 32)); // trim brand string p = model; q = cpuInfo.modelId; space = 0; while (*p == ' ') p++; while (*p) { if (*p == ' ') { space = 1; } else { if (space) *q++ = ' '; space = 0; *q++ = *p; } p++; } *q = 0; } else { // Note: we can not call 'panic' here because 'stop' try to stop threads! kprintf("panic: CPU too old! This OS needs CPUID instruction with support for processor brand."); kmach_cli(); kmach_halt(); } kprintf(KERN_INFO "cpu: %s family %d model %d stepping %d\n", cpuInfo.modelId, cpuInfo.family, cpuInfo.model, cpuInfo.stepping); } int proc_cpuinfo( struct proc_file *output, void *arg ) { pprintf(output, "%s family %d model %d stepping %d\n", cpuInfo.modelId, cpuInfo.family, cpuInfo.model, cpuInfo.stepping); return 0; } int kcpu_get_info(struct cpu_info *info) { info->vendor = cpuInfo.vendor; info->family = cpuInfo.family; info->model = cpuInfo.model; info->stepping = cpuInfo.stepping; info->mhz = cpuInfo.mhz; info->features = cpuInfo.features; info->pageSize = PAGESIZE; strcpy(info->vendorId, cpuInfo.vendorId); strcpy(info->modelId, cpuInfo.modelId); return 0; }
30.106599
132
0.620975
[ "model" ]
b9c7f2a253929cb1bdfbc5c34c162a6b820c80e9
20,989
c
C
src/scheduler.c
AndreLaranjeira/ProgramScheduler
7ae7b000c9ef80290f263bb0880b5cc721180b50
[ "MIT" ]
null
null
null
src/scheduler.c
AndreLaranjeira/ProgramScheduler
7ae7b000c9ef80290f263bb0880b5cc721180b50
[ "MIT" ]
27
2019-04-29T14:06:16.000Z
2019-06-03T02:37:37.000Z
src/scheduler.c
AndreLaranjeira/ProgramScheduler
7ae7b000c9ef80290f263bb0880b5cc721180b50
[ "MIT" ]
null
null
null
// Program scheduler - Scheduler process. /* Code authors: * André Filipe Caldas Laranjeira - 16/0023777 * Hugo Nascimento Fonseca - 16/0008166 * José Luiz Gomes Nogueira - 16/0032458 * Victor André Gris Costa - 16/0019311 */ // Compiler includes: #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <float.h> #include <signal.h> #include <string.h> #include <sys/ipc.h> #include <sys/msg.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> // Project includes: #include "console.h" #include "data_structures.h" // Macros: #define CONTEXT "Scheduler" #define NODE_PROGRAM "node" // Type definitions: typedef struct topology_name_function{ char* name; int (*init)(); }topology; // Function headers: boolean is_a_job_ready(); boolean is_no_job_executing(); int init_hypercube_topology(); int init_torus_topology(); int init_tree_topology(); msg_kind get_message(int msqid, msg *message_received); return_codes add_table(msg_data received); return_codes execute_next_job(int msqid); return_codes print_metrics(scheduler_table* table); return_codes save_metrics(msg_data received); return_codes treat_message(msg received, msg_kind kind); void destroy_msg_queues(); void fork_nodes(char *const [N_MAX_NODES][N_MAX_PARAMS], int); void initialize_msg_queues(); void panic_function(); void set_panic_flag(); void shutdown(); // Global variables: pid_t nodes_pid[N_MAX_NODES]; int msqid_top_level, msqid_nodes; int panic_flag = 0; boolean received_shutdown = False; scheduler_table *process_table; int32_t actual_job = -1, last_node_job = 0; int occupied_nodes = 0, quant_nodes; // Signal usage: // SIGABRT: Sets a panic flag to 1. The panic_function will soon be called. // SIGINT: Terminates the program in an orderly way. Resources are deallocated. // SIGTERM: Die without asking any further questions. // Main function: int main(int argc, char **argv){ // Variable declaration: msg execute_info, shutdown_info, received; msg_kind kind; return_codes returned_code; int status; topology topology_options[] = {{"hypercube", &init_hypercube_topology}, {"torus", &init_torus_topology}, {"tree", &init_tree_topology}}; topology selected_topology = {"", NULL}; char previous_topologies[80] = ""; // Signal assignment: signal(SIGABRT, set_panic_flag); // In case something goes wrong. signal(SIGINT, shutdown); // Allows CTRL-C to shutdown! // Arguments number handling: if(argc != 2){ error(CONTEXT, "Wrong arguments number. \nUsage: ./scheduler <topologia>\n"); exit(COUNT_ARGS); } // Topology argument handling: for(int i=0; i < (sizeof(topology_options)/sizeof(topology)); i++){ strcat(previous_topologies, topology_options[i].name); strcat(previous_topologies, "\n"); if(strcmp(topology_options[i].name, argv[1]) == 0){ selected_topology = topology_options[i]; break; } } if(selected_topology.init != NULL){ success(CONTEXT, "Starting scheduler with %s topology...\n", selected_topology.name); }else{ error(CONTEXT, "Wrong topology argument. Choose one of that topologies: \n%s", previous_topologies); exit(INVALID_ARG); } // Create messages queues needed for the application: initialize_msg_queues(); // First things first. The shutdown process needs to know this process' PID // to able to send a SIGTERM. So we will write a message informing our PID. // Write the message adequately: shutdown_info.recipient = QUEUE_ID_SHUTDOWN; shutdown_info.data.type = KIND_PID; shutdown_info.data.msg_body.data_pid.sender_id = QUEUE_ID_SCHEDULER; shutdown_info.data.msg_body.data_pid.pid = getpid(); // Send the message: if(msgsnd(msqid_top_level, &shutdown_info, sizeof(shutdown_info.data), 0) == -1) { error(CONTEXT, "A message could not be sent! Please check your message queues.\n"); exit(IPC_MSG_QUEUE_SEND); } // We also need to send a message to the execute process to indicate the job // number. execute_info.recipient = QUEUE_ID_EXECUTE; execute_info.data.type = KIND_JOB; execute_info.data.msg_body.data_job.job_num = FIRST_JOB_NUM; // Send the message: if(msgsnd(msqid_top_level, &execute_info, sizeof(execute_info.data), 0) == -1) { error(CONTEXT, "A message could not be sent! Please check your message queues.\n"); exit(IPC_MSG_QUEUE_SEND); } // Call the topology initialization selected_topology.init(); // Initialize process table for scaling if ((returned_code=create_table(&process_table)) != SUCCESS) { error(CONTEXT, "Could not create process table.\n"); exit(returned_code); } // Main loop while(!received_shutdown || !is_no_job_executing()) { // Scales jobs if (!received_shutdown && is_a_job_ready() && is_no_job_executing()) { returned_code = execute_next_job(msqid_nodes); if ( returned_code != SUCCESS ) { error(CONTEXT, "Couldn't execute a job when it was supposed to be possible.\n"); exit(returned_code); } } // Check for messages from exec kind = get_message(msqid_top_level, &received); if (kind != KIND_ERROR){ returned_code = treat_message(received, kind); if ( returned_code != SUCCESS ){ error(CONTEXT, "Couldn't treat a message.\n"); exit(returned_code); } } // Check for messages from node 0 kind = get_message(msqid_nodes, &received); if (kind != KIND_ERROR){ returned_code = treat_message(received, kind); if ( returned_code != SUCCESS ){ error(CONTEXT, "Couldn't treat a message.\n"); exit(returned_code); } } } print_metrics(process_table); // Delete process table if ((returned_code=delete_table(&process_table)) != SUCCESS) { error(CONTEXT, "Could not delete process table.\n"); exit(returned_code); } for(int i=0; i<quant_nodes; i++){ if(nodes_pid[i] !=0){ kill(nodes_pid[i], SIGTERM); wait(&status); } } // Clean up the message queues: destroy_msg_queues(); // Success message: success(CONTEXT, "Scheduler successfully shut down!\n"); return 0; } // Function implementations: boolean is_a_job_ready() { return process_table != NULL && process_table->next != NULL && time(NULL) > process_table->next->start_time; } boolean is_no_job_executing() { return actual_job == -1 && occupied_nodes == 0; } // Topology initialization functions: int init_hypercube_topology(){ int n_nodes = 16; quant_nodes = n_nodes; char *const topology[N_MAX_NODES][N_MAX_PARAMS] = { {NODE_PROGRAM,N0, SCHEDULER, N1,N2,N4,N8, END_PARAMS}, {NODE_PROGRAM,N1, N0,N3,N5,N9, END_PARAMS}, {NODE_PROGRAM,N2, N0,N3,N6,N10, END_PARAMS}, {NODE_PROGRAM,N3, N1,N2,N7,N11, END_PARAMS}, {NODE_PROGRAM,N4, N0,N5,N6,N12, END_PARAMS}, {NODE_PROGRAM,N5, N1,N4,N7,N13, END_PARAMS}, {NODE_PROGRAM,N6, N2,N4,N7,N14, END_PARAMS}, {NODE_PROGRAM,N7, N3,N5,N6,N15, END_PARAMS}, {NODE_PROGRAM,N8, N0,N9,N10,N12, END_PARAMS}, {NODE_PROGRAM,N9, N1,N8,N11,N13, END_PARAMS}, {NODE_PROGRAM,N10, N2,N8,N11,N14, END_PARAMS}, {NODE_PROGRAM,N11, N3,N9,N10,N15, END_PARAMS}, {NODE_PROGRAM,N12, N4,N8,N13,N14, END_PARAMS}, {NODE_PROGRAM,N13, N5,N9,N12,N15, END_PARAMS}, {NODE_PROGRAM,N14, N6,N10,N12,N15, END_PARAMS}, {NODE_PROGRAM,N15, N7,N11,N13,N14, END_PARAMS} //{Program name, id_node, neighbors, end of params} }; // Fork all the nodes fork_nodes(topology, n_nodes); return 0; } int init_torus_topology(){ int n_nodes = 16; quant_nodes = n_nodes; char *const topology[N_MAX_NODES][N_MAX_PARAMS] = { {NODE_PROGRAM,N0, SCHEDULER, N1,N3,N4,N12, END_PARAMS}, {NODE_PROGRAM,N1, N0,N2,N5,N13, END_PARAMS}, {NODE_PROGRAM,N2, N1,N3,N6,N14, END_PARAMS}, {NODE_PROGRAM,N3, N0,N2,N7,N15, END_PARAMS}, {NODE_PROGRAM,N4, N0,N5,N7,N8, END_PARAMS}, {NODE_PROGRAM,N5, N1,N4,N6,N9, END_PARAMS}, {NODE_PROGRAM,N6, N2,N5,N7,N10, END_PARAMS}, {NODE_PROGRAM,N7, N3,N4,N6,N11, END_PARAMS}, {NODE_PROGRAM,N8, N4,N9,N11,N12, END_PARAMS}, {NODE_PROGRAM,N9, N5,N8,N10,N13, END_PARAMS}, {NODE_PROGRAM,N10, N6,N9,N11,N14, END_PARAMS}, {NODE_PROGRAM,N11, N7,N8,N10,N15, END_PARAMS}, {NODE_PROGRAM,N12, N0,N8,N13,N15, END_PARAMS}, {NODE_PROGRAM,N13, N1,N9,N12,N14, END_PARAMS}, {NODE_PROGRAM,N14, N2,N10,N13,N15, END_PARAMS}, {NODE_PROGRAM,N15, N3,N11,N12,N14, END_PARAMS} //{Program name, id_node, neighbors, end of params} }; // Fork all the nodes fork_nodes(topology, n_nodes); return 0; } int init_tree_topology(){ int n_nodes = 15; quant_nodes = n_nodes; char *const topology[N_MAX_NODES][N_MAX_PARAMS] = { {NODE_PROGRAM,N0, SCHEDULER, N1,N2, END_PARAMS}, {NODE_PROGRAM,N1, N0,N3,N4, END_PARAMS}, {NODE_PROGRAM,N2, N0,N5,N6, END_PARAMS}, {NODE_PROGRAM,N3, N1,N7,N8, END_PARAMS}, {NODE_PROGRAM,N4, N1,N9,N10, END_PARAMS}, {NODE_PROGRAM,N5, N2,N11,N12, END_PARAMS}, {NODE_PROGRAM,N6, N2,N13,N14, END_PARAMS}, {NODE_PROGRAM,N7, N3, END_PARAMS}, {NODE_PROGRAM,N8, N3, END_PARAMS}, {NODE_PROGRAM,N9, N4, END_PARAMS}, {NODE_PROGRAM,N10, N4, END_PARAMS}, {NODE_PROGRAM,N11, N5, END_PARAMS}, {NODE_PROGRAM,N12, N5, END_PARAMS}, {NODE_PROGRAM,N13, N6, END_PARAMS}, {NODE_PROGRAM,N14, N6, END_PARAMS}, //{Program name, id_node, neighbors, end of params} }; // Fork all the nodes fork_nodes(topology, n_nodes); return 0; } msg_kind get_message(int msqid, msg *message_received) { if (msgrcv(msqid, message_received, sizeof(message_received->data), QUEUE_ID_SCHEDULER, IPC_NOWAIT) == -1){ return KIND_ERROR; } return message_received->data.type; } return_codes add_table(msg_data received) { msg_data_program extracted = received.msg_body.data_prog; table_item item; int i; item.job = extracted.job; item.argc = extracted.argc; for(i = 0; i < MAX_ARG_NUM; i++){ strcpy(item.argv[i], extracted.argv[i]); } item.arrival_time = time(NULL); item.start_time = time(NULL) + (time_t)extracted.delay; add_table_item(process_table, item); #if DEBUG_LEVEL >= 2 print_table(process_table); #endif return SUCCESS; } return_codes execute_next_job(int msqid) { /* Colocar o job para executar nos nodes */ /* actual_job é -1 para livre e o valor real do job se estiver executando. Para os nodes job terá um índice incremental para a execução que será guardado em node_job. */ msg to_send; int i; #if DEBUG_LEVEL >= 1 printf("\nStarting the next job\n>> Job: %d\n>> File: %s\n", process_table->next->job, process_table->next->argv[0]); #endif /* Gravo valores de controle */ process_table->next->done = True; process_table->next->actual_start_time = time(NULL); process_table->next->node_job = ++last_node_job; actual_job = process_table->next->job; occupied_nodes = quant_nodes; /* Configuro mensagem */ to_send.recipient = QUEUE_ID_NODE(0); to_send.data.type = KIND_PROGRAM; /* Gravo dados principais */ to_send.data.msg_body.data_prog.argc = process_table->next->argc; to_send.data.msg_body.data_prog.job = process_table->next->node_job; to_send.data.msg_body.data_prog.delay = 0; for ( i = 0; i < MAX_ARG_NUM; i++ ) { strcpy(to_send.data.msg_body.data_prog.argv[i], process_table->next->argv[i]); } /* Envio a mensagem para a fila de mensagens de nó */ msgsnd(msqid, &to_send, sizeof(to_send.data), 0); /* Atualizo qual o próximo */ process_table->next = process_table->first; while(process_table->next != NULL && process_table->next->done) { process_table->next = process_table->next->next; } return SUCCESS; } return_codes print_metrics(scheduler_table* table) { int i; table_item *aux; aux = table->first; int node_error; char *some_time; double time_aux, best_node_end_time_seconds; time_t time_t_aux; time_measure best_node_end_time, greatest_node_end_time, smallest_node_start_time; while(aux != NULL){ // Print Job status time_aux = difftime(aux->start_time, aux->arrival_time); printf("Job: %3d | Done?: %s | Delay: %3.0lfs | ", aux->job, (aux->done ? "T":"F"), time_aux); // Gets better time, greatest, smallest and verify if any error occurred at nodes node_error = 0; best_node_end_time_seconds = DBL_MAX; smallest_node_start_time = aux->metrics[0].start_time; greatest_node_end_time = aux->metrics[0].end_time; for (i = 0; i < aux->metrics_idx; i++) { // gets best time time_aux = difftime(mktime(&aux->metrics[i].end_time), mktime(&aux->metrics[i].start_time)); if (time_aux < best_node_end_time_seconds) { best_node_end_time_seconds = time_aux; best_node_end_time = aux->metrics[i].end_time; } // get smallest time time_aux = difftime(mktime(&smallest_node_start_time), mktime(&aux->metrics[i].start_time)); if(time_aux > 0){ smallest_node_start_time = aux->metrics[i].start_time; } // get greatest time time_aux = difftime(mktime(&greatest_node_end_time), mktime(&aux->metrics[i].end_time)); if(time_aux < 0){ greatest_node_end_time = aux->metrics[i].end_time; } // check for errors in node if (aux->metrics[i].return_code != 0) { node_error = WEXITSTATUS(aux->metrics[i].return_code); break; } } if (node_error == 0 && aux->done) { // Calculate and show Turnround Time time_aux = difftime(mktime(&greatest_node_end_time), aux->arrival_time); printf("Turnaround: %3.0lfs | ", time_aux); // Calculate and show Scheduler Time time_aux = difftime(mktime(&greatest_node_end_time), aux->actual_start_time); printf("Scheduler Time: %3.0lfs | ", time_aux); // Show Best Node Time printf("Node Time: %3.0lfs | ", best_node_end_time_seconds); // Show smallest node start Time time_t_aux = mktime(&smallest_node_start_time); some_time = ctime(&time_t_aux); some_time[(int)strlen(some_time)-1] = '\0'; printf("Start Node: %s | ", some_time); // Show greatest node start Time time_t_aux = mktime(&greatest_node_end_time); some_time = ctime(&time_t_aux); some_time[(int)strlen(some_time)-1] = '\0'; printf("End Node: %s | ", some_time); // Show node error printf("Node error: %d | ", node_error); }else{ printf("Turnaround: ---- | " "Scheduler Time: ---- | " "Node Time: ---- | " "Start Node: --- --- -- --:--:-- ---- | " "End Node: --- --- -- --:--:-- ---- | " "Node error: %d | ", node_error); } // Print Job command printf("command: "); for (i = 0; i < aux->argc; i++){ printf("%s ", aux->argv[i]); } printf("\n"); aux = aux->next; } return SUCCESS; } return_codes save_metrics(msg_data received) { table_item *aux; aux = process_table->first; while(aux != NULL && aux->node_job != received.msg_body.data_metrics.job) { aux = aux->next; } if (aux == NULL) { return NO_JOB_ON_TABLE_ERROR; } aux->metrics[aux->metrics_idx++] = received.msg_body.data_metrics; #if DEBUG_LEVEL >= 2 info(CONTEXT, "Recebida métrica do job %d. Faltam %d métricas.\n", actual_job, occupied_nodes-1); #endif if((--occupied_nodes) == 0) { actual_job = -1; } return SUCCESS; } return_codes treat_message(msg received, msg_kind kind) { switch (kind) { case KIND_PROGRAM: return add_table(received.data); case KIND_METRICS: return save_metrics(received.data); case KIND_PID: case KIND_ERROR: case KIND_JOB: return INVALID_ARG; } } void destroy_msg_queues(){ int status1, status2; // Destroy the top level message queue: status1 = msgctl(msqid_top_level, IPC_RMID, NULL); // Destroy the nodes message queue: status2 = msgctl(msqid_nodes, IPC_RMID, NULL); // Now, I'm sure you are wondering: why save the return status into // variables? Can't I just execute these commands inside the if conditional // clause? // // The answer is simple: C implements smart evaluation for the "&&" // and "||" logical operation. That means that if the first destruction // fails inside an "&&" conditional clause, the second destruction command // is NEVER EXECUTED because the condition will always evaluate to 0. // // Hence, these status variables are always needed! You learn something new // everyday. // // TL;DR: DO NOT PUT THOSE STATEMENTS IN A CONDITIONAL CLAUSE!!! if((status1 != -1) && (status2 != -1)){ info(CONTEXT, "Scheduler message queues destroyed with success!\n"); }else{ error(CONTEXT, "An error occurred while trying to destroy a message queue!\n"); exit(IPC_MSG_QUEUE_RMID); } } /** * Create the 'nodes' process 'n_nodes' times * and if something goes wrong at creation sends a SIGABRT * to parent (scheduler) to kill all nodes created * */ void fork_nodes(char *const nodes[N_MAX_NODES][N_MAX_PARAMS], int n_nodes){ // Parent pid pid_t ppid = getpid(); char program_path[128] = "./"; strcat(program_path, NODE_PROGRAM); // Initialize all the pids with 0 for(int i=0; i < N_MAX_NODES; i++) nodes_pid[i]=0; for(int i=0; i<n_nodes; i++){ nodes_pid[i] = fork(); if(nodes_pid[i] == 0){ execvp(program_path, nodes[i]); kill(ppid, SIGABRT); exit(-1); } } if(panic_flag == 1) panic_function(); } void initialize_msg_queues(){ int status1, status2; // Acquire the top level message queue: msqid_top_level = msgget(QUEUE_TOP_LEVEL, IPC_CREAT|0x1FF); // Acquire the nodes message queue: msqid_nodes = msgget(QUEUE_NODES, IPC_CREAT|0x1FF); if((msqid_top_level != -1) && (msqid_nodes != -1)){ info(CONTEXT, "Scheduler message queues created with success!\n"); }else{ error(CONTEXT, "An error occur trying to create a message queue!\n"); // Destroy the top level message queue: status1 = msgctl(msqid_top_level, IPC_RMID, NULL); // Destroy the nodes message queue: status2 = msgctl(msqid_nodes, IPC_RMID, NULL); exit(IPC_MSG_QUEUE_CREAT); } } /** * If something goes wrong at creation of the nodes * this function will kill all created nodes * finalize the queues messages and exit * */ void panic_function(){ int count_killed_nodes = 0; int status; // Kill all created nodes for(int i=0; i<N_MAX_NODES; i++){ if(nodes_pid[i] != 0){ kill(nodes_pid[i], SIGTERM); // Must not be SIGABRT! count_killed_nodes++; } } // wait for killed nodes for(int i=0; i<count_killed_nodes; i++){ wait(&status); } // Clean up the message queues: destroy_msg_queues(); error(CONTEXT, "something went wrong at creation of nodes, please check if 'node' program file are in the same" "place of the scheduler program\n"); exit(EXEC_FAILED); } void set_panic_flag() { panic_flag = 1; } void shutdown() { info(CONTEXT, "Shutdown signal received! Shutting down scheduler...\n"); received_shutdown = True; }
31.467766
123
0.616895
[ "3d" ]
b9c94bea2dc19b8ab71d8d3989eae3f8c8c3962b
511
h
C
include/Game.h
Diesel-Hadez/vforvector
ab0f68d5ac6335e2eadcf2b19106c9506bb01b13
[ "MIT" ]
null
null
null
include/Game.h
Diesel-Hadez/vforvector
ab0f68d5ac6335e2eadcf2b19106c9506bb01b13
[ "MIT" ]
null
null
null
include/Game.h
Diesel-Hadez/vforvector
ab0f68d5ac6335e2eadcf2b19106c9506bb01b13
[ "MIT" ]
null
null
null
#ifndef GAME_H #define GAME_H #include "stdafx.h" #include <vector> #include <memory> class Scene; class Game { public: static GLFWwindow * m_Window; private: Game(); void InitOpenGL(); #ifdef __EMSCRIPTEN__ public: #endif void loop(); public: std::vector<std::unique_ptr<Scene>> m_Scenes; Game(Game const&) = delete; void operator=(Game const&) = delete; static Game& GetInstance() { static Game instance; return instance; } void Run(); ~Game(); }; #endif
15.484848
47
0.649706
[ "vector" ]
b9ce19c5ddac94c61ae52e1adc926594d0738118
3,815
h
C
production_apps/ESPRESO/src/mesh/elements/volume/prisma15.h
readex-eu/readex-apps
38493b11806c306f4e8f1b7b2d97764b45fac8e2
[ "BSD-3-Clause" ]
2
2020-11-25T13:10:11.000Z
2021-03-15T20:26:35.000Z
production_apps/ESPRESO/src/mesh/elements/volume/prisma15.h
readex-eu/readex-apps
38493b11806c306f4e8f1b7b2d97764b45fac8e2
[ "BSD-3-Clause" ]
null
null
null
production_apps/ESPRESO/src/mesh/elements/volume/prisma15.h
readex-eu/readex-apps
38493b11806c306f4e8f1b7b2d97764b45fac8e2
[ "BSD-3-Clause" ]
1
2018-09-30T19:04:38.000Z
2018-09-30T19:04:38.000Z
#ifndef SRC_MESH_ELEMENTS_VOLUME_PRISMA15_H_ #define SRC_MESH_ELEMENTS_VOLUME_PRISMA15_H_ #include "volumeelement.h" #include "../line/line3.h" #include "../plane/square8.h" #include "../plane/triangle6.h" #include "prisma6.h" #define Prisma15NodesCount 15 #define Prisma15EdgeCount 9 #define Prisma15FacesCount 5 #define Prisma15GPCount 9 #define Prisma15CommonNodes 3 #define Prisma15VTKCode 26 namespace espreso { class Prisma15: public VolumeElement { public: static bool match(const eslocal *indices, eslocal n); static void setDOFs( const std::vector<Property> element, const std::vector<Property> face, const std::vector<Property> edge, const std::vector<Property> point, const std::vector<Property> midPoint) { _DOFElement = element; _DOFFace = face; _DOFEdge = edge; _DOFPoint = point; _DOFMidPoint = midPoint; } Prisma15(const eslocal *indices, eslocal n, const eslocal *params); Prisma15(std::ifstream &is); Element* copy() const { return new Prisma15(*this); } eslocal nCommon() const { return Prisma15CommonNodes; } eslocal vtkCode() const { return Prisma15VTKCode; } size_t faces() const { return Prisma15FacesCount; } size_t edges() const { return Prisma15EdgeCount; } size_t nodes() const { return Prisma15NodesCount; } size_t coarseNodes() const { return Prisma6NodesCount; } size_t gaussePoints() const { return Prisma15GPCount; } Element* addFace(const std::vector<eslocal> &nodes); const std::vector<eslocal>& faceNodes(size_t index) const { return Prisma15::_facesNodes[index]; } const std::vector<eslocal>& edgeNodes(size_t index) const { return Prisma15::_edgesNodes[index]; } const std::vector<DenseMatrix>& facedN(size_t index, ElementPointType type = ElementPointType::GAUSSE_POINT) const { return index < 3 ? Square8::_dN : Triangle6::_dN; } const std::vector<DenseMatrix>& faceN(size_t index, ElementPointType type = ElementPointType::GAUSSE_POINT) const { return index < 3 ? Square8::_N : Triangle6::_N; } const std::vector<DenseMatrix>& edgedN(size_t index, ElementPointType type = ElementPointType::GAUSSE_POINT) const { return Line3::_dN; } const std::vector<DenseMatrix>& edgeN(size_t index, ElementPointType type = ElementPointType::GAUSSE_POINT) const { return Line3::_N; } const std::vector<DenseMatrix>& dN(ElementPointType type = ElementPointType::GAUSSE_POINT) const { return Prisma15::_dN; } const std::vector<DenseMatrix>& N(ElementPointType type = ElementPointType::GAUSSE_POINT) const { return Prisma15::_N; } const std::vector<double>& weighFactor(ElementPointType type = ElementPointType::GAUSSE_POINT) const { return Prisma15::_weighFactor; } const std::vector<Property>& elementDOFs() const { return Prisma15::_DOFElement; } const std::vector<Property>& faceDOFs() const { return Prisma15::_DOFFace; } const std::vector<Property>& edgeDOFs() const { return Prisma15::_DOFEdge; } const std::vector<Property>& pointDOFs() const { return Prisma15::_DOFPoint; } const std::vector<Property>& midPointDOFs() const { return Prisma15::_DOFMidPoint; } static std::vector<DenseMatrix> _dN; static std::vector<DenseMatrix> _N; static std::vector<double> _weighFactor; protected: std::vector<eslocal> getNeighbours(size_t nodeIndex) const; eslocal* indices() { return _indices; } const eslocal* indices() const { return _indices; } size_t fillFaces(); size_t fillEdges(); private: eslocal _indices[Prisma15NodesCount]; static std::vector<Property> _DOFElement; static std::vector<Property> _DOFFace; static std::vector<Property> _DOFEdge; static std::vector<Property> _DOFPoint; static std::vector<Property> _DOFMidPoint; static std::vector<std::vector<eslocal> > _facesNodes; static std::vector<std::vector<eslocal> > _edgesNodes; }; } #endif /* SRC_MESH_ELEMENTS_VOLUME_PRISMA15_H_ */
37.772277
169
0.758322
[ "vector" ]
b9d31f503c42b9d7aec2639ac04271120421bbf3
45,841
h
C
deps/include/whisper_session.h
stiartsly/WhisperDemo-Pi
23aef69f5194274828b32e3c1dd560b3bbe80fab
[ "MIT" ]
null
null
null
deps/include/whisper_session.h
stiartsly/WhisperDemo-Pi
23aef69f5194274828b32e3c1dd560b3bbe80fab
[ "MIT" ]
null
null
null
deps/include/whisper_session.h
stiartsly/WhisperDemo-Pi
23aef69f5194274828b32e3c1dd560b3bbe80fab
[ "MIT" ]
null
null
null
#ifndef __WHISPER_SESSION_H__ #define __WHISPER_SESSION_H__ #include <stddef.h> #include <stdbool.h> #include <sys/types.h> #include <whisper.h> #if defined(__APPLE__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdocumentation" #endif #ifdef __cplusplus extern "C" { #endif #define WHISPER_MAX_IP_STRING_LEN 45 #define WHISPER_MAX_USER_DATA_LEN 2048 typedef struct WhisperSession WhisperSession; /** * \~English * Whisper underlying transport types definitions. * * \~Chinese * Whisper传输层协议类型定义 */ typedef enum WhisperTransportType { /** * \~English * ICE protocol. * * \~Chinese * ICE 协议。 */ WhisperTransportType_ICE = 0, /** * \~English * UDP transport protocol. * * \~Chinese * UDP 传输协议。 */ WhisperTransportType_UDP, /** * \~English * TCP transport protocol. * * \~Chinese * TCP 传输协议。 */ WhisperTransportType_TCP } WhisperTransportType; /** * \~English * Whisper stream types definition. * Reference: * https://tools.ietf.org/html/rfc4566#section-5.14 * https://tools.ietf.org/html/rfc4566#section-8 * * \~Chinese * Whisper stream 类型定义。 * 参考如下: * https://tools.ietf.org/html/rfc4566#section-5.14 * https://tools.ietf.org/html/rfc4566#section-8 */ typedef enum WhisperStreamType { /** * \~English * Audio stream. * * \~Chinese * 音频流。 */ WhisperStreamType_audio = 0, /** * \~English * Video stream. * * \~Chinese * 视频流。 */ WhisperStreamType_video, /** * \~English * Text stream. * * \~Chinese * 文本流。 */ WhisperStreamType_text, /** * \~English * Application stream. * * \~Chinese * 应用流。 */ WhisperStreamType_application, /** * \~English * Message stream. * * \~Chinese * 消息流。 */ WhisperStreamType_message } WhisperStreamType; /** * \~English * Whisper ICE transport options. * * \~Chinese * Whisper ICE 传输选项。 */ typedef struct IceTransportOptions { /** * \~English * STUN server host name or IP. * * \~Chinese * STUN服务器的主机或者IP。 */ const char *stun_host; /** * \~English * STUN server port. * * The default port is 3478. * * \~Chinese * STUN服务端口。 * * 默认端口port是3478。 */ const char *stun_port; /** * \~English * TURN server host name or IP. * * \~Chinese * TURN服务器的主机或者IP。 */ const char *turn_host; /** * \~English * TURN server port. * * The default port is 3478. * * \~Chinese * TURN服务端口。 * * 默认端口port是3478。 */ const char *turn_port; /** * \~English * TURN server user name. * * \~Chinese * TURN服务器用户名。 */ const char *turn_username; /** * \~English * TURN server password. * * \~Chinese * TURN服务器密码。 */ const char *turn_password; /** * \~English * TURN server realm. * * \~Chinese * TURN服务器ICE协议中域值 */ const char *turn_realm; } IceTransportOptions; /** * \~English * Whisper UDP transport options. * * \~Chinese * Whisper UDP 传输选项。 */ typedef struct UdpTransportOptions { /** * \~English * UDP server hostname or ip. * * Only valid when using UDP protocol. * * \~Chinese * UDP服务器的主机或者IP。 * * 只在使用UDP协议情况有效 */ const char *udp_host; /** * \~English * UDP server port. * * Only valid when using UDP protocol. * If set to NULL, the server will running on an random available * port. * * \~Chinese * UDP服务的端口。 * * 只在使用UDP协议情况有效。 * 如果设定为NULL,那么UDP server将运行在一个随机的可用端口。 */ const char *udp_port; /** * \~English * UDP server external public address when running behind a NAT, and mapped * to public address. * * Only valid when using UDP protocol behind NAT * and mapped to public address. * * \~Chinese * UDP服务的公网地址,适用于运行在NAT之后并且提供和到公网地址映射的情况。 * * 只在使用UDP协议并且提供了NAT公网地址映射的情况有效 */ const char *udp_external_host; /** * \~English * UDP server external public port when running behind a NAT, and mapped * to public address. * * Only valid when using UDP protocol behind NAT * and mapped to public address * * \~Chinese * UDP服务的公网端口,适用于运行在NAT之后并且提供和到公网地址映射的情况。 * * 只在使用UDP协议并且提供了NAT公网地址映射的情况有效 */ const char *udp_external_port; } UdpTransportOptions; /** * \~English * Whisper UDP transport options. * * \~Chinese * Whisper UDP 传输选项。 */ typedef struct TcpTransportOptions { /** * \~English * TCP server hostname or IP. * * Only valid when using TCP protocol. * * \~Chinese * TCP服务器的主机或者IP。 * * 只在使用TCP协议情况有效 */ const char *tcp_host; /** * \~English * TCP server port. * * Only valid when using TCP protocol. * If set to NULL, the server will running on an random available * port. * * \~Chinese * TCP服务器的端口 * * 只在使用TCP协议情况有效 * 如果设定为NULL,那么TCP server将运行在一个随机的可用端口。 */ const char *tcp_port; /** * \~English * TCP server external public address when running behind a NAT, and mapped * to public address. * * Only valid when using TCP protocol behind NAT and mapped to * public address. * * \~Chinese * TCP服务器的公网地址,适用于运行在NAT之后并且提供和到公网地址映射的情况。 * * 格式如下:server_name_or_ip[:port] * 只在使用TCP协议并且提供了NAT公网地址映射的情况有效 */ const char *tcp_external_host; /** * \~English * TCP server external public port when running behind a NAT, and mapped * to public address. * * Only valid when using TCP protocol behind NAT and mapped to * public address. * * \~Chinese * TCP服务器的公网端口,适用于运行在NAT之后并且提供和到公网地址映射的情况。 * * 只在使用TCP协议并且提供了NAT公网地址映射的情况有效 */ const char *tcp_external_port; } TcpTransportOptions; #define TRANSPORT_SHARED_THREAD 0x01 #define TRANSPORT_STANDALONE_THREAD 0x02 typedef struct WhisperTransportOptions { int thread_model; union { IceTransportOptions ice; UdpTransportOptions udp; TcpTransportOptions tcp; } options; } WhisperTransportOptions; typedef enum WhisperCandidateType { WhisperCandidateType_Host, WhisperCandidateType_ServerReflexive, WhisperCandidateType_PeerReflexive, WhisperCandidateType_Relayed, } WhisperCandidateType; typedef enum WhisperNetworkTopology { WhisperNetworkTopology_LAN, WhisperNetworkTopology_P2P, WhisperNetworkTopology_RELAYED, WhisperNetWorkTopology_CS } WhisperNetworkTopology; typedef struct WhisperAddressInfo { WhisperCandidateType type; char addr[WHISPER_MAX_IP_STRING_LEN + 1]; int port; char related_addr[WHISPER_MAX_IP_STRING_LEN + 1]; int related_port; } WhisperAddressInfo; typedef struct WhisperTransportInfo { WhisperTransportType transport; WhisperNetworkTopology topology; WhisperAddressInfo local; WhisperAddressInfo remote; } WhisperTransportInfo; /* Global session APIs */ /** *\~English * Make initialization on Android platform. * * @return * true if initialization succeeded, or false if not. */ #if defined(__ANDROID__) WHISPER_API bool whisper_session_jni_onload(void *vm, void *reserved); #endif /** * \~English * An application-defined function that handle session requests. * * WhisperSessionRequestCallback is the callback function type. * * @param * whisper [in] A handle to the Whisper node instance. * @param * from [in] The id(userid@nodeid) from who send the message. * @param * sdp [in] The remote users SDP. End the null terminal. * Reference: https://tools.ietf.org/html/rfc4566 * @param * len [in] The length of the SDP. * @param * context [in] The application defined context data. * * \~Chinese * 应用定义用于处理session请求的函数。 * * WhisperSessionRequestCallback是回调函数类型。 * * @param * whisper [输入] 指向Whisper节点对象的句柄。 * @param * from [输入] 消息发送者的id(userid@nodeid) * @param * sdp [输入] 对端用户的SDP,以null结尾。 * 具体参考:https://tools.ietf.org/html/rfc4566 * @param * len [输入] SDP长度。 * @param * context [输入] 应用定义的上下文数据。 */ typedef void WhisperSessionRequestCallback(Whisper *whisper, const char *from, const char *sdp, size_t len, void *context); /** * \~English * Initialize Whisper session extension. * * The application must initialize the session extension before calling * any session API. * * @param * whisper [in] A handle to the Whisper node instance. * @param * callback [in] A pointer to the application-defined function of type * WhisperSessionRequestCallback. * @param * context [in] The application defined context data. * * @return * 0 on success, or -1 if an error occurred. The specific error code * can be retrieved by calling whisper_get_error(). * * \~Chinese * 初始化Whisper session扩展。 * * 应用必须在调用session API前初始化session扩展。 * * @param * whisper [输入] 指向Whisper节点对象的句柄。 * @param * callback [输入] 指向应用定义的WhisperSessionRequestCallback类型函数。 * @param * context [输入] 应用定义的上下文数据。 * * @return * 0表示成功,-1表示失败。具体错误可以调用whisper_get_error()来获得。 */ WHISPER_API int whisper_session_init(Whisper *whisper, WhisperSessionRequestCallback *callback, void *context); /** * \~English * Clean up Whisper session extension. * * The application should call whisper_session_cleanup before quit, * to clean up the resources associated with the extension. * * If the extension is not initialized, this function has no effect. * * @param * whisper [in] A handle to the Whisper node instance. * * \~Chinese * 清除Whisper session扩展。 * * 应用必须在退出前调用whisper_session_cleanup,用于清除和扩展相关的资源。 * * @param * whisper [输入] 指向Whisper节点对象的句柄。 */ WHISPER_API void whisper_session_cleanup(Whisper *whisper); /* Transport APIs */ WHISPER_API int whisper_transport_add(Whisper *whisper, WhisperTransportType transport, WhisperTransportOptions *options); WHISPER_API void whisper_transport_remove(Whisper *whisper, WhisperTransportType transport); /* Session instance APIs */ /** * \~English * Create a new session to a friend. * * The session object represent a conversation handle to a friend. * * @param * whisper [in] A handle to the Whisper node instance. * @param * address [in] The target address. * @param * options [in] A pointer to a valid WhisperSessionOptions structure. * @param * transport [in] The transport protocol to use, only can be TCP, UDP * or ICE exclusively. * * @return * If no error occurs, return the pointer of WhisperSession object. * Otherwise, return NULL, and a specific error code can be * retrieved by calling whisper_get_error(). * * \~Chinese * 创建一个新session * * 一个session实例代表一次和friend的会话句柄。 * * @param * whisper [输入] 指向Whisper节点对象的句柄。 * @param * address [输入] 目标地址。 * @param * options [输入] 指向一个有效WhisperSessionOptions结构的指针。 * @param * transport [输入] 传输协议,目前仅支持ICE,UDP或者TCP。 * * @return * 如果成功,返回WishierSession对象的指针,否则返回NULL。 * 具体错误可以调用whisper_get_error()来获得。 */ WHISPER_API WhisperSession *whisper_session_new(Whisper *whisper, const char *address, WhisperTransportType transport, WhisperTransportOptions *options); /** * \~English * Close a session to friend. All resources include streams, multiplexers * associated with current session will be destroyed. * * @param * session [in] A handle to the Whisper session. * * \~Chinese * 关闭指定session。销毁所有和session有关资源,包括streams和multiplexers。 * * @param * session [输入] 指向WhisperSession的句柄。 */ WHISPER_API void whisper_session_close(WhisperSession *session); /** * \~English * Get the remote peer id (userid or userid@nodeid) of the session. * * @param * session [in] A handle to the Whisper session. * @param * address [out] The buffer that will receive the peer address. * The buffer size should at least * (2 * WHISPER_MAX_ID_LEN + 1) bytes. * @param * len [in] The buffer size of appid. * * @return * The remote peer string address, or NULL if buffer is too small. * * \~Chinese * 获取与指定会话关联的对端标识。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * address [输出] 用来存放会话对端标识的存储空间。 * 存储空间至少要有2*WHISPER_MAX_ID_LEN+1个字节。 * @param * len [输入] peer存储空间的长度。 * * @return * 指向会话对端标识字符串的指针,如果提供的存储空间太小则返回空指针。 */ WHISPER_API char *whisper_session_get_peer(WhisperSession *session, char *address, size_t len); /** * \~English * Set the arbitary user data to be associated with the session. * * @param * session [in] A handle to the Whisper session. * @param * userdata [in] Arbitary user data to be associated with this session. * * \~Chinese * 设置指定会话关联的用户数据块。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * userdata [输入] 指向待关联的用户数据块。 */ WHISPER_API void whisper_session_set_userdata(WhisperSession *session, void *userdata); /** * \~English * Get the user data associated with the session. * * @param * session [in] A handle to the Whisper session. * * @return * The user data associated with session. * * \~Chinese * 获取指定会话关联的用户数据块。 * * @param * session [输入] 指向WhisperSession的句柄。 * @return * 指定会话关联的用户数据块。 */ WHISPER_API void *whisper_session_get_userdata(WhisperSession *session); /** * \~English * An application-defined function that receive session request complete * event. * * WhisperSessionRequestCompleteCallback is the callback function type. * * @param * session [in] A handle to the WhisperSession. * @param * status [in] The status code of the response. * 0 is success, otherwise is error. * @param * reason [in] The error message if status is error, or NULL * @param * sdp [in] The remote users SDP. End the null terminal. * Reference: https://tools.ietf.org/html/rfc4566 * @param * len [in] The length of the SDP. * @param * context [in] The application defined context data. * * \~Chinese * 应用定义用于接收session请求完成的函数。 * * WhisperSessionRequestCompleteCallback是回调函数类型。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * status [输入] 响应的状态码。 * 0表示成功,否则表示失败。 * @param * reason [输入] 若状态码表示失败,reason中存放失败的信息;否则为空。 * @param * sdp [输入] 对端用户的SDP,以null结尾。 * 具体参考:https://tools.ietf.org/html/rfc4566 * @param * len [输入] SDP长度。 * @param * context [输入] 应用定义的上下文数据。 */ typedef void WhisperSessionRequestCompleteCallback(WhisperSession *session, int status, const char *reason, const char *sdp, size_t len, void *context); /** * \~English * Send session request to the friend. * * @param * session [in] A handle to the WhisperSession. * @param * callback [in] A pointer to WhisperSessionRequestCompleteCallback * function to receive the session response. * @param * context [in] The application defined context data. * * @return * 0 if the session request successfully send to the friend. * Otherwise, return -1, and a specific error code can be * retrieved by calling whisper_get_error(). * * \~Chinese * 发送session请求。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * callback [输入] 指向接收session响应的WhisperSessionRequestCompleteCallback函数。 * @param * context [输入] 应用定义的上下文数据。 * * @return * 若session请求发送成功,则返回0。否则,返回-1。具体错误可以调用whisper_get_error()来获得。 */ WHISPER_API int whisper_session_request(WhisperSession *session, WhisperSessionRequestCompleteCallback *callback, void *context); /** * \~English * Reply the session request from friend. * * This function will send a session response to friend. * * @param * session [in] A handle to the WhisperSession. * @param * status [in] The status code of the response. * 0 is success, otherwise is error. * @param * reason [in] The error message if status is error, or NULL * if success. * * @return * 0 if the session response successfully send to the friend. * Otherwise, return -1, and a specific error code can be * retrieved by calling whisper_get_error(). * * \~Chinese * 回复session请求。 * * 函数发送session响应。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * status [输入] 响应的状态码。 * 0表示成功,否则表示失败。 * @param * reason [输入] 若状态码表示失败,reason中存放失败的信息;否则为空。 * * @return * 若session响应发送成功,则返回0。否则,返回-1。具体错误可以调用whisper_get_error()来获得。 */ WHISPER_API int whisper_session_reply_request(WhisperSession *session, int status, const char* reason); /** * \~English * Begin to start a session. * * All streams in current session will try to connect with remote friend, * the stream status will update to application by stream's callbacks. * * @param * session [in] A handle to the WhisperSession. * @param * sdp [in] The remote users SDP. End the null terminal. * Reference: https://tools.ietf.org/html/rfc4566 * @param * len [in] The length of the SDP. * * @return * 0 on success, or -1 if an error occurred. The specific error code * can be retrieved by calling whisper_get_error(). * * \~Chinese * 开始启动session。 * * 当前session的所有stream都尝试连接对端,相应引起的stream状态更新通过回调传递给应用。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * sdp [输入] 对端用户的SDP,以null结尾。 * 具体参考:https://tools.ietf.org/html/rfc4566 * @param * len [输入] SDP长度。 * @return * 0表示成功,-1表示失败。具体错误可以调用whisper_get_error()来获得。 */ WHISPER_API int whisper_session_start(WhisperSession *session, const char *sdp, size_t len); /* Session stream APIs */ /** * \~English * Whisper stream state. * The stream status will be changed according to the phase of the stream. * * \~Chinese * Whisper stream状态。 * stream状态根据stream所处阶段不同而不同。 */ typedef enum WhisperStreamState { /** Initialized stream */ WhisperStreamState_initialized = 1, /** The underlying transport is ready for the stream. */ WhisperStreamState_transport_ready, /** The stream is trying to connecting the remote. */ WhisperStreamState_connecting, /** The stream connected with remote */ WhisperStreamState_connected, /** The stream is deactivated */ WhisperStreamState_deactivated, /** The stream closed normally */ WhisperStreamState_closed, /** The stream is failed, cannot to continue. */ WhisperStreamState_failed } WhisperStreamState; /** * \~English * Portforwarding supported protocols. * * \~Chinese * Portforwarding支持的协议。 */ typedef enum PortForwardingProtocol { /** UDP protocol. */ PortForwardingProtocol_UDP = 0, /** TCP protocol. */ PortForwardingProtocol_TCP = 1 } PortForwardingProtocol; /** * \~English * Multiplexing channel close reason code. * * \Chinese * 多路复用通道关闭原因。 */ typedef enum CloseReason { /* Channel closed normally. */ CloseReason_Normal = 0, /* Channel closed because timeout. */ CloseReason_Timeout = 1, /* Channel closed because error ocurred. */ CloseReason_Error = 2 } CloseReason; /** * \~English * Whisper stream callbacks. * * Include stream status callback, stream data callback, and multiplexing * callbacks. * * \~Chinese * Whisper stream回调函数组合。 * * 该结构包含回调函数可以更新stream状态,接收stream数据和实现多路复用。 */ typedef struct WhisperStreamCallbacks { /* Common callbacks */ /** * \~English * Callback to report status of various stream operations. * * @param * session [in] The handle to the WhisperSession. * @param * stream [in] The stream ID. * @param * state [in] Stream state defined in WhisperStreamState. * @param * context [in] The application defined context data. * * \~Chinese * 该回调提示因不同stream操作引起的状态变化。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * stream [输入] stream id。 * @param * state [输入] Whisper Stream状态。 * @param * context [输入] 应用定义的上下文数据。 */ void (*state_changed)(WhisperSession *session, int stream, WhisperStreamState state, void *context); /* Stream callbacks */ /** * \~English * Callback will be called when the stream receives * incoming packet. * * If the stream enabled multiplexing mode, application will not * receive stream_data callback any more. All data will reported * as multiplexing channel data. * * @param * session [in] The handle to the WhisperSession. * @param * stream [in] The stream ID. * @param * data [in] The received packet data. * @param * len [in] The received data length. * @param * context [in] The application defined context data. * * \~Chinese * 该回调接收对端传输到应用的数据包。 * * 如果stream处于多路复用工作模式,应用将不会通过该回调来接收stream数据。所有数据都将通过 * 多路复用通道传递给应用。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * stream [输入] stream id。 * @param * data [输入] 接收到的数据包。 * @param * len [输入] 接收到的数据长度。 * @param * context [输入] 应用定义的上下文数据。 */ void (*stream_data)(WhisperSession *session, int stream, const void *data, size_t len, void *context); /* Multiplexer callbacks */ /** * \~English * Callback will be called when new multiplexing channel request to open. * * @param * session [in] The handle to the WhisperSession. * @param * stream [in] The stream ID. * @param * channel [in] The current channel ID. * @param * cookie [in] Application defined string data receive from peer. * @param * context [in] The application defined context data. * * @return * True on success, or false if an error occurred. * The channel will continue to open only this callback return true, * otherwise the channel will be closed. * * \~Chinese * 应用收到创建一条多路复用请求,调用该函数。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * stream [输入] stream id。 * @param * channel [输入] 当前channel id。 * @param * cookie [输入] 对端应用的自定义数据。 * @param * context [输入] 应用定义的上下文数据。 * @return * true表示成功,false表示失败。若返回true, 应用继续创建通道,否则通道关闭。 */ bool (*channel_open)(WhisperSession *session, int stream, int channel, const char *cookie, void *context); /** * \~English * Callback will be called when new multiplexing channel opened. * * @param * session [in] The handle to the WhisperSession. * @param * stream [in] The stream ID. * @param * channel [in] The current channel ID. * @param * context [in] The application defined context data. * * \~Chinese * 应用成功创建一条多路复用通道,调用该函数。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * stream [输入] stream id。 * @param * channel [输入] 当前channel id。 * @param * context [输入] 应用定义的上下文数据。 */ void (*channel_opened)(WhisperSession *session, int stream, int channel, void *context); /** * \~English * Callback will be called when channel close. * * @param * session [in] The handle to the WhisperSession. * @param * stream [in] The stream ID. * @param * channel [in] The current channel ID. * @param * reason [in] Channel close reason code, defined in CloseReason. * @param * context [in] The application defined context data. * * \~Chinese * 应用关闭通道,调用该函数。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * stream [输入] stream id。 * @param * channel [输入] 当前channel id。 * @param * reason [输入] 关闭通道的原因,原因类型定义在CloseReason。 * @param * context [输入] 应用定义的上下文数据。 */ void (*channel_close)(WhisperSession *session, int stream, int channel, CloseReason reason, void *context); /** * \~English * Callback will be called when channel received incoming data. * * @param * session [in] The handle to the WhisperSession. * @param * stream [in] The stream ID. * @param * channel [in] The current channel ID. * @param * data [in] The received data. * @param * len [in] The received data length. * @param * context [in] The application defined context data. * * @return * True on success, or false if an error occurred. * If this callback return false, the channel will be closed * with CloseReason_Error. * * \~Chinese * 应用接收到对端数据,调用该函数。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * stream [输入] stream id。 * @param * channel [输入] 当前channel id。 * @param * data [输入] 接收到的数据包。 * @param * len [输入] 接收到的数据长度。 * @param * context [输入] 应用定义的上下文数据。 * * @return * true表示成功,false表示失败。若返回false, 通道关闭失败原因保存在CloseReason_Error。 */ bool (*channel_data)(WhisperSession *session, int stream, int channel, const void *data, size_t len, void *context); /** * \~English * Callback will be called when remote peer ask to pend data sending. * * @param * session [in] The handle to the WhisperSession. * @param * stream [in] The stream ID. * @param * channel [in] The current channel ID. * @param * context [in] The application defined context data. * * \~Chinese * 接收到对端要求暂停数据发送,应用调用该函数。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * stream [输入] stream id。 * @param * channel [输入] 当前channel id。 * @param * context [输入] 应用定义的上下文数据。 */ void (*channel_pending)(WhisperSession *session, int stream, int channel, void *context); /** * \~English * Callback will be called when remote peer ask to resume data sending. * * @param * session [in] The handle to the WhisperSession. * @param * stream [in] The stream ID. * @param * channel [in] The current channel ID. * @param * context [in] The application defined context data. * * \~Chinese * 接收到对端要求回复数据发送,应用调用该函数。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * stream [输入] stream id。 * @param * channel [输入] 当前channel id。 * @param * context [输入] 应用定义的上下文数据。 */ void (*channel_resume)(WhisperSession *session, int stream, int channel, void *context); } WhisperStreamCallbacks; #define WHISPER_STREAM_COMPRESS 0x01 #define WHISPER_STREAM_PLAIN 0x02 #define WHISPER_STREAM_RELIABLE 0x04 #define WHISPER_STREAM_MULTIPLEXING 0x08 #define WHISPER_STREAM_PORT_FORWARDING 0x10 /** * \~English * Add a new stream to session. * * Whisper stream supports several underlying transport mechanisms: * * - Plain/encrypted UDP data gram protocol * - Plain/encrypted TCP like reliable stream protocol * - Multiplexing over UDP * - Multiplexing over TCP like reliable protocol * * Application can use options to specify the new stream mode. Data * transferred on stream is defaultly encrypted. Multiplexing over UDP can * not provide reliable transport. * * @param * session [in] The handle to the WhisperSession. * @param * type [in] The stream type defined in WhisperStreamType. * @param * options [in] The stream mode options. options are constructed * by a bitwise-inclusive OR of flags from the * following list: * * - WHISPER_STREAM_PLAIN * Plain mode. * - WHISPER_STREAM_RELIABLE * Reliable mode. * - WHISPER_STREAM_MULTIPLEXING * Multiplexing mode. * - WHISPER_STREAM_PORT_FORWARDING * Support portforwarding over multiplexing. * * @param * callbacks [in] The Application defined callback functions in * WhisperStreamCallbacks. * @param * context [in] The application defined context data. * * @return * Return stream id on success, or -1 if an error occurred. * The specific error code can be retrieved by calling * whisper_get_error(). * * \~Chinese * 指定session中添加stream。 * * Whisper stream支持以下几种传输机制: * * - 非加密/加密UDP数据报传输 * - 非加密/加密TCP可靠数据流传输 * - 基于UDP的多路复用 * - 基于TCP可靠传输的多路复用 * * 应用通过参数options来表明添加stream的传输机制,传输数据默认加密。基于UDP的多路复用 * 不能提供可靠传输。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * type [输入] stream类型,定义在WhisperStreamType。 * @param * options [输入] stream工作模式。该参数通过位操作或者以下的flag来设置: * * - WHISPER_STREAM_PLAIN * 非加密模式。 * - WHISPER_STREAM_RELIABLE * 可靠传输模式。 * - WHISPER_STREAM_MULTIPLEXING * 多路复用模式。 * - WHISPER_STREAM_PORT_FORWARDING * 基于多路复用的端口转发模式。 * * @param * callbacks [输入] 应用定义的WhisperStreamCallbacks类型回调函数。 * @param * context [输入] 应用定义的上下文数据。 * * @return * 若添加stream成功,返回stream id,反之,返回-1。 * 具体错误可以调用whisper_get_error()来获得。 */ WHISPER_API int whisper_session_add_stream(WhisperSession *session, WhisperStreamType type, int options, WhisperStreamCallbacks *callbacks, void *context); /** * \~English * Remove a stream from session. * * @param * session [in] The handle to the WhisperSession. * @param * stream [in] The stream id to be removed. * * @return * 0 on success, or -1 if an error occurred. * The specific error code can be retrieved by calling * whisper_get_error(). * * \~Chinese * 删除session中的指定stream。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * stream [输入] 需删除的stream id。 * * @return * 0表示成功,-1表示失败。具体错误可以调用whisper_get_error()来获得。 */ WHISPER_API int whisper_session_remove_stream(WhisperSession *session, int stream); /** * \~English * Add a new portforwarding service to session. * * The registered services can be used by remote peer in portforwarding * request. * * @param * session [in] The handle to the WhisperSession. * @param * service [in] The new service name, should be unique * in session scope. * @param * protocol [in] The protocol of the service. * @param * host [in] The host name or ip of the service. * @param * port [in] The port of the service. * * @return * 0 on success, or -1 if an error occurred. * The specific error code can be retrieved by calling * whisper_get_error(). * * \~Chinese * 添加一个新端口转发服务。 * * 新注册的服务可以被对端用于端口转发请求。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * service [输入] 新服务名,在session中具有唯一性。 * @param * protocol [输入] 服务支持的协议。 * @param * host [输入] 服务的主机名或者ip地址。 * @param * port [输入] 服务的端口。 * * @return * 0表示成功,-1表示失败。具体错误可以调用whisper_get_error()来获得。 */ WHISPER_API int whisper_session_add_service(WhisperSession *session, const char *service, PortForwardingProtocol protocol, const char *host, const char *port); /** * \~English * Remove a portforwarding service to session. * * This function has not effect on existing portforwarings. * * @param * session [in] The handle to the WhisperSession. * @param * service [in] The service name. * * \~Chinese * 删除session中的指定的端口转发服务。 * * 该函数不能用于已存在的portforwaring中。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * service [输入] 服务名。 */ WHISPER_API void whisper_session_remove_service(WhisperSession *session, const char *service); /** * \~English * Set the whisper stream type. * * This function has not effect on connected streams. * Application can change the stream type before start session. * * @param * session [in] The handle to the WhisperSession. * @param * stream [in] The stream ID. * @param * type [in] New stream type defined in WhisperStreamType. * * @return * 0 on success, or -1 if an error occurred. * The specific error code can be retrieved by calling * whisper_get_error(). * * \~Chinese * 设置whisper stream类型 * * 该函数不能用于已连接stream。 * 应用可以在开启session之前改变stream类型。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * stream [输入] stream id。 * @param * type [输入] 新stream类型,具体定义WhisperStreamType。 * * @return * 0表示成功,-1表示失败。具体错误可以调用whisper_get_error()来获得。 */ WHISPER_API int whisper_stream_set_type(WhisperSession *session, int stream, WhisperStreamType type); /** * \~English * Get the whisper stream type. * * @param * session [in] The handle to the WhisperSession. * @param * stream [in] The stream ID. * @param * type [out] The stream type defined in WhisperStreamType. * * @return * 0 on success, or -1 if an error occurred. * The specific error code can be retrieved by calling * whisper_get_error(). * * \~Chinses * 获取whisper stream类型。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * stream [输入] stream id。 * @param * type [输入] 新stream类型,具体定义WhisperStreamType。 * * @return * 0表示成功,-1表示失败。具体错误可以调用whisper_get_error()来获得。 */ WHISPER_API int whisper_stream_get_type(WhisperSession *session, int stream, WhisperStreamType *type); /** * \~English * Get the whisper stream current state. * * @param * session [in] The handle to the WhisperSession. * @param * stream [in] The stream ID. * @param * state [out] The stream state defined in WhisperStreamState. * * @return * 0 on success, or -1 if an error occurred. * The specific error code can be retrieved by calling * whisper_get_error(). * * \~Chinses * 获取whisper stream当前状态。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * stream [输入] stream id。 * @param * state [输入] 新stream状态,具体定义WhisperStreamState。 * * @return * 0表示成功,-1表示失败。具体错误可以调用whisper_get_error()来获得。 */ WHISPER_API int whisper_stream_get_state(WhisperSession *session, int stream, WhisperStreamState *state); /** * \~English * Get the whisper stream transport information. * * @param * session [in] The handle to the WhisperSession. * @param * stream [in] The stream ID. * @param * info [out] The stream transport information defined in * WhisperTransportInfo. * * @return * 0 on success, or -1 if an error occurred. * The specific error code can be retrieved by calling * whisper_get_error(). * * \~Chinses * 获取whisper stream当前传输通道信息 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * stream [输入] stream id。 * @param * state [输入] 指向传输通道信息的内存块,具体定义WhisperTransportInfo。 * * @return * 0表示成功,-1表示失败。具体错误可以调用whisper_get_error()来获得。 */ WHISPER_API int whisper_stream_get_transport_info(WhisperSession *session, int stream, WhisperTransportInfo *info); /** * \~English * Send outgoing data to remote peer. * * If the stream is in multiplexing mode, application can not * call this function to send data. If this function is called * on multiplexing mode stream, it will return error. * * @param * session [in] The handle to the WhisperSession. * @param * stream [in] The stream ID. * @param * data [in] The outgoing data. * @param * len [in] The outgoing data length. * * @return * Sent bytes on success, or -1 if an error occurred. * The specific error code can be retrieved by calling * whisper_get_error(). * * \~Chinese * 发送数据到对端。 * * 若stream处于多路复用模式,应用不能调用该函数去发送数据。如果多路复用stream调用该函数发送数据, * 函数返回错误。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * stream [输入] stream id。 * @param * data [输入] 发送的数据。 * @param * len [输入] 发送数据的长度。 * * @return * 0表示成功,-1表示失败。具体错误可以调用whisper_get_error()来获得。 */ WHISPER_API ssize_t whisper_stream_write(WhisperSession *session, int stream, const void *data, size_t len); /** * \~English * Open a new channel on multiplexing stream. * * If the stream is not multiplexing this function will fail. * * @param * session [in] The handle to the WhisperSession. * @param * stream [in] The stream ID. * @param * cookie [in] Application defined data pass to remote peer. * * @return * New channel ID on success, or -1 if an error occurred. * The specific error code can be retrieved by calling * whisper_get_error(). * * \~Chinese * 创建一个新多路复用通道。 * * 若stream不支持多路复用,调用该函数失败。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * stream [输入] stream id。 * @param * cookie [输入] 传递给对端的自定义数据。 * * @return * 0表示成功,-1表示失败。具体错误可以调用whisper_get_error()来获得。 */ WHISPER_API int whisper_stream_open_channel(WhisperSession *session, int stream, const char *cookie); /** * \~English * Close a new channel on multiplexing stream. * * If the stream is not multiplexing this function will fail. * * @param * session [in] The handle to the WhisperSession. * @param * stream [in] The stream ID. * @param * channel [in] The channel ID. * * @return * 0 on success, or -1 if an error occurred. * The specific error code can be retrieved by calling * whisper_get_error(). * * \~Chinese * 关闭指定多路复用通道。 * * 若stream不支持多路复用,调用该函数失败。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * stream [输入] stream id。 * @param * channel [输入] channel id。 * * @return * 0表示成功,-1表示失败。具体错误可以调用whisper_get_error()来获得。 */ WHISPER_API int whisper_stream_close_channel(WhisperSession *session, int stream, int channel); /** * \~English * Send outgoing data to remote peer. * * If the stream is not multiplexing this function will fail. * * @param * session [in] The handle to the WhisperSession. * @param * stream [in] The stream ID. * @param * channel [in] The channel ID. * @param * data [in] The outgoing data. * @param * len [in] The outgoing data length. * * @return * Sent bytes on success, or -1 if an error occurred. * The specific error code can be retrieved by calling * whisper_get_error(). * * \~Chinese * 发送数据到对端。 * * 如果stream不支持多路复用,调用该函数失败。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * stream [输入] stream id。 * @param * channel [输入] channel id。 * @param * data [输入] 发送的数据。 * @param * len [输入] 发送数据的长度。 * * @return * 0表示成功,-1表示失败。具体错误可以调用whisper_get_error()来获得。 */ WHISPER_API ssize_t whisper_stream_write_channel(WhisperSession *session, int stream, int channel, const void *data, size_t len); /** * \~English * Request remote peer to pend channel data sending. * * If the stream is not multiplexing this function will fail. * * @param * session [in] The handle to the WhisperSession. * @param * stream [in] The stream ID. * @param * channel [in] The channel ID. * * @return * 0 on success, or -1 if an error occurred. * The specific error code can be retrieved by calling * whisper_get_error(). * * \~Chinese * 请求对端暂停数据发送。 * * 如果stream不支持多路复用,调用该函数失败。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * stream [输入] stream id。 * @param * channel [输入] channel id。 * * @return * 0表示成功,-1表示失败。具体错误可以调用whisper_get_error()来获得。 */ WHISPER_API int whisper_stream_pend_channel(WhisperSession *session, int stream, int channel); /** * \~English * Request remote peer to resume channel data sending. * * If the stream is not multiplexing this function will fail. * * @param * session [in] The handle to the WhisperSession. * @param * stream [in] The stream ID. * @param * channel [in] The channel ID. * * @return * 0 on success, or -1 if an error occurred. * The specific error code can be retrieved by calling * whisper_get_error(). * * \~Chinese * 请求对端恢复数据传输 * * 如果stream不支持多路复用,调用该函数失败。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * stream [输入] stream id。 * @param * channel [输入] channel id。 * * @return * 0表示成功,-1表示失败。具体错误可以调用whisper_get_error()来获得。 */ WHISPER_API int whisper_stream_resume_channel(WhisperSession *session, int stream, int channel); /** * \~English * Open a portforwarding to remote service over multiplexing. * * If the stream is not multiplexing this function will fail. * * @param * session [in] The handle to the WhisperSession. * @param * stream [in] The stream ID. * @param * service [in] The remote service name. * @param * protocol [in] Portforwarding protocol. * @param * host [in] Local host or ip to binding. * If host is NULL, portforwarding will bind to 127.0.0.1. * @param * port [in] Local port to binding, can not be NULL. * * @return * Portforwarding ID on success, or -1 if an error occurred. * The specific error code can be retrieved by calling * whisper_get_error(). * * \~Chinese * 创建一个基于多路复用的端口转发。 * * 如果stream不支持多路复用,调用该函数失败。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * stream [输入] stream id。 * @param * service [输入] 对端服务名。 * @param * protocol [输入] 端口转发协议。 * @param * host [输入] 用于绑定的本地主机或者ip地址。 * 如果本地主机为空,则绑定127.0.0.1。 * @param * port [输入] 用于绑定的本地端口,不可为空。 * * @return * 0表示成功,-1表示失败。具体错误可以调用whisper_get_error()来获得。 */ WHISPER_API int whisper_stream_open_port_forwarding(WhisperSession *session, int stream, const char *service, PortForwardingProtocol protocol, const char *host, const char *port); /** * \~English * Close a portforwarding to remote service over multiplexing. * * If the stream is not multiplexing this function will fail. * * @param * session [in] The handle to the WhisperSession. * @param * stream [in] The stream ID. * @param * portforwarding [in] The portforwarding ID. * * @return * 0 on success, or -1 if an error occurred. * The specific error code can be retrieved by calling * whisper_get_error(). * * \~Chinese * 关闭一个基于多路复用的端口转发。 * * 如果stream不支持多路复用,调用该函数失败。 * * @param * session [输入] 指向WhisperSession的句柄。 * @param * stream [输入] stream id。 * @param * portforwarding [输入] portforwarding id。 * * @return * 0表示成功,-1表示失败。具体错误可以调用whisper_get_error()来获得。 */ WHISPER_API int whisper_stream_close_port_forwarding(WhisperSession *session, int stream, int portforwarding); #ifdef __cplusplus } #endif #if defined(__APPLE__) #pragma GCC diagnostic pop #endif #endif /* __WHISPER_SESSION_H__ */
25.753371
87
0.601907
[ "object" ]
b9da7cd47b84f33bfaab84912144ff919719150d
78,083
c
C
lib/src/tinyhtm/src/tree_gen.c
Caltech-IPAC/SpatialIndex
8898ea7bd71b3ea9e5b9104f011695e0c20e5f98
[ "BSD-3-Clause" ]
1
2020-06-19T01:07:56.000Z
2020-06-19T01:07:56.000Z
lib/src/tinyhtm/src/tree_gen.c
Caltech-IPAC/SpatialIndex
8898ea7bd71b3ea9e5b9104f011695e0c20e5f98
[ "BSD-3-Clause" ]
null
null
null
lib/src/tinyhtm/src/tree_gen.c
Caltech-IPAC/SpatialIndex
8898ea7bd71b3ea9e5b9104f011695e0c20e5f98
[ "BSD-3-Clause" ]
2
2020-07-09T22:32:21.000Z
2021-08-04T13:55:59.000Z
/** \file \brief HTM tree generation. \authors Serge Monkewitz \copyright IPAC/Caltech */ /** \page htm_tree_gen Tree index generation with htm_tree_gen The \c htm_tree_gen utility takes character separated value files containing points (integer ID, longitude angle and latitude angle columns are expected), and outputs an HTM tree index which is useful for fast point-in-region counts. \section usage Usage <pre><tt> htm_tree_gen [options] &lt;tree file&gt; &lt;input file 1&gt; [&lt;input file 2&gt; ...] </tt></pre> \section opts Command Line Options Running <tt>htm_tree_index --help</tt> provides a list of the supported command line options and their descriptions. \section over Overview HTM tree indexes can be used to quickly count or estimate how many points fall in a spherical region. The indexing utility produces two binary files - a data file consisting of points sorted in ascending HTM ID order, and a tree file which contains an HTM tree over the points. Tree nodes contain a count of the number of points inside the node and an index into the data file; empty nodes are omitted. This leads to the following simple and fast counting algorithm: Given a geometric region, visit all non-empty nodes overlapping the region. For nodes fully covered by the region, add the point count to a running total. For partially covered internal nodes, visit the non-empty children. For partially covered leaves, read points from the data file and check whether they are contained in the region. \section data Data File Algorithm Producing the sorted data file is conceptually simple; all that is required is an external sorting routine. The implementation uses quicksort on in-memory blocks followed by a series of k-way merges. \section tree Tree File Algorithm More difficult is an external algorithm for producing the tree file, especially if one wishes to optimize with respect to cache-line and memory page size. Alstrup's Split-and-Refine algorithm is used for layout. It produces a cache oblivious layout via repeated application of an arbitrary black-box algorithm, which is required to produce an optimal layout for a specified block size. The black-box is Clark and Munro's greedy bottom-up method for worst-cast optimal tree layout. These algorithms are detailed in the papers below: <pre> David R. Clark and J. Ian Munro. Efficient suffix trees on secondary storage. In Proceedings of the 7th Annual ACM-SIAM Symposium on Discrete Algorithms, Pages 383-391, Atlanta, January 1996. </pre> <pre> Stephen Alstrup, Michael A. Bender, Erik D. Demaine, Martin Farach-Colton, Theis Rauhe, and Mikkel Thorup. Efficient tree layout in a multilevel memory hierarchy. arXiv:cs.DS/0211010, 2004. http://www.arXiv.org/abs/cs.DS/0211010. </pre> The tree generation phase produces an HTM tree with the following properties: - Each node N corresponds to an HTM triangle, and stores a count of the number of entries inside N, count(N), as well as the index (in the data file) of its first entry. - If level(N) == 20, N is a leaf - no children are generated. - If count(N) < K for some fixed threshold K, N is a leaf - no children are generated. - If count(N) >= K and level(N) < 20, N is an internal node - the non-empty children of N are generated. Given the data file (points sorted by HTM ID), it is possible to emit tree nodes satisfying the above in post-order with a single sequential scan. Iterating over nodes in post-order means that a parent node is processed only after all children have been processed. Because Clark and Munro's layout algorithm is bottom-up, one can simultaneously perform layout for all the block-sizes used by Split-and-Refine. The result is a string of block IDs for each node - a unique node ID. Note that block IDs are handed out sequentially for a given block size. Since tree nodes are visited in post-order, the block ID of a parent must be greater than or equal to the block ID of a child. Once block IDs for a node have been computed at every block size, the node can be written to disk. If the largest block size is B, the in-memory node size is M, and the on disk node size is N, then 8BM/N bytes of RAM are required in the worst case. Next, the tree node file is sorted by node ID, yielding the desired cache-oblivious layout (per Alstrup). The sort is in ascending lexicographic block ID string order, always placing children before parents. At this stage, nodes contain very space-heavy node IDs, and child pointers are also node IDs! These are necessary for layout, but are not useful for tree searches. In fact, mapping a node ID to a file offset is non-trivial. Therefore, the sorted node file is converted to a much more space efficient representation: - Leaf nodes store a position count and the data file index of the first position inside the node. The index is stored as an offset relative to the index of the parent (this results in smaller numbers towards the leaves, allowing variable length coding to squeeze them into fewer bytes - see below). - Internal nodes additionally store relative tree file offsets for 4 children. Tree file offsets of empty children are set to 0. - Note that internal nodes can be distinguished from leaves simply by comparing their position count to the leaf threshold K. Variable length coding is used for counts and data file indexes. Using such an encoding for tree file offsets is hard. Why? Because with variable length encoding, the size of a child offset depends on the offset value, which in turn depends on the size of the child offsets of nodes between the parent and child - in other words, it is node order dependent. This invalidates the block size computations required by Clark and Munro's algorithm, which has no a priori knowledge of the final node order - the reason for invoking it in the first place is to determine that order! Nevertheless, offsets are also variable length coded since it significantly reduces tree file size. The layout algorithm simply treats child offsets as having some fixed (hopefully close to average) on-disk size. The main difficulty during compression is the computation of tree file offsets from node IDs. Note that in the sorted node file a child will always occur before a parent. Therefore, the algorithm operates as follows: first, an empty hash-table that maps node IDs to file offsets is initialized. Next, the sorted node file is scanned sequentially. Finally, for each node: - the offsets of its children are looked up in the hashtable and the corresponding hashtable entries are removed (a node has exactly one parent). - the compressed byte string corresponding to the node is written out in reverse, and the size of the node is added to the running total file size. - an entry mapping the node id to the file size is added to the hashtable. To be precise: the parent of a node can subtract the file size just after a child was written from the current file size to obtain the child's offset. This yields a a compressed tree file T in reverse byte order. The last step consists of simply reversing the order of the bytes in T, giving the final tree file (with parent nodes always occurring before children). \section notes Notes The Clark and Munro layout algorithm is invoked only with a limited set of block sizes. The small number chosen (5) results in various internal structures having reasonable power-of-2 sizes, whilst still covering the block sizes that commonly occur in the multi-level memory hierarchies of modern 64-bit x86 systems. The largest block size used is 2 MiB, which corresponds to the size of a large page on x86-64. Using larger sizes seems to be of questionable utility and would increase the memory requirements for the tree generation phase, as nodes can only be written once a block ID for every block size has been assigned. The code is targeted at 64-bit machines with plenty of virtual address space. For example, huge files are mmapped in read-only mode (with MAP_NORESERVE). If system admins are restricting per-process address space, one may have to run `ulimit -v unlimited` prior to htm_tree_gen. The largest table that will have to be dealt with in the near future will contain around 10 billion points; at 32 bytes per record, this will involve asking for 320GB of address space. Should this be problematic, fancier IO strategies may have to be employed. Note however that e.g. RHEL 6 (and other recent x86-64 Linux distros) have a per process virtual address space limit of 128TB, and that in any case, practical tree generation at larger scales will require parallelization, possibly even across machines. While such parallelization is conceptually straightforward, even for tree generation/compression, it adds very significant implementation complexity, and so the code is mostly serial for now. */ #include <assert.h> #include <ctype.h> #include <errno.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/mman.h> #include <fcntl.h> #include <unistd.h> #include <getopt.h> #include <pthread.h> #include "tinyhtm/geometry.h" #include "tinyhtm/htm.h" #include "tinyhtm/tree.h" #include "tinyhtm/varint.h" /** \cond */ /* ================================================================ */ /* Utilities and plumbing */ /* ================================================================ */ /* Prints an error message to stderr and exits. */ static void err(const char *fmt, ...) { va_list ap; fprintf(stderr, "ERROR: "); va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fprintf(stderr, "\n"); fflush(stderr); exit(EXIT_FAILURE); } /* Prints a message to stdout and exits. */ static void msg(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vprintf(fmt, ap); va_end(ap); fflush(stdout); } /* Returns the number of seconds that have elapsed since the epoch. */ static double now() { struct timeval t; gettimeofday(&t, NULL); return ((double) t.tv_sec) + ((double) t.tv_usec) / 1.0e6; } /* ---- Memory and IO related parameters ---- */ struct mem_params { size_t memsz; /* Max memory usage in bytes */ size_t sortsz; /* Size of blocks operated on by in-memory sorts */ size_t ioblksz; /* Size of IO blocks */ size_t k; /* Number of merge segments in one multi-way merge pass */ }; static void mem_params_init(struct mem_params *mem, size_t total, size_t ioblksz) { const size_t pagesz = (size_t) sysconf(_SC_PAGESIZE); if (total % (2*pagesz) != 0) { total += 2*pagesz - total % (2*pagesz); } if (ioblksz % pagesz != 0) { ioblksz += pagesz - ioblksz % pagesz; } if (total < 6*ioblksz) { total = 6*ioblksz; } mem->memsz = total; mem->sortsz = total / 2; mem->ioblksz = ioblksz; mem->k = (total - 2*ioblksz) / (2*ioblksz); } /* ---- Asynchronous block writer ---- */ enum bk_write_state { BK_WRITE_START = 0, BK_WRITE_READY, BK_WRITE_BLK, BK_WRITE_EXIT, BK_WRITE_ERR }; struct blk_writer { size_t n; /* Number of bytes per block */ size_t i; /* Number of bytes in current block */ unsigned char *buf; /* Current block pointer */ void *mem; /* Space for 2 blocks of n tree entries */ size_t memsz; /* Size of mem in bytes */ int fd; /* File descriptor of file being written to */ enum bk_write_state state; unsigned char *wrbuf; size_t wrbytes; pthread_attr_t attr; pthread_mutex_t mtx; pthread_cond_t cv; pthread_t thr; }; /* Writes data blocks in the background. */ static void * bk_write(void *arg) { struct blk_writer *w = (struct blk_writer *) arg; pthread_mutex_lock(&w->mtx); while (1) { unsigned char *buf; size_t n; ssize_t b; /* signal readiness for a command */ w->state = BK_WRITE_READY; pthread_cond_signal(&w->cv); /* wait for a command */ pthread_cond_wait(&w->cv, &w->mtx); if (w->state == BK_WRITE_READY) { continue; /* nothing to do */ } else if (w->state == BK_WRITE_EXIT) { break; /* exit background writer thread */ } /* write a block */ buf = w->wrbuf; n = w->wrbytes; pthread_mutex_unlock(&w->mtx); while (n > 0) { b = write(w->fd, buf, n); if (b < 0) { if (errno != EINTR) { /* error - exit background writer thread */ pthread_mutex_lock(&w->mtx); w->state = BK_WRITE_ERR; goto done; } } else { buf += b; n -= (size_t) b; } } pthread_mutex_lock(&w->mtx); } done: pthread_cond_signal(&w->cv); pthread_mutex_unlock(&w->mtx); return NULL; } /* Creates a new block writer with the given block size. */ static struct blk_writer * blk_writer_init(const char * const file, size_t blksz) { struct blk_writer *w; const size_t pagesz = (size_t) sysconf(_SC_PAGESIZE); w = (struct blk_writer *) malloc(sizeof(struct blk_writer)); if (w == NULL) { err("malloc() failed"); } w->n = blksz; w->i = 0; w->fd = open(file, O_CREAT | O_TRUNC | O_APPEND | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (w->fd == -1) { err("failed to open file %s for writing", file); } w->memsz = 2 * blksz; if (w->memsz % pagesz != 0) { w->memsz += pagesz - w->memsz % pagesz; } w->mem = mmap(NULL, w->memsz, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); if (w->mem == MAP_FAILED) { err("write buffer allocation via mmap() failed"); } w->buf = (unsigned char *) w->mem; w->state = BK_WRITE_START; w->wrbuf = NULL; w->wrbytes = 0; pthread_attr_init(&w->attr); pthread_attr_setdetachstate(&w->attr, PTHREAD_CREATE_JOINABLE); pthread_mutex_init(&w->mtx, NULL); pthread_cond_init(&w->cv, NULL); pthread_create(&w->thr, &w->attr, &bk_write, (void *) w); return w; } /* Issues (asynchronous) write of one block. */ static void blk_writer_issue(struct blk_writer * const w, void (*sortfn)(void *, size_t)) { if (sortfn != NULL) { (*sortfn)(w->buf, w->i); } pthread_mutex_lock(&w->mtx); /* wait until background writer thread is ready for a command */ while (w->state != BK_WRITE_READY && w->state != BK_WRITE_ERR) { pthread_cond_wait(&w->cv, &w->mtx); } if (w->state == BK_WRITE_ERR) { pthread_mutex_unlock(&w->mtx); err("background thread failed to write() disk block"); } /* issue write for the current block */ w->state = BK_WRITE_BLK; w->wrbuf = w->buf; w->wrbytes = w->i; pthread_cond_signal(&w->cv); pthread_mutex_unlock(&w->mtx); /* flip write buffer */ w->i = 0; if (w->buf == (unsigned char *) w->mem) { w->buf = ((unsigned char *) w->mem) + w->n; } else { w->buf = ((unsigned char *) w->mem); } } /* Closes writer w; all as yet unwritten data is flushed to disk first. If a non-NULL sorting function pointer is supplied, unwritten data is sorted prior to being written. */ static void blk_writer_close(struct blk_writer * const w, void (*sortfn)(void *, size_t)) { blk_writer_issue(w, sortfn); pthread_mutex_lock(&w->mtx); /* wait until background writer thread is ready for a command */ while (w->state != BK_WRITE_READY && w->state != BK_WRITE_ERR) { pthread_cond_wait(&w->cv, &w->mtx); } if (w->state == BK_WRITE_ERR) { pthread_mutex_unlock(&w->mtx); err("background thread failed to write() disk block"); } /* issue thread exit command ... */ w->state = BK_WRITE_EXIT; pthread_cond_signal(&w->cv); pthread_mutex_unlock(&w->mtx); /* ... and wait for writer thread to terminate */ pthread_join(w->thr, NULL); /* clean up */ if (munmap(w->mem, w->memsz) != 0) { err("munmap() of write buffers failed"); } if (fsync(w->fd) != 0) { err("fsync() failed"); } if (close(w->fd) != 0) { err("file close() failed"); } pthread_cond_destroy(&w->cv); pthread_mutex_destroy(&w->mtx); pthread_attr_destroy(&w->attr); free(w); } /* Appends data to the given block writer. */ HTM_INLINE void blk_writer_append(struct blk_writer * const w, const void * const data, const size_t nbytes, void (*sortfn)(void *, size_t)) { size_t i = w->i; if (i + nbytes > w->n) { blk_writer_issue(w, sortfn); i = 0; } assert(i + nbytes <= w->n); memcpy(w->buf + i, data, nbytes); w->i = i + nbytes; } /* ---- Multi-way external merge sort ---- */ /* A contiguous sequence of sorted items, dubbed a multi-way merge segment. */ struct mrg_seg { const void *cur; const void *end; const void *blk; }; /* Initializes a merge segment. */ static void mrg_seg_init(struct mrg_seg * const s, const void * start, const void * end, const size_t blksz) { size_t n; const size_t pagesz = (size_t) sysconf(_SC_PAGESIZE); size_t nbytes = (const char *) end - (const char *) start; if (end <= start || blksz % pagesz != 0) { err("Invalid merge segment"); } s->cur = start; s->end = end; n = ((size_t) start) % pagesz; if (n != 0) { start = (const char *) start - n; nbytes += n; } n = (nbytes > 2*blksz ? 2*blksz : nbytes); if (n % pagesz != 0) { n += pagesz - n % pagesz; } s->blk = (const char *) start + blksz; if (madvise((void *) start, n, MADV_WILLNEED) != 0) { err("madvise() failed"); } } /* Handles prefetch and merge segment exhaustion. */ static int mrg_seg_advance(struct mrg_seg * const s, const size_t blksz, const void * const cur) { const size_t pagesz = (size_t) sysconf(_SC_PAGESIZE); if (cur == s->end) { void *start = (char *) s->blk - blksz; size_t n = (char *) s->end - (char *) start; if (n % pagesz != 0) { n += pagesz - n % pagesz; } if (madvise(start, n, MADV_DONTNEED) != 0) { err("madvise() failed"); } return 0; } assert(cur >= s->blk && cur < s->end); if (madvise((char *) s->blk - blksz, blksz, MADV_DONTNEED) != 0) { err("madvise() failed"); } s->cur = cur; s->blk = (const char *) s->blk + blksz; if (s->blk < s->end) { size_t n = (char *) s->end - (char *) s->blk; if (n >= blksz) { n = blksz; } else if (n % pagesz != 0) { n += pagesz - n % pagesz; } if (madvise((void *) s->blk, n, MADV_WILLNEED) != 0) { err("madvise() failed"); } } return 1; } /* Consumes one item in the given merge segment; returns 0 if there are no more items in the segment. */ HTM_INLINE int mrg_seg_consume(struct mrg_seg * const s, const size_t blksz, const size_t itemsz) { const void *cur = (const char *) s->cur + itemsz; if (cur < s->end && cur < s->blk) { s->cur = cur; return 1; } return mrg_seg_advance(s, blksz, cur); } /* Adds segs[n] to the min-heap segs[0], segs[1], ..., segs[n - 1]. */ static void heap_up(struct mrg_seg *segs, size_t n, int (*cmpfn)(const void *, const void *)) { struct mrg_seg tmp; size_t p; while (n != 0) { p = (n - 1) / 2; if ((*cmpfn)(segs[p].cur, segs[n].cur) != 0) { break; } tmp = segs[p]; segs[p] = segs[n]; segs[n] = tmp; n = p; } } /* Fix possible min-heap violation by segs[0]. */ static void heap_down(struct mrg_seg *segs, const size_t n, int (*cmpfn)(const void *, const void *)) { struct mrg_seg tmp; size_t i; if (n > 1) { i = 0; while (1) { size_t left = 2*i + 1; size_t right = 2*i + 2; size_t least = i; if (left < n && (*cmpfn)(segs[left].cur, segs[i].cur) != 0) { least = left; } if (right < n && (*cmpfn)(segs[right].cur, segs[least].cur) != 0) { least = right; } if (least == i) { break; } tmp = segs[i]; segs[i] = segs[least]; segs[least] = tmp; i = least; } } } /* Performs one multi-way merge pass. */ static void mrg_pass(struct blk_writer * const w, const void * const data, const struct mem_params * const mem, const size_t filesz, const size_t sortsz, const size_t itemsz, int (*cmpfn)(const void *, const void *)) { struct mrg_seg *segs; size_t start; /* allocate merge segments */ segs = (struct mrg_seg *) malloc( mem->k * sizeof(struct mrg_seg)); if (segs == NULL) { err("malloc() failed"); } for (start = 0; start < filesz;) { size_t ns, end; /* initialize up to mem->k merge segments */ for (ns = 0; ns < mem->k && start < filesz; ++ns, start = end) { end = (start + sortsz > filesz ? filesz : start + sortsz); mrg_seg_init(&segs[ns], (const char *) data + start, (const char *) data + end, mem->ioblksz); heap_up(segs, ns, cmpfn); } /* merge ns segments */ while (ns > 0) { /* write minimum value from all ns merge segments to disk */ blk_writer_append(w, segs->cur, itemsz, NULL); if (mrg_seg_consume(segs, mem->ioblksz, itemsz) == 0) { segs[0] = segs[ns - 1]; --ns; } heap_down(segs, ns, cmpfn); } } free(segs); } /* Computes the number of k-way merge passes required to sort n items, i.e. the ceiling of the base-k logarithm of n. */ static int mrg_npasses(size_t n, size_t k) { int m = 1; size_t b = k; while (b < n) { b *= k; ++m; } return m; } /* Sorts the given file using multi-way external merge sort. @param[in] file File to sort. Runs of size mem->sortb are assumed to be sorted already. @param[in] tmpl Temporary file name template. @param[in] mem Memory parameters. @param[in] itemsz Size of a single item in bytes. @param[in] nitems Number of items in file. */ static void ext_sort(const char *file, const char *scratch, const struct mem_params *mem, size_t itemsz, size_t nitems, int (*cmpfn)(const void *, const void *)) { const size_t pagesz = (size_t) sysconf(_SC_PAGESIZE); const size_t filesz = nitems * itemsz; size_t sortsz = mem->sortsz - mem->sortsz % itemsz; const size_t nblk = filesz / sortsz + (filesz % sortsz != 0 ? 1u : 0u); const int nmp = mrg_npasses(nblk, mem->k); int mp; double ttot; if (nblk < 2) { msg("Skipping multi-way merge step (%s already sorted)\n", file); return; } msg("Multi-way external merge sort of %s\n", file); ttot = now(); /* Perform k-way merge passes; the sorted block grows by a factor of k on every pass */ for (mp = 0; mp < nmp; ++mp, sortsz *= mem->k) { const char *inf; const char *outf; const void *data; struct blk_writer *w; double t; size_t nmap; int infd; msg("\t- merge pass %d/%d ... ", mp + 1, nmp); t = now(); /* memory map input file and create writer for output file */ if (mp % 2 == 0) { inf = file; outf = scratch; } else { inf = scratch; outf = file; } infd = open(inf, O_RDONLY); if (infd == -1) { err("failed to open file %s for reading", inf); } if (filesz % pagesz != 0) { nmap = filesz + (pagesz - filesz % pagesz); } else { nmap = filesz; } data = mmap(NULL, nmap, PROT_READ, MAP_SHARED | MAP_NORESERVE, infd, 0); if (data == MAP_FAILED) { err("failed to mmap() file %s", inf); } if (madvise((void *) data, filesz, MADV_DONTNEED) != 0) { err("madvise() failed"); } w = blk_writer_init(outf, mem->ioblksz); /* perform merges */ mrg_pass(w, data, mem, filesz, sortsz, itemsz, cmpfn); /* cleanup */ blk_writer_close(w, NULL); if (munmap((void *) data, nmap) != 0) { err("failed to munmap() file %s", inf); } if (close(infd) != 0) { err("failed to close() file %s", inf); } msg("%.3f sec\n", now() - t); } /* make sure sorted results are in data file and delete scratch file. */ if (nmp % 2 == 1) { if (rename(scratch, file) != 0) { err("failed to rename file %s to %s", scratch, file); } } else { if (unlink(scratch) != 0) { err("failed to delete file %s", scratch); } } msg("\t%.3f sec total\n\n", now() - ttot); } /* ---- Fast constant size memory allocator ---- */ /* Undefine FAST_ALLOC (or define it as 0) to allocate nodes with malloc() instead. Useful when checking memory safety, e.g. with valgrind. */ #define FAST_ALLOC 1 #if FAST_ALLOC # define ARENA_SEGSZ 16*1024*1024 /* A contiguous memory segment belonging to an arena. */ struct arena_seg { struct arena_seg *prev; void *mem; }; static struct arena_seg * arena_seg_init(struct arena_seg * const prev, const size_t itemsz) { unsigned char *node, *end; struct arena_seg *seg = (struct arena_seg *) malloc(sizeof(struct arena_seg)); if (seg == NULL) { err("malloc() failed"); } seg->prev = prev; seg->mem = mmap(NULL, ARENA_SEGSZ, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); if (seg->mem == MAP_FAILED) { err("mmap() failed"); } /* initialize free list */ node = (unsigned char *) seg->mem; end = node + (ARENA_SEGSZ/itemsz - 1)*itemsz; while (node < end) { *((void **) node) = node + itemsz; node += itemsz; } *((void **) node) = NULL; return seg; } /* A (non-shrinkable) memory arena. Memory nodes can be freed one at a time, or en-masse. */ struct arena { struct arena_seg *tail; /* reverse linked list of memory segments */ struct mem_node *head; /* head of linked list of free memory locations */ size_t itemsz; size_t nseg; }; static void arena_init(struct arena * const a, const size_t itemsz) { a->tail = arena_seg_init(NULL, itemsz); a->head = a->tail->mem; a->itemsz = itemsz; a->nseg = 1; } static void arena_destroy(struct arena * const a) { struct arena_seg *seg = a->tail; while (seg != NULL) { struct arena_seg *prev = seg->prev; if (munmap(seg->mem, ARENA_SEGSZ) != 0) { err("munmap() failed"); } seg->prev = NULL; seg->mem = NULL; free(seg); seg = prev; } a->tail = NULL; a->head = NULL; a->nseg = 0; } HTM_INLINE void * arena_alloc(struct arena * const a) { void *item; if (a->head == NULL) { a->tail = arena_seg_init(a->tail, a->itemsz); a->head = a->tail->mem; ++a->nseg; } item = a->head; a->head = *((void **) item); return item; } HTM_INLINE void arena_free(struct arena * const a, void * const n) { *((void **) n) = a->head; a->head = n; } #endif /* FAST_ALLOC */ /* ================================================================ */ /* Phase 1: Produce data file from ASCII inputs */ /* ================================================================ */ /* An entry in an HTM tree. */ struct tree_entry { int64_t htmid; int64_t rowid; struct htm_sc sc; } HTM_ALIGNED(16); /* Tests whether tree entry e1 is less than e2; this is the same as testing whether the HTM ID of e1 is less than e2. Row IDs are used to break ties. */ HTM_INLINE int tree_entry_lt(const struct tree_entry *e1, const struct tree_entry *e2) { return (e1->htmid < e2->htmid || (e1->htmid == e2->htmid && e1->rowid < e2->rowid)); } /* Returns 1 if the first tree entry is less than the second. */ static int tree_entry_cmp(const void *e1, const void *e2) { return tree_entry_lt((const struct tree_entry *) e1, (const struct tree_entry *) e2); } /* ---- Quicksort of tree entries ---- */ static void tree_entry_isort(struct tree_entry *entries, size_t n) { size_t i, j, k; for (i = 0; i < n; ++i) { k = i; for (j = i + 1; j < n; ++j) { if (tree_entry_lt(&entries[j], &entries[k])) { k = j; } } if (k != i) { struct tree_entry tmp = entries[k]; entries[k] = entries[i]; entries[i] = tmp; } } } static void tree_entry_qsort(struct tree_entry *entries, size_t left, size_t right) { struct tree_entry pivot; size_t l, r, mid; while (1) { if (right <= left + 8) { tree_entry_isort(entries + left, right - left + 1); return; } /* find median-of-3 */ mid = left + ((right - left) >> 1); if (tree_entry_lt(entries + left, entries + mid)) { if (tree_entry_lt(entries + right, entries + left)) { mid = left; /* right, left, mid */ } else if (tree_entry_lt(entries + right, entries + mid)) { mid = right; /* left, right, mid */ } /* left, mid, right */ } else { if (tree_entry_lt(entries + left, entries + right)) { mid = left; /* mid, left, right */ } else if (tree_entry_lt(entries + mid, entries + right)) { mid = right; /* mid, right, left */ } /* right, mid, left */ } /* set pivot to median-of-3 and store at left-most array location */ pivot = entries[mid]; if (mid != left) { entries[mid] = entries[left]; entries[left] = pivot; } /* partition around pivot */ l = left; r = right; do { while (tree_entry_lt(&pivot, &entries[right])) { --right; if (left >= right) { goto end; } } entries[left] = entries[right]; do { ++left; if (left >= right) { left = right; goto end; } } while (tree_entry_lt(&entries[left], &pivot)); entries[right] = entries[left]; --right; } while (left < right); end: entries[left] = pivot; /* recurse on smaller partition */ if (2*left <= r + l) { if (l < left) { tree_entry_qsort(entries, l, left - 1); } ++left; right = r; } else { if (r > left) { tree_entry_qsort(entries, left + 1, r); } right = left - 1; left = l; } /* process larger partition without recursing to limit stack usage */ } } /* Sorts a memory block containing tree entries. */ static void tree_entry_sort(void *data, size_t nbytes) { size_t n; assert(((size_t) data) % 16 == 0 && "block pointer not aligned to a multiple of 16 bytes"); assert(nbytes % sizeof(struct tree_entry) == 0 && "block size not a multiple of sizeof(struct tree_entry)"); n = nbytes / sizeof(struct tree_entry); if (n > 1) { tree_entry_qsort((struct tree_entry *) data, 0, n - 1); } } /* ---- Convert text inputs to a block-sorted binary tree entry file ---- */ static char * eat_delim(char *s, char delim, const char *fname, size_t lineno) { for (; isspace(*s) && *s != delim; ++s) { } if (*s != delim) { err("[%s:%llu] - invalid/truncated record", fname, (unsigned long long) lineno); } return s + 1; } static char * eat_ws(char *s, char delim, const char *fname, size_t lineno) { for (; isspace(*s) && *s != delim; ++s) { } if (*s == delim || *s == '\0') { err("[%s:%llu] - invalid/truncated record", fname, (unsigned long long) lineno); } return s; } /* Converts ASCII input files to a block-sorted binary file. */ static size_t blk_sort_ascii(char **infile, const int nfile, const char *outfile, const char delim, const struct mem_params * const mem) { char line[16384]; size_t nentries; struct blk_writer *out; double ttot; int i; if (mem->sortsz % sizeof(struct tree_entry) != 0) { err("Write block size is not a multiple of " "sizeof(struct tree_entry)"); } msg("Creating block-sorted tree entry file %s from ASCII file(s)\n", outfile); ttot = now(); nentries = 0; out = blk_writer_init(outfile, mem->sortsz); /* For each input file... */ for (i = 0; i < nfile; ++i) { FILE *f; size_t lineno; struct tree_entry entry; struct htm_v3 v; double t; msg("\t- processing %s ... ", infile[i]); t = now(); /* open input file */ f = fopen(infile[i], "r"); if (f == NULL) { err("Failed to open file %s for reading", infile[i]); } for (lineno = 1; fgets(line, sizeof(line), f) != NULL; ++lineno) { char *s, *endptr; double lon, lat; size_t len = strlen(line); if (line[len - 1] != '\n') { if (feof(f) == 0) { err("Line %llu of file %s is too long (> %d characters)", (unsigned long long) lineno, infile[i], (int) sizeof(line)); } } s = eat_ws(line, delim, infile[i], lineno); entry.rowid = (int64_t) strtoll(s, &endptr, 0); if (endptr == s || endptr == NULL || errno != 0) { err("[%s:%llu] - failed to convert row_id to an integer", infile[i], (unsigned long long) lineno); } s = eat_delim(endptr, delim, infile[i], lineno); s = eat_ws(s, delim, infile[i], lineno); lon = strtod(s, &endptr); if (endptr == s || endptr == NULL || errno != 0) { err("[%s:%llu] - failed to convert right ascension/longitude " "to a double", infile[i], (unsigned long long) lineno); } s = eat_delim(endptr, delim, infile[i], lineno); s = eat_ws(s, delim, infile[i], lineno); lat = strtod(s, &endptr); if (endptr == s || endptr == NULL || errno != 0) { err("[%s:%llu] - failed to convert declination/latitude " "to a double", infile[i], (unsigned long long) lineno); } s = endptr; if (*s != delim && *s != '\0' && !isspace(*s)) { err("[%s:%llu] - invalid record", infile[i], (unsigned long long) lineno); } /* compute and store tree_entry for line */ if (htm_sc_init(&entry.sc, lon, lat) != HTM_OK) { err("[%s:%llu] - invalid spherical coordinates", infile[i], (unsigned long long) lineno); } if (htm_sc_tov3(&v, &entry.sc) != HTM_OK) { err("[%s:%llu] - failed to convert spherical coordinates " "to a unit vector", infile[i], (unsigned long long) lineno); } entry.htmid = htm_v3_id(&v, 20); if (entry.htmid == 0) { err("[%s:%llu] - failed to compute HTM ID for spherical " "coordinates", infile[i], (unsigned long long) lineno); } blk_writer_append(out, &entry, sizeof(struct tree_entry), &tree_entry_sort); } if (ferror(f) != 0) { err("failed to read file %s", infile[i]); } if (fclose(f) != 0) { err("failed to close file %s", infile[i]); } nentries += lineno - 1; msg("%llu records in %.3f sec\n", (unsigned long long) lineno, now() - t); /* advance to next input file */ } /* flush and close block writer */ blk_writer_close(out, &tree_entry_sort); msg("\t%.3f sec for %llu records total\n\n", now() - ttot, (unsigned long long) nentries); return nentries; } /* ================================================================ */ /* Phase 2: Tree generation and layout */ /* ================================================================ */ /* Number of levels-of-detail used by Split-and-Refine. */ #define NLOD 5 /* Tree layout block sizes in bytes, from largest to smallest. */ static const uint32_t layout_size[NLOD] = { 2097152, /* 2MiB: large page size for modern x86 processors. */ 65536, /* Between small and large page size. Chosen in hopes of improving OS disk prefetch effectiveness. */ 4096, /* 4KiB: default page size for modern x86 processors */ 256, /* Between cache line and small page sizes. Chosen in hopes of improving HW cache-line prefetch effectiveness. */ 64 /* L1/L2/L3 cache-line size for modern x86 processors. */ }; /* A node ID, consisting of NLOD block IDs (one per layout block size) and the index of the node in a post-order traversal. This last index makes node IDs unique (more than one node might fit in a block at the finest LOD). */ struct node_id { uint64_t block[NLOD + 1]; } HTM_ALIGNED(16); /* On-disk representation of a tree node. */ struct disk_node { struct node_id id; uint64_t count; uint64_t index; struct node_id child[4]; } HTM_ALIGNED(16); /* Returns 1 if the given node ID corresponds to an empty child (all block IDs are zero). */ HTM_INLINE int node_empty(const struct node_id * const id) { int i; for (i = 0; i < NLOD + 1; ++i) { if (id->block[i] != 0) { return 0; } } return 1; } /* Returns 1 if the given node IDs are equal. */ HTM_INLINE int node_id_eq(const struct node_id * const id1, const struct node_id * const id2) { int i; for (i = 0; i < NLOD + 1; ++i) { if (id1->block[i] != id2->block[i]) { return 0; } } return 1; } /* Returns 1 if the first node ID is less than the second. We say that a node N1 is less than N2 if the string of block IDs for N1 is lexicographically less than the string for N2. */ HTM_INLINE int node_id_lt(const struct node_id * const id1, const struct node_id * const id2) { int i; for (i = 0; i < NLOD + 1; ++i) { if (id1->block[i] < id2->block[i]) { return 1; } else if (id1->block[i] > id2->block[i]) { break; } } return 0; } /* Compares nodes by ID. */ HTM_INLINE int disk_node_lt(const struct disk_node *n1, const struct disk_node *n2) { return node_id_lt(&n1->id, &n2->id); } static int disk_node_cmp(const void *n1, const void * n2) { return disk_node_lt((const struct disk_node *) n1, (const struct disk_node *) n2); } /* ---- Quicksort of disk nodes ---- */ static void disk_node_isort(struct disk_node *nodes, size_t n) { size_t i, j, k; for (i = 0; i < n; ++i) { k = i; for (j = i + 1; j < n; ++j) { if (disk_node_lt(&nodes[j], &nodes[k])) { k = j; } } if (k != i) { struct disk_node tmp = nodes[k]; nodes[k] = nodes[i]; nodes[i] = tmp; } } } static void disk_node_qsort(struct disk_node *nodes, size_t left, size_t right) { struct disk_node pivot; size_t l, r, mid; while (1) { if (right <= left + 8) { disk_node_isort(nodes + left, right - left + 1); return; } /* find median-of-3 */ mid = left + ((right - left) >> 1); if (disk_node_lt(nodes + left, nodes + mid)) { if (disk_node_lt(nodes + right, nodes + left)) { mid = left; /* right, left, mid */ } else if (disk_node_lt(nodes + right, nodes + mid)) { mid = right; /* left, right, mid */ } /* left, mid, right */ } else { if (disk_node_lt(nodes + left, nodes + right)) { mid = left; /* mid, left, right */ } else if (disk_node_lt(nodes + mid, nodes + right)) { mid = right; /* mid, right, left */ } /* right, mid, left */ } /* set pivot to median-of-3 and store at left-most array location */ pivot = nodes[mid]; if (mid != left) { nodes[mid] = nodes[left]; nodes[left] = pivot; } /* partition around pivot */ l = left; r = right; do { while (disk_node_lt(&pivot, &nodes[right])) { --right; if (left >= right) { goto end; } } nodes[left] = nodes[right]; do { ++left; if (left >= right) { left = right; goto end; } } while (disk_node_lt(&nodes[left], &pivot)); nodes[right] = nodes[left]; --right; } while (left < right); end: nodes[left] = pivot; /* recurse on smaller partition */ if (2*left <= r + l) { if (l < left) { disk_node_qsort(nodes, l, left - 1); } ++left; right = r; } else { if (r > left) { disk_node_qsort(nodes, left + 1, r); } right = left - 1; left = l; } /* process larger partition without recursing to limit stack usage */ } } /* Sorts a memory block containing disk nodes. */ static void disk_node_sort(void *data, size_t nbytes) { size_t n; assert(((size_t) data) % 16 == 0 && "block pointer not aligned to a multiple of 16 bytes"); assert(nbytes % sizeof(struct disk_node) == 0 && "block size not a multiple of sizeof(struct disk_node)"); n = nbytes / sizeof(struct disk_node); if (n > 1) { disk_node_qsort((struct disk_node *) data, 0, n - 1); } } /* ---- In-memory node representation ---- */ /* Status of an in-memory tree node. */ enum node_status { NODE_INIT = 0, /* node is minty fresh */ NODE_EMITTED, /* node has been processed by emit_node() */ NODE_LAID_OUT, /* node has been processed by layout_node() */ }; /* In-memory representation of a tree node. Note that block size/depth is packed into a single 32 bit integer; as a result, nodes occupy exactly 256 bytes and are nicely cache aligned. */ struct mem_node { struct node_id id; /* Hierarchical ID for node */ int64_t htmid; /* HTM ID of node */ uint64_t index; /* File offset of first point in node */ uint64_t count; /* Number of points in node */ enum node_status status; uint32_t blockinfo[NLOD]; /* Clark & Munro: block depth (8 MSBs) and block size (24 LSBs) for each LOD. */ struct mem_node *child[4]; } HTM_ALIGNED(16); /* get/set block size/depth from 32 bit blockinfo */ HTM_INLINE uint32_t get_block_size(uint32_t blockinfo) { return blockinfo & 0xffffff; } HTM_INLINE uint8_t get_block_depth(uint32_t blockinfo) { return blockinfo >> 24; } HTM_INLINE uint32_t make_block_info(uint32_t size, uint8_t depth) { return (size & 0xffffff) | (((uint32_t) depth) << 24); } /* ---- Tree generation ---- */ /* Tree generation context. */ struct tree_gen_context { #if FAST_ALLOC struct arena ar; /* node memory allocator */ #endif size_t nnodes; /* number of nodes in the tree */ uint64_t leafthresh; /* maximum # of points per leaf */ uint64_t poidx; /* next post-order tree traversal index */ uint64_t blockid[NLOD]; /* index of next block ID to assign for each LOD */ struct blk_writer *wr; /* node writer */ }; static void tree_gen_context_init(struct tree_gen_context * const ctx, const uint64_t leafthresh, const char * const file, const size_t blksz) { int i; ctx->nnodes = 0; ctx->leafthresh = leafthresh; ctx->poidx = 0; for (i = 0; i < NLOD; ++i) { ctx->blockid[i] = 0; } #if FAST_ALLOC arena_init(&ctx->ar, sizeof(struct mem_node)); #endif ctx->wr = blk_writer_init(file, blksz); } static void tree_gen_context_destroy(struct tree_gen_context * const ctx) { #if FAST_ALLOC arena_destroy(&ctx->ar); #endif blk_writer_close(ctx->wr, &disk_node_sort); ctx->wr = NULL; } /* Assigns a block ID at the specified level-of-detail to all nodes in the sub-tree rooted at n that do not already have a block ID at that level-of-detail. When assigning a block ID to a node, check whether all block IDs are now valid and if so write the node out to disk. Children of nodes that are written are destroyed. */ static void assign_block(struct tree_gen_context * const ctx, struct mem_node * const n, const uint64_t blockid, const int lod) { int i; if (n->id.block[lod] != 0) { return; } /* visit children */ for (i = 0; i < 4; ++i) { if (n->child[i] != NULL) { assign_block(ctx, n->child[i], blockid, lod); } } n->id.block[lod] = blockid; for (i = 0; i < NLOD; ++i) { if (n->id.block[i] == 0) { return; } } /* write node to disk */ { struct disk_node d; d.id = n->id; d.count = n->count; d.index = n->index; for (i = 0; i < 4; ++i) { struct mem_node *tmp = n->child[i]; if (tmp != NULL) { /* copy id of child to disk node, throw away child */ d.child[i] = tmp->id; #if FAST_ALLOC arena_free(&ctx->ar, tmp); #else free(tmp); #endif n->child[i] = NULL; } else { memset(&d.child[i], 0, sizeof(struct node_id)); } } blk_writer_append(ctx->wr, &d, sizeof(struct disk_node), &disk_node_sort); ++ctx->nnodes; } } /* Estimates the compressed on-disk size of a tree node. */ static uint32_t estimate_node_size(const struct mem_node * const node, const uint32_t nchild) { uint32_t sz = htm_varint_len(node->index) + htm_varint_len(node->count); if (nchild > 0) { /* There is no way to compute size of a child offset accurately without knowing the final node layout, so use a guess of 4 bytes per non-empty child. The offset for an empty child (0) will will occupy exactly 1 byte, regardless of layout. */ sz += nchild*3 + 4; } return sz; } struct child_info { struct mem_node *node; uint32_t size; uint8_t depth; int8_t idx; }; /* Insertion sort of (at most 8) child_info structs; they are sorted by block depth and size. */ static void child_info_isort(struct child_info * const c, const int n) { if (n < 2) { return; } else { int i, j, k; for (i = 0; i < n; ++i) { k = i; for (j = i + 1; j < n; ++j) { if (c[j].depth < c[k].depth || (c[j].depth == c[k].depth && c[j].size < c[k].size)) { k = j; } } if (k != i) { struct child_info tmp = c[k]; c[k] = c[i]; c[i] = tmp; } } } } static void layout_node(struct mem_node * const node, struct tree_gen_context * const ctx) { struct child_info cinfo[4]; int c, nchild; if (node->status > NODE_EMITTED) { return; } /* visit children */ for (c = 0, nchild = 0; c < 4; ++c) { if (node->child[c] != NULL) { layout_node(node->child[c], ctx); cinfo[nchild].node = node->child[c]; cinfo[nchild].idx = c; ++nchild; } } /* update status and assign post-order index. */ node->status = NODE_LAID_OUT; node->id.block[5] = ++ctx->poidx; /* Clark & Munro at every level-of-detail */ if (nchild == 0) { /* leaf */ int lod; const uint32_t nodesz = estimate_node_size(node, nchild); const uint32_t info = make_block_info(nodesz, 1u); for (lod = 0; lod < NLOD; ++lod) { node->blockinfo[lod] = info; if (nodesz > layout_size[lod]) { uint64_t blockid = ++ctx->blockid[lod]; assign_block(ctx, node, blockid, lod); } } } else { /* internal node */ int lod; const uint32_t nodesz = estimate_node_size(node, nchild); for (lod = 0; lod < NLOD; ++lod) { uint64_t blockid; uint32_t totsz = nodesz; int close = 0, endclose = nchild; for (c = 0; c < nchild; ++c) { uint32_t s; struct mem_node *tmp = cinfo[c].node; s = get_block_size(tmp->blockinfo[lod]); cinfo[c].size = s; cinfo[c].depth = get_block_depth(tmp->blockinfo[lod]); totsz += s; } child_info_isort(cinfo, nchild); if (cinfo[0].depth == cinfo[nchild - 1].depth) { /* all children have the same block depth */ if (totsz <= layout_size[lod]) { /* children and parent all fit in one block; merge them */ node->blockinfo[lod] = make_block_info(totsz, cinfo[0].depth); continue; } else { /* cannot fit family into one block: scan children from smallest to largest, placing as many as possible in the same block as the parent. */ totsz = nodesz; for (close = 0; close < nchild - 1; ++close) { if (totsz + cinfo[close].size > layout_size[lod]) { break; } totsz += cinfo[close].size; } /* increase block depth of parent by 1 */ node->blockinfo[lod] = make_block_info(totsz, cinfo[0].depth + 1); } } else { /* nchild > 1, not all children have the same block depth */ totsz = nodesz; for (endclose = nchild - 1; endclose > 0; --endclose) { totsz += cinfo[endclose].size; if (cinfo[endclose - 1].depth != cinfo[nchild - 1].depth) { break; } } if (totsz < layout_size[lod]) { /* merge parent and largest-depth children */ node->blockinfo[lod] = make_block_info(totsz, cinfo[nchild - 1].depth); } else { /* fresh block for parent, increase block depth by 1 */ node->blockinfo[lod] = make_block_info(nodesz, cinfo[nchild - 1].depth + 1); endclose = nchild; } } /* scan remaining children from smallest to largest, merging runs of children into a single block where possible. */ totsz = cinfo[close].size; for (c = close + 1; c < endclose; ++c) { if (totsz + cinfo[c].size > layout_size[lod]) { blockid = ++ctx->blockid[lod]; for (; close < c; ++close) { assign_block(ctx, cinfo[close].node, blockid, lod); } totsz = cinfo[c].size; } else { totsz += cinfo[c].size; } } blockid = ++ctx->blockid[lod]; for (; close < endclose; ++close) { assign_block(ctx, cinfo[close].node, blockid, lod); } } } } /* Called on a node when all points belonging to it have been accounted for. */ static void emit_node(struct mem_node * const node, struct tree_gen_context * const ctx) { int c; if (node->status > NODE_INIT) { return; } /* visit children */ for (c = 0; c < 4; ++c) { if (node->child[c] != NULL) { emit_node(node->child[c], ctx); } } if (node->count < ctx->leafthresh) { /* if the node point count is too small, make it a leaf by deleting all children. */ for (c = 0; c < 4; ++c) { if (node->child[c] != NULL) { #if FAST_ALLOC arena_free(&ctx->ar, node->child[c]); #else free(node->child[c]); #endif node->child[c] = NULL; } } node->status = NODE_EMITTED; } else { /* otherwise, layout the subtree rooted at node */ layout_node(node, ctx); } } /* Adds a new node to root (one of S0,S1,S2,S3,N0,N1,N2,N3). */ static void add_node(struct mem_node * const root, struct tree_gen_context * const ctx, int64_t htmid, int64_t count, int64_t index) { struct mem_node *node; int lvl = 0; for (lvl = 0, node = root; lvl < 20; ++lvl) { /* keep subdividing */ int i, c; node->count += count; c = (htmid >> 2*(19 - lvl)) & 3; for (i = 0; i < c; ++i) { struct mem_node *tmp = node->child[i]; if (tmp != NULL && tmp->status == NODE_INIT) { emit_node(node->child[i], ctx); } } index -= node->index; /* relativize index */ if (node->child[c] != NULL) { node = node->child[c]; } else { /* create child node */ #if FAST_ALLOC struct mem_node *child = (struct mem_node *) arena_alloc(&ctx->ar); #else struct mem_node *child = (struct mem_node *) malloc(sizeof(struct mem_node)); if (child == NULL) { err("malloc() failed"); } #endif memset(child, 0, sizeof(struct mem_node)); child->index = index; child->htmid = node->htmid*4 + c; node->child[c] = child; node = child; } } assert(node->htmid == htmid); node->count = count; } /* Container for the 8 level-0 HTM tree nodes. */ struct tree_root { uint64_t count; /* Total number of points in tree */ struct mem_node *child[8]; struct node_id childid[8]; }; /* Assigns block IDs to the HTM root nodes. */ static void finish_root(struct tree_root * const super, struct tree_gen_context * const ctx) { struct child_info cinfo[8]; int c, close, nchild, lod; for (c = 0, nchild = 0; c < 8; ++c) { struct mem_node *tmp = super->child[c]; if (tmp != NULL) { super->count += tmp->count; cinfo[nchild].node = tmp; cinfo[nchild].idx = c; ++nchild; } } /* Clark & Munro for each level of detail */ for (lod = 0; lod < NLOD; ++lod) { uint64_t blockid; uint32_t totsz; for (c = 0; c < nchild; ++c) { struct mem_node *tmp = cinfo[c].node; cinfo[c].size = get_block_size(tmp->blockinfo[lod]); cinfo[c].depth = get_block_depth(tmp->blockinfo[lod]); } child_info_isort(cinfo, nchild); /* scan children from smallest to largest, merging as many as possible into blocks. */ close = 0; totsz = cinfo[0].size; for (c = 1; c < nchild; ++c) { if (totsz + cinfo[c].size > layout_size[lod]) { blockid = ++ctx->blockid[lod]; for (; close < c; ++close) { assign_block(ctx, cinfo[close].node, blockid, lod); } totsz = cinfo[c].size; } } blockid = ++ctx->blockid[lod]; for (; close < nchild; ++close) { assign_block(ctx, cinfo[close].node, blockid, lod); } } /* At this point, all nodes are guaranteed to have been written to disk. Copy HTM root node IDs to the super root and then throw them away. */ for (c = 0; c < nchild; ++c) { super->childid[cinfo[c].idx] = cinfo[c].node->id; #if FAST_ALLOC arena_free(&ctx->ar, cinfo[c].node); #else free(cinfo[c].node); #endif super->child[cinfo[c].idx] = NULL; } } /* Tree generation driver function. */ static size_t tree_gen(const char * const datafile, const char * const treefile, const struct mem_params * const mem, struct tree_root * const super, const uint64_t leafthresh, const size_t npoints) { struct tree_gen_context ctx; const struct tree_entry *data; void *behind; int64_t htmid; uint64_t index, count; size_t i, nseg; int r, fd; const size_t pagesz = (size_t) sysconf(_SC_PAGESIZE); size_t mapsz = npoints * sizeof(struct tree_entry); double t; if (npoints == 0) { err("no input points"); } msg("Generating block sorted tree node file %s from %s\n", treefile, datafile); t = now(); fd = open(datafile, O_RDONLY); if (fd == -1) { err("failed to open file %s for reading", datafile); } if (mapsz % pagesz != 0) { mapsz += pagesz - mapsz % pagesz; } behind = mmap(NULL, mapsz, PROT_READ, MAP_SHARED | MAP_NORESERVE, fd, 0); if (behind == MAP_FAILED) { err("mmap() file %s for reading", datafile); } if (madvise(behind, mapsz, MADV_SEQUENTIAL) != 0) { err("madvise() failed on mmap for file %s", datafile); } data = (const struct tree_entry *) behind; behind = ((unsigned char *) behind) + mem->ioblksz; tree_gen_context_init(&ctx, leafthresh, treefile, mem->sortsz); memset(super, 0, sizeof(struct tree_root)); /* walk over tree entries, adding tree nodes. */ if (data[0].htmid == 0) { err("invalid HTM ID"); } htmid = 0; index = 0; count = 0; r = -1; for (i = 0; i < npoints; ++i) { if ((void *) &data[i] > behind) { void *ptr = ((unsigned char *) behind) - mem->ioblksz; if (madvise(ptr, mem->ioblksz, MADV_DONTNEED) != 0) { err("madvise() failed"); } behind = ((unsigned char *) behind) + mem->ioblksz; } if (data[i].htmid == htmid) { /* increase point count for the current htmid */ ++count; } else { int r2; assert(data[i].htmid > htmid); if (r >= 0) { /* add previous node if there is one */ add_node(super->child[r], &ctx, htmid, count, (uint64_t) index); } /* reset index, count, and htmid */ count = 1; index = (uint64_t) i; htmid = data[i].htmid; r2 = (int) (htmid >> 40) - 8; if (r2 < 0 || r2 > 7) { err("invalid HTM ID"); } if (r != r2) { /* need a new HTM root node */ if (r >= 0) { /* emit and layout the previous root if there is one */ emit_node(super->child[r], &ctx); layout_node(super->child[r], &ctx); } r = r2; /* create new root */ #if FAST_ALLOC super->child[r] = (struct mem_node *) arena_alloc(&ctx.ar); #else super->child[r] = (struct mem_node *) malloc(sizeof(struct mem_node)); if (super->child[r] == NULL) { err("malloc() failed"); } #endif memset(super->child[r], 0, sizeof(struct mem_node)); super->child[r]->htmid = r + 8; super->child[r]->index = index; } } } /* add last node, emit and layout last root */ add_node(super->child[r], &ctx, htmid, count, (uint64_t) index); emit_node(super->child[r], &ctx); layout_node(super->child[r], &ctx); /* assign block IDs to the HTM roots */ finish_root(super, &ctx); if (super->count != npoints) { err("bug in tree generation phase - points not all accounted for"); } /* cleanup */ i = ctx.nnodes; nseg = ctx.ar.nseg; tree_gen_context_destroy(&ctx); if (munmap((void *) data, mapsz) != 0) { err("munmap() failed"); } if (close(fd) != 0) { err("close() failed"); } msg("\t%.3f sec total (%llu tree nodes, %llu MiB memory)\n\n", now() - t, (unsigned long long) i, (unsigned long long) (nseg*ARENA_SEGSZ)/(1024*1024)); return i; } /* ================================================================ */ /* Phase 3: Tree compression */ /* ================================================================ */ /* Mapping from a node ID to a relative file offset. */ struct id_off { struct node_id id; uint64_t off; struct id_off *next; } HTM_ALIGNED(16); /* Simple hash table that maps node IDs to relative file offsets. The implementation uses a power-of-2 sized backing array and chains on collision. The hash-code of a node ID is taken to be its post-order index (which is unique). */ struct hash_table { size_t n; size_t cap; struct id_off **array; #if FAST_ALLOC struct arena ar; #endif }; static void hash_table_init(struct hash_table *ht) { ht->cap = 65536; /* must be a power of 2 */ ht->n = 0; ht->array = (struct id_off **) malloc(ht->cap * sizeof(struct id_off *)); if (ht->array == NULL) { err("malloc() failed"); } memset(ht->array, 0, ht->cap * sizeof(struct id_off *)); #if FAST_ALLOC arena_init(&ht->ar, sizeof(struct id_off)); #endif } static void hash_table_destroy(struct hash_table *ht) { #if FAST_ALLOC arena_destroy(&ht->ar); #else size_t i; struct id_off *ptr; for (i = 0; i < ht->cap; ++i) { ptr = ht->array[i]; while (ptr != NULL) { struct id_off *next = ptr->next; free(ptr); ptr = next; } } #endif free(ht->array); ht->array = NULL; ht->n = 0; ht->cap = 0; } /* Grows hash table capacity by a factor of two. */ static void hash_table_grow(struct hash_table *ht) { size_t i, cap = ht->cap; struct id_off **array = ht->array; ht->cap = 2*cap; ht->array = (struct id_off **) malloc(ht->cap * sizeof(struct id_off *)); if (ht->array == NULL) { err("malloc() failed"); } memset(ht->array, 0, ht->cap * sizeof(struct id_off *)); /* add previous hash table entries */ for (i = 0; i < cap; ++i) { struct id_off *e = array[i]; while (e != NULL) { struct id_off *next = e->next; size_t j = (2*cap - 1) & (size_t) e->id.block[NLOD]; e->next = ht->array[j]; ht->array[j] = e; e = next; } } } /* Adds an id to offset mapping to the given hash table. */ static void hash_table_add(struct hash_table * const ht, const struct node_id * const id, uint64_t off) { struct id_off *e; size_t i; if ((ht->n*3)/4 > ht->cap) { hash_table_grow(ht); } i = (ht->cap - 1) & (size_t) id->block[NLOD]; #if FAST_ALLOC e = (struct id_off *) arena_alloc(&ht->ar); #else e = (struct id_off *) malloc(sizeof(struct id_off)); if (e == NULL) { err("malloc() failed"); } #endif e->id = *id; e->off = off; e->next = ht->array[i]; ht->array[i] = e; ++ht->n; } /* Returns the offset of the node with the given ID and removes the corresponding hash table entry. */ static uint64_t hash_table_get(struct hash_table * const ht, const struct node_id * const id) { struct id_off *e, *prev; const size_t i = (ht->cap - 1) & (size_t) id->block[NLOD]; prev = NULL; e = ht->array[i]; /* child must occur before parent */ while (1) { if (e == NULL) { err("tree generation bug: parent node written before child"); } if (node_id_eq(id, &e->id)) { uint64_t off = e->off; if (prev == NULL) { ht->array[i] = e->next; } else { prev->next = e->next; } #if FAST_ALLOC arena_free(&ht->ar, e); #else free(e); #endif --ht->n; return off; } prev = e; e = e->next; } /* never reached */ } /* Writes out a tree node (byte reversed). */ static uint64_t compress_node(struct hash_table * const ht, struct blk_writer * const wr, const struct disk_node * const n, const uint64_t filesz, const uint64_t leafthresh) { unsigned char buf[48]; unsigned char *s = buf; uint64_t sz = filesz; unsigned int v; int c, leaf; /* write out child offsets (from child 3 to child 0) */ for (c = 3, leaf = 1; c >= 0; --c) { if (node_empty(&n->child[c])) { *s = 0; ++s; ++sz; } else { /* this is tricky - child 3 of n can be laid out immediately after n, yielding a child offset of 0. But 0 also means "empty child", so instead encode the actual offset + 1. */ v = htm_varint_rencode(s, sz + 1 - hash_table_get(ht, &n->child[c])); s += v; sz += v; leaf = 0; } } if (leaf != 0) { /* n is a leaf: don't store child offsets */ s -= 4; sz -= 4; } else if (n->count < leafthresh) { err("tree generation bug: internal node contains too few points"); } /* write out relative index, then count */ v = htm_varint_rencode(s, n->index); s += v; sz += v; v = htm_varint_rencode(s, n->count); s += v; sz += v; /* write out byte reversed node, add node id to hashtable */ blk_writer_append(wr, buf, (size_t) (s - buf), NULL); hash_table_add(ht, &n->id, sz); return sz; } /* Writes out a tree header (byte reversed). */ static uint64_t write_tree_header(struct hash_table * const ht, struct blk_writer * const wr, const struct tree_root * const super, const uint64_t filesz, const uint64_t leafthresh) { unsigned char buf[96]; unsigned char *s; uint64_t sz; int r; unsigned int v; /* write offsets of N3, N2, N1, N0, S3, S2, S1, S0 */ for (r = 7, s = buf, sz = filesz; r >= 0; --r) { if (node_empty(&super->childid[r])) { *s = 0; ++s; ++sz; } else { /* N3 could be laid out immediately after super root, yielding a child offset of 0, which means "empty child". Therefore encode 1 + actual offset. */ v = htm_varint_rencode( s, sz + 1 - hash_table_get(ht, &super->childid[r])); s += v; sz += v; } } /* write total number of points in tree */ v = htm_varint_rencode(s, super->count); s += v; sz += v; /* write leaf threshold */ v = htm_varint_rencode(s, leafthresh); s += v; sz += v; blk_writer_append(wr, buf, (size_t) (s - buf), NULL); if (ht->n != 0) { err("tree compression bug: node id hash table non-empty"); } return sz; } /* Tree compression driver function. */ static uint64_t tree_compress(const char * const treefile, const char * const scratchfile, const struct mem_params * const mem, const struct tree_root * const super, const size_t nnodes, const uint64_t leafthresh) { struct hash_table ht; struct blk_writer *wr; const struct disk_node *data; void *behind; double t; size_t i; uint64_t filesz; int fd; const size_t pagesz = (size_t) sysconf(_SC_PAGESIZE); size_t mapsz = nnodes * sizeof(struct disk_node); if (nnodes == 0) { err("no input nodes"); } t = now(); msg("Generating reversed compressed tree node file %s from %s\n", scratchfile, treefile); fd = open(treefile, O_RDONLY); if (fd == -1) { err("failed to open file %s for reading", treefile); } if (mapsz % pagesz != 0) { mapsz += pagesz - mapsz % pagesz; } behind = mmap(NULL, mapsz, PROT_READ, MAP_SHARED | MAP_NORESERVE, fd, 0); if (behind == MAP_FAILED) { err("mmap() file %s for reading", treefile); } if (madvise(behind, mapsz, MADV_SEQUENTIAL) != 0) { err("madvise() failed on mmap for file %s", treefile); } data = (const struct disk_node *) behind; behind = ((unsigned char *) behind) + mem->ioblksz; hash_table_init(&ht); wr = blk_writer_init(scratchfile, mem->ioblksz); /* write nodes */ for (i = 0, filesz = 0; i < nnodes; ++i) { if (i > 0) { assert(disk_node_lt(&data[i - 1], &data[i]) && "tree node file not sorted"); } if ((void *) &data[i] > behind) { void *ptr = ((unsigned char *) behind) - mem->ioblksz; if (madvise(ptr, mem->ioblksz, MADV_DONTNEED) != 0) { err("madvise() failed"); } behind = ((unsigned char *) behind) + mem->ioblksz; } filesz = compress_node(&ht, wr, &data[i], filesz, leafthresh); } /* and tree header */ filesz = write_tree_header(&ht, wr, super, filesz, leafthresh); /* cleanup */ blk_writer_close(wr, NULL); hash_table_destroy(&ht); if (munmap((void *) data, mapsz) != 0) { err("munmap() failed"); } if (close(fd) != 0) { err("close() failed"); } msg("\t%.3f sec total\n\n", now() - t); return filesz; } /* Byte reverses an input file to an output file and removes the input file. */ static void reverse_file(const char * const infile, const char * const outfile, const struct mem_params * const mem, const uint64_t filesz) { const unsigned char *data; struct blk_writer *wr; double t; uint64_t i, j; int fd; const size_t pagesz = (size_t) sysconf(_SC_PAGESIZE); size_t mapsz = filesz; if (filesz == 0) { err("cannot reverse an empty file"); } msg("Reversing file %s to produce %s\n", infile, outfile); t = now(); fd = open(infile, O_RDONLY); if (fd == -1) { err("failed to open file %s for reading", infile); } if (mapsz % pagesz != 0) { mapsz += pagesz - mapsz % pagesz; } data = (const unsigned char *) mmap(NULL, mapsz, PROT_READ, MAP_SHARED | MAP_NORESERVE, fd, 0); if ((void *) data == MAP_FAILED) { err("failed to mmap() file %s", infile); } wr = blk_writer_init(outfile, mem->ioblksz); j = mem->ioblksz * (filesz / mem->ioblksz); if (j == filesz) { j -= mem->ioblksz; } for (i = filesz - 1; i > 0; --i) { blk_writer_append(wr, &data[i], 1, NULL); if (i == j) { size_t sz = filesz - j; if (sz > mem->ioblksz) { sz = mem->ioblksz; } madvise((void *) &data[i], sz, MADV_DONTNEED); j -= mem->ioblksz; } } blk_writer_append(wr, data, 1, NULL); blk_writer_close(wr, NULL); if (munmap((void *) data, mapsz) != 0) { err("munmap() failed"); } if (close(fd) != 0) { err("close() failed"); } if (unlink(infile) != 0) { err("failed to delete file %s", infile); } msg("\t%.3f sec total\n\n", now() - t); } /* ================================================================ */ /* Phase 4: Convert spherical coords to unit vectors */ /* ================================================================ */ static void spherical_to_vec(const char * const datafile, const char * const scratchfile, const struct mem_params * const mem, const size_t npoints) { const struct tree_entry *data; struct blk_writer *wr; void *behind; double t; size_t i; int fd; const size_t pagesz = (size_t) sysconf(_SC_PAGESIZE); size_t mapsz = sizeof(struct tree_entry) * npoints; if (mapsz == 0) { err("Empty data file"); } msg("Converting spherical coordinates in %s to unit vectors\n", datafile); t = now(); fd = open(datafile, O_RDONLY); if (fd == -1) { err("failed to open file %s for reading", datafile); } if (mapsz % pagesz != 0) { mapsz += pagesz - mapsz % pagesz; } behind = mmap(NULL, mapsz, PROT_READ, MAP_SHARED | MAP_NORESERVE, fd, 0); if (behind == MAP_FAILED) { err("failed to mmap() file %s", datafile); } if (madvise(behind, mapsz, MADV_SEQUENTIAL) != 0) { err("madvise() failed"); } data = (const struct tree_entry *) behind; behind = ((unsigned char *) behind) + mem->ioblksz; wr = blk_writer_init(scratchfile, mem->ioblksz); for (i = 0; i < npoints; ++i) { struct htm_tree_entry e; if ((void *) &data[i] > behind) { void *ptr = ((unsigned char *) behind) - mem->ioblksz; if (madvise(ptr, mem->ioblksz, MADV_DONTNEED) != 0) { err("madvise() failed"); } behind = ((unsigned char *) behind) + mem->ioblksz; } htm_sc_tov3(&e.v, &data[i].sc); e.rowid = data[i].rowid; blk_writer_append(wr, &e, sizeof(struct htm_tree_entry), NULL); } blk_writer_close(wr, NULL); if (munmap((void *) data, mapsz) != 0) { err("munmap() failed"); } if (close(fd) != 0) { err("close() failed"); } if (rename(scratchfile, datafile) != 0) { err("failed to rename file %s to %s", scratchfile, datafile); } msg("\t%.3f sec total\n\n", now() - t); }
31.961932
96
0.532472
[ "geometry", "vector" ]
026d49eef87ba7ae3384c4d9b5690f1bc6e3ec95
10,295
h
C
src/gridtools_verification/verification/field_collection.h
GridTools/gridtools_verification
1c8b12d53a074c7c2ad380d59e3a0a3158082f1e
[ "BSD-3-Clause" ]
null
null
null
src/gridtools_verification/verification/field_collection.h
GridTools/gridtools_verification
1c8b12d53a074c7c2ad380d59e3a0a3158082f1e
[ "BSD-3-Clause" ]
null
null
null
src/gridtools_verification/verification/field_collection.h
GridTools/gridtools_verification
1c8b12d53a074c7c2ad380d59e3a0a3158082f1e
[ "BSD-3-Clause" ]
null
null
null
/* * GridTools * * Copyright (c) 2014-2019, ETH Zurich * All rights reserved. * * Please, refer to the LICENSE file in the root directory. * SPDX-License-Identifier: BSD-3-Clause */ #pragma once #include "../common.h" #include "../core/error.h" #include "../core/logger.h" #include "../core/serialization.h" #include "../core/type_erased_field.h" #include "../verification_exception.h" #include "boundary_extent.h" #include "error_metric_interface.h" #include "verification.h" #include "verification_reporter.h" #include "verification_result.h" #include "verification_specification.h" #include <vector> namespace gt_verification { namespace internal { struct savepoint_pair { template < class SavePointType > savepoint_pair(SavePointType &&_input, SavePointType &&_output) : input(std::forward< SavePointType >(_input)), output(std::forward< SavePointType >(_output)) {} ser::savepoint input; ser::savepoint output; }; template < typename T > class input_field { public: input_field(std::string name, gt_verification::type_erased_field_view< T > field_view, bool also_previous) : name_(name), field_view_(field_view), also_previous_(also_previous) {} std::string name() const noexcept { return name_; } gt_verification::type_erased_field_view< T > field_view() const noexcept { return field_view_; } bool also_previous() const noexcept { return also_previous_; } private: const std::string name_; const gt_verification::type_erased_field_view< T > field_view_; const bool also_previous_; }; } /** * @brief A collection of serialized fields * * @ingroup DycoreUnittestVerificationLibrary */ template < typename T > class field_collection { public: field_collection(verification_specification verificationSpecification) : verificationSpecification_(verificationSpecification){}; /** * @brief Attach a reference serializer to the collection. * * After this, input and reference sources can be registred within the collection via * FieldCollection::registerInputField and FieldCollection::registerOutputAndRefrenceField. * The serializer must be already open in read mode. The serializer is searched for all * savepoints whose name correponds to the @c outSavepointName parameter and for all * corresponding input savepoints. * * @param serializer The serializer that loads the reference data * @param outSavepointName The name of the savepoint where the reference values are stored * @param inSavepointName The name of the savepoint where the input values are stored */ void attach_reference_serializer(std::shared_ptr< ser::serializer > serializer, const std::string &inSavepointName, const std::string &outSavepointName) { referenceSerializer_ = serializer; const std::vector< ser::savepoint > &savepoints = referenceSerializer_->savepoints(); iterations_.clear(); for (auto it = savepoints.cbegin(), end = savepoints.cend(); it != end; ++it) { if (it->name() == outSavepointName) { // Output savepoint is found, now search input savepoint auto rit = std::reverse_iterator< decltype(it) >(it); while (rit != savepoints.rend()) { if (rit->name() == inSavepointName) // Pair found, finish search break; ++rit; } if (rit != savepoints.rend()) iterations_.push_back(internal::savepoint_pair(*rit, *it)); } } } /** * @brief Attach an error serializer to the collection which will be used to serialize the * error result to disk [not implemented] * * @param serializer The serializer which will be used to serialization * (in SerializerOpenModeWrite) */ void attach_error_serializer(std::shared_ptr< ser::serializer > serializer) { errorSerializer_ = serializer; } /** * @brief Register an input field which will be filled during the loadIteration() function * * @param fieldname The name of the field as registered in the reference serializer * @param field The field that has to be filled with data from disk */ template < typename FieldType > void register_input_field(const std::string &fieldname, FieldType field, bool also_previous = false) noexcept { field.sync(); inputFields_.push_back( internal::input_field< T >{fieldname, type_erased_field_view< T >(field), also_previous}); } /** * @brief Register an output field for verification * * The registered output field will be validated against a newly allocate reference field which * is going to be loaded from disk (using the reference serializer). * * @param fieldname The name of the field as serialized * @param field The field that has to be checked * @param metric The metric which is used to check the field */ template < typename FieldType > void register_output_and_reference_field( const std::string &fieldname, FieldType field, boundary_extent boundary = boundary_extent()) noexcept { field.sync(); boundaries_.push_back(boundary); outputFields_.push_back(std::make_pair(fieldname, type_erased_field_view< T >(field))); // Construct new field holding the reference data referenceFields_.push_back(std::make_pair(fieldname, type_erased_field< T >(field))); } /** * @brief Loads input values and reference values from disk into the input- and reference fields * * After this the computations and verification can take place. */ void load_iteration(int iteration) { if (iteration >= (int)iterations_.size()) error::fatal(boost::format("invalid access of iteration '%i' (there are only %i iterations)") % iteration % iterations_.size()); serialization serialization(referenceSerializer_); auto inputSavepoint = iterations_[iteration].input; auto refSavepoint = iterations_[iteration].output; try { // Load input fields VERIFICATION_LOG() << "Loading input savepoint '" << inputSavepoint << "'" << logger_action::endl; for (auto &inputFieldPair : inputFields_) serialization.load(inputFieldPair.name(), inputFieldPair.field_view(), inputSavepoint, inputFieldPair.also_previous()); // Load reference fields VERIFICATION_LOG() << "Loading reference savepoint '" << refSavepoint << "'" << logger_action::endl; for (auto &refFieldPair : referenceFields_) serialization.load(refFieldPair.first, refFieldPair.second.to_view(), refSavepoint); } catch (verification_exception &e) { error::fatal(e.what()); } } /** * @brief Verifies all output sources and collects the result * * This function discards all previous recorded errors. To get a list of occured errors use * FieldCollection::reportFailures(). * * @return VerificationResult */ verification_result verify(const error_metric_interface< T > &error_metric) { verifications_.clear(); verification_result totalResult(true, "\n"); // Iterate over output fields and compare them to the reference fields for (std::size_t i = 0; i < outputFields_.size(); ++i) { verifications_.emplace_back( outputFields_[i].second, referenceFields_[i].second.to_view(), boundaries_[i]); // Perform actual verification and merge results totalResult.merge(verifications_.back().verify(error_metric)); } return totalResult; } /** * @brief Report failures depending on values set in VerificationReporter */ void report_failures() const noexcept { verification_reporter verificationReporter(verificationSpecification_); for (const auto &verification : verifications_) if (!verification) { verificationReporter.report(verification); } } /** * @brief Get the reference serializer */ std::shared_ptr< ser::serializer > reference_serializer() const noexcept { return referenceSerializer_; } /** * @brief Get the error serializer */ std::shared_ptr< ser::serializer > error_serializer() const noexcept { return errorSerializer_; } /** * @brief Get a const reference of the iterations */ const std::vector< internal::savepoint_pair > &iterations() const noexcept { return iterations_; } private: std::string name_; std::shared_ptr< ser::serializer > referenceSerializer_; std::shared_ptr< ser::serializer > errorSerializer_; std::vector< internal::savepoint_pair > iterations_; std::vector< internal::input_field< T > > inputFields_; std::vector< std::pair< std::string, type_erased_field_view< T > > > outputFields_; std::vector< std::pair< std::string, type_erased_field< T > > > referenceFields_; std::vector< boundary_extent > boundaries_; verification_specification verificationSpecification_; std::vector< verification< T > > verifications_; }; }
41.345382
119
0.610296
[ "vector" ]
026e9c6c8e13f8ff8e8ba1d47305ad53b380e247
4,611
c
C
main.c
robtech21/d-cpuminer
8f79beb9b44d47dbfcdb749714c8e3fafc0b8df4
[ "MIT" ]
2
2020-11-05T14:04:27.000Z
2020-11-18T10:38:30.000Z
main.c
robtech21/d-cpuminer
8f79beb9b44d47dbfcdb749714c8e3fafc0b8df4
[ "MIT" ]
5
2020-11-12T17:05:07.000Z
2022-02-04T11:56:25.000Z
main.c
robtech21/d-cpuminer
8f79beb9b44d47dbfcdb749714c8e3fafc0b8df4
[ "MIT" ]
3
2020-11-12T16:56:20.000Z
2022-02-04T11:57:29.000Z
#include <stdio.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #include <string.h> #include <netdb.h> #include <openssl/sha.h> #include <stdlib.h> #include <pthread.h> #ifdef _WIN32 #include <Windows.h> #else #include <unistd.h> #endif #define serverip "51.15.127.80" const unsigned int serverport = 2811; char *itoa (int num, char *str) { /* Int to string */ if (str == NULL) return NULL; sprintf(str, "%d", num); return str; } int main (int argc, char **argv) { time_t start_t, end_t; double diff_t; char job_message[64] = "JOB,"; char* requested_difficulty = ",LOW"; char serverversion[3]; // server ver is always 3 chars char serverreply[40 + 1 + 40 + 1 + 8]; // 2x sha1s, 2x commas, difficulty, \n char username[32] = ""; unsigned int rejected_shares = 0; unsigned int accepted_shares = 0; unsigned int hashrate = 0; int socket_desc; struct sockaddr_in server; printf("\033[1;33md-cpuminer\n\033[1;35mby phantom32 and revox 2020-2021\n"); printf("\033[0m----------\n"); /* Create socket object */ socket_desc = socket(AF_INET , SOCK_STREAM , 0); if (socket_desc == -1) { printf("Error: Couldn't create socket\n"); return 1; } if (argc < 2) { printf("Enter your DUCO username (you can also pass it when launching the miner: ./d-cpuminer username): "); scanf("%s", username); } else sprintf(username, argv[1], "%s"); // Get username from sys argv printf("Continuing as user %s\n", username); /* Establish connection to the server */ printf("Connecting\n"); server.sin_addr.s_addr = inet_addr(serverip); server.sin_family = AF_INET; server.sin_port = htons(serverport); if (connect(socket_desc, (struct sockaddr *)&server, sizeof(server)) < 0) { printf("Error: Couldn't connect to the server\n"); return 1; } else printf("Connected to the server\n"); if (recv(socket_desc, serverversion, 3, 0) < 0) { printf("Error: Server version couldn't be received\n"); return 1; } else printf("Server is on version: %s\n\n", serverversion); /* Combine job request message */ strcat(job_message, username); strcat(job_message, requested_difficulty); printf("Mining started using DUCO-S1 algorithm\n"); while (1) { if (send(socket_desc, job_message, strlen(job_message), 0) < 0) { printf("Error: Couldn't send JOB message\n"); return 1; } if (recv(socket_desc, serverreply, 40 + 1 + 40 + 1 + 8, 0) < 0) { printf("Error: Couldn't receive job\n"); return 1; } /* Split received data */ char* job = strtok (serverreply, ","); char* work = strtok (NULL, ","); char* diff = strtok (NULL, ""); char ducos1_result_string[10] = ""; //printf("\nRecived data:\n"); //printf("JOB: %s\n", job); //printf("JOB2: %s\n", work); //printf("DIFF: %s\n", diff); time(&start_t); // measure starting time for (int i = 0; i < (100 * atoi(diff)) + 1; i++) { char str_to_hash[128] = ""; strcat(str_to_hash, job); itoa(i, ducos1_result_string); strcat(str_to_hash, ducos1_result_string); //printf("String to hash: %s\n", str_to_hash); unsigned char temp[SHA_DIGEST_LENGTH]; char buf[SHA_DIGEST_LENGTH * 2]; memset(buf, 0x0, SHA_DIGEST_LENGTH * 2); memset(temp, 0x0, SHA_DIGEST_LENGTH); SHA1((unsigned char *)str_to_hash, strlen(str_to_hash), temp); long iZ = 0; for (iZ = 0; iZ < SHA_DIGEST_LENGTH; iZ++) sprintf((char*) & (buf[iZ * 2]), "%02x", temp[iZ]); //printf("Hashed res : %s\n", buf); //printf("Expected res : %s\n\n", work); if (strcmp(work, buf) == 0) { //printf("Found share! %s\n", ducos1_result_string); /* Calculate hashrate */ time(&end_t); diff_t = difftime(end_t, start_t); hashrate = (atoi(ducos1_result_string) / diff_t) / 1000; if (send(socket_desc, ducos1_result_string, strlen(ducos1_result_string), 0) < 0) { //send result printf("Error: Couldn't send result\n"); return 1; } char feedback[6] = ""; if (recv(socket_desc, feedback, 6, 0) < 0) { // receive feedback printf("Error: Feedback couldn't be received\n"); return 1; } //printf("Feedback: %s\n", feedback); if (strcmp("GOOD\n", feedback) == 0 || strcmp("BLOCK\n", feedback) == 0) { accepted_shares++; printf("Accepted share #%i (%s) %i kH/s\n", accepted_shares, ducos1_result_string, hashrate); } else if (strcmp("INVU\n", feedback) == 0) { printf("Error: Incorrect username\n"); return 1; } else { rejected_shares++; printf("Rejected share #%i (%s) %i kH/s\n", rejected_shares, ducos1_result_string, hashrate); } break; } } } return 0; }
27.446429
110
0.640642
[ "object" ]
0273ef39da34de85b8c4c46c5a01cb347b84e85e
4,436
c
C
examples/hello_acquaintances/hello_acq.c
GeneAssembly/biosal
a18d6d08f1b31dfd78a6c1d1c5af8d7bb6e91584
[ "BSD-2-Clause" ]
9
2015-05-13T15:58:08.000Z
2021-01-07T12:06:11.000Z
examples/hello_acquaintances/hello_acq.c
sebhtml/biosal
a18d6d08f1b31dfd78a6c1d1c5af8d7bb6e91584
[ "BSD-2-Clause" ]
8
2015-01-08T19:05:33.000Z
2015-04-03T21:14:28.000Z
examples/hello_acquaintances/hello_acq.c
GeneAssembly/biosal
a18d6d08f1b31dfd78a6c1d1c5af8d7bb6e91584
[ "BSD-2-Clause" ]
2
2015-10-02T17:29:48.000Z
2018-01-26T12:36:10.000Z
/* * hello_acq.c: * A distributed version of Hello, World, works as follows: * - There are many possible ways to say a distributed "hello" * - original hello.c is a great example: each of the initial actors says hello! * only issue: no coordination involved, so it is more of a straight parallel example * - this hello works by having the first actor in the list say hello to the other n-1 actors * - a state vector of which of the n-1 peers has been greeted is sent from one actor to the next * - when an actor is greeted, we indicate this by negating the (int) actor name. I would prefer to use * a map but don't know whether we have pack/unpack yet. (It's also easier to send vectors in Thorium right now.) * - when all of the n-1 peers have been greeted, each will have a negative entry in the state vector * - when an actor is greeted, it has nothing left to do and can stop * - the lone remaining actor will be the originator of the first hello message. * */ #include "hello_acq.h" #include <stdio.h> #include <stdlib.h> void hello_acq_init(struct thorium_actor *self); void hello_acq_destroy(struct thorium_actor *self); void hello_acq_receive(struct thorium_actor *self, struct thorium_message *message); struct thorium_script hello_acq_script = { .identifier = SCRIPT_HELLO_ACQ, .init = hello_acq_init, .destroy = hello_acq_destroy, .receive = hello_acq_receive, .size = sizeof(struct hello_acq), .name = "hello" }; void hello_acq_init(struct thorium_actor *actor) { struct hello_acq *hello1; hello1 = (struct hello_acq *)thorium_actor_concrete_actor(actor); core_vector_init(&hello1->initial_helloes, sizeof(int)); core_vector_init(&hello1->actors_to_greet, sizeof(int)); } void hello_acq_destroy(struct thorium_actor *actor) { struct hello_acq *hello1; hello1 = (struct hello_acq *)thorium_actor_concrete_actor(actor); core_vector_destroy(&hello1->initial_helloes); core_vector_destroy(&hello1->actors_to_greet); } void hello_acq_receive(struct thorium_actor *actor, struct thorium_message *message) { int tag; int name; void *buffer; struct hello_acq *hello1; int i; hello1 = (struct hello_acq *)thorium_actor_concrete_actor(actor); tag = thorium_message_action(message); name = thorium_actor_name(actor); buffer = thorium_message_buffer(message); if (tag == ACTION_START) { core_vector_unpack(&hello1->initial_helloes, buffer); if (core_vector_at_as_int(&hello1->initial_helloes, 0) == name) { printf("Actor %d initiating greetings to its initial peers (below, if present):\n", name); core_vector_print_int(&hello1->initial_helloes); printf("\n"); thorium_actor_send_vector(actor, name, ACTION_HELLO_ACQ_GREET_OTHERS, &hello1->initial_helloes); } } else if (tag == ACTION_HELLO_ACQ_GREET_OTHERS) { int actor_name = -1; core_vector_unpack(&hello1->actors_to_greet, buffer); printf("Actor %d received state vector of peers remaining to be greeted (negative means already greeted):\n", name); core_vector_print_int(&hello1->actors_to_greet); printf("\n"); /* replace with map that knows all actors that have been greeted */ for (i = 1; i < core_vector_size(&hello1->actors_to_greet); i++) { actor_name = core_vector_at_as_int(&hello1->actors_to_greet, i); if (actor_name >= 0) break; } if (actor_name < 0) { /* int greeter = core_vector_at_as_int(&hello1->actors_to_greet, 0); */ thorium_actor_send_to_self_empty(actor, ACTION_HELLO_ACQ_PEER); printf("\n"); } else { core_vector_set_int(&hello1->actors_to_greet, i, -actor_name); /* flip sign to indicate we greeted it. */ core_vector_print_int(&hello1->actors_to_greet); printf("\n"); thorium_actor_send_vector(actor, actor_name, ACTION_HELLO_ACQ_GREET_OTHERS, &hello1->actors_to_greet); thorium_actor_send_to_self_empty(actor, ACTION_HELLO_ACQ_PEER); printf("\n"); } } else if (tag == ACTION_HELLO_ACQ_PEER) { printf("Hello, World (received by %d).\n\n", name); thorium_actor_send_to_self_empty(actor, ACTION_STOP); } }
39.963964
124
0.676736
[ "vector" ]
027679aaec6c2dc4b4aa76628caf369be31adfd3
2,407
h
C
Programs/QuickEd/Classes/Modules/LibraryModule/Private/LibraryModel.h
stinvi/dava.engine
2b396ca49cdf10cdc98ad8a9ffcf7768a05e285e
[ "BSD-3-Clause" ]
26
2018-09-03T08:48:22.000Z
2022-02-14T05:14:50.000Z
Programs/QuickEd/Classes/Modules/LibraryModule/Private/LibraryModel.h
ANHELL-blitz/dava.engine
ed83624326f000866e29166c7f4cccfed1bb41d4
[ "BSD-3-Clause" ]
null
null
null
Programs/QuickEd/Classes/Modules/LibraryModule/Private/LibraryModel.h
ANHELL-blitz/dava.engine
ed83624326f000866e29166c7f4cccfed1bb41d4
[ "BSD-3-Clause" ]
45
2018-05-11T06:47:17.000Z
2022-02-03T11:30:55.000Z
#pragma once #include "Base/BaseTypes.h" #include "Base/RefPtr.h" #include "Model/PackageHierarchy/PackageListener.h" #include <QStandardItemModel> class PackageNode; class PackageBaseNode; class AbstractProperty; class ControlNode; class ControlsContainerNode; class ImportedPackagesNode; namespace DAVA { class UI; class ContextAccessor; } class LibraryModel : public QStandardItemModel, PackageListener { Q_OBJECT enum { POINTER_DATA = Qt::UserRole + 1, PROTOTYPE }; public: LibraryModel(DAVA::UI* ui, DAVA::ContextAccessor* accessor, QObject* parent = nullptr); ~LibraryModel() override; void SetLibraryPackages(const DAVA::Vector<DAVA::RefPtr<PackageNode>>& libraryPackages); Qt::ItemFlags flags(const QModelIndex& index) const override; QStringList mimeTypes() const override; QMimeData* mimeData(const QModelIndexList& indexes) const override; void SetPackageNode(PackageNode* package); QModelIndex GetDefaultControlsModelIndex() const; private: QVariant data(const QModelIndex& index, int role) const override; QModelIndex indexByNode(const void* node, const QStandardItem* item) const; void AddControl(ControlNode* node, QStandardItem* rootItem, bool makePrototype); void AddPackageControls(PackageControlsNode* packageControls, QStandardItem* rootItem, bool makePrototype); QStandardItem* CreatePackageControlsItem(PackageNode* package, bool makePrototype); //Package Signals void ControlPropertyWasChanged(ControlNode* node, AbstractProperty* property) override; void ControlWasAdded(ControlNode* node, ControlsContainerNode* destination, int row) override; void ControlWillBeRemoved(ControlNode* node, ControlsContainerNode* from) override; void ImportedPackageWasAdded(PackageNode* node, ImportedPackagesNode* to, int index) override; void ImportedPackageWillBeRemoved(PackageNode* node, ImportedPackagesNode* from) override; DAVA::RefPtr<PackageNode> package; DAVA::Vector<DAVA::RefPtr<PackageNode>> libraryPackages; DAVA::Vector<QStandardItem*> libraryRootItems; QStandardItem* defaultControlsRootItem = nullptr; QStandardItem* controlsRootItem = nullptr; QStandardItem* importedPackageRootItem = nullptr; DAVA::Vector<DAVA::RefPtr<ControlNode>> defaultControls; DAVA::UI* ui = nullptr; DAVA::ContextAccessor* accessor = nullptr; };
33.901408
111
0.770669
[ "vector", "model" ]
028fa3f72c080d8e18e08fbc88bbfb1d4ac280ac
535
h
C
include/Chapter.h
bibo5088/mangadex-downloader
8a33bf3850808d6d111224a61e54c9c4e538d64a
[ "MIT" ]
5
2019-08-29T13:29:33.000Z
2020-11-30T19:03:23.000Z
include/Chapter.h
bibo5088/mangadex-downloader
8a33bf3850808d6d111224a61e54c9c4e538d64a
[ "MIT" ]
2
2020-04-20T21:59:41.000Z
2020-05-12T09:02:19.000Z
include/Chapter.h
bibo5088/mangadex-downloader
8a33bf3850808d6d111224a61e54c9c4e538d64a
[ "MIT" ]
1
2020-01-05T07:19:43.000Z
2020-01-05T07:19:43.000Z
#ifndef MANGADEX_DOWNLOADER_CHAPTER_H #define MANGADEX_DOWNLOADER_CHAPTER_H #include <string> #include <filesystem> #include <nlohmann/json.hpp> struct Chapter { int id; std::string volume; std::string chapter; std::string title; std::string lang_code; int manga_id; std::vector<std::string> pages_urls; static Chapter from_json(const nlohmann::json &); void download_pages(const std::filesystem::path &output_dir, int max_parallel_connection = 6); }; #endif //MANGADEX_DOWNLOADER_CHAPTER_H
20.576923
98
0.73271
[ "vector" ]
02933dd92a1daf7cc8b6282e4fc13dd48077a59f
1,379
h
C
Source/InteractiveObjects/InteractiveActor_Desk.h
robertcorponoi/unreal-cpp-an-in-depth-guide-to-creating-interactive-actors
b7d0d155176973144e8b0518eb7f592c2d591727
[ "MIT" ]
3
2020-08-30T06:41:56.000Z
2021-05-24T17:19:15.000Z
Source/InteractiveObjects/InteractiveActor_Desk.h
robertcorponoi/unreal-cpp-an-in-depth-guide-to-creating-interactive-actors
b7d0d155176973144e8b0518eb7f592c2d591727
[ "MIT" ]
null
null
null
Source/InteractiveObjects/InteractiveActor_Desk.h
robertcorponoi/unreal-cpp-an-in-depth-guide-to-creating-interactive-actors
b7d0d155176973144e8b0518eb7f592c2d591727
[ "MIT" ]
1
2020-08-30T06:41:59.000Z
2020-08-30T06:41:59.000Z
#pragma once #include "CoreMinimal.h" #include "InteractiveActor.h" #include "InteractiveActor_Desk.generated.h" /** * Creates an interactive desk with a drawer. */ UCLASS() class INTERACTIVEOBJECTS_API AInteractiveActor_Desk : public AInteractiveActor { GENERATED_BODY() public: // Sets up the default values. AInteractiveActor_Desk(); // A non-interactive desk. UPROPERTY(VisibleAnywhere, BlueprintReadWrite) UStaticMeshComponent* Desk; // An interactive drawer in the desk that the PlayerCharacter can interact with. UPROPERTY(VisibleAnywhere, BlueprintReadWrite) UStaticMeshComponent* DeskDrawer; // A non-interactive chair base. UPROPERTY(VisibleAnywhere, BlueprintReadWrite) UStaticMeshComponent* ChairBase; // A non-interactive chair seat. UPROPERTY(VisibleAnywhere, BlueprintReadWrite) UStaticMeshComponent* ChairSeat; // An interactive lamp. UPROPERTY(VisibleAnywhere, BlueprintReadWrite) UStaticMeshComponent* Lamp; // The light for the lamp. UPROPERTY(VisibleAnywhere, BlueprintReadWrite) class UPointLightComponent* LampLight; // The timer handle for updating the chair rotation. FTimerHandle ChairTimerHandle; protected: // Called when the game starts or when spawned. virtual void BeginPlay() override; public: // Called when the PlayerCharacter interacts with an object in this Actor. virtual void Interact() override; };
25.537037
81
0.791878
[ "object" ]
02a62a75609f4b0b82f4dcda1dd6f81f2c6ab821
223
h
C
ports/textproc/aiksaurus/dragonfly/patch-gtk_src_Display.h
liweitianux/DeltaPorts
b907de0ceb9c0e46ae8961896e97b361aa7c62c0
[ "BSD-2-Clause-FreeBSD" ]
31
2015-02-06T17:06:37.000Z
2022-03-08T19:53:28.000Z
ports/textproc/aiksaurus/dragonfly/patch-gtk_src_Display.h
liweitianux/DeltaPorts
b907de0ceb9c0e46ae8961896e97b361aa7c62c0
[ "BSD-2-Clause-FreeBSD" ]
236
2015-06-29T19:51:17.000Z
2021-12-16T22:46:38.000Z
ports/textproc/aiksaurus/dragonfly/patch-gtk_src_Display.h
liweitianux/DeltaPorts
b907de0ceb9c0e46ae8961896e97b361aa7c62c0
[ "BSD-2-Clause-FreeBSD" ]
52
2015-02-06T17:05:36.000Z
2021-10-21T12:13:06.000Z
--- gtk/src/Display.h.orig 2002-07-11 12:09:37.000000000 +0200 +++ gtk/src/Display.h @@ -5,6 +5,7 @@ #include <gtk/gtk.h> #include <vector> #include <string> +#include <cstring> #include <new> #include "Exception.h"
20.272727
62
0.64574
[ "vector" ]
02b585f80d55e8c86038a3cbd83995b2a1cdb867
4,021
h
C
rendering/include/lamure/ren/data_provenance.h
gary444/lamure
0b57a70d8496cd9632873628dc4064e09c57fef7
[ "BSD-3-Clause" ]
null
null
null
rendering/include/lamure/ren/data_provenance.h
gary444/lamure
0b57a70d8496cd9632873628dc4064e09c57fef7
[ "BSD-3-Clause" ]
null
null
null
rendering/include/lamure/ren/data_provenance.h
gary444/lamure
0b57a70d8496cd9632873628dc4064e09c57fef7
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2014-2018 Bauhaus-Universitaet Weimar // This Software is distributed under the Modified BSD License, see license.txt. // // Virtual Reality and Visualization Research Group // Faculty of Media, Bauhaus-Universitaet Weimar // http://www.uni-weimar.de/medien/vr #ifndef REN_PROVENANCE_H_ #define REN_PROVENANCE_H_ #include <lamure/ren/3rd_party/json.h> #include <fstream> #include <lamure/ren/item_provenance.h> #include <lamure/ren/policy.h> #include <lamure/types.h> #include <lamure/utils.h> #include <map> #include <mutex> #include <set> #include <thread> #include <vector> namespace lamure { namespace ren { class Data_Provenance { public: Data_Provenance() { _size_in_bytes = policy::get_instance()->size_of_provenance(); }; static Data_Provenance parse_json(std::string path) { Data_Provenance data_provenance; std::ifstream ifs(path); std::string json((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>())); picojson::value v; std::string err = picojson::parse(v, json); if(!err.empty()) { std::cout << err << std::endl; exit(2); } // check if the type of the value is "array" if(!v.is<picojson::array>()) { std::cout << "JSON is not an array" << std::endl; exit(2); } // obtain a const reference to the map, and print the contents const picojson::value::array &array = v.get<picojson::array>(); for(picojson::value::array::const_iterator iter = array.begin(); iter != array.end(); ++iter) { picojson::value::object obj = (*iter).get<picojson::value::object>(); Item_Provenance::type_item type; Item_Provenance::visualization_item visualization; picojson::value::object::const_iterator iter_type = obj.find("type"); if(iter_type != obj.end()) { if(iter_type->second.get<std::string>() == "int") { type = Item_Provenance::type_item::TYPE_INT; } else if(iter_type->second.get<std::string>() == "float") { type = Item_Provenance::type_item::TYPE_FLOAT; } else if(iter_type->second.get<std::string>() == "vec3i") { type = Item_Provenance::type_item::TYPE_VEC3I; } else if(iter_type->second.get<std::string>() == "vec3f") { type = Item_Provenance::type_item::TYPE_VEC3F; } } picojson::value::object::const_iterator iter_visualization = obj.find("visualization"); if(iter_visualization != obj.end()) { if(iter_visualization->second.get<std::string>() == "color") { visualization = Item_Provenance::visualization_item::VISUALIZATION_COLOR; } else if(iter_visualization->second.get<std::string>() == "arrow") { visualization = Item_Provenance::visualization_item::VISUALIZATION_ARROW; } } Item_Provenance item_provenance(type, visualization); data_provenance.add_item(item_provenance); } policy::get_instance()->set_size_of_provenance(data_provenance.get_size_in_bytes()); return data_provenance; } std::vector<Item_Provenance> get_items() const { return _items_provenance; }; int32_t get_size_in_bytes() const { return _size_in_bytes; }; private: void add_item(Item_Provenance &item_provenance) { _items_provenance.push_back(item_provenance); _size_in_bytes += item_provenance.get_size_in_bytes(); }; std::vector<Item_Provenance> _items_provenance; int32_t _size_in_bytes; }; } } // namespace lamure #endif // REN_PROVENANCE_H_
32.427419
101
0.591893
[ "object", "vector" ]
02c3328c243f87819fb065f392098111ba1a6fcd
3,304
h
C
aovs.h
LepelTsmok/Benchmark-Vc
bd8e946f72fc941f995df4254d3f33579c5bc1c1
[ "BSD-3-Clause" ]
1
2016-10-29T21:21:22.000Z
2016-10-29T21:21:22.000Z
aovs.h
LepelTsmok/Benchmark-Vc
bd8e946f72fc941f995df4254d3f33579c5bc1c1
[ "BSD-3-Clause" ]
null
null
null
aovs.h
LepelTsmok/Benchmark-Vc
bd8e946f72fc941f995df4254d3f33579c5bc1c1
[ "BSD-3-Clause" ]
null
null
null
/*Copyright © 2016 Björn Gaier 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 names of contributing organizations nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.*/ #ifndef AOVS_H #define AOVS_H template <typename T> using VectorizedCoordinateContainer = std::vector<Coordinate<T>, Vc::Allocator<Coordinate<T>>>; template <typename T> using VectorizedPolarCoordinateContainer = std::vector<PolarCoordinate<T>, Vc::Allocator<PolarCoordinate<T>>>; template <typename T> void simulateInputAovs(VectorizedCoordinateContainer<T> &input, const size_t size) { typename VectorizedCoordinateContainer<T>::iterator aktElement = input.begin(); typename VectorizedCoordinateContainer<T>::iterator endElement = (input.begin() + size); while (aktElement != endElement) { aktElement->x = T::Random(); aktElement->y = T::Random(); aktElement++; } } template <typename T> struct AovsLayout { using IC = VectorizedCoordinateContainer<T>; using OC = VectorizedPolarCoordinateContainer<T>; IC inputValues; OC outputValues; AovsLayout(size_t containerSize) : inputValues(containerSize / T::size()), outputValues(containerSize / T::size()) { simulateInputAovs<T>(inputValues, inputValues.size()); } Coordinate<typename T::value_type> coordinate(size_t index) { Coordinate<typename T::value_type> r; return r; } void setPolarCoordinate(size_t index, const PolarCoordinate<typename T::value_type> &coord) {} }; template <typename T> struct AovsAccessImpl : public AovsLayout<T> { AovsAccessImpl(size_t containerSize) : AovsLayout<T>(containerSize) {} void setupLoop() {} Coordinate<T> load(size_t index) { return AovsLayout<T>::inputValues[index / T::size()]; } void store(size_t index, const PolarCoordinate<T> &coord) { AovsLayout<T>::outputValues[index / T::size()] = coord; } }; struct AovsAccess { template <typename T> using type = AovsAccessImpl<T>; }; #endif // AOVS_H
37.977011
90
0.750303
[ "vector" ]
02cb49b0f7285089394548b04ca92c0ba4d69b44
1,530
h
C
include/NIsEmptyOrValid.h
justinmann/sj
24d0a75723b024f17de6dab9070979a4f1bf1a60
[ "Apache-2.0" ]
2
2017-01-04T02:27:10.000Z
2017-01-22T05:36:41.000Z
include/NIsEmptyOrValid.h
justinmann/sj
24d0a75723b024f17de6dab9070979a4f1bf1a60
[ "Apache-2.0" ]
null
null
null
include/NIsEmptyOrValid.h
justinmann/sj
24d0a75723b024f17de6dab9070979a4f1bf1a60
[ "Apache-2.0" ]
1
2020-06-15T12:17:26.000Z
2020-06-15T12:17:26.000Z
// // NIsEmptyOrValid.h // sj // // Created by Mann, Justin on 12/25/16. // Copyright � 2016 Mann, Justin. All rights reserved. // #ifndef NIsEmptyOrValid_h #define NIsEmptyOrValid_h class CIsEmptyOrValidVar : public CVar { public: CIsEmptyOrValidVar(CLoc loc, shared_ptr<CScope> scope, shared_ptr<CVar> var, bool isEmpty) : CVar(loc, scope), var(var), isEmpty(isEmpty){ } bool getReturnThis(); shared_ptr<CType> getType(Compiler* compiler); void transpile(Compiler* compiler, TrOutput* trOutput, TrBlock* trBlock, shared_ptr<TrValue> thisValue, shared_ptr<TrStoreValue> storeValue); void dump(Compiler* compiler, map<shared_ptr<CBaseFunction>, string>& functions, stringstream& ss, int level); private: shared_ptr<CVar> var; bool isEmpty; }; class NIsEmptyOrValid : public NVariableBase { public: NIsEmptyOrValid(CLoc loc, shared_ptr<NBase> node, bool isEmpty) : NVariableBase(NodeType_IsEmptyOrValid, loc), node(node), isEmpty(isEmpty) {} bool getReturnThis(); void initFunctionsImpl(Compiler* compiler, vector<pair<string, vector<string>>>& importNamespaces, vector<string>& packageNamespace, shared_ptr<CBaseFunctionDefinition> thisFunction); void initVarsImpl(Compiler* compiler, shared_ptr<CScope> scope, CTypeMode returnMode); shared_ptr<CVar> getVarImpl(Compiler* compiler, shared_ptr<CScope> scope, shared_ptr<CVar> dotVar, shared_ptr<CType> returnType, CTypeMode returnMode); private: shared_ptr<NBase> node; bool isEmpty; }; #endif /* NIsEmpty_h */
39.230769
187
0.750327
[ "vector" ]