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
ba560c3d6d7ba0b85c2824fb3d10761bdd9b960b
902
h
C
engine/common/core/src/cpp/include/RunnableQueue.h
mikolajgucki/ae-engine
c4953feb74853b01b39b45b3bce23c10f6f74db0
[ "MIT" ]
1
2021-02-23T09:36:42.000Z
2021-02-23T09:36:42.000Z
engine/common/core/src/cpp/include/RunnableQueue.h
mikolajgucki/ae-engine
c4953feb74853b01b39b45b3bce23c10f6f74db0
[ "MIT" ]
null
null
null
engine/common/core/src/cpp/include/RunnableQueue.h
mikolajgucki/ae-engine
c4953feb74853b01b39b45b3bce23c10f6f74db0
[ "MIT" ]
null
null
null
#ifndef AE_RUNNABLE_QUEUE_H #define AE_RUNNABLE_QUEUE_H #include <vector> #include "Runnable.h" namespace ae { /** * \brief Holds runnables and runs then in the order in which they were added. */ class RunnableQueue:public Runnable { /** */ std::vector<Runnable *> runnables; /** * \brief Deletets runnables in a vector. * \param toDelete The runnables to delete. */ void deleteRunnables(std::vector<Runnable *> toDelete); public: /** */ RunnableQueue():Runnable(),runnables() { } /** */ virtual ~RunnableQueue() { deleteRunnables(runnables); } /** * \brief Adds a runnable to the queue. * \param runnable The runnable. */ void add(Runnable *runnable); /** */ virtual bool run(); }; } // namespace #endif // AE_RUNNABLE_QUEUE_H
20.5
79
0.574279
[ "vector" ]
ba5b97594e5a970b888b181199fabd1660d6f93a
978
c
C
cmds/arch/cleartemp.c
zhangyifei/mud
b2090bbd2a8d3d82b86148d794a7ca59cd2429f3
[ "MIT" ]
69
2018-03-08T18:24:44.000Z
2022-02-24T13:43:53.000Z
cmds/arch/cleartemp.c
zhangyifei/mud
b2090bbd2a8d3d82b86148d794a7ca59cd2429f3
[ "MIT" ]
3
2019-04-24T12:21:19.000Z
2021-03-28T23:34:58.000Z
cmds/arch/cleartemp.c
zhangyifei/mud
b2090bbd2a8d3d82b86148d794a7ca59cd2429f3
[ "MIT" ]
33
2017-12-23T05:06:58.000Z
2021-08-16T02:42:59.000Z
// cleartemp.c // created by doing #include <ansi.h> #include <localtime.h> inherit F_CLEAN_UP; int help(object me); int main(object me, string arg) { string flogin; string fuser; if (!SECURITY_D->valid_grant(me, "(arch)")) return 0; if (!arg) return help(me); seteuid(getuid()); arg = arg[0..0] + "/" + arg + __SAVE_EXTENSION__; flogin = TEMP_DIR + "login/" + arg; fuser = TEMP_DIR + "user/" + arg; if (file_size(flogin) < 0 && file_size(fuser) < 0) { write("这个玩家在暂存区中没有临时档案。\n"); return 1; } rm(flogin); rm(fuser); if (file_size(flogin) >= 0 || file_size(fuser) >= 0) { write("清除暂存区中玩家(" + arg + ")的文件失败了。"); return 1; } write("成功的清除暂存中玩家(" + arg + ")的档案。\n"); return 1; } int help(object me) { write(@HELP 指令格式:cleartemp <玩家ID> 这是清除暂存区中的玩家临时档案的命令,这些临时档案一般是使用 restore 命令从备份区恢复玩家数据时产生的。 相关指令:restore HELP ); return 1; }
16.576271
53
0.563395
[ "object" ]
ba647766987b4fe5a52024c37c23cb513ba4400b
9,873
c
C
fftw.c
bukka/php-fftw
88dca53a2ea6b5c84be7e97c06b46f3c6be550ac
[ "PHP-3.01" ]
3
2016-12-20T07:25:40.000Z
2020-06-05T22:50:40.000Z
fftw.c
bukka/php-fftw
88dca53a2ea6b5c84be7e97c06b46f3c6be550ac
[ "PHP-3.01" ]
null
null
null
fftw.c
bukka/php-fftw
88dca53a2ea6b5c84be7e97c06b46f3c6be550ac
[ "PHP-3.01" ]
null
null
null
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2014 Jakub Zelenka | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Jakub Zelenka <bukka@php.net> | +----------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_fftw.h" #include "ext/standard/info.h" #include <fftw3.h> /* malloc and free wrapper */ #ifdef PHP_FFTW_DEBUG #define php_fftw_malloc emalloc #define php_fftw_free efree #else #define php_fftw_malloc fftw_malloc #define php_fftw_free fftw_free #endif /* data for input or output*/ typedef union { fftw_complex *c; double *r; } php_fftw_io; /* fftw plan */ typedef struct { zend_object zo; fftw_plan plan; php_fftw_io in; php_fftw_io out; } php_fftw_plan_object; /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO(arginfo_fftw_plan_dft_1d, 0) ZEND_ARG_INFO(0, n) ZEND_ARG_INFO(0, in) ZEND_ARG_INFO(0, sign) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_fftw_execute, 0) ZEND_ARG_INFO(0, plan) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_fftw_output, 0) ZEND_ARG_INFO(0, plan) ZEND_END_ARG_INFO() /* }}} */ /* {{{ php_fftw_functions[] */ zend_function_entry php_fftw_functions[] = { PHP_FE(fftw_plan_dft_1d, arginfo_fftw_plan_dft_1d) PHP_FE(fftw_execute, arginfo_fftw_execute) PHP_FE(fftw_output, arginfo_fftw_output) PHP_FFTW_FE_END }; /* }}} */ /* {{{ php_fftw_plan_object_methods[] */ zend_function_entry php_fftw_plan_object_methods[] = { PHP_FFTW_FE_END }; /* }}} */ /* {{{ fftw_module_entry */ zend_module_entry fftw_module_entry = { STANDARD_MODULE_HEADER, "fftw", php_fftw_functions, PHP_MINIT(fftw), PHP_MSHUTDOWN(fftw), NULL, NULL, PHP_MINFO(fftw), PHP_FFTW_VERSION, STANDARD_MODULE_PROPERTIES }; /* }}} */ #ifdef COMPILE_DL_FFTW ZEND_GET_MODULE(fftw) #endif /* class entry */ PHP_FFTW_API zend_class_entry *php_fftw_plan_ce; /* object handler */ static zend_object_handlers php_fftw_plan_object_handlers; /* {{{ */ static void php_fftw_plan_object_dtor(void *object, zend_object_handle handle TSRMLS_DC) { zend_objects_destroy_object(object, handle TSRMLS_CC); } /* }}} */ /* {{{ */ static void php_fftw_plan_object_free(zend_object *object TSRMLS_DC) { php_fftw_plan_object *intern = (php_fftw_plan_object *) object; zend_object_std_dtor(&intern->zo TSRMLS_CC); if (intern->out.r && intern->in.r != intern->out.r) { php_fftw_free(intern->out.r); } if (intern->in.r) { fftw_destroy_plan(intern->plan); php_fftw_free(intern->in.r); } efree(intern); } /* }}} */ /* {{{ */ static zend_object_value php_fftw_plan_object_create_ex(zend_class_entry *class_type, php_fftw_plan_object **ptr TSRMLS_DC) { zend_object_value retval; php_fftw_plan_object *intern; /* Allocate memory for it */ intern = (php_fftw_plan_object *) emalloc(sizeof(php_fftw_plan_object)); memset(intern, 0, sizeof(php_fftw_plan_object)); if (ptr) { *ptr = intern; } zend_object_std_init(&intern->zo, class_type TSRMLS_CC); PHP_FFTW_OBJECT_PROPERTIES_INIT(&intern->zo, class_type); retval.handlers = &php_fftw_plan_object_handlers; retval.handle = zend_objects_store_put( intern, (zend_objects_store_dtor_t) php_fftw_plan_object_dtor, (zend_objects_free_object_storage_t) php_fftw_plan_object_free, NULL TSRMLS_CC); return retval; } /* }}} */ /* {{{ */ static zend_object_value php_fftw_plan_object_create(zend_class_entry *class_type TSRMLS_DC) { return php_fftw_plan_object_create_ex(class_type, NULL TSRMLS_CC); } /* }}} */ /* {{{ */ zend_object_value php_fftw_plan_object_clone(zval *this_ptr TSRMLS_DC) { php_fftw_plan_object *new_obj = NULL; php_fftw_plan_object *old_obj = (php_fftw_plan_object *) zend_object_store_get_object(this_ptr TSRMLS_CC); zend_object_value new_ov = php_fftw_plan_object_create_ex(old_obj->zo.ce, &new_obj TSRMLS_CC); zend_objects_clone_members(&new_obj->zo, new_ov, &old_obj->zo, Z_OBJ_HANDLE_P(this_ptr) TSRMLS_CC); /*TODO: copy plan fftw data */ return new_ov; } /* }}} */ /* macro for registering FFTW constants */ #define REGISTER_FFTW_CONSTANT(constant) REGISTER_LONG_CONSTANT(#constant, constant, CONST_CS | CONST_PERSISTENT) /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(fftw) { zend_class_entry ce; /* fftw_plan class */ INIT_CLASS_ENTRY(ce, "fftw_plan", php_fftw_plan_object_methods); ce.create_object = php_fftw_plan_object_create; memcpy(&php_fftw_plan_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); php_fftw_plan_object_handlers.clone_obj = php_fftw_plan_object_clone; php_fftw_plan_ce = zend_register_internal_class(&ce TSRMLS_CC); REGISTER_STRING_CONSTANT("FFTW_VERSION", (char *) fftw_version, CONST_PERSISTENT | CONST_CS); /* Sign constants */ REGISTER_FFTW_CONSTANT(FFTW_FORWARD); REGISTER_FFTW_CONSTANT(FFTW_BACKWARD); /* Flags constants */ REGISTER_FFTW_CONSTANT(FFTW_MEASURE); REGISTER_FFTW_CONSTANT(FFTW_DESTROY_INPUT); REGISTER_FFTW_CONSTANT(FFTW_UNALIGNED); REGISTER_FFTW_CONSTANT(FFTW_CONSERVE_MEMORY); REGISTER_FFTW_CONSTANT(FFTW_EXHAUSTIVE); REGISTER_FFTW_CONSTANT(FFTW_PRESERVE_INPUT); REGISTER_FFTW_CONSTANT(FFTW_PATIENT); REGISTER_FFTW_CONSTANT(FFTW_ESTIMATE); REGISTER_FFTW_CONSTANT(FFTW_WISDOM_ONLY); return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ PHP_MSHUTDOWN_FUNCTION(fftw) { return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(fftw) { php_info_print_table_start(); php_info_print_table_row(2, "FFTW support", "enabled"); php_info_print_table_row(2, "FFTW version", PHP_FFTW_VERSION); php_info_print_table_row(2, "FFTW library version", fftw_version); php_info_print_table_end(); } /* }}} */ /* {{{ */ static fftw_complex *php_fftw_fill_complex_array(fftw_complex *in, zval *z_ht TSRMLS_DC) { zval **ppz_item, *pz_real, *pz_complex, z_tmp; HashPosition pos; HashTable *ht = Z_ARRVAL_P(z_ht); int i = 0; for (zend_hash_internal_pointer_reset_ex(ht, &pos); zend_hash_get_current_data_ex(ht, (void **) &ppz_item, &pos) == SUCCESS; zend_hash_move_forward_ex(ht, &pos), i++ ) { if (Z_TYPE_PP(ppz_item) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Complex item %d has to be array", i); return NULL; } if (zend_hash_num_elements(Z_ARRVAL_PP(ppz_item)) != 2) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Complex item %d array has to contain exactly two elements", i); return NULL; } if (zend_hash_index_find(Z_ARRVAL_PP(ppz_item), 0, (void **) &pz_real) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Complex item %d missing index 0 for real part", i); return NULL; } if (zend_hash_index_find(Z_ARRVAL_PP(ppz_item), 0, (void **) &pz_complex) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Complex item %d missing index 1 for complex part", i); return NULL; } INIT_PZVAL_COPY(&z_tmp, pz_real); convert_to_double(&z_tmp); in[i][0] = Z_DVAL(z_tmp); INIT_PZVAL_COPY(&z_tmp, pz_complex); convert_to_double(&z_tmp); in[i][1] = Z_DVAL(z_tmp); } return in; } /* }}} */ /* {{{ proto fftw_plan fftw_plan_dft_1d(int $n, array $in, int $sign, int $flags) Create plan for 1d dft */ PHP_FUNCTION(fftw_plan_dft_1d) { zval *z_in; long n, sign, flags; int in_size; fftw_complex *in, *out; fftw_plan plan; php_fftw_plan_object *object; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lall", &n, &z_in, &sign, &flags) == FAILURE) { return; } in_size = zend_hash_num_elements(Z_ARRVAL_P(z_in)); if (in_size != n) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid number of elements in input array (expected: %ld, received: %d)", n, in_size); RETURN_NULL(); } in = (fftw_complex *) php_fftw_malloc(n * sizeof(fftw_complex)); out = (fftw_complex *) php_fftw_malloc(n * sizeof(fftw_complex)); plan = fftw_plan_dft_1d(n, in, out, sign, flags); if (!php_fftw_fill_complex_array(in, z_in TSRMLS_CC)) { RETURN_NULL(); } object_init_ex(return_value, php_fftw_plan_ce); object = (php_fftw_plan_object *) zend_object_store_get_object(return_value TSRMLS_CC); object->plan = plan; object->in.c = in; object->out.c = out; } /* }}} */ /* {{{ proto void fftw_execute(fftw_plan $plan) Execute plan */ PHP_FUNCTION(fftw_execute) { zval *z_plan; php_fftw_plan_object *object; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O", &z_plan, php_fftw_plan_ce) == FAILURE) { return; } object = (php_fftw_plan_object *) zend_object_store_get_object(z_plan TSRMLS_CC); fftw_execute(object->plan); RETURN_NULL(); } /* }}} */ /* {{{ proto void fftw_output(fftw_plan $plan) Return plan output */ PHP_FUNCTION(fftw_output) { zval *z_plan; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &z_plan) == FAILURE) { return; } RETURN_TRUE; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
27.655462
123
0.692393
[ "object" ]
0f7b9c4fea44c12ff7c58367d55bd06128fdb9d1
1,877
h
C
Kernel/VM/VMObject.h
vger92/serenity
e83afe228a424fa096586bf4528cf859ea5b9965
[ "BSD-2-Clause" ]
null
null
null
Kernel/VM/VMObject.h
vger92/serenity
e83afe228a424fa096586bf4528cf859ea5b9965
[ "BSD-2-Clause" ]
null
null
null
Kernel/VM/VMObject.h
vger92/serenity
e83afe228a424fa096586bf4528cf859ea5b9965
[ "BSD-2-Clause" ]
null
null
null
#pragma once #include <AK/AKString.h> #include <AK/Badge.h> #include <AK/RetainPtr.h> #include <AK/Retainable.h> #include <AK/Vector.h> #include <AK/Weakable.h> #include <Kernel/Lock.h> #include <Kernel/PhysicalAddress.h> #include <Kernel/UnixTypes.h> class Inode; class PhysicalPage; class VMObject : public Retainable<VMObject> , public Weakable<VMObject> { friend class MemoryManager; public: static Retained<VMObject> create_file_backed(RetainPtr<Inode>&&); static Retained<VMObject> create_anonymous(size_t); static Retained<VMObject> create_for_physical_range(PhysicalAddress, size_t); Retained<VMObject> clone(); ~VMObject(); bool is_anonymous() const { return !m_inode; } Inode* inode() { return m_inode.ptr(); } const Inode* inode() const { return m_inode.ptr(); } size_t inode_offset() const { return m_inode_offset; } String name() const { return m_name; } void set_name(const String& name) { m_name = name; } size_t page_count() const { return m_size / PAGE_SIZE; } const Vector<RetainPtr<PhysicalPage>>& physical_pages() const { return m_physical_pages; } Vector<RetainPtr<PhysicalPage>>& physical_pages() { return m_physical_pages; } void inode_contents_changed(Badge<Inode>, off_t, ssize_t, const byte*); void inode_size_changed(Badge<Inode>, size_t old_size, size_t new_size); size_t size() const { return m_size; } private: VMObject(RetainPtr<Inode>&&); explicit VMObject(VMObject&); explicit VMObject(size_t); VMObject(PhysicalAddress, size_t); template<typename Callback> void for_each_region(Callback); String m_name; bool m_allow_cpu_caching { true }; off_t m_inode_offset { 0 }; size_t m_size { 0 }; RetainPtr<Inode> m_inode; Vector<RetainPtr<PhysicalPage>> m_physical_pages; Lock m_paging_lock { "VMObject" }; };
30.274194
94
0.71284
[ "vector" ]
0f7ca41316498d6f9ec732cb61508d8871a5946d
19,501
h
C
include/BPTree.h
JiangWenPL/miniSQL
33f1848d0374de1c421c63a3b8c63310344a99ef
[ "MIT" ]
1
2019-04-30T02:10:25.000Z
2019-04-30T02:10:25.000Z
include/BPTree.h
JiangWenPL/miniSQL
33f1848d0374de1c421c63a3b8c63310344a99ef
[ "MIT" ]
null
null
null
include/BPTree.h
JiangWenPL/miniSQL
33f1848d0374de1c421c63a3b8c63310344a99ef
[ "MIT" ]
null
null
null
// // Created by Wen Jiang on 6/15/18. // #ifndef MINISQL_BPTREE_H #define MINISQL_BPTREE_H #include "Node.h" // Template B+ tree node. // For coding convenience, we define an unified node class both represent // internal node and leaf node. template<typename T> class BPTree { private: typedef Node<T> *Tree; struct search_info { Tree pNode; int value; bool is_found; }; static const int PAGESIZE = 4096; // name of index std::string m_name; // Pointer to root Tree root; // Pointer to the head of leaf node Tree p_leaf_head; // Number of keys unsigned int key_num; // Number of levels unsigned int level; // Number of nodes. unsigned int node_num; int key_size; // Degree of this B+ tree int degree; // min number of keys. int min_key_num; public: explicit BPTree(std::string &name); ~BPTree(); // Search by key // @key: key to search // @return the value stored in b+ tree. // -1 if not find offset search_by_key(const T &key); // Insert key:value into B+ tree // @return true if success inserted. bool insert(const T &key, int value); // Delete key:value in B+ tree // @return true if delte success bool delete_by_key(const T &key); // Destroy this tree. // @tree: root of this tree // Can also be a node. void destroy_tree(Tree tree); // Search all value in range (key1, key2) // @start_key start key to search // @end_key terminate key to searh // @return: vector to store all value found std::vector<offset> search_between(const T &begin_key, const T &end_key); std::vector<offset> search_smaller(const T &end_key); std::vector<offset> search_greater(const T &begin_key); // Load from disk void load_all_node(); // Dump to disk void dump_to_disk(); // load a page void load_from_disk(char *p, char *end); void print_leaf(); private: // Init B+ tree void initialize(); // Adjust to avoid overflow bool adjust_after_insert(Tree pNode); // Adjust to avoid underflow bool adjust_after_delete(Tree pNode); // Search where the leaf stored void find_by_key(Tree pNode, const T &key, search_info &info); // Create or open file. void get_file(const std::string &file_name); int count_block_num(const std::string &index_name); }; template<class T> BPTree<T>::BPTree(std::string &name): m_name(name), key_num(0), level(0), node_num(0), root(nullptr), p_leaf_head(nullptr) { key_size = sizeof(T); degree = (PAGESIZE - sizeof(int)) / (sizeof(T) + sizeof(int)); min_key_num = (degree - 1) / 2; // Initialize the keys. initialize(); load_all_node(); } template<class T> BPTree<T>::~BPTree() { destroy_tree(root); key_num = 0; root = nullptr; level = 0; } template<class T> void BPTree<T>::initialize() { root = new Node<T>(degree, true); key_num = 0; level = 1; node_num = 1; p_leaf_head = root; } template<class T> void BPTree<T>::find_by_key(Tree pNode, const T &key, search_info &info) { int key_index = 0; // The index storing the key in this node. // Search if key exist in this node if (pNode->find_by_key(key, key_index)) { // This is leaf node and key in this node. if (pNode->is_leaf) { info.pNode = pNode; info.value = key_index; info.is_found = true; } else { // Not leaf node, search recursively. pNode = pNode->child[key_index + 1]; while (!pNode->is_leaf) { pNode = pNode->child[0]; } // Since key appears in non leaf node. // Key must be the first value in this node. info.pNode = pNode; info.value = 0; info.is_found = true; } } else { // Key not appears in this node. if (pNode->is_leaf) { // Still not find info.pNode = pNode; info.value = key_index; info.is_found = false; } else { // Search recursively find_by_key(pNode->child[key_index], key, info); } } } template<class T> bool BPTree<T>::insert(const T &key, const int value) { search_info info; // Init in the first insert; if (!root) initialize(); // Check if exist find_by_key(root, key, info); if (info.is_found) { throw DuplicateKey(); return false; } else { info.pNode->insert_key(key, value); // Adjust after insertion if (info.pNode->key_num == degree) { adjust_after_insert(info.pNode); } key_num++; return true; } } template<class T> bool BPTree<T>::adjust_after_insert(Tree pNode) { T key; Tree newNode = pNode->split_node(key); node_num++; if (pNode->is_root()) { // If just have root node. auto root = new Node<T>(degree, false); level++; node_num++; this->root = root; pNode->father = root; newNode->father = root; root->insert_key(key); root->child[0] = pNode; root->child[1] = newNode; return true; } else { // Not root Tree father = pNode->father; int index = father->insert_key(key); father->child[index + 1] = newNode; newNode->father = father; // Adjust recursively if (father->key_num == degree) return adjust_after_insert(father); return true; } } template<class T> offset BPTree<T>::search_by_key(const T &key) { if (!root) return -1; search_info info; find_by_key(root, key, info); if (!info.is_found) return -1; else return info.pNode->values[info.value]; } template<class T> bool BPTree<T>::delete_by_key(const T &key) { search_info info; // Root node not exist. if (!root) { throw BPTreeInnerException("Tree to delete with a null root"); return false; } else { find_by_key(root, key, info); if (!info.is_found) { throw KeyNotExist(); return false; } else { if (info.pNode->is_root()) { // This tree just contain an root node. info.pNode->delete_key_start_by(info.value); key_num--; return adjust_after_delete(info.pNode); } else { if (info.value == 0 && p_leaf_head != info.pNode) { // Update internal node int index = 0; Tree cur_father = info.pNode->father; bool if_found_inBranch = cur_father->find_by_key(key, index); while (!if_found_inBranch) { if (cur_father->father) cur_father = cur_father->father; else break; if_found_inBranch = cur_father->find_by_key(key, index); } cur_father->keys[index] = info.pNode->keys[1]; info.pNode->delete_key_start_by(info.value); key_num--; return adjust_after_delete(info.pNode); } else { // Update lead node. info.pNode->delete_key_start_by(info.value); key_num--; return adjust_after_delete(info.pNode); } } } } } template<class T> bool BPTree<T>::adjust_after_delete(Tree pNode) { // Not necessary to adjust: if (((pNode->is_leaf) && (pNode->key_num >= min_key_num)) || ((degree != 3) && (!pNode->is_leaf) && (pNode->key_num >= min_key_num - 1)) || ((degree == 3) && (!pNode->is_leaf) && (pNode->key_num < 0))) { return true; } if (pNode->is_root()) { // For root node if (pNode->key_num > 0) return true; else { // None leaf node if (root->is_leaf) { // If root is also a leaf node, we shall set root = nullptr delete pNode; root = nullptr; p_leaf_head = nullptr; level--; node_num--; } else { // son of root node become leaf root = pNode->child[0]; root->father = nullptr; delete pNode; level--; node_num--; } } } else { // Non root Tree father = pNode->father, brother = nullptr; if (pNode->is_leaf) { // delete in leaf int index = 0; father->find_by_key(pNode->keys[0], index); // Borrow from left siblings if ((father->child[0] != pNode) && (index + 1 == father->key_num)) { brother = father->child[index]; if (brother->key_num > min_key_num) { for (int i = pNode->key_num; i > 0; i--) { pNode->keys[i] = pNode->keys[i - 1]; pNode->values[i] = pNode->values[i - 1]; } pNode->keys[0] = brother->keys[brother->key_num - 1]; pNode->values[0] = brother->values[brother->key_num - 1]; brother->delete_key_start_by(brother->key_num - 1); pNode->key_num++; father->keys[index] = pNode->keys[0]; return true; } else { father->delete_key_start_by(index); for (int i = 0; i < pNode->key_num; i++) { brother->keys[i + brother->key_num] = pNode->keys[i]; brother->values[i + brother->key_num] = pNode->values[i]; } brother->key_num += pNode->key_num; brother->sibling = pNode->sibling; delete pNode; node_num--; return adjust_after_delete(father); } } else { if (father->child[0] == pNode) brother = father->child[1]; else brother = father->child[index + 2]; if (brother->key_num > min_key_num) { pNode->keys[pNode->key_num] = brother->keys[0]; pNode->values[pNode->key_num] = brother->values[0]; pNode->key_num++; brother->delete_key_start_by(0); if (father->child[0] == pNode) father->keys[0] = brother->keys[0]; else father->keys[index + 1] = brother->keys[0]; return true; } else { for (int i = 0; i < brother->key_num; i++) { pNode->keys[pNode->key_num + i] = brother->keys[i]; pNode->values[pNode->key_num + i] = brother->values[i]; } if (pNode == father->child[0]) father->delete_key_start_by(0); else father->delete_key_start_by(index + 1); pNode->key_num += brother->key_num; pNode->sibling = brother->sibling; delete brother; node_num--; return adjust_after_delete(father); } } } else { int index = 0; father->find_by_key(pNode->child[0]->keys[0], index); if ((father->child[0] != pNode) && (index + 1 == father->key_num)) { brother = father->child[index]; if (brother->key_num > min_key_num - 1) { pNode->child[pNode->key_num + 1] = pNode->child[pNode->key_num]; for (int i = pNode->key_num; i > 0; i--) { pNode->child[i] = pNode->child[i - 1]; pNode->keys[i] = pNode->keys[i - 1]; } pNode->child[0] = brother->child[brother->key_num]; pNode->keys[0] = father->keys[index]; pNode->key_num++; father->keys[index] = brother->keys[brother->key_num - 1]; if (brother->child[brother->key_num]) brother->child[brother->key_num]->father = pNode; brother->delete_key_start_by(brother->key_num - 1); return true; } else { brother->keys[brother->key_num] = father->keys[index]; father->delete_key_start_by(index); brother->key_num++; for (int i = 0; i < pNode->key_num; i++) { brother->child[brother->key_num + i] = pNode->child[i]; brother->keys[brother->key_num + i] = pNode->keys[i]; brother->child[brother->key_num + i]->father = brother; } brother->child[brother->key_num + pNode->key_num] = pNode->child[pNode->key_num]; brother->child[brother->key_num + pNode->key_num]->father = brother; brother->key_num += pNode->key_num; delete pNode; node_num--; return adjust_after_delete(father); } } else { if (father->child[0] == pNode) brother = father->child[1]; else brother = father->child[index + 2]; if (brother->key_num > min_key_num - 1) { pNode->child[pNode->key_num + 1] = brother->child[0]; pNode->keys[pNode->key_num] = brother->keys[0]; pNode->child[pNode->key_num + 1]->father = pNode; pNode->key_num++; if (pNode == father->child[0]) father->keys[0] = brother->keys[0]; else father->keys[index + 1] = brother->keys[0]; brother->child[0] = brother->child[1]; brother->delete_key_start_by(0); return true; } else { pNode->keys[pNode->key_num] = father->keys[index]; if (pNode == father->child[0]) father->delete_key_start_by(0); else father->delete_key_start_by(index + 1); pNode->key_num++; for (int i = 0; i < brother->key_num; i++) { pNode->child[pNode->key_num + i] = brother->child[i]; pNode->keys[pNode->key_num + i] = brother->keys[i]; pNode->child[pNode->key_num + i]->father = pNode; } pNode->child[pNode->key_num + brother->key_num] = brother->child[brother->key_num]; pNode->child[pNode->key_num + brother->key_num]->father = pNode; pNode->key_num += brother->key_num; delete brother; node_num--; return adjust_after_delete(father); } } } } return false; } template<class T> void BPTree<T>::destroy_tree(Tree tree) { // Check if is a empty tree if (!tree) return; // Destroy B+ tree recursively if (!tree->is_leaf) { for (unsigned int i = 0; i <= tree->key_num; i++) { destroy_tree(tree->child[i]); tree->child[i] = nullptr; } } delete tree; node_num--; } template<class T> std::vector<offset> BPTree<T>::search_between(const T &begin_key, const T &end_key) { std::vector<offset> results; if (!root) return results; search_info info1, info2; find_by_key(root, begin_key, info1); find_by_key(root, end_key, info2); bool finished; int index; if (begin_key > end_key) { Tree pNode = info2.pNode; index = info2.value; do { finished = pNode->find_in_range(index, begin_key, results); index = 0; if (pNode->sibling == nullptr) break; else pNode = pNode->get_sibling_node(); } while (!finished); } else { Tree pNode = info1.pNode; index = info1.value; do { finished = pNode->find_in_range(index, end_key, results); index = 0; if (pNode->sibling == nullptr) break; else pNode = pNode->get_sibling_node(); } while (!finished); } std::sort(results.begin(), results.end()); results.erase(unique(results.begin(), results.end()), results.end()); return results; } template<class T> std::vector<offset> BPTree<T>::search_smaller(const T &end_key) { std::vector<offset> results; if (!root) return results; search_info info2; find_by_key(root, end_key, info2); bool finished; Tree pNode = info2.pNode; int index = info2.value; do { finished = pNode->find_greater_than(index, results); index = 0; if (pNode->sibling == nullptr) break; else pNode = pNode->get_sibling_node(); } while (!finished); std::sort(results.begin(), results.end()); results.erase(unique(results.begin(), results.end()), results.end()); return results; } template<class T> std::vector<offset> BPTree<T>::search_greater(const T &begin_key) { std::vector<offset> results; if (!root) return results; search_info info1; find_by_key(root, begin_key, info1); bool finished; Tree pNode = info1.pNode; int index = info1.value; do { finished = pNode->find_greater_than(index, results); index = 0; if (pNode->sibling == nullptr) break; else pNode = pNode->get_sibling_node(); } while (!finished); std::sort(results.begin(), results.end()); results.erase(unique(results.begin(), results.end()), results.end()); return results; } template<class T> void BPTree<T>::print_leaf() { Tree p = p_leaf_head; while (p != nullptr) { p->print_node(); p = p->get_sibling_node(); } } template<class T> void BPTree<T>::get_file(const std::string &file_name) { FILE *f = fopen(file_name.c_str(), "r"); if (f == nullptr) { f = fopen(file_name.c_str(), "w+"); fclose(f); f = fopen(file_name.c_str(), "r"); } fclose(f); } template<class T> void BPTree<T>::load_from_disk(char *p, char *end) { //TODO: load B+ tree from disk } template<class T> void BPTree<T>::dump_to_disk() { // TODO: dump B+ tree to disk } template<class T> int BPTree<T>::count_block_num(const std::string &index_name) { // TODO: get block number: return 0; } template<class T> void BPTree<T>::load_all_node() { //TODO: load from disk } #endif //MINISQL_BPTREE_H
29.863706
103
0.50623
[ "vector" ]
0f89129867c2de1f0e5c0893d46253d137461459
122
c
C
lib/wizards/celtron/shadow.c
vlehtola/questmud
8bc3099b5ad00a9e0261faeb6637c76b521b6dbe
[ "MIT" ]
null
null
null
lib/wizards/celtron/shadow.c
vlehtola/questmud
8bc3099b5ad00a9e0261faeb6637c76b521b6dbe
[ "MIT" ]
null
null
null
lib/wizards/celtron/shadow.c
vlehtola/questmud
8bc3099b5ad00a9e0261faeb6637c76b521b6dbe
[ "MIT" ]
null
null
null
start(object ob) { shadow(ob, 1); } hit_player() { return 1; } hit_with_spell() { return 1; } death() { return 1; }
8.133333
18
0.590164
[ "object" ]
0f8ba991a85c8b53c90213eb29aa50e11efec0c6
960
h
C
GameState.h
Krian0/GameProject
a6fb34048c40eb2487ec55624515f3a897c879f7
[ "MIT" ]
null
null
null
GameState.h
Krian0/GameProject
a6fb34048c40eb2487ec55624515f3a897c879f7
[ "MIT" ]
null
null
null
GameState.h
Krian0/GameProject
a6fb34048c40eb2487ec55624515f3a897c879f7
[ "MIT" ]
null
null
null
#pragma once #include "GameStateHelpers.h" #include "Renderer2D.h" #include "Texture.h" #include <assert.h> #include <vector> using std::vector; class GameState { friend class GameStateManager; public: GameState() {} virtual ~GameState() {} bool isActive() const; //Returns the bool of m_active protected: void enter(); //Sets m_active to true, then calls onEnter() void exit(); //Sets m_active to false, then calls onExit() //Updates all necessary elements. Parameters take a float (deltaTime) virtual void onUpdate(float deltaTime) = 0; //Draws all necessary elements. Parameters take a pointer to a aie::Renderer2D virtual void onDraw(aie::Renderer2D* renderer) = 0; virtual void onEnter() {} virtual void onExit() {} virtual void onPushed() {} virtual void onPopped() {} //Return current eState virtual States get_eState() = 0; vector<Request> m_requests; States m_currentState; private: bool m_active = false; };
22.325581
79
0.71875
[ "vector" ]
0fa00bf9dcf650b4aaadcf46678fe26a38063600
2,647
h
C
WFHttp/WFHttp.h
williamFalcon/WFHttp
d2fa7c8bd72c707af9d0a8f9dde556031a8096ea
[ "MIT" ]
null
null
null
WFHttp/WFHttp.h
williamFalcon/WFHttp
d2fa7c8bd72c707af9d0a8f9dde556031a8096ea
[ "MIT" ]
null
null
null
WFHttp/WFHttp.h
williamFalcon/WFHttp
d2fa7c8bd72c707af9d0a8f9dde556031a8096ea
[ "MIT" ]
null
null
null
// // WFHttp.h // WFHttp // // Created by William Falcon on 3/20/14. // Copyright (c) 2014 William Falcon. All rights reserved. // #import <Foundation/Foundation.h> static BOOL LOGGING_ENABLED = true; static BOOL PRINT_POST_JSON_BEFORE_SENDING = true; typedef NS_ENUM(int, WFHTTPContentType) { WFHTTPContentTypeJSON, WFHTTPContentTypeMultipartForm }; @interface WFHttp : NSObject //Holds requests waiting to be sent. Acts as a queque @property (nonatomic) NSMutableArray *requests; //makeshift tracks requests so we can show the nav spinner @property (nonatomic) NSMutableArray *requestsInProgress; /* Will auto empty once this threshold has been reached. Defaults to 50 unless modified */ @property (assign) int queueEmptyThreshold; /* Determines how cookies will be handled. Defaults to NSHTTPCookieAcceptPolicyAlways */ @property (assign) NSHTTPCookieAcceptPolicy cookiePolicy; #pragma mark - GET /* Basic GET request. Results return in the completion block */ +(void)GET:(NSString*)url optionalParameters:(NSDictionary *)parameters optionalHTTPHeaders:(NSDictionary *)headers onSuccess:(void(^)(id result, NSInteger statusCode, NSHTTPURLResponse *response))success onFailure:(void(^)(NSString *error))failure; #pragma mark - POST /* Basic POST request. Results return in the completion block Object can be anything (array, dictionary, NSObject, and more) */ +(void)POST:(NSString*)url optionalHTTPHeaders:(NSDictionary *)headers object:(id)object completion:(void(^)(id result, NSInteger statusCode, NSHTTPURLResponse *response))completion; +(void)POST:(NSString *)url optionalHTTPHeaders:(NSDictionary *)headers form:(id)form completion:(void (^)(id, NSInteger, NSHTTPURLResponse *))completion; /* Create a post request but instead of sending immediately, it adds to a queue to be sent after the threshold specified */ +(void)POSTToQueue:(NSString *)url optionalHTTPHeaders:(NSDictionary *)headers object:(id)object; #pragma mark - PUT /* Basic POST request. Used for multipart form. To post image, add image to form dictionary Ex: To post image, add an image parameter to the dictionary */ + (void)PUT:(NSString*)url optionalHTTPHeaders:(NSDictionary *)headers form:(id)form completion:(void(^)(id result, NSInteger statusCode, NSHTTPURLResponse *response))completion; /* Basic PUT request. Results return in the completion block Object can be anything (array, dictionary, NSObject, and more) */ +(void)PUT:(NSString*)url optionalHTTPHeaders:(NSDictionary *)headers object:(id)object completion:(void(^)(id result, NSInteger statusCode, NSHTTPURLResponse *response))completion; @end
30.425287
249
0.767662
[ "object" ]
0fa76ef0162793a9fd95933974afaa6ce0c1e510
7,016
h
C
include/CQDataFrameWidget.h
colinw7/CQDataFrame
bc82952dbe9f9a3fc79cc274f4c0ee97abcf0d5e
[ "MIT" ]
1
2021-12-23T02:25:36.000Z
2021-12-23T02:25:36.000Z
include/CQDataFrameWidget.h
colinw7/CQDataFrame
bc82952dbe9f9a3fc79cc274f4c0ee97abcf0d5e
[ "MIT" ]
null
null
null
include/CQDataFrameWidget.h
colinw7/CQDataFrame
bc82952dbe9f9a3fc79cc274f4c0ee97abcf0d5e
[ "MIT" ]
null
null
null
#ifndef CQDataFrameWidget_H #define CQDataFrameWidget_H #include <CQScrollArea.h> #include <QFrame> class CQTcl; class QMenu; class QTextStream; namespace CQDataFrame { class Area; class Frame; class WidgetContents; class Widget : public QFrame { Q_OBJECT Q_PROPERTY(int contentsWidth READ width WRITE setContentsWidth ) Q_PROPERTY(int contentsHeight READ height WRITE setContentsHeight) public: using Args = std::vector<std::string>; public: Widget(Area *area); //--- void init(); virtual void addWidgets() { } //--- Area *area() const { return area_; } void setArea(Area *area) { area_ = area; } Area *larea() const; Area *rarea() const; Frame *frame() const; CQTcl *qtcl() const; virtual QString id() const = 0; int pos() const { return pos_; } void setPos(int i) { pos_ = i; } bool isExpanded() const { return expanded_; } virtual void setExpanded(bool b); bool isEditing() const { return editing_; } bool isDocked() const { return docked_; } bool isResizeFrame () const { return resizeFrame_ ; } bool isResizeContents() const { return resizeContents_; } int x() const { return x_; } virtual void setX(int x) { x_ = x; } int y() const { return y_; } virtual void setY(int y) { y_ = y; } void setWidgetWidth (int w); void setWidgetHeight(int h); virtual int contentsWidth() const { return width_; } virtual void setContentsWidth(int w); virtual int contentsHeight() const { return height_; } virtual void setContentsHeight(int h); virtual int defaultWidth () const { return 100; } virtual int defaultHeight() const { return 100; } virtual bool getNameValue(const QString &name, QVariant &value) const; virtual bool setNameValue(const QString &name, const QVariant &value); virtual void addMenuItems(QMenu *menu); void placeWidgets(); void updateSize(); virtual void draw(QPainter *painter, int dx, int dy) = 0; virtual void handleResize(int /*w*/, int /*h*/) { } void drawText(QPainter *painter, int x, int y, const QString &text); virtual void save(QTextStream &) { } //--- bool runTclCommand(const QString &line, QString &res) const; bool runUnixCommand(const std::string &cmd, const Args &args, QString &res) const; void parseCommand(const QString &line, std::string &name, Args &args) const; //--- void paintEvent(QPaintEvent *e) override; void mousePressEvent (QMouseEvent *e) override; void mouseMoveEvent (QMouseEvent *e) override; void mouseReleaseEvent(QMouseEvent *e) override; //--- void contentsMousePress (QMouseEvent *e); void contentsMouseMove (QMouseEvent *e); void contentsMouseRelease(QMouseEvent *e); bool pixelToText(const QPoint &p, int &lineNum, int &charNum); void drawContents(QPainter *painter); //void resizeContents(int w, int h); virtual QSize contentsSizeHint() const = 0; virtual QSize contentsSize() const = 0; QSize sizeHint() const override; protected: void setFixedFont(); signals: void contentsChanged(); protected slots: void contentsUpdateSlot(); void setExpandedSlot(bool b) { setExpanded(b); } virtual void setEditing(bool b); virtual void setDocked(bool b); virtual void setResizeFrame (bool b); virtual void setResizeContents(bool b); void copySlot(); void pasteSlot(); void closeSlot(); void loadSlot(); void saveSlot(); protected: class Line { public: Line() = default; Line(const QString &text) : text_(text) { } const QString &text() const { return text_; } void setText(const QString &s) { text_ = s; } int x() const { return x_; } void setX(int x) { x_ = x; } int y() const { return y_; } void setY(int y) { y_ = y; } bool isJoin() const { return join_; } void setJoin(bool b) { join_ = b; } private: QString text_; int x_ { 0 }; int y_ { 0 }; bool join_ { false }; }; using LineList = std::vector<Line *>; protected: virtual bool canCollapse() const { return true; } virtual bool canDock() const { return true; } virtual bool canMove () const { return true; } virtual bool canResize() const { return true; } virtual bool canEdit() const { return false; } virtual bool canClose() const { return true; } void contextMenuEvent(QContextMenuEvent *e) override; void drawBorder(QPainter *painter) const; QRect contentsRect() const; virtual void copy () { } virtual void paste(); virtual void pasteText(const QString &) { } void copyText(const QString &text) const; protected: struct CharData { int width { 10 }; int height { 12 }; int ascent { 12 }; //int descent { 0 }; }; void updateFont(); protected: struct MouseData { bool pressed { false }; int pressLineNum { -1 }; int pressCharNum { -1 }; int moveLineNum { -1 }; int moveCharNum { -1 }; bool dragging { false }; bool resizing { false }; bool resizeX { true }; bool resizeY { true }; int dragX { 0 }; int dragY { 0 }; int dragW { 0 }; int dragH { 0 }; int dragX1 { 0 }; int dragY1 { 0 }; int dragX2 { 0 }; int dragY2 { 0 }; void reset() { pressed = false; dragging = false; resizing = false; resizeX = true; resizeY = true; dragX = 0; dragY = 0; dragW = 0; dragH = 0; dragX1 = 0; dragY1 = 0; dragX2 = 0; dragY2 = 0; } void resetSelection() { pressLineNum = -1; pressCharNum = -1; moveLineNum = -1; moveCharNum = -1; } }; using ScrollArea = CQScrollArea; using Contents = WidgetContents; Area* area_ { nullptr }; //!< parent area ScrollArea* scrollArea_ { nullptr }; //!< scroll area Contents* contents_ { nullptr }; //!< scrolled contents int pos_ { -1 }; bool expanded_ { true }; bool editing_ { false }; bool docked_ { false }; bool resizeFrame_ { true }; bool resizeContents_ { true }; QColor bgColor_ { 240, 240, 240 }; QColor fgColor_ { 0, 0, 0 }; CharData charData_; int margin_ { 2 }; int x_ { 0 }; int y_ { 0 }; int width_ { -1 }; int height_ { -1 }; LineList lines_; MouseData mouseData_; }; //--- class WidgetContents : public QFrame { Q_OBJECT public: WidgetContents(Widget *widget); //--- void mousePressEvent (QMouseEvent *e) override; void mouseMoveEvent (QMouseEvent *e) override; void mouseReleaseEvent(QMouseEvent *e) override; void paintEvent(QPaintEvent *e) override; void resizeEvent(QResizeEvent *e) override; //--- QSize sizeHint() const override; QSize contentsSize() const; private: Widget* widget_ { nullptr }; }; } #endif
22.132492
84
0.617588
[ "vector" ]
0fa8c6e8625f93640541e7606c845f5b9ffa1995
274
h
C
include/entity2/CompComplex.h
xzrunner/entity2
11de4d6217c14a85f516b1d624fd155287c2efb9
[ "MIT" ]
null
null
null
include/entity2/CompComplex.h
xzrunner/entity2
11de4d6217c14a85f516b1d624fd155287c2efb9
[ "MIT" ]
null
null
null
include/entity2/CompComplex.h
xzrunner/entity2
11de4d6217c14a85f516b1d624fd155287c2efb9
[ "MIT" ]
null
null
null
#pragma once #include <entity0/Component.h> #include <entity0/Entity.h> #include <vector> namespace e2 { struct CompComplex : public e0::Component { std::shared_ptr<std::vector<e0::Entity>> children = std::make_unique<std::vector<e0::Entity>>(); }; // CompComplex }
15.222222
52
0.70438
[ "vector" ]
0fbbeeea9bcdf66630cd50b3366cabcb62f0c221
861
c
C
nitan/clone/animal/lamb.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
1
2019-03-27T07:25:16.000Z
2019-03-27T07:25:16.000Z
nitan/clone/animal/lamb.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
nitan/clone/animal/lamb.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
// lamb.c // Last Modified by winder on Aug. 1 2002 inherit NPC; void create() { set_name("黃羊", ({ "lamb", "yang", "huang yang" }) ); set("race", "走畜"); set("age", 11); set("long", "一隻野黃羊,正低頭認真地吃着草。\n"); set("str", 26); set("cor", 30); set("combat_exp", 800); set("chat_chance", 6); set("chat_msg", ({ "黃羊咩~~咩~~的叫了幾聲。\n" }) ); set_temp("apply/attack", 15); set_temp("apply/damage", 6); set_temp("apply/armor", 2); setup(); } void die() { object ob; message_vision("$N倒在地上,咩~~的一聲就死了!\n", this_object()); ob = new(__DIR__"obj/yangrou"); ob->move(environment(this_object())); ob = new(__DIR__"obj/yangpi"); ob->move(environment(this_object())); destruct(this_object()); }
21.525
61
0.493612
[ "object" ]
0fd642e8022c11d02aa234806c0c016e9f5f225d
4,689
h
C
include/omnic/CalibratedProjector.h
WilstonOreo/omnicalib
5dcea24eb68fab19860e37c272f32288cd3fce71
[ "MIT" ]
4
2017-04-14T14:15:02.000Z
2018-12-09T17:18:27.000Z
include/omnic/CalibratedProjector.h
cr8tr/omnicalib
5dcea24eb68fab19860e37c272f32288cd3fce71
[ "MIT" ]
null
null
null
include/omnic/CalibratedProjector.h
cr8tr/omnicalib
5dcea24eb68fab19860e37c272f32288cd3fce71
[ "MIT" ]
2
2019-12-05T07:36:31.000Z
2021-07-21T09:58:34.000Z
/* Copyright (c) 2014-2016 "OmniCalibration" by Michael Winkelmann * Calibration Format for Omnidome (http://omnido.me). * Created by Michael Winkelmann aka Wilston Oreo (@WilstonOreo) * * This file is part of Omnidome. * * Simplified BSD license * Copyright (c) 2016 * 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 HOLDERS 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 OMNIC_CALIBRATEDPROJECTOR_H_ #define OMNIC_CALIBRATEDPROJECTOR_H_ #include "Rect.h" #include "PixelData.h" #include "ColorCorrectionLOT.h" namespace omnic { /// Data structure for calibrated projector class CalibratedProjector { public: /// Return flag if projector has a virtual screen assigned inline bool virtualScreen() const { return screenInfo_ & 1; // Virtual screen is first bit } /// Set virtual screen inline void setVirtualScreen(bool _virtualScreen) { screenInfo_ &= 0xFFFFFFFE; screenInfo_ |= _virtualScreen; } /// Rectangle representing the screen geometry inline Rect const& screenGeometry() const { return screenGeometry_; } /// Set screen geometry inline void setScreenGeometry(Rect const& _screenGeometry) { screenGeometry_ = _screenGeometry; } /// Rectangle representing the content placement inside the screen inline Rect const& contentGeometry() const { return contentGeometry_; } /// Set Content geometry inline void setContentGeometry(Rect const& _contentGeometry) { contentGeometry_ = _contentGeometry; } /// Return color correction look up table inline ColorCorrectionLOT const& colorCorrection() const { return colorCorrection_; } /// Set new color correction look up table inline void setColorCorrection(ColorCorrectionLOT const& _colorCorrection) { colorCorrection_ = _colorCorrection; } /// Return pixel data inline PixelData const& pixelData() const { return pixelData_; } /// Set pixel data inline void setPixelData(PixelData const& _pixelData) { pixelData_ = _pixelData; } /// Load from stream template<typename STREAM> void load(STREAM& _is, Version _version = Version::current()) { using namespace util; readBinary(_is,screenInfo_); screenGeometry_.load(_is,_version); contentGeometry_.load(_is,_version); colorCorrection_.load(_is,_version); pixelData_.load(_is,_version); } /// Save to stream template<typename STREAM> void save(STREAM& _os, Version _version = Version::current()) const { using namespace util; writeBinary(_os,screenInfo_); screenGeometry_.save(_os,_version); contentGeometry_.save(_os,_version); colorCorrection_.save(_os,_version); pixelData_.save(_os,_version); } /// Test for equality inline friend bool operator==( CalibratedProjector const& _lhs, CalibratedProjector const& _rhs) { return (_lhs.screenInfo_ == _rhs.screenInfo_) && (_lhs.screenGeometry_ == _rhs.screenGeometry_) && (_lhs.contentGeometry_ == _lhs.contentGeometry_) && (_lhs.colorCorrection_ == _rhs.colorCorrection_) && (_lhs.pixelData_ == _rhs.pixelData_) ; } private: uint32_t screenInfo_ = 0; Rect screenGeometry_; Rect contentGeometry_; ColorCorrectionLOT colorCorrection_; PixelData pixelData_; }; } #endif /* OMNIC_CALIBRATEDPROJECTOR_H_ */
33.492857
82
0.707827
[ "geometry" ]
0fe6983ae99070f3b807797675a7e9bdf81c8d91
5,880
h
C
RegExp/HexControl.h
y11en/RegExp
c51b2e99d957f0f20284af89e0cf280aa316d3d0
[ "MIT" ]
825
2021-07-22T19:14:09.000Z
2022-03-30T14:12:59.000Z
RegExp/HexControl.h
y11en/RegExp
c51b2e99d957f0f20284af89e0cf280aa316d3d0
[ "MIT" ]
28
2021-07-24T17:30:46.000Z
2022-01-10T23:11:08.000Z
RegExp/HexControl.h
y11en/RegExp
c51b2e99d957f0f20284af89e0cf280aa316d3d0
[ "MIT" ]
64
2021-07-23T02:15:21.000Z
2022-03-28T07:07:53.000Z
#pragma once #include <map> #include <string> struct IBufferManager { virtual uint32_t GetData(int64_t offset, uint8_t* buffer, uint32_t count) = 0; virtual bool Insert(int64_t offset, const uint8_t* data, uint32_t count) = 0; virtual bool Delete(int64_t offset, size_t count) = 0; virtual bool SetData(int64_t offset, const uint8_t* data, uint32_t count) = 0; virtual int64_t GetSize() const = 0; virtual uint8_t* GetRawData(int64_t offset) = 0; virtual bool IsReadOnly() const = 0; virtual bool Increase(uint32_t size) { return false; } virtual ~IBufferManager() = default; }; struct HexControlColors { COLORREF Text{ ::GetSysColor(COLOR_WINDOWTEXT) }; COLORREF Background{ ::GetSysColor(COLOR_WINDOW) }; COLORREF Ascii{ RGB(128, 0, 0) }; COLORREF Offset{ RGB(0, 0, 128) }; COLORREF SelectionText{ ::GetSysColor(COLOR_HIGHLIGHTTEXT) }; COLORREF SelectionBackground{ ::GetSysColor(COLOR_HIGHLIGHT) }; }; enum class SelectionType { Simple, Box }; class Selection { public: void SetSimple(int64_t offset, int64_t len); void SetBox(int64_t offset, int bytesPerLine, int width, int height); void SetAnchor(int64_t offset); int64_t GetOffset() const; int64_t GetAnchor() const; bool IsSelected(int64_t offset) const; bool IsEmpty() const; SelectionType GetSelectionType() const; int64_t GetLength() const { return _length; } void Clear(); private: SelectionType _type{ SelectionType::Simple }; int64_t _offset{ -1 }, _anchor{ -1 }; int64_t _length{ 0 }; int _width, _height, _bytesPerLine; }; const UINT HCN_SIZECHANGED = NM_FIRST - 3000; const UINT HCN_RCLICK = NM_FIRST - 3001; struct HCNOTIFY { NMHDR hdr; }; class CHexControl : public CBufferedPaintWindowImpl<CHexControl> { public: DECLARE_WND_CLASS_EX(L"WTLHexControl", CS_OWNDC | CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW, NULL) HWND GetHwnd() const; void SetBufferManager(IBufferManager* mgr); IBufferManager* GetBufferManager() const; void SetReadOnly(bool readonly); bool IsReadOnly() const; void SetAllowExtension(bool allow); bool IsAllowExtension() const; void SetSize(int64_t size); bool SetDataSize(int32_t size); int32_t GetDataSize() const; bool SetBytesPerLine(int32_t bytesPerLine); int32_t GetBytesPerLine() const; bool Copy(int64_t offset = -1, int64_t size = 0); bool Paste(int64_t offset = -1); bool CanCopy() const; bool CanPaste() const; bool Cut(int64_t offset = -1, int64_t size = 0); bool Delete(int64_t offset = -1, int64_t size = 0); bool CanCut() const; bool CanDelete() const; int64_t SetBiasOffset(int64_t offset); int64_t GetBiasOffset() const; HexControlColors& GetColors(); std::wstring GetText(int64_t offset, int64_t size); void Refresh(); BEGIN_MSG_MAP(CHexControl) MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLeftButtonDown) MESSAGE_HANDLER(WM_SIZE, OnSize) MESSAGE_HANDLER(WM_KEYDOWN, OnKeyDown) MESSAGE_HANDLER(WM_MOUSEMOVE, OnMouseMove) MESSAGE_HANDLER(WM_LBUTTONUP, OnLeftButtonUp) MESSAGE_HANDLER(WM_CHAR, OnChar) MESSAGE_HANDLER(WM_CREATE, OnCreate) MESSAGE_HANDLER(WM_VSCROLL, OnVScroll) MESSAGE_HANDLER(WM_HSCROLL, OnHScroll) MESSAGE_HANDLER(WM_MOUSEWHEEL, OnMouseWheel) MESSAGE_HANDLER(WM_SETFOCUS, OnSetFocus) MESSAGE_HANDLER(WM_KILLFOCUS, OnKillFocus) MESSAGE_HANDLER(WM_GETDLGCODE, OnGetDialogCode) MESSAGE_HANDLER(WM_CONTEXTMENU, OnContextMenu) CHAIN_MSG_MAP(CBufferedPaintWindowImpl<CHexControl>) END_MSG_MAP() void DoPaint(CDCHandle dc, RECT& rect); private: LRESULT OnSize(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnHScroll(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnVScroll(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnMouseWheel(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnSetFocus(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnKillFocus(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnLeftButtonDown(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnGetDialogCode(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnKeyDown(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnChar(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnMouseMove(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnLeftButtonUp(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnContextMenu(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); private: void RecalcLayout(); void InitFontMetrics(); CPoint GetPointFromOffset(int64_t offset) const; int64_t GetOffsetFromPoint(const POINT& pt) const; void DrawNumber(CDCHandle dc, int64_t offset, uint64_t value, int editDigits); PCWSTR FormatNumber(ULONGLONG number) const; LRESULT SendNotify(HCNOTIFY* notify); void UpdateCaret(); void RedrawWindow(RECT* = nullptr); void ClearSelection(); void CommitValue(int64_t offset, uint64_t value); void ResetInput(); int64_t NormalizeOffset(int64_t offset) const; void RedrawCaretLine(); private: HexControlColors m_Colors; CFont m_Font; int m_FontPointSize{ 100 }; int m_Lines{ 1 }; int m_CharWidth, m_CharHeight; IBufferManager* m_Buffer{ nullptr }; std::vector<std::wstring> m_Text; int64_t m_StartOffset{ 0 }, m_EndOffset; int32_t m_DataSize{ 1 }, m_BytesPerLine{ 32 }; int64_t m_CaretOffset{ 0 }; int m_AddressDigits{ 4 }; int m_EditDigits{ 0 }, m_LastDigits{ 0 }; Selection m_Selection; HCNOTIFY m_NotifyData; uint64_t m_CurrentInput{ 0 }, m_OldValue; bool m_InsertMode{ false }; bool m_ReadOnly{ false }; };
34.792899
99
0.739116
[ "vector" ]
0feb79eb797b8bc7b0fd75c448c8952742458702
672
h
C
distortion.h
ekmett/vr
8d321730e9bbacddbe652e0fb501e82fb0b7d76b
[ "BSD-2-Clause" ]
21
2016-08-16T22:31:37.000Z
2020-04-27T20:29:04.000Z
distortion.h
ekmett/vr
8d321730e9bbacddbe652e0fb501e82fb0b7d76b
[ "BSD-2-Clause" ]
null
null
null
distortion.h
ekmett/vr
8d321730e9bbacddbe652e0fb501e82fb0b7d76b
[ "BSD-2-Clause" ]
3
2016-08-26T06:32:37.000Z
2021-05-12T20:49:49.000Z
#pragma once #include "gl.h" #include "shader.h" #include "vao.h" namespace framework { // generates a preview of the warped display looks like struct distortion { struct vertex { vec2 p, r, g, b; GLushort eye; }; distortion(GLushort segmentsH = 43, GLushort segmentsV = 43); ~distortion(); void render_stencil(); void render(int view_mask, GLuint64 handle, float render_buffer_usage); bool debug_wireframe_render_stencil = false; bool debug_wireframe_render = false; private: vertex_array<vertex> vao; vertex_array<vec2> hidden_vao; int n_indices, n_hidden, n_hidden_left; gl::shader mask, warp; }; }
24.888889
75
0.688988
[ "render" ]
0ff5ef3421486e6793bd77cc0c242278bec8e29e
1,840
c
C
sources/intersect/square_intersect.c
gmzorz/MiniRT
ce87cd1745036391f54503f25eb815273918d7e6
[ "MIT" ]
10
2021-04-13T15:48:34.000Z
2022-03-10T19:16:24.000Z
sources/intersect/square_intersect.c
gmzorz/MiniRT
ce87cd1745036391f54503f25eb815273918d7e6
[ "MIT" ]
null
null
null
sources/intersect/square_intersect.c
gmzorz/MiniRT
ce87cd1745036391f54503f25eb815273918d7e6
[ "MIT" ]
null
null
null
/* ************************************************************************** */ /* */ /* :::::::: */ /* square_intersect.c :+: :+: */ /* +:+ */ /* By: goosterl <goosterl@student.codam.nl> +#+ */ /* +#+ */ /* Created: 2020/12/21 13:59:01 by goosterl #+# #+# */ /* Updated: 2021/04/12 13:52:31 by goosterl ######## odam.nl */ /* */ /* ************************************************************************** */ #if IS_BONUS == 0 # include <scene.h> # include <utils.h> # include <math.h> t_bool square_intersect(t_shapes *catch, t_hitrecord *rec) { t_square *square; t_square_vars vars; square = catch->shape; vars.pl = vec3_dot(square->normal, rec->ray.dir); if (fabs(vars.pl) < M_EPSILON) return (false); vars.p = vec3_sub(square->origin, rec->ray.origin); vars.t = vec3_dot(vars.p, square->normal) / vars.pl; if (vars.t < 0) return (false); vars.point = get_point(rec->ray.origin, rec->ray.dir, vars.t); vars.diff = vec3_sub(vars.point, square->origin); vars.u = vec3_dot(square->span_a, vars.diff); vars.v = vec3_dot(square->span_b, vars.diff); if ((fabs(vars.u) > square->size * 0.5 || fabs(vars.v) > square->size * 0.5) || vars.t > rec->distance) return (false); rec->point = vars.point; rec->normal = square->normal; if (vars.pl > 0) rec->normal = vec3_mult_s(rec->normal, -1); return (hit(catch, rec, vars.t)); } #endif
40
80
0.403804
[ "shape" ]
0ff915f41fa08cd2a37cb4369361bccb95c04814
1,496
h
C
of/ofxTraceSkeleton/example/src/ofApp.h
freder/skeleton-tracing
5fdd9e9274a33302ae981d237a622206a7b1f6e2
[ "MIT" ]
375
2020-04-19T22:47:27.000Z
2022-03-30T20:23:59.000Z
of/ofxTraceSkeleton/example/src/ofApp.h
freder/skeleton-tracing
5fdd9e9274a33302ae981d237a622206a7b1f6e2
[ "MIT" ]
17
2020-04-20T19:42:03.000Z
2021-12-26T04:37:26.000Z
of/ofxTraceSkeleton/example/src/ofApp.h
freder/skeleton-tracing
5fdd9e9274a33302ae981d237a622206a7b1f6e2
[ "MIT" ]
42
2020-04-20T02:02:17.000Z
2022-03-18T19:00:01.000Z
#pragma once #include "ofMain.h" #include "ofxGui.h" #include "ofxTraceSkeleton.h" // include the library #define INPUT_WIDTH 240 // input frame dimensions #define INPUT_HEIGHT 180 #define VIEW_SCALE 3 // upscale the result for viewing class ofApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void keyPressed(int key); void keyReleased(int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void mouseEntered(int x, int y); void mouseExited(int x, int y); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); // read from webcam/video file for demo ofVideoGrabber cap; ofVideoPlayer vid; std::vector<std::vector<ofVec2f>> polylines; // the polylines holding the skeleton // GUI for tweaking params ofxPanel gui; ofxFloatSlider ui_chunkSize; // affacts level of detail ofxToggle ui_drawRects; // visualize rects processed by algorithm ofxToggle ui_useCam; // use live webcam input ofxFloatSlider ui_camThresh; // threshold to binarize webcam input bool isVidInit; // because ofVideoPlayer::isInitialized() is broken... bool isCapInit; void preprocessWebcam(ofPixels& im); // add some vignette, some bluring and thresholding ofImage preprocessed; // the preprocessed image };
30.530612
90
0.709225
[ "vector" ]
b5a23b21b0272ac0d02ecb394cbe6e982f60f6d5
1,762
h
C
src/lepp3/models/Coordinate.h
am-lola/lepp3
7f92ce61bccad984e18ce86da0d8a1b9c48feb65
[ "MIT" ]
6
2017-01-16T10:41:56.000Z
2020-10-09T09:13:30.000Z
src/lepp3/models/Coordinate.h
am-lola/lepp3
7f92ce61bccad984e18ce86da0d8a1b9c48feb65
[ "MIT" ]
null
null
null
src/lepp3/models/Coordinate.h
am-lola/lepp3
7f92ce61bccad984e18ce86da0d8a1b9c48feb65
[ "MIT" ]
4
2015-08-07T13:07:32.000Z
2021-08-03T03:18:33.000Z
#ifndef LEPP3_MODELS_COORDINATE_H__ #define LEPP3_MODELS_COORDINATE_H__ #include <iostream> #include <pcl/common/pca.h> #include <pcl/common/common.h> namespace lepp { /** * A struct representing a spatial coordinate. */ struct Coordinate { double x; double y; double z; Coordinate() {} Coordinate(double x, double y, double z) : x(x), y(y), z(z) {} // Convenience constructors to seamlessly convert from Eigen::Vectors. Coordinate(Eigen::Vector3f const& vec) : x(vec(0)), y(vec(1)), z(vec(2)) {} Coordinate(Eigen::Vector3d const& vec) : x(vec(0)), y(vec(1)), z(vec(2)) {} template<class PointT> Coordinate(PointT const& pt) : x(pt.x), y(pt.y), z(pt.z) {} /** * Returns the squared norm of the vector. */ double square_norm() const { return x*x + y*y + z*z; } /* * Allow implicit conversion to Eigen::Vector3f for convenience */ operator Eigen::Vector3f() const { return Eigen::Vector3f(x, y, z); } }; inline Coordinate operator*(int scalar, Coordinate const& obj) { return Coordinate(scalar * obj.x, scalar * obj.y, scalar * obj.z); } inline Coordinate operator-(Coordinate const& obj) { return Coordinate(-obj.x, -obj.y, -obj.z); } inline Coordinate operator+(Coordinate const& lhs, Coordinate const& rhs) { return Coordinate(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z); } inline Coordinate operator-(Coordinate const& lhs, Coordinate const& rhs) { return lhs + (-rhs); } inline Coordinate operator/(Coordinate const& lhs, double coef) { return Coordinate(lhs.x / coef, lhs.y / coef, lhs.z / coef); } inline std::ostream& operator<<(std::ostream& out, Coordinate const& coord) { out << "(" << coord.x << ", " << coord.y << ", " << coord.z << ")"; return out; } } // namespace lepp #endif
27.107692
77
0.660613
[ "vector" ]
b5a46532375b0b73fc7c933568fbb15de66f6a25
4,426
h
C
CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/javax/swing/tree/DefaultMutableTreeNode.h
chewaiwai/huaweicloud-sdk-c-obs
fbcd3dadd910c22af3a91aeb73ca0fee94d759fb
[ "Apache-2.0" ]
22
2019-06-13T01:16:44.000Z
2022-03-29T02:42:39.000Z
CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/javax/swing/tree/DefaultMutableTreeNode.h
chewaiwai/huaweicloud-sdk-c-obs
fbcd3dadd910c22af3a91aeb73ca0fee94d759fb
[ "Apache-2.0" ]
26
2019-09-20T06:46:05.000Z
2022-03-11T08:07:14.000Z
CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/javax/swing/tree/DefaultMutableTreeNode.h
chewaiwai/huaweicloud-sdk-c-obs
fbcd3dadd910c22af3a91aeb73ca0fee94d759fb
[ "Apache-2.0" ]
14
2019-07-15T06:42:39.000Z
2022-02-15T10:32:28.000Z
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*- #ifndef __javax_swing_tree_DefaultMutableTreeNode__ #define __javax_swing_tree_DefaultMutableTreeNode__ #pragma interface #include <java/lang/Object.h> #include <gcj/array.h> extern "Java" { namespace javax { namespace swing { namespace tree { class DefaultMutableTreeNode; class MutableTreeNode; class TreeNode; } } } } class javax::swing::tree::DefaultMutableTreeNode : public ::java::lang::Object { public: DefaultMutableTreeNode(); DefaultMutableTreeNode(::java::lang::Object *); DefaultMutableTreeNode(::java::lang::Object *, jboolean); virtual ::java::lang::Object * clone(); virtual ::java::lang::String * toString(); virtual void add(::javax::swing::tree::MutableTreeNode *); virtual ::javax::swing::tree::TreeNode * getParent(); virtual void remove(jint); virtual void remove(::javax::swing::tree::MutableTreeNode *); private: void writeObject(::java::io::ObjectOutputStream *); void readObject(::java::io::ObjectInputStream *); public: virtual void insert(::javax::swing::tree::MutableTreeNode *, jint); virtual JArray< ::javax::swing::tree::TreeNode * > * getPath(); virtual ::java::util::Enumeration * children(); virtual void setParent(::javax::swing::tree::MutableTreeNode *); virtual ::javax::swing::tree::TreeNode * getChildAt(jint); virtual jint getChildCount(); virtual jint getIndex(::javax::swing::tree::TreeNode *); virtual void setAllowsChildren(jboolean); virtual jboolean getAllowsChildren(); virtual void setUserObject(::java::lang::Object *); virtual ::java::lang::Object * getUserObject(); virtual void removeFromParent(); virtual void removeAllChildren(); virtual jboolean isNodeAncestor(::javax::swing::tree::TreeNode *); virtual jboolean isNodeDescendant(::javax::swing::tree::DefaultMutableTreeNode *); virtual ::javax::swing::tree::TreeNode * getSharedAncestor(::javax::swing::tree::DefaultMutableTreeNode *); virtual jboolean isNodeRelated(::javax::swing::tree::DefaultMutableTreeNode *); virtual jint getDepth(); virtual jint getLevel(); public: // actually protected virtual JArray< ::javax::swing::tree::TreeNode * > * getPathToRoot(::javax::swing::tree::TreeNode *, jint); public: virtual JArray< ::java::lang::Object * > * getUserObjectPath(); virtual ::javax::swing::tree::TreeNode * getRoot(); virtual jboolean isRoot(); virtual ::javax::swing::tree::DefaultMutableTreeNode * getNextNode(); virtual ::javax::swing::tree::DefaultMutableTreeNode * getPreviousNode(); virtual ::java::util::Enumeration * preorderEnumeration(); virtual ::java::util::Enumeration * postorderEnumeration(); virtual ::java::util::Enumeration * breadthFirstEnumeration(); virtual ::java::util::Enumeration * depthFirstEnumeration(); virtual ::java::util::Enumeration * pathFromAncestorEnumeration(::javax::swing::tree::TreeNode *); virtual jboolean isNodeChild(::javax::swing::tree::TreeNode *); virtual ::javax::swing::tree::TreeNode * getFirstChild(); virtual ::javax::swing::tree::TreeNode * getLastChild(); virtual ::javax::swing::tree::TreeNode * getChildAfter(::javax::swing::tree::TreeNode *); virtual ::javax::swing::tree::TreeNode * getChildBefore(::javax::swing::tree::TreeNode *); virtual jboolean isNodeSibling(::javax::swing::tree::TreeNode *); virtual jint getSiblingCount(); virtual ::javax::swing::tree::DefaultMutableTreeNode * getNextSibling(); virtual ::javax::swing::tree::DefaultMutableTreeNode * getPreviousSibling(); virtual jboolean isLeaf(); virtual ::javax::swing::tree::DefaultMutableTreeNode * getFirstLeaf(); virtual ::javax::swing::tree::DefaultMutableTreeNode * getLastLeaf(); virtual ::javax::swing::tree::DefaultMutableTreeNode * getNextLeaf(); virtual ::javax::swing::tree::DefaultMutableTreeNode * getPreviousLeaf(); virtual jint getLeafCount(); private: static const jlong serialVersionUID = -4298474751201349152LL; public: static ::java::util::Enumeration * EMPTY_ENUMERATION; public: // actually protected ::javax::swing::tree::MutableTreeNode * __attribute__((aligned(__alignof__( ::java::lang::Object)))) parent; ::java::util::Vector * children__; ::java::lang::Object * userObject; jboolean allowsChildren; public: static ::java::lang::Class class$; }; #endif // __javax_swing_tree_DefaultMutableTreeNode__
41.754717
110
0.722323
[ "object", "vector" ]
b5a4b8ac71e82776e7e2c405b5f1246ea5e713f4
4,305
h
C
predicator_collision/src/predicate.h
cpaxton/predicator
16691dde8576d5af342bb9ea8906141e57006220
[ "BSD-2-Clause" ]
null
null
null
predicator_collision/src/predicate.h
cpaxton/predicator
16691dde8576d5af342bb9ea8906141e57006220
[ "BSD-2-Clause" ]
null
null
null
predicator_collision/src/predicate.h
cpaxton/predicator
16691dde8576d5af342bb9ea8906141e57006220
[ "BSD-2-Clause" ]
null
null
null
#include <ros/ros.h> // -------------------------------------- // FCL stuff #include <fcl/data_types.h> // Triangles, other simple data types #include <fcl/shape/geometric_shapes.h> // spheres, cylinders, etc. #include <fcl/BVH/BVH_model.h> // -------------------------------------- // MoveIt types and functions //#include <moveit_ros/robot_model_loader/robot_model_loader.h> #include <moveit_msgs/PlanningScene.h> #include <moveit_msgs/PlanningSceneWorld.h> #include <moveit_msgs/CollisionObject.h> // -------------------------------------- // Data types and other input #include <geometry_msgs/Pose.h> #include <sensor_msgs/JointState.h> #include <tf/transform_listener.h> #include <shape_msgs/SolidPrimitive.h> #include <shape_msgs/Mesh.h> #include <shape_msgs/MeshTriangle.h> // -------------------------------------- // Predicator stuff #include <predicator_msgs/PredicateStatement.h> #include <predicator_msgs/PredicateList.h> #include <map> #include <string> namespace predicator { typedef fcl::BVHModel<fcl::OBBRSS> Model; class CollisionEntity; /** * GeometryParser * Listens for PlanningScene updates and deals with them. * * NOTE: this should also connect to MoveIt, for convenience functions describing robot/world interactions. * Right now, there are no names sent for individual links in world objects on the PlanningScene topic. * This could cause trouble if we want to identify specific parts of the objects by name. */ class GeometryParser { private: ros::Subscriber sub_; // listen to incoming planning scenes ros::Publisher pub_; // publish predicate information ros::NodeHandle nh_; // node handle for extra stuff protected: // set of all collision entities std::map<std::string, CollisionEntity> entities_; void addMesh(const std::string &id, const shape_msgs::Mesh &mesh); void addPrimitive(const std::string &id, const shape_msgs::SolidPrimitive &primitive); /** * updateCollisionObject() * Called once for each CollisionObject method. * If operation == add or append, it will add these entities to that object. * Else, */ void updateCollisionObject(const moveit_msgs::CollisionObject &co); public: void planningSceneCallback(const moveit_msgs::PlanningScene::ConstPtr &msg); /** * GeometryParser() * Constructor, creates a subscriber and a publisher among other things */ GeometryParser(const std::string &planning_topic, const std::string &predicate_topic); }; /** * Entity * Defines an unknown object in the world. * Consists of Collision Links, which are smaller objects. */ class CollisionEntity { private: std::string id_; // what identifies this object? bool enabled_; // are we tracking predicates? bool open_; // are we still reading links? geometry_msgs::Pose pose_; protected: Model * model; public: const std::string &getId() const; CollisionEntity(const std::string &id = ""); void setId(const std::string &new_id); /** * setEnabled() * Set the object to be enabled in the world. * Is the object enabled? AKA, should we report predicates? */ void setEnabled(bool enabled); /** * isEnabled() * Is the object enabled? AKA, should we report predicates? */ bool isEnabled() const; /** * isOpen() * Is this open to add more links to it? */ const bool isOpen() const; /** * open() * Set this object to accept new links */ void open(); /** * close() * Stop adding new links */ void close(); /** * purge() * Delete the underlying structure(s) */ void purge(); /** * addLink() * Append a single sub model to the object. */ void addLink(const std::vector<fcl::Vec3f> &vertices, const std::vector<fcl::Triangle> &triangles); }; /** * Volume * Defines a region of space we are interested in for some reason. */ class Volume { }; /** * KnownEntity * Defines an object in the world. This is based on an URDF of that object. * */ class KnownEntity { }; /** * Observation * Defines an unknown point cloud in the world. */ class Observation { }; }
24.6
109
0.642509
[ "mesh", "object", "shape", "vector", "model" ]
b5ac6bf8b7a6255c2548d18169c3a9c85b959b6b
1,611
h
C
modules/spaint/include/spaint/features/interface/FeatureCalculator.h
torrvision/spaint
9cac8100323ea42fe439f66407b832b88f72d2fd
[ "Unlicense" ]
197
2015-10-01T07:23:01.000Z
2022-03-23T03:02:31.000Z
modules/spaint/include/spaint/features/interface/FeatureCalculator.h
GucciPrada/spaint
b09ff1ec0d9e123cf316f2737e1b70b5ecc0beea
[ "Unlicense" ]
16
2016-03-26T13:01:08.000Z
2020-09-02T09:13:49.000Z
modules/spaint/include/spaint/features/interface/FeatureCalculator.h
GucciPrada/spaint
b09ff1ec0d9e123cf316f2737e1b70b5ecc0beea
[ "Unlicense" ]
62
2015-10-03T07:14:59.000Z
2021-08-31T08:58:18.000Z
/** * spaint: FeatureCalculator.h * Copyright (c) Torr Vision Group, University of Oxford, 2015. All rights reserved. */ #ifndef H_SPAINT_FEATURECALCULATOR #define H_SPAINT_FEATURECALCULATOR #include "../../util/SpaintVoxelScene.h" namespace spaint { /** * \brief An instance of a class deriving from this one can be used to calculate feature descriptors for voxels sampled from a scene. */ class FeatureCalculator { //#################### DESTRUCTOR #################### public: /** * \brief Destroys the feature calculator. */ virtual ~FeatureCalculator() {} //#################### PUBLIC ABSTRACT MEMBER FUNCTIONS #################### public: /** * \brief Calculates feature descriptors for the specified voxels (grouped by label). * * \param voxelLocationsMB A memory block containing the locations of the voxels for which to calculate feature descriptors. * \param scene The scene. * \param featuresMB A memory block into which to store the calculated feature descriptors (packed sequentially). */ virtual void calculate_features(const ORUtils::MemoryBlock<Vector3s>& voxelLocationsMB, const SpaintVoxelScene *scene, ORUtils::MemoryBlock<float>& featuresMB) const = 0; /** * \brief Gets the size of feature vector generated by this feature calculator. * * \return The size of feature vector generated by this feature calculator. */ virtual size_t get_feature_count() const = 0; }; //#################### TYPEDEFS #################### typedef boost::shared_ptr<const FeatureCalculator> FeatureCalculator_CPtr; } #endif
31.588235
172
0.677219
[ "vector" ]
b5b0e8ebeb2e1ae91d9899686f23ab0a3f9315ca
2,430
h
C
ainstein_radar_filters/include/ainstein_radar_filters/tracking_filter.h
mission-systems-pty-ltd/ainstein_radar
9f348b668ad2957f08879e0b585a2c1a78c39f75
[ "BSD-3-Clause" ]
24
2019-08-22T09:10:32.000Z
2022-03-14T13:22:01.000Z
ainstein_radar_filters/include/ainstein_radar_filters/tracking_filter.h
mission-systems-pty-ltd/ainstein_radar
9f348b668ad2957f08879e0b585a2c1a78c39f75
[ "BSD-3-Clause" ]
11
2019-10-04T16:05:02.000Z
2022-03-09T10:18:41.000Z
ainstein_radar_filters/include/ainstein_radar_filters/tracking_filter.h
mission-systems-pty-ltd/ainstein_radar
9f348b668ad2957f08879e0b585a2c1a78c39f75
[ "BSD-3-Clause" ]
24
2019-07-20T02:45:37.000Z
2022-01-24T07:02:06.000Z
#ifndef TRACKING_FILTER_H_ #define TRACKING_FILTER_H_ #include <Eigen/Eigen> #include <chrono> #include <mutex> #include <thread> #include <iostream> #include <ainstein_radar_filters/radar_target_kf.h> namespace ainstein_radar_filters { // simple, ROS-independent target class class RadarTarget { public: RadarTarget(void) { } RadarTarget(double range, double speed, double azimuth, double elevation) { this->range = range; this->speed = speed; this->azimuth = azimuth; this->elevation = elevation; } ~RadarTarget(void) { } public: double range; double speed; double azimuth; double elevation; }; class TrackingFilter { public: TrackingFilter(void) { print_debug_ = false; is_running_ = true; } ~TrackingFilter() { } class FilterParameters { public: FilterParameters(void) { } ~FilterParameters(void) { } double filter_process_rate; double filter_min_time; double filter_timeout; double filter_val_gate_thresh; // Underlying Kalman Filter parameters (shared among all KFs): RadarTargetKF::FilterParameters kf_params; }; void setFilterParameters(const FilterParameters& params) { filter_process_rate_ = params.filter_process_rate; filter_min_time_ = params.filter_min_time; filter_timeout_ = params.filter_timeout; filter_val_gate_thresh_ = params.filter_val_gate_thresh; RadarTargetKF::setFilterParameters(params.kf_params); } void initialize(void); void processFiltersLoop(double frequency); void updateFilters(const std::vector<RadarTarget>& targets); void stopRunning(void) { is_running_ = false; } void getTrackedObjects(std::vector<RadarTarget>& tracked_objects); void getTrackedObjectTargets(std::vector<std::vector<RadarTarget>>& tracked_objects); static const int max_tracked_targets; private: // Parameters: double filter_process_rate_; double filter_min_time_; double filter_timeout_; double filter_val_gate_thresh_; bool print_debug_; bool is_running_; std::unique_ptr<std::thread> filter_process_thread_; std::mutex mutex_; std::vector<ainstein_radar_filters::RadarTargetKF> filters_; std::vector<std::vector<ainstein_radar_filters::RadarTarget>> filter_targets_; std::vector<int> meas_count_vec_; std::vector<bool> is_tracked_; }; } // namespace ainstein_radar_filters #endif // RADAR_TRACKING_FILTER_H_
21.130435
87
0.739095
[ "vector" ]
b5b626abbc570913438b7bd4eaa99e15d835a6a3
12,228
c
C
kungfu/class/ultra/dugu.c
zhangyifei/mud
b2090bbd2a8d3d82b86148d794a7ca59cd2429f3
[ "MIT" ]
69
2018-03-08T18:24:44.000Z
2022-02-24T13:43:53.000Z
kungfu/class/ultra/dugu.c
zhangyifei/mud
b2090bbd2a8d3d82b86148d794a7ca59cd2429f3
[ "MIT" ]
3
2019-04-24T12:21:19.000Z
2021-03-28T23:34:58.000Z
kungfu/class/ultra/dugu.c
zhangyifei/mud
b2090bbd2a8d3d82b86148d794a7ca59cd2429f3
[ "MIT" ]
33
2017-12-23T05:06:58.000Z
2021-08-16T02:42:59.000Z
// huang 黄裳 #include <ansi.h> inherit NPC; inherit F_MASTER; inherit F_NOCLONE; mixed ask_opinion(); #define ULTRA_OPINION "宗师" #define OPINION_TYPE HIY "兵器功夫" NOR #define MY_OPINION "weapon" string *my_opinions = ({ "sword", "blade", "staff", "hammer", "club", "whip", "dagger", }); // 该头文件必须在这里嵌入 #include "ultra.h" void check_weapon(); void create() { set_name("独孤求败", ({ "dugu qiubai", "dugu" }) ); set("title", HIC "大宗师" NOR); set("gender", "男性"); set("age", 48); set("long", "此人诚恳敦厚,眉目菱角分明,气宇轩昂。\n"); set("attitude", "peaceful"); set("str", 38); set("int", 39); set("con", 32); set("dex", 33); set("max_qi", 20000); set("max_jing", 20000); set("neili", 30000); set("max_neili", 30000); set("jiali", 100); set("combat_exp", 50000000); set("inquiry", ([ "独孤九剑" : "我把天下武功的变化归结在九剑之中,算不得是剑法,若拘\n" "泥于形势就无法理解其中奥妙。\n" "独孤九剑真正的精妙之处不在于其剑招,而是其" HIY "剑意" NOR + CYN "。", "剑意" : "剑招乃其形,而剑意乃其神,吾花费毕生经历于华山一山洞\n" HIY"空室" NOR + CYN"中参悟出独孤九剑之剑意,并将其笔录在「" HIY "独孤九剑残" "本" NOR + CYN"」" NOR + CYN "内。\n" NOR, "空室" : "穿过我身后的山洞就会发现一个峭壁,我将残本藏于其间的\n" "山洞内,并请高手匠人设计出六把不同锁将其锁住,每把琐" "连接着一个开锁\n的机关,机关藏于六个不同的石室内,须得" "将所有" HIY "锁" NOR + CYN "打开方能进入空室。\n" NOR, "锁" : "年深日久,开锁的方法我已不记得了。我只记得如果石门\n" "上的六把火炬都点燃了,石门上的锁也就开了。\n", "无招胜有招" : "那就是独孤九剑的最高境界!\n", "独孤九剑残本" : "如果你能拿来给话我到是可以把独孤九剑中的精妙之处传\n授于你。\n", "评价" : (: ask_opinion :), "opinion" : (: ask_opinion :), "武学修养" : "武学修养(martial-cognize)乃武术大义,可谓是以一通通百通!", ])); set_skill("unarmed", 500); set_skill("sword", 500); set_skill("blade", 500); set_skill("staff", 500); set_skill("hammer", 500); set_skill("club", 500); set_skill("whip", 500); set_skill("dagger", 500); set_skill("throwing", 500); set_skill("parry", 500); set_skill("dodge", 500); set_skill("force", 500); set_skill("never-defeated", 500); set_skill("martial-cognize", 500); map_skill("sword", "never-defeated"); map_skill("blade", "never-defeated"); map_skill("staff", "never-defeated"); map_skill("hammer", "never-defeated"); map_skill("club", "never-defeated"); map_skill("whip", "never-defeated"); map_skill("dagger", "never-defeated"); map_skill("parry", "never-defeated"); map_skill("dodge", "never-defeated"); map_skill("force", "never-defeated"); set("opinion/ultra", 1); set("opinion/master", 1); set("chat_chance_combat", 120); set("chat_msg_combat", ({ (: check_weapon :), }) ); set("rank_info/self", "在下"); setup(); carry_object("/clone/cloth/cloth")->wear(); carry_object("/clone/weapon/zhujian")->wield(); set("startroom", "/d/huashan/shandong"); check_clone(); } void init() { object me; if (! interactive(me = this_player())) return; me->delete_temp("want_opinion"); if (ultrap(me)) { message_vision(CYN "$N" CYN "微微一笑,对$n" CYN "点了点头。\n" NOR, this_object(), me); } } void check_weapon() { if (objectp(query_temp("weapon"))) return; message_vision(CYN "$N" CYN "长叹一口气道:我$N" CYN "多年来兵器还从未离过手,罢!罢" "了!我去也!\n" NOR, this_object()); destruct(this_object()); } mixed ask_opinion() { object me; object ob; me = this_player(); if (me->query("combat_exp") < 200000) return "呵呵,你这点武功还谈什么评价?"; if (me->query("opinion/" MY_OPINION) == ULTRA_OPINION) return "哈哈,你兵器方面的修为已经称得上是宗师了!咱们要不要过过招?"; if (is_fighting(me)) return "哈哈,废什么话,打赢了我,你自己给自己评价吧!"; if (me->is_fighting()) return "你等会儿吧!待我赶走他们。"; if (objectp(ob = query_temp("opinion"))) { if (ob == me) { command("say 你着什么急?不要烦我。"); return 1; } message_vision(CYN "$N" CYN "正在沉思,没有回答$n" CYN ",只是摆了摆手。\n" NOR, this_object(), me); return 1; } switch(me->query_temp("want_opinion/dugu")) { case 0: command("look " + me->query("id")); command("say 好吧,你用兵器攻我一招,我看看你的水平如何。"); break; case 1: command("say 不是说让你来一招我看看吗?"); break; case 2: message_vision(CYN "$N" CYN "皱眉对$n" CYN "道:“我看你这人是够罗嗦的。”\n" NOR, this_object(), me); break; case 3: command("say 给我闭上你的嘴!"); return 1; } me->add_temp("want_opinion/dugu", 1); return 1; } int calc_level(object me, string skill) { int lvl; string sp; mapping action; lvl = me->query_skill(skill, 1) / 2; sp = me->query_skill_mapped(skill); if (! sp) return lvl; lvl += me->query_skill(sp, 1); action = SKILL_D(sp)->query_action(me, me->query_temp("weapon")); if (mapp(action)) lvl += (action["force"] + action["parry"] + action["dodge"] - 250) / 10; return lvl; } void do_congration(object me) { command("chat 这位" + RANK_D->query_respect(me) + "可要善自珍重,须知强中更有强中手。"); } int accept_hit(object me) { if (me->query_temp("want_hit/dugu") >= 2) { command("heng"); command("say 事不过三,你要找死那就去死吧!"); kill_ob(me); return 1; } command("shake"); command("say 这位" + RANK_D->query_respect(me) + "," "练武之人切忌贸然挑衅。"); me->add_temp("want_hit/dugu", 1); return 0; } int accept_fight(object me) { object weapon; if (me->query("opinion/" MY_OPINION) == ULTRA_OPINION) { message_vision(CYN "$N" CYN "大喜,对$n" CYN "道:“很好,近年我还没有和宗" "师高手过过招,来吧!”\n" NOR, this_object(), me); return 1; } if (! me->query_temp("want_opinion/dugu")) { command("say 平白无故动什么手?"); return 0; } if (! objectp(weapon = me->query_temp("weapon"))) { command("say 没兵器你动什么手?"); return 0; } if (me->query("qi") * 100 / me->query("max_qi") < 80|| me->query("jing") * 100 / me->query("max_jing") < 80) { command("say 你现在状态不佳,等休息好了再说吧!"); return 0; } command("nod"); COMBAT_D->do_attack(me, this_object(), weapon); COMBAT_D->do_attack(this_object(), me, query_temp("weapon")); if (me->query("qi") <= 0) { message_vision(CYN "\n$N" CYN "摇摇头对$n" CYN "道:“你现在的武功还差得远,连" "我一招都接不住!”\n" NOR, this_object(), me); return notify_fail("看来要好好的修炼功夫了。\n"); } call_out("check_opinion", 2, me); set_temp("opinion", me); me->delete_temp("want_opinion"); message_vision(CYN "\n$N" CYN "点点头道:“好了,你先等" "会儿,待我想想。”\n" NOR, this_object(), me); return notify_fail("看来不能心急,还得等一会儿。\n"); } int accept_kill(object me) { if (me->query("combat_exp") < 500000) { message_vision(CYN "$N" CYN "大怒道:“无名小辈捣" "什么乱?给我滚!”说罢一掌把$n" CYN "劈倒在地。\n" NOR, this_object(), me); me->unconcious(); return -1; } command("sigh"); command("say 很好!近年还真没有遇到什么敢和我较量的高手!"); return 1; } /* int recognize_apprentice(object me, string skill) { if (me->query("character") != "狡黠多变") { command("say 我看你的性格不够机智灵活,不适宜" "向我学习武功,还是算了吧!"); return -1; } if (skill == "martial-cognize") return 1; if (! ultrap(me)) { command("say 想学我的不败神功?你还不够资格," "等你成了大宗师再说吧!"); return -1; } if (me->query_skill(skill, 1) >= 180) { command("say 够了!我就教你到这里吧,武功还是" "要靠自己多研究才是!"); return -1; } if (skill != "never-defeated") return 1; if (me->query_temp("can_learn/dugu/never-defeated")) return 1; me->set_temp("can_learn/dugu/never-defeated", 1); command("nod"); command("say 我可以教你我多年领悟出来的不败神功,可是" "你能不能学,还要看你的机缘了!"); return 1; } */ void unconcious() { message("vision", "\n"HIR + name() + "脸色一变,吐了一口鲜" "血,身形一闪,消逝不见。\n\n" NOR, environment()); command("chat 罢!罢!罢!在下去也!"); destruct(this_object()); } void die() { message("vision", "\n"HIR + name() + "大叫一声,狂吐了一口鲜" "血,身形一闪,就此不见。\n\n" NOR, environment()); command("chat 在下去也!"); destruct(this_object()); } int accept_object(object me, object ob) { if (base_name(ob) != "/clone/lonely/book/dugubook") { command("say 你给我这种东西干什么?"); return 0; } if (me->query_skill("dugu-jiujian", 1) < 340) { command("shake"); command("say 可惜,可惜!你独孤九剑还不够熟练,还无法领悟独孤九剑的精妙之处!"); destruct(ob); return 1; } if (me->query("can_learn/dugu-jiujian/nothing")) { command("nod"); command("say 你已经领悟了独孤九剑之精髓,下去好好练习吧!"); destruct(ob); return 1; } if (me->query("int") < 39) { command("say 你先天悟性不足,不知道你是怎么学的独孤九剑!\n"); return 1; } if (me->query("con") < 36 && me->query("dex") < 36) { command("say 你先天身法和根骨都不足,无法体会独孤九剑的精髓!\n"); return 1; } // 开始传授独孤九剑之无招 command("nod"); command("say 不错,不错!既然如此,我就将独孤九剑之精髓传授于你。"); command("say 独孤九剑最精妙之处已经不是招式,而是一种" HIY "境界" NOR + CYN "!"); command("say 独孤九剑讲究后发制人,不拘泥于任何招式,随心而发,随心而收,达到一\n" "种" HIY "无招胜有招" NOR + CYN "的境界!"); command("say 明白了?"); me->set("can_learn/dugu-jiujian/nothing", 1); if (me->can_improve_skill("sword")) me->improve_skill("sword", 1500000); if (me->can_improve_skill("sword")) me->improve_skill("sword", 1500000); if (me->can_improve_skill("sword")) me->improve_skill("sword", 1500000); if (me->can_improve_skill("dugu-jiujian")) me->improve_skill("dugu-jiujian", 1500000); if (me->can_improve_skill("dugu-jiujian")) me->improve_skill("dugu-jiujian", 1500000); if (me->can_improve_skill("dugu-jiujian")) me->improve_skill("dugu-jiujian", 1500000); me->improve_skill("martial-cognize", 1500000); me->improve_skill("martial-cognize", 1500000); me->improve_skill("martial-cognize", 1500000); tell_object(me, HIG "你学会了独孤九剑之「无招」。\n" NOR); destruct(ob); return 1; }
28.704225
88
0.461891
[ "object" ]
b5cbd59cd7fa82ceab3f94a25873afb23b661b09
29,733
c
C
src/emit.c
reki2000/rekicc
106c08d407f832cf75655f4cfed8f54bb3bdc85e
[ "MIT" ]
1
2022-02-11T15:37:51.000Z
2022-02-11T15:37:51.000Z
src/emit.c
reki2000/rekicc
106c08d407f832cf75655f4cfed8f54bb3bdc85e
[ "MIT" ]
null
null
null
src/emit.c
reki2000/rekicc
106c08d407f832cf75655f4cfed8f54bb3bdc85e
[ "MIT" ]
null
null
null
#include "types.h" #include "rsys.h" #include "rstring.h" #include "devtool.h" #include "vec.h" #include "token.h" #include "type.h" #include "var.h" #include "func.h" #include "atom.h" #include "gstr.h" #include "parse.h" int output_fd = 1; void _write(char *s) { write(output_fd, s, strlen(s)); } void genf(char *fmt, ...) { va_list va; va_start(va, fmt); char buf[RCC_BUF_SIZE]; vsnprintf(buf, RCC_BUF_SIZE, fmt, va); va_end(va); _write(buf); _write("\n"); } void gen_label(char *str) { genf("%s:", str); } void gen(char *str) { genf("\t%s", str); } int label_index = 0; int new_label() { return label_index++; } typedef enum reg { R_DI, R_SI, R_DX, R_CX, R_8, R_9, R_AX, R_BX, R_10, R_11, R_12, R_13, R_14, R_15, R_LAST } reg_e; char *regs8[] = { "%rdi", "%rsi", "%rdx", "%rcx", "%r8" , "%r9" , "%rax", "%rbx", "%r10" , "%r11" , "%r12" , "%r13" , "%r14" , "%r15" }; char *regs4[] = { "%edi", "%esi", "%edx", "%ecx", "%r8d", "%r9d", "%eax", "%ebx", "%r10d", "%r11d", "%r12d", "%r13d", "%r14d", "%r15d" }; char *regs1[] = { "%dil", "%sil", "%dl" , "%cl" , "%r8b", "%r9b", "%al" , "%bl", "%r10b", "%r11b", "%r12b", "%r13b", "%r14b", "%r15b" }; char *reg(int no, int size) { if (no >= R_LAST) { error("invalid reg no:%d", no); } switch (size) { case 8: return regs8[no]; case 4: return regs4[no]; case 1: return regs1[no]; default: error("invalid size for reg:%d", size); return (void *)0; } } char *opsize(int size) { return (size == 8) ? "q" : (size == 4) ? "l" : (size == 1) ? "b" : "?"; } int stack_offset = 0; /* * reg_in_use stores a status for the register. * 0: not in use (freely assignable) * 1: used * 2+: used and had 1+ pushed on the stack */ int reg_in_use[R_LAST]; void dump_reg_is_use() { char b1[100] = {0}; char b0[100] = {0}; for(reg_e i=0; i<R_LAST; i++) { snprintf(b1, 100, "%d[%d] ", i, reg_in_use[i]); strcat(b0, b1); } debug("before pop_all: %s", b0); } bool reg_is_callee_saved(reg_e i) { return (i==R_BX || i==R_12 || i==R_13 || i==R_14 || i==R_15); } void init_reg_in_use() { for (reg_e i=0; i<R_LAST; i++) { reg_in_use[i] = reg_is_callee_saved(i) ? 1 : 0; } } void emit_push(reg_e r) { genf(" pushq %s", reg(r,8)); stack_offset -= 8; } void emit_pop(reg_e r) { genf(" popq %s", reg(r,8)); stack_offset += 8; } void reg_push_all() { for (reg_e i=0; i<R_LAST; i++) { if (i == R_AX) continue; if (reg_is_callee_saved(i)) continue; if (reg_in_use[i]) { emit_push(i); } } } void reg_pop_all() { for (reg_e i=0; i<R_LAST; i++) { if (i == R_AX) continue; reg_e r = R_LAST-i-1; if (reg_is_callee_saved(r)) continue; if (reg_in_use[r]) { emit_pop(r); } } } /* * assign a register which is the least pushed on the stack, except it's the specified one. */ reg_e reg_assign_keep(reg_e keep) { reg_e reg_min = R_LAST; int val_min = INT32_MAX; for (reg_e i=0; i<R_LAST; i++) { if (i == R_AX || i == keep) continue; if (val_min > reg_in_use[i]) { reg_min = i; val_min = reg_in_use[i]; } } if (reg_in_use[reg_min] > 0) { emit_push(reg_min); } reg_in_use[reg_min]++; return reg_min; } reg_e reg_assign() { return reg_assign_keep(R_LAST); } void reg_release(reg_e r) { if (!reg_in_use[r]) { error("invalid release for reg %d", r); } if (reg_in_use[r] > 1) { emit_pop(r); } reg_in_use[r]--; } reg_e reg_reserve(reg_e org, reg_e keep) { emit_push(keep); if (org == keep) { reg_e tmp = reg_assign_keep(keep); genf(" movq %s, %s", reg(org,8), reg(tmp,8)); return tmp; } return org; } void reg_restore(reg_e tmp, reg_e org, reg_e keep) { if (tmp != org) { reg_release(tmp); } emit_pop(keep); } void emit_int(long val, int size, reg_e out) { genf(" mov%s $%ld, %s", opsize(size), val, reg(out, size)); } void emit_string(char* str) { char buf[RCC_BUF_SIZE] = {0}; strcat(buf, ".string \""); escape_string(buf + strlen(buf), str); strcat(buf, "\""); gen(buf); } void emit_global_ref(int i, reg_e out) { genf(" leaq .G%d(%%rip), %s", i, reg(out, 8)); } void emit_var_val(int i, int size, reg_e out) { if (size == 1) { genf(" movzbl %d(%%rbp), %s", -i, reg(out, 4)); } else { genf(" mov%s %d(%%rbp), %s", opsize(size), -i, reg(out, size)); } } void emit_global_var_val(char *name, int size, reg_e out) { if (size == 1) { genf(" movzbl %s(%%rip), %s", name, reg(out, 4)); } else { genf(" mov%s %s($%rip), %s", opsize(size), name, reg(out, size)); } } void emit_var_arg_init(reg_e no, int offset, int size) { if (size == 1) { genf(" movzbl %s, %s", reg(no,1), reg(no,4)); size = 4; } genf(" mov%s %s, %d(%%rbp)", opsize(size), reg(no, size), -offset); } void emit_deref(int size, reg_e inout) { if (size == 1) { genf(" movzbl (%s), %s", reg(inout,8), reg(inout,4)); } else { genf(" mov%s (%s), %s", opsize(size), reg(inout,8), reg(inout,size)); } } void emit_var_ref(int i, reg_e ret) { genf(" leaq %d(%%rbp), %s", -i, reg(ret,8)); } void emit_global_var_ref(char *name, reg_e out) { genf(" leaq %s(%%rip), %s", name, reg(out, 8)); } void emit_postfix_add(int size, int ptr_size, reg_e inout) { reg_e tmp = R_AX; genf(" mov%s (%s), %s", opsize(size), reg(inout, 8), reg(tmp, size)); genf(" add%s $%d, (%s)", opsize(size), ptr_size, reg(inout,8)); genf(" mov%s %s, %s", opsize(size), reg(tmp,size), reg(inout, size)); } void emit_copy(int size, reg_e in, reg_e out) { reg_e tmp = R_AX; int offset = 0; while (size>=8) { genf(" movq %d(%s), %s", offset, reg(in,8), reg(tmp,8)); genf(" movq %s, %d(%s)", reg(tmp,8), offset, reg(out,8)); size -= 8; offset += 8; } while (size>=4) { genf(" movl %d(%s), %s", offset, reg(in,8), reg(tmp,4)); genf(" movl %s, %d(%s)", reg(tmp,4), offset, reg(out,8)); offset += 4; size -= 4; } while (size>0) { genf(" movb %d(%s), %s", offset, reg(in,8), reg(tmp,1)); genf(" movb %s, %d(%s)", reg(tmp,1), offset, reg(out,8)); size--; offset++; } } void emit_store(int size, reg_e in, reg_e out) { genf(" mov%s %s, (%s)", opsize(size), reg(in,size), reg(out, 8)); } void emit_zcast(int size, reg_e inout) { if (size == 8) { return; } genf(" movz%sq %s, %s", opsize(size), reg(inout,size), reg(inout,8)); } void emit_scast(int size, reg_e inout) { if (size == 8) { return; } genf(" movs%sq %s, %s", opsize(size), reg(inout,size), reg(inout,8)); } void emit_array_index(int item_size, reg_e in, reg_e out) { // out = out + in * item_size reg_e in2 = reg_reserve(in, R_DX); genf(" movl $%d,%%eax", item_size); genf(" imulq %s", reg(in2,8)); genf(" addq %%rax, %s", reg(out,8)); reg_restore(in2, in, R_DX); } void emit_binop(char *binop, int size, reg_e in, reg_e out) { genf(" %s%s %s,%s", binop, opsize(size), reg(in,size), reg(out,size)); } void emit_bit_shift(char* op, int size, reg_e in, reg_e out) { genf(" movq %%rcx, %%rax"); genf(" movb %s,%%cl", reg(in,1)); genf(" sa%s%s %%cl, %s", op, opsize(size), reg(out,size)); genf(" movq %%rax, %%rcx"); } void emit_mul(int size, reg_e in, reg_e inout) { reg_e in2 = reg_reserve(in, R_DX); genf(" mov%s %s,%s", opsize(size), reg(inout,size), reg(R_AX,size)); genf(" imul%s %s", opsize(size), reg(in2,size)); genf(" mov%s %s,%s", opsize(size), reg(R_AX,size), reg(inout,size)); reg_restore(in2, in, R_DX); } void emit_divmod(int size, reg_e in, reg_e out, reg_e ret_reg) { // out = out [ / | % ] in reg_e in2 = reg_reserve(in, R_DX); genf(" mov%s %s,%s", opsize(size), reg(out,size), reg(R_AX,size)); genf(" %s", (size == 8) ? "cqo" : (size == 4) ? "cdq" : "???"); genf(" idiv%s %s", opsize(size), reg(in2,size)); genf(" mov%s %s,%s", opsize(size), reg(ret_reg,size), reg(out,size)); reg_restore(in2, in, R_DX); } void emit_div(int size, reg_e in, reg_e out) { emit_divmod(size, in, out, R_AX); } void emit_mod(int size, reg_e in, reg_e out) { emit_divmod(size, in, out, R_DX); } void emit_eq_x(char *set, int size, reg_e in, reg_e out) { genf(" cmp%s %s, %s", opsize(size), reg(in,size), reg(out,size)); genf(" set%s %s", set, reg(out,1)); genf(" andq $1,%s", reg(out, 8)); } void emit_log_not(int size, reg_e out) { genf(" or%s %s, %s", opsize(size), reg(out,size), reg(out,size)); genf(" setz %s", reg(out,1)); genf(" andq $1,%s", reg(out, 8)); } void emit_neg(int size, reg_e out) { genf(" not%s %s", opsize(size), reg(out,size)); } void emit_label(int i) { genf(".L%d:", i); } void emit_global_label(int i) { genf(".G%d:", i); } void emit_jmp(int i) { genf(" jmp .L%d", i); } void emit_jmp_false(int i, reg_e in) { genf(" orl %s, %s", reg(in,4), reg(in,4)); genf(" jz .L%d", i); } void emit_jmp_true(int i, reg_e in) { genf(" orl %s, %s", reg(in,4), reg(in,4)); genf(" jnz .L%d", i); } void emit_jmp_eq(int i, int size, reg_e in1, reg_e in2) { genf(" cmp%s %s,%s", opsize(size), reg(in1,size), reg(in2,size)); genf(" jz .L%d", i); } void emit_jmp_ne(int i, int size, reg_e in1, reg_e in2) { genf(" cmp%s %s,%s", opsize(size), reg(in1,size), reg(in2,size)); genf(" jnz .L%d", i); } int emit_push_struct(int size, reg_e from) { reg_e to = reg_assign(); int offset = align(size, 8); stack_offset += offset; genf(" subq $%d, %%rsp", offset); genf(" movq %%rsp, %s", reg(to, 8)); emit_copy(size, from, to); reg_release(to); return offset / 8; } int func_return_label; int func_void_return_label; typedef struct { int break_label; int continue_label; } break_label_t; VEC_HEADER(break_label_t, break_label_vec) VEC_BODY(break_label_t, break_label_vec) break_label_vec break_labels = 0; int get_break_label() { if (!break_label_vec_len(break_labels)) { error("cannot emit break"); } return break_label_vec_top(break_labels)->break_label; } int get_continue_label() { if (!break_label_vec_len(break_labels)) { error("cannot emit break"); } return break_label_vec_top(break_labels)->continue_label; } void enter_break_label(int break_label, int continue_label) { if (!break_labels) break_labels = break_label_vec_new(); break_label_t b; b.break_label = break_label; b.continue_label = continue_label; break_label_vec_push(break_labels, b); } void exit_break_label() { if (!break_label_vec_len(break_labels)) { error("cannot exit break label"); } break_label_vec_pop(break_labels); } void compile(int pos, reg_e reg_out) { atom_t *p = &(program[pos]); char ast_text[RCC_BUF_SIZE] = {0}; dump_atom3(ast_text, p, 0, pos); debug("compiling out:R#%d atom_t: %s", reg_out, ast_text); set_token_pos(p->token_pos); //dump_token_by_id(p->token_pos); switch (p->type) { case TYPE_VAR_REF: emit_var_ref(p->int_value, reg_out); break; case TYPE_GLOBAL_VAR_REF: emit_global_var_ref(p->ptr_value, reg_out); break; case TYPE_BIND: { reg_e i1 = reg_assign(); compile(p->atom_pos, reg_out); // rvalue compile((p+1)->atom_pos, i1); // lvalue - should be an address if (p->t->struct_of) { emit_copy(type_size(p->t), reg_out, i1); } else { emit_store(type_size(p->t), reg_out, i1); } reg_release(i1); break; } case TYPE_PTR: case TYPE_PTR_DEREF: compile(p->atom_pos, reg_out); break; case TYPE_RVALUE: compile(p->atom_pos, reg_out); if (p->t->array_length >= 0 || p->t->struct_of) { // rvalue of array / struct will be a pointer for itself } else { emit_deref(type_size(p->t), reg_out); } break; case TYPE_CONVERT: { compile(p->atom_pos, reg_out); int org_size = type_size(program[p->atom_pos].t); int new_size = type_size(p->t); if (!p->t->ptr_to && org_size < new_size) { emit_scast(type_size(program[p->atom_pos].t), reg_out); } break; } case TYPE_CAST: compile(p->atom_pos, reg_out); emit_scast(type_size(p->t), reg_out); break; case TYPE_INTEGER: if (type_size(p->t) == 8) { emit_int(p->long_value, 8, reg_out); } else { emit_int((long)(p->int_value), type_size(p->t), reg_out); } break; case TYPE_ADD: case TYPE_SUB: case TYPE_DIV: case TYPE_MOD: case TYPE_MUL: case TYPE_EQ_EQ: case TYPE_EQ_NE: case TYPE_EQ_LT: case TYPE_EQ_LE: case TYPE_EQ_GT: case TYPE_EQ_GE: case TYPE_OR: case TYPE_AND: case TYPE_XOR: case TYPE_LSHIFT: case TYPE_RSHIFT: case TYPE_MEMBER_OFFSET: case TYPE_ARRAY_INDEX: compile(p->atom_pos, reg_out); reg_e i1 = reg_assign(); compile((p+1)->atom_pos, i1); switch (p->type) { case TYPE_MEMBER_OFFSET: case TYPE_ADD: emit_binop("add", type_size(p->t), i1, reg_out); break; case TYPE_SUB: emit_binop("sub", type_size(p->t), i1, reg_out); break; case TYPE_DIV: emit_div(type_size(p->t), i1, reg_out); break; case TYPE_MOD: emit_mod(type_size(p->t), i1, reg_out); break; case TYPE_MUL: emit_mul(type_size(p->t), i1, reg_out); break; case TYPE_EQ_EQ: emit_eq_x("e", type_size(p->t), i1, reg_out); break; case TYPE_EQ_NE: emit_eq_x("ne", type_size(p->t), i1, reg_out); break; case TYPE_EQ_LE: emit_eq_x("le", type_size(p->t), i1, reg_out); break; case TYPE_EQ_LT: emit_eq_x("nge", type_size(p->t), i1, reg_out); break; case TYPE_EQ_GE: emit_eq_x("ge", type_size(p->t), i1, reg_out); break; case TYPE_EQ_GT: emit_eq_x("nle", type_size(p->t), i1, reg_out); break; case TYPE_OR: emit_binop("or", type_size(p->t), i1, reg_out); break; case TYPE_AND: emit_binop("and", type_size(p->t), i1, reg_out); break; case TYPE_XOR: emit_binop("xor", type_size(p->t), i1, reg_out); break; case TYPE_LSHIFT: emit_bit_shift("l", type_size(p->t), i1, reg_out); break; case TYPE_RSHIFT: emit_bit_shift("r", type_size(p->t), i1, reg_out); break; case TYPE_ARRAY_INDEX: emit_array_index((p+2)->int_value, i1, reg_out); break; } reg_release(i1); break; case TYPE_POSTFIX_DEC: { compile(p->atom_pos, reg_out); type_t *target_t = p->t; emit_postfix_add(type_size(target_t), (target_t->ptr_to) ? -type_size(target_t->ptr_to) : -1, reg_out); break; } case TYPE_POSTFIX_INC: { compile(p->atom_pos, reg_out); type_t *target_t = p->t; emit_postfix_add(type_size(target_t), (target_t->ptr_to) ? type_size(target_t->ptr_to) : 1, reg_out); break; } case TYPE_NOP: break; case TYPE_EXPR_STATEMENT: compile(p->atom_pos, reg_out); break; case TYPE_ANDTHEN: compile(p->atom_pos, reg_out); compile((p+1)->atom_pos, reg_out); break; case TYPE_LOG_AND: { int l_end = new_label(); compile(p->atom_pos, reg_out); emit_jmp_false(l_end, reg_out); // short circuit of '&&' compile((p+1)->atom_pos, reg_out); emit_label(l_end); } break; case TYPE_LOG_OR: { int l_end = new_label(); compile(p->atom_pos, reg_out); emit_jmp_true(l_end, reg_out); // short circuit of '||' compile((p+1)->atom_pos, reg_out); emit_label(l_end); } break; case TYPE_LOG_NOT: compile(p->atom_pos, reg_out); emit_log_not(type_size(p->t), reg_out); break; case TYPE_NEG: compile(p->atom_pos, reg_out); emit_neg(type_size(p->t), reg_out); break; case TYPE_TERNARY: { int l_end = new_label(); int l_else = new_label(); compile(p->atom_pos, reg_out); emit_jmp_false(l_else, reg_out); compile((p+1)->atom_pos, reg_out); emit_jmp(l_end); emit_label(l_else); compile((p+2)->atom_pos, reg_out); emit_label(l_end); } break; case TYPE_IF: { bool has_else = ((p+2)->atom_pos != 0); int l_end = new_label(); int l_else = new_label(); compile(p->atom_pos, reg_out); emit_jmp_false(has_else ? l_else : l_end, reg_out); compile((p+1)->atom_pos, reg_out); if (has_else) { emit_jmp(l_end); emit_label(l_else); compile((p+2)->atom_pos, reg_out); } emit_label(l_end); } break; case TYPE_FOR: { int l_body = new_label(); int l_loop = new_label(); int l_end = new_label(); enter_break_label(l_end, l_loop); compile((p+2)->atom_pos, reg_out); emit_label(l_body); compile((p+1)->atom_pos, reg_out); emit_jmp_false(l_end, reg_out); compile(p->atom_pos, reg_out); emit_label(l_loop); compile((p+3)->atom_pos, reg_out); emit_jmp(l_body); emit_label(l_end); exit_break_label(); } break; case TYPE_WHILE: { int l_body = new_label(); int l_end = new_label(); enter_break_label(l_end, l_body); emit_label(l_body); compile((p+1)->atom_pos, reg_out); emit_jmp_false(l_end, reg_out); compile(p->atom_pos, reg_out); emit_jmp(l_body); emit_label(l_end); exit_break_label(); } break; case TYPE_DO_WHILE: { int l_body = new_label(); int l_end = new_label(); enter_break_label(l_end, l_body); emit_label(l_body); compile(p->atom_pos, reg_out); compile((p+1)->atom_pos, reg_out); emit_jmp_true(l_body, reg_out); emit_label(l_end); exit_break_label(); } break; case TYPE_RETURN: if (p->t != type_void) { compile(p->atom_pos, reg_out); genf(" movq %s, %%rax", reg(reg_out, 8)); emit_jmp(func_return_label); } else { emit_jmp(func_void_return_label); } break; case TYPE_BREAK: emit_jmp(get_break_label()); break; case TYPE_CONTINUE: emit_jmp(get_continue_label()); break; case TYPE_APPLY: { dump_atom_tree(pos,0); func *f = (func *)(p->ptr_value); int argc = (p+1)->int_value; int num_reg_args = 0; bool use_reg[100]; // NUM_ARGC int struct_size[100]; int stack_size = 0; for (int i=0; i<argc; i++) { type_t *t = program[(p+i+2)->atom_pos].t; if (t->struct_of) { int size = type_size(t); struct_size[i] = size; use_reg[i] = ((size <= 8 && num_reg_args < ABI_NUM_GP) || (size <= 16 && num_reg_args < ABI_NUM_GP - 1)); if (use_reg[i]) { num_reg_args += (size <= 8) ? 1 : 2; } else { stack_size += align(size, 8); } } else { struct_size[i] = 0; use_reg[i] = (num_reg_args < ABI_NUM_GP); if (use_reg[i]) { num_reg_args++; } else { stack_size += 8; } } } // push for stack-passing reg_push_all(); if ((stack_size + stack_offset) % 16 != 0) { genf(" subq $8, %%rsp"); stack_size += 8; } for (int i=argc-1; i>=0; i--) { if (use_reg[i]) continue; debug("compiling stack passing values %d, to R#%d", i, reg_out); compile((p+i+2)->atom_pos, reg_out); emit_push(reg_out); if (struct_size[i] > 0) { emit_push_struct(struct_size[i], reg_out); } } // push for register-passing for (int i=argc-1; i>=0; i--) { if (!use_reg[i]) continue; debug("compiling register #%d passing value, to R#%d", i, reg_out); compile((p+i+2)->atom_pos, reg_out); // todo: direct assign to registers if (struct_size[i] > 0) { emit_push_struct(struct_size[i], reg_out); } else { emit_push(reg_out); } } for (int i=0; i<num_reg_args; i++) { emit_pop(i); } genf(" movb $0, %%al"); genf(" call %s%s", f->name, f->is_external ? "@PLT" : ""); if (stack_size > 0) { genf(" addq $%d, %%rsp", stack_size); } reg_pop_all(); int size = type_size(f->ret_type); if (size > 0) { genf(" mov%s %s, %s", opsize(size), reg(R_AX, size), reg(reg_out, size)); } } break; case TYPE_STRING: emit_global_ref(p->int_value, reg_out); break; case TYPE_SWITCH: { int l_end = new_label(); enter_break_label(l_end, 0); compile(p->atom_pos, reg_out); int size = type_size(p->t); p++; int l_fallthrough = new_label(); while (p->type == TYPE_ARG) { int l_next_case = new_label(); atom_t *case_atom = &program[p->atom_pos]; int pos; if (case_atom->type == TYPE_CASE) { reg_e tmp = reg_assign(); compile((case_atom )->atom_pos, tmp); genf(" movq %s, %%rax", reg(tmp,8)); reg_release(tmp); emit_jmp_ne(l_next_case, size, reg_out, R_AX); pos = (case_atom+1)->atom_pos; } else if (case_atom->type == TYPE_DEFAULT) { pos = case_atom->atom_pos; } else { dump_atom_tree(p->atom_pos, 0); error("invalid child under switch node"); } emit_label(l_fallthrough); compile(pos, reg_out); l_fallthrough = new_label(); // points the body of the next case emit_jmp(l_fallthrough); emit_label(l_next_case); p++; } emit_label(l_fallthrough); exit_break_label(); emit_label(l_end); } break; default: dump_atom(pos, 0); error("Invalid program"); } if (p->type == TYPE_EXPR_STATEMENT || p->type == TYPE_APPLY || p->type == TYPE_RETURN || p->type == TYPE_IF || p->type == TYPE_FOR || p->type == TYPE_WHILE || p->type == TYPE_DO_WHILE) { genf("# %s", ast_text); } debug("compiled out:R#%d atom_t: %s", reg_out, ast_text); } void emit_function(func *f) { if (!f->body_pos) { return; } set_token_pos(program[f->body_pos].token_pos); func_return_label = new_label(); func_void_return_label = new_label(); genf(".globl %s", f->name); genf(".type %s, @function", f->name); gen_label(f->name); genf(" pushq %%rbp"); genf(" movq %%rsp, %%rbp"); genf(" subq $%d, %%rsp", align(f->max_offset, 16)); stack_offset = 0; // at this point, %rsp must be 16-bytes aligned init_reg_in_use(); int arg_offset = 0; int reg_index = 0; for (int i=0; i<f->argc; i++) { var_t *v = var_vec_get(f->argv, i); debug("emitting function:%s arg:%s", f->name, v->name); if (v->t->struct_of) { int size = type_size(v->t); if (size > 16 || reg_index >= ABI_NUM_GP || (size > 8 && reg_index == ABI_NUM_GP - 1)) { debug("is on the stack. do nothing here", f->name, v->name); } else if (size <= 8) { debug("is passed by one register. do nothing here", f->name, v->name); emit_var_arg_init(reg_index++, v->offset, type_size(v->t)); arg_offset = align(v->offset, ALIGN_OF_STACK); } else { debug("is passed by two registers. ", f->name, v->name); emit_var_arg_init(reg_index++, v->offset, 8); emit_var_arg_init(reg_index++, v->offset - 8, size - 8); arg_offset = align(v->offset, ALIGN_OF_STACK); } continue; } else { switch (type_size(v->t)) { case 1: case 4: case 8: break; default: error("invalid size for funciton arg:%s", v->name); } } if (reg_index < ABI_NUM_GP) { emit_var_arg_init(reg_index, v->offset, type_size(v->t)); arg_offset = align(v->offset, ALIGN_OF_STACK); reg_index++; } } if (f->is_variadic) { for (int i=0; i<ABI_NUM_GP; i++) { emit_var_arg_init(ABI_NUM_GP-i-1, 8 + i*8 + arg_offset + 8*16, 8); } } reg_e ret = reg_assign(); compile(f->body_pos, ret); emit_label(func_void_return_label); genf(" xorq %%rax, %%rax"); // set default return value to $0 emit_label(func_return_label); genf(" leave"); genf(" ret"); genf(""); } int emit_global_constant_by_type(type_t *pt, int value) { int filled_size = 0; if (pt == type_char) { genf(".byte %d", value); filled_size += 1; } else if (pt == type_int) { genf(".long %d", value); filled_size += 4; } else if (pt == type_long) { genf(".quad %d", value); filled_size += 4; } else if (pt == type_char_ptr) { genf(".quad .G%d", value); filled_size += 8; } else if (pt->ptr_to) { genf(".quad %d", value); filled_size += 8; } return filled_size; } void emit_global_constant(var_t *v) { genf(".globl %s", v->name); genf(".data"); genf(".align 4"); genf(".type %s, @object", v->name); genf(".size %s, %d", v->name, type_size(v->t)); gen_label(v->name); if (v->t->array_length >= 0) { int filled_size = 0; int pos = v->int_value; int len = get_global_array_length(pos); type_t *pt = v->t->ptr_to; for (int index = 0; index < len; index++) { int value = get_global_array(pos, index); filled_size += emit_global_constant_by_type(pt, value); } if (type_size(v->t) > filled_size) { genf(".zero %d", type_size(v->t) - filled_size); } } else { int filled_size = emit_global_constant_by_type(v->t, v->int_value); if (!filled_size) { error("unknown size for global variable:%s %s", v->name, dump_type(v->t)); } } gen(""); } void emit_global_declaration(var_t *v) { genf(".comm %s, %d", v->name, type_size(v->t)); } void compile_file(int fd) { output_fd = fd; gen(".file \"main.c\""); gen(""); var_vec vars = get_global_frame()->vars; for (int i=0; i<var_vec_len(vars); i++) { var_t *v = var_vec_get(vars, i); if (v->is_constant) { continue; } if (v->has_value) { emit_global_constant(v); } else if (!v->is_external) { emit_global_declaration(v); } } gen(".text"); gen(".section .rodata"); int gstr_i=0; char *gstr; while ((gstr = find_global_string(gstr_i)) != 0) { emit_global_label(gstr_i); emit_string(gstr); gstr_i++; } gen(""); gen(".text"); gen(""); for (int i=0; i<func_vec_len(functions); i++) { func *f = func_vec_get(functions, i); if (f->body_pos != 0) { debug("%s --------------------- ", f->name); //dump_atom_tree(f->body_pos, 0); emit_function(f); } } }
29.822467
190
0.513167
[ "object" ]
b5ce1c88c68397dd91aa765cb3cf38f9216c60d8
3,423
h
C
Classes/KKCinemaView.h
tankista/KKCinemaView
936cef3e00f659659a85868b4f103d4c89fb9229
[ "MIT" ]
null
null
null
Classes/KKCinemaView.h
tankista/KKCinemaView
936cef3e00f659659a85868b4f103d4c89fb9229
[ "MIT" ]
1
2017-01-26T23:28:08.000Z
2017-01-26T23:28:08.000Z
Classes/KKCinemaView.h
tankista/KKCinemaView
936cef3e00f659659a85868b4f103d4c89fb9229
[ "MIT" ]
null
null
null
// // KKCinemaView.h // Cinemas // // Created by Peter Stajger on 12/03/14. // Copyright (c) 2014 KinemaKity. All rights reserved. // #import <UIKit/UIKit.h> @class KKCinemaView; typedef enum { KKSeatTypeNone, KKSeatTypeFree, KKSeatTypeWheelChair, // KKSeatTypeLoveSeats, TODO: to be implemented KKSeatTypeReserved, KKSeatTypeSelected } KKSeatType; typedef struct { NSUInteger row; NSUInteger col; } KKSeatLocation; extern const KKSeatLocation KKSeatLocationInvalid; bool KKSeatLocationIsInvalid(KKSeatLocation location); bool KKSeatLocationEqualsToLocation(KKSeatLocation location, KKSeatLocation otherLocation); NSString* NSStringFromKKSeatLocation(KKSeatLocation location); @protocol KKCinemaViewDataSource <NSObject> - (NSUInteger)numberOfRowsInCinemaView:(KKCinemaView*)cinemaView; - (NSUInteger)numberOfColsInCinemaView:(KKCinemaView*)cinemaView; - (KKSeatType)cinemaView:(KKCinemaView*)cinemaView seatTypeForLocation:(KKSeatLocation)location; @optional /** * Asks for height of a gap, between 2 rows. Specified *row* is row that is being offset. * Default value is 1; */ - (CGFloat)cinemaView:(KKCinemaView*)cinemaView interRowSpacingForRow:(NSUInteger)row; /** * Space between cols. Default value is 1; */ - (CGFloat)interColSpacingInCinemaView:(KKCinemaView*)cinemaView; @end @protocol KKCinemaViewDelegate <UIScrollViewDelegate> @optional /** * Determine whether a seat should be selected at given location. Default is YES. * * @return NO if seat can not be selected. If you return YES, as a consequence, * cinemaView:didSelectSeatAtLocation: will be called. */ - (BOOL)cinemaView:(KKCinemaView*)view shouldSelectSeatAtLocation:(KKSeatLocation)location; - (BOOL)cinemaView:(KKCinemaView*)view shouldDeselectSeatAtLocation:(KKSeatLocation)location; - (void)cinemaView:(KKCinemaView*)view didSelectSeatAtLocation:(KKSeatLocation)location; - (void)cinemaView:(KKCinemaView*)view didDeselectSeatAtLocation:(KKSeatLocation)location; @end @interface KKCinemaView : UIScrollView @property (nonatomic, weak) IBOutlet id<KKCinemaViewDataSource> dataSource; @property (nonatomic, weak) id<KKCinemaViewDelegate> delegate; /** * Restrict number of selected seats. Default value is 0 which means, there is no restriction. */ @property (nonatomic, assign) NSUInteger maximumSeatsToSelect; /** * Array of KKSeatLocation structures. These are wrapped in NSValue object. Call *seatLocationValue* * to obtain structure directly from NSValue. */ @property (nonatomic, readonly) NSArray* locationsOfSelectedSeats; /** * This will zoom in and out automatically after first and last seat selection. To zoom out * properly, you must set maximumSeatsToSelect. */ @property (nonatomic, assign) BOOL zoomAutomatically; /** * Offset every even seat row by specified offset ratio. Ratio is calculated relatively to seat width. * Use values between -1.0 to 1.0, where 0.5 means half of seat with. Default value is 0. */ @property (nonatomic, assign) CGFloat evenOddOffsetRatio; /** * Forces KKCinemaView to reload it's data using dataSource and redraw whole seat layout */ - (void)reloadData; - (void)zoomAtLocation:(KKSeatLocation)location animated:(BOOL)animated; - (void)unzoomAnimated:(BOOL)animated; @end @interface NSValue (KKSeatLocation) + (instancetype)valueWithKKSeatLocation:(KKSeatLocation)location; - (KKSeatLocation)seatLocationValue; @end
29.765217
102
0.779725
[ "object" ]
b5d9e12bd21c5a766d85fd48e703eeae529fdc92
2,677
c
C
src/hg/tutorial/cgiPicture/cgiPicture.c
andypohl/kent
af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1
[ "MIT" ]
171
2015-04-22T15:16:02.000Z
2022-03-18T20:21:53.000Z
src/hg/tutorial/cgiPicture/cgiPicture.c
andypohl/kent
af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1
[ "MIT" ]
60
2016-10-03T15:15:06.000Z
2022-03-30T15:21:52.000Z
src/hg/tutorial/cgiPicture/cgiPicture.c
andypohl/kent
af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1
[ "MIT" ]
80
2015-04-16T10:39:48.000Z
2022-03-29T16:36:30.000Z
/* cgiPicture - Simple CGI that makes an image.. */ #include "common.h" #include "linefile.h" #include "hash.h" #include "options.h" #include "jksql.h" #include "htmshell.h" #include "web.h" #include "cheapcgi.h" #include "cart.h" #include "portable.h" #include "hui.h" #include "vGfx.h" /* Global Variables */ struct cart *cart; /* CGI and other variables */ struct hash *oldVars = NULL; char *shapes[] = { "square", "line", "X", }; #define varPrefix "cgiPicture." #define shapeVar varPrefix "shape" #define redVar varPrefix "red" #define greenVar varPrefix "green" #define blueVar varPrefix "blue" void drawImage(struct vGfx *vg) /* Draw on our image. */ { int red = cartInt(cart, redVar); int green = cartInt(cart, greenVar); int blue = cartInt(cart, blueVar); char *shape = cartString(cart, shapeVar); Color col = vgFindColorIx(vg, red, green, blue); if (sameString(shape, "square")) { /* Draw a square half the dimensions of image in middle */ int h2 = vg->height/2; int w2 = vg->width/2; vgBox(vg, w2/2, h2/2, w2, h2, col); } else if (sameString(shape, "line")) { vgLine(vg, 0, 0, vg->width, vg->height, col); } else if (sameString(shape, "X")) { vgLine(vg, 0, 0, vg->width, vg->height, col); vgLine(vg, vg->width, 0, 0, vg->height, col); } else { errAbort("Unknown shape %s", shape); } #ifdef NEVER #endif /* NEVER */ } void doMiddle(struct cart *theCart) /* Set up globals and make web page */ { cart = theCart; cartWebStart(cart, database, "Simple CGI that makes an image."); printf("<FORM ACTION=\"../cgi-bin/cgiPicture\">"); cartSaveSession(cart); /* Put up some web controls. */ cgiMakeDropList(shapeVar, shapes, ArraySize(shapes), cartUsualString(cart, shapeVar, shapes[0])); cgiMakeSubmitButton(); printf("<BR>"); printf("Color. Red: "); cgiMakeIntVar(redVar, cartUsualInt(cart, redVar, 200), 3 ); printf(" Green: "); cgiMakeIntVar(greenVar, cartUsualInt(cart, greenVar, 200), 3 ); printf(" Blue: "); cgiMakeIntVar(blueVar, cartUsualInt(cart, blueVar, 200), 3 ); printf("<BR>"); /* Create and draw image to temp file and write out URL of temp file. */ struct tempName tn; makeTempName(&tn, "image", ".gif"); struct vGfx *vg = vgOpenGif(500, 500, tn.forCgi, FALSE); drawImage(vg); vgClose(&vg); printf("<IMG SRC=\"%s\">", tn.forCgi); printf("</FORM>"); cartWebEnd(); } /* Null terminated list of CGI Variables we don't want to save * permanently. */ char *excludeVars[] = {"Submit", "submit", NULL,}; int main(int argc, char *argv[]) /* Process command line. */ { cgiSpoof(&argc, argv); cartEmptyShell(doMiddle, hUserCookie(), excludeVars, oldVars); return 0; }
24.559633
72
0.65932
[ "shape" ]
b5df93e1c64d55b135f15056be5ab91782a96b58
4,299
h
C
Source/AudioAnalysisTools/Public/Analyzers/OnsetDetection.h
gtreshchev/AudioAnalysisTools
564f56d4ca2e35d5cc6c881b372fab284efb3567
[ "MIT" ]
13
2021-07-24T14:31:28.000Z
2022-02-28T13:30:26.000Z
Source/AudioAnalysisTools/Public/Analyzers/OnsetDetection.h
gtreshchev/AudioAnalysisTools
564f56d4ca2e35d5cc6c881b372fab284efb3567
[ "MIT" ]
2
2022-01-22T01:43:47.000Z
2022-03-13T10:59:41.000Z
Source/AudioAnalysisTools/Public/Analyzers/OnsetDetection.h
gtreshchev/AudioAnalysisTools
564f56d4ca2e35d5cc6c881b372fab284efb3567
[ "MIT" ]
2
2021-07-25T19:27:00.000Z
2022-01-31T18:34:22.000Z
// Georgy Treshchev 2022. #pragma once #include "AudioAnalysisToolsDefines.h" #include "OnsetDetection.generated.h" /** * Provides various functions to detect onset */ UCLASS(BlueprintType, Category = "Onset Detection") class AUDIOANALYSISTOOLS_API UOnsetDetection : public UObject { GENERATED_BODY() public: /** * Instantiates an Onset Detection object * * @param FrameSize The frame size of internal buffers * @return The OnsetDetection object */ UFUNCTION(BlueprintCallable, Category = "Onset Detection") static UOnsetDetection* CreateOnsetDetection(int32 FrameSize); /** * Update the frame size * * @param FrameSize The frame size of internal buffers */ UFUNCTION(BlueprintCallable, Category = "Onset Detection") void UpdateFrameSize(int32 FrameSize); /** * Calculate the energy difference between the current and previous energy sum * * @param AudioFrame An array containing audio frame in 32-bit float PCM format * @return The energy difference onset detection function sample for the frame */ UFUNCTION(BlueprintCallable, Category = "Onset Detection") float GetEnergyDifference(const TArray<float>& AudioFrame); /** * Calculate the spectral difference between the current and the previous magnitude spectrum * * @param MagnitudeSpectrum An array containing the magnitude spectrum * @return The spectral difference onset detection function sample */ UFUNCTION(BlueprintCallable, Category = "Onset Detection") float GetSpectralDifference(const TArray<float>& MagnitudeSpectrum); /** * Calculate the half wave rectified spectral difference between the current and the previous magnitude spectrum * * @param MagnitudeSpectrum An array containing the magnitude spectrum * @return The HWR spectral difference onset detection function sample */ UFUNCTION(BlueprintCallable, Category = "Onset Detection") float GetSpectralDifferenceHWR(const TArray<float>& MagnitudeSpectrum); /** * Calculate the complex spectral difference from the real and imaginary parts of the FFT * * @param FFTReal An array containing the real part of the FFT * @param FFTImaginary An array containing the imaginary part of the FFT * @return The complex spectral difference onset detection function sample */ UFUNCTION(BlueprintCallable, Category = "Onset Detection") float GetComplexSpectralDifference(const TArray<float>& FFTReal, const TArray<float>& FFTImaginary); /** * Calculate the high frequency content onset detection function from the magnitude spectrum * * @param MagnitudeSpectrum An array containing the magnitude spectrum * @return The high frequency content onset detection function sample */ UFUNCTION(BlueprintCallable, Category = "Onset Detection") static float GetHighFrequencyContent(const TArray<float>& MagnitudeSpectrum); private: /** * Set phase values between [-pi:pi] range * * @param PhaseValue the phase value to process * @return The wrapped phase value */ static FORCEINLINE float Princarg(float PhaseValue) { /** If phase value is less than or equal to -PI then add 2 * PI */ while (PhaseValue <= -PI) { PhaseValue += 2 * PI; } /** If phase value is larger than PI, then subtract 2 * PI */ while (PhaseValue > PI) { PhaseValue -= 2 * PI; } return PhaseValue; } /** holds the previous energy sum for the energy difference onset detection function */ float PrevEnergySum; /** An array containing the previous magnitude spectrum passed to the last spectral difference call */ TArray<float> PrevMagnitudeSpectrum_spectralDifference; /** An array containing the previous magnitude spectrum passed to the last spectral difference (half wave rectified) call */ TArray<float> PrevMagnitudeSpectrum_spectralDifferenceHWR; /** An array containing the previous phase spectrum passed to the last complex spectral difference call */ TArray<float> PrevPhaseSpectrum_complexSpectralDifference; /** An array containing the second previous phase spectrum passed to the last complex spectral difference call */ TArray<float> PrevPhaseSpectrum2_complexSpectralDifference; /** An array containing the previous magnitude spectrum passed to the last complex spectral difference call */ TArray<float> PrevMagnitudeSpectrum_complexSpectralDifference; };
34.95122
125
0.76762
[ "object" ]
b5eb9b098b962dba11536e24731d12b4157edde1
481
h
C
butterbur/src/imagesAndText/imgdistmap.h
N-eil/ecere-sdk
5a5fc1f84a8dfc4bf66e99461839849f5cc4a7b6
[ "BSD-3-Clause" ]
264
2015-01-08T22:19:27.000Z
2022-03-25T19:33:03.000Z
butterbur/src/imagesAndText/imgdistmap.h
N-eil/ecere-sdk
5a5fc1f84a8dfc4bf66e99461839849f5cc4a7b6
[ "BSD-3-Clause" ]
34
2015-11-07T07:48:18.000Z
2022-02-05T09:13:55.000Z
butterbur/src/imagesAndText/imgdistmap.h
N-eil/ecere-sdk
5a5fc1f84a8dfc4bf66e99461839849f5cc4a7b6
[ "BSD-3-Clause" ]
91
2015-01-08T22:19:28.000Z
2022-01-10T10:14:38.000Z
/* ----------------------------------------------------------------------------- * * Copyright (c) 2015 Alexis Naveros. * * Based on the "Dead Reckoning signed distance transform", by George J. Grevera * * Ecere Corporation has unlimited/unrestricted rights. * ----------------------------------------------------------------------------- */ void imgDistMapBuild( float *distancemap, unsigned char *src, int sizex, int sizey, int srcbytesperpixel, int srcbytesperline );
37
128
0.494802
[ "transform" ]
b5f7bd55d2fbe0ab52a0f5963a827476f8552daa
1,890
h
C
src/tsppd/data/tsppd_tree.h
ryanjoneil/tsppd
f0e1e5e867e13c8fa0dcddf4d2ffa2aae7f46da4
[ "AFL-1.1" ]
4
2018-03-30T20:58:57.000Z
2018-04-25T01:48:09.000Z
src/tsppd/data/tsppd_tree.h
ryanjoneil/tsppd
f0e1e5e867e13c8fa0dcddf4d2ffa2aae7f46da4
[ "AFL-1.1" ]
7
2019-04-21T13:42:09.000Z
2019-05-09T15:49:56.000Z
src/tsppd/data/tsppd_tree.h
ryanjoneil/tsppd-hybrid
f0e1e5e867e13c8fa0dcddf4d2ffa2aae7f46da4
[ "AFL-1.1" ]
1
2020-03-01T16:19:18.000Z
2020-03-01T16:19:18.000Z
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the tsppd program and library for solving */ /* Traveling Salesman Problems with Pickup and Delivery. tsppd requires */ /* other commercial and open source software to build. tsppd is decribed */ /* in the paper "Exact Methods for Solving Traveling Salesman Problems */ /* with Pickup and Delivery in Real Time". */ /* */ /* Copyright (C) 2017 Ryan J. O'Neil <roneil1@gmu.edu> */ /* */ /* tsppd is distributed under the terms of the ZIB Academic License. */ /* You should have received a copy of the ZIB Academic License along with */ /* tsppd. See the file LICENSE. If not, email roneil1@gmu.edu. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef TSPPD_DATA_TSPPD_TREE_H #define TSPPD_DATA_TSPPD_TREE_H #include <memory> #include <tsppd/data/tsppd_arc.h> #include <tsppd/data/tsppd_problem.h> namespace TSPPD { namespace Data { class TSPPDTree { public: TSPPDTree(); bool contains(const unsigned int node) const; size_t size() const; void insert(const TSPPDArc& arc); void merge(const std::shared_ptr<TSPPDTree> other); static TSPPDTree minimum_spanning_tree(const TSPPDProblem& problem); std::set<unsigned int> nodes; std::vector<TSPPDArc> arcs; unsigned int cost; }; } } #endif
40.212766
80
0.462963
[ "vector" ]
c9aae077ed378b85c8887f964dd196f11de0bd0b
6,053
h
C
Inc/ObjectCreationUtils.h
Remag/ReversedLibrary
c2e929586b1fccdf0f090bc68df2ec62389ceada
[ "MIT" ]
null
null
null
Inc/ObjectCreationUtils.h
Remag/ReversedLibrary
c2e929586b1fccdf0f090bc68df2ec62389ceada
[ "MIT" ]
null
null
null
Inc/ObjectCreationUtils.h
Remag/ReversedLibrary
c2e929586b1fccdf0f090bc68df2ec62389ceada
[ "MIT" ]
null
null
null
#pragma once #include <Redefs.h> #include <BaseString.h> #include <MemoryUtils.h> #include <SafeCounters.h> #include <StaticAllocators.h> #include <Tuple.h> #include <Action.h> #include <Invoke.h> #include <ExternalObject.h> namespace Relib { ////////////////////////////////////////////////////////////////////////// // Base creation function wrapper. Pointers to this class are stored in an external name base. // This class is casted to the real template wrapper before use. class CBaseObjectCreationFunction { public: explicit CBaseObjectCreationFunction( int _objectSize ) : objectSize( _objectSize ) {} // Class must be polymorphic for dynamic_cast to work. virtual ~CBaseObjectCreationFunction() {} // Get the size of created object in bytes. int GetObjectSize() const { return objectSize; } private: // Size of created object. int objectSize; }; ////////////////////////////////////////////////////////////////////////// // Actual function wrapper. Stores a function with template arguments as its parameters. template <class ArgTuple> class CObjectCreationFunction; template <class... Args> class CObjectCreationFunction<CTuple<Args...>> : public CBaseObjectCreationFunction { public: typedef IAction<IExternalObject*( void*, Args... )> TCreateAction; typedef CTuple<Args...> TCreationArgsTuple; CObjectCreationFunction( CPtrOwner<TCreateAction> createFunc, int objectSize ) : CBaseObjectCreationFunction( objectSize ), createAction( move( createFunc ) ) {} // Call the creation function. IExternalObject* CreateObject( void* targetMemory, Args... args ) const { return createAction->Invoke( targetMemory, forward<Args>( args )... ); } private: // Pointer to creation action. CPtrOwner<TCreateAction> createAction; }; ////////////////////////////////////////////////////////////////////////// namespace RelibInternal { ////////////////////////////////////////////////////////////////////////// // An association between a class and its creation function. // By default classes are associated with default constructor creation. template <class T, class Enable = void> struct CObjectCreationInfo { typedef CObjectCreationFunction<CTuple<>> TCreateFunction; }; // Classes that inherit from IConstructible, use the function with the annotated constructor arguments. template <class T> struct CObjectCreationInfo<T, typename Types::EnableIf<Types::IsDerivedFrom<T, IBaseConstructable>::Result>::Result> { typedef CObjectCreationFunction<typename T::TConstructorArgsTuple> TCreateFunction; }; ////////////////////////////////////////////////////////////////////////// // Action that creates an object using its constructor with the specified arguments. template <class ClassType, class ArgTuple> class CClassConstructionAction; template <class ClassType, class... Args> class CClassConstructionAction<ClassType, CTuple<Args...>> : public IAction<IExternalObject*( void*, Args... )> { public: // Action invocation creates a class object using its constructor with correctly converted arguments. virtual IExternalObject* Invoke( void* targetMemory, Args... args ) const override final { static_assert( Types::HasConstructor<ClassType, Args...>::Result, "External object must be constructible with the specified arguments." ); return ::new( targetMemory ) ClassType( forward<Args>( args )... ); } }; // Action that uses another arbitrary action to create an object. template <class ActionType, class ArgTuple> class CClassCreationAction; template <class ActionType, class... Args> class CClassCreationAction<ActionType, CTuple<Args...>> : public IAction<IExternalObject*( void*, Args... )> { public: CClassCreationAction( ActionType _action ) : action( move( _action ) ) {} // Action invocation creates a class object using its constructor with correctly converted arguments. virtual IExternalObject* Invoke( void* targetMemory, Args... args ) const override final { return doInvoke( targetMemory, forward<Args>( args )... ); } private: ActionType action; IExternalObject* doInvoke( void* targetMemory, Args... args ) const; }; ////////////////////////////////////////////////////////////////////////// template <class ActionType, class... Args> IExternalObject* CClassCreationAction<ActionType, CTuple<Args...>>::doInvoke( void* targetMemory, Args... args ) const { typedef Types::FunctionInfo<ActionType>::ReturnType TClassType; typedef Types::FunctionInfo<ActionType>::ArgsTuple TConstructorArgs; staticAssert( TConstructorArgs::Size() == sizeof...( Args ) ); return ::new( targetMemory ) TClassType( Relib::Invoke( action, forward<Args>( args )... ) ); } ////////////////////////////////////////////////////////////////////////// } // namespace RelibInternal. ////////////////////////////////////////////////////////////////////////// // Return a creation function for an object with the given name. // ObjectName must be a registered external class name. REAPI const CBaseObjectCreationFunction* GetObjectCreationFunction( CUnicodePart objectName ); // Register an external name and a creation function for an object of a given type. void REAPI RegisterObject( const type_info& objectInfo, CUnicodePart objectName, CPtrOwner<CBaseObjectCreationFunction, CProcessHeap> newFunction ); // Destroy the association between a given name and a previously registered creation function. void REAPI UnregisterObject( const type_info& objectInfo, CUnicodePart objectName ); // Get the registered external name for an external object. // Note that a single object can have several external names. // In this case, the latest registered name is returned. CUnicodeView REAPI GetExternalName( const IExternalObject& object ); // Check if the given name has a registered object associated with it. bool REAPI IsExternalName( CUnicodePart name ); ////////////////////////////////////////////////////////////////////////// } // namespace Relib.
41.176871
149
0.667107
[ "object" ]
c9b85374a7145528a827a5b5ee15e666419fe426
3,233
h
C
modules/ugdk-core/include/pyramidworks/geometry/convexpolygon.h
uspgamedev/ugdk
95885a70df282a8e8e6e5c72b28a7f2f21bf7e99
[ "Zlib" ]
11
2015-03-06T13:14:32.000Z
2020-06-09T23:34:28.000Z
modules/ugdk-core/include/pyramidworks/geometry/convexpolygon.h
uspgamedev/ugdk
95885a70df282a8e8e6e5c72b28a7f2f21bf7e99
[ "Zlib" ]
62
2015-01-04T05:47:40.000Z
2018-06-15T17:00:25.000Z
modules/ugdk-core/include/pyramidworks/geometry/convexpolygon.h
uspgamedev/ugdk
95885a70df282a8e8e6e5c72b28a7f2f21bf7e99
[ "Zlib" ]
2
2017-04-05T20:35:49.000Z
2017-07-30T03:44:02.000Z
#ifndef PYRAMIDWORKS_GEOMETRY_CONVEXPOLYGON_H_ #define PYRAMIDWORKS_GEOMETRY_CONVEXPOLYGON_H_ #include <pyramidworks/geometry/geometricshape.h> #include <vector> namespace pyramidworks { namespace geometry { /// A convex polygon, one type of GeometricShape. This determines a polygon conposed by at least 3 vertices. class ConvexPolygon : public GeometricShape { public: /** @param vertices The list of vertices of the polygon, in local coordinates (0,0 is the "center", where this polygon is positioned). vertices[i] and vertices[i+1] form a edge, and vertices[n]-vertices[0] is the closing edge. */ ConvexPolygon(const std::vector<ugdk::math::Vector2D>& vertices); void set_vertices(const std::vector<ugdk::math::Vector2D>& vertices) { vertices_ = vertices; this->CalculateSize(); } bool Intersects(const ugdk::math::Vector2D& this_pos, const GeometricShape *obj, const ugdk::math::Vector2D& that_pos) const; bool Intersects(const ugdk::math::Vector2D& this_pos, const Rect *obj, const ugdk::math::Vector2D& that_pos) const; bool Intersects(const ugdk::math::Vector2D& this_pos, const Circle *obj, const ugdk::math::Vector2D& that_pos) const; bool Intersects(const ugdk::math::Vector2D& this_pos, const ConvexPolygon *obj, const ugdk::math::Vector2D& that_pos) const; ugdk::structure::Box<2> GetBoundingBox(const ugdk::math::Vector2D& position) const; double bbox_width() { return bbox_half_width_*2; } double bbox_height() { return bbox_half_height_*2; } private: void CalculateSize(); /// Checks if there's an separating axis between the two given objects (convex polygons represented as a Vector2D list and a position). /// If a separating axis exist, the two polygons do not intersect. /** @param obj1 The list of vertices, in local coordinates, of the first convex polygon. Each pair of adjacent vectors (plus the last and initial vectors) in the list correspond to a pair of vertices that form a edge of the polygon. Vertices should be ordered clockwise. @param obj1pos The position of the first convex polygon. @param obj2 The list of vertices, in local coordinates, of the second convex polygon. Each pair of adjacent vectors (plus the last and initial vectors) in the list correspond to a pair of vertices that form a edge of the polygon. Vertices should be ordered clockwise. @param obj2pos The position of the second convex polygon. @return True if there's a separating axis. */ bool CheckAxisSeparation(const std::vector<ugdk::math::Vector2D>& obj1, const ugdk::math::Vector2D& obj1pos, const std::vector<ugdk::math::Vector2D>& obj2, const ugdk::math::Vector2D& obj2pos) const; bool AxisSeparationTest(const ugdk::math::Vector2D& p1, const ugdk::math::Vector2D& p2, const ugdk::math::Vector2D& ref, const std::vector<ugdk::math::Vector2D>& obj, const ugdk::math::Vector2D& obj2pos) const; bool InsideSameSpace(const ugdk::math::Vector2D& line, const ugdk::math::Vector2D& point) const; std::vector<ugdk::math::Vector2D> vertices_; double bbox_half_width_, bbox_half_height_; }; } // namespace geometry } // namespace pyramidworks #endif /* PYRAMIDWORKS_GEOMETRY_CONVEXPOLYGON_H_ */
57.732143
155
0.746366
[ "geometry", "vector" ]
c9b9ce3305a4a1cbc21e73259265979c2a5ff464
2,174
h
C
src/fvm/src/modules/fvmbase/AMG.h
drm42/fvm-drm
c9b940e593034f1aa3020d63ff1e09ebef9c182a
[ "MIT" ]
null
null
null
src/fvm/src/modules/fvmbase/AMG.h
drm42/fvm-drm
c9b940e593034f1aa3020d63ff1e09ebef9c182a
[ "MIT" ]
null
null
null
src/fvm/src/modules/fvmbase/AMG.h
drm42/fvm-drm
c9b940e593034f1aa3020d63ff1e09ebef9c182a
[ "MIT" ]
null
null
null
// This file os part of FVM // Copyright (c) 2012 FVM Authors // See LICENSE file for terms. #ifndef _AMG_H_ #define _AMG_H_ #include <vector> #include <cmath> #include "LinearSystem.h" #include "LinearSolver.h" #include "MultiFieldReduction.h" #include "LinearSystemMerger.h" #include <iostream> #include <fstream> class LinearSystemMerger; using namespace std; /** * Solve a linear system using algebraic multigrid. * */ class AMG : public LinearSolver { public: enum CycleType { V_CYCLE, W_CYCLE, F_CYCLE }; enum SmootherType { GAUSS_SEIDEL, JACOBI }; AMG(); virtual ~AMG(); DEFINE_TYPENAME("AMG"); virtual MFRPtr solve(LinearSystem & ls); virtual void smooth(LinearSystem & ls); virtual void setMergeLevelSize(int ls_size){ #ifdef FVM_PARALLEL //_mergeLevelSize = ceil( double(ls_size) / double(MPI::COMM_WORLD.Get_size()) ); _mergeLevelSize = ls_size; _isMerge = true; #endif #ifndef FVM_PARALLEL _mergeLevelSize = ls_size; cout << " you can not set mergeLevelSize in serial version !!!!!!!!!!! " << endl; abort(); #endif } void redirectPrintToFile( const string& fname ); void redirectPrintToScreen( ); int getTotalIterations() const { return _totalIterations;} virtual void cleanup(); // these parameters can be tuned. int maxCoarseLevels; int nPreSweeps; int nPostSweeps; int coarseGroupSize; double weightRatioThreshold; CycleType cycleType; SmootherType smootherType; bool scaleCorrections; private: AMG(const AMG&); LinearSystem* _finestLinearSystem; vector<shared_ptr<LinearSystem> > _coarseLinearSystems; shared_ptr<LinearSystemMerger> _mergeLS; void createCoarseLevels( ); void doSweeps( const int nSweeps, const int level ); void cycle( CycleType cycleType, const int level ); void flipComm(); static int amg_indx; int _mergeLevelSize; //where int _mergeLevel; bool _isMerge; int _totalIterations; #ifdef FVM_PARALLEL MPI::Intracomm _commTarget; #endif streambuf *m_psbuf; streambuf *m_backup; ofstream m_filestr; bool _isCOMMWORLD; }; #endif
19.238938
89
0.698712
[ "vector" ]
c9be71b479a3b1ae98adcea3c21b2c5819ada153
8,116
h
C
lib/SILOptimizer/SemanticARC/OwnershipLiveRange.h
gandhi56/swift
2d851ff61991bb8964079661339671c2fd21d88a
[ "Apache-2.0" ]
72,551
2015-12-03T16:45:13.000Z
2022-03-31T18:57:59.000Z
lib/SILOptimizer/SemanticARC/OwnershipLiveRange.h
gandhi56/swift
2d851ff61991bb8964079661339671c2fd21d88a
[ "Apache-2.0" ]
39,352
2015-12-03T16:55:06.000Z
2022-03-31T23:43:41.000Z
lib/SILOptimizer/SemanticARC/OwnershipLiveRange.h
gandhi56/swift
2d851ff61991bb8964079661339671c2fd21d88a
[ "Apache-2.0" ]
13,845
2015-12-03T16:45:13.000Z
2022-03-31T11:32:29.000Z
//===--- OwnershipLiveRange.h ---------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #ifndef SWIFT_SILOPTIMIZER_SEMANTICARC_OWNERSHIPLIVERANGE_H #define SWIFT_SILOPTIMIZER_SEMANTICARC_OWNERSHIPLIVERANGE_H #include "swift/SIL/OwnershipUtils.h" #include "swift/SILOptimizer/Utils/InstOptUtils.h" #include "swift/SILOptimizer/Utils/ValueLifetime.h" namespace swift { namespace semanticarc { /// This class represents an "extended live range" of an owned value. Such a /// representation includes: /// /// 1. The owned introducing value. /// 2. Any forwarding instructions that consume the introduced value /// (transitively) and then propagate a new owned value. /// 3. Transitive destroys on the forwarding instructions/destroys on the owned /// introducing value. /// 4. Any unknown consuming uses that are not understood by this code. /// /// This allows for this to be used to convert such a set of uses from using /// owned ownership to using guaranteed ownership by converting the /// destroy_value -> end_borrow and "flipping" the ownership of individual /// forwarding instructions. /// /// NOTE: We do not look through "phi nodes" in the ownership graph (e.x.: real /// phi arguments, struct, tuple). Instead we represent those as nodes in a /// larger phi ownership web, connected via individual OwnershipLiveRange. class LLVM_LIBRARY_VISIBILITY OwnershipLiveRange { /// The value that we are computing the LiveRange for. Expected to be an owned /// introducer and not to be forwarding. OwnedValueIntroducer introducer; /// A vector that we store all of our uses into. /// /// Some properties of this array are: /// /// 1. It is only mutated in the constructor of LiveRange. /// /// 2. destroyingUses, ownershipForwardingUses, and unknownConsumingUses are /// views into this array. We store the respective uses in the aforementioned /// order. This is why it is important not to mutate consumingUses after we /// construct the LiveRange since going from small -> large could invalidate /// the uses. SmallVector<Operand *, 6> consumingUses; /// A list of destroy_values of the live range. /// /// This is just a view into consuming uses. ArrayRef<Operand *> destroyingUses; /// A list of forwarding instructions that forward owned ownership, but that /// are also able to be converted to guaranteed ownership. /// /// If we are able to eliminate this LiveRange due to it being from a /// guaranteed value, we must flip the ownership of all of these instructions /// to guaranteed from owned. /// /// NOTE: Normally only destroying or consuming uses end the live range. We /// copy these transitive uses as well into the consumingUses array since /// transitive uses can extend a live range up to an unreachable block without /// ultimately being consuming. In such a situation if we did not also store /// this into consuming uses, we would not be able to ascertain just using the /// "consumingUses" array the true lifetime of the OwnershipLiveRange. /// /// Corresponds to isOwnershipForwardingInst(...). ArrayRef<Operand *> ownershipForwardingUses; /// Consuming uses that we were not able to understand as a forwarding /// instruction or a destroy_value. These must be passed a strongly control /// equivalent +1 value. ArrayRef<Operand *> unknownConsumingUses; public: OwnershipLiveRange(SILValue value); OwnershipLiveRange(const OwnershipLiveRange &) = delete; OwnershipLiveRange &operator=(const OwnershipLiveRange &) = delete; enum class HasConsumingUse_t { No = 0, YesButAllPhiArgs = 1, Yes = 2, }; /// Return true if v only has invalidating uses that are destroy_value. Such /// an owned value is said to represent a dead "live range". /// /// Semantically this implies that a value is never passed off as +1 to memory /// or another function implying it can be used everywhere at +0. HasConsumingUse_t hasUnknownConsumingUse(bool assumingFixedPoint = false) const; /// Return an array ref to /all/ consuming uses. Will include all 3 sorts of /// consuming uses: destroying uses, forwarding consuming uses, and unknown /// forwarding instruction. ArrayRef<Operand *> getAllConsumingUses() const { return consumingUses; } ArrayRef<Operand *> getDestroyingUses() const { return destroyingUses; } private: struct OperandToUser; public: using DestroyingInstsRange = TransformRange<ArrayRef<Operand *>, OperandToUser>; DestroyingInstsRange getDestroyingInsts() const; using ConsumingInstsRange = TransformRange<ArrayRef<Operand *>, OperandToUser>; ConsumingInstsRange getAllConsumingInsts() const; /// If this LiveRange has a single destroying use, return that use. Otherwise, /// return nullptr. Operand *getSingleDestroyingUse() const { if (destroyingUses.size() != 1) { return nullptr; } return destroyingUses.front(); } /// If this LiveRange has a single unknown destroying use, return that /// use. Otherwise, return nullptr. Operand *getSingleUnknownConsumingUse() const { if (unknownConsumingUses.size() != 1) { return nullptr; } return unknownConsumingUses.front(); } OwnedValueIntroducer getIntroducer() const { return introducer; } ArrayRef<Operand *> getOwnershipForwardingUses() const { return ownershipForwardingUses; } void convertOwnedGeneralForwardingUsesToGuaranteed() &&; /// A consuming operation that: /// /// 1. If \p insertEndBorrows is true inserts end borrows at all /// destroying insts locations. /// /// 2. Deletes all destroy_values. /// /// 3. RAUW value with newGuaranteedValue. /// /// 4. Convert all of the general forwarding instructions from /// @owned -> @guaranteed. "Like Dominoes". /// /// 5. Leaves all of the unknown consuming users alone. It is up to /// the caller to handle converting their ownership. void convertToGuaranteedAndRAUW(SILValue newGuaranteedValue, InstModCallbacks callbacks) &&; /// A consuming operation that in order: /// /// 1. Converts the phi argument to be guaranteed via setOwnership. /// /// 2. If this consumes a borrow, insert end_borrows at the relevant /// destroy_values. /// /// 3. Deletes all destroy_values. /// /// 4. Converts all of the general forwarding instructions from @owned -> /// @guaranteed. "Like Dominoes". /// /// NOTE: This leaves all of the unknown consuming users alone. It is up to /// the caller to handle converting their ownership. /// /// NOTE: This routine leaves inserting begin_borrows for the incoming values /// to the caller since those are not part of the LiveRange itself. void convertJoinedLiveRangePhiToGuaranteed( DeadEndBlocks &deadEndBlocks, ValueLifetimeAnalysis::Frontier &scratch, InstModCallbacks callbacks) &&; /// Given a new guaranteed value, insert end_borrow for the newGuaranteedValue /// at all of our destroy_values in prepration for converting from owned to /// guaranteed. /// /// This is used when converting load [copy] -> load_borrow. void insertEndBorrowsAtDestroys(SILValue newGuaranteedValue, DeadEndBlocks &deadEndBlocks, ValueLifetimeAnalysis::Frontier &scratch); }; struct OwnershipLiveRange::OperandToUser { OperandToUser() {} SILInstruction *operator()(const Operand *use) const { auto *nonConstUse = const_cast<Operand *>(use); return nonConstUse->getUser(); } }; } // namespace semanticarc } // namespace swift #endif // SWIFT_SILOPTIMIZER_SEMANTICARC_OWNERSHIPLIVERANGE_H
38.464455
80
0.710572
[ "vector" ]
c9dda9d3efa607d290d5c42713e07ac71815726c
4,130
h
C
desktop_version/src/Editor.h
CNate/VVVVVV
6e832cae20102079a065b212fdc9b0b4f03795d3
[ "RSA-MD" ]
6,811
2020-01-10T14:56:19.000Z
2022-03-31T20:11:04.000Z
desktop_version/src/Editor.h
CNate/VVVVVV
6e832cae20102079a065b212fdc9b0b4f03795d3
[ "RSA-MD" ]
423
2020-01-10T18:11:26.000Z
2022-03-24T23:22:14.000Z
desktop_version/src/Editor.h
CNate/VVVVVV
6e832cae20102079a065b212fdc9b0b4f03795d3
[ "RSA-MD" ]
639
2020-01-10T14:56:27.000Z
2022-03-31T06:04:40.000Z
#if !defined(NO_CUSTOM_LEVELS) && !defined(NO_EDITOR) #ifndef EDITOR_H #define EDITOR_H #include "CustomLevels.h" #include <SDL.h> #include <string> #include <vector> // Text entry field type enum textmode { TEXT_NONE, // In-editor text fields TEXT_LOAD, TEXT_SAVE, TEXT_ROOMNAME, TEXT_SCRIPT, TEXT_ROOMTEXT, TEXT_GOTOROOM, LAST_EDTEXT = TEXT_GOTOROOM, // Settings-mode text fields TEXT_TITLE, TEXT_DESC, TEXT_WEBSITE, TEXT_CREATOR, NUM_TEXTMODES, // Text modes with an entity FIRST_ENTTEXT = TEXT_SCRIPT, LAST_ENTTEXT = TEXT_ROOMTEXT }; struct GhostInfo { int rx; // game.roomx-100 int ry; // game.roomy-100 int x; // .xp int y; // .yp int col; // .colour Uint32 realcol; int frame; // .drawframe }; class editorclass { public: editorclass(void); void reset(void); void getlin(const enum textmode mode, const std::string& prompt, std::string* ptr); void placetilelocal(int x, int y, int t); int base(int x, int y); int backbase(int x, int y); int at(int x, int y); int freewrap(int x, int y); int backonlyfree(int x, int y); int backfree(int x, int y); int spikefree(int x, int y); int free(int x, int y); int match(int x, int y); int outsidematch(int x, int y); int backmatch(int x, int y); int edgetile(int x, int y); int outsideedgetile(int x, int y); int backedgetile(int x, int y); int labspikedir(int x, int y, int t); int spikedir(int x, int y); int getenemyframe(int t); void switch_tileset(const bool reversed); void switch_tilecol(const bool reversed); void clamp_tilecol(const int rx, const int ry, const bool wrap); void switch_enemy(const bool reversed); void switch_warpdir(const bool reversed); int entcol; Uint32 entcolreal; int kludgewarpdir[customlevelclass::numrooms]; int notedelay; int oldnotedelay; std::string note; std::string keybuffer; std::string filename; std::string loaded_filepath; int drawmode; int tilex, tiley; int keydelay, lclickdelay; bool savekey, loadkey; int levx, levy; int entframe, entframedelay; int scripttexttype; std::string oldenttext; enum textmode textmod; // In text entry std::string* textptr; // Pointer to text we're changing std::string textdesc; // Description (for editor mode text fields) union { int desc; // Which description row we're changing int textent; // Entity ID for text prompt }; bool xmod, zmod, cmod, vmod, bmod, hmod, spacemod, warpmod; bool titlemod, creatormod, desc1mod, desc2mod, desc3mod, websitemod; int roomnamehide; bool saveandquit; bool shiftmenu, shiftkey; int spacemenu; bool settingsmod, settingskey; int warpent; bool updatetiles, changeroom; int deletekeyheld; int boundarymod, boundarytype; int boundx1, boundx2, boundy1, boundy2; //Script editor stuff void removeline(int t); void insertline(int t); bool scripteditmod; int scripthelppage, scripthelppagedelay; std::vector<std::string> sb; std::string sbscript; int sbx, sby; int pagey; //Functions for interfacing with the script: void addhook(const std::string& t); void removehook(const std::string& t); void addhooktoscript(const std::string& t); void removehookfromscript(const std::string& t); void loadhookineditor(const std::string& t); void clearscriptbuffer(void); void gethooks(void); bool checkhook(const std::string& t); std::vector<std::string> hooklist; int hookmenupage, hookmenu; //Direct Mode variables int dmtile; int dmtileeditor; int returneditoralpha; int oldreturneditoralpha; std::vector<GhostInfo> ghosts; int currentghosts; }; void editorrender(void); void editorrenderfixed(void); void editorlogic(void); void editorinput(void); #ifndef ED_DEFINITION extern editorclass ed; #endif #endif /* EDITOR_H */ #endif /* NO_CUSTOM_LEVELS and NO_EDITOR */
21.736842
87
0.667797
[ "vector" ]
c9e7afb6f4a0c528e7cc5cedc7cc9442b3b873d2
5,711
h
C
System/Library/PrivateFrameworks/iWorkImport.framework/Frameworks/KeynoteQuicklook.framework/KNNoteInfo.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
1
2020-11-04T15:43:01.000Z
2020-11-04T15:43:01.000Z
System/Library/PrivateFrameworks/iWorkImport.framework/Frameworks/KeynoteQuicklook.framework/KNNoteInfo.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
null
null
null
System/Library/PrivateFrameworks/iWorkImport.framework/Frameworks/KeynoteQuicklook.framework/KNNoteInfo.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
null
null
null
/* * This header is generated by classdump-dyld 1.0 * on Sunday, September 27, 2020 at 12:27:08 PM Mountain Standard Time * Operating System: Version 14.0 (Build 18A373) * Image Source: /System/Library/PrivateFrameworks/iWorkImport.framework/Frameworks/KeynoteQuicklook.framework/KeynoteQuicklook * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. */ #import <KeynoteQuicklook/KeynoteQuicklook-Structs.h> #import <TSReading/TSPObject.h> #import <libobjc.A.dylib/TSDContainerInfo.h> #import <libobjc.A.dylib/TSWPStorageParent.h> #import <libobjc.A.dylib/TSKDocumentObject.h> #import <libobjc.A.dylib/TSKTransformableObject.h> @protocol TSDContainerInfo, TSDInfo; @class NSObject, TSWPStorage, NSArray, TSDInfoGeometry, NSString; @interface KNNoteInfo : TSPObject <TSDContainerInfo, TSWPStorageParent, TSKDocumentObject, TSKTransformableObject> { NSObject*<TSDContainerInfo> _parentInfo; BOOL _shrinkTextForPrinting; NSObject*<TSDInfo> parentInfo; TSWPStorage* _containedStorage; unsigned long long _initialCharacterIndexForExporting; CGRect _frameForPrinting; } @property (nonatomic,retain) TSWPStorage * containedStorage; //@synthesize containedStorage=_containedStorage - In the implementation block @property (nonatomic,readonly) int verticalAlignment; @property (assign,nonatomic) CGRect frameForPrinting; //@synthesize frameForPrinting=_frameForPrinting - In the implementation block @property (assign,nonatomic) BOOL shrinkTextForPrinting; //@synthesize shrinkTextForPrinting=_shrinkTextForPrinting - In the implementation block @property (assign,nonatomic) unsigned long long initialCharacterIndexForExporting; //@synthesize initialCharacterIndexForExporting=_initialCharacterIndexForExporting - In the implementation block @property (nonatomic,copy,readonly) NSArray * childInfos; @property (nonatomic,readonly) BOOL isMaster; @property (nonatomic,copy) TSDInfoGeometry * geometry; @property (assign,nonatomic) NSObject*<TSDInfo> parentInfo; @property (assign,nonatomic) TSPObject*<TSDOwningAttachment> owningAttachment; @property (nonatomic,readonly) TSPObject*<TSDOwningAttachment> owningAttachmentNoRecurse; @property (getter=isFloatingAboveText,nonatomic,readonly) BOOL floatingAboveText; @property (getter=isAnchoredToText,nonatomic,readonly) BOOL anchoredToText; @property (getter=isInlineWithText,nonatomic,readonly) BOOL inlineWithText; @property (getter=isInlineWithTextWithWrap,nonatomic,readonly) BOOL inlineWithTextWithWrap; @property (getter=isAttachedToBodyText,nonatomic,readonly) BOOL attachedToBodyText; @property (readonly) unsigned long long hash; @property (readonly) Class superclass; @property (copy,readonly) NSString * description; @property (copy,readonly) NSString * debugDescription; @property (assign,nonatomic) BOOL matchesObjectPlaceholderGeometry; @property (nonatomic,readonly) BOOL autoListRecognition; @property (nonatomic,readonly) BOOL autoListTermination; @property (nonatomic,readonly) BOOL textIsLinked; @property (nonatomic,readonly) BOOL preventsComments; @property (nonatomic,readonly) BOOL preventsChangeTracking; @property (nonatomic,readonly) BOOL supportsMultipleColumns; @property (nonatomic,readonly) long long contentWritingDirection; @property (nonatomic,readonly) BOOL storageChangesInvalidateWrap; @property (nonatomic,readonly) BOOL supportsVerticalTextLayoutInChildStorages; @property (nonatomic,readonly) BOOL supportsDropCapsInChildStorages; +(BOOL)needsObjectUUID; -(void)dealloc; -(int)verticalAlignment; -(id)childEnumerator; -(BOOL)isSelectable; -(id)copyWithContext:(id)arg1 ; -(void)setGeometry:(TSDInfoGeometry *)arg1 ; -(Class)layoutClass; -(TSDInfoGeometry *)geometry; -(id)initWithContext:(id)arg1 ; -(Class)repClass; -(void)setParentInfo:(NSObject*<TSDInfo>)arg1 ; -(void)clearBackPointerToParentInfoIfNeeded:(id)arg1 ; -(BOOL)isThemeContent; -(NSObject*<TSDInfo>)parentInfo; -(TSPObject*<TSDOwningAttachment>)owningAttachment; -(void)setOwningAttachment:(TSPObject*<TSDOwningAttachment>)arg1 ; -(TSPObject*<TSDOwningAttachment>)owningAttachmentNoRecurse; -(BOOL)isFloatingAboveText; -(BOOL)isAnchoredToText; -(BOOL)isInlineWithText; -(BOOL)isAttachedToBodyText; -(NSArray *)childInfos; -(BOOL)textIsVerticalAtCharIndex:(unsigned long long)arg1 ; -(void)willBeRemovedFromDocumentRoot:(id)arg1 ; -(void)wasRemovedFromDocumentRoot:(id)arg1 ; -(void)adoptStylesheet:(id)arg1 withMapper:(id)arg2 ; -(TSWPStorage *)containedStorage; -(void)setContainedStorage:(TSWPStorage *)arg1 ; -(void)willBeAddedToDocumentRoot:(id)arg1 dolcContext:(id)arg2 ; -(void)wasAddedToDocumentRoot:(id)arg1 dolcContext:(id)arg2 ; -(BOOL)autoListRecognition; -(BOOL)autoListTermination; -(long long)contentWritingDirection; -(BOOL)shouldHideEmptyBullets; -(id)objectUUIDPath; -(void)setPrimitiveGeometry:(id)arg1 ; -(BOOL)isInlineWithTextWithWrap; -(void)loadFromArchive:(const NoteArchive*)arg1 unarchiver:(id)arg2 ; -(void)saveToArchive:(NoteArchive*)arg1 archiver:(id)arg2 ; -(id)infoForSelectionPath:(id)arg1 ; -(void)loadFromUnarchiver:(id)arg1 ; -(void)saveToArchiver:(id)arg1 ; -(id)initWithContext:(id)arg1 containedStorage:(id)arg2 ; -(BOOL)textIsLinked; -(BOOL)preventsComments; -(BOOL)preventsChangeTracking; -(BOOL)supportsMultipleColumns; -(CGRect)frameForPrinting; -(void)setFrameForPrinting:(CGRect)arg1 ; -(BOOL)shrinkTextForPrinting; -(void)setShrinkTextForPrinting:(BOOL)arg1 ; -(unsigned long long)initialCharacterIndexForExporting; -(void)setInitialCharacterIndexForExporting:(unsigned long long)arg1 ; @end
48.811966
217
0.793031
[ "geometry" ]
c9e81f954fe10289b50eb3e53be65eb0d4432628
497
h
C
src/render/RenderableRectangle.h
ds84182/WiMu
91988bef1b82fda31bfee75e920b384831584e9b
[ "MIT" ]
1
2015-12-17T16:17:50.000Z
2015-12-17T16:17:50.000Z
src/render/RenderableRectangle.h
ds84182/WiMu
91988bef1b82fda31bfee75e920b384831584e9b
[ "MIT" ]
null
null
null
src/render/RenderableRectangle.h
ds84182/WiMu
91988bef1b82fda31bfee75e920b384831584e9b
[ "MIT" ]
null
null
null
#pragma once // smeas stream: 5:19 #include <stdlib.h> #include <stdio.h> #include <gccore.h> #include <malloc.h> #include "Renderable.h" class RenderableRectangle : public Renderable { public: f32 x, y, width, height; u32 *color; RenderableRectangle(f32 x, f32 y, f32 w, f32 h, u32 col = 0xFFFFFFFF) : x(x), y(y), width(w), height(h) { color = (u32*)memalign(32, 4); *color = col; DCFlushRange(color, sizeof(u32)); }; virtual ~RenderableRectangle(); virtual void render(); };
19.88
72
0.665996
[ "render" ]
c9e85229ac2f9d11b04f32bc971b21aaf7504256
5,139
h
C
src/core/camera.h
Shot511/RapidGL
eebad98eb38ea5f554beb75e151c47f5076e7088
[ "MIT" ]
1
2021-05-18T11:11:15.000Z
2021-05-18T11:11:15.000Z
src/core/camera.h
Shot511/RapidGL
eebad98eb38ea5f554beb75e151c47f5076e7088
[ "MIT" ]
2
2021-04-24T07:33:38.000Z
2021-07-08T15:10:26.000Z
src/core/camera.h
Shot511/RapidGL
eebad98eb38ea5f554beb75e151c47f5076e7088
[ "MIT" ]
null
null
null
#pragma once #include <glad/glad.h> #include <glm/vec2.hpp> #include <glm/mat4x4.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/quaternion.hpp> #include "input.h" namespace RGL { class Camera { public: /* * Perspective camera */ Camera(float fov, float aspect_ratio, float z_near, float z_far) : Camera() { m_projection = glm::perspective(glm::radians(fov), aspect_ratio, z_near, z_far); m_aspect_ratio = aspect_ratio; m_near = z_near; m_far = z_far; m_fov = fov; } /* * Ortho camera */ Camera(float left, float right, float bottom, float top, float z_near, float z_far) : Camera(true) { m_projection = glm::ortho(left, right, bottom, top, z_near, z_far); m_aspect_ratio = 1.0f; m_near = z_near; m_far = z_far; m_fov = 1.0f; } void setPosition(float x, float y, float z) { m_position = glm::vec3(x, y, z); m_is_dirty = true; } void setPosition(const glm::vec3& position) { m_position = position; m_is_dirty = true; } /* * Set orientation using Euler Angles in degrees */ void setOrientation(float x, float y, float z) { m_orientation = glm::angleAxis(glm::radians(x), glm::vec3(1.0f, 0.0f, 0.0f)) * glm::angleAxis(glm::radians(y), glm::vec3(0.0f, 1.0f, 0.0f)) * glm::angleAxis(glm::radians(z), glm::vec3(0.0f, 0.0f, 1.0f)); m_direction = glm::normalize(glm::conjugate(m_orientation) * glm::vec3(0.0f, 0.0f, 1.0f)); m_is_dirty = true; } /* * Set orientation using explicit direction vector */ void setOrientation(const glm::vec3 & direction) { m_orientation = glm::quatLookAt(glm::normalize(direction), glm::vec3(0.0, 1.0, 0.0)); m_direction = glm::normalize(glm::conjugate(m_orientation) * glm::vec3(0.0f, 0.0f, 1.0f)); m_is_dirty = true; } /* * Set orientation using axis and angle in degrees */ void setOrientation(const glm::vec3& axis, float angle) { m_orientation = glm::angleAxis(glm::radians(angle), glm::normalize(axis)); m_direction = glm::normalize(glm::conjugate(m_orientation) * glm::vec3(0.0f, 0.0f, 1.0f)); m_is_dirty = true; } void setOrientation(const glm::quat& quat) { m_orientation = quat; m_direction = glm::normalize(glm::conjugate(m_orientation) * glm::vec3(0.0f, 0.0f, 1.0f)); m_is_dirty = true; } glm::quat orientation() const { return m_orientation; } glm::vec3 position() const { return m_position; } glm::vec3 direction() const { return m_direction; } float AspectRatio() const { return m_aspect_ratio; } float NearPlane() const { return m_near; } float FarPlane() const { return m_far; } float FOV() const { return m_fov; } void update(double dt); glm::mat4 m_view; glm::mat4 m_projection; const bool m_is_ortho; float m_sensitivity; float m_move_speed; KeyCode m_unlock_mouse_key; KeyCode m_forward_key; KeyCode m_backward_key; KeyCode m_left_key; KeyCode m_right_key; KeyCode m_up_key; KeyCode m_down_key; private: Camera(bool is_ortho = false) : m_orientation (glm::vec3(0.0f)), m_position (glm::vec3(0.0f)), m_direction (glm::vec3(0.0f, 0.0f, -1.0f)), m_is_dirty (true), m_is_mouse_move (false), m_view (1.0f), m_projection (1.0f), m_is_ortho (is_ortho), m_sensitivity (0.2), m_move_speed (10.0), m_unlock_mouse_key(KeyCode::MouseRight), m_forward_key (KeyCode::W), m_backward_key (KeyCode::S), m_left_key (KeyCode::A), m_right_key (KeyCode::D), m_up_key (KeyCode::E), m_down_key (KeyCode::Q) {} glm::quat m_orientation; glm::vec3 m_position; glm::vec3 m_direction; float m_near; float m_far; float m_aspect_ratio; float m_fov; // in degrees glm::vec2 m_mouse_pressed_position; bool m_is_dirty; bool m_is_mouse_move; void move(const glm::vec3 & position, const glm::vec3& dir, float amount); }; }
31.527607
104
0.503016
[ "vector" ]
a00ac8f61bbf0aa3ba3c138070bd0b927c955111
1,625
h
C
src/Triangulation/Triangulation.h
vnm-interactive/Grove
3323e9090103a34c19bd799f39ade63f9ad9c746
[ "MIT" ]
1
2020-12-01T13:07:15.000Z
2020-12-01T13:07:15.000Z
src/Triangulation.h
rezaali/Cinder-Triangulation
419fbce8cdbc1e4d87c27203fb7096f08a85cf67
[ "MIT" ]
null
null
null
src/Triangulation.h
rezaali/Cinder-Triangulation
419fbce8cdbc1e4d87c27203fb7096f08a85cf67
[ "MIT" ]
null
null
null
/* Copyright (c) 2015 Simon Geilfus This code uses a class extracted and adapted from the OpenCV library for use with the Cinder C++ library, http://libcinder.org and all the relevant portion of code is tied to OpenCV license that can be found in Triangulation.cpp file 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 "cinder/Rect.h" #include "cinder/Vector.h" namespace Delaunay { //! triangulates the list of points and returns a list of triangles indices std::vector<uint32_t> getTriangleIndices( const ci::Rectf &rect, const std::vector<ci::vec2> &points = std::vector<ci::vec2>() ); };
43.918919
130
0.772923
[ "vector" ]
a7672a0c67d4321fb502ff05a937a5837ece980a
392
h
C
Sparky-core/src/sp/graphics/TextureManager.h
LifeOrGame/Sparky
2ebcba2613b47011a224ddce5bc9267b46ba0119
[ "Apache-2.0" ]
1,303
2015-02-15T05:12:55.000Z
2022-03-18T18:23:28.000Z
Sparky-core/src/sp/graphics/TextureManager.h
WildFire212/Sparky
a679d0834e37eb3570dff18b01550210734cb97e
[ "Apache-2.0" ]
124
2015-04-02T14:15:05.000Z
2021-05-05T12:47:16.000Z
Sparky-core/src/sp/graphics/TextureManager.h
WildFire212/Sparky
a679d0834e37eb3570dff18b01550210734cb97e
[ "Apache-2.0" ]
538
2015-02-19T21:53:15.000Z
2022-03-11T06:18:05.000Z
#pragma once #include "sp/sp.h" #include "sp/Types.h" #include "sp/graphics/API/Texture.h" namespace sp { namespace graphics { class SP_API TextureManager { private: static std::vector<API::Texture*> m_Textures; public: static API::Texture* Add(API::Texture* texture); static API::Texture* Get(const String& name); static void Clean(); private: TextureManager() { } }; } }
18.666667
50
0.693878
[ "vector" ]
a76d2d1463886e612c3c31accbeb7127f9876f34
3,013
h
C
NeatMouseWtl/neatcommon/include/neatcommon/system/localization.h
fernandojconti/neatmouse
f9b5a98622049063287d4734c7983b73f4bcb271
[ "MS-PL" ]
30
2017-01-20T08:28:08.000Z
2022-02-12T16:13:36.000Z
NeatMouseWtl/neatcommon/include/neatcommon/system/localization.h
fernandojconti/neatmouse
f9b5a98622049063287d4734c7983b73f4bcb271
[ "MS-PL" ]
12
2018-09-11T10:05:24.000Z
2020-11-17T09:41:40.000Z
NeatMouseWtl/neatcommon/include/neatcommon/system/localization.h
fernandojconti/neatmouse
f9b5a98622049063287d4734c7983b73f4bcb271
[ "MS-PL" ]
14
2017-01-20T08:28:12.000Z
2021-07-12T03:46:38.000Z
// // Copyright © 2016–2019 Neat Decisions. All rights reserved. // // This file is part of NeatMouse. // The use and distribution terms for this software are covered by the // Microsoft Public License (http://opensource.org/licenses/MS-PL) // which can be found in the file LICENSE at the root folder. // #pragma once #include "neatcommon/system/IniFiles.h" #include <memory> namespace neatcommon { namespace system { //===================================================================================================================== // CFormatter //===================================================================================================================== class CFormatter { public: explicit CFormatter(const std::wstring & fmtString) : fmtString(fmtString) {} template <class T> CFormatter & operator % (const T & t) { std::wstringstream s; s << t; values.push_back(s.str()); return *this; } std::wstring str() const; protected: std::vector<std::wstring> values; std::wstring fmtString; }; //===================================================================================================================== // LocalizeSection //===================================================================================================================== class LocalizeSection { public: using Ptr = std::shared_ptr<LocalizeSection>; LocalizeSection(); void Clear(); const std::wstring & GetValue(const std::string & value) const; const Ptr GetSection(const std::string & section) const; Ptr GetSection(const std::string & section); Ptr AddSection(const std::string & name); void SetValue(const std::string & name, const std::wstring & value); protected: std::wstring defaultString; std::map<std::string, std::wstring> values; std::map<std::string, Ptr> sections; }; //===================================================================================================================== // CLocalizer //===================================================================================================================== class CLocalizer { protected: std::wstring defaultString; LocalizeSection::Ptr section; public: CLocalizer(); void SetValue(const std::string & path, const std::wstring & value); const std::wstring & GetValue(const std::string & path) const; void loadFromIniFile(MyIniFile & iniFile); void load(UINT resourceId, const std::wstring & iResourceType); void load(const std::wstring & fileName); }; //===================================================================================================================== // LocaleUiDescriptor //===================================================================================================================== struct LocaleUiDescriptor { std::string code; UINT fileId; UINT iconId; UINT menuItemId; LocaleUiDescriptor(const std::string & iCode, UINT iFileId, UINT iIconId, UINT iMenuItemId) : code(iCode), fileId(iFileId), iconId(iIconId), menuItemId(iMenuItemId) {} }; }}
30.434343
119
0.49386
[ "vector" ]
a770e5299fbee7da79a74f289fc5787b9954719f
928
c
C
src/disposable/dispose_init.c
VeloPayments/v-portable-runtime
0810b249f78b04c9003db47782eb6a5bbb95f028
[ "MIT" ]
null
null
null
src/disposable/dispose_init.c
VeloPayments/v-portable-runtime
0810b249f78b04c9003db47782eb6a5bbb95f028
[ "MIT" ]
null
null
null
src/disposable/dispose_init.c
VeloPayments/v-portable-runtime
0810b249f78b04c9003db47782eb6a5bbb95f028
[ "MIT" ]
1
2020-07-03T18:18:24.000Z
2020-07-03T18:18:24.000Z
/** * \file dispose_init.c * * Implementation of disposable.dispose_init. * * \copyright 2020 Velo Payments, Inc. All rights reserved. */ #include <cbmc/model_assert.h> #include <vpr/disposable.h> MODEL_STRUCT_TAG_GLOBAL_EXTERN(disposable); /** * \brief Initialize a disposable instance with the given dispose method. * * \param disp The disposable instance to initialize. * \param func The dispose method to use to dispose this instance. */ void dispose_init(disposable_t* disp, dispose_method_t func) { /* parameter sanity checks. */ MODEL_ASSERT(NULL != disp); MODEL_ASSERT(NULL != func); /* set the dispose function. */ disp->dispose = func; /* set the struct tag for model checking. */ MODEL_STRUCT_TAG_INIT(disp->MODEL_STRUCT_TAG_REF(disposable), disposable); /* verify that this disposable instance is valid. */ MODEL_ASSERT(prop_disposable_valid(disp)); }
26.514286
78
0.709052
[ "model" ]
a78ca50f08afeffa51fc85cf80f4557469cf24dd
33,861
c
C
font.c
WartyMN/A2560-FoenixRetroOS
fd4c03d78794f2cc75e9d2de6b9ce86024e5b6fa
[ "MIT" ]
null
null
null
font.c
WartyMN/A2560-FoenixRetroOS
fd4c03d78794f2cc75e9d2de6b9ce86024e5b6fa
[ "MIT" ]
null
null
null
font.c
WartyMN/A2560-FoenixRetroOS
fd4c03d78794f2cc75e9d2de6b9ce86024e5b6fa
[ "MIT" ]
null
null
null
/* * font.c * * Created on: Mar 15, 2022 * Author: micahbly */ /*****************************************************************************/ /* Includes */ /*****************************************************************************/ // project includes #include "font.h" // C includes #include <stdbool.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> // A2560 includes #include <mcp/syscalls.h> #include "a2560_platform.h" #include "general.h" #include "bitmap.h" #include "text.h" /*****************************************************************************/ /* Definitions */ /*****************************************************************************/ /*****************************************************************************/ /* Enumerations */ /*****************************************************************************/ /*****************************************************************************/ /* Global Variables */ /*****************************************************************************/ /*****************************************************************************/ /* Private Function Prototypes */ /*****************************************************************************/ //! Get the total width, in pixels, for the specified character, including any whitespace uint8_t Font_GetCharWidth(Font* the_font, unsigned char the_char); //! Get the total height, in pixels, of one line of text, including any leading uint8_t Font_GetRowHeight(Font* the_font); //! Get the width of characters, in pixels, for fixed width fonts (all fonts will report one) uint8_t Font_GetFixedWidth(Font* the_font); // **** Debug functions ***** void Font_Print(Font* the_font); /*****************************************************************************/ /* Private Function Definitions */ /*****************************************************************************/ // **** NOTE: all functions in private section REQUIRE pre-validated parameters. // **** NEVER call these from your own functions. Always use the public interface. You have been warned! //! Get the total width, in pixels, for the specified character, including any whitespace uint8_t Font_GetCharWidth(Font* the_font, unsigned char the_char) { int16_t offset_width_value; int8_t width_value; //!< the total width of the character including any whitespace to left/right offset_width_value = the_font->width_table_[the_char]; if (offset_width_value == -1) { // offset/width table says this char does not exist in the font // switch to the "missing glyph" character, which is the last one in the font. the_char = the_font->lastChar + 1; offset_width_value = the_font->width_table_[the_char]; } width_value = offset_width_value & 0xFF; return width_value; } //! Get the total height, in pixels, of one line of text, including any leading uint8_t Font_GetRowHeight(Font* the_font) { return the_font->leading + the_font->fRectHeight; } //! Get the width of characters, in pixels, for fixed width fonts (all fonts will report one) uint8_t Font_GetFixedWidth(Font* the_font) { return the_font->leading + the_font->widMax; } // **** Debug functions ***** void Font_Print(Font* the_font) { DEBUG_OUT(("Font print out:")); DEBUG_OUT((" fontType: %i", the_font->fontType)); DEBUG_OUT((" firstChar: %i", the_font->firstChar)); DEBUG_OUT((" lastChar: %i", the_font->lastChar)); DEBUG_OUT((" widMax: %i", the_font->widMax)); DEBUG_OUT((" kernMax: %i", the_font->kernMax)); DEBUG_OUT((" nDescent: %i", the_font->nDescent)); DEBUG_OUT((" fRectWidth: %i", the_font->fRectWidth)); DEBUG_OUT((" fRectHeight: %i", the_font->fRectHeight)); DEBUG_OUT((" owTLoc: %u", the_font->owTLoc)); DEBUG_OUT((" ascent: %i", the_font->ascent)); DEBUG_OUT((" descent: %i", the_font->descent)); DEBUG_OUT((" leading: %i", the_font->leading)); DEBUG_OUT((" rowWords: %i", the_font->rowWords)); } /*****************************************************************************/ /* Public Function Definitions */ /*****************************************************************************/ // **** CONSTRUCTOR AND DESTRUCTOR ***** // constructor //! Create a Font object, and populate it from the passed buffer. //! NOTE: it is not possible to create a Font object without having a valid 'FONT' data chunk already in memory. //! NOTE: this allocates new memory for the font, and copies the font data to it from the passed buffer. It is not dependent on the data in the buffer after returning. //! @param the_data: Must contain a valid Mac 'FONT' resource data hunk. Font* Font_New(unsigned char* the_data) { Font* the_font; uint16_t image_table_count; uint16_t loc_table_count; uint16_t width_table_count; uint16_t height_table_count; bool has_height_table; // LOGIC: // the font data will contain 26 bytes of font record, followed by data // the data is: // font bits. size is 2 * rowWords * fRectHeight // location table. size is 2 * (lastChar-firstChar+3) // glyph offset/width table. size is 2 * (lastChar-firstChar+3) // // process is allocate space for font rec, copy over its 20 bytes // use the data now in the font rec to allocate space for the other 3 tables and copy them over. if ( (the_font = (Font*)calloc(1, sizeof(Font)) ) == NULL) { LOG_ERR(("%s %d: could not allocate memory to create new font record", __func__ , __LINE__)); goto error; } LOG_ALLOC(("%s %d: __ALLOC__ the_font %p size %i", __func__ , __LINE__, the_font, sizeof(Font))); // copy in the font record memcpy(the_font, the_data, FONT_RECORD_SIZE); the_data += FONT_RECORD_SIZE; // set up font data tables // LOGIC: // Mac fonts will have 3 tables immediately after the rowWords table: bitmap image table, bitmap offset table, and width/offset table // Mac fonts can optionally have a separate (higher-precision) character width table after the width offset table // Mac fonts can optionally have a separate image height table after the width offset table (or height table if present) // Both tables are presumed to be same size as the width offset table // We have no use for the higher precision character width table, but the optional height table, if present, can speed up drawing // Flags for both these are stored in bits 0 and 1 of the font type field. // font image table -- holds the pixels for each glyph, packed into 16 bit ints image_table_count = the_font->rowWords * the_font->fRectHeight; if ( (the_font->image_table_ = (uint16_t*)calloc(image_table_count, sizeof(uint16_t)) ) == NULL) { LOG_ERR(("%s %d: could not allocate memory to create new font image data", __func__ , __LINE__)); goto error; } LOG_ALLOC(("%s %d: __ALLOC__ the_font->image_table_ %p size %i", __func__ , __LINE__, the_font->image_table_, image_table_count * sizeof(uint16_t))); memcpy((char*)the_font->image_table_, (char*)the_data, image_table_count * sizeof(uint16_t)); the_data += image_table_count * sizeof(uint16_t); // location table -- holds offsets to each glyph, in BITS, from the start of the image table loc_table_count = the_font->lastChar - the_font->firstChar + 3; if ( (the_font->loc_table_ = (uint16_t*)calloc(loc_table_count, sizeof(uint16_t)) ) == NULL) { LOG_ERR(("%s %d: could not allocate memory to create new font location data", __func__ , __LINE__)); goto error; } LOG_ALLOC(("%s %d: __ALLOC__ the_font->loc_table_ %p size %i", __func__ , __LINE__, the_font->loc_table_, loc_table_count * sizeof(uint16_t))); memcpy((char*)the_font->loc_table_, (char*)the_data, loc_table_count * sizeof(uint16_t)); the_data += loc_table_count * sizeof(uint16_t); // width/offset table -- holds the horizontal offset to first pixel and total render width // the low byte will be the h offset (eg, 1, if you need to start drawing 1 pixel to the right of the pen location) // the high byte will contain the total width needed to render the character (including any whitespace to left or right of pixels) width_table_count = the_font->lastChar - the_font->firstChar + 3; if ( (the_font->width_table_ = (uint16_t*)calloc(width_table_count, sizeof(uint16_t)) ) == NULL) { LOG_ERR(("%s %d: could not allocate memory to create new font width data", __func__ , __LINE__)); goto error; } LOG_ALLOC(("%s %d: __ALLOC__ the_font->width_table_ %p size %i", __func__ , __LINE__, the_font->width_table_, width_table_count * sizeof(uint16_t))); memcpy((char*)the_font->width_table_, (char*)the_data, width_table_count * sizeof(uint16_t)); the_data += width_table_count * sizeof(uint16_t); // get the optional height table, if any - this can be used to optimize drawing speed // the low byte will be the v offset from top of glyph rect (eg, 3, if the first pixel is in the 4th row down) // the high byte will contain the total rows of visible pixels (eg, 3 for say a comma, but 9 for a capital letter) has_height_table = (bool)((the_font->fontType >> 0) & 0x01); // DEBUG_OUT(("%s %d: has_height_table=%u, has_detailed_width_table=%u", __func__, __LINE__, has_height_table, (bool)((the_font->fontType >> 1) & 0x01))); if (has_height_table) { //DEBUG_OUT(("%s %d: this font has the optional height table", __func__, __LINE__)); height_table_count = the_font->lastChar - the_font->firstChar + 3; if ( (the_font->height_table_ = (uint16_t*)calloc(height_table_count, sizeof(uint16_t)) ) == NULL) { LOG_ERR(("%s %d: could not allocate memory to create new font height data", __func__ , __LINE__)); goto error; } LOG_ALLOC(("%s %d: __ALLOC__ the_font->height_table_ %p size %i", __func__ , __LINE__, the_font->height_table_, height_table_count * sizeof(uint16_t))); memcpy((char*)the_font->height_table_, (char*)the_data, height_table_count * sizeof(uint16_t)); } else { //DEBUG_OUT(("%s %d: this font does NOT have the optional height table", __func__, __LINE__)); height_table_count = 0; the_font->height_table_ = NULL; } //DEBUG_OUT(("%s %d: image_table_count=%u, loc_table_count=%u, width_table_count=%u", __func__, __LINE__, image_table_count, loc_table_count, width_table_count)); // DEBUG //Font_Print(the_font); // General_PrintBufferCharacters((char*)the_font->image_table_, image_table_count * sizeof(uint16_t)); // General_PrintBufferCharacters((char*)the_font->loc_table_, loc_table_count * sizeof(uint16_t)); // General_PrintBufferCharacters((char*)the_font->width_table_, width_table_count * sizeof(uint16_t)); return the_font; error: if (the_font) Font_Destroy(&the_font); return NULL; } // destructor // frees all allocated memory associated with the passed object, and the object itself bool Font_Destroy(Font** the_font) { if (*the_font == NULL) { LOG_ERR(("%s %d: passed class object was null", __func__ , __LINE__)); return false; } if ((*the_font)->image_table_) { LOG_ALLOC(("%s %d: __FREE__ (*the_font)->image_table_ %p size ?", __func__ , __LINE__, (*the_font)->image_table_)); free((*the_font)->image_table_); } if ((*the_font)->loc_table_) { LOG_ALLOC(("%s %d: __FREE__ (*the_font)->loc_table_ %p size ?", __func__ , __LINE__, (*the_font)->loc_table_)); free((*the_font)->loc_table_); } if ((*the_font)->width_table_) { LOG_ALLOC(("%s %d: __FREE__ (*the_font)->width_table_ %p size ?", __func__ , __LINE__, (*the_font)->width_table_)); free((*the_font)->width_table_); } if ((*the_font)->height_table_) { LOG_ALLOC(("%s %d: __FREE__ (*the_font)->height_table_ %p size ?", __func__ , __LINE__, (*the_font)->height_table_)); free((*the_font)->height_table_); } LOG_ALLOC(("%s %d: __FREE__ *the_font %p size %i", __func__ , __LINE__, *the_font, sizeof(Font))); free(*the_font); *the_font = NULL; return true; } // **** xxx functions ***** //! Load a font into memory from disk, and create a font record from it //! NOTE: this allocates new memory for the font, and copies the font data to it from the passed buffer. It is not dependent on the data in the buffer after returning. //! This preliminary version is just a shell that does not read from disk, because no disk functionality available yet in f68/mcp as far as I know. Will switch to taking a path or something once disk is available. Font* Font_LoadFontData(unsigned char* the_data) { Font* the_font; // uint16_t image_table_count; // uint16_t loc_table_count; // uint16_t width_table_count; // uint16_t height_table_count; // bool has_height_table; if ( (the_font = Font_New(the_data)) == NULL) { LOG_ERR(("%s %d: Could not create a Font object", __func__ , __LINE__)); return NULL; } return the_font; } // **** Set xxx functions ***** // **** Get xxx functions ***** // **** Draw string functions ***** // Draw a string at the current "pen" location, using the current pen color of the bitmap // Truncate, but still draw the string if it is too long to display on the line it started. // No word wrap is performed. // If max_chars is less than the string length, only that many characters will be drawn (as space allows) // If max_chars is -1, then the full string length will be drawn, as space allows. bool Font_DrawString(Bitmap* the_bitmap, char* the_string, int16_t max_chars) { int16_t fit_count; int16_t i; int16_t num_chars; int16_t available_width; int16_t draw_result = 0; int16_t pixels_used; // LOGIC: // Determine how many characters of the string will fit in one line on the bitmap and draw that many num_chars = strlen(the_string); if (num_chars > max_chars && max_chars != -1) { num_chars = max_chars; } available_width = the_bitmap->width_ - the_bitmap->x_; //DEBUG_OUT(("%s %d: the_bitmap->width_=%i, the_bitmap->x_=%i, max_chars=%i, num_chars=%i", __func__, __LINE__, the_bitmap->width_, the_bitmap->x_, max_chars, num_chars)); fit_count = Font_MeasureStringWidth(the_bitmap->font_, the_string, num_chars, available_width, 0, &pixels_used); if (fit_count == -1) { LOG_ERR(("%s %d: Could not measure string width", __func__, __LINE__)); return false; } for (i = 0; i < fit_count && draw_result != -1; i++) { unsigned char the_char; the_char = the_string[i]; draw_result = Font_DrawChar(the_bitmap, the_char, NULL); } return true; } //! Draw a string in a rectangular block on the screen, with wrap. //! The current font, pen location, and pen color of the bitmap will be used //! If a word can't be wrapped, it will break the word and move on to the next line. So if you pass a rect with 1 char of width, it will draw a vertical line of chars down the screen. //! @param the_bitmap: a valid Bitmap object, with a valid font_ property //! @param width: the horizontal size of the text wrap box, in pixels. The total of 'width' and the current X coord of the bitmap must not be greater than width of the bitmap. //! @param height: the vertical size of the text wrap box, in pixels. The total of 'height' and the current Y coord of the bitmap must not be greater than height of the bitmap. //! @param the_string: the null-terminated string to be displayed. //! @param num_chars: either the length of the passed string, or as much of the string as should be displayed. Passing GEN_NO_STRLEN_CAP will mean it will attempt to display the entire string if it fits. //! @param wrap_buffer: pointer to a pointer to a temporary text buffer that can be used to hold the wrapped ('formatted') characters. The buffer must be large enough to hold num_chars of incoming text, plus additional line break characters where necessary. //! @param continue_function: optional hook to a function that will be called if the provided text cannot fit into the specified box. If provided, the function will be called each time text exceeds available space. If the function returns true, another chunk of text will be displayed, replacing the first. If the function returns false, processing will stop. If no function is provided, processing will stop at the point text exceeds the available space. //! @return returns a pointer to the first character in the string after which it stopped processing (if string is too long to be displayed in its entirety). Returns the original string if the entire string was processed successfully. Returns NULL in the event of any error. char* Font_DrawStringInBox(Bitmap* the_bitmap, int16_t width, int16_t height, char* the_string, int16_t num_chars, char** wrap_buffer, bool (* continue_function)(void)) { Font* the_font; char* needs_formatting; char* needed_formatting_last_round; char* formatted_string; int16_t this_line_len; bool do_another_round = false; int16_t row_height; int16_t fixed_char_width; int16_t x; int16_t y; if (the_bitmap == NULL) { LOG_ERR(("%s %d: passed bitmap was NULL", __func__, __LINE__)); return NULL; } x = Bitmap_GetX(the_bitmap); y = Bitmap_GetY(the_bitmap); //DEBUG_OUT(("%s %d: x=%i, y=%i, num_chars=%i", __func__, __LINE__, x, y, num_chars)); if (width < 1 || height < 1) { LOG_ERR(("%s %d: illegal width or height (%i, %i)", __func__, __LINE__, width, height)); return NULL; } if (x + width > the_bitmap->width_ || y + height > the_bitmap->height_) { LOG_ERR(("%s %d: illegal box size (%i, %i, %i, %i)", __func__, __LINE__, x, y, width, height)); return NULL; } // num_chars will be GEN_NO_STRLEN_CAP (-1) if the calling method wants us to display the entire string. if (num_chars == GEN_NO_STRLEN_CAP) { num_chars = General_Strnlen(the_string, WORD_WRAP_MAX_LEN); } formatted_string = *wrap_buffer; needs_formatting = the_string; needed_formatting_last_round = needs_formatting; the_font = the_bitmap->font_; row_height = Font_GetRowHeight(the_font); fixed_char_width = Font_GetFixedWidth(the_font); // DEBUG_OUT(("%s %d: row_height=%i, fixed_char_width=%i", __func__, __LINE__, row_height, fixed_char_width)); // outer loop: iterate on one-box worth of text until all text is displayed, or calling function no longer wants to proceed do { char* remaining_string; int16_t remaining_len; int16_t orig_len; int16_t v_pixels; int16_t num_rows; int16_t the_row; remaining_len = General_Strnlen(needs_formatting, num_chars + 1); // +1 for terminator. orig_len = remaining_len; // clear out the word wrap buffer in case anything had been there before. Shouldn't be necessary, but something weird happening in some cases with 2nd+ wrap, and this does prevent it. memset(formatted_string, 0, num_chars + 1); // format the string into chunks that will fit in the width specified, with line breaks on each line v_pixels = General_WrapAndTrimTextToFit(&needs_formatting, &formatted_string, orig_len, width, height, fixed_char_width, row_height, the_font, &Font_MeasureStringWidth); num_rows = v_pixels / row_height; // LOGIC: // needs_formatting is now either pointing at next char after cutoff (it not all text fit), or at itself still (if all text fit). // we can detect if all chars fit by comparing needs_formatting to needed_formatting_last_round //DEBUG_OUT(("%s %d: v_pixels=%i, num_rows=%i, remaining_len=%i, needs_formatting=%p, the_string=%p", __func__, __LINE__, v_pixels, num_rows, remaining_len, needs_formatting, the_string)); remaining_string = formatted_string; // clear the target box area on the screen -- if fail to do this, when we draw page 2, etc, it will be messy. //Text_FillBox(the_screen, x1, y1, x2, y2, ' ', fore_color, back_color); // set up char and attribute memory initial loc // the_char_loc = Text_GetMemLocForXY(the_screen, x1, y1, SCREEN_FOR_TEXT_CHAR); // the_attr_loc = the_char_loc + (the_screen->text_attr_ram_ - the_screen->text_ram_); // draw the string, one line at a time, until string is done or no more lines available the_row = 0; do { int16_t this_write_len; this_line_len = General_StrFindNextLineBreak(remaining_string, orig_len); // we don't know how many chars could fit on a line so have to just use remaining string len if (this_line_len == 1) { // next/first character is a line break char this_write_len = 0; // *(the_attr_loc) = the_attribute_value; } else { if (this_line_len == 0) { // there is no other line break char left in the string. this_write_len = General_Strnlen(remaining_string, remaining_len) - 0; //DEBUG_OUT(("%s %d: this_write_len=%i, remaining_len=%i, remaining='%s'", __func__ , __LINE__, this_write_len, remaining_len, remaining_string)); } else { // there is a line break character, but some other chars come first. write up to be not including the line break this_write_len = this_line_len - 1; // stop short of the the actual \n char. //DEBUG_OUT(("%s %d: this_line_len=%i, remaining_len=%i, remaining='%s'", __func__ , __LINE__, this_write_len, this_line_len, remaining_string)); } // memcpy(the_char_loc, remaining_string, this_write_len); // memset(the_attr_loc, the_attribute_value, this_write_len); Font_DrawString(the_bitmap, remaining_string, this_write_len); } remaining_string += this_write_len + 1; // skip past the actual \n char. remaining_len -= (this_write_len + 1); //DEBUG_OUT(("%s %d: remaining_len=%i, remaining='%s'", __func__ , __LINE__, remaining_len, remaining_string)); y += row_height; Bitmap_SetXY(the_bitmap, x, y); // the_char_loc += the_screen->text_mem_cols_; // the_attr_loc += the_screen->text_mem_cols_; the_row++; //DEBUG_OUT(("%s %d: the_row=%i, num_rows=%i, this_line_len=%i", __func__ , __LINE__, the_row, num_rows, this_line_len)); } while (the_row < num_rows && this_line_len > 0); // any more text still to format? if (needs_formatting == needed_formatting_last_round) { // all chars fit return the_string; } else { // some chars didn't fit - let calling function determine if it wants to display more if (continue_function == NULL) { // no hook provided, just return return needs_formatting; } else { if ((*continue_function)() == true) { // show next portion do_another_round = true; needed_formatting_last_round = needs_formatting; // reset to end results of this round so can check what happens next round } else { // calling function indicated it didn't want to display next portion return needs_formatting; } } } } while (do_another_round == true); return needs_formatting; } //! Calculates how many characters of the passed string will fit into the passed pixel width. //! The current font of the bitmap will be used as the basis for calculating fit. //! @param the_font: reference to a complete, loaded Font object. //! @param the_string: the null-terminated string to be measured. //! @param num_chars: either the length of the passed string, or as much of the string as should be displayed. Passing GEN_NO_STRLEN_CAP will mean it will attempt to measure the entire string. //! @param available_width: the width, in pixels, of the space the string is to be measured against. //! @param fixed_char_width: the width, in pixels, of one character. This value will be ignored. It exists to keep text-mode text-wrapping compatible with bitmap-font text-wrapping. //! @param measured_width: the number of pixels needed to display the characters that fit into the available_width. If the entire string fit, this is the width in pixels of that string. If only X characters fit, it is the pixel width of those X characters. //! @return returns -1 in any error condition, or the number of characters that fit. If the entire string fits, the passed len will be returned. int16_t Font_MeasureStringWidth(Font* the_font, char* the_string, int16_t num_chars, int16_t available_width, int16_t fixed_char_width, int16_t* measured_width) { int16_t required_width = 0; int16_t i; uint8_t this_width; if (the_font == NULL) { LOG_ERR(("%s %d: passed font was NULL", __func__, __LINE__)); return -1; } //DEBUG_OUT(("%s %d: num_chars=%i, available_width=%i, str='%s'", __func__, __LINE__, num_chars, available_width, the_string)); if (num_chars == 0) { return -1; } // num_chars will be GEN_NO_STRLEN_CAP (-1) if the calling method wants us to display the entire string. if (num_chars == GEN_NO_STRLEN_CAP) { num_chars = General_Strnlen(the_string, WORD_WRAP_MAX_LEN); } // LOGIC: // The Font object contains a table with the total width (including white space) of every character in the font // The Font object also contains a height pixel count and a leading pixel count. Combination of those is required V space per line. // The Mac fonts are in macRoman encoding, so a future translation process might be necessary. // Each glyph needs to be examined individually to get the width. for (i=0; i < num_chars && required_width <= available_width; i++) { unsigned char the_char; the_char = the_string[i]; this_width = Font_GetCharWidth(the_font, the_char); required_width += this_width; //DEBUG_OUT(("%s %d: the_char=%u, this_width=%u, required_width=%i, available_width=%i, i=%i, num_chars=%i", __func__, __LINE__, the_char, this_width, required_width, available_width, i, num_chars)); } if (required_width <= available_width) { *measured_width = required_width; //DEBUG_OUT(("%s %d: required_width=%i, measured_width=%i, available_width=%i, i=%i, num_chars=%i", __func__, __LINE__, required_width, *measured_width, available_width, i, num_chars)); return num_chars; } else { *measured_width = required_width - this_width; // take back that last measurement, as it went over the limit //DEBUG_OUT(("%s %d: required_width=%i, measured_width=%i, available_width=%i, i=%i, num_chars=%i", __func__, __LINE__, required_width, *measured_width, available_width, i, num_chars)); return i - 1; } } //! Draw one character on the bitmap, at the current bitmap pen coordinates //! NOTE: if the draw action is successful, the bitmaps current pen position will be updated in preparation for the next character draw. //! TODO: stop passing Font, and have the concept of a current font for a given bitmap. and maybe a default system font. //! return Returns number of horizontal pixels used, including left/right offsets, or -1 on any error condition. int16_t Font_DrawChar(Bitmap* the_bitmap, unsigned char the_char, Font* the_font) { uint8_t next_char; int16_t loc_offset; int16_t next_loc_offset; int16_t pixel_only_width; //!< the width of the character's actual pixels at max width int16_t image_offset_index; int16_t image_offset_index_rem; int16_t offset_width_value; int8_t h_offset_value; //!< the horizontal offset from pen position before the first pixel should be drawn int8_t width_value; //!< the total width of the character including any whitespace to left/right uint16_t* start_read_addr; int32_t row; uint8_t this_bit; uint8_t the_color; // shortcut to bitmap->color_ unsigned char* start_write_addr; int32_t pixels_moved; uint8_t first_row; // if no height table available, this is 0. otherwise it's first row to start drawing. uint8_t max_row; // if no height table available, this is height of font rec. otherwise it's 1 past the last vis row if (the_bitmap == NULL) { LOG_ERR(("%s %d: passed bitmap was NULL", __func__, __LINE__)); return -1; } // use the passed font record, unless NULL, and in that case, use the bitmap's font record if not NULL if (the_font == NULL) { the_font = the_bitmap->font_; if (the_bitmap->font_ == NULL) { LOG_ERR(("%s %d: passed font was NULL and the bitmap's font was also NULL", __func__, __LINE__)); return -1; } } // LOGIC: // Some Mac fonts have an optional height offset/num rows table. // If present, it will contain row of first visible pixel, and count of rows with pixels // We can use that to reduce reads/write loops and draw faster. // Characters that are not in the font (missing/-1 glyphs) will have 0 for height/offset. // If no height table present, we read/write through every row in the Font if ( ((the_font->fontType >> 0) & 0x01) ) { uint16_t v_offset_height; v_offset_height = the_font->height_table_[the_char]; if (v_offset_height == 0) { // if char is missing, height value seems to get set to 0. Use the one for the "missing glyph" char, which is one past last real char in font v_offset_height = the_font->height_table_[the_font->lastChar + 1]; } first_row = v_offset_height >> 8; max_row = first_row + v_offset_height & 0xFF; } else { first_row = 0; max_row = the_font->fRectHeight; } //DEBUG_OUT(("%s %d: glyph char=%u, height/offset value=%i, first_row=%i, max_row=%i", __func__, __LINE__, the_char, v_offset_height, first_row, max_row)); // the low byte will be the v offset from top of glyph rect (eg, 3, if the first pixel is in the 4th row down) // the high byte will contain the total rows of visible pixels (eg, 3 for say a comma, but 9 for a capital letter) // LOGIC: // The pixel-only width (max width of character excluding any whitespace to left or right) is determined by subtracting the location offset of the the char to draw, from that of the following character. All the characters are packed in "shoulder to shoulder, so basically you are just comparing start of this char vs start of next char. next_char = the_char + 1; // LOGIC: // The offset/width table contains -1 if the char does not exist in this font // If the char does exist: // the low byte will be the horizontal offset (eg, 1, if you need to start drawing 1 pixel to the right of the pen location)if the value is -1 // the high byte will contain the total width needed to render the character (including any whitespace to left or right of pixels) offset_width_value = the_font->width_table_[the_char]; if (offset_width_value == -1) { //DEBUG_OUT(("%s %d: offset/width table says this char (%u) does not exist in the font", __func__, __LINE__, the_char)); // switch to the "missing glyph" character, which is the last one in the font. the_char = the_font->lastChar + 1; next_char = the_char+1; offset_width_value = the_font->width_table_[the_char]; } else { //DEBUG_OUT(("%s %d: this char (%u) has a glyph in the font. Width/offset value=%i", __func__, __LINE__, the_char, offset_width_value)); } h_offset_value = offset_width_value >> 8; width_value = offset_width_value & 0xFF; loc_offset = the_font->loc_table_[the_char]; next_loc_offset = the_font->loc_table_[next_char]; pixel_only_width = next_loc_offset - loc_offset; //DEBUG_OUT(("%s %d: glyph char=%u, pixelwidth=%i, Width/offset value=%i, width_value=%i, h_offset_value=%i", __func__, __LINE__, the_char, pixel_only_width, offset_width_value, width_value, h_offset_value)); // for A in Chicago, I get "227". this is apparently the BIT offset from the start of the image data table. // so 227/16=14.1875=image_table_[13] + 3 bits. image_offset_index = loc_offset / 16; image_offset_index_rem = loc_offset % 16; //DEBUG_OUT(("%s %d: loc_offset=%i, image_offset_index=%i, image_offset_index_rem=%i", __func__, __LINE__, loc_offset, image_offset_index, image_offset_index_rem)); the_color = Bitmap_GetColor(the_bitmap); start_read_addr = the_font->image_table_ + image_offset_index; start_write_addr = Bitmap_GetMemLoc(the_bitmap); //DEBUG_OUT(("%s %d: start_write_addr=%p", __func__, __LINE__, start_write_addr)); for (row = 0; row < the_font->fRectHeight; row++) { uint16_t* read_addr; unsigned char* write_addr; read_addr = start_read_addr; write_addr = start_write_addr; // LOGIC: // we have one or more 16 bit words to parse // each bit in the word represents one horizontal pixel on or off // a glyph may start on one word, and end on the next // of the 16 bits, we likely only need a subset: // the bits from image_offset_index_rem to image_offset_index_rem + pixel_only_width if (row >= first_row && row < max_row) { int32_t pixels_written = 0; // for each row, account for any H offset specified for the glyph write_addr += h_offset_value; pixels_moved = 0; do { int16_t i; for (i = 15; i >= 0 && pixels_written < pixel_only_width; i--) { //DEBUG_OUT(("font_data=%u, bit=%u, i=%i, row=%i", *font_data, (unsigned char)((*font_data >> i) & 0x01), i, row)); if (pixels_moved >= image_offset_index_rem) { this_bit = (unsigned char)((*read_addr >> i) & 0x01); if (this_bit) { *write_addr = the_color; } write_addr++; pixels_written++; } pixels_moved++; } read_addr++; // move to next word in the font data } while (pixels_written < pixel_only_width); } // move read pointer in font to next row; move write pointer in bitmap to next row start_read_addr += the_font->rowWords; start_write_addr += the_bitmap->width_; } // finished writing visible pixels, but need to move pen further right if char's overall width was greater than amount moved so far pixels_moved += width_value - pixels_moved; the_bitmap->x_ += pixels_moved; return pixels_moved; }
39.603509
455
0.682142
[ "render", "object" ]
a78fc65be7dfa5a9367d25e292dac1dc273dc300
1,814
h
C
reatrix/src/World.h
PocoyoChow/Reatrix
17e4ea852df11f3e52417e3b1c4977d6a4050744
[ "MIT" ]
2
2019-08-09T11:46:56.000Z
2019-08-11T02:06:38.000Z
reatrix/src/World.h
PocoyoChow/Reatrix
17e4ea852df11f3e52417e3b1c4977d6a4050744
[ "MIT" ]
null
null
null
reatrix/src/World.h
PocoyoChow/Reatrix
17e4ea852df11f3e52417e3b1c4977d6a4050744
[ "MIT" ]
1
2021-08-13T08:13:04.000Z
2021-08-13T08:13:04.000Z
// // World.h // Reatrix // // Created by Lyn on 2019/5/30. // Copyright © 2019 Vin-Ex. All rights reserved. // #ifndef _RTX_SCENE_H_ #define _RTX_SCENE_H_ #include "Object.h" #include "Group.h" #include "Matcher.h" #include "SharedPtr.h" #include "container/Vector.h" #include "container/Set.h" #include "container/Map.h" #include "container/Stack.h" #include "component/Component.h" NAMESPACE_REATRIX_ENGINE_BEGIN class Entity; class System; class World : public Object { public: static SharedPtr<World> create(const String& name); virtual ~World(); void init(); void update(); void destroy(); bool isStarted(); SharedPtr<Entity> createEntity(const String& name); bool hasEntity(const SharedPtr<Entity>& entity) const; void destroyEntity(SharedPtr<Entity> entity); void destroyAllEntities(); Stack<SharedPtr<Entity> > getEntityPools(); Vector<SharedPtr<Entity> > getEntities(); SharedPtr<Group> getGroup(Matcher matcher); void clearGroups(); void addSystem(const SharedPtr<System> system); bool removeSystem(const SharedPtr<System> system); Map<ComponentId, Stack<Component *> > *getComponentPools(); void clearComponentPool(const ComponentId index); void clearComponentPools(); private: World(); bool m_is_started; Vector<SharedPtr<System> > m_systems; Set<SharedPtr<Entity> > m_entities; Set<SharedPtr<Entity> > m_retained_entities; Vector<SharedPtr<Entity> > m_entities_cache; Stack<SharedPtr<Entity> > m_reusable_entities; Map<ComponentId, Stack<Component *> > m_component_pools; Map<ComponentId, Vector<WeakPtr<Group> > > m_groups_for_index; Map<Matcher, SharedPtr<Group> > m_groups; }; NAMESPACE_REATRIX_ENGINE_END #endif /* World_h */
25.194444
66
0.701764
[ "object", "vector" ]
a799cecd2c493a4433219cc20402dad907f2df77
2,365
h
C
src/plugins/lvdfile.h
yslib/VoxelMan
e6e7719cccc3b5b95db0c6eb8d9f6277e5321e6c
[ "MIT" ]
5
2020-07-07T09:51:22.000Z
2021-09-15T04:20:06.000Z
src/plugins/lvdfile.h
yslib/VoxelMan
e6e7719cccc3b5b95db0c6eb8d9f6277e5321e6c
[ "MIT" ]
null
null
null
src/plugins/lvdfile.h
yslib/VoxelMan
e6e7719cccc3b5b95db0c6eb8d9f6277e5321e6c
[ "MIT" ]
1
2021-05-25T14:46:51.000Z
2021-05-25T14:46:51.000Z
#pragma once #include <memory> #include <VMFoundation/blockarray.h> #include <vector> #include <VMUtils/ref.hpp> #include <VMCoreExtension/ifilemappingplugininterface.h> #include "lvdfileheader.h" /** * This class is deprecated because of its ugly api, just for test */ namespace vm { class LVDFile { std::string fileName; LVDFileHeader header; //AbstraFileMap* lvdIO; unsigned char *lvdPtr; vm::Size3 vSize; vm::Size3 bSize; vm::Size3 oSize; int logBlockSize; int padding; bool validFlag; enum { LVDFileMagicNumber = 277536 }; enum { LogBlockSize5 = 5, LogBlockSize6 = 6, LogBlockSize7 = 7 }; enum { LVDHeaderSize = 24 }; void InitLVDIO(); void InitInfoByHeader(const LVDFileHeader & header); public: explicit LVDFile( const std::string &fileName ); LVDFile( const std::vector<std::string> &fileName, const std::vector<int> &lods = std::vector<int>{} ); LVDFile(const std::string & fileName,int BlockSideInLog,const Vec3i& dataSize, int padding ); bool Valid() const { return validFlag; } Size3 Size( int lod = 0 ) const { return vSize; } Size3 SizeByBlock( int lod = 0 ) const { return bSize; } int GetBlockPadding( int lod = 0 ) const { return padding; } int BlockSizeInLog( int lod = 0 ) const { return logBlockSize; } int BlockSize( int lod = 0 ) const { return 1 << BlockSizeInLog(); } int BlockDataCount( int lod = 0 ) const { return BlockSize() * BlockSize() * BlockSize(); } int BlockCount( int lod = 0 ) const { return bSize.x * bSize.y * bSize.z; } Size3 OriginalDataSize( int lod = 0 ) const { return oSize; } template <typename T, int nLogBlockSize> std::shared_ptr<Block3DArray<T, nLogBlockSize>> ReadAll( int lod = 0 ); void ReadBlock( char *dest, int blockId, int lod = 0 ); void WriteBlock( const char *src, int blockId, int lod ); bool Flush( int blockId, int lod ); bool Flush(); void Close(); unsigned char *ReadBlock( int blockId, int lod = 0 ); const LVDFileHeader &GetHeader() const { return header; } ~LVDFile(); private: Ref<IMappingFile> lvdIO; }; template <typename T, int nLogBlockSize> std::shared_ptr<Block3DArray<T, nLogBlockSize>> LVDFile::ReadAll( int lod ) { const auto s = Size(); const size_t bytes = s.x * s.y * s.z * sizeof( T ); auto ptr = std::make_shared<vm::Block3DArray<T, nLogBlockSize>>( s.x, s.y, s.z, nullptr ); return ptr; } } // namespace ysl
26.875
104
0.696829
[ "vector" ]
a79adfc56cb87b5f754745fd3345ab2bb308b656
5,526
h
C
MITK/Plugins/uk.ac.ucl.cmic.dnddisplay/src/niftkDnDDisplayPreferencePage.h
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
13
2018-07-28T13:36:38.000Z
2021-11-01T19:17:39.000Z
MITK/Plugins/uk.ac.ucl.cmic.dnddisplay/src/niftkDnDDisplayPreferencePage.h
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
null
null
null
MITK/Plugins/uk.ac.ucl.cmic.dnddisplay/src/niftkDnDDisplayPreferencePage.h
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
10
2018-08-20T07:06:00.000Z
2021-07-07T07:55:27.000Z
/*============================================================================= NifTK: A software platform for medical image computing. Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt in the top level directory for details. =============================================================================*/ #ifndef niftkDnDDisplayPreferencePage_h #define niftkDnDDisplayPreferencePage_h #include <berryIQtPreferencePage.h> #include <uk_ac_ucl_cmic_dnddisplay_Export.h> #include <berryIPreferences.h> class QWidget; namespace Ui { class niftkDnDDisplayPreferencePage; } namespace niftk { /** * \class DnDDisplayPreferencePage * \brief Provides a preferences page for the NifTK DnD Display, including default number of rows, * default number of columns, image interpolation, default window layout and background colour. * \ingroup uk_ac_ucl_cmic_dnddisplay */ struct DNDDISPLAY_EXPORT DnDDisplayPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: DnDDisplayPreferencePage(); DnDDisplayPreferencePage(const DnDDisplayPreferencePage& other); void CreateQtControl(QWidget* widget); QWidget* GetQtControl() const; /// \brief Nothing to do. void Init(berry::IWorkbench::Pointer workbench); /// \see IPreferencePage::PerformOk() virtual bool PerformOk(); /// \see IPreferencePage::PerformCancel() virtual void PerformCancel(); /// \see IPreferencePage::Update() virtual void Update(); /// \brief Stores the preference name for the default image interpolation in the DnD Display. static const QString DNDDISPLAY_DEFAULT_INTERPOLATION_TYPE; /// \brief Stores the preference name for the default background colour in the DnD Display. static const QString DNDDISPLAY_BACKGROUND_COLOUR; /// \brief Stores the preference name for the default background colour stylesheet in the NifTK DnD Display. static const QString DNDDISPLAY_BACKGROUND_COLOUR_STYLESHEET; /// \brief Stores the preference name for slice select tracking static const QString DNDDISPLAY_SLICE_SELECT_TRACKING; /// \brief Stores the preference name for time select tracking static const QString DNDDISPLAY_TIME_SELECT_TRACKING; /// \brief Stores the preference name for magnification select tracking static const QString DNDDISPLAY_MAGNIFICATION_SELECT_TRACKING; /// \brief Stores the preference name for whether we show the 2D cursors as people may prefer them to always be off. static const QString DNDDISPLAY_SHOW_2D_CURSORS; /// \brief Stores the preference name for whether we show the direction annotations. static const QString DNDDISPLAY_SHOW_DIRECTION_ANNOTATIONS; /// \brief Stores the preference name for whether we show the position annotation. static const QString DNDDISPLAY_SHOW_POSITION_ANNOTATION; /// \brief Stores the preference name for whether we show the intensity annotation. static const QString DNDDISPLAY_SHOW_INTENSITY_ANNOTATION; /// \brief Stores the preference name for whether we show the property annotation. static const QString DNDDISPLAY_SHOW_PROPERTY_ANNOTATION; /// \brief Stores the preference name for the properties to show as annotation. static const QString DNDDISPLAY_PROPERTIES_FOR_ANNOTATION; /// \brief Stores the preference name for the default window layout in the NifTK DnD Display. static const QString DNDDISPLAY_DEFAULT_WINDOW_LAYOUT; /// \brief Stores the preference name for whether to revert to last remembered slice, timestep and magnification when switching window layout. static const QString DNDDISPLAY_REMEMBER_VIEWER_SETTINGS_PER_WINDOW_LAYOUT; /// \brief Stores the preference name for the default number of rows in the DnD Display. static const QString DNDDISPLAY_DEFAULT_VIEWER_ROW_NUMBER; /// \brief Stores the preference name for the default number of columns in the DnD Display. static const QString DNDDISPLAY_DEFAULT_VIEWER_COLUMN_NUMBER; /// \brief Stores the preference name for the default drop type (single, multiple, all). static const QString DNDDISPLAY_DEFAULT_DROP_TYPE; /// \brief Stores the preference name for whether we show the magnification slider, as most people wont need it. static const QString DNDDISPLAY_SHOW_MAGNIFICATION_SLIDER; /// \brief Stores the preference name for whether we show the the options to show/hide cursor, /// direction annotations and 3D window in multi window layout. static const QString DNDDISPLAY_SHOW_SHOWING_OPTIONS; /// \brief Stores the preference name for whether we show the window layout controls. static const QString DNDDISPLAY_SHOW_WINDOW_LAYOUT_CONTROLS; /// \brief Stores the preference name for whether we show the viewer number controls. static const QString DNDDISPLAY_SHOW_VIEWER_NUMBER_CONTROLS; /// \brief Stores the preference name for a simple on/off preference for whether we show the single, multiple, all checkbox. static const QString DNDDISPLAY_SHOW_DROP_TYPE_CONTROLS; public slots: void OnBackgroundColourChanged(); void OnResetBackgroundColour(); void OnResetMIDASBackgroundColour(); private: QWidget* m_MainWidget; Ui::niftkDnDDisplayPreferencePage* ui; QString m_BackgroundColorStyleSheet; QString m_BackgroundColor; berry::IPreferences::Pointer m_DnDDisplayPreferencesNode; }; } #endif
36.84
144
0.773797
[ "3d" ]
a79d4e8706d5dc458d42510c7f18bfb55207b943
6,038
h
C
src/src/Container/unique_buffered_priority_indexed_fixed_queue.h
Scorbutics/skalang
c8d1869a2f0c7857ee05ef45bd3aa4e537d39558
[ "MIT" ]
3
2019-04-08T17:34:19.000Z
2020-01-03T04:47:06.000Z
src/src/Container/unique_buffered_priority_indexed_fixed_queue.h
Scorbutics/skalang
c8d1869a2f0c7857ee05ef45bd3aa4e537d39558
[ "MIT" ]
4
2020-04-19T22:09:06.000Z
2020-11-06T15:47:08.000Z
src/src/Container/unique_buffered_priority_indexed_fixed_queue.h
Scorbutics/skalang
c8d1869a2f0c7857ee05ef45bd3aa4e537d39558
[ "MIT" ]
null
null
null
#pragma once #include <optional> #include <array> #include <vector> #include <cassert> #include <iterator> namespace ska { template <typename T, std::size_t ArraySize, class Container = std::array<std::optional<T>, ArraySize>> class unique_buffered_priority_indexed_fixed_queue_iterator { Container* buf {}; std::size_t off; void safe_next_element() { while (off < ArraySize && !(*buf)[off].has_value()) { ++off; } keep_safe(); } void safe_previous_element() { while (off > 0 && !(*buf)[off].has_value()) { --off; } keep_safe(); } void keep_safe() { if ( off < 0 || off >= ArraySize || !(*buf)[off].has_value()) { off = ArraySize; } } public: unique_buffered_priority_indexed_fixed_queue_iterator(Container& buf, std::size_t offset, bool next = true) : buf(&buf), off(offset) { if(next) { safe_next_element(); } else { safe_previous_element(); } } bool operator==(const unique_buffered_priority_indexed_fixed_queue_iterator& i) { return i.buf == buf && i.off == off; } bool operator!=(const unique_buffered_priority_indexed_fixed_queue_iterator& i) { return !(*this == i); } unique_buffered_priority_indexed_fixed_queue_iterator& operator++() { off++; safe_next_element(); return *this; } unique_buffered_priority_indexed_fixed_queue_iterator operator++(int) { auto t = *this; off++; safe_next_element(); return t; } unique_buffered_priority_indexed_fixed_queue_iterator& operator--() { off--; safe_previous_element(); return *this; } unique_buffered_priority_indexed_fixed_queue_iterator operator--(int) { auto t = *this; off--; safe_previous_element(); return t; } unique_buffered_priority_indexed_fixed_queue_iterator operator-(int i) { return {*buf, off - i, false}; } unique_buffered_priority_indexed_fixed_queue_iterator operator+(int i) { return {*buf, off + i}; } std::size_t operator-(unique_buffered_priority_indexed_fixed_queue_iterator i) { return off - i.off; } std::size_t operator+(unique_buffered_priority_indexed_fixed_queue_iterator i) { return off + i.off; } bool operator<(unique_buffered_priority_indexed_fixed_queue_iterator const& sibling) const { return off < sibling.off; } bool operator<=(unique_buffered_priority_indexed_fixed_queue_iterator const& sibling) const { return off <= sibling.off; } bool operator>(unique_buffered_priority_indexed_fixed_queue_iterator const& sibling) const { return off > sibling.off; } bool operator>=(unique_buffered_priority_indexed_fixed_queue_iterator const& sibling) const { return off >= sibling.off; } auto& operator*() const { return (*buf)[off].value(); } }; struct PropertyPriorityGetter { template<class T> std::size_t operator()(const T& value) const { return value.priority; } }; template <class T, std::size_t ArraySize, class PriorityGetter = PropertyPriorityGetter> class unique_buffered_priority_indexed_fixed_queue { using BufferArrayContainer = std::array<std::vector<T>, ArraySize>; using ArrayContainer = std::array<std::optional<T>, ArraySize>; protected: ArrayContainer front_container; BufferArrayContainer buffer; PriorityGetter priorityGetter; std::size_t counter = 0; public: using iterator = unique_buffered_priority_indexed_fixed_queue_iterator<T, ArraySize>; using const_iterator = unique_buffered_priority_indexed_fixed_queue_iterator<T, ArraySize, const std::array<std::optional<T>, ArraySize>>; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; explicit unique_buffered_priority_indexed_fixed_queue() = default; bool empty() const { return size() == 0; } std::size_t size() const { return counter; } const T& top() const { assert(counter > 0); return front_container[counter - 1].value(); } void push(T x) { const auto priority = priorityGetter(x); assert(priority < ArraySize && priority >= 0); auto & cell = front_container[priority]; if (cell.has_value()) { auto newValue = std::move(cell.value()); cell = std::move(x); buffer[priority].push_back(std::move(newValue)); } else { cell = std::move(x); counter++; } } void pop() { if (remove_from_index(counter - 1)) { counter--; } } void remove(const T& x) { const auto priority = priorityGetter(x); if (priority == counter - 1) { pop(); } else { remove_from_index(priority); } } void erase(iterator it) { remove(*it); } iterator begin() { return { front_container, 0 }; } iterator end() { return { front_container, ArraySize }; } const_iterator begin() const { return { front_container, 0 }; } const_iterator end() const { return { front_container, ArraySize }; } const_iterator cbegin() const { return begin(); } const_iterator cend() const { return end(); } reverse_iterator rbegin() { return reverse_iterator{ end() }; } reverse_iterator rend() { return reverse_iterator{ begin() }; } const_reverse_iterator rbegin() const { return const_reverse_iterator{ end() }; } const_reverse_iterator rend() const { return const_reverse_iterator{ begin() }; } const_reverse_iterator crbegin() const { return rbegin(); } const_reverse_iterator crend() const { return rend(); } private: bool remove_from_index(std::size_t index) { assert(index < ArraySize && index >= 0); auto & bufferPool = buffer[index]; if (bufferPool.empty()) { front_container[index] = std::move(std::optional<T>{}); return true; } front_container[index] = std::move(bufferPool.back()); bufferPool.pop_back(); return false; } }; } namespace std { template<typename T, std::size_t ArraySize> class iterator_traits<ska::unique_buffered_priority_indexed_fixed_queue_iterator<T, ArraySize>> { public: using difference_type = std::ptrdiff_t; using size_type = std::size_t; using value_type = T; using pointer = T*; using reference = T&; using iterator_category = std::random_access_iterator_tag; }; }
36.593939
140
0.710831
[ "vector" ]
a7a34c5e5f4abef01351852f90e95d9cf679a302
3,241
h
C
visa/iga/GEDLibrary/GED_external/build/autogen-intel64/ged_enumerations_internal.h
bader/intel-graphics-compiler
04f51dc2f3d5047f334da5cb5eebe568480622f5
[ "MIT" ]
null
null
null
visa/iga/GEDLibrary/GED_external/build/autogen-intel64/ged_enumerations_internal.h
bader/intel-graphics-compiler
04f51dc2f3d5047f334da5cb5eebe568480622f5
[ "MIT" ]
null
null
null
visa/iga/GEDLibrary/GED_external/build/autogen-intel64/ged_enumerations_internal.h
bader/intel-graphics-compiler
04f51dc2f3d5047f334da5cb5eebe568480622f5
[ "MIT" ]
null
null
null
/*========================== begin_copyright_notice ============================ Copyright (c) 2015-2021 Intel Corporation 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. ============================= end_copyright_notice ===========================*/ /* * !!! DO NOT EDIT THIS FILE !!! * * This file was automagically crafted by GED's model parser. */ #ifndef GED_ENUMERATIONS_INTERNAL_H #define GED_ENUMERATIONS_INTERNAL_H extern const char* AccessModeEnumeration[3]; extern const char* AccWrCtrlEnumeration[3]; extern const char* AddrModeEnumeration[3]; extern const char* ArchRegEnumeration[16]; extern const char* AtomicOperationTypeEnumeration[16]; extern const char* BlockSizeEnumeration[6]; extern const char* BranchCtrlEnumeration[3]; extern const char* ChannelMaskEnumeration[6]; extern const char* ChannelModeEnumeration[3]; extern const char* ChannelOffsetEnumeration[9]; extern const char* CondModifierEnumeration[10]; extern const char* DataTypeEnumeration[16]; extern const char* DebugCtrlEnumeration[3]; extern const char* DepCtrlEnumeration[5]; extern const char* DstChanEnEnumeration[17]; extern const char* EOTEnumeration[3]; extern const char* ExecMaskOffsetCtrlEnumeration[15]; extern const char* ExecutionDataTypeEnumeration[3]; extern const char* FusionCtrlEnumeration[3]; extern const char* HeaderPresentEnumeration[3]; extern const char* MaskCtrlEnumeration[3]; extern const char* MathFCEnumeration[15]; extern const char* MathMacroExtEnumeration[10]; extern const char* MessageTypeEnumeration[64]; extern const char* NoSrcDepSetEnumeration[3]; extern const char* OpcodeEnumeration[76]; extern const char* PredCtrlEnumeration[19]; extern const char* PredInvEnumeration[3]; extern const char* RegFileEnumeration[4]; extern const char* RepCtrlEnumeration[3]; extern const char* ReturnDataControlEnumeration[3]; extern const char* SaturateEnumeration[3]; extern const char* SFIDEnumeration[16]; extern const char* SIMDModeEnumeration[4]; extern const char* SlotGroupEnumeration[4]; extern const char* SrcModEnumeration[5]; extern const char* SubFuncIDEnumeration[8]; extern const char* SwizzleEnumeration[5]; extern const char* SyncFCEnumeration[7]; extern const char* ThreadCtrlEnumeration[5]; #endif // GED_ENUMERATIONS_INTERNAL_H
42.644737
80
0.782783
[ "model" ]
a7a419f631e53cff6d80c2fb71ece9124f3ea663
1,545
h
C
include/org/apache/lucene/queryparser/flexible/core/parser/package-info.h
lukhnos/objclucene
29c7189a0b30ab3d3dd4c8ed148235ee296128b7
[ "MIT" ]
9
2016-01-13T05:38:05.000Z
2020-06-04T23:05:03.000Z
include/org/apache/lucene/queryparser/flexible/core/parser/package-info.h
lukhnos/objclucene
29c7189a0b30ab3d3dd4c8ed148235ee296128b7
[ "MIT" ]
4
2016-05-12T10:40:53.000Z
2016-06-11T19:08:33.000Z
include/org/apache/lucene/queryparser/flexible/core/parser/package-info.h
lukhnos/objclucene
29c7189a0b30ab3d3dd4c8ed148235ee296128b7
[ "MIT" ]
5
2016-01-13T05:37:39.000Z
2019-07-27T16:53:10.000Z
// // Generated by the J2ObjC translator. DO NOT EDIT! // source: ./queryparser/src/java/org/apache/lucene/queryparser/flexible/core/parser/package-info.java // /*! @brief Necessary interfaces to implement text parsers. <h2>Parser</h2> <p> The package <tt>org.apache.lucene.queryparser.flexible.parser</tt> contains interfaces that should be implemented by the parsers. Parsers produce QueryNode Trees from a string object. These package still needs some work to add support to for multiple parsers. Features that should be supported for the future, related with the parser: - QueryNode tree should be able convertible to any parser syntax. - The query syntax should support calling other parsers. - QueryNode tree created by multiple parsers. */ #include "J2ObjC_header.h" #pragma push_macro("INCLUDE_ALL_OrgApacheLuceneQueryparserFlexibleCoreParserPackage_info") #ifdef RESTRICT_OrgApacheLuceneQueryparserFlexibleCoreParserPackage_info #define INCLUDE_ALL_OrgApacheLuceneQueryparserFlexibleCoreParserPackage_info 0 #else #define INCLUDE_ALL_OrgApacheLuceneQueryparserFlexibleCoreParserPackage_info 1 #endif #undef RESTRICT_OrgApacheLuceneQueryparserFlexibleCoreParserPackage_info #if __has_feature(nullability) #pragma clang diagnostic push #pragma GCC diagnostic ignored "-Wnullability" #pragma GCC diagnostic ignored "-Wnullability-completeness" #endif #if __has_feature(nullability) #pragma clang diagnostic pop #endif #pragma pop_macro("INCLUDE_ALL_OrgApacheLuceneQueryparserFlexibleCoreParserPackage_info")
38.625
103
0.82589
[ "object" ]
a7ab575878e90410366a8b76247ee4b065692f92
6,338
h
C
cpp/libjoynr/include/joynr/LibJoynrMessageRouter.h
naeramarth7/joynr
3c378d3447cf83678d26ef0def44a29fe1270193
[ "Apache-2.0" ]
null
null
null
cpp/libjoynr/include/joynr/LibJoynrMessageRouter.h
naeramarth7/joynr
3c378d3447cf83678d26ef0def44a29fe1270193
[ "Apache-2.0" ]
null
null
null
cpp/libjoynr/include/joynr/LibJoynrMessageRouter.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 CHILDMESSAGEROUTER_H #define CHILDMESSAGEROUTER_H #include <functional> #include <memory> #include <mutex> #include <string> #include <unordered_set> #include "joynr/AbstractMessageRouter.h" #include "joynr/JoynrExport.h" #include "joynr/MessagingSettings.h" #include "joynr/PrivateCopyAssign.h" #include "joynr/Logger.h" namespace boost { namespace asio { class io_service; } // namespace asio } // namespace boost namespace joynr { template <typename T> class MessageQueue; class ITransportStatus; namespace exceptions { class JoynrRuntimeException; } // namespace exceptions class IMessagingStubFactory; class IMulticastAddressCalculator; namespace system { class Address; class RoutingProxy; } // namespace system /** * Class MessageRouter receives incoming JoynrMessages on the ClusterController * and forwards them either to a remote ClusterController or to a LibJoynr on the machine. * * 1 extracts the destination participant ID and looks up the EndpointAddress in the *MessagingEndpointDirectory * 2 creates a <Middleware>MessagingStub by calling MessagingStubFactory.create(EndpointAddress *addr) * 3 forwards the message using the <Middleware>MessagingStub.send(JoynrMessage msg) * * In sending, a ThreadPool of default size 6 is used with a 500ms default retry interval. */ class JOYNR_EXPORT LibJoynrMessageRouter : public joynr::AbstractMessageRouter { public: LibJoynrMessageRouter( MessagingSettings& messagingSettings, std::shared_ptr<const joynr::system::RoutingTypes::Address> incomingAddress, std::shared_ptr<IMessagingStubFactory> messagingStubFactory, boost::asio::io_service& ioService, std::unique_ptr<IMulticastAddressCalculator> addressCalculator, bool persistRoutingTable, std::vector<std::shared_ptr<ITransportStatus>> transportStatuses, std::unique_ptr<MessageQueue<std::string>> messageQueue, std::unique_ptr<MessageQueue<std::shared_ptr<ITransportStatus>>> transportNotAvailableQueue); ~LibJoynrMessageRouter() override; void routeInternal(std::shared_ptr<ImmutableMessage> message, std::uint32_t tryCount = 0) final; /* * Implement methods from IMessageRouter */ void addNextHop(const std::string& participantId, const std::shared_ptr<const joynr::system::RoutingTypes::Address>& address, bool isGloballyVisible, const std::int64_t expiryDateMs, const bool isSticky, const bool allowUpdate, std::function<void()> onSuccess = nullptr, std::function<void(const joynr::exceptions::ProviderRuntimeException&)> onError = nullptr) final; void removeNextHop( const std::string& participantId, std::function<void()> onSuccess, std::function<void(const joynr::exceptions::ProviderRuntimeException&)> onError) final; void addMulticastReceiver( const std::string& multicastId, const std::string& subscriberParticipantId, const std::string& providerParticipantId, std::function<void()> onSuccess, std::function<void(const joynr::exceptions::ProviderRuntimeException&)> onError) final; void removeMulticastReceiver( const std::string& multicastId, const std::string& subscriberParticipantId, const std::string& providerParticipantId, std::function<void()> onSuccess, std::function<void(const joynr::exceptions::ProviderRuntimeException&)> onError) final; void setParentAddress( std::string parentParticipantId, std::shared_ptr<const joynr::system::RoutingTypes::Address> parentAddress); /* * Method specific to LibJoynrMessageRouter */ void setParentRouter(std::shared_ptr<joynr::system::RoutingProxy> parentRouter, std::function<void()> onSuccess = nullptr, std::function<void(const joynr::exceptions::ProviderRuntimeException&)> onError = nullptr); bool publishToGlobal(const ImmutableMessage& message) final; /* * Method specific to LibJoynrMessageRouter, * removes parentRouter shared ptr in order to break cyclic dependency * SubscriptionManager -> LibJoynrMessageRouter -> RoutingProxy -> SubscriptionManager */ void shutdown() final; friend class MessageRunnable; private: DISALLOW_COPY_AND_ASSIGN(LibJoynrMessageRouter); ADD_LOGGER(LibJoynrMessageRouter) bool isParentMessageRouterSet(); void addNextHopToParent(std::string participantId, bool isGloballyVisible, std::function<void(void)> onSuccess = nullptr, std::function<void(const joynr::exceptions::ProviderRuntimeException&)> onError = nullptr); std::shared_ptr<joynr::system::RoutingProxy> parentRouter; std::shared_ptr<const joynr::system::RoutingTypes::Address> parentAddress; std::shared_ptr<const joynr::system::RoutingTypes::Address> incomingAddress; std::unordered_set<std::string> runningParentResolves; mutable std::mutex parentResolveMutex; void removeRunningParentResolvers(const std::string& destinationPartId); std::mutex parentClusterControllerReplyToAddressMutex; std::string parentClusterControllerReplyToAddress; const bool DEFAULT_IS_GLOBALLY_VISIBLE; }; } // namespace joynr #endif // CHILDMESSAGEROUTER_H
35.606742
100
0.692016
[ "vector" ]
a7b4549c7b7dcb75f572fff5fe38f2849be0c115
654
h
C
IpcDelegate/IpcCallPacket.h
antonplakhotnyk/ipcdelegates
0fc30118747596035fd13bf1dd55fa8c61fd1ad5
[ "MIT" ]
1
2021-09-18T12:34:01.000Z
2021-09-18T12:34:01.000Z
IpcDelegate/IpcCallPacket.h
antonplakhotnyk/ipcdelegates
0fc30118747596035fd13bf1dd55fa8c61fd1ad5
[ "MIT" ]
null
null
null
IpcDelegate/IpcCallPacket.h
antonplakhotnyk/ipcdelegates
0fc30118747596035fd13bf1dd55fa8c61fd1ad5
[ "MIT" ]
null
null
null
#pragma once #include <stdint.h> #include <vector> #include "IpcCallTransport.h" class IpcCallPacket { public: // |-- size 4B --|-- type 4B --|-- data (size B) --| enum PacketType { pt_call, pt_return, pt_enumerate }; static const int c_net_call_packet_type_size = 4; IpcCallPacket(); ~IpcCallPacket(); bool IsEnoughPacketData(IpcCallTransport* in_data); PacketType ReadType(IpcCallTransport* in_data); void ReadData(IpcCallTransport* in_data, std::vector<uint8_t>* data_replace); static void SendData(const std::vector<uint8_t>& out_data_buf, PacketType type, IpcCallTransport* out_data); private: uint32_t m_packet_size; };
21.8
109
0.737003
[ "vector" ]
a7b508dafaa01f7ead8461212e353e3be391b5ee
1,310
h
C
srcs/lox/frontend/scanner.h
edimetia3d/cppLox
394bb0855c2a9d9b53f179330c2daa341786a04d
[ "MIT" ]
2
2021-12-25T01:45:26.000Z
2022-02-10T00:50:25.000Z
srcs/lox/frontend/scanner.h
edimetia3d/cppLox
394bb0855c2a9d9b53f179330c2daa341786a04d
[ "MIT" ]
null
null
null
srcs/lox/frontend/scanner.h
edimetia3d/cppLox
394bb0855c2a9d9b53f179330c2daa341786a04d
[ "MIT" ]
null
null
null
// // License: MIT // #ifndef CPPLOX_SRCS_LOX_SCANNER_H_ #define CPPLOX_SRCS_LOX_SCANNER_H_ #include <string> #include <vector> #include "lox/lox_error.h" #include "lox/token/token.h" namespace lox { class Scanner { public: explicit Scanner(const std::string& srcs) : srcs_(&srcs) {} LoxError ScanAll(std::vector<Token>* output); LoxError ScanOne(Token* output); void Reset() { Reset(*srcs_); } void Reset(const std::string& srcs) { Scanner tmp(srcs); std::swap(tmp, *this); } private: bool ScanOne(); bool Match(char expected); char Peek(int offseet = 0); void AddStringToken(); static bool IsDigit(char c) { return c >= '0' && c <= '9'; } static bool IsAlpha(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_'; } static bool IsAlphaNumeric(char c) { return IsAlpha(c) || IsDigit(c); } void AddNumToken(); void AddToken(TokenType type); bool IsAtEnd() { return current_lex_pos_ >= srcs_->size(); } char Advance(); void AddIdentifierToken(); const std::string* srcs_; int start_lex_pos_ = 0; int current_lex_pos_ = 0; Token last_scan_; bool new_token_scaned_ = false; LoxError err_; int line_ = 0; void ResetTokenBeg(); void ResetErr(); }; } // namespace lox #endif // CPPLOX_SRCS_LOX_SCANNER_H_
19.552239
102
0.649618
[ "vector" ]
a7ba3ea002af28cc3125a1cbffbba3e9297e52a6
1,892
h
C
module/MathStats/mathstats.h
kungfooman/EiC-C-Interpreter
0c4150760b613f7de666c492ce14683f216cfc84
[ "Artistic-1.0-Perl" ]
19
2015-05-06T07:40:06.000Z
2021-01-22T01:59:31.000Z
module/MathStats/mathstats.h
kungfooman/EiC-C-Interpreter
0c4150760b613f7de666c492ce14683f216cfc84
[ "Artistic-1.0-Perl" ]
null
null
null
module/MathStats/mathstats.h
kungfooman/EiC-C-Interpreter
0c4150760b613f7de666c492ce14683f216cfc84
[ "Artistic-1.0-Perl" ]
4
2018-08-28T16:55:20.000Z
2022-02-07T12:42:58.000Z
#ifndef MATHSTATSH_ #define MATHSTTSH_ #define sortFloats(d,x) qsort(d,x,sizeof(float),compareFloats) #define showVector(data, n) do {int _i; for(_i = 0;_i<n;++_i)\ printf("%g,",(double)data[_i]);printf("\n");} while(0) #define showArray(data,nx,ny) do {int _i,_j,_c;\ for(_c=_i = 0;_i<ny;++_i) {\ printf("%3d: ",_i);\ for(_j =0;_j<nx;++_j,++_c)\ printf("%8.4g,",(double)data[_c]);\ printf("\n");}} while(0) #ifndef deg2rad #define deg2rad(a) (0.0174533*(a)) #endif int compareInts(const void *i1, const void *i2); int compareFloats(const void *i1, const void *i2); void subarray(void *IN, void *OUT, int n, int sizein, int sizeout); int * float2int(float *f, int n); float * int2float(int *f, int n); float * readarray(char *fname, int ncols, int *nrows); float getRange(float * data, int n); int * rselect(int N, int ns, int seed ); float randg(float mean, float sigma); int *intShell(int *y, int n); float *floatShell(float *y, int n); float * getcurve(float * data, int n); void modeDist(float *in, int nin, int *out, int nout); void regline(float *x, float *y, int n, float *b, float *a, float *r); void crosscorF(float *x, float *y, float *r, int nx, int nr); void crosscorI(int *x, int *y, int *r, int nx, int nr); int getlagF(float *x, float *y, int nx, float *minimum); int getlagI(int *x, int *y, int nx, int *minimum); float getSum(float *data,int nx); float getStd(float *data,int nx); float ** read_arrays(char *input, /* filename to get data from */ int *nx, /* array used to return array lengths in*/ int *na); /* number of arrays read returned here */ void free_arrays(float **arrays,int na); float ** readInTabFloats(FILE *fp, int *nv, int nc); /* combinatorial.c */ void nexcom(int N, int K, int *R, int *MTC); #endif
24.894737
67
0.617336
[ "3d" ]
a7bb3262fe165c76ad2376b424ff99e3f1f7497f
6,072
h
C
include/command_line.h
gc-ant/digiholo2D
354cb4b0377dd58eebe6393beb73e581ddd7126e
[ "Apache-2.0" ]
7
2016-09-07T16:54:51.000Z
2021-02-13T16:31:21.000Z
include/command_line.h
gc-ant/digiholo2D
354cb4b0377dd58eebe6393beb73e581ddd7126e
[ "Apache-2.0" ]
1
2021-02-13T16:43:38.000Z
2021-03-13T12:50:31.000Z
include/command_line.h
gc-ant/digiholo2D
354cb4b0377dd58eebe6393beb73e581ddd7126e
[ "Apache-2.0" ]
3
2017-01-30T13:54:46.000Z
2020-03-27T14:53:32.000Z
/* * Copyright 2015 G.C. Antonopoulos and B. Steltner, Laser Zentrum Hannover e.V. * * 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](http://www.apache.org/licenses/LICENSE-2.0) * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * File: command_line.h * Author: b.steltner * * Created on 19. Dezember 2014, 11:08 */ #ifndef COMMAND_LINE_H #define COMMAND_LINE_H /* Include Boost Headers */ //SmartPtr will be included via basic_includes #include <boost/algorithm/string.hpp> /* Input & output*/ #include "image/float_image.h" #include "image/in_out.h" //FORWARD DECLARATION START class abstract_tile_unwrapper; class abstract_tile_merger; //FORWARD DECLARATION END class command_line { public: //!Std constructor - does nothing... command_line(); /** * Main function call. Gets all necessary parameters and starts the program * @param method unwrap & merge or just unwrap * @param unwrapper name of the unwrapper to be used * @param model name of the model to be used in MLSQU unwrapper * @param merger name of the merger to be used * @param input input location of the file (for getting the real filename) * @param output output location (directory, ending with \\ !). NOTE: May be passed empty! * @param dimx width of the image * @param dimy height of the image * @param tilecount number of tiles in x and y direction */ void execute(std::string method, std::string unwrapper, std::vector<std::string> usettings, std::string merger, std::vector<std::string> msettings, std::string input_path, std::vector<std::string> input, std::string output, int dimx, int dimy, std::vector<int> tilecount); virtual ~command_line(); private: /** * Generate the filename with regards to the parameters used for creating the image * @param unwrapper name of the unwrapper used * @param merger merger used * @param input input location of the file (for getting the real filename) * @param output output location (directory, ending with \\ !). NOTE: May be passed empty! * @param dimx width of the image * @param dimy height of the image * @param tilecount number of tiles * @return */ std::string create_filename(std::string unwrapper, std::string merger, std::string input, std::string output, int dimx, int dimy, std::vector<int> tilecount); /** * Method returning the named unwrapper, empty sharedptr if no unwrapper with this name is implemented/supported * @param unwrapper name of the unwrapper to be used * @param model name of the model function to be used by the MLSQU-unwrapper * @return sharedptr to unwrapper */ sharedptr<abstract_tile_unwrapper> get_unwrapper(std::string unwrapper, std::vector<std::string> usettings); /** * Method returning the named merger, empty sharedptr if no merger with this name is implemented/supported * @param merger name of the merger to be used * @return sharedptr to merger */ sharedptr<abstract_tile_merger> get_merger(std::string merger, std::vector<std::string> msettings); /** * Single image unwrap method. * @param unwrapper name of the unwrapper to be used * @param model to be used by the MLSQU unwrapper * @param merger name of the merger to be used * @param input path to one image *.raw * @param output path to a directory the *.raw should be saved to (MAY be un-initialised => Standard Input File Directory is Output File Directory will be used) * @param dimx width of the input image * @param dimy height of the input image * @param tilecount number of tiles in each direction the image is split into blocks (eg. tilecount 50 => 2500 tiles) * @param expert_options */ void unwrap_and_merge(std::string unwrapper, std::vector<std::string> usettings, std::string merger, std::vector<std::string> msettings, std::string input_path, std::vector<std::string> input, std::string output, int dimx, int dimy, std::vector<int> tilecount, std::vector<std::string> expert_options = std::vector<std::string>()); /** * Get the image from the input-file location and read it into the wrapped_img. * @param input path to one image *.raw * @param wrapped_img sharedptr to empty float image, which will get filled with the input image. */ void cl_read_image(std::string input, sharedptr<row_major_float_image> wrapped_img); /** * Split the image into tiles and calculate the gradient of the tiles (for debug purposes mainly). Then save the two resulting images. */ void calculate_gradient(int dim, std::string input_path, std::vector<std::string> input, std::string output, int dimx, int dimy, std::vector<int> tilecount); //! Same arguments as above... bool legit_arguments(std::string method, std::string unwrapper, std::string merger, std::string output, int dimx, int dimy, std::vector<int> tilecount); /** * Use the pixel-based SRNCP-Merger (mainly for comparing purposes). * @param input * @param output * @param dimx * @param dimy */ void pixel_srncp(std::string input_path, std::vector<std::string> input, std::string output, int dimx, int dimy); /** * This method calls the right measurement methods * @param method Defines part of the analyse package used * @param input_path * @param input * @param dimx * @param dimy */ void analyse(std::string method, std::string input_path, std::vector<std::string> input, int dimx, int dimy); }; #endif /* COMMAND_LINE_H */
41.589041
335
0.701581
[ "vector", "model" ]
a7c226852b5de8c9621e209466e37917ab2b9c80
3,441
h
C
message/generation/swift-mt-generation/repository/SR2018/parsers/SwiftMtParser_MT203BaseListener.h
Yanick-Salzmann/message-converter-c
6dfdf56e12f19e0f0b63ee0354fda16968f36415
[ "MIT" ]
null
null
null
message/generation/swift-mt-generation/repository/SR2018/parsers/SwiftMtParser_MT203BaseListener.h
Yanick-Salzmann/message-converter-c
6dfdf56e12f19e0f0b63ee0354fda16968f36415
[ "MIT" ]
null
null
null
message/generation/swift-mt-generation/repository/SR2018/parsers/SwiftMtParser_MT203BaseListener.h
Yanick-Salzmann/message-converter-c
6dfdf56e12f19e0f0b63ee0354fda16968f36415
[ "MIT" ]
null
null
null
#include "repository/ISwiftMtParser.h" #include "SwiftMtMessage.pb.h" #include <vector> #include <string> #include "BaseErrorListener.h" #include "SwiftMtParser_MT203Lexer.h" // Generated from C:/programming/message-converter-c/message/generation/swift-mt-generation/repository/SR2018/grammars/SwiftMtParser_MT203.g4 by ANTLR 4.7.2 #pragma once #include "antlr4-runtime.h" #include "SwiftMtParser_MT203Listener.h" namespace message::definition::swift::mt::parsers::sr2018 { /** * This class provides an empty implementation of SwiftMtParser_MT203Listener, * which can be extended to create a listener which only needs to handle a subset * of the available methods. */ class SwiftMtParser_MT203BaseListener : public SwiftMtParser_MT203Listener { public: virtual void enterMessage(SwiftMtParser_MT203Parser::MessageContext * /*ctx*/) override { } virtual void exitMessage(SwiftMtParser_MT203Parser::MessageContext * /*ctx*/) override { } virtual void enterBh(SwiftMtParser_MT203Parser::BhContext * /*ctx*/) override { } virtual void exitBh(SwiftMtParser_MT203Parser::BhContext * /*ctx*/) override { } virtual void enterBh_content(SwiftMtParser_MT203Parser::Bh_contentContext * /*ctx*/) override { } virtual void exitBh_content(SwiftMtParser_MT203Parser::Bh_contentContext * /*ctx*/) override { } virtual void enterAh(SwiftMtParser_MT203Parser::AhContext * /*ctx*/) override { } virtual void exitAh(SwiftMtParser_MT203Parser::AhContext * /*ctx*/) override { } virtual void enterAh_content(SwiftMtParser_MT203Parser::Ah_contentContext * /*ctx*/) override { } virtual void exitAh_content(SwiftMtParser_MT203Parser::Ah_contentContext * /*ctx*/) override { } virtual void enterUh(SwiftMtParser_MT203Parser::UhContext * /*ctx*/) override { } virtual void exitUh(SwiftMtParser_MT203Parser::UhContext * /*ctx*/) override { } virtual void enterTr(SwiftMtParser_MT203Parser::TrContext * /*ctx*/) override { } virtual void exitTr(SwiftMtParser_MT203Parser::TrContext * /*ctx*/) override { } virtual void enterSys_block(SwiftMtParser_MT203Parser::Sys_blockContext * /*ctx*/) override { } virtual void exitSys_block(SwiftMtParser_MT203Parser::Sys_blockContext * /*ctx*/) override { } virtual void enterSys_element(SwiftMtParser_MT203Parser::Sys_elementContext * /*ctx*/) override { } virtual void exitSys_element(SwiftMtParser_MT203Parser::Sys_elementContext * /*ctx*/) override { } virtual void enterSys_element_key(SwiftMtParser_MT203Parser::Sys_element_keyContext * /*ctx*/) override { } virtual void exitSys_element_key(SwiftMtParser_MT203Parser::Sys_element_keyContext * /*ctx*/) override { } virtual void enterSys_element_content(SwiftMtParser_MT203Parser::Sys_element_contentContext * /*ctx*/) override { } virtual void exitSys_element_content(SwiftMtParser_MT203Parser::Sys_element_contentContext * /*ctx*/) override { } virtual void enterMt(SwiftMtParser_MT203Parser::MtContext * /*ctx*/) override { } virtual void exitMt(SwiftMtParser_MT203Parser::MtContext * /*ctx*/) override { } virtual void enterEveryRule(antlr4::ParserRuleContext * /*ctx*/) override { } virtual void exitEveryRule(antlr4::ParserRuleContext * /*ctx*/) override { } virtual void visitTerminal(antlr4::tree::TerminalNode * /*node*/) override { } virtual void visitErrorNode(antlr4::tree::ErrorNode * /*node*/) override { } }; } // namespace message::definition::swift::mt::parsers::sr2018
46.5
156
0.771287
[ "vector" ]
a7d83c5d4848e2165200807328c151cb8926f27b
1,817
h
C
mission/assembly/GyroAssembly.h
levkovigor/freertos-template2
7fdac94eb8e83da752d6db6cedb323c4e0ee8203
[ "Apache-2.0" ]
null
null
null
mission/assembly/GyroAssembly.h
levkovigor/freertos-template2
7fdac94eb8e83da752d6db6cedb323c4e0ee8203
[ "Apache-2.0" ]
null
null
null
mission/assembly/GyroAssembly.h
levkovigor/freertos-template2
7fdac94eb8e83da752d6db6cedb323c4e0ee8203
[ "Apache-2.0" ]
null
null
null
#ifndef MISSION_ASSEMBLY_GYROASSEMBLY_H_ #define MISSION_ASSEMBLY_GYROASSEMBLY_H_ #include <fsfw/devicehandlers/AssemblyBase.h> #include <fsfw/container/FixedArrayList.h> /** * @brief Assembly object for all Gyro Devices. * @ingroup subsystems */ class GyroAssembly: public AssemblyBase { public: GyroAssembly(object_id_t objectId, object_id_t objectIdGps0, object_id_t objectIdGps1, object_id_t parentId); virtual ~GyroAssembly(); /** * command children to reach mode,submode * * set #commandsOutstanding correctly, or use executeTable() * * @param mode * @param submode * @return * - @c RETURN_OK if ok * - @c NEED_SECOND_STEP if children need to be commanded again */ virtual ReturnValue_t commandChildren(Mode_t mode, Submode_t submode); virtual ReturnValue_t checkChildrenStateOn(Mode_t wantedMode, Submode_t wantedSubmode); /** * List of valid mode and submode combination for Gyro devices is * implemented here * @param mode * @param submode * @return */ virtual ReturnValue_t isModeCombinationValid(Mode_t mode, Submode_t submode); virtual ReturnValue_t initialize(); private: object_id_t gyro0Id; object_id_t gyro1Id; enum class Device { ONE, TWO }; static constexpr uint8_t NUMBER_OF_GYRO_DEVICES = 2; FixedArrayList<ModeListEntry, NUMBER_OF_GYRO_DEVICES> modeTable; static const Submode_t SINGLE = 0; static const Submode_t DUAL = 1; bool isUseable(object_id_t object, Mode_t mode); ReturnValue_t handleNormalModeCommand(Mode_t mode, Submode_t submode, uint8_t d0, uint8_t d1); ReturnValue_t handleOnModeCommand(Mode_t mode, Submode_t submode, uint8_t d0, uint8_t d1); }; #endif /* MISSION_ASSEMBLY_GYROASSEMBLY_H_ */
25.957143
72
0.722069
[ "object" ]
80fe25dce5d71b5c467a823e5f4bdbaaba0fe236
2,115
h
C
src/Grapher.h
ZeroBone/SdlGrapher
7c1cb73da49876032c128fb7b1c1085412d3be39
[ "MIT" ]
2
2019-02-25T10:46:30.000Z
2022-02-05T05:08:27.000Z
src/Grapher.h
ZeroBone/SdlGrapher
7c1cb73da49876032c128fb7b1c1085412d3be39
[ "MIT" ]
null
null
null
src/Grapher.h
ZeroBone/SdlGrapher
7c1cb73da49876032c128fb7b1c1085412d3be39
[ "MIT" ]
null
null
null
#ifndef ZAVU_GRAPHER_H #define ZAVU_GRAPHER_H #include <SDL_ttf.h> #include <limits> #include <cmath> #include "App.h" typedef double (*mathFunction_t)(double); class Grapher : public App { private: mathFunction_t mathFunction; int cx, cy; double scale = 30; bool rendering; TTF_Font* labelFont; public: Grapher(mathFunction_t mathFunction) : mathFunction(mathFunction) {} ~Grapher(); void run(); void init(const char* title, const char* fontFile); void onResized(); private: void render() override; void renderAxes(); void renderGraph(); void adjustForInterval(double intervalStart, double intervalEnd); void handleEvents(); void shouldRerender() { rendering = true; } double screenXToMathX(int screenX) { return (screenX - cx) / scale; } double screenYToMathY(int screenY) { return -(screenY - cy) / scale; } int mathXToScreenX(double mathX) { return cx + (int)(mathX * scale); } int mathYToScreenY(double mathY) { return cy - (int)(mathY * scale); } void handleKeyPressOrRelease() { // std::cout << currentEvent.key.keysym.sym << std::endl; // std::cout << currentEvent.key.keysym.scancode << std::endl; const Uint8* kbStateArray = SDL_GetKeyboardState(nullptr); if (kbStateArray[SDL_SCANCODE_UP]) { cy += 3; shouldRerender(); } else if (kbStateArray[SDL_SCANCODE_DOWN]) { cy -= 3; shouldRerender(); } if (kbStateArray[SDL_SCANCODE_LEFT]) { cx += 3; shouldRerender(); } else if (kbStateArray[SDL_SCANCODE_RIGHT]) { cx -= 3; shouldRerender(); } } static bool mathValueValid(double mathValue) { return !std::isnan(mathValue) && !std::isinf(mathValue); /*return mathValue != std::numeric_limits<double>::quiet_NaN() && mathValue != std::numeric_limits<double>::infinity();*/ } }; #endif //ZAVU_GRAPHER_H
20.142857
73
0.592908
[ "render" ]
440bf417c3e43f67fc1db3bd1a7148a39fe841ba
6,258
h
C
Source/NdiMedia/Public/NdiMediaFinder.h
Twentystudios/NdiMedia
4cc842c11940fbd2062cb940cce1e49ff5bea453
[ "BSD-3-Clause" ]
101
2016-08-05T10:33:42.000Z
2022-03-11T13:10:28.000Z
Source/NdiMedia/Public/NdiMediaFinder.h
Twentystudios/NdiMedia
4cc842c11940fbd2062cb940cce1e49ff5bea453
[ "BSD-3-Clause" ]
35
2016-10-03T14:35:25.000Z
2021-03-25T05:18:34.000Z
Source/NdiMedia/Public/NdiMediaFinder.h
Twentystudios/NdiMedia
4cc842c11940fbd2062cb940cce1e49ff5bea453
[ "BSD-3-Clause" ]
34
2016-08-19T15:34:55.000Z
2021-12-08T14:42:33.000Z
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "UObject/ObjectMacros.h" #include "UObject/Object.h" #include "UObject/ScriptMacros.h" #include "NdiMediaFinder.generated.h" /** * Identifies an NDI media source. */ USTRUCT(BlueprintType) struct FNdiMediaSourceId { GENERATED_BODY() /** Default constructor. */ FNdiMediaSourceId() { } /** * Create and initialize a new instance. * * @param InEndpoint The NDI source's IP endpoint. * @param InName The NDI source's name. */ FNdiMediaSourceId(const FString& InEndpoint, const FString& InName) : Endpoint(InEndpoint) , Name(InName) { } /** The IP endpoint of the NDI media source, i.e. "1.2.3.4:12345". */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=NDI) FString Endpoint; /** The name of the NDI media source, i.e. "NDI_SOURCE_NAME". */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=NDI) FString Name; public: /** * Get a string representation of this source. * * @return String representation, i.e. "My Stream (1.2.3.4:12345)". * @see ToMediaUrl */ FString ToString() const { return Name + TEXT(" [") + Endpoint + TEXT("]"); } }; // // Asset for finding NDI streams. // UCLASS(BlueprintType) class NDIMEDIA_API UNdiMediaFinder : public UObject { GENERATED_BODY() public: /** Default constructor. */ UNdiMediaFinder(); public: /** * Get the list of NDI media sources currently available on the network. * * @param OutSources Will contain the collection of found NDI source names and their URLs. * @return true on success, false if the finder wasn't initialized. * @see Initialize, Shutdown */ UFUNCTION(BlueprintCallable, Category=NDI) bool GetSources(TArray<FNdiMediaSourceId>& OutSources) const; /** * Initialize this finder and start discovering NDI sources on the network. * * @return true on success, false otherwise. * @see GetSources, Shutdown */ UFUNCTION(BlueprintCallable, Category=NDI) bool Initialize(); /** * Shut down this finder and stop discovering NDI sources on the network. * * @see GetSources, Initialize */ UFUNCTION(BlueprintCallable, Category=NDI) void Shutdown(); public: /** * Whether NDI sources running on the local machine should be discovered. * * @return true if local sources are discovered, false otherwise. * @see GetExtraAddresses, GetGroupFilters, GetSources, SetShowLocalSources */ UFUNCTION(BlueprintCallable, Category=NDI) bool GetShowLocalSources() const { return ShowLocalSources; } /** * Set whether NDI sources running on the local machine should be returned. * * @param ShowLocal Whether to show local sources. * @see GetShowLocalSources */ UFUNCTION(BlueprintCallable, Category=NDI) void SetShowLocalSources(bool NewShowLocal); public: /** * Add an IP address that should be searched for NDI sources. * * @param Address The address to add. * @see AddGroupFilter, ClearExtraAddresses, GetExtraAddresses, RemoveExtraAddress */ UFUNCTION(BlueprintCallable, Category=NDI) void AddExtraAddress(const FString& Address); /** * Clear the list of IP addresses to be searched for NDI sources. * * @see AddExtraAddress, ClearGroupFilters, GetExtraAddresses, RemoveExtraAddress */ UFUNCTION(BlueprintCallable, Category=NDI) void ClearExtraAddresses(); /** * Get the list of extra IP addresses to search for NDI sources. * * @return Collection of IP group strings. * @see AddExtraAddress, ClearExtraAddresses, GetGroupFilters, GetShowLocalSources, RemoveExtraAddress */ UFUNCTION(BlueprintCallable, Category=NDI) const TArray<FString>& GetExtraAddresses() const { return ExtraAddresses; } /** * Remove an IP address that should no longer be searched for NDI sources. * * @param Address The address to remove. * @see AddExtraAddress, ClearExtraAddresses, GetExtraAddresses, RemoveGroupFilter */ UFUNCTION(BlueprintCallable, Category=NDI) void RemoveExtraAddress(const FString& Address); public: /** * Add an NDI group to return NDI sources for. * * @param GroupName The group to add. * @see AddExtraAddress, ClearGroupFilters, GetGroupFilters, RemoveGroupFilter */ UFUNCTION(BlueprintCallable, Category=NDI) void AddGroupFilter(const FString& GroupName); /** * Clear the list of NDI groups to return NDI sources for. * * @see AddGroupFilter, ClearExtraAddresses, GetGroupFilters, RemoveGroupFilter */ UFUNCTION(BlueprintCallable, Category=NDI) void ClearGroupFilters(); /** * Get the list of NDI group names to return sources for. * * @return Collection of group names. * @see AddGroupFilter, ClearGroupFilters, GetExtraAddresses, GetShowLocalSources, RemoveGroupFilter */ UFUNCTION(BlueprintCallable, Category=NDI) const TArray<FString>& GetGroupFilters() const { return GroupFilters; } /** * Remove an NDI group to return sources for. * * @param GroupName The group to remove. * @see AddGroupFilter, ClearGroupFilters, GetGroupFilters, RemoveExtraAddress */ UFUNCTION(BlueprintCallable, Category=NDI) void RemoveGroupFilter(const FString& GroupName); public: //~ UObject interface virtual void BeginDestroy() override; #if WITH_EDITOR virtual void PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) override; #endif private: /** * The IP addresses of additional NDI sources to search. * * Use this setting to search additional IP addresses that cannot be discovered * automatically via the built-in mDNS discovery, i.e. computers in a separate * subnet or on the internet. */ UPROPERTY(EditAnywhere, Category=Discovery, AdvancedDisplay) TArray<FString> ExtraAddresses; /** * Optional list of NDI groups for which to find sources. * * Use this setting to limit the search for NDI media sources to a particular group. * If this field is empty, all groups will be searched. */ UPROPERTY(EditAnywhere, Category=Discovery, AdvancedDisplay) TArray<FString> GroupFilters; /** Whether to include sources running on the local machine (default = true). */ UPROPERTY(EditAnywhere, Category=Discovery) bool ShowLocalSources; private: /** The NDI source finder instance. */ void* FindInstance; };
25.647541
103
0.737136
[ "object" ]
440d91d4bf141db4474c5748bca7315bd55e5fa8
5,535
h
C
Source/BladeFramework/header/interface/IPage.h
OscarGame/blade
6987708cb011813eb38e5c262c7a83888635f002
[ "MIT" ]
146
2018-12-03T08:08:17.000Z
2022-03-21T06:04:06.000Z
Source/BladeFramework/header/interface/IPage.h
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
1
2019-01-18T03:35:49.000Z
2019-01-18T03:36:08.000Z
Source/BladeFramework/header/interface/IPage.h
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
31
2018-12-03T10:32:43.000Z
2021-10-04T06:31:44.000Z
/******************************************************************** created: 2016/04/20 filename: IPage.h author: Crazii purpose: paging for streaming static geometry in large scale scenes *********************************************************************/ #ifndef __Blade_IPage_h__ #define __Blade_IPage_h__ #include <BladeFramework.h> #include <math/Vector2i.h> #include <utility/String.h> #include <interface/public/IProgressCallback.h> namespace Blade { class IEntity; class IPage { public: //paging static const uint32 VISIBLE_PAGE_BITCOUNT = 3; static const uint32 VISIBlE_PAGE_MASK = (1 << VISIBLE_PAGE_BITCOUNT) - 1; static const uint32 MAX_VISIBLE_PAGE = 1 << VISIBLE_PAGE_BITCOUNT; static const uint32 MAX_PAGE_COUNT = 16; static const uint32 MIN_SUBPAGE_SIZE = 16; static const int DEFAULT_PRIORITY = 0xFFFF; static BLADE_FRAMEWORK_API const TString DEFAULT_LAYER; public: virtual ~IPage() {} /** @describe get page center position @param @return */ virtual const Vector2& getPosition() const = 0; /** @describe get page indices (x,z) @param @return */ virtual Vector2i getIndices() const = 0; /** @describe get local indices (x,z) within the range of [0,IPagingManager::DESC::mVisiblePages) @note local indices are fixed and irrelevant to current loading position @param @return */ virtual Vector2i getLocalIndices() const = 0; }; class IPagingManager { public: typedef struct SDesc { uint32 mVisiblePages; ///page per side. total visible = mVisiblePages*mVisiblePages uint32 mPageSize; ///size (loading range) for each page uint32 mPageCount; ///total page per side. }DESC; class IListener { public: //note: pages are always unloaded first, then load to new data (even it is initially empty) //that means the two event always appears in pair, the same event is never successively called twice. //also means onPageUnload is guaranteed to be always dispatched before onPageLoad //note2: if onPageUnload for a page happens in one main loop, onPageLoad for another page is guaranteed to happen in the same loop //note3: don't keep any references of the page parameter /** @brief */ virtual void onPageUnload(IPage* page) = 0; /** @brief */ virtual void onPageLoad(IPage* page) = 0; }; public: virtual ~IPagingManager() {} /** @describe get stage's descriptor @param @return */ virtual const DESC& getDesc() const = 0; inline uint32 getPageSize() const { return this->getDesc().mPageSize; } inline uint32 getVisiblePageCount() const { return this->getDesc().mVisiblePages; } inline uint32 getPageCount() const { return this->getDesc().mPageCount; } /** @describe @param @return */ virtual IPage* getPage(size_t x, size_t z) const = 0; /** @describe get page enclosing specified pos @param @return */ virtual IPage* getPageByPosition(scalar x, scalar z) const = 0; /** @describe @param @return */ virtual size_t getEntities(const AABB& aab, const TStringParam& elementTypes, TPointerParam<IEntity>& outEntities, size_t limit = -1) const = 0; inline size_t getEntities(const AABB& aab, const TString& elementType, TPointerParam<IEntity>& outEntities, size_t limit = -1) const { TStringParam l; l.push_back(elementType); return this->getEntities(aab, l, outEntities, limit); } /** @describe add layer info for paging system, shared by all stages' paging manager @param name: specify layer name @param elmentTypes: list of element types managed by this layer. managed layer will be loaded/unloaded by paging system @param subPageSize: layers are divided to sub pages. minimal sub page size is MIN_SUBPAGE_SIZE @param range: loading range, sub pages will be loaded if they pass range intersection, unloaded if they out of range. there is a buffer zone to avoid frequent loads/unloads. @param priority: loading order of the layer, layer with high priority value will loaded first @return */ virtual bool addLayer(const TString& name, const TStringParam& elementTypes, size_t subPageSize, scalar range, int priority = IPage::DEFAULT_PRIORITY) const = 0; /** @describe re-calculate paging by entity's geometry info (position, scale, rotation, bounding) @param @return */ virtual bool resetPaging() = 0; /** @describe load page synchronously. all entity within radius of paging strategy will be loaded synchronously @param @return */ virtual bool loadPages(const TString& path, const Vector3& position, const ProgressNotifier& notifier = ProgressNotifier::EMPTY) = 0; /** @describe @param @return */ virtual bool savePages(const TString& path, bool textFormat) const = 0; /** @describe @param @return */ virtual void update(const Vector3& position) = 0; /** @describe notify if a new static entity created or static entity geometry changed(pos,scale,rotation,bounds). @param @return */ virtual bool notifyEntity(IEntity* entity, bool newCreated = false, bool performLoad = false) = 0; /** @describe @param @return */ virtual bool addListener(IListener* listener) = 0; /** @describe @param @return */ virtual bool removeListener(IListener* listener) = 0; /** @describe @param @return */ virtual void setEditMode(bool editMode) = 0; /** @describe @param @return */ virtual bool isEditMode() const = 0; }; }//namespace Blade #endif//__Blade_IPage_h__
27.81407
175
0.69196
[ "geometry" ]
4411f45c5896d7847b7fb53c7c03735b6cf8fd17
601
h
C
RenderEngine.h
adhikasp/crane-transformation
95b4a3da60ac7930f25e18ab84598136947ba155
[ "MIT" ]
null
null
null
RenderEngine.h
adhikasp/crane-transformation
95b4a3da60ac7930f25e18ab84598136947ba155
[ "MIT" ]
null
null
null
RenderEngine.h
adhikasp/crane-transformation
95b4a3da60ac7930f25e18ab84598136947ba155
[ "MIT" ]
null
null
null
#ifndef __RENDERENGINE__ #define __RENDERENGINE__ #include <vector> #include "Shape.h" namespace CraneTranformation { using namespace System; using namespace System::Drawing; using System::Collections::Generic::List; public ref class RenderEngine { private: System::Windows::Forms::Panel^ canvas; List<Shape^>^ queue; Pen^ renderPen = gcnew Pen(Color::Black, 1.0f); public: RenderEngine(System::Windows::Forms::Panel^ Canvas); void addShape(Shape^ shape); void render(System::Object^ sender, System::Windows::Forms::PaintEventArgs^ e); }; } #endif
20.033333
83
0.700499
[ "render", "object", "shape", "vector" ]
4416407f13028aa2481928acde0864744cb4963c
7,585
h
C
sleuthkit/framework/tsk/framework/file/TskFile.h
hcktheheaven/OpenDF
2664307a9a4924c47f487d2c62b603a5fa449923
[ "Apache-2.0" ]
53
2015-01-24T10:36:01.000Z
2021-07-04T12:27:03.000Z
sleuthkit/framework/tsk/framework/file/TskFile.h
OSSSP/OpenDF
2664307a9a4924c47f487d2c62b603a5fa449923
[ "Apache-2.0" ]
84
2015-01-24T06:40:58.000Z
2019-07-07T17:35:30.000Z
sleuthkit/framework/tsk/framework/file/TskFile.h
OSSSP/OpenDF
2664307a9a4924c47f487d2c62b603a5fa449923
[ "Apache-2.0" ]
122
2015-01-24T17:52:45.000Z
2020-03-18T06:32:15.000Z
/* * The Sleuth Kit * * Contact: Brian Carrier [carrier <at> sleuthkit [dot] org] * Copyright (c) 2010-2012 Basis Technology Corporation. All Rights * reserved. * * This software is distributed under the Common Public License 1.0 */ /** * \file TskFile.h * Contains the interface for the TskFile class. */ #ifndef _TSK_FILE_H #define _TSK_FILE_H // System includes #include <string> #include <ios> // Framework includes #include "tsk/framework/services/TskImgDB.h" #include "tsk/framework/services/TskBlackboardArtifact.h" /** * An interface that is used to represent a file. This interface * is used during the analysis of a file and is typically created * based on data in TskImgDB, which was created by CarveExtract * or TskImageFile. Different implementations of this class * may retrieve file content and metadata in different ways. * TskFile objects are obtained from TskFileManager. */ class TSK_FRAMEWORK_API TskFile { public: virtual ~TskFile(); /** Returns the file id. */ uint64_t getId() const; /** * Get the high-level type (file system, local, carved, etc.) */ TskImgDB::FILE_TYPES getTypeId() const; /** Get the name */ std::string getName() const; /** Get the extension */ std::string getExtension() const; /** Get the parent file id */ uint64_t getParentFileId() const; /** Get the directory type */ TSK_FS_NAME_TYPE_ENUM getDirType() const; /** Get the metadata flags */ TSK_FS_META_TYPE_ENUM getMetaType() const; /** Get the directory flags */ TSK_FS_NAME_FLAG_ENUM getDirFlags() const; /** Get the metadata flags */ TSK_FS_META_FLAG_ENUM getMetaFlags() const; /** Get the file size */ TSK_OFF_T getSize() const; /** Get the change time */ time_t getCtime() const; /** Get the creation time */ time_t getCrtime() const; /** Get the last access time */ time_t getAtime() const; /** Get the modify time */ time_t getMtime() const; /** Get the mode */ TSK_FS_META_MODE_ENUM getMode() const; /** Get the user id */ TSK_UID_T getUid() const; /** Get the group id */ TSK_GID_T getGid() const; /** * Get the path of the file in the disk image. This * will not include the file name and will not include * any information about the file system or volume that * it was found in (if there were multiple file systems * in the image. * @returns Original path of the file. */ std::string getFullPath() const; /** * Get the path of the file in the disk image. This * will not include the file name but will include * either information about the file system or volume that * it was found in or an indicator that the file was produced * by carving. * @returns Original path of the file. */ std::string getUniquePath() const; /** * Get the fully qualified path of where this file should * be locally stored. It does not check if the file is * locally stored. Use exists() for that. */ virtual std::string getPath() const = 0; /** * Get the pre-calculated hash value of the specified type. * @param hashType Type of hash to lookup * @returns String of hash value or empty string if the value * has not been calculated. */ std::string getHash(TskImgDB::HASH_TYPE hashType) const; /** * Sets the file's hash value in the database. note that hash values * are not stored in the blackboard. * @param hashType Type of hash value * @param hash String value of hash. */ void setHash(TskImgDB::HASH_TYPE hashType, const std::string hash); /** * Return the known status of the file * @returns KNOWN_STATUS or -1 on error */ TskImgDB::KNOWN_STATUS getKnownStatus() const; /** * Tests if a local copy of the file exists at the default location. * @return True if a file exists, false otherwise */ virtual bool exists() const = 0; /** * @return True if this is a directory, false otherwise */ virtual bool isDirectory() const = 0; /** * @return True if this is a "virtual" file, false otherwise */ virtual bool isVirtual() const = 0; /** * Open the file. Must be called before reading. Implementations must * support concept of open() being called multiple times even if file * is already open. * @throws TskFileException on error */ virtual void open() = 0; /** * Closes the open file. */ virtual void close() = 0; /** * Save the file to the default location. This is a simple wrapper * around TskFileManager::saveFile. * @throws TskException if file id is zero along with exceptions * thrown by TskFileManager::saveFile. */ virtual void save(); /** * Get the current byte offset within the file. * @returns Current byte offset. * @throws TskFileException if file is not open. */ virtual TSK_OFF_T tell() const = 0; /** * Set the byte offset within the file. If the second parameter is not * supplied the offset will be set relative to the beginning of the file. * @param off Number off bytes to offset from origin. * @param origin The point from which the given offset is relative to. Defaults * to beginning of file. If origin is std::ios::end the offset must be a * negative number. * @returns The absolute file offset resulting from the repositioning. * @throws TskFileException if file is not open or if you attempt to seek * to an invalid offset. */ virtual TSK_OFF_T seek(const TSK_OFF_T off, std::ios::seekdir origin = std::ios::beg) = 0; /** * Read file content into a buffer. Reads from end of last read. * @param buf Buffer into which file content will be placed. * Must be at least "count" bytes in size. * @param count The number of bytes to read from the file. * @return The number of bytes read or -1 on error. */ virtual ssize_t read(char * buf, const size_t count) = 0; /** * Set the file status (where it is in its analysis life cycle) */ void setStatus(TskImgDB::FILE_STATUS status); /** Get the analysis status of the file (where it is in the analysis life cycle) */ TskImgDB::FILE_STATUS getStatus() const; //Blackboard methods virtual TskBlackboardArtifact createArtifact(int artifactTypeID); virtual TskBlackboardArtifact createArtifact(TSK_ARTIFACT_TYPE type); virtual TskBlackboardArtifact createArtifact(string artifactTypeName); virtual vector<TskBlackboardArtifact> getArtifacts(string artifactTypeName); virtual vector<TskBlackboardArtifact> getArtifacts(int artifactTypeID); virtual vector<TskBlackboardArtifact> getArtifacts(TSK_ARTIFACT_TYPE type); virtual vector<TskBlackboardArtifact> getAllArtifacts(); virtual TskBlackboardArtifact getGenInfo(); virtual void addGenInfoAttribute(TskBlackboardAttribute attr); protected: // File id. uint64_t m_id; // Our current offset into the file TSK_OFF_T m_offset; // Is the file open (used for both on disk and image files) bool m_isOpen; // The database file record. TskFileRecord m_fileRecord; /** * Loads the raw file data from the database. * @throws TskException on error */ void initialize(); }; #endif
28.515038
94
0.6588
[ "vector" ]
4436596142d70856f6a977567e1c8ebdb77b7b35
286
h
C
source/HelloOglSeries/source/tdogl/Texture.h
felixfqiu/ogl-series-Tom-Dalling
353ee1c4af4bd957f1c326b784f97eb175fdbde4
[ "Apache-2.0" ]
null
null
null
source/HelloOglSeries/source/tdogl/Texture.h
felixfqiu/ogl-series-Tom-Dalling
353ee1c4af4bd957f1c326b784f97eb175fdbde4
[ "Apache-2.0" ]
null
null
null
source/HelloOglSeries/source/tdogl/Texture.h
felixfqiu/ogl-series-Tom-Dalling
353ee1c4af4bd957f1c326b784f97eb175fdbde4
[ "Apache-2.0" ]
null
null
null
#pragma once #include <gl/glew.h> #include "Bitmap.h" namespace tdogl { class Texture { public: Texture(const Bitmap& bitmap, GLuint minMagFiler = GL_LINEAR, GLuint wrapMode = GL_CLAMP_TO_EDGE); ~Texture(); GLuint object() const; private: GLuint _object; }; };
13
40
0.678322
[ "object" ]
443e545720269181780063ee206fda59556d451f
22,200
h
C
dalign/align.h
MartinPippel/DAmar
3624a8c98d3d6c26db82d370a0aa4b13f5a0af17
[ "BSD-3-Clause" ]
12
2020-01-14T00:24:44.000Z
2022-03-31T03:42:00.000Z
dalign/align.h
MartinPippel/DAmar
3624a8c98d3d6c26db82d370a0aa4b13f5a0af17
[ "BSD-3-Clause" ]
null
null
null
dalign/align.h
MartinPippel/DAmar
3624a8c98d3d6c26db82d370a0aa4b13f5a0af17
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************************\ * * * Copyright (c) 2014, Dr. Eugene W. Myers (EWM). 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. * * * * · The name of EWM may not be used to endorse or promote products derived from * * this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY EWM ”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 EWM 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. * * * * For any issues regarding this software and its use, contact EWM at: * * * * Eugene W. Myers Jr. * * Bautzner Str. 122e * * 01099 Dresden * * GERMANY * * Email: gene.myers@gmail.com * * * \************************************************************************************/ /******************************************************************************************* * * Local alignment module. Routines for finding local alignments given a seed position, * representing such an l.a. with its interval and a set of pass-thru points, so that * a detailed alignment can be efficiently computed on demand. * * All routines work on a numeric representation of DNA sequences, i.e. 0 for A, 1 for C, * 2 for G, and 3 for T. * * Author: Gene Myers * Date : July 2013 * ********************************************************************************************/ #ifndef _A_MODULE #define _A_MODULE #include "db/DB.h" #define TRACE_XOVR 125 // If the trace spacing is not more than this value, then can // and do compress traces pts to 8-bit unsigned ints /*** INTERACTIVE vs BATCH version The defined constant INTERACTIVE (set in DB.h) determines whether an interactive or batch version of the routines in this library are compiled. In batch mode, routines print an error message and exit. In interactive mode, the routines place the error message in EPLACE (also defined in DB.h) and return an error value, typically NULL if the routine returns a pointer, and an unusual integer value if the routine returns an integer. Below when an error return is described, one should understand that this value is returned only if the routine was compiled in INTERACTIVE mode. ***/ /*** PATH ABSTRACTION: Coordinates are *between* characters where 0 is the tick just before the first char, 1 is the tick between the first and second character, and so on. Our data structure is called a Path refering to its conceptualization in an edit graph. A local alignment is specified by the point '(abpos,bbpos)' at which its path in the underlying edit graph starts, and the point '(aepos,bepos)' at which it ends. In otherwords A[abpos+1..aepos] is aligned to B[bbpos+1..bepos] (assuming X[1] is the *first* character of X). There are 'diffs' differences in an optimal local alignment between the beginning and end points of the alignment (if computed by Compute_Trace), or nearly so (if computed by Local_Alignment). Optionally, a Path can have additional information about the exact nature of the aligned substrings if the field 'trace' is not NULL. Trace points to either an array of integers (if computed by a Compute_Trace routine), or an array of unsigned short integers (if computed by Local_Alignment). If computed by Local_Alignment 'trace' points at a list of 'tlen' (always even) short values: d_0, b_0, d_1, b_1, ... d_n-1, b_n-1, d_n, b_n to be interpreted as follows. The alignment from (abpos,bbpos) to (aepos,bepos) passes through the n trace points for i in [1,n]: (a_i,b_i) where a_i = floor(abpos/TS)*TS + i*TS and b_i = bbpos + (b_0 + b_1 + b_i-1) where also let a_0,b_0 = abpos,bbpos and a_(n+1),b_(n+1) = aepos,bepos. That is, the interior (i.e. i != 0 and i != n+1) trace points pass through every TS'th position of the aread where TS is the "trace spacing" employed when finding the alignment (see New_Align_Spec). Typically TS is 100. Then d_i is the number of differences in the portion of the alignment between (a_i,b_i) and (a_i+1,b_i+1). These trace points allow the Compute_Trace routines to efficiently compute the exact alignment between the two reads by efficiently computing exact alignments between consecutive pairs of trace points. Moreover, the diff values give one an idea of the quality of the alignment along every segment of TS symbols of the aread. If computed by a Compute_Trace routine, 'trace' points at a list of 'tlen' integers < i1, i2, ... in > that encodes an exact alignment as follows. A negative number j indicates that a dash should be placed before A[-j] and a positive number k indicates that a dash should be placed before B[k], where A and B are the two sequences of the overlap. The indels occur in the trace in the order in which they occur along the alignment. For a good example of how to "decode" a trace into an alignment, see the code for the routine Print_Alignment. ***/ typedef struct { void *trace; int tlen; int diffs; int abpos, bbpos; int aepos, bepos; } Path; /*** ALIGNMENT ABSTRACTION: An alignment is modeled by an Alignment record, which in addition to a *pointer* to a 'path', gives pointers to the A and B sequences, their lengths, and indicates whether the B-sequence needs to be complemented ('comp' non-zero if so). The 'trace' pointer of the 'path' subrecord can be either NULL, a list of pass-through points, or an exact trace depending on what routines have been called on the record. One can (1) compute a trace, with Compute_Trace, either from scratch if 'path.trace' = NULL, or using the sequence of pass-through points in trace, (2) print an ASCII representation of an alignment, or (3) reverse the roles of A and B, and (4) complement a sequence (which is a reversible process). If the alignment record shows the B sequence as complemented, *** THEN IT IS THE RESPONSIBILITY OF THE CALLER *** to make sure that bseq points at a complement of the sequence before calling Compute_Trace or Print_Alignment. Complement_Seq complements the sequence a of length n. The operation does the complementation/reversal in place. Calling it a second time on a given fragment restores it to its original state. ***/ #define COMP_FLAG 0x1 #define ACOMP_FLAG 0x2 // A-sequence is complemented, not B ! Only Local_Alignment notices #define COMP(x) ((x) & COMP_FLAG) #define ACOMP(x) ((x) & ACOMP_FLAG) #define START_FLAG 0x4 // LA is the first of a chain of 1 or more la's #define NEXT_FLAG 0x8 // LA is the next segment of a chain. #define BEST_FLAG 0x10 // This is the start of the best chain #define CHAIN_START(x) ((x) & START_FLAG) #define CHAIN_NEXT(x) ((x) & NEXT_FLAG) #define BEST_CHAIN(x) ((x) & BEST_FLAG) #define ELIM_FLAG 0x20 // This LA should be ignored #define ELIM(x) ((x) & ELIM_FLAG) typedef struct { Path *path; uint32 flags; /* Pipeline status and complementation flags */ char *aseq; /* Pointer to A sequence */ char *bseq; /* Pointer to B sequence */ int alen; /* Length of A sequence */ int blen; /* Length of B sequence */ } Alignment; void Complement_Seq(char *a, int n); /* Many routines like Local_Alignment, Compute_Trace, and Print_Alignment need working storage that is more efficiently reused with each call, rather than being allocated anew with each call. Each *thread* can create a Work_Data object with New_Work_Data and this object holds and retains the working storage for routines of this module between calls to the routines. If enough memory for a Work_Data is not available then NULL is returned. Free_Work_Data frees a Work_Data object and all working storage held by it. */ typedef void Work_Data; Work_Data *New_Work_Data(); void Free_Work_Data(Work_Data *work); /* Local_Alignment seeks local alignments of a quality determined by a number of parameters. These are coded in an Align_Spec object that can be created with New_Align_Spec and freed with Free_Align_Spec when no longer needed. There are 4 essential parameters: ave_corr: the average correlation (1 - 2*error_rate) for the sought alignments. For Pacbio data we set this to .70 assuming an average of 15% error in each read. trace_space: the spacing interval for keeping trace points and segment differences (see description of 'trace' for Paths above) freq[4]: a 4-element vector where afreq[0] = frequency of A, f(A), freq[1] = f(C), freq[2] = f(G), and freq[3] = f(T). This vector is part of the header of every HITS database (see db.h). If an alignment cannot reach the boundary of the d.p. matrix with this condition (i.e. overlap), then the last/first 30 columns of the alignment are guaranteed to be suffix/prefix positive at correlation ave_corr * g(freq) where g is an empirically measured function that increases from 1 as the entropy of freq decreases. If memory is unavailable or the freq distribution is too skewed then NULL is returned. You can get back the original parameters used to create an Align_Spec with the simple utility functions below. */ typedef void Align_Spec; //Align_Spec *New_Align_Spec(double ave_corr, int trace_space, float *freq, int reach);// HEIDELBERG_MODIFICATION Align_Spec *New_Align_Spec(double ave_corr, int trace_space, float *freq, int nthreads, int symmetric, int only_identity, int no_trace_points, int reach); void Free_Align_Spec(Align_Spec *spec); int Trace_Spacing(Align_Spec *spec); double Average_Correlation(Align_Spec *spec); float *Base_Frequencies(Align_Spec *spec); int Overlap_If_Possible(Align_Spec *spec); /* Local_Alignment finds the longest significant local alignment between the sequences in 'align' subject to: (a) the alignment criterion given by the Align_Spec 'spec', (b) it passes through one of the points (anti+k)/2,(anti-k)/2 for k in [low,hgh] within the underlying dynamic programming matrix (i.e. the points on diagonals low to hgh on anti-diagonal anti or anti-1 (depending on whether the diagonal is odd or even)), (c) if lbord >= 0, then the alignment is always above diagonal low-lbord, and (d) if hbord >= 0, then the alignment is always below diagonal hgh+hbord. The path record of 'align' has its 'trace' filled from the point of view of an overlap between the aread and the bread. In addition a Path record from the point of view of the bread versus the aread is returned by the function, with this Path's 'trace' filled in appropriately. The space for the returned path and the two 'trace's are in the working storage supplied by the Work_Data packet and this space is reused with each call, so if one wants to retain the bread-path and the two trace point sequences, then they must be copied to user-allocated storage before calling the routine again. NULL is returned in the event of an error. Find_Extension is a variant of Local_Alignment that simply finds a local alignment that either ends (if prefix is non-zero) or begins (if prefix is zero) at the point (anti+diag)/2,(anti-diag)/2). All other parameters are as before. It returns a non-zero value only when INTERACTIVE is on and it cannot allocate the memory it needs. Only the path and trace with respect to the aread is returned. This routine is experimental and may not persist in later versions of the code. */ Path *Local_Alignment(Alignment *align, Work_Data *work, Align_Spec *spec, int low, int hgh, int anti, int lbord, int hbord); int Find_Extension(Alignment *align, Work_Data *work, Align_Spec *spec, // experimental !! int diag, int anti, int lbord, int hbord, int prefix); /* Given a legitimate Alignment object and associated trace point vector in 'align->path.trace', Compute_Trace_X, computes an exact trace for the alignment and resets 'align->path.trace' to point at an integer array within the storage of the Work_Data packet encoding an exact optimal trace from the start to end points. If the trace is needed beyond the next call to a routine that sets it, then it should be copied to an array allocated and managed by the caller. Compute_Trace_PTS computes a trace by computing the trace between successive trace points. It is much, much faster than Compute_Alignment below but at the tradeoff of not necessarily being optimal as pass-through points are not all perfect. Compute_Trace_MID computes a trace by computing the trace between the mid-points of alignments between two adjacent pairs of trace points. It is generally twice as slow as Compute_Trace_PTS, but it produces nearer optimal alignments. Both these routines return 1 if an error occurred and 0 otherwise. */ #define LOWERMOST -1 // Possible modes for "mode" parameter below) #define GREEDIEST 0 #define UPPERMOST 1 int Compute_Trace_PTS(Alignment *align, Work_Data *work, int trace_spacing, int mode); int Compute_Trace_MID(Alignment *align, Work_Data *work, int trace_spacing, int mode); /* Compute_Trace_IRR (IRR for IRRegular) computes a trace for the given alignment where it assumes the spacing between trace points between both the A and B read varies, and futher assumes that the A-spacing is given in the short integers normally occupied by the differences in the alignment between the trace points. This routine is experimental and may not persist in later versions of the code. */ int Compute_Trace_IRR(Alignment *align, Work_Data *work, int mode); // experimental !! /* Compute Alignment determines the best alignment between the substrings specified by align. If the task is DIFF_ONLY, then only the difference of this alignment is computed and placed in the "diffs" field of align's path. If the task is PLUS_TRACE or DIFF_TRACE, then 'path.trace' is set to point at an integer array within the storage of the Work_Data packet encoding a trace point sequence for an optimal alignment, whereas if the task is PLUS_ALIGN or DIFF_ALIGN, then it points to an optimal trace of an optimatl alignment. The PLUS tasks can only be called if the immmediately proceeding call was a DIFF_ONLY on the same alignment record and sequences, in which case a little efficiency is gained by avoiding the repetition of the top level search for an optimal mid-point. */ #define PLUS_ALIGN 0 #define PLUS_TRACE 1 #define DIFF_ONLY 2 #define DIFF_ALIGN 3 #define DIFF_TRACE 4 int Compute_Alignment(Alignment *align, Work_Data *work, int task, int trace_spacing); /* Alignment_Cartoon prints an ASCII representation of the overlap relationhip between the two reads of 'align' to the given 'file' indented by 'indent' space. Coord controls the display width of numbers, it must be not less than the width of any number to be displayed. If the alignment trace is an exact trace, then one can ask Print_Alignment to print an ASCII representation of the alignment 'align' to the file 'file'. Indent the display by "indent" spaces and put "width" columns per line in the display. Show "border" characters of sequence on each side of the aligned region. If upper is non-zero then display bases in upper case. If coord is greater than 0, then the positions of the first character in A and B in the given row is displayed with a field width given by coord's value. Print_Reference is like Print_Alignment but rather than printing exaclty "width" columns per segment, it prints "block" characters of the A sequence in each segment. This results in segments of different lengths, but is convenient when looking at two alignments involving A as segments are guaranteed to cover the same interval of A in a segment. Both Print routines return 1 if an error occurred (not enough memory), and 0 otherwise. Flip_Alignment modifies align so the roles of A and B are reversed. If full is off then the trace is ignored, otherwise the trace must be to a full alignment trace and this trace is also appropriately inverted. */ void Alignment_Cartoon(FILE *file, Alignment *align, int indent, int coord); int Print_Alignment(FILE *file, Alignment *align, Work_Data *work, int indent, int width, int border, int upper, int coord); int Print_Reference(FILE *file, Alignment *align, Work_Data *work, int indent, int block, int border, int upper, int coord); void Flip_Alignment(Alignment *align, int full); /*** OVERLAP ABSTRACTION: Externally, between modules an Alignment is modeled by an "Overlap" record, which (a) replaces the pointers to the two sequences with their ID's in the HITS data bases, (b) does not contain the length of the 2 sequences (must fetch from DB), and (c) contains its path as a subrecord rather than as a pointer (indeed, typically the corresponding Alignment record points at the Overlap's path sub-record). The trace pointer is always to a sequence of trace points and can be either compressed (uint8) or uncompressed (uint16). One can read and write binary records of an "Overlap". ***/ typedef struct { Path path; /* Path: begin- and end-point of alignment + diffs */ uint32 flags; /* Pipeline status and complementation flags */ int aread; /* Id # of A sequence */ int bread; /* Id # of B sequence */ } Overlap; /* Read_Overlap reads the next Overlap record from stream 'input', not including the trace (if any), and without modifying 'ovl's trace pointer. Read_Trace reads the ensuing trace into the memory pointed at by the trace field of 'ovl'. It is assumed to be big enough to accommodate the trace where each value take 'tbytes' bytes (1 if uint8 or 2 if uint16). Write_Overlap write 'ovl' to stream 'output' followed by its trace vector (if any) that occupies 'tbytes' bytes per value. Print_Overlap prints an ASCII version of the contents of 'ovl' to stream 'output' where the trace occupes 'tbytes' per value and the print out is indented from the left margin by 'indent' spaces. Compress_TraceTo8 converts a trace fo 16-bit values to 8-bit values in place, and Decompress_TraceTo16 does the reverse conversion. Check_Trace_Points checks that the number of trace points is correct and that the sum of the b-read displacements equals the b-read alignment interval, assuming the trace spacing is 'tspace'. It reports an error message if there is a problem and 'verbose' is non-zero. The 'ovl' came from the file names 'fname'. */ int Read_Overlap(FILE *input, Overlap *ovl); int Read_Trace(FILE *innput, Overlap *ovl, int tbytes); int Write_Overlap(FILE *output, Overlap *ovl, int tbytes); void Print_Overlap(FILE *output, Overlap *ovl, int tbytes, int indent); int Compress_TraceTo8(Overlap *ovl, int check); void Decompress_TraceTo16(Overlap *ovl); int Check_Trace_Points(Overlap *ovl, int tspace, int verbose, char *fname); /* * BEGIN HEIDELBERG_ADDITION */ typedef struct { // trace buffer int tbytes; uint64 tmax; uint64 ttop; void *trace; int no_trace; // overlap buffer int omax; int otop; Overlap *ovls; } Overlap_IO_Buffer; Overlap_IO_Buffer *CreateOverlapBuffer(int nthreads, int tbytes, int no_trace); int AddOverlapToBuffer(Overlap_IO_Buffer *iobuf, Overlap *ovl, int tbytes); void Write_Overlap_Buffer(Align_Spec *spec, char *dirName1, char *dirName2, char *ablock, char *bblock, int lastRead); void Reset_Overlap_Buffer(Align_Spec* spec); Overlap_IO_Buffer *OVL_IO_Buffer(Align_Spec *espec); int Num_Threads(Align_Spec *espec); Overlap_IO_Buffer *OVL_IO_Buffer(Align_Spec *espec); int Only_Identity(Align_Spec *espec); int Symmetric(Align_Spec *espec); /* * END HEIDELBERG_ADDITION */ #endif // _A_MODULE
50.800915
154
0.689324
[ "object", "vector" ]
44596dcbca27f5b222a12f1ca9687c58a8a19fdd
1,393
h
C
TraceRay/foundation.h
leix28/TraceRay
fa99719ab5fefff6d9518535018885a9edea095f
[ "MIT" ]
2
2018-01-01T08:10:44.000Z
2018-03-12T03:29:08.000Z
TraceRay/foundation.h
leix28/TraceRay
fa99719ab5fefff6d9518535018885a9edea095f
[ "MIT" ]
null
null
null
TraceRay/foundation.h
leix28/TraceRay
fa99719ab5fefff6d9518535018885a9edea095f
[ "MIT" ]
1
2018-11-28T02:51:22.000Z
2018-11-28T02:51:22.000Z
// // foundation.h // TraceRay // // Created by LazyLie on 15/6/16. // Copyright (c) 2015年 LeonardXu. All rights reserved. // #ifndef __TraceRay__foundation__ #define __TraceRay__foundation__ #include <stdio.h> #include <assert.h> #include <math.h> #include <stdlib.h> #include <algorithm> #include <cstring> #include <string> #include <vector> #include <map> #include <set> using std::make_pair; using std::max; extern const double EPS; extern const double EPS_LOOSE; extern const double INFD; extern const int THREAD_NUM; extern const double PI; inline double sqr(double x) {return x * x; } class Vector { public: Vector(); Vector(double _x, double _y, double _z); double& operator [] (const int id); double operator [] (const int id) const; double x, y, z; }; double det(const Vector &a, const Vector &b, const Vector &c); double norm(const Vector &v); Vector operator - (const Vector &a); Vector operator + (const Vector &a, const Vector &b); Vector operator - (const Vector &a, const Vector &b); Vector operator * (const double a, const Vector &b); Vector operator * (const Vector &a, const double b); Vector operator * (const Vector &a, const Vector &b); Vector operator / (const Vector &a, const double b); double innerProduct(const Vector &a, const Vector &b); Vector crossProduct(const Vector &a, const Vector &b); #endif /* defined(__TraceRay__foundation__) */
24.875
62
0.715004
[ "vector" ]
6862b1070e2f38926d35926b130764f768dad001
9,826
h
C
src/include/PPU.h
Pricea810/nes_emu
1f1d91f15185d40e6c1e2ece60b5bdc3d2a465f1
[ "MIT" ]
8
2021-03-09T19:50:06.000Z
2021-06-28T12:03:43.000Z
src/include/PPU.h
Pricea810/nes_emu
1f1d91f15185d40e6c1e2ece60b5bdc3d2a465f1
[ "MIT" ]
8
2021-03-14T19:30:53.000Z
2021-05-04T00:49:28.000Z
src/include/PPU.h
Pricea810/nes_emu
1f1d91f15185d40e6c1e2ece60b5bdc3d2a465f1
[ "MIT" ]
2
2021-03-09T20:04:03.000Z
2021-04-22T04:13:35.000Z
#ifndef PPU_H #define PPU_H #include <cinttypes> #include <tuple> #include <vector> #include ".\SFML\Graphics.hpp" enum mirrorEnum : uint8_t; class CartridgeClass; class CPUClass; class GUIClass; struct Sprite { // see the following for why these are stored in this particular order: https://wiki.nesdev.com/w/index.php/PPU_memory_map // with this, we can efficiently memcpy from the OAMDMA into uint8_t y = 0; uint8_t index = 0; uint8_t attributes = 0; uint8_t x = 0; }; struct SpriteContainer { uint8_t id = 0; Sprite data; uint8_t dataH = 0; uint8_t dataL = 0; }; // Loopy's VRAM addressing union Address { struct { unsigned cX : 5; // Coarse X. unsigned cY : 5; // Coarse Y. unsigned nt : 2; // Nametable. unsigned fY : 3; // Fine Y. }; struct { unsigned l : 8; unsigned h : 7; }; unsigned addr : 14; unsigned r : 15; }; // flags for stating the bit ordering of registers enum CTRL_BITMASKS : uint8_t { NAMETABLE = 0b00000011, // 0 = 0x2000, 1 = 0x2400, 2 = 0x2800, 3 = 0x2C00 INCREMENT = 0b00000100, // VRAM increment per CPU read/write of PPUDATA: 0 = +1, 1 = +32 SPRITE = 0b00001000, // Sprite pattern table address, for 8x8 sprites(ignored in 8x16 mode): 0 = 0x0000, 1 = 0x1000 BACKGROUND = 0b00010000, // Background pattern table address: 0 = 0x0000, 1 = 0x1000 S_HEIGHT = 0b00100000, // Sprite size: 0 = 8x8, 1 = 8x16 MASTER = 0b01000000, // PPU Master/Slave selection: 0 = read backdrop from EXT, 1 = write backdrop to EXT NMI = 0b10000000 // Generate NMI at start of vertical blanking: 0 = false, 1 = true }; enum MASK_BITMASKS : uint8_t { GREYSCALE = 0b00000001, BG_LEFT_COL = 0b00000010, S_LEFT_COL = 0b00000100, BG_ENABLE = 0b00001000, S_ENABLE = 0b00010000, COLOR_EMPH = 0b11100000 }; enum STAT_BITMASKS : uint8_t { UNUSED = 0b00011111, S_OVERFLOW = 0b00100000, S_0_HIT = 0b01000000, VBLANK = 0b10000000 }; enum SCANLINE_TYPES : uint8_t { // in order to properly handle what happens when in the scanlines, please follow this: https://wiki.nesdev.com/w/images/d/d1/Ntsc_timing.png // scanline timings are given in terms of NTSC, NOT PAL PRE = 0b00000001, // (-1/261) this is what happens before the visible frame is started, it is only 1 scanline: https://wiki.nesdev.com/w/index.php/PPU_rendering#Pre-render_scanline_.28-1_or_261.29 FRAME = 0b00000010, // (0-239) this is the frame that is draw to the window: https://wiki.nesdev.com/w/index.php/PPU_rendering#Visible_scanlines_.280-239.29 POST = 0b00000100, // (240) this is the scanline after the visible frame is handled: https://wiki.nesdev.com/w/index.php/PPU_rendering#Post-render_scanline_.28240.29 BLANK = 0b00001000 // (240-260) this is the vertical blanking that happens after the post scanline: https://wiki.nesdev.com/w/index.php/PPU_rendering#Post-render_scanline_.28240.29 }; #pragma pack(1) struct PPU_Registers { // see following for explaination of PPU registers: https://wiki.nesdev.com/w/index.php/PPU_registers uint8_t CTRL = 0; // $2000 uint8_t MASK = 0; // $2001 uint8_t STAT = 0; // $2002 uint8_t OAMADDR = 0; // $2003 //uint8_t OAMDATA = 0; // $2004 // this register is effectively useless, we can address the OAM memory directly instead //uint8_t SCROLL = 0; // $2005 // this register is effectively useless, because we can use Loopy's //uint8_t ADDR = 0; // $2006 // this register is effectively useless, because we can use Loopy's //uint8_t DATA = 0; // $2007 // this register is effectively useless, because we can just store the data immediately instead //uint8_t OAMDMA = 0; // $4014 // also effectively useless, it only matters if the CPU writes to the address of $4014, not what it writes }; #pragma pack() class PPUClass { public: PPUClass(); ~PPUClass() { } // Shorthand notations used // BG == Background // AT == Attributes // NT == Nametables // L == Low (Low order byte) // H == High (High order byte) // used to access PPU registers void write(uint16_t addr, uint8_t& data); uint8_t read(uint16_t addr); // used to store components needed to communicate with void loadCartridge(CartridgeClass* _cartridge) { this->cartridge = _cartridge; } void loadCPU(CPUClass* _CPU) { this->CPU = _CPU; } void loadGUI(GUIClass* _GUI) { this->GUI = _GUI; } // we only need the GUIClass to give SDL2 the new frame to draw std::tuple<uint32_t, uint32_t> getResolution(); uint32_t getTVFrameRate(); void reset(); void cycle(); void* get_ppu_regs() { return (void*)&this->registers; } size_t get_ppu_regs_size() { return sizeof(this->registers); } void* get_ppu_nametables() { return (void*)&this->nametables.at(0); } size_t get_ppu_nametables_size() { return this->nametables.size(); } void* get_ppu_palettes() { return (void*)&this->palettes.at(0); } size_t get_ppu_palettes_size() { return this->palettes.size(); } void* get_ppu_oam() { return (void*)(&this->OAM); } size_t get_ppu_oam_size() { return 0x0100; } void* get_ppu_primary_oam() { return (void*)(&this->primaryOAM); } void* get_ppu_secondary_oam() { return (void*)(&this->secondaryOAM); } size_t get_ppu_oam_reg_size() { return (sizeof(SpriteContainer) * 8); } // function pointers for GUI access to CPU data typedef void* (PPUClass::* getPPUData)(void); typedef size_t(PPUClass::* getPPUDataSize)(void); typedef void* (PPUClass::* getPPUData)(void); typedef size_t(PPUClass::* getPPUDataSize)(void); protected: // registers within the PPU PPU_Registers registers; // this is used for drawing to the screen, every time a ROM is loaded, we must change the size of this sf::Image pixels; // used to determine what scanline we are currently on int16_t scanline = -1; int16_t scanlinePixel = 0; // The pixel within the scanline // Nametable storage std::vector<uint8_t> nametables; // the actual palette storage for the PPU std::vector<uint8_t> palettes; // this follows directly with RGBA32(NOT ARGB32) which SFML uses uint32_t paletteColors[64] = { 0x666666FF, 0x002A88FF, 0x1412A7FF, 0x3B00A4FF, 0x5C007EFF, 0x6E0040FF, 0x6C0600FF, 0x561D00FF, 0x333500FF, 0x0B4800FF, 0x005200FF, 0x004F08FF, 0x00404DFF, 0x000000FF, 0x000000FF, 0x000000FF, 0xADADADFF, 0x155FD9FF, 0x4240FFFF, 0x7527FEFF, 0xA01ACCFF, 0xB71E7BFF, 0xB53120FF, 0x994E00FF, 0x6b6d00FF, 0x388700FF, 0x0c9300FF, 0x008F32FF, 0x007C8DFF, 0x000000FF, 0x000000FF, 0x000000FF, 0xFFFEFFFF, 0x64B0FFFF, 0x9290FFFF, 0xC676FFFF, 0xF36AFFFF, 0xFE6ECCFF, 0xFE8170FF, 0xEA9E22FF, 0xBCBE00FF, 0x88D800FF, 0x5CE430FF, 0x45E082FF, 0x48CDDEFF, 0x4F4F4FFF, 0x000000FF, 0x000000FF, 0xFFFEFFFF, 0xC0DFFFFF, 0xd3D2FFFF, 0xE8C8FFFF, 0xFBC2FFFF, 0xFEC4EAFF, 0xFECCC5FF, 0xF7D8A5FF, 0xE4E594FF, 0xCFEF96FF, 0xBDf4ABFF, 0xB3F3CCFF, 0xB5EBF2FF, 0xB8B8B8FF, 0x000000FF, 0x000000FF }; // for OAM data, please see: https://wiki.nesdev.com/w/index.php/PPU_OAM#Internal_operation // in short, the secondary is filled by the OAM, which in turn initializes 8 internal sprite outputs std::vector<uint8_t> OAM; SpriteContainer primaryOAM[8]; SpriteContainer secondaryOAM[8]; // Loopy's V and T addresses Address vAddr, tAddr; // latches uint8_t NT = 0, AT = 0, BGL = 0, BGH = 0; bool ATLatchL = false, ATLatchH = false; // shift registers uint16_t atShiftL = 0, atShiftH = 0, bgShiftL = 0, bgShiftH = 0; // latch for determining if has been an register access already bool latch = false; // return value for read() uint8_t result = 0; // Loopy's fineX uint8_t fineX = 0; bool isOddFrame = false; // we need to store the cartridge for CHR reading CartridgeClass* cartridge = nullptr; CPUClass* CPU = nullptr; GUIClass* GUI = nullptr; // store the resolution of the image displayed(NTSC, PAL) uint32_t tvResolutionX[2] = { 256, 256 }; uint32_t tvResolutionY[2] = { 240, 288 }; uint32_t tvFrameRate[2] = { 60, 50 }; // it does 1/2 frames at Xfps, but full frame is X/2fps // used to access Cartridge or RAM uint8_t access(uint16_t addr, uint8_t data = 0, bool isWrite = false); // Scanlines void pre_scanline(); // scanline -1 void frame_scanline(); // scanline 0 through 239 void post_scanline(); // scanline 240 void blank_scanline(); // scanline 241 through 260 bool rendering() { return ((this->registers.MASK & MASK_BITMASKS::BG_ENABLE) || (this->registers.MASK & MASK_BITMASKS::S_ENABLE)); } uint32_t sprite_height() { return (this->registers.CTRL & CTRL_BITMASKS::S_HEIGHT) ? 16 : 8; } // Nametable uint16_t addressNT() { return (0x2000 | (this->vAddr.r & 0x0FFF)); } // Attributes uint16_t addressAT() { return (0x23C0 | (this->vAddr.nt << 10) | ((this->vAddr.cY / 4) << 3) | (this->vAddr.cX / 4)); } // Background // Only the value of the Background bit in the control register matters. // Bitshift right by 4 because it is the 4th bit in the control register. // Without the bitshift, it will multiply by 0x10000 instead of 0x1000 uint16_t addressBG() { return ((((this->registers.CTRL & CTRL_BITMASKS::BACKGROUND) >> 4) * 0x1000) + (this->NT * 16) + this->vAddr.fY); } // Scrolls void horizontal_scroll(); void vertical_scroll(); // Updates - Copies data from Loopy T to Loopy V void horizontal_update() { if (!this->rendering()) return; this->vAddr.r = ((this->vAddr.r & ~0x041F) | (this->tAddr.r & 0x041F)); } void vertical_update() { if (!this->rendering()) return; this->vAddr.r = ((this->vAddr.r & ~0x7BE0) | (this->tAddr.r & 0x7BE0)); } void reload_shift(); void clear_oam(); void evaluate_sprites(); void load_sprites(); void pixelDraw(); uint16_t addressMirrorAdjust(uint16_t addr); // Change Register Values void SetRegisterBits(uint8_t &ppuRegister, uint8_t ppuBitmask); void ClearRegisterBits(uint8_t &ppuRegister, uint8_t ppuBitmask); void ResetRegister(uint8_t& ppuRegister); }; #endif
34.843972
199
0.711785
[ "vector" ]
68642d1798dcbb15b7d0806eb73d5f9e99d66ac8
60,674
c
C
vnet/vnet/ethernet/arp.c
muharif/vpp
74436ed67d8cfa1f5cf18563b6060e298bfd64b9
[ "Apache-2.0" ]
null
null
null
vnet/vnet/ethernet/arp.c
muharif/vpp
74436ed67d8cfa1f5cf18563b6060e298bfd64b9
[ "Apache-2.0" ]
null
null
null
vnet/vnet/ethernet/arp.c
muharif/vpp
74436ed67d8cfa1f5cf18563b6060e298bfd64b9
[ "Apache-2.0" ]
null
null
null
/* * ethernet/arp.c: IP v4 ARP node * * Copyright (c) 2010 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <vnet/ip/ip.h> #include <vnet/ethernet/ethernet.h> #include <vnet/ethernet/arp_packet.h> #include <vnet/l2/l2_input.h> #include <vppinfra/mhash.h> void vl_api_rpc_call_main_thread (void *fp, u8 * data, u32 data_length); typedef struct { u32 sw_if_index; u32 fib_index; ip4_address_t ip4_address; } ethernet_arp_ip4_key_t; typedef struct { ethernet_arp_ip4_key_t key; u8 ethernet_address[6]; u16 flags; #define ETHERNET_ARP_IP4_ENTRY_FLAG_STATIC (1 << 0) #define ETHERNET_ARP_IP4_ENTRY_FLAG_GLEAN (2 << 0) u64 cpu_time_last_updated; u32 * adjacencies; } ethernet_arp_ip4_entry_t; typedef struct { u32 lo_addr; u32 hi_addr; u32 fib_index; } ethernet_proxy_arp_t; typedef struct { u32 next_index; uword node_index; uword type_opaque; uword data; /* Used for arp event notification only */ void * data_callback; u32 pid; } pending_resolution_t; typedef struct { /* Hash tables mapping name to opcode. */ uword * opcode_by_name; /* lite beer "glean" adjacency handling */ uword * pending_resolutions_by_address; pending_resolution_t * pending_resolutions; /* Mac address change notification */ uword * mac_changes_by_address; pending_resolution_t * mac_changes; ethernet_arp_ip4_entry_t * ip4_entry_pool; mhash_t ip4_entry_by_key; /* ARP attack mitigation */ u32 arp_delete_rotor; u32 limit_arp_cache_size; /* Proxy arp vector */ ethernet_proxy_arp_t * proxy_arps; } ethernet_arp_main_t; static ethernet_arp_main_t ethernet_arp_main; static u8 * format_ethernet_arp_hardware_type (u8 * s, va_list * va) { ethernet_arp_hardware_type_t h = va_arg (*va, ethernet_arp_hardware_type_t); char * t = 0; switch (h) { #define _(n,f) case n: t = #f; break; foreach_ethernet_arp_hardware_type; #undef _ default: return format (s, "unknown 0x%x", h); } return format (s, "%s", t); } static u8 * format_ethernet_arp_opcode (u8 * s, va_list * va) { ethernet_arp_opcode_t o = va_arg (*va, ethernet_arp_opcode_t); char * t = 0; switch (o) { #define _(f) case ETHERNET_ARP_OPCODE_##f: t = #f; break; foreach_ethernet_arp_opcode; #undef _ default: return format (s, "unknown 0x%x", o); } return format (s, "%s", t); } static uword unformat_ethernet_arp_opcode_host_byte_order (unformat_input_t * input, va_list * args) { int * result = va_arg (*args, int *); ethernet_arp_main_t * am = &ethernet_arp_main; int x, i; /* Numeric opcode. */ if (unformat (input, "0x%x", &x) || unformat (input, "%d", &x)) { if (x >= (1 << 16)) return 0; *result = x; return 1; } /* Named type. */ if (unformat_user (input, unformat_vlib_number_by_name, am->opcode_by_name, &i)) { *result = i; return 1; } return 0; } static uword unformat_ethernet_arp_opcode_net_byte_order (unformat_input_t * input, va_list * args) { int * result = va_arg (*args, int *); if (! unformat_user (input, unformat_ethernet_arp_opcode_host_byte_order, result)) return 0; *result = clib_host_to_net_u16 ((u16) *result); return 1; } static u8 * format_ethernet_arp_header (u8 * s, va_list * va) { ethernet_arp_header_t * a = va_arg (*va, ethernet_arp_header_t *); u32 max_header_bytes = va_arg (*va, u32); uword indent; u16 l2_type, l3_type; if (max_header_bytes != 0 && sizeof (a[0]) > max_header_bytes) return format (s, "ARP header truncated"); l2_type = clib_net_to_host_u16 (a->l2_type); l3_type = clib_net_to_host_u16 (a->l3_type); indent = format_get_indent (s); s = format (s, "%U, type %U/%U, address size %d/%d", format_ethernet_arp_opcode, clib_net_to_host_u16 (a->opcode), format_ethernet_arp_hardware_type, l2_type, format_ethernet_type, l3_type, a->n_l2_address_bytes, a->n_l3_address_bytes); if (l2_type == ETHERNET_ARP_HARDWARE_TYPE_ethernet && l3_type == ETHERNET_TYPE_IP4) { s = format (s, "\n%U%U/%U -> %U/%U", format_white_space, indent, format_ethernet_address, a->ip4_over_ethernet[0].ethernet, format_ip4_address, &a->ip4_over_ethernet[0].ip4, format_ethernet_address, a->ip4_over_ethernet[1].ethernet, format_ip4_address, &a->ip4_over_ethernet[1].ip4); } else { uword n2 = a->n_l2_address_bytes; uword n3 = a->n_l3_address_bytes; s = format (s, "\n%U%U/%U -> %U/%U", format_white_space, indent, format_hex_bytes, a->data + 0*n2 + 0*n3, n2, format_hex_bytes, a->data + 1*n2 + 0*n3, n3, format_hex_bytes, a->data + 1*n2 + 1*n3, n2, format_hex_bytes, a->data + 2*n2 + 1*n3, n3); } return s; } static u8 * format_ethernet_arp_ip4_entry (u8 * s, va_list * va) { vnet_main_t * vnm = va_arg (*va, vnet_main_t *); ethernet_arp_ip4_entry_t * e = va_arg (*va, ethernet_arp_ip4_entry_t *); vnet_sw_interface_t * si; ip4_fib_t * fib; u8 * flags = 0; if (! e) return format (s, "%=12s%=6s%=16s%=6s%=20s%=24s", "Time", "FIB", "IP4", "Flags", "Ethernet", "Interface"); fib = find_ip4_fib_by_table_index_or_id (&ip4_main, e->key.fib_index, IP4_ROUTE_FLAG_FIB_INDEX); si = vnet_get_sw_interface (vnm, e->key.sw_if_index); if (e->flags & ETHERNET_ARP_IP4_ENTRY_FLAG_GLEAN) flags = format(flags, "G"); if (e->flags & ETHERNET_ARP_IP4_ENTRY_FLAG_STATIC) flags = format(flags, "S"); s = format (s, "%=12U%=6u%=16U%=6s%=20U%=24U", format_vlib_cpu_time, vnm->vlib_main, e->cpu_time_last_updated, fib->table_id, format_ip4_address, &e->key.ip4_address, flags ? (char *) flags : "", format_ethernet_address, e->ethernet_address, format_vnet_sw_interface_name, vnm, si); vec_free(flags); return s; } typedef struct { u8 packet_data[64]; } ethernet_arp_input_trace_t; static u8 * format_ethernet_arp_input_trace (u8 * s, va_list * va) { CLIB_UNUSED (vlib_main_t * vm) = va_arg (*va, vlib_main_t *); CLIB_UNUSED (vlib_node_t * node) = va_arg (*va, vlib_node_t *); ethernet_arp_input_trace_t * t = va_arg (*va, ethernet_arp_input_trace_t *); s = format (s, "%U", format_ethernet_arp_header, t->packet_data, sizeof (t->packet_data)); return s; } clib_error_t * ethernet_arp_sw_interface_up_down (vnet_main_t * vnm, u32 sw_if_index, u32 flags) { ethernet_arp_main_t * am = &ethernet_arp_main; ethernet_arp_ip4_entry_t * e; u32 i; u32 * to_add_del = 0; pool_foreach (e, am->ip4_entry_pool, ({ if (e->key.sw_if_index == sw_if_index) vec_add1 (to_add_del, e - am->ip4_entry_pool); })); for (i = 0; i < vec_len (to_add_del); i++) { ethernet_arp_ip4_over_ethernet_address_t arp_add; e = pool_elt_at_index (am->ip4_entry_pool, to_add_del[i]); clib_memcpy (&arp_add.ethernet, e->ethernet_address, 6); arp_add.ip4.as_u32 = e->key.ip4_address.as_u32; if (flags & VNET_SW_INTERFACE_FLAG_ADMIN_UP) { vnet_arp_set_ip4_over_ethernet (vnm, e->key.sw_if_index, e->key.fib_index, &arp_add, e->flags & ETHERNET_ARP_IP4_ENTRY_FLAG_STATIC); } else if ((e->flags & ETHERNET_ARP_IP4_ENTRY_FLAG_STATIC) == 0) { vnet_arp_unset_ip4_over_ethernet (vnm, e->key.sw_if_index, e->key.fib_index, &arp_add); } } vec_free (to_add_del); return 0; } VNET_SW_INTERFACE_ADMIN_UP_DOWN_FUNCTION (ethernet_arp_sw_interface_up_down); static int vnet_arp_set_ip4_over_ethernet_internal (vnet_main_t * vnm, u32 sw_if_index, u32 fib_index, void * a_arg, int is_static); static int vnet_arp_unset_ip4_over_ethernet_internal (vnet_main_t * vnm, u32 sw_if_index, u32 fib_index, void * a_arg); typedef struct { u32 sw_if_index; u32 fib_index; ethernet_arp_ip4_over_ethernet_address_t a; int is_static; int is_remove; /* set is_remove=1 to clear arp entry */ } vnet_arp_set_ip4_over_ethernet_rpc_args_t; static void set_ip4_over_ethernet_rpc_callback ( vnet_arp_set_ip4_over_ethernet_rpc_args_t * a) { vnet_main_t * vm = vnet_get_main(); ASSERT(os_get_cpu_number() == 0); if (a->is_remove) vnet_arp_unset_ip4_over_ethernet_internal(vm, a->sw_if_index, a->fib_index, &(a->a)); else vnet_arp_set_ip4_over_ethernet_internal (vm, a->sw_if_index, a->fib_index, &(a->a), a->is_static); } int vnet_arp_set_ip4_over_ethernet (vnet_main_t * vnm, u32 sw_if_index, u32 fib_index, void * a_arg, int is_static) { ethernet_arp_ip4_over_ethernet_address_t * a = a_arg; vnet_arp_set_ip4_over_ethernet_rpc_args_t args; args.sw_if_index = sw_if_index; args.fib_index = fib_index; args.is_static = is_static; args.is_remove = 0; clib_memcpy (&args.a, a, sizeof (*a)); vl_api_rpc_call_main_thread (set_ip4_over_ethernet_rpc_callback, (u8 *) &args, sizeof (args)); return 0; } int vnet_arp_set_ip4_over_ethernet_internal (vnet_main_t * vnm, u32 sw_if_index, u32 fib_index, void * a_arg, int is_static) { ethernet_arp_ip4_key_t k; ethernet_arp_ip4_entry_t * e = 0; ethernet_arp_main_t * am = &ethernet_arp_main; ethernet_arp_ip4_over_ethernet_address_t * a = a_arg; vlib_main_t * vm = vlib_get_main(); ip4_main_t * im = &ip4_main; ip_lookup_main_t * lm = &im->lookup_main; int make_new_arp_cache_entry=1; uword * p; ip4_add_del_route_args_t args; ip_adjacency_t adj, * existing_adj; pending_resolution_t * pr, * mc; u32 next_index; u32 adj_index; fib_index = (fib_index != (u32)~0) ? fib_index : im->fib_index_by_sw_if_index[sw_if_index]; k.sw_if_index = sw_if_index; k.ip4_address = a->ip4; k.fib_index = fib_index; p = mhash_get (&am->ip4_entry_by_key, &k); if (p) { e = pool_elt_at_index (am->ip4_entry_pool, p[0]); /* Refuse to over-write static arp. */ if (!is_static && (e->flags & ETHERNET_ARP_IP4_ENTRY_FLAG_STATIC)) return -2; make_new_arp_cache_entry = 0; } /* Note: always install the route. It might have been deleted */ memset(&adj, 0, sizeof(adj)); adj.lookup_next_index = IP_LOOKUP_NEXT_REWRITE; adj.n_adj = 1; /* otherwise signature compare fails */ vnet_rewrite_for_sw_interface (vnm, VNET_L3_PACKET_TYPE_IP4, sw_if_index, ip4_rewrite_node.index, a->ethernet, /* destination address */ &adj.rewrite_header, sizeof (adj.rewrite_data)); /* result of this lookup should be next-hop adjacency */ adj_index = ip4_fib_lookup_with_table (im, fib_index, &a->ip4, 0); existing_adj = ip_get_adjacency(lm, adj_index); if (existing_adj->lookup_next_index == IP_LOOKUP_NEXT_ARP && existing_adj->arp.next_hop.ip4.as_u32 == a->ip4.as_u32) { u32 * ai; u32 * adjs = vec_dup(e->adjacencies); /* Update all adj assigned to this arp entry */ vec_foreach(ai, adjs) { int i; ip_adjacency_t * uadj = ip_get_adjacency(lm, *ai); for (i = 0; i < uadj->n_adj; i++) if (uadj[i].lookup_next_index == IP_LOOKUP_NEXT_ARP && uadj[i].arp.next_hop.ip4.as_u32 == a->ip4.as_u32) ip_update_adjacency (lm, *ai + i, &adj); } vec_free(adjs); } else { /* Check that new adjacency actually isn't exactly the same as * what is already there. If we over-write the adjacency with * exactly the same info, its technically a new adjacency with * new counters, but to user it appears as counters reset. */ if (vnet_ip_adjacency_share_compare (&adj, existing_adj) == 0) { /* create new adj */ args.table_index_or_table_id = fib_index; args.flags = IP4_ROUTE_FLAG_FIB_INDEX | IP4_ROUTE_FLAG_ADD | IP4_ROUTE_FLAG_NEIGHBOR; args.dst_address = a->ip4; args.dst_address_length = 32; args.adj_index = ~0; args.add_adj = &adj; args.n_add_adj = 1; ip4_add_del_route (im, &args); } } if (make_new_arp_cache_entry) { pool_get (am->ip4_entry_pool, e); mhash_set (&am->ip4_entry_by_key, &k, e - am->ip4_entry_pool, /* old value */ 0); e->key = k; } /* Update time stamp and ethernet address. */ clib_memcpy (e->ethernet_address, a->ethernet, sizeof (e->ethernet_address)); e->cpu_time_last_updated = clib_cpu_time_now (); if (is_static) e->flags |= ETHERNET_ARP_IP4_ENTRY_FLAG_STATIC; /* Customer(s) waiting for this address to be resolved? */ p = hash_get (am->pending_resolutions_by_address, a->ip4.as_u32); if (p) { next_index = p[0]; while (next_index != (u32)~0) { pr = pool_elt_at_index (am->pending_resolutions, next_index); vlib_process_signal_event (vm, pr->node_index, pr->type_opaque, pr->data); next_index = pr->next_index; pool_put (am->pending_resolutions, pr); } hash_unset (am->pending_resolutions_by_address, a->ip4.as_u32); } /* Customer(s) requesting ARP event for this address? */ p = hash_get (am->mac_changes_by_address, a->ip4.as_u32); if (p) { next_index = p[0]; while (next_index != (u32)~0) { int (*fp)(u32, u8 *, u32, u32); int rv = 1; mc = pool_elt_at_index (am->mac_changes, next_index); fp = mc->data_callback; /* Call the user's data callback, return 1 to suppress dup events */ if (fp) rv = (*fp)(mc->data, a->ethernet, sw_if_index, 0); /* * Signal the resolver process, as long as the user * says they want to be notified */ if (rv == 0) vlib_process_signal_event (vm, mc->node_index, mc->type_opaque, mc->data); next_index = mc->next_index; } } return 0; } void vnet_register_ip4_arp_resolution_event (vnet_main_t * vnm, void * address_arg, uword node_index, uword type_opaque, uword data) { ethernet_arp_main_t * am = &ethernet_arp_main; ip4_address_t * address = address_arg; uword * p; pending_resolution_t * pr; pool_get (am->pending_resolutions, pr); pr->next_index = ~0; pr->node_index = node_index; pr->type_opaque = type_opaque; pr->data = data; pr->data_callback = 0; p = hash_get (am->pending_resolutions_by_address, address->as_u32); if (p) { /* Insert new resolution at the head of the list */ pr->next_index = p[0]; hash_unset (am->pending_resolutions_by_address, address->as_u32); } hash_set (am->pending_resolutions_by_address, address->as_u32, pr - am->pending_resolutions); } int vnet_add_del_ip4_arp_change_event (vnet_main_t * vnm, void * data_callback, u32 pid, void * address_arg, uword node_index, uword type_opaque, uword data, int is_add) { ethernet_arp_main_t * am = &ethernet_arp_main; ip4_address_t * address = address_arg; uword * p; pending_resolution_t * mc; void (*fp)(u32, u8 *) = data_callback; if (is_add) { pool_get (am->mac_changes, mc); mc->next_index = ~0; mc->node_index = node_index; mc->type_opaque = type_opaque; mc->data = data; mc->data_callback = data_callback; mc->pid = pid; p = hash_get (am->mac_changes_by_address, address->as_u32); if (p) { /* Insert new resolution at the head of the list */ mc->next_index = p[0]; hash_unset (am->mac_changes_by_address, address->as_u32); } hash_set (am->mac_changes_by_address, address->as_u32, mc - am->mac_changes); return 0; } else { u32 index; pending_resolution_t * mc_last = 0; p = hash_get (am->mac_changes_by_address, address->as_u32); if (p == 0) return VNET_API_ERROR_NO_SUCH_ENTRY; index = p[0]; while (index != (u32)~0) { mc = pool_elt_at_index (am->mac_changes, index); if (mc->node_index == node_index && mc->type_opaque == type_opaque && mc->pid == pid) { /* Clients may need to clean up pool entries, too */ if (fp) (*fp)(mc->data, 0 /* no new mac addrs */); if (index == p[0]) { hash_unset (am->mac_changes_by_address, address->as_u32); if (mc->next_index != ~0) hash_set (am->mac_changes_by_address, address->as_u32, mc->next_index); pool_put (am->mac_changes, mc); return 0; } else { ASSERT(mc_last); mc_last->next_index = mc->next_index; pool_put (am->mac_changes, mc); return 0; } } mc_last = mc; index = mc->next_index; } return VNET_API_ERROR_NO_SUCH_ENTRY; } } /* Either we drop the packet or we send a reply to the sender. */ typedef enum { ARP_INPUT_NEXT_DROP, ARP_INPUT_NEXT_REPLY_TX, ARP_INPUT_N_NEXT, } arp_input_next_t; #define foreach_ethernet_arp_error \ _ (replies_sent, "ARP replies sent") \ _ (l2_type_not_ethernet, "L2 type not ethernet") \ _ (l3_type_not_ip4, "L3 type not IP4") \ _ (l3_src_address_not_local, "IP4 source address not local to subnet") \ _ (l3_dst_address_not_local, "IP4 destination address not local to subnet") \ _ (l3_src_address_is_local, "IP4 source address matches local interface") \ _ (l3_src_address_learned, "ARP request IP4 source address learned") \ _ (replies_received, "ARP replies received") \ _ (opcode_not_request, "ARP opcode not request") \ _ (proxy_arp_replies_sent, "Proxy ARP replies sent") \ _ (l2_address_mismatch, "ARP hw addr does not match L2 frame src addr") \ _ (missing_interface_address, "ARP missing interface address") \ _ (gratuitous_arp, "ARP probe or announcement dropped") \ typedef enum { #define _(sym,string) ETHERNET_ARP_ERROR_##sym, foreach_ethernet_arp_error #undef _ ETHERNET_ARP_N_ERROR, } ethernet_arp_input_error_t; /* get first interface address */ ip4_address_t * ip4_interface_first_address (ip4_main_t * im, u32 sw_if_index, ip_interface_address_t ** result_ia) { ip_lookup_main_t * lm = &im->lookup_main; ip_interface_address_t * ia = 0; ip4_address_t * result = 0; foreach_ip_interface_address (lm, ia, sw_if_index, 1 /* honor unnumbered */, ({ ip4_address_t * a = ip_interface_address_get_address (lm, ia); result = a; break; })); if (result_ia) *result_ia = result ? ia : 0; return result; } static void unset_random_arp_entry (void) { ethernet_arp_main_t * am = &ethernet_arp_main; ethernet_arp_ip4_entry_t * e; vnet_main_t * vnm = vnet_get_main(); ethernet_arp_ip4_over_ethernet_address_t delme; u32 index; index = pool_next_index (am->ip4_entry_pool, am->arp_delete_rotor); am->arp_delete_rotor = index; /* Try again from elt 0, could happen if an intfc goes down */ if (index == ~0) { index = pool_next_index (am->ip4_entry_pool, am->arp_delete_rotor); am->arp_delete_rotor = index; } /* Nothing left in the pool */ if (index == ~0) return; e = pool_elt_at_index (am->ip4_entry_pool, index); clib_memcpy (&delme.ethernet, e->ethernet_address, 6); delme.ip4.as_u32 = e->key.ip4_address.as_u32; vnet_arp_unset_ip4_over_ethernet (vnm, e->key.sw_if_index, e->key.fib_index, &delme); } static void arp_unnumbered (vlib_buffer_t * p0, u32 pi0, ethernet_header_t * eth0, ip_interface_address_t * ifa0) { vlib_main_t * vm = vlib_get_main(); vnet_main_t * vnm = vnet_get_main(); vnet_interface_main_t * vim = &vnm->interface_main; vnet_sw_interface_t * si; vnet_hw_interface_t * hi; u32 unnum_src_sw_if_index; u32 * broadcast_swifs = 0; u32 * buffers = 0; u32 n_alloc = 0; vlib_buffer_t * b0; int i; u8 dst_mac_address[6]; i16 header_size; ethernet_arp_header_t * arp0; /* Save the dst mac address */ clib_memcpy(dst_mac_address, eth0->dst_address, sizeof (dst_mac_address)); /* Figure out which sw_if_index supplied the address */ unnum_src_sw_if_index = ifa0->sw_if_index; /* Track down all users of the unnumbered source */ pool_foreach (si, vim->sw_interfaces, ({ if (si->flags & VNET_SW_INTERFACE_FLAG_UNNUMBERED && (si->unnumbered_sw_if_index == unnum_src_sw_if_index)) { vec_add1 (broadcast_swifs, si->sw_if_index); } })); ASSERT (vec_len(broadcast_swifs)); /* Allocate buffering if we need it */ if (vec_len(broadcast_swifs) > 1) { vec_validate (buffers, vec_len(broadcast_swifs)-2); n_alloc = vlib_buffer_alloc (vm, buffers, vec_len(buffers)); _vec_len (buffers) = n_alloc; for (i = 0; i < n_alloc; i++) { b0 = vlib_get_buffer (vm, buffers[i]); /* xerox (partially built) ARP pkt */ clib_memcpy (b0->data, p0->data, p0->current_length + p0->current_data); b0->current_data = p0->current_data; b0->current_length = p0->current_length; vnet_buffer(b0)->sw_if_index[VLIB_RX] = vnet_buffer(p0)->sw_if_index[VLIB_RX]; } } vec_insert (buffers, 1, 0); buffers[0] = pi0; for (i = 0; i < vec_len(buffers); i++) { b0 = vlib_get_buffer(vm, buffers[i]); arp0 = vlib_buffer_get_current (b0); hi = vnet_get_sup_hw_interface (vnm, broadcast_swifs[i]); si = vnet_get_sw_interface (vnm, broadcast_swifs[i]); /* For decoration, most likely */ vnet_buffer(b0)->sw_if_index[VLIB_TX] = hi->sw_if_index; /* Fix ARP pkt src address */ clib_memcpy (arp0->ip4_over_ethernet[0].ethernet, hi->hw_address, 6); /* Build L2 encaps for this swif */ header_size = sizeof (ethernet_header_t); if (si->sub.eth.flags.one_tag) header_size += 4; else if (si->sub.eth.flags.two_tags) header_size += 8; vlib_buffer_advance (b0, -header_size); eth0 = vlib_buffer_get_current (b0); if (si->sub.eth.flags.one_tag) { ethernet_vlan_header_t * outer = (void *) (eth0 + 1); eth0->type = si->sub.eth.flags.dot1ad ? clib_host_to_net_u16 (ETHERNET_TYPE_DOT1AD) : clib_host_to_net_u16 (ETHERNET_TYPE_VLAN); outer->priority_cfi_and_id = clib_host_to_net_u16 (si->sub.eth.outer_vlan_id); outer->type = clib_host_to_net_u16 (ETHERNET_TYPE_ARP); } else if (si->sub.eth.flags.two_tags) { ethernet_vlan_header_t * outer = (void *) (eth0 + 1); ethernet_vlan_header_t * inner = (void *) (outer + 1); eth0->type = si->sub.eth.flags.dot1ad ? clib_host_to_net_u16 (ETHERNET_TYPE_DOT1AD) : clib_host_to_net_u16 (ETHERNET_TYPE_VLAN); outer->priority_cfi_and_id = clib_host_to_net_u16 (si->sub.eth.outer_vlan_id); outer->type = clib_host_to_net_u16 (ETHERNET_TYPE_VLAN); inner->priority_cfi_and_id = clib_host_to_net_u16 (si->sub.eth.inner_vlan_id); inner->type = clib_host_to_net_u16 (ETHERNET_TYPE_ARP); } else { eth0->type = clib_host_to_net_u16 (ETHERNET_TYPE_ARP); } /* Restore the original dst address, set src address */ clib_memcpy (eth0->dst_address, dst_mac_address, sizeof (eth0->dst_address)); clib_memcpy (eth0->src_address, hi->hw_address, sizeof (eth0->src_address)); /* Transmit replicas */ if (i > 0) { vlib_frame_t * f = vlib_get_frame_to_node (vm, hi->output_node_index); u32 * to_next = vlib_frame_vector_args (f); to_next[0] = buffers[i]; f->n_vectors = 1; vlib_put_frame_to_node (vm, hi->output_node_index, f); } } /* The regular path outputs the original pkt.. */ vnet_buffer (p0)->sw_if_index[VLIB_TX] = broadcast_swifs[0]; vec_free (broadcast_swifs); vec_free (buffers); } static uword arp_input (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame) { ethernet_arp_main_t * am = &ethernet_arp_main; vnet_main_t * vnm = vnet_get_main(); ip4_main_t * im4 = &ip4_main; u32 n_left_from, next_index, * from, * to_next; u32 n_replies_sent = 0, n_proxy_arp_replies_sent = 0; from = vlib_frame_vector_args (frame); n_left_from = frame->n_vectors; next_index = node->cached_next_index; if (node->flags & VLIB_NODE_FLAG_TRACE) vlib_trace_frame_buffers_only (vm, node, from, frame->n_vectors, /* stride */ 1, sizeof (ethernet_arp_input_trace_t)); while (n_left_from > 0) { u32 n_left_to_next; vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next); while (n_left_from > 0 && n_left_to_next > 0) { vlib_buffer_t * p0; vnet_hw_interface_t * hw_if0; ethernet_arp_header_t * arp0; ethernet_header_t * eth0; ip_interface_address_t * ifa0; ip_adjacency_t * adj0; ip4_address_t * if_addr0; ip4_address_t proxy_src; u32 pi0, error0, next0, sw_if_index0; u8 is_request0, src_is_local0, dst_is_local0, is_unnum0; ethernet_proxy_arp_t * pa; pi0 = from[0]; to_next[0] = pi0; from += 1; to_next += 1; n_left_from -= 1; n_left_to_next -= 1; p0 = vlib_get_buffer (vm, pi0); arp0 = vlib_buffer_get_current (p0); is_request0 = arp0->opcode == clib_host_to_net_u16 (ETHERNET_ARP_OPCODE_request); error0 = ETHERNET_ARP_ERROR_replies_sent; error0 = (arp0->l2_type != clib_net_to_host_u16 (ETHERNET_ARP_HARDWARE_TYPE_ethernet) ? ETHERNET_ARP_ERROR_l2_type_not_ethernet : error0); error0 = (arp0->l3_type != clib_net_to_host_u16 (ETHERNET_TYPE_IP4) ? ETHERNET_ARP_ERROR_l3_type_not_ip4 : error0); sw_if_index0 = vnet_buffer (p0)->sw_if_index[VLIB_RX]; if (error0) goto drop1; /* Check that IP address is local and matches incoming interface. */ if_addr0 = ip4_interface_address_matching_destination (im4, &arp0->ip4_over_ethernet[1].ip4, sw_if_index0, &ifa0); if (! if_addr0) { error0 = ETHERNET_ARP_ERROR_l3_dst_address_not_local; goto drop1; } /* Honor unnumbered interface, if any */ is_unnum0 = sw_if_index0 != ifa0->sw_if_index; /* Source must also be local to subnet of matching interface address. */ if (! ip4_destination_matches_interface (im4, &arp0->ip4_over_ethernet[0].ip4, ifa0)) { error0 = ETHERNET_ARP_ERROR_l3_src_address_not_local; goto drop1; } /* Reject requests/replies with our local interface address. */ src_is_local0 = if_addr0->as_u32 == arp0->ip4_over_ethernet[0].ip4.as_u32; if (src_is_local0) { error0 = ETHERNET_ARP_ERROR_l3_src_address_is_local; goto drop1; } dst_is_local0 = if_addr0->as_u32 == arp0->ip4_over_ethernet[1].ip4.as_u32; /* Fill in ethernet header. */ eth0 = ethernet_buffer_get_header (p0); /* Trash ARP packets whose ARP-level source addresses do not match their L2-frame-level source addresses */ if (memcmp (eth0->src_address, arp0->ip4_over_ethernet[0].ethernet, sizeof (eth0->src_address))) { error0 = ETHERNET_ARP_ERROR_l2_address_mismatch; goto drop2; } /* Learn or update sender's mapping only for requests or unicasts that don't match local interface address. */ if (ethernet_address_cast (eth0->dst_address) == ETHERNET_ADDRESS_UNICAST || is_request0) { if (am->limit_arp_cache_size && pool_elts (am->ip4_entry_pool) >= am->limit_arp_cache_size) unset_random_arp_entry(); vnet_arp_set_ip4_over_ethernet (vnm, sw_if_index0, (u32)~0 /* default fib */, &arp0->ip4_over_ethernet[0], 0 /* is_static */); error0 = ETHERNET_ARP_ERROR_l3_src_address_learned; } /* Only send a reply for requests sent which match a local interface. */ if (! (is_request0 && dst_is_local0)) { error0 = (arp0->opcode == clib_host_to_net_u16 (ETHERNET_ARP_OPCODE_reply) ? ETHERNET_ARP_ERROR_replies_received : error0); goto drop1; } /* Send a reply. */ send_reply: vnet_buffer (p0)->sw_if_index[VLIB_TX] = sw_if_index0; hw_if0 = vnet_get_sup_hw_interface (vnm, sw_if_index0); /* Send reply back through input interface */ vnet_buffer (p0)->sw_if_index[VLIB_TX] = sw_if_index0; next0 = ARP_INPUT_NEXT_REPLY_TX; arp0->opcode = clib_host_to_net_u16 (ETHERNET_ARP_OPCODE_reply); arp0->ip4_over_ethernet[1] = arp0->ip4_over_ethernet[0]; clib_memcpy (arp0->ip4_over_ethernet[0].ethernet, hw_if0->hw_address, 6); clib_mem_unaligned (&arp0->ip4_over_ethernet[0].ip4.data_u32, u32) = if_addr0->data_u32; /* Hardware must be ethernet-like. */ ASSERT (vec_len (hw_if0->hw_address) == 6); clib_memcpy (eth0->dst_address, eth0->src_address, 6); clib_memcpy (eth0->src_address, hw_if0->hw_address, 6); /* Figure out how much to rewind current data from adjacency. */ if (ifa0) { adj0 = ip_get_adjacency (&ip4_main.lookup_main, ifa0->neighbor_probe_adj_index); if (adj0->lookup_next_index != IP_LOOKUP_NEXT_ARP) { error0 = ETHERNET_ARP_ERROR_missing_interface_address; goto drop2; } if (is_unnum0) arp_unnumbered (p0, pi0, eth0, ifa0); else vlib_buffer_advance (p0, -adj0->rewrite_header.data_bytes); } vlib_validate_buffer_enqueue_x1 (vm, node, next_index,to_next, n_left_to_next,pi0,next0); n_replies_sent += 1; continue; drop1: if (0 == arp0->ip4_over_ethernet[0].ip4.as_u32 || (arp0->ip4_over_ethernet[0].ip4.as_u32 == arp0->ip4_over_ethernet[1].ip4.as_u32)) { error0 = ETHERNET_ARP_ERROR_gratuitous_arp; goto drop2; } /* See if proxy arp is configured for the address */ if (is_request0) { vnet_sw_interface_t * si; u32 this_addr = clib_net_to_host_u32 (arp0->ip4_over_ethernet[1].ip4.as_u32); u32 fib_index0; si = vnet_get_sw_interface (vnm, sw_if_index0); if (!(si->flags & VNET_SW_INTERFACE_FLAG_PROXY_ARP)) goto drop2; fib_index0 = vec_elt (im4->fib_index_by_sw_if_index, sw_if_index0); vec_foreach (pa, am->proxy_arps) { u32 lo_addr = clib_net_to_host_u32 (pa->lo_addr); u32 hi_addr = clib_net_to_host_u32 (pa->hi_addr); /* an ARP request hit in the proxy-arp table? */ if ((this_addr >= lo_addr && this_addr <= hi_addr) && (fib_index0 == pa->fib_index)) { eth0 = ethernet_buffer_get_header (p0); proxy_src.as_u32 = arp0->ip4_over_ethernet[1].ip4.data_u32; /* * Rewind buffer, direct code above not to * think too hard about it. * $$$ is the answer ever anything other than * vlib_buffer_reset(..)? */ ifa0 = 0; if_addr0 = &proxy_src; vlib_buffer_reset (p0); n_proxy_arp_replies_sent++; goto send_reply; } } } drop2: next0 = ARP_INPUT_NEXT_DROP; p0->error = node->errors[error0]; vlib_validate_buffer_enqueue_x1 (vm, node, next_index,to_next, n_left_to_next,pi0,next0); } vlib_put_next_frame (vm, node, next_index, n_left_to_next); } vlib_error_count (vm, node->node_index, ETHERNET_ARP_ERROR_replies_sent, n_replies_sent - n_proxy_arp_replies_sent); vlib_error_count (vm, node->node_index, ETHERNET_ARP_ERROR_proxy_arp_replies_sent, n_proxy_arp_replies_sent); return frame->n_vectors; } static char * ethernet_arp_error_strings[] = { #define _(sym,string) string, foreach_ethernet_arp_error #undef _ }; VLIB_REGISTER_NODE (arp_input_node,static) = { .function = arp_input, .name = "arp-input", .vector_size = sizeof (u32), .n_errors = ETHERNET_ARP_N_ERROR, .error_strings = ethernet_arp_error_strings, .n_next_nodes = ARP_INPUT_N_NEXT, .next_nodes = { [ARP_INPUT_NEXT_DROP] = "error-drop", [ARP_INPUT_NEXT_REPLY_TX] = "interface-output", }, .format_buffer = format_ethernet_arp_header, .format_trace = format_ethernet_arp_input_trace, }; static int ip4_arp_entry_sort (void *a1, void *a2) { ethernet_arp_ip4_entry_t * e1 = a1; ethernet_arp_ip4_entry_t * e2 = a2; int cmp; vnet_main_t * vnm = vnet_get_main(); cmp = vnet_sw_interface_compare (vnm, e1->key.sw_if_index, e2->key.sw_if_index); if (! cmp) cmp = ip4_address_compare (&e1->key.ip4_address, &e2->key.ip4_address); return cmp; } static clib_error_t * show_ip4_arp (vlib_main_t * vm, unformat_input_t * input, vlib_cli_command_t * cmd) { vnet_main_t * vnm = vnet_get_main(); ethernet_arp_main_t * am = &ethernet_arp_main; ethernet_arp_ip4_entry_t * e, * es; ethernet_proxy_arp_t * pa; clib_error_t * error = 0; u32 sw_if_index; /* Filter entries by interface if given. */ sw_if_index = ~0; (void) unformat_user (input, unformat_vnet_sw_interface, vnm, &sw_if_index); es = 0; pool_foreach (e, am->ip4_entry_pool, ({ vec_add1 (es, e[0]); })); if ( es ) { vec_sort_with_function (es, ip4_arp_entry_sort); vlib_cli_output (vm, "%U", format_ethernet_arp_ip4_entry, vnm, 0); vec_foreach (e, es) { if (sw_if_index != ~0 && e->key.sw_if_index != sw_if_index) continue; vlib_cli_output (vm, "%U", format_ethernet_arp_ip4_entry, vnm, e); } vec_free (es); } if (vec_len (am->proxy_arps)) { vlib_cli_output (vm, "Proxy arps enabled for:"); vec_foreach(pa, am->proxy_arps) { vlib_cli_output (vm, "Fib_index %d %U - %U ", pa->fib_index, format_ip4_address, &pa->lo_addr, format_ip4_address, &pa->hi_addr); } } return error; } VLIB_CLI_COMMAND (show_ip4_arp_command, static) = { .path = "show ip arp", .function = show_ip4_arp, .short_help = "Show ARP table", }; typedef struct { pg_edit_t l2_type, l3_type; pg_edit_t n_l2_address_bytes, n_l3_address_bytes; pg_edit_t opcode; struct { pg_edit_t ethernet; pg_edit_t ip4; } ip4_over_ethernet[2]; } pg_ethernet_arp_header_t; static inline void pg_ethernet_arp_header_init (pg_ethernet_arp_header_t * p) { /* Initialize fields that are not bit fields in the IP header. */ #define _(f) pg_edit_init (&p->f, ethernet_arp_header_t, f); _ (l2_type); _ (l3_type); _ (n_l2_address_bytes); _ (n_l3_address_bytes); _ (opcode); _ (ip4_over_ethernet[0].ethernet); _ (ip4_over_ethernet[0].ip4); _ (ip4_over_ethernet[1].ethernet); _ (ip4_over_ethernet[1].ip4); #undef _ } uword unformat_pg_arp_header (unformat_input_t * input, va_list * args) { pg_stream_t * s = va_arg (*args, pg_stream_t *); pg_ethernet_arp_header_t * p; u32 group_index; p = pg_create_edit_group (s, sizeof (p[0]), sizeof (ethernet_arp_header_t), &group_index); pg_ethernet_arp_header_init (p); /* Defaults. */ pg_edit_set_fixed (&p->l2_type, ETHERNET_ARP_HARDWARE_TYPE_ethernet); pg_edit_set_fixed (&p->l3_type, ETHERNET_TYPE_IP4); pg_edit_set_fixed (&p->n_l2_address_bytes, 6); pg_edit_set_fixed (&p->n_l3_address_bytes, 4); if (! unformat (input, "%U: %U/%U -> %U/%U", unformat_pg_edit, unformat_ethernet_arp_opcode_net_byte_order, &p->opcode, unformat_pg_edit, unformat_ethernet_address, &p->ip4_over_ethernet[0].ethernet, unformat_pg_edit, unformat_ip4_address, &p->ip4_over_ethernet[0].ip4, unformat_pg_edit, unformat_ethernet_address, &p->ip4_over_ethernet[1].ethernet, unformat_pg_edit, unformat_ip4_address, &p->ip4_over_ethernet[1].ip4)) { /* Free up any edits we may have added. */ pg_free_edit_group (s); return 0; } return 1; } clib_error_t *ip4_set_arp_limit (u32 arp_limit) { ethernet_arp_main_t * am = &ethernet_arp_main; am->limit_arp_cache_size = arp_limit; return 0; } static void arp_ip4_entry_del_adj(ethernet_arp_ip4_entry_t *e, u32 adj_index) { int done = 0; int i; while (!done) { vec_foreach_index(i, e->adjacencies) if (vec_elt(e->adjacencies, i) == adj_index) { vec_del1(e->adjacencies, i); continue; } done = 1; } } static void arp_ip4_entry_add_adj(ethernet_arp_ip4_entry_t *e, u32 adj_index) { int i; vec_foreach_index(i, e->adjacencies) if (vec_elt(e->adjacencies, i) == adj_index) return; vec_add1(e->adjacencies, adj_index); } static void arp_add_del_adj_cb (struct ip_lookup_main_t * lm, u32 adj_index, ip_adjacency_t * adj, u32 is_del) { ethernet_arp_main_t * am = &ethernet_arp_main; ip4_main_t * im = &ip4_main; ethernet_arp_ip4_key_t k; ethernet_arp_ip4_entry_t * e = 0; uword * p; u32 ai; for(ai = adj->heap_handle; ai < adj->heap_handle + adj->n_adj ; ai++) { adj = ip_get_adjacency (lm, ai); if (adj->lookup_next_index == IP_LOOKUP_NEXT_ARP && adj->arp.next_hop.ip4.as_u32) { k.sw_if_index = adj->rewrite_header.sw_if_index; k.ip4_address.as_u32 = adj->arp.next_hop.ip4.as_u32; k.fib_index = im->fib_index_by_sw_if_index[adj->rewrite_header.sw_if_index]; p = mhash_get (&am->ip4_entry_by_key, &k); if (p) e = pool_elt_at_index (am->ip4_entry_pool, p[0]); } else continue; if (is_del) { if (!e) clib_warning("Adjacency contains unknown ARP next hop %U (del)", format_ip46_address, &adj->arp.next_hop, IP46_TYPE_IP4); else arp_ip4_entry_del_adj(e, adj->heap_handle); } else /* add */ { if (!e) clib_warning("Adjacency contains unknown ARP next hop %U (add)", format_ip46_address, &adj->arp.next_hop, IP46_TYPE_IP4); else arp_ip4_entry_add_adj(e, adj->heap_handle); } } } static clib_error_t * ethernet_arp_init (vlib_main_t * vm) { ethernet_arp_main_t * am = &ethernet_arp_main; pg_node_t * pn; clib_error_t * error; ip4_main_t * im = &ip4_main; ip_lookup_main_t * lm = &im->lookup_main; if ((error = vlib_call_init_function (vm, ethernet_init))) return error; ethernet_register_input_type (vm, ETHERNET_TYPE_ARP, arp_input_node.index); pn = pg_get_node (arp_input_node.index); pn->unformat_edit = unformat_pg_arp_header; am->opcode_by_name = hash_create_string (0, sizeof (uword)); #define _(o) hash_set_mem (am->opcode_by_name, #o, ETHERNET_ARP_OPCODE_##o); foreach_ethernet_arp_opcode; #undef _ mhash_init (&am->ip4_entry_by_key, /* value size */ sizeof (uword), /* key size */ sizeof (ethernet_arp_ip4_key_t)); /* $$$ configurable */ am->limit_arp_cache_size = 50000; am->pending_resolutions_by_address = hash_create (0, sizeof (uword)); am->mac_changes_by_address = hash_create (0, sizeof (uword)); /* don't trace ARP error packets */ { vlib_node_runtime_t *rt = vlib_node_get_runtime (vm, arp_input_node.index); #define _(a,b) \ vnet_pcap_drop_trace_filter_add_del \ (rt->errors[ETHERNET_ARP_ERROR_##a], \ 1 /* is_add */); foreach_ethernet_arp_error #undef _ } ip_register_add_del_adjacency_callback(lm, arp_add_del_adj_cb); return 0; } VLIB_INIT_FUNCTION (ethernet_arp_init); int vnet_arp_unset_ip4_over_ethernet (vnet_main_t * vnm, u32 sw_if_index, u32 fib_index, void * a_arg) { ethernet_arp_ip4_over_ethernet_address_t * a = a_arg; vnet_arp_set_ip4_over_ethernet_rpc_args_t args; args.sw_if_index = sw_if_index; args.fib_index = fib_index; args.is_remove = 1; clib_memcpy (&args.a, a, sizeof (*a)); vl_api_rpc_call_main_thread (set_ip4_over_ethernet_rpc_callback, (u8 *) &args, sizeof (args)); return 0; } static inline int vnet_arp_unset_ip4_over_ethernet_internal (vnet_main_t * vnm, u32 sw_if_index, u32 fib_index, void * a_arg) { ethernet_arp_ip4_entry_t * e; ethernet_arp_main_t * am = &ethernet_arp_main; ethernet_arp_ip4_over_ethernet_address_t * a = a_arg; ethernet_arp_ip4_key_t k; uword * p; ip4_add_del_route_args_t args; ip4_main_t * im = &ip4_main; ip_lookup_main_t * lm = &im->lookup_main; u32 adj_index; ip_adjacency_t * adj; k.sw_if_index = sw_if_index; k.ip4_address = a->ip4; k.fib_index = fib_index; p = mhash_get (&am->ip4_entry_by_key, &k); if (! p) return -1; memset(&args, 0, sizeof(args)); /* * Make sure that the route actually exists before we try to delete it, * and make sure that it's a rewrite adjacency. * * If we point 1-N unnumbered interfaces at a loopback interface and * shut down the loopback before shutting down 1-N unnumbered * interfaces, the ARP cache will still have an entry, * but the route will have disappeared. * * See also ip4_del_interface_routes (...) * -> ip4_delete_matching_routes (...). */ adj_index = ip4_fib_lookup_with_table (im, fib_index, &a->ip4, 1 /* disable default route */); /* Miss adj? Forget it... */ if (adj_index != lm->miss_adj_index) { adj = ip_get_adjacency (lm, adj_index); /* * Stupid control-plane trick: * admin down an interface (removes arp routes from fib), * bring the interface back up (does not reinstall them) * then remove the arp cache entry (yuck). When that happens, * the adj we find here will be the interface subnet ARP adj. */ if (adj->lookup_next_index == IP_LOOKUP_NEXT_REWRITE) { args.table_index_or_table_id = fib_index; args.flags = IP4_ROUTE_FLAG_FIB_INDEX | IP4_ROUTE_FLAG_DEL | IP4_ROUTE_FLAG_NEIGHBOR; args.dst_address = a->ip4; args.dst_address_length = 32; ip4_add_del_route (im, &args); ip4_maybe_remap_adjacencies (im, fib_index, args.flags); } } e = pool_elt_at_index (am->ip4_entry_pool, p[0]); mhash_unset (&am->ip4_entry_by_key, &e->key, 0); pool_put (am->ip4_entry_pool, e); return 0; } static void increment_ip4_and_mac_address (ethernet_arp_ip4_over_ethernet_address_t *a) { u8 old; int i; for (i = 3; i >= 0; i--) { old = a->ip4.as_u8[i]; a->ip4.as_u8[i] += 1; if (old < a->ip4.as_u8[i]) break; } for (i = 5; i >= 0; i--) { old = a->ethernet[i]; a->ethernet[i] += 1; if (old < a->ethernet[i]) break; } } int vnet_proxy_arp_add_del (ip4_address_t *lo_addr, ip4_address_t *hi_addr, u32 fib_index, int is_del) { ethernet_arp_main_t *am = &ethernet_arp_main; ethernet_proxy_arp_t *pa; u32 found_at_index = ~0; vec_foreach (pa, am->proxy_arps) { if (pa->lo_addr == lo_addr->as_u32 && pa->hi_addr == hi_addr->as_u32 && pa->fib_index == fib_index) { found_at_index = pa - am->proxy_arps; break; } } if (found_at_index != ~0) { /* Delete, otherwise it's already in the table */ if (is_del) vec_delete (am->proxy_arps, 1, found_at_index); return 0; } /* delete, no such entry */ if (is_del) return VNET_API_ERROR_NO_SUCH_ENTRY; /* add, not in table */ vec_add2 (am->proxy_arps, pa, 1); pa->lo_addr = lo_addr->as_u32; pa->hi_addr = hi_addr->as_u32; pa->fib_index = fib_index; return 0; } /* * Remove any proxy arp entries asdociated with the * specificed fib. */ int vnet_proxy_arp_fib_reset (u32 fib_id) { ip4_main_t * im = &ip4_main; ethernet_arp_main_t *am = &ethernet_arp_main; ethernet_proxy_arp_t *pa; u32 * entries_to_delete = 0; u32 fib_index; uword * p; int i; p = hash_get (im->fib_index_by_table_id, fib_id); if (! p) return VNET_API_ERROR_NO_SUCH_ENTRY; fib_index = p[0]; vec_foreach (pa, am->proxy_arps) { if (pa->fib_index == fib_index) { vec_add1 (entries_to_delete, pa - am->proxy_arps); } } for (i = 0; i < vec_len(entries_to_delete); i++) { vec_delete (am->proxy_arps, 1, entries_to_delete[i]); } vec_free (entries_to_delete); return 0; } u32 vnet_arp_glean_add(u32 fib_index, void * next_hop_arg) { ethernet_arp_main_t * am = &ethernet_arp_main; ip4_main_t * im = &ip4_main; ip_lookup_main_t * lm = &im->lookup_main; ip4_address_t * next_hop = next_hop_arg; ip_adjacency_t add_adj, *adj; ip4_add_del_route_args_t args; ethernet_arp_ip4_entry_t * e; ethernet_arp_ip4_key_t k; u32 adj_index; adj_index = ip4_fib_lookup_with_table(im, fib_index, next_hop, 0); adj = ip_get_adjacency(lm, adj_index); if (!adj || adj->lookup_next_index != IP_LOOKUP_NEXT_ARP) return ~0; if (adj->arp.next_hop.ip4.as_u32 != 0) return adj_index; k.sw_if_index = adj->rewrite_header.sw_if_index; k.fib_index = fib_index; k.ip4_address.as_u32 = next_hop->as_u32; if (mhash_get (&am->ip4_entry_by_key, &k)) return adj_index; pool_get (am->ip4_entry_pool, e); mhash_set (&am->ip4_entry_by_key, &k, e - am->ip4_entry_pool, /* old value */ 0); e->key = k; e->cpu_time_last_updated = clib_cpu_time_now (); e->flags = ETHERNET_ARP_IP4_ENTRY_FLAG_GLEAN; memset(&args, 0, sizeof(args)); clib_memcpy(&add_adj, adj, sizeof(add_adj)); ip46_address_set_ip4(&add_adj.arp.next_hop, next_hop); /* install neighbor /32 route */ args.table_index_or_table_id = fib_index; args.flags = IP4_ROUTE_FLAG_FIB_INDEX | IP4_ROUTE_FLAG_ADD| IP4_ROUTE_FLAG_NEIGHBOR; args.dst_address.as_u32 = next_hop->as_u32; args.dst_address_length = 32; args.adj_index = ~0; args.add_adj = &add_adj; args.n_add_adj = 1; ip4_add_del_route (im, &args); return ip4_fib_lookup_with_table (im, fib_index, next_hop, 0); } static clib_error_t * ip_arp_add_del_command_fn (vlib_main_t * vm, unformat_input_t * input, vlib_cli_command_t * cmd) { vnet_main_t * vnm = vnet_get_main(); u32 sw_if_index; ethernet_arp_ip4_over_ethernet_address_t lo_addr, hi_addr, addr; int addr_valid = 0; int is_del = 0; int count = 1; u32 fib_index = 0; u32 fib_id; int is_static = 0; int is_proxy = 0; while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT) { /* set ip arp TenGigE1/1/0/1 1.2.3.4 aa:bb:... or aabb.ccdd... */ if (unformat (input, "%U %U %U", unformat_vnet_sw_interface, vnm, &sw_if_index, unformat_ip4_address, &addr.ip4, unformat_ethernet_address, &addr.ethernet)) addr_valid = 1; else if (unformat (input, "delete") || unformat (input, "del")) is_del = 1; else if (unformat (input, "static")) is_static = 1; else if (unformat (input, "count %d", &count)) ; else if (unformat (input, "fib-id %d", &fib_id)) { ip4_main_t * im = &ip4_main; uword * p = hash_get (im->fib_index_by_table_id, fib_id); if (! p) return clib_error_return (0, "fib ID %d doesn't exist\n", fib_id); fib_index = p[0]; } else if (unformat (input, "proxy %U - %U", unformat_ip4_address, &lo_addr.ip4, unformat_ip4_address, &hi_addr.ip4)) is_proxy = 1; else break; } if (is_proxy) { (void) vnet_proxy_arp_add_del (&lo_addr.ip4, &hi_addr.ip4, fib_index, is_del); return 0; } if (addr_valid) { int i; for (i = 0; i < count; i++) { if (is_del == 0) { uword event_type, * event_data = 0; /* Park the debug CLI until the arp entry is installed */ vnet_register_ip4_arp_resolution_event (vnm, &addr.ip4, vlib_current_process(vm), 1 /* type */, 0 /* data */); vnet_arp_set_ip4_over_ethernet (vnm, sw_if_index, fib_index, &addr, is_static); vlib_process_wait_for_event (vm); event_type = vlib_process_get_events (vm, &event_data); vec_reset_length(event_data); if (event_type != 1) clib_warning ("event type %d unexpected", event_type); } else vnet_arp_unset_ip4_over_ethernet (vnm, sw_if_index, fib_index, &addr); increment_ip4_and_mac_address (&addr); } } else { return clib_error_return (0, "unknown input `%U'", format_unformat_error, input); } return 0; } VLIB_CLI_COMMAND (ip_arp_add_del_command, static) = { .path = "set ip arp", .short_help = "set ip arp [del] <intfc> <ip-address> <mac-address> [static] [count <count>] [fib-id <fib-id>] [proxy <lo-addr> - <hi-addr>]", .function = ip_arp_add_del_command_fn, }; static clib_error_t * set_int_proxy_arp_command_fn (vlib_main_t * vm, unformat_input_t * input, vlib_cli_command_t * cmd) { vnet_main_t * vnm = vnet_get_main(); u32 sw_if_index; vnet_sw_interface_t * si; int enable = 0; int intfc_set = 0; while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT) { if (unformat (input, "%U", unformat_vnet_sw_interface, vnm, &sw_if_index)) intfc_set = 1; else if (unformat (input, "enable") || unformat (input, "on")) enable = 1; else if (unformat (input, "disable") || unformat (input, "off")) enable = 0; else break; } if (intfc_set == 0) return clib_error_return (0, "unknown input '%U'", format_unformat_error, input); si = vnet_get_sw_interface (vnm, sw_if_index); ASSERT(si); if (enable) si->flags |= VNET_SW_INTERFACE_FLAG_PROXY_ARP; else si->flags &= ~VNET_SW_INTERFACE_FLAG_PROXY_ARP; return 0; } VLIB_CLI_COMMAND (set_int_proxy_enable_command, static) = { .path = "set interface proxy-arp", .short_help = "set interface proxy-arp <intfc> [enable|disable]", .function = set_int_proxy_arp_command_fn, }; /* * ARP Termination in a L2 Bridge Domain based on an * IP4 to MAC hash table mac_by_ip4 for each BD. */ typedef enum { ARP_TERM_NEXT_L2_OUTPUT, ARP_TERM_NEXT_DROP, ARP_TERM_N_NEXT, } arp_term_next_t; u32 arp_term_next_node_index[32]; static uword arp_term_l2bd (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame) { l2input_main_t * l2im = &l2input_main; u32 n_left_from, next_index, * from, * to_next; u32 n_replies_sent = 0; u16 last_bd_index = ~0; l2_bridge_domain_t * last_bd_config = 0; l2_input_config_t * cfg0; from = vlib_frame_vector_args (frame); n_left_from = frame->n_vectors; next_index = node->cached_next_index; while (n_left_from > 0) { u32 n_left_to_next; vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next); while (n_left_from > 0 && n_left_to_next > 0) { vlib_buffer_t * p0; ethernet_header_t * eth0; ethernet_arp_header_t * arp0; u8 * l3h0; u32 pi0, error0, next0, sw_if_index0; u16 ethertype0; u16 bd_index0; u32 ip0; u8 * macp0; pi0 = from[0]; to_next[0] = pi0; from += 1; to_next += 1; n_left_from -= 1; n_left_to_next -= 1; p0 = vlib_get_buffer (vm, pi0); eth0 = vlib_buffer_get_current (p0); l3h0 = (u8 *)eth0 + vnet_buffer(p0)->l2.l2_len; ethertype0 = clib_net_to_host_u16(*(u16 *)(l3h0 - 2)); arp0 = (ethernet_arp_header_t *) l3h0; if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) && (p0->flags & VLIB_BUFFER_IS_TRACED))) { u8 *t0 = vlib_add_trace ( vm, node, p0, sizeof(ethernet_arp_input_trace_t)); clib_memcpy (t0, l3h0, sizeof(ethernet_arp_input_trace_t)); } if (PREDICT_FALSE ( (ethertype0 != ETHERNET_TYPE_ARP) || (arp0->opcode != clib_host_to_net_u16(ETHERNET_ARP_OPCODE_request)))) goto next_l2_feature; error0 = ETHERNET_ARP_ERROR_replies_sent; error0 = (arp0->l2_type != clib_net_to_host_u16 (ETHERNET_ARP_HARDWARE_TYPE_ethernet) ? ETHERNET_ARP_ERROR_l2_type_not_ethernet : error0); error0 = (arp0->l3_type != clib_net_to_host_u16 (ETHERNET_TYPE_IP4) ? ETHERNET_ARP_ERROR_l3_type_not_ip4 : error0); sw_if_index0 = vnet_buffer (p0)->sw_if_index[VLIB_RX]; if (error0) goto drop; // Trash ARP packets whose ARP-level source addresses do not // match their L2-frame-level source addresses */ if (PREDICT_FALSE ( memcmp (eth0->src_address, arp0->ip4_over_ethernet[0].ethernet, sizeof (eth0->src_address)))) { error0 = ETHERNET_ARP_ERROR_l2_address_mismatch; goto drop; } // Check if anyone want ARP request events for L2 BDs { pending_resolution_t * mc; ethernet_arp_main_t * am = &ethernet_arp_main; uword *p = hash_get (am->mac_changes_by_address, 0); if (p && (vnet_buffer(p0)->l2.shg == 0)) { // Only SHG 0 interface which is more likely local u32 next_index = p[0]; while (next_index != (u32)~0) { int (*fp)(u32, u8 *, u32, u32); int rv = 1; mc = pool_elt_at_index (am->mac_changes, next_index); fp = mc->data_callback; // Call the callback, return 1 to suppress dup events */ if (fp) rv = (*fp)(mc->data, arp0->ip4_over_ethernet[0].ethernet, sw_if_index0, arp0->ip4_over_ethernet[0].ip4.as_u32); // Signal the resolver process if (rv == 0) vlib_process_signal_event (vm, mc->node_index, mc->type_opaque, mc->data); next_index = mc->next_index; } } } // lookup BD mac_by_ip4 hash table for MAC entry ip0 = arp0->ip4_over_ethernet[1].ip4.as_u32; bd_index0 = vnet_buffer(p0)->l2.bd_index; if (PREDICT_FALSE ( (bd_index0 != last_bd_index) || (last_bd_index == (u16) ~0))) { last_bd_index = bd_index0; last_bd_config = vec_elt_at_index(l2im->bd_configs, bd_index0); } macp0 = (u8 *) hash_get (last_bd_config->mac_by_ip4, ip0); if (PREDICT_FALSE(!macp0)) goto next_l2_feature; // MAC not found // MAC found, send ARP reply - // Convert ARP request packet to ARP reply arp0->opcode = clib_host_to_net_u16 (ETHERNET_ARP_OPCODE_reply); arp0->ip4_over_ethernet[1] = arp0->ip4_over_ethernet[0]; arp0->ip4_over_ethernet[0].ip4.as_u32 = ip0; clib_memcpy (arp0->ip4_over_ethernet[0].ethernet, macp0, 6); clib_memcpy (eth0->dst_address, eth0->src_address, 6); clib_memcpy (eth0->src_address, macp0, 6); n_replies_sent += 1; // For BVI, need to use l2-fwd node to send ARP reply as // l2-output node cannot output packet to BVI properly cfg0 = vec_elt_at_index(l2im->configs, sw_if_index0); if (PREDICT_FALSE (cfg0->bvi)) { vnet_buffer(p0)->l2.feature_bitmap |= L2INPUT_FEAT_FWD; vnet_buffer (p0)->sw_if_index[VLIB_RX] = 0; goto next_l2_feature; } // Send ARP reply back out input interface through l2-output vnet_buffer (p0)->sw_if_index[VLIB_TX] = sw_if_index0; next0 = ARP_TERM_NEXT_L2_OUTPUT; // Note that output to VXLAN tunnel will fail due to SHG which // is probably desireable since ARP termination is not intended // for ARP requests from other hosts. If output to VXLAN tunnel is // required, however, can just clear the SHG in packet as follows: // vnet_buffer(p0)->l2.shg = 0; vlib_validate_buffer_enqueue_x1 (vm, node, next_index,to_next, n_left_to_next,pi0,next0); continue; next_l2_feature: { u32 feature_bitmap0 = vnet_buffer(p0)->l2.feature_bitmap & ~L2INPUT_FEAT_ARP_TERM; vnet_buffer(p0)->l2.feature_bitmap = feature_bitmap0; next0 = feat_bitmap_get_next_node_index(arp_term_next_node_index, feature_bitmap0); vlib_validate_buffer_enqueue_x1 (vm, node, next_index,to_next, n_left_to_next,pi0,next0); continue; } drop: if (0 == arp0->ip4_over_ethernet[0].ip4.as_u32 || (arp0->ip4_over_ethernet[0].ip4.as_u32 == arp0->ip4_over_ethernet[1].ip4.as_u32)) { error0 = ETHERNET_ARP_ERROR_gratuitous_arp; } next0 = ARP_TERM_NEXT_DROP; p0->error = node->errors[error0]; vlib_validate_buffer_enqueue_x1 (vm, node, next_index,to_next, n_left_to_next,pi0,next0); } vlib_put_next_frame (vm, node, next_index, n_left_to_next); } vlib_error_count (vm, node->node_index, ETHERNET_ARP_ERROR_replies_sent, n_replies_sent); return frame->n_vectors; } VLIB_REGISTER_NODE (arp_term_l2bd_node,static) = { .function = arp_term_l2bd, .name = "arp-term-l2bd", .vector_size = sizeof (u32), .n_errors = ETHERNET_ARP_N_ERROR, .error_strings = ethernet_arp_error_strings, .n_next_nodes = ARP_TERM_N_NEXT, .next_nodes = { [ARP_TERM_NEXT_L2_OUTPUT] = "l2-output", [ARP_TERM_NEXT_DROP] = "error-drop", }, .format_buffer = format_ethernet_arp_header, .format_trace = format_ethernet_arp_input_trace, }; clib_error_t *arp_term_init (vlib_main_t *vm) { // Initialize the feature next-node indexes feat_bitmap_init_next_nodes(vm, arp_term_l2bd_node.index, L2INPUT_N_FEAT, l2input_get_feat_names(), arp_term_next_node_index); return 0; } VLIB_INIT_FUNCTION (arp_term_init);
30.09623
145
0.6291
[ "vector" ]
6867c380c3f0ae485958084a42fd18ad5a40233f
2,060
h
C
blades/xbmc/xbmc/windowing/egl/EGLNativeTypeAmlogic.h
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
4
2016-04-26T03:43:54.000Z
2016-11-17T08:09:04.000Z
blades/xbmc/xbmc/windowing/egl/EGLNativeTypeAmlogic.h
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
17
2015-01-05T21:06:22.000Z
2015-12-07T20:45:44.000Z
blades/xbmc/xbmc/windowing/egl/EGLNativeTypeAmlogic.h
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
3
2016-04-26T03:43:55.000Z
2020-11-06T11:02:08.000Z
#pragma once /* * Copyright (C) 2011-2013 Team XBMC * http://xbmc.org * * 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, 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 XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "EGLNativeType.h" class CEGLNativeTypeAmlogic : public CEGLNativeType { public: CEGLNativeTypeAmlogic(); virtual ~CEGLNativeTypeAmlogic(); virtual std::string GetNativeName() const { return "amlogic"; }; virtual bool CheckCompatibility(); virtual void Initialize(); virtual void Destroy(); virtual int GetQuirks() { return EGL_QUIRK_NONE; }; virtual bool CreateNativeDisplay(); virtual bool CreateNativeWindow(); virtual bool GetNativeDisplay(XBNativeDisplayType **nativeDisplay) const; virtual bool GetNativeWindow(XBNativeWindowType **nativeWindow) const; virtual bool DestroyNativeWindow(); virtual bool DestroyNativeDisplay(); virtual bool GetNativeResolution(RESOLUTION_INFO *res) const; virtual bool SetNativeResolution(const RESOLUTION_INFO &res); virtual bool ProbeResolutions(std::vector<RESOLUTION_INFO> &resolutions); virtual bool GetPreferredResolution(RESOLUTION_INFO *res) const; virtual bool ShowWindow(bool show); protected: bool SetDisplayResolution(const char *resolution); void SetupVideoScaling(const char *mode); void DisableFreeScale(); private: void SetFramebufferResolution(const RESOLUTION_INFO &res) const; void SetFramebufferResolution(int width, int height) const; std::string m_framebuffer_name; };
33.770492
76
0.752913
[ "vector" ]
686d3f155a3d20cb3025f14cc63fada442647ea8
4,941
h
C
debs/com.maxleiter.cairomm/usr/include/cairomm-1.0/cairomm/region.h
MaxLeiter/Cydia
eb5ac542926523d55c7732c2077162daf5f3e0ef
[ "MIT" ]
3
2017-01-19T09:30:50.000Z
2017-03-20T10:47:20.000Z
debs/com.maxleiter.cairomm/usr/include/cairomm-1.0/cairomm/region.h
MaxLeiter/Cydia
eb5ac542926523d55c7732c2077162daf5f3e0ef
[ "MIT" ]
null
null
null
debs/com.maxleiter.cairomm/usr/include/cairomm-1.0/cairomm/region.h
MaxLeiter/Cydia
eb5ac542926523d55c7732c2077162daf5f3e0ef
[ "MIT" ]
11
2020-03-28T19:24:12.000Z
2021-10-18T00:20:45.000Z
/* Copyright (C) 2010 The cairomm Development Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ #ifndef __CAIROMM_REGION_H #define __CAIROMM_REGION_H #include <cairomm/types.h> #include <cairomm/enums.h> #include <cairomm/refptr.h> #include <cairo.h> #include <vector> namespace Cairo { /** * A simple graphical data type representing an area of integer-aligned * rectangles. They are often used on raster surfaces to track areas of * interest, such as change or clip areas * * It allows set-theoretical operations like union and intersect to be performed * on them. * * @since: 1.10 **/ class Region { private: Region(); explicit Region(const RectangleInt& rectangle); explicit Region(const std::vector<RectangleInt>& rects); Region(const RectangleInt *rects, int count); public: /** Create a C++ wrapper for the C instance. This C++ instance should then be given to a RefPtr. * @param cobject The C instance. * @param has_reference Whether we already have a reference. Otherwise, the constructor will take an extra reference. */ explicit Region(cairo_region_t* cobject, bool has_reference = false); /** Creates an empty Region object */ static RefPtr<Region> create(); /** Creates a Region object containing @a rectangle */ static RefPtr<Region> create(const RectangleInt& rectangle); /** Creates a Region object containing the union of all given @a rects */ static RefPtr<Region> create(const std::vector<RectangleInt>& rects); /** Creates a Region object containing the union of all given @a rects */ static RefPtr<Region> create(const RectangleInt *rects, int count); /** allocates a new region object copied from the original */ RefPtr<Region> copy() const; virtual ~Region(); /** Gets the bounding rectangle of the region */ RectangleInt get_extents() const; /** Gets the number of rectangles contained in the region */ int get_num_rectangles() const; /** Gets the nth rectangle from the region */ RectangleInt get_rectangle(int nth_rectangle) const; /** Checks whether the region is empty */ bool empty() const; /** Checks whether @a rectangle is inside, outside, or partially contained in * the region */ RegionOverlap contains_rectangle(const RectangleInt& rectangle) const; /** Checks whether (x,y) is contained in the region */ bool contains_point(int x, int y) const; /** Translates the region by (dx,dy) */ void translate(int dx, int dy); /** Subtracts @a other from this region */ void subtract(const RefPtr<Region>& other); /** Subtracts @a rectangle from this region */ void subtract(const RectangleInt& rectangle); /** Sets the region to the intersection of this region with @a other */ void intersect(const RefPtr<Region>& other); /** Sets the region to the intersection of this region with @a rectangle */ void intersect(const RectangleInt& rectangle); //We don't call this method union() because that is a C++ keyword. /** Sets this region to the union of the region with @a other */ void do_union(const RefPtr<Region>& other); /** Sets this region to the union of the region with @a rectangle */ void do_union(const RectangleInt& rectangle); /** Sets this region to the exclusive difference of the region with @a other. * That is, the region will contain all areas that are in the original region * or in @a other, but not in both */ void do_xor(const RefPtr<Region>& other); /** Sets this region to the exclusive difference of the region with @a * rectangle. That is, the region will contain all areas that are in the * original region or in @a rectangle, but not in both */ void do_xor(const RectangleInt& rectangle); typedef cairo_region_t cobject; inline cobject* cobj() { return m_cobject; } inline const cobject* cobj() const { return m_cobject; } #ifndef DOXYGEN_IGNORE_THIS ///For use only by the cairomm implementation. inline ErrorStatus get_status() const { return cairo_region_status(const_cast<cairo_region_t*>(cobj())); } #endif //DOXYGEN_IGNORE_THIS void reference() const; void unreference() const; protected: cobject* m_cobject; }; } // namespace Cairo #endif //__CAIROMM_REGION_H // vim: ts=2 sw=2 et
32.506579
119
0.724954
[ "object", "vector" ]
686e9c43153a19626d668dad716171fd3be19bd2
1,144
h
C
sdk/src/main/cpp/crossplatform/CrossPlatform/CaffePredictor/CaffeResultList.h
LouisP79/CardScanner
94c6299f219584073e5443465419c19d67df93c3
[ "Apache-2.0", "MIT" ]
172
2017-08-13T10:25:24.000Z
2022-03-21T08:10:18.000Z
sdk/src/main/cpp/crossplatform/CrossPlatform/CaffePredictor/CaffeResultList.h
LouisP79/CardScanner
94c6299f219584073e5443465419c19d67df93c3
[ "Apache-2.0", "MIT" ]
58
2017-08-21T09:51:09.000Z
2021-12-08T17:27:04.000Z
sdk/src/main/cpp/crossplatform/CrossPlatform/CaffePredictor/CaffeResultList.h
LouisP79/CardScanner
94c6299f219584073e5443465419c19d67df93c3
[ "Apache-2.0", "MIT" ]
125
2017-10-22T10:54:32.000Z
2022-01-20T10:06:17.000Z
// // CaffeResultList.h // CardRecognizer // // Created by Vladimir Tchernitski on 08/06/15. // Copyright (c) 2015 Vladimir Tchernitski. All rights reserved. // #ifndef __CardRecognizer__CaffeResultList__ #define __CardRecognizer__CaffeResultList__ #include "INeuralNetworkResultList.h" using namespace std; class CCaffeResultList : public INeuralNetworkResultList { public: CCaffeResultList() {}; virtual ~CCaffeResultList(); virtual void PushBack(const shared_ptr<INeuralNetworkResult>& result); virtual int Size() const; virtual void Clear(); virtual ResultIterator Begin() {return _resultList.begin();} virtual ConstResultIterator Begin() const {return _resultList.cbegin();} virtual ResultIterator End() {return _resultList.end();} virtual ConstResultIterator End() const {return _resultList.cend();}; virtual shared_ptr<INeuralNetworkResult> GetAtIndex(int idx); virtual float GetMeanConfidence() const; private: vector<shared_ptr<INeuralNetworkResult>> _resultList; }; #endif /* defined(__CardRecognizer__CaffeResultList__) */
23.833333
76
0.727273
[ "vector" ]
68a6462b73395b790d7a93e20d06dae8f1c3e62b
2,763
h
C
lr2/headers/Service.h
ShinShil/spovm
034ddc101999311c2ab4f850e00ad5cfd05d4751
[ "MIT" ]
null
null
null
lr2/headers/Service.h
ShinShil/spovm
034ddc101999311c2ab4f850e00ad5cfd05d4751
[ "MIT" ]
null
null
null
lr2/headers/Service.h
ShinShil/spovm
034ddc101999311c2ab4f850e00ad5cfd05d4751
[ "MIT" ]
null
null
null
#pragma once #include "MainHeader.h" class Service { public: static void writeToFile(string src, string path); static void readFromFile(string& dest, string path); static string getCurrDir(); static void cycleIncrement(int& i, int max); static int stringToInt(string num) { int res = 0; int ten = 1; for(int i = num.length() - 1; i>=0; --i) { int t = chToI(num[i]); t *= ten; res += t; ten *= 10; } return res; } static string intToString(int num) { string res = ""; while(num/10 > 0) { int t = num % 10; num /= 10; res += iToCh(t); } int t = num%10; res += iToCh(t); reverse(res.begin(), res.end()); return res; } static void readLineFromFile(string& dest, string path) { ifstream in; in.open(path.c_str()); in >> dest; //cout<<"debug readFile: "<<path <<" "<<dest<<endl; in.close(); } static char iToCh(int num) { switch(num) { case 1: return '1'; break; case 2: return '2'; break; case 3: return '3'; break; case 4: return '4'; break; case 5: return '5'; break; case 6: return '6'; break; case 7: return '7'; break; case 8: return '8'; break; case 9: return '9'; break; case 0: return '0'; break; } } static int chToI(char ch) { switch(ch) { case '1': return 1; break; case '2': return 2; break; case '3': return 3; break; case '4': return 4; break; case '5': return 5; break; case '6': return 6; break; case '7': return 7; break; case '8': return 8; break; case '9': return 9; break; case '0': return 0; break; } } static vector<string> splitLines(string line) { string t = ""; vector<string> res; if(line != "") for(int i = 0; i<line.length(); ++i) { if(line[i]!='\n') { t += line[i]; }else { res.push_back(t); t = ""; } } if(t!="") res.push_back(t); return res; } static void addLineToFile(string line, string path) { ofstream ofs; ofs.open(path.c_str(), ios_base::app); line += '\n'; ofs << line; ofs.close(); } static void sleep(int ms) { #ifdef WIN32 Sleep(ms); #endif #ifdef __linux__ sleep(ms); #endif } };
27.909091
61
0.443359
[ "vector" ]
68ada5655a3ae3df8bc7f91f6b862dc5483564e2
1,817
h
C
Foundation/NSKeyValueCoding/NSKVCMutableArray.h
bamwu/cocotron
9cda7d719428a8ff940b134e391e511104ee0b5d
[ "MIT" ]
374
2015-03-20T03:04:04.000Z
2022-03-23T11:49:51.000Z
Foundation/NSKeyValueCoding/NSKVCMutableArray.h
bamwu/cocotron
9cda7d719428a8ff940b134e391e511104ee0b5d
[ "MIT" ]
8
2015-05-01T17:10:19.000Z
2018-03-10T13:51:52.000Z
Foundation/NSKeyValueCoding/NSKVCMutableArray.h
bamwu/cocotron
9cda7d719428a8ff940b134e391e511104ee0b5d
[ "MIT" ]
99
2015-03-20T03:04:12.000Z
2022-03-15T03:09:07.000Z
/* Copyright (c) 2006-2007 Johannes Fortmann 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/NSMutableArray.h> @interface NSKVCMutableArray : NSMutableArray { id proxyObject; id key; IMP insert; IMP remove; IMP replace; IMP objectAtIndex; IMP count; IMP accessor; IMP setter; SEL insertSel; SEL removeSel; SEL replaceSel; SEL objectAtIndexSel; SEL countSel; SEL accessorSel; SEL setterSel; } - (id)initWithKey:(id)theKey forProxyObject:(id)object; - (NSUInteger)count; - (id)objectAtIndex:(NSUInteger)index; - (void)addObject:(id)anObject; - (void)insertObject:(id)anObject atIndex:(NSUInteger)index; - (void)removeLastObject; - (void)removeObjectAtIndex:(NSUInteger)index; - (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject; @end
46.589744
463
0.766648
[ "object" ]
68ae2b0bcd68499ba76988b5704da7e3889439be
950
h
C
src/util/colorspace.h
neverfelly/LuisaRender
2f7a2b52908b81b035d17e541df1ce3dbc18b2b8
[ "BSD-3-Clause" ]
null
null
null
src/util/colorspace.h
neverfelly/LuisaRender
2f7a2b52908b81b035d17e541df1ce3dbc18b2b8
[ "BSD-3-Clause" ]
null
null
null
src/util/colorspace.h
neverfelly/LuisaRender
2f7a2b52908b81b035d17e541df1ce3dbc18b2b8
[ "BSD-3-Clause" ]
null
null
null
// // Created by Mike Smith on 2022/1/19. // #pragma once #include <core/basic_types.h> #include <dsl/syntax.h> namespace luisa::render { template<typename T> [[nodiscard]] inline auto cie_xyz_to_linear_srgb(T &&xyz) noexcept { constexpr auto m = make_float3x3( +3.240479f, -0.969256f, +0.055648f, -1.537150f, +1.875991f, -0.204043f, -0.498535f, +0.041556f, +1.057311f); return m * std::forward<T>(xyz); } template<typename T> [[nodiscard]] inline auto srgb_to_cie_y(T &&rgb) noexcept { constexpr auto m = make_float3(0.212671f, 0.715160f, 0.072169f); return dot(m, std::forward<T>(rgb)); } template<typename T> [[nodiscard]] inline auto srgb_to_cie_xyz(T &&rgb) noexcept { constexpr auto m = make_float3x3( 0.412453f, 0.212671f, 0.019334f, 0.357580f, 0.715160f, 0.119193f, 0.180423f, 0.072169f, 0.950227f); return m * std::forward<T>(rgb); } }// namespace luisa::render
25.675676
68
0.656842
[ "render" ]
68b05d4d42faaf0890ba0bc247c28330b5e923d7
41,057
h
C
voxcad-code-2014/GeneratedFiles/ui_vPalette.h
fgolemo/EC14-voxelyze
7fcb1abe4e2d35f996437f833c8febd01e368901
[ "Apache-2.0" ]
null
null
null
voxcad-code-2014/GeneratedFiles/ui_vPalette.h
fgolemo/EC14-voxelyze
7fcb1abe4e2d35f996437f833c8febd01e368901
[ "Apache-2.0" ]
null
null
null
voxcad-code-2014/GeneratedFiles/ui_vPalette.h
fgolemo/EC14-voxelyze
7fcb1abe4e2d35f996437f833c8febd01e368901
[ "Apache-2.0" ]
null
null
null
/******************************************************************************** ** Form generated from reading UI file 'vPalette.ui' ** ** Created: Thu Sep 18 02:14:44 2014 ** by: Qt User Interface Compiler version 4.8.2 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_VPALETTE_H #define UI_VPALETTE_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QCheckBox> #include <QtGui/QComboBox> #include <QtGui/QGroupBox> #include <QtGui/QHBoxLayout> #include <QtGui/QHeaderView> #include <QtGui/QLabel> #include <QtGui/QLineEdit> #include <QtGui/QListView> #include <QtGui/QPushButton> #include <QtGui/QRadioButton> #include <QtGui/QScrollArea> #include <QtGui/QSlider> #include <QtGui/QSpacerItem> #include <QtGui/QSpinBox> #include <QtGui/QTabWidget> #include <QtGui/QVBoxLayout> #include <QtGui/QWidget> QT_BEGIN_NAMESPACE class Ui_PaletteDlg { public: QVBoxLayout *verticalLayout_14; QListView *MaterialList; QHBoxLayout *horizontalLayout_2; QPushButton *AddMatButton; QPushButton *DelMatButton; QPushButton *LoadPalButton; QPushButton *SavePalButton; QSpacerItem *horizontalSpacer; QCheckBox *VisibleCheck; QGroupBox *MatTypeGroup; QVBoxLayout *verticalLayout_4; QHBoxLayout *horizontalLayout_4; QRadioButton *MTBasicRadio; QRadioButton *MTDitherRadio; QRadioButton *MTStructureRadio; QTabWidget *tabProperties; QWidget *AppearanceTab; QVBoxLayout *verticalLayout_5; QHBoxLayout *horizontalLayout; QVBoxLayout *verticalLayout; QSlider *RedSlider; QSlider *GreenSlider; QSlider *BlueSlider; QSlider *AlphaSlider; QVBoxLayout *verticalLayout_2; QSpinBox *RedSpin; QSpinBox *GreenSpin; QSpinBox *BlueSpin; QSpinBox *AlphaSpin; QVBoxLayout *verticalLayout_3; QLabel *RedLabel; QLabel *GreenLabel; QLabel *BlueLabel; QLabel *AlphaLabel; QSpacerItem *verticalSpacer; QWidget *ModelTab; QVBoxLayout *verticalLayout_23; QHBoxLayout *horizontalLayout_14; QComboBox *MatModelCombo; QLabel *MatModelLabel; QHBoxLayout *horizontalLayout_15; QVBoxLayout *verticalLayout_22; QLineEdit *ElasticEdit; QLineEdit *PlasticEdit; QLineEdit *YieldEdit; QVBoxLayout *verticalLayout_21; QLabel *StiffLabel; QLabel *PlasticLabel; QLabel *YieldLabel; QHBoxLayout *horizontalLayout_13; QVBoxLayout *verticalLayout_10; QRadioButton *StressFailRadio; QRadioButton *StrainFailRadio; QVBoxLayout *verticalLayout_19; QLineEdit *FailEdit; QLineEdit *FailStrainEdit; QVBoxLayout *verticalLayout_20; QLabel *FailLabel; QLabel *FailStrainLabel; QPushButton *LoadSSButton; QWidget *PhysicalTab; QHBoxLayout *horizontalLayout_16; QVBoxLayout *verticalLayout_8; QHBoxLayout *horizontalLayout_3; QVBoxLayout *verticalLayout_6; QLineEdit *PoissoEdit; QLineEdit *DensityEdit; QLineEdit *CTEEdit; QLineEdit *TempPhaseEdit; QLineEdit *UsEdit; QLineEdit *UdEdit; QVBoxLayout *verticalLayout_7; QLabel *PoissonLabel; QLabel *DensityLabel; QLabel *CTELabel; QLabel *TempPhaseLabel; QLabel *UsLabel; QLabel *UdLabel; QSpacerItem *verticalSpacer_2; QWidget *DitherTab; QVBoxLayout *verticalLayout_9; QHBoxLayout *horizontalLayout_8; QLabel *Mat1SelLabel; QComboBox *Mat1SelCombo; QHBoxLayout *horizontalLayout_7; QLabel *Mat2SelLabel; QComboBox *Mat2SelCombo; QHBoxLayout *horizontalLayout_5; QSlider *MatPercSlider; QSpinBox *MatPercSpin; QHBoxLayout *horizontalLayout_6; QSpacerItem *horizontalSpacer_2; QLabel *PercLabel; QSpacerItem *verticalSpacer_3; QWidget *StructureTab; QVBoxLayout *verticalLayout_24; QScrollArea *scrollArea; QWidget *scrollAreaWidgetContents; QVBoxLayout *verticalLayout_18; QHBoxLayout *horizontalLayout_9; QPushButton *ImportButton; QPushButton *ExportButton; QHBoxLayout *horizontalLayout_12; QVBoxLayout *verticalLayout_16; QLabel *DimLabel; QHBoxLayout *horizontalLayout_11; QVBoxLayout *verticalLayout_12; QSpinBox *XDimSpin; QSpinBox *YDimSpin; QSpinBox *ZDimSpin; QVBoxLayout *verticalLayout_11; QLabel *XDimLabel; QLabel *YDimLabel; QLabel *ZDimLabel; QSpacerItem *horizontalSpacer_3; QVBoxLayout *verticalLayout_17; QLabel *OffLabel; QHBoxLayout *horizontalLayout_10; QVBoxLayout *verticalLayout_13; QSpinBox *XOffSpin; QSpinBox *YOffSpin; QSpinBox *ZOffSpin; QVBoxLayout *verticalLayout_15; QLabel *XOffLabel; QLabel *YOffLabel; QLabel *ZOffLabel; QGroupBox *groupBox; QHBoxLayout *horizontalLayout_17; QRadioButton *RxRadio; QRadioButton *RyRadio; QRadioButton *RzRadio; QGroupBox *groupBox_2; QHBoxLayout *horizontalLayout_18; QRadioButton *R0Radio; QRadioButton *R90Radio; QRadioButton *R180Radio; QRadioButton *R270Radio; QPushButton *EditStructureButton; QSpacerItem *verticalSpacer_4; void setupUi(QWidget *PaletteDlg) { if (PaletteDlg->objectName().isEmpty()) PaletteDlg->setObjectName(QString::fromUtf8("PaletteDlg")); PaletteDlg->resize(220, 621); QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(PaletteDlg->sizePolicy().hasHeightForWidth()); PaletteDlg->setSizePolicy(sizePolicy); PaletteDlg->setMinimumSize(QSize(0, 0)); PaletteDlg->setMaximumSize(QSize(5000, 5000)); verticalLayout_14 = new QVBoxLayout(PaletteDlg); verticalLayout_14->setObjectName(QString::fromUtf8("verticalLayout_14")); MaterialList = new QListView(PaletteDlg); MaterialList->setObjectName(QString::fromUtf8("MaterialList")); MaterialList->setIconSize(QSize(16, 16)); verticalLayout_14->addWidget(MaterialList); horizontalLayout_2 = new QHBoxLayout(); horizontalLayout_2->setObjectName(QString::fromUtf8("horizontalLayout_2")); AddMatButton = new QPushButton(PaletteDlg); AddMatButton->setObjectName(QString::fromUtf8("AddMatButton")); AddMatButton->setMaximumSize(QSize(25, 16777215)); AddMatButton->setBaseSize(QSize(0, 0)); horizontalLayout_2->addWidget(AddMatButton); DelMatButton = new QPushButton(PaletteDlg); DelMatButton->setObjectName(QString::fromUtf8("DelMatButton")); DelMatButton->setMaximumSize(QSize(25, 16777215)); horizontalLayout_2->addWidget(DelMatButton); LoadPalButton = new QPushButton(PaletteDlg); LoadPalButton->setObjectName(QString::fromUtf8("LoadPalButton")); LoadPalButton->setMaximumSize(QSize(40, 16777215)); horizontalLayout_2->addWidget(LoadPalButton); SavePalButton = new QPushButton(PaletteDlg); SavePalButton->setObjectName(QString::fromUtf8("SavePalButton")); SavePalButton->setMaximumSize(QSize(40, 16777215)); horizontalLayout_2->addWidget(SavePalButton); horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_2->addItem(horizontalSpacer); verticalLayout_14->addLayout(horizontalLayout_2); VisibleCheck = new QCheckBox(PaletteDlg); VisibleCheck->setObjectName(QString::fromUtf8("VisibleCheck")); verticalLayout_14->addWidget(VisibleCheck); MatTypeGroup = new QGroupBox(PaletteDlg); MatTypeGroup->setObjectName(QString::fromUtf8("MatTypeGroup")); verticalLayout_4 = new QVBoxLayout(MatTypeGroup); verticalLayout_4->setObjectName(QString::fromUtf8("verticalLayout_4")); horizontalLayout_4 = new QHBoxLayout(); horizontalLayout_4->setObjectName(QString::fromUtf8("horizontalLayout_4")); MTBasicRadio = new QRadioButton(MatTypeGroup); MTBasicRadio->setObjectName(QString::fromUtf8("MTBasicRadio")); horizontalLayout_4->addWidget(MTBasicRadio); MTDitherRadio = new QRadioButton(MatTypeGroup); MTDitherRadio->setObjectName(QString::fromUtf8("MTDitherRadio")); horizontalLayout_4->addWidget(MTDitherRadio); MTStructureRadio = new QRadioButton(MatTypeGroup); MTStructureRadio->setObjectName(QString::fromUtf8("MTStructureRadio")); horizontalLayout_4->addWidget(MTStructureRadio); verticalLayout_4->addLayout(horizontalLayout_4); verticalLayout_14->addWidget(MatTypeGroup); tabProperties = new QTabWidget(PaletteDlg); tabProperties->setObjectName(QString::fromUtf8("tabProperties")); tabProperties->setTabPosition(QTabWidget::North); AppearanceTab = new QWidget(); AppearanceTab->setObjectName(QString::fromUtf8("AppearanceTab")); verticalLayout_5 = new QVBoxLayout(AppearanceTab); verticalLayout_5->setObjectName(QString::fromUtf8("verticalLayout_5")); horizontalLayout = new QHBoxLayout(); horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout")); verticalLayout = new QVBoxLayout(); verticalLayout->setObjectName(QString::fromUtf8("verticalLayout")); RedSlider = new QSlider(AppearanceTab); RedSlider->setObjectName(QString::fromUtf8("RedSlider")); RedSlider->setMaximum(255); RedSlider->setOrientation(Qt::Horizontal); verticalLayout->addWidget(RedSlider); GreenSlider = new QSlider(AppearanceTab); GreenSlider->setObjectName(QString::fromUtf8("GreenSlider")); GreenSlider->setMaximum(255); GreenSlider->setOrientation(Qt::Horizontal); verticalLayout->addWidget(GreenSlider); BlueSlider = new QSlider(AppearanceTab); BlueSlider->setObjectName(QString::fromUtf8("BlueSlider")); BlueSlider->setMaximum(255); BlueSlider->setOrientation(Qt::Horizontal); verticalLayout->addWidget(BlueSlider); AlphaSlider = new QSlider(AppearanceTab); AlphaSlider->setObjectName(QString::fromUtf8("AlphaSlider")); AlphaSlider->setMaximum(255); AlphaSlider->setOrientation(Qt::Horizontal); verticalLayout->addWidget(AlphaSlider); horizontalLayout->addLayout(verticalLayout); verticalLayout_2 = new QVBoxLayout(); verticalLayout_2->setObjectName(QString::fromUtf8("verticalLayout_2")); RedSpin = new QSpinBox(AppearanceTab); RedSpin->setObjectName(QString::fromUtf8("RedSpin")); RedSpin->setMaximum(255); RedSpin->setSingleStep(1); verticalLayout_2->addWidget(RedSpin); GreenSpin = new QSpinBox(AppearanceTab); GreenSpin->setObjectName(QString::fromUtf8("GreenSpin")); GreenSpin->setMaximum(255); GreenSpin->setSingleStep(1); verticalLayout_2->addWidget(GreenSpin); BlueSpin = new QSpinBox(AppearanceTab); BlueSpin->setObjectName(QString::fromUtf8("BlueSpin")); BlueSpin->setMaximum(255); BlueSpin->setSingleStep(1); verticalLayout_2->addWidget(BlueSpin); AlphaSpin = new QSpinBox(AppearanceTab); AlphaSpin->setObjectName(QString::fromUtf8("AlphaSpin")); AlphaSpin->setMaximum(255); AlphaSpin->setSingleStep(1); verticalLayout_2->addWidget(AlphaSpin); horizontalLayout->addLayout(verticalLayout_2); verticalLayout_3 = new QVBoxLayout(); verticalLayout_3->setObjectName(QString::fromUtf8("verticalLayout_3")); RedLabel = new QLabel(AppearanceTab); RedLabel->setObjectName(QString::fromUtf8("RedLabel")); verticalLayout_3->addWidget(RedLabel); GreenLabel = new QLabel(AppearanceTab); GreenLabel->setObjectName(QString::fromUtf8("GreenLabel")); verticalLayout_3->addWidget(GreenLabel); BlueLabel = new QLabel(AppearanceTab); BlueLabel->setObjectName(QString::fromUtf8("BlueLabel")); verticalLayout_3->addWidget(BlueLabel); AlphaLabel = new QLabel(AppearanceTab); AlphaLabel->setObjectName(QString::fromUtf8("AlphaLabel")); verticalLayout_3->addWidget(AlphaLabel); horizontalLayout->addLayout(verticalLayout_3); verticalLayout_5->addLayout(horizontalLayout); verticalSpacer = new QSpacerItem(20, 51, QSizePolicy::Minimum, QSizePolicy::Expanding); verticalLayout_5->addItem(verticalSpacer); tabProperties->addTab(AppearanceTab, QString()); ModelTab = new QWidget(); ModelTab->setObjectName(QString::fromUtf8("ModelTab")); verticalLayout_23 = new QVBoxLayout(ModelTab); verticalLayout_23->setObjectName(QString::fromUtf8("verticalLayout_23")); horizontalLayout_14 = new QHBoxLayout(); horizontalLayout_14->setObjectName(QString::fromUtf8("horizontalLayout_14")); MatModelCombo = new QComboBox(ModelTab); MatModelCombo->setObjectName(QString::fromUtf8("MatModelCombo")); horizontalLayout_14->addWidget(MatModelCombo); MatModelLabel = new QLabel(ModelTab); MatModelLabel->setObjectName(QString::fromUtf8("MatModelLabel")); horizontalLayout_14->addWidget(MatModelLabel); verticalLayout_23->addLayout(horizontalLayout_14); horizontalLayout_15 = new QHBoxLayout(); horizontalLayout_15->setObjectName(QString::fromUtf8("horizontalLayout_15")); verticalLayout_22 = new QVBoxLayout(); verticalLayout_22->setObjectName(QString::fromUtf8("verticalLayout_22")); ElasticEdit = new QLineEdit(ModelTab); ElasticEdit->setObjectName(QString::fromUtf8("ElasticEdit")); verticalLayout_22->addWidget(ElasticEdit); PlasticEdit = new QLineEdit(ModelTab); PlasticEdit->setObjectName(QString::fromUtf8("PlasticEdit")); verticalLayout_22->addWidget(PlasticEdit); YieldEdit = new QLineEdit(ModelTab); YieldEdit->setObjectName(QString::fromUtf8("YieldEdit")); verticalLayout_22->addWidget(YieldEdit); horizontalLayout_15->addLayout(verticalLayout_22); verticalLayout_21 = new QVBoxLayout(); verticalLayout_21->setObjectName(QString::fromUtf8("verticalLayout_21")); StiffLabel = new QLabel(ModelTab); StiffLabel->setObjectName(QString::fromUtf8("StiffLabel")); verticalLayout_21->addWidget(StiffLabel); PlasticLabel = new QLabel(ModelTab); PlasticLabel->setObjectName(QString::fromUtf8("PlasticLabel")); verticalLayout_21->addWidget(PlasticLabel); YieldLabel = new QLabel(ModelTab); YieldLabel->setObjectName(QString::fromUtf8("YieldLabel")); verticalLayout_21->addWidget(YieldLabel); horizontalLayout_15->addLayout(verticalLayout_21); verticalLayout_23->addLayout(horizontalLayout_15); horizontalLayout_13 = new QHBoxLayout(); horizontalLayout_13->setObjectName(QString::fromUtf8("horizontalLayout_13")); verticalLayout_10 = new QVBoxLayout(); verticalLayout_10->setSpacing(10); verticalLayout_10->setObjectName(QString::fromUtf8("verticalLayout_10")); StressFailRadio = new QRadioButton(ModelTab); StressFailRadio->setObjectName(QString::fromUtf8("StressFailRadio")); StressFailRadio->setMaximumSize(QSize(13, 16777215)); verticalLayout_10->addWidget(StressFailRadio); StrainFailRadio = new QRadioButton(ModelTab); StrainFailRadio->setObjectName(QString::fromUtf8("StrainFailRadio")); QSizePolicy sizePolicy1(QSizePolicy::Minimum, QSizePolicy::Fixed); sizePolicy1.setHorizontalStretch(0); sizePolicy1.setVerticalStretch(0); sizePolicy1.setHeightForWidth(StrainFailRadio->sizePolicy().hasHeightForWidth()); StrainFailRadio->setSizePolicy(sizePolicy1); StrainFailRadio->setMaximumSize(QSize(13, 16777215)); verticalLayout_10->addWidget(StrainFailRadio); horizontalLayout_13->addLayout(verticalLayout_10); verticalLayout_19 = new QVBoxLayout(); verticalLayout_19->setObjectName(QString::fromUtf8("verticalLayout_19")); FailEdit = new QLineEdit(ModelTab); FailEdit->setObjectName(QString::fromUtf8("FailEdit")); verticalLayout_19->addWidget(FailEdit); FailStrainEdit = new QLineEdit(ModelTab); FailStrainEdit->setObjectName(QString::fromUtf8("FailStrainEdit")); verticalLayout_19->addWidget(FailStrainEdit); horizontalLayout_13->addLayout(verticalLayout_19); verticalLayout_20 = new QVBoxLayout(); verticalLayout_20->setObjectName(QString::fromUtf8("verticalLayout_20")); FailLabel = new QLabel(ModelTab); FailLabel->setObjectName(QString::fromUtf8("FailLabel")); verticalLayout_20->addWidget(FailLabel); FailStrainLabel = new QLabel(ModelTab); FailStrainLabel->setObjectName(QString::fromUtf8("FailStrainLabel")); verticalLayout_20->addWidget(FailStrainLabel); horizontalLayout_13->addLayout(verticalLayout_20); verticalLayout_23->addLayout(horizontalLayout_13); LoadSSButton = new QPushButton(ModelTab); LoadSSButton->setObjectName(QString::fromUtf8("LoadSSButton")); verticalLayout_23->addWidget(LoadSSButton); tabProperties->addTab(ModelTab, QString()); PhysicalTab = new QWidget(); PhysicalTab->setObjectName(QString::fromUtf8("PhysicalTab")); horizontalLayout_16 = new QHBoxLayout(PhysicalTab); horizontalLayout_16->setObjectName(QString::fromUtf8("horizontalLayout_16")); verticalLayout_8 = new QVBoxLayout(); verticalLayout_8->setObjectName(QString::fromUtf8("verticalLayout_8")); horizontalLayout_3 = new QHBoxLayout(); horizontalLayout_3->setObjectName(QString::fromUtf8("horizontalLayout_3")); verticalLayout_6 = new QVBoxLayout(); verticalLayout_6->setObjectName(QString::fromUtf8("verticalLayout_6")); PoissoEdit = new QLineEdit(PhysicalTab); PoissoEdit->setObjectName(QString::fromUtf8("PoissoEdit")); verticalLayout_6->addWidget(PoissoEdit); DensityEdit = new QLineEdit(PhysicalTab); DensityEdit->setObjectName(QString::fromUtf8("DensityEdit")); verticalLayout_6->addWidget(DensityEdit); CTEEdit = new QLineEdit(PhysicalTab); CTEEdit->setObjectName(QString::fromUtf8("CTEEdit")); verticalLayout_6->addWidget(CTEEdit); TempPhaseEdit = new QLineEdit(PhysicalTab); TempPhaseEdit->setObjectName(QString::fromUtf8("TempPhaseEdit")); verticalLayout_6->addWidget(TempPhaseEdit); UsEdit = new QLineEdit(PhysicalTab); UsEdit->setObjectName(QString::fromUtf8("UsEdit")); verticalLayout_6->addWidget(UsEdit); UdEdit = new QLineEdit(PhysicalTab); UdEdit->setObjectName(QString::fromUtf8("UdEdit")); verticalLayout_6->addWidget(UdEdit); horizontalLayout_3->addLayout(verticalLayout_6); verticalLayout_7 = new QVBoxLayout(); verticalLayout_7->setObjectName(QString::fromUtf8("verticalLayout_7")); PoissonLabel = new QLabel(PhysicalTab); PoissonLabel->setObjectName(QString::fromUtf8("PoissonLabel")); verticalLayout_7->addWidget(PoissonLabel); DensityLabel = new QLabel(PhysicalTab); DensityLabel->setObjectName(QString::fromUtf8("DensityLabel")); verticalLayout_7->addWidget(DensityLabel); CTELabel = new QLabel(PhysicalTab); CTELabel->setObjectName(QString::fromUtf8("CTELabel")); verticalLayout_7->addWidget(CTELabel); TempPhaseLabel = new QLabel(PhysicalTab); TempPhaseLabel->setObjectName(QString::fromUtf8("TempPhaseLabel")); verticalLayout_7->addWidget(TempPhaseLabel); UsLabel = new QLabel(PhysicalTab); UsLabel->setObjectName(QString::fromUtf8("UsLabel")); verticalLayout_7->addWidget(UsLabel); UdLabel = new QLabel(PhysicalTab); UdLabel->setObjectName(QString::fromUtf8("UdLabel")); verticalLayout_7->addWidget(UdLabel); horizontalLayout_3->addLayout(verticalLayout_7); verticalLayout_8->addLayout(horizontalLayout_3); verticalSpacer_2 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); verticalLayout_8->addItem(verticalSpacer_2); horizontalLayout_16->addLayout(verticalLayout_8); tabProperties->addTab(PhysicalTab, QString()); DitherTab = new QWidget(); DitherTab->setObjectName(QString::fromUtf8("DitherTab")); verticalLayout_9 = new QVBoxLayout(DitherTab); verticalLayout_9->setObjectName(QString::fromUtf8("verticalLayout_9")); horizontalLayout_8 = new QHBoxLayout(); horizontalLayout_8->setObjectName(QString::fromUtf8("horizontalLayout_8")); Mat1SelLabel = new QLabel(DitherTab); Mat1SelLabel->setObjectName(QString::fromUtf8("Mat1SelLabel")); horizontalLayout_8->addWidget(Mat1SelLabel); Mat1SelCombo = new QComboBox(DitherTab); Mat1SelCombo->setObjectName(QString::fromUtf8("Mat1SelCombo")); QSizePolicy sizePolicy2(QSizePolicy::Expanding, QSizePolicy::Fixed); sizePolicy2.setHorizontalStretch(0); sizePolicy2.setVerticalStretch(0); sizePolicy2.setHeightForWidth(Mat1SelCombo->sizePolicy().hasHeightForWidth()); Mat1SelCombo->setSizePolicy(sizePolicy2); horizontalLayout_8->addWidget(Mat1SelCombo); verticalLayout_9->addLayout(horizontalLayout_8); horizontalLayout_7 = new QHBoxLayout(); horizontalLayout_7->setObjectName(QString::fromUtf8("horizontalLayout_7")); Mat2SelLabel = new QLabel(DitherTab); Mat2SelLabel->setObjectName(QString::fromUtf8("Mat2SelLabel")); horizontalLayout_7->addWidget(Mat2SelLabel); Mat2SelCombo = new QComboBox(DitherTab); Mat2SelCombo->setObjectName(QString::fromUtf8("Mat2SelCombo")); sizePolicy2.setHeightForWidth(Mat2SelCombo->sizePolicy().hasHeightForWidth()); Mat2SelCombo->setSizePolicy(sizePolicy2); horizontalLayout_7->addWidget(Mat2SelCombo); verticalLayout_9->addLayout(horizontalLayout_7); horizontalLayout_5 = new QHBoxLayout(); horizontalLayout_5->setObjectName(QString::fromUtf8("horizontalLayout_5")); MatPercSlider = new QSlider(DitherTab); MatPercSlider->setObjectName(QString::fromUtf8("MatPercSlider")); MatPercSlider->setMaximum(100); MatPercSlider->setOrientation(Qt::Horizontal); horizontalLayout_5->addWidget(MatPercSlider); MatPercSpin = new QSpinBox(DitherTab); MatPercSpin->setObjectName(QString::fromUtf8("MatPercSpin")); MatPercSpin->setMaximum(100); horizontalLayout_5->addWidget(MatPercSpin); verticalLayout_9->addLayout(horizontalLayout_5); horizontalLayout_6 = new QHBoxLayout(); horizontalLayout_6->setObjectName(QString::fromUtf8("horizontalLayout_6")); horizontalSpacer_2 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_6->addItem(horizontalSpacer_2); PercLabel = new QLabel(DitherTab); PercLabel->setObjectName(QString::fromUtf8("PercLabel")); horizontalLayout_6->addWidget(PercLabel); verticalLayout_9->addLayout(horizontalLayout_6); verticalSpacer_3 = new QSpacerItem(20, 55, QSizePolicy::Minimum, QSizePolicy::Expanding); verticalLayout_9->addItem(verticalSpacer_3); tabProperties->addTab(DitherTab, QString()); StructureTab = new QWidget(); StructureTab->setObjectName(QString::fromUtf8("StructureTab")); verticalLayout_24 = new QVBoxLayout(StructureTab); verticalLayout_24->setSpacing(0); verticalLayout_24->setContentsMargins(0, 0, 0, 0); verticalLayout_24->setObjectName(QString::fromUtf8("verticalLayout_24")); scrollArea = new QScrollArea(StructureTab); scrollArea->setObjectName(QString::fromUtf8("scrollArea")); scrollArea->setWidgetResizable(true); scrollAreaWidgetContents = new QWidget(); scrollAreaWidgetContents->setObjectName(QString::fromUtf8("scrollAreaWidgetContents")); scrollAreaWidgetContents->setGeometry(QRect(0, 0, 194, 270)); verticalLayout_18 = new QVBoxLayout(scrollAreaWidgetContents); verticalLayout_18->setObjectName(QString::fromUtf8("verticalLayout_18")); horizontalLayout_9 = new QHBoxLayout(); horizontalLayout_9->setObjectName(QString::fromUtf8("horizontalLayout_9")); ImportButton = new QPushButton(scrollAreaWidgetContents); ImportButton->setObjectName(QString::fromUtf8("ImportButton")); horizontalLayout_9->addWidget(ImportButton); ExportButton = new QPushButton(scrollAreaWidgetContents); ExportButton->setObjectName(QString::fromUtf8("ExportButton")); horizontalLayout_9->addWidget(ExportButton); verticalLayout_18->addLayout(horizontalLayout_9); horizontalLayout_12 = new QHBoxLayout(); horizontalLayout_12->setObjectName(QString::fromUtf8("horizontalLayout_12")); verticalLayout_16 = new QVBoxLayout(); verticalLayout_16->setObjectName(QString::fromUtf8("verticalLayout_16")); DimLabel = new QLabel(scrollAreaWidgetContents); DimLabel->setObjectName(QString::fromUtf8("DimLabel")); verticalLayout_16->addWidget(DimLabel); horizontalLayout_11 = new QHBoxLayout(); horizontalLayout_11->setObjectName(QString::fromUtf8("horizontalLayout_11")); verticalLayout_12 = new QVBoxLayout(); verticalLayout_12->setObjectName(QString::fromUtf8("verticalLayout_12")); XDimSpin = new QSpinBox(scrollAreaWidgetContents); XDimSpin->setObjectName(QString::fromUtf8("XDimSpin")); XDimSpin->setMinimum(1); verticalLayout_12->addWidget(XDimSpin); YDimSpin = new QSpinBox(scrollAreaWidgetContents); YDimSpin->setObjectName(QString::fromUtf8("YDimSpin")); YDimSpin->setMinimum(1); verticalLayout_12->addWidget(YDimSpin); ZDimSpin = new QSpinBox(scrollAreaWidgetContents); ZDimSpin->setObjectName(QString::fromUtf8("ZDimSpin")); ZDimSpin->setMinimum(1); verticalLayout_12->addWidget(ZDimSpin); horizontalLayout_11->addLayout(verticalLayout_12); verticalLayout_11 = new QVBoxLayout(); verticalLayout_11->setObjectName(QString::fromUtf8("verticalLayout_11")); XDimLabel = new QLabel(scrollAreaWidgetContents); XDimLabel->setObjectName(QString::fromUtf8("XDimLabel")); verticalLayout_11->addWidget(XDimLabel); YDimLabel = new QLabel(scrollAreaWidgetContents); YDimLabel->setObjectName(QString::fromUtf8("YDimLabel")); verticalLayout_11->addWidget(YDimLabel); ZDimLabel = new QLabel(scrollAreaWidgetContents); ZDimLabel->setObjectName(QString::fromUtf8("ZDimLabel")); ZDimLabel->setFrameShape(QFrame::NoFrame); verticalLayout_11->addWidget(ZDimLabel); horizontalLayout_11->addLayout(verticalLayout_11); verticalLayout_16->addLayout(horizontalLayout_11); horizontalLayout_12->addLayout(verticalLayout_16); horizontalSpacer_3 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_12->addItem(horizontalSpacer_3); verticalLayout_17 = new QVBoxLayout(); verticalLayout_17->setObjectName(QString::fromUtf8("verticalLayout_17")); OffLabel = new QLabel(scrollAreaWidgetContents); OffLabel->setObjectName(QString::fromUtf8("OffLabel")); verticalLayout_17->addWidget(OffLabel); horizontalLayout_10 = new QHBoxLayout(); horizontalLayout_10->setObjectName(QString::fromUtf8("horizontalLayout_10")); verticalLayout_13 = new QVBoxLayout(); verticalLayout_13->setObjectName(QString::fromUtf8("verticalLayout_13")); XOffSpin = new QSpinBox(scrollAreaWidgetContents); XOffSpin->setObjectName(QString::fromUtf8("XOffSpin")); verticalLayout_13->addWidget(XOffSpin); YOffSpin = new QSpinBox(scrollAreaWidgetContents); YOffSpin->setObjectName(QString::fromUtf8("YOffSpin")); verticalLayout_13->addWidget(YOffSpin); ZOffSpin = new QSpinBox(scrollAreaWidgetContents); ZOffSpin->setObjectName(QString::fromUtf8("ZOffSpin")); verticalLayout_13->addWidget(ZOffSpin); horizontalLayout_10->addLayout(verticalLayout_13); verticalLayout_15 = new QVBoxLayout(); verticalLayout_15->setObjectName(QString::fromUtf8("verticalLayout_15")); XOffLabel = new QLabel(scrollAreaWidgetContents); XOffLabel->setObjectName(QString::fromUtf8("XOffLabel")); verticalLayout_15->addWidget(XOffLabel); YOffLabel = new QLabel(scrollAreaWidgetContents); YOffLabel->setObjectName(QString::fromUtf8("YOffLabel")); verticalLayout_15->addWidget(YOffLabel); ZOffLabel = new QLabel(scrollAreaWidgetContents); ZOffLabel->setObjectName(QString::fromUtf8("ZOffLabel")); ZOffLabel->setFrameShape(QFrame::NoFrame); verticalLayout_15->addWidget(ZOffLabel); horizontalLayout_10->addLayout(verticalLayout_15); verticalLayout_17->addLayout(horizontalLayout_10); horizontalLayout_12->addLayout(verticalLayout_17); verticalLayout_18->addLayout(horizontalLayout_12); groupBox = new QGroupBox(scrollAreaWidgetContents); groupBox->setObjectName(QString::fromUtf8("groupBox")); horizontalLayout_17 = new QHBoxLayout(groupBox); horizontalLayout_17->setContentsMargins(1, 1, 1, 1); horizontalLayout_17->setObjectName(QString::fromUtf8("horizontalLayout_17")); RxRadio = new QRadioButton(groupBox); RxRadio->setObjectName(QString::fromUtf8("RxRadio")); horizontalLayout_17->addWidget(RxRadio); RyRadio = new QRadioButton(groupBox); RyRadio->setObjectName(QString::fromUtf8("RyRadio")); horizontalLayout_17->addWidget(RyRadio); RzRadio = new QRadioButton(groupBox); RzRadio->setObjectName(QString::fromUtf8("RzRadio")); horizontalLayout_17->addWidget(RzRadio); verticalLayout_18->addWidget(groupBox); groupBox_2 = new QGroupBox(scrollAreaWidgetContents); groupBox_2->setObjectName(QString::fromUtf8("groupBox_2")); horizontalLayout_18 = new QHBoxLayout(groupBox_2); horizontalLayout_18->setSpacing(3); horizontalLayout_18->setContentsMargins(1, 1, 1, 1); horizontalLayout_18->setObjectName(QString::fromUtf8("horizontalLayout_18")); R0Radio = new QRadioButton(groupBox_2); R0Radio->setObjectName(QString::fromUtf8("R0Radio")); horizontalLayout_18->addWidget(R0Radio); R90Radio = new QRadioButton(groupBox_2); R90Radio->setObjectName(QString::fromUtf8("R90Radio")); horizontalLayout_18->addWidget(R90Radio); R180Radio = new QRadioButton(groupBox_2); R180Radio->setObjectName(QString::fromUtf8("R180Radio")); horizontalLayout_18->addWidget(R180Radio); R270Radio = new QRadioButton(groupBox_2); R270Radio->setObjectName(QString::fromUtf8("R270Radio")); horizontalLayout_18->addWidget(R270Radio); verticalLayout_18->addWidget(groupBox_2); EditStructureButton = new QPushButton(scrollAreaWidgetContents); EditStructureButton->setObjectName(QString::fromUtf8("EditStructureButton")); EditStructureButton->setCheckable(false); verticalLayout_18->addWidget(EditStructureButton); verticalSpacer_4 = new QSpacerItem(20, 10, QSizePolicy::Minimum, QSizePolicy::Expanding); verticalLayout_18->addItem(verticalSpacer_4); scrollArea->setWidget(scrollAreaWidgetContents); verticalLayout_24->addWidget(scrollArea); tabProperties->addTab(StructureTab, QString()); verticalLayout_14->addWidget(tabProperties); retranslateUi(PaletteDlg); QObject::connect(RedSlider, SIGNAL(valueChanged(int)), RedSpin, SLOT(setValue(int))); QObject::connect(RedSpin, SIGNAL(valueChanged(int)), RedSlider, SLOT(setValue(int))); QObject::connect(GreenSlider, SIGNAL(valueChanged(int)), GreenSpin, SLOT(setValue(int))); QObject::connect(GreenSpin, SIGNAL(valueChanged(int)), GreenSlider, SLOT(setValue(int))); QObject::connect(BlueSlider, SIGNAL(valueChanged(int)), BlueSpin, SLOT(setValue(int))); QObject::connect(BlueSpin, SIGNAL(valueChanged(int)), BlueSlider, SLOT(setValue(int))); QObject::connect(AlphaSpin, SIGNAL(valueChanged(int)), AlphaSlider, SLOT(setValue(int))); QObject::connect(AlphaSlider, SIGNAL(valueChanged(int)), AlphaSpin, SLOT(setValue(int))); QObject::connect(MatPercSpin, SIGNAL(valueChanged(int)), MatPercSlider, SLOT(setValue(int))); QObject::connect(MatPercSlider, SIGNAL(valueChanged(int)), MatPercSpin, SLOT(setValue(int))); tabProperties->setCurrentIndex(4); QMetaObject::connectSlotsByName(PaletteDlg); } // setupUi void retranslateUi(QWidget *PaletteDlg) { PaletteDlg->setWindowTitle(QApplication::translate("PaletteDlg", "Palette Editor", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP AddMatButton->setToolTip(QApplication::translate("PaletteDlg", "Add Material", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP AddMatButton->setText(QApplication::translate("PaletteDlg", "+", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP DelMatButton->setToolTip(QApplication::translate("PaletteDlg", "Delete Material", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP DelMatButton->setText(QApplication::translate("PaletteDlg", "-", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP LoadPalButton->setToolTip(QApplication::translate("PaletteDlg", "Load Palette", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP LoadPalButton->setText(QApplication::translate("PaletteDlg", "Load", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP SavePalButton->setToolTip(QApplication::translate("PaletteDlg", "Save Palette", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP SavePalButton->setText(QApplication::translate("PaletteDlg", "Save", 0, QApplication::UnicodeUTF8)); VisibleCheck->setText(QApplication::translate("PaletteDlg", "Visible", 0, QApplication::UnicodeUTF8)); MatTypeGroup->setTitle(QApplication::translate("PaletteDlg", "Material Type", 0, QApplication::UnicodeUTF8)); MTBasicRadio->setText(QApplication::translate("PaletteDlg", "Basic", 0, QApplication::UnicodeUTF8)); MTDitherRadio->setText(QApplication::translate("PaletteDlg", "Dither", 0, QApplication::UnicodeUTF8)); MTStructureRadio->setText(QApplication::translate("PaletteDlg", "Structure", 0, QApplication::UnicodeUTF8)); RedLabel->setText(QApplication::translate("PaletteDlg", "Red", 0, QApplication::UnicodeUTF8)); GreenLabel->setText(QApplication::translate("PaletteDlg", "Green", 0, QApplication::UnicodeUTF8)); BlueLabel->setText(QApplication::translate("PaletteDlg", "Blue", 0, QApplication::UnicodeUTF8)); AlphaLabel->setText(QApplication::translate("PaletteDlg", "Alpha", 0, QApplication::UnicodeUTF8)); tabProperties->setTabText(tabProperties->indexOf(AppearanceTab), QApplication::translate("PaletteDlg", "Appearance", 0, QApplication::UnicodeUTF8)); MatModelLabel->setText(QApplication::translate("PaletteDlg", "Material Model", 0, QApplication::UnicodeUTF8)); PlasticEdit->setText(QString()); StiffLabel->setText(QApplication::translate("PaletteDlg", "Elastic Modulus (MPa)", 0, QApplication::UnicodeUTF8)); PlasticLabel->setText(QApplication::translate("PaletteDlg", "Plastic Modulus (MPa)", 0, QApplication::UnicodeUTF8)); YieldLabel->setText(QApplication::translate("PaletteDlg", "Yield Stress (MPa)", 0, QApplication::UnicodeUTF8)); StressFailRadio->setText(QString()); StrainFailRadio->setText(QString()); FailLabel->setText(QApplication::translate("PaletteDlg", "Failure Stress (MPa)", 0, QApplication::UnicodeUTF8)); FailStrainLabel->setText(QApplication::translate("PaletteDlg", "Failure Strain (m/m)", 0, QApplication::UnicodeUTF8)); LoadSSButton->setText(QApplication::translate("PaletteDlg", "Load Stress/Strain Data", 0, QApplication::UnicodeUTF8)); tabProperties->setTabText(tabProperties->indexOf(ModelTab), QApplication::translate("PaletteDlg", "Model", 0, QApplication::UnicodeUTF8)); PoissonLabel->setText(QApplication::translate("PaletteDlg", "Poissons Ratio", 0, QApplication::UnicodeUTF8)); DensityLabel->setText(QApplication::translate("PaletteDlg", "Density (Kg/m^3)", 0, QApplication::UnicodeUTF8)); CTELabel->setText(QApplication::translate("PaletteDlg", "CTE (1/deg C)", 0, QApplication::UnicodeUTF8)); TempPhaseLabel->setText(QApplication::translate("PaletteDlg", "Temp Phase (rad)", 0, QApplication::UnicodeUTF8)); UsLabel->setText(QApplication::translate("PaletteDlg", "Static Fric Coeff", 0, QApplication::UnicodeUTF8)); UdLabel->setText(QApplication::translate("PaletteDlg", "Dynamic Fric Coeff", 0, QApplication::UnicodeUTF8)); tabProperties->setTabText(tabProperties->indexOf(PhysicalTab), QApplication::translate("PaletteDlg", "Physical", 0, QApplication::UnicodeUTF8)); Mat1SelLabel->setText(QApplication::translate("PaletteDlg", "Material 1:", 0, QApplication::UnicodeUTF8)); Mat2SelLabel->setText(QApplication::translate("PaletteDlg", "Material 2:", 0, QApplication::UnicodeUTF8)); PercLabel->setText(QApplication::translate("PaletteDlg", "% Mat1", 0, QApplication::UnicodeUTF8)); tabProperties->setTabText(tabProperties->indexOf(DitherTab), QApplication::translate("PaletteDlg", "Dither", 0, QApplication::UnicodeUTF8)); ImportButton->setText(QApplication::translate("PaletteDlg", "Import", 0, QApplication::UnicodeUTF8)); ExportButton->setText(QApplication::translate("PaletteDlg", "Export", 0, QApplication::UnicodeUTF8)); DimLabel->setText(QApplication::translate("PaletteDlg", "Dim (voxels)", 0, QApplication::UnicodeUTF8)); XDimLabel->setText(QApplication::translate("PaletteDlg", "X", 0, QApplication::UnicodeUTF8)); YDimLabel->setText(QApplication::translate("PaletteDlg", "Y", 0, QApplication::UnicodeUTF8)); ZDimLabel->setText(QApplication::translate("PaletteDlg", "Z", 0, QApplication::UnicodeUTF8)); OffLabel->setText(QApplication::translate("PaletteDlg", "Offset (voxels)", 0, QApplication::UnicodeUTF8)); XOffLabel->setText(QApplication::translate("PaletteDlg", "X", 0, QApplication::UnicodeUTF8)); YOffLabel->setText(QApplication::translate("PaletteDlg", "Y", 0, QApplication::UnicodeUTF8)); ZOffLabel->setText(QApplication::translate("PaletteDlg", "Z", 0, QApplication::UnicodeUTF8)); groupBox->setTitle(QApplication::translate("PaletteDlg", "Rotate Axis", 0, QApplication::UnicodeUTF8)); RxRadio->setText(QApplication::translate("PaletteDlg", "X", 0, QApplication::UnicodeUTF8)); RyRadio->setText(QApplication::translate("PaletteDlg", "Y", 0, QApplication::UnicodeUTF8)); RzRadio->setText(QApplication::translate("PaletteDlg", "Z", 0, QApplication::UnicodeUTF8)); groupBox_2->setTitle(QApplication::translate("PaletteDlg", "Rotate degrees", 0, QApplication::UnicodeUTF8)); R0Radio->setText(QApplication::translate("PaletteDlg", "0", 0, QApplication::UnicodeUTF8)); R90Radio->setText(QApplication::translate("PaletteDlg", "90", 0, QApplication::UnicodeUTF8)); R180Radio->setText(QApplication::translate("PaletteDlg", "180", 0, QApplication::UnicodeUTF8)); R270Radio->setText(QApplication::translate("PaletteDlg", "270", 0, QApplication::UnicodeUTF8)); EditStructureButton->setText(QApplication::translate("PaletteDlg", "Edit Structure", 0, QApplication::UnicodeUTF8)); tabProperties->setTabText(tabProperties->indexOf(StructureTab), QApplication::translate("PaletteDlg", "Structure", 0, QApplication::UnicodeUTF8)); } // retranslateUi }; namespace Ui { class PaletteDlg: public Ui_PaletteDlg {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_VPALETTE_H
41.304829
156
0.710451
[ "model" ]
68bac12ae94f3d4d07215f9cf8119798b1a5583b
2,349
h
C
kMC/VSSM.h
CharleySchaefer/ZiltoidLIB
e8b745968447ba8df82a562804876e0ec1f71242
[ "Apache-2.0" ]
null
null
null
kMC/VSSM.h
CharleySchaefer/ZiltoidLIB
e8b745968447ba8df82a562804876e0ec1f71242
[ "Apache-2.0" ]
null
null
null
kMC/VSSM.h
CharleySchaefer/ZiltoidLIB
e8b745968447ba8df82a562804876e0ec1f71242
[ "Apache-2.0" ]
1
2018-06-20T22:23:39.000Z
2018-06-20T22:23:39.000Z
/* VSSM kinetic Monte Carlo: Variable step size method DEPENDENCE: uses find_index_above_y0_float() from ZiltoidLIB/NumericalMethods Algorithm: 1. Initialise VSSM: Initialisation function provided in VSSM.h - using VSSM_initialise - Set (intended) number of time steps, Vssm->max_iter, may be updated throughout the algorithm. - Set number of events / rates, Vssm->max_rates, may also be updated throughout the algorithm. - allocate memory 2. calculate rates - set the values in the array Vssm->rates - set the number of rates Vssm->Nrates -------------------------------------------------- 3. CORE (Functions independent of physical model) Input: Rates, Nrates Output: event number 3.A. calculate total rate - using VSSM_sum_rates 3.B. determine (stochastic and adaptive) time step - using VSSM_get_time_step 3.C. select event - using VSSM_select_event - sets int value VSSM->selected_event -------------------------------------------------- 4. execute event 5. repeat from 2 until max_iter is reached TODO: - For large simulations, the event selection can be significantly improved in terms of cpu time: By grouping events in Ngroup groups where all events have the same rate may speed up the cpu time from ~ log N_rates to ~ log Ngroup. */ #ifndef VSSM_H #define VSSM_H 1 #include "../ZiltoidLIB.h" typedef struct { int selected_event; // label of event after selection int N_iter; // iteration counter int N_rates; // number of non-zero rates double sum_rates; // sum over all rates *rate double t; // time double dt; // (adaptive) time step int max_iter; // number of kMC time steps int max_rates; // number of possible rates double *rate; // all possible rates double *S; // cummulative rates int *event_list; // list with labels that refer to events } VSSM; VSSM * VSSM_make(void); int VSSM_free(VSSM *); int VSSM_initialise( VSSM *, int, int); int VSSM_sum_rates( VSSM * ); int VSSM_get_time_step(VSSM * ); int VSSM_select_event( VSSM * ); #endif
30.506494
79
0.605364
[ "model" ]
68d6d75c21634ff080df7f304418a298c17ba0ea
928
c
C
gempak/source/cgemlib/cap/cappsiterinit.c
oxelson/gempak
e7c477814d7084c87d3313c94e192d13d8341fa1
[ "BSD-3-Clause" ]
42
2015-06-03T15:26:21.000Z
2022-02-28T22:36:03.000Z
gempak/source/cgemlib/cap/cappsiterinit.c
oxelson/gempak
e7c477814d7084c87d3313c94e192d13d8341fa1
[ "BSD-3-Clause" ]
60
2015-05-11T21:36:08.000Z
2022-03-29T16:22:42.000Z
gempak/source/cgemlib/cap/cappsiterinit.c
oxelson/gempak
e7c477814d7084c87d3313c94e192d13d8341fa1
[ "BSD-3-Clause" ]
27
2016-06-06T21:55:14.000Z
2022-03-18T18:23:28.000Z
#include "capcmn.h" void cap_psiterinit(PlacementSet placements, int *iret) /***************************************************************************** * cap_psiterinit * * Initializes the PlacementSet iterator so that the cap_psiternext can be * used to iterate over the Placements contained in the set. * * Input parameters: * placements PlacementSet handle to PlacementSet * * Output parameters: * *iret int Return code * 0 = Function successful * -1 = Invalid object ** * Log: * S.Danz/AWC 2/06 Created ****************************************************************************/ { PlacementSetContainer *p = (PlacementSetContainer*)placements; /*---------------------------------------------------------------------*/ if (p) { p->iter = 0; *iret = 0; } else { *iret = -1; } return; }
27.294118
78
0.44181
[ "object" ]
68d7a0b8e8404b73fb248a99e4e749e263766483
2,097
h
C
new_struct/inc/coordtransforms.h
jlsanders/genfunc
6a608a21651be37462e42289c0a15233b8e29bbb
[ "MIT" ]
2
2019-05-12T13:24:27.000Z
2019-10-14T01:06:54.000Z
new_struct/inc/coordtransforms.h
jlsanders/genfunc
6a608a21651be37462e42289c0a15233b8e29bbb
[ "MIT" ]
null
null
null
new_struct/inc/coordtransforms.h
jlsanders/genfunc
6a608a21651be37462e42289c0a15233b8e29bbb
[ "MIT" ]
null
null
null
#ifndef COORDTRANSFORMS_H #define COORDTRANSFORMS_H #include "utils.h" namespace conv{ // Conventions const VecDoub StandardSolar {8.0,0.0,11.1,232.24,7.25}; // in km/s with v_c = 220 km/s const VecDoub StandardSolar2 {8.29,0.0,0.01135,0.257055,0.0074148}; // in kpc/Myr with v_c=239.1km/s const VecDoub StandardSolarPAUL {8.29,0.0,11.1,251.34,7.25}; // in km/s with v_c = 239.1 km/s const double masyr2radMyr = 4.8481368111e-3; const double deg2rad = 0.017453292; const double kpcMyr2kms = 977.775; const double kpcMyr2kmsSq = kpcMyr2kms*kpcMyr2kms; const double kms2kpcMyr = 1./kpcMyr2kms; const double kms2kpcGyr = 1000.*kms2kpcMyr; const double RA_GP=3.36603292,decGP=0.473477282,lCP=2.145566725; const double PM_Const = 4.74057170372; // ====================================================================================== // Cartesian <==> Polar VecDoub CartesianToPolar(const VecDoub& Cartesian); VecDoub PolarToCartesian(const VecDoub& Polar); // ====================================================================================== // Galactic <==> Cartesian VecDoub GalacticToCartesian(const VecDoub &Galactic, const VecDoub& SolarPosition); VecDoub GalacticToCartesian(const VecDoub &Galactic); VecDoub CartesianToGalactic(const VecDoub &Cartesian, const VecDoub& SolarPosition); VecDoub CartesianToGalactic(const VecDoub &Cartesian); // ====================================================================================== // Galactic <==> Polar VecDoub PolarToGalactic(const VecDoub &Polar, const VecDoub& SolarPosition); VecDoub PolarToGalactic(const VecDoub &Polar); VecDoub GalacticToPolar(const VecDoub &Galactic, const VecDoub& SolarPosition); VecDoub GalacticToPolar(const VecDoub &Galactic); // ====================================================================================== // Equatorial <==> Galactic VecDoub EquatorialToGalactic(const VecDoub &Eq); std::vector<VecDoub> EquatorialToGalacticwithErrors(const VecDoub &E,const VecDoub &EqE); VecDoub GalacticToEquatorial(const VecDoub &Galactic); } #endif
38.833333
100
0.631855
[ "vector" ]
68e0a933c048d2ec08757148191f4dc587830cc4
397
c
C
d/islands/tonerra/obj/liquid4.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-07-19T05:24:44.000Z
2021-11-18T04:08:19.000Z
d/islands/tonerra/obj/liquid4.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
4
2021-03-15T18:56:39.000Z
2021-08-17T17:08:22.000Z
d/islands/tonerra/obj/liquid4.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-09-12T06:22:38.000Z
2022-01-31T01:15:12.000Z
#include <std.h> inherit OBJECT; void create(){ ::create(); set_name("%^BOLD%^%^BLACK%^black liquid"); set_short("Vial containing %^BOLD%^%^BLACK%^black liquid%^RESET%^"); set_id(({"liquide","liquid","black liquid","vial"})); set_long( @OLI This thick black liquid oozes around before you. No telling what chemical is in it. OLI ); set_value(2000); set_weight(10); }
22.055556
87
0.644836
[ "object" ]
be2904c6017eff6c0361f9bb2dee6048ab75f4a7
159
h
C
whycpp/src/loop/i_render_handler.h
senior-sigan/WHY_CPP
f9e2d060a782b9d72fb2c9f3ce580af00eb40779
[ "MIT" ]
6
2019-01-10T12:06:04.000Z
2022-01-06T15:22:03.000Z
whycpp/src/loop/i_render_handler.h
senior-sigan/WHY_CPP
f9e2d060a782b9d72fb2c9f3ce580af00eb40779
[ "MIT" ]
8
2019-02-22T09:14:34.000Z
2019-04-20T18:46:37.000Z
whycpp/src/loop/i_render_handler.h
senior-sigan/WHY_CPP
f9e2d060a782b9d72fb2c9f3ce580af00eb40779
[ "MIT" ]
3
2019-03-22T09:01:52.000Z
2021-06-13T17:50:31.000Z
#pragma once #include "../i_object.h" class IRenderHandler : public IObject { public: virtual void Render() = 0; virtual ~IRenderHandler() = default; };
17.666667
39
0.691824
[ "render" ]
be3411114daa4bacdf43ff1c99d0c5eb3b97e5e6
305
h
C
Unit-Tests/CBLKVOProxy.h
mugabe/couchbase-lite-ios-1.x-xcode11
948b4ab285ee5145a1ef4793630bbf1c4d14988e
[ "Apache-2.0" ]
null
null
null
Unit-Tests/CBLKVOProxy.h
mugabe/couchbase-lite-ios-1.x-xcode11
948b4ab285ee5145a1ef4793630bbf1c4d14988e
[ "Apache-2.0" ]
null
null
null
Unit-Tests/CBLKVOProxy.h
mugabe/couchbase-lite-ios-1.x-xcode11
948b4ab285ee5145a1ef4793630bbf1c4d14988e
[ "Apache-2.0" ]
null
null
null
// // CBLKVOProxy.h // CouchbaseLite // // Created by Jens Alfke on 8/18/15. // Copyright © 2015 Couchbase, Inc. All rights reserved. // #import "CBLDatabase.h" @interface CBLKVOProxy : NSObject - (CBLKVOProxy*) initWithObject: (id)object keyPath: (NSString*)keyPath; @end
17.941176
57
0.642623
[ "object" ]
be3a6d4c7d11bac0fc677a12c1cdc562879ebb74
579
h
C
app42/libs/Shephertz_App42_iOS_API.framework/Versions/Current/Headers/Log.h
saqsun/robovm-ios-bindings
dae85f2e573dbbc0973e40a730a22ce356f6a3c1
[ "Apache-2.0" ]
90
2015-01-01T21:20:50.000Z
2021-12-28T00:52:27.000Z
app42/libs/Shephertz_App42_iOS_API.framework/Versions/Current/Headers/Log.h
saqsun/robovm-ios-bindings
dae85f2e573dbbc0973e40a730a22ce356f6a3c1
[ "Apache-2.0" ]
68
2015-01-02T00:22:36.000Z
2017-02-14T23:49:46.000Z
app42/libs/Shephertz_App42_iOS_API.framework/Versions/Current/Headers/Log.h
saqsun/robovm-ios-bindings
dae85f2e573dbbc0973e40a730a22ce356f6a3c1
[ "Apache-2.0" ]
65
2015-01-11T23:53:12.000Z
2021-11-08T06:25:36.000Z
// // Log.h // PAE_iOS_SDK // // Created by shephertz technologies on 11/04/12. // Copyright (c) 2012 ShephertzTechnology PVT LTD. All rights reserved. // #import <Foundation/Foundation.h> #import "App42Response.h" /** * * This Log object is the value object which contains the properties of Log * along with the setter & getter for those properties. * */ @interface Log : App42Response{ NSMutableArray *logMessageArray; } /*! *set and get the list of all the messages in the log. */ @property(nonatomic,retain) NSMutableArray *logMessageArray; @end
19.3
75
0.702936
[ "object" ]
be3b87cb8077a9eeb832ae2cd31a702aae6e8604
6,873
c
C
src/text.c
propublica/simple-tiles
79c4636095f7f278fa5aa6698b1cd1f93775459a
[ "MIT" ]
33
2015-01-22T18:34:04.000Z
2021-03-13T18:44:15.000Z
src/text.c
propublica/simple-tiles
79c4636095f7f278fa5aa6698b1cd1f93775459a
[ "MIT" ]
4
2015-02-25T03:07:04.000Z
2019-07-02T14:54:15.000Z
src/text.c
propublica/simple-tiles
79c4636095f7f278fa5aa6698b1cd1f93775459a
[ "MIT" ]
7
2016-09-14T22:15:44.000Z
2020-11-09T12:34:53.000Z
#include "text.h" #include "style.h" #include "util.h" #include "bounds.h" #include "memory.h" #include <math.h> #define GTimer GTimer_GTK #include <glib.h> #include <glib-object.h> #undef GTimer // A storage structure that holds the current state of the layout. typedef struct { PangoLayout *layout; int placed; simplet_bounds_t *bounds; } placement_t; // Create and return a new lithograph, returns NULL on failure. simplet_lithograph_t *simplet_lithograph_new(cairo_t *ctx) { simplet_lithograph_t *litho; if (!(litho = malloc(sizeof(*litho)))) return NULL; memset(litho, 0, sizeof(*litho)); if (!(litho->placements = simplet_list_new(litho))) { free(litho); return NULL; } litho->ctx = ctx; litho->pango_ctx = pango_cairo_create_context(ctx); cairo_reference(ctx); simplet_retain((simplet_retainable_t *)litho); return litho; } // Free a placement. void placement_vfree(void *placement) { placement_t *plc = placement; simplet_bounds_free(plc->bounds); g_object_unref(plc->layout); free(plc); } // Free a lithograph and unref the stored ctx. void simplet_lithograph_free(simplet_lithograph_t *litho) { if (simplet_release((simplet_retainable_t *)litho) > 0) return; cairo_destroy(litho->ctx); simplet_list_set_item_free(litho->placements, placement_vfree); g_object_unref(litho->pango_ctx); simplet_list_free(litho->placements); free(litho); } // Create and return a new placement. placement_t *placement_new(PangoLayout *layout, simplet_bounds_t *bounds) { placement_t *placement; if (!(placement = malloc(sizeof(*placement)))) return NULL; memset(placement, 0, sizeof(*placement)); placement->layout = layout; placement->bounds = bounds; placement->placed = FALSE; return placement; } // Before placing a new label we need to see if the label overlaps over // previously placed labels. This algorithm will be refactored a bit to try // NE SE SW NW placements in the future. void try_and_insert_placement(simplet_lithograph_t *litho, PangoLayout *layout, double x, double y) { int width, height; // Find the computed width and height of a layout in image pixels pango_layout_get_pixel_size(layout, &width, &height); simplet_bounds_t *bounds = simplet_bounds_new(); if (!bounds) return; // Create a bounds to test for intersection simplet_bounds_extend(bounds, floor(x - width / 2), floor(y - height / 2)); simplet_bounds_extend(bounds, floor(x + width / 2), floor(y + height / 2)); // Iterate through the list of already placed labels and check for overlaps. simplet_listiter_t *iter = simplet_get_list_iter(litho->placements); placement_t *placement; while ((placement = (placement_t *)simplet_list_next(iter))) { if (simplet_bounds_intersects(placement->bounds, bounds)) { simplet_bounds_free(bounds); g_object_unref(layout); simplet_list_iter_free(iter); return; } } // If we get here we can create and insert a new placement. placement_t *plc = placement_new(layout, bounds); if (!plc) { simplet_bounds_free(bounds); g_object_unref(layout); return; } simplet_list_push(litho->placements, (void *)plc); } // Apply the labels to the map. void simplet_lithograph_apply(simplet_lithograph_t *litho, simplet_list_t *styles) { simplet_listiter_t *iter = simplet_get_list_iter(litho->placements); placement_t *placement; cairo_save(litho->ctx); while ((placement = (placement_t *)simplet_list_next(iter))) { if (placement->placed == TRUE) continue; cairo_move_to(litho->ctx, placement->bounds->nw.x, placement->bounds->se.y); // Draw the placement pango_cairo_layout_path(litho->ctx, placement->layout); placement->placed = TRUE; } simplet_apply_styles(litho->ctx, styles, "text-stroke-weight", "text-stroke-color", "color", NULL); // Apply and draw various outline options. cairo_restore(litho->ctx); } // Create and add a placement to the current lithograph if it doesn't overlap // with current labels. void simplet_lithograph_add_placement(simplet_lithograph_t *litho, OGRFeatureH feature, simplet_list_t *styles, cairo_t *proj_ctx) { simplet_style_t *field = simplet_lookup_style(styles, "text-field"); if (!field) return; OGRFeatureDefnH defn; if (!(defn = OGR_F_GetDefnRef(feature))) return; int idx = OGR_FD_GetFieldIndex(defn, (const char *)field->arg); if (idx < 0) return; // Find the largest sub geometry of a particular multi-geometry. OGRGeometryH super = OGR_F_GetGeometryRef(feature); OGRGeometryH geom = super; double area = 0.0; switch (wkbFlatten(OGR_G_GetGeometryType(super))) { case wkbMultiPolygon: case wkbGeometryCollection: for (int i = 0; i < OGR_G_GetGeometryCount(super); i++) { OGRGeometryH subgeom = OGR_G_GetGeometryRef(super, i); if (subgeom == NULL) continue; double ar = OGR_G_Area(subgeom); if (ar > area) { geom = subgeom; area = ar; } } break; default:; } // Find the center of our geometry. This sometimes throws an invalid geometry // error, so there is a slight bug here somehow. OGRGeometryH center; if (!(center = OGR_G_CreateGeometry(wkbPoint))) return; if (OGR_G_Centroid(geom, center) == OGRERR_FAILURE) { OGR_G_DestroyGeometry(center); return; } // Turn font hinting off cairo_font_options_t *opts; if (!(opts = cairo_font_options_create())) { OGR_G_DestroyGeometry(center); return; } cairo_font_options_set_hint_style(opts, CAIRO_HINT_STYLE_NONE); cairo_font_options_set_hint_metrics(opts, CAIRO_HINT_METRICS_OFF); pango_cairo_context_set_font_options(litho->pango_ctx, opts); cairo_font_options_destroy(opts); // Get the field containing the text for the label. char *txt = simplet_copy_string(OGR_F_GetFieldAsString(feature, idx)); PangoLayout *layout = pango_layout_new(litho->pango_ctx); pango_layout_set_text(layout, txt, -1); free(txt); // Grab the font to use and apply tracking. simplet_style_t *font = simplet_lookup_style(styles, "font"); simplet_apply_styles(layout, styles, "letter-spacing", NULL); const char *font_family; if (!font) font_family = "helvetica 12px"; else font_family = font->arg; PangoFontDescription *desc = pango_font_description_from_string(font_family); pango_layout_set_font_description(layout, desc); pango_font_description_free(desc); double x = OGR_G_GetX(center, 0), y = OGR_G_GetY(center, 0); cairo_user_to_device(proj_ctx, &x, &y); // Finally try the placement and test for overlaps. try_and_insert_placement(litho, layout, x, y); OGR_G_DestroyGeometry(center); }
31.819444
80
0.704059
[ "geometry", "object" ]
be512c1926aebf3652284107f64879bc3712732f
2,080
h
C
fboss/lib/phy/ExternalPhy.h
fakeNetflix/facebook-repo-fboss
b4b64540c779022bcbeff72376549d0addf3f7e7
[ "BSD-3-Clause" ]
null
null
null
fboss/lib/phy/ExternalPhy.h
fakeNetflix/facebook-repo-fboss
b4b64540c779022bcbeff72376549d0addf3f7e7
[ "BSD-3-Clause" ]
null
null
null
fboss/lib/phy/ExternalPhy.h
fakeNetflix/facebook-repo-fboss
b4b64540c779022bcbeff72376549d0addf3f7e7
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #pragma once #include <stdint.h> #include <vector> #include <folly/Range.h> #include "fboss/lib/phy/gen-cpp2/phy_types.h" namespace facebook { namespace fboss { namespace phy { /* * API for programming external phy chips. Down the line all of these * structs should be represented in the SwitchState somehow. */ struct ExternalPhyLaneStats { float signalToNoiseRatio{0}; uint64_t numAdapt{0}; uint64_t numReadapt{0}; uint64_t numLinkLost{0}; }; struct ExternalPhyPortSideStats { uint64_t fecUncorrectableErrors{0}; // This is per lane std::unordered_map<uint16_t, ExternalPhyLaneStats> lanes; }; struct ExternalPhyPortStats { ExternalPhyPortSideStats system; ExternalPhyPortSideStats line; }; class ExternalPhy { public: virtual ~ExternalPhy() {} virtual PhyFwVersion fwVersion() = 0; // Program all settings in one go. This is a rather inflexible API // in that we expect to use all lanes in the external phy and that // all logical ports are the same speed on a given side of the phy. // // Down the line we can support mismatched speeds using more first // class integration with the switch state. virtual void program(PhySettings settings) = 0; virtual void programOnePort(PhyPortSettings settings) = 0; virtual PhySettings getSettings() = 0; virtual bool legalSettings(const PhySettings& settings) { // optionally overridable by subclasses return true; } // loopback virtual Loopback getLoopback(Side side) = 0; virtual void setLoopback(Side side, Loopback loopback) = 0; virtual ExternalPhyPortStats getPortStats( const PhyPortSettings& settings) = 0; virtual void reset() = 0; virtual void dump() {} }; } // namespace phy } // namespace fboss } // namespace facebook
25.679012
79
0.732212
[ "vector" ]
be59319d8764e17a014170127e611fbd50fbb0fe
4,885
h
C
include/OsmAndCore/ArrayMap.h
pierreloicq/OsmAnd-core
3eb51a19e33eb0fddb9f88e8aaa2d35089a2a7fd
[ "MIT" ]
null
null
null
include/OsmAndCore/ArrayMap.h
pierreloicq/OsmAnd-core
3eb51a19e33eb0fddb9f88e8aaa2d35089a2a7fd
[ "MIT" ]
null
null
null
include/OsmAndCore/ArrayMap.h
pierreloicq/OsmAnd-core
3eb51a19e33eb0fddb9f88e8aaa2d35089a2a7fd
[ "MIT" ]
null
null
null
#ifndef _OSMAND_CORE_ARRAY_MAP_H_ #define _OSMAND_CORE_ARRAY_MAP_H_ #include <OsmAndCore/stdlib_common.h> #include <vector> #include <type_traits> #include <QtGlobal> #include <OsmAndCore.h> #include <OsmAndCore/Nullable.h> namespace OsmAnd { template<typename VALUE> class ArrayMap Q_DECL_FINAL { public: typedef ArrayMap<VALUE> ArrayMapT; typedef Nullable<VALUE> NullableT; typedef typename std::vector<NullableT>::size_type KeyType; typedef typename std::vector<NullableT>::size_type SizeType; private: protected: std::vector<NullableT> _storage; public: inline ArrayMap(const SizeType size = 0) { _storage.reserve(size); } inline ArrayMap(const ArrayMapT& that) : _storage(that._storage) { } #ifdef Q_COMPILER_RVALUE_REFS inline ArrayMap(ArrayMapT&& that) : _storage(qMove(that._storage)) { } #endif // Q_COMPILER_RVALUE_REFS inline ~ArrayMap() { } inline ArrayMapT& operator=(const ArrayMapT& that) { if (this != &that) _storage = that._storage; return *this; } #ifdef Q_COMPILER_RVALUE_REFS inline ArrayMapT& operator=(ArrayMapT&& that) { if (this != &that) _storage = qMove(that._storage); return *this; } #endif // Q_COMPILER_RVALUE_REFS inline bool contains(const KeyType key) const { if (key >= _storage.size()) return false; return _storage[key].isSet(); } inline const VALUE& operator[](const KeyType key) const { return *_storage[key]; } inline VALUE& operator[](const KeyType key) { return *_storage[key]; } inline void set(const KeyType key, const VALUE& value) { if (key >= _storage.size()) _storage.resize(key + 1); _storage[key] = value; } inline VALUE* insert(const KeyType key, const VALUE& value) { if (key >= _storage.size()) _storage.resize(key + 1); auto& entry = _storage[key]; entry = value; return entry.getValuePtrOrNullptr(); } inline bool get(const KeyType key, VALUE& outValue) const { if (key >= _storage.size()) return false; const auto& value = _storage[key]; if (!value.isSet()) return false; outValue = *value; return true; } inline const VALUE* getRef(const KeyType key) const { if (key >= _storage.size()) return nullptr; return _storage[key].getValuePtrOrNullptr(); } inline VALUE* getRef(const KeyType key) { if (key >= _storage.size()) return nullptr; return _storage[key].getValuePtrOrNullptr(); } inline void reserve(const SizeType size) { if (_storage.size() >= size) return; _storage.resize(size); } inline void reset() { _storage.clear(); } inline void clear() { const auto size = _storage.size(); auto pValue = _storage.data(); for (SizeType index = 0; index < size; index++) (pValue++)->unset(); } inline SizeType size() const { return _storage.size(); } inline bool isEmpty() const { return _storage.empty(); } inline bool empty() const { return isEmpty(); } inline void squeeze() { _storage.shrink_to_fit(); } inline bool findMinKey(KeyType& outKey) const { const auto size = _storage.size(); auto pValue = _storage.constData(); for (SizeType index = 0; index < size; index++) { if (!(pValue++)->isSet()) continue; outKey = index; return true; } return false; } inline bool findMaxKey(KeyType& outKey) const { const auto size = _storage.size(); auto pValue = _storage.data() + (size - 1); for (SizeType index = 0; index < size; index++) { if (!(pValue--)->isSet()) continue; outKey = size - index - 1; return true; } return false; } }; } #endif // !defined(_OSMAND_CORE_ARRAY_MAP_H_)
23.829268
68
0.498465
[ "vector" ]
be5bd5edc188bd4ac94ed8d7034264ca72019f31
5,098
h
C
clang-tools-extra/clangd/ConfigFragment.h
DeeSee/llvm-project
1109ec40cdb8ca6a192b8fd44bc6dc0fe150a751
[ "Apache-2.0" ]
null
null
null
clang-tools-extra/clangd/ConfigFragment.h
DeeSee/llvm-project
1109ec40cdb8ca6a192b8fd44bc6dc0fe150a751
[ "Apache-2.0" ]
null
null
null
clang-tools-extra/clangd/ConfigFragment.h
DeeSee/llvm-project
1109ec40cdb8ca6a192b8fd44bc6dc0fe150a751
[ "Apache-2.0" ]
null
null
null
//===--- ConfigFragment.h - Unit of user-specified configuration -*- C++-*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // Various clangd features have configurable behaviour (or can be disabled). // The configuration system allows users to control this: // - in a user config file, a project config file, via LSP, or via flags // - specifying different settings for different files // // This file defines the config::Fragment structure which models one piece of // configuration as obtained from a source like a file. // // This is distinct from how the config is interpreted (CompiledFragment), // combined (Provider) and exposed to the rest of clangd (Config). // //===----------------------------------------------------------------------===// // // To add a new configuration option, you must: // - add its syntactic form to Fragment // - update ConfigYAML.cpp to parse it // - add its semantic form to Config (in Config.h) // - update ConfigCompile.cpp to map Fragment -> Config // - make use of the option inside clangd // - document the new option (config.md in the llvm/clangd-www repository) // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_CONFIGFRAGMENT_H #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_CONFIGFRAGMENT_H #include "ConfigProvider.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Error.h" #include "llvm/Support/SMLoc.h" #include "llvm/Support/SourceMgr.h" #include <string> #include <vector> namespace clang { namespace clangd { namespace config { /// An entity written in config along, with its optional location in the file. template <typename T> struct Located { Located(T Value, llvm::SMRange Range = {}) : Range(Range), Value(std::move(Value)) {} llvm::SMRange Range; T &operator->() { return Value; } const T &operator->() const { return Value; } T &operator*() { return Value; } const T &operator*() const { return Value; } private: T Value; }; /// A chunk of configuration obtained from a config file, LSP, or elsewhere. struct Fragment { /// Parses fragments from a YAML file (one from each --- delimited document). /// Documents that contained fatal errors are omitted from the results. /// BufferName is used for the SourceMgr and diagnostics. static std::vector<Fragment> parseYAML(llvm::StringRef YAML, llvm::StringRef BufferName, DiagnosticCallback); /// Analyzes and consumes this fragment, possibly yielding more diagnostics. /// This always produces a usable result (errors are recovered). /// /// Typically, providers will compile a Fragment once when it's first loaded, /// caching the result for reuse. /// Like a compiled program, this is good for performance and also encourages /// errors to be reported early and only once. /// /// The returned function is a cheap-copyable wrapper of refcounted internals. CompiledFragment compile(DiagnosticCallback) &&; /// These fields are not part of the user-specified configuration, but /// instead are populated by the parser to describe the configuration source. struct SourceInfo { /// Retains a buffer of the original source this fragment was parsed from. /// Locations within Located<T> objects point into this SourceMgr. /// Shared because multiple fragments are often parsed from one (YAML) file. /// May be null, then all locations should be ignored. std::shared_ptr<llvm::SourceMgr> Manager; /// The start of the original source for this fragment. /// Only valid if SourceManager is set. llvm::SMLoc Location; }; SourceInfo Source; /// Conditions in the If block restrict when a Fragment applies. /// /// Each separate condition must match (combined with AND). /// When one condition has multiple values, any may match (combined with OR). /// e.g. `PathMatch: [foo/.*, bar/.*]` matches files in either directory. /// /// Conditions based on a file's path use the following form: /// - if the fragment came from a project directory, the path is relative /// - if the fragment is global (e.g. user config), the path is absolute /// - paths always use forward-slashes (UNIX-style) /// If no file is being processed, these conditions will not match. struct IfBlock { /// The file being processed must fully match a regular expression. std::vector<Located<std::string>> PathMatch; /// An unrecognized key was found while parsing the condition. /// The condition will evaluate to false. bool HasUnrecognizedCondition = false; }; IfBlock If; struct CompileFlagsBlock { std::vector<Located<std::string>> Add; } CompileFlags; }; } // namespace config } // namespace clangd } // namespace clang #endif
40.141732
80
0.672813
[ "vector" ]
be6629303e77be3969bbfab80e2c320f95d55b5b
6,291
h
C
core/math/vec3.h
marcs77/MuonEngine
275757597fa414247de925c8b1d4f9389ecad8f0
[ "MIT" ]
null
null
null
core/math/vec3.h
marcs77/MuonEngine
275757597fa414247de925c8b1d4f9389ecad8f0
[ "MIT" ]
null
null
null
core/math/vec3.h
marcs77/MuonEngine
275757597fa414247de925c8b1d4f9389ecad8f0
[ "MIT" ]
null
null
null
#ifndef VECTOR3_H #define VECTOR3_H #include <cmath> #include <string> #include "vec2.h" namespace muon { namespace math { template <class T> struct Vec3 { T x, y, z; Vec3(); Vec3(const Vec3& v); Vec3(const Vec2<T>& v, const T& z); Vec3(const T& x, const T& y, const T& z); Vec3 operator+(const Vec3 &v2) const; Vec3& operator+=(const Vec3 &v2); Vec3 operator-(const Vec3 &v2) const; Vec3& operator-=(const Vec3 &v2); Vec3 operator*(const Vec3 &v2) const; Vec3 operator*(const T &scalar) const; Vec3& operator*=(const Vec3 &v2); Vec3& operator*=(const T &scalar); Vec3 operator/(const Vec3 &v2) const; Vec3 operator/(const T &scalar) const; Vec3& operator/=(const Vec3 &v2); Vec3& operator/=(const T &scalar); inline T lengthSquared() const; inline T length() const; Vec3& normalize(); Vec3 normalized() const; Vec3& limit(const T& max); inline T dot(const Vec3 &v2) const; inline Vec3<T> cross(const Vec3 &v2) const; inline std::string toString(); void set(const Vec3& v); void set(const T& x, const T& y, const T& z); //STATIC static inline T distance(const Vec3& a, const Vec3& b); static inline Vec3 direction(const Vec3& from, const Vec3& to); static inline T projection(const Vec3& a, const Vec3& b); static inline Vec3 projectionVector(const Vec3& a, const Vec3& b); static const Vec3 zero; static const Vec3 i; static const Vec3 j; static const Vec3 k; }; template<typename T> const Vec3<T> Vec3<T>::zero = Vec3(); template<typename T> const Vec3<T> Vec3<T>::i = Vec3(1,0,0); template<typename T> const Vec3<T> Vec3<T>::j = Vec3(0,1,0); template<typename T> const Vec3<T> Vec3<T>::k = Vec3(0,0,1); /* Constructors */ template<typename T> inline Vec3<T>::Vec3() : x(0), y(0), z(0) { } template<typename T> inline Vec3<T>::Vec3(const Vec3 & v) : x(v.x), y(v.y), z(v.z) { } template<class T> inline Vec3<T>::Vec3(const Vec2<T>& v, const T & z) : x(v.x), y(v.y), z(z) { } template<typename T> inline Vec3<T>::Vec3(const T & x, const T & y, const T & z) : x(x), y(y), z(z) { } /* Operators */ template<typename T> Vec3<T> Vec3<T>::operator+(const Vec3 & v2) const { return Vec3(x + v2.x, y + v2.y, z + v2.z); } template<typename T> Vec3<T>& Vec3<T>::operator+=(const Vec3 & v2) { x += v2.x; y += v2.y; z += v2.z; return *this; } template<typename T> Vec3<T> Vec3<T>::operator-(const Vec3 & v2) const { return Vec3(x - v2.x, y - v2.y, z - v2.z); } template<typename T> Vec3<T>& Vec3<T>::operator-=(const Vec3 & v2) { x -= v2.x; y -= v2.y; z -= v2.z; return *this; } template<typename T> Vec3<T> Vec3<T>::operator*(const Vec3 & v2) const { return Vec3(x * v2.x, y * v2.y, z * v2.z); } template<typename T> Vec3<T> Vec3<T>::operator*(const T &scalar) const { return Vec3(x * scalar, y * scalar, z * scalar); } template<typename T> Vec3<T>& Vec3<T>::operator*=(const Vec3 & v2) { x *= v2.x; y *= v2.y; z *= v2.z; return *this; } template<typename T> inline Vec3<T> & Vec3<T>::operator*=(const T & scalar) { x *= scalar; y *= scalar; z *= scalar; return *this; } template<typename T> Vec3<T> Vec3<T>::operator/(const Vec3 & v2) const { return Vec3(x / v2.x, y / v2.y, z / v2.z); } template<typename T> Vec3<T> Vec3<T>::operator/(const T &scalar) const { T inv = 1.0 / scalar; return Vec3(x * inv, y * inv, z * inv); } template<typename T> Vec3<T>& Vec3<T>::operator/=(const Vec3 & v2) { x /= v2.x; y /= v2.y; z /= v2.z; return *this; } template<typename T> inline Vec3<T> & Vec3<T>::operator/=(const T & scalar) { T inv = 1.0 / scalar; x *= inv; y *= inv; z *= inv; return *this; } /* Methods */ template<typename T> inline T Vec3<T>::lengthSquared() const { return x*x + y*y + z*z; } template<typename T> inline T Vec3<T>::length() const { return (T) sqrt(lengthSquared()); } template<typename T> inline Vec3<T>& Vec3<T>::normalize() { if (x != 0 || y != 0 || z != 0) { (*this) *= 1.0 / length(); } return *this; } template<typename T> inline Vec3<T> Vec3<T>::normalized() const { if (x != 0 || y != 0 || z != 0) { return (*this) / length(); } return Vec3<T>(); } template<typename T> inline Vec3<T> & Vec3<T>::limit(const T& max) { if (lengthSquared > max*max) { normalize(); (*this) *= max; } } template<typename T> inline T Vec3<T>::dot(const Vec3 & v2) const { return x*v2.x + y*v2.y + z*v2.z; } template<typename T> inline Vec3<T> Vec3<T>::cross(const Vec3 & v2) const { return Vec3<T>( y * v2.z - z * v2.y, z * v2.x - x * v2.z, x * v2.y - y * v2.x ); } template<typename T> inline std::string Vec3<T>::toString() { return "Vec3: (" + std::to_string(x) + "," + std::to_string(y) + "," + std::to_string(z) + ")"; } template<typename T> inline void Vec3<T>::set(const Vec3 & v) { x = v.x; y = v.y; z = v.z; } template<typename T> inline void Vec3<T>::set(const T & x, const T & y, const T & z) { this->x = x; this->y = y; this->z = z; } /* Static */ template<typename T> inline T Vec3<T>::distance(const Vec3<T> & a, const Vec3<T> & b) { return (b - a).length(); } template<typename T> inline Vec3<T> Vec3<T>::direction(const Vec3 & from, const Vec3 & to) { return (to - from).normalize(); } template<typename T> inline T Vec3<T>::projection(const Vec3 & a, const Vec3 & b) { return a.dot(b) / b.length(); } template<typename T> inline Vec3<T> Vec3<T>::projectionVector(const Vec3 & a, const Vec3 & b) { return b.normalized() * projection(a, b); } template <typename T> std::ostream& operator<<(std::ostream& stream, const Vec3<T>& vector) { stream << "Vec3: (" << vector.x << ", " << vector.y << ", " << vector.z << ")"; return stream; } typedef Vec3<float> Vec3f; typedef Vec3<double> Vec3d; typedef Vec3<int> Vec3i; } } #endif // !VECTOR3_H
20.359223
98
0.561755
[ "vector" ]
be7d4492c58c5cba9f0929df97f3dbca712e4891
2,784
h
C
cc/trees/LayerSorter.h
wenfeifei/miniblink49
2ed562ff70130485148d94b0e5f4c343da0c2ba4
[ "Apache-2.0" ]
5,964
2016-09-27T03:46:29.000Z
2022-03-31T16:25:27.000Z
cc/trees/LayerSorter.h
w4454962/miniblink49
b294b6eacb3333659bf7b94d670d96edeeba14c0
[ "Apache-2.0" ]
459
2016-09-29T00:51:38.000Z
2022-03-07T14:37:46.000Z
cc/trees/LayerSorter.h
w4454962/miniblink49
b294b6eacb3333659bf7b94d670d96edeeba14c0
[ "Apache-2.0" ]
1,006
2016-09-27T05:17:27.000Z
2022-03-30T02:46:51.000Z
// Copyright 2011 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 CC_TREES_LAYER_SORTER_H_ #define CC_TREES_LAYER_SORTER_H_ #include "third_party/WebKit/Source/wtf/Vector.h" #include "cc/blink/WebLayerImpl.h" #include "third_party/WebKit/Source/platform/geometry/FloatRect.h" #include "third_party/WebKit/Source/platform/geometry/FloatQuad.h" #include "third_party/WebKit/Source/platform/geometry/FloatPoint.h" #include "third_party/WebKit/Source/platform/geometry/FloatPoint3D.h" #if defined(COMPILER_GCC) namespace cc { struct GraphEdge; } namespace BASE_HASH_NAMESPACE { template <> struct hash<cc::GraphEdge*> { size_t operator()(cc::GraphEdge* ptr) const { return hash<size_t>()(reinterpret_cast<size_t>(ptr)); } }; } // namespace BASE_HASH_NAMESPACE #endif // COMPILER using cc_blink::WebLayerImplList; namespace cc { struct GraphEdge; // Holds various useful properties derived from a layer's 3D outline. struct LayerShape { LayerShape(); LayerShape(float width, float height, const SkMatrix44& draw_transform); ~LayerShape(); float LayerZFromProjectedPoint(const blink::FloatPoint& p) const; blink::FloatPoint3D layer_normal; blink::FloatPoint3D transform_origin; blink::FloatQuad projected_quad; blink::FloatRect projected_bounds; }; struct GraphNode { explicit GraphNode(cc_blink::WebLayerImpl* layer_impl); ~GraphNode(); cc_blink::WebLayerImpl* layer; LayerShape shape; Vector<GraphEdge*> incoming; Vector<GraphEdge*> outgoing; float incoming_edge_weight; }; struct GraphEdge { GraphEdge(GraphNode* from_node, GraphNode* to_node, float weight) : from(from_node), to(to_node), weight(weight) {} GraphNode* from; GraphNode* to; float weight; }; class LayerSorter { public: LayerSorter(); ~LayerSorter(); void Sort(WebLayerImplList::iterator first, WebLayerImplList::iterator last); enum ABCompareResult { ABeforeB, BBeforeA, None }; static ABCompareResult CheckOverlap(LayerShape* a, LayerShape* b, float z_threshold, float* weight); private: typedef Vector<GraphNode> NodeList; typedef Vector<GraphEdge> EdgeList; NodeList nodes_; EdgeList edges_; float z_range_; typedef HashMap<GraphEdge*, GraphEdge*> EdgeMap; EdgeMap active_edges_; void CreateGraphNodes(WebLayerImplList::iterator first, WebLayerImplList::iterator last); void CreateGraphEdges(); void RemoveEdgeFromList(GraphEdge* graph, Vector<GraphEdge*>* list); DISALLOW_COPY_AND_ASSIGN(LayerSorter); }; } // namespace cc #endif // CC_TREES_LAYER_SORTER_H_
25.777778
93
0.727011
[ "geometry", "shape", "vector", "3d" ]
be801e8d4210f6a185a253d779929fea51a78ef2
2,074
h
C
utilopengl.h
csmyamanaka/utils
e14e842c708c9936e9cabcd04bee49eb7221fb07
[ "MIT" ]
null
null
null
utilopengl.h
csmyamanaka/utils
e14e842c708c9936e9cabcd04bee49eb7221fb07
[ "MIT" ]
null
null
null
utilopengl.h
csmyamanaka/utils
e14e842c708c9936e9cabcd04bee49eb7221fb07
[ "MIT" ]
null
null
null
#pragma once #include <GL/glut.h> #include <math.h> #include <stdlib.h> //setting 3d stuff void setObjectT(GLfloat* aF0, GLfloat aF1, GLfloat aF2, GLfloat aF3){ aF0[3] = aF1; aF0[7] = aF2; aF0[11] = aF3; } void setObjectRx(GLfloat* aF0, GLfloat aF1){ aF0[5] = cos(aF1); aF0[6] = -sin(aF1); aF0[9] = sin(aF1); aF0[10] = cos(aF1); } void setObjectRy(GLfloat* aF0, GLfloat aF1){ aF0[0] = cos(aF1); aF0[2] = sin(aF1); aF0[8] = -sin(aF1); aF0[10] = cos(aF1); } void setObjectRz(GLfloat* aF0, GLfloat aF1){ aF0[0] = cos(aF1); aF0[1] = -sin(aF1); aF0[4] = sin(aF1); aF0[5] = cos(aF1); } void scaleObject(GLfloat* aF0, GLfloat aF1){ aF0[0] *= aF1; aF0[5] *= aF1; aF0[10] *= aF1; } void setObjectS(GLfloat* aF0, GLfloat aF1){ aF0[0] = aF1; aF0[5] = aF1; aF0[10] = aF1; } //create zero matrix GLfloat* ugl_Z(int aI0){ GLfloat* ret = malloc(sizeof(GLfloat)*aI0); for(int it0 = 0; it0 < aI0; it0++) ret[it0] = 0; return ret; } //create identity matrix GLfloat* ugl_I(int aI0){ GLfloat* ret = malloc(sizeof(GLfloat)*aI0*aI0); for(int it0 = 0; it0 < aI0*aI0; it0++){ if(it0%(aI0 + 1) == 0) ret[it0] = 1; else ret[it0] = 0; } return ret; } //create duplicate GLfloat* ugl_duplicate(GLfloat* aF0, int aI0){ GLfloat* ret = malloc(sizeof(GLfloat)*aI0); for(int it0 = 0; it0 < aI0; it0++) ret[it0] = aF0[it0]; return ret; } //some arithmetics GLfloat* ugl_mult(GLfloat* aF0, GLfloat* aF1, int aI0, int aI1, int aI2){ //input array 0, input array 1, row 0, col 0/row1, col 1 GLfloat* ret = ugl_Z(aI0*aI2); for(int it0 = 0; it0 < aI0*aI2; it0++){ for(int it1 = 0; it1 < aI1; it1++) ret[it0] += aF0[(it0/4)*aI1 + it1]*aF1[it1*aI2 + (it0%4)]; } return ret; } //create a single transformation matrix from a list of transformation //matrices GLfloat* ugl_T(GLfloat** aF0){ GLfloat* ret = ugl_mult(aF0[1], aF0[0], 4, 4, 4); for(int it0 = 2; it0 < 5; it0++){ GLfloat* temp = ugl_mult(aF0[it0], ret, 4, 4, 4); free(ret); ret = ugl_duplicate(temp, 16); free(temp); } return ret; }
21.831579
97
0.605593
[ "3d" ]
be8365b0785166517de089d0df0d47400e349391
4,320
c
C
src/pm/hydra/tools/topo/hwloc/hwloc/utils/hwloc-ps.c
grondo/mvapich2-cce
ec084d8e07db1cf2ac1352ee4c604ae7dbae55cb
[ "Intel", "mpich2", "Unlicense" ]
1
2021-11-11T15:42:30.000Z
2021-11-11T15:42:30.000Z
src/pm/hydra/tools/topo/hwloc/hwloc/utils/hwloc-ps.c
grondo/mvapich2-cce
ec084d8e07db1cf2ac1352ee4c604ae7dbae55cb
[ "Intel", "mpich2", "Unlicense" ]
null
null
null
src/pm/hydra/tools/topo/hwloc/hwloc/utils/hwloc-ps.c
grondo/mvapich2-cce
ec084d8e07db1cf2ac1352ee4c604ae7dbae55cb
[ "Intel", "mpich2", "Unlicense" ]
null
null
null
/* * Copyright © 2009-2010 INRIA. All rights reserved. * Copyright © 2009-2010 Université Bordeaux 1 * Copyright © 2009-2011 Cisco Systems, Inc. All rights reserved. * See COPYING in top-level directory. */ #include <private/autogen/config.h> #include <hwloc.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <dirent.h> #include <fcntl.h> static void usage(char *name, FILE *where) { fprintf (where, "Usage: %s [ options ] ... [ filename ]\n", name); fprintf (where, "Options:\n"); fprintf (where, " -a Show all processes, including those that are not bound\n"); fprintf (where, " -l --logical Use logical object indexes (default)\n"); fprintf (where, " -p --physical Use physical object indexes\n"); fprintf (where, " -c --cpuset Show cpuset instead of objects\n"); } int main(int argc, char *argv[]) { const struct hwloc_topology_support *support; hwloc_topology_t topology; hwloc_obj_t root; hwloc_bitmap_t cpuset; int logical = 1; int show_cpuset = 0; DIR *dir; struct dirent *dirent; int show_all = 0; char *callname; int err; int opt; callname = strrchr(argv[0], '/'); if (!callname) callname = argv[0]; else callname++; while (argc >= 2) { opt = 0; if (!strcmp(argv[1], "-a")) show_all = 1; else if (!strcmp(argv[1], "-l") || !strcmp(argv[1], "--logical")) { logical = 1; } else if (!strcmp(argv[1], "-p") || !strcmp(argv[1], "--physical")) { logical = 0; } else if (!strcmp(argv[1], "-c") || !strcmp(argv[1], "--cpuset")) { show_cpuset = 1; } else { fprintf (stderr, "Unrecognized option: %s\n", argv[1]); usage (callname, stderr); exit(EXIT_FAILURE); } argc -= opt+1; argv += opt+1; } err = hwloc_topology_init(&topology); if (err) goto out; err = hwloc_topology_load(topology); if (err) goto out_with_topology; root = hwloc_get_root_obj(topology); support = hwloc_topology_get_support(topology); if (!support->cpubind->get_thisproc_cpubind) goto out_with_topology; dir = opendir("/proc"); if (!dir) goto out_with_topology; cpuset = hwloc_bitmap_alloc(); if (!cpuset) goto out_with_dir; while ((dirent = readdir(dir))) { long pid; char *end; char name[64] = ""; char *cpuset_str = NULL; pid = strtol(dirent->d_name, &end, 10); if (*end) /* Not a number */ continue; #ifdef HWLOC_LINUX_SYS { unsigned pathlen = 6 + strlen(dirent->d_name) + 1 + 7 + 1; char *path; int file; ssize_t n; path = malloc(pathlen); snprintf(path, pathlen, "/proc/%s/cmdline", dirent->d_name); file = open(path, O_RDONLY); free(path); if (file >= 0) { n = read(file, name, sizeof(name) - 1); close(file); if (n <= 0) /* Ignore kernel threads and errors */ continue; name[n] = 0; } } #endif /* HWLOC_LINUX_SYS */ if (hwloc_get_proc_cpubind(topology, pid, cpuset, 0)) continue; hwloc_bitmap_and(cpuset, cpuset, hwloc_topology_get_topology_cpuset(topology)); if (hwloc_bitmap_iszero(cpuset)) continue; if (hwloc_bitmap_isequal(cpuset, root->cpuset) && !show_all) continue; printf("%ld\t", pid); if (show_cpuset) { hwloc_bitmap_asprintf(&cpuset_str, cpuset); printf("%s", cpuset_str); } else { hwloc_bitmap_t remaining = hwloc_bitmap_dup(cpuset); int first = 1; while (!hwloc_bitmap_iszero(remaining)) { char type[64]; unsigned idx; hwloc_obj_t obj = hwloc_get_first_largest_obj_inside_cpuset(topology, remaining); hwloc_obj_type_snprintf(type, sizeof(type), obj, 1); idx = logical ? obj->logical_index : obj->os_index; if (idx == (unsigned) -1) printf("%s%s", first ? "" : " ", type); else printf("%s%s:%u", first ? "" : " ", type, idx); hwloc_bitmap_andnot(remaining, remaining, obj->cpuset); first = 0; } hwloc_bitmap_free(remaining); } printf("\t\t%s\n", name); free(cpuset_str); } err = 0; hwloc_bitmap_free(cpuset); out_with_dir: closedir(dir); out_with_topology: hwloc_topology_destroy(topology); out: return err; }
24.827586
95
0.602546
[ "object" ]
be87c5e2ee9584747e05b57f8ce60ee2b29d93ed
15,400
c
C
linux-2.6.16-unmod/arch/i386/kernel/nmi.c
ut-osa/syncchar
eba20da163260b6ae1ef3e334ad2137873a8d625
[ "BSD-3-Clause" ]
null
null
null
linux-2.6.16-unmod/arch/i386/kernel/nmi.c
ut-osa/syncchar
eba20da163260b6ae1ef3e334ad2137873a8d625
[ "BSD-3-Clause" ]
null
null
null
linux-2.6.16-unmod/arch/i386/kernel/nmi.c
ut-osa/syncchar
eba20da163260b6ae1ef3e334ad2137873a8d625
[ "BSD-3-Clause" ]
1
2019-05-14T16:36:45.000Z
2019-05-14T16:36:45.000Z
/* * linux/arch/i386/nmi.c * * NMI watchdog support on APIC systems * * Started by Ingo Molnar <mingo@redhat.com> * * Fixes: * Mikael Pettersson : AMD K7 support for local APIC NMI watchdog. * Mikael Pettersson : Power Management for local APIC NMI watchdog. * Mikael Pettersson : Pentium 4 support for local APIC NMI watchdog. * Pavel Machek and * Mikael Pettersson : PM converted to driver model. Disable/enable API. */ #include <linux/config.h> #include <linux/mm.h> #include <linux/delay.h> #include <linux/bootmem.h> #include <linux/smp_lock.h> #include <linux/interrupt.h> #include <linux/mc146818rtc.h> #include <linux/kernel_stat.h> #include <linux/module.h> #include <linux/nmi.h> #include <linux/sysdev.h> #include <linux/sysctl.h> #include <asm/smp.h> #include <asm/div64.h> #include <asm/nmi.h> #include "mach_traps.h" unsigned int nmi_watchdog = NMI_NONE; extern int unknown_nmi_panic; static unsigned int nmi_hz = HZ; static unsigned int nmi_perfctr_msr; /* the MSR to reset in NMI handler */ static unsigned int nmi_p4_cccr_val; extern void show_registers(struct pt_regs *regs); /* * lapic_nmi_owner tracks the ownership of the lapic NMI hardware: * - it may be reserved by some other driver, or not * - when not reserved by some other driver, it may be used for * the NMI watchdog, or not * * This is maintained separately from nmi_active because the NMI * watchdog may also be driven from the I/O APIC timer. */ static DEFINE_SPINLOCK(lapic_nmi_owner_lock); static unsigned int lapic_nmi_owner; #define LAPIC_NMI_WATCHDOG (1<<0) #define LAPIC_NMI_RESERVED (1<<1) /* nmi_active: * +1: the lapic NMI watchdog is active, but can be disabled * 0: the lapic NMI watchdog has not been set up, and cannot * be enabled * -1: the lapic NMI watchdog is disabled, but can be enabled */ int nmi_active; #define K7_EVNTSEL_ENABLE (1 << 22) #define K7_EVNTSEL_INT (1 << 20) #define K7_EVNTSEL_OS (1 << 17) #define K7_EVNTSEL_USR (1 << 16) #define K7_EVENT_CYCLES_PROCESSOR_IS_RUNNING 0x76 #define K7_NMI_EVENT K7_EVENT_CYCLES_PROCESSOR_IS_RUNNING #define P6_EVNTSEL0_ENABLE (1 << 22) #define P6_EVNTSEL_INT (1 << 20) #define P6_EVNTSEL_OS (1 << 17) #define P6_EVNTSEL_USR (1 << 16) #define P6_EVENT_CPU_CLOCKS_NOT_HALTED 0x79 #define P6_NMI_EVENT P6_EVENT_CPU_CLOCKS_NOT_HALTED #define MSR_P4_MISC_ENABLE 0x1A0 #define MSR_P4_MISC_ENABLE_PERF_AVAIL (1<<7) #define MSR_P4_MISC_ENABLE_PEBS_UNAVAIL (1<<12) #define MSR_P4_PERFCTR0 0x300 #define MSR_P4_CCCR0 0x360 #define P4_ESCR_EVENT_SELECT(N) ((N)<<25) #define P4_ESCR_OS (1<<3) #define P4_ESCR_USR (1<<2) #define P4_CCCR_OVF_PMI0 (1<<26) #define P4_CCCR_OVF_PMI1 (1<<27) #define P4_CCCR_THRESHOLD(N) ((N)<<20) #define P4_CCCR_COMPLEMENT (1<<19) #define P4_CCCR_COMPARE (1<<18) #define P4_CCCR_REQUIRED (3<<16) #define P4_CCCR_ESCR_SELECT(N) ((N)<<13) #define P4_CCCR_ENABLE (1<<12) /* Set up IQ_COUNTER0 to behave like a clock, by having IQ_CCCR0 filter CRU_ESCR0 (with any non-null event selector) through a complemented max threshold. [IA32-Vol3, Section 14.9.9] */ #define MSR_P4_IQ_COUNTER0 0x30C #define P4_NMI_CRU_ESCR0 (P4_ESCR_EVENT_SELECT(0x3F)|P4_ESCR_OS|P4_ESCR_USR) #define P4_NMI_IQ_CCCR0 \ (P4_CCCR_OVF_PMI0|P4_CCCR_THRESHOLD(15)|P4_CCCR_COMPLEMENT| \ P4_CCCR_COMPARE|P4_CCCR_REQUIRED|P4_CCCR_ESCR_SELECT(4)|P4_CCCR_ENABLE) #ifdef CONFIG_SMP /* The performance counters used by NMI_LOCAL_APIC don't trigger when * the CPU is idle. To make sure the NMI watchdog really ticks on all * CPUs during the test make them busy. */ static __init void nmi_cpu_busy(void *data) { volatile int *endflag = data; local_irq_enable(); /* Intentionally don't use cpu_relax here. This is to make sure that the performance counter really ticks, even if there is a simulator or similar that catches the pause instruction. On a real HT machine this is fine because all other CPUs are busy with "useless" delay loops and don't care if they get somewhat less cycles. */ while (*endflag == 0) barrier(); } #endif static int __init check_nmi_watchdog(void) { volatile int endflag = 0; unsigned int *prev_nmi_count; int cpu; if (nmi_watchdog == NMI_NONE) return 0; prev_nmi_count = kmalloc(NR_CPUS * sizeof(int), GFP_KERNEL); if (!prev_nmi_count) return -1; printk(KERN_INFO "Testing NMI watchdog ... "); if (nmi_watchdog == NMI_LOCAL_APIC) smp_call_function(nmi_cpu_busy, (void *)&endflag, 0, 0); for_each_cpu(cpu) prev_nmi_count[cpu] = per_cpu(irq_stat, cpu).__nmi_count; local_irq_enable(); mdelay((10*1000)/nmi_hz); // wait 10 ticks for (cpu = 0; cpu < NR_CPUS; cpu++) { #ifdef CONFIG_SMP /* Check cpu_callin_map here because that is set after the timer is started. */ if (!cpu_isset(cpu, cpu_callin_map)) continue; #endif if (nmi_count(cpu) - prev_nmi_count[cpu] <= 5) { endflag = 1; printk("CPU#%d: NMI appears to be stuck (%d->%d)!\n", cpu, prev_nmi_count[cpu], nmi_count(cpu)); nmi_active = 0; lapic_nmi_owner &= ~LAPIC_NMI_WATCHDOG; kfree(prev_nmi_count); return -1; } } endflag = 1; printk("OK.\n"); /* now that we know it works we can reduce NMI frequency to something more reasonable; makes a difference in some configs */ if (nmi_watchdog == NMI_LOCAL_APIC) nmi_hz = 1; kfree(prev_nmi_count); return 0; } /* This needs to happen later in boot so counters are working */ late_initcall(check_nmi_watchdog); static int __init setup_nmi_watchdog(char *str) { int nmi; get_option(&str, &nmi); if (nmi >= NMI_INVALID) return 0; if (nmi == NMI_NONE) nmi_watchdog = nmi; /* * If any other x86 CPU has a local APIC, then * please test the NMI stuff there and send me the * missing bits. Right now Intel P6/P4 and AMD K7 only. */ if ((nmi == NMI_LOCAL_APIC) && (boot_cpu_data.x86_vendor == X86_VENDOR_INTEL) && (boot_cpu_data.x86 == 6 || boot_cpu_data.x86 == 15)) nmi_watchdog = nmi; if ((nmi == NMI_LOCAL_APIC) && (boot_cpu_data.x86_vendor == X86_VENDOR_AMD) && (boot_cpu_data.x86 == 6 || boot_cpu_data.x86 == 15)) nmi_watchdog = nmi; /* * We can enable the IO-APIC watchdog * unconditionally. */ if (nmi == NMI_IO_APIC) { nmi_active = 1; nmi_watchdog = nmi; } return 1; } __setup("nmi_watchdog=", setup_nmi_watchdog); static void disable_lapic_nmi_watchdog(void) { if (nmi_active <= 0) return; switch (boot_cpu_data.x86_vendor) { case X86_VENDOR_AMD: wrmsr(MSR_K7_EVNTSEL0, 0, 0); break; case X86_VENDOR_INTEL: switch (boot_cpu_data.x86) { case 6: if (boot_cpu_data.x86_model > 0xd) break; wrmsr(MSR_P6_EVNTSEL0, 0, 0); break; case 15: if (boot_cpu_data.x86_model > 0x4) break; wrmsr(MSR_P4_IQ_CCCR0, 0, 0); wrmsr(MSR_P4_CRU_ESCR0, 0, 0); break; } break; } nmi_active = -1; /* tell do_nmi() and others that we're not active any more */ nmi_watchdog = 0; } static void enable_lapic_nmi_watchdog(void) { if (nmi_active < 0) { nmi_watchdog = NMI_LOCAL_APIC; setup_apic_nmi_watchdog(); } } int reserve_lapic_nmi(void) { unsigned int old_owner; spin_lock(&lapic_nmi_owner_lock); old_owner = lapic_nmi_owner; lapic_nmi_owner |= LAPIC_NMI_RESERVED; spin_unlock(&lapic_nmi_owner_lock); if (old_owner & LAPIC_NMI_RESERVED) return -EBUSY; if (old_owner & LAPIC_NMI_WATCHDOG) disable_lapic_nmi_watchdog(); return 0; } void release_lapic_nmi(void) { unsigned int new_owner; spin_lock(&lapic_nmi_owner_lock); new_owner = lapic_nmi_owner & ~LAPIC_NMI_RESERVED; lapic_nmi_owner = new_owner; spin_unlock(&lapic_nmi_owner_lock); if (new_owner & LAPIC_NMI_WATCHDOG) enable_lapic_nmi_watchdog(); } void disable_timer_nmi_watchdog(void) { if ((nmi_watchdog != NMI_IO_APIC) || (nmi_active <= 0)) return; unset_nmi_callback(); nmi_active = -1; nmi_watchdog = NMI_NONE; } void enable_timer_nmi_watchdog(void) { if (nmi_active < 0) { nmi_watchdog = NMI_IO_APIC; touch_nmi_watchdog(); nmi_active = 1; } } #ifdef CONFIG_PM static int nmi_pm_active; /* nmi_active before suspend */ static int lapic_nmi_suspend(struct sys_device *dev, pm_message_t state) { nmi_pm_active = nmi_active; disable_lapic_nmi_watchdog(); return 0; } static int lapic_nmi_resume(struct sys_device *dev) { if (nmi_pm_active > 0) enable_lapic_nmi_watchdog(); return 0; } static struct sysdev_class nmi_sysclass = { set_kset_name("lapic_nmi"), .resume = lapic_nmi_resume, .suspend = lapic_nmi_suspend, }; static struct sys_device device_lapic_nmi = { .id = 0, .cls = &nmi_sysclass, }; static int __init init_lapic_nmi_sysfs(void) { int error; if (nmi_active == 0 || nmi_watchdog != NMI_LOCAL_APIC) return 0; error = sysdev_class_register(&nmi_sysclass); if (!error) error = sysdev_register(&device_lapic_nmi); return error; } /* must come after the local APIC's device_initcall() */ late_initcall(init_lapic_nmi_sysfs); #endif /* CONFIG_PM */ /* * Activate the NMI watchdog via the local APIC. * Original code written by Keith Owens. */ static void clear_msr_range(unsigned int base, unsigned int n) { unsigned int i; for(i = 0; i < n; ++i) wrmsr(base+i, 0, 0); } static void write_watchdog_counter(const char *descr) { u64 count = (u64)cpu_khz * 1000; do_div(count, nmi_hz); if(descr) Dprintk("setting %s to -0x%08Lx\n", descr, count); wrmsrl(nmi_perfctr_msr, 0 - count); } static void setup_k7_watchdog(void) { unsigned int evntsel; nmi_perfctr_msr = MSR_K7_PERFCTR0; clear_msr_range(MSR_K7_EVNTSEL0, 4); clear_msr_range(MSR_K7_PERFCTR0, 4); evntsel = K7_EVNTSEL_INT | K7_EVNTSEL_OS | K7_EVNTSEL_USR | K7_NMI_EVENT; wrmsr(MSR_K7_EVNTSEL0, evntsel, 0); write_watchdog_counter("K7_PERFCTR0"); apic_write(APIC_LVTPC, APIC_DM_NMI); evntsel |= K7_EVNTSEL_ENABLE; wrmsr(MSR_K7_EVNTSEL0, evntsel, 0); } static void setup_p6_watchdog(void) { unsigned int evntsel; nmi_perfctr_msr = MSR_P6_PERFCTR0; clear_msr_range(MSR_P6_EVNTSEL0, 2); clear_msr_range(MSR_P6_PERFCTR0, 2); evntsel = P6_EVNTSEL_INT | P6_EVNTSEL_OS | P6_EVNTSEL_USR | P6_NMI_EVENT; wrmsr(MSR_P6_EVNTSEL0, evntsel, 0); write_watchdog_counter("P6_PERFCTR0"); apic_write(APIC_LVTPC, APIC_DM_NMI); evntsel |= P6_EVNTSEL0_ENABLE; wrmsr(MSR_P6_EVNTSEL0, evntsel, 0); } static int setup_p4_watchdog(void) { unsigned int misc_enable, dummy; rdmsr(MSR_P4_MISC_ENABLE, misc_enable, dummy); if (!(misc_enable & MSR_P4_MISC_ENABLE_PERF_AVAIL)) return 0; nmi_perfctr_msr = MSR_P4_IQ_COUNTER0; nmi_p4_cccr_val = P4_NMI_IQ_CCCR0; #ifdef CONFIG_SMP if (smp_num_siblings == 2) nmi_p4_cccr_val |= P4_CCCR_OVF_PMI1; #endif if (!(misc_enable & MSR_P4_MISC_ENABLE_PEBS_UNAVAIL)) clear_msr_range(0x3F1, 2); /* MSR 0x3F0 seems to have a default value of 0xFC00, but current docs doesn't fully define it, so leave it alone for now. */ if (boot_cpu_data.x86_model >= 0x3) { /* MSR_P4_IQ_ESCR0/1 (0x3ba/0x3bb) removed */ clear_msr_range(0x3A0, 26); clear_msr_range(0x3BC, 3); } else { clear_msr_range(0x3A0, 31); } clear_msr_range(0x3C0, 6); clear_msr_range(0x3C8, 6); clear_msr_range(0x3E0, 2); clear_msr_range(MSR_P4_CCCR0, 18); clear_msr_range(MSR_P4_PERFCTR0, 18); wrmsr(MSR_P4_CRU_ESCR0, P4_NMI_CRU_ESCR0, 0); wrmsr(MSR_P4_IQ_CCCR0, P4_NMI_IQ_CCCR0 & ~P4_CCCR_ENABLE, 0); write_watchdog_counter("P4_IQ_COUNTER0"); apic_write(APIC_LVTPC, APIC_DM_NMI); wrmsr(MSR_P4_IQ_CCCR0, nmi_p4_cccr_val, 0); return 1; } void setup_apic_nmi_watchdog (void) { switch (boot_cpu_data.x86_vendor) { case X86_VENDOR_AMD: if (boot_cpu_data.x86 != 6 && boot_cpu_data.x86 != 15) return; setup_k7_watchdog(); break; case X86_VENDOR_INTEL: switch (boot_cpu_data.x86) { case 6: if (boot_cpu_data.x86_model > 0xd) return; setup_p6_watchdog(); break; case 15: if (boot_cpu_data.x86_model > 0x4) return; if (!setup_p4_watchdog()) return; break; default: return; } break; default: return; } lapic_nmi_owner = LAPIC_NMI_WATCHDOG; nmi_active = 1; } /* * the best way to detect whether a CPU has a 'hard lockup' problem * is to check it's local APIC timer IRQ counts. If they are not * changing then that CPU has some problem. * * as these watchdog NMI IRQs are generated on every CPU, we only * have to check the current processor. * * since NMIs don't listen to _any_ locks, we have to be extremely * careful not to rely on unsafe variables. The printk might lock * up though, so we have to break up any console locks first ... * [when there will be more tty-related locks, break them up * here too!] */ static unsigned int last_irq_sums [NR_CPUS], alert_counter [NR_CPUS]; void touch_nmi_watchdog (void) { int i; /* * Just reset the alert counters, (other CPUs might be * spinning on locks we hold): */ for (i = 0; i < NR_CPUS; i++) alert_counter[i] = 0; /* * Tickle the softlockup detector too: */ touch_softlockup_watchdog(); } extern void die_nmi(struct pt_regs *, const char *msg); void nmi_watchdog_tick (struct pt_regs * regs) { /* * Since current_thread_info()-> is always on the stack, and we * always switch the stack NMI-atomically, it's safe to use * smp_processor_id(). */ int sum, cpu = smp_processor_id(); sum = per_cpu(irq_stat, cpu).apic_timer_irqs; if (last_irq_sums[cpu] == sum) { /* * Ayiee, looks like this CPU is stuck ... * wait a few IRQs (5 seconds) before doing the oops ... */ alert_counter[cpu]++; if (alert_counter[cpu] == 5*nmi_hz) /* * die_nmi will return ONLY if NOTIFY_STOP happens.. */ die_nmi(regs, "NMI Watchdog detected LOCKUP"); } else { last_irq_sums[cpu] = sum; alert_counter[cpu] = 0; } if (nmi_perfctr_msr) { if (nmi_perfctr_msr == MSR_P4_IQ_COUNTER0) { /* * P4 quirks: * - An overflown perfctr will assert its interrupt * until the OVF flag in its CCCR is cleared. * - LVTPC is masked on interrupt and must be * unmasked by the LVTPC handler. */ wrmsr(MSR_P4_IQ_CCCR0, nmi_p4_cccr_val, 0); apic_write(APIC_LVTPC, APIC_DM_NMI); } else if (nmi_perfctr_msr == MSR_P6_PERFCTR0) { /* Only P6 based Pentium M need to re-unmask * the apic vector but it doesn't hurt * other P6 variant */ apic_write(APIC_LVTPC, APIC_DM_NMI); } write_watchdog_counter(NULL); } } #ifdef CONFIG_SYSCTL static int unknown_nmi_panic_callback(struct pt_regs *regs, int cpu) { unsigned char reason = get_nmi_reason(); char buf[64]; if (!(reason & 0xc0)) { sprintf(buf, "NMI received for unknown reason %02x\n", reason); die_nmi(regs, buf); } return 0; } /* * proc handler for /proc/sys/kernel/unknown_nmi_panic */ int proc_unknown_nmi_panic(ctl_table *table, int write, struct file *file, void __user *buffer, size_t *length, loff_t *ppos) { int old_state; old_state = unknown_nmi_panic; proc_dointvec(table, write, file, buffer, length, ppos); if (!!old_state == !!unknown_nmi_panic) return 0; if (unknown_nmi_panic) { if (reserve_lapic_nmi() < 0) { unknown_nmi_panic = 0; return -EBUSY; } else { set_nmi_callback(unknown_nmi_panic_callback); } } else { release_lapic_nmi(); unset_nmi_callback(); } return 0; } #endif EXPORT_SYMBOL(nmi_active); EXPORT_SYMBOL(nmi_watchdog); EXPORT_SYMBOL(reserve_lapic_nmi); EXPORT_SYMBOL(release_lapic_nmi); EXPORT_SYMBOL(disable_timer_nmi_watchdog); EXPORT_SYMBOL(enable_timer_nmi_watchdog);
24.758842
76
0.723117
[ "vector", "model" ]
be9fad59da722f6dc32d714455cfdb8952c473df
3,307
h
C
google/cloud/filestore/cloud_filestore_manager_connection_idempotency_policy.h
sydney-munro/google-cloud-cpp
374b52e5cec78962358bdd5913d4118a47af1952
[ "Apache-2.0" ]
80
2017-11-24T00:19:45.000Z
2019-01-25T10:24:33.000Z
google/cloud/filestore/cloud_filestore_manager_connection_idempotency_policy.h
sydney-munro/google-cloud-cpp
374b52e5cec78962358bdd5913d4118a47af1952
[ "Apache-2.0" ]
1,579
2017-11-24T01:01:21.000Z
2019-01-28T23:41:21.000Z
google/cloud/filestore/cloud_filestore_manager_connection_idempotency_policy.h
sydney-munro/google-cloud-cpp
374b52e5cec78962358bdd5913d4118a47af1952
[ "Apache-2.0" ]
51
2017-11-24T00:56:11.000Z
2019-01-18T20:35:02.000Z
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/cloud/filestore/v1/cloud_filestore_service.proto #ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_FILESTORE_CLOUD_FILESTORE_MANAGER_CONNECTION_IDEMPOTENCY_POLICY_H #define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_FILESTORE_CLOUD_FILESTORE_MANAGER_CONNECTION_IDEMPOTENCY_POLICY_H #include "google/cloud/idempotency.h" #include "google/cloud/internal/retry_policy.h" #include "google/cloud/version.h" #include <google/cloud/filestore/v1/cloud_filestore_service.grpc.pb.h> #include <memory> namespace google { namespace cloud { namespace filestore { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN class CloudFilestoreManagerConnectionIdempotencyPolicy { public: virtual ~CloudFilestoreManagerConnectionIdempotencyPolicy() = 0; /// Create a new copy of this object. virtual std::unique_ptr<CloudFilestoreManagerConnectionIdempotencyPolicy> clone() const = 0; virtual google::cloud::Idempotency ListInstances( google::cloud::filestore::v1::ListInstancesRequest request) = 0; virtual google::cloud::Idempotency GetInstance( google::cloud::filestore::v1::GetInstanceRequest const& request) = 0; virtual google::cloud::Idempotency CreateInstance( google::cloud::filestore::v1::CreateInstanceRequest const& request) = 0; virtual google::cloud::Idempotency UpdateInstance( google::cloud::filestore::v1::UpdateInstanceRequest const& request) = 0; virtual google::cloud::Idempotency RestoreInstance( google::cloud::filestore::v1::RestoreInstanceRequest const& request) = 0; virtual google::cloud::Idempotency DeleteInstance( google::cloud::filestore::v1::DeleteInstanceRequest const& request) = 0; virtual google::cloud::Idempotency ListBackups( google::cloud::filestore::v1::ListBackupsRequest request) = 0; virtual google::cloud::Idempotency GetBackup( google::cloud::filestore::v1::GetBackupRequest const& request) = 0; virtual google::cloud::Idempotency CreateBackup( google::cloud::filestore::v1::CreateBackupRequest const& request) = 0; virtual google::cloud::Idempotency DeleteBackup( google::cloud::filestore::v1::DeleteBackupRequest const& request) = 0; virtual google::cloud::Idempotency UpdateBackup( google::cloud::filestore::v1::UpdateBackupRequest const& request) = 0; }; std::unique_ptr<CloudFilestoreManagerConnectionIdempotencyPolicy> MakeDefaultCloudFilestoreManagerConnectionIdempotencyPolicy(); GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace filestore } // namespace cloud } // namespace google #endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_FILESTORE_CLOUD_FILESTORE_MANAGER_CONNECTION_IDEMPOTENCY_POLICY_H
39.369048
106
0.781675
[ "object" ]
bea28eadf5bfeb02daeb54c23db8f305e65eca0e
18,138
h
C
Models/CommonStateSignalAuthorChatCall.pb.h
wpscott/AcFunDanmaku-C-
c1b834dbb7133fd9d3908a8e0840747b759bdb0f
[ "MIT" ]
null
null
null
Models/CommonStateSignalAuthorChatCall.pb.h
wpscott/AcFunDanmaku-C-
c1b834dbb7133fd9d3908a8e0840747b759bdb0f
[ "MIT" ]
null
null
null
Models/CommonStateSignalAuthorChatCall.pb.h
wpscott/AcFunDanmaku-C-
c1b834dbb7133fd9d3908a8e0840747b759bdb0f
[ "MIT" ]
null
null
null
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: CommonStateSignalAuthorChatCall.proto #ifndef GOOGLE_PROTOBUF_INCLUDED_CommonStateSignalAuthorChatCall_2eproto #define GOOGLE_PROTOBUF_INCLUDED_CommonStateSignalAuthorChatCall_2eproto #include <limits> #include <string> #include <google/protobuf/port_def.inc> #if PROTOBUF_VERSION < 3014000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3014000 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/port_undef.inc> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/metadata_lite.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/unknown_field_set.h> #include "AuthorChatPlayerInfo.pb.h" // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> #define PROTOBUF_INTERNAL_EXPORT_CommonStateSignalAuthorChatCall_2eproto PROTOBUF_NAMESPACE_OPEN namespace internal { class AnyMetadata; } // namespace internal PROTOBUF_NAMESPACE_CLOSE // Internal implementation detail -- do not use these members. struct TableStruct_CommonStateSignalAuthorChatCall_2eproto { static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[1] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[]; }; extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_CommonStateSignalAuthorChatCall_2eproto; namespace AcFunDanmu { class CommonStateSignalAuthorChatCall; class CommonStateSignalAuthorChatCallDefaultTypeInternal; extern CommonStateSignalAuthorChatCallDefaultTypeInternal _CommonStateSignalAuthorChatCall_default_instance_; } // namespace AcFunDanmu PROTOBUF_NAMESPACE_OPEN template<> ::AcFunDanmu::CommonStateSignalAuthorChatCall* Arena::CreateMaybeMessage<::AcFunDanmu::CommonStateSignalAuthorChatCall>(Arena*); PROTOBUF_NAMESPACE_CLOSE namespace AcFunDanmu { // =================================================================== class CommonStateSignalAuthorChatCall PROTOBUF_FINAL : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:AcFunDanmu.CommonStateSignalAuthorChatCall) */ { public: inline CommonStateSignalAuthorChatCall() : CommonStateSignalAuthorChatCall(nullptr) {} virtual ~CommonStateSignalAuthorChatCall(); CommonStateSignalAuthorChatCall(const CommonStateSignalAuthorChatCall& from); CommonStateSignalAuthorChatCall(CommonStateSignalAuthorChatCall&& from) noexcept : CommonStateSignalAuthorChatCall() { *this = ::std::move(from); } inline CommonStateSignalAuthorChatCall& operator=(const CommonStateSignalAuthorChatCall& from) { CopyFrom(from); return *this; } inline CommonStateSignalAuthorChatCall& operator=(CommonStateSignalAuthorChatCall&& from) noexcept { if (GetArena() == from.GetArena()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const CommonStateSignalAuthorChatCall& default_instance(); static inline const CommonStateSignalAuthorChatCall* internal_default_instance() { return reinterpret_cast<const CommonStateSignalAuthorChatCall*>( &_CommonStateSignalAuthorChatCall_default_instance_); } static constexpr int kIndexInFileMessages = 0; friend void swap(CommonStateSignalAuthorChatCall& a, CommonStateSignalAuthorChatCall& b) { a.Swap(&b); } inline void Swap(CommonStateSignalAuthorChatCall* other) { if (other == this) return; if (GetArena() == other->GetArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(CommonStateSignalAuthorChatCall* other) { if (other == this) return; GOOGLE_DCHECK(GetArena() == other->GetArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline CommonStateSignalAuthorChatCall* New() const final { return CreateMaybeMessage<CommonStateSignalAuthorChatCall>(nullptr); } CommonStateSignalAuthorChatCall* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<CommonStateSignalAuthorChatCall>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const CommonStateSignalAuthorChatCall& from); void MergeFrom(const CommonStateSignalAuthorChatCall& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CommonStateSignalAuthorChatCall* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "AcFunDanmu.CommonStateSignalAuthorChatCall"; } protected: explicit CommonStateSignalAuthorChatCall(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_CommonStateSignalAuthorChatCall_2eproto); return ::descriptor_table_CommonStateSignalAuthorChatCall_2eproto.file_level_metadata[kIndexInFileMessages]; } public: // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kAuthorChatIdFieldNumber = 1, kInviterUserInfoFieldNumber = 2, kCallTimestampMsFieldNumber = 3, }; // string authorChatId = 1; void clear_authorchatid(); const std::string& authorchatid() const; void set_authorchatid(const std::string& value); void set_authorchatid(std::string&& value); void set_authorchatid(const char* value); void set_authorchatid(const char* value, size_t size); std::string* mutable_authorchatid(); std::string* release_authorchatid(); void set_allocated_authorchatid(std::string* authorchatid); private: const std::string& _internal_authorchatid() const; void _internal_set_authorchatid(const std::string& value); std::string* _internal_mutable_authorchatid(); public: // .AcFunDanmu.AuthorChatPlayerInfo inviterUserInfo = 2; bool has_inviteruserinfo() const; private: bool _internal_has_inviteruserinfo() const; public: void clear_inviteruserinfo(); const ::AcFunDanmu::AuthorChatPlayerInfo& inviteruserinfo() const; ::AcFunDanmu::AuthorChatPlayerInfo* release_inviteruserinfo(); ::AcFunDanmu::AuthorChatPlayerInfo* mutable_inviteruserinfo(); void set_allocated_inviteruserinfo(::AcFunDanmu::AuthorChatPlayerInfo* inviteruserinfo); private: const ::AcFunDanmu::AuthorChatPlayerInfo& _internal_inviteruserinfo() const; ::AcFunDanmu::AuthorChatPlayerInfo* _internal_mutable_inviteruserinfo(); public: void unsafe_arena_set_allocated_inviteruserinfo( ::AcFunDanmu::AuthorChatPlayerInfo* inviteruserinfo); ::AcFunDanmu::AuthorChatPlayerInfo* unsafe_arena_release_inviteruserinfo(); // int64 callTimestampMs = 3; void clear_calltimestampms(); ::PROTOBUF_NAMESPACE_ID::int64 calltimestampms() const; void set_calltimestampms(::PROTOBUF_NAMESPACE_ID::int64 value); private: ::PROTOBUF_NAMESPACE_ID::int64 _internal_calltimestampms() const; void _internal_set_calltimestampms(::PROTOBUF_NAMESPACE_ID::int64 value); public: // @@protoc_insertion_point(class_scope:AcFunDanmu.CommonStateSignalAuthorChatCall) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr authorchatid_; ::AcFunDanmu::AuthorChatPlayerInfo* inviteruserinfo_; ::PROTOBUF_NAMESPACE_ID::int64 calltimestampms_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_CommonStateSignalAuthorChatCall_2eproto; }; // =================================================================== // =================================================================== #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ // CommonStateSignalAuthorChatCall // string authorChatId = 1; inline void CommonStateSignalAuthorChatCall::clear_authorchatid() { authorchatid_.ClearToEmpty(); } inline const std::string& CommonStateSignalAuthorChatCall::authorchatid() const { // @@protoc_insertion_point(field_get:AcFunDanmu.CommonStateSignalAuthorChatCall.authorChatId) return _internal_authorchatid(); } inline void CommonStateSignalAuthorChatCall::set_authorchatid(const std::string& value) { _internal_set_authorchatid(value); // @@protoc_insertion_point(field_set:AcFunDanmu.CommonStateSignalAuthorChatCall.authorChatId) } inline std::string* CommonStateSignalAuthorChatCall::mutable_authorchatid() { // @@protoc_insertion_point(field_mutable:AcFunDanmu.CommonStateSignalAuthorChatCall.authorChatId) return _internal_mutable_authorchatid(); } inline const std::string& CommonStateSignalAuthorChatCall::_internal_authorchatid() const { return authorchatid_.Get(); } inline void CommonStateSignalAuthorChatCall::_internal_set_authorchatid(const std::string& value) { authorchatid_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena()); } inline void CommonStateSignalAuthorChatCall::set_authorchatid(std::string&& value) { authorchatid_.Set( ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena()); // @@protoc_insertion_point(field_set_rvalue:AcFunDanmu.CommonStateSignalAuthorChatCall.authorChatId) } inline void CommonStateSignalAuthorChatCall::set_authorchatid(const char* value) { GOOGLE_DCHECK(value != nullptr); authorchatid_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena()); // @@protoc_insertion_point(field_set_char:AcFunDanmu.CommonStateSignalAuthorChatCall.authorChatId) } inline void CommonStateSignalAuthorChatCall::set_authorchatid(const char* value, size_t size) { authorchatid_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string( reinterpret_cast<const char*>(value), size), GetArena()); // @@protoc_insertion_point(field_set_pointer:AcFunDanmu.CommonStateSignalAuthorChatCall.authorChatId) } inline std::string* CommonStateSignalAuthorChatCall::_internal_mutable_authorchatid() { return authorchatid_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena()); } inline std::string* CommonStateSignalAuthorChatCall::release_authorchatid() { // @@protoc_insertion_point(field_release:AcFunDanmu.CommonStateSignalAuthorChatCall.authorChatId) return authorchatid_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void CommonStateSignalAuthorChatCall::set_allocated_authorchatid(std::string* authorchatid) { if (authorchatid != nullptr) { } else { } authorchatid_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), authorchatid, GetArena()); // @@protoc_insertion_point(field_set_allocated:AcFunDanmu.CommonStateSignalAuthorChatCall.authorChatId) } // .AcFunDanmu.AuthorChatPlayerInfo inviterUserInfo = 2; inline bool CommonStateSignalAuthorChatCall::_internal_has_inviteruserinfo() const { return this != internal_default_instance() && inviteruserinfo_ != nullptr; } inline bool CommonStateSignalAuthorChatCall::has_inviteruserinfo() const { return _internal_has_inviteruserinfo(); } inline const ::AcFunDanmu::AuthorChatPlayerInfo& CommonStateSignalAuthorChatCall::_internal_inviteruserinfo() const { const ::AcFunDanmu::AuthorChatPlayerInfo* p = inviteruserinfo_; return p != nullptr ? *p : reinterpret_cast<const ::AcFunDanmu::AuthorChatPlayerInfo&>( ::AcFunDanmu::_AuthorChatPlayerInfo_default_instance_); } inline const ::AcFunDanmu::AuthorChatPlayerInfo& CommonStateSignalAuthorChatCall::inviteruserinfo() const { // @@protoc_insertion_point(field_get:AcFunDanmu.CommonStateSignalAuthorChatCall.inviterUserInfo) return _internal_inviteruserinfo(); } inline void CommonStateSignalAuthorChatCall::unsafe_arena_set_allocated_inviteruserinfo( ::AcFunDanmu::AuthorChatPlayerInfo* inviteruserinfo) { if (GetArena() == nullptr) { delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(inviteruserinfo_); } inviteruserinfo_ = inviteruserinfo; if (inviteruserinfo) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:AcFunDanmu.CommonStateSignalAuthorChatCall.inviterUserInfo) } inline ::AcFunDanmu::AuthorChatPlayerInfo* CommonStateSignalAuthorChatCall::release_inviteruserinfo() { ::AcFunDanmu::AuthorChatPlayerInfo* temp = inviteruserinfo_; inviteruserinfo_ = nullptr; if (GetArena() != nullptr) { temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } return temp; } inline ::AcFunDanmu::AuthorChatPlayerInfo* CommonStateSignalAuthorChatCall::unsafe_arena_release_inviteruserinfo() { // @@protoc_insertion_point(field_release:AcFunDanmu.CommonStateSignalAuthorChatCall.inviterUserInfo) ::AcFunDanmu::AuthorChatPlayerInfo* temp = inviteruserinfo_; inviteruserinfo_ = nullptr; return temp; } inline ::AcFunDanmu::AuthorChatPlayerInfo* CommonStateSignalAuthorChatCall::_internal_mutable_inviteruserinfo() { if (inviteruserinfo_ == nullptr) { auto* p = CreateMaybeMessage<::AcFunDanmu::AuthorChatPlayerInfo>(GetArena()); inviteruserinfo_ = p; } return inviteruserinfo_; } inline ::AcFunDanmu::AuthorChatPlayerInfo* CommonStateSignalAuthorChatCall::mutable_inviteruserinfo() { // @@protoc_insertion_point(field_mutable:AcFunDanmu.CommonStateSignalAuthorChatCall.inviterUserInfo) return _internal_mutable_inviteruserinfo(); } inline void CommonStateSignalAuthorChatCall::set_allocated_inviteruserinfo(::AcFunDanmu::AuthorChatPlayerInfo* inviteruserinfo) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena(); if (message_arena == nullptr) { delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(inviteruserinfo_); } if (inviteruserinfo) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(inviteruserinfo)->GetArena(); if (message_arena != submessage_arena) { inviteruserinfo = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, inviteruserinfo, submessage_arena); } } else { } inviteruserinfo_ = inviteruserinfo; // @@protoc_insertion_point(field_set_allocated:AcFunDanmu.CommonStateSignalAuthorChatCall.inviterUserInfo) } // int64 callTimestampMs = 3; inline void CommonStateSignalAuthorChatCall::clear_calltimestampms() { calltimestampms_ = PROTOBUF_LONGLONG(0); } inline ::PROTOBUF_NAMESPACE_ID::int64 CommonStateSignalAuthorChatCall::_internal_calltimestampms() const { return calltimestampms_; } inline ::PROTOBUF_NAMESPACE_ID::int64 CommonStateSignalAuthorChatCall::calltimestampms() const { // @@protoc_insertion_point(field_get:AcFunDanmu.CommonStateSignalAuthorChatCall.callTimestampMs) return _internal_calltimestampms(); } inline void CommonStateSignalAuthorChatCall::_internal_set_calltimestampms(::PROTOBUF_NAMESPACE_ID::int64 value) { calltimestampms_ = value; } inline void CommonStateSignalAuthorChatCall::set_calltimestampms(::PROTOBUF_NAMESPACE_ID::int64 value) { _internal_set_calltimestampms(value); // @@protoc_insertion_point(field_set:AcFunDanmu.CommonStateSignalAuthorChatCall.callTimestampMs) } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ // @@protoc_insertion_point(namespace_scope) } // namespace AcFunDanmu // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc> #endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_CommonStateSignalAuthorChatCall_2eproto
42.981043
139
0.782776
[ "object" ]
bea2abb235e98f309db35beb623ade3d93d555f4
48,754
h
C
source/containers/vgeometry.h
xvela/code-vault
780dad2d2855e28d802a64baf781927b7edd9ed9
[ "MIT" ]
2
2019-01-09T19:09:45.000Z
2019-04-02T17:53:49.000Z
source/containers/vgeometry.h
xvela/code-vault
780dad2d2855e28d802a64baf781927b7edd9ed9
[ "MIT" ]
17
2015-01-07T02:05:04.000Z
2019-08-30T16:57:42.000Z
source/containers/vgeometry.h
xvela/code-vault
780dad2d2855e28d802a64baf781927b7edd9ed9
[ "MIT" ]
3
2016-04-06T19:01:11.000Z
2017-09-20T09:28:00.000Z
/* Copyright c1997-2014 Trygve Isaacson. All rights reserved. This file is part of the Code Vault version 4.1 http://www.bombaydigital.com/ License: MIT. See LICENSE.md in the Vault top level directory. */ #ifndef vgeometry_h #define vgeometry_h /** @file */ #include "vtypes.h" #include "vexception.h" #include "vbinaryiostream.h" #ifdef VAULT_QT_SUPPORT #include <QSize> #include <QSizeF> #include <QPoint> #include <QPointF> #include <QLine> #include <QLineF> #include <QRect> #include <QRectF> #include <QPolygon> #include <QPolygonF> #endif namespace VGeometry { /* When using VDouble types, tests for equality and inequality are of dubious use, because fine precision can be lost even in the simplest calculations, rendering unexpected results. (For example, 5.9 + 2.3 may not "==" 8.2 .) The equal() and notEqual() functions let you test for approximate equality within 0.000001. In order for the templates to work with both VDouble and int, we define int versions, too, and those do an exact test. */ extern bool equal(VDouble a, VDouble b); ///< Returns true if the two doubles are equal to within 0.000001. extern bool notEqual(VDouble a, VDouble b); ///< Returns true if the two doubles are not equal to within 0.000001. extern bool equal(int a, int b); ///< Returns true if the two ints are equal. (Used in template-based code below regardless of type.) extern bool notEqual(int a, int b); ///< Returns true if the two ints are not equal. (Used in template-based code below regardless of type.) extern void writePairToStream(VBinaryIOStream& stream, VDouble item1, VDouble item2); extern void readPairFromStream(VBinaryIOStream& stream, VDouble& item1, VDouble& item2); extern void writePairToStream(VBinaryIOStream& stream, int item1, int item2); extern void readPairFromStream(VBinaryIOStream& stream, int& item1, int& item2); extern void writeTripletToStream(VBinaryIOStream& stream, VDouble item1, VDouble item2, VDouble item3); extern void readTripletFromStream(VBinaryIOStream& stream, VDouble& item1, VDouble& item2, VDouble& item3); extern void writeTripletToStream(VBinaryIOStream& stream, int item1, int item2, int item3); extern void readTripletFromStream(VBinaryIOStream& stream, int& item1, int& item2, int& item3); extern VDouble getDistance(VDouble dx, VDouble dy); ///< Returns the distance between two double-based points. extern VDouble getDistance(int dx, int dy); ///< Returns the distance between two int-based points; the result must be a double. } /* These types are define as templates, simply in order to allow each to be used with both "int" and "VDouble" coordinates, without requiring complete duplicated implementations. Because they are templates, all functions must be coded inline here; no separating the declaration here from an implementation in the .cpp file. Wherever there is a short function I just put it on the same line as the function name; otherwise I break it out into a multi-line code block kind of like a normal implementation. */ template <typename T> class VSizeT; template <typename T> bool operator== (const VSizeT<T>& s1, const VSizeT<T>& s2); template <typename T> bool operator!= (const VSizeT<T>& s1, const VSizeT<T>& s2); template <typename T> VSizeT<T> operator+ (const VSizeT<T>& s1, const VSizeT<T>& s2); template <typename T> VSizeT<T> operator- (const VSizeT<T>& s1, const VSizeT<T>& s2); template <typename T> VSizeT<T> operator*(const VSizeT<T>& x, T scale); template <typename T> VSizeT<T> operator*(T scale, const VSizeT<T>& x); template <typename T> VSizeT<T> operator/ (const VSizeT<T>& x, T divisor); /** VSizeT defines a width and height. VSize uses VDouble values; VISize uses int values. */ template <typename T> class VSizeT { public: VSizeT() : mWidth(0), mHeight(0) {} VSizeT(T width, T height) : mWidth(width), mHeight(height) {} VSizeT(VBinaryIOStream& stream) : mWidth(0), mHeight(0) { VGeometry::readPairFromStream(stream, mWidth, mHeight); } ~VSizeT() {} #ifdef VAULT_QT_SUPPORT VSizeT(const QSize& s) : mWidth(s.width()), mHeight(s.height()) {} VSizeT(const QSizeF& s) : mWidth(static_cast<T>(s.width())), mHeight(static_cast<T>(s.height())) {} #endif void readFromStream(VBinaryIOStream& stream) { VGeometry::readPairFromStream(stream, mWidth, mHeight); } void writeToStream(VBinaryIOStream& stream) const { VGeometry::writePairToStream(stream, mWidth, mHeight); } T getWidth() const { return mWidth; } T getHeight() const { return mHeight; } void setWidth(T width) { mWidth = width; } void setHeight(T height) { mHeight = height; } T& rWidth() { return mWidth; } T& rHeight() { return mHeight; } VSizeT<T>& operator+=(const VSizeT<T>& x) { mWidth += x.mWidth; mHeight += x.mHeight; return *this; } VSizeT<T>& operator-=(const VSizeT<T>& x) { mWidth -= x.mWidth; mHeight -= x.mHeight; return *this; } VSizeT<T>& operator*=(T scale) { mWidth *= scale; mHeight *= scale; return *this; } VSizeT<T>& operator/=(T divisor) { if (divisor == 0) throw VRangeException("VSizeT divide by zero."); mWidth /= divisor; mHeight /= divisor; return *this; } // These use "approximate" equality by testing for a difference >= 0.000001. static bool equal(const VSizeT<T>& s1, const VSizeT<T>& s2) { return VGeometry::equal(s1.mWidth, s2.mWidth) && VGeometry::equal(s1.mHeight, s2.mHeight); } static bool notEqual(const VSizeT<T>& s1, const VSizeT<T>& s2) { return VGeometry::notEqual(s1.mWidth, s2.mWidth) || VGeometry::notEqual(s1.mHeight, s2.mHeight); } friend bool operator== <>(const VSizeT<T>& s1, const VSizeT<T>& s2); // exact equality friend bool operator!= <>(const VSizeT<T>& s1, const VSizeT<T>& s2); // exact inequality friend VSizeT<T> operator+ <>(const VSizeT<T>& s1, const VSizeT<T>& s2); // addition friend VSizeT<T> operator- <>(const VSizeT<T>& s1, const VSizeT<T>& s2); // subtraction friend VSizeT<T> operator* <>(const VSizeT<T>& x, T scale); // multiplication p*n friend VSizeT<T> operator* <>(T scale, const VSizeT<T>& x); // multiplication n*p friend VSizeT<T> operator/ <>(const VSizeT<T>& x, T divisor); // division #ifdef VAULT_QT_SUPPORT void setQSize(const QSize& s) { mWidth = s.width(); mHeight = s.height(); } QSize getQSize() const { return QSize(static_cast<int>(mWidth), static_cast<int>(mHeight)); } void setQSizeF(const QSizeF& s) { mWidth = static_cast<T>(s.width()); mHeight = static_cast<T>(s.height()); } QSizeF getQSizeF() const { return QSizeF(mWidth, mHeight); } #endif private: T mWidth; T mHeight; }; template<typename T> bool operator==(const VSizeT<T>& s1, const VSizeT<T>& s2) { return s1.mWidth == s2.mWidth && s1.mHeight == s2.mHeight; } template<typename T> bool operator!=(const VSizeT<T>& s1, const VSizeT<T>& s2) { return s1.mWidth != s2.mWidth || s1.mHeight != s2.mHeight; } template<typename T> VSizeT<T> operator+(const VSizeT<T>& s1, const VSizeT<T>& s2) { return VSizeT<T>(s1.mWidth + s2.mWidth, s1.mHeight + s2.mHeight); } template<typename T> VSizeT<T> operator-(const VSizeT<T>& s1, const VSizeT<T>& s2) { return VSizeT<T>(s1.mWidth - s2.mWidth, s1.mHeight - s2.mHeight); } template<typename T> VSizeT<T> operator*(const VSizeT<T>& x, T scale) { return VSizeT<T>(x.mWidth * scale, x.mHeight * scale); } template<typename T> VSizeT<T> operator*(T scale, const VSizeT<T>& x) { return VSizeT<T>(x.mWidth * scale, x.mHeight * scale); } template<typename T> VSizeT<T> operator/(const VSizeT<T>& x, T divisor) { if (divisor == 0) throw VRangeException("VSizeT divide by zero."); return VSizeT<T>(x.mWidth / divisor, x.mHeight / divisor); } typedef VSizeT<VDouble> VSize; ///< A size defined by w/h doubles. typedef VSizeT<int> VISize; ///< A size defined by w/h ints. template <typename T> class VPointT; template <typename T> bool operator== (const VPointT<T>& p1, const VPointT<T>& p2); template <typename T> bool operator!= (const VPointT<T>& p1, const VPointT<T>& p2); template <typename T> VPointT<T> operator+ (const VPointT<T>& p1, const VPointT<T>& p2); template <typename T> VPointT<T> operator+ (const VPointT<T>& p, const VSizeT<T>& s); template <typename T> VPointT<T> operator- (const VPointT<T>& p1, const VPointT<T>& p2); template <typename T> VPointT<T> operator- (const VPointT<T>& p, const VSizeT<T>& s); template <typename T> VPointT<T> operator- (const VPointT<T>& p); template <typename T> VPointT<T> operator*(const VPointT<T>& p, T scale); template <typename T> VPointT<T> operator*(T scale, const VPointT<T>& p); template <typename T> VPointT<T> operator/ (const VPointT<T>& p, T divisor); /** VPointT defines a point with x and y coordinates. VPoint uses VDouble coordinates; VIPoint uses int coordinates. */ template <typename T> class VPointT { public: /** Returns the distance between two points. */ static VDouble getDistance(const VPointT<T>& p1, const VPointT<T>& p2) { return VGeometry::getDistance(p2.getX() - p1.getX(), p2.getY() - p1.getY()); } VPointT() : mX(0), mY(0) {} VPointT(T x, T y) : mX(x), mY(y) {} VPointT(VBinaryIOStream& stream) : mX(0), mY(0) { VGeometry::readPairFromStream(stream, mX, mY); } ~VPointT() {} #ifdef VAULT_QT_SUPPORT VPointT(const QPoint& p) : mX(p.x()), mY(p.y()) {} VPointT(const QPointF& p) : mX(static_cast<T>(p.x())), mY(static_cast<T>(p.y())) {} #endif void readFromStream(VBinaryIOStream& stream) { VGeometry::readPairFromStream(stream, mX, mY); } void writeToStream(VBinaryIOStream& stream) const { VGeometry::writePairToStream(stream, mX, mY); } T getX() const { return mX; } T getY() const { return mY; } void setX(T x) { mX = x; } void setY(T y) { mY = y; } T& rX() { return mX; } T& rY() { return mY; } VPointT<T>& operator+=(const VPointT<T>& p) { mX += p.mX; mY += p.mY; return *this; } VPointT<T>& operator-=(const VPointT<T>& p) { mX -= p.mX; mY -= p.mY; return *this; } VPointT<T>& operator*=(T scale) { mX *= scale; mY *= scale; return *this; } VPointT<T>& operator/=(T divisor) { if (divisor == 0) throw VRangeException("VPointT divide by zero."); mX /= divisor; mY /= divisor; return *this; } // These use "approximate" equality by testing for a difference >= 0.000001. static bool equal(const VPointT<T>& p1, const VPointT<T>& p2) { return VGeometry::equal(p1.mX, p2.mX) && VGeometry::equal(p1.mY, p2.mY); } static bool notEqual(const VPointT<T>& p1, const VPointT<T>& p2) { return VGeometry::notEqual(p1.mX, p2.mX) || VGeometry::notEqual(p1.mY, p2.mY); } friend bool operator== <>(const VPointT<T>& p1, const VPointT<T>& p2); // exact equality friend bool operator!= <>(const VPointT<T>& p1, const VPointT<T>& p2); // exact inequality friend VPointT<T> operator+ <>(const VPointT<T>& p1, const VPointT<T>& p2); // addition friend VPointT<T> operator+ <>(const VPointT<T>& p, const VSizeT<T>& s); // addition friend VPointT<T> operator- <>(const VPointT<T>& p1, const VPointT<T>& p2); // subtraction friend VPointT<T> operator- <>(const VPointT<T>& p, const VSizeT<T>& s); // subtraction friend VPointT<T> operator- <>(const VPointT<T>& p); // negation friend VPointT<T> operator* <>(const VPointT<T>& p, T scale); // multiplication p*n friend VPointT<T> operator* <>(T scale, const VPointT<T>& p); // multiplication n*p friend VPointT<T> operator/ <>(const VPointT<T>& p, T divisor); // division #ifdef VAULT_QT_SUPPORT void setQPoint(const QPoint& p) { mX = p.x(); mY = p.y(); } QPoint getQPoint() const { return QPoint(static_cast<int>(mX), static_cast<int>(mY)); } void setQPointF(const QPointF& p) { mX = static_cast<T>(p.x()); mY = static_cast<T>(p.y()); } QPointF getQPointF() const { return QPointF(mX, mY); } #endif private: T mX; T mY; }; template<typename T> bool operator==(const VPointT<T>& p1, const VPointT<T>& p2) { return p1.mX == p2.mX && p1.mY == p2.mY; } template<typename T> bool operator!=(const VPointT<T>& p1, const VPointT<T>& p2) { return p1.mX != p2.mX || p1.mY != p2.mY; } template<typename T> VPointT<T> operator+(const VPointT<T>& p1, const VPointT<T>& p2) { return VPointT<T>(p1.mX + p2.mX, p1.mY + p2.mY); } template<typename T> VPointT<T> operator+(const VPointT<T>& p, const VSizeT<T>& s) { return VPointT<T>(p.mX + s.getWidth(), p.mY + s.getHeight()); } template<typename T> VPointT<T> operator-(const VPointT<T>& p1, const VPointT<T>& p2) { return VPointT<T>(p1.mX - p2.mX, p1.mY - p2.mY); } template<typename T> VPointT<T> operator-(const VPointT<T>& p, const VSizeT<T>& s) { return VPointT<T>(p.mX - s.getWidth(), p.mY - s.getHeight()); } template<typename T> VPointT<T> operator-(const VPointT<T>& p) { return VPointT<T>(-p.mX, -p.mY); } template<typename T> VPointT<T> operator*(const VPointT<T>& p, T scale) { return VPointT<T>(p.mX * scale, p.mY * scale); } template<typename T> VPointT<T> operator*(T scale, const VPointT<T>& p) { return VPointT<T>(p.mX * scale, p.mY * scale); } template<typename T> VPointT<T> operator/(const VPointT<T>& p, T divisor) { if (divisor == 0) throw VRangeException("VPointT divide by zero."); return VPointT<T>(p.mX / divisor, p.mY / divisor); } typedef VPointT<VDouble> VPoint; ///< A point defined by x/y doubles. typedef VPointT<int> VIPoint; ///< A point defined by x/y ints. typedef std::vector<VPoint> VPointVector; typedef std::vector<VIPoint> VIPointVector; template <typename T> class VPoint3DT; template <typename T> bool operator== (const VPoint3DT<T>& p1, const VPoint3DT<T>& p2); template <typename T> bool operator!= (const VPoint3DT<T>& p1, const VPoint3DT<T>& p2); template <typename T> VPoint3DT<T> operator+ (const VPoint3DT<T>& p1, const VPoint3DT<T>& p2); template <typename T> VPoint3DT<T> operator- (const VPoint3DT<T>& p1, const VPoint3DT<T>& p2); template <typename T> VPoint3DT<T> operator- (const VPoint3DT<T>& p); template <typename T> VPoint3DT<T> operator*(const VPoint3DT<T>& p, T scale); template <typename T> VPoint3DT<T> operator*(T scale, const VPoint3DT<T>& p); template <typename T> VPoint3DT<T> operator/ (const VPoint3DT<T>& p, T divisor); /** VPoint3DT defines a point with x, y, and z coordinates. VPoint3D uses VDouble coordinates; VIPoint3D uses int coordinates. */ template <typename T> class VPoint3DT { public: VPoint3DT() : mX(0), mY(0), mZ(0) {} VPoint3DT(T x, T y, T z) : mX(x), mY(y), mZ(z) {} VPoint3DT(VBinaryIOStream& stream) : mX(0), mY(0), mZ(0) { VGeometry::readTripletFromStream(stream, mX, mY, mZ); } ~VPoint3DT() {} void readFromStream(VBinaryIOStream& stream) { VGeometry::readTripletFromStream(stream, mX, mY, mZ); } void writeToStream(VBinaryIOStream& stream) const { VGeometry::writeTripletToStream(stream, mX, mY, mZ); } T getX() const { return mX; } T getY() const { return mY; } T getZ() const { return mZ; } void setX(T x) { mX = x; } void setY(T y) { mY = y; } void setZ(T z) { mZ = z; } T& rX() { return mX; } T& rY() { return mY; } T& rZ() { return mZ; } void setNull() { setX(0); setY(0); setZ(0); } VPoint3DT<T>& operator+=(const VPoint3DT<T>& p) { mX += p.mX; mY += p.mY; mZ += p.mZ; return *this; } VPoint3DT<T>& operator-=(const VPoint3DT<T>& p) { mX -= p.mX; mY -= p.mY; mZ -= p.mZ; return *this; } VPoint3DT<T>& operator*=(T scale) { mX *= scale; mY *= scale; mZ *= scale; return *this; } VPoint3DT<T>& operator/=(T divisor) { if (divisor == 0) throw VRangeException("VPoint3DT divide by zero."); mX /= divisor; mY /= divisor; mZ /= divisor; return *this; } // These use "approximate" equality by testing for a difference >= 0.000001. static bool equal(const VPoint3DT<T>& p1, const VPoint3DT<T>& p2) { return VGeometry::equal(p1.mX, p2.mX) && VGeometry::equal(p1.mY, p2.mY) && VGeometry::equal(p1.mZ, p2.mZ); } static bool notEqual(const VPoint3DT<T>& p1, const VPoint3DT<T>& p2) { return VGeometry::notEqual(p1.mX, p2.mX) || VGeometry::notEqual(p1.mY, p2.mY) || VGeometry::notEqual(p1.mZ, p2.mZ); } friend bool operator== <>(const VPoint3DT<T>& p1, const VPoint3DT<T>& p2); // exact equality friend bool operator!= <>(const VPoint3DT<T>& p1, const VPoint3DT<T>& p2); // exact inequality friend VPoint3DT<T> operator+ <>(const VPoint3DT<T>& p1, const VPoint3DT<T>& p2); // addition friend VPoint3DT<T> operator- <>(const VPoint3DT<T>& p1, const VPoint3DT<T>& p2); // subtraction friend VPoint3DT<T> operator- <>(const VPoint3DT<T>& p); // negation friend VPoint3DT<T> operator* <>(const VPoint3DT<T>& p, T scale); // multiplication p*n friend VPoint3DT<T> operator* <>(T scale, const VPoint3DT<T>& p); // multiplication n*p friend VPoint3DT<T> operator/ <>(const VPoint3DT<T>& p, T divisor); // division private: T mX; T mY; T mZ; }; template<typename T> bool operator==(const VPoint3DT<T>& p1, const VPoint3DT<T>& p2) { return p1.mX == p2.mX && p1.mY == p2.mY && p1.mZ == p2.mZ; } template<typename T> bool operator!=(const VPoint3DT<T>& p1, const VPoint3DT<T>& p2) { return p1.mX != p2.mX || p1.mY != p2.mY || p1.mZ != p2.mZ; } template<typename T> VPoint3DT<T> operator+(const VPoint3DT<T>& p1, const VPoint3DT<T>& p2) { return VPoint3DT<T>(p1.mX + p2.mX, p1.mY + p2.mY, p1.mZ + p2.mZ); } template<typename T> VPoint3DT<T> operator-(const VPoint3DT<T>& p1, const VPoint3DT<T>& p2) { return VPoint3DT<T>(p1.mX - p2.mX, p1.mY - p2.mY, p1.mZ - p2.mZ); } template<typename T> VPoint3DT<T> operator-(const VPoint3DT<T>& p) { return VPoint3DT<T>(-p.mX, -p.mY, -p.mZ); } template<typename T> VPoint3DT<T> operator*(const VPoint3DT<T>& p, T scale) { return VPoint3DT<T>(p.mX * scale, p.mY * scale, p.mZ * scale); } template<typename T> VPoint3DT<T> operator*(T scale, const VPoint3DT<T>& p) { return VPoint3DT<T>(p.mX * scale, p.mY * scale, p.mZ * scale); } template<typename T> VPoint3DT<T> operator/(const VPoint3DT<T>& p, T divisor) { if (divisor == 0) throw VRangeException("VPoint3DT divide by zero."); return VPoint3DT<T>(p.mX / divisor, p.mY / divisor, p.mZ / divisor); } typedef VPoint3DT<VDouble> VPoint3D; ///< A 3D point defined by x/y/z doubles. typedef VPoint3DT<int> VIPoint3D; ///< A 3D point defined by x/y/z ints. template <typename T> class VLineT; template <typename T> bool operator== (const VLineT<T>& line1, const VLineT<T>& line2); // equality of start and end template <typename T> bool operator!= (const VLineT<T>& line1, const VLineT<T>& line2); // inequality of start or end /** VLineT defines a line segment with two points. The order matters for equality and math. Use the same() function to test equality without respect to the order of the two points. VLine uses VDouble coordinates; VILine uses int coordinates. */ template <typename T> class VLineT { public: VLineT() : mP1(), mP2() {} VLineT(VPointT<T> start, VPointT<T> end) : mP1(start), mP2(end) {} VLineT(VPointT<T> start, VSizeT<T> vec) : mP1(start), mP2(start + vec) {} VLineT(T x1, T y1, T x2, T y2) : mP1(x1, y1), mP2(x2, y2) {} VLineT(T x1, T y1, VSizeT<T> vec) : mP1(x1, y1), mP2(VPointT<T>(x1, y1) + vec) {} VLineT(VBinaryIOStream& stream) : mP1(), mP2() { mP1.readFromStream(stream); mP2.readFromStream(stream); } ~VLineT() {} #ifdef VAULT_QT_SUPPORT VLineT(const QLine& line) : mP1(line.p1()), mP2(line.p2()) {} VLineT(const QLineF& line) : mP1(line.p1()), mP2(line.p2()) {} #endif void readFromStream(VBinaryIOStream& stream) { mP1.readFromStream(stream); mP2.readFromStream(stream); } void writeToStream(VBinaryIOStream& stream) const { mP1.writeToStream(stream); mP2.writeToStream(stream); } VPointT<T> getP1() const { return mP1; } VPointT<T> getP2() const { return mP2; } void setP1(VPointT<T> p) { mP1 = p; } void setP2(VPointT<T> p) { mP2 = p; } void setPoints(VPointT<T> p1, VPointT<T> p2) { mP1 = p1; mP2 = p2; } VPointT<T>& rP1() { return mP1; } VPointT<T>& rP2() { return mP2; } VSizeT<T> getSize() const { return VSizeT<T>(this->getDX(), this->getDY()); } T getDX() const { return mP2.getX() - mP1.getX(); } T getDY() const { return mP2.getY() - mP1.getY(); } VDouble getLength() const { return VGeometry::getDistance(this->getDX(), this->getDY()); } void translate(const VPointT<T>& delta) { mP1 += delta; mP2 += delta; } void translate(T deltaX, T deltaY) { this->translate(VPointT<T>(deltaX, deltaY)); } VLineT<T> translated(const VPointT<T>& delta) const { VLineT<T> line(*this); line.translate(delta); return line; } VLineT<T> translated(T deltaX, T deltaY) const { return this->translated(VPointT<T>(deltaX, deltaY)); } /** Normalizes the line in the following sense: The resulting line's P1 and P2 will point left-to-right (+x), and if the x values are the same, it will point top-to-bottom (+y). This can be useful when comparing or using two lines when you don't want the "directionality" of the line to matter. @return a normalized copy of this line */ VLineT<T> normalized() const { if (mP1.getX() < mP2.getX()) { return *this; } else if (mP1.getX() > mP2.getX()) { return VLineT<T>(mP2, mP1); } else if (mP1.getY() < mP2.getY()) { return *this; } return VLineT<T>(mP2, mP1); } VLineT<T> reversed() const { return VLineT<T>(mP2, mP1); } /** Returns a VLine starting at P1, towards P2 but with length 1.0. @return a unit vector of this line */ VLineT<VDouble> getUnitVector() const { VDouble length = this->getLength(); if (length == 0.0) return VLineT<T>(); return VLineT<T>(mP1, (this->getSize() / length)); } // These use "approximate" equality by testing for a difference >= 0.000001. static bool equal(const VLineT<T>& line1, const VLineT<T>& line2) { return VPointT<T>::equal(line1.mP1, line2.mP1) && VPointT<T>::equal(line1.mP2, line2.mP2); } static bool notEqual(const VLineT<T>& line1, const VLineT<T>& line2) { return VPointT<T>::notEqual(line1.mP1, line2.mP1) || VPointT<T>::notEqual(line1.mP2, line2.mP2); } /** Returns true if the two lines have the same endpoints (within 0.000001), regardless of their order. @param line1 a line @param line2 a line @return true if line1 and line2 have the same endpoints */ static bool same(const VLineT<T>& line1, const VLineT<T>& line2) { return VLineT<T>::equal(line1.normalized(), line2.normalized()); } friend bool operator== <>(const VLineT<T>& line1, const VLineT<T>& line2); // exact equality friend bool operator!= <>(const VLineT<T>& line1, const VLineT<T>& line2); // exact inequality #ifdef VAULT_QT_SUPPORT void setQLine(const QLine& line) { mP1 = line.p1(); mP2 = line.p2(); } QLine getQLine() const { return QLine(mP1.getQPoint(), mP2.getQPoint()); } void setQLineF(const QLineF& line) { mP1.setQPointF(line.p1()); mP2.setQPointF(line.p2()); } QLineF getQLineF() const { return QLineF(mP1, mP2); } #endif /** Returns the point on this line (AB) that is the nearest to the supplied point C. You can specify whether this line is treated as a line segment (result within the segment) or not (result may be outside the segment). Note the input and result points are VPoint, not VPointT<T>, because even if this line is integer-based, the result may not be. @param C a point to test @param restrictToSegment true if the result must lie between endpoints @return the point along this line (or within segment) that is nearest to C */ VPoint getNearestPoint(const VPoint& C, bool restrictToSegment) const { // Name shortcuts for readability. const VDouble cx = C.getX(); const VDouble cy = C.getY(); const VDouble ax = mP1.getX(); const VDouble ay = mP1.getY(); const VDouble bx = mP2.getX(); const VDouble by = mP2.getY(); const VDouble ratioABNumerator = (cx - ax) * (bx - ax) + (cy - ay) * (by - ay); const VDouble ratioABDenomenator = (bx - ax) * (bx - ax) + (by - ay) * (by - ay); const VDouble ratioAB = ratioABNumerator / ratioABDenomenator; // how far along the segment A->B is nearest point (0.0 = @A, 1.0 = @B) // P is the result. We may need to restrict it to the segment ( next. VPoint P(ax + (ratioAB*(bx - ax)), ay + (ratioAB*(by - ay))); // You can uncomment these if needed for debugging. // const VDouble s = ((ay-cy)*(bx-ax)-(ax-cx)*(by-ay) ) / ratioABDenomenator; // const VDouble distanceToLine = V_FABS(s) * sqrt(ratioABDenomenator); // VDouble distanceToSegment = 0.0; if (((ratioAB >= 0.0) && (ratioAB <= 1.0)) || !restrictToSegment) { // nearest point is inside segment, or we don't care that it's outside // distanceToSegment = distanceToLine; } else { // Select the nearest endpoint of the segment. // Avoid calling sqrt until needed. const VDouble P1_distance_squared = (cx - ax) * (cx - ax) + (cy - ay) * (cy - ay); const VDouble P2_distance_squared = (cx - bx) * (cx - bx) + (cy - by) * (cy - by); if (P1_distance_squared < P2_distance_squared) { P = mP1; // distanceToSegment = sqrt(P1_distance_squared); } else { P = mP2; // distanceToSegment = sqrt(P2_distance_squared); } } return P; } VDouble getDistanceToPoint(const VPoint& p, bool restrictToSegment) const { VPoint nearestPointOnLine = this->getNearestPoint(p, restrictToSegment); return VPoint::getDistance(p, nearestPointOnLine); } private: VPointT<T> mP1; VPointT<T> mP2; }; template<typename T> bool operator==(const VLineT<T>& line1, const VLineT<T>& line2) { return line1.mP1 == line2.mP1 && line1.mP2 == line2.mP2; } template<typename T> bool operator!=(const VLineT<T>& line1, const VLineT<T>& line2) { return line1.mP1 != line2.mP1 || line1.mP2 != line2.mP2; } typedef VLineT<VDouble> VLine; ///< A line defined by double-based points. typedef VLineT<int> VILine; ///< A line defined by integer-based points. template <typename T> class VPolygonT; // forward declaration for use by VRectT template <typename T> class VRectT; template <typename T> bool operator== (const VRectT<T>& p1, const VRectT<T>& p2); template <typename T> bool operator!= (const VRectT<T>& p1, const VRectT<T>& p2); /** VRectT defines a rectangle. VRect uses VDouble coordinates; VIRect uses int coordinates. */ template <typename T> class VRectT { public: VRectT() : mLeftTop(), mSize() {} VRectT(const VPointT<T>& leftTop, const VSizeT<T>& size) : mLeftTop(leftTop), mSize(size) {} VRectT(const VPointT<T>& leftTop, const VPointT<T>& rightBottom) : mLeftTop(leftTop), mSize(rightBottom.getX() - leftTop.getX(), rightBottom.getY() - leftTop.getY()) {} VRectT(VBinaryIOStream& stream) : mLeftTop(stream), mSize(stream) {} VRectT(T left, T top, T width, T height) : mLeftTop(left, top), mSize(width, height) {} ~VRectT() {} #ifdef VAULT_QT_SUPPORT VRectT(const QRect& r) : mLeftTop(r.topLeft()), mSize(r.size()) {} VRectT(const QRectF& r) : mLeftTop(static_cast<VPointT<T> >(r.topLeft())), mSize(static_cast<VSizeT<T> >(r.size())) {} #endif void readFromStream(VBinaryIOStream& stream) { mLeftTop.readFromStream(stream); mSize.readFromStream(stream); } void writeToStream(VBinaryIOStream& stream) const { mLeftTop.writeToStream(stream); mSize.writeToStream(stream); } VPointT<T> getLeftTop() const { return mLeftTop; } VPointT<T> getRightBottom() const { return VPointT<T>(mLeftTop + mSize); } VPointT<T> getRightTop() const { return VPointT<T>(mLeftTop + VSizeT<T>(mSize.getWidth(), 0)); } VPointT<T> getLeftBottom() const { return VPointT<T>(mLeftTop + VSizeT<T>(0, mSize.getHeight())); } VSizeT<T> getSize() const { return mSize; } T getLeft() const { return mLeftTop.getX(); } T getTop() const { return mLeftTop.getY(); } T getRight() const { return mLeftTop.getX() + mSize.getWidth(); } T getBottom() const { return mLeftTop.getY() + mSize.getHeight(); } T getWidth() const { return mSize.getWidth(); } T getHeight() const { return mSize.getHeight(); } VPointT<T> getCenter() const { return VPointT<T>(mLeftTop.getX() + (mSize.getWidth() / 2), mLeftTop.getY() + (mSize.getHeight() / 2)); } /** The "edge" functions return lines that are "normalized", preferring to point +x, then +y. */ VLineT<T> getTopSide() const { return VLineT<T>(this->getLeftTop(), this->getRightTop()).normalized(); } VLineT<T> getRightSide() const { return VLineT<T>(this->getRightTop(), this->getRightBottom()).normalized(); } VLineT<T> getBottomSide() const { return VLineT<T>(this->getRightBottom(), this->getLeftBottom()).normalized(); } VLineT<T> getLeftSide() const { return VLineT<T>(this->getLeftBottom(), this->getLeftTop()).normalized(); } VRectT<T> normalized() const { VPointT<T> p(mLeftTop); VSizeT<T> s(mSize); T width = s.getWidth(); if (width < 0) { s.setWidth(-width); p.rX() += width; // width is negative at this point } T height = s.getHeight(); if (height < 0) { s.setHeight(-height); p.rY() += height; // height is negative at this point } return VRectT<T>(p, s); } void moveTo(const VPointT<T>& leftTop) { mLeftTop = leftTop; } void translate(T dx, T dy) { mLeftTop += VPointT<T>(dx, dy); } void translate(const VPointT<T>& offset) { mLeftTop += offset; } void setSize(const VSizeT<T>& size) { mSize = size; } void setWidth(T width) { mSize.setWidth(width); } void setHeight(T height) { mSize.setHeight(height); } void setBounds(T left, T top, T right, T bottom) { mLeftTop.setX(left); mLeftTop.setY(top); mSize.setWidth(right - left); mSize.setHeight(bottom - top); } void setLeft(T left) { mLeftTop.setX(left); } void setTop(T top) { mLeftTop.setY(top); } void setRight(T right) { mSize.setWidth(right - this->getLeft()); } void setBottom(T bottom) { mSize.setHeight(bottom - this->getTop()); } bool contains(const VPointT<T>& p) const { VPointT<T> rightBottom = this->getRightBottom(); return p.getX() >= mLeftTop.getX() && p.getX() < rightBottom.getX() && p.getY() >= mLeftTop.getY() && p.getY() < rightBottom.getY(); } void expandTo(const VPointT<T>& p) { if (! this->contains(p)) { T leftDX = mLeftTop.getX() - p.getX(); if (leftDX > 0) { mLeftTop.rX() -= leftDX; mSize.rWidth() += leftDX; } else { T rightDX = p.getX() - this->getRight(); if (rightDX > 0) { mSize.rWidth() += rightDX; } } T topDY = mLeftTop.getY() - p.getY(); if (topDY > 0) { mLeftTop.rY() -= topDY; mSize.rHeight() += topDY; } else { T bottomDY = p.getY() - this->getBottom(); if (bottomDY > 0) { mSize.rHeight() += bottomDY; } } } } VRectT<T> united(const VRectT<T>& r) const { VRectT<T> result(mLeftTop, mSize); result.expandTo(r.getLeftTop()); result.expandTo(r.getRightBottom()); return result; } VRectT<T> intersected(const VRectT<T>& r) const { T left = V_MAX(this->getLeft(), r.getLeft()); T top = V_MAX(this->getTop(), r.getTop()); T right = V_MIN(this->getRight(), r.getRight()); T bottom = V_MIN(this->getBottom(), r.getBottom()); T width = right - left; T height = bottom - top; if ((width >= 0) && (height >= 0)) { return VRectT<T>(left, top, width, height); } return VRectT<T>(); } /** Returns the corner of the rectangle nearest to the supplied point. @param testPoint a point to test proximity @return the corner nearest to the test point */ VPointT<T> getNearestVertex(const VPointT<T>& testPoint) const { VPolygonT<T> polygon(*this); int nearestVertex = polygon.getNearestVertex(testPoint); return polygon.getPoint(nearestVertex); } /** Returns the side of the rectangle that is nearest to the supplied point. If the test point is in a "dead zone" where the nearest point on a side is a vertex, there is currently no guarantee which of the two candidate sides will be returned. @param testPoint a point to test proximity @return a line defining a side of the rectangle the point is nearest to @see "dead zone" comments at the end of this file */ VLineT<T> getNearestSide(const VPointT<T>& testPoint) const { VPointT<T> unused; return this->getNearestSide(testPoint, unused); } /** Returns the side of the rectangle that is nearest to the supplied point. If the test point is in a "dead zone" where the nearest point on a side is a vertex, there is currently no guarantee which of the two candidate sides will be returned, and the returned nearestPoint will a vertex (shared by the two possible sides). @param testPoint a point to test proximity @param nearestPoint returned value, the point (on the line segment) that is nearest to the test point @return a line defining a side of the rectangle the point is nearest to @see "dead zone" comments at the end of this file */ VLineT<T> getNearestSide(const VPointT<T>& testPoint, VPoint& nearestPoint) const { VPolygonT<T> polygon(*this); int nearestSide = polygon.getNearestSide(testPoint, nearestPoint); return polygon.getSide(nearestSide); } // These use "approximate" equality by testing for a difference >= 0.000001. static bool equal(const VRectT<T>& r1, const VRectT<T>& r2) { return VPointT<T>::equal(r1.mLeftTop, r2.mLeftTop) && VSizeT<T>::equal(r1.mSize, r2.mSize); } static bool notEqual(const VRectT<T>& r1, const VRectT<T>& r2) { return VPointT<T>::notEqual(r1.mLeftTop, r2.mLeftTop) || VSizeT<T>::notEqual(r1.mSize, r2.mSize); } friend bool operator== <>(const VRectT<T>& r1, const VRectT<T>& r2); // exact equality friend bool operator!= <>(const VRectT<T>& r1, const VRectT<T>& r2); // exact inequality #ifdef VAULT_QT_SUPPORT void setQRect(const QRect& r) { mLeftTop = r.topLeft(); mSize = r.size(); } QRect getQRect() const { return QRect(static_cast<int>(mLeftTop.getX()), static_cast<int>(mLeftTop.getY()), static_cast<int>(mSize.getWidth()), static_cast<int>(mSize.getHeight())); } void setQRectF(const QRectF& r) { mLeftTop = static_cast<T>(r.topLeft()); mSize = static_cast<T>(r.size()); } QRectF getQRectF() const { return QRectF(mLeftTop, mSize); } #endif private: VPointT<T> mLeftTop; VSizeT<T> mSize; }; template<typename T> bool operator==(const VRectT<T>& r1, const VRectT<T>& r2) { return r1.mLeftTop == r2.mLeftTop && r1.mSize == r2.mSize; } template<typename T> bool operator!=(const VRectT<T>& r1, const VRectT<T>& r2) { return r1.mLeftTop != r2.mLeftTop || r1.mSize != r2.mSize; } typedef VRectT<VDouble> VRect; ///< A rectangle defined by double-based points. typedef VRectT<int> VIRect; ///< A rectangle defined by integer-based points. template <typename T> class VPolygonT; template <typename T> bool operator== (const VPolygonT<T>& p1, const VPolygonT<T>& p2); template <typename T> bool operator!= (const VPolygonT<T>& p1, const VPolygonT<T>& p2); /** VPolygonT defines a polygon or series of points. VPolygon uses VDouble coordinates; VIPolygon uses int coordinates. */ template <typename T> class VPolygonT { public: VPolygonT() : mPoints() {} VPolygonT(const std::vector<VPointT<T> >& points) : mPoints(points) {} VPolygonT(VBinaryIOStream& stream) : mPoints() { this->readFromStream(stream); } VPolygonT(const VRectT<T>& rect) : mPoints() { this->add(rect.getLeftTop()); this->add(rect.getRightTop()); this->add(rect.getRightBottom()); this->add(rect.getLeftBottom()); } ~VPolygonT() {} #ifdef VAULT_QT_SUPPORT VPolygonT(const QPolygon& p) { for (QPolygon::const_iterator i = p.begin(); i != p.end(); ++i) { this->add(VPointT<T>(static_cast<T>(i->x()), static_cast<T>(i->y()))); } } VPolygonT(const QPolygonF& p) { for (QPolygonF::const_iterator i = p.begin(); i != p.end(); ++i) { this->add(VPointT<T>(i->x(), i->y())); } } #endif void readFromStream(VBinaryIOStream& stream) { this->eraseAll(); int numPoints = static_cast<int>(stream.readS32()); for (int i = 0; i < numPoints; ++i) { VPointT<T> point; point.readFromStream(stream); this->add(point); } } void writeToStream(VBinaryIOStream& stream) const { int numPoints = this->getNumPoints(); stream.writeInt32(numPoints); for (int i = 0; i < numPoints; ++i) { mPoints[i].writeToStream(stream); } } void add(VPointT<T> p) { mPoints.push_back(p); } void insert(int beforeIndex, VPointT<T> p) { mPoints.insert(mPoints.begin() + beforeIndex, p); } int getNumPoints() const { return static_cast<int>(mPoints.size()); } size_t size() const { return mPoints.size(); } const std::vector<VPointT<T> >& getPoints() const { return mPoints; } VPointT<T> getPoint(int index) const { if (index >= this->getNumPoints()) { throw VRangeException(VSTRING_FORMAT("getPoint: Invalid index %d into %d-point polygon.", index, this->getNumPoints())); } return mPoints[index]; } void setPoint(int index, VPointT<T> p) { if (index >= this->getNumPoints()) { throw VRangeException(VSTRING_FORMAT("setPoint: Invalid index %d into %d-point polygon.", index, this->getNumPoints())); } mPoints[index] = p; } VPointT<T>& operator[](int index) { return mPoints[index]; } // Note that operator[] by definition does no range checking. VPointT<T> operator[](int index) const { return mPoints[index]; } // Note that operator[] by definition does no range checking. VRectT<T> getBounds() const { VRectT<T> bounds; // defaults to a zero rect int numPoints = this->getNumPoints(); if (numPoints > 0) { bounds.moveTo(mPoints[0]); for (int i = 1; i < numPoints; ++i) { bounds.expandTo(mPoints[i]); } } return bounds; } void remove(int index) { mPoints.erase(mPoints.begin() + index); } void eraseAll() { mPoints.erase(mPoints.begin(), mPoints.end()); } void translate(VPointT<T> offset) { int numPoints = static_cast<int>(mPoints.size()); for (int i = 0; i < numPoints; ++i) { mPoints[i] += offset; } } VLineT<T> getSide(int index) const { int maxValidIndex = this->getNumPoints() - 1; if (index > maxValidIndex) { throw VRangeException(VSTRING_FORMAT("getSide: Invalid index %d into %d-point polygon.", index, this->getNumPoints())); } int index2 = (index == maxValidIndex) ? 0 : index + 1; return VLineT<T>(mPoints[index], mPoints[index2]); } /** Returns the index of the vertex of the polygon nearest to the supplied point. @param testPoint a point to test proximity @return the vertex nearest to the test point */ int getNearestVertex(const VPointT<T>& testPoint) const { int nearestVertexIndex = -1; VDouble nearestVertexDistance = -1.0; int numPoints = static_cast<int>(mPoints.size()); for (int i = 0; i < numPoints; ++i) { VDouble distanceToVertex = VPoint::getDistance(testPoint, mPoints[i]); if ((nearestVertexIndex < 0) || (distanceToVertex < nearestVertexDistance)) { nearestVertexIndex = i; nearestVertexDistance = distanceToVertex; } } return nearestVertexIndex; } /** Returns the index of the side of the polygon that is nearest to the supplied point. If the test point is in a "dead zone" where the nearest point on a side is a vertex, there is currently no guarantee which of the two candidate sides will be returned. @param testPoint a point to test proximity @return the index of the side of the polygon the point is nearest to @see "dead zone" comments at the end of this file */ int getNearestSide(const VPointT<T>& testPoint) const { VPointT<T> unused; return this->getNearestSide(testPoint, unused); } /** Returns the index of the side of the polygon that is nearest to the supplied point. If the test point is in a "dead zone" where the nearest point on a side is a vertex, there is currently no guarantee which of the two candidate sides will be returned, and the returned nearestPoint will a vertex (shared by the two possible sides). @param testPoint a point to test proximity @param nearestPoint returned value, the point (on the side) that is nearest to the test point @return the index of the side of the polygon the point is nearest to @see "dead zone" comments at the end of this file */ int getNearestSide(const VPointT<T>& testPoint, VPoint& nearestPoint) const { int nearestSideIndex = -1; VDouble nearestSideDistance = -1.0; VPoint nearestSidePoint; int numSides = static_cast<int>(mPoints.size()); for (int i = 0; i < numSides; ++i) { VLine side = this->getSide(i); VPoint p = side.getNearestPoint(testPoint, true); VDouble distanceToSide = VPoint::getDistance(testPoint, p); if ((nearestSideIndex < 0) || (distanceToSide < nearestSideDistance)) { nearestSideIndex = i; nearestSidePoint = p; nearestSideDistance = distanceToSide; } } nearestPoint = nearestSidePoint; return nearestSideIndex; } // These use "approximate" equality by testing for a coordinate difference >= 0.000001. static bool equal(const VPolygonT<T>& p1, const VPolygonT<T>& p2) { if (p1.mPoints.size() != p2.mPoints.size()) return false; int numPoints = static_cast<int>(p1.mPoints.size()); for (int i = 0; i < numPoints; ++i) { if (VPointT<T>::notEqual(p1.mPoints[i], p2.mPoints[i])) { return false; } } return true; } static bool notEqual(const VPolygonT<T>& p1, const VPolygonT<T>& p2) { if (p1.mPoints.size() == p2.mPoints.size()) return false; int numPoints = static_cast<int>(p1.mPoints.size()); for (int i = 0; i < numPoints; ++i) { if (VPointT<T>::equal(p1.mPoints[i], p2.mPoints[i])) { return false; } } return true; } friend bool operator== <>(const VPolygonT<T>& p1, const VPolygonT<T>& p2); // exact equality friend bool operator!= <>(const VPolygonT<T>& p1, const VPolygonT<T>& p2); // exact inequality #ifdef VAULT_QT_SUPPORT void setQPolygon(const QPolygon& p) { this->eraseAll(); for (QPolygon::const_iterator i = p.begin(); i != p.end(); ++i) { this->add(VPointT<T>(static_cast<T>(i->x()), static_cast<T>(i->y()))); } } QPolygon getQPolygon() const { QPolygon p; int numPoints = static_cast<int>(mPoints.size()); for (int i = 0; i < numPoints; ++i) { p.push_back(mPoints[i].getQPoint()); } return p; } void setQPolygonF(const QPolygonF& p) { this->eraseAll(); for (QPolygonF::const_iterator i = p.begin(); i != p.end(); ++i) { this->add(VPointT<T>(i->x(), i->y())); } } QPolygonF getQPolygonF() const { QPolygonF p; int numPoints = static_cast<int>(mPoints.size()); for (int i = 0; i < numPoints; ++i) { p.push_back(mPoints[i].getQPointF()); } return p; } #endif private: std::vector<VPointT<T> > mPoints; }; template<typename T> bool operator==(const VPolygonT<T>& p1, const VPolygonT<T>& p2) { return p1.mPoints == p2.mPoints; } template<typename T> bool operator!=(const VPolygonT<T>& p1, const VPolygonT<T>& p2) { return p1.mPoints != p2.mPoints; } typedef VPolygonT<VDouble> VPolygon; ///< A polygon defined by double-based points. typedef VPolygonT<int> VIPolygon; ///< A polygon defined by integer-based points. /* Comments about "dead zones": There are several functions in VRectT and VPolygonT that locate the "nearest" side of the rectangle or polygon to a particular point in 2D space. There are some cases where the point is in a "dead zone", such that the answer is ambiguous. I have a diagram showing this at the following URL: <http://www.bombaydigital.com/software/vault/images/deadzone.png> The basic problem is that if the nearest point on the edge of the rectangle or polygon is a vertex (a corner), then it is not clear which of the two sides attached at the vertex should be considered "nearest" to the point. The current implementation makes no guarantee about which of the two sides will be chosen in this case. If you ask which vertex is nearest, the answer is unambiguous. It's the "nearest side" question that has an ambigous answer. Fortunately, the use cases I can think of don't care which side is returned because they are really trying to get the nearest point on that side, which is the same for either side. */ #endif /* vgeometry_h */
50.627207
231
0.61275
[ "vector", "3d" ]
bea3525a419a3c5b5c6d1d080a41b9e20f1a819c
1,186
h
C
src/Cpp/701-800/743.NetworkDelayTime.h
Peefy/PeefyLeetCode
92156e4b48ba19e3f02e4286b9f733e9769a1dee
[ "Apache-2.0" ]
2
2018-05-03T07:50:03.000Z
2018-06-17T04:32:13.000Z
src/Cpp/701-800/743.NetworkDelayTime.h
Peefy/PeefyLeetCode
92156e4b48ba19e3f02e4286b9f733e9769a1dee
[ "Apache-2.0" ]
null
null
null
src/Cpp/701-800/743.NetworkDelayTime.h
Peefy/PeefyLeetCode
92156e4b48ba19e3f02e4286b9f733e9769a1dee
[ "Apache-2.0" ]
3
2018-11-09T14:18:11.000Z
2021-11-17T15:23:52.000Z
#ifndef __NETWORK_DELAY_TIME_H #define __NETWORK_DELAY_TIME_H #include <iostream> #include <vector> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <algorithm> #include <queue> #include <math.h> using namespace std; static int pr = []() { std::ios::sync_with_stdio(false); cin.tie(NULL); return 0; }(); class Solution{ public: int networkDelayTime(vector<vector<int>> &times, int N, int K){ vector<int> v(N + 1, INT32_MAX); v[K] = 0; int loop = 1; while (loop--){ for (int i = 0; i < times.size(); i++){ if (v[times[i][0]] != INT32_MAX){ int t = v[times[i][1]]; // relax v[times[i][1]] = min(v[times[i][0]] + times[i][2], v[times[i][1]]); //更新连通时间 if (t != v[times[i][1]]) loop = 1; //如果这一趟没有任何变化,中止循环 } } } int maxnum = 0; for (int j = 1; j <= N; j++){ if (v[j] == INT32_MAX) return -1; maxnum = max(maxnum, v[j]); } return maxnum; } }; #endif
23.254902
96
0.474705
[ "vector" ]
bea841545f1eb2f15d4297357ec3d663999a9698
1,422
h
C
src/BLEService.h
bsiever/DuoBLE
52368a974c2ada95bcc075f97dcd98c6f8a98c62
[ "MIT" ]
null
null
null
src/BLEService.h
bsiever/DuoBLE
52368a974c2ada95bcc075f97dcd98c6f8a98c62
[ "MIT" ]
null
null
null
src/BLEService.h
bsiever/DuoBLE
52368a974c2ada95bcc075f97dcd98c6f8a98c62
[ "MIT" ]
null
null
null
/** * Bluetooth Low Energy Service * * Copyright (c) 2017 Bill Siever. All rights reserved. * Licensed under the MIT license. See LICENSE file in the project root for full license information. * */ #ifndef _BLE_SERVICE_h_ #define _BLE_SERVICE_h_ #include"BLEUuid.h" #include"BLEAttribute.h" #include <cstddef> class BLECharacteristic; class DuoBLE_; // Status for C-style callbacks typedef enum { CONNECTED, // ;;;status = BLE_STATUS_OK CONNECTION_ERROR, // Failed to successfully connect ;;; status = BLE_STATUS_CONNECTION_ERROR DISCONNECTED } BLEServiceCallbackReason; // Simple Callbacks typedef void (*BLEServiceCallback)(uint16_t conn_handle, BLEServiceCallbackReason reason); // OOP Callbacks: Listener Object class BLEServiceListener { protected: virtual void connected(uint16_t conn_handle) {} virtual void disconnected(uint16_t conn_handle) {} friend class DuoBLE_; }; class BLEService { public: BLEService(const char *uuidString); void addCharacteristic(BLECharacteristic& characteristics); const char *uuid(); void setListener(BLEServiceListener& object); void setListener(BLEServiceListener* object); void setCallback(BLEServiceCallback callback); friend class DuoBLE_; private: UUID m_uuid; BLEServiceListener *m_listenerObject; BLEServiceCallback m_callbackFunction; BLECharacteristic *m_characteristicChain; BLEService *m_nextService; }; #endif
24.947368
101
0.775668
[ "object" ]
beb50a7689b044e8f9b810957369eb55fa0ec39c
787
h
C
ConfigFile.h
aaronmcniven/Common-Classes
ed084131ef39a427e99c3cbaa83b13e34edbdea7
[ "Unlicense" ]
null
null
null
ConfigFile.h
aaronmcniven/Common-Classes
ed084131ef39a427e99c3cbaa83b13e34edbdea7
[ "Unlicense" ]
null
null
null
ConfigFile.h
aaronmcniven/Common-Classes
ed084131ef39a427e99c3cbaa83b13e34edbdea7
[ "Unlicense" ]
null
null
null
#pragma once #include <Windows.h> #include <iostream> #include <string> #include <vector> #include <fstream> #include <algorithm> #include <map> class ConfigFile { private: bool m_loaded; std::string m_location; std::map<std::string, std::string> m_values; public: ConfigFile(); ConfigFile(const std::string &filename); bool load(const std::string &filename); bool loaded(); const std::string &getLocation(); bool valueExists(const std::string &name); std::pair<std::string, bool> getValueString(const std::string &name); std::pair<bool, bool> getValueBool(const std::string &name); std::pair<int, bool> getValueInt(const std::string &name); std::pair<float, bool> getValueFloat(const std::string &name); ~ConfigFile(); };
25.387097
75
0.678526
[ "vector" ]
beba0e9a3bbc31bee3ffc9be359af4c64b9bc99d
2,063
h
C
Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/SharedViewBookmarkComponent.h
BreakerOfThings/o3de
f4c59f868c726470ec910623facd836047d059c3
[ "Apache-2.0", "MIT" ]
1
2022-03-28T08:06:58.000Z
2022-03-28T08:06:58.000Z
Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/SharedViewBookmarkComponent.h
BreakerOfThings/o3de
f4c59f868c726470ec910623facd836047d059c3
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/SharedViewBookmarkComponent.h
BreakerOfThings/o3de
f4c59f868c726470ec910623facd836047d059c3
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #pragma once #include <AzToolsFramework/ToolsComponents/EditorComponentBase.h> #include <Viewport/ViewBookmarkLoaderInterface.h> namespace AzToolsFramework { //! @class EditorViewBookmarks. //! @brief struct that stores a vector of View bookmarks. struct EditorViewBookmarks final { AZ_CLASS_ALLOCATOR(EditorViewBookmarks, AZ::SystemAllocator, 0); AZ_TYPE_INFO(EditorViewBookmarks, "{EA0B8FF9-F706-4115-8226-E3F54F1EE8A1}"); static void Reflect(AZ::ReflectContext* context); AZStd::string GetBookmarkLabel(int index) const; AZStd::vector<ViewBookmark> m_viewBookmarks; }; //! @class SharedViewBookmarkComponent. //! @brief component that stores a vector of View bookmarks stored in the prefab. //! so they can be shared in version control easily. class SharedViewBookmarkComponent : public AzToolsFramework::Components::EditorComponentBase { public: static constexpr const char* const ViewBookmarkComponentTypeId = "{6959832F-9382-4C7D-83AC-380DA9F138DE}"; AZ_EDITOR_COMPONENT(SharedViewBookmarkComponent, ViewBookmarkComponentTypeId, EditorComponentBase); static void Reflect(AZ::ReflectContext* context); AZStd::optional<ViewBookmark> GetBookmarkAtIndex(int index) const; void AddBookmark(ViewBookmark viewBookmark); bool RemoveBookmarkAtIndex(int index); bool ModifyBookmarkAtIndex(int index, const ViewBookmark& newBookmark); protected: static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& services); static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& services); private: //! A user editable list of View Bookmarks EditorViewBookmarks m_viewBookmark; }; } // namespace AzToolsFramework
36.839286
114
0.739699
[ "vector", "3d" ]
bebb21f10571774ad6791a6e254163efa3d34352
9,968
h
C
bench/node.h
telosprotocol/xkad
f3591d5544bf26ba486cb4a7f141d9500422206e
[ "MIT" ]
13
2019-09-16T13:34:35.000Z
2020-01-13T08:06:17.000Z
bench/node.h
telosprotocol/xkad
f3591d5544bf26ba486cb4a7f141d9500422206e
[ "MIT" ]
null
null
null
bench/node.h
telosprotocol/xkad
f3591d5544bf26ba486cb4a7f141d9500422206e
[ "MIT" ]
null
null
null
// Copyright (c) 2017-2019 Telos Foundation & contributors // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #pragma once #include "xpbase/base/top_utils.h" #include "xpbase/base/line_parser.h" #include "xpbase/base/kad_key/platform_kadmlia_key.h" #include "xtransport/udp_transport/udp_transport.h" #include "xtransport/src/message_manager.h" #include "util.h" #define private public #define protected public #include "xkad/routing_table/routing_table.h" #include "xkad/routing_table/local_node_info.h" #include "xkad/routing_table/kad_message_handler.h" #include "xtransport/message_manager/multi_message_handler.h" #include "xkad/src/nat_manager.h" #undef private #undef protected #include "xpbase/base/top_timer.h" #include "node.pb.h" namespace top { namespace kadmlia { namespace test { const int kTestMsgBase = kMessageTypeMax + 200; const int kTestReportNodes = kTestMsgBase + 0; // send to super node const int kTestConnRequest = kTestMsgBase + 10; // relay to des node const int kTestConnResponse = kTestMsgBase + 11; // relay to src node const int kTestConnReply = kTestMsgBase + 12; // send to src node const int kTestConn2Request = kTestMsgBase + 20; // relay to des node const int kTestConn2Response = kTestMsgBase + 21; // relay to src node const int kTestGetrtRequest = kTestMsgBase + 30; // send to des node const int kTestGetrtResponse = kTestMsgBase + 31; // send to src node const int kTestGetrt2Request = kTestMsgBase + 40; // send to des node const int kTestGetrt2Response = kTestMsgBase + 41; // send to src node class MyRoutingTable : public RoutingTable { public: MyRoutingTable( base::TimerManager* timer_manager, std::shared_ptr<transport::Transport> udp_transport, uint32_t kadmlia_key_len, std::shared_ptr<LocalNodeInfo> local_node_ptr); bool Init(const std::string& name_prefix, const std::string& supernode_ip, uint16_t supernode_port); virtual void HandleBootstrapJoinRequest( transport::protobuf::RoutingMessage& message, base::xpacket_t& packet) override; // ---------------- save/load all_nodes void OnCommandSave(const BenchCommand::Arguments& args); void OnCommandLoad(const BenchCommand::Arguments& args); // ---------------- prn void HandleReportNodes( transport::protobuf::RoutingMessage& message, base::xpacket_t& packet); struct NodeReport { int count{0}; std::string ep; }; struct StructPrn { time_t time_now; // struct Node { // std::string ip_port; // std::string // }; std::map<std::string, NodeReport> details; }; void PrintReportNodes(const StructPrn& struct_prn, int node_count); // void PrintNodes(int node_count); void GetReportNodes(StructPrn& struct_prn); void SendReportNodes(); void OnCommandPrn(const BenchCommand::Arguments& args); void OnCommandPrt(const BenchCommand::Arguments& args); void OnCommandPrtSimple(const BenchCommand::Arguments& args); // ---------------- conn void OnCommandConn(const BenchCommand::Arguments& args); void HandleConnRequest( transport::protobuf::RoutingMessage& message, base::xpacket_t& packet); void HandleConnResponse( transport::protobuf::RoutingMessage& message, base::xpacket_t& packet); void HandleConnReply( transport::protobuf::RoutingMessage& message, base::xpacket_t& packet); void SendConnReply(const std::string& reply, const std::string& ip, uint16_t port); void RelayConnRequest(const std::string& node_id); void RelayConnResponse(const std::string& data, const uint64_t des_service_type, const std::string& des_node_id); // ---------------- connvia void SendConnVia(NodeInfoPtr via_node, NodeInfoPtr des_node); void OnCommandConnVia(const BenchCommand::Arguments& args); // ---------------- conn2/query void HandleConn2Request( transport::protobuf::RoutingMessage& message, base::xpacket_t& packet); void HandleConn2Response( transport::protobuf::RoutingMessage& message, base::xpacket_t& packet); void SendConn2Response(const std::string& data, const std::string& des_node_id, const std::string& ip, uint16_t port); void RelayConn2Response(const std::string& data, const uint64_t des_service_type, const std::string& des_node_id); void SendConn2Request(bool send_or_relay); void ClearQuery(); void OnCommandConn2(const BenchCommand::Arguments& args); // conn2 when directly sendto first node void OnCommandConn3(const BenchCommand::Arguments& args); // conn + query void OnCommandQuery(const BenchCommand::Arguments& args); struct StructQuery { std::vector<std::string> hops; // std::vector<std::string> not_found_nodes; std::vector<NodeInfoPtr> not_found_nodes; }; void GetQuery(StructQuery& struct_query); void DumpQuery(const StructQuery& struct_query); // ---------------- getrt void OnCommandGetrt(const BenchCommand::Arguments& args); void SendGetrtRequest(const std::string& ip, uint16_t port); void HandleGetrtRequest( transport::protobuf::RoutingMessage& message, base::xpacket_t& packet); void HandleGetrtResponse( transport::protobuf::RoutingMessage& message, base::xpacket_t& packet); // ---------------- getrt2/rtsize void ClearRtdiff(); void OnCommandGetrt2(const BenchCommand::Arguments& args); void OnCommandRtsize(const BenchCommand::Arguments& args); void SendGetrt2Request(const std::string& ip, uint16_t port); void HandleGetrt2Request( transport::protobuf::RoutingMessage& message, base::xpacket_t& packet); void HandleGetrt2Response( transport::protobuf::RoutingMessage& message, base::xpacket_t& packet); std::string CompareDiffLines(const std::string& str1, const std::string& str2); void GetGetrt2(int& diff_count); int GetLines(const std::string& str); // ---------------- autotest void OnCommandAutoTest(const BenchCommand::Arguments& args); bool AutoTestAllBoot(int node_count); bool AutoTestAllFull(int rt_size); bool AutoTestAllConn(); bool AutoTestAllGetrt2(); void SleepWait(int seconds); private: std::string GetDumpNodes(std::vector<NodeInfoPtr> nodes, int max_detail); // columns: id/dis/pub/local/nat(3.3KB) std::string GetDumpNodesSimple(std::vector<NodeInfoPtr> nodes, int max_detail); // columns: id/dis(1.16KB) std::string GetDumpSelf(); long long GetSteadyTimepoint(); int ParseArg(const std::string& arg, int default_value); NodeInfoPtr GetNode(const std::string& node_id); private: std::string supernode_ip_; uint16_t supernode_port_{0}; base::TimerManager* timer_manager_{base::TimerManager::Instance()}; std::mutex all_nodes_mutex_; std::vector<NodeInfoPtr> all_nodes_; std::map<std::string, NodeInfoPtr> all_nodes_map_; // ---------------- prn std::mutex report_mutex_; std::shared_ptr<base::TimerRepeated> report_timer_; std::map<std::string, NodeReport> map_report_nodes_; // ---------------- conn2/query std::mutex test_conn_mutex_; struct NodeSearch { bool found{false}; NodeInfoPtr node; }; struct NodeHops { long long total{0}; long long max{-1}; long long min{9999}; std::vector<NodeInfoPtr> nodes; }; std::map<std::string, NodeSearch> search_map_; // mark node found std::map<int, NodeHops> hops_map_; std::map<std::string, NodeInfoPtr> last_not_found_map_; // ---------------- getrt2 std::mutex rt_map_mutex_; std::map<std::string, std::string> rt_map_; // about 700KB for 600 nodes int rt_diff_count_{0}; std::map<int, int> rt_size_map_; // ---------------- autotest long time_all_boot_{-1}; // prn and total is the all nodes, as the first_time long time_all_full_{-1}; long time_all_conn_{-1}; long time_all_getrt2_{-1}; }; class MyMessageHandler : public KadMessageHandler { public: void Init(); }; class MyKadkey : public base::PlatformKadmliaKey { public: MyKadkey(const std::string& str_for_hash, bool hash_tag) : PlatformKadmliaKey(str_for_hash, hash_tag) { node_id_ = str_for_hash; } virtual std::string Get() override { return node_id_; } private: std::string node_id_; }; class MyNodeMgr { public: MyNodeMgr() {} ~MyNodeMgr(); bool Init(const base::Config& config, const std::string& name); bool JoinRt(); uint16_t RealLocalPort(); void HandleMessage( transport::protobuf::RoutingMessage& message, base::xpacket_t& packet); private: bool LoadConfig(const base::Config& config); bool NatDetect(); private: std::shared_ptr<base::TimerManager> timer_manager_impl_; MyMessageHandler message_handler_; transport::MessageManager message_manager_; std::shared_ptr<transport::MultiThreadHandler> message_threads_; transport::UdpTransportPtr udp_transport_; std::shared_ptr<LocalNodeInfo> local_node_info_; std::shared_ptr<MyRoutingTable> routing_table_; bool first_node_{false}; std::string local_ip_; uint16_t local_port_{0}; std::string supernode_ip_; uint16_t supernode_port_{0}; uint16_t real_local_port_{0}; // system assigned transport::UdpTransportPtr nat_transport_; NatManagerIntf* nat_manager_{nullptr}; }; } // namespace test } // namespace kadmlia } // namespace top
37.055762
122
0.67506
[ "vector" ]
bebc49b0ef99ed6bca172cac96534fed1cdc61ef
31,122
c
C
src/core/ztp_settings.c
microsoft/wifi-ztp
273d9b5a00613e793c2e0a6967e8dd93e96a9d92
[ "MIT" ]
6
2021-07-06T14:14:43.000Z
2022-01-26T18:39:41.000Z
src/core/ztp_settings.c
QPC-database/wifi-ztp
fa66199a56645305a1a773291e7d1d01f042cb73
[ "MIT" ]
9
2021-06-14T21:24:16.000Z
2021-08-09T17:17:30.000Z
src/core/ztp_settings.c
QPC-database/wifi-ztp
fa66199a56645305a1a773291e7d1d01f042cb73
[ "MIT" ]
2
2021-06-18T14:54:52.000Z
2021-07-06T14:14:44.000Z
#include <errno.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <json-c/json_object.h> #include <json-c/json_util.h> #include <userspace/linux/compiler.h> #include <userspace/linux/kernel.h> #include "file_utils.h" #include "json_parse.h" #include "ztp_log.h" #include "ztp_settings.h" /** * @brief Settings changed event handler. */ struct ztp_settings_changed_event_handler { struct list_head list; ztp_settings_changed_fn callback; void *context; }; /** * @brief Signals that the ztp settings have changed. * * @param settings The settings object that has changed. * @param changed_item The setting item that changed. */ void ztp_settings_signal_changed(struct ztp_settings *settings, enum ztp_settings_changed_item changed_item) { struct ztp_settings_changed_event changed_event = { .changed_item = changed_item, }; const struct ztp_settings_changed_event_handler *changed_handler; const struct ztp_settings_changed_event_handler *changed_handler_tmp; list_for_each_entry_safe (changed_handler, changed_handler_tmp, &settings->change_handlers, list) { changed_handler->callback(settings, &changed_event, changed_handler->context); } } /** * @brief Finds a changed handler, given a callback and context argument. * * @param settings The ztp settings to search for the specified handler. * @param callback The callback function associated with the handler. * @param context The context argument assoicated with the callback. * @return struct ztp_settings_changed_event_handler* If such a handler has * been registered, otherwise NULL. */ struct ztp_settings_changed_event_handler * find_settings_changed_handler(struct ztp_settings *settings, ztp_settings_changed_fn callback, void *context) { struct ztp_settings_changed_event_handler *change_handler; list_for_each_entry (change_handler, &settings->change_handlers, list) { if (change_handler->callback == callback && change_handler->context == context) { return change_handler; } } return NULL; } /** * @brief Registers a settings changed handler. The specified callback function * will be invoked with the context argument and a changed event structure each * time the settings change. * * @param settings The ztp settings to monitor change events for. * @param callback The callback function to invoke oin change. * @param context An additional context-specific argument to be passed to the callback function. * @return int 0 if the handler was successfully registered, non-zero otherwise. */ int ztp_settings_register_change_handler(struct ztp_settings *settings, ztp_settings_changed_fn callback, void *context) { if (find_settings_changed_handler(settings, callback, context)) return 0; struct ztp_settings_changed_event_handler *changed_handler = malloc(sizeof *changed_handler); if (!changed_handler) { zlog_error("failed to allocate memory for ztp settings changed handler"); return -ENOMEM; } changed_handler->callback = callback; changed_handler->context = context; list_add(&changed_handler->list, &settings->change_handlers); return 0; } /** * @brief Unregisters a settings changed handler. * * @param settings The ztp settings to remove the handler from. * @param callback The previously registered callback. * @param context The context previously registered with the callback. */ void ztp_settings_unregister_change_handler(struct ztp_settings *settings, ztp_settings_changed_fn callback, void *context) { struct ztp_settings_changed_event_handler *change_handler = find_settings_changed_handler(settings, callback, context); if (!change_handler) return; list_del(&change_handler->list); free(change_handler); } /** * @brief Uninitializes a role settings entry. * * @param settings The settings object to uninitialize. */ static void ztp_device_role_settings_uninitialize(struct ztp_device_role_settings *settings) { if (settings->activation_unit) { free(settings->activation_unit); settings->activation_unit = NULL; } if (settings->interface) { free(settings->interface); settings->interface = NULL; } if (settings->path) { free(settings->path); settings->path = NULL; } switch (settings->role) { case DPP_DEVICE_ROLE_ENROLLEE: { ztp_enrollee_settings_uninitialize(&settings->enrollee); break; } case DPP_DEVICE_ROLE_CONFIGURATOR: ztp_configurator_settings_uninitialize(&settings->configurator); break; default: break; } } /** * @brief Create an initialize a new interface settings entry. * * @return struct ztp_interface_settings_entry* */ struct ztp_device_role_settings_entry * ztp_device_role_settings_entry_initialize(void) { struct ztp_device_role_settings_entry *entry = calloc(1, sizeof *entry); if (!entry) { zlog_warning("failed to allocate memory for role settings entry"); return NULL; } INIT_LIST_HEAD(&entry->list); return entry; } /** * @brief Finds a device role settings entry, given an interface name. * * @param settings The ztp settings structure to search. * @param interface The interface name to lookup settings for. * @return struct ztp_device_role_settings_entry* */ static struct ztp_device_role_settings_entry * ztp_settings_find_device_role_settings_entry(const struct ztp_settings *settings, const char *interface) { struct ztp_device_role_settings_entry *entry; list_for_each_entry (entry, &settings->role_settings, list) { if (strcmp(entry->settings.interface, interface) == 0) return entry; } return NULL; } /** * @brief Finds role settings, given an interface name. * * @param settings The ztp settings structure to search. * @param interface The name of the interface to lookup settings for. * @return struct ztp_device_role_settings* */ struct ztp_device_role_settings * ztp_settings_find_device_role_settings(const struct ztp_settings *settings, const char *interface) { struct ztp_device_role_settings_entry *entry = ztp_settings_find_device_role_settings_entry(settings, interface); if (entry) return &entry->settings; return NULL; } /** * @brief Uninitialize an interface settings entry. * * @param entry The interface settings entry to uninitialize. */ static void ztp_device_role_settings_entry_uninitialize(struct ztp_device_role_settings_entry *entry) { ztp_device_role_settings_uninitialize(&entry->settings); list_del(&entry->list); } /** * @brief Adds a new interface settings entry to ztpd. * * @param ztpd The global ztpd instance. * @param entry The entry to add. */ static void ztp_settings_add_device_role_settings(struct ztp_settings *settings, struct ztp_device_role_settings_entry *entry) { struct ztp_device_role_settings_entry *existing = ztp_settings_find_device_role_settings_entry(settings, entry->settings.interface); if (existing) { ztp_device_role_settings_entry_uninitialize(existing); free(existing); } list_add(&entry->list, &settings->role_settings); } /** * @brief Function to parse each "ui.activation.gpio" configuration option * object entry. * * @param parent The parent object. * @param name The name of the json entry. * @param jobj The json object for the entry. * @param context A pointer to a ztpd instance. Will be of type (struct ztpd *). */ static void json_parse_ui_activation_gpio_entry(struct json_object *parent, const char *name, struct json_object *jobj, void *context) { __unused(parent); __unused(name); struct ztp_settings *settings = (struct ztp_settings *)context; if (strcmp(name, "chip") == 0) { if (!json_validate_object_type(name, jobj, json_type_string)) return; const char *chip = json_object_get_string(jobj); settings->ui_activation_gpio_chip = strdup(chip); } else if (strcmp(name, "line") == 0) { json_type type = json_object_get_type(jobj); switch (type) { case json_type_string: { const char *line_name = json_object_get_string(jobj); settings->ui_activation_gpio_line_name = strdup(line_name); break; } case json_type_int: { int32_t line = json_object_get_int(jobj); settings->ui_activation_gpio_line = line; break; } default: return; } } else if (strcmp(name, "debounceDelay") == 0) { int32_t debounce_delay = json_object_get_int(jobj); settings->ui_activation_gpio_delay = debounce_delay; } } /** * @brief Functon to parse "ui.activation.gpio" configuration option. * * @param parent The parent object. * @param name The name of the json entry. Must be "ui.activation.gpio". * @param jobj The json object value for "ui.activation.gpio". * @param ztpd The global ztpd instance. */ static void json_parse_ui_activation_gpio(struct json_object *parent, const char *name, struct json_object *jobj, void *context) { __unused(parent); __unused(name); json_for_each_object(jobj, json_parse_ui_activation_gpio_entry, context); } /** * @brief Functon to parse "ui.activation.unit" configuration option. * * @param parent The parent object. * @param name The name of the json entry. Must be "ui.activation.unit". * @param jobj The json object value for "ui.activation.unit". * @param ztpd The global ztpd instance. */ static void json_parse_ui_activation_unit(struct json_object *parent, const char *name, struct json_object *jobj, void *context) { __unused(parent); __unused(name); struct ztp_settings *settings = (struct ztp_settings *)context; const char *ui_activation_unit = json_object_get_string(jobj); settings->ui_activation_unit = strdup(ui_activation_unit); } /** * @brief Function to parse "ui.activation" configuration option array entry. * * @param parent The parent object. * @param array The containing array object. * @param name The name of the parent object ("ui.activation"). * @param jobj The array element value. * @param index The array element index. * @param type The type of the array element (json_type_string). * @param context The ztpd global instance. */ static void json_parse_ui_activation_array_entry(struct json_object *parent, struct json_object *array, const char *name, struct json_object *jobj, uint32_t index, json_type type, void *context) { __unused(parent); __unused(array); __unused(name); __unused(index); __unused(type); struct ztp_settings *settings = (struct ztp_settings *)context; const char *value = json_object_get_string(jobj); if (strcmp(value, "command") == 0) { settings->ui_activation_command = true; } else if (strcmp(value, "gpio") == 0) { settings->ui_activation_gpio = true; } } /** * @brief Json object key names for "device.roles" array and child objects. */ #define JSON_PROPERTY_NAME_DEVICE_ROLES "device.roles" #define JSON_PROPERTY_NAME_DEVICE_ROLE_ROLE "role" #define JSON_PROPERTY_NAME_DEVICE_ROLE_INTERFACE "interface" #define JSON_PROPERTY_NAME_DEVICE_ROLE_SETTINGS_PATH "settingsPath" #define JSON_PROPERTY_NAME_DEVICE_ROLE_ACTIVATION_UNIT "activationUnit" /** * @brief Get the context for the string properties of the bootstrap info object. * * @param context The parent context. Must be of type struct dpp_bootstrap_info. * @param name The name of the child property to retrieve the context for. * @return void* The context for the child property with key 'name'. */ static void * get_device_role_string_context(void *context, const char *name) { struct ztp_device_role_settings *settings = (struct ztp_device_role_settings *)context; if (strcmp(name, JSON_PROPERTY_NAME_DEVICE_ROLE_INTERFACE) == 0) { return &settings->interface; } else if (strcmp(name, JSON_PROPERTY_NAME_DEVICE_ROLE_SETTINGS_PATH) == 0) { return &settings->path; } else if (strcmp(name, JSON_PROPERTY_NAME_DEVICE_ROLE_ACTIVATION_UNIT) == 0) { return &settings->activation_unit; } else { return NULL; } } /** * @brief Parses individual "role" property of a device role entry. * * @param parent The parent object. * @param name The name of the json entry. Must be "role". * @param jobj The json object value. * @param ztpd The ztp_device_role_settings instance to populate. */ static void json_parse_device_role_rolestr(struct json_object *parent, const char *name, struct json_object *jobj, void *context) { __unused(parent); __unused(name); struct ztp_device_role_settings *settings = (struct ztp_device_role_settings *)context; const char *device_role = json_object_get_string(jobj); settings->role = dpp_device_role_parse(device_role); switch (settings->role) { case DPP_DEVICE_ROLE_ENROLLEE: ztp_enrollee_settings_initialize(&settings->enrollee); break; case DPP_DEVICE_ROLE_CONFIGURATOR: ztp_configurator_settings_initialize(&settings->configurator); break; default: break; } } /** * @brief Property map for enrollee bootstrap info configuration. */ static struct json_property_parser device_role_entry_properties[] = { { .name = JSON_PROPERTY_NAME_DEVICE_ROLE_ROLE, .type = json_type_string, .value = { json_parse_device_role_rolestr, }, }, { .name = JSON_PROPERTY_NAME_DEVICE_ROLE_INTERFACE, .type = json_type_string, .value = { json_parse_string_generic, }, .get_context = get_device_role_string_context, }, { .name = JSON_PROPERTY_NAME_DEVICE_ROLE_SETTINGS_PATH, .type = json_type_string, .value = { json_parse_string_generic, }, .get_context = get_device_role_string_context, }, { .name = JSON_PROPERTY_NAME_DEVICE_ROLE_ACTIVATION_UNIT, .type = json_type_string, .value = { json_parse_string_generic, }, .get_context = get_device_role_string_context, }, }; /** * @brief Function to parse an "device.roles" json object. * * If a valid device role object was found, it is added to the passed in * ztp_settings structure. If settings already existed for the interface name * in question, they will be replaced by the newly parsed settings. * * @param parent The parent object. * @param array The containing array object. * @param name The name of the json entry. * @param jobj The json object value associated with the device role settings. * @param index The array index of the object. * @param type The type of the object. * @param context The struct ztp_settings object to populate. */ static void json_parse_device_roles(struct json_object *parent, struct json_object *array, const char *name, struct json_object *jobj, uint32_t index, json_type type, void *context) { __unused(parent); __unused(array); __unused(name); __unused(index); __unused(type); struct ztp_settings *settings = (struct ztp_settings *)context; struct ztp_device_role_settings_entry *entry = ztp_device_role_settings_entry_initialize(); if (!entry) return; json_parse_object_s(jobj, device_role_entry_properties, &entry->settings); if (!entry->settings.interface) { zlog_warning("role settings entry missing interface name; ignoring"); ztp_device_role_settings_entry_uninitialize(entry); free(entry); return; } ztp_settings_add_device_role_settings(settings, entry); } /** * @brief Function to parse "device.roles.exclusive" configuration option. * * @param parent The parent object. * @param name The name of the json entry. Must be "device.roles.exclusive". * @param jobj The json object value for "device.roles.exclusive". * @param ztpd The global ztpd instance. */ static void json_parse_device_roles_exclusive(struct json_object *parent, const char *name, struct json_object *jobj, void *context) { __unused(parent); __unused(name); struct ztp_settings *settings = (struct ztp_settings *)context; bool exclusive = json_object_get_boolean(jobj); settings->dpp_roles_exclusive = exclusive; } /** * @brief Parses the "device.roles.activated" object (not the entries). * * @param parent The parent object. * @param name The name, which will always be NULL. * @param jobj The array object. * @param context The array context. */ static void json_parse_device_roles_activated(struct json_object *parent, const char *name, struct json_object *jobj, void *context) { __unused(parent); __unused(name); struct ztp_settings *settings = (struct ztp_settings *)context; if (settings->dpp_roles_activated_json == NULL) { settings->dpp_roles_activated_json = jobj; json_object_get(jobj); } } /** * @brief Parses individual "device.roles.activated" entries. * * @param parent The parent object. * @param array The containing array object. * @param name The name of the json object. * @param jobj The json object value. * @param index The index of the json value within the array. * @param context A pointer to the ztpd global instance. This must be of type 'struct ztpd'. */ static void json_parse_device_roles_activated_entry(struct json_object *parent, struct json_object *array, const char *name, struct json_object *jobj, uint32_t index, json_type type, void *context) { __unused(parent); __unused(array); __unused(name); __unused(index); __unused(type); struct ztp_settings *settings = (struct ztp_settings *)context; const char *rolestr = json_object_get_string(jobj); enum dpp_device_role role = dpp_device_role_parse(rolestr); if (role != DPP_DEVICE_ROLE_UNKNOWN) settings->dpp_roles_activated[role] = true; } /** * @brief Array of supported configuration file options. */ static struct json_property_parser ztp_config_properties[] = { { .name = "ui.activation", .type = json_type_array, .array = { json_parse_ui_activation_array_entry, json_type_string, }, }, { .name = "ui.activation.gpio", .type = json_type_object, .value = { json_parse_ui_activation_gpio, }, }, { .name = "ui.activation.unit", .type = json_type_string, .value = { json_parse_ui_activation_unit, }, }, { .name = "device.roles", .type = json_type_array, .array = { json_parse_device_roles, json_type_object, }, }, { .name = "device.roles.exclusive", .type = json_type_boolean, .value = { json_parse_device_roles_exclusive, }, }, { .name = "device.roles.activated", .type = json_type_array, .value = { json_parse_device_roles_activated, }, .array = { json_parse_device_roles_activated_entry, json_type_string, }, }, }; /** * @brief Creates and initializes a new ztp settings intance. * * @param config_file The full path of the configuration file. * @return struct ztp_settings* A pointer to the settings object. */ static struct ztp_settings * ztp_settings_create(const char *config_file) { size_t config_file_length = strlen(config_file) + 1; struct ztp_settings *settings = malloc((sizeof *settings) * config_file_length); if (!settings) { zlog_error("failed to allocate memory for ztp settings"); return NULL; } explicit_bzero(settings, sizeof *settings); INIT_LIST_HEAD(&settings->role_settings); INIT_LIST_HEAD(&settings->change_handlers); memcpy(settings->config_file, config_file, config_file_length); return settings; } /** * @brief Parses a ztp settings file. * * @param config_file The full path of the configuration file to parse. * @param psettings An output pointer to receive a parsed settings object. The * caller is responsible for calling ztp_settings_destroy on this object. * @return int */ int ztp_settings_parse(const char *config_file, struct ztp_settings **psettings) { struct ztp_settings *settings = ztp_settings_create(config_file); if (!settings) { zlog_error("failed to allocate memory for ztp settings"); return -ENOMEM; } int ret = json_parse_file_s(config_file, ztp_config_properties, settings, &settings->json); if (ret < 0) { zlog_error("failed to parse ztp settings from %s (%d)", config_file, ret); goto fail; } struct ztp_device_role_settings_entry *entry; list_for_each_entry (entry, &settings->role_settings, list) { switch (entry->settings.role) { case DPP_DEVICE_ROLE_ENROLLEE: ret = ztp_enrollee_config_parse(entry->settings.path, &entry->settings.enrollee); break; case DPP_DEVICE_ROLE_CONFIGURATOR: ret = ztp_configurator_config_parse(entry->settings.path, &entry->settings.configurator); break; default: ret = -EINVAL; break; } if (ret < 0) { zlog_error("failed to parse '%s' settings from '%s' (%d)", dpp_device_role_str(entry->settings.role), entry->settings.path, ret); goto fail; } } *psettings = settings; ret = 0; out: return ret; fail: if (settings) ztp_settings_destroy(&settings); goto out; } /** * @brief Persists settings to file descriptor. * * @param fd The file descriptor to write the settings to. * @param settings The settings to write to file. * @return int 0 if the settings were successfully written to file, non-zero otherwise. */ static int ztp_settings_persist_fd(int fd, const struct ztp_settings *settings) { static const int JSON_C_SERIALIZE_FLAGS = (0 | JSON_C_TO_STRING_NOSLASHESCAPE // don't escape paths | JSON_C_TO_STRING_PRETTY // make it look good | JSON_C_TO_STRING_SPACED // minimize whitespace | JSON_C_TO_STRING_PRETTY_TAB // use a full tab character ); struct json_object *jsettings = settings->json; if (!jsettings) { zlog_error("serialized json settings not found"); return -EINVAL; } int ret = json_object_to_fd(fd, jsettings, JSON_C_SERIALIZE_FLAGS); if (ret < 0) { zlog_error("failed to write settings to file descriptor (%d)", ret); return ret; } return 0; } /** * @brief Macros to help defined the temporary path string for writing the * settings file. */ #define TMP_TEMPLATE_SUFFIX_STRING ".XXXXXX" /** * @brief Persists ztp settings to file. * * @param filename The filename to write the settings to. * @param settings The settings to write to file. * @return int 0 if the settings were successfully written to file, non-zero otherwise. */ int ztp_settings_persist(const char *filename, const struct ztp_settings *settings) { int ret; int fd = -1; char *filename_target = NULL; ret = get_link_target(filename, &filename_target); if (ret < 0) { zlog_error("failed to resolve ztp settings file '%s' link target (%d)", filename, ret); return ret; } if (filename_target) filename = filename_target; size_t filename_length = strlen(filename); char *pathtmp = malloc(filename_length + ARRAY_SIZE(TMP_TEMPLATE_SUFFIX_STRING)); if (!pathtmp) { zlog_error("failed to allocate memory for temp configurator settings file path"); ret = -ENOMEM; goto out; } memcpy(pathtmp, filename, filename_length); memcpy(pathtmp + filename_length, TMP_TEMPLATE_SUFFIX_STRING, ARRAY_SIZE(TMP_TEMPLATE_SUFFIX_STRING)); fd = mkstemp(pathtmp); if (fd < 0) { ret = -errno; zlog_error("failed to create temporary file for ztp settings (%d)", ret); goto out; } ret = ztp_settings_persist_fd(fd, settings); if (ret < 0) { zlog_error("failed to write ztp settings to temporary file (%d)", ret); goto out; } fdatasync(fd); ret = rename(pathtmp, filename); if (ret < 0) { ret = -errno; zlog_error("failed to move temporary settings file to target file (%d)", ret); goto out; } zlog_debug("ztp settings persisted to '%s'", filename); out: if (fd != -1) close(fd); if (filename_target) free(filename_target); if (pathtmp) free(pathtmp); return ret; } /** * @brief Uninitialize ztpd daemon options. * * @param settings The options to uninitialize. */ void ztp_settings_uninitialize(struct ztp_settings *settings) { if (settings->ui_activation_gpio_chip) { free(settings->ui_activation_gpio_chip); settings->ui_activation_gpio_chip = NULL; } if (settings->ui_activation_gpio_line_name) { free(settings->ui_activation_gpio_line_name); settings->ui_activation_gpio_line_name = NULL; } if (settings->ui_activation_unit) { free(settings->ui_activation_unit); settings->ui_activation_unit = NULL; } if (settings->dpp_roles_activated_json) { json_object_put(settings->dpp_roles_activated_json); settings->dpp_roles_activated_json = NULL; } if (settings->json) { json_object_put(settings->json); settings->json = NULL; } struct ztp_device_role_settings_entry *entry; struct ztp_device_role_settings_entry *entrytmp; list_for_each_entry_safe (entry, entrytmp, &settings->role_settings, list) { ztp_device_role_settings_entry_uninitialize(entry); free(entry); } struct ztp_settings_changed_event_handler *change_handler; struct ztp_settings_changed_event_handler *change_handler_tmp; list_for_each_entry_safe (change_handler, change_handler_tmp, &settings->change_handlers, list) { ztp_settings_unregister_change_handler(settings, change_handler->callback, change_handler->context); } } /** * @brief Uninitializes and destroys a ztp settings instance. * * @param settings A pointer to the settings instance to destroy. This function * will set the memory this references to NULL, so the pointer must not be * accessed following this call. */ void ztp_settings_destroy(struct ztp_settings **settings) { if (!settings || !*settings) return; ztp_settings_uninitialize(*settings); free(*settings); *settings = NULL; } /** * @brief Synchronizes the in-memory activated roles with those stored in the * json object. This is a one-way function which will replace anything that * currently exists in the json object. * * @param settings The ztp settings. * @return int 0 if the json object associated with activated roles was * succcessfully updated to reflect the in-memory activated roles. */ static int ztp_settings_role_disposition_synchronize_json(struct ztp_settings *settings) { int ret; struct json_object *roles_activated = settings->dpp_roles_activated_json; size_t roles_activated_num = json_object_array_length(roles_activated); if (roles_activated_num > 0) { ret = json_object_array_del_idx(roles_activated, 0, roles_activated_num); if (ret < 0) { zlog_error("failed to clear activated roles json array (%d)", ret); return ret; } } for (size_t i = 0, index = 0; i < ARRAY_SIZE(settings->dpp_roles_activated); i++) { if (!settings->dpp_roles_activated[i]) continue; const char *role = dpp_device_role_str((enum dpp_device_role)i); struct json_object *value = json_object_new_string(role); if (!value) { zlog_error("failed to allocate memory for device role string"); return -ENOMEM; } ret = json_object_array_put_idx(roles_activated, index, value); if (ret < 0) { zlog_error("failed to add activated role to activated role json array (%d)", ret); json_object_put(value); return ret; } zlog_debug("device role '%s' added to activated json array", role); index++; } return 0; } /** * @brief Set the disposition of a role. * * @param settings The settings instance to update. * @param role The role to set the disposition for. * @param activate The role disposition. * @return true If the role disposition was changed * @return false If the role disposition was not changed. */ static bool set_role_disposition(struct ztp_settings *settings, enum dpp_device_role role, bool activate) { if (settings->dpp_roles_activated[role] == activate) return false; const char *rolestr = dpp_device_role_str(role); settings->dpp_roles_activated[role] = activate; zlog_debug("role '%s' disposition set to '%s'", rolestr, activate ? "activated" : "deactivated"); return true; } /** * @brief Sets the device role setting to activated or deactivated. Note that * this does not necessarily affect the functionality of any running daemon; * this only updates the setting. * * If exclusive mode is set, and the new role disposition is to activate, then * the existing activated role (if one exists) will be changed to disabled. * * @param settings The settings instance to update. * @param role The role to set the disposition for. * @param activate The role disposition. * @return int The number of roles that changed disposition successfully * updated, otherwise a negative value indicating the cause for the failure. */ int ztp_settings_set_device_role_disposition(struct ztp_settings *settings, enum dpp_device_role role, bool activate) { int num_role_changes = 0; if (set_role_disposition(settings, role, activate)) num_role_changes++; if (settings->dpp_roles_exclusive) { enum dpp_device_role role_peer = dpp_device_role_peer(role); if (dpp_device_role_is_valid(role_peer)) { if (set_role_disposition(settings, role_peer, !activate)) num_role_changes++; } } if (num_role_changes == 0) return 0; int ret = ztp_settings_role_disposition_synchronize_json(settings); if (ret < 0) { zlog_error("failed to synchronize role dispoition change with json settings (%d)", ret); return ret; } ret = ztp_settings_persist(settings->config_file, settings); if (ret < 0) { zlog_error("failed to persist updated ztp settings to file (%d)", ret); return ret; } ztp_settings_signal_changed(settings, ZTP_SETTING_CHANGED_ITEM_DEVICE_ROLES); return num_role_changes; }
31.692464
185
0.694525
[ "object" ]
db4662a72aba2fc72beb9ccb87da6e4fda06a2ea
3,133
h
C
include/LogPort.h
homer6/logport
46c291892e51decf2c6251f47dc90751237454ed
[ "MIT" ]
4
2019-05-01T16:45:49.000Z
2022-01-29T06:48:32.000Z
include/LogPort.h
homer6/logport
46c291892e51decf2c6251f47dc90751237454ed
[ "MIT" ]
1
2019-04-30T18:02:37.000Z
2019-04-30T18:02:37.000Z
include/LogPort.h
homer6/logport
46c291892e51decf2c6251f47dc90751237454ed
[ "MIT" ]
3
2019-04-30T17:48:46.000Z
2021-04-29T01:40:50.000Z
#ifndef LOGPORT_LOGPORT_H #define LOGPORT_LOGPORT_H #include <string> using std::string; #include <vector> using std::vector; #include <map> using std::map; #include "Platform.h" #include "Observer.h" namespace logport{ class Watch; class Database; class Inspector; class LogPort{ public: LogPort(); ~LogPort(); void closeDatabase(); void closeObserver(); void install(); void uninstall(); void destroy(); void restoreToFactoryDefault(); void enable(); void disable(); void start(); void stop(); void restart(); void reload(); void reloadIfRunning(); void status(); bool isRunning(); void printHelp(); void printVersion(); void printHelpWatch(); void printHelpSet(); void printHelpUnset(); void printHelpInspect(); void printHelpAdopt(); void printUnsupportedPlatform(); int runFromCommandLine( int argc, char **argv ); void registerSignalHandlers(); void addWatch( const Watch& watch ); void listWatches(); void watchNow( const Watch& watch ) const; void adopt( const Watch& watch ); bool addSetting( const string& key, const string& value ); string getSetting( const string& key ); bool removeSetting( const string& key ); void listSettings(); void loadEnvironmentVariables(); string getEnvironmentVariable( const string& variable_name ) const; void setEnvironmentVariable( const string& variable_name, const string& variable_value ); Database& getDatabase(); Inspector& getInspector(); Observer& getObserver(); string getDefaultTopic(); string getDefaultBrokers(); string getDefaultProductCode(); string getDefaultHostname(); protected: void installInitScript(); void installLogrotate(); void startWatches(); //main loop (blocks) //this will wait for 60 seconds; but, it'll check to see if there's an event every second void waitUnlessEvent( int seconds ); pid_t startProcess( const string& executable_path, const string& process_description, const std::vector<string>& arguments, const std::map<string,string>& environment_variables, int *child_stdin_pipe, int *child_stdout_pipe, int *child_stderr_pipe ); private: Database *db; Inspector* inspector; Observer* observer; public: bool run; bool reload_required; bool watches_paused; string command; vector<string> command_line_arguments; string current_version; Platform current_platform; vector<string> additional_arguments; map<string,string> environment_variables; string pid_filename; bool verbose_mode; }; } #endif //LOGPORT_LOGPORT_H
21.909091
257
0.598468
[ "vector" ]
db4882dd2f9d17036a8e42ea19d8b24c9fd9d051
136
c
C
Comandos/catalogcommands/libc/exemplos/strerror.c
ribafs/linux
2a839202d956903cb0dbc14a9b13035455c694d9
[ "MIT" ]
1
2021-06-12T07:14:38.000Z
2021-06-12T07:14:38.000Z
Comandos/catalogcommands/libc/exemplos/strerror.c
ribafs/linux
2a839202d956903cb0dbc14a9b13035455c694d9
[ "MIT" ]
null
null
null
Comandos/catalogcommands/libc/exemplos/strerror.c
ribafs/linux
2a839202d956903cb0dbc14a9b13035455c694d9
[ "MIT" ]
null
null
null
#include<stdio.h> #include<string.h> int main() { int i; for (i = 0; i <= 133; i++) printf("%3d %s\n", i, strerror(i)); }
15.111111
43
0.5
[ "3d" ]
db57c9741bd0cce05578dcbb2d73e7492dee3601
9,455
h
C
src/cfdapi_get_extkeyinfo_json.h
cryptogarageinc/cg-cfd-js
05af38708215e144ea167207fd920719c3112c7e
[ "MIT" ]
null
null
null
src/cfdapi_get_extkeyinfo_json.h
cryptogarageinc/cg-cfd-js
05af38708215e144ea167207fd920719c3112c7e
[ "MIT" ]
null
null
null
src/cfdapi_get_extkeyinfo_json.h
cryptogarageinc/cg-cfd-js
05af38708215e144ea167207fd920719c3112c7e
[ "MIT" ]
null
null
null
// Copyright 2019 CryptoGarage /** * @file cfdapi_get_extkeyinfo_json.h * * @brief JSONマッピングファイル (自動生成) */ #ifndef CFD_JS_SRC_CFDAPI_GET_EXTKEYINFO_JSON_H_ #define CFD_JS_SRC_CFDAPI_GET_EXTKEYINFO_JSON_H_ #include <set> #include <string> #include <vector> #include "cfdcore/cfdcore_json_mapping_base.h" #include "cfdjs/cfdjs_struct.h" namespace cfd { namespace js { namespace api { namespace json { using cfd::core::JsonClassBase; using cfd::core::JsonObjectVector; using cfd::core::JsonValueVector; using cfd::core::JsonVector; // clang-format off // @formatter:off // ------------------------------------------------------------------------ // GetExtkeyInfoRequest // ------------------------------------------------------------------------ /** * @brief JSON-API(GetExtkeyInfoRequest)クラス */ class GetExtkeyInfoRequest : public cfd::core::JsonClassBase<GetExtkeyInfoRequest> { public: GetExtkeyInfoRequest() { CollectFieldName(); } virtual ~GetExtkeyInfoRequest() { // do nothing } /** * @brief フィールド名を収集する. */ static void CollectFieldName(); /** * @brief extkey 取得処理 * @return extkey */ std::string GetExtkey() const { return extkey_; } /** * @brief extkey 設定処理 * @param[in] extkey 設定値 */ void SetExtkey( // line separate const std::string& extkey) { // NOLINT this->extkey_ = extkey; } /** * @brief extkey データ型の取得処理 * @return extkeyのデータ型 */ static std::string GetExtkeyFieldType() { return "std::string"; } /** * @brief extkey フィールドのJSON文字列取得処理 * @param[in,out] obj クラスオブジェクト * @return JSON文字列 */ static std::string GetExtkeyString( // line separate const GetExtkeyInfoRequest& obj) { // NOLINT return cfd::core::ConvertToString(obj.extkey_); } /** * @brief extkey フィールドへのJSON情報設定処理 * @param[in,out] obj クラスオブジェクト * @param[in] json_value JSON情報 */ static void SetExtkeyString( // line separate GetExtkeyInfoRequest& obj, // NOLINT const UniValue& json_value) { cfd::core::ConvertFromUniValue( // line separate obj.extkey_, json_value); } /** * @brief 無視対象アイテムを設定する。 * @param[in] key 無視対象アイテムのキー名称 */ void SetIgnoreItem(const std::string& key) { ignore_items.insert(key); } /** * @brief 構造体からクラスへ変換する. * @param[in] data 構造体データ */ void ConvertFromStruct( const GetExtkeyInfoRequestStruct& data); /** * @brief クラスから構造体へ変換する. * @return 構造体データ */ GetExtkeyInfoRequestStruct ConvertToStruct() const; protected: /** * @brief Mapテーブルの型名定義 */ using GetExtkeyInfoRequestMapTable = cfd::core::JsonTableMap<GetExtkeyInfoRequest>; /** * @brief JSONマッピングオブジェクトを取得する。 * @return JSONマッピングオブジェクト * @see cfd::core::JsonClassBase::GetJsonMapper() */ virtual const GetExtkeyInfoRequestMapTable& GetJsonMapper() const { // NOLINT return json_mapper; } /** * @brief JSONマッピングのアイテム一覧を取得する。 * 対象の変数名を、定義順序に従い一覧取得する。 * @return JSONマッピングのアイテム一覧 * @see cfd::core::JsonClassBase::GetJsonItemList() */ virtual const std::vector<std::string>& GetJsonItemList() const { return item_list; } /** * @brief JSONマッピング時に無視するアイテム一覧を取得する。 * Serialize時に対象の変数を無視する。 * @return JSONマッピング時に無視するアイテム一覧 * @see cfd::core::JsonClassBase::GetIgnoreItem() */ virtual const std::set<std::string>& GetIgnoreItem() const { return ignore_items; } private: /** * @brief JsonFunctionMapテーブル */ static GetExtkeyInfoRequestMapTable json_mapper; /** * @brief フィールド名リスト */ static std::vector<std::string> item_list; /** * @brief 無視リスト */ std::set<std::string> ignore_items; /** * @brief JsonAPI(extkey) のvalue */ std::string extkey_ = ""; }; // ------------------------------------------------------------------------ // GetExtkeyInfoResponse // ------------------------------------------------------------------------ /** * @brief JSON-API(GetExtkeyInfoResponse)クラス */ class GetExtkeyInfoResponse : public cfd::core::JsonClassBase<GetExtkeyInfoResponse> { public: GetExtkeyInfoResponse() { CollectFieldName(); } virtual ~GetExtkeyInfoResponse() { // do nothing } /** * @brief フィールド名を収集する. */ static void CollectFieldName(); /** * @brief version 取得処理 * @return version */ uint32_t GetVersion() const { return version_; } /** * @brief version 設定処理 * @param[in] version 設定値 */ void SetVersion( // line separate const uint32_t& version) { // NOLINT this->version_ = version; } /** * @brief version データ型の取得処理 * @return versionのデータ型 */ static std::string GetVersionFieldType() { return "uint32_t"; } /** * @brief version フィールドのJSON文字列取得処理 * @param[in,out] obj クラスオブジェクト * @return JSON文字列 */ static std::string GetVersionString( // line separate const GetExtkeyInfoResponse& obj) { // NOLINT return cfd::core::ConvertToString(obj.version_); } /** * @brief version フィールドへのJSON情報設定処理 * @param[in,out] obj クラスオブジェクト * @param[in] json_value JSON情報 */ static void SetVersionString( // line separate GetExtkeyInfoResponse& obj, // NOLINT const UniValue& json_value) { cfd::core::ConvertFromUniValue( // line separate obj.version_, json_value); } /** * @brief depth 取得処理 * @return depth */ uint8_t GetDepth() const { return depth_; } /** * @brief depth 設定処理 * @param[in] depth 設定値 */ void SetDepth( // line separate const uint8_t& depth) { // NOLINT this->depth_ = depth; } /** * @brief depth データ型の取得処理 * @return depthのデータ型 */ static std::string GetDepthFieldType() { return "uint8_t"; } /** * @brief depth フィールドのJSON文字列取得処理 * @param[in,out] obj クラスオブジェクト * @return JSON文字列 */ static std::string GetDepthString( // line separate const GetExtkeyInfoResponse& obj) { // NOLINT return cfd::core::ConvertToString(obj.depth_); } /** * @brief depth フィールドへのJSON情報設定処理 * @param[in,out] obj クラスオブジェクト * @param[in] json_value JSON情報 */ static void SetDepthString( // line separate GetExtkeyInfoResponse& obj, // NOLINT const UniValue& json_value) { cfd::core::ConvertFromUniValue( // line separate obj.depth_, json_value); } /** * @brief childNumber 取得処理 * @return childNumber */ uint32_t GetChildNumber() const { return child_number_; } /** * @brief childNumber 設定処理 * @param[in] child_number 設定値 */ void SetChildNumber( // line separate const uint32_t& child_number) { // NOLINT this->child_number_ = child_number; } /** * @brief childNumber データ型の取得処理 * @return childNumberのデータ型 */ static std::string GetChildNumberFieldType() { return "uint32_t"; } /** * @brief childNumber フィールドのJSON文字列取得処理 * @param[in,out] obj クラスオブジェクト * @return JSON文字列 */ static std::string GetChildNumberString( // line separate const GetExtkeyInfoResponse& obj) { // NOLINT return cfd::core::ConvertToString(obj.child_number_); } /** * @brief childNumber フィールドへのJSON情報設定処理 * @param[in,out] obj クラスオブジェクト * @param[in] json_value JSON情報 */ static void SetChildNumberString( // line separate GetExtkeyInfoResponse& obj, // NOLINT const UniValue& json_value) { cfd::core::ConvertFromUniValue( // line separate obj.child_number_, json_value); } /** * @brief 無視対象アイテムを設定する。 * @param[in] key 無視対象アイテムのキー名称 */ void SetIgnoreItem(const std::string& key) { ignore_items.insert(key); } /** * @brief 構造体からクラスへ変換する. * @param[in] data 構造体データ */ void ConvertFromStruct( const GetExtkeyInfoResponseStruct& data); /** * @brief クラスから構造体へ変換する. * @return 構造体データ */ GetExtkeyInfoResponseStruct ConvertToStruct() const; protected: /** * @brief Mapテーブルの型名定義 */ using GetExtkeyInfoResponseMapTable = cfd::core::JsonTableMap<GetExtkeyInfoResponse>; /** * @brief JSONマッピングオブジェクトを取得する。 * @return JSONマッピングオブジェクト * @see cfd::core::JsonClassBase::GetJsonMapper() */ virtual const GetExtkeyInfoResponseMapTable& GetJsonMapper() const { // NOLINT return json_mapper; } /** * @brief JSONマッピングのアイテム一覧を取得する。 * 対象の変数名を、定義順序に従い一覧取得する。 * @return JSONマッピングのアイテム一覧 * @see cfd::core::JsonClassBase::GetJsonItemList() */ virtual const std::vector<std::string>& GetJsonItemList() const { return item_list; } /** * @brief JSONマッピング時に無視するアイテム一覧を取得する。 * Serialize時に対象の変数を無視する。 * @return JSONマッピング時に無視するアイテム一覧 * @see cfd::core::JsonClassBase::GetIgnoreItem() */ virtual const std::set<std::string>& GetIgnoreItem() const { return ignore_items; } private: /** * @brief JsonFunctionMapテーブル */ static GetExtkeyInfoResponseMapTable json_mapper; /** * @brief フィールド名リスト */ static std::vector<std::string> item_list; /** * @brief 無視リスト */ std::set<std::string> ignore_items; /** * @brief JsonAPI(version) のvalue */ uint32_t version_ = 0; /** * @brief JsonAPI(depth) のvalue */ uint8_t depth_ = 0; /** * @brief JsonAPI(childNumber) のvalue */ uint32_t child_number_ = 0; }; // @formatter:on // clang-format on } // namespace json } // namespace api } // namespace js } // namespace cfd #endif // CFD_JS_SRC_CFDAPI_GET_EXTKEYINFO_JSON_H_
23.117359
81
0.632047
[ "vector" ]
db57ec1c7b711748761df6a7eed01794f96e2f89
4,023
c
C
ConfProfile/jni/strongswan/src/charon-tkm/src/tkm/tkm_private_key.c
Infoss/conf-profile-4-android
619bd63095bb0f5a67616436d5510d24a233a339
[ "MIT" ]
2
2017-10-16T07:51:18.000Z
2019-06-16T12:07:52.000Z
strongswan/strongswan-5.3.2/src/charon-tkm/src/tkm/tkm_private_key.c
SECURED-FP7/secured-mobility-ned
36fdbfee58a31d42f7047f7a7eaa1b2b70246151
[ "Apache-2.0" ]
5
2016-01-25T18:04:42.000Z
2016-02-25T08:54:56.000Z
strongswan/strongswan-5.3.2/src/charon-tkm/src/tkm/tkm_private_key.c
SECURED-FP7/secured-mobility-ned
36fdbfee58a31d42f7047f7a7eaa1b2b70246151
[ "Apache-2.0" ]
2
2016-01-25T17:14:17.000Z
2016-02-13T20:14:09.000Z
/* * Copyright (C) 2012-2013 Reto Buerki * Copyright (C) 2012-2013 Adrian-Ken Rueegsegger * Hochschule fuer Technik Rapperswil * * 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. See <http://www.fsf.org/copyleft/gpl.txt>. * * 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. */ #include <utils/debug.h> #include <tkm/constants.h> #include <tkm/client.h> #include "tkm_utils.h" #include "tkm_types.h" #include "tkm_private_key.h" typedef struct private_tkm_private_key_t private_tkm_private_key_t; /** * Private data of a tkm_private_key_t object. */ struct private_tkm_private_key_t { /** * Public interface for this signer. */ tkm_private_key_t public; /** * Key ID. */ identification_t *id; /** * Key type. */ key_type_t key_type; /** * Reference count. */ refcount_t ref; }; METHOD(private_key_t, get_type, key_type_t, private_tkm_private_key_t *this) { return this->key_type; } METHOD(private_key_t, sign, bool, private_tkm_private_key_t *this, signature_scheme_t scheme, chunk_t data, chunk_t *signature) { signature_type sig; init_message_type msg; sign_info_t sign; isa_id_type isa_id; if (data.ptr == NULL) { DBG1(DBG_LIB, "unable to get signature information"); return FALSE; } sign = *(sign_info_t *)(data.ptr); chunk_to_sequence(&sign.init_message, &msg, sizeof(init_message_type)); isa_id = sign.isa_id; chunk_free(&sign.init_message); if (ike_isa_sign(isa_id, 1, msg, &sig) != TKM_OK) { DBG1(DBG_LIB, "signature operation failed"); return FALSE; } sequence_to_chunk(sig.data, sig.size, signature); return TRUE; } METHOD(private_key_t, decrypt, bool, private_tkm_private_key_t *this, encryption_scheme_t scheme, chunk_t crypto, chunk_t *plain) { return FALSE; } METHOD(private_key_t, get_keysize, int, private_tkm_private_key_t *this) { return 0; } METHOD(private_key_t, get_public_key, public_key_t*, private_tkm_private_key_t *this) { return NULL; } METHOD(private_key_t, get_encoding, bool, private_tkm_private_key_t *this, cred_encoding_type_t type, chunk_t *encoding) { return FALSE; } METHOD(private_key_t, get_fingerprint, bool, private_tkm_private_key_t *this, cred_encoding_type_t type, chunk_t *fp) { *fp = this->id->get_encoding(this->id); return TRUE; } METHOD(private_key_t, get_ref, private_key_t*, private_tkm_private_key_t *this) { ref_get(&this->ref); return &this->public.key; } METHOD(private_key_t, destroy, void, private_tkm_private_key_t *this) { if (ref_put(&this->ref)) { this->id->destroy(this->id); free(this); } } /** * See header. */ tkm_private_key_t *tkm_private_key_init(identification_t * const id) { private_tkm_private_key_t *this; certificate_t *cert; public_key_t *pubkey; INIT(this, .public = { .key = { .get_type = _get_type, .sign = _sign, .decrypt = _decrypt, .get_keysize = _get_keysize, .get_public_key = _get_public_key, .equals = private_key_equals, .belongs_to = private_key_belongs_to, .get_fingerprint = _get_fingerprint, .has_fingerprint = private_key_has_fingerprint, .get_encoding = _get_encoding, .get_ref = _get_ref, .destroy = _destroy, }, }, .ref = 1, .id = id->clone(id), ); /* get key type from associated public key */ cert = lib->credmgr->get_cert(lib->credmgr, CERT_ANY, KEY_ANY, id, FALSE); if (!cert) { destroy(this); return NULL; } pubkey = cert->get_public_key(cert); if (!pubkey) { cert->destroy(cert); destroy(this); return NULL; } this->key_type = pubkey->get_type(pubkey); pubkey->destroy(pubkey); cert->destroy(cert); return &this->public; }
21.062827
77
0.719115
[ "object" ]